@botiverse/porthole 0.2.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +14 -9
  2. package/dist/check/check.d.ts +83 -0
  3. package/dist/check/check.js +169 -0
  4. package/dist/check/drivers.d.ts +24 -0
  5. package/dist/check/drivers.js +110 -0
  6. package/dist/check/index.d.ts +8 -0
  7. package/dist/check/index.js +8 -0
  8. package/dist/check/lint.d.ts +21 -0
  9. package/dist/check/lint.js +131 -0
  10. package/dist/check/page-source.d.ts +2 -0
  11. package/dist/check/page-source.js +2 -0
  12. package/dist/check/page.d.ts +51 -0
  13. package/dist/check/page.js +150 -0
  14. package/dist/check/tools.d.ts +61 -0
  15. package/dist/check/tools.js +140 -0
  16. package/dist/conformance/host-kit.d.ts +10 -2
  17. package/dist/conformance/host-kit.js +9 -2
  18. package/dist/displays/displays.d.ts +61 -0
  19. package/dist/displays/displays.js +113 -0
  20. package/dist/host/client.d.ts +92 -0
  21. package/dist/host/client.js +259 -0
  22. package/dist/index.d.ts +4 -0
  23. package/dist/index.js +6 -0
  24. package/dist/node/index.d.ts +22 -1
  25. package/dist/node/index.js +46 -1
  26. package/dist/react/frame.d.ts +71 -3
  27. package/dist/react/frame.js +120 -19
  28. package/dist/react/index.d.ts +1 -0
  29. package/dist/react/index.js +1 -0
  30. package/dist/react/view.d.ts +54 -0
  31. package/dist/react/view.js +146 -0
  32. package/dist/server/bootstrap.d.ts +27 -0
  33. package/dist/server/bootstrap.js +63 -0
  34. package/dist/server/host.d.ts +74 -7
  35. package/dist/server/host.js +237 -9
  36. package/dist/server/index.d.ts +4 -2
  37. package/dist/server/index.js +3 -1
  38. package/dist/server/pages.d.ts +19 -0
  39. package/dist/server/pages.js +8 -0
  40. package/dist/server/proxy.d.ts +24 -0
  41. package/dist/server/proxy.js +67 -0
  42. package/dist/server/server.js +14 -1
  43. package/dist/server/types.d.ts +8 -0
  44. package/docs/ADOPTING.md +356 -0
  45. package/docs/DECISIONS.md +146 -0
  46. package/docs/DESIGN.md +58 -0
  47. package/examples/app.mjs +62 -64
  48. package/examples/conformance/page.spec.mjs +23 -0
  49. package/examples/conformance/playwright.config.mjs +1 -1
  50. package/examples/conformance/porthole.spec.mjs +5 -3
  51. package/examples/displays.mjs +19 -0
  52. package/examples/mcp/server.mjs +121 -0
  53. package/package.json +9 -1
  54. package/src/check/check.ts +278 -0
  55. package/src/check/drivers.ts +144 -0
  56. package/src/check/index.ts +15 -0
  57. package/src/check/lint.ts +238 -0
  58. package/src/check/page-source.ts +19 -0
  59. package/src/check/page.ts +204 -0
  60. package/src/check/tools.ts +206 -0
  61. package/src/conformance/host-kit.ts +20 -11
  62. package/src/displays/displays.ts +191 -0
  63. package/src/host/client.ts +364 -0
  64. package/src/index.ts +25 -0
  65. package/src/node/index.ts +66 -2
  66. package/src/react/frame.tsx +191 -33
  67. package/src/react/index.ts +8 -0
  68. package/src/react/view.tsx +232 -0
  69. package/src/server/bootstrap.ts +97 -0
  70. package/src/server/host.ts +331 -15
  71. package/src/server/index.ts +11 -1
  72. package/src/server/pages.ts +28 -0
  73. package/src/server/proxy.ts +86 -0
  74. package/src/server/server.ts +26 -2
  75. package/src/server/types.ts +5 -0
