feat(protocol): send and receive official my-device chats

Pad and phone device conversations were missing from the friend list
and arrived as empty private messages. They now show up as stable
contacts and support text send/receive.

Fixes #452
This commit is contained in:
DrSmoothl committed 2026-09-14 19:34:42 +08:00
1 parent 60c9669abd
commit dac3deb7bd
16 files changed
+692 -17

No files matched your search

+4
View File
@@ -99,6 +99,10 @@
"./web/*": {
"types": "./src/web/*.ts",
"default": "./src/web/*.ts"
},
"./dataline/*": {
"types": "./src/dataline/*.ts",
"default": "./src/dataline/*.ts"
}
},
"scripts": {
+105
View File
@@ -0,0 +1,105 @@
import { toHex } from '@snowluma/common/hex';
import type {
DatalineMsgBody,
DatalineTextMsg,
} from '@snowluma/proto-defs/dataline';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { MessageElement } from '../events';
import { appIdForTerType, DATALINE_SELF_TER_TYPE } from './device-contacts';
const DATALINE_SUBCMD_FTN = 1;
const DATALINE_SUBCMD_GENERIC = 4;
const DATALINE_GENERIC_TEXT = 1;
const DATALINE_TEXT_ITEM = 1;
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
export function encodeDatalineText(params: {
selfUin: number;
srcTerType?: number;
dstTerType: number;
text: string;
}): Uint8Array {
const srcTerType = params.srcTerType ?? DATALINE_SELF_TER_TYPE;
const textBytes = textEncoder.encode(params.text);
const buf = protobuf_encode<DatalineTextMsg>({
items: [{ type: DATALINE_TEXT_ITEM, text: textBytes }],
});
const selfUin = BigInt(params.selfUin);
return protobuf_encode<DatalineMsgBody>({
subCmd: DATALINE_SUBCMD_GENERIC,
header: {
srcAppId: appIdForTerType(srcTerType),
srcInstId: 1,
dstAppId: appIdForTerType(params.dstTerType),
dstInstId: 1,
dstUin: selfUin,
srcUin: selfUin,
srcTerType,
dstTerType: params.dstTerType,
},
generic: {
sessionId: BigInt(Date.now()),
size: 1,
index: 0,
type: DATALINE_GENERIC_TEXT,
buf,
},
});
}
export function decodeDatalineMsgBody(bytes: Uint8Array): DatalineMsgBody | undefined {
return protobuf_decode<DatalineMsgBody>(bytes);
}
export function elementsFromDatalineBody(body: DatalineMsgBody): MessageElement[] {
const elements: MessageElement[] = [];
if (body.subCmd === DATALINE_SUBCMD_GENERIC || body.generic) {
const genericType = body.generic?.type ?? 0;
if (genericType === 0 || genericType === DATALINE_GENERIC_TEXT) {
const text = decodeGenericText(body.generic?.buf);
if (text.length > 0) elements.push({ type: 'text', text });
}
}
if (body.subCmd === DATALINE_SUBCMD_FTN || (body.ftn && body.ftn.length > 0)) {
for (const notify of body.ftn ?? []) {
const fileName = notify.fileName?.trim();
if (!fileName && notify.fileIndex == null && notify.sessionId == null) continue;
const fileSize = notify.fileLen != null ? Number(notify.fileLen) : undefined;
elements.push({
type: 'file',
fileId: notify.fileIndex || (notify.sessionId != null ? String(notify.sessionId) : undefined),
fileName: fileName || undefined,
fileSize: fileSize != null && Number.isFinite(fileSize) ? fileSize : undefined,
md5Hex: notify.fileMd5 && notify.fileMd5.length > 0 ? toHex(notify.fileMd5) : undefined,
});
}
}
return elements;
}
function decodeGenericText(buf: Uint8Array | undefined): string {
if (!buf || buf.length === 0) return '';
const parsed = protobuf_decode<DatalineTextMsg>(buf);
const parts: string[] = [];
for (const item of parsed?.items ?? []) {
if (!item.text || item.text.length === 0) continue;
parts.push(textDecoder.decode(item.text));
}
return parts.join('');
}
export function datalineTextFromElements(elements: readonly MessageElement[]): string {
if (elements.length === 0) throw new Error('message is empty');
const unsupported = elements.find((element) => element.type !== 'text');
if (unsupported) {
throw new Error(`this contact only accepts text messages, got ${unsupported.type}`);
}
const text = elements
.filter((element): element is Extract<MessageElement, { type: 'text' }> => element.type === 'text')
.map((element) => element.text)
.join('');
if (text.length === 0) throw new Error('message is empty');
return text;
}
@@ -0,0 +1,58 @@
import type { FriendMessage } from '../events';
import type { MsgPushContext } from '../msg-push/context';
import { decodeDatalineMsgBody, elementsFromDatalineBody } from './codec';
import {
DATALINE_SELF_TER_TYPE,
findDatalineDeviceByTerType,
} from './device-contacts';
/**
* Incoming my-device chats reuse the private-file push type but carry a
* different body. Rewrite the conversation peer onto the matching device
* contact — both sides of the wire use the logged-in account number.
*/
export function tryDecodeDatalineFriendMessage(ctx: MsgPushContext): FriendMessage | null {
if (ctx.head.msgType !== 529 || ctx.head.subType !== 7) return null;
const raw = ctx.body?.msgContent;
if (!raw || raw.length === 0) return null;
const body = decodeDatalineMsgBody(raw);
if (!body) return null;
if (
body.subCmd == null
&& !body.header
&& !body.generic
&& !(body.ftn && body.ftn.length > 0)
) {
return null;
}
const elements = elementsFromDatalineBody(body);
const srcTer = body.header?.srcTerType ?? 0;
const dstTer = body.header?.dstTerType ?? 0;
const sentBySelf = srcTer === DATALINE_SELF_TER_TYPE;
const peerTer = peerTerType(srcTer, dstTer);
const peer = findDatalineDeviceByTerType(peerTer);
const sequenceAuthoritative = ctx.head.ntMsgSeq > 0;
return {
kind: 'friend_message',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
senderUin: sentBySelf ? ctx.selfUin : (peer?.uin ?? ctx.fromUin),
senderUid: sentBySelf ? ctx.fromUid : (peer?.uid ?? ctx.fromUid),
...(peer ? { peerUin: peer.uin } : {}),
msgSeq: ctx.head.sequence,
ntMsgSeq: ctx.head.ntMsgSeq,
clientSeq: ctx.head.sequence,
sequenceAuthoritative,
msgId: ctx.head.msgId & 0x7FFFFFFF,
elements,
senderNick: sentBySelf ? '' : (peer?.name ?? ''),
};
}
function peerTerType(srcTer: number, dstTer: number): number {
if (srcTer !== DATALINE_SELF_TER_TYPE && srcTer > 0) return srcTer;
if (dstTer !== DATALINE_SELF_TER_TYPE && dstTer > 0) return dstTer;
return dstTer || srcTer || DATALINE_SELF_TER_TYPE;
}
@@ -0,0 +1,81 @@
/** Official "my computer / my phone / my Pad" device contacts. */
export const DATALINE_SELF_TER_TYPE = 1;
export const DATALINE_TER_PC = 1;
export const DATALINE_TER_PHONE = 2;
export const DATALINE_TER_PAD = 3;
/** Stable OneBot user_ids reserved for the three official device peers. */
export const DATALINE_UIN_PC = 0x7E000001;
export const DATALINE_UIN_PHONE = 0x7E000002;
export const DATALINE_UIN_PAD = 0x7E000003;
export interface DatalineDeviceContact {
readonly terType: number;
readonly uid: string;
readonly name: string;
readonly uin: number;
}
export interface DatalineFriendEntry {
user_id: number;
nickname: string;
remark: string;
}
export const DATALINE_DEVICES: readonly DatalineDeviceContact[] = [
{
terType: DATALINE_TER_PC,
uid: 'u_rK7NMsbv2ZjEGPdCuOiCfw',
name: '我的电脑',
uin: DATALINE_UIN_PC,
},
{
terType: DATALINE_TER_PHONE,
uid: 'u_Wcc5rknRRqRO8y5gxMD6sA',
name: '我的手机',
uin: DATALINE_UIN_PHONE,
},
{
terType: DATALINE_TER_PAD,
uid: 'u_l7jpPIZxQo0mzJwoEt-SKw',
name: '我的Pad',
uin: DATALINE_UIN_PAD,
},
];
const BY_UIN = new Map(DATALINE_DEVICES.map((device) => [device.uin, device]));
const BY_TER = new Map(DATALINE_DEVICES.map((device) => [device.terType, device]));
export function findDatalineDeviceByUin(uin: number): DatalineDeviceContact | undefined {
return BY_UIN.get(uin);
}
export function findDatalineDeviceByTerType(terType: number): DatalineDeviceContact | undefined {
return BY_TER.get(terType);
}
export function isDatalineDeviceUin(uin: number): boolean {
return BY_UIN.has(uin);
}
export function datalineFriendListEntries(): DatalineFriendEntry[] {
return DATALINE_DEVICES.map((device) => ({
user_id: device.uin,
nickname: device.name,
remark: device.name,
}));
}
export function appendDatalineFriendEntries<T extends { user_id: number }>(
friends: readonly T[],
): Array<T | DatalineFriendEntry> {
const occupied = new Set(friends.map((friend) => friend.user_id));
const extras = datalineFriendListEntries().filter((entry) => !occupied.has(entry.user_id));
return extras.length === 0 ? [...friends] : [...friends, ...extras];
}
export function appIdForTerType(terType: number): number {
return terType === DATALINE_TER_PC ? 1 : 1001;
}
@@ -1,3 +1,4 @@
import { tryDecodeDatalineFriendMessage } from '../../dataline/decode-push';
import type { FriendMessage } from '../../events';
import type { MsgPushDecoder } from '../registry';
import { decodeRichBody } from '../rich-body-decoder';
@@ -24,6 +25,9 @@ function parseGroupInviteCard(jsonText: string): { groupUin: number; sequence: n
}
export const decodeFriendMessage: MsgPushDecoder = (ctx) => {
const dataline = tryDecodeDatalineFriendMessage(ctx);
if (dataline) return [dataline];
const elements = decodeRichBody(ctx.body, false);
const sentBySelf = ctx.fromUin > 0 && ctx.fromUin === ctx.selfUin;
const peerUin = sentBySelf ? (ctx.responseHead?.toUin ?? 0) : ctx.fromUin;
+164
View File
@@ -0,0 +1,164 @@
import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { DatalineMsgBody, DatalineTextMsg } from '@snowluma/proto-defs/dataline';
import type { PushMsg, PushMsgBody } from '@snowluma/proto-defs/message';
import { protobuf_encode } from '@snowluma/proton';
import { describe, expect, it } from 'vitest';
import { encodeDatalineText } from '../src/dataline/codec';
import {
DATALINE_UIN_PAD,
DATALINE_UIN_PHONE,
} from '../src/dataline/device-contacts';
import type { IdentityService } from '../src/identity-service';
import { parseMsgPush } from '../src/msg-push';
const identity = { findFriend: () => undefined } as unknown as IdentityService;
const encoder = new TextEncoder();
function pushPacket(message: PushMsgBody): PacketInfo {
return {
pid: 0,
uin: '2000000001',
serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush',
seqId: 0,
retCode: 0,
fromClient: false,
body: protobuf_encode<PushMsg>({ message }),
};
}
function datalinePush(
body: DatalineMsgBody,
extras: Partial<PushMsgBody> = {},
): PacketInfo {
return pushPacket({
responseHead: { fromUin: 2000000001, fromUid: 'u_self' },
contentHead: {
msgType: 529,
subType: 7,
sequence: 11,
ntMsgSeq: 22,
timestamp: 1710000000,
msgId: 33,
},
body: { msgContent: protobuf_encode<DatalineMsgBody>(body) },
...extras,
});
}
function textBuf(text: string): Uint8Array {
return protobuf_encode<DatalineTextMsg>({
items: [{ type: 1, text: encoder.encode(text) }],
});
}
describe('dataline my-device chats', () => {
it('decodes an incoming Pad text push as a named device peer', () => {
const out = parseMsgPush(datalinePush({
subCmd: 4,
header: {
srcAppId: 1001,
srcInstId: 1,
dstAppId: 1,
dstInstId: 1,
dstUin: 2000000001n,
srcUin: 2000000001n,
srcTerType: 3,
dstTerType: 1,
},
generic: {
sessionId: 1n,
size: 1,
index: 0,
type: 1,
buf: textBuf('from pad'),
},
}), identity);
expect(out).toHaveLength(1);
expect(out[0]).toMatchObject({
kind: 'friend_message',
senderUin: DATALINE_UIN_PAD,
senderUid: 'u_l7jpPIZxQo0mzJwoEt-SKw',
peerUin: DATALINE_UIN_PAD,
senderNick: '我的Pad',
elements: [{ type: 'text', text: 'from pad' }],
});
});
it('treats a self-originated device text as a message_sent-style peer rewrite', () => {
const out = parseMsgPush(datalinePush({
subCmd: 4,
header: {
srcAppId: 1,
srcInstId: 1,
dstAppId: 1001,
dstInstId: 1,
dstUin: 2000000001n,
srcUin: 2000000001n,
srcTerType: 1,
dstTerType: 2,
},
generic: {
sessionId: 2n,
size: 1,
index: 0,
type: 1,
buf: textBuf('to phone'),
},
}), identity);
expect(out[0]).toMatchObject({
kind: 'friend_message',
senderUin: 2000000001,
senderUid: 'u_self',
peerUin: DATALINE_UIN_PHONE,
senderNick: '',
elements: [{ type: 'text', text: 'to phone' }],
});
});
it('surfaces a device file notify as a file element', () => {
const out = parseMsgPush(datalinePush({
subCmd: 1,
header: {
srcTerType: 2,
dstTerType: 1,
srcUin: 2000000001n,
dstUin: 2000000001n,
},
ftn: [{
sessionId: 9n,
fileName: 'shot.png',
fileIndex: 'ftn-1',
fileLen: 32n,
}],
}), identity);
expect(out[0]).toMatchObject({
kind: 'friend_message',
senderUin: DATALINE_UIN_PHONE,
senderNick: '我的手机',
elements: [{ type: 'file', fileId: 'ftn-1', fileName: 'shot.png', fileSize: 32 }],
});
});
it('round-trips outbound device text through the same decoder', () => {
const encoded = encodeDatalineText({
selfUin: 2000000001,
dstTerType: 2,
text: 'hello phone',
});
const out = parseMsgPush(pushPacket({
responseHead: { fromUin: 2000000001, fromUid: 'u_self' },
contentHead: { msgType: 529, subType: 7, sequence: 1, timestamp: 1, msgId: 1 },
body: { msgContent: encoded },
}), identity);
expect(out[0]).toMatchObject({
kind: 'friend_message',
senderUin: 2000000001,
peerUin: DATALINE_UIN_PHONE,
elements: [{ type: 'text', text: 'hello phone' }],
});
});
});