@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/DESIGN.md CHANGED
@@ -1,81 +1,260 @@
1
- # Phase-1 design
2
-
3
- The stable shape is in [ARCHITECTURE.md](ARCHITECTURE.md) and the reasons in
4
- [DECISIONS.md](DECISIONS.md). This is the concrete phase-1 plan. Web first:
5
- a framework-agnostic TypeScript core plus a thin React binding.
6
-
7
- Adopting Porthole? Start with [ADOPTING.md](ADOPTING.md) and the package's `examples/`. Paths
8
- below like `leak/…` and `ops/…` are Porthole's own repository, not the package.
9
-
10
- ## Threat model
11
-
12
- The whole of it, use by use (who attacks, what is out of scope, what each scenario
13
- guarantees and leaves to the host), is [THREAT_MODEL.md](THREAT_MODEL.md). In short:
14
- two classes of attacker, handled by different layers (ARCHITECTURE § Trust
15
- boundaries):
16
-
17
- 1. **Attacking the host** — steal the host's credentials or data, act as the
18
- person, or escape the sandbox. Countered by **origin isolation**: the content
19
- runs on an origin that is never the host's, so same-origin policy denies it
20
- the host's DOM, storage, cookies and credentials. This is the catastrophic
21
- class; a regression here is the one bug that matters most.
22
- 2. **Leaking or deceiving** — exfiltrate what the content was already handed
23
- (whatever the agent wrote into it, or data a capability returned), or draw a
24
- convincing fake (a login form, an "approve" button) to fool the viewer.
25
- Origin isolation does not help. Countered by **egress hardening** (close every
26
- outbound channel to all but declared origins), **gating** (powers that affect
27
- the person or the agent need a gesture or confirmation), and the host drawing
28
- its own chrome/approvals outside the frame, never inside it.
29
-
30
- The agent is itself a trust boundary: the HTML is agent-authored, so loading a
31
- library from an allowed CDN is no more trusted than the agent's own code. The
32
- manual's supply-chain rule (pin exact, aged versions) is advice to the agent, not
33
- a wall; the walls are isolation and egress.
1
+ # Design
34
2
 
35
- ## Package layout
3
+ How Porthole works: the architecture, each mechanism, then every defense with the test that proves
4
+ it. What each use is protected from: [THREAT_MODEL.md](THREAT_MODEL.md). Why:
5
+ [DECISIONS.md](DECISIONS.md). Porthole is web first: a framework-agnostic TypeScript core plus a
6
+ thin React binding.
36
7
 
37
- One package, `@botiverse/porthole`, with subpath exports (P013), in a pnpm
38
- workspace (`packages/porthole`):
8
+ Adopting Porthole? Start with [ADOPTING.md](ADOPTING.md) and the package's `examples/`. Paths below
9
+ like `leak/…` and `ops/…` are in Porthole's own repository, not the package.
39
10
 
40
- | Import | What | Source |
41
- | --- | --- | --- |
42
- | `@botiverse/porthole` | The core: config, presets, compiler, theme, guide, and the seams below. No DOM framework, no host, no MCP SDK. | `src/index.ts` |
43
- | `@botiverse/porthole/react` | The React binding: `<PortholeProvider>`, `<PortholeFrame>`, the default `ConfirmDialog`. Peer: `react`. | `src/react/` |
44
- | `@botiverse/porthole/mcp` | The MCP Apps adapter for full MCP Apps views. Depends on the core only. | `src/mcp/` |
45
- | `@botiverse/porthole/conformance` | The leak/conformance suite and the host test interface. Peer: `@playwright/test`. | `src/conformance/` |
46
- | `@botiverse/porthole/server` | Serving for domain, artifact and url modes, and the MCP Apps sandbox proxy: a request handler a host's backend mounts. | `src/server/` |
11
+ ## Architecture
12
+
13
+ ### The core abstraction
14
+
15
+ Porthole renders **agent-drawn HTML plus a declared set of host functions.** The HTML is untrusted:
16
+ on its own it can only draw. A **host function (capability)** is any power beyond drawing: send a
17
+ prompt to the agent, open a link, read or write state, call a tool, read data, report an error. The
18
+ config names each with its **gate** (a user gesture, a person's confirmation, shown to the person
19
+ first, a rate limit), its **egress needs** (origins it must reach) and its **guide entry** (how the
20
+ manual describes it).
47
21
 
48
- Inside `src/`:
22
+ One capability list drives three artifacts: the **bridge** (which functions the shell wires and the
23
+ host handles), the **CSP** (what the sandbox may reach) and the **manual** (what the agent is told).
24
+ So the config is the single source (PRINCIPLE 3), and "talk to the agent" is just one host function
25
+ (PRINCIPLE 4).
26
+
27
+ A page published as an artifact may be an app. Under the **capability runtime**, an optional layer
28
+ over the display, it reaches its host through one global, `porthole.use(name)`, for the capabilities
29
+ it declared and its viewer's level allows. Each runtime method is served by a host function the
30
+ config declares; the bridge alone decides each call (the page's declaration, the viewer's level, the
31
+ gates). The services behind them (a document store, an asset library, versions, comments) are the
32
+ host's.
33
+
34
+ ### Layers
49
35
 
50
36
  ```
51
- config/ schema.ts (the config types), capabilities.ts (the vocabulary), validate.ts
52
- compile/ compile.ts (config → CompiledConfig), policy.ts (CSP, sandbox, allow, embedder CSP)
53
- shell/ runtime.ts (the in-frame script, a string), plan.ts (what it wires), document.ts
54
- guide/ guide.ts (manual + tool description), examples.ts
55
- theme/ variables.ts (the default vocabulary, resolveTheme)
56
- presets/ presets.ts (inlineWidget, liveWidget, artifact, mcpApp, url; LIBRARY_CDNS)
57
- libraries/ libraries.ts (VENDORED_LIBRARIES), files.generated.ts (their bytes, P079)
58
- protocol/ adapter.ts (the adapter seam), mcp-apps.ts (method names, HostContext), jsonrpc.ts
59
- bridge/ types.ts (the host-function bridge)
60
- transport/ types.ts platform/ types.ts isolation/ types.ts
61
- host/ types.ts (host API), create-host.ts
62
- react/ mcp/ conformance/ server/ the subpath entries
37
+ ┌──────────────────────────────────────────────────────────┐
38
+ │ Host app (owns product policy, theme, callbacks) │
39
+ └───────────────┬──────────────────────────────────────────┘
40
+ │ picks a preset, passes theme + callbacks
41
+ ┌─────────────────────────▼─────────────────────────────────────────┐
42
+ │ PRESET POLICY LAYER │
43
+ │ inline-widget · artifact · mcp-app · url │
44
+ │ each = a config: CSP+origins, capabilities+gates, theme, guide │
45
+ └─────────────────────────┬─────────────────────────────────────────┘
46
+ │ one config
47
+ ┌─────────────────────────▼─────────────────────────────────────────┐
48
+ │ FRAMEWORK LAYER (mechanisms only, no policy) │
49
+ │ │
50
+ │ config compiler ── CSP + sandbox/allow attrs │
51
+ │ └── shell runtime (what to wire) │
52
+ │ └── guide + tool description │
53
+ │ │
54
+ │ isolation core · egress hardening · streaming render · auto-size │
55
+ │ theming · host-function bridge · guide gen · serving (/server) │
56
+ └───────┬───────────────────────────────────────┬────────────────────┘
57
+ │ host side │ in-frame side (shell)
58
+ ┌───────▼─────────┐ ┌───────▼──────────────────┐
59
+ │ PROTOCOL ADAPTER│ ◄── transport ──► │ SHELL (runs first in │
60
+ │ (MCP Apps; …) │ (postMessage/ │ the isolated frame; │
61
+ │ │ native bridge) │ renders HTML, wires caps)│
62
+ └───────┬─────────┘ └───────────────────────────┘
63
+ │
64
+ ┌───────▼───────────────────────────────────────────────────────────┐
65
+ │ PLATFORM HOST web (iframe) now · WKWebView / Android later │
66
+ └─────────────────────────────────────────────────────────────────── ┘
63
67
  ```
64
68
 
