@botiverse/porthole 0.2.2 → 0.2.3
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.
- package/README.md +83 -0
- package/dist/cli.d.ts +6 -0
- package/dist/cli.js +51 -0
- package/dist/conformance/entry.d.ts +12 -6
- package/dist/conformance/entry.js +17 -5
- package/dist/conformance/harness.js +8 -8
- package/dist/conformance/host-kit.d.ts +43 -13
- package/dist/conformance/host-kit.js +83 -6
- package/dist/conformance/index.d.ts +1 -1
- package/dist/conformance/index.js +1 -1
- package/dist/conformance/limits.js +15 -2
- package/dist/conformance/page.d.ts +6 -0
- package/dist/conformance/page.js +8 -0
- package/dist/host/types.d.ts +6 -3
- package/dist/isolation/served.js +13 -2
- package/dist/react/frame.d.ts +5 -2
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.js +2 -0
- package/docs/DECISIONS.md +37 -0
- package/docs/DESIGN.md +13 -6
- package/examples/app.mjs +234 -0
- package/examples/conformance/playwright.config.mjs +28 -0
- package/examples/conformance/porthole.spec.mjs +36 -0
- package/examples/node/server.mjs +75 -0
- package/examples/workers/migrations/0001_porthole_tickets.sql +2 -0
- package/examples/workers/worker.mjs +33 -0
- package/examples/workers/wrangler.jsonc +19 -0
- package/package.json +7 -2
- package/src/cli.ts +54 -0
- package/src/conformance/entry.ts +33 -11
- package/src/conformance/host-kit.ts +127 -21
- package/src/conformance/index.ts +4 -0
- package/src/conformance/limits.ts +21 -4
- package/src/conformance/page.ts +8 -0
- package/src/host/types.ts +6 -3
- package/src/isolation/served.ts +12 -2
- package/src/react/frame.tsx +5 -2
- package/src/server/index.ts +2 -0
package/examples/app.mjs
ADDED
|
@@ -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,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.
|
|
3
|
+
"version": "0.2.3",
|
|
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
|
+
}
|
package/src/conformance/entry.ts
CHANGED
|
@@ -18,18 +18,24 @@ export interface EntryConformanceHost {
|
|
|
18
18
|
* `scope`: it draws `<main id="artifact">version 1</main>`.
|
|
19
19
|
*/
|
|
20
20
|
url(scope: string): string | Promise<string>;
|
|
21
|
-
/** A clean address the signed-in viewer may not open. */
|
|
22
|
-
denied(scope: string): string | Promise<string>;
|
|
21
|
+
/** A clean address the signed-in viewer may not open. Absent: `served.entry.denied` is skipped. */
|
|
22
|
+
denied?(scope: string): string | Promise<string>;
|
|
23
23
|
/**
|
|
24
24
|
* Addresses on the content domain that name nothing (a label the app never assigns, the bare
|
|
25
25
|
* domain, a path no instance has): each must be Porthole's 404 there, never the app's sign-in
|
|
26
26
|
* (P070). Absent: the case is skipped.
|
|
27
27
|
*/
|
|
28
28
|
unknown?(): readonly string[] | Promise<readonly string[]>;
|
|
29
|
-
/**
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
29
|
+
/**
|
|
30
|
+
* Whether `page` shows the app's own sign-in. Absent: the browser left the content origin for
|
|
31
|
+
* another (the app's) and shows no content.
|
|
32
|
+
*/
|
|
33
|
+
atSignIn?(page: Page): Promise<boolean>;
|
|
34
|
+
/**
|
|
35
|
+
* On the app's sign-in page: signs in, as a person does (and the app goes back). Absent: the
|
|
36
|
+
* signed-out case stops at the sign-in.
|
|
37
|
+
*/
|
|
38
|
+
completeSignIn?(page: Page): Promise<void>;
|
|
33
39
|
/**
|
|
34
40
|
* Frames a clean address on the app's page as the app would (a location of that address),
|
|
35
41
|
* returning the frame and the display's outcome once it has one.
|
|
@@ -111,11 +117,22 @@ export function entryTests(
|
|
|
111
117
|
define(
|
|
112
118
|
"served.entry.signed-out",
|
|
113
119
|
"signed out, a clean address goes to the app's own sign-in, then back to the content",
|
|
114
|
-
async ({ page }) => {
|
|
120
|
+
async ({ page }, info) => {
|
|
115
121
|
const url = await host.url("entry-signed-out");
|
|
116
122
|
await page.goto(url);
|
|
117
|
-
|
|
123
|
+
const atSignIn =
|
|
124
|
+
host.atSignIn === undefined
|
|
125
|
+
? new URL(page.url()).origin !== new URL(url).origin
|
|
126
|
+
: await host.atSignIn(page);
|
|
127
|
+
expect(atSignIn, `the app's sign-in (ended at ${page.url()})`).toBe(true);
|
|
118
128
|
expect(await shows(page)).toBe(false);
|
|
129
|
+
if (host.completeSignIn === undefined) {
|
|
130
|
+
info.annotations.push({
|
|
131
|
+
type: "note",
|
|
132
|
+
description: "the sign-in wasn't completed: entry.completeSignIn not given",
|
|
133
|
+
});
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
119
136
|
await host.completeSignIn(page);
|
|
120
137
|
await expect(page.locator("#artifact")).toHaveText("version 1");
|
|
121
138
|
expect(page.url()).toBe(url);
|
|
@@ -125,9 +142,13 @@ export function entryTests(
|
|
|
125
142
|
define(
|
|
126
143
|
"served.entry.denied",
|
|
127
144
|
"a viewer without access gets the app's refusal, never the content",
|
|
128
|
-
async ({ page }) => {
|
|
145
|
+
async ({ page }, info) => {
|
|
146
|
+
info.skip(
|
|
147
|
+
host.denied === undefined,
|
|
148
|
+
"the host gave no address its viewer may not open (denied)",
|
|
149
|
+
);
|
|
129
150
|
await host.signIn(page);
|
|
130
|
-
const url = await host.denied("entry-denied");
|
|
151
|
+
const url = (await host.denied?.("entry-denied")) ?? "";
|
|
131
152
|
const answer = await page.goto(url);
|
|
132
153
|
expect(answer?.status()).toBe(403);
|
|
133
154
|
expect(await shows(page)).toBe(false);
|
|
@@ -196,10 +217,11 @@ export function entryTests(
|
|
|
196
217
|
"a clean address in a frame shows the content where the browser keeps the cookies, else asks for a tab: never the app's sign-in",
|
|
197
218
|
async ({ page, browserName }, info) => {
|
|
198
219
|
await host.signIn(page);
|
|
220
|
+
const before = page.url();
|
|
199
221
|
const shown = await host.frame(page, await host.url("entry-framed"));
|
|
200
222
|
const outcome = await shown.outcome();
|
|
201
223
|
const frame = await shown.frame();
|
|
202
|
-
expect(
|
|
224
|
+
expect(page.url(), "the app's page stays where it was").toBe(before);
|
|
203
225
|
expect(new URL(frame.url()).pathname).not.toMatch(/sign-?in/iu);
|
|
204
226
|
if (outcome.state === "loaded") {
|
|
205
227
|
await expect(frame.locator("#artifact")).toHaveText("version 1");
|