@botiverse/porthole 0.2.1 → 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 +19 -7
- package/dist/conformance/entry.js +39 -12
- package/dist/conformance/harness.js +8 -8
- package/dist/conformance/host-kit.d.ts +48 -13
- package/dist/conformance/host-kit.js +140 -28
- 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/conformance/served.d.ts +4 -4
- package/dist/conformance/served.js +26 -16
- package/dist/host/types.d.ts +6 -3
- package/dist/isolation/served.js +13 -2
- package/dist/node/index.d.ts +11 -3
- package/dist/node/index.js +70 -10
- package/dist/react/frame.d.ts +5 -2
- package/dist/server/host.d.ts +42 -8
- package/dist/server/host.js +35 -5
- package/dist/server/index.d.ts +4 -1
- package/dist/server/index.js +2 -0
- package/dist/server/pages.js +15 -1
- package/dist/server/proxy.js +2 -0
- package/dist/server/server.js +9 -2
- package/dist/server/types.d.ts +15 -6
- package/docs/ARCHITECTURE.md +277 -0
- package/docs/DECISIONS.md +1811 -0
- package/docs/DESIGN.md +1074 -0
- package/docs/OBJECTIVES.md +116 -0
- package/docs/PRINCIPLES.md +155 -0
- 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 +9 -3
- package/src/cli.ts +54 -0
- package/src/conformance/entry.ts +70 -19
- package/src/conformance/host-kit.ts +194 -45
- package/src/conformance/index.ts +4 -0
- package/src/conformance/limits.ts +21 -4
- package/src/conformance/page.ts +8 -0
- package/src/conformance/served.ts +34 -21
- package/src/host/types.ts +6 -3
- package/src/isolation/served.ts +12 -2
- package/src/node/index.ts +73 -10
- package/src/react/frame.tsx +5 -2
- package/src/server/host.ts +84 -14
- package/src/server/index.ts +6 -0
- package/src/server/pages.ts +15 -1
- package/src/server/proxy.ts +2 -0
- package/src/server/server.ts +11 -2
- package/src/server/types.ts +18 -7
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# Objectives
|
|
2
|
+
|
|
3
|
+
## What Porthole is for
|
|
4
|
+
|
|
5
|
+
Any app that wants the "show content made by an agent" ability — like the inline
|
|
6
|
+
visuals and standalone pages in ChatGPT and the Claude app — should be able to
|
|
7
|
+
embed Porthole and get a working, safe display out of the box, plus the manual
|
|
8
|
+
that teaches the agent to write for it.
|
|
9
|
+
|
|
10
|
+
The library has two layers:
|
|
11
|
+
|
|
12
|
+
- a **framework layer** of mechanisms (isolation, egress hardening, the in-frame
|
|
13
|
+
shell, streaming, sizing, theming, the host-function bridge, the guide
|
|
14
|
+
generator); and
|
|
15
|
+
- a **preset policy layer** of ready-made bundles a host adopts with near-zero
|
|
16
|
+
config: **inline widget**, **artifact** (a standalone page), **MCP Apps** (the
|
|
17
|
+
standard protocol), and **URL** (a running app framed by URL, such as a dev
|
|
18
|
+
server's preview).
|
|
19
|
+
|
|
20
|
+
The subject, stated generally, is **HTML drawn by an agent that may optionally
|
|
21
|
+
interact with the agent** — and that interaction is just one host function among
|
|
22
|
+
several. "Out of the box" means: a host picks a preset, passes theme tokens and
|
|
23
|
+
callbacks, and receives a safe display plus a generated agent manual.
|
|
24
|
+
|
|
25
|
+
## Objectives and success criteria
|
|
26
|
+
|
|
27
|
+
1. **Show untrusted agent HTML without putting the host at risk.**
|
|
28
|
+
- *Success:* the conformance/leak suite passes on Chromium, WebKit and
|
|
29
|
+
Firefox — every egress and escape probe attempts its channel and observes
|
|
30
|
+
nothing; the content cannot reach the host origin, its storage, its DOM, or
|
|
31
|
+
its credentials.
|
|
32
|
+
|
|
33
|
+
2. **One config generates the sandbox, the shell, and the manual, in agreement.**
|
|
34
|
+
- *Success:* for every preset, a test derives the CSP, the shell's wired host
|
|
35
|
+
functions, and the generated guide from the same config and asserts they
|
|
36
|
+
match — the guide names only variables the shell injects and only
|
|
37
|
+
capabilities the CSP and bridge allow; changing the config changes all
|
|
38
|
+
three together.
|
|
39
|
+
|
|
40
|
+
3. **Speak the MCP Apps standard, proven against the reference implementation.**
|
|
41
|
+
- *Success:* the MCP Apps preset renders and interacts with the official
|
|
42
|
+
ext-apps example servers **unmodified** (initialize handshake, tool input
|
|
43
|
+
and result, size and theme changes, open-link and message), driven in the
|
|
44
|
+
leak suite.
|
|
45
|
+
|
|
46
|
+
4. **Embed with near-zero config across the modes.**
|
|
47
|
+
- *Success:* a host mounts an inline widget, an artifact page, an MCP Apps
|
|
48
|
+
view and a URL frame each in a few lines using only a preset, theme tokens
|
|
49
|
+
and callbacks; the framework-agnostic core and the React binding both do
|
|
50
|
+
this; no host-specific code lives in the core.
|
|
51
|
+
|
|
52
|
+
5. **Ship the agent manual as a first-class output.**
|
|
53
|
+
- *Success:* each preset produces an agent-facing guide and tool description
|
|
54
|
+
from its config; a real agent that reads the guide produces content that
|
|
55
|
+
renders within the sandbox and reads correctly at the target widths in light
|
|
56
|
+
and dark, checked by rendering the guide's own examples in the leak suite.
|
|
57
|
+
|
|
58
|
+
## Non-goals
|
|
59
|
+
|
|
60
|
+
- **Host-drawn DSL rendering.** Rendering a JSON/JSX/remote-DOM UI description
|
|
61
|
+
with the host's own native components (A2UI, json-render, remote-dom, JSX
|
|
62
|
+
preview) is a separate concern and a different project. Porthole is the HTML
|
|
63
|
+
sandbox only.
|
|
64
|
+
- **A component vocabulary inside the sandbox.** Content is plain HTML and SVG,
|
|
65
|
+
taught by the generated manual; a consistent look comes from the injected theme
|
|
66
|
+
variables and, at most, plain base CSS for native elements, never from tags and
|
|
67
|
+
props an agent must learn (P015). Nor is Porthole a design-system library.
|
|
68
|
+
- **A new widget-side protocol.** The contract is MCP Apps; we do not define an
|
|
69
|
+
alternative (PRINCIPLE 2).
|
|
70
|
+
- **A shell or egress control for URL mode.** A URL frame is someone else's
|
|
71
|
+
running app: Porthole gives it isolation and access auth, nothing more (P020).
|
|
72
|
+
- **Operating infrastructure.** The serving part (`/server`) is a request handler a
|
|
73
|
+
host mounts in its own backend; Porthole runs no service, domain or certificate
|
|
74
|
+
of its own.
|
|
75
|
+
- **Being an agent framework or an MCP server.** Porthole is host-side rendering
|
|
76
|
+
and isolation. It does not run models, implement an MCP server, or decide
|
|
77
|
+
product policy (PRINCIPLE 8).
|
|
78
|
+
|
|
79
|
+
## Who the users are
|
|
80
|
+
|
|
81
|
+
- **Host app developers** who want to show agent-made HTML in a chat or canvas UI
|
|
82
|
+
and do not want to build or audit an isolation layer themselves. They are the
|
|
83
|
+
primary users: they embed the library and pick a preset.
|
|
84
|
+
- **Agents (and the people prompting them)** who write the HTML. They are served
|
|
85
|
+
indirectly: the generated manual is written for them, and the sandbox is the
|
|
86
|
+
environment their code runs in.
|
|
87
|
+
- **MCP App authors** who build standard MCP Apps and want them to render in any
|
|
88
|
+
Porthole-based host unmodified.
|
|
89
|
+
|
|
90
|
+
The first adopter is a normal user of the public API, with no privileged path
|
|
91
|
+
(PRINCIPLE 9).
|
|
92
|
+
|
|
93
|
+
## What "done" means for phase 1
|
|
94
|
+
|
|
95
|
+
Phase 1 is done when:
|
|
96
|
+
|
|
97
|
+
- the framework-agnostic web core and the React binding (with its default,
|
|
98
|
+
replaceable confirmation dialog) exist, with opaque-origin isolation, egress
|
|
99
|
+
hardening, the shell runtime, streaming render, auto-sizing, theming, and the
|
|
100
|
+
host-function bridge;
|
|
101
|
+
- the served modes exist: domain mode (a stable origin per storage scope, CSP in
|
|
102
|
+
headers, ticket → cookie for private content) with its `/server` request
|
|
103
|
+
handler, the artifact page on it, and URL mode (frame, isolation and access
|
|
104
|
+
auth only);
|
|
105
|
+
- the presets exist (inline widget, artifact page, MCP Apps view, URL), each
|
|
106
|
+
generating its CSP and frame policy, and all but URL its shell and manual, from
|
|
107
|
+
one config;
|
|
108
|
+
- the MCP Apps adapter runs the official ext-apps examples unmodified;
|
|
109
|
+
- the leak/conformance suite passes on Chromium and WebKit, then Firefox, and is
|
|
110
|
+
runnable by any host; and
|
|
111
|
+
- the first host has migrated onto it (dogfooding), every one of its features
|
|
112
|
+
that shows agent-made or foreign HTML (widgets, shown HTML files, the dev-server
|
|
113
|
+
preview) going through Porthole, with its own code reduced to configuration
|
|
114
|
+
plus callbacks.
|
|
115
|
+
|
|
116
|
+
Native hosts (WKWebView, maybe Android) are phase 2.
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
# Principles
|
|
2
|
+
|
|
3
|
+
These are the rules we use to make decisions quickly. When a choice is unclear,
|
|
4
|
+
pick the option that best satisfies these, write it down in
|
|
5
|
+
[DECISIONS.md](DECISIONS.md), and move on. Principles change only through a
|
|
6
|
+
decision entry.
|
|
7
|
+
|
|
8
|
+
Each principle gives its reason and what it rules out.
|
|
9
|
+
|
|
10
|
+
## 1. Security defaults cannot be weakened silently
|
|
11
|
+
|
|
12
|
+
Isolation is on, egress is closed, host functions are off until declared, and
|
|
13
|
+
their gates are on — by default. Any change that loosens a default (widens an
|
|
14
|
+
allowlist, drops a sandbox flag, relaxes the CSP, removes a gate) happens only
|
|
15
|
+
through a decision entry that names the threat it re-opens and ships the test
|
|
16
|
+
that bounds the new risk.
|
|
17
|
+
|
|
18
|
+
- **Why.** The whole point of the library is that a host can hand it untrusted
|
|
19
|
+
HTML without reasoning about browser internals. A quiet loosening moves risk
|
|
20
|
+
onto hosts who never agreed to it.
|
|
21
|
+
- **Rules out.** Convenience flags that trade safety for a smaller config;
|
|
22
|
+
"temporary" allowlist entries without an owner; a default that is safe only if
|
|
23
|
+
the host remembers to also set something.
|
|
24
|
+
|
|
25
|
+
## 2. The external contract is the standard; we do not invent a widget protocol
|
|
26
|
+
|
|
27
|
+
What the agent-written HTML speaks to its host is **MCP Apps**
|
|
28
|
+
(`io.modelcontextprotocol/ui`). Gaps are filled through the spec's own extension
|
|
29
|
+
points (experimental capabilities, own-prefixed methods), and anything general is
|
|
30
|
+
taken upstream to the spec, not kept as a private dialect.
|
|
31
|
+
|
|
32
|
+
- **Why.** The value of standard agent-UI is that one widget runs in many hosts
|
|
33
|
+
and one host renders many widgets. A bespoke protocol forfeits that and makes
|
|
34
|
+
every author integrate with us specifically.
|
|
35
|
+
- **Rules out.** A new wire format for widgets; forking the protocol to ship a
|
|
36
|
+
feature faster; host-specific globals the widget must detect.
|
|
37
|
+
|
|
38
|
+
## 3. One config is the single source for the sandbox, the shell, and the manual
|
|
39
|
+
|
|
40
|
+
From one config Porthole derives the CSP, the iframe sandbox and `allow`
|
|
41
|
+
attributes, the in-frame shell, the host-function bridge, **and** the
|
|
42
|
+
agent-facing guide and tool description. They are generated together, never
|
|
43
|
+
edited apart.
|
|
44
|
+
|
|
45
|
+
- **Why.** These four artifacts must agree to be safe and usable: a manual that
|
|
46
|
+
promises a capability the CSP blocks wastes the agent's turns; a CSP that
|
|
47
|
+
allows more than the manual teaches is unaudited surface. Drift between them is
|
|
48
|
+
the most common defect in hand-built sandboxes.
|
|
49
|
+
- **Rules out.** A guide maintained by hand; a CSP string literal that no test
|
|
50
|
+
ties back to the capability list; teaching a variable or function the shell
|
|
51
|
+
does not inject.
|
|
52
|
+
|
|
53
|
+
## 4. Everything the HTML can do beyond drawing is a declared host function
|
|
54
|
+
|
|
55
|
+
Drawing pixels is free; every other power — send a prompt to the agent, open a
|
|
56
|
+
link, read or write state, call a tool, read data, report an error — is a
|
|
57
|
+
**host function (capability)** named in the config. Each declares its gate (needs
|
|
58
|
+
a user gesture, needs a person's confirmation, is rate-limited), its egress
|
|
59
|
+
needs, and its guide entry. Talking to the agent is just one host function among
|
|
60
|
+
these.
|
|
61
|
+
|
|
62
|
+
- **Why.** This is the core abstraction: "agent-drawn HTML + host functions." It
|
|
63
|
+
gives one list that drives the bridge, the CSP and the manual at once (see
|
|
64
|
+
PRINCIPLE 3), and it makes the question "what can this content do?" answerable
|
|
65
|
+
by reading the config.
|
|
66
|
+
- **Rules out.** Ambient powers the HTML gets without the host opting in; a
|
|
67
|
+
capability wired into the bridge but absent from the CSP or the manual; a
|
|
68
|
+
gate decided ad hoc per call site instead of declared once.
|
|
69
|
+
|
|
70
|
+
## 5. Every hardening item ships with a test that proves it
|
|
71
|
+
|
|
72
|
+
A claim that the sandbox blocks something is backed by a test in the conformance
|
|
73
|
+
suite that attempts it and observes nothing. A hardening item without a passing
|
|
74
|
+
test does not exist.
|
|
75
|
+
|
|
76
|
+
- **Why.** Browser behavior changes across versions and engines, and egress
|
|
77
|
+
paths are easy to miss by inspection. Only an executed probe shows the wall is
|
|
78
|
+
really there, and keeps it there as browsers move.
|
|
79
|
+
- **Rules out.** "We set the CSP, so it's blocked" without a probe; hardening
|
|
80
|
+
described in a doc but not exercised; a fix landed without first writing the
|
|
81
|
+
test that failed.
|
|
82
|
+
|
|
83
|
+
## 6. Measured over assumed
|
|
84
|
+
|
|
85
|
+
Browser isolation facts are decided by running the probe on the engines we
|
|
86
|
+
support, not by reading a spec or assuming parity across engines. Where engines
|
|
87
|
+
differ, we harden for the weakest and record the measurement.
|
|
88
|
+
|
|
89
|
+
- **Why.** CSP directives are honored unevenly, and sandbox and frame rules have
|
|
90
|
+
engine-specific gaps. An assumption that is wrong in one engine is a hole in
|
|
91
|
+
production.
|
|
92
|
+
- **Rules out.** Relying on a single directive that one engine ignores; trusting
|
|
93
|
+
that two engines behave the same; shipping a hardening item we have not seen
|
|
94
|
+
pass and fail.
|
|
95
|
+
|
|
96
|
+
## 7. Host-agnostic outside, protocol-pluggable inside
|
|
97
|
+
|
|
98
|
+
The core knows nothing about any particular host app or vendor. It exposes
|
|
99
|
+
mechanisms and takes a config; the host supplies theme tokens, callbacks and
|
|
100
|
+
policy. Inside, the protocol an adapter speaks is swappable behind a thin seam;
|
|
101
|
+
MCP Apps is the first and default adapter.
|
|
102
|
+
|
|
103
|
+
- **Why.** The library is meant to be embedded by many apps. Baking one app's
|
|
104
|
+
assumptions, or one protocol's object model, into the core makes it that app's
|
|
105
|
+
library, not everyone's.
|
|
106
|
+
- **Rules out.** Importing a host's types into the core; a core that only works
|
|
107
|
+
with one framework; tying the core to one protocol SDK's class hierarchy.
|
|
108
|
+
|
|
109
|
+
## 8. The host owns product policy; the surface stays small
|
|
110
|
+
|
|
111
|
+
Porthole decides mechanism (how isolation and gating work); the host decides
|
|
112
|
+
policy (whether to confirm an action, what the confirmation says, which origins
|
|
113
|
+
are allowed, what the theme is). We prefer deleting options to adding them, and
|
|
114
|
+
presets over knobs.
|
|
115
|
+
|
|
116
|
+
Authentication and authorization *policy* are the host's; carrying the host's
|
|
117
|
+
decision safely onto the content domain is Porthole's *mechanism*. Porthole never
|
|
118
|
+
knows who someone is or what they may see: the host decides before it issues a
|
|
119
|
+
ticket and on every request after (`authorize`), and Porthole carries that decision
|
|
120
|
+
in tickets and cookies, opaque to it (P046, P050).
|
|
121
|
+
|
|
122
|
+
- **Why.** Policy is product-specific and changes faster than mechanism. A small,
|
|
123
|
+
opinionated surface with safe presets is easier to audit and harder to misuse
|
|
124
|
+
than a large configurable one.
|
|
125
|
+
- **Rules out.** Drawing our own confirmation UI the host can't control; config
|
|
126
|
+
options that exist only to avoid a decision; a second way to do something the
|
|
127
|
+
presets already cover; users, roles, share lists or revocation lists inside
|
|
128
|
+
Porthole.
|
|
129
|
+
|
|
130
|
+
## 9. No special first user
|
|
131
|
+
|
|
132
|
+
Porthole is built as a general library. Its first adopter is a normal consumer of
|
|
133
|
+
the public API, not a privileged case with private hooks. If the first user needs
|
|
134
|
+
something, it goes into the config or an extension point that any host could use.
|
|
135
|
+
|
|
136
|
+
- **Why.** A library shaped around one caller's internals is not reusable, and
|
|
137
|
+
the shortcuts leak that caller's assumptions into the core (against PRINCIPLE
|
|
138
|
+
7).
|
|
139
|
+
- **Rules out.** An escape hatch only the first host uses; branching on who the
|
|
140
|
+
caller is; features reachable only through internal, undocumented API.
|
|
141
|
+
|
|
142
|
+
## 10. The agent manual is a first-class output, from day one
|
|
143
|
+
|
|
144
|
+
The shell is designed together with the manual that teaches an agent to write for
|
|
145
|
+
it. Guide generation is part of the framework layer, not an afterthought: every
|
|
146
|
+
preset ships an agent-facing manual and a tool description generated from the
|
|
147
|
+
same config as the sandbox and the shell.
|
|
148
|
+
|
|
149
|
+
- **Why.** Untrusted HTML is only as good as what the author was told — the sizes
|
|
150
|
+
that read on each screen, the theme variables that exist, what the sandbox
|
|
151
|
+
forbids. A shell without a matching manual produces content that is almost
|
|
152
|
+
right, and the manual must track the shell automatically to stay true.
|
|
153
|
+
- **Rules out.** Shipping a shell and leaving the manual to each host; a manual
|
|
154
|
+
that lists variables or limits the shell does not actually enforce; prose
|
|
155
|
+
guidance that no test checks against real renders.
|
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
|
+
}
|