@botiverse/porthole 0.14.5 → 0.14.6

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 (76) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/dist/check/page-source.js +1 -1
  3. package/dist/check/page.js +5 -1
  4. package/dist/compile/policy.d.ts +6 -0
  5. package/dist/compile/policy.js +6 -0
  6. package/dist/conformance/entry.d.ts +25 -6
  7. package/dist/conformance/entry.js +69 -18
  8. package/dist/conformance/harness/page.d.ts +12 -0
  9. package/dist/conformance/harness/page.js +95 -51
  10. package/dist/conformance/harness-source.js +1 -1
  11. package/dist/conformance/host-kit.js +39 -13
  12. package/dist/conformance/served.js +140 -0
  13. package/dist/files/paths.d.ts +2 -2
  14. package/dist/files/paths.js +12 -2
  15. package/dist/host/client.d.ts +8 -0
  16. package/dist/host/client.js +47 -17
  17. package/dist/host/create-host.d.ts +10 -0
  18. package/dist/host/create-host.js +124 -10
  19. package/dist/host/door.d.ts +41 -0
  20. package/dist/host/door.js +55 -0
  21. package/dist/host/locate.js +2 -0
  22. package/dist/host/locator.d.ts +55 -3
  23. package/dist/host/locator.js +152 -42
  24. package/dist/host/outcome.d.ts +54 -1
  25. package/dist/host/outcome.js +33 -8
  26. package/dist/host/types.d.ts +10 -2
  27. package/dist/isolation/served.d.ts +1 -1
  28. package/dist/isolation/served.js +35 -0
  29. package/dist/isolation/types.d.ts +20 -2
  30. package/dist/isolation/types.js +2 -0
  31. package/dist/platform/types.d.ts +22 -0
  32. package/dist/platform/web.js +55 -12
  33. package/dist/react/view.d.ts +13 -0
  34. package/dist/react/view.js +101 -2
  35. package/dist/server/files.d.ts +11 -0
  36. package/dist/server/files.js +26 -4
  37. package/dist/server/host.js +106 -28
  38. package/dist/server/index.d.ts +2 -1
  39. package/dist/server/index.js +6 -1
  40. package/dist/server/pages.d.ts +32 -0
  41. package/dist/server/pages.js +82 -6
  42. package/dist/server/server.js +140 -11
  43. package/dist/server/types.d.ts +15 -1
  44. package/dist/transport/post-message.d.ts +1 -9
  45. package/dist/transport/post-message.js +2 -8
  46. package/docs/ADOPTING.md +57 -4
  47. package/docs/DECISIONS.md +198 -0
  48. package/docs/DESIGN.md +24 -18
  49. package/docs/THREAT_MODEL.md +79 -13
  50. package/package.json +1 -1
  51. package/src/check/page.ts +6 -1
  52. package/src/compile/policy.ts +7 -0
  53. package/src/conformance/entry.ts +129 -24
  54. package/src/conformance/harness/page.ts +112 -49
  55. package/src/conformance/host-kit.ts +53 -16
  56. package/src/conformance/served.ts +175 -0
  57. package/src/files/paths.ts +11 -2
  58. package/src/host/client.ts +59 -22
  59. package/src/host/create-host.ts +144 -18
  60. package/src/host/door.ts +97 -0
  61. package/src/host/locate.ts +2 -0
  62. package/src/host/locator.ts +208 -57
  63. package/src/host/outcome.ts +41 -9
  64. package/src/host/types.ts +10 -2
  65. package/src/isolation/served.ts +40 -1
  66. package/src/isolation/types.ts +19 -2
  67. package/src/platform/types.ts +21 -0
  68. package/src/platform/web.ts +55 -20
  69. package/src/react/view.tsx +149 -2
  70. package/src/server/files.ts +37 -5
  71. package/src/server/host.ts +131 -46
  72. package/src/server/index.ts +6 -1
  73. package/src/server/pages.ts +101 -6
  74. package/src/server/server.ts +186 -19
  75. package/src/server/types.ts +16 -1
  76. package/src/transport/post-message.ts +1 -9
@@ -76,7 +76,22 @@ export interface FrameLocation {
76
76
  * the display's bridge checks each runtime method's level against it.
77
77
  */
78
78
  readonly viewer?: ViewerInfo;
79
+ /**
80
+ * The display's door (P125): a page of Porthole's on the same origin, at
81
+ * `/__porthole/door/<instance key>?ticket=<its own ticket>`, that says how loading went before
82
+ * any content is framed. The host frames it opaque and hidden, and takes its one frame status
83
+ * (`open`, or `blocked` and why); then frames `url`. Given for a served shell, a page that isn't
84
+ * nested and the sandbox proxy: content of the scope runs on their origin, so no frame status
85
+ * from their own frame is ever Porthole's. A host that is given none for one of them takes no
86
+ * frame status at all (a load that shows nothing is a timeout) and says so (`hostError` kind
87
+ * `door`). A custom locator passes it on as it came.
88
+ */
89
+ readonly door?: {
90
+ readonly url: string;
91
+ };
79
92
  }
