Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
7aab309
fix: fail closed on blocked actions, preserve manual user control
the-code-learner Nov 3, 2026
0002a66
test: assert non-automatable actions are rejected
the-code-learner Nov 3, 2026
4c481e3
hardening: limit native frames, protect public fetch and opt-in priva…
the-code-learner Nov 3, 2026
b3af18b
feat: Gemini API preset, opt-in diagnostics and final-action disclaimer
the-code-learner Nov 3, 2026
78f6592
feat: add single-use action approval protocol
the-code-learner Nov 3, 2026
8ae0300
security: authorize state-changing action plans using single-use appr…
the-code-learner Nov 3, 2026
2348ef0
security: require per-action explicit user approval and disable autom…
the-code-learner Nov 3, 2026
a77d554
fix: gate all detailed HTTP error artifacts behind opt-in
the-code-learner Nov 3, 2026
78fdb76
fix: re-check typed consent and retain approval across site-permissio…
the-code-learner Nov 3, 2026
ac9155a
privacy: prevent automatic remote upload of Mermaid diagram content
the-code-learner Nov 3, 2026
2c69f02
docs: describe human approval, local LLM exemptions, Gemini free tier…
the-code-learner Nov 3, 2026
7aa3fa4
test: add regression invariants for consent, network, debug and local…
the-code-learner Nov 3, 2026
2e6271f
test: fix Gemini endpoint assertion
the-code-learner Nov 3, 2026
9aa73d0
test: include security invariants and JavaScript syntax checks
the-code-learner Nov 3, 2026
0b0479a
ci: validate syntax, tests and dependency security on pull requests
the-code-learner Nov 3, 2026
adad6c8
test: match Gemini URL normalization invariant reliably
the-code-learner Nov 3, 2026
7a0176e
security: require user approval for all browser interactions includin…
the-code-learner Nov 3, 2026
4ef92cf
test: reflect user-first consent for browser interactions
the-code-learner Nov 3, 2026
b01f152
docs: clarify consent required even for low-risk browser interactions
the-code-learner Nov 3, 2026
4c1c84b
security: require typed confirmation for plans marked as final submis…
the-code-learner Nov 3, 2026
3c73994
docs: link new security model and Gemini API setup from README
the-code-learner Nov 3, 2026
95c9549
security: pin public research connections to DNS-verified IPs
the-code-learner Nov 3, 2026
e089bfa
docs: document pinned DNS SSRF defense
the-code-learner Nov 3, 2026
240cd81
test: assert public HTTP fetch uses pinned addresses
the-code-learner Nov 3, 2026
bfce184
security: avoid carrying credentials across HTTP provider presets
the-code-learner Nov 3, 2026
4ba339c
ci: generate reproducible audit-patched lockfile for review
the-code-learner Nov 3, 2026
0866201
security: apply npm audit patch-level dependency lockfile updates
the-code-learner Nov 3, 2026
7211020
ci: restore reproducible locked installs after patching vulnerable de…
the-code-learner Nov 3, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .github/workflows/validate.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: Validate Browser Companion

on:
push:
branches: [main]
pull_request:

permissions:
contents: read

jobs:
checks:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: npm
- run: npm ci
- run: npm run check:syntax
- run: npm run check
- run: npm test
- run: npm run test:memory
- run: npm run test:attachments
- run: npm audit --audit-level=high --omit=dev
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ The project is intentionally plain JavaScript and can be loaded directly as an u

## Technical Reports

- [Security, user consent and Gemini API setup](docs/security-and-providers.md): manual approval boundaries, local LLM network access, optional detailed HTTP diagnostics, and Google AI Studio free-tier integration.
- [Context synthesis architecture](docs/context-synthesis-architecture.md): reusable patterns for compacting large browser/research context with synthesis agents, link refs, task memory, compact/minimal retries, resume checkpoints, and future grep-style external retrieval.

## What It Does
Expand Down Expand Up @@ -81,6 +82,7 @@ Browser Companion does **not** let the model execute arbitrary code in the page.

Instead:

