fix(core): handle group file storage limits

Retry eligible storage failures as temporary files and preserve their storage type for later use. Reject incompatible mixed content before chat publication.

Refs #644
This commit is contained in:
DrSmoothl committed 2026-11-07 15:14:55 +08:00
1 parent 84f4cde85e
commit 8bea681aa2
16 files changed
+750 -104

No files matched your search

+17 -1
View File
@@ -406,6 +406,7 @@ export class ForwardApi {
name: string,
groupId?: number,
userId?: number,
allowTemporary = true,
): Promise<MessageElementOf<'file'>> {
if (groupId !== undefined) {
const uploaded = await this.ctx.apis.groupFile.upload(
@@ -415,6 +416,7 @@ export class ForwardApi {
'/',
true,
false,
{ allowTemporary },
);
if (!uploaded.fileId) {
@@ -482,6 +484,7 @@ export class ForwardApi {
element: MessageElement,
groupId?: number,
userId?: number,
allowTemporary = true,
): Promise<MessageElement> {
if (element.type !== 'file') {
return element;
@@ -495,6 +498,7 @@ export class ForwardApi {
fileNameForUpload(element),
groupId,
userId,
allowTemporary,
);
return {
...stripFileSource(element),
@@ -506,6 +510,14 @@ export class ForwardApi {
const cached = this.ctx.recallUploadedFile(element.fileId);
if (isCachedFileUsableInTarget(cached, groupId, userId)) {
if (groupId !== undefined && cached?.busId === 104 && !allowTemporary) {
throw new MessageElementValidationError(
'UNSENDABLE_TYPE',
'temporary group files require only file or image segments in the same forward node',
'file',
);
}
return element;
}
@@ -515,6 +527,7 @@ export class ForwardApi {
fileNameForUpload(element, cached),
groupId,
userId,
allowTemporary,
);
return {
...stripFileSource(element),
@@ -532,9 +545,12 @@ export class ForwardApi {
): Promise<ForwardNodePayload[]> {
return Promise.all(
nodes.map(async (node) => {
const allowTemporary = node.elements.every(
(element) => element.type === 'file' || element.type === 'image',
);
const elements = await Promise.all(
node.elements.map((element) =>
this.prepareForwardFileElement(element, groupId, userId),
this.prepareForwardFileElement(element, groupId, userId, allowTemporary),
),
);
return cloneNodeWithElements(node, elements);
+86 -27
View File
@@ -76,6 +76,16 @@ export interface UploadFileResult {
fileHash?: string | null;
}
export interface GroupFileUploadResult {
fileId: string;
busId: number;
}
export interface GroupFileUploadOptions {
/** False when the enclosing message contains content a temporary file cannot carry. */
allowTemporary?: boolean;
}
// Re-export so callers don't have to dig into apis/shared.
export type { MediaIndexNode } from './shared';
@@ -136,6 +146,7 @@ async function assertUnchanged(
function buildGroupFileUploadExt(
senderUin: number,
groupId: number,
busId: number,
fileName: string,
fileSize: number,
md5: Uint8Array,
@@ -150,7 +161,7 @@ function buildGroupFileUploadExt(
unknown2: 1,
entry: {
busiBuff: {
busId: 102,
busId,
senderUin: BigInt(senderUin),
receiverUin: BigInt(groupId),
groupCode: BigInt(groupId),
@@ -255,12 +266,23 @@ export class GroupFileApi {
// ─────────────── publish (group file → chat) ───────────────
publish(groupId: number, fileId: string): Promise<void> {
publish(groupId: number, fileId: string, busId?: number): Promise<void> {
if (!fileId) {
throw new Error('publish requires fileId');
}
return PublishGroupFile.invoke(this.ctx, { groupId, fileId });
return PublishGroupFile.invoke(this.ctx, {
groupId,
fileId,
busId: busId ?? this.cachedBusId(groupId, fileId),
});
}
private cachedBusId(groupId: number, fileId: string): number {
const cached = this.ctx.recallUploadedFile(fileId);
return cached?.scope === 'group' && cached.groupId === groupId
? (cached.busId ?? 102)
: 102;
}
trans(groupId: number, fileId: string): Promise<TransGroupFileResult> {
@@ -290,7 +312,8 @@ export class GroupFileApi {
folderId = '/',
uploadFile = true,
publishFile = uploadFile,
): Promise<UploadFileResult> {
options: GroupFileUploadOptions = {},
): Promise<GroupFileUploadResult> {
const bridge = this.ctx;
// Group/private files may legitimately be up to 4 GiB on QQ's wire, so
// override the default 1 GiB cap with the protocol ceiling. Stage onto a
@@ -307,14 +330,36 @@ export class GroupFileApi {
const guardStat = await fsp.stat(staged.filePath); // mutation-guard baseline
const hashes = await hashFileStreaming(staged.filePath);
const upload = await UploadGroupFileRequest.invoke(this.ctx, {
const params: UploadGroupFileRequest.Params = {
groupId,
fileName,
folderId: normalizeDirectory(folderId),
fileSize: staged.fileSize,
fileSha1: hashes.sha1,
fileMd5: hashes.md5,
});
busId: 102,
};
let upload = await UploadGroupFileRequest.invoke(this.ctx, params);
// These are the storage-limit responses for which QQ switches to
// temporary storage. Never retry transport, permission or arbitrary
// service errors, and never retry the temporary request itself.
if (upload.retCode === -403 || upload.retCode === -9801 || upload.retCode === -98090) {
if (options.allowTemporary === false) {
throw new Error(
`temporary group files require only file or image segments; remove text and other content before retrying (group file upload code=${upload.retCode})`,
);
}
log.warn(
'Group %d permanent file storage rejected upload (code=%d); retrying as a temporary file',
groupId,
upload.retCode,
);
params.busId = 104;
upload = await UploadGroupFileRequest.invoke(this.ctx, params);
}
ensureRetCodeZero(
'group file upload',
upload.retCode,
@@ -322,6 +367,18 @@ export class GroupFileApi {
upload.clientWording,
);
const busId = upload.busId || params.busId;
if (busId !== 102 && busId !== 104) {
throw new Error(`group file upload returned unsupported storage type: ${busId}`);
}
if (busId === 104 && options.allowTemporary === false) {
throw new Error(
'temporary group files require only file or image segments; remove text and other content before retrying',
);
}
const fileId =
typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
@@ -329,23 +386,6 @@ export class GroupFileApi {
throw new Error('group file upload response missing file_id');
}
// Remember the upload so a later `send_group_msg` carrying just the
// file_id can route via `publish` without forcing the OneBot caller
// to thread fileName/size/md5 separately. For groups the wire
// publish (OIDB 0x6d9_4) only needs the file_id itself, so this is
// mainly for log-line correctness; the c2c counterpart in
// `uploadPrivate` is where the cache is actually load-bearing.
this.ctx.rememberUploadedFile({
fileId,
scope: 'group',
groupId,
fileName,
fileSize: staged.fileSize,
fileMd5: hashes.md5,
fileSha1: hashes.sha1,
rememberedAt: Date.now(),
});
if (!upload.boolFileExist && uploadFile) {
const senderUin = toInt(this.ctx.identity.uin);
@@ -366,6 +406,7 @@ export class GroupFileApi {
const ext = buildGroupFileUploadExt(
senderUin,
groupId,
busId,
fileName,
staged.fileSize,
hashes.md5,
@@ -386,6 +427,20 @@ export class GroupFileApi {
await uploadHighwayHttp(bridge, session, 71, chunkSource, hashes.md5, ext);
}
// Retain the storage type for later file_id publication and download.
// A failed byte transfer must not leave a usable-looking cache entry.
this.ctx.rememberUploadedFile({
fileId,
scope: 'group',
groupId,
busId,
fileName,
fileSize: staged.fileSize,
fileMd5: hashes.md5,
fileSha1: hashes.sha1,
rememberedAt: Date.now(),
});
// Stage 3: file is on the server, now publish it as a chat message.
//
// Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes —
@@ -398,7 +453,7 @@ export class GroupFileApi {
// tests can mock at the same Api boundary.
if (publishFile) {
try {
await this.publish(groupId, fileId);
await this.publish(groupId, fileId, busId);
} catch (err) {
// Keep the completed upload identifiable, but a requested chat
// publication must not be reported as a successful send.
@@ -409,7 +464,7 @@ export class GroupFileApi {
}
}
return { fileId };
return { fileId, busId };
} finally {
await staged.cleanup();
}
@@ -711,8 +766,12 @@ export class GroupFileApi {
// ─────────────── url fetch (group / private files) ───────────────
async getUrl(groupId: number, fileId: string, busId = 102): Promise<string> {
return GetGroupFileUrl.invoke(this.ctx, { groupId, fileId, busId });
async getUrl(groupId: number, fileId: string, busId?: number): Promise<string> {
return GetGroupFileUrl.invoke(this.ctx, {
groupId,
fileId,
busId: busId ?? this.cachedBusId(groupId, fileId),
});
}
async getPrivateUrl(userId: number, fileId: string, fileHash: string): Promise<string> {
+2 -17
View File
@@ -17,6 +17,8 @@ import type { OnlineDeviceInfo } from '@snowluma/protocol/events';
import { buildApiHub, type ApiHub } from './apis';
import { AiVoiceChatType, type AiVoiceCategory, type StrangerStatus } from './apis/extras';
import type { BridgeInterface, RosterWarmupResult } from './bridge-interface';
import type { UploadedFileMeta } from './bridge-context';
export type { UploadedFileMeta } from './bridge-context';
const log = createLogger('Bridge');
const runtimeLog = createLogger('Bridge.Runtime');
@@ -594,23 +596,6 @@ export interface SendMessageReceipt {
timestamp: number;
}
export interface UploadedFileMeta {
fileId: string;
scope: 'group' | 'private';
/** Group id if scope='group', else `undefined`. */
groupId?: number;
/** Friend uin if scope='private', else `undefined`. */
userId?: number;
fileName: string;
fileSize: number;
fileMd5: Uint8Array;
fileSha1: Uint8Array;
/** Server-issued hash returned alongside the upload (private only). */
fileHash?: string;
/** Insert time — used to evict the oldest entry when the cache fills. */
rememberedAt: number;
}
export interface DownloadRKeyInfo {
rkey: string;
ttlSeconds: number;
@@ -73,6 +73,64 @@ function decodeLongMsgRequest(rawBytes: Uint8Array): LongMsgResult {
}
describe('actions/forward — file segment inside forward node', () => {
it('rejects cached temporary files mixed with text before building a forward payload', async () => {
buildSendElemsMock.mockClear();
const bridge = mockBridge({
recallUploadedFile: vi.fn(() => ({ scope: 'group', groupId: 12345, busId: 104 })),
});
await expect(
new ForwardApi(bridge as any).upload(
[
{
userUin: 10001,
nickname: 'alice',
elements: [
{ type: 'text', text: 'caption' },
{ type: 'file', fileId: 'temp' },
],
},
],
12345,
),
).rejects.toThrow(/temporary group files.*only file or image/i);
expect(buildSendElemsMock).not.toHaveBeenCalled();
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
});
it('disallows temporary fallback when a forward node mixes a new file with text', async () => {
buildSendElemsMock.mockClear();
const bridge = mockBridge();
bridge.apis.groupFile.upload.mockRejectedValueOnce(
new Error('temporary group files require only file or image segments'),
);
await expect(
new ForwardApi(bridge as any).upload(
[
{
userUin: 10001,
nickname: 'alice',
elements: [
{ type: 'text', text: 'caption' },
{ type: 'file', url: 'base64://AQID', fileName: 'note.txt' },
],
},
],
12345,
),
).rejects.toThrow(/temporary group files/);
expect(bridge.apis.groupFile.upload).toHaveBeenCalledWith(
12345,
'base64://AQID',
'note.txt',
'/',
true,
false,
{ allowTemporary: false },
);
expect(buildSendElemsMock).not.toHaveBeenCalled();
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
});
it('rejects a recursive window shake before identity resolution or upload', async () => {
buildSendElemsMock.mockClear();
const resolveUserUid = vi.fn();
@@ -288,7 +346,9 @@ describe('actions/forward — file segment inside forward node', () => {
12345,
);
expect(upload).toHaveBeenCalledWith(12345, 'base64://AQID', 'note.txt', '/', true, false);
expect(upload).toHaveBeenCalledWith(12345, 'base64://AQID', 'note.txt', '/', true, false, {
allowTemporary: true,
});
expect(publish).not.toHaveBeenCalled();
const [elements] = buildSendElemsMock.mock.calls[0]!;
expect(elements).toEqual([
@@ -513,6 +573,7 @@ describe('actions/forward — file segment inside forward node', () => {
'/',
true,
false,
{ allowTemporary: true },
);
const [elements] = buildSendElemsMock.mock.calls[0]!;
expect(elements).toEqual([
+182 -3
View File
@@ -1,10 +1,12 @@
import { describe, it, expect, vi, beforeEach, beforeAll, afterAll } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { FileUploadExt } from '@snowluma/proto-defs/highway';
import type {
OidbGroupFileCountViewResp,
OidbGroupFileReq,
OidbGroupFileResp,
OidbGroupFileUploadResp,
OidbGroupFileViewResp,
OidbGroupFileFolderResp,
OidbGroupSendFileReq,
@@ -70,6 +72,10 @@ function packResponse(body: Uint8Array) {
};
}
function uploadResponse(upload: OidbGroupFileUploadResp) {
return packResponse(protobuf_encode<OidbBase<OidbGroupFileResp>>({ body: { upload } }));
}
let STAGED_FILE: string;
describe('apis/group-file', () => {
@@ -138,7 +144,7 @@ describe('apis/group-file', () => {
const api = new GroupFileApi(bridge as any);
vi.spyOn(api, 'publish').mockResolvedValue();
const out = await api.upload(12345, '/path/file.bin');
expect(out).toEqual({ fileId: 'fid-xyz' });
expect(out).toEqual({ fileId: 'fid-xyz', busId: 102 });
expect(highwayClient.fetchHighwaySession).not.toHaveBeenCalled();
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
});
@@ -224,8 +230,180 @@ describe('apis/group-file', () => {
await expect(
new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'),
).rejects.toThrow(/code=999/);
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
});
it.each([-403, -9801, -98090])(
'retries capacity error %s as a temporary group file',
async (retCode) => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(
uploadResponse({ retCode, retMsg: 'permanent storage full' }),
)
.mockResolvedValueOnce(
uploadResponse({ fileId: 'temporary-file', busId: 104, boolFileExist: true }),
);
const api = new GroupFileApi(bridge as any);
const result = await api.upload(12345, '/path/file.bin', 'doc.bin', '/folder');
expect(result).toMatchObject({ fileId: 'temporary-file', busId: 104 });
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3);
const requests = bridge.sendRawPacket.mock.calls
.slice(0, 2)
.map(([, bytes]) => protobuf_decode<OidbBase<OidbGroupFileReq>>(bytes).body?.file);
expect(requests[0]).toMatchObject({ busId: 102, targetDirectory: '/folder' });
expect(requests[1]).toEqual({ ...requests[0], busId: 104 });
const publish = protobuf_decode<OidbBase<OidbGroupSendFileReq>>(
bridge.sendRawPacket.mock.calls[2]![1],
);
expect(publish.body?.body?.info).toMatchObject({
fileId: 'temporary-file',
busiType: 104,
});
expect(bridge.rememberUploadedFile).toHaveBeenCalledWith(
expect.objectContaining({ busId: 104, groupId: 12345 }),
);
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
},
);
it('carries the server-selected storage type through bytes, publication and cached reuse', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(
uploadResponse({
fileId: 'temporary-file',
busId: 104,
uploadIp: '127.0.0.1',
uploadPort: 8080,
fileKey: new Uint8Array([7]),
checkKey: new Uint8Array([8]),
}),
);
bridge.recallUploadedFile.mockImplementation(
() => bridge.rememberUploadedFile.mock.calls.at(-1)?.[0],
);
const api = new GroupFileApi(bridge as any);
await api.upload(12345, '/path/file.bin');
const ext = protobuf_decode<FileUploadExt>(
vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]![5],
);
expect(ext.entry?.busiBuff?.busId).toBe(104);
await api.publish(12345, 'temporary-file');
for (const [, bytes] of bridge.sendRawPacket.mock.calls.slice(1)) {
expect(
protobuf_decode<OidbBase<OidbGroupSendFileReq>>(bytes).body?.body?.info?.busiType,
).toBe(104);
}
});
it('stops after a failed temporary attempt and releases the staged file', async () => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(uploadResponse({ retCode: -403 }))
.mockResolvedValueOnce(
uploadResponse({ retCode: -9801, retMsg: 'temporary storage rejected' }),
);
await expect(
new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'),
).rejects.toThrow(/code=-9801/);
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
const staged = await vi.mocked(stageMod.stageSourceToDisk).mock.results.at(-1)!.value;
expect(staged.cleanup).toHaveBeenCalledOnce();
});
it('retains temporary mode when the successful retry omits its storage type', async () => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(uploadResponse({ retCode: -403 }))
.mockResolvedValueOnce(uploadResponse({ fileId: 'temp', boolFileExist: true }));
const api = new GroupFileApi(bridge as any);
const publish = vi.spyOn(api, 'publish').mockResolvedValue();
await expect(api.upload(12345, '/path/file.bin')).resolves.toEqual({
fileId: 'temp',
busId: 104,
});
expect(publish).toHaveBeenCalledExactlyOnceWith(12345, 'temp', 104);
});
it('rejects an unknown server storage type before bytes or publication', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(
uploadResponse({ fileId: 'bad', busId: 777, boolFileExist: true }),
);
await expect(
new GroupFileApi(bridge as any).upload(12345, '/path/file.bin'),
).rejects.toThrow(/unsupported storage type: 777/);
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
});
it.each([
{ scope: 'group', groupId: 12345, expected: 104 },
{ scope: 'group', groupId: 54321, expected: 102 },
{ scope: 'private', groupId: undefined, expected: 102 },
] as const)(
'scopes cached storage to the target group for download and reuse (%j)',
async ({ scope, groupId, expected }) => {
const bridge = mockBridge();
bridge.recallUploadedFile.mockReturnValue({
fileId: 'temp',
scope,
groupId,
busId: 104,
});
bridge.sendRawPacket.mockResolvedValueOnce(
packResponse(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: {
download: {
downloadDns: 'download.example.com',
downloadUrl: new Uint8Array([1]),
},
},
}),
),
);
const api = new GroupFileApi(bridge as any);
await api.getUrl(12345, 'temp');
await api.publish(12345, 'temp');
const requests = bridge.sendRawPacket.mock.calls;
expect(
protobuf_decode<OidbBase<OidbGroupFileReq>>(requests[0]![1]).body?.download?.busId,
).toBe(expected);
expect(
protobuf_decode<OidbBase<OidbGroupSendFileReq>>(requests[1]![1]).body?.body?.info
?.busiType,
).toBe(expected);
},
);
it.each([{ retCode: -403 }, { fileId: 'temp', busId: 104, boolFileExist: true }])(
'rejects a disallowed temporary upload before transferring bytes or publishing (%j)',
async (response) => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(uploadResponse(response));
await expect(
new GroupFileApi(bridge as any).upload(
12345,
'/path/file.bin',
'',
'/',
true,
false,
{ allowTemporary: false },
),
).rejects.toThrow(/temporary group files.*only file or image/i);
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
expect(highwayClient.uploadHighwayHttp).not.toHaveBeenCalled();
},
);
it('upload publishes the file via OIDB 0x6d9_4 after upload (the "empty message" regression)', async () => {
// Reproduces the bug report: OIDB upload + highway PUT alone only
// stage the bytes on QQ's side; without the trailing 0x6d9_4 OIDB
@@ -341,11 +519,12 @@ describe('apis/group-file', () => {
const upload = api.upload(12345, 'base64://AQID', 'confirmed.txt');
if (confirmed) {
await expect(upload).resolves.toEqual({ fileId: 'fid-confirm' });
expect(publishSpy).toHaveBeenCalledExactlyOnceWith(12345, 'fid-confirm');
await expect(upload).resolves.toEqual({ fileId: 'fid-confirm', busId: 102 });
expect(publishSpy).toHaveBeenCalledExactlyOnceWith(12345, 'fid-confirm', 102);
} else {
await expect(upload).rejects.toBe(failure);
expect(publishSpy).not.toHaveBeenCalled();
expect(bridge.rememberUploadedFile).not.toHaveBeenCalled();
}
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
+22 -1
View File
@@ -30,7 +30,7 @@ vi.mock('@snowluma/protocol/highway/video-upload', () => ({
}));
import { type bytes, type pb, protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { MsgInfo } from '@snowluma/proto-defs/element';
import type { GroupFileExtra, MsgInfo } from '@snowluma/proto-defs/element';
import { buildSendElems, encodePrivateRichText } from '@snowluma/protocol/element-builder';
import { uploadPtt } from '@snowluma/protocol/highway/ptt-upload';
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
@@ -374,6 +374,27 @@ describe('element-builder / all-message validation preflight', () => {
});
describe('element-builder / file element is no longer carried in elems[]', () => {
it.each([12345, 54321])(
'preserves temporary storage only in a matching group forward (%s)',
async (cachedGroupId) => {
const bridge = {
recallUploadedFile: vi.fn(() => ({
scope: 'group',
groupId: cachedGroupId,
busId: 104,
fileName: 'doc.pdf',
fileSize: 3,
})),
} as any;
const [elem] = await buildSendElems([{ type: 'file', fileId: 'temp' }], {
bridge,
groupId: 12345,
forwardFake: true,
});
const extra = protobuf_decode<GroupFileExtra>(elem!.transElem!.elemValue!.subarray(3));
expect(extra.inner?.info?.busId).toBe(cachedGroupId === 12345 ? 104 : 102);
},
);
// Regression for the `result=79` class: previously the element-builder
// emitted a `transElem(elemType=24, ...)` for `{type:'file'}` segments
// and the QQ-NT server rejected the outgoing PbSendMsg with that wire