@@ -0,0 +1,356 @@
1
+ # Adopting Porthole
2
+
3
+ How to put Porthole in an app, from the npm package alone. The package's `examples/` is a whole
4
+ app that does everything below: `examples/app.mjs` is the app, runtime-agnostic;
5
+ `examples/node/server.mjs` and `examples/workers/` run it; `examples/mcp/server.mjs` gives the
6
+ agent its tools. DESIGN.md says how it works and DECISIONS.md why (the P-numbers the code cites).
7
+
8
+ ## 1. Choose how content is shown
9
+
10
+ | | Opaque | Served |
11
+ | --- | --- | --- |
12
+ | Where it runs | A sandboxed frame in your page, origin `null` | A frame on an origin of its own (`a-<id>.example-usercontent.com`) |
13
+ | Server side | None | The host kit (`createContentHost`) |
14
+ | Storage, clean address, open in a tab | No | Yes |
15
+ | Typical | Widgets in a conversation | Stored pages, artifacts, a viewer |
16
+
17
+ Start opaque if you can; add served pages when content needs storage or an address. A served app
18
+ keeps the opaque config as its fallback for when the content domain is down.
19
+
20
+ ## 2. Say your display kinds once
21
+
22
+ ```js
23
+ // displays.mjs: imported by the server, the page and the agent's tools
24
+ import { defineDisplays } from "@botiverse/porthole";
25
+
26
+ export const displays = defineDisplays({
27
+ widget: { preset: "inlineWidget", options: { capabilities: { sendPrompt: {}, copyText: {} } } },
28
+ artifact: { preset: "artifact", options: { layout: { kind: "fill" } } }, // a whole-page viewer
29
+ preview: { preset: "url" }, // a running app: served only
30
+ });
31
+ ```
32
+
33
+ `displays.opaque(kind)`, `displays.served(contentSource)`, `displays.configFor(instance, source)`,
34
+ `displays.frameSources(source, { authorizeUrl })` (a CSP built without a server: a dev server, a
35
+ desktop shell) and `displays.guideConfig(kind, "served" | "opaque")` (the agent's manual) all come
36
+ from it. A kind's name is the preset name its documents carry: a stored page names `artifact`
37
+ unless its `document.preset` says otherwise.
38
+
39
+ **Fill:** a whole-page viewer says `layout: { kind: "fill" }`. The frame fills its box, and the
40
+ manual tells the agent so (the page scrolls itself; `position: fixed` works). `MountOptions.fill`
41
+ and `<PortholeFrame fill>` are deprecated: they size the frame but leave the manual saying the
42
+ height follows the content.
43
+
44
+ ## 3. Opaque displays: the page only
45
+
46
+ ```js
47
+ import { createHost } from "@botiverse/porthole";
48
+
49
+ const host = createHost(displays.opaque("widget"), {
50
+ handlers: { sendPrompt: ({ text }) => send(text) },
51
+ // A gated call asks the person first, with the call's whole effect.
52
+ confirm: async (request) => window.confirm(`${request.capability}: ${JSON.stringify(request.args)}?`),
53
+ });
54
+ const display = host.mount(box, { displayId: "w1", title: "A chart", scheme: "light" });
55
+ display.setContent(agentHtml, { partial: true }); // while it streams: drawn inert
56
+ display.setContent(agentHtml); // once whole: it runs, once
57
+ display.on("contentError", ({ message }) => tellTheAgent(message));
58
+ ```
59
+
60
+ React: `<PortholeProvider>` near the root; `<PortholeFrame config displayId title content partial />`
61
+ per display. The provider takes what every frame shares: `scheme`, `theme` (and `themeKey`;
62
+ `cssVariableTheme(tokens)` reads the values from your page's CSS variables), `nonce` (`"auto"`
63
+ reads the page's), `handlers`, `openLink` (default: a new tab), `notify` (your own toast for what
64
+ a copy button copied), and `renderConfirm` (your own dialog: Porthole keeps the queue, runs your
65
+ yes inside its click, and counts declines). `useRunAgain()` gives a "run again" button.
66
+
67
+ ## 4. Served pages: the host kit
68
+
69
+ ### Local development
70
+
71
+ Run the app and the content domain on one server: app `http://localhost:8790`, content domain
72
+ `content.localhost:8790` (pages at `http://a-<id>.content.localhost:8790`). Browsers resolve every
73
+ `*.localhost` name to loopback, and each is a site of its own, so the app and its content never
74
+ share cookies or storage. `http` is allowed only on loopback; everything else is `https`.
75
+
76
+ In production the content domain is a registrable domain your app uses for nothing else
77
+ (`example-usercontent.com`), with wildcard DNS and a wildcard certificate pointing at the same
78
+ app. Porthole refuses one that holds or may share a site with an app origin (`ContentDomainError`).
79
+ Put it on the Public Suffix List when you can, so its labels are sites of their own.
80
+
81
+ ### The server
82
+
83
+ ```js
84
+ import { createContentHost, prefixedName, memoryTicketStore } from "@botiverse/porthole/server";
85
+ import { displays } from "./displays.mjs";
86
+
87
+ const APP = "http://localhost:8790";
88
+ const content = createContentHost({
89
+ domain: "content.localhost:8790", // "" turns content off
90
+ appOrigins: [APP],
91
+ secret: process.env.PORTHOLE_SECRET, // npx porthole secret
92
+ tickets: memoryTicketStore(), // one process; d1TicketStore(env.DB) on Workers
93
+ displays,
94
+ name: prefixedName("a-"), // page "abc" is served on a-abc.<domain>
95
+ instance: (proposal) => myInstance(proposal), // what a frame request asks for, as you mean it
96
+ access: async (instance, viewer) => ((await mayView(viewer, instance)) ? { viewer: viewer.id } : null),
97
+ source: (id, version) => myStore.page(id, version), // { html } | null
98
+ entry: { // clean addresses: a-abc.<domain>/ in a new tab
99
+ at: (scope, path) => instanceAt(scope, path), // null: nothing there (a 404 on the content domain)
100
+ pathOf: (instance) => pathOf(instance), // the reverse: frames come with their link
101
+ signIn: (returnTo) => Response.redirect(`${APP}/login?next=${encodeURIComponent(returnTo)}`, 303),
102
+ },
103
+ });
104
+
105
+ // One mount, under /porthole: POST frames, GET authorize, GET meta, POST/DELETE handoff.
106
+ const routes = content.routes(viewerOf);
107
+ // Every request: the content domain first, then Porthole's routes, then your app.
108
+ const answer = (await content.fetch(request)) ?? (await routes(request)) ?? (await app(request));
109
+ ```
110
+
111
+ - **`instance`** gets the client's proposal (`{ scope, document }`) and returns the instance as
112
+ your app means it, or null. Derive the scope (the origin) from what it names: the client never
113
+ chooses an origin. **`access`** returns a grant (`{ viewer }`, or `{ anonymous: true }` for a
114
+ public page) or null; `authorize` (optional) checks again on every request after, and
115
+ `content.forget({ scope, subject })` drops its cached answers when you revoke.
116
+ - **`viewerOf(request)`** is your app's own: who is signed in, from its cookie or token, or null.
117
+ - **`Response.redirect` needs an absolute URL** outside a browser (Node throws on `/login`).
118
+ - **`reserved`** is only for labels your app itself serves on the content domain (previews of a
119
+ dev server, `p-*`). Labels nothing serves need nothing: they are a 404 there.
120
+ - **Node:** `nodeServer({ content, app: (request) => answer(request) }).listen(8790)` is the whole
121
+ server, WebSockets included, the health gate started on listen. **Workers:**
122
+ `contentHostFor((env) => options)` makes one host per `env`, and answers a plain 503 naming the
123
+ problem when the settings can't be served.
124
+ - **Health:** `health: { probe: nodeProbe(), onServedChange: (served) => … }` checks the content
125
+ domain over the real network and falls back to opaque frames while it doesn't answer.
126
+
127
+ ### The page
128
+
129
+ ```js
130
+ import { createHost, frameFallback, portholeClient } from "@botiverse/porthole";
131
+ import { displays } from "./displays.mjs";
132
+
133
+ const porthole = portholeClient({ displays }); // the server's /porthole routes
134
+ const meta = await porthole.refresh(); // { served, contentSource, frameSources }
135
+ const display = createHost(porthole.config("artifact"), { locator: porthole })
136
+ .mount(box, { displayId: id, title, scheme: "light", ...(meta?.served ? { instance } : {}) });
137
+ if (!meta?.served) display.setContent(opaqueCopy); // frames not served now: the page, opaque
138
+ display.on("outcome", (outcome) => {
139
+ const fallback = frameFallback(outcome); // null when it loaded
140
+ if (fallback !== null) offer(fallback.title, fallback.message); // "Open this in a new tab", …
141
+ });
142
+ openButton.onclick = () => porthole.openInTab(instance); // the clean address
143
+ ```
144
+
145
+ `porthole.config(kind)` is the served config while frames are served, the opaque one while they
146
+ aren't, and null until the meta is known, so a frame never starts opaque and then restarts
147
+ served. A client module that fails to load shows nothing at all: catch its import and say so
148
+ (`examples/app.mjs` does).
149
+
150
+ React: give the provider the client, and show a kind:
151
+
152
+ ```jsx
153
+ <PortholeProvider client={porthole} scheme={mode} theme={cssVariableTheme(TOKENS)} nonce="auto">
154
+ <PortholeView display="artifact" instance={instance} content={opaqueCopy}
155
+ fallback={({ title, message, link, retry }) => <Fallback {...{ title, message, link, retry }} />} />
156
+ </PortholeProvider>
157
+ // const { link, open, copy } = usePortholeLink(instance); "Open in a new tab", "Copy link"
158
+ ```
159
+
160
+ ### The page's CSP
161
+
162
+ - `frame-src`: `content.frameSources` (the content origins, and the authorize route), also in
163
+ `GET /porthole/meta`; `displays.frameSources(source, { authorizeUrl })` without a server.
164
+ - **An opaque display inherits your page's CSP.** Its own policy then narrows it, never widens it.
165
+ If your page sets `default-src`, also allow what agent content uses inline:
166
+ `img-src data: blob:`, `media-src data: blob:`, `font-src data:`, `style-src 'unsafe-inline'`,
167
+ `worker-src blob:`. A nonce-based `script-src` works: give `createHost` the nonce
168
+ (`HostOptions.nonce`) and the shell runs content's scripts under it.
169
+
170
+ ### Sign-in
171
+
172
+ - Your sign-in page gets the authorize URL as `next`, and goes back to it when signed in. Check
173
+ it with `entryTarget(next, authorizeUrl)` (or `porthole.entryTarget(next)`): only your own
174
+ authorize route, never another site.
175
+ - **Warning: no `form-action 'self'` on a sign-in page that posts a form.** `form-action` holds
176
+ every redirect of a submission, and redirect entry continues from your sign-in through the
177
+ content origin, so the browser blocks the last hop and the person stays on your sign-in. Leave
178
+ `form-action` out of that page's CSP, or add the content source.
179
+ - **A page that authenticates with a token** (a single-page app holding a bearer token, a desktop
180
+ app) has no cookie for the authorize route to know the viewer by. Use the viewer handoff:
181
+ `entry.handoff: { id: (viewer) => viewer.id, viewer: (id) => lookUp(id) }` on the server, and
182
+ `portholeClient({ displays, headers: () => ({ authorization: `Bearer ${token()}` }), handoff: true })`
183
+ on the page. It posts to `/porthole/handoff` with your own credential, on load and when the
184
+ page regains focus; Porthole answers with a cookie that holds a key it signs (the viewer's id
185
+ and ten minutes), `HttpOnly`, scoped to `/porthole`. That beats storing the app's token in a
186
+ cookie: the key isn't a credential for your API, goes nowhere but Porthole's routes, can't be
187
+ set from another site (the POST needs your credential, and is refused from another origin), and
188
+ expires in ten minutes (an expired one costs only a quiet trip through your sign-in route).
189
+ `entry.spa: { route: "/sign-in" }` sends a signed-out person to your app's route with `next`.
190
+
191
+ ### Url mode: a relay of your own
192
+
193
+ `proxyTo` relays a url-mode app by HTTP. A relay of your own (over your own transport) uses the
194
+ same parts: `upstreamHeaders.request(headers, { origin, target, websocket })` and
195
+ `.response(...)` (the header rewrite, Porthole's cookies kept out), `statusPage({ status, title,
196
+ detail, reason, hostOrigins })` (a page that tells the frame's host why it shows nothing, desktop
197
+ schemes included), and `nodeHost`'s `appSocket` (a WebSocket, Porthole's cookies already removed).
198
+
199
+ ## 5. Cloudflare Workers
200
+
201
+ ```js
202
+ import { contentHostFor, d1TicketStore } from "@botiverse/porthole/server";
203
+
204
+ const porthole = contentHostFor((env) => ({ domain: env.CONTENT_DOMAIN, appOrigins: [env.APP_ORIGIN],
205
+ secret: env.PORTHOLE_SECRET, tickets: d1TicketStore(env.DB), displays, /* your policy */ }));
206
+ export default {
207
+ async fetch(request, env) {
208
+ return (await porthole.fetch(request, env)) ??
209
+ (await porthole.routes(request, env, viewerOf)) ?? app.fetch(request, env);
210
+ },
211
+ };
212
+ ```
213
+
214
+ - **Tickets in D1** (never KV, which is eventually consistent):
215
+ `npx porthole d1-schema > migrations/0001_porthole_tickets.sql`, then
216
+ `wrangler d1 migrations apply <db>`.
217
+ - **One secret, `PORTHOLE_SECRET`:** `npx porthole secret`, then `wrangler secret put
218
+ PORTHOLE_SECRET` (`.dev.vars` locally). At least 32 bytes; it signs tickets, cookies, entry
219
+ codes and handoffs.
220
+ - **Static assets:** set `"assets": { "run_worker_first": true }`. Otherwise Workers serves your
221
+ static files before the Worker runs, on every host, content origins included.
222
+ - No `nodejs_compat` needed. `wrangler dev` passes the Host through, so
223
+ `*.content.localhost:<port>` works locally.
224
+
225
+ ## 6. The agent's side
226
+
227
+ ### Its tools
228
+
229
+ ```js
230
+ import { admitContent, answerGuide, checkTool, guideTool, showTool } from "@botiverse/porthole";
231
+
232
+ const config = displays.guideConfig("artifact", "served");
233
+ const tools = [showTool(config), guideTool(config), checkTool(config)]; // { name, description, inputSchema }
234
+ // show: const admitted = admitContent(config, args.html); // refuses only what certainly fails
235
+ // admitted.ok ? show(admitted.content) + admitted.note : refuse(admitted.refusal)
236
+ // guide: answerGuide(config, args) // { text } or { error }
237
+ ```
238
+
239
+ Names come from the config (`guide.toolName`, `guide.guideToolName`); the descriptions are the
240
+ manual's own words. `examples/mcp/server.mjs` wires all three as an MCP server.
241
+
242
+ - **`admitContent`** runs `lintContent` and refuses (by default, `refuseOn: "error"`) only what
243
+ would certainly fail or be cut: over the size limit, a document with no body where a fragment
244
+ goes, nested frames, `document.write`. Its refusal says exactly what to change. Everything else
245
+ (hosts outside egress, unpinned libraries, `alert`, forms, the clipboard…) comes back as
246
+ warnings with the result. `refuseOn: "never"` only warns.
247
+ - **`guideChanges(from, to)`** is the notice for the agent when a kind flips between served and
248
+ opaque (null when its manual reads the same).
249
+ - **`errors: "agent"`** sends what content throws (and what the sandbox blocks) back to the agent
250
+ once people see it: listen for `contentError` and pass it on.
251
+
252
+ ### Checking a page before people see it
253
+
254
+ `checkPage` (`@botiverse/porthole/check`) runs the content in the real sandbox at the manual's
255
+ phone and desktop widths, in light and dark, and answers a report whose `text` is a few lines for
256
+ the agent: what it threw, what the sandbox blocked, what failed to load, `console.error`, overflow
257
+ and a cut height, each problem once with where it happened (at most 8; the rest counted).
258
+
259
+ ```js
260
+ import { checkPage, playwrightDriver } from "@botiverse/porthole/check";
261
+ const report = await checkPage({ config, content: html, driver: playwrightDriver(browser) });
262
+ report.ok; report.text;
263
+ ```
264
+
265
+ It needs a browser somewhere: Chromium is best (WebKit mutes a thrown error's message in an
266
+ opaque frame, so the agent reads only "Script error."). Where:
267
+
268
+ - **A server with Chromium** (Node): `playwrightDriver(await chromium.launch())`.
269
+ - **An agent on a person's machine, maybe without Chromium** (Ferry's daemon): run
270
+ `lintContent` there (no browser needed), and send `check_page` to your server, which runs
271
+ `checkPage`; or use Playwright where it is installed (`examples/mcp/server.mjs` falls back to
272
+ the lint, saying so).
273
+ - **Cloudflare Workers:** Browser Rendering, through a CDP session:
274
+
275
+ ```js
276
+ import puppeteer from "@cloudflare/puppeteer";
277
+ import { cdpDriver, checkPage } from "@botiverse/porthole/check";
278
+ import page from "@botiverse/porthole/check/page"; // the check page's script, bundled
279
+ const browser = await puppeteer.launch(env.BROWSER);
280
+ const tab = await browser.newPage();
281
+ const report = await checkPage({ config, content, page, driver: cdpDriver(() => tab.createCDPSession()) });
282
+ await browser.close();
283
+ ```
284
+
285
+ ## 7. Conformance: prove your integration
286
+
287
+ `@botiverse/porthole/conformance` runs Porthole's suite (egress and escape probes, the served
288
+ cases, redirect entry) against your app's real page, its CSP and session, in Playwright:
289
+
290
+ ```js
291
+ // playwright.config.mjs
292
+ import { defineConfig, devices } from "@playwright/test";
293
+ import { conformanceProjects } from "@botiverse/porthole/conformance";
294
+ export default defineConfig({ projects: conformanceProjects(devices), webServer: { … } });
295
+
296
+ // porthole.spec.mjs
297
+ import { test } from "@playwright/test";
298
+ import { defineHostConformance } from "@botiverse/porthole/conformance";
299
+ defineHostConformance(test, {
300
+ name: "my-app",
301
+ open: async (page) => { /* sign in, open the page that shows content */ },
302
+ issue: { url: "/porthole/frames" },
303
+ displays, contentSource: "http://*.content.localhost:8790",
304
+ instances: { artifact: (scope, version) => ({ scope, document: { kind: "artifact", id: "conformance", version } }) },
305
+ entry: { url: (scope) => `http://a-t-${scope}.content.localhost:8790/v/1`, unknown: "derive" },
306
+ });
307
+ ```
308
+
309
+ What the runner asks of your app, and what it skips without:
310
+
311
+ | Option | It needs | Without it |
312
+ | --- | --- | --- |
313
+ | `instances.artifact(scope, version)` | versions `"1"` and `"2"` of one stored page on `scope`'s origin, each exactly `conformancePage(version)` | the stored-page case |
314
+ | `instances.shell(scope)` | a served shell | the domain cases run on `artifact(scope, "1")` |
315
+ | `instances.app`, `.proxy` | a url-mode app, the MCP Apps proxy | their cases |
316
+ | `entry.url(scope)` | the clean address of `artifact(scope, "1")` | the redirect entry cases |
317
+ | `entry.denied`, `atSignIn`, `completeSignIn` | a page the viewer may not see; your sign-in page | that case; the sign-in is judged by leaving the content origin, and not completed |
318
+ | `entry.unknown` | addresses that name nothing, or `"derive"` | that case |
319
+
320
+ The suite names its own scopes, so an app serves them through a **test mode**
321
+ (`examples/app.mjs`: `PORTHOLE_CONFORMANCE=1`): the test page under `t-<scope>`, and a private
322
+ page. **Never ship test mode**: with it, anyone signed in can make content origins of their
323
+ choosing. `onDemand(make)` memoizes fixtures made the first time a case asks (a page published
324
+ on demand); `instances` and `entry.url` may be async. The tests are located at your
325
+ `defineHostConformance` call, so `playwright test porthole.spec.mjs` selects them.
326
+
327
+ The leak probes run opaque displays on your page: where its own CSP closes what a probe needs,
328
+ the probe reports itself inapplicable, saying which directive. Those are facts about your page's
329
+ opaque fallback, not failures.
330
+
331
+ ## 8. Expected, and how to tell
332
+
333
+ - Chromium logs `Unrecognized Content-Security-Policy directive 'webrtc'` for every frame: the
334
+ directive closes WebRTC where an engine knows it, and is ignored where it doesn't.
335
+ - Content's CSP allows `'unsafe-eval'`. Content is the agent's own script already
336
+ (`'unsafe-inline'`), so eval adds no capability, and libraries content uses compile with it
337
+ (Vue's in-browser build, Alpine.js, Vega's expressions, WebAssembly). Egress, the sandbox and the
338
+ origin are what isolate it (P071).
339
+ - On `http` loopback the session cookies are `porthole-<key>`; on `https`, `__Host-porthole-<key>`.
340
+ - A clean address that names nothing (a label the naming never makes, the bare domain, a path
341
+ `entry.at` says has nothing) is a 404 on the content domain: it never reaches your sign-in.
342
+ - Host errors name the content origin and leave out ticket URLs.
343
+
344
+ ## 9. Reference
345
+
346
+ | Import | What |
347
+ | --- | --- |
348
+ | `@botiverse/porthole` | `createHost`, `presets`, `defineDisplays`, `portholeClient`, `frameFallback`, `entryTarget`, `lintContent`, `admitContent`, `showTool`, `guideTool`, `checkTool`, `answerGuide`, `guideChanges`, `compile` |
349
+ | `@botiverse/porthole/react` | `PortholeProvider`, `PortholeFrame`, `PortholeView`, `usePortholeLink`, `cssVariableTheme`, `useRunAgain` |
350
+ | `@botiverse/porthole/server` | `createContentHost` (`routes`, `forget`), `contentHostFor`, `prefixedName`, `memoryTicketStore`, `d1TicketStore`, `upstreamHeaders`, `statusPage`, `conformancePage`, the callbacks' types |
351
+ | `@botiverse/porthole/node` | `nodeServer`, `nodeHost`, `nodeProbe`, `toRequest`, `sendResponse` |
352
+ | `@botiverse/porthole/check` | `checkPage`, `playwrightDriver`, `cdpDriver`; `/check/page`, the check page's script |
353
+ | `@botiverse/porthole/mcp` | the MCP Apps adapter (views, the sandbox proxy) |
354
+ | `@botiverse/porthole/conformance` | `defineHostConformance`, `conformanceProjects`, `onDemand`, `conformancePage` |
355
+
356
+ The types' doc comments are the precise reference; DESIGN.md § "The host kit" is the long form.
package/docs/DECISIONS.md CHANGED
@@ -1809,3 +1809,149 @@ artifact-only app lacks, two snippet bugs, no word on the page's CSP, two ways t
1809
1809
  which left the manual wrong), Workers specifics, and local development.
1810
1810
  **Revisit when** a second cold adoption (after 0.3) finds friction these don't cover.
1811
1811
 
1812
+
1813
+ ## P072 · 2026-10-12 · Host kit 0.3: the client, the bootstrap and the relay, so adopters stop writing glue · Accepted
1814
+
1815
+ **Decision.** After 0.2.2 the server's content file is policy and little
1816
+ else; the glue moved to the client, the bootstrap and url mode. Ferry still writes about 1,650
1817
+ lines of glue and workarounds, Raft about 450 (notes/porthole-0.3-audit.md). 0.3 adds, all
1818
+ additive:
1819
+
1820
+ 1. **`defineDisplays(kinds)`** (core): one registry for every kind an app shows.
1821
+
1822
+ ```ts
1823
+ const displays = defineDisplays({
1824
+ widget: { preset: "inlineWidget", options: { capabilities: { sendPrompt: {} } } },
1825
+ page: { preset: "artifact", options: { layout: { kind: "fill" } } },
1826
+ preview:{ preset: "url", options: {} }, // url mode: served only
1827
+ });
1828
+ displays.opaque("widget"); // PortholeConfig
1829
+ displays.served(contentSource); // Record<kind, PortholeConfig> | null, memoized
1830
+ displays.configFor(instance, contentSource | null); // by the document's kind and preset
1831
+ displays.frameSources(contentSource, { authorizeUrl }); // for a CSP built without a ContentHost (Vite, Electron)
1832
+ displays.guideConfig("widget", "served" | "opaque"); // the agent's manual, without real origins
1833
+ ```
1834
+
1835
+ `createContentHost({ displays })` and `defineHostConformance({ displays })` take it in place of
1836
+ `configs` and `config(instance)` (both stay).
1837
+ 2. **Conventional routes and bootstrap** (/server, /node):
1838
+ - `content.routes(viewerOf, { prefix = "/porthole" })`: `POST frames` (issue), `GET authorize`,
1839
+ `GET meta`, `POST handoff` (item 6), one mount. `entry.authorizeUrl` defaults to
1840
+ `${appOrigins[0]}${prefix}/authorize`.
1841
+ - `GET meta` answers `ContentClientMeta`: `{ served, contentSource, frameSources, health }`.
1842
+ - `issue` answers 201 `{ url, origin, link? }`: `link` is the clean address, where
1843
+ `entry.pathOf(instance)` names the instance's path.
1844
+ - `contentHostFor((env) => options)` on Workers: one host per `env`, a fail-closed 503 naming
1845
+ the problem (logged once), `fetch(request, env)` answering the content domain first.
1846
+ - `nodeServer({ content, app, upgrade?, appSocket? })`: the `http.Server`, the gate started on
1847
+ listen and stopped on close.
1848
+ 3. **The client served kit** (core, React):
1849
+ - `portholeClient({ base = "/porthole", headers?, credentials?, displays })`: `meta()`,
1850
+ `subscribe()`, `config(kind)` (served or opaque, null until meta is known), the locator,
1851
+ `link(instance)`, `openInTab(instance)` (a blank tab inside the click, then the link).
1852
+ - React: `<PortholeProvider client>` and `<PortholeView display="page" instance={…}
1853
+ content={…} fallback={({ kind, message, link, retry }) => …} />`, where `kind` is
1854
+ `needs-tab | denied | expired | failed | timeout`, worded as Porthole's pages word them.
1855
+ `usePortholeLink(instance)` gives `{ link, open, copy }`.
1856
+ 4. **React ergonomics:** provider `scheme`, `theme` with `themeKey`, `cssVariableTheme(tokens)`,
1857
+ `nonce: "auto"`, `openLink`, `notify` (skin the copy notice), `renderConfirm(request, answer)`
1858
+ (the app draws the dialog; Porthole keeps the gates, the one-at-a-time queue and decline
1859
+ counting); content errors deduplicated per run; `useRunAgain()` for a "run again" button.
1860
+ 5. **The url-mode relay kit** (/server, /node): `upstreamHeaders.request/response` (the header
1861
+ rewrite `proxyTo` uses, on `Headers` or raw pairs, WebSockets too); `statusPage(…)` (P070's
1862
+ fallback included); `nodeHost`'s `appSocket` gets the request with Porthole's cookies removed;
1863
+ `content.forget({ scope?, subject? })` drops cached `authorize` answers.
1864
+ 6. **Viewer handoff for token-authenticated apps:** `POST handoff`, called by the signed-in app
1865
+ with its own token (`client.handoff()`), sets an `HttpOnly` cookie scoped to the authorize
1866
+ path holding a short-lived viewer key Porthole signs (never the app's token);
1867
+ `entry.handoff: { id(viewer), viewer(id) }` says who a viewer is and turns it back. `entry.spa: { route }` gives the
1868
+ default `signIn` for a single-page app, with `entryTarget(next)` as the open-redirect guard.
1869
+ 7. **If cheap:** `health.onServedChange(served)`, deduplicated; `log` also takes a
1870
+ `{ info, warn, error }` logger; `prefixedNames({ w: …, f: … })` for several prefixes; a
1871
+ `location` on a mount, used once before the locator (pre-located frames).
1872
+
1873
+ **Why.** Each item deletes code both apps (or every adopter with that need) wrote the same way,
1874
+ and three of them already drift: Ferry's desktop CSP lacks the authorize route, its copied status
1875
+ page lacks P070's fallback, and clean addresses are computed two ways.
1876
+ **Rejected.** A framework-specific server adapter (Hono, Express): `routes` is a fetch handler
1877
+ any of them mounts in one line.
1878
+ **Decided in review:**
1879
+ - The default prefix is `/porthole`, overridable (`createContentHost({ prefix })`), and `issue`
1880
+ moves under it (`POST /porthole/frames`), so one mount serves frames, authorize, meta and
1881
+ handoff, and an embedding CSP, a dev proxy or a desktop CSP each need one path. Apps move their
1882
+ old routes themselves (`issue(viewerOf)` and `authorize(viewerOf)` still exist for that).
1883
+ - The handoff cookie lasts 10 minutes, refreshed whenever the app's page loads or regains focus
1884
+ (`portholeClient({ handoff: true })`, at most every 30 s); an expired one costs only a quiet
1885
+ trip through the app's sign-in route. The POST needs the app's own credential (`viewerOf` must
1886
+ name a viewer) and is refused from another origin (`Origin`, or `Sec-Fetch-Site` where there is
1887
+ no `Origin`), so no other site can set or clear it. The key is Porthole-signed (HMAC under the
1888
+ secret, apart from session keys), names the viewer's id and its expiry, and the cookie is
1889
+ `HttpOnly`, `SameSite=Lax`, scoped to the prefix path (`__Secure-` on https). It is no
1890
+ credential for the app's API, unlike the app's token stored in a cookie (which Ferry did), which
1891
+ would ride on every request to the app origin, for as long as the token lives.
1892
+ - Item 7: `health.onServedChange` and logger adapters only.
1893
+
1894
+ **Measured.** The example app on the new routes and client passes the whole suite on three
1895
+ engines; `PortholeView`, its fallback and `renderConfirm` run in the React spec.
1896
+
1897
+ ## P073 · 2026-10-12 · The agent's side: check a page before people see it; tools with names and schemas · Accepted
1898
+
1899
+ **Decision.** Today an agent learns its page broke only after a person
1900
+ looked (Ferry, at its next turn, at most 5 errors) or never (Raft). Porthole already has the
1901
+ parts: the shell's error capture, the conformance harness's `launch` at a width and a scheme, and
1902
+ a browser check behind every line of the manual. 0.3 exposes them:
1903
+
1904
+ 1. **`lintContent(config, content): Finding[]`** (core, pure, any runtime): what can be told
1905
+ without running it, worded as the manual words it, each rule tied to the manual's limit id:
1906
+ over `maxBytes`; a document where a fragment is shown (or the reverse); `document.write`;
1907
+ nested frames and plugins; `navigator.clipboard` and `execCommand("copy")` (use `copyText`);
1908
+ `alert`/`confirm`/`prompt`; a `<form>` that submits; hosts outside egress in `src`, `href`,
1909
+ `fetch` and imports; an unpinned library (`@latest`, a range); `position: fixed` in a flow
1910
+ layout; `target=_blank` without `openLink`. `{ rule, severity, message, line? }`.
1911
+ 2. **`checkPage(options): Promise<CheckReport>`** (`@botiverse/porthole/check`): runs the content
1912
+ in the real sandbox (the harness, the production CSP) at each width and scheme (defaults from
1913
+ the config: the manual's phone and desktop widths, light and dark unless the config is
1914
+ unthemed), and reports per run: errors (thrown, rejected, "Blocked by the sandbox"), CSP
1915
+ blocks, failed loads, `console.error`/`warn`, the height and whether the limit clips it,
1916
+ horizontal overflow, optional screenshots; plus `lint`, `ok` and one agent-readable `text`.
1917
+ Drivers: `playwrightDriver(browser)` (Node), and `cdpDriver(session)` over any CDP session
1918
+ (Puppeteer's, or `@cloudflare/puppeteer`'s on Cloudflare Browser Rendering), so a Worker can
1919
+ check too. The harness ships as a string module, so no file system is needed.
1920
+ 3. **Tool definitions** (core): `showTool(config)`, `guideTool(config)`, `checkTool(config)`, each
1921
+ `{ name, description, inputSchema }` (JSON Schema; names from `guide.toolName` and
1922
+ `guideToolName`, the topics an enum of the built-in and the config's own); `answerGuide(config,
1923
+ args)` validates and answers; `guideChanges(from, to)`, the notice for the agent when a display
1924
+ kind flips between served and opaque (null when the manual doesn't change). An MCP server
1925
+ example in `examples/mcp/` wires show, guide and check.
1926
+ 4. **The manual's own examples pass the check:** a test runs `checkPage` on every
1927
+ `GUIDE_EXAMPLES` entry under every preset, at the manual's widths, in light and dark
1928
+ (OBJECTIVES criterion 5).
1929
+
1930
+ **Why.** It is the one change that improves what agents make rather than what hosts write, and
1931
+ both apps asked for errors to reach the agent before a person does.
1932
+ **Rejected.** Running content on the host's server without a browser (jsdom and the like): it
1933
+ doesn't apply CSP, layout or the sandbox, so it would pass pages that break.
1934
+ **Decided in review:**
1935
+ - The show tool refuses by default (`admitContent`, `refuseOn: "error"`), but only on a narrow
1936
+ set of deterministic errors that would certainly fail or be cut: over the size limit, a whole
1937
+ document where a fragment goes when it can't be taken as its body, nested frames and plugins,
1938
+ `document.write`. Everything heuristic is a warning returned with the result. A host sets the
1939
+ policy (`refuseOn: "never"`). A refusal says exactly what to change, and to call the tool again.
1940
+ - Contrast: later.
1941
+ - `checkPage` must work where the host has no browser: an agent on a person's machine lints
1942
+ locally and sends the check to its server (or uses Playwright where installed); a Worker uses
1943
+ Browser Rendering through `cdpDriver`, with the check page's script imported
1944
+ (`@botiverse/porthole/check/page`). The report's text is short enough for an agent's context:
1945
+ each problem once, with where it happened, at most 8 (`maxProblems`), the rest counted.
1946
+
1947
+ **How it runs.** The check page (bundled from `src/check/page.ts`) is served at a fixed origin
1948
+ the driver answers itself (`https://porthole-check.invalid`: the shell needs a real host origin),
1949
+ mounts the content with `createHost` under its own CSP, opaque (a served config's content with the
1950
+ same CSP; an MCP Apps view as a page with its egress), and puts a small script first in the
1951
+ content that reports errors, rejections, CSP blocks, failed loads, `console.error`/`warn` and the
1952
+ document's width to the page by `postMessage`. Height comes from the display's own resize events.
1953
+
1954
+ **Measured.** Every `GUIDE_EXAMPLES` entry passes under the inline, artifact, whole-page viewer
1955
+ and MCP Apps presets at the manual's widths in light and dark, on three engines
1956
+ (`leak/check.spec.ts`); a broken widget is told each problem once; the CDP driver runs on
1957
+ Chromium.
package/docs/DESIGN.md CHANGED
@@ -509,6 +509,64 @@ package carries these docs (`docs/`), and `/server` exports the types an app's c
509
509
  renamed, so there is no compat module. `FrameBlock` gains `sign-in`; `ContentDomain.name` takes
