Files
SnowLuma/packages/core/tests/bridge-private-routing.test.ts
T
DrSmoothl 1db287d8cc 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.
2026-05-19 23:45:40 +08:00

129 lines
5.3 KiB
TypeScript

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' } }]),
}));
describe('Bridge private media routing', () => {
it('includes resolved uid in the final c2c send request for media messages', async () => {
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 resolveUserUid(uin: number): Promise<string> {
expect(uin).toBe(12345);
return 'u_peer_12345';
}
override async sendRawPacket(serviceCmd: string, body: Uint8Array): Promise<SendPacketResult> {
expect(serviceCmd).toBe('MessageSvc.PbSendMsg');
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'));
await bridge.sendPrivateMessage(12345, [{ type: 'video', url: 'file:///tmp/clip.mp4' } as any]);
expect(bridge.capturedBody).toBeInstanceOf(Uint8Array);
const request = protoDecode(bridge.capturedBody as Uint8Array, SendMessageRequestSchema);
expect(request?.routingHead?.c2c).toMatchObject({
uin: 12345,
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);
});
});