- the user retains final control of browser interactions and grants each plan explicit approval; high-risk actions include an extra disclaimer and typed confirmation
- the model returns structured action plans
- the extension validates those plans against local policy
- the content executor resolves targets using constrained logic
Expand Down
34 changes: 34 additions & 0 deletions docs/security-and-providers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Security, consent and provider notes

## Human authority for browser actions

The model proposes; the user makes the final decision for actions that change page state. Read-only observation/research steps may run automatically. All browser-interaction plans (including navigation, scrolling, highlighting and clicks) require a fresh user confirmation; high-risk and sensitive actions also require typing a phrase. A worker-issued, single-use grant is bound to the exact plan for up to 60 seconds. Session-wide reuse of action approvals is disabled.

Automation of CAPTCHA/OTP/bypass flows is not supported; the user can carry out these steps personally on the page. Granting site access is not authorization to execute another plan. If a tab changes, re-observe before proceeding.

## Network access and local AI

Public `http_request` research disallows local and private network destinations, including redirect hops. This is distinct from the **explicitly configured HTTP provider** connector, which still supports `http://127.0.0.1:... `, `http://localhost:... `, and LAN-hosted OpenAI-compatible services. Do not place access tokens in public research URLs.

Public HTTP research resolves all DNS answers, rejects private/unsupported addresses and pins the request socket to a prevalidated address. Redirects are checked separately. IPv6 in public research is conservatively denied pending full address classification; local provider connectivity is unaffected.

## Google Gemini API free tier

Under Connector, choose **Google Gemini API (free tier supported)**, enter a Google AI Studio API key, click **Refresh Models**, select a compatible model, then **Save HTTP Provider**. Browser Companion uses Google's officially documented OpenAI-compatible endpoint:
`https://generativelanguage.googleapis.com/v1beta/openai`

Availability, costs and limits depend on your Google project and selected model. A model listed by Google is not necessarily free. Free-tier content may be used by Google to improve its products. Check https://ai.google.dev/gemini-api/docs/pricing and https://ai.google.dev/gemini-api/docs/openai.

Google Antigravity is a separate agent/IDE offering. Browser Companion does not authenticate with Antigravity sessions or reuse Antigravity IDE quotas. The existing Gemini CLI connector remains available independently.

## Detailed debug (opt-in)

For an HTTP provider, select **Detailed HTTP debug** before saving. It is OFF by default and can be switched OFF again. When enabled, the native host writes the HTTP request body and error artifacts under `~/.browser-companion/debug/` with owner-only permissions on POSIX systems. Request artifacts can contain complete prompts or page context, so do not enable this when dealing with sensitive material. Disable the option and delete old artifacts from that directory when finished.

The ordinary side-panel diagnostic logs remain sanitized. Existing artifacts generated by earlier versions at the repository root are not deleted automatically.

## Recovery and testing

The native host rejects malformed input frames, limits frame size and uses bounded timeouts for HTTP providers by default. Pending approval tokens intentionally disappear on service-worker restart: the user must approve the plan again.

Run `npm test`, `npm run test:attachments`, and `npm run test:memory` before merging. Automated tests cover policy invariants and local-only diagram rendering. Dynamic end-to-end tests for service-worker suspension, authenticated local models, and DNS rebinding should be added before claiming comprehensive coverage.
131 changes: 114 additions & 17 deletions native-host/bridge.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ import { fileURLToPath } from "node:url";
import { spawn, spawnSync } from "node:child_process";
import process from "node:process";
import crypto from "node:crypto";
import dns from "node:dns/promises";
import http from "node:http";
import https from "node:https";
import { Readable } from "node:stream";

