fix(core): bound merged-forward decompression

Cap long-message gunzip output at 32 MiB and fail before an oversized QQ response can exhaust process memory. Include the resource id, compressed size, and configured limit in observable errors.
This commit is contained in:
DrSmoothl committed 2026-07-10 13:42:34 +08:00
1 parent ffede67aed
commit 9f7f34cd8f
2 files changed
+50 -2

No files matched your search

+30 -1
View File
@@ -1,5 +1,6 @@
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { mapWithConcurrency } from '@snowluma/common/concurrency';
import { createLogger } from '@snowluma/common/logger';
import type {
LongMsgResult,
RecvLongMsgReq,
@@ -25,6 +26,14 @@ function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge;
// resolve a forward immediately after receiving the parent message.
const forwardResCache = new Map<string, ForwardNodePayload[]>();
const log = createLogger('Bridge.Forward');
// Forward bodies are gzip-compressed by QQ. Bound decompression while zlib is
// producing output so a small server response cannot expand until the process
// exhausts its heap. 32 MiB leaves ample room for legitimate merged forwards
// while making the maximum per-fetch allocation explicit.
const FORWARD_LONG_MSG_MAX_OUTPUT_BYTES = 32 * 1024 * 1024;
/** QQ's placeholder when it doesn't hand back a real sender name — treated as
* "missing" so #174's enrichment resolves the real nickname. */
const FORWARD_NAME_PLACEHOLDER = 'QQ用户';
@@ -577,7 +586,27 @@ export class ForwardApi {
throw new Error('download forward message payload is empty');
}
const inflate = gunzipSync(Buffer.from(payload));
let inflate: Buffer;
try {
inflate = gunzipSync(Buffer.from(payload), {
maxOutputLength: FORWARD_LONG_MSG_MAX_OUTPUT_BYTES,
});
} catch (cause) {
const reason = cause instanceof Error ? cause.message : String(cause);
log.warn(
'forward long-msg decompression failed: res_id=%s compressed_bytes=%d max_output_bytes=%d error=%s',
resId,
payload.byteLength,
FORWARD_LONG_MSG_MAX_OUTPUT_BYTES,
reason,
);
throw new Error(
`download forward message decompression failed ` +
`(res_id=${resId}, compressed_bytes=${payload.byteLength}, ` +
`max_output_bytes=${FORWARD_LONG_MSG_MAX_OUTPUT_BYTES}): ${reason}`,
{ cause },
);
}
const longMsg = protobuf_decode<LongMsgResult>(inflate);
const actions = Array.isArray(longMsg?.action) ? longMsg!.action! : [];
const mainAction = actions.find(item => item?.actionCommand === 'MultiMsg');
+20 -1
View File
@@ -51,7 +51,11 @@ function recvLongMsgResp(bodies: PushMsgBody[]) {
action: [{ actionCommand: 'MultiMsg', actionData: { msgBody: bodies } }],
};
const gz = gzipSync(Buffer.from(protobuf_encode<LongMsgResult>(longMsg)));
const resp = protobuf_encode<RecvLongMsgResp>({ result: { payload: new Uint8Array(gz) } });
return recvCompressedLongMsgResp(gz);
}
function recvCompressedLongMsgResp(payload: Uint8Array) {
const resp = protobuf_encode<RecvLongMsgResp>({ result: { payload } });
return { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.from(resp) };
}
@@ -169,6 +173,21 @@ describe('actions/forward', () => {
.rejects.toThrow(/download forward message failed|down/);
});
it('bounds long-message gunzip output and reports decompression context', async () => {
// This is one byte beyond the production 32 MiB ceiling but compresses to
// a small response, modelling an otherwise cheap gzip bomb from QQ.
const expandedBytes = (32 * 1024 * 1024) + 1;
const payload = gzipSync(Buffer.alloc(expandedBytes, 0x61));
const resId = 'oversized-compressed-forward';
const bridge = mockBridge({
sendRawPacket: vi.fn(async () => recvCompressedLongMsgResp(payload)) as any,
});
await expect(new ForwardApi(bridge as any).fetch(resId)).rejects.toThrow(
/download forward message decompression failed .*res_id=oversized-compressed-forward.*max_output_bytes=33554432/,
);
});
it('uploadForwardNodes recursively uploads nested innerForward chains (NapCat piggyback model)', async () => {
// Regression: nested forward needs the inner chain to be uploaded
// first (so we have its res_id for the outer ARK preview), AND