Skip to content

Spot it. Save it. Free, local-first Chrome extension for images, videos and prompts. Explore 2,000+ curated cases and connect your library to AI Agents via MCP. 提示词导演

9.6 KB
Raw Blame
import test from "node:test";
import assert from "node:assert/strict";

import {
  assertRemoteMediaUrl,
  boundedMediaBlobFromResponse,
  detectImageDimensions,
  fetchBoundedMedia,
  isSupportedDocumentMimeType
} from "../extension/bounded-media.js";

const PNG = Uint8Array.from([
  0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
  0x00, 0x00, 0x00, 0x0d
]);

test("bounded media rejects declared and streamed overflow before creating a Blob", async () => {
  const declared = new Response(PNG, {
    headers: { "content-type": "image/png", "content-length": "99" }
  });
  await assert.rejects(
    () => boundedMediaBlobFromResponse(declared, { kind: "image", maxBytes: 12 }),
    /超过本次接收预算/
  );

  const streamed = new Response(new Uint8Array([...PNG, 1]));
  await assert.rejects(
    () => boundedMediaBlobFromResponse(streamed, { kind: "image", maxBytes: 12 }),
    /超过本次接收预算/
  );
});

for (const mode of ['timeout', 'user_cancel']) {
  test(`download ${mode} reaches a pending body after headers and cancels its reader`, async () => {
    const controller = new AbortController();
    let canceled = false;
    const response = new Response(new ReadableStream({
      start(stream) { stream.enqueue(PNG); },
      cancel() { canceled = true; }
    }));
    const operation = fetchBoundedMedia('https://media.example/pending', {
      kind: 'image', signal: controller.signal, timeoutMs: mode === 'timeout' ? 25 : 1000,
      fetchImpl: async () => response
    });
    if (mode === 'user_cancel') setTimeout(() => controller.abort(), 10);
    await assert.rejects(operation, { name: 'AbortError' });
    assert.equal(canceled, true, 'cancellation must stop network/body reads, not only the UI');
  });
}

test('unknown-length overflow cancels the source rather than leaving a downloading stream', async () => {
  let canceled = false;
  const response = new Response(new ReadableStream({
    start(stream) { stream.enqueue(new Uint8Array(64)); }, cancel() { canceled = true; }
  }));
  await assert.rejects(boundedMediaBlobFromResponse(response, { kind: 'image', maxBytes: 32 }), /接收预算/);
  assert.equal(canceled, true);
});

test('download progress counts actual streamed bytes while preserving the original blob', async () => {
  const events = [];
  const stream = new ReadableStream({ start(controller) {
    controller.enqueue(PNG.slice(0, 8)); controller.enqueue(PNG.slice(8)); controller.close();
  } });
  const blob = await boundedMediaBlobFromResponse(new Response(stream, { headers: { 'content-length': String(PNG.length) } }),
    { kind: 'image', maxBytes: 1024, onProgress: value => events.push(value) });
  assert.deepEqual(new Uint8Array(await blob.arrayBuffer()), PNG);
  assert.deepEqual(events[0], { receivedBytes: 0, totalBytes: PNG.length });
  assert.ok(events.some(event => event.receivedBytes === 8));
  assert.deepEqual(events.at(-1), { receivedBytes: PNG.length, totalBytes: PNG.length });
});

test('missing, compressed and inaccurate lengths never produce a false completed-file percentage', async () => {
  for (const headers of [{}, { 'content-length': '10', 'content-encoding': 'gzip' }, { 'content-length': String(PNG.length + 8) }]) {
    const events = [];
    await boundedMediaBlobFromResponse(new Response(PNG, { headers }),
      { kind: 'image', maxBytes: 1024, onProgress: value => events.push(value) });
    assert.equal(events.at(-1).receivedBytes, PNG.length);
    assert.equal(events.at(-1).totalBytes, null);
  }
});

test('an interrupted original still fails saving after showing only the bytes actually received', async () => {
  const events = [];
  const cause = new Error('network interrupted https://media.example/file?signature=private-signature');
  const stream = new ReadableStream({ start(controller) { controller.enqueue(PNG); }, pull(controller) { controller.error(cause); } });
  await assert.rejects(() => boundedMediaBlobFromResponse(new Response(stream),
    { kind: 'image', maxBytes: 1024, onProgress: value => events.push(value) }), error => {
      assert.match(error.message, /network interrupted/);
      assert.doesNotMatch(error.message, /private-signature|https:/);
      assert.equal(error.cause, cause);
      assert.deepEqual(error.mediaDownload, { stage: 'read', receivedBytes: PNG.length });
      return true;
    });
  assert.equal(events.at(-1).receivedBytes, PNG.length);
  assert.equal(events.at(-1).totalBytes, null);
});

