@botiverse/porthole 0.2.4 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +17 -11
  2. package/dist/check/check.d.ts +100 -0
  3. package/dist/check/check.js +247 -0
  4. package/dist/check/drivers.d.ts +43 -0
  5. package/dist/check/drivers.js +181 -0
  6. package/dist/check/index.d.ts +8 -0
  7. package/dist/check/index.js +8 -0
  8. package/dist/check/instrument.d.ts +71 -0
  9. package/dist/check/instrument.js +84 -0
  10. package/dist/check/lint.d.ts +21 -0
  11. package/dist/check/lint.js +131 -0
  12. package/dist/check/page-source.d.ts +2 -0
  13. package/dist/check/page-source.js +2 -0
  14. package/dist/check/page.d.ts +13 -0
  15. package/dist/check/page.js +170 -0
  16. package/dist/check/tools.d.ts +61 -0
  17. package/dist/check/tools.js +140 -0
  18. package/dist/conformance/host-kit.d.ts +26 -5
  19. package/dist/conformance/host-kit.js +46 -22
  20. package/dist/conformance/index.d.ts +1 -1
  21. package/dist/conformance/reporter.d.ts +14 -0
  22. package/dist/conformance/reporter.js +28 -0
  23. package/dist/displays/displays.d.ts +61 -0
  24. package/dist/displays/displays.js +113 -0
  25. package/dist/host/client.d.ts +110 -0
  26. package/dist/host/client.js +274 -0
  27. package/dist/index.d.ts +4 -0
  28. package/dist/index.js +6 -0
  29. package/dist/node/index.d.ts +26 -1
  30. package/dist/node/index.js +91 -1
  31. package/dist/react/frame.d.ts +79 -3
  32. package/dist/react/frame.js +183 -42
  33. package/dist/react/index.d.ts +2 -1
  34. package/dist/react/index.js +1 -0
  35. package/dist/react/view.d.ts +54 -0
  36. package/dist/react/view.js +151 -0
  37. package/dist/server/bootstrap.d.ts +27 -0
  38. package/dist/server/bootstrap.js +63 -0
  39. package/dist/server/host.d.ts +77 -8
  40. package/dist/server/host.js +268 -11
  41. package/dist/server/index.d.ts +4 -2
  42. package/dist/server/index.js +3 -1
  43. package/dist/server/pages.d.ts +19 -0
  44. package/dist/server/pages.js +8 -0
  45. package/dist/server/proxy.d.ts +24 -0
  46. package/dist/server/proxy.js +67 -0
  47. package/dist/server/server.js +14 -1
  48. package/dist/server/types.d.ts +8 -0
  49. package/docs/ADOPTING.md +278 -108
  50. package/docs/DECISIONS.md +280 -0
  51. package/docs/DESIGN.md +84 -2
  52. package/examples/app.mjs +82 -78
  53. package/examples/conformance/page.spec.mjs +23 -0
  54. package/examples/conformance/playwright.config.mjs +3 -2
  55. package/examples/conformance/porthole.spec.mjs +6 -3
  56. package/examples/displays.mjs +21 -0
  57. package/examples/mcp/server.mjs +121 -0
  58. package/examples/node/server.mjs +16 -34
  59. package/examples/workers/worker.mjs +19 -7
  60. package/package.json +13 -1
  61. package/src/check/check.ts +386 -0
  62. package/src/check/drivers.ts +242 -0
  63. package/src/check/index.ts +22 -0
  64. package/src/check/instrument.ts +138 -0
  65. package/src/check/lint.ts +238 -0
  66. package/src/check/page-source.ts +19 -0
  67. package/src/check/page.ts +230 -0
  68. package/src/check/tools.ts +206 -0
  69. package/src/conformance/host-kit.ts +82 -27
  70. package/src/conformance/index.ts +1 -0
  71. package/src/conformance/reporter.ts +38 -0
  72. package/src/displays/displays.ts +191 -0
  73. package/src/host/client.ts +395 -0
  74. package/src/index.ts +25 -0
  75. package/src/node/index.ts +112 -2
  76. package/src/react/frame.tsx +271 -57
  77. package/src/react/index.ts +9 -0
  78. package/src/react/view.tsx +237 -0
  79. package/src/server/bootstrap.ts +97 -0
  80. package/src/server/host.ts +372 -18
  81. package/src/server/index.ts +11 -1
  82. package/src/server/pages.ts +28 -0
  83. package/src/server/proxy.ts +86 -0
  84. package/src/server/server.ts +26 -2
  85. package/src/server/types.ts +5 -0
package/docs/ADOPTING.md CHANGED
@@ -2,8 +2,9 @@
2
2
 
3
3
  How to put Porthole in an app, from the npm package alone. The package's `examples/` is a whole
4
4
  app that does everything below: `examples/app.mjs` is the app, runtime-agnostic;
5
- `examples/node/server.mjs` and `examples/workers/` run it. DESIGN.md says how it works and
6
- DECISIONS.md why (the P-numbers the code cites).
5
+ `examples/node/server.mjs` (`nodeServer`) and `examples/workers/` (`contentHostFor`) run it, as
6
+ §4 and §5 recommend; `examples/mcp/server.mjs` gives the
7
+ agent its tools. DESIGN.md says how it works and DECISIONS.md why (the P-numbers the code cites).
7
8
 
