Skip to content

Commit 5350b92

Browse files
authored
fix(browser): wake extension relay through gateway (#122537)
* fix(browser): wake extension relay through gateway * fix(browser): preserve manual extension relay pairing
1 parent 08b7fcc commit 5350b92

11 files changed

Lines changed: 395 additions & 49 deletions

‎docs/cli/browser.md‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,13 +154,26 @@ openclaw browser extension cdp --json
154154
challenge/complete binding. It never prints the relay key or an authorization
155155
header by default.
156156

157+
Automatic local bootstrap connects through the local Gateway's exact
158+
`/browser/extension` route so the first authenticated extension connection
159+
starts the lazy browser-control service. Keep `openclaw gateway run` or the
160+
managed Gateway service running; no separate browser request or prewarm is
161+
needed. Local OpenClaw and mcporter calls still use the profile relay port
162+
reported by `extension pair` or `extension cdp` after that wakeup. Browser-node
163+
pairings continue to use the relay on the browser-node host, while explicit
164+
`--gateway-url` pairings remain direct-remote and manual-only.
165+
166+
The advanced manual `extension pair` command without `--gateway-url` retains
167+
the host-local `/extension` relay URL. It does not wake Browser control, so the
168+
selected profile relay must already be running before the extension connects.
169+
157170
`extension cdp --legacy-bearer` is a temporary migration escape hatch. It
158171
prints the old Bearer header with a warning only while
159172
`browser.extensionRelay.allowLegacyAuth=true`; otherwise it exits with an error
160173
without printing a credential. Use `--json` for machine output; warnings remain
161174
on stderr so stdout stays valid JSON.
162175

163-
Setup, security model, and migration steps: [Chrome extension](/tools/chrome-extension).
176+
Setup, security model, and recovery steps: [Chrome extension](/tools/chrome-extension).
164177

165178
If the extension already attempted automatic setup before the native host
166179
existed, Chromium retains that miss for the running browser process. Restart

‎docs/tools/chrome-extension.md‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,18 @@ openclaw config set browser.defaultProfile chrome
101101
Fresh automatic pairings use **All tabs**. Existing valid pairings are never
102102
overwritten, and older pairings keep their stored access mode.
103103

104+
For local setup, native bootstrap connects the extension through the local
105+
Gateway's exact `/browser/extension` route. That first authenticated connection
106+
wakes the lazy browser-control service and starts the profile's loopback relay;
107+
OpenClaw and local clients such as mcporter then use that profile relay port.
108+
Keep `openclaw gateway run` or the managed Gateway service running. A separate
109+
browser request or prewarm step is not required.
110+
111+
Browser-node setup remains different: the extension connects to the relay on
112+
the browser-node host while the node uses its configured remote Gateway. An
113+
explicit `--gateway-url` pairing connects directly to that remote Gateway and
114+
remains a manual-only flow.
115+
104116
### Choose tab access
105117

106118
- **All tabs** exposes every eligible ordinary tab in that Chrome profile,
@@ -130,6 +142,11 @@ local setup** switch.
130142
- **Use local OpenClaw** clears the opt-out and retries the native host.
131143
- Saving an explicit manual pairing also clears the opt-out.
132144

145+
Pre-release development installs that paired before local Gateway wakeup
146+
routing keep their existing pairing unchanged. In Settings, use **Disconnect
147+
and disable automatic setup**, then **Use local OpenClaw** to create the new
148+
local pairing. Released builds do not require this recovery step.
149+
133150
### Upgrades from the retired tab copilot
134151

135152
If Settings says automation is paused to protect a pre-upgrade copilot
@@ -178,6 +195,10 @@ openclaw browser extension pair
178195
Manual pairing remains useful on Windows and for recovery. Treat the complete
179196
pairing string as a password.
180197

198+
Without `--gateway-url`, this command retains the host-local `/extension` relay
199+
for standalone manual pairing. It does not wake Browser control; the selected
200+
profile relay must already be running before the extension connects.
201+
181202
For a laptop that has Chrome but does not run OpenClaw or a browser node, pair
182203
directly to a remote Gateway:
183204

@@ -270,8 +291,10 @@ openclaw doctor
270291
OpenClaw**.
271292
- **Manual setup required:** use Settings for the advanced pairing flow. This
272293
is expected on Windows and direct extension-only remote Gateway setups.
273-
- **Relay unavailable:** confirm the Gateway or browser node is running, then
274-
run browser doctor.
294+
- **Relay unavailable:** confirm `openclaw gateway run` or the managed Gateway
295+
service is running for local setup, or confirm the browser node is running
296+
for browser-node setup. Then run browser doctor. No separate browser prewarm
297+
should be necessary.
275298

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

‎extensions/browser/chrome-extension/bootstrap.chromium.test.ts‎

Lines changed: 46 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { spawnSync } from "node:child_process";
22
import fs from "node:fs/promises";
3+
import http from "node:http";
34
import os from "node:os";
45
import path from "node:path";
56
import { fileURLToPath } from "node:url";
@@ -12,8 +13,9 @@ import {
1213
stableChromeExtensionDir,
1314
} from "../src/browser/extension-install-layout.js";
1415
import { installChromeExtensionBootstrap } from "../src/browser/extension-install.js";
15-
import { startExtensionRelayServer } from "../src/browser/extension-relay/relay-server.js";
16+
import { handleGatewayExtensionUpgrade } from "../src/browser/extension-relay/gateway-relay-route.js";
1617
import { getFreePort } from "../src/browser/test-port.js";
18+
import { getBrowserControlState, stopBrowserControlService } from "../src/control-service.js";
1719
import { relayTestKey } from "./relay-key.test-support.js";
1820

1921
declare const chrome: {
@@ -146,7 +148,11 @@ describe.runIf(runE2E)("Chrome native bootstrap Chromium E2E", () => {
146148
const homeDir = path.join(root, "home");
147149
const stateDir = path.join(root, "custom-state");
148150
const configPath = path.join(root, "custom-config", "openclaw.json");
149-
const relayPort = await getFreePort();
151+
const gatewayPort = await getFreePort();
152+
let relayPort = await getFreePort();
153+
while (relayPort === gatewayPort) {
154+
relayPort = await getFreePort();
155+
}
150156
const linuxConfigHome = path.join(homeDir, ".config");
151157
const chromeRootEnv =
152158
process.platform === "linux"
@@ -166,11 +172,15 @@ describe.runIf(runE2E)("Chrome native bootstrap Chromium E2E", () => {
166172
);
167173
await fs.writeFile(
168174
configPath,
169-
`${JSON.stringify({ browser: { profiles: { e2e: { driver: "extension", cdpPort: relayPort } } } })}\n`,
175+
`${JSON.stringify({ gateway: { port: gatewayPort }, browser: { profiles: { e2e: { driver: "extension", cdpPort: relayPort } } } })}\n`,
170176
{ mode: 0o600 },
171177
);
172178
await withEnvAsync(
173-
{ OPENCLAW_STATE_DIR: stateDir, OPENCLAW_CONFIG_PATH: configPath },
179+
{
180+
OPENCLAW_STATE_DIR: stateDir,
181+
OPENCLAW_CONFIG_PATH: configPath,
182+
OPENCLAW_GATEWAY_PORT: String(gatewayPort),
183+
},
174184
async () => {
175185
const extensionSource = path.dirname(fileURLToPath(import.meta.url));
176186
const nativeHostPath = await fs.realpath(
@@ -187,12 +197,28 @@ describe.runIf(runE2E)("Chrome native bootstrap Chromium E2E", () => {
187197
...chromeRootEnv,
188198
OPENCLAW_STATE_DIR: stateDir,
189199
OPENCLAW_CONFIG_PATH: configPath,
200+
OPENCLAW_GATEWAY_PORT: String(gatewayPort),
190201
},
191202
nodePath: tsxPath,
192203
nativeHostPath,
193204
};
194-
const relay = await startExtensionRelayServer({ port: relayPort, token });
195-
cleanups.push(relay.close);
205+
const gatewayServer = http.createServer((_req, res) => {
206+
res.writeHead(426);
207+
res.end();
208+
});
209+
gatewayServer.on("upgrade", (req, socket, head) => {
210+
void handleGatewayExtensionUpgrade(req, socket, head);
211+
});
212+
await new Promise<void>((resolve) => {
213+
gatewayServer.listen(gatewayPort, "127.0.0.1", resolve);
214+
});
215+
cleanups.push(
216+
async () =>
217+
await new Promise<void>((resolve) => {
218+
gatewayServer.close(() => resolve());
219+
}),
220+
);
221+
cleanups.push(stopBrowserControlService);
196222
const browserEnv: NodeJS.ProcessEnv = {
197223
...process.env,
198224
HOME: homeDir,
@@ -291,7 +317,13 @@ describe.runIf(runE2E)("Chrome native bootstrap Chromium E2E", () => {
291317
}
292318
expect(extensionStatus).toMatchObject({ paired: true, accessMode: "all" });
293319
try {
294-
await expect.poll(() => relay.bridge.extensionConnected, { timeout: 15_000 }).toBe(true);
320+
await expect
321+
.poll(
322+
() =>
323+
getBrowserControlState()?.extensionRelays?.get("e2e")?.bridge.extensionConnected,
324+
{ timeout: 15_000 },
325+
)
326+
.toBe(true);
295327
} catch (error) {
296328
extensionStatus = await extensionPage.evaluate(
297329
async () => await chrome.runtime.sendMessage({ type: "getStatus" }),
@@ -300,6 +332,10 @@ describe.runIf(runE2E)("Chrome native bootstrap Chromium E2E", () => {
300332
cause: error,
301333
});
302334
}
335+
const relay = getBrowserControlState()?.extensionRelays?.get("e2e");
336+
if (!relay || relay.port !== relayPort) {
337+
throw new Error("Gateway wakeup did not start the configured extension relay");
338+
}
303339

304340
const registration = status.registrations.find(
305341
(entry) => relevantManifestPaths.includes(entry.manifestPath) && entry.state === "owned",
@@ -349,7 +385,9 @@ describe.runIf(runE2E)("Chrome native bootstrap Chromium E2E", () => {
349385
}
350386
if (
351387
relayUrl.hostname !== "127.0.0.1" ||
352-
relayUrl.port !== String(relayPort) ||
388+
relayUrl.port !== String(gatewayPort) ||
389+
relayUrl.pathname !== "/browser/extension" ||
390+
relayUrl.searchParams.get("gateway") !== `ws://127.0.0.1:${gatewayPort}` ||
353391
nativeResponse.pairingString.slice(fragmentAt + 1) !== token
354392
) {
355393
throw new Error("native host did not use the custom installation context");

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,8 @@ function validatePairingFields(relayUrl, token, gatewayUrl) {
155155

156156
/**
157157
* Parse a pairing string printed by `openclaw browser extension pair`.
158-
* Shape: ws://127.0.0.1:<port>/extension?gateway=<url>#<token>
158+
* Native local and direct-remote pairings use the Gateway route; local manual,
159+
* browser-node, and legacy local pairings use the host relay route.
159160
* The additive gateway hint is not a credential; old extensions safely pass
160161
* it through to the relay while new extensions remove it before connecting.
161162
*/

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -131,11 +131,11 @@ describe("persisted pairing storage", () => {
131131
},
132132
},
133133
{
134-
label: "a loopback relay with an independent Gateway hint",
134+
label: "an SSH-tunneled browser-node pairing with a loopback Gateway hint",
135135
stored: {
136136
relayUrl: "ws://127.0.0.1:18797/extension",
137137
token: RELAY_SECRET,
138-
gatewayUrl: "wss://gateway.example.com/base",
138+
gatewayUrl: "ws://127.0.0.1:19089",
139139
},
140140
},
141141
{

‎extensions/browser/native-host-entry.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,11 @@ async function main(): Promise<void> {
2626
write: (frame) => {
2727
responseFrame = frame;
2828
},
29-
buildPairing: async () => await buildBrowserExtensionPairing({ cfg: getRuntimeConfig() }),
29+
buildPairing: async () =>
30+
await buildBrowserExtensionPairing({
31+
cfg: getRuntimeConfig(),
32+
localTransport: "gateway",
33+
}),
3034
});
3135
const response = responseFrame;
3236
if (!response) {

‎extensions/browser/src/browser/extension-install.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -489,7 +489,7 @@ describe("native host registration", () => {
489489
v: 1,
490490
ok: true,
491491
nonce,
492-
pairingString: `ws://127.0.0.1:${relayPort}/extension?gateway=ws%3A%2F%2F127.0.0.1%3A18789#${token}`,
492+
pairingString: `ws://127.0.0.1:18789/browser/extension?gateway=ws%3A%2F%2F127.0.0.1%3A18789#${token}`,
493493
});
494494
},
495495
);
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
import { withEnvAsync } from "openclaw/plugin-sdk/test-env";
2+
import { describe, expect, it } from "vitest";
3+
import { relayTestKey } from "../../chrome-extension/relay-key.test-support.js";
4+
import { buildBrowserExtensionPairing } from "./extension-pairing.js";
5+
6+
const RELAY_KEY = relayTestKey(5);
7+
const ensureToken = async () => RELAY_KEY;
8+
9+
describe("buildBrowserExtensionPairing", () => {
10+
it("preserves the standalone host relay for local manual pairing compatibility", async () => {
11+
await withEnvAsync({ OPENCLAW_GATEWAY_PORT: undefined }, async () => {
12+
await expect(
13+
buildBrowserExtensionPairing({
14+
cfg: {
15+
gateway: { port: 19_089 },
16+
browser: {
17+
profiles: { chrome: { driver: "extension", cdpPort: 19_199 } },
18+
},
19+
},
20+
ensureToken,
21+
}),
22+
).resolves.toEqual({
23+
pairingString: `ws://127.0.0.1:19199/extension?gateway=ws%3A%2F%2F127.0.0.1%3A19089#${RELAY_KEY}`,
24+
relayPort: 19_199,
25+
topology: "local",
26+
});
27+
});
28+
});
29+
30+
it("routes local native bootstrap through the Gateway while retaining relay metadata", async () => {
31+
await withEnvAsync({ OPENCLAW_GATEWAY_PORT: undefined }, async () => {
32+
await expect(
33+
buildBrowserExtensionPairing({
34+
cfg: {
35+
gateway: { port: 19_089 },
36+
browser: {
37+
profiles: { chrome: { driver: "extension", cdpPort: 19_199 } },
38+
},
39+
},
40+
localTransport: "gateway",
41+
ensureToken,
42+
}),
43+
).resolves.toEqual({
44+
pairingString: `ws://127.0.0.1:19089/browser/extension?gateway=ws%3A%2F%2F127.0.0.1%3A19089#${RELAY_KEY}`,
45+
relayPort: 19_199,
46+
topology: "local",
47+
});
48+
});
49+
});
50+
51+
it.each([
52+
{
53+
label: "remote TLS Gateway",
54+
gatewayUrl: "wss://gateway.example.com:9444",
55+
encodedGateway: "wss%3A%2F%2Fgateway.example.com%3A9444",
56+
},
57+
{
58+
label: "loopback SSH tunnel to a remote Gateway",
59+
gatewayUrl: "ws://127.0.0.1:29089",
60+
encodedGateway: "ws%3A%2F%2F127.0.0.1%3A29089",
61+
},
62+
])("keeps browser-node bootstrap on the host-local relay for $label", async (testCase) => {
63+
await expect(
64+
buildBrowserExtensionPairing({
65+
cfg: {
66+
gateway: {
67+
mode: "remote",
68+
remote: { url: testCase.gatewayUrl },
69+
},
70+
browser: {
71+
profiles: { chrome: { driver: "extension", cdpPort: 19_198 } },
72+
},
73+
},
74+
ensureToken,
75+
}),
76+
).resolves.toEqual({
77+
pairingString: `ws://127.0.0.1:19198/extension?gateway=${testCase.encodedGateway}#${RELAY_KEY}`,
78+
relayPort: 19_198,
79+
topology: "browser-node",
80+
});
81+
});
82+
83+
it("keeps an explicit remote Gateway direct and manual-only", async () => {
84+
await expect(
85+
buildBrowserExtensionPairing({
86+
cfg: {
87+
browser: {
88+
profiles: { chrome: { driver: "extension", cdpPort: 19_197 } },
89+
},
90+
},
91+
gatewayUrl: "wss://gateway.example.com:9443",
92+
ensureToken,
93+
}),
94+
).resolves.toEqual({
95+
pairingString: `wss://gateway.example.com:9443/browser/extension?gateway=wss%3A%2F%2Fgateway.example.com%3A9443#${RELAY_KEY}`,
96+
relayPort: 19_197,
97+
topology: "direct-remote",
98+
});
99+
});
100+
101+
it("requires an explicit certificate hostname for local Gateway TLS", async () => {
102+
await expect(
103+
buildBrowserExtensionPairing({
104+
cfg: { gateway: { tls: { enabled: true } } },
105+
ensureToken,
106+
}),
107+
).rejects.toThrow("--gateway-url wss://<certificate-host>");
108+
});
109+
});

0 commit comments

Comments
 (0)