@botiverse/porthole 0.5.0 → 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 (42) hide show
  1. package/dist/bridge/bridge.d.ts +12 -4
  2. package/dist/bridge/bridge.js +58 -26
  3. package/dist/bridge/navigation.d.ts +11 -0
  4. package/dist/bridge/navigation.js +30 -0
  5. package/dist/bridge/refusal.d.ts +53 -0
  6. package/dist/bridge/refusal.js +121 -0
  7. package/dist/bridge/types.d.ts +7 -0
  8. package/dist/check/page-source.js +1 -1
  9. package/dist/check/page.js +5 -0
  10. package/dist/config/capabilities.d.ts +5 -0
  11. package/dist/conformance/harness-source.js +1 -1
  12. package/dist/guide/guide.js +14 -4
  13. package/dist/host/create-host.js +15 -4
  14. package/dist/host/types.d.ts +15 -2
  15. package/dist/index.d.ts +2 -1
  16. package/dist/index.js +3 -1
  17. package/dist/mcp/adapter.js +22 -7
  18. package/dist/protocol/mcp-apps.d.ts +6 -0
  19. package/dist/protocol/mcp-apps.js +6 -0
  20. package/dist/protocol/shell-adapter.js +14 -2
  21. package/dist/react/frame.d.ts +19 -4
  22. package/dist/react/frame.js +37 -9
  23. package/dist/shell/runtime.js +34 -8
  24. package/docs/ADOPTING.md +39 -9
  25. package/docs/DECISIONS.md +92 -0
  26. package/docs/DESIGN.md +12 -7
  27. package/package.json +1 -1
  28. package/src/bridge/bridge.ts +70 -22
  29. package/src/bridge/navigation.ts +34 -0
  30. package/src/bridge/refusal.ts +151 -0
  31. package/src/bridge/types.ts +12 -1
  32. package/src/check/page.ts +7 -0
  33. package/src/config/capabilities.ts +5 -1
  34. package/src/guide/guide.ts +18 -4
  35. package/src/host/create-host.ts +16 -4
  36. package/src/host/types.ts +13 -2
  37. package/src/index.ts +9 -0
  38. package/src/mcp/adapter.ts +26 -6
  39. package/src/protocol/mcp-apps.ts +7 -0
  40. package/src/protocol/shell-adapter.ts +15 -2
  41. package/src/react/frame.tsx +53 -14
  42. package/src/shell/runtime.ts +34 -8
package/docs/DECISIONS.md CHANGED
@@ -2341,3 +2341,95 @@ accepts either outcome, as the opaque probes do. The opaque probes `5.*` keep fa
2341
2341
  **Revisit when** MCP Apps specifies subscriptions (follow it), an engine Porthole supports lacks the
2342
2342
  Navigation API, a host needs libraries in opaque frames, or agents' live widgets reach for a library
2343
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
@@ -110,7 +110,7 @@ no `components` field (P015).
110
110
  | `readData` | 120/min | handler | `readData(uri)` | `resources/read` (`app.readServerResource`) |
111
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) |
112
112
  | `setModelContext` | 30/min | handler | — | `ui/update-model-context` (`app.updateModelContext`) |