8
9
  ## 1. Choose how content is shown
9
10
 
@@ -17,32 +18,56 @@ DECISIONS.md why (the P-numbers the code cites).
17
18
  Start opaque if you can; add served pages when content needs storage or an address. A served app
18
19
  keeps the opaque config as its fallback for when the content domain is down.
19
20
 
20
- The config is the source of truth: `presets.inlineWidget()`, `presets.artifact()`,
21
- `presets.mcpApp()`, `presets.url()` with your options. The same config object (or the same
22
- options) must be used by the server (it puts the CSP in headers), the page (`createHost`) and the
23
- agent's manual (`compile(config).guide()`): give it one home and import it everywhere.
21
+ ## 2. Say your display kinds once
24
22
 
25
- ## 2. Opaque displays: the page only
23
+ ```js
24
+ // displays.mjs: imported by the server, the page and the agent's tools
25
+ import { defineDisplays } from "@botiverse/porthole";
26
+
27
+ export const displays = defineDisplays({
28
+ widget: { preset: "inlineWidget", options: { capabilities: { sendPrompt: {}, copyText: {} } } },
29
+ artifact: { preset: "artifact", options: { layout: { kind: "fill" } } }, // a whole-page viewer
30
+ preview: { preset: "url" }, // a running app: served only
31
+ });
32
+ ```
33
+
34
+ `displays.opaque(kind)`, `displays.served(contentSource)`, `displays.configFor(instance, source)`,
35
+ `displays.frameSources(source, { authorizeUrl })` (a CSP built without a server: a dev server, a
36
+ desktop shell) and `displays.guideConfig(kind, "served" | "opaque")` (the agent's manual) all come
37
+ from it. A kind's name is the preset name its documents carry: a stored page names `artifact`
38
+ unless its `document.preset` says otherwise.
39
+
40
+ **Fill:** a whole-page viewer says `layout: { kind: "fill" }`. The frame fills its box, and the
41
+ manual tells the agent so (the page scrolls itself; `position: fixed` works). `MountOptions.fill`
42
+ and `<PortholeFrame fill>` are deprecated: they size the frame but leave the manual saying the
43
+ height follows the content.
44
+
45
+ ## 3. Opaque displays: the page only
26
46
 
27
47
  ```js
28
- import { createHost, presets } from "@botiverse/porthole";
48
+ import { createHost } from "@botiverse/porthole";
29
49
 
30
- const config = presets.inlineWidget({ capabilities: { openLink: {} } });
31
- const host = createHost(config, {
32
- handlers: { openLink: ({ url }) => window.open(url, "_blank", "noopener") },
33
- // A gated call asks the person first, with the call's whole effect (here: the link).
34
- confirm: async (request) => window.confirm(`Open ${JSON.stringify(request.args)}?`),
50
+ const host = createHost(displays.opaque("widget"), {
51
+ handlers: { sendPrompt: ({ text }) => send(text) },
52
+ // A gated call asks the person first, with the call's whole effect.
53
+ confirm: async (request) => window.confirm(`${request.capability}: ${JSON.stringify(request.args)}?`),
35
54
  });
36
- const display = host.mount(container, { displayId: "w1", title: "A chart", scheme: "light" });
55
+ const display = host.mount(box, { displayId: "w1", title: "A chart", scheme: "light" });
37
56
  display.setContent(agentHtml, { partial: true }); // while it streams: drawn inert
38
57
  display.setContent(agentHtml); // once whole: it runs, once
39
58
  display.on("contentError", ({ message }) => tellTheAgent(message));
40
59
  ```
41
60
 
42
- React: wrap the app in `<PortholeProvider>`, then
43
- `<PortholeFrame config={config} displayId={id} title={title} scheme={scheme} content={html} partial={streaming} />`.
61
+ React: `<PortholeProvider>` near the root; `<PortholeFrame config displayId title content partial />`
62
+ per display. The provider takes what every frame shares: `scheme`, `theme` (and `themeKey`;
63
+ `cssVariableTheme(tokens)` reads the values from your page's CSS variables), `nonce` (`"auto"`
64
+ reads the page's), `handlers`, `openLink` (default: a new tab), `notify` (your own toast for what
65
+ a copy button copied), and `renderConfirm` (your own dialog, given `accept`, `decline` and
66
+ `redirect`: Porthole keeps the queue, runs `accept` inside its click, and counts declines toward
67
+ muting the display; `redirect`, for "edit it first", answers the call `"redirected"` and neither
68
+ counts nor resets the count). `useRunAgain()` gives a "run again" button.
44
69
 
45
- ## 3. Served pages: the host kit
70
+ ## 4. Served pages: the host kit
46
71
 
47
72
  ### Local development
48
73
 
@@ -59,145 +84,268 @@ Put it on the Public Suffix List when you can, so its labels are sites of their
59
84
  ### The server
60
85
 
61
86
  ```js
62
- import { presets } from "@botiverse/porthole";
63
87
  import { createContentHost, prefixedName, memoryTicketStore } from "@botiverse/porthole/server";
88
+ import { nodeServer } from "@botiverse/porthole/node";
89
+ import { displays } from "./displays.mjs";
64
90
 
65
91
  const APP = "http://localhost:8790";
66
- export const pageConfig = (source) =>
67
- presets.artifact({ layout: { kind: "fill" }, isolation: "domain", contentOrigins: [source] });
68
-
69
92
  const content = createContentHost({
70
- domain: "content.localhost:8790", // "" turns content off
93
+ domain: "content.localhost:8790", // "" turns content off
71
94
  appOrigins: [APP],
72
95
  secret: process.env.PORTHOLE_SECRET, // npx porthole secret
73
96
  tickets: memoryTicketStore(), // one process; d1TicketStore(env.DB) on Workers
74
- configs: (source) => ({ artifact: pageConfig(source) }),
97
+ displays,
75
98
  name: prefixedName("a-"), // page "abc" is served on a-abc.<domain>
76
99
  instance: (proposal) => myInstance(proposal), // what a frame request asks for, as you mean it
77
100
  access: async (instance, viewer) => ((await mayView(viewer, instance)) ? { viewer: viewer.id } : null),
78
101
  source: (id, version) => myStore.page(id, version), // { html } | null
79
102
  entry: { // clean addresses: a-abc.<domain>/ in a new tab
80
- authorizeUrl: `${APP}/porthole/authorize`,
81
- at: (scope, path) => instanceAt(scope, path), // null: nothing there (404)
103
+ at: (scope, path) => instanceAt(scope, path), // null: nothing there (a 404 on the content domain)
104
+ pathOf: async (instance) => pathOf(instance), // the reverse (may look it up): frames come with their link
82
105
  signIn: (returnTo) => Response.redirect(`${APP}/login?next=${encodeURIComponent(returnTo)}`, 303),
83
106
  },
84
107
  });
108
+
109
+ // One mount, under /porthole: POST frames, GET authorize, GET meta, POST/DELETE handoff.
110
+ const routes = content.routes(viewerOf);
111
+ // The whole server: the content domain to Porthole, then Porthole's routes, then your app.
112
+ nodeServer({ content, app: async (request) => (await routes(request)) ?? app(request) }).listen(8790);
85
113
  ```
86
114
 
87
- - **`configs`' keys** are the preset names a stored page names: an artifact page names
88
- `artifact` unless its `document.preset` says otherwise, so key it `artifact`.
89
115
  - **`instance`** gets the client's proposal (`{ scope, document }`) and returns the instance as
90
116
  your app means it, or null. Derive the scope (the origin) from what it names: the client never
91
- chooses an origin.
92
- - **`access`** returns a grant (`{ viewer }`, or `{ anonymous: true }` for a public page) or null.
93
- `authorize` (optional) checks again on every request after, for revocation.
117
+ chooses an origin. **`access`** returns a grant (`{ viewer }`, or `{ anonymous: true }` for a
118
+ public page) or null; `authorize` (optional) checks again on every request after, and
119
+ `content.forget({ scope, subject })` drops its cached answers when you revoke.
120
+ - **`viewerOf(request)`** is your app's own: who is signed in, from its cookie or token, or null.
94
121
  - **`Response.redirect` needs an absolute URL** outside a browser (Node throws on `/login`).
95
122
  - **`reserved`** is only for labels your app itself serves on the content domain (previews of a
96
123
  dev server, `p-*`). Labels nothing serves need nothing: they are a 404 there.
124
+ - **No content domain** (self-hosted without one): still make the host, with `domain: null` (or
125
+ `""`). That is the supported setup: no secret is needed, `GET /porthole/meta` answers
126
+ `{ served: false }`, and pages show every kind opaque (a url kind, its fallback) instead of
127
+ waiting for a meta that never comes. Without a host, `portholeClient` stays pending.
128
+ - **`secret`** is at least 32 random bytes (`npx porthole secret`), from the environment
129
+ (`PORTHOLE_SECRET`). A missing or short one throws at `createContentHost`, saying so (with
130
+ `health`, frames stay opaque and the meta says why).
131
+ - **`nodeServer`** is the whole Node server: the content domain to Porthole, WebSockets included,
132
+ every other request to `app` (fetch-style: Hono's `app.fetch`) or `request` (a Node listener:
133
+ Express), the health gate started on listen and stopped on close. Behind a TLS edge, add
134
+ `scheme: "https"`. A host that needs the port first (`listen(0)`) can come later: `content:
135
+ () => host` (null until made); requests go to the app until it gives one.
136
+ - **`nodeHost(content, { request })`** is for an app that keeps its own `node:http` server (or a
137
+ framework that owns one): put its `request` and `upgrade` listeners on your server, call
138
+ `content.start()` once it listens and `content.close()` when it stops.
139
+ - **Health:** `health: { probe: nodeProbe(), onServedChange: (served) => … }` checks the content
140
+ domain over the real network and falls back to opaque frames while it doesn't answer.
97
141
 
98
- Routes: the content domain first, then your app.
142
+ ### The page
99
143
 
100
144
  ```js
101
- // Node (node:http)
102
- import { nodeHost, nodeProbe, toRequest, sendResponse } from "@botiverse/porthole/node";
103
- const porthole = nodeHost(content, { request: (req, res) => app(toRequest(req, "http")).then((r) => sendResponse(res, r)) });
104
- http.createServer(porthole.request).on("upgrade", porthole.upgrade).listen(8790, () => content.start());
105
-
106
- // Any fetch-style runtime (Workers, Hono, Bun, Deno)
107
- const answer = (await content.fetch(request)) ?? (await app(request));
108
-
109
- // Your app's routes
110
- "/api/frames" → content.issue(viewerOf)(request) // POST { instance } → 201 { url, origin }
111
- "/porthole/authorize" → content.authorize(viewerOf)(request) // GET, for clean addresses
112
- "/api/meta" → content.meta() // { served, contentSource, health }
145
+ import { createHost, frameFallback, portholeClient } from "@botiverse/porthole";
146
+ import { displays } from "./displays.mjs";
147
+
148
+ const porthole = portholeClient({ displays }); // the server's /porthole routes
149
+ const meta = await porthole.refresh(); // { served, contentSource, frameSources }
150
+ const display = createHost(porthole.config("artifact"), { locator: porthole })
151
+ .mount(box, { displayId: id, title, scheme: "light", ...(meta?.served ? { instance } : {}) });
152
+ if (!meta?.served) display.setContent(opaqueCopy); // frames not served now: the page, opaque
153
+ display.on("outcome", (outcome) => {
154
+ const fallback = frameFallback(outcome); // null when it loaded
155
+ if (fallback !== null) offer(fallback.title, fallback.message); // "Open this in a new tab", …
156
+ });
157
+ openButton.onclick = () => porthole.openInTab(instance); // the clean address
113
158
  ```
114
159
 
115
- `viewerOf(request)` is your app's own: who is signed in, from its cookie, or null.
116
-
117
- ### The page
118
-
119
- ```html
120
- <script type="module" nonce="…">
121
- // A client module that fails to load shows nothing at all: say so.
122
- import("@botiverse/porthole").then(async ({ createHost, httpLocator }) => {
123
- const meta = await (await fetch("/api/meta")).json();
124
- const host = createHost(meta.served ? servedConfig(meta.contentSource) : opaqueConfig, {
125
- locator: httpLocator("/api/frames"),
126
- });
127
- const display = host.mount(box, {
128
- displayId: id, title, scheme: "light",
129
- instance: { scope: id, document: { kind: "artifact", id, version } },
130
- });
131
- display.on("outcome", (outcome) => { if (outcome.state !== "loaded") offerNewTab(); });
132
- }, (error) => showProblem(`Porthole didn't load: ${error.message}`));
133
- </script>
160
+ `porthole.config(kind)` is the served config while frames are served, the opaque one while they
161
+ aren't, and null until the meta is known, so a frame never starts opaque and then restarts
162
+ served. The client's functions take no `this`: pass them bare
163
+ (`useSyncExternalStore(porthole.subscribe, porthole.meta)`). A client module that fails to load shows nothing at all: catch its import and say so
164
+ (`examples/app.mjs` does).
165
+
166
+ **Without a bundler**, the page gets Porthole's browser modules from your server, in three parts
167
+ (`examples/app.mjs` has all three):
168
+
169
+ 1. Serve the package's `dist/` at a path of your app's (`/porthole-client/`, `.js` files only).
170
+ On Workers it is the static assets directory (`assets.directory`, with `run_worker_first`).
171
+ 2. Map the bare name in an import map that carries the page's nonce:
172
+ `<script type="importmap" nonce="…">{"imports":{"@botiverse/porthole":"/porthole-client/index.js"}}</script>`.
173
+ 3. Serve the page its display kinds as a module, made from the same plain object the server's
174
+ `defineDisplays` gets, so they never disagree:
175
+ `` `import { defineDisplays } from "@botiverse/porthole";\nexport const displays = defineDisplays(${JSON.stringify(kinds)});` ``
176
+ at `/porthole-client/displays.mjs`, imported from there.
177
+
178
+ With a bundler, import `@botiverse/porthole` and your `displays.mjs` as usual.
179
+
180
+ React: give the provider the client, and show a kind. Flipping the provider's `scheme`, or a new
181
+ `themeKey`, re-themes running frames in place: they keep their state.
182
+
183
+ ```jsx
184
+ <PortholeProvider client={porthole} scheme={mode} theme={cssVariableTheme(TOKENS)} nonce="auto">
185
+ <PortholeView display="artifact" instance={instance} content={opaqueCopy}
186
+ fallback={({ title, message, link, retry }) => <Fallback {...{ title, message, link, retry }} />} />
187
+ </PortholeProvider>
188
+ // const { link, open, copy } = usePortholeLink(instance); "Open in a new tab", "Copy link"
134
189
  ```
135
190
 
136
- - `servedOrOpaque(meta, servedConfigs, opaqueConfigs)` picks the configs and says nothing until
137
- meta is known, so a frame never starts opaque and then restarts served.
138
- - "Open in a new tab" and "Copy link" use `content.urlOf(scope, path)`, the clean address, never a
139
- ticket URL. Pass it to the page from the server.
140
- - `outcome` says how the frame loaded: `blocked` with a `reason` (`cookies`: the browser keeps no
141
- cookie in a frame, as Safari; `sign-in`; `denied`; `session`) is your cue to offer a new tab.
191
+ Rendered on a server, `PortholeView` draws what the client's meta says: give `portholeClient` the
192
+ meta it starts with (`meta`, from your page's data), and the server's HTML has the frame's
193
+ placeholder or the fallback, which the page then hydrates. Without it, `pending`.
142
194
 
143
195
  ### The page's CSP
144
196
 
145
- - `frame-src`: `content.frameSources` (the content origins, and the authorize route).
146
- `embedderCsp(configs)` gives the same as a directive, from configs alone.
197
+ - `frame-src`: `content.frameSources` (the content origins, and the authorize route), also in
198
+ `GET /porthole/meta`; `displays.frameSources(source, { authorizeUrl })` without a server.
147
199
  - **An opaque display inherits your page's CSP.** Its own policy then narrows it, never widens it.
148
200
  If your page sets `default-src`, also allow what agent content uses inline:
149
201
  `img-src data: blob:`, `media-src data: blob:`, `font-src data:`, `style-src 'unsafe-inline'`,
150
202
  `worker-src blob:`. A nonce-based `script-src` works: give `createHost` the nonce
151
203
  (`HostOptions.nonce`) and the shell runs content's scripts under it.
152
- - **`form-action` holds every redirect of a submission.** If your sign-in page posts a form and
153
- then redirect entry continues to the content origin, a `form-action 'self'` blocks the last
154
- hop: leave it out there, or add the content source.
155
204
 
156
- ## 4. Cloudflare Workers
205
+ ### Sign-in
206
+
207
+ - Your sign-in page gets the authorize URL as `next` (`signIn`'s `returnTo`), and goes back to it
208
+ when signed in. The authorize URL is `<first app origin>/porthole/authorize` unless
209
+ `entry.authorizeUrl` names another, and `next` is built from it with the entry's state: never
210
+ from the address the request arrived at, which behind a TLS edge or a dev proxy isn't your app's.
211
+ - Check `next` with `entryTarget(next, authorizeUrl, { app: true })` (in the page,
212
+ `porthole.entryTarget(next, { app: true })`): the authorize route or any page on your app's
213
+ origin, as an absolute URL, and null for anything else (another site, `//host`, `/\host`,
214
+ `javascript:`), so one check serves sign-ins that go back to a page and those that go back to
215
+ a frame's content. Without `{ app: true }` it takes only the authorize route.
216
+ - **Warning: no `form-action 'self'` on a sign-in page that posts a form.** `form-action` holds
217
+ every redirect of a submission, and redirect entry continues from your sign-in through the
218
+ content origin, so the browser blocks the last hop and the person stays on your sign-in. Leave
219
+ `form-action` out of that page's CSP, or add the content source.
220
+ - **A page that authenticates with a token** (a single-page app holding a bearer token, a desktop
221
+ app) has no cookie for the authorize route to know the viewer by. Use the viewer handoff:
222
+ `entry.handoff: { id: (viewer) => viewer.id, viewer: (id) => lookUp(id) }` on the server, and
223
+ `portholeClient({ displays, headers: () => ({ authorization: `Bearer ${token()}` }), handoff: true })`
224
+ on the page. It posts to `/porthole/handoff` with your own credential, on load and when the
225
+ page regains focus; Porthole answers with a cookie that holds a key it signs (the viewer's id
226
+ and ten minutes), `HttpOnly`, scoped to `/porthole`. That beats storing the app's token in a
227
+ cookie: the key isn't a credential for your API, goes nowhere but Porthole's routes, can't be
228
+ set from another site (the POST needs your credential, and is refused from another origin), and
229
+ expires in ten minutes (an expired one costs only a quiet trip through your sign-in route).
230
+ `entry.spa: { route: "/sign-in" }` sends a signed-out person to your app's route with `next`.
231
+
232
+ ### Url mode: a relay of your own
233
+
234
+ `proxyTo` relays a url-mode app by HTTP. A relay of your own (over your own transport) uses the
235
+ same parts: `upstreamHeaders.request(headers, { origin, target, websocket })` and
236
+ `.response(...)` (the header rewrite, Porthole's cookies kept out), `statusPage({ status, title,
237
+ detail, reason, hostOrigins })` (a page that tells the frame's host why it shows nothing, desktop
238
+ schemes included), and `nodeHost`'s `appSocket` (a WebSocket, Porthole's cookies already removed).
239
+
240
+ ## 5. Cloudflare Workers
157
241
 
158
242
  ```js
159
- import { d1TicketStore } from "@botiverse/porthole/server";
160
- let app = null;
243
+ import { contentHostFor, d1TicketStore } from "@botiverse/porthole/server";
244
+
245
+ const porthole = contentHostFor((env) => ({ domain: env.CONTENT_DOMAIN, appOrigins: [env.APP_ORIGIN],
246
+ secret: env.PORTHOLE_SECRET, tickets: d1TicketStore(env.DB), displays, /* your policy */ }));
161
247
  export default {
162
248
  async fetch(request, env) {
163
- app ??= makeApp({ ...settingsFrom(env), tickets: d1TicketStore(env.DB) }); // once per isolate
164
- return (await app.content.fetch(request)) ?? app.handle(request);
249
+ return (await porthole.fetch(request, env)) ??
250
+ (await porthole.routes(request, env, viewerOf)) ?? app.fetch(request, env);
165
251
  },
166
252
  };
167
253
  ```
168
254
 
255
+ - **`contentHostFor`** makes one content host per `env`, the first time a request needs it. While
256
+ the settings can't be served (no `PORTHOLE_SECRET`, a content domain that shares a site with the
257
+ app), every request gets a plain 503 naming the problem, logged once (`{ log }`), instead of a
258
+ stack trace. `porthole.host(env)` is the host itself (`frameSources` for your CSP) once `fetch`
259
+ has answered null. Settings fixed at build time (no `env`) can make one `createContentHost` at
260
+ module scope instead; a bad setting then fails the Worker as it starts.
261
+
169
262
  - **Tickets in D1** (never KV, which is eventually consistent):
170
263
  `npx porthole d1-schema > migrations/0001_porthole_tickets.sql`, then
171
264
  `wrangler d1 migrations apply <db>`.
172
265
  - **One secret, `PORTHOLE_SECRET`:** `npx porthole secret`, then `wrangler secret put
173
- PORTHOLE_SECRET` (`.dev.vars` locally). At least 32 bytes; it signs tickets, cookies and
174
- entry codes.
266
+ PORTHOLE_SECRET` (`.dev.vars` locally). At least 32 bytes; it signs tickets, cookies, entry
267
+ codes and handoffs.
175
268
  - **Static assets:** set `"assets": { "run_worker_first": true }`. Otherwise Workers serves your
176
269
  static files before the Worker runs, on every host, content origins included.
177
270
  - No `nodejs_compat` needed. `wrangler dev` passes the Host through, so
178
271
  `*.content.localhost:<port>` works locally.
179
272
 
180
- ## 5. The agent's side
273
+ ## 6. The agent's side
274
+
275
+ ### Its tools
276
+
277
+ ```js
278
+ import { admitContent, answerGuide, checkTool, guideTool, showTool } from "@botiverse/porthole";
279
+
280
+ const config = displays.guideConfig("artifact", "served");
281
+ const tools = [showTool(config), guideTool(config), checkTool(config)]; // { name, description, inputSchema }
282
+ // show: const admitted = admitContent(config, args.html); // refuses only what certainly fails
283
+ // admitted.ok ? show(admitted.content) + admitted.note : refuse(admitted.refusal)
284
+ // guide: answerGuide(config, args) // { text } or { error }
285
+ ```
286
+
287
+ Names come from the config (`guide.toolName`, `guide.guideToolName`), else `show_<noun>`,
288
+ `<noun>_guide` and `check_<noun>` (`show_page`, `page_guide`, `check_page` for a page; naming them
289
+ in the config also has the manual name them). The descriptions are the manual's own words.
290
+ `examples/mcp/server.mjs` wires all three as an MCP server.
291
+
292
+ - **`admitContent`** runs `lintContent` and refuses (by default, `refuseOn: "error"`) only what
293
+ would certainly fail or be cut: over the size limit, a document with no body where a fragment
294
+ goes, nested frames, `document.write`. Its refusal says exactly what to change. Everything else
295
+ (hosts outside egress, unpinned libraries, `alert`, forms, the clipboard…) comes back as
296
+ warnings with the result. `refuseOn: "never"` only warns.
297
+ - **`guideChanges(from, to)`** is the notice for the agent when a kind flips between served and
298
+ opaque (null when its manual reads the same).
299
+ - **`errors: "agent"`** sends what content throws (and what the sandbox blocks) back to the agent
300
+ once people see it: listen for `contentError` and pass it on.
301
+
302
+ ### Checking a page before people see it
303
+
304
+ `checkPage` (`@botiverse/porthole/check`) runs the content in the real sandbox at the manual's
305
+ phone and desktop widths, in light and dark, and answers a report whose `text` is a few lines for
306
+ the agent: what it threw, what the sandbox blocked, what failed to load, `console.error`, overflow
307
+ and a cut height, each problem once with where it happened (at most 8; the rest counted). Lines
308
+ are the content's own, as the agent wrote it (a script's error and a lint finding name the same
309
+ line).
310
+
311
+ A served config is checked served: its content runs on an origin of its own under Porthole's
312
+ server, with the served CSP, shell, storage and cookies, as people's browsers run it (both drivers
313
+ answer a reserved content domain themselves; nothing goes to your server). An opaque config, or
314
+ an MCP Apps view, runs opaque.
315
+
316
+ The host functions the config declares are answered as a host that declines would: a person
317
+ asked to confirm says no, and a handler answers no (no prompt sent, a tool call refused). Each
318
+ call is in the report (`run.calls`): one hosts refuse whatever the person says (no click, bad
319
+ arguments) is a problem; one a person may decline is a note, so the agent makes sure the page
320
+ still works then.
181
321
 
