Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.

</details>
Expand Down
8 changes: 4 additions & 4 deletions docs/agent-protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -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

Expand All @@ -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": "<bridge token>"
}
```

Expand All @@ -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

Expand Down
4 changes: 2 additions & 2 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -43,7 +43,7 @@ X-WebOperator-Token: <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":"<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`.

Expand Down
6 changes: 3 additions & 3 deletions docs/requirements.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 2 additions & 1 deletion scripts/bridge-p0-live.mjs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
#!/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';
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;
Expand Down
3 changes: 2 additions & 1 deletion scripts/bridge-p1-p2-live.mjs
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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) => {
Expand Down
23 changes: 20 additions & 3 deletions scripts/bridge-smoke.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
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';
Expand All @@ -12,15 +15,20 @@
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'],
Expand All @@ -40,8 +48,17 @@

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`);

Expand Down
3 changes: 2 additions & 1 deletion scripts/bridge-tools-live.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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==';
Expand Down Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion weboperator-bridge/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion weboperator-bridge/agent-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
17 changes: 9 additions & 8 deletions weboperator-bridge/bridge.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';


Expand Down Expand Up @@ -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');
}

Expand Down Expand Up @@ -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');
}

Expand Down
3 changes: 3 additions & 0 deletions weboperator-bridge/install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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."
2 changes: 1 addition & 1 deletion weboperator-bridge/mcp-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions weboperator-bridge/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"mcp-server.js",
"tools.js",
"local-files.js",
"token.js",
"bridge.js",
"agent-client.js",
"native-host.sh",
Expand Down
34 changes: 34 additions & 0 deletions weboperator-bridge/token.js
Original file line number Diff line number Diff line change
@@ -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 };
Loading