113
- | `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) |
114
114
  | `resize` | none | event | (automatic) | `ui/notifications/size-changed` |
115
115
  | `copyText` | user-activation, 30/min | handler | `copyText(text)` | `porthole/copy-text` (none in the standard) |
116
116
  | `annotate` | 120/min (the frame's reports) | event | — | `porthole/annotate.*` (the host drives it, P053) |
@@ -121,7 +121,10 @@ must pass; `confirm` calls the host's `confirm` function and fails closed withou
121
121
  one; `user-activation` is checked by the shell (advisory: it shares the content's
122
122
  realm) and by the host where the engine passes the gesture up; `consent` asks the
123
123
  host's `consent` function once per display, before its first consent-gated call,
124
- and fails closed without one (P079). `presets.liveWidget` declares `readData` and
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
125
128
  `subscribeData` with `consent` and its rate, and keeps egress closed (no option opens
126
129
  it); served, it loads Porthole's libraries from its origin (`egress.libraries`).
127
130
 
@@ -660,7 +663,8 @@ binding is mounting and lifecycle (P034).
660
663
  handlers={{ sendPrompt, openLink }} // one per declared capability; latest are called
661
664
  theme={(scheme) => tokens} // live values for the config's variable names
662
665
  generation={n} // bump to run again from the start
663
- onContentError onHostError onResize onNavigated onRefused onMuted onInitialized onOutcome
666
+ onContentError onHostError onResize onNavigated onNavigationBlocked onRefused onMuted
667
+ onInitialized onOutcome
664
668
  fill? // fill the box and scroll inside, not grow with the content
665
669
  annotating? annotations? focusedAnnotation? onAnnotation? // where annotate is declared
666
670
  aliases? themeKey? renderPlaceholder? eager? confirm? document? instance?
@@ -699,8 +703,9 @@ binding is mounting and lifecycle (P034).
699
703
  view; `{ id, key }` with a new key focuses the same one again); `onAnnotation` gets
700
704
  what the frame reported. A frame that mounts again gets them all.
701
705
  - **Errors** (P055): `onContentError` gets what the content did wrong (what it
702
- threw, what the sandbox blocked, that it kept navigating away): the agent's to
703
- 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`,
704
709
  `annotations`): never the agent's. `onError(message, source)` gets both.
705
710
  - **Identity** (P057): `config`, `instance`, `annotations` and the provider's
706
711
  `hostInfo` are compared by value, and the provider's `locator` and `confirm` are
@@ -797,7 +802,7 @@ closed like a strict host's (`leak/inherited-policy.spec.ts`).
797
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) |
798
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) |
799
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. |
800
- | 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); 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) | `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) |
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) |
801
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 |
802
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) |
803
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 |
@@ -819,7 +824,7 @@ official App SDK connects under the inline, artifact and MCP Apps presets
819
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) | — |
820
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) | — |
821
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 |
822
- | 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 | `test/live-data.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) | — |
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`) | — |
823
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` |
824
829
 
