diff --git a/packages/core/tests/highway-utils.test.ts b/packages/core/tests/highway-utils.test.ts index a6fa17d6..bcbe5c2f 100644 --- a/packages/core/tests/highway-utils.test.ts +++ b/packages/core/tests/highway-utils.test.ts @@ -25,6 +25,29 @@ describe('highway source paths', () => { try { fs.unlinkSync(filePath); } catch { /* ignore */ } } }); + + it('loads base64 data URLs as inline bytes', async () => { + const loaded = await loadBinarySource('data:audio/webm;base64,AQID', 'record', 64); + + expect({ bytes: Array.from(loaded.bytes), fileName: loaded.fileName }) + .toEqual({ bytes: [1, 2, 3], fileName: '' }); + }); + + it('never classifies data URLs as local file paths', () => { + expect(resolveLocalFilePath('data:audio/webm;base64,AQID')).toBeNull(); + }); + + it('rejects non-base64 data URLs explicitly', async () => { + await expect( + loadBinarySource('data:text/plain,hello', 'record', 64), + ).rejects.toThrow(/data URL source must use base64 encoding/); + }); + + it('requires the RFC 2397 base64 flag instead of a base64 media type', async () => { + await expect( + loadBinarySource('data:base64,AQID', 'record', 64), + ).rejects.toThrow(/data URL source must use base64 encoding/); + }); }); describe('loadBinarySource maxBytes enforcement', () => { @@ -98,6 +121,13 @@ describe('loadBinarySource maxBytes enforcement', () => { loadBinarySource(`base64://${big}`, 'test', 64), ).rejects.toThrow(/too large: 128 > 64/); }); + + it('rejects oversized base64 data URL payloads', async () => { + const big = Buffer.alloc(128).toString('base64'); + await expect( + loadBinarySource(`data:audio/webm;base64,${big}`, 'test', 64), + ).rejects.toThrow(/too large: 128 > 64/); + }); }); describe('loadBinarySource HTTP header hardening', () => { diff --git a/packages/core/tests/highway/stage.test.ts b/packages/core/tests/highway/stage.test.ts index 93a60159..797cddd4 100644 --- a/packages/core/tests/highway/stage.test.ts +++ b/packages/core/tests/highway/stage.test.ts @@ -38,12 +38,34 @@ describe('stageSourceToDisk — base64', () => { } finally { await staged.cleanup(); } }); + it('stages base64 data URLs to disk', async () => { + const data = Buffer.from('hello data URL'); + const staged = await stageSourceToDisk( + `data:audio/webm;codecs=opus;base64,${data.toString('base64')}`, + 1024, + ); + try { + expect(staged.fileSize).toBe(data.length); + expect(staged.fileName).toBe(''); + expect((await readStaged(staged.filePath)).equals(data)).toBe(true); + } finally { await staged.cleanup(); } + }); + it('rejects oversized base64 on decoded length (before allocation) and leaves no temp', async () => { const big = Buffer.alloc(4096).toString('base64'); await expect(stageSourceToDisk(`base64://${big}`, 64)).rejects.toThrow(/too large/); const parts = (await fsp.readdir(STAGE_DIR).catch(() => [] as string[])).filter((n) => n.endsWith('.part')); expect(parts).toEqual([]); }); + + it('rejects oversized base64 data URLs before allocation and leaves no temp', async () => { + const big = Buffer.alloc(4096).toString('base64'); + await expect( + stageSourceToDisk(`data:audio/webm;base64,${big}`, 64), + ).rejects.toThrow(/too large/); + const parts = (await fsp.readdir(STAGE_DIR).catch(() => [] as string[])).filter((n) => n.endsWith('.part')); + expect(parts).toEqual([]); + }); }); describe('stageSourceToDisk — http', () => { diff --git a/packages/protocol/src/highway/stage.ts b/packages/protocol/src/highway/stage.ts index 6ece7810..9998eeab 100644 --- a/packages/protocol/src/highway/stage.ts +++ b/packages/protocol/src/highway/stage.ts @@ -10,7 +10,7 @@ // http(s):// → stream the download to a .part file, fsync, atomic // rename (shares the exact transport of loadBinarySource // via downloadHttp — same UA/redirect/timeout/retry/caps). -// base64:// → enforce maxBytes on the DECODED length, then decode to +// base64:// / data: → enforce maxBytes on the DECODED length, then decode to // a .part file and rename. // // Crash safety: staged temps are written `.part` → fsync → rename → fsync(dir), @@ -23,7 +23,12 @@ import os from 'os'; import path from 'path'; import { randomUUID } from 'crypto'; import { createLogger } from '@snowluma/common/logger'; -import { downloadHttp, resolveLocalFilePath, type DownloadSink } from './utils'; +import { + downloadHttp, + inlineBase64Payload, + resolveLocalFilePath, + type DownloadSink, +} from './utils'; const log = createLogger('Highway.Stage'); @@ -155,9 +160,9 @@ export async function stageSourceToDisk(source: string, maxBytes: number): Promi ensureReaper(); await fsp.mkdir(STAGE_DIR, { recursive: true }); - // ── base64:// ────────────────────────────────────────────────────────── - if (/^base64:\/\//i.test(source)) { - const b64 = source.slice(9); + // ── inline Base64 (`base64://` or RFC 2397 `data:`) ──────────────────── + const b64 = inlineBase64Payload(source); + if (b64 !== null) { const decodedLen = base64DecodedLength(b64); if (decodedLen > maxBytes) { throw new Error(`stage source too large: ${decodedLen} > ${maxBytes}`); @@ -178,7 +183,7 @@ export async function stageSourceToDisk(source: string, maxBytes: number): Promi } finally { active.delete(partPath); } - log.debug('staged base64 source (%d bytes)', bytes.length); + log.debug('staged inline base64 source (%d bytes)', bytes.length); return registerStaged(finalPath, bytes.length, ''); } diff --git a/packages/protocol/src/highway/utils.ts b/packages/protocol/src/highway/utils.ts index 0e428e85..9e785085 100644 --- a/packages/protocol/src/highway/utils.ts +++ b/packages/protocol/src/highway/utils.ts @@ -50,9 +50,31 @@ export interface ImageFormat { // --- Binary source loading --- +/** + * Return the encoded payload for an inline Base64 source. + * + * OneBot historically accepts the shorthand `base64://...`; media elements + * also accept RFC 2397 Data URLs such as `data:audio/webm;base64,...`. Keep + * their classification in one place so Data URLs can never fall through to + * the local-file path. + */ +export function inlineBase64Payload(source: string): string | null { + if (/^base64:\/\//i.test(source)) return source.slice(9); + if (!/^data:/i.test(source)) return null; + + const comma = source.indexOf(','); + if (comma < 0) throw new Error('data URL source is missing its payload separator'); + + const metadata = source.slice(5, comma); + if (!/;base64$/i.test(metadata)) { + throw new Error('data URL source must use base64 encoding'); + } + return source.slice(comma + 1); +} + export function resolveLocalFilePath(source: string): string | null { if (!source) return null; - if (/^base64:\/\//i.test(source)) return null; + if (/^(?:base64:\/\/|data:)/i.test(source)) return null; if (/^https?:\/\//i.test(source)) return null; let filePath = source; @@ -187,8 +209,9 @@ export async function loadBinarySource( ): Promise { if (!source) throw new Error(`${resourceName} source is empty`); - if (/^base64:\/\//i.test(source)) { - const bytes = Buffer.from(source.slice(9), 'base64'); + const inlinePayload = inlineBase64Payload(source); + if (inlinePayload !== null) { + const bytes = Buffer.from(inlinePayload, 'base64'); if (bytes.length > maxBytes) { throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`); }