let inputBuffer = Buffer.alloc(0);
const bridgeDir = path.dirname(fileURLToPath(import.meta.url));
Expand All @@ -23,10 +27,13 @@ const geminiQuotaCache = {
value: null,
pending: null
};
const httpProviderDebugRequestPath = path.join(projectRoot, "tmp-http-provider-request.json");
const httpProviderDebugErrorPath = path.join(projectRoot, "tmp-http-provider-error.json");
const debugDirectory = path.join(os.homedir(), ".browser-companion", "debug");
const httpProviderDebugRequestPath = path.join(debugDirectory, "http-provider-request.json");
const httpProviderDebugErrorPath = path.join(debugDirectory, "http-provider-error.json");
const activeRequestControllers = new Map();
const HTTP_PROVIDER_DEFAULT_TIMEOUT_MS = 0;
const HTTP_PROVIDER_DEFAULT_TIMEOUT_MS = 120000;
const NATIVE_MAX_INPUT_BYTES = 1024 * 1024;
const HTTP_REQUEST_MAX_REDIRECTS = 5;
const CLI_PROVIDER_INACTIVITY_TIMEOUT_MS = 300000;
const GEMINI_QUOTA_CACHE_TTL_MS = 30000;
const COMMAND_MAX_BUFFER_BYTES = 1024 * 1024 * 12;
Expand All @@ -41,14 +48,23 @@ function readMessages() {
while (inputBuffer.length >= 4) {
const messageLength = inputBuffer.readUInt32LE(0);

if (inputBuffer.length < messageLength + 4) {
if (!messageLength || messageLength > NATIVE_MAX_INPUT_BYTES) {
process.stderr.write("Invalid native message length.\n");
process.exitCode = 1;
process.stdin.pause();
return;
}
if (inputBuffer.length < messageLength + 4) return;

const rawMessage = inputBuffer.subarray(4, 4 + messageLength).toString("utf8");
inputBuffer = inputBuffer.subarray(4 + messageLength);

handleMessage(JSON.parse(rawMessage));
try {
const message = JSON.parse(rawMessage);
if (!message || typeof message !== "object" || typeof message.type !== "string") throw new Error("Invalid message envelope");
handleMessage(message);
} catch (error) {
process.stderr.write(`Rejected malformed native message: ${error.message}\n`);
}
}
}

Expand Down Expand Up @@ -489,12 +505,28 @@ async function runHttpRequest(payload = {}) {
const timeout = setTimeout(() => controller.abort(), 20000);

try {
const response = await fetch(url, {
method,
redirect: "follow",
signal: controller.signal,
headers: sanitizeHeaders(payload.headers || {})
});
const headersForRequest = sanitizeHeaders(payload.headers || {});
let currentUrl = url;
let response;
for (let hop = 0; hop <= HTTP_REQUEST_MAX_REDIRECTS; hop++) {
const verifiedAddress = await assertPublicHttpTarget(currentUrl);
response = await fetchPinnedPublicUrl(currentUrl, verifiedAddress, {
method,
signal: controller.signal,
headers: headersForRequest
});
if (![301, 302, 303, 307, 308].includes(response.status)) break;
const location = response.headers.get("location");
if (!location || hop === HTTP_REQUEST_MAX_REDIRECTS) throw new Error("HTTP redirect limit reached.");
const nextUrl = new URL(location, currentUrl).href;
await assertPublicHttpTarget(nextUrl);
// Never forward custom headers across origins.
if (new URL(nextUrl).origin !== new URL(currentUrl).origin) {
for (const key of Object.keys(headersForRequest)) if (key.toLowerCase() !== "user-agent") delete headersForRequest[key];
}
await response.body?.cancel().catch(() => {});
currentUrl = nextUrl;
}
const headers = Object.fromEntries(response.headers.entries());
const contentType = response.headers.get("content-type") || "";
const bodyText = method === "HEAD" ? "" : await readLimitedResponseText(response, 200000);
Expand Down Expand Up @@ -750,6 +782,66 @@ function normalizeHttpUrl(value) {
return url.href;
}

function isPublicAddress(address) {
const value = String(address || "").toLowerCase();
if (!value) return false;
if (value.includes(":")) {
// Default-deny IPv6 for the public fetch tool; local LLM providers are separate.
return false;
}
const parts = value.split(".").map(Number);
if (parts.length !== 4 || parts.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return false;
const [a, b, c] = parts;
return !(a === 0 || a === 10 || a === 127 || a >= 224 ||
(a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) ||
(a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) ||
(a === 192 && b === 0 && c === 0) || (a === 192 && b === 0 && c === 2) ||
(a === 198 && (b === 18 || b === 19)) ||
(a === 198 && b === 51 && c === 100) || (a === 203 && b === 0 && c === 113));
}

async function assertPublicHttpTarget(value) {
const url = new URL(normalizeHttpUrl(value));
if (url.username || url.password) throw new Error("Credentials in public request URLs are forbidden.");
const host = url.hostname.toLowerCase().replace(/\.$/, "");
if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal")) {
throw new Error("Private network destinations are not permitted in public research requests.");
}
const addresses = await dns.lookup(host, { all: true, verbatim: true });
if (!addresses.length || addresses.some(({ address }) => !isPublicAddress(address))) {
throw new Error("Public research request resolved to a private or unsupported address.");
}
return addresses.find(({ family }) => family === 4);
}

function fetchPinnedPublicUrl(value, verifiedAddress, { method, headers, signal }) {
const url = new URL(value);
const transport = url.protocol === "https:" ? https : http;
return new Promise((resolve, reject) => {
const req = transport.request(url, {
method,
headers,
signal,
// DNS resolution was validated above; connect only to that verified IP.
lookup(hostname, options, callback) {
if (options?.all) callback(null, [verifiedAddress]);
else callback(null, verifiedAddress.address, verifiedAddress.family);
}
}, (res) => {
const responseHeaders = new Headers(res.headers);
resolve({
status: res.statusCode || 0,
ok: (res.statusCode || 0) >= 200 && (res.statusCode || 0) < 300,
url: url.href,
headers: responseHeaders,
body: Readable.toWeb(res)
});
});
req.on("error", reject);
req.end();
});
}

function sanitizeHeaders(headers) {
const blocked = new Set(["cookie", "authorization", "proxy-authorization", "host", "content-length"]);
const clean = {};
Expand Down Expand Up @@ -2566,7 +2658,7 @@ function runHttpProviderAgentRequest(provider, payload = {}, options = {}) {
return parsed;
})
.catch((error) => {
saveHttpProviderDebugError(createHttpProviderErrorArtifact({
if (provider.detailedDebug === true) saveHttpProviderDebugError(createHttpProviderErrorArtifact({
requestId: options.requestId || "",
baseUrl: normalizeHttpProviderBaseUrl(provider.baseUrl),
provider,
Expand Down Expand Up @@ -2621,7 +2713,7 @@ function runHttpProviderSynthesisRequest(provider, payload = {}, options = {}) {
thinking
}))
.catch((error) => {
saveHttpProviderDebugError(createHttpProviderErrorArtifact({
if (provider.detailedDebug === true) saveHttpProviderDebugError(createHttpProviderErrorArtifact({
requestId: options.requestId || "",
baseUrl: normalizeHttpProviderBaseUrl(provider.baseUrl),
provider,
Expand Down Expand Up @@ -2663,7 +2755,7 @@ async function runHttpProviderCompletion(provider, prompt, wantsJson, options =
requestBody.response_format = { type: "json_object" };
}

saveHttpProviderDebugRequest({
if (provider.detailedDebug === true) saveHttpProviderDebugRequest({
savedAt: new Date().toISOString(),
baseUrl,
wantsJson,
Expand Down Expand Up @@ -2710,15 +2802,17 @@ async function runHttpProviderCompletion(provider, prompt, wantsJson, options =

function saveHttpProviderDebugRequest(payload) {
try {
fs.writeFileSync(httpProviderDebugRequestPath, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
fs.mkdirSync(debugDirectory, { recursive: true, mode: 0o700 });
fs.writeFileSync(httpProviderDebugRequestPath, `${JSON.stringify(payload, null, 2)}\n`, { mode: 0o600 });
} catch {
// Best-effort debug artifact only.
}
}

function saveHttpProviderDebugError(payload) {
try {
fs.writeFileSync(httpProviderDebugErrorPath, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
fs.mkdirSync(debugDirectory, { recursive: true, mode: 0o700 });
fs.writeFileSync(httpProviderDebugErrorPath, `${JSON.stringify(payload, null, 2)}\n`, { mode: 0o600 });
} catch {
// Best-effort debug artifact only.
}
Expand Down Expand Up @@ -3220,6 +3314,9 @@ function buildHttpProviderApiUrl(baseUrl, routePath) {
const normalizedBaseUrl = normalizeHttpProviderBaseUrl(baseUrl);
const normalizedRoutePath = `/${String(routePath || "").trim().replace(/^\/+/, "")}`;

if (/\/v1beta\/openai$/i.test(normalizedBaseUrl) && /^\/v1\//i.test(normalizedRoutePath)) {
return `${normalizedBaseUrl}${normalizedRoutePath.replace(/^\/v1/i, "")}`;
}
if (/\/v1$/i.test(normalizedBaseUrl) && /^\/v1(\/|$)/i.test(normalizedRoutePath)) {
return `${normalizedBaseUrl}${normalizedRoutePath.replace(/^\/v1/i, "") || ""}`;
}
Expand Down
24 changes: 12 additions & 12 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
"type": "module",
"scripts": {
"check": "node scripts/check-extension.mjs",
"test": "node scripts/test-policy.mjs && node scripts/test-deep-search.mjs && node scripts/test-markdown.mjs",
"test": "node scripts/test-policy.mjs && node scripts/test-deep-search.mjs && node scripts/test-markdown.mjs && node scripts/test-hardening.mjs",
"test:attachments": "node scripts/test-attachment-extraction.mjs",
"test:memory": "node scripts/test-user-memory.mjs"
"test:memory": "node scripts/test-user-memory.mjs",
"check:syntax": "node --check native-host/bridge.js && node --check src/background/service-worker.js && node --check src/sidepanel/App.js && node --check src/deep-search/App.js"
},
"engines": {
"node": ">=20"
Expand Down
27 changes: 27 additions & 0 deletions scripts/test-hardening.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import assert from "node:assert/strict";
import fs from "node:fs";
import { validateActionPlan } from "../src/shared/policy.js";
import { renderRichText } from "../src/shared/markdown.js";

const blocked = validateActionPlan({ actions: [{ type: "click_element", target: { role: "button", name: "Solve CAPTCHA" } }] });
assert.equal(blocked.allowed, false, "non-automatable actions must fail closed");
assert.equal(blocked.results[0].allowed, false);
const medium = validateActionPlan({ actions: [{ type: "fill_field", target: { role: "textbox", name: "Public note" }, value: "hello" }] });
assert.equal(medium.requiresConfirmation, true);
const sensitive = validateActionPlan({ actions: [{ type: "fill_field", target: { name: "Password" }, value: "test" }] });
assert.equal(sensitive.requiresConfirmation, true);
const mermaid = renderRichText("Here is a diagram:\n\`\`\`mermaid\nA-->B\n\`\`\`", { allowMermaid: true });
assert.match(mermaid, /data-language="mermaid"/);
assert.doesNotMatch(mermaid, /mermaid\.ink/);

const worker = fs.readFileSync(new URL("../src/background/service-worker.js", import.meta.url), "utf8");
assert.match(worker, /pendingActionApprovals/);
assert.match(worker, /APPROVE_ACTION_PLAN/);
assert.match(worker, /approved\.planDigest !== JSON\.stringify\(plan\)/);
const native = fs.readFileSync(new URL("../native-host/bridge.js", import.meta.url), "utf8");
assert.match(native, /NATIVE_MAX_INPUT_BYTES/);
assert.match(native, /assertPublicHttpTarget\(currentUrl\)/);
assert.match(native, /fetchPinnedPublicUrl\(currentUrl, verifiedAddress/);
assert.match(native, /provider\.detailedDebug === true/);
assert.match(native, /v1beta/);
console.log("Security invariants passed.");
Loading
Loading