Skip to content

Commit 75bcc5c

Browse files
authored
fix(ui): keep Control UI device identity working on plain-HTTP origins (#124724)
* fix(ui): keep Control UI device identity working on plain-HTTP origins @noble/ed25519 defaults its SHA-512 provider to crypto.subtle, which browsers gate to secure contexts, so device identity silently vanished on http:// LAN dashboards and connects fell back to shared-credential auth with no pairing. Wire a lazy pure-JS @noble/hashes fallback for SHA-512 and the fingerprint SHA-256, and drop the isSecureContext gate in the connect path. Secure contexts keep the platform digests and pay no startup bytes: the fallback loads as its own lazy chunk, kept out of the gateway-runtime startup chunk on purpose. * test(ui): cover device identity minting and signing without crypto.subtle New jsdom regression suite fails on pre-fix code (subtle-less crypto stub with getRandomValues, which real insecure contexts keep). Rewrites the gateway connect tests that previously asserted the device-less insecure fallback: an insecure context now attaches a device identity. * docs(web): plain-HTTP dashboards now pair with a device identity The signing key never crosses the wire, so HTTP+pairing is strictly stronger than the old HTTP token-only fallback; HTTPS (Tailscale Serve) stays the recommendation for transport privacy. * fix(ui): drop unnecessary boolean literal compare in secure-context timing meta * test(ui): declare device.id on the connect-frame test shape * test(ui): split the subtle-less scope-upgrade e2e into the two real invariants Without crypto.subtle the browser can now sign, so the banner offers the explicit admin upgrade; manual-only guidance is reserved for browsers that cannot mint an identity at all (no WebCrypto RNG). Also corrects the connect-path comment: blocked storage yields an ephemeral identity, only a failed mint degrades device-less. * fix(ui): address review findings on the HTTP device-identity path - Storage-blocked pages keep one stable in-memory identity per page lifetime instead of minting a fresh unpaired key on every reconnect, and a write-rejecting store no longer fails the mint (regression tests bite pre-fix). - Connect timing now reports the real browser secure-context fact via a shared browserSecureContext() helper instead of inferring it from device-identity presence. - Docs state the accepted trusted-proxy contract: browsers attach a device identity on every origin, so first connects follow the standard pairing flow (deviceAutoApprove or a one-time approval); device-less admission remains only for browsers that cannot mint an identity. * refactor(ui): trim the connect-path additions under the max-lines cap
1 parent 22dd3d4 commit 75bcc5c

11 files changed

Lines changed: 211 additions & 43 deletions

‎docs/gateway/security/index.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -688,11 +688,11 @@ Trusted proxy headers do not make node device pairing automatically trusted - `g
688688

689689
### Control UI over HTTP
690690

691-
The Control UI needs a secure context (HTTPS or localhost) to generate device identity.
691+
The Control UI generates device identity with pure-JS Ed25519, so pairing works on any origin, including plain HTTP.
692692

693-
- Token/password auth does not replace browser device identity over remote plain HTTP. Use HTTPS (for example, Tailscale Serve) or open the UI on `127.0.0.1` from the Gateway host.
693+
- Token/password auth does not replace browser device identity: HTTP browsers still pair with a signed device key, which never crosses the wire. Prefer HTTPS (for example, Tailscale Serve) — plaintext transport still exposes the page and the shared secret to on-path attackers.
694694
- `gateway.controlUi.dangerouslyDisableDeviceAuth`: retired break-glass input, now fully inert. Control UI browsers pair through the normal device flow; `openclaw doctor --fix` removes the legacy key.
695-
- Separately, successful `gateway.auth.mode: "trusted-proxy"` authentication can admit **operator** Control UI sessions without device identity. This does not extend to node-role Control UI sessions.
695+
- Separately, successful `gateway.auth.mode: "trusted-proxy"` authentication can admit **operator** Control UI sessions without device identity when the browser cannot supply one. Browsers that can mint an identity (any origin, including plain HTTP) follow the normal pairing flow instead — automatic with `deviceAutoApprove`, otherwise a one-time approval. This does not extend to node-role Control UI sessions.
696696

697697
### Insecure/dangerous flags
698698

‎docs/gateway/trusted-proxy-auth.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -203,12 +203,12 @@ Enabling this option delegates new browser device enrollment entirely to the rev
203203

204204
## Control UI pairing behavior
205205

206-
When `gateway.auth.mode = "trusted-proxy"` is active and the request passes trusted-proxy checks, Control UI WebSocket sessions can connect without device pairing identity.
206+
Browsers attach a device identity on every origin, including plain HTTP, so first connects follow the standard pairing flow: automatic approval when [`deviceAutoApprove`](#automatic-device-approval) is enabled, otherwise a one-time approval on the Gateway host. When `gateway.auth.mode = "trusted-proxy"` is active and the request passes trusted-proxy checks, only Control UI sessions from browsers that cannot supply a device identity at all are admitted device-less.
207207

208208
Scope implications:
209209

210210
- Device-less Control UI WebSocket sessions cannot self-declare permissions. OpenClaw clears their requested scope list to `[]`, then applies any matching server-side `identityScopes` grant after proxy identity verification.
211-
- If methods fail with `missing scope` after a successful WebSocket connect, use HTTPS so the browser can generate device identity and complete pairing. See [Control UI insecure HTTP](/web/control-ui#insecure-http).
211+
- If methods fail with `missing scope` after a successful WebSocket connect, reload so the browser pairs its device identity, or approve the pending device request. See [Control UI insecure HTTP](/web/control-ui#insecure-http).
212212

213213
Reverse-proxy scope capping: if your proxy sends `x-openclaw-scopes` on the Control UI WebSocket upgrade request, OpenClaw caps device enrollment or upgrade requests and the final union of device-authorized and identity-granted session scopes. This header does not grant scopes; it only narrows authority. When `deviceAutoApprove.enabled` is true, the cap also limits the persistent device grant written by [automatic device approval](#automatic-device-approval).
214214

@@ -537,7 +537,7 @@ Separate, non-trusted-proxy-specific findings also apply whenever Control UI is
537537

538538
Fix:
539539

540-
- For Control UI, use HTTPS so the browser can generate device identity and complete pairing.
540+
- For Control UI, reload the dashboard so the browser generates device identity and completes pairing (works over HTTP too).
541541
- For custom automation, use device identity/pairing, the reserved direct-local `gateway-client` backend helper path, or [admin HTTP RPC](/plugins/admin-http-rpc).
542542
- Do not add the retired `gateway.controlUi.dangerouslyDisableDeviceAuth` key to current config; it is ignored and `openclaw doctor --fix` removes it.
543543

‎docs/web/control-ui.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -661,13 +661,15 @@ Tokenless Serve auth assumes the gateway host is trusted. If untrusted local cod
661661

662662
## Insecure HTTP
663663

664-
If you open the dashboard over plain HTTP (`http://<lan-ip>` or `http://<tailscale-ip>`), the browser runs in a **non-secure context** and blocks WebCrypto. OpenClaw rejects token/password Control UI connections without device identity; a shared secret cannot replace browser identity.
664+
Opening the dashboard over plain HTTP (`http://<lan-ip>` or `http://<tailscale-ip>`) works: device identity is generated and signed with pure-JS Ed25519, so pairing does not depend on WebCrypto or a secure context. The signing key never leaves the browser, which makes it the one credential a plaintext transport cannot leak — unlike the shared token, which any on-path observer of an HTTP connection can read.
665+
666+
Plain HTTP remains a downgraded transport: an active attacker on the path can modify the page and capture anything in it. Prefer HTTPS wherever possible — Tailscale Serve gives you a real certificate with no configuration — and treat HTTP as a LAN-only convenience. Browsers also withhold secure-context features (for example passkeys) on HTTP, and Chrome's Local Network Access rules increasingly restrict plaintext local requests.
665667

666668
The supported device-less exception is successful operator Control UI auth
667669
through `gateway.auth.mode: "trusted-proxy"`. There is no persistent config
668670
switch that disables device identity.
669671

670-
**Recommended fix:** use HTTPS (Tailscale Serve) or open the UI locally at `https://<magicdns>/` (Serve) or `http://127.0.0.1:18789/` (on the gateway host).
672+
**Recommended setup:** HTTPS via `https://<magicdns>/` (Tailscale Serve) or the UI locally at `http://127.0.0.1:18789/` (on the gateway host).
671673

672674
<AccordionGroup>
673675
<Accordion title="Trusted-proxy note">

‎pnpm-lock.yaml‎

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎ui/config/control-ui-chunking.ts‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -59,11 +59,9 @@ export function controlUiStableChunkName(id: string): string | undefined {
5959
return "config-runtime";
6060
}
6161

62-
if (
63-
moduleIdIncludesPackage(id, "@noble/ed25519") ||
64-
moduleIdIncludesPackage(id, "@noble/hashes") ||
65-
moduleIdIncludesPackage(id, "ipaddr.js")
66-
) {
62+
// @noble/hashes stays out of this startup chunk deliberately: it is only
63+
// dynamically imported as the insecure-context fallback digest provider.
64+
if (moduleIdIncludesPackage(id, "@noble/ed25519") || moduleIdIncludesPackage(id, "ipaddr.js")) {
6765
return "gateway-runtime";
6866
}
6967

‎ui/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
"@modelcontextprotocol/ext-apps": "1.7.5",
2222
"@modelcontextprotocol/sdk": "1.30.0",
2323
"@noble/ed25519": "3.1.0",
24+
"@noble/hashes": "2.2.0",
2425
"@novnc/novnc": "1.7.0",
2526
"@openclaw/gateway-client": "workspace:*",
2627
"@openclaw/gateway-protocol": "workspace:*",

‎ui/src/api/gateway.node.test.ts‎

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,7 @@ type ConnectFrame = {
168168
caps?: string[];
169169
scopes?: string[];
170170
device?: {
171+
id?: string;
171172
signedAt?: number;
172173
};
173174
};
@@ -312,8 +313,11 @@ function getLatestWebSocket(): MockWebSocket {
312313
}
313314

314315
function stubInsecureCrypto() {
316+
// Real insecure contexts keep randomUUID/getRandomValues; only crypto.subtle
317+
// is gated to secure contexts.
315318
vi.stubGlobal("crypto", {
316319
randomUUID: () => "req-insecure",
320+
getRandomValues: (array: Uint8Array) => array.fill(7),
317321
});
318322
}
319323

@@ -1038,7 +1042,9 @@ describe("GatewayBrowserClient", () => {
10381042
phase: "hello",
10391043
hasChallenge: true,
10401044
usedFallback: false,
1041-
secureContext: true,
1045+
// The Node test host has no window, so the reported browser secure-context
1046+
// fact is false even though a device identity is present.
1047+
secureContext: false,
10421048
hasDeviceIdentity: true,
10431049
hasDevice: true,
10441050
hasAuthToken: true,
@@ -1423,7 +1429,7 @@ describe("GatewayBrowserClient", () => {
14231429
client.stop();
14241430
});
14251431

1426-
it("uses a Gateway-owned recovery scope without browser crypto or client credentials", async () => {
1432+
it("uses a Gateway-owned recovery scope without shared credentials on an insecure context", async () => {
14271433
localStorage.clear();
14281434
stubInsecureCrypto();
14291435
const onRecoveryScopeChange = vi.fn();
@@ -1450,7 +1456,8 @@ describe("GatewayBrowserClient", () => {
14501456

14511457
await vi.waitFor(() => expect(onRecoveryScopeChange).toHaveBeenCalledOnce());
14521458
expect(connectFrame.params?.auth).toBeUndefined();
1453-
expect(connectFrame.params?.device).toBeUndefined();
1459+
// Pure-JS signing keeps device identity available even without crypto.subtle.
1460+
expect(connectFrame.params?.device?.id).toBe("device-1");
14541461
expect(client.recoveryScope).toBe("gateway-recovery-scope");
14551462
expect(client.recoveryScopeReady).toBe(true);
14561463
client.stop();
@@ -1625,7 +1632,7 @@ describe("GatewayBrowserClient", () => {
16251632
});
16261633
});
16271634

1628-
it("sends explicit shared token on insecure first connect without cached device fallback", async () => {
1635+
it("attaches device identity alongside an explicit shared token on an insecure context", async () => {
16291636
stubInsecureCrypto();
16301637
const client = new GatewayBrowserClient({
16311638
url: "ws://gateway.example:18789",
@@ -1641,11 +1648,11 @@ describe("GatewayBrowserClient", () => {
16411648
password: undefined,
16421649
deviceToken: undefined,
16431650
});
1644-
expect(loadOrCreateDeviceIdentityMock).not.toHaveBeenCalled();
1645-
expect(signDevicePayloadMock).not.toHaveBeenCalled();
1651+
expect(connectFrame.params?.device?.id).toBe("device-1");
1652+
expect(signDevicePayloadMock).toHaveBeenCalled();
16461653
});
16471654

1648-
it("sends explicit shared password on insecure first connect without cached device fallback", async () => {
1655+
it("attaches device identity alongside an explicit shared password on an insecure context", async () => {
16491656
stubInsecureCrypto();
16501657
const client = new GatewayBrowserClient({
16511658
url: "ws://gateway.example:18789",
@@ -1661,8 +1668,8 @@ describe("GatewayBrowserClient", () => {
16611668
password: "shared-password", // pragma: allowlist secret
16621669
deviceToken: undefined,
16631670
});
1664-
expect(loadOrCreateDeviceIdentityMock).not.toHaveBeenCalled();
1665-
expect(signDevicePayloadMock).not.toHaveBeenCalled();
1671+
expect(connectFrame.params?.device?.id).toBe("device-1");
1672+
expect(signDevicePayloadMock).toHaveBeenCalled();
16661673
});
16671674

16681675
it("uses cached device tokens only when no explicit shared auth is provided", async () => {

‎ui/src/api/gateway.ts‎

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,11 @@ export class GatewayRequestError extends GatewayProtocolRequestError {
7272
}
7373
}
7474

75+
function browserSecureContext(): boolean {
76+
const win = typeof window !== "undefined" ? window : undefined;
77+
return win?.isSecureContext === true;
78+
}
79+
7580
function isLoopbackIPv4Host(host: string): boolean {
7681
const octets = host.split(".");
7782
return (
@@ -399,7 +404,7 @@ export class GatewayBrowserClient {
399404

400405
private connectPlanTimingPayload(plan: ConnectPlan): Partial<GatewayConnectTiming> {
401406
return {
402-
secureContext: Boolean(plan.deviceIdentity),
407+
secureContext: browserSecureContext(),
403408
hasDeviceIdentity: Boolean(plan.deviceIdentity),
404409
hasDevice: Boolean(plan.params.device),
405410
hasAuthToken: Boolean(plan.selectedAuth.authToken),
@@ -429,25 +434,20 @@ export class GatewayBrowserClient {
429434
const explicitGatewayToken = this.opts.token?.trim() || undefined;
430435
const explicitPassword = this.opts.password?.trim() || undefined;
431436

432-
// crypto.subtle is only available in secure contexts (HTTPS, localhost).
433-
// Token/password auth cannot replace browser device identity over plain HTTP.
434-
const isSecureContext = typeof crypto !== "undefined" && Boolean(crypto.subtle);
435-
let deviceIdentity: Awaited<ReturnType<typeof loadOrCreateDeviceIdentity>> | null = null;
437+
// Pure-JS Ed25519 signing keeps device identity working on any origin,
438+
// including plain-HTTP dashboards without crypto.subtle; only a failed
439+
// mint (no WebCrypto RNG) degrades to a device-less connect.
436440
let selectedAuth: GatewayConnectAuthSelection = {
437441
authToken: explicitGatewayToken,
438442
authPassword: explicitPassword,
439443
};
440-
441-
if (isSecureContext) {
442-
deviceIdentity = await loadOrCreateDeviceIdentity();
443-
this.client.recordTiming("device-identity-ready", generation, undefined, {
444-
secureContext: true,
445-
hasDeviceIdentity: true,
446-
});
447-
selectedAuth = this.selectConnectAuth({
448-
role,
449-
deviceId: deviceIdentity.deviceId,
450-
});
444+
const deviceIdentity = await loadOrCreateDeviceIdentity().catch(() => null);
445+
this.client.recordTiming("device-identity-ready", generation, undefined, {
446+
secureContext: browserSecureContext(),
447+
hasDeviceIdentity: deviceIdentity !== null,
448+
});
449+
if (deviceIdentity) {
450+
selectedAuth = this.selectConnectAuth({ role, deviceId: deviceIdentity.deviceId });
451451
}
452452
const scopes = resolveGatewayConnectScopes({
453453
requestedScopes: selectedAuth.authBootstrapToken

‎ui/src/e2e/device-scope-upgrade.e2e.test.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -413,7 +413,7 @@ describeControlUiE2e("Control UI live device scope upgrade", () => {
413413
}
414414
});
415415

416-
it("shows manual repair guidance without a signed browser device", async () => {
416+
it("offers the admin upgrade without crypto.subtle", async () => {
417417
const context = await createContext();
418418
const page = await context.newPage();
419419
await page.addInitScript(() => {
@@ -422,6 +422,35 @@ describeControlUiE2e("Control UI live device scope upgrade", () => {
422422
value: undefined,
423423
});
424424
});
425+
const gateway = await installMockGateway(page, {
426+
operatorScopes: LIMITED_SCOPES,
427+
methodResponses: {
428+
"device.scopes.requestUpgrade": { requestId: "upgrade-insecure" },
429+
},
430+
});
431+
432+
await page.goto(`${server.baseUrl}chat`);
433+
// Pure-JS Ed25519 signs the device connect on insecure contexts, so the
434+
// explicit upgrade path stays available instead of manual-only guidance.
435+
await page.getByRole("button", { name: "Request admin" }).waitFor();
436+
expect(await gateway.getRequests("device.scopes.requestUpgrade")).toHaveLength(0);
437+
});
438+
439+
it("shows manual repair guidance when the browser cannot mint a device identity", async () => {
440+
const context = await createContext();
441+
const page = await context.newPage();
442+
await page.addInitScript(() => {
443+
// Without a WebCrypto RNG the identity mint fails and the client
444+
// degrades to a device-less connect that cannot sign upgrade requests.
445+
Object.defineProperty(globalThis.crypto, "subtle", {
446+
configurable: true,
447+
value: undefined,
448+
});
449+
Object.defineProperty(globalThis.crypto, "getRandomValues", {
450+
configurable: true,
451+
value: undefined,
452+
});
453+
});
425454
const gateway = await installMockGateway(page, { operatorScopes: LIMITED_SCOPES });
426455

427456
await page.goto(`${server.baseUrl}chat`);
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
/* @vitest-environment jsdom */
2+
// Plain-HTTP origins have no crypto.subtle; device identity must still mint,
3+
// fingerprint, and sign with the pure-JS paths so pairing works everywhere.
4+
import { hashes, verifyAsync } from "@noble/ed25519";
5+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
6+
import { createStorageMock } from "../../test-helpers/storage.ts";
7+
import { loadOrCreateDeviceIdentity, signDevicePayload } from "./index.ts";
8+
9+
function base64UrlDecode(value: string): Uint8Array {
10+
const normalized = value.replaceAll("-", "+").replaceAll("_", "/");
11+
const binary = atob(normalized);
12+
return Uint8Array.from(binary, (char) => char.charCodeAt(0));
13+
}
14+
15+
describe("device identity on an insecure context", () => {
16+
beforeEach(() => {
17+
vi.stubGlobal("localStorage", createStorageMock());
18+
// Real insecure contexts keep getRandomValues; only crypto.subtle is gated.
19+
vi.stubGlobal("crypto", {
20+
getRandomValues: (array: Uint8Array) => {
21+
for (let i = 0; i < array.length; i += 1) {
22+
array[i] = (i * 37 + 11) % 256;
23+
}
24+
return array;
25+
},
26+
});
27+
});
28+
29+
afterEach(() => {
30+
vi.unstubAllGlobals();
31+
});
32+
33+
it("mints, persists, and signs a device identity without crypto.subtle", async () => {
34+
expect(globalThis.crypto.subtle).toBeUndefined();
35+
36+
const identity = await loadOrCreateDeviceIdentity();
37+
expect(identity.deviceId).toMatch(/^[0-9a-f]{64}$/);
38+
39+
// The identity round-trips from storage with a stable id.
40+
const reloaded = await loadOrCreateDeviceIdentity();
41+
expect(reloaded.deviceId).toBe(identity.deviceId);
42+
43+
const payload = "insecure-context-payload";
44+
const signature = await signDevicePayload(identity.privateKey, payload);
45+
await expect(
46+
verifyAsync(
47+
base64UrlDecode(signature),
48+
new TextEncoder().encode(payload),
49+
base64UrlDecode(identity.publicKey),
50+
),
51+
).resolves.toBe(true);
52+
});
53+
54+
it("keeps one stable identity per page lifetime when storage is blocked", async () => {
55+
// The suite's default RNG stub is deterministic, which would mint identical
56+
// keys and mask churn; every draw must differ for this regression to bite.
57+
let draw = 0;
58+
vi.stubGlobal("crypto", {
59+
getRandomValues: (array: Uint8Array) => {
60+
draw += 1;
61+
for (let i = 0; i < array.length; i += 1) {
62+
array[i] = (i * 37 + draw) % 256;
63+
}
64+
return array;
65+
},
66+
});
67+
vi.stubGlobal("localStorage", undefined);
68+
vi.resetModules();
69+
const cold = await import("./index.ts");
70+
71+
const first = await cold.loadOrCreateDeviceIdentity();
72+
const second = await cold.loadOrCreateDeviceIdentity();
73+
expect(first.deviceId).toMatch(/^[0-9a-f]{64}$/);
74+
expect(second.deviceId).toBe(first.deviceId);
75+
});
76+
77+
it("still mints an identity when the store rejects writes", async () => {
78+
vi.stubGlobal("localStorage", {
79+
getItem: () => null,
80+
setItem: () => {
81+
throw new Error("quota exceeded");
82+
},
83+
});
84+
vi.resetModules();
85+
const cold = await import("./index.ts");
86+
87+
const identity = await cold.loadOrCreateDeviceIdentity();
88+
expect(identity.deviceId).toMatch(/^[0-9a-f]{64}$/);
89+
});
90+
91+
it("resolves the SHA-512 provider without crypto.subtle", async () => {
92+
expect(typeof hashes.sha512Async).toBe("function");
93+
const digest = await hashes.sha512Async?.(new Uint8Array([1, 2, 3]));
94+
expect(digest).toHaveLength(64);
95+
});
96+
});

0 commit comments

Comments
 (0)