This commit is contained in:
DrSmoothl committed 2026-10-12 15:43:34 +08:00
1 parent effeb66554
commit 7c0519f75f
977 files changed
+198426 -158324

No files matched your search

+90 -62
View File
@@ -18,7 +18,8 @@ const C2C_CONTROL_TYPES = new Set<number>([141, 166, 167]);
// phantom (#102) is one of them.
const C2C_CONTROL_CMDS = new Set<number>([1, 73, 75, 129, 131, 133, 135, 192]);
export type MessageSurvival = 'drop-control' | 'drop-receipt' | 'drop-blank' | 'keep-undecoded' | 'keep';
export type MessageSurvival =
'drop-control' | 'drop-receipt' | 'drop-blank' | 'keep-undecoded' | 'keep';
/**
* Whether a push is a C2C control/system signal that QQ NT never renders as a
@@ -29,7 +30,7 @@ export type MessageSurvival = 'drop-control' | 'drop-receipt' | 'drop-blank' | '
* the post-decode filter still returns `drop-control` for the same decision.
*/
export function isC2cControlPush(head: Pick<MsgPushHead, 'msgType' | 'c2cCmd'>): boolean {
return C2C_CONTROL_TYPES.has(head.msgType) && C2C_CONTROL_CMDS.has(head.c2cCmd);
return C2C_CONTROL_TYPES.has(head.msgType) && C2C_CONTROL_CMDS.has(head.c2cCmd);
}
/**
@@ -37,10 +38,10 @@ export function isC2cControlPush(head: Pick<MsgPushHead, 'msgType' | 'c2cCmd'>):
* decoded to zero elements AND its body carried nothing decodable.
*/
export function isBlankMessage(
elements: readonly unknown[],
body: PushMsgBody | undefined,
elements: readonly unknown[],
body: PushMsgBody | undefined,
): boolean {
return elements.length === 0 && !hasDecodableContent(body);
return elements.length === 0 && !hasDecodableContent(body);
}
/**
@@ -50,76 +51,103 @@ export function isBlankMessage(
* elements is keep-undecoded, not blank.
*/
export function classifyMessageSurvival(
head: Pick<MsgPushHead, 'msgType' | 'c2cCmd'>,
elements: readonly unknown[],
body: PushMsgBody | undefined,
head: Pick<MsgPushHead, 'msgType' | 'c2cCmd'>,
elements: readonly unknown[],
body: PushMsgBody | undefined,
): MessageSurvival {
if (isC2cControlPush(head)) return 'drop-control';
if (isOfflineFileReceipt(body)) return 'drop-receipt';
if (elements.length !== 0) return 'keep';
if (hasDecodableContent(body)) return 'keep-undecoded';
return 'drop-blank';
if (isC2cControlPush(head)) {
return 'drop-control';
}
if (isOfflineFileReceipt(body)) {
return 'drop-receipt';
}
if (elements.length !== 0) {
return 'keep';
}
if (hasDecodableContent(body)) {
return 'keep-undecoded';
}
return 'drop-blank';
}
/** Summarise a body that decoded to zero elements despite carrying content. */
export function describeUndecodedBody(body: PushMsgBody | undefined): string {
const elems = (body?.richText?.elems ?? []) as Elem[];
const parts = elems.map((e) => {
if (e.commonElem) {
const ce = e.commonElem;
const pb = ce.pbElem && ce.pbElem.length > 0 ? ` pbElem=${hexPreview(ce.pbElem, 256)}` : '';
return `commonElem(svc=${ce.serviceType ?? 0},biz=${ce.businessType ?? 0})${pb}`;
const elems = (body?.richText?.elems ?? []) as Elem[];
const parts = elems.map((e) => {
if (e.commonElem) {
const ce = e.commonElem;
const pb =
ce.pbElem && ce.pbElem.length > 0 ? ` pbElem=${hexPreview(ce.pbElem, 256)}` : '';
return `commonElem(svc=${ce.serviceType ?? 0},biz=${ce.businessType ?? 0})${pb}`;
}
const keys = Object.keys(e).filter((k) => (e as Record<string, unknown>)[k] != null);
return keys.join('+') || '(empty)';
});
const extras: string[] = [];
if (body?.richText?.ptt) {
extras.push('ptt');
}
const keys = Object.keys(e).filter((k) => (e as Record<string, unknown>)[k] != null);
return keys.join('+') || '(empty)';
});
const extras: string[] = [];
if (body?.richText?.ptt) extras.push('ptt');
if (body?.richText?.notOnlineFile) extras.push('notOnlineFile');
if (body?.msgContent && body.msgContent.length > 0) {
extras.push(`msgContent=${hexPreview(body.msgContent, 256)}`);
}
return `elems=[${parts.join('; ')}]${extras.length ? ` ${extras.join(' ')}` : ''}`;
if (body?.richText?.notOnlineFile) {
extras.push('notOnlineFile');
}
if (body?.msgContent && body.msgContent.length > 0) {
extras.push(`msgContent=${hexPreview(body.msgContent, 256)}`);
}
return `elems=[${parts.join('; ')}]${extras.length ? ` ${extras.join(' ')}` : ''}`;
}
/** Keep when the message should appear as a bubble. Warns on keep-undecoded. */
export function keepDecodedMessage(
head: Pick<MsgPushHead, 'msgType' | 'c2cCmd' | 'sequence' | 'subType'>,
elements: readonly unknown[],
body: PushMsgBody | undefined,
kind: string,
fromUin: number,
head: Pick<MsgPushHead, 'msgType' | 'c2cCmd' | 'sequence' | 'subType'>,
elements: readonly unknown[],
body: PushMsgBody | undefined,
kind: string,
fromUin: number,
): boolean {
const survival = classifyMessageSurvival(head, elements, body);
if (survival === 'drop-control' || survival === 'drop-receipt' || survival === 'drop-blank') return false;
if (survival === 'keep-undecoded') {
warnUndecodedMessage({
kind,
sequence: head.sequence,
fromUin,
msgType: head.msgType,
subType: head.subType,
body,
});
}
return true;
const survival = classifyMessageSurvival(head, elements, body);
if (survival === 'drop-control' || survival === 'drop-receipt' || survival === 'drop-blank') {
return false;
}
if (survival === 'keep-undecoded') {
warnUndecodedMessage({
kind,
sequence: head.sequence,
fromUin,
msgType: head.msgType,
subType: head.subType,
body,
});
}
return true;
}
export function warnUndecodedMessage(info: {
kind: string;
sequence: number;
fromUin: number;
msgType: number;
subType: number;
body: PushMsgBody | undefined;
kind: string;
sequence: number;
fromUin: number;
msgType: number;
subType: number;
body: PushMsgBody | undefined;
}): void {
log.warn(
'message had content but decoded to 0 elements — missing decoder? (kind=%s seq=%d from=%d msgType=%d/%d): %s',
info.kind,
info.sequence,
info.fromUin,
info.msgType,
info.subType,
describeUndecodedBody(info.body),
);
log.warn(
'message had content but decoded to 0 elements — missing decoder? (kind=%s seq=%d from=%d msgType=%d/%d): %s',
info.kind,
info.sequence,
info.fromUin,
info.msgType,
info.subType,
describeUndecodedBody(info.body),
);
}
+89 -71
View File
@@ -1,60 +1,75 @@
import { protobuf_decode } from '@snowluma/proton';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { IdentityService } from '../identity-service';
import type { ContentHead, MessageBody, PushMsg, PushMsgBody as ProtoMessage, ResponseHead } from '@snowluma/proto-defs/message';
import type {
ContentHead,
MessageBody,
PushMsg,
PushMsgBody as ProtoMessage,
ResponseHead,
} from '@snowluma/proto-defs/message';
export type PushMsgBody = MessageBody;
export type PushMsgResponseHead = ResponseHead;
export type PushMsgContentHead = ContentHead;
export interface MsgPushHead {
readonly msgType: number;
readonly subType: number;
/** C2C command (`contentHead` field 3). Discriminates control pushes — see
* `isC2cControlPush` in ./blank-filter. */
readonly c2cCmd: number;
/** Sender-local C2C client sequence (field 5), or the group sequence. */
readonly sequence: number;
/** Bidirectional C2C sequence (field 11); zero on groups/legacy packets. */
readonly ntMsgSeq: number;
readonly timestamp: number;
readonly msgId: number;
readonly msgType: number;
readonly subType: number;
/** C2C command (`contentHead` field 3). Discriminates control pushes — see
* `isC2cControlPush` in ./blank-filter. */
readonly c2cCmd: number;
/** Sender-local C2C client sequence (field 5), or the group sequence. */
readonly sequence: number;
/** Bidirectional C2C sequence (field 11); zero on groups/legacy packets. */
readonly ntMsgSeq: number;
readonly timestamp: number;
readonly msgId: number;
}
export interface MsgPushContext {
readonly head: MsgPushHead;
readonly fromUin: number;
readonly fromUid: string;
readonly selfUin: number;
readonly content: Uint8Array;
readonly body: PushMsgBody | undefined;
readonly responseHead: PushMsgResponseHead | undefined;
readonly identity: IdentityService;
/**
* Historical messages reuse the live decoder but must not replay
* live-only identity observations.
*/
readonly isHistorical: boolean;
readonly head: MsgPushHead;
readonly fromUin: number;
readonly fromUid: string;
readonly selfUin: number;
readonly content: Uint8Array;
readonly body: PushMsgBody | undefined;
readonly responseHead: PushMsgResponseHead | undefined;
readonly identity: IdentityService;
/**
* Historical messages reuse the live decoder but must not replay
* live-only identity observations.
*/
readonly isHistorical: boolean;
}
export function buildContext(pkt: PacketInfo, identity: IdentityService): MsgPushContext | null {
if (pkt.body.length === 0) return null;
if (pkt.body.length === 0) {
return null;
}
// `pkt.body` is already a `Uint8Array` (see `PacketInfo` in
// @snowluma/common/protocol-types). The legacy `Buffer.from(uint8)`
// wrap was a no-op copy — Buffer is a Uint8Array subclass and
// proton's decoder accepts the parent type directly. Dropping the
// wrap saves one allocation per incoming push packet.
const push = protobuf_decode<PushMsg>(pkt.body);
if (!push?.message) return null;
// `pkt.body` is already a `Uint8Array` (see `PacketInfo` in
// @snowluma/common/protocol-types). The legacy `Buffer.from(uint8)`
// wrap was a no-op copy — Buffer is a Uint8Array subclass and
// proton's decoder accepts the parent type directly. Dropping the
// wrap saves one allocation per incoming push packet.
const push = protobuf_decode<PushMsg>(pkt.body);
let selfUin = 0;
if (pkt.uin) {
const n = parseInt(pkt.uin, 10);
if (!isNaN(n)) selfUin = n;
}
if (!push?.message) {
return null;
}
return buildContextFromMessage(push.message, selfUin, identity, false);
let selfUin = 0;
if (pkt.uin) {
const n = parseInt(pkt.uin, 10);
if (!isNaN(n)) {
selfUin = n;
}
}
return buildContextFromMessage(push.message, selfUin, identity, false);
}
/**
@@ -65,41 +80,44 @@ export function buildContext(pkt: PacketInfo, identity: IdentityService): MsgPus
* regular msg-push decoders parse fetched history unchanged.
*/
export function buildContextFromMessage(
msg: ProtoMessage,
selfUin: number,
identity: IdentityService,
isHistorical = true,
msg: ProtoMessage,
selfUin: number,
identity: IdentityService,
isHistorical = true,
): MsgPushContext | null {
if (!msg.contentHead) return null;
if (!msg.contentHead) {
return null;
}
const head: MsgPushHead = {
msgType: msg.contentHead.msgType ?? 0,
subType: msg.contentHead.subType ?? 0,
c2cCmd: msg.contentHead.c2cCmd ?? 0,
sequence: msg.contentHead.sequence ?? 0,
ntMsgSeq: msg.contentHead.ntMsgSeq ?? 0,
timestamp: msg.contentHead.timestamp ?? 0,
msgId: msg.contentHead.msgId ?? 0,
};
const head: MsgPushHead = {
msgType: msg.contentHead.msgType ?? 0,
subType: msg.contentHead.subType ?? 0,
c2cCmd: msg.contentHead.c2cCmd ?? 0,
sequence: msg.contentHead.sequence ?? 0,
ntMsgSeq: msg.contentHead.ntMsgSeq ?? 0,
timestamp: msg.contentHead.timestamp ?? 0,
msgId: msg.contentHead.msgId ?? 0,
};
let fromUin = 0;
let fromUid = '';
if (msg.responseHead) {
fromUin = msg.responseHead.fromUin ?? 0;
fromUid = msg.responseHead.fromUid ?? '';
}
let fromUin = 0;
let fromUid = '';
const content = msg.body?.msgContent ?? new Uint8Array(0);
if (msg.responseHead) {
fromUin = msg.responseHead.fromUin ?? 0;
fromUid = msg.responseHead.fromUid ?? '';
}
return {
head,
fromUin,
fromUid,
selfUin,
content,
body: msg.body,
responseHead: msg.responseHead,
identity,
isHistorical,
};
const content = msg.body?.msgContent ?? new Uint8Array(0);
return {
head,
fromUin,
fromUid,
selfUin,
content,
body: msg.body,
responseHead: msg.responseHead,
identity,
isHistorical,
};
}
@@ -1,30 +1,27 @@
import { protobuf_decode } from '@snowluma/proton';
import { createLogger } from '@snowluma/common/logger';
import type {
FriendAddEvent,
FriendPokeEvent,
FriendRequestEvent,
OnlineDeviceInfo,
OnlineDeviceKind,
QQEventVariant,
FriendAddEvent,
FriendPokeEvent,
FriendRequestEvent,
OnlineDeviceInfo,
OnlineDeviceKind,
QQEventVariant,
} from '../../events';
import type {
FriendRecall,
FriendRemarkChangedNotify,
FriendRequest,
GeneralGrayTipInfo,
InputStatusNotify,
NewFriend,
OnlineDeviceNotify,
ProfileLikeTip,
FriendRecall,
FriendRemarkChangedNotify,
FriendRequest,
GeneralGrayTipInfo,
InputStatusNotify,
NewFriend,
OnlineDeviceNotify,
ProfileLikeTip,
} from '@snowluma/proto-defs/notify';
import type { PttTransPush } from '@snowluma/proto-defs/ptt-trans';
import type { MsgPushContext } from '../context';
import { Event0x210SubType } from '../enums';
import {
buildTemplateMap, c2cRoutingUin, findTemplateValue,
resolveUidToUin,
} from '../helpers';
import { buildTemplateMap, c2cRoutingUin, findTemplateValue, resolveUidToUin } from '../helpers';
import type { MsgPushDecoder } from '../registry';
type FriendRecallEvent = Extract<QQEventVariant, { kind: 'friend_recall' }>;
@@ -34,67 +31,86 @@ type FriendProfileLikeEvent = Extract<QQEventVariant, { kind: 'friend_profile_li
const unknownLog = createLogger('MsgPush.Unknown');
export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
switch (ctx.head.subType as Event0x210SubType) {
case Event0x210SubType.FriendRequestNotice: return decodeFriendRequest(ctx);
case Event0x210SubType.PttTransResult: return decodePttTransResult(ctx);
// 138 (other-recalled) and 139 (self-recalled) share the same
// FriendRecall wire shape; the helper picks the right uid side
// based on the subType.
case Event0x210SubType.FriendRecallNotice:
case Event0x210SubType.FriendRecallSelfNotice:
return decodeFriendRecall(ctx);
case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx);
case Event0x210SubType.InputStatusNotice: return decodeInputStatus(ctx);
case Event0x210SubType.OnlineDevicesNotice: return decodeOnlineDevices(ctx);
case Event0x210SubType.FriendRemarkChangedNotice: return decodeFriendRemarkChanged(ctx);
case Event0x210SubType.ProfileLikeNotice: return decodeProfileLike(ctx);
// 179 + 226 both carry the NewFriend payload — see enum comment.
case Event0x210SubType.NewFriendNotice:
case Event0x210SubType.NewFriendNoticeAlt:
return decodeNewFriend(ctx);
case Event0x210SubType.GroupAppStatePush:
// QQ-client-internal troop shortcut bar / discussion app state
// push — no OneBot-level event. See enum comment for the
// decompiled-source breakdown of the sub_cmd dispatch.
return [];
case Event0x210SubType.UnmappedClientState380:
// QQ-NT-era subType with no reference handler: the legacy QQ
// Android decompile (tsuzcx/qq_apk) only enumerates SubType0x26
// through SubType0x146 under msgType0x210/, so 380 / 0x17C is
// an NT-era addition. None of the NT clients (Lagrange.Core,
// LagrangeGo, lagrange-python, mania) handle it either. See the
// enum comment for the full investigation; acknowledge silently
// until someone maps the schema.
return [];
}
unknownLog.debug('Event0x210 unknown subType=%d', ctx.head.subType);
return [];
switch (ctx.head.subType as Event0x210SubType) {
case Event0x210SubType.FriendRequestNotice:
return decodeFriendRequest(ctx);
case Event0x210SubType.PttTransResult:
return decodePttTransResult(ctx);
// 138 (other-recalled) and 139 (self-recalled) share the same
// FriendRecall wire shape; the helper picks the right uid side
// based on the subType.
case Event0x210SubType.FriendRecallNotice:
case Event0x210SubType.FriendRecallSelfNotice:
return decodeFriendRecall(ctx);
case Event0x210SubType.FriendPokeNotice:
return decodeFriendPoke(ctx);
case Event0x210SubType.InputStatusNotice:
return decodeInputStatus(ctx);
case Event0x210SubType.OnlineDevicesNotice:
return decodeOnlineDevices(ctx);
case Event0x210SubType.FriendRemarkChangedNotice:
return decodeFriendRemarkChanged(ctx);
case Event0x210SubType.ProfileLikeNotice:
return decodeProfileLike(ctx);
// 179 + 226 both carry the NewFriend payload — see enum comment.
case Event0x210SubType.NewFriendNotice:
case Event0x210SubType.NewFriendNoticeAlt:
return decodeNewFriend(ctx);
case Event0x210SubType.GroupAppStatePush:
// QQ-client-internal troop shortcut bar / discussion app state
// push — no OneBot-level event. See enum comment for the
// decompiled-source breakdown of the sub_cmd dispatch.
return [];
case Event0x210SubType.UnmappedClientState380:
// QQ-NT-era subType with no reference handler: the legacy QQ
// Android decompile (tsuzcx/qq_apk) only enumerates SubType0x26
// through SubType0x146 under msgType0x210/, so 380 / 0x17C is
// an NT-era addition. None of the NT clients (Lagrange.Core,
// LagrangeGo, lagrange-python, mania) handle it either. See the
// enum comment for the full investigation; acknowledge silently
// until someone maps the schema.
return [];
}
unknownLog.debug('Event0x210 unknown subType=%d', ctx.head.subType);
return [];
};
function decodeFriendRemarkChanged(ctx: MsgPushContext): QQEventVariant[] {
const notify = protobuf_decode<FriendRemarkChangedNotify>(ctx.content);
const change = notify?.change;
const uid = change?.target?.uid?.trim() ?? '';
const rawUin = change?.target?.uin;
const uin = rawUin === undefined ? 0 : Number(rawUin);
if (rawUin !== undefined && (!Number.isSafeInteger(uin) || uin <= 0)) {
throw new Error(`friend remark synchronization has invalid UIN ${rawUin}`);
}
if (!uid && uin <= 0) {
throw new Error('friend remark synchronization is missing both UID and UIN');
}
if (change?.remark === undefined) {
throw new Error(`friend remark synchronization is missing the remark value (uid=${uid} uin=${uin})`);
}
if (ctx.isHistorical) return [];
return [{
kind: 'friend_remark_changed',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
userUid: uid,
userUin: uin,
remark: change.remark,
}];
const notify = protobuf_decode<FriendRemarkChangedNotify>(ctx.content);
const change = notify?.change;
const uid = change?.target?.uid?.trim() ?? '';
const rawUin = change?.target?.uin;
const uin = rawUin === undefined ? 0 : Number(rawUin);
if (rawUin !== undefined && (!Number.isSafeInteger(uin) || uin <= 0)) {
throw new Error(`friend remark synchronization has invalid UIN ${rawUin}`);
}
if (!uid && uin <= 0) {
throw new Error('friend remark synchronization is missing both UID and UIN');
}
if (change?.remark === undefined) {
throw new Error(
`friend remark synchronization is missing the remark value (uid=${uid} uin=${uin})`,
);
}
if (ctx.isHistorical) {
return [];
}
return [
{
kind: 'friend_remark_changed',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
userUid: uid,
userUin: uin,
remark: change.remark,
},
];
}
const COMPUTER_CLIENT_TYPES = new Set([1, 5, 15]);
@@ -102,56 +118,79 @@ const PHONE_CLIENT_TYPES = new Set([2, 3, 4, 6, 7, 12]);
const PAD_CLIENT_TYPES = new Set([8, 9, 10, 11, 13]);
function onlineDeviceKind(clientType: number): OnlineDeviceKind {
if (COMPUTER_CLIENT_TYPES.has(clientType)) return 'computer';
if (PHONE_CLIENT_TYPES.has(clientType)) return 'phone';
if (PAD_CLIENT_TYPES.has(clientType)) return 'pad';
unknownLog.warn('online-device snapshot contains unknown clientType=%d', clientType);
return 'unknown';
if (COMPUTER_CLIENT_TYPES.has(clientType)) {
return 'computer';
}
if (PHONE_CLIENT_TYPES.has(clientType)) {
return 'phone';
}
if (PAD_CLIENT_TYPES.has(clientType)) {
return 'pad';
}
unknownLog.warn('online-device snapshot contains unknown clientType=%d', clientType);
return 'unknown';
}
function onlineDeviceClientType(rawClientType: number): number {
// QQ's OnRecvSysMsg path stores this wire field as an unsigned byte before
// it reaches DecodeOnLineDev. Higher bits carry terminal metadata and must
// not participate in device classification (live examples: 0x14702 -> 2,
// 0x10107 -> 7).
return rawClientType & 0xff;
// QQ's OnRecvSysMsg path stores this wire field as an unsigned byte before
// it reaches DecodeOnLineDev. Higher bits carry terminal metadata and must
// not participate in device classification (live examples: 0x14702 -> 2,
// 0x10107 -> 7).
return rawClientType & 0xff;
}
function decodeOnlineDevices(ctx: MsgPushContext): QQEventVariant[] {
const notify = protobuf_decode<OnlineDeviceNotify>(ctx.content);
if (!notify) return [];
const devices: OnlineDeviceInfo[] = [];
const seenDeviceKinds = new Set<OnlineDeviceKind>();
for (const [index, item] of (notify.devices ?? []).entries()) {
const appId = item.appId ?? 0;
const rawClientType = item.clientType ?? 0;
if (appId <= 0 || rawClientType <= 0) {
throw new Error(
`online-device entry ${index} is missing appId or clientType `
+ `(appIdPresent=${item.appId != null} clientTypePresent=${item.clientType != null})`,
);
const notify = protobuf_decode<OnlineDeviceNotify>(ctx.content);
if (!notify) {
return [];
}
const clientType = onlineDeviceClientType(rawClientType);
const deviceKind = onlineDeviceKind(clientType);
// QQ's DecodeOnLineDevList exposes one entry per derived devUid
// (computer/pad/phone), retaining the first item in each category.
if (seenDeviceKinds.has(deviceKind)) continue;
seenDeviceKinds.add(deviceKind);
devices.push({
appId,
instanceId: item.instanceId ?? 0,
clientType,
platform: item.platform ?? 0,
deviceName: item.deviceName ?? '',
deviceKind,
});
}
return [{
kind: 'online_devices_changed',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
devices,
}];
const devices: OnlineDeviceInfo[] = [];
const seenDeviceKinds = new Set<OnlineDeviceKind>();
for (const [index, item] of (notify.devices ?? []).entries()) {
const appId = item.appId ?? 0;
const rawClientType = item.clientType ?? 0;
if (appId <= 0 || rawClientType <= 0) {
throw new Error(
`online-device entry ${index} is missing appId or clientType ` +
`(appIdPresent=${item.appId != null} clientTypePresent=${item.clientType != null})`,
);
}
const clientType = onlineDeviceClientType(rawClientType);
const deviceKind = onlineDeviceKind(clientType);
// QQ's DecodeOnLineDevList exposes one entry per derived devUid
// (computer/pad/phone), retaining the first item in each category.
if (seenDeviceKinds.has(deviceKind)) {
continue;
}
seenDeviceKinds.add(deviceKind);
devices.push({
appId,
instanceId: item.instanceId ?? 0,
clientType,
platform: item.platform ?? 0,
deviceName: item.deviceName ?? '',
deviceKind,
});
}
return [
{
kind: 'online_devices_changed',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
devices,
},
];
}
// Voice-to-text async result push. Wire shape (live-verified):
@@ -159,69 +198,95 @@ function decodeOnlineDevices(ctx: MsgPushContext): QQEventVariant[] {
// `msgId` is the correlation key a pending fetch_ptt_text waits on; we surface
// it + the recognised text as an internal `ptt_trans_result` event.
function decodePttTransResult(ctx: MsgPushContext): QQEventVariant[] {
const push = protobuf_decode<PttTransPush>(ctx.content);
const item = push?.item;
if (!item) return [];
const msgId = Number(item.msgId ?? 0n);
const text = item.text ?? '';
if (!msgId || !text) return [];
return [{ kind: 'ptt_trans_result', time: ctx.head.timestamp, selfUin: ctx.selfUin, msgId, text }];
const push = protobuf_decode<PttTransPush>(ctx.content);
const item = push?.item;
if (!item) {
return [];
}
const msgId = Number(item.msgId ?? 0n);
const text = item.text ?? '';
if (!msgId || !text) {
return [];
}
return [
{ kind: 'ptt_trans_result', time: ctx.head.timestamp, selfUin: ctx.selfUin, msgId, text },
];
}
function decodeFriendRequest(ctx: MsgPushContext): QQEventVariant[] {
const request = protobuf_decode<FriendRequest>(ctx.content);
if (!request?.info) return [];
const sourceUid = request.info.newSource || request.info.sourceUid || '';
const ev: FriendRequestEvent = {
kind: 'friend_request',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
fromUin: resolveUidToUin(ctx.identity, 0, sourceUid),
fromUid: sourceUid,
message: request.info.message ?? '',
flag: sourceUid,
};
return [ev];
const request = protobuf_decode<FriendRequest>(ctx.content);
if (!request?.info) {
return [];
}
const sourceUid = request.info.newSource || request.info.sourceUid || '';
const ev: FriendRequestEvent = {
kind: 'friend_request',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
fromUin: resolveUidToUin(ctx.identity, 0, sourceUid),
fromUid: sourceUid,
message: request.info.message ?? '',
flag: sourceUid,
};
return [ev];
}
function decodeFriendRecall(ctx: MsgPushContext): QQEventVariant[] {
const recall = protobuf_decode<FriendRecall>(ctx.content);
if (!recall?.info) return [];
// 138 = friend recalled their own message sent to bot (peer = fromUid).
// 139 = bot recalled own message sent to friend (peer = toUid). Same
// ambiguity acidify handles in `parseFriendRecall:380`. Without this
// split, self-recall events surface `userUin` as the bot itself which
// confuses downstream OneBot consumers that key off `user_id`.
const isSelfRecall = ctx.head.subType === Event0x210SubType.FriendRecallSelfNotice;
const peerUid = (isSelfRecall ? recall.info.toUid : recall.info.fromUid) ?? '';
const ev: FriendRecallEvent = {
kind: 'friend_recall',
time: recall.info.time ?? ctx.head.timestamp,
selfUin: ctx.selfUin,
userUin: resolveUidToUin(ctx.identity, 0, peerUid),
msgSeq: recall.info.clientSequence ?? 0,
clientSeq: recall.info.clientSequence ?? 0,
recalledBySelf: isSelfRecall,
};
return [ev];
const recall = protobuf_decode<FriendRecall>(ctx.content);
if (!recall?.info) {
return [];
}
// 138 = friend recalled their own message sent to bot (peer = fromUid).
// 139 = bot recalled own message sent to friend (peer = toUid). Same
// ambiguity acidify handles in `parseFriendRecall:380`. Without this
// split, self-recall events surface `userUin` as the bot itself which
// confuses downstream OneBot consumers that key off `user_id`.
const isSelfRecall = ctx.head.subType === Event0x210SubType.FriendRecallSelfNotice;
const peerUid = (isSelfRecall ? recall.info.toUid : recall.info.fromUid) ?? '';
const ev: FriendRecallEvent = {
kind: 'friend_recall',
time: recall.info.time ?? ctx.head.timestamp,
selfUin: ctx.selfUin,
userUin: resolveUidToUin(ctx.identity, 0, peerUid),
msgSeq: recall.info.clientSequence ?? 0,
clientSeq: recall.info.clientSequence ?? 0,
recalledBySelf: isSelfRecall,
};
return [ev];
}
function decodeNewFriend(ctx: MsgPushContext): QQEventVariant[] {
const nf = protobuf_decode<NewFriend>(ctx.content);
if (!nf?.info) return [];
const newFriendUid = nf.info.uid ?? '';
const newFriendUin = c2cRoutingUin(ctx.identity, newFriendUid, ctx.fromUin);
if (newFriendUin <= 0) return []; // can't surface a `user_id`-less friend_add to OneBot
const ev: FriendAddEvent = {
kind: 'friend_add',
// proto field is `fixed32 Time` — already uint32 seconds epoch.
// Fall back to head.timestamp if the field is missing (some
// captures have it as 0).
time: nf.info.time && nf.info.time > 0 ? nf.info.time : ctx.head.timestamp,
selfUin: ctx.selfUin,
userUin: newFriendUin,
};
return [ev];
const nf = protobuf_decode<NewFriend>(ctx.content);
if (!nf?.info) {
return [];
}
const newFriendUid = nf.info.uid ?? '';
const newFriendUin = c2cRoutingUin(ctx.identity, newFriendUid, ctx.fromUin);
if (newFriendUin <= 0) {
return [];
} // can't surface a `user_id`-less friend_add to OneBot
const ev: FriendAddEvent = {
kind: 'friend_add',
// proto field is `fixed32 Time` — already uint32 seconds epoch.
// Fall back to head.timestamp if the field is missing (some
// captures have it as 0).
time: nf.info.time && nf.info.time > 0 ? nf.info.time : ctx.head.timestamp,
selfUin: ctx.selfUin,
userUin: newFriendUin,
};
return [ev];
}
// C2C "对方正在输入…" input-status push. Body (`InputStatusNotify`) rides in
@@ -231,25 +296,29 @@ function decodeNewFriend(ctx: MsgPushContext): QQEventVariant[] {
// synthesises the status text from that type, so we do the same for OneBot
// parity (NapCat's `onInputStatusPush` → `notice/notify` `input_status`).
function decodeInputStatus(ctx: MsgPushContext): QQEventVariant[] {
const notify = protobuf_decode<InputStatusNotify>(ctx.content);
const fromUid = notify?.fromUid ?? '';
if (!fromUid) return [];
const eventType = notify.notifyItem?.eventType ?? 1;
const ev: FriendInputStatusEvent = {
kind: 'friend_input_status',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
userUin: resolveUidToUin(ctx.identity, 0, fromUid),
userUid: fromUid,
eventType,
statusText: inputStatusText(eventType),
};
return [ev];
const notify = protobuf_decode<InputStatusNotify>(ctx.content);
const fromUid = notify?.fromUid ?? '';
if (!fromUid) {
return [];
}
const eventType = notify.notifyItem?.eventType ?? 1;
const ev: FriendInputStatusEvent = {
kind: 'friend_input_status',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
userUin: resolveUidToUin(ctx.identity, 0, fromUid),
userUid: fromUid,
eventType,
statusText: inputStatusText(eventType),
};
return [ev];
}
// The client's own strings (wrapper.linux.node @0xB8FFE0 / @0xB90000).
function inputStatusText(eventType: number): string {
return eventType === 3 ? '对方正在讲话...' : '对方正在输入...';
return eventType === 3 ? '对方正在讲话...' : '对方正在输入...';
}
// subType 39 is multiplexed; body.msgContent decodes as ProfileLikeTip and is a
@@ -258,61 +327,71 @@ function inputStatusText(eventType: number): string {
// `times` is the like count parsed out of `detail.txt` ("赞了我的资料卡N次").
// Field layout confirmed byte-exact against real on-wire captures.
function decodeProfileLike(ctx: MsgPushContext): QQEventVariant[] {
const tip = protobuf_decode<ProfileLikeTip>(ctx.content);
// msgType 0 is the proto default → omitted on the wire → decodes as undefined,
// so treat missing as 0 (matches NapCat's `msgType !== 0` check).
if (!tip || (tip.msgType ?? 0) !== 0 || (tip.subType ?? 0) !== 203) return [];
const msg = tip.content?.msg;
const detail = msg?.detail;
const operatorUin = Number(detail?.uin ?? 0n);
if (!operatorUin) return [];
const times = Number.parseInt((detail?.txt ?? '').match(/\d+/)?.[0] ?? '0', 10) || 0;
const ev: FriendProfileLikeEvent = {
kind: 'friend_profile_like',
time: msg?.time || ctx.head.timestamp,
selfUin: ctx.selfUin,
operatorUin,
operatorNick: detail?.nickname ?? '',
times,
};
return [ev];
const tip = protobuf_decode<ProfileLikeTip>(ctx.content);
// msgType 0 is the proto default → omitted on the wire → decodes as undefined,
// so treat missing as 0 (matches NapCat's `msgType !== 0` check).
if (!tip || (tip.msgType ?? 0) !== 0 || (tip.subType ?? 0) !== 203) {
return [];
}
const msg = tip.content?.msg;
const detail = msg?.detail;
const operatorUin = Number(detail?.uin ?? 0n);
if (!operatorUin) {
return [];
}
const times = Number.parseInt((detail?.txt ?? '').match(/\d+/)?.[0] ?? '0', 10) || 0;
const ev: FriendProfileLikeEvent = {
kind: 'friend_profile_like',
time: msg?.time || ctx.head.timestamp,
selfUin: ctx.selfUin,
operatorUin,
operatorNick: detail?.nickname ?? '',
times,
};
return [ev];
}
function decodeFriendPoke(ctx: MsgPushContext): QQEventVariant[] {
const grayTip = protobuf_decode<GeneralGrayTipInfo>(ctx.content);
if (!grayTip || (grayTip.busiType ?? 0n) !== 12n) return [];
const templates = buildTemplateMap(grayTip.msgTemplParam ?? []);
const actor = findTemplateValue(templates, 'uin_str1');
const target = findTemplateValue(templates, 'uin_str2');
const senderUin = resolveUidToUin(ctx.identity, 0, actor);
const routeFromUin = c2cRoutingUin(ctx.identity, ctx.fromUid, ctx.fromUin);
// The gray-tip template only identifies the two poke endpoints. The C2C
// routing head owns the conversation peer: outbound notices use `to`,
// while inbound notices use `from`, just like ordinary friend messages.
const sentBySelf = routeFromUin > 0 && routeFromUin === ctx.selfUin;
const peerUin = sentBySelf
? c2cRoutingUin(
ctx.identity,
ctx.responseHead?.toUid ?? '',
ctx.responseHead?.toUin ?? 0,
)
: routeFromUin;
if (peerUin <= 0) {
throw new Error(
'friend poke conversation peer is missing '
+ `(fromUin=${ctx.fromUin} toUin=${ctx.responseHead?.toUin ?? 0} sentBySelf=${sentBySelf})`,
);
}
const ev: FriendPokeEvent = {
kind: 'friend_poke',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
peerUin,
senderUin,
targetUin: resolveUidToUin(ctx.identity, 0, target),
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
suffix: findTemplateValue(templates, 'suffix_str'),
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
};
return [ev];
const grayTip = protobuf_decode<GeneralGrayTipInfo>(ctx.content);
if (!grayTip || (grayTip.busiType ?? 0n) !== 12n) {
return [];
}
const templates = buildTemplateMap(grayTip.msgTemplParam ?? []);
const actor = findTemplateValue(templates, 'uin_str1');
const target = findTemplateValue(templates, 'uin_str2');
const senderUin = resolveUidToUin(ctx.identity, 0, actor);
const routeFromUin = c2cRoutingUin(ctx.identity, ctx.fromUid, ctx.fromUin);
// The gray-tip template only identifies the two poke endpoints. The C2C
// routing head owns the conversation peer: outbound notices use `to`,
// while inbound notices use `from`, just like ordinary friend messages.
const sentBySelf = routeFromUin > 0 && routeFromUin === ctx.selfUin;
const peerUin = sentBySelf
? c2cRoutingUin(ctx.identity, ctx.responseHead?.toUid ?? '', ctx.responseHead?.toUin ?? 0)
: routeFromUin;
if (peerUin <= 0) {
throw new Error(
'friend poke conversation peer is missing ' +
`(fromUin=${ctx.fromUin} toUin=${ctx.responseHead?.toUin ?? 0} sentBySelf=${sentBySelf})`,
);
}
const ev: FriendPokeEvent = {
kind: 'friend_poke',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
peerUin,
senderUin,
targetUin: resolveUidToUin(ctx.identity, 0, target),
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
suffix: findTemplateValue(templates, 'suffix_str'),
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
};
return [ev];
}
@@ -1,121 +1,159 @@
import { protobuf_decode } from '@snowluma/proton';
import { createLogger } from '@snowluma/common/logger';
import type {
GroupEssenceEvent,
GroupMsgEmojiLikeEvent,
GroupMuteEvent,
GroupNameChangeEvent,
GroupTitleChangeEvent,
GroupPokeEvent,
GroupRecallEvent,
QQEventVariant,
GroupEssenceEvent,
GroupMsgEmojiLikeEvent,
GroupMuteEvent,
GroupNameChangeEvent,
GroupTitleChangeEvent,
GroupPokeEvent,
GroupRecallEvent,
QQEventVariant,
} from '../../events';
import type {
GroupMute,
GroupNameChange,
GroupSpecialTitleChange,
GroupReactNotify,
NotifyMessageBody,
GroupMute,
GroupNameChange,
GroupSpecialTitleChange,
GroupReactNotify,
NotifyMessageBody,
} from '@snowluma/proto-defs/notify';
import type { MsgPushContext } from '../context';
import { Event0x2DCSubType } from '../enums';
import {
buildTemplateMap, findTemplateValue,
resolveUidToUin,
unwrapGroupNotifyPayload,
buildTemplateMap,
findTemplateValue,
resolveUidToUin,
unwrapGroupNotifyPayload,
} from '../helpers';
import type { MsgPushDecoder } from '../registry';
const unknownLog = createLogger('MsgPush.Unknown');
export const decodeEvent0x2DC: MsgPushDecoder = (ctx) => {
switch (ctx.head.subType as Event0x2DCSubType) {
case Event0x2DCSubType.GroupMuteNotice: return decodeGroupMute(ctx);
case Event0x2DCSubType.GroupMsgEmojiLikeNotice: return decodeSubType16(ctx);
case Event0x2DCSubType.GroupRecallNotice: return decodeGroupRecall(ctx);
case Event0x2DCSubType.GroupGreyTipNotice: return decodeGroupGreyTip(ctx);
case Event0x2DCSubType.GroupEssenceNotice: return decodeGroupEssence(ctx);
}
unknownLog.debug('Event0x2DC unknown subType=%d', ctx.head.subType);
return [];
switch (ctx.head.subType as Event0x2DCSubType) {
case Event0x2DCSubType.GroupMuteNotice:
return decodeGroupMute(ctx);
case Event0x2DCSubType.GroupMsgEmojiLikeNotice:
return decodeSubType16(ctx);
case Event0x2DCSubType.GroupRecallNotice:
return decodeGroupRecall(ctx);
case Event0x2DCSubType.GroupGreyTipNotice:
return decodeGroupGreyTip(ctx);
case Event0x2DCSubType.GroupEssenceNotice:
return decodeGroupEssence(ctx);
}
unknownLog.debug('Event0x2DC unknown subType=%d', ctx.head.subType);
return [];
};
function decodeGroupMute(ctx: MsgPushContext): QQEventVariant[] {
const mute = protobuf_decode<GroupMute>(ctx.content);
if (!mute?.data?.state) return [];
const duration = mute.data.state.duration ?? 0;
const ev: GroupMuteEvent = {
kind: 'group_mute',
time: mute.data.timestamp ?? ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: mute.groupUin ?? 0,
operatorUin: resolveUidToUin(ctx.identity, mute.groupUin ?? 0, mute.operatorUid ?? ''),
userUin: resolveUidToUin(ctx.identity, mute.groupUin ?? 0, mute.data.state.targetUid ?? ''),
duration: duration === 0xFFFFFFFF ? 0x7FFFFFFF : duration,
};
return [ev];
const mute = protobuf_decode<GroupMute>(ctx.content);
if (!mute?.data?.state) {
return [];
}
const duration = mute.data.state.duration ?? 0;
const ev: GroupMuteEvent = {
kind: 'group_mute',
time: mute.data.timestamp ?? ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: mute.groupUin ?? 0,
operatorUin: resolveUidToUin(ctx.identity, mute.groupUin ?? 0, mute.operatorUid ?? ''),
userUin: resolveUidToUin(ctx.identity, mute.groupUin ?? 0, mute.data.state.targetUid ?? ''),
duration: duration === 0xffffffff ? 0x7fffffff : duration,
};
return [ev];
}
function decodeGroupRecall(ctx: MsgPushContext): QQEventVariant[] {
const payload = unwrapGroupNotifyPayload(ctx.content);
if (!payload) return [];
const notify = protobuf_decode<NotifyMessageBody>(payload);
if (!notify?.recall?.recallMessages || notify.recall.recallMessages.length === 0) return [];
const recalled = notify.recall.recallMessages[0];
const ev: GroupRecallEvent = {
kind: 'group_recall',
time: recalled.time ?? ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: notify.groupUin ?? 0,
operatorUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0,
notify.recall.operatorUid || notify.operatorUid || ''),
authorUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, recalled.authorUid ?? ''),
msgSeq: recalled.sequence ?? 0,
};
return [ev];
const payload = unwrapGroupNotifyPayload(ctx.content);
if (!payload) {
return [];
}
const notify = protobuf_decode<NotifyMessageBody>(payload);
if (!notify?.recall?.recallMessages || notify.recall.recallMessages.length === 0) {
return [];
}
const recalled = notify.recall.recallMessages[0];
const ev: GroupRecallEvent = {
kind: 'group_recall',
time: recalled.time ?? ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: notify.groupUin ?? 0,
operatorUin: resolveUidToUin(
ctx.identity,
notify.groupUin ?? 0,
notify.recall.operatorUid || notify.operatorUid || '',
),
authorUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, recalled.authorUid ?? ''),
msgSeq: recalled.sequence ?? 0,
};
return [ev];
}
function decodeGroupGreyTip(ctx: MsgPushContext): QQEventVariant[] {
const payload = unwrapGroupNotifyPayload(ctx.content);
if (!payload) return [];
const notify = protobuf_decode<NotifyMessageBody>(payload);
if (!notify?.generalGrayTip || (notify.generalGrayTip.busiType ?? 0n) !== 12n) return [];
const templates = buildTemplateMap(notify.generalGrayTip.msgTemplParam ?? []);
const actor = findTemplateValue(templates, 'uin_str1');
const target = findTemplateValue(templates, 'uin_str2');
const ev: GroupPokeEvent = {
kind: 'group_poke',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: notify.groupUin ?? 0,
userUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, actor),
targetUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, target),
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
suffix: findTemplateValue(templates, 'suffix_str'),
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
};
return [ev];
const payload = unwrapGroupNotifyPayload(ctx.content);
if (!payload) {
return [];
}
const notify = protobuf_decode<NotifyMessageBody>(payload);
if (!notify?.generalGrayTip || (notify.generalGrayTip.busiType ?? 0n) !== 12n) {
return [];
}
const templates = buildTemplateMap(notify.generalGrayTip.msgTemplParam ?? []);
const actor = findTemplateValue(templates, 'uin_str1');
const target = findTemplateValue(templates, 'uin_str2');
const ev: GroupPokeEvent = {
kind: 'group_poke',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: notify.groupUin ?? 0,
userUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, actor),
targetUin: resolveUidToUin(ctx.identity, notify.groupUin ?? 0, target),
action: findTemplateValue(templates, 'action_str', 'alt_str1'),
suffix: findTemplateValue(templates, 'suffix_str'),
actionImgUrl: findTemplateValue(templates, 'action_img_url'),
};
return [ev];
}
function decodeGroupEssence(ctx: MsgPushContext): QQEventVariant[] {
const payload = unwrapGroupNotifyPayload(ctx.content);
if (!payload) return [];
const notify = protobuf_decode<NotifyMessageBody>(payload);
if (!notify?.essenceMessage) return [];
const essence = notify.essenceMessage;
const setFlag = essence.setFlag ?? essence.setFlag2 ?? 0;
const ev: GroupEssenceEvent = {
kind: 'group_essence',
time: essence.timestamp ?? ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: essence.groupUin ?? notify.groupUin ?? 0,
senderUin: essence.memberUin ?? 0,
operatorUin: essence.operatorUin ?? 0,
msgSeq: essence.msgSequence ?? essence.msgSequence2 ?? notify.msgSequence ?? 0,
random: essence.random ?? 0,
set: setFlag === 1,
};
return [ev];
const payload = unwrapGroupNotifyPayload(ctx.content);
if (!payload) {
return [];
}
const notify = protobuf_decode<NotifyMessageBody>(payload);
if (!notify?.essenceMessage) {
return [];
}
const essence = notify.essenceMessage;
const setFlag = essence.setFlag ?? essence.setFlag2 ?? 0;
const ev: GroupEssenceEvent = {
kind: 'group_essence',
time: essence.timestamp ?? ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: essence.groupUin ?? notify.groupUin ?? 0,
senderUin: essence.memberUin ?? 0,
operatorUin: essence.operatorUin ?? 0,
msgSeq: essence.msgSequence ?? essence.msgSequence2 ?? notify.msgSequence ?? 0,
random: essence.random ?? 0,
set: setFlag === 1,
};
return [ev];
}
// Magic prefix QQ prepends to the GroupReactNotify payload inside
@@ -134,16 +172,25 @@ const SUBTYPE16_SPECIAL_TITLE = 6;
const SUBTYPE16_GROUP_NAME_CHANGE = 12;
function decodeSubType16(ctx: MsgPushContext): QQEventVariant[] {
if (ctx.content.length <= GROUP_REACT_PREFIX_BYTES) return [];
const field13 = protobuf_decode<NotifyMessageBody>(ctx.content.subarray(GROUP_REACT_PREFIX_BYTES))?.field13 ?? 0;
switch (field13) {
case SUBTYPE16_SPECIAL_TITLE: return decodeGroupTitle(ctx);
case SUBTYPE16_GROUP_NAME_CHANGE: return decodeGroupName(ctx);
case GROUP_REACT_DISCRIMINATOR: return decodeGroupMsgEmojiLike(ctx);
default:
unknownLog.debug('Event0x2DC subType=16 unhandled field13=%d', field13);
return [];
}
if (ctx.content.length <= GROUP_REACT_PREFIX_BYTES) {
return [];
}
const field13 =
protobuf_decode<NotifyMessageBody>(ctx.content.subarray(GROUP_REACT_PREFIX_BYTES))
?.field13 ?? 0;
switch (field13) {
case SUBTYPE16_SPECIAL_TITLE:
return decodeGroupTitle(ctx);
case SUBTYPE16_GROUP_NAME_CHANGE:
return decodeGroupName(ctx);
case GROUP_REACT_DISCRIMINATOR:
return decodeGroupMsgEmojiLike(ctx);
default:
unknownLog.debug('Event0x2DC subType=16 unhandled field13=%d', field13);
return [];
}
}
// field13 == 6: a member was granted a special title. eventParam carries the
@@ -151,95 +198,128 @@ function decodeSubType16(ctx: MsgPushContext): QQEventVariant[] {
// `<{"…","text":TITLE,…}>` rich token in that string (on-wire captured shape —
// the kernel resolves the template to a clean string, we parse it here).
function decodeGroupTitle(ctx: MsgPushContext): QQEventVariant[] {
const notify = protobuf_decode<NotifyMessageBody>(ctx.content.subarray(GROUP_REACT_PREFIX_BYTES));
const param = notify?.eventParam
? protobuf_decode<GroupSpecialTitleChange>(notify.eventParam)
: undefined;
const userUin = param?.memberUin ?? 0;
const title = extractTitleFromTip(param?.tipText ?? '');
if (!userUin || !title) return [];
const ev: GroupTitleChangeEvent = {
kind: 'group_title_change',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: notify?.groupUin ?? 0,
userUin,
title,
};
return [ev];
const notify = protobuf_decode<NotifyMessageBody>(
ctx.content.subarray(GROUP_REACT_PREFIX_BYTES),
);
const param = notify?.eventParam
? protobuf_decode<GroupSpecialTitleChange>(notify.eventParam)
: undefined;
const userUin = param?.memberUin ?? 0;
const title = extractTitleFromTip(param?.tipText ?? '');
if (!userUin || !title) {
return [];
}
const ev: GroupTitleChangeEvent = {
kind: 'group_title_change',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: notify?.groupUin ?? 0,
userUin,
title,
};
return [ev];
}
// The tip text is "恭喜<{member}>获得群主授予的<{…"text":TITLE…}>头衔" — the title is
// the `text` of the LAST `<{…}>` rich token (the one just before "头衔"). Tokens
// are flat JSON with no `<`/`>` inside, so a non-greedy scan is safe.
function extractTitleFromTip(text: string): string {
const tokens = text.match(/<\{[^<>]*\}>/g);
if (!tokens || tokens.length === 0) return '';
const last = tokens[tokens.length - 1];
try {
const parsed = JSON.parse(last.slice(1, -1)) as { text?: string };
return parsed.text ?? '';
} catch {
return '';
}
const tokens = text.match(/<\{[^<>]*\}>/g);
if (!tokens || tokens.length === 0) {
return '';
}
const last = tokens[tokens.length - 1];
try {
const parsed = JSON.parse(last.slice(1, -1)) as { text?: string };
return parsed.text ?? '';
} catch {
return '';
}
}
// field13 == 12: group renamed. New name is nested in `eventParam` as a
// `GroupNameChange` (field 2); operator is `NotifyMessageBody.operatorUid`.
function decodeGroupName(ctx: MsgPushContext): QQEventVariant[] {
const notify = protobuf_decode<NotifyMessageBody>(ctx.content.subarray(GROUP_REACT_PREFIX_BYTES));
const name = notify?.eventParam ? (protobuf_decode<GroupNameChange>(notify.eventParam)?.name ?? '') : '';
if (!name) return [];
const groupId = notify?.groupUin ?? 0;
const ev: GroupNameChangeEvent = {
kind: 'group_name_change',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
// Operator is a group member → resolves from the roster. Fall back to 0
// (not ctx.fromUin, which on a 0x2DC push is the group id) so an
// unresolved operator never surfaces the group id as user_id.
operatorUin: resolveUidToUin(ctx.identity, groupId, notify?.operatorUid ?? ''),
name,
};
return [ev];
const notify = protobuf_decode<NotifyMessageBody>(
ctx.content.subarray(GROUP_REACT_PREFIX_BYTES),
);
const name = notify?.eventParam
? (protobuf_decode<GroupNameChange>(notify.eventParam)?.name ?? '')
: '';
if (!name) {
return [];
}
const groupId = notify?.groupUin ?? 0;
const ev: GroupNameChangeEvent = {
kind: 'group_name_change',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
// Operator is a group member → resolves from the roster. Fall back to 0
// (not ctx.fromUin, which on a 0x2DC push is the group id) so an
// unresolved operator never surfaces the group id as user_id.
operatorUin: resolveUidToUin(ctx.identity, groupId, notify?.operatorUid ?? ''),
name,
};
return [ev];
}
function decodeGroupMsgEmojiLike(ctx: MsgPushContext): QQEventVariant[] {
if (ctx.content.length <= GROUP_REACT_PREFIX_BYTES) return [];
const payload = ctx.content.subarray(GROUP_REACT_PREFIX_BYTES);
const notify = protobuf_decode<GroupReactNotify>(payload);
if (!notify) return [];
if ((notify.field13 ?? 0) !== GROUP_REACT_DISCRIMINATOR) {
unknownLog.debug('Event0x2DC subType=16 unhandled field13=%d (expected %d for emoji react)',
notify.field13 ?? 0, GROUP_REACT_DISCRIMINATOR);
return [];
}
const content = notify.groupReactionData?.data?.data?.groupReactionDataContent;
const target = notify.groupReactionData?.data?.data?.groupReactionTarget;
if (!content) return [];
if (ctx.content.length <= GROUP_REACT_PREFIX_BYTES) {
return [];
}
const groupId = Number(notify.groupUin ?? 0n);
const operatorUid = content.operatorUid ?? '';
const emojiId = content.code ?? '';
const count = content.count ?? 1;
// type is QQ's add/remove discriminator: 1 = react added, 2 = react
// removed. Older payloads occasionally omit it; default to "add"
// since most clients can only generate add events.
const isAdd = (content.type ?? 1) === 1;
const msgSeq = Number(target?.seq ?? 0n);
const payload = ctx.content.subarray(GROUP_REACT_PREFIX_BYTES);
const notify = protobuf_decode<GroupReactNotify>(payload);
const ev: GroupMsgEmojiLikeEvent = {
kind: 'group_msg_emoji_like',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid),
operatorUid,
msgSeq,
emojiId,
count,
isAdd,
};
return [ev];
if (!notify) {
return [];
}
if ((notify.field13 ?? 0) !== GROUP_REACT_DISCRIMINATOR) {
unknownLog.debug(
'Event0x2DC subType=16 unhandled field13=%d (expected %d for emoji react)',
notify.field13 ?? 0,
GROUP_REACT_DISCRIMINATOR,
);
return [];
}
const content = notify.groupReactionData?.data?.data?.groupReactionDataContent;
const target = notify.groupReactionData?.data?.data?.groupReactionTarget;
if (!content) {
return [];
}
const groupId = Number(notify.groupUin ?? 0n);
const operatorUid = content.operatorUid ?? '';
const emojiId = content.code ?? '';
const count = content.count ?? 1;
// type is QQ's add/remove discriminator: 1 = react added, 2 = react
// removed. Older payloads occasionally omit it; default to "add"
// since most clients can only generate add events.
const isAdd = (content.type ?? 1) === 1;
const msgSeq = Number(target?.seq ?? 0n);
const ev: GroupMsgEmojiLikeEvent = {
kind: 'group_msg_emoji_like',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid),
operatorUid,
msgSeq,
emojiId,
count,
isAdd,
};
return [ev];
}
@@ -12,56 +12,86 @@ import { decodeRichBody } from '../rich-body-decoder';
* use it. See issue #125.
*/
function parseGroupInviteCard(jsonText: string): { groupUin: number; sequence: number } | null {
if (!jsonText.includes('group/invite_join')) return null;
const m = jsonText.match(/mqqapi:\/\/group\/invite_join[^"\\\s]*/);
if (!m) return null;
const query = m[0].split('?')[1] ?? '';
const params = new URLSearchParams(query);
const groupUin = Number(params.get('groupcode') ?? 0);
const sequence = Number(params.get('msgseq') ?? 0);
if (!Number.isSafeInteger(groupUin) || !Number.isSafeInteger(sequence)) return null;
if (groupUin <= 0 || sequence <= 0) return null;
return { groupUin, sequence };
if (!jsonText.includes('group/invite_join')) {
return null;
}
const m = jsonText.match(/mqqapi:\/\/group\/invite_join[^"\\\s]*/);
if (!m) {
return null;
}
const query = m[0].split('?')[1] ?? '';
const params = new URLSearchParams(query);
const groupUin = Number(params.get('groupcode') ?? 0);
const sequence = Number(params.get('msgseq') ?? 0);
if (!Number.isSafeInteger(groupUin) || !Number.isSafeInteger(sequence)) {
return null;
}
if (groupUin <= 0 || sequence <= 0) {
return null;
}
return { groupUin, sequence };
}
export const decodeFriendMessage: MsgPushDecoder = (ctx) => {
const dataline = tryDecodeDatalineFriendMessage(ctx);
if (dataline) return [dataline];
const dataline = tryDecodeDatalineFriendMessage(ctx);
const elements = decodeRichBody(ctx.body, false);
const sentBySelf = ctx.fromUin > 0 && ctx.fromUin === ctx.selfUin;
const peerUin = sentBySelf ? (ctx.responseHead?.toUin ?? 0) : ctx.fromUin;
const sequenceAuthoritative = ctx.head.ntMsgSeq > 0;
let inviteCard: { groupUin: number; sequence: number } | null = null;
for (const el of elements) {
if (el.type === 'json' && typeof el.text === 'string') {
inviteCard = parseGroupInviteCard(el.text);
if (inviteCard) break;
if (dataline) {
return [dataline];
}
}
const ev: FriendMessage = {
kind: 'friend_message',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
senderUin: ctx.fromUin,
senderUid: ctx.fromUid,
...(peerUin > 0 ? { peerUin } : {}),
msgSeq: ctx.head.sequence,
ntMsgSeq: ctx.head.ntMsgSeq,
clientSeq: ctx.head.sequence,
sequenceAuthoritative,
msgId: ctx.head.msgId & 0x7FFFFFFF,
elements,
senderNick: '',
...(inviteCard ? {
inviteCardGroupUin: inviteCard.groupUin,
inviteCardSequence: inviteCard.sequence,
} : {}),
};
if (ctx.responseHead?.forward?.friendName) {
ev.senderNick = ctx.responseHead.forward.friendName;
}
const friend = ctx.identity.findFriend(ctx.fromUin);
if (friend && !ev.senderNick) ev.senderNick = friend.nickname;
return [ev];
const elements = decodeRichBody(ctx.body, false);
const sentBySelf = ctx.fromUin > 0 && ctx.fromUin === ctx.selfUin;
const peerUin = sentBySelf ? (ctx.responseHead?.toUin ?? 0) : ctx.fromUin;
const sequenceAuthoritative = ctx.head.ntMsgSeq > 0;
let inviteCard: { groupUin: number; sequence: number } | null = null;
for (const el of elements) {
if (el.type === 'json' && typeof el.text === 'string') {
inviteCard = parseGroupInviteCard(el.text);
if (inviteCard) {
break;
}
}
}
const ev: FriendMessage = {
kind: 'friend_message',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
senderUin: ctx.fromUin,
senderUid: ctx.fromUid,
...(peerUin > 0 ? { peerUin } : {}),
msgSeq: ctx.head.sequence,
ntMsgSeq: ctx.head.ntMsgSeq,
clientSeq: ctx.head.sequence,
sequenceAuthoritative,
msgId: ctx.head.msgId & 0x7fffffff,
elements,
senderNick: '',
...(inviteCard
? {
inviteCardGroupUin: inviteCard.groupUin,
inviteCardSequence: inviteCard.sequence,
}
: {}),
};
if (ctx.responseHead?.forward?.friendName) {
ev.senderNick = ctx.responseHead.forward.friendName;
}
const friend = ctx.identity.findFriend(ctx.fromUin);
if (friend && !ev.senderNick) {
ev.senderNick = friend.nickname;
}
return [ev];
};
@@ -5,29 +5,37 @@ import { resolveUidToUin } from '../helpers';
import type { MsgPushDecoder } from '../registry';
export const decodeGroupAdmin: MsgPushDecoder = (ctx) => {
const admin = protobuf_decode<GroupAdmin>(ctx.content);
if (!admin?.body) return [];
// proton materializes an *absent* embedded-message field as an empty
// `{}` rather than leaving it undefined, so the old
// `extraEnable !== undefined` promote/demote test was always true and
// every demote got reported as a promotion (with a fallback userUin).
// The live sub-message is the one that actually carries an `adminUid`
// — key off that instead.
const enableUid = admin.body.extraEnable?.adminUid;
const disableUid = admin.body.extraDisable?.adminUid;
const adminUid = enableUid || disableUid;
if (!adminUid) return [];
const groupId = admin.groupUin ?? 0;
const set = !!enableUid;
const userUin = resolveUidToUin(ctx.identity, groupId, adminUid);
const admin = protobuf_decode<GroupAdmin>(ctx.content);
const ev: GroupAdminEvent = {
kind: 'group_admin',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
userUin,
set,
};
return [ev];
if (!admin?.body) {
return [];
}
// proton materializes an *absent* embedded-message field as an empty
// `{}` rather than leaving it undefined, so the old
// `extraEnable !== undefined` promote/demote test was always true and
// every demote got reported as a promotion (with a fallback userUin).
// The live sub-message is the one that actually carries an `adminUid`
// — key off that instead.
const enableUid = admin.body.extraEnable?.adminUid;
const disableUid = admin.body.extraDisable?.adminUid;
const adminUid = enableUid || disableUid;
if (!adminUid) {
return [];
}
const groupId = admin.groupUin ?? 0;
const set = !!enableUid;
const userUin = resolveUidToUin(ctx.identity, groupId, adminUid);
const ev: GroupAdminEvent = {
kind: 'group_admin',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
userUin,
set,
};
return [ev];
};
@@ -1,64 +1,73 @@
import { protobuf_decode } from '@snowluma/proton';
import type { GroupInviteEvent } from '../../events';
import type {
GroupInvitation, GroupInvite,
GroupJoin,
} from '@snowluma/proto-defs/notify';
import type { GroupInvitation, GroupInvite, GroupJoin } from '@snowluma/proto-defs/notify';
import { resolveUidToUin } from '../helpers';
import type { MsgPushDecoder } from '../registry';
export const decodeGroupJoinRequest: MsgPushDecoder = (ctx) => {
const join = protobuf_decode<GroupJoin>(ctx.content);
if (!join) return [];
const ev: GroupInviteEvent = {
kind: 'group_invite',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: join.groupUin ?? 0,
// Strangers stay unresolved here. Pipeline fills UIN via Identity.resolveUin.
fromUin: resolveUidToUin(ctx.identity, join.groupUin ?? 0, join.targetUid ?? ''),
fromUid: join.targetUid ?? '',
subType: 'add',
message: '',
flag: 'add:' + (join.groupUin ?? 0) + ':' + (join.targetUid ?? ''),
};
return [ev];
const join = protobuf_decode<GroupJoin>(ctx.content);
if (!join) {
return [];
}
const ev: GroupInviteEvent = {
kind: 'group_invite',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: join.groupUin ?? 0,
// Strangers stay unresolved here. Pipeline fills UIN via Identity.resolveUin.
fromUin: resolveUidToUin(ctx.identity, join.groupUin ?? 0, join.targetUid ?? ''),
fromUid: join.targetUid ?? '',
subType: 'add',
message: '',
flag: 'add:' + (join.groupUin ?? 0) + ':' + (join.targetUid ?? ''),
};
return [ev];
};
export const decodeGroupInvitation: MsgPushDecoder = (ctx) => {
const invitation = protobuf_decode<GroupInvitation>(ctx.content);
if (!invitation?.info?.inner) return [];
const inner = invitation.info.inner;
const ev: GroupInviteEvent = {
kind: 'group_invite',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: inner.groupUin ?? 0,
fromUin: resolveUidToUin(ctx.identity, inner.groupUin ?? 0, inner.invitorUid ?? ''),
fromUid: inner.invitorUid ?? '',
invitedUin: resolveUidToUin(ctx.identity, inner.groupUin ?? 0, inner.targetUid ?? ''),
invitedUid: inner.targetUid ?? '',
subType: 'invite',
message: '',
flag: 'invite:' + (inner.groupUin ?? 0) + ':' + (inner.invitorUid ?? ''),
};
return [ev];
const invitation = protobuf_decode<GroupInvitation>(ctx.content);
if (!invitation?.info?.inner) {
return [];
}
const inner = invitation.info.inner;
const ev: GroupInviteEvent = {
kind: 'group_invite',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: inner.groupUin ?? 0,
fromUin: resolveUidToUin(ctx.identity, inner.groupUin ?? 0, inner.invitorUid ?? ''),
fromUid: inner.invitorUid ?? '',
invitedUin: resolveUidToUin(ctx.identity, inner.groupUin ?? 0, inner.targetUid ?? ''),
invitedUid: inner.targetUid ?? '',
subType: 'invite',
message: '',
flag: 'invite:' + (inner.groupUin ?? 0) + ':' + (inner.invitorUid ?? ''),
};
return [ev];
};
export const decodeGroupInvite: MsgPushDecoder = (ctx) => {
const invite = protobuf_decode<GroupInvite>(ctx.content);
if (!invite) return [];
const ev: GroupInviteEvent = {
kind: 'group_invite',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: invite.groupUin ?? 0,
fromUin: resolveUidToUin(ctx.identity, invite.groupUin ?? 0, invite.invitorUid ?? ''),
fromUid: invite.invitorUid ?? '',
invitedUin: ctx.selfUin,
subType: 'invite',
message: '',
flag: 'invite:' + (invite.groupUin ?? 0) + ':' + (invite.invitorUid ?? ''),
};
return [ev];
const invite = protobuf_decode<GroupInvite>(ctx.content);
if (!invite) {
return [];
}
const ev: GroupInviteEvent = {
kind: 'group_invite',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId: invite.groupUin ?? 0,
fromUin: resolveUidToUin(ctx.identity, invite.groupUin ?? 0, invite.invitorUid ?? ''),
fromUid: invite.invitorUid ?? '',
invitedUin: ctx.selfUin,
subType: 'invite',
message: '',
flag: 'invite:' + (invite.groupUin ?? 0) + ':' + (invite.invitorUid ?? ''),
};
return [ev];
};
@@ -1,43 +1,43 @@
import { protobuf_decode } from '@snowluma/proton';
import type { GroupMemberJoin, GroupMemberLeave } from '../../events';
import type { GroupChange, SelfJoinInGroup } from '@snowluma/proto-defs/notify';
import {
decodeGroupChangeOperatorUid,
decodeNestedOperatorUid,
resolveUidToUin,
} from '../helpers';
import { decodeGroupChangeOperatorUid, decodeNestedOperatorUid, resolveUidToUin } from '../helpers';
import type { MsgPushDecoder } from '../registry';
function joinTypeFromOperationType(raw: number): NonNullable<GroupMemberJoin['joinType']> {
// QQ uses bit 0x80 as a flag on the PkgType=33 operation code. Clear only
// that bit: other high bits remain significant in the native handler. The
// normalized code 3 means an invitation; all other values mean approval.
// Do not use the nested `join_type`: that is an invitation-source enum.
const normalized = raw - (raw & 0x80);
return normalized === 3 ? 'invite' : 'approve';
// QQ uses bit 0x80 as a flag on the PkgType=33 operation code. Clear only
// that bit: other high bits remain significant in the native handler. The
// normalized code 3 means an invitation; all other values mean approval.
// Do not use the nested `join_type`: that is an invitation-source enum.
const normalized = raw - (raw & 0x80);
return normalized === 3 ? 'invite' : 'approve';
}
export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => {
const change = protobuf_decode<GroupChange>(ctx.content);
if (!change) return [];
const groupId = change.groupUin ?? 0;
const userUid = change.memberUid ?? '';
const operatorUid = decodeGroupChangeOperatorUid(
change.operatorBytes ?? new Uint8Array(0),
'group member increase',
);
const ev: GroupMemberJoin = {
kind: 'group_member_join',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
userUin: resolveUidToUin(ctx.identity, groupId, userUid),
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid),
userUid,
operatorUid,
joinType: joinTypeFromOperationType(change.decreaseType ?? 0),
};
return [ev];
const change = protobuf_decode<GroupChange>(ctx.content);
if (!change) {
return [];
}
const groupId = change.groupUin ?? 0;
const userUid = change.memberUid ?? '';
const operatorUid = decodeGroupChangeOperatorUid(
change.operatorBytes ?? new Uint8Array(0),
'group member increase',
);
const ev: GroupMemberJoin = {
kind: 'group_member_join',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
userUin: resolveUidToUin(ctx.identity, groupId, userUid),
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid),
userUid,
operatorUid,
joinType: joinTypeFromOperationType(change.decreaseType ?? 0),
};
return [ev];
};
// QQ's GroupChange.decreaseType (proto field 4) on a member-decrease push:
@@ -49,78 +49,89 @@ export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => {
// The kick → kick_me distinction (was it us?) is decided downstream in the
// OneBot converter via selfId; here we only resolve the protocol-level reason.
function leaveTypeFromDecreaseType(dt: number): GroupMemberLeave['leaveType'] {
switch (dt) {
case 129:
return 'disband';
case 0:
case 130:
return 'leave';
default:
return 'kick';
}
switch (dt) {
case 129:
return 'disband';
case 0:
case 130:
return 'leave';
default:
return 'kick';
}
}
export const decodeGroupMemberLeave: MsgPushDecoder = (ctx) => {
const change = protobuf_decode<GroupChange>(ctx.content);
if (!change) return [];
const dt = change.decreaseType ?? 0;
const groupId = change.groupUin ?? 0;
const userUid = change.memberUid ?? '';
const userUin = resolveUidToUin(ctx.identity, groupId, userUid);
const change = protobuf_decode<GroupChange>(ctx.content);
let operatorUid: string;
let operatorUin: number;
if (dt === 130) {
// A voluntary leave has no independent operator. QQ may place structured
// metadata in field 5, so it must not be decoded as a UID. OneBot models
// the leaving member as the operator for this event.
operatorUid = userUid;
operatorUin = userUin;
} else {
const operatorBytes = change.operatorBytes ?? new Uint8Array(0);
// Self-kick always uses OperatorInfo. Ordinary removals vary between a raw
// UTF-8 UID and the same envelope, so discriminate by its field-1 wire tag.
operatorUid = dt === 3
? decodeNestedOperatorUid(operatorBytes, 'group member decrease type=3')
: decodeGroupChangeOperatorUid(operatorBytes, `group member decrease type=${dt}`);
operatorUin = resolveUidToUin(ctx.identity, groupId, operatorUid);
}
const ev: GroupMemberLeave = {
kind: 'group_member_leave',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
userUin,
operatorUin,
userUid,
operatorUid,
leaveType: leaveTypeFromDecreaseType(dt),
};
return [ev];
if (!change) {
return [];
}
const dt = change.decreaseType ?? 0;
const groupId = change.groupUin ?? 0;
const userUid = change.memberUid ?? '';
const userUin = resolveUidToUin(ctx.identity, groupId, userUid);
let operatorUid: string;
let operatorUin: number;
if (dt === 130) {
// A voluntary leave has no independent operator. QQ may place structured
// metadata in field 5, so it must not be decoded as a UID. OneBot models
// the leaving member as the operator for this event.
operatorUid = userUid;
operatorUin = userUin;
} else {
const operatorBytes = change.operatorBytes ?? new Uint8Array(0);
// Self-kick always uses OperatorInfo. Ordinary removals vary between a raw
// UTF-8 UID and the same envelope, so discriminate by its field-1 wire tag.
operatorUid =
dt === 3
? decodeNestedOperatorUid(operatorBytes, 'group member decrease type=3')
: decodeGroupChangeOperatorUid(operatorBytes, `group member decrease type=${dt}`);
operatorUin = resolveUidToUin(ctx.identity, groupId, operatorUid);
}
const ev: GroupMemberLeave = {
kind: 'group_member_leave',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
userUin,
operatorUin,
userUid,
operatorUid,
leaveType: leaveTypeFromDecreaseType(dt),
};
return [ev];
};
export const decodeGroupSelfJoined: MsgPushDecoder = (ctx) => {
const joined = protobuf_decode<SelfJoinInGroup>(ctx.content);
if (!joined) return [];
// groupUin is uint_64 on the wire (bigint). Real group IDs fit in
// uint32 (≤ 10 digits in practice), so Number() conversion is safe
// — saturate to 0 on the unlikely overflow rather than letting
// BigInt propagate downstream where consumers expect a number.
const groupUinBig = joined.groupUin ?? 0n;
const groupId = groupUinBig > 0n && groupUinBig <= 0x7FFFFFFFn ? Number(groupUinBig) : 0;
const operatorUid = joined.operatorUid ?? '';
// We're the one joining — surface the bot's own identity as userUin
// so the existing converter's `notice.group_increase` shape works
// unchanged.
const ev: GroupMemberJoin = {
kind: 'group_member_join',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
userUin: ctx.selfUin,
userUid: ctx.identity.selfUid ?? '',
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid),
operatorUid,
};
return [ev];
const joined = protobuf_decode<SelfJoinInGroup>(ctx.content);
if (!joined) {
return [];
}
// groupUin is uint_64 on the wire (bigint). Real group IDs fit in
// uint32 (≤ 10 digits in practice), so Number() conversion is safe
// — saturate to 0 on the unlikely overflow rather than letting
// BigInt propagate downstream where consumers expect a number.
const groupUinBig = joined.groupUin ?? 0n;
const groupId = groupUinBig > 0n && groupUinBig <= 0x7fffffffn ? Number(groupUinBig) : 0;
const operatorUid = joined.operatorUid ?? '';
// We're the one joining — surface the bot's own identity as userUin
// so the existing converter's `notice.group_increase` shape works
// unchanged.
const ev: GroupMemberJoin = {
kind: 'group_member_join',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
groupId,
userUin: ctx.selfUin,
userUid: ctx.identity.selfUid ?? '',
operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid),
operatorUid,
};
return [ev];
};
@@ -3,50 +3,58 @@ import type { MsgPushDecoder } from '../registry';
import { decodeRichBody } from '../rich-body-decoder';
export const decodeGroupMessage: MsgPushDecoder = (ctx) => {
const ev: GroupMessage = {
kind: 'group_message',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
senderUin: ctx.fromUin,
msgSeq: ctx.head.sequence,
msgId: ctx.head.msgId & 0x7FFFFFFF,
elements: decodeRichBody(ctx.body, true),
groupId: 0,
groupName: '',
senderNick: '',
senderCard: '',
senderRole: '',
};
const grp = ctx.responseHead?.grp;
if (grp) {
ev.groupId = grp.groupUin ?? 0;
// Sender name priority (#201): the group-history fetch fills `memberName`
// (field 2); the local member cache gives a clean nickname/card split; and
// live pushes + merged-forward nodes carry the display name in `memberCard`
// (field 4). Prefer the explicit field-2 name, then the cache, then field 4
// — the last is what lets a forward node from a group the bot isn't in keep
// its per-node sender name without a member-list lookup.
ev.senderNick = grp.memberName ?? '';
}
const member = ctx.identity.findGroupMember(ev.groupId, ctx.fromUin);
if (member) {
if (!ev.senderNick) ev.senderNick = member.nickname;
ev.senderCard = member.card;
ev.senderRole = member.role;
// [#1] field 4 (memberCard) is the sender's CURRENT display name (group card
// if set, else base nickname). When it differs from the base nickname it's an
// up-to-date group card — fresher than the cache, which nothing refreshes on
// a card change (no push; a quiet group can freeze at warmup for months).
// Prefer it. (Self-healed back into the cache in packet-pipeline side effects.)
if (grp?.memberCard && grp.memberCard !== ev.senderNick) {
ev.senderCard = grp.memberCard;
const ev: GroupMessage = {
kind: 'group_message',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
senderUin: ctx.fromUin,
msgSeq: ctx.head.sequence,
msgId: ctx.head.msgId & 0x7fffffff,
elements: decodeRichBody(ctx.body, true),
groupId: 0,
groupName: '',
senderNick: '',
senderCard: '',
senderRole: '',
};
const grp = ctx.responseHead?.grp;
if (grp) {
ev.groupId = grp.groupUin ?? 0;
// Sender name priority (#201): the group-history fetch fills `memberName`
// (field 2); the local member cache gives a clean nickname/card split; and
// live pushes + merged-forward nodes carry the display name in `memberCard`
// (field 4). Prefer the explicit field-2 name, then the cache, then field 4
// — the last is what lets a forward node from a group the bot isn't in keep
// its per-node sender name without a member-list lookup.
ev.senderNick = grp.memberName ?? '';
}
} else if (!ev.senderNick && grp?.memberCard) {
ev.senderNick = grp.memberCard;
}
// Group name: prefer the message's own wire field (ResponseGrp field 7 —
// fresh even right after a rename), fall back to the cached group list, else
// leave it empty. `ev.groupId` is set above from grp.groupUin.
ev.groupName = grp?.groupName || ctx.identity.findGroup?.(ev.groupId)?.groupName || '';
return [ev];
const member = ctx.identity.findGroupMember(ev.groupId, ctx.fromUin);
if (member) {
if (!ev.senderNick) {
ev.senderNick = member.nickname;
}
ev.senderCard = member.card;
ev.senderRole = member.role;
// [#1] field 4 (memberCard) is the sender's CURRENT display name (group card
// if set, else base nickname). When it differs from the base nickname it's an
// up-to-date group card — fresher than the cache, which nothing refreshes on
// a card change (no push; a quiet group can freeze at warmup for months).
// Prefer it. (Self-healed back into the cache in packet-pipeline side effects.)
if (grp?.memberCard && grp.memberCard !== ev.senderNick) {
ev.senderCard = grp.memberCard;
}
} else if (!ev.senderNick && grp?.memberCard) {
ev.senderNick = grp.memberCard;
}
// Group name: prefer the message's own wire field (ResponseGrp field 7 —
// fresh even right after a rename), fall back to the cached group list, else
// leave it empty. `ev.groupId` is set above from grp.groupUin.
ev.groupName = grp?.groupName || ctx.identity.findGroup?.(ev.groupId)?.groupName || '';
return [ev];
};
@@ -3,31 +3,38 @@ import type { MsgPushDecoder } from '../registry';
import { decodeRichBody } from '../rich-body-decoder';
export const decodeTempMessage: MsgPushDecoder = (ctx) => {
const sequenceAuthoritative = ctx.head.ntMsgSeq > 0;
const ev: TempMessage = {
kind: 'temp_message',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
senderUin: ctx.fromUin,
msgSeq: ctx.head.sequence,
ntMsgSeq: ctx.head.ntMsgSeq,
clientSeq: ctx.head.sequence,
sequenceAuthoritative,
elements: decodeRichBody(ctx.body, false),
groupId: 0,
senderNick: '',
};
if (ctx.responseHead?.grp) {
ev.groupId = ctx.responseHead.grp.groupUin ?? 0;
ev.senderNick = ctx.responseHead.grp.memberName ?? '';
}
// A group temp session carries its source group in responseHead.forward.
if (ctx.responseHead?.forward?.tempGroupUin) {
ev.groupId = ctx.responseHead.forward.tempGroupUin;
}
if (!ev.senderNick) {
const friend = ctx.identity.findFriend(ctx.fromUin);
if (friend) ev.senderNick = friend.nickname;
}
return [ev];
const sequenceAuthoritative = ctx.head.ntMsgSeq > 0;
const ev: TempMessage = {
kind: 'temp_message',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
senderUin: ctx.fromUin,
msgSeq: ctx.head.sequence,
ntMsgSeq: ctx.head.ntMsgSeq,
clientSeq: ctx.head.sequence,
sequenceAuthoritative,
elements: decodeRichBody(ctx.body, false),
groupId: 0,
senderNick: '',
};
if (ctx.responseHead?.grp) {
ev.groupId = ctx.responseHead.grp.groupUin ?? 0;
ev.senderNick = ctx.responseHead.grp.memberName ?? '';
}
// A group temp session carries its source group in responseHead.forward.
if (ctx.responseHead?.forward?.tempGroupUin) {
ev.groupId = ctx.responseHead.forward.tempGroupUin;
}
if (!ev.senderNick) {
const friend = ctx.identity.findFriend(ctx.fromUin);
if (friend) {
ev.senderNick = friend.nickname;
}
}
return [ev];
};
+133 -133
View File
@@ -1,141 +1,141 @@
export enum PkgType {
ForwardFakePrivateMessage = 9,
PrivateMessage = 166,
GroupMessage = 82,
TempMessage = 141,
Event0x210 = 528,
Event0x2DC = 732,
PrivateRecordMessage = 208,
PrivateFileMessage = 529,
GroupRequestInvitationNotice = 525,
GroupRequestJoinNotice = 84,
/**
* Self-join admittance — fires on the bot's session right after an
* admin approves its `set_group_add_request` or an invite-accept
* goes through. Ported from `lagrange-python`'s
* `server_push/msg.py:108 case 85`. Maps to OneBot11
* `notice.group_increase` with the bot itself as `user_id` —
* existing 33 (GroupMemberIncreaseNotice) doesn't fire for the
* bot's own join, so without this case the bot never knows it
* just entered a group until the first message arrives.
*/
GroupSelfJoinedNotice = 85,
GroupInviteNotice = 87,
GroupAdminChangedNotice = 44,
GroupMemberIncreaseNotice = 33,
GroupMemberDecreaseNotice = 34,
ForwardFakePrivateMessage = 9,
PrivateMessage = 166,
GroupMessage = 82,
TempMessage = 141,
Event0x210 = 528,
Event0x2DC = 732,
PrivateRecordMessage = 208,
PrivateFileMessage = 529,
GroupRequestInvitationNotice = 525,
GroupRequestJoinNotice = 84,
/**
* Self-join admittance — fires on the bot's session right after an
* admin approves its `set_group_add_request` or an invite-accept
* goes through. Ported from `lagrange-python`'s
* `server_push/msg.py:108 case 85`. Maps to OneBot11
* `notice.group_increase` with the bot itself as `user_id` —
* existing 33 (GroupMemberIncreaseNotice) doesn't fire for the
* bot's own join, so without this case the bot never knows it
* just entered a group until the first message arrives.
*/
GroupSelfJoinedNotice = 85,
GroupInviteNotice = 87,
GroupAdminChangedNotice = 44,
GroupMemberIncreaseNotice = 33,
GroupMemberDecreaseNotice = 34,
}
export enum Event0x2DCSubType {
GroupMuteNotice = 12,
GroupMsgEmojiLikeNotice = 16,
GroupRecallNotice = 17,
GroupGreyTipNotice = 20,
GroupEssenceNotice = 21,
GroupMuteNotice = 12,
GroupMsgEmojiLikeNotice = 16,
GroupRecallNotice = 17,
GroupGreyTipNotice = 20,
GroupEssenceNotice = 21,
}
export enum Event0x210SubType {
FriendRequestNotice = 35,
/**
* Voice-to-text (语音转文字) async result push, fired after a
* `pttTrans.Trans{C2C,Group}PttReq` once the server finishes transcribing.
* Live-verified body: `{ f1:uint, f2:{ f1=msgId, f8=text, ... } }`. There's
* no static sys_msg_0x210_0x3d handler — the ptt-trans subsystem registers
* it dynamically; we decode it into an internal `ptt_trans_result` event.
*/
PttTransResult = 61,
/**
* Outgoing friend-message recall — bot recalled its own message that
* was sent to a friend. Same `FriendRecall` wire shape as 138; the
* difference is direction (138 = friend recalled their own message
* sent to bot, 139 = bot recalled own message sent to friend).
* Cross-referenced against Lagrange V2 (`FriendRecallMessageProcessor`
* registered for both 138 and 139) + acidify (`138, 139 ->
* parseFriendRecall`). The decoder uses the subType to figure out
* which UID side ends up as `userUin` on the emitted event.
*/
FriendRecallSelfNotice = 139,
FriendRecallNotice = 138,
FriendPokeNotice = 290,
/**
* Mutual-accept friend notice — 179 fires when bot sent a friend
* request and the other side accepted; 226 fires for the opposite
* direction. Both decode through the same `NewFriend` wire shape
* (LagrangeGo registers them via a `case 226: case 179:` fallthrough
* in `client/listener.go:248-258`). Maps to OneBot11
* `notice.friend_add`.
*/
NewFriendNotice = 179,
NewFriendNoticeAlt = 226,
/**
* Multiplexed subType (Lagrange calls it FriendDeleteOrPinChanged=39). One of
* its variants is the profile-like ("名片赞") push: body.msgContent decodes as
* `ProfileLikeTip` and is a like only when inner msgType==0 && subType==203.
* NapCat routes 528/39 → parseLikeEvent (`api/msg.ts:1547`); other 39 variants
* (multi-device sync etc.) fall through.
*/
ProfileLikeNotice = 39,
/**
* C2C input-status notify — the "对方正在输入…" push. subMsgType 0x115 (277).
* RE-confirmed against `wrapper.linux.node`
* `aio_input_state_worker.cc::IsInputStateNotifySysMsg`, which matches exactly
* `(msg_type ^ 0x210) | (sub_msg_type ^ 0x115) == 0`. The payload
* (`InputStatusNotify`) rides in `body.msgContent`. Mirrors NapCat's
* `onInputStatusPush`.
*/
InputStatusNotice = 277,
/**
* QQ NT online-device cache update. The payload is a snapshot with repeated
* device entries; the kernel's getOnLineDev call only replays this cache and
* does not issue a separate network request.
*/
OnlineDevicesNotice = 349,
/** Server-authoritative friend/stranger remark synchronization push. */
FriendRemarkChangedNotice = 364,
/**
* Group-app state push (troop shortcut bar / discussion app).
*
* Sourced from the decompiled stock QQ Android client decoder at
* `com.tencent.imcore.message.ext.codec.decoder.msgType0x210.SubType0x26`
* (tsuzcx/qq_apk @ afe46ef). The payload is `submsgtype0x26.MsgBody`
* dispatching on `uint32_sub_cmd`:
*
* - 0x1 → `UpdateAppUnreadNum`: a list of
* `{group_code, app_id, unread_num}` entries the QQ client uses
* to keep group-internal "mini-app" badges (e.g. `appId=101846662`
* / `101896870` for the shortcut bar) in sync.
* - 0x3 → `UpdateDiscussAppInfo`: `{conf_uin, app_tip_notify.text}`
* for discussion-group app tips, routed to `getGAudioHandler()`.
* - 0x4 → delegated to the troop online-push handler.
*
* None of these have a OneBot event mapping — they're QQ-client-UI
* state pushes (unread badges, in-app tips), not user-visible
* conversation events. Acknowledge the subType so it doesn't keep
* showing up as "unknown" in debug logs and drop it silently.
* Lagrange V2 / lagrange-python / LagrangeGo / acidify all also
* fall through on this one because they don't surface the shortcut
* bar either.
*/
GroupAppStatePush = 38,
/**
* Unmapped QQ-NT-internal subType — first seen as a recurring
* "Event0x210 unknown subType=380" debug log in production captures.
*
* The tsuzcx/qq_apk decompile of the legacy QQ Android client only
* enumerates SubType0x26 (38) through SubType0x146 (326) under
* `com.tencent.imcore.message.ext.codec.decoder.msgType0x210/` —
* `SubType0x17c.java` (380) literally doesn't exist in that tree, so
* 380 is a QQ-NT-era addition rather than a missed legacy subType.
*
* The NT-era reference clients also don't handle it: Lagrange.Core
* (`PushMessageService.cs`), LagrangeGo (`client/listener.go`),
* lagrange-python (`server_push/msg.py`), and mania (`push_msg.rs`)
* each enumerate explicit 0x210 subtypes and none include 380 / 0x17C.
*
* Most likely a QQ-NT-client-UI state push (similar to 38) that
* doesn't map to any OneBot event. Acknowledge silently to keep the
* unknown log clean; if a real OneBot event ends up depending on it,
* revisit with whichever NT-era project finally maps the schema.
*/
UnmappedClientState380 = 380,
FriendRequestNotice = 35,
/**
* Voice-to-text (语音转文字) async result push, fired after a
* `pttTrans.Trans{C2C,Group}PttReq` once the server finishes transcribing.
* Live-verified body: `{ f1:uint, f2:{ f1=msgId, f8=text, ... } }`. There's
* no static sys_msg_0x210_0x3d handler — the ptt-trans subsystem registers
* it dynamically; we decode it into an internal `ptt_trans_result` event.
*/
PttTransResult = 61,
/**
* Outgoing friend-message recall — bot recalled its own message that
* was sent to a friend. Same `FriendRecall` wire shape as 138; the
* difference is direction (138 = friend recalled their own message
* sent to bot, 139 = bot recalled own message sent to friend).
* Cross-referenced against Lagrange V2 (`FriendRecallMessageProcessor`
* registered for both 138 and 139) + acidify (`138, 139 ->
* parseFriendRecall`). The decoder uses the subType to figure out
* which UID side ends up as `userUin` on the emitted event.
*/
FriendRecallSelfNotice = 139,
FriendRecallNotice = 138,
FriendPokeNotice = 290,
/**
* Mutual-accept friend notice — 179 fires when bot sent a friend
* request and the other side accepted; 226 fires for the opposite
* direction. Both decode through the same `NewFriend` wire shape
* (LagrangeGo registers them via a `case 226: case 179:` fallthrough
* in `client/listener.go:248-258`). Maps to OneBot11
* `notice.friend_add`.
*/
NewFriendNotice = 179,
NewFriendNoticeAlt = 226,
/**
* Multiplexed subType (Lagrange calls it FriendDeleteOrPinChanged=39). One of
* its variants is the profile-like ("名片赞") push: body.msgContent decodes as
* `ProfileLikeTip` and is a like only when inner msgType==0 && subType==203.
* NapCat routes 528/39 → parseLikeEvent (`api/msg.ts:1547`); other 39 variants
* (multi-device sync etc.) fall through.
*/
ProfileLikeNotice = 39,
/**
* C2C input-status notify — the "对方正在输入…" push. subMsgType 0x115 (277).
* RE-confirmed against `wrapper.linux.node`
* `aio_input_state_worker.cc::IsInputStateNotifySysMsg`, which matches exactly
* `(msg_type ^ 0x210) | (sub_msg_type ^ 0x115) == 0`. The payload
* (`InputStatusNotify`) rides in `body.msgContent`. Mirrors NapCat's
* `onInputStatusPush`.
*/
InputStatusNotice = 277,
/**
* QQ NT online-device cache update. The payload is a snapshot with repeated
* device entries; the kernel's getOnLineDev call only replays this cache and
* does not issue a separate network request.
*/
OnlineDevicesNotice = 349,
/** Server-authoritative friend/stranger remark synchronization push. */
FriendRemarkChangedNotice = 364,
/**
* Group-app state push (troop shortcut bar / discussion app).
*
* Sourced from the decompiled stock QQ Android client decoder at
* `com.tencent.imcore.message.ext.codec.decoder.msgType0x210.SubType0x26`
* (tsuzcx/qq_apk @ afe46ef). The payload is `submsgtype0x26.MsgBody`
* dispatching on `uint32_sub_cmd`:
*
* - 0x1 → `UpdateAppUnreadNum`: a list of
* `{group_code, app_id, unread_num}` entries the QQ client uses
* to keep group-internal "mini-app" badges (e.g. `appId=101846662`
* / `101896870` for the shortcut bar) in sync.
* - 0x3 → `UpdateDiscussAppInfo`: `{conf_uin, app_tip_notify.text}`
* for discussion-group app tips, routed to `getGAudioHandler()`.
* - 0x4 → delegated to the troop online-push handler.
*
* None of these have a OneBot event mapping — they're QQ-client-UI
* state pushes (unread badges, in-app tips), not user-visible
* conversation events. Acknowledge the subType so it doesn't keep
* showing up as "unknown" in debug logs and drop it silently.
* Lagrange V2 / lagrange-python / LagrangeGo / acidify all also
* fall through on this one because they don't surface the shortcut
* bar either.
*/
GroupAppStatePush = 38,
/**
* Unmapped QQ-NT-internal subType — first seen as a recurring
* "Event0x210 unknown subType=380" debug log in production captures.
*
* The tsuzcx/qq_apk decompile of the legacy QQ Android client only
* enumerates SubType0x26 (38) through SubType0x146 (326) under
* `com.tencent.imcore.message.ext.codec.decoder.msgType0x210/` —
* `SubType0x17c.java` (380) literally doesn't exist in that tree, so
* 380 is a QQ-NT-era addition rather than a missed legacy subType.
*
* The NT-era reference clients also don't handle it: Lagrange.Core
* (`PushMessageService.cs`), LagrangeGo (`client/listener.go`),
* lagrange-python (`server_push/msg.py`), and mania (`push_msg.rs`)
* each enumerate explicit 0x210 subtypes and none include 380 / 0x17C.
*
* Most likely a QQ-NT-client-UI state push (similar to 38) that
* doesn't map to any OneBot event. Acknowledge silently to keep the
* unknown log clean; if a real OneBot event ends up depending on it,
* revisit with whichever NT-era project finally maps the schema.
*/
UnmappedClientState380 = 380,
}
@@ -2,10 +2,10 @@ import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { createLogger } from '@snowluma/common/logger';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type {
SsoGetC2cMsg,
SsoGetC2cMsgResponse,
SsoGetRoamMsg,
SsoGetRoamMsgResponse,
SsoGetC2cMsg,
SsoGetC2cMsgResponse,
SsoGetRoamMsg,
SsoGetRoamMsgResponse,
} from '@snowluma/proto-defs/get-c2c-msg';
import type { PushMsgBody } from '@snowluma/proto-defs/message';
import type { QQEventVariant } from '../events';
@@ -23,40 +23,58 @@ const log = createLogger('MsgPush.C2CHistory');
type FriendMessage = Extract<QQEventVariant, { kind: 'friend_message' }>;
interface RawSender {
sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise<SendPacketResult>;
sendRawPacket(
serviceCmd: string,
body: Uint8Array,
timeoutMs?: number,
): Promise<SendPacketResult>;
}
export interface C2cRoamPage {
messages: FriendMessage[];
cursor: { time: number; random: number };
messages: FriendMessage[];
cursor: { time: number; random: number };
}
function decodeC2cMessages(
messages: readonly PushMsgBody[],
identity: IdentityService,
selfUin: number,
source: string,
messages: readonly PushMsgBody[],
identity: IdentityService,
selfUin: number,
source: string,
): FriendMessage[] {
const out: FriendMessage[] = [];
for (const msg of messages) {
const ctx = buildContextFromMessage(msg, selfUin, identity);
if (!ctx) {
throw new Error(`${source} response contains a message without a content head`);
const out: FriendMessage[] = [];
for (const msg of messages) {
const ctx = buildContextFromMessage(msg, selfUin, identity);
if (!ctx) {
throw new Error(`${source} response contains a message without a content head`);
}
if (isC2cControlPush(ctx.head)) {
continue;
}
for (const ev of decodeFriendMessage(ctx)) {
if (ev.kind !== 'friend_message') {
continue;
}
if (!keepDecodedMessage(ctx.head, ev.elements, ctx.body, ev.kind, ctx.fromUin)) {
continue;
}
if (ev.sequenceAuthoritative === false || !ev.ntMsgSeq || ev.ntMsgSeq <= 0) {
throw new Error(
`${source} message is missing the canonical NT sequence ` +
`(clientSeq=${ev.clientSeq ?? ev.msgSeq} from=${ev.senderUin} time=${ev.time})`,
);
}
out.push(ev);
}
}
if (isC2cControlPush(ctx.head)) continue;
for (const ev of decodeFriendMessage(ctx)) {
if (ev.kind !== 'friend_message') continue;
if (!keepDecodedMessage(ctx.head, ev.elements, ctx.body, ev.kind, ctx.fromUin)) continue;
if (ev.sequenceAuthoritative === false || !ev.ntMsgSeq || ev.ntMsgSeq <= 0) {
throw new Error(
`${source} message is missing the canonical NT sequence `
+ `(clientSeq=${ev.clientSeq ?? ev.msgSeq} from=${ev.senderUin} time=${ev.time})`,
);
}
out.push(ev);
}
}
return out;
return out;
}
/**
@@ -67,40 +85,44 @@ function decodeC2cMessages(
* owns chunking/throttling.
*/
export async function fetchC2cMessageRange(
sender: RawSender,
identity: IdentityService,
selfUin: number,
friendUid: string,
startSeq: number,
endSeq: number,
sender: RawSender,
identity: IdentityService,
selfUin: number,
friendUid: string,
startSeq: number,
endSeq: number,
): Promise<FriendMessage[]> {
if (!friendUid || !(endSeq > 0) || startSeq > endSeq) return [];
if (!friendUid || !(endSeq > 0) || startSeq > endSeq) {
return [];
}
const req = protobuf_encode<SsoGetC2cMsg>({
friendUid,
startSequence: startSeq,
endSequence: endSeq,
});
const req = protobuf_encode<SsoGetC2cMsg>({
friendUid,
startSequence: startSeq,
endSequence: endSeq,
});
const res = await sender.sendRawPacket(SSO_GET_C2C_MSG_CMD, req);
const decoded = protobuf_decode<SsoGetC2cMsgResponse>(
requirePacketResponse(res, 'SsoGetC2cMsg'),
);
if (decoded.friendUid && decoded.friendUid !== friendUid) {
throw new Error(`SsoGetC2cMsg response friend uid mismatch: ${decoded.friendUid}`);
}
const messages = decoded?.messages ?? [];
const out = decodeC2cMessages(messages, identity, selfUin, 'SsoGetC2cMsg');
out.sort((a, b) => (a.ntMsgSeq ?? 0) - (b.ntMsgSeq ?? 0));
log.debug(
'SsoGetC2cMsg decoded friend=%s range=%d-%d wire=%d usable=%d',
friendUid,
startSeq,
endSeq,
messages.length,
out.length,
);
return out;
const res = await sender.sendRawPacket(SSO_GET_C2C_MSG_CMD, req);
const decoded = protobuf_decode<SsoGetC2cMsgResponse>(
requirePacketResponse(res, 'SsoGetC2cMsg'),
);
if (decoded.friendUid && decoded.friendUid !== friendUid) {
throw new Error(`SsoGetC2cMsg response friend uid mismatch: ${decoded.friendUid}`);
}
const messages = decoded?.messages ?? [];
const out = decodeC2cMessages(messages, identity, selfUin, 'SsoGetC2cMsg');
out.sort((a, b) => (a.ntMsgSeq ?? 0) - (b.ntMsgSeq ?? 0));
log.debug(
'SsoGetC2cMsg decoded friend=%s range=%d-%d wire=%d usable=%d',
friendUid,
startSeq,
endSeq,
messages.length,
out.length,
);
return out;
}
/**
@@ -108,54 +130,60 @@ export async function fetchC2cMessageRange(
* for an unanchored latest page; it returns messages from both participants.
*/
export async function fetchC2cRoamMessagePage(
sender: RawSender,
identity: IdentityService,
selfUin: number,
friendUid: string,
beforeTime: number,
count: number,
beforeRandom = 0,
sender: RawSender,
identity: IdentityService,
selfUin: number,
friendUid: string,
beforeTime: number,
count: number,
beforeRandom = 0,
): Promise<C2cRoamPage> {
if (!friendUid) throw new Error('SsoGetRoamMsg friend uid is required');
if (!Number.isSafeInteger(beforeTime) || beforeTime < 0 || beforeTime > 0xffff_ffff) {
throw new Error(`SsoGetRoamMsg cursor time is invalid: ${String(beforeTime)}`);
}
if (!Number.isSafeInteger(beforeRandom) || beforeRandom < 0 || beforeRandom > 0xffff_ffff) {
throw new Error(`SsoGetRoamMsg cursor random is invalid: ${String(beforeRandom)}`);
}
if (!Number.isSafeInteger(count) || count < 1 || count > 200) {
throw new Error(`SsoGetRoamMsg count is invalid: ${String(count)}`);
}
if (!friendUid) {
throw new Error('SsoGetRoamMsg friend uid is required');
}
const req = protobuf_encode<SsoGetRoamMsg>({
friendUid,
time: beforeTime,
random: beforeRandom,
count,
direction: true,
});
const result = await sender.sendRawPacket(SSO_GET_ROAM_MSG_CMD, req);
const response = protobuf_decode<SsoGetRoamMsgResponse>(
requirePacketResponse(result, 'SsoGetRoamMsg'),
);
if (response.friendUid && response.friendUid !== friendUid) {
throw new Error(`SsoGetRoamMsg response friend uid mismatch: ${response.friendUid}`);
}
if (!Number.isSafeInteger(beforeTime) || beforeTime < 0 || beforeTime > 0xffff_ffff) {
throw new Error(`SsoGetRoamMsg cursor time is invalid: ${String(beforeTime)}`);
}
const wireMessages = response.messages ?? [];
const messages = decodeC2cMessages(wireMessages, identity, selfUin, 'SsoGetRoamMsg');
messages.sort((a, b) => (a.ntMsgSeq ?? 0) - (b.ntMsgSeq ?? 0) || a.time - b.time);
const cursor = { time: response.timestamp ?? 0, random: response.random ?? 0 };
log.debug(
'SsoGetRoamMsg decoded friend=%s before=%d/%d count=%d wire=%d usable=%d next=%d/%d',
friendUid,
beforeTime,
beforeRandom,
count,
wireMessages.length,
messages.length,
cursor.time,
cursor.random,
);
return { messages, cursor };
if (!Number.isSafeInteger(beforeRandom) || beforeRandom < 0 || beforeRandom > 0xffff_ffff) {
throw new Error(`SsoGetRoamMsg cursor random is invalid: ${String(beforeRandom)}`);
}
if (!Number.isSafeInteger(count) || count < 1 || count > 200) {
throw new Error(`SsoGetRoamMsg count is invalid: ${String(count)}`);
}
const req = protobuf_encode<SsoGetRoamMsg>({
friendUid,
time: beforeTime,
random: beforeRandom,
count,
direction: true,
});
const result = await sender.sendRawPacket(SSO_GET_ROAM_MSG_CMD, req);
const response = protobuf_decode<SsoGetRoamMsgResponse>(
requirePacketResponse(result, 'SsoGetRoamMsg'),
);
if (response.friendUid && response.friendUid !== friendUid) {
throw new Error(`SsoGetRoamMsg response friend uid mismatch: ${response.friendUid}`);
}
const wireMessages = response.messages ?? [];
const messages = decodeC2cMessages(wireMessages, identity, selfUin, 'SsoGetRoamMsg');
messages.sort((a, b) => (a.ntMsgSeq ?? 0) - (b.ntMsgSeq ?? 0) || a.time - b.time);
const cursor = { time: response.timestamp ?? 0, random: response.random ?? 0 };
log.debug(
'SsoGetRoamMsg decoded friend=%s before=%d/%d count=%d wire=%d usable=%d next=%d/%d',
friendUid,
beforeTime,
beforeRandom,
count,
wireMessages.length,
messages.length,
cursor.time,
cursor.random,
);
return { messages, cursor };
}
@@ -16,7 +16,11 @@ type GroupMessage = Extract<QQEventVariant, { kind: 'group_message' }>;
const log = createLogger('MsgPush.GroupHistory');
interface RawSender {
sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise<SendPacketResult>;
sendRawPacket(
serviceCmd: string,
body: Uint8Array,
timeoutMs?: number,
): Promise<SendPacketResult>;
}
/**
@@ -28,75 +32,88 @@ interface RawSender {
* chunking/throttling so the server's frequency limits aren't tripped.
*/
export async function fetchGroupMessageRange(
sender: RawSender,
identity: IdentityService,
selfUin: number,
groupUin: number,
startSeq: number,
endSeq: number,
sender: RawSender,
identity: IdentityService,
selfUin: number,
groupUin: number,
startSeq: number,
endSeq: number,
): Promise<GroupMessage[]> {
if (!(groupUin > 0) || !(endSeq > 0) || startSeq > endSeq) return [];
const req = protobuf_encode<SsoGetGroupMsg>({
info: { groupUin, startSequence: startSeq, endSequence: endSeq },
direction: true,
});
const res = await sender.sendRawPacket(SSO_GET_GROUP_MSG_CMD, req);
const decoded = protobuf_decode<SsoGetGroupMsgResponse>(
requirePacketResponse(res, 'SsoGetGroupMsg'),
);
const messages = decoded?.body?.messages ?? [];
const out: GroupMessage[] = [];
for (let index = 0; index < messages.length; index += 1) {
const msg = messages[index];
const ctx = buildContextFromMessage(msg, selfUin, identity);
if (!ctx) {
throw new Error(
`SsoGetGroupMsg response message ${index} has no content head `
+ `(group=${groupUin} range=${startSeq}-${endSeq})`,
);
if (!(groupUin > 0) || !(endSeq > 0) || startSeq > endSeq) {
return [];
}
// QQ NT turns deleted/body-null roam entries into MsgType::kNull and its
// FilterBlankSeqsMsg pass removes them before exposing history to callers.
// SsoGetGroupMsg still carries a localized placeholder body for some of
// those entries (for example "[已删除]"), so the ordinary content-less
// filter below cannot recognize them. On the wire these null records have
// neither a sender nor a timestamp; require both structural absences rather
// than matching localized text so a real message is never language-filtered.
if (ctx.fromUin <= 0 && ctx.head.timestamp <= 0) {
log.debug(
'dropping QQ null roam record: group=%d seq=%d msgId=%d',
groupUin,
ctx.head.sequence,
ctx.head.msgId,
);
continue;
const req = protobuf_encode<SsoGetGroupMsg>({
info: { groupUin, startSequence: startSeq, endSequence: endSeq },
direction: true,
});
const res = await sender.sendRawPacket(SSO_GET_GROUP_MSG_CMD, req);
const decoded = protobuf_decode<SsoGetGroupMsgResponse>(
requirePacketResponse(res, 'SsoGetGroupMsg'),
);
const messages = decoded?.body?.messages ?? [];
const out: GroupMessage[] = [];
for (let index = 0; index < messages.length; index += 1) {
const msg = messages[index];
const ctx = buildContextFromMessage(msg, selfUin, identity);
if (!ctx) {
throw new Error(
`SsoGetGroupMsg response message ${index} has no content head ` +
`(group=${groupUin} range=${startSeq}-${endSeq})`,
);
}
// QQ NT turns deleted/body-null roam entries into MsgType::kNull and its
// FilterBlankSeqsMsg pass removes them before exposing history to callers.
// SsoGetGroupMsg still carries a localized placeholder body for some of
// those entries (for example "[已删除]"), so the ordinary content-less
// filter below cannot recognize them. On the wire these null records have
// neither a sender nor a timestamp; require both structural absences rather
// than matching localized text so a real message is never language-filtered.
if (ctx.fromUin <= 0 && ctx.head.timestamp <= 0) {
log.debug(
'dropping QQ null roam record: group=%d seq=%d msgId=%d',
groupUin,
ctx.head.sequence,
ctx.head.msgId,
);
continue;
}
for (const ev of decodeGroupMessage(ctx)) {
if (ev.kind !== 'group_message') {
throw new Error(
`SsoGetGroupMsg response message ${index} decoded as ${ev.kind} ` +
`(group=${groupUin} range=${startSeq}-${endSeq})`,
);
}
if (!Number.isSafeInteger(ev.msgSeq) || ev.msgSeq <= 0) {
throw new Error(
`SsoGetGroupMsg response message ${index} has invalid sequence ${String(ev.msgSeq)} ` +
`(group=${groupUin} range=${startSeq}-${endSeq})`,
);
}
if (ev.groupId !== groupUin) {
throw new Error(
`SsoGetGroupMsg response message ${index} belongs to group ${ev.groupId} ` +
`(expected=${groupUin} range=${startSeq}-${endSeq})`,
);
}
if (!keepDecodedMessage(ctx.head, ev.elements, ctx.body, ev.kind, ctx.fromUin)) {
continue;
}
out.push(ev);
}
}
for (const ev of decodeGroupMessage(ctx)) {
if (ev.kind !== 'group_message') {
throw new Error(
`SsoGetGroupMsg response message ${index} decoded as ${ev.kind} `
+ `(group=${groupUin} range=${startSeq}-${endSeq})`,
);
}
if (!Number.isSafeInteger(ev.msgSeq) || ev.msgSeq <= 0) {
throw new Error(
`SsoGetGroupMsg response message ${index} has invalid sequence ${String(ev.msgSeq)} `
+ `(group=${groupUin} range=${startSeq}-${endSeq})`,
);
}
if (ev.groupId !== groupUin) {
throw new Error(
`SsoGetGroupMsg response message ${index} belongs to group ${ev.groupId} `
+ `(expected=${groupUin} range=${startSeq}-${endSeq})`,
);
}
if (!keepDecodedMessage(ctx.head, ev.elements, ctx.body, ev.kind, ctx.fromUin)) continue;
out.push(ev);
}
}
out.sort((a, b) => a.msgSeq - b.msgSeq);
return out;
out.sort((a, b) => a.msgSeq - b.msgSeq);
return out;
}
+207 -121
View File
@@ -8,89 +8,125 @@ export const MAX_RICH_CARD_OUTPUT_BYTES = 4 * 1024 * 1024;
export const MAX_RICH_CARD_MESSAGE_OUTPUT_BYTES = 8 * 1024 * 1024;
export type DecompressDataResult =
| { ok: true; text: string; outputBytes: number }
| { ok: false; reason: string };
{ ok: true; text: string; outputBytes: number } | { ok: false; reason: string };
export function makeImageUrl(origUrl: string): string {
if (!origUrl) return '';
if (/^https?:\/\//i.test(origUrl)) return origUrl;
// Compatibility faces sometimes carry a query fragment without a path.
// Prefixing the host onto that produces an unusable URL.
if (!origUrl.startsWith('/')) return '';
if (origUrl.includes('rkey') || origUrl.includes('fileid')) {
return 'https://multimedia.nt.qq.com.cn' + origUrl;
}
return 'http://gchat.qpic.cn' + origUrl;
if (!origUrl) {
return '';
}
if (/^https?:\/\//i.test(origUrl)) {
return origUrl;
}
// Compatibility faces sometimes carry a query fragment without a path.
// Prefixing the host onto that produces an unusable URL.
if (!origUrl.startsWith('/')) {
return '';
}
if (origUrl.includes('rkey') || origUrl.includes('fileid')) {
return 'https://multimedia.nt.qq.com.cn' + origUrl;
}
return 'http://gchat.qpic.cn' + origUrl;
}
/** Classic group-pic URL used when the wire carries an MD5 and no download path. */
export function imageUrlFromMd5(md5Hex: string): string {
if (!/^[0-9a-fA-F]{32}$/.test(md5Hex)) return '';
return `http://gchat.qpic.cn/gchatpic_new/0/0-0-${md5Hex.toUpperCase()}/0`;
if (!/^[0-9a-fA-F]{32}$/.test(md5Hex)) {
return '';
}
return `http://gchat.qpic.cn/gchatpic_new/0/0-0-${md5Hex.toUpperCase()}/0`;
}
/** NT multimedia download URL reconstructed from a file id when the path is omitted. */
export function ntImageUrlFromFileId(fileId: string, isGroup: boolean): string {
if (!fileId) return '';
const appid = isGroup ? 1407 : 1406;
return `https://multimedia.nt.qq.com.cn/download?appid=${appid}&fileid=${encodeURIComponent(fileId)}`;
if (!fileId) {
return '';
}
const appid = isGroup ? 1407 : 1406;
return `https://multimedia.nt.qq.com.cn/download?appid=${appid}&fileid=${encodeURIComponent(fileId)}`;
}
export function decompressData(
data: Uint8Array,
maxOutputBytes = MAX_RICH_CARD_OUTPUT_BYTES,
data: Uint8Array,
maxOutputBytes = MAX_RICH_CARD_OUTPUT_BYTES,
): DecompressDataResult {
if (!data || data.length === 0) return { ok: false, reason: 'empty_payload' };
if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes <= 0) {
throw new Error(`invalid decompression output limit: ${maxOutputBytes}`);
}
if ((data[0] === 0x00 || data[0] === 0x01) && data.length === 1) {
return { ok: false, reason: 'marker_without_payload' };
}
if (data[0] === 0x01) {
try {
const inflated = inflateSync(Buffer.from(data.subarray(1)), {
maxOutputLength: maxOutputBytes,
});
return inflated.length > 0
? { ok: true, text: inflated.toString('utf8'), outputBytes: inflated.length }
: { ok: false, reason: 'empty_output' };
} catch (error) {
const code = typeof error === 'object' && error !== null && 'code' in error
? String(error.code)
: '';
return {
ok: false,
reason: code === 'ERR_BUFFER_TOO_LARGE'
? 'output_limit_exceeded'
: code
? `inflate_failed:${code}`
: 'inflate_failed',
};
if (!data || data.length === 0) {
return { ok: false, reason: 'empty_payload' };
}
}
if (data[0] === 0x00) {
if (data.length - 1 > maxOutputBytes) return { ok: false, reason: 'output_limit_exceeded' };
return {
ok: true,
text: Buffer.from(data.subarray(1)).toString('utf8'),
outputBytes: data.length - 1,
};
}
if (data.length > maxOutputBytes) return { ok: false, reason: 'output_limit_exceeded' };
return { ok: true, text: Buffer.from(data).toString('utf8'), outputBytes: data.length };
if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes <= 0) {
throw new Error(`invalid decompression output limit: ${maxOutputBytes}`);
}
if ((data[0] === 0x00 || data[0] === 0x01) && data.length === 1) {
return { ok: false, reason: 'marker_without_payload' };
}
if (data[0] === 0x01) {
try {
const inflated = inflateSync(Buffer.from(data.subarray(1)), {
maxOutputLength: maxOutputBytes,
});
return inflated.length > 0
? { ok: true, text: inflated.toString('utf8'), outputBytes: inflated.length }
: { ok: false, reason: 'empty_output' };
} catch (error) {
const code =
typeof error === 'object' && error !== null && 'code' in error
? String(error.code)
: '';
return {
ok: false,
reason:
code === 'ERR_BUFFER_TOO_LARGE'
? 'output_limit_exceeded'
: code
? `inflate_failed:${code}`
: 'inflate_failed',
};
}
}
if (data[0] === 0x00) {
if (data.length - 1 > maxOutputBytes) {
return { ok: false, reason: 'output_limit_exceeded' };
}
return {
ok: true,
text: Buffer.from(data.subarray(1)).toString('utf8'),
outputBytes: data.length - 1,
};
}
if (data.length > maxOutputBytes) {
return { ok: false, reason: 'output_limit_exceeded' };
}
return { ok: true, text: Buffer.from(data).toString('utf8'), outputBytes: data.length };
}
export function parseU64OrZero(value: string): number {
if (!value) return 0;
const n = parseInt(value, 10);
return isNaN(n) ? 0 : n;
if (!value) {
return 0;
}
const n = parseInt(value, 10);
return isNaN(n) ? 0 : n;
}
/** Sync Identity lookup. Miss is unresolved (0). Decoder must not invent a UIN. */
export function resolveUidToUin(identity: IdentityService, groupId: number, uid: string): number {
if (!uid) return 0;
return identity.findUinByUid(uid, groupId || undefined) ?? 0;
if (!uid) {
return 0;
}
return identity.findUinByUid(uid, groupId || undefined) ?? 0;
}
/**
@@ -99,94 +135,144 @@ export function resolveUidToUin(identity: IdentityService, groupId: number, uid:
* to a different UID.
*/
export function c2cRoutingUin(identity: IdentityService, uid: string, wireUin: number): number {
const resolved = resolveUidToUin(identity, 0, uid);
if (resolved > 0) return resolved;
return wireUin > 0 ? wireUin : 0;
const resolved = resolveUidToUin(identity, 0, uid);
if (resolved > 0) {
return resolved;
}
return wireUin > 0 ? wireUin : 0;
}
const OPERATOR_BYTES_PREVIEW_LENGTH = 32;
function describeOperatorBytes(bytes: Uint8Array): string {
return `bytes=${bytes.length} preview=${hexPreview(bytes, OPERATOR_BYTES_PREVIEW_LENGTH)}`;
return `bytes=${bytes.length} preview=${hexPreview(bytes, OPERATOR_BYTES_PREVIEW_LENGTH)}`;
}
function hasControlCharacter(value: string): boolean {
for (const char of value) {
const codePoint = char.codePointAt(0);
if (codePoint !== undefined && (codePoint <= 0x1f || codePoint === 0x7f)) return true;
}
return false;
for (const char of value) {
const codePoint = char.codePointAt(0);
if (codePoint !== undefined && (codePoint <= 0x1f || codePoint === 0x7f)) {
return true;
}
}
return false;
}
function assertOperatorUid(uid: string, context: string, bytes: Uint8Array): string {
if (hasControlCharacter(uid)) {
throw new Error(`${context} operator UID contains control characters (${describeOperatorBytes(bytes)})`);
}
return uid;
if (hasControlCharacter(uid)) {
throw new Error(
`${context} operator UID contains control characters (${describeOperatorBytes(bytes)})`,
);
}
return uid;
}
export function decodeRawOperatorUid(bytes: Uint8Array, context: string): string {
if (!bytes || bytes.length === 0) return '';
let uid: string;
try {
uid = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
} catch (error) {
throw new Error(
`${context} operator UID is not valid UTF-8 (${describeOperatorBytes(bytes)})`,
{ cause: error },
);
}
return assertOperatorUid(uid, context, bytes);
if (!bytes || bytes.length === 0) {
return '';
}
let uid: string;
try {
uid = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
} catch (error) {
throw new Error(
`${context} operator UID is not valid UTF-8 (${describeOperatorBytes(bytes)})`,
{ cause: error },
);
}
return assertOperatorUid(uid, context, bytes);
}
export function decodeNestedOperatorUid(bytes: Uint8Array, context: string): string {
if (!bytes || bytes.length === 0) return '';
let info: OperatorInfo | null;
try {
info = protobuf_decode<OperatorInfo>(bytes);
} catch (error) {
throw new Error(
`${context} operator info decode failed (${describeOperatorBytes(bytes)})`,
{ cause: error },
);
}
const uid = info?.operatorField?.uid;
if (!uid) {
throw new Error(`${context} operator info is missing UID (${describeOperatorBytes(bytes)})`);
}
return assertOperatorUid(uid, context, bytes);
if (!bytes || bytes.length === 0) {
return '';
}
let info: OperatorInfo | null;
try {
info = protobuf_decode<OperatorInfo>(bytes);
} catch (error) {
throw new Error(
`${context} operator info decode failed (${describeOperatorBytes(bytes)})`,
{
cause: error,
},
);
}
const uid = info?.operatorField?.uid;
if (!uid) {
throw new Error(
`${context} operator info is missing UID (${describeOperatorBytes(bytes)})`,
);
}
return assertOperatorUid(uid, context, bytes);
}
const OPERATOR_INFO_FIELD_TAG = 0x0a;
export function decodeGroupChangeOperatorUid(bytes: Uint8Array, context: string): string {
if (!bytes || bytes.length === 0) return '';
return bytes[0] === OPERATOR_INFO_FIELD_TAG
? decodeNestedOperatorUid(bytes, context)
: decodeRawOperatorUid(bytes, context);
if (!bytes || bytes.length === 0) {
return '';
}
return bytes[0] === OPERATOR_INFO_FIELD_TAG
? decodeNestedOperatorUid(bytes, context)
: decodeRawOperatorUid(bytes, context);
}
export function buildTemplateMap(params: Array<{ name?: string; value?: string }>): Map<string, string> {
const map = new Map<string, string>();
for (const p of params) {
if (p.name !== undefined) map.set(p.name, p.value ?? '');
}
return map;
export function buildTemplateMap(
params: Array<{ name?: string; value?: string }>,
): Map<string, string> {
const map = new Map<string, string>();
for (const p of params) {
if (p.name !== undefined) {
map.set(p.name, p.value ?? '');
}
}
return map;
}
export function findTemplateValue(map: Map<string, string>, ...keys: string[]): string {
for (const k of keys) {
const v = map.get(k);
if (v) return v;
}
return '';
for (const k of keys) {
const v = map.get(k);
if (v) {
return v;
}
}
return '';
}
export function unwrapGroupNotifyPayload(content: Uint8Array): Uint8Array | null {
if (content.length <= 7) return null;
const lenBe = (content[5] << 8) | content[6];
const lenLe = content[5] | (content[6] << 8);
if (7 + lenBe <= content.length) return content.subarray(7, 7 + lenBe);
if (7 + lenLe <= content.length) return content.subarray(7, 7 + lenLe);
return content.subarray(7);
if (content.length <= 7) {
return null;
}
const lenBe = (content[5] << 8) | content[6];
const lenLe = content[5] | (content[6] << 8);
if (7 + lenBe <= content.length) {
return content.subarray(7, 7 + lenBe);
}
if (7 + lenLe <= content.length) {
return content.subarray(7, 7 + lenLe);
}
return content.subarray(7);
}
+172 -160
View File
@@ -9,34 +9,31 @@ import { decodeEvent0x2DC } from './decoders/event-0x2dc';
import { decodeFriendMessage } from './decoders/friend-message';
import { decodeGroupAdmin } from './decoders/group-admin';
import {
decodeGroupInvitation, decodeGroupInvite,
decodeGroupJoinRequest,
decodeGroupInvitation,
decodeGroupInvite,
decodeGroupJoinRequest,
} from './decoders/group-join-request';
import {
decodeGroupMemberJoin, decodeGroupMemberLeave, decodeGroupSelfJoined,
decodeGroupMemberJoin,
decodeGroupMemberLeave,
decodeGroupSelfJoined,
} from './decoders/group-member-change';
import { decodeGroupMessage } from './decoders/group-message';
import { decodeTempMessage } from './decoders/temp-message';
import { PkgType } from './enums';
import { MsgPushRegistry } from './registry';
import {
deriveSysMsgDedupIdentity,
SysMsgDedup,
} from './sysmsg-dedup';
import { deriveSysMsgDedupIdentity, SysMsgDedup } from './sysmsg-dedup';
export {
deriveSysMsgDedupIdentity,
SysMsgDedup,
} from './sysmsg-dedup';
export { deriveSysMsgDedupIdentity, SysMsgDedup } from './sysmsg-dedup';
export type { SysMsgDedupIdentity } from './sysmsg-dedup';
export { SSO_GET_GROUP_MSG_CMD, fetchGroupMessageRange } from './fetch-group-history';
export {
SSO_GET_C2C_MSG_CMD,
SSO_GET_ROAM_MSG_CMD,
fetchC2cMessageRange,
fetchC2cRoamMessagePage,
type C2cRoamPage,
SSO_GET_C2C_MSG_CMD,
SSO_GET_ROAM_MSG_CMD,
fetchC2cMessageRange,
fetchC2cRoamMessagePage,
type C2cRoamPage,
} from './fetch-c2c-history';
export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush';
@@ -53,171 +50,186 @@ registry.register(PkgType.Event0x210, decodeEvent0x210);
registry.register(PkgType.Event0x2DC, decodeEvent0x2DC);
registry.register(PkgType.GroupMessage, decodeGroupMessage);
registry.register(PkgType.TempMessage, decodeTempMessage);
registry.register([
PkgType.PrivateMessage,
PkgType.ForwardFakePrivateMessage,
PkgType.PrivateRecordMessage,
PkgType.PrivateFileMessage,
], decodeFriendMessage);
registry.register(
[
PkgType.PrivateMessage,
PkgType.ForwardFakePrivateMessage,
PkgType.PrivateRecordMessage,
PkgType.PrivateFileMessage,
],
decodeFriendMessage,
);
const log = createLogger('MsgPush');
function messageElements(ev: QQEventVariant): readonly unknown[] | undefined {
if (ev.kind === 'friend_message' || ev.kind === 'group_message' || ev.kind === 'temp_message') {
return ev.elements;
}
return undefined;
if (ev.kind === 'friend_message' || ev.kind === 'group_message' || ev.kind === 'temp_message') {
return ev.elements;
}
return undefined;
}
function warnMissingC2cSequence(ev: QQEventVariant, fromUin: number): void {
if (
(ev.kind === 'friend_message' || ev.kind === 'temp_message')
&& ev.sequenceAuthoritative === false
) {
log.warn(
'c2c message omitted NT sequence; keeping non-authoritative client sequence (kind=%s from=%d clientSeq=%d time=%d)',
ev.kind,
fromUin,
ev.clientSeq ?? ev.msgSeq,
ev.time,
);
}
if (
(ev.kind === 'friend_message' || ev.kind === 'temp_message') &&
ev.sequenceAuthoritative === false
) {
log.warn(
'c2c message omitted NT sequence; keeping non-authoritative client sequence (kind=%s from=%d clientSeq=%d time=%d)',
ev.kind,
fromUin,
ev.clientSeq ?? ev.msgSeq,
ev.time,
);
}
}
export function parseMsgPush(
pkt: PacketInfo,
identity: IdentityService,
dedup?: SysMsgDedup,
pkt: PacketInfo,
identity: IdentityService,
dedup?: SysMsgDedup,
): QQEventVariant[] {
return parseMsgPushInternal(
pkt,
identity,
dedup,
false,
);
return parseMsgPushInternal(pkt, identity, dedup, false);
}
export function parseMsgPushOrThrow(
pkt: PacketInfo,
identity: IdentityService,
dedup?: SysMsgDedup,
pkt: PacketInfo,
identity: IdentityService,
dedup?: SysMsgDedup,
): QQEventVariant[] {
return parseMsgPushInternal(
pkt,
identity,
dedup,
true,
);
return parseMsgPushInternal(pkt, identity, dedup, true);
}
function parseMsgPushInternal(
pkt: PacketInfo,
identity: IdentityService,
dedup: SysMsgDedup | undefined,
throwDecoderErrors: boolean,
pkt: PacketInfo,
identity: IdentityService,
dedup: SysMsgDedup | undefined,
throwDecoderErrors: boolean,
): QQEventVariant[] {
const ctx = buildContext(pkt, identity);
if (!ctx) {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=push_context_invalid',
pkt.serviceCmd,
pkt.seqId,
]);
return [];
}
const ctx = buildContext(pkt, identity);
// #137/#266: mirror QQ NT `sys_msg_mgr.cc::ProcessRecvSysMsg` before
// dispatch. Its static routing table is the scope boundary: listed routes
// use the native global key, while unlisted routes fail open. Running this
// before registry decode also covers native system packets whose outer type
// SnowLuma otherwise interprets as a chat message or does not decode at all.
if (dedup) {
const dedupIdentity = deriveSysMsgDedupIdentity(ctx);
if (dedupIdentity && dedup.seenDuplicate(dedupIdentity)) {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=duplicate_system_push peer=%j chatType=%d messageSeq=%d messageRandom=%d',
pkt.serviceCmd,
pkt.seqId,
dedupIdentity.peerUid,
dedupIdentity.chatType,
dedupIdentity.sequence,
dedupIdentity.random,
]);
log.debug(
'dropped duplicate system push (peer=%s chatType=%d seq=%d msgType=%d/%d msgId=%d)',
dedupIdentity.peerUid,
dedupIdentity.chatType,
ctx.head.sequence,
ctx.head.msgType,
ctx.head.subType,
ctx.head.msgId,
);
return [];
if (!ctx) {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=push_context_invalid',
pkt.serviceCmd,
pkt.seqId,
]);
return [];
}
}
const events = throwDecoderErrors
? registry.decodeOrThrow(ctx)
: registry.decode(ctx);
const out = events.filter((ev) => {
const elements = messageElements(ev);
if (elements === undefined) return true;
const survival = classifyMessageSurvival(ctx.head, elements, ctx.body);
if (survival === 'drop-control') {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=c2c_control_push msgType=%d subType=%d c2cCmd=%d messageSeq=%d',
pkt.serviceCmd,
pkt.seqId,
ctx.head.msgType,
ctx.head.subType,
ctx.head.c2cCmd,
ctx.head.sequence,
]);
if (elements.length > 0) {
log.debug('dropped c2c control push that carried %d element(s) (kind=%s seq=%d from=%d msgType=%d cmd=%d)',
elements.length, ev.kind, ctx.head.sequence, ctx.fromUin, ctx.head.msgType, ctx.head.c2cCmd);
}
return false;
}
if (survival === 'drop-receipt') {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=offline_file_receipt msgType=%d subType=%d messageSeq=%d',
pkt.serviceCmd,
pkt.seqId,
ctx.head.msgType,
ctx.head.subType,
ctx.head.sequence,
]);
log.debug(
'dropped offline file receipt (kind=%s seq=%d from=%d msgType=%d)',
ev.kind, ctx.head.sequence, ctx.fromUin, ctx.head.msgType,
);
return false;
}
if (survival === 'drop-blank') {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=empty_message msgType=%d subType=%d messageSeq=%d',
pkt.serviceCmd,
pkt.seqId,
ctx.head.msgType,
ctx.head.subType,
ctx.head.sequence,
]);
return false;
}
if (survival === 'keep-undecoded') {
warnUndecodedMessage({
kind: ev.kind,
sequence: ctx.head.sequence,
fromUin: ctx.fromUin,
msgType: ctx.head.msgType,
subType: ctx.head.subType,
body: ctx.body,
});
}
warnMissingC2cSequence(ev, ctx.fromUin);
return true;
});
// #137/#266: mirror QQ NT `sys_msg_mgr.cc::ProcessRecvSysMsg` before
// dispatch. Its static routing table is the scope boundary: listed routes
// use the native global key, while unlisted routes fail open. Running this
// before registry decode also covers native system packets whose outer type
// SnowLuma otherwise interprets as a chat message or does not decode at all.
if (dedup) {
const dedupIdentity = deriveSysMsgDedupIdentity(ctx);
return out;
if (dedupIdentity && dedup.seenDuplicate(dedupIdentity)) {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=duplicate_system_push peer=%j chatType=%d messageSeq=%d messageRandom=%d',
pkt.serviceCmd,
pkt.seqId,
dedupIdentity.peerUid,
dedupIdentity.chatType,
dedupIdentity.sequence,
dedupIdentity.random,
]);
log.debug(
'dropped duplicate system push (peer=%s chatType=%d seq=%d msgType=%d/%d msgId=%d)',
dedupIdentity.peerUid,
dedupIdentity.chatType,
ctx.head.sequence,
ctx.head.msgType,
ctx.head.subType,
ctx.head.msgId,
);
return [];
}
}
const events = throwDecoderErrors ? registry.decodeOrThrow(ctx) : registry.decode(ctx);
const out = events.filter((ev) => {
const elements = messageElements(ev);
if (elements === undefined) {
return true;
}
const survival = classifyMessageSurvival(ctx.head, elements, ctx.body);
if (survival === 'drop-control') {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=c2c_control_push msgType=%d subType=%d c2cCmd=%d messageSeq=%d',
pkt.serviceCmd,
pkt.seqId,
ctx.head.msgType,
ctx.head.subType,
ctx.head.c2cCmd,
ctx.head.sequence,
]);
if (elements.length > 0) {
log.debug(
'dropped c2c control push that carried %d element(s) (kind=%s seq=%d from=%d msgType=%d cmd=%d)',
elements.length,
ev.kind,
ctx.head.sequence,
ctx.fromUin,
ctx.head.msgType,
ctx.head.c2cCmd,
);
}
return false;
}
if (survival === 'drop-receipt') {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=offline_file_receipt msgType=%d subType=%d messageSeq=%d',
pkt.serviceCmd,
pkt.seqId,
ctx.head.msgType,
ctx.head.subType,
ctx.head.sequence,
]);
log.debug(
'dropped offline file receipt (kind=%s seq=%d from=%d msgType=%d)',
ev.kind,
ctx.head.sequence,
ctx.fromUin,
ctx.head.msgType,
);
return false;
}
if (survival === 'drop-blank') {
log.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=empty_message msgType=%d subType=%d messageSeq=%d',
pkt.serviceCmd,
pkt.seqId,
ctx.head.msgType,
ctx.head.subType,
ctx.head.sequence,
]);
return false;
}
if (survival === 'keep-undecoded') {
warnUndecodedMessage({
kind: ev.kind,
sequence: ctx.head.sequence,
fromUin: ctx.fromUin,
msgType: ctx.head.msgType,
subType: ctx.head.subType,
body: ctx.body,
});
}
warnMissingC2cSequence(ev, ctx.fromUin);
return true;
});
return out;
}
@@ -1,16 +1,15 @@
import type { SendPacketResult } from '@snowluma/common/packet-sender';
export function requirePacketResponse(
result: SendPacketResult,
command: string,
): Uint8Array {
if (!result.success) {
throw new Error(
`${command} transport failed: ${result.errorMessage || 'unknown transport error'}`,
);
}
if (!result.gotResponse || !result.responseData || result.responseData.length === 0) {
throw new Error(`${command} response is empty`);
}
return result.responseData;
export function requirePacketResponse(result: SendPacketResult, command: string): Uint8Array {
if (!result.success) {
throw new Error(
`${command} transport failed: ${result.errorMessage || 'unknown transport error'}`,
);
}
if (!result.gotResponse || !result.responseData || result.responseData.length === 0) {
throw new Error(`${command} response is empty`);
}
return result.responseData;
}
+62 -54
View File
@@ -9,67 +9,75 @@ const unknownLog = createLogger('MsgPush.Unknown');
export type MsgPushDecoder = (ctx: MsgPushContext) => QQEventVariant[];
export class MsgPushRegistry {
private readonly decoders_ = new Map<PkgType, MsgPushDecoder>();
private readonly decoders_ = new Map<PkgType, MsgPushDecoder>();
register(pkgType: PkgType | PkgType[], decoder: MsgPushDecoder): void {
const list = Array.isArray(pkgType) ? pkgType : [pkgType];
for (const t of list) {
if (this.decoders_.has(t)) {
throw new Error(`MsgPushRegistry: PkgType ${t} already registered`);
}
this.decoders_.set(t, decoder);
register(pkgType: PkgType | PkgType[], decoder: MsgPushDecoder): void {
const list = Array.isArray(pkgType) ? pkgType : [pkgType];
for (const t of list) {
if (this.decoders_.has(t)) {
throw new Error(`MsgPushRegistry: PkgType ${t} already registered`);
}
this.decoders_.set(t, decoder);
}
}
}
decode(ctx: MsgPushContext): QQEventVariant[] {
try {
return this.runDecoder(ctx);
} catch (e) {
this.traceDecoderException(ctx, e);
log.error('decoder error for PkgType=%d subType=%d: %s',
ctx.head.msgType, ctx.head.subType,
e instanceof Error ? (e.stack ?? e.message) : String(e));
return [];
decode(ctx: MsgPushContext): QQEventVariant[] {
try {
return this.runDecoder(ctx);
} catch (e) {
this.traceDecoderException(ctx, e);
log.error(
'decoder error for PkgType=%d subType=%d: %s',
ctx.head.msgType,
ctx.head.subType,
e instanceof Error ? (e.stack ?? e.message) : String(e),
);
return [];
}
}
}
decodeOrThrow(ctx: MsgPushContext): QQEventVariant[] {
try {
return this.runDecoder(ctx);
} catch (e) {
this.traceDecoderException(ctx, e);
throw e;
decodeOrThrow(ctx: MsgPushContext): QQEventVariant[] {
try {
return this.runDecoder(ctx);
} catch (e) {
this.traceDecoderException(ctx, e);
throw e;
}
}
}
private runDecoder(ctx: MsgPushContext): QQEventVariant[] {
const decoder = this.decoders_.get(ctx.head.msgType as PkgType);
if (!decoder) {
unknownLog.trace(() => [
'packet_branch branch=decoder_unregistered msgType=%d subType=%d messageSeq=%d',
ctx.head.msgType,
ctx.head.subType,
ctx.head.sequence,
]);
// Unrecognized PkgType: either we don't care about this notify, or
// the QQ NT client added a new variant. Surface at debug so a
// protocol change can be spotted without spamming production logs.
unknownLog.debug('no decoder for PkgType=%d subType=%d', ctx.head.msgType, ctx.head.subType);
return [];
private runDecoder(ctx: MsgPushContext): QQEventVariant[] {
const decoder = this.decoders_.get(ctx.head.msgType as PkgType);
if (!decoder) {
unknownLog.trace(() => [
'packet_branch branch=decoder_unregistered msgType=%d subType=%d messageSeq=%d',
ctx.head.msgType,
ctx.head.subType,
ctx.head.sequence,
]);
// Unrecognized PkgType: either we don't care about this notify, or
// the QQ NT client added a new variant. Surface at debug so a
// protocol change can be spotted without spamming production logs.
unknownLog.debug(
'no decoder for PkgType=%d subType=%d',
ctx.head.msgType,
ctx.head.subType,
);
return [];
}
return decoder(ctx);
}
return decoder(ctx);
}
private traceDecoderException(
ctx: MsgPushContext,
error: unknown,
): void {
log.trace(() => [
'packet_branch branch=decoder_exception msgType=%d subType=%d messageSeq=%d error=%j',
ctx.head.msgType,
ctx.head.subType,
ctx.head.sequence,
error instanceof Error ? error.message : String(error),
]);
}
private traceDecoderException(ctx: MsgPushContext, error: unknown): void {
log.trace(() => [
'packet_branch branch=decoder_exception msgType=%d subType=%d messageSeq=%d error=%j',
ctx.head.msgType,
ctx.head.subType,
ctx.head.sequence,
error instanceof Error ? error.message : String(error),
]);
}
}
File diff suppressed because it is too large. Load diff
+77 -43
View File
@@ -3,20 +3,37 @@ import type { MsgPushContext } from './context';
export type SysMsgChatType = 1 | 2;
export interface SysMsgDedupIdentity {
readonly peerUid: string;
readonly chatType: SysMsgChatType;
readonly sequence: number;
readonly random: number;
readonly peerUid: string;
readonly chatType: SysMsgChatType;
readonly sequence: number;
readonly random: number;
}
function getNativeSysMsgChatType(msgType: number, subType: number): SysMsgChatType | null {
if (msgType === 528 && subType === 290) return 1;
if (msgType === 166 && (subType === 75 || subType === 129 || subType === 131 || subType === 133 || subType === 135)) return 1;
if (msgType === 167 && subType === 133) return 1;
if (msgType === 528 && subType === 290) {
return 1;
}
if (msgType === 732 && (subType === 12 || subType === 16 || subType === 20)) return 2;
if ((msgType === 33 || msgType === 34 || msgType === 85) && subType === 0) return 2;
return null;
if (
msgType === 166 &&
(subType === 75 || subType === 129 || subType === 131 || subType === 133 || subType === 135)
) {
return 1;
}
if (msgType === 167 && subType === 133) {
return 1;
}
if (msgType === 732 && (subType === 12 || subType === 16 || subType === 20)) {
return 2;
}
if ((msgType === 33 || msgType === 34 || msgType === 85) && subType === 0) {
return 2;
}
return null;
}
/**
@@ -25,24 +42,30 @@ function getNativeSysMsgChatType(msgType: number, subType: number): SysMsgChatTy
* routes fail open rather than risking suppression of unrelated events.
*/
export function deriveSysMsgDedupIdentity(
ctx: Pick<MsgPushContext, 'head' | 'fromUin' | 'fromUid'>,
ctx: Pick<MsgPushContext, 'head' | 'fromUin' | 'fromUid'>,
): SysMsgDedupIdentity | null {
const { head } = ctx;
const chatType = getNativeSysMsgChatType(head.msgType, head.subType);
// Decoded zero is also the protobuf default for an absent field. Without a
// complete server identity, prefer a duplicate event over suppressing two
// unrelated pushes that collapse to the same default-valued key.
if (chatType === null || head.sequence === 0 || head.msgId === 0) return null;
const { head } = ctx;
const chatType = getNativeSysMsgChatType(head.msgType, head.subType);
const peerUid = chatType === 1 ? ctx.fromUid : String(ctx.fromUin);
if (!peerUid || (chatType === 2 && ctx.fromUin === 0)) return null;
// Decoded zero is also the protobuf default for an absent field. Without a
// complete server identity, prefer a duplicate event over suppressing two
// unrelated pushes that collapse to the same default-valued key.
if (chatType === null || head.sequence === 0 || head.msgId === 0) {
return null;
}
return {
peerUid,
chatType,
sequence: head.sequence,
random: head.msgId,
};
const peerUid = chatType === 1 ? ctx.fromUid : String(ctx.fromUin);
if (!peerUid || (chatType === 2 && ctx.fromUin === 0)) {
return null;
}
return {
peerUid,
chatType,
sequence: head.sequence,
random: head.msgId,
};
}
/**
@@ -60,24 +83,35 @@ export function deriveSysMsgDedupIdentity(
* groups. {@link deriveSysMsgDedupIdentity} mirrors those routes exactly.
*/
export class SysMsgDedup {
private readonly seen = new Set<string>();
private readonly ring: (string | undefined)[];
private cursor = 0;
private readonly seen = new Set<string>();
private readonly ring: (string | undefined)[];
private cursor = 0;
constructor(private readonly capacity = 1024) {
this.ring = new Array<string | undefined>(capacity);
}
constructor(private readonly capacity = 1024) {
this.ring = new Array<string | undefined>(capacity);
}
/** Returns true when this native system-message identity was already seen. */
seenDuplicate(identity: SysMsgDedupIdentity): boolean {
if (identity.sequence === 0 || identity.random === 0 || !identity.peerUid) return false;
const key = `${identity.peerUid}_${identity.chatType}_${identity.sequence}_${identity.random}`;
if (this.seen.has(key)) return true;
const evicted = this.ring[this.cursor];
if (evicted !== undefined) this.seen.delete(evicted);
this.ring[this.cursor] = key;
this.seen.add(key);
this.cursor = (this.cursor + 1) % this.capacity;
return false;
}
/** Returns true when this native system-message identity was already seen. */
seenDuplicate(identity: SysMsgDedupIdentity): boolean {
if (identity.sequence === 0 || identity.random === 0 || !identity.peerUid) {
return false;
}
const key = `${identity.peerUid}_${identity.chatType}_${identity.sequence}_${identity.random}`;
if (this.seen.has(key)) {
return true;
}
const evicted = this.ring[this.cursor];
if (evicted !== undefined) {
this.seen.delete(evicted);
}
this.ring[this.cursor] = key;
this.seen.add(key);
this.cursor = (this.cursor + 1) % this.capacity;
return false;
}
}