65
- Tooling: Node ≥ 24 running TypeScript by type stripping (erasable syntax only;
66
- relative imports carry `.ts`), pnpm 11, TypeScript 7 for typechecking, oxlint
67
- (type-aware) and oxfmt, vitest for unit tests (`packages/porthole/test/`), and
68
- Playwright for the leak suite (`packages/porthole/leak/`). In the workspace the
69
- package exports its sources; `pnpm build` emits JS and declarations to `dist/`,
70
- which a packed package exports instead (Node does not strip types under
71
- `node_modules`).
69
+ #### Framework layer (mechanisms)
70
+
71
+ Pure mechanism: no product policy, no host or vendor types.
72
+
73
+ - **Config compiler.** One config → the CSP, the iframe `sandbox` and `allow` attributes, the
74
+ shell's wiring, the guide and tool description. Pure and deterministic, so a test asserts the
75
+ outputs agree.
76
+ - **Isolation core.** Puts content on an origin that is never the host's, with nothing of the host's
77
+ reachable: an opaque-origin frame, or a served origin of its own (domain mode: a subdomain per
78
+ storage scope on a separate registrable domain; url mode: the app's own origin). Config picks the
79
+ mode; nothing else depends on which.
80
+ - **Egress hardening.** The closed-by-default network and navigation walls, plus in-shell defenses
81
+ for channels a CSP doesn't cover.
82
+ - **Shell runtime.** Runs first in the frame: applies the theme, inserts the HTML (streaming-aware),
83
+ reports size and errors, exposes the declared host functions.
84
+ - **Host-function bridge.** Carries capability calls to the host and results back over a transport,
85
+ validating and gating at the boundary.
86
+ - **Streaming render, auto-size, theming, guide generator**, each usable alone. Content is plain
87
+ HTML and SVG, styled by theme variables, never a component vocabulary (P015).
88
+ - **Serving** (`/server`). A request handler a host's backend mounts for served modes: documents on
89
+ their own origins, CSP in headers, entered by a one-time ticket the host minted that becomes a
90
+ cookie of that origin only. A stored version is one page or a set of files, each looked up in the
91
+ version's manifest only, typed by Porthole's own table, served under that version's own address.
92
+
93
+ #### Preset policy layer
94
+
95
+ A preset is a named config with safe defaults: CSP and origins, capabilities and gates, theme
96
+ vocabulary, manual. A host overrides only theme and callbacks. The presets (inline-widget, artifact,
97
+ mcp-app, url) are in § The modes.
98
+
99
+ #### Protocol adapters
100
+
101
+ A thin adapter maps capability and lifecycle events onto a wire protocol; **MCP Apps** is the first
102
+ and default. Only the adapter knows protocol method names and shapes (§ The MCP Apps adapters).
103
+
104
+ #### Platform hosts
105
+
106
+ The platform host owns the isolation primitive and the transport: `iframe` + `postMessage` on the
107
+ web now, `WKWebView` + a message handler on iOS later. The framework is written against a small
108
+ platform interface, so a new platform is an implementation, not a fork.
109
+
110
+ #### Conformance / leak suite
111
+
112
+ A standalone runner drives a platform host through an adapter and attempts every known egress and
113
+ escape channel, asserting none succeeds. Any host can run it on its own integration. It is our
114
+ regression gate and what we offer upstream (PRINCIPLE 5, 6).
115
+
116
+ ### Contracts between layers
117
+
118
+ | Between | What passes |
119
+ | --- | --- |
120
+ | Host → preset | a preset name, theme tokens (resolved per color scheme), callbacks for each enabled host function; nothing else |
121
+ | Preset → framework | one config: capabilities with gates and egress needs, allowed origins, theme variable map, limits, layout, mode, isolation |
122
+ | Config → {CSP, shell, guide} | derived, never hand-written; a test asserts they agree |
123
+ | Framework ↔ shell | lifecycle and capability messages, validated both ways; unknown or malformed ones dropped |
124
+ | Framework ↔ adapter | capability/lifecycle events ↔ protocol messages, plus protocol-only ones (handshake, teardown) the framework doesn't model |
125
+ | Framework ↔ platform host | create an isolated surface, set its policy (CSP/sandbox/allow or native equivalent), send and receive messages, report size, tear down |
126
+
127
+ So *which protocol* (adapter), *which platform* (platform host) and *what policy* (preset/config)
128
+ vary independently. A new protocol is a new adapter plus a preset selecting it; the core and shell
129
+ mechanisms are untouched. A new platform is a new platform-host implementation; the shell runtime is
130
+ plain, dependency-free script that runs as-is in a new engine.
131
+
132
+ ### Flows per mode
133
+
134
+ #### Inline widget
135
+
136
+ ```
137
+ Host app Framework/Adapter Shell (opaque frame)
138
+ │ mount(config, cbs) │ │
139
+ │──────────────────────────►│ compile config → CSP, │
140
+ │ │ sandbox attrs, shell doc │
141
+ │ │ create opaque frame ───────►│ (shell runs first)
142
+ │ │◄──── initialize ─────────────│
143
+ │ │──── host context (theme, │
144
+ │ │ capabilities, size) ────►│
145
+ │ content (may stream) ───►│──── content (partial*) ─────►│ draw inert
146
+ │ │──── content (complete) ─────►│ run
147
+ │ │◄──── size / error ───────────│
148
+ │◄── onError / onResize ────│ │
149
+ │ │◄──── capability call ────────│ (e.g. sendPrompt)
150
+ │◄── gate (confirm?) ───────│ validate + gate │
151
+ │── result ────────────────►│──── result ─────────────────►│
152
+ ```
153
+
154
+ `*` partial content is drawn inert (no scripts, handlers or navigation) until complete (§
155
+ Streaming).
156
+
157
+ #### MCP Apps view
158
+
159
+ Same shape, the adapter speaking MCP Apps. The view is an MCP Apps `App`; `initialize`/`initialized`
160
+ is the handshake; content arrives as tool input (tool-input-partial, then tool-input) and tool
161
+ result; capability calls (`ui/message`, `ui/open-link`, etc.) map to host functions. On the web a
162
+ second-origin sandbox proxy relays messages, isolating arbitrary MCP App HTML (which expects
163
+ `allow-same-origin`) from the host, transparently to both.
164
+
165
+ #### Artifact page
166
+
167
+ A real document at a URL on a separate registrable domain, CSP in HTTP headers, framed by the host;
168
+ its `frame-ancestors` names the host. No code injection; the shell is optional. A page's own files
169
+ (stylesheets, scripts, data, images, other pages) are served beside it under its version's address;
170
+ its CSP opens that path and nothing else of its origin, and every page of the set gets the shell.
171
+ Access: a one-time ticket exchanged for a scoped cookie. Where the host holds the page and needs no
172
+ stable origin, the shell writes it into an opaque frame instead.
173
+
174
+ #### URL frame
175
+
176
+ ```
177
+ Host app Host backend (+ /server) App origin (served)
178
+ │ mount(url preset) │ │
179
+ │── locate ─────────►│ decide the viewer may see it, │
180
+ │◄── ticketed URL ───│ mint a one-time ticket │
181
+ │ frame src = URL ──────────────────────────────────────►│ ticket → cookie
182
+ │ │ (that origin only)
183
+ ```
184
+
185
+ No shell and no protocol: the app is someone else's. The embedding page frames only the declared
186
+ content origins.
187
+
188
+ ### Trust boundaries
189
+
190
+ Attackers, out of scope, and several displays on one page: [THREAT_MODEL.md](THREAT_MODEL.md) (§ 3,
191
+ § 4).
192
+
193
+ 1. **Host ↔ content.** The hard boundary. Content runs on an origin never the host's, so the
194
+ same-origin policy denies it the host's DOM, storage, cookies and credentials; it never holds a
195
+ host secret. Everything beyond drawing crosses the bridge as a validated, gated call. What
196
+ content says is its own word; the host confirms with a person where the gate says so.
197
+ 2. **Content ↔ the network.** Closed by default; open only to the origins declared capabilities
198
+ need, plus, for a served page with files, its version's path on its own origin and its artifact's
199
+ asset library at `/_blob/` (the host's own server, P082, P089). Origin isolation stops attacks on
200
+ the host, the catastrophic class. Leaking and deceiving are stopped by egress hardening, gates,
201
+ and approvals drawn outside the frame (THREAT_MODEL.md § 4). Channels that bypass a frame's
202
+ `connect-src` (ICE gathering, self-navigation, a nested frame's fresh realm) are closed by
203
+ in-shell defenses and the embedding page's policy, each with a probe. A served page outside its
204
+ frame carries the sandbox in its CSP header (P099); an opaque frame also inherits its page's
205
+ policy (P058).
206
+ 3. **Host's decision ↔ what a page may do.** Under the capability runtime a page reaches only the
207
+ built-ins and what it declared at publish (stored by the host, given to the mount), each method
208
+ only for viewers at its level (`view < interact < admin < owner`) as the host's access says. The
209
+ bridge refuses before any handler; the host's API checks again, as its data's wall. Per-user data
210
+ is reached by the host's id for the person, never the content's word.
211
+ 4. **Message boundary.** Every message crossing the frame is schema-validated and its sender
212
+ checked: the shell takes messages only from its host, the host only from its frame. What the
213
+ frame says about itself (size, errors, an annotation's anchor and place, find's match count) is
214
+ the content's word even when the shell says it, since they share a realm: the host bounds it and
215
+ uses it as a UI hint, never a permission (P053, P131). What the host sends in (a mark, a find
216
+ query) the content can read.
217
+ 5. **Host's decision ↔ content domain.** Authentication and authorization *policy* are the host's;
218
+ carrying its decision onto the content domain is Porthole's *mechanism*. The host decides who may
219
+ open an instance before it calls `issue` (a viewer, or a public link), and may decide again per
220
+ request (`ServerOptions.authorize`). Porthole carries the decision as a one-time ticket, then a
221
+ signed cookie of that origin and instance with the host's opaque `subject` inside, and never
222
+ interprets identity. A deny ends access from the next request on and tells the display why.
223
+
224
+ ### Extension points
225
+
226
+ - **Capabilities.** A new host function joins the vocabulary with a gate, egress need and guide
227
+ entry, extending bridge, CSP and manual together.
228
+ - **Protocol extension points.** MCP Apps gaps go through the spec's own mechanisms (experimental
229
+ capabilities, own-prefixed methods), so the external contract stays standard (PRINCIPLE 2).
230
+ - **Theme variables.** The theme map is config; the MCP Apps variable names are the default
231
+ vocabulary.
232
+ - **Host-drawn features**, each in its section: the clipboard (content asks with `copyText`; the
233
+ host copies and shows what, P051, P052); the capability runtime (`config.runtime`: per contract
234
+ version, namespaces of methods over host functions with a versioned `.d.ts`); annotations
235
+ (`annotate`, P053: the host drives a select mode, stores W3C Web Annotation anchors with its
236
+ comments, and answers a marker's click with its own UI outside the frame); find in page (`find`:
237
+ the host's find bar, the shell's highlights).
238
+ - **Served content.** A host plugs into `/server`: who may see what (`authorize`), where tickets
239
+ live (`TicketStore`: memory, D1), how origins are named (`content.name`, other servers' `reserved`
240
+ namespaces), where apps and versions come from (`upstream`, `artifacts`: a page, or a manifest of
241
+ files and their bytes), which address means which version (`entry.at`). It runs on any runtime
242
+ with web-standard `Request`/`Response` (Node, Workers).
243
+
244
+ ## Package layout
245
+
246
+ One package, `@botiverse/porthole` (`packages/porthole`), with subpath exports (P013), listed in the
247
+ package README's Subpaths; the source tree is in AGENTS.md § Layout. The core (`src/index.ts`) has
248
+ no DOM framework, no host and no MCP SDK. `/react` has the peer `react`, `/conformance` the peer
249
+ `@playwright/test`; `/mcp` depends on the core only. Node ≥ 24 runs the TypeScript by type
250
+ stripping. In the workspace the package exports its sources; `pnpm build` emits JS and declarations
251
+ to `dist/`, which a packed package exports (Node does not strip types under `node_modules`).
72
252
 
73
253
  ## Config schema
74
254
 
75
- One config per kind of display (`src/config/schema.ts`); `validateConfig` refuses
76
- a bad one whole (unknown fields, capabilities or gates; any origin that isn't
77
- exactly `scheme://host[:port]`, so nothing can inject a CSP directive; theme values
78
- that could break out of CSS). Presets return validated configs.
255
+ One config per kind of display (`src/config/schema.ts`). `validateConfig` refuses a bad one whole:
256
+ unknown fields, capabilities or gates; any origin not exactly `scheme://host[:port]` (so nothing can
257
+ inject a CSP directive); theme values that could break out of CSS. Presets return validated configs.
79
258
 
80
259
  ```ts
81
260
  interface PortholeConfig {
@@ -99,8 +278,8 @@ interface PortholeConfig {
99
278
  type Gate = "user-activation" | "confirm" | "consent" | "show" | { rateLimit: { perMinute: number } };
100
279
  ```
101
280
 
102
- `mode` and `isolation` select the mechanism; everything else is policy. There is
103
- no `components` field (P015).
281
+ `mode` and `isolation` select the mechanism; the rest is policy. There is no `components` field
282
+ (P015).
104
283
 
105
284
  ### The capability vocabulary
106
285
 
@@ -123,618 +302,458 @@ no `components` field (P015).
123
302
  | `assets` (runtime, served artifacts) | 30/min | handler (`op: list \| upload \| delete`) | `porthole.use("assets")` | `porthole/call`; `/server` serves `/_blob/<id>` (P089) |
124
303
  | `db` (runtime) | 600/min | handler (`op: get \| query \| watch \| set \| update \| delete \| batch`) | `porthole.use("db")` | `porthole/call`, `porthole/event`, `porthole/unwatch` (P088) |
125
304
 
126
- Every preset declares only `resize` and `reportError` (they report to the host and
127
- carry nothing out); the host declares the rest. Gates are explained in P021: all
128
- must pass; `confirm` calls the host's `confirm` function and fails closed without
129
- one; `user-activation` (by default `copyText`'s alone since 0.16.0, P149; a host may name it
130
- for any other) is checked by the shell (advisory: it shares the content's
131
- realm) and by the host where the engine passes the gesture up; `consent` asks the
132
- host's `consent` function once per display, before its first consent-gated call,
133
- and fails closed without one (P079); a `Refused` given as `consent` refuses them all,
134
- asking nothing, and their capabilities need no handler (P080); `show` calls the host's
135
- `show` function with the call's whole effect before the handler runs, asking nothing, and
136
- fails closed without one, or when it throws (P100: by default every model context update,
137
- which the person sees outside the frame before the agent's next turn; the React binding's
138
- `ContextNotice` is the default surface). A refused request's
139
- error carries why, `data: { code, message }` (`consent_required`, `denied`,
140
- `rate_limited`, `not_allowed`, `failed`; the host's `Refused` words its own, P080). `presets.liveWidget` declares `readData` and
141
- `subscribeData` with `consent` and its rate, and keeps egress closed (no option opens
142
- it: it refuses `egress` and a capability's own `connect` or `resource`, P103); served, it loads
143
- Porthole's libraries from its origin (`egress.libraries`).
305
+ Presets declare only `resize` and `reportError` (they report to the host and carry nothing out); the
306
+ host declares the rest. All gates must pass (P021):
307
+ - `confirm` calls the host's `confirm`; fails closed without one.
308
+ - `user-activation` (by default `copyText`'s alone, P149; a host may name it for any other) is
309
+ checked by the shell (advisory: same realm as the content) and by the host where the engine passes
310
+ the gesture up.
311
+ - `consent` asks the host's `consent` once per display, before the first consent-gated call; fails
312
+ closed without one (P079). A `Refused` given as `consent` refuses them all without asking, and
313
+ their capabilities need no handler (P080).
314
+ - `show` hands the host's `show` the call's whole effect before the handler, asking nothing; fails
315
+ closed without one or when it throws (P100). By default every model context update is shown, so
316
+ the person sees it outside the frame before the agent's next turn; the React binding's
317
+ `ContextNotice` is the default surface.
318
+
319
+ A refusal says why: `data: { code, message }` (`consent_required`, `denied`, `rate_limited`,
320
+ `not_allowed`, `failed`; a host's `Refused` words its own, P080).
144
321
 
145
322
  ## What the compiler derives
146
323
 
147
324
  `compile(config)` (`src/compile/compile.ts`) validates the config and returns:
148
325
 
149
- - `csp` / `cspDirectives`: the frame's policy. `default-src 'none'`; scripts may be
150
- inline (agent content is inline), `'unsafe-eval'` (content is the agent's own script already,
151
- so eval adds no capability, and libraries content uses compile with it, WebAssembly too: P071),
152
- plus `blob:` and the script origins (and, with `egress.libraries`, Porthole's library path on
153
- the content origins, `<origin>/__porthole/lib/`, P079); each other
154
- kind opens only to its origins; `connect-src 'none'` unless something is
155
- declared; `frame-src`, `object-src`, `base-uri`, `form-action` all `'none'`;
156
- `webrtc 'block'`. Never `'self'` (P022). Empty in url mode.
157
- - `sandbox`: `allow-scripts` (opaque); `allow-scripts allow-same-origin` (domain,
158
- P016); `allow-scripts allow-same-origin allow-forms` (url, P020).
159
- - `allow`: empty (no powerful feature delegated).
160
- - `embedderFrameSources` (and `embedderCsp(configs)` for a page that shows several
161
- kinds): `frame-src 'self'` plus content origins plus the host's own frames, and
162
- `child-src` the same; no `default-src`.
163
- - `shell` (the plan) and `shellDocument({ origins, title?, document?, cspMeta? })`:
164
- the frame's document with the CSP `<meta>` first, the base styles, and the runtime
165
- given its plan. A given `document` (an MCP Apps view, a served page) travels in the
166
- plan as data; the runtime renders it as it renders any document (§ The shell
167
- runtime), never handing its markup to the page's parser.
168
- - `guide(topics?)` and `toolDescription()`: the manual and the show tool's
169
- description.
170
-
171
- **The agreement test** (`test/agreement.test.ts`) compiles every preset and
172
- variations of it, and asserts: the shell injects exactly the config's theme
173
- variables and the manual teaches exactly them; the manual names exactly the
174
- globals the shell defines, and the runtime defines each; the shell wires exactly
175
- the declared capabilities, and each capability's manual entry states its gates
176
- (confirm, click, rate); the manual names exactly the origins the CSP allows; each
177
- CSP directive equals the egress plus the declared capabilities' needs; the manual
178
- states the limits, layout and theme event; and changing the config (opening an
179
- origin, dropping a capability or a variable, overriding an entry) changes all of
180
- them together. The leak suite's `0.*` probes check the same wiring in real frames.
326
+ - `csp` / `cspDirectives`: `default-src 'none'`. Scripts: inline (agent content is inline),
327
+ `'unsafe-eval'` (the content is the agent's script already, so eval adds nothing; libraries
328
+ content uses compile with it, WebAssembly too: P071), `blob:`, the script origins, and with
329
+ `egress.libraries` Porthole's library path `<origin>/__porthole/lib/` on the content origins
330
+ (P079). Other kinds open only to their origins; `connect-src 'none'` unless declared; `frame-src`,
331
+ `object-src`, `base-uri`, `form-action` all `'none'`; `webrtc 'block'`. Never `'self'` (P022).
332
+ Empty in url mode.
333
+ - `sandbox`: `allow-scripts` (opaque); `allow-scripts allow-same-origin` (domain, P016);
334
+ `allow-scripts allow-same-origin allow-forms` (url, P020). `allow`: empty (nothing delegated).
335
+ - `embedderFrameSources` (and `embedderCsp(configs)` for a page showing several kinds): `frame-src
336
+ 'self'` plus the content origins and the host's own frames, `child-src` the same; no
337
+ `default-src`.
338
+ - `shell` (the plan) and `shellDocument({ origins, title?, document?, cspMeta? })`: the frame's
339
+ document, CSP `<meta>` first, then base styles and the runtime with its plan. A given `document`
340
+ (an MCP Apps view, a served page) travels in the plan as data and is rendered as any document (§
341
+ The shell runtime), never handed to the page's parser.
342
+ - `guide(topics?)` and `toolDescription()`: the manual and the show tool's description.
343
+
344
+ **The agreement test** (`test/agreement.test.ts`) compiles every preset and variations, and asserts:
345
+ the shell injects exactly the config's theme variables and the manual teaches exactly them; the
346
+ manual names exactly the globals the shell defines, and the runtime defines each; the shell wires
347
+ exactly the declared capabilities, and each one's manual entry states its gates (confirm, click,
348
+ rate); the manual names exactly the origins the CSP allows; each CSP directive equals the egress
349
+ plus the declared capabilities' needs; the manual states the limits, layout and theme event; and a
350
+ config change (opening an origin, dropping a capability or variable, overriding an entry) changes
351
+ all of them together. The leak suite's `0.*` probes check the same wiring in real frames.
181
352
 
182
353
  ## Public interfaces
183
354
 
184
- The seams other work builds against. Interfaces are typed in the files below;
185
- functions not built yet throw `NotBuiltYet` naming their milestone.
186
-
187
- | Seam | File | Built by | Used by |
188
- | --- | --- | --- | --- |
189
- | Config, presets, compiler, guide, theme | `src/config/`, `src/presets/`, `src/compile/`, `src/guide/`, `src/theme/` | core (M1, done) | everyone |
190
- | Host API: `createHost`, `MountOptions`, `DisplayHandle`, `DisplayEvents` | `src/host/types.ts`, `src/host/create-host.ts` | core (M2, built: opaque, domain and url frames) | React binding, hosts |
191
- | Isolation: `InstanceRef`, `ServedDocument`, `InstanceLocator`, `FrameLocation`, `FrameSource`; `checkFrameLocation` | `src/isolation/types.ts`, `src/isolation/served.ts` | core; served modes (the checks) | served modes, hosts |
192
- | Platform host: `PlatformHost`, `Surface`, `SurfaceSpec`; `webPlatform` | `src/platform/` | core (web, M2, built) | native hosts later |
193
- | Transport; `postMessageTransport` | `src/transport/` | core (M2, built) | adapters |
194
- | Protocol adapter: `ProtocolAdapter`, `AdapterSession`, `AdapterConnection`, `ShellConnection`; `shellAdapter` | `src/protocol/adapter.ts`, `src/protocol/shell-adapter.ts` | core (shell adapter, M2, built) | MCP adapter |
195
- | MCP Apps names: `MCP_APPS_METHODS`, `MCP_APPS_STYLE_VARIABLES`, `PORTHOLE_STYLES`, `HostContext`; JSON-RPC parsing | `src/protocol/mcp-apps.ts`, `src/protocol/jsonrpc.ts` | core | shell, both adapters |
196
- | MCP Apps adapter: `mcpAppsAdapter`, `McpAppConnection`, `viewEgress`, `readViewResource`, `MCP_APPS_STYLE_VARIABLES`, `sandboxProxyDocument` | `src/mcp/` | MCP adapter (done) | hosts showing MCP Apps views |
197
- | Host-function bridge: `HostFunctionBridge`, `CapabilityHandlers`, `Confirm`, `ConfirmRequest`, `Refusal`; `createBridge` | `src/bridge/` | core (M2–M3, built and proven) | adapters, hosts |
198
- | React: `PortholeProvider`, `PortholeFrame`, `ConfirmDialog`, `admitFrame` | `src/react/` | core (M4, built) | first host |
199
- | Conformance: `ConformanceHost`, `LaunchSpec`, `LaunchedDisplay`, `defineLeakSuite`, `PROBES`, the oracles; `defineServedSuite`, `ServedConformanceHost` | `src/conformance/` | core (M2, built); served modes (done) | any host |
200
- | Server: `createServer`, `PortholeServer`, `TicketStore`, `ArtifactStore`, `ContentDomain`, `Grant`, `Access`, `Upstream`, `proxyTo`, `memoryTicketStore` | `src/server/` | served modes (done) | host backends |
201
- | Files (P081): `checkFileSet`, `filePathProblem`, `fileLimits`, `requestFilePath`, `lookupFile`, `fileTypeOf`, `servesFiles`; `StoredFiles`, `FileAddress`, `versionedAddress`; `lintFiles`, `admitFiles` | `src/files/`, `src/server/files.ts`, `src/check/files.ts` | 0.6 (done) | host backends, publish tools |
355
+ The seams other work builds against, typed in these files.
202
356
 
203
- ### Host API
357
+ | Seam | File | Used by |
358
+ | --- | --- | --- |
359
+ | Config, presets, compiler, guide, theme | `src/config/`, `src/presets/`, `src/compile/`, `src/guide/`, `src/theme/` | everyone |
360
+ | Host API: `createHost`, `MountOptions`, `DisplayHandle`, `DisplayEvents` | `src/host/types.ts`, `src/host/create-host.ts` | React binding, hosts |
361
+ | Isolation: `InstanceRef`, `ServedDocument`, `InstanceLocator`, `FrameLocation`, `FrameSource`; `checkFrameLocation` | `src/isolation/types.ts`, `src/isolation/served.ts` | served modes, hosts |
362
+ | Platform host: `PlatformHost`, `Surface`, `SurfaceSpec`; `webPlatform` | `src/platform/` | native hosts later |
363
+ | Transport; `postMessageTransport` | `src/transport/` | adapters |
364
+ | Protocol adapter: `ProtocolAdapter`, `AdapterSession`, `AdapterConnection`, `ShellConnection`; `shellAdapter` | `src/protocol/adapter.ts`, `src/protocol/shell-adapter.ts` | MCP adapter |
365
+ | MCP Apps names: `MCP_APPS_METHODS`, `MCP_APPS_STYLE_VARIABLES`, `PORTHOLE_STYLES`, `HostContext`; JSON-RPC parsing | `src/protocol/mcp-apps.ts`, `src/protocol/jsonrpc.ts` | shell, both adapters |
366
+ | MCP Apps adapter: `mcpAppsAdapter`, `McpAppConnection`, `viewEgress`, `readViewResource`, `MCP_APPS_STYLE_VARIABLES`, `sandboxProxyDocument` | `src/mcp/` | hosts showing MCP Apps views |
367
+ | Host-function bridge: `HostFunctionBridge`, `CapabilityHandlers`, `Confirm`, `ConfirmRequest`, `Refusal`; `createBridge` | `src/bridge/` | adapters, hosts |
368
+ | React: `PortholeProvider`, `PortholeFrame`, `ConfirmDialog`, `admitFrame` | `src/react/` | hosts |
369
+ | Conformance: `ConformanceHost`, `LaunchSpec`, `LaunchedDisplay`, `defineLeakSuite`, `PROBES`, the oracles; `defineServedSuite`, `ServedConformanceHost` | `src/conformance/` | any host |
370
+ | Server: `createServer`, `PortholeServer`, `TicketStore`, `ArtifactStore`, `ContentDomain`, `Grant`, `Access`, `Upstream`, `proxyTo`, `memoryTicketStore` | `src/server/` | host backends |
371
+ | Files (P081): `checkFileSet`, `filePathProblem`, `fileLimits`, `requestFilePath`, `lookupFile`, `fileTypeOf`, `servesFiles`; `StoredFiles`, `FileAddress`, `versionedAddress`; `lintFiles`, `admitFiles` | `src/files/`, `src/server/files.ts`, `src/check/files.ts` | host backends, publish tools |
204
372
 
205
- ```ts
206
- import { createHost, presets, LIBRARY_CDNS } from "@botiverse/porthole";
207
-
208
- const host = createHost(
209
- presets.inlineWidget({
210
- capabilities: { sendPrompt: {}, openLink: {} }, // default gates
211
- egress: LIBRARY_CDNS, // opt in to library CDNs
212
- guide: { toolName: "show_widget", guideToolName: "display_guide" },
213
- }),
214
- {
215
- handlers: { sendPrompt: ({ text }, call) => send(text, call.displayId), openLink: ({ url }) => open(url) },
216
- confirm: (request) => askThePerson(request), // or the React binding's default dialog
217
- theme: (scheme) => readMyTokens(scheme), // live values for the config's names
218
- },
219
- );
220
-
221
- const display = host.mount(container, { displayId, title, scheme: "light" });
222
- display.setContent(code, { partial: true }); // while the agent writes it
223
- display.setContent(code); // once, whole: now it runs
224
- display.setTheme("dark");
225
- display.on("resize", ({ height }) => {});
226
- display.on("error", ({ message }) => {});
227
- display.on("outcome", (outcome) => {}); // loaded | blocked (why) | timeout (P040)
228
- display.refreshTheme(); // the host's values changed without a flip
229
- display.destroy();
230
-
231
- host.compiled.guide(["widget", "chart"]); // the manual, from the same config
232
- host.compiled.toolDescription();
233
- host.compiled.csp; // the exact CSP, for audit
234
- embedderCsp([config]); // what the embedding page must send
235
- ```
373
+ ### Host API
236
374
 
237
- `mount` throws if a declared capability served by a handler has none, so a manual
238
- never teaches a function nobody serves. A `DisplayHandle` is the framework's
239
- controls plus the adapter's own operations (`setContent` for the shell adapter;
240
- the MCP adapter adds its own, such as a tool result).
375
+ `createHost(config, options)` takes one config, the host's handlers, `confirm` and theme.
376
+ `host.mount(container, …)` gives a `DisplayHandle`: `setContent` (partial, then whole), `setTheme`,
377
+ `refreshTheme`, events `resize`, `error`, `outcome` (loaded, blocked and why, or timeout: P040),
378
+ `destroy`; the adapter adds its own operations (the MCP adapter, a tool result). `mount` throws if a
379
+ declared handler-served capability has no handler, so the manual never teaches a function nobody
380
+ serves. `host.compiled` holds the manual, the tool description and the exact CSP;
381
+ `embedderCsp([config])` is what the embedding page must send. Wiring: [ADOPTING.md](ADOPTING.md) §
382
+ "3. Opaque displays".
241
383
 
242
384
  ### Isolation modes and served content
243
385
 
244
- Opaque frames need nothing from outside: the host builds the shell document and
245
- the frame is `srcdoc`. Served frames (domain, external) load a URL: the host's
246
- `InstanceLocator` turns an `InstanceRef` into a `FrameLocation`, usually by asking
247
- the host's own backend, which authenticates the viewer, decides they may see it,
248
- and calls `PortholeServer.issue`.
249
-
250
- - **Storage is keyed by origin.** An `InstanceRef` names its `scope` (the host's
251
- choice: a display id, an app id); `/server` maps each scope to
252
- `<label>.<content domain>`, the label keyed from the scope with the server's
253
- secret. Same scope, same origin, shared storage; different scope, nothing shared.
254
- Browsers partition a framed origin's storage by the top-level site, so it is
255
- stable within one host app.
256
- - **What a served frame loads** is a `ServedDocument`: the shell (content then
257
- arrives over the transport, as for opaque frames), a stored artifact version, the
258
- MCP Apps sandbox proxy, or an external app (url mode).
259
- - **A served page carries its frame's sandbox** (P099). Every page `/server` serves (a shell, an
260
- artifact page, a set's page, the sandbox proxy; not a url-mode app's own documents) sends
261
- `sandbox allow-scripts allow-same-origin` in its CSP header (`servedSandboxDirective`: the
262
- frame's own tokens). In a frame it repeats the attribute; on a tab of its own (a public link, a
263
- new tab, a frame's address opened outside it) it is the only sandbox: no popups, forms,
264
- downloads, modals or navigation of another window. Its `Permissions-Policy` header denies what
265
- the frame's `allow` doesn't grant (`servedPermissionsPolicy`: camera, microphone, location, full
266
- screen and the rest of `FRAME_DENIED_FEATURES`), changing nothing in a frame. On a tab the shell
267
- also answers `window.open` with null (but `_self`), refuses picture-in-picture windows, devices,
268
- location and full screen (for engines that don't read the header), and its navigation guard
269
- stops the page navigating itself away (an engine without the Navigation API has no wall for
270
- that on a tab: P099's accepted limit).
271
- - **A version made of files** (P081–P084). The store answers a manifest (`files`: path →
272
- `{ size, sha256, type? }`, an `entry`, `spa`) and `read(path)`; `{ html }` stays one page. Every
273
- file is looked up in the manifest only, by the path below the version's base, decoded once
274
- (`requestFilePath`, `lookupFile`: `dir/` is its `index.html`, `name` is `name.html`, the nearest
275
- `404.html`, the entry for a single-page app's navigations). Its answer is typed by Porthole's
276
- table (`fileTypeOf`; unknown: a download), `nosniff`, with its CSP (a page's and a script's: the
277
- frame's plus the version's own path, P082; anything else `default-src 'none'; sandbox`), a
278
- strong ETag and 304, ranges, `Cross-Origin-Resource-Policy: same-origin` (files), and the cache
279
- rule of its address (files immutable, pages revalidated); a service worker's script is refused.
280
- Every page is in the shell. Its address: in a frame, `/__porthole/f/<sealed access>/<path>` (the
281
- ticket's answer is the entry, whose shell moves to that address first, P083); on a tab, the
282
- version's own clean address, `entry.at`'s `base` (`/v/3/`), where an address that means the
283
- latest (`/`, `/style.css`) is redeemed (P081). So a page never mixes versions: its relative
284
- addresses are its version's. A set's pages open each other in the frame (P084).
285
- - **Tickets** are minted by `issue` (one-time, short-lived, bound to an instance and
286
- a viewer, stored as their hash), carried once in the frame's URL, and taken by the
287
- content origin. A served document (at `/__porthole/d/<instance key>`) comes back in
288
- that same answer, with a cookie of that origin and instance only (`__Host-`,
289
- `Secure`, `HttpOnly`, `SameSite=None; Partitioned` in a frame, `Lax` on a tab) for
290
- what follows, a reload; a url-mode app's ticket buys the cookie and redirects to
291
- the app's own landing path, every request of the app riding on the cookie. WebKit
292
- keeps no cookie in a cross-site frame (measured), so a framed url-mode app runs
293
- only where the engine keeps partitioned cookies; elsewhere the host opens it on a
294
- tab (P025).
295
- - **Separation is checked.** The content domain is a registrable domain the host
296
- uses for nothing else, and a mount refuses a located origin that doesn't match
297
- `contentOrigins` or is same-site with the host.
298
- - **Names** (P047). By default a scope's label is keyed (24 base32 characters). A
299
- host may name its own (`content.name`; `prefixedName("a-")` gives `a-<scope>`,
300
- one-to-one): one lowercase DNS label, never an IDNA form or a `reserved` one.
301
- `reserved` labels are other servers' namespaces under the same domain (`f` for
302
- `<label>.f.<domain>`) or the host's own (`p-*`: every label starting `p-`; or a
303
- function of the label, P056): requests for them and anything under them return
304
- null, to the host's routes; any other deeper name gets this server's 404.
305
- - **Requests** (P056). The label is the request URL's; a request whose Host header
306
- names another host, where either is under the content domain, gets a 400 (a Node
307
- adapter builds the URL from an absolute-form target, and a host or a cache routes
308
- by Host). A Host that is a local address (an IP literal, `localhost`), as a test
309
- runner sends, isn't compared. A server without an `upstream` serves only Porthole's
310
- own paths: any other is a plain 404. Every answer says `x-robots-tag: noindex`.
311
- - **Who** (P046, P050). A grant names a `viewer`, or is `anonymous` (a public link:
312
- documents only, never a url-mode app), and may carry the host's opaque `subject`
313
- (a share or session id), signed into the ticket and the cookie. The host's
314
- `authorize.check` runs after a ticket or cookie verifies and before anything is
315
- served: document loads, url-mode entry, every app request, `/__porthole/session`
316
- and `access()`. A deny is a 403 status page (`denied`, the host's code); answers
317
- are not reused unless the host sets `ttlSeconds` (at most 300).
318
- - **Runtimes** (P044, P045). `/server` uses no Node module (hashing in plain
319
- JavaScript, randomness from `crypto.getRandomValues`), so it runs on Cloudflare
320
- Workers without `nodejs_compat`; tickets there live in D1 (`d1TicketStore`, taken
321
- by one `DELETE … RETURNING`), never KV (eventually consistent). Sessions are
322
- signed cookies: no store.
323
-
324
- `/server`'s handler is fetch-style (`Request → Response | null`, null for requests
325
- that aren't for the content domain or are in a reserved namespace), so a backend
326
- mounts it in front of its own routes. Dev and tests use `*.localhost` subdomains, which browsers resolve to
327
- loopback. In url mode an app's requests go, once its cookie checks out, to the
328
- host's `upstream` (`proxyTo` relays them by HTTP, telling the app it is on its own
329
- origin and nothing of the proxy); WebSockets take the host's own upgrade path, let
330
- in by `PortholeServer.access`. The MCP Apps sandbox proxy is served the same way,
331
- its CSP from the config plus the view's declared egress, signed into the ticket; it
332
- becomes the view rather than nesting it (P026).
333
-
334
- #### Wiring on Cloudflare Workers
335
-
336
- A Worker with Hono, D1 and R2 serving artifact pages on `a-<id>.<content domain>`
337
- (`test/workers/` runs one like it in workerd, with real D1):
338
-
339
- - **Bindings.** A D1 database (`DB`) with `d1TicketSchema()` applied once as a
340
- migration; a secret of at least 32 random bytes (`wrangler secret put
341
- PORTHOLE_SECRET`); the host's own artifact source (R2, D1) behind `artifacts.get`.
342
- No `nodejs_compat`.
343
- - **Routes.** The content domain's wildcard (`*.<content domain>/*`, with wildcard
344
- DNS and a certificate for every level served, `*.f.<domain>` included) and the
345
- host's own domain, to the same Worker, or the content domain to a Worker of its own.
346
- - **Handler.** One server per isolate, made on first use from `env`:
347
-
348
- ```ts
349
- const porthole = createServer({
350
- content: { domain: "example-usercontent.com", scheme: "https", name: prefixedName("a-"), reserved: ["f", "www"] },
351
- secret: new TextEncoder().encode(env.PORTHOLE_SECRET),
352
- hostOrigins: ["https://app.example.com"],
353
- configs: { artifact: presets.artifact({ isolation: "domain", contentOrigins: ["https://*.example-usercontent.com"] }) },
354
- artifacts: { get: (id, version) => env.ARTIFACTS.get(`${id}/${version}`).then((o) => o && o.text()).then((html) => html && { html }) },
355
- tickets: d1TicketStore(env.DB),
356
- authorize: { check: ({ subject }) => stillShared(env, subject) }, // the host's policy
357
- });
358
- app.all("*", async (c, next) => (await porthole.handle(c.req.raw)) ?? next());
359
- ```
360
-
361
- and from the host's own authenticated API, once it has decided the person may see
362
- it, `porthole.issue({ scope: id, document: { kind: "artifact", id, version } },
363
- { viewer: userId, subject: shareId })` (a public share route: `{ anonymous: true,
364
- subject: shareId }`) returns the `FrameLocation` the host page frames. Scopes named
365
- by `prefixedName` must already be label-safe (lowercase letters, digits, inner
366
- hyphens); other ids keep the keyed default.
367
-
368
- A page whose `script-src` is nonce-based (no `'unsafe-inline'`) blocks an opaque
369
- frame's shell: a `srcdoc` frame inherits the embedding page's whole policy (P054).
370
- The host passes its nonce (`HostOptions.nonce`, `PortholeProvider`'s `nonce`); the
371
- shell's script and style carry it, and the shell gives it to every script it runs
372
- for the content. Inline event handlers in content (`onclick="…"`) stay blocked by
373
- such a page's policy, as on the page itself; scripts and `addEventListener` work.
374
- The whole leak suite runs again on a reference page with a nonce-only `script-src`
375
- (`leak/strict-csp.spec.ts`), and passes on all three engines; its negative control
376
- `nonce` (the shell without the nonce) fails it.
377
-
378
- The served modes have their own conformance cases (`defineServedSuite`, run against
379
- `leak/served/`'s reference serving, which starts its own servers per worker): content
380
- runs on its own origin and can't reach the host's DOM, storage, cookies or URL,
381
- navigate the host's page or open a window (domain and url mode, each also after a
382
- click); storage persists within a scope and is never shared across scopes; a ticket
383
- opens its content once; only the host origins may frame content; the CSP in headers
384
- closes egress; each version of an artifact page shows as stored, hardened before it runs; an app shows nothing without its cookie, runs on a tab, and runs
385
- framed where the engine keeps partitioned cookies; the sandbox proxy becomes a
386
- hardened view, takes it only from its host, and opens only what the view declares.
387
- `served.domain.egress` reads the policy that applied to the document (from the
388
- violations its attempts raise) and holds the host to its config: scripts, styles,
389
- fetches and frames never reach the canary, and no directive for them opens a scheme;
390
- images and media are closed unless the config opened them to any https site
391
- (`anyHttps`, P059), where an image then must reach an https canary, reported as
392
- expected rather than as a leak (P062; `leak/served/any-https.spec.ts`).
393
- A served shell draws nothing, and reports no height, until its host sends content,
394
- so the suite gives `show` a line of content for each shell (`options.content`) and a
395
- host that speaks to the shell sends it (P057). The shell cases also run against a
396
- host on `createHost` whose frames take their content's height
386
+ An opaque frame is `srcdoc`: the host builds the shell document. A served frame (domain, external)
387
+ loads a URL: the host's `InstanceLocator` turns an `InstanceRef` into a `FrameLocation`, usually
388
+ through the host's backend, which authenticates the viewer, decides they may see it, and calls
389
+ `PortholeServer.issue`. It loads a `ServedDocument`: the shell (content then arrives over the
390
+ transport), a stored artifact version, the MCP Apps sandbox proxy, or an external app (url mode).
391
+
392
+ - **Storage is keyed by origin.** An `InstanceRef` names its `scope` (the host's choice: a display
393
+ id, an app id); `/server` maps it to `<label>.<content domain>`, the label keyed from the scope
394
+ with the server's secret. Same scope, same origin and storage; different scopes share nothing.
395
+ Browsers partition a framed origin's storage by top-level site, so it is stable within one host
396
+ app.
397
+ - **A served page carries its frame's sandbox** (P099; the row in § Served content). Every page
398
+ `/server` serves (a shell, an artifact page, a set's page, the sandbox proxy; not a url-mode app's
399
+ documents) sends `sandbox allow-scripts allow-same-origin`. In a frame that repeats the attribute;
400
+ on a tab of its own (a public link, a new tab, a frame's address opened outside it) it is the only
401
+ sandbox: no popups, forms, downloads, modals or navigation of another window. Its
402
+ `Permissions-Policy` denies camera, microphone, location, full screen and the rest of
403
+ `FRAME_DENIED_FEATURES`, changing nothing in a frame. On a tab the shell's locks cover engines
404
+ that don't read the header. An engine without the Navigation API has no wall against the page
405
+ navigating itself away on a tab (P099's accepted limit).
406
+ - **A version made of files** (P081–P084; rows in § Served content). The store answers a manifest
407
+ (`files`: path → `{ size, sha256, type? }`, an `entry`, `spa`) and `read(path)`; `{ html }` stays
408
+ one page. A request's path below the version's base is decoded once and looked up
409
+ (`requestFilePath`, `lookupFile`): `dir/` is its `index.html`, `name` is `name.html`, then the
410
+ nearest `404.html`, and a single-page app's navigations get the entry. An unknown type is a
411
+ download (`fileTypeOf`); a page's or script's CSP is the frame's plus the version's path (P082),
412
+ anything else `default-src 'none'; sandbox`; files carry `Cross-Origin-Resource-Policy:
413
+ same-origin`; files are immutable, pages revalidated. In a frame the address is
414
+ `/__porthole/f/<sealed access>/<path>` (the ticket's answer is the entry, whose shell moves there
415
+ first, P083). On a tab it is the version's clean address, `entry.at`'s `base` (`/v/3/`); an
416
+ address meaning the latest (`/`, `/style.css`) is redeemed there (P081). A page never mixes
417
+ versions; a set's pages open each other in the frame (P084).
418
+ - **Tickets.** `issue` mints one: one-time, short-lived, bound to an instance and a viewer, stored
419
+ as its hash, carried once in the frame's URL. The content origin takes it and answers with the
420
+ served document (at `/__porthole/d/<instance key>`) and a cookie of that origin and instance only
421
+ (`__Host-`, `Secure`, `HttpOnly`; `SameSite=None; Partitioned` in a frame, `Lax` on a tab) for
422
+ what follows, a reload. A url-mode app's ticket buys the cookie and redirects to the app's landing
423
+ path; every app request rides the cookie. WebKit keeps no cookie in a cross-site frame (measured),
424
+ so a framed url-mode app runs only where partitioned cookies are kept; elsewhere the host opens it
425
+ on a tab (P025).
426
+ - **Separation is checked.** The content domain is a registrable domain used for nothing else; a
427
+ mount refuses a located origin not in `contentOrigins` or same-site with the host.
428
+ - **Names** (P047). A label is keyed by default (24 base32 characters). A host may name its own
429
+ (`content.name`; `prefixedName("a-")` gives `a-<scope>`, one-to-one): one lowercase DNS label,
430
+ never an IDNA form or a `reserved` one. `reserved` labels are other servers' namespaces under the
431
+ domain (`f` for `<label>.f.<domain>`) or the host's own (`p-*`: every label starting `p-`; or a
432
+ function of the label, P056): they and anything under them return null, to the host's routes. Any
433
+ other deeper name gets this server's 404.
434
+ - **Requests** (P056). The label is the request URL's. A Host header naming another host, where
435
+ either is under the content domain, gets a 400 (a Node adapter builds the URL from an
436
+ absolute-form target; hosts and caches route by Host). A local Host (an IP literal, `localhost`),
437
+ as test runners send, isn't compared. Without an `upstream` only Porthole's own paths are served;
438
+ others are a plain 404. Every answer says `x-robots-tag: noindex`.
439
+ - **Who** (P046, P050). A grant names a `viewer`, or is `anonymous` (a public link: documents only,
440
+ never a url-mode app), and may carry the host's opaque `subject` (a share or session id), signed
441
+ into ticket and cookie. `authorize.check` runs after a ticket or cookie verifies, before anything
442
+ is served: document loads, url-mode entry, every app request, `/__porthole/session`, `access()`. A
443
+ deny is a 403 status page (`denied`, the host's code). Answers are reused only if the host sets
444
+ `ttlSeconds` (at most 300).
445
+ - **Runtimes** (P044, P045). `/server` uses no Node module (hashing in plain JavaScript,
446
+ `crypto.getRandomValues`), so it runs on Cloudflare Workers without `nodejs_compat`. Tickets there
447
+ live in D1 (`d1TicketStore`, taken by one `DELETE … RETURNING`), never KV (eventually consistent).
448
+ Sessions are signed cookies: no store. Steps: [ADOPTING.md](ADOPTING.md) § "5. Cloudflare
449
+ Workers"; `test/workers/` runs such a Worker in workerd with real D1. The routes need wildcard DNS
450
+ and a certificate for every level served (`*.f.<domain>` included). Scopes named by `prefixedName`
451
+ must already be label-safe (lowercase letters, digits, inner hyphens); other ids keep the keyed
452
+ default.
453
+
454
+ `/server`'s handler is fetch-style (`Request → Response | null`; null for requests not for the
455
+ content domain or in a reserved namespace), mounted in front of the backend's routes. Dev and tests
456
+ use `*.localhost` subdomains (browsers resolve them to loopback). In url mode, once the cookie
457
+ checks out, an app's requests go to the host's `upstream` (`proxyTo` relays by HTTP, telling the app
458
+ it is on its own origin and nothing of the proxy); WebSockets take the host's own upgrade path, let
459
+ in by `PortholeServer.access`. The MCP Apps sandbox proxy is served the same way, its CSP from the
460
+ config plus the view's declared egress, signed into the ticket; it becomes the view rather than
461
+ nesting it (P026).
462
+
463
+ **A strict host page** (P054). A nonce-based `script-src` (no `'unsafe-inline'`) blocks an opaque
464
+ frame's shell, since a `srcdoc` frame inherits the page's whole policy. The host passes its nonce
465
+ (`HostOptions.nonce`, `PortholeProvider`'s `nonce`); the shell's script and style carry it, and the
466
+ shell gives it to every script it runs for the content. Content's inline handlers (`onclick="…"`)
467
+ stay blocked, as on the page; scripts and `addEventListener` work. The whole leak suite runs again
468
+ on a reference page with a nonce-only `script-src` (`leak/strict-csp.spec.ts`) and passes on all
469
+ three engines; its negative control `nonce` (the shell without the nonce) fails it.
470
+
471
+ **Served conformance** (`defineServedSuite`, against `leak/served/`'s reference serving, which
472
+ starts its own servers per worker). Content runs on its own origin and can't reach the host's DOM,
473
+ storage, cookies or URL, navigate the host's page or open a window (domain and url mode, each also
474
+ after a click). Storage persists within a scope, never across. A ticket opens its content once. Only
475
+ host origins may frame content. The CSP in headers closes egress. Each artifact version shows as
476
+ stored, hardened before it runs. An app shows nothing without its cookie, runs on a tab, and runs
477
+ framed where partitioned cookies are kept. The sandbox proxy becomes a hardened view, takes it only
478
+ from its host, and opens only what the view declares. `served.domain.egress` reads the policy that
479
+ applied (from the violations its attempts raise) and holds the host to its config: scripts, styles,
480
+ fetches and frames never reach the canary, and no directive for them opens a scheme; images and
481
+ media stay closed unless opened to any https site (`anyHttps`, P059), where an image must then reach
482
+ an https canary, reported as expected, not a leak (P062; `leak/served/any-https.spec.ts`). A served
483
+ shell draws nothing and reports no height until content arrives, so the suite gives `show` a line of
484
+ content per shell (`options.content`) and a host that speaks to the shell sends it (P057). The shell
485
+ cases also run against a `createHost` host whose frames take their content's height
397
486
  (`leak/served/core-host.spec.ts`), as a React host's do.
398
487
 
399
- ### The host kit (0.2.0: P066, P068)
400
-
401
- Two hosts each wrote the same ~2,000 lines around `/server`. The host kit makes that machinery
402
- Porthole's, so an app writes its policy and its settings. The policy is four callbacks (five
403
- with redirect entry):
404
- - `instance`: the instance an issue request proposes, as the app means it;
405
- - `access`: may this viewer see it, and with what grant;
406
- - `authorize`: may this cookie still see it, on each request (P050);
407
- - `source`: a stored version by id and version: one page (`{ html }`), or a set of files (P081);
408
- - `entry.at`: the instance a clean address's path names (redirect entry), or, for a set of files,
409
- the instance with its version's own address (`{ instance, base, file }`, P081).
488
+ ### The host kit
410
489
 
411
- **An adopter's whole wiring** (the package's `examples/app.mjs` is this, runnable on Node and
412
- Workers; docs/ADOPTING.md walks through it):
490
+ The machinery around `/server` each app would otherwise write (P066, P068, P072). The app supplies
491
+ settings and callbacks: `instance` (the instance an issue request proposes, as the app means it),
492
+ `access` (may this viewer see it, with what grant), `authorize` (may this cookie still see it, per
493
+ request, P050), `source` (a stored version by id and version: one page `{ html }` or a set of files,
494
+ P081), and for redirect entry `entry.at` (the instance a clean address's path names; for a set of
495
+ files, with its version's address, `{ instance, base, file }`, P081). Wiring and options:
496
+ [ADOPTING.md](ADOPTING.md) § "The server" and `examples/app.mjs` (Node and Workers).
413
497
 
414
- ```ts
415
- const content = createContentHost<Viewer>({
416
- domain: env.CONTENT_DOMAIN, // "content.example.com" | "content.localhost:8790"; "" = off
417
- appOrigins: [env.APP_ORIGIN], // frame-ancestors, and the clash guard
418
- secret: env.PORTHOLE_SECRET, tickets: d1TicketStore(env.DB), // npx porthole secret
419
- // Keyed by the preset a stored page names: an artifact's is "artifact" unless it says otherwise.
420
- configs: (source) => ({ artifact: presets.artifact({ isolation: "domain", contentOrigins: [source] }) }),
421
- name: prefixedName("a-"), reserved: ["p-*"], // only labels the app itself serves there
422
- instance: (proposal, viewer) => mapToMyInstance(proposal), // a proposal: validate, derive the scope
423
- access: async (instance, viewer) =>
424
- viewer !== null && (await canSee(viewer, instance)) ? { viewer: viewer.id, subject: viewer.id } : null,
425
- authorize: ({ subject }) => (revoked(subject) ? { allow: false, code: "revoked" } : { allow: true }),
426
- source: (id, version) => store.page(id, version), // { html } | { files, read } | null
427
- entry: {
428
- authorizeUrl: `${env.APP_ORIGIN}/porthole/authorize`,
429
- at: (scope, path) => pageAt(scope, path), // "/" → latest, "/v/3" → version 3
430
- // Absolute: outside a browser, Response.redirect has no base URL.
431
- signIn: (returnTo) => Response.redirect(`${env.APP_ORIGIN}/login?next=${encodeURIComponent(returnTo)}`, 303),
432
- },
433
- health: { probe: nodeProbe(), onChange: (view) => pushToClients(view) }, // optional: the opaque fallback
434
- });
435
- // Hono / Workers: content first, then the app's own routes.
436
- app.use("*", async (c, next) => (await content.fetch(c.req.raw)) ?? next());
437
- app.post("/api/frames", (c) => content.issue(viewerOf)(c.req.raw));
438
- app.get("/porthole/authorize", (c) => content.authorize(viewerOf)(c.req.raw));
439
- // The page: frame-src from content.frameSources; meta from content.meta(); "open in a new tab"
440
- // and "copy link" from content.urlOf(scope, path).
441
- ```
442
-
443
- **Server: `createContentHost(options)` (`@botiverse/porthole/server`, runtime-agnostic: Node,
444
- Workers, Deno, Bun).** It gives:
445
- - **`fetch(request)`, the routing middleware.** Every host under the content domain is
446
- Porthole's, so the app never answers there. Reserved labels and the app's own hosts return
447
- null, for the app's routes. `reserved` is only for labels the app itself serves on the content
448
- domain (Ferry's `p-*` previews); a label nothing serves needs no entry. A label the naming
449
- never makes, the bare domain, and a clean address `entry.at` says names nothing all get
450
- Porthole's 404 there, never a trip to the app (P070). Settings that can't be served answer a
451
- plain 503, never the app's. `owns(request)` says the same for a WebSocket upgrade.
452
- - **`issue(viewerOf)`, the issue endpoint** (a fetch handler). The body is always `{ instance }`
453
- (an `InstanceRef`, the wire shape). The app's `instance` callback treats it as a proposal: it
454
- validates it, derives the scope from what it names (a session, a page), and refuses anything
455
- else (404). App ids travel in the document's fields. **The client never chooses an origin**:
456
- the scope the server maps to does. Then `access` (401 without a viewer, 403 refused), a ticket,
457
- and `201 FrameLocation`. `503 not-served` while content isn't served; `409` when `/server`
458
- refuses the instance; an optional per-viewer rate limit (429), an anonymous viewer keyed by an
459
- address the host trusts (the socket's peer, `CF-Connecting-IP` on Workers, or behind
460
- `trustedProxies` the `X-Forwarded-For` entry they appended; never what a client says, P092).
461
- The body is read to at most
462
- `ISSUE_BODY_BYTES` (64 KiB), counted as it arrives: past it the read stops and the answer is
463
- `413 too-large`; a Content-Length over it is refused before the viewer is asked (P092).
464
- - **`authorize(viewerOf)` and `urlOf(scope, path)`: redirect entry** (below).
465
- - **`meta()`** `{ served, contentSource, health }` for the app's page; **`frameSources`** for
466
- its CSP (`frame-src`), the authorize route's path included.
467
- - **Domain helpers.** `contentDomain(input, { appOrigins })` parses (the scheme from loopback or
468
- `*.localhost`, the port) and gives `originOf(label)`, `source`, `isContentHost(host)`,
469
- `labelOf(host)`; `ContentDomainError` names the rule (`invalid`, `clash`, `same-site`).
470
- - **Clashes.** Porthole never serves a content domain that holds an app origin or may share its
471
- site. With the health gate (the opaque fallback) on, such settings are a lasting "unhealthy:
472
- misconfigured, <reason>": logged once (`porthole.content.misconfigured`, with its `code`),
473
- `meta().served` false, frames run opaque. Without it, `createContentHost` throws the typed
474
- error at startup. Fail closed either way; there is no separate switch.
475
- - **The health gate (optional).** Porthole answers a who-am-I on its health label
476
- (`/__porthole/health`, a keyed id, so another deployment's answer doesn't count). The kit
477
- probes it over the real network (DNS, the edge, TLS): every 60 s while unhealthy, every 10 min
478
- while healthy, 10 s timeout. While unhealthy, `issue` answers `503 not-served` and the page's
479
- `servedOrOpaque` picks opaque configs. `health.onChange(view)` is told each change of state
480
- (P070), for an app that pushes "frames served" to its clients. On Workers the probe is optional (a host that doesn't
481
- enable it serves from startup).
482
-
483
- **Redirect entry (P068).** Every instance has a clean, stable address
484
- (`https://a-<id>.content.example.com/v/3`) that opens directly: a new tab, a reload, a bookmark,
485
- a link sent to someone with access.
486
- 1. A request on a clean address that names nothing gets Porthole's 404 on the content origin:
487
- the naming never made its label, or `entry.at(scope, path)`, asked with no viewer, says
488
- nothing (null or undefined) is there (P070).
489
- A request on a clean address without a cookie for it gets a 302 to the app's authorize route
490
- with a signed state (label, path, nonce, five minutes), and a cookie holding the nonce on the
491
- content origin (partitioned in a frame, `Lax` on a tab, like the session cookie).
492
- 2. `authorize` asks `entry.at(scope, path)` and `access`. No viewer: the app's own sign-in
493
- (`signIn(returnTo, request, entry)`), which comes back to the same route. No access: the app's
494
- refusal (`refusal(status, request, entry)`; nothing returned: Porthole's page); never content.
495
- **Redirect entry is for a tab alone (P125):** a clean address asked from a frame
496
- (`Sec-Fetch-Dest: iframe`/`frame`), and the authorize route asked from one, answer Porthole's
497
- "open this in a new tab" page (the status pages' policy, no script), never a trip to the app. Both hooks get the address decoded
498
- (`EntryContext`: label, scope, path, clean URL, the instance, framed). `returnTo` (and
499
- `entry.spa`'s `next`) is `authorizeUrl` with the request's query: the app as it is reached,
500
- never the request's own URL, whose scheme and host behind a TLS edge or a dev proxy are
501
- another's (P074).
502
- 3. Granted, a 302 back to `/__porthole/entry?code=…`: a one-time code (60 s), bound to the
503
- label, the path and the nonce. The content origin redeems it only on that label and only with
504
- the nonce's cookie, sets the session (bound to the path) and 303s to the clean address. The
505
- code is in an address for that one hop (gone from history), every redirect sends
506
- `no-referrer`, and Porthole never logs it.
507
- 4. A path whose session didn't come back is caught on the second bounce (`blocked: cookies`, the
508
- loop guard): on a tab only, since a frame never enters (P125).
509
-
510
- Frames use tickets (`issue` → `FrameLocation`, with its door): no extra round trip, and no
511
- dependence on the app's own cookie reaching its authorize route inside a frame. To frame what a
512
- clean address names, the host resolves it through `issue` first (`{ address }`, `client.resolve`,
513
- `<PortholeView address>`, P125); a refusal there is the outcome, with no frame. (Why frames never
514
- entered, measured before P125: Firefox and WebKit don't send a `Lax` app cookie on a frame
515
- navigation that came through a cross-site redirect; Chromium does.) Use clean addresses for tabs, links, bookmarks and reloads: a host's "open in a new tab"
516
- and "copy link" use `urlOf`, never a ticket. The first open of an instance per browser costs one
517
- extra round trip through the app.
518
-
519
- **Node: `@botiverse/porthole/node`.** `nodeHost(content, { request, upgrade, appSocket })`
520
- returns a request listener and an upgrade listener for `http.createServer`: content hosts to
521
- `content.fetch`, WebSockets on reserved labels to the app's upgrade, a url-mode app's socket to
522
- `appSocket(access, …)` once its cookie checks out, any other socket on the content domain a 404.
523
- `toRequest`/`sendResponse` convert (P070): the request carries a signal aborted when the client
524
- goes away (`proxyTo` passes it on, so a proxied event stream ends with its page); the body is
525
- written as the socket drains and cancelled when the client leaves; an error mid-body destroys
526
- the response rather than end it looking whole. Nothing a request does throws out of the
527
- listeners or ends the process (P092): a request fetch can't take is 405 (`CONNECT`, `TRACE`,
528
- `TRACK`) or 400 (a Host or a target that is no URL); a handler or an app listener that throws or
529
- rejects, or an answer Node can't write, is 500, and `onError` hears it (by default a process
530
- warning); an upgrade's socket closes on its own errors. A HEAD gets the head, its body cancelled;
531
- a client gone before the answer cancels it too. The request body is read only as it is pulled
532
- (a reserved label's request reaches the app whole); once the answer is out, what no one read is
533
- dropped (at most 1 MiB and 5 s) before the connection closes, so a client still sending reads
534
- its answer. `nodeListener(app, { scheme, onError })` is a fetch-style app's listener with the
535
- same guarantees (it is `nodeServer`'s `app`). `nodeProbe()` is the health probe (`*.localhost`
536
- resolved to loopback, no redirects, 4 KB read). `/server` stays free of Node.
537
-
538
- **Client** (core). `httpLocator(url, { headers, credentials, onNotServed })` POSTs
539
- `{ instance }`, passes the abort signal, refuses redirects, and throws a `LocateError` with the
540
- endpoint's status and code. `servedOrOpaque(meta, servedConfigs, opaqueConfigs)` gives
541
- `{ served, configs }`, or null until meta is known, so a frame never starts opaque and then
542
- restarts served. A redirect entry's pages on the app origin report the frame's status too
543
- (`blocked: sign-in`), and the frame transport hears that from the host's own origin only for
544
- frame status.
545
-
546
- **Conformance runner (`@botiverse/porthole/conformance`).** `defineHostConformance(test,
547
- { name, open, issue, config, instances, entry?, nonce?, skip? })` registers the leak suite, the
548
- served cases and the redirect entry cases against the app's real page:
549
- - `open(page)` opens it as a person sees it (signed in, its real CSP);
550
- - the harness is framework-free, on the core's `createHost` (no React: an app's own frame
551
- components are its own e2e's; Porthole's React binding is Porthole's own tests'). It loads as a
552
- script from the page's own origin (routed by the test), with the page's nonce, so a strict CSP
553
- needs nothing added;
554
- - served frames are located by the app's issue endpoint from the page, with its cookies;
555
- - the canaries and a foreign origin are routed; cases for instances the app doesn't give
556
- (versions, url mode, the MCP Apps proxy) are skipped with the reason.
557
-
558
- The tests are located in the app's own spec file, at the `defineHostConformance` call, so
559
- `playwright test <spec>` and `<spec>:<line>` select them (P070). `instances` and the entry
560
- addresses may be async (an app publishes a test page on demand and returns its real instance,
561
- which the issue endpoint then gets); `entry.unknown` lists addresses that name nothing, each of
562
- which must be a 404 on the content domain. `hostConformance(options)` gives the hosts for an app
563
- that registers the cases itself. Playwright's list and line reporters show a skipped case without
564
- its reason; `@botiverse/porthole/conformance/reporter` prints each reason after the run (P074).
565
- `contentSource` may be a function, asked per case (a port known only once the server runs), and
566
- `conformanceProjects` merges an app's own `use` and per-engine `launchOptions` (a system
567
- browser) with Porthole's (P074).
568
-
569
- **Prod shape** (`ops/prod-shape/`, `ops/prod-shape/run.sh`). Docker compose: Caddy's internal
570
- CA serving `app.test`, `*.content.test` (same-site siblings, as in production without a Public
571
- Suffix List entry), `clash.test` and `evil.test`; wildcard DNS (CoreDNS); the kit reference app
572
- behind the edge, its health probe over the real TLS; a misconfigured twin that must run opaque,
573
- and a strict one that must not start; a Playwright image trusting the CA (Chromium's NSS store,
574
- the system store for WebKit; Playwright's Firefox reads neither, so its project overrides
575
- certificate errors). The suite (`packages/porthole/prod-shape`) runs the whole runner over https,
576
- then the sibling cases: Porthole's cookies host-only and `__Host-`; a sibling label (an app's
577
- preview) can't plant a cookie that opens content, or frame it; another site can't frame it; the
578
- clash. CI (`.github/workflows/ci.yml`) runs the checks, the examples and the loopback suites on
579
- Chromium on every push, and the loopback suites on each engine, the negative controls and the
580
- prod-shape profile when started by hand, which a release requires on its commit (P146).
581
-
582
- **Compatibility.** Every 0.1.x export stays as it was; the kit wraps `createServer`. The npm
583
- package carries these docs (`docs/`), and `/server` exports the types an app's callbacks take
584
- (`InstanceRef`, `FrameLocation`, `ServedDocument`, `PortholeConfig`, `EntryContext`). Nothing was
585
- renamed, so there is no compat module. `FrameBlock` gains `sign-in`; `ContentDomain.name` takes
586
- a `Naming` (any function still fits).
587
-
588
- ### The host kit 0.3: the client, the bootstrap, the relay (P072)
589
-
590
- What both adopters still wrote after 0.2 moves into Porthole (ADOPTING.md is the walk-through):
591
- - **`defineDisplays(kinds)`** (core): each kind's preset and options once; opaque and served
592
- configs (memoized per content source), the kind an instance names, frame sources and the
498
+ - **`defineDisplays(kinds)`** (core): each kind's preset and options, once. It gives opaque and
499
+ served configs (memoized per content source), the kind an instance names, frame sources and the
593
500
  `frame-src` directive without a server, and a served kind's config for the manual without a real
594
501
  origin. `createContentHost({ displays })` and the conformance runner take it.
595
- - **`content.routes(viewerOf)`** (/server): one mount under `/porthole` (`prefix`): `POST frames`
596
- (`issue`, answering `link`, the clean address, where `entry.pathOf` names the path, which it
597
- may look up: a promise, P074), `GET
598
- authorize` (its URL now the default `entry.authorizeUrl`), `GET meta` (`ContentClientMeta`:
599
- served, content source, frame sources, health) and `POST`/`DELETE handoff`.
600
- `contentHostFor(build)` gives one host per Workers `env`, failing closed with a plain 503;
601
- `nodeServer({ content, app })` is the whole Node server (`content` may be a function giving the
602
- host once made, P074; asked right after the `listen` callbacks and at each request until it
603
- gives one, and `start` is idempotent, P076). A missing or short secret throws, naming `PORTHOLE_SECRET`.
604
- - **The client:** `portholeClient({ displays, base, headers, credentials, handoff })` is the
605
- locator and knows each kind's config from the meta (null until known), links, `openInTab`
606
- (a tab opened in the click, then sent to the address), the handoff, and `entryTarget` (the
607
- authorize route only; with `{ app: true }` also a path or address on the app's origin, P074).
608
- `frameFallback(outcome)` words what to offer when a frame shows nothing (`needs-tab`,
609
- `denied`, `expired`, `failed`, `timeout`). React: `PortholeView` (a display by kind, served or
610
- opaque, with its fallback), `usePortholeLink`, and the provider's shared `scheme`, `theme`
611
- (`cssVariableTheme`), `nonce: "auto"`, `handlers`, `openLink`, `notify` and `renderConfirm`
612
- (`accept`, `decline`, and `redirect`: `"redirected"`, which doesn't count toward muting, P074;
613
- the request's `display` carries the instance the host gave the frame, served or opaque, and an
614
- opaque frame never gets it, P076, P077).
615
- A flip of the provider's scheme or a new themeKey re-themes running frames in place: no effect
616
- that makes a display depends on the context value those renew (#9, P074).
617
- - **The viewer handoff** for a page that holds a token: `POST /porthole/handoff` with the app's
618
- own credential, from the app's own page, sets a 10-minute `HttpOnly` cookie scoped to the
619
- prefix holding a Porthole-signed key (the viewer's id and expiry), which the authorize route
620
- reads when `viewerOf` knows no one. `entry.spa` signs a person in through the app's own route.
621
- - **The url-mode relay kit:** `upstreamHeaders` (the header rewrite `proxyTo` makes, for any
622
- transport, WebSockets too), `statusPage` (the frame-status page with its script under its hash),
623
- `nodeHost`'s `appSocket` without Porthole's cookies, `content.forget()` for cached `authorize`
624
- answers.
625
- - **Server:** `health.onServedChange(served)`, once per flip; `log` takes a `{ info, warn, error }`
626
- logger.
627
-
628
- ### The agent's side: lint, check, tools (P073)
629
-
630
- - **`lintContent(config, content)`** (core, pure): what can be told without running it, each
631
- finding worded for the agent with its line. Errors only for what certainly fails or is cut:
632
- over the size, a document where a fragment goes that has no body, nested frames and plugins,
633
- `document.write`. Warnings for the rest: a document sent as a widget (taken as its body,
634
- `fragmentOf`), the clipboard, dialogs, forms, hosts outside egress, unpinned CDN libraries,
635
- `position: fixed` in a flow layout, new windows without `openLink`, the page's own styles
636
- holding it to one screen (P106, P110: `src/check/scroll.ts`, a cascade of html, body and the
637
- root's overflow, height and position; `lintFiles` reads the version's linked stylesheets too,
638
- only those within its caps; advisory, so a throw in it says the page wasn't checked).
639
- - **`admitContent(config, content, { refuseOn })`**: the show tool's gate. It refuses errors by
640
- default with a text that says what to change; otherwise it shows the content (a widget's
641
- document taken as its body) and returns the warnings as a note.
642
- - **A page with files** (P081): `lintFiles(config, files)` lints each page as `lintContent` does
643
- (findings name their `path`), holds the set to `checkFileSet`'s rules and the config's limits,
644
- and looks each relative reference up in the set (markup, CSS, module imports, workers,
645
- fetches): a page's reference that starts with `/` is an error (it names the address's root, not
646
- the version: a Vite build without `base: "./"`), one that isn't in the set a warning.
647
- `admitFiles` is the publish tool's gate, as `admitContent` is the show tool's. `checkPage({
648
- config, files, driver })` serves the whole set and runs its entry (a served artifact config and
649
- a driver that serves).
650
- - **`checkPage({ config, content, driver })`** (`/check`): the content in the real sandbox at each
651
- width and scheme (defaults: the manual's phone and desktop widths, light and dark unless
652
- unthemed). The check page (`src/check/page.ts`, bundled and shipped as `/check/page`, a module
653
- `checkPage` imports, so a bundle carries it, P075) is served
654
- by the driver at a fixed origin (`https://porthole-check.invalid`), mounts the content with a
655
- small instrument first in it, and hears errors, rejections, CSP blocks, failed loads, the
656
- console and the document's width by `postMessage`; heights come from the display's resize
657
- events. A served config runs served (P074): the driver also answers a reserved content domain
658
- (`*.porthole-check-content.invalid`) with an in-process `createServer` (a random secret, the
659
- check page as its only host origin), so the content gets its own origin, the served CSP in
660
- headers, the shell, storage and cookies, each run on a new origin; an opaque config, an MCP
661
- Apps view (as a page with the view's egress) and a driver without `serve` run opaque. Each
662
- inline script is named (`//# sourceURL=porthole-script-<n>`) and its first line recorded, so an
663
- error's line is the content's own line, as lint numbers it. Every host function the config
664
- declares is answered as a host that declines (`confirm` says no; each handler answers no; no
665
- call comes from a click, P078), and
666
- each call the host sees is reported (`run.calls`): refused by a gate whatever the person says (no
667
- click, bad arguments, too often) a problem, declined or answered a note. A global the shell
668
- refuses itself without a click (`sendPrompt`) rejects in the content, so it shows as an error. The report's `text` names each
669
- problem once, with where it happened, at most 8. Drivers: `playwrightDriver(browser)` (requests
670
- answered by `page.route`), and `cdpDriver(open)` over any CDP session (`Fetch` interception;
671
- Cloudflare Browser Rendering from a Worker).
672
- - **Tools:** `showTool`, `guideTool`, `checkTool` give `{ name, description, inputSchema }` from
673
- the config; `answerGuide` answers the guide tool; `guideChanges(from, to)` is the notice when a
674
- kind flips between served and opaque. `examples/mcp/server.mjs` wires them over MCP.
675
- - **The manual's examples pass the check:** `leak/check.spec.ts` runs every `GUIDE_EXAMPLES`
676
- entry under each preset at the manual's widths in light and dark, on three engines (OBJECTIVES
677
- criterion 5).
678
-
679
- ### Protocol adapters
680
-
681
- The core ships the adapter for the MCP Apps subset its own shell speaks
682
- (`ShellConnection`): `ui/initialize` answered with the host context,
683
- `tool-input-partial` (0..n) then `tool-input` carrying `{ html }`,
684
- `host-context-changed`, `size-changed` and `notifications/message` (errors) into
685
- the bridge, `ui/message` and `ui/open-link` into the bridge, `ui/resource-teardown`.
686
- Content may also use the official App SDK directly; the adapter answers a second
687
- `ui/initialize` from the same frame, and the shell numbers its own requests with
688
- strings (`porthole-shell-1`) so neither takes the other's answers.
689
- The shell asks `ui/initialize` up to 40 times, 250 ms apart (the host may listen after it runs);
690
- on a tab of its own it asks nothing, since no host can hear it, and its runtime has nothing to
691
- offer from the start. The document's root says how the handshake ended (`data-porthole-host`:
692
- `"answered"`, or `"none"`), for a tool that shoots a page to wait on (P139).
693
-
694
- The host context carries in `styles.variables` only the names MCP Apps defines
695
- (`MCP_APPS_STYLE_VARIABLES`): the official SDK refuses any other name there and fails
696
- the whole handshake. Porthole's own variables (the accent, the chart palette) go in
697
- the host context's own-prefixed field `porthole/styles: { variables }`, which the
698
- shell applies beside the standard ones and a view ignores (P028). The `0.app-sdk-*`
699
- probes connect the official SDK from content under the inline, artifact and MCP Apps
700
- presets.
701
-
702
- The `/mcp` adapter (full MCP Apps views) implements `ProtocolAdapter` with its own
703
- connection operations (`sendToolInputPartial`, `sendToolInput`, `sendToolResult`,
704
- `sendToolCancelled`), carries `ui/message`, `ui/open-link`, `tools/call`,
705
- `resources/read`, `ui/download-file` and `ui/update-model-context` through the
706
- bridge, answers `ui/request-display-mode` with the current mode, sends a view only
707
- the standard style variables (the official SDK refuses others), and performs the
708
- sandbox-proxy handshake when the frame is the proxy (P027). A host maps a view's
709
- `_meta.ui.csp` into its config's egress with `viewEgress` (or `readViewResource`,
710
- which reads the view and its egress from a `resources/read` result). An adapter
711
- validates every message and never calls a host handler itself: `bridge.call`
712
- decides. The leak suite runs the official ext-apps examples, as published, through
713
- it (`leak/mcp/`), in an opaque frame and behind the sandbox proxy.
502
+ - **`createContentHost(options)`** (`@botiverse/porthole/server`; Node, Workers, Deno, Bun).
503
+ `fetch(request)` routes: every host under the content domain is Porthole's; reserved labels (only
504
+ those the app serves there, like Ferry's `p-*` previews) and the app's own hosts return null, to
505
+ the app's routes; a label the naming never makes, the bare domain, and a clean address `entry.at`
506
+ says names nothing get Porthole's 404, never the app (P070); unservable settings get a plain 503.
507
+ `owns(request)` says the same for a WebSocket upgrade. `routes(viewerOf)` is one mount under
508
+ `/porthole` (`prefix`): `POST frames` (`issue`, answering `link`, the clean address `entry.pathOf`
509
+ names, possibly a promise, P074), `GET authorize` (its URL the default `entry.authorizeUrl`), `GET
510
+ meta` (`ContentClientMeta`: served, content source, frame sources, health), `POST`/`DELETE
511
+ handoff`. Also: `authorize(viewerOf)` and `urlOf(scope, path)` (redirect entry), `meta()` (`{
512
+ served, contentSource, health }`), `frameSources` (for the app's `frame-src`, the authorize
513
+ route's path included). `contentHostFor(build)` gives one host per Workers `env`, failing closed
514
+ with a plain 503. A missing or short secret throws, naming `PORTHOLE_SECRET`.
515
+ - **The issue endpoint** (`issue(viewerOf)`). The body is always `{ instance }` (an `InstanceRef`),
516
+ a proposal: the `instance` callback validates it, derives the scope from what it names (a session,
517
+ a page), and refuses anything else (404); app ids travel in the document's fields. **The client
518
+ never chooses an origin.** Then `access` (401 without a viewer, 403 refused), a ticket, `201
519
+ FrameLocation`. `503 not-served` while content isn't served; `409` when `/server` refuses the
520
+ instance. An optional per-viewer rate limit (429) keys an anonymous viewer by an address the host
521
+ trusts (the socket's peer, `CF-Connecting-IP` on Workers, or behind `trustedProxies` the
522
+ `X-Forwarded-For` entry they appended; never a client's word, P092). The body is read to at most
523
+ `ISSUE_BODY_BYTES` (64 KiB), counted as it arrives (past it, `413 too-large`); a Content-Length
524
+ over it is refused before the viewer is asked (P092).
525
+ - **Domains and clashes.** `contentDomain(input, { appOrigins })` parses (scheme from loopback or
526
+ `*.localhost`, port) into `originOf(label)`, `source`, `isContentHost(host)`, `labelOf(host)`;
527
+ `ContentDomainError` names the rule (`invalid`, `clash`, `same-site`). Porthole never serves a
528
+ content domain that holds an app origin or may share its site. With the health gate on, that is a
529
+ lasting "unhealthy: misconfigured, <reason>": logged once (`porthole.content.misconfigured`, with
530
+ its `code`), `meta().served` false, frames opaque. Without it, `createContentHost` throws the
531
+ typed error at startup. Fail closed either way; no separate switch.
532
+ - **The health gate** (optional; the opaque fallback). Porthole answers a who-am-I on its health
533
+ label (`/__porthole/health`, a keyed id, so another deployment's answer doesn't count). The kit
534
+ probes it over the real network (DNS, edge, TLS): every 60 s while unhealthy, every 10 min while
535
+ healthy, 10 s timeout. While unhealthy, `issue` answers `503 not-served` and the page's
536
+ `servedOrOpaque` picks opaque configs. `health.onChange(view)` hears each state change (P070),
537
+ `health.onServedChange(served)` each flip. On Workers the probe is optional (without it, the host
538
+ serves from startup). `log` takes a `{ info, warn, error }` logger.
539
+ - **Handoff and relay.** The viewer handoff, for a page holding a token: `POST /porthole/handoff`
540
+ with the app's credential sets a 10-minute `HttpOnly` cookie scoped to the prefix, holding a
541
+ Porthole-signed key (viewer id, expiry) that the authorize route reads when `viewerOf` knows no
542
+ one; `entry.spa` signs a person in through the app's own route (ADOPTING.md § Sign-in). The
543
+ url-mode relay kit: `upstreamHeaders` (`proxyTo`'s header rewrite, for any transport, WebSockets
544
+ too), `statusPage` (the frame-status page, its script under its hash), `nodeHost`'s `appSocket`
545
+ without Porthole's cookies; `content.forget()` drops cached `authorize` answers.
546
+
547
+ **Redirect entry (P068).** Every instance has a clean, stable address
548
+ (`https://a-<id>.content.example.com/v/3`) for a new tab, a reload, a bookmark, a link sent to
549
+ someone with access.
550
+ 1. One that names nothing gets Porthole's 404 on the content origin (the naming never made its
551
+ label, or `entry.at(scope, path)`, asked with no viewer, answers null or undefined, P070). One
552
+ without its cookie gets a 302 to the app's authorize route with a signed state (label, path,
553
+ nonce, five minutes) and a nonce cookie on the content origin (partitioned in a frame, `Lax` on a
554
+ tab, like the session cookie).
555
+ 2. `authorize` asks `entry.at(scope, path)` and `access`. No viewer: the app's sign-in
556
+ (`signIn(returnTo, request, entry)`), which returns to this route. No access: the app's refusal
557
+ (`refusal(status, request, entry)`; nothing returned, Porthole's page); never content. Both get
558
+ the decoded address (`EntryContext`: label, scope, path, clean URL, instance, framed). `returnTo`
559
+ (and `entry.spa`'s `next`) is `authorizeUrl` plus the request's query, never the request's own
560
+ URL, whose scheme and host behind a TLS edge or dev proxy are another's (P074).
561
+ 3. Granted: a 302 to `/__porthole/entry?code=…`, a one-time code (60 s) bound to label, path and
562
+ nonce. The content origin redeems it only on that label with the nonce's cookie, sets the session
563
+ (bound to the path) and 303s to the clean address. The code is in an address for one hop (gone
564
+ from history), every redirect sends `no-referrer`, and Porthole never logs it.
565
+ 4. A session that didn't come back is caught on the second bounce (`blocked: cookies`, the loop
566
+ guard), on a tab only.
567
+
568
+ **Redirect entry is for a tab alone (P125).** A clean address or the authorize route asked from a
569
+ frame (`Sec-Fetch-Dest: iframe`/`frame`) answers Porthole's "open this in a new tab" page (the
570
+ status pages' policy, no script). Frames use tickets (`issue` → `FrameLocation`, with its door): no
571
+ extra round trip, and no reliance on the app's cookie reaching its authorize route in a frame
572
+ (Firefox and WebKit don't send a `Lax` app cookie on a frame navigation through a cross-site
573
+ redirect; Chromium does, measured). To frame what a clean address names, the host resolves it
574
+ through `issue` (`{ address }`, `client.resolve`, `<PortholeView address>`); a refusal there is the
575
+ outcome, with no frame. "Open in a new tab" and "copy link" use `urlOf`, never a ticket. The first
576
+ open of an instance per browser costs one extra round trip through the app.
577
+
578
+ **Node (`@botiverse/porthole/node`; `/server` stays free of Node).** `nodeServer({ content, app })`
579
+ is the whole server; `content` may be a function giving the host once made (P074), asked after the
580
+ `listen` callbacks and per request until it gives one; `start` is idempotent (P076).
581
+ `nodeHost(content, { request, upgrade, appSocket })` gives request and upgrade listeners for
582
+ `http.createServer`: content hosts → `content.fetch`; WebSockets on reserved labels → the app's
583
+ upgrade; a url-mode app's socket → `appSocket(access, …)` once its cookie checks out; other
584
+ content-domain sockets → 404. `nodeListener(app, { scheme, onError })` wraps a fetch-style app (it
585
+ is `nodeServer`'s `app`). `nodeProbe()` is the health probe (`*.localhost` to loopback, no
586
+ redirects, 4 KB read). Their guarantees:
587
+ - `toRequest`/`sendResponse` convert (P070). The request's signal aborts when the client leaves
588
+ (`proxyTo` passes it on, so a proxied event stream ends with its page). The body is written as the
589
+ socket drains and cancelled when the client leaves; an error mid-body destroys the response rather
590
+ than ending it looking whole.
591
+ - Nothing a request does throws out of the listeners or ends the process (P092): 405 for what fetch
592
+ can't take (`CONNECT`, `TRACE`, `TRACK`); 400 for a Host or target that is no URL; 500 for a
593
+ throwing or rejecting handler or listener, or an unwritable answer, which `onError` hears
594
+ (default: a process warning). An upgrade's socket closes on its own errors. A HEAD gets the head,
595
+ its body cancelled; a client gone before the answer cancels it.
596
+ - The request body is read only as pulled (a reserved label's request reaches the app whole). After
597
+ the answer, unread input is dropped (at most 1 MiB and 5 s) before the connection closes, so a
598
+ client still sending reads its answer.
599
+
600
+ **Client** (core). `httpLocator(url, { headers, credentials, onNotServed })` POSTs `{ instance }`,
601
+ passes the abort signal, refuses redirects, and throws a `LocateError` with the endpoint's status
602
+ and code. `servedOrOpaque(meta, servedConfigs, opaqueConfigs)` gives `{ served, configs }`, or null
603
+ until meta is known, so a frame never starts opaque then restarts served. `portholeClient({
604
+ displays, base, headers, credentials, handoff })` is the locator plus each kind's config from the
605
+ meta (null until known), links, `openInTab` (a tab opened in the click, then sent to the address),
606
+ the handoff, and `entryTarget` (the authorize route only; with `{ app: true }` also a path or
607
+ address on the app's origin, P074). `frameFallback(outcome)` words what to offer when a frame shows
608
+ nothing (`needs-tab`, `denied`, `expired`, `failed`, `timeout`). Redirect entry's pages on the app
609
+ origin report frame status too (`blocked: sign-in`), taken from the host's own origin only, for
610
+ frame status only.
611
+
612
+ **React** (the kit's part): `PortholeView` (a display by kind, served or opaque, with its fallback),
613
+ `usePortholeLink`, and the provider's shared props (ADOPTING.md § 3: `scheme`, `theme`, `nonce:
614
+ "auto"`, `handlers`, `openLink`, `notify`, `renderConfirm`, whose `redirect` doesn't count toward
615
+ muting, P074). The confirm request's `display` carries the instance the host gave the frame; an
616
+ opaque frame never gets it (P076, P077). A scheme flip or a new themeKey re-themes running frames in
617
+ place; no display-making effect depends on the context value those renew (#9, P074).
618
+
619
+ **Conformance runner (`@botiverse/porthole/conformance`).** `defineHostConformance(test, { name,
620
+ open, issue, config, instances, entry?, nonce?, skip? })` registers the leak suite, the served cases
621
+ and the redirect entry cases against the app's real page, which `open(page)` opens as a person sees
622
+ it (signed in, its real CSP). The harness is framework-free, on the core's `createHost` (an app's
623
+ frame components are its own e2e's; Porthole's React binding is Porthole's tests'), and loads as a
624
+ script from the page's origin (routed by the test) with the page's nonce, so a strict CSP needs
625
+ nothing added. The app's issue endpoint locates served frames from the page, with its cookies.
626
+ Canaries and a foreign origin are routed; cases for instances the app doesn't give (versions, url
627
+ mode, the MCP Apps proxy) are skipped with the reason. Tests are located at the
628
+ `defineHostConformance` call, so `playwright test <spec>` and `<spec>:<line>` select them (P070).
629
+ `entry.unknown`: addresses that name nothing, each a 404 on the content domain.
630
+ `hostConformance(options)` gives the hosts to an app that registers cases itself. Options, reporter,
631
+ `conformanceProjects`: [ADOPTING.md](ADOPTING.md) § "7. Conformance".
632
+
633
+ **Prod shape** (`ops/prod-shape/`, `ops/prod-shape/run.sh`). Docker compose: Caddy's internal CA
634
+ serving `app.test`, `*.content.test` (same-site siblings, as in production without a Public Suffix
635
+ List entry), `clash.test`, `evil.test`; wildcard DNS (CoreDNS); the kit reference app behind the
636
+ edge, its health probe over real TLS; a misconfigured twin that must run opaque and a strict one
637
+ that must not start; a Playwright image trusting the CA (Chromium's NSS store, the system store for
638
+ WebKit; Playwright's Firefox reads neither, so its project overrides certificate errors). The suite
639
+ (`packages/porthole/prod-shape`) runs the whole runner over https, then sibling cases: Porthole's
640
+ cookies are host-only and `__Host-`; a sibling label (an app's preview) can't plant a cookie that
641
+ opens content, or frame it; another site can't frame it; the clash. CI (`.github/workflows/ci.yml`)
642
+ runs the checks, examples and loopback suites on Chromium on every push; each engine's loopback
643
+ suites, the negative controls and prod shape run when started by hand, which a release requires on
644
+ its commit (P146).
645
+
646
+ **Types.** The kit wraps `createServer`, still public. The npm package carries these docs (`docs/`);
647
+ `/server` exports the types an app's callbacks take (`InstanceRef`, `FrameLocation`,
648
+ `ServedDocument`, `PortholeConfig`, `EntryContext`). `FrameBlock` includes `sign-in`;
649
+ `ContentDomain.name` takes a `Naming` (any function fits).
650
+
651
+ ### The agent's side: lint, check, tools
652
+
653
+ Wiring: [ADOPTING.md](ADOPTING.md) § "6. The agent's side".
654
+
655
+ - **`lintContent(config, content)`** (core, pure): findings worded for the agent, with their line.
656
+ Errors only for what certainly fails or is cut: over the size, a document with no body where a
657
+ fragment goes, nested frames and plugins, `document.write`. Warnings for the rest: a document sent
658
+ as a widget (taken as its body, `fragmentOf`), the clipboard, dialogs, forms, hosts outside
659
+ egress, unpinned CDN libraries, `position: fixed` in a flow layout, new windows without
660
+ `openLink`, the page's own styles holding it to one screen (P106, P110: `src/check/scroll.ts`, a
661
+ cascade of html, body and the root's overflow, height and position; `lintFiles` reads the
662
+ version's linked stylesheets within its caps; advisory, so a throw says the page wasn't checked).
663
+ - **`admitContent(config, content, { refuseOn })`**, the show tool's gate: refuses errors by default
664
+ with what to change; otherwise shows the content (a widget's document taken as its body) and
665
+ returns warnings as a note.
666
+ - **Files** (P081). `lintFiles(config, files)` lints each page as `lintContent` does (findings name
667
+ their `path`), holds the set to `checkFileSet`'s rules and the config's limits, and looks each
668
+ relative reference up in the set (markup, CSS, module imports, workers, fetches). A page's
669
+ reference starting with `/` is an error (it names the address's root, not the version: a Vite
670
+ build without `base: "./"`); one not in the set, a warning. `admitFiles` is the publish tool's
671
+ gate. `checkPage({ config, files, driver })` serves the set and runs its entry (a served artifact
672
+ config, a driver that serves).
673
+ - **`checkPage({ config, content, driver })`** (`/check`) runs the content in the real sandbox per
674
+ width and scheme (default: the manual's phone and desktop widths, light and dark unless unthemed).
675
+ The check page (`src/check/page.ts`, shipped as `/check/page`, a module `checkPage` imports so a
676
+ bundle carries it, P075) is served by the driver at `https://porthole-check.invalid`; it mounts
677
+ the content with a small instrument first and hears errors, rejections, CSP blocks, failed loads,
678
+ the console and the document's width by `postMessage`; heights come from resize events. A served
679
+ config runs served (P074): the driver answers a reserved content domain
680
+ (`*.porthole-check-content.invalid`) with an in-process `createServer` (random secret, the check
681
+ page its only host origin), so the content gets its own origin per run, the served CSP in headers,
682
+ the shell, storage and cookies. An opaque config, an MCP Apps view (as a page with the view's
683
+ egress) and a driver without `serve` run opaque. Each inline script is named (`//#
684
+ sourceURL=porthole-script-<n>`) with its first line recorded, so an error's line is the content's
685
+ line, as lint numbers it. Host functions are answered as a host that declines (`confirm` says no;
686
+ handlers answer no; no call comes from a click, P078). Each call the host sees is reported
687
+ (`run.calls`): refused by a gate regardless of the person (no click, bad arguments, too often) is
688
+ a problem; declined or answered, a note. A global the shell refuses without a click (`sendPrompt`)
689
+ rejects in the content, so it shows as an error. The report's `text` names each problem once, with
690
+ where, at most 8. Drivers: `playwrightDriver(browser)` (`page.route`), `cdpDriver(open)` over any
691
+ CDP session (`Fetch` interception; Cloudflare Browser Rendering from a Worker).
692
+ - **Tools:** `showTool`, `guideTool`, `checkTool` give `{ name, description, inputSchema }` from the
693
+ config; `answerGuide` answers the guide tool; `guideChanges(from, to)` is the notice when a kind
694
+ flips between served and opaque. `examples/mcp/server.mjs` wires them over MCP.
695
+ - **The manual's examples pass the check:** `leak/check.spec.ts` runs every `GUIDE_EXAMPLES` entry
696
+ under each preset at the manual's widths, light and dark, on three engines ([PRINCIPLES.md §
697
+ Objectives](PRINCIPLES.md#objectives-and-success-criteria), criterion 5).
698
+
699
+ ### The MCP Apps adapters
700
+
701
+ The core's adapter covers the MCP Apps subset its shell speaks (`ShellConnection`): `ui/initialize`
702
+ answered with the host context; `tool-input-partial` (0..n) then `tool-input` carrying `{ html }`;
703
+ `host-context-changed`; `size-changed`, `notifications/message` (errors), `ui/message` and
704
+ `ui/open-link` into the bridge; `ui/resource-teardown`. Content may also use the official App SDK:
705
+ the adapter answers a second `ui/initialize` from the same frame, and the shell numbers its requests
706
+ with strings (`porthole-shell-1`) so neither takes the other's answers. The shell asks
707
+ `ui/initialize` up to 40 times, 250 ms apart (the host may listen late). On a tab of its own it asks
708
+ nothing (no host can hear) and its runtime offers nothing. The document's root records the outcome
709
+ (`data-porthole-host`: `"answered"` or `"none"`) for a screenshot tool to wait on (P139).
710
+
711
+ `styles.variables` in the host context holds only MCP Apps' names (`MCP_APPS_STYLE_VARIABLES`): the
712
+ official SDK fails the whole handshake on any other. Porthole's own (the accent, the chart palette)
713
+ go in the own-prefixed `porthole/styles: { variables }`, which the shell applies and a view ignores
714
+ (P028). The `0.app-sdk-*` probes connect the official SDK from content under the inline, artifact
715
+ and MCP Apps presets.
716
+
717
+ The `/mcp` adapter (full MCP Apps views) implements `ProtocolAdapter` with its own connection
718
+ operations (`sendToolInputPartial`, `sendToolInput`, `sendToolResult`, `sendToolCancelled`). It
719
+ carries `ui/message`, `ui/open-link`, `tools/call`, `resources/read`, `ui/download-file` and
720
+ `ui/update-model-context` through the bridge, answers `ui/request-display-mode` with the current
721
+ mode, sends only standard style variables, and does the sandbox-proxy handshake when the frame is
722
+ the proxy (P027). `viewEgress` maps a view's `_meta.ui.csp` into the config's egress
723
+ (`readViewResource` reads the view and its egress from a `resources/read` result). Adapters validate
724
+ every message and never call a handler: `bridge.call` decides. The leak suite runs the official
725
+ ext-apps examples, as published, through it (`leak/mcp/`), opaque and behind the sandbox proxy.
726
+
727
+ **Not AppBridge** (P007). The SDK's host side, `AppBridge`, extends the MCP SDK's `Protocol` class
728
+ and pulls in the MCP client/core packages. Porthole reimplements the thin host-side subset that maps
729
+ to capabilities; no AppBridge-backed adapter is offered for now (P014). On the widget side nothing
730
+ is reimplemented: authors use the official `App` SDK. Upstream, once code and tests exist (P018), we
731
+ contribute what is general: the conformance/leak runner, the container-agnostic framing note (one
732
+ hardened frame instead of the mandated double-iframe, where equally secure), and the shadow-root /
733
+ document-rewrite frame-escape findings.
714
734
 
715
735
  ### The host-function bridge
716
736
 
717
- `bridge.call(capability, args)` checks, in order: the display's run not stopped (a restart or
718
- its end closes its bridge, P095) → declared by the config → declared by the page, where it has
719
- a declaration (P086) → before the arguments are read: for the runtime's own host functions, a
720
- method by its `op` and the viewer's level for it, then for every capability its host function's
721
- own rate (P091, P095: a malformed call costs its rate) → arguments valid and within their
722
- limits (`openLink` http(s) only and without credentials in the URL; a prompt
723
- 1..`maxPromptChars` characters; a tool's arguments, model context and a download's contents
724
- plain, bounded JSON, P095) → who may (P087: the level of each method the call runs for the
725
- viewer, the data a page named with or without a viewer (P094), db's rules) → muted, if
726
- confirm-gated → the own rate of each method it runs (`methodGates`; P094: a batch's writes count
727
- each) → user activation → the viewer's `consent` → `confirm` (at most 10 waiting a display, P095)
728
- → the host's handler (or, for a read, a result the host already gave for it (P094), or for a read
729
- allowed stale, the host's cache). Each refusal is a
730
- `Refusal` and a `refused` display event; the frame gets an error result. After
731
- `declinesBeforeMute` declines a display stops asking (`muted`) until it runs again.
737
+ `bridge.call(capability, args)` checks, in order: the display's run not stopped (a restart or its
738
+ end closes its bridge, P095) → declared by the config → declared by the page, where it has a
739
+ declaration (P086) → before reading arguments: for the runtime's own host functions, a method by its
740
+ `op` and the viewer's level for it, then for every capability its host function's own rate (P091,
741
+ P095: a malformed call costs its rate) → arguments valid and within limits (`openLink` http(s) only,
742
+ no credentials in the URL; a prompt 1..`maxPromptChars` characters; a tool's arguments, model
743
+ context and a download's contents plain, bounded JSON, P095) → who may (P087: each method's level
744
+ for the viewer, the data a page named with or without a viewer (P094), db's rules) → muted, if
745
+ confirm-gated → each method's own rate (`methodGates`; P094: a batch's writes count each) → user
746
+ activation → the viewer's `consent` → `confirm` (at most 10 waiting a display, P095) → the host's
747
+ handler (or for a read, a result the host already gave for it (P094), or for a read allowed stale,
748
+ the host's cache). Each refusal is a `Refusal` and a `refused` display event; the frame gets an
749
+ error result. After `declinesBeforeMute` declines a display stops asking (`muted`) until it runs
750
+ again.
732
751
 
733
752
  ### React binding
734
753
 
735
- `@botiverse/porthole/react` (`src/react/`, TSX that a host's bundler or `pnpm build`
736
- compiles; peer `react` 19.2+ for `useEffectEvent`). All isolation is the core's; the
737
- binding is mounting and lifecycle (P034).
754
+ `@botiverse/porthole/react` (`src/react/`, TSX a host's bundler or `pnpm build` compiles; peer
755
+ `react` 19.2+ for `useEffectEvent`). Isolation is the core's; the binding is mounting and lifecycle
756
+ (P034).
738
757
 
739
758
  ```ts
740
759
  <PortholeProvider confirm? hostInfo? locator? nonce? dialogClassName? toastClassName?> // once per page
@@ -756,193 +775,166 @@ binding is mounting and lifecycle (P034).
756
775
  </PortholeProvider>
757
776
  ```
758
777
 
759
- - **Provider** (per page): which frames run (a live-frame cap: the config's
760
- `limits.maxLiveFrames`; frames off screen longest stop first, show a placeholder at
761
- their last height with "Run again", and run again when they come back), the
762
- heights displays reported (by `displayId`, so a frame mounting again starts at its
763
- last height), and the default confirmation dialog (`ConfirmDialog`, P019): the
764
- call's whole effect and the display's title, Cancel focused, the accept button
765
- ignoring presses for `ARM_DELAY_MS` after it opens, Escape cancels; a modal in the
766
- host page, outside every frame. `confirm` replaces it. Without a provider frames
767
- still run (one page-wide registry) and calls that need a person are refused. It
768
- also serves `copyText` for frames whose handlers don't (P052): the host's page
769
- writes the clipboard and the copy toast (`CopyToast`) shows the person what went on
770
- it, clipped to four lines and `TOAST_CHARS`; if the write failed it says so and
771
- offers a Copy button, a click on the host's own page.
772
- - **Frame**: mounts when it nears the screen (800 px) unless `eager`; until its
773
- content reports a size it holds its remembered height (at least
774
- `PLACEHOLDER_HEIGHT_PX`) and is hidden behind its placeholder (`data-porthole-state`:
775
- `waiting`, `running`, `stopped`; `data-porthole-ready` while it loads); then it is
776
- as tall as its content, within the config's limits. Only a new `config`,
777
- `document`, `instance` or `generation` makes a new display; `content`, `partial`,
778
- `scheme`, handlers, and even `displayId` and `title` are fed to the running one (a
779
- streamed display keeps its frame when its id settles, and its confirmations name
780
- it as the host now does).
781
- Navigation recovery is the core's: started again up to three times, `onNavigated`
782
- each time, then stopped with an error.
783
- - The shell reports no size before it has drawn something, so an empty shell never
784
- overwrites a remembered height (the first host's frame jumped there).
785
- - **Annotations** follow props: `annotating` (what the person may point at now, or
786
- null), `annotations` (the marks), `focusedAnnotation` (each new id is brought into
787
- view; `{ id, key }` with a new key focuses the same one again), `trackedAnnotation`
788
- (the mark followed, or null, P118), `trackedSelection` (true: the selection followed in
789
- its place, and highlighted, P138); `onAnnotation` gets what the frame reported, `tracked`
790
- and `selectionTracked` boxes too. A frame that mounts again gets them all. A `ref` holds `clearSelection()`, `find`,
791
- `clearFind` and `focusMark(id)` (`PortholeFrameHandle`), each a no-op while no display runs.
792
- - **Errors** (P055): `onContentError` gets what the content did wrong (what it
793
- threw, what the sandbox blocked, a navigation the shell stopped, that it kept
794
- navigating away): the agent's to hear. `onNavigationBlocked` gets a stopped
795
- navigation's address whole (P080). `onHostError` gets what failed on the host's side (`locate`, `mount`,
796
- `annotations`): never the agent's. `onError(message, source)` gets both.
797
- - **Identity** (P057): `config`, `instance`, `annotations` and the provider's
798
- `hostInfo` are compared by value, and the provider's `locator` and `confirm` are
799
- read when used, so a host may build them inline. A new `config`, `document`,
800
- `instance` or `generation` still makes a new display.
801
- - **Fill** (P057): `fill` makes the frame fill its box (give the box, or its parent,
802
- a height) and the content scroll inside it, instead of growing with it; a url-mode
803
- app always fills. In the core, `MountOptions.fill`.
804
- - **A strict page** (P054): `nonce` passes the page's CSP nonce to opaque frames, which
805
- inherit the page's policy (`HostOptions.nonce` in the core).
806
-
807
- Its tests run in real browsers (`leak/react.spec.ts`, against `leak/react/app.tsx`,
808
- which the leak server bundles with esbuild because React ships CommonJS only).
778
+ - **Provider** (per page): a live-frame cap (`limits.maxLiveFrames`; frames off screen longest stop
779
+ first, show a placeholder at their last height with "Run again", and rerun when back); heights by
780
+ `displayId`, so a remounted frame starts at its last height; the default confirmation
781
+ (`ConfirmDialog`, P019: the call's whole effect and the display's title, Cancel focused, accept
782
+ ignoring presses for `ARM_DELAY_MS` after opening, Escape cancels; a modal in the host page,
783
+ outside every frame), which `confirm` replaces. Without a provider frames still run (one page-wide
784
+ registry) and calls needing a person are refused. It serves `copyText` for frames whose handlers
785
+ don't (P052): the host's page writes the clipboard and `CopyToast` shows what went on it, clipped
786
+ to four lines and `TOAST_CHARS`; a failed write says so and offers a Copy button, a click on the
787
+ host's own page.
788
+ - **Frame**: mounts near the screen (800 px) unless `eager`. Until its content reports a size it
789
+ holds its remembered height (at least `PLACEHOLDER_HEIGHT_PX`) behind its placeholder
790
+ (`data-porthole-state`: `waiting`, `running`, `stopped`; `data-porthole-ready` while loading),
791
+ then is as tall as its content within the config's limits. The shell reports no size before
792
+ drawing something, so an empty shell never overwrites a remembered height. Only a new `config`,
793
+ `document`, `instance` or `generation` makes a new display; `content`, `partial`, `scheme`,
794
+ handlers, even `displayId` and `title` go to the running one (a streamed display keeps its frame
795
+ when its id settles, and its confirmations name it as the host now does). `config`, `instance`,
796
+ `annotations` and the provider's `hostInfo` are compared by value, and the provider's `locator`
797
+ and `confirm` read when used, so a host may build them inline (P057). Navigation recovery is the
798
+ core's: restarted up to three times, `onNavigated` each time, then stopped with an error.
799
+ - **Annotations** follow props: `annotating` (what the person may point at now, or null),
800
+ `annotations` (the marks), `focusedAnnotation` (each new id is brought into view; `{ id, key }`
801
+ with a new key refocuses), `trackedAnnotation` (the mark followed, or null, P118),
802
+ `trackedSelection` (true: the selection followed in place and highlighted, P138). `onAnnotation`
803
+ gets the frame's reports, `tracked` and `selectionTracked` boxes too. A remounted frame gets them
804
+ all. The `ref` (`PortholeFrameHandle`) holds `clearSelection()`, `find`, `clearFind`,
805
+ `focusMark(id)`, each a no-op while no display runs.
806
+ - **Errors** (P055): `onContentError` gets the content's faults (what it threw, what the sandbox
807
+ blocked, a stopped navigation, that it kept navigating away): the agent's to hear.
808
+ `onNavigationBlocked` gets a stopped navigation's whole address (P080). `onHostError` gets the
809
+ host side's failures (`locate`, `mount`, `annotations`), never the agent's. `onError(message,
810
+ source)` gets both.
811
+ - **Fill** (P057): the frame fills its box (give it or its parent a height) and the content scrolls
812
+ inside instead of growing; a url-mode app always fills. Core: `MountOptions.fill`. **`nonce`**
813
+ (P054): see § Isolation modes and served content (`HostOptions.nonce` in the core).
814
+
815
+ Tests run in real browsers (`leak/react.spec.ts`, against `leak/react/app.tsx`, bundled by the leak
816
+ server with esbuild since React ships CommonJS only).
809
817
 
810
818
  ## Widget side (what the agent writes against)
811
819
 
812
- The content speaks **MCP Apps**. An author can use the official
813
- `@modelcontextprotocol/ext-apps` `App` SDK, or the raw JSON-RPC over `postMessage`
814
- the spec documents — the host side answers it. For convenience the shell defines
815
- `sendPrompt(text)` and `openLink(url)` when those capabilities are declared (sugar
816
- over `ui/message` and `ui/open-link`), turns link clicks into `openLink`, stands in
817
- for `localStorage` in an opaque frame, applies the theme variables, and fires the
818
- config's theme event after a change. A capability that is not declared is simply
819
- absent.
820
+ Content speaks **MCP Apps**: the official `@modelcontextprotocol/ext-apps` `App` SDK, or the raw
821
+ JSON-RPC over `postMessage` the spec documents. For convenience the shell defines `sendPrompt(text)`
822
+ and `openLink(url)` when declared (sugar over `ui/message` and `ui/open-link`), turns link clicks
823
+ into `openLink`, stands in for `localStorage` in an opaque frame, applies the theme variables, and
824
+ fires the config's theme event after a change. An undeclared capability is absent.
820
825
 
821
- ## The capability runtime (0.7.0: P085–P090)
826
+ ## The capability runtime
822
827
 
823
828
  A config with `runtime: "1"` (inline widgets and artifact pages) gives its frames one global,
824
- `porthole`, whose only member is `use(name)`:
825
-
826
- ```js
827
- const db = await porthole.use("db"); // a frozen namespace, or null (not here: draw without it)
828
- if (db) {
829
- try { await db.set("votes/me-1", { choice: "b" }, { ifVersion: 0 }); }
830
- catch (error) { show(error.message); if (error.code === "conflict") reread(); } // a stable code
831
- }
832
- ```
833
-
834
- - **Contract** (`RUNTIME_CAPABILITIES`, version 1; `types/runtime/v1/*.d.ts`): `clipboard`,
835
- `links`, `downloads`, `comments` (built in), `user`, `chat`, `data`, `context`, `artifact`,
836
- `assets`, `db` (declared). Each method is served by one of the config's host functions, gated as
837
- the config says; the table in P085 maps them.
829
+ `porthole`, whose only member is `use(name)`: a frozen namespace, or null where the capability isn't
830
+ offered (the page draws without it). Errors carry a stable `code`. Offering it:
831
+ [ADOPTING.md](ADOPTING.md) § "The capability runtime". Guarantees: [THREAT_MODEL.md §
832
+ 7](THREAT_MODEL.md#7-the-display-layer-and-the-app-runtime).
833
+
834
+ - **Contract** (`RUNTIME_CAPABILITIES`, version 1; `types/runtime/v1/*.d.ts`): `clipboard`, `links`,
835
+ `downloads`, `comments` (built in), `user`, `chat`, `data`, `context`, `artifact`, `assets`, `db`
836
+ (declared). Each method is served by one of the config's host functions, gated as configured;
837
+ P085's table maps them.
838
838
  - **Declaration** (P086): `{ capabilities: { name: config }, runtime }`, stored by the host,
839
839
  resolved at publish by `declareCapabilities` (omitted carries forward, `{}` clears, an object
840
- replaces), checked against the config, given to `mount({ declaration })`. The bridge refuses an
841
- undeclared capability on every path (`undeclared` → `not_allowed`). No declaration: a 0.6 page.
842
- - **Levels** (P087): `view < interact < admin < owner`; each method's least level (config `levels`
843
- at or above its floor; a page's declaration raises). The host's access says the viewer's level
844
- (`Grant.level`, `Grant.user` → `FrameLocation.viewer`; or `mount({ viewer })`); below it is
845
- `forbidden`, before any handler. Without a viewer 0.6's functions run as before; the runtime's own
846
- are refused.
847
- - **Order in the bridge**: declared in the config → declared by the page → for the runtime's own,
848
- the method's level and the host function's rate before the arguments are read → arguments
849
- (shape, bounded walks, limits: `too_large`) → the call's level (a batch's writes', a watch's
850
- read's), `data`'s names (with a viewer or without one, P094), `db`'s paths and rules → mute →
851
- rates → gesture → consent → confirm (the host function's gates and the own gates of each method
852
- the call runs: `artifact.publish` and `assets.delete` a yes, an upload whose code
853
- may run a yes; a db batch its writes', confirmed once whole, a rate counting each write; a watch
854
- its read's, P094) → the handler, or for a read a result the host already gave for it (P094)
855
- (context: `viewer`, `declared`, `instance`) → `db` answers with `data/users/me` (P091).
856
- - **Mounts under a runtime** say what the page declared (`declaration`, or `null` for a page from
857
- before 0.7); an older version is mounted with `intersectDeclarations(version's, current)`, which
858
- allows exactly what both allow (each side's `db` rules read as `dbAccess` reads them, P093). A
859
- display without a viewer gets nothing above view; a viewer that doesn't parse is an error.
840
+ replaces), checked against the config, given to `mount({ declaration })` (`null` for a page stored
841
+ without one). The bridge refuses an undeclared capability on every path (`undeclared` →
842
+ `not_allowed`). A page stored before runtime declarations takes the legacy path. An older version
843
+ mounts with `intersectDeclarations(version's, current)`: exactly what both allow (each side's `db`
844
+ rules read as `dbAccess` reads them, P093).
845
+ - **Levels** (P087): `view < interact < admin < owner`. Each method has a least level (config
846
+ `levels` at or above its floor; a page's declaration raises it). The host's access gives the
847
+ viewer's level (`Grant.level`, `Grant.user` → `FrameLocation.viewer`; or `mount({ viewer })`);
848
+ below it is `forbidden`, before any handler. Without a viewer the config's other host functions
849
+ run but the runtime's are refused, and nothing above view is given; a viewer that doesn't parse is
850
+ an error.
851
+ - **In the bridge** (§ The host-function bridge gives the order): arguments are checked for shape,
852
+ by bounded walks, and against limits (`too_large`); "who may" is the call's level (a batch's
853
+ writes', a watch's read's), `data`'s names (with or without a viewer, P094), `db`'s paths and
854
+ rules; the gates are the host function's plus each method's own (`artifact.publish` and
855
+ `assets.delete` a yes, an upload whose code may run a yes; a db batch its writes', confirmed once
856
+ whole, its rate counting each write; a watch its read's, P094). The handler gets context `viewer`,
857
+ `declared`, `instance`; `db` answers with `data/users/me` (P091).
860
858
  - **Wire**: the roster in `ui/initialize`'s `hostCapabilities.experimental["porthole/runtime"]`;
861
- `porthole/call { capability, method, args, watch? }` → `{ value }` or an error with
862
- `data: { code, message }`; `porthole/event { watch, data }`; `porthole/unwatch { watch }`.
859
+ `porthole/call { capability, method, args, watch? }` → `{ value }` or an error with `data: { code,
860
+ message }`; `porthole/event { watch, data }`; `porthole/unwatch { watch }`.
863
861
  `data.read`/`data.subscribe` use MCP's `resources/*`.
864
- - **Services are the host's**: `db` (paths, versions, `ifVersion`, batches, watches, `data/users/<id>`
865
- private, the page's rules: `dbAccess`, which the host applies again), `artifact` (current version;
866
- a base-checked patch), `assets` (an `AssetStore` `/server` serves at `/_blob/<id>`), `comments`
867
- (the host's composer; content hears a boolean). `defineRuntimeConformance` checks an app's real
868
- handlers, and with `api` its own API past the bridge with a forged context (never trust
869
- `context.viewer` or `context.declared`); `leak/runtime/memory.ts` is the reference, in memory.
870
- `pseudonymFor(secret, artifact, person)` gives a person an id per artifact.
862
+ - **Services are the host's**: `db` (paths, versions, `ifVersion`, batches, watches,
863
+ `data/users/<id>` private, the page's rules: `dbAccess`, which the host applies again), `artifact`
864
+ (current version; a base-checked patch), `assets` (an `AssetStore` `/server` serves at
865
+ `/_blob/<id>`), `comments` (the host's composer; content hears a boolean).
866
+ `defineRuntimeConformance` checks an app's real handlers, and with `api` its own API past the
867
+ bridge with a forged context (never trust `context.viewer` or `context.declared`);
868
+ `leak/runtime/memory.ts` is the in-memory reference. `pseudonymFor(secret, artifact, person)`
869
+ gives a person an id per artifact.
871
870
  - **Assets on the content origin** (P089, P091): for an access to the asset's artifact (a session
872
- cookie, a framed set's sealed address as `Referer`, or `assets.url(id)`'s
873
- `<sealed base>__porthole/blob/<id>`), then the host's check, then `AssetStore.get(id, access)`;
874
- revalidated (`no-cache`, ETag); code-typed only where trusted and the config lets uploaded code
875
- run, asked at each load (in bearer mode, every artifact config must, P103); by id alone only in
876
- bearer mode.
877
- - **The manual**: under a runtime, topic `interactive` lists `porthole.use`'s methods with levels and
878
- gates, and topic `capabilities` teaches declaring, levels, errors, where state goes, and each
879
- offered capability's `.d.ts`. 0.6's globals stay defined (`shell/legacy.ts`) and untaught.
871
+ cookie, a framed set's sealed address as `Referer`, or `assets.url(id)`'s `<sealed
872
+ base>__porthole/blob/<id>`), then the host's check, then `AssetStore.get(id, access)`; revalidated
873
+ (`no-cache`, ETag); code-typed only where trusted and the config lets uploaded code run, asked at
874
+ each load (in bearer mode every artifact config must, P103); by id alone only in bearer mode.
875
+ - **The manual**: topic `interactive` lists `porthole.use`'s methods with levels and gates; topic
876
+ `capabilities` teaches declaring, levels, errors, where state goes, and each offered capability's
877
+ `.d.ts`. The legacy globals stay defined (`shell/legacy.ts`) and untaught.
880
878
 
881
879
  ## The modes
882
880
 
883
- - **Inline widget** (`presets.inlineWidget`). The host has the HTML (the agent
884
- wrote it) and the shell draws it in an opaque frame, streamed as it is written.
885
- The phase-1 workhorse.
886
- - **Live widget** (`presets.liveWidget`, P079). An inline widget that shows the
887
- host's data, current, as the viewer may see it: `readData` and `subscribeData`
888
- behind the viewer's consent, no network of its own (no option opens it, a
889
- capability's own origins included, P103), and, served, Porthole's Chart.js and D3
890
- from its own origin.
891
- - **Artifact page** (`presets.artifact`). A whole document: written into an opaque
892
- frame by the shell where the host has it (the first host's "show an HTML file"),
893
- or served on its own origin (domain isolation), CSP in headers, versioned. It
894
- scrolls inside past a shorter height cap.
895
- - **MCP Apps view** (`presets.mcpApp`). A standard `ui://` template plus tool
896
- input/result, through the `/mcp` adapter: hardened in an opaque frame (the shell's
897
- runtime first in the view's document), or behind the sandbox proxy on a second
898
- origin.
899
- - **Domain mode** (any of the above with `isolation: "domain"`). A stable origin per
900
- storage scope, so `localStorage` persists (P016).
901
- - **URL mode** (`presets.url`). A running app by URL (the first host's dev-server
902
- preview): frame, isolation and access auth; no shell, no egress control (P020).
903
- It has no handshake: its first load makes it ready, and it fills its container (an
904
- app reports no size; give the frame a height), at least `minHeightPx`. A host may
905
- add popups, modals and downloads to its sandbox, never top navigation (P037), and
906
- delegate clipboard writes and full screen (`permissions`, P049; none by default).
907
- Through `/server`, a framed app is entered through a page that checks the browser
908
- kept its cookie, tells the host (P040), and goes on once it has loaded itself; the host's `outcome` says loaded,
909
- blocked (and why: `cookies` on WebKit, `framing`, `session`, `upstream`, `denied`
910
- with the host's code, `locate` when the host's own locator failed) or timeout, so
911
- it can offer its own "Open in a new tab". A `denied` may follow `loaded`: the host
912
- revoked access mid-session (P050).
881
+ - **Inline widget** (`presets.inlineWidget`): the agent's HTML, held by the host, drawn by the shell
882
+ in an opaque frame, streamed as written; the smallest capability set, for cards in a conversation.
883
+ The workhorse.
884
+ - **Live widget** (`presets.liveWidget`, P079): an inline widget showing the host's current data as
885
+ the viewer may see it. It declares `readData` and `subscribeData` with `consent` and its rate.
886
+ Egress stays closed: no option opens it; it refuses `egress` and a capability's own `connect` or
887
+ `resource` (P103). Served, it loads Porthole's Chart.js and D3 from its own origin
888
+ (`egress.libraries`).
889
+ - **Artifact page** (`presets.artifact`): a whole document, written into an opaque frame by the
890
+ shell where the host has it (an app's "show an HTML file"), or served on its own origin (domain
891
+ isolation), CSP in headers, versioned. It scrolls inside past a shorter height cap.
892
+ - **MCP Apps view** (`presets.mcpApp`): a `ui://` template plus tool input/result through the `/mcp`
893
+ adapter, hardened in an opaque frame (the shell's runtime first in the view's document) or behind
894
+ the sandbox proxy on a second origin.
895
+ - **Domain mode** (any of the above with `isolation: "domain"`): a stable origin per storage scope,
896
+ so `localStorage` persists (P016).
897
+ - **URL mode** (`presets.url`): a running app by URL (a dev server's preview): frame, isolation and
898
+ access auth; no shell, no capabilities, no egress control (P020). No handshake: its first load
899
+ makes it ready. It fills its container (it reports no size; give the frame a height), at least
900
+ `minHeightPx`. A host may add popups, modals and downloads to its sandbox, never top navigation
901
+ (P037), and delegate clipboard writes and full screen (`permissions`, P049; none by default).
902
+ Through `/server`, a framed app is entered through a page that checks the browser kept its cookie,
903
+ tells the host (P040), and goes on once loaded. The host's `outcome` says loaded, blocked
904
+ (`cookies` on WebKit, `framing`, `session`, `upstream`, `denied` with the host's code, `locate`
905
+ when the host's locator failed) or timeout, so it can offer "Open in a new tab". A `denied` after
906
+ `loaded` means the host revoked access mid-session (P050).
913
907
 
914
908
  ## Egress hardening, each with its test
915
909
 
916
- Closed by default; opened only to origins the config declares. For a host choosing a level
917
- (closed, library CDNs, passive media from any https site), ADOPTING.md § "Choosing egress" is the
918
- summary; this section is the long form. The leak suite
919
- (`src/conformance/probes.ts`, run by `pnpm test:leak` against the reference host)
920
- attempts each channel from inside the content, as an agent's code would, and asserts
921
- with an out-of-band oracle that nothing left: an HTTP canary that also counts raw TCP
922
- connections, a UDP listener for STUN, a witness origin a navigated document would
923
- reach, and the page's responses. Each oracle has a positive control (an allowed
924
- origin loads; an unsandboxed peer connection sends STUN; an unsandboxed hint
925
- connects) or the probe says it has none. Each defense has a negative control
926
- (`PORTHOLE_LEAK_WEAKEN`, P032) that takes it out, so its probes are seen to fail.
927
- Engines: Chromium 153, WebKit 26.6 and Firefox 155 (Playwright 1.63) all gate (P017,
928
- P035).
929
-
930
- Origins are exact, or `https://*.` a domain of the host's own: a wildcard over a
931
- public suffix (`*.com`, `*.co.uk`, `*.github.io`) is refused, as is any scheme
932
- source, with one exception (P060). A host may let passive content load from any
933
- https site (`egress.anyHttps: ["img", "media", "font"]`, P059): those directives
934
- get `https:`, scripts, styles, data and frames never do, and the manual says so
935
- (`leak/cdn.spec.ts`: a hotlinked image loads; a script, a stylesheet and a fetch
936
- to the same site don't reach it).
937
-
938
- An opaque frame inherits the embedding page's whole policy (P058): on a page that
939
- closes images or fetches to its own origin, the positive controls of `1.connect`
940
- and `2.resources` can't load, through no fault of the host's isolation. The suite
941
- then reports the probe inapplicable on this host, with the reason, instead of
942
- failing it: a probe sees the allowed origin blocked by a policy that isn't the
943
- frame's own (the frame's allows it). `12.no-confirm` likewise, on a host that
944
- always has a confirm function (a default dialog). Tested against a reference page
945
- closed like a strict host's (`leak/inherited-policy.spec.ts`).
910
+ Closed by default; opened only to origins the config declares. ADOPTING.md § "Choosing egress"
911
+ summarizes the levels (closed, library CDNs, passive media from any https site); this is the long
912
+ form.
913
+
914
+ The leak suite (`src/conformance/probes.ts`, `pnpm test:leak` against the reference host) attempts
915
+ each channel from inside the content, as an agent's code would, and asserts with an out-of-band
916
+ oracle that nothing left: an HTTP canary that also counts raw TCP connections, a UDP listener for
917
+ STUN, a witness origin a navigated document would reach, the page's responses. Each oracle has a
918
+ positive control (an allowed origin loads; an unsandboxed peer connection sends STUN; an unsandboxed
919
+ hint connects), or the probe says it has none. Each defense has a negative control
920
+ (`PORTHOLE_LEAK_WEAKEN`, P032) that takes it out, so its probes are seen to fail. Chromium 153,
921
+ WebKit 26.6 and Firefox 155 (Playwright 1.63) all gate (P017, P035).
922
+
923
+ Origins are exact, or `https://*.` a domain of the host's own. A wildcard over a public suffix
924
+ (`*.com`, `*.co.uk`, `*.github.io`) is refused, as is any scheme source, with one exception (P060):
925
+ `egress.anyHttps: ["img", "media", "font"]` lets passive content load from any https site (P059).
926
+ Those directives get `https:`; scripts, styles, data and frames never do, and the manual says so
927
+ (`leak/cdn.spec.ts`: a hotlinked image loads; a script, a stylesheet and a fetch to the same site
928
+ don't).
929
+
930
+ An opaque frame inherits the embedding page's whole policy (P058). On a page with `default-src
931
+ 'none'` and a tight `connect-src`/`img-src`, an origin the config opens stays shut; there, prefer
932
+ domain mode, whose frames inherit nothing. On a page that closes images or fetches to its own
933
+ origin, the positive controls of `1.connect` and `2.resources` can't load, through no fault of the
934
+ host's isolation; the suite then reports the probe inapplicable on this host, with the reason (the
935
+ allowed origin was blocked by a policy not the frame's own), instead of failing it. `12.no-confirm`
936
+ likewise, on a host that always has a confirm function (a default dialog). Tested on a reference
937
+ page closed like a strict host's (`leak/inherited-policy.spec.ts`).
946
938
 
947
939
  | # | Channel | Mechanism | Probes | Negative control → fails (Chromium / WebKit / Firefox) |
948
940
  |---|---------|-----------|--------|------------------------------------------|
@@ -957,11 +949,10 @@ closed like a strict host's (`leak/inherited-policy.spec.ts`).
957
949
  | 9 | the host's DOM, storage, cookies, credentials; another display | opaque origin (no `allow-same-origin`); nothing secret is sent into the frame; the shell takes messages only from its parent | `9.host`, `9.siblings` (a display can't navigate or drive another) | — (the sandbox is the platform's; measured: a new frame's realm is cross-origin even in the task that made it, both engines) |
958
950
  | 10 | the embedding page's own origin | no `'self'` in any directive (P022) | `10.self` | `self` → none: measured, an opaque frame's `'self'` reaches nothing of the host on either engine. Kept out anyway (nothing legitimate needs it) |
959
951
 
960
- Interop (`0.*`): the content runs in an opaque origin; the shell defines a global only
961
- per declared capability, fixed in place; it applies exactly the declared theme
962
- variables; streamed content is drawn inert and runs once; and content using the
963
- official App SDK connects under the inline, artifact and MCP Apps presets
964
- (`style-split` → all three, P028).
952
+ Interop (`0.*`): the content runs in an opaque origin; the shell defines a global only per declared
953
+ capability, fixed in place, and applies exactly the declared theme variables; streamed content is
954
+ drawn inert and runs once; content using the official App SDK connects under the inline, artifact
955
+ and MCP Apps presets (`style-split` → all three, P028).
965
956
 
966
957
  ### Behavior and gates, each with its test
967
958
 
@@ -977,12 +968,12 @@ official App SDK connects under the inline, artifact and MCP Apps presets
977
968
  | 14 | error reports (`reportError`, S05, P095) | the adapters hand the bridge what content logged as it came; the bridge counts reportError's rate before reading it, then makes bounded text of it (`boundedText`: each object once, `[Circular]`/`[Repeated]`; 1,000 values, 16 levels, 8,000 characters; a BigInt as `"5n"`), scrubs sealed addresses and cuts to 2,000; nothing a log holds throws out of an adapter | `14.error-shapes` (a cycle, a BigInt and a 20-level shared graph from an inline widget and from an MCP Apps view, each reported as bounded text); `test/log-bounds.test.ts` (undeclared or past its rate: nothing of it read) | `report-unbounded` → `14.error-shapes`, `14.silent` (its blocked-load report read as the text it was), on both host pages (P096) |
978
969
  | 12 | model context (`setModelContext`, S5, P100) | the `show` gate by default: the bridge hands the host's `show` the whole update (text blocks rebuilt, structured content P095's JSON data, at most `MAX_CONTEXT_CHARS`, no character the person can't see: format characters, variation selectors, private use, lone surrogates, controls but `\n` and `\t`, save the selectors and joiners of real emoji and the joiners that shape Arabic, Indic and Myanmar letters) after every other gate and before the handler; no `show`, or one that throws, refuses it (`no-show`, `not_allowed`), and `close` ends its wait; the manual calls it the content's unconfirmed text, never instructions, and says what is refused; the React provider's default `show` draws `ContextNotice`, whole, and lets a call go once its own update is on the page (one replaced before it was drawn is refused); named gates without `show` and without `withoutShow: true` earn a `ConfigWarning` | `12.model-context` (a raw `ui/update-model-context`: shown whole, then handled; a host without `show`: refused, no handler); `test/model-context.test.ts` (both adapters, the order, the shapes, the size, each invisible character in text, values and keys, the warning); `leak/react.spec.ts` (the default notice is drawn before the handler runs, with its size; two updates in one task: only the drawn one goes; stacked displays all reachable; no provider: refused) | `model-context-show` → `12.model-context` (all three, `scripts/controls.ts`; the kit's harness is built unweakened), and both React cases (measured on Chromium) |
979
970
 
980
- Measured: a click in the frame gives the host page user activation (it propagates to
981
- ancestors) on Chromium, WebKit and Firefox, so the host-side gesture check (`copyText`'s, and
982
- any a host names) holds for real clicks; it is still advisory, since a person may have clicked
983
- the host a moment before. Playwright's own page evaluations count as gestures, so the gate
984
- probes (`12.copy-text`, `12.raw-copy`; `shell-gesture` → copy-text, `host-gesture` → raw-copy)
985
- wait for that to lapse and click with raw input.
971
+ Measured: a click in the frame gives the host page user activation (it propagates to ancestors) on
972
+ Chromium, WebKit and Firefox, so the host-side gesture check (`copyText`'s, and any a host names)
973
+ holds for real clicks. It stays advisory: the person may have clicked the host a moment before.
974
+ Playwright's own page evaluations count as gestures, so the gate probes (`12.copy-text`,
975
+ `12.raw-copy`; `shell-gesture` → copy-text, `host-gesture` → raw-copy) wait for that to lapse and
976
+ click with raw input.
986
977
 
987
978
  ### Served content, each with its test
988
979
 
@@ -1014,14 +1005,12 @@ wait for that to lapse and click with raw input.
1014
1005
 
1015
1006
  ### The clipboard, and copy buttons
1016
1007
 
1017
- Content never writes the clipboard (P051). The frame's `allow` denies
1018
- `clipboard-read` and `clipboard-write` by name; the shell makes the async Clipboard
1019
- API refuse (`write`, `writeText`, `read`, `readText`), makes `execCommand` refuse
1020
- `copy`, `cut` and `paste`, and stops copy and cut events at the window before any
1021
- listener of the content's, so a copy the person makes copies their selection as the
1022
- browser makes it. Copy buttons call `copyText(text)` (P052): the host's page
1023
- writes the clipboard, inside the person's click (a click in a frame activates its
1024
- ancestors), and shows them what went on it.
1008
+ Content never writes the clipboard (P051). The frame's `allow` denies `clipboard-read` and
1009
+ `clipboard-write` by name. The shell makes the async Clipboard API (`write`, `writeText`, `read`,
1010
+ `readText`) and `execCommand`'s `copy`, `cut` and `paste` refuse, and stops copy and cut events at
1011
+ the window before any content listener, so the person's own copy copies their selection as the
1012
+ browser makes it. Copy buttons call `copyText(text)` (P052): the host's page writes the clipboard
1013
+ inside the person's click (a click in a frame activates its ancestors) and shows what went on it.
1025
1014
 
1026
1015
  | # | Channel | Mechanism | Probes | Negative control → fails |
1027
1016
  |---|---------|-----------|--------|--------------------------|
@@ -1030,338 +1019,234 @@ ancestors), and shows them what went on it.
1030
1019
  | 13 | a copy listener swapping what the person copies (`clipboardData.setData`) | copy and cut events stopped at the window, first | `13.clipboard-event` (the person's own copy works: positive control) | `clipboard` → all three |
1031
1020
  | 12 | `copyText` | a click (shell and host), 30 a minute, the host's handler | `12.copy-text` (refused on load; the whole text reaches the handler from a click) | — |
1032
1021
 
1033
- Measured before the walls (0.1.2): a click in an opaque widget wrote the clipboard
1034
- on all three engines (the async API on WebKit and Firefox, the copy command and copy
1035
- listeners everywhere). The oracle is the person's clipboard: text copied on the
1036
- host's page, then pasted back there. What the shell can't stop: text hidden by CSS
1037
- inside what the person selects goes with their copy (the browser's own copy); hosts
1038
- that care point people at copy buttons, whose toast shows exactly what was copied.
1022
+ Measured before the walls: a click in an opaque widget wrote the clipboard on all three engines (the
1023
+ async API on WebKit and Firefox, the copy command and copy listeners everywhere). The oracle is the
1024
+ person's clipboard: copied on the host's page, then pasted back there. Not stoppable: text hidden by
1025
+ CSS inside what the person selects goes with their copy (the browser's own); hosts that care point
1026
+ people at copy buttons, whose toast shows exactly what was copied.
1039
1027
 
1040
- ### Annotations
1028
+ ## Annotations
1041
1029
 
1042
- A person points at part of a display to comment on it (P053). The host drives the
1043
- shell with Porthole's own messages and the shell reports back; the config declares
1044
- `annotate` (inline widgets and artifact pages; MCP Apps views where the host
1045
- chooses), and the annotation runtime is in the shell only then.
1030
+ A person points at part of a display to comment on it (P053). Where the config declares `annotate`
1031
+ (inline widgets and artifact pages; MCP Apps views where the host chooses), the annotation runtime
1032
+ is in the shell; the host drives it with Porthole's own messages and it reports back. Wiring and
1033
+ host duties: [ADOPTING.md § Annotations](ADOPTING.md#annotations-comments-on-a-display). What a page
1034
+ can learn or fake: [THREAT_MODEL.md § 7](THREAT_MODEL.md#7-the-display-layer-and-the-app-runtime).
1046
1035
 
1047
1036
  | Direction | Message | Params |
1048
1037
  |-----------|---------|--------|
1049
- | host → frame | `porthole/annotate.start` | `{ elements, text, keepSelection? }`: picking elements (the one under the pointer or finger outlined with its name; a click or tap picks it, never reaching the content; Escape cancels; one pick), selecting text (each settled selection), or both (a click picks, a drag selects); `keepSelection: true` (absent otherwise): the host follows what is selected, so the frame keeps it, and a pick's outline, for a follow asked after `selected` (P140) |
1038
+ | host → frame | `porthole/annotate.start` | `{ elements, text, keepSelection? }`: picking elements (the one under the pointer or finger outlined with its name; a click or tap picks it, never reaching the content; Escape cancels; one pick), selecting text (each settled selection), or both (a click picks, a drag selects); `keepSelection: true`: the host will follow what is selected, so the frame keeps it, and a pick's outline (P140) |
1050
1039
  | host → frame | `porthole/annotate.stop` | — |
1051
- | host → frame | `porthole/annotate.show` | `{ marks: [{ id, anchor, count?, kind? }], active? }`: drawn over the content in the shell's own layer (a closed shadow root), found again whenever the content changes; a mark with a `count` (0 to 999; the host clamps a larger one, P116) also gets a marker (P104); `kind: "draft"` (absent: posted) is drawn apart, with a marker and never a count (P107) |
1040
+ | host → frame | `porthole/annotate.show` | `{ marks: [{ id, anchor, count?, kind? }], active? }`: drawn in the shell's own layer, found again whenever the content changes; a `count` (0 to 999; the host clamps a larger one, P116) gives a marker (P104); `kind: "draft"` (absent: posted) is drawn apart, with a marker and never a count (P107) |
1052
1041
  | host → frame | `porthole/annotate.focus` | `{ id }`: scrolled into view inside the frame, made the active mark, flashed |
1053
1042
  | host → frame | `porthole/annotate.clear` | — |
1054
- | host → frame | `porthole/annotate.clearSelection` | —: the page's text selection is taken away (the DOM's own `removeAllRanges`, taken before content runs) with what the shell held of it, and nothing is reported back; marks, drafts and the mode stay (P115) |
1055
- | host → frame | `porthole/annotate.focusMark` | `{ id, at }`, `at` the host's `Date.now()` as it sent it (P137): the DOM focus goes to that mark's marker (the DOM's own `focus`, taken before content runs), once the marks of a `show` are found; a call that had to wait for them is dropped unless the focus is in the frame's document as it lands (the DOM's own `hasFocus`, taken before content runs; P135), and so is one the frame takes 100 ms or more after `at` by its own clock (the DOM's own `Date.now`, taken before content runs) or with no `at` (P137); a fresh one isn't asked; nothing is reported back, and with no such marker, or while elements are picked, nothing happens. For after the keyboard closed the host's view: Escape, or a Tab past its ends (P134); a host calls it again after its own `display.focus()` |
1056
- | frame → host | `porthole/annotate.selected` | `{ anchor, rect, lastLineDocumentRect?, scroll? }` (a newer shell's last two, only as a pair: P133, below, P137); after a scroll, the same selection again only if its box moved more than 0.5 px, on the follow-ups' clock (P105), and not while the host follows the selection (P138) |
1043
+ | host → frame | `porthole/annotate.clearSelection` | —: the page's text selection is taken away (the DOM's own `removeAllRanges`, taken before content runs) with what the shell held of it; nothing is reported back; marks, drafts and the mode stay (P115) |
1044
+ | host → frame | `porthole/annotate.focusMark` | `{ id, at }`, `at` the host's `Date.now()` as it sent it: the DOM focus goes to that mark's marker once the marks of a `show` are found. Dropped if it had to wait and the focus isn't in the frame's document as it lands (the DOM's own `hasFocus`, P135), if the frame takes it 100 ms or more after `at` by its own clock (the DOM's own `Date.now`), or with no `at` (P137); the built-ins are taken before content runs. Nothing is reported back; with no such marker, or while elements are picked, nothing happens. For after the keyboard closed the host's view: Escape, or a Tab past its ends (P134) |
1045
+ | host → frame | `porthole/annotate.track` | `{ id }` or `{ id: null }`: follow one shown mark, or none (P112); `{ id: null, selection: true }`: follow the selection last reported as `selected`, highlighted while followed (P138; an older shell reads it as none) |
1046
+ | frame → host | `porthole/annotate.selected` | `{ anchor, rect, lastLineDocumentRect?, scroll?, pointDocument? }` (`lastLineDocumentRect` and `scroll` only as a pair, P133, P137; `pointDocument` only on an element pick, and with `scroll`, P150); after a scroll, sent again only if its box moved more than 0.5 px, on the follow-ups' clock (P105), and not while the host follows the selection (P138) |
1057
1047
  | frame → host | `porthole/annotate.unselected` | — (the text selection went away) |
1058
1048
  | frame → host | `porthole/annotate.cancelled` | — (Escape) |
1059
- | frame → host | `porthole/annotate.anchored` | `{ results: [{ id, state: "attached" \| "orphaned", rect?, documentRect?, lastLineDocumentRect?, order? }], scroll? }` (a newer shell's `documentRect` and `scroll`: P132, below; `lastLineDocumentRect`: P133, never without `scroll`, P137): every mark after `show`, the one after `focus`, every mark when the content changed a state, and, while any mark has a marker (a `count` or a draft, P107), once a scroll, a resize or a run of content changes has settled (150 ms quiet), only the marks that moved more than 0.5 px since the host was last told, at most one a second together with the selection's (P104, P105) |
1060
- | host → frame | `porthole/annotate.track` | `{ id }` or `{ id: null }`: follow one shown mark, or none (P112); `{ id: null, selection: true }`: follow the selection last reported as `selected` instead, and highlight it while followed (P138; an older shell reads it as none) |
1061
- | frame → host | `porthole/annotate.tracked` | `{ id, rect, documentRect?, lastLineDocumentRect?, scroll? }`: the followed mark's box at an animation frame where it moved, at most one every 16 ms; the host takes 60 a second, for that mark only (P112); a newer shell adds its place in the document and the document's scroll (P132), and its last line's (P133, never without the scroll, P137) |
1062
- | frame → host | `porthole/annotate.selectionTracked` | `{ state: "attached", rect, documentRect, lastLineDocumentRect?, scroll, inView }` or `{ state: "orphaned" }`: the followed selection's boxes, as `tracked`'s, at an animation frame where it moved or the viewport changed size, at most one every 16 ms, the first at the frame after the host asks; `orphaned` once while it isn't in the page (or the frame has no selection), found again by its anchor at most twice a second; the host takes it only while it follows the selection (otherwise dropped unread, no refusal, P140), 60 a second with `tracked`, its `rect` clamped, `inView` false unless its box as read reaches the viewport (P138) |
1063
- | frame → host | `porthole/annotate.activated` | `{ id, rect }`: the person clicked a mark's marker, or pressed Enter or Space on it (P133); `rect` is the marker's (P104); taken only while the host's page has transient activation (P105) |
1064
-
1065
- - **Anchors** are W3C Web Annotation selectors, at most one of each:
1066
- `CssSelector` (unique: the nearest id, else a path of `nth-of-type` steps),
1067
- `TextQuoteSelector` (the words, with 32 characters of context each side), and
1068
- `TextPositionSelector` (offsets into the body's text, without scripts, styles and
1069
- templates). An element anchor has its selector and its first 300 characters of
1070
- text; a text anchor its words (at most 4,000), position and nearest element.
1071
- - **Found again**, best-effort: a text anchor where it was, else its words anywhere
1072
- (the occurrence whose context matches best), else its words with any spacing; an
1073
- element anchor by its selector if its text still starts with its words (or the
1074
- selector is an id, or it has no words), else the element holding its words. What
1075
- can't be found is `orphaned`, said so; a host keeps the comment and shows it apart.
1076
- - **Rects** are in the frame's viewport, CSS px: add the frame element's position
1077
- (and map them through the frame's transform, where the host scales it). They are
1078
- the page's word: `createHost` clamps each to the frame's viewport before the host
1079
- hears it (P104); a box wholly outside becomes one of no size on the nearest edge
1080
- (a mark below the fold: `y` at the viewport's height, no height). A platform whose
1081
- `viewport()` answers no size or throws gets nothing at the corner (P105).
1082
- - **Places in the document** (P132). A newer shell gives each attached result a
1083
- `documentRect` too: its box plus how far the document was scrolled as it was read, the
1084
- report's `scroll` (`{ x, y }`: the root element's top left from the viewport's, negated,
1085
- read with the DOM's own `getBoundingClientRect`). So it stays put as the document
1086
- scrolls, and says where a mark outside the frame is; `rect` is `documentRect` less
1087
- `scroll`, before the clamp. `tracked` carries both too: a followed mark's box moves at
1088
- every scroll, so its reports tell the scroll at each animation frame, in the frame or
1089
- not. `createHost` checks them as boxes (finite, within the coordinate limit, sizes not
1090
- negative; a malformed one drops the report) and clamps neither: the host clips what it
1091
- draws from them. A page that scrolls a box of its own rather than its document moves
1092
- its marks' places with it, as their `rect` does; those are told as before.
1093
- - **The last line** (P133). A newer shell says where a selection or a mark ends, for a
1094
- host's UI after it: `lastLineDocumentRect`, on `selected` (with `scroll`, read with
1095
- it), on each attached result of `anchored` and on `tracked`, in the coordinates of
1096
- `documentRect`, checked and left unclamped as it is. It is the last box with a width
1097
- of the words' client rects, the box a text marker's place starts from; an element,
1098
- which has no lines of its own, gives its whole box. Its place in the frame's viewport
1099
- is it less `scroll`. Absent from an older shell, and where nothing of it is drawn.
1100
- - **The selection followed** (P138, P140). For a host that follows the selection, or said at
1101
- `start` that it will (`keepSelection`), the shell keeps what each `selected` reported: the
1102
- element picked (a click, or a block held), or a copy of the selection's range (the
1103
- DOM's own `cloneRange`, taken before content runs), which the page's changes keep up to
1104
- date and which stays when the page's own selection goes (the host's `clearSelection`
1105
- too). While the host follows it (`track` with `selection`; one followed thing at a time,
1106
- so a mark's id or `null` ends it, as `clear` does; `show`, `stop` and a pick's end leave
1107
- it), it is drawn in the layer as a pick is (an element in the picking outline, lighter
1108
- and without its name; words with a light fill and a line under them, in the picking
1109
- blue) and its boxes are told as a followed mark's are, with `inView` (any of its box in
1110
- the viewport). Taken out of the page, it is `orphaned` once, and found again by its
1111
- anchor as a mark is. It reads boxes only: no focus moves, no selection changes, no
1112
- listener is added, and nothing about the words goes with it (they went with
1113
- `selected`). A newer `selected` replaces it, followed from the next frame. For any other host
1114
- nothing is kept and a pick's outline goes with the pick, as before P138; the end of a following
1115
- lets the kept selection go unless `keepSelection` holds (P140). Under `keepSelection`, before the
1116
- host follows it, the element just picked keeps an outline drawn the same way, so nothing changes
1117
- on screen when the follow takes over; until a follow it ends as a selection does (the next pick
1118
- or selection, `clearSelection`, `start`, `stop`, `clear`, Escape, the element leaving the page),
1119
- on no timer (Tenny's review). While followed, a scroll re-sends no `selected` (P105's follow-up):
1120
- once the following ends, it does again. The React binding sends the following before a mode
1121
- change made in the same render, and starts the mode with `keepSelection` while
1122
- `trackedSelection` is given (P140), read at each start and never a reason for one. The host drops a `selectionTracked` unread, before parsing
1123
- it, while it follows no selection (P140).
1124
- - **Markers** (P104). A mark with a `count` gets a bubble glyph and its number ("99+"
1125
- above 99; 0 the bubble alone), a real button (P133, below), on an element's top right
1126
- corner, inside the frame's width, and at the end of a text anchor's paragraph (P133):
1127
- on the last line of the block its words end in, read as far as a block inside it,
1128
- just past that line's last word, or where that doesn't fit at the places a draft's
1129
- takes. A draft's goes beside its anchor's own last line, centred on it (P105, #36): in
1130
- the line's gutter, just past the right edge of the anchor's block; at the frame's right
1131
- edge where the frame is too narrow for that; just past the line's last word where
1132
- something else is beside the block (a table's next cell, a card in a row). Each
1133
- place must be clear of that line's words and of anything of the content's but a box
1134
- holding the anchor, between the words and the marker too (the shell hit-tests it).
1135
- Markers ending on one line go together, in the order their words end; where the
1136
- bubble with its glyph fits nowhere, its number alone does (compact); where neither
1137
- does (two anchors on one full line of a phone), they go over the line's end. The
1138
- pointer on a marker lights its words. Placing costs a bounded number of hit tests
1139
- per marker in view (the layer's own boxes out of the way meanwhile), none for one
1140
- out of view, and its line's end is read only as far as the line goes (P105: 300
1141
- marks with counts in view, about 20 ms a change). An element's mark with a marker
1142
- is a thin line. The layer takes no pointer but on markers: a press on one, and the pointer's
1143
- moves over it, are stopped in the shell's first window listener, read through the
1144
- platform's own functions kept before content runs (P105), and a trusted click is
1145
- reported `activated`; a tap too, on WebKit as well, since a button is an element it
1146
- makes a tap a click on (P105). On
1147
- touch (P119), while the last pointer down or moved was a finger or a pen (before any,
1148
- where `(any-pointer: coarse)` matches), each marker also takes the pointer in a box of
1149
- at least 44 by 44 px centred on its bubble (an invisible `::before` in the layer), the
1150
- bubble itself unchanged; a press there is a press on the marker, and where two such
1151
- boxes overlap it is the marker whose bubble's centre is nearest (on a bubble, that
1152
- bubble). A mouse's move takes the boxes away, so a mouse is hit-tested on bubbles
1153
- alone. Against content that patches none of the built-ins, none of
1154
- its handlers, nor what is under the marker, gets them; content that patches others
1155
- can reach the layer's nodes (P105). Either way the content can tell a press
1156
- happened, by `:active`, `relatedTarget` and user activation. Markers step aside
1157
- while elements are picked, the keyboard's Tab too.
1158
- - **Markers from the keyboard** (P133). Each marker is a `<button>` with a tab stop,
1159
- in the page's reading order after the page's own stops (the layer is the document's
1160
- last child), named for what it is (`aria-label`: `3 comments on "…"`, `Draft comment
1161
- on "…"`, with the words it is on, an element's tag left out, P134, in English); only the markers are exposed to
1162
- assistive technology, the layer no longer `aria-hidden`, its marks and outline are.
1163
- A press of a pointer still moves no focus. Enter and Space make the button's own
1164
- trusted click, which goes the way a pointer's does, but has no count and no place, so
1165
- it is the focused marker's (read through the shadow root's `activeElement`, kept
1166
- before content runs); those two keys are stopped at the window as a press is, a
1167
- repeat of them cancelled (a key held down clicks once), and every other key stays the
1168
- page's. A real key gives the host's page transient activation as a click does. The
1169
- focus on a marker lights its words and, out of view, scrolls the document to it: the
1170
- layer clips rather than hides, so it never scrolls itself. While one has the focus a
1171
- draw takes the markers out of hit tests by `pointer-events`, not `display` (which
1172
- would lose it), and moves none. The page shares the focus order: the host's own list
1173
- of marks stays the keyboard path it can rely on.
1174
- - **Drafts** (P107). A mark with `kind: "draft"` (a comment not yet posted) has a
1175
- marker whether or not it has a count, placed by its own words (not at its paragraph's
1176
- end, P133), and drawn apart: a
1177
- dashed underline (a dashed outline on an element), a lighter fill, and a hollow
1178
- marker (a light bubble with a dashed edge and the glyph's outline) with no number.
1179
- `checkMarks` sends a posted mark as before (no `kind`), a draft without its count,
1180
- and throws on any other kind; the shell draws no number for a draft and drops a
1181
- mark of a kind it doesn't know. Its click is `activated`, its place `anchored`,
1182
- and it is followed after a scroll, as a posted marker's.
1183
- - **Following** (P104), only while a mark has a marker (a `count`, or a draft:
1184
- P107). Each mark keeps what the host was last told (state and box); a settled
1185
- scroll or resize (any scroller), or
1186
- a quiet run of content changes (one the deadline cut short is checked once quiet),
1187
- reports only what moved. A selection the host was told is told again after a
1188
- settled scroll only if its box moved (P105, with or without counts). Both share one
1189
- clock, at most one report a second (the latest), so honest scrolling takes at most
1190
- half of the bridge's 120 a minute.
1191
- - **Settled.** Nothing is reported before the content is in place (marks shown
1192
- before it arrives are anchored once it has), nor while a run of changes settles; a
1193
- `focus` asked for meanwhile waits for anchoring, then scrolls and reports, so a
1194
- focus right after `show` says where the mark is, never `orphaned` first (P057).
1195
- - **Trust.** The shell shares its realm with the content, which can interfere with
1196
- all of it, read what `show` sends (ids, anchors, counts), or fake any report. The
1197
- host takes a selection only while it asked for that kind, a cancel only while
1198
- picking, results only for its own marks, a marker's click only for a mark it shows
1199
- with a marker (a count or a draft), with or without a gesture (P149); it rebuilds
1200
- each from known fields within `ANNOTATION_LIMITS` (a label without what the person can't see, P105) and
1201
- drops the rest, through the bridge's rate limit. UI hints only, never
1202
- permissions: what a report says decides where a comment is drawn, never who may
1203
- see or do anything. A view a report opens or moves guards its presses
1204
- (THREAT_MODEL §6).
1205
- - **Host API.** `display.annotations.start(mode?)`, `stop()`, `show(marks)`,
1206
- `focus(id)`, `track(id)`, `clear()`, `clearSelection()` (P115), `focusMark(id)` (P134), and the
1207
- `annotation` event (`AnnotationReport`); the state is given to every frame the display runs (not a
1208
- `clearSelection`: a new frame has no selection; nor a `focusMark`). `parseAnchor` checks an anchor a host
1209
- stores (its server, before saving a comment).
1210
-
1211
- Tests (`leak/annotate.spec.ts`, all three engines): a pick outlines and picks
1212
- without the content seeing the click, by id or by path; Escape cancels; a text
1213
- selection and its clearing; both modes together; marks shown, one focused into
1214
- view, one orphaned, all cleared; re-anchoring on a revised page (by id, by words
1215
- moved, by words respaced, one deleted and orphaned); live changes reported only as
1216
- they change; an MCP Apps view; and a hostile page faking every report (not asked,
1217
- malformed, too large, the wrong kind, no such mark, a flood), whose negative
1218
- control is `annotation-checks`. Markers (P104): drawn with their numbers, a click
1219
- reported with its id and box and heard by none of the content's listeners, nor a
1220
- double, right or middle click (`marker-click` → those two cases), by the keyboard
1221
- too (P133: a button in reading order and named for what it is, Enter and Space
1222
- reported once, a key held down once, none of it heard, nothing while elements are
1223
- picked; `marker-key`, `marker-click` too), brought into view by the focus and keeping
1224
- it through redraws, reached by the host's `focusMark` after its card closed and left
1225
- alone where there's no such marker, by the kept `focus` (P134, `marker-focus`), a call parked meanwhile
1226
- dropped once the person has moved on or the focus is on the host's body, and a second after the
1227
- host's `display.focus()` landing (P135, `marker-late`), by the kept
1228
- `hasFocus`, which a page's patch can't answer (`marker-has-focus`), a word a busy page takes late
1229
- held to the same test, by the host's stamp and the kept clock, a calm close landing, and a second
1230
- word after the host's move landing (P137, `marker-busy`, `marker-clock`, in
1231
- `late-word.spec.ts`, which full Chromium runs too, where a person's click comes before the
1232
- word), at its paragraph's end past the last word, a nested block's
1233
- words not its own, a draft's by its words; focus and
1234
- selection kept, a drag from a marker too (`marker-prevent` → the press case), none
1235
- without a count, stepping aside while picking, drawn whole at the frame's top; a
1236
- run of scrolls reported with only the marks that moved, a fixed one never; marks
1237
- without counts told nothing after a scroll (`follow-count`); a long honest scroll
1238
- session in comment mode, a selection made, leaving a marker's click its budget,
1239
- and then, by when each arrives, the selection's re-reports and the marks'
1240
- follow-ups a second apart however fast the machine (`follow-throttle`,
1241
- `selection-follow`); a content change that moves one mark
1242
- reports it alone, even when the deadline cut its run short; a hostile page faking a
1243
- marker's click for no mark, an unknown id or a mark without a marker, or clicking
1244
- the layer itself (`annotation-activated`, `annotation-activated-count`,
1245
- `marker-trusted` → that case); and a page that patches `Event`'s and
1246
- `MouseEvent`'s prototypes neither hearing a marker's press nor stopping its report
1247
- (`marker-originals`; `marker-click` too); a tap on a marker reported on each
1248
- engine, a touch screen and a phone's emulation (iPhone 13, Pixel 5), content hearing
1249
- none of it (`marker-click`); on a 640 px column and a phone page's lines
1250
- with one marker each, no marker covering a word (`marker-place`, the marker just
1251
- past its words as 0.9.0 had it, which a draft's in a line's middle shows); drafts (P107) drawn apart from posted marks on the
1252
- same anchors (the frame's pixels and the words' own differ; on Chromium every draft's
1253
- marker and line drawn as a draft's, no number though given a count), a draft's and a
1254
- posted marker's clicks reported beside each other, none reaching the content
1255
- (`marker-click` too), the
1256
- page reading a draft's kind and never its count (`draft-count`), a raw `show` past
1257
- `checkMarks` drawing a draft given a count without a number and dropping a mark of
1258
- an unknown kind (`draft-shell-checks`), and drafts alone followed after a scroll; and ADOPTING.md's `guardPresses`, as written
1259
- there, taking no press within 500 ms of its view opening (a release on a menu item,
1260
- a double click's second press on a button or a trigger, a press held past the
1261
- arming) and the person's own press or key after. The host's `clearSelection` (P115) takes
1262
- a selection away from a page that patched `Selection.prototype.removeAllRanges`, tells
1263
- nothing back, leaves marks and drafts found, and the same words selected again are told
1264
- (`clear-selection`).
1265
-
1266
- ### Find in page
1267
-
1268
- A host's own find bar over a display (P131), where the config declares `find`:
1269
-
1270
- - **Shell.** `FIND_RUNTIME` (`src/shell/find.ts`), spliced in as the annotation runtime is, before
1049
+ | frame → host | `porthole/annotate.anchored` | `{ results: [{ id, state: "attached" \| "orphaned", rect?, documentRect?, lastLineDocumentRect?, order? }], scroll? }`: every mark after `show`, the one after `focus`, every mark when the content changed a state; while any mark has a marker, once a scroll, a resize or a run of content changes has settled (150 ms quiet), only the marks that moved more than 0.5 px since the host was last told, at most one a second together with the selection's (P104, P105) |
1050
+ | frame → host | `porthole/annotate.tracked` | `{ id, rect, documentRect?, lastLineDocumentRect?, scroll? }`: the followed mark's box at an animation frame where it moved, at most one every 16 ms; the host takes 60 a second, for that mark only (P112, P132, P133) |
1051
+ | frame → host | `porthole/annotate.selectionTracked` | `{ state: "attached", rect, documentRect, lastLineDocumentRect?, scroll, inView }` or `{ state: "orphaned" }`: the followed selection's boxes, as `tracked`'s, also when the viewport changed size, the first at the frame after the host asks; `orphaned` once while it isn't in the page, found again by its anchor at most twice a second. The host takes it only while it follows the selection (otherwise dropped unread, no refusal, P140), 60 a second with `tracked`, its `rect` clamped, `inView` false unless its box reaches the viewport (P138) |
1052
+ | frame → host | `porthole/annotate.activated` | `{ id, rect }`: the person clicked a mark's marker, or pressed Enter or Space on it (P133); `rect` is the marker's (P104); no gesture is asked of it (P149) |
1053
+
1054
+ - **Anchors** are W3C Web Annotation selectors, at most one of each: `CssSelector` (unique: the
1055
+ nearest id, else `nth-of-type` steps), `TextQuoteSelector` (the words, with 32 characters of
1056
+ context each side), `TextPositionSelector` (offsets into the body's text, without scripts, styles
1057
+ and templates). An element anchor has its selector and first 300 characters of text; a text anchor
1058
+ its words (at most 4,000), position and nearest element.
1059
+ - **Found again**, best-effort. A text anchor: where it was, else its words anywhere (the occurrence
1060
+ whose context matches best), else its words with any spacing. An element anchor: its selector if
1061
+ its text still starts with its words (or the selector is an id, or it has no words), else the
1062
+ element holding its words. Not found: `orphaned`; a host keeps the comment and shows it apart.
1063
+ - **Boxes.** `rect` is in the frame's viewport, CSS px (the host adds the frame element's position
1064
+ and maps it through the frame's transform). `createHost` clamps each `rect` to the frame's
1065
+ viewport (P104): a box wholly outside becomes a zero-size one on the nearest edge; a platform
1066
+ whose `viewport()` answers no size or throws gets nothing at the corner (P105). `documentRect`
1067
+ (P132) is the box plus the document's scroll as read (the report's `scroll`, `{ x, y }`, via the
1068
+ DOM's own `getBoundingClientRect`), so it places a mark outside the frame; `rect` is
1069
+ `documentRect` less `scroll`, before the clamp. `lastLineDocumentRect` (P133) is the last box with
1070
+ a width of the words' client rects (an element's whole box), same coordinates, for a host's UI
1071
+ after a selection or mark. `createHost` checks these as boxes (finite, within the coordinate
1072
+ limit, sizes not negative; a malformed one drops the report) and clamps neither: the host clips
1073
+ what it draws. `pointDocument` (P150), on an element picked by a pointer, is the point it was
1074
+ picked at (the click's or tap's, a held finger's press), plus `scroll`, as these are: for a host's
1075
+ UI where the element is larger than most of the frame. Checked as `scroll` is (two finite numbers
1076
+ within the limit), unclamped; one on a text selection, or without `scroll`, drops the report; a
1077
+ pick from the keyboard has none. A page scrolling a box of its own rather than its document moves
1078
+ its marks' places with it, as `rect`.
1079
+ - **The selection followed** (P138, P140). For a host that follows the selection, or said at `start`
1080
+ it will (`keepSelection`), the shell keeps what each `selected` reported (the element picked, or a
1081
+ copy of the range via the DOM's own `cloneRange`), updated through the page's changes and kept
1082
+ when the page's own selection goes. One thing is followed at a time: a mark's id, `null` or
1083
+ `clear` ends it; `show`, `stop` and a pick's end leave it. Followed, it is drawn in the layer (an
1084
+ element outlined, lighter, without its name; words with a light fill and an underline) and its
1085
+ boxes are told as a followed mark's, with `inView`. Boxes only: no focus moves, no selection
1086
+ changes, no listener added, nothing of the words sent. Under `keepSelection`, before a follow, a
1087
+ just-picked element keeps the same outline, so nothing changes on screen when the follow takes
1088
+ over; it ends as a selection does (the next pick or selection, `clearSelection`, `start`, `stop`,
1089
+ `clear`, Escape, the element leaving the page), on no timer. Ending a follow lets the kept
1090
+ selection go unless `keepSelection` holds; for other hosts nothing is kept and a pick's outline
1091
+ goes with the pick. The React binding sends the follow before a mode change in the same render,
1092
+ and starts the mode with `keepSelection` while `trackedSelection` is given (read at each start,
1093
+ never a reason for one).
1094
+ - **Markers** (P104, P133). A mark with a `count` gets a real `<button>`: a bubble glyph and its
1095
+ number ("99+" above 99; 0 the bubble alone), on an element's top right corner, or at the end of a
1096
+ text anchor's paragraph just past the last word of its last line, or failing that where a draft's
1097
+ goes. A draft's goes beside its own last line: in the gutter past the block's right edge, at the
1098
+ frame's right edge where the frame is too narrow, or just past the line's last word where
1099
+ something else is beside the block (P105, #36). Each place must be clear of the line's words and
1100
+ of anything of the content's but a box holding the anchor (the shell hit-tests it). Markers on one
1101
+ line go together in the order their words end; where the bubble doesn't fit its number alone does
1102
+ (compact); where neither fits they go over the line's end. Pointing at a marker lights its words;
1103
+ an element's mark with a marker is a thin line. Placing costs a bounded number of hit tests per
1104
+ marker in view, none out of view, and reads a line's end only as far as the line goes (P105: 300
1105
+ marks with counts in view, about 20 ms a change).
1106
+ - **The layer** is a closed shadow root, the document's last child, taking no pointer except on
1107
+ markers. A press on a marker, and pointer moves over it, are stopped in the shell's first window
1108
+ listener, read through built-ins kept before content runs (P105); a trusted click or a tap is
1109
+ reported `activated`. On touch (P119), while the last pointer down or moved was a finger or pen
1110
+ (before any, where `(any-pointer: coarse)` matches), each marker also takes the pointer in a box
1111
+ of at least 44 by 44 px centred on its bubble (an invisible `::before` in the layer), the nearest
1112
+ bubble's where two overlap; a mouse move takes the boxes away, so a mouse is hit-tested on bubbles
1113
+ alone. Content that patches no built-in hears none of a press; content that patches others can
1114
+ reach the layer's nodes (P105); either way it can tell a press happened (`:active`,
1115
+ `relatedTarget`, user activation). A pointer press moves no focus. Markers step aside while
1116
+ elements are picked, from Tab too.
1117
+ - **The keyboard** (P133, P134). Each marker has a tab stop after the page's own and a name
1118
+ (`aria-label`: `3 comments on "…"`, `Draft comment on "…"`, an element's tag left out, P134, in
1119
+ English); only markers are exposed to assistive technology. Enter and Space make the focused
1120
+ marker (the shadow root's `activeElement`, kept before content runs) give its own trusted click;
1121
+ those keys are stopped at the window, a held key clicks once, and every other key stays the
1122
+ page's. A real key gives the host's page transient activation as a click does. Focus on a marker
1123
+ lights its words and, out of view, scrolls the document to it (the layer clips rather than hides,
1124
+ so it never scrolls itself). While a marker has focus, a draw moves none and takes markers out of
1125
+ hit tests by `pointer-events`, not `display`. The host's own list of marks stays the keyboard path
1126
+ it can rely on.
1127
+ - **Drafts** (P107). A `kind: "draft"` mark has a marker with or without a count, placed by its own
1128
+ words, drawn apart: a dashed underline (a dashed outline on an element), a lighter fill, a hollow
1129
+ marker with no number. `checkMarks` sends a draft without its count and throws on an unknown kind;
1130
+ the shell draws no number for a draft and drops a mark of an unknown kind. Its click, place and
1131
+ following are a posted marker's.
1132
+ - **Following and budgets** (P104, P105, P057). Only while a mark has a marker (a count or a draft)
1133
+ does each mark keep what the host was last told; a settled scroll or resize (any scroller), or a
1134
+ quiet run of content changes, reports only what moved. A selection already told is told again
1135
+ after a settled scroll only if its box moved. One shared clock, at most one report a second, so
1136
+ honest scrolling takes at most half of the bridge's 120 a minute. Nothing is reported before the
1137
+ content is in place (earlier marks are anchored once it is) or while changes settle; a `focus`
1138
+ asked meanwhile waits, so a focus right after `show` is never `orphaned` first.
1139
+ - **What the host takes** (THREAT_MODEL.md § 7 says what a page can fake). A selection only while it
1140
+ asked for that kind, a cancel only while picking, results only for its own marks, a marker's click
1141
+ only for a mark it shows with a marker, gesture or not (P149); each rebuilt from known fields
1142
+ within `ANNOTATION_LIMITS` (a label stripped of what the person can't see, P105), the rest
1143
+ dropped, at the bridge's rate. A report places a comment, never decides who may see or do
1144
+ anything.
1145
+ - **Host API.** `display.annotations.start(mode?)`, `stop()`, `show(marks)`, `focus(id)`,
1146
+ `track(id)`, `clear()`, `clearSelection()`, `focusMark(id)`, and the `annotation` event
1147
+ (`AnnotationReport`). The state goes to every frame the display runs (not `clearSelection` or
1148
+ `focusMark`). `parseAnchor` checks an anchor a host stores.
1149
+
1150
+ Tests (`leak/annotate.spec.ts`, and `leak/late-word.spec.ts` for a word a busy page takes late,
1151
+ which full Chromium runs too; all three engines): picking and selecting unseen by the content; marks
1152
+ shown, focused, orphaned and found again on a revised page; follow-ups only for what moved, within
1153
+ budget; markers clear of words, reported by click, tap and key, heard by none of the content, also
1154
+ against patched built-ins; `focusMark` landing only when it should; drafts drawn apart; the
1155
+ selection followed; `clearSelection` against a patched `removeAllRanges`; a hostile page faking
1156
+ every report; and ADOPTING.md's `guardPresses`, as written there, taking no press within 500 ms of
1157
+ its view opening and the person's own press or key after. Negative controls: § The negative
1158
+ controls.
1159
+
1160
+ ## Find in page
1161
+
1162
+ A host's own find bar over a display (P131), where the config declares `find`. Wiring: [ADOPTING.md
1163
+ § Find in page](ADOPTING.md#find-in-page-the-hosts-find-bar). What the page learns: [THREAT_MODEL.md
1164
+ § 7](THREAT_MODEL.md#7-the-display-layer-and-the-app-runtime).
1165
+
1166
+ - **Shell.** `FIND_RUNTIME` (`src/shell/find.ts`) is spliced in like the annotation runtime, before
1271
1167
  content runs. It finds a query (`porthole/find.query`, a request) in annotations' text index
1272
1168
  (`TEXT_INDEX`, `src/shell/text.ts`, shared), case-insensitive and loose about spacing
1273
- (`FIND_MATCH`), only matches that are drawn, at most 1,000; draws them in a layer of its own (a
1274
- closed shadow root, annotations' layer style), the current one apart, redrawn on scroll and
1275
- resize and found again as the content changes (`porthole/find.updated`, at most once a second);
1276
- brings the current one into view through its scrolling ancestors and the window; and, while the
1277
- host says it draws its own bar (`porthole/find.handled`), cancels the browser's find on Cmd+F or
1278
- Ctrl+F a page didn't take (`FIND_SHORTCUT`) and says `porthole/find.requested`. Like the guards
1279
- (P129), it and the text index call only built-ins captured before content runs, through
1280
- `callOf`; its layer goes in through the guarded insertion methods (P130,
1169
+ (`FIND_MATCH`), drawn matches only, at most 1,000. It draws them in a layer of its own (a closed
1170
+ shadow root, annotations' layer style; never the CSS Custom Highlight API, which the content can
1171
+ read and rewrite), the current one apart, redrawn on scroll and resize and found again as content
1172
+ changes (`porthole/find.updated`, at most once a second), and brings the current one into view
1173
+ through its scrolling ancestors and the window. While the host says it draws its own bar
1174
+ (`porthole/find.handled`), it cancels the browser's find on a Cmd+F or Ctrl+F the page didn't take
1175
+ (`FIND_SHORTCUT`) and says `porthole/find.requested`. Like the guards (P129), it and the text
1176
+ index call only built-ins captured before content runs, through `callOf`; its layer goes in
1177
+ through the guarded insertion methods (P130,
1281
1178
  [insertion-entry-points.md](insertion-entry-points.md) § The shell's own layers).
1282
1179
  - **Host API.** `display.find.query(query, { direction, caseSensitive })` → `{ total, active,
1283
- capped?, rect? }` or `"unsupported"` (no `find`, an older shell's `-32601`, a malformed answer, no
1284
- answer in `FIND_LIMITS.timeoutMs`, a query superseded by a later one: the shell searches only the
1285
- latest of a burst, `FIND_LATEST`), `clear()`, `takeShortcut(take)`; the query holds only for the
1286
- content it was asked of (a new run or other content forgets it); events `findRequested`
1287
- (only while taken, with the page's focus in the frame) and `findUpdated` (only while a query is
1288
- shown), checked and rate-limited through the bridge. React: `onFindRequested`, `onFindUpdated`,
1289
- and the handle's `find` and `clearFind`.
1290
- - **Trust.** The page reads every query; what it says back is a find bar's numbers. Tests:
1291
- `test/find.test.ts` (the matching and its limits, the shortcut rule, the checks, the shell's
1292
- splice and built-ins, only the latest query, `createHost`'s requests, answers, forgetting and
1293
- gates, the React handle's scope); `leak/find.spec.ts`
1294
- on three engines (highlights, next and previous into view, a scrolling box, a change found again,
1295
- the shortcut the host's only while taken and the page's own find keeping it, and a hostile page's
1296
- `requested` while the person types in the host's composer dropped: `find-requested-focus`).
1180
+ capped?, rect? }`, or `"unsupported"` (no `find`, an older shell's `-32601`, a malformed answer,
1181
+ no answer within `FIND_LIMITS.timeoutMs`, a query superseded: the shell searches only a burst's
1182
+ latest, `FIND_LATEST`); `clear()`; `takeShortcut(take)`. A query holds only for the content it was
1183
+ asked of (a new run or other content forgets it). Events `findRequested` (only while taken, with
1184
+ the page's focus in the frame) and `findUpdated` (only while a query is shown), checked and
1185
+ rate-limited through the bridge. React: `onFindRequested`, `onFindUpdated`, the handle's `find`
1186
+ and `clearFind`.
1187
+ - **Trust and tests.** The page reads every query; what it says back is a find bar's numbers.
1188
+ `test/find.test.ts`: matching and its limits, the shortcut rule, the checks, the shell's splice
1189
+ and built-ins, only the latest query, `createHost`'s requests, answers, forgetting and gates, the
1190
+ React handle's scope. `leak/find.spec.ts` on three engines: highlights, next and previous into
1191
+ view, a scrolling box, a change found again, the shortcut the host's only while taken and the
1192
+ page's own find keeping it, and a hostile page's `requested` while the person types in the host's
1193
+ composer dropped (`find-requested-focus`).
1297
1194
 
1298
1195
  ## The shell runtime
1299
1196
 
1300
- The runtime (`src/shell/runtime.ts`, plain ES2020, no build) runs first in every
1301
- frame it serves. Before any content: an in-memory `localStorage` (opaque frames), the
1302
- WebRTC removal (item 3), the frame and hint guards (items 4, 8: the observer, the
1303
- wrapped `attachShadow`, the synchronous insertion and attribute guards), and the
1304
- closed parser entry points (P029). Then, when it speaks for the content: the
1305
- handshake, the theme (P028), content drawn inert while partial and run once when
1306
- whole (a fragment parsed in a template, its scripts recreated in order; a document
1307
- parsed with `DOMParser` and imported, its scripts recreated in order, then
1308
- `DOMContentLoaded` and `load`), size and error reports, and link clicks sent out
1309
- through `openLink`. A view that speaks for itself (`protocol: "none"`, MCP Apps) is
1310
- rendered the same way from the plan, once the shell's document has loaded.
1197
+ The runtime (`src/shell/runtime.ts`, plain ES2020, no build) runs first in every frame it serves.
1198
+ Before any content: an in-memory `localStorage` (opaque frames), the WebRTC removal (item 3), the
1199
+ frame and hint guards (items 4, 8: the observer, the wrapped `attachShadow`, the synchronous
1200
+ insertion and attribute guards), and the closed parser entry points (P029). Then, when it speaks for
1201
+ the content: the handshake, the theme (P028), the content (§ Streaming), size and error reports,
1202
+ link clicks sent out through `openLink`. A view that speaks for itself (`protocol: "none"`, MCP
1203
+ Apps) is rendered the same way from the plan once the shell's document has loaded.
1311
1204
 
1312
1205
  ## Streaming
1313
1206
 
1314
- Agents write a widget's code over seconds, so the shell renders it as it grows
1315
- (PRINCIPLE 10 — the manual tells the agent to order it styles → markup →
1316
- scripts). While the code is incomplete the shell draws the **markup inert**: it
1317
- parses in a `<template>`, removes anything that runs or navigates (`script`,
1318
- frames, `on*` handlers, `javascript:` URLs) and changes only what changed, so an
1319
- image does not reload and an animation does not restart. When the code is
1320
- complete the shell drops the draft and renders once, running scripts in order
1321
- (external ones awaited). Partial input never runs code. The adapter carries this
1322
- as MCP Apps `tool-input-partial` (0..n) then `tool-input` (once). A leak-suite
1323
- test asserts: markup appears as it streams, no script or handler runs until the
1324
- code is whole, then runs exactly once.
1207
+ Agents write a widget over seconds, so the shell renders it as it grows (PRINCIPLE 10; the manual
1208
+ tells the agent to order it styles → markup → scripts). While incomplete, the **markup is drawn
1209
+ inert**: parsed in a `<template>`, stripped of what runs or navigates (`script`, frames, `on*`
1210
+ handlers, `javascript:` URLs), changing only what changed, so an image doesn't reload and an
1211
+ animation doesn't restart. When complete, the draft is dropped and the content runs once: a fragment
1212
+ parsed in a template, or a document parsed with `DOMParser` and imported (then `DOMContentLoaded`
1213
+ and `load`), its scripts recreated in order, external ones awaited. Partial input never runs code.
1214
+ The adapter carries this as MCP Apps `tool-input-partial` (0..n) then `tool-input` (once). Tested by
1215
+ `11.streaming` (§ Behavior and gates).
1325
1216
 
1326
1217
  ## Theme and base styles
1327
1218
 
1328
- The theme vocabulary is the MCP Apps style variables (`--color-background-*`,
1329
- `--color-text-*`, `--color-border-*`, `--color-ring-*`, `--font-*`,
1330
- `--border-radius-*`, `--border-width-regular`, `--shadow-*`) plus Porthole's own
1331
- `--color-accent(-soft)` and chart palette (`--color-chart-1…8`, `-seq-1…7`,
1332
- `-neg/-mid/-pos`), each with a neutral light and dark default
1333
- (`src/theme/variables.ts`). A host supplies live values for the same names from
1334
- its own tokens (`HostOptions.theme`); `resolveTheme` takes a host value for each
1335
- declared name, the default otherwise, and drops undeclared names. The shell
1336
- applies them in place on a flip and fires the theme event; the host's values are
1337
- read two frames after the flip, so a host that restyles on its next frame is read
1338
- after it has (`refreshTheme()` reads them again, P043). A host drops a default it
1339
- doesn't want with `null` in a preset's theme. Its base styles set the body's type
1340
- and color from the variables; base styles for native form elements (buttons,
1341
- inputs) are the only further look Porthole adds, as plain CSS (P015). A whole
1342
- document (an artifact page) takes the person's scheme only when it declares it
1343
- supports both, `<meta name="color-scheme" content="light dark">`, or the host sets
1344
- `theme.documents: "always"`; otherwise it shows as its author styled it (P039).
1219
+ The vocabulary is the MCP Apps style variables (`--color-background-*`, `--color-text-*`,
1220
+ `--color-border-*`, `--color-ring-*`, `--font-*`, `--border-radius-*`, `--border-width-regular`,
1221
+ `--shadow-*`) plus Porthole's `--color-accent(-soft)` and chart palette (`--color-chart-1…8`,
1222
+ `-seq-1…7`, `-neg/-mid/-pos`), each with a neutral light and dark default
1223
+ (`src/theme/variables.ts`). A host supplies live values for the same names from its tokens
1224
+ (`HostOptions.theme`); `resolveTheme` takes the host's value per declared name, else the default,
1225
+ and drops undeclared names; `null` in a preset's theme drops a default. On a flip the shell applies
1226
+ them in place and fires the theme event; the host's values are read two frames after the flip, so a
1227
+ host restyling on its next frame is read after it has (`refreshTheme()` reads again, P043). Base
1228
+ styles set the body's type and color from the variables; base styles for native form elements
1229
+ (buttons, inputs) are the only further look Porthole adds, as plain CSS (P015). A whole document (an
1230
+ artifact page) takes the person's scheme only if it declares both, `<meta name="color-scheme"
1231
+ content="light dark">`, or the host sets `theme.documents: "always"`; otherwise it shows as its
1232
+ author styled it (P039).
1345
1233
 
1346
1234
  ## Guide generation
1347
1235
 
1348
- The manual and the tool description are generated from the same config, lazily,
1349
- so they cannot teach a variable the shell does not inject or a capability the CSP
1350
- blocks (PRINCIPLE 3, 10). Topics: `widget` (what to pass, where it runs, sizes that
1351
- read on a phone, what is not allowed, the network in prose from the CSP's origins,
1352
- the size limit, libraries when scripts may load, the color variables by group,
1353
- diagrams), `chart` (form, look, size, libraries or hand-drawn SVG, the chart
1354
- palette, marks, reading values), and `interactive` (one entry per declared
1355
- capability, with its gates in words, and how state behaves under the isolation
1356
- mode); a host adds its own topics (`guide.topics`) for its own tools. A sentence
1357
- that needs a variable the config doesn't declare, and an example that uses one, is
1358
- left out. The examples (`GUIDE_EXAMPLES`) use only the default theme and no
1359
- network; the leak suite renders each through the real sandbox at phone and desktop
1360
- widths in light and dark and asserts it reads (no overflow, text above a floor
1361
- size) — the guide's examples are themselves conformance cases.
1362
-
1363
- The `widget` topic's "The sandbox:" list states every limit that silently changes
1364
- how content behaves, each one line derived from the config (`manualLimits`, P064):
1236
+ The manual and tool description are generated lazily from the same config, so they can't teach a
1237
+ variable the shell doesn't inject or a capability the CSP blocks (PRINCIPLE 3, 10). Topics: `widget`
1238
+ (what to pass, where it runs, sizes that read on a phone, what isn't allowed, the network in prose
1239
+ from the CSP's origins, the size limit, libraries when scripts may load, the color variables by
1240
+ group, diagrams); `chart` (form, look, size, libraries or hand-drawn SVG, the chart palette, marks,
1241
+ reading values); `interactive` (one entry per declared capability, its gates in words, and how state
1242
+ behaves under the isolation mode); and the host's own (`guide.topics`) for its tools. A sentence
1243
+ needing an undeclared variable, and an example using one, is left out. The examples
1244
+ (`GUIDE_EXAMPLES`) use only the default theme and no network; the leak suite renders each in the
1245
+ real sandbox at phone and desktop widths, light and dark, and asserts it reads (no overflow, text
1246
+ above a floor size), so the guide's examples are conformance cases.
1247
+
1248
+ The `widget` topic's "The sandbox:" list states every limit that silently changes how content
1249
+ behaves, one line each, derived from the config (`manualLimits`, P064):
1365
1250
 
1366
1251
  | Limit | Says | Stated when | Checks (all three engines) |
1367
1252
  |-------|------|-------------|----------------------------|
@@ -1381,157 +1266,78 @@ how content behaves, each one line derived from the config (`manualLimits`, P064
1381
1266
  | `shell` | document.write/open throw; nested frames removed (with `nestedFrames: "own"`, P128: but `srcdoc` ones and frames of the page's own files); full screen and clipboard closed | always | `14.shell`, `4.document-write`, `4.light-dom`, `4.own-external` |
1382
1267
  | `storage` (interactive topic) | per isolation; in domain mode reads and writes can throw: try/catch | always | `14.storage`, `served.domain.storage-scope` |
1383
1268
 
1384
- Three more limits sit outside the list:
1385
- - `layout` (where it runs): a card whose height follows its content, or `layout.kind:
1386
- "fill"`, a frame as tall as its box with the page scrolling itself. Checks: `11.size`, `14.fill`.
1387
- - `theme` (where it runs): the person's theme, a page that declares it, or
1388
- `theme.documents: "never"`, always light. Checks: `11.theme-flip`, `11.document-theme`,
1269
+ Three more limits sit outside the list, config facts a whole-page viewer needed (P065):
1270
+ - `layout` (where it runs): a card whose height follows its content, or `layout.kind: "fill"`: every
1271
+ mount fills its container (`MountOptions.fill`, React `fill`), and the manual says the page fills
1272
+ the app's viewer (as tall as that, often smaller than the window), that `position: fixed` and
1273
+ `sticky` work, and to read the frame's own width, phone width first; it drops the card's height
1274
+ cap and the "no `position: fixed`" line. Checks: `11.size`, `14.fill`.
1275
+ - `theme` (where it runs): the person's theme, a page that declares it, or `theme.documents:
1276
+ "never"` (pages only): light values and a light `color-scheme`, untouched by a host flip, so no
1277
+ theme event. The manual says style it yourself and don't rely on `prefers-color-scheme`; measured
1278
+ with the person on dark, that query says light inside on WebKit and Firefox (they follow the frame
1279
+ element's `color-scheme`) and dark on Chromium. Checks: `11.theme-flip`, `11.document-theme`,
1389
1280
  `14.theme-never`.
1390
- - `errors` (interactive): `errors: "agent" | "host" | "none"`. Checks: `14.errors`, `14.error-shapes`.
1391
-
1392
- They are config facts a whole-page viewer needed (P065):
1393
- - `layout.kind: "fill"` makes every mount fill its container (`MountOptions.fill`, React
1394
- `fill`). The manual says the page fills the app's viewer (as tall as that, often smaller than
1395
- the window), that `position: fixed` and `sticky` work, and to read the frame's own width,
1396
- designing for the phone's width first; it drops the card's height cap and the "no
1397
- `position: fixed`" line (0.2.1: the viewer, not the window).
1398
- - `theme.documents: "never"` (pages only) gives the frame light values and a light
1399
- `color-scheme`. A host flip doesn't reach it, so it hears no theme event. The manual says
1400
- style it yourself, and not to rely on `prefers-color-scheme`. Measured with the person on
1401
- dark: inside, that query says light on WebKit and Firefox (they follow the frame element's
1402
- `color-scheme`) and dark on Chromium.
1403
- - `limits.maxBytes` is stated in KB or MB (`Keep it under 10 MB.`).
1404
- - `storage.scope` names what one display's storage is kept for ("this artifact, across its
1405
- versions"), without `storage.shared`'s prefix advice.
1406
- - `errors` says where the content's errors go: back to the agent, to the app only, or nowhere
1407
- (no `reportError`). Absent, the manual keeps its old "reported to the app".
1408
-
1409
- `test/limits.test.ts` fails if a limit names no check, names one no suite defines,
1410
- or the list holds a line that isn't a limit. Measured differences, each stated as
1411
- the behavior safe everywhere:
1412
- - submit events fire on WebKit only;
1413
- - `window.open` returns null on Chromium and WebKit and throws on Firefox;
1414
- - reading `navigator.serviceWorker` in an opaque frame throws on Chromium and
1415
- WebKit, and `register` rejects on Firefox;
1416
- - `play()` without a click is refused on Chromium and WebKit, and allowed by
1417
- Playwright's Firefox;
1418
- - Web Share is absent on all three desktop engines.
1419
-
1420
- On a page whose own policy closes blob: workers, `14.workers` reports itself
1281
+ - `errors` (interactive): `errors: "agent" | "host" | "none"`: back to the agent, to the app only,
1282
+ or nowhere (no `reportError`); absent, the manual says "reported to the app". Checks: `14.errors`,
1283
+ `14.error-shapes`.
1284
+
1285
+ The manual also states `limits.maxBytes` in KB or MB (`Keep it under 10 MB.`), and `storage.scope`
1286
+ names what one display's storage is kept for ("this artifact, across its versions"), without
1287
+ `storage.shared`'s prefix advice. `test/limits.test.ts` fails if a limit names no check, names one
1288
+ no suite defines, or the list holds a line that isn't a limit. Measured differences, each stated as
1289
+ the behavior safe everywhere: submit events fire on WebKit only; `window.open` returns null on
1290
+ Chromium and WebKit and throws on Firefox; reading `navigator.serviceWorker` in an opaque frame
1291
+ throws on Chromium and WebKit, and `register` rejects on Firefox; `play()` without a click is
1292
+ refused on Chromium and WebKit and allowed by Playwright's Firefox; Web Share is absent on all three
1293
+ desktop engines. On a page whose own policy closes blob: workers, `14.workers` reports itself
1421
1294
  inapplicable (P058).
1422
1295
 
1423
- ## MCP Apps adapter vs AppBridge
1424
-
1425
- The official SDK ships `AppBridge` (host side), which extends the MCP SDK's
1426
- `Protocol` class and pulls in the MCP client/core packages. **Decision: Porthole's
1427
- MCP adapter reimplements the thin host-side subset of MCP Apps that maps to
1428
- capabilities; it does not embed AppBridge** (P007), and no AppBridge-backed adapter
1429
- is offered for now (P014). On the **widget side** we reimplement nothing — authors
1430
- use the official `App` SDK, which is exactly the point of speaking the standard.
1431
- Upstream, once the code and tests exist (P018), we contribute what is general: the
1432
- conformance/leak runner, the container-agnostic framing note (a single hardened
1433
- frame instead of the mandated double-iframe, where equally secure), and the
1434
- shadow-root / document-rewrite frame-escape findings.
1435
-
1436
- ## Migration plan: the first host (Ferry)
1437
-
1438
- Ferry already has a working widget sandbox; it becomes Porthole's first user and
1439
- proves the API is general (PRINCIPLE 9). This section names Ferry only as that
1440
- first adopter. Every Ferry feature that shows agent-made or foreign HTML goes
1441
- through Porthole: widgets (inline widget), shown HTML files (artifact page), and
1442
- the dev-server preview pane (URL mode).
1443
-
1444
- **Moved into Porthole** (seeded from Ferry, renamed, wired from the config): the
1445
- shell (`widget-shell.ts`) → `src/shell/`; its CSP builder → `src/compile/policy.ts`
1446
- (now without `'self'`, its CDNs an opt-in, `LIBRARY_CDNS`); the embedding-page CSP
1447
- (`webAppCsp`) → `embedderCsp`; the theme map (`widget-theme.ts`) → the default
1448
- vocabulary and `resolveTheme` (Ferry's rUI token names become its `theme` function;
1449
- its chart palette is the default); the guide (`display-guide.ts`) →
1450
- `src/guide/` (its `file` topic stays Ferry's, as `guide.topics.file`); the frame
1451
- component (`WidgetFrame.tsx`) → the React binding (live-frame cap, heights).
1452
-
1453
- **Names that change** for content Ferry already shows: the theme event
1454
- `ferry:theme` → `config.theme.event` (Ferry may keep its name there, P024); the
1455
- error method `ferry/notifications/error` → `notifications/message` (level
1456
- `error`); the tool-input argument `widget_code` → `html` (Ferry maps its tool's
1457
- argument when it calls `setContent`); the root `#ferry-root` → `#porthole-root`.
1458
-
1459
- **Stays in Ferry** (product policy and plumbing): the `show_file`/`show_widget`/
1460
- `display_guide` MCP tools and their receipts/log entries; the daemon upload and
1461
- attachment storage; the session-log fold that decides where a display draws; the
1462
- `sendPrompt` send-permission rules (its dialog may stay its own, through
1463
- `confirm`); lazy-mount/live-frame numbers as config; the preview gateway and its
1464
- daemon streams (URL mode frames it); anything tied to Ferry's session model.
1465
-
1466
- **Ferry files that change:** `packages/core` drops the moved modules and depends
1467
- on `@botiverse/porthole`, re-exporting what its own tools need; `WidgetFrame.tsx`
1468
- becomes a thin wrapper over `@botiverse/porthole/react` supplying callbacks and
1469
- theme; `apps/server/src/http.ts`, `apps/web/vite.config.ts` and
1470
- `apps/desktop/src/main.ts` take the embedding-page CSP from `embedderCsp`;
1471
- `apps/daemon/src/crew/mcp.ts` builds its tool description and guide from the
1472
- Porthole config; the preview pane frames through the url preset; the native bridge
1473
- keeps carrying `@ferry/core`, which re-exports Porthole's shell. Ferry's display
1474
- decision entry gets a follow-up noting the extraction. The goal is Ferry's widget
1475
- code reduced to a config plus callbacks (OBJECTIVE 4, the dogfooding success
1476
- test).
1477
-
1478
1296
  ## The leak / conformance suite
1479
1297
 
1480
1298
  A Playwright suite (`@botiverse/porthole/conformance`) that:
1481
-
1482
- - drives a **platform host** (the web iframe host, and later others) through an
1483
- **adapter**, via a small host **test interface** (`ConformanceHost`: launch a
1484
- display in a fresh page; answer confirmations; read the calls that reached the
1485
- handlers and the errors; flip the theme) so the suite is not coupled to any one
1486
- host's DOM — aligned with the upstream conformance-interface effort so results
1487
- can feed it;
1488
- - is registered by the host in a spec file of its own (`leakTests(host)`,
1489
- `servedTests(host)`: one entry per probe, `test(each.title, ({ page, browserName },
1490
- info) => each.run({ page, browserName }, info))`), so its tests are located there
1491
- and selected by that file or a probe id; it runs on the host's own Playwright, which
1492
- Porthole doesn't declare (P041);
1493
- - runs every egress and escape probe in the table above, each attempting its
1494
- channel and asserting nothing leaves, using out-of-band oracles (`httpOracle`: a
1495
- local HTTP server that also counts TCP connections; `udpOracle`: a UDP listener
1496
- for STUN), each with its positive control;
1497
- - runs the MCP Apps examples unmodified and checks the lifecycle and interaction;
1498
- - renders the generated guide's examples and checks they read at the target
1499
- widths and themes.
1500
-
1501
- Porthole runs it against its own reference host (`leak/host/reference.ts`, the real
1502
- `createHost` in a page; `leak/reference-host.ts`, its `ConformanceHost`; served by
1503
- `leak/server.ts`, which serves the core's TypeScript stripped as Node does, with the
1504
- embedding CSP `embedderCsp` derives): `pnpm test:leak` runs Chromium, WebKit and
1505
- Firefox;
1506
- `PORTHOLE_LEAK_ENGINES=chromium` runs a subset where an engine's system libraries
1507
- are missing; `PORTHOLE_LEAK_WEAKEN=<control>[,<control>]` serves the core with
1508
- defenses taken out (P032; § The negative controls lists what each must fail).
1509
- `ConformanceHost.launch` called twice on one page shows two displays side by side
1510
- (`9.siblings`).
1299
+ - drives a **platform host** (the web iframe host, later others) through an **adapter** via a small
1300
+ **test interface** (`ConformanceHost`: launch a display in a fresh page; answer confirmations;
1301
+ read the calls that reached the handlers and the errors; flip the theme), coupled to no host's DOM
1302
+ and aligned with the upstream conformance-interface effort so results can feed it;
1303
+ - is registered by the host in a spec file of its own (`leakTests(host)`, `servedTests(host)`: one
1304
+ entry per probe, `test(each.title, ({ page, browserName }, info) => each.run({ page, browserName
1305
+ }, info))`), so its tests are located and selected there or by probe id; it runs on the host's own
1306
+ Playwright, which Porthole doesn't declare (P041);
1307
+ - runs every probe in the tables above with out-of-band oracles (`httpOracle`: a local HTTP server
1308
+ that also counts TCP connections; `udpOracle`: a UDP listener for STUN), each with its positive
1309
+ control;
1310
+ - runs the MCP Apps examples unmodified, checking lifecycle and interaction, and renders the guide's
1311
+ examples at the target widths and themes.
1312
+
1313
+ Porthole's reference host: `leak/host/reference.ts` (the real `createHost` in a page) and
1314
+ `leak/reference-host.ts` (its `ConformanceHost`), served by `leak/server.ts`, which strips the
1315
+ core's TypeScript as Node does and sends the embedding CSP `embedderCsp` derives. `pnpm test:leak`
1316
+ runs Chromium, WebKit and Firefox; `PORTHOLE_LEAK_ENGINES=chromium` a subset where an engine's
1317
+ system libraries are missing; `PORTHOLE_LEAK_WEAKEN=<control>[,<control>]` serves the core with
1318
+ defenses taken out (P032). `ConformanceHost.launch` twice on one page shows two displays side by
1319
+ side (`9.siblings`).
1511
1320
 
1512
1321
  ### The negative controls
1513
1322
 
1514
- Every control the suite has is in one registry (`leak/controls.ts`, P096): the specs it
1515
- is run with and the tests it must fail on each engine, each named exactly (a probe's
1516
- `[id]`, a served case's id, or a test's whole title). `pnpm --filter @botiverse/porthole
1517
- test:controls` (`scripts/controls.ts`; in CI, a job per engine) runs each of them and
1518
- requires its tests to fail by their verdicts, on every engine asked, and every other test
1519
- of its specs to pass. A probe's verdict is its deciding `expect`, whose message starts
1520
- `probe: ` (in the shipped probes and in the spec tests the registry names); a failure of
1521
- its setup or of a positive control is no failure of the wall. A run that didn't happen, an
1522
- engine missing from the report, a probe skipped, never run, timed out or failed by anything
1523
- but its verdict, or a test declared to fail (`test.fail`) that passes, fails the check. A
1524
- control that fails nothing on an engine says why: another wall holds, shown by a combined
1525
- control that takes both out and fails something there, or no probe can see the wall; one
1526
- that fails "every other test" takes out what all of them stand on (`nonce`: the shell),
1527
- and none of them may pass. No control runs `kit.spec.ts`: the kit's reference app runs
1528
- Porthole in Node, where no weakening reaches (`UNWEAKENED`). In CI a whole engine's controls
1529
- outlast a job, so each job runs one of four shards of the registry (`--shard k/4`, split by
1530
- measured weight, stable for a registry), and the `controls` job checks every shard's verdicts
1531
- (`--summary`): every control ran and held on every engine. The table is the registry's
1532
- (`node scripts/controls.ts --table` prints it; `test/controls.test.ts` holds them equal,
1533
- every weakening to a control, every control that fails nothing to its reason, and every
1534
- control the tables above name to the registry):
1323
+ Every control is in one registry (`leak/controls.ts`, P096): the specs it runs with and the tests it
1324
+ must fail on each engine, named exactly (a probe's `[id]`, a served case's id, or a test's whole
1325
+ title). `pnpm --filter @botiverse/porthole test:controls` (`scripts/controls.ts`; in CI, a job per
1326
+ engine) runs each one and requires its tests to fail by their verdicts on every engine asked, and
1327
+ every other test of its specs to pass. A probe's verdict is its deciding `expect`, whose message
1328
+ starts `probe: ` (in the shipped probes and in the spec tests the registry names); a failing setup
1329
+ or positive control is no failure of the wall. The check fails on a run that didn't happen, an
1330
+ engine missing from the report, a probe skipped, never run, timed out or failed by anything but its
1331
+ verdict, or a `test.fail` test that passes. A control that fails nothing on an engine says why:
1332
+ another wall holds (a combined control taking both out fails something there), or no probe can see
1333
+ the wall. One that fails "every other test" takes out what all stand on (`nonce`: the shell), and
1334
+ none may pass. No control runs `kit.spec.ts`: the kit's reference app runs Porthole in Node, where
1335
+ no weakening reaches (`UNWEAKENED`). A whole engine's controls outlast a CI job, so each job runs
1336
+ one of four shards (`--shard k/4`, split by measured weight, stable for a registry) and the
1337
+ `controls` job checks every shard's verdicts (`--summary`): every control ran and held on every
1338
+ engine. `node scripts/controls.ts --table` prints the table below; `test/controls.test.ts` holds it
1339
+ equal to the registry, every weakening to a control, every control that fails nothing to its reason,
1340
+ and every control the tables above name to the registry.
1535
1341
 
1536
1342
  | Control | Run with | Fails on every engine | Fails only on | Where it fails nothing, or may skip, why |
1537
1343
  |---------|----------|-----------------------|---------------|-----------------------------|
@@ -1581,7 +1387,7 @@ control the tables above name to the registry):
1581
1387
  | `follow-count` | `annotate.spec.ts` | `following: a host that gives no counts hears no follow-up after a scroll, as before markers` | — | — |
1582
1388
  | `draft-count` | `annotate.spec.ts` | `what the page reads of a draft (P107): that it is one, never its count; a posted mark as before` | — | — |
1583
1389
  | `draft-shell-checks` | `annotate.spec.ts` | `the shell's own checks on a raw show (P107): a draft draws no number, a kind it doesn't know is no mark` | — | — |
1584
- | `annotation-rect-clamp` | `annotate.spec.ts` | `a hostile page reports a box outside its frame: the host gets it clamped to the frame's viewport`, `marks: drawn over their anchors, one brought into view, an unfound one orphaned, all cleared`, `following: once a scroll settles, one report with only the marks that moved`, `every attached mark's place in the document comes with the scroll it was read at, offscreen ones too, and the followed mark's as the document scrolls (P132)`, `a selection's and a mark's last line come in the document's coordinates with the scroll, offscreen ones too; rect stays clamped (P133)` | — | — |
1390
+ | `annotation-rect-clamp` | `annotate.spec.ts` | `a hostile page reports a box outside its frame: the host gets it clamped to the frame's viewport`, `marks: drawn over their anchors, one brought into view, an unfound one orphaned, all cleared`, `following: once a scroll settles, one report with only the marks that moved`, `every attached mark's place in the document comes with the scroll it was read at, offscreen ones too, and the followed mark's as the document scrolls (P132)`, `a selection's and a mark's last line come in the document's coordinates with the scroll, offscreen ones too; rect stays clamped (P133)`, `an element pick says where it was clicked, in the document's coordinates with the scroll; a pick from the keyboard says no point (P150)` | — | — |
1585
1391
  | `authorize` | `served/authorize.spec.ts` | `a revoked subject's ticket opens nothing: a page and an app are denied, and the host is told`, `in a tab of its own, a revoked app and page are denied from the next request on`, `a framed page mid-session: its next load after revocation is denied where the engine keeps its cookie` | Chromium, Firefox: `a framed app mid-session: its next request after revocation is denied, and its next load tells the host` | — |
1586
1392
  | `url-permissions` | `served/permissions.spec.ts` | `a url-mode frame gets no clipboard writes or full screen unless the host delegates them` | — | — |
1587
1393
  | `navigate-guard` | `served/live.spec.ts`, `served/files.spec.ts`, `served/served.spec.ts`, `served/tab.spec.ts` | `served.domain.self-navigation`, `served.domain.tab-navigation`, `served.domain.tab-links`, `can't navigate itself away (location): to a site, or to another content origin`, `can't navigate itself away (replace): to a site, or to another content origin`, `can't navigate itself away (open-self): to a site, or to another content origin`, `can't navigate itself away (navigation-api): to a site, or to another content origin`, `a link to another page of the set opens it in the frame; the display goes on`, `a link to another page of the set opens it in the frame when the leaving page's notice is dropped (P098)`, `a link to another page of the set opens it in the frame when the leaving page's notice is late (P098)`, `without the Navigation API, a link to another page of the set opens it in the frame; the display goes on`, `a link down the page scrolls it; the document stays, and so does the display`, `without the Navigation API, a link down the page scrolls it; the document stays, and so does the display`, `a page opens nothing else: not a file that isn't a page, not another path of its origin`, `no report, content error or blocked navigation names the frame's sealed address (P083)` | — | — |
@@ -1624,46 +1430,3 @@ control the tables above name to the registry):
1624
1430
  | `blob-script,blob-trusted` | `served/runtime.spec.ts` | `a script asset runs as code only if an admin uploaded it where uploads are the admins'`, `scripts load from /_blob/ only where uploads are the admins' (a tab, its session)` | — | — |
1625
1431
  | `blob-inert` | `served/runtime.spec.ts` | `an asset opened on its own runs nothing, on a tab with the artifact's session` | — | — |
1626
1432
  | `find-requested-focus` | `find.spec.ts` | `a hostile page says the find shortcut was pressed while the person types in the host's composer: the host's find bar stays shut (P131)` | — | — |
1627
-
1628
- ## Milestones
1629
-
1630
- The core (this repository's lead work), in order; each lands when its tests pass:
1631
-
1632
- 1. **M1 — scaffold, config, compiler, presets, interfaces** (done). The workspace
1633
- and tooling; the config schema and validation; the compiler (CSP, sandbox and
1634
- `allow`, embedder CSP, shell plan and document, guide and tool description) with
1635
- the agreement test; the presets as configs; the public interfaces above as typed
1636
- stubs; the shell's wiring checked in real frames on Chromium and WebKit.
1637
- 2. **M2 — isolation core, shell runtime, egress hardening** (done). The web
1638
- platform host and transport, `createHost` mounting opaque, domain and url frames
1639
- (served frames checked by `checkFrameLocation`), the shell adapter and the bridge,
1640
- the reference host and `defineLeakSuite`, items 1–10 above each with its probes,
1641
- positive controls and negative controls, green on Chromium and WebKit; the
1642
- official App SDK connecting under every preset.
1643
- 3. **M3 — streaming, auto-size, theming, the gated bridge** (done). Streaming
1644
- drafts through the host API, size reporting under the limits, theme apply and
1645
- flip with the host's live values, base styles for native form elements, and the
1646
- host-function bridge's gates, each proven in real frames (items 11, 12) with
1647
- negative controls, and in unit tests (`test/bridge.test.ts`,
1648
- `test/shell-adapter.test.ts`).
1649
- 4. **M4 — the React binding and its default confirmation dialog** (done).
1650
- `<PortholeProvider>`, `<PortholeFrame>`, `ConfirmDialog`: streaming through props,
1651
- height memory per display, the live-frame cap with "Run again", theme flips,
1652
- navigation recovery, generations, and the default, replaceable dialog, each
1653
- proven in a real browser.
1654
- 5. **M5 — Firefox** in the gate (done): every Playwright suite (leak, served, MCP
1655
- examples, React) runs on Chromium, WebKit and Firefox, and every negative control
1656
- was run on Firefox; its differences are recorded in P035.
1657
-
1658
- In parallel, against the interfaces: the **MCP Apps adapter** (`/mcp`, running the
1659
- official ext-apps examples unmodified); the **served modes** (domain mode, `/server`,
1660
- the artifact page served, the MCP Apps sandbox proxy, URL mode); and the **Ferry
1661
- migration**.
1662
-
1663
- ## Open questions
1664
-
1665
- 1. ~~URL mode's sandbox tokens~~: popups, modals and downloads are a host's
1666
- opt-in (P037); clipboard writes and full screen too (P049).
1667
- 2. ~~`'self'` in the embedding page's `frame-src`~~: measured and dropped (P033).
1668
- 3. ~~Clipboard writes from agent-written content~~: closed (P051); copy buttons go
1669
- through the host (`copyText`, P052).