Skip to content

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

Authenticate the bridge controller before sending any credential

Barack Sokullu07c62cac5828
diff --git a/docs/cloud-bridge-browser-approval.md b/docs/cloud-bridge-browser-approval.md
index 472437280..6b27cd846 100644
--- a/docs/cloud-bridge-browser-approval.md
+++ b/docs/cloud-bridge-browser-approval.md
@@ -2,10 +2,12 @@
A backend can require explicit approval of a WebBrain installation before it is allowed to run `cloud_*` commands. The feature is opt-in: **without a Cloud Bridge token the bridge behaves exactly as before** (local MCP server, no approval step).
+With a token, the backend and the browser first authenticate each other with a challenge-response over the token. The token itself never crosses the socket, so a program that takes the loopback port before the real backend learns nothing it can reuse and cannot get the browser to run commands.
+
## Architecture
```
-background (cloud-runs.js) --cloud-bridge-start {url, token, browserId, installationId, extensionVersion}--> offscreen (cloud-bridge.js) <== WebSocket ==> backend
+background (cloud-runs.js) --cloud-bridge-start {url, token, browserId, installationId, extensionVersion, legacyBearerAuth}--> offscreen (cloud-bridge.js) <== WebSocket ==> backend
```
```mermaid
@@ -24,7 +26,7 @@ flowchart LR
BG --> AG --> TAB
end
subgraph Backend["Backend (today: local ws:// only)"]
- SRV["WebSocket server<br/>checks token<br/>approves / rejects"]
+ SRV["WebSocket server<br/>proves the token, checks the browser's proof<br/>approves / rejects"]
end
OFF <== "WebSocket opened by the extension" ==> SRV
```
@@ -34,7 +36,7 @@ The French guide ([cloud-bridge-test-guide.fr.md](cloud-bridge-test-guide.fr.md)
**Chrome vs Firefox.** Chrome (MV3) hosts the socket in an offscreen document (`src/chrome/src/offscreen/cloud-bridge.js`). Firefox (MV2) has no offscreen documents, so `src/firefox/src/cloud-bridge.js` is a module that runs in the persistent background page and hands commands directly to `handleMessage`. The protocol, storage keys, approval rules and Settings tab are identical; `src/firefox/src/cloud-runs.js` mirrors the Chrome controller and receives the bridge as an injected dependency.
- `cloud-runs.js` reads the persistent identity from `chrome.storage.local` and passes it to the offscreen page with the existing `cloud-bridge-start` message (the offscreen page has no storage access).
-- `offscreen/cloud-bridge.js` sends the enriched `hello` and tracks the approval state **per socket**.
+- `offscreen/cloud-bridge.js` sends the enriched `hello`, runs the challenge-response and tracks the authentication and approval state **per socket**.
- Command routing (`cloud_run`, `cloud_status`, `cloud_respond`, `cloud_abort`, workflows, scheduled jobs) and payloads are unchanged.
## Local configuration
@@ -48,28 +50,27 @@ Keys in `chrome.storage.local` (the existing mechanism; the URL and enable toggl
| `webbrainCloudBridgeToken` | Cloud Bridge credential. Distinct from provider API keys. Setting it turns approval on. |
| `webbrainCloudBridgeBrowserId` | Backend-visible name; defaults to the installation id |
| `webbrainCloudBridgeInstallationId` | Generated once (`crypto.randomUUID()`) |
+| `webbrainCloudBridgeLegacyBearerAuth` | Deprecated. Only the boolean `true` turns it on; see [Legacy bearer hello](#legacy-bearer-hello-deprecated). Not shown in Settings. |
-All of these are editable in **Settings → Bridge**: enable toggle, backend URL, token, browser name (`browserId`), the read-only installation ID, and a **Save & test connection** button. The test saves the form, (re)starts the bridge and reports one of: backend unreachable, connected (no approval needed), waiting for approval, approved, or rejected (with the reason).
+All of these except the legacy flag are editable in **Settings → Bridge**: enable toggle, backend URL, token, browser name (`browserId`), the read-only installation ID, and a **Save & test connection** button. The test saves the form, (re)starts the bridge and reports one of: backend unreachable, connected (no approval needed), waiting for approval, approved, or rejected (with the reason).
To try it end to end: run `node examples/cloud-bridge-approval-server.mjs --token dev-token`, enter `dev-token` in the tab, press **Save & test connection** (status: waiting for approval), then type `approve` in the server terminal (status: approved) or `reject`.
The older Display → MCP block controls the same enable/URL keys; it is not refreshed live when the new tab changes them (reload Settings).
-Changing the token or browserId reconnects the socket.
+Changing the token, browserId or legacy flag reconnects the socket.
## Messages
-Extension → backend, on every socket open:
+### 1. Extension → backend: `hello` (every socket open)
```json
{
"type": "hello",
"client": "webbrain-extension",
"protocolVersion": 2,
- "capabilities": ["saved_workflows_v1", "run_modes_v1", "scheduled_jobs_v1", "run_provider_v1", "private_results_v1", "bot_memory_v1"],
- "auth": { "type": "bearer", "token": "dev-token" },
- "browserId": "my-laptop",
- "installationId": "0b0c6a3e-…",
+ "capabilities": ["saved_workflows_v1", "run_modes_v1", "scheduled_jobs_v1", "run_provider_v1", "private_results_v1", "bot_memory_v1", "run_handoff_v1"],
+ "auth": { "type": "challenge", "method": "hmac-sha256-v1", "nonce": "<64 lowercase hex chars>" },
"browser": { "name": "Chrome", "version": "126.0.0.0" },
"extensionVersion": "40.2.1",
"platform": "Linux x86_64",
@@ -77,9 +78,33 @@ Extension → backend, on every socket open:
}
```
-`auth`, `browserId` and `installationId` are only sent when a token is configured. The token is never included in `status`.
+`auth` is only sent when a token is configured. `nonce` is 32 fresh random bytes per socket. The hello carries neither the token nor `browserId` / `installationId` (they are also removed from its `status`); those come in step 3, after the backend has proved itself. Without a token the hello is unchanged from earlier versions (no `auth`; `status` keeps both IDs).
-Backend → extension:
+### 2. Backend → extension: `auth_challenge`
+
+```json
+{ "type": "auth_challenge", "method": "hmac-sha256-v1", "nonce": "<64 lowercase hex chars>", "proof": "<64 lowercase hex chars>" }
+```
+
+`nonce` is the backend's own 32 random bytes. `proof` is
+
+```
+hex(HMAC-SHA256(key = UTF-8(token), message = UTF-8(JSON.stringify(["webbrain-bridge-auth-v1", "controller", helloNonce, backendNonce]))))
+```
+
+`JSON.stringify` of a string array has no whitespace, for example `["webbrain-bridge-auth-v1","controller","ab…","cd…"]`. The extension answers only the first `auth_challenge` of a socket. If the method, either nonce or the proof is wrong it sends nothing back, closes the socket, reports `Bridge controller failed authentication` and reconnects with the usual backoff (the real backend may get its port back). It is not a rejection.
+
+### 3. Extension → backend: `auth_response`
+
+```json
+{ "type": "auth_response", "method": "hmac-sha256-v1", "proof": "<64 lowercase hex chars>", "browserId": "my-laptop", "installationId": "0b0c6a3e-…" }
+```
+
+`proof` is the same HMAC over `["webbrain-bridge-auth-v1", "extension", helloNonce, backendNonce, browserId, installationId]`. The backend recomputes it with its token (compare in constant time) and rejects the browser if it does not match. The role label stops either side from replaying the other's proof, and the nonces stop a recorded proof from working on another socket.
+
+Test vector: token `secret-token`, hello nonce `00` × 32, backend nonce `11` × 32, `browserId` `browser-1`, `installationId` `install-1` give the backend proof `04734662625940a90c0e3aeed5a653b6fb2e24779baa71b6dccab394601937d4` and the extension proof `5670c5e30c40e94ed27cd0e99148310d44a3efe54d668b2f9fd21efe9a8e913e`.
+
+### 4. Backend → extension: approval
```json
{ "type": "connection_pending", "browserId": "my-laptop" }
@@ -87,6 +112,8 @@ Backend → extension:
{ "type": "connection_rejected", "browserId": "my-laptop", "reason": "Rejected by user" }
```
+- With a token, `connection_pending` and `connection_approved` are ignored until the backend's `auth_challenge` has been verified. Send them after a valid `auth_response`.
+- `connection_rejected` is honoured at any point, since it only takes rights away.
- `browserId` is optional; if present and different from the local one, the message is ignored.
- `connection_rejected` closes the socket and **stops auto-reconnect** until the settings change or the bridge is restarted.
@@ -111,7 +138,28 @@ contract, credential handling, and image-upgrade checks.
## Reconnection
-Approval belongs to one WebSocket. Every new socket (reconnect, URL/identity change) starts `pending`, resends `hello`, and must be approved again.
+Authentication and approval belong to one WebSocket. Every new socket (reconnect, URL/identity change) starts `pending`, resends `hello` with a new nonce, and must pass the challenge and be approved again. With a token, the reconnect backoff is only reset once the backend has proved itself, so a program that keeps failing the challenge is retried at most every 30 seconds.
+
+## Legacy bearer hello (deprecated)
+
+Before the challenge-response, a token-configured hello carried `"auth": { "type": "bearer", "token": "…" }` plus `browserId` and `installationId`, and the extension accepted `connection_approved` from whoever answered. A backend that has not implemented steps 2 and 3 yet sees a hello without a token and should refuse it.
+
+To keep such a backend working during the transition, set the flag by hand in the extension's console (service worker console on Chrome, background page console on Firefox):
+
+```js
+chrome.storage.local.set({ webbrainCloudBridgeLegacyBearerAuth: true }) // Firefox: browser.storage.local
+```
+
+With the flag the extension sends the old bearer hello and accepts unauthenticated approval messages, exactly as before. It hands the token to whatever listens on the configured port, so use it only until the backend implements the challenge, then remove it with `chrome.storage.local.remove('webbrainCloudBridgeLegacyBearerAuth')`. The flag will be removed in a later release.
+
+## Implementing a backend
+
+1. On `hello` with `auth.type === "challenge"` and `auth.method === "hmac-sha256-v1"`, check that `auth.nonce` is 64 lowercase hex characters, generate 32 random bytes of your own, and send `auth_challenge` with your proof. Answer each socket's hello once.
+2. On `auth_response`, recompute the extension's proof from both nonces and the `browserId` / `installationId` in the message, compare in constant time, and reply `connection_rejected` (and close) on a mismatch.
+3. Only then treat the socket as the browser: send `connection_pending` / `connection_approved`, and route `cloud_*` commands to it.
+4. Optionally, during a transition, also accept the deprecated bearer hello (constant-time compare of `auth.token`) for extension builds that predate the challenge.
+
+The example server below is a complete reference.
## Local test server
@@ -120,9 +168,10 @@ Approval belongs to one WebSocket. Every new socket (reconnect, URL/identity cha
```bash
node examples/cloud-bridge-approval-server.mjs --token dev-token # manual approval
node examples/cloud-bridge-approval-server.mjs --token dev-token --auto-approve
+node examples/cloud-bridge-approval-server.mjs --token dev-token --legacy-bearer # also accept the deprecated bearer hello
```
-It replies `connection_pending` after a valid `hello` (or `connection_rejected` for a bad token). On stdin, type `approve`, `reject`, or `send {"id":"1","action":"cloud_status","payload":{"runId":"run_x"}}`.
+It runs the challenge-response and replies `connection_pending` after a valid `auth_response` (or `connection_rejected` for a bad proof or an unexpected hello). If its token differs from the browser's, the browser drops it first (`Bridge controller failed authentication`). On stdin, type `approve`, `reject`, or `send {"id":"1","action":"cloud_status","payload":{"runId":"run_x"}}`.
Automated tests (unit with a fake WebSocket + one end-to-end run against that server):
@@ -133,7 +182,8 @@ npm run test:cloud-bridge-approval
## Limits & security
- The bridge URL is still restricted to `ws://` on localhost/127.0.0.1/::1. A remote backend needs a local relay, or a deliberate relaxation (needs TLS and a decision upstream).
-- The token travels in the `hello` over that local socket; it is stored in plain `chrome.storage.local` like other settings.
-- The backend is responsible for validating the token and for the user-facing approval UI; the extension only enforces "no approval, no commands".
+- The token never travels over the socket (unless the deprecated legacy flag is set); it is stored in plain `chrome.storage.local` like other settings. Use a long random token: any program that can connect to the real backend can collect its proofs and try to guess a weak token offline.
+- The backend is responsible for verifying the browser's proof and for the user-facing approval UI; the extension enforces "no proof from the backend, no identity and no approval" and "no approval, no commands".
+- **Without a token there is no authentication.** Any program that listens on the configured port first, such as another user's process on a shared machine, can send `cloud_*` commands to the browser and read their results. This mode exists for the local MCP server, the LM Studio plugin and WebBrain Cloud, which do not use a token today; it is only active after the user (or the Cloud image) turns the bridge on.
- The extension still only accepts the `cloud_*` run actions; no cookies, tabs, history, provider keys or configuration are exposed.
- Approval is not persisted and not revocable from the extension side other than by disabling the bridge or rotating the token.
diff --git a/docs/cloud-bridge-test-guide.fr.md b/docs/cloud-bridge-test-guide.fr.md
index e9d2b2829..2f31537a0 100644
--- a/docs/cloud-bridge-test-guide.fr.md
+++ b/docs/cloud-bridge-test-guide.fr.md
@@ -22,7 +22,7 @@ flowchart LR
BG --> AG --> TAB
end
subgraph Backend["Backend (aujourd'hui : ws:// en local uniquement)"]
- SRV["Serveur WebSocket<br/>vérifie le token<br/>approuve / refuse"]
+ SRV["Serveur WebSocket<br/>prouve le token, vérifie la preuve du navigateur<br/>approuve / refuse"]
end
OFF <== "WebSocket initié par l'extension" ==> SRV
```
@@ -35,11 +35,17 @@ sequenceDiagram
participant B as Backend
participant U as Utilisateur
E->>B: connexion WebSocket
- E->>B: hello {auth.token, browserId, installationId, navigateur, version, plateforme, capabilities}
- alt token invalide
+ E->>B: hello {auth.nonce, navigateur, version, plateforme, capabilities}
+ B-->>E: auth_challenge {nonce serveur, preuve HMAC(token)}
+ alt preuve du serveur invalide
+ Note over E: rien n'est envoyé, socket fermée, nouvel essai avec délai croissant
+ else preuve du serveur valide
+ E->>B: auth_response {preuve HMAC(token), browserId, installationId}
+ end
+ alt preuve du navigateur invalide
B-->>E: connection_rejected
Note over E: socket fermée, pas de reconnexion auto
- else token valide
+ else preuve du navigateur valide
B-->>E: connection_pending
B->>E: cloud_run (avant approbation)
E-->>B: ok:false, connection_not_approved (403)
@@ -54,7 +60,7 @@ sequenceDiagram
B->>E: cloud_status {runId}
E-->>B: status completed + résultat
end
- Note over E,B: coupure réseau → nouvelle socket → nouveau hello → repart en pending
+ Note over E,B: coupure réseau → nouvelle socket → nouveau hello et nouveau challenge → repart en pending
```
## 1. Prérequis
@@ -102,7 +108,7 @@ node examples/cloud-bridge-approval-server.mjs --token dev-token
Vous devez voir : `Listening on ws://127.0.0.1:17374/extension`.
-Options : `--port 17374` (défaut), `--auto-approve` (approuve automatiquement, pratique pour tester les commandes).
+Options : `--port 17374` (défaut), `--auto-approve` (approuve automatiquement, pratique pour tester les commandes), `--legacy-bearer` (accepte aussi l'ancien `hello` qui contenait le token, voir le scénario G).
Ce terminal sert à la fois de **backend** (il affiche tout ce que l'extension envoie, préfixé par `<-`) et de **console d'approbation**.
@@ -118,16 +124,18 @@ Ce terminal sert à la fois de **backend** (il affiche tout ce que l'extension e
Le statut passe à : *Connected — waiting for the backend to approve this browser.*
-Dans le terminal du serveur, vous voyez le `hello` reçu, par exemple :
+Dans le terminal du serveur, vous voyez le `hello` reçu, puis la réponse au challenge, par exemple :
```json
{"type":"hello","client":"webbrain-extension","protocolVersion":2,
"capabilities":["saved_workflows_v1","run_modes_v1","scheduled_jobs_v1"],
- "auth":{"type":"bearer","token":"dev-token"},
- "browserId":"mon-chrome","installationId":"…",
+ "auth":{"type":"challenge","method":"hmac-sha256-v1","nonce":"…"},
"browser":{"name":"Chrome","version":"…"},"extensionVersion":"38.0.13","platform":"Linux", …}
+{"type":"auth_response","method":"hmac-sha256-v1","proof":"…","browserId":"mon-chrome","installationId":"…"}
```
+Le token n'apparaît jamais : le serveur prouve d'abord qu'il le connaît (`auth_challenge`), puis l'extension envoie sa propre preuve avec `browserId` et `installationId`.
+
## 5. Scénarios à tester
### A. Commande avant approbation (doit être refusée)
@@ -167,17 +175,21 @@ Dans le terminal : `reject`. Le statut devient *Rejected by the backend: …*, l
### D. Reconnexion
1. Arrêter le serveur (Ctrl+C) puis le relancer : l'extension se reconnecte automatiquement (délai croissant, jusqu'à 30 s).
-2. Elle renvoie un `hello`, et la connexion est de nouveau **en attente** : toute commande est refusée tant que vous n'avez pas retapé `approve`.
+2. Elle renvoie un `hello` avec un nouveau nonce, refait le challenge, et la connexion est de nouveau **en attente** : toute commande est refusée tant que vous n'avez pas retapé `approve`.
Note connue : juste après une reconnexion, le texte de statut de la page Settings peut rester sur « approved » alors que la connexion est repassée en attente ; les commandes sont bien refusées. Cliquer sur **Save & test connection** pour resynchroniser l'affichage.
### E. Mauvais token
-Mettre un autre token dans Settings puis **Save & test connection** : le serveur répond `connection_rejected` (« Invalid token »).
+Mettre un autre token dans Settings puis **Save & test connection** : la preuve du serveur ne correspond plus, l'extension ferme la socket sans rien envoyer d'autre et affiche *Connection error: Bridge controller failed authentication*. Elle réessaie ensuite avec un délai croissant (jusqu'à 30 s), sans jamais passer en *approved*.
### F. Mode historique (sans token)
-Vider le champ token et sauvegarder : plus aucune approbation n'est exigée, le comportement est celui d'avant la feature (serveur MCP local inchangé). Le serveur de test ne l'acceptera pas (il exige un token) ; ce mode se teste avec le serveur MCP du dépôt (`mcp-server/`).
+Vider le champ token et sauvegarder : plus aucune approbation n'est exigée, le comportement est celui d'avant la feature (serveur MCP local inchangé). Le serveur de test ne l'acceptera pas (il exige un token) ; ce mode se teste avec le serveur MCP du dépôt (`mcp-server/`). Attention : sans token, n'importe quel programme qui écoute le premier sur le port configuré peut piloter le navigateur.
+
+### G. Ancien `hello` avec token (déprécié)
+
+Pour un backend qui n'implémente pas encore le challenge : lancer le serveur avec `--legacy-bearer`, puis dans la console du service worker `chrome.storage.local.set({webbrainCloudBridgeLegacyBearerAuth: true})`. Le `hello` contient alors de nouveau `"auth":{"type":"bearer","token":"dev-token"}`. Sans ce drapeau, l'extension n'envoie jamais le token. Le retirer ensuite : `chrome.storage.local.remove('webbrainCloudBridgeLegacyBearerAuth')`.
## 6. Inspecter / déboguer
@@ -199,19 +211,21 @@ Problèmes fréquents :
| *Backend unreachable* | Le serveur n'est pas lancé, mauvais port, ou URL autre que `ws://127.0.0.1/localhost` |
| Rien ne change après modification du code | Extension non rechargée (↻ sur `chrome://extensions`) |
| Reste « Rejected » | Normal : pas de reconnexion auto après un refus, cliquer sur **Save & test connection** |
+| *Connection error: Bridge controller failed authentication* | Le token du serveur diffère de celui de Settings, ou un autre programme occupe le port |
+| *Rejected by the backend: Invalid token* avec un ancien backend | Le backend attend encore le token dans le `hello` : l'adapter au challenge, ou scénario G |
| Port 17374 déjà utilisé | Un serveur MCP tourne déjà : l'arrêter ou utiliser `--port` (et changer l'URL dans Settings) |
## 7. Tests automatisés
```bash
-npm run test:cloud-bridge-approval # 18 tests (Chrome + Firefox) : hello, pending, approved, rejected, commande avant/après, reconnexion, minuteur annulé après refus, mode sans token, identité unique, e2e vs serveur d'exemple
+npm run test:cloud-bridge-approval # Chrome + Firefox : hello, challenge, faux serveur sur le port, mauvais token, pending, approved, rejected, commande avant/après, reconnexion, minuteur annulé après refus, mode sans token, drapeau historique, identité unique, e2e vs serveur d'exemple
node test/run.js # suite complète existante (≈ 2400 tests)
```
## 8. Bonnes pratiques de sécurité pour vos essais
- Utilisez un token de test (`dev-token`), jamais une vraie clé API de provider : le token du Cloud Bridge est distinct.
-- Le token est stocké en clair dans `chrome.storage.local` et envoyé dans le `hello` (en local uniquement).
+- Le token est stocké en clair dans `chrome.storage.local` mais n'est jamais envoyé sur la socket (sauf avec le drapeau historique du scénario G).
- Le serveur d'exemple est un outil de test local, pas un backend de production.
## 9. Test réel : lancer une vraie tâche (`cloud_run`)
@@ -232,6 +246,6 @@ status run_xxxxx # état d'un run (l'id est dans la réponse de cloud
Votre backend doit :
1. **Écouter en WebSocket** sur une URL `ws://127.0.0.1` / `localhost` / `::1` (l'extension se connecte *vers* lui). Un backend distant n'est pas accepté tel quel : utilisez un relais local ou voyez la décision « URL localhost uniquement » dans la doc technique.
-2. À la réception du `hello`, vérifier `auth.token`, puis répondre `{"type":"connection_pending"}` puis, après validation côté utilisateur, `{"type":"connection_approved"}` (ou `connection_rejected`).
+2. À la réception du `hello`, répondre `auth_challenge` avec son propre nonce et sa preuve HMAC, puis vérifier la preuve de l'`auth_response` (calcul exact dans la doc technique, section « Messages »). Ensuite seulement répondre `{"type":"connection_pending"}` puis, après validation côté utilisateur, `{"type":"connection_approved"}` (ou `connection_rejected`). L'extension ignore toute approbation reçue avant que le serveur ait prouvé le token.
3. Envoyer ensuite les commandes `{"id","action","payload"}` et lire les réponses `{"id","ok","result"|"error"}`.
diff --git a/docs/security-model.md b/docs/security-model.md
index 1bc3e8090..b0fa2d2c1 100644
--- a/docs/security-model.md
+++ b/docs/security-model.md
@@ -194,9 +194,11 @@ Users can store a short profile (name, email, throwaway password) in Settings
The Cloud Bridge lets a controller send `cloud_*` run commands to the browser. By default (no token) it behaves as before. When a Cloud Bridge token is configured the bridge adds an opt-in approval step:
-- Each socket sends a `hello` with the token, `browserId`, `installationId` and browser/extension/platform info, then is *pending*; the backend must answer `connection_approved` before any command runs. Earlier commands get `connection_not_approved` (403) and never reach the background.
+- Each socket sends a `hello` with a fresh nonce and browser/extension/platform info, then is *pending*. The backend must first prove it holds the token (an HMAC over both sides' nonces); only then does the extension send its own proof with `browserId` and `installationId`. The token is never sent, so a program that takes the loopback port first learns nothing reusable, and `connection_approved` is ignored until the backend has proved itself. The backend must answer `connection_approved` before any command runs. Earlier commands get `connection_not_approved` (403) and never reach the background.
+- The old hello that carried the token is kept only behind the deprecated `webbrainCloudBridgeLegacyBearerAuth` flag, for backends that have not implemented the challenge yet.
- Approval is **per socket**: a reconnect, URL change or identity change starts pending again. `connection_rejected` closes the socket and stops auto-reconnect, and cancels any pending reconnect timer.
- The token is a Cloud Bridge credential, distinct from provider API keys. It is stored in `chrome.storage.local` and is never included in the bridge `status`.
+- Without a token nothing is authenticated: whichever program listens on the configured port first can send `cloud_*` commands. The local MCP server, the LM Studio plugin and WebBrain Cloud use this mode today, and it only runs once the bridge is turned on.
- The URL stays restricted to `ws://` on localhost, and the allowed actions stay limited to the `cloud_*` run operations rather than general browser APIs. The bridge sends connection metadata (such as the configured URL) and run data (`tabId`, `finalUrl`, `content` and `result`), which may contain sensitive page data.
**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).
diff --git a/examples/cloud-bridge-approval-server.mjs b/examples/cloud-bridge-approval-server.mjs
index aca4983e0..9aecc3902 100644
--- a/examples/cloud-bridge-approval-server.mjs
+++ b/examples/cloud-bridge-approval-server.mjs
@@ -2,17 +2,36 @@
// Minimal local WebSocket backend for the Cloud Bridge browser approval flow.
// Dependency-free (RFC 6455 text frames only). For local testing, not production.
//
-// node examples/cloud-bridge-approval-server.mjs --token dev-token [--port 17374] [--auto-approve]
+// node examples/cloud-bridge-approval-server.mjs --token dev-token [--port 17374] [--auto-approve] [--legacy-bearer]
//
// Interactive commands on stdin once a browser is pending/approved:
// approve | reject | run <task> | status [runId] | send {"id":"1","action":"cloud_status","payload":{"runId":"run_x"}}
+//
+// Authentication is the mutual HMAC challenge from
+// docs/cloud-bridge-browser-approval.md. --legacy-bearer also accepts the
+// deprecated hello that carries the token itself (older extension builds, or
+// webbrainCloudBridgeLegacyBearerAuth set in the browser).
-import { createHash } from 'node:crypto';
+import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
import { createServer } from 'node:http';
import { createInterface } from 'node:readline';
import { fileURLToPath } from 'node:url';
const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
+const AUTH_METHOD = 'hmac-sha256-v1';
+const AUTH_LABEL = 'webbrain-bridge-auth-v1';
+const HEX_256 = /^[0-9a-f]{64}$/;
+
+// role is 'controller' (this server's proof) or 'extension' (the browser's).
+function authProof(token, role, ...parts) {
+ return createHmac('sha256', token).update(JSON.stringify([AUTH_LABEL, role, ...parts])).digest('hex');
+}
+
+function sameSecret(a, b) {
+ const left = Buffer.from(String(a ?? ''));
+ const right = Buffer.from(String(b ?? ''));
+ return left.length === right.length && timingSafeEqual(left, right);
+}
function encodeFrame(text) {
const payload = Buffer.from(text);
@@ -46,7 +65,7 @@ function decodeFrames(buf) {
return { messages, rest: buf, close };
}
-export function startApprovalServer({ port = 17374, host = '127.0.0.1', token = 'dev-token', autoApprove = false, onMessage = () => {} } = {}) {
+export function startApprovalServer({ port = 17374, host = '127.0.0.1', token = 'dev-token', autoApprove = false, legacyBearer = false, onMessage = () => {} } = {}) {
const sessions = new Set();
const server = createServer((_req, res) => { res.writeHead(426).end(); });
server.on('upgrade', (req, socket) => {
@@ -62,15 +81,24 @@ export function startApprovalServer({ port = 17374, host = '127.0.0.1', token =
const session = {
socket,
hello: null,
+ browserId: null,
+ installationId: null,
state: 'connected',
send: (obj) => socket.write(encodeFrame(JSON.stringify(obj))),
+ pending(identity) {
+ session.browserId = identity.browserId;
+ session.installationId = identity.installationId || null;
+ session.state = 'pending';
+ session.send({ type: 'connection_pending', browserId: session.browserId });
+ if (autoApprove) session.approve();
+ },
approve() {
session.state = 'approved';
- session.send({ type: 'connection_approved', browserId: session.hello?.browserId });
+ session.send({ type: 'connection_approved', browserId: session.browserId });
},
reject(reason = 'Rejected by user') {
session.state = 'rejected';
- session.send({ type: 'connection_rejected', browserId: session.hello?.browserId, reason });
+ session.send({ type: 'connection_rejected', browserId: session.browserId, reason });
},
};
sessions.add(session);
@@ -83,12 +111,26 @@ export function startApprovalServer({ port = 17374, host = '127.0.0.1', token =
try { msg = JSON.parse(text); } catch { continue; }
if (msg.type === 'hello') {
session.hello = msg;
- if (msg.auth?.token !== token || !msg.browserId) session.reject('Invalid token');
- else {
- session.state = 'pending';
- session.send({ type: 'connection_pending', browserId: msg.browserId });
- if (autoApprove) session.approve();
- }
+ if (msg.auth?.type === 'challenge' && msg.auth.method === AUTH_METHOD && HEX_256.test(String(msg.auth.nonce))) {
+ // Prove the token first; the browser answers only if this checks out.
+ session.clientNonce = msg.auth.nonce;
+ session.serverNonce = randomBytes(32).toString('hex');
+ session.state = 'authenticating';
+ session.send({
+ type: 'auth_challenge',
+ method: AUTH_METHOD,
+ nonce: session.serverNonce,
+ proof: authProof(token, 'controller', session.clientNonce, session.serverNonce),
+ });
+ } else if (legacyBearer && msg.auth?.type === 'bearer' && sameSecret(msg.auth.token, token) && msg.browserId) {
+ session.pending(msg);
+ } else session.reject('Invalid token');
+ } else if (msg.type === 'auth_response' && session.state === 'authenticating') {
+ const browserId = String(msg.browserId || '');
+ const installationId = String(msg.installationId || '');
+ const expected = authProof(token, 'extension', session.clientNonce, session.serverNonce, browserId, installationId);
+ if (!browserId || msg.method !== AUTH_METHOD || !sameSecret(msg.proof, expected)) session.reject('Invalid token');
+ else session.pending({ browserId, installationId });
}
onMessage(msg, session);
}
@@ -115,6 +157,7 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
port: Number(opt('--port', 17374)),
token: opt('--token', 'dev-token'),
autoApprove: args.includes('--auto-approve'),
+ legacyBearer: args.includes('--legacy-bearer'),
onMessage: (msg) => console.log('<-', JSON.stringify(msg)),
});
console.log(`Listening on ws://127.0.0.1:${srv.port}/extension`);
diff --git a/src/chrome/ARCHITECTURE.md b/src/chrome/ARCHITECTURE.md
index a80f55d84..aa2fbfd09 100644
--- a/src/chrome/ARCHITECTURE.md
+++ b/src/chrome/ARCHITECTURE.md
@@ -270,10 +270,12 @@ only the `cloud_*` run actions. `cloud-runs.js` reads the persistent identity
(`webbrainCloudBridgeToken`, `…BrowserId`, `…InstallationId`) from
`chrome.storage.local` and passes it with `cloud-bridge-start`, because the
offscreen page has no storage access. With a token configured, each new socket
-sends an authenticated `hello` and stays *pending* until the backend answers
-`connection_approved`; commands before that get `connection_not_approved`.
-Approval is per socket and never carries over a reconnect. Without a token the
-legacy behaviour is unchanged. Protocol and limits:
+sends a `hello` with a nonce instead of the token; the backend must prove it
+holds the token before the extension answers with its own proof and IDs. The
+socket then stays *pending* until the backend answers `connection_approved`;
+commands before that get `connection_not_approved`. Authentication and approval are per
+socket and never carry over a reconnect. Without a token the legacy behaviour
+is unchanged. Protocol and limits:
[docs/cloud-bridge-browser-approval.md](../../docs/cloud-bridge-browser-approval.md).
### Why a shared offscreen document
diff --git a/src/chrome/src/background.js b/src/chrome/src/background.js
index 433d6abd5..39c76476e 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.webbrainCloudBridgeLegacyBearerAuth) {
cloudRunController.syncBridge().catch(() => {});
}
if (changes.maxAgentSteps) {
diff --git a/src/chrome/src/cloud-runs.js b/src/chrome/src/cloud-runs.js
index 4b127ca8a..199ed4a1b 100644
--- a/src/chrome/src/cloud-runs.js
+++ b/src/chrome/src/cloud-runs.js
@@ -2007,12 +2007,16 @@ export function createCloudRunController({
const stored = await api.storage.local.get([
'webbrainCloudBridgeToken',
'webbrainCloudBridgeBrowserId',
+ 'webbrainCloudBridgeLegacyBearerAuth',
]);
return {
token: stored.webbrainCloudBridgeToken || '',
browserId: stored.webbrainCloudBridgeBrowserId || installationId,
installationId,
extensionVersion: api.runtime.getManifest?.().version || '',
+ // Deprecated opt-in for controllers that only accept the token in the
+ // hello; off unless explicitly set (docs/cloud-bridge-browser-approval.md).
+ legacyBearerAuth: stored.webbrainCloudBridgeLegacyBearerAuth === true,
};
}
diff --git a/src/chrome/src/offscreen/cloud-bridge.js b/src/chrome/src/offscreen/cloud-bridge.js
index 94ccf6b46..f2d3471a3 100644
--- a/src/chrome/src/offscreen/cloud-bridge.js
+++ b/src/chrome/src/offscreen/cloud-bridge.js
@@ -24,6 +24,15 @@
'cloud_pause',
'cloud_resume',
]);
+ // A token-configured controller must pass a mutual HMAC challenge
+ // (docs/cloud-bridge-browser-approval.md). The token never crosses the
+ // socket: whoever answers on the loopback port proves it knows the token
+ // first, and only then does the extension prove itself and reveal its
+ // browser and installation IDs. A process that wins the port learns nothing
+ // it can replay and cannot move the socket to `approved`.
+ const BRIDGE_AUTH_METHOD = 'hmac-sha256-v1';
+ const BRIDGE_AUTH_LABEL = 'webbrain-bridge-auth-v1';
+ const HEX_256 = /^[0-9a-f]{64}$/;
let socket = null;
let bridgeUrl = null;
let enabled = false;
@@ -32,9 +41,11 @@
let lastError = '';
// Browser registration/approval. Identity is pushed by the background worker
// with `cloud-bridge-start` (the offscreen page has no storage access). When
- // a token is configured the backend must approve each new socket before any
- // cloud_* command runs; without a token the legacy local behaviour is kept.
- let identity = { token: '', browserId: '', installationId: '', extensionVersion: '' };
+ // a token is configured the backend must authenticate and then approve each
+ // new socket before any cloud_* command runs; without a token the legacy
+ // local behaviour is kept. `legacyBearerAuth` is the deprecated opt-in that
+ // still sends the token in the hello for controllers without the challenge.
+ let identity = { token: '', browserId: '', installationId: '', extensionVersion: '', legacyBearerAuth: false };
let approval = 'not_required'; // not_required | pending | approved | rejected
function browserInfo() {
@@ -83,6 +94,51 @@
}
}
+ function authMode() {
+ if (!identity.token) return 'none';
+ return identity.legacyBearerAuth ? 'legacy_bearer' : 'challenge';
+ }
+
+ const utf8 = (value) => new TextEncoder().encode(value);
+ const toHex = (bytes) => Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, '0')).join('');
+ const fromHex = (hex) => Uint8Array.from(hex.match(/../g), (pair) => parseInt(pair, 16));
+ const hmacKey = (token, usage) => crypto.subtle.importKey('raw', utf8(token), { name: 'HMAC', hash: 'SHA-256' }, false, [usage]);
+ // A JSON array keeps the role, the nonces and the identity unambiguous.
+ const authTranscript = (...parts) => utf8(JSON.stringify([BRIDGE_AUTH_LABEL, ...parts]));
+
+ async function answerAuthChallenge(msg, target, auth) {
+ // One challenge per socket, and only after our own nonce went out.
+ if (auth.mode !== 'challenge' || auth.state !== 'awaiting_controller') return;
+ auth.state = 'verifying';
+ const { token, browserId, installationId } = identity;
+ let proof = '';
+ try {
+ const verified = msg.method === BRIDGE_AUTH_METHOD
+ && typeof msg.nonce === 'string' && HEX_256.test(msg.nonce)
+ && typeof msg.proof === 'string' && HEX_256.test(msg.proof)
+ && await crypto.subtle.verify('HMAC', await hmacKey(token, 'verify'), fromHex(msg.proof),
+ authTranscript('controller', auth.nonce, msg.nonce));
+ if (verified) {
+ proof = toHex(await crypto.subtle.sign('HMAC', await hmacKey(token, 'sign'),
+ authTranscript('extension', auth.nonce, msg.nonce, browserId, installationId)));
+ }
+ } catch {
+ proof = '';
+ }
+ if (socket !== target) return;
+ if (!proof) {
+ // Not the controller this token belongs to: answer nothing and retry
+ // with backoff, in case the real controller gets its port back.
+ auth.state = 'failed';
+ lastError = 'Bridge controller failed authentication';
+ try { target.close(); } catch {}
+ return;
+ }
+ auth.state = 'verified';
+ reconnectAttempt = 0;
+ sendJson({ type: 'auth_response', method: BRIDGE_AUTH_METHOD, proof, browserId, installationId }, target);
+ }
+
function scheduleReconnect() {
if (!enabled || !bridgeUrl || reconnectTimer) return;
const delay = Math.min(30000, 500 * Math.pow(2, reconnectAttempt++));
@@ -97,10 +153,15 @@
if (socket && (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING)) return;
try {
const nextSocket = new WebSocket(bridgeUrl);
+ // Per-socket authentication state; nothing carries over a reconnect.
+ const auth = { mode: 'none', state: 'none', nonce: '' };
socket = nextSocket;
nextSocket.addEventListener('open', () => {
if (socket !== nextSocket) return;
- reconnectAttempt = 0;
+ auth.mode = authMode();
+ // A challenged socket only counts as healthy once the controller has
+ // proved itself, so a squatter that fails cannot reset the backoff.
+ if (auth.mode !== 'challenge') reconnectAttempt = 0;
lastError = '';
// Every new socket starts unapproved; approval never carries over.
approval = identity.token ? 'pending' : 'not_required';
@@ -114,7 +175,15 @@
platform: platformName(),
status: status(),
};
- if (identity.token) {
+ if (auth.mode === 'challenge') {
+ auth.nonce = toHex(crypto.getRandomValues(new Uint8Array(32)));
+ auth.state = 'awaiting_controller';
+ hello.auth = { type: 'challenge', method: BRIDGE_AUTH_METHOD, nonce: auth.nonce };
+ // The IDs go out in auth_response, after the controller's proof.
+ delete hello.status.browserId;
+ delete hello.status.installationId;
+ } else if (auth.mode === 'legacy_bearer') {
+ // Deprecated: hands the reusable token to whoever owns the port.
hello.auth = { type: 'bearer', token: identity.token };
hello.browserId = identity.browserId;
hello.installationId = identity.installationId;
@@ -135,8 +204,17 @@
return;
}
+ if (msg.type === 'auth_challenge') {
+ await answerAuthChallenge(msg, nextSocket, auth);
+ return;
+ }
+
if (msg.type === 'connection_pending' || msg.type === 'connection_approved' || msg.type === 'connection_rejected') {
if (!identity.token) return;
+ // Only a controller that proved the token may move a challenged
+ // socket toward approval. A rejection only takes rights away, so it
+ // is honoured from anyone.
+ if (auth.mode === 'challenge' && auth.state !== 'verified' && msg.type !== 'connection_rejected') return;
if (msg.browserId && msg.browserId !== identity.browserId) return;
if (msg.type === 'connection_pending') {
if (approval !== 'approved') approval = 'pending';
@@ -198,7 +276,8 @@
scheduleReconnect();
});
nextSocket.addEventListener('error', () => {
- if (socket !== nextSocket) return;
+ // Closing a socket we dropped can error; keep the reason we dropped it.
+ if (socket !== nextSocket || auth.state === 'failed') return;
lastError = 'WebSocket error';
});
} catch (e) {
@@ -223,6 +302,7 @@
browserId: String(msg.browserId || ''),
installationId: String(msg.installationId || ''),
extensionVersion: String(msg.extensionVersion || ''),
+ legacyBearerAuth: msg.legacyBearerAuth === true,
};
const identityChanged = JSON.stringify(nextIdentity) !== JSON.stringify(identity);
const changed = (bridgeUrl && bridgeUrl !== nextUrl) || identityChanged;
diff --git a/src/firefox/src/background.js b/src/firefox/src/background.js
index 94c788044..440b0e498 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.webbrainCloudBridgeLegacyBearerAuth) {
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..6109c62a2 100644
--- a/src/firefox/src/cloud-bridge.js
+++ b/src/firefox/src/cloud-bridge.js
@@ -21,6 +21,22 @@ const ALLOWED_BRIDGE_ACTIONS = new Set([
'cloud_pause',
'cloud_resume',
]);
+// A token-configured controller must pass a mutual HMAC challenge
+// (docs/cloud-bridge-browser-approval.md). The token never crosses the
+// socket: whoever answers on the loopback port proves it knows the token
+// first, and only then does the extension prove itself and reveal its
+// browser and installation IDs. A process that wins the port learns nothing
+// it can replay and cannot move the socket to `approved`.
+const BRIDGE_AUTH_METHOD = 'hmac-sha256-v1';
+const BRIDGE_AUTH_LABEL = 'webbrain-bridge-auth-v1';
+const HEX_256 = /^[0-9a-f]{64}$/;
+
+const utf8 = (value) => new TextEncoder().encode(value);
+const toHex = (bytes) => Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, '0')).join('');
+const fromHex = (hex) => Uint8Array.from(hex.match(/../g), (pair) => parseInt(pair, 16));
+const hmacKey = (token, usage) => crypto.subtle.importKey('raw', utf8(token), { name: 'HMAC', hash: 'SHA-256' }, false, [usage]);
+// A JSON array keeps the role, the nonces and the identity unambiguous.
+const authTranscript = (...parts) => utf8(JSON.stringify([BRIDGE_AUTH_LABEL, ...parts]));
export function createCloudBridge({ dispatch, WebSocketImpl = globalThis.WebSocket, nav = globalThis.navigator } = {}) {
let socket = null;
@@ -29,9 +45,11 @@ export function createCloudBridge({ dispatch, WebSocketImpl = globalThis.WebSock
let reconnectTimer = null;
let reconnectAttempt = 0;
let lastError = '';
- // With a token configured the backend must approve each new socket before
- // any cloud_* command runs; without one the legacy local behaviour is kept.
- let identity = { token: '', browserId: '', installationId: '', extensionVersion: '' };
+ // With a token configured the backend must authenticate and then approve
+ // each new socket before any cloud_* command runs; without one the legacy
+ // local behaviour is kept. `legacyBearerAuth` is the deprecated opt-in that
+ // still sends the token in the hello for controllers without the challenge.
+ let identity = { token: '', browserId: '', installationId: '', extensionVersion: '', legacyBearerAuth: false };
let approval = 'not_required'; // not_required | pending | approved | rejected
function browserInfo() {
@@ -72,6 +90,44 @@ export function createCloudBridge({ dispatch, WebSocketImpl = globalThis.WebSock
}
}
+ function authMode() {
+ if (!identity.token) return 'none';
+ return identity.legacyBearerAuth ? 'legacy_bearer' : 'challenge';
+ }
+
+ async function answerAuthChallenge(msg, target, auth) {
+ // One challenge per socket, and only after our own nonce went out.
+ if (auth.mode !== 'challenge' || auth.state !== 'awaiting_controller') return;
+ auth.state = 'verifying';
+ const { token, browserId, installationId } = identity;
+ let proof = '';
+ try {
+ const verified = msg.method === BRIDGE_AUTH_METHOD
+ && typeof msg.nonce === 'string' && HEX_256.test(msg.nonce)
+ && typeof msg.proof === 'string' && HEX_256.test(msg.proof)
+ && await crypto.subtle.verify('HMAC', await hmacKey(token, 'verify'), fromHex(msg.proof),
+ authTranscript('controller', auth.nonce, msg.nonce));
+ if (verified) {
+ proof = toHex(await crypto.subtle.sign('HMAC', await hmacKey(token, 'sign'),
+ authTranscript('extension', auth.nonce, msg.nonce, browserId, installationId)));
+ }
+ } catch {
+ proof = '';
+ }
+ if (socket !== target) return;
+ if (!proof) {
+ // Not the controller this token belongs to: answer nothing and retry
+ // with backoff, in case the real controller gets its port back.
+ auth.state = 'failed';
+ lastError = 'Bridge controller failed authentication';
+ try { target.close(); } catch {}
+ return;
+ }
+ auth.state = 'verified';
+ reconnectAttempt = 0;
+ sendJson({ type: 'auth_response', method: BRIDGE_AUTH_METHOD, proof, browserId, installationId }, target);
+ }
+
function scheduleReconnect() {
if (!enabled || !bridgeUrl || reconnectTimer) return;
const delay = Math.min(30000, 500 * Math.pow(2, reconnectAttempt++));
@@ -86,10 +142,15 @@ export function createCloudBridge({ dispatch, WebSocketImpl = globalThis.WebSock
if (socket && (socket.readyState === WebSocketImpl.OPEN || socket.readyState === WebSocketImpl.CONNECTING)) return;
try {
const nextSocket = new WebSocketImpl(bridgeUrl);
+ // Per-socket authentication state; nothing carries over a reconnect.
+ const auth = { mode: 'none', state: 'none', nonce: '' };
socket = nextSocket;
nextSocket.addEventListener('open', () => {
if (socket !== nextSocket) return;
- reconnectAttempt = 0;
+ auth.mode = authMode();
+ // A challenged socket only counts as healthy once the controller has
+ // proved itself, so a squatter that fails cannot reset the backoff.
+ if (auth.mode !== 'challenge') reconnectAttempt = 0;
lastError = '';
// Every new socket starts unapproved; approval never carries over.
approval = identity.token ? 'pending' : 'not_required';
@@ -103,7 +164,15 @@ export function createCloudBridge({ dispatch, WebSocketImpl = globalThis.WebSock
platform: nav?.platform || '',
status: status(),
};
- if (identity.token) {
+ if (auth.mode === 'challenge') {
+ auth.nonce = toHex(crypto.getRandomValues(new Uint8Array(32)));
+ auth.state = 'awaiting_controller';
+ hello.auth = { type: 'challenge', method: BRIDGE_AUTH_METHOD, nonce: auth.nonce };
+ // The IDs go out in auth_response, after the controller's proof.
+ delete hello.status.browserId;
+ delete hello.status.installationId;
+ } else if (auth.mode === 'legacy_bearer') {
+ // Deprecated: hands the reusable token to whoever owns the port.
hello.auth = { type: 'bearer', token: identity.token };
hello.browserId = identity.browserId;
hello.installationId = identity.installationId;
@@ -124,8 +193,17 @@ export function createCloudBridge({ dispatch, WebSocketImpl = globalThis.WebSock
return;
}
+ if (msg.type === 'auth_challenge') {
+ await answerAuthChallenge(msg, nextSocket, auth);
+ return;
+ }
+
if (msg.type === 'connection_pending' || msg.type === 'connection_approved' || msg.type === 'connection_rejected') {
if (!identity.token) return;
+ // Only a controller that proved the token may move a challenged
+ // socket toward approval. A rejection only takes rights away, so it
+ // is honoured from anyone.
+ if (auth.mode === 'challenge' && auth.state !== 'verified' && msg.type !== 'connection_rejected') return;
if (msg.browserId && msg.browserId !== identity.browserId) return;
if (msg.type === 'connection_pending') {
if (approval !== 'approved') approval = 'pending';
@@ -182,7 +260,8 @@ export function createCloudBridge({ dispatch, WebSocketImpl = globalThis.WebSock
scheduleReconnect();
});
nextSocket.addEventListener('error', () => {
- if (socket !== nextSocket) return;
+ // Closing a socket we dropped can error; keep the reason we dropped it.
+ if (socket !== nextSocket || auth.state === 'failed') return;
lastError = 'WebSocket error';
});
} catch (e) {
@@ -205,6 +284,7 @@ export function createCloudBridge({ dispatch, WebSocketImpl = globalThis.WebSock
browserId: String(msg.browserId || ''),
installationId: String(msg.installationId || ''),
extensionVersion: String(msg.extensionVersion || ''),
+ legacyBearerAuth: msg.legacyBearerAuth === true,
};
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..e2d9ae292 100644
--- a/src/firefox/src/cloud-runs.js
+++ b/src/firefox/src/cloud-runs.js
@@ -2008,12 +2008,16 @@ export function createCloudRunController({
const stored = await api.storage.local.get([
'webbrainCloudBridgeToken',
'webbrainCloudBridgeBrowserId',
+ 'webbrainCloudBridgeLegacyBearerAuth',
]);
return {
token: stored.webbrainCloudBridgeToken || '',
browserId: stored.webbrainCloudBridgeBrowserId || installationId,
installationId,
extensionVersion: api.runtime.getManifest?.().version || '',
+ // Deprecated opt-in for controllers that only accept the token in the
+ // hello; off unless explicitly set (docs/cloud-bridge-browser-approval.md).
+ legacyBearerAuth: stored.webbrainCloudBridgeLegacyBearerAuth === true,
};
}
diff --git a/test/cloud-bridge-approval.mjs b/test/cloud-bridge-approval.mjs
index 35ca8c486..7d99eb539 100644
--- a/test/cloud-bridge-approval.mjs
+++ b/test/cloud-bridge-approval.mjs
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
+import { createHmac, randomBytes } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { startApprovalServer } from '../examples/cloud-bridge-approval-server.mjs';
@@ -11,7 +12,28 @@ const source = fs.readFileSync(path.join(ROOT, 'src/chrome/src/offscreen/cloud-b
const IDENTITY = { token: 'secret-token', browserId: 'browser-1', installationId: 'install-1', extensionVersion: '1.2.3' };
const tick = (ms = 0) => new Promise(resolve => setTimeout(resolve, ms));
-function harness({ WebSocketImpl, sendMessage = async () => ({ runId: 'r1', status: 'running' }) } = {}) {
+// Wire format pinned independently of the example server.
+const hmacProof = (token, ...parts) => createHmac('sha256', token)
+ .update(JSON.stringify(['webbrain-bridge-auth-v1', ...parts])).digest('hex');
+
+// Plays the controller's half of the challenge and returns the browser's answer.
+async function authenticate(socket, token = IDENTITY.token, overrides = {}) {
+ const hello = socket.sent.filter(m => m.type === 'hello').at(-1);
+ const nonce = randomBytes(32).toString('hex');
+ const before = socket.sent.length;
+ await socket.receive({
+ type: 'auth_challenge',
+ method: 'hmac-sha256-v1',
+ nonce,
+ proof: hmacProof(token, 'controller', hello.auth.nonce, nonce),
+ ...overrides,
+ });
+ return { clientNonce: hello.auth.nonce, serverNonce: nonce, response: socket.sent.slice(before).find(m => m.type === 'auth_response') };
+}
+
+const leaksSecretOrIdentity = (messages) => /secret-token|browser-1|install-1/.test(JSON.stringify(messages));
+
+function harness({ WebSocketImpl, cryptoImpl = globalThis.crypto, sendMessage = async () => ({ runId: 'r1', status: 'running' }) } = {}) {
const sockets = [];
const timers = [];
const runtimeCalls = [];
@@ -31,6 +53,8 @@ function harness({ WebSocketImpl, sendMessage = async () => ({ runId: 'r1', stat
}
vm.runInNewContext(source, {
URL,
+ TextEncoder,
+ crypto: cryptoImpl,
WebSocket: WebSocketImpl || FakeWebSocket,
navigator: { userAgent: 'Mozilla/5.0 Chrome/126.0.1 Safari/537.36', platform: 'Linux x86_64' },
chrome: { runtime: {
@@ -49,28 +73,67 @@ function harness({ WebSocketImpl, sendMessage = async () => ({ runId: 'r1', stat
const cmd = { id: 'c1', action: 'cloud_status', payload: { runId: 'r1' } };
-test('hello carries identity, token, browser, version and platform', () => {
+test('hello carries a challenge and browser info but never the token or identity', () => {
const h = harness();
h.start();
h.sockets[0].emit('open');
const hello = h.sockets[0].sent[0];
assert.equal(hello.type, 'hello');
- assert.deepEqual(hello.auth, { type: 'bearer', token: 'secret-token' });
- assert.equal(hello.browserId, 'browser-1');
- assert.equal(hello.installationId, 'install-1');
+ assert.equal(hello.auth.type, 'challenge');
+ assert.equal(hello.auth.method, 'hmac-sha256-v1');
+ assert.match(hello.auth.nonce, /^[0-9a-f]{64}$/);
+ assert.equal(hello.auth.token, undefined);
+ assert.equal(hello.browserId, undefined);
+ assert.equal(hello.installationId, undefined);
+ assert.equal(leaksSecretOrIdentity(hello), false, 'the controller has not proved anything yet');
assert.deepEqual({ ...hello.browser }, { name: 'Chrome', version: '126.0.1' });
assert.equal(hello.extensionVersion, '1.2.3');
assert.equal(hello.platform, 'Linux x86_64');
assert.deepEqual([...hello.capabilities], ['saved_workflows_v1', 'run_modes_v1', 'scheduled_jobs_v1', 'run_provider_v1', 'private_results_v1', 'bot_memory_v1', 'run_handoff_v1']);
- assert.equal(JSON.stringify(hello.status).includes('secret-token'), false, 'status must not leak the token');
assert.equal(JSON.stringify(h.status()).includes('secret-token'), false);
});
+test('a controller that proves the token gets the identity and a proof bound to both nonces', async () => {
+ const h = harness();
+ h.start();
+ const s = h.sockets[0];
+ s.emit('open');
+ const { clientNonce, serverNonce, response } = await authenticate(s);
+ assert.deepEqual({ ...response }, {
+ type: 'auth_response',
+ method: 'hmac-sha256-v1',
+ proof: hmacProof('secret-token', 'extension', clientNonce, serverNonce, 'browser-1', 'install-1'),
+ browserId: 'browser-1',
+ installationId: 'install-1',
+ });
+ assert.notEqual(response.proof, hmacProof('secret-token', 'controller', clientNonce, serverNonce), 'roles must not be interchangeable');
+ assert.equal(JSON.stringify(s.sent).includes('secret-token'), false, 'the token itself never crosses the socket');
+ const again = await authenticate(s);
+ assert.equal(again.response, undefined, 'one challenge per socket');
+});
+
+test('the extension proof matches the documented test vector', async () => {
+ // docs/cloud-bridge-browser-approval.md: hello nonce 00 x 32, backend nonce 11 x 32.
+ const h = harness({ cryptoImpl: { subtle: globalThis.crypto.subtle, getRandomValues: bytes => bytes.fill(0) } });
+ h.start();
+ const s = h.sockets[0];
+ s.emit('open');
+ assert.equal(s.sent[0].auth.nonce, '00'.repeat(32));
+ await s.receive({
+ type: 'auth_challenge',
+ method: 'hmac-sha256-v1',
+ nonce: '11'.repeat(32),
+ proof: '04734662625940a90c0e3aeed5a653b6fb2e24779baa71b6dccab394601937d4',
+ });
+ assert.equal(s.sent.find(m => m.type === 'auth_response').proof, '5670c5e30c40e94ed27cd0e99148310d44a3efe54d668b2f9fd21efe9a8e913e');
+});
+
test('pending connection refuses cloud commands without calling the background', async () => {
const h = harness();
h.start();
const s = h.sockets[0];
s.emit('open');
+ await authenticate(s);
s.receive({ type: 'connection_pending', browserId: 'browser-1' });
assert.equal(h.status().approval, 'pending');
s.receive(cmd);
@@ -96,6 +159,7 @@ test('approved connection runs commands with the unchanged payload format', asyn
h.start();
const s = h.sockets[0];
s.emit('open');
+ await authenticate(s);
s.receive({ type: 'connection_pending' });
s.receive({ type: 'connection_approved', browserId: 'browser-1' });
assert.equal(h.status().approval, 'approved');
@@ -111,6 +175,7 @@ test('approval for another browserId is ignored', async () => {
const h = harness();
h.start();
h.sockets[0].emit('open');
+ await authenticate(h.sockets[0]);
h.sockets[0].receive({ type: 'connection_approved', browserId: 'someone-else' });
assert.equal(h.status().approval, 'pending');
});
@@ -130,23 +195,29 @@ test('rejected connection closes, blocks commands and does not reconnect', async
assert.equal(h.runtimeCalls.length, 0);
});
-test('reconnect requires a fresh approval', async () => {
+test('reconnect requires a fresh challenge and a fresh approval', async () => {
const h = harness();
h.start();
const first = h.sockets[0];
first.emit('open');
+ await authenticate(first);
first.receive({ type: 'connection_approved' });
+ assert.equal(h.status().approval, 'approved');
first.close();
assert.equal(h.status().approval, 'pending');
h.timers[0].callback();
const second = h.sockets[1];
second.emit('open');
assert.equal(second.sent[0].type, 'hello');
- assert.equal(second.sent[0].auth.token, 'secret-token');
+ assert.equal(second.sent[0].auth.token, undefined);
+ assert.notEqual(second.sent[0].auth.nonce, first.sent[0].auth.nonce, 'every socket gets a new nonce');
second.receive(cmd);
await tick();
assert.equal(second.sent.find(m => m.id === 'c1').code, 'connection_not_approved');
+ second.receive({ type: 'connection_approved' });
+ assert.equal(h.status().approval, 'pending', 'approval before the new challenge is ignored');
assert.equal(h.runtimeCalls.length, 0);
+ await authenticate(second);
second.receive({ type: 'connection_approved' });
second.receive(cmd);
await tick();
@@ -186,7 +257,9 @@ test('end to end against the example server', async () => {
for (let i = 0; i < 50 && ![...server.sessions].some(s => s.state === 'pending'); i++) await tick(20);
const session = [...server.sessions][0];
assert.equal(session.state, 'pending');
- assert.equal(session.hello.browserId, 'browser-1');
+ assert.equal(session.browserId, 'browser-1');
+ assert.equal(session.installationId, 'install-1');
+ assert.equal(JSON.stringify(received).includes('secret-token'), false, 'the server verified the browser without receiving the token');
session.send(cmd);
for (let i = 0; i < 50 && !received.some(m => m.id === 'c1'); i++) await tick(20);
assert.equal(received.find(m => m.id === 'c1').code, 'connection_not_approved');
@@ -199,6 +272,39 @@ test('end to end against the example server', async () => {
}
});
+test('end to end: an example server holding another token is refused by the browser', async () => {
+ const received = [];
+ const server = await startApprovalServer({ port: 0, token: 'other-token', onMessage: m => received.push(m) });
+ const h = harness({ WebSocketImpl: WebSocket });
+ try {
+ h.start(IDENTITY, `ws://127.0.0.1:${server.port}/extension`);
+ for (let i = 0; i < 50 && !/failed authentication/.test(h.status().lastError); i++) await tick(20);
+ assert.match(h.status().lastError, /failed authentication/);
+ assert.equal(received.some(m => m.type === 'auth_response'), false);
+ assert.equal(leaksSecretOrIdentity(received), false);
+ } finally {
+ await server.close();
+ }
+});
+
+test('end to end: the legacy bearer flag still works against a --legacy-bearer server', async () => {
+ const strict = await startApprovalServer({ port: 0, token: 'secret-token' });
+ const legacy = await startApprovalServer({ port: 0, token: 'secret-token', legacyBearer: true, autoApprove: true });
+ const h = harness({ WebSocketImpl: WebSocket });
+ try {
+ h.start({ ...IDENTITY, legacyBearerAuth: true }, `ws://127.0.0.1:${strict.port}/extension`);
+ for (let i = 0; i < 50 && h.status().approval !== 'rejected'; i++) await tick(20);
+ assert.equal(h.status().approval, 'rejected', 'a challenge-only server refuses the bearer hello');
+ h.start({ ...IDENTITY, legacyBearerAuth: true }, `ws://127.0.0.1:${legacy.port}/extension`);
+ for (let i = 0; i < 50 && h.status().approval !== 'approved'; i++) await tick(20);
+ assert.equal(h.status().approval, 'approved');
+ assert.equal([...legacy.sessions][0].browserId, 'browser-1');
+ } finally {
+ await strict.close();
+ await legacy.close();
+ }
+});
+
// ---- Firefox: same protocol, socket lives in the background page ----
const { createCloudBridge } = await import('../src/firefox/src/cloud-bridge.js');
const { createCloudRunController: createFxController } = await import('../src/firefox/src/cloud-runs.js');
@@ -223,6 +329,78 @@ function fxHarness({ WebSocketImpl, dispatch } = {}) {
return { bridge, sockets, calls };
}
+for (const [label, make, startBridge, statusOf, callsOf] of [
+ ['chrome', () => harness(), (h, extra) => h.start({ ...IDENTITY, ...extra }), h => h.status(), h => h.runtimeCalls],
+ ['firefox', () => fxHarness(), (h, extra) => h.bridge.start({ url: 'ws://127.0.0.1:17374/extension', ...IDENTITY, ...extra }), h => h.bridge.status(), h => h.calls],
+]) {
+ test(`${label}: a process squatting the port cannot get approved or learn the token`, async () => {
+ const h = make();
+ try {
+ startBridge(h);
+ const s = h.sockets[0];
+ s.emit('open');
+ // The old protocol let any listener echo these and run commands.
+ await s.receive({ type: 'connection_pending' });
+ await s.receive({ type: 'connection_approved' });
+ await s.receive({ type: 'connection_approved', browserId: 'browser-1' });
+ assert.equal(statusOf(h).approval, 'pending');
+ await s.receive({ id: 'squat', action: 'cloud_run', payload: { task: 'x', mode: 'act' } });
+ assert.equal(s.sent.find(m => m.id === 'squat').code, 'connection_not_approved');
+ assert.equal(callsOf(h).length, 0);
+ assert.equal(leaksSecretOrIdentity(s.sent), false, 'nothing reusable reaches an unauthenticated controller');
+ } finally { if (label === 'firefox') h.bridge.stop(); }
+ });
+
+ test(`${label}: a controller with the wrong token gets no answer and is retried with growing backoff`, async () => {
+ const h = make();
+ try {
+ startBridge(h);
+ const s = h.sockets[0];
+ s.emit('open');
+ const { response } = await authenticate(s, 'guessed-token');
+ assert.equal(response, undefined, 'no extension proof for a controller that failed');
+ assert.equal(s.readyState, 3, 'socket closed');
+ assert.equal(statusOf(h).approval, 'pending', 'not a rejection: the real controller may come back');
+ assert.match(statusOf(h).lastError, /failed authentication/);
+ await s.receive({ type: 'connection_approved' });
+ assert.equal(statusOf(h).approval, 'pending');
+ assert.equal(leaksSecretOrIdentity(s.sent), false);
+ assert.equal(callsOf(h).length, 0);
+ if (label === 'chrome') {
+ assert.equal(h.timers[0].delay, 500);
+ const malformed = [{ method: 'bearer' }, { nonce: 'short' }, { proof: 'zz' }, { proof: 'A'.repeat(64) }];
+ for (const [i, bad] of malformed.entries()) {
+ h.timers[i].callback();
+ const next = h.sockets[i + 1];
+ next.emit('open');
+ assert.equal((await authenticate(next, IDENTITY.token, bad)).response, undefined, JSON.stringify(bad));
+ assert.equal(next.readyState, 3, JSON.stringify(bad));
+ // Opening a socket must not reset the backoff before the controller proves itself.
+ assert.equal(h.timers[i + 1].delay, 500 * 2 ** (i + 1));
+ }
+ assert.equal(callsOf(h).length, 0);
+ }
+ } finally { if (label === 'firefox') h.bridge.stop(); }
+ });
+
+ test(`${label}: the deprecated bearer hello needs the explicit legacy flag`, async () => {
+ const h = make();
+ try {
+ startBridge(h, { legacyBearerAuth: true });
+ const s = h.sockets[0];
+ s.emit('open');
+ const hello = s.sent[0];
+ assert.deepEqual({ ...hello.auth }, { type: 'bearer', token: 'secret-token' });
+ assert.equal(hello.browserId, 'browser-1');
+ assert.equal(hello.installationId, 'install-1');
+ await s.receive({ type: 'connection_approved', browserId: 'browser-1' });
+ await s.receive(cmd);
+ assert.equal(s.sent.find(m => m.id === 'c1').ok, true);
+ assert.equal(callsOf(h).length, 1);
+ } finally { if (label === 'firefox') h.bridge.stop(); }
+ });
+}
+
for (const build of ['chrome', 'firefox']) {
test(`${build}: handoff commands require approval and preserve their run and note payload`, async () => {
const h = build === 'chrome' ? harness() : fxHarness();
@@ -238,6 +416,7 @@ for (const build of ['chrome', 'firefox']) {
assert.equal(socket.sent.find(reply => reply.id === `unapproved-${action}`).status, 403);
}
assert.equal(calls.length, 0);
+ await authenticate(socket);
await socket.receive({ type: 'connection_approved', browserId: IDENTITY.browserId });
await socket.receive({ id: 'pause', action: 'cloud_pause', payload: { runId: 'r1' } });
await socket.receive({ id: 'resume', action: 'cloud_resume', payload: { runId: 'r1', note: 'I signed in' } });
@@ -256,6 +435,7 @@ for (const build of ['chrome', 'firefox']) {
else h.bridge.start({ url: 'ws://127.0.0.1:17374/extension', ...IDENTITY });
const socket = h.sockets[0];
socket.emit('open');
+ await authenticate(socket);
await socket.receive({ type: 'connection_approved', browserId: IDENTITY.browserId });
for (const malformed of [null, [], 'cloud_status', 0, true]) {
const before = socket.sent.length;
@@ -279,11 +459,18 @@ test('firefox: hello, pending refusal, approval, rejection', async () => {
s.emit('open');
const hello = s.sent[0];
assert.deepEqual({ ...hello.browser }, { name: 'Firefox', version: '140.0' });
- assert.equal(hello.auth.token, 'secret-token');
- assert.equal(hello.browserId, 'browser-1');
+ assert.equal(hello.auth.type, 'challenge');
+ assert.match(hello.auth.nonce, /^[0-9a-f]{64}$/);
+ assert.equal(leaksSecretOrIdentity(hello), false);
assert.equal(hello.platform, 'Linux x86_64');
assert.equal(JSON.stringify(h.bridge.status()).includes('secret-token'), false);
+ const { clientNonce, serverNonce, response } = await authenticate(s);
+ assert.equal(response.browserId, 'browser-1');
+ assert.equal(response.installationId, 'install-1');
+ assert.equal(response.proof, hmacProof('secret-token', 'extension', clientNonce, serverNonce, 'browser-1', 'install-1'));
+ assert.equal(JSON.stringify(s.sent).includes('secret-token'), false);
+
s.receive({ type: 'connection_pending' });
s.receive(cmd);
await tick();
@@ -311,7 +498,9 @@ test('firefox: reconnect requires a fresh approval', async () => {
h.bridge.start({ url: 'ws://127.0.0.1:17374/extension', ...IDENTITY });
const first = h.sockets[0];
first.emit('open');
+ await authenticate(first);
first.receive({ type: 'connection_approved' });
+ assert.equal(h.bridge.status().approval, 'approved');
first.close();
assert.equal(h.bridge.status().approval, 'pending');
await tick(700); // first backoff is 500 ms
@@ -422,4 +611,28 @@ for (const [label, createController] of [['chrome', null], ['firefox', createFxC
assert.equal(ids.size, 1, 'all concurrent starts must use the same installation id');
assert.equal([...ids][0], store.webbrainCloudBridgeInstallationId, 'and it matches the persisted one');
});
+
+ test(`${label}: the deprecated bearer hello is off unless the legacy flag is stored as true`, async () => {
+ const { createCloudRunController: make } = label === 'chrome'
+ ? await import('../src/chrome/src/cloud-runs.js')
+ : { createCloudRunController: createController };
+ const store = { webbrainCloudBridgeEnabled: true, webbrainCloudBridgeToken: 'tok' };
+ const started = [];
+ const api = {
+ storage: { local: {
+ get: async (keys) => Object.fromEntries([].concat(keys).map(k => [k, store[k]]).filter(([, v]) => v !== undefined)),
+ set: async (obj) => { Object.assign(store, obj); },
+ } },
+ runtime: { getManifest: () => ({ version: '1.0.0' }), sendMessage: async (m) => { started.push(m); return {}; } },
+ };
+ const bridge = { start: (m) => { started.push(m); return {}; }, stop: () => ({}), status: () => ({}) };
+ const controller = make({ chromeApi: api, agent: {}, ensureOffscreen: async () => {}, bridge });
+ for (const value of [undefined, 'true', 1, true]) {
+ if (value === undefined) delete store.webbrainCloudBridgeLegacyBearerAuth;
+ else store.webbrainCloudBridgeLegacyBearerAuth = value;
+ await controller.syncBridge();
+ assert.equal(started.at(-1).legacyBearerAuth, value === true, `only an explicit true opts in (${JSON.stringify(value)})`);
+ assert.equal(started.at(-1).token, 'tok');
+ }
+ });
}