@botiverse/porthole 0.16.0 → 0.16.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.
package/docs/ADOPTING.md CHANGED
@@ -1,13 +1,12 @@
1
1
  # Adopting Porthole
2
2
 
3
- How to put Porthole in an app, from the npm package alone. The package's `examples/` is a whole
4
- app that does everything below: `examples/app.mjs` is the app, runtime-agnostic;
5
- `examples/node/server.mjs` (`nodeServer`) and `examples/workers/` (`contentHostFor`) run it, as
6
- §4 and §5 recommend; `examples/mcp/server.mjs` gives the
7
- agent its tools. DESIGN.md says how it works and DECISIONS.md why (the P-numbers the code cites).
8
- [THREAT_MODEL.md](THREAT_MODEL.md) says, for each use (chat widgets, live data, private and public
9
- pages, MCP Apps, previews, several displays on one page), what Porthole guarantees, what you must
10
- do, and what isn't covered: read your use's section before you show content that matters.
3
+ How to put Porthole in an app, from the npm package alone. `examples/` does all of it:
4
+ `examples/app.mjs` is the app (runtime-agnostic), run by `examples/node/server.mjs` (`nodeServer`,
5
+ §4) or `examples/workers/` (`contentHostFor`, §5); `examples/mcp/server.mjs` gives the agent its
6
+ tools. How it works: DESIGN.md. Why: DECISIONS.md (the P-numbers the code cites). Before you show
7
+ content that matters, read your use's section of [THREAT_MODEL.md](THREAT_MODEL.md) (chat widgets,
8
+ live data, private and public pages, MCP Apps, previews, several displays on one page): what is
9
+ guaranteed, what you must do, what isn't covered.
11
10
 
12
11
  ## 1. Choose how content is shown
13
12
 
@@ -34,22 +33,21 @@ export const displays = defineDisplays({
34
33
  });
35
34
  ```
36
35
 
37
- `displays.opaque(kind)`, `displays.served(contentSource)`, `displays.configFor(instance, source)`,
38
- `displays.frameSources(source, { authorizeUrl })` (a CSP built without a server: a dev server, a
39
- desktop shell) and `displays.guideConfig(kind, "served" | "opaque")` (the agent's manual) all come
40
- from it. A kind's name is the preset name its documents carry: a stored page names `artifact`
41
- unless its `document.preset` says otherwise.
36
+ It gives `displays.opaque(kind)`, `displays.served(contentSource)`,
37
+ `displays.configFor(instance, source)`, `displays.frameSources(source, { authorizeUrl })` (a CSP
38
+ without a server: a dev server, a desktop shell) and `displays.guideConfig(kind, "served" | "opaque")`
39
+ (the agent's manual). A kind's name is the preset its documents carry: a stored page names
40
+ `artifact` unless its `document.preset` says otherwise.
42
41
 
43
- **Fill:** a whole-page viewer says `layout: { kind: "fill" }`. The frame fills its box, and the
44
- manual tells the agent so (the page scrolls itself; `position: fixed` works). `MountOptions.fill`
45
- and `<PortholeFrame fill>` are deprecated: they size the frame but leave the manual saying the
46
- height follows the content.
42
+ **Fill**: `layout: { kind: "fill" }` makes the frame fill its box and tells the agent the page
43
+ scrolls itself (`position: fixed` works). The deprecated `MountOptions.fill` and
44
+ `<PortholeFrame fill>` size the frame but leave the manual saying the height follows the content.
47
45
 
48
46
  ### Choosing egress
49
47
 
50
48
  Egress is what content may load and send out: scripts, styles, fonts, images, audio and video, and
51
- data (fetch, WebSocket). Every preset starts closed, and a kind opens more only through its
52
- `options.egress`. There are three levels, and Porthole's own libraries for served content:
49
+ data (fetch, WebSocket). Every preset starts closed; a kind opens more only through its
50
+ `options.egress`. Three levels, and Porthole's own libraries for served content:
53
51
 
54
52
  | Level | Config (`options`) | What it opens | The risk it re-opens | Typical host | The agent's manual says | Why | Tested by |
55
53
  | --- | --- | --- | --- | --- | --- | --- | --- |
@@ -58,126 +56,64 @@ data (fetch, WebSocket). Every preset starts closed, and a kind opens more only
58
56
  | **Passive from any https site** (`anyHttps`, on top of either) | `egress: { ...LIBRARY_CDNS, anyHttps: ["img"] }`; closed but for them: `egress: { anyHttps: ["img"] }` | The passive kinds you name (`img`, `media`, `font`) from any https site. Never scripts, styles, data, workers or frames, and never `http:`: a config naming another kind is refused. | Any site an image names learns that someone viewed the content, and from which address; content can send data out in an image URL to a server of its choosing (the channel P006 closes); whoever owns an image controls what it shows, inside the frame. | A host showing content that already exists, with hotlinked media: Raft's HTML attachment previews, reports whose `<img>` point at other sites (the case P059 was written for). | `images from any https site` (`fonts, images, audio and video from any https site` for all three) | [P059](DECISIONS.md#p059--2026-10-11--passive-content-may-load-from-any-https-site-by-the-hosts-explicit-choice--accepted), [P062](DECISIONS.md#p062--2026-10-11--serveddomainegress-holds-a-host-to-its-own-configs-egress--accepted) | `leak/cdn.spec.ts` (a hotlinked image loads; a script, a stylesheet and a fetch to the same site never reach it; without the flag, nothing does); served `served.domain.egress` (the image must reach an https canary; scripts, styles, fetches and frames never), `leak/served/any-https.spec.ts` |
59
57
  | **Porthole's libraries** (`egress.libraries`, served kinds only; on in `presets.liveWidget`) | `egress: { libraries: true }` with `isolation: "domain"` | Chart.js 4.5.1 and D3 7.9.0 as scripts, from the frame's own origin (`/__porthole/lib/…`, served by `/server` on every content origin). Nothing from outside. | None from outside: the requests reach your content server, which serves fixed, pinned files. | Live widgets, which read your data and must have no network of their own (P079). | `Libraries, served from this frame's own address` with a `<script>` line for each | [P079](DECISIONS.md#p079--2026-10-15--live-widgets-no-network-of-their-own-portholes-libraries-on-their-origin-the-hosts-data-behind-the-viewers-consent-and-frames-that-never-navigate-away--accepted-amended-by-p084-p094-p103) | `test/libraries.test.ts`; `leak/served/live.spec.ts` (they load and draw; an external script, a stylesheet, an image and every fetch reach no oracle) |
60
58
 
61
- How to decide: **start closed; add `LIBRARY_CDNS` if agents use libraries; add passive `anyHttps`
62
- only for existing content with hotlinks**, and only the kinds it hotlinks (usually `img`). An
63
- agent writing new content can inline what it shows, so agent-made pages never need `anyHttps`.
64
-
65
- ```js
66
- import { defineDisplays, LIBRARY_CDNS } from "@botiverse/porthole";
67
-
68
- export const displays = defineDisplays({
69
- // Closed: nothing to write.
70
- widget: { preset: "inlineWidget" },
71
- // Library CDNs (and, if you need one, a script host of your own).
72
- artifact: { preset: "artifact", options: { egress: { ...LIBRARY_CDNS, script: [...(LIBRARY_CDNS.script ?? []), "https://cdn.example.com"] } } },
73
- // Existing pages with hotlinked images: Library CDNs, and images from any https site.
74
- attachment: { preset: "artifact", options: { egress: { ...LIBRARY_CDNS, anyHttps: ["img"] } } },
75
- });
76
- ```
77
-
78
- - Each kind's documents name it as their preset (`document.preset: "attachment"`); `egress` is
79
- the kind's whole policy, so kinds that differ in egress are kinds of their own.
80
- - The libraries' own CDNs serve scripts only (P078). Plotly's maps fetch their shapes from
81
- `cdn.plot.ly`, which stays closed, so the manual gives agents the copy on jsDelivr
82
- (`topojsonURL`); Tailwind's Play CDN builds its CSS in the page and needs nothing more.
83
- - Origins are exact (`https://cdn.example.com`), or `https://*.` a domain of your own; a wildcard
84
- over a public suffix (`*.com`, `*.github.io`) is refused.
85
- - An opaque frame also inherits your page's CSP ([P058](DECISIONS.md#p058--2026-10-11--an-opaque-frame-is-as-closed-as-its-page-the-suite-says-when-a-case-cant-be-observed--accepted)): where your page closes images or
86
- fetches, opaque content is that closed whatever its egress opens (see "The page's CSP"). A
87
- served frame has only its own policy.
88
- - `checkPage` and `lintContent` tell the agent when its content reaches past the kind's egress, by
89
- directive. The manual names exactly the origins the CSP allows (`test/agreement.test.ts`), and
90
- DESIGN.md § "Egress hardening, each with its test" is the long form.
59
+ **Start closed; add `LIBRARY_CDNS` if agents use libraries; add passive `anyHttps` only for
60
+ existing content with hotlinks**, and only the kinds it hotlinks (usually `img`). Agents writing new
61
+ content can inline what they show, so agent-made pages never need `anyHttps`.
62
+
63
+ - `egress` is a kind's whole policy, so kinds that differ in egress are kinds of their own, named by
64
+ their documents (`document.preset: "attachment"`). Add a script host with
65
+ `script: [...(LIBRARY_CDNS.script ?? []), "https://cdn.example.com"]`.
66
+ - The libraries' own CDNs serve scripts only (P078). Plotly's maps fetch shapes from `cdn.plot.ly`,
67
+ which stays closed, so the manual gives agents jsDelivr's copy (`topojsonURL`). Tailwind's Play CDN
68
+ builds its CSS in the page.
69
+ - Origins are exact (`https://cdn.example.com`) or `https://*.` a domain of your own; a wildcard over
70
+ a public suffix (`*.com`, `*.github.io`) is refused.
71
+ - An opaque frame also inherits your page's CSP ([P058](DECISIONS.md#p058--2026-10-11--an-opaque-frame-is-as-closed-as-its-page-the-suite-says-when-a-case-cant-be-observed--accepted)):
72
+ what your page closes stays closed, whatever egress opens ("The page's CSP"). A served frame has
73
+ only its own policy.
74
+ - `checkPage` and `lintContent` tell the agent, by directive, when content reaches past the egress.
75
+ The manual names exactly the origins the CSP allows (`test/agreement.test.ts`). Long form:
76
+ DESIGN.md § "Egress hardening, each with its test".
91
77
 
92
78
  ### Live widgets: content that reads your data
93
79
 