825
830
  Measured: a click in the frame gives the host page user activation (it propagates to
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botiverse/porthole",
3
- "version": "0.5.0",
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": {
@@ -9,6 +9,15 @@ 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 {
13
22
  CallOptions,
14
23
  CallOutcome,
@@ -34,6 +43,8 @@ import type {
34
43
  export type BridgeEvent =
35
44
  | { readonly type: "resize"; readonly height: number; readonly width?: number }
36
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 }
37
48
  | { readonly type: "annotation"; readonly report: AnnotationReport }
38
49
  | { readonly type: "refused"; readonly capability: CapabilityName; readonly refusal: Refusal }
39
50
  | { readonly type: "muted" };
@@ -45,9 +56,10 @@ export interface BridgeOptions {
45
56
  readonly confirm?: Confirm;
46
57
  /**
47
58
  * Asked before a `consent`-gated call (P079). The host's, made to ask once per display by the
48
- * caller (`createHost` keeps the answer across the display's frames).
59
+ * caller (`createHost` keeps the answer across the display's frames). A `Refused` refuses every
60
+ * such call with it, asking nothing (P080).
49
61
  */
50
- readonly consent?: Consent;
62
+ readonly consent?: Consent | Refused;
51
63
  /** The host's cache, for reads that may be answered stale (`CallOptions.stale`, P079). */
52
64
  readonly cached?: DataCache;
53
65
  /** Whether the embedding page has user activation now; undefined where it can't tell. */
@@ -143,7 +155,15 @@ const VALIDATORS: { readonly [N in CapabilityName]: Validator<N> } = {
143
155
  ...(structuredContent === undefined ? {} : { structuredContent }),
144
156
  };
145
157
  },
146
- 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
+ }
147
167
  const message = isRecord(args) ? args.message : undefined;
148
168
  return typeof message === "string" && message !== ""
149
169
  ? { message: message.slice(0, 2_000) }
@@ -174,22 +194,32 @@ const VALIDATORS: { readonly [N in CapabilityName]: Validator<N> } = {
174
194
 
175
195
  /**
176
196
  * The host's `consent`, asked once (P079): the first call asks, every later one gets that answer,
177
- * for as long as the returned function is kept (`createHost` keeps one per display). A consent
178
- * function that fails is a no for that call, and is asked again at the next.
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.
179
200
  */
180
201
  export function onceConsent(consent: Consent): Consent {
181
- let answer: Promise<boolean> | null = null;
182
- return (request) =>
183
- (answer ??= Promise.resolve()
202
+ let answer: Promise<boolean | Refused> | null = null;
203
+ return async (request) => {
204
+ const asked = (answer ??= Promise.resolve()
184
205
  .then(() => consent(request))
185
206
  .then(
186
207
  // Only a real yes: anything else a host's function gives is a no (fail closed).
187
208
  (allowed: unknown) => allowed === true,
188
- () => {
209
+ (error: unknown) => {
210
+ if (isRefused(error)) {
211
+ return error;
212
+ }
189
213
  answer = null;
190
- return false;
214
+ throw error;
191
215
  },
192
216
  ));
217
+ const given = await asked;
218
+ if (typeof given !== "boolean") {
219
+ throw given;
220
+ }
221
+ return given;
222
+ };
193
223
  }
194
224
 
195
225
  export function createBridge(options: BridgeOptions): HostFunctionBridge {
@@ -203,9 +233,15 @@ export function createBridge(options: BridgeOptions): HostFunctionBridge {
203
233
  capability: CapabilityName,
204
234
  refusal: Refusal,
205
235
  message?: string,
236
+ reason?: RefusalReason,
206
237
  ): CallOutcome<T> => {
207
238
  onEvent({ type: "refused", capability, refusal });
208
- 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
+ };
209
245
  };
210
246
 
211
247
  const withinRate = (capability: CapabilityName, perMinute: number): boolean => {
@@ -253,21 +289,27 @@ export function createBridge(options: BridgeOptions): HostFunctionBridge {
253
289
  }
254
290
  }
255
291
  if (gates.includes("consent")) {
256
- if (options.consent === undefined) {
292
+ const consent = options.consent;
293
+ if (consent === undefined) {
257
294
  return refuse<Result>(capability, "no-consent");
258
295
  }
259
- let allowed = false;
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;
260
301
  try {
261
- const answer: unknown = await options.consent({
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>(
262
306
  capability,
263
- args,
264
- display,
265
- } as ConfirmRequest);
266
- allowed = answer === true;
267
- } catch {
268
- allowed = false;
307
+ "denied",
308
+ undefined,
309
+ isRefused(error) ? reasonOf(error) : pendingReason(capability),
310
+ );
269
311
  }
270
- if (!allowed) {
312
+ if (answer !== true) {
271
313
  return refuse<Result>(capability, "denied");
272
314
  }
273
315
  }
@@ -321,7 +363,11 @@ export function createBridge(options: BridgeOptions): HostFunctionBridge {
321
363
  } else if (capability === "annotate") {
322
364
  onEvent({ type: "annotation", report: args as CapabilityArgs["annotate"] });
323
365
  } else {
324
- 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 });
325
371
  }
326
372
  return { ok: true, value: undefined as Result };
327
373
  }
@@ -353,10 +399,12 @@ export function createBridge(options: BridgeOptions): HostFunctionBridge {
353
399
  );
354
400
  return { ok: true, value: value as Result };
355
401
  } catch (error) {
402
+ // A host's Refused tells content its reason (P080); any other error stays the host's.
356
403
  return refuse<Result>(
357
404
  capability,
358
405
  "failed",
359
406
  error instanceof Error ? error.message : String(error),
407
+ isRefused(error) ? reasonOf(error) : undefined,
360
408
  );
361
409
  }
362
410
  }
@@ -0,0 +1,34 @@
1
+ import type { PortholeConfig } from "../config/schema.ts";
2
+
3
+ /**
4
+ * A navigation the shell cancelled (P079), as the host is told it (P080): the address, whole, on
5
+ * the `navigationBlocked` event (the host's to keep), and a sentence for the content's errors
6
+ * (`contentError`, which a host may give the agent that wrote it) that names the address without
7
+ * its query or fragment, where a viewer's data would be.
8
+ */
9
+
10
+ /** An address without what could carry data: an http(s) one's origin and path, else its scheme. */
11
+ export function addressWithoutQuery(url: string): string {
12
+ let parsed: URL;
13
+ try {
14
+ parsed = new URL(url);
15
+ } catch {
16
+ return "another address";
17
+ }
18
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
19
+ return `a ${parsed.protocol} address`;
20
+ }
21
+ const rest = parsed.search !== "" || parsed.hash !== "" ? "?…" : "";
22
+ return `${parsed.origin}${parsed.pathname}${rest}`;
23
+ }
24
+
25
+ /** What the content's errors say about a navigation the shell cancelled. */
26
+ export function blockedNavigationMessage(url: string, config: PortholeConfig): string {
27
+ const links =
28
+ config.capabilities.openLink === undefined
29
+ ? ""
30
+ : config.mode === "mcp-app"
31
+ ? " Open links with ui/open-link (a new tab)."
32
+ : " Open links with openLink(url) or an <a href> (a new tab).";
33
+ return `It tried to navigate its frame to ${addressWithoutQuery(url)}, and was stopped: content never leaves its page.${links}`;
34
+ }
@@ -0,0 +1,151 @@
1
+ import type { CapabilityName } from "../config/capabilities.ts";
2
+ import type { Refusal } from "./types.ts";
3
+
4
+ /**
5
+ * Why a call was refused, as content is told (P080): a code it can branch on and a sentence it can
6
+ * show the person viewing it. Carried in a refused request's JSON-RPC error, as its `data`; the
7
+ * shell's globals reject with an error that has both (`error.code`, `error.message`).
8
+ *
9
+ * - `consent_required`: the viewer hasn't allowed it yet (their answer is still to come).
10
+ * - `denied`: the viewer (or the person asked to confirm) said no.
11
+ * - `rate_limited`: too many calls this minute.
12
+ * - `not_allowed`: the host doesn't let this content have it, here or at all (a URI it doesn't
13
+ * serve, a page where data never runs).
14
+ * - `failed`: the host tried and couldn't.
15
+ */
16
+ export const REFUSAL_CODES = [
17
+ "consent_required",
18
+ "denied",
19
+ "rate_limited",
20
+ "not_allowed",
21
+ "failed",
22
+ ] as const;
23
+
24
+ export type RefusalCode = (typeof REFUSAL_CODES)[number];
25
+
26
+ /** What content is told about a refusal: the JSON-RPC error's `data`. */
27
+ export interface RefusalReason {
28
+ readonly code: RefusalCode;
29
+ /** A sentence for the person viewing the content: the host's, else Porthole's. */
30
+ readonly message: string;
31
+ }
32
+
33
+ /** The most a refusal's message carries to content. */
34
+ const MAX_MESSAGE = 500;
35
+
36
+ export function isRefusalCode(value: unknown): value is RefusalCode {
37
+ return typeof value === "string" && (REFUSAL_CODES as readonly string[]).includes(value);
38
+ }
39
+
40
+ /**
41
+ * A refusal the host gives, with the reason content is told (P080). Throw it from a handler (this
42
+ * URI isn't one you serve: `not_allowed`; the viewer didn't allow this kind of data: `denied`), or
43
+ * from a `consent` function (kept as the display's answer, as `false` is). Or pass one as
44
+ * `HostOptions.consent` itself: every `consent`-gated call is refused with it, and those
45
+ * capabilities need no handler (a page where data never runs).
46
+ *
47
+ * Any other error a handler throws is `failed` with Porthole's words: its message stays the host's.
48
+ */
49
+ export class Refused extends Error {
50
+ readonly code: RefusalCode;
51
+
52
+ /** `message`: a sentence for the viewer; absent, Porthole's for the code. */
53
+ constructor(code: RefusalCode, message?: string) {
54
+ if (!isRefusalCode(code)) {
55
+ throw new TypeError(`Refused: code must be one of ${REFUSAL_CODES.join(", ")}`);
56
+ }
57
+ super(message === undefined || message.trim() === "" ? DEFAULT_MESSAGES[code] : message);
58
+ this.name = "Refused";
59
+ this.code = code;
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Whether `value` is a `Refused`: by class, or by shape where two copies of Porthole meet (a
65
+ * host's bundle and a library's).
66
+ */
67
+ export function isRefused(value: unknown): value is Refused {
68
+ return (
69
+ value instanceof Refused ||
70
+ (value instanceof Error &&
71
+ value.name === "Refused" &&
72
+ isRefusalCode((value as { code?: unknown }).code))
73
+ );
74
+ }
75
+
76
+ /** The reason a host's `Refused` gives content. */
77
+ export function reasonOf(refused: Refused): RefusalReason {
78
+ const message = refused.message.trim();
79
+ return {
80
+ code: refused.code,
81
+ message: (message === "" ? DEFAULT_MESSAGES[refused.code] : message).slice(0, MAX_MESSAGE),
82
+ };
83
+ }
84
+
85
+ /** Porthole's sentence for each code, where the host gave none. */
86
+ const DEFAULT_MESSAGES: { readonly [Code in RefusalCode]: string } = {
87
+ consent_required: "This needs your permission first.",
88
+ denied: "You didn't allow this.",
89
+ rate_limited: "Too many requests: try again in a minute.",
90
+ not_allowed: "This isn't available here.",
91
+ failed: "The app couldn't do this.",
92
+ };
93
+
94
+ /** Where a data capability's words differ: they name the data. */
95
+ const DATA_MESSAGES: { readonly [Code in RefusalCode]: string } = {
96
+ consent_required: "Reading this data needs your permission first.",
97
+ denied: "You didn't allow this to read your data.",
98
+ rate_limited: "Too many data requests: try again in a minute.",
99
+ not_allowed: "This data isn't available here.",
100
+ failed: "The app couldn't get this data.",
101
+ };
102
+
103
+ /** Each refusal's code, as content is told it. */
104
+ const CODES: { readonly [R in Refusal]: RefusalCode } = {
105
+ "not-declared": "not_allowed",
106
+ invalid: "not_allowed",
107
+ "no-user-activation": "not_allowed",
108
+ "no-confirm": "not_allowed",
109
+ declined: "denied",
110
+ redirected: "denied",
111
+ muted: "denied",
112
+ "no-consent": "not_allowed",
113
+ denied: "denied",
114
+ "rate-limited": "rate_limited",
115
+ failed: "failed",
116
+ };
117
+
118
+ /** Refusals whose own words say more than their code's. */
119
+ const OWN_MESSAGES: { readonly [R in Refusal]?: string } = {
120
+ "no-user-activation": "This needs a click.",
121
+ invalid: "The app can't take this request.",
122
+ muted: "You declined this too often: it isn't asked again until it runs again.",
123
+ };
124
+
125
+ /** What content is told about a refusal Porthole made (the host gave no `Refused`). */
126
+ export function defaultReason(capability: CapabilityName, refusal: Refusal): RefusalReason {
127
+ const code = CODES[refusal];
128
+ const data = capability === "readData" || capability === "subscribeData";
129
+ return {
130
+ code,
131
+ message: OWN_MESSAGES[refusal] ?? (data ? DATA_MESSAGES : DEFAULT_MESSAGES)[code],
132
+ };
133
+ }
134
+
135
+ /** What content is told about a refused call: the bridge's reason, else Porthole's for it. */
136
+ export function reasonFor(
137
+ capability: CapabilityName,
138
+ outcome: { readonly refusal: Refusal; readonly reason?: RefusalReason },
139
+ ): RefusalReason {
140
+ const reason = outcome.reason ?? defaultReason(capability, outcome.refusal);
141
+ return { code: reason.code, message: reason.message };
142
+ }
143
+
144
+ /** A consent function that failed (threw, rejected): not an answer, so asked again at the next. */
145
+ export function pendingReason(capability: CapabilityName): RefusalReason {
146
+ const data = capability === "readData" || capability === "subscribeData";
147
+ return {
148
+ code: "consent_required",
149
+ message: (data ? DATA_MESSAGES : DEFAULT_MESSAGES).consent_required,
150
+ };
151
+ }
@@ -5,6 +5,7 @@ import type {
5
5
  HandledCapability,
6
6
  } from "../config/capabilities.ts";
7
7
  import type { InstanceRef } from "../isolation/types.ts";
8
+ import type { RefusalReason } from "./refusal.ts";
8
9
 
9
10
  /**
10
11
  * The host-function bridge (ARCHITECTURE § Framework layer): carries a capability call from the
@@ -48,6 +49,9 @@ export type CapabilityHandlers = { readonly [N in HandledCapability]?: Capabilit
48
49
  * Asked once per display before its first call of a `consent`-gated capability (P079): may this
49
50
  * content have them (read the viewer's data)? The request is that first call. A host remembers
50
51
  * the answer where it likes (per viewer, per widget); Porthole keeps it for the display's life.
52
+ * `false` is a no (content is told `denied`); a thrown `Refused` is a no with its reason, kept
53
+ * the same way (P080); anything else it throws is no answer yet (`consent_required`), and the next
54
+ * call asks again.
51
55
  */
52
56
  export type Consent = (request: ConfirmRequest) => boolean | Promise<boolean>;
53
57
 
@@ -126,7 +130,14 @@ export type Refusal =
126
130
  export type CallOutcome<T> =
127
131
  /** `stale`: a `readData` answered from the host's cache (`DataCache`). */
128
132
  | { readonly ok: true; readonly value: T; readonly stale?: true }
129
- | { readonly ok: false; readonly refusal: Refusal; readonly message?: string };
133
+ | {
134
+ readonly ok: false;
135
+ readonly refusal: Refusal;
136
+ /** What the host's handler threw: the host's own words, never sent to content. */
137
+ readonly message?: string;
138
+ /** What content is told (P080): the host's `Refused`, else Porthole's for the refusal. */
139
+ readonly reason?: RefusalReason;
140
+ };
130
141
 
131
142
  /** What an adapter adds to a call, beyond what the content sent. */
132
143
  export interface CallOptions {
package/src/check/page.ts CHANGED
@@ -4,6 +4,7 @@ import {
4
4
  isCapabilityName,
5
5
  type HandledCapability,
6
6
  } from "../config/capabilities.ts";
7
+ import { addressWithoutQuery } from "../bridge/navigation.ts";
7
8
  import { createHost } from "../host/create-host.ts";
8
9
  import type { PlatformHost } from "../platform/types.ts";
9
10
  import { webPlatform } from "../platform/web.ts";
@@ -209,6 +210,12 @@ const check = {
209
210
  calls.push({ capability, outcome: refusal });
210
211
  }
211
212
  });
213
+ // A navigation the shell stopped (P080): the content tried to leave its page.
214
+ display.on("navigationBlocked", ({ url }) => {
215
+ run.data.errors.push(
216
+ `It tried to navigate its frame to ${addressWithoutQuery(url)}, and was stopped: content never leaves its page`,
217
+ );
218
+ });
212
219
  display.on("outcome", (outcome) => {
213
220
  run.data.outcome = outcome.state === "blocked" ? `blocked: ${outcome.reason}` : outcome.state;
214
221
  });
@@ -147,7 +147,11 @@ export interface CapabilityArgs {
147
147
  readonly content?: readonly unknown[];
148
148
  readonly structuredContent?: Readonly<Record<string, unknown>>;
149
149
  };
150
- readonly reportError: { readonly message: string };
150
+ /**
151
+ * `navigationBlocked`: the address a navigation of the frame went to when the shell cancelled it
152
+ * (P080), the content's word; `message` is then Porthole's, which names it without its query.
153
+ */
154
+ readonly reportError: { readonly message: string; readonly navigationBlocked?: string };
151
155
  readonly resize: { readonly height: number; readonly width?: number };
152
156
  readonly copyText: { readonly text: string };
153
157
  /** What the frame reported, once checked (`AnnotationReport`). */