From a557bf72e75e7e792616a92d6a0bad33fea06e3f Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sat, 31 Oct 2026 18:00:50 +0800 Subject: [PATCH] fix(protocol): preserve private voice playback on older clients Keep private voice messages playable on older clients while retaining the existing voice message for current clients. Cover the reported upload response in a regression test. Refs #614 --- packages/core/src/bridge/apis/message.ts | 16 ++-- .../tests/actions/forward-metadata.test.ts | 2 +- .../core/tests/actions/forward-nested.test.ts | 2 +- .../core/tests/bridge-private-routing.test.ts | 9 +- packages/core/tests/element-builder.test.ts | 38 +++++++- .../issue-614-private-voice-upload.hex | 14 +++ .../core/tests/private-voice-wire.test.ts | 91 +++++++++++++++++++ packages/proto-defs/src/action.ts | 10 +- packages/proto-defs/src/highway.ts | 1 + packages/protocol/src/element-builder.ts | 64 ++++++++++--- packages/protocol/src/highway/ptt-upload.ts | 15 ++- 11 files changed, 223 insertions(+), 39 deletions(-) create mode 100644 packages/core/tests/fixtures/issue-614-private-voice-upload.hex create mode 100644 packages/core/tests/private-voice-wire.test.ts diff --git a/packages/core/src/bridge/apis/message.ts b/packages/core/src/bridge/apis/message.ts index 5092e1f7..298b05ed 100644 --- a/packages/core/src/bridge/apis/message.ts +++ b/packages/core/src/bridge/apis/message.ts @@ -8,7 +8,7 @@ import type { SsoReadedReportReq, SsoReadedReportResp, } from '@snowluma/proto-defs/oidb-actions/base'; -import { buildSendElems } from '@snowluma/protocol/element-builder'; +import { buildSendElems, encodePrivateRichText } from '@snowluma/protocol/element-builder'; import { assertWindowShakeSendPolicy } from '@snowluma/protocol/element-manifest'; import { FinalizeOfflineFile } from '@snowluma/protocol/oidb-services/group-file/finalize-offline-file'; import { datalineTextFromElements, encodeDatalineText } from '@snowluma/protocol/dataline/codec'; @@ -22,7 +22,7 @@ import { fetchC2cRoamMessagePage, fetchGroupMessageRange, } from '@snowluma/protocol/msg-push'; -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { type bytes, protobuf_decode, protobuf_encode } from '@snowluma/proton'; import { createLogger } from '@snowluma/common/logger'; import type { SendPacketResult } from '@snowluma/common/packet-sender'; import type { BridgeContext } from '../bridge-context'; @@ -548,15 +548,15 @@ export class MessageApi { userUid = await this.ctx.resolveUserUid(userUin); } - const protoElems = await buildSendElems(elements, { - bridge: this.ctx as unknown as Bridge, + const richText = await encodePrivateRichText(elements, { + bridge: this.ctx, userUid, scene: 'direct-private', }); const random = this.ctx.nextMessageRandom(); const clientSeq = this.ctx.nextClientSequence(); - const request = protobuf_encode({ + const request = protobuf_encode>({ routingHead: { c2c: { uin: userUin, @@ -568,11 +568,7 @@ export class MessageApi { subType: 0, c2cCmd: 11, }, - messageBody: { - richText: { - elems: protoElems, - }, - }, + messageBody: { richText }, clientSequence: clientSeq, random, syncCookie: new Uint8Array(0), diff --git a/packages/core/tests/actions/forward-metadata.test.ts b/packages/core/tests/actions/forward-metadata.test.ts index f1f4e66d..fa62c8a7 100644 --- a/packages/core/tests/actions/forward-metadata.test.ts +++ b/packages/core/tests/actions/forward-metadata.test.ts @@ -6,7 +6,7 @@ import { ForwardApi } from '../../src/bridge/apis/forward'; import { mockBridge } from './_helpers'; vi.mock('@snowluma/protocol/highway/image-upload', () => ({ uploadImageMsgInfo: vi.fn() })); -vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({ uploadPttMsgInfo: vi.fn() })); +vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({ uploadPtt: vi.fn() })); vi.mock('@snowluma/protocol/highway/video-upload', () => ({ uploadVideoMsgInfo: vi.fn() })); describe('forward metadata through upload and cached reads', () => { diff --git a/packages/core/tests/actions/forward-nested.test.ts b/packages/core/tests/actions/forward-nested.test.ts index d072cf41..f1931c2b 100644 --- a/packages/core/tests/actions/forward-nested.test.ts +++ b/packages/core/tests/actions/forward-nested.test.ts @@ -33,7 +33,7 @@ vi.mock('@snowluma/protocol/highway/image-upload', () => ({ uploadImageMsgInfo: vi.fn(async () => new Uint8Array()), })); vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({ - uploadPttMsgInfo: vi.fn(async () => new Uint8Array()), + uploadPtt: vi.fn(async () => ({ msgInfo: new Uint8Array() })), })); vi.mock('@snowluma/protocol/highway/video-upload', () => ({ uploadVideoMsgInfo: vi.fn(async () => new Uint8Array()), diff --git a/packages/core/tests/bridge-private-routing.test.ts b/packages/core/tests/bridge-private-routing.test.ts index 7f5996af..13058fc4 100644 --- a/packages/core/tests/bridge-private-routing.test.ts +++ b/packages/core/tests/bridge-private-routing.test.ts @@ -2,7 +2,11 @@ import { describe, expect, it, vi } from 'vitest'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { SendPacketResult } from '@snowluma/common/packet-sender'; import type { DatalineMsgBody, DatalineTextMsg } from '@snowluma/proto-defs/dataline'; -import type { SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action'; +import type { + SendMessageRequest, + SendMessageResponse, + SendRichText, +} from '@snowluma/proto-defs/action'; import type { FileExtra } from '@snowluma/proto-defs/message'; import { DATALINE_UIN_PHONE } from '@snowluma/protocol/dataline/device-contacts'; import type { OidbBase } from '@snowluma/proto-defs/oidb'; @@ -10,6 +14,9 @@ import type { OidbOfflineFileFinalizeResp } from '@snowluma/proto-defs/oidb-acti vi.mock('@snowluma/protocol/element-builder', () => ({ buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]), + encodePrivateRichText: vi.fn(async () => + protobuf_encode({ elems: [{ text: { str: 'stub media elem' } }] }), + ), })); // Imported statically (not via `await import` inside each `it`) so the heavy diff --git a/packages/core/tests/element-builder.test.ts b/packages/core/tests/element-builder.test.ts index 48447c46..0597cc6c 100644 --- a/packages/core/tests/element-builder.test.ts +++ b/packages/core/tests/element-builder.test.ts @@ -1,3 +1,4 @@ +import type { SendRichText } from '@snowluma/proto-defs/action'; // Regression test for the c2c-vs-group businessType asymmetry that made // private-chat video / record sends bounce with `send private message // rejected: result=79`. The receive-side decoder @@ -22,15 +23,16 @@ vi.mock('@snowluma/protocol/highway/image-upload', () => ({ uploadImageMsgInfo: vi.fn(async () => new Uint8Array([7, 8, 9])), })); vi.mock('@snowluma/protocol/highway/ptt-upload', () => ({ - uploadPttMsgInfo: vi.fn(async () => new Uint8Array([4, 5, 6])), + uploadPtt: vi.fn(async () => ({ msgInfo: new Uint8Array([4, 5, 6]) })), })); vi.mock('@snowluma/protocol/highway/video-upload', () => ({ uploadVideoMsgInfo: vi.fn(async () => new Uint8Array([1, 2, 3])), })); -import { protobuf_encode } from '@snowluma/proton'; +import { type bytes, type pb, protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { MsgInfo } from '@snowluma/proto-defs/element'; -import { buildSendElems } from '@snowluma/protocol/element-builder'; +import { buildSendElems, encodePrivateRichText } from '@snowluma/protocol/element-builder'; +import { uploadPtt } from '@snowluma/protocol/highway/ptt-upload'; import { MessageElementValidationError } from '@snowluma/protocol/element-manifest'; import { uploadImageMsgInfo } from '@snowluma/protocol/highway/image-upload'; import { uploadVideoMsgInfo } from '@snowluma/protocol/highway/video-upload'; @@ -569,3 +571,33 @@ describe('element-builder / forward preview', () => { ).rejects.toBeInstanceOf(MessageElementValidationError); }); }); + +describe('private voice compatibility', () => { + const context = { bridge: fakeBridge, userUid: 'u_peer', scene: 'direct-private' } as const; + const record = { type: 'record', url: 'voice.amr' } as const; + const modern = Uint8Array.of(4, 5, 6); + + it('keeps all modern clips when one legacy voice slot cannot represent the message', async () => { + const compat = protobuf_encode<{ ptt?: pb<4, bytes> }>({ ptt: Uint8Array.of(8, 4) }); + vi.mocked(uploadPtt) + .mockResolvedValueOnce({ msgInfo: modern, compatQMsg: compat }) + .mockResolvedValueOnce({ msgInfo: modern, compatQMsg: compat }); + const rich = await encodePrivateRichText([record, record], context); + expect(protobuf_decode<{ ptt?: pb<4, bytes> }>(rich).ptt).toBeNull(); + expect(protobuf_decode(rich).elems).toHaveLength(2); + }); + + it('sends modern voice when no compatibility data is available and rejects malformed data', async () => { + vi.mocked(uploadPtt).mockResolvedValueOnce({ msgInfo: modern }); + expect( + protobuf_decode(await encodePrivateRichText([record], context)).elems, + ).toHaveLength(1); + vi.mocked(uploadPtt).mockResolvedValueOnce({ + msgInfo: modern, + compatQMsg: Uint8Array.of(0x12, 0), + }); + await expect(encodePrivateRichText([record], context)).rejects.toThrow( + 'incomplete playback information', + ); + }); +}); diff --git a/packages/core/tests/fixtures/issue-614-private-voice-upload.hex b/packages/core/tests/fixtures/issue-614-private-voice-upload.hex new file mode 100644 index 00000000..8d389654 --- /dev/null +++ b/packages/core/tests/fixtures/issue-614-private-voice-upload.hex @@ -0,0 +1,14 @@ +08ed241064180022ef0412ec0432b9020af6010af3010a7d08fb3d122030303030303030303030303030303030303030 +303030303030303030303030301a28303030303030303030303030303030303030303030303030303030303030303030 +30303030303030222430303030303030303030303030303030303030303030303030303030303030302e616d722a0408 +032001400312637878787878787878787878787878787878787878787878787878787878787878787878787878787878 +787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878 +7878787878787878787818012081808080012881800138fa0a123e0a0612047465737412001a3208818080800110012a +22081e121e0505050505050505050505050505050505050505050505050505050505055a040800380042ad02122baa02 +289a0125aa0322081e121e05050505050505050505050505050505050505050505050505050505050522fd0108041081 +808080011a97017878787878787878787878787878787878787878787878787878787878787878787878787878787878 +787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878 +787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878 +78787878787878787878787878782210000000000000000000000000000000002a243030303030303030303030303030 +3030303030303030303030303030303030302e616d7230fb3d3a16000000000000000000000000000000000000000000 +005801980103e80101 diff --git a/packages/core/tests/private-voice-wire.test.ts b/packages/core/tests/private-voice-wire.test.ts new file mode 100644 index 00000000..a7d49614 --- /dev/null +++ b/packages/core/tests/private-voice-wire.test.ts @@ -0,0 +1,91 @@ +import { readFileSync } from 'node:fs'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; +import type { SendMessageResponse } from '@snowluma/proto-defs/action'; +import type { Elem } from '@snowluma/proto-defs/element'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import { IdentityService } from '@snowluma/protocol/identity-service'; +import { + type bytes, + type pb, + type pb_repeated, + protobuf_decode, + protobuf_encode, +} from '@snowluma/proton'; +import { expect, it } from 'vitest'; +import { Bridge } from '../src/bridge/bridge'; + +interface VoiceParts { + elems?: pb_repeated<2, bytes>; + ptt?: pb<4, bytes>; +} + +interface UploadReply { + upload?: pb<2, { compat?: pb<8, bytes> }>; +} + +interface OutgoingMessage { + body?: pb<3, { richText?: pb<1, VoiceParts> }>; +} + +it('preserves the private voice returned for older clients alongside the modern voice', async () => { + // The upload reply from #614, with identifiers redacted and transport credentials removed. + const upload = Buffer.from( + readFileSync( + new URL('./fixtures/issue-614-private-voice-upload.hex', import.meta.url), + 'utf8', + ).replace(/\s/g, ''), + 'hex', + ); + const captured = protobuf_decode>(Uint8Array.from(upload)).body!.upload! + .compat!; + const expected = protobuf_decode(captured); + expect(captured).toHaveLength(301); + expect(expected.ptt).toHaveLength(253); + let sent: VoiceParts | undefined; + + class VoiceBridge extends Bridge { + override async resolveUserUid(): Promise { + return 'u_peer'; + } + + override async sendRawPacket(cmd: string, body: Uint8Array): Promise { + let response: Uint8Array; + + if (cmd === 'OidbSvcTrpcTcp.0x126d_100') { + response = upload; + } else if (cmd === 'MessageSvc.PbSendMsg') { + sent = protobuf_decode(body).body!.richText!; + response = protobuf_encode({ privateSequence: 88 }); + } else { + throw new Error(`Unexpected packet ${cmd}`); + } + + return { + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData: Buffer.from(response), + }; + } + } + + const bridge = new VoiceBridge(IdentityService.memory('10000')); + await bridge.apis.message.sendPrivate(10001, [ + { + type: 'record', + noByteFallback: true, + fileSize: 7931, + duration: 3, + md5Hex: '0'.repeat(32), + sha1Hex: '0'.repeat(40), + fileName: 'voice.amr', + }, + ]); + expect(protobuf_decode(sent!.elems![0]!).commonElem).toMatchObject({ + serviceType: 48, + businessType: 12, + }); + expect(sent!.ptt).toEqual(expected.ptt); + expect(sent!.elems!.slice(1)).toEqual(expected.elems); +}); diff --git a/packages/proto-defs/src/action.ts b/packages/proto-defs/src/action.ts index 48729195..2810444b 100644 --- a/packages/proto-defs/src/action.ts +++ b/packages/proto-defs/src/action.ts @@ -47,24 +47,24 @@ export interface MessageControl { msgFlag?: pb<1, int_32>; } -// RichText (for send — only elems) +// RichText for outgoing message elements. export interface SendRichText { elems?: pb_repeated<2, Elem>; } // MessageBody (for send) -export interface SendMessageBody { - richText?: pb<1, SendRichText>; +export interface SendMessageBody { + richText?: pb<1, TRichText>; // C2C 离线文件元数据(NotOnlineFile)必须序列化后塞入此字段 // 服务器不会读取 richText.notOnlineFile。 msgContent?: pb<2, bytes>; } // SendMessageRequest -export interface SendMessageRequest { +export interface SendMessageRequest { routingHead?: pb<1, RoutingHead>; contentHead?: pb<2, SendContentHead>; - messageBody?: pb<3, SendMessageBody>; + messageBody?: pb<3, SendMessageBody>; clientSequence?: pb<4, uint_32>; random?: pb<5, uint_32>; syncCookie?: pb<6, bytes>; diff --git a/packages/proto-defs/src/highway.ts b/packages/proto-defs/src/highway.ts index 33366024..3612e0fe 100644 --- a/packages/proto-defs/src/highway.ts +++ b/packages/proto-defs/src/highway.ts @@ -322,6 +322,7 @@ export interface NTV2UploadRespBody { ipv4s?: pb_repeated<3, NTV2IPv4>; msgSeq?: pb<5, uint_64>; msgInfo?: pb<6, NTV2UploadRespMsgInfo>; + compatQMsg?: pb<8, bytes>; subFileInfos?: pb_repeated<10, NTV2SubFileInfoResp>; } diff --git a/packages/protocol/src/element-builder.ts b/packages/protocol/src/element-builder.ts index e5d8d4c6..d64d4660 100644 --- a/packages/protocol/src/element-builder.ts +++ b/packages/protocol/src/element-builder.ts @@ -1,4 +1,4 @@ -import type { MarkdownData, MentionExtraSend } from '@snowluma/proto-defs/action'; +import type { MarkdownData, MentionExtraSend, SendRichText } from '@snowluma/proto-defs/action'; import type { Elem, GroupFileExtra, @@ -8,7 +8,7 @@ import type { QFaceExtra, QSmallFaceExtra, } from '@snowluma/proto-defs/element'; -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { type bytes, type pb, protobuf_decode, protobuf_encode } from '@snowluma/proton'; import { createLogger } from '@snowluma/common/logger'; import { randomUUID } from 'crypto'; import { deflateSync } from 'zlib'; @@ -24,7 +24,7 @@ import { } from './element-manifest'; import { uploadImageMsgInfo } from './highway/image-upload'; import { hexToBytes } from './highway/pipeline'; -import { uploadPttMsgInfo } from './highway/ptt-upload'; +import { uploadPtt } from './highway/ptt-upload'; import { uploadVideoMsgInfo } from './highway/video-upload'; type ProtoElem = Partial; @@ -562,7 +562,7 @@ async function makeImageElem(ctx: SendContext, element: MessageElement): Promise return legacy ? [nt, legacy] : [nt]; } -async function makePttElem(ctx: SendContext, element: MessageElement): Promise { +async function makePttElem(ctx: SendContext, element: MessageElement) { const isGroup = ctx.groupId !== undefined; const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? ''); @@ -570,17 +570,14 @@ async function makePttElem(ctx: SendContext, element: MessageElement): Promise

