Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

browser-extension: private interceptor channel, validated relay, loopback-only delivery

Claude17ba26480b0b
diff --git a/browser-extension/README.md b/browser-extension/README.md
index 19a20136..5701665c 100644
--- a/browser-extension/README.md
+++ b/browser-extension/README.md
@@ -23,7 +23,7 @@ flowchart LR
direction TB
MAIN["interceptor.js<br/>MAIN world · tee fetch SSE"]
ISO["content.js<br/>ISOLATED world · relay"]
- MAIN -->|postMessage| ISO
+ MAIN -->|private MessagePort| ISO
end
subgraph SW["Extension service worker"]
@@ -315,12 +315,19 @@ dashboard), including interleaved sessions with no cross-contamination.
currently missed. That resume stream is also SSE-over-fetch (no WebSocket needed for tokens; the
`wss://ws.chatgpt.com` socket only carries control messages), so teeing the resume GET is a
follow-up, not a rearchitecture. ChatGPT web (like Claude web) doesn't stream token usage.
-- **Telemetry integrity on the injected page.** The MAIN-world interceptor and any other page script
- share the same JS world, so the ISOLATED content script cannot cryptographically distinguish the
- extension's own `postMessage` events from forged ones. A malicious script already running on
- claude.ai could therefore inject fabricated chat records into the local collector. Impact is
- telemetry *integrity* only (no credential/code exposure). A proper fix is service-worker-driven
- MAIN injection (`chrome.scripting`) with a per-tab nonce the page can't read; deferred for V0.
+- **Telemetry integrity on the injected page.** The MAIN-world interceptor and the ISOLATED content
+ script talk over a private `MessageChannel` whose port is handed over once, by a synchronously
+ dispatched event at `document_start`, before any page script runs (`src/shared/channel.ts`). The
+ content script never reads `window` messages, request ids are random, and the service worker
+ checks every relayed event's shape and size and bounds how many open streams it holds, so a page
+ script can no longer inject or splice into telemetry. What remains: a script in the page's own
+ world can still change what the page fetches, or wrap `window.fetch` itself, because the page is
+ the data source; and if the interceptor failed to run at all, a page script could offer the
+ content script its own port while the document is still loading.
+- **Loopback-only delivery.** The OTLP endpoint must be `http(s)` on `127.0.0.1`, `localhost` or
+ `[::1]` with an explicit port. The service worker enforces this when settings are saved and again
+ before every send (redirects are refused), and it takes settings changes only from the
+ extension's own popup and options pages, never from a content script.
> **Fixtures.** The committed `*.sse` files are **real, sanitized** captures (via
> `npm run record:fixtures`): `fixtures/claude/simple-turn.sse` (claude.ai) and
diff --git a/browser-extension/e2e/forgery.spec.ts b/browser-extension/e2e/forgery.spec.ts
new file mode 100644
index 00000000..2f7127f6
--- /dev/null
+++ b/browser-extension/e2e/forgery.spec.ts
@@ -0,0 +1,105 @@
+// A script on the chat page must not be able to forge telemetry. The old bridge
+// took any window.postMessage tagged '__beacon_intercept__'; now events travel
+// only over the private port handed over at document_start, so forged window
+// messages and forged port hand-overs from page scripts are ignored, while the
+// real turn is still captured.
+import { test, expect, seedSettings } from './fixtures.js';
+import { allRecords, flatAttrs, recordByAction } from './helpers/otlp-assertions.js';
+
+const CONV = '11111111-2222-3333-4444-555555555555';
+const COMPLETION_PATH = '/api/organizations/org-test/chat_conversations/{conv}/completion';
+const FORGED = 'FORGED PROMPT FROM A PAGE SCRIPT';
+
+test.beforeEach(async ({ mockCollector }) => {
+ mockCollector.reset();
+});
+
+test('page scripts cannot inject telemetry, and the real turn is still captured', async ({
+ context,
+ serviceWorker,
+ replay,
+ mockCollector,
+ extensionId,
+}) => {
+ replay.setCase({
+ site: 'claude',
+ name: 'simple-turn',
+ conversationId: CONV,
+ prompt: 'What is the capital of France?',
+ completionPath: COMPLETION_PATH,
+ });
+ await seedSettings(serviceWorker, {
+ enabled: true,
+ retention: 'full',
+ endpoint: mockCollector.url,
+ sites: { claude_web: true, chatgpt_web: true },
+ });
+
+ const page = await context.newPage();
+ await page.goto(`https://claude.ai/chat?conv=${CONV}`);
+ await expect(page.locator('[data-testid="assistant-message"]')).toHaveAttribute('data-complete', '1');
+ await expect
+ .poll(() => recordByAction(mockCollector.received, 'agent.response.completed'), { timeout: 10_000 })
+ .toBeTruthy();
+
+ // Everything below runs in the page's own world, as any site script would.
+ const probe = await page.evaluate(
+ async ({ forged, conv, path, extensionId }) => {
+ const url = path.replace('{conv}', conv);
+ const body = JSON.stringify({ prompt: forged, conversation_id: conv });
+ const sse =
+ 'event: message_start\ndata: {"type":"message_start","message":{"id":"msg_forged","model":"forged-model"}}\n\n';
+
+ // 1. The old bridge: tagged window messages, with guessable ids.
+ for (const reqId of [1, 2, 3, 'forged-request-0001']) {
+ window.postMessage({ source: '__beacon_intercept__', event: { kind: 'request', reqId, url, method: 'POST', body } }, '*');
+ window.postMessage({ source: '__beacon_intercept__', event: { kind: 'chunk', reqId, chunk: sse } }, '*');
+ window.postMessage({ source: '__beacon_intercept__', event: { kind: 'done', reqId } }, '*');
+ }
+
+ // 2. Ask for the port again, and listen for it.
+ let stolen = 0;
+ window.addEventListener('__beacon_port__', (e) => {
+ if ((e as MessageEvent).ports?.length) stolen++;
+ });
+ window.dispatchEvent(new Event('__beacon_hello__'));
+ const stolenOnHello = stolen;
+
+ // 3. Offer the content script a port of our own.
+ const ch = new MessageChannel();
+ const claimed = !window.dispatchEvent(new MessageEvent('__beacon_port__', { ports: [ch.port2], cancelable: true }));
+ const reqId = 'forged-request-0002';
+ for (const ev of [
+ { kind: 'request', reqId, url, method: 'POST', body },
+ { kind: 'chunk', reqId, chunk: sse },
+ { kind: 'done', reqId },
+ ]) {
+ ch.port1.postMessage(JSON.stringify(ev));
+ }
+
+ // 4. The interceptor bundle is no longer web-accessible.
+ let fingerprintable = true;
+ try {
+ await fetch(`chrome-extension://${extensionId}/interceptor.js`);
+ } catch {
+ fingerprintable = false;
+ }
+
+ await new Promise((r) => setTimeout(r, 1500));
+ return { stolen: stolenOnHello, claimed, fingerprintable };
+ },
+ { forged: FORGED, conv: CONV, path: COMPLETION_PATH, extensionId },
+ );
+
+ expect(probe.stolen).toBe(0);
+ expect(probe.claimed).toBe(false);
+ expect(probe.fingerprintable).toBe(false);
+
+ // Give anything forged time to have been delivered, then check none was.
+ await new Promise((r) => setTimeout(r, 1000));
+ const recs = allRecords(mockCollector.received).map((r) => flatAttrs(r.attributes));
+ const prompts = recs.filter((a) => a['beacon.event.action'] === 'prompt.submitted');
+ expect(prompts.map((a) => a['beacon.prompt.text'])).toEqual(['What is the capital of France?']);
+ expect(JSON.stringify(mockCollector.received)).not.toContain(FORGED);
+ expect(JSON.stringify(mockCollector.received)).not.toContain('forged-model');
+});
diff --git a/browser-extension/e2e/permissions.spec.ts b/browser-extension/e2e/permissions.spec.ts
index 9f464827..04690eb0 100644
--- a/browser-extension/e2e/permissions.spec.ts
+++ b/browser-extension/e2e/permissions.spec.ts
@@ -30,7 +30,7 @@ test('popup and options name withheld hosts and clear once they are granted', as
// needs the browser UI. So simulate the withheld state the way the page sees
// it: a permissions API that reports two hosts missing until they are
// requested. Everything else -- markup, CSS, the click wiring -- is real.
- const withheld = ['*://chatgpt.com/*', 'http://127.0.0.1/*'];
+ const withheld = ['https://chatgpt.com/*', 'http://127.0.0.1/*'];
await context.addInitScript((missing: string[]) => {
if (location.protocol !== 'chrome-extension:') return;
const perms = chrome.permissions;
diff --git a/browser-extension/e2e/settings.spec.ts b/browser-extension/e2e/settings.spec.ts
new file mode 100644
index 00000000..17b20850
--- /dev/null
+++ b/browser-extension/e2e/settings.spec.ts
@@ -0,0 +1,30 @@
+// The options page in the real, loaded extension: the service worker refuses an
+// endpoint off loopback, the page says why, and nothing is saved.
+import { test, expect } from './fixtures.js';
+
+test('options page refuses a non-loopback endpoint and keeps the saved one', async ({
+ context,
+ extensionId,
+ serviceWorker,
+}) => {
+ const page = await context.newPage();
+ await page.goto(`chrome-extension://${extensionId}/options.html`);
+ const endpoint = page.locator('[data-testid="endpoint"]');
+ await expect(endpoint).toHaveValue('http://127.0.0.1:4318/v1/logs');
+
+ await endpoint.fill('https://collector.example.com:4318/v1/logs');
+ await page.locator('#save').click();
+ await expect(page.locator('[data-testid="settings-error"]')).toBeVisible();
+ await expect(page.locator('[data-testid="settings-error"]')).toContainText('127.0.0.1');
+
+ const stored = await serviceWorker.evaluate(async () => (await chrome.storage.local.get('settings')).settings);
+ expect(stored.endpoint).toBe('http://127.0.0.1:4318/v1/logs');
+
+ await endpoint.fill('http://localhost:4319/v1/logs');
+ await page.locator('#save').click();
+ await expect(page.locator('#saved')).toBeVisible();
+ await expect(page.locator('[data-testid="settings-error"]')).toBeHidden();
+ await expect
+ .poll(() => serviceWorker.evaluate(async () => (await chrome.storage.local.get('settings')).settings.endpoint))
+ .toBe('http://localhost:4319/v1/logs');
+});
diff --git a/browser-extension/src/adapters/adapter.ts b/browser-extension/src/adapters/adapter.ts
index 1f8a663d..9b3c3a0f 100644
--- a/browser-extension/src/adapters/adapter.ts
+++ b/browser-extension/src/adapters/adapter.ts
@@ -20,8 +20,8 @@ export interface SiteAdapter {
matchesHost(host: string): boolean;
/** Whether this request is a chat completion worth capturing. */
matchesRequest(url: string, method: string): boolean;
- /** @param reqId the interceptor's per-page request id (from the InterceptEvent). */
- createParser(reqId: number): TurnParser;
+ /** @param reqId the interceptor's random request id (from the InterceptEvent). */
+ createParser(reqId: string): TurnParser;
}
const registry: SiteAdapter[] = [];
diff --git a/browser-extension/src/adapters/chatgpt.ts b/browser-extension/src/adapters/chatgpt.ts
index 9b9fe626..aab399f7 100644
--- a/browser-extension/src/adapters/chatgpt.ts
+++ b/browser-extension/src/adapters/chatgpt.ts
@@ -28,7 +28,7 @@ import { turnId } from '../shared/ids.js';
class ChatGptParser implements TurnParser {
private sse = new SSEParser();
- private reqId: number;
+ private reqId: string;
private sessionId = '';
private requestModel?: string;
private promptText = '';
@@ -43,7 +43,7 @@ class ChatGptParser implements TurnParser {
/** Reference to the visible assistant message object (mutated in place by ops). */
private assistantMsg: any = null;
- constructor(reqId: number) {
+ constructor(reqId: string) {
this.reqId = reqId;
}
diff --git a/browser-extension/src/adapters/claude.ts b/browser-extension/src/adapters/claude.ts
index ce61c2c6..2e2846e0 100644
--- a/browser-extension/src/adapters/claude.ts
+++ b/browser-extension/src/adapters/claude.ts
@@ -34,14 +34,14 @@ class ClaudeParser implements TurnParser {
private cacheReadInputTokens?: number;
private startedAt = Date.now();
private completedAt?: number;
- private reqId: number;
+ private reqId: string;
/** Stable per-turn id from message_start; used for turnId so ids don't collide
* across service-worker restarts (which reset the reqId counter). */
private messageId = '';
// tool_use blocks keyed by content-block index.
private blocks = new Map<number, { type: string; tool?: ToolCall; argBuf: string }>();
- constructor(reqId: number) {
+ constructor(reqId: string) {
this.reqId = reqId;
}
diff --git a/browser-extension/src/background/assembler.ts b/browser-extension/src/background/assembler.ts
index ded16b9e..04af8606 100644
--- a/browser-extension/src/background/assembler.ts
+++ b/browser-extension/src/background/assembler.ts
@@ -2,56 +2,148 @@
// (tabId, reqId). No chrome.* — unit-testable. State is intentionally in-memory:
// a stream lasts seconds and the SW is kept awake while one is active; the
// DURABLE state (the delivery queue) lives in storage, not here.
+//
+// The state is bounded. A tab holds at most `maxPerTab` open streams and the
+// worker at most `maxTotal`; a stream with no event for `maxIdleMs`, or one
+// that has buffered more than `maxEntryBytes`, is closed. Closing a stream that
+// never saw `done` finalizes it the same way an aborted stream is: whatever was
+// parsed becomes a best-effort partial turn (no completedAt), or nothing if the
+// parser captured nothing. So a stream that never ends cannot hold memory, or
+// the keepalive, forever.
import type { ChatTurn } from '../shared/types.js';
import type { InterceptEvent } from '../shared/types.js';
import { adapterForHost, type SiteAdapter, type TurnParser } from '../adapters/adapter.js';
interface Entry {
+ tabId: number;
adapter: SiteAdapter;
parser: TurnParser;
+ /** Last event time (epoch ms). */
+ seenAt: number;
+ /** Request body plus chunk characters buffered so far. */
+ bytes: number;
}
+export interface AssemblerLimits {
+ maxPerTab: number;
+ maxTotal: number;
+ maxIdleMs: number;
+ maxEntryBytes: number;
+}
+
+export const DEFAULT_LIMITS: Readonly<AssemblerLimits> = Object.freeze({
+ maxPerTab: 8,
+ maxTotal: 64,
+ // Long reasoning turns can go quiet for a while between chunks.
+ maxIdleMs: 10 * 60_000,
+ maxEntryBytes: 32 * 1024 * 1024,
+});
+
export class Assembler {
+ // Map iteration order is insertion order, which makes the first entry for a
+ // tab its oldest.
private entries = new Map<string, Entry>();
+ private readonly limits: AssemblerLimits;
+ private readonly now: () => number;
+
+ constructor(limits: Partial<AssemblerLimits> = {}, now: () => number = Date.now) {
+ this.limits = { ...DEFAULT_LIMITS, ...limits };
+ this.now = now;
+ }
- private key(tabId: number | undefined, reqId: number): string {
- return `${tabId ?? -1}:${reqId}`;
+ private key(tabId: number, reqId: string): string {
+ return `${tabId}:${reqId}`;
}
- /** Feed one intercept event. Returns a finalized ChatTurn on 'done'/'error'. */
- handle(host: string, tabId: number | undefined, event: InterceptEvent): ChatTurn | null {
- const k = this.key(tabId, event.reqId);
+ /**
+ * Feed one intercept event. Returns the turns finalized by it: the stream's
+ * own turn on 'done'/'error', plus any older stream closed to make room.
+ */
+ handle(host: string, tabId: number | undefined, event: InterceptEvent): ChatTurn[] {
+ const tab = tabId ?? -1;
+ const k = this.key(tab, event.reqId);
+ const out: ChatTurn[] = [];
if (event.kind === 'request') {
+ // A repeated request id replaces nothing: ids are random, so a repeat is
+ // not the interceptor's.
+ if (this.entries.has(k)) return out;
const adapter = adapterForHost(host);
- if (!adapter || !adapter.matchesRequest(event.url, event.method)) return null;
+ if (!adapter || !adapter.matchesRequest(event.url, event.method)) return out;
+ this.makeRoom(tab, out);
const parser = adapter.createParser(event.reqId);
parser.onRequest(event.url, event.method, event.body);
- this.entries.set(k, { adapter, parser });
- return null;
+ this.entries.set(k, {
+ tabId: tab,
+ adapter,
+ parser,
+ seenAt: this.now(),
+ bytes: event.body?.length ?? 0,
+ });
+ return out;
}
const entry = this.entries.get(k);
- if (!entry) return null;
+ if (!entry) return out;
+ entry.seenAt = this.now();
switch (event.kind) {
case 'chunk':
+ entry.bytes += event.chunk.length;
+ if (entry.bytes > this.limits.maxEntryBytes) {
+ this.close(k, out);
+ return out;
+ }
entry.parser.onChunk(event.chunk);
- return null;
+ return out;
case 'done':
- case 'error': {
- entry.parser.onDone();
- const turn = entry.parser.getTurn();
- this.entries.delete(k);
- return turn;
- }
+ case 'error':
+ this.close(k, out);
+ return out;
}
- return null;
+ return out;
+ }
+
+ /** Close every stream idle for longer than maxIdleMs. */
+ sweep(): ChatTurn[] {
+ const out: ChatTurn[] = [];
+ const cutoff = this.now() - this.limits.maxIdleMs;
+ for (const [k, e] of [...this.entries]) {
+ if (e.seenAt <= cutoff) this.close(k, out);
+ }
+ return out;
+ }
+
+ /** Close every stream of a tab (the tab was closed or navigated away). */
+ closeTab(tabId: number): ChatTurn[] {
+ const out: ChatTurn[] = [];
+ for (const [k, e] of [...this.entries]) {
+ if (e.tabId === tabId) this.close(k, out);
+ }
+ return out;
}
/** Number of in-flight streams (used to decide SW keepalive). */
get active(): number {
return this.entries.size;
}
+
+ private makeRoom(tabId: number, out: ChatTurn[]): void {
+ const forTab = [...this.entries].filter(([, e]) => e.tabId === tabId);
+ for (let i = 0; i <= forTab.length - this.limits.maxPerTab; i++) this.close(forTab[i][0], out);
+ while (this.entries.size >= this.limits.maxTotal) {
+ const oldest = this.entries.keys().next().value as string;
+ this.close(oldest, out);
+ }
+ }
+
+ private close(k: string, out: ChatTurn[]): void {
+ const entry = this.entries.get(k);
+ if (!entry) return;
+ this.entries.delete(k);
+ entry.parser.onDone();
+ const turn = entry.parser.getTurn();
+ if (turn) out.push(turn);
+ }
}
diff --git a/browser-extension/src/background/delivery.ts b/browser-extension/src/background/delivery.ts
index 7eb95595..8f027568 100644
--- a/browser-extension/src/background/delivery.ts
+++ b/browser-extension/src/background/delivery.ts
@@ -8,6 +8,7 @@ import type { ChatTurn, Settings } from '../shared/types.js';
import { turnToEnvelope } from '../shared/normalize.js';
import type { LogsEnvelope } from '../shared/otlp.js';
import type { BrowserIdentity } from '../shared/browser-identity.js';
+import { isAllowedEndpoint } from '../shared/validate.js';
const QUEUE_KEY = 'delivery_queue';
const ALARM = 'beacon_flush';
@@ -74,6 +75,10 @@ export async function flush(): Promise<void> {
let anyFailed = false;
for (const item of queue) {
+ // Checked again at send time, not only when settings are saved: an item
+ // queued by an older build, or a tampered queue, must not reach anything
+ // but the local collector. Such an item is dropped, not retried.
+ if (!isAllowedEndpoint(item.endpoint)) continue;
const ok = await post(item);
if (!ok) {
item.attempts += 1;
@@ -90,10 +95,13 @@ export async function flush(): Promise<void> {
}
async function post(item: QueueItem): Promise<boolean> {
+ if (!isAllowedEndpoint(item.endpoint)) return false;
try {
const res = await fetch(item.endpoint, {
method: 'POST',
headers: { 'content-type': 'application/json' },
+ // A loopback listener must not be able to bounce chat content elsewhere.
+ redirect: 'error',
body: JSON.stringify(item.envelope),
});
return res.ok;
diff --git a/browser-extension/src/background/sender.ts b/browser-extension/src/background/sender.ts
new file mode 100644
index 00000000..684a7b0f
--- /dev/null
+++ b/browser-extension/src/background/sender.ts
@@ -0,0 +1,47 @@
+// Who sent a runtime message. Content scripts run inside the chat site's
+// renderer process, which the browser treats as untrusted: a compromised
+// renderer can send any message a content script could. So control messages
+// (settings, flush, status) are taken only from the extension's own pages, and
+// relay messages only from a content script in a tab. Pure, for unit tests.
+
+/** The fields of runtime.MessageSender this module reads. */
+export interface SenderLike {
+ id?: string;
+ url?: string;
+ origin?: string;
+ tab?: { id?: number };
+}
+
+/**
+ * True when the message came from one of this extension's own pages (popup,
+ * options, whether or not it is open in a tab): same extension id, and a sender
+ * URL on the extension's own scheme and host. `extensionBaseUrl` is
+ * runtime.getURL(''). Scheme and host are compared rather than `URL.origin`,
+ * which some engines report as "null" for extension schemes.
+ */
+export function isExtensionPage(sender: SenderLike, runtimeId: string, extensionBaseUrl: string): boolean {
+ if (!runtimeId || sender.id !== runtimeId || typeof sender.url !== 'string') return false;
+ try {
+ const from = new URL(sender.url);
+ const own = new URL(extensionBaseUrl);
+ return own.host !== '' && from.protocol === own.protocol && from.host === own.host;
+ } catch {
+ return false;
+ }
+}
+
+/** True when the message came from this extension's content script in a tab. */
+export function isOwnContentScript(sender: SenderLike, runtimeId: string): boolean {
+ return !!runtimeId && sender.id === runtimeId && typeof sender.tab?.id === 'number';
+}
+
+/** The host of the frame that sent a relay message, from the browser's own
+ * record of the sender rather than from the message body. */
+export function senderHost(sender: SenderLike): string | null {
+ if (typeof sender.url !== 'string') return null;
+ try {
+ return new URL(sender.url).host || null;
+ } catch {
+ return null;
+ }
+}
diff --git a/browser-extension/src/background/settings.ts b/browser-extension/src/background/settings.ts
index 5e3d44b7..b8987725 100644
--- a/browser-extension/src/background/settings.ts
+++ b/browser-extension/src/background/settings.ts
@@ -3,19 +3,37 @@
import { ext } from '../shared/browser.js';
import { DEFAULT_SETTINGS, type Settings, type SiteName } from '../shared/types.js';
+import { parseSettingsPatch } from '../shared/validate.js';
const KEY = 'settings';
+/**
+ * Merge stored settings over the defaults, keeping only stored values that
+ * still validate. A value saved by an older build that is no longer allowed
+ * (an endpoint off loopback, say) falls back to its default.
+ */
+export function resolveSettings(stored: unknown): Settings {
+ const s = (stored ?? {}) as Partial<Settings>;
+ const out: Settings = { ...DEFAULT_SETTINGS, sites: { ...DEFAULT_SETTINGS.sites } };
+ for (const key of ['enabled', 'retention', 'endpoint'] as const) {
+ if (!(key in s)) continue;
+ const r = parseSettingsPatch({ [key]: s[key] });
+ if (r.ok) Object.assign(out, r.patch);
+ }
+ if (s.sites && typeof s.sites === 'object') {
+ for (const site of Object.keys(out.sites) as SiteName[]) {
+ if (typeof s.sites[site] === 'boolean') out.sites[site] = s.sites[site];
+ }
+ }
+ return out;
+}
+
export async function getSettings(): Promise<Settings> {
const got = await ext.storage.local.get(KEY);
- const stored = (got[KEY] ?? {}) as Partial<Settings>;
- return {
- ...DEFAULT_SETTINGS,
- ...stored,
- sites: { ...DEFAULT_SETTINGS.sites, ...(stored.sites ?? {}) },
- };
+ return resolveSettings(got[KEY]);
}
+/** Apply an already-validated patch (see parseSettingsPatch). */
export async function saveSettings(patch: Partial<Settings>): Promise<Settings> {
const current = await getSettings();
const next: Settings = {
diff --git a/browser-extension/src/background/sw.ts b/browser-extension/src/background/sw.ts
index 83692ded..9b439d52 100644
--- a/browser-extension/src/background/sw.ts
+++ b/browser-extension/src/background/sw.ts
@@ -4,11 +4,13 @@
import '../adapters/claude.js'; // registers the Claude adapter (side effect)
import '../adapters/chatgpt.js'; // registers the ChatGPT adapter (side effect)
import { ext } from '../shared/browser.js';
-import type { ChatTurn, RelayMessage, Settings } from '../shared/types.js';
+import type { ChatTurn } from '../shared/types.js';
import { getSettings, saveSettings, siteEnabled } from './settings.js';
import { Assembler } from './assembler.js';
import { enqueueTurn, flush, installFlushAlarm } from './delivery.js';
import { detectBrowser } from '../shared/browser-identity.js';
+import { parseHost, parseInterceptEvent, parseSettingsPatch } from '../shared/validate.js';
+import { isExtensionPage, isOwnContentScript, senderHost, type SenderLike } from './sender.js';
const assembler = new Assembler();
@@ -19,36 +21,58 @@ const browserIdentity = detectBrowser(globalThis.navigator);
// Keep the SW awake while any stream is active, so mid-stream suspension is
// rare. Correctness never depends on this — durable state covers the rest.
+// Each tick also closes streams that went idle, so a stream that never sends
+// `done` cannot keep the worker awake.
let keepAliveTimer: ReturnType<typeof setInterval> | undefined;
function updateKeepAlive(): void {
if (assembler.active > 0 && keepAliveTimer == null) {
- keepAliveTimer = setInterval(() => void ext.runtime.getPlatformInfo(), 20_000);
+ keepAliveTimer = setInterval(() => {
+ finalizeAll(assembler.sweep());
+ updateKeepAlive();
+ if (keepAliveTimer != null) void ext.runtime.getPlatformInfo();
+ }, 20_000);
} else if (assembler.active === 0 && keepAliveTimer != null) {
clearInterval(keepAliveTimer);
keepAliveTimer = undefined;
}
}
+function finalizeAll(turns: ChatTurn[]): void {
+ for (const turn of turns) void finalizeTurn(turn);
+}
+
ext.runtime.onInstalled.addListener(() => {
void saveSettings({}); // materialize defaults
});
installFlushAlarm();
-ext.runtime.onMessage.addListener((msg: RelayMessage | ControlMessage, sender, sendResponse) => {
- if (isControl(msg)) {
- handleControl(msg).then(sendResponse);
+// A closed tab's streams will never send `done`; finalize what they captured.
+ext.tabs?.onRemoved?.addListener((tabId) => {
+ finalizeAll(assembler.closeTab(tabId));
+ updateKeepAlive();
+});
+
+ext.runtime.onMessage.addListener((msg: unknown, sender, sendResponse) => {
+ const type = (msg as { type?: unknown } | null)?.type;
+ if (isControlType(type)) {
+ if (!isExtensionPage(sender as SenderLike, ext.runtime.id, ext.runtime.getURL(''))) return false;
+ handleControl(msg as ControlMessage).then(sendResponse);
return true; // async response
}
- if (msg?.type === 'BEACON_RAW') {
+ if (type === 'BEACON_RAW') {
+ if (!isOwnContentScript(sender as SenderLike, ext.runtime.id)) return false;
+ const event = parseInterceptEvent((msg as { event?: unknown }).event);
+ // Prefer the browser's record of the sending frame over the message body.
+ const host = senderHost(sender as SenderLike) ?? parseHost((msg as { host?: unknown }).host);
+ if (!event || !host) return false;
// Feed the assembler SYNCHRONOUSLY, in message-arrival order. Stream events
// arrive ordered (request → chunk → … → done); an `await` before this call
// could let a chunk be processed before its `request` registered a parser,
// dropping early SSE (e.g. message_start). Async work (settings, delivery)
// happens only after a turn is finalized.
- const turn = assembler.handle(msg.host, sender.tab?.id, msg.event);
+ finalizeAll(assembler.handle(host, sender.tab?.id, event));
updateKeepAlive();
- if (turn) void finalizeTurn(turn);
return false;
}
return false;
@@ -65,11 +89,11 @@ async function finalizeTurn(turn: ChatTurn): Promise<void> {
type ControlMessage =
| { type: 'GET_STATUS' }
- | { type: 'SET_SETTINGS'; patch: Partial<Settings> }
+ | { type: 'SET_SETTINGS'; patch: unknown }
| { type: 'FLUSH_NOW' };
-function isControl(msg: any): msg is ControlMessage {
- return msg?.type === 'GET_STATUS' || msg?.type === 'SET_SETTINGS' || msg?.type === 'FLUSH_NOW';
+function isControlType(type: unknown): type is ControlMessage['type'] {
+ return type === 'GET_STATUS' || type === 'SET_SETTINGS' || type === 'FLUSH_NOW';
}
async function handleControl(msg: ControlMessage): Promise<unknown> {
@@ -79,8 +103,11 @@ async function handleControl(msg: ControlMessage): Promise<unknown> {
const q = await ext.storage.local.get('delivery_queue');
return { settings, queueDepth: (q.delivery_queue ?? []).length, active: assembler.active };
}
- case 'SET_SETTINGS':
- return { settings: await saveSettings(msg.patch) };
+ case 'SET_SETTINGS': {
+ const parsed = parseSettingsPatch(msg.patch);
+ if (!parsed.ok) return { error: parsed.error, settings: await getSettings() };
+ return { settings: await saveSettings(parsed.patch) };
+ }
case 'FLUSH_NOW':
await flush();
return { ok: true };
diff --git a/browser-extension/src/content/content.ts b/browser-extension/src/content/content.ts
index 1b51735b..4c8d95cd 100644
--- a/browser-extension/src/content/content.ts
+++ b/browser-extension/src/content/content.ts
@@ -1,10 +1,16 @@
// ISOLATED-world content script. The bridge between the page (MAIN interceptor)
-// and the extension service worker. Deliberately thin: validate the message
-// origin, then forward raw intercept events to the SW. All parsing/normalizing
-// happens in the SW so this script stays resistant to page interference.
+// and the extension service worker. Deliberately thin: take events only from
+// the private port the interceptor handed over at document_start
+// (src/shared/channel.ts), check their shape, and forward them to the SW. All
+// parsing/normalizing happens in the SW so this script stays resistant to page
+// interference.
+//
+// This script never listens to window messages: any page script can post one.
-import { BEACON_MSG, type BeaconWindowMessage, type RelayMessage } from '../shared/types.js';
+import type { RelayMessage } from '../shared/types.js';
import { ext } from '../shared/browser.js';
+import { acceptChannel, type ChannelHost } from '../shared/channel.js';
+import { parseInterceptEvent } from '../shared/validate.js';
/**
* True only when the extension context this content script belongs to is still
@@ -23,11 +29,17 @@ function extensionAlive(): boolean {
let warnedInvalidated = false;
-window.addEventListener('message', (event: MessageEvent) => {
- // Only trust messages from this same window/frame.
- if (event.source !== window) return;
- const data = event.data as BeaconWindowMessage | undefined;
- if (!data || data.source !== BEACON_MSG) return;
+function relay(raw: unknown): void {
+ // The interceptor sends JSON strings; anything else did not come from it.
+ if (typeof raw !== 'string') return;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(raw);
+ } catch {
+ return;
+ }
+ const event = parseInterceptEvent(parsed);
+ if (!event) return;
if (!extensionAlive()) {
if (!warnedInvalidated) {
@@ -37,18 +49,22 @@ window.addEventListener('message', (event: MessageEvent) => {
return;
}
- const relay: RelayMessage = {
+ const message: RelayMessage = {
type: 'BEACON_RAW',
host: window.location.host,
- event: data.event,
+ event,
};
// Fire-and-forget; the SW may be asleep and will wake to handle it. Wrap in
// try/catch in case the context is invalidated between the check and the call.
try {
- void ext.runtime.sendMessage(relay).catch(() => {
+ void ext.runtime.sendMessage(message).catch(() => {
/* SW not ready / extension reloading — safe to drop a single event */
});
} catch {
/* context invalidated mid-flight */
}
+}
+
+acceptChannel(window as unknown as ChannelHost, (port) => {
+ port.onmessage = (event: MessageEvent) => relay(event.data);
});
diff --git a/browser-extension/src/interceptor/interceptor.ts b/browser-extension/src/interceptor/interceptor.ts
index d870c706..97d98125 100644
--- a/browser-extension/src/interceptor/interceptor.ts
+++ b/browser-extension/src/interceptor/interceptor.ts
@@ -1,15 +1,21 @@
// MAIN-world interceptor. Runs in the page's own JS context (injected as a file
// via a world:"MAIN" content script, which satisfies ChatGPT's CSP since it is
// not inline). It monkeypatches window.fetch, clones matched streaming
-// responses so the page is completely unaffected, and posts raw SSE chunks to
-// the ISOLATED content script over window.postMessage.
+// responses so the page is completely unaffected, and sends raw SSE chunks to
+// the ISOLATED content script over a private MessagePort handed over at
+// document_start (src/shared/channel.ts), never over window.postMessage.
//
// This layer is deliberately site-agnostic: it does NOT understand SSE
// semantics. It only decides "is this a chat request worth teeing?" and relays
// bytes. All parsing happens in the service worker via the site adapter.
+//
+// Everything the send path calls is captured here, at document_start, before
+// any page script runs, so a page script that later replaces JSON.stringify or
+// MessagePort.prototype.postMessage cannot read or rewrite what is sent.
-import { BEACON_MSG, type InterceptEvent } from '../shared/types.js';
+import type { InterceptEvent } from '../shared/types.js';
import { looksLikeChatRequest } from '../adapters/adapter.js';
+import { offerChannel } from '../shared/channel.js';
declare global {
interface Window {
@@ -21,11 +27,17 @@ declare global {
if (window.__beaconInterceptorInstalled) return;
window.__beaconInterceptorInstalled = true;
- let reqSeq = 0;
+ const apply = Reflect.apply;
+ const stringify = JSON.stringify;
+ const portPostMessage = MessagePort.prototype.postMessage;
+ const randomId = makeRandomId();
const originalFetch = window.fetch.bind(window);
+ const port = offerChannel(window);
function post(event: InterceptEvent): void {
- window.postMessage({ source: BEACON_MSG, event }, window.location.origin);
+ // A JSON string, so the receiving world parses it itself instead of
+ // reading an object created in this one.
+ apply(portPostMessage, port, [stringify(event)]);
}
window.fetch = async function beaconFetch(
@@ -57,13 +69,13 @@ declare global {
const response = await originalFetch(input as RequestInfo, init);
if (matched && response.body) {
- const reqId = ++reqSeq;
+ const reqId = randomId();
post({ kind: 'request', reqId, url, method, body });
// Tee the stream via a clone so the page's own reader is untouched.
const clone = response.clone();
teeStream(clone, reqId, post).catch((err) =>
- post({ kind: 'error', reqId, message: String(err) }),
+ post({ kind: 'error', reqId, message: String(err).slice(0, 1024) }),
);
}
@@ -71,9 +83,20 @@ declare global {
} as typeof window.fetch;
})();
+/** Unguessable request ids, so nothing can address another request's stream. */
+function makeRandomId(): () => string {
+ const c = globalThis.crypto;
+ if (typeof c?.randomUUID === 'function') return c.randomUUID.bind(c);
+ const getRandomValues = c.getRandomValues.bind(c);
+ return () => {
+ const b = getRandomValues(new Uint8Array(16));
+ return Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');
+ };
+}
+
async function teeStream(
response: Response,
- reqId: number,
+ reqId: string,
post: (e: InterceptEvent) => void,
): Promise<void> {
const reader = response.body!.getReader();
diff --git a/browser-extension/src/manifest.json b/browser-extension/src/manifest.json
index 3d502a23..7dcdd9b6 100644
--- a/browser-extension/src/manifest.json
+++ b/browser-extension/src/manifest.json
@@ -3,11 +3,11 @@
"name": "Agent Beacon — Browser Collector",
"version": "0.1.0",
"description": "Relays LLM chat telemetry (Claude, ChatGPT) into the local Agent Beacon pipeline.",
- "permissions": ["storage", "alarms", "scripting"],
+ "permissions": ["storage", "alarms"],
"host_permissions": [
- "*://claude.ai/*",
- "*://chatgpt.com/*",
- "*://chat.openai.com/*",
+ "https://claude.ai/*",
+ "https://chatgpt.com/*",
+ "https://chat.openai.com/*",
"http://127.0.0.1/*",
"http://localhost/*"
],
@@ -21,22 +21,16 @@
"options_page": "options.html",
"content_scripts": [
{
- "matches": ["*://claude.ai/*", "*://chatgpt.com/*", "*://chat.openai.com/*"],
+ "matches": ["https://claude.ai/*", "https://chatgpt.com/*", "https://chat.openai.com/*"],
"js": ["interceptor.js"],
"run_at": "document_start",
"world": "MAIN"
},
{
- "matches": ["*://claude.ai/*", "*://chatgpt.com/*", "*://chat.openai.com/*"],
+ "matches": ["https://claude.ai/*", "https://chatgpt.com/*", "https://chat.openai.com/*"],
"js": ["content.js"],
"run_at": "document_start",
"world": "ISOLATED"
}
- ],
- "web_accessible_resources": [
- {
- "resources": ["interceptor.js"],
- "matches": ["*://claude.ai/*", "*://chatgpt.com/*", "*://chat.openai.com/*"]
- }
]
}
diff --git a/browser-extension/src/options/options.html b/browser-extension/src/options/options.html
index 85f4528d..3f9105bb 100644
--- a/browser-extension/src/options/options.html
+++ b/browser-extension/src/options/options.html
@@ -10,6 +10,8 @@
.site { display: flex; align-items: center; gap: 8px; font-weight: 400; margin: 6px 0; }
button { margin-top: 16px; padding: 8px 14px; font: inherit; }
.saved { color: #2a7; margin-left: 10px; }
+ .error { color: #b00020; margin: 8px 0 0; }
+ .hint { color: #555; margin: 4px 0 0; font-size: 12px; }
.perm { margin: 12px 0; padding: 10px; border: 1px solid #e0a800; background: #fff8e1; border-radius: 4px; }
.perm p { margin: 0 0 8px; }
.perm button { margin-top: 0; }
@@ -27,6 +29,7 @@
<label for="endpoint">OTLP logs endpoint</label>
<input type="text" id="endpoint" data-testid="endpoint" />
+ <p class="hint">Loopback only: an http(s) URL on 127.0.0.1, localhost or [::1] with a port.</p>
<label>Sites</label>
<label class="site"><input type="checkbox" id="site_claude_web" /><span>claude.ai</span></label>
@@ -35,6 +38,7 @@
<div>
<button id="save">Save</button>
<span class="saved" id="saved" hidden>Saved ✓</span>
+ <p class="error" id="error" data-testid="settings-error" role="alert" hidden></p>
</div>
<script src="options.js"></script>
diff --git a/browser-extension/src/options/options.ts b/browser-extension/src/options/options.ts
index b2ec68db..5579dd12 100644
--- a/browser-extension/src/options/options.ts
+++ b/browser-extension/src/options/options.ts
@@ -22,7 +22,14 @@ $('save').addEventListener('click', async () => {
chatgpt_web: ($('site_chatgpt_web') as HTMLInputElement).checked,
},
};
- await ext.runtime.sendMessage({ type: 'SET_SETTINGS', patch });
+ const res = (await ext.runtime.sendMessage({ type: 'SET_SETTINGS', patch })) as {
+ error?: string;
+ };
+ // The service worker validates every patch; a rejected one changes nothing.
+ const error = $('error');
+ error.textContent = res?.error ?? '';
+ error.hidden = !res?.error;
+ if (res?.error) return;
const saved = $('saved');
saved.hidden = false;
setTimeout(() => (saved.hidden = true), 1500);
diff --git a/browser-extension/src/shared/browser.ts b/browser-extension/src/shared/browser.ts
index 430f75bb..13d53efa 100644
--- a/browser-extension/src/shared/browser.ts
+++ b/browser-extension/src/shared/browser.ts
@@ -10,7 +10,8 @@
// promise-returning object without a polyfill or per-call feature checks.
//
// Scope is deliberately small: only the APIs this extension uses (storage,
-// runtime, alarms, permissions), which have the same shape on all three engines.
+// runtime, alarms, permissions, tabs.onRemoved), which have the same shape on
+// all three engines.
// The type is Chrome's, because @types/chrome describes the promise overloads we
// call and Firefox/Safari match them for this subset.
diff --git a/browser-extension/src/shared/channel.ts b/browser-extension/src/shared/channel.ts
new file mode 100644
index 00000000..fd6b60b6
--- /dev/null
+++ b/browser-extension/src/shared/channel.ts
@@ -0,0 +1,108 @@
+// Private channel between the MAIN-world interceptor and the ISOLATED-world
+// content script.
+//
+// The two scripts share the page's window but not its JavaScript world. The old
+// bridge was window.postMessage, which every page script can call, so any script
+// on claude.ai or chatgpt.com could forge telemetry. Now the interceptor creates
+// a MessageChannel and hands one end to the content script once, at
+// document_start, before any page script exists. Afterwards events travel only
+// over that port, which lives in two closures and is never reachable from the
+// page. The content script no longer listens to window messages at all.
+//
+// The hand-over is a synchronously dispatched event, never window.postMessage:
+// postMessage delivers in a later task, and a page script that ran in between
+// could register a listener and read the port from `event.ports`. Dispatch is
+// synchronous, so the port is delivered and claimed before the dispatch
+// returns, while nothing but the two extension scripts has run.
+//
+// Chrome injects document_start scripts in manifest order, but neither side
+// relies on it. Whichever script runs second completes the hand-over:
+// - The interceptor dispatches PORT_EVENT (cancelable) carrying the port. If
+// the content script is already listening it claims the port and cancels the
+// event, which tells the interceptor the port arrived.
+// - Otherwise the interceptor waits for HELLO_EVENT, which the content script
+// dispatches when it starts, and answers it by dispatching PORT_EVENT again.
+// Both sides accept exactly one hand-over and stop listening when the document
+// finishes loading.
+//
+// Residual risk, stated plainly: a script in the page's own world can still
+// change what the page fetches, or replace window.fetch after the interceptor,
+// because the page is the data source. What it can no longer do is inject or
+// alter events on the channel without holding the port. If the interceptor
+// failed to run at all, a page script could hand the content script a port of
+// its own while the document is still loading; nothing else can.
+
+/** Fired by the interceptor (a MessageEvent whose ports[0] is the channel). */
+export const PORT_EVENT = '__beacon_port__';
+/** Fired by the content script to ask an already-installed interceptor for the port. */
+export const HELLO_EVENT = '__beacon_hello__';
+
+/** The DOM surface both halves need: the page's window in production, a plain
+ * EventTarget in unit tests. */
+export interface ChannelHost extends EventTarget {
+ document?: { readyState?: string; addEventListener?(type: string, fn: () => void, opts?: unknown): void };
+}
+
+/** True while the hand-over window is open: before the document finishes
+ * parsing. A host without a document (unit tests) is always open. */
+function loading(host: ChannelHost): boolean {
+ const state = host.document?.readyState;
+ return state == null || state === 'loading';
+}
+
+/** Run `fn` once, when the document finishes parsing. */
+function onLoaded(host: ChannelHost, fn: () => void): void {
+ host.document?.addEventListener?.('DOMContentLoaded', fn, { once: true });
+}
+
+/**
+ * MAIN-world half. Creates the channel, starts the hand-over and returns the
+ * end the interceptor keeps. Call once, at document_start.
+ */
+export function offerChannel(
+ host: ChannelHost,
+ makeChannel: () => MessageChannel = () => new MessageChannel(),
+): MessagePort {
+ const { port1, port2 } = makeChannel();
+ let handed = false;
+
+ const offer = (): void => {
+ if (handed) return;
+ const event = new MessageEvent(PORT_EVENT, { ports: [port2], cancelable: true });
+ // dispatchEvent returns false when a listener called preventDefault, which
+ // the content script does when it claims the port.
+ if (!host.dispatchEvent(event)) {
+ handed = true;
+ host.removeEventListener(HELLO_EVENT, offer);
+ }
+ };
+
+ host.addEventListener(HELLO_EVENT, offer);
+ onLoaded(host, () => host.removeEventListener(HELLO_EVENT, offer));
+ offer();
+ return port1;
+}
+
+/**
+ * ISOLATED-world half. Claims the first port offered while the document is
+ * still loading and passes it to `onPort`. Call once, at document_start.
+ */
+export function acceptChannel(host: ChannelHost, onPort: (port: MessagePort) => void): void {
+ let claimed = false;
+
+ const claim = (event: Event): void => {
+ if (claimed || !loading(host)) return;
+ const port = (event as MessageEvent).ports?.[0];
+ if (!port) return;
+ claimed = true;
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ host.removeEventListener(PORT_EVENT, claim);
+ onPort(port);
+ };
+
+ host.addEventListener(PORT_EVENT, claim);
+ onLoaded(host, () => host.removeEventListener(PORT_EVENT, claim));
+ // An interceptor that ran first answers this synchronously.
+ host.dispatchEvent(new Event(HELLO_EVENT));
+}
diff --git a/browser-extension/src/shared/types.ts b/browser-extension/src/shared/types.ts
index 67b45408..5f2f784e 100644
--- a/browser-extension/src/shared/types.ts
+++ b/browser-extension/src/shared/types.ts
@@ -79,25 +79,19 @@ export const DEFAULT_SETTINGS: Settings = {
// ---- Messaging between MAIN interceptor → ISOLATED content → service worker ----
-/** Emitted by the MAIN-world interceptor via window.postMessage. */
+/**
+ * Emitted by the MAIN-world interceptor over its private MessagePort (see
+ * src/shared/channel.ts). `reqId` is a random, unguessable id per teed request.
+ */
export type InterceptEvent =
- | { kind: 'request'; reqId: number; url: string; method: string; body: string | null }
- | { kind: 'chunk'; reqId: number; chunk: string }
- | { kind: 'done'; reqId: number }
- | { kind: 'error'; reqId: number; message: string };
-
-export const BEACON_MSG = '__beacon_intercept__' as const;
-
-/** Envelope posted on window by the interceptor. */
-export interface BeaconWindowMessage {
- source: typeof BEACON_MSG;
- event: InterceptEvent;
-}
+ | { kind: 'request'; reqId: string; url: string; method: string; body: string | null }
+ | { kind: 'chunk'; reqId: string; chunk: string }
+ | { kind: 'done'; reqId: string }
+ | { kind: 'error'; reqId: string; message: string };
/** Sent from the content script to the service worker. */
export interface RelayMessage {
type: 'BEACON_RAW';
host: string;
- tabId?: number;
event: InterceptEvent;
}
diff --git a/browser-extension/src/shared/validate.ts b/browser-extension/src/shared/validate.ts
new file mode 100644
index 00000000..ffcab5d3
--- /dev/null
+++ b/browser-extension/src/shared/validate.ts
@@ -0,0 +1,136 @@
+// Shape and size checks for everything that crosses a trust boundary into the
+// service worker: intercept events relayed from a chat-site renderer, and
+// settings patches. Pure, so it is unit-tested without a browser.
+
+import type { InterceptEvent, Retention, Settings, SiteName } from './types.js';
+
+/** Request ids are random (crypto.randomUUID in the interceptor). */
+const REQ_ID = /^[A-Za-z0-9-]{8,64}$/;
+
+export const LIMITS = Object.freeze({
+ url: 8 * 1024,
+ method: 16,
+ /** Request bodies carry the whole conversation on some sites. */
+ body: 8 * 1024 * 1024,
+ chunk: 4 * 1024 * 1024,
+ message: 4 * 1024,
+ host: 253,
+});
+
+function str(v: unknown, max: number): v is string {
+ return typeof v === 'string' && v.length <= max;
+}
+
+/**
+ * Return `raw` as an InterceptEvent when it has exactly the expected shape and
+ * sizes, or null. Unknown kinds, wrong types, oversized strings and malformed
+ * request ids are all rejected. The result is a fresh object holding only the
+ * known fields.
+ */
+export function parseInterceptEvent(raw: unknown): InterceptEvent | null {
+ if (raw == null || typeof raw !== 'object') return null;
+ const e = raw as Record<string, unknown>;
+ if (typeof e.reqId !== 'string' || !REQ_ID.test(e.reqId)) return null;
+ const reqId = e.reqId;
+ switch (e.kind) {
+ case 'request':
+ if (!str(e.url, LIMITS.url) || !str(e.method, LIMITS.method)) return null;
+ if (e.body !== null && !str(e.body, LIMITS.body)) return null;
+ return { kind: 'request', reqId, url: e.url, method: e.method, body: e.body };
+ case 'chunk':
+ if (!str(e.chunk, LIMITS.chunk)) return null;
+ return { kind: 'chunk', reqId, chunk: e.chunk };
+ case 'done':
+ return { kind: 'done', reqId };
+ case 'error':
+ if (!str(e.message, LIMITS.message)) return null;
+ return { kind: 'error', reqId, message: e.message };
+ default:
+ return null;
+ }
+}
+
+/** A plausible host name (with optional port), or null. */
+export function parseHost(raw: unknown): string | null {
+ if (!str(raw, LIMITS.host) || raw === '') return null;
+ return /^[A-Za-z0-9.-]+(:\d{1,5})?$/.test(raw) ? raw : null;
+}
+
+const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']);
+
+/**
+ * The only endpoints the extension may deliver to: http(s) on loopback, with an
+ * explicit port and no credentials. Chat content never leaves the machine from
+ * the browser; anything beyond it is the local collector's job.
+ */
+export function isAllowedEndpoint(raw: unknown): raw is string {
+ if (!str(raw, LIMITS.url)) return false;
+ let u: URL;
+ try {
+ u = new URL(raw);
+ } catch {
+ return false;
+ }
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') return false;
+ if (!LOOPBACK_HOSTS.has(u.hostname)) return false;
+ if (u.port === '') return false;
+ if (u.username !== '' || u.password !== '') return false;
+ return true;
+}
+
+const RETENTIONS: readonly Retention[] = ['metadata', 'redacted', 'full'];
+const SITES: readonly SiteName[] = ['claude_web', 'chatgpt_web'];
+
+export type PatchResult = { ok: true; patch: Partial<Settings> } | { ok: false; error: string };
+
+/**
+ * Validate a settings patch from the popup or options page. Only known keys
+ * with valid values are accepted; anything else rejects the whole patch, so a
+ * bad save changes nothing.
+ */
+export function parseSettingsPatch(raw: unknown): PatchResult {
+ if (raw == null || typeof raw !== 'object' || Array.isArray(raw)) {
+ return { ok: false, error: 'settings patch must be an object' };
+ }
+ const out: Partial<Settings> = {};
+ for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
+ switch (key) {
+ case 'enabled':
+ if (typeof value !== 'boolean') return { ok: false, error: 'enabled must be true or false' };
+ out.enabled = value;
+ break;
+ case 'retention':
+ if (!RETENTIONS.includes(value as Retention)) {
+ return { ok: false, error: `retention must be one of ${RETENTIONS.join(', ')}` };
+ }
+ out.retention = value as Retention;
+ break;
+ case 'endpoint':
+ if (!isAllowedEndpoint(value)) {
+ return {
+ ok: false,
+ error:
+ 'endpoint must be an http(s) URL on 127.0.0.1, localhost or [::1] with a port, such as http://127.0.0.1:4318/v1/logs',
+ };
+ }
+ out.endpoint = value;
+ break;
+ case 'sites': {
+ if (value == null || typeof value !== 'object' || Array.isArray(value)) {
+ return { ok: false, error: 'sites must be an object' };
+ }
+ const sites: Partial<Record<SiteName, boolean>> = {};
+ for (const [site, on] of Object.entries(value as Record<string, unknown>)) {
+ if (!SITES.includes(site as SiteName)) return { ok: false, error: `unknown site ${site}` };
+ if (typeof on !== 'boolean') return { ok: false, error: `sites.${site} must be true or false` };
+ sites[site as SiteName] = on;
+ }
+ out.sites = sites as Record<SiteName, boolean>;
+ break;
+ }
+ default:
+ return { ok: false, error: `unknown setting ${key}` };
+ }
+ }
+ return { ok: true, patch: out };
+}
diff --git a/browser-extension/test/unit/assembler.test.ts b/browser-extension/test/unit/assembler.test.ts
new file mode 100644
index 00000000..5cf11f9c
--- /dev/null
+++ b/browser-extension/test/unit/assembler.test.ts
@@ -0,0 +1,132 @@
+// Bounded turn assembly (src/background/assembler.ts): per-tab and total caps,
+// idle expiry, per-stream byte cap and tab cleanup all finalize or drop open
+// streams, so nothing stays in memory (or keeps the worker awake) forever.
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import '../../src/adapters/claude.js';
+import { Assembler } from '../../src/background/assembler.js';
+import type { InterceptEvent } from '../../src/shared/types.js';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const SSE = readFileSync(path.join(__dirname, '..', '..', 'fixtures', 'claude', 'simple-turn.sse'), 'utf8');
+const CONV = '11111111-2222-3333-4444-555555555555';
+const URL = `/api/organizations/org-x/chat_conversations/${CONV}/completion`;
+const HOST = 'claude.ai';
+
+const id = (n: number) => `req-${String(n).padStart(8, '0')}`;
+const request = (reqId: string): InterceptEvent => ({
+ kind: 'request',
+ reqId,
+ url: URL,
+ method: 'POST',
+ body: JSON.stringify({ prompt: 'hi', conversation_id: CONV }),
+});
+
+function clock(start = 1_000_000) {
+ let t = start;
+ return { now: () => t, advance: (ms: number) => (t += ms) };
+}
+
+describe('Assembler', () => {
+ it('assembles a full turn and forgets it on done', () => {
+ const a = new Assembler();
+ a.handle(HOST, 1, request(id(1)));
+ expect(a.active).toBe(1);
+ a.handle(HOST, 1, { kind: 'chunk', reqId: id(1), chunk: SSE });
+ const turns = a.handle(HOST, 1, { kind: 'done', reqId: id(1) });
+ expect(turns).toHaveLength(1);
+ expect(turns[0].responseText).toBe('Paris.');
+ expect(a.active).toBe(0);
+ });
+
+ it('ignores events for a request id it never registered', () => {
+ const a = new Assembler();
+ expect(a.handle(HOST, 1, { kind: 'done', reqId: id(9) })).toEqual([]);
+ expect(a.handle(HOST, 1, { kind: 'chunk', reqId: id(9), chunk: SSE })).toEqual([]);
+ expect(a.active).toBe(0);
+ });
+
+ it('does not let another tab address a stream', () => {
+ const a = new Assembler();
+ a.handle(HOST, 1, request(id(1)));
+ expect(a.handle(HOST, 2, { kind: 'done', reqId: id(1) })).toEqual([]);
+ expect(a.active).toBe(1);
+ });
+
+ it('does not let a repeated request id replace an open stream', () => {
+ const a = new Assembler();
+ a.handle(HOST, 1, request(id(1)));
+ a.handle(HOST, 1, { kind: 'chunk', reqId: id(1), chunk: SSE });
+ a.handle(HOST, 1, request(id(1)));
+ const [turn] = a.handle(HOST, 1, { kind: 'done', reqId: id(1) });
+ expect(turn.responseText).toBe('Paris.');
+ });
+
+ it('ignores requests for a host with no adapter', () => {
+ const a = new Assembler();
+ a.handle('example.com', 1, request(id(1)));
+ expect(a.active).toBe(0);
+ });
+
+ it('caps open streams per tab, closing the oldest', () => {
+ const a = new Assembler({ maxPerTab: 3 });
+ for (let i = 1; i <= 5; i++) a.handle(HOST, 1, request(id(i)));
+ expect(a.active).toBe(3);
+ // The two oldest were closed; the newest three are still addressable.
+ expect(a.handle(HOST, 1, { kind: 'done', reqId: id(1) })).toEqual([]);
+ expect(a.handle(HOST, 1, { kind: 'done', reqId: id(5) })).toHaveLength(1);
+ // Another tab is unaffected by tab 1's cap.
+ a.handle(HOST, 2, request(id(1)));
+ expect(a.active).toBe(3);
+ });
+
+ it('caps open streams in total', () => {
+ const a = new Assembler({ maxPerTab: 100, maxTotal: 4 });
+ for (let tab = 1; tab <= 10; tab++) a.handle(HOST, tab, request(id(tab)));
+ expect(a.active).toBe(4);
+ });
+
+ it('finalizes a stream that went idle as a partial turn', () => {
+ const c = clock();
+ const a = new Assembler({ maxIdleMs: 60_000 }, c.now);
+ a.handle(HOST, 1, request(id(1)));
+ a.handle(HOST, 1, { kind: 'chunk', reqId: id(1), chunk: SSE.slice(0, SSE.length / 2) });
+ c.advance(30_000);
+ expect(a.sweep()).toEqual([]);
+ c.advance(30_001);
+ const turns = a.sweep();
+ expect(a.active).toBe(0);
+ expect(turns).toHaveLength(1);
+ expect(turns[0].sessionId).toBe(CONV);
+ });
+
+ it('keeps a stream alive while events keep arriving', () => {
+ const c = clock();
+ const a = new Assembler({ maxIdleMs: 60_000 }, c.now);
+ a.handle(HOST, 1, request(id(1)));
+ for (let i = 0; i < 5; i++) {
+ c.advance(50_000);
+ a.handle(HOST, 1, { kind: 'chunk', reqId: id(1), chunk: '' });
+ a.sweep();
+ }
+ expect(a.active).toBe(1);
+ });
+
+ it('closes a stream that buffers more than its byte cap', () => {
+ const a = new Assembler({ maxEntryBytes: 1024 });
+ a.handle(HOST, 1, request(id(1)));
+ a.handle(HOST, 1, { kind: 'chunk', reqId: id(1), chunk: 'x'.repeat(2048) });
+ expect(a.active).toBe(0);
+ });
+
+ it('closes every stream of a removed tab', () => {
+ const a = new Assembler();
+ a.handle(HOST, 1, request(id(1)));
+ a.handle(HOST, 1, request(id(2)));
+ a.handle(HOST, 2, request(id(3)));
+ a.closeTab(1);
+ expect(a.active).toBe(1);
+ });
+});
diff --git a/browser-extension/test/unit/channel.test.ts b/browser-extension/test/unit/channel.test.ts
new file mode 100644
index 00000000..634c868f
--- /dev/null
+++ b/browser-extension/test/unit/channel.test.ts
@@ -0,0 +1,100 @@
+// The private interceptor -> content-script channel (src/shared/channel.ts).
+// A plain EventTarget stands in for the page's window: what matters is the
+// event protocol, which is the same object model in both worlds.
+import { describe, it, expect, vi } from 'vitest';
+import { acceptChannel, offerChannel, HELLO_EVENT, PORT_EVENT, type ChannelHost } from '../../src/shared/channel.js';
+
+function nextMessage(port: MessagePort): Promise<unknown> {
+ return new Promise((resolve) => {
+ port.onmessage = (e) => resolve(e.data);
+ });
+}
+
+function closeAll(...ports: (MessagePort | undefined)[]): void {
+ for (const p of ports) p?.close();
+}
+
+describe('private channel hand-over', () => {
+ it('connects when the interceptor runs first (manifest order)', async () => {
+ const host: ChannelHost = new EventTarget();
+ const mine = offerChannel(host);
+ let theirs: MessagePort | undefined;
+ acceptChannel(host, (p) => (theirs = p));
+ expect(theirs).toBeDefined();
+
+ const got = nextMessage(theirs!);
+ mine.postMessage('{"kind":"done","reqId":"abcdefgh"}');
+ expect(await got).toBe('{"kind":"done","reqId":"abcdefgh"}');
+ closeAll(mine, theirs);
+ });
+
+ it('connects when the content script runs first', async () => {
+ const host: ChannelHost = new EventTarget();
+ let theirs: MessagePort | undefined;
+ acceptChannel(host, (p) => (theirs = p));
+ expect(theirs).toBeUndefined();
+ const mine = offerChannel(host);
+ expect(theirs).toBeDefined();
+
+ const got = nextMessage(theirs!);
+ mine.postMessage('x');
+ expect(await got).toBe('x');
+ closeAll(mine, theirs);
+ });
+
+ it('ignores a port a page script offers after the hand-over', () => {
+ const host: ChannelHost = new EventTarget();
+ const mine = offerChannel(host);
+ const onPort = vi.fn();
+ acceptChannel(host, onPort);
+ expect(onPort).toHaveBeenCalledTimes(1);
+
+ const forged = new MessageChannel();
+ const claimed = !host.dispatchEvent(
+ new MessageEvent(PORT_EVENT, { ports: [forged.port2], cancelable: true }),
+ );
+ expect(claimed).toBe(false);
+ expect(onPort).toHaveBeenCalledTimes(1);
+ closeAll(mine, forged.port1, forged.port2, onPort.mock.calls[0][0]);
+ });
+
+ it('does not hand the port out again to a later hello', () => {
+ const host: ChannelHost = new EventTarget();
+ const mine = offerChannel(host);
+ let theirs: MessagePort | undefined;
+ acceptChannel(host, (p) => (theirs = p));
+
+ // A page script listening for the port and asking for it again gets nothing.
+ const thief = vi.fn();
+ host.addEventListener(PORT_EVENT, thief);
+ host.dispatchEvent(new Event(HELLO_EVENT));
+ expect(thief).not.toHaveBeenCalled();
+ closeAll(mine, theirs);
+ });
+
+ it('refuses a port once the document has finished loading', () => {
+ const doc = { readyState: 'loading', addEventListener: vi.fn() };
+ const host = Object.assign(new EventTarget(), { document: doc }) as ChannelHost;
+ const onPort = vi.fn();
+ acceptChannel(host, onPort);
+ doc.readyState = 'interactive';
+
+ const late = new MessageChannel();
+ host.dispatchEvent(new MessageEvent(PORT_EVENT, { ports: [late.port2], cancelable: true }));
+ expect(onPort).not.toHaveBeenCalled();
+ closeAll(late.port1, late.port2);
+ });
+
+ it('stops listening when DOMContentLoaded fires', () => {
+ const listeners: Record<string, () => void> = {};
+ const doc = {
+ readyState: 'loading',
+ addEventListener: (type: string, fn: () => void) => (listeners[type] = fn),
+ };
+ const host = Object.assign(new EventTarget(), { document: doc }) as ChannelHost;
+ const remove = vi.spyOn(host, 'removeEventListener');
+ acceptChannel(host, () => {});
+ listeners.DOMContentLoaded();
+ expect(remove).toHaveBeenCalledWith(PORT_EVENT, expect.any(Function));
+ });
+});
diff --git a/browser-extension/test/unit/chatgpt.adapter.test.ts b/browser-extension/test/unit/chatgpt.adapter.test.ts
index f2d33079..29965937 100644
--- a/browser-extension/test/unit/chatgpt.adapter.test.ts
+++ b/browser-extension/test/unit/chatgpt.adapter.test.ts
@@ -24,7 +24,7 @@ function reqBody(prompt: string, conversationId: string | null): string {
}
function run(name: string, prompt: string, conversationId: string | null, chunkSize = 7): TurnParser {
- const parser = chatgptAdapter.createParser(1);
+ const parser = chatgptAdapter.createParser('req-0001');
parser.onRequest('https://chatgpt.com/backend-api/f/conversation', 'POST', reqBody(prompt, conversationId));
const body = fixture(name);
for (let i = 0; i < body.length; i += chunkSize) parser.onChunk(body.slice(i, i + chunkSize));
diff --git a/browser-extension/test/unit/claude.adapter.test.ts b/browser-extension/test/unit/claude.adapter.test.ts
index 4eb09947..23872512 100644
--- a/browser-extension/test/unit/claude.adapter.test.ts
+++ b/browser-extension/test/unit/claude.adapter.test.ts
@@ -14,7 +14,7 @@ const URL = `/api/organizations/org-x/chat_conversations/${CONV}/completion`;
/** Feed a body through a fresh parser in tiny, boundary-crossing chunks. */
function run(name: string, prompt: string, chunkSize = 7): TurnParser {
- const parser = claudeAdapter.createParser(1);
+ const parser = claudeAdapter.createParser('req-0001');
parser.onRequest(URL, 'POST', JSON.stringify({ prompt, conversation_id: CONV }));
const body = fixture(name);
for (let i = 0; i < body.length; i += chunkSize) parser.onChunk(body.slice(i, i + chunkSize));
@@ -140,7 +140,7 @@ describe('claude adapter -- one-hour cache writes', () => {
describe('claude adapter -- partial stream usage', () => {
it('reports no output tokens when the stream aborts before message_delta', () => {
- const parser = claudeAdapter.createParser(1);
+ const parser = claudeAdapter.createParser('req-0001');
parser.onRequest(URL, 'POST', JSON.stringify({ prompt: 'hi', conversation_id: CONV }));
const body = fixture('with-usage');
parser.onChunk(body.slice(0, body.indexOf('event: message_delta')));
diff --git a/browser-extension/test/unit/permissions.test.ts b/browser-extension/test/unit/permissions.test.ts
index 680b10e7..bafe4fcd 100644
--- a/browser-extension/test/unit/permissions.test.ts
+++ b/browser-extension/test/unit/permissions.test.ts
@@ -11,9 +11,9 @@ import {
} from '../../src/shared/permissions.js';
const HOSTS = [
- '*://claude.ai/*',
- '*://chatgpt.com/*',
- '*://chat.openai.com/*',
+ 'https://claude.ai/*',
+ 'https://chatgpt.com/*',
+ 'https://chat.openai.com/*',
'http://127.0.0.1/*',
'http://localhost/*',
];
@@ -73,8 +73,8 @@ describe('missingOrigins', () => {
});
it('lists only the withheld hosts, in manifest order', async () => {
- const { api } = fakeApi(['*://claude.ai/*', 'http://127.0.0.1/*']);
- expect(await missingOrigins(api)).toEqual(['*://chatgpt.com/*', '*://chat.openai.com/*', 'http://localhost/*']);
+ const { api } = fakeApi(['https://claude.ai/*', 'http://127.0.0.1/*']);
+ expect(await missingOrigins(api)).toEqual(['https://chatgpt.com/*', 'https://chat.openai.com/*', 'http://localhost/*']);
});
it('treats a failing check as missing rather than hiding a gap', async () => {
@@ -98,7 +98,7 @@ describe('missingOrigins', () => {
describe('describeOrigin', () => {
it('reduces a match pattern to its host', () => {
- expect(describeOrigin('*://claude.ai/*')).toBe('claude.ai');
+ expect(describeOrigin('https://claude.ai/*')).toBe('claude.ai');
expect(describeOrigin('http://127.0.0.1/*')).toBe('127.0.0.1');
expect(describeOrigin('<all_urls>')).toBe('<all_urls>');
});
@@ -115,7 +115,7 @@ describe('mountPermissionBanner', () => {
it('shows the not-granted state naming the missing sites', async () => {
const { doc, els } = fakeDoc();
- mountPermissionBanner(fakeApi(['*://claude.ai/*']).api, doc);
+ mountPermissionBanner(fakeApi(['https://claude.ai/*']).api, doc);
await settle();
expect(els['perm-missing'].hidden).toBe(false);
expect(els['perm-missing'].dataset.state).toBe('missing');
@@ -124,7 +124,7 @@ describe('mountPermissionBanner', () => {
it('requests exactly the missing hosts synchronously on click, then hides once granted', async () => {
const { doc, els } = fakeDoc();
- const { api, request } = fakeApi(['*://claude.ai/*'], { grantOnRequest: true });
+ const { api, request } = fakeApi(['https://claude.ai/*'], { grantOnRequest: true });
mountPermissionBanner(api, doc);
await settle();
els['perm-grant'].click!();
diff --git a/browser-extension/test/unit/sender.test.ts b/browser-extension/test/unit/sender.test.ts
new file mode 100644
index 00000000..09dc8b81
--- /dev/null
+++ b/browser-extension/test/unit/sender.test.ts
@@ -0,0 +1,60 @@
+// Runtime-message sender checks (src/background/sender.ts). Control messages
+// come only from the extension's own pages; content scripts run in the chat
+// site's renderer and must not be able to change settings or trigger a flush.
+import { describe, it, expect } from 'vitest';
+import { isExtensionPage, isOwnContentScript, senderHost } from '../../src/background/sender.js';
+
+const ID = 'abcdefghijklmnopabcdefghijklmnop';
+const BASE = `chrome-extension://${ID}/`;
+
+describe('isExtensionPage', () => {
+ it('accepts the popup (no tab)', () => {
+ expect(isExtensionPage({ id: ID, url: `${BASE}popup.html` }, ID, BASE)).toBe(true);
+ });
+
+ it('accepts the options page open in a tab', () => {
+ expect(isExtensionPage({ id: ID, url: `${BASE}options.html`, tab: { id: 7 } }, ID, BASE)).toBe(true);
+ });
+
+ it('accepts a Firefox moz-extension page', () => {
+ const base = 'moz-extension://0b1c2d3e-4f50-6172-8394-a5b6c7d8e9f0/';
+ expect(isExtensionPage({ id: ID, url: `${base}options.html` }, ID, base)).toBe(true);
+ });
+
+ it.each([
+ ['a content script on claude.ai', { id: ID, url: 'https://claude.ai/chat/x', tab: { id: 3 } }],
+ ['a content script with no url', { id: ID, tab: { id: 3 } }],
+ ['another extension', { id: 'zzzz', url: `${BASE}popup.html` }],
+ ['another extension page origin', { id: ID, url: 'chrome-extension://otherotherotherotherotherother12/popup.html' }],
+ ['no sender id', { url: `${BASE}popup.html` }],
+ ['a malformed url', { id: ID, url: 'not a url' }],
+ ])('refuses %s', (_name, sender) => {
+ expect(isExtensionPage(sender, ID, BASE)).toBe(false);
+ });
+
+ it('refuses everything when the runtime id is unknown', () => {
+ expect(isExtensionPage({ id: '', url: `${BASE}popup.html` }, '', BASE)).toBe(false);
+ });
+});
+
+describe('isOwnContentScript', () => {
+ it('accepts this extension in a tab', () => {
+ expect(isOwnContentScript({ id: ID, url: 'https://claude.ai/', tab: { id: 3 } }, ID)).toBe(true);
+ });
+ it.each([
+ ['no tab', { id: ID, url: 'https://claude.ai/' }],
+ ['another extension', { id: 'other', tab: { id: 3 } }],
+ ])('refuses %s', (_name, sender) => {
+ expect(isOwnContentScript(sender, ID)).toBe(false);
+ });
+});
+
+describe('senderHost', () => {
+ it('reads the host from the browser-reported frame url', () => {
+ expect(senderHost({ url: 'https://chatgpt.com/c/123' })).toBe('chatgpt.com');
+ });
+ it('returns null without a usable url', () => {
+ expect(senderHost({})).toBeNull();
+ expect(senderHost({ url: 'nope' })).toBeNull();
+ });
+});
diff --git a/browser-extension/test/unit/validate.test.ts b/browser-extension/test/unit/validate.test.ts
new file mode 100644
index 00000000..017bf764
--- /dev/null
+++ b/browser-extension/test/unit/validate.test.ts
@@ -0,0 +1,134 @@
+// Trust-boundary checks (src/shared/validate.ts): relayed intercept events,
+// settings patches, and the loopback-only delivery endpoint.
+import { describe, it, expect } from 'vitest';
+import {
+ LIMITS,
+ isAllowedEndpoint,
+ parseHost,
+ parseInterceptEvent,
+ parseSettingsPatch,
+} from '../../src/shared/validate.js';
+import { resolveSettings } from '../../src/background/settings.js';
+import { DEFAULT_SETTINGS } from '../../src/shared/types.js';
+
+const ID = '3f2b8c1e-0a4d-4e7b-9c55-1d2e3f4a5b6c';
+
+describe('parseInterceptEvent', () => {
+ it.each([
+ [{ kind: 'request', reqId: ID, url: 'https://claude.ai/x', method: 'POST', body: '{}' }],
+ [{ kind: 'request', reqId: ID, url: 'https://claude.ai/x', method: 'POST', body: null }],
+ [{ kind: 'chunk', reqId: ID, chunk: 'data: {}\n\n' }],
+ [{ kind: 'done', reqId: ID }],
+ [{ kind: 'error', reqId: ID, message: 'TypeError: network' }],
+ ])('accepts %o', (e) => {
+ expect(parseInterceptEvent(e)).toEqual(e);
+ });
+
+ it('keeps only known fields', () => {
+ expect(parseInterceptEvent({ kind: 'done', reqId: ID, extra: { evil: true } })).toEqual({ kind: 'done', reqId: ID });
+ });
+
+ it.each([
+ ['null', null],
+ ['a string', 'done'],
+ ['an unknown kind', { kind: 'reset', reqId: ID }],
+ ['a numeric (guessable) request id', { kind: 'done', reqId: 1 }],
+ ['a short request id', { kind: 'done', reqId: 'abc' }],
+ ['a request id with odd characters', { kind: 'done', reqId: '../../etc/passwd' }],
+ ['a request with no url', { kind: 'request', reqId: ID, method: 'POST', body: null }],
+ ['a request with an object body', { kind: 'request', reqId: ID, url: 'u', method: 'POST', body: {} }],
+ ['a request with a missing body', { kind: 'request', reqId: ID, url: 'u', method: 'POST' }],
+ ['a non-string chunk', { kind: 'chunk', reqId: ID, chunk: 42 }],
+ ['an oversized chunk', { kind: 'chunk', reqId: ID, chunk: 'x'.repeat(LIMITS.chunk + 1) }],
+ ['an oversized url', { kind: 'request', reqId: ID, url: 'x'.repeat(LIMITS.url + 1), method: 'POST', body: null }],
+ ['an error with no message', { kind: 'error', reqId: ID }],
+ ])('rejects %s', (_name, e) => {
+ expect(parseInterceptEvent(e)).toBeNull();
+ });
+});
+
+describe('parseHost', () => {
+ it('accepts chat hosts', () => {
+ expect(parseHost('claude.ai')).toBe('claude.ai');
+ expect(parseHost('chatgpt.com:443')).toBe('chatgpt.com:443');
+ });
+ it.each(['', 'claude.ai/x', 'a b', 42, null])('rejects %o', (h) => {
+ expect(parseHost(h)).toBeNull();
+ });
+});
+
+describe('isAllowedEndpoint', () => {
+ it.each([
+ 'http://127.0.0.1:4318/v1/logs',
+ 'http://localhost:4318/v1/logs',
+ 'https://127.0.0.1:4318/v1/logs',
+ 'http://[::1]:4318/v1/logs',
+ ])('allows %s', (u) => {
+ expect(isAllowedEndpoint(u)).toBe(true);
+ });
+
+ it.each([
+ ['a remote host', 'https://collector.example.com:4318/v1/logs'],
+ ['no port', 'http://127.0.0.1/v1/logs'],
+ ['a default port spelled out', 'http://127.0.0.1:80/v1/logs'],
+ ['another loopback-looking host', 'http://127.0.0.1.example.com:4318/v1/logs'],
+ ['credentials', 'http://user:[email protected]:4318/v1/logs'],
+ ['a non-http scheme', 'ftp://127.0.0.1:4318/'],
+ ['a javascript URL', 'javascript:alert(1)'],
+ ['a private LAN address', 'http://192.168.1.10:4318/v1/logs'],
+ ['not a URL', 'not a url'],
+ ['a non-string', 4318],
+ ])('refuses %s', (_name, u) => {
+ expect(isAllowedEndpoint(u)).toBe(false);
+ });
+});
+
+describe('parseSettingsPatch', () => {
+ it('accepts every known key with a valid value', () => {
+ const patch = {
+ enabled: false,
+ retention: 'metadata',
+ endpoint: 'http://localhost:4318/v1/logs',
+ sites: { claude_web: false },
+ };
+ expect(parseSettingsPatch(patch)).toEqual({ ok: true, patch });
+ });
+
+ it.each([
+ ['an unknown key', { proxy: 'x' }],
+ ['a non-boolean enabled', { enabled: 'yes' }],
+ ['an unknown retention', { retention: 'everything' }],
+ ['a remote endpoint', { endpoint: 'https://attacker.example/v1/logs' }],
+ ['an unknown site', { sites: { gemini_web: true } }],
+ ['a non-boolean site', { sites: { claude_web: 1 } }],
+ ['a non-object', 'enabled'],
+ ['an array', []],
+ ])('rejects %s and changes nothing', (_name, patch) => {
+ const r = parseSettingsPatch(patch);
+ expect(r.ok).toBe(false);
+ });
+
+ it('rejects the whole patch when one key is bad', () => {
+ expect(parseSettingsPatch({ enabled: false, endpoint: 'https://evil.example:1/' }).ok).toBe(false);
+ });
+});
+
+describe('resolveSettings', () => {
+ it('falls back to defaults for stored values that no longer validate', () => {
+ const s = resolveSettings({
+ enabled: false,
+ retention: 'bogus',
+ endpoint: 'https://remote.example:443/v1/logs',
+ sites: { claude_web: false, chatgpt_web: 'no' },
+ });
+ expect(s).toEqual({
+ ...DEFAULT_SETTINGS,
+ enabled: false,
+ sites: { claude_web: false, chatgpt_web: true },
+ });
+ });
+
+ it('returns defaults for nothing stored', () => {
+ expect(resolveSettings(undefined)).toEqual(DEFAULT_SETTINGS);
+ });
+});
diff --git a/docs/runtimes/browser-extension.mdx b/docs/runtimes/browser-extension.mdx
index f7e9bd51..3b7f109f 100644
--- a/docs/runtimes/browser-extension.mdx
+++ b/docs/runtimes/browser-extension.mdx
@@ -121,7 +121,7 @@ The extension is configured in its own UI, not by `beacon`. There is no CLI comm
| Surface | How to open it | Settings |
|---------|----------------|----------|
| Popup | Click the extension's toolbar icon | Capture on or off, content retention (`full`, `redacted`, `metadata`), plus live queue depth and active stream count |
-| Options page | Right-click the icon and choose **Options**, or use **Details** then **Extension options** in `chrome://extensions` | OTLP logs endpoint, and per-site checkboxes for claude.ai and chatgpt.com |
+| Options page | Right-click the icon and choose **Options**, or use **Details** then **Extension options** in `chrome://extensions` | OTLP logs endpoint (loopback only: `http(s)` on `127.0.0.1`, `localhost` or `[::1]` with a port), and per-site checkboxes for claude.ai and chatgpt.com |
Both sites are enabled by default. Turn one off in the options page to collect from the other alone.