@botiverse/porthole 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +3 -1
  2. package/dist/bridge/bridge.d.ts +24 -2
  3. package/dist/bridge/bridge.js +102 -17
  4. package/dist/bridge/navigation.d.ts +11 -0
  5. package/dist/bridge/navigation.js +30 -0
  6. package/dist/bridge/refusal.d.ts +53 -0
  7. package/dist/bridge/refusal.js +121 -0
  8. package/dist/bridge/types.d.ts +51 -6
  9. package/dist/check/lint.js +2 -2
  10. package/dist/check/page-source.js +1 -1
  11. package/dist/check/page.js +10 -0
  12. package/dist/compile/policy.d.ts +5 -0
  13. package/dist/compile/policy.js +18 -1
  14. package/dist/config/capabilities.d.ts +30 -2
  15. package/dist/config/capabilities.js +13 -0
  16. package/dist/config/schema.d.ts +7 -0
  17. package/dist/config/validate.js +14 -3
  18. package/dist/conformance/harness/page.js +1 -0
  19. package/dist/conformance/harness-source.js +1 -1
  20. package/dist/displays/displays.d.ts +1 -1
  21. package/dist/guide/guide.js +58 -8
  22. package/dist/host/create-host.js +18 -3
  23. package/dist/host/types.d.ts +25 -1
  24. package/dist/index.d.ts +5 -3
  25. package/dist/index.js +4 -1
  26. package/dist/libraries/files.generated.d.ts +1 -0
  27. package/dist/libraries/files.generated.js +8 -0
  28. package/dist/libraries/libraries.d.ts +36 -0
  29. package/dist/libraries/libraries.js +40 -0
  30. package/dist/mcp/adapter.js +49 -5
  31. package/dist/presets/presets.d.ts +15 -0
  32. package/dist/presets/presets.js +27 -2
  33. package/dist/protocol/live-data.d.ts +27 -0
  34. package/dist/protocol/live-data.js +98 -0
  35. package/dist/protocol/mcp-apps.d.ts +15 -0
  36. package/dist/protocol/mcp-apps.js +17 -0
  37. package/dist/protocol/shell-adapter.js +49 -4
  38. package/dist/react/dialog.js +2 -0
  39. package/dist/react/frame.d.ts +30 -1
  40. package/dist/react/frame.js +63 -1
  41. package/dist/server/libraries.d.ts +7 -0
  42. package/dist/server/libraries.js +27 -0
  43. package/dist/server/server.js +2 -1
  44. package/dist/shell/runtime.d.ts +5 -1
  45. package/dist/shell/runtime.js +196 -6
  46. package/docs/ADOPTING.md +89 -3
  47. package/docs/DECISIONS.md +221 -0
  48. package/docs/DESIGN.md +28 -10
  49. package/package.json +3 -1
  50. package/src/bridge/bridge.ts +136 -16
  51. package/src/bridge/navigation.ts +34 -0
  52. package/src/bridge/refusal.ts +151 -0
  53. package/src/bridge/types.ts +57 -4
  54. package/src/check/lint.ts +2 -1
  55. package/src/check/page.ts +12 -0
  56. package/src/compile/policy.ts +19 -1
  57. package/src/config/capabilities.ts +26 -1
  58. package/src/config/schema.ts +7 -0
  59. package/src/config/validate.ts +21 -3
  60. package/src/conformance/harness/page.ts +1 -0
  61. package/src/displays/displays.ts +1 -1
  62. package/src/guide/guide.ts +71 -7
  63. package/src/host/create-host.ts +19 -3
  64. package/src/host/types.ts +23 -1
  65. package/src/index.ts +22 -0
  66. package/src/libraries/files.generated.ts +8 -0
  67. package/src/libraries/libraries.ts +64 -0
  68. package/src/mcp/adapter.ts +63 -5
  69. package/src/presets/presets.ts +46 -3
  70. package/src/protocol/live-data.ts +138 -0
  71. package/src/protocol/mcp-apps.ts +19 -0
  72. package/src/protocol/shell-adapter.ts +50 -5
  73. package/src/react/dialog.tsx +2 -0
  74. package/src/react/frame.tsx +93 -0
  75. package/src/server/libraries.ts +28 -0
  76. package/src/server/server.ts +2 -1
  77. package/src/shell/runtime.ts +196 -6
package/docs/DECISIONS.md CHANGED
@@ -2212,3 +2212,224 @@ refused, and reported as a problem, on every engine (`leak/check.spec.ts`).
2212
2212
  **Revisit when** a host needs one of them for anything but scripts, or Raft's trace of blocked
2213
2213
  loads (its follow-up) proposes more hosts, such as mirrors reachable from mainland China.
2214
2214
 
