Skip to content

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

Pair the extension with the MCP and LM Studio bridges before trusting it

Barack Sokullu92511676188e
diff --git a/README.md b/README.md
index 915fbd64b..b25305da5 100644
--- a/README.md
+++ b/README.md
@@ -313,7 +313,13 @@ npx -y @webbrain/mcp-server
```
Once the server is running, open **WebBrain → Settings → Bridge**,
-set the URL to `ws://127.0.0.1:17374/extension`, and enable it.
+set the URL to `ws://127.0.0.1:17374/extension`, paste the pairing key printed by
+`npx -y @webbrain/mcp-server pairing-key` into **Pairing key**, and enable it.
+The server only trusts a socket that proves it holds that key (an HMAC over a
+fresh challenge; the key is never sent), so another local process cannot pose
+as the extension. The LM Studio plugin uses the same key file,
+`~/.webbrain/bridge-key`. Update the extension before upgrading the server: a
+version without the Pairing key field cannot pair.
On Chromium browsers the bridge runs from the extension's off-screen document.
Firefox hosts it in the background page and is configured under the same
**Settings → Bridge** tab (not yet verified against the MCP server on a real Firefox
diff --git a/docs/cloud-bridge-browser-approval.md b/docs/cloud-bridge-browser-approval.md
index 472437280..8a5975467 100644
--- a/docs/cloud-bridge-browser-approval.md
+++ b/docs/cloud-bridge-browser-approval.md
@@ -113,6 +113,18 @@ contract, credential handling, and image-upgrade checks.
Approval belongs to one WebSocket. Every new socket (reconnect, URL/identity change) starts `pending`, resends `hello`, and must be approved again.
+## 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.
+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).
+
## Local test server
`examples/cloud-bridge-approval-server.mjs` is a dependency-free backend for testing:
diff --git a/docs/security-model.md b/docs/security-model.md
index 1bc3e8090..fa899996d 100644
--- a/docs/security-model.md
+++ b/docs/security-model.md
@@ -201,6 +201,10 @@ The Cloud Bridge lets a controller send `cloud_*` run commands to the browser. B
**Where it stops.** The permission prompts raised during a cloud run (navigate, click, …) are answered by the backend through `cloud_respond`, including "always". An approved backend is therefore effectively an operator of that browser. Approval is per socket and is not persisted. The backend can revoke it with `connection_rejected`, which closes the socket and stops auto-reconnect. Disabling the bridge or changing its URL or identity also closes the active socket; a replacement needs fresh approval if a token remains configured. Details: [cloud-bridge-browser-approval.md](cloud-bridge-browser-approval.md).
+### Local Bridge Pairing
+
+The MCP server and the LM Studio plugin listen on loopback, where any local process can connect and send the extension's `hello`. They therefore pair with the extension through a shared key: each new socket gets a random nonce and is trusted only after returning an HMAC-SHA256 of it keyed with the pairing key. The key is generated on the user's machine (`~/.webbrain/bridge-key`, owner-only), pasted once under **Settings → Bridge → Pairing key**, stored in `chrome.storage.local`, never sent over the socket, and never included in the bridge `status`. An unpaired socket receives no commands and cannot replace the paired extension; a wrong proof closes it with code `4001`, after which the extension stops reconnecting until the settings change. This protects the bridges from impostor clients; it does not authenticate the bridge to the extension.
+
---
## Prompt Injection Defenses
diff --git a/lmstudio-plugin/README.md b/lmstudio-plugin/README.md
index cd39fc0a8..a8befe356 100644
--- a/lmstudio-plugin/README.md
+++ b/lmstudio-plugin/README.md
@@ -112,14 +112,26 @@ Firefox, `browser_task` will always return the not-connected response.
`fetch_url` and `research_url` are unaffected and work everywhere.
1. Install the extension and open your browser.
-2. In **WebBrain → Settings → Bridge**, set the URL to
- `ws://127.0.0.1:17375/extension` and enable it.
-3. Ask the model to call `browser_status` to confirm.
+2. Enable the plugin once so it creates its pairing key, then copy the key
+ from `~/.webbrain/bridge-key` (`%USERPROFILE%\.webbrain\bridge-key` on
+ Windows). The file is readable only by you. If you also use the MCP server,
+ it is the same key (`npx -y @webbrain/mcp-server pairing-key` prints it).
+3. In **WebBrain → Settings → Bridge**, set the URL to
+ `ws://127.0.0.1:17375/extension`, paste the key into **Pairing key**, and
+ enable it.
+4. Ask the model to call `browser_status` to confirm.
> **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 MCP server (`17374`). Override the port with
-> `WEBBRAIN_BRIDGE_PORT`.
+> `WEBBRAIN_BRIDGE_PORT`, and the key with `WEBBRAIN_BRIDGE_KEY` or
+> `WEBBRAIN_BRIDGE_KEY_FILE`.
+
+**Upgrading from an unpaired version.** Earlier plugin versions accepted any
+socket that sent the right `hello`. Update the WebBrain extension first (a
+version without the **Pairing key** field cannot pair and is disconnected after
+10 seconds), then paste the key as in step 3. "Rejected by the backend: Pairing
+key mismatch" under Settings means the pasted key is not the plugin's.
Try it:
@@ -172,11 +184,13 @@ Node project.
├── htmlToText.ts ← regex HTML stripper
├── safeFetch.ts ← redirect-revalidating wrapper + streaming cap
├── urlGuard.ts ← private-IP / file:// blocker
- └── bridgeClient.ts ← WebSocket listener the extension dials into
+ ├── bridgeClient.ts ← WebSocket listener the extension dials into
+ └── pairing.ts ← pairing key file and challenge proof
```
-`bridgeClient.ts` is a deliberate standalone copy of the same protocol in
-[`mcp-server/src/bridge.ts`](../mcp-server/src/bridge.ts). The two ship to
+`bridgeClient.ts` and `pairing.ts` are deliberate standalone copies of the same
+protocol in [`mcp-server/src/bridge.ts`](../mcp-server/src/bridge.ts) and
+[`mcp-server/src/pairing.ts`](../mcp-server/src/pairing.ts). The two ship to
different registries — LM Studio Hub and npm — and sharing a package would
drag the monorepo into both installs. **Change the protocol in one, change
it in the other.**
@@ -198,10 +212,13 @@ Everything below concerns `fetch_url` / `research_url`. For `browser_task`:
- The bridge listener binds `127.0.0.1` only. Anything that can reach that
port can drive your signed-in browser — never expose it to a network or a
container bridge.
-- Connections must send the extension's `hello` frame with
- `client: "webbrain-extension"`; anything else is closed. This is **not**
- authentication — the shipping extension sends no shared secret, so a local
- process could impersonate it. Treat the port as trusted-local.
+- Connections must send the extension's `hello` frame and answer a pairing
+ challenge: the plugin sends a random nonce and the extension returns an
+ HMAC-SHA256 of it keyed with the pairing key, so the key never crosses the
+ socket. Until a socket has done both it receives no commands and cannot
+ replace the connected extension; a wrong answer closes it with code `4001`.
+ The protocol is the MCP server's; see
+ [its Pairing section](../mcp-server/README.md#pairing).
- `browser_task` delegates a *goal*, never individual clicks. WebBrain's
capability × origin permission gate runs inside its own agent loop, so
every approval prompt a human would see still fires. That is why this
diff --git a/lmstudio-plugin/src/util/bridgeClient.ts b/lmstudio-plugin/src/util/bridgeClient.ts
index cca752584..42370f86e 100644
--- a/lmstudio-plugin/src/util/bridgeClient.ts
+++ b/lmstudio-plugin/src/util/bridgeClient.ts
@@ -6,11 +6,17 @@
* 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)
* extension -> us {type:'hello', client, protocolVersion, capabilities, status}
+ * extension -> us {type:'auth', scheme, proof} (either order)
* us -> extension {id, action, payload}
* extension -> us {id, ok:true, result} | {id, ok:false, error, status?}
*
+ * A socket stays a candidate until it has sent both a valid hello and the
+ * pairing proof (see pairing.ts). Candidates never receive commands and never
+ * displace the connected extension.
+ *
* This is deliberately a standalone copy of the same ~150 lines that live in
* `mcp-server/src/bridge.ts`. The two are separately published artifacts — this
* one goes to LM Studio's registry, that one to npm — and coupling them through
@@ -23,6 +29,14 @@
*/
import { WebSocketServer, type WebSocket } from "ws";
+import {
+ PAIRING_CLOSE_CODE,
+ PAIRING_SCHEME,
+ loadPairingKey,
+ newPairingNonce,
+ validatePairingKey,
+ verifyPairingProof,
+} from "./pairing";
export type BridgeAction = "cloud_run" | "cloud_status" | "cloud_respond" | "cloud_abort";
@@ -76,10 +90,22 @@ interface Pending {
timer: ReturnType<typeof setTimeout>;
}
+/** A socket that connected but has not yet proved it holds the pairing key. */
+interface Candidate {
+ nonce: string;
+ hello: boolean;
+ paired: boolean;
+ timer: ReturnType<typeof setTimeout>;
+}
+
export interface BridgeOptions {
port?: number;
path?: string;
commandTimeoutMs?: number;
+ /** Pairing key supplied by the host. Defaults to loadPairingKey(). */
+ pairingKey?: string;
+ /** How long a new socket may take to send hello and pair before it is closed. */
+ pairingTimeoutMs?: number;
}
function isAllowedBridgeOrigin(origin: string | string[] | undefined): boolean {
@@ -95,21 +121,28 @@ function isAllowedBridgeOrigin(origin: string | string[] | undefined): boolean {
export class BridgeClient {
private wss: WebSocketServer | null = null;
+ /** The paired extension. Only set once a socket has sent hello and paired. */
private socket: WebSocket | null = null;
+ private candidates = new Map<WebSocket, Candidate>();
private pending = new Map<number, Pending>();
private nextId = 1;
private waiters: Array<() => void> = [];
- private handshakenSocket: WebSocket | null = null;
+ private pairingKey = "";
+ private pairingSource = "";
readonly port: number;
readonly path: string;
readonly commandTimeoutMs: number;
+ private readonly pairingTimeoutMs: number;
+ private readonly configuredPairingKey: string | undefined;
constructor(options: BridgeOptions = {}) {
this.port = options.port ?? Number(process.env.WEBBRAIN_BRIDGE_PORT ?? 17375);
this.path = options.path ?? (process.env.WEBBRAIN_BRIDGE_PATH || "/extension");
this.commandTimeoutMs =
options.commandTimeoutMs ?? Number(process.env.WEBBRAIN_COMMAND_TIMEOUT_MS ?? 30_000);
+ this.pairingTimeoutMs = options.pairingTimeoutMs ?? 10_000;
+ this.configuredPairingKey = options.pairingKey;
}
get url(): string {
@@ -120,6 +153,16 @@ export class BridgeClient {
async ensureStarted(): Promise<void> {
if (this.wss) return;
+ // Resolve the key before binding: without it every socket would be refused.
+ if (this.configuredPairingKey !== undefined) {
+ this.pairingKey = validatePairingKey(this.configuredPairingKey, "The pairing key");
+ this.pairingSource = "the plugin configuration";
+ } else {
+ const loaded = loadPairingKey();
+ this.pairingKey = loaded.key;
+ this.pairingSource = loaded.source;
+ }
+
await new Promise<void>((resolve, reject) => {
// Loopback only. Anything that can reach this port can drive the user's
// logged-in browser, so it must never bind a routable interface.
@@ -140,28 +183,33 @@ export class BridgeClient {
socket.close(1008, "Unexpected path");
return;
}
- if (this.socket) {
- this.failAllPending(
- new BridgeError(
- "WebBrain extension connection was superseded.",
- undefined,
- "COMMAND_INTERRUPTED",
- ),
- );
- try {
- this.socket.close(1000, "Superseded");
- } catch {
- /* already gone */
- }
- }
- this.socket = socket;
- this.handshakenSocket = null;
+ // The new socket is only a candidate. The connected extension keeps
+ // working until the candidate pairs, and is never touched if it fails.
+ const candidate: Candidate = {
+ nonce: newPairingNonce(),
+ hello: false,
+ paired: false,
+ timer: setTimeout(() => {
+ this.rejectCandidate(
+ socket,
+ candidate.hello
+ ? "Pairing required: update WebBrain and paste the pairing key under Settings → Bridge"
+ : "Handshake timeout",
+ );
+ }, this.pairingTimeoutMs),
+ };
+ this.candidates.set(socket, candidate);
socket.on("message", (raw) => this.handleMessage(socket, raw.toString()));
socket.on("close", () => {
+ const unpaired = this.candidates.get(socket);
+ if (unpaired) {
+ clearTimeout(unpaired.timer);
+ this.candidates.delete(socket);
+ return;
+ }
if (this.socket !== socket) return;
this.socket = null;
- this.handshakenSocket = null;
this.failAllPending(
new BridgeError(
"WebBrain extension disconnected mid-command.",
@@ -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 }));
+ } 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") {
+ 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 {
@@ -185,20 +295,10 @@ export class BridgeClient {
} catch {
return;
}
+ if (!msg || typeof msg !== "object") return;
- if (msg.type === "hello") {
- if (msg.client !== "webbrain-extension") {
- socket.close(1008, "Unknown client");
- if (this.socket === socket) {
- this.socket = null;
- this.handshakenSocket = null;
- }
- return;
- }
- this.handshakenSocket = socket;
- const waiters = this.waiters;
- this.waiters = [];
- for (const wake of waiters) wake();
+ if (candidate) {
+ this.handleCandidateMessage(socket, candidate, msg);
return;
}
@@ -230,11 +330,7 @@ export class BridgeClient {
}
isConnected(): boolean {
- return (
- this.socket !== null &&
- this.socket.readyState === 1 &&
- this.handshakenSocket === this.socket
- );
+ return this.socket !== null && this.socket.readyState === 1;
}
waitForExtension(timeoutMs: number): Promise<boolean> {
@@ -258,7 +354,10 @@ export class BridgeClient {
`This plugin is listening on ${this.url}. To connect: install the WebBrain ` +
"extension (https://webbrain.one) on a Chromium browser — Chrome, Edge, Brave, " +
"Opera or Vivaldi — open it, then set WebBrain → Settings → Bridge to " +
- `${this.url} and enable it. The extension holds one bridge at a time, so it ` +
+ `${this.url}, paste the pairing key from ${this.pairingSource || "~/.webbrain/bridge-key"} ` +
+ "into Pairing key, and enable it. Ask the user to copy the key themselves; never request " +
+ "it in chat. Older WebBrain versions without a Pairing key field must be " +
+ "updated first. The extension holds one bridge at a time, so it " +
"cannot also be pointed at WebBrain Cloud (17373) or the MCP server (17374). " +
"Firefox cannot host the bridge at all: that build has no offscreen document. " +
"fetch_url and research_url keep working everywhere, with or without the extension."
@@ -312,6 +411,15 @@ export class BridgeClient {
async stop(): Promise<void> {
this.failAllPending(new BridgeError("Bridge shutting down."));
+ for (const [candidate, state] of this.candidates) {
+ clearTimeout(state.timer);
+ try {
+ candidate.close(1001, "Shutting down");
+ } catch {
+ /* ignore */
+ }
+ }
+ this.candidates.clear();
if (this.socket) {
try {
this.socket.close(1001, "Shutting down");
@@ -319,7 +427,6 @@ export class BridgeClient {
/* ignore */
}
this.socket = null;
- this.handshakenSocket = null;
}
if (this.wss) {
await new Promise<void>((resolve) => this.wss!.close(() => resolve()));
diff --git a/lmstudio-plugin/src/util/pairing.ts b/lmstudio-plugin/src/util/pairing.ts
new file mode 100644
index 000000000..bfd6e8eb5
--- /dev/null
+++ b/lmstudio-plugin/src/util/pairing.ts
@@ -0,0 +1,91 @@
+/**
+ * Pairing key — the shared secret that authenticates the extension's socket.
+ *
+ * Standalone copy of `mcp-server/src/pairing.ts` (the two packages ship to
+ * different registries; see bridgeClient.ts). Change both, and the proof in
+ * the extension's `cloud-bridge.js`, together.
+ *
+ * The Origin header and the `client: "webbrain-extension"` hello are both
+ * forgeable by any local process. The bridge therefore sends every new socket
+ * a random nonce and accepts it only after it answers with
+ * HMAC-SHA256(key, label + nonce). The key never crosses the socket.
+ *
+ * Where the key comes from, first match wins: `WEBBRAIN_BRIDGE_KEY`, the file
+ * named by `WEBBRAIN_BRIDGE_KEY_FILE`, then `~/.webbrain/bridge-key` (created
+ * with owner-only permissions on first use). The MCP server reads the same
+ * default file, so one pairing covers both bridges.
+ */
+
+import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
+import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { dirname, join } from "node:path";
+
+export const PAIRING_SCHEME = "hmac-sha256-v1";
+const PROOF_LABEL = "webbrain-bridge-pairing-v1:";
+export const MIN_PAIRING_KEY_LENGTH = 16;
+
+/** WebSocket close code for a socket that failed or skipped pairing. The extension stops reconnecting on it. */
+export const PAIRING_CLOSE_CODE = 4001;
+
+export interface PairingKey {
+ key: string;
+ /** Where the key came from, for setup messages. Never the key itself. */
+ source: string;
+}
+
+export function defaultPairingKeyFile(): string {
+ return join(homedir(), ".webbrain", "bridge-key");
+}
+
+export function validatePairingKey(raw: string, source: string): string {
+ const key = raw.trim();
+ if (key.length < MIN_PAIRING_KEY_LENGTH) {
+ throw new Error(`${source} must contain a pairing key of at least ${MIN_PAIRING_KEY_LENGTH} characters.`);
+ }
+ return key;
+}
+
+function readKeyFile(file: string): PairingKey {
+ return { key: validatePairingKey(readFileSync(file, "utf8"), file), source: file };
+}
+
+/** Resolve the pairing key, creating the default key file on first use. */
+export function loadPairingKey(env: NodeJS.ProcessEnv = process.env): PairingKey {
+ if (env.WEBBRAIN_BRIDGE_KEY) {
+ return { key: validatePairingKey(env.WEBBRAIN_BRIDGE_KEY, "WEBBRAIN_BRIDGE_KEY"), source: "WEBBRAIN_BRIDGE_KEY" };
+ }
+ const file = env.WEBBRAIN_BRIDGE_KEY_FILE || defaultPairingKeyFile();
+ try {
+ return readKeyFile(file);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
+ }
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
+ const key = randomBytes(32).toString("base64url");
+ try {
+ // `wx` never replaces an existing file: when the MCP server created it
+ // first, use that key instead of forking pairings.
+ writeFileSync(file, `${key}\n`, { mode: 0o600, flag: "wx" });
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
+ return readKeyFile(file);
+ }
+ return { key, source: file };
+}
+
+export function newPairingNonce(): string {
+ return randomBytes(32).toString("base64url");
+}
+
+/** Hex HMAC the extension must return for `nonce`. */
+export function pairingProof(key: string, nonce: string): string {
+ return createHmac("sha256", key).update(PROOF_LABEL + nonce).digest("hex");
+}
+
+export function verifyPairingProof(key: string, nonce: string, proof: unknown): boolean {
+ if (typeof proof !== "string") return false;
+ const expected = Buffer.from(pairingProof(key, nonce));
+ const actual = Buffer.from(proof);
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
+}
diff --git a/lmstudio-plugin/test/browserTask.test.mjs b/lmstudio-plugin/test/browserTask.test.mjs
index a8cabee7b..ccaf07a91 100644
--- a/lmstudio-plugin/test/browserTask.test.mjs
+++ b/lmstudio-plugin/test/browserTask.test.mjs
@@ -1,4 +1,5 @@
import assert from "node:assert/strict";
+import { createHmac } from "node:crypto";
import { once } from "node:events";
import { createServer } from "node:net";
import { after, before, test } from "node:test";
@@ -11,12 +12,29 @@ import {
browserTask,
} from "../dist/tools/browserTask.js";
import { main } from "../dist/index.js";
-import { sharedBridge } from "../dist/util/bridgeClient.js";
+import { BridgeClient, sharedBridge } from "../dist/util/bridgeClient.js";
+import { pairingProof } from "../dist/util/pairing.js";
+const PAIRING_KEY = "lmstudio-test-pairing-key-0123456789";
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) }));
+ }
+ });
+}
+
async function freePort() {
const server = createServer();
server.listen(0, "127.0.0.1");
@@ -35,6 +53,7 @@ function reply(message, result) {
before(async () => {
process.env.WEBBRAIN_BRIDGE_PORT = String(await freePort());
process.env.WEBBRAIN_COMMAND_TIMEOUT_MS = "50";
+ process.env.WEBBRAIN_BRIDGE_KEY = PAIRING_KEY;
const context = {
withToolsProvider(provider) {
toolsProvider = provider;
@@ -46,8 +65,10 @@ before(async () => {
const bridge = sharedBridge();
socket = new WebSocket(bridge.url);
+ answerPairing(socket);
socket.on("message", (raw) => {
const message = JSON.parse(raw.toString());
+ if (!message.action) return;
received.push(message);
if (message.action === "cloud_run") {
@@ -111,7 +132,7 @@ before(async () => {
});
await once(socket, "open");
socket.send(JSON.stringify({ type: "hello", client: "webbrain-extension" }));
- await new Promise((resolve) => setTimeout(resolve, 10));
+ assert.equal(await bridge.waitForExtension(3_000), true);
});
after(async () => {
@@ -266,6 +287,47 @@ test("a web-page origin cannot replace the connected extension", async () => {
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"]);
+
+ 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 });
@@ -278,11 +340,11 @@ test("browser_task preserves its generated run ID when the start socket disconne
assert.equal(request.payload.runId, result.runId);
});
-test("a replacement socket receives nothing until it sends a valid hello", async () => {
+test("an unpaired socket receives no commands while no extension is connected", async () => {
const rogue = new WebSocket(sharedBridge().url);
let receivedCommands = 0;
- rogue.on("message", () => {
- receivedCommands += 1;
+ rogue.on("message", (raw) => {
+ if (JSON.parse(raw.toString()).action) receivedCommands += 1;
});
await once(rogue, "open");
await new Promise((resolve) => setTimeout(resolve, 20));
diff --git a/mcp-server/README.md b/mcp-server/README.md
index 87102a171..5e1759e82 100644
--- a/mcp-server/README.md
+++ b/mcp-server/README.md
@@ -24,13 +24,41 @@ cd mcp-server && npm install && npm run build
> **Chromium first.** Chrome, Edge, Brave, Opera, Vivaldi run the bridge from the extension's **offscreen document** (`src/chrome/src/offscreen/cloud-bridge.js`). Firefox has no offscreen document, so `src/firefox/src/cloud-bridge.js` runs it in the background page, configured under the same **Settings → Bridge** tab; it has not yet been verified against this MCP server on a real Firefox install.
>
-> This server does not use the optional browser-approval handshake (token, `connection_pending` / `connection_approved`). Without a token the extension behaves exactly as before. See [Cloud Bridge browser approval](../docs/cloud-bridge-browser-approval.md) for backends that want it.
+> This server does not use the optional browser-approval handshake (token, `connection_pending` / `connection_approved`); leave the Cloud Bridge token empty. It authenticates the extension with a **pairing key** instead (below). See [Cloud Bridge browser approval](../docs/cloud-bridge-browser-approval.md) for backends that want approval.
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.
+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**.
@@ -82,7 +110,8 @@ npm start
```
After it is running, enable `ws://127.0.0.1:17374/extension` under **WebBrain →
-Settings → Bridge**. Ask the MCP client to call
+Settings → Bridge** with the pairing key from `npx -y @webbrain/mcp-server pairing-key`
+(or `node dist/index.js pairing-key` in a checkout). Ask the MCP client to call
`webbrain_connection` to verify the complete connection.
## Troubleshooting
@@ -101,6 +130,12 @@ WebBrain Cloud uses `17373`, this MCP server uses `17374`, and the LM Studio
plugin uses `17375`. Only one can be selected at a time. The bridge is available
in Chromium browsers only, not Firefox.
+**Rejected by the backend: Pairing key mismatch** means the key under
+**Settings → Bridge → Pairing key** is not the one this server uses. Print it
+again with `npx -y @webbrain/mcp-server pairing-key`. If the server runs with
+`WEBBRAIN_BRIDGE_KEY` or `WEBBRAIN_BRIDGE_KEY_FILE`, use that key instead.
+**This bridge requires a pairing key** means the field is empty.
+
## Tools
| Tool | Purpose |
@@ -182,11 +217,30 @@ WebBrain exposes roughly fifty primitives internally — `click_ax`, `type_ax`,
| `WEBBRAIN_COMMAND_TIMEOUT_MS` | `30000` | Per-command reply timeout. |
| `WEBBRAIN_RUN_TIMEOUT_MS` | `300000` | Default ceiling for `webbrain_run` polling. |
| `WEBBRAIN_POLL_INTERVAL_MS` | `1000` | Status poll interval. |
+| `WEBBRAIN_BRIDGE_KEY` | — | Pairing key to use instead of the key file (at least 16 characters). |
+| `WEBBRAIN_BRIDGE_KEY_FILE` | `~/.webbrain/bridge-key` | Key file to read, or create on first start. |
+
+### Embedding the server in another app
+
+A host process that launches `dist/index.js` itself (for example over stdio, as
+webbrain.me does) configures pairing through the same environment:
+
+- Pass nothing to use the shared `~/.webbrain/bridge-key`, and show the user the
+ output of `node <path-to>/dist/index.js pairing-key` (or the file's contents)
+ to paste into WebBrain.
+- Or generate a key, keep it in the host's own user-only storage, and pass it as
+ `WEBBRAIN_BRIDGE_KEY` in the child's environment. `WEBBRAIN_BRIDGE_KEY_FILE`
+ points the server at a different file instead.
+
+`webbrain_connection` answers `Connected.` only for a paired extension. Its
+"Not connected" text names the key's source (a file path or variable name),
+never the key.
## Security notes
- The listener binds `127.0.0.1` only. Anything that can reach this port can drive your signed-in browser — never expose it to a network or a container bridge.
-- Connections from HTTP(S) pages and other non-extension browser origins are rejected before they can replace the extension socket. Accepted connections must also present the extension's `hello` frame with `client: "webbrain-extension"`; anything else is closed. This is **not** authentication. The shipping extension sends no shared secret, so a local process could impersonate it. Treat the port as trusted-local, and see [`docs/security-model.md`](../docs/security-model.md).
+- Connections from HTTP(S) pages and other non-extension browser origins are rejected outright. Every other socket must send the extension's `hello` frame and answer the pairing challenge (see [Pairing](#pairing)) before it receives a command; until then it cannot replace the connected extension. A local process without the key can still occupy the port before the server starts, or connect and be refused, but it cannot read tasks or answer them.
+- The pairing key is as sensitive as the browser session it unlocks. It lives in a user-only file; do not paste it into an MCP client chat. See [`docs/security-model.md`](../docs/security-model.md).
- A `webbrain_run` timeout does **not** abort the run. A task that already submitted a form should not be silently killed — the browser keeps going and `webbrain_status` picks it back up.
- `allow_api_mutations` lifts WebBrain's UI-first rule and is off by default. It is accepted only with `mode: "act"`; Ask runs remain read-only. The UI path is visible and stoppable; direct API mutations are neither.
@@ -196,10 +250,10 @@ WebBrain exposes roughly fifty primitives internally — `click_ax`, `type_ax`,
npm run build && node --test test/bridge.test.mjs
```
-The suite stands up the real listener and connects a fake extension speaking the exact frames `src/chrome/src/offscreen/cloud-bridge.js` emits — handshake, id correlation under concurrency, error propagation, disconnect mid-command, and the poll/timeout/clarify paths. If the extension's wire format changes, these fail. That is intentional.
+The suite stands up the real listener and connects a fake extension speaking the exact frames `src/chrome/src/offscreen/cloud-bridge.js` emits — handshake, pairing, id correlation under concurrency, error propagation, disconnect mid-command, and the poll/timeout/clarify paths. `test/pairing.test.mjs` also runs the extension's real Chrome and Firefox bridge code against the server. If the extension's wire format changes, these fail. That is intentional.
For manual poking, [`scripts/fake-extension.mjs`](scripts/fake-extension.mjs) is
-the same fake as a standalone process — run the server, then:
+the same fake as a standalone process. It pairs with the server's key — run the server, then:
```bash
node scripts/fake-extension.mjs
diff --git a/mcp-server/package.json b/mcp-server/package.json
index e2c9e505b..036de3baf 100644
--- a/mcp-server/package.json
+++ b/mcp-server/package.json
@@ -20,7 +20,7 @@
"build": "tsc",
"dev": "tsc --watch",
"start": "node dist/index.js",
- "test": "npm run build && node --test test/bridge.test.mjs test/catalog.test.mjs test/config.test.mjs test/runs-request-timeout.test.mjs test/runs-timeout.test.mjs test/stdio-shutdown.test.mjs test/task-memory.test.mjs",
+ "test": "npm run build && node --test test/bridge.test.mjs test/catalog.test.mjs test/config.test.mjs test/pairing.test.mjs test/runs-request-timeout.test.mjs test/runs-timeout.test.mjs test/stdio-shutdown.test.mjs test/task-memory.test.mjs",
"clean": "rm -rf dist",
"prepack": "npm run build",
"prepare": "npm run build"
diff --git a/mcp-server/scripts/fake-extension.mjs b/mcp-server/scripts/fake-extension.mjs
index 21a15ca9d..904cef676 100644
--- a/mcp-server/scripts/fake-extension.mjs
+++ b/mcp-server/scripts/fake-extension.mjs
@@ -2,18 +2,22 @@
// Stands in for the WebBrain extension so the MCP server can be driven without
// Chrome. Speaks the same frames as src/chrome/src/offscreen/cloud-bridge.js:
-// the `hello` handshake, then canned replies to cloud_run / cloud_status /
-// cloud_respond / cloud_abort. Anything else comes back as an error, which is
-// how you check the server's failure path.
+// the `hello` handshake and the answer to the pairing challenge, then canned
+// replies to cloud_run / cloud_status / cloud_respond / cloud_abort. Anything
+// else comes back as an error, which is how you check the server's failure path.
//
// cd mcp-server && node scripts/fake-extension.mjs [ws-url]
//
// Defaults to ws://127.0.0.1:17374/extension. Start the server first
-// (npm start), then this, then point your MCP client at the server.
+// (npm start), then this, then point your MCP client at the server. It pairs
+// with the same key the server uses (WEBBRAIN_BRIDGE_KEY, WEBBRAIN_BRIDGE_KEY_FILE
+// or ~/.webbrain/bridge-key).
import WebSocket from "ws";
+import { loadPairingKey, pairingProof, PAIRING_SCHEME } from "../dist/pairing.js";
const url = process.argv[2] || "ws://127.0.0.1:17374/extension";
+const { key: pairingKey } = loadPairingKey();
const socket = new WebSocket(url);
let lastRunId = null;
@@ -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) }));
+ log("pairing proof sent");
+ return;
+ }
if (!msg.action) {
log("<-", JSON.stringify(msg));
return;
diff --git a/mcp-server/src/bridge.ts b/mcp-server/src/bridge.ts
index 29a442b35..83f33928a 100644
--- a/mcp-server/src/bridge.ts
+++ b/mcp-server/src/bridge.ts
@@ -6,12 +6,19 @@
* 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)
* extension -> us {type:'hello', client, protocolVersion, capabilities, status}
+ * extension -> us {type:'auth', scheme, proof} (either order)
* us -> extension {id, action, payload}
* extension -> us {id, ok:true, result}
* {id, ok:false, error, status?}
*
+ * A socket stays a candidate until it has sent both a valid hello and the
+ * pairing proof (see pairing.ts). Candidates never receive commands and never
+ * displace the connected extension, so a local process that merely claims to
+ * be WebBrain cannot take over the bridge or read task payloads.
+ *
* The extension spreads `payload` over the message it forwards to its own
* background worker, so payload keys become top-level fields there. Send the
* exact field names `cloud-runs.js` reads.
@@ -19,6 +26,14 @@
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. */
@@ -66,6 +81,21 @@ interface Pending {
memoryStart?: boolean;
}
+/** A socket that connected but has not yet proved it holds the pairing key. */
+interface Candidate {
+ nonce: string;
+ hello: Record<string, unknown> | null;
+ paired: boolean;
+ timer: NodeJS.Timeout;
+}
+
+export interface BridgeOptions {
+ /** Pairing key supplied by a host process. Defaults to loadPairingKey(). */
+ pairingKey?: string;
+ /** How long a new socket may take to send hello and pair before it is closed. */
+ pairingTimeoutMs?: number;
+}
+
export class BridgeError extends Error {
readonly status?: number;
readonly code?: "COMMAND_TIMEOUT" | "COMMAND_INTERRUPTED";
@@ -99,21 +129,44 @@ function isAllowedBridgeOrigin(origin: string | string[] | undefined): boolean {
export class WebBrainBridge {
private wss: WebSocketServer | null = null;
+ /** The paired extension. Only set once a socket has sent hello and paired. */
private socket: WebSocket | null = null;
+ private candidates = new Map<WebSocket, Candidate>();
private pending = new Map<number, Pending>();
private nextId = 1;
private extensionCapabilities: string[] = [];
private extensionProtocol: number | null = null;
- private handshakenSocket: WebSocket | null = null;
private waiters: Array<() => void> = [];
+ private pairingKey = "";
+ private pairingSource = "";
+ private readonly pairingTimeoutMs: number;
private memoryPrivateValues = new Set<string>();
private memoryProtectedRunIds = new Set<string>();
private memoryRunValues = new Map<string, ReadonlySet<string>>();
private protectedMemoryRequests = 0;
+ 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;
+ // Resolve the key before binding: without it every socket would be refused.
+ if (this.options.pairingKey !== undefined) {
+ this.pairingKey = validatePairingKey(this.options.pairingKey, "The pairing key");
+ this.pairingSource = "host configuration";
+ } else {
+ const loaded = loadPairingKey();
+ this.pairingKey = loaded.key;
+ this.pairingSource = loaded.source;
+ }
+
await new Promise<void>((resolve, reject) => {
// Bind to loopback explicitly. Never expose this listener to the network:
// anything that can reach it can drive the user's logged-in browser.
@@ -141,36 +194,34 @@ export class WebBrainBridge {
return;
}
- // Latest connection wins. The extension reconnects with backoff after a
- // browser restart or an offscreen-document teardown, and the stale socket
- // is never reused.
- if (this.socket) {
- this.failAllPending(
- new BridgeError(
- "WebBrain extension connection was superseded mid-command.",
- undefined,
- "COMMAND_INTERRUPTED",
- ),
- );
- try {
- this.socket.close(1000, "Superseded by a newer extension connection");
- } catch {
- /* already gone */
- }
- }
-
- this.socket = socket;
- this.handshakenSocket = null;
- this.extensionCapabilities = [];
- this.extensionProtocol = null;
- log(`extension connected on ${config.bridgePath}`);
+ // The new socket is only a candidate. The connected extension keeps
+ // working until the candidate pairs, and is never touched if it fails.
+ const candidate: Candidate = {
+ nonce: newPairingNonce(),
+ hello: null,
+ paired: false,
+ timer: setTimeout(() => {
+ this.rejectCandidate(
+ socket,
+ candidate.hello
+ ? "Pairing required: update WebBrain and paste the pairing key under Settings → Bridge"
+ : "Handshake timeout",
+ );
+ }, this.pairingTimeoutMs),
+ };
+ this.candidates.set(socket, candidate);
socket.on("message", (raw) => this.handleMessage(socket, raw.toString()));
socket.on("close", () => {
+ const unpaired = this.candidates.get(socket);
+ if (unpaired) {
+ clearTimeout(unpaired.timer);
+ this.candidates.delete(socket);
+ return;
+ }
if (this.socket !== socket) return;
this.socket = null;
- this.handshakenSocket = null;
this.extensionCapabilities = [];
this.extensionProtocol = null;
log("extension disconnected");
@@ -186,45 +237,110 @@ export class WebBrainBridge {
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 }));
+ } 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;
+ }
+ candidate.hello = msg;
+ } else if (msg.type === "auth") {
+ if (msg.scheme !== PAIRING_SCHEME || !verifyPairingProof(this.pairingKey, candidate.nonce, msg.proof)) {
+ this.rejectCandidate(socket, "Pairing key mismatch");
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.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;
}
@@ -263,11 +379,7 @@ export class WebBrainBridge {
}
isConnected(): boolean {
- return (
- this.socket !== null &&
- this.socket.readyState === 1 &&
- this.handshakenSocket === this.socket
- );
+ return this.socket !== null && this.socket.readyState === 1;
}
capabilities(): string[] {
@@ -301,7 +413,8 @@ export class WebBrainBridge {
throw new BridgeError(
"No WebBrain extension is connected. Open the browser, then set " +
"WebBrain → Settings → Bridge to " +
- `ws://127.0.0.1:${config.bridgePort}${config.bridgePath} and enable the MCP bridge.`,
+ `ws://127.0.0.1:${config.bridgePort}${config.bridgePath}, paste the pairing key ` +
+ `from ${this.pairingKeyHint()} into Pairing key, and enable the MCP bridge.`,
);
}
@@ -377,6 +490,15 @@ export class WebBrainBridge {
this.memoryProtectedRunIds.clear();
this.memoryRunValues.clear();
this.protectedMemoryRequests = 0;
+ 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");
@@ -384,7 +506,6 @@ export class WebBrainBridge {
/* ignore */
}
this.socket = null;
- this.handshakenSocket = null;
}
if (this.wss) {
await new Promise<void>((resolve) => this.wss!.close(() => resolve()));
diff --git a/mcp-server/src/index.ts b/mcp-server/src/index.ts
index e696fe04e..044a5cd8c 100644
--- a/mcp-server/src/index.ts
+++ b/mcp-server/src/index.ts
@@ -26,6 +26,7 @@ import { z } from "zod";
import { BridgeError, WebBrainBridge, type CloudSnapshot } from "./bridge.js";
import { bridgeUrl, config } from "./config.js";
+import { loadPairingKey } from "./pairing.js";
import { abort, awaitSettled, describeSnapshot, getStatus, respond, startRun } from "./runs.js";
import { taskMemorySchema } from "./task-memory.js";
@@ -393,11 +394,15 @@ server.registerTool(
);
}
return ok(
- `Not connected. Listening on ${bridgeUrl()}, but no extension has dialled in.\n\n` +
+ `Not connected. Listening on ${bridgeUrl()}, but no paired extension has dialled in.\n\n` +
"To connect: open a Chromium browser (Chrome, Edge, Brave), then in " +
"WebBrain → Settings → Bridge set the URL to\n" +
` ${bridgeUrl()}\n` +
- "and enable it. The extension holds one bridge socket at a time, so this cannot " +
+ "paste the pairing key into Pairing key, and enable it. The key comes from " +
+ `${bridge.pairingKeySource()}; when that is a file, the user can print it with ` +
+ "`npx -y @webbrain/mcp-server pairing-key`. " +
+ "Do not ask the user to paste the key into this chat. WebBrain versions without a " +
+ "Pairing key field must be updated first. The extension holds one bridge socket at a time, so this cannot " +
"run at the same time as WebBrain Cloud on port 17373.\n\n" +
"Firefox cannot host the bridge — that build has no offscreen document. If the " +
"user is on Firefox, say so rather than suggesting settings changes.",
@@ -428,15 +433,28 @@ async function shutdown(): Promise<void> {
process.exit(0);
}
-process.on("SIGINT", () => void shutdown());
-process.on("SIGTERM", () => void shutdown());
-// MCP hosts commonly stop stdio servers by closing the child's stdin rather
-// than sending a signal. Without these handlers the WebSocket listener keeps
-// the event loop alive and leaves port 17374 occupied by an orphan process.
-process.stdin.once("end", () => void shutdown());
-process.stdin.once("close", () => void shutdown());
+if (process.argv[2] === "pairing-key") {
+ // `webbrain-mcp pairing-key` prints the key to paste into WebBrain →
+ // Settings → Bridge (creating it on first use) and exits without serving.
+ try {
+ const { key, source } = loadPairingKey();
+ process.stdout.write(`${key}\n`);
+ console.error(`[webbrain-mcp] pairing key from ${source}`);
+ } catch (error) {
+ console.error("[webbrain-mcp] fatal:", error instanceof Error ? error.message : error);
+ process.exitCode = 1;
+ }
+} else {
+ process.on("SIGINT", () => void shutdown());
+ process.on("SIGTERM", () => void shutdown());
+ // MCP hosts commonly stop stdio servers by closing the child's stdin rather
+ // than sending a signal. Without these handlers the WebSocket listener keeps
+ // the event loop alive and leaves port 17374 occupied by an orphan process.
+ process.stdin.once("end", () => void shutdown());
+ process.stdin.once("close", () => void shutdown());
-main().catch((error) => {
- console.error("[webbrain-mcp] fatal:", error);
- process.exit(1);
-});
+ main().catch((error) => {
+ console.error("[webbrain-mcp] fatal:", error);
+ process.exit(1);
+ });
+}
diff --git a/mcp-server/src/pairing.ts b/mcp-server/src/pairing.ts
new file mode 100644
index 000000000..c01b60aa8
--- /dev/null
+++ b/mcp-server/src/pairing.ts
@@ -0,0 +1,93 @@
+/**
+ * Pairing key — the shared secret that authenticates the extension's socket.
+ *
+ * The Origin header and the `client: "webbrain-extension"` hello are both
+ * forgeable by any local process, so they cannot tell the real extension from
+ * an impostor. The bridge therefore sends every new socket a random nonce and
+ * accepts it only after it answers with HMAC-SHA256(key, label + nonce). The
+ * key itself never crosses the socket, and an answer recorded on one socket is
+ * useless on the next because the nonce changes.
+ *
+ * Where the key comes from, first match wins:
+ * 1. `WEBBRAIN_BRIDGE_KEY` (for host processes that manage their own key);
+ * 2. the file named by `WEBBRAIN_BRIDGE_KEY_FILE`;
+ * 3. `~/.webbrain/bridge-key`, created with owner-only permissions on first use.
+ *
+ * The LM Studio plugin keeps a copy of this file (`lmstudio-plugin/src/util/pairing.ts`)
+ * and reads the same default key file, so one pairing covers both bridges. The
+ * extension computes the same proof in `cloud-bridge.js`. Change all three together.
+ */
+
+import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
+import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { dirname, join } from "node:path";
+
+export const PAIRING_SCHEME = "hmac-sha256-v1";
+const PROOF_LABEL = "webbrain-bridge-pairing-v1:";
+export const MIN_PAIRING_KEY_LENGTH = 16;
+
+/** WebSocket close code for a socket that failed or skipped pairing. The extension stops reconnecting on it. */
+export const PAIRING_CLOSE_CODE = 4001;
+
+export interface PairingKey {
+ key: string;
+ /** Where the key came from, for log and setup messages. Never the key itself. */
+ source: string;
+}
+
+export function defaultPairingKeyFile(): string {
+ return join(homedir(), ".webbrain", "bridge-key");
+}
+
+export function validatePairingKey(raw: string, source: string): string {
+ const key = raw.trim();
+ if (key.length < MIN_PAIRING_KEY_LENGTH) {
+ throw new Error(`${source} must contain a pairing key of at least ${MIN_PAIRING_KEY_LENGTH} characters.`);
+ }
+ return key;
+}
+
+function readKeyFile(file: string): PairingKey {
+ return { key: validatePairingKey(readFileSync(file, "utf8"), file), source: file };
+}
+
+/** Resolve the pairing key, creating the default key file on first use. */
+export function loadPairingKey(env: NodeJS.ProcessEnv = process.env): PairingKey {
+ if (env.WEBBRAIN_BRIDGE_KEY) {
+ return { key: validatePairingKey(env.WEBBRAIN_BRIDGE_KEY, "WEBBRAIN_BRIDGE_KEY"), source: "WEBBRAIN_BRIDGE_KEY" };
+ }
+ const file = env.WEBBRAIN_BRIDGE_KEY_FILE || defaultPairingKeyFile();
+ try {
+ return readKeyFile(file);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
+ }
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
+ const key = randomBytes(32).toString("base64url");
+ try {
+ // `wx` never replaces an existing file: when the LM Studio plugin or a
+ // second server created it first, use that key instead of forking pairings.
+ writeFileSync(file, `${key}\n`, { mode: 0o600, flag: "wx" });
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
+ return readKeyFile(file);
+ }
+ return { key, source: file };
+}
+
+export function newPairingNonce(): string {
+ return randomBytes(32).toString("base64url");
+}
+
+/** Hex HMAC the extension must return for `nonce`. */
+export function pairingProof(key: string, nonce: string): string {
+ return createHmac("sha256", key).update(PROOF_LABEL + nonce).digest("hex");
+}
+
+export function verifyPairingProof(key: string, nonce: string, proof: unknown): boolean {
+ if (typeof proof !== "string") return false;
+ const expected = Buffer.from(pairingProof(key, nonce));
+ const actual = Buffer.from(proof);
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
+}
diff --git a/mcp-server/test/bridge.test.mjs b/mcp-server/test/bridge.test.mjs
index 36d5fb200..35e420c42 100644
--- a/mcp-server/test/bridge.test.mjs
+++ b/mcp-server/test/bridge.test.mjs
@@ -9,21 +9,35 @@
*/
import assert from "node:assert/strict";
+import { createHmac } from "node:crypto";
+import { once } from "node:events";
import test from "node:test";
import WebSocket from "ws";
+const PAIRING_KEY = "bridge-test-pairing-key-0123456789";
process.env.WEBBRAIN_BRIDGE_PORT = process.env.WEBBRAIN_BRIDGE_PORT || "17399";
process.env.WEBBRAIN_COMMAND_TIMEOUT_MS = "2000";
process.env.WEBBRAIN_POLL_INTERVAL_MS = "20";
+process.env.WEBBRAIN_BRIDGE_KEY = PAIRING_KEY;
const { WebBrainBridge, BridgeError, TERMINAL_STATUSES } = await import("../dist/bridge.js");
const { bridgeUrl } = await import("../dist/config.js");
const { awaitSettled, describeSnapshot } = await import("../dist/runs.js");
-/** Minimal stand-in for the extension's offscreen bridge client. */
-function fakeExtension(url, handler, { client = "webbrain-extension" } = {}) {
+/** Computed independently of dist/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");
+}
+
+/**
+ * Minimal stand-in for the extension's offscreen bridge client. `key: null`
+ * models an extension that cannot answer the pairing challenge.
+ */
+function fakeExtension(url, handler, { client = "webbrain-extension", key = PAIRING_KEY, hello = true } = {}) {
const socket = new WebSocket(url);
+ socket.frames = [];
socket.on("open", () => {
+ if (!hello) return;
socket.send(
JSON.stringify({
type: "hello",
@@ -36,6 +50,13 @@ function fakeExtension(url, handler, { client = "webbrain-extension" } = {}) {
});
socket.on("message", async (raw) => {
const msg = JSON.parse(raw.toString());
+ socket.frames.push(msg);
+ if (msg.type === "auth_challenge") {
+ if (key !== null) {
+ socket.send(JSON.stringify({ type: "auth", 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 }));
@@ -43,6 +64,10 @@ function fakeExtension(url, handler, { client = "webbrain-extension" } = {}) {
return socket;
}
+function closeInfo(socket) {
+ return once(socket, "close").then(([code, reason]) => ({ code, reason: reason.toString() }));
+}
+
test("handshake, command correlation, and payload shape", async (t) => {
const bridge = new WebBrainBridge();
t.after(() => bridge.stop());
@@ -193,32 +218,137 @@ test("a web-page origin cannot replace the connected extension", async (t) => {
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");
+
+ 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.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) }));
+ 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 --git a/mcp-server/test/catalog.test.mjs b/mcp-server/test/catalog.test.mjs
index 262a6d672..389e4f68b 100644
--- a/mcp-server/test/catalog.test.mjs
+++ b/mcp-server/test/catalog.test.mjs
@@ -26,7 +26,7 @@ test("MCP catalog exposes structured extraction alongside run controls", async (
command: process.execPath,
args: ["dist/index.js"],
cwd: packageDir,
- env: { ...process.env, WEBBRAIN_BRIDGE_PORT: String(port) },
+ env: { ...process.env, WEBBRAIN_BRIDGE_PORT: String(port), WEBBRAIN_BRIDGE_KEY: "spawned-server-test-pairing-key" },
stderr: "pipe",
});
const client = new Client({ name: "webbrain-catalog-test", version: "1.0.0" });
diff --git a/mcp-server/test/pairing.test.mjs b/mcp-server/test/pairing.test.mjs
new file mode 100644
index 000000000..15aec1575
--- /dev/null
+++ b/mcp-server/test/pairing.test.mjs
@@ -0,0 +1,182 @@
+/**
+ * Pairing tests: key storage, the `pairing-key` command, and an end-to-end run
+ * of the extension's real bridge code (Chrome offscreen page and Firefox
+ * background module) against this server.
+ *
+ * Run: node --test test/pairing.test.mjs (after `npm run build`)
+ */
+
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { once } from "node:events";
+import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
+import { createServer } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import test from "node:test";
+import vm from "node:vm";
+
+const allocator = createServer();
+allocator.listen(0, "127.0.0.1");
+await once(allocator, "listening");
+process.env.WEBBRAIN_BRIDGE_PORT = String(allocator.address().port);
+process.env.WEBBRAIN_COMMAND_TIMEOUT_MS = "2000";
+allocator.close();
+await once(allocator, "close");
+
+const { WebBrainBridge } = await import("../dist/bridge.js");
+const { bridgeUrl } = await import("../dist/config.js");
+const { defaultPairingKeyFile, loadPairingKey, pairingProof } = await import("../dist/pairing.js");
+const { createCloudBridge } = await import("../../src/firefox/src/cloud-bridge.js");
+
+const packageDir = fileURLToPath(new URL("..", import.meta.url));
+const KEY = "end-to-end-pairing-key-0123456789";
+
+function tempKeyFile(t) {
+ const dir = mkdtempSync(join(tmpdir(), "webbrain-pairing-"));
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ return join(dir, "nested", "bridge-key");
+}
+
+async function until(predicate, timeoutMs = 3000) {
+ const deadline = Date.now() + timeoutMs;
+ while (!predicate()) {
+ if (Date.now() > deadline) throw new Error("condition not reached in time");
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ }
+}
+
+test("the proof matches the vector the extension and LM Studio tests also check", () => {
+ assert.equal(
+ pairingProof("webbrain-pairing-test-vector-key", "fixed-nonce-for-cross-checks"),
+ "5d2a446bcc1734f26d8b94e20d3329a07fb2513aa6d036f47f687065d33c55da",
+ );
+});
+
+test("the key file is created once with owner-only permissions and then reused", (t) => {
+ const file = tempKeyFile(t);
+ const first = loadPairingKey({ WEBBRAIN_BRIDGE_KEY_FILE: file });
+ assert.equal(first.source, file);
+ assert.ok(first.key.length >= 32);
+ assert.equal(readFileSync(file, "utf8").trim(), first.key);
+ if (process.platform !== "win32") assert.equal(statSync(file).mode & 0o777, 0o600);
+
+ const second = loadPairingKey({ WEBBRAIN_BRIDGE_KEY_FILE: file });
+ assert.equal(second.key, first.key, "a restart must not invalidate the pairing");
+ assert.match(defaultPairingKeyFile(), /[\\/]\.webbrain[\\/]bridge-key$/);
+});
+
+test("WEBBRAIN_BRIDGE_KEY overrides the file and short keys are refused", (t) => {
+ const file = tempKeyFile(t);
+ const fromEnv = loadPairingKey({ WEBBRAIN_BRIDGE_KEY: ` ${KEY}\n`, WEBBRAIN_BRIDGE_KEY_FILE: file });
+ assert.deepEqual(fromEnv, { key: KEY, source: "WEBBRAIN_BRIDGE_KEY" });
+ assert.throws(() => statSync(file), /ENOENT/, "an explicit key must not create a key file");
+
+ assert.throws(() => loadPairingKey({ WEBBRAIN_BRIDGE_KEY: "too-short" }), /at least 16 characters/);
+ loadPairingKey({ WEBBRAIN_BRIDGE_KEY_FILE: file });
+ writeFileSync(file, "tiny\n");
+ assert.throws(() => loadPairingKey({ WEBBRAIN_BRIDGE_KEY_FILE: file }), /at least 16 characters/);
+});
+
+test("`webbrain-mcp pairing-key` prints the stored key without starting the bridge", (t) => {
+ const file = tempKeyFile(t);
+ const { key } = loadPairingKey({ WEBBRAIN_BRIDGE_KEY_FILE: file });
+ const env = { ...process.env, WEBBRAIN_BRIDGE_KEY_FILE: file };
+ delete env.WEBBRAIN_BRIDGE_KEY;
+ const run = spawnSync(process.execPath, ["dist/index.js", "pairing-key"], {
+ cwd: packageDir,
+ env,
+ input: "",
+ encoding: "utf8",
+ timeout: 10_000,
+ });
+ assert.equal(run.status, 0, run.stderr);
+ assert.equal(run.stdout, `${key}\n`);
+ assert.doesNotMatch(run.stderr, /listening on/);
+});
+
+/** The Chrome offscreen bridge, run as the browser would run it. */
+function chromeExtension(dispatch) {
+ const source = readFileSync(new URL("../../src/chrome/src/offscreen/cloud-bridge.js", import.meta.url), "utf8");
+ let listener;
+ vm.runInNewContext(source, {
+ URL,
+ WebSocket,
+ TextEncoder,
+ crypto: globalThis.crypto,
+ navigator: { userAgent: "Mozilla/5.0 Chrome/126.0.1", platform: "test" },
+ chrome: { runtime: { onMessage: { addListener: (cb) => { listener = cb; } }, sendMessage: dispatch } },
+ setTimeout,
+ clearTimeout,
+ });
+ const call = (msg) => {
+ let out;
+ listener(msg, null, (value) => { out = value; });
+ return out;
+ };
+ return {
+ start: (identity) => call({ type: "cloud-bridge-start", url: bridgeUrl(), ...identity }),
+ stop: () => call({ type: "cloud-bridge-stop" }),
+ status: () => call({ type: "cloud-bridge-status" }),
+ };
+}
+
+function firefoxExtension(dispatch) {
+ const bridge = createCloudBridge({ dispatch, WebSocketImpl: WebSocket, nav: { userAgent: "Firefox/140.0", platform: "test" } });
+ return { start: (identity) => bridge.start({ url: bridgeUrl(), ...identity }), stop: bridge.stop, status: bridge.status };
+}
+
+for (const [label, makeExtension] of [["chrome", chromeExtension], ["firefox", firefoxExtension]]) {
+ test(`${label}: the real extension pairs with the MCP server and runs commands`, async (t) => {
+ const bridge = new WebBrainBridge({ pairingKey: KEY });
+ t.after(() => bridge.stop());
+ await bridge.start();
+ const calls = [];
+ const extension = makeExtension(async (msg) => {
+ calls.push(msg);
+ return { runId: msg.runId, status: "running" };
+ });
+ t.after(() => extension.stop());
+
+ extension.start({ pairingKey: KEY });
+ assert.equal(await bridge.waitForExtension(3000), true);
+ const result = await bridge.request("cloud_status", { runId: `${label}-run` });
+ assert.equal(result.runId, `${label}-run`);
+ assert.equal(calls.length, 1);
+ assert.equal(JSON.stringify(extension.status()).includes(KEY), false, "status must not expose the key");
+ });
+
+ test(`${label}: a wrong pairing key is refused and the extension stops retrying`, async (t) => {
+ const bridge = new WebBrainBridge({ pairingKey: KEY });
+ t.after(() => bridge.stop());
+ await bridge.start();
+ const extension = makeExtension(async () => ({}));
+ t.after(() => extension.stop());
+
+ extension.start({ pairingKey: "not-the-servers-pairing-key" });
+ await until(() => extension.status().approval === "rejected");
+ assert.equal(extension.status().lastError, "Pairing key mismatch");
+ assert.equal(bridge.isConnected(), false);
+ await new Promise((resolve) => setTimeout(resolve, 700)); // first reconnect backoff is 500 ms
+ assert.equal(extension.status().readyState, null, "a refused pairing must not reconnect in a loop");
+ assert.equal(bridge.isConnected(), false);
+ });
+
+ test(`${label}: an extension without a pairing key is told to add one`, async (t) => {
+ const bridge = new WebBrainBridge({ pairingKey: KEY });
+ t.after(() => bridge.stop());
+ await bridge.start();
+ const extension = makeExtension(async () => ({}));
+ t.after(() => extension.stop());
+
+ extension.start({});
+ await until(() => extension.status().approval === "rejected");
+ assert.match(extension.status().lastError, /requires a pairing key/);
+ assert.equal(bridge.isConnected(), false);
+
+ // Pasting the key restarts the bridge with a changed identity and pairs.
+ extension.start({ pairingKey: KEY });
+ assert.equal(await bridge.waitForExtension(3000), true);
+ });
+}
diff --git a/mcp-server/test/stdio-shutdown.test.mjs b/mcp-server/test/stdio-shutdown.test.mjs
index dc1d8315a..882163ce7 100644
--- a/mcp-server/test/stdio-shutdown.test.mjs
+++ b/mcp-server/test/stdio-shutdown.test.mjs
@@ -40,7 +40,7 @@ test("closing MCP stdin stops the bridge process", async () => {
const port = await freePort();
const child = spawn(process.execPath, ["dist/index.js"], {
cwd: packageDir,
- env: { ...process.env, WEBBRAIN_BRIDGE_PORT: String(port) },
+ env: { ...process.env, WEBBRAIN_BRIDGE_PORT: String(port), WEBBRAIN_BRIDGE_KEY: "spawned-server-test-pairing-key" },
stdio: ["pipe", "ignore", "pipe"],
});
diff --git a/mcp-server/test/task-memory.test.mjs b/mcp-server/test/task-memory.test.mjs
index 2e7ffd176..c3bdb0ff5 100644
--- a/mcp-server/test/task-memory.test.mjs
+++ b/mcp-server/test/task-memory.test.mjs
@@ -3,6 +3,7 @@ import test from 'node:test';
import { createServer } from 'node:net';
import { once } from 'node:events';
import WebSocket from 'ws';
+import { createHmac } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
@@ -11,6 +12,8 @@ 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');
@@ -18,6 +21,20 @@ 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;
+ 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 }));
+ });
+ 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',
@@ -79,9 +96,8 @@ test('direct bridge rejects invalid, misplaced, or unsupported memory without se
const bridge = new WebBrainBridge();
await bridge.start();
const seen = [];
- const extension = new WebSocket(bridgeUrl());
- extension.on('open', () => extension.send(JSON.stringify({ type: 'hello', client: 'webbrain-extension', protocolVersion: 2, capabilities: [] })));
- extension.on('message', raw => { seen.push(JSON.parse(raw.toString())); });
+ const extension = pairedExtension(bridgeUrl(), []);
+ extension.on('message', raw => { const msg = JSON.parse(raw.toString()); if (msg.action) seen.push(msg); });
try {
assert.equal(await bridge.waitForExtension(3000), true);
await assert.rejects(bridge.request('cloud_run', { task: 'Read', taskMemory: memory }), error => error.status === 409);
@@ -97,13 +113,12 @@ test('memory values survive failure and reconnect, with capability downgrade sti
await bridge.start();
const privateMemory = { ...memory, context: { notes: 'private-reconnect-note' } };
const connect = capabilities => {
- const socket = new WebSocket(bridgeUrl());
- socket.on('open', () => socket.send(JSON.stringify({ type: 'hello', client: 'webbrain-extension', protocolVersion: 2, capabilities })));
- return socket;
+ return pairedExtension(bridgeUrl(), capabilities);
};
const first = connect(['bot_memory_v1']);
first.on('message', raw => {
const msg = JSON.parse(raw.toString());
+ if (!msg.action) return;
first.send(JSON.stringify({ id: msg.id, ok: true, result: { runId: 'reconnect-protected', status: 'running' } }));
});
let second;
@@ -114,7 +129,7 @@ test('memory values survive failure and reconnect, with capability downgrade sti
second = connect([]);
const received = [];
second.on('message', raw => {
- const msg = JSON.parse(raw.toString()); received.push(msg);
+ const msg = JSON.parse(raw.toString()); if (!msg.action) return; received.push(msg);
const ordinary = msg.payload.runId === 'reconnect-ordinary';
second.send(JSON.stringify(msg.action === 'cloud_respond'
? { id: msg.id, ok: false, status: 500, error: 'failed private-reconnect-note ' + memory.callbackToken }
@@ -149,10 +164,10 @@ test('MCP transports memory outside prompts and redacts credentials from status
await bridge.start();
const seen = [];
let rejectNext = false;
- const extension = new WebSocket(bridgeUrl());
- extension.on('open', () => extension.send(JSON.stringify({ type: 'hello', client: 'webbrain-extension', protocolVersion: 2, capabilities: ['bot_memory_v1'] })));
+ const extension = pairedExtension(bridgeUrl(), ['bot_memory_v1']);
extension.on('message', raw => {
const message = JSON.parse(raw.toString());
+ if (!message.action) return;
seen.push(message);
const ordinary = message.action === 'cloud_run' && !message.payload.taskMemory;
extension.send(JSON.stringify(rejectNext
@@ -199,10 +214,9 @@ test('real MCP stdio run forwards the optional envelope privately and preserves
assert.equal(unsupported.isError, true);
assert.match(JSON.stringify(unsupported), /Update the browser extension/);
assert.equal(JSON.stringify(unsupported).includes(memory.callbackToken), false);
- extension = new WebSocket(`ws://127.0.0.1:${port}/extension`);
- extension.on('open', () => extension.send(JSON.stringify({ type: 'hello', client: 'webbrain-extension', protocolVersion: 2, capabilities: ['bot_memory_v1'] })));
+ extension = pairedExtension(`ws://127.0.0.1:${port}/extension`, ['bot_memory_v1']);
extension.on('message', raw => {
- const msg = JSON.parse(raw.toString()); seen.push(msg);
+ const msg = JSON.parse(raw.toString()); if (!msg.action) return; seen.push(msg);
const protectedRun = !!msg.payload.taskMemory;
extension.send(JSON.stringify({ id: msg.id, ok: true, result: {
runId: msg.payload.runId, status: 'completed',
diff --git a/src/chrome/src/background.js b/src/chrome/src/background.js
index 433d6abd5..e49ff25d1 100644
--- a/src/chrome/src/background.js
+++ b/src/chrome/src/background.js
@@ -1401,7 +1401,8 @@ chrome.storage.onChanged.addListener((changes, areaName) => {
if (PROFILE_SYNC_DATA_KEYS.some((key) => changes[key])) profileSync.noteChanges(changes).catch(() => {});
if (changes.providers || changes.activeProvider || changes.helpImproveWebBrain) providerManager.load().catch(() => {});
if (changes.webbrainCloudBridgeEnabled || changes.webbrainCloudBridgeUrl
- || changes.webbrainCloudBridgeToken || changes.webbrainCloudBridgeBrowserId) {
+ || changes.webbrainCloudBridgeToken || changes.webbrainCloudBridgeBrowserId
+ || changes.webbrainCloudBridgePairingKey) {
cloudRunController.syncBridge().catch(() => {});
}
if (changes.maxAgentSteps) {
diff --git a/src/chrome/src/cloud-runs.js b/src/chrome/src/cloud-runs.js
index 4b127ca8a..3d313dfb7 100644
--- a/src/chrome/src/cloud-runs.js
+++ b/src/chrome/src/cloud-runs.js
@@ -1983,7 +1983,8 @@ export function createCloudRunController({
}
// Persistent bridge identity (chrome.storage.local). The token is the Cloud
- // Bridge credential only; it is unrelated to provider API keys.
+ // Bridge credential only; it is unrelated to provider API keys. The pairing
+ // key authenticates this browser to a local MCP / LM Studio bridge.
//
// Concurrent starts (a settings save triggers syncBridge while the page also
// sends cloud_bridge_start) must not each mint an installation id, so the
@@ -2007,12 +2008,14 @@ export function createCloudRunController({
const stored = await api.storage.local.get([
'webbrainCloudBridgeToken',
'webbrainCloudBridgeBrowserId',
+ 'webbrainCloudBridgePairingKey',
]);
return {
token: stored.webbrainCloudBridgeToken || '',
browserId: stored.webbrainCloudBridgeBrowserId || installationId,
installationId,
extensionVersion: api.runtime.getManifest?.().version || '',
+ pairingKey: stored.webbrainCloudBridgePairingKey || '',
};
}
diff --git a/src/chrome/src/offscreen/cloud-bridge.js b/src/chrome/src/offscreen/cloud-bridge.js
index 94ccf6b46..c70dba6f4 100644
--- a/src/chrome/src/offscreen/cloud-bridge.js
+++ b/src/chrome/src/offscreen/cloud-bridge.js
@@ -24,6 +24,13 @@
'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;
let socket = null;
let bridgeUrl = null;
let enabled = false;
@@ -34,7 +41,7 @@
// 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: '' };
+ let identity = { token: '', browserId: '', installationId: '', extensionVersion: '', pairingKey: '' };
let approval = 'not_required'; // not_required | pending | approved | rejected
function browserInfo() {
@@ -83,6 +90,23 @@
}
}
+ 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 scheduleReconnect() {
if (!enabled || !bridgeUrl || reconnectTimer) return;
const delay = Math.min(30000, 500 * Math.pow(2, reconnectAttempt++));
@@ -135,6 +159,24 @@
return;
}
+ if (msg.type === 'auth_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);
+ return;
+ }
+
if (msg.type === 'connection_pending' || msg.type === 'connection_approved' || msg.type === 'connection_rejected') {
if (!identity.token) return;
if (msg.browserId && msg.browserId !== identity.browserId) return;
@@ -189,9 +231,13 @@
sendJson({ id, ok: false, error: e.message || String(e) }, nextSocket);
}
});
- nextSocket.addEventListener('close', () => {
+ nextSocket.addEventListener('close', (event) => {
if (socket !== nextSocket) return;
socket = null;
+ if (event?.code === PAIRING_CLOSE_CODE) {
+ failPairing(nextSocket, String(event.reason || 'Pairing rejected by the bridge'));
+ return;
+ }
// A rejected browser stays rejected until the settings change.
if (approval === 'rejected') return;
approval = identity.token ? 'pending' : 'not_required';
@@ -223,6 +269,7 @@
browserId: String(msg.browserId || ''),
installationId: String(msg.installationId || ''),
extensionVersion: String(msg.extensionVersion || ''),
+ pairingKey: String(msg.pairingKey || '').trim(),
};
const identityChanged = JSON.stringify(nextIdentity) !== JSON.stringify(identity);
const changed = (bridgeUrl && bridgeUrl !== nextUrl) || identityChanged;
diff --git a/src/chrome/src/ui/locales/cloud-bridge-copy.mjs b/src/chrome/src/ui/locales/cloud-bridge-copy.mjs
index 98f7f11e5..1deea6a45 100644
--- a/src/chrome/src/ui/locales/cloud-bridge-copy.mjs
+++ b/src/chrome/src/ui/locales/cloud-bridge-copy.mjs
@@ -17,6 +17,8 @@ export default {
"st.cb.enabled": 'Let a backend control this browser',
"st.cb.desc": 'WebBrain connects out to the backend below and waits for cloud_* commands. With a token set, the backend must approve this browser before any command runs.',
"st.cb.url": 'Backend WebSocket URL (local ws:// only)',
+ "st.cb.pairing_key": 'Pairing key (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Required by the WebBrain MCP server and the LM Studio plugin. Copy it from ~/.webbrain/bridge-key or run: npx -y @webbrain/mcp-server pairing-key. The key itself is never sent over the connection.',
"st.cb.token": 'Cloud Bridge token',
"st.cb.token_hint": 'Leave empty for a plain local controller (no approval step). This is not a provider API key.',
"st.cb.browser_name": 'Browser name',
@@ -54,6 +56,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'السماح لواجهة خلفية بالتحكم في هذا المتصفح',
"st.cb.desc": 'يتصل WebBrain بالواجهة الخلفية أدناه وينتظر أوامر cloud_*. عند تعيين رمز، يجب أن توافق الواجهة الخلفية على هذا المتصفح قبل تشغيل أي أمر.',
"st.cb.url": 'عنوان WebSocket للواجهة الخلفية (ws:// محلي فقط)',
+ "st.cb.pairing_key": 'مفتاح الإقران (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'مطلوب لخادم MCP الخاص بـ WebBrain وملحق LM Studio. انسخه من ~/.webbrain/bridge-key أو شغّل: npx -y @webbrain/mcp-server pairing-key. لا يُرسَل المفتاح نفسه عبر الاتصال أبدًا.',
"st.cb.token": 'رمز الجسر السحابي',
"st.cb.token_hint": 'اتركه فارغًا لوحدة تحكم محلية عادية (بدون خطوة موافقة). هذا ليس مفتاح API للمزود.',
"st.cb.browser_name": 'اسم المتصفح',
@@ -85,6 +89,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'একটি ব্যাকএন্ডকে এই ব্রাউজার নিয়ন্ত্রণ করতে দিন',
"st.cb.desc": 'WebBrain নিচের ব্যাকএন্ডের সাথে বাইরে থেকে সংযোগ করে এবং cloud_* কমান্ডের জন্য অপেক্ষা করে। টোকেন সেট থাকলে, কোনো কমান্ড চলার আগে ব্যাকএন্ডকে এই ব্রাউজার অনুমোদন করতে হবে।',
"st.cb.url": 'ব্যাকএন্ড WebSocket URL (শুধু স্থানীয় ws://)',
+ "st.cb.pairing_key": 'পেয়ারিং কী (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'WebBrain MCP সার্ভার ও LM Studio প্লাগইনের জন্য প্রয়োজন। ~/.webbrain/bridge-key থেকে কপি করুন অথবা চালান: npx -y @webbrain/mcp-server pairing-key। কী নিজে কখনো সংযোগের মাধ্যমে পাঠানো হয় না।',
"st.cb.token": 'ক্লাউড ব্রিজ টোকেন',
"st.cb.token_hint": 'সাধারণ স্থানীয় কন্ট্রোলারের জন্য খালি রাখুন (কোনো অনুমোদন ধাপ নেই)। এটি প্রদানকারী API কী নয়।',
"st.cb.browser_name": 'ব্রাউজার নাম',
@@ -116,6 +122,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Einem Backend erlauben, diesen Browser zu steuern',
"st.cb.desc": 'WebBrain verbindet sich nach außen mit dem untenstehenden Backend und wartet auf cloud_*-Befehle. Mit gesetztem Token muss das Backend diesen Browser genehmigen, bevor ein Befehl ausgeführt wird.',
"st.cb.url": 'Backend-WebSocket-URL (nur lokales ws://)',
+ "st.cb.pairing_key": 'Kopplungsschlüssel (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Erforderlich für den WebBrain-MCP-Server und das LM-Studio-Plugin. Aus ~/.webbrain/bridge-key kopieren oder ausführen: npx -y @webbrain/mcp-server pairing-key. Der Schlüssel selbst wird nie über die Verbindung gesendet.',
"st.cb.token": 'Cloud-Bridge-Token',
"st.cb.token_hint": 'Für einen einfachen lokalen Controller leer lassen (kein Genehmigungsschritt). Dies ist kein Anbieter-API-Schlüssel.',
"st.cb.browser_name": 'Browsername',
@@ -147,6 +155,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Permitir que un backend controle este navegador',
"st.cb.desc": 'WebBrain se conecta al backend indicado abajo y espera comandos cloud_*. Si hay un token configurado, el backend debe aprobar este navegador antes de ejecutar ningún comando.',
"st.cb.url": 'URL de WebSocket del backend (solo ws:// local)',
+ "st.cb.pairing_key": 'Clave de emparejamiento (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Necesaria para el servidor MCP de WebBrain y el plugin de LM Studio. Cópiala de ~/.webbrain/bridge-key o ejecuta: npx -y @webbrain/mcp-server pairing-key. La clave nunca se envía por la conexión.',
"st.cb.token": 'Token del puente de la nube',
"st.cb.token_hint": 'Déjalo vacío para un controlador local simple (sin paso de aprobación). No es una clave API de proveedor.',
"st.cb.browser_name": 'Nombre del navegador',
@@ -178,6 +188,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'به بک‌اند اجازه بده این مرورگر را کنترل کند',
"st.cb.desc": 'WebBrain به بک‌اند زیر متصل می‌شود و منتظر فرمان‌های cloud_* می‌ماند. اگر رمز تنظیم شده باشد، بک‌اند باید پیش از اجرای هر فرمانی این مرورگر را تأیید کند.',
"st.cb.url": 'نشانی WebSocket بک‌اند (فقط ws:// محلی)',
+ "st.cb.pairing_key": 'کلید جفت‌سازی (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'برای سرور MCP ‏WebBrain و افزونهٔ LM Studio لازم است. آن را از ~/.webbrain/bridge-key کپی کنید یا اجرا کنید: npx -y @webbrain/mcp-server pairing-key. خود کلید هرگز از طریق اتصال ارسال نمی‌شود.',
"st.cb.token": 'رمز پل ابری',
"st.cb.token_hint": 'برای یک کنترل‌کننده محلی ساده خالی بگذارید (بدون مرحله تأیید). این کلید API ارائه‌دهنده نیست.',
"st.cb.browser_name": 'نام مرورگر',
@@ -209,6 +221,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Laisser un backend contrôler ce navigateur',
"st.cb.desc": 'WebBrain se connecte au backend ci-dessous et attend des commandes cloud_*. Si un jeton est défini, le backend doit approuver ce navigateur avant toute exécution de commande.',
"st.cb.url": 'URL WebSocket du backend (ws:// local uniquement)',
+ "st.cb.pairing_key": 'Clé d’appairage (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Requise par le serveur MCP WebBrain et le plugin LM Studio. Copiez-la depuis ~/.webbrain/bridge-key ou exécutez : npx -y @webbrain/mcp-server pairing-key. La clé elle-même n’est jamais envoyée sur la connexion.',
"st.cb.token": 'Jeton du pont Cloud',
"st.cb.token_hint": 'Laissez vide pour un contrôleur local simple (sans étape d’approbation). Il ne s’agit pas d’une clé API de fournisseur.',
"st.cb.browser_name": 'Nom du navigateur',
@@ -240,6 +254,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'אפשר לבקאנד לשלוט בדפדפן הזה',
"st.cb.desc": 'WebBrain מתחבר החוצה אל הבקאנד למטה וממתין לפקודות cloud_*. כאשר מוגדר אסימון, הבקאנד חייב לאשר את הדפדפן הזה לפני שפקודה כלשהי תפעל.',
"st.cb.url": 'כתובת WebSocket של הבקאנד (ws:// מקומי בלבד)',
+ "st.cb.pairing_key": 'מפתח צימוד (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'נדרש לשרת ה-MCP של WebBrain ולתוסף LM Studio. העתיקו אותו מ-~/.webbrain/bridge-key או הריצו: npx -y @webbrain/mcp-server pairing-key. המפתח עצמו לעולם אינו נשלח דרך החיבור.',
"st.cb.token": 'אסימון גשר הענן',
"st.cb.token_hint": 'השאירו ריק עבור בקר מקומי פשוט (ללא שלב אישור). זה אינו מפתח API של ספק.',
"st.cb.browser_name": 'שם הדפדפן',
@@ -271,6 +287,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'किसी बैकएंड को इस ब्राउज़र को नियंत्रित करने दें',
"st.cb.desc": 'WebBrain नीचे दिए गए बैकएंड से बाहर कनेक्ट करता है और cloud_* कमांड की प्रतीक्षा करता है। टोकन सेट होने पर, कोई भी कमांड चलने से पहले बैकएंड को इस ब्राउज़र का अनुमोदन करना होगा।',
"st.cb.url": 'बैकएंड WebSocket URL (केवल स्थानीय ws://)',
+ "st.cb.pairing_key": 'पेयरिंग कुंजी (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'WebBrain MCP सर्वर और LM Studio प्लगइन के लिए आवश्यक। इसे ~/.webbrain/bridge-key से कॉपी करें या चलाएँ: npx -y @webbrain/mcp-server pairing-key। कुंजी स्वयं कभी कनेक्शन पर नहीं भेजी जाती।',
"st.cb.token": 'क्लाउड ब्रिज टोकन',
"st.cb.token_hint": 'सादे स्थानीय कंट्रोलर के लिए खाली छोड़ें (कोई अनुमोदन चरण नहीं)। यह प्रदाता एपीआई कुंजी नहीं है।',
"st.cb.browser_name": 'ब्राउज़र नाम',
@@ -302,6 +320,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Biarkan backend mengontrol browser ini',
"st.cb.desc": 'WebBrain terhubung keluar ke backend di bawah dan menunggu perintah cloud_*. Jika token diisi, backend harus menyetujui browser ini sebelum perintah apa pun berjalan.',
"st.cb.url": 'URL WebSocket backend (hanya ws:// lokal)',
+ "st.cb.pairing_key": 'Kunci pemasangan (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Diperlukan oleh server MCP WebBrain dan plugin LM Studio. Salin dari ~/.webbrain/bridge-key atau jalankan: npx -y @webbrain/mcp-server pairing-key. Kunci itu sendiri tidak pernah dikirim melalui koneksi.',
"st.cb.token": 'Token Cloud Bridge',
"st.cb.token_hint": 'Kosongkan untuk pengontrol lokal biasa (tanpa langkah persetujuan). Ini bukan kunci API penyedia.',
"st.cb.browser_name": 'Nama browser',
@@ -333,6 +353,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'バックエンドによるこのブラウザーの制御を許可する',
"st.cb.desc": 'WebBrain は下のバックエンドへ外向きに接続し、cloud_* コマンドを待ち受けます。トークンが設定されている場合、コマンド実行前にバックエンドがこのブラウザーを承認する必要があります。',
"st.cb.url": 'バックエンド WebSocket URL(ローカル ws:// のみ)',
+ "st.cb.pairing_key": 'ペアリングキー(MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'WebBrain MCP サーバーと LM Studio プラグインで必要です。~/.webbrain/bridge-key からコピーするか、次を実行してください: npx -y @webbrain/mcp-server pairing-key。キー自体が接続経由で送信されることはありません。',
"st.cb.token": 'Cloud Bridge トークン',
"st.cb.token_hint": '通常のローカルコントローラー用には空欄のままにします(承認ステップなし)。これはプロバイダーの API キーではありません。',
"st.cb.browser_name": 'ブラウザー名',
@@ -364,6 +386,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": '백엔드가 이 브라우저를 제어하도록 허용',
"st.cb.desc": 'WebBrain은 아래 백엔드에 연결하여 cloud_* 명령을 기다립니다. 토큰이 설정되어 있으면 명령이 실행되기 전에 백엔드가 이 브라우저를 승인해야 합니다.',
"st.cb.url": '백엔드 WebSocket URL(로컬 ws:// 전용)',
+ "st.cb.pairing_key": '페어링 키 (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'WebBrain MCP 서버와 LM Studio 플러그인에 필요합니다. ~/.webbrain/bridge-key에서 복사하거나 다음을 실행하세요: npx -y @webbrain/mcp-server pairing-key. 키 자체는 연결을 통해 전송되지 않습니다.',
"st.cb.token": 'Cloud Bridge 토큰',
"st.cb.token_hint": '일반 로컬 컨트롤러는 비워 두세요(승인 단계 없음). 제공자 API 키가 아닙니다.',
"st.cb.browser_name": '브라우저 이름',
@@ -395,6 +419,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Benarkan backend mengawal pelayar ini',
"st.cb.desc": 'WebBrain bersambung keluar ke backend di bawah dan menunggu perintah cloud_*. Jika token ditetapkan, backend mesti meluluskan pelayar ini sebelum sebarang perintah berjalan.',
"st.cb.url": 'URL WebSocket backend (ws:// setempat sahaja)',
+ "st.cb.pairing_key": 'Kunci pasangan (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Diperlukan oleh pelayan MCP WebBrain dan pemalam LM Studio. Salin daripada ~/.webbrain/bridge-key atau jalankan: npx -y @webbrain/mcp-server pairing-key. Kunci itu sendiri tidak pernah dihantar melalui sambungan.',
"st.cb.token": 'Token Cloud Bridge',
"st.cb.token_hint": 'Biarkan kosong untuk pengawal setempat biasa (tanpa langkah kelulusan). Ini bukan kunci API pembekal.',
"st.cb.browser_name": 'Nama pelayar',
@@ -426,6 +452,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Een backend deze browser laten bedienen',
"st.cb.desc": 'WebBrain verbindt naar de onderstaande backend en wacht op cloud_*-opdrachten. Met een ingestelde token moet de backend deze browser goedkeuren voordat een opdracht wordt uitgevoerd.',
"st.cb.url": 'Backend-WebSocket-URL (alleen lokale ws://)',
+ "st.cb.pairing_key": 'Koppelingssleutel (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Vereist door de WebBrain MCP-server en de LM Studio-plug-in. Kopieer hem uit ~/.webbrain/bridge-key of voer uit: npx -y @webbrain/mcp-server pairing-key. De sleutel zelf wordt nooit over de verbinding verzonden.',
"st.cb.token": 'Cloud-bridge-token',
"st.cb.token_hint": 'Laat leeg voor een eenvoudige lokale controller (geen goedkeuringsstap). Dit is geen provider-API-sleutel.',
"st.cb.browser_name": 'Browsernaam',
@@ -457,6 +485,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Pozwól backendowi sterować tą przeglądarką',
"st.cb.desc": 'WebBrain łączy się z backendem poniżej i czeka na polecenia cloud_*. Po ustawieniu tokenu backend musi zatwierdzić tę przeglądarkę przed wykonaniem jakiegokolwiek polecenia.',
"st.cb.url": 'Adres URL backendu WebSocket (tylko lokalny ws://)',
+ "st.cb.pairing_key": 'Klucz parowania (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Wymagany przez serwer MCP WebBrain i wtyczkę LM Studio. Skopiuj go z ~/.webbrain/bridge-key lub uruchom: npx -y @webbrain/mcp-server pairing-key. Sam klucz nigdy nie jest wysyłany przez połączenie.',
"st.cb.token": 'Token mostu w chmurze',
"st.cb.token_hint": 'Pozostaw puste dla zwykłego lokalnego kontrolera (bez kroku zatwierdzania). To nie jest klucz API dostawcy.',
"st.cb.browser_name": 'Nazwa przeglądarki',
@@ -488,6 +518,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Permitir que um backend controle este navegador',
"st.cb.desc": 'O WebBrain se conecta ao backend abaixo e aguarda comandos cloud_*. Com um token definido, o backend precisa aprovar este navegador antes da execução de qualquer comando.',
"st.cb.url": 'URL do WebSocket do backend (somente ws:// local)',
+ "st.cb.pairing_key": 'Chave de pareamento (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Necessária para o servidor MCP do WebBrain e o plugin do LM Studio. Copie-a de ~/.webbrain/bridge-key ou execute: npx -y @webbrain/mcp-server pairing-key. A chave em si nunca é enviada pela conexão.',
"st.cb.token": 'Token da ponte na nuvem',
"st.cb.token_hint": 'Deixe vazio para um controlador local simples (sem etapa de aprovação). Isso não é uma chave API de provedor.',
"st.cb.browser_name": 'Nome do navegador',
@@ -519,6 +551,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Разрешить бэкенду управлять этим браузером',
"st.cb.desc": 'WebBrain подключается к бэкенду ниже и ожидает команды cloud_*. Если задан токен, бэкенд должен одобрить этот браузер, прежде чем будет выполнена какая-либо команда.',
"st.cb.url": 'URL бэкенда WebSocket (только локальный ws://)',
+ "st.cb.pairing_key": 'Ключ сопряжения (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Нужен MCP-серверу WebBrain и плагину LM Studio. Скопируйте его из ~/.webbrain/bridge-key или выполните: npx -y @webbrain/mcp-server pairing-key. Сам ключ никогда не передаётся по соединению.',
"st.cb.token": 'Токен облачного моста',
"st.cb.token_hint": 'Оставьте пустым для обычного локального контроллера (без шага одобрения). Это не API-ключ провайдера.',
"st.cb.browser_name": 'Название браузера',
@@ -550,6 +584,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'ให้แบ็กเอนด์ควบคุมเบราว์เซอร์นี้',
"st.cb.desc": 'WebBrain เชื่อมต่อออกไปยังแบ็กเอนด์ด้านล่างและรอคำสั่ง cloud_* เมื่อตั้งค่าโทเค็นไว้ แบ็กเอนด์ต้องอนุมัติเบราว์เซอร์นี้ก่อนคำสั่งใดจะทำงาน',
"st.cb.url": 'URL WebSocket ของแบ็กเอนด์ (เฉพาะ ws:// ภายในเครื่อง)',
+ "st.cb.pairing_key": 'คีย์จับคู่ (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'จำเป็นสำหรับเซิร์ฟเวอร์ MCP ของ WebBrain และปลั๊กอิน LM Studio คัดลอกจาก ~/.webbrain/bridge-key หรือเรียกใช้: npx -y @webbrain/mcp-server pairing-key ตัวคีย์เองจะไม่ถูกส่งผ่านการเชื่อมต่อ',
"st.cb.token": 'โทเค็นบริดจ์คลาวด์',
"st.cb.token_hint": 'เว้นว่างไว้สำหรับตัวควบคุมภายในเครื่องแบบธรรมดา (ไม่มีขั้นตอนการอนุมัติ) นี่ไม่ใช่คีย์ API ของผู้ให้บริการ',
"st.cb.browser_name": 'ชื่อเบราว์เซอร์',
@@ -581,6 +617,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Hayaang kontrolin ng backend ang browser na ito',
"st.cb.desc": 'Kumokonekta ang WebBrain palabas sa backend sa ibaba at naghihintay ng mga cloud_* na command. Kapag may nakatakdang token, kailangang aprubahan ng backend ang browser na ito bago tumakbo ang anumang command.',
"st.cb.url": 'Backend WebSocket URL (lokal na ws:// lang)',
+ "st.cb.pairing_key": 'Pairing key (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Kailangan ng WebBrain MCP server at ng LM Studio plugin. Kopyahin ito mula sa ~/.webbrain/bridge-key o patakbuhin: npx -y @webbrain/mcp-server pairing-key. Hindi kailanman ipinapadala ang key mismo sa koneksyon.',
"st.cb.token": 'Cloud Bridge token',
"st.cb.token_hint": 'Iwang blangko para sa payak na lokal na controller (walang hakbang ng pag-apruba). Hindi ito provider API key.',
"st.cb.browser_name": 'Pangalan ng browser',
@@ -612,6 +650,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Bir arka ucun bu tarayıcıyı kontrol etmesine izin ver',
"st.cb.desc": 'WebBrain aşağıdaki arka uca bağlanır ve cloud_* komutlarını bekler. Jeton ayarlanmışsa, herhangi bir komut çalışmadan önce arka ucun bu tarayıcıyı onaylaması gerekir.',
"st.cb.url": 'Arka uç WebSocket URL’si (yalnızca yerel ws://)',
+ "st.cb.pairing_key": 'Eşleştirme anahtarı (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'WebBrain MCP sunucusu ve LM Studio eklentisi için gereklidir. ~/.webbrain/bridge-key dosyasından kopyalayın veya şunu çalıştırın: npx -y @webbrain/mcp-server pairing-key. Anahtarın kendisi bağlantı üzerinden asla gönderilmez.',
"st.cb.token": 'Bulut Köprü jetonu',
"st.cb.token_hint": 'Düz bir yerel denetleyici için boş bırak (onay adımı olmaz). Bu bir sağlayıcı API anahtarı değildir.',
"st.cb.browser_name": 'Tarayıcı adı',
@@ -643,6 +683,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Дозволити бекенду керувати цим браузером',
"st.cb.desc": 'WebBrain підключається до бекенда нижче й чекає на команди cloud_*. Якщо задано токен, бекенд має схвалити цей браузер, перш ніж виконуватиметься будь-яка команда.',
"st.cb.url": 'URL бекенда WebSocket (лише локальний ws://)',
+ "st.cb.pairing_key": 'Ключ сполучення (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Потрібен MCP-серверу WebBrain і плагіну LM Studio. Скопіюйте його з ~/.webbrain/bridge-key або виконайте: npx -y @webbrain/mcp-server pairing-key. Сам ключ ніколи не надсилається через з’єднання.',
"st.cb.token": 'Токен хмарного мосту',
"st.cb.token_hint": 'Залиште порожнім для звичайного локального контролера (без кроку схвалення). Це не ключ API провайдера.',
"st.cb.browser_name": 'Назва браузера',
@@ -674,6 +716,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Cho phép backend điều khiển trình duyệt này',
"st.cb.desc": 'WebBrain kết nối ra tới backend bên dưới và chờ lệnh cloud_*. Nếu đã đặt mã thông báo, backend phải phê duyệt trình duyệt này trước khi bất kỳ lệnh nào chạy.',
"st.cb.url": 'URL WebSocket của backend (chỉ ws:// cục bộ)',
+ "st.cb.pairing_key": 'Khóa ghép nối (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Bắt buộc với máy chủ MCP của WebBrain và plugin LM Studio. Sao chép từ ~/.webbrain/bridge-key hoặc chạy: npx -y @webbrain/mcp-server pairing-key. Bản thân khóa không bao giờ được gửi qua kết nối.',
"st.cb.token": 'Mã thông báo Cloud Bridge',
"st.cb.token_hint": 'Để trống nếu dùng bộ điều khiển cục bộ thông thường (không cần phê duyệt). Đây không phải khóa API của nhà cung cấp.',
"st.cb.browser_name": 'Tên trình duyệt',
@@ -705,6 +749,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": '允许后端控制此浏览器',
"st.cb.desc": 'WebBrain 会向下方后端发起外连并等待 cloud_* 命令。如果设置了令牌,后端必须先批准此浏览器,然后才能运行任何命令。',
"st.cb.url": '后端 WebSocket URL(仅限本地 ws://)',
+ "st.cb.pairing_key": '配对密钥(MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'WebBrain MCP 服务器和 LM Studio 插件需要此密钥。从 ~/.webbrain/bridge-key 复制,或运行:npx -y @webbrain/mcp-server pairing-key。密钥本身从不通过连接发送。',
"st.cb.token": 'Cloud Bridge 令牌',
"st.cb.token_hint": '普通本地控制器请留空(无批准步骤)。这不是提供商 API 密钥。',
"st.cb.browser_name": '浏览器名称',
diff --git a/src/chrome/src/ui/settings-cloud-bridge.js b/src/chrome/src/ui/settings-cloud-bridge.js
index 8c41f9ed5..c0686f62b 100644
--- a/src/chrome/src/ui/settings-cloud-bridge.js
+++ b/src/chrome/src/ui/settings-cloud-bridge.js
@@ -1,4 +1,4 @@
-// Settings → Bridge tab: URL, token, browser name, connection test.
+// Settings → Bridge tab: URL, pairing key, token, browser name, connection test.
// Sole owner of webbrainCloudBridge* keys; identity keys are
// read by cloud-runs.js when the bridge starts.
import { t } from './i18n.js';
@@ -9,12 +9,14 @@ const KEYS = {
token: 'webbrainCloudBridgeToken',
browserId: 'webbrainCloudBridgeBrowserId',
installationId: 'webbrainCloudBridgeInstallationId',
+ pairingKey: 'webbrainCloudBridgePairingKey',
};
const DEFAULT_URL = 'ws://127.0.0.1:17374/extension';
const $ = (id) => document.getElementById(id);
const enabled = $('cb-enabled');
const urlInput = $('cb-url');
const tokenInput = $('cb-token');
+const pairingKeyInput = $('cb-pairing-key');
const nameInput = $('cb-browser-id');
const installationEl = $('cb-installation-id');
const statusEl = $('cb-status');
@@ -92,6 +94,7 @@ async function load() {
urlInput.value = stored[KEYS.url] || DEFAULT_URL;
markActivePill(urlInput.value);
tokenInput.value = stored[KEYS.token] || '';
+ pairingKeyInput.value = stored[KEYS.pairingKey] || '';
nameInput.value = stored[KEYS.browserId] || '';
installationEl.textContent = stored[KEYS.installationId] || '—';
const approvalDetails = $('cb-approval-details');
@@ -108,7 +111,7 @@ async function refresh() {
async function save() {
const url = normalizeUrl(urlInput.value);
urlInput.value = url;
- const patch = { [KEYS.url]: url, [KEYS.enabled]: enabled.checked, [KEYS.token]: tokenInput.value.trim() };
+ const patch = { [KEYS.url]: url, [KEYS.enabled]: enabled.checked, [KEYS.token]: tokenInput.value.trim(), [KEYS.pairingKey]: pairingKeyInput.value.trim() };
const name = nameInput.value.trim();
await chrome.storage.local.set(patch);
if (name) await chrome.storage.local.set({ [KEYS.browserId]: name });
diff --git a/src/chrome/src/ui/settings.html b/src/chrome/src/ui/settings.html
index 437893ed2..c3846268d 100644
--- a/src/chrome/src/ui/settings.html
+++ b/src/chrome/src/ui/settings.html
@@ -728,6 +728,11 @@
<span class="cloud-bridge-url-label" data-i18n="st.cb.url"></span>
<input class="setting-input" type="text" id="cb-url" inputmode="url" autocomplete="off" spellcheck="false" placeholder="ws://127.0.0.1:17374/extension">
</label>
+ <label class="cloud-bridge-url-field" for="cb-pairing-key" style="margin-top:12px;">
+ <span class="cloud-bridge-url-label" data-i18n="st.cb.pairing_key"></span>
+ <input class="setting-input" type="password" id="cb-pairing-key" autocomplete="off" spellcheck="false">
+ </label>
+ <div class="setting-desc" style="margin-top:4px;" data-i18n="st.cb.pairing_key_hint"></div>
<details class="advanced-settings" id="cb-approval-details" style="margin-top:12px;">
<summary data-i18n="st.cb.approval_summary"></summary>
<div class="advanced-settings-body">
diff --git a/src/firefox/src/background.js b/src/firefox/src/background.js
index 94c788044..0d1058b3d 100644
--- a/src/firefox/src/background.js
+++ b/src/firefox/src/background.js
@@ -1281,7 +1281,8 @@ browser.storage.onChanged.addListener((changes, areaName) => {
setApiMutationObserverEnabled(value === undefined || value === true);
}
if (changes.webbrainCloudBridgeEnabled || changes.webbrainCloudBridgeUrl
- || changes.webbrainCloudBridgeToken || changes.webbrainCloudBridgeBrowserId) {
+ || changes.webbrainCloudBridgeToken || changes.webbrainCloudBridgeBrowserId
+ || changes.webbrainCloudBridgePairingKey) {
cloudRunController.syncBridge().catch(() => {});
}
if (areaName === 'local' && changes.browserBatchEnabled) {
diff --git a/src/firefox/src/cloud-bridge.js b/src/firefox/src/cloud-bridge.js
index 9d68aed5f..440b355a6 100644
--- a/src/firefox/src/cloud-bridge.js
+++ b/src/firefox/src/cloud-bridge.js
@@ -21,6 +21,20 @@ 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('');
+}
export function createCloudBridge({ dispatch, WebSocketImpl = globalThis.WebSocket, nav = globalThis.navigator } = {}) {
let socket = null;
@@ -31,7 +45,7 @@ export function createCloudBridge({ dispatch, WebSocketImpl = globalThis.WebSock
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: '' };
+ let identity = { token: '', browserId: '', installationId: '', extensionVersion: '', pairingKey: '' };
let approval = 'not_required'; // not_required | pending | approved | rejected
function browserInfo() {
@@ -72,6 +86,16 @@ export function createCloudBridge({ dispatch, WebSocketImpl = globalThis.WebSock
}
}
+ // 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 scheduleReconnect() {
if (!enabled || !bridgeUrl || reconnectTimer) return;
const delay = Math.min(30000, 500 * Math.pow(2, reconnectAttempt++));
@@ -124,6 +148,24 @@ export function createCloudBridge({ dispatch, WebSocketImpl = globalThis.WebSock
return;
}
+ if (msg.type === 'auth_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);
+ return;
+ }
+
if (msg.type === 'connection_pending' || msg.type === 'connection_approved' || msg.type === 'connection_rejected') {
if (!identity.token) return;
if (msg.browserId && msg.browserId !== identity.browserId) return;
@@ -173,9 +215,13 @@ export function createCloudBridge({ dispatch, WebSocketImpl = globalThis.WebSock
sendJson({ id, ok: false, error: e.message || String(e) }, nextSocket);
}
});
- nextSocket.addEventListener('close', () => {
+ nextSocket.addEventListener('close', (event) => {
if (socket !== nextSocket) return;
socket = null;
+ if (event?.code === PAIRING_CLOSE_CODE) {
+ failPairing(nextSocket, String(event.reason || 'Pairing rejected by the bridge'));
+ return;
+ }
// A rejected browser stays rejected until the settings change.
if (approval === 'rejected') return;
approval = identity.token ? 'pending' : 'not_required';
@@ -205,6 +251,7 @@ export function createCloudBridge({ dispatch, WebSocketImpl = globalThis.WebSock
browserId: String(msg.browserId || ''),
installationId: String(msg.installationId || ''),
extensionVersion: String(msg.extensionVersion || ''),
+ pairingKey: String(msg.pairingKey || '').trim(),
};
const identityChanged = JSON.stringify(nextIdentity) !== JSON.stringify(identity);
const changed = (bridgeUrl && bridgeUrl !== nextUrl) || identityChanged;
diff --git a/src/firefox/src/cloud-runs.js b/src/firefox/src/cloud-runs.js
index d32c888c1..21d0b7a7f 100644
--- a/src/firefox/src/cloud-runs.js
+++ b/src/firefox/src/cloud-runs.js
@@ -1984,7 +1984,8 @@ export function createCloudRunController({
}
// Persistent bridge identity (chrome.storage.local). The token is the Cloud
- // Bridge credential only; it is unrelated to provider API keys.
+ // Bridge credential only; it is unrelated to provider API keys. The pairing
+ // key authenticates this browser to a local MCP / LM Studio bridge.
//
// Concurrent starts (a settings save triggers syncBridge while the page also
// sends cloud_bridge_start) must not each mint an installation id, so the
@@ -2008,12 +2009,14 @@ export function createCloudRunController({
const stored = await api.storage.local.get([
'webbrainCloudBridgeToken',
'webbrainCloudBridgeBrowserId',
+ 'webbrainCloudBridgePairingKey',
]);
return {
token: stored.webbrainCloudBridgeToken || '',
browserId: stored.webbrainCloudBridgeBrowserId || installationId,
installationId,
extensionVersion: api.runtime.getManifest?.().version || '',
+ pairingKey: stored.webbrainCloudBridgePairingKey || '',
};
}
diff --git a/src/firefox/src/ui/locales/cloud-bridge-copy.mjs b/src/firefox/src/ui/locales/cloud-bridge-copy.mjs
index 6023810fe..7a5d76232 100644
--- a/src/firefox/src/ui/locales/cloud-bridge-copy.mjs
+++ b/src/firefox/src/ui/locales/cloud-bridge-copy.mjs
@@ -17,6 +17,8 @@ export default {
"st.cb.enabled": 'Let a backend control this browser',
"st.cb.desc": 'WebBrain connects out to the backend below and waits for cloud_* commands. With a token set, the backend must approve this browser before any command runs.',
"st.cb.url": 'Backend WebSocket URL (local ws:// only)',
+ "st.cb.pairing_key": 'Pairing key (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Required by the WebBrain MCP server and the LM Studio plugin. Copy it from ~/.webbrain/bridge-key or run: npx -y @webbrain/mcp-server pairing-key. The key itself is never sent over the connection.',
"st.cb.token": 'Cloud Bridge token',
"st.cb.token_hint": 'Leave empty for a plain local controller (no approval step). This is not a provider API key.',
"st.cb.browser_name": 'Browser name',
@@ -54,6 +56,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'السماح لواجهة خلفية بالتحكم في هذا المتصفح',
"st.cb.desc": 'يتصل WebBrain بالواجهة الخلفية أدناه وينتظر أوامر cloud_*. عند تعيين رمز، يجب أن توافق الواجهة الخلفية على هذا المتصفح قبل تشغيل أي أمر.',
"st.cb.url": 'عنوان WebSocket للواجهة الخلفية (ws:// محلي فقط)',
+ "st.cb.pairing_key": 'مفتاح الإقران (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'مطلوب لخادم MCP الخاص بـ WebBrain وملحق LM Studio. انسخه من ~/.webbrain/bridge-key أو شغّل: npx -y @webbrain/mcp-server pairing-key. لا يُرسَل المفتاح نفسه عبر الاتصال أبدًا.',
"st.cb.token": 'رمز الجسر السحابي',
"st.cb.token_hint": 'اتركه فارغًا لوحدة تحكم محلية عادية (بدون خطوة موافقة). هذا ليس مفتاح API للمزود.',
"st.cb.browser_name": 'اسم المتصفح',
@@ -85,6 +89,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'একটি ব্যাকএন্ডকে এই ব্রাউজার নিয়ন্ত্রণ করতে দিন',
"st.cb.desc": 'WebBrain নিচের ব্যাকএন্ডের সাথে বাইরে থেকে সংযোগ করে এবং cloud_* কমান্ডের জন্য অপেক্ষা করে। টোকেন সেট থাকলে, কোনো কমান্ড চলার আগে ব্যাকএন্ডকে এই ব্রাউজার অনুমোদন করতে হবে।',
"st.cb.url": 'ব্যাকএন্ড WebSocket URL (শুধু স্থানীয় ws://)',
+ "st.cb.pairing_key": 'পেয়ারিং কী (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'WebBrain MCP সার্ভার ও LM Studio প্লাগইনের জন্য প্রয়োজন। ~/.webbrain/bridge-key থেকে কপি করুন অথবা চালান: npx -y @webbrain/mcp-server pairing-key। কী নিজে কখনো সংযোগের মাধ্যমে পাঠানো হয় না।',
"st.cb.token": 'ক্লাউড ব্রিজ টোকেন',
"st.cb.token_hint": 'সাধারণ স্থানীয় কন্ট্রোলারের জন্য খালি রাখুন (কোনো অনুমোদন ধাপ নেই)। এটি প্রদানকারী API কী নয়।',
"st.cb.browser_name": 'ব্রাউজার নাম',
@@ -116,6 +122,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Einem Backend erlauben, diesen Browser zu steuern',
"st.cb.desc": 'WebBrain verbindet sich nach außen mit dem untenstehenden Backend und wartet auf cloud_*-Befehle. Mit gesetztem Token muss das Backend diesen Browser genehmigen, bevor ein Befehl ausgeführt wird.',
"st.cb.url": 'Backend-WebSocket-URL (nur lokales ws://)',
+ "st.cb.pairing_key": 'Kopplungsschlüssel (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Erforderlich für den WebBrain-MCP-Server und das LM-Studio-Plugin. Aus ~/.webbrain/bridge-key kopieren oder ausführen: npx -y @webbrain/mcp-server pairing-key. Der Schlüssel selbst wird nie über die Verbindung gesendet.',
"st.cb.token": 'Cloud-Bridge-Token',
"st.cb.token_hint": 'Für einen einfachen lokalen Controller leer lassen (kein Genehmigungsschritt). Dies ist kein Anbieter-API-Schlüssel.',
"st.cb.browser_name": 'Browsername',
@@ -147,6 +155,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Permitir que un backend controle este navegador',
"st.cb.desc": 'WebBrain se conecta al backend indicado abajo y espera comandos cloud_*. Si hay un token configurado, el backend debe aprobar este navegador antes de ejecutar ningún comando.',
"st.cb.url": 'URL de WebSocket del backend (solo ws:// local)',
+ "st.cb.pairing_key": 'Clave de emparejamiento (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Necesaria para el servidor MCP de WebBrain y el plugin de LM Studio. Cópiala de ~/.webbrain/bridge-key o ejecuta: npx -y @webbrain/mcp-server pairing-key. La clave nunca se envía por la conexión.',
"st.cb.token": 'Token del puente de la nube',
"st.cb.token_hint": 'Déjalo vacío para un controlador local simple (sin paso de aprobación). No es una clave API de proveedor.',
"st.cb.browser_name": 'Nombre del navegador',
@@ -178,6 +188,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'به بک‌اند اجازه بده این مرورگر را کنترل کند',
"st.cb.desc": 'WebBrain به بک‌اند زیر متصل می‌شود و منتظر فرمان‌های cloud_* می‌ماند. اگر رمز تنظیم شده باشد، بک‌اند باید پیش از اجرای هر فرمانی این مرورگر را تأیید کند.',
"st.cb.url": 'نشانی WebSocket بک‌اند (فقط ws:// محلی)',
+ "st.cb.pairing_key": 'کلید جفت‌سازی (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'برای سرور MCP ‏WebBrain و افزونهٔ LM Studio لازم است. آن را از ~/.webbrain/bridge-key کپی کنید یا اجرا کنید: npx -y @webbrain/mcp-server pairing-key. خود کلید هرگز از طریق اتصال ارسال نمی‌شود.',
"st.cb.token": 'رمز پل ابری',
"st.cb.token_hint": 'برای یک کنترل‌کننده محلی ساده خالی بگذارید (بدون مرحله تأیید). این کلید API ارائه‌دهنده نیست.',
"st.cb.browser_name": 'نام مرورگر',
@@ -209,6 +221,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Laisser un backend contrôler ce navigateur',
"st.cb.desc": 'WebBrain se connecte au backend ci-dessous et attend des commandes cloud_*. Si un jeton est défini, le backend doit approuver ce navigateur avant toute exécution de commande.',
"st.cb.url": 'URL WebSocket du backend (ws:// local uniquement)',
+ "st.cb.pairing_key": 'Clé d’appairage (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Requise par le serveur MCP WebBrain et le plugin LM Studio. Copiez-la depuis ~/.webbrain/bridge-key ou exécutez : npx -y @webbrain/mcp-server pairing-key. La clé elle-même n’est jamais envoyée sur la connexion.',
"st.cb.token": 'Jeton du pont Cloud',
"st.cb.token_hint": 'Laissez vide pour un contrôleur local simple (sans étape d’approbation). Il ne s’agit pas d’une clé API de fournisseur.',
"st.cb.browser_name": 'Nom du navigateur',
@@ -240,6 +254,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'אפשר לבקאנד לשלוט בדפדפן הזה',
"st.cb.desc": 'WebBrain מתחבר החוצה אל הבקאנד למטה וממתין לפקודות cloud_*. כאשר מוגדר אסימון, הבקאנד חייב לאשר את הדפדפן הזה לפני שפקודה כלשהי תפעל.',
"st.cb.url": 'כתובת WebSocket של הבקאנד (ws:// מקומי בלבד)',
+ "st.cb.pairing_key": 'מפתח צימוד (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'נדרש לשרת ה-MCP של WebBrain ולתוסף LM Studio. העתיקו אותו מ-~/.webbrain/bridge-key או הריצו: npx -y @webbrain/mcp-server pairing-key. המפתח עצמו לעולם אינו נשלח דרך החיבור.',
"st.cb.token": 'אסימון גשר הענן',
"st.cb.token_hint": 'השאירו ריק עבור בקר מקומי פשוט (ללא שלב אישור). זה אינו מפתח API של ספק.',
"st.cb.browser_name": 'שם הדפדפן',
@@ -271,6 +287,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'किसी बैकएंड को इस ब्राउज़र को नियंत्रित करने दें',
"st.cb.desc": 'WebBrain नीचे दिए गए बैकएंड से बाहर कनेक्ट करता है और cloud_* कमांड की प्रतीक्षा करता है। टोकन सेट होने पर, कोई भी कमांड चलने से पहले बैकएंड को इस ब्राउज़र का अनुमोदन करना होगा।',
"st.cb.url": 'बैकएंड WebSocket URL (केवल स्थानीय ws://)',
+ "st.cb.pairing_key": 'पेयरिंग कुंजी (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'WebBrain MCP सर्वर और LM Studio प्लगइन के लिए आवश्यक। इसे ~/.webbrain/bridge-key से कॉपी करें या चलाएँ: npx -y @webbrain/mcp-server pairing-key। कुंजी स्वयं कभी कनेक्शन पर नहीं भेजी जाती।',
"st.cb.token": 'क्लाउड ब्रिज टोकन',
"st.cb.token_hint": 'सादे स्थानीय कंट्रोलर के लिए खाली छोड़ें (कोई अनुमोदन चरण नहीं)। यह प्रदाता एपीआई कुंजी नहीं है।',
"st.cb.browser_name": 'ब्राउज़र नाम',
@@ -302,6 +320,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Biarkan backend mengontrol browser ini',
"st.cb.desc": 'WebBrain terhubung keluar ke backend di bawah dan menunggu perintah cloud_*. Jika token diisi, backend harus menyetujui browser ini sebelum perintah apa pun berjalan.',
"st.cb.url": 'URL WebSocket backend (hanya ws:// lokal)',
+ "st.cb.pairing_key": 'Kunci pemasangan (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Diperlukan oleh server MCP WebBrain dan plugin LM Studio. Salin dari ~/.webbrain/bridge-key atau jalankan: npx -y @webbrain/mcp-server pairing-key. Kunci itu sendiri tidak pernah dikirim melalui koneksi.',
"st.cb.token": 'Token Cloud Bridge',
"st.cb.token_hint": 'Kosongkan untuk pengontrol lokal biasa (tanpa langkah persetujuan). Ini bukan kunci API penyedia.',
"st.cb.browser_name": 'Nama browser',
@@ -333,6 +353,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'バックエンドによるこのブラウザーの制御を許可する',
"st.cb.desc": 'WebBrain は下のバックエンドへ外向きに接続し、cloud_* コマンドを待ち受けます。トークンが設定されている場合、コマンド実行前にバックエンドがこのブラウザーを承認する必要があります。',
"st.cb.url": 'バックエンド WebSocket URL(ローカル ws:// のみ)',
+ "st.cb.pairing_key": 'ペアリングキー(MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'WebBrain MCP サーバーと LM Studio プラグインで必要です。~/.webbrain/bridge-key からコピーするか、次を実行してください: npx -y @webbrain/mcp-server pairing-key。キー自体が接続経由で送信されることはありません。',
"st.cb.token": 'Cloud Bridge トークン',
"st.cb.token_hint": '通常のローカルコントローラー用には空欄のままにします(承認ステップなし)。これはプロバイダーの API キーではありません。',
"st.cb.browser_name": 'ブラウザー名',
@@ -364,6 +386,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": '백엔드가 이 브라우저를 제어하도록 허용',
"st.cb.desc": 'WebBrain은 아래 백엔드에 연결하여 cloud_* 명령을 기다립니다. 토큰이 설정되어 있으면 명령이 실행되기 전에 백엔드가 이 브라우저를 승인해야 합니다.',
"st.cb.url": '백엔드 WebSocket URL(로컬 ws:// 전용)',
+ "st.cb.pairing_key": '페어링 키 (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'WebBrain MCP 서버와 LM Studio 플러그인에 필요합니다. ~/.webbrain/bridge-key에서 복사하거나 다음을 실행하세요: npx -y @webbrain/mcp-server pairing-key. 키 자체는 연결을 통해 전송되지 않습니다.',
"st.cb.token": 'Cloud Bridge 토큰',
"st.cb.token_hint": '일반 로컬 컨트롤러는 비워 두세요(승인 단계 없음). 제공자 API 키가 아닙니다.',
"st.cb.browser_name": '브라우저 이름',
@@ -395,6 +419,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Benarkan backend mengawal pelayar ini',
"st.cb.desc": 'WebBrain bersambung keluar ke backend di bawah dan menunggu perintah cloud_*. Jika token ditetapkan, backend mesti meluluskan pelayar ini sebelum sebarang perintah berjalan.',
"st.cb.url": 'URL WebSocket backend (ws:// setempat sahaja)',
+ "st.cb.pairing_key": 'Kunci pasangan (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Diperlukan oleh pelayan MCP WebBrain dan pemalam LM Studio. Salin daripada ~/.webbrain/bridge-key atau jalankan: npx -y @webbrain/mcp-server pairing-key. Kunci itu sendiri tidak pernah dihantar melalui sambungan.',
"st.cb.token": 'Token Cloud Bridge',
"st.cb.token_hint": 'Biarkan kosong untuk pengawal setempat biasa (tanpa langkah kelulusan). Ini bukan kunci API pembekal.',
"st.cb.browser_name": 'Nama pelayar',
@@ -426,6 +452,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Een backend deze browser laten bedienen',
"st.cb.desc": 'WebBrain verbindt naar de onderstaande backend en wacht op cloud_*-opdrachten. Met een ingestelde token moet de backend deze browser goedkeuren voordat een opdracht wordt uitgevoerd.',
"st.cb.url": 'Backend-WebSocket-URL (alleen lokale ws://)',
+ "st.cb.pairing_key": 'Koppelingssleutel (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Vereist door de WebBrain MCP-server en de LM Studio-plug-in. Kopieer hem uit ~/.webbrain/bridge-key of voer uit: npx -y @webbrain/mcp-server pairing-key. De sleutel zelf wordt nooit over de verbinding verzonden.',
"st.cb.token": 'Cloud-bridge-token',
"st.cb.token_hint": 'Laat leeg voor een eenvoudige lokale controller (geen goedkeuringsstap). Dit is geen provider-API-sleutel.',
"st.cb.browser_name": 'Browsernaam',
@@ -457,6 +485,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Pozwól backendowi sterować tą przeglądarką',
"st.cb.desc": 'WebBrain łączy się z backendem poniżej i czeka na polecenia cloud_*. Po ustawieniu tokenu backend musi zatwierdzić tę przeglądarkę przed wykonaniem jakiegokolwiek polecenia.',
"st.cb.url": 'Adres URL backendu WebSocket (tylko lokalny ws://)',
+ "st.cb.pairing_key": 'Klucz parowania (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Wymagany przez serwer MCP WebBrain i wtyczkę LM Studio. Skopiuj go z ~/.webbrain/bridge-key lub uruchom: npx -y @webbrain/mcp-server pairing-key. Sam klucz nigdy nie jest wysyłany przez połączenie.',
"st.cb.token": 'Token mostu w chmurze',
"st.cb.token_hint": 'Pozostaw puste dla zwykłego lokalnego kontrolera (bez kroku zatwierdzania). To nie jest klucz API dostawcy.',
"st.cb.browser_name": 'Nazwa przeglądarki',
@@ -488,6 +518,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Permitir que um backend controle este navegador',
"st.cb.desc": 'O WebBrain se conecta ao backend abaixo e aguarda comandos cloud_*. Com um token definido, o backend precisa aprovar este navegador antes da execução de qualquer comando.',
"st.cb.url": 'URL do WebSocket do backend (somente ws:// local)',
+ "st.cb.pairing_key": 'Chave de pareamento (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Necessária para o servidor MCP do WebBrain e o plugin do LM Studio. Copie-a de ~/.webbrain/bridge-key ou execute: npx -y @webbrain/mcp-server pairing-key. A chave em si nunca é enviada pela conexão.',
"st.cb.token": 'Token da ponte na nuvem',
"st.cb.token_hint": 'Deixe vazio para um controlador local simples (sem etapa de aprovação). Isso não é uma chave API de provedor.',
"st.cb.browser_name": 'Nome do navegador',
@@ -519,6 +551,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Разрешить бэкенду управлять этим браузером',
"st.cb.desc": 'WebBrain подключается к бэкенду ниже и ожидает команды cloud_*. Если задан токен, бэкенд должен одобрить этот браузер, прежде чем будет выполнена какая-либо команда.',
"st.cb.url": 'URL бэкенда WebSocket (только локальный ws://)',
+ "st.cb.pairing_key": 'Ключ сопряжения (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Нужен MCP-серверу WebBrain и плагину LM Studio. Скопируйте его из ~/.webbrain/bridge-key или выполните: npx -y @webbrain/mcp-server pairing-key. Сам ключ никогда не передаётся по соединению.',
"st.cb.token": 'Токен облачного моста',
"st.cb.token_hint": 'Оставьте пустым для обычного локального контроллера (без шага одобрения). Это не API-ключ провайдера.',
"st.cb.browser_name": 'Название браузера',
@@ -550,6 +584,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'ให้แบ็กเอนด์ควบคุมเบราว์เซอร์นี้',
"st.cb.desc": 'WebBrain เชื่อมต่อออกไปยังแบ็กเอนด์ด้านล่างและรอคำสั่ง cloud_* เมื่อตั้งค่าโทเค็นไว้ แบ็กเอนด์ต้องอนุมัติเบราว์เซอร์นี้ก่อนคำสั่งใดจะทำงาน',
"st.cb.url": 'URL WebSocket ของแบ็กเอนด์ (เฉพาะ ws:// ภายในเครื่อง)',
+ "st.cb.pairing_key": 'คีย์จับคู่ (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'จำเป็นสำหรับเซิร์ฟเวอร์ MCP ของ WebBrain และปลั๊กอิน LM Studio คัดลอกจาก ~/.webbrain/bridge-key หรือเรียกใช้: npx -y @webbrain/mcp-server pairing-key ตัวคีย์เองจะไม่ถูกส่งผ่านการเชื่อมต่อ',
"st.cb.token": 'โทเค็นบริดจ์คลาวด์',
"st.cb.token_hint": 'เว้นว่างไว้สำหรับตัวควบคุมภายในเครื่องแบบธรรมดา (ไม่มีขั้นตอนการอนุมัติ) นี่ไม่ใช่คีย์ API ของผู้ให้บริการ',
"st.cb.browser_name": 'ชื่อเบราว์เซอร์',
@@ -581,6 +617,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Hayaang kontrolin ng backend ang browser na ito',
"st.cb.desc": 'Kumokonekta ang WebBrain palabas sa backend sa ibaba at naghihintay ng mga cloud_* na command. Kapag may nakatakdang token, kailangang aprubahan ng backend ang browser na ito bago tumakbo ang anumang command.',
"st.cb.url": 'Backend WebSocket URL (lokal na ws:// lang)',
+ "st.cb.pairing_key": 'Pairing key (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Kailangan ng WebBrain MCP server at ng LM Studio plugin. Kopyahin ito mula sa ~/.webbrain/bridge-key o patakbuhin: npx -y @webbrain/mcp-server pairing-key. Hindi kailanman ipinapadala ang key mismo sa koneksyon.',
"st.cb.token": 'Cloud Bridge token',
"st.cb.token_hint": 'Iwang blangko para sa payak na lokal na controller (walang hakbang ng pag-apruba). Hindi ito provider API key.',
"st.cb.browser_name": 'Pangalan ng browser',
@@ -612,6 +650,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Bir arka ucun bu tarayıcıyı kontrol etmesine izin ver',
"st.cb.desc": 'WebBrain aşağıdaki arka uca bağlanır ve cloud_* komutlarını bekler. Jeton ayarlanmışsa, herhangi bir komut çalışmadan önce arka ucun bu tarayıcıyı onaylaması gerekir.',
"st.cb.url": 'Arka uç WebSocket URL’si (yalnızca yerel ws://)',
+ "st.cb.pairing_key": 'Eşleştirme anahtarı (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'WebBrain MCP sunucusu ve LM Studio eklentisi için gereklidir. ~/.webbrain/bridge-key dosyasından kopyalayın veya şunu çalıştırın: npx -y @webbrain/mcp-server pairing-key. Anahtarın kendisi bağlantı üzerinden asla gönderilmez.',
"st.cb.token": 'Bulut Köprü jetonu',
"st.cb.token_hint": 'Düz bir yerel denetleyici için boş bırak (onay adımı olmaz). Bu bir sağlayıcı API anahtarı değildir.',
"st.cb.browser_name": 'Tarayıcı adı',
@@ -643,6 +683,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Дозволити бекенду керувати цим браузером',
"st.cb.desc": 'WebBrain підключається до бекенда нижче й чекає на команди cloud_*. Якщо задано токен, бекенд має схвалити цей браузер, перш ніж виконуватиметься будь-яка команда.',
"st.cb.url": 'URL бекенда WebSocket (лише локальний ws://)',
+ "st.cb.pairing_key": 'Ключ сполучення (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Потрібен MCP-серверу WebBrain і плагіну LM Studio. Скопіюйте його з ~/.webbrain/bridge-key або виконайте: npx -y @webbrain/mcp-server pairing-key. Сам ключ ніколи не надсилається через з’єднання.',
"st.cb.token": 'Токен хмарного мосту',
"st.cb.token_hint": 'Залиште порожнім для звичайного локального контролера (без кроку схвалення). Це не ключ API провайдера.',
"st.cb.browser_name": 'Назва браузера',
@@ -674,6 +716,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": 'Cho phép backend điều khiển trình duyệt này',
"st.cb.desc": 'WebBrain kết nối ra tới backend bên dưới và chờ lệnh cloud_*. Nếu đã đặt mã thông báo, backend phải phê duyệt trình duyệt này trước khi bất kỳ lệnh nào chạy.',
"st.cb.url": 'URL WebSocket của backend (chỉ ws:// cục bộ)',
+ "st.cb.pairing_key": 'Khóa ghép nối (MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'Bắt buộc với máy chủ MCP của WebBrain và plugin LM Studio. Sao chép từ ~/.webbrain/bridge-key hoặc chạy: npx -y @webbrain/mcp-server pairing-key. Bản thân khóa không bao giờ được gửi qua kết nối.',
"st.cb.token": 'Mã thông báo Cloud Bridge',
"st.cb.token_hint": 'Để trống nếu dùng bộ điều khiển cục bộ thông thường (không cần phê duyệt). Đây không phải khóa API của nhà cung cấp.',
"st.cb.browser_name": 'Tên trình duyệt',
@@ -705,6 +749,8 @@ export const cloudBridgeTranslations = Object.freeze({
"st.cb.enabled": '允许后端控制此浏览器',
"st.cb.desc": 'WebBrain 会向下方后端发起外连并等待 cloud_* 命令。如果设置了令牌,后端必须先批准此浏览器,然后才能运行任何命令。',
"st.cb.url": '后端 WebSocket URL(仅限本地 ws://)',
+ "st.cb.pairing_key": '配对密钥(MCP / LM Studio)',
+ "st.cb.pairing_key_hint": 'WebBrain MCP 服务器和 LM Studio 插件需要此密钥。从 ~/.webbrain/bridge-key 复制,或运行:npx -y @webbrain/mcp-server pairing-key。密钥本身从不通过连接发送。',
"st.cb.token": 'Cloud Bridge 令牌',
"st.cb.token_hint": '普通本地控制器请留空(无批准步骤)。这不是提供商 API 密钥。',
"st.cb.browser_name": '浏览器名称',
diff --git a/src/firefox/src/ui/settings-cloud-bridge.js b/src/firefox/src/ui/settings-cloud-bridge.js
index cf13f7dda..ff4fda791 100644
--- a/src/firefox/src/ui/settings-cloud-bridge.js
+++ b/src/firefox/src/ui/settings-cloud-bridge.js
@@ -1,4 +1,4 @@
-// Settings → Bridge tab: URL, token, browser name, connection test.
+// Settings → Bridge tab: URL, pairing key, token, browser name, connection test.
// Sole owner of webbrainCloudBridge* keys; identity keys are
// read by cloud-runs.js when the bridge starts.
import { t } from './i18n.js';
@@ -9,12 +9,14 @@ const KEYS = {
token: 'webbrainCloudBridgeToken',
browserId: 'webbrainCloudBridgeBrowserId',
installationId: 'webbrainCloudBridgeInstallationId',
+ pairingKey: 'webbrainCloudBridgePairingKey',
};
const DEFAULT_URL = 'ws://127.0.0.1:17374/extension';
const $ = (id) => document.getElementById(id);
const enabled = $('cb-enabled');
const urlInput = $('cb-url');
const tokenInput = $('cb-token');
+const pairingKeyInput = $('cb-pairing-key');
const nameInput = $('cb-browser-id');
const installationEl = $('cb-installation-id');
const statusEl = $('cb-status');
@@ -88,6 +90,7 @@ async function load() {
urlInput.value = stored[KEYS.url] || DEFAULT_URL;
markActivePill(urlInput.value);
tokenInput.value = stored[KEYS.token] || '';
+ pairingKeyInput.value = stored[KEYS.pairingKey] || '';
nameInput.value = stored[KEYS.browserId] || '';
installationEl.textContent = stored[KEYS.installationId] || '—';
const approvalDetails = $('cb-approval-details');
@@ -104,7 +107,7 @@ async function refresh() {
async function save() {
const url = normalizeUrl(urlInput.value);
urlInput.value = url;
- const patch = { [KEYS.url]: url, [KEYS.enabled]: enabled.checked, [KEYS.token]: tokenInput.value.trim() };
+ const patch = { [KEYS.url]: url, [KEYS.enabled]: enabled.checked, [KEYS.token]: tokenInput.value.trim(), [KEYS.pairingKey]: pairingKeyInput.value.trim() };
const name = nameInput.value.trim();
await browser.storage.local.set(patch);
if (name) await browser.storage.local.set({ [KEYS.browserId]: name });
diff --git a/src/firefox/src/ui/settings.html b/src/firefox/src/ui/settings.html
index 6e9b0366c..0f8050d1d 100644
--- a/src/firefox/src/ui/settings.html
+++ b/src/firefox/src/ui/settings.html
@@ -708,6 +708,11 @@
<span class="cloud-bridge-url-label" data-i18n="st.cb.url"></span>
<input class="setting-input" type="text" id="cb-url" inputmode="url" autocomplete="off" spellcheck="false" placeholder="ws://127.0.0.1:17374/extension">
</label>
+ <label class="cloud-bridge-url-field" for="cb-pairing-key" style="margin-top:12px;">
+ <span class="cloud-bridge-url-label" data-i18n="st.cb.pairing_key"></span>
+ <input class="setting-input" type="password" id="cb-pairing-key" autocomplete="off" spellcheck="false">
+ </label>
+ <div class="setting-desc" style="margin-top:4px;" data-i18n="st.cb.pairing_key_hint"></div>
<details class="advanced-settings" id="cb-approval-details" style="margin-top:12px;">
<summary data-i18n="st.cb.approval_summary"></summary>
<div class="advanced-settings-body">
diff --git a/test/cloud-bridge-approval.mjs b/test/cloud-bridge-approval.mjs
index 35ca8c486..316e7a6f6 100644
--- a/test/cloud-bridge-approval.mjs
+++ b/test/cloud-bridge-approval.mjs
@@ -31,6 +31,8 @@ function harness({ WebSocketImpl, sendMessage = async () => ({ runId: 'r1', stat
}
vm.runInNewContext(source, {
URL,
+ TextEncoder,
+ crypto: globalThis.crypto,
WebSocket: WebSocketImpl || FakeWebSocket,
navigator: { userAgent: 'Mozilla/5.0 Chrome/126.0.1 Safari/537.36', platform: 'Linux x86_64' },
chrome: { runtime: {
@@ -423,3 +425,111 @@ for (const [label, createController] of [['chrome', null], ['firefox', createFxC
assert.equal([...ids][0], store.webbrainCloudBridgeInstallationId, 'and it matches the persisted one');
});
}
+
+// ---- 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 };
+
+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 });
+ 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);
+ 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');
+ });
+}
diff --git a/test/run.js b/test/run.js
index 62cf7d479..e9937475b 100644
--- a/test/run.js
+++ b/test/run.js
@@ -66766,6 +66766,13 @@ test('MCP bridge settings are Chromium-only, live under Bridge, and keep setup g
assert.match(bridgePanel, />MCP</, 'Bridge pill labels should use plain destination names');
assert.match(bridgePanel, /data-i18n-title="st\.cb\.preset_mcp_hint"/, 'Bridge pills should explain their destination on hover');
assert.match(bridgePanel, /id="cb-approval-details"/, 'Bridge approval fields should hide behind progressive disclosure');
+ assert.match(bridgePanel, /type="password" id="cb-pairing-key"/, 'Bridge tab should expose a masked pairing key for the MCP / LM Studio bridges');
+ assert.ok(bridgePanel.indexOf('id="cb-pairing-key"') < bridgePanel.indexOf('id="cb-approval-details"'), 'the required pairing key should not hide behind the optional approval disclosure');
+ assert.match(firefoxHtml, /type="password" id="cb-pairing-key"/, 'Firefox Bridge tab should expose the pairing key');
+ for (const source of [chromeBridgeSettings, firefoxBridgeSettings]) {
+ assert.match(source, /pairingKey: 'webbrainCloudBridgePairingKey'/, 'Bridge tab should own the pairing key storage key');
+ assert.match(source, /\[KEYS\.pairingKey\]: pairingKeyInput\.value\.trim\(\)/, 'saving Settings should store the pasted pairing key');
+ }
assert.match(bridgePanel, /id="toggle-webmcp"/, 'Bridge tab should expose the WebMCP toggle');
assert.match(bridgePanel, /id="toggle-webmcp"\s+checked/, 'WebMCP must default on in Bridge tab');
assert.match(bridgePanel, /id="cb-status"[^>]*role="status"[^>]*aria-live="polite"/, 'bridge status should be announced accessibly');
diff --git a/web/docs/lm-studio/index.html b/web/docs/lm-studio/index.html
index 5c7af9591..f373022cf 100644
--- a/web/docs/lm-studio/index.html
+++ b/web/docs/lm-studio/index.html
@@ -43,7 +43,7 @@ lms dev --install</code></pre><p>See LM Studio’s current <a href="https://lmst
<section class="doc-section" id="public-web"><h2>Use public HTTP tools without a browser</h2><h3>Read a known article</h3><blockquote>Use research_url to read https://example.com/article and give me the author’s main claim, supporting evidence, and stated limitations.</blockquote><h3>Inspect an API response</h3><blockquote>Use fetch_url to read https://api.example.com/status. Return the HTTP status and the fields that indicate service health.</blockquote><p><code>research_url</code> is usually the better choice for prose. Use <code>fetch_url</code> when the exact response type, JSON structure, headers, method, or body matters.</p><div class="callout warning"><strong class="callout-title">A URL fetch is not a browser tab</strong><p>These requests are anonymous and do not execute page JavaScript. If a result reports <code>spaSuspected: true</code>, or the page requires login, stop retrying the HTTP route and use <code>browser_task</code> after connecting the extension.</p></div></section>
- <section class="doc-section" id="browser"><div class="eyebrow">Optional signed-in route</div><h2>Connect the browser you already use</h2><ol class="step-list"><li><strong>Install WebBrain in a Chromium browser.</strong> The bridge works in Chrome, Edge, Brave, Opera, and Vivaldi. Firefox cannot host this connection.</li><li><strong>Enable webbrain/web-tools in LM Studio.</strong> The plugin opens its loopback listener when it initializes.</li><li><strong>Open WebBrain Settings.</strong> Go to <strong>Settings → Bridge</strong>.</li><li><strong>Set the plugin URL.</strong> Enter <code>ws://127.0.0.1:17375/extension</code>, then enable MCP.</li><li><strong>Verify the complete path.</strong> Ask the LM Studio model to call <code>browser_status</code>. A connected result proves the plugin listener and extension handshake are present.</li></ol><div class="callout"><strong class="callout-title">One bridge destination at a time</strong><p>The extension has one outbound bridge socket. Port <code>17375</code> connects it to this plugin, port <code>17374</code> connects it to the MCP server, and port <code>17373</code> connects it to WebBrain Cloud. Changing the URL switches the destination; it does not combine them.</p></div><div class="callout tip"><strong class="callout-title">Two models may be involved</strong><p>The LM Studio chat model decides to call <code>browser_task</code> and receives the result. The WebBrain extension performs the delegated browser run with the active provider configured in WebBrain. If page content must stay on-device, configure that WebBrain provider to use a local model too.</p></div><h3>Read without changing the page</h3><blockquote>Use browser_task in Ask mode to read the account dashboard already open in my browser and list the five most recent alerts. Do not change anything.</blockquote><h3>Interact through the permission gate</h3><blockquote>Use browser_task in Act mode to open the draft already visible in my browser and change its title to Quarterly review. Stop before publishing.</blockquote></section>
+ <section class="doc-section" id="browser"><div class="eyebrow">Optional signed-in route</div><h2>Connect the browser you already use</h2><ol class="step-list"><li><strong>Install WebBrain in a Chromium browser.</strong> The bridge works in Chrome, Edge, Brave, Opera, and Vivaldi. Firefox cannot host this connection.</li><li><strong>Enable webbrain/web-tools in LM Studio.</strong> The plugin opens its loopback listener when it initializes.</li><li><strong>Open WebBrain Settings.</strong> Go to <strong>Settings → Bridge</strong>.</li><li><strong>Set the plugin URL and pairing key.</strong> Enter <code>ws://127.0.0.1:17375/extension</code>, paste the key from <code>~/.webbrain/bridge-key</code> (created when the plugin starts; the MCP server uses the same key) into <strong>Pairing key</strong>, then enable MCP.</li><li><strong>Verify the complete path.</strong> Ask the LM Studio model to call <code>browser_status</code>. A connected result proves the plugin listener and extension handshake are present.</li></ol><div class="callout"><strong class="callout-title">One bridge destination at a time</strong><p>The extension has one outbound bridge socket. Port <code>17375</code> connects it to this plugin, port <code>17374</code> connects it to the MCP server, and port <code>17373</code> connects it to WebBrain Cloud. Changing the URL switches the destination; it does not combine them.</p></div><div class="callout tip"><strong class="callout-title">Two models may be involved</strong><p>The LM Studio chat model decides to call <code>browser_task</code> and receives the result. The WebBrain extension performs the delegated browser run with the active provider configured in WebBrain. If page content must stay on-device, configure that WebBrain provider to use a local model too.</p></div><h3>Read without changing the page</h3><blockquote>Use browser_task in Ask mode to read the account dashboard already open in my browser and list the five most recent alerts. Do not change anything.</blockquote><h3>Interact through the permission gate</h3><blockquote>Use browser_task in Act mode to open the draft already visible in my browser and change its title to Quarterly review. Stop before publishing.</blockquote></section>
<section class="doc-section" id="lifecycle"><h2>Let continuing browser runs continue</h2><p><code>browser_task</code> waits for a result, but its timeout does not cancel work already running in the extension. Keep the returned <code>runId</code> and use the recovery tool that matches the state.</p><div class="status-strip" aria-label="LM Studio browser task statuses"><div class="status-item"><code>running</code><span>Poll with browser_status</span></div><div class="status-item waiting"><code>needs_user_input</code><span>Ask, then browser_respond</span></div><div class="status-item done"><code>completed</code><span>Result is ready</span></div><div class="status-item"><code>failed</code><span>Read the error and evidence</span></div><div class="status-item"><code>aborted</code><span>Stopped; earlier actions remain</span></div></div><ul><li>Do not start a duplicate <code>browser_task</code> after a timeout; poll the existing run.</li><li>Never invent an answer to a WebBrain clarification. Ask the human and forward their response verbatim.</li><li><code>browser_abort</code> stops future steps. It cannot undo a submitted form, sent message, or other completed action.</li></ul></section>
diff --git a/web/docs/mcp/index.html b/web/docs/mcp/index.html
index aeb0f3cf3..1f38a170a 100644
--- a/web/docs/mcp/index.html
+++ b/web/docs/mcp/index.html
@@ -72,7 +72,7 @@ hermes mcp test webbrain</code></pre><p>Keep <code>--args</code> last: current H
--timeout 360
openclaw mcp doctor webbrain --probe</code></pre><p><code>mcp add</code> probes the stdio server before saving it; <code>doctor --probe</code> performs a fresh launch and tool-discovery check. <code>status --verbose</code> only inspects the saved definition. Normal <code>coding</code> and <code>messaging</code> profiles include configured MCP servers; <code>minimal</code>, an explicit <code>bundle-mcp</code> deny, or a sandbox policy can hide them. See the current <a href="https://docs.openclaw.ai/cli/mcp">OpenClaw MCP guide</a>.</p><p>Whenever OpenClaw invokes WebBrain, the OpenClaw runtime, Chromium, WebBrain extension, and WebBrain provider must all be running on this computer.</p><p><strong>Example:</strong> “Use WebBrain to read the operations dashboard already open in Chromium and post a read-only summary of today’s warnings in this conversation.”</p><h3>Any other local stdio client</h3><p>Configure the executable as <code>npx</code> and the argument array as <code>["-y", "@webbrain/mcp-server"]</code>. The client must own the child process, preserve stdout for MCP messages, and run on the same computer as the browser.</p><h3>Run it manually</h3><p>Manual launch is useful for diagnosing the listener, but not required during normal MCP use:</p><pre class="code-block"><code>npx -y @webbrain/mcp-server</code></pre><p>Leave that terminal open. Closing it closes the bridge listener. From a source checkout, run <code>npm install</code>, <code>npm run build</code>, then <code>npm start</code> inside <code>mcp-server/</code>.</p></section>
- <section class="doc-section" id="browser"><div class="eyebrow">Step 2</div><h2>Point WebBrain at the local listener</h2><ol class="step-list"><li><strong>Start or restart your MCP client.</strong> Its WebBrain server must be running before the extension can connect.</li><li><strong>Open WebBrain Settings.</strong> Go to <strong>Settings → Bridge</strong>.</li><li><strong>Set the exact URL.</strong> Enter <code>ws://127.0.0.1:17374/extension</code>.</li><li><strong>Enable MCP.</strong> The status should move from connecting to connected.</li><li><strong>Verify end to end.</strong> Ask the MCP client to call <code>webbrain_connection</code>. “Connected” proves the client, local server, WebSocket listener, and extension handshake are all present.</li></ol><div class="callout"><strong class="callout-title">One bridge destination at a time</strong><p>The extension holds one outbound bridge socket: WebBrain Cloud on <code>17373</code>, this MCP server on <code>17374</code>, or the LM Studio plugin on <code>17375</code>. Changing the URL switches the destination; it does not multiplex them.</p></div></section>
+ <section class="doc-section" id="browser"><div class="eyebrow">Step 2</div><h2>Point WebBrain at the local listener</h2><ol class="step-list"><li><strong>Start or restart your MCP client.</strong> Its WebBrain server must be running before the extension can connect.</li><li><strong>Open WebBrain Settings.</strong> Go to <strong>Settings → Bridge</strong>.</li><li><strong>Set the exact URL.</strong> Enter <code>ws://127.0.0.1:17374/extension</code>.</li><li><strong>Paste the pairing key.</strong> Run <code>npx -y @webbrain/mcp-server pairing-key</code> in a terminal (or open <code>~/.webbrain/bridge-key</code>) and paste the key into <strong>Pairing key</strong>. The server only trusts a browser that proves it holds this key. Update WebBrain first if the field is missing.</li><li><strong>Enable MCP.</strong> The status should move from connecting to connected.</li><li><strong>Verify end to end.</strong> Ask the MCP client to call <code>webbrain_connection</code>. “Connected” proves the client, local server, WebSocket listener, and extension handshake are all present.</li></ol><div class="callout"><strong class="callout-title">One bridge destination at a time</strong><p>The extension holds one outbound bridge socket: WebBrain Cloud on <code>17373</code>, this MCP server on <code>17374</code>, or the LM Studio plugin on <code>17375</code>. Changing the URL switches the destination; it does not multiplex them.</p></div></section>
<section class="doc-section" id="first-task"><div class="eyebrow">Step 3 · just ask</div><h2>Describe the browser job in natural language</h2><p>In Codex, Claude Code, Hermes Agent, OpenClaw, Cursor, or OpenCode, write the request the same way you would give it to a teammate. Naming WebBrain makes your intent unambiguous; include the open page, desired outcome, scope, output shape, and whether changes are allowed.</p><h3>Read something without changing the page</h3><blockquote>Use WebBrain to read the Stripe dashboard already open in my browser. List failed payments from the last seven days with customer, amount, currency, date, and failure reason. Do not change anything.</blockquote><h3>Combine browser evidence with a codebase</h3><blockquote>Use WebBrain in Ask mode to inspect the staging error already open in Chromium. Then inspect this repository, connect the visible error to the most likely implementation, and propose a fix. Do not change the browser page.</blockquote><h3>Return predictable JSON</h3><blockquote>Use WebBrain to extract every overdue invoice from the dashboard already open in my browser. Return JSON with customer, amount, currency, due date, and invoice URL. Do not change anything.</blockquote><h3>Report back through a personal agent</h3><blockquote>Use WebBrain to read the support dashboard already open on this computer and summarize urgent unresolved tickets in this conversation. Keep the run read-only.</blockquote><h3>Interact with the page</h3><blockquote>Use WebBrain in Act mode to open the customer record already visible in my browser and update the company name to Acme Europe. Stop before any final submit or confirmation.</blockquote><p>The agent chooses <code>webbrain_run</code> for general reading or interaction and <code>webbrain_extract</code> when you request structured data. It supplies the arguments, monitors the run, and presents WebBrain’s result back in the conversation. Ask mode can read and extract; it cannot click, type, navigate, or submit. Act mode can interact, subject to WebBrain’s normal browser-side permissions.</p><div class="callout"><strong class="callout-title">Under the hood — you do not enter this</strong><p>For the first prompt above, the client will make a call similar to the following. This representation is useful when building or debugging an MCP client, but ordinary users can ignore it.</p></div><pre class="code-block"><code>webbrain_run(
task: "read the open Stripe dashboard and list failed payments from the last 7 days with customer, amount, currency, date, and failure reason",
@@ -118,7 +118,7 @@ webbrain_status(run_id: "mcp_…")</code></pre><p>A WebBrain run timeout returns
<section class="doc-section" id="modes"><h2>Choose the smallest authority</h2><div class="table-wrap"><table><thead><tr><th>Choice</th><th>What it allows</th><th>Use when</th></tr></thead><tbody><tr><td><code>mode: "ask"</code></td><td>Reading, summarizing, comparing, and extracting. No page interaction.</td><td>You only need information. This is the default.</td></tr><tr><td><code>mode: "act"</code></td><td>Navigation, clicking, typing, downloading, and form interaction through WebBrain’s permission gate.</td><td>The outcome requires visible browser actions.</td></tr><tr><td><code>allow_api_mutations: true</code></td><td>Allows an Act run to use mutating HTTP requests when the UI path is unsuitable.</td><td>Rare, explicit exceptions. It is rejected in Ask mode and should stay off by default.</td></tr></tbody></table></div><p>MCP-client approval and WebBrain approval are separate layers. Your client may ask before it invokes <code>webbrain_run</code>; WebBrain may then ask before a consequential action on a particular origin. One approval does not replace the other.</p></section>
- <section class="doc-section" id="security"><h2>Security boundaries you should keep</h2><ul><li><strong>Keep the listener local.</strong> It binds to <code>127.0.0.1</code>. Do not forward port <code>17374</code>, publish it through a container bridge, or proxy it onto a network.</li><li><strong>Loopback is not authentication.</strong> The extension sends an identifying handshake but no shared secret. A process already running as your local user could attempt to impersonate the extension or server. Treat local code and MCP packages as trusted software.</li><li><strong>Use Ask first.</strong> Read-only work is easier to verify and has a smaller blast radius.</li><li><strong>Keep the browser visible for Act.</strong> You can stop the run in the side panel, and unexpected navigation or typing should be treated as a reason to stop.</li><li><strong>Remember the provider boundary.</strong> The MCP bridge stays local, but page content is sent to the model provider configured in WebBrain. Use a local model when the content must remain on-device.</li><li><strong>Do not mistake a timeout for a rollback.</strong> Aborting stops future steps; it cannot undo a sent email, submitted form, purchase, or other completed action.</li></ul><p>For the complete design, see the <a href="https://github.com/webbrain-one/webbrain/blob/main/docs/security-model.md">security model</a>, <a href="https://github.com/webbrain-one/webbrain/blob/main/docs/privacy-and-data-flow.md">privacy and data flow</a>, and <a href="/docs/safety/">modes, safety, and privacy guide</a>.</p></section>
+ <section class="doc-section" id="security"><h2>Security boundaries you should keep</h2><ul><li><strong>Keep the listener local.</strong> It binds to <code>127.0.0.1</code>. Do not forward port <code>17374</code>, publish it through a container bridge, or proxy it onto a network.</li><li><strong>Keep the pairing key private.</strong> Loopback alone is not authentication, so the server trusts a socket only after it answers a fresh challenge with an HMAC keyed by the pairing key; the key itself never crosses the socket. Anyone who can read <code>~/.webbrain/bridge-key</code> can pair, so do not paste the key into a chat. The extension does not authenticate the server, so still treat local code and MCP packages as trusted software.</li><li><strong>Use Ask first.</strong> Read-only work is easier to verify and has a smaller blast radius.</li><li><strong>Keep the browser visible for Act.</strong> You can stop the run in the side panel, and unexpected navigation or typing should be treated as a reason to stop.</li><li><strong>Remember the provider boundary.</strong> The MCP bridge stays local, but page content is sent to the model provider configured in WebBrain. Use a local model when the content must remain on-device.</li><li><strong>Do not mistake a timeout for a rollback.</strong> Aborting stops future steps; it cannot undo a sent email, submitted form, purchase, or other completed action.</li></ul><p>For the complete design, see the <a href="https://github.com/webbrain-one/webbrain/blob/main/docs/security-model.md">security model</a>, <a href="https://github.com/webbrain-one/webbrain/blob/main/docs/privacy-and-data-flow.md">privacy and data flow</a>, and <a href="/docs/safety/">modes, safety, and privacy guide</a>.</p></section>
<section class="doc-section" id="troubleshooting"><h2>Troubleshooting by symptom</h2><div class="table-wrap"><table><thead><tr><th>Symptom</th><th>What it usually means</th><th>Fix</th></tr></thead><tbody><tr><td><strong>Connection error: WebSocket error</strong></td><td>No process is listening at the configured URL.</td><td>Start or restart the MCP client, confirm port <code>17374</code>, and leave the server process running.</td></tr><tr><td><code>webbrain_connection</code> says not connected</td><td>The local server exists, but the extension has not completed its handshake.</td><td>Use a Chromium browser, enable MCP, and set the exact <code>/extension</code> URL.</td></tr><tr><td><code>EADDRINUSE</code> or the server exits immediately</td><td>Another MCP client or manual server already owns port <code>17374</code>.</td><td>Stop the other process. Only one WebBrain MCP server can own the default port at a time.</td></tr><tr><td>The MCP tools do not appear</td><td>The client has not reloaded its configuration or the npm process failed to start.</td><td>Restart the client, inspect its MCP server list/log, and confirm Node 20+ plus npm access.</td></tr><tr><td>The tool returns <code>running</code></td><td>The server or client wait budget expired; the browser run was intentionally left alive.</td><td>Poll <code>webbrain_status</code> with the returned ID, or start future long tasks with <code>wait: false</code>.</td></tr><tr><td>The run says <code>needs_user_input</code></td><td>WebBrain needs a human decision before it can continue.</td><td>Relay the exact question, then call <code>webbrain_respond</code> with the matching IDs.</td></tr><tr><td>Firefox never connects</td><td>Firefox has no offscreen-document bridge runtime.</td><td>Use Chrome, Edge, Brave, Opera, or Vivaldi for MCP. Firefox remains supported for direct side-panel use.</td></tr><tr><td>WebBrain Cloud or LM Studio disconnected</td><td>The MCP URL replaced the extension’s single bridge destination.</td><td>Switch the MCP URL back to port <code>17373</code> or <code>17375</code> when you are finished.</td></tr></tbody></table></div><p>Check the listener directly:</p><pre class="code-block"><code>lsof -nP -iTCP:17374 -sTCP:LISTEN</code></pre><p>No output means nothing is listening. If a PID appears and you did not expect it, identify the process before stopping it.</p></section>
diff --git a/web/docs/zh/lm-studio/index.html b/web/docs/zh/lm-studio/index.html
index 634924b6d..3fcb10d68 100644
--- a/web/docs/zh/lm-studio/index.html
+++ b/web/docs/zh/lm-studio/index.html
@@ -44,7 +44,7 @@ lms dev --install</code></pre><p>参阅 LM Studio 的 <a href="https://lmstudio.
<section class="doc-section" id="public-web"><h2>无需浏览器即可使用公开 HTTP 工具</h2><h3>读取已知文章</h3><blockquote>使用 research_url 读取 https://example.com/article,给出作者的主要论点、支持证据和已说明的局限性。</blockquote><h3>检查 API 响应</h3><blockquote>使用 fetch_url 读取 https://api.example.com/status。返回 HTTP 状态和指示服务健康状况的字段。</blockquote><p><code>research_url</code> 通常更适合处理文章内容。当响应类型、JSON 结构、请求头、方法或请求体很重要时,使用 <code>fetch_url</code>。</p><div class="callout warning"><strong class="callout-title">URL 获取不等于浏览器标签页</strong><p>这些请求是匿名的,不会执行页面 JavaScript。如果结果报告 <code>spaSuspected: true</code>,或页面需要登录,请停止重试 HTTP 路线,在连接扩展后使用 <code>browser_task</code>。</p></div></section>
- <section class="doc-section" id="browser"><div class="eyebrow">可选的已登录路线</div><h2>连接你正在使用的浏览器</h2><ol class="step-list"><li><strong>在 Chromium 浏览器中安装 WebBrain。</strong>桥接适用于 Chrome、Edge、Brave、Opera 和 Vivaldi。Firefox 无法承载此连接。</li><li><strong>在 LM Studio 中启用 webbrain/web-tools。</strong>插件在初始化时会打开其本地回环监听器。</li><li><strong>打开 WebBrain 设置。</strong>进入<strong>设置 → Bridge</strong>。</li><li><strong>设置插件 URL。</strong>输入 <code>ws://127.0.0.1:17375/extension</code>,然后启用云桥接。</li><li><strong>验证完整路径。</strong>要求 LM Studio 模型调用 <code>browser_status</code>。连接成功的结果证明插件监听器和扩展握手均已就绪。</li></ol><div class="callout"><strong class="callout-title">同一时间只能连接一个桥接目标</strong><p>扩展只有一个出站桥接套接字。端口 <code>17375</code> 将其连接到此插件,端口 <code>17374</code> 连接到 MCP 服务器,端口 <code>17373</code> 连接到 WebBrain Cloud。更改 URL 会切换目标,而不会合并它们。</p></div><div class="callout tip"><strong class="callout-title">可能涉及两个模型</strong><p>LM Studio 聊天模型决定调用 <code>browser_task</code> 并接收结果。WebBrain 扩展使用 WebBrain 内配置的活跃提供商执行委派的浏览器运行。如果页面内容必须保留在本地设备上,请将该 WebBrain 提供商也配置为使用本地模型。</p></div><h3>不改变页面的读取</h3><blockquote>使用 Ask 模式下的 browser_task 读取我浏览器中已打开的账户仪表盘,列出最近五条警报。不要更改任何内容。</blockquote><h3>通过权限闸门进行交互</h3><blockquote>使用 Act 模式下的 browser_task 打开我浏览器中已显示的草稿,将公司名称更新为 Acme Europe。在任何最终提交或确认之前停止。</blockquote></section>
+ <section class="doc-section" id="browser"><div class="eyebrow">可选的已登录路线</div><h2>连接你正在使用的浏览器</h2><ol class="step-list"><li><strong>在 Chromium 浏览器中安装 WebBrain。</strong>桥接适用于 Chrome、Edge、Brave、Opera 和 Vivaldi。Firefox 无法承载此连接。</li><li><strong>在 LM Studio 中启用 webbrain/web-tools。</strong>插件在初始化时会打开其本地回环监听器。</li><li><strong>打开 WebBrain 设置。</strong>进入<strong>设置 → Bridge</strong>。</li><li><strong>设置插件 URL 和配对密钥。</strong>输入 <code>ws://127.0.0.1:17375/extension</code>,将 <code>~/.webbrain/bridge-key</code>(插件启动时创建,与 MCP 服务器共用)中的密钥粘贴到<strong>配对密钥</strong>字段,然后启用云桥接。</li><li><strong>验证完整路径。</strong>要求 LM Studio 模型调用 <code>browser_status</code>。连接成功的结果证明插件监听器和扩展握手均已就绪。</li></ol><div class="callout"><strong class="callout-title">同一时间只能连接一个桥接目标</strong><p>扩展只有一个出站桥接套接字。端口 <code>17375</code> 将其连接到此插件,端口 <code>17374</code> 连接到 MCP 服务器,端口 <code>17373</code> 连接到 WebBrain Cloud。更改 URL 会切换目标,而不会合并它们。</p></div><div class="callout tip"><strong class="callout-title">可能涉及两个模型</strong><p>LM Studio 聊天模型决定调用 <code>browser_task</code> 并接收结果。WebBrain 扩展使用 WebBrain 内配置的活跃提供商执行委派的浏览器运行。如果页面内容必须保留在本地设备上,请将该 WebBrain 提供商也配置为使用本地模型。</p></div><h3>不改变页面的读取</h3><blockquote>使用 Ask 模式下的 browser_task 读取我浏览器中已打开的账户仪表盘,列出最近五条警报。不要更改任何内容。</blockquote><h3>通过权限闸门进行交互</h3><blockquote>使用 Act 模式下的 browser_task 打开我浏览器中已显示的草稿,将公司名称更新为 Acme Europe。在任何最终提交或确认之前停止。</blockquote></section>
<section class="doc-section" id="lifecycle"><h2>让正在进行的浏览器运行继续</h2><p><code>browser_task</code> 会等待结果,但其超时不会取消扩展中已在运行的工作。保留返回的 <code>runId</code>,并使用与状态匹配的恢复工具。</p><div class="status-strip" aria-label="LM Studio 浏览器任务状态"><div class="status-item"><code>running</code><span>使用 browser_status 轮询</span></div><div class="status-item waiting"><code>needs_user_input</code><span>提问,然后使用 browser_respond</span></div><div class="status-item done"><code>completed</code><span>结果已就绪</span></div><div class="status-item"><code>failed</code><span>查看错误和证据</span></div><div class="status-item"><code>aborted</code><span>已停止;之前的操作仍然有效</span></div></div><ul><li>超时后不要启动重复的 <code>browser_task</code>;轮询现有运行。</li><li>永远不要为 WebBrain 的澄清问题编造答案。询问用户并逐字转发他们的回答。</li><li><code>browser_abort</code> 停止后续步骤。它无法撤销已提交的表单、已发送的消息或其他已完成的操作。</li></ul></section>
diff --git a/web/docs/zh/mcp/index.html b/web/docs/zh/mcp/index.html
index 5f2e2d7f7..1ab74f813 100644
--- a/web/docs/zh/mcp/index.html
+++ b/web/docs/zh/mcp/index.html
@@ -59,7 +59,7 @@ tool_timeout_sec = 360</code></pre><p>更改文件后重启应用或 IDE 扩展
--arg @webbrain/mcp-server \
--timeout 360</code></pre><p><code>mcp add</code> 会在保存前探测 stdio 服务器。运行 <code>openclaw mcp status --verbose</code> 检查已保存的定义。普通的 <code>coding</code> 和 <code>messaging</code> 工具配置文件包含已配置的 MCP 服务器;<code>minimal</code> 配置文件、显式 <code>bundle-mcp</code> 拒绝或沙箱工具策略可能会隐藏它们。参阅 <a href="https://docs.openclaw.ai/cli/mcp">OpenClaw MCP 指南</a> 了解当前注册表和策略详情。</p><h3>手动运行</h3><p>手动启动对于诊断监听器很有用,但在正常使用 MCP 时不需要:</p><pre class="code-block"><code>npx -y @webbrain/mcp-server</code></pre><p>保持该终端打开。关闭它会关闭桥接监听器。从源码检出时,在 <code>mcp-server/</code> 内运行 <code>npm install</code>、<code>npm run build</code>,然后 <code>npm start</code>。</p></section>
- <section class="doc-section" id="browser"><div class="eyebrow">步骤 2</div><h2>将 WebBrain 指向本地监听器</h2><ol class="step-list"><li><strong>启动或重启你的 MCP 客户端。</strong>其 WebBrain 服务器必须在扩展连接之前运行。</li><li><strong>打开 WebBrain 设置。</strong>进入<strong>设置 → Bridge</strong>。</li><li><strong>设置精确的 URL。</strong>输入 <code>ws://127.0.0.1:17374/extension</code>。</li><li><strong>启用云桥接。</strong>状态应从"正在连接"变为"已连接"。名称是历史原因:此目标是本地的。</li><li><strong>验证端到端连接。</strong>要求 MCP 客户端调用 <code>webbrain_connection</code>。"Connected" 证明客户端、本地服务器、WebSocket 监听器和扩展握手均已就绪。</li></ol><div class="callout"><strong class="callout-title">同一时间只能连接一个桥接目标</strong><p>扩展持有一个出站桥接套接字:WebBrain Cloud 在 <code>17373</code>、此 MCP 服务器在 <code>17374</code>,或 LM Studio 插件在 <code>17375</code>。更改 URL 会切换目标,而不会多路复用。</p></div></section>
+ <section class="doc-section" id="browser"><div class="eyebrow">步骤 2</div><h2>将 WebBrain 指向本地监听器</h2><ol class="step-list"><li><strong>启动或重启你的 MCP 客户端。</strong>其 WebBrain 服务器必须在扩展连接之前运行。</li><li><strong>打开 WebBrain 设置。</strong>进入<strong>设置 → Bridge</strong>。</li><li><strong>设置精确的 URL。</strong>输入 <code>ws://127.0.0.1:17374/extension</code>。</li><li><strong>粘贴配对密钥。</strong>在终端运行 <code>npx -y @webbrain/mcp-server pairing-key</code>(或打开 <code>~/.webbrain/bridge-key</code>),将密钥粘贴到<strong>配对密钥</strong>字段。服务器只信任能证明持有该密钥的浏览器。如果没有该字段,请先更新 WebBrain。</li><li><strong>启用云桥接。</strong>状态应从"正在连接"变为"已连接"。名称是历史原因:此目标是本地的。</li><li><strong>验证端到端连接。</strong>要求 MCP 客户端调用 <code>webbrain_connection</code>。"Connected" 证明客户端、本地服务器、WebSocket 监听器和扩展握手均已就绪。</li></ol><div class="callout"><strong class="callout-title">同一时间只能连接一个桥接目标</strong><p>扩展持有一个出站桥接套接字:WebBrain Cloud 在 <code>17373</code>、此 MCP 服务器在 <code>17374</code>,或 LM Studio 插件在 <code>17375</code>。更改 URL 会切换目标,而不会多路复用。</p></div></section>
<section class="doc-section" id="first-task"><div class="eyebrow">步骤 3 · 直接提问</div><h2>用自然语言描述浏览器任务</h2><p>在 Codex、Claude Code、Cursor、OpenClaw 或 OpenCode 中,像给同事布置任务一样写出请求。提及 WebBrain 使你的意图明确无误;包括页面、期望结果、范围,以及是否允许更改。</p><h3>不改变页面的读取</h3><blockquote>使用 WebBrain 读取我浏览器中已打开的 Stripe 仪表盘。列出过去七天的失败支付,包含客户、金额、货币、日期和失败原因。不要更改任何内容。</blockquote><h3>返回可预测的 JSON</h3><blockquote>使用 WebBrain 从我浏览器中已打开的仪表盘提取所有逾期发票。返回包含客户、金额、货币、到期日和发票 URL 的 JSON。不要更改任何内容。</blockquote><h3>与页面交互</h3><blockquote>使用 WebBrain 的 Act 模式打开我浏览器中已显示的客户记录,将公司名称更新为 Acme Europe。在任何最终提交或确认之前停止。</blockquote><p>编程代理会选择 <code>webbrain_run</code> 进行一般读取或交互,当请求结构化数据时选择 <code>webbrain_extract</code>。它提供参数、监控运行,并将 WebBrain 的结果呈现回对话中。Ask 模式可以读取和提取;不能点击、输入、导航或提交。Act 模式可以交互,受 WebBrain 正常的浏览器端权限约束。</p><div class="callout"><strong class="callout-title">底层细节——你不需要输入这些</strong><p>对于上面的第一个提示,客户端会进行类似以下的调用。此表示在构建或调试 MCP 客户端时有用,普通用户可以忽略。</p></div><pre class="code-block"><code>webbrain_run(
task: "read the open Stripe dashboard and list failed payments from the last 7 days with customer, amount, currency, date, and failure reason",
@@ -105,7 +105,7 @@ webbrain_status(run_id: "mcp_…")</code></pre><p>WebBrain 运行超时会将控
<section class="doc-section" id="modes"><h2>选择最小权限</h2><div class="table-wrap"><table><thead><tr><th>选择</th><th>允许的操作</th><th>使用场景</th></tr></thead><tbody><tr><td><code>mode: "ask"</code></td><td>读取、总结、比较和提取。无页面交互。</td><td>你只需要信息。这是默认选项。</td></tr><tr><td><code>mode: "act"</code></td><td>通过 WebBrain 的权限闸门进行导航、点击、输入、下载和表单交互。</td><td>结果需要可见的浏览器操作。</td></tr><tr><td><code>allow_api_mutations: true</code></td><td>允许 Act 运行在 UI 路径不合适时使用修改型 HTTP 请求。</td><td>罕见的显式例外。在 Ask 模式下被拒绝,默认应保持关闭。</td></tr></tbody></table></div><p>MCP 客户端审批和 WebBrain 审批是独立的层级。你的客户端可能在调用 <code>webbrain_run</code> 之前询问;WebBrain 可能在某个来源上的重要操作之前询问。一个审批不会替代另一个。</p></section>
- <section class="doc-section" id="security"><h2>你应该保持的安全边界</h2><ul><li><strong>保持监听器本地化。</strong>它绑定到 <code>127.0.0.1</code>。不要转发端口 <code>17374</code>、通过容器桥接发布,或代理到网络上。</li><li><strong>本地回环不是认证。</strong>扩展发送识别握手但没有共享密钥。以你本地用户身份运行的进程可能尝试冒充扩展或服务器。将本地代码和 MCP 包视为可信软件。</li><li><strong>先使用 Ask。</strong>只读工作更容易验证,爆炸半径更小。</li><li><strong>Act 模式保持浏览器可见。</strong>你可以在侧边栏中停止运行,意外的导航或输入应被视为停止的理由。</li><li><strong>记住提供商边界。</strong>MCP 桥接保持本地,但页面内容会发送到 WebBrain 中配置的模型提供商。当内容必须保留在本地设备上时,请使用本地模型。</li><li><strong>不要将超时误解为回滚。</strong>中止会停止后续步骤;它无法撤销已发送的邮件、已提交的表单、购买或其他已完成的操作。</li></ul><p>完整设计请参阅 <a href="https://github.com/webbrain-one/webbrain/blob/main/docs/security-model.md">安全模型</a>、<a href="https://github.com/webbrain-one/webbrain/blob/main/docs/privacy-and-data-flow.md">隐私与数据流</a>,以及 <a href="/docs/zh/safety/">模式、安全与隐私指南</a>。</p></section>
+ <section class="doc-section" id="security"><h2>你应该保持的安全边界</h2><ul><li><strong>保持监听器本地化。</strong>它绑定到 <code>127.0.0.1</code>。不要转发端口 <code>17374</code>、通过容器桥接发布,或代理到网络上。</li><li><strong>妥善保管配对密钥。</strong>本地回环本身不是认证,因此服务器只有在套接字用以配对密钥为键的 HMAC 回答一次性质询后才信任它;密钥本身从不通过套接字发送。任何能读取 <code>~/.webbrain/bridge-key</code> 的人都能配对,所以不要把密钥粘贴到聊天中。扩展不验证服务器的身份,因此仍应将本地代码和 MCP 包视为可信软件。</li><li><strong>先使用 Ask。</strong>只读工作更容易验证,爆炸半径更小。</li><li><strong>Act 模式保持浏览器可见。</strong>你可以在侧边栏中停止运行,意外的导航或输入应被视为停止的理由。</li><li><strong>记住提供商边界。</strong>MCP 桥接保持本地,但页面内容会发送到 WebBrain 中配置的模型提供商。当内容必须保留在本地设备上时,请使用本地模型。</li><li><strong>不要将超时误解为回滚。</strong>中止会停止后续步骤;它无法撤销已发送的邮件、已提交的表单、购买或其他已完成的操作。</li></ul><p>完整设计请参阅 <a href="https://github.com/webbrain-one/webbrain/blob/main/docs/security-model.md">安全模型</a>、<a href="https://github.com/webbrain-one/webbrain/blob/main/docs/privacy-and-data-flow.md">隐私与数据流</a>,以及 <a href="/docs/zh/safety/">模式、安全与隐私指南</a>。</p></section>
<section class="doc-section" id="troubleshooting"><h2>按症状排查</h2><div class="table-wrap"><table><thead><tr><th>症状</th><th>通常含义</th><th>解决方法</th></tr></thead><tbody><tr><td><strong>连接错误:WebSocket 错误</strong></td><td>配置的 URL 上没有进程在监听。</td><td>启动或重启 MCP 客户端,确认端口 <code>17374</code>,并保持服务器进程运行。</td></tr><tr><td><code>webbrain_connection</code> 报告未连接</td><td>本地服务器存在,但扩展未完成握手。</td><td>使用 Chromium 浏览器,启用云桥接,并设置精确的 <code>/extension</code> URL。</td></tr><tr><td><code>EADDRINUSE</code> 或服务器立即退出</td><td>另一个 MCP 客户端或手动服务器已占用端口 <code>17374</code>。</td><td>停止其他进程。同一时间只有一个 WebBrain MCP 服务器可以占用默认端口。</td></tr><tr><td>MCP 工具没有出现</td><td>客户端未重新加载配置或 npm 进程启动失败。</td><td>重启客户端,检查其 MCP 服务器列表/日志,确认 Node 20+ 和 npm 访问权限。</td></tr><tr><td>工具返回 <code>running</code></td><td>服务器或客户端等待预算已用尽;浏览器运行被故意保持存活。</td><td>使用返回的 ID 轮询 <code>webbrain_status</code>,或使用 <code>wait: false</code> 启动未来的长时间任务。</td></tr><tr><td>运行显示 <code>needs_user_input</code></td><td>WebBrain 需要人工决策才能继续。</td><td>中继确切的问题,然后使用匹配的 ID 调用 <code>webbrain_respond</code>。</td></tr><tr><td>Firefox 始终无法连接</td><td>Firefox 没有离屏文档桥接运行时。</td><td>使用 Chrome、Edge、Brave、Opera 或 Vivaldi 进行 MCP。Firefox 仍支持直接侧边栏使用。</td></tr><tr><td>WebBrain Cloud 或 LM Studio 已断开连接</td><td>MCP URL 替换了扩展的单个桥接目标。</td><td>完成后将设置切换回端口 <code>17373</code>(Cloud)或 <code>17375</code>(LM Studio)。</td></tr></tbody></table></div></section>