@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/examples/app.mjs CHANGED
@@ -1,19 +1,14 @@
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
- // 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
- });
7
+ // may see each, and what a clean address names. Everything else is Porthole's: one mount
8
+ // (`content.routes`, under /porthole) answers frames, the authorize route and the page's meta.
9
+ import { entryTarget } from "@botiverse/porthole";
10
+ import { conformancePage, prefixedName } from "@botiverse/porthole/server";
11
+ import { displays, kinds } from "./displays.mjs";
17
12
 
18
13
  /** The stored pages: id → versions. An app keeps them in its database. */
19
14
  const PAGES = {
@@ -37,18 +32,21 @@ const html = (body, headers = {}) =>
37
32
 
38
33
  const escape = (text) => text.replace(/[&<>"']/gu, (char) => `&#${char.charCodeAt(0)};`);
39
34
 
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
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
+ *
47
40
  * @param {{ appOrigin: string, contentDomain: string, secret: string, tickets?: import("@botiverse/porthole/server").TicketStore,
48
41
  * health?: import("@botiverse/porthole/server").HealthOptions, conformance?: boolean, client: (path: string) => Promise<Response | null> }} settings
49
42
  */
50
43
  export function makeApp(settings) {
51
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}/`;
52
50
  const pages = { ...PAGES };
53
51
  // TEST MODE, for Porthole's conformance runner only (examples/conformance): pages the suite
54
52
  // names itself, and one page no one may see. NEVER enable it in production: anyone signed in
@@ -60,6 +58,13 @@ export function makeApp(settings) {
60
58
  };
61
59
  pages.private = { owner: "nobody", versions: { 1: "<!doctype html><p>private</p>" } };
62
60
  }
61
+ const page = (scope) =>
62
+ pages[scope]
63
+ ? scope
64
+ : settings.conformance === true && /^t-[a-z0-9-]{1,40}$/u.test(scope)
65
+ ? "conformance"
66
+ : null;
67
+ const latest = (id) => Object.keys(pages[id].versions).at(-1);
63
68
  /** Who may see an instance: anyone signed in, but a page with an owner only its owner. */
64
69
  const accessOf = (instance, viewer) => {
65
70
  const owner = pages[page(instance.scope) ?? ""]?.owner ?? null;
@@ -67,20 +72,14 @@ export function makeApp(settings) {
67
72
  ? { viewer, subject: viewer }
68
73
  : null;
69
74
  };
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
75
 
77
- const content = createContentHost({
76
+ /** @type {import("@botiverse/porthole/server").ContentHostOptions<string>} */
77
+ const options = {
78
78
  domain: settings.contentDomain,
79
79
  appOrigins: [appOrigin],
80
80
  secret: settings.secret,
81
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) }),
82
+ displays,
84
83
  name: prefixedName("a-"),
85
84
  // Policy 1: the instance a frame request proposes. The server picks the scope, never the client.
86
85
  instance: (proposal) => {
@@ -110,18 +109,21 @@ export function makeApp(settings) {
110
109
  const stored = pages[id]?.versions[version];
111
110
  return stored === undefined ? null : { html: stored };
112
111
  },
113
- // Policy 4: what a clean address names: `/` the latest version, `/v/<n>` version n.
112
+ // Policy 4: what a clean address names: `/` the latest version, `/v/<n>` version n. And the
113
+ // reverse (pathOf), so frames come with their clean address for "open in a new tab".
114
114
  entry: {
115
- authorizeUrl: `${appOrigin}/porthole/authorize`,
116
115
  at: (scope, path) => {
117
116
  const id = page(scope);
118
117
  if (id === null) return null;
119
- const version =
120
- path === "/" ? Object.keys(pages[id].versions).at(-1) : /^\/v\/(\d+)$/u.exec(path)?.[1];
118
+ const version = path === "/" ? latest(id) : /^\/v\/(\d+)$/u.exec(path)?.[1];
121
119
  return pages[id].versions[version] === undefined
122
120
  ? null
123
121
  : { scope, document: { kind: "artifact", id, version } };
124
122
  },
123
+ pathOf: (instance) =>
124
+ instance.document.version === latest(page(instance.scope) ?? "hello")
125
+ ? "/"
126
+ : `/v/${instance.document.version}`,
125
127
  // The app's own sign-in, coming back to the authorize route. Absolute: Node's
126
128
  // Response.redirect needs one.
127
129
  signIn: (returnTo) =>
@@ -129,44 +131,53 @@ export function makeApp(settings) {
129
131
  },
130
132
  ...(settings.health === undefined ? {} : { health: settings.health }),
131
133
  log: (event) => console.log(JSON.stringify(event)),
132
- });
133
- const issue = content.issue(viewerOf);
134
- const authorize = content.authorize(viewerOf);
134
+ };
135
135
 
136
- async function handle(request) {
136
+ /** @param {Request} request @param {import("@botiverse/porthole/server").ContentHost<string>} content */
137
+ async function handle(request, content) {
137
138
  const url = new URL(request.url);
138
139
  const viewer = viewerOf(request);
139
- if (url.pathname === "/porthole/authorize") return authorize(request);
140
- if (url.pathname === "/api/frames") return issue(request);
140
+ // Frames, the authorize route and the page's meta, under /porthole.
141
+ const porthole = await content.routes(viewerOf)(request);
142
+ if (porthole !== null) return porthole;
143
+ if (url.pathname === "/porthole-client/displays.mjs") {
144
+ // The page's display kinds: the same as the server's, as a module.
145
+ return new Response(
146
+ `import { defineDisplays } from "@botiverse/porthole";\nexport const displays = defineDisplays(${JSON.stringify(kinds)});\n`,
147
+ { headers: { "content-type": "text/javascript; charset=utf-8" } },
148
+ );
149
+ }
141
150
  if (url.pathname.startsWith("/porthole-client/")) {
142
151
  return (
143
152
  (await settings.client(url.pathname.slice("/porthole-client".length))) ??
144
153
  new Response("not found", { status: 404 })
145
154
  );
146
155
  }
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
- });
156
+ if (url.pathname === "/api/page") {
157
+ // The opaque fallback's content: the latest version, for a viewer who may see it.
158
+ const id = url.searchParams.get("id") ?? "";
159
+ const version = pages[id] === undefined ? undefined : latest(id);
160
+ const instance =
161
+ version === undefined ? null : { scope: id, document: { kind: "artifact", id, version } };
162
+ return instance === null || accessOf(instance, viewer) === null
163
+ ? new Response("not found", { status: 404 })
164
+ : new Response(pages[id].versions[version], {
165
+ headers: { "content-type": "text/html; charset=utf-8" },
166
+ });
155
167
  }
156
168
  if (url.pathname === "/login" && request.method === "GET") {
157
- const next = escape(ownPath(url.searchParams.get("next"), appOrigin));
169
+ const next = escape(backTo(url.searchParams.get("next")));
158
170
  return html(
159
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>`,
160
172
  {
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'",
173
+ // No form-action: after the sign-in POST, redirect entry goes on through the content
174
+ // origin, and form-action holds every redirect of a submission (docs/ADOPTING.md).
175
+ "content-security-policy": "default-src 'none'; frame-ancestors 'none'",
165
176
  },
166
177
  );
167
178
  }
168
179
  if (url.pathname === "/login" && request.method === "POST") {
169
- const next = ownPath(new URLSearchParams(await request.text()).get("next"), appOrigin);
180
+ const next = backTo(new URLSearchParams(await request.text()).get("next"));
170
181
  return new Response(null, {
171
182
  status: 303,
172
183
  headers: {
@@ -175,30 +186,16 @@ export function makeApp(settings) {
175
186
  },
176
187
  });
177
188
  }
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
189
  if (url.pathname === "/") {
194
190
  if (viewer === null) return Response.redirect(`${appOrigin}/login?next=/`, 303);
195
191
  const id = url.searchParams.get("page") ?? "hello";
196
192
  if (pages[id] === undefined) return new Response("not found", { status: 404 });
193
+ const frames = content.frameSources;
197
194
  return html(viewerPage(id), {
198
195
  // 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'`,
196
+ // and the authorize route (content.frameSources). An opaque display inherits this policy
197
+ // too, so it leaves img/media/font/style/worker open to what inline content uses.
198
+ "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 ${frames.length === 0 ? "'none'" : frames.join(" ")}; base-uri 'none'; frame-ancestors 'none'`,
202
199
  });
203
200
  }
204
201
  return new Response("not found", { status: 404 });
@@ -210,25 +207,32 @@ export function makeApp(settings) {
210
207
  id,
211
208
  ) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Pages</title>
212
209
  <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>
210
+ <body><main id="app"><p>Signed in. <button id="open-tab" type="button">Open in a new tab</button></p>
214
211
  <div id="frame"></div><p id="problem" role="alert"></p></main>
215
212
  <script type="importmap" nonce="${NONCE}">{"imports":{"@botiverse/porthole":"/porthole-client/index.js"}}</script>
216
213
  <script type="module" nonce="${NONCE}">
217
214
  const problem = (text) => { document.getElementById("problem").textContent = text; };
218
215
  // 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)} });
216
+ Promise.all([import("@botiverse/porthole"), import("/porthole-client/displays.mjs")]).then(async ([{ createHost, frameFallback, portholeClient }, { displays }]) => {
217
+ const porthole = portholeClient({ displays }); // the server's /porthole routes
218
+ const meta = await porthole.refresh();
219
+ const instance = { scope: ${JSON.stringify(id)}, document: { kind: "artifact", id: ${JSON.stringify(id)}, version: ${JSON.stringify(latest(id))} } };
220
+ // "Open in a new tab": the clean address, opened inside the click.
221
+ document.getElementById("open-tab").addEventListener("click", () => porthole.openInTab(instance));
222
+ // Served while frames are served (located through /porthole/frames); opaque, inline, while not.
223
+ const host = createHost(porthole.config("artifact"), { locator: porthole, nonce: ${JSON.stringify(NONCE)} });
222
224
  const display = host.mount(document.getElementById("frame"), {
223
225
  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
+ ...(meta?.served ? { instance } : {}),
227
+ });
228
+ if (!meta?.served) display.setContent(await (await fetch("/api/page?id=${encodeURIComponent(id)}")).text());
229
+ display.on("outcome", (outcome) => {
230
+ const fallback = frameFallback(outcome);
231
+ if (fallback !== null) problem(fallback.title + ": " + fallback.message);
226
232
  });
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
233
  display.on("hostError", (error) => problem(error.message));
230
234
  }, (error) => problem("Porthole's client didn't load: " + error.message));
231
235
  </script></body></html>`;
232
236
 
233
- return { content, handle };
237
+ return { options, handle };
234
238
  }
@@ -0,0 +1,23 @@
1
+ // The example app's own page, as a person uses it: signed in, its page shown served on its own
2
+ // origin, and "Open in a new tab" opening the clean address.
3
+ import { expect, test } from "@playwright/test";
4
+
5
+ const port = Number(process.env.PORTHOLE_EXAMPLE_PORT ?? 8796);
6
+ const app = `http://localhost:${port}`;
7
+
8
+ test("the viewer shows the page on its own origin, and opens it in a new tab", async ({
9
+ page,
10
+ context,
11
+ }) => {
12
+ await page.goto(`${app}/login?next=/`);
13
+ await Promise.all([page.waitForURL(`${app}/`), page.click("#sign-in")]);
14
+ const frame = page.frameLocator("#frame iframe");
15
+ await expect(frame.locator("h1")).toHaveText("Hello from an agent");
16
+ const element = await page.locator("#frame iframe").elementHandle();
17
+ const origin = await (await element?.contentFrame())?.evaluate(() => location.origin);
18
+ expect(origin).toBe(`http://a-hello.content.localhost:${port}`);
19
+ const [tab] = await Promise.all([context.waitForEvent("page"), page.click("#open-tab")]);
20
+ await tab.waitForURL(`http://a-hello.content.localhost:${port}/`);
21
+ await expect(tab.locator("h1")).toHaveText("Hello from an agent");
22
+ await expect(page.locator("#problem")).toHaveText("");
23
+ });
@@ -11,14 +11,15 @@ 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
  }),