182
- - `compile(config).toolDescription()` is your show tool's description; `compile(config).guide()`
183
- the manual (topics: `widget`, `interactive`, `chart`, and yours). Set `guide.toolName` and
184
- `guide.guideToolName` so they name your tools.
185
- - A tool definition, as an MCP server lists it:
322
+ ```js
323
+ import { checkPage, playwrightDriver } from "@botiverse/porthole/check";
324
+ const report = await checkPage({ config, content: html, driver: playwrightDriver(browser) });
325
+ report.ok; report.text;
326
+ ```
327
+
328
+ It needs a browser somewhere: Chromium is best (WebKit mutes a thrown error's message in an
329
+ opaque frame, so the agent reads only "Script error.", and names no line in a served one). Where:
330
+
331
+ - **A server with Chromium** (Node): `playwrightDriver(await chromium.launch())`.
332
+ - **An agent on a person's machine, maybe without Chromium** (Ferry's daemon): run
333
+ `lintContent` there (no browser needed), and send `check_page` to your server, which runs
334
+ `checkPage`; or use Playwright where it is installed (`examples/mcp/server.mjs` falls back to
335
+ the lint, saying so).
336
+ - **Cloudflare Workers:** Browser Rendering, through a CDP session:
186
337
 
187
338
  ```js
188
- { name: "show_page", description: compiled.toolDescription(),
189
- inputSchema: { type: "object", required: ["title", "html"],
190
- properties: { title: { type: "string" }, html: { type: "string", description: "The whole HTML document" } } } }
339
+ import puppeteer from "@cloudflare/puppeteer";
340
+ import { cdpDriver, checkPage } from "@botiverse/porthole/check";
341
+ import page from "@botiverse/porthole/check/page"; // the check page's script, bundled
342
+ const browser = await puppeteer.launch(env.BROWSER);
343
+ const tab = await browser.newPage();
344
+ const report = await checkPage({ config, content, page, driver: cdpDriver(() => tab.createCDPSession()) }); // no cast
345
+ await browser.close();
191
346
  ```
