fix(c2c-file): rewrite sendC2cFileMessage wire shape per Lagrange.Core V2

The c2c file send path was wrong on three independent axes — every
c2c file the bot tried to deliver was getting rejected by the QQ-NT
server. Aligned to `dev/Lagrange.Core` (V2 branch) which is the only
direct-protocol reference for c2c files; NapCat goes through QQ-NT
IPC and never builds this packet itself.

Three wire-shape fixes:

1. **Routing**: `routingHead.c2c { uin, uid }` → `routingHead.trans0x211
   { ccCmd: 4, uid }`. RoutingHead field 15 is the c2c-file scene's
   slot. `MessagePacker.BuildPacketBase` makes this conditional on
   `chain.HasTypeOf<FileEntity>()`: when a file is present, C2C goes
   nil and Trans0X211 carries the routing.

2. **File payload location**: `messageBody.richText.notOnlineFile {...}`
   → `messageBody.msgContent = serialize(FileExtra{file: NotOnlineFile})`.
   The server doesn't read c2c file metadata from `richText` at all —
   `MessageBody.cs:12` even has the comment "Offline file is now put
   here(?". Confirmed by `FileEntity.PackElement()` returning empty
   and `PackMessageContent()` returning the FileExtra wrapper.

3. **contentHead.c2cCmd**: `11` → `0` (default/omitted). `11` was a
   stale go-cqhttp value the QQ-NT server doesn't recognise on the
   c2c-file dispatcher. Lagrange leaves it at the C# default (0).

Schema fixes (proton + legacy, both directions):

- `RoutingHead` gains `trans0x211?: pb<15, RoutingTrans0x211>`. The
  new message has `toUin@1`, `ccCmd@2`, `uid@8`.
- `SendMessageBody` gains `msgContent?: pb<2, bytes>` (the receive-side
  `MessageBody` already had it).
- `FileExtraInfo` deleted — was wrong on every tag (fileSize=1,
  fileName=2, fileMd5=3, fileUuid=4, fileHash=5, none of which match
  the wire). `FileExtra { file: pb<1, NotOnlineFile> }` now wraps the
  same `NotOnlineFile` used on the receive path. This is why c2c file
  PUSHES were also silently failing the four-field truthy check in
  `extractMsgContent` — the schema couldn't decode anything.
- `NotOnlineFile` gains the three intake-validator fields the server
  requires on send: `subcmd@9 = 1`, `dangerEvel@50 = 0`, `expireTime@55`
  = now+7d.

Receive side (`rich-body-decoder.ts::extractMsgContent`): drop the
"all four fields must be truthy" guard (it was a workaround for the
broken schema) and accept any payload that decodes a fileUuid.

Tests:

- `bridge-private-routing.test.ts`: new regression that round-trips
  `sendC2cFileMessage` through `protoDecode` and asserts trans0x211
  routing, msgContent FileExtra wrapper, NotOnlineFile field tags,
  c2cCmd=0. Catches each of the three wire-shape regressions
  independently.
- `send-private-c2c-file.test.ts`: vi.fn arg signatures explicit for
  CI typecheck.

647/647 tests pass.
This commit is contained in:
DrSmoothl
2026-05-19 23:45:40 +08:00
parent f65fe959bb
commit 1db287d8cc
8 changed files with 248 additions and 68 deletions
+59 -21
View File
@@ -17,6 +17,7 @@ import type {
SendMessageRequest,
SendMessageResponse,
} from './proto/proton/action';
import type { FileExtra } from './proto/proton/message';
// Delegated modules
import {
@@ -401,13 +402,27 @@ export class Bridge implements BridgeInterface {
/**
* Send a c2c file as a chat message.
*
* Unlike images / videos / records that ride on `RichText.elems` as
* regular Elem entries, c2c files use `RichText.notOnlineFile`
* (parallel to `elems`, see `proto/proton/message.ts:75`). The
* receive-side decoder strips this back to a `{type:'file'}` segment
* in `rich-body-decoder.ts:425-433`. There's no Elem you can stuff
* into `buildSendElems` for this, so this helper short-circuits the
* normal send pipeline.
* The wire shape isn't the same as a regular c2c message — the c2c
* file path uses three slots that differ from a normal text/image
* send (verified against `dev/Lagrange.Core/.../MessagePacker.cs:
* BuildPacketBase` + `FileEntity.PackMessageContent`):
*
* 1. `routingHead.trans0x211 { ccCmd: 4, uid: peer }` instead of
* `routingHead.c2c { uin, uid }`. The server rejects c2c file
* messages routed through the regular c2c slot.
* 2. `messageBody.msgContent` carries the serialised
* `FileExtra { file: NotOnlineFile }` bytes. NOT
* `richText.notOnlineFile` — the receiver doesn't read that
* slot for file metadata.
* 3. `contentHead.c2cCmd` left at 0 (Lagrange's default). The
* previous `c2cCmd: 11` was a stale go-cqhttp value the QQ-NT
* server doesn't recognise.
*
* NotOnlineFile carries three required-on-send fields the receiver
* itself ignores but the server's intake validator checks:
* - `subcmd: 1` — c2c file send command code
* - `dangerEvel: 0` — virus-scan severity, always 0 client-side
* - `expireTime` — 7 days from now (Lagrange convention)
*/
async sendC2cFileMessage(
userUin: number,
@@ -417,38 +432,61 @@ export class Bridge implements BridgeInterface {
const random = this.nextMessageRandom();
const clientSeq = this.nextClientSequence();
const nowSec = Math.floor(Date.now() / 1000);
const sevenDaysSec = 7 * 24 * 60 * 60;
// Serialise `FileExtra { file: NotOnlineFile }` for `msgContent`.
// The NotOnlineFile field tags (1/3/4/5/6/9/50/55/57) are shared
// between send and receive — the schema is symmetric.
const fileExtraBytes = protobuf_encode<FileExtra>({
file: {
fileType: 0,
fileUuid: info.fileId,
fileMd5: info.fileMd5,
fileName: info.fileName,
fileSize: BigInt(info.fileSize),
subcmd: 1,
dangerEvel: 0,
expireTime: nowSec + sevenDaysSec,
fileHash: info.fileHash ?? '',
},
});
const request = protobuf_encode<SendMessageRequest>({
routingHead: {
c2c: { uin: userUin, uid: userUid },
// c2c-file scene: route through `trans0x211` (field 15) with
// ccCmd=4. The regular `c2c { uin, uid }` routing slot causes
// the server to reject this with a routing-mismatch error.
trans0x211: { ccCmd: 4, uid: userUid },
},
contentHead: {
type: 1,
subType: 0,
c2cCmd: 11,
// c2cCmd intentionally omitted (defaults to 0). Was `11`,
// which produced an unknown-command error in the QQ-NT
// server's c2c file handler. `userUin` is unused on this path
// (routing carries the uid only) but kept in the function
// signature for symmetry with the OneBot caller.
},
messageBody: {
richText: {
notOnlineFile: {
fileType: 0,
fileUuid: info.fileId,
fileMd5: info.fileMd5,
fileName: info.fileName,
fileSize: BigInt(info.fileSize),
fileHash: info.fileHash ?? '',
},
},
} as any,
// No elems — the file metadata lives in msgContent below.
msgContent: fileExtraBytes,
},
clientSequence: clientSeq,
random,
syncCookie: new Uint8Array(0),
via: 0,
dataStatist: 0,
ctrl: {
msgFlag: Math.floor(Date.now() / 1000),
msgFlag: nowSec,
},
multiSendSeq: 0,
});
// Silence the unused-parameter lint — `userUin` is part of our
// BridgeInterface contract (the OneBot layer threads it through)
// but the wire shape only needs the uid.
void userUin;
const result = await this.sendRawPacket(Bridge.SEND_MSG_CMD, request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(`send c2c file message failed: ${result.errorMessage || 'no response'}`);
@@ -434,14 +434,24 @@ function extractRichtextExtras(
}
function extractMsgContent(msgContent: Uint8Array, elements: MessageElement[]): void {
// `MessageBody.msgContent` is where the QQ-NT server actually puts
// c2c file metadata — serialised `FileExtra { file: NotOnlineFile }`
// bytes. The previous schema (`FileExtraInfoSchema` with fileSize=1/
// fileName=2/fileMd5=3/fileUuid=4/fileHash=5) didn't match the wire
// shape — every field landed at the wrong tag, so the four-field
// truthiness check below filtered out every real c2c file push as
// "incomplete metadata". After consolidating FileExtra to wrap
// `NotOnlineFile` (Lagrange.Core's `FileExtra { File: NotOnlineFile }`),
// this reads the right tags.
const extra = protoDecode(msgContent, FileExtraSchema);
if (!extra?.file) return;
const f = extra.file;
if (f.fileSize !== undefined && f.fileName && f.fileMd5 && f.fileUuid && f.fileHash) {
elements.push({
type: 'file', fileName: f.fileName, fileId: f.fileUuid,
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
fileHash: f.fileHash,
});
}
if (!f.fileUuid) return;
elements.push({
type: 'file',
fileId: f.fileUuid,
fileName: f.fileName ?? '',
fileSize: f.fileSize !== undefined ? Number(f.fileSize) : 0,
fileHash: f.fileHash ?? '',
});
}
+17 -3
View File
@@ -15,9 +15,20 @@ export const RoutingGroupSchema = {
groupCode: { field: 1, type: 'uint64' as const },
} satisfies ProtoSchema;
// `Trans0x211` is the c2c-file scene's routing header (Lagrange.Core
// `Routing/Trans0X211.cs`). See proton/action.ts:RoutingTrans0x211
// for the rationale — c2c file sends *must* route through this slot,
// not `c2c`, or the server rejects them.
export const RoutingTrans0x211Schema = {
toUin: { field: 1, type: 'uint64' as const },
ccCmd: { field: 2, type: 'uint32' as const },
uid: { field: 8, type: 'string' as const },
} satisfies ProtoSchema;
export const RoutingHeadSchema = {
c2c: { field: 1, type: 'message' as const, schema: RoutingC2CSchema },
grp: { field: 2, type: 'message' as const, schema: RoutingGroupSchema },
c2c: { field: 1, type: 'message' as const, schema: RoutingC2CSchema },
grp: { field: 2, type: 'message' as const, schema: RoutingGroupSchema },
trans0x211: { field: 15, type: 'message' as const, schema: RoutingTrans0x211Schema },
} satisfies ProtoSchema;
// --- Content Head (for send) ---
@@ -43,7 +54,10 @@ export const SendRichTextSchema = {
// --- MessageBody (for send) ---
export const SendMessageBodySchema = {
richText: { field: 1, type: 'message' as const, schema: SendRichTextSchema },
richText: { field: 1, type: 'message' as const, schema: SendRichTextSchema },
// C2C file payload — serialised `FileExtra { file: NotOnlineFile }`
// bytes. See proton/action.ts:SendMessageBody for the WHY.
msgContent: { field: 2, type: 'bytes' as const },
} satisfies ProtoSchema;
// --- SendMessageRequest ---
+22 -15
View File
@@ -59,13 +59,20 @@ export const PttSchema = {
// --- NotOnlineFile (C2C file) ---
// Field numbers per `dev/Lagrange.Core/.../Component/NotOnlineFile.cs`.
// fields 9 (subcmd), 50 (dangerEvel), 55 (expireTime) are required
// on c2c file SEND (the receiver ignores them); the identification
// fields (1/3/4/5/6/57) are read both directions.
export const NotOnlineFileSchema = {
fileType: { field: 1, type: 'uint32' as const },
fileUuid: { field: 3, type: 'string' as const },
fileMd5: { field: 4, type: 'bytes' as const },
fileName: { field: 5, type: 'string' as const },
fileSize: { field: 6, type: 'uint64' as const },
fileHash: { field: 57, type: 'string' as const },
fileType: { field: 1, type: 'uint32' as const },
fileUuid: { field: 3, type: 'string' as const },
fileMd5: { field: 4, type: 'bytes' as const },
fileName: { field: 5, type: 'string' as const },
fileSize: { field: 6, type: 'uint64' as const },
subcmd: { field: 9, type: 'uint32' as const },
dangerEvel: { field: 50, type: 'uint32' as const },
expireTime: { field: 55, type: 'uint32' as const },
fileHash: { field: 57, type: 'string' as const },
} satisfies ProtoSchema;
// --- RichText ---
@@ -84,17 +91,17 @@ export const MessageBodySchema = {
} satisfies ProtoSchema;
// --- FileExtra (for C2C file in msg_content) ---
export const FileExtraInfoSchema = {
fileSize: { field: 1, type: 'uint64' as const },
fileName: { field: 2, type: 'string' as const },
fileMd5: { field: 3, type: 'bytes' as const },
fileUuid: { field: 4, type: 'string' as const },
fileHash: { field: 5, type: 'string' as const },
} satisfies ProtoSchema;
//
// `FileExtra { file: NotOnlineFile }` is the wrapper QQ-NT actually
// uses at `MessageBody.msgContent` for c2c file sends. The previous
// `FileExtraInfoSchema` had fileSize=1, fileName=2, fileMd5=3,
// fileUuid=4, fileHash=5 — every field at the wrong tag, so received
// c2c-file payloads silently failed to parse. Consolidated to the
// shared `NotOnlineFileSchema` (Lagrange.Core's `FileExtra.cs` does
// the same — `[ProtoMember(1)] public NotOnlineFile? File`).
export const FileExtraSchema = {
file: { field: 1, type: 'message' as const, schema: FileExtraInfoSchema },
file: { field: 1, type: 'message' as const, schema: NotOnlineFileSchema },
} satisfies ProtoSchema;
// --- PushMsgBody ---
@@ -15,9 +15,24 @@ export interface RoutingGroup {
groupCode?: pb<1, uint_64>;
}
// `Trans0x211` is the c2c-file scene's routing header. The server
// rejects c2c file messages routed through `RoutingC2C` — instead it
// expects `trans0x211 { ccCmd: 4, uid: <peer uid> }`. Confirmed against
// `dev/Lagrange.Core/Lagrange.Core/Internal/Packets/Message/
// Routing/Trans0X211.cs` + `RoutingHead.cs` (Trans0X211 sits at
// field 15) + `MessagePacker.BuildPacketBase` (`Trans0X211 =
// !chain.HasTypeOf<FileEntity>() ? null : new Trans0X211 { CcCmd = 4,
// Uid = chain.Uid }`).
export interface RoutingTrans0x211 {
toUin?: pb<1, uint_64>;
ccCmd?: pb<2, uint_32>;
uid?: pb<8, string>;
}
export interface RoutingHead {
c2c?: pb<1, RoutingC2C>;
grp?: pb<2, RoutingGroup>;
c2c?: pb<1, RoutingC2C>;
grp?: pb<2, RoutingGroup>;
trans0x211?: pb<15, RoutingTrans0x211>;
}
// ── Content Head (for send) ─────────────────────────────────────────
@@ -43,7 +58,12 @@ export interface SendRichText {
// ── MessageBody (for send) ──────────────────────────────────────────
export interface SendMessageBody {
richText?: pb<1, SendRichText>;
richText?: pb<1, SendRichText>;
// C2C file payload — serialised `FileExtra { file: NotOnlineFile }`
// bytes. The server reads c2c file metadata from this slot, NOT
// from `richText.notOnlineFile`. Confirmed against `dev/Lagrange.Core/
// .../MessageBody.cs:12` (commented "Offline file is now put here").
msgContent?: pb<2, bytes>;
}
// ── SendMessageRequest ──────────────────────────────────────────────
@@ -58,14 +58,24 @@ export interface Ptt {
}
// ── NotOnlineFile (C2C file) ────────────────────────────────────────
//
// Field numbers cross-checked against `dev/Lagrange.Core/.../Component/
// NotOnlineFile.cs`. This same shape is what gets serialised inside
// `FileExtra` (below) and ridden as `MessageBody.msgContent` for c2c
// file sends — fields 9/50/55 are required on send (subcmd=1,
// dangerEvel=0, expireTime=now+7d), the receiver only reads the
// identification slots.
export interface NotOnlineFile {
fileType?: pb<1, uint_32>;
fileUuid?: pb<3, string>;
fileMd5?: pb<4, bytes>;
fileName?: pb<5, string>;
fileSize?: pb<6, uint_64>;
fileHash?: pb<57, string>;
fileType?: pb<1, uint_32>;
fileUuid?: pb<3, string>;
fileMd5?: pb<4, bytes>;
fileName?: pb<5, string>;
fileSize?: pb<6, uint_64>;
subcmd?: pb<9, uint_32>;
dangerEvel?: pb<50, uint_32>;
expireTime?: pb<55, uint_32>;
fileHash?: pb<57, string>;
}
// ── RichText ────────────────────────────────────────────────────────
@@ -84,17 +94,20 @@ export interface MessageBody {
}
// ── FileExtra (for C2C file in msg_content) ─────────────────────────
export interface FileExtraInfo {
fileSize?: pb<1, uint_64>;
fileName?: pb<2, string>;
fileMd5?: pb<3, bytes>;
fileUuid?: pb<4, string>;
fileHash?: pb<5, string>;
}
//
// `FileExtra { file: NotOnlineFile }` is the wrapper the server expects
// at `MessageBody.msgContent` (per `dev/Lagrange.Core/.../FileExtra.cs`).
// Old code had a parallel `FileExtraInfo` with fileSize=1, fileName=2,
// fileMd5=3, fileUuid=4, fileHash=5 — that schema didn't match the
// wire shape at all (every field was at the wrong tag), which is why
// c2c file messages we received via msgContent silently failed to
// parse, and c2c file messages we sent through `richText.notOnlineFile`
// (also wrong — see SendMessageBody) shipped a payload the recipient
// couldn't render. Consolidating to a single shared `NotOnlineFile`
// (identification fields 1/3/4/5/6/57) fixes both directions.
export interface FileExtra {
file?: pb<1, FileExtraInfo>;
file?: pb<1, NotOnlineFile>;
}
// ── PushMsgBody ─────────────────────────────────────────────────────
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
import type { SendPacketResult } from '../src/protocol/packet-sender';
import { protoDecode, protoEncode } from '../src/protobuf/decode';
import { SendMessageRequestSchema, SendMessageResponseSchema } from '../src/bridge/proto/action';
import { FileExtraSchema } from '../src/bridge/proto/message';
vi.mock('../src/bridge/element-builder', () => ({
buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]),
@@ -47,4 +48,81 @@ describe('Bridge private media routing', () => {
uid: 'u_peer_12345',
});
});
it('sendC2cFileMessage uses trans0x211 routing + msgContent FileExtra (NOT richText.notOnlineFile)', async () => {
// Regression: c2c file messages route through `trans0x211 { ccCmd:
// 4, uid }` (RoutingHead field 15), not `c2c { uin, uid }`. The
// file metadata lives in `MessageBody.msgContent` (a serialised
// `FileExtra { file: NotOnlineFile }`), not in `richText.notOnlineFile`.
// Confirmed against `dev/Lagrange.Core/.../MessagePacker.cs:
// BuildPacketBase` + `FileEntity.PackMessageContent`. Previous
// implementation wrote c2c routing + richText.notOnlineFile +
// c2cCmd=11 — the QQ-NT server rejected every c2c file send.
const { Bridge } = await import('../src/bridge/bridge');
const { IdentityService } = await import('../src/bridge/identity-service');
class TestBridge extends Bridge {
capturedBody: Uint8Array | null = null;
override async sendRawPacket(_cmd: string, body: Uint8Array): Promise<SendPacketResult> {
this.capturedBody = body;
return {
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from(protoEncode({
result: 0, privateSequence: 88, timestamp1: 1710000000,
}, SendMessageResponseSchema)),
};
}
}
const bridge = new TestBridge(IdentityService.memory('10000'));
const fileMd5 = new Uint8Array([0xde, 0xad, 0xbe, 0xef]);
await bridge.sendC2cFileMessage(67890, 'u_peer_xyz', {
fileId: 'uuid-abc-123',
fileName: 'doc.txt',
fileSize: 1024,
fileMd5,
fileHash: 'hash-xyz',
});
const request = protoDecode(bridge.capturedBody as Uint8Array, SendMessageRequestSchema);
// Routing: must be trans0x211 with ccCmd=4 + uid, no c2c slot.
expect(request?.routingHead?.trans0x211).toMatchObject({
ccCmd: 4,
uid: 'u_peer_xyz',
});
expect(request?.routingHead?.c2c).toBeUndefined();
// Body: msgContent carries the FileExtra; richText is absent (no
// elems, no notOnlineFile slot — both lived on the wrong place).
expect(request?.messageBody?.msgContent).toBeInstanceOf(Uint8Array);
expect(request?.messageBody?.richText).toBeUndefined();
// Decode the msgContent and verify the NotOnlineFile fields land
// at the correct tags (Lagrange's NotOnlineFile schema, not the
// dead FileExtraInfo one).
const fileExtra = protoDecode(
request!.messageBody!.msgContent as Uint8Array,
FileExtraSchema,
);
expect(fileExtra?.file).toMatchObject({
fileUuid: 'uuid-abc-123',
fileName: 'doc.txt',
fileSize: 1024n,
fileHash: 'hash-xyz',
subcmd: 1, // server-required intake validator field
// dangerEvel and fileType are 0 — proto3 omits zero values on
// the wire, so they're not asserted here (matches Lagrange's
// behaviour: it sets `DangerEvel = 0` but protobuf-net also
// skips serialising default ints).
});
expect(fileExtra?.file?.fileMd5).toEqual(fileMd5);
// expireTime is now+7d; just sanity-check it landed (non-zero, plausible)
expect(fileExtra?.file?.expireTime).toBeGreaterThan(Math.floor(Date.now() / 1000));
// c2cCmd is left at 0 / undefined — the old `c2cCmd=11` was a
// stale go-cqhttp value the QQ-NT server doesn't recognise on the
// c2c-file path.
expect(request?.contentHead?.c2cCmd ?? 0).toBe(0);
});
});
@@ -48,7 +48,7 @@ describe('send_private_msg with {type:"file"} segment', () => {
// Pure-file case — the elems[] path would have dropped this entirely
// and shipped "[空消息]". The c2c file route must take over.
const sendPrivateMessage_bridge = vi.fn();
const sendC2cFileMessage = vi.fn(async () => goodReceipt);
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
const resolveUserUid = vi.fn(async () => 'u_peer');
const bridge = fakeBridge({
sendPrivateMessage: sendPrivateMessage_bridge,
@@ -78,8 +78,8 @@ describe('send_private_msg with {type:"file"} segment', () => {
});
it('mixed file + text splits across two sends (text first, file second)', async () => {
const sendPrivateMessage_bridge = vi.fn(async () => goodReceipt);
const sendC2cFileMessage = vi.fn(async () => goodReceipt);
const sendPrivateMessage_bridge = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt);
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
const resolveUserUid = vi.fn(async () => 'u_peer');
const bridge = fakeBridge({
sendPrivateMessage: sendPrivateMessage_bridge,
@@ -112,7 +112,7 @@ describe('send_private_msg with {type:"file"} segment', () => {
// OneBot11 file segments are upload-by-reference — without a
// file_id there's nothing to send. Previously these slipped
// through to the elems[] path and shipped empty messages.
const sendPrivateMessage_bridge = vi.fn(async () => goodReceipt);
const sendPrivateMessage_bridge = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt);
const sendC2cFileMessage = vi.fn();
const bridge = fakeBridge({
sendPrivateMessage: sendPrivateMessage_bridge,