Skip to content

Open-source AI browser agent for Chrome and Firefox (monorepo) 🧠

Merge origin/main into fix-533 and reconcile bridge peer auth with controller auth

Emre Sokullu2f706069ce5d
diff --cc docs/cloud-bridge-browser-approval.md
index 8a5975467,6b27cd846..27394f1a2
--- a/docs/cloud-bridge-browser-approval.md
+++ b/docs/cloud-bridge-browser-approval.md
@@@ -111,20 -138,29 +138,41 @@@ contract, credential handling, and imag
## Reconnection
- Approval belongs to one WebSocket. Every new socket (reconnect, URL/identity change) starts `pending`, resends `hello`, and must be approved again.
+ Authentication and approval belong to one WebSocket. Every new socket (reconnect, URL/identity change) starts `pending`, resends `hello` with a new nonce, and must pass the challenge and be approved again. With a token, the reconnect backoff is only reset once the backend has proved itself, so a program that keeps failing the challenge is retried at most every 30 seconds.
+
+ ## Legacy bearer hello (deprecated)
+
+ Before the challenge-response, a token-configured hello carried `"auth": { "type": "bearer", "token": "…" }` plus `browserId` and `installationId`, and the extension accepted `connection_approved` from whoever answered. A backend that has not implemented steps 2 and 3 yet sees a hello without a token and should refuse it.
+
+ To keep such a backend working during the transition, set the flag by hand in the extension's console (service worker console on Chrome, background page console on Firefox):
+
+ ```js
+ chrome.storage.local.set({ webbrainCloudBridgeLegacyBearerAuth: true }) // Firefox: browser.storage.local
+ ```
+
+ With the flag the extension sends the old bearer hello and accepts unauthenticated approval messages, exactly as before. It hands the token to whatever listens on the configured port, so use it only until the backend implements the challenge, then remove it with `chrome.storage.local.remove('webbrainCloudBridgeLegacyBearerAuth')`. The flag will be removed in a later release.
+
+ ## Implementing a backend
+
+ 1. On `hello` with `auth.type === "challenge"` and `auth.method === "hmac-sha256-v1"`, check that `auth.nonce` is 64 lowercase hex characters, generate 32 random bytes of your own, and send `auth_challenge` with your proof. Answer each socket's hello once.
+ 2. On `auth_response`, recompute the extension's proof from both nonces and the `browserId` / `installationId` in the message, compare in constant time, and reply `connection_rejected` (and close) on a mismatch.
+ 3. Only then treat the socket as the browser: send `connection_pending` / `connection_approved`, and route `cloud_*` commands to it.
+ 4. Optionally, during a transition, also accept the deprecated bearer hello (constant-time compare of `auth.token`) for extension builds that predate the challenge.
+
+ The example server below is a complete reference.
+## Local bridge pairing (MCP server, LM Studio plugin)
+
+Pairing is separate from approval and does not need a token. The MCP server
+(`17374`) and the LM Studio plugin (`17375`) authenticate the extension's socket
+before trusting its `hello`:
+
- 1. On connect the bridge sends `{ "type": "auth_challenge", "scheme": "hmac-sha256-v1", "nonce": "…" }`.
- 2. The extension answers `{ "type": "auth", "scheme": "hmac-sha256-v1", "proof": "…" }`, where `proof` is the hex HMAC-SHA256 of `"webbrain-bridge-pairing-v1:" + nonce`, keyed with the pairing key from `webbrainCloudBridgePairingKey` (**Settings β†’ Bridge β†’ Pairing key**). The key itself is never sent.
++1. On connect the bridge sends `{ "type": "pairing_challenge", "scheme": "hmac-sha256-v1", "nonce": "…" }`.
++2. The extension answers `{ "type": "pairing_proof", "scheme": "hmac-sha256-v1", "proof": "…" }`, where `proof` is the hex HMAC-SHA256 of `"webbrain-bridge-pairing-v1:" + nonce`, keyed with the pairing key from `webbrainCloudBridgePairingKey` (**Settings β†’ Bridge β†’ Pairing key**). The key itself is never sent.
+3. Without a key the extension closes the socket. A bridge that refuses the proof closes with code `4001`. Either way `status().approval` becomes `rejected` with the reason in `lastError`, and auto-reconnect stops until the settings change.
+
- Backends that never send `auth_challenge` (WebBrain Cloud, the example server below) are unaffected. The bridges read the key from `~/.webbrain/bridge-key`, `WEBBRAIN_BRIDGE_KEY_FILE` or `WEBBRAIN_BRIDGE_KEY`; see the [MCP server README](../mcp-server/README.md#pairing).
++Backends that never send `pairing_challenge` (WebBrain Cloud, the example server below) are unaffected. The bridges read the key from `~/.webbrain/bridge-key`, `WEBBRAIN_BRIDGE_KEY_FILE` or `WEBBRAIN_BRIDGE_KEY`; see the [MCP server README](../mcp-server/README.md#pairing).
+
## Local test server
`examples/cloud-bridge-approval-server.mjs` is a dependency-free backend for testing:
diff --cc lmstudio-plugin/src/util/bridgeClient.ts
index 42370f86e,cca752584..a106e31ba
--- a/lmstudio-plugin/src/util/bridgeClient.ts
+++ b/lmstudio-plugin/src/util/bridgeClient.ts
@@@ -6,10 -6,8 +6,10 @@@
* document and we host the listener. Every command is initiated here and
* answered by the browser.
*
- * Wire protocol (unchanged from the shipping extension):
+ * Wire protocol:
- * us -> extension {type:'auth_challenge', scheme, nonce} (on connect)
++ * us -> extension {type:'pairing_challenge', scheme, nonce} (on connect)
* extension -> us {type:'hello', client, protocolVersion, capabilities, status}
- * extension -> us {type:'auth', scheme, proof} (either order)
++ * extension -> us {type:'pairing_proof', scheme, proof} (either order)
* us -> extension {id, action, payload}
* extension -> us {id, ok:true, result} | {id, ok:false, error, status?}
*
@@@ -221,73 -173,11 +221,73 @@@ export class BridgeClient
socket.on("error", () => {
/* close handler does the cleanup */
});
+
+ try {
- socket.send(JSON.stringify({ type: "auth_challenge", scheme: PAIRING_SCHEME, nonce: candidate.nonce }));
++ socket.send(JSON.stringify({ type: "pairing_challenge", scheme: PAIRING_SCHEME, nonce: candidate.nonce }));
+ } catch {
+ /* the close handler drops the candidate */
+ }
});
}
+ private rejectCandidate(socket: WebSocket, reason: string, code = PAIRING_CLOSE_CODE): void {
+ const candidate = this.candidates.get(socket);
+ if (candidate) clearTimeout(candidate.timer);
+ this.candidates.delete(socket);
+ try {
+ socket.close(code, reason);
+ } catch {
+ /* already gone */
+ }
+ }
+
+ private handleCandidateMessage(socket: WebSocket, candidate: Candidate, msg: Record<string, unknown>): void {
+ if (msg.type === "hello") {
+ if (msg.client !== "webbrain-extension") {
+ this.rejectCandidate(socket, "Unknown client", 1008);
+ return;
+ }
+ candidate.hello = true;
- } else if (msg.type === "auth") {
++ } else if (msg.type === "pairing_proof" || msg.type === "auth") {
+ if (msg.scheme !== PAIRING_SCHEME || !verifyPairingProof(this.pairingKey, candidate.nonce, msg.proof)) {
+ this.rejectCandidate(socket, "Pairing key mismatch");
+ return;
+ }
+ candidate.paired = true;
+ } else {
+ // Candidates are never sent commands, so anything else is noise.
+ return;
+ }
+ if (!candidate.paired || !candidate.hello) return;
+
+ // Paired: promote it. Latest paired connection wins.
+ clearTimeout(candidate.timer);
+ this.candidates.delete(socket);
+ const previous = this.socket;
+ if (previous) {
+ this.socket = null;
+ this.failAllPending(
+ new BridgeError(
+ "WebBrain extension connection was superseded.",
+ undefined,
+ "COMMAND_INTERRUPTED",
+ ),
+ );
+ try {
+ previous.close(1000, "Superseded");
+ } catch {
+ /* already gone */
+ }
+ }
+ this.socket = socket;
+ const waiters = this.waiters;
+ this.waiters = [];
+ for (const wake of waiters) wake();
+ }
+
private handleMessage(socket: WebSocket, data: string): void {
- if (this.socket !== socket) return;
+ const candidate = this.candidates.get(socket);
+ if (!candidate && this.socket !== socket) return;
let msg: Record<string, unknown>;
try {
diff --cc lmstudio-plugin/test/browserTask.test.mjs
index ccaf07a91,a8cabee7b..89e596615
--- a/lmstudio-plugin/test/browserTask.test.mjs
+++ b/lmstudio-plugin/test/browserTask.test.mjs
@@@ -20,21 -17,6 +20,21 @@@ let socket
let toolsProvider;
const received = [];
+/** Computed independently of dist/util/pairing.js so a drift in either side fails here. */
+function proofFor(key, nonce) {
+ return createHmac("sha256", key).update(`webbrain-bridge-pairing-v1:${nonce}`).digest("hex");
+}
+
+/** Answer the bridge's pairing challenge the way the extension does. */
+function answerPairing(ws, key = PAIRING_KEY) {
+ ws.on("message", (raw) => {
+ const message = JSON.parse(raw.toString());
- if (message.type === "auth_challenge") {
- ws.send(JSON.stringify({ type: "auth", scheme: message.scheme, proof: proofFor(key, message.nonce) }));
++ if (message.type === "pairing_challenge" || message.type === "auth_challenge") {
++ ws.send(JSON.stringify({ type: "pairing_proof", scheme: message.scheme, proof: proofFor(key, message.nonce) }));
+ }
+ });
+}
+
async function freePort() {
const server = createServer();
server.listen(0, "127.0.0.1");
@@@ -287,47 -266,6 +287,47 @@@ test("a web-page origin cannot replace
assert.equal(receivedCommands, 0);
});
+test("a local process with a forged hello cannot replace the paired extension", async () => {
+ for (const key of [null, "a-guessed-pairing-key-000000"]) {
+ const rogue = new WebSocket(sharedBridge().url);
+ const closed = once(rogue, "close");
+ const frames = [];
+ rogue.on("message", (raw) => frames.push(JSON.parse(raw.toString())));
+ if (key) answerPairing(rogue, key);
+ await once(rogue, "open");
+ rogue.send(JSON.stringify({ type: "hello", client: "webbrain-extension" }));
+ await new Promise((resolve) => setTimeout(resolve, 30));
+
+ assert.equal(sharedBridge().isConnected(), true, "an unpaired hello displaced the extension");
+ const result = await browserStatus("still-private-run");
+ assert.equal(result.ok, true);
+ assert.equal(result.runId, "still-private-run");
- assert.deepEqual(frames.map((frame) => frame.type), ["auth_challenge"]);
++ assert.deepEqual(frames.map((frame) => frame.type), ["pairing_challenge"]);
+
+ if (key) {
+ const [code, reason] = await closed;
+ assert.equal(code, 4001);
+ assert.equal(reason.toString(), "Pairing key mismatch");
+ } else {
+ rogue.close();
+ await closed;
+ }
+ }
+});
+
+test("the pairing proof matches the vector the MCP server and extension tests check", () => {
+ assert.equal(
+ pairingProof("webbrain-pairing-test-vector-key", "fixed-nonce-for-cross-checks"),
+ "5d2a446bcc1734f26d8b94e20d3329a07fb2513aa6d036f47f687065d33c55da",
+ );
+});
+
+test("a pairing key shorter than 16 characters keeps the listener closed", async () => {
+ const bridge = new BridgeClient({ port: await freePort(), pairingKey: "short" });
+ await assert.rejects(() => bridge.ensureStarted(), /at least 16 characters/);
+ await bridge.stop();
+});
+
test("browser_task preserves its generated run ID when the start socket disconnects", async () => {
const result = await browserTask({ task: "disconnect initial response", timeout: 5_000 });
diff --cc mcp-server/README.md
index 5e1759e82,87102a171..a9cf8dc16
--- a/mcp-server/README.md
+++ b/mcp-server/README.md
@@@ -29,36 -29,8 +29,36 @@@ cd mcp-server && npm install && npm ru
The MCP server hosts the listener; the extension dials out to it. A Manifest V3 extension cannot listen on a socket, so the direction is fixed.
1. Install the [WebBrain extension](https://webbrain.one) and open your browser.
-2. In **WebBrain β†’ Settings β†’ Bridge**, set the URL to `ws://127.0.0.1:17374/extension` and enable it.
-3. Ask your MCP client to call `webbrain_connection` to confirm.
+2. Print the pairing key:
+
+ ```bash
+ npx -y @webbrain/mcp-server pairing-key
+ ```
+
+ The first run creates it in `~/.webbrain/bridge-key` (`%USERPROFILE%\.webbrain\bridge-key` on Windows), readable only by you. You can also open that file and copy its contents.
+3. In **WebBrain β†’ Settings β†’ Bridge**, set the URL to `ws://127.0.0.1:17374/extension`, paste the key into **Pairing key**, and enable the bridge.
+4. Ask your MCP client to call `webbrain_connection` to confirm.
+
+The LM Studio plugin reads the same key file, so one pairing covers both destinations.
+
+### Pairing
+
+Anything on your machine can open a socket to `127.0.0.1:17374` and claim to be WebBrain, so the server does not trust a socket until it proves it holds the pairing key:
+
- 1. On connect the server sends `{type: "auth_challenge", scheme: "hmac-sha256-v1", nonce}` with a fresh random nonce.
- 2. The extension answers `{type: "auth", scheme, proof}`, where `proof` is the hex HMAC-SHA256 of `"webbrain-bridge-pairing-v1:" + nonce` keyed with the pairing key. The key itself never crosses the socket, and a recorded proof is useless on the next socket.
++1. On connect the server sends `{type: "pairing_challenge", scheme: "hmac-sha256-v1", nonce}` with a fresh random nonce.
++2. The extension answers `{type: "pairing_proof", scheme, proof}`, where `proof` is the hex HMAC-SHA256 of `"webbrain-bridge-pairing-v1:" + nonce` keyed with the pairing key. The key itself never crosses the socket, and a recorded proof is useless on the next socket.
+3. Only after a valid `hello` **and** a valid proof does the socket become the extension. Until then it receives no commands and the already-connected extension keeps working. A wrong proof closes the socket with code `4001`; a socket that does not pair within 10 seconds is closed the same way.
+
+The extension stops reconnecting after a `4001` and shows the reason under **Settings β†’ Bridge**. Saving a new key reconnects it.
+
+### Upgrading from an unpaired version
+
+Earlier versions of this server accepted any socket that sent the right `hello`. After upgrading:
+
+1. Update the WebBrain extension first. A version without the **Pairing key** field cannot pair, and this server closes its socket after 10 seconds with "Pairing required". The updated extension still works with older servers: without a challenge it never sends a proof.
+2. Run `npx -y @webbrain/mcp-server pairing-key`, paste the key under **Settings β†’ Bridge β†’ Pairing key**, and press **Save & test connection**.
+
+Deleting `~/.webbrain/bridge-key` and restarting the server rotates the key; paste the new one into WebBrain.
> **One bridge at a time.** The extension holds exactly one outbound bridge socket. Pointing it here means it is *not* pointed at WebBrain Cloud (`17373`) or the LM Studio plugin (`17375`). Switch it under **Settings β†’ Bridge**.
diff --cc mcp-server/scripts/fake-extension.mjs
index 904cef676,21a15ca9d..a5515a8b0
--- a/mcp-server/scripts/fake-extension.mjs
+++ b/mcp-server/scripts/fake-extension.mjs
@@@ -47,11 -43,6 +47,11 @@@ socket.on("message", (raw) =>
log("non-JSON frame:", raw.toString());
return;
}
- if (msg.type === "auth_challenge") {
- socket.send(JSON.stringify({ type: "auth", scheme: PAIRING_SCHEME, proof: pairingProof(pairingKey, msg.nonce) }));
++ if (msg.type === "pairing_challenge" || msg.type === "auth_challenge") {
++ socket.send(JSON.stringify({ type: "pairing_proof", scheme: PAIRING_SCHEME, proof: pairingProof(pairingKey, msg.nonce) }));
+ log("pairing proof sent");
+ return;
+ }
if (!msg.action) {
log("<-", JSON.stringify(msg));
return;
diff --cc mcp-server/src/bridge.ts
index 83f33928a,c56489e3e..72ff7b37f
--- a/mcp-server/src/bridge.ts
+++ b/mcp-server/src/bridge.ts
@@@ -6,10 -6,8 +6,10 @@@
* document and we host the listener. That also means every command below is
* initiated by us and answered by the extension.
*
- * Wire protocol (already shipping in the extension, unchanged here):
+ * Wire protocol:
- * us -> extension {type:'auth_challenge', scheme, nonce} (on connect)
++ * us -> extension {type:'pairing_challenge', scheme, nonce} (on connect)
* extension -> us {type:'hello', client, protocolVersion, capabilities, status}
- * extension -> us {type:'auth', scheme, proof} (either order)
++ * extension -> us {type:'pairing_proof', scheme, proof} (either order)
* us -> extension {id, action, payload}
* extension -> us {id, ok:true, result}
* {id, ok:false, error, status?}
@@@ -24,16 -17,9 +24,17 @@@
* exact field names `cloud-runs.js` reads.
*/
+ import { randomUUID } from "node:crypto";
import { WebSocketServer, type WebSocket } from "ws";
import { config } from "./config.js";
+import {
+ PAIRING_CLOSE_CODE,
+ PAIRING_SCHEME,
+ loadPairingKey,
+ newPairingNonce,
+ validatePairingKey,
+ verifyPairingProof,
+} from "./pairing.js";
import { BOT_MEMORY_CAPABILITY, validateTaskMemory, taskMemoryPrivateValues, redactTaskMemory, redactMemoryRunResponse } from "./task-memory.js";
/** Actions already present in the extension's ALLOWED_BRIDGE_ACTIONS set. */
@@@ -143,17 -126,9 +160,18 @@@ export class WebBrainBridge
private memoryPrivateValues = new Set<string>();
private memoryProtectedRunIds = new Set<string>();
private memoryRunValues = new Map<string, ReadonlySet<string>>();
- private protectedMemoryRequests = 0;
+ /** Lifecycle of each scope above, in eviction order (oldest finished first). */
+ private memoryRuns = new Map<string, MemoryRunState>();
+ constructor(private readonly options: BridgeOptions = {}) {
+ this.pairingTimeoutMs = options.pairingTimeoutMs ?? 10_000;
+ }
+
+ /** Where the pairing key came from (a file path or variable name), for setup messages. */
+ pairingKeySource(): string {
+ return this.pairingSource;
+ }
+
async start(): Promise<void> {
if (this.wss) return;
@@@ -237,110 -204,45 +255,110 @@@
socket.on("error", (error) => {
log("socket error:", redactTaskMemory(error instanceof Error ? error.message : String(error), this.memoryPrivateValues));
});
+
+ try {
- socket.send(JSON.stringify({ type: "auth_challenge", scheme: PAIRING_SCHEME, nonce: candidate.nonce }));
++ socket.send(JSON.stringify({ type: "pairing_challenge", scheme: PAIRING_SCHEME, nonce: candidate.nonce }));
+ } catch {
+ /* the close handler drops the candidate */
+ }
});
log(`listening on ws://127.0.0.1:${config.bridgePort}${config.bridgePath}`);
+ log(`extensions must pair with the key from ${this.pairingKeyHint()}`);
}
- private handleMessage(socket: WebSocket, data: string): void {
- if (this.socket !== socket) return;
+ /** Where the user finds the key. Never the key itself. */
+ private pairingKeyHint(): string {
+ const source = this.pairingSource || "~/.webbrain/bridge-key";
+ return this.options.pairingKey === undefined ? `${source} (print it with: webbrain-mcp pairing-key)` : source;
+ }
- let msg: Record<string, unknown>;
+ private rejectCandidate(socket: WebSocket, reason: string, code = PAIRING_CLOSE_CODE): void {
+ const candidate = this.candidates.get(socket);
+ if (candidate) clearTimeout(candidate.timer);
+ this.candidates.delete(socket);
+ log(`rejected unpaired connection: ${reason}`);
try {
- msg = JSON.parse(data);
+ socket.close(code, reason);
} catch {
- log("dropped non-JSON frame from extension");
- return;
+ /* already gone */
}
+ }
- // Handshake frame β€” no id, nothing to correlate.
+ private handleCandidateMessage(socket: WebSocket, candidate: Candidate, msg: Record<string, unknown>): void {
if (msg.type === "hello") {
if (msg.client !== "webbrain-extension") {
- log(`rejecting unknown bridge client: ${String(msg.client)}`);
- socket.close(1008, "Unknown client");
- if (this.socket === socket) {
- this.socket = null;
- this.handshakenSocket = null;
- }
+ this.rejectCandidate(socket, "Unknown client", 1008);
return;
}
- this.handshakenSocket = socket;
- this.extensionProtocol = typeof msg.protocolVersion === "number" ? msg.protocolVersion : null;
- this.extensionCapabilities = Array.isArray(msg.capabilities)
- ? (msg.capabilities as string[])
- : [];
- log(
- `handshake ok β€” protocol v${this.extensionProtocol}, capabilities: ` +
- (this.extensionCapabilities.join(", ") || "none"),
+ candidate.hello = msg;
- } else if (msg.type === "auth") {
++ } else if (msg.type === "pairing_proof" || msg.type === "auth") {
+ if (msg.scheme !== PAIRING_SCHEME || !verifyPairingProof(this.pairingKey, candidate.nonce, msg.proof)) {
+ this.rejectCandidate(socket, "Pairing key mismatch");
+ return;
+ }
+ candidate.paired = true;
+ } else {
+ // Candidates are never sent commands, so anything else is noise.
+ return;
+ }
+ if (candidate.paired && candidate.hello) this.adopt(socket, candidate);
+ }
+
+ /** Promote a paired candidate to the extension. Latest paired connection wins. */
+ private adopt(socket: WebSocket, candidate: Candidate): void {
+ clearTimeout(candidate.timer);
+ this.candidates.delete(socket);
+ const hello = candidate.hello!;
+
+ // The extension reconnects with backoff after a browser restart or an
+ // offscreen-document teardown, and the stale socket is never reused.
+ const previous = this.socket;
+ if (previous) {
+ this.socket = null;
+ this.failAllPending(
+ new BridgeError(
+ "WebBrain extension connection was superseded mid-command.",
+ undefined,
+ "COMMAND_INTERRUPTED",
+ ),
);
- const waiters = this.waiters;
- this.waiters = [];
- for (const wake of waiters) wake();
+ try {
+ previous.close(1000, "Superseded by a newer extension connection");
+ } catch {
+ /* already gone */
+ }
+ }
+
+ this.socket = socket;
+ this.extensionProtocol = typeof hello.protocolVersion === "number" ? hello.protocolVersion : null;
+ this.extensionCapabilities = Array.isArray(hello.capabilities)
+ ? (hello.capabilities as string[])
+ : [];
+ log(
+ `extension paired on ${config.bridgePath} β€” protocol v${this.extensionProtocol}, capabilities: ` +
+ (this.extensionCapabilities.join(", ") || "none"),
+ );
+ const waiters = this.waiters;
+ this.waiters = [];
+ for (const wake of waiters) wake();
+ }
+
+ private handleMessage(socket: WebSocket, data: string): void {
+ const candidate = this.candidates.get(socket);
+ if (!candidate && this.socket !== socket) return;
+
+ let msg: Record<string, unknown>;
+ try {
+ msg = JSON.parse(data);
+ } catch {
+ log("dropped non-JSON frame from extension");
+ return;
+ }
+ if (!msg || typeof msg !== "object") return;
+
+ if (candidate) {
+ this.handleCandidateMessage(socket, candidate, msg);
return;
}
@@@ -378,8 -291,70 +407,66 @@@
this.pending.clear();
}
+ /** Track which protected runs the extension reports as finished (or live again). */
+ private noteMemoryRunStatuses(result: unknown, requestRunId?: string): void {
+ if (!this.memoryRuns.size || !result || typeof result !== "object") return;
+ const listed = (result as { runs?: unknown }).runs;
+ for (const run of Array.isArray(listed) ? listed : [result]) {
+ if (!run || typeof run !== "object") continue;
+ const snapshot = run as Record<string, unknown>;
+ const runId = String(snapshot.runId || snapshot.run_id || (Array.isArray(listed) ? "" : requestRunId || ""));
+ const state = this.memoryRuns.get(runId);
+ if (!state || typeof snapshot.status !== "string") continue;
+ state.startSettled = true;
+ const finished = TERMINAL_STATUSES.has(snapshot.status);
+ if (finished && !state.finished) {
+ // Re-append so the most recently finished runs keep their scope longest.
+ this.memoryRuns.delete(runId);
+ this.memoryRuns.set(runId, state);
+ }
+ state.finished = finished;
+ }
+ }
+
+ /** Drop the oldest finished scopes until one more fits; false if every slot is unfinished. */
+ private evictFinishedMemoryRuns(): boolean {
+ let evicted = false;
+ for (const [runId, state] of this.memoryRuns) {
+ if (this.memoryRuns.size < MAX_MEMORY_RUN_SCOPES) break;
+ if (!state.finished) continue;
+ this.memoryRuns.delete(runId);
+ this.memoryProtectedRunIds.delete(runId);
+ this.memoryRunValues.delete(runId);
+ evicted = true;
+ }
+ if (evicted) {
+ // Runs can share a credential, so keep every one a retained run still uses.
+ this.memoryPrivateValues = new Set([...this.memoryRuns.values()].flatMap((state) => state.credentials));
+ }
+ return this.memoryRuns.size < MAX_MEMORY_RUN_SCOPES;
+ }
+
+ /**
+ * A caller that stopped polling leaves a finished run looking unfinished.
+ * The extension's run list is authoritative (it hydrates first), so re-read
+ * it: terminal runs are noted on the way in, and a settled start missing
+ * from the list can never be returned again.
+ */
+ private async refreshMemoryRunStates(timeoutMs: number): Promise<void> {
+ try {
+ const listed = await this.request<{ runs?: CloudSnapshot[] }>("cloud_status", {}, timeoutMs);
+ if (!Array.isArray(listed?.runs)) return;
+ const present = new Set(listed.runs.map((run) => String(run.runId || run.run_id || "")));
+ for (const [runId, state] of this.memoryRuns) {
+ if (state.startSettled && !present.has(runId)) state.finished = true;
+ }
+ } catch {
+ /* the caller reports capacity */
+ }
+ }
+
isConnected(): boolean {
- return (
- this.socket !== null &&
- this.socket.readyState === 1 &&
- this.handshakenSocket === this.socket
- );
+ return this.socket !== null && this.socket.readyState === 1;
}
capabilities(): string[] {
@@@ -489,16 -479,7 +592,16 @@@
this.memoryPrivateValues.clear();
this.memoryProtectedRunIds.clear();
this.memoryRunValues.clear();
- this.protectedMemoryRequests = 0;
+ this.memoryRuns.clear();
+ for (const [candidate, state] of this.candidates) {
+ clearTimeout(state.timer);
+ try {
+ candidate.close(1001, "Server shutting down");
+ } catch {
+ /* ignore */
+ }
+ }
+ this.candidates.clear();
if (this.socket) {
try {
this.socket.close(1001, "Server shutting down");
diff --cc mcp-server/test/bridge.test.mjs
index 35e420c42,36d5fb200..27ee8a898
--- a/mcp-server/test/bridge.test.mjs
+++ b/mcp-server/test/bridge.test.mjs
@@@ -50,13 -36,6 +50,13 @@@ function fakeExtension(url, handler, {
});
socket.on("message", async (raw) => {
const msg = JSON.parse(raw.toString());
+ socket.frames.push(msg);
- if (msg.type === "auth_challenge") {
++ if (msg.type === "pairing_challenge" || msg.type === "auth_challenge") {
+ if (key !== null) {
- socket.send(JSON.stringify({ type: "auth", scheme: msg.scheme, proof: proofFor(key, msg.nonce) }));
++ socket.send(JSON.stringify({ type: "pairing_proof", scheme: msg.scheme, proof: proofFor(key, msg.nonce) }));
+ }
+ return;
+ }
if (!msg.action) return;
const reply = await handler(msg);
socket.send(JSON.stringify({ id: msg.id, ...reply }));
@@@ -218,137 -193,32 +218,137 @@@ test("a web-page origin cannot replace
await bridge.stop();
});
-test("a new socket cannot inherit an earlier extension handshake", async (t) => {
+test("a local process claiming to be the extension cannot replace the paired extension", async (t) => {
+ const bridge = new WebBrainBridge({ pairingTimeoutMs: 200 });
+ t.after(() => bridge.stop());
+ await bridge.start();
+
+ const extension = fakeExtension(bridgeUrl(), (msg) => ({
+ ok: true,
+ result: { runId: msg.payload.runId, status: "running" },
+ }));
+ await bridge.waitForExtension(3000);
+ assert.equal(bridge.isConnected(), true);
+
+ // Origin-less native client with a perfect hello but no pairing proof.
+ const rogue = fakeExtension(bridgeUrl(), () => ({ ok: true, result: { runId: "forged" } }), { key: null });
+ const rogueClosed = closeInfo(rogue);
+ await once(rogue, "open");
+ await new Promise((resolve) => setTimeout(resolve, 30));
+
+ assert.equal(bridge.isConnected(), true, "an unpaired hello displaced the extension");
+ const result = await bridge.request("cloud_run", { runId: "still-private", task: "private task", mode: "ask" });
+ assert.equal(result.runId, "still-private", "the paired extension must keep answering");
- assert.deepEqual(rogue.frames.map((frame) => frame.type), ["auth_challenge"], "an unpaired socket must only see the challenge");
++ assert.deepEqual(rogue.frames.map((frame) => frame.type), ["pairing_challenge"], "an unpaired socket must only see the challenge");
+
+ const { code, reason } = await rogueClosed;
+ assert.equal(code, 4001);
+ assert.match(reason, /Pairing required/);
+ assert.equal(bridge.isConnected(), true);
+
+ extension.close();
+ await bridge.stop();
+});
+
+test("a wrong pairing proof is refused without touching the paired extension", async (t) => {
const bridge = new WebBrainBridge();
t.after(() => bridge.stop());
await bridge.start();
- const extension = fakeExtension(bridgeUrl(), () => ({ ok: true, result: {} }));
+ const extension = fakeExtension(bridgeUrl(), () => ({ ok: true, result: { runId: "safe", status: "running" } }));
await bridge.waitForExtension(3000);
+
+ const rogue = fakeExtension(bridgeUrl(), () => ({ ok: true, result: {} }), { key: "a-guessed-pairing-key-000000" });
+ const { code, reason } = await closeInfo(rogue);
+ assert.equal(code, 4001);
+ assert.equal(reason, "Pairing key mismatch");
- assert.deepEqual(rogue.frames.map((frame) => frame.type), ["auth_challenge"]);
++ assert.deepEqual(rogue.frames.map((frame) => frame.type), ["pairing_challenge"]);
+
assert.equal(bridge.isConnected(), true);
+ assert.equal((await bridge.request("cloud_status", { runId: "safe" })).runId, "safe");
- const rogue = new WebSocket(bridgeUrl());
- let receivedCommands = 0;
- rogue.on("message", () => {
- receivedCommands += 1;
+ extension.close();
+ await bridge.stop();
+});
+
+test("a pairing proof cannot be replayed on another socket", async (t) => {
+ const bridge = new WebBrainBridge();
+ t.after(() => bridge.stop());
+ await bridge.start();
+
+ const first = fakeExtension(bridgeUrl(), () => ({ ok: true, result: {} }));
+ await bridge.waitForExtension(3000);
+ const recordedNonce = first.frames[0].nonce;
+ const recordedProof = proofFor(PAIRING_KEY, recordedNonce);
+ first.close();
+ await once(first, "close");
+
+ const replay = new WebSocket(bridgeUrl());
+ const replayClosed = closeInfo(replay);
+ const [challengeRaw] = await once(replay, "message");
+ const challenge = JSON.parse(challengeRaw.toString());
+ assert.notEqual(challenge.nonce, recordedNonce, "every socket needs a fresh nonce");
+ replay.send(JSON.stringify({ type: "hello", client: "webbrain-extension", protocolVersion: 2, capabilities: [] }));
+ replay.send(JSON.stringify({ type: "auth", scheme: challenge.scheme, proof: recordedProof }));
+ assert.equal((await replayClosed).code, 4001);
+ assert.equal(bridge.isConnected(), false);
+
+ await bridge.stop();
+});
+
+test("the pairing key never crosses the socket and pairing works in either frame order", async (t) => {
+ const bridge = new WebBrainBridge();
+ t.after(() => bridge.stop());
+ await bridge.start();
+
+ // Proof before hello: the bridge must wait for both before trusting the socket.
+ const socket = new WebSocket(bridgeUrl());
+ const seen = [];
+ socket.on("message", (raw) => {
+ const text = raw.toString();
+ seen.push(text);
+ const msg = JSON.parse(text);
- if (msg.type === "auth_challenge") {
- socket.send(JSON.stringify({ type: "auth", scheme: msg.scheme, proof: proofFor(PAIRING_KEY, msg.nonce) }));
++ if (msg.type === "pairing_challenge" || msg.type === "auth_challenge") {
++ socket.send(JSON.stringify({ type: "pairing_proof", scheme: msg.scheme, proof: proofFor(PAIRING_KEY, msg.nonce) }));
+ setTimeout(() => {
+ assert.equal(bridge.isConnected(), false, "a proof without hello must not be enough");
+ socket.send(JSON.stringify({ type: "hello", client: "webbrain-extension", protocolVersion: 2, capabilities: [] }));
+ }, 30);
+ return;
+ }
+ if (msg.action) socket.send(JSON.stringify({ id: msg.id, ok: true, result: { runId: "r", status: "running" } }));
});
- await new Promise((resolve) => rogue.on("open", resolve));
- await new Promise((resolve) => setTimeout(resolve, 20));
+ assert.equal(await bridge.waitForExtension(3000), true);
+ await bridge.request("cloud_status", { runId: "r" });
- assert.equal(bridge.isConnected(), false, "the replacement socket has not sent hello");
- await assert.rejects(
- () => bridge.request("cloud_run", { task: "private task", mode: "ask" }),
- /No WebBrain extension is connected/,
- );
- assert.equal(receivedCommands, 0, "an unverified socket must not receive task frames");
+ assert.equal(JSON.parse(seen[0]).scheme, "hmac-sha256-v1");
+ for (const frame of seen) assert.equal(frame.includes(PAIRING_KEY), false, "the key must never be sent");
- rogue.close();
- extension.close();
+ socket.close();
+ await bridge.stop();
+});
+
+test("a paired reconnect supersedes the previous extension socket", async (t) => {
+ const bridge = new WebBrainBridge();
+ t.after(() => bridge.stop());
+ await bridge.start();
+
+ const first = fakeExtension(bridgeUrl(), () => ({ ok: true, result: { runId: "first" } }));
+ await bridge.waitForExtension(3000);
+ const firstClosed = closeInfo(first);
+
+ const second = fakeExtension(bridgeUrl(), () => ({ ok: true, result: { runId: "second" } }));
+ assert.equal((await firstClosed).code, 1000);
+ assert.equal(bridge.isConnected(), true);
+ assert.equal((await bridge.request("cloud_status", {})).runId, "second");
+
+ second.close();
+ await bridge.stop();
+});
+
+test("a pairing key shorter than 16 characters is refused at start", async () => {
+ const bridge = new WebBrainBridge({ pairingKey: "short" });
+ await assert.rejects(() => bridge.start(), /at least 16 characters/);
await bridge.stop();
});
diff --cc mcp-server/test/task-memory.test.mjs
index c3bdb0ff5,4c9eeae02..d1c37dbd8
--- a/mcp-server/test/task-memory.test.mjs
+++ b/mcp-server/test/task-memory.test.mjs
@@@ -12,29 -11,13 +12,29 @@@ const allocator = createServer()
allocator.listen(0, '127.0.0.1');
await once(allocator, 'listening');
process.env.WEBBRAIN_BRIDGE_PORT = String(allocator.address().port);
+const PAIRING_KEY = 'task-memory-test-pairing-key-0123';
+process.env.WEBBRAIN_BRIDGE_KEY = PAIRING_KEY;
allocator.close();
await once(allocator, 'close');
- const { WebBrainBridge } = await import('../dist/bridge.js');
+ const { WebBrainBridge, MAX_MEMORY_RUN_SCOPES } = await import('../dist/bridge.js');
const { startRun, getStatus, describeSnapshot } = await import('../dist/runs.js');
const { bridgeUrl } = await import('../dist/config.js');
const { validateTaskMemory, redactTaskMemory, redactMemoryRunResponse, taskMemoryPrivateValues } = await import('../dist/task-memory.js');
+// Stand-in extension socket: sends hello and answers the pairing challenge.
+// The tests' own message handlers also see the challenge and skip frames without an action.
+function pairedExtension(url, capabilities) {
+ const socket = new WebSocket(url);
+ socket.on('open', () => socket.send(JSON.stringify({ type: 'hello', client: 'webbrain-extension', protocolVersion: 2, capabilities })));
+ socket.on('message', raw => {
+ const msg = JSON.parse(raw.toString());
- if (msg.type !== 'auth_challenge') return;
++ if (msg.type !== 'pairing_challenge' && msg.type !== 'auth_challenge') return;
+ const proof = createHmac('sha256', PAIRING_KEY).update('webbrain-bridge-pairing-v1:' + msg.nonce).digest('hex');
- socket.send(JSON.stringify({ type: 'auth', scheme: msg.scheme, proof }));
++ socket.send(JSON.stringify({ type: 'pairing_proof', scheme: msg.scheme, proof }));
+ });
+ return socket;
+}
+
const memory = {
version: 1, botId: 'bot-owned', runId: 'app-run-1', policyVersion: 1,
callbackUrl: 'http://127.0.0.1:4174/api/internal/bot-memory/app-run-1',
@@@ -150,6 -135,94 +150,103 @@@ test('memory values survive failure an
} finally { first.close(); second?.close(); await bridge.stop(); }
});
+ const memoryFor = runId => ({ ...memory, runId, callbackUrl: `http://127.0.0.1:4174/api/internal/bot-memory/${runId}`,
+ callbackToken: `private-scoped-callback-token-${runId}`, context: { notes: `private-note-${runId}` } });
+ const memoryExtension = reply => {
+ const socket = new WebSocket(bridgeUrl());
+ socket.on('open', () => socket.send(JSON.stringify({ type: 'hello', client: 'webbrain-extension', protocolVersion: 2, capabilities: ['bot_memory_v1'] })));
- socket.on('message', raw => { const msg = JSON.parse(raw.toString()); socket.send(JSON.stringify({ id: msg.id, ...reply(msg) })); });
++ socket.on('message', raw => {
++ const msg = JSON.parse(raw.toString());
++ if (msg.type === 'pairing_challenge' || msg.type === 'auth_challenge') {
++ const proof = createHmac('sha256', PAIRING_KEY).update('webbrain-bridge-pairing-v1:' + msg.nonce).digest('hex');
++ socket.send(JSON.stringify({ type: 'pairing_proof', scheme: msg.scheme, proof }));
++ return;
++ }
++ if (!msg.action) return;
++ socket.send(JSON.stringify({ id: msg.id, ...reply(msg) }));
++ });
+ return socket;
+ };
+ const assertBoundedScopes = bridge => {
+ assert.ok(bridge.memoryRuns.size <= MAX_MEMORY_RUN_SCOPES);
+ assert.ok(bridge.memoryRunValues.size <= MAX_MEMORY_RUN_SCOPES);
+ assert.ok(bridge.memoryProtectedRunIds.size <= MAX_MEMORY_RUN_SCOPES);
+ assert.ok(bridge.memoryPrivateValues.size <= 2 * MAX_MEMORY_RUN_SCOPES);
+ };
+
+ test('one long-lived bridge keeps accepting sequential memory runs while retained memory stays bounded', async () => {
+ const bridge = new WebBrainBridge();
+ await bridge.start();
+ const extension = memoryExtension(msg => ({ ok: true, result: msg.action === 'cloud_run'
+ ? { runId: msg.payload.runId, status: 'running' }
+ : { runId: msg.payload.runId, status: 'completed', content: `Finished private-note-${msg.payload.runId}` } }));
+ const total = 2 * MAX_MEMORY_RUN_SCOPES + 10;
+ try {
+ assert.equal(await bridge.waitForExtension(3000), true);
+ for (let i = 0; i < total; i++) {
+ const runId = `sequential-${i}`;
+ const privateMemory = memoryFor(runId);
+ await startRun(bridge, { runId, task: 'Check the page', mode: 'act', taskMemory: privateMemory });
+ const settled = await getStatus(bridge, runId);
+ assert.equal(settled.status, 'completed');
+ for (const secret of [privateMemory.callbackToken, privateMemory.context.notes]) assert.equal(JSON.stringify(settled).includes(secret), false);
+ }
+ assertBoundedScopes(bridge);
+ const latest = `sequential-${total - 1}`;
+ assert.equal(JSON.stringify(await getStatus(bridge, latest)).includes(`private-note-${latest}`), false);
+ } finally { extension.close(); await bridge.stop(); }
+ });
+
+ test('unfinished memory runs keep their scopes; a full bridge rereads the run list before refusing', async () => {
+ const bridge = new WebBrainBridge();
+ await bridge.start();
+ const states = new Map();
+ const sent = [];
+ const extension = memoryExtension(msg => {
+ sent.push(msg);
+ const { runId } = msg.payload;
+ if (msg.action === 'cloud_run') { states.set(runId, 'running'); return { ok: true, result: { runId, status: 'running' } }; }
+ if (!runId) return { ok: true, result: { runs: [...states].map(([id, status]) => ({ runId: id, status })) } };
+ return { ok: true, result: { runId, status: states.get(runId), content: `Working on private-note-${runId}` } };
+ });
+ const starts = () => sent.filter(msg => msg.action === 'cloud_run').length;
+ const start = runId => startRun(bridge, { runId, task: 'Check the page', mode: 'act', taskMemory: memoryFor(runId) });
+ try {
+ assert.equal(await bridge.waitForExtension(3000), true);
+ for (let i = 0; i < MAX_MEMORY_RUN_SCOPES; i++) await start(`live-${i}`);
+ await assert.rejects(start('overflow'), error => error.status === 409 && /unfinished/.test(error.message));
+ assert.equal(starts(), MAX_MEMORY_RUN_SCOPES);
+ assert.deepEqual(sent.at(-1), { id: sent.at(-1).id, action: 'cloud_status', payload: {} });
+ assert.equal(JSON.stringify(await getStatus(bridge, 'live-0')).includes('private-note-live-0'), false);
+ // Finished without anyone polling it; only the run list reveals that.
+ states.set('live-7', 'completed');
+ await start('after-finish');
+ assert.equal(starts(), MAX_MEMORY_RUN_SCOPES + 1);
+ assert.equal(bridge.memoryRuns.has('live-7'), false);
+ assertBoundedScopes(bridge);
+ for (const runId of ['live-0', 'live-8', 'after-finish']) {
+ assert.equal(JSON.stringify(await getStatus(bridge, runId)).includes(`private-note-${runId}`), false);
+ }
+ } finally { extension.close(); await bridge.stop(); }
+ });
+
+ test('memory starts the extension refuses never exhaust bridge capacity', async () => {
+ const bridge = new WebBrainBridge();
+ await bridge.start();
+ const extension = memoryExtension(msg => msg.action === 'cloud_run'
+ ? { ok: false, status: 409, error: `Tab is busy for private-note-${msg.payload.runId}` }
+ : { ok: true, result: { runs: [] } });
+ try {
+ assert.equal(await bridge.waitForExtension(3000), true);
+ for (let i = 0; i < MAX_MEMORY_RUN_SCOPES + 10; i++) {
+ const runId = `refused-${i}`;
+ await assert.rejects(startRun(bridge, { runId, task: 'Check the page', mode: 'act', taskMemory: memoryFor(runId) }),
+ error => error.status === 409 && /Tab is busy/.test(error.message) && !error.message.includes(`private-note-${runId}`));
+ }
+ assertBoundedScopes(bridge);
+ } finally { extension.close(); await bridge.stop(); }
+ });
+
test('MCP rejects protected runs on old bridges before dispatch; ordinary calls are unchanged', async () => {
const calls = [];
const bridge = { capabilities: () => [], async request(action, payload) { calls.push({ action, payload }); return { runId: 'ordinary', status: 'running' }; } };
diff --cc src/chrome/src/background.js
index e49ff25d1,cf69998f5..e5a429d7b
--- a/src/chrome/src/background.js
+++ b/src/chrome/src/background.js
@@@ -1402,7 -1416,7 +1416,8 @@@ chrome.storage.onChanged.addListener((c
if (changes.providers || changes.activeProvider || changes.helpImproveWebBrain) providerManager.load().catch(() => {});
if (changes.webbrainCloudBridgeEnabled || changes.webbrainCloudBridgeUrl
|| changes.webbrainCloudBridgeToken || changes.webbrainCloudBridgeBrowserId
- || changes.webbrainCloudBridgeLegacyBearerAuth) {
++ || changes.webbrainCloudBridgeLegacyBearerAuth
+ || changes.webbrainCloudBridgePairingKey) {
cloudRunController.syncBridge().catch(() => {});
}
if (changes.maxAgentSteps) {
diff --cc src/chrome/src/cloud-runs.js
index 3d313dfb7,b981b1aa4..2d0a1f725
--- a/src/chrome/src/cloud-runs.js
+++ b/src/chrome/src/cloud-runs.js
@@@ -2008,14 -2010,16 +2011,18 @@@ export function createCloudRunControlle
const stored = await api.storage.local.get([
'webbrainCloudBridgeToken',
'webbrainCloudBridgeBrowserId',
+ 'webbrainCloudBridgePairingKey',
+ 'webbrainCloudBridgeLegacyBearerAuth',
]);
return {
token: stored.webbrainCloudBridgeToken || '',
browserId: stored.webbrainCloudBridgeBrowserId || installationId,
installationId,
extensionVersion: api.runtime.getManifest?.().version || '',
+ pairingKey: stored.webbrainCloudBridgePairingKey || '',
+ // Deprecated opt-in for controllers that only accept the token in the
+ // hello; off unless explicitly set (docs/cloud-bridge-browser-approval.md).
+ legacyBearerAuth: stored.webbrainCloudBridgeLegacyBearerAuth === true,
};
}
diff --cc src/chrome/src/offscreen/cloud-bridge.js
index c70dba6f4,f2d3471a3..86139d54e
--- a/src/chrome/src/offscreen/cloud-bridge.js
+++ b/src/chrome/src/offscreen/cloud-bridge.js
@@@ -24,13 -24,15 +24,22 @@@
'cloud_pause',
'cloud_resume',
]);
+ // Local bridges (the MCP server and the LM Studio plugin) challenge each new
+ // socket with a nonce and only trust it after it returns this HMAC, keyed by
+ // the pairing key the user pasted in Settings. The key never crosses the
+ // socket. Keep in sync with mcp-server/src/pairing.ts.
+ const PAIRING_SCHEME = 'hmac-sha256-v1';
+ const PAIRING_PROOF_LABEL = 'webbrain-bridge-pairing-v1:';
+ const PAIRING_CLOSE_CODE = 4001;
+ // A token-configured controller must pass a mutual HMAC challenge
+ // (docs/cloud-bridge-browser-approval.md). The token never crosses the
+ // socket: whoever answers on the loopback port proves it knows the token
+ // first, and only then does the extension prove itself and reveal its
+ // browser and installation IDs. A process that wins the port learns nothing
+ // it can replay and cannot move the socket to `approved`.
+ const BRIDGE_AUTH_METHOD = 'hmac-sha256-v1';
+ const BRIDGE_AUTH_LABEL = 'webbrain-bridge-auth-v1';
+ const HEX_256 = /^[0-9a-f]{64}$/;
let socket = null;
let bridgeUrl = null;
let enabled = false;
@@@ -39,9 -41,11 +48,13 @@@
let lastError = '';
// Browser registration/approval. Identity is pushed by the background worker
// with `cloud-bridge-start` (the offscreen page has no storage access). When
- // a token is configured the backend must approve each new socket before any
- // cloud_* command runs; without a token the legacy local behaviour is kept.
- let identity = { token: '', browserId: '', installationId: '', extensionVersion: '', pairingKey: '' };
+ // a token is configured the backend must authenticate and then approve each
+ // new socket before any cloud_* command runs; without a token the legacy
+ // local behaviour is kept. `legacyBearerAuth` is the deprecated opt-in that
+ // still sends the token in the hello for controllers without the challenge.
- let identity = { token: '', browserId: '', installationId: '', extensionVersion: '', legacyBearerAuth: false };
++ // `pairingKey` is independent of the token: it answers the pairing challenge
++ // that the local MCP / LM Studio bridges send to authenticate the extension.
++ let identity = { token: '', browserId: '', installationId: '', extensionVersion: '', legacyBearerAuth: false, pairingKey: '' };
let approval = 'not_required'; // not_required | pending | approved | rejected
function browserInfo() {
@@@ -90,23 -94,51 +103,68 @@@
}
}
+ async function pairingProof(key, nonce) {
+ const encoder = new TextEncoder();
+ const hmacKey = await crypto.subtle.importKey('raw', encoder.encode(key), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
+ const mac = await crypto.subtle.sign('HMAC', hmacKey, encoder.encode(PAIRING_PROOF_LABEL + nonce));
+ return Array.from(new Uint8Array(mac), (byte) => byte.toString(16).padStart(2, '0')).join('');
+ }
+
+ // A pairing failure needs the user to fix Settings; reconnecting would only
+ // repeat it. Saving Settings or "Save & test" starts a fresh attempt.
+ function failPairing(target, reason) {
+ approval = 'rejected';
+ lastError = reason;
+ if (reconnectTimer) clearTimeout(reconnectTimer);
+ reconnectTimer = null;
+ try { target.close(); } catch {}
+ }
+
+ function authMode() {
+ if (!identity.token) return 'none';
+ return identity.legacyBearerAuth ? 'legacy_bearer' : 'challenge';
+ }
+
+ const utf8 = (value) => new TextEncoder().encode(value);
+ const toHex = (bytes) => Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, '0')).join('');
+ const fromHex = (hex) => Uint8Array.from(hex.match(/../g), (pair) => parseInt(pair, 16));
+ const hmacKey = (token, usage) => crypto.subtle.importKey('raw', utf8(token), { name: 'HMAC', hash: 'SHA-256' }, false, [usage]);
+ // A JSON array keeps the role, the nonces and the identity unambiguous.
+ const authTranscript = (...parts) => utf8(JSON.stringify([BRIDGE_AUTH_LABEL, ...parts]));
+
+ async function answerAuthChallenge(msg, target, auth) {
+ // One challenge per socket, and only after our own nonce went out.
+ if (auth.mode !== 'challenge' || auth.state !== 'awaiting_controller') return;
+ auth.state = 'verifying';
+ const { token, browserId, installationId } = identity;
+ let proof = '';
+ try {
+ const verified = msg.method === BRIDGE_AUTH_METHOD
+ && typeof msg.nonce === 'string' && HEX_256.test(msg.nonce)
+ && typeof msg.proof === 'string' && HEX_256.test(msg.proof)
+ && await crypto.subtle.verify('HMAC', await hmacKey(token, 'verify'), fromHex(msg.proof),
+ authTranscript('controller', auth.nonce, msg.nonce));
+ if (verified) {
+ proof = toHex(await crypto.subtle.sign('HMAC', await hmacKey(token, 'sign'),
+ authTranscript('extension', auth.nonce, msg.nonce, browserId, installationId)));
+ }
+ } catch {
+ proof = '';
+ }
+ if (socket !== target) return;
+ if (!proof) {
+ // Not the controller this token belongs to: answer nothing and retry
+ // with backoff, in case the real controller gets its port back.
+ auth.state = 'failed';
+ lastError = 'Bridge controller failed authentication';
+ try { target.close(); } catch {}
+ return;
+ }
+ auth.state = 'verified';
+ reconnectAttempt = 0;
+ sendJson({ type: 'auth_response', method: BRIDGE_AUTH_METHOD, proof, browserId, installationId }, target);
+ }
+
function scheduleReconnect() {
if (!enabled || !bridgeUrl || reconnectTimer) return;
const delay = Math.min(30000, 500 * Math.pow(2, reconnectAttempt++));
@@@ -160,25 -205,16 +231,37 @@@
}
if (msg.type === 'auth_challenge') {
+ await answerAuthChallenge(msg, nextSocket, auth);
+ return;
+ }
+
++ // The local MCP / LM Studio bridges authenticate the extension with a
++ // separate pairing challenge. It has its own message types so it can
++ // never be confused with the controller auth_challenge above.
++ if (msg.type === 'pairing_challenge') {
+ if (msg.scheme !== PAIRING_SCHEME || typeof msg.nonce !== 'string' || !msg.nonce || msg.nonce.length > 256) return;
+ if (!identity.pairingKey) {
+ failPairing(nextSocket, 'This bridge requires a pairing key. Paste it under Settings β†’ Bridge β†’ Pairing key.');
+ return;
+ }
+ let proof;
+ try {
+ proof = await pairingProof(identity.pairingKey, msg.nonce);
+ } catch (e) {
+ failPairing(nextSocket, `Could not compute the pairing proof: ${e.message || e}`);
+ return;
+ }
+ if (socket !== nextSocket) return;
- sendJson({ type: 'auth', scheme: PAIRING_SCHEME, proof }, nextSocket);
++ sendJson({ type: 'pairing_proof', scheme: PAIRING_SCHEME, proof }, nextSocket);
+ return;
+ }
+
if (msg.type === 'connection_pending' || msg.type === 'connection_approved' || msg.type === 'connection_rejected') {
if (!identity.token) return;
+ // Only a controller that proved the token may move a challenged
+ // socket toward approval. A rejection only takes rights away, so it
+ // is honoured from anyone.
+ if (auth.mode === 'challenge' && auth.state !== 'verified' && msg.type !== 'connection_rejected') return;
if (msg.browserId && msg.browserId !== identity.browserId) return;
if (msg.type === 'connection_pending') {
if (approval !== 'approved') approval = 'pending';
@@@ -269,7 -302,7 +353,8 @@@
browserId: String(msg.browserId || ''),
installationId: String(msg.installationId || ''),
extensionVersion: String(msg.extensionVersion || ''),
+ pairingKey: String(msg.pairingKey || '').trim(),
+ legacyBearerAuth: msg.legacyBearerAuth === true,
};
const identityChanged = JSON.stringify(nextIdentity) !== JSON.stringify(identity);
const changed = (bridgeUrl && bridgeUrl !== nextUrl) || identityChanged;
diff --cc src/firefox/src/background.js
index 0d1058b3d,61595c9d5..205b13f1d
--- a/src/firefox/src/background.js
+++ b/src/firefox/src/background.js
@@@ -1282,7 -1300,7 +1300,8 @@@ browser.storage.onChanged.addListener((
}
if (changes.webbrainCloudBridgeEnabled || changes.webbrainCloudBridgeUrl
|| changes.webbrainCloudBridgeToken || changes.webbrainCloudBridgeBrowserId
- || changes.webbrainCloudBridgeLegacyBearerAuth) {
++ || changes.webbrainCloudBridgeLegacyBearerAuth
+ || changes.webbrainCloudBridgePairingKey) {
cloudRunController.syncBridge().catch(() => {});
}
if (areaName === 'local' && changes.browserBatchEnabled) {
diff --cc src/firefox/src/cloud-bridge.js
index 440b355a6,6109c62a2..48bf60598
--- a/src/firefox/src/cloud-bridge.js
+++ b/src/firefox/src/cloud-bridge.js
@@@ -21,21 -21,23 +21,38 @@@ const ALLOWED_BRIDGE_ACTIONS = new Set(
'cloud_pause',
'cloud_resume',
]);
+// Local bridges (the MCP server and the LM Studio plugin) challenge each new
+// socket with a nonce and only trust it after it returns this HMAC, keyed by
+// the pairing key the user pasted in Settings. The key never crosses the
+// socket. Keep in sync with mcp-server/src/pairing.ts.
+const PAIRING_SCHEME = 'hmac-sha256-v1';
+const PAIRING_PROOF_LABEL = 'webbrain-bridge-pairing-v1:';
+const PAIRING_CLOSE_CODE = 4001;
+
+async function pairingProof(key, nonce) {
+ const encoder = new TextEncoder();
+ const hmacKey = await crypto.subtle.importKey('raw', encoder.encode(key), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
+ const mac = await crypto.subtle.sign('HMAC', hmacKey, encoder.encode(PAIRING_PROOF_LABEL + nonce));
+ return Array.from(new Uint8Array(mac), (byte) => byte.toString(16).padStart(2, '0')).join('');
+}
+
+ // A token-configured controller must pass a mutual HMAC challenge
+ // (docs/cloud-bridge-browser-approval.md). The token never crosses the
+ // socket: whoever answers on the loopback port proves it knows the token
+ // first, and only then does the extension prove itself and reveal its
+ // browser and installation IDs. A process that wins the port learns nothing
+ // it can replay and cannot move the socket to `approved`.
+ const BRIDGE_AUTH_METHOD = 'hmac-sha256-v1';
+ const BRIDGE_AUTH_LABEL = 'webbrain-bridge-auth-v1';
+ const HEX_256 = /^[0-9a-f]{64}$/;
+
+ const utf8 = (value) => new TextEncoder().encode(value);
+ const toHex = (bytes) => Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, '0')).join('');
+ const fromHex = (hex) => Uint8Array.from(hex.match(/../g), (pair) => parseInt(pair, 16));
+ const hmacKey = (token, usage) => crypto.subtle.importKey('raw', utf8(token), { name: 'HMAC', hash: 'SHA-256' }, false, [usage]);
+ // A JSON array keeps the role, the nonces and the identity unambiguous.
+ const authTranscript = (...parts) => utf8(JSON.stringify([BRIDGE_AUTH_LABEL, ...parts]));
+
export function createCloudBridge({ dispatch, WebSocketImpl = globalThis.WebSocket, nav = globalThis.navigator } = {}) {
let socket = null;
let bridgeUrl = null;
@@@ -43,9 -45,11 +60,13 @@@
let reconnectTimer = null;
let reconnectAttempt = 0;
let lastError = '';
- // With a token configured the backend must approve each new socket before
- // any cloud_* command runs; without one the legacy local behaviour is kept.
- let identity = { token: '', browserId: '', installationId: '', extensionVersion: '', pairingKey: '' };
+ // With a token configured the backend must authenticate and then approve
+ // each new socket before any cloud_* command runs; without one the legacy
+ // local behaviour is kept. `legacyBearerAuth` is the deprecated opt-in that
+ // still sends the token in the hello for controllers without the challenge.
- let identity = { token: '', browserId: '', installationId: '', extensionVersion: '', legacyBearerAuth: false };
++ // `pairingKey` is independent of the token: it answers the pairing challenge
++ // that the local MCP / LM Studio bridges send to authenticate the extension.
++ let identity = { token: '', browserId: '', installationId: '', extensionVersion: '', legacyBearerAuth: false, pairingKey: '' };
let approval = 'not_required'; // not_required | pending | approved | rejected
function browserInfo() {
@@@ -86,16 -90,44 +107,54 @@@
}
}
+ // A pairing failure needs the user to fix Settings; reconnecting would only
+ // repeat it. Saving Settings or "Save & test" starts a fresh attempt.
+ function failPairing(target, reason) {
+ approval = 'rejected';
+ lastError = reason;
+ if (reconnectTimer) clearTimeout(reconnectTimer);
+ reconnectTimer = null;
+ try { target.close(); } catch {}
+ }
+
+ function authMode() {
+ if (!identity.token) return 'none';
+ return identity.legacyBearerAuth ? 'legacy_bearer' : 'challenge';
+ }
+
+ async function answerAuthChallenge(msg, target, auth) {
+ // One challenge per socket, and only after our own nonce went out.
+ if (auth.mode !== 'challenge' || auth.state !== 'awaiting_controller') return;
+ auth.state = 'verifying';
+ const { token, browserId, installationId } = identity;
+ let proof = '';
+ try {
+ const verified = msg.method === BRIDGE_AUTH_METHOD
+ && typeof msg.nonce === 'string' && HEX_256.test(msg.nonce)
+ && typeof msg.proof === 'string' && HEX_256.test(msg.proof)
+ && await crypto.subtle.verify('HMAC', await hmacKey(token, 'verify'), fromHex(msg.proof),
+ authTranscript('controller', auth.nonce, msg.nonce));
+ if (verified) {
+ proof = toHex(await crypto.subtle.sign('HMAC', await hmacKey(token, 'sign'),
+ authTranscript('extension', auth.nonce, msg.nonce, browserId, installationId)));
+ }
+ } catch {
+ proof = '';
+ }
+ if (socket !== target) return;
+ if (!proof) {
+ // Not the controller this token belongs to: answer nothing and retry
+ // with backoff, in case the real controller gets its port back.
+ auth.state = 'failed';
+ lastError = 'Bridge controller failed authentication';
+ try { target.close(); } catch {}
+ return;
+ }
+ auth.state = 'verified';
+ reconnectAttempt = 0;
+ sendJson({ type: 'auth_response', method: BRIDGE_AUTH_METHOD, proof, browserId, installationId }, target);
+ }
+
function scheduleReconnect() {
if (!enabled || !bridgeUrl || reconnectTimer) return;
const delay = Math.min(30000, 500 * Math.pow(2, reconnectAttempt++));
@@@ -149,25 -194,16 +221,37 @@@
}
if (msg.type === 'auth_challenge') {
+ await answerAuthChallenge(msg, nextSocket, auth);
+ return;
+ }
+
++ // The local MCP / LM Studio bridges authenticate the extension with a
++ // separate pairing challenge. It has its own message types so it can
++ // never be confused with the controller auth_challenge above.
++ if (msg.type === 'pairing_challenge') {
+ if (msg.scheme !== PAIRING_SCHEME || typeof msg.nonce !== 'string' || !msg.nonce || msg.nonce.length > 256) return;
+ if (!identity.pairingKey) {
+ failPairing(nextSocket, 'This bridge requires a pairing key. Paste it under Settings β†’ Bridge β†’ Pairing key.');
+ return;
+ }
+ let proof;
+ try {
+ proof = await pairingProof(identity.pairingKey, msg.nonce);
+ } catch (e) {
+ failPairing(nextSocket, `Could not compute the pairing proof: ${e.message || e}`);
+ return;
+ }
+ if (socket !== nextSocket) return;
- sendJson({ type: 'auth', scheme: PAIRING_SCHEME, proof }, nextSocket);
++ sendJson({ type: 'pairing_proof', scheme: PAIRING_SCHEME, proof }, nextSocket);
+ return;
+ }
+
if (msg.type === 'connection_pending' || msg.type === 'connection_approved' || msg.type === 'connection_rejected') {
if (!identity.token) return;
+ // Only a controller that proved the token may move a challenged
+ // socket toward approval. A rejection only takes rights away, so it
+ // is honoured from anyone.
+ if (auth.mode === 'challenge' && auth.state !== 'verified' && msg.type !== 'connection_rejected') return;
if (msg.browserId && msg.browserId !== identity.browserId) return;
if (msg.type === 'connection_pending') {
if (approval !== 'approved') approval = 'pending';
@@@ -251,7 -284,7 +336,8 @@@
browserId: String(msg.browserId || ''),
installationId: String(msg.installationId || ''),
extensionVersion: String(msg.extensionVersion || ''),
+ pairingKey: String(msg.pairingKey || '').trim(),
+ legacyBearerAuth: msg.legacyBearerAuth === true,
};
const identityChanged = JSON.stringify(nextIdentity) !== JSON.stringify(identity);
const changed = (bridgeUrl && bridgeUrl !== nextUrl) || identityChanged;
diff --cc src/firefox/src/cloud-runs.js
index 21d0b7a7f,3a911c430..0931f9938
--- a/src/firefox/src/cloud-runs.js
+++ b/src/firefox/src/cloud-runs.js
@@@ -2009,14 -2011,16 +2012,18 @@@ export function createCloudRunControlle
const stored = await api.storage.local.get([
'webbrainCloudBridgeToken',
'webbrainCloudBridgeBrowserId',
+ 'webbrainCloudBridgePairingKey',
+ 'webbrainCloudBridgeLegacyBearerAuth',
]);
return {
token: stored.webbrainCloudBridgeToken || '',
browserId: stored.webbrainCloudBridgeBrowserId || installationId,
installationId,
extensionVersion: api.runtime.getManifest?.().version || '',
+ pairingKey: stored.webbrainCloudBridgePairingKey || '',
+ // Deprecated opt-in for controllers that only accept the token in the
+ // hello; off unless explicitly set (docs/cloud-bridge-browser-approval.md).
+ legacyBearerAuth: stored.webbrainCloudBridgeLegacyBearerAuth === true,
};
}
diff --cc test/cloud-bridge-approval.mjs
index 316e7a6f6,7d99eb539..3949dfb45
--- a/test/cloud-bridge-approval.mjs
+++ b/test/cloud-bridge-approval.mjs
@@@ -424,112 -611,28 +611,136 @@@ for (const [label, createController] o
assert.equal(ids.size, 1, 'all concurrent starts must use the same installation id');
assert.equal([...ids][0], store.webbrainCloudBridgeInstallationId, 'and it matches the persisted one');
});
+
+ test(`${label}: the deprecated bearer hello is off unless the legacy flag is stored as true`, async () => {
+ const { createCloudRunController: make } = label === 'chrome'
+ ? await import('../src/chrome/src/cloud-runs.js')
+ : { createCloudRunController: createController };
+ const store = { webbrainCloudBridgeEnabled: true, webbrainCloudBridgeToken: 'tok' };
+ const started = [];
+ const api = {
+ storage: { local: {
+ get: async (keys) => Object.fromEntries([].concat(keys).map(k => [k, store[k]]).filter(([, v]) => v !== undefined)),
+ set: async (obj) => { Object.assign(store, obj); },
+ } },
+ runtime: { getManifest: () => ({ version: '1.0.0' }), sendMessage: async (m) => { started.push(m); return {}; } },
+ };
+ const bridge = { start: (m) => { started.push(m); return {}; }, stop: () => ({}), status: () => ({}) };
+ const controller = make({ chromeApi: api, agent: {}, ensureOffscreen: async () => {}, bridge });
+ for (const value of [undefined, 'true', 1, true]) {
+ if (value === undefined) delete store.webbrainCloudBridgeLegacyBearerAuth;
+ else store.webbrainCloudBridgeLegacyBearerAuth = value;
+ await controller.syncBridge();
+ assert.equal(started.at(-1).legacyBearerAuth, value === true, `only an explicit true opts in (${JSON.stringify(value)})`);
+ assert.equal(started.at(-1).token, 'tok');
+ }
+ });
}
+
+// ---- Local bridge pairing (MCP server / LM Studio plugin) ----
+// Same vector as mcp-server/test/pairing.test.mjs and the LM Studio test, so
+// the extension and both servers cannot drift apart.
+const PAIRING_VECTOR = {
+ key: 'webbrain-pairing-test-vector-key',
+ nonce: 'fixed-nonce-for-cross-checks',
+ proof: '5d2a446bcc1734f26d8b94e20d3329a07fb2513aa6d036f47f687065d33c55da',
+};
- const challenge = { type: 'auth_challenge', scheme: 'hmac-sha256-v1', nonce: PAIRING_VECTOR.nonce };
++const challenge = { type: 'pairing_challenge', scheme: 'hmac-sha256-v1', nonce: PAIRING_VECTOR.nonce };
+
+async function until(predicate) {
+ for (let i = 0; i < 100 && !predicate(); i++) await tick(10);
+ assert.ok(predicate(), 'condition not reached');
+}
+
+function pairingHarness(build) {
+ if (build === 'chrome') {
+ const h = harness();
+ return { ...h, start: (extra) => h.start(extra), stop: () => {}, reconnects: () => h.timers.filter(timer => !timer.cleared).length };
+ }
+ const h = fxHarness();
+ return {
+ sockets: h.sockets,
+ start: (extra) => h.bridge.start({ url: 'ws://127.0.0.1:17374/extension', ...extra }),
+ status: () => h.bridge.status(),
+ stop: () => h.bridge.stop(),
+ reconnects: () => h.sockets.length - 1,
+ };
+}
+
+for (const build of ['chrome', 'firefox']) {
+ test(`${build}: answers the bridge pairing challenge with an HMAC and never sends the key`, async () => {
+ const h = pairingHarness(build);
+ try {
+ h.start({ pairingKey: PAIRING_VECTOR.key });
+ const socket = h.sockets[0];
+ socket.emit('open');
+ assert.equal(socket.sent[0].type, 'hello');
+ await socket.receive(challenge);
- await until(() => socket.sent.some(frame => frame.type === 'auth'));
- const auth = socket.sent.find(frame => frame.type === 'auth');
- assert.deepEqual({ ...auth }, { type: 'auth', scheme: 'hmac-sha256-v1', proof: PAIRING_VECTOR.proof });
++ await until(() => socket.sent.some(frame => frame.type === 'pairing_proof'));
++ const auth = socket.sent.find(frame => frame.type === 'pairing_proof');
++ assert.deepEqual({ ...auth }, { type: 'pairing_proof', scheme: 'hmac-sha256-v1', proof: PAIRING_VECTOR.proof });
+ assert.equal(JSON.stringify(socket.sent).includes(PAIRING_VECTOR.key), false, 'the key must not cross the socket');
+ assert.equal(JSON.stringify(h.status()).includes(PAIRING_VECTOR.key), false, 'status must not expose the key');
+ assert.equal(h.status().connected, true);
+
+ const before = socket.sent.length;
+ await socket.receive({ ...challenge, scheme: 'plain-v0' });
+ await socket.receive({ ...challenge, nonce: 'x'.repeat(257) });
+ await tick(20);
+ assert.equal(socket.sent.length, before, 'unknown schemes and oversized nonces are ignored');
+ } finally { h.stop(); }
+ });
+
+ test(`${build}: a challenge without a pairing key stops the bridge with a clear error`, async () => {
+ const h = pairingHarness(build);
+ try {
+ h.start({});
+ const socket = h.sockets[0];
+ socket.emit('open');
+ await socket.receive(challenge);
+ assert.equal(h.status().approval, 'rejected');
+ assert.match(h.status().lastError, /requires a pairing key/);
- assert.equal(socket.sent.some(frame => frame.type === 'auth'), false);
++ assert.equal(socket.sent.some(frame => frame.type === 'pairing_proof'), false);
+ if (build === 'firefox') await tick(700); // first backoff is 500 ms
+ assert.equal(h.reconnects(), 0, 'a missing key must not reconnect in a loop');
+ } finally { h.stop(); }
+ });
+
+ test(`${build}: a pairing refusal from the bridge is final until the settings change`, async () => {
+ const h = pairingHarness(build);
+ try {
+ h.start({ pairingKey: 'an-old-pairing-key-0000' });
+ h.sockets[0].emit('open');
+ h.sockets[0].emit('close', { code: 4001, reason: 'Pairing key mismatch' });
+ assert.equal(h.status().approval, 'rejected');
+ assert.equal(h.status().lastError, 'Pairing key mismatch');
+ if (build === 'firefox') await tick(700);
+ assert.equal(h.reconnects(), 0, 'a refused key must not reconnect in a loop');
+
+ h.start({ pairingKey: PAIRING_VECTOR.key });
+ assert.equal(h.sockets.length, 2, 'pasting a new key reconnects immediately');
+ } finally { h.stop(); }
+ });
+}
+
+for (const [label, loadController] of [
+ ['chrome', async () => (await import('../src/chrome/src/cloud-runs.js')).createCloudRunController],
+ ['firefox', async () => createFxController],
+]) {
+ test(`${label}: controller passes the stored pairing key to the bridge`, async () => {
+ const make = await loadController();
+ const store = { webbrainCloudBridgeEnabled: true, webbrainCloudBridgePairingKey: 'stored-pairing-key-0123' };
+ const started = [];
+ const api = {
+ storage: { local: {
+ get: async (keys) => Object.fromEntries([].concat(keys).map(k => [k, store[k]]).filter(([, v]) => v !== undefined)),
+ set: async (obj) => { Object.assign(store, obj); },
+ } },
+ runtime: { getManifest: () => ({ version: '1.0.0' }), sendMessage: async (m) => { started.push(m); return {}; } },
+ };
+ const bridge = { start: (m) => { started.push(m); return {}; }, stop: () => ({}), status: () => ({}) };
+ const controller = make({ chromeApi: api, agent: {}, ensureOffscreen: async () => {}, bridge });
+ await controller.syncBridge();
+ assert.equal(started[0].pairingKey, 'stored-pairing-key-0123');
+ });
+}