@botiverse/porthole 0.2.2 → 0.2.4

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 (39) hide show
  1. package/README.md +83 -0
  2. package/dist/cli.d.ts +6 -0
  3. package/dist/cli.js +51 -0
  4. package/dist/conformance/entry.d.ts +12 -6
  5. package/dist/conformance/entry.js +17 -5
  6. package/dist/conformance/harness.js +8 -8
  7. package/dist/conformance/host-kit.d.ts +43 -13
  8. package/dist/conformance/host-kit.js +83 -6
  9. package/dist/conformance/index.d.ts +1 -1
  10. package/dist/conformance/index.js +1 -1
  11. package/dist/conformance/limits.js +15 -2
  12. package/dist/conformance/page.d.ts +6 -0
  13. package/dist/conformance/page.js +8 -0
  14. package/dist/host/types.d.ts +6 -3
  15. package/dist/isolation/served.js +13 -2
  16. package/dist/react/frame.d.ts +5 -2
  17. package/dist/server/index.d.ts +1 -0
  18. package/dist/server/index.js +2 -0
  19. package/docs/ADOPTING.md +269 -0
  20. package/docs/DECISIONS.md +37 -0
  21. package/docs/DESIGN.md +13 -6
  22. package/examples/app.mjs +234 -0
  23. package/examples/conformance/playwright.config.mjs +28 -0
  24. package/examples/conformance/porthole.spec.mjs +36 -0
  25. package/examples/node/server.mjs +75 -0
  26. package/examples/workers/migrations/0001_porthole_tickets.sql +2 -0
  27. package/examples/workers/worker.mjs +33 -0
  28. package/examples/workers/wrangler.jsonc +19 -0
  29. package/package.json +7 -2
  30. package/src/cli.ts +54 -0
  31. package/src/conformance/entry.ts +33 -11
  32. package/src/conformance/host-kit.ts +127 -21
  33. package/src/conformance/index.ts +4 -0
  34. package/src/conformance/limits.ts +21 -4
  35. package/src/conformance/page.ts +8 -0
  36. package/src/host/types.ts +6 -3
  37. package/src/isolation/served.ts +12 -2
  38. package/src/react/frame.tsx +5 -2
  39. package/src/server/index.ts +2 -0
package/docs/DECISIONS.md CHANGED
@@ -1772,3 +1772,40 @@ own served flag in the `log` callback, a `-g` filter to find its tests.
1772
1772
  **Revisit when** an app needs an address that exists but must not be told apart from one that
1773
1773
  doesn't (then `at` grows a way to say "ask the app").
1774
1774
 
1775
+ ## P071 · 2026-10-12 · Adopting from the package alone: a README, examples, ADOPTING.md, and fixes a cold adopter hit · Accepted
1776
+
1777
+ **Decision.** A fresh agent adopted 0.2.2 from the npm package alone (Node and Workers, about 25
1778
+ minutes, 130 lines); everything it hit was documentation, or small. 0.2.3:
1779
+ - **Docs in the package:** a README with a quickstart; `docs/ADOPTING.md`, the adopter's path
1780
+ apart from DESIGN (the server, the page, its CSP, Workers, local development, the agent's
1781
+ tools, conformance, expected noise); DESIGN's snippet fixed (`Response.redirect` needs an
1782
+ absolute URL outside a browser; `configs` keyed `artifact`, the preset an artifact names by
1783
+ default; one secret name, `PORTHOLE_SECRET`).
1784
+ - **Runnable examples in the package:** `examples/app.mjs` (one app, runtime-agnostic, with a
1785
+ conformance test mode), `examples/node/`, `examples/workers/` (D1 migration, `wrangler.jsonc`
1786
+ with `run_worker_first`), `examples/conformance/` (the suite against it, three engines). The
1787
+ page reports a client module that fails to load; the sign-in page has no `form-action`, which
1788
+ would hold the redirect back to the content origin.
1789
+ - **`npx porthole`:** `secret` makes a `PORTHOLE_SECRET`; `d1-schema` prints the migration.
1790
+ - **One way to fill:** the config's `layout.kind: "fill"`, which the manual follows.
1791
+ `MountOptions.fill` and `<PortholeFrame fill>` are deprecated (they size the frame only).
1792
+ - **`'unsafe-eval'` in content's CSP is kept, and said:** content is the agent's own script
1793
+ (`'unsafe-inline'`), so eval adds no capability; libraries content uses (Vue's in-browser
1794
+ build, Alpine.js, Vega) and WebAssembly need it. Isolation comes from the origin, the sandbox and
1795
+ egress.
1796
+ - **Conformance for an app that serves only stored pages:** `instances.shell` is optional (the
1797
+ domain cases run on `artifact(scope, "1")`); `conformancePage(version)` is the exact test page
1798
+ (also from `/server`, free of Playwright); `entry.denied`, `atSignIn` and `completeSignIn` are
1799
+ optional; `entry.unknown: "derive"`; `conformanceProjects(devices)`; `onDemand`;
1800
+ `defineHostConformance` takes any `TestType` without a cast. Test mode is documented with its
1801
+ warning: never ship it.
1802
+ - **`14.inline-assets`** reports itself inapplicable where the page's own CSP (which an opaque
1803
+ frame inherits) blocks data: images or inline styles, as its siblings do (P058).
1804
+ - **Host errors never quote a located URL** (it carries a ticket): they name its origin.
1805
+
1806
+ **Why.** The cold adopter's top ten were all here: no README, the runnable example unshipped,
1807
+ adopter docs buried in DESIGN, no client snippet, a conformance runner that demanded what an
1808
+ artifact-only app lacks, two snippet bugs, no word on the page's CSP, two ways to fill (one of
1809
+ which left the manual wrong), Workers specifics, and local development.
1810
+ **Revisit when** a second cold adoption (after 0.3) finds friction these don't cover.
1811
+
package/docs/DESIGN.md CHANGED
@@ -4,6 +4,9 @@ The stable shape is in [ARCHITECTURE.md](ARCHITECTURE.md) and the reasons in
4
4
  [DECISIONS.md](DECISIONS.md). This is the concrete phase-1 plan. Web first:
