Skip to content

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

browser-extension: managed settings, update feed URL and a CRX signer

shukieshah6a0acc24500a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 40ea6935..4cd75536 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -103,7 +103,7 @@ jobs:
shell: bash
run: |
set -euo pipefail
- for f in manifest.json sw.js content.js interceptor.js \
+ for f in manifest.json managed_schema.json sw.js content.js interceptor.js \
popup.html popup.js options.html options.js; do
test -s "dist/$f" || { echo "missing or empty dist/$f"; exit 1; }
done
@@ -192,6 +192,56 @@ jobs:
if-no-files-found: warn
retention-days: 14
+ # The self-hosted install path: Chrome policy force-installs a CRX signed by
+ # tools/pack-crx.mjs from a local update feed, with every other extension
+ # blocked and the settings locked through managed storage. Branded Google
+ # Chrome, because that is what fleets run and it no longer loads unpacked
+ # extensions from the command line. Linux reads machine policy from /etc with
+ # no device-management check, and the runner's passwordless sudo writes it.
+ browser-extension-policy:
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ env:
+ BROWSER_CHANNEL: chrome
+ POLICY_E2E: "1"
+ steps:
+ - uses: actions/checkout@v7
+ - uses: actions/setup-node@v7
+ with:
+ node-version: 22
+ cache: npm
+ cache-dependency-path: browser-extension/package-lock.json
+
+ - name: Install extension dependencies
+ working-directory: browser-extension
+ run: npm ci
+
+ - name: Build extension
+ working-directory: browser-extension
+ run: npm run build
+
+ # Google Chrome stable from Google's apt repository, plus its system
+ # libraries. It installs outside ~/.cache/ms-playwright, so there is
+ # nothing to cache.
+ - name: Install Google Chrome for Playwright
+ working-directory: browser-extension
+ run: npx playwright install --with-deps chrome
+
+ - name: Policy install e2e
+ working-directory: browser-extension
+ run: npx playwright test e2e/policy-install.spec.ts
+
+ - name: Upload Playwright report and traces
+ if: failure()
+ uses: actions/upload-artifact@v7
+ with:
+ name: browser-extension-policy-playwright-report
+ path: |
+ browser-extension/playwright-report/
+ browser-extension/test-results/
+ if-no-files-found: warn
+ retention-days: 14
+
go-test:
runs-on: macos-latest
steps:
diff --git a/CLAUDE.md b/CLAUDE.md
index 0a3ad686..77a3eb74 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -64,7 +64,7 @@ Supported runtime surfaces today:
- OpenClaw Gateway uses a Beacon-managed plugin directory plus OpenClaw's own diagnostics OTLP guidance (`beacon endpoint integrations openclaw`). The plugin's `before_tool_call` hook is fail-closed, so the handler dispatches synchronously and returns without awaiting. Conversation hooks, including `llm_output`, require `plugins.entries.beacon-endpoint.hooks.allowConversationAccess`; without it, token and agent-message coverage is partial. Beacon reads OpenClaw JSON/JSON5 config for advice but does not rewrite it.
- GitHub Copilot CLI uses MDM/customer-managed OTLP HTTP for live spans and approval-like activity, plus `beacon endpoint copilot sync` to backfill local session records from `~/.copilot/session-state`. Poll events carry assistant text, complete tool results, command/file details, and token usage with `harness.collection_method=poll`, plus the shutdown's session-wide `totalNanoAiu` differenced into `gen_ai.usage.cost_usd` once per shutdown (10^9 nano-AIU = one AI credit = US$0.01), only for sessions started on or after the 2026-06-01 AI-credit cutover (`cli/beacon/internal/copilotsession/cost.go`); approvals still come only from the live OTLP path and are not synthesized from persisted records.
- Runtimes that ride shared hook/OTLP paths without a special contract worth expanding here include Antigravity CLI, Devin CLI, Devin Desktop, Factory Droid, Gemini CLI, Grok Build, Hermes Agent, Qwen Code, and VS Code. Installed hook/endpoint support is governed by `cli/beacon/cmd/endpoint_targets.go` plus the install/status switches in `cli/beacon/cmd/endpoint_hooks.go`; discovery rows live in `cli/beacon/internal/endpoint/harness`.
-- Browser chat telemetry through an optional MV3 extension (`browser-extension/`; Chrome, with a beta Firefox build) covering claude.ai and chatgpt.com. A main-world interceptor tees the streamed response, a per-site adapter parses it into a normalized turn, and the service worker POSTs OTLP GenAI logs to the local collector on `127.0.0.1:4318`; the extension never writes files and never contacts a remote endpoint. `harness.name` resolves to `claude_web` or `chatgpt_web` (already handled by `NormalizeHarnessName` in `pkg/asymptoteobserve/harness.go`, where the browser cases must stay above the generic `claude` rule) and `harness.collection_method` is `otlp`. The one build serves every Chromium browser; each event names the browser it came from in the typed `user_agent.name`/`user_agent.version` fields (OTel semconv, promoted by the exporter so Metadata-only forwarding keeps them), resolved in `browser-extension/src/shared/browser-identity.ts` from UA Client Hints brands, with a UA-string fallback that also names Firefox. Scope is deliberately narrow: only those origins' chat streams, never other tabs or general browsing. Retention defaults to `full`, so prompt and response text is retained by default; this is documented rather than defaulted down, because browser chat telemetry without content has no investigative value. Treat the adapters as experimental, since both sites' stream formats are private and undocumented. Per-browser differences live only in `browser-extension/tools/targets.mjs` (one entry per target, deriving its manifest from `src/manifest.json`; Chrome ships that file verbatim to `dist/`, Firefox gets `dist-firefox/`), and every extension API call goes through the `src/shared/browser.ts` shim (a unit test fails on direct `chrome.*` use). The Firefox Gecko ID `[email protected]` is pinned and must never change.
+- Browser chat telemetry through an optional MV3 extension (`browser-extension/`; Chrome, with a beta Firefox build) covering claude.ai and chatgpt.com. A main-world interceptor tees the streamed response, a per-site adapter parses it into a normalized turn, and the service worker POSTs OTLP GenAI logs to the local collector on `127.0.0.1:4318`; the extension never writes files and never contacts a remote endpoint. `harness.name` resolves to `claude_web` or `chatgpt_web` (already handled by `NormalizeHarnessName` in `pkg/asymptoteobserve/harness.go`, where the browser cases must stay above the generic `claude` rule) and `harness.collection_method` is `otlp`. The one build serves every Chromium browser; each event names the browser it came from in the typed `user_agent.name`/`user_agent.version` fields (OTel semconv, promoted by the exporter so Metadata-only forwarding keeps them), resolved in `browser-extension/src/shared/browser-identity.ts` from UA Client Hints brands, with a UA-string fallback that also names Firefox. Scope is deliberately narrow: only those origins' chat streams, never other tabs or general browsing. Retention defaults to `full`, so prompt and response text is retained by default; this is documented rather than defaulted down, because browser chat telemetry without content has no investigative value. Treat the adapters as experimental, since both sites' stream formats are private and undocumented. Per-browser differences live only in `browser-extension/tools/targets.mjs` (one entry per target, deriving its manifest from `src/manifest.json`; Chrome ships that file verbatim to `dist/`, Firefox gets `dist-firefox/`), and every extension API call goes through the `src/shared/browser.ts` shim (a unit test fails on direct `chrome.*` use). The Firefox Gecko ID `[email protected]` is pinned and must never change. Managed fleets install a signed, self-hosted Chrome build instead of the unpacked zip: Chrome policy (`ExtensionSettings` `force_installed`) installs the CRX from the `update_url` feed (`CHROME_UPDATE_URL` in `tools/targets.mjs`, also the manifest's `update_url`, dropped from the Firefox manifest), and the pinned `CHROME_EXTENSION_ID` there, derived from the CRX signing key, must never change either, because every fleet's policy names it. `tools/pack-crx.mjs` signs CRX3 files and writes the feed with `node:crypto` only, so the signing job runs it without `npm ci`. Admins lock settings through Chrome managed storage (`src/managed_schema.json`): `getSettingsState` in `src/background/settings.ts` lays those values over the stored ones on every read, each held to `parseSettingsPatch`, never writes them to `storage.local`, and reports them as `locked`, which the popup and options page show disabled and `SET_SETTINGS` refuses to change.
- `beaconjson` OpenTelemetry Collector exporter that converts OTLP logs, traces, metrics, and resource attributes into Beacon endpoint JSONL.
- OTLP forward (`beacon endpoint install|repair --otlp-forward-endpoint`, `--otlp-forward-protocol grpc|http/protobuf`, `--otlp-forward-harness`, repeatable `--otlp-forward-header`, `--no-otlp-forward`; `config.json` `destinations.otlp_forward`): for machines whose runtimes already exported OTLP to another backend before Beacon pointed them at its collector. The collector renders an `otlp/forward` or `otlphttp/forward` exporter (both in `collector-builder/builder.yaml`) on `logs/forward`, `traces/forward` and `metrics/forward` pipelines fed by the same receiver: `memory_limiter`, `beacon_forward_filter` (`forwardfilterprocessor`; keeps only resources whose harness, resolved like beaconjson resolves it, is listed, default Claude Code and Codex, so browser-extension chats and other runtimes never leave), `claude_api_body` on logs, `beacon_privacy`, `batch`. The exporter's queue and retries are bounded so a down backend sheds data instead of pushing `memory_limiter` into refusing Beacon's own pipelines. It is a customer-chosen destination like the HEC exporters, not a Beacon network channel, and carries no hook or session-store data. Install and repair carry it over (`buildConfig`) until `--no-otlp-forward` removes it. Header values never go in `config.json` (ordinary accounts read the system one to find the system log): they live in `OTLPForwardSecretsPath` (`otlp-forward-headers.json`, 0600) and the 0600 collector config, `config.json` keeps `header_names`, and status, doctor and `config show` show names only. Guide: `docs/guides/kandji-otlp-forward-mdm.mdx`.
- Managed Microsoft Sentinel forwarder (`beacon endpoint sentinel forwarder install|status|remove --system`, hidden `reconcile`; `cli/beacon/internal/endpoint/sentinel/forwarder.go`, `cli/beacon/cmd/endpoint_sentinel_forwarder.go`; docs in `docs/log-forwarding/microsoft-sentinel.mdx#vector-and-the-logs-ingestion-api` and `docs/cli/sentinel.mdx`): the bundled Vector (the MSI ships `vector.exe` beside `beacon.exe`, checked against the pinned `packaging/vector/` checksums by `packaging/windows/fetch-vector.ps1`) run as a system service (`BeaconSentinelForwarder`, `beacon-sentinel-forwarder.service`, `com.beacon.endpoint.sentinel-forwarder`) through `service.ForwarderManager` with a `ForwarderSpec`; the Asymptote forwarder's spec is the zero value, byte-identical units, and has no Windows service, so `connect` stays refused there. System mode only. Its state is `<SystemBaseDir>/forwarders/sentinel/` (`forwarder.json` non-secret settings, `secrets.json` read by Vector's `file` secret backend, optional `client.pfx`, `vector.toml` with literal values, `data/` checkpoints, `logs/vector-<date>.log` warnings), `sysacl.SecureSecretDir`/`WriteSecretFile` (root-only 0700/0600 on POSIX), apart from `config.json` so repair never touches it. The credential is never a flag value (env or stdin). Install validates a scratch copy with Vector before writing anything, so a rejected install leaves the old forwarder. The config (`pack/vector.toml.tmpl`, shared with the manual env-var pack via `manualVectorConfig`) reads `runtime.jsonl` and `.1` with the default checksum fingerprint, acknowledgements on, a custom `retry_strategy` (401/403/408/429/5xx, unlimited), 512 KB batches. Vector recognizes a file by its first line, so after the log is replaced with a copy (the log-access switch) it keeps reading the old file until restarted: `lifecycle.Install` therefore reconciles with `Restart` on every install, repair and package upgrade (the macOS postinstall runs the hidden `reconcile`), which is also how the MSI upgrade re-registers the service its uninstall step removed. `lifecycle.Uninstall` always removes the service (so `vector.exe` can be replaced) and keeps the state under `KeepConfig`; repair keeps it running (`KeepForwarders`). `AZURE_AUTHORITY_HOST` (`--authority-host`) goes into the service environment. `sentinelmock` (and `cmd/sentinel-mock`) stands in for Entra ID and the Logs Ingestion API; `TestForwarderConfigDeliversThroughRealVector` runs real Vector against it in `linux-test` and `windows-test` (`BEACON_TEST_VECTOR_BIN`, `BEACON_TEST_SENTINEL_TRUST_STORE=1` on Windows), and `packaging/windows/smoke-sentinel-forwarder.ps1` drives the installed MSI through setup, upgrade, log-access switches and uninstall in `windows-package-smoke`.
@@ -609,6 +609,7 @@ unpacked through Chrome's developer mode.
- `linux-test` (ubuntu) and `windows-test` (windows-2025) rerun the Go suites per platform. The Windows job tests a measured package list rather than `./...`; the excluded packages are tracked in #318, and the scope must not be widened back to `./...`.
- `typescript-sdk` (Node 20, 22, 24): `npm test`, `npm run check`, `npm run build`, `npm run pack:dry-run`, `npm run pack:smoke` in `packages/asymptote-sdk-js`.
- `browser-extension` (Node 22, matrix over `chromium` and `msedge`): `npm run check`, `npm run test:unit`, `npm run build`, a check that the build is a loadable MV3 extension, `npm run lint:firefox` (the Firefox build plus `addons-linter --warnings-as-errors`), and the Playwright replay e2e running the real extension headless in that leg's browser (`BROWSER_CHANNEL`) against a local HTTPS replay server; the HTML report and traces upload on failure. Brave, Opera, Vivaldi and Arc have no Playwright channel; `BROWSER_EXECUTABLE` runs the same e2e against their binaries for the manual checklist in `docs/runtimes/browser-extension-chromium.mdx`.
+- `browser-extension-policy` (ubuntu, Google Chrome): `e2e/policy-install.spec.ts` with `POLICY_E2E=1`. It signs `dist/` with a throwaway key, serves the CRX and `updates.xml` from a local feed, writes Chrome machine policy under `/etc/opt/chrome/policies/managed` with sudo (a `*` blocklist, a force-install of the test ID with `override_update_url`, and managed values), then checks the install, the locked popup, a replayed chat arriving with metadata only at the locked endpoint, and an update to the next version. Linux is the only platform where Chrome honors an off-store force-install without a managed device, which is why it runs there.
- `lens-e2e` (ubuntu): runs the real dashboard handler with hostile fixture lenses and the full `rules/` corpus installed (`cli/beacon/internal/endpoint/dashboard/e2eserver`, `testdata/lens-e2e`) and drives the session page in headless Chromium. Every escape from the lens sandbox must be refused, and a lens that throws, stalls or navigates must give way to the full session.
- `beacon-sandbox` (ubuntu): `go build`, `go vet`, and `go test` for the verification harness. Hermetic — no Modal account, no API key, no paid resources.
- `terraform` (ubuntu): `terraform fmt -check`, `validate`, and `terraform test` (mocked providers) for every module under `terraform/`, and `validate` for each example.
diff --git a/browser-extension/e2e/policy-install.spec.ts b/browser-extension/e2e/policy-install.spec.ts
new file mode 100644
index 00000000..9b341668
--- /dev/null
+++ b/browser-extension/e2e/policy-install.spec.ts
@@ -0,0 +1,272 @@
+// Installs the signed CRX the way a managed fleet does. Chrome policy force-installs it from a
+// self-hosted update feed while every other extension is blocked, and pushes managed settings that
+// lock retention and the collector endpoint. A replayed chat must then reach the collector without
+// content, and a newer version on the feed must replace the installed one.
+//
+// Linux only, opt-in: Chrome reads machine policy from /etc/opt/chrome/policies/managed there with
+// no device-management check (on Windows and macOS an off-store force-install needs a managed
+// machine), and writing it needs root or passwordless sudo. CI sets POLICY_E2E=1.
+
+import { test, expect, chromium, type BrowserContext, type Page } from '@playwright/test';
+import crypto from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import http from 'node:http';
+import type { AddressInfo } from 'node:net';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { feedXml, packCrx } from '../tools/pack-crx.mjs';
+import { resolveBrowserTarget } from './browser-target.js';
+import { startMockCollector, type MockCollector } from './helpers/mock-collector.js';
+import { startReplayServer, type ReplayServer } from './helpers/sse-replay-server.js';
+import { flatAttrs, recordByAction } from './helpers/otlp-assertions.js';
+
+const enabled = process.platform === 'linux' && process.env.POLICY_E2E === '1';
+test.skip(!enabled, 'needs Linux and POLICY_E2E=1: it writes Chrome machine policy under /etc');
+
+const dist = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'dist');
+// Chrome, Chromium and Chrome for Testing each read their own directory. Writing all three lets
+// the spec run in whichever BROWSER_CHANNEL is set; CI runs it in branded Chrome.
+const POLICY_DIRS = [
+ '/etc/opt/chrome/policies/managed',
+ '/etc/chromium/policies/managed',
+ '/etc/opt/chrome_for_testing/policies/managed',
+];
+const POLICY_FILE = 'beacon-e2e.json';
+const CONV = '11111111-2222-3333-4444-555555555555';
+
+const asRoot = process.getuid?.() === 0;
+function writeAsRoot(file: string, content: string): void {
+ if (asRoot) {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, content);
+ return;
+ }
+ execFileSync('sudo', ['mkdir', '-p', path.dirname(file)]);
+ execFileSync('sudo', ['tee', file], { input: content, stdio: ['pipe', 'ignore', 'inherit'] });
+}
+function removeAsRoot(file: string): void {
+ if (asRoot) rmSync(file, { force: true });
+ else execFileSync('sudo', ['rm', '-f', file]);
+}
+
+/** dist/ as the release workflow packages it (no sourcemaps), at `version`, signed with `key`. */
+function signedBuild(work: string, version: string, key: string): { crx: Buffer; id: string } {
+ const dir = path.join(work, `ext-${version}`);
+ cpSync(dist, dir, { recursive: true, filter: (src) => !src.endsWith('.map') });
+ const manifestPath = path.join(dir, 'manifest.json');
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
+ manifest.version = version;
+ writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
+ const zip = path.join(work, `ext-${version}.zip`);
+ execFileSync('zip', ['-q', '-r', '-X', zip, '.'], { cwd: dir });
+ return packCrx(readFileSync(zip), key);
+}
+
+interface Feed {
+ url: string;
+ requests: string[];
+ offer(version: string): void;
+ close(): Promise<void>;
+}
+
+/** A self-hosted update server: updates.xml for the offered version, and the CRX files. */
+async function startFeed(id: string, crxs: Map<string, Buffer>): Promise<Feed> {
+ let offered = '';
+ const requests: string[] = [];
+ const server = http.createServer((req, res) => {
+ const pathname = new URL(req.url ?? '/', 'http://feed').pathname;
+ requests.push(pathname);
+ if (pathname === '/updates.xml') {
+ const crx = crxs.get(offered)!;
+ const sha256 = crypto.createHash('sha256').update(crx).digest('hex');
+ res.writeHead(200, { 'content-type': 'application/xml' });
+ res.end(feedXml({ id, version: offered, codebase: `${base}/ext-${offered}.crx`, sha256 }));
+ return;
+ }
+ const crx = crxs.get(/^\/ext-([\d.]+)\.crx$/.exec(pathname)?.[1] ?? '');
+ if (crx) {
+ res.writeHead(200, { 'content-type': 'application/x-chrome-extension' });
+ res.end(crx);
+ return;
+ }
+ res.writeHead(404).end();
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+ return {
+ url: `${base}/updates.xml`,
+ requests,
+ offer: (version) => (offered = version),
+ close: () => new Promise<void>((resolve) => server.close(() => resolve())),
+ };
+}
+
+/**
+ * The installed extension's popup, once Chrome runs `version` (any version when omitted).
+ *
+ * Driven through an extension page rather than the service worker: Playwright does not report the
+ * worker of an extension that policy installs after launch. The page has the same chrome.runtime
+ * and chrome.storage APIs.
+ */
+async function extensionPage(context: BrowserContext, id: string, version?: string): Promise<Page> {
+ const deadline = Date.now() + 120_000;
+ let last = 'no attempt';
+ while (Date.now() < deadline) {
+ // A fresh page per attempt: Chrome closes the extension's tabs when it installs or reloads it.
+ const page = await context.newPage();
+ try {
+ await page.goto(`chrome-extension://${id}/popup.html`);
+ const running = await page.evaluate(() => chrome.runtime.getManifest().version);
+ if (!version || running === version) return page;
+ last = `running ${running}`;
+ } catch (err) {
+ last = err instanceof Error ? err.message.split('\n')[0] : String(err);
+ }
+ await page.close().catch(() => undefined);
+ await new Promise((resolve) => setTimeout(resolve, 2_000));
+ }
+ // Chrome's own record of the install: an off-store CRX it refused shows up here with the reason.
+ const page = await context.newPage();
+ await page.goto('chrome://extensions-internals').catch(() => undefined);
+ const internals = (await page.locator('body').textContent().catch(() => '')) ?? '';
+ throw new Error(
+ `extension ${id}${version ? ` ${version}` : ''} never ran (last attempt: ${last}); extensions-internals: ${internals.slice(0, 4000)}`,
+ );
+}
+
+let work: string;
+let feed: Feed;
+let collector: MockCollector;
+let replay: ReplayServer;
+let context: BrowserContext;
+let id: string;
+let nextVersion: string;
+
+test.beforeAll(async () => {
+ test.setTimeout(180_000);
+ work = mkdtempSync(path.join(tmpdir(), 'beacon-policy-e2e-'));
+ // A throwaway signing key: the ID it gives stands in for the pinned production one.
+ const key = crypto.generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();
+ const version = JSON.parse(readFileSync(path.join(dist, 'manifest.json'), 'utf8')).version as string;
+ nextVersion = version.replace(/\d+$/, (n) => String(Number(n) + 1));
+ const current = signedBuild(work, version, key);
+ const next = signedBuild(work, nextVersion, key);
+ id = current.id;
+ feed = await startFeed(id, new Map([[version, current.crx], [nextVersion, next.crx]]));
+ feed.offer(version);
+ collector = await startMockCollector();
+ replay = await startReplayServer();
+
+ // What an admin pushes: block every extension, force-install ours from the feed, and lock its
+ // settings. override_update_url makes Chrome keep polling this feed rather than the manifest's
+ // update_url, which is how a fleet that mirrors the files internally stays on its mirror.
+ const policy = {
+ // Test-only. Chrome's default keeps DevTools, and so Playwright, off extensions installed by
+ // policy: their pages detach as soon as the test opens them.
+ DeveloperToolsAvailability: 1,
+ ExtensionSettings: {
+ '*': { installation_mode: 'blocked' },
+ [id]: { installation_mode: 'force_installed', update_url: feed.url, override_update_url: true },
+ },
+ '3rdparty': { extensions: { [id]: { enabled: true, retention: 'metadata', endpoint: collector.url } } },
+ };
+ for (const dir of POLICY_DIRS) writeAsRoot(path.join(dir, POLICY_FILE), JSON.stringify(policy, null, 2));
+
+ const map = ['claude.ai', 'chatgpt.com', 'chat.openai.com']
+ .map((host) => `MAP ${host}:443 127.0.0.1:${replay.port}`)
+ .join(', ');
+ context = await chromium.launchPersistentContext(path.join(work, 'profile'), {
+ ...resolveBrowserTarget(process.env).launch,
+ headless: process.env.HEADED !== '1',
+ ignoreHTTPSErrors: true,
+ // Playwright turns off extensions and the background networking the extension updater runs
+ // on; a policy install needs both.
+ ignoreDefaultArgs: ['--disable-extensions', '--disable-background-networking', '--disable-component-extensions-with-background-pages'],
+ args: [`--host-resolver-rules=${map}`, '--ignore-certificate-errors'],
+ });
+});
+
+test.afterAll(async () => {
+ await context?.close();
+ for (const dir of POLICY_DIRS) removeAsRoot(path.join(dir, POLICY_FILE));
+ await Promise.all([feed?.close(), collector?.close(), replay?.close()]);
+ if (work) rmSync(work, { recursive: true, force: true });
+});
+
+test('a managed fleet force-installs the signed build, locks its settings and updates it', async () => {
+ test.setTimeout(300_000);
+
+ await test.step('Chrome installs the signed CRX from the self-hosted feed', async () => {
+ const page = await extensionPage(context, id).catch((err) => {
+ throw new Error(`${err.message}; feed requests: ${JSON.stringify(feed.requests)}`);
+ });
+ expect(feed.requests).toEqual(expect.arrayContaining(['/updates.xml', expect.stringMatching(/\.crx$/)]));
+ await page.close();
+ });
+
+ await test.step('policy values reach managed storage and lock the popup', async () => {
+ // Chrome delivers an extension's policy once it has registered the extension's schema, a
+ // moment after the install, and the extension's open pages may not survive that; each read
+ // opens a fresh page.
+ const managed = async () => {
+ const page = await extensionPage(context, id);
+ try {
+ return await page.evaluate(() => chrome.storage.managed.get(null));
+ } finally {
+ await page.close().catch(() => undefined);
+ }
+ };
+ await expect
+ .poll(managed, { timeout: 30_000 })
+ .toEqual({ enabled: true, retention: 'metadata', endpoint: collector.url });
+ const popup = await extensionPage(context, id);
+ await expect(popup.locator('[data-testid="managed"]')).toBeVisible();
+ await expect(popup.locator('#retention')).toHaveValue('metadata');
+ await expect(popup.locator('#retention')).toBeDisabled();
+ await expect(popup.locator('#enabled')).toBeDisabled();
+ await expect(popup.locator('[data-testid="endpoint"]')).toHaveText(collector.url);
+ await popup.close();
+ });
+
+ await test.step('a chat reaches the locked endpoint with metadata only', async () => {
+ replay.setCase({
+ site: 'claude',
+ name: 'simple-turn',
+ conversationId: CONV,
+ prompt: 'What is the capital of France?',
+ completionPath: '/api/organizations/org-test/chat_conversations/{conv}/completion',
+ });
+ const page = await context.newPage();
+ await page.goto('https://claude.ai/chat');
+ await expect(page.locator('[data-testid="assistant-message"]')).toHaveAttribute('data-complete', '1');
+ await expect.poll(() => collector.received.length, { timeout: 15_000 }).toBeGreaterThan(0);
+ await page.close();
+
+ // Metadata retention drops the prompt record and every text field; the response record keeps
+ // its counts.
+ expect(recordByAction(collector.received, 'prompt.submitted')).toBeUndefined();
+ const response = recordByAction(collector.received, 'agent.response.completed');
+ expect(response, 'a completed-response record should have been delivered').toBeTruthy();
+ const attrs = flatAttrs(response!.attributes);
+ expect(attrs['beacon.content.retention']).toBe('metadata');
+ expect(attrs['gen_ai.output.messages']).toBeUndefined();
+ expect(attrs['beacon.response.chars']).toBe('Paris.'.length);
+ });
+
+ await test.step('a newer version on the feed replaces the installed one', async () => {
+ feed.offer(nextVersion);
+ const page = await extensionPage(context, id);
+ // Chrome holds a downloaded update until the extension is idle. Reloading as soon as it is
+ // ready applies it now instead of whenever this test's pages let the extension go idle.
+ const status = await page.evaluate(() => {
+ chrome.runtime.onUpdateAvailable.addListener(() => chrome.runtime.reload());
+ return chrome.runtime.requestUpdateCheck();
+ });
+ expect(status).toMatchObject({ status: 'update_available', version: nextVersion });
+ const updated = await extensionPage(context, id, nextVersion);
+ expect(await updated.evaluate(() => chrome.storage.managed.get(null))).toMatchObject({ retention: 'metadata' });
+ expect(feed.requests).toContain(`/ext-${nextVersion}.crx`);
+ });
+});
diff --git a/browser-extension/esbuild.config.mjs b/browser-extension/esbuild.config.mjs
index 09a41d86..50534dcf 100644
--- a/browser-extension/esbuild.config.mjs
+++ b/browser-extension/esbuild.config.mjs
@@ -52,6 +52,8 @@ async function writeManifest() {
/** Copy static assets (manifest, html, icons) into the output directory. */
async function copyStatic() {
await writeManifest();
+ // Named by the manifest's storage.managed_schema: the settings an admin can lock through policy.
+ await cp(path.join(src, 'managed_schema.json'), path.join(dist, 'managed_schema.json'));
for (const surface of ['popup', 'options']) {
await cp(path.join(src, surface, `${surface}.html`), path.join(dist, `${surface}.html`));
}
@@ -85,7 +87,7 @@ async function run() {
let staticRefresh = Promise.resolve();
watchFiles(src, { recursive: true }, (_event, filename) => {
const name = filename?.replaceAll('\\', '/');
- if (name && name !== 'manifest.json' && name !== 'popup/popup.html' &&
+ if (name && name !== 'manifest.json' && name !== 'managed_schema.json' && name !== 'popup/popup.html' &&
name !== 'options/options.html' && name !== 'icons' && !name.startsWith('icons/')) return;
staticRefresh = staticRefresh.then(async () => {
await copyStatic();
diff --git a/browser-extension/package-lock.json b/browser-extension/package-lock.json
index 42b64902..a276c300 100644
--- a/browser-extension/package-lock.json
+++ b/browser-extension/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "agent-beacon-browser-extension",
- "version": "0.1.1",
+ "version": "0.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "agent-beacon-browser-extension",
- "version": "0.1.1",
+ "version": "0.2.0",
"devDependencies": {
"@playwright/test": "^1.55.0",
"@types/chrome": "^0.0.270",
diff --git a/browser-extension/package.json b/browser-extension/package.json
index bba5ad79..ee0b4863 100644
--- a/browser-extension/package.json
+++ b/browser-extension/package.json
@@ -1,6 +1,6 @@
{
"name": "agent-beacon-browser-extension",
- "version": "0.1.1",
+ "version": "0.2.0",
"private": true,
"type": "module",
"description": "Chrome and Firefox extension that relays LLM chat telemetry (ChatGPT, Claude) into the local Agent Beacon pipeline, with a fully automated self-verifying build/test loop.",
diff --git a/browser-extension/src/background/settings.ts b/browser-extension/src/background/settings.ts
index 537161da..f1d020c4 100644
--- a/browser-extension/src/background/settings.ts
+++ b/browser-extension/src/background/settings.ts
@@ -1,15 +1,27 @@
// Storage-backed settings with defaults. Lives in chrome.storage.local so it
// survives service-worker suspension.
+//
+// An administrator can also fix settings through Chrome policy, which Chrome
+// delivers in chrome.storage.managed (keys and types in src/managed_schema.json).
+// Managed values win over stored ones every time settings are read, so a lock
+// holds even if something writes storage.local directly; refusing to change a
+// locked setting from the popup or options page is only how the UI says so.
import { ext } from '../shared/browser.js';
import { serial } from '../shared/serial.js';
-import { DEFAULT_SETTINGS, type Settings, type SiteName } from '../shared/types.js';
+import { DEFAULT_SETTINGS, type LockedSetting, type Settings, type SiteName } from '../shared/types.js';
import { parseSettingsPatch } from '../shared/validate.js';
const KEY = 'settings';
// Concurrent popup and options patches must merge over the preceding write, not a stale snapshot.
const withSettingsLock = serial();
+/** Effective settings plus the ones policy fixed. */
+export interface SettingsState {
+ settings: Settings;
+ locked: LockedSetting[];
+}
+
/**
* 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
@@ -31,25 +43,87 @@ export function resolveSettings(stored: unknown): Settings {
return out;
}
+/**
+ * Read policy values with the same checks a stored value gets. Chrome already
+ * drops values that do not match the schema; this also holds managed values to
+ * the loopback endpoint rule. A value that fails is ignored on its own and
+ * locks nothing.
+ */
+export function resolveManaged(raw: unknown): { patch: Partial<Settings>; locked: LockedSetting[] } {
+ const m = (raw ?? {}) as Record<string, unknown>;
+ const patch: Partial<Settings> = {};
+ const locked: LockedSetting[] = [];
+ for (const key of ['enabled', 'retention', 'endpoint'] as const) {
+ if (!(key in m)) continue;
+ const r = parseSettingsPatch({ [key]: m[key] });
+ if (!r.ok) continue;
+ Object.assign(patch, r.patch);
+ locked.push(key);
+ }
+ const sites = m.sites;
+ if (sites && typeof sites === 'object' && !Array.isArray(sites)) {
+ for (const site of Object.keys(DEFAULT_SETTINGS.sites) as SiteName[]) {
+ const on = (sites as Record<string, unknown>)[site];
+ if (typeof on !== 'boolean') continue;
+ patch.sites = { ...(patch.sites ?? {}), [site]: on } as Settings['sites'];
+ locked.push(`sites.${site}`);
+ }
+ }
+ return { patch, locked };
+}
+
+/** The first setting in `patch` that policy has locked, if any. */
+export function lockedIn(patch: Partial<Settings>, locked: readonly LockedSetting[]): LockedSetting | undefined {
+ return locked.find((key) => {
+ if (!key.startsWith('sites.')) return key in patch;
+ return patch.sites != null && key.slice('sites.'.length) in patch.sites;
+ });
+}
+
+export async function getSettingsState(): Promise<SettingsState> {
+ const [stored, managed] = await Promise.all([getStoredSettings(), readManaged()]);
+ const { patch, locked } = resolveManaged(managed);
+ return { settings: merge(stored, patch), locked };
+}
+
export async function getSettings(): Promise<Settings> {
- const got = await ext.storage.local.get(KEY);
- return resolveSettings(got[KEY]);
+ return (await getSettingsState()).settings;
}
-/** Apply an already-validated patch (see parseSettingsPatch). */
+/**
+ * Apply an already-validated patch (see parseSettingsPatch) to the stored
+ * settings and return the effective ones. Policy values are never written to
+ * storage.local, so removing a policy brings back what the user had chosen.
+ */
export function saveSettings(patch: Partial<Settings>): Promise<Settings> {
return withSettingsLock(async () => {
- const current = await getSettings();
- const next: Settings = {
- ...current,
- ...patch,
- sites: { ...current.sites, ...(patch.sites ?? {}) },
- };
+ const [current, managed] = await Promise.all([getStoredSettings(), readManaged()]);
+ const next = merge(current, patch);
await ext.storage.local.set({ [KEY]: next });
- return next;
+ return merge(next, resolveManaged(managed).patch);
});
}
export function siteEnabled(settings: Settings, site: SiteName): boolean {
return settings.enabled && settings.sites[site] !== false;
}
+
+async function getStoredSettings(): Promise<Settings> {
+ const got = await ext.storage.local.get(KEY);
+ return resolveSettings(got[KEY]);
+}
+
+// Managed storage is absent where nothing manages the browser: Firefox rejects
+// the read without an enterprise policy, and test doubles have no managed area.
+// Both mean no policy values.
+async function readManaged(): Promise<unknown> {
+ try {
+ return await ext.storage.managed?.get(null);
+ } catch {
+ return undefined;
+ }
+}
+
+function merge(base: Settings, patch: Partial<Settings>): Settings {
+ return { ...base, ...patch, sites: { ...base.sites, ...(patch.sites ?? {}) } };
+}
diff --git a/browser-extension/src/background/sw.ts b/browser-extension/src/background/sw.ts
index 9b439d52..178a0f1f 100644
--- a/browser-extension/src/background/sw.ts
+++ b/browser-extension/src/background/sw.ts
@@ -5,7 +5,7 @@ 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 } from '../shared/types.js';
-import { getSettings, saveSettings, siteEnabled } from './settings.js';
+import { getSettings, getSettingsState, lockedIn, saveSettings, siteEnabled } from './settings.js';
import { Assembler } from './assembler.js';
import { enqueueTurn, flush, installFlushAlarm } from './delivery.js';
import { detectBrowser } from '../shared/browser-identity.js';
@@ -99,14 +99,17 @@ function isControlType(type: unknown): type is ControlMessage['type'] {
async function handleControl(msg: ControlMessage): Promise<unknown> {
switch (msg.type) {
case 'GET_STATUS': {
- const settings = await getSettings();
+ const { settings, locked } = await getSettingsState();
const q = await ext.storage.local.get('delivery_queue');
- return { settings, queueDepth: (q.delivery_queue ?? []).length, active: assembler.active };
+ return { settings, locked, queueDepth: (q.delivery_queue ?? []).length, active: assembler.active };
}
case 'SET_SETTINGS': {
const parsed = parseSettingsPatch(msg.patch);
- if (!parsed.ok) return { error: parsed.error, settings: await getSettings() };
- return { settings: await saveSettings(parsed.patch) };
+ const state = await getSettingsState();
+ if (!parsed.ok) return { error: parsed.error, ...state };
+ const locked = lockedIn(parsed.patch, state.locked);
+ if (locked) return { error: `${locked} is set by your organization and cannot be changed here`, ...state };
+ return { settings: await saveSettings(parsed.patch), locked: state.locked };
}
case 'FLUSH_NOW':
await flush();
diff --git a/browser-extension/src/managed_schema.json b/browser-extension/src/managed_schema.json
new file mode 100644
index 00000000..70b04583
--- /dev/null
+++ b/browser-extension/src/managed_schema.json
@@ -0,0 +1,30 @@
+{
+ "type": "object",
+ "properties": {
+ "enabled": {
+ "title": "Capture enabled",
+ "description": "Whether the extension captures chats at all. Locks the popup's Capture enabled switch.",
+ "type": "boolean"
+ },
+ "retention": {
+ "title": "Content retention",
+ "description": "How much chat content is kept: full text, redacted text, or metadata only.",
+ "type": "string",
+ "enum": ["full", "redacted", "metadata"]
+ },
+ "endpoint": {
+ "title": "Collector endpoint",
+ "description": "OTLP logs URL of the local Beacon collector. Must be on 127.0.0.1, localhost or [::1].",
+ "type": "string"
+ },
+ "sites": {
+ "title": "Sites",
+ "description": "Per-site capture switches.",
+ "type": "object",
+ "properties": {
+ "claude_web": { "title": "claude.ai", "type": "boolean" },
+ "chatgpt_web": { "title": "chatgpt.com", "type": "boolean" }
+ }
+ }
+ }
+}
diff --git a/browser-extension/src/manifest.json b/browser-extension/src/manifest.json
index 9d0f0c70..60c8ecf9 100644
--- a/browser-extension/src/manifest.json
+++ b/browser-extension/src/manifest.json
@@ -1,8 +1,9 @@
{
"manifest_version": 3,
"name": "Agent Beacon — Browser Collector",
- "version": "0.1.1",
+ "version": "0.2.0",
"description": "Relays LLM chat telemetry (Claude, ChatGPT) into the local Agent Beacon pipeline.",
+ "update_url": "https://github.com/Asymptote-Labs/agent-beacon/releases/download/ext-updates/updates.xml",
"permissions": ["storage", "alarms"],
"host_permissions": [
"https://claude.ai/*",
@@ -11,6 +12,9 @@
"http://127.0.0.1/*",
"http://localhost/*"
],
+ "storage": {
+ "managed_schema": "managed_schema.json"
+ },
"background": {
"service_worker": "sw.js"
},
diff --git a/browser-extension/src/options/options.html b/browser-extension/src/options/options.html
index 5fe6872e..84256309 100644
--- a/browser-extension/src/options/options.html
+++ b/browser-extension/src/options/options.html
@@ -15,6 +15,7 @@
.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; }
+ .managed { margin: 12px 0; padding: 10px; border: 1px solid #c5d3e8; background: #f2f6fc; border-radius: 4px; }
</style>
</head>
<body>
@@ -27,6 +28,9 @@
<button id="perm-grant" data-testid="perm-grant">Grant site access</button>
</div>
+ <p class="managed" id="managed" data-testid="managed" hidden>Some settings are managed by your
+ organization and cannot be changed here.</p>
+
<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].</p>
diff --git a/browser-extension/src/options/options.ts b/browser-extension/src/options/options.ts
index 5579dd12..fbd01976 100644
--- a/browser-extension/src/options/options.ts
+++ b/browser-extension/src/options/options.ts
@@ -1,27 +1,41 @@
// Options UI: endpoint override + per-site enable.
import { ext } from '../shared/browser.js';
import { mountPermissionBanner } from '../shared/permissions.js';
-import type { Settings } from '../shared/types.js';
+import type { LockedSetting, Settings, SiteName } from '../shared/types.js';
const $ = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;
+const SITES: readonly SiteName[] = ['claude_web', 'chatgpt_web'];
+const siteBox = (site: SiteName) => $(`site_${site}`) as HTMLInputElement;
+
+// Settings fixed by policy: shown, disabled, and left out of every save.
+let locked = new Set<LockedSetting>();
async function load(): Promise<void> {
- const { settings } = (await ext.runtime.sendMessage({ type: 'GET_STATUS' })) as {
+ const status = (await ext.runtime.sendMessage({ type: 'GET_STATUS' })) as {
settings: Settings;
+ locked?: LockedSetting[];
};
- ($('endpoint') as HTMLInputElement).value = settings.endpoint;
- ($('site_claude_web') as HTMLInputElement).checked = settings.sites.claude_web !== false;
- ($('site_chatgpt_web') as HTMLInputElement).checked = settings.sites.chatgpt_web !== false;
+ locked = new Set(status.locked ?? []);
+ const endpoint = $('endpoint') as HTMLInputElement;
+ endpoint.value = status.settings.endpoint;
+ endpoint.disabled = locked.has('endpoint');
+ for (const site of SITES) {
+ siteBox(site).checked = status.settings.sites[site] !== false;
+ siteBox(site).disabled = locked.has(`sites.${site}`);
+ }
+ ($('save') as HTMLButtonElement).disabled =
+ endpoint.disabled && SITES.every((site) => siteBox(site).disabled);
+ $('managed').hidden = locked.size === 0;
}
$('save').addEventListener('click', async () => {
- const patch: Partial<Settings> = {
- endpoint: ($('endpoint') as HTMLInputElement).value.trim(),
- sites: {
- claude_web: ($('site_claude_web') as HTMLInputElement).checked,
- chatgpt_web: ($('site_chatgpt_web') as HTMLInputElement).checked,
- },
- };
+ const patch: Partial<Settings> = {};
+ if (!locked.has('endpoint')) patch.endpoint = ($('endpoint') as HTMLInputElement).value.trim();
+ const sites: Partial<Record<SiteName, boolean>> = {};
+ for (const site of SITES) {
+ if (!locked.has(`sites.${site}`)) sites[site] = siteBox(site).checked;
+ }
+ if (Object.keys(sites).length > 0) patch.sites = sites as Settings['sites'];
const res = (await ext.runtime.sendMessage({ type: 'SET_SETTINGS', patch })) as {
error?: string;
};
diff --git a/browser-extension/src/popup/popup.html b/browser-extension/src/popup/popup.html
index b084710a..d78c02a9 100644
--- a/browser-extension/src/popup/popup.html
+++ b/browser-extension/src/popup/popup.html
@@ -11,6 +11,7 @@
.status { margin-top: 10px; padding-top: 10px; border-top: 1px solid #eee; }
.perm { margin: 0 0 10px; padding: 8px; border: 1px solid #e0a800; background: #fff8e1; border-radius: 4px; }
.perm p { margin: 0 0 6px; }
+ .managed { margin: 0 0 10px; padding: 8px; border: 1px solid #c5d3e8; background: #f2f6fc; border-radius: 4px; }
</style>
</head>
<body>
@@ -20,6 +21,7 @@
<span id="perm-list" data-testid="perm-list"></span></p>
<button id="perm-grant" data-testid="perm-grant">Grant site access</button>
</div>
+ <p class="managed" id="managed" data-testid="managed" hidden>Some settings are managed by your organization.</p>
<div class="row">
<label for="enabled">Capture enabled</label>
<input type="checkbox" id="enabled" />
diff --git a/browser-extension/src/popup/popup.ts b/browser-extension/src/popup/popup.ts
index 3320b064..e19e63fd 100644
--- a/browser-extension/src/popup/popup.ts
+++ b/browser-extension/src/popup/popup.ts
@@ -1,10 +1,11 @@
// Popup UI: toggle capture, choose retention, show live status.
import { ext } from '../shared/browser.js';
import { mountPermissionBanner } from '../shared/permissions.js';
-import type { Settings } from '../shared/types.js';
+import type { LockedSetting, Settings } from '../shared/types.js';
interface Status {
settings: Settings;
+ locked?: LockedSetting[];
queueDepth: number;
active: number;
}
@@ -18,6 +19,11 @@ async function refresh(): Promise<void> {
$('endpoint').textContent = status.settings.endpoint;
$('queue').textContent = String(status.queueDepth);
$('active').textContent = String(status.active);
+ // Settings fixed by policy stay visible but cannot be changed here.
+ const locked = new Set(status.locked ?? []);
+ ($('enabled') as HTMLInputElement).disabled = locked.has('enabled');
+ ($('retention') as HTMLSelectElement).disabled = locked.has('retention');
+ $('managed').hidden = locked.size === 0;
}
$('enabled').addEventListener('change', async (e) => {
diff --git a/browser-extension/src/shared/browser.ts b/browser-extension/src/shared/browser.ts
index 13d53efa..98a3544b 100644
--- a/browser-extension/src/shared/browser.ts
+++ b/browser-extension/src/shared/browser.ts
@@ -10,8 +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, tabs.onRemoved), which have the same shape on
-// all three engines.
+// including the policy-fed storage.managed, 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/types.ts b/browser-extension/src/shared/types.ts
index 5f2f784e..15885c44 100644
--- a/browser-extension/src/shared/types.ts
+++ b/browser-extension/src/shared/types.ts
@@ -70,6 +70,10 @@ export interface Settings {
sites: Record<SiteName, boolean>;
}
+/** A setting an administrator fixed through Chrome policy (managed storage). The popup and options
+ * page show it disabled, and the service worker refuses to change it. */
+export type LockedSetting = 'enabled' | 'retention' | 'endpoint' | `sites.${SiteName}`;
+
export const DEFAULT_SETTINGS: Settings = {
enabled: true,
retention: 'full',
diff --git a/browser-extension/test/unit/build.test.ts b/browser-extension/test/unit/build.test.ts
index 80206e69..e8d8f306 100644
--- a/browser-extension/test/unit/build.test.ts
+++ b/browser-extension/test/unit/build.test.ts
@@ -9,7 +9,7 @@ import { fileURLToPath } from 'node:url';
import { GECKO_ID } from '../../tools/targets.mjs';
const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
-const FILES = ['manifest.json', 'sw.js', 'content.js', 'interceptor.js', 'popup.html', 'popup.js', 'options.html', 'options.js'];
+const FILES = ['manifest.json', 'managed_schema.json', 'sw.js', 'content.js', 'interceptor.js', 'popup.html', 'popup.js', 'options.html', 'options.js'];
let work: string;
const out = (t: string) => path.join(work, t);
diff --git a/browser-extension/test/unit/pack-crx.test.ts b/browser-extension/test/unit/pack-crx.test.ts
new file mode 100644
index 00000000..80b72df6
--- /dev/null
+++ b/browser-extension/test/unit/pack-crx.test.ts
@@ -0,0 +1,131 @@
+// The CRX3 signer and update feed (tools/pack-crx.mjs). Chrome itself accepting the output is the
+// policy e2e's job (e2e/policy-install.spec.ts); these pin the format and the refusals.
+import { describe, expect, it } from 'vitest';
+import crypto from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { compareVersions, crxIdFromPublicKey, feedVersion, feedXml, packCrx, readCrx } from '../../tools/pack-crx.mjs';
+
+const tool = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'tools', 'pack-crx.mjs');
+const rsaPem = () =>
+ crypto.generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();
+const spkiOf = (pem: string) => crypto.createPublicKey(pem).export({ type: 'spki', format: 'der' });
+const zip = Buffer.from('PK\u0003\u0004 stand-in archive bytes');
+
+describe('crxIdFromPublicKey', () => {
+ it("matches Chromium's own id_util test vector", () => {
+ // components/crx_file/id_util_unittest.cc: GenerateId("test").
+ expect(crxIdFromPublicKey(Buffer.from('test'))).toBe('jpignaibiiemhngfjkcpokkamffknabf');
+ });
+});
+
+describe('packCrx / readCrx', () => {
+ const pem = rsaPem();
+
+ it('round-trips: the ID comes from the key and the archive is carried byte for byte', () => {
+ const { crx, id } = packCrx(zip, pem);
+ expect(id).toBe(crxIdFromPublicKey(spkiOf(pem)));
+ expect(id).toMatch(/^[a-p]{32}$/);
+ expect(readCrx(crx)).toEqual({ id, zip });
+ });
+
+ it('writes the CRX3 framing and the signed_header_data field Chrome reads', () => {
+ const { crx } = packCrx(zip, pem);
+ expect(crx.subarray(0, 4).toString('latin1')).toBe('Cr24');
+ expect(crx.readUInt32LE(4)).toBe(3);
+ expect(crx.subarray(crx.length - zip.length)).toEqual(zip);
+ // Field 10000, wire type 2, then an 18-byte SignedData holding the 16-byte crx_id.
+ expect(crx.includes(Buffer.from([0x82, 0xf1, 0x04, 0x12, 0x0a, 0x10]))).toBe(true);
+ });
+
+ it('refuses an archive changed after signing', () => {
+ const { crx } = packCrx(zip, pem);
+ crx[crx.length - 1] ^= 0xff;
+ expect(() => readCrx(crx)).toThrow('signature does not match');
+ });
+
+ it('refuses a header whose ID no proof belongs to', () => {
+ const { crx } = packCrx(zip, pem);
+ const otherId = crypto.createHash('sha256').update(spkiOf(rsaPem())).digest().subarray(0, 16);
+ const at = crx.indexOf(Buffer.from([0x82, 0xf1, 0x04, 0x12, 0x0a, 0x10])) + 6;
+ otherId.copy(crx, at);
+ expect(() => readCrx(crx)).toThrow('no RSA proof');
+ });
+
+ it('refuses a file that is not a CRX3', () => {
+ expect(() => readCrx(zip)).toThrow('not a CRX file');
+ });
+
+ it('refuses a key that is not RSA', () => {
+ const ec = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' }).privateKey.export({ type: 'pkcs8', format: 'pem' });
+ expect(() => packCrx(zip, ec.toString())).toThrow('must be RSA');
+ });
+});
+
+describe('update feed', () => {
+ const id = 'abcdefghijklmnopabcdefghijklmnop';
+ const sha = 'a'.repeat(64);
+
+ it('names the app, the version, where to download it and its hash', () => {
+ const xml = feedXml({ id, version: '0.2.0', codebase: 'https://example.test/x.crx?a=1&b=2', sha256: sha });
+ expect(xml).toContain("<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>");
+ expect(xml).toContain(`<app appid='${id}'>`);
+ expect(xml).toContain(
+ `<updatecheck codebase='https://example.test/x.crx?a=1&amp;b=2' version='0.2.0' hash_sha256='${sha}' />`,
+ );
+ expect(feedVersion(xml, id)).toBe('0.2.0');
+ expect(feedVersion(xml, 'pppppppppppppppppppppppppppppppp')).toBeUndefined();
+ });
+
+ it('refuses values Chrome would reject', () => {
+ const ok = { id, version: '0.2.0', codebase: 'https://example.test/x.crx', sha256: sha };
+ expect(() => feedXml({ ...ok, id: 'not-an-id' })).toThrow('extension ID');
+ expect(() => feedXml({ ...ok, version: '0.2.0-rc1' })).toThrow('version');
+ expect(() => feedXml({ ...ok, codebase: 'file:///tmp/x.crx' })).toThrow('http(s)');
+ expect(() => feedXml({ ...ok, sha256: 'A'.repeat(64) })).toThrow('SHA-256');
+ });
+
+ it('compares dotted versions numerically', () => {
+ expect(compareVersions('0.10.0', '0.9.9')).toBeGreaterThan(0);
+ expect(compareVersions('1.0', '1.0.0')).toBe(0);
+ expect(compareVersions('0.2.0', '0.2.1')).toBeLessThan(0);
+ });
+});
+
+describe('CLI', () => {
+ const dir = mkdtempSync(path.join(tmpdir(), 'beacon-crx-'));
+ const pem = rsaPem();
+ const id = crxIdFromPublicKey(spkiOf(pem));
+ const run = (args: string[], env: Record<string, string> = {}) =>
+ execFileSync(process.execPath, [tool, ...args], { env: { ...process.env, ...env }, encoding: 'utf8', stdio: 'pipe' });
+ writeFileSync(path.join(dir, 'ext.zip'), zip);
+
+ it('signs from a key in the environment, checks the ID, and verifies the result', () => {
+ const out = run(
+ ['pack', '--zip', path.join(dir, 'ext.zip'), '--key-env', 'TEST_CRX_KEY', '--out', path.join(dir, 'ext.crx'), '--expect-id', id],
+ { TEST_CRX_KEY: pem },
+ );
+ expect(out.trim()).toBe(id);
+ expect(run(['verify', '--crx', path.join(dir, 'ext.crx'), '--zip', path.join(dir, 'ext.zip'), '--expect-id', id])).toContain('crx ok');
+ });
+
+ it('refuses a key that gives a different ID than the pinned one', () => {
+ expect(() =>
+ run(['pack', '--zip', path.join(dir, 'ext.zip'), '--key-env', 'TEST_CRX_KEY', '--out', path.join(dir, 'x.crx'), '--expect-id', 'a'.repeat(32)], {
+ TEST_CRX_KEY: pem,
+ }),
+ ).toThrow(/expected a{32}/);
+ });
+
+ it('refuses to roll the feed back to an older version', () => {
+ const feed = path.join(dir, 'updates.xml');
+ const args = (version: string) => ['feed', '--id', id, '--version', version, '--codebase', 'https://example.test/x.crx', '--sha256', 'b'.repeat(64), '--out', feed, '--current', feed];
+ run(args('0.3.0'));
+ expect(() => run(args('0.2.0'))).toThrow(/already offers 0\.3\.0/);
+ run(args('0.3.0')); // re-running the same release rewrites the same feed
+ expect(feedVersion(readFileSync(feed, 'utf8'), id)).toBe('0.3.0');
+ });
+});
diff --git a/browser-extension/test/unit/settings-managed.test.ts b/browser-extension/test/unit/settings-managed.test.ts
new file mode 100644
index 00000000..0629ce07
--- /dev/null
+++ b/browser-extension/test/unit/settings-managed.test.ts
@@ -0,0 +1,80 @@
+// Settings an administrator fixes through Chrome policy (chrome.storage.managed) win over the
+// stored ones, are reported as locked, and are never written back to storage.local.
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { DEFAULT_SETTINGS } from '../../src/shared/types.js';
+
+const local = vi.hoisted(() => ({ get: vi.fn(), set: vi.fn() }));
+const managed = vi.hoisted(() => ({ get: vi.fn() }));
+vi.mock('../../src/shared/browser.js', () => ({ ext: { storage: { local, managed } } }));
+
+const { getSettingsState, lockedIn, resolveManaged, saveSettings } = await import('../../src/background/settings.js');
+
+let stored: Record<string, unknown> | undefined;
+beforeEach(() => {
+ stored = undefined;
+ local.get.mockReset().mockImplementation(async () => ({ settings: stored }));
+ local.set.mockReset().mockImplementation(async ({ settings }) => {
+ stored = settings;
+ });
+ managed.get.mockReset().mockResolvedValue({});
+});
+
+describe('resolveManaged', () => {
+ it('locks each policy value that passes the same checks a stored value gets', () => {
+ expect(
+ resolveManaged({ enabled: true, retention: 'metadata', sites: { chatgpt_web: false } }),
+ ).toEqual({
+ patch: { enabled: true, retention: 'metadata', sites: { chatgpt_web: false } },
+ locked: ['enabled', 'retention', 'sites.chatgpt_web'],
+ });
+ });
+
+ it('ignores a value that fails, without dropping the others', () => {
+ const { patch, locked } = resolveManaged({
+ endpoint: 'https://collector.example.com/v1/logs',
+ retention: 'everything',
+ enabled: false,
+ sites: { claude_web: 'yes', other_site: true },
+ });
+ expect(patch).toEqual({ enabled: false });
+ expect(locked).toEqual(['enabled']);
+ });
+
+ it('reads no policy as nothing locked', () => {
+ expect(resolveManaged(undefined)).toEqual({ patch: {}, locked: [] });
+ });
+});
+
+describe('lockedIn', () => {
+ const locked = ['retention', 'sites.claude_web'] as const;
+ it('names the first locked setting a patch touches', () => {
+ expect(lockedIn({ enabled: true, retention: 'full' }, locked)).toBe('retention');
+ expect(lockedIn({ sites: { claude_web: true } as never }, locked)).toBe('sites.claude_web');
+ });
+ it('lets a patch through when it touches only unlocked settings', () => {
+ expect(lockedIn({ enabled: false, sites: { chatgpt_web: false } as never }, locked)).toBeUndefined();
+ });
+});
+
+describe('effective settings', () => {
+ it('lays policy values over the stored ones and reports them locked', async () => {
+ stored = { ...DEFAULT_SETTINGS, enabled: false, retention: 'redacted' };
+ managed.get.mockResolvedValue({ enabled: true, endpoint: 'http://127.0.0.1:4400/v1/logs' });
+ const { settings, locked } = await getSettingsState();
+ expect(settings).toMatchObject({ enabled: true, retention: 'redacted', endpoint: 'http://127.0.0.1:4400/v1/logs' });
+ expect(locked).toEqual(['enabled', 'endpoint']);
+ });
+
+ it('treats a browser without managed storage as unmanaged', async () => {
+ managed.get.mockRejectedValue(new Error('Managed storage manifest not found'));
+ expect(await getSettingsState()).toEqual({ settings: DEFAULT_SETTINGS, locked: [] });
+ });
+
+ it('saves the user choice beside a lock without writing the policy value', async () => {
+ managed.get.mockResolvedValue({ retention: 'metadata' });
+ const effective = await saveSettings({ enabled: false });
+ expect(effective).toMatchObject({ enabled: false, retention: 'metadata' });
+ // Removing the policy later must bring back what the user had, not the locked value.
+ expect(stored).toMatchObject({ enabled: false, retention: 'full' });
+ });
+});
diff --git a/browser-extension/test/unit/targets.test.ts b/browser-extension/test/unit/targets.test.ts
index c56c83cf..d834103f 100644
--- a/browser-extension/test/unit/targets.test.ts
+++ b/browser-extension/test/unit/targets.test.ts
@@ -7,6 +7,8 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import {
assertSafeOutdir,
+ CHROME_EXTENSION_ID,
+ CHROME_UPDATE_URL,
FIREFOX_MIN_VERSION,
GECKO_ID,
MIN_FIREFOX_FOR_MAIN_WORLD,
@@ -83,7 +85,7 @@ describe('firefoxManifest', () => {
it('carries over everything else unchanged, including the MAIN-world interceptor', () => {
const b = base();
const m = firefoxManifest(b);
- const { background: _b1, options_page: _o1, ...restBase } = b;
+ const { background: _b1, options_page: _o1, update_url: _u1, ...restBase } = b;
const { background: _b2, browser_specific_settings: _s, options_ui: _o2, ...restFf } = m;
expect(restFf).toEqual(restBase);
expect(m.content_scripts[0]).toMatchObject({ js: ['interceptor.js'], world: 'MAIN', run_at: 'document_start' });
@@ -91,6 +93,11 @@ describe('firefoxManifest', () => {
expect(m.manifest_version).toBe(3);
});
+ it("drops Chrome's self-hosted update feed, which Firefox must not poll", () => {
+ expect(base().update_url).toBe(CHROME_UPDATE_URL);
+ expect(firefoxManifest(base()).update_url).toBeUndefined();
+ });
+
it("uses Firefox's options_ui in place of Chrome's options_page", () => {
const m = firefoxManifest(base());
expect(m.options_page).toBeUndefined();
@@ -133,3 +140,27 @@ describe('assertSafeOutdir', () => {
expect(() => assertSafeOutdir(project, src, out)).toThrow(/refusing to build into/);
});
});
+
+describe('chrome self-hosted build', () => {
+ it('pins the extension ID that fleet policies name', () => {
+ // Chrome derives the ID from the CRX signing key, and every fleet's force-install policy names
+ // it. Changing it means a new key, a new extension, and rewriting every policy, so this
+ // assertion is deliberately a literal.
+ expect(CHROME_EXTENSION_ID).toBe('PENDING_SIGNING_KEY');
+ });
+
+ it('points installed copies at the update feed the release workflow publishes', () => {
+ expect(CHROME_UPDATE_URL).toBe(
+ 'https://github.com/Asymptote-Labs/agent-beacon/releases/download/ext-updates/updates.xml',
+ );
+ expect(base().update_url).toBe(CHROME_UPDATE_URL);
+ });
+
+ it('declares the managed-settings schema that policy values are checked against', () => {
+ expect(base().storage).toEqual({ managed_schema: 'managed_schema.json' });
+ const schema = JSON.parse(readFileSync(path.join(root, 'src', 'managed_schema.json'), 'utf8'));
+ expect(schema.type).toBe('object');
+ expect(Object.keys(schema.properties).sort()).toEqual(['enabled', 'endpoint', 'retention', 'sites']);
+ expect(Object.keys(schema.properties.sites.properties).sort()).toEqual(['chatgpt_web', 'claude_web']);
+ });
+});
diff --git a/browser-extension/tools/pack-crx.d.mts b/browser-extension/tools/pack-crx.d.mts
new file mode 100644
index 00000000..a1b640ed
--- /dev/null
+++ b/browser-extension/tools/pack-crx.d.mts
@@ -0,0 +1,9 @@
+// Types for tools/pack-crx.mjs, so the TypeScript unit tests can import it under
+// `strict` without enabling allowJs for the whole project.
+
+export declare function crxIdFromPublicKey(spkiDer: Buffer): string;
+export declare function packCrx(zip: Buffer, privateKeyPem: string): { crx: Buffer; id: string };
+export declare function readCrx(crx: Buffer): { id: string; zip: Buffer };
+export declare function feedXml(feed: { id: string; version: string; codebase: string; sha256: string }): string;
+export declare function feedVersion(xml: string, id: string): string | undefined;
+export declare function compareVersions(a: string, b: string): number;
diff --git a/browser-extension/tools/pack-crx.mjs b/browser-extension/tools/pack-crx.mjs
new file mode 100644
index 00000000..099839f4
--- /dev/null
+++ b/browser-extension/tools/pack-crx.mjs
@@ -0,0 +1,290 @@
+#!/usr/bin/env node
+// Signs the Chrome build as a CRX3 file and writes the update feed Chrome polls for new versions.
+//
+// IT installs the extension through Chrome policy (ExtensionSettings `force_installed`) from a
+// self-hosted update URL rather than the Chrome Web Store. That needs two files: a CRX signed with
+// our key, whose public key fixes the extension ID, and an update manifest (`updates.xml`) naming
+// the current version and where to download it.
+//
+// Dependency-free on purpose (node:crypto, node:fs): the release job that holds the signing key runs
+// this file without `npm ci`, so no third-party package ever executes alongside the key.
+//
+// The format follows Chromium's components/crx_file (crx3.proto, crx_creator.cc, crx_verifier.cc):
+//
+// "Cr24" | uint32le 3 | uint32le header length | CrxFileHeader | zip
+//
+// CrxFileHeader { repeated AsymmetricKeyProof sha256_with_rsa = 2; bytes signed_header_data = 10000; }
+// AsymmetricKeyProof { bytes public_key = 1; bytes signature = 2; } // SubjectPublicKeyInfo DER
+// SignedData { bytes crx_id = 1; } // first 16 bytes of SHA-256(SPKI)
+//
+// The signature is RSA PKCS#1 v1.5 with SHA-256 over
+// "CRX3 SignedData\x00" | uint32le len(signed_header_data) | signed_header_data | zip
+//
+// Plain JavaScript, like targets.mjs, so Node runs it directly. Types for the unit tests are in
+// pack-crx.d.mts.
+
+import crypto from 'node:crypto';
+import fs from 'node:fs';
+import { pathToFileURL } from 'node:url';
+import { CHROME_EXTENSION_ID } from './targets.mjs';
+
+const MAGIC = Buffer.from('Cr24', 'latin1');
+const CRX_VERSION = 3;
+const SIGNED_DATA_PREFIX = Buffer.from('CRX3 SignedData\x00', 'latin1');
+const FIELD_PUBLIC_KEY = 1;
+const FIELD_SIGNATURE = 2;
+const FIELD_CRX_ID = 1;
+const FIELD_SHA256_WITH_RSA = 2;
+const FIELD_SIGNED_HEADER_DATA = 10000;
+const ID_PATTERN = /^[a-p]{32}$/;
+const VERSION_PATTERN = /^\d{1,9}(\.\d{1,9}){0,3}$/;
+const SHA256_PATTERN = /^[0-9a-f]{64}$/;
+
+/** Chrome's extension ID for a public key: SHA-256 of its SPKI DER, first 16 bytes, each hex digit
+ * mapped onto a–p (components/crx_file/id_util.cc). */
+export function crxIdFromPublicKey(spkiDer) {
+ const head = sha256(spkiDer).subarray(0, 16).toString('hex');
+ return [...head].map((c) => String.fromCharCode(97 + parseInt(c, 16))).join('');
+}
+
+/**
+ * Sign `zip` (the extension archive, as published) with an RSA private key in PEM form.
+ * @returns {{ crx: Buffer, id: string }}
+ */
+export function packCrx(zip, privateKeyPem) {
+ const key = crypto.createPrivateKey(privateKeyPem);
+ if (key.asymmetricKeyType !== 'rsa') {
+ throw new Error(`signing key must be RSA, got ${key.asymmetricKeyType}`);
+ }
+ const spki = crypto.createPublicKey(key).export({ type: 'spki', format: 'der' });
+ const signedHeaderData = lengthDelimited(FIELD_CRX_ID, sha256(spki).subarray(0, 16));
+ const signature = crypto.sign('sha256', signedMessage(signedHeaderData, zip), {
+ key,
+ padding: crypto.constants.RSA_PKCS1_PADDING,
+ });
+ const proof = Buffer.concat([
+ lengthDelimited(FIELD_PUBLIC_KEY, spki),
+ lengthDelimited(FIELD_SIGNATURE, signature),
+ ]);
+ const header = Buffer.concat([
+ lengthDelimited(FIELD_SHA256_WITH_RSA, proof),
+ lengthDelimited(FIELD_SIGNED_HEADER_DATA, signedHeaderData),
+ ]);
+ const prefix = Buffer.alloc(12);
+ MAGIC.copy(prefix, 0);
+ prefix.writeUInt32LE(CRX_VERSION, 4);
+ prefix.writeUInt32LE(header.length, 8);
+ return { crx: Buffer.concat([prefix, header, zip]), id: crxIdFromPublicKey(spki) };
+}
+
+/**
+ * Parse a CRX3 file and verify it the way Chrome does for an off-store extension: the header names
+ * an ID, an RSA proof's public key hashes to that ID, and that proof's signature covers the archive.
+ * Throws on anything else.
+ * @returns {{ id: string, zip: Buffer }}
+ */
+export function readCrx(crx) {
+ if (crx.length < 12 || !crx.subarray(0, 4).equals(MAGIC)) throw new Error('not a CRX file');
+ const version = crx.readUInt32LE(4);
+ if (version !== CRX_VERSION) throw new Error(`unsupported CRX version ${version}`);
+ const headerLength = crx.readUInt32LE(8);
+ if (12 + headerLength > crx.length) throw new Error('CRX header runs past the end of the file');
+ const header = crx.subarray(12, 12 + headerLength);
+ const zip = crx.subarray(12 + headerLength);
+
+ const proofs = [];
+ let signedHeaderData;
+ for (const { field, value } of readFields(header)) {
+ if (field === FIELD_SHA256_WITH_RSA) proofs.push(value);
+ if (field === FIELD_SIGNED_HEADER_DATA) signedHeaderData = value;
+ }
+ if (!signedHeaderData) throw new Error('CRX header has no signed_header_data');
+ const crxId = readFields(signedHeaderData).find((f) => f.field === FIELD_CRX_ID)?.value;
+ if (!crxId || crxId.length !== 16) throw new Error('CRX header has no 16-byte crx_id');
+
+ const message = signedMessage(signedHeaderData, zip);
+ for (const proof of proofs) {
+ const fields = readFields(proof);
+ const spki = fields.find((f) => f.field === FIELD_PUBLIC_KEY)?.value;
+ const signature = fields.find((f) => f.field === FIELD_SIGNATURE)?.value;
+ if (!spki || !signature || !sha256(spki).subarray(0, 16).equals(crxId)) continue;
+ const key = crypto.createPublicKey({ key: spki, format: 'der', type: 'spki' });
+ const ok = crypto.verify('sha256', message, { key, padding: crypto.constants.RSA_PKCS1_PADDING }, signature);
+ if (!ok) throw new Error('CRX signature does not match its contents');
+ return { id: crxIdFromPublicKey(spki), zip };
+ }
+ throw new Error('CRX has no RSA proof for its own extension ID');
+}
+
+/**
+ * The update manifest Chrome fetches from the policy's (or the manifest's) update_url
+ * (extensions/browser/updater/safe_manifest_parser.cc). `hash_sha256` makes Chrome refuse a
+ * download that is not exactly the published CRX.
+ */
+export function feedXml({ id, version, codebase, sha256: hash }) {
+ if (!ID_PATTERN.test(id)) throw new Error(`not an extension ID: ${id}`);
+ if (!VERSION_PATTERN.test(version)) throw new Error(`not a Chrome extension version: ${version}`);
+ const url = new URL(codebase);
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') throw new Error(`codebase must be http(s): ${codebase}`);
+ if (!SHA256_PATTERN.test(hash)) throw new Error(`not a lowercase SHA-256: ${hash}`);
+ return [
+ "<?xml version='1.0' encoding='UTF-8'?>",
+ "<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>",
+ ` <app appid='${id}'>`,
+ ` <updatecheck codebase='${xmlAttr(url.href)}' version='${version}' hash_sha256='${hash}' />`,
+ ' </app>',
+ '</gupdate>',
+ '',
+ ].join('\n');
+}
+
+/** The version a feed offers for `id`, or undefined when it names none. Reads only what feedXml writes. */
+export function feedVersion(xml, id) {
+ const app = new RegExp(`<app\\s+appid=['"]${id}['"][^>]*>([\\s\\S]*?)</app>`).exec(xml);
+ return app ? /\bversion=['"]([^'"]+)['"]/.exec(app[1])?.[1] : undefined;
+}
+
+/** Compare dotted Chrome versions numerically: negative, zero or positive. */
+export function compareVersions(a, b) {
+ const pa = a.split('.').map(Number);
+ const pb = b.split('.').map(Number);
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
+ const d = (pa[i] ?? 0) - (pb[i] ?? 0);
+ if (d !== 0) return d;
+ }
+ return 0;
+}
+
+function sha256(data) {
+ return crypto.createHash('sha256').update(data).digest();
+}
+
+function signedMessage(signedHeaderData, zip) {
+ const length = Buffer.alloc(4);
+ length.writeUInt32LE(signedHeaderData.length, 0);
+ return Buffer.concat([SIGNED_DATA_PREFIX, length, signedHeaderData, zip]);
+}
+
+function varint(n) {
+ const out = [];
+ while (n > 0x7f) {
+ out.push((n & 0x7f) | 0x80);
+ n = Math.floor(n / 128);
+ }
+ out.push(n);
+ return Buffer.from(out);
+}
+
+/** A protobuf length-delimited field (wire type 2), the only kind the CRX header uses. */
+function lengthDelimited(field, bytes) {
+ return Buffer.concat([varint(field * 8 + 2), varint(bytes.length), bytes]);
+}
+
+function readVarint(buf, pos) {
+ let value = 0;
+ let scale = 1;
+ for (let i = 0; i < 5; i++) {
+ if (pos >= buf.length) throw new Error('truncated protobuf varint');
+ const byte = buf[pos++];
+ value += (byte & 0x7f) * scale;
+ if ((byte & 0x80) === 0) return [value, pos];
+ scale *= 128;
+ }
+ throw new Error('protobuf varint too long');
+}
+
+function readFields(buf) {
+ const fields = [];
+ let pos = 0;
+ while (pos < buf.length) {
+ let tag, length;
+ [tag, pos] = readVarint(buf, pos);
+ if (tag % 8 !== 2) throw new Error(`unexpected protobuf wire type ${tag % 8} in CRX header`);
+ [length, pos] = readVarint(buf, pos);
+ if (pos + length > buf.length) throw new Error('truncated protobuf field');
+ fields.push({ field: Math.floor(tag / 8), value: buf.subarray(pos, pos + length) });
+ pos += length;
+ }
+ return fields;
+}
+
+function xmlAttr(s) {
+ return s.replace(/&/g, '&amp;').replace(/'/g, '&apos;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
+}
+
+// ---- CLI ----
+
+const USAGE = `usage:
+ pack-crx.mjs pack --zip <archive.zip> --key-env <VAR> | --key <key.pem> --out <file.crx> [--expect-id <id>]
+ pack-crx.mjs verify --crx <file.crx> [--zip <archive.zip>] [--expect-id <id>]
+ pack-crx.mjs feed --id <id> --version <v> --codebase <url> --sha256 <hex> --out <updates.xml> [--current <updates.xml>]
+
+--expect-id defaults to CHROME_EXTENSION_ID in targets.mjs. pack prints the extension ID.
+feed refuses to write a version lower than the one in --current, so re-running an old release
+cannot roll installed extensions back.`;
+
+function parseArgs(argv) {
+ const opts = {};
+ for (let i = 0; i < argv.length; i++) {
+ const arg = argv[i];
+ if (!arg.startsWith('--') || i + 1 >= argv.length) throw new Error(`unexpected argument ${arg}\n\n${USAGE}`);
+ opts[arg.slice(2)] = argv[++i];
+ }
+ return opts;
+}
+
+function need(opts, name) {
+ if (!opts[name]) throw new Error(`missing --${name}\n\n${USAGE}`);
+ return opts[name];
+}
+
+function main(argv) {
+ const [command, ...rest] = argv;
+ const opts = parseArgs(rest);
+ const expectId = opts['expect-id'] ?? CHROME_EXTENSION_ID;
+ switch (command) {
+ case 'pack': {
+ const pem = opts['key-env'] ? process.env[opts['key-env']] : opts.key && fs.readFileSync(opts.key, 'utf8');
+ if (!pem) throw new Error(`no signing key: set --key-env to a non-empty variable or pass --key\n\n${USAGE}`);
+ const { crx, id } = packCrx(fs.readFileSync(need(opts, 'zip')), pem);
+ if (id !== expectId) throw new Error(`signing key gives extension ID ${id}, expected ${expectId}`);
+ fs.writeFileSync(need(opts, 'out'), crx);
+ console.log(id);
+ return;
+ }
+ case 'verify': {
+ const { id, zip } = readCrx(fs.readFileSync(need(opts, 'crx')));
+ if (id !== expectId) throw new Error(`CRX is extension ${id}, expected ${expectId}`);
+ if (opts.zip && !zip.equals(fs.readFileSync(opts.zip))) {
+ throw new Error(`CRX does not contain exactly ${opts.zip}`);
+ }
+ console.log(`crx ok: ${id}${opts.zip ? `, contains ${opts.zip}` : ''}`);
+ return;
+ }
+ case 'feed': {
+ const id = need(opts, 'id');
+ const version = need(opts, 'version');
+ if (opts.current && fs.existsSync(opts.current)) {
+ const current = feedVersion(fs.readFileSync(opts.current, 'utf8'), id);
+ if (current && compareVersions(version, current) < 0) {
+ throw new Error(`the feed already offers ${current}; refusing to roll it back to ${version}`);
+ }
+ }
+ const xml = feedXml({ id, version, codebase: need(opts, 'codebase'), sha256: need(opts, 'sha256') });
+ fs.writeFileSync(need(opts, 'out'), xml);
+ process.stdout.write(xml);
+ return;
+ }
+ default:
+ throw new Error(USAGE);
+ }
+}
+
+if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
+ try {
+ main(process.argv.slice(2));
+ } catch (err) {
+ console.error(err instanceof Error ? err.message : err);
+ process.exit(1);
+ }
+}
diff --git a/browser-extension/tools/targets.d.mts b/browser-extension/tools/targets.d.mts
index a127ec4b..14e6e43b 100644
--- a/browser-extension/tools/targets.d.mts
+++ b/browser-extension/tools/targets.d.mts
@@ -2,6 +2,8 @@
// `strict` without enabling allowJs for the whole project.
export declare const GECKO_ID: string;
+export declare const CHROME_EXTENSION_ID: string;
+export declare const CHROME_UPDATE_URL: string;
export declare const FIREFOX_MIN_VERSION: string;
export declare const FIREFOX_ANDROID_MIN_VERSION: string;
export declare const MIN_FIREFOX_FOR_MAIN_WORLD: number;
diff --git a/browser-extension/tools/targets.mjs b/browser-extension/tools/targets.mjs
index 8e8506f0..8e945851 100644
--- a/browser-extension/tools/targets.mjs
+++ b/browser-extension/tools/targets.mjs
@@ -20,6 +20,24 @@ import path from 'node:path';
*/
export const GECKO_ID = '[email protected]';
+/**
+ * Pinned Chrome extension ID of the signed, self-hosted build. Chrome derives it
+ * from the public half of the CRX signing key, and IT names it in the policy that
+ * force-installs the extension, so it must never change: a new key is a new
+ * extension, and every fleet would have to rewrite its policy. The release
+ * workflow refuses to publish a CRX whose ID differs.
+ */
+export const CHROME_EXTENSION_ID = 'PENDING_SIGNING_KEY';
+
+/**
+ * Where an installed copy checks for new versions (`update_url` in
+ * src/manifest.json). Chrome uses the policy's URL only for the first install and
+ * this one afterwards, unless the policy sets `override_update_url`. The release
+ * workflow replaces `updates.xml` on this fixed release after each signed build.
+ */
+export const CHROME_UPDATE_URL =
+ 'https://github.com/Asymptote-Labs/agent-beacon/releases/download/ext-updates/updates.xml';
+
/**
* Oldest Firefox the Firefox build supports. 140 is the current ESR, which is
* what managed fleets run, and the first release that understands
@@ -56,8 +74,10 @@ export const FIREFOX_DATA_COLLECTION = Object.freeze({
* Chrome's service worker becomes a Firefox MV3 background script (an event
* page; Firefox does not run extension service workers), and Firefox gets its
* add-on ID, minimum version, and data-collection declaration; `options_page`
- * becomes Firefox's `options_ui`. Nothing else changes: the MAIN-world content script, host permissions, popup and options
- * page carry over as they are.
+ * becomes Firefox's `options_ui`. Chrome's top-level `update_url` names the
+ * self-hosted Chrome update feed, which Firefox must not read (its own lives
+ * under `gecko`), so it is dropped. Nothing else changes: the MAIN-world content
+ * script, host permissions, popup and options page carry over as they are.
*
* @param {Record<string, any>} base parsed src/manifest.json (not mutated)
* @returns {Record<string, any>}
@@ -71,6 +91,7 @@ export function firefoxManifest(base) {
// The bundles are IIFEs (see esbuild.config.mjs), so a classic script is
// right; `type: "module"` would be wrong for them.
m.background = { scripts: [worker] };
+ delete m.update_url;
// Firefox documents `options_ui` as its options key; `options_page` is the
// Chrome spelling. Open in a tab, matching how Chrome shows options_page.
if (typeof m.options_page === 'string') {