Skip to content

Commit 1a8f89c

Browse files
committed
fix(browser): wake the paired extension relay
1 parent fc59f0b commit 1a8f89c

21 files changed

Lines changed: 504 additions & 210 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,6 @@ extensions/browser/src/browser/extension-install.ts 3
7777
extensions/browser/src/browser/extension-native-host.ts 1
7878
extensions/browser/src/browser/extension-native-protocol.ts 1
7979
extensions/browser/src/browser/extension-relay/auth-v2.ts 10
80-
extensions/browser/src/browser/extension-relay/relay-auth.ts 1
8180
extensions/browser/src/browser/extension-relay/relay-bridge.ts 9
8281
extensions/browser/src/browser/extension-relay/relay-protocol.ts 4
8382
extensions/browser/src/browser/output-files.ts 1

‎docs/tools/chrome-extension.md‎

Lines changed: 66 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ openclaw config set browser.defaultProfile chrome
107107
Fresh automatic pairings use **All tabs**. Existing valid pairings are never
108108
overwritten, and older pairings keep their stored access mode.
109109

110-
For local setup, native bootstrap connects the extension through the local
110+
For fresh local setup, native bootstrap connects the extension through the local
111111
Gateway's exact `/browser/extension` route. That first authenticated connection
112112
wakes the lazy browser-control service and starts the profile's loopback relay;
113113
OpenClaw and local clients such as mcporter then use that profile relay port.
@@ -119,6 +119,43 @@ the browser-node host while the node uses its configured remote Gateway. An
119119
explicit `--gateway-url` pairing connects directly to that remote Gateway and
120120
remains a manual-only flow.
121121

122+
### Standalone direct-loopback relay
123+
124+
A pairing on `ws://127.0.0.1:<port>/extension` can run without a local Gateway
125+
or browser node. On macOS and Linux, the bundled extension can ask the installed
126+
native host to start a standalone relay when reconnecting to that endpoint.
127+
Automatic local setup must be enabled. Requests are limited to once per minute;
128+
the extension still authenticates the relay with connection-bound v2 proofs.
129+
This requires both the updated native host and an extension build containing
130+
relay wake-up support. Do not assume the Store v2.2.0 build includes that code;
131+
the bundled unpacked development copy is the source-build validation path.
132+
133+
Automatic wake-up requires the exact `127.0.0.1` host that the daemon serves.
134+
Other loopback aliases, including `localhost` and IPv6, do not trigger wake-up;
135+
use the canonical IPv4 endpoint when pairing for standalone operation.
136+
137+
Wake-up uses the port in the extension's existing canonical pairing. It does
138+
not switch to the first configured profile. The native host resolves current
139+
`browser.profiles` and permits only an extension-driver relay port, including
140+
automatically allocated ports and explicit `cdpPort` pins. A removed profile
141+
or stale port fails closed; correct the pairing to match the current profile.
142+
Gateway `/browser/extension` routes and remote pairings never trigger local
143+
daemon wake-up. Browser-node pairings that use a direct loopback relay can use
144+
it even when their Gateway hint points to a remote host.
145+
146+
An existing listener keeps ownership of its port. Otherwise, the native host
147+
spawns `dist/extensions/browser/relay-daemon-entry.js` as a detached process.
148+
The daemon uses the same per-host relay key and stays alive while an extension
149+
or CDP client is connected. After both disconnect, it exits following ten
150+
minutes of inactivity, checked every 30 seconds. Closing Chrome alone does not
151+
stop it while a CDP client remains connected. A later reconnect can wake it again.
152+
153+
The standalone daemon defaults to **v2-only authentication**, independently of
154+
the Gateway relay's legacy default. Only an explicit
155+
`browser.extensionRelay.allowLegacyAuth=true` enables legacy authentication;
156+
an unset value, `false`, or a config-read failure never enables it. Prefer v2
157+
clients so the persistent key is not disclosed to a process occupying the port.
158+
122159
### Choose tab access
123160

