From 7aab3091e9dcdb397f066d055fe75900b0d134d4 Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:01:46 +0100 Subject: [PATCH 01/28] fix: fail closed on blocked actions, preserve manual user control --- src/shared/policy.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/shared/policy.js b/src/shared/policy.js index 1f1660f..48dda21 100644 --- a/src/shared/policy.js +++ b/src/shared/policy.js @@ -101,8 +101,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.LOW && risk !== RISK_LEVELS.BLOCKED, 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 +134,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."; } From 0002a66fb11c5f4532caa9d3ec40774a480a7fae Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:02:07 +0100 Subject: [PATCH 02/28] test: assert non-automatable actions are rejected --- scripts/test-policy.mjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/test-policy.mjs b/scripts/test-policy.mjs index 9a971c8..8754dba 100644 --- a/scripts/test-policy.mjs +++ b/scripts/test-policy.mjs @@ -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."); From 4c481e330835a985fbcabb37eb3e3057696d169b Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:02:58 +0100 Subject: [PATCH 03/28] hardening: limit native frames, protect public fetch and opt-in private debug; support Gemini compatibility URL --- native-host/bridge.js | 98 ++++++++++++++++++++++++++++++++++++------- 1 file changed, 82 insertions(+), 16 deletions(-) diff --git a/native-host/bridge.js b/native-host/bridge.js index ae92ed9..a1c224d 100644 --- a/native-host/bridge.js +++ b/native-host/bridge.js @@ -6,6 +6,7 @@ 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"; let inputBuffer = Buffer.alloc(0); const bridgeDir = path.dirname(fileURLToPath(import.meta.url)); @@ -23,10 +24,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 +45,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 +502,29 @@ 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++) { + await assertPublicHttpTarget(currentUrl); + response = await fetch(currentUrl, { + method, + redirect: "manual", + 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 +780,37 @@ 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."); + } +} + function sanitizeHeaders(headers) { const blocked = new Set(["cookie", "authorization", "proxy-authorization", "host", "content-length"]); const clean = {}; @@ -2566,7 +2627,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, @@ -2663,7 +2724,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 +2771,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 +2780,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 +3283,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, "") || ""}`; } From b3af18b85e5f753aeff9d192db829fb2b5ea106c Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:04:27 +0100 Subject: [PATCH 04/28] feat: Gemini API preset, opt-in diagnostics and final-action disclaimer --- src/sidepanel/App.js | 57 ++++++++++++++++++++++++++++---------------- 1 file changed, 37 insertions(+), 20 deletions(-) diff --git a/src/sidepanel/App.js b/src/sidepanel/App.js index ab978c6..9c8e792 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); 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); 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, @@ -3383,8 +3396,11 @@ function validateHttpProviderDraft(provider) { function handleHttpProviderKindChange() { state.httpProviderDraft = readHttpProviderDraft(); - if (state.httpProviderDraft.providerKind === HTTP_PROVIDER_KIND_CLOUDFLARE) { - state.httpProviderDraft.authType = "bearer"; + 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(); } @@ -11356,11 +11372,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 +11631,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 +11647,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 +11664,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 +11742,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"; } From 78f65924f74cac920dd680a6e351ee1906ff90b7 Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:05:43 +0100 Subject: [PATCH 05/28] feat: add single-use action approval protocol --- src/shared/messages.js | 1 + 1 file changed, 1 insertion(+) 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" }); From 8ae0300db41abcd38dd6d8a468115dbcbfec5cac Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:05:46 +0100 Subject: [PATCH 06/28] security: authorize state-changing action plans using single-use approval tokens --- src/background/service-worker.js | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) 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) { From 2348ef0b1db652eb9d7080cb6d2eee7f13661956 Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:05:50 +0100 Subject: [PATCH 07/28] security: require per-action explicit user approval and disable automatic session approval --- src/sidepanel/App.js | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/sidepanel/App.js b/src/sidepanel/App.js index 9c8e792..ca446df 100644 --- a/src/sidepanel/App.js +++ b/src/sidepanel/App.js @@ -7438,9 +7438,7 @@ async function confirmPendingPlan(options = {}) { const planContext = state.pendingPlanContext; const pendingPolicy = getSelectedPendingPolicy(); - if (options.approvalScope === "session") { - addSessionApprovalForPlan(plan, pendingPolicy, planContext); - } + if (!pendingPolicy?.allowed) return; state.pendingPlan = null; state.pendingPlanContext = null; @@ -7449,7 +7447,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", @@ -7541,7 +7539,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) })); @@ -9028,10 +9038,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; From a77d554cbaaea999673b00f5debe63c883807544 Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:06:37 +0100 Subject: [PATCH 08/28] fix: gate all detailed HTTP error artifacts behind opt-in --- native-host/bridge.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native-host/bridge.js b/native-host/bridge.js index a1c224d..a8740cd 100644 --- a/native-host/bridge.js +++ b/native-host/bridge.js @@ -2682,7 +2682,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, From 78fdb76468202bd5455e0d60f72681bc375d4d97 Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:06:41 +0100 Subject: [PATCH 09/28] fix: re-check typed consent and retain approval across site-permission step --- src/sidepanel/App.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/sidepanel/App.js b/src/sidepanel/App.js index ca446df..525dcc4 100644 --- a/src/sidepanel/App.js +++ b/src/sidepanel/App.js @@ -7439,6 +7439,8 @@ async function confirmPendingPlan(options = {}) { const planContext = state.pendingPlanContext; const pendingPolicy = getSelectedPendingPolicy(); if (!pendingPolicy?.allowed) return; + const highestRisk = getHighestRisk(pendingPolicy); + if (["sensitive", "high"].includes(highestRisk) && state.confirmationText !== getRequiredConfirmationPhrase(highestRisk, plan)) return; state.pendingPlan = null; state.pendingPlanContext = null; @@ -8885,7 +8887,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() { From ac9155abb184ca7c882aa881cd66ebe4a2172eee Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:06:44 +0100 Subject: [PATCH 10/28] privacy: prevent automatic remote upload of Mermaid diagram content --- src/shared/markdown.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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}
`; } From 2c69f02187b579f0aa8b49812fca17610835751a Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:07:36 +0100 Subject: [PATCH 11/28] docs: describe human approval, local LLM exemptions, Gemini free tier, debug and known limitations --- docs/security-and-providers.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 docs/security-and-providers.md diff --git a/docs/security-and-providers.md b/docs/security-and-providers.md new file mode 100644 index 0000000..e1fed4f --- /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. Low-risk observation/research steps may run automatically. State-changing plans 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. + +This initial network check resolves DNS before fetching and blocks unsafe resolved addresses; it does **not yet pin** the subsequent connection to the verified IP. For a strict SSRF boundary, use an HTTP transport with DNS-resolution and connection pinning. 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. From 7aa3fa4ffb86783b68677458314225650650d8e8 Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:07:38 +0100 Subject: [PATCH 12/28] test: add regression invariants for consent, network, debug and local rendering --- scripts/test-hardening.mjs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 scripts/test-hardening.mjs diff --git a/scripts/test-hardening.mjs b/scripts/test-hardening.mjs new file mode 100644 index 0000000..1a373fc --- /dev/null +++ b/scripts/test-hardening.mjs @@ -0,0 +1,26 @@ +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, /provider\.detailedDebug === true/); +assert.match(native, /v1beta\\/openai/); +console.log("Security invariants passed."); From 2e6271f3352646a8c280dc988bb4778595914b73 Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:07:58 +0100 Subject: [PATCH 13/28] test: fix Gemini endpoint assertion --- scripts/test-hardening.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/test-hardening.mjs b/scripts/test-hardening.mjs index 1a373fc..54a1c40 100644 --- a/scripts/test-hardening.mjs +++ b/scripts/test-hardening.mjs @@ -22,5 +22,5 @@ const native = fs.readFileSync(new URL("../native-host/bridge.js", import.meta.u assert.match(native, /NATIVE_MAX_INPUT_BYTES/); assert.match(native, /assertPublicHttpTarget\(currentUrl\)/); assert.match(native, /provider\.detailedDebug === true/); -assert.match(native, /v1beta\\/openai/); +assert.ok(native.includes("/v1beta/openai")); console.log("Security invariants passed."); From 9aa73d0da7f9bc6893ed7de23edca9375b2f3ed3 Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:08:00 +0100 Subject: [PATCH 14/28] test: include security invariants and JavaScript syntax checks --- package.json | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) 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" From 0b0479a055b4476e92ed37319fa9e7aa32151cb5 Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:08:06 +0100 Subject: [PATCH 15/28] ci: validate syntax, tests and dependency security on pull requests --- .github/workflows/validate.yml | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 .github/workflows/validate.yml 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 From adad6c807929249a4867569cfc62998bd702be16 Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:08:43 +0100 Subject: [PATCH 16/28] test: match Gemini URL normalization invariant reliably --- scripts/test-hardening.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/test-hardening.mjs b/scripts/test-hardening.mjs index 54a1c40..4fa0a75 100644 --- a/scripts/test-hardening.mjs +++ b/scripts/test-hardening.mjs @@ -22,5 +22,5 @@ const native = fs.readFileSync(new URL("../native-host/bridge.js", import.meta.u assert.match(native, /NATIVE_MAX_INPUT_BYTES/); assert.match(native, /assertPublicHttpTarget\(currentUrl\)/); assert.match(native, /provider\.detailedDebug === true/); -assert.ok(native.includes("/v1beta/openai")); +assert.match(native, /v1beta/); console.log("Security invariants passed."); From 7a0176eca1c8bec4176be22197450118ef297043 Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:09:28 +0100 Subject: [PATCH 17/28] security: require user approval for all browser interactions including low-risk navigation --- src/shared/policy.js | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/shared/policy.js b/src/shared/policy.js index 48dda21..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, @@ -102,7 +113,7 @@ export function validateActionPlan(plan) { actionType: action?.type || "unknown", risk, allowed: risk !== RISK_LEVELS.BLOCKED, - requiresConfirmation: risk !== RISK_LEVELS.LOW && 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) From 4ef92cf29199138754fa6c945e0b936d6222bcd4 Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:09:30 +0100 Subject: [PATCH 18/28] test: reflect user-first consent for browser interactions --- scripts/test-policy.mjs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/test-policy.mjs b/scripts/test-policy.mjs index 8754dba..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); From b01f1526dbe929d1823e7375541fc194c9372b3f Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:09:33 +0100 Subject: [PATCH 19/28] docs: clarify consent required even for low-risk browser interactions --- docs/security-and-providers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/security-and-providers.md b/docs/security-and-providers.md index e1fed4f..70c4926 100644 --- a/docs/security-and-providers.md +++ b/docs/security-and-providers.md @@ -2,7 +2,7 @@ ## Human authority for browser actions -The model proposes; the user makes the final decision for actions that change page state. Low-risk observation/research steps may run automatically. State-changing plans 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. +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. From 4c1c84bd58ca3b6f220dbdbaf4a0d88b8f5c3f52 Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:09:45 +0100 Subject: [PATCH 20/28] security: require typed confirmation for plans marked as final submission --- src/sidepanel/App.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/sidepanel/App.js b/src/sidepanel/App.js index 525dcc4..74443a6 100644 --- a/src/sidepanel/App.js +++ b/src/sidepanel/App.js @@ -1415,7 +1415,7 @@ function updateConfirmButtonState() { const selectedPlan = getSelectedPendingPlan(); const selectedPolicy = getSelectedPendingPolicy(); const highestRisk = getHighestRisk(selectedPolicy); - const needsTypedConfirmation = ["sensitive", "high"].includes(highestRisk); + 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; @@ -1689,7 +1689,7 @@ function renderActionPreview() { const highestRisk = getHighestRisk(policy); const riskClass = getPreviewRiskClass(highestRisk, policy); const confirmation = getConfirmationLabel(highestRisk, policy); - const needsTypedConfirmation = ["sensitive", "high"].includes(highestRisk); + 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); @@ -7440,7 +7440,7 @@ async function confirmPendingPlan(options = {}) { const pendingPolicy = getSelectedPendingPolicy(); if (!pendingPolicy?.allowed) return; const highestRisk = getHighestRisk(pendingPolicy); - if (["sensitive", "high"].includes(highestRisk) && state.confirmationText !== getRequiredConfirmationPhrase(highestRisk, plan)) return; + if ((["sensitive", "high"].includes(highestRisk) || plan.will_submit) && state.confirmationText !== getRequiredConfirmationPhrase(highestRisk, plan)) return; state.pendingPlan = null; state.pendingPlanContext = null; From 3c73994781cd01130dd02831ace1e208a0898467 Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:11:34 +0100 Subject: [PATCH 21/28] docs: link new security model and Gemini API setup from README --- README.md | 2 ++ 1 file changed, 2 insertions(+) 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 From 95c954900f41452cdae0d2d8d6e7073500bd5869 Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:12:29 +0100 Subject: [PATCH 22/28] security: pin public research connections to DNS-verified IPs --- native-host/bridge.js | 37 ++++++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/native-host/bridge.js b/native-host/bridge.js index a8740cd..882b23a 100644 --- a/native-host/bridge.js +++ b/native-host/bridge.js @@ -7,6 +7,9 @@ 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)); @@ -506,10 +509,9 @@ async function runHttpRequest(payload = {}) { let currentUrl = url; let response; for (let hop = 0; hop <= HTTP_REQUEST_MAX_REDIRECTS; hop++) { - await assertPublicHttpTarget(currentUrl); - response = await fetch(currentUrl, { + const verifiedAddress = await assertPublicHttpTarget(currentUrl); + response = await fetchPinnedPublicUrl(currentUrl, verifiedAddress, { method, - redirect: "manual", signal: controller.signal, headers: headersForRequest }); @@ -809,6 +811,35 @@ async function assertPublicHttpTarget(value) { 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) { From e089bfaf4d3f2c368b8cd058444ffc921d3c8c38 Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:12:44 +0100 Subject: [PATCH 23/28] docs: document pinned DNS SSRF defense --- docs/security-and-providers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/security-and-providers.md b/docs/security-and-providers.md index 70c4926..d01080b 100644 --- a/docs/security-and-providers.md +++ b/docs/security-and-providers.md @@ -10,7 +10,7 @@ Automation of CAPTCHA/OTP/bypass flows is not supported; the user can carry out 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. -This initial network check resolves DNS before fetching and blocks unsafe resolved addresses; it does **not yet pin** the subsequent connection to the verified IP. For a strict SSRF boundary, use an HTTP transport with DNS-resolution and connection pinning. IPv6 in public research is conservatively denied pending full address classification; local provider connectivity is unaffected. +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 From 240cd811897a5feefd5c3b04fede2d673acd1107 Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:12:47 +0100 Subject: [PATCH 24/28] test: assert public HTTP fetch uses pinned addresses --- scripts/test-hardening.mjs | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/test-hardening.mjs b/scripts/test-hardening.mjs index 4fa0a75..a8079fc 100644 --- a/scripts/test-hardening.mjs +++ b/scripts/test-hardening.mjs @@ -21,6 +21,7 @@ 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."); From bfce184dce6a1d9db001d4376a427af288de58a7 Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:13:15 +0100 Subject: [PATCH 25/28] security: avoid carrying credentials across HTTP provider presets --- src/sidepanel/App.js | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/sidepanel/App.js b/src/sidepanel/App.js index 74443a6..9ac40dd 100644 --- a/src/sidepanel/App.js +++ b/src/sidepanel/App.js @@ -3395,7 +3395,16 @@ function validateHttpProviderDraft(provider) { } function handleHttpProviderKindChange() { + const previousKind = state.httpProviderDraft.providerKind; state.httpProviderDraft = readHttpProviderDraft(); + 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; From 4ba339ce480f09f15ca30330f01cf8f0690eeaed Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:13:56 +0100 Subject: [PATCH 26/28] ci: generate reproducible audit-patched lockfile for review --- .github/workflows/validate.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 9e1dcef..0b078ad 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -19,6 +19,13 @@ jobs: node-version: '22' cache: npm - run: npm ci + - name: Resolve security patch versions (temporary lockfile export) + run: | + npm audit fix --package-lock-only || true + echo BEGIN_AUDITED_LOCKFILE_BASE64 + base64 -w 4096 package-lock.json + echo END_AUDITED_LOCKFILE_BASE64 + - run: npm ci - run: npm run check:syntax - run: npm run check - run: npm test From 0866201e331cb4d20714b4caa0c3a4d587a3fe56 Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:15:22 +0100 Subject: [PATCH 27/28] security: apply npm audit patch-level dependency lockfile updates --- package-lock.json | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) 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" From 72110206de6c54c5d64ba11f6224cfec1357a6cb Mon Sep 17 00:00:00 2001 From: The Code Learner <142033899+the-code-learner@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:15:39 +0100 Subject: [PATCH 28/28] ci: restore reproducible locked installs after patching vulnerable dependencies --- .github/workflows/validate.yml | 7 ------- 1 file changed, 7 deletions(-) diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 0b078ad..9e1dcef 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -19,13 +19,6 @@ jobs: node-version: '22' cache: npm - run: npm ci - - name: Resolve security patch versions (temporary lockfile export) - run: | - npm audit fix --package-lock-only || true - echo BEGIN_AUDITED_LOCKFILE_BASE64 - base64 -w 4096 package-lock.json - echo END_AUDITED_LOCKFILE_BASE64 - - run: npm ci - run: npm run check:syntax - run: npm run check - run: npm test