192
347
 
193
- - **Fill:** a whole-page viewer says `layout: { kind: "fill" }` in its config. The frame then fills
194
- its box, and the manual tells the agent so (the page scrolls itself; `position: fixed` works).
195
- `MountOptions.fill` and `<PortholeFrame fill>` are deprecated: they size the frame but leave the
196
- manual saying the height follows the content.
197
- - `errors: "agent"` sends what content throws (and what the sandbox blocks) back to the agent:
198
- listen for `contentError` and pass it on.
199
-
200
- ## 6. Conformance: prove your integration
348
+ ## 7. Conformance: prove your integration
201
349
 
202
350
  `@botiverse/porthole/conformance` runs Porthole's suite (egress and escape probes, the served
203
351
  cases, redirect entry) against your app's real page, its CSP and session, in Playwright:
@@ -206,7 +354,16 @@ cases, redirect entry) against your app's real page, its CSP and session, in Pla
206
354
  // playwright.config.mjs
207
355
  import { defineConfig, devices } from "@playwright/test";
208
356
  import { conformanceProjects } from "@botiverse/porthole/conformance";
209
- export default defineConfig({ projects: conformanceProjects(devices), webServer: { … } });
357
+ export default defineConfig({
358
+ fullyParallel: true, // else one spec file is one worker: minutes longer
359
+ // The list, then why each skipped case was skipped (the list alone shows a bare "-").
360
+ reporter: [["list"], ["@botiverse/porthole/conformance/reporter"]],
361
+ projects: conformanceProjects(devices, {
362
+ engines: ["chromium", "webkit", "firefox"], // the default
363
+ // launchOptions: { chromium: { executablePath: "/usr/bin/chromium" } }, a system browser
364
+ }),
365
+ webServer: { … },
366
+ });
210
367
 
