Skip to content

Commit fd4404d

Browse files
authored
fix(dashboard): open widget links through the host instead of sandbox popups (#128125)
* fix(dashboard): open widget links through the host instead of sandbox popups Widget frames granted allow-popups/allow-popups-to-escape-sandbox to every rendered widget, including grantState "none" widgets that never reach an operator approval card. CSP has no navigate-to, so a popup bypassed the connect-src 'none' containment those widgets otherwise run under. Scripted window.open was blocked only by the document guard's open lock, which is emitted solely when blockDescendantFrames is set, so two unrelated knobs had to agree for the boundary to hold. Restore both sandbox strings and route user-clicked links through the existing ticket-bound bridge: a trusted click on a ticketed board widget's http(s) target="_blank" anchor forwards to the Control UI, which opens the tab with noopener,noreferrer. Links keep working for every rendered widget, the host owns the scheme filter instead of trusting widget-authored rel attributes, and scripted popups are impossible by construction rather than by coincidence. Also collapses the unreachable controlUiBaseUrl branch and corrects both docs pages, including the claim that links opened for every rendered widget, which was never true for MCP-App board widgets. Follow-up to #127315; refs #127314. * fix(dashboard): open widget links through the Control UI external-url owner The widget bridge opened links with a local window.open helper, which the lint:ui:no-raw-window-open boundary guard rejects. Delegate to openExternalUrlSafe(), the Control UI owner for external navigation: it applies noopener/noreferrer, detaches the opener handle, and keeps one canonical open path. The bridge keeps a narrower absolute-http(s) gate, since widget-supplied links must not reach blob: URLs that the shared external-link policy permits. * fix(dashboard): route middle-button widget links and honor canceled clicks Address ClawSweeper review on #128125. The wrapper only handled primary click, so with popup permission removed from both sandbox layers a middle-button activation silently did nothing. It also listened on capture, so a widget handler's preventDefault could not cancel the link the wrapper then opened itself. Match the Control UI activation contract in ui/src/app/native-link-routing.ts: listen for click and auxclick, gate on !defaultPrevented && !shiftKey && !altKey && (click+button 0 || auxclick+button 1), and listen on bubble so widget cancellation stays effective. A middle click now routes for any widget link, not just target=_blank, since middle-click always means new tab and leaving plain links unrouted would keep the same silent-no-op class. Move the wrapped-document test into src/canvas/wrap.test.ts: it exercises buildWidgetDocument, so it belongs with its owner, and the added assertions would otherwise push widget-tool.test.ts past the max-lines cap that AGENTS.md forbids suppressing.
1 parent 67613e7 commit fd4404d

13 files changed

Lines changed: 159 additions & 52 deletions

‎docs/tools/show-widget.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ Pinned widgets expose one ticket-bound host API. Calls that require declared cap
142142
- `openclaw.action.run(actionId, params?)` invokes an operator-granted plugin dashboard action verb through its write-scoped Gateway method.
143143
- `openclaw.cron.trigger(jobId)` runs an existing job now only when the exact `cron.trigger:<jobId>` capability was granted.
144144

145-
Links are ordinary user navigation, not a granted host capability. Rendered widgets can open user-clicked links in a new tab; use `target="_blank"` with `rel="noopener noreferrer"` so the dashboard stays open and the destination cannot retain an opener reference.
145+
User-clicked links to `http` or `https` destinations are forwarded to the Control UI host, which opens a new tab with `noopener` and `noreferrer`. Forwarding covers a primary click on a `target="_blank"` link and a middle-button click on any link, matching how links behave elsewhere in the Control UI; a widget's own `preventDefault` still cancels the click. The widget sandbox never grants popup permission, and script-initiated `window.open` does not work.
146146

147147
Network access is separate from host tools. Put exact HTTPS origins in `capabilities.netOrigins`; after approval, only those origins enter the widget's `connect-src`. Wildcards, credentials, paths, query strings, and undeclared origins remain blocked. A literal port is allowed only when it is part of the declared origin.
148148

‎docs/web/dashboard-architecture.md‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -176,14 +176,16 @@ Shared infrastructure underneath (this is where the simplification lands):
176176
`pending` on the board: a placeholder card lists them human-readably with
177177
one-tap **Allow**/**Reject**. Grants are per widget name; for `html` widgets
178178
they are byte-frozen (sha256), and changed bytes keep the grant only if the
179-
declaration shrank. User-clicked links are ordinary navigation rather than a
180-
grant capability and open in a new tab for every rendered widget.
179+
declaration shrank. Wrapper-authored board widgets forward user-clicked
180+
`http`/`https` new-tab links to the Control UI host; this ordinary navigation
181+
needs no grant and never grants iframe popup permissions.
181182
- **Authoring shim.** The document wrapper injects `window.openclaw.prompt`,
182183
`window.openclaw.state`, `window.openclaw.data`, `window.openclaw.action`,
183184
`window.openclaw.cron`, and the host-provided
184185
`window.openclaw.host.controlUiBaseUrl` as the stable author API. Dashboard
185-
calls share one view-ticket-bound request channel; size reporting and theme
186-
tokens remain separate host notifications.
186+
calls and trusted new-tab link clicks share one view-ticket-bound request
187+
channel. The host opens links with `noopener,noreferrer`; size reporting and
188+
theme tokens remain separate host notifications.
187189

188190
### Plugin capability declarations
189191

‎src/agents/sandbox-host.ts‎

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -230,14 +230,7 @@ export function buildSandboxHostProxyHtml(csp?: SandboxHostCsp): string {
230230
}
231231
const createInner = () => {
232232
const frame = document.createElement("iframe");
233-
// Nested sandbox restrictions compose with the host iframe. The inner
234-
// document must declare popup support so a granted outer widget can open
235-
// user-clicked links, while ungranted widgets remain blocked by the outer
236-
// frame's stricter sandbox.
237-
frame.setAttribute(
238-
"sandbox",
239-
"allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox",
240-
);
233+
frame.setAttribute("sandbox", "allow-scripts allow-forms");
241234
return frame;
242235
};
243236
let inner = createInner();

‎src/canvas/widget-tool.test.ts‎

Lines changed: 1 addition & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
// Core inline widget validation, byte stability, materialization, and retention.
2-
import { createHash } from "node:crypto";
1+
// Core inline widget validation, materialization, and retention.
32
import { access, mkdtemp, readFile, readdir, rm } from "node:fs/promises";
43
import { tmpdir } from "node:os";
54
import path from "node:path";
@@ -538,28 +537,6 @@ describe("show_widget", () => {
538537
});
539538
});
540539

541-
it("keeps the wrapped document bytes stable", () => {
542-
const html = buildWidgetDocument(
543-
"Status <live>",
544-
'<SvG viewBox="0 0 10 10"><circle r="4" /></SvG>',
545-
);
546-
547-
expect(Buffer.byteLength(html)).toBe(13859);
548-
expect(createHash("sha256").update(html).digest("hex")).toBe(
549-
"a3d6c52c6b19498b1041a3e2c0feac20b234f6497cf3d41c8783feba3ae47dcf",
550-
);
551-
expect(html).toContain("openclaw:widget-host-init-ack");
552-
expect(html).toContain("controlUiBaseUrl");
553-
expect(html).toContain('define(host,"controlUiBaseUrl"');
554-
expect(html).toContain("else push.call(waiting,{send,reject})");
555-
expect(html).toContain("else push.call(promptWaiting,{send,inline,reject})");
556-
expect(html).toContain("openclaw:widget-prompt-host-ready");
557-
expect(html).toContain("widget host capabilities unavailable");
558-
expect(html).toContain("widget prompt host unavailable");
559-
expect(html).toContain("openclaw:widget-chat-host");
560-
expect(html).not.toContain("widget is not hosted on a board");
561-
});
562-
563540
it("rejects empty and oversized widget code", async () => {
564541
const stateDir = await createStateDir();
565542
const tool = createShowWidgetTool({ stateDir, sessionId: "validation" });

‎src/canvas/wrap.test.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Widget document wrapper: byte stability and the host-bridge contract it emits.
2+
import { createHash } from "node:crypto";
3+
import { describe, expect, it } from "vitest";
4+
import { buildWidgetDocument } from "./wrap.js";
5+
6+
describe("buildWidgetDocument", () => {
7+
it("keeps the wrapped document bytes stable", () => {
8+
const html = buildWidgetDocument(
9+
"Status <live>",
10+
'<SvG viewBox="0 0 10 10"><circle r="4" /></SvG>',
11+
);
12+
13+
expect(Buffer.byteLength(html)).toBe(14664);
14+
expect(createHash("sha256").update(html).digest("hex")).toBe(
15+
"2ba50a2b43f51e46644b27201bed47a02ba84023e37f01763e94baf998f32386",
16+
);
17+
expect(html).toContain("openclaw:widget-host-init-ack");
18+
expect(html).toContain('request("host.open",{url})');
19+
// Widget links follow the Control UI activation contract: primary click and
20+
// middle-button auxclick, on bubble so a widget's preventDefault still wins.
21+
expect(html).toContain('listen("click",activate);listen("auxclick",activate);');
22+
expect(html).toContain('event.type==="auxclick"&&event.button===1');
23+
expect(html).toContain("event.defaultPrevented||event.shiftKey||event.altKey");
24+
expect(html).not.toContain("{capture:true}");
25+
expect(html).toContain("controlUiBaseUrl");
26+
expect(html).toContain('define(host,"controlUiBaseUrl"');
27+
expect(html).toContain("else push.call(waiting,{send,reject})");
28+
expect(html).toContain("else push.call(promptWaiting,{send,inline,reject})");
29+
expect(html).toContain("openclaw:widget-prompt-host-ready");
30+
expect(html).toContain("widget host capabilities unavailable");
31+
expect(html).toContain("widget prompt host unavailable");
32+
expect(html).toContain("openclaw:widget-chat-host");
33+
expect(html).not.toContain("widget is not hosted on a board");
34+
});
35+
});

‎src/canvas/wrap.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,12 +108,22 @@ export function buildWidgetDocument(
108108
// This bridge precedes widget code and snapshots every authority-bearing
109109
// primitive. Inline chat keeps its private prompt port; board hosting adopts
110110
// the view ticket and routes every host API over one request channel.
111+
// The activation listeners are that channel's navigation half: the frame
112+
// sandbox grants no popups, so only a trusted new-tab activation on a
113+
// ticketed board widget's http(s) anchor reaches the host. Widening the
114+
// trusted/ticketed/http(s) gates hands ungranted widgets an outbound channel
115+
// that the `connect-src` CSP in board-sandbox.ts otherwise denies. The
116+
// activation predicate mirrors ui/src/app/native-link-routing.ts so widget
117+
// links honor the same primary-click and middle-button contract; listening on
118+
// bubble rather than capture keeps a widget's own preventDefault effective.
111119
const widgetBridge =
112120
'<script>(()=>{if(!window.parent||window.parent===window||Object.prototype.hasOwnProperty.call(window,"openclaw"))return;' +
113121
"const parent=window.parent;const post=parent.postMessage.bind(parent);" +
114122
"const P=Promise;const then=P.prototype.then;const ErrorCtor=Error;" +
115123
"const stringify=String;const freeze=Object.freeze;const define=Object.defineProperty;" +
116124
"const push=Array.prototype.push;const shift=Array.prototype.shift;" +
125+
"const listen=window.addEventListener.bind(window);const path=Event.prototype.composedPath;" +
126+
"const prevent=Event.prototype.preventDefault;const test=RegExp.prototype.test;" +
117127
"const later=setTimeout.bind(window);const cancel=clearTimeout.bind(window);" +
118128
"const c=new MessageChannel();" +
119129
"const promptPost=c.port1.postMessage.bind(c.port1);" +
@@ -145,6 +155,14 @@ export function buildWidgetDocument(
145155
"catch(error){pending.delete(id);reject(error);}};" +
146156
'if(ticket)send();else if(hostInitExpired)reject(new ErrorCtor("widget host capabilities unavailable"));' +
147157
"else push.call(waiting,{send,reject});});" +
158+
"const activate=event=>{if(event.isTrusted!==true||!ticket||event.defaultPrevented||event.shiftKey||event.altKey)return;" +
159+
'const auxiliary=event.type==="auxclick"&&event.button===1;' +
160+
'if(!auxiliary&&!(event.type==="click"&&event.button===0))return;' +
161+
'for(let index=0,entries=path.call(event);index<entries.length;index++){const anchor=entries[index];if(anchor?.tagName!=="A")continue;' +
162+
'const url=anchor.href;if(!url)continue;if(!auxiliary&&anchor.target!=="_blank")return;' +
163+
"if(!test.call(/^https?:\\/\\//i,url))return;" +
164+
'prevent.call(event);then.call(request("host.open",{url}),()=>{},()=>{});return;}};' +
165+
'listen("click",activate);listen("auxclick",activate);' +
148166
"const sendPrompt=text=>{if(!act||act()!==true)return P.resolve(false);const value=stringify(text);" +
149167
'if(ticket)return request("prompt.send",{text:value});return new P((resolve,reject)=>{' +
150168
'const send=()=>{const result=request("prompt.send",{text:value});then.call(result,resolve,reject);};' +

‎src/gateway/board-sandbox.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,4 +88,16 @@ describe("board widget sandbox CSP", () => {
8888
expect(genericProxy).toContain("const blockDescendantFrames = false");
8989
expect(genericProxy).not.toContain('lock(Document.prototype,\\"createElement\\"');
9090
});
91+
92+
it("blocks scripted popups regardless of whether descendant-frame hardening is enabled", () => {
93+
const path = buildBoardWidgetSandboxPath(document("pending"));
94+
const encoded = new URL(path, "https://sandbox.example").searchParams.get("csp");
95+
const csp = decodeSandboxHostCsp(encoded);
96+
97+
expect(csp?.blockDescendantFrames).toBe(true);
98+
for (const proxy of [buildSandboxHostProxyHtml(csp), buildSandboxHostProxyHtml()]) {
99+
expect(proxy).toContain('frame.setAttribute("sandbox", "allow-scripts allow-forms")');
100+
expect(proxy).not.toContain("allow-popups");
101+
}
102+
});
91103
});

‎src/gateway/mcp-app-sandbox-http.test.ts‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -59,16 +59,13 @@ describe("MCP App sandbox HTTP origin", () => {
5959
);
6060
expect(result.end).toHaveBeenCalledWith(expect.stringContaining("document.referrer"));
6161
expect(result.end).toHaveBeenCalledWith(expect.stringContaining("sandbox-proxy-ready"));
62-
expect(result.end).toHaveBeenCalledWith(
63-
expect.stringContaining(
64-
"allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox",
65-
),
66-
);
62+
expect(result.end).toHaveBeenCalledWith(expect.stringContaining("allow-scripts allow-forms"));
6763
expect(result.end).toHaveBeenCalledWith(
6864
expect.stringContaining("openclaw:widget-bridge-port-offer"),
6965
);
7066
expect(result.end).toHaveBeenCalledWith(expect.stringContaining("widgetBridgePortOffered"));
7167
const proxyHtml = String(result.end.mock.calls.at(-1)?.[0]);
68+
expect(proxyHtml).not.toContain("allow-popups");
7269
expect(proxyHtml).toContain("const guardedHtml = guardDocument(params.html)");
7370
expect(proxyHtml).toContain("nextInner.srcdoc = guardedHtml");
7471
});

‎ui/src/components/board/board-view.test.ts‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ describe("openclaw-board-view", () => {
4141
}
4242
});
4343

44-
it("renders the shared sandbox for an empty same-origin gateway URL", async () => {
44+
it("renders an ungranted widget in the shared sandbox without popup authority", async () => {
4545
const view = await mount({
4646
context: gatewayContext(null),
4747
snapshot: snapshot({
@@ -58,9 +58,8 @@ describe("openclaw-board-view", () => {
5858

5959
const frame = view.querySelector("iframe");
6060
expect(frame?.getAttribute("src")).toContain(":18790/mcp-app-sandbox");
61-
expect(frame?.getAttribute("sandbox")).toBe(
62-
"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",
63-
);
61+
expect(frame?.getAttribute("sandbox")).toBe("allow-scripts allow-same-origin allow-forms");
62+
expect(frame?.getAttribute("sandbox")).not.toContain("allow-popups");
6463
expect(frame?.getAttribute("loading")).toBe("eager");
6564
expect(view.querySelector('[data-test-id="board-widget-error"]')).toBeNull();
6665
});

‎ui/src/components/board/board-widget-frame.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,6 @@ const TICKET_REFRESH_LEAD_MS = 15_000;
1717
const TICKET_REFRESH_MIN_DELAY_MS = 1_000;
1818
const TICKET_REFRESH_RETRY_MS = 1_000;
1919
const TICKET_REFRESH_MAX_RETRY_MS = 30_000;
20-
const WIDGET_SANDBOX =
21-
"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox";
2220

2321
function documentHidden(): boolean {
2422
return typeof document !== "undefined" && document.visibilityState === "hidden";
@@ -239,10 +237,12 @@ export class BoardWidgetFrameLifecycle {
239237
this.lastFrameUrl = src;
240238
const sandboxSrc = this.resolveSandboxFrameUrl(widget);
241239
if (sandboxSrc) {
240+
// Never grant popups: host.open handles user-clicked links so ungranted
241+
// widgets cannot escape network containment through navigation.
242242
return html`
243243
<iframe
244244
class="board-widget__frame"
245-
sandbox=${WIDGET_SANDBOX}
245+
sandbox="allow-scripts allow-same-origin allow-forms"
246246
referrerpolicy="origin"
247247
loading="eager"
248248
title=${widget.title || widget.name}

0 commit comments

Comments
 (0)