18
19
  webServer: {
19
20
  command: "node ../node/server.mjs",
20
21
  cwd: import.meta.dirname,
21
- url: `http://localhost:${port}/api/meta`,
22
+ url: `http://localhost:${port}/porthole/meta`,
22
23
  env: {
23
24
  PORT: String(port),
24
25
  PORTHOLE_SECRET: "example-secret-for-tests-only-0123456789",
@@ -3,7 +3,7 @@
3
3
  // (PORTHOLE_CONFORMANCE=1, examples/app.mjs): pages the suite names itself. Never ship it.
4
4
  import { test } from "@playwright/test";
5
5
  import { defineHostConformance } from "@botiverse/porthole/conformance";
6
- import { pageConfig } from "../app.mjs";
6
+ import { displays } from "../displays.mjs";
7
7
 
8
8
  const port = Number(process.env.PORTHOLE_EXAMPLE_PORT ?? 8796);
9
9
  const app = `http://localhost:${port}`;
@@ -16,8 +16,11 @@ defineHostConformance(test, {
16
16
  await page.goto(`${app}/login?next=/`);
17
17
  await Promise.all([page.waitForURL(`${app}/`), page.click("#sign-in")]);
18
18
  },
19
- issue: { url: "/api/frames" },
20
- config: () => pageConfig(`http://*.content.localhost:${port}`),
19
+ // The app's frame endpoint (content.routes), and its display kinds.
20
+ issue: { url: "/porthole/frames" },
21
+ displays,
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}`,
21
24
  // A stored-pages app: its test page's two versions (the domain cases run on version 1).
22
25
  instances: {
23
26
  artifact: (scope, version) => ({
@@ -0,0 +1,21 @@
1
+ // The app's display kinds, in one place (defineDisplays): the server serves under them, the page
2
+ // frames under them, and the agent's tools and manual come from them. Shared by the server, the
3
+ // page (served to it as a module) and the agent's tools (examples/mcp).
4
+ import { defineDisplays } from "@botiverse/porthole";
5
+
6
+ /** The kinds as plain data: the server also hands them to the page as a module. */
7
+ export const kinds = {
8
+ // A stored page: a kind named "artifact" is the preset an artifact instance names by default.
9
+ artifact: {
10
+ preset: "artifact",
11
+ options: {
12
+ // A whole-page viewer: the frame fills its box, and the agent's manual says so.
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.
16
+ guide: { toolName: "show_page", guideToolName: "page_guide" },
17
+ },
18
+ },
19
+ };
20
+
21
+ export const displays = defineDisplays(kinds);
@@ -0,0 +1,121 @@
1
+ // The agent's side, as an MCP server over stdio: show_page, page_guide and check_page, each a
2
+ // tool definition Porthole makes from the app's display kind (names, descriptions and JSON
3
+ // Schemas), answered by Porthole's own helpers. With the official MCP SDK, register the same
4
+ // definitions and handlers; this file speaks the protocol by hand to stay dependency-free.
5
+ //
6
+ // node node_modules/@botiverse/porthole/examples/mcp/server.mjs (an MCP client starts it)
7
+ //
8
+ // show_page refuses only what certainly fails (over the size, nested frames, document.write…) and
9
+ // says exactly what to change; everything else comes back as warnings with the result.
10
+ // check_page runs the page in the real sandbox where this machine has a browser (Playwright);
11
+ // without one, it says so and gives the lint alone (docs/ADOPTING.md: hosts without a browser).
12
+ import { createInterface } from "node:readline";
13
+ import {
14
+ admitContent,
15
+ answerGuide,
16
+ checkTool,
17
+ guideTool,
18
+ lintContent,
19
+ showTool,
20
+ } from "@botiverse/porthole";
21
+ import { displays } from "../displays.mjs";
22
+
23
+ // The manual as served pages get it (the kind's served config, no real origin needed).
24
+ const config = displays.guideConfig("artifact", "served");
25
+ const tools = [showTool(config), guideTool(config), checkTool(config)];
26
+ const shown = new Map(); // title → html: an app stores and shows it (examples/app.mjs)
27
+
28
+ /** A browser, if this machine has Playwright: the check's driver. */
29
+ let browser = null;
30
+ async function driver() {
31
+ try {
32
+ const [{ chromium }, { playwrightDriver }] = await Promise.all([
33
+ import("@playwright/test"),
34
+ import("@botiverse/porthole/check"),
35
+ ]);
36
+ browser ??= await chromium.launch();
37
+ return playwrightDriver(browser);
38
+ } catch {
39
+ return null;
40
+ }
41
+ }
42
+
43
+ const text = (value, isError = false) => ({
44
+ content: [{ type: "text", text: value }],
45
+ ...(isError ? { isError: true } : {}),
46
+ });
47
+
48
+ async function call(name, args) {
49
+ if (name === showTool(config).name) {
50
+ const admitted = admitContent(config, String(args?.html ?? ""));
51
+ if (!admitted.ok) return text(admitted.refusal, true);
52
+ shown.set(String(args?.title ?? "Untitled"), admitted.content);
53
+ return text(admitted.note ?? "Shown.");
54
+ }
55
+ if (name === guideTool(config).name) {
56
+ const answer = answerGuide(config, args);
57
+ return "error" in answer ? text(answer.error, true) : text(answer.text);
58
+ }
59
+ if (name === checkTool(config).name) {
60
+ const html = String(args?.html ?? "");
61
+ const check = await driver();
62
+ if (check === null) {
63
+ const findings = lintContent(config, html);
64
+ return text(
65
+ `No browser here, so only what can be told without running it:\n${findings.length === 0 ? "nothing to fix." : findings.map((each) => `- ${each.message}`).join("\n")}`,
66
+ );
67
+ }
68
+ const { checkPage } = await import("@botiverse/porthole/check");
69
+ const report = await checkPage({
70
+ config,
71
+ content: html,
72
+ driver: check,
73
+ ...(Array.isArray(args?.widths) ? { widths: args.widths } : {}),
74
+ ...(Array.isArray(args?.schemes) ? { schemes: args.schemes } : {}),
75
+ });
76
+ return text(report.text, !report.ok);
77
+ }
78
+ throw Object.assign(new Error(`No tool ${name}`), { code: -32602 });
79
+ }
80
+
81
+ async function respond(message) {
82
+ switch (message.method) {
83
+ case "initialize":
84
+ return {
85
+ protocolVersion: message.params?.protocolVersion ?? "2025-06-18",
86
+ capabilities: { tools: {} },
87
+ serverInfo: { name: "porthole-example", version: "1" },
88
+ instructions: `Call ${guideTool(config).name} once before your first page, and ${checkTool(config).name} before ${showTool(config).name}.`,
89
+ };
90
+ case "tools/list":
91
+ return { tools };
92
+ case "tools/call":
93
+ return call(message.params?.name, message.params?.arguments ?? {});
94
+ case "ping":
95
+ return {};
96
+ default:
97
+ throw Object.assign(new Error(`No method ${message.method}`), { code: -32601 });
98
+ }
99
+ }
100
+
101
+ const lines = createInterface({ input: process.stdin });
102
+ lines.on("line", (line) => void handleLine(line));
103
+
104
+ async function handleLine(line) {
105
+ let message;
106
+ try {
107
+ message = JSON.parse(line);
108
+ } catch {
109
+ return;
110
+ }
111
+ if (message.id === undefined) return; // a notification
112
+ try {
113
+ const result = await respond(message);
114
+ process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id: message.id, result })}\n`);
115
+ } catch (error) {
116
+ process.stdout.write(
117
+ `${JSON.stringify({ jsonrpc: "2.0", id: message.id, error: { code: error.code ?? -32603, message: error.message } })}\n`,
118
+ );
119
+ }
120
+ }
121
+ lines.on("close", () => browser?.close());
@@ -1,4 +1,5 @@
1
- // The example app on Node: node:http, with Porthole's Node adapter in front of it.
1
+ // The example app on Node: `nodeServer` sends the content domain to Porthole and everything else
2
+ // to the app, WebSockets included, and runs the health gate while it listens.
2
3
  //