2215
+
2216
+ ## P079 · 2026-10-15 · Live widgets: no network of their own, Porthole's libraries on their origin, the host's data behind the viewer's consent, and frames that never navigate away · Accepted
2217
+
2218
+ **Decision.** Content that shows its host's data, current, read as the person viewing it (a
2219
+ dashboard tile, a kept widget) gets a preset of its own and the mechanisms it needs. 0.5.0.
2220
+ - **`presets.liveWidget(options)`**: an inline widget whose egress stays closed. Its options are
2221
+ a widget's less `egress` (a JavaScript caller passing one gets a `ConfigError`): no option opens
2222
+ its network. It declares `readData` and `subscribeData`, each gated `consent` and a rate (120 and
2223
+ 60 a minute). In domain isolation it sets `egress.libraries`. A host adds what any widget may
2224
+ have (a link, a copy button) or changes the data capabilities' gates, as for any capability.
2225
+ - **Porthole's libraries (`egress.libraries`)**: Chart.js 4.5.1 and D3 7.9.0
2226
+ (`VENDORED_LIBRARIES`), copied byte for byte from their npm packages (exact devDependencies, so
2227
+ the lockfile fixes the bytes) into a generated module (`scripts/vendor-libraries.ts`; P075: no
2228
+ file beside a module), with their licenses (MIT, ISC). `/server` serves them on every content
2229
+ origin at `/__porthole/lib/<name>@<version>/<file>` (the jsDelivr layout agents know), inside
2230
+ its reserved prefix: no ticket or cookie, `cache-control: immutable`, `nosniff`,
2231
+ `cross-origin-resource-policy: same-site`, GET and HEAD only, and nothing else under the path.
2232
+ A released path keeps its bytes; a new version is a new path beside it. The frame's CSP gets
2233
+ `script-src <content origin>/__porthole/lib/` per content origin: path-limited, so P022 holds
2234
+ (no `'self'`: nothing else served on the origin runs as a script). Domain isolation only; the
2235
+ manual gives a `<script>` line for each, and the chart topic says they are there.
2236
+ - **The `consent` gate**: the host's `consent(request)` (`HostOptions.consent`, React's
2237
+ `PortholeProvider`/`PortholeFrame` `consent`) is asked once per display before its first
2238
+ consent-gated call, the request being that call; Porthole keeps the answer for the display's life
2239
+ (`onceConsent`, across its frames); the host remembers it where it likes (per viewer, per widget).
2240
+ A no refuses every such call (`denied`) and no handler runs; no `consent` function refuses them
2241
+ (`no-consent`, fail closed); a consent function that throws is a no for that call and is asked
2242
+ again at the next. It comes after the rate and gesture gates and before `confirm`.
2243
+ - **`subscribeData`** speaks MCP's own subscriptions, which MCP Apps doesn't list: the view is the
2244
+ host's MCP client, as it is for `resources/read`. `resources/subscribe` and
2245
+ `resources/unsubscribe` with `{ uri }`, and the host's `notifications/resources/updated` with
2246
+ `{ uri }`, after which the view reads it again. The host offers it as MCP does,
2247
+ `hostCapabilities.serverResources: { subscribe: true }` (the official App SDK's schema keeps the
2248
+ field open, so its views still connect). The handler gets `changed(result?)` and an `AbortSignal`
2249
+ that ends with the subscription, the frame or the display; a `result` passed to `changed` answers
2250
+ the content's next read without the read handler. One subscription per URI per frame;
2251
+ unsubscribing is never gated.
2252
+ - **The host's cache (`HostOptions.cached`, `DataCache`)**: a read of a resource the content
2253
+ subscribes to is answered at once from it, after the gates, marked
2254
+ `_meta["porthole/stale"]: true` (`STALE_META`); the fresh read follows in the background, is kept
2255
+ for the content's next read, and is announced as an update. A read of an unsubscribed resource
2256
+ never gets the cache: no update would follow it.
2257
+ - **Shell globals**: `readData(uri)` (the first content's value: JSON parsed when its MIME type says
2258
+ JSON, else its text) and `subscribeData(uri, onData, onError)` (onData(value, { stale, uri }) now
2259
+ and at every change; a read at a time, one more if it changed meanwhile; one subscription per URI
2260
+ however many follow it; returns a stop function).
2261
+ - **No navigation to another document, in every shell**: the shell cancels each navigation the
2262
+ frame starts to another document (the Navigation API's `navigate` event, read through the
2263
+ platform's own getters kept at document start, its listener the first), before any request. It
2264
+ works where the frame has an origin of its own (served: domain isolation, MCP Apps proxies),
2265
+ which is where the page's `frame-src` must let frames in. An opaque frame gets no navigate
2266
+ events (the spec disables them for opaque origins; measured on Chromium: `navigation` is there,
2267
+ with no entries, and `location.href` goes on), so there `frame-src` stays the wall (P033).
2268
+ Same-document ones (an anchor) and reloads (the same address, on the frame's own origin) go on.
2269
+ Not only for live widgets: it is cheap and breaks nothing a shell's content did on purpose (links
2270
+ already open outside through `openLink`, P030; a page that reloads itself still does).
2271
+
2272
+ **Why.**
2273
+ - A widget that reads the viewer's data must have no way out but its host: Claude's dashboards
2274
+ take the same rule (no fetch, no external scripts; libraries from the host). The default egress
2275
+ is already closed (P022); what a live widget adds is that no option can open it, and libraries
2276
+ that don't need a CDN, whose request paths are a channel out (P048).
2277
+ - Two leaks Ferry measured in its own widget shell (2026-10-11): WebRTC gathering candidates (here
2278
+ since P006: `webrtc 'block'` and the shell's removal, probe `3.webrtc`, a child frame can't get the
2279
+ constructors: `4.*`), and a frame navigating itself away with data in the URL. Porthole's wall
2280
+ for the second is the embedding page's `frame-src` (P006, P033), but a page that frames served
2281
+ content must allow the content origins, so **a served frame could navigate itself to another
2282
+ content origin, with data in the URL** (measured on Chromium 153, WebKit 26.6 and Firefox 155:
2283
+ under the `navigate-guard` negative control, every one of `leak/served/live.spec.ts`' sibling
2284
+ navigations reaches the harness's server, the display restarting each time; with the guard, none
2285
+ does). On a host whose content origins include
2286
+ a url-mode app relayed to someone's machine (a dev server's preview), that is a way out. The
2287
+ guard closes it in the frame, where it starts.
2288
+ - Consent is the host's policy (PRINCIPLE 8), its gate is mechanism (PRINCIPLE 4): one answer per
2289
+ display, asked lazily, so a widget that never reads data never asks.
2290
+
2291
+ **Rejected.**
2292
+ - A config field (`network: "none"`) or a flag on `inlineWidget`: a preset is the knob-free path
2293
+ (PRINCIPLE 8), the CSP needs nothing new, and the guarantee is that no option opens egress.
2294
+ - `consent` among `readData`'s default gates: it would refuse every call of hosts that declare
2295
+ `readData` today (MCP Apps views proxying to a server). The live widget preset has it.
2296
+ - Libraries for opaque live widgets from the host app's own origin: a `srcdoc` frame inherits the
2297
+ embedding page's policy (nonce pages refuse them, P054), and it adds a second origin to name.
2298
+ Opaque live widgets get no libraries; the manual says so.
2299
+ - A third library. Plotly and ECharts are 1–3 MB; Mermaid draws diagrams, not data; a Markdown
2300
+ renderer would turn the host's data into HTML in a frame that holds the viewer's data (injection);
2301
+ a Chart.js date adapter is for time axes D3 already covers.
2302
+ - Data inside `notifications/resources/updated`: MCP's notification carries the URI only; the kept
2303
+ fresh result gives the same one round trip and keeps the wire standard.
2304
+ - Serving the libraries only to configs that set `egress.libraries`: the files are public, fixed
2305
+ and same-site only; a server that knows which config a request is for would need a ticket.
2306
+
2307
+ **Residual, documented (ADOPTING § Live widgets).**
2308
+ - A frame can `postMessage` any frame on its page (`top.frames[i]`), and nothing in it can stop
2309
+ that. A live widget on a page with frames that reach the network (a url-mode app, an `anyHttps`
2310
+ display) can hand them what it read. Hosts keep live widgets off such pages.
2311
+ - An opaque frame on a page that also frames content origins (one `frame-src` for every kind) can
2312
+ navigate itself to them: the guard has no events there. Show live widgets served, or keep opaque
2313
+ ones on pages whose `frame-src` is `'none'` (no content domain: `defineDisplays` gives every kind
2314
+ one or the other).
2315
+ - An engine without the Navigation API falls back to `frame-src`: an outside site stays shut, other
2316
+ content origins don't.
2317
+ - A clean address opened as a tab has no host, so no data.
2318
+ - Upstream: MCP Apps lists no resource subscriptions; to propose `serverResources.subscribe` and
2319
+ the three methods to the spec (ext-apps), with this entry as the evidence.
2320
+
2321
+ **Tested.** `test/live-data.test.ts` (the preset, its CSP, validation; consent: once, a no kept,
2322
+ fail closed, a throw asked again, invalid calls before consent, rates; MCP's subscribe, update,
2323
+ read again, a pushed result, unsubscribe, close, refusal, the cache stale then fresh, only after
2324
+ consent, only when subscribed); `test/libraries.test.ts` (the module is npm's bytes, pinned, with
2325
+ licenses; served without a ticket, immutable, nothing else under the path); `test/agreement.test.ts`
2326
+ (two live widget cases: the libraries taught exactly where the CSP loads them; consent's words
2327
+ exactly where the gate is); `leak/served/live.spec.ts` (a served live widget on a page with
2328
+ Porthole's embedder CSP: fetch, no-cors fetch, XHR, beacon, WebSocket, EventSource, an image, a CSS
2329
+ image, a stylesheet and an external script reach no oracle (no request, no connection); no RTC
2330
+ constructor, no peer, no STUN at a UDP oracle, no child frame; `location`, `replace`,
2331
+ `open(…, "_self")` and `navigation.navigate` to another content origin and to an outside site send
2332
+ no request (the document is kept, or the display started again); Chart.js and D3 load and draw; data read and followed, consent
2333
+ asked once; the cache first, stale, then fresh; a viewer's no refuses both), passing on
2334
+ Chromium, WebKit and Firefox. Negative control: `navigate-guard` (also applied to the served
2335
+ harness's documents) → the four navigation cases on all three engines (each sibling navigation
2336
+ reaches the harness's server). Measured on WebKit: `navigation.navigate()` to a site the page's
2337
+ `frame-src` blocks fires no navigate event (the block comes first), and WebKit then replaces the
2338
+ frame's document, so the display is started again (P031); nothing reaches the site, and the case
2339
+ accepts either outcome, as the opaque probes do. The opaque probes `5.*` keep failing under
2340
+ `embedder-csp` with the guard in place (measured, Chromium): their wall is the page's `frame-src`.
2341
+ **Revisit when** MCP Apps specifies subscriptions (follow it), an engine Porthole supports lacks the
2342
+ Navigation API, a host needs libraries in opaque frames, or agents' live widgets reach for a library
2343
+ the two don't cover.
2344
+
2345
+ ## P080 · 2026-10-15 · The host hears a navigation the shell stopped; a host may refuse all data without handlers; a refusal tells content why · Accepted
2346
+
2347
+ From Ferry's adoption of 0.5.0's live widgets (#12, #13, #14). 0.5.1, additive but for the text of
2348
+ a refused data call's error (below).
2349
+
2350
+ **Decision.**
2351
+ - **A navigation the shell stopped is an error report (#12).** When the navigate guard (P079)
2352
+ cancels a navigation, the shell sends Porthole's own notification `porthole/navigation-blocked`
2353
+ with `{ url }` (`NAVIGATION_BLOCKED_METHOD`), where the config declares `reportError` and within
2354
+ its reports (`limits.maxErrorReports` a run, the capability's rate). Both adapters carry it into
2355
+ `reportError`; the shell sends it even where the content speaks for itself (an MCP Apps view).
2356
+ The host gets `navigationBlocked: { url }` (React `onNavigationBlocked`), the address whole, and a
2357
+ `contentError` (so `errors: "agent"` hosts pass it on as they do every content error) that
2358
+ Porthole words and that names the address without its query or fragment: "It tried to navigate
2359
+ its frame to https://x.example/path?…, and was stopped: content never leaves its page.", with
2360
+ where links go when `openLink` is declared. `checkPage` reports it as an error.
2361
+ - **A host may refuse every data call without handlers (#13).** `HostOptions.consent` (React's
2362
+ `consent` on the provider and the frame) takes a `Refused` in place of the function: every
2363
+ `consent`-gated call is refused with it, nothing is asked, the host's cache isn't read, and those
2364
+ capabilities need no handler at mount. Any other declared capability still needs one, and so does
2365
+ one whose gates the host stripped of `consent`. React compares the `Refused` by value (its code and
2366
+ message), so one written inline restarts nothing; a change between a `Refused` and a function makes
2367
+ the display again, since its handlers differ.
2368
+ - **A refusal tells content why (#14).** A refused request's JSON-RPC error carries
2369
+ `data: { code, message }` (`RefusalReason`): `code` is one of `REFUSAL_CODES`,
2370
+ `consent_required` (no answer yet: the host's consent function failed, and the next call asks
2371
+ again), `denied` (the viewer said no, or the person asked to confirm declined), `rate_limited`,
2372
+ `not_allowed` (no consent function, an undeclared or malformed call, a `consent` given as a
2373
+ `Refused` with that code: not here) or `failed` (the handler threw); `message` is a sentence for
2374
+ the person viewing it. A host words its own by throwing `new Refused(code, message)` from a
2375
+ handler (a URI it doesn't serve) or from a consent function (kept as the display's answer, as
2376
+ `false` is), or by passing one as `consent`; otherwise Porthole's sentence for the code (naming
2377
+ the data for `readData` and `subscribeData`). Anything else a handler throws is `failed` in
2378
+ Porthole's words: the error's own message stays the host's (`CallOutcome.message`). The shell's
2379
+ `readData` and `subscribeData`'s `onError` reject with an `Error` whose `message` is that sentence
2380
+ and whose `code` is the code; the manual teaches the codes and to show the sentence. The JSON-RPC
2381
+ error's own `message` is unchanged (`Refused (denied)`). A host's `refused` event still names the
2382
+ bridge's `Refusal` (a handler's `Refused` is `failed` there, a consent's `denied`).
2383
+
2384
+ **Why.**
2385
+ - 0.5.0's guard was silent: a host that learned of navigations from the frame reloading (Ferry's
2386
+ display tests; its agents hearing that their widget left its page) heard nothing, so an agent
2387
+ never learned its widget's link or form was dead. A blocked navigation is something the sandbox
2388
+ blocked, which `reportError` already reports ("Blocked by the sandbox: …"), so it rides the same
2389
+ capability, bound and rate, and no frame says anything to a host whose config says errors go
2390
+ nowhere (PRINCIPLE 4). The address is the content's word either way; the host gets it whole (it
2391
+ holds the viewer's data already), while the sentence that may reach the agent drops the query and
2392
+ fragment, where a widget that read the viewer's data would have put it.
2393
+ - A page where live data must not run (Ferry: a transcript beside a preview that reaches the
2394
+ network, P079's residual) passed handlers that threw, only to satisfy the mount's check, and a
2395
+ consent that said no. The check exists so a manual never teaches a function nobody serves; with
2396
+ every call refused before any handler, the function is taught and answered, with a reason. A
2397
+ value rather than a flag: the policy is the consent's answer, known before any call, and the same
2398
+ `Refused` words the reason (PRINCIPLE 8: one option, no knob).
2399
+ - "Refused (denied)" told a widget nothing it could show. The reasons are the five a widget draws
2400
+ differently (wait for permission, show it isn't allowed, back off, say it isn't available here,
2401
+ show an error), in the error's `data`, which JSON-RPC leaves to the implementation: no new
2402
+ method, and an App SDK view reads them from the error it already gets (PRINCIPLE 2).
2403
+
2404
+ **Rejected.**
2405
+ - A `navigationBlocked` event for every config, without `reportError`: content would speak to a
2406
+ host that declared no channel for it.
2407
+ - `consent: false` for refuse-all: indistinguishable at a glance from an absent consent (also a
2408
+ refusal, but one that keeps the handler check), and it carries no words.
2409
+ - Passing a handler's error message to content: hosts' errors carry internals (a database
2410
+ address); content gets them only through a `Refused`.
2411
+ - New `Refusal` members for the consent cases: the host-facing union stays as it was; the code
2412
+ content gets is a separate, smaller vocabulary.
2413
+
2414
+ **Residual.** Opaque frames get no navigate events (P079): the guard can't see their navigations,
2415
+ so nothing is reported; a navigation the page's `frame-src` blocks replaces the frame's document,
2416
+ which the host hears as `navigated` (P031), without the address. WebKit fires no navigate event for
2417
+ `navigation.navigate()` to a site the page's `frame-src` blocks (P079): `navigated` there too.
2418
+ Content can send `porthole/navigation-blocked` itself, with any address: it is its word, bound like
2419
+ any error report.
2420
+
2421
+ **Tested.** `test/refusals.test.ts` (on `createHost` over a stand-in platform: each code over the
2422
+ wire, the consent's `Refused` kept, a failing consent asked again, a handler's `Refused` and a plain
2423
+ throw that keeps the host's words; `consent` as a `Refused` mounts without data handlers, refuses
2424
+ both, never reads the cache, and still needs any other handler; `navigationBlocked` whole and the
2425
+ content error without the query, a non-http address by its scheme, nothing without `reportError`,
2426
+ the rate, malformed reports dropped); `test/mcp.test.ts` (the `/mcp` adapter carries both);
2427
+ `test/agreement.test.ts` (the codes taught exactly where `readData` is); `leak/served/live.spec.ts`
2428
+ (each served navigation case tells the host the sibling's address, and its content error omits
2429
+ the secret; a viewer's no reaches the content as `denied` and the sentence; a host refusing all,
2430
+ with no handlers, as `not_allowed` and its sentence; a handler's `Refused` for one URI);
2431
+ `leak/react.spec.ts` (a `Refused` on the frame and on the provider: no data handlers, the content
2432
+ told why, nothing started again on re-render); `leak/check.spec.ts` (a served widget that
2433
+ navigates is told so, without the query). On Chromium, WebKit and Firefox.
2434
+ **Revisit when** MCP or MCP Apps standardizes error data for refused requests (follow it), or a
2435
+ host needs the navigation without `reportError`.
package/docs/DESIGN.md CHANGED
@@ -51,7 +51,8 @@ compile/ compile.ts (config → CompiledConfig), policy.ts (CSP, sandbox, al
51
51
  shell/ runtime.ts (the in-frame script, a string), plan.ts (what it wires), document.ts
52
52
  guide/ guide.ts (manual + tool description), examples.ts
53
53
  theme/ variables.ts (the default vocabulary, resolveTheme)
54
- presets/ presets.ts (inlineWidget, artifact, mcpApp, url; LIBRARY_CDNS)
54
+ presets/ presets.ts (inlineWidget, liveWidget, artifact, mcpApp, url; LIBRARY_CDNS)
55
+ libraries/ libraries.ts (VENDORED_LIBRARIES), files.generated.ts (their bytes, P079)
55
56
  protocol/ adapter.ts (the adapter seam), mcp-apps.ts (method names, HostContext), jsonrpc.ts
56
57
  bridge/ types.ts (the host-function bridge)
57
58
  transport/ types.ts platform/ types.ts isolation/ types.ts
@@ -92,7 +93,7 @@ interface PortholeConfig {
92
93
  contentOrigins: string[]; // domain/external: where content is served from
93
94
  embedder: { frameSrc?: string[] }; // extra frames the embedding page shows
94
95
  }
95
- type Gate = "user-activation" | "confirm" | { rateLimit: { perMinute: number } };
96
+ type Gate = "user-activation" | "confirm" | "consent" | { rateLimit: { perMinute: number } };
96
97
  ```
97
98
 
98
99
  `mode` and `isolation` select the mechanism; everything else is policy. There is
@@ -106,9 +107,10 @@ no `components` field (P015).
106
107
  | `openLink` | user-activation, confirm | handler | `openLink(url)` | `ui/open-link` (`app.openLink`) |
107
108
  | `downloadFile` | user-activation, confirm | handler | — | `ui/download-file` (`app.downloadFile`) |
108
109
  | `callTool` | confirm | handler | — | `tools/call` (`app.callServerTool`) |
109
- | `readData` | 120/min | handler | — | `resources/read` (`app.readServerResource`) |
110
+ | `readData` | 120/min | handler | `readData(uri)` | `resources/read` (`app.readServerResource`) |
111
+ | `subscribeData` | 60/min (needs `readData`) | handler (`changed`, `signal`) | `subscribeData(uri, onData, onError)` | `resources/subscribe`, `resources/unsubscribe`; the host's `notifications/resources/updated` (MCP's own; none in MCP Apps, P079) |
110
112
  | `setModelContext` | 30/min | handler | — | `ui/update-model-context` (`app.updateModelContext`) |
111
- | `reportError` | 10/min | event | (automatic) | `notifications/message`, level `error` |
113
+ | `reportError` | 10/min | event | (automatic) | `notifications/message`, level `error`; `porthole/navigation-blocked` `{ url }`, a navigation the shell stopped (P080) |
112
114
  | `resize` | none | event | (automatic) | `ui/notifications/size-changed` |
113
115
  | `copyText` | user-activation, 30/min | handler | `copyText(text)` | `porthole/copy-text` (none in the standard) |
114
116
  | `annotate` | 120/min (the frame's reports) | event | — | `porthole/annotate.*` (the host drives it, P053) |
@@ -117,7 +119,14 @@ Every preset declares only `resize` and `reportError` (they report to the host a
117
119
  carry nothing out); the host declares the rest. Gates are explained in P021: all
118
120
  must pass; `confirm` calls the host's `confirm` function and fails closed without
119
121
  one; `user-activation` is checked by the shell (advisory: it shares the content's
120
- realm) and by the host where the engine passes the gesture up.
122
+ realm) and by the host where the engine passes the gesture up; `consent` asks the
123
+ host's `consent` function once per display, before its first consent-gated call,
124
+ and fails closed without one (P079); a `Refused` given as `consent` refuses them all,
125
+ asking nothing, and their capabilities need no handler (P080). A refused request's
126
+ error carries why, `data: { code, message }` (`consent_required`, `denied`,
127
+ `rate_limited`, `not_allowed`, `failed`; the host's `Refused` words its own, P080). `presets.liveWidget` declares `readData` and
128
+ `subscribeData` with `consent` and its rate, and keeps egress closed (no option opens
129
+ it); served, it loads Porthole's libraries from its origin (`egress.libraries`).
121
130
 
122
131
  ## What the compiler derives
123
132
 
@@ -126,7 +135,8 @@ realm) and by the host where the engine passes the gesture up.
126
135
  - `csp` / `cspDirectives`: the frame's policy. `default-src 'none'`; scripts may be
127
136
  inline (agent content is inline), `'unsafe-eval'` (content is the agent's own script already,
128
137
  so eval adds no capability, and libraries content uses compile with it, WebAssembly too: P071),
129
- plus `blob:` and the script origins; each other
138
+ plus `blob:` and the script origins (and, with `egress.libraries`, Porthole's library path on
139
+ the content origins, `<origin>/__porthole/lib/`, P079); each other
130
140
  kind opens only to its origins; `connect-src 'none'` unless something is
131
141
  declared; `frame-src`, `object-src`, `base-uri`, `form-action` all `'none'`;
132
142
  `webrtc 'block'`. Never `'self'` (P022). Empty in url mode.
@@ -653,7 +663,8 @@ binding is mounting and lifecycle (P034).
653
663
  handlers={{ sendPrompt, openLink }} // one per declared capability; latest are called
654
664
  theme={(scheme) => tokens} // live values for the config's variable names
655
665
  generation={n} // bump to run again from the start
656
- onContentError onHostError onResize onNavigated onRefused onMuted onInitialized onOutcome
666
+ onContentError onHostError onResize onNavigated onNavigationBlocked onRefused onMuted
667
+ onInitialized onOutcome
657
668
  fill? // fill the box and scroll inside, not grow with the content
658
669
  annotating? annotations? focusedAnnotation? onAnnotation? // where annotate is declared
659
670
  aliases? themeKey? renderPlaceholder? eager? confirm? document? instance?
@@ -692,8 +703,9 @@ binding is mounting and lifecycle (P034).
692
703
  view; `{ id, key }` with a new key focuses the same one again); `onAnnotation` gets
693
704
  what the frame reported. A frame that mounts again gets them all.
694
705
  - **Errors** (P055): `onContentError` gets what the content did wrong (what it
695
- threw, what the sandbox blocked, that it kept navigating away): the agent's to
696
- hear. `onHostError` gets what failed on the host's side (`locate`, `mount`,
706
+ threw, what the sandbox blocked, a navigation the shell stopped, that it kept
707
+ navigating away): the agent's to hear. `onNavigationBlocked` gets a stopped
708
+ navigation's address whole (P080). `onHostError` gets what failed on the host's side (`locate`, `mount`,
697
709
  `annotations`): never the agent's. `onError(message, source)` gets both.
698
710
  - **Identity** (P057): `config`, `instance`, `annotations` and the provider's
699
711
  `hostInfo` are compared by value, and the provider's `locator` and `confirm` are
@@ -724,6 +736,10 @@ absent.
724
736
  - **Inline widget** (`presets.inlineWidget`). The host has the HTML (the agent
725
737
  wrote it) and the shell draws it in an opaque frame, streamed as it is written.
726
738
  The phase-1 workhorse.
739
+ - **Live widget** (`presets.liveWidget`, P079). An inline widget that shows the
740
+ host's data, current, as the viewer may see it: `readData` and `subscribeData`
741
+ behind the viewer's consent, no network of its own, and, served, Porthole's
742
+ Chart.js and D3 from its own origin.
727
743
  - **Artifact page** (`presets.artifact`). A whole document: written into an opaque
728
744
  frame by the shell where the host has it (the first host's "show an HTML file"),
729
745
  or served on its own origin (domain isolation), CSP in headers, versioned. It
@@ -786,7 +802,7 @@ closed like a strict host's (`leak/inherited-policy.spec.ts`).
786
802
  | 2 | images, CSS images, SVG `<image>`/`<use>`, media and posters, `input type=image`, stylesheets, `@import`, fonts, scripts, `import()`, workers, manifests, icons | CSP `img/media/font/style/script-src` = the allowlist only; `worker-src blob:` | `2.resources` (an allowed image as positive control) | — (the same CSP as item 1) |
787
803
  | 3 | WebRTC (ICE gathering reaches the network outside `connect-src`) | CSP `webrtc 'block'` **and** the shell removes every `RTC*`/`webkitRTC*` constructor, fixed in place, before content runs | `3.webrtc` (an unsandboxed peer connection as positive control: it sends STUN on both engines) | `webrtc` → `3.webrtc` (all three; Firefox's positive control needs `media.peerconnection.ice.loopback`, set in the suite's Firefox project, P035) |
788
804
  | 4 | a nested frame: a fresh realm where item 3's removal never happened | the shell drops frame-like elements (`iframe, frame, frameset, object, embed, portal, fencedframe`) synchronously wherever content connects a node (P030), and an observer removes any that arrive another way, in the document and every shadow root (`attachShadow` is wrapped so closed ones are reached too); documents are rendered inert and imported, never written; `document.open/write` throw; declarative shadow roots can't be built (P029); CSP `frame-src 'none'` | `4.light-dom`, `.sync-realm`, `.open-shadow`, `.closed-shadow`, `.shadow-nested`, `.declarative-shadow`, `.parse-html-unsafe`, `.domparser`, `.document-write`, `.plugins`, `.foreign-object`, `.template-clone`, `.static` (each: the child never runs, no STUN, no frame left) | `frame-guard,sync-guard` → light-dom, sync-realm, plugins, foreign-object, template-clone; `attach-shadow,sync-guard` → closed-shadow, shadow-nested; `declarative-shadow` → declarative-shadow; `parser-entry-points` → document-write (each on all three engines). Either guard alone is covered by the other. |
789
- | 5 | self-navigation out, with data in the URL (`location`, `replace`, `open(…, "_self")`, meta refresh, a link clicked past the shell, an SVG link), to the host's own origin, or to a `blob:`/`data:` document of its own (a fresh realm) | the **embedding page's** `frame-src` (`embedderCsp`: `'none'` for opaque content, P033; frames only, so the host's own workers are untouched, P038): a frame's own CSP cannot stop its own navigation; the shell sends link clicks out through `openLink` and drops refreshes (P030); a display whose frame navigates is started again, at most three times (P031) | `5.location`, `.replace`, `.open-self`, `.refresh`, `.anchor`, `.svg-link`, `.host-origin`, `.blob`, `.data` (no request reaches the canary or the host; a navigated document never runs: a witness origin hears nothing) | `embedder-csp` → location, replace, open-self, anchor, svg-link, blob, data, `6.remote-download` (all three; `.refresh` holds: the synchronous guard drops the refresh; Firefox also holds `.data` by itself, P035); `embedder-self` → `5.host-origin` |
805
+ | 5 | self-navigation out, with data in the URL (`location`, `replace`, `open(…, "_self")`, meta refresh, a link clicked past the shell, an SVG link), to the host's own origin, or to a `blob:`/`data:` document of its own (a fresh realm) | the **embedding page's** `frame-src` (`embedderCsp`: `'none'` for opaque content, P033; frames only, so the host's own workers are untouched, P038): a frame's own CSP cannot stop its own navigation; the shell sends link clicks out through `openLink` and drops refreshes (P030); a display whose frame navigates is started again, at most three times (P031). A served frame's page must let it reach the content origins, so there the shell cancels every navigation the frame starts to another document (the Navigation API's `navigate` event; reloads and same-document ones go on, P079), and tells the host (`navigationBlocked`, P080); an opaque frame gets no navigate events | `5.location`, `.replace`, `.open-self`, `.refresh`, `.anchor`, `.svg-link`, `.host-origin`, `.blob`, `.data` (no request reaches the canary or the host; a navigated document never runs: a witness origin hears nothing); served: `leak/served/live.spec.ts` (`location`, `replace`, `open(…, "_self")`, `navigation.navigate` to another content origin and to an outside site: no request reaches either, the document stays, the host is told the sibling's address) | `embedder-csp` → location, replace, open-self, anchor, svg-link, blob, data, `6.remote-download` (all three; `.refresh` holds: the synchronous guard drops the refresh; Firefox also holds `.data` by itself, P035; the navigation guard has no events in these opaque frames); `embedder-self` → `5.host-origin`; `navigate-guard` → the four served navigation cases (each reaches another content origin) |
790
806
  | 6 | forms, popups, downloads, top and parent navigation | `sandbox="allow-scripts"` only; CSP `form-action 'none'` | `6.submit`, `.request-submit`, `.blank-form`, `.open`, `.blank-link`, `.download`, `.remote-download`, `.top`, `.top-link`, `.parent` | `sandbox` → open, blank-link, top, top-link, parent (all three), download (Chromium; WebKit and Firefox started no download either way). Form submits still fail: `form-action` is a second wall |
791
807
  | 7 | `<base>` hijack, plugins | CSP `base-uri 'none'`, `object-src 'none'`; plugins removed as frames | `7.base-plugins` | `base-uri` → `7.base-plugins` (all three); `frame-guard,sync-guard` too (plugins left in place) |
792
808
  | 8 | resource hints and speculation rules | CSP for those an engine governs (`prefetch`, `preload`, `modulepreload`); for the rest the shell drops `dns-prefetch`, `preconnect`, `prefetch`, `prerender` links, speculation rules, refreshes and `x-dns-prefetch-control` metas synchronously, and refuses changes that would make a connected link one (P030); `x-dns-prefetch-control: off` | `8.preconnect`, `.dns-prefetch`, `.prefetch`, `.prerender`, `.preload`, `.modulepreload`, `.speculation-rules` (each in markup, inserted, and switched on by attribute change; no request, no connection) | `sync-guard` → `8.preconnect` (WebKit: it preconnects synchronously, outside CSP). Measured: Chromium and Firefox opened no preconnect even unsandboxed. `dns-prefetch` has no out-of-band oracle here (DNS isn't observed); the element is refused before it connects |
@@ -808,6 +824,7 @@ official App SDK connects under the inline, artifact and MCP Apps presets
808
824
  | 11 | theming | `setTheme(scheme)`: the host sends the resolved variables (the host's live values over the defaults, P028), the shell sets them in place, with `data-theme` and `color-scheme`, then fires the config's theme event once, only when the scheme or a value changed (never at mount, never for a host re-sending what the content has, P061); the frame element's `color-scheme` follows | `11.theme-flip` (no event at mount or for the same scheme; in place: content state kept, the event fired once per flip, back and forth), `11.theme-host-values` (live values for standard and own names; undeclared names dropped) | — |
809
825
  | 11 | base styles | plain CSS at zero specificity (`:where`): native buttons, inputs, selects and text areas take the theme's borders, radius, colors and focus ring, 44 px tall (the manual's touch size); the manual says so for inline widgets | `11.base-styles` (themed; content's own CSS overrides them) | — |
810
826
  | 12 | `sendPrompt` | the shell refuses a call without a gesture; the host refuses one without its page's user activation, then asks `confirm` with the whole text; declines count toward a mute | `12.prompt-gesture-confirm` (a call on load is refused; a click asks; a no sends nothing; a yes reaches the handler), `12.raw-message` (a raw `ui/message` around the shell, no click: refused by the host), `12.mute`, `12.no-confirm` | `confirm-gate` → prompt-gesture-confirm, link, mute, no-confirm; `shell-gesture` → prompt-gesture-confirm, mute; `host-gesture` → raw-message |
827
+ | 12 | live data (`readData`, `subscribeData`, P079) | MCP `resources/read`, `resources/subscribe`/`unsubscribe`, `notifications/resources/updated`; the `consent` gate asks the host once per display before the first data call (a no refuses them all; none refuses, fail closed), then the rate; a subscribed read may be answered from the host's cache, marked stale, the fresh one following as an update; a refusal tells content why (`data: { code, message }`, P080) | `test/live-data.test.ts`, `test/refusals.test.ts`; `leak/served/live.spec.ts` (read and followed, consent asked once; cached then fresh; a viewer's no refuses both, no handler runs, `denied` with its sentence; a host refusing all without handlers; a handler's `Refused`) | — |
811
828
  | 12 | `openLink` | link clicks go out through `openLink`; the bridge takes http(s) only, without credentials in the URL; confirmed | `12.link` (a web link asks and opens; `javascript:` links and `openLink("javascript:…")` do nothing and are refused) | `link-scheme` → `12.link` |
812
829
 
813
830
  Measured: a click in the frame gives the host page user activation (it propagates to
@@ -822,6 +839,7 @@ for that to lapse and click with raw input.
822
839
  |------|-----------|-------|------------------|
823
840
  | The host's check (P050) | `authorize.check` after a ticket or cookie verifies, before anything is served; a deny is a 403 page saying `denied` and the host's code, and the display's `outcome` says so even after `loaded` | `leak/served/authorize.spec.ts`: a revoked subject's ticket (a page, an app); a framed app's next request and reload mid-session (Chromium, Firefox: WebKit keeps no framed cookie, P025); a framed page's next load; an app and a page in a tab | `authorize` → every case but WebKit's framed page (`session` either way) |
824
841
  | Url-mode delegation (P049) | `allow` from `permissions`, `""` by default | `leak/served/permissions.spec.ts`: full screen follows it on all three; clipboard writes on Chromium only (WebKit and Firefox let any frame write in a click) | `url-permissions` → the default case (all three) |
842
+ | Porthole's libraries (P079) | `egress.libraries` (domain isolation; on in `presets.liveWidget`): `script-src <content origin>/__porthole/lib/`; `/server` serves Chart.js 4.5.1 and D3 7.9.0, npm's bytes, on every content origin, without a ticket, immutable | `test/libraries.test.ts` (npm's bytes, pinned, licenses; headers; nothing else under the path); `leak/served/live.spec.ts` (both load and draw in a live widget whose every other load and fetch reaches no oracle) | — (rows 1–2) |
825
843
  | Library CDNs for artifacts (P048, P078) | `egress: LIBRARY_CDNS` in the host's artifact config; closed by default (P022); Tailwind's, jQuery's and Plotly's own CDNs for scripts only | `leak/cdn.spec.ts`: opaque and served, a CDN library loads only when opened; another origin never; a stylesheet, an image and a fetch never reach the libraries' own CDNs | — (the CSP of rows 1–2) |
826
844
  | Workers (P044, P045) | no Node module in `/server`; D1 tickets taken by one `DELETE … RETURNING` | `test/workers.test.ts` (workerd, no `nodejs_compat`, real D1: once per ticket, a race, anonymous, a revocation, flat names, reserved namespaces) | — |
827
845
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botiverse/porthole",
3
- "version": "0.4.1",
3
+ "version": "0.5.1",
4
4
  "description": "A host-side sandbox for agent-made HTML: isolation, egress hardening, a themed shell, gated host functions, and the agent manual, from one config.",
5
5
  "license": "Apache-2.0",
6
6
  "bin": {
@@ -62,6 +62,8 @@
62
62
  "@types/node": "26.6.3",
63
63
  "@types/react": "19.3.0",
64
64
  "@types/react-dom": "19.3.0",
65
+ "chart.js": "4.5.1",
66
+ "d3": "7.9.0",
65
67
  "esbuild": "0.28.2",
66
68
  "miniflare": "4.20260730.0",
67
69
  "react": "19.3.0",
@@ -9,7 +9,17 @@ import type { AnnotationReport } from "../annotate/types.ts";
9
9
  import { parseReport } from "../annotate/validate.ts";
10
10
  import type { PortholeConfig } from "../config/schema.ts";
11
11
  import { effectiveGates } from "../compile/policy.ts";
12
+ import { blockedNavigationMessage } from "./navigation.ts";
13
+ import {
14
+ defaultReason,
15
+ isRefused,
16
+ pendingReason,
17
+ reasonOf,
18
+ type Refused,
19
+ type RefusalReason,
20
+ } from "./refusal.ts";
12
21
  import type {
22
+ CallOptions,
13
23
  CallOutcome,
14
24
  CapabilityHandler,
15
25
  CapabilityHandlers,
@@ -17,6 +27,8 @@ import type {
17
27
  ConfirmAnswer,
18
28
  ConfirmDisplay,
19
29
  ConfirmRequest,
30
+ Consent,
31
+ DataCache,
20
32
  HostFunctionBridge,
21
33
  Refusal,
22
34
  } from "./types.ts";
@@ -24,12 +36,15 @@ import type {
24
36
  /**
25
37
  * The host-function bridge: every capability call from a frame passes here, and nowhere else
26
38
  * reaches a host handler. In order: declared → arguments well formed → not muted → within its
27
- * rate → a user gesture, if gated so → a person's confirmation, if gated so → the handler.
39
+ * rate → a user gesture, if gated so → the viewer's consent, if gated so → a person's
40
+ * confirmation, if gated so → the handler (or, for a stale-allowed read, the host's cache).
28
41
  */
29
42
 
30
43
  export type BridgeEvent =
31
44
  | { readonly type: "resize"; readonly height: number; readonly width?: number }
32
45
  | { readonly type: "error"; readonly message: string }
46
+ /** The shell cancelled a navigation of the frame to `url` (P080): the content's word. */
47
+ | { readonly type: "navigationBlocked"; readonly url: string }
33
48
  | { readonly type: "annotation"; readonly report: AnnotationReport }
34
49
  | { readonly type: "refused"; readonly capability: CapabilityName; readonly refusal: Refusal }
35
50
  | { readonly type: "muted" };
@@ -39,6 +54,14 @@ export interface BridgeOptions {
39
54
  readonly display: ConfirmDisplay;
40
55
  readonly handlers: CapabilityHandlers;
41
56
  readonly confirm?: Confirm;
57
+ /**
58
+ * Asked before a `consent`-gated call (P079). The host's, made to ask once per display by the
59
+ * caller (`createHost` keeps the answer across the display's frames). A `Refused` refuses every
60
+ * such call with it, asking nothing (P080).
61
+ */
62
+ readonly consent?: Consent | Refused;
63
+ /** The host's cache, for reads that may be answered stale (`CallOptions.stale`, P079). */
64
+ readonly cached?: DataCache;
42
65
  /** Whether the embedding page has user activation now; undefined where it can't tell. */
43
66
  readonly userActivation?: () => boolean | undefined;
44
67
  readonly onEvent: (event: BridgeEvent) => void;
@@ -72,6 +95,12 @@ export function linkTarget(value: unknown): string | null {
72
95
  return url.href;
73
96
  }
74
97
 
98
+ /** A resource's URI, as `resources/read` and `resources/subscribe` carry it. */
99
+ function resourceUri(args: unknown): { uri: string } | null {
100
+ const uri = isRecord(args) ? args.uri : undefined;
101
+ return typeof uri === "string" && uri !== "" && uri.length <= MAX_URL ? { uri } : null;
102
+ }
103
+
75
104
  type Validator<N extends CapabilityName> = (
76
105
  args: unknown,
77
106
  config: PortholeConfig,
@@ -108,10 +137,8 @@ const VALIDATORS: { readonly [N in CapabilityName]: Validator<N> } = {
108
137
  const given = args.arguments ?? {};
109
138
  return isRecord(given) ? { name: args.name, arguments: given } : null;
110
139
  },
111
- readData: (args) => {
112
- const uri = isRecord(args) ? args.uri : undefined;
113
- return typeof uri === "string" && uri !== "" && uri.length <= MAX_URL ? { uri } : null;
114
- },
140
+ readData: (args) => resourceUri(args),
141
+ subscribeData: (args) => resourceUri(args),
115
142
  setModelContext: (args) => {
116
143
  if (!isRecord(args)) {
117
144
  return null;
@@ -128,7 +155,15 @@ const VALIDATORS: { readonly [N in CapabilityName]: Validator<N> } = {
128
155
  ...(structuredContent === undefined ? {} : { structuredContent }),
129
156
  };
130
157
  },
131
- reportError: (args) => {
158
+ reportError: (args, config) => {
159
+ // A navigation the shell cancelled (P080): Porthole words it, naming the address without its
160
+ // query; the address itself goes to the host whole.
161
+ const blocked = isRecord(args) ? args.navigationBlocked : undefined;
162
+ if (blocked !== undefined) {
163
+ return typeof blocked === "string" && blocked !== "" && blocked.length <= MAX_URL
164
+ ? { message: blockedNavigationMessage(blocked, config), navigationBlocked: blocked }
165
+ : null;
166
+ }
132
167
  const message = isRecord(args) ? args.message : undefined;
133
168
  return typeof message === "string" && message !== ""
134
169
  ? { message: message.slice(0, 2_000) }
@@ -157,6 +192,36 @@ const VALIDATORS: { readonly [N in CapabilityName]: Validator<N> } = {
157
192
  },
158
193
  };
159
194
 
195
+ /**
196
+ * The host's `consent`, asked once (P079): the first call asks, every later one gets that answer,
197
+ * for as long as the returned function is kept (`createHost` keeps one per display). A `Refused`
198
+ * it throws is an answer, kept and thrown again at every call (P080); anything else it throws is
199
+ * no answer: thrown for that call, and the next asks again.
200
+ */
201
+ export function onceConsent(consent: Consent): Consent {
202
+ let answer: Promise<boolean | Refused> | null = null;
203
+ return async (request) => {
204
+ const asked = (answer ??= Promise.resolve()
205
+ .then(() => consent(request))
206
+ .then(
207
+ // Only a real yes: anything else a host's function gives is a no (fail closed).
208
+ (allowed: unknown) => allowed === true,
209
+ (error: unknown) => {
210
+ if (isRefused(error)) {
211
+ return error;
212
+ }
213
+ answer = null;
214
+ throw error;
215
+ },
216
+ ));
217
+ const given = await asked;
218
+ if (typeof given !== "boolean") {
219
+ throw given;
220
+ }
221
+ return given;
222
+ };
223
+ }
224
+
160
225
  export function createBridge(options: BridgeOptions): HostFunctionBridge {
161
226
  const { config, display, handlers, onEvent } = options;
162
227
  const now = options.now ?? (() => Date.now());
@@ -168,9 +233,15 @@ export function createBridge(options: BridgeOptions): HostFunctionBridge {
168
233
  capability: CapabilityName,
169
234
  refusal: Refusal,
170
235
  message?: string,
236
+ reason?: RefusalReason,
171
237
  ): CallOutcome<T> => {
172
238
  onEvent({ type: "refused", capability, refusal });
173
- return { ok: false, refusal, ...(message === undefined ? {} : { message }) };
239
+ return {
240
+ ok: false,
241
+ refusal,
242
+ ...(message === undefined ? {} : { message }),
243
+ reason: reason ?? defaultReason(capability, refusal),
244
+ };
174
245
  };
175
246
 
176
247
  const withinRate = (capability: CapabilityName, perMinute: number): boolean => {
@@ -191,7 +262,7 @@ export function createBridge(options: BridgeOptions): HostFunctionBridge {
191
262
  async call<N extends CapabilityName>(
192
263
  capability: N,
193
264
  raw: unknown,
194
- callOptions?: { readonly userActivated?: boolean },
265
+ callOptions?: CallOptions,
195
266
  ): Promise<CallOutcome<CapabilityResults[N]>> {
196
267
  type Result = CapabilityResults[N];
197
268
  if (config.capabilities[capability] === undefined) {
@@ -217,10 +288,36 @@ export function createBridge(options: BridgeOptions): HostFunctionBridge {
217
288
  return refuse<Result>(capability, "no-user-activation");
218
289
  }
219
290
  }
291
+ if (gates.includes("consent")) {
292
+ const consent = options.consent;
293
+ if (consent === undefined) {
294
+ return refuse<Result>(capability, "no-consent");
295
+ }
296
+ // The host's policy, known before any call: every one refused with its reason (P080).
297
+ if (isRefused(consent)) {
298
+ return refuse<Result>(capability, "denied", undefined, reasonOf(consent));
299
+ }
300
+ let answer: unknown = false;
301
+ try {
302
+ answer = await consent({ capability, args, display } as ConfirmRequest);
303
+ } catch (error) {
304
+ // A Refused is the host's no, with its reason; any other failure is no answer yet.
305
+ return refuse<Result>(
306
+ capability,
307
+ "denied",
308
+ undefined,
309
+ isRefused(error) ? reasonOf(error) : pendingReason(capability),
310
+ );
311
+ }
312
+ if (answer !== true) {
313
+ return refuse<Result>(capability, "denied");
314
+ }
315
+ }
220
316
  // The effect, run once: when the person's "yes" calls `proceed` (inside its own click, so an
221
317
  // effect that needs a gesture gets one), or after `confirm` resolves accepted.
222
318
  let effect: Promise<CallOutcome<Result>> | null = null;
223
- const run = (): Promise<CallOutcome<Result>> => (effect ??= perform(capability, args));
319
+ const run = (): Promise<CallOutcome<Result>> =>
320
+ (effect ??= perform(capability, args, callOptions));
224
321
  if (confirms) {
225
322
  if (options.confirm === undefined) {
226
323
  return refuse<Result>(capability, "no-confirm");
@@ -255,6 +352,7 @@ export function createBridge(options: BridgeOptions): HostFunctionBridge {
255
352
  async function perform<N extends CapabilityName>(
256
353
  capability: N,
257
354
  args: CapabilityArgs[N],
355
+ callOptions: CallOptions | undefined,
258
356
  ): Promise<CallOutcome<CapabilityResults[N]>> {
259
357
  type Result = CapabilityResults[N];
260
358
  {
@@ -265,7 +363,11 @@ export function createBridge(options: BridgeOptions): HostFunctionBridge {
265
363
  } else if (capability === "annotate") {
266
364
  onEvent({ type: "annotation", report: args as CapabilityArgs["annotate"] });
267
365
  } else {
268
- onEvent({ type: "error", message: (args as CapabilityArgs["reportError"]).message });
366
+ const report = args as CapabilityArgs["reportError"];
367
+ if (report.navigationBlocked !== undefined) {
368
+ onEvent({ type: "navigationBlocked", url: report.navigationBlocked });
369
+ }
370
+ onEvent({ type: "error", message: report.message });
269
371
  }
270
372
  return { ok: true, value: undefined as Result };
271
373
  }
@@ -273,18 +375,36 @@ export function createBridge(options: BridgeOptions): HostFunctionBridge {
273
375
  if (handler === undefined) {
274
376
  return refuse<Result>(capability, "not-declared");
275
377
  }
378
+ const context = { displayId: display.id, title: display.title, capability };
379
+ // A read the content subscribes to may be answered from the host's cache, marked stale; the
380
+ // fresh one follows as an update (the adapter asks for it). A cache that fails is no answer.
381
+ if (capability === "readData" && callOptions?.stale === true && options.cached) {
382
+ try {
383
+ const cached = await options.cached(args as CapabilityArgs["readData"], context);
384
+ if (cached !== undefined) {
385
+ return { ok: true, value: cached as Result, stale: true };
386
+ }
387
+ } catch {
388
+ // Read it fresh instead.
389
+ }
390
+ }
391
+ const subscription = callOptions?.subscription;
392
+ if (capability === "subscribeData" && subscription === undefined) {
393
+ return refuse<Result>(capability, "invalid");
394
+ }
276
395
  try {
277
- const value = await handler(args, {
278
- displayId: display.id,
279
- title: display.title,
280
- capability,
281
- });
282
- return { ok: true, value };
396
+ const value = await (handler as (args: unknown, context: unknown) => unknown)(
397
+ args,
398
+ capability === "subscribeData" ? { ...context, ...subscription } : context,
399
+ );
400
+ return { ok: true, value: value as Result };
283
401
  } catch (error) {
402
+ // A host's Refused tells content its reason (P080); any other error stays the host's.
284
403
  return refuse<Result>(
285
404
  capability,
286
405
  "failed",
287
406
  error instanceof Error ? error.message : String(error),
407
+ isRefused(error) ? reasonOf(error) : undefined,
288
408
  );
289
409
  }
290
410
  }