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 `
- Mermaid diagram -
Mermaid diagram
+
Mermaid source (local-only preview)
+
${diagram}
`; } diff --git a/src/shared/messages.js b/src/shared/messages.js index 3299f30..c6fdba5 100644 --- a/src/shared/messages.js +++ b/src/shared/messages.js @@ -33,6 +33,7 @@ export const MESSAGE_TYPES = Object.freeze({ VALIDATE_ACTION_PLAN: "validate_action_plan", POLICY_RESULT: "policy_result", DEV_WATCH_STATUS: "dev_watch_status", + APPROVE_ACTION_PLAN: "approve_action_plan", EXECUTE_ACTION_PLAN: "execute_action_plan", EXECUTION_RESULT: "execution_result" }); diff --git a/src/shared/policy.js b/src/shared/policy.js index 1f1660f..56f2a43 100644 --- a/src/shared/policy.js +++ b/src/shared/policy.js @@ -23,6 +23,17 @@ const LOW_RISK_ACTIONS = new Set([ ACTION_TYPES.STOP_FOR_HUMAN ]); +// Observations/research are read-only; any browser interaction needs a fresh user decision. +const READ_ONLY_ACTIONS = new Set([ + ACTION_TYPES.OBSERVE_PAGE, ACTION_TYPES.OBSERVE_KNOWN_TAB, + ACTION_TYPES.GET_VISIBLE_TEXT, ACTION_TYPES.GET_DOM_SNAPSHOT, + ACTION_TYPES.GET_FORMS, ACTION_TYPES.GET_LINKS, ACTION_TYPES.GET_BUTTONS, + ACTION_TYPES.CAPTURE_VIEWPORT, ACTION_TYPES.CAPTURE_NUMBERED_OVERLAY, + ACTION_TYPES.WEB_SEARCH, ACTION_TYPES.HTTP_REQUEST, + ACTION_TYPES.WAIT_FOR_PAGE_CHANGE, ACTION_TYPES.ASK_USER, + ACTION_TYPES.STOP_FOR_HUMAN +]); + const MEDIUM_RISK_ACTIONS = new Set([ ACTION_TYPES.FOCUS_ELEMENT, ACTION_TYPES.GO_BACK, @@ -101,8 +112,8 @@ export function validateActionPlan(plan) { index, actionType: action?.type || "unknown", risk, - allowed: true, - requiresConfirmation: risk !== RISK_LEVELS.LOW, + allowed: risk !== RISK_LEVELS.BLOCKED, + requiresConfirmation: risk !== RISK_LEVELS.BLOCKED && !READ_ONLY_ACTIONS.has(action?.type), reason: action?.type === ACTION_TYPES.UPLOAD_FILE_TO_FIELD ? "File upload fields must be completed by the user through the browser file picker." : getPolicyReason(risk) @@ -134,5 +145,5 @@ function getPolicyReason(risk) { return "The action touches sensitive personal, financial, legal, or security data."; } - return "The action needs especially careful human review before continuing."; + return "This operation is not automated. The user can complete it manually on the site."; } diff --git a/src/sidepanel/App.js b/src/sidepanel/App.js index ab978c6..9ac40dd 100644 --- a/src/sidepanel/App.js +++ b/src/sidepanel/App.js @@ -16,11 +16,13 @@ import { const HTTP_PROVIDER_DEFAULT_MAX_TOKENS = 24576; const HTTP_PROVIDER_DEFAULT_RETRY_MAX_TOKENS = 49152; -const HTTP_PROVIDER_DEFAULT_TIMEOUT_MS = 0; +const HTTP_PROVIDER_DEFAULT_TIMEOUT_MS = 120000; const HTTP_PROVIDER_DEFAULT_PLANNER_ENABLED = false; const HTTP_PROVIDER_LEGACY_TIMEOUT_MS = 360000; const HTTP_PROVIDER_KIND_OPENAI = "openai-compatible"; const HTTP_PROVIDER_KIND_CLOUDFLARE = "cloudflare-workers-ai"; +const HTTP_PROVIDER_KIND_GEMINI = "google-gemini-api"; +const GEMINI_API_BASE_URL = "https://generativelanguage.googleapis.com/v1beta/openai"; const GEMINI_CLI_PROVIDER_ID = "google-gemini-cli"; const GEMINI_NANO_PROVIDER_ID = "chrome-gemini-nano"; const GEMINI_NANO_MODEL_ID = "gemini-nano"; @@ -831,6 +833,7 @@ function renderConnectorSettings() { function renderHttpProviderSettings() { const isCloudflare = isCloudflareHttpProviderDraft(state.httpProviderDraft); + const isGemini = state.httpProviderDraft.providerKind === HTTP_PROVIDER_KIND_GEMINI; const computedBaseUrl = isCloudflare ? computeCloudflareWorkersAiBaseUrl(state.httpProviderDraft.accountId || "") : ""; @@ -845,6 +848,7 @@ function renderHttpProviderSettings() { ` : ` - + ${isGemini ? `

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.