211
368
  // porthole.spec.mjs
212
369
  import { test } from "@playwright/test";
@@ -214,8 +371,8 @@ import { defineHostConformance } from "@botiverse/porthole/conformance";
214
371
  defineHostConformance(test, {
215
372
  name: "my-app",
216
373
  open: async (page) => { /* sign in, open the page that shows content */ },
217
- issue: { url: "/api/frames" },
218
- config: () => pageConfig("http://*.content.localhost:8790"),
374
+ issue: { url: "/porthole/frames" },
375
+ displays, contentSource: () => `http://*.content.localhost:${port}`, // asked per case: a port known later
219
376
  instances: { artifact: (scope, version) => ({ scope, document: { kind: "artifact", id: "conformance", version } }) },
220
377
  entry: { url: (scope) => `http://a-t-${scope}.content.localhost:8790/v/1`, unknown: "derive" },
221
378
  });
@@ -236,13 +393,21 @@ The suite names its own scopes, so an app serves them through a **test mode**
236
393
  (`examples/app.mjs`: `PORTHOLE_CONFORMANCE=1`): the test page under `t-<scope>`, and a private
237
394
  page. **Never ship test mode**: with it, anyone signed in can make content origins of their
238
395
  choosing. `onDemand(make)` memoizes fixtures made the first time a case asks (a page published
239
- on demand); `instances` and `entry.url` may be async.
396
+ on demand); `instances` and `entry.url` may be async. The tests are located at your
397
+ `defineHostConformance` call, so `playwright test porthole.spec.mjs` selects them.
398
+
399
+ Each engine needs its browser (`npx playwright install chromium webkit firefox`); a subset is
400
+ `engines: ["chromium"]`. Where Playwright has no build of one (arm64 Linux's Chromium), point at
401
+ the system's: `launchOptions: { chromium: { executablePath, args } }`, merged with Porthole's own
402
+ (`use` adds to every project's).
240
403
 
241
404
  The leak probes run opaque displays on your page: where its own CSP closes what a probe needs,
242
405
  the probe reports itself inapplicable, saying which directive. Those are facts about your page's
243
- opaque fallback, not failures.
406
+ opaque fallback, not failures: a page with a `default-src` sees `[1.connect]` and
407
+ `[2.resources]` skipped, its `connect-src` already closing what they probe. The reporter above
408
+ prints each reason at the end; so does `--reporter=json`.
244
409
 
245
- ## 7. Expected, and how to tell
410
+ ## 8. Expected, and how to tell
246
411
 
247
412
  - Chromium logs `Unrecognized Content-Security-Policy directive 'webrtc'` for every frame: the
248
413
  directive closes WebRTC where an engine knows it, and is ignored where it doesn't.
@@ -251,19 +416,24 @@ opaque fallback, not failures.
251
416
  (Vue's in-browser build, Alpine.js, Vega's expressions, WebAssembly). Egress, the sandbox and the
252
417
  origin are what isolate it (P071).
253
418
  - On `http` loopback the session cookies are `porthole-<key>`; on `https`, `__Host-porthole-<key>`.
419
+ A frame's are `Secure; SameSite=None; Partitioned` on loopback too: browsers keep `Secure`
420
+ cookies on `localhost`.
421
+ - A served frame is one iframe on the content's own origin (no frame inside it), first loaded at
422
+ `/__porthole/d/<key>?ticket=…`: in a test, `page.frameLocator('iframe[src*="/__porthole/d/"]')`.
254
423
  - A clean address that names nothing (a label the naming never makes, the bare domain, a path
255
424
  `entry.at` says has nothing) is a 404 on the content domain: it never reaches your sign-in.
256
425
  - Host errors name the content origin and leave out ticket URLs.
257
426
 
258
- ## 8. Reference
427
+ ## 9. Reference
259
428
 
260
429
  | Import | What |
261
430
  | --- | --- |
262
- | `@botiverse/porthole` | `createHost`, `presets`, `compile`, `embedderCsp`, `httpLocator`, `servedOrOpaque` |
263
- | `@botiverse/porthole/react` | `PortholeProvider`, `PortholeFrame` |
264
- | `@botiverse/porthole/server` | `createContentHost`, `prefixedName`, `memoryTicketStore`, `d1TicketStore`, `contentDomain`, `conformancePage`, the callbacks' types |
265
- | `@botiverse/porthole/node` | `nodeHost`, `nodeProbe`, `toRequest`, `sendResponse` |
431
+ | `@botiverse/porthole` | `createHost`, `presets`, `defineDisplays`, `portholeClient`, `frameFallback`, `entryTarget`, `lintContent`, `admitContent`, `showTool`, `guideTool`, `checkTool`, `answerGuide`, `guideChanges`, `compile` |
432
+ | `@botiverse/porthole/react` | `PortholeProvider`, `PortholeFrame`, `PortholeView`, `usePortholeLink`, `cssVariableTheme`, `useRunAgain` |
433
+ | `@botiverse/porthole/server` | `createContentHost` (`routes`, `forget`), `contentHostFor`, `prefixedName`, `memoryTicketStore`, `d1TicketStore`, `upstreamHeaders`, `statusPage`, `conformancePage`, the callbacks' types |
434
+ | `@botiverse/porthole/node` | `nodeServer`, `nodeHost`, `nodeProbe`, `toRequest`, `sendResponse` |
435
+ | `@botiverse/porthole/check` | `checkPage`, `playwrightDriver`, `cdpDriver` (`CHECK_ORIGIN`, `CHECK_CONTENT_DOMAIN`: the names a driver of your own answers); `/check/page`, the check page's script |
266
436
  | `@botiverse/porthole/mcp` | the MCP Apps adapter (views, the sandbox proxy) |
267
- | `@botiverse/porthole/conformance` | `defineHostConformance`, `conformanceProjects`, `onDemand`, `conformancePage` |
437
+ | `@botiverse/porthole/conformance` | `defineHostConformance`, `conformanceProjects`, `onDemand`, `conformancePage`; `/conformance/reporter`, skip reasons |
268
438
 
269
439
  The types' doc comments are the precise reference; DESIGN.md § "The host kit" is the long form.