93
+ /** Where a served display's door is (P125): `<origin>/__porthole/door/<instance key>`. */
94
+ export declare const DOOR_PATH = "/__porthole/door/";
80
95
  /** The message a served page sends its host about loading (own-prefixed, P040). */
81
96
  export declare const FRAME_STATUS_METHOD = "porthole/notifications/frame-status";
82
97
  /** A nested page's shell's report of its own state to the host (P111). */
@@ -94,8 +109,9 @@ export declare const SHELL_METHOD_PREFIX = "porthole/shell/";
94
109
  export declare const STORAGE_USED_METHOD = "porthole/storage-used";
95
110
  /**
96
111
  * Turns an instance into the URL its frame loads. Implemented by the host, usually by asking its
97
- * own backend (which authenticates the viewer and calls `PortholeServer.issue`). Called on every
98
- * mount: a ticket is good once.
112
+ * own backend (which authenticates the viewer and calls `PortholeServer.issue`). Called for every
113
+ * run (a mount, a reload, a restart after the content navigated away): answer each with a fresh
114
+ * issue, since a ticket and a door ticket are each good once (P125).
99
115
  */
100
116
  export interface InstanceLocator {
101
117
  locate(instance: InstanceRef, signal?: AbortSignal): Promise<FrameLocation>;
@@ -114,4 +130,6 @@ export type FrameSource = {
114
130
  readonly reports?: boolean;
115
131
  /** The issue's viewer (`FrameLocation.viewer`), for the display's bridge. */
116
132
  readonly viewer?: ViewerInfo;
133
+ /** The display's door (`FrameLocation.door`, P125): framed before `url`. */
134
+ readonly door?: string;
117
135
  };
@@ -1,3 +1,5 @@
1
+ /** Where a served display's door is (P125): `<origin>/__porthole/door/<instance key>`. */
2
+ export const DOOR_PATH = "/__porthole/door/";
1
3
  /** The message a served page sends its host about loading (own-prefixed, P040). */
2
4
  export const FRAME_STATUS_METHOD = "porthole/notifications/frame-status";
3
5
  /** A nested page's shell's report of its own state to the host (P111). */
@@ -80,8 +80,30 @@ export interface Surface {
80
80
  onLoad(listener: () => void): () => void;
81
81
  destroy(): void;
82
82
  }
83
+ /**
84
+ * A served display's door (P125): a hidden frame of the host's own at the door's address,
85
+ * sandboxed with scripts alone (an opaque origin no content shares), with no `allow`, no name, out
86
+ * of focus and of the accessibility tree. Its one frame status is heard from its window and the
87
+ * opaque origin (`"null"`) alone.
88
+ */
89
+ export interface DoorSurface {
90
+ readonly transport: Transport;
91
+ /** The platform's own element for the door (an `HTMLIFrameElement` on the web). */
92
+ readonly element: unknown;
93
+ /** Every load of the door's document. */
94
+ onLoad(listener: () => void): () => void;
95
+ destroy(): void;
96
+ }
83
97
  export interface PlatformHost<Container = HTMLElement> {
84
98
  readonly name: string;
85
99
  /** Creates an isolated frame in `container`, its policy set before its document loads. */
86
100
  createSurface(container: Container, spec: SurfaceSpec): Surface;
101
+ /**
102
+ * Creates a served display's door in `container` (P125), loading `url`. A platform without one
103
+ * shows served displays that have a door without it: no frame status is taken from them, and
104
+ * the host hears a `door` host error.
105
+ */
106
+ createDoor?(container: Container, spec: {
107
+ readonly url: string;
108
+ }): DoorSurface;
87
109
  }
@@ -1,11 +1,7 @@
1
- import { FRAME_STATUS_METHOD, SHELL_BEAT_METHOD, SHELL_LOOK_METHOD, SHELL_METHOD_PREFIX, SHELL_STATE_METHOD, } from "../isolation/types.js";
1
+ import { DOOR_SANDBOX_TOKENS } from "../compile/policy.js";
2
+ import { SHELL_BEAT_METHOD, SHELL_LOOK_METHOD, SHELL_METHOD_PREFIX, SHELL_STATE_METHOD, } from "../isolation/types.js";
2
3
  import { postMessageTransport } from "../transport/post-message.js";
3
4
  import { focusGuard } from "./focus-guard.js";
4
- /** A frame-status message (`porthole/notifications/frame-status`), by its method alone. */
5
- const isFrameStatus = (data) => data !== null &&
6
- typeof data === "object" &&
7
- data.jsonrpc === "2.0" &&
8
- data.method === FRAME_STATUS_METHOD;
9
5
  /** A shell's own message (P111), by its namespace. */
10
6
  const isShellWord = (data) => data !== null &&
11
7
  typeof data === "object" &&
@@ -120,12 +116,10 @@ export const webPlatform = {
120
116
  const guard = focusGuard(view);
121
117
  const taken = new Set();
122
118
  const nested = spec.nested === true && spec.source.kind === "url";
123
- // A served frame may pass through the host's own pages (a redirect entry's, P068): what they
124
- // say of the frame's status is heard too, and nothing else from there.
125
- const own = view.origin;
126
- const opened = postMessageTransport(() => frame.contentWindow, origin, view, origin === "null" || own === "null" || own === origin
127
- ? undefined
128
- : { origin: own, accept: isFrameStatus });
119
+ // A frame is heard from its own window and its located origin alone: never the host's own
120
+ // origin (P125 removed P068's in-frame pages and the channel that heard them), so no page of
121
+ // the host's own can speak for a frame either.
122
+ const opened = postMessageTransport(() => frame.contentWindow, origin, view);
129
123
  const unguard = guard.add(frame, (take) => {
130
124
  for (const listener of taken) {
131
125
  listener(take);
@@ -194,4 +188,53 @@ export const webPlatform = {
194
188
  },
195
189
  };
196
190
  },
191
+ /**
192
+ * A served display's door (P125): hidden (no size, `visibility: hidden`, which still runs its
193
+ * script and fires its load on all three engines), out of focus and of the accessibility tree,
194
+ * sandboxed with scripts alone, no `allow`, no name. Nothing but its frame status is heard from
195
+ * it, from its window and the opaque origin alone; the focus guard, the bridge and annotations
196
+ * never see it.
197
+ */
198
+ createDoor(container, spec) {
199
+ // oxlint-disable-next-line react/iframe-missing-sandbox -- set from the door's list, next
200
+ const frame = container.ownerDocument.createElement("iframe");
201
+ frame.setAttribute("sandbox", DOOR_SANDBOX_TOKENS.join(" "));
202
+ frame.setAttribute("allow", "");
203
+ frame.setAttribute("referrerpolicy", "no-referrer");
204
+ frame.setAttribute("aria-hidden", "true");
205
+ frame.setAttribute("tabindex", "-1");
206
+ frame.setAttribute("inert", "");
207
+ frame.setAttribute("loading", "eager");
208
+ frame.dataset.portholeDoor = "";
209
+ Object.assign(frame.style, {
210
+ display: "block",
211
+ width: "0",
212
+ height: "0",
213
+ border: "0",
214
+ visibility: "hidden",
215
+ });
216
+ frame.src = spec.url;
217
+ const loaded = new Set();
218
+ frame.addEventListener("load", () => {
219
+ for (const listener of loaded) {
220
+ listener();
221
+ }
222
+ });
223
+ container.append(frame);
224
+ const view = container.ownerDocument.defaultView ?? window;
225
+ const transport = postMessageTransport(() => frame.contentWindow, "null", view);
226
+ return {
227
+ transport,
228
+ element: frame,
229
+ onLoad(listener) {
230
+ loaded.add(listener);
231
+ return () => loaded.delete(listener);
232
+ },
233
+ destroy() {
234
+ loaded.clear();
235
+ transport.close();
236
+ frame.remove();
237
+ },
238
+ };
239
+ },
197
240
  };
@@ -27,6 +27,13 @@ export interface PortholeViewProps extends Omit<PortholeFrameProps, "config" | "
27
27
  * back in its confirmations only, never sent to the frame (P077).
28
28
  */
29
29
  readonly instance?: InstanceRef;
30
+ /**
31
+ * A clean address to show instead of an instance (P125): resolved through the client
32
+ * (`client.resolve`) before any frame. What it names is framed through its issued location (a
33
+ * door, a ticket); signed out, denied or not found, the fallback is drawn from that answer, and
34
+ * no frame is made. A clean address is never framed itself.
35
+ */
36
+ readonly address?: string;
30
37
  /**
31
38
  * The content: a served shell's to draw, and what an opaque frame shows while frames aren't
32
39
  * served (a stored page's HTML). Without it, a served-only display shows the fallback then.
@@ -38,6 +45,12 @@ export interface PortholeViewProps extends Omit<PortholeFrameProps, "config" | "
38
45
  readonly pending?: ReactNode;
39
46
  }
40
47
  export declare function PortholeView(props: PortholeViewProps): ReactElement | null;
48
+ /**
49
+ * Whether `address` may be offered as a fallback's "open in a new tab": a clean address on the
50
+ * served content domain (`contentSource`, its scheme and port), not Porthole's own paths. Anything
51
+ * else (another site, a typo the server answered 404 for elsewhere) gets no link.
52
+ */
53
+ export declare function tabLinkOf(address: string, contentSource: string | null | undefined): string | null;
41
54
  /** An instance's clean address, and its "open in a new tab" and "copy link" (P072). */
42
55
  export declare function usePortholeLink(instance: InstanceRef | null): {
43
56
  readonly link: string | null;
@@ -1,6 +1,8 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { useCallback, useContext, useEffect, useImperativeHandle, useRef, useState, useSyncExternalStore, } from "react";
2
+ import { useCallback, useContext, useEffect, useImperativeHandle, useMemo, useRef, useState, useSyncExternalStore, } from "react";
3
3
  import { frameFallback } from "../host/client.js";
4
+ import { oneShot } from "../host/locator.js";
5
+ import { originMatchesSource } from "../isolation/served.js";
4
6
  import { PortholeFrame, PortholeContext, } from "./frame.js";
5
7
  function useClient() {
6
8
  const client = useContext(PortholeContext).client;
@@ -22,9 +24,106 @@ function DefaultFallback({ title, message, link }) {
22
24
  return (_jsxs("div", { "data-porthole-fallback": "", role: "status", style: { padding: 16 }, children: [_jsx("strong", { children: title }), " ", _jsx("span", { children: message }), " ", link === null ? null : (_jsx("a", { href: link, target: "_blank", rel: "noopener", children: "Open in a new tab" }))] }));
23
25
  }
24
26
  export function PortholeView(props) {
27
+ return props.address !== undefined && props.instance === undefined ? (_jsx(AddressView, { ...props, address: props.address })) : (_jsx(InstanceView, { ...props }));
28
+ }
29
+ /**
30
+ * Whether `address` may be offered as a fallback's "open in a new tab": a clean address on the
31
+ * served content domain (`contentSource`, its scheme and port), not Porthole's own paths. Anything
32
+ * else (another site, a typo the server answered 404 for elsewhere) gets no link.
33
+ */
34
+ export function tabLinkOf(address, contentSource) {
35
+ if (contentSource === null || contentSource === undefined) {
36
+ return null;
37
+ }
38
+ try {
39
+ const url = new URL(address);
40
+ return originMatchesSource(url.origin, contentSource) &&
41
+ !url.pathname.startsWith("/__porthole/")
42
+ ? url.href
43
+ : null;
44
+ }
45
+ catch {
46
+ return null;
47
+ }
48
+ }
49
+ /** A clean address's view (P125): resolved first; its instance's view, or the answer's fallback. */
50
+ function AddressView(props) {
51
+ const client = useClient();
52
+ const page = useContext(PortholeContext);
53
+ const meta = useMeta(client);
54
+ const { address, fallback, pending, onOutcome } = props;
55
+ const [state, setState] = useState({ kind: "resolving" });
56
+ const [generation, setGeneration] = useState(0);
57
+ const retry = useCallback(() => setGeneration((each) => each + 1), []);
58
+ useEffect(() => {
59
+ const controller = new AbortController();
60
+ setState({ kind: "resolving" });
61
+ client.resolve(address, controller.signal).then((resolved) => {
62
+ if (controller.signal.aborted) {
63
+ return;
64
+ }
65
+ if ("outcome" in resolved) {
66
+ onOutcome?.(resolved.outcome);
67
+ const said = frameFallback(resolved.outcome);
68
+ setState(said === null
69
+ ? {
70
+ kind: "refused",
71
+ said: { kind: "failed", title: "This can't be shown now", message: "" },
72
+ }
73
+ : { kind: "refused", said });
74
+ return;
75
+ }
76
+ setState({ kind: "instance", instance: resolved.instance, location: resolved.location });
77
+ }, () => {
78
+ if (controller.signal.aborted) {
79
+ return;
80
+ }
81
+ const outcome = { state: "blocked", reason: "locate" };
82
+ onOutcome?.(outcome);
83
+ setState({
84
+ kind: "refused",
85
+ said: frameFallback(outcome) ?? {
86
+ kind: "failed",
87
+ title: "This can't be shown now",
88
+ message: "",
89
+ },
90
+ });
91
+ });
92
+ return () => controller.abort();
93
+ // The address and a retry decide; a new onOutcome doesn't resolve it again.
94
+ // oxlint-disable-next-line react-hooks/exhaustive-deps
95
+ }, [client, address, generation]);
96
+ // This view's own locator (P125): its frame's first run takes the location it resolved, once;
97
+ // every later run issues afresh. No other view of the instance can take it.
98
+ const located = state.kind === "instance" ? state.location : null;
99
+ const own = useMemo(() => {
100
+ if (located === null) {
101
+ return null;
102
+ }
103
+ const locator = oneShot(located, { locate: (each, signal) => client.locate(each, signal) });
104
+ return {
105
+ ...page,
106
+ locate: (each, signal) => locator.locate(each, signal),
107
+ };
108
+ }, [page, located, client]);
109
+ if (state.kind === "resolving") {
110
+ return _jsx(_Fragment, { children: pending ?? null });
111
+ }
112
+ if (state.kind === "refused") {
113
+ // The clean address is the "open in a new tab" only where it is one: on the content domain.
114
+ return (_jsx(_Fragment, { children: (fallback ?? DefaultFallback)({
115
+ ...state.said,
116
+ link: tabLinkOf(address, meta?.contentSource),
117
+ retry,
118
+ }) }));
119
+ }
120
+ const { address: _address, ...rest } = props;
121
+ return (_jsx(PortholeContext.Provider, { value: own ?? page, children: _jsx(InstanceView, { ...rest, instance: state.instance }) }));
122
+ }
123
+ function InstanceView(props) {
25
124
  const client = useClient();
26
125
  const meta = useMeta(client);
27
- const { display, instance, content, fallback, pending, onOutcome, ref, ...frame } = props;
126
+ const { display, instance, content, fallback, pending, onOutcome, ref, address: _address, ...frame } = props;
28
127
  // The view's handle (P118) is there while the view is, a fallback drawn or not: its calls reach
29
128
  // the frame's display when one runs, and do nothing otherwise.
30
129
  const shown = useRef(null);
@@ -32,6 +32,11 @@ export interface FileServing {
32
32
  */
33
33
  readonly ticket?: {
34
34
  readonly expires: number;
35
+ /**
36
+ * A page below the base the ticket was issued for (P125: a clean address's file, resolved
37
+ * through `issue`), opened instead of the entry (`ticketPage`).
38
+ */
39
+ readonly page?: string;
35
40
  };
36
41
  /** The artifact version the set is, which its pages name in their notices to the host (P098). */
37
42
  readonly artifact?: {
@@ -46,6 +51,12 @@ export declare function isNavigation(request: Request): boolean;
46
51
  * only a browser sets and no page can change), and not a navigation.
47
52
  */
48
53
  export declare const ownLoad: (request: Request) => boolean;
54
+ /**
55
+ * The page a ticket opens in a set (P081, P125): its entry, or the page below the base it was
56
+ * issued for, found as a navigation finds it (`dir/` its index, `name` its `.html`); null when
57
+ * that is no page of the set. The door asks the same (`serveDoor`), so both say `not-found` alike.
58
+ */
59
+ export declare function ticketPage(set: StoredFiles, page?: string): string | null;
49
60
  export declare function serveFile(serving: FileServing): Promise<Response>;
50
61
  /**
51
62
  * An asset of an artifact's library (P089), at `/_blob/<id>`: typed by Porthole's table by its
@@ -108,6 +108,30 @@ function nothing(serving, status, method) {
108
108
  },
109
109
  });
110
110
  }
111
+ /**
112
+ * The page a ticket opens in a set (P081, P125): its entry, or the page below the base it was
113
+ * issued for, found as a navigation finds it (`dir/` its index, `name` its `.html`); null when
114
+ * that is no page of the set. The door asks the same (`serveDoor`), so both say `not-found` alike.
115
+ */
116
+ export function ticketPage(set, page) {
117
+ const has = (each) => Object.hasOwn(set.files, each);
118
+ const entry = set.entry ?? DEFAULT_ENTRY;
119
+ if (page === undefined || page === "") {
120
+ return has(entry) ? entry : null;
121
+ }
122
+ const path = requestFilePath(page);
123
+ if (path === null) {
124
+ return null;
125
+ }
126
+ let found = lookupFile(has, path, { entry, navigation: false });
127
+ if (found.kind === "redirect") {
128
+ found = lookupFile(has, found.to, { entry, navigation: false });
129
+ }
130
+ return found.kind === "file" && found.status === 200 && fileTypeOf(found.path).role === "page"
131
+ ? found.path
132
+ : null;
133
+ }
134
+ const ticketLookup = (path) => path === null ? { kind: "none" } : { kind: "file", path, status: 200 };
111
135
  export async function serveFile(serving) {
112
136
  const { request, set } = serving;
113
137
  const method = request.method.toUpperCase();
@@ -127,9 +151,7 @@ export async function serveFile(serving) {
127
151
  const has = (each) => Object.hasOwn(set.files, each);
128
152
  const entryPath = set.entry ?? DEFAULT_ENTRY;
129
153
  const found = serving.ticket !== undefined
130
- ? has(entryPath)
131
- ? { kind: "file", path: entryPath, status: 200 }
132
- : { kind: "none" }
154
+ ? ticketLookup(ticketPage(set, serving.ticket.page))
133
155
  : lookupFile(has, path, {
134
156
  ...(set.entry === undefined ? {} : { entry: set.entry }),
135
157
  ...(set.spa === undefined ? {} : { spa: set.spa }),
@@ -206,7 +228,7 @@ export async function serveFile(serving) {
206
228
  ...(serving.ticket === undefined
207
229
  ? {}
208
230
  : {
209
- address: `${base}${found.path.includes("/") ? encodePath(found.path) : ""}`,
231
+ address: `${base}${found.path === entryPath && !found.path.includes("/") ? "" : encodePath(found.path)}`,
210
232
  expires: serving.ticket.expires,
211
233
  }),
212
234
  ...(serving.artifact === undefined ? {} : { set: serving.artifact }),
@@ -3,7 +3,7 @@ import { base64url, fromBase64url, fromUtf8, hmacSha256, timingSafeEqual, utf8 }
3
3
  import { ContentDomainError, contentDomain, serverDomain, } from "./domain.js";
4
4
  import { reservedLabels } from "./naming.js";
5
5
  import { peerAddress } from "./peer.js";
6
- import { appStatusPage } from "./pages.js";
6
+ import { appStatusPage, tabOnlyPage } from "./pages.js";
7
7
  import { createServer } from "./server.js";
8
8
  /**
9
9
  * The host kit (P066): everything around `/server` that every host wrote, so an app writes only
@@ -425,6 +425,20 @@ export function createContentHost(options) {
425
425
  };
426
426
  // Issues per key per minute, in this process.
427
427
  const issued = new Map();
428
+ /**
429
+ * What a clean address names (P068, P125): its label's scope (the naming's `scopeOf`) and what
430
+ * `entry.at` answers for its path, for this viewer. One mapping for a tab (`authorize`) and for a
431
+ * frame (`issue` given `{ address }`), so a frame shows what the address's tab would.
432
+ */
433
+ const entryAt = async (label, pathname, viewer, request) => {
434
+ const scope = options.name?.scopeOf?.(label) ?? null;
435
+ const at = options.entry?.at;
436
+ const answer = scope === null || at === undefined
437
+ ? null
438
+ : ((await at(scope, new URL(pathname, "https://x.invalid").pathname, viewer, request)) ??
439
+ null);
440
+ return { scope, answer };
441
+ };
428
442
  const withinRate = (key) => {
429
443
  const limit = options.rateLimit;
430
444
  if (limit === undefined) {
@@ -619,6 +633,10 @@ export function createContentHost(options) {
619
633
  catch {
620
634
  return refusal(400, "bad-json", "The body is JSON: { instance }");
621
635
  }
636
+ // A clean address (P125): what it names, as its tab would open it, issued for a frame.
637
+ if (isRecord(body) && body.instance === undefined && body.address !== undefined) {
638
+ return issueAddress(body.address, viewer, request);
639
+ }
622
640
  const proposal = isRecord(body) ? body.instance : undefined;
623
641
  if (!isRecord(proposal) ||
624
642
  typeof proposal.scope !== "string" ||
@@ -637,28 +655,86 @@ export function createContentHost(options) {
637
655
  ? refusal(401, "unauthenticated", "Sign in to see this")
638
656
  : refusal(403, "forbidden", "You can't see this");
639
657
  }
640
- let location;
641
- try {
642
- location = await server.issue(instance, grant);
643
- }
644
- catch (error) {
645
- return refusal(409, "refused", error instanceof Error ? error.message : String(error));
658
+ return issuedFor(instance, grant, request);
659
+ }
660
+ catch {
661
+ return refusal(500, "failed", "The app's policy failed");
662
+ }
663
+ };
664
+ /** A location issued for what the host's access granted, with its clean address. */
665
+ async function issuedFor(instance, grant, request, more = {}) {
666
+ let location;
667
+ try {
668
+ location = await server.issue(instance, grant, more.page === undefined ? undefined : { page: more.page });
669
+ }
670
+ catch (error) {
671
+ return refusal(409, "refused", error instanceof Error ? error.message : String(error));
672
+ }
673
+ // The clean address, where the app says the instance's path (P072, P074).
674
+ let link = null;
675
+ try {
676
+ const path = (await options.entry?.pathOf?.(instance, request)) ?? null;
677
+ link = path === null ? null : server.urlOf(instance.scope, path);
678
+ }
679
+ catch {
680
+ link = null;
681
+ }
682
+ return json(201, {
683
+ ...location,
684
+ ...(link === null ? {} : { link }),
685
+ // What a clean address named (P125): the instance its later frames are issued for.
686
+ ...(more.resolved === true ? { instance } : {}),
687
+ });
688
+ }
689
+ /**
690
+ * A clean address asked about for a frame (P125): resolved as its tab's authorize would
691
+ * resolve it (`entry.at`, then the host's access), and answered before any frame: a location
692
+ * with its door, or the same refusal the tab would get (401 signed out, 403 no access, 404
693
+ * nothing there). Never a redirect, never a page: the host shows its fallback from this.
694
+ */
695
+ async function issueAddress(given, viewer, request) {
696
+ let url;
697
+ try {
698
+ if (typeof given !== "string" || given.length > 4_096) {
699
+ throw new TypeError("not an address");
646
700
  }
647
- // The clean address, where the app says the instance's path (P072, P074).
648
- let link = null;
649
- try {
650
- const path = (await options.entry?.pathOf?.(instance, request)) ?? null;
651
- link = path === null ? null : server.urlOf(instance.scope, path);
701
+ url = new URL(given);
702
+ }
703
+ catch {
704
+ return refusal(400, "bad-request", "The body is { address: <a clean address> }");
705
+ }
706
+ const label = domain?.labelOf(url.host) ?? null;
707
+ if (options.entry === undefined ||
708
+ domain === null ||
709
+ label === null ||
710
+ domain.originOf(label) !== url.origin ||
711
+ url.pathname.startsWith("/__porthole/")) {
712
+ return refusal(404, "not-found", "That address names nothing here");
713
+ }
714
+ try {
715
+ const { answer } = await entryAt(label, `${url.pathname}${url.search}`, viewer, request);
716
+ const address = answer !== null && isFileAddress(answer) ? answer : null;
717
+ const instance = address === null ? answer : address.instance;
718
+ if (instance === null) {
719
+ return refusal(404, "not-found", "That address names nothing here");
652
720
  }
653
- catch {
654
- link = null;
721
+ const grant = await options.access(instance, viewer, request);
722
+ if (grant === null) {
723
+ return viewer === null
724
+ ? refusal(401, "unauthenticated", "Sign in to see this")
725
+ : refusal(403, "forbidden", "You can't see this");
655
726
  }
656
- return json(201, link === null ? location : { ...location, link });
727
+ // A file set's address below its version (P081): the frame opens at that page.
728
+ const page = address?.file !== undefined && address.file !== "" ? address.file : undefined;
729
+ return await issuedFor(instance, grant, request, {
730
+ ...(page === undefined ? {} : { page }),
731
+ resolved: true,
732
+ });
657
733
  }
658
734
  catch {
659
735
  return refusal(500, "failed", "The app's policy failed");
660
736
  }
661
- };
737
+ }
662
738
  },
663
739
  meta: () => ({
664
740
  served: served(),
@@ -777,13 +853,19 @@ export function createContentHost(options) {
777
853
  if (state === null) {
778
854
  return appPage(400, "This link isn't valid", "Open the address again.", "error", method);
779
855
  }
856
+ // Redirect entry is for a tab alone (P125): asked in a frame, it never shows the app's
857
+ // sign-in or refusal there, and says nothing to the page that frames it.
780
858
  const dest = request.headers.get("sec-fetch-dest");
781
- const framed = dest === null ? state.framed : dest !== "document";
859
+ if (dest === "iframe" || dest === "frame") {
860
+ return tabOnlyPage(options.appOrigins.join(" "), method);
861
+ }
782
862
  const clean = `${domain.originOf(state.label)}${state.path}`;
783
863
  if (state.expired) {
784
- return appPage(401, "This took too long", "Open the address again.", "session", method, framed ? undefined : { href: clean, text: "Open it again" });
864
+ return appPage(401, "This took too long", "Open the address again.", "session", method, {
865
+ href: clean,
866
+ text: "Open it again",
867
+ });
785
868
  }
786
- const scope = options.name?.scopeOf?.(state.label) ?? null;
787
869
  let viewer;
788
870
  try {
789
871
  viewer = (await viewerOf(request)) ?? (await handedOver(request));
@@ -792,9 +874,7 @@ export function createContentHost(options) {
792
874
  return appPage(500, "Something went wrong", "The app couldn't tell who is asking.", "error", method);
793
875
  }
794
876
  try {
795
- const answer = scope === null
796
- ? null
797
- : ((await entry.at(scope, new URL(state.path, "https://x.invalid").pathname, viewer, request)) ?? null);
877
+ const { scope, answer } = await entryAt(state.label, state.path, viewer, request);
798
878
  // A file set's address (P081) names its instance and where its version lives.
799
879
  const address = answer !== null && isFileAddress(answer) ? answer : null;
800
880
  const instance = address === null ? answer : address.instance;
@@ -806,17 +886,15 @@ export function createContentHost(options) {
806
886
  path: state.path,
807
887
  url: clean,
808
888
  instance,
809
- framed,
889
+ // A frame never gets here since P125: kept for the hooks' type.
890
+ framed: false,
810
891
  };
811
892
  if (instance === null || grant === null) {
812
893
  if (viewer === null) {
813
- // The app's sign-in never shows in a frame: the person opens a tab for it.
814
- return framed
815
- ? appPage(401, "Open this in a new tab to sign in", "Signing in doesn't work inside a frame.", "sign-in", method)
816
- : await signInWith(entry, request, context);
894
+ return await signInWith(entry, request, context);
817
895
  }
818
896
  const status = instance === null ? 404 : 403;
819
- const own = framed ? null : await entry.refusal?.(status, request, context);
897
+ const own = await entry.refusal?.(status, request, context);
820
898
  if (own !== null && own !== undefined) {
821
899
  return own;
822
900
  }
@@ -36,7 +36,8 @@ export { createServer } from "./server.ts";
36
36
  export { createContentHost, HEALTH_PATH, ISSUE_BODY_BYTES, type ContentHealthView, type ContentHost, type ContentHostEvent, type ContentHostOptions, type ContentClientMeta, type ContentLogger, type EntryContext, type EntryOptions, ASSET_LIBRARY_PATH, type FileAddress, isFileAddress, versionBase, versionedAddress, type ContentMeta, type HealthOptions, type HealthProbe, } from "./host.ts";
37
37
  export { clashOf, contentDomain, ContentDomainError, hostnameOf, type ContentDomainInfo, type ContentDomainProblem, } from "./domain.ts";
38
38
  export { d1TicketSchema, d1TicketStore, memoryTicketStore, type D1Like, type D1StatementLike, } from "./tickets.ts";
39
- export { FRAME_STATUS_METHOD } from "../isolation/types.ts";
39
+ export { DOOR_PATH, FRAME_STATUS_METHOD } from "../isolation/types.ts";
40
+ export { doorResponse, doorStatusResponse, type DoorOptions } from "./pages.ts";
40
41
  export { isNestedLabel, NESTED_FILE_HEADERS, NESTED_FILES_PREFIX, nestedAncestors, nestedFileCsp, nestedLabelOf, nestedShellCsp, nestedShellResponse, PORTHOLE_LABEL_PREFIX, } from "./nested.ts";
41
42
  export { isHostLabel, prefixedName, type Naming } from "./naming.ts";
42
43
  export { conformancePage } from "../conformance/page.ts";
@@ -36,7 +36,12 @@ export { createServer } from "./server.js";
36
36
  export { createContentHost, HEALTH_PATH, ISSUE_BODY_BYTES, ASSET_LIBRARY_PATH, isFileAddress, versionBase, versionedAddress, } from "./host.js";
37
37
  export { clashOf, contentDomain, ContentDomainError, hostnameOf, } from "./domain.js";
38
38
  export { d1TicketSchema, d1TicketStore, memoryTicketStore, } from "./tickets.js";
39
- export { FRAME_STATUS_METHOD } from "../isolation/types.js";
39
+ export { DOOR_PATH, FRAME_STATUS_METHOD } from "../isolation/types.js";
40
+ // A served display's door (P125): `/server` serves it for a shell, a page that isn't nested and the
41
+ // sandbox proxy; a content Worker of a host's own answers the same at `DOOR_PATH<key>`, after
42
+ // taking the door's own ticket (`TicketRecord.door`) and running the checks its content's address
43
+ // runs (docs/ADOPTING.md, "The door").
44
+ export { doorResponse, doorStatusResponse } from "./pages.js";
40
45
  // A nested page (P111): Porthole's shell at the framed address, the page and its files below the
41
46
  // sealed prefix, all on the shell's own label (P114, `nestedLabelOf`). `/server` serves them for a
42
47
  // config with `nested`; a content Worker of its own answers the same (docs/ADOPTING.md, "Nested
@@ -37,3 +37,35 @@ export declare function statusPageOf(options: {
37
37
  };
38
38
  readonly method?: string;
39
39
  }): Response;
40
+ /** What a door is given: the host origins it tells, and who may frame it (default, those). */
41
+ export interface DoorOptions {
42
+ readonly hostOrigins: readonly string[];
43
+ readonly frameAncestors?: string;
44
+ readonly method?: string;
45
+ }
46
+ /**
47
+ * A door that opens (P125): its display may be framed. It says `open` to the page that frames it,
48
+ * at each web host origin and (a desktop scheme among them) to its parent (P070), once, as it
49
+ * parses. For a content Worker of a host's own: answer it at `DOOR_PATH<key>` only once the door's
50
+ * own ticket was taken and the checks the content's address runs passed for the same grant.
51
+ */
52
+ export declare function doorResponse(options: DoorOptions): Response;
53
+ /**
54
+ * A door that doesn't open (P125): why, said `blocked` to the page that frames it, as a content
55
+ * origin's status page says it (`session` 401: no ticket, or one used, ended, or not a door's of
56
+ * this instance on this origin; `denied` 403 with the host's code; `not-found` 404: no document, or
57
+ * a file set whose entry isn't a page; `error` 500).
58
+ */
59
+ export declare function doorStatusResponse(options: DoorOptions & {
60
+ readonly status: number;
61
+ readonly reason: FrameBlock;
62
+ readonly code?: string;
63
+ }): Response;
64
+ /**
65
+ * What a clean address answers in a frame (P125): a clean address is for a tab of its own, so in a
66
+ * frame it never goes to the app (no authorize, no sign-in, no refusal page of the app's) and says
67
+ * nothing to the page that frames it: no script at all, under the status pages' policy without
68
+ * `script-src` (so `default-src 'none'` forbids every script), framed by the host origins only. A
69
+ * host frames what a clean address names by resolving it through `issue` (`client.resolve`).
70
+ */
71
+ export declare function tabOnlyPage(frameAncestors: string, method?: string): Response;