3
4
  // PORTHOLE_SECRET=$(npx porthole secret) node node_modules/@botiverse/porthole/examples/node/server.mjs
4
5
  // open http://localhost:8790 (content is served on http://*.content.localhost:8790, the same server)
@@ -6,24 +7,27 @@
6
7
  // Locally the app is http://localhost:<port> and content http://*.content.localhost:<port>: every
7
8
  // *.localhost name is loopback in browsers, and each is a site of its own, so they never share
8
9
  // cookies or storage. In production: https://app.example.com and content.example-usercontent.com.
10
+ //
11
+ // An app that keeps its own node:http server (or Express, Fastify) uses `nodeHost(content, { request })`
12
+ // instead: its `request` and `upgrade` listeners, with `content.start()` once listening.
9
13
  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";
14
+ import { createContentHost, memoryTicketStore } from "@botiverse/porthole/server";
15
+ import { nodeProbe, nodeServer } from "@botiverse/porthole/node";
13
16
  import { makeApp } from "../app.mjs";
14
17
 
15
18
  /** Porthole's browser modules (the package's dist/), served to the app's page. */
16
19
  const dist = new URL("../dist/", import.meta.resolve("@botiverse/porthole"));
17
- const TYPES = { ".js": "text/javascript; charset=utf-8" };
18
20
 
