feat(core,onebot): debug-console stream-invoke + upload endpoints

Phase 2 of the debug-console expansion. Two backend endpoints under the
existing /api/* bearer auth:

- POST /api/debug/invoke-stream — drive a Stream API action (#163) and
  relay every frame to the browser over an SSE body. The frontend reads
  it with fetch()+a stream reader (header auth), so it needs no SSE
  query-token allowlist entry. Frames are NEVER dropped: backpressure is
  handled by waiting for the consumer to drain, not by discarding (a lost
  chunk corrupts a transfer). Non-stream actions emit a single frame.
- POST /api/debug/upload — stream a browser-selected file to a temp path
  on THIS server (the bot runs server-side, not on the operator's
  machine), so the path can feed a send action's file/image/record/video
  param. Raw bytes in the body (no multipart buffering), ?filename= for a
  readable suffix, streamed to disk under os.tmpdir()/snowluma-debug-
  upload with a 4 GiB cap and a 24h TTL sweep.

instance.invokeStream() delegates to ApiHandler.processStreamRequest.

Pure logic (filename sanitisation, fenced size-capped disk sink, the
stream-invoke Response builder) lives in debug-tools.ts with 12 unit
tests. Adversarially reviewed: path traversal is robust (19 hostile
filenames all fenced), frames provably never dropped, auth runs before
any disk write. Fixed a High found in review — the write stream had no
'error' listener (an async ENOSPC/EIO during flush would crash the whole
process) and a late-open race could leak a partial file; both now raced
into the awaits and cleaned up after 'close'.
This commit is contained in:
DrSmoothl committed 2026-06-30 16:19:59 +08:00
1 parent c839121fdb
commit a7667f1cd5
4 files changed
+395

No files matched your search

+197
View File
@@ -0,0 +1,197 @@
// debug-tools — backend for the debug console's two heavier endpoints
// (Phase 2 of the debug-console expansion):
//
// • POST /api/debug/invoke-stream — drive a Stream API action and relay every
// frame to the browser over an SSE body. Unlike the live-activity stream
// (debug-stream.ts), this MUST NOT drop frames: a file transfer that loses a
// chunk is corrupt. So backpressure is handled by *waiting* for the consumer
// to drain, never by dropping.
// • POST /api/debug/upload — stream a browser-selected file to a temp path on
// the SERVER (the bot runs on the server, not the user's machine), so the
// returned path can be fed to a send action. Streamed straight to disk with a
// byte cap — never buffered whole, so large videos don't blow up memory.
//
// The pure pieces live here (path sanitisation, the size-capped disk sink, the
// stream-invoke Response builder) so they are unit-testable away from Hono.
import { createWriteStream } from 'fs';
import { mkdir, readdir, rm, stat } from 'fs/promises';
import os from 'os';
import path from 'path';
import { randomBytes } from 'crypto';
/** Temp dir for browser→server uploads. Siblings the Stream API's temp root but
* kept distinct so the two cleanup stories don't entangle. */
export const DEBUG_UPLOAD_DIR = path.join(os.tmpdir(), 'snowluma-debug-upload');
/** Hard ceiling on a single upload. Mirrors the Stream API's upload cap. */
export const MAX_UPLOAD_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB
/** Uploads older than this are swept on the next upload (best-effort). */
const UPLOAD_TTL_MS = 24 * 60 * 60 * 1000;
/** Reduce a client-supplied filename to a safe basename (extension preserved),
* with no path separators or traversal. The client path is NEVER trusted for
* placement — this is only used to keep the stored name human-readable. */
export function safeUploadName(raw: string | undefined): string {
// Treat both separators as path delimiters, then take the basename so any
// `../` / absolute prefix is discarded regardless of host platform.
const base = path.basename(String(raw ?? '').replace(/\\/g, '/'));
const cleaned = base
.replace(/[^\w.\-]+/g, '_') // collapse anything exotic to underscore
.replace(/^\.+/, '') // no leading dots (no hidden / '..' names)
.slice(0, 120);
return cleaned || 'file';
}
/** Unguessable destination path under DEBUG_UPLOAD_DIR for a sanitised name.
* Throws if the composed path would escape the dir (defence in depth — it
* can't, given the random id + basename, but we assert anyway). */
export function uploadDestPath(safeName: string): string {
const id = randomBytes(12).toString('hex');
const dest = path.join(DEBUG_UPLOAD_DIR, `${id}__${safeName}`);
const rel = path.relative(DEBUG_UPLOAD_DIR, dest);
if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {
throw new Error('invalid upload path');
}
return dest;
}
/** Stream raw request-body bytes to a temp file under DEBUG_UPLOAD_DIR, enforcing
* a byte cap. Returns the final server path + byte size. On overflow or any
* error the partial file is removed and the call rejects. Never buffers the
* whole body. */
export async function streamUploadToDisk(
body: ReadableStream<Uint8Array> | null,
filename: string | undefined,
opts: { maxBytes?: number } = {},
): Promise<{ path: string; size: number }> {
if (!body) throw new Error('empty body');
const maxBytes = opts.maxBytes ?? MAX_UPLOAD_BYTES;
await mkdir(DEBUG_UPLOAD_DIR, { recursive: true });
void sweepOldUploads(); // fire-and-forget TTL cleanup
const dest = uploadDestPath(safeUploadName(filename));
const out = createWriteStream(dest, { mode: 0o600 });
// A WriteStream emits 'error' ASYNCHRONOUSLY (ENOSPC / EIO / quota) during a
// background flush — typically while we're parked at reader.read() or waiting
// on 'drain'. An unhandled 'error' event would crash the whole process, and a
// backpressured error would leave 'drain' to never fire (a forever-hung await
// + leaked fd). So turn it into a rejection and race it into every await; the
// catch below then destroys + unlinks the partial.
const errored = new Promise<never>((_, rej) => out.once('error', rej));
errored.catch(() => { /* swallow a late error after success (still raced below) */ });
let size = 0;
try {
const reader = body.getReader();
for (;;) {
const { done, value } = await Promise.race([errored, reader.read()]);
if (done) break;
if (!value || value.byteLength === 0) continue;
size += value.byteLength;
if (size > maxBytes) throw new Error('上传超出大小上限');
// Respect the write stream's backpressure (but never hang on an error).
if (!out.write(value)) {
await Promise.race([errored, new Promise<void>((res) => out.once('drain', res))]);
}
}
await Promise.race([errored, new Promise<void>((res, rej) => out.end((err?: Error | null) => (err ? rej(err) : res())))]);
if (size === 0) throw new Error('empty body');
return { path: dest, size };
} catch (err) {
// Wait for the stream to fully close BEFORE unlinking: createWriteStream
// opens the fd asynchronously, so a fast failure can reach `rm` before the
// file even exists on disk — then the late open would re-create it and leak
// the partial. 'close' guarantees the fd is settled and no more writes land.
out.destroy();
if (!out.closed) await new Promise<void>((res) => out.once('close', () => res()));
await rm(dest, { force: true }).catch(() => { /* best-effort */ });
throw err;
}
}
/** Remove upload temp files older than the TTL. Best-effort; never throws. */
export async function sweepOldUploads(now: number = Date.now()): Promise<number> {
let removed = 0;
try {
const names = await readdir(DEBUG_UPLOAD_DIR);
await Promise.all(
names.map(async (n) => {
const p = path.join(DEBUG_UPLOAD_DIR, n);
try {
const s = await stat(p);
if (now - s.mtimeMs > UPLOAD_TTL_MS) {
await rm(p, { force: true, recursive: true });
removed += 1;
}
} catch { /* racing cleanup / vanished file */ }
}),
);
} catch { /* dir absent yet */ }
return removed;
}
/** Drives a stream-capable action and relays its frames. The driver is the
* instance's `invokeStream` (which itself handles non-stream actions by emitting
* a single frame). */
export type StreamInvokeDriver = (
rawRequest: string,
emit: (json: string) => Promise<void>,
isAlive: () => boolean,
) => Promise<void>;
/** How long emit() will wait for a backed-up consumer to drain before it gives
* up waiting and enqueues anyway (the request abort / action idle-watchdog are
* the real stall guards). */
const DRAIN_WAIT_MS = 20;
const DRAIN_MAX_SPINS = 3000; // 3000 * 20ms ≈ 60s
/** Build the SSE `Response` for `/api/debug/invoke-stream`: each relayed frame
* is one `data: <json>\n\n` event; no frame is ever dropped. A driver error
* becomes a terminal `failed` frame. Closing the request (signal abort) stops
* delivery. `delay` is injectable for tests. */
export function buildStreamInvokeResponse(
driver: StreamInvokeDriver,
rawRequest: string,
signal: AbortSignal,
delay: (ms: number) => Promise<void> = (ms) => new Promise((r) => setTimeout(r, ms)),
): Response {
const encoder = new TextEncoder();
const stream = new ReadableStream<Uint8Array>({
async start(controller) {
let closed = false;
const onAbort = () => { closed = true; };
signal.addEventListener('abort', onAbort);
const isAlive = () => !closed && !signal.aborted;
const emit = async (json: string): Promise<void> => {
if (!isAlive()) throw new Error('stream transport closed');
// Backpressure WITHOUT dropping: wait for the consumer to catch up.
let spins = 0;
while (isAlive() && (controller.desiredSize ?? 1) <= 0 && spins < DRAIN_MAX_SPINS) {
await delay(DRAIN_WAIT_MS);
spins += 1;
}
if (!isAlive()) throw new Error('stream transport closed');
controller.enqueue(encoder.encode(`data: ${json}\n\n`));
};
try {
await driver(rawRequest, emit, isAlive);
} catch (err) {
if (isAlive()) {
const msg = err instanceof Error ? err.message : 'stream error';
try {
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ status: 'failed', retcode: 1400, message: msg, wording: msg })}\n\n`));
} catch { /* controller already torn down */ }
}
} finally {
signal.removeEventListener('abort', onAbort);
try { controller.close(); } catch { /* already closed */ }
}
},
});
return new Response(stream, {
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
});
}
+37
View File
@@ -22,6 +22,7 @@ import { coerceSettingsPatch } from './system-settings';
import { buildBackup, planRestore, validateBackup } from './backup';
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
import { createFramePusher } from './debug-stream';
import { buildStreamInvokeResponse, streamUploadToDisk } from './debug-tools';
import { bindStateStream } from './state-stream';
import type { StateBus, StateResource } from './state-bus';
import { startConnectionDiffLoop } from './connection-diff-loop';
@@ -929,6 +930,42 @@ export async function initWebUI(
return c.json(result);
});
// Invoke a Stream API action (or any action) and relay every frame to the
// browser over an SSE body. The frontend reads this with fetch()+a stream
// reader (Bearer auth in the header), so — unlike /api/debug/stream — it does
// NOT need a query-token allowlist entry. Frames are never dropped.
app.post('/api/debug/invoke-stream', async (c) => {
let body: unknown;
try { body = await c.req.json(); } catch { return c.json({ status: 'failed', message: '请求格式错误' }, 400); }
const { uin, action, params } = (body ?? {}) as { uin?: unknown; action?: unknown; params?: unknown };
if (typeof uin !== 'string' || !UIN_REGEX.test(uin)) return c.json({ status: 'failed', message: '无效的账号' }, 400);
if (typeof action !== 'string' || !action) return c.json({ status: 'failed', message: 'action 必填' }, 400);
if (params !== undefined && (typeof params !== 'object' || params === null || Array.isArray(params))) {
return c.json({ status: 'failed', message: 'params 必须是对象' }, 400);
}
const inst = oneBotManager.getInstance(uin);
if (!inst) return c.json({ status: 'failed', message: '账号不在线' }, 404);
const rawRequest = JSON.stringify({ action, params: params ?? {} });
return buildStreamInvokeResponse(
(rq, emit, alive) => inst.invokeStream(rq, emit, alive),
rawRequest,
c.req.raw.signal,
);
});
// Stream a browser-selected file to a temp path on THIS server (the bot runs
// here, not on the operator's machine), so the returned path can be fed to a
// send action's file/image/record/video param. Raw bytes in the body,
// `?filename=` for a human-readable suffix; streamed to disk with a byte cap.
app.post('/api/debug/upload', async (c) => {
try {
const result = await streamUploadToDisk(c.req.raw.body as ReadableStream<Uint8Array> | null, c.req.query('filename'));
return c.json({ status: 'ok', path: result.path, size: result.size });
} catch (err) {
return c.json({ status: 'failed', message: err instanceof Error ? err.message : '上传失败' }, 400);
}
});
// Live merged SSE of OneBot events + action calls across all accounts. Taps
// are attached only while a client is connected (on-demand). A slow client is
// dropped (not back-pressured onto the bot) with a periodic drop marker.
@@ -0,0 +1,151 @@
import { afterAll, describe, expect, it } from 'vitest';
import { readdir, readFile, rm } from 'fs/promises';
import path from 'path';
import {
buildStreamInvokeResponse,
DEBUG_UPLOAD_DIR,
safeUploadName,
streamUploadToDisk,
uploadDestPath,
} from '../src/webui/debug-tools';
const written: string[] = [];
afterAll(async () => {
await Promise.all(written.map((p) => rm(p, { force: true }).catch(() => {})));
});
function streamOf(...chunks: Uint8Array[]): ReadableStream<Uint8Array> {
let i = 0;
return new ReadableStream<Uint8Array>({
pull(controller) {
if (i < chunks.length) controller.enqueue(chunks[i++]);
else controller.close();
},
});
}
async function readSse(res: Response): Promise<string[]> {
const text = await res.text();
return text.split('\n\n').filter((s) => s.startsWith('data: ')).map((s) => s.slice('data: '.length));
}
describe('safeUploadName', () => {
it('strips path traversal and separators to a bare basename', () => {
expect(safeUploadName('../../etc/passwd')).toBe('passwd');
expect(safeUploadName('/abs/secret.key')).toBe('secret.key');
expect(safeUploadName('a\\b\\c.png')).toBe('c.png');
expect(safeUploadName('..')).toBe('file'); // leading dots stripped → empty → fallback
expect(safeUploadName('...hidden')).toBe('hidden');
});
it('collapses exotic chars and falls back for empties', () => {
expect(safeUploadName('my pic!@#.jpg')).toBe('my_pic_.jpg');
expect(safeUploadName('')).toBe('file');
expect(safeUploadName(undefined)).toBe('file');
});
it('keeps the extension and caps length', () => {
const long = 'x'.repeat(500) + '.mp4';
const out = safeUploadName(long);
expect(out.length).toBeLessThanOrEqual(120);
expect(out.startsWith('x')).toBe(true);
});
});
describe('uploadDestPath', () => {
it('produces a unique path inside the upload dir', () => {
const a = uploadDestPath('pic.png');
const b = uploadDestPath('pic.png');
expect(a).not.toBe(b); // random id prefix
expect(path.dirname(a)).toBe(DEBUG_UPLOAD_DIR);
expect(a.endsWith('__pic.png')).toBe(true);
const rel = path.relative(DEBUG_UPLOAD_DIR, a);
expect(rel.startsWith('..')).toBe(false);
expect(path.isAbsolute(rel)).toBe(false);
});
});
describe('streamUploadToDisk', () => {
it('streams bytes to disk and reports the size', async () => {
const data = new TextEncoder().encode('hello debug upload');
const res = await streamUploadToDisk(streamOf(data.slice(0, 5), data.slice(5)), 'note.txt');
written.push(res.path);
expect(res.size).toBe(data.byteLength);
expect(path.dirname(res.path)).toBe(DEBUG_UPLOAD_DIR);
expect(await readFile(res.path, 'utf8')).toBe('hello debug upload');
});
it('rejects and removes the partial file when the cap is exceeded', async () => {
const big = new Uint8Array(64);
await expect(
streamUploadToDisk(streamOf(big, big), 'big.bin', { maxBytes: 100 }),
).rejects.toThrow(/大小上限/);
// the partial must not survive — no leftover `__big.bin` in the dir
const names = await readdir(DEBUG_UPLOAD_DIR).catch(() => [] as string[]);
expect(names.filter((n) => n.endsWith('__big.bin'))).toEqual([]);
});
it('rejects an empty body', async () => {
await expect(streamUploadToDisk(null, 'x')).rejects.toThrow(/empty/);
await expect(streamUploadToDisk(streamOf(), 'x')).rejects.toThrow(/empty/);
});
it('propagates a mid-transfer source error and removes the partial', async () => {
const failing = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new TextEncoder().encode('partial-bytes'));
controller.error(new Error('source aborted'));
},
});
await expect(streamUploadToDisk(failing, 'oops.bin')).rejects.toThrow(/source aborted/);
const names = await readdir(DEBUG_UPLOAD_DIR).catch(() => [] as string[]);
expect(names.filter((n) => n.endsWith('__oops.bin'))).toEqual([]);
});
});
describe('buildStreamInvokeResponse', () => {
const noDelay = async () => {};
it('relays each emitted frame as one SSE event, in order', async () => {
const ac = new AbortController();
const driver = async (_rq: string, emit: (j: string) => Promise<void>) => {
await emit(JSON.stringify({ data: { type: 'stream', i: 1 } }));
await emit(JSON.stringify({ data: { type: 'stream', i: 2 } }));
await emit(JSON.stringify({ status: 'ok', data: { type: 'response' } }));
};
const res = buildStreamInvokeResponse(driver, '{"action":"x"}', ac.signal, noDelay);
const frames = (await readSse(res)).map((s) => JSON.parse(s));
expect(frames).toHaveLength(3);
expect(frames[0].data.i).toBe(1);
expect(frames[2].data.type).toBe('response');
});
it('turns a driver error into a terminal failed frame', async () => {
const ac = new AbortController();
const driver = async (_rq: string, emit: (j: string) => Promise<void>) => {
await emit(JSON.stringify({ data: { type: 'stream' } }));
throw new Error('disk exploded');
};
const res = buildStreamInvokeResponse(driver, '{}', ac.signal, noDelay);
const frames = (await readSse(res)).map((s) => JSON.parse(s));
expect(frames).toHaveLength(2);
expect(frames[1].status).toBe('failed');
expect(frames[1].message).toMatch(/disk exploded/);
});
it('passes the raw request through to the driver', async () => {
const ac = new AbortController();
let seen = '';
const driver = async (rq: string, emit: (j: string) => Promise<void>) => {
seen = rq;
await emit('{"data":{"type":"response"}}');
};
const res = buildStreamInvokeResponse(driver, '{"action":"test_download_stream"}', ac.signal, noDelay);
await readSse(res);
expect(seen).toBe('{"action":"test_download_stream"}');
});
it('exposes an SSE content-type', () => {
const ac = new AbortController();
const res = buildStreamInvokeResponse(async () => {}, '{}', ac.signal, noDelay);
expect(res.headers.get('Content-Type')).toBe('text/event-stream');
});
});
+10
View File
@@ -73,6 +73,16 @@ export class OneBotInstance {
invokeAction(action: string, params: JsonObject): Promise<ApiResponse> {
return this.apiHandler.handle(action, params);
}
/** Drive an action through the streaming seam (debug tester, stream actions).
* `rawRequest` is a `{action, params, echo?}` JSON string; `emit` receives
* each frame as a JSON string. Non-stream actions emit a single frame. */
invokeStream(
rawRequest: string,
emit: (json: string) => void | Promise<void>,
isAlive?: () => boolean,
): Promise<void> {
return this.apiHandler.processStreamRequest(rawRequest, emit, isAlive);
}
constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig, globalSettings: GlobalSettings) {
this.uin = uin;