@botiverse/porthole 0.3.0 → 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 (51) hide show
  1. package/README.md +3 -2
  2. package/dist/check/check.d.ts +18 -1
  3. package/dist/check/check.js +84 -6
  4. package/dist/check/drivers.d.ts +25 -6
  5. package/dist/check/drivers.js +99 -28
  6. package/dist/check/index.d.ts +2 -2
  7. package/dist/check/index.js +1 -1
  8. package/dist/check/instrument.d.ts +71 -0
  9. package/dist/check/instrument.js +84 -0
  10. package/dist/check/page-source.js +1 -1
  11. package/dist/check/page.d.ts +2 -40
  12. package/dist/check/page.js +63 -43
  13. package/dist/conformance/host-kit.d.ts +18 -5
  14. package/dist/conformance/host-kit.js +38 -21
  15. package/dist/conformance/index.d.ts +1 -1
  16. package/dist/conformance/reporter.d.ts +14 -0
  17. package/dist/conformance/reporter.js +28 -0
  18. package/dist/host/client.d.ts +33 -15
  19. package/dist/host/client.js +39 -24
  20. package/dist/node/index.d.ts +6 -2
  21. package/dist/node/index.js +53 -8
  22. package/dist/react/frame.d.ts +13 -5
  23. package/dist/react/frame.js +67 -27
  24. package/dist/react/index.d.ts +1 -1
  25. package/dist/react/view.js +6 -1
  26. package/dist/server/host.d.ts +5 -3
  27. package/dist/server/host.js +41 -12
  28. package/docs/ADOPTING.md +108 -25
  29. package/docs/DECISIONS.md +134 -0
  30. package/docs/DESIGN.md +36 -12
  31. package/examples/app.mjs +23 -17
  32. package/examples/conformance/playwright.config.mjs +2 -1
  33. package/examples/conformance/porthole.spec.mjs +2 -1
  34. package/examples/displays.mjs +2 -0
  35. package/examples/node/server.mjs +16 -34
  36. package/examples/workers/worker.mjs +19 -7
  37. package/package.json +5 -1
  38. package/src/check/check.ts +116 -8
  39. package/src/check/drivers.ts +137 -39
  40. package/src/check/index.ts +8 -1
  41. package/src/check/instrument.ts +138 -0
  42. package/src/check/page.ts +94 -68
  43. package/src/conformance/host-kit.ts +65 -19
  44. package/src/conformance/index.ts +1 -0
  45. package/src/conformance/reporter.ts +38 -0
  46. package/src/host/client.ts +65 -34
  47. package/src/node/index.ts +56 -10
  48. package/src/react/frame.tsx +89 -33
  49. package/src/react/index.ts +1 -0
  50. package/src/react/view.tsx +6 -1
  51. package/src/server/host.ts +53 -15
package/docs/ADOPTING.md CHANGED
@@ -2,7 +2,8 @@
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; `examples/mcp/server.mjs` gives the
5
+ `examples/node/server.mjs` (`nodeServer`) and `examples/workers/` (`contentHostFor`) run it, as
6
+ §4 and §5 recommend; `examples/mcp/server.mjs` gives the
6
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
@@ -61,8 +62,10 @@ React: `<PortholeProvider>` near the root; `<PortholeFrame config displayId titl
61
62
  per display. The provider takes what every frame shares: `scheme`, `theme` (and `themeKey`;
62
63
  `cssVariableTheme(tokens)` reads the values from your page's CSS variables), `nonce` (`"auto"`
63
64
  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.
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.
66
69
 
67
70
  ## 4. Served pages: the host kit
68
71
 
@@ -82,6 +85,7 @@ Put it on the Public Suffix List when you can, so its labels are sites of their
82
85
 
83
86
  ```js
84
87
  import { createContentHost, prefixedName, memoryTicketStore } from "@botiverse/porthole/server";
88
+ import { nodeServer } from "@botiverse/porthole/node";
85
89
  import { displays } from "./displays.mjs";
86
90
 
87
91
  const APP = "http://localhost:8790";
@@ -97,15 +101,15 @@ const content = createContentHost({
97
101
  source: (id, version) => myStore.page(id, version), // { html } | null
98
102
  entry: { // clean addresses: a-abc.<domain>/ in a new tab
99
103
  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
104
+ pathOf: async (instance) => pathOf(instance), // the reverse (may look it up): frames come with their link
101
105
  signIn: (returnTo) => Response.redirect(`${APP}/login?next=${encodeURIComponent(returnTo)}`, 303),
102
106
  },
103
107
  });
104
108
 
105
109
  // One mount, under /porthole: POST frames, GET authorize, GET meta, POST/DELETE handoff.