` : ""} + +
@@ -926,7 +935,7 @@ function renderHttpProviderAuthFields() { } if (state.httpProviderDraft.authType === "bearer") { - return ``; + return ``; } return ""; @@ -953,7 +962,8 @@ function renderHttpProviderModelControl() { function renderHttpProviderItem(provider) { const extras = [ - provider.providerKind === HTTP_PROVIDER_KIND_CLOUDFLARE ? "Cloudflare Workers AI" : "OpenAI-compatible", + provider.providerKind === HTTP_PROVIDER_KIND_CLOUDFLARE ? "Cloudflare Workers AI" : provider.providerKind === HTTP_PROVIDER_KIND_GEMINI ? "Google Gemini API" : "OpenAI-compatible", + provider.detailedDebug ? "detailed diagnostics ON" : "", provider.useStreaming ? "streaming on" : "", provider.plannerEnabled ? "planner on" : "", provider.maxTokens ? `max ${provider.maxTokens}` : "", @@ -989,7 +999,8 @@ function makeDefaultHttpProviderDraft() { plannerEnabled: HTTP_PROVIDER_DEFAULT_PLANNER_ENABLED, maxTokens: HTTP_PROVIDER_DEFAULT_MAX_TOKENS, retryMaxTokens: HTTP_PROVIDER_DEFAULT_RETRY_MAX_TOKENS, - timeoutMs: HTTP_PROVIDER_DEFAULT_TIMEOUT_MS + timeoutMs: HTTP_PROVIDER_DEFAULT_TIMEOUT_MS, + detailedDebug: false }; } @@ -1014,7 +1025,7 @@ function sanitizeTimeoutMs(value, fallback, defaultValue = HTTP_PROVIDER_DEFAULT } function normalizeHttpProviderKind(value) { - return value === HTTP_PROVIDER_KIND_CLOUDFLARE ? HTTP_PROVIDER_KIND_CLOUDFLARE : HTTP_PROVIDER_KIND_OPENAI; + return [HTTP_PROVIDER_KIND_CLOUDFLARE, HTTP_PROVIDER_KIND_GEMINI].includes(value) ? value : HTTP_PROVIDER_KIND_OPENAI; } function normalizeHttpProviderAuthType(value) { @@ -1404,7 +1415,7 @@ function updateConfirmButtonState() { const selectedPlan = getSelectedPendingPlan(); const selectedPolicy = getSelectedPendingPolicy(); const highestRisk = getHighestRisk(selectedPolicy); - const needsTypedConfirmation = highestRisk === "sensitive"; + const needsTypedConfirmation = ["sensitive", "high"].includes(highestRisk) || Boolean(selectedPlan?.will_submit); const requiredPhrase = getRequiredConfirmationPhrase(highestRisk, selectedPlan); const disabled = !selectedPlan?.actions?.length || !selectedPolicy?.allowed || (needsTypedConfirmation && state.confirmationText !== requiredPhrase); button.disabled = disabled; @@ -1678,7 +1689,7 @@ function renderActionPreview() { const highestRisk = getHighestRisk(policy); const riskClass = getPreviewRiskClass(highestRisk, policy); const confirmation = getConfirmationLabel(highestRisk, policy); - const needsTypedConfirmation = highestRisk === "sensitive"; + const needsTypedConfirmation = ["sensitive", "high"].includes(highestRisk) || Boolean(selectedPlan?.will_submit); const canApproveSession = canOfferSessionApproval(selectedPlan, policy, state.pendingPlanContext); const requiredPhrase = getRequiredConfirmationPhrase(highestRisk, selectedPlan); const confirmDisabled = !selectedActions || blocked || (needsTypedConfirmation && state.confirmationText !== requiredPhrase); @@ -3290,16 +3301,16 @@ function readHttpProviderDraft() { const providerKind = normalizeHttpProviderKind( document.getElementById("http-provider-kind")?.value || state.httpProviderDraft.providerKind || HTTP_PROVIDER_KIND_OPENAI ); - const defaultName = providerKind === HTTP_PROVIDER_KIND_CLOUDFLARE ? "Cloudflare Workers AI" : "Local LLM"; + const defaultName = providerKind === HTTP_PROVIDER_KIND_CLOUDFLARE ? "Cloudflare Workers AI" : providerKind === HTTP_PROVIDER_KIND_GEMINI ? "Google Gemini API" : "Local LLM"; const name = document.getElementById("http-provider-name")?.value.trim() || defaultName; const accountId = providerKind === HTTP_PROVIDER_KIND_CLOUDFLARE ? (document.getElementById("http-provider-account-id")?.value.trim() || state.httpProviderDraft.accountId || "") : (state.httpProviderDraft.accountId || ""); - const baseUrl = providerKind === HTTP_PROVIDER_KIND_CLOUDFLARE + const baseUrl = providerKind === HTTP_PROVIDER_KIND_GEMINI ? GEMINI_API_BASE_URL : providerKind === HTTP_PROVIDER_KIND_CLOUDFLARE ? computeCloudflareWorkersAiBaseUrl(accountId) : (document.getElementById("http-provider-base-url")?.value.trim().replace(/\/+$/, "") || ""); const requestedAuthType = document.getElementById("http-provider-auth-type")?.value || state.httpProviderDraft.authType || "none"; - const authType = providerKind === HTTP_PROVIDER_KIND_CLOUDFLARE ? "bearer" : normalizeHttpProviderAuthType(requestedAuthType); + const authType = [HTTP_PROVIDER_KIND_CLOUDFLARE, HTTP_PROVIDER_KIND_GEMINI].includes(providerKind) ? "bearer" : normalizeHttpProviderAuthType(requestedAuthType); const username = authType === "basic" ? (document.getElementById("http-provider-username")?.value.trim() || "") : (state.httpProviderDraft.username || ""); @@ -3316,6 +3327,7 @@ function readHttpProviderDraft() { const model = document.getElementById("http-provider-model")?.value.trim() || state.httpProviderDraft.model || ""; const useStreaming = Boolean(document.getElementById("http-provider-use-streaming")?.checked); const plannerEnabled = Boolean(document.getElementById("http-provider-planner-enabled")?.checked); + const detailedDebug = Boolean(document.getElementById("http-provider-detailed-debug")?.checked); const maxTokens = sanitizePositiveInteger( document.getElementById("http-provider-max-tokens")?.value, state.httpProviderDraft.maxTokens, @@ -3345,6 +3357,7 @@ function readHttpProviderDraft() { model, useStreaming, plannerEnabled, + detailedDebug, maxTokens, retryMaxTokens, timeoutMs, @@ -3382,9 +3395,21 @@ function validateHttpProviderDraft(provider) { } function handleHttpProviderKindChange() { + const previousKind = state.httpProviderDraft.providerKind; state.httpProviderDraft = readHttpProviderDraft(); - if (state.httpProviderDraft.providerKind === HTTP_PROVIDER_KIND_CLOUDFLARE) { - state.httpProviderDraft.authType = "bearer"; + if (previousKind !== state.httpProviderDraft.providerKind) { + // Never carry an API credential or model selection into another provider. + state.httpProviderDraft.token = ""; + state.httpProviderDraft.password = ""; + state.httpProviderDraft.username = ""; + state.httpProviderDraft.model = ""; + state.httpProviderDraft.models = []; + } + if ([HTTP_PROVIDER_KIND_CLOUDFLARE, HTTP_PROVIDER_KIND_GEMINI].includes(state.httpProviderDraft.providerKind)) state.httpProviderDraft.authType = "bearer"; + if (state.httpProviderDraft.providerKind === HTTP_PROVIDER_KIND_GEMINI) { + state.httpProviderDraft.baseUrl = GEMINI_API_BASE_URL; + state.httpProviderDraft.name ||= "Google Gemini API"; + state.httpProviderDraft.model ||= "gemini-2.5-flash"; } render(); } @@ -7422,9 +7447,9 @@ async function confirmPendingPlan(options = {}) { const planContext = state.pendingPlanContext; const pendingPolicy = getSelectedPendingPolicy(); - if (options.approvalScope === "session") { - addSessionApprovalForPlan(plan, pendingPolicy, planContext); - } + if (!pendingPolicy?.allowed) return; + const highestRisk = getHighestRisk(pendingPolicy); + if ((["sensitive", "high"].includes(highestRisk) || plan.will_submit) && state.confirmationText !== getRequiredConfirmationPhrase(highestRisk, plan)) return; state.pendingPlan = null; state.pendingPlanContext = null; @@ -7433,7 +7458,7 @@ async function confirmPendingPlan(options = {}) { state.confirmationText = ""; try { - await executeActionPlan(plan, { planContext }); + await executeActionPlan(plan, { planContext, userApproved: true }); } catch (error) { state.messages.push({ role: "assistant", @@ -7525,7 +7550,19 @@ async function executeActionPlan(plan, options = {}) { addDebugLog("action.execute.start", { plan: normalizedPlan }, `${actions.length} action(s).`); render(); + let approvalToken = ""; + if (options.userApproved) { + const grant = await sendRuntimeMessage(makeEnvelope(MESSAGE_TYPES.APPROVE_ACTION_PLAN, { plan: normalizedPlan })); + if (!grant.ok || !grant.token) { + state.activity.unshift(`Action approval failed: ${grant.error || "Unknown error"}`); + render(); + return; + } + approvalToken = grant.token; + } + const response = await sendRuntimeMessage(makeEnvelope(MESSAGE_TYPES.EXECUTE_ACTION_PLAN, { + approvalToken, plan: normalizedPlan, executionContext: getLatestPlanContext(options.planContext) })); @@ -8859,7 +8896,7 @@ async function grantPendingPermissionRequest() { state.pendingPermissionRequest = null; state.activity.unshift(`Granted site access for ${pending.origins.join(", ")}.`); render(); - await executeActionPlan(plan, { planContext }); + await executeActionPlan(plan, { planContext, userApproved: true }); } function cancelPendingPermissionRequest() { @@ -9012,10 +9049,11 @@ function canOfferSessionApproval(plan, policy, planContext) { return false; } - return buildSessionApprovalEntries(plan, policy, planContext).length > 0; + return false; // A fresh user decision is required for every state-changing plan. } function hasSessionApprovalForPlan(plan, policy, planContext) { + return false; const entries = buildSessionApprovalEntries(plan, policy, planContext); if (!entries.length) { return false; @@ -11356,11 +11394,12 @@ async function restoreProviderSettings() { ), useStreaming: Boolean(provider.useStreaming), plannerEnabled: Boolean(provider.plannerEnabled), + detailedDebug: Boolean(provider.detailedDebug), maxTokens: sanitizePositiveInteger(provider.maxTokens, HTTP_PROVIDER_DEFAULT_MAX_TOKENS, HTTP_PROVIDER_DEFAULT_MAX_TOKENS), retryMaxTokens: sanitizePositiveInteger(provider.retryMaxTokens, HTTP_PROVIDER_DEFAULT_RETRY_MAX_TOKENS, HTTP_PROVIDER_DEFAULT_RETRY_MAX_TOKENS), timeoutMs: normalizeStoredTimeoutMs(provider), timeoutConfigured: normalizeStoredTimeoutMs(provider) > 0, - baseUrl: providerKind === HTTP_PROVIDER_KIND_CLOUDFLARE + baseUrl: providerKind === HTTP_PROVIDER_KIND_GEMINI ? GEMINI_API_BASE_URL : providerKind === HTTP_PROVIDER_KIND_CLOUDFLARE ? computeCloudflareWorkersAiBaseUrl(accountId) : provider.baseUrl }; @@ -11614,8 +11653,8 @@ function getActionPreviewNote(risk, policy, plan, totalActions = 0) { if (risk === "blocked") { return { tone: "blocked", - title: "Review carefully before confirming", - body: `One or more selected actions fall into a high-attention category. You can still approve them, but review the notes below carefully before continuing with ${actionLabel}.${skippedCount ? ` ${skippedCount} action${skippedCount === 1 ? " is" : "s are"} currently skipped.` : ""}` + title: "Manual action required", + body: `Some steps cannot be automated. Complete them yourself or unselect them to proceed with the remaining ${actionLabel}.${skippedCount ? ` ${skippedCount} action${skippedCount === 1 ? " is" : "s are"} currently skipped.` : ""}` }; } @@ -11630,8 +11669,8 @@ function getActionPreviewNote(risk, policy, plan, totalActions = 0) { if (plan?.will_submit || risk === "high") { return { tone: "high", - title: "Final acceptance step", - body: `Confirm will continue with ${actionLabel} and may accept or submit on the site. Review the target fields before proceeding.${skippedCount ? ` ${skippedCount} action${skippedCount === 1 ? " is" : "s are"} currently skipped.` : ""}` + title: "Irreversible action — additional disclaimer", + body: `This may submit, publish, purchase, delete or accept something. You have the final decision. Type ${getRequiredConfirmationPhrase(risk, plan)} after reviewing the target. Confirm continues with ${actionLabel}.${skippedCount ? ` ${skippedCount} action${skippedCount === 1 ? " is" : "s are"} currently skipped.` : ""}` }; } @@ -11647,7 +11686,7 @@ function getConfirmDisabledReason(risk, policy, plan) { return "Select at least one action to continue."; } - if (risk === "sensitive") { + if (risk === "sensitive" || risk === "high") { return `Confirm unlocks after you type ${getRequiredConfirmationPhrase(risk, plan)} exactly.`; } @@ -11725,7 +11764,7 @@ function getSelectedPendingPolicy() { function getRequiredConfirmationPhrase(risk, plan) { if (risk === "sensitive") return "CONFIRM SENSITIVE"; - if (plan?.will_submit || risk === "high") return ""; + if (plan?.will_submit || risk === "high") return "CONFIRM FINAL"; return "CONFIRM"; }