From 02de2acea4172e5f882c68291ab6c2751612efe7 Mon Sep 17 00:00:00 2001 From: Airline233 Date: Thu, 25 Jun 2026 20:55:39 +0800 Subject: [PATCH] fix(core): support file sources in forwarded messages (#144) Pre-upload file/url/base64 segments for forwarded message nodes into the target scope, re-upload cached file_ids when crossing private/group scope, and suppress standalone file-message publishing during forward preparation. --- packages/core/src/bridge/apis/forward.ts | 143 ++++++++++- packages/core/src/bridge/apis/group-file.ts | 14 +- .../core/tests/actions/forward-file.test.ts | 222 +++++++++++++++++- .../core/tests/actions/group-file.test.ts | 44 ++++ 4 files changed, 401 insertions(+), 22 deletions(-) diff --git a/packages/core/src/bridge/apis/forward.ts b/packages/core/src/bridge/apis/forward.ts index c47d9aa9..dbd61704 100644 --- a/packages/core/src/bridge/apis/forward.ts +++ b/packages/core/src/bridge/apis/forward.ts @@ -14,7 +14,7 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import { randomUUID } from 'crypto'; import { gunzipSync, gzipSync } from 'zlib'; import type { Bridge } from '../bridge'; -import type { BridgeContext } from '../bridge-context'; +import type { BridgeContext, UploadedFileMeta } from '../bridge-context'; import { resolveSelfUid, toInt } from './shared'; function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; } @@ -202,6 +202,46 @@ function previewFromElements(elements: MessageElement[]): string { return ''; } +function cloneNodeWithElements(node: ForwardNodePayload, elements: MessageElement[]): ForwardNodePayload { + return { + userUin: node.userUin, + nickname: node.nickname, + elements, + time: node.time, + msgId: node.msgId, + msgSeq: node.msgSeq, + groupId: node.groupId, + senderCard: node.senderCard, + messageType: node.messageType, + innerForward: node.innerForward, + }; +} + +function stripFileSource(element: MessageElement): MessageElement { + const next: MessageElement = { ...element }; + delete next.url; + return next; +} + +function isCachedFileUsableInTarget( + cached: UploadedFileMeta | undefined, + groupId?: number, + userId?: number, +): boolean { + if (!cached) return true; + if (groupId !== undefined) { + return cached.scope === 'group' && cached.groupId === groupId; + } + if (userId !== undefined) { + return cached.scope === 'private' && cached.userId === userId; + } + return true; +} + +function fileNameForUpload(element: MessageElement, cached?: UploadedFileMeta): string { + return (element.fileName ?? cached?.fileName ?? '').trim(); +} + export class ForwardApi { constructor(private readonly ctx: BridgeContext) { } @@ -210,6 +250,101 @@ export class ForwardApi { return resId; } + private async downloadSourceFromCachedFile(cached: UploadedFileMeta): Promise { + if (cached.scope === 'group' && cached.groupId !== undefined) { + return this.ctx.apis.groupFile.getUrl(cached.groupId, cached.fileId); + } + if (cached.scope === 'private' && cached.userId !== undefined && cached.fileHash) { + return this.ctx.apis.groupFile.getPrivateUrl(cached.userId, cached.fileId, cached.fileHash); + } + throw new Error('forward file_id belongs to another scope; pass file/base64/url so SnowLuma can re-upload it'); + } + + private async uploadForwardFileSource( + source: string, + name: string, + groupId?: number, + userId?: number, + ): Promise { + if (groupId !== undefined) { + const uploaded = await this.ctx.apis.groupFile.upload(groupId, source, name, '/', true, false); + if (!uploaded.fileId) throw new Error('forward group file upload returned no file_id'); + const cached = this.ctx.recallUploadedFile(uploaded.fileId); + const element: MessageElement = { + type: 'file', + fileId: uploaded.fileId, + }; + const fileName = cached?.fileName || name; + if (fileName) element.fileName = fileName; + if (cached?.fileSize !== undefined) element.fileSize = cached.fileSize; + return element; + } + if (userId !== undefined) { + const uploaded = await this.ctx.apis.groupFile.uploadPrivate(userId, source, name, true, false); + if (!uploaded.fileId) throw new Error('forward private file upload returned no file_id'); + const cached = this.ctx.recallUploadedFile(uploaded.fileId); + const element: MessageElement = { + type: 'file', + fileId: uploaded.fileId, + }; + const fileName = cached?.fileName || name; + const fileHash = uploaded.fileHash ?? cached?.fileHash ?? ''; + if (fileName) element.fileName = fileName; + if (cached?.fileSize !== undefined) element.fileSize = cached.fileSize; + if (fileHash) element.fileHash = fileHash; + return element; + } + throw new Error('forward file source requires group_id or user_id'); + } + + private async prepareForwardFileElement( + element: MessageElement, + groupId?: number, + userId?: number, + ): Promise { + if (element.type !== 'file') return element; + + const source = (element.url ?? '').trim(); + if (source && !element.fileId) { + const uploaded = await this.uploadForwardFileSource(source, fileNameForUpload(element), groupId, userId); + return { + ...stripFileSource(element), + ...uploaded, + }; + } + + if (element.fileId) { + const cached = this.ctx.recallUploadedFile(element.fileId); + if (isCachedFileUsableInTarget(cached, groupId, userId)) return element; + const sourceFromCache = await this.downloadSourceFromCachedFile(cached!); + const uploaded = await this.uploadForwardFileSource( + sourceFromCache, + fileNameForUpload(element, cached), + groupId, + userId, + ); + return { + ...stripFileSource(element), + ...uploaded, + }; + } + + return element; + } + + private async prepareForwardFiles( + nodes: ForwardNodePayload[], + groupId?: number, + userId?: number, + ): Promise { + return Promise.all(nodes.map(async (node) => { + const elements = await Promise.all(node.elements.map( + element => this.prepareForwardFileElement(element, groupId, userId), + )); + return cloneNodeWithElements(node, elements); + })); + } + /** * Recursive upload with NapCat-style piggyback. Each invocation: * 1. Walks `nodes`. For any node whose `innerForward` is set, @@ -304,8 +439,10 @@ export class ForwardApi { } } + const uploadReadyNodes = await this.prepareForwardFiles(processedNodes, groupId, userId); + // Encode this level's msgBody. - const msgBody = await Promise.all(processedNodes.map( + const msgBody = await Promise.all(uploadReadyNodes.map( node => buildForwardPushBody(bridge, node, groupId, userUid), )); @@ -349,7 +486,7 @@ export class ForwardApi { throw new Error('upload forward message response missing res_id'); } - forwardResCache.set(resId, processedNodes.map(node => ({ + forwardResCache.set(resId, uploadReadyNodes.map(node => ({ userUin: node.userUin, nickname: node.nickname, elements: [...node.elements], diff --git a/packages/core/src/bridge/apis/group-file.ts b/packages/core/src/bridge/apis/group-file.ts index bbdddb49..cac85589 100644 --- a/packages/core/src/bridge/apis/group-file.ts +++ b/packages/core/src/bridge/apis/group-file.ts @@ -241,6 +241,7 @@ export class GroupFileApi { name = '', folderId = '/', uploadFile = true, + publishFile = uploadFile, ): Promise { const bridge = asBridge(this.ctx); // Group/private files may legitimately be up to 4 GiB on QQ's wire, @@ -316,11 +317,11 @@ export class GroupFileApi { // the chat shows nothing. The publish step goes via a dedicated OIDB // call (0x6D9_4), NOT via `MessageSvc.PbSendMsg` with a transElem(24) // payload — the QQ-NT server rejects that with `result=79`. Mirrors - // Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when the - // caller opts out via `uploadFile=false` (treat that as "I only - // wanted the slot allocated, hold the chat post"). Routes through - // `this.publish` so tests can mock at the same Api boundary. - if (uploadFile) { + // Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when a + // caller only needs a valid file_id embedded elsewhere, e.g. a + // forward-message long-msg payload. Routes through `this.publish` so + // tests can mock at the same Api boundary. + if (publishFile) { try { await this.publish(groupId, fileId); } catch (err) { @@ -341,6 +342,7 @@ export class GroupFileApi { source: string, name = '', uploadFile = true, + publishFile = uploadFile, ): Promise { const bridge = asBridge(this.ctx); const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES); @@ -482,7 +484,7 @@ export class GroupFileApi { // which only knows about elems[]. NapCat does the same atomic // upload+send dance — without it the file sits on the server and // the recipient sees nothing. - if (uploadFile) { + if (publishFile) { try { await this.ctx.apis.message.sendC2cFile(userId, targetUid, { fileId, diff --git a/packages/core/tests/actions/forward-file.test.ts b/packages/core/tests/actions/forward-file.test.ts index dc67a058..408de67a 100644 --- a/packages/core/tests/actions/forward-file.test.ts +++ b/packages/core/tests/actions/forward-file.test.ts @@ -24,6 +24,7 @@ // split. import { describe, it, expect, vi } from 'vitest'; +import { gunzipSync } from 'zlib'; vi.mock('@snowluma/protocol/bridge-oidb', () => ({ runOidb: vi.fn(async () => new Uint8Array()), @@ -44,8 +45,9 @@ vi.mock('@snowluma/protocol/element-builder', () => ({ buildSendElems: buildSendElemsMock, })); -import { protobuf_encode } from '@snowluma/proton'; -import type { SendLongMsgResp } from '@snowluma/proto-defs/longmsg'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { LongMsgResult, SendLongMsgReq, SendLongMsgResp } from '@snowluma/proto-defs/longmsg'; +import type { FileExtra } from '@snowluma/proto-defs/message'; import { ForwardApi } from '../../src/bridge/apis/forward'; import { mockBridge } from './_helpers'; @@ -60,6 +62,13 @@ function uploadResponseWithResId(resId: string) { }; } +function decodeLongMsgRequest(rawBytes: Uint8Array): LongMsgResult { + const env = protobuf_decode(rawBytes); + const payload = env.info?.payload; + if (!(payload instanceof Uint8Array)) throw new Error('payload missing on SendLongMsgReq'); + return protobuf_decode(gunzipSync(Buffer.from(payload))); +} + describe('actions/forward — file segment inside forward node', () => { it('group forward sets forwardFake:true on the SendContext so transElem(24) is emitted', async () => { // Group case: the file element rides on elems[] as transElem(24). @@ -120,18 +129,19 @@ describe('actions/forward — file segment inside forward node', () => { expect(ctx).toMatchObject({ forwardFake: true }); expect(ctx?.groupId).toBeUndefined(); - // Spot-check that the upload body carries the file metadata. The - // payload is gzipped + protobuf-wrapped, so we just verify the - // raw filename string survived — that's enough to confirm the - // FileExtra branch ran (a "missing file" regression would drop - // these bytes entirely). expect(captured).toBeDefined(); - const flat = Buffer.from(captured!).toString('binary'); - // The filename gets gzipped, so we can't substring-search; instead - // assert the body is large enough that the FileExtra wasn't elided. - // (A name-only forward with no msgContent runs ~80-100 bytes; with - // the FileExtra blob it's noticeably larger.) - expect(flat.length).toBeGreaterThan(80); + const longMsg = decodeLongMsgRequest(captured!); + const body = longMsg.action?.[0]?.actionData?.msgBody?.[0]?.body; + expect(body?.msgContent).toBeInstanceOf(Uint8Array); + expect(body?.richText?.notOnlineFile ?? undefined).toBeUndefined(); + + const fileExtra = protobuf_decode(body!.msgContent as Uint8Array); + expect(fileExtra.file).toMatchObject({ + fileUuid: 'pfid-1', + fileName: 'invoice.pdf', + fileHash: 'srv-hash-abc', + }); + expect(fileExtra.file?.fileSize).toBe(4096n); }); it('c2c forward falls back to the upload metadata cache when inline fields are missing', async () => { @@ -165,4 +175,190 @@ describe('actions/forward — file segment inside forward node', () => { expect(recallUploadedFile).toHaveBeenCalledWith('pfid-cached'); }); + + it('group forward pre-uploads file sources into the target group without publishing a separate file message', async () => { + buildSendElemsMock.mockClear(); + const upload = vi.fn(async () => ({ fileId: 'gfid-from-base64' })); + const publish = vi.fn(); + const bridge = mockBridge({ + sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-grp-source')) as any, + apis: { + ...mockBridge().apis, + groupFile: { + ...mockBridge().apis.groupFile, + upload, + publish, + }, + }, + recallUploadedFile: vi.fn((id: string) => id === 'gfid-from-base64' ? { + fileId: 'gfid-from-base64', + scope: 'group' as const, + groupId: 12345, + fileName: 'note.txt', + fileSize: 3, + fileMd5: new Uint8Array(16), + fileSha1: new Uint8Array(20), + rememberedAt: 0, + } : undefined), + }); + + await new ForwardApi(bridge as any).upload([{ + userUin: 10001, + nickname: 'alice', + elements: [{ type: 'file', url: 'base64://AQID', fileName: 'note.txt' } as any], + }], 12345); + + expect(upload).toHaveBeenCalledWith(12345, 'base64://AQID', 'note.txt', '/', true, false); + expect(publish).not.toHaveBeenCalled(); + const [elements] = buildSendElemsMock.mock.calls[0]!; + expect(elements).toEqual([expect.objectContaining({ + type: 'file', + fileId: 'gfid-from-base64', + fileName: 'note.txt', + fileSize: 3, + })]); + }); + + it('private forward pre-uploads file sources without sending a standalone c2c file message', async () => { + buildSendElemsMock.mockClear(); + const uploadPrivate = vi.fn(async () => ({ fileId: 'pfid-from-base64', fileHash: 'phash' })); + const sendC2cFile = vi.fn(); + const bridge = mockBridge({ + sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-c2c-source')) as any, + apis: { + ...mockBridge().apis, + message: { + ...mockBridge().apis.message, + sendC2cFile, + }, + groupFile: { + ...mockBridge().apis.groupFile, + uploadPrivate, + }, + }, + recallUploadedFile: vi.fn((id: string) => id === 'pfid-from-base64' ? { + fileId: 'pfid-from-base64', + scope: 'private' as const, + userId: 67890, + fileName: 'note.txt', + fileSize: 3, + fileMd5: new Uint8Array(16), + fileSha1: new Uint8Array(20), + fileHash: 'phash', + rememberedAt: 0, + } : undefined), + }); + + await new ForwardApi(bridge as any).upload([{ + userUin: 10001, + nickname: 'alice', + elements: [{ type: 'file', url: 'base64://AQID', fileName: 'note.txt' } as any], + }], undefined, 67890); + + expect(uploadPrivate).toHaveBeenCalledWith(67890, 'base64://AQID', 'note.txt', true, false); + expect(sendC2cFile).not.toHaveBeenCalled(); + const [elements] = buildSendElemsMock.mock.calls[0]!; + expect(elements).toEqual([expect.objectContaining({ + type: 'file', + fileId: 'pfid-from-base64', + fileName: 'note.txt', + fileSize: 3, + fileHash: 'phash', + })]); + }); + + it('private file forward keeps the long-msg upload under the self uid namespace', async () => { + buildSendElemsMock.mockClear(); + let captured: Uint8Array | undefined; + const bridge = mockBridge({ + sendRawPacket: vi.fn(async (_cmd: string, body: Uint8Array) => { + captured = body; + return uploadResponseWithResId('res-c2c-target-uid'); + }) as any, + resolveUserUid: vi.fn(async () => 'target-uid'), + recallUploadedFile: vi.fn((id: string) => id === 'pfid-1' ? { + fileId: 'pfid-1', + scope: 'private' as const, + userId: 67890, + fileName: 'invoice.pdf', + fileSize: 4096, + fileMd5: new Uint8Array(16), + fileSha1: new Uint8Array(20), + fileHash: 'srv-hash', + rememberedAt: 0, + } : undefined), + }); + + await new ForwardApi(bridge as any).upload([{ + userUin: 10001, + nickname: 'alice', + elements: [{ type: 'file', fileId: 'pfid-1' } as any], + }], undefined, 67890); + + expect(bridge.resolveUserUid).not.toHaveBeenCalled(); + expect(captured).toBeDefined(); + const request = protobuf_decode(captured!); + expect(request.info?.uid?.uid).toBe('self-uid'); + }); + + it('group forward re-uploads a cached private file_id into the target group scope', async () => { + buildSendElemsMock.mockClear(); + const getPrivateUrl = vi.fn(async () => 'https://download.test/private-file'); + const upload = vi.fn(async () => ({ fileId: 'gfid-reuploaded' })); + const bridge = mockBridge({ + sendRawPacket: vi.fn(async () => uploadResponseWithResId('res-cross-scope')) as any, + apis: { + ...mockBridge().apis, + groupFile: { + ...mockBridge().apis.groupFile, + getPrivateUrl, + upload, + }, + }, + recallUploadedFile: vi.fn((id: string) => { + if (id === 'pfid-cached') { + return { + fileId: 'pfid-cached', + scope: 'private' as const, + userId: 67890, + fileName: 'cached.txt', + fileSize: 5, + fileMd5: new Uint8Array(16), + fileSha1: new Uint8Array(20), + fileHash: 'cached-hash', + rememberedAt: 0, + }; + } + if (id === 'gfid-reuploaded') { + return { + fileId: 'gfid-reuploaded', + scope: 'group' as const, + groupId: 12345, + fileName: 'cached.txt', + fileSize: 5, + fileMd5: new Uint8Array(16), + fileSha1: new Uint8Array(20), + rememberedAt: 1, + }; + } + return undefined; + }), + }); + + await new ForwardApi(bridge as any).upload([{ + userUin: 10001, + nickname: 'alice', + elements: [{ type: 'file', fileId: 'pfid-cached' } as any], + }], 12345); + + expect(getPrivateUrl).toHaveBeenCalledWith(67890, 'pfid-cached', 'cached-hash'); + expect(upload).toHaveBeenCalledWith(12345, 'https://download.test/private-file', 'cached.txt', '/', true, false); + const [elements] = buildSendElemsMock.mock.calls[0]!; + expect(elements).toEqual([expect.objectContaining({ + type: 'file', + fileId: 'gfid-reuploaded', + fileName: 'cached.txt', + fileSize: 5, + })]); + }); }); diff --git a/packages/core/tests/actions/group-file.test.ts b/packages/core/tests/actions/group-file.test.ts index adf18667..7b18ef34 100644 --- a/packages/core/tests/actions/group-file.test.ts +++ b/packages/core/tests/actions/group-file.test.ts @@ -170,6 +170,28 @@ describe('apis/group-file', () => { expect(publishSpy).not.toHaveBeenCalled(); }); + it('upload can PUT bytes without publishing a separate group file message', async () => { + const bridge = mockBridge(); + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( + protobuf_encode>({ + body: { + upload: { + fileId: 'fid-forward', + uploadIp: '127.0.0.1', + uploadPort: 443, + fileKey: new Uint8Array([1]), + checkKey: new Uint8Array([2]), + } as any, + }, + }), + )); + const api = new GroupFileApi(bridge as any); + const publishSpy = vi.spyOn(api, 'publish').mockResolvedValue(); + await api.upload(12345, 'base64://AQID', 'forward.txt', '/', true, false); + expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce(); + expect(publishSpy).not.toHaveBeenCalled(); + }); + it('upload returns success even when the chat post fails (file is still uploaded)', async () => { const bridge = mockBridge(); bridge.sendRawPacket.mockResolvedValueOnce(packResponse( @@ -298,6 +320,28 @@ describe('apis/group-file', () => { expect(bridge.apis.message.sendC2cFile).not.toHaveBeenCalled(); }); + it('uploadPrivate can PUT bytes without publishing a separate c2c file message', async () => { + const bridge = mockBridge(); + vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid'); + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( + protobuf_encode>({ + body: { + upload: { + uuid: 'pfid-forward', + fileAddon: 'phash-forward', + rtpMediaPlatformUploadAddress: [ + { outIP: 0, outPort: 0, inIP: 16885952, inPort: 8080, iPType: 1 }, + ], + mediaPlatformUploadKey: new Uint8Array([1, 2, 3]), + } as any, + }, + }), + )); + await new GroupFileApi(bridge as any).uploadPrivate(67890, 'base64://AQID', 'forward.txt', true, false); + expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce(); + expect(bridge.apis.message.sendC2cFile).not.toHaveBeenCalled(); + }); + it('uploadPrivate reads host from rtpMediaPlatformUploadAddress[0].inIP when populated', async () => { const bridge = mockBridge(); vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');