124161
- **All tabs** exposes every eligible ordinary tab in that Chrome profile,
@@ -165,7 +202,7 @@ Settings shows redacted relay/native bootstrap status and the **Use automatic
165202
local setup** switch.
166203

167204
- Turning automatic setup off preserves a valid existing pairing but prevents
168-
new native bootstrap attempts.
205+
new native bootstrap and standalone relay wake-up attempts.
169206
- **Disconnect and disable automatic setup** revokes the pairing immediately,
170207
detaches debugger sessions, and persists the opt-out.
171208
- **Use local OpenClaw** clears the opt-out and retries the native host.
@@ -233,8 +270,10 @@ Manual pairing remains useful on Windows and for recovery. Treat the complete
233270
pairing string as a password.
234271

235272
Without `--gateway-url`, this command retains the host-local `/extension` relay
236-
for standalone manual pairing. It does not wake Browser control; the selected
237-
profile relay must already be running before the extension connects.
273+
for standalone manual pairing. It does not wake Browser control. With native
274+
wake-up support installed and automatic local setup enabled, the extension can
275+
start that relay on reconnect without a local Gateway. Otherwise, the relay
276+
must already be running, for example through Browser control or a browser node.
238277

239278
For a laptop that has Chrome but does not run OpenClaw or a browser node, pair
240279
directly to a remote Gateway:
@@ -330,20 +369,28 @@ The extension requests only:
330369
- `tabs` and `tabGroups`: discover tabs and enforce access mode;
331370
- `storage`: persist pairing, access mode, session pauses, and bootstrap opt-out;
332371
- `alarms`: wake the MV3 worker for relay/bootstrap retries;
333-
- `nativeMessaging`: request one local bootstrap pairing.
372+
- `nativeMessaging`: request a local bootstrap pairing or wake its configured relay.
334373

335374
It does not request `activeTab`, `contextMenus`, `scripting`, or `sidePanel`.
336375

337376
## Native bootstrap security
338377

339-
The native host is `ai.openclaw.browser_bootstrap`. Each
340-
`chrome.runtime.sendNativeMessage` call starts one process, reads one request,
341-
writes one response, and exits.
378+
The native host is `ai.openclaw.browser_bootstrap`. The extension opens a
379+
`chrome.runtime.connectNative` port for one request, validates the response,
380+
then disconnects. The host writes one response and exits; a spawned standalone
381+
relay outlives this short-lived native connection.
342382

343383
The request uses a versioned, length-prefixed JSON frame with a fresh 16-byte
344384
nonce. The host caps input at 4 KiB, requires fatal UTF-8 decoding and exact
345385
fields, verifies the caller origin against the exact installed manifest, and
346-
returns only a locally generated pairing or a bounded non-secret failure code.
386+
returns only a locally generated pairing, a relay status, or a bounded
387+
non-secret failure code. The bootstrap request remains exactly
388+
`{v:1, op:"bootstrap", nonce}`. Relay wake-up uses
389+
`{v:1, op:"ensure_relay", nonce, relayPort}` with a required integer port from
390+
1 through 65535. Missing, duplicate, malformed, or extra fields are rejected.
391+
After manifest and caller validation, the host checks the requested port
392+
against current extension profiles before probing or spawning. No request can
393+
supply a host, executable path, or credential to the launcher.
347394
The response is below Chrome's 1 MiB native-message limit. Pairing keys never
348395
appear in launcher arguments, manifests, status JSON, or diagnostics.
349396

@@ -370,7 +417,10 @@ manifest has no `key`; only these development IDs depend on approved
370417
OpenClaw-owned realpaths.
371418

372419
The relay itself uses connection-bound HMAC proofs. The persistent per-host key
373-
is not sent in a URL, header, WebSocket subprotocol, or application frame.
420+
is not sent in a URL, header, WebSocket subprotocol, or application frame during
421+
v2 authentication. On POSIX hosts, each key read rejects foreign-owned and
422+
non-regular files and tightens an owned group/other-accessible file to `0600`;
423+
if tightening fails, the key is refused. Windows uses its existing ACL policy.
374424