106
110
  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));
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);
109
113
  ```
110
114
 
111
115
  - **`instance`** gets the client's proposal (`{ scope, document }`) and returns the instance as
@@ -117,10 +121,21 @@ const answer = (await content.fetch(request)) ?? (await routes(request)) ?? (awa
117
121
  - **`Response.redirect` needs an absolute URL** outside a browser (Node throws on `/login`).
118
122
  - **`reserved`** is only for labels your app itself serves on the content domain (previews of a
119
123
  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
+ - **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.
124
139
  - **Health:** `health: { probe: nodeProbe(), onServedChange: (served) => … }` checks the content
125
140
  domain over the real network and falls back to opaque frames while it doesn't answer.
126
141
 
@@ -144,10 +159,26 @@ openButton.onclick = () => porthole.openInTab(instance); // the clean
144
159
 
145
160
  `porthole.config(kind)` is the served config while frames are served, the opaque one while they
146
161
  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
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
148
164
  (`examples/app.mjs` does).
149
165
 
150
- React: give the provider the client, and show a kind:
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.
151
182
 
152
183
  ```jsx
153
184
  <PortholeProvider client={porthole} scheme={mode} theme={cssVariableTheme(TOKENS)} nonce="auto">
@@ -157,6 +188,10 @@ React: give the provider the client, and show a kind:
157
188
  // const { link, open, copy } = usePortholeLink(instance); "Open in a new tab", "Copy link"
158
189
  ```
159
190
 
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`.
194
+
160
195
  ### The page's CSP
161
196
 
162
197
  - `frame-src`: `content.frameSources` (the content origins, and the authorize route), also in
@@ -169,9 +204,15 @@ React: give the provider the client, and show a kind:
169
204
 
170
205
  ### Sign-in
171
206
 
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.
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.
175
216
  - **Warning: no `form-action 'self'` on a sign-in page that posts a form.** `form-action` holds
176
217
  every redirect of a submission, and redirect entry continues from your sign-in through the
177
218
  content origin, so the browser blocks the last hop and the person stays on your sign-in. Leave
@@ -211,6 +252,13 @@ export default {
211
252
  };
212
253
  ```
213
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
+
214
262
  - **Tickets in D1** (never KV, which is eventually consistent):
215
263
  `npx porthole d1-schema > migrations/0001_porthole_tickets.sql`, then
216
264
  `wrangler d1 migrations apply <db>`.
@@ -236,8 +284,10 @@ const tools = [showTool(config), guideTool(config), checkTool(config)]; // { nam
236
284
  // guide: answerGuide(config, args) // { text } or { error }
237
285
  ```
238
286
 
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.
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.
241
291
 
242
292
  - **`admitContent`** runs `lintContent` and refuses (by default, `refuseOn: "error"`) only what
243
293
  would certainly fail or be cut: over the size limit, a document with no body where a fragment
@@ -254,7 +304,20 @@ manual's own words. `examples/mcp/server.mjs` wires all three as an MCP server.
254
304
  `checkPage` (`@botiverse/porthole/check`) runs the content in the real sandbox at the manual's
255
305
  phone and desktop widths, in light and dark, and answers a report whose `text` is a few lines for
256
306
  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).
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.
258
321
 
259
322
  ```js
260
323
  import { checkPage, playwrightDriver } from "@botiverse/porthole/check";
@@ -263,7 +326,7 @@ report.ok; report.text;
263
326
  ```
264
327
 
265
328
  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:
329
+ opaque frame, so the agent reads only "Script error.", and names no line in a served one). Where:
267
330
 
268
331
  - **A server with Chromium** (Node): `playwrightDriver(await chromium.launch())`.
269
332
  - **An agent on a person's machine, maybe without Chromium** (Ferry's daemon): run
@@ -278,7 +341,7 @@ opaque frame, so the agent reads only "Script error."). Where:
278
341
  import page from "@botiverse/porthole/check/page"; // the check page's script, bundled
279
342
  const browser = await puppeteer.launch(env.BROWSER);
280
343
  const tab = await browser.newPage();
281
- const report = await checkPage({ config, content, page, driver: cdpDriver(() => tab.createCDPSession()) });
344
+ const report = await checkPage({ config, content, page, driver: cdpDriver(() => tab.createCDPSession()) }); // no cast
282
345
  await browser.close();
283
346
  ```
284
347
 
@@ -291,7 +354,16 @@ cases, redirect entry) against your app's real page, its CSP and session, in Pla
291
354
  // playwright.config.mjs
292
355
  import { defineConfig, devices } from "@playwright/test";
293
356
  import { conformanceProjects } from "@botiverse/porthole/conformance";
294
- 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
+ });
295
367
 
296
368
  // porthole.spec.mjs
297
369
  import { test } from "@playwright/test";
@@ -300,7 +372,7 @@ defineHostConformance(test, {
300
372
  name: "my-app",
301
373
  open: async (page) => { /* sign in, open the page that shows content */ },
302
374
  issue: { url: "/porthole/frames" },
303
- displays, contentSource: "http://*.content.localhost:8790",
375
+ displays, contentSource: () => `http://*.content.localhost:${port}`, // asked per case: a port known later
304
376
  instances: { artifact: (scope, version) => ({ scope, document: { kind: "artifact", id: "conformance", version } }) },