test('shared download distinguishes request permission failure from a complete-body Blob sink failure', async () => {
  const denied = new DOMException('Permission denied', 'NotAllowedError');
  await assert.rejects(fetchBoundedMedia('https://media.example/file', { fetchImpl: async () => { throw denied; } }), error => {
    assert.equal(error.name, 'NotAllowedError');
    assert.equal(error.cause, denied);
    assert.deepEqual(error.mediaDownload, { stage: 'request', receivedBytes: 0 });
    return true;
  });
  const OriginalResponse = globalThis.Response;
  const response = new Response(PNG);
  const disk = new DOMException('Temporary disk write failed', 'NotReadableError');
  globalThis.Response = class extends OriginalResponse {
    async blob() { await this.arrayBuffer(); throw disk; }
  };
  try {
    await assert.rejects(fetchBoundedMedia('https://media.example/file', { kind: 'image', fetchImpl: async () => response }), error => {
      assert.equal(error.name, 'NotReadableError');
      assert.equal(error.cause, disk, 'outer fetch must retain the original cause, not wrap it a second time');
      assert.deepEqual(error.mediaDownload, { stage: 'blob', receivedBytes: PNG.length });
      return true;
    });
  } finally { globalThis.Response = OriginalResponse; }
});

test("bounded media trusts file signatures instead of a spoofed content type", async () => {
  const response = new Response(new TextEncoder().encode("<svg onload=alert(1)></svg>"), {
    headers: { "content-type": "image/png" }
  });
  await assert.rejects(
    () => boundedMediaBlobFromResponse(response, { kind: "image", maxBytes: 1024 }),
    /有效图片文件/
  );
});

test("bounded media returns the detected safe type and refuses redirects", async () => {
  const calls = [];
  const blob = await fetchBoundedMedia("https://media.example/image", {
    kind: "image",
    maxBytes: 1024,
    fetchImpl: async (url, options) => {
      calls.push({ url, options });
      return new Response(PNG, { headers: { "content-type": "application/octet-stream" } });
    }
  });
  assert.equal(blob.type, "image/png");
  assert.equal(calls[0].options.redirect, "error");
  assert.equal(calls[0].options.credentials, "omit");
});

test("remote media URLs require HTTPS and cannot contain credentials", () => {
  assert.throws(() => assertRemoteMediaUrl("http://example.com/image.png"), /HTTPS/);
  assert.throws(() => assertRemoteMediaUrl("https://name:[email protected]/image.png"), /登录凭据/);
  assert.equal(assertRemoteMediaUrl("http://127.0.0.1:8080/image.png", { allowLoopback: true }).hostname, "127.0.0.1");
});

test("bounded images report real header dimensions and reject excessive pixel counts", async () => {
  const sizedPng = Uint8Array.from([
    0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
    0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
    0x00, 0x00, 0x0f, 0xa0, 0x00, 0x00, 0x0b, 0xb8
  ]);
  assert.deepEqual(detectImageDimensions(sizedPng, "image/png"), { width: 4000, height: 3000 });
  let metadata = null;
  const blob = await boundedMediaBlobFromResponse(new Response(sizedPng), {
    kind: "image",
    maxBytes: 1024,
    maxPixels: 12_000_000,
    onMetadata: (value) => { metadata = value; }
  });
  assert.equal(blob.type, "image/png");
  assert.deepEqual(metadata, { mimeType: "image/png", width: 4000, height: 3000 });
  await assert.rejects(
    () => boundedMediaBlobFromResponse(new Response(sizedPng), { kind: "image", maxBytes: 1024, maxPixels: 11_999_999 }),
    /图片像素超过/
  );
});

test("bounded documents accept only verified safe document content", async () => {
  const pdf = new TextEncoder().encode("%PDF-1.7\n1 0 obj\n<<>>\nendobj\n%%EOF");
  const pdfBlob = await boundedMediaBlobFromResponse(new Response(pdf, {
    headers: { "content-type": "application/octet-stream" }
  }), { kind: "document", expectedMimeType: "application/pdf", maxBytes: 1024 });
  assert.equal(pdfBlob.type, "application/pdf");

  const html = new TextEncoder().encode("<!doctype html><html><body>Reference</body></html>");
  const htmlBlob = await boundedMediaBlobFromResponse(new Response(html, {
    headers: { "content-type": "text/plain" }
  }), { kind: "document", expectedMimeType: "text/html", maxBytes: 1024 });
  assert.equal(htmlBlob.type, "text/html");

  assert.equal(isSupportedDocumentMimeType("text/markdown; charset=utf-8"), true);
  assert.equal(isSupportedDocumentMimeType("application/zip"), false);
});

test("bounded documents reject spoofed, binary and unsupported files", async () => {
  await assert.rejects(
    () => boundedMediaBlobFromResponse(new Response(new TextEncoder().encode("not a pdf"), {
      headers: { "content-type": "application/pdf" }
    }), { kind: "document", expectedMimeType: "application/pdf", maxBytes: 1024 }),
    /有效文档文件/
  );
  await assert.rejects(
    () => boundedMediaBlobFromResponse(new Response(Uint8Array.from([0x50, 0x4b, 0x03, 0x04, 0, 0, 0]), {
      headers: { "content-type": "text/plain" }
    }), { kind: "document", expectedMimeType: "text/plain", maxBytes: 1024 }),
    /有效文档文件/
  );
  await assert.rejects(
    () => boundedMediaBlobFromResponse(new Response(new TextEncoder().encode("plain"), {
      headers: { "content-type": "application/zip" }
    }), { kind: "document", expectedMimeType: "application/zip", maxBytes: 1024 }),
    /支持的安全文档类型/
  );
});