510
510
  a `Naming` (any function still fits).
511
511
 
512
+ ### The host kit 0.3: the client, the bootstrap, the relay (P072)
513
+
514
+ What both adopters still wrote after 0.2 moves into Porthole (ADOPTING.md is the walk-through):
515
+ - **`defineDisplays(kinds)`** (core): each kind's preset and options once; opaque and served
516
+ configs (memoized per content source), the kind an instance names, frame sources and the
517
+ `frame-src` directive without a server, and a served kind's config for the manual without a real
518
+ origin. `createContentHost({ displays })` and the conformance runner take it.
519
+ - **`content.routes(viewerOf)`** (/server): one mount under `/porthole` (`prefix`): `POST frames`
520
+ (`issue`, answering `link`, the clean address, where `entry.pathOf` names the path), `GET
521
+ authorize` (its URL now the default `entry.authorizeUrl`), `GET meta` (`ContentClientMeta`:
522
+ served, content source, frame sources, health) and `POST`/`DELETE handoff`.
523
+ `contentHostFor(build)` gives one host per Workers `env`, failing closed with a plain 503;
524
+ `nodeServer({ content, app })` is the whole Node server.
525
+ - **The client:** `portholeClient({ displays, base, headers, credentials, handoff })` is the
526
+ locator and knows each kind's config from the meta (null until known), links, `openInTab`
527
+ (a tab opened in the click, then sent to the address), the handoff, and `entryTarget`.
528
+ `frameFallback(outcome)` words what to offer when a frame shows nothing (`needs-tab`,
529
+ `denied`, `expired`, `failed`, `timeout`). React: `PortholeView` (a display by kind, served or
530
+ opaque, with its fallback), `usePortholeLink`, and the provider's shared `scheme`, `theme`
531
+ (`cssVariableTheme`), `nonce: "auto"`, `handlers`, `openLink`, `notify` and `renderConfirm`.
532
+ - **The viewer handoff** for a page that holds a token: `POST /porthole/handoff` with the app's
533
+ own credential, from the app's own page, sets a 10-minute `HttpOnly` cookie scoped to the
534
+ prefix holding a Porthole-signed key (the viewer's id and expiry), which the authorize route
535
+ reads when `viewerOf` knows no one. `entry.spa` signs a person in through the app's own route.
536
+ - **The url-mode relay kit:** `upstreamHeaders` (the header rewrite `proxyTo` makes, for any
537
+ transport, WebSockets too), `statusPage` (the frame-status page with its script under its hash),
538
+ `nodeHost`'s `appSocket` without Porthole's cookies, `content.forget()` for cached `authorize`
539
+ answers.
540
+ - **Server:** `health.onServedChange(served)`, once per flip; `log` takes a `{ info, warn, error }`
541
+ logger.
542
+
543
+ ### The agent's side: lint, check, tools (P073)
544
+
545
+ - **`lintContent(config, content)`** (core, pure): what can be told without running it, each
546
+ finding worded for the agent with its line. Errors only for what certainly fails or is cut:
547
+ over the size, a document where a fragment goes that has no body, nested frames and plugins,
548
+ `document.write`. Warnings for the rest: a document sent as a widget (taken as its body,
549
+ `fragmentOf`), the clipboard, dialogs, forms, hosts outside egress, unpinned CDN libraries,
550
+ `position: fixed` in a flow layout, new windows without `openLink`.
551
+ - **`admitContent(config, content, { refuseOn })`**: the show tool's gate. It refuses errors by
552
+ default with a text that says what to change; otherwise it shows the content (a widget's
553
+ document taken as its body) and returns the warnings as a note.
554
+ - **`checkPage({ config, content, driver })`** (`/check`): the content in the real sandbox at each
555
+ width and scheme (defaults: the manual's phone and desktop widths, light and dark unless
556
+ unthemed). The check page (`src/check/page.ts`, bundled and shipped as `/check/page`) is served
557
+ by the driver at a fixed origin, mounts the content opaque under its own CSP with a small
558
+ instrument first in it, and hears errors, rejections, CSP blocks, failed loads, the console and
559
+ the document's width by `postMessage`; heights come from the display's resize events. The
560
+ report's `text` names each problem once, with where it happened, at most 8. Drivers:
561
+ `playwrightDriver(browser)`, and `cdpDriver(open)` over any CDP session (Cloudflare Browser
562
+ Rendering from a Worker).
563
+ - **Tools:** `showTool`, `guideTool`, `checkTool` give `{ name, description, inputSchema }` from
564
+ the config; `answerGuide` answers the guide tool; `guideChanges(from, to)` is the notice when a
565
+ kind flips between served and opaque. `examples/mcp/server.mjs` wires them over MCP.
566
+ - **The manual's examples pass the check:** `leak/check.spec.ts` runs every `GUIDE_EXAMPLES`
567
+ entry under each preset at the manual's widths in light and dark, on three engines (OBJECTIVES
568
+ criterion 5).
569
+
512
570
  ### Protocol adapters
513
571
 
514
572
  The core ships the adapter for the MCP Apps subset its own shell speaks