diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a9466d..90c86ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,15 @@ evals. ### Fixed +- The bridge no longer runs open by default. A missing `WEBOPERATOR_API_TOKEN` + left every HTTP and socket call unauthenticated, the opposite of what the docs + said, so any local process or a web page posting `text/plain` to + `127.0.0.1:8765` could drive the browser. The bridge now falls back to a token + in `~/.weboperator/bridge-token` (0600, created on first start), which the MCP + server and agent client read too, so existing MCP setups keep working. + `WEBOPERATOR_ALLOW_UNAUTHENTICATED_BRIDGE=1` still turns auth off for + development. Plain HTTP clients now have to send the token. + - The MCP server's HTTP fallback, which never worked: it sent the extension's request types (`browser.snapshot`) to an API that takes tool names (`browser_snapshot`), so with the socket unavailable every tool came back diff --git a/README.md b/README.md index ad3c4bf..15fc630 100644 --- a/README.md +++ b/README.md @@ -129,8 +129,9 @@ The `debugger` permission is why Chrome shows a yellow "WebOperator started debu ### Bridge authentication -The bridge listens on `127.0.0.1:8765` and will accept unauthenticated calls until you set -`WEBOPERATOR_API_TOKEN`. Set it. Every bridge variable — bind host, port, socket and log +The bridge listens on `127.0.0.1:8765` and refuses calls without a token. Unless you set +`WEBOPERATOR_API_TOKEN`, it creates one in `~/.weboperator/bridge-token` on first start, and +the MCP server picks it up from there; HTTP clients send it as `Authorization: Bearer`. Every bridge variable — bind host, port, socket and log paths — is documented in [docs/api.md](docs/api.md). ### Requirements @@ -164,7 +165,7 @@ paths — is documented in [docs/api.md](docs/api.md). above is fixed by the manifest key, and the side panel's own error message repeats it. - **"Model stopped issuing tool calls"** — the model cannot call tools, or is too small to do it reliably. Swap it; tool calling is the one hard requirement. - **Chrome rejects the folder on Load unpacked** — point it at `core/dist` or at the unzipped release folder, not at the repository root. -- **The bridge answers `401`** — you set `WEBOPERATOR_API_TOKEN` on the bridge but the client is not sending it. Add `Authorization: Bearer $WEBOPERATOR_API_TOKEN` to the request. +- **The bridge answers `401`** — the client is not sending the bridge token. Add `Authorization: Bearer $(cat ~/.weboperator/bridge-token)`, or your `WEBOPERATOR_API_TOKEN` if you set one, to the request. - **A task fails on a page that looks fine** — check the step trace in the side panel first; a stale element ref or a bot-detection wall shows up there as the failing action. diff --git a/docs/agent-protocol.md b/docs/agent-protocol.md index 378ab5c..c874d04 100644 --- a/docs/agent-protocol.md +++ b/docs/agent-protocol.md @@ -36,7 +36,7 @@ UTF-8 JSON payload ## Auth -Every agent request must include `WEBOPERATOR_API_TOKEN` when the bridge starts: +Every agent request must include the bridge token: `WEBOPERATOR_API_TOKEN`, or when it is unset the contents of `~/.weboperator/bridge-token`: ```json { @@ -45,7 +45,7 @@ Every agent request must include `WEBOPERATOR_API_TOKEN` when the bridge starts: ``` Events do not require a token after the socket is connected. -If no token is configured, requests are rejected unless `WEBOPERATOR_ALLOW_UNAUTHENTICATED_BRIDGE=1` is set for development. +Auth is off only when `WEBOPERATOR_ALLOW_UNAUTHENTICATED_BRIDGE=1` is set and no token is configured, for development. ## Request @@ -55,7 +55,7 @@ If no token is configured, requests are rejected unless `WEBOPERATOR_ALLOW_UNAUT "type": "browser.snapshot", "payload": {}, "timeoutMs": 30000, - "token": "optional-if-auth-enabled" + "token": "" } ``` @@ -65,7 +65,7 @@ Fields: - `type`: command name - `payload`: command payload object - `timeoutMs`: optional request timeout -- `token`: required only when `WEBOPERATOR_API_TOKEN` is set +- `token`: required unless the bridge runs with `WEBOPERATOR_ALLOW_UNAUTHENTICATED_BRIDGE=1` ## Response diff --git a/docs/api.md b/docs/api.md index 764b5fa..8f2a4f5 100644 --- a/docs/api.md +++ b/docs/api.md @@ -28,7 +28,7 @@ Environment variables: - `WEBOPERATOR_BRIDGE_PORT`: bind port, default `8765` - `WEBOPERATOR_BRIDGE_LOG`: log file, default `/tmp/weboperator-bridge.log` - `WEBOPERATOR_AGENT_SOCKET`: framed JSON socket path, default `/tmp/weboperator-bridge.sock` -- `WEBOPERATOR_API_TOKEN`: bearer token for `/v1/*` +- `WEBOPERATOR_API_TOKEN`: bearer token for `/v1/*`; when unset, the token in `~/.weboperator/bridge-token` is used (created on first start, mode 0600) - `WEBOPERATOR_ALLOW_UNAUTHENTICATED_BRIDGE=1`: explicit development-only bypass when no token is set ## Auth @@ -43,7 +43,7 @@ X-WebOperator-Token: Query-string tokens are not supported because URLs are commonly logged. `GET /health` does not require auth and returns `authRequired`. Socket requests must include `"token":""`. -If no token is configured, `/v1/*` and socket requests are rejected unless `WEBOPERATOR_ALLOW_UNAUTHENTICATED_BRIDGE=1` is set. +Without `WEBOPERATOR_API_TOKEN` the bridge reads or creates `~/.weboperator/bridge-token`, so it never runs open by default. `mcp-server.js` and `agent-client.js` read the same file. Only `WEBOPERATOR_ALLOW_UNAUTHENTICATED_BRIDGE=1`, with no token set, turns auth off. For a machine-readable contract, see `docs/openapi.yaml`. diff --git a/docs/requirements.md b/docs/requirements.md index 75453c1..6214a97 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -52,9 +52,9 @@ Only needed to drive the browser from an external agent. - macOS or Linux. `weboperator-bridge/install.sh` exits with "Unsupported OS." anywhere else, so Windows has no supported path. -- The bridge accepts unauthenticated calls unless `WEBOPERATOR_API_TOKEN` is - set and `WEBOPERATOR_ALLOW_UNAUTHENTICATED_BRIDGE=0`. See the environment - variable table in the README. +- The bridge refuses calls without a token. It uses `WEBOPERATOR_API_TOKEN`, or + creates `~/.weboperator/bridge-token` on first start; only + `WEBOPERATOR_ALLOW_UNAUTHENTICATED_BRIDGE=1` turns auth off. See docs/api.md. ## Development diff --git a/scripts/bridge-p0-live.mjs b/scripts/bridge-p0-live.mjs index 516aa1c..4b44a69 100644 --- a/scripts/bridge-p0-live.mjs +++ b/scripts/bridge-p0-live.mjs @@ -1,5 +1,6 @@ #!/usr/bin/env node // Acceptance checks against an already loaded extension and its native bridge. +import { createRequire } from 'node:module'; import assert from 'node:assert/strict'; import net from 'node:net'; import { createServer } from 'node:http'; @@ -7,7 +8,7 @@ import { once } from 'node:events'; import { randomUUID } from 'node:crypto'; const socketPath = process.env.WEBOPERATOR_AGENT_SOCKET || '/tmp/weboperator-bridge.sock'; -const token = process.env.WEBOPERATOR_API_TOKEN; +const token = createRequire(import.meta.url)('../weboperator-bridge/token.js').loadBridgeToken(); const rows = []; let tabId; let taskId; diff --git a/scripts/bridge-p1-p2-live.mjs b/scripts/bridge-p1-p2-live.mjs index 86d9209..a87729f 100644 --- a/scripts/bridge-p1-p2-live.mjs +++ b/scripts/bridge-p1-p2-live.mjs @@ -1,4 +1,5 @@ #!/usr/bin/env node +import { createRequire } from 'node:module'; import assert from 'node:assert/strict'; import { createServer } from 'node:http'; import { once } from 'node:events'; @@ -7,7 +8,7 @@ import net from 'node:net'; import { randomUUID } from 'node:crypto'; const socketPath = process.env.WEBOPERATOR_AGENT_SOCKET || '/tmp/weboperator-bridge.sock'; -const token = process.env.WEBOPERATOR_API_TOKEN; +const token = createRequire(import.meta.url)('../weboperator-bridge/token.js').loadBridgeToken(); const rows = []; const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=', 'base64'); const fixture = createServer((req, res) => { diff --git a/scripts/bridge-smoke.mjs b/scripts/bridge-smoke.mjs index 48ae81b..7b5c528 100644 --- a/scripts/bridge-smoke.mjs +++ b/scripts/bridge-smoke.mjs @@ -3,6 +3,9 @@ import assert from 'node:assert/strict'; import { once } from 'node:events'; import { spawn } from 'node:child_process'; import net from 'node:net'; +import { mkdtempSync, readFileSync, statSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; const port = 19000 + Math.floor(Math.random() * 1000); const token = 'test-token'; @@ -12,15 +15,20 @@ const unauthPort = port + 2000; const unauthBase = `http://127.0.0.1:${unauthPort}`; const unauthSocketPath = `/tmp/weboperator-bridge-smoke-unauth-${process.pid}.sock`; +// Default start: no token and no bypass in the environment, so the bridge must fail closed +// on a token file it creates in HOME. +const defaultHome = mkdtempSync(path.join(tmpdir(), 'weboperator-home-')); +const cleanEnv = { ...process.env }; +delete cleanEnv.WEBOPERATOR_API_TOKEN; +delete cleanEnv.WEBOPERATOR_ALLOW_UNAUTHENTICATED_BRIDGE; const unauthChild = spawn(process.execPath, ['weboperator-bridge/bridge.js'], { cwd: new URL('..', import.meta.url), env: { - ...process.env, + ...cleanEnv, + HOME: defaultHome, WEBOPERATOR_BRIDGE_PORT: String(unauthPort), WEBOPERATOR_AGENT_SOCKET: unauthSocketPath, WEBOPERATOR_BRIDGE_LOG: '/tmp/weboperator-bridge-smoke-unauth.log', - WEBOPERATOR_API_TOKEN: '', - WEBOPERATOR_ALLOW_UNAUTHENTICATED_BRIDGE: '0', }, stdio: ['ignore', 'ignore', 'inherit'], @@ -40,8 +48,17 @@ const child = spawn(process.execPath, ['weboperator-bridge/bridge.js'], { try { await waitForServer(`${unauthBase}/health`); + assert.equal((await getJson(`${unauthBase}/health`)).authRequired, true); const unauthDenied = await fetch(`${unauthBase}/v1/browser/snapshot`); assert.equal(unauthDenied.status, 401); + const noPreflight = await fetch(`${unauthBase}/v1/tools/call`, { method: 'POST', headers: { 'content-type': 'text/plain' }, body: '{"tool":"browser_eval","arguments":{"expression":"1"}}' }); + assert.equal(noPreflight.status, 401); + const tokenFile = path.join(defaultHome, '.weboperator', 'bridge-token'); + assert.equal(statSync(tokenFile).mode & 0o777, 0o600); + const fileToken = readFileSync(tokenFile, 'utf8').trim(); + assert.match(fileToken, /^[0-9a-f]{64}$/); + const withFileToken = await fetch(`${unauthBase}/v1/browser/snapshot`, { headers: { authorization: `Bearer ${fileToken}` } }); + assert.notEqual(withFileToken.status, 401); await waitForServer(`${base}/health`); diff --git a/scripts/bridge-tools-live.mjs b/scripts/bridge-tools-live.mjs index bec3d6a..bb109c4 100644 --- a/scripts/bridge-tools-live.mjs +++ b/scripts/bridge-tools-live.mjs @@ -4,6 +4,7 @@ import { createServer } from 'node:http'; import { once } from 'node:events'; import { createRequire } from 'node:module'; const require = createRequire(import.meta.url); +const bridgeToken = require('../weboperator-bridge/token.js').loadBridgeToken(); const { TOOLS } = require('../weboperator-bridge/tools.js'); const endpoint = `http://127.0.0.1:${process.env.WEBOPERATOR_BRIDGE_PORT || 8765}/mcp`; const pixel = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl6UAAAAABJRU5ErkJggg=='; @@ -74,7 +75,7 @@ try { } function evaluate(expression) { return tool('browser_eval', { tabId, expression }); } async function rpc(method, params) { - const response = await fetch(endpoint, { method: 'POST', headers: { 'content-type': 'application/json', ...(process.env.WEBOPERATOR_API_TOKEN ? { authorization: `Bearer ${process.env.WEBOPERATOR_API_TOKEN}` } : {}) }, body: JSON.stringify({ jsonrpc: '2.0', id: ++rpcId, method, params }), signal: AbortSignal.timeout(40000) }); + const response = await fetch(endpoint, { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${bridgeToken}` }, body: JSON.stringify({ jsonrpc: '2.0', id: ++rpcId, method, params }), signal: AbortSignal.timeout(40000) }); if (!response.ok) throw new Error(`MCP HTTP ${response.status}`); const message = await response.json(); if (message.error) throw new Error(message.error.message); diff --git a/weboperator-bridge/README.md b/weboperator-bridge/README.md index d9f03e0..7709450 100644 --- a/weboperator-bridge/README.md +++ b/weboperator-bridge/README.md @@ -46,7 +46,7 @@ Reload the extension in `chrome://extensions` after registering the host. | `WEBOPERATOR_BRIDGE_PORT` | `8765` | Port of the local bridge HTTP API | | `WEBOPERATOR_BRIDGE_HOST` | `127.0.0.1` | Bridge bind address | | `WEBOPERATOR_AGENT_SOCKET` | `/tmp/weboperator-bridge.sock` | Unix socket the bridge listens on | -| `WEBOPERATOR_API_TOKEN` | _(unset)_ | Shared token, required when unauthenticated bridge access is disabled | +| `WEBOPERATOR_API_TOKEN` | _(unset)_ | Shared token. When unset, bridge and MCP server use `~/.weboperator/bridge-token`, created on first start | macOS and Linux. Chrome, Chromium, Brave, Edge, and Arc are all registered by the installer. diff --git a/weboperator-bridge/agent-client.js b/weboperator-bridge/agent-client.js index 09dd748..bdb68da 100755 --- a/weboperator-bridge/agent-client.js +++ b/weboperator-bridge/agent-client.js @@ -4,7 +4,7 @@ const net = require('net'); const { randomUUID } = require('crypto'); const socketPath = process.env.WEBOPERATOR_AGENT_SOCKET || '/tmp/weboperator-bridge.sock'; -const token = process.env.WEBOPERATOR_API_TOKEN || ''; +const token = require('./token').loadBridgeToken(); const input = process.argv[2] ? JSON.parse(process.argv[2]) : { type: 'bridge.health' }; const message = { id: input.id || randomUUID(), diff --git a/weboperator-bridge/bridge.js b/weboperator-bridge/bridge.js index a1e6826..15b33b2 100755 --- a/weboperator-bridge/bridge.js +++ b/weboperator-bridge/bridge.js @@ -5,12 +5,15 @@ const net = require('net'); const { randomUUID } = require('crypto'); const fs = require('fs'); const { prepareLocalRequest, completeLocalRequest, clipboardRequest } = require('./local-files'); +const { loadBridgeToken, sameToken } = require('./token'); const HOST = process.env.WEBOPERATOR_BRIDGE_HOST || '127.0.0.1'; const PORT = Number(process.env.WEBOPERATOR_BRIDGE_PORT || 8765); const LOG = process.env.WEBOPERATOR_BRIDGE_LOG || '/tmp/weboperator-bridge.log'; -const API_TOKEN = process.env.WEBOPERATOR_API_TOKEN || ''; -const ALLOW_UNAUTHENTICATED = process.env.WEBOPERATOR_ALLOW_UNAUTHENTICATED_BRIDGE !== '0'; +// Fail closed: without a token in the environment the shared token file is used. Only an +// explicit WEBOPERATOR_ALLOW_UNAUTHENTICATED_BRIDGE=1 (development) runs with no token. +const ALLOW_UNAUTHENTICATED = process.env.WEBOPERATOR_ALLOW_UNAUTHENTICATED_BRIDGE === '1'; +const API_TOKEN = ALLOW_UNAUTHENTICATED ? (process.env.WEBOPERATOR_API_TOKEN || '').trim() : loadBridgeToken(); const AGENT_SOCKET = process.env.WEBOPERATOR_AGENT_SOCKET || '/tmp/weboperator-bridge.sock'; @@ -271,13 +274,12 @@ function statusForError(err) { function enforceAuth(req, url) { if (url.pathname.replace(/\/+$/, '') === '/health') return; - if (!API_TOKEN && ALLOW_UNAUTHENTICATED) return; - if (!API_TOKEN) throw httpError(401, 'WEBOPERATOR_API_TOKEN is required unless WEBOPERATOR_ALLOW_UNAUTHENTICATED_BRIDGE=1'); + if (!API_TOKEN) return; const authorization = req.headers.authorization || ''; const bearer = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length).trim() : ''; const headerToken = String(req.headers['x-weboperator-token'] || '').trim(); - if (bearer === API_TOKEN || headerToken === API_TOKEN) return; + if (sameToken(bearer, API_TOKEN) || sameToken(headerToken, API_TOKEN)) return; throw httpError(401, 'Missing or invalid WebOperator API token'); } @@ -498,9 +500,8 @@ async function handleAgentMessage(client, msg) { } function enforceAgentAuth(msg) { - if (!API_TOKEN && ALLOW_UNAUTHENTICATED) return; - if (!API_TOKEN) throw new Error('WEBOPERATOR_API_TOKEN is required unless WEBOPERATOR_ALLOW_UNAUTHENTICATED_BRIDGE=1'); - if (msg.token === API_TOKEN) return; + if (!API_TOKEN) return; + if (sameToken(msg.token, API_TOKEN)) return; throw new Error('Missing or invalid WebOperator API token'); } diff --git a/weboperator-bridge/install.sh b/weboperator-bridge/install.sh index 4929f2a..4983200 100755 --- a/weboperator-bridge/install.sh +++ b/weboperator-bridge/install.sh @@ -52,10 +52,13 @@ EOF echo "Installed native host: $HOST_FILE" done +TOKEN_FILE="$(node -e "const t = require(process.argv[1]); t.loadBridgeToken(); console.log(t.TOKEN_FILE)" "$SCRIPT_DIR/token.js")" + echo "" echo "Extension ID: $EXT_ID" echo "Native Host: $HOST_SCRIPT" echo "Agent socket: ${WEBOPERATOR_AGENT_SOCKET:-/tmp/weboperator-bridge.sock}" echo "HTTP API: http://127.0.0.1:8765" +echo "API token: $TOKEN_FILE (send it as: Authorization: Bearer \$(cat \"$TOKEN_FILE\"))" echo "" echo "Reload the extension in chrome://extensions." diff --git a/weboperator-bridge/mcp-server.js b/weboperator-bridge/mcp-server.js index 15b85b1..bc1a090 100755 --- a/weboperator-bridge/mcp-server.js +++ b/weboperator-bridge/mcp-server.js @@ -15,7 +15,7 @@ const { version: SERVER_VERSION } = require('./package.json'); const SOCKET_PATH = process.env.WEBOPERATOR_AGENT_SOCKET || '/tmp/weboperator-bridge.sock'; const BRIDGE_HOST = process.env.WEBOPERATOR_BRIDGE_HOST || '127.0.0.1'; const BRIDGE_PORT = Number(process.env.WEBOPERATOR_BRIDGE_PORT || 8765); -const API_TOKEN = process.env.WEBOPERATOR_API_TOKEN || ''; +const API_TOKEN = require('./token').loadBridgeToken(); // Shared, optional tool properties understood by the extension itself: // `tabId` acts on one specific tab instead of the focused one, `ref` targets an diff --git a/weboperator-bridge/package.json b/weboperator-bridge/package.json index 80301dd..d073490 100644 --- a/weboperator-bridge/package.json +++ b/weboperator-bridge/package.json @@ -31,6 +31,7 @@ "mcp-server.js", "tools.js", "local-files.js", + "token.js", "bridge.js", "agent-client.js", "native-host.sh", diff --git a/weboperator-bridge/token.js b/weboperator-bridge/token.js new file mode 100644 index 0000000..b68ce31 --- /dev/null +++ b/weboperator-bridge/token.js @@ -0,0 +1,34 @@ +// Shared bridge token: WEBOPERATOR_API_TOKEN if set, else ~/.weboperator/bridge-token, +// created on first use. The bridge (started by Chrome) and MCP clients (started by an +// agent) never share an environment, so a 0600 file is how they agree without setup. +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { randomBytes, timingSafeEqual } = require('crypto'); + +const TOKEN_FILE = path.join(os.homedir(), '.weboperator', 'bridge-token'); + +function loadBridgeToken() { + const fromEnv = (process.env.WEBOPERATOR_API_TOKEN || '').trim(); + if (fromEnv) return fromEnv; + const existing = readTokenFile(); + if (existing) return existing; + fs.mkdirSync(path.dirname(TOKEN_FILE), { recursive: true, mode: 0o700 }); + // Write then link, so a process starting at the same moment never reads a half-written file. + const tmp = `${TOKEN_FILE}.${process.pid}.tmp`; + fs.writeFileSync(tmp, `${randomBytes(32).toString('hex')}\n`, { mode: 0o600 }); + try { fs.linkSync(tmp, TOKEN_FILE); } catch (err) { if (err.code !== 'EEXIST') throw err; } finally { fs.rmSync(tmp, { force: true }); } + return readTokenFile(); +} + +function readTokenFile() { + try { return fs.readFileSync(TOKEN_FILE, 'utf8').trim(); } catch (err) { if (err.code === 'ENOENT') return ''; throw err; } +} + +function sameToken(given, expected) { + const a = Buffer.from(String(given || '')); + const b = Buffer.from(expected); + return a.length === b.length && timingSafeEqual(a, b); +} + +module.exports = { TOKEN_FILE, loadBridgeToken, sameToken };