19
21
  export function start({
20
22
  port = 8790,
21
23
  secret = process.env.PORTHOLE_SECRET,
22
24
  conformance = process.env.PORTHOLE_CONFORMANCE === "1",
23
25
  } = {}) {
24
- if (!secret) throw new Error("Set PORTHOLE_SECRET (npx porthole secret)");
26
+ // Under the health gate, createContentHost takes a missing secret as a lasting misconfiguration
27
+ // (frames opaque, the log says why); an example says so at once.
28
+ if (!secret) throw new Error("Set PORTHOLE_SECRET (npx porthole secret makes one)");
25
29
  const appOrigin = `http://localhost:${port}`;
26
- const { content, handle } = makeApp({
30
+ const app = makeApp({
27
31
  appOrigin,
28
32
  contentDomain: `content.localhost:${port}`,
29
33
  secret,
@@ -34,38 +38,16 @@ export function start({
34
38
  client: async (path) => {
35
39
  if (!/^\/[\w/.-]+\.js$/u.test(path) || path.includes("..")) return null;
36
40
  return readFile(new URL(`.${path}`, dist)).then(
37
- (body) => new Response(body, { headers: { "content-type": TYPES[".js"] } }),
41
+ (body) =>
42
+ new Response(body, { headers: { "content-type": "text/javascript; charset=utf-8" } }),
38
43
  () => null,
39
44
  );
40
45
  },
41
46
  });
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);
47
+ const content = createContentHost(app.options);
48
+ const server = nodeServer({ content, app: (request) => app.handle(request, content) });
56
49
  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
- }),
50
+ server.listen(port, () => resolve({ server, content, appOrigin, close: () => server.close() })),
69
51
  );
70
52
  }
