fix(onebot): bound download_file and drop unused error helper
PR #39 hardened most of the OneBot action surface but left download_file on the original `await response.arrayBuffer()` path — an authenticated client could still hand us a multi-GB URL (or a chunked response with no Content-Length) and OOM the bot. The base64 branch had the same problem in the other direction: `Buffer.from(huge, 'base64')` allocates the decoded payload before any size check. Match the loadBinarySource pattern that `0804351` introduced for highway uploads: * HTTP path runs through `fetchDownloadFile`: AbortSignal.timeout (60s), Content-Length precheck, then a streaming reader that aborts the moment the running total crosses the 1 GiB cap. * Base64 path rejects before `Buffer.from` based on the upper-bound `floor(len * 3 / 4)`, with a post-decode check for safety. * Writes go through `fs.promises.writeFile` so a multi-hundred-MB download doesn't stall every other bot action on the event loop. Also drop the `actionFailed` helper added in the same PR — it was intended as a sanitized-error wrapper but never wired up. Wiring it into the dozen-or-so `String(e)` sites is its own cleanup; for now remove the dead code (and the no-longer-used createLogger import).
This commit is contained in:
1 file changed
+82
-26
@@ -2,18 +2,61 @@ import type { ApiHandler, ApiActionContext } from '../api-handler';
|
|||||||
import { asMessage, asNumber, asString, asBoolean } from '../api-handler';
|
import { asMessage, asNumber, asString, asBoolean } from '../api-handler';
|
||||||
import type { ForwardPreviewMeta } from '../modules/message-actions';
|
import type { ForwardPreviewMeta } from '../modules/message-actions';
|
||||||
import { RETCODE, failedResponse, okResponse } from '../types';
|
import { RETCODE, failedResponse, okResponse } from '../types';
|
||||||
import { createLogger } from '../../utils/logger';
|
|
||||||
|
|
||||||
const log = createLogger('OneBot.Action');
|
// Bounded download for the OneBot `download_file` action. An authenticated
|
||||||
|
// client could otherwise hand us a multi-GB URL (or chunked response with
|
||||||
|
// no Content-Length) and OOM the bot — `await response.arrayBuffer()`
|
||||||
|
// happily allocates the whole payload before any size check fires.
|
||||||
|
const DOWNLOAD_FILE_MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB
|
||||||
|
const DOWNLOAD_FILE_TIMEOUT_MS = 60_000;
|
||||||
|
|
||||||
/**
|
async function fetchDownloadFile(
|
||||||
* Standard error wrapper. Logs the full error (so operators can debug) but
|
url: string,
|
||||||
* surfaces only `Error.message` (or the supplied fallback) to the caller.
|
headers: Record<string, string>,
|
||||||
*/
|
maxBytes: number,
|
||||||
function actionFailed(action: string, err: unknown, fallback = 'action failed') {
|
timeoutMs: number,
|
||||||
const detail = err instanceof Error ? err.message : String(err);
|
): Promise<Buffer> {
|
||||||
log.warn('%s failed: %s', action, detail);
|
const response = await fetch(url, {
|
||||||
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : fallback);
|
headers,
|
||||||
|
signal: AbortSignal.timeout(timeoutMs),
|
||||||
|
});
|
||||||
|
if (!response.ok) throw new Error(`download failed: HTTP ${response.status}`);
|
||||||
|
|
||||||
|
const declared = Number(response.headers.get('content-length') ?? '0');
|
||||||
|
if (Number.isFinite(declared) && declared > maxBytes) {
|
||||||
|
throw new Error(`download too large: ${declared} > ${maxBytes}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const reader = response.body?.getReader();
|
||||||
|
if (!reader) {
|
||||||
|
const bytes = Buffer.from(await response.arrayBuffer());
|
||||||
|
if (bytes.length > maxBytes) {
|
||||||
|
throw new Error(`download too large: ${bytes.length} > ${maxBytes}`);
|
||||||
|
}
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stream so a server that omits / understates Content-Length can't make
|
||||||
|
// us buffer past maxBytes — abort the read as soon as the running total
|
||||||
|
// crosses the cap.
|
||||||
|
const chunks: Uint8Array[] = [];
|
||||||
|
let total = 0;
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
if (!value) continue;
|
||||||
|
total += value.byteLength;
|
||||||
|
if (total > maxBytes) {
|
||||||
|
await reader.cancel().catch(() => { /* ignore */ });
|
||||||
|
throw new Error(`download too large: > ${maxBytes}`);
|
||||||
|
}
|
||||||
|
chunks.push(value);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
reader.releaseLock();
|
||||||
|
}
|
||||||
|
return Buffer.concat(chunks, total);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -581,25 +624,38 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void {
|
|||||||
return resolved;
|
return resolved;
|
||||||
};
|
};
|
||||||
|
|
||||||
let filePath: string;
|
let buf: Buffer;
|
||||||
if (base64) {
|
if (base64) {
|
||||||
const buf = Buffer.from(base64, 'base64');
|
// Every 4 base64 chars decode to at most 3 bytes. Reject before
|
||||||
const safe = resolveSafePath(name, buf);
|
// `Buffer.from` allocates anything to avoid OOM on a giant payload
|
||||||
if (!safe) return failedResponse(RETCODE.BAD_REQUEST, 'invalid file name');
|
// that wouldn't pass the post-decode check anyway.
|
||||||
filePath = safe;
|
const upperBound = Math.floor((base64.length * 3) / 4);
|
||||||
fs.writeFileSync(filePath, buf);
|
if (upperBound > DOWNLOAD_FILE_MAX_BYTES) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: > ${DOWNLOAD_FILE_MAX_BYTES} bytes`);
|
||||||
|
}
|
||||||
|
buf = Buffer.from(base64, 'base64');
|
||||||
|
if (buf.length > DOWNLOAD_FILE_MAX_BYTES) {
|
||||||
|
return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: ${buf.length} > ${DOWNLOAD_FILE_MAX_BYTES} bytes`);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
const response = await fetch(url!, {
|
try {
|
||||||
headers: parseDownloadHeaders(params.headers),
|
buf = await fetchDownloadFile(
|
||||||
});
|
url!,
|
||||||
if (!response.ok) return failedResponse(RETCODE.ACTION_FAILED, `download failed: ${response.status}`);
|
parseDownloadHeaders(params.headers),
|
||||||
const buf = Buffer.from(await response.arrayBuffer());
|
DOWNLOAD_FILE_MAX_BYTES,
|
||||||
const safe = resolveSafePath(name, buf);
|
DOWNLOAD_FILE_TIMEOUT_MS,
|
||||||
if (!safe) return failedResponse(RETCODE.BAD_REQUEST, 'invalid file name');
|
);
|
||||||
filePath = safe;
|
} catch (err) {
|
||||||
fs.writeFileSync(filePath, buf);
|
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return okResponse({ file: filePath });
|
|
||||||
|
const safe = resolveSafePath(name, buf);
|
||||||
|
if (!safe) return failedResponse(RETCODE.BAD_REQUEST, 'invalid file name');
|
||||||
|
// Async write so we don't block the event loop on a GiB-class download
|
||||||
|
// (the prior `writeFileSync` stalled every other bot action while it ran).
|
||||||
|
await fs.promises.writeFile(safe, buf);
|
||||||
|
return okResponse({ file: safe });
|
||||||
});
|
});
|
||||||
|
|
||||||
h.registerAction('set_qq_profile', async (params) => {
|
h.registerAction('set_qq_profile', async (params) => {
|
||||||
|
|||||||
Reference in new issue
Block a user