diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml
new file mode 100644
index 0000000..9e1dcef
--- /dev/null
+++ b/.github/workflows/validate.yml
@@ -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
diff --git a/README.md b/README.md
index 3ef4ccf..4b5c6c0 100644
--- a/README.md
+++ b/README.md
@@ -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
@@ -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
diff --git a/docs/security-and-providers.md b/docs/security-and-providers.md
new file mode 100644
index 0000000..d01080b
--- /dev/null
+++ b/docs/security-and-providers.md
@@ -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.
diff --git a/native-host/bridge.js b/native-host/bridge.js
index ae92ed9..882b23a 100644
--- a/native-host/bridge.js
+++ b/native-host/bridge.js
@@ -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));
@@ -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;
@@ -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`);
+ }
}
}
@@ -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);
@@ -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 = {};
@@ -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,
@@ -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,
@@ -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,
@@ -2710,7 +2802,8 @@ 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.
}
@@ -2718,7 +2811,8 @@ function saveHttpProviderDebugRequest(payload) {
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.
}
@@ -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, "") || ""}`;
}
diff --git a/package-lock.json b/package-lock.json
index a43b69b..0032692 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -239,9 +239,9 @@
"license": "MIT"
},
"node_modules/@xmldom/xmldom": {
- "version": "0.8.13",
- "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.13.tgz",
- "integrity": "sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw==",
+ "version": "0.8.15",
+ "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.15.tgz",
+ "integrity": "sha512-/5NV/vDALVFDXgLmfsy9TRCBlKwO2LNBFzpzvb9iIj+jR+eSc6DLYYvVOdivT/jm7MtU6TebYuRmzEOI7w40UA==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
@@ -401,9 +401,9 @@
"license": "MIT"
},
"node_modules/brace-expansion": {
- "version": "1.1.14",
- "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.14.tgz",
- "integrity": "sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g==",
+ "version": "1.1.21",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz",
+ "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==",
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0",
@@ -1077,9 +1077,9 @@
}
},
"node_modules/readdir-glob/node_modules/brace-expansion": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.0.tgz",
- "integrity": "sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w==",
+ "version": "2.1.7",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz",
+ "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==",
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0"
@@ -1210,9 +1210,9 @@
"license": "Apache-2.0"
},
"node_modules/tmp": {
- "version": "0.2.5",
- "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.5.tgz",
- "integrity": "sha512-voyz6MApa1rQGUxT3E+BK7/ROe8itEx7vD8/HEvt4xwXucvQ5G5oeEiHkmHZJuBO21RpOf+YYm9MOivj709jow==",
+ "version": "0.2.7",
+ "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz",
+ "integrity": "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==",
"license": "MIT",
"engines": {
"node": ">=14.14"
diff --git a/package.json b/package.json
index 17a555e..a5054ff 100644
--- a/package.json
+++ b/package.json
@@ -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"
diff --git a/scripts/test-hardening.mjs b/scripts/test-hardening.mjs
new file mode 100644
index 0000000..a8079fc
--- /dev/null
+++ b/scripts/test-hardening.mjs
@@ -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.");
diff --git a/scripts/test-policy.mjs b/scripts/test-policy.mjs
index 9a971c8..ecb19c2 100644
--- a/scripts/test-policy.mjs
+++ b/scripts/test-policy.mjs
@@ -111,9 +111,9 @@ const blockedPlan = {
]
};
-assert.equal(validateActionPlan(lowRiskPlan).requiresConfirmation, false);
-assert.equal(validateActionPlan(linkClickPlan).requiresConfirmation, false);
-assert.equal(validateActionPlan(openUrlPlan).requiresConfirmation, false);
+assert.equal(validateActionPlan(lowRiskPlan).requiresConfirmation, true);
+assert.equal(validateActionPlan(linkClickPlan).requiresConfirmation, true);
+assert.equal(validateActionPlan(openUrlPlan).requiresConfirmation, true);
assert.equal(validateActionPlan(httpRequestPlan).requiresConfirmation, false);
assert.equal(validateActionPlan(webSearchPlan).requiresConfirmation, false);
assert.equal(validateActionPlan(fillPlan).requiresConfirmation, true);
@@ -135,8 +135,8 @@ const captchaPlan = {
]
};
-assert.equal(validateActionPlan(captchaPlan).allowed, true);
+assert.equal(validateActionPlan(captchaPlan).allowed, false);
assert.equal(validateActionPlan(captchaPlan).results[0].risk, "blocked");
-assert.equal(validateActionPlan(captchaPlan).results[0].requiresConfirmation, true);
+assert.equal(validateActionPlan(captchaPlan).results[0].requiresConfirmation, false);
console.log("Policy tests passed.");
diff --git a/src/background/service-worker.js b/src/background/service-worker.js
index 9ffb508..d9ee677 100644
--- a/src/background/service-worker.js
+++ b/src/background/service-worker.js
@@ -9,6 +9,8 @@ chrome.runtime.onInstalled.addListener(() => {
let nativePort = null;
let nativePortSequence = 1;
const nativePortPending = new Map();
+const pendingActionApprovals = new Map();
+const ACTION_APPROVAL_LIFETIME_MS = 60000;
let activeNativeRequestId = null;
const AUTO_OBSERVE_OPENED_TAB_LIMIT = 3;
@@ -33,7 +35,7 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
return true;
});
-async function handleMessage(message) {
+async function handleMessage(message, sender) {
if (message?.type === MESSAGE_TYPES.OBSERVE_ACTIVE_TAB) {
return observeActiveTab(message.payload);
}
@@ -133,8 +135,19 @@ async function handleMessage(message) {
return requestDevWatchStatus();
}
+ if (message?.type === MESSAGE_TYPES.APPROVE_ACTION_PLAN) {
+ if (!isSidepanelSender(sender)) return { ok: false, error: "Action approval must originate from the side panel." };
+ const plan = message.payload?.plan;
+ const policy = validateActionPlan(plan);
+ if (!policy.allowed || !Array.isArray(plan?.actions) || !plan.actions.length) return { ok: false, error: "Action plan cannot be approved." };
+ const token = crypto.randomUUID();
+ pendingActionApprovals.set(token, { planDigest: JSON.stringify(plan), expiresAt: Date.now() + ACTION_APPROVAL_LIFETIME_MS });
+ return { ok: true, token };
+ }
+
if (message?.type === MESSAGE_TYPES.EXECUTE_ACTION_PLAN) {
- return executeActionPlan(message.payload?.plan, message.payload?.executionContext || null);
+ if (!isSidepanelSender(sender)) return { ok: false, error: "Action execution must originate from the side panel." };
+ return executeActionPlan(message.payload?.plan, message.payload?.executionContext || null, message.payload?.approvalToken);
}
return {
@@ -593,7 +606,11 @@ async function requestDevWatchStatus() {
}
}
-async function executeActionPlan(plan, executionContext = null) {
+function isSidepanelSender(sender) {
+ return sender?.id === chrome.runtime.id && sender?.url === chrome.runtime.getURL("src/sidepanel/index.html");
+}
+
+async function executeActionPlan(plan, executionContext = null, approvalToken = "") {
const policy = validateActionPlan(plan);
if (!policy.allowed) {
@@ -604,6 +621,14 @@ async function executeActionPlan(plan, executionContext = null) {
};
}
+ if (policy.requiresConfirmation) {
+ const approved = pendingActionApprovals.get(approvalToken);
+ pendingActionApprovals.delete(approvalToken);
+ if (!approved || approved.expiresAt < Date.now() || approved.planDigest !== JSON.stringify(plan)) {
+ return { ok: false, error: "An explicit, current user approval is required for this action plan." };
+ }
+ }
+
const tab = await resolveExecutionContextTab(executionContext);
if (!tab?.id) {
diff --git a/src/shared/markdown.js b/src/shared/markdown.js
index 9428825..cbf04b8 100644
--- a/src/shared/markdown.js
+++ b/src/shared/markdown.js
@@ -251,11 +251,11 @@ function splitTableRow(line) {
}
function renderMermaidBlock(source) {
- const diagram = encodeURIComponent(String(source || "").trim());
+ const diagram = escapeHtml(String(source || "").trim());
return `
-
${diagram}
Google AI Studio API key required. Free tier models and quotas vary. Google may use free-tier data to improve products; Antigravity IDE limits are separate.
` : ""} + +