305
377
  entry: { url: (scope) => `http://a-t-${scope}.content.localhost:8790/v/1`, unknown: "derive" },
306
378
  });
@@ -324,9 +396,16 @@ choosing. `onDemand(make)` memoizes fixtures made the first time a case asks (a
324
396
  on demand); `instances` and `entry.url` may be async. The tests are located at your
325
397
  `defineHostConformance` call, so `playwright test porthole.spec.mjs` selects them.
326
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).
403
+
327
404
  The leak probes run opaque displays on your page: where its own CSP closes what a probe needs,
328
405
  the probe reports itself inapplicable, saying which directive. Those are facts about your page's
329
- 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`.
330
409
 
331
410
  ## 8. Expected, and how to tell
332
411
 
@@ -337,6 +416,10 @@ opaque fallback, not failures.
337
416
  (Vue's in-browser build, Alpine.js, Vega's expressions, WebAssembly). Egress, the sandbox and the
338
417
  origin are what isolate it (P071).
339
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/"]')`.
340
423
  - A clean address that names nothing (a label the naming never makes, the bare domain, a path
341
424
  `entry.at` says has nothing) is a 404 on the content domain: it never reaches your sign-in.
342
425
  - Host errors name the content origin and leave out ticket URLs.
@@ -349,8 +432,8 @@ opaque fallback, not failures.
349
432
  | `@botiverse/porthole/react` | `PortholeProvider`, `PortholeFrame`, `PortholeView`, `usePortholeLink`, `cssVariableTheme`, `useRunAgain` |
350
433
  | `@botiverse/porthole/server` | `createContentHost` (`routes`, `forget`), `contentHostFor`, `prefixedName`, `memoryTicketStore`, `d1TicketStore`, `upstreamHeaders`, `statusPage`, `conformancePage`, the callbacks' types |
351
434
  | `@botiverse/porthole/node` | `nodeServer`, `nodeHost`, `nodeProbe`, `toRequest`, `sendResponse` |
352
- | `@botiverse/porthole/check` | `checkPage`, `playwrightDriver`, `cdpDriver`; `/check/page`, the check page's script |
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 |
353
436
  | `@botiverse/porthole/mcp` | the MCP Apps adapter (views, the sandbox proxy) |
354
- | `@botiverse/porthole/conformance` | `defineHostConformance`, `conformanceProjects`, `onDemand`, `conformancePage` |
437
+ | `@botiverse/porthole/conformance` | `defineHostConformance`, `conformanceProjects`, `onDemand`, `conformancePage`; `/conformance/reporter`, skip reasons |
355
438
 
356
439
  The types' doc comments are the precise reference; DESIGN.md § "The host kit" is the long form.
package/docs/DECISIONS.md CHANGED
@@ -1955,3 +1955,137 @@ document's width to the page by `postMessage`. Height comes from the display's o
1955
1955
  and MCP Apps presets at the manual's widths in light and dark, on three engines
1956
1956
  (`leak/check.spec.ts`); a broken widget is told each problem once; the CDP driver runs on
1957
1957
  Chromium.