94
- A live widget shows your data, current, read as the person viewing it, with no network of its own
80
+ A live widget shows your data, current, read as its viewer, with no network of its own
95
81
  ([P079](DECISIONS.md#p079--2026-10-15--live-widgets-no-network-of-their-own-portholes-libraries-on-their-origin-the-hosts-data-behind-the-viewers-consent-and-frames-that-never-navigate-away--accepted-amended-by-p084-p094-p103)).
96
- Its only way out is your host: `readData` (MCP `resources/read`) and `subscribeData` (MCP
97
- `resources/subscribe`, `resources/unsubscribe`, `notifications/resources/updated`). No option opens
98
- its network: `presets.liveWidget` refuses `egress`, and a capability's own `connect` or `resource`
99
- origins (a `ConfigError` naming the option, P103); a display that needs an origin is another kind.
82
+ Its only way out is your host: `readData` (MCP `resources/read`) and `subscribeData`
83
+ (`resources/subscribe`, `resources/unsubscribe`, `notifications/resources/updated`).
84
+ `presets.liveWidget` refuses `egress` and a capability's own `connect` or `resource` origins
85
+ (`ConfigError`, P103): a display that needs an origin is another kind. Guarantees and duties:
86
+ [THREAT_MODEL.md § S2](THREAT_MODEL.md#s2-live-widgets-content-that-reads-the-hosts-data).
100
87
 
101
88
  ```js
102
- import { defineDisplays, Refused } from "@botiverse/porthole";
103
-
104
- export const displays = defineDisplays({
105
- // No egress option exists for it; served, it loads Porthole's Chart.js and D3 from its origin.
106
- tile: { preset: "liveWidget", options: { capabilities: { openLink: {} } } },
107
- });
89
+ const displays = defineDisplays({ tile: { preset: "liveWidget", options: { capabilities: { openLink: {} } } } });
108
90
 
109
91
  createHost(displays.configFor(instance, contentSource), {
110
92
  locator,
111
93
  handlers: {
112
- // As the viewer: your own access rules, never the author's. Return MCP's read result; refuse
113
- // what you don't serve with a Refused, whose code and sentence the widget shows (P080).
94
+ // As the viewer, by your access rules: MCP's read result, or a Refused (P080).
114
95
  readData: async ({ uri }, { displayId }) => {
115
96
  if (!servedUri(uri)) throw new Refused("not_allowed", "This widget can read issues only.");
116
- return {
117
- contents: [{ uri, mimeType: "application/json", text: JSON.stringify(await load(uri)) }],
118
- };
119
- },
120
- // Call changed() when it changes (the content reads it again), or changed(result) to send it:
121
- // the content's read of it then passes readData's gates, and counts against its rate (P094).
122
- subscribeData: ({ uri }, { changed, signal }) => {
123
- const stop = realtime.on(uri, () => changed());
124
- signal.addEventListener("abort", stop);
97
+ return { contents: [{ uri, mimeType: "application/json", text: JSON.stringify(await load(uri)) }] };
125
98
  },
99
+ // changed(): the content reads again. changed(result): sent, through readData's gates (P094).
100
+ subscribeData: ({ uri }, { changed, signal }) => signal.addEventListener("abort", realtime.on(uri, () => changed())),
126
101
  },
127
- // Asked once per display, before its first data call: may this widget read this viewer's data?
128
- // Remember the answer per viewer and widget; a no refuses every data call (`denied`).
102
+ // Once per display, before its first data call. Remember the answer per viewer and widget.
129
103
  consent: async ({ display }) => allowedBefore(display) ?? (await askTheViewer(display)),
130
- // Optional: your last copy, shown at once (stale), then the fresh read.
131
- cached: ({ uri }) => lastCopy(uri),
104
+ cached: ({ uri }) => lastCopy(uri), // optional: shown at once (stale), then the fresh read
132
105
  });
133
106
  ```
134
107
 
135
- - **Your handlers decide what a URI may name.** Answer only the resources you mean widgets to read
136
- (a whitelist of URI shapes), with the viewer's rights. The content's URI is its word.
137
- - **Consent is your UI.** Without a `consent` function every data call is refused (fail closed).
138
- React: `PortholeProvider` and `PortholeFrame` take `consent` and `cached`. A consent function
139
- that throws a `Refused` gives that answer, kept like `false`; anything else it throws is no
140
- answer yet (the next call asks again).
141
- - **A page where data must not run** (beside a frame that reaches the network, below): pass a
142
- `Refused` as `consent` and no data handlers. Every data call is refused with it, nothing is asked,
143
- and the widget shows your sentence:
144
-
145
- ```js
146
- createHost(displays.configFor(instance, contentSource), {
147
- locator,
148
- consent: new Refused("not_allowed", "Live data shows on the dashboard."),
149
- });
150
- ```
151
-
152
- Any other capability you declare still needs its handler.
153
- - **Refusals tell the widget why** (P080). A refused call's JSON-RPC error carries
154
- `data: { code, message }`; the shell's `readData` rejects (and `subscribeData`'s `onError` is
155
- called) with an `Error` whose `code` and `message` are those. `code` is `consent_required` (no
156
- answer yet), `denied` (the viewer said no), `rate_limited`, `not_allowed` (not here, or not this
157
- URI) or `failed` (your handler threw); `message` is your `Refused`'s sentence, else Porthole's.
158
- The manual tells the agent to draw the widget without the data, with that sentence. A handler's
159
- other errors are `failed` in Porthole's words: their messages stay yours.
160
- - **Rates stay gates**: 120 reads and 60 subscriptions a minute per display by default; change them
161
- with the capability's `gates` (keep `"consent"` in the list). Every read counts, a read your
162
- `changed(result)` answers too (P094): a widget that follows a resource changing faster than
163
- twice a second needs a higher read rate.
164
- - **Your page's CSP**: send `displays.embedderCsp(source, …)` (`frame-src` of your content origins
165
- and the authorize route, nothing else). It keeps a frame from navigating to an outside site; the
166
- shell keeps a served frame from navigating to another content origin (P079), and tells you:
167
- `display.on("navigationBlocked", ({ url }) => …)` (React `onNavigationBlocked`) gets the address
168
- whole, and `contentError` a sentence naming it without its query, for the agent (P080). Only
169
- where the config declares `reportError`, and only served frames: an opaque frame's navigations
170
- get no events (you hear `navigated` when one replaces its document).
171
- - **Keep live widgets off pages with frames that reach the network.** A frame can `postMessage` any
172
- frame on its page, and nothing in it can stop that: a url-mode app (a dev server's preview) or an
173
- `anyHttps` display beside a live widget could be handed what it read. Displays with closed egress
174
- or `LIBRARY_CDNS` are fine beside it. The rule for any page: its egress is the union of its
175
- frames' ([THREAT_MODEL.md § S7](THREAT_MODEL.md#s7-several-displays-on-one-page)).
176
- - **Opaque live widgets** (no content domain) work, without libraries: the manual tells the agent
177
- to draw with SVG and CSS. An opaque frame's only wall against navigating itself away is your
178
- page's `frame-src` (the shell's guard gets no events in an opaque origin), so show them on pages
179
- that frame no content origins (`frame-src 'none'`), which is what `defineDisplays` gives a page
180
- without a content domain.
108
+ | What | How |
109
+ | --- | --- |
110
+ | What a URI may name | Your handlers decide, with the viewer's rights; the content's URI is its word. |
111
+ | Consent is your UI | With no `consent` every data call is refused; a no refuses them all (`denied`). A thrown `Refused` is that answer, kept like `false`; any other throw is no answer yet. Where data must not run, pass a `Refused` as `consent` (`new Refused("not_allowed", "Live data shows on the dashboard.")`) and no data handlers: nothing is asked and the widget shows your sentence. Other capabilities still need their handlers. React: `PortholeProvider` and `PortholeFrame` take `consent` and `cached`. |
112
+ | Refusals say why (P080) | The call rejects with an `Error` whose `code` is `consent_required`, `denied`, `rate_limited`, `not_allowed` or `failed` (your handler threw) and whose `message` is your `Refused`'s sentence, else Porthole's; a handler's other errors stay yours. The manual has the agent draw the widget without the data, with that sentence. |
113
+ | Rates | 120 reads and 60 subscriptions a minute per display, set in the capability's `gates` (keep `"consent"`). `changed(result)` counts as a read (P094): a resource changing more than twice a second needs a higher read rate. |
114
+ | Your page's CSP | Send `displays.embedderCsp(source, …)`. The shell stops a served frame's navigation to another content origin (P079); with `reportError` declared you get `display.on("navigationBlocked", ({ url }) => …)` (React `onNavigationBlocked`) and the agent gets `contentError` (P080). An opaque frame's navigations raise no events. |
115
+ | Neighbours | Any frame can `postMessage` the widget's, so keep live widgets off pages with frames that reach the network (a url-mode app, an `anyHttps` display). Closed and `LIBRARY_CDNS` displays are fine ([THREAT_MODEL.md § S7](THREAT_MODEL.md#s7-several-displays-on-one-page)). |
116
+ | Opaque live widgets (no content domain) | They draw with SVG and CSS. Show them only on pages that frame no content origins (`frame-src 'none'`, which `defineDisplays` gives a page without one). |
181
117
 
182
118
  ## 3. Opaque displays: the page only
183
119
 
@@ -195,72 +131,54 @@ display.setContent(agentHtml); // once whole: it runs, once
195
131
  display.on("contentError", ({ message }) => tellTheAgent(message));
196
132
  ```
197
133
 
198
- React: `<PortholeProvider>` near the root; `<PortholeFrame config displayId title content partial />`
199
- per display. The provider takes what every frame shares: `scheme`, `theme` (and `themeKey`;
200
- `cssVariableTheme(tokens)` reads the values from your page's CSS variables), `nonce` (`"auto"`
201
- reads the page's), `handlers`, `openLink` (default: a new tab), `notify` (your own toast for what
202
- a copy button copied), and `renderConfirm` (your own dialog, given `accept`, `decline` and
203
- `redirect`: Porthole keeps the queue, runs `accept` inside its click, and counts declines toward
204
- muting the display; `redirect`, for "edit it first", answers the call `"redirected"` and neither
205
- counts nor resets the count). The request names the display (`request.display`: its `id`,
206
- `title`, and the `instance` you gave the frame, served or opaque), so the dialog can say what it
207
- is from your own records. It stays on your side: an opaque frame never gets the instance. `useRunAgain()` gives a "run again" button.
134
+ React: `<PortholeProvider>` near the root, `<PortholeFrame config displayId title content partial />`
135
+ per display. The provider holds what frames share: `scheme`, `theme` and `themeKey`
136
+ (`cssVariableTheme(tokens)` reads your page's CSS variables), `nonce` (`"auto"` reads the page's),
137
+ `handlers`, `openLink` (default: a new tab), `notify` (your toast for what a copy button copied) and
138
+ `renderConfirm` (your dialog, given `accept`, `decline` and `redirect`). Porthole keeps the queue,
139
+ runs `accept` inside its click and counts declines toward muting the display; `redirect` ("edit it
140
+ first") answers `"redirected"` and neither counts nor resets the count. `request.display` gives the
141
+ display's `id`, `title` and the `instance` you gave the frame (never sent to an opaque frame), so the
142
+ dialog can name it from your records. `useRunAgain()` gives a "run again" button.
208
143
 
209
144
  ### Context for the agent (`setModelContext`)
210
145
 
211
- A widget or an MCP Apps view may tell the agent what the person is looking at
212
- (`ui/update-model-context`, the App SDK's `app.updateModelContext`). That is the content's text,
213
- in your model's next turn, so by default the person is shown every update first (the `show` gate,
214
- [P100](DECISIONS.md#p100--2026-10-19--what-content-tells-the-model-the-person-is-shown-first-the-show-gate-on-by-default-for-setmodelcontext--accepted)): pass `show`. It gets the whole update (`request.args`: text blocks and
215
- structured content, at most `MAX_CONTEXT_CHARS` together) and the display, before your handler,
216
- and draws it outside the frame: the latest per display, since each replaces the last. Without
217
- `show` every update is refused (fail closed). React: `PortholeProvider` draws `ContextNotice`
218
- unless you pass your own `show`.
146
+ A widget or MCP Apps view may tell the agent what the person sees (`ui/update-model-context`, the
147
+ App SDK's `app.updateModelContext`). By default the person sees each update first: the `show` gate
148
+ ([P100](DECISIONS.md#p100--2026-10-19--what-content-tells-the-model-the-person-is-shown-first-the-show-gate-on-by-default-for-setmodelcontext--accepted)).
149
+ Before your handler, `show` gets the display and the whole update (`request.args`: text blocks and
150
+ structured content, at most `MAX_CONTEXT_CHARS` together) and draws it outside the frame (the latest
151
+ per display). Without `show` every update is refused. React: `PortholeProvider` draws
152
+ `ContextNotice` unless you pass your own `show`.
219
153
 
220
154
  ```js
221
155
  createHost(config, {
222
156
  handlers: { setModelContext: (update, { displayId }) => modelContext.set(displayId, update) },
223
- // Before the handler has it: the person sees what the agent will read.
224
- show: ({ args, display }) => composer.contextChip(display.id, display.title, args),
157
+ show: ({ args, display }) => composer.contextChip(display.id, display.title, args), // before the handler
225
158
  });
226
159
  ```
227
160
 
228
- - **Give it to the model as the content's words** ("the view “Signups” says: …"), never as the
229
- person's message or as instructions. The manual tells the agent the same.
230
- - **Send it with the person's next message** (MCP Apps lets a host defer it), so they have seen it
231
- before the model reads it. If your agent takes turns on its own, add `"confirm"` to the gates.
232
- - **Opting out**: `setModelContext: { gates: [{ rateLimit: { perMinute: 30 } }], withoutShow: true }`
233
- names the gates without `show`, and says so on purpose. Do it only where your handler itself puts
234
- the text in front of the person (or the content is your own): otherwise the content writes into
235
- your model's turns unseen. Gates named without `show` and without `withoutShow` (a 0.7 config
236
- that set its own rate) earn the warning `model-context-unshown`, which you see only if you read
237
- it: Porthole logs nothing, anywhere. Read `host.compiled.warnings` (or `compile(config).warnings`,
238
- `configWarnings(config)`) at startup, or pass `validateConfig(config, { onWarning })`, and log
239
- or fail on what you find; otherwise nothing tells you.
240
- - **What can't be seen is refused**: an update with an invisible character (zero-width ones, bidi
241
- controls, variation selectors, tag or private-use characters, controls other than new lines and
242
- tabs), in its text or any string of its structured content, never reaches `show` or your
243
- handler. Real emoji pass (☀️, 👨‍👩‍👧, 👩🏽‍💻, 1️⃣): a selector right after a pictograph or in a
244
- keycap, a joiner between two pictographs. So do joiners that shape letters: U+200C or U+200D
245
- between two letters or marks of Arabic, Syriac, N'Ko, Mongolian, the Indic scripts, Sinhala or
246
- Myanmar (Persian's می‌خواهم). Subdivision flags (tag characters) don't. Your own `show` resolves only once that very update is visible: if a later update of
247
- the display replaces it before it is drawn, reject, and it doesn't go.
161
+ | What | How |
162
+ | --- | --- |
163
+ | **Give it to the model as the content's words** | For example "the view “Signups” says: …"; never as the person's message or as instructions, and with their next message (MCP Apps lets a host defer it). If your agent takes turns on its own, add `"confirm"` to the gates. |
164
+ | **Your own `show`** | Resolve only once that very update is visible; if a later one replaces it before it is drawn, reject, and it doesn't go. |
165
+ | **Opting out** | `setModelContext: { gates: [{ rateLimit: { perMinute: 30 } }], withoutShow: true }`, only where your handler itself shows the text to the person (or the content is your own). Gates named without `show` or `withoutShow` earn the warning `model-context-unshown`. Porthole logs nothing: read `host.compiled.warnings` (or `compile(config).warnings`, `configWarnings(config)`) at startup, or pass `validateConfig(config, { onWarning })`. |
166
+ | **Invisible characters are refused** | An update with one in its text or any string of its structured content (zero-width, bidi controls, variation selectors, tag or private-use characters, controls but new line and tab) never reaches `show` or your handler. Real emoji pass (☀️, 👨‍👩‍👧, 👩🏽‍💻, 1️⃣: a selector after a pictograph or in a keycap, a joiner between two pictographs), as do U+200C and U+200D between letters or marks of Arabic, Syriac, N'Ko, Mongolian, the Indic scripts, Sinhala or Myanmar (Persian's می‌خواهم). Subdivision flags (tag characters) don't. |
248
167
 
249
168
  ### Annotations: comments on a display
250
169
 
251
- With `annotate` declared (`capabilities: { annotate: {} }`), a host lets people point at a
252
- display and keeps its comments beside it ([P053](DECISIONS.md), P104). Everything the frame
253
- reports is the page's word: a hint where to draw, never a permission. A mark's `count` puts a
254
- numbered marker, a button, at the end of its words' paragraph (P133); a click on one, or Enter or
255
- Space with the keyboard on it, is `activated`. A draft, a comment its author hasn't posted yet
256
- (`kind: "draft"`, P107), is drawn apart, beside its own words: a dashed line and a hollow marker
257
- with no number, which is clicked and followed as a posted one is.
170
+ With `annotate` declared (`capabilities: { annotate: {} }`), people point at a display and you keep
171
+ their comments beside it (P053, P104). A mark with a `count` gets a numbered marker button at the
172
+ end of its words' paragraph (P133); a click, Enter or Space on it is `activated`. A draft
173
+ (`kind: "draft"`, not yet posted, P107) gets a hollow marker and no number, and is clicked and
174
+ followed like a posted mark. Every report is the page's word: a hint where to draw, never a
175
+ permission. How it works: [DESIGN.md § Annotations](DESIGN.md#annotations). What a page learns and
176
+ can fake: [THREAT_MODEL.md §7](THREAT_MODEL.md#7-the-display-layer-and-the-app-runtime).
258
177
 
259
178
  ```js
260
179
  display.annotations.show([
261
180
  ...comments.map((c) => ({ id: c.markId, anchor: c.anchor, count: c.replies })),
262
- // Only in the author's own frame: the page can read that these are drafts.
263
- ...myDrafts.map((d) => ({ id: d.markId, anchor: d.anchor, kind: "draft" })),
181
+ ...myDrafts.map((d) => ({ id: d.markId, anchor: d.anchor, kind: "draft" })), // author's frame only
264
182
  ]);
265
183
  display.annotations.start({ elements: false, text: true }); // comment mode: the person selects words
266
184
  display.on("annotation", (report) => {
@@ -268,81 +186,33 @@ display.on("annotation", (report) => {
268
186
  if (report.type === "activated") bubble.openBeside(frame, report.rect, report.id);
269
187
  if (report.type === "anchored") bubble.follow(report.results);
270
188
  });
271
- // The composer closed, whatever came of it (posted, a draft added, dismissed): take the selection,
272
- // and its highlight, away. The page sees the clear: never clear only when a draft is added.
273
- composer.onClose(() => display.annotations.clearSelection());
189
+ composer.onClose(() => display.annotations.clearSelection()); // however it closed
274
190
  ```
275
191
 
276
- - **Clear the selection when the composer closes, every time** (`annotations.clearSelection()`,
277
- P115): the page's text selection, and the highlight the browser leaves on it (gray while focus
278
- is in your composer), stay until something clears them; the person's next click in the page
279
- would, and this does it when your composer is done with it. The page sees the clear (the
280
- message, and a `selectionchange` with no press of its own), so it learns when the person was
281
- done with its words (P121): clear on every close, kept or dismissed, or as the composer opens
282
- (which tells it nothing `selected` and its blur didn't), or leave it to their next click; never
283
- only when a draft is added, which tells the page that a draft exists there, and when. Above all
284
- for a page `mayPassOn` says to keep drafts from (below). No `unselected` follows it (you know), and nothing else
285
- changes: your marks and drafts, the mode (`start`) and a followed mark stay. With nothing
286
- selected it does nothing; it is never sent to a frame that runs later (a reload has no selection
287
- to clear). Like `start` and `show`, only where the config declares `annotate`. The shell is your
288
- content server's: an older one ignores it.
289
-
290
- - **React** (P118): `PortholeFrame` and `PortholeView` take the same as props: `annotating`,
291
- `annotations`, `focusedAnnotation` and `trackedAnnotation` (the mark to follow, by value; `null`
292
- stops), `trackedSelection` (true while your composer is open: the selection is followed in the
293
- mark's place, P138; give it from the first render, `false` until then, so the mode starts with
294
- `keepSelection`, P140: it is read as the mode starts, and giving it later restarts nothing), every report through `onAnnotation` (`tracked` and `selectionTracked` too). The selection is cleared through a
295
- ref, which holds `clearSelection()` only (a `PortholeFrameHandle`; never the display, whose life
296
- is the binding's); with no display running it does nothing. Errors the core's calls throw (an id
297
- no shown mark has, a config without `annotate`) reach `onHostError`, kind `"annotations"`.
298
-
299
- ```tsx
300
- const frame = useRef<PortholeFrameHandle>(null);
301
- <PortholeView ref={frame} display="page" instance={instance} displayId={id} title={title}
302
- annotating={commenting ? { elements: false, text: true } : null}
303
- annotations={marks} trackedAnnotation={openCard?.markId ?? null}
304
- onAnnotation={(report) => {
305
- // The page moves its mark, and so the card, at will: armed again as it moves (§6, P121).
306
- if (report.type === "tracked" && card.moveBeside(report.rect) > 4) cardGuard.placed();
307
- if (report.type === "selected") composer.openBeside(report.rect, report.anchor);
308
- }} />
309
- // cardGuard = guardPresses(card.element) (below); moveBeside answers how far it moved, in px.
310
- composer.onClose(() => frame.current?.clearSelection()); // every close, kept or dismissed
311
- ```
192
+ **React** (P118): `PortholeFrame` and `PortholeView` take `annotating`, `annotations`,
193
+ `focusedAnnotation`, `trackedAnnotation` (the mark to follow, by value; `null` stops),
194
+ `trackedSelection` (from the first render, `false` until then: it is read as the mode starts, P140)
195
+ and `onAnnotation`. `clearSelection()` and `focusMark(id)` are on the `ref` (a `PortholeFrameHandle`,
196
+ not the display) and do nothing with no display running. Errors the core's calls throw (an id no
197
+ shown mark has, a config without `annotate`) reach `onHostError`, kind `"annotations"`.
312
198
 
313
- - **Ids say nothing, and a count only where the page may know it**: the content reads every
314
- `show`. Who wrote what stays in your view, outside the frame.
315
- - **Drafts only to their author's frame**: the page reads which marks are drafts (that its viewer
316
- is writing a comment there), so send a person's drafts only to the frame that person is viewing,
317
- never one shared with others. A draft's `count` is dropped before the frame (no number is
318
- drawn), so give a draft's id at random like any other; a `kind` other than `"posted"` or
319
- `"draft"` throws, as a bad anchor does (React: `onHostError`, kind `"annotations"`). The shell
320
- is your content server's: upgrade its Porthole first, or an older shell draws a draft as a
321
- posted mark without a marker. The view a draft's `activated` opens is guarded like any (below)
322
- and puts no "Post", "Submit review" or "Discard" one click away: a page can say that click
323
- itself, at a moment it picks (P107; no gesture is asked of it since 0.16.0, P149).
324
- - **No drafts to a page that can pass them on**, or accept that it does: a page with the runtime's
325
- `db` writes and `user` can store who is drafting where (`user.get()` and the marks it is shown)
326
- for its author and other viewers to read before the draft is posted, and tie the posted comment
327
- to its author after; origins its config declares for egress (an MCP App's `connectDomains`, an
328
- `egress` you opened) can carry the same out. Send
329
- drafts only to pages without such a channel (annotations, `copyText`, `openLink` and the like),
330
- or accept that the page's author and other viewers can learn of them (THREAT_MODEL §7). Ask
331
- `host.mayPassOn(declaration)` (or `mayPassOn(config, declaration)`, P112): true for a page that
332
- can reach `db`, `artifact`, `assets`, `openLink`, `sendPrompt`, `setModelContext`, `callTool`,
333
- `readData` or `subscribeData` (or `reportError` with errors to the agent), or egress beyond the
334
- library CDNs (whose paths only their operators read); show such a page no draft marks.
335
- - **The content chooses when your view opens and where** (it can post `activated` for a mark you
336
- show on the person's own press in the content, under their pointer, P105), so a view that a
337
- report opens or moves (a card that follows a `tracked` mark included, each time it moves more
338
- than a few px: the page moves it at will, up to 60 times a second) takes no press of any kind
339
- for 500 ms after it appears or moves (no
340
- `pointerdown`, `pointerup`, `click` or key: menu triggers act on a press, and menu items click
341
- themselves on a release), ignores a press that began before that, opens beside the frame rather
342
- than over `rect` where the layout allows, takes no focus (unless it meets the conditions of
343
- THREAT_MODEL §6's exceptions), and has nothing one click away that
344
- posts, submits, resolves, deletes or discards. Making it `inert` while it arms does all of the
345
- first:
199
+ What the host must do (why: THREAT_MODEL.md §6 "What every host must do"):
200
+
201
+ | Duty | How |
202
+ | --- | --- |
203
+ | **Clear the selection on every close of the composer** | Kept or dismissed (`annotations.clearSelection()`, P115), or as it opens, or leave it to the person's next click. Never only when a draft is added: the page sees the clear (P121) and would learn a draft exists there, and when. Nothing else changes (marks, drafts, the mode, a followed mark). An older shell ignores it. |
204
+ | **Ids say nothing; counts only where the page may know them** | The content reads every `show`; who wrote what stays outside the frame. |
205
+ | **Drafts only in their author's frame** | Never a shared one: the page reads which marks are drafts. A draft's `count` is dropped before the frame; give its id at random like any other. A `kind` other than `"posted"` or `"draft"` throws. Upgrade the content server first: an older shell draws a draft as a posted mark without a marker. |
206
+ | **No drafts to a page that can pass them on** | Or accept that its author and other viewers can learn of them. `host.mayPassOn(declaration)` (or `mayPassOn(config, declaration)`, P112) is true for a page that can reach `db`, `artifact`, `assets`, `openLink`, `sendPrompt`, `setModelContext`, `callTool`, `readData` or `subscribeData` (or `reportError` with errors to the agent), or egress beyond the library CDNs. |
207
+ | **Labels and quotes are the page's text** | Show them as text, and give them to a model only as the page's words. A label omits what the person can't see; a quote (`exact`) keeps it. |
208
+
209
+ - **Guard every view a report opens or moves** (`activated`, `selected`, a card following a `tracked`
210
+ mark each time it moves more than a few px): the content picks the moment and the place (P105).
211
+ For 500 ms after it appears or moves, the view takes no press (`pointerdown`, `pointerup`, `click`
212
+ or key) and ignores one begun before. It opens beside the frame rather than over `rect` where the
213
+ layout allows, takes no focus (but for THREAT_MODEL §6's exceptions), and has nothing one click away
214
+ that posts, submits, resolves, deletes or discards (a draft's view too: no "Post", "Submit review"
215
+ or "Discard"). Making it `inert` while it arms does the first part:
346
216
 
347
217
  ```js
348
218
  // Call placed() each time the view appears or moves. For 500 ms it takes nothing (inert: no
@@ -380,287 +250,99 @@ composer.onClose(() => display.annotations.clearSelection());
380
250
  }
381
251
  ```
382
252
 
383
- Menus and popovers the view opens are part of it, but a portaled one (Base UI's, Radix's) is
384
- drawn outside it, where this guard doesn't reach: give it a container inside the view (both take
385
- one, `container`), or pass that container to `guardPresses` too, and close it each time the view
386
- appears or moves.
387
-
388
- - **Boxes are in the frame's CSS px**, clamped to its viewport (P104): add the frame element's
389
- position. A frame you scale or transform (a thumbnail, a zoomed preview) needs the box mapped
390
- through that transform too (`frame.getBoundingClientRect().width / frame.clientWidth` for a
391
- plain scale), or your view lands off by the difference.
392
- - **Places in the document** (P132): for UI that lines up with marks outside the frame's view
393
- (comment cards in a margin beside a scrolling page), a newer shell gives each attached result a
394
- `documentRect` (its box in the document: it doesn't move as the page scrolls, and isn't clamped)
395
- and each `anchored` report the `scroll` it was read at; `tracked` carries both too, so following
396
- one mark (`track`) tells the scroll at every animation frame where it changed, whether that mark
397
- is in view or not. A mark's top in the frame's viewport is then `documentRect.y - scroll.y`, with
398
- no need to ask again as the page scrolls. The numbers are the page's word, and unclamped: clip
399
- what you draw from them to the frame's box, or to your own region beside it. An older shell sends
400
- neither: test for `scroll` and keep the viewport boxes' way where it is absent.
253
+ Portaled menus and popovers (Base UI's, Radix's) are drawn outside the view, beyond the guard: give
254
+ them a `container` inside it (both take one) or pass that container to `guardPresses` too, and
255
+ close them each time the view appears or moves.
401
256
 
402
- ```js
403
- const tops = new Map(); // mark id → its top in the document
404
- let scrollY = null; // null: an older shell, places by `rect` only
405
- display.on("annotation", (report) => {
406
- if (report.type !== "anchored" && report.type !== "tracked") return;
407
- if (report.scroll) scrollY = report.scroll.y;
408
- if (report.type === "anchored") {
409
- for (const result of report.results) {
410
- if (result.documentRect) tops.set(result.id, result.documentRect.y);
411
- else tops.delete(result.id); // orphaned
412
- }
413
- }
414
- if (scrollY !== null) margin.place(tops, scrollY); // card top: frame top + top - scrollY, clipped
415
- });
416
- display.annotations.track(anyShownMarkId); // its reports carry the scroll
417
- ```
257
+ Where to draw:
418
258
 
419
- A page that scrolls a box of its own rather than its document moves the places of the marks in
420
- it as it scrolls; show again (or follow such a mark) to hear them again.
421
- - **After the last line** (P133): for UI after a selection's or a mark's words rather than beside
422
- their whole box (a composer's button, a card), a newer shell gives `selected`, each attached
423
- result and `tracked` a `lastLineDocumentRect`: the last line with words on it, in the document's
424
- coordinates (an element's whole box: it has no lines), unclamped as `documentRect` is. `selected`
425
- carries the `scroll` it was read at too; an `anchored` report and `tracked` already do, and
426
- `createHost` drops a report with a last line and no `scroll`, so where you have the line you have
427
- the scroll (P137). A line's end in the frame's viewport is `x + width - scroll.x`, its bottom
428
- `y + height - scroll.y`. Clip what you draw from it, as above, and keep `rect` where it is absent
429
- (an older shell):
259
+ | What | How |
260
+ | --- | --- |
261
+ | **Boxes** (`rect`, P104) | In the frame's CSS px, clamped to its viewport: add the frame element's position and map them through any transform on the frame (`frame.getBoundingClientRect().width / frame.clientWidth` for a plain scale). |
262
+ | **Places in the document** (P132) | `tracked` and each attached result of `anchored` carry a `documentRect` (unclamped, fixed as the page scrolls) and the report's `scroll`. A mark's top in the frame's viewport is `documentRect.y - scroll.y`, so margin cards need no new ask. A box the page scrolls itself moves its marks: show again, or follow the mark, to hear where. Clip what you draw to the frame's box or your region beside it. An older shell sends neither: test for `scroll`, else place by `rect`. |
263
+ | **A composer that follows the selection** (P138, P140) | Start with `keepSelection: true` (React: while you give `trackedSelection`) and on `selected` call `annotations.track({ selection: true })`. The frame highlights the selection and reports `selectionTracked` as `tracked` reports a mark (at most 60 a second, the same boxes, and `inView`: hide the composer while it is false). `state: "orphaned"`: it left the page; keep the person's words. One thing is followed at a time; `track(null)`, a mark's id or `clear` ends it. End it on every close, as you clear the selection (the frame's own Escape doesn't), and guard the composer as it moves. Ask for the follow before a `start` or `stop` you send as the composer opens (React orders them so). Without `keepSelection`, a follow asked after `selected` answers `orphaned`. An older shell sends no `selectionTracked`: place by `selected` until the first one. |
430
264
 
431
- ```js
432
- display.on("annotation", (report) => {
433
- if (report.type !== "selected") return;
434
- const line = report.lastLineDocumentRect;
435
- const at = line
436
- ? { x: line.x + line.width - report.scroll.x, y: line.y + line.height - report.scroll.y }
437
- : { x: report.rect.x + report.rect.width, y: report.rect.y + report.rect.height };
438
- composer.openAt(frame, clipToFrame(at), report.anchor); // the frame's px: clip them, then add its position
439
- });
440
- ```
441
- - **A composer that stays beside what it is for** (P138, P140): `selected` comes once for a pick
442
- (and for words again only once a scroll settles), and by default a pick's outline goes with it
443
- and the frame keeps nothing of it. To follow it, start with `keepSelection: true`
444
- (`annotations.start({ elements: true, keepSelection: true })`; React does it while you give
445
- `trackedSelection`), so the frame keeps what is picked or selected, then follow the selection
446
- while your composer is open, `annotations.track({ selection: true })` (React:
447
- `trackedSelection`). The frame highlights it (a picked element in the picking outline) and
448
- reports `selectionTracked` as `tracked` reports a mark: at most 60 a second, its `rect` clamped,
449
- `documentRect`, `lastLineDocumentRect` and `scroll` as above, and `inView`, so you hide the
450
- composer (and show your own marker at the frame's edge, from `documentRect` and `scroll`, clipped)
451
- while it is out of view. `state: "orphaned"`: it isn't in the page now (a re-render took it out;
452
- a reload); keep the person's words, it may be found again. Without `keepSelection`, a follow
453
- asked after `selected` has nothing to follow and answers `orphaned`; one asked before the pick
454
- follows each selection made while it lasts. It follows the latest `selected`, so a new pick or
455
- selection moves it. One thing is followed at a time: it takes a followed mark's place, and
456
- `track(null)`, a mark's id or `clear` ends it, the highlight with it. End it on every close
457
- (posted, dismissed, Escape in your composer: the frame's own Escape doesn't end it), as you
458
- clear the selection: the page reads when it starts and ends, so an end on every close says
459
- nothing of what came of it. The composer moves at the page's word: guard it as below, armed
460
- again each time it moves or shows again. An older shell sends nothing (and draws nothing): place
461
- by `selected` until the first `selectionTracked`, which a newer one sends at its next animation
462
- frame. Under `keepSelection` a newer shell keeps the picked element outlined from the pick on,
463
- so there is no gap before the follow's highlight; ask for the follow before a `start` or `stop`
464
- you send as the composer opens (React orders them so), or the stop ends that outline a moment
465
- before the follow draws it again. Until the follow comes, the outline ends as a selection does
466
- (the next pick, Escape, `clearSelection`, `start`, `stop`, `clear`). Without `keepSelection` the
467
- outline goes with the pick, as before 0.14.15. While you follow the selection, `selected` isn't
468
- re-sent after a scroll: read where it is from `selectionTracked`; and while you don't, a
469
- `selectionTracked` from the page is dropped unread.
265
+ **After the last line** (P133), for UI after a selection's or a mark's words (a composer's button):
266
+ `selected`, each attached result and `tracked` carry `lastLineDocumentRect`, the last line with words
267
+ (an element's whole box), unclamped. `createHost` drops a report with a last line and no `scroll`,
268
+ so where you have the line you have the scroll (P137). Clip it; use `rect` where it is absent (an
269
+ older shell):
470
270
 
471
- ```js
472
- display.annotations.start({ elements: true, text: true, keepSelection: true });
473
- display.on("annotation", (report) => {
474
- if (report.type === "selected") {
475
- composer.openBeside(frame, report.rect, report.anchor); // as before: an older shell stops here
476
- display.annotations.track({ selection: true });
477
- }
478
- if (report.type !== "selectionTracked") return;
479
- if (report.state === "orphaned") return composer.detach(); // keep its words
480
- if (!report.inView) return composer.collapseToMarker(report.documentRect, report.scroll);
481
- if (composer.moveBeside(frame, report.rect) > 4) composerGuard.placed();
482
- });
483
- composer.onClose(() => {
484
- display.annotations.track(null); // or the open card's mark: track(cardId)
485
- display.annotations.clearSelection();
486
- });
487
- ```
488
- - **The keyboard** (P133): each marker is a button in the frame's Tab order, after the page's own
489
- stops, in reading order, named for what it is (`3 comments on "the words"`, from the `count` and
490
- the anchor's words, without an element's tag, P134; in English, whatever your UI's language). The
491
- `label` you store keeps its tag. Enter or Space on it is `activated`,
492
- through the same path as a click: nothing to handle apart. It is the
493
- page's focus order, which a page can steal from or hide a marker from, and it is one more
494
- `activated` the content can time: keep your own list of marks as the way a keyboard can rely on,
495
- with `annotations.focus(id)` to bring one into view, and leave your view's guard as it is (it
496
- takes no key for 500 ms either, and takes no focus: Enter again on the marker is one more
497
- `activated`).
498
- - **Key or pointer, and back to the marker** (P134). `activated` doesn't say what made it. Read
499
- your own page as it arrives, in the listener: `document.activeElement === container.querySelector("iframe")`
500
- (a shadow root of yours: its `activeElement`). True means the focus is in the frame, as it is
501
- for a key on a marker; a pointer's press on a marker moves no focus, so a click from outside
502
- reads false. The page can't change that reading, but it is a hint, not a proof: a click after the
503
- person was already in the frame reads true, the page can put the focus in its frame itself, and it
504
- can forge `activated` while the person really is there, which this doesn't stop. So moving the
505
- keyboard into your view on it is your own step outside "takes no focus" above, and a page can
506
- bring it about: gate whatever posts from that view (a Reply in a frame-opened card) yourself;
507
- Porthole can't. That goes for keys too: with the focus in your view the person's next keys reach
508
- your document, so the view's own key handlers and your page-wide shortcuts that write (an `r` that
509
- resolves, Cmd+Enter that posts) need the same gate (P137). When the person's key closes your view
510
- of that mark from inside it (Escape, or a
511
- Tab past its first or last control), whether or not the keyboard got there through `activated`,
512
- and only then, close it and call
513
- `display.annotations.focusMark(id)` (React: `focusMark(id)` on the `ref`) to put the keyboard back
514
- on the marker. It carries no content and reports nothing; an id with no marker, or a marker the
515
- page has moved away, does nothing and throws nothing; the page can take the focus straight back.
516
- Keep your own list of marks as the way that holds.
517
- On a calm page that lands at once, from your `<body>`. While the frame is finding its marks (a
518
- `show` just sent, which many hosts send as a card closes, or content that just changed) the word
519
- waits, up to a second, and is then dropped unless the focus is in the frame by then. A word the
520
- frame takes more than 100 ms after you sent it, because its page is busy, is held to the same
521
- test. So a late word takes no keyboard from a person who moved on ([P135](DECISIONS.md),
522
- [P137](DECISIONS.md)). As your card has just closed, the focus is on your `<body>`, so a word that
523
- waited or came late is dropped, and nothing tells you: **call `focusMark` again after your own
524
- move of the focus into the frame.** Call it as your close runs, not after other work: its age
525
- starts when you call it, and where the browser runs the frame on your thread, what your task does
526
- next counts too.
271
+ ```js
272
+ display.on("annotation", (report) => {
273
+ if (report.type !== "selected") return;
274
+ const line = report.lastLineDocumentRect;
275
+ const at = line
276
+ ? { x: line.x + line.width - report.scroll.x, y: line.y + line.height - report.scroll.y }
277
+ : { x: report.rect.x + report.rect.width, y: report.rect.y + report.rect.height };
278
+ composer.openAt(frame, clipToFrame(at), report.anchor); // the frame's px: clip them, then add its position
279
+ });
280
+ ```
527
281
 
528
- ```js
529
- closeCard();
530
- display.annotations.focusMark(id);
531
- setTimeout(() => {
532
- // Not on the marker, and the person hasn't moved on: the frame was busy.
533
- if (document.activeElement === document.body) {
534
- display.focus();
535
- display.annotations.focusMark(id);
536
- }
537
- }, 200);
538
- ```
282
+ **Where an element was picked** (P150): an element pick by a click or tap also carries `pointDocument`
283
+ (with `scroll`), the point it was picked at in the same coordinates. Where the element fills most of
284
+ the frame, place your UI at `pointDocument.x - scroll.x`, `pointDocument.y - scroll.y`, clipped. A
285
+ pick from the keyboard, a text selection and an older shell send none.
539
286
 
540
- Keep the check: on a button of yours, the person has moved on, and `display.focus()` would take the
541
- keyboard from them. With React, whose `ref` has no `focus()`, call the frame's own `focus()` for
542
- that step. An id with no marker then leaves the focus in the frame, with the keys going to the
543
- page.
287
+ The keyboard:
544
288
 
545
- Without the second call, nothing changes on a calm page. On a busy one, a word that the frame
546
- finishes with before your own move is lost where it used to land, so the person gets the frame and
547
- not the marker. That is the cost of never pulling the keyboard into the page. Upgrade the host and
548
- the content server together: a newer shell takes a word from an older `createHost`, which has no
549
- stamp, as a late one (the second call still lands), and an older shell ignores the stamp.
550
- - **Labels and quotes are the page's text**: shown only as text. Porthole takes out of a label what
551
- the person can't see; a quote (`exact`) keeps it, to be found again. Hand either to a model only
552
- as the page's words.
289
+ | Case | What to do |
290
+ | --- | --- |
291
+ | **Markers are buttons** (P133, P134) | In the frame's Tab order after the page's own stops, named for what they are (`3 comments on "the words"`, in English); Enter or Space is `activated`. The page owns that focus order and can steal from it: keep your own list of marks as the keyboard path that holds (`annotations.focus(id)` brings one into view), and keep your view's guard. |
292
+ | **Key or pointer** (P134) | `activated` doesn't say which. `document.activeElement === container.querySelector("iframe")` (in a shadow root of yours, its `activeElement`) is true when focus is in the frame, as after a key on a marker; a pointer's press moves no focus. It is a hint, not proof: the page can focus its frame and forge `activated`. Moving the keyboard into your view on it is THREAT_MODEL §6's second exception: gate whatever posts from that view yourself, its key handlers and your page-wide shortcuts that write included (P137). |
293
+ | **Back to the marker** (P134, P135, P137) | Only when the person's key closes your view of a mark from inside it (Escape, or Tab past its ends): close it and call `display.annotations.focusMark(id)` at once. It carries no content and reports nothing; an id with no marker does nothing. A call the frame must wait on, or arriving over 100 ms after you sent it, lands only if focus is in the frame by then; once your card closes focus is on your `<body>`, so the call is dropped silently. If `document.activeElement` is still your `<body>` 200 ms later, call `display.focus()` (React: the frame element's `focus()`), then `focusMark(id)` again; on a button of yours, the person moved on. Upgrade the host and the content server together. |
553
294
 
554
295
  ### Find in page: the host's find bar
555
296
 
556
- With `find` declared (`capabilities: { find: {} }`), your own find bar searches a display
557
- ([P131](DECISIONS.md)): the shell finds the query in the page's text (case-insensitive by default,
558
- any spacing), highlights every match it can see and the current one apart, brings the current one
559
- into view (its scrolling box too), and answers where they stand. The page reads every query you
560
- send (the search runs in the page's document): declare `find` only where the page may learn what
561
- the person searches for (not a third-party app with egress, unless you accept that).
562
-
563
- Send a query when the person pauses (a debounce of a few hundred ms) or presses Enter, not at
564
- every key. Each query you send is posted into the page, so a bar that searches at every key shows
565
- the page each prefix of what the person types and the rhythm of their typing; one that waits for
566
- a pause shows it the words they settled on. It also spares a large page a search per key (the
567
- shell searches only the latest of a burst, below).
297
+ With `find` declared (`capabilities: { find: {} }`), your own find bar searches a display (P131): the
298
+ shell highlights the matches (case-insensitive by default, any spacing), brings the current one into
299
+ view and answers the counts. How it works: [DESIGN.md § Find in page](DESIGN.md#find-in-page). The
300
+ page reads every query: declare `find` only where it may learn what the person searches for
301
+ (THREAT_MODEL §7). Send a query when the person pauses or presses Enter, never at every key, which
302
+ would show the page each prefix and the rhythm of the typing.
568
303
 
569
304
  ```js
570
- display.find.takeShortcut(true); // Cmd+F / Ctrl+F in the frame opens your bar, not the browser's
305
+ display.find.takeShortcut(true); // Cmd+F / Ctrl+F in the frame opens your bar, not the browser's
571
306
  display.on("findRequested", () => bar.open()); // the page's word too: open the bar, nothing more
572
- // "unsupported", or `${active}/${total}` ("+" after the total where `capped`).
573
- bar.showResult = (result) => bar.show(result === "unsupported" ? "Not available here" : result);
574
- // Only the answer to the latest query is shown: an earlier one may come back "unsupported".
575
- let asked = 0;
307
+ // A result is "unsupported" or `${active}/${total}` ("+" after the total where `capped`).
308
+ const show = (result) => bar.show(result === "unsupported" ? "Not available here" : result);
309
+ let asked = 0, pause; // only the answer to the latest query is shown
576
310
  const ask = (query, options) => {
577
311
  const mine = ++asked;
578
- void display.find.query(query, options).then((result) => mine === asked && bar.showResult(result));
312
+ void display.find.query(query, options).then((result) => mine === asked && show(result));
579
313
  };
580
- // A new query once the person pauses or presses Enter: the first match in view becomes current.
581
- let pause;
582
- bar.onInput((query) => {
583
- clearTimeout(pause);
584
- pause = setTimeout(() => ask(query), 300);
585
- });
314
+ bar.onInput((query) => (clearTimeout(pause), (pause = setTimeout(() => ask(query), 300))));
586
315
  bar.onEnter((query) => (clearTimeout(pause), ask(query)));
587
- bar.onNext(() => ask(bar.query, { direction: "next" }));
588
- bar.onPrevious(() => ask(bar.query, { direction: "prev" }));
589
- display.on("findUpdated", bar.showResult); // the page changed: new numbers
590
- bar.onClose(() => display.find.clear()); // Escape in your bar: highlights gone
591
- // The display forgot the query: its content navigated away (it runs again). Reset your bar here,
592
- // and wherever you reload() it or give it other content.
593
- display.on("navigated", () => bar.reset());
316
+ bar.onStep((direction) => ask(bar.query, { direction })); // "next" or "prev"
317
+ display.on("findUpdated", show); // the page changed: new numbers
318
+ bar.onClose(() => display.find.clear()); // Escape in your bar: highlights gone
319
+ display.on("navigated", () => bar.reset()); // the query is forgotten; also on reload() or new content
594
320
  ```
595
321
 
596
- - **`"unsupported"`**: the config doesn't declare `find`, the frame's shell is older than your
597
- host (it answers that it doesn't know the request: upgrade the content server first), or no
598
- answer came within `FIND_LIMITS.timeoutMs` (3 s) of the frame running. Also for a query that a
599
- later one superseded before it ran (the shell searches only the latest of a burst; queries asked
600
- before the frame ran: the latest is sent), and for one waiting when the content it was asked of
601
- went (below): show the answer to your latest query only. A query asked before the frame ran
602
- waits for it. An empty query clears and answers `{ total: 0, active: 0 }`; one longer than
603
- `FIND_LIMITS.query` (256) rejects with a `TypeError`.
604
- - **A query is for the content it was asked of.** A new run (`reload()`, a restart after the
605
- content navigated its frame away, `navigated`) or other content (`setContent` with content that
606
- doesn't continue what you gave: more of a streamed page keeps it) forgets the query: nothing is
607
- highlighted or searched there until you call `find.query` again, so another page never sees the
608
- last one's search. Clear your find bar's state (its query, "3/12") whenever the display shows
609
- other content, then search again if the person asks. The shortcut (`takeShortcut`) is kept.
610
- - **The numbers are the page's word**: at most 1,000 matches (`capped: true`: there may be
611
- more), the current one from 1. `rect` is the current match's box in the frame's CSS px, clamped
612
- to its viewport: a display that grows with its content (not `layout: "fill"`) doesn't scroll
613
- itself, so scroll your page to the frame's position plus `rect`.
614
- - **The shortcut** is yours only while you take it, and only where the page doesn't handle Cmd+F
615
- or Ctrl+F itself. `findRequested` is taken only with the page's focus in the frame, so a page
616
- can't open your bar while the person types in your composer. Your own page's Cmd+F (focus
617
- outside every frame) is yours to handle as before. Escape and Cmd+G in the frame stay the page's:
618
- close and move on from your bar.
619
- - **Not found**: words in open shadow roots, in a page's own frames (P128), in form fields, in
620
- images or a canvas, and words split across cells with no space between them.
621
- - **React**: `onFindRequested` (given, the shortcut is yours) and `onFindUpdated` are props; the
622
- handle holds `find(query, options)` and `clearFind()` beside `clearSelection()`. With no display
623
- running, `find` answers `"unsupported"` and keeps the query for the content the frame shows: a
624
- display made later for it (the frame nears the screen again) finds it again and tells
625
- `onFindUpdated`. Other content forgets it: another `content` that doesn't continue it, a new
626
- `generation`, `document`, `instance` (another artifact or version), `config`, `declaration` or
627
- `viewer`. Reset your find bar when you change those. A refused query reaches `onHostError`,
628
- kind `"find"`.
629
-
630
- ```tsx
631
- const frame = useRef<PortholeFrameHandle>(null);
632
- <PortholeView ref={frame} display="page" instance={instance} displayId={id} title={title}
633
- onFindRequested={() => setFinding(true)} onFindUpdated={setFound} />;
634
- const result = await frame.current?.find(query, { direction: "next" });
635
- ```
322
+ | Case | What happens |
323
+ | --- | --- |
324
+ | **`"unsupported"`** | No `find` in the config; a shell older than your host (upgrade the content server first); no answer within `FIND_LIMITS.timeoutMs` (3 s) of the frame running; a query a later one superseded (only a burst's latest is searched); or one waiting when its content went. |
325
+ | **Edge queries** | One asked before the frame runs waits for it. An empty one clears and answers `{ total: 0, active: 0 }`; one longer than `FIND_LIMITS.query` (256) rejects with a `TypeError`. |
326
+ | **New content** | A new run (`reload()`, `navigated`) or other content (a `setContent` that doesn't continue the last) forgets the query: reset your bar. The shortcut stays taken. |
327
+ | **The numbers are the page's word** | At most 1,000 (`capped`), the current one from 1. `rect` is its box in the frame's CSS px, clamped to the viewport; for a display that grows with its content, scroll your page to the frame's position plus `rect`. |
328
+ | **The shortcut** | Yours only while you take it and where the page doesn't handle Cmd+F itself; `findRequested` counts only with focus in the frame. Escape and Cmd+G in the frame stay the page's. |
329
+ | **Not found** | Words in open shadow roots, a page's own frames (P128), form fields, images or a canvas, and words split across cells with no space between them. |
330
+ | **React** | Props `onFindRequested` (given, the shortcut is yours) and `onFindUpdated`; the `ref`'s `find(query, options)` and `clearFind()`. With no display running, `find` answers `"unsupported"` and keeps the query for a display made later for the same content. Other content forgets it (a `content` that doesn't continue it, a new `generation`, `document`, `instance`, `config`, `declaration` or `viewer`). A refused query reaches `onHostError`, kind `"find"`. |
636
331
 
637
332
  ### The keyboard: a display can take it
638
333
 
639
- Any display can move the keyboard into its frame (`element.focus()` in the page, with no gesture
640
- on Chromium and WebKit), and what the person goes on typing in your composer or chat box then goes
641
- to the page, until they see it and click back. Porthole doesn't stop that. From 0.13 to 0.15 a
642
- guard took such a move back when it judged the move to be the page's; it could only guess whose
643
- move it was (your page sees no press inside a cross-site frame), and a wrong guess refused a
644
- person's own click. 0.16.0 removed it ([P149](DECISIONS.md)): no `focusTaken` event, no
645
- `onFocusTaken`, and a display is never stopped for taking the keyboard.
334
+ Any display can move the keyboard into its frame (`element.focus()`, with no gesture on Chromium and
335
+ WebKit), and what the person goes on typing in your composer goes to the page until they click back.
336
+ Porthole neither stops that nor stops a display for it (P149; THREAT_MODEL §7 "The keyboard").
337
+ Beside a field that must never lose a key (a password, a payment field), show no display you don't
338
+ trust.
646
339
 
647
- ```js
648
- // Moving focus into a display yourself (a "focus the page" shortcut):
649
- display.focus();
650
- // Moving it to a field of yours (opening your composer focused): Porthole's move, which lands on
651
- // every engine. Firefox ignores a plain focus() while a frame that takes focus back on its blur
652
- // holds it.
653
- import { focusField } from "@botiverse/porthole";
654
- focusField(composer.textarea);
655
- ```
656
-
657
- - **Yours:** where a field must never lose a key to a page (a password, a payment field), don't
658
- show a display you don't trust beside it. A view a display's report opens still takes no focus
659
- and no press for its first 500 ms (THREAT_MODEL §6); that is your view's own guard, and it
660
- doesn't depend on this.
661
- - **A platform of your own** (a native web view): `focus` on its surface is what `display.focus()`
662
- calls; `focused`, if you give it, says whether the keyboard is in the display, which the find
663
- shortcut reads (P131). `onFocusTaken` is no longer read.
340
+ - Move focus into a display with `display.focus()`, and to a field of yours with `focusField(field)`
341
+ (from `@botiverse/porthole`), not the field's `focus()`: Firefox ignores that while a frame that
342
+ takes focus back on its blur holds it.
343
+ - A platform of your own (a native web view): `display.focus()` calls `focus` on its surface;
344
+ `focused`, if given, says whether the keyboard is in the display (the find shortcut reads it,
345
+ P131). There is no `focusTaken` event, and `onFocusTaken` is not read.
664
346
 
665
347
  ## 4. Served pages: the host kit
666
348
 
@@ -668,13 +350,13 @@ focusField(composer.textarea);
668
350
 
669
351
  Run the app and the content domain on one server: app `http://localhost:8790`, content domain
670
352
  `content.localhost:8790` (pages at `http://a-<id>.content.localhost:8790`). Browsers resolve every
671
- `*.localhost` name to loopback, and each is a site of its own, so the app and its content never
672
- share cookies or storage. `http` is allowed only on loopback; everything else is `https`.
353
+ `*.localhost` name to loopback, each a site of its own, so the app and its content never share
354
+ cookies or storage. `http` is allowed only on loopback; everything else is `https`.
673
355
 
674
356
  In production the content domain is a registrable domain your app uses for nothing else
675
- (`example-usercontent.com`), with wildcard DNS and a wildcard certificate pointing at the same
676
- app. Porthole refuses one that holds or may share a site with an app origin (`ContentDomainError`).
677
- Put it on the Public Suffix List when you can, so its labels are sites of their own.
357
+ (`example-usercontent.com`), with wildcard DNS and a wildcard certificate pointing at the same app.
358
+ Porthole refuses one that holds or may share a site with an app origin (`ContentDomainError`). Put
359
+ it on the Public Suffix List when you can, so its labels are sites of their own.
678
360
 
679
361
  ### The server
680
362
 
@@ -707,101 +389,38 @@ const routes = content.routes(viewerOf);
707
389
  nodeServer({ content, app: async (request) => (await routes(request)) ?? app(request) }).listen(8790);
708
390
  ```
709
391
 
710
- - **`instance`** gets the client's proposal (`{ scope, document }`) and returns the instance as
711
- your app means it, or null. Derive the scope (the origin) from what it names: the client never
712
- chooses an origin. **`access`** returns a grant (`{ viewer }`, or `{ anonymous: true }` for a
713
- public page) or null; `authorize` (optional) checks again on every request after, and
714
- `content.forget({ scope, subject })` drops its cached answers when you revoke.
715
- - **`viewerOf(request)`** is your app's own: who is signed in, from its cookie or token, or null.
716
- - **`Response.redirect` needs an absolute URL** outside a browser (Node throws on `/login`).
717
- - **`reserved`** is only for labels your app itself serves on the content domain (previews of a
718
- dev server, `p-*`). Labels nothing serves need nothing: they are a 404 there.
719
- - **`framedBy`** (P141): where another app frames yours (a dashboard that embeds your app in an
720
- iframe), its origins: `framedBy: ["https://dashboard.example.com"]`. `frame-ancestors` names every
721
- ancestor, so without it each of your frames is blank inside that app. Each may then be an
722
- ancestor of every frame Porthole serves, after `appOrigins`, and is never a host: no frame hears
723
- or tells it, it isn't in `data-porthole-hosts`, and redirect entry and the handoff stay
724
- `appOrigins`' alone. Exact https origins (`http://` on loopback), none an app origin. Your own
725
- page between them is still the frame's parent, and its `frame-ancestors` is yours to set. A
726
- content Worker of your own passes the same list to `statusPage`, `doorResponse` and
727
- `doorStatusResponse` (`framedBy`). The outer page is then an ancestor of content: a content page can
728
- `postMessage` it and every frame in its tree, and learn its origin, so the outer page's authors
729
- must check `event.source` and `event.origin` in every message listener
730
- ([THREAT_MODEL.md §6 "What every host must do"](THREAT_MODEL.md#what-every-host-must-do)).
731
- - **`embeds`** (P143): to let any site embed a public artifact page, set `embeds: true` and, from
732
- one route of your own that decides the page is public (never your reader's issue endpoint),
733
- issue it with `{ anonymous: true, embed: true }` (no `level`, no `user`; an artifact's page):
734
- `host.server.issue(instance, { anonymous: true, embed: true })`. Never answer
735
- `embed` from `access`: it answers your readers, and the kit refuses it there (409 from the issue
736
- endpoint and a clean address's resolve, its 409 page at a clean address's tab; P145). That
737
- session's answers say `frame-ancestors *`, and nothing else's do. It has no
738
- host: frame it from an outer page of your own that listens to nothing (its `frame-src` the one
739
- label), which any site may frame; the shell asks no host and says nothing to any parent, links out
740
- of the page go nowhere (give the outer page your own "Open" link), and there is no door.
741
- `authorize.check` gets `embed: true` for it, so your check can hold an embed subject to embed
742
- sessions. A content Worker of your own answers its refusals before a session exists with
743
- `statusPage({ embed: true, … })` or `doorStatusResponse({ embed: true, … })`. The page learns
744
- where it is embedded: its request's `Referer` and `document.referrer` name your outer page, and
745
- `location.ancestorOrigins` names every ancestor, the embedding site included (Chromium, Firefox
746
- and WebKit), so a page with any egress can report where it is shown
747
- ([THREAT_MODEL.md S4](THREAT_MODEL.md#s4-public-links-and-pages-that-are-apps)).
748
- - **No content domain** (self-hosted without one): still make the host, with `domain: null` (or
749
- `""`). That is the supported setup: no secret is needed, `GET /porthole/meta` answers
750
- `{ served: false }`, and pages show every kind opaque (a url kind, its fallback) instead of
751
- waiting for a meta that never comes. Without a host, `portholeClient` stays pending.
752
- - **`secret`** is at least 32 random bytes (`npx porthole secret`), from the environment
753
- (`PORTHOLE_SECRET`). A missing or short one throws at `createContentHost`, saying so (with
754
- `health`, frames stay opaque and the meta says why).
755
- - **`nodeServer`** is the whole Node server: the content domain to Porthole, WebSockets included,
756
- every other request to `app` (fetch-style: Hono's `app.fetch`) or `request` (a Node listener:
757
- Express), the health gate started on listen and stopped on close. Behind a TLS edge, add
758
- `scheme: "https"`. A host that needs the port first (`listen(0)`) can come later: `content:
759
- () => host` (null until made); requests go to the app until it gives one. `nodeServer` starts
760
- the host it is given: a host made in a `listen` callback starts right after it, and one made
761
- later at the next request. `start()` runs once (a started host ignores it), so starting it
762
- yourself as soon as you make it is fine too.
763
- - **`nodeHost(content, { request })`** is for an app that keeps its own `node:http` server (or a
764
- framework that owns one): put its `request` and `upgrade` listeners on your server, call
765
- `content.start()` once it listens and `content.close()` when it stops. A fetch-style app's
766
- listener there is `nodeListener(app, { scheme })`, not `toRequest` and `sendResponse` by hand:
767
- `toRequest` throws for a request fetch can't take (`TRACE`, a Host that is no URL), and a throw
768
- in a listener ends a Node process. `nodeListener`, `nodeHost` and `nodeServer` answer those 405
769
- and 400, and a handler or listener that fails 500 (P092). Pass `onError: (error, request) =>
770
- log.error(…)` to any of them to hear your own failures (by default a process warning).
771
- - **Rate limit:** `rateLimit: { perMinute }` keys an anonymous viewer by the address the server
772
- saw (the socket's peer on Node, `CF-Connecting-IP` on Workers), never by `X-Forwarded-For` a
773
- client can write (P092). **Behind a proxy** (a TLS edge, a load balancer, a CDN), that address
774
- is the proxy's: say how many proxies append to `X-Forwarded-For` (`trustedProxies: 1` for one
775
- edge, `2` for a CDN in front of a balancer), or key it yourself (`key: (request, viewer) =>
776
- …`). Without either, anonymous requests through the proxy share one allowance. An IPv6
777
- address counts by its /64 (one client's network). Three cases to know:
778
- - **No peer address:** the Node adapter leaves the socket's peer on the request it makes. Where
779
- it is missing (Hono's own Node adapter, an app that rebuilds the request with
780
- `new Request(req)`, Deno or Bun), every anonymous request shares one allowance: set
781
- `rateLimit.key`.
782
- - **`trustedProxies` only where the app can't be reached except through those proxies:** a
783
- client that reaches it directly writes the very `X-Forwarded-For` entry that is counted.
784
- - **Uploads after the answer:** once an answer is out, a request body no one read is dropped
785
- for at most 1 MiB and 5 s, then the connection closes (P092). An app that answers early and
786
- keeps reading the upload (a handler that returns its Response before it has read the
787
- request's body) is cut off there.
788
- - **Health:** `health: { probe: nodeProbe(), onServedChange: (served) => … }` checks the content
789
- domain over the real network and falls back to opaque frames while it doesn't answer.
790
- - **Behind an edge that rewrites headers** (a CDN, a proxy), pass Porthole's
791
- `Content-Security-Policy` on as it is: a served page opened on a tab of its own (a link, a new
792
- tab) has no frame, and the header's `sandbox allow-scripts allow-same-origin` is its sandbox
793
- there (P099). The conformance runner's `served.domain.tab-*` cases fail if it is lost.
392
+ | Option | What to give |
393
+ | --- | --- |
394
+ | `instance` | The client's proposal (`{ scope, document }`) in, your instance (or null) out. Derive the scope (the origin) from what it names: the client never chooses an origin. |
395
+ | `access` | A grant (`{ viewer }`, or `{ anonymous: true }` for a public page) or null. `authorize` (optional) checks again on every later request; `content.forget({ scope, subject })` drops its cached answers when you revoke. |
396
+ | `routes(viewerOf)` | `viewerOf(request)` is your app's: who is signed in (its cookie or token), or null. |
397
+ | `entry.signIn` | `Response.redirect` needs an absolute URL outside a browser (Node throws on `/login`). |
398
+ | `reserved` | Only labels your app itself serves on the content domain (dev-server previews, `p-*`). Labels nothing serves need nothing: they are a 404 there. |
399
+ | `secret` | At least 32 random bytes (`npx porthole secret`), from the environment (`PORTHOLE_SECRET`). A missing or short one throws at `createContentHost`, saying so (with `health`, frames stay opaque and the meta says why). |
400
+ | `domain: null` (or `""`) | No content domain (self-hosted), a supported setup: no secret needed, `GET /porthole/meta` answers `{ served: false }`, pages show every kind opaque (a url kind, its fallback). Without a host at all, `portholeClient` stays pending. |
401
+ | `health` | `health: { probe: nodeProbe(), onServedChange: (served) => … }` checks the content domain over the real network and falls back to opaque frames while it doesn't answer. |
402
+ | `rateLimit` | `rateLimit: { perMinute }` keys an anonymous viewer by the address the server saw (the socket's peer on Node, `CF-Connecting-IP` on Workers, IPv6 by its /64), never a client-written `X-Forwarded-For` (P092). Behind proxies, set `trustedProxies` (how many append to `X-Forwarded-For`) only where the app is reachable through them alone, or give `key: (request, viewer) => …`. Without a peer address (Hono's own Node adapter, `new Request(req)`, Deno, Bun), set `rateLimit.key`. Without `trustedProxies` or `key` where these apply, anonymous requests share one allowance. |
403
+
404
+ | What | Detail |
405
+ | --- | --- |
406
+ | **`framedBy`** (P141) | Where another app frames yours (a dashboard), its exact https origins (`http://` on loopback), none an app origin: `framedBy: ["https://dashboard.example.com"]`. Without it your frames are blank there. They become ancestors of every frame Porthole serves, never hosts: no frame hears or tells them, and redirect entry and the handoff stay `appOrigins`'. Your page stays the frame's parent and sets its own `frame-ancestors`. A content Worker of your own passes the list to `statusPage`, `doorResponse` and `doorStatusResponse`. Content can `postMessage` the outer page, so its authors must check `event.source` and `event.origin` in every message listener ([THREAT_MODEL.md § What every host must do](THREAT_MODEL.md#what-every-host-must-do)). |
407
+ | **`embeds`** (P143) | To let any site embed a public artifact page, set `embeds: true` and issue it from one route of your own that decides the page is public (never your reader's issue endpoint): `host.server.issue(instance, { anonymous: true, embed: true })` (no `level`, no `user`). Never answer `embed` from `access`: the kit refuses it there with a 409 (P145). Only that session says `frame-ancestors *`; it has no host and no door, and its links out go nowhere. Frame it from an outer page of your own that listens to nothing (its `frame-src` the one label), with your own "Open" link. `authorize.check` gets `embed: true`. A content Worker of your own answers refusals before a session with `statusPage({ embed: true, … })` or `doorStatusResponse({ embed: true, … })`. The page learns where it is embedded ([THREAT_MODEL.md S4](THREAT_MODEL.md#s4-public-links-and-pages-that-are-apps)). |
408
+ | **`nodeServer`** | The whole Node server: the content domain to Porthole (WebSockets included), the rest to `app` (fetch-style: Hono's `app.fetch`) or `request` (a Node listener: Express), the health gate started on listen. Behind a TLS edge, add `scheme: "https"`. A host that needs the port first (`listen(0)`) can come later: `content: () => host` (null until made). `nodeServer` starts it; `start()` runs once, so starting it yourself as well is fine. |
409
+ | **`nodeHost(content, { request })`** | For an app that keeps its own `node:http` server: add its `request` and `upgrade` listeners, call `content.start()` once it listens and `content.close()` when it stops. Wrap a fetch-style app with `nodeListener(app, { scheme })`, not `toRequest` and `sendResponse` by hand: `toRequest` throws for a request fetch can't take, and a throw in a listener ends a Node process (`nodeListener` answers 405, 400 or 500, P092). Pass `onError: (error, request) => …` to any of them to hear your own failures. |
410
+ | **Request bodies** | An unread one is drained for at most 1 MiB and 5 s after the answer, then the connection closes, so an app that answers before reading an upload is cut off. |
411
+ | **Behind an edge that rewrites headers** (a CDN, a proxy) | Pass Porthole's `Content-Security-Policy` on unchanged: in a tab of its own a served page has no frame, and the header's `sandbox allow-scripts allow-same-origin` is its sandbox (P099). The conformance runner's `served.domain.tab-*` cases fail if it is lost. |
794
412
 
795
413
  ### Pages made of many files
796
414
 
797
- A stored version may be a set of files (a build's output, a report with its images; P081). The
798
- store answers a manifest and the bytes by path; `{ html }` stays one page:
415
+ A stored version may be a set of files (a build's output, a report with its images; P081): the store
416
+ answers a manifest and the bytes by path; `{ html }` stays one page. How they are served: DESIGN.md
417
+ § "Isolation modes and served content".
799
418
 
800
419
  ```js
801
420
  import { checkFileSet, fileLimits, versionBase, versionedAddress } from "@botiverse/porthole/server";
802
421
 
803
- // When a version is published: every path canonical, within your page kind's limits.
804
- const problems = checkFileSet(manifest, { limits: fileLimits(pageConfig.limits) }); // [] to take it
422
+ // At publish: every path canonical, within your page kind's limits ([] to take it).
423
+ const problems = checkFileSet(manifest, { limits: fileLimits(pageConfig.limits) });
805
424
 
806
425
  source: async (id, version) => {
807
426
  const stored = await myStore.version(id, version); // { files: { path: { size, sha256 } }, entry? }
@@ -820,55 +439,33 @@ entry: {
820
439
  },
821
440
  ```
822
441
 
823
- - **Each file is served from the manifest only**, typed by its extension (Porthole's table, never
824
- the type it was published with), `nosniff`, with a CSP that opens the version's own path and
825
- nothing else of the origin (P082). Files are immutable at a version's address; pages revalidate
826
- (the host's check runs on every load). `read` returns the whole file (`Uint8Array` or a
827
- stream); Porthole cuts ranges.
828
- - **A page never mixes versions.** The latest's address (`/`, `/style.css`) goes to the version's
829
- own (`/v/3/`, `/v/3/style.css`) before the page loads anything, so a version published while it
830
- loads never reaches it. Answer `entry.at` with the version's `base`, and `pinned: true` when that
831
- base names one version only (its files are then immutable); a plain instance is served at a
832
- frame's address instead. A base's segments are letters, digits and `. _ : ~ -`.
833
- - **An artifact's versions share an origin**, so they are one trust domain (P082): give versions
834
- that must stay apart scopes of their own.
835
- - **Each version is a directory of its origin** (`/v/<n>/`). `/_blob/` (`ASSET_LIBRARY_PATH`) is
836
- the asset library's, across versions (0.7, below); `versionedAddress` names nothing there.
837
- - **In a frame**, the files' address carries the frame's access (WebKit keeps no cookie there,
838
- P083): the frame's URL is `/__porthole/f/<sealed>/`, good for the session. A host's
839
- `issue` and its locator don't change.
840
- - **Every page of the set is in the shell**, and a set's pages open each other in the frame (P084).
841
- Service workers never register.
842
- - **The agent's side:** `lintFiles` and `admitFiles` before you take a version, `checkPage({ files
843
- })` to run it, and the manual's Files section where a kind serves files. Show a set served: an
844
- opaque frame has no origin to serve its files from.
442
+ | Rule | Detail |
443
+ | --- | --- |
444
+ | **Files are served from the manifest only** | Typed by their extension, never by the type they were published with (P082). `read` returns the whole file (`Uint8Array` or a stream); Porthole cuts ranges. |
445
+ | **A page never mixes versions** | The latest's address (`/`, `/style.css`) goes first to the version's own (`/v/3/`, `/v/3/style.css`). Answer `entry.at` with the version's `base`, and `pinned: true` when that base names one version only (its files are then immutable); a plain instance is served at a frame's address instead. A base's segments are letters, digits and `. _ : ~ -`. |
446
+ | **An artifact's versions share an origin** | They are one trust domain (P082): give versions that must stay apart scopes of their own. `/_blob/` (`ASSET_LIBRARY_PATH`) is the asset library's, across versions; `versionedAddress` names nothing there. |
447
+ | **The agent's side** | `lintFiles` and `admitFiles` before you take a version, `checkPage({ files })` to run it, and the manual's Files section where a kind serves files. Show a set served: an opaque frame has no origin to serve its files from. |
845
448
 
846
449
  ### A page's own nested frames (opt-in)
847
450
 
848
451
  By default the shell refuses every nested frame content makes: markup frames are removed, and a
849
- script that creates a frame-like element (`createElement("iframe")`, `object`, `embed`, …) gets a
850
- `NotSupportedError` at that line (P130), so tell your users' agents to build pages without them (the
851
- manual and the lint already do). Pasting or dropping formatted content into an editable element
852
- inserts its plain text only. `nestedFrames: "own"` (P128) on a
853
- kind's `options` lets a page keep an `<iframe>` of one of its version's own files (a relative
854
- `src`, served kinds) or with `srcdoc` (every kind), as Claude's Artifacts do; frames of other
855
- sites, `<object>` and `<embed>` stay out, and the manual and the lint say so:
856
-
857
- ```ts
858
- artifact: { preset: "artifact", options: { layout: { kind: "fill" }, nestedFrames: "own" } },
859
- ```
452
+ script that creates one (`createElement("iframe")`, `object`, `embed`, …) gets a `NotSupportedError`
453
+ at that line (P130). The manual and the lint tell agents to build pages without them. Pasting or
454
+ dropping formatted content into an editable element inserts its plain text only.
860
455
 
861
- It is a weakening: a nested frame is a realm of its own where the shell's defenses never ran, so
862
- content there has WebRTC (a way out past `connect-src`) and can put text on the clipboard from a
863
- click, with no notice. The CSP still governs every frame's loads and navigations. Not for url mode
864
- or live widgets (refused). Turn it on only where your product accepts that.
456
+ `nestedFrames: "own"` (P128) in a kind's `options` lets a page keep an `<iframe>` of one of its
457
+ version's own files (a relative `src`, served kinds) or with `srcdoc` (every kind), as Claude's
458
+ Artifacts do. Frames of other sites, `<object>` and `<embed>` stay out; url mode and live widgets
459
+ refuse it. It is a weakening: a nested frame runs without the shell's defenses (WebRTC past
460
+ `connect-src`, clipboard writes from a click with no notice; THREAT_MODEL.md S1), though the CSP
461
+ still governs every frame's loads and navigations. Turn it on only where your product accepts that.
865
462
 
866
463
  ### The capability runtime: pages that are apps
867
464
 
868
- 0.7 (P085–P090). A page reaches your services through one global, `porthole.use(name)`, for what
869
- it declared when it was published and what its viewer's level allows. Porthole carries, checks
870
- and gates the calls; you keep the services. It is an optional layer over the display: what it adds
871
- to your side (your API's checks, versions, revocation, each person's data) is in
465
+ A page reaches your services through one global, `porthole.use(name)`, for what it declared when it
466
+ was published and what its viewer's level allows. Porthole carries, checks and gates the calls; you
467
+ keep the services. It is an optional layer over the display. How it works: DESIGN.md § "The
468
+ capability runtime". What it adds to your side:
872
469
  [THREAT_MODEL.md § The display layer and the app runtime](THREAT_MODEL.md#7-the-display-layer-and-the-app-runtime).
873
470
 
874
471
  ```js
@@ -880,7 +477,7 @@ const page = presets.artifact({
880
477
  capabilities: { copyText: {}, openLink: {}, comments: {}, user: {}, artifact: {}, assets: {}, db: {} },
881
478
  });
882
479
 
883
- // 2. At publish: the artifact's declaration (omitted: carried forward; {}: cleared; an object: replaced).
480
+ // 2. At publish, the artifact's declaration (omitted: carried forward; {}: cleared; an object: replaced).
884
481
  const declared = declareCapabilities({ stored: artifact.declaration, given: body.capabilities, config: page });
885
482
  if (!declared.ok) return problems(declared.problems); // [{ path: "capabilities.db.rules", message }]
886
483
  await myStore.saveDeclaration(artifact.id, declared.declaration); // { capabilities, runtime: "1" }
@@ -894,125 +491,66 @@ handlers: {
894
491
  db: (args, { viewer, declared, instance, changed, signal }) => myApi.db(instance, viewer, args, declared?.rules, { changed, signal }),
895
492
  artifact: (args, { viewer, instance }) => myApi.artifact(instance, viewer, args), // Refused("conflict") when base moved
896
493
  assets: (args, { viewer, instance }) => myApi.assets(instance, viewer, args),
897
- // true if it opened. Never over the person's own words or place; a page's draft (P108) shown whole,
898
- // editable, as the page's suggestion, taking no focus, posted only on the person's Send (below)
899
- // (inUse: the composer holds the person's own words, or a place they chose)
494
+ // true if it opened; never over the person's own words or place (inUse). A page's draft: below.
900
495
  comments: ({ anchor, draft }) =>
901
496
  composer.inUse() ? false : draft === undefined ? composer.open(anchor) : openPageDraft(composer, anchor, draft),
902
497
  },
903
- // 5. The mount: what this version declared, within what the artifact declares now; null for a
904
- // page published before 0.7 (required under a runtime). Before rendering: a stored
905
- // declaration that isn't one's shape is a problem to show, never a mount with null (0.6's
906
- // surface) or with either declaration alone (P093).
498
+ // 5. The mount: this version's declaration within the artifact's current one; null for a page stored
499
+ // without one (required under a runtime). A stored declaration of the wrong shape is a problem to
500
+ // show, never a mount with null or with either declaration alone (P093).
907
501
  const shown = version.declaration ? tryIntersectDeclarations(version.declaration, artifact.declaration) : null;
908
502
  if (shown && !shown.ok) return <VersionError problems={shown.problems} />; // "This version can't be shown"
909
503
  <PortholeView display="page" instance={instance} declaration={shown ? shown.declaration : null} />
910
504
  ```
911
505
 
912
- - **A page's draft in your composer** (P108): `comments.open` reaches your handler whenever the
913
- page calls it, within its rate (30 a minute by default). No proof of a click is asked since
914
- 0.16.0 ([P149](DECISIONS.md)): the page picks the moment, and may call with no one pressing
915
- anything. So the composer it fills is the person's to act on, and whether it opens at all is
916
- yours to say (return false while the person is writing, or after they closed several unused):
506
+ | Rule | Detail |
507
+ | --- | --- |
508
+ | **Built-ins** (`clipboard`, `links`, `downloads`, `comments`) | Reach every page whose kind offers them; everything else only a page that declared it. A page stored without a declaration takes the legacy path (the built-ins through `use`, and the legacy globals): give it a declaration when it is next published. |
509
+ | **Levels** | `view < interact < admin < owner`. Reads are `view`; `chat.send`, `data.call`, `context.set` and db writes `interact`; `artifact.publish` and asset removal `admin`; uploads `admin` unless `assets: { levels: { upload: "interact" } }` (then the library's scripts and styles never run: P089). Raise any method in its config's `levels`. Without a viewer the runtime's own are refused. |
510
+ | **Your API is the wall** | Your handlers call your API as the viewer, and it checks again from its own session and stored declaration, never from `context.viewer` or `context.declared` (a page past the bridge could forge them). `dbAccess(request, viewer, rules)` is the db rule set, `atLeast(level, "admin")` for a publish. Hold every write to an existing document to its `ifVersion` (updates and deletes too), apply a batch in order against one state, refuse a moved base or version with `new Refused("conflict")`, and check and admit a merged version as any other. |
511
+ | **Per version** | Store each version's declaration with it and mount it with `tryIntersectDeclarations(version's, current)` (`intersectDeclarations` throws its problems as a `TypeError`); your API's rules for it are that intersection's. |
512
+ | **Details** | `dbAccess` holds `Votes/a` to its exact name's rule (else `*`'s) and to any rule naming it in another ASCII case, so a store that folds case is safe with it; paths reach your handler as the page wrote them, and a publish naming a collection twice in different cases is refused. Checked declarations have no prototype: use `Object.hasOwn` and `JSON.stringify`. `Grant.user.id` is one path segment, never `me`; `pseudonymFor(secret, artifact, person)` keeps pages from linking a person across artifacts. |
513
+ | **Assets** | `createContentHost({ assets: (id, access) => myStore.asset(id, access) })` answers `{ scope, artifact, name, size, sha256, trusted?, read }` for an id you made (`ASSET_ID`: 32 random hex characters). `/server` serves it at `/_blob/<id>` on that scope's origin only, to an access for that artifact, after your check, revalidated at each load. Store an upload's `trusted` (set by the bridge) and give it back: other code-typed assets are downloads, and a trusted script runs only while the config still lets uploaded code run (P103). Pages show assets with `assets.url(id)`. `{ get, bearer: true }` serves by id alone, an opt-in for public artifacts; then every artifact config your server has must let uploaded code run, or all code is a download. Refuse names that aren't assets (`assetNameProblem`). |
514
+ | **The agent** | Declares capabilities in your publish tool (`capabilities: { db: {} }`) and reads the manual's topic `capabilities`, with each one's types (`types/runtime/v1/*.d.ts`, also in the package). |
515
+
516
+ **A page's draft in your composer** (P108): `comments.open` reaches your handler whenever the page
517
+ calls it (30 a minute by default), with no proof of a click (P149). Whether the composer opens is
518
+ yours to say (not while the person is writing, or after they closed several unused). A composer the
519
+ page filled is the person's to act on:
917
520
 
918
- ```js
919
- // A composer the page filled: its words are the page's until the person acts in it.
920
- function openPageDraft(composer, anchor, draft) {
921
- // Opens beside the frame, and takes no focus: keys stay where the person was typing, so what
922
- // they type for the page never lands in a postable comment.
923
- composer.open(anchor, { text: draft, focus: false }); // where your composer focuses, focusField
924
- // Armed as THREAT_MODEL §6 says: no press of any kind for 500 ms (guardPresses, § Annotations).
925
- guardPresses(composer.element).placed();
926
- // Said by you, outside the frame where the page can't draw, until they edit it: never shown as
927
- // one of their own drafts.
928
- composer.setNote("Suggested by this page");
929
- composer.input.addEventListener("input", () => composer.setNote(null), { once: true });
930
- // Enter sends only once the person has focused or edited the composer themselves (a press in
931
- // it, a Tab into it, their typing); until then Send is a click. It opened without focus, and a
932
- // page can't move focus into your page's fields, so its focus is theirs.
933
- let theirs = false;
934
- for (const type of ["pointerdown", "focus", "input"]) {
935
- composer.input.addEventListener(type, () => (theirs = true), { once: true });
936
- }
937
- composer.input.addEventListener("keydown", (event) => {
938
- if (event.key === "Enter" && !theirs) event.preventDefault();
939
- });
940
- return true;
521
+ ```js
522
+ function openPageDraft(composer, anchor, draft) {
523
+ // Beside the frame, without focus: keys stay where the person was typing.
524
+ composer.open(anchor, { text: draft, focus: false }); // where your composer focuses, focusField
525
+ guardPresses(composer.element).placed(); // no press for 500 ms (§ Annotations)
526
+ // Said by you, outside the frame, until they edit it: never shown as one of their own drafts.
527
+ composer.setNote("Suggested by this page");
528
+ composer.input.addEventListener("input", () => composer.setNote(null), { once: true });
529
+ // Enter sends only once the person has focused or edited it themselves; until then Send is a click.
530
+ let theirs = false;
531
+ for (const type of ["pointerdown", "focus", "input"]) {
532
+ composer.input.addEventListener(type, () => (theirs = true), { once: true });
941
533
  }
942
- ```
534
+ composer.input.addEventListener("keydown", (event) => {
535
+ if (event.key === "Enter" && !theirs) event.preventDefault();
536
+ });
537
+ return true;
538
+ }
539
+ ```
943
540
 
944
- - Never over the person's words: while the composer holds their text, or a place they chose,
945
- answer `false`, or show the page's words as a separate suggestion that takes no focus; never
946
- replace, append to or retarget what they wrote.
947
- - Show the draft whole, as plain text (a comment that renders as markdown hides an HTML comment
948
- or a link definition from readers but not from an agent: render a page-drafted comment as
949
- plain text, or show before Send what readers will see); show the anchor's `label` and `quote`
950
- as isolated text (`<bdi>`, `dir="auto"`). Porthole has already refused a draft with anything
951
- invisible, a line separator or a run of blanks, and taken what can't be seen out of the label
952
- and quote.
953
- - Nothing one click away in it, or in a draft's view, posts, submits or discards; your own list
954
- of a person's drafts (not the frame's markers, which a page can draw too) is how they find
955
- theirs.
956
- - **Built-ins** (`clipboard`, `links`, `downloads`, `comments`) reach every page whose kind offers
957
- them; everything else only a page that declared it. A page with no declaration (one published
958
- before 0.7) gets the built-ins through `use` and 0.6's globals as before: give it a declaration
959
- when it is next published.
960
- - **Levels**: `view < interact < admin < owner`. Reads are `view`; `chat.send`, `data.call`,
961
- `context.set` and db writes `interact`; `artifact.publish` and asset removal `admin`; uploads
962
- `admin` unless you set `assets: { levels: { upload: "interact" } }` (then scripts and styles from
963
- the library never run: P089). Raise any method in its config's `levels`. Without a viewer the
964
- runtime's own are refused.
965
- - **Your API is the wall.** The bridge refuses early, in your page; your handlers call your API as
966
- the viewer, and it must check again, from its own session and its own stored declaration: never
967
- trust `context.viewer` or `context.declared` for what your data allows (a page past the bridge
968
- could forge them). `dbAccess(request, viewer, rules)` is the db rule set (another person's
969
- `data/users/<id>` refused, `me` resolved), `atLeast(level, "admin")` for a publish. Hold every
970
- write to an existing document to its `ifVersion` (updates and deletes too), apply a batch in
971
- order against one state, and refuse a moved base or version with `new Refused("conflict")`;
972
- check and admit the merged version as any (`checkFileSet`, `admitFiles`).
973
- - **Per version**: store each version's declaration with it (`declareCapabilities` at its publish)
974
- and mount a version with `tryIntersectDeclarations(version's, current)` (`intersectDeclarations`
975
- throws its problems as a `TypeError`); your API's rules for that version are the same
976
- intersection's (whatever it allows, both declarations allow).
977
- - **Rules hold in any case**: `dbAccess` holds `Votes/a` to its exact name's rule (else `*`'s)
978
- and to the rule for `votes` too (any rule naming it in another ASCII case), so a store that
979
- folds case is safe with it; paths reach your handler as the page wrote them (Porthole never
980
- lowercases them), and a publish that names a collection twice in different cases is refused.
981
- - **Objects without a prototype**: checked declarations (`checkDeclaration`, `declareCapabilities`,
982
- the intersection) have none, so `.hasOwnProperty()` on one, or one in a template string,
983
- throws: use `Object.hasOwn` and `JSON.stringify`.
984
- - **Who the page may know**: `Grant.user.id` is one path segment, never `me`; give
985
- `pseudonymFor(secret, artifact, person)` where pages shouldn't link a person across artifacts.
986
- - **Assets**: `createContentHost({ assets: (id, access) => myStore.asset(id, access) })` answers
987
- `{ scope, artifact, name, size, sha256, trusted?, read }` for an id you made (32 random hex
988
- characters, `ASSET_ID`); `/server` serves it at `/_blob/<id>` on that scope's origin only, to an
989
- access for that artifact (a session, or a framed page's sealed address), after your check,
990
- revalidated at each load. Store an upload's `trusted` (the bridge sets it: an admin's code where
991
- uploaded code may run) and give it back: other code-typed assets are served as downloads. Pages
992
- show assets with `assets.url(id)` (some engines' frames send no address a `/_blob/` load could
993
- carry). `{ get, bearer: true }` serves by id alone, an explicit opt-in for public artifacts.
994
- A trusted script goes out as one only while the config still lets uploaded code run, checked at
995
- each load (P103): in bearer mode, with no access to name the page's config, every artifact
996
- config your server has must (one where anyone who interacts uploads, or with no `assets`, turns
997
- them all into downloads).
998
- Refuse names that aren't assets (`assetNameProblem`).
999
- - **Run the conformance cases** against your handlers (no browser):
541
+ Never replace, append to or retarget what the person wrote. Show the draft whole, as plain text,
542
+ and the anchor's `label` and `quote` as isolated text (`<bdi>`, `dir="auto"`). Nothing one click
543
+ away posts, submits or discards. The full list: THREAT_MODEL.md §7 "The app runtime".
1000
544
 
1001
- ```js
1002
- import { defineRuntimeConformance } from "@botiverse/porthole/conformance";
1003
- for (const each of defineRuntimeConformance({
1004
- config: page, viewers, handlers: () => freshArtifactHandlers(), assets: () => assetStore,
1005
- // Your own API for the same artifact, signed in as `viewer` with that person's real session:
1006
- // the cases past the bridge then forge the context, as a page past it could.
1007
- api: (handlers, viewer) => apiAs(handlers, viewer),
1008
- })) {
1009
- test(each.name, () => each.run());
1010
- }
1011
- ```
545
+ **Run the conformance cases** against your handlers (no browser). `api` is your own API for the
546
+ same artifact, signed in as `viewer` with that person's real session: the cases past the bridge
547
+ then forge the context, as a page past it could.
1012
548
 
1013
- - **The agent** declares capabilities in your publish tool (`capabilities: { db: {} }`) and reads
1014
- topic `capabilities` of the manual: declaring, levels, errors, where state goes, each one's types
1015
- (`types/runtime/v1/*.d.ts`, also in the package for a page's own TypeScript).
549
+ ```js
550
+ import { defineRuntimeConformance } from "@botiverse/porthole/conformance";
551
+ for (const each of defineRuntimeConformance({ config: page, viewers, handlers: () => freshArtifactHandlers(),
552
+ assets: () => assetStore, api: (handlers, viewer) => apiAs(handlers, viewer) })) test(each.name, () => each.run());
553
+ ```
1016
554
 
1017
555
  ### The page
1018
556
 
@@ -1032,100 +570,48 @@ display.on("outcome", (outcome) => {
1032
570
  openButton.onclick = () => porthole.openInTab(instance); // the clean address
1033
571
  ```
1034
572
 
1035
- A `blocked` outcome is the word of Porthole's own pages, never of the content (P124, P125): an
1036
- opaque frame's frame status is never taken, nor one a frame says after its first word; the host
1037
- hears those as a `hostError` of kind `"frame-status"` (log it, show nothing for it). Draw the
1038
- fallback from `outcome` only. A url-mode app is the exception: it can say any outcome (THREAT_MODEL
1039
- S6).
1040
-
1041
- **The door (P125).** A served display (a served shell, a page, a view through the
1042
- sandbox proxy) is framed on its scope's origin, where the scope's other displays run content: its
1043
- own frame can't be trusted for how loading went (a same-scope sibling could speak for it). So
1044
- `createHost` first frames a **door** — a page of Porthole's on the display's origin, in a hidden
1045
- opaque frame it can't reach — and takes the door's word (`FrameLocation.door`, which `issue` returns
1046
- for those kinds). The content frame's own frame status is then never taken, and its silence is a
1047
- `timeout`, never a fallback. You don't wire anything: `createHost` and `/server` do it. Two
1048
- requirements:
1049
-
1050
- - **Deploy the server (or your content Worker) before the host.** The door is minted and served by
1051
- the server; a host given a served location with no door (from a server that doesn't
1052
- yet mint one) builds no frame for it: `blocked: locate`, and a `hostError` of kind `"door"`
1053
- naming the fix. Upgrade the server/Worker first, then the host. This is a hard requirement, not a
1054
- preference.
1055
- - **A custom locator must pass `door` through, and issue anew for every run.** If you rebuild
1056
- `FrameLocation` yourself (a locator of your own rather than `httpLocator`), carry `door` from your
1057
- issue endpoint unchanged; `httpLocator` and the host kit's client already do. Dropping it refuses
1058
- every served display, as above. And `locate` is called again on every run (a reload,
1059
- a restart after the content navigated its frame away): answer each call with a fresh issue (a new
1060
- ticket, a new door ticket). A location reused from an earlier run carries tickets already taken,
1061
- so its door says `blocked: session` ("this link has been used"), and `createHost` tells you
1062
- with a `hostError` of kind `"locate"`. (A sibling of the scope could force that by reloading the
1063
- display.)
1064
- - **A platform of your own makes the web's doors.** A `PlatformHost` that wraps
1065
- `webPlatform.createSurface` must also give `createDoor` (delegate to `webPlatform.createDoor`):
1066
- a platform without doors frames no served display (`blocked: locate`, a `door` host error).
1067
- - **The door sits in the display's container while it decides**, a hidden 0×0 frame
1068
- (`data-porthole-door`), removed once it says its word. Code that grabs
1069
- `container.querySelector("iframe")` just after mounting may get the door: select
1070
- `iframe:not([data-porthole-door])`.
1071
- - **A clean address is for a tab.** Never give `createHost` a clean address (`urlOf`, `link`) as a
1072
- frame's location: it has no door, so it is refused before any frame, as above, and the content
1073
- origin answers it in a frame with a page that has no script and goes nowhere. To frame what a
1074
- clean address names, resolve it through your issue endpoint first: `client.resolve(address)` (or
1075
- `<PortholeView address>`) posts `{ address }`, and the endpoint answers the location for what it
1076
- names (with its door; a file set's page below its version opens at that page), or the refusal its
1077
- tab would get. A refusal is the display's outcome with no frame built: 401 `blocked: sign-in`,
1078
- 403 `blocked: denied` (with your reason code if your answer gives `error.reason`), 404 `blocked:
1079
- not-found`; any other failure is `blocked: locate` with a `locate` host error, and a backend that
1080
- never answers is a `timeout`. That mapping holds for every locate, an instance's too.
1081
-
1082
- A **content Worker of your own** (one that answers the content origins itself, instead of
1083
- `/server`) serves the door too: `issue` mints the door ticket and returns `door: { url }`, and the
1084
- Worker routes `DOOR_PATH + <key>` (`/__porthole/door/<key>`) on every label — take the door ticket
1085
- (`TicketRecord.door === true`, bound to the label and key), run the same access, document and entry
1086
- checks the content route runs for that grant, then answer `doorResponse({ hostOrigins, framedBy })` (open) or
1087
- `doorStatusResponse({ status, reason, code?, hostOrigins, framedBy })` (401 `session` / 403 `denied` / 404
1088
- `not-found` / 500 `error`). Refuse a door ticket at `/__porthole/d/`. `DOOR_PATH`, `doorResponse` and `doorStatusResponse` are exported from
1089
- `@botiverse/porthole/server`.
1090
-
1091
- **A host that signs its own tickets** (P126) — its server mints its own ticket for a display and its
1092
- content Worker verifies it, so the Worker holds no Porthole ticket when the door is asked — answers
1093
- the door with **`server.doorAnswer(instance, grant, request?)`**, on the object `createServer`
1094
- returns. Raft's shape: the Worker routes its door path (`/__porthole/door/_raft`, say), verifies
1095
- its own ticket (signature, single use, bound to the label and the instance, and a door's, never its
1096
- content's), admits the request and recovers the grant it was signed for, then returns `await
1097
- server.doorAnswer(instance, grant, request)`. The answer is exactly what `/server`'s own door route
1098
- gives once it has taken its ticket: the host's `authorize` check (`denied` with its code), the
1099
- document and version, a file set's entry being a page (`not-found`), `doorResponse` or
1100
- `doorStatusResponse` with the door's CSP and no cookie. It never takes a ticket and checks nothing
1101
- about the request but its method: **you must have authenticated the request and established the
1102
- grant yourself**, as before `issue`. Pass the request so `authorize.check` sees it, and `{ page }`
1103
- as the fourth argument for a frame that opens at a file set's page below its version. It throws for
1104
- an instance with no door (a url-mode app) and for an instance or grant `issue` would
1105
- refuse. The content route still takes its own ticket and checks again (P050).
1106
-
1107
573
  `porthole.config(kind)` is the served config while frames are served, the opaque one while they
1108
- aren't, and null until the meta is known, so a frame never starts opaque and then restarts
1109
- served. The client's functions take no `this`: pass them bare
1110
- (`useSyncExternalStore(porthole.subscribe, porthole.meta)`). A client module that fails to load shows nothing at all: catch its import and say so
1111
- (`examples/app.mjs` does).
1112
-
1113
- **Without a bundler**, the page gets Porthole's browser modules from your server, in three parts
1114
- (`examples/app.mjs` has all three):
1115
-
1116
- 1. Serve the package's `dist/` at a path of your app's (`/porthole-client/`, `.js` files only).
1117
- On Workers it is the static assets directory (`assets.directory`, with `run_worker_first`).
574
+ aren't, and null until the meta is known, so a frame never starts opaque and then restarts served.
575
+ The client's functions take no `this`: pass them bare
576
+ (`useSyncExternalStore(porthole.subscribe, porthole.meta)`). A client module that fails to load
577
+ shows nothing at all: catch its import and say so (`examples/app.mjs` does).
578
+
579
+ Draw the fallback from `outcome` only: a `blocked` outcome is the word of Porthole's own pages,
580
+ never the content's (P124, P125), except a url-mode app's, which can say any outcome (THREAT_MODEL
581
+ S6). A frame status Porthole doesn't take (an opaque frame's, or one said after a frame's first
582
+ word) reaches you as a `hostError` of kind `"frame-status"`: log it, show nothing.
583
+
584
+ **The door (P125).** `createHost` takes a served display's outcome from its **door** (a page of
585
+ Porthole's on the display's origin, in a hidden opaque frame the content can't reach;
586
+ `FrameLocation.door`, which `issue` returns), never from the content frame, whose silence is a
587
+ `timeout`. Why: THREAT_MODEL.md §7 "The host's fallback". `createHost` and `/server` wire it. Yours:
588
+
589
+ | Your part | Detail |
590
+ | --- | --- |
591
+ | **Deploy the server (or your content Worker) before the host** | A hard requirement: a host given a served location with no door builds no frame (`blocked: locate`, and a `hostError` of kind `"door"` naming the fix). |
592
+ | **A custom locator passes `door` through unchanged and issues anew for every run** | `locate` is called again on every run (a reload, a restart after the content navigated away): answer each with a fresh issue (a new ticket and door ticket). A reused location's door says `blocked: session` ("this link has been used"), with a `hostError` of kind `"locate"`. `httpLocator` and the host kit's client already do both. |
593
+ | **A platform of your own** | One wrapping `webPlatform.createSurface` must also give `createDoor` (delegate to `webPlatform.createDoor`), or it frames no served display. |
594
+ | **The door sits in the display's container while it decides** (a hidden 0×0 frame, `data-porthole-door`) | Select `iframe:not([data-porthole-door])`, not the first `iframe`. |
595
+ | **A clean address is for a tab** | Never give `createHost` a clean address (`urlOf`, `link`) as a frame's location: it has no door, so it is refused. Resolve it through your issue endpoint first: `client.resolve(address)` (or `<PortholeView address>`) answers the location for what it names (a file set's page below its version opens at that page), or the refusal its tab would get. |
596
+ | **A locate's refusals** | Become the outcome, with no frame built: 401 `blocked: sign-in`, 403 `blocked: denied` (with your `error.reason`, if given), 404 `blocked: not-found`, any other failure `blocked: locate` with a `locate` host error, and no answer a `timeout`. |
597
+ | **A content Worker of your own** (answering the content origins instead of `/server`) | Serves the door too. `issue` mints the door ticket and returns `door: { url }`. The Worker routes `DOOR_PATH + <key>` (`/__porthole/door/<key>`) on every label: it takes the door ticket (`TicketRecord.door === true`, bound to the label and key), runs the access, document and entry checks the content route runs for that grant, then answers `doorResponse({ hostOrigins, framedBy })` or `doorStatusResponse({ status, reason, code?, hostOrigins, framedBy })` (401 `session`, 403 `denied`, 404 `not-found`, 500 `error`). It refuses a door ticket at `/__porthole/d/`. All three are exported from `@botiverse/porthole/server`. |
598
+ | **A host that signs its own tickets** (P126) | Its Worker holds no Porthole ticket for the door: answer it with `await server.doorAnswer(instance, grant, request)` on the object `createServer` returns (pass the request: `authorize.check` sees it; `{ page }` as a fourth argument for a file set's page below its version). Its Worker first verifies its own ticket (signature, single use, bound to the label and the instance, a door's and never its content's) and recovers the grant. `doorAnswer` gives exactly what `/server`'s door route gives after its ticket (the host's `authorize` check, the document and version, the entry, the door's CSP, no cookie), but takes no ticket and checks nothing about the request but its method: **you must have authenticated the request and established the grant yourself**, as for `issue`. It throws for an instance with no door (a url-mode app) or one `issue` would refuse. The content route still takes its own ticket and checks again (P050). |
599
+
600
+ **Without a bundler**, the page gets Porthole's browser modules from your server (`examples/app.mjs`
601
+ does all three):
602
+
603
+ 1. Serve the package's `dist/` at a path of your app's (`/porthole-client/`, `.js` files only). On
604
+ Workers it is the static assets directory (`assets.directory`, with `run_worker_first`).
1118
605
  2. Map the bare name in an import map that carries the page's nonce:
1119
606
  `<script type="importmap" nonce="…">{"imports":{"@botiverse/porthole":"/porthole-client/index.js"}}</script>`.
1120
- 3. Serve the page its display kinds as a module, made from the same plain object the server's
1121
- `defineDisplays` gets, so they never disagree:
607
+ 3. Serve the page its display kinds at `/porthole-client/displays.mjs`, as a module made from the
608
+ same plain object the server's `defineDisplays` gets, so they never disagree:
1122
609
  `` `import { defineDisplays } from "@botiverse/porthole";\nexport const displays = defineDisplays(${JSON.stringify(kinds)});` ``
1123
- at `/porthole-client/displays.mjs`, imported from there.
1124
-
1125
- With a bundler, import `@botiverse/porthole` and your `displays.mjs` as usual.
1126
610
 
1127
- React: give the provider the client, and show a kind. Flipping the provider's `scheme`, or a new
1128
- `themeKey`, re-themes running frames in place: they keep their state.
611
+ **React**: give the provider the client and show a kind. Flipping `scheme`, or a new `themeKey`,
612
+ re-themes running frames in place. Rendered on a server, `PortholeView` draws what the client's meta
613
+ says: give `portholeClient` the meta it starts with (`meta`, from your page's data), or it renders
614
+ `pending`.
1129
615
 
1130
616
  ```jsx
1131
617
  <PortholeProvider client={porthole} scheme={mode} theme={cssVariableTheme(TOKENS)} nonce="auto">
@@ -1135,68 +621,47 @@ React: give the provider the client, and show a kind. Flipping the provider's `s
1135
621
  // const { link, open, copy } = usePortholeLink(instance); "Open in a new tab", "Copy link"
1136
622
  ```
1137
623
 
1138
- Rendered on a server, `PortholeView` draws what the client's meta says: give `portholeClient` the
1139
- meta it starts with (`meta`, from your page's data), and the server's HTML has the frame's
1140
- placeholder or the fallback, which the page then hydrates. Without it, `pending`.
1141
-
1142
624
  ### The page's CSP
1143
625
 
1144
626
  - `frame-src`: `content.frameSources` (the content origins, and the authorize route), also in
1145
627
  `GET /porthole/meta`; `displays.frameSources(source, { authorizeUrl })` without a server.
1146
- - **An opaque display inherits your page's CSP.** Its own policy then narrows it, never widens it.
1147
- If your page sets `default-src`, also allow what agent content uses inline:
1148
- `img-src data: blob:`, `media-src data: blob:`, `font-src data:`, `style-src 'unsafe-inline'`,
1149
- `worker-src blob:`. A nonce-based `script-src` works: give `createHost` the nonce
1150
- (`HostOptions.nonce`) and the shell runs content's scripts under it.
628
+ - **An opaque display inherits your page's CSP**; its own policy narrows it, never widens it. If your
629
+ page sets `default-src`, also allow what agent content uses inline: `img-src data: blob:`,
630
+ `media-src data: blob:`, `font-src data:`, `style-src 'unsafe-inline'`, `worker-src blob:`. A
631
+ nonce-based `script-src` works: give `createHost` the nonce (`HostOptions.nonce`) and the shell
632
+ runs content's scripts under it.
1151
633
 
1152
634
  ### Sign-in
1153
635
 
1154
- - Your sign-in page gets the authorize URL as `next` (`signIn`'s `returnTo`), and goes back to it
1155
- when signed in. The authorize URL is `<first app origin>/porthole/authorize` unless
1156
- `entry.authorizeUrl` names another, and `next` is built from it with the entry's state: never
1157
- from the address the request arrived at, which behind a TLS edge or a dev proxy isn't your app's.
1158
- - Check `next` with `entryTarget(next, authorizeUrl, { app: true })` (in the page,
1159
- `porthole.entryTarget(next, { app: true })`): the authorize route or any page on your app's
1160
- origin, as an absolute URL, and null for anything else (another site, `//host`, `/\host`,
1161
- `javascript:`), so one check serves sign-ins that go back to a page and those that go back to
1162
- a frame's content. Without `{ app: true }` it takes only the authorize route.
1163
- - **Warning: no `form-action 'self'` on a sign-in page that posts a form.** `form-action` holds
1164
- every redirect of a submission, and redirect entry continues from your sign-in through the
1165
- content origin, so the browser blocks the last hop and the person stays on your sign-in. Leave
1166
- `form-action` out of that page's CSP, or add the content source.
1167
- - **A page that authenticates with a token** (a single-page app holding a bearer token, a desktop
1168
- app) has no cookie for the authorize route to know the viewer by. Use the viewer handoff:
1169
- `entry.handoff: { id: (viewer) => viewer.id, viewer: (id) => lookUp(id) }` on the server, and
1170
- `portholeClient({ displays, headers: () => ({ authorization: `Bearer ${token()}` }), handoff: true })`
1171
- on the page. It posts to `/porthole/handoff` with your own credential, on load and when the
1172
- page regains focus; Porthole answers with a cookie that holds a key it signs (the viewer's id
1173
- and ten minutes), `HttpOnly`, scoped to `/porthole`. That beats storing the app's token in a
1174
- cookie: the key isn't a credential for your API, goes nowhere but Porthole's routes, can't be
1175
- set from another site (the POST needs your credential, and is refused from another origin), and
1176
- expires in ten minutes (an expired one costs only a quiet trip through your sign-in route).
1177
- `entry.spa: { route: "/sign-in" }` sends a signed-out person to your app's route with `next`.
636
+ | What | Detail |
637
+ | --- | --- |
638
+ | **`next`** | Your sign-in page gets the authorize URL as `next` (`signIn`'s `returnTo`) and goes back to it when signed in. The authorize URL is `<first app origin>/porthole/authorize` unless `entry.authorizeUrl` names another; `next` is built from it with the entry's state, never from the address the request arrived at (behind a TLS edge or a dev proxy, that isn't your app's). |
639
+ | **Check `next`** | `entryTarget(next, authorizeUrl, { app: true })` (in the page, `porthole.entryTarget(next, { app: true })`) answers the authorize route or any page on your app's origin, as an absolute URL, and null for anything else (another site, `//host`, `/\host`, `javascript:`). One check serves sign-ins that go back to a page and to a frame's content. Without `{ app: true }` it takes only the authorize route. |
640
+ | **Warning: no `form-action 'self'` on a sign-in page that posts a form** | `form-action` holds every redirect of a submission, and redirect entry continues from your sign-in through the content origin, so the browser blocks the last hop and the person stays on your sign-in. Leave `form-action` out of that page's CSP, or add the content source. |
641
+ | **A page that authenticates with a token** (a single-page app holding a bearer token, a desktop app) | It has no cookie for the authorize route to know the viewer by: use the viewer handoff (P072). Give `entry.handoff: { id: (viewer) => viewer.id, viewer: (id) => lookUp(id) }` on the server and `portholeClient({ displays, headers: () => ({ authorization: `Bearer ${token()}` }), handoff: true })` on the page. It posts to `/porthole/handoff` with your own credential (refused from another origin), on load and when the page regains focus, and gets an `HttpOnly` cookie scoped to `/porthole` holding a key Porthole signs: the viewer's id and ten minutes, no credential for your API. An expired one costs only a quiet trip through your sign-in route. `entry.spa: { route: "/sign-in" }` sends a signed-out person to your app's route with `next`. |
1178
642
 
1179
643
  ### Url mode: a relay of your own
1180
644
 
1181
- `proxyTo` relays a url-mode app by HTTP. A relay of your own (over your own transport) uses the
1182
- same parts: `upstreamHeaders.request(headers, { origin, target, websocket })` and
1183
- `.response(...)` (the header rewrite, Porthole's cookies kept out), `statusPage({ status, title,
1184
- detail, reason, hostOrigins })` (a page that tells the frame's host why it shows nothing, desktop
1185
- schemes included), and `nodeHost`'s `appSocket` (a WebSocket, Porthole's cookies already removed).
1186
-
1187
- What a url-mode app gets from another origin (P101): its cookie opens it for what its own origin
1188
- asks (`Origin` its own, or `Sec-Fetch-Site` `same-origin` or `none`) and for a navigation that
1189
- opens it (GET or HEAD: your frame, a link, the way back from sign-in); anything else another origin
1190
- sends (a sibling app's fetch, form post, script tag or image, an opaque origin's `null`) is a 403
1191
- that never reaches the app or your `authorize.check`. A WebSocket opens from the app's own origin
1192
- only: `access(request)`, which `nodeHost` asks before `appSocket` and a Worker asks on its own
1193
- upgrade path, is null for any other `Origin`. A client that sends neither header (curl with the
1194
- cookie) is no browser and goes on. An app whose sign-in posts back from another site (OpenID's
1195
- `form_post`) can't sign in through the preview; a tab's `Lax` cookie didn't go with that post
1196
- before either.
645
+ `proxyTo` relays a url-mode app by HTTP. A relay of your own (over your own transport) uses the same
646
+ parts: `upstreamHeaders.request(headers, { origin, target, websocket })` and `.response(...)` (the
647
+ header rewrite, Porthole's cookies kept out), `statusPage({ status, title, detail, reason,
648
+ hostOrigins })` (a page that tells the frame's host why it shows nothing, desktop schemes included),
649
+ and `nodeHost`'s `appSocket` (a WebSocket, Porthole's cookies already removed).
650
+
651
+ What other origins get (P101): the app's cookie opens it only for its own origin and for a
652
+ navigation that opens it (GET or HEAD); anything else another origin sends is a 403 that never
653
+ reaches the app or your `authorize.check`. A WebSocket opens from the app's own origin only
654
+ (`access(request)`, asked by `nodeHost` before `appSocket` and by a Worker on its own upgrade path).
655
+ The full rule: [THREAT_MODEL.md § S6](THREAT_MODEL.md#s6-previews-of-a-running-app). An app whose
656
+ sign-in posts back from another site (OpenID's `form_post`) can't sign in through the preview; a
657
+ tab's `Lax` cookie doesn't go with that post either.
1197
658
 
1198
659
  ## 5. Cloudflare Workers
1199
660
 
661
+ Route the content domain's wildcard (`*.<content domain>/*`, with wildcard DNS and a certificate for
662
+ every level served, `*.f.<domain>` included) and your own domain to the same Worker, or the content
663
+ domain to a Worker of its own.
664
+
1200
665
  ```js
1201
666
  import { contentHostFor, d1TicketStore } from "@botiverse/porthole/server";
1202
667
 
@@ -1210,23 +675,13 @@ export default {
1210
675
  };
1211
676
  ```
1212
677
 
1213
- - **`contentHostFor`** makes one content host per `env`, the first time a request needs it. While
1214
- the settings can't be served (no `PORTHOLE_SECRET`, a content domain that shares a site with the
1215
- app), every request gets a plain 503 naming the problem, logged once (`{ log }`), instead of a
1216
- stack trace. `porthole.host(env)` is the host itself (`frameSources` for your CSP) once `fetch`
1217
- has answered null. Settings fixed at build time (no `env`) can make one `createContentHost` at
1218
- module scope instead; a bad setting then fails the Worker as it starts.
1219
-
1220
- - **Tickets in D1** (never KV, which is eventually consistent):
1221
- `npx porthole d1-schema > migrations/0001_porthole_tickets.sql`, then
1222
- `wrangler d1 migrations apply <db>`.
1223
- - **One secret, `PORTHOLE_SECRET`:** `npx porthole secret`, then `wrangler secret put
1224
- PORTHOLE_SECRET` (`.dev.vars` locally). At least 32 bytes; it signs tickets, cookies, entry
1225
- codes and handoffs.
1226
- - **Static assets:** set `"assets": { "run_worker_first": true }`. Otherwise Workers serves your
1227
- static files before the Worker runs, on every host, content origins included.
1228
- - No `nodejs_compat` needed. `wrangler dev` passes the Host through, so
1229
- `*.content.localhost:<port>` works locally.
678
+ | What | Detail |
679
+ | --- | --- |
680
+ | **`contentHostFor`** | Makes one content host per `env`, the first time a request needs it. While the settings can't be served (no `PORTHOLE_SECRET`, a content domain sharing a site with the app), every request gets a plain 503 naming the problem, logged once (`{ log }`), instead of a stack trace. `porthole.host(env)` is the host itself (`frameSources` for your CSP) once `fetch` has answered null. Settings fixed at build time (no `env`) can make one `createContentHost` at module scope instead; a bad setting then fails the Worker as it starts. |
681
+ | **Tickets in D1** (never KV, which is eventually consistent) | `npx porthole d1-schema > migrations/0001_porthole_tickets.sql`, then `wrangler d1 migrations apply <db>`. |
682
+ | **`PORTHOLE_SECRET`** | `npx porthole secret`, then `wrangler secret put PORTHOLE_SECRET` (`.dev.vars` locally). It signs tickets, cookies, entry codes and handoffs. |
683
+ | **Static assets** | Set `"assets": { "run_worker_first": true }`, or Workers serves your static files before the Worker runs, on every host, content origins included. |
684
+ | **Locally** | No `nodejs_compat` needed. `wrangler dev` passes the Host through, so `*.content.localhost:<port>` works locally. |
1230
685
 
1231
686
  ## 6. The agent's side
1232
687
 
@@ -1243,40 +698,24 @@ const tools = [showTool(config), guideTool(config), checkTool(config)]; // { nam
1243
698
  ```
1244
699
 
1245
700
  Names come from the config (`guide.toolName`, `guide.guideToolName`), else `show_<noun>`,
1246
- `<noun>_guide` and `check_<noun>` (`show_page`, `page_guide`, `check_page` for a page; naming them
1247
- in the config also has the manual name them). The descriptions are the manual's own words.
701
+ `<noun>_guide` and `check_<noun>` (`show_page`, `page_guide`, `check_page` for a page); naming them
702
+ in the config also has the manual name them. The descriptions are the manual's own words.
1248
703
  `examples/mcp/server.mjs` wires all three as an MCP server.
1249
704
 
1250
- - **`admitContent`** runs `lintContent` and refuses (by default, `refuseOn: "error"`) only what
1251
- would certainly fail or be cut: over the size limit, a document with no body where a fragment
1252
- goes, nested frames, `document.write`. Its refusal says exactly what to change. Everything else
1253
- (hosts outside egress, unpinned libraries, `alert`, forms, the clipboard…) comes back as
1254
- warnings with the result. `refuseOn: "never"` only warns.
1255
- - **`guideChanges(from, to)`** is the notice for the agent when a kind flips between served and
1256
- opaque (null when its manual reads the same).
1257
- - **`errors: "agent"`** sends what content throws (and what the sandbox blocks, and a navigation
1258
- the shell stopped, P080) back to the agent once people see it: listen for `contentError` and pass
1259
- it on.
705
+ | What | Detail |
706
+ | --- | --- |
707
+ | **`admitContent`** | Runs `lintContent` and refuses (by default, `refuseOn: "error"`) only what would certainly fail or be cut: over the size limit, a document with no body where a fragment goes, nested frames, `document.write`. Its refusal says exactly what to change. Everything else (hosts outside egress, unpinned libraries, `alert`, forms, the clipboard…) comes back as warnings with the result. `refuseOn: "never"` only warns. |
708
+ | **`guideChanges(from, to)`** | The notice for the agent when a kind flips between served and opaque (null when its manual reads the same). |
709
+ | **`errors: "agent"`** | Sends what content throws (and what the sandbox blocks, and a navigation the shell stopped, P080) back to the agent once people see it: listen for `contentError` and pass it on. |
1260
710
 
1261
711
  ### Checking a page before people see it
1262
712
 
1263
- `checkPage` (`@botiverse/porthole/check`) runs the content in the real sandbox at the manual's
1264
- phone and desktop widths, in light and dark, and answers a report whose `text` is a few lines for
1265
- the agent: what it threw, what the sandbox blocked, what failed to load, `console.error`, overflow
1266
- and a cut height, each problem once with where it happened (at most 8; the rest counted). Lines
1267
- are the content's own, as the agent wrote it (a script's error and a lint finding name the same
1268
- line).
1269
-
1270
- A served config is checked served: its content runs on an origin of its own under Porthole's
1271
- server, with the served CSP, shell, storage and cookies, as people's browsers run it (both drivers
1272
- answer a reserved content domain themselves; nothing goes to your server). An opaque config, or
1273
- an MCP Apps view, runs opaque.
1274
-
1275
- The host functions the config declares are answered as a host that declines would: a person
1276
- asked to confirm says no, and a handler answers no (no prompt sent, a tool call refused). Each
1277
- call is in the report (`run.calls`): one hosts refuse whatever the person says (no click, bad
1278
- arguments) is a problem; one a person may decline is a note, so the agent makes sure the page
1279
- still works then.
713
+ `checkPage` (`@botiverse/porthole/check`) runs the content in the real sandbox at the manual's phone
714
+ and desktop widths, light and dark (served configs served, on an origin of their own; nothing goes
715
+ to your server), with every host function answered as a declining host would. Its report's `text`
716
+ is a few lines for the agent, each problem once with its line (at most 8): what it threw, what was
717
+ blocked or failed to load, `console.error`, overflow, a cut height. How it works: DESIGN.md §
718
+ "The agent's side: lint, check, tools".
1280
719
 
1281
720
  ```js
1282
721
  import { checkPage, playwrightDriver } from "@botiverse/porthole/check";
@@ -1284,15 +723,14 @@ const report = await checkPage({ config, content: html, driver: playwrightDriver
1284
723
  report.ok; report.text;
1285
724
  ```
1286
725
 
1287
- It needs a browser somewhere: Chromium is best (WebKit mutes a thrown error's message in an
1288
- opaque frame, so the agent reads only "Script error.", and names no line in a served one). Where:
726
+ It needs a browser somewhere. Chromium is best: WebKit mutes a thrown error's message in an opaque
727
+ frame (the agent reads only "Script error.") and names no line in a served one.
1289
728
 
1290
729
  - **A server with Chromium** (Node): `playwrightDriver(await chromium.launch())`.
1291
- - **An agent on a person's machine, maybe without Chromium** (Ferry's daemon): run
1292
- `lintContent` there (no browser needed), and send `check_page` to your server, which runs
1293
- `checkPage`; or use Playwright where it is installed (`examples/mcp/server.mjs` falls back to
1294
- the lint, saying so).
1295
- - **Cloudflare Workers:** Browser Rendering, through a CDP session:
730
+ - **An agent on a person's machine, maybe without Chromium** (Ferry's daemon): run `lintContent`
731
+ there (no browser needed) and send `check_page` to your server, which runs `checkPage`; or use
732
+ Playwright where it is installed (`examples/mcp/server.mjs` falls back to the lint, saying so).
733
+ - **Cloudflare Workers**: Browser Rendering, through a CDP session:
1296
734
 
1297
735
  ```js
1298
736
  import puppeteer from "@cloudflare/puppeteer";
@@ -1303,30 +741,23 @@ opaque frame, so the agent reads only "Script error.", and names no line in a se
1303
741
  await browser.close();
1304
742
  ```
1305
743
 
1306
- **Bundling:** every entry point bundles whole (a Worker, a single executable): `/check` imports
1307
- its check page's script as a module, and `/conformance` its harness, so nothing is looked up
1308
- beside a module at run time. Each release is bundled with rolldown and esbuild and checked for
1309
- that before it is published (`test:bundle`). `/conformance`, which runs under Playwright, still
1310
- looks for the optional MCP Apps App SDK where it runs; without it, the App SDK probes say so and
1311
- don't run.
744
+ **Bundling**: every entry point bundles whole (a Worker, a single executable): nothing is looked up
745
+ beside a module at run time. `/conformance` still looks for the optional MCP Apps App SDK where it
746
+ runs; without it, the App SDK probes say so and don't run.
1312
747
 
1313
748
  ## 7. Conformance: prove your integration
1314
749
 
1315
- `@botiverse/porthole/conformance` runs Porthole's suite (egress and escape probes, the served
1316
- cases, redirect entry) against your app's real page, its CSP and session, in Playwright:
750
+ `@botiverse/porthole/conformance` runs Porthole's suite (egress and escape probes, the served cases,
751
+ redirect entry) against your app's real page, its CSP and session, in Playwright:
1317
752
 
1318
753
  ```js
1319
754
  // playwright.config.mjs
1320
755
  import { defineConfig, devices } from "@playwright/test";
1321
756
  import { conformanceProjects } from "@botiverse/porthole/conformance";
1322
757
  export default defineConfig({
1323
- fullyParallel: true, // else one spec file is one worker: minutes longer
1324
- // The list, then why each skipped case was skipped (the list alone shows a bare "-").
1325
- reporter: [["list"], ["@botiverse/porthole/conformance/reporter"]],
1326
- projects: conformanceProjects(devices, {
1327
- engines: ["chromium", "webkit", "firefox"], // the default
1328
- // launchOptions: { chromium: { executablePath: "/usr/bin/chromium" } }, a system browser
1329
- }),
758
+ fullyParallel: true, // else one spec file is one worker: minutes longer
759
+ reporter: [["list"], ["@botiverse/porthole/conformance/reporter"]], // why each skip was skipped, not a bare "-"
760
+ projects: conformanceProjects(devices, { engines: ["chromium", "webkit", "firefox"] }), // the default
1330
761
  webServer: { … },
1331
762
  });
1332
763
 
@@ -1354,48 +785,30 @@ What the runner asks of your app, and what it skips without:
1354
785
  | `entry.denied`, `atSignIn`, `completeSignIn` | a page the viewer may not see; your sign-in page | that case; the sign-in is judged by leaving the content origin, and not completed |
1355
786
  | `entry.unknown` | addresses that name nothing, or `"derive"` | that case |
1356
787
 
1357
- The suite names its own scopes, so an app serves them through a **test mode**
1358
- (`examples/app.mjs`: `PORTHOLE_CONFORMANCE=1`): the test page under `t-<scope>`, and a private
1359
- page. **Never ship test mode**: with it, anyone signed in can make content origins of their
1360
- choosing. `onDemand(make)` memoizes fixtures made the first time a case asks (a page published
1361
- on demand); `instances` and `entry.url` may be async. The tests are located at your
1362
- `defineHostConformance` call, so `playwright test porthole.spec.mjs` selects them.
1363
-
1364
- Each engine needs its browser (`npx playwright install chromium webkit firefox`); a subset is
1365
- `engines: ["chromium"]`. Where Playwright has no build of one (arm64 Linux's Chromium), point at
1366
- the system's: `launchOptions: { chromium: { executablePath, args } }`, merged with Porthole's own
1367
- (`use` adds to every project's).
1368
-
1369
- The leak probes run opaque displays on your page: where its own CSP closes what a probe needs,
1370
- the probe reports itself inapplicable, saying which directive. Those are facts about your page's
1371
- opaque fallback, not failures: a page with a `default-src` sees `[1.connect]` and
1372
- `[2.resources]` skipped, its `connect-src` already closing what they probe. The reporter above
1373
- prints each reason at the end; so does `--reporter=json`.
788
+ | What | Detail |
789
+ | --- | --- |
790
+ | **Test mode** | The suite names its own scopes, so an app serves them through a test mode (`examples/app.mjs`: `PORTHOLE_CONFORMANCE=1`): the test page under `t-<scope>`, and a private page. **Never ship test mode**: with it, anyone signed in can make content origins of their choosing. |
791
+ | **Fixtures** | `onDemand(make)` memoizes fixtures made the first time a case asks (a page published on demand); `instances` and `entry.url` may be async. The tests are located at your `defineHostConformance` call, so `playwright test porthole.spec.mjs` selects them. |
792
+ | **Browsers** | Each engine needs its own (`npx playwright install chromium webkit firefox`); a subset is `engines: ["chromium"]`. Where Playwright has no build of one (arm64 Linux's Chromium), point at the system's: `launchOptions: { chromium: { executablePath, args } }` in `conformanceProjects`' options (`executablePath: "/usr/bin/chromium"`), merged with Porthole's own (`use` adds to every project's). |
793
+ | **Skips are facts about your page, not failures** | The leak probes run opaque displays on your page; where its CSP closes what a probe needs, the probe reports itself inapplicable, naming the directive. A page with a `default-src` sees `[1.connect]` and `[2.resources]` skipped, its `connect-src` already closing what they probe. The reporter prints each reason at the end; so does `--reporter=json`. |
1374
794
 
1375
795
  ## 8. Expected, and how to tell
1376
796
 
1377
- - Chromium logs `Unrecognized Content-Security-Policy directive 'webrtc'` for every frame: the
1378
- directive closes WebRTC where an engine knows it, and is ignored where it doesn't.
1379
- - Content's CSP allows `'unsafe-eval'`. Content is the agent's own script already
1380
- (`'unsafe-inline'`), so eval adds no capability, and libraries content uses compile with it
1381
- (Vue's in-browser build, Alpine.js, Vega's expressions, WebAssembly). Egress, the sandbox and the
1382
- origin are what isolate it (P071).
1383
- - On `http` loopback the session cookies are `porthole-<key>`; on `https`, `__Host-porthole-<key>`,
1384
- and only that name is read (P101: a sibling label can set any other for the whole domain).
1385
- A frame's are `Secure; SameSite=None; Partitioned` on loopback too: browsers keep `Secure`
1386
- cookies on `localhost`.
1387
- - A served frame is one iframe on the content's own origin (no frame inside it), first loaded at
1388
- `/__porthole/d/<key>?ticket=…`: in a test, `page.frameLocator('iframe[src*="/__porthole/d/"]')`.
1389
- - A clean address that names nothing (a label the naming never makes, the bare domain, a path
1390
- `entry.at` says has nothing) is a 404 on the content domain: it never reaches your sign-in.
1391
- - Host errors name the content origin and leave out ticket URLs.
797
+ | You see | Why |
798
+ | --- | --- |
799
+ | Chromium logs `Unrecognized Content-Security-Policy directive 'webrtc'` for every frame | The directive closes WebRTC where an engine knows it and is ignored where it doesn't. |
800
+ | Content's CSP allows `'unsafe-eval'` | Content is the agent's own script already (`'unsafe-inline'`), so eval adds no capability, and libraries compile with it (Vue's in-browser build, Alpine.js, Vega's expressions, WebAssembly). Egress, the sandbox and the origin isolate it (P071). |
801
+ | Session cookies `porthole-<key>` on `http` loopback, `__Host-porthole-<key>` on `https` | Only that name is read (P101: a sibling label can set any other for the whole domain). A frame's are `Secure; SameSite=None; Partitioned` on loopback too: browsers keep `Secure` cookies on `localhost`. |
802
+ | A served frame is one iframe on the content's own origin (no frame inside it), first loaded at `/__porthole/d/<key>?ticket=…` | In a test: `page.frameLocator('iframe[src*="/__porthole/d/"]')`. |
803
+ | A clean address that names nothing (a label the naming never makes, the bare domain, a path `entry.at` says has nothing) is a 404 on the content domain | It never reaches your sign-in. |
804
+ | Host errors name the content origin | They leave out ticket URLs. |
1392
805
 
1393
806
  ## 9. Reference
1394
807
 
1395
808
  | Import | What |
1396
809
  | --- | --- |
1397
810
  | `@botiverse/porthole` | `createHost`, `presets`, `defineDisplays`, `portholeClient`, `frameFallback`, `entryTarget`, `lintContent`, `admitContent`, `showTool`, `guideTool`, `checkTool`, `answerGuide`, `guideChanges`, `compile` |
1398
- | `@botiverse/porthole` (the runtime, 0.7) | `declareCapabilities`, `declarationProblems`, `checkDeclaration`, `dbAccess`, `atLeast`, `methodLevel`, `rosterOf`, `assetNameProblem`, `RUNTIME_CAPABILITIES`, `RUNTIME_TYPES`, `Refused` (`conflict`, `forbidden`, `too_large`); `types/runtime/v1/*.d.ts` |
811
+ | `@botiverse/porthole` (the runtime) | `declareCapabilities`, `declarationProblems`, `checkDeclaration`, `dbAccess`, `atLeast`, `methodLevel`, `rosterOf`, `assetNameProblem`, `RUNTIME_CAPABILITIES`, `RUNTIME_TYPES`, `Refused` (`conflict`, `forbidden`, `too_large`); `types/runtime/v1/*.d.ts` |
1399
812
  | `@botiverse/porthole/react` | `PortholeProvider`, `PortholeFrame`, `PortholeView`, `usePortholeLink`, `cssVariableTheme`, `useRunAgain` |
1400
813
  | `@botiverse/porthole/server` | `createContentHost` (`routes`, `forget`), `contentHostFor`, `prefixedName`, `memoryTicketStore`, `d1TicketStore`, `upstreamHeaders`, `statusPage`, `conformancePage`, the callbacks' types |
1401
814
  | `@botiverse/porthole/node` | `nodeServer`, `nodeHost`, `nodeListener`, `nodeProbe`, `toRequest`, `sendResponse` |