375425
## Troubleshooting
376426

@@ -399,10 +449,12 @@ openclaw doctor
399449
OpenClaw**.
400450
- **Manual setup required:** use Settings for the advanced pairing flow. This
401451
is expected on Windows and direct extension-only remote Gateway setups.
402-
- **Relay unavailable:** confirm `openclaw gateway run` or the managed Gateway
403-
service is running for local setup, or confirm the browser node is running
404-
for browser-node setup. Then run browser doctor. No separate browser prewarm
405-
should be necessary.
452+
- **Relay unavailable:** for `/browser/extension` pairings, confirm the target
453+
Gateway is running. For direct loopback `/extension` pairings, check native
454+
host registration, wake-up support in the extension build, automatic setup,
455+
and that the paired port still belongs to an extension profile. Allow for the
456+
one-minute wake-up throttle, then run browser doctor. No local Gateway is
457+
required for the standalone path.
406458

407459
See [Browser](/tools/browser) for the full profile model and the managed
408460
`openclaw` and Chrome MCP `user` profiles.

‎extensions/browser/chrome-extension/background.js‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import { openAuthenticatedRelaySocket } from "./modules/relay-connection.js";
1717
import {
1818
ACCESS_MODE_SELECTED,
1919
createPairingConfigStore,
20-
isDirectLoopbackRelayUrl,
20+
directLoopbackRelayPort,
2121
reconnectDelayMs,
2222
toRelayTabInfo,
2323
} from "./modules/relay-core.js";
@@ -394,7 +394,7 @@ async function connectRelay(isConnectionAllowed = () => true) {
394394
return;
395395
}
396396
closeRelaySocket();
397-
maybeEnsureRelayDaemon(relayUrl);
397+
void maybeEnsureRelayDaemon(relayUrl, connectionIsCurrent).catch(() => {});
398398
setBadge("connecting");
399399
let ws;
400400
const owner = relayDebugger.createOwner(
@@ -506,16 +506,22 @@ function handleRelayOpeningDeadline() {
506506
* host (rate-limited) to spawn the standalone relay daemon so the extension
507507
* has something to connect to without a running Gateway.
508508
*/
509-
function maybeEnsureRelayDaemon(relayUrl) {
510-
if (reconnectAttempt === 0 || !isDirectLoopbackRelayUrl(relayUrl)) {
509+
async function maybeEnsureRelayDaemon(relayUrl, connectionIsCurrent) {
510+
const relayPort = directLoopbackRelayPort(relayUrl);
511+
if (reconnectAttempt === 0 || relayPort === null) {
512+
return;
513+
}
514+
const { disabled } = await nativeBootstrap.status();
515+
// Opt-out or pair revocation can win the storage read above.
516+
if (disabled || retiredCopilotCustodyBlocked || !connectionIsCurrent()) {
511517
return;
512518
}
513519
const now = Date.now();
514520
if (now - lastRelayEnsureAtMs < RELAY_ENSURE_MIN_INTERVAL_MS) {
515521
return;
516522
}
517523
lastRelayEnsureAtMs = now;
518-
void requestRelayEnsure(chrome).catch(() => {});
524+
await requestRelayEnsure(relayPort, chrome);
519525
}
520526

521527
function scheduleReconnect() {

‎extensions/browser/chrome-extension/background.test.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -422,3 +422,62 @@ describe("relay pairing and authentication", () => {
422422
expect(harness.storageValues).not.toHaveProperty("relayUrl");
423423
});
424424
});
425+
426+
describe("standalone relay wake-up", () => {
427+
beforeEach(() => {
428+
vi.resetModules();
429+
vi.useFakeTimers();
430+
vi.setSystemTime(100_000);
431+
});
432+
433+
afterEach(async () => {
434+
await cleanupBackgroundHarnesses();
435+
vi.useRealTimers();
436+
vi.unstubAllGlobals();
437+
});
438+
439+
it.each([18798, 20123])(
440+
"wakes the paired port %i on reconnect, at most once per minute",
441+
async (relayPort) => {
442+
const harness = await loadBackground({
443+
storedConfig: { relayUrl: `ws://127.0.0.1:${relayPort}/extension`, token: TEST_RELAY_KEY },
444+
nativeMessage: async (request) => ({
445+
v: 1,
446+
ok: true,
447+
nonce: (request as { nonce: string }).nonce,
448+
relay: "spawned",
449+
}),
450+
});
451+
expect(harness.sendNativeMessage).not.toHaveBeenCalled();
452+
harness.relaySockets.at(-1)?.close();
453+
await vi.advanceTimersByTimeAsync(1000);
454+
expect(harness.sendNativeMessage).toHaveBeenCalledExactlyOnceWith(
455+
"ai.openclaw.browser_bootstrap",
456+
{ v: 1, op: "ensure_relay", nonce: expect.any(String), relayPort },
457+
);
458+
harness.relaySockets.at(-1)?.close();
459+
await vi.advanceTimersByTimeAsync(2000);
460+
expect(harness.relaySockets).toHaveLength(3);
461+
expect(harness.sendNativeMessage).toHaveBeenCalledOnce();
462+
vi.setSystemTime(Date.now() + 60_000);
463+
harness.relaySockets.at(-1)?.close();
464+
await vi.advanceTimersByTimeAsync(4000);
465+
expect(harness.sendNativeMessage).toHaveBeenCalledTimes(2);
466+
},
467+
);
468+
469+
it.each([
470+
["local Gateway", "ws://127.0.0.1:18789/browser/extension", false],
471+
["remote Gateway", "wss://gateway.example.com/browser/extension", false],
472+
["secure loopback", "wss://localhost:18798/extension", false],
473+
["automatic setup opt-out", "ws://127.0.0.1:18798/extension", true],
474+
])("does not wake a daemon for %s", async (_label, relayUrl, nativeBootstrapDisabled) => {
475+
const harness = await loadBackground({
476+
storedConfig: { relayUrl, token: TEST_RELAY_KEY, nativeBootstrapDisabled },
477+
});
478+
harness.relaySockets.at(-1)?.close();
479+
await vi.advanceTimersByTimeAsync(1000);
480+
expect(harness.relaySockets).toHaveLength(2);
481+
expect(harness.sendNativeMessage).not.toHaveBeenCalled();
482+
});
483+
});

‎extensions/browser/chrome-extension/modules/native-bootstrap.d.ts‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -52,12 +52,15 @@ type RetiredCopilotStorage = {
5252
};
5353
};
5454

55-
export function requestRelayEnsure(chromeApi?: {
56-
runtime: {
57-
connectNative(name: string): NativeMessagePort;
58-
lastError?: { message?: string };
59-
};
60-
}): Promise<{ status: "spawned" | "running" | "skipped" | "unavailable" }>;
55+
export function requestRelayEnsure(
56+
relayPort: number,
57+
chromeApi?: {
58+
runtime: {
59+
connectNative(name: string): NativeMessagePort;
60+
lastError?: { message?: string };
61+
};
62+
},
63+
): Promise<{ status: "spawned" | "running" | "skipped" | "unavailable" }>;
6164

6265
export function prepareRetiredCopilotState(
6366
chromeApi?: RetiredCopilotStorage,

‎extensions/browser/chrome-extension/modules/native-bootstrap.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,11 +93,11 @@ function sendNativeBootstrap(chromeApi, request) {
9393
const RELAY_ENSURE_STATUSES = new Set(["spawned", "running", "skipped"]);
9494

9595
/** Ask the native host to start the standalone relay daemon when nothing serves the relay port. */
96-
export async function requestRelayEnsure(chromeApi = chrome) {
96+
export async function requestRelayEnsure(relayPort, chromeApi = chrome) {
9797
const nonce = randomRelayBase64Url(crypto, 16);
9898
let response;
9999
try {
100-
response = await sendNativeBootstrap(chromeApi, { v: 1, op: "ensure_relay", nonce });
100+
response = await sendNativeBootstrap(chromeApi, { v: 1, op: "ensure_relay", nonce, relayPort });
101101
} catch {
102102
return { status: "unavailable" };
103103
}

‎extensions/browser/chrome-extension/modules/native-bootstrap.test.ts‎

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -420,13 +420,16 @@ function ensureChromeApi(script: EnsurePortScript | "disconnect") {
420420

421421
describe("requestRelayEnsure", () => {
422422
it("returns the relay status when the native host answers with the echoed nonce", async () => {
423-
const chromeApi = ensureChromeApi((request) => ({
424-
v: 1,
425-
ok: true,
426-
nonce: request.nonce,
427-
relay: "spawned",
428-
}));
429-
await expect(requestRelayEnsure(chromeApi)).resolves.toEqual({ status: "spawned" });
423+
const chromeApi = ensureChromeApi((request) => {
424+
expect(request).toEqual({
425+
v: 1,
426+
op: "ensure_relay",
427+
nonce: expect.any(String),
428+
relayPort: 20123,
429+
});
430+
return { v: 1, ok: true, nonce: request.nonce, relay: "spawned" };
431+
});
432+
await expect(requestRelayEnsure(20123, chromeApi)).resolves.toEqual({ status: "spawned" });
430433
});
431434

432435
it("treats a nonce mismatch as unavailable", async () => {
@@ -436,11 +439,11 @@ describe("requestRelayEnsure", () => {
436439
nonce: "AAAAAAAAAAAAAAAAAAAAAA",
437440
relay: "spawned",
438441
}));
439-
await expect(requestRelayEnsure(chromeApi)).resolves.toEqual({ status: "unavailable" });
442+
await expect(requestRelayEnsure(20123, chromeApi)).resolves.toEqual({ status: "unavailable" });
440443
});
441444

442445
it("treats a missing native host as unavailable", async () => {
443-
await expect(requestRelayEnsure(ensureChromeApi("disconnect"))).resolves.toEqual({
446+
await expect(requestRelayEnsure(20123, ensureChromeApi("disconnect"))).resolves.toEqual({
444447
status: "unavailable",
445448
});
446449
});

‎extensions/browser/chrome-extension/modules/relay-core.d.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ export function createPairingConfigStore(storage: {
3535

3636
export function buildRelayWsProtocols(): string[];
3737

38-
export function isDirectLoopbackRelayUrl(raw: unknown): boolean;
38+
export function directLoopbackRelayPort(raw: unknown): number | null;
3939

4040
export function reconnectDelayMs(attempt: number): number;
4141

‎extensions/browser/chrome-extension/modules/relay-core.js‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,15 +51,26 @@ function isAllowedWebSocketUrl(url) {
5151
return url.protocol === "wss:" || (url.protocol === "ws:" && isLoopbackHost(url.hostname));
5252
}
5353

54-
/** True for a loopback ws:// relay URL on the direct /extension path — the URL the standalone relay daemon serves. */
55-
export function isDirectLoopbackRelayUrl(raw) {
54+
/** Wake-up carries only a port; match the relay server's 127.0.0.1 bind address. */
55+
export function directLoopbackRelayPort(raw) {
5656
let url;
5757
try {
5858
url = new URL(raw);
5959
} catch {
60-
return false;
60+
return null;
6161
}
62-
return url.protocol === "ws:" && isLoopbackHost(url.hostname) && url.pathname === "/extension";
62+
const port = Number(url.port || 80);
63+
return url.protocol === "ws:" &&
64+
url.hostname === "127.0.0.1" &&
65+
url.pathname === "/extension" &&
66+
port > 0 &&
67+
!url.username &&
68+
!url.password &&
69+
!url.hash &&
70+
normalizeRelayQuery(url) &&
71+
url.toString() === raw
72+
? port
73+
: null;
6374
}
6475

6576
function parseGatewayHint(raw) {

0 commit comments

Comments
 (0)