71
53
 
@@ -8,14 +8,15 @@
8
8
  //
9
9
  // wrangler.jsonc sets `run_worker_first`: every request, the content domain's included, comes
10
10
  // here first, so static assets are never answered on a content origin.
11
- import { d1TicketStore } from "@botiverse/porthole/server";
11
+ import { contentHostFor, d1TicketStore } from "@botiverse/porthole/server";
12
12
  import { makeApp } from "../app.mjs";
13
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({
14
+ /** The app for a Worker's settings (its `env`): made once per settings object. */
15
+ const apps = new WeakMap();
16
+ const appOf = (env) => {
17
+ let app = apps.get(env);
18
+ if (app === undefined) {
19
+ app = makeApp({
19
20
  appOrigin: env.APP_ORIGIN,
20
21
  contentDomain: env.CONTENT_DOMAIN,
21
22
  secret: env.PORTHOLE_SECRET,
@@ -27,7 +28,18 @@ export default {
27
28
  return answer.ok ? answer : null;
28
29
  },
29
30
  });
31
+ apps.set(env, app);
32
+ }
33
+ return app;
34
+ };
35
+
36
+ // One content host per `env`. Settings that can't be served (no PORTHOLE_SECRET, a content
37
+ // domain that shares a site with the app) answer every request with a 503 naming the problem.
38
+ const porthole = contentHostFor((env) => appOf(env).options, { log: console.error });
39
+
40
+ export default {
41
+ async fetch(request, env) {
30
42
  // The content domain first (Porthole answers every request there), then the app.
31
- return (await app.content.fetch(request)) ?? app.handle(request);
43
+ return (await porthole.fetch(request, env)) ?? appOf(env).handle(request, porthole.host(env));
32
44
  },
33
45
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botiverse/porthole",
3
- "version": "0.2.4",
3
+ "version": "0.3.1",
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
6
  "bin": {
@@ -39,6 +39,18 @@
39
39
  "./node": {
40
40
  "types": "./dist/node/index.d.ts",
41
41
  "default": "./dist/node/index.js"
42
+ },
43
+ "./check": {
44
+ "types": "./dist/check/index.d.ts",
45
+ "default": "./dist/check/index.js"
46
+ },
47
+ "./check/page": {
48
+ "types": "./dist/check/page-source.d.ts",
49
+ "default": "./dist/check/page-source.js"
50
+ },
51
+ "./conformance/reporter": {
52
+ "types": "./dist/conformance/reporter.d.ts",
53
+ "default": "./dist/conformance/reporter.js"
42
54
  }
43
55
  },
44
56
  "devDependencies": {