{ +): Promise<{ elems: ProtoElem[]; voiceCompatibility?: Uint8Array }> { // Validate the whole message before the first upload or packet build. This // preserves all-or-nothing semantics: a malformed later segment cannot make // an earlier media segment perform side effects before the send is rejected. @@ -732,6 +729,9 @@ export async function buildSendElems( } const result: ProtoElem[] = []; + let voiceCompatibility: Uint8Array | undefined; + const singlePrivateVoice = + ctx?.scene === 'direct-private' && elements.filter((e) => e.type === 'record').length === 1; // A user-supplied @ that lands immediately after a reply's srcMsg isn't // honored by the QQ NT group server (the @ shows but never notifies, #129). // When a reply and an @ coexist, emit the replied sender as a trailing @@ -796,9 +796,16 @@ export async function buildSendElems( result.push(makeForwardElem(elem)); break; - case 'record': - result.push(await makePttElem(ctx!, elem)); + case 'record': { + const voice = await makePttElem(ctx!, elem); + result.push(voice.elem); + + if (singlePrivateVoice) { + voiceCompatibility = voice.compatQMsg; + } + break; + } case 'video': result.push(await makeVideoElem(ctx!, elem)); @@ -851,5 +858,32 @@ export async function buildSendElems( } } - return result; + return { elems: result, voiceCompatibility }; +} + +export async function buildSendElems( + elements: MessageElement[], + ctx?: SendContext, +): Promise { + return (await buildSendContent(elements, ctx)).elems; +} + +export async function encodePrivateRichText( + elements: MessageElement[], + ctx: SendContext, +): Promise { + const { elems, voiceCompatibility } = await buildSendContent(elements, ctx); + const modern = protobuf_encode({ elems }); + + // Both parts encode the same RichText message. Preserve the server's playback + // data verbatim, including extensions our receive schema does not interpret. + if (!voiceCompatibility?.length) { + return modern; + } + + if (!protobuf_decode<{ ptt?: pb<4, bytes> }>(voiceCompatibility).ptt?.length) { + throw new Error('private voice upload returned incomplete playback information'); + } + + return Buffer.concat([modern, voiceCompatibility]); } diff --git a/packages/protocol/src/highway/ptt-upload.ts b/packages/protocol/src/highway/ptt-upload.ts index f94a0a2f..50147f69 100644 --- a/packages/protocol/src/highway/ptt-upload.ts +++ b/packages/protocol/src/highway/ptt-upload.ts @@ -211,12 +211,12 @@ async function tryPttWaveform( * Upload a voice clip and return the encoded MsgInfo bytes that go inside * a `commonElem { serviceType: 48, businessType: 22 }`. */ -export async function uploadPttMsgInfo( +export async function uploadPtt( bridge: BridgeContext, isGroup: boolean, targetIdOrUid: string | number, element: MessageElement, -): Promise { +): Promise<{ msgInfo: Uint8Array; compatQMsg?: Uint8Array }> { const log = loggerFor(bridge); const tempDir = defaultPttTempDir(); const ptt = await loadPtt(element, tempDir); @@ -313,7 +313,7 @@ export async function uploadPttMsgInfo( fileId: mediaNode?.fileUuid, mediaNode, }); - return encoded; + return { msgInfo: encoded, compatQMsg: upload.compatQMsg }; } finally { for (const fn of ptt.cleanups) { try { @@ -324,3 +324,12 @@ export async function uploadPttMsgInfo( } } } + +export async function uploadPttMsgInfo( + bridge: BridgeContext, + isGroup: boolean, + targetIdOrUid: string | number, + element: MessageElement, +): Promise { + return (await uploadPtt(bridge, isGroup, targetIdOrUid, element)).msgInfo; +}