Open-source AI browser agent for Chrome and Firefox (monorepo) ðŸ§
JavaScript ai-agentai-agentsai-toolsbrowser-aibrowser-automationbrowser-extensionchrome-aichrome-devtoolschrome-extensionchrome-extensionsfirefox-addonfirefox-addonsfirefox-extensionfirefox-extensionsgemmagemma4minimaxoffline-aioffline-llmqwen
fix(chrome): harden PDF host readiness, sender gate, and handler URLs
Codex release-state testaa8c6fb8ff16
diff --git a/src/chrome/src/agent/pdf-extraction.js b/src/chrome/src/agent/pdf-extraction.jsindex 7a6134f00..70a8d89ca 100644--- a/src/chrome/src/agent/pdf-extraction.js+++ b/src/chrome/src/agent/pdf-extraction.js@@ -11,26 +11,58 @@ export const PDF_EXTRACTION_READY_MESSAGE = 'offscreen-pdf-extract-ready';export const PDF_PASSTHROUGH_MAX_BYTES = 16 * 1024 * 1024;const ALLOWED_PDF_PROTOCOLS = new Set(['http:', 'https:', 'file:']);+const PDF_HANDLER_PAGE = 'src/ui/pdf-handler.html';const BASE64_MAX_INPUT_BYTES = 32 * 1024 * 1024;-export function normalizePdfUrl(value) {+// When the native MIME handler owns a PDF tab, the tab URL is our own viewer+// page wrapping the real URL in ?url=. read_pdf falls back to the tab URL when+// called without an explicit one, so unwrap it before the scheme check.+function unwrapPdfHandlerUrl(url, runtime = globalThis.chrome?.runtime) {+ if (url.protocol !== 'chrome-extension:' && url.protocol !== 'moz-extension:') return url;+ if (typeof runtime?.getURL !== 'function') return url;+ let handler;+ try {+ handler = new URL(runtime.getURL(PDF_HANDLER_PAGE));+ } catch {+ return url;+ }+ if (url.origin !== handler.origin || url.pathname !== handler.pathname) return url;+ const inner = url.searchParams.get('url');+ if (!inner) return url;+ try {+ return new URL(inner);+ } catch {+ return url;+ }+}++export function normalizePdfUrl(value, runtime = globalThis.chrome?.runtime) {let url;try {url = new URL(String(value || '').trim());} catch {throw new Error('PDF extraction requires a valid URL.');}+ url = unwrapPdfHandlerUrl(url, runtime);if (!ALLOWED_PDF_PROTOCOLS.has(url.protocol)) {throw new Error('PDF URL must use http:, https:, or file:.');}return url.href;}+// Derived from the manifest rather than hardcoded: a rename of the service+// worker entry would otherwise reject every extraction with a "not ready"+// error that points at the wrong subsystem.+function backgroundScriptPath(runtime) {+ const manifest = typeof runtime?.getManifest === 'function' ? runtime.getManifest() : null;+ return manifest?.background?.service_worker || 'src/background.js';+}+export function isTrustedPdfExtractionSender(sender, runtime = globalThis.chrome?.runtime) {if (!runtime?.id || typeof runtime.getURL !== 'function') return false;return sender?.id === runtime.id&& sender?.tab == null- && sender?.url === runtime.getURL('src/background.js');+ && sender?.url === runtime.getURL(backgroundScriptPath(runtime));}export function bytesToBase64(bytes) {diff --git a/src/chrome/src/agent/pdf-tools.js b/src/chrome/src/agent/pdf-tools.jsindex 9eafe5a02..7795af98a 100644--- a/src/chrome/src/agent/pdf-tools.js+++ b/src/chrome/src/agent/pdf-tools.js@@ -44,13 +44,25 @@ function wait(ms) {async function waitForPdfExtractionHost() {let lastError = null;for (let attempt = 0; attempt < PDF_HOST_READY_ATTEMPTS; attempt++) {+ let refusal = null;try {const response = await chrome.runtime.sendMessage({ type: PDF_EXTRACTION_READY_MESSAGE });if (response?.ready === true) return;- if (response?.error) lastError = new Error(response.error);+ // An explicit error means the host answered and refused. Retrying cannot+ // change the outcome, and reporting it as "not ready" sends whoever is+ // debugging to the wrong subsystem.+ if (response?.error) refusal = new Error(response.error);} catch (error) {+ // No listener: the document went away between ensureOffscreen() seeing it+ // and this probe. Recreate it rather than retrying into a dead channel.lastError = error;+ try {+ await ensureOffscreen();+ } catch (ensureError) {+ lastError = ensureError;+ }}+ if (refusal) throw refusal;if (attempt + 1 < PDF_HOST_READY_ATTEMPTS) await wait(PDF_HOST_READY_RETRY_MS);}const detail = lastError?.message ? ` ${lastError.message}` : '';diff --git a/src/chrome/src/offscreen/pdf-extraction-host.js b/src/chrome/src/offscreen/pdf-extraction-host.jsindex e5c37d22a..26332406b 100644--- a/src/chrome/src/offscreen/pdf-extraction-host.js+++ b/src/chrome/src/offscreen/pdf-extraction-host.js@@ -35,17 +35,18 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {(async () => {const url = normalizePdfUrl(message.url);const bytes = await fetchPdfBytes(url);- // PDF.js can transfer and detach the input buffer. Encode the optional- // Claude document before parsing so text and document use the same fetch.- // The ~4/3 base64 message overhead is intentional to preserve that- // single-fetch, byte-identical guarantee.- const pdfBase64 = message.options?.includeBase64 === true- && bytes.length <= PDF_PASSTHROUGH_MAX_BYTES- ? bytesToBase64(bytes)- : '';+ // PDF.js can transfer and detach the input buffer, so keep a copy of the+ // optional Claude document taken before parsing: text and document then+ // come from the same fetch. The ~4/3 base64 message overhead is+ // intentional to preserve that single-fetch, byte-identical guarantee.+ // The encode itself is deferred until parsing succeeds, so a corrupt PDF+ // that throws in getDocument() does not pay for a string nobody reads.+ const wantsBase64 = message.options?.includeBase64 === true+ && bytes.length <= PDF_PASSTHROUGH_MAX_BYTES;+ const passthrough = wantsBase64 ? bytes.slice() : null;const pdfjs = await getPdfjs();const result = await extractPdfTextFromBytes(pdfjs, bytes, message.options || {});- if (pdfBase64) result._pdfBase64 = pdfBase64;+ if (passthrough) result._pdfBase64 = bytesToBase64(passthrough);sendResponse({ ok: true, result });})().catch((error) => {sendResponse({ ok: false, error: error?.message || String(error) });diff --git a/test/pdf-mime-handler-e2e.mjs b/test/pdf-mime-handler-e2e.mjsindex 8594a99f0..fa769bc7e 100644--- a/test/pdf-mime-handler-e2e.mjs+++ b/test/pdf-mime-handler-e2e.mjs@@ -179,7 +179,15 @@ async function main() {assert.equal(fixture.requestCount(), 0, 'An unauthorized PDF extraction request reached the network.');const backgroundUrl = `chrome-extension://${extensionId}/src/background.js`;- const background = context.serviceWorkers().find(worker => worker.url() === backgroundUrl);+ // serviceWorkers() is a snapshot: Playwright may not have observed the+ // worker yet, and Chrome can idle it out during the steps above.+ let background = context.serviceWorkers().find(worker => worker.url() === backgroundUrl);+ if (!background) {+ background = await context.waitForEvent('serviceworker', {+ predicate: worker => worker.url() === backgroundUrl,+ timeout: 10000,+ }).catch(() => null);+ }assert.ok(background, 'The WebBrain service worker was not available for the PDF extraction test.');const ready = await background.evaluate(async () => chrome.runtime.sendMessage({type: 'offscreen-pdf-extract-ready',diff --git a/test/pdf-read.mjs b/test/pdf-read.mjsindex 4e8856bf5..88e876701 100644--- a/test/pdf-read.mjs+++ b/test/pdf-read.mjs@@ -45,11 +45,35 @@ async function testPdfUrlAndSenderBoundaries() {assert.equal(isTrustedPdfExtractionSender({ id: runtime.id, url: backgroundUrl, tab: { id: 7 } }, runtime), false);assert.equal(isTrustedPdfExtractionSender({ id: 'other-extension', url: backgroundUrl }, runtime), false);+ // The trusted path follows the manifest, so renaming the service worker+ // entry cannot silently start rejecting every extraction.+ const renamedRuntime = {+ ...runtime,+ getManifest: () => ({ background: { service_worker: 'src/sw/main.js' } }),+ };+ assert.equal(isTrustedPdfExtractionSender(+ { id: runtime.id, url: renamedRuntime.getURL('src/sw/main.js') }, renamedRuntime), true);+ assert.equal(isTrustedPdfExtractionSender(+ { id: runtime.id, url: backgroundUrl }, renamedRuntime), false);+assert.equal(normalizePdfUrl('https://example.test/document.pdf'), 'https://example.test/document.pdf');assert.equal(normalizePdfUrl('file:///tmp/document.pdf'), 'file:///tmp/document.pdf');assert.throws(() => normalizePdfUrl('data:application/pdf;base64,JVBERg=='), /must use http.*https.*file/i);assert.throws(() => normalizePdfUrl('javascript:alert(1)'), /must use http.*https.*file/i);+ // A PDF tab owned by the native MIME handler reports our viewer page as its+ // URL; read_pdf falls back to that, so the real URL must be unwrapped.+ const handlerUrl = `${runtime.getURL('src/ui/pdf-handler.html')}?url=${encodeURIComponent('https://example.test/paper.pdf')}&tabId=7`;+ assert.equal(normalizePdfUrl(handlerUrl, runtime), 'https://example.test/paper.pdf');+ assert.throws(+ () => normalizePdfUrl(`${runtime.getURL('src/ui/settings.html')}?url=${encodeURIComponent('https://example.test/x.pdf')}`, runtime),+ /must use http.*https.*file/i,+ 'Only the PDF handler page may unwrap an inner URL.');+ assert.throws(+ () => normalizePdfUrl(`${runtime.getURL('src/ui/pdf-handler.html')}?url=${encodeURIComponent('javascript:alert(1)')}`, runtime),+ /must use http.*https.*file/i,+ 'An unwrapped inner URL must still pass the scheme allowlist.');+let fetchCalls = 0;const originalFetch = globalThis.fetch;globalThis.fetch = async () => {