feat(protocol): decode online device snapshots

Decode Event 0x210 subtype 349 into typed online-device snapshots, including QQ-compatible low-byte client type normalization and one-entry-per-device-category projection.

Keep replacement snapshots outside system-message deduplication, reject malformed device identities observably, and add wire-level regressions for complete, packed, repeated, and invalid payloads. Live verification covered mobile account switching without requiring native changes.
This commit is contained in:
DrSmoothl committed 2026-07-19 19:19:58 +08:00
1 parent e6a69b05a7
commit b92c8ad881
8 files changed
+279 -3

No files matched your search

+126 -1
View File
@@ -15,7 +15,7 @@ import type { GroupMemberInfo, QQGroupInfo } from '@snowluma/protocol/qq-info';
import type {
GroupChange, NewFriend, FriendRecall, OperatorInfo, SelfJoinInGroup, GroupAdmin,
InputStatusNotify, NotifyMessageBody, GroupNameChange, GroupSpecialTitleChange,
ProfileLikeTip,
OnlineDeviceNotify, ProfileLikeTip,
} from '@snowluma/proto-defs/notify';
import type { PushMsg } from '@snowluma/proto-defs/message';
import type {
@@ -449,6 +449,131 @@ describe('parseMsgPush Event0x210 subType=277 (input status → 对方正在输
});
});
describe('parseMsgPush Event0x210 subType=349 (online-device snapshot)', () => {
it('decodes the complete device fields recovered from the QQ wire handler', () => {
const content = protobuf_encode<OnlineDeviceNotify>({
appId: 537242075,
instanceId: 101,
clientType: 1,
platform: 3,
devices: [
{
appId: 537242075,
instanceId: 202,
clientType: 1,
platform: 3,
deviceName: 'DESKTOP-TEST',
},
{
appId: 537242075,
instanceId: 203,
clientType: 5,
platform: 3,
deviceName: 'DESKTOP-DUPLICATE',
},
{
appId: 537242075,
instanceId: 303,
clientType: 4,
platform: 2,
deviceName: 'Pixel 9',
},
],
});
const events = parseMsgPush(
makeEvent0x210PacketAny(349, content),
makeIdentity(),
);
expect(events).toEqual([{
kind: 'online_devices_changed',
time: 1710000000,
selfUin: Number(SELF_UIN),
devices: [
{
appId: 537242075,
instanceId: 202,
clientType: 1,
platform: 3,
deviceName: 'DESKTOP-TEST',
deviceKind: 'computer',
},
{
appId: 537242075,
instanceId: 303,
clientType: 4,
platform: 2,
deviceName: 'Pixel 9',
deviceKind: 'phone',
},
],
}]);
});
it('normalizes packed wire client types before classification and deduplication', () => {
const content = protobuf_encode<OnlineDeviceNotify>({
devices: [
{
appId: 1001,
instanceId: 202,
clientType: 83714, // 0x14702 -> phone client type 2
platform: 3,
deviceName: 'BOT-HOST',
},
{
appId: 1001,
instanceId: 203,
clientType: 65799, // 0x10107 -> phone client type 7
platform: 2,
deviceName: 'MOBILE-DUPLICATE',
},
],
});
const events = parseMsgPush(
makeEvent0x210PacketAny(349, content),
makeIdentity(),
);
expect(events).toEqual([{
kind: 'online_devices_changed',
time: 1710000000,
selfUin: Number(SELF_UIN),
devices: [{
appId: 1001,
instanceId: 202,
clientType: 2,
platform: 3,
deviceName: 'BOT-HOST',
deviceKind: 'phone',
}],
}]);
});
it('rejects entries that omit required identity fields', () => {
const content = protobuf_encode<OnlineDeviceNotify>({
devices: [{ instanceId: 202, platform: 3, deviceName: 'BROKEN' }],
});
const captured: string[] = [];
const unsubscribe = subscribeLogs((entry) => {
if (entry.scope === 'MsgPush' && /online-device entry 0/.test(entry.message)) {
captured.push(entry.message);
}
});
try {
expect(parseMsgPush(
makeEvent0x210PacketAny(349, content),
makeIdentity(),
)).toEqual([]);
expect(captured).toHaveLength(1);
expect(captured[0]).toMatch(/appIdPresent=false clientTypePresent=false/);
} finally {
unsubscribe();
}
});
});
describe('parseMsgPush Event0x210 subType=39 (profile like → 名片赞)', () => {
// 0x210/39 is multiplexed; body.msgContent decodes as ProfileLikeTip and is a
// like only when inner msgType==0 && subType==203. Proto shape from NapCat's
@@ -97,6 +97,8 @@ const CONVERTERS: ConverterRegistry = {
// Internal-only: async voice-to-text result, correlated by a pending
// fetch_ptt_text; never emitted as an OneBot event.
ptt_trans_result: null,
// Internal-only cache snapshot consumed by Bridge.getOnlineClients().
online_devices_changed: null,
};
export async function convertEvent(
+24
View File
@@ -95,6 +95,30 @@ export interface FriendRequest {
info?: pb<1, FriendRequestInfo>;
}
/**
* Online-device snapshot carried by Event 0x210 / subType 349.
*
* Field numbers were recovered from QQ NT's OnRecvOnLineDev decoder. The
* outer four fields describe the current client, while field 5 contains the
* online-device entries exposed by getOnLineDev's kernel cache.
*/
export interface OnlineDeviceNotifyItem {
appId?: pb<1, uint_32>;
instanceId?: pb<2, uint_32>;
/** Packed terminal value; QQ normalizes it to the low byte before use. */
clientType?: pb<3, uint_32>;
platform?: pb<4, uint_32>;
deviceName?: pb<5, string>;
}
export interface OnlineDeviceNotify {
appId?: pb<1, uint_32>;
instanceId?: pb<2, uint_32>;
clientType?: pb<3, uint_32>;
platform?: pb<4, uint_32>;
devices?: pb_repeated<5, OnlineDeviceNotifyItem>;
}
export interface FriendRecallTipInfo {
tip?: pb<2, string>;
}
+23
View File
@@ -486,6 +486,28 @@ export interface FriendInputStatusEvent extends QQEvent {
statusText: string;
}
export type OnlineDeviceKind = 'computer' | 'pad' | 'phone' | 'unknown';
/** One entry from QQ NT's online-device cache notification. */
export interface OnlineDeviceInfo {
appId: number;
instanceId: number;
clientType: number;
platform: number;
deviceName: string;
deviceKind: OnlineDeviceKind;
}
/**
* Full online-device snapshot pushed through Event 0x210 / subType 349.
* Internal-only: Bridge consumes this to maintain the query snapshot; it is
* not forwarded as an OneBot event.
*/
export interface OnlineDevicesChangedEvent extends QQEvent {
kind: 'online_devices_changed';
devices: OnlineDeviceInfo[];
}
export type QQEventVariant =
| FriendMessage
| GroupMessage
@@ -510,4 +532,5 @@ export type QQEventVariant =
| GroupCardChangeEvent
| GroupTitleChangeEvent
| FriendProfileLikeEvent
| OnlineDevicesChangedEvent
| BotOfflineEvent;
@@ -4,6 +4,8 @@ import type {
FriendAddEvent,
FriendPokeEvent,
FriendRequestEvent,
OnlineDeviceInfo,
OnlineDeviceKind,
QQEventVariant,
} from '../../events';
import type {
@@ -12,6 +14,7 @@ import type {
GeneralGrayTipInfo,
InputStatusNotify,
NewFriend,
OnlineDeviceNotify,
ProfileLikeTip,
} from '@snowluma/proto-defs/notify';
import type { PttTransPush } from '@snowluma/proto-defs/ptt-trans';
@@ -42,6 +45,7 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
return decodeFriendRecall(ctx);
case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx);
case Event0x210SubType.InputStatusNotice: return decodeInputStatus(ctx);
case Event0x210SubType.OnlineDevicesNotice: return decodeOnlineDevices(ctx);
case Event0x210SubType.ProfileLikeNotice: return decodeProfileLike(ctx);
// 179 + 226 both carry the NewFriend payload — see enum comment.
case Event0x210SubType.NewFriendNotice:
@@ -66,6 +70,63 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => {
return [];
};
const COMPUTER_CLIENT_TYPES = new Set([1, 5, 15]);
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';
}
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;
}
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 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):
// { f1: uint, f2: { f1 = msgId (echoes the request), f8 = text, ... } }
// `msgId` is the correlation key a pending fetch_ptt_text waits on; we surface
+6
View File
@@ -84,6 +84,12 @@ export enum Event0x210SubType {
* `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,
/**
* Group-app state push (troop shortcut bar / discussion app).
*
+13 -1
View File
@@ -57,6 +57,13 @@ const MESSAGE_KINDS = new Set<QQEventVariant['kind']>([
'friend_message', 'group_message', 'temp_message',
]);
// Replacement snapshots describe the complete current state. They are
// idempotent, but not duplicate events: a later snapshot may legitimately
// reuse the enclosing system-message identity while carrying new state.
const STATE_SNAPSHOT_KINDS = new Set<QQEventVariant['kind']>([
'online_devices_changed',
]);
/**
* Summarise a body that decoded to zero elements despite carrying content —
* each element's field names, every `commonElem`'s serviceType/businessType +
@@ -127,7 +134,12 @@ export function parseMsgPush(
// messages have their own NT dedup path and the forward re-parse re-runs
// this without a tracker. A push that decodes to a message kind, or to
// nothing, is never deduped here.
if (dedup && out.length > 0 && out.every((ev) => !MESSAGE_KINDS.has(ev.kind))) {
if (
dedup
&& out.length > 0
&& out.every((ev) => !MESSAGE_KINDS.has(ev.kind))
&& out.every((ev) => !STATE_SNAPSHOT_KINDS.has(ev.kind))
) {
if (dedup.seenDuplicate(ctx.head, ctx.fromUin)) {
log.debug('dropped duplicate system push (kinds=%s seq=%d from=%d msgType=%d msgId=%d)',
out.map((ev) => ev.kind).join(','), ctx.head.sequence, ctx.fromUin, ctx.head.msgType, ctx.head.msgId);
@@ -12,7 +12,7 @@ import { describe, expect, it } from 'vitest';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { protobuf_encode } from '@snowluma/proton';
import type { PushMsg, PushMsgBody } from '@snowluma/proto-defs/message';
import type { GroupChange } from '@snowluma/proto-defs/notify';
import type { GroupChange, OnlineDeviceNotify } from '@snowluma/proto-defs/notify';
import type { IdentityService } from '../../src/identity-service';
import { parseMsgPush, SysMsgDedup } from '../../src/msg-push';
@@ -40,6 +40,18 @@ function memberIncreasePush(opts: { groupId: number; memberUin: number; sequence
});
}
function onlineDevicesPush(deviceName: string): PacketInfo {
return pushPacket({
responseHead: { fromUin: 2000000001, fromUid: '' },
contentHead: { msgType: 528, subType: 349, sequence: 800, timestamp: 1781540572, msgId: 555 },
body: {
msgContent: protobuf_encode<OnlineDeviceNotify>({
devices: [{ appId: 537242075, instanceId: 202, clientType: 1, platform: 3, deviceName }],
}),
},
});
}
describe('SysMsgDedup', () => {
it('flags the second push with the same (msgType, subType, fromUin, seq, msgId)', () => {
const d = new SysMsgDedup();
@@ -115,4 +127,15 @@ describe('parseMsgPush — system-push dedup (#137)', () => {
expect(parseMsgPush(chat(), identity, dedup)).toHaveLength(1);
expect(parseMsgPush(chat(), identity, dedup)).toHaveLength(1);
});
it('does not dedup replacement state snapshots with the same server identity', () => {
const dedup = new SysMsgDedup();
expect(parseMsgPush(onlineDevicesPush('DESKTOP-A'), identity, dedup)).toMatchObject([
{ kind: 'online_devices_changed', devices: [{ deviceName: 'DESKTOP-A' }] },
]);
expect(parseMsgPush(onlineDevicesPush('DESKTOP-B'), identity, dedup)).toMatchObject([
{ kind: 'online_devices_changed', devices: [{ deviceName: 'DESKTOP-B' }] },
]);
});
});