1958
+
1959
+ ## P074 · 2026-10-12 · 0.3.1: sign-in behind a proxy, pages checked as they run, and what 0.3.0's adopters had to guess · Accepted
1960
+
1961
+ **Decision.** 0.3.1 fixes what Ferry's and Raft Artifacts' adoptions of 0.3.0 and a second cold
1962
+ adoption (from the package alone) hit. Additions only.
1963
+ 1. **Sign-in comes back to the app as it is reached.** `signIn`'s `returnTo` and `entry.spa`'s
1964
+ `next` are `authorizeUrl` (by default `<first app origin>/porthole/authorize`) with the
1965
+ request's query, its state. Before, they were the request's own URL, which behind a TLS edge
1966
+ (`http://`) or a dev proxy (`localhost:5173`, a rewritten Host) names an origin that isn't the
1967
+ app's, so `entryTarget` refused it and the person stayed on the sign-in.
1968
+ 2. **`renderConfirm` gets `redirect()`** beside `accept` and `decline`: the call answers
1969
+ `"redirected"` (the core's existing answer for "the person took it elsewhere": edited the
1970
+ prompt first). It doesn't go, and neither counts toward muting the display nor resets the
1971
+ count. `ConfirmActions` is exported.
1972
+ 3. **`nodeServer`'s `content` may be a function** giving the host once it exists (null until
1973
+ then): a host whose content domain names the port `listen(0)` chose. Until it gives one, every
1974
+ request and upgrade is the app's; the host is started once, when first given while listening,
1975
+ and closed with the server.
1976
+ 4. **A served config is checked served.** `checkPage` ran every config opaque, so for a served
1977
+ page it reported what people never see (`document.cookie` throwing in an opaque frame) and
1978
+ missed what they do (the CSP block the throw stopped short of). Now, where the driver can serve
1979
+ (`CheckSession.serve`, both shipped drivers), the check runs Porthole's own `createServer`
1980
+ in process (a random secret; the check page, `https://porthole-check.invalid`, its only host
1981
+ origin), and the driver answers a reserved content domain (`*.porthole-check-content.invalid`)
1982
+ from it, so the content gets an origin of its own, the served CSP in headers, the shell,
1983
+ storage and cookies; each run a new origin. Nothing reaches the app's server or the network
1984
+ for those names. Opaque configs, MCP Apps views and drivers without `serve` run opaque as
1985
+ before. **One numbering:** each inline script is named (`//# sourceURL=porthole-script-<n>`)
1986
+ and its first line recorded, so a runtime error's line is the content's own line, as lint
1987
+ numbers it (it was the line within the script).
1988
+ 5. **Conformance says why it skipped:** `@botiverse/porthole/conformance/reporter`, beside the
1989
+ list reporter, prints each skipped case's reason after the run (an inapplicable probe names the
1990
+ page's directive). The example config uses it; ADOPTING's snippet has it and `fullyParallel`.
1991
+ 6. **A missing secret is named:** `createContentHost` without one throws "needs a secret: at
1992
+ least 32 random bytes (set PORTHOLE_SECRET; npx porthole secret makes one)" (it threw a
1993
+ `TypeError` from inside the HMAC); a short one says the same. Like any setting it refuses, it
1994
+ is a lasting "misconfigured" instead under the health gate's fallback (P066), and
1995
+ `contentHostFor` answers its 503 with the text. Content off (`domain: ""`) needs no secret.
1996
+ 7. **The examples follow the recommended path:** Node on `nodeServer`, Workers on
1997
+ `contentHostFor`; `examples/app.mjs` gives the host's options and a handler that takes the
1998
+ host. ADOPTING says when the other path is right: `nodeHost` for an app that keeps its own
1999
+ server, `createContentHost` at module scope for settings fixed at build time.
2000
+ 8. **ADOPTING says how a page without a bundler loads Porthole:** the package's `dist/` served at
2001
+ a path, an import map with the page's nonce, and the display kinds served as a module made
2002
+ from the same object the server's `defineDisplays` gets.
2003
+ 9. **`entryTarget(next, authorizeUrl, { app: true })`** also takes a path or address on the app's
2004
+ own origin (one leading slash, no backslash, `http(s)` only, the origin checked once resolved),
2005
+ returned absolute: one open-redirect guard for a sign-in that goes back to a page or to a
2006
+ frame's content. Without the option it is the authorize route only, as before. ADOPTING and
2007
+ the doc comment state the default authorize URL.
2008
+
2009
+ 10. **Configs that declare host functions can be checked (#8).** The check page mounted with no
2010
+ handlers, so `mount` threw "No handler for the declared capabilities" before content ran,
2011
+ and `checkTool` on a widget config with `sendPrompt` couldn't run at all. Now the check page
2012
+ answers every declared host function as a host that declines (its `confirm` says no; each
2013
+ handler answers no: `false`, nothing, or a refused tool call or read) and reports each call
2014
+ the host sees (`run.calls`): one a host's gates refuse whatever the person says (no click, bad
2015
+ arguments, not offered, too often) is a problem; one a person or host may decline is a note.
2016
+ A global the shell refuses itself (`sendPrompt` with no click) rejects in the content, which
2017
+ the check reports as the error it is. The manual's examples are now checked under presets
2018
+ that declare every host function too, opaque, served and MCP Apps.
2019
+
2020
+ From Raft Artifacts' adoption of 0.3.0 (its workarounds grew from 14 lines to 34 for these):
2021
+
2022
+ 11. **`entry.pathOf` may be async** (`Awaitable`, given the request too): a clean path that needs a
2023
+ lookup (`/` for a page's current version) comes from the database. Where it fails, the frame
2024
+ is issued without a link rather than refused. `link`, `usePortholeLink` and `openInTab` were
2025
+ async already.
2026
+ 12. **The runner's `contentSource` may be a function**, asked when a case needs a config: the
2027
+ test server's port isn't known when the spec file loads.
2028
+ 13. **`conformanceProjects(devices, { use, launchOptions })`**: `use` adds to every project's;
2029
+ `launchOptions` per engine (a system Chromium's `executablePath` and `args`, where Playwright
2030
+ has no build: arm64 Linux) merges with Porthole's own, Firefox's preferences with the ones its
2031
+ probes need.
2032
+ 14. **`PortholeView` renders on the server** what the client's meta says: the frame's placeholder
2033
+ or the fallback, from `portholeClient({ meta })`. Its server snapshot was null, so an SSR'd
2034
+ page (and its tests) had nothing until hydration.
2035
+ 15. **`CdpSession` is documented as the least the driver uses**, and a type test holds that
2036
+ Playwright's `CDPSession` and Puppeteer's (as it declares itself, generic over the protocol)
2037
+ are taken with no cast. Checked against Raft's own `@cloudflare/puppeteer` and TypeScript
2038
+ 5.9 settings, 0.3.0's type took both already: its cast can simply go.
2039
+
2040
+ From Ferry, after 0.3.0:
2041
+
2042
+ 16. **`portholeClient`'s functions are declared `this: void`**, so they pass bare
2043
+ (`useSyncExternalStore(porthole.subscribe, porthole.meta)`) under type-aware lint's
2044
+ `unbound-method`, and none reads `this` (`openInTab` called `this.link`). Method syntax with
2045
+ `this: void` rather than function properties keeps `PortholeClient<"a" | "b">` assignable to
2046
+ `PortholeClient` (the provider's), as methods' parameters are.
2047
+ 17. **No content domain is a host with `domain: null`**, the supported setup for a self-hosted app
2048
+ without one: no secret needed, and `/porthole/meta` answers `{ served: false }`, so pages show
2049
+ opaque rather than pending. ADOPTING says so.
2050
+ 18. **A provider's scheme flip or new `themeKey` re-themes its frames in place (#9).** The
2051
+ provider's context value is renewed with its scheme, theme and themeKey, and two effects were
2052
+ keyed on it: `PortholeFrame`'s registry effect (whose cleanup let the frame go, so it was made
2053
+ again) and the mount effect. Every display was destroyed and made again: widgets lost their
2054
+ state, url-mode previews reloaded. Both now depend only on the provider's stable parts (the
2055
+ registry, heights, handlers, confirm, locator, nonce, hostInfo by value), and read the scheme
2056
+ and theme when used; flips go through `setTheme`, a new themeKey through `refreshTheme`, and a
2057
+ new theme function (tokens passed inline) through `refreshTheme` where its values changed.
2058
+
2059
+ **Risks.**
2060
+ - Item 9 widens what a guard accepts, on request. Bounded by `test/kit03.test.ts`: `//host`,
2061
+ `/\host`, a tab inside the slashes, `\\host`, another scheme, a look-alike host, `javascript:`
2062
+ and `data:` are all null.
2063
+ - Item 3 sends every request to the app until the host exists, the content domain's included.
2064
+ Nothing names that domain before the host does (its port is the one just chosen); an app whose
2065
+ DNS already points the content domain at it makes the host before it listens.
2066
+ - Item 1 trusts `authorizeUrl`, which the app sets (or its first app origin); the request can no
2067
+ longer choose where sign-in comes back to, which is narrower than before.
2068
+
2069
+ **Why.** Each item was a workaround or a wrong guess: Ferry's sign-in stayed put behind its dev
2070
+ proxy and a TLS edge; an app's own dialog couldn't answer "edit first" without a decline that
2071
+ counts; an app that makes its host after its server starts had to drop to `nodeHost`; an agent told
2072
+ to fix line 6 of a served page's runtime error edited the wrong line, for an error people never see;
2073
+ `[1.connect]` showed as a bare "-"; a forgotten secret crashed inside the HMAC; Ferry's widget
2074
+ config couldn't be checked at all (#8); the cold adopter had to choose between the guide's path and
2075
+ the examples', read `examples/app.mjs` to load the browser modules, and read `client.js` to learn
2076
+ `entryTarget` refused `/`; Raft Artifacts' workarounds for items 11 to 15 had grown to 34 lines;
2077
+ Ferry's type-aware lint refused the client's functions passed bare, it made no host at all without a
2078
+ content domain, leaving displays pending, and every theme flip made its displays again (#9).
2079
+ **Measured.** `test/kit03.test.ts` (a proxied authorize request, the SPA `next`, the lazy
2080
+ `nodeServer`, the secret, `entryTarget`, an async `pathOf`, the client's functions taken bare and
2081
+ linted, no content domain); the prod-shape profile signs in through its TLS edge with the kit app
2082
+ reached as `http` behind it (failing before item 1); `leak/react.spec.ts` (four redirects, never
2083
+ muted, no prompt sent); `leak/check.spec.ts` (a served page: no cookie error, the connect block
2084
+ reported, errors on their file lines, on both drivers; every host function declared: the manual's
2085
+ examples pass, and a widget's calls on load are answered and reported, opaque and served);
2086
+ `test/check.test.ts` (the calls' words, the CDP session types); `test/conformance-options.test.ts`;
2087
+ `test/react-ssr.test.ts` (failing before item 14); `leak/react.spec.ts`'s flips of the provider's
2088
+ scheme and themeKey keep each frame element, its window and its page, opaque, served and url
2089
+ (failing before item 18); the examples' unit tests and their conformance run on three engines.
2090
+ **Revisit when** a driver that can't intercept requests needs served checks (it would need a
2091
+ real content domain).
package/docs/DESIGN.md CHANGED
@@ -437,7 +437,10 @@ a link sent to someone with access.
437
437
  frame, never the sign-in**: a plain page asking for a new tab (`blocked: sign-in`). No
438
438
  access: the app's refusal on a tab (`refusal(status, request, entry)`; nothing returned:
439
439
  Porthole's page), a plain page in a frame; never content. Both hooks get the address decoded
440
- (`EntryContext`: label, scope, path, clean URL, the instance, framed).
440
+ (`EntryContext`: label, scope, path, clean URL, the instance, framed). `returnTo` (and
441
+ `entry.spa`'s `next`) is `authorizeUrl` with the request's query: the app as it is reached,
442
+ never the request's own URL, whose scheme and host behind a TLS edge or a dev proxy are
443
+ another's (P074).
441
444
  3. Granted, a 302 back to `/__porthole/entry?code=…`: a one-time code (60 s), bound to the
442
445
  label, the path and the nonce. The content origin redeems it only on that label and only with
443
446
  the nonce's cookie, sets the session (bound to the path) and 303s to the clean address. The
@@ -489,7 +492,11 @@ The tests are located in the app's own spec file, at the `defineHostConformance`
489
492
  addresses may be async (an app publishes a test page on demand and returns its real instance,
490
493
  which the issue endpoint then gets); `entry.unknown` lists addresses that name nothing, each of
491
494
  which must be a 404 on the content domain. `hostConformance(options)` gives the hosts for an app
492
- that registers the cases itself.
495
+ that registers the cases itself. Playwright's list and line reporters show a skipped case without
496
+ its reason; `@botiverse/porthole/conformance/reporter` prints each reason after the run (P074).
497
+ `contentSource` may be a function, asked per case (a port known only once the server runs), and
498
+ `conformanceProjects` merges an app's own `use` and per-engine `launchOptions` (a system
499
+ browser) with Porthole's (P074).
493
500
 
494
501
  **Prod shape** (`ops/prod-shape/`, `ops/prod-shape/run.sh`). Docker compose: Caddy's internal
495
502
  CA serving `app.test`, `*.content.test` (same-site siblings, as in production without a Public
@@ -517,18 +524,24 @@ What both adopters still wrote after 0.2 moves into Porthole (ADOPTING.md is the
517
524
  `frame-src` directive without a server, and a served kind's config for the manual without a real
518
525
  origin. `createContentHost({ displays })` and the conformance runner take it.
519
526
  - **`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
527
+ (`issue`, answering `link`, the clean address, where `entry.pathOf` names the path, which it
528
+ may look up: a promise, P074), `GET
521
529
  authorize` (its URL now the default `entry.authorizeUrl`), `GET meta` (`ContentClientMeta`:
522
530
  served, content source, frame sources, health) and `POST`/`DELETE handoff`.
523
531
  `contentHostFor(build)` gives one host per Workers `env`, failing closed with a plain 503;
524
- `nodeServer({ content, app })` is the whole Node server.
532
+ `nodeServer({ content, app })` is the whole Node server (`content` may be a function giving the
533
+ host once made, P074). A missing or short secret throws, naming `PORTHOLE_SECRET`.
525
534
  - **The client:** `portholeClient({ displays, base, headers, credentials, handoff })` is the
526
535
  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`.
536
+ (a tab opened in the click, then sent to the address), the handoff, and `entryTarget` (the
537
+ authorize route only; with `{ app: true }` also a path or address on the app's origin, P074).
528
538
  `frameFallback(outcome)` words what to offer when a frame shows nothing (`needs-tab`,
529
539
  `denied`, `expired`, `failed`, `timeout`). React: `PortholeView` (a display by kind, served or
530
540
  opaque, with its fallback), `usePortholeLink`, and the provider's shared `scheme`, `theme`
531
- (`cssVariableTheme`), `nonce: "auto"`, `handlers`, `openLink`, `notify` and `renderConfirm`.
541
+ (`cssVariableTheme`), `nonce: "auto"`, `handlers`, `openLink`, `notify` and `renderConfirm`
542
+ (`accept`, `decline`, and `redirect`: `"redirected"`, which doesn't count toward muting, P074).
543
+ A flip of the provider's scheme or a new themeKey re-themes running frames in place: no effect
544
+ that makes a display depends on the context value those renew (#9, P074).
532
545
  - **The viewer handoff** for a page that holds a token: `POST /porthole/handoff` with the app's
533
546
  own credential, from the app's own page, sets a 10-minute `HttpOnly` cookie scoped to the
534
547
  prefix holding a Porthole-signed key (the viewer's id and expiry), which the authorize route
@@ -554,12 +567,23 @@ What both adopters still wrote after 0.2 moves into Porthole (ADOPTING.md is the
554
567
  - **`checkPage({ config, content, driver })`** (`/check`): the content in the real sandbox at each
555
568
  width and scheme (defaults: the manual's phone and desktop widths, light and dark unless
556
569
  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).
570
+ by the driver at a fixed origin (`https://porthole-check.invalid`), mounts the content with a
571
+ small instrument first in it, and hears errors, rejections, CSP blocks, failed loads, the
572
+ console and the document's width by `postMessage`; heights come from the display's resize
573
+ events. A served config runs served (P074): the driver also answers a reserved content domain
574
+ (`*.porthole-check-content.invalid`) with an in-process `createServer` (a random secret, the
575
+ check page as its only host origin), so the content gets its own origin, the served CSP in
576
+ headers, the shell, storage and cookies, each run on a new origin; an opaque config, an MCP
577
+ Apps view (as a page with the view's egress) and a driver without `serve` run opaque. Each
578
+ inline script is named (`//# sourceURL=porthole-script-<n>`) and its first line recorded, so an
579
+ error's line is the content's own line, as lint numbers it. Every host function the config
580
+ declares is answered as a host that declines (`confirm` says no; each handler answers no), and
581
+ each call the host sees is reported (`run.calls`): refused by a gate whatever the person says (no
582
+ click, bad arguments, too often) a problem, declined or answered a note. A global the shell
583
+ refuses itself without a click (`sendPrompt`) rejects in the content, so it shows as an error. The report's `text` names each
584
+ problem once, with where it happened, at most 8. Drivers: `playwrightDriver(browser)` (requests
585
+ answered by `page.route`), and `cdpDriver(open)` over any CDP session (`Fetch` interception;
586
+ Cloudflare Browser Rendering from a Worker).
563
587
  - **Tools:** `showTool`, `guideTool`, `checkTool` give `{ name, description, inputSchema }` from
564
588
  the config; `answerGuide` answers the guide tool; `guideChanges(from, to)` is the notice when a
565
589
  kind flips between served and opaque. `examples/mcp/server.mjs` wires them over MCP.
package/examples/app.mjs CHANGED
@@ -1,11 +1,13 @@
1
1
  // A whole Porthole app, runtime-agnostic (a web `Request` in, a `Response` out): agents' HTML
2
2
  // pages, each version on an origin of its own, framed in the app's viewer and openable at a
3
- // clean address. examples/node/server.mjs and examples/workers/worker.mjs only adapt it.
3
+ // clean address. examples/node/server.mjs (`nodeServer`) and examples/workers/worker.mjs
4
+ // (`contentHostFor`) only run it.
4
5
  //
5
6
  // What is the app's own here (the policy): who is signed in (a cookie), which pages exist, who
6
7
  // may see each, and what a clean address names. Everything else is Porthole's: one mount
7
8
  // (`content.routes`, under /porthole) answers frames, the authorize route and the page's meta.
8
- import { conformancePage, createContentHost, prefixedName } from "@botiverse/porthole/server";
9
+ import { entryTarget } from "@botiverse/porthole";
10
+ import { conformancePage, prefixedName } from "@botiverse/porthole/server";
9
11
  import { displays, kinds } from "./displays.mjs";
10
12
 
11
13
  /** The stored pages: id → versions. An app keeps them in its database. */
@@ -30,18 +32,21 @@ const html = (body, headers = {}) =>
30
32
 
31
33
  const escape = (text) => text.replace(/[&<>"']/gu, (char) => `&#${char.charCodeAt(0)};`);
32
34
 
33
- /** Only a path of the app's own comes back from sign-in: never another site's address. */
34
- const ownPath = (next, appOrigin) => {
35
- if (next?.startsWith(`${appOrigin}/`)) next = next.slice(appOrigin.length);
36
- return next?.startsWith("/") && !next.startsWith("//") && !next.includes("\\") ? next : "/";
37
- };
38
-
39
35
  /**
36
+ * The app: `options`, its content host's (its policy), and `handle(request, content)`, its own
37
+ * requests, given that host. A runtime makes the host from the options and sends the content
38
+ * domain's requests to it.
39
+ *
40
40
  * @param {{ appOrigin: string, contentDomain: string, secret: string, tickets?: import("@botiverse/porthole/server").TicketStore,
41
41
  * health?: import("@botiverse/porthole/server").HealthOptions, conformance?: boolean, client: (path: string) => Promise<Response | null> }} settings
42
42
  */
43
43
  export function makeApp(settings) {
44
44
  const { appOrigin } = settings;
45
+ // Where redirect entry comes back after sign-in: `<first app origin>/porthole/authorize`, the
46
+ // default (`entry.authorizeUrl` names another).
47
+ const authorizeUrl = `${appOrigin}/porthole/authorize`;
48
+ /** Where sign-in goes on to: the authorize route or a page of the app's own, never another site. */
49
+ const backTo = (next) => entryTarget(next, authorizeUrl, { app: true }) ?? `${appOrigin}/`;
45
50
  const pages = { ...PAGES };
46
51
  // TEST MODE, for Porthole's conformance runner only (examples/conformance): pages the suite
47
52
  // names itself, and one page no one may see. NEVER enable it in production: anyone signed in
@@ -68,7 +73,8 @@ export function makeApp(settings) {
68
73
  : null;
69
74
  };
70
75
 
71
- const content = createContentHost({
76
+ /** @type {import("@botiverse/porthole/server").ContentHostOptions<string>} */
77
+ const options = {
72
78
  domain: settings.contentDomain,
73
79
  appOrigins: [appOrigin],
74
80
  secret: settings.secret,
@@ -125,14 +131,14 @@ export function makeApp(settings) {
125
131
  },
126
132
  ...(settings.health === undefined ? {} : { health: settings.health }),
127
133
  log: (event) => console.log(JSON.stringify(event)),
128
- });
129
- // Frames, the authorize route and the page's meta, under /porthole.
130
- const routes = content.routes(viewerOf);
134
+ };
131
135
 
132
- async function handle(request) {
136
+ /** @param {Request} request @param {import("@botiverse/porthole/server").ContentHost<string>} content */
137
+ async function handle(request, content) {
133
138
  const url = new URL(request.url);
134
139
  const viewer = viewerOf(request);
135
- const porthole = await routes(request);
140
+ // Frames, the authorize route and the page's meta, under /porthole.
141
+ const porthole = await content.routes(viewerOf)(request);
136
142
  if (porthole !== null) return porthole;
137
143
  if (url.pathname === "/porthole-client/displays.mjs") {
138
144
  // The page's display kinds: the same as the server's, as a module.
@@ -160,7 +166,7 @@ export function makeApp(settings) {
160
166
  });
161
167
  }
162
168
  if (url.pathname === "/login" && request.method === "GET") {
163
- const next = escape(ownPath(url.searchParams.get("next"), appOrigin));
169
+ const next = escape(backTo(url.searchParams.get("next")));
164
170
  return html(
165
171
  `<!doctype html><title>Sign in</title><main id="sign-in-page"><form method="post"><input type="hidden" name="next" value="${next}"><button id="sign-in">Sign in as ada</button></form></main>`,
166
172
  {
@@ -171,7 +177,7 @@ export function makeApp(settings) {
171
177
  );
172
178
  }
173
179
  if (url.pathname === "/login" && request.method === "POST") {
174
- const next = ownPath(new URLSearchParams(await request.text()).get("next"), appOrigin);
180
+ const next = backTo(new URLSearchParams(await request.text()).get("next"));
175
181
  return new Response(null, {
176
182
  status: 303,
177
183
  headers: {
@@ -228,5 +234,5 @@ Promise.all([import("@botiverse/porthole"), import("/porthole-client/displays.mj
228
234
  }, (error) => problem("Porthole's client didn't load: " + error.message));
229
235
  </script></body></html>`;
230
236
 
231
- return { content, handle };
237
+ return { options, handle };
232
238
  }
@@ -11,7 +11,8 @@ export default defineConfig({
11
11
  testMatch: "*.spec.mjs",
12
12
  outputDir: process.env.PORTHOLE_EXAMPLE_RESULTS ?? "test-results",
13
13
  fullyParallel: true,
14
- reporter: [["list"]],
14
+ // The list, and why each skipped case was skipped (an inapplicable probe says which directive).
15
+ reporter: [["list"], ["@botiverse/porthole/conformance/reporter"]],
15
16
  projects: conformanceProjects(devices, {
16
17
  engines: (process.env.PORTHOLE_ENGINES ?? "chromium,webkit,firefox").split(","),
17
18
  }),
@@ -19,7 +19,8 @@ defineHostConformance(test, {
19
19
  // The app's frame endpoint (content.routes), and its display kinds.
20
20
  issue: { url: "/porthole/frames" },
21
21
  displays,
22
- contentSource: `http://*.content.localhost:${port}`,
22
+ // Asked when a case needs it: a function, so a port known only once the server runs works too.
23
+ contentSource: () => `http://*.content.localhost:${port}`,
23
24
  // A stored-pages app: its test page's two versions (the domain cases run on version 1).
24
25
  instances: {
25
26
  artifact: (scope, version) => ({
@@ -11,6 +11,8 @@ export const kinds = {
11
11
  options: {
12
12
  // A whole-page viewer: the frame fills its box, and the agent's manual says so.
13
13
  layout: { kind: "fill" },
14
+ // Optional: the tools default to these names (show_page, page_guide, check_page); naming
15
+ // them here also has the manual name them.
14
16
  guide: { toolName: "show_page", guideToolName: "page_guide" },
15
17
  },
16
18
  },