5
5
  a framework-agnostic TypeScript core plus a thin React binding.
6
6
 
7
+ Adopting Porthole? Start with [ADOPTING.md](ADOPTING.md) and the package's `examples/`. Paths
8
+ below like `leak/…` and `ops/…` are Porthole's own repository, not the package.
9
+
7
10
  ## Threat model
8
11
 
9
12
  Two classes of attacker, handled by different layers (ARCHITECTURE § Trust
@@ -121,7 +124,9 @@ realm) and by the host where the engine passes the gesture up.
121
124
  `compile(config)` (`src/compile/compile.ts`) validates the config and returns:
122
125
 
123
126
  - `csp` / `cspDirectives`: the frame's policy. `default-src 'none'`; scripts may be
124
- inline (agent content is inline) plus `blob:` and the script origins; each other
127
+ inline (agent content is inline), `'unsafe-eval'` (content is the agent's own script already,
128
+ so eval adds no capability, and libraries content uses compile with it, WebAssembly too: P071),
129
+ plus `blob:` and the script origins; each other
125
130
  kind opens only to its origins; `connect-src 'none'` unless something is
126
131
  declared; `frame-src`, `object-src`, `base-uri`, `form-action` all `'none'`;
127
132
  `webrtc 'block'`. Never `'self'` (P022). Empty in url mode.
@@ -351,15 +356,16 @@ with redirect entry):
351
356
  - `source`: a stored page by id and version;
352
357
  - `entry.at`: the instance a clean address's path names (redirect entry).
353
358
 
354
- **An adopter's whole wiring** (the kit reference app, `packages/porthole/leak/kit/app.ts`, is
355
- this, runnable):
359
+ **An adopter's whole wiring** (the package's `examples/app.mjs` is this, runnable on Node and
360
+ Workers; docs/ADOPTING.md walks through it):
356
361
 
357
362
  ```ts
358
363
  const content = createContentHost<Viewer>({
359
364
  domain: env.CONTENT_DOMAIN, // "content.example.com" | "content.localhost:8790"; "" = off
360
365
  appOrigins: [env.APP_ORIGIN], // frame-ancestors, and the clash guard
361
- secret: env.CONTENT_SECRET, tickets: d1TicketStore(env.DB),
362
- configs: (source) => ({ page: presets.artifact({ isolation: "domain", contentOrigins: [source] }) }),
366
+ secret: env.PORTHOLE_SECRET, tickets: d1TicketStore(env.DB), // npx porthole secret
367
+ // Keyed by the preset a stored page names: an artifact's is "artifact" unless it says otherwise.
368
+ configs: (source) => ({ artifact: presets.artifact({ isolation: "domain", contentOrigins: [source] }) }),
363
369
  name: prefixedName("a-"), reserved: ["p-*"], // only labels the app itself serves there
364
370
  instance: (proposal, viewer) => mapToMyInstance(proposal), // a proposal: validate, derive the scope
365
371
  access: async (instance, viewer) =>
@@ -369,7 +375,8 @@ const content = createContentHost<Viewer>({
369
375
  entry: {
370
376
  authorizeUrl: `${env.APP_ORIGIN}/porthole/authorize`,
371
377
  at: (scope, path) => pageAt(scope, path), // "/" → latest, "/v/3" → version 3
372
- signIn: (returnTo) => Response.redirect(`/login?next=${encodeURIComponent(returnTo)}`, 303),
378
+ // Absolute: outside a browser, Response.redirect has no base URL.
379
+ signIn: (returnTo) => Response.redirect(`${env.APP_ORIGIN}/login?next=${encodeURIComponent(returnTo)}`, 303),
373
380
  },
374
381
  health: { probe: nodeProbe(), onChange: (view) => pushToClients(view) }, // optional: the opaque fallback
375
382
  });
@@ -0,0 +1,234 @@
1
+ // A whole Porthole app, runtime-agnostic (a web `Request` in, a `Response` out): agents' HTML
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.
4
+ //
5
+ // What is the app's own here (the policy): who is signed in (a cookie), which pages exist, who
6
+ // may see each. Everything else is Porthole's. Copy this file and replace the policy.
7
+ import { presets } from "@botiverse/porthole";
8
+ import { conformancePage, createContentHost, prefixedName } from "@botiverse/porthole/server";
9
+
10
+ /** The config a page is shown under: served on its own origin, or opaque while that's down. */
11
+ export const pageConfig = (contentSource) =>
12
+ presets.artifact({
13
+ // A whole-page viewer: the frame fills its box, and the agent's manual says so.
14
+ layout: { kind: "fill" },
15
+ ...(contentSource === null ? {} : { isolation: "domain", contentOrigins: [contentSource] }),
16
+ });
17
+
18
+ /** The stored pages: id → versions. An app keeps them in its database. */
19
+ const PAGES = {
20
+ hello: {
21
+ owner: null,
22
+ versions: {
23
+ 1: `<!doctype html><html><head><title>Hello</title></head><body><h1>Hello from an agent</h1><p id="when"></p><script>document.getElementById("when").textContent = new Date().toDateString();</script></body></html>`,
24
+ },
25
+ },
26
+ };
27
+
28
+ const viewerOf = (request) => {
29
+ const found = /(?:^|;\s*)example-viewer=([a-z]{1,20})(?:;|$)/u.exec(
30
+ request.headers.get("cookie") ?? "",
31
+ );
32
+ return found === null ? null : found[1];
33
+ };
34
+
35
+ const html = (body, headers = {}) =>
36
+ new Response(body, { headers: { "content-type": "text/html; charset=utf-8", ...headers } });
37
+
38
+ const escape = (text) => text.replace(/[&<>"']/gu, (char) => `&#${char.charCodeAt(0)};`);
39
+
40
+ /** Only a path of the app's own comes back from sign-in: never another site's address. */
41
+ const ownPath = (next, appOrigin) => {
42
+ if (next?.startsWith(`${appOrigin}/`)) next = next.slice(appOrigin.length);
43
+ return next?.startsWith("/") && !next.startsWith("//") && !next.includes("\\") ? next : "/";
44
+ };
45
+
46
+ /**
47
+ * @param {{ appOrigin: string, contentDomain: string, secret: string, tickets?: import("@botiverse/porthole/server").TicketStore,
48
+ * health?: import("@botiverse/porthole/server").HealthOptions, conformance?: boolean, client: (path: string) => Promise<Response | null> }} settings
49
+ */
50
+ export function makeApp(settings) {
51
+ const { appOrigin } = settings;
52
+ const pages = { ...PAGES };
53
+ // TEST MODE, for Porthole's conformance runner only (examples/conformance): pages the suite
54
+ // names itself, and one page no one may see. NEVER enable it in production: anyone signed in
55
+ // could then make content origins of their own choosing.
56
+ if (settings.conformance === true) {
57
+ pages.conformance = {
58
+ owner: null,
59
+ versions: { 1: conformancePage("1"), 2: conformancePage("2") },
60
+ };
61
+ pages.private = { owner: "nobody", versions: { 1: "<!doctype html><p>private</p>" } };
62
+ }
63
+ /** Who may see an instance: anyone signed in, but a page with an owner only its owner. */
64
+ const accessOf = (instance, viewer) => {
65
+ const owner = pages[page(instance.scope) ?? ""]?.owner ?? null;
66
+ return viewer !== null && (owner === null || owner === viewer)
67
+ ? { viewer, subject: viewer }
68
+ : null;
69
+ };
70
+ const page = (scope) =>
71
+ pages[scope]
72
+ ? scope
73
+ : settings.conformance === true && /^t-[a-z0-9-]{1,40}$/u.test(scope)
74
+ ? "conformance"
75
+ : null;
76
+
77
+ const content = createContentHost({
78
+ domain: settings.contentDomain,
79
+ appOrigins: [appOrigin],
80
+ secret: settings.secret,
81
+ ...(settings.tickets === undefined ? {} : { tickets: settings.tickets }),
82
+ // The key is the preset a stored page names: an artifact's defaults to "artifact".
83
+ configs: (source) => ({ artifact: pageConfig(source) }),
84
+ name: prefixedName("a-"),
85
+ // Policy 1: the instance a frame request proposes. The server picks the scope, never the client.
86
+ instance: (proposal) => {
87
+ const { document } = proposal;
88
+ if (document.kind !== "artifact") return null;
89
+ if (
90
+ settings.conformance === true &&
91
+ document.id === "conformance" &&
92
+ /^[a-z0-9-]{1,38}$/u.test(proposal.scope)
93
+ ) {
94
+ return {
95
+ scope: `t-${proposal.scope}`,
96
+ document: { kind: "artifact", id: "conformance", version: document.version },
97
+ };
98
+ }
99
+ return pages[document.id]?.versions[document.version] === undefined
100
+ ? null
101
+ : {
102
+ scope: document.id,
103
+ document: { kind: "artifact", id: document.id, version: document.version },
104
+ };
105
+ },
106
+ // Policy 2: who may see it.
107
+ access: (instance, viewer) => accessOf(instance, viewer),
108
+ // Policy 3: a stored page, by id and version.
109
+ source: async (id, version) => {
110
+ const stored = pages[id]?.versions[version];
111
+ return stored === undefined ? null : { html: stored };
112
+ },
113
+ // Policy 4: what a clean address names: `/` the latest version, `/v/<n>` version n.
114
+ entry: {
115
+ authorizeUrl: `${appOrigin}/porthole/authorize`,
116
+ at: (scope, path) => {
117
+ const id = page(scope);
118
+ if (id === null) return null;
119
+ const version =
120
+ path === "/" ? Object.keys(pages[id].versions).at(-1) : /^\/v\/(\d+)$/u.exec(path)?.[1];
121
+ return pages[id].versions[version] === undefined
122
+ ? null
123
+ : { scope, document: { kind: "artifact", id, version } };
124
+ },
125
+ // The app's own sign-in, coming back to the authorize route. Absolute: Node's
126
+ // Response.redirect needs one.
127
+ signIn: (returnTo) =>
128
+ Response.redirect(`${appOrigin}/login?next=${encodeURIComponent(returnTo)}`, 303),
129
+ },
130
+ ...(settings.health === undefined ? {} : { health: settings.health }),
131
+ log: (event) => console.log(JSON.stringify(event)),
132
+ });
133
+ const issue = content.issue(viewerOf);
134
+ const authorize = content.authorize(viewerOf);
135
+
136
+ async function handle(request) {
137
+ const url = new URL(request.url);
138
+ const viewer = viewerOf(request);
139
+ if (url.pathname === "/porthole/authorize") return authorize(request);
140
+ if (url.pathname === "/api/frames") return issue(request);
141
+ if (url.pathname.startsWith("/porthole-client/")) {
142
+ return (
143
+ (await settings.client(url.pathname.slice("/porthole-client".length))) ??
144
+ new Response("not found", { status: 404 })
145
+ );
146
+ }
147
+ if (url.pathname === "/api/meta") {
148
+ // What the page needs: whether frames are served, and the config to show them under.
149
+ const meta = content.meta();
150
+ return Response.json({
151
+ ...meta,
152
+ config: pageConfig(meta.served ? meta.contentSource : null),
153
+ viewer,
154
+ });
155
+ }
156
+ if (url.pathname === "/login" && request.method === "GET") {
157
+ const next = escape(ownPath(url.searchParams.get("next"), appOrigin));
158
+ return html(
159
+ `<!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>`,
160
+ {
161
+ "content-security-policy":
162
+ // No form-action: after the sign-in POST, redirect entry goes on through the
163
+ // content origin, and form-action holds every redirect of a submission.
164
+ "default-src 'none'; frame-ancestors 'none'",
165
+ },
166
+ );
167
+ }
168
+ if (url.pathname === "/login" && request.method === "POST") {
169
+ const next = ownPath(new URLSearchParams(await request.text()).get("next"), appOrigin);
170
+ return new Response(null, {
171
+ status: 303,
172
+ headers: {
173
+ location: next,
174
+ "set-cookie": `example-viewer=ada; Path=/; HttpOnly; SameSite=Lax${appOrigin.startsWith("https:") ? "; Secure" : ""}`,
175
+ },
176
+ });
177
+ }
178
+ if (url.pathname === "/api/page") {
179
+ // The opaque fallback's content: the latest version, for a viewer who may see it.
180
+ const id = url.searchParams.get("id") ?? "";
181
+ const latest = pages[id] === undefined ? undefined : Object.keys(pages[id].versions).at(-1);
182
+ const instance =
183
+ latest === undefined
184
+ ? null
185
+ : { scope: id, document: { kind: "artifact", id, version: latest } };
186
+ const grant = instance === null ? null : accessOf(instance, viewer);
187
+ return grant === null
188
+ ? new Response("not found", { status: 404 })
189
+ : new Response(pages[id].versions[latest], {
190
+ headers: { "content-type": "text/html; charset=utf-8" },
191
+ });
192
+ }
193
+ if (url.pathname === "/") {
194
+ if (viewer === null) return Response.redirect(`${appOrigin}/login?next=/`, 303);
195
+ const id = url.searchParams.get("page") ?? "hello";
196
+ if (pages[id] === undefined) return new Response("not found", { status: 404 });
197
+ return html(viewerPage(id), {
198
+ // The embedding page's CSP: its scripts by nonce, and frames only from content origins
199
+ // (content.frameSources). An opaque display inherits this policy too, so it leaves
200
+ // img/media/font/style/worker open to what inline content uses (docs/ADOPTING.md).
201
+ "content-security-policy": `default-src 'self'; script-src 'self' 'nonce-${NONCE}'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src data: blob:; font-src data:; worker-src blob:; frame-src ${content.frameSources.length === 0 ? "'none'" : content.frameSources.join(" ")}; base-uri 'none'; frame-ancestors 'none'`,
202
+ });
203
+ }
204
+ return new Response("not found", { status: 404 });
205
+ }
206
+
207
+ // A fixed nonce keeps the example short; an app makes one per response.
208
+ const NONCE = "example-nonce";
209
+ const viewerPage = (
210
+ id,
211
+ ) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Pages</title>
212
+ <style>body{font-family:system-ui;margin:24px} #frame{height:480px;border:1px solid #8884} #problem{color:#b00}</style></head>
213
+ <body><main id="app"><p>Signed in. <a id="open-tab" href="${escape(content.urlOf(id) ?? "#")}" target="_blank" rel="noopener">Open in a new tab</a></p>
214
+ <div id="frame"></div><p id="problem" role="alert"></p></main>
215
+ <script type="importmap" nonce="${NONCE}">{"imports":{"@botiverse/porthole":"/porthole-client/index.js"}}</script>
216
+ <script type="module" nonce="${NONCE}">
217
+ const problem = (text) => { document.getElementById("problem").textContent = text; };
218
+ // The client module failing to load would otherwise show nothing at all.
219
+ import("@botiverse/porthole").then(async ({ createHost, httpLocator }) => {
220
+ const meta = await (await fetch("/api/meta")).json();
221
+ const host = createHost(meta.config, { locator: httpLocator("/api/frames"), nonce: ${JSON.stringify(NONCE)} });
222
+ const display = host.mount(document.getElementById("frame"), {
223
+ displayId: ${JSON.stringify(id)}, title: ${JSON.stringify(id)}, scheme: "light",
224
+ // Served: located by the issue endpoint. Opaque (frames not served now): the same page, inline.
225
+ ...(meta.served ? { instance: { scope: ${JSON.stringify(id)}, document: { kind: "artifact", id: ${JSON.stringify(id)}, version: "1" } } } : {}),
226
+ });
227
+ if (!meta.served) display.setContent(await (await fetch("/api/page?id=${encodeURIComponent(id)}")).text());
228
+ display.on("outcome", (outcome) => { if (outcome.state !== "loaded") problem("The page couldn't be shown here (" + (outcome.reason ?? outcome.state) + "): open it in a new tab."); });
229
+ display.on("hostError", (error) => problem(error.message));
230
+ }, (error) => problem("Porthole's client didn't load: " + error.message));
231
+ </script></body></html>`;
232
+
233
+ return { content, handle };
234
+ }
@@ -0,0 +1,28 @@
1
+ // Porthole's conformance suite against the example app, on Chromium, WebKit and Firefox:
2
+ // npx playwright test -c node_modules/@botiverse/porthole/examples/conformance/playwright.config.mjs
3
+ // It starts the Node example in TEST MODE (PORTHOLE_CONFORMANCE=1): never ship that.
4
+ import { defineConfig, devices } from "@playwright/test";
5
+ import { conformanceProjects } from "@botiverse/porthole/conformance";
6
+
7
+ const port = Number(process.env.PORTHOLE_EXAMPLE_PORT ?? 8796);
8
+
9
+ export default defineConfig({
10
+ testDir: ".",
11
+ testMatch: "*.spec.mjs",
12
+ outputDir: process.env.PORTHOLE_EXAMPLE_RESULTS ?? "test-results",
13
+ fullyParallel: true,
14
+ reporter: [["list"]],
15
+ projects: conformanceProjects(devices, {
16
+ engines: (process.env.PORTHOLE_ENGINES ?? "chromium,webkit,firefox").split(","),
17
+ }),
18
+ webServer: {
19
+ command: "node ../node/server.mjs",
20
+ cwd: import.meta.dirname,
21
+ url: `http://localhost:${port}/api/meta`,
22
+ env: {
23
+ PORT: String(port),
24
+ PORTHOLE_SECRET: "example-secret-for-tests-only-0123456789",
25
+ PORTHOLE_CONFORMANCE: "1",
26
+ },
27
+ },
28
+ });
@@ -0,0 +1,36 @@
1
+ // Porthole's conformance suite (leak probes, served cases, redirect entry) against the example
2
+ // app's real page, signed in, through its real issue endpoint. The app runs in TEST MODE
3
+ // (PORTHOLE_CONFORMANCE=1, examples/app.mjs): pages the suite names itself. Never ship it.
4
+ import { test } from "@playwright/test";
5
+ import { defineHostConformance } from "@botiverse/porthole/conformance";
6
+ import { pageConfig } from "../app.mjs";
7
+
8
+ const port = Number(process.env.PORTHOLE_EXAMPLE_PORT ?? 8796);
9
+ const app = `http://localhost:${port}`;
10
+ const clean = (label, path = "/") => `http://${label}.content.localhost:${port}${path}`;
11
+
12
+ defineHostConformance(test, {
13
+ name: "example",
14
+ // The app's real page, as a person sees it: signed in.
15
+ open: async (page) => {
16
+ await page.goto(`${app}/login?next=/`);
17
+ await Promise.all([page.waitForURL(`${app}/`), page.click("#sign-in")]);
18
+ },
19
+ issue: { url: "/api/frames" },
20
+ config: () => pageConfig(`http://*.content.localhost:${port}`),
21
+ // A stored-pages app: its test page's two versions (the domain cases run on version 1).
22
+ instances: {
23
+ artifact: (scope, version) => ({
24
+ scope,
25
+ document: { kind: "artifact", id: "conformance", version },
26
+ }),
27
+ },
28
+ entry: {
29
+ // The clean address of the test page's version 1 (`/` is its latest).
30
+ url: (scope) => clean(`a-t-${scope}`, "/v/1"),
31
+ denied: () => clean("a-private"),
32
+ atSignIn: async (page) => (await page.locator("#sign-in-page").count()) > 0,
33
+ completeSignIn: (page) => page.click("#sign-in"),
34
+ unknown: "derive",
35
+ },
36
+ });
@@ -0,0 +1,75 @@
1
+ // The example app on Node: node:http, with Porthole's Node adapter in front of it.
2
+ //
3
+ // PORTHOLE_SECRET=$(npx porthole secret) node node_modules/@botiverse/porthole/examples/node/server.mjs
4
+ // open http://localhost:8790 (content is served on http://*.content.localhost:8790, the same server)
5
+ //
6
+ // Locally the app is http://localhost:<port> and content http://*.content.localhost:<port>: every
7
+ // *.localhost name is loopback in browsers, and each is a site of its own, so they never share
8
+ // cookies or storage. In production: https://app.example.com and content.example-usercontent.com.
9
+ import { readFile } from "node:fs/promises";
10
+ import { createServer } from "node:http";
11
+ import { memoryTicketStore } from "@botiverse/porthole/server";
12
+ import { nodeHost, nodeProbe, sendResponse, toRequest } from "@botiverse/porthole/node";
13
+ import { makeApp } from "../app.mjs";
14
+
15
+ /** Porthole's browser modules (the package's dist/), served to the app's page. */
16
+ const dist = new URL("../dist/", import.meta.resolve("@botiverse/porthole"));
17
+ const TYPES = { ".js": "text/javascript; charset=utf-8" };
18
+
19
+ export function start({
20
+ port = 8790,
21
+ secret = process.env.PORTHOLE_SECRET,
22
+ conformance = process.env.PORTHOLE_CONFORMANCE === "1",
23
+ } = {}) {
24
+ if (!secret) throw new Error("Set PORTHOLE_SECRET (npx porthole secret)");
25
+ const appOrigin = `http://localhost:${port}`;
26
+ const { content, handle } = makeApp({
27
+ appOrigin,
28
+ contentDomain: `content.localhost:${port}`,
29
+ secret,
30
+ tickets: memoryTicketStore(),
31
+ // The opaque fallback: frames are served once the content domain answers over the network.
32
+ health: { probe: nodeProbe() },
33
+ conformance,
34
+ client: async (path) => {
35
+ if (!/^\/[\w/.-]+\.js$/u.test(path) || path.includes("..")) return null;
36
+ return readFile(new URL(`.${path}`, dist)).then(
37
+ (body) => new Response(body, { headers: { "content-type": TYPES[".js"] } }),
38
+ () => null,
39
+ );
40
+ },
41
+ });
42
+ // Content hosts go to Porthole; everything else to the app.
43
+ const porthole = nodeHost(content, {
44
+ request: (request, response) => {
45
+ handle(toRequest(request, "http")).then(
46
+ (answer) => sendResponse(response, answer),
47
+ (error) => {
48
+ console.error(error);
49
+ response.writeHead(500).end();
50
+ },
51
+ );
52
+ },
53
+ });
54
+ const server = createServer(porthole.request);
55
+ server.on("upgrade", porthole.upgrade);
56
+ return new Promise((resolve) =>
57
+ server.listen(port, () => {
58
+ content.start();
59
+ resolve({
60
+ server,
61
+ content,
62
+ appOrigin,
63
+ close: () => {
64
+ content.close();
65
+ server.close();
66
+ },
67
+ });
68
+ }),
69
+ );
70
+ }
71
+
72
+ if (import.meta.main) {
73
+ const { appOrigin } = await start({ port: Number(process.env.PORT ?? 8790) });
74
+ console.log(`The app: ${appOrigin}`);
75
+ }
@@ -0,0 +1,2 @@
1
+ CREATE TABLE IF NOT EXISTS porthole_tickets (id TEXT PRIMARY KEY, record TEXT NOT NULL, expires_at INTEGER NOT NULL);
2
+ CREATE INDEX IF NOT EXISTS porthole_tickets_expires_at ON porthole_tickets (expires_at);
@@ -0,0 +1,33 @@
1
+ // The example app on Cloudflare Workers: tickets in D1, Porthole's browser modules as static
2
+ // assets. No nodejs_compat needed.
3
+ //
4
+ // npx porthole d1-schema > migrations/0001_porthole_tickets.sql (already here)
5
+ // echo "PORTHOLE_SECRET=$(npx porthole secret)" > .dev.vars
6
+ // npx wrangler d1 migrations apply porthole-example --local && npx wrangler dev --port 8793
7
+ // open http://localhost:8793 (content: http://*.content.localhost:8793)
8
+ //
9
+ // wrangler.jsonc sets `run_worker_first`: every request, the content domain's included, comes
10
+ // here first, so static assets are never answered on a content origin.
11
+ import { d1TicketStore } from "@botiverse/porthole/server";
12
+ import { makeApp } from "../app.mjs";
13
+
14
+ let app = null; // one per isolate, made from the first request's env
15
+
16
+ export default {
17
+ async fetch(request, env) {
18
+ app ??= makeApp({
19
+ appOrigin: env.APP_ORIGIN,
20
+ contentDomain: env.CONTENT_DOMAIN,
21
+ secret: env.PORTHOLE_SECRET,
22
+ tickets: d1TicketStore(env.DB),
23
+ conformance: env.PORTHOLE_CONFORMANCE === "1",
24
+ // Porthole's browser modules, from the assets directory (the package's dist/).
25
+ client: async (path) => {
26
+ const answer = await env.ASSETS.fetch(new URL(path, env.APP_ORIGIN));
27
+ return answer.ok ? answer : null;
28
+ },
29
+ });
30
+ // The content domain first (Porthole answers every request there), then the app.
31
+ return (await app.content.fetch(request)) ?? app.handle(request);
32
+ },
33
+ };
@@ -0,0 +1,19 @@
1
+ // The example app on Workers. In your app, point `assets.directory` at
2
+ // node_modules/@botiverse/porthole/dist (or your bundle of Porthole's client).
3
+ {
4
+ "name": "porthole-example",
5
+ "main": "worker.mjs",
6
+ "compatibility_date": "2026-10-01",
7
+ "vars": { "APP_ORIGIN": "http://localhost:8793", "CONTENT_DOMAIN": "content.localhost:8793" },
8
+ "d1_databases": [
9
+ {
10
+ "binding": "DB",
11
+ "database_name": "porthole-example",
12
+ "database_id": "00000000-0000-0000-0000-000000000000",
13
+ "migrations_dir": "migrations",
14
+ },
15
+ ],
16
+ // run_worker_first: every request (content origins included) goes through the Worker, so the
17
+ // app's static files are never served on a content origin.
18
+ "assets": { "directory": "../../dist", "binding": "ASSETS", "run_worker_first": true },
19
+ }
package/package.json CHANGED
@@ -1,12 +1,17 @@
1
1
  {
2
2
  "name": "@botiverse/porthole",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "description": "A host-side sandbox for agent-made HTML: isolation, egress hardening, a themed shell, gated host functions, and the agent manual, from one config.",
5
5
  "license": "Apache-2.0",
6
+ "bin": {
7
+ "porthole": "./dist/cli.js"
8
+ },
6
9
  "files": [
7
10
  "src",
8
11
  "dist",
9
- "docs"
12
+ "docs",
13
+ "examples",
14
+ "README.md"
10
15
  ],
11
16
  "type": "module",
12
17
  "sideEffects": false,
package/src/cli.ts ADDED
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `npx porthole <command>`: the setup steps an adopter would otherwise script (P071).
4
+ *
5
+ * porthole secret a new PORTHOLE_SECRET (32 random bytes, base64url)
6
+ * porthole d1-schema [table] the D1 ticket table's SQL, for a migration file
7
+ * (npx porthole d1-schema > migrations/0001_porthole_tickets.sql)
8
+ */
9
+ import { d1TicketSchema } from "./server/tickets.ts";
10
+
11
+ const USAGE = `Usage: porthole <command>
12
+
13
+ secret Print a new PORTHOLE_SECRET: 32 random bytes, base64url.
14
+ wrangler secret put PORTHOLE_SECRET, or your platform's secret store.
15
+ d1-schema [table] Print the D1 ticket table's SQL (default table porthole_tickets):
16
+ npx porthole d1-schema > migrations/0001_porthole_tickets.sql
17
+ `;
18
+
19
+ function base64url(bytes: Uint8Array): string {
20
+ let text = "";
21
+ for (const byte of bytes) {
22
+ text += String.fromCharCode(byte);
23
+ }
24
+ return btoa(text).replace(/\+/gu, "-").replace(/\//gu, "_").replace(/=+$/u, "");
25
+ }
26
+
27
+ /** Runs one command; returns what to print and the exit code. */
28
+ export function run(args: readonly string[]): { readonly out: string; readonly code: number } {
29
+ const [command, ...rest] = args;
30
+ try {
31
+ switch (command) {
32
+ case "secret":
33
+ return { out: `${base64url(crypto.getRandomValues(new Uint8Array(32)))}\n`, code: 0 };
34
+ case "d1-schema":
35
+ return { out: `${d1TicketSchema(rest[0])}\n`, code: 0 };
36
+ case undefined:
37
+ case "help":
38
+ case "--help":
39
+ case "-h":
40
+ return { out: USAGE, code: command === undefined ? 1 : 0 };
41
+ default:
42
+ return { out: `Unknown command ${JSON.stringify(command)}.\n\n${USAGE}`, code: 1 };
43
+ }
44
+ } catch (error) {
45
+ return { out: `${error instanceof Error ? error.message : String(error)}\n`, code: 1 };
46
+ }
47
+ }
48
+
49
+ // Run as a program (`porthole …`), not when imported (its test).
50
+ if (import.meta.main) {
51
+ const { out, code } = run(process.argv.slice(2));
52
+ (code === 0 ? process.stdout : process.stderr).write(out);
53
+ process.exitCode = code;
54
+ }