@botiverse/porthole 0.2.3 → 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.
- package/docs/ADOPTING.md +269 -0
- package/package.json +1 -1
package/docs/ADOPTING.md
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
# Adopting Porthole
|
|
2
|
+
|
|
3
|
+
How to put Porthole in an app, from the npm package alone. The package's `examples/` is a whole
|
|
4
|
+
app that does everything below: `examples/app.mjs` is the app, runtime-agnostic;
|
|
5
|
+
`examples/node/server.mjs` and `examples/workers/` run it. DESIGN.md says how it works and
|
|
6
|
+
DECISIONS.md why (the P-numbers the code cites).
|
|
7
|
+
|
|
8
|
+
## 1. Choose how content is shown
|
|
9
|
+
|
|
10
|
+
| | Opaque | Served |
|
|
11
|
+
| --- | --- | --- |
|
|
12
|
+
| Where it runs | A sandboxed frame in your page, origin `null` | A frame on an origin of its own (`a-<id>.example-usercontent.com`) |
|
|
13
|
+
| Server side | None | The host kit (`createContentHost`) |
|
|
14
|
+
| Storage, clean address, open in a tab | No | Yes |
|
|
15
|
+
| Typical | Widgets in a conversation | Stored pages, artifacts, a viewer |
|
|
16
|
+
|
|
17
|
+
Start opaque if you can; add served pages when content needs storage or an address. A served app
|
|
18
|
+
keeps the opaque config as its fallback for when the content domain is down.
|
|
19
|
+
|
|
20
|
+
The config is the source of truth: `presets.inlineWidget()`, `presets.artifact()`,
|
|
21
|
+
`presets.mcpApp()`, `presets.url()` with your options. The same config object (or the same
|
|
22
|
+
options) must be used by the server (it puts the CSP in headers), the page (`createHost`) and the
|
|
23
|
+
agent's manual (`compile(config).guide()`): give it one home and import it everywhere.
|
|
24
|
+
|
|
25
|
+
## 2. Opaque displays: the page only
|
|
26
|
+
|
|
27
|
+
```js
|
|
28
|
+
import { createHost, presets } from "@botiverse/porthole";
|
|
29
|
+
|
|
30
|
+
const config = presets.inlineWidget({ capabilities: { openLink: {} } });
|
|
31
|
+
const host = createHost(config, {
|
|
32
|
+
handlers: { openLink: ({ url }) => window.open(url, "_blank", "noopener") },
|
|
33
|
+
// A gated call asks the person first, with the call's whole effect (here: the link).
|
|
34
|
+
confirm: async (request) => window.confirm(`Open ${JSON.stringify(request.args)}?`),
|
|
35
|
+
});
|
|
36
|
+
const display = host.mount(container, { displayId: "w1", title: "A chart", scheme: "light" });
|
|
37
|
+
display.setContent(agentHtml, { partial: true }); // while it streams: drawn inert
|
|
38
|
+
display.setContent(agentHtml); // once whole: it runs, once
|
|
39
|
+
display.on("contentError", ({ message }) => tellTheAgent(message));
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
React: wrap the app in `<PortholeProvider>`, then
|
|
43
|
+
`<PortholeFrame config={config} displayId={id} title={title} scheme={scheme} content={html} partial={streaming} />`.
|
|
44
|
+
|
|
45
|
+
## 3. Served pages: the host kit
|
|
46
|
+
|
|
47
|
+
### Local development
|
|
48
|
+
|
|
49
|
+
Run the app and the content domain on one server: app `http://localhost:8790`, content domain
|
|
50
|
+
`content.localhost:8790` (pages at `http://a-<id>.content.localhost:8790`). Browsers resolve every
|
|
51
|
+
`*.localhost` name to loopback, and each is a site of its own, so the app and its content never
|
|
52
|
+
share cookies or storage. `http` is allowed only on loopback; everything else is `https`.
|
|
53
|
+
|
|
54
|
+
In production the content domain is a registrable domain your app uses for nothing else
|
|
55
|
+
(`example-usercontent.com`), with wildcard DNS and a wildcard certificate pointing at the same
|
|
56
|
+
app. Porthole refuses one that holds or may share a site with an app origin (`ContentDomainError`).
|
|
57
|
+
Put it on the Public Suffix List when you can, so its labels are sites of their own.
|
|
58
|
+
|
|
59
|
+
### The server
|
|
60
|
+
|
|
61
|
+
```js
|
|
62
|
+
import { presets } from "@botiverse/porthole";
|
|
63
|
+
import { createContentHost, prefixedName, memoryTicketStore } from "@botiverse/porthole/server";
|
|
64
|
+
|
|
65
|
+
const APP = "http://localhost:8790";
|
|
66
|
+
export const pageConfig = (source) =>
|
|
67
|
+
presets.artifact({ layout: { kind: "fill" }, isolation: "domain", contentOrigins: [source] });
|
|
68
|
+
|
|
69
|
+
const content = createContentHost({
|
|
70
|
+
domain: "content.localhost:8790", // "" turns content off
|
|
71
|
+
appOrigins: [APP],
|
|
72
|
+
secret: process.env.PORTHOLE_SECRET, // npx porthole secret
|
|
73
|
+
tickets: memoryTicketStore(), // one process; d1TicketStore(env.DB) on Workers
|
|
74
|
+
configs: (source) => ({ artifact: pageConfig(source) }),
|
|
75
|
+
name: prefixedName("a-"), // page "abc" is served on a-abc.<domain>
|
|
76
|
+
instance: (proposal) => myInstance(proposal), // what a frame request asks for, as you mean it
|
|
77
|
+
access: async (instance, viewer) => ((await mayView(viewer, instance)) ? { viewer: viewer.id } : null),
|
|
78
|
+
source: (id, version) => myStore.page(id, version), // { html } | null
|
|
79
|
+
entry: { // clean addresses: a-abc.<domain>/ in a new tab
|
|
80
|
+
authorizeUrl: `${APP}/porthole/authorize`,
|
|
81
|
+
at: (scope, path) => instanceAt(scope, path), // null: nothing there (404)
|
|
82
|
+
signIn: (returnTo) => Response.redirect(`${APP}/login?next=${encodeURIComponent(returnTo)}`, 303),
|
|
83
|
+
},
|
|
84
|
+
});
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
- **`configs`' keys** are the preset names a stored page names: an artifact page names
|
|
88
|
+
`artifact` unless its `document.preset` says otherwise, so key it `artifact`.
|
|
89
|
+
- **`instance`** gets the client's proposal (`{ scope, document }`) and returns the instance as
|
|
90
|
+
your app means it, or null. Derive the scope (the origin) from what it names: the client never
|
|
91
|
+
chooses an origin.
|
|
92
|
+
- **`access`** returns a grant (`{ viewer }`, or `{ anonymous: true }` for a public page) or null.
|
|
93
|
+
`authorize` (optional) checks again on every request after, for revocation.
|
|
94
|
+
- **`Response.redirect` needs an absolute URL** outside a browser (Node throws on `/login`).
|
|
95
|
+
- **`reserved`** is only for labels your app itself serves on the content domain (previews of a
|
|
96
|
+
dev server, `p-*`). Labels nothing serves need nothing: they are a 404 there.
|
|
97
|
+
|
|
98
|
+
Routes: the content domain first, then your app.
|
|
99
|
+
|
|
100
|
+
```js
|
|
101
|
+
// Node (node:http)
|
|
102
|
+
import { nodeHost, nodeProbe, toRequest, sendResponse } from "@botiverse/porthole/node";
|
|
103
|
+
const porthole = nodeHost(content, { request: (req, res) => app(toRequest(req, "http")).then((r) => sendResponse(res, r)) });
|
|
104
|
+
http.createServer(porthole.request).on("upgrade", porthole.upgrade).listen(8790, () => content.start());
|
|
105
|
+
|
|
106
|
+
// Any fetch-style runtime (Workers, Hono, Bun, Deno)
|
|
107
|
+
const answer = (await content.fetch(request)) ?? (await app(request));
|
|
108
|
+
|
|
109
|
+
// Your app's routes
|
|
110
|
+
"/api/frames" → content.issue(viewerOf)(request) // POST { instance } → 201 { url, origin }
|
|
111
|
+
"/porthole/authorize" → content.authorize(viewerOf)(request) // GET, for clean addresses
|
|
112
|
+
"/api/meta" → content.meta() // { served, contentSource, health }
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
`viewerOf(request)` is your app's own: who is signed in, from its cookie, or null.
|
|
116
|
+
|
|
117
|
+
### The page
|
|
118
|
+
|
|
119
|
+
```html
|
|
120
|
+
<script type="module" nonce="…">
|
|
121
|
+
// A client module that fails to load shows nothing at all: say so.
|
|
122
|
+
import("@botiverse/porthole").then(async ({ createHost, httpLocator }) => {
|
|
123
|
+
const meta = await (await fetch("/api/meta")).json();
|
|
124
|
+
const host = createHost(meta.served ? servedConfig(meta.contentSource) : opaqueConfig, {
|
|
125
|
+
locator: httpLocator("/api/frames"),
|
|
126
|
+
});
|
|
127
|
+
const display = host.mount(box, {
|
|
128
|
+
displayId: id, title, scheme: "light",
|
|
129
|
+
instance: { scope: id, document: { kind: "artifact", id, version } },
|
|
130
|
+
});
|
|
131
|
+
display.on("outcome", (outcome) => { if (outcome.state !== "loaded") offerNewTab(); });
|
|
132
|
+
}, (error) => showProblem(`Porthole didn't load: ${error.message}`));
|
|
133
|
+
</script>
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
- `servedOrOpaque(meta, servedConfigs, opaqueConfigs)` picks the configs and says nothing until
|
|
137
|
+
meta is known, so a frame never starts opaque and then restarts served.
|
|
138
|
+
- "Open in a new tab" and "Copy link" use `content.urlOf(scope, path)`, the clean address, never a
|
|
139
|
+
ticket URL. Pass it to the page from the server.
|
|
140
|
+
- `outcome` says how the frame loaded: `blocked` with a `reason` (`cookies`: the browser keeps no
|
|
141
|
+
cookie in a frame, as Safari; `sign-in`; `denied`; `session`) is your cue to offer a new tab.
|
|
142
|
+
|
|
143
|
+
### The page's CSP
|
|
144
|
+
|
|
145
|
+
- `frame-src`: `content.frameSources` (the content origins, and the authorize route).
|
|
146
|
+
`embedderCsp(configs)` gives the same as a directive, from configs alone.
|
|
147
|
+
- **An opaque display inherits your page's CSP.** Its own policy then narrows it, never widens it.
|
|
148
|
+
If your page sets `default-src`, also allow what agent content uses inline:
|
|
149
|
+
`img-src data: blob:`, `media-src data: blob:`, `font-src data:`, `style-src 'unsafe-inline'`,
|
|
150
|
+
`worker-src blob:`. A nonce-based `script-src` works: give `createHost` the nonce
|
|
151
|
+
(`HostOptions.nonce`) and the shell runs content's scripts under it.
|
|
152
|
+
- **`form-action` holds every redirect of a submission.** If your sign-in page posts a form and
|
|
153
|
+
then redirect entry continues to the content origin, a `form-action 'self'` blocks the last
|
|
154
|
+
hop: leave it out there, or add the content source.
|
|
155
|
+
|
|
156
|
+
## 4. Cloudflare Workers
|
|
157
|
+
|
|
158
|
+
```js
|
|
159
|
+
import { d1TicketStore } from "@botiverse/porthole/server";
|
|
160
|
+
let app = null;
|
|
161
|
+
export default {
|
|
162
|
+
async fetch(request, env) {
|
|
163
|
+
app ??= makeApp({ ...settingsFrom(env), tickets: d1TicketStore(env.DB) }); // once per isolate
|
|
164
|
+
return (await app.content.fetch(request)) ?? app.handle(request);
|
|
165
|
+
},
|
|
166
|
+
};
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
- **Tickets in D1** (never KV, which is eventually consistent):
|
|
170
|
+
`npx porthole d1-schema > migrations/0001_porthole_tickets.sql`, then
|
|
171
|
+
`wrangler d1 migrations apply <db>`.
|
|
172
|
+
- **One secret, `PORTHOLE_SECRET`:** `npx porthole secret`, then `wrangler secret put
|
|
173
|
+
PORTHOLE_SECRET` (`.dev.vars` locally). At least 32 bytes; it signs tickets, cookies and
|
|
174
|
+
entry codes.
|
|
175
|
+
- **Static assets:** set `"assets": { "run_worker_first": true }`. Otherwise Workers serves your
|
|
176
|
+
static files before the Worker runs, on every host, content origins included.
|
|
177
|
+
- No `nodejs_compat` needed. `wrangler dev` passes the Host through, so
|
|
178
|
+
`*.content.localhost:<port>` works locally.
|
|
179
|
+
|
|
180
|
+
## 5. The agent's side
|
|
181
|
+
|
|
182
|
+
- `compile(config).toolDescription()` is your show tool's description; `compile(config).guide()`
|
|
183
|
+
the manual (topics: `widget`, `interactive`, `chart`, and yours). Set `guide.toolName` and
|
|
184
|
+
`guide.guideToolName` so they name your tools.
|
|
185
|
+
- A tool definition, as an MCP server lists it:
|
|
186
|
+
|
|
187
|
+
```js
|
|
188
|
+
{ name: "show_page", description: compiled.toolDescription(),
|
|
189
|
+
inputSchema: { type: "object", required: ["title", "html"],
|
|
190
|
+
properties: { title: { type: "string" }, html: { type: "string", description: "The whole HTML document" } } } }
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
- **Fill:** a whole-page viewer says `layout: { kind: "fill" }` in its config. The frame then fills
|
|
194
|
+
its box, and the manual tells the agent so (the page scrolls itself; `position: fixed` works).
|
|
195
|
+
`MountOptions.fill` and `<PortholeFrame fill>` are deprecated: they size the frame but leave the
|
|
196
|
+
manual saying the height follows the content.
|
|
197
|
+
- `errors: "agent"` sends what content throws (and what the sandbox blocks) back to the agent:
|
|
198
|
+
listen for `contentError` and pass it on.
|
|
199
|
+
|
|
200
|
+
## 6. Conformance: prove your integration
|
|
201
|
+
|
|
202
|
+
`@botiverse/porthole/conformance` runs Porthole's suite (egress and escape probes, the served
|
|
203
|
+
cases, redirect entry) against your app's real page, its CSP and session, in Playwright:
|
|
204
|
+
|
|
205
|
+
```js
|
|
206
|
+
// playwright.config.mjs
|
|
207
|
+
import { defineConfig, devices } from "@playwright/test";
|
|
208
|
+
import { conformanceProjects } from "@botiverse/porthole/conformance";
|
|
209
|
+
export default defineConfig({ projects: conformanceProjects(devices), webServer: { … } });
|
|
210
|
+
|
|
211
|
+
// porthole.spec.mjs
|
|
212
|
+
import { test } from "@playwright/test";
|
|
213
|
+
import { defineHostConformance } from "@botiverse/porthole/conformance";
|
|
214
|
+
defineHostConformance(test, {
|
|
215
|
+
name: "my-app",
|
|
216
|
+
open: async (page) => { /* sign in, open the page that shows content */ },
|
|
217
|
+
issue: { url: "/api/frames" },
|
|
218
|
+
config: () => pageConfig("http://*.content.localhost:8790"),
|
|
219
|
+
instances: { artifact: (scope, version) => ({ scope, document: { kind: "artifact", id: "conformance", version } }) },
|
|
220
|
+
entry: { url: (scope) => `http://a-t-${scope}.content.localhost:8790/v/1`, unknown: "derive" },
|
|
221
|
+
});
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
What the runner asks of your app, and what it skips without:
|
|
225
|
+
|
|
226
|
+
| Option | It needs | Without it |
|
|
227
|
+
| --- | --- | --- |
|
|
228
|
+
| `instances.artifact(scope, version)` | versions `"1"` and `"2"` of one stored page on `scope`'s origin, each exactly `conformancePage(version)` | the stored-page case |
|
|
229
|
+
| `instances.shell(scope)` | a served shell | the domain cases run on `artifact(scope, "1")` |
|
|
230
|
+
| `instances.app`, `.proxy` | a url-mode app, the MCP Apps proxy | their cases |
|
|
231
|
+
| `entry.url(scope)` | the clean address of `artifact(scope, "1")` | the redirect entry cases |
|
|
232
|
+
| `entry.denied`, `atSignIn`, `completeSignIn` | a page the viewer may not see; your sign-in page | that case; the sign-in is judged by leaving the content origin, and not completed |
|
|
233
|
+
| `entry.unknown` | addresses that name nothing, or `"derive"` | that case |
|
|
234
|
+
|
|
235
|
+
The suite names its own scopes, so an app serves them through a **test mode**
|
|
236
|
+
(`examples/app.mjs`: `PORTHOLE_CONFORMANCE=1`): the test page under `t-<scope>`, and a private
|
|
237
|
+
page. **Never ship test mode**: with it, anyone signed in can make content origins of their
|
|
238
|
+
choosing. `onDemand(make)` memoizes fixtures made the first time a case asks (a page published
|
|
239
|
+
on demand); `instances` and `entry.url` may be async.
|
|
240
|
+
|
|
241
|
+
The leak probes run opaque displays on your page: where its own CSP closes what a probe needs,
|
|
242
|
+
the probe reports itself inapplicable, saying which directive. Those are facts about your page's
|
|
243
|
+
opaque fallback, not failures.
|
|
244
|
+
|
|
245
|
+
## 7. Expected, and how to tell
|
|
246
|
+
|
|
247
|
+
- Chromium logs `Unrecognized Content-Security-Policy directive 'webrtc'` for every frame: the
|
|
248
|
+
directive closes WebRTC where an engine knows it, and is ignored where it doesn't.
|
|
249
|
+
- Content's CSP allows `'unsafe-eval'`. Content is the agent's own script already
|
|
250
|
+
(`'unsafe-inline'`), so eval adds no capability, and libraries content uses compile with it
|
|
251
|
+
(Vue's in-browser build, Alpine.js, Vega's expressions, WebAssembly). Egress, the sandbox and the
|
|
252
|
+
origin are what isolate it (P071).
|
|
253
|
+
- On `http` loopback the session cookies are `porthole-<key>`; on `https`, `__Host-porthole-<key>`.
|
|
254
|
+
- A clean address that names nothing (a label the naming never makes, the bare domain, a path
|
|
255
|
+
`entry.at` says has nothing) is a 404 on the content domain: it never reaches your sign-in.
|
|
256
|
+
- Host errors name the content origin and leave out ticket URLs.
|
|
257
|
+
|
|
258
|
+
## 8. Reference
|
|
259
|
+
|
|
260
|
+
| Import | What |
|
|
261
|
+
| --- | --- |
|
|
262
|
+
| `@botiverse/porthole` | `createHost`, `presets`, `compile`, `embedderCsp`, `httpLocator`, `servedOrOpaque` |
|
|
263
|
+
| `@botiverse/porthole/react` | `PortholeProvider`, `PortholeFrame` |
|
|
264
|
+
| `@botiverse/porthole/server` | `createContentHost`, `prefixedName`, `memoryTicketStore`, `d1TicketStore`, `contentDomain`, `conformancePage`, the callbacks' types |
|
|
265
|
+
| `@botiverse/porthole/node` | `nodeHost`, `nodeProbe`, `toRequest`, `sendResponse` |
|
|
266
|
+
| `@botiverse/porthole/mcp` | the MCP Apps adapter (views, the sandbox proxy) |
|
|
267
|
+
| `@botiverse/porthole/conformance` | `defineHostConformance`, `conformanceProjects`, `onDemand`, `conformancePage` |
|
|
268
|
+
|
|
269
|
+
The types' doc comments are the precise reference; DESIGN.md § "The host kit" is the long form.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@botiverse/porthole",
|
|
3
|
-
"version": "0.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
6
|
"bin": {
|