Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(ghost): recover media MIME from response bytes (#233)

Lizifd299c8408eb
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.ts
index 257d7d1923..13bd402ac3 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.ts
@@ -11,6 +11,7 @@ import { GhostNetworkSlot, type NetworkSlotDeps } from '../networkSlot';
import {
GHOST_FETCH_DIR_UPLOAD_MAX_BYTES_PER_FILE,
GHOST_FETCH_INFLIGHT_LIMIT,
+ GHOST_FETCH_MEDIA_MAX_BYTES,
GHOST_FETCH_RESPONSE_MAX_BYTES,
GHOST_FETCH_UPLOAD_MAX_BYTES_PER_FILE,
type GhostNetworkNeeds,
@@ -72,6 +73,24 @@ function fakeResponse(params: {
} as unknown as Response;
}
+function mp3WithId3(tagSize = 0): Uint8Array {
+ return new Uint8Array([
+ 0x49, 0x44, 0x33, 0x04, 0x00, 0x00,
+ (tagSize >>> 21) & 0x7f,
+ (tagSize >>> 14) & 0x7f,
+ (tagSize >>> 7) & 0x7f,
+ tagSize & 0x7f,
+ ...new Uint8Array(tagSize),
+ 0xff, 0xfb, 0x90, 0x64,
+ ]);
+}
+
+function toArrayBuffer(bytes: Uint8Array): ArrayBuffer {
+ const copy = new Uint8Array(bytes.byteLength);
+ copy.set(bytes);
+ return copy.buffer;
+}
+
function makeSlot(overrides: Partial<NetworkSlotDeps> = {}): {
slot: GhostNetworkSlot;
fetchImpl: ReturnType<typeof vi.fn>;
@@ -413,7 +432,7 @@ describe('networkSlot · 响应收敛', () => {
fetchImpl: (async (url: string) => {
if (String(url).includes('/big')) return bigTextResponse();
if (String(url).includes('brave')) {
- return fakeResponse({ headers: { 'content-type': 'image/png' }, body: new Uint8Array([0x89, 0x50, 0x4e, 0x47]).buffer });
+ return fakeResponse({ headers: { 'content-type': 'image/png' }, body: new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).buffer });
}
return fakeResponse();
}) as unknown as NetworkSlotDeps['fetchImpl'],
@@ -455,7 +474,7 @@ describe('networkSlot · 响应收敛', () => {
});
describe('networkSlot · 媒体模式(as:media,字节不进沙箱)', () => {
- const pngBytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 1, 2, 3]);
+ const pngBytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3]);
const pngResponse = (headers: Record<string, string> = {}) =>
fakeResponse({ headers: { 'content-type': 'image/png', ...headers }, body: pngBytes.buffer.slice(0) });
@@ -478,9 +497,454 @@ describe('networkSlot · 媒体模式(as:media,字节不进沙箱)', () => {
expect(Array.from(buf.slice(0, 4))).toEqual([0x89, 0x50, 0x4e, 0x47]);
});
+ it('text/plain 误报的 MP3 按 ID3 / MPEG frame 魔数恢复为 audio/mpeg', async () => {
+ for (const bytes of [
+ mp3WithId3(),
+ new Uint8Array([0xff, 0xfb, 0x90, 0x64]),
+ ]) {
+ const { slot, saveGhostMedia } = makeSlot({
+ fetchImpl: async () => fakeResponse({ headers: { 'content-type': 'text/plain' }, body: toArrayBuffer(bytes) }),
+ });
+ const r = await slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
+ expect(r.ok && 'media' in r).toBe(true);
+ expect((saveGhostMedia.mock.calls[0][0] as { mimeType: string }).mimeType).toBe('audio/mpeg');
+ }
+ });
+
+ it('text/plain 流式 MP3 在探针边界后仍按魔数恢复', async () => {
+ for (const chunks of [
+ [mp3WithId3(8192)],
+ [mp3WithId3(8192).subarray(0, 4096), mp3WithId3(8192).subarray(4096)],
+ ]) {
+ const stream = new ReadableStream<Uint8Array>({
+ start(controller) {
+ for (const chunk of chunks) controller.enqueue(chunk);
+ controller.close();
+ },
+ });
+ const { slot, saveGhostMedia } = makeSlot({
+ fetchImpl: async () => ({
+ status: 200,
+ headers: new Headers({ 'content-type': 'text/plain' }),
+ body: stream,
+ }) as unknown as Response,
+ });
+ const r = await slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
+ expect(r.ok && 'media' in r).toBe(true);
+ expect((saveGhostMedia.mock.calls[0][0] as { mimeType: string }).mimeType).toBe('audio/mpeg');
+ const savedBytes = (saveGhostMedia.mock.calls[0][0] as { buffer: Uint8Array }).buffer;
+ expect(savedBytes.byteLength).toBe(chunks.reduce((total, chunk) => total + chunk.byteLength, 0));
+ }
+ });
+
+ it('泛化 MIME 的媒体按魔数落仓;真实 text/plain / 缺头文本仍回落 body', async () => {
+ for (const contentType of ['application/octet-stream', '']) {
+ const bytes = mp3WithId3();
+ const { slot, saveGhostMedia } = makeSlot({
+ fetchImpl: async () => fakeResponse({ headers: contentType ? { 'content-type': contentType } : {}, body: toArrayBuffer(bytes) }),
+ });
+ const r = await slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
+ expect(r.ok && 'media' in r, contentType || '(empty)').toBe(true);
+ expect((saveGhostMedia.mock.calls[0][0] as { mimeType: string }).mimeType).toBe('audio/mpeg');
+ }
+
+ for (const contentType of ['text/plain', '']) {
+ const { slot, saveGhostMedia } = makeSlot({
+ fetchImpl: async () => fakeResponse({ headers: contentType ? { 'content-type': contentType } : {}, body: '{"status":"processing"}' }),
+ });
+ const r = await slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
+ expect(r.ok && 'body' in r, contentType || '(empty)').toBe(true);
+ if (r.ok && 'body' in r) expect(r.body).toBe('{"status":"processing"}');
+ expect(saveGhostMedia).not.toHaveBeenCalled();
+ }
+ });
+
+ it('UTF-8 文本跨 4 KiB 探针边界时仍可回落', async () => {
+ const prefix = new Uint8Array(4095).fill(97);
+ const suffix = new TextEncoder().encode('中文');
+ const bytes = new Uint8Array(prefix.byteLength + suffix.byteLength);
+ bytes.set(prefix);
+ bytes.set(suffix, prefix.byteLength);
+ const { slot, saveGhostMedia } = makeSlot({
+ fetchImpl: async () => fakeResponse({
+ headers: { 'content-type': 'application/octet-stream' },
+ body: bytes.buffer,
+ }),
+ });
+ const r = await slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
+ expect(r.ok && 'body' in r).toBe(true);
+ expect(saveGhostMedia).not.toHaveBeenCalled();
+ });
+
+ it('application/octet-stream 的未知二进制识别失败后拒绝且不回流 body', async () => {
+ const zip = new Uint8Array([0x50, 0x4b, 0x03, 0x04]);
+ const { slot, saveGhostMedia } = makeSlot({
+ fetchImpl: async () => fakeResponse({ headers: { 'content-type': 'application/octet-stream' }, body: zip.buffer.slice(0) }),
+ });
+ const r = await slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.message).toContain('不受总仓支持');
+ expect(saveGhostMedia).not.toHaveBeenCalled();
+ });
+
+ it('application/octet-stream 的 JSON 回落文本;未知二进制、NUL 与非法 UTF-8 拒绝', async () => {
+ const json = makeSlot({
+ fetchImpl: async () => fakeResponse({ headers: { 'content-type': 'application/octet-stream' }, body: '{"status":"processing"}' }),
+ });
+ const text = await json.slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
+ expect(text.ok && 'body' in text).toBe(true);
+
+ for (const bytes of [
+ new Uint8Array([0x50, 0x4b, 0x03, 0x04]),
+ new Uint8Array([0x7b, 0x00, 0x7d]),
+ new Uint8Array([0xc3, 0x28]),
+ new Uint8Array([0xc3]),
+ ]) {
+ const { slot, saveGhostMedia } = makeSlot({
+ fetchImpl: async () => fakeResponse({ headers: { 'content-type': 'application/octet-stream' }, body: bytes.buffer.slice(0) }),
+ });
+ expect((await slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' })).ok).toBe(false);
+ expect(saveGhostMedia).not.toHaveBeenCalled();
+ }
+ });
+
+ it('流式短响应以截断 UTF-8 结尾时拒绝回落', async () => {
+ const stream = new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(new Uint8Array([0x61, 0xc3]));
+ controller.close();
+ },
+ });
+ const { slot, saveGhostMedia } = makeSlot({
+ fetchImpl: async () => ({
+ status: 200,
+ headers: new Headers({ 'content-type': 'application/octet-stream' }),
+ body: stream,
+ }) as unknown as Response,
+ });
+ expect((await slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' })).ok).toBe(false);
+ expect(saveGhostMedia).not.toHaveBeenCalled();
+ });
+
+ it('流式文本探针后的 NUL / 非法 UTF-8 尾部拒绝回落', async () => {
+ const stream = new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(new Uint8Array(4096).fill(0x61));
+ controller.enqueue(new Uint8Array([0x00]));
+ controller.close();
+ },
+ });
+ const { slot, saveGhostMedia } = makeSlot({
+ fetchImpl: async () => ({
+ status: 200,
+ headers: new Headers({ 'content-type': 'text/plain' }),
+ body: stream,
+ }) as unknown as Response,
+ });
+ expect((await slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' })).ok).toBe(false);
+ expect(saveGhostMedia).not.toHaveBeenCalled();
+ });
+
+ it('媒体模式下空文本响应回落为空 body', async () => {
+ const cases: Array<Record<string, string>> = [
+ { 'content-type': 'text/plain' },
+ {},
+ ];
+ for (const headers of cases) {
+ const { slot, saveGhostMedia } = makeSlot({
+ fetchImpl: async () => fakeResponse({ headers, body: new ArrayBuffer(0) }),
+ });
+ const r = await slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
+ expect(r.ok && 'body' in r).toBe(true);
+ if (r.ok && 'body' in r) expect(r.body).toBe('');
+ expect(saveGhostMedia).not.toHaveBeenCalled();
+ }
+ });
+
+ it('流式 sniff 文本在首次小 chunk 后跨过大文本门槛时先申请全局闸', async () => {
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => (release = resolve));
+ let cancelled = false;
+ const { slot } = makeSlot({
+ fetchImpl: async (url: string) => {
+ if (url.includes('/large-text')) {
+ return {
+ status: 200,
+ headers: new Headers({ 'content-type': 'text/plain' }),
+ body: new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(new TextEncoder().encode('{"status":"processing"}'));
+ controller.enqueue(new Uint8Array(2 * 1024 * 1024).fill(0x61));
+ },
+ cancel() {
+ cancelled = true;
+ },
+ }),
+ } as unknown as Response;
+ }
+ return pngResponse();
+ },
+ saveGhostMedia: (async () => {
+ await gate;
+ return { url: 'cindy-media://blobs/abc.png', hash: 'a'.repeat(64), ext: '.png' };
+ }) as unknown as NetworkSlotDeps['saveGhostMedia'],
+ });
+ const media = slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ const text = await slot.handleFetchRequest('web-search', {
+ url: 'https://api.tavily.com/large-text',
+ as: 'media',
+ });
+ expect(text.ok).toBe(false);
+ if (!text.ok) expect(text.message).toContain('正忙');
+ expect(cancelled).toBe(true);
+ release();
+ expect((await media).ok).toBe(true);
+ });
+
+ it('声明 video/quicktime 时接受无 ftyp 的合法首 atom', async () => {
+ const mov = new Uint8Array([0, 0, 0, 8, 0x6d, 0x6f, 0x6f, 0x76]);
+ const { slot, saveGhostMedia } = makeSlot({
+ fetchImpl: async () => fakeResponse({
+ headers: { 'content-type': 'video/quicktime' },
+ body: toArrayBuffer(mov),
+ }),
+ isSupportedMediaMime: (mime) => mime === 'video/quicktime',
+ });
+ const r = await slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
+ expect(r.ok && 'media' in r).toBe(true);
+ expect((saveGhostMedia.mock.calls[0][0] as { mimeType: string }).mimeType).toBe('video/quicktime');
+ });
+
+ it('流式 sniff 文本在保留大 chunk 前先申请全局闸', async () => {
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => (release = resolve));
+ let cancelled = false;
+ const fetchImpl = vi.fn(async (url: string) => {
+ if (url.includes('/large-text')) {
+ return {
+ status: 200,
+ headers: new Headers({ 'content-type': 'text/plain' }),
+ body: new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(new TextEncoder().encode('{"status":"processing"}'));
+ controller.enqueue(new Uint8Array(2 * 1024 * 1024).fill(0x61));
+ },
+ cancel() {
+ cancelled = true;
+ },
+ }),
+ } as unknown as Response;
+ }
+ return pngResponse();
+ });
+ const { slot } = makeSlot({
+ fetchImpl: fetchImpl as unknown as NetworkSlotDeps['fetchImpl'],
+ saveGhostMedia: (async () => {
+ await gate;
+ return { url: 'cindy-media://blobs/abc.png', hash: 'a'.repeat(64), ext: '.png' };
+ }) as unknown as NetworkSlotDeps['saveGhostMedia'],
+ });
+ const media = slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ const text = await slot.handleFetchRequest('web-search', {
+ url: 'https://api.tavily.com/large-text',
+ as: 'media',
+ });
+ expect(text.ok).toBe(false);
+ if (!text.ok) expect(text.message).toContain('正忙');
+ expect(cancelled).toBe(true);
+ release();
+ expect((await media).ok).toBe(true);
+ });
+ it('声明媒体但字节不是媒体时拒绝;声明 MIME 错误时按字节类型入仓', async () => {
+ const html = makeSlot({
+ fetchImpl: async () => fakeResponse({ headers: { 'content-type': 'image/png' }, body: '<html>bad</html>' }),
+ });
+ expect((await html.slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' })).ok).toBe(false);
+ expect(html.saveGhostMedia).not.toHaveBeenCalled();
+
+ const mismatch = makeSlot({
+ fetchImpl: async () => fakeResponse({ headers: { 'content-type': 'image/png' }, body: new Uint8Array([0xff, 0xd8, 0xff, 0xe0]).buffer }),
+ });
+ expect((await mismatch.slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' })).ok).toBe(true);
+ expect((mismatch.saveGhostMedia.mock.calls[0][0] as { mimeType: string }).mimeType).toBe('image/jpeg');
+ });
+
+ it('正确声明的 audio/mpeg 继续走原媒体路径', async () => {
+ const bytes = mp3WithId3();
+ const { slot, saveGhostMedia } = makeSlot({
+ fetchImpl: async () => fakeResponse({ headers: { 'content-type': 'audio/mpeg' }, body: toArrayBuffer(bytes) }),
+ });
+ const r = await slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
+ expect(r.ok && 'media' in r).toBe(true);
+ expect((saveGhostMedia.mock.calls[0][0] as { mimeType: string }).mimeType).toBe('audio/mpeg');
+ });
+
+ it('text/plain 与缺头的未知二进制不回落 body', async () => {
+ for (const contentType of ['text/plain', '']) {
+ const { slot, saveGhostMedia } = makeSlot({
+ fetchImpl: async () => fakeResponse({
+ headers: contentType ? { 'content-type': contentType } : {},
+ body: new Uint8Array([0x50, 0x4b, 0x03, 0x04]).buffer,
+ }),
+ });
+ const r = await slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
+ expect(r.ok, contentType || '(empty)').toBe(false);
+ expect(saveGhostMedia).not.toHaveBeenCalled();
+ }
+ });
+
+ it('流式声明媒体会占用全局媒体读闸', async () => {
+ let release!: () => void;
+ const blocked = new Promise<void>((resolve) => (release = resolve));
+ const streamResponse = () => ({
+ status: 200,
+ headers: new Headers({ 'content-type': 'image/png' }),
+ body: new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));
+ controller.close();
+ },
+ }),
+ }) as unknown as Response;
+ const { slot } = makeSlot({
+ fetchImpl: async () => streamResponse(),
+ saveGhostMedia: async () => {
+ await blocked;
+ return { url: 'cindy-media://blobs/abc.png', hash: 'a'.repeat(64), ext: '.png' };
+ },
+ });
+ const first = slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ const second = await slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
+ expect(second.ok).toBe(false);
+ if (!second.ok) expect(second.message).toContain('正忙');
+ release();
+ expect((await first).ok).toBe(true);
+ });
+
+ it('非流式泛化媒体在 arrayBuffer 前获取读闸', async () => {
+ let arrayBufferRead = false;
+ let release!: () => void;
+ const blocked = new Promise<void>((resolve) => (release = resolve));
+ const response = {
+ status: 200,
+ headers: new Headers({ 'content-type': 'text/plain' }),
+ body: null,
+ arrayBuffer: async () => {
+ arrayBufferRead = true;
+ await blocked;
+ return mp3WithId3().buffer;
+ },
+ } as unknown as Response;
+ const { slot } = makeSlot({ fetchImpl: async () => response });
+ const first = slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(arrayBufferRead).toBe(true);
+ const second = await slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
+ expect(second.ok).toBe(false);
+ release();
+ expect((await first).ok).toBe(true);
+ });
+
+ it('text/plain 小轮询响应不占媒体闸,媒体闸忙时仍正常回落文本', async () => {
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => (release = resolve));
+ const fetchImpl = vi.fn(async (url: string) => {
+ if (url.includes('/poll')) {
+ return {
+ status: 200,
+ headers: new Headers({ 'content-type': 'text/plain' }),
+ body: new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(new TextEncoder().encode('{"status":"processing"}'));
+ controller.close();
+ },
+ }),
+ } as unknown as Response;
+ }
+ return pngResponse();
+ });
+ const { slot } = makeSlot({
+ fetchImpl: fetchImpl as unknown as NetworkSlotDeps['fetchImpl'],
+ saveGhostMedia: (async () => {
+ await gate;
+ return { url: 'cindy-media://blobs/abc.png', hash: 'a'.repeat(64), ext: '.png' };
+ }) as unknown as NetworkSlotDeps['saveGhostMedia'],
+ });
+ const media = slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ const text = await slot.handleFetchRequest('web-search', {
+ url: 'https://api.tavily.com/poll',
+ as: 'media',
+ });
+ expect(text.ok && 'body' in text).toBe(true);
+ if (text.ok && 'body' in text) expect(text.body).toBe('{"status":"processing"}');
+
+ release();
+ expect((await media).ok).toBe(true);
+ });
+
+ it('text/plain 大文本 sniff miss 仍按 50MB 文本上限截断并标记 truncated', async () => {
+ const chunk = new Uint8Array(GHOST_FETCH_RESPONSE_MAX_BYTES + 17).fill(97);
+ const { slot, saveGhostMedia } = makeSlot({
+ fetchImpl: async () => fakeResponse({ headers: { 'content-type': 'text/plain' }, body: chunk.buffer }),
+ });
+ const r = await slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
+ expect(r.ok && 'body' in r).toBe(true);
+ if (r.ok && 'body' in r) {
+ expect(r.body.length).toBe(GHOST_FETCH_RESPONSE_MAX_BYTES);
+ expect(r.truncated).toBe(true);
+ }
+ expect(saveGhostMedia).not.toHaveBeenCalled();
+ });
+
+ it('泛化 MIME 非流式媒体超 256MB 时拒绝,不保存截断文件', async () => {
+ const size = GHOST_FETCH_MEDIA_MAX_BYTES + 1;
+ const raw = new Uint8Array(size);
+ raw.set(mp3WithId3(), 0);
+ const { slot, saveGhostMedia } = makeSlot({
+ fetchImpl: async () => fakeResponse({ headers: { 'content-type': 'text/plain' }, body: raw.buffer }),
+ });
+ const r = await slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.message).toContain('媒体过大');
+ expect(saveGhostMedia).not.toHaveBeenCalled();
+ }, 30_000);
+
+ it('content-length 预检对泛化 MIME 的超大响应也在读体前拒绝', async () => {
+ let bodyRead = false;
+ const response = {
+ status: 200,
+ headers: new Headers({
+ 'content-type': 'application/octet-stream',
+ 'content-length': String(GHOST_FETCH_MEDIA_MAX_BYTES + 1),
+ }),
+ arrayBuffer: async () => {
+ bodyRead = true;
+ return new ArrayBuffer(0);
+ },
+ };
+ Object.defineProperty(response, 'body', {
+ get() {
+ bodyRead = true;
+ return null;
+ },
+ });
+ const { slot, saveGhostMedia } = makeSlot({
+ fetchImpl: async () => response as unknown as Response,
+ });
+ const r = await slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
+ expect(r.ok).toBe(false);
+ expect(bodyRead).toBe(false);
+ expect(saveGhostMedia).not.toHaveBeenCalled();
+ });
+
it('content-type 带参数/别名归一化后再判(image/jpg; charset=binary → image/jpeg)', async () => {
const { slot, saveGhostMedia } = makeSlot({
- fetchImpl: async () => fakeResponse({ headers: { 'content-type': 'image/jpg; charset=binary' }, body: pngBytes.buffer.slice(0) }),
+ fetchImpl: async () => fakeResponse({ headers: { 'content-type': 'image/jpg; charset=binary' }, body: new Uint8Array([0xff, 0xd8, 0xff, 0xe0]).buffer }),
});
const r = await slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
expect(r.ok && 'media' in r).toBe(true);
@@ -519,6 +983,7 @@ describe('networkSlot · 媒体模式(as:media,字节不进沙箱)', () => {
it('媒体超硬顶整单拒(不截断——截断的媒体是坏文件),不落仓', async () => {
const chunk = new Uint8Array(1024 * 1024).fill(1);
+ chunk.set([0, 0, 0, 16, 0x66, 0x74, 0x79, 0x70, 0x69, 0x73, 0x6f, 0x6d]);
const stream = new ReadableStream<Uint8Array>({
pull(controller) {
controller.enqueue(chunk);
@@ -542,14 +1007,14 @@ describe('networkSlot · 媒体模式(as:media,字节不进沙箱)', () => {
}, 30_000);
it('音频/模型的常见非标 mime 归一化(audio/mp3 → audio/mpeg 等)', async () => {
- for (const [wire, canonical] of [
- ['audio/mp3', 'audio/mpeg'],
- ['audio/x-wav', 'audio/wav'],
- ['audio/wave', 'audio/wav'],
- ['audio/x-m4a', 'audio/mp4'],
+ for (const [wire, canonical, body] of [
+ ['audio/mp3', 'audio/mpeg', new Uint8Array([0xff, 0xfb, 0x90, 0x64])],
+ ['audio/x-wav', 'audio/wav', new Uint8Array([0x52, 0x49, 0x46, 0x46, 0x64, 0, 0, 0, 0x57, 0x41, 0x56, 0x45, 0x66, 0x6d, 0x74, 0x20, 16, 0, 0, 0])],
+ ['audio/wave', 'audio/wav', new Uint8Array([0x52, 0x49, 0x46, 0x46, 0x64, 0, 0, 0, 0x57, 0x41, 0x56, 0x45, 0x66, 0x6d, 0x74, 0x20, 16, 0, 0, 0])],
+ ['audio/x-m4a', 'audio/mp4', new Uint8Array([0, 0, 0, 16, 0x66, 0x74, 0x79, 0x70, 0x4d, 0x34, 0x41, 0x20, 0, 0, 0, 0, 0])],
] as const) {
const { slot, saveGhostMedia } = makeSlot({
- fetchImpl: async () => fakeResponse({ headers: { 'content-type': wire }, body: pngBytes.buffer.slice(0) }),
+ fetchImpl: async () => fakeResponse({ headers: { 'content-type': wire }, body: body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength) }),
isSupportedMediaMime: (m) => ['audio/mpeg', 'audio/wav', 'audio/mp4'].includes(m),
});
const r = await slot.handleFetchRequest('web-search', { url: BRAVE_URL, as: 'media' });
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 9038888b98..d633b2459d 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -1313,8 +1313,12 @@ const r = await cindy.fetch({
// { ok:true, status, headers, media: { url: 'cindy-media://blobs/<指纹>.<后缀>', hash, ext, bytes } }
// **字节不进你的沙箱**:主机直接落媒体总仓、记到你名下(与 cindy 代办产物同等待遇:
// 可当改图源图、可上画廊、交卷 xdt_image_urls 可渲染)。受支持类型 = 图片(png/jpg/
-// webp/gif)/ 视频(mp4/webm/mov)/ 音频(mp3/wav/m4a)/ 3D(glb);上限 256MB,
-// 超限整单拒(不截断)。媒体模式下 2xx 的文本响应(如轮询"生成中"JSON)自动
+// webp/gif)/ 视频(mp4/webm/mov)/ 音频(mp3/wav/m4a/ogg)/ 3D(glb);上限 256MB,
+// 超限整单拒(不截断)。Content-Type 只作为线索,落仓前主机会按字节验证真实媒体类型;
+// 对缺失、text/plain 或通用 octet-stream 这类常见误报/泛化声明,主机会按受支持
+// 媒体的有限魔数尝试识别。识别成功仍走同一媒体总仓,并以字节识别出的 MIME 落仓;
+// 识别失败的真实 UTF-8 文本继续回落文本形态,未知二进制拒绝。
+// 媒体模式下 2xx 的文本响应(如轮询"生成中"JSON)自动
// 回落文本形态给你看;非 2xx 同样回落文本,方便诊断。
// 失败:{ ok:false, message: '原因' }(白名单外 / 凭证未配置 / 超时 / 网络错误…)
\`\`\`
diff --git a/apps/desktop/src/main/cindy-brain/networkSlot.ts b/apps/desktop/src/main/cindy-brain/networkSlot.ts
index 951ae5bb9a..fe2dba4b66 100644
--- a/apps/desktop/src/main/cindy-brain/networkSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/networkSlot.ts
@@ -23,6 +23,8 @@
import { randomUUID } from 'node:crypto';
+import { sniffMediaMime, additionalMp3BytesNeeded } from '../cindy-media/sniffMediaMime.js';
+
import {
GHOST_FETCH_BODY_MAX_BYTES,
GHOST_FETCH_INFLIGHT_LIMIT,
@@ -215,6 +217,35 @@ function isTextualContentType(ct: string): boolean {
return mime === '';
}
+/**
+ * Generic octet-stream is not automatically text: only a bounded, valid UTF-8
+ * prefix without NUL/control bytes may use the polling/text fallback.
+ */
+function isProbablyUtf8Text(bytes: Uint8Array, complete: boolean): boolean {
+ if (bytes.byteLength === 0) return true;
+ for (const byte of bytes) {
+ if (byte === 0x00 || (byte < 0x20 && byte !== 0x09 && byte !== 0x0a && byte !== 0x0d)) {
+ return false;
+ }
+ }
+ try {
+ // An open probe may end in the middle of a valid multi-byte sequence. A
+ // complete body must flush the decoder so a dangling sequence is rejected.
+ new TextDecoder('utf-8', { fatal: true }).decode(bytes, { stream: !complete });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * An empty Content-Type is historically text-compatible; octet-stream falls
+ * back only after the bytes themselves pass the conservative text check.
+ */
+function allowsSniffedTextFallback(probe: Uint8Array, complete: boolean): boolean {
+ return isProbablyUtf8Text(probe, complete);
+}
+
/**
* 常见非标 mime → 总仓白名单正名(blobStore EXT_BY_MIME 只认正名)。
* 音频三兄弟的别名野得很(audio/mp3 / x-wav / wave / x-m4a 满天飞),
@@ -235,6 +266,22 @@ function normalizeMime(ct: string): string {
return MIME_ALIASES[mime] ?? mime;
}
+/**
+ * These response types are frequently omitted or misconfigured by object stores/CDNs.
+ * Only this narrow set is eligible for byte-signature recovery in as:'media' mode;
+ * specific unsupported types such as application/zip remain rejected without sniffing.
+ */
+const SNIFFABLE_GENERIC_MEDIA_MIMES = new Set([
+ '',
+ 'text/plain',
+ 'application/octet-stream',
+ 'binary/octet-stream',
+]);
+
+function shouldSniffMediaMime(mime: string): boolean {
+ return SNIFFABLE_GENERIC_MEDIA_MIMES.has(mime);
+}
+
/**
* 大小写不敏感地删掉 headers 对象里某头名的全部变体。普通对象里
* `X-Token` 与 `x-token` 是两个键,但 fetch 把对象转 Headers 时按大小写
@@ -336,6 +383,267 @@ async function readBodyCapped(
return { bytes, truncated };
}
+const MEDIA_SNIFF_PROBE_BYTES = 4096;
+
+type SniffableBodyResult =
+ | { kind: 'media'; bytes: Uint8Array; mime: string; overLimit: boolean }
+ | { kind: 'text'; bytes: Uint8Array; truncated: boolean }
+ | { kind: 'unsupported' }
+ | { kind: 'mediaTooLarge' }
+ | { kind: 'gateBusy' };
+
+function joinChunks(chunks: Uint8Array[], total: number): Uint8Array {
+ const out = new Uint8Array(total);
+ let offset = 0;
+ for (const chunk of chunks) {
+ out.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ return out;
+}
+
+function inferredMediaMime(
+ bytes: Uint8Array,
+ isSupportedMediaMime: (mime: string) => boolean,
+ declaredMime: string,
+): string | null {
+ const sniffed = sniffMediaMime(bytes, declaredMime);
+ return sniffed && isSupportedMediaMime(sniffed) ? sniffed : null;
+}
+
+function pendingMp3Bytes(bytes: Uint8Array): number | null {
+ return additionalMp3BytesNeeded(bytes);
+}
+
+/**
+ * Read a response whose declared MIME is missing/generic without penalizing real text:
+ * inspect at most the first 4 KiB, then commit to either the media cap+global gate,
+ * the existing text cap+size-gated gate, or an immediate unsupported-binary reject.
+ */
+async function readSniffableBody(
+ response: Response,
+ declaredMime: string,
+ tryAcquireGate: () => boolean,
+ releaseGate: () => void,
+ allowTextFallback: boolean,
+ isSupportedMediaMime: (mime: string) => boolean,
+ expectedMedia = false,
+): Promise<SniffableBodyResult> {
+ const body = (response as { body?: ReadableStream<Uint8Array> | null }).body;
+ if (!body) {
+ // Without a stream there is no bounded way to inspect the body before
+ // arrayBuffer(). Hold the gate first so an unknown-length generic response
+ // cannot fill memory before being rejected or classified.
+ if (!tryAcquireGate()) return { kind: 'gateBusy' };
+ let retainGate = false;
+ try {
+ const raw = new Uint8Array(await response.arrayBuffer());
+ const initialProbe = raw.subarray(0, MEDIA_SNIFF_PROBE_BYTES);
+ const mp3BytesNeeded = pendingMp3Bytes(initialProbe);
+ const probe = raw.subarray(
+ 0,
+ Math.min(raw.byteLength, mp3BytesNeeded ?? MEDIA_SNIFF_PROBE_BYTES),
+ );
+ const mime = inferredMediaMime(probe, isSupportedMediaMime, declaredMime);
+ if (mime) {
+ retainGate = true;
+ return {
+ kind: 'media',
+ bytes: raw.subarray(0, GHOST_FETCH_MEDIA_MAX_BYTES),
+ mime,
+ overLimit: raw.byteLength > GHOST_FETCH_MEDIA_MAX_BYTES,
+ };
+ }
+ if (
+ !allowTextFallback ||
+ !allowsSniffedTextFallback(probe, raw.byteLength <= MEDIA_SNIFF_PROBE_BYTES)
+ ) {
+ return { kind: 'unsupported' };
+ }
+ const textBytes = raw.subarray(0, GHOST_FETCH_RESPONSE_MAX_BYTES);
+ if (!isProbablyUtf8Text(textBytes, true)) return { kind: 'unsupported' };
+ return {
+ kind: 'text',
+ bytes: textBytes,
+ truncated: raw.byteLength > GHOST_FETCH_RESPONSE_MAX_BYTES,
+ };
+ } finally {
+ if (!retainGate) releaseGate();
+ }
+ }
+
+ const reader = body.getReader();
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ let kind: 'media' | 'text' | null = null;
+ let mediaMime = '';
+ let gateAcquired = false;
+ let truncated = false;
+ let retainedTotal = 0;
+ let readerDone = false;
+ let readerCancelled = false;
+
+ const cancelReader = async (): Promise<void> => {
+ if (readerDone || readerCancelled) return;
+ readerCancelled = true;
+ await reader.cancel().catch(() => {});
+ };
+
+ let undecidedCap = MEDIA_SNIFF_PROBE_BYTES;
+ let pendingMp3 = false;
+ const acquireGate = (): boolean => {
+ if (gateAcquired) return true;
+ if (!tryAcquireGate()) return false;
+ gateAcquired = true;
+ return true;
+ };
+ if (expectedMedia && !acquireGate()) {
+ await cancelReader();
+ return { kind: 'gateBusy' };
+ }
+ const classify = async (complete: boolean): Promise<'ok' | 'unsupported' | 'pending' | 'gateBusy'> => {
+ const joined = joinChunks(chunks, retainedTotal);
+ const sniffed = inferredMediaMime(joined, isSupportedMediaMime, declaredMime);
+ if (sniffed) {
+ if (!acquireGate()) return 'gateBusy';
+ kind = 'media';
+ mediaMime = sniffed;
+ return 'ok';
+ }
+ const mp3BytesNeeded = pendingMp3Bytes(joined);
+ if (!complete && mp3BytesNeeded !== null && mp3BytesNeeded > retainedTotal) {
+ if (mp3BytesNeeded > GHOST_FETCH_MEDIA_MAX_BYTES) return 'unsupported';
+ undecidedCap = mp3BytesNeeded;
+ pendingMp3 = true;
+ return 'pending';
+ }
+ const textProbe = joined.subarray(0, MEDIA_SNIFF_PROBE_BYTES);
+ if (!allowTextFallback || !allowsSniffedTextFallback(textProbe, complete)) return 'unsupported';
+ kind = 'text';
+ if (total > LARGE_TEXT_GATE_BYTES && !acquireGate()) return 'gateBusy';
+ return 'ok';
+ };
+
+ try {
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) {
+ readerDone = true;
+ if (kind === null) {
+ const classified = await classify(true);
+ if (classified !== 'ok') return { kind: classified === 'pending' ? 'unsupported' : classified };
+ }
+ break;
+ }
+ if (!value || value.byteLength === 0) continue;
+ total += value.byteLength;
+ const activeCap = kind === 'media'
+ ? GHOST_FETCH_MEDIA_MAX_BYTES
+ : kind === 'text'
+ ? GHOST_FETCH_RESPONSE_MAX_BYTES
+ : undecidedCap;
+ if (
+ kind === 'text' &&
+ !gateAcquired &&
+ retainedTotal + value.byteLength > LARGE_TEXT_GATE_BYTES &&
+ !acquireGate()
+ ) {
+ await cancelReader();
+ return { kind: 'gateBusy' };
+ }
+ let keptFromValue = 0;
+ if (retainedTotal < activeCap) {
+ const keep = Math.min(value.byteLength, activeCap - retainedTotal);
+ if (keep > 0) {
+ chunks.push(keep === value.byteLength ? value : value.slice(0, keep));
+ retainedTotal += keep;
+ keptFromValue = keep;
+ }
+ }
+
+ if (kind === null && retainedTotal >= undecidedCap) {
+ const classified = await classify(false);
+ if (classified === 'pending') {
+ if (!acquireGate()) {
+ await cancelReader();
+ return { kind: 'gateBusy' };
+ }
+ // A valid ID3 tag may put the first MPEG frame after the initial
+ // probe. Keep reading until that frame can be inspected.
+ if (keptFromValue < value.byteLength && retainedTotal < undecidedCap) {
+ const keepRemainder = Math.min(value.byteLength - keptFromValue, undecidedCap - retainedTotal);
+ if (keepRemainder > 0) {
+ chunks.push(value.slice(keptFromValue, keptFromValue + keepRemainder));
+ retainedTotal += keepRemainder;
+ keptFromValue += keepRemainder;
+ }
+ }
+ if (retainedTotal >= undecidedCap) {
+ const resolved = await classify(false);
+ if (resolved !== 'ok') {
+ await cancelReader();
+ return { kind: resolved === 'pending' ? 'unsupported' : resolved };
+ }
+ }
+ } else if (classified !== 'ok') {
+ await cancelReader();
+ return { kind: classified };
+ }
+ if (kind !== null) {
+ // Keep the remainder of the current chunk now that the final
+ // text/media cap is known.
+ const decidedCap = kind === 'media' ? GHOST_FETCH_MEDIA_MAX_BYTES : GHOST_FETCH_RESPONSE_MAX_BYTES;
+ if (
+ kind === 'text' &&
+ !gateAcquired &&
+ retainedTotal < LARGE_TEXT_GATE_BYTES &&
+ retainedTotal + (value.byteLength - keptFromValue) > LARGE_TEXT_GATE_BYTES &&
+ !acquireGate()
+ ) {
+ await cancelReader();
+ return { kind: 'gateBusy' };
+ }
+ if (keptFromValue < value.byteLength && retainedTotal < decidedCap) {
+ const keepRemainder = Math.min(value.byteLength - keptFromValue, decidedCap - retainedTotal);
+ if (keepRemainder > 0) {
+ chunks.push(value.slice(keptFromValue, keptFromValue + keepRemainder));
+ retainedTotal += keepRemainder;
+ }
+ }
+ }
+ }
+ if (kind === 'text' && total > LARGE_TEXT_GATE_BYTES && !acquireGate()) {
+ await cancelReader();
+ return { kind: 'gateBusy' };
+ }
+ const maxBytes = kind === 'media'
+ ? GHOST_FETCH_MEDIA_MAX_BYTES
+ : kind === 'text'
+ ? GHOST_FETCH_RESPONSE_MAX_BYTES
+ : pendingMp3
+ ? undecidedCap
+ : GHOST_FETCH_RESPONSE_MAX_BYTES;
+ if (kind !== null && total > maxBytes) {
+ truncated = true;
+ await cancelReader();
+ break;
+ }
+ }
+ } finally {
+ await cancelReader();
+ }
+
+ const maxBytes = kind === 'media' ? GHOST_FETCH_MEDIA_MAX_BYTES : GHOST_FETCH_RESPONSE_MAX_BYTES;
+ const joined = joinChunks(chunks, retainedTotal);
+ const bytes = joined.subarray(0, maxBytes);
+ if (kind === 'media') {
+ if (truncated || total > maxBytes) return { kind: 'mediaTooLarge' };
+ return { kind: 'media', bytes, mime: mediaMime, overLimit: false };
+ }
+ if (!isProbablyUtf8Text(bytes, true)) return { kind: 'unsupported' };
+ return { kind: 'text', bytes, truncated: truncated || total > maxBytes };
+}
+
/** 解析并硬校验目标 URL:仅 https、默认端口、无内嵌凭证。失败返回人话原因。 */
function parseTargetUrl(raw: string): { url: URL } | { error: string } {
let url: URL;
@@ -913,49 +1221,88 @@ export class GhostNetworkSlot {
}
if (asMode === 'media' && response.status >= 200 && response.status < 300) {
- const mime = normalizeMime(contentType);
- if (this.deps.isSupportedMediaMime(mime)) {
+ const declaredMime = normalizeMime(contentType);
+ const sniffGeneric = shouldSniffMediaMime(declaredMime);
+ if (this.deps.isSupportedMediaMime(declaredMime) || sniffGeneric) {
// 诚实服务器的超大文件在读之前就拒掉,不白读 256MB;撒谎/缺头的
// 由下面的流式硬顶兜底。
const declaredLength = Number(response.headers.get('content-length') ?? Number.NaN);
- if (Number.isFinite(declaredLength) && declaredLength > GHOST_FETCH_MEDIA_MAX_BYTES) {
+ if (
+ Number.isFinite(declaredLength) &&
+ declaredLength > GHOST_FETCH_MEDIA_MAX_BYTES
+ ) {
return { ok: false, message: `媒体过大(声明 ${declaredLength} 字节,上限 ${GHOST_FETCH_MEDIA_MAX_BYTES})` };
}
- // 全局串行闸:读体 + 落仓期间独占,防聚合内存峰值(见常量注释)。
- if (this.mediaReadsInflight >= MEDIA_READ_GLOBAL_LIMIT) {
- return { ok: false, message: '媒体通道正忙(全局同时只取一单),请稍后重试' };
+ const sniffed = await readSniffableBody(
+ response,
+ declaredMime,
+ () => {
+ if (holdingMediaGate) return true;
+ if (this.mediaReadsInflight >= MEDIA_READ_GLOBAL_LIMIT) return false;
+ this.mediaReadsInflight += 1;
+ holdingMediaGate = true;
+ return true;
+ },
+ () => {
+ if (!holdingMediaGate) return;
+ this.mediaReadsInflight -= 1;
+ holdingMediaGate = false;
+ },
+ sniffGeneric,
+ this.deps.isSupportedMediaMime,
+ !sniffGeneric,
+ );
+ if (sniffed.kind === 'gateBusy') {
+ return { ok: false, message: '媒体/大响应通道正忙(全局同时只处理一单),请稍后重试' };
}
- this.mediaReadsInflight += 1;
- try {
- const { bytes: mediaBytes, truncated: overLimit } = await readBodyCapped(response, GHOST_FETCH_MEDIA_MAX_BYTES);
- if (overLimit) {
- return { ok: false, message: `媒体过大(上限 ${GHOST_FETCH_MEDIA_MAX_BYTES} 字节)——截断的媒体是坏文件,整单拒` };
- }
- const saved = await this.deps.saveGhostMedia({
- ghostId,
- buffer: mediaBytes,
- mimeType: mime,
- ...(label !== undefined ? { label } : {}),
- // 署名调用记账(ghostMediaLedger):产物随 ghost_call 收口带回,
- // IM/hook 出站兜底送达;未署名不记(避免并发误配)。
- ...(callId !== 'unattributed' ? { callId } : {}),
- });
- this.deps.log?.info('ghost fetch-request done (media)', {
+ if (sniffed.kind === 'unsupported') {
+ return { ok: false, message: `该媒体类型不受总仓支持(${declaredMime || 'unknown'}),无法取回` };
+ }
+ if (sniffed.kind === 'mediaTooLarge') {
+ return { ok: false, message: `媒体过大(上限 ${GHOST_FETCH_MEDIA_MAX_BYTES} 字节)——截断的媒体是坏文件,整单拒` };
+ }
+ if (sniffed.kind === 'text') {
+ const bodyText = new TextDecoder('utf-8', { fatal: false }).decode(sniffed.bytes);
+ this.deps.log?.info('ghost fetch-request done', {
ghostId, callId, method, host: url.hostname, status: response.status,
- bytes: mediaBytes.byteLength, hash: saved.hash,
+ bytes: sniffed.bytes.byteLength, mediaSniffMiss: true,
+ ...(sniffed.truncated ? { truncated: true } : {}),
});
return {
ok: true,
status: response.status,
headers: responseHeaders,
- media: { ...saved, bytes: mediaBytes.byteLength },
+ body: bodyText,
+ ...(sniffed.truncated ? { truncated: true } : {}),
};
- } finally {
- this.mediaReadsInflight -= 1;
}
+ if (sniffed.overLimit) {
+ return { ok: false, message: `媒体过大(上限 ${GHOST_FETCH_MEDIA_MAX_BYTES} 字节)——截断的媒体是坏文件,整单拒` };
+ }
+ const saved = await this.deps.saveGhostMedia({
+ ghostId,
+ buffer: sniffed.bytes,
+ // Always persist the MIME recovered from bytes, never the external
+ // declaration. This also corrects a valid but misdeclared response.
+ mimeType: sniffed.mime,
+ ...(label !== undefined ? { label } : {}),
+ ...(callId !== 'unattributed' ? { callId } : {}),
+ });
+ this.deps.log?.info('ghost fetch-request done (media)', {
+ ghostId, callId, method, host: url.hostname, status: response.status,
+ bytes: sniffed.bytes.byteLength, hash: saved.hash, mime: sniffed.mime,
+ ...(sniffGeneric ? { recoveredBySniff: true } : {}),
+ declaredMime,
+ });
+ return {
+ ok: true,
+ status: response.status,
+ headers: responseHeaders,
+ media: { ...saved, bytes: sniffed.bytes.byteLength },
+ };
}
if (!isTextualContentType(contentType)) {
- return { ok: false, message: `该媒体类型不受总仓支持(${normalizeMime(contentType)}),无法取回` };
+ return { ok: false, message: `该媒体类型不受总仓支持(${declaredMime || 'unknown'}),无法取回` };
}
// 2xx 但内容是文本(如返回 JSON 的"生成中"状态):回落文本形态。
}
diff --git a/apps/desktop/src/main/cindy-media/__tests__/sniffMediaMime.test.ts b/apps/desktop/src/main/cindy-media/__tests__/sniffMediaMime.test.ts
new file mode 100644
index 0000000000..2e3f130412
--- /dev/null
+++ b/apps/desktop/src/main/cindy-media/__tests__/sniffMediaMime.test.ts
@@ -0,0 +1,180 @@
+import { describe, expect, it } from 'vitest';
+
+import { sniffMediaMime } from '../sniffMediaMime';
+
+function ascii(value: string, total = value.length): Uint8Array {
+ const bytes = new Uint8Array(total);
+ bytes.set(new TextEncoder().encode(value));
+ return bytes;
+}
+
+function id3(version: number, flags = 0, tagSize = 0): Uint8Array {
+ const footer = version === 4 && (flags & 0x10) !== 0
+ ? new Uint8Array(10)
+ : new Uint8Array();
+ return new Uint8Array([
+ 0x49, 0x44, 0x33, version, 0x00, flags,
+ (tagSize >>> 21) & 0x7f,
+ (tagSize >>> 14) & 0x7f,
+ (tagSize >>> 7) & 0x7f,
+ tagSize & 0x7f,
+ ...new Uint8Array(tagSize),
+ ...footer,
+ 0xff, 0xfb, 0x90, 0x64,
+ ]);
+}
+
+function riff(
+ format: 'WEBP' | 'WAVE',
+ chunks: Array<{ id: string; size: number }>,
+ declaredSize?: number,
+): Uint8Array {
+ const bodySize = chunks.reduce((total, chunk) => total + 8 + chunk.size + (chunk.size & 1), 4);
+ const size = declaredSize ?? bodySize;
+ const bytes = new Uint8Array(8 + bodySize);
+ bytes.set(new TextEncoder().encode('RIFF'), 0);
+ bytes.set([
+ size & 0xff,
+ (size >>> 8) & 0xff,
+ (size >>> 16) & 0xff,
+ (size >>> 24) & 0xff,
+ ], 4);
+ bytes.set(new TextEncoder().encode(format), 8);
+ let offset = 12;
+ for (const chunk of chunks) {
+ bytes.set(new TextEncoder().encode(chunk.id), offset);
+ bytes.set([
+ chunk.size & 0xff,
+ (chunk.size >>> 8) & 0xff,
+ (chunk.size >>> 16) & 0xff,
+ (chunk.size >>> 24) & 0xff,
+ ], offset + 4);
+ offset += 8 + chunk.size + (chunk.size & 1);
+ }
+ return bytes;
+}
+
+function ftyp(brand: string, compatibleBrands: string[] = [], minorVersion = 0): Uint8Array {
+ const bytes = new Uint8Array(16 + compatibleBrands.length * 4);
+ bytes.set([0, 0, 0, bytes.length], 0);
+ bytes.set(new TextEncoder().encode('ftyp'), 4);
+ bytes.set(new TextEncoder().encode(brand), 8);
+ bytes.set([
+ (minorVersion >>> 24) & 0xff,
+ (minorVersion >>> 16) & 0xff,
+ (minorVersion >>> 8) & 0xff,
+ minorVersion & 0xff,
+ ], 12);
+ for (const [index, compatible] of compatibleBrands.entries()) {
+ bytes.set(new TextEncoder().encode(compatible), 16 + index * 4);
+ }
+ return bytes;
+}
+
+function atom(type: string, size = 8): Uint8Array {
+ const bytes = new Uint8Array(Math.max(size, 8));
+ bytes.set([
+ (size >>> 24) & 0xff,
+ (size >>> 16) & 0xff,
+ (size >>> 8) & 0xff,
+ size & 0xff,
+ ], 0);
+ bytes.set(new TextEncoder().encode(type), 4);
+ return bytes;
+}
+
+function glb(version = 2, length = 12): Uint8Array {
+ const bytes = new Uint8Array(12);
+ bytes.set(new TextEncoder().encode('glTF'), 0);
+ bytes.set([
+ version & 0xff,
+ (version >>> 8) & 0xff,
+ (version >>> 16) & 0xff,
+ (version >>> 24) & 0xff,
+ length & 0xff,
+ (length >>> 8) & 0xff,
+ (length >>> 16) & 0xff,
+ (length >>> 24) & 0xff,
+ ], 4);
+ return bytes;
+}
+
+describe('sniffMediaMime', () => {
+ it('recognizes the cindy-media image formats', () => {
+ expect(sniffMediaMime(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))).toBe('image/png');
+ expect(sniffMediaMime(new Uint8Array([0xff, 0xd8, 0xff, 0xe0]))).toBe('image/jpeg');
+ expect(sniffMediaMime(ascii('GIF89a'))).toBe('image/gif');
+ const webp = riff('WEBP', [{ id: 'VP8X', size: 10 }], 10_000);
+ expect(sniffMediaMime(webp)).toBe('image/webp');
+ });
+
+ it('recognizes valid ID3v2 headers and MPEG audio frame headers', () => {
+ expect(sniffMediaMime(id3(2))).toBe('audio/mpeg');
+ expect(sniffMediaMime(id3(3))).toBe('audio/mpeg');
+ expect(sniffMediaMime(id3(4))).toBe('audio/mpeg');
+ expect(sniffMediaMime(id3(4, 0x10))).toBe('audio/mpeg');
+ expect(sniffMediaMime(id3(4, 0, 5))).toBe('audio/mpeg');
+ expect(sniffMediaMime(new Uint8Array([0xff, 0xfb, 0x90, 0x64]))).toBe('audio/mpeg');
+ });
+
+ it('rejects ID3 lookalikes, malformed headers and reserved MPEG fields', () => {
+ expect(sniffMediaMime(ascii('ID3 status: ready'))).toBeNull();
+ expect(sniffMediaMime(ascii('ID3\x04\x00'))).toBeNull();
+ expect(sniffMediaMime(new Uint8Array([0x49, 0x44, 0x33, 0x04, 0x00, 0x00, 0, 0, 0, 0]))).toBeNull();
+ expect(sniffMediaMime(new Uint8Array([0x49, 0x44, 0x33, 0x04, 0x00, 0x00, 0, 0, 0, 5, 1, 2, 3, 4, 5]))).toBeNull();
+ expect(sniffMediaMime(new Uint8Array([0x49, 0x44, 0x33, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]))).toBeNull();
+ expect(sniffMediaMime(new Uint8Array([0x49, 0x44, 0x33, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00]))).toBeNull();
+ expect(sniffMediaMime(new Uint8Array([0x49, 0x44, 0x33, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00]))).toBeNull();
+ expect(sniffMediaMime(new Uint8Array([0x49, 0x44, 0x33, 0x04, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00]))).toBeNull();
+ expect(sniffMediaMime(new Uint8Array([0xff, 0xe0, 0x00, 0x00]))).toBeNull();
+ expect(sniffMediaMime(new Uint8Array([0xff, 0xf8, 0xf0, 0x00]))).toBeNull();
+ expect(sniffMediaMime(new Uint8Array([0xff, 0xfb, 0x9c, 0x00]))).toBeNull();
+ });
+
+ it('recognizes OGG container (audio/ogg)', () => {
+ expect(sniffMediaMime(ascii('OggS', 32))).toBe('audio/ogg');
+ });
+
+ it('recognizes WAV, ISO BMFF video/audio, WebM and GLB', () => {
+ expect(sniffMediaMime(riff('WAVE', [{ id: 'fmt ', size: 16 }], 10_000))).toBe('audio/wav');
+ expect(sniffMediaMime(riff('WAVE', [
+ { id: 'JUNK', size: 3 },
+ { id: 'fmt ', size: 16 },
+ ]))).toBe('audio/wav');
+ expect(sniffMediaMime(ftyp('isom'))).toBe('video/mp4');
+ expect(sniffMediaMime(ftyp('iso9'))).toBe('video/mp4');
+ expect(sniffMediaMime(ftyp('zzzz', ['isom']))).toBe('video/mp4');
+ expect(sniffMediaMime(ftyp('M4A '))).toBe('audio/mp4');
+ expect(sniffMediaMime(ftyp('qt '))).toBe('video/quicktime');
+ for (const type of ['moov', 'mdat', 'free', 'skip', 'wide']) {
+ expect(sniffMediaMime(atom(type), 'video/quicktime')).toBe('video/quicktime');
+ expect(sniffMediaMime(atom(type))).toBeNull();
+ }
+ expect(sniffMediaMime(atom('evil'), 'video/quicktime')).toBeNull();
+ expect(sniffMediaMime(new Uint8Array([
+ 0x1a, 0x45, 0xdf, 0xa3, 0x42, 0x82, 0x84, 0x77, 0x65, 0x62, 0x6d,
+ ]))).toBe('video/webm');
+ expect(sniffMediaMime(glb())).toBe('model/gltf-binary');
+ });
+
+ it('fails closed for text, zip, unknown brands and short inputs', () => {
+ expect(sniffMediaMime(ascii('{"status":"processing"}'))).toBeNull();
+ expect(sniffMediaMime(new Uint8Array([0x50, 0x4b, 0x03, 0x04]))).toBeNull();
+ expect(sniffMediaMime(new Uint8Array([0x1a, 0x45, 0xdf, 0xa3]))).toBeNull();
+ expect(sniffMediaMime(new Uint8Array([
+ 0x1a, 0x45, 0xdf, 0xa3, 0x42, 0x82, 0x88, 0x6d, 0x61, 0x74, 0x72, 0x6f, 0x73, 0x6b, 0x61,
+ ]))).toBeNull();
+ expect(sniffMediaMime(ftyp('zzzz'))).toBeNull();
+ expect(sniffMediaMime(ftyp('zzzz', [], 0x69736f6d))).toBeNull();
+ expect(sniffMediaMime(ascii('RIFF0000WEBP'))).toBeNull();
+ expect(sniffMediaMime(ascii('RIFF0000WAVE'))).toBeNull();
+ expect(sniffMediaMime(riff('WEBP', [{ id: 'NOPE', size: 10 }]))).toBeNull();
+ expect(sniffMediaMime(riff('WAVE', [{ id: 'JUNK', size: 16 }]))).toBeNull();
+ expect(sniffMediaMime(riff('WAVE', [{ id: 'fmt ', size: 4 }]))).toBeNull();
+ expect(sniffMediaMime(ascii('glTF'))).toBeNull();
+ expect(sniffMediaMime(glb(1))).toBeNull();
+ expect(sniffMediaMime(glb(2, 10))).toBeNull();
+ expect(sniffMediaMime(new Uint8Array())).toBeNull();
+ expect(sniffMediaMime(new Uint8Array([0xff]))).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/cindy-media/sniffMediaMime.ts b/apps/desktop/src/main/cindy-media/sniffMediaMime.ts
new file mode 100644
index 0000000000..69fbb72c87
--- /dev/null
+++ b/apps/desktop/src/main/cindy-media/sniffMediaMime.ts
@@ -0,0 +1,220 @@
+/**
+ * sniffMediaMime.ts — 媒体总仓支持类型的保守魔数识别。
+ * ---------------------------------------------------------------------------
+ * 供主机在媒体入仓前核验外部响应的真实类型;Content-Type 只作为线索,不能
+ * 单独决定落仓 MIME。识别范围必须与 blobStore 当前白名单保持一致,识别不出返回 null。
+ */
+
+/** ASCII bytes at an exact offset. */
+function asciiAt(bytes: Uint8Array, offset: number, value: string): boolean {
+ if (offset < 0 || bytes.byteLength < offset + value.length) return false;
+ for (let i = 0; i < value.length; i++) {
+ if (bytes[offset + i] !== value.charCodeAt(i)) return false;
+ }
+ return true;
+}
+
+/** ISO BMFF ftyp brand → the subset accepted by cindy-media. */
+function sniffIsoBmffMime(bytes: Uint8Array): string | null {
+ if (bytes.byteLength < 16 || !asciiAt(bytes, 4, 'ftyp')) return null;
+ const declaredSize =
+ (((bytes[0] << 24) >>> 0) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]);
+ // A normal ftyp box contains size, type, major_brand and minor_version.
+ // Reject short or truncated boxes instead of treating arbitrary bytes as brands.
+ // Compatible brands area must be 4-byte aligned to reject malformed/forged sizes.
+ if (declaredSize < 16 || declaredSize > bytes.byteLength || (declaredSize - 16) % 4 !== 0) return null;
+ const majorBrand = String.fromCharCode(bytes[8], bytes[9], bytes[10], bytes[11]);
+ const brands = [majorBrand];
+ for (let offset = 16; offset + 4 <= declaredSize; offset += 4) {
+ brands.push(String.fromCharCode(bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3]));
+ }
+ if (brands.includes('qt ')) return 'video/quicktime';
+ if (brands.some((brand) => ['M4A ', 'M4B ', 'M4P ', 'F4A ', 'F4B '].includes(brand))) {
+ return 'audio/mp4';
+ }
+ if (
+ brands.some((brand) => [
+ '3gp4', '3gp5', '3gp6', '3gp7', '3gp8', '3gp9', 'avc1', 'av01', 'dash',
+ 'iso2', 'iso3', 'iso4', 'iso5', 'iso6', 'iso8', 'iso9', 'isom', 'M4V ',
+ 'mmp4', 'MP4 ', 'mp41', 'mp42', 'MSNV',
+ ].includes(brand))
+ ) {
+ return 'video/mp4';
+ }
+ return null;
+}
+
+function readUint32Be(bytes: Uint8Array, offset: number): number {
+ return (
+ (((bytes[offset] << 24) >>> 0) |
+ (bytes[offset + 1] << 16) |
+ (bytes[offset + 2] << 8) |
+ bytes[offset + 3]) >>> 0
+ );
+}
+
+function looksLikeDeclaredQuickTime(bytes: Uint8Array): boolean {
+ if (bytes.byteLength < 8) return false;
+ const size = readUint32Be(bytes, 0);
+ const type = String.fromCharCode(bytes[4], bytes[5], bytes[6], bytes[7]);
+ if (!['moov', 'mdat', 'free', 'skip', 'wide'].includes(type)) return false;
+ if (size === 0) return true;
+ if (size === 1) {
+ if (bytes.byteLength < 16) return false;
+ const high = readUint32Be(bytes, 8);
+ const low = readUint32Be(bytes, 12);
+ return high > 0 || low >= 16;
+ }
+ return size >= 8;
+}
+
+function readUint32Le(bytes: Uint8Array, offset: number): number {
+ return (
+ bytes[offset] |
+ (bytes[offset + 1] << 8) |
+ (bytes[offset + 2] << 16) |
+ (bytes[offset + 3] << 24)
+ ) >>> 0;
+}
+
+function looksLikeGlb(bytes: Uint8Array): boolean {
+ if (bytes.byteLength < 12 || !asciiAt(bytes, 0, 'glTF')) return false;
+ const version = readUint32Le(bytes, 4);
+ const length = readUint32Le(bytes, 8);
+ // GLB v2's total length includes this header and is four-byte aligned. The
+ // complete payload may be beyond the 4 KiB sniff probe, so do not require it
+ // to fit in the probe itself.
+ return version === 2 && length >= 12 && length % 4 === 0;
+}
+
+function looksLikeWebp(bytes: Uint8Array): boolean {
+ if (bytes.byteLength < 16 || !asciiAt(bytes, 0, 'RIFF') || !asciiAt(bytes, 8, 'WEBP')) return false;
+ const declaredSize = readUint32Le(bytes, 4);
+ if (declaredSize < 8 || declaredSize % 2 !== 0) return false;
+ return asciiAt(bytes, 12, 'VP8 ') || asciiAt(bytes, 12, 'VP8L') || asciiAt(bytes, 12, 'VP8X');
+}
+
+function looksLikeWav(bytes: Uint8Array): boolean {
+ if (bytes.byteLength < 20 || !asciiAt(bytes, 0, 'RIFF') || !asciiAt(bytes, 8, 'WAVE')) return false;
+ const declaredSize = readUint32Le(bytes, 4);
+ if (declaredSize < 12 || declaredSize % 2 !== 0) return false;
+ const scanEnd = Math.min(bytes.byteLength, declaredSize + 8);
+ for (let offset = 12; offset + 8 <= scanEnd;) {
+ const chunkSize = readUint32Le(bytes, offset + 4);
+ if (asciiAt(bytes, offset, 'fmt ')) return chunkSize >= 16 && chunkSize <= 40;
+ const nextOffset = offset + 8 + chunkSize + (chunkSize & 1);
+ if (nextOffset <= offset || nextOffset > scanEnd) return false;
+ offset = nextOffset;
+ }
+ return false;
+}
+
+function parseId3FrameOffset(bytes: Uint8Array): number | null {
+ if (bytes.byteLength < 10 || !asciiAt(bytes, 0, 'ID3')) return null;
+ const majorVersion = bytes[3];
+ const revision = bytes[4];
+ const flags = bytes[5];
+ if (majorVersion < 2 || majorVersion > 4 || revision !== 0) return null;
+ const allowedFlags = majorVersion === 2 ? 0x00 : majorVersion === 3 ? 0xe0 : 0xf0;
+ if ((flags & ~allowedFlags) !== 0) return null;
+ for (let i = 6; i < 10; i++) {
+ if ((bytes[i] & 0x80) !== 0) return null;
+ }
+ const tagSize =
+ (bytes[6] << 21) |
+ (bytes[7] << 14) |
+ (bytes[8] << 7) |
+ bytes[9];
+ const footerSize = majorVersion === 4 && (flags & 0x10) !== 0 ? 10 : 0;
+ return 10 + tagSize + footerSize;
+}
+
+/**
+ * Upper bound for ID3 tag size we're willing to probe past. Prevents a forged
+ * tag from causing us to buffer arbitrarily large data just to reach the first
+ * MPEG frame. 2 MiB covers virtually all real-world embedded artwork tags.
+ */
+const MAX_ID3_TAG_BYTES = 2 * 1024 * 1024;
+
+/** Return the byte count needed to inspect the first MPEG frame after ID3. */
+export function additionalMp3BytesNeeded(bytes: Uint8Array): number | null {
+ const frameOffset = parseId3FrameOffset(bytes);
+ if (frameOffset === null || frameOffset > MAX_ID3_TAG_BYTES) return null;
+ return frameOffset + 4;
+}
+
+/** Validate an ID3v2 header and require an MPEG frame after the tag. */
+function looksLikeId3v2(bytes: Uint8Array): boolean {
+ const frameOffset = parseId3FrameOffset(bytes);
+ return frameOffset !== null && frameOffset <= MAX_ID3_TAG_BYTES &&
+ frameOffset + 4 <= bytes.byteLength &&
+ looksLikeMpegAudioFrame(bytes.subarray(frameOffset));
+}
+
+/** Validate enough MPEG audio header fields to avoid accepting any ff-prefixed bytes. */
+function looksLikeMpegAudioFrame(bytes: Uint8Array): boolean {
+ if (bytes.byteLength < 4 || bytes[0] !== 0xff || (bytes[1] & 0xe0) !== 0xe0) return false;
+ const version = (bytes[1] >> 3) & 0x03;
+ const layer = (bytes[1] >> 1) & 0x03;
+ const bitrate = (bytes[2] >> 4) & 0x0f;
+ const sampleRate = (bytes[2] >> 2) & 0x03;
+ return version !== 0x01 && layer !== 0x00 && bitrate !== 0x00 && bitrate !== 0x0f && sampleRate !== 0x03;
+}
+
+function looksLikeWebm(bytes: Uint8Array): boolean {
+ if (
+ bytes.byteLength < 11 ||
+ bytes[0] !== 0x1a || bytes[1] !== 0x45 || bytes[2] !== 0xdf || bytes[3] !== 0xa3
+ ) {
+ return false;
+ }
+ // EBML is also the Matroska container. Require DocType(id 0x4282) = "webm"
+ // instead of treating the shared four-byte EBML header as sufficient.
+ const limit = Math.min(bytes.byteLength - 6, 4096);
+ for (let i = 4; i <= limit; i++) {
+ if (
+ bytes[i] === 0x42 && bytes[i + 1] === 0x82 && bytes[i + 2] === 0x84 &&
+ asciiAt(bytes, i + 3, 'webm')
+ ) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * Infer a canonical MIME from bytes without consulting a filename or URL.
+ * The returned value is always one of blobStore's currently supported MIME values.
+ */
+export function sniffMediaMime(bytes: Uint8Array, declaredMime = ''): string | null {
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0) return null;
+
+ if (
+ bytes.byteLength >= 8 &&
+ bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47 &&
+ bytes[4] === 0x0d && bytes[5] === 0x0a && bytes[6] === 0x1a && bytes[7] === 0x0a
+ ) {
+ return 'image/png';
+ }
+ if (bytes.byteLength >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {
+ return 'image/jpeg';
+ }
+ if (bytes.byteLength >= 6 && (asciiAt(bytes, 0, 'GIF87a') || asciiAt(bytes, 0, 'GIF89a'))) {
+ return 'image/gif';
+ }
+ if (looksLikeWebp(bytes)) return 'image/webp';
+ if (looksLikeWav(bytes)) return 'audio/wav';
+ if (bytes.byteLength >= 4 && asciiAt(bytes, 0, 'OggS')) return 'audio/ogg';
+ if (looksLikeId3v2(bytes)) return 'audio/mpeg';
+ if (looksLikeMpegAudioFrame(bytes)) return 'audio/mpeg';
+
+ const isoMime = sniffIsoBmffMime(bytes);
+ if (isoMime) return isoMime;
+ if (declaredMime === 'video/quicktime' && looksLikeDeclaredQuickTime(bytes)) {
+ return 'video/quicktime';
+ }
+
+ if (looksLikeWebm(bytes)) return 'video/webm';
+ if (looksLikeGlb(bytes)) return 'model/gltf-binary';
+ return null;
+}