fix(protocol): support image replies in existing temp sessions

Allow image replies in existing group temporary conversations while preserving passive-only restrictions. Missing, expired, or mismatched sessions remain rejected before media processing, and sending never creates or refreshes a session.

Fixes #471
This commit is contained in:
DrSmoothl committed 2026-09-26 16:30:54 +08:00
1 parent ad360c8eba
commit 1914880df4
11 files changed
+210 -30

No files matched your search

+1
View File
@@ -577,6 +577,7 @@ export class MessageApi {
bridge: this.ctx as unknown as Bridge,
userUid,
scene: 'group-temp',
tempGroupId: groupUin,
});
const random = this.ctx.nextMessageRandom();
const clientSeq = this.ctx.nextClientSequence();
@@ -294,6 +294,7 @@ describe('element-builder / all-message validation preflight', () => {
true,
12345,
expect.objectContaining({ imageUrl: 'https://gchat.qpic.cn/received.jpg' }),
undefined,
);
});
@@ -0,0 +1,101 @@
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { RoutingHead, SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { NTV2C2CUserInfo, NTV2UploadRichMediaReq, NTV2UploadRichMediaResp } from '@snowluma/proto-defs/highway';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { describe, expect, it, vi } from 'vitest';
import { Bridge } from '../src/bridge/bridge';
const png = 'base64://iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jFZkAAAAASUVORK5CYII=';
function fixture(rejectUpload = false) {
const requests: Array<{ command: string; body: Uint8Array }> = [];
class TestBridge extends Bridge {
override async resolveUserUid(): Promise<string> { return 'u_peer'; }
override async sendRawPacket(command: string, body: Uint8Array): Promise<SendPacketResult> {
requests.push({ command, body });
let response: Uint8Array;
if (command === 'OidbSvcTrpcTcp.0x11c5_100') {
response = protobuf_encode<OidbBase<NTV2UploadRichMediaResp>>({
command: 0x11c5, subCommand: 100,
errorCode: rejectUpload ? 170019003 : 0,
errorMsg: rejectUpload ? 'verify identify fail' : '',
body: { upload: { msgInfo: { msgInfoBody: [{ index: { fileUuid: 'cached-image' } }] } } },
});
} else if (command === 'MessageSvc.PbSendMsg') {
response = protobuf_encode<SendMessageResponse>({ result: 0, privateSequence: 88 });
} else {
throw new Error(`unexpected packet: ${command}`);
}
return { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.from(response) };
}
}
return { bridge: new TestBridge(IdentityService.memory('10000')), requests };
}
describe('passive temp-session image wire request (#471)', () => {
it('uses the same existing-session route for image upload and the final message', async () => {
const { bridge, requests } = fixture();
await bridge.apis.message.sendGroupTempMessage(1001, 700, [
{ type: 'text', text: 'reply' },
{ type: 'image', url: png },
]);
expect(requests.map((r) => r.command)).toEqual([
'OidbSvcTrpcTcp.0x11c5_100', 'MessageSvc.PbSendMsg',
]);
const upload = protobuf_decode<OidbBase<NTV2UploadRichMediaReq>>(requests[0]!.body).body!;
expect(upload.reqHead?.scene).toMatchObject({
sceneType: 1, businessType: 1, c2c: { accountType: 2, targetUid: 'u_peer' },
});
expect(upload.reqHead?.scene?.group ?? undefined).toBeUndefined();
const route = upload.reqHead!.scene!.c2c!.routingHead!;
expect(Array.from(route)).toEqual([
0x1a, 0x0b, 0x18, 0xbc, 0x05, 0x22, 0x06, 0x75, 0x5f, 0x70, 0x65, 0x65, 0x72,
]);
expect(Array.from(protobuf_encode<NTV2C2CUserInfo>(upload.reqHead!.scene!.c2c!))).toEqual([
0x08, 0x02, 0x12, 0x06, 0x75, 0x5f, 0x70, 0x65, 0x65, 0x72,
0x1a, 0x0d, 0x1a, 0x0b, 0x18, 0xbc, 0x05, 0x22, 0x06, 0x75, 0x5f, 0x70, 0x65, 0x65, 0x72,
]);
const sent = protobuf_decode<SendMessageRequest>(requests[1]!.body);
expect(protobuf_decode<RoutingHead>(route)).toEqual(sent.routingHead);
expect(sent.routingHead?.grpTmp).toEqual({ groupUin: 700n, toUid: 'u_peer' });
expect(sent.messageBody?.richText?.elems).toEqual([
expect.objectContaining({ text: expect.objectContaining({ str: 'reply' }) }),
expect.objectContaining({ commonElem: expect.objectContaining({ serviceType: 48, businessType: 10 }) }),
]);
});
it('keeps normal private image uploads free of temp-session context', async () => {
const { bridge, requests } = fixture();
await bridge.apis.message.sendPrivate(1001, [{ type: 'image', url: png }]);
const upload = protobuf_decode<OidbBase<NTV2UploadRichMediaReq>>(requests[0]!.body).body!;
expect(upload.reqHead?.scene?.c2c?.routingHead ?? undefined).toBeUndefined();
const sent = protobuf_decode<SendMessageRequest>(requests[1]!.body);
expect(sent.routingHead?.grpTmp ?? undefined).toBeUndefined();
});
it('propagates upload rejection without sending text or retrying as another conversation', async () => {
const { bridge, requests } = fixture(true);
await expect(bridge.apis.message.sendGroupTempMessage(1001, 700, [
{ type: 'text', text: 'must not be sent separately' },
{ type: 'image', url: png },
])).rejects.toThrow('verify identify fail');
expect(requests.map((r) => r.command)).toEqual(['OidbSvcTrpcTcp.0x11c5_100']);
});
it('rejects missing source context before reading the image or sending any packet', async () => {
const { bridge, requests } = fixture();
const fetch = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('must not download image'));
try {
await expect(buildSendElems([{ type: 'image', url: 'https://must-not-fetch.invalid/image.png' }], {
bridge, scene: 'group-temp', userUid: 'u_peer',
})).rejects.toThrow('temp-session image source group is missing');
expect(fetch).not.toHaveBeenCalled();
expect(requests).toEqual([]);
} finally { fetch.mockRestore(); }
});
});
@@ -1111,6 +1111,22 @@ describe('buildApiContext send and forward dispatch', () => {
expect(dispatchEvent).not.toHaveBeenCalled();
});
it('replies with an image only through the recorded temp session without refreshing it', async () => {
const { api, ref } = makeRef();
ref.tempSessions.record(PEER_ID, GROUP_ID);
const record = vi.spyOn(ref.tempSessions, 'record');
const source = 'base64://iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jFZkAAAAASUVORK5CYII=';
await api.sendPrivateMessage(PEER_ID, [
{ type: 'image', data: { file: source } },
], false, GROUP_ID);
expect(ref.bridge.apis.message.sendGroupTempMessage).toHaveBeenCalledWith(
PEER_ID, GROUP_ID, [expect.objectContaining({ type: 'image', url: source })],
);
expect(ref.bridge.apis.message.sendPrivate).not.toHaveBeenCalled();
expect(record).not.toHaveBeenCalled();
});
it('sends a group message without a self-sent dispatch callback', async () => {
const { api, dispatchEvent, ref } = makeRef();
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest';
import { sendPrivateMessage } from '../src/modules/message-actions';
import { TempSessionStore } from '../src/temp-session-store';
import { TempSessionStore, TEMP_SESSION_TTL_MS } from '../src/temp-session-store';
import type { OneBotInstanceContext } from '../src/instance-context';
// The passive gate lives at the very top of sendPrivateMessage, before any
@@ -21,6 +21,25 @@ function refWith(store: TempSessionStore): OneBotInstanceContext {
}
describe('sendPrivateMessage temp-session gate (passive-only)', () => {
it.each(['missing', 'other-user', 'other-group', 'expired'])(
'refuses an image before parsing or uploading when the session is %s', async (state) => {
const store = new TempSessionStore();
if (state === 'other-user') store.record(1002, 700);
if (state === 'other-group') store.record(1001, 701);
if (state === 'expired') store.record(1001, 700, Date.now() - TEMP_SESSION_TTL_MS);
const record = vi.spyOn(store, 'record');
const ref = refWith(store);
await expect(sendPrivateMessage(ref, 1001, [
{ type: 'image', data: { file: 'https://must-not-fetch.invalid/image.png' } },
], false, 700)).rejects.toThrow('no such temp session');
expect(ref.bridge.apis.message.sendGroupTempMessage).not.toHaveBeenCalled();
expect(ref.bridge.apis.message.sendPrivate).not.toHaveBeenCalled();
expect(record).not.toHaveBeenCalled();
},
);
it('refuses a temp reply to an unrecorded (user, group) and never sends', async () => {
const store = new TempSessionStore();
const ref = refWith(store);
+1
View File
@@ -254,6 +254,7 @@ export interface NTV2UploadReq {
export interface NTV2C2CUserInfo {
accountType?: pb<1, uint_32>;
targetUid?: pb<2, string>;
routingHead?: pb<3, bytes>;
}
export interface NTV2GroupInfo {
+7 -1
View File
@@ -27,6 +27,8 @@ export interface SendContext {
bridge: BridgeContext;
groupId?: number;
userUid?: string;
/** Source group of an already authorized passive temp-session reply. */
tempGroupId?: number;
/** Explicit transport scene used by scene-limited message elements. */
scene?: OutboundMessageScene;
/**
@@ -386,7 +388,11 @@ async function makeImageElem(ctx: SendContext, element: MessageElement): Promise
throw new Error('private image target uid is missing');
}
const msgInfo = await uploadImageMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
const tempGroupId = ctx.scene === 'group-temp' ? ctx.tempGroupId : undefined;
if (ctx.scene === 'group-temp' && tempGroupId === undefined) {
throw new Error('temp-session image source group is missing');
}
const msgInfo = await uploadImageMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element, tempGroupId);
const nt: ProtoElem = {
commonElem: {
serviceType: 48,
@@ -116,6 +116,7 @@ export async function uploadImageMsgInfo(
isGroup: boolean,
targetIdOrUid: string | number,
element: MessageElement,
tempGroupId?: number,
): Promise<Uint8Array> {
const log = loggerFor(bridge);
const image = await loadImage(element);
@@ -128,11 +129,12 @@ export async function uploadImageMsgInfo(
subType: image.subType, summary: image.summary,
}) }),
};
log.debug('uploading %d bytes md5=%s... → %s %s',
log.debug('uploading %d bytes md5=%s... → %s %s%s',
image.fileSize,
image.md5Hex.slice(0, 8),
isGroup ? 'group' : 'c2c',
String(targetIdOrUid));
isGroup ? 'group' : tempGroupId !== undefined ? 'group-temp' : 'c2c',
String(targetIdOrUid),
tempGroupId !== undefined ? ` sourceGroup=${tempGroupId}` : '');
const uploads: MediaSubFileUpload[] = [{
source: 'top',
@@ -147,6 +149,7 @@ export async function uploadImageMsgInfo(
bridge,
isGroup,
targetIdOrUid,
tempGroupId,
oidbCmd: isGroup ? 0x11C4 : 0x11C5,
serviceCmd: isGroup ? 'OidbSvcTrpcTcp.0x11c4_100' : 'OidbSvcTrpcTcp.0x11c5_100',
requestId: 1,
+6 -2
View File
@@ -66,6 +66,8 @@ export interface NtV2UploadParams {
isGroup: boolean;
/** Group uin when isGroup, otherwise the recipient's uid string. */
targetIdOrUid: string | number;
/** Existing passive group temp session; never creates or refreshes a session. */
tempGroupId?: number;
/** OIDB command id (e.g. 0x11C4 / 0x11C5 / 0x126E / 0x126D / 0x11EA / 0x11E9). */
oidbCmd: number;
/** Service cmd (e.g. 'OidbSvcTrpcTcp.0x11c4_100'). */
@@ -147,10 +149,11 @@ export function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2UploadRespB
let didPut = false;
return runWithTraceRequest(async () => {
moduleLog.trace(() => [
'highway_media_start label=%j scope=%s target=%j oidbCmd=%d serviceCmd=%j requestId=%d businessType=%d uploads=%s',
'highway_media_start label=%j scope=%s target=%j sourceGroup=%s oidbCmd=%d serviceCmd=%j requestId=%d businessType=%d uploads=%s',
label,
params.isGroup ? 'group' : 'private',
params.isGroup ? 'group' : params.tempGroupId !== undefined ? 'group-temp' : 'private',
String(params.targetIdOrUid),
params.tempGroupId === undefined ? '-' : String(params.tempGroupId),
params.oidbCmd,
params.serviceCmd,
params.requestId,
@@ -209,6 +212,7 @@ async function runNtv2UploadOperation(
oidbCmd,
isGroup,
targetIdOrUid,
tempGroupId: params.tempGroupId,
requestId: params.requestId,
businessType: params.businessType,
uploadInfo: params.uploadInfo,
@@ -1,5 +1,6 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { RoutingHead } from '@snowluma/proto-defs/action';
import type {
NTV2ExtBizInfo,
NTV2UploadInfo,
@@ -23,6 +24,7 @@ export namespace Ntv2UploadRequest {
oidbCmd: number;
isGroup: boolean;
targetIdOrUid: string | number;
tempGroupId?: number;
requestId: number;
businessType: number;
uploadInfo: NTV2UploadInfo[];
@@ -37,30 +39,42 @@ export namespace Ntv2UploadRequest {
export const resolveCommand = (params: Params): number => params.oidbCmd;
export const serialize = (_ctx: Deps, params: Params): NTV2UploadRichMediaReq => ({
reqHead: {
common: { requestId: params.requestId, command: 100 },
scene: {
requestType: 2,
businessType: params.businessType,
sceneType: params.isGroup ? 2 : 1,
...(params.isGroup
? { group: { groupUin: Number(params.targetIdOrUid) } }
: { c2c: { accountType: 2, targetUid: String(params.targetIdOrUid) } }),
export const serialize = (_ctx: Deps, params: Params): NTV2UploadRichMediaReq => {
let routingHead: Uint8Array | undefined;
if (params.tempGroupId !== undefined) {
if (params.isGroup || !Number.isSafeInteger(params.tempGroupId) || params.tempGroupId <= 0
|| typeof params.targetIdOrUid !== 'string' || !params.targetIdOrUid.trim()) {
throw new Error('invalid temp-session image upload context');
}
routingHead = protobuf_encode<RoutingHead>({
grpTmp: { groupUin: BigInt(params.tempGroupId), toUid: params.targetIdOrUid },
});
}
return {
reqHead: {
common: { requestId: params.requestId, command: 100 },
scene: {
requestType: 2,
businessType: params.businessType,
sceneType: params.isGroup ? 2 : 1,
...(params.isGroup
? { group: { groupUin: Number(params.targetIdOrUid) } }
: { c2c: { accountType: 2, targetUid: String(params.targetIdOrUid), routingHead } }),
},
client: { agentType: 2 },
},
client: { agentType: 2 },
},
upload: {
uploadInfo: params.uploadInfo,
tryFastUploadCompleted: params.tryFast,
srvSendMsg: false,
clientRandomId: params.clientRandomId,
compatQmsgSceneType: params.compatQmsgSceneType,
extBizInfo: params.extBizInfo,
clientSeq: 0,
noNeedCompatMsg: false,
},
});
upload: {
uploadInfo: params.uploadInfo,
tryFastUploadCompleted: params.tryFast,
srvSendMsg: false,
clientRandomId: params.clientRandomId,
compatQmsgSceneType: params.compatQmsgSceneType,
extBizInfo: params.extBizInfo,
clientSeq: 0,
noNeedCompatMsg: false,
},
};
};
export const deserializeUpload = (body: NTV2UploadRichMediaResp, label = 'media'): NTV2UploadRespBody => {
if (!body) throw new Error(`${label} upload response body missing`);
@@ -36,6 +36,20 @@ const params: Ntv2UploadRequest.Params = {
};
describe('Ntv2UploadRequest', () => {
it.each([
{ tempGroupId: 0 },
{ tempGroupId: -1 },
{ tempGroupId: 1.5 },
{ tempGroupId: 700, isGroup: true },
{ tempGroupId: 700, targetIdOrUid: '' },
{ tempGroupId: 700, targetIdOrUid: 1001 },
])('rejects invalid temp context before sending: %j', async (invalid) => {
const sendRawPacket = vi.fn();
await expect(Ntv2UploadRequest.invoke({ sendRawPacket }, { ...params, ...invalid }))
.rejects.toThrow('invalid temp-session image upload context');
expect(sendRawPacket).not.toHaveBeenCalled();
});
it('sends the resolved command on the default OIDB wire name', async () => {
const sendRawPacket = vi.fn(async () => packet({
upload: { msgInfo: { msgInfoBody: [] } },