@botiverse/porthole 0.14.18 → 0.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,7 +5,7 @@ What Porthole protects, from whom, and where that protection ends. For each way
5
5
  guaranteed. [ADOPTING.md](ADOPTING.md) says how to set each one up, and
6
6
  [DESIGN.md](DESIGN.md) lists every defense with the test that proves it.
7
7
 
8
- **Status.** This describes Porthole 0.14.18 (2026-11-09). A review on 2026-10-19 found gaps, and every decision it led to
8
+ **Status.** This describes Porthole 0.15.1 (2026-11-10). A review on 2026-10-19 found gaps, and every decision it led to
9
9
  has merged ([§8](#8-fixes-in-flight) lists them). P096 changed the negative-control runner and CI,
10
10
  and the shipped conformance probes' messages and timing, not what they check. P104 (0.9.0's
11
11
  annotation markers) had a review of its own, and P105, in 0.10.0, is what it led to. 0.11.0 was
@@ -50,7 +50,25 @@ host a frame hears or tells, and a page's `*` fallback is held to a parent named
50
50
  (§6 "What every host must do", S3). 0.14.18: P142 keeps a set's pages and links within a page from
51
51
  starting the display again where there is no Navigation API, and where WebKit fires a frame's load
52
52
  for a link within its document: the arriving page's notice is sent without the API, and a page
53
- says it stayed; no wall moves, and the limit without the API is P079's, unchanged.
53
+ says it stayed; no wall moves, and the limit without the API is P079's, unchanged. 0.15.0: P143
54
+ lets a host that opts in (`embeds`) mint an embed grant: a public artifact page's answers say
55
+ `frame-ancestors *` for that session alone, and the page has no host: it hears no one, tells no
56
+ parent anything, and no capability, runtime host function or door is there (S4, §8). P144, after
57
+ Ferryman's audit of 0.14.17 and 0.14.18 (no P0, no new egress), amends P141: without `framedBy`
58
+ every header (every `frame-ancestors` and `script-src` hash) and the status, entry and door pages'
59
+ scripts and the nested page's shell are 0.14.16's again, byte for byte (0.14.17 had changed their
60
+ hashes, not what they do); the shell runtime every served document inlines is not (P142's
61
+ changes, and P143's `hostless` branches, inert where a plan names a host; no hash covers it: P145);
62
+ in the nesting P141 is for (the outer page, then the app's page, then content), content can message
63
+ the outer page and every frame in its tree and learn its origin, so the outer page must check every
64
+ message it takes, and S7's egress rule covers its frames (§6 "What every host must do", S7); and
65
+ `framedBy` is compared with the host origins as browsers serialize origins (`https://a.example:443`
66
+ is `https://a.example`).
67
+ 0.15.1: P145, after Ferryman's audit of 0.15.0 (no P0, no escape, no new egress), amends P143 and
68
+ P144: their "byte for byte" is said as it holds (above); the host kit refuses an `access` answer
69
+ with `embed`, so a reader's issue endpoint never mints an embed session (S4); an embed page learns
70
+ where it is embedded (S4); and a host origin's or `framedBy`'s port is 1 to 65535, without a
71
+ leading zero, and its host as the URL parser gives it. No wall moves.
54
72
 
55
73
  ## 1. Two layers
56
74
 
@@ -283,6 +301,14 @@ Whatever the use:
283
301
  can hear is the content's own word to its parent (`*`), which it must treat as untrusted. Your
284
302
  app page's own `frame-ancestors` is yours to set; Porthole never sends it. Name exact origins of
285
303
  that one product, and drop them when it stops framing you.
304
+ - In the nesting `framedBy` is for (the outer page, then your app's page, then content), content
305
+ is a descendant of the outer page (P144): it can `postMessage` the outer page (`top`) and every
306
+ frame in its tree, and learn the outer page's origin (measured in Chromium and Firefox). No
307
+ header stops that. Tell the outer page's authors: every message listener on the outer page and in
308
+ each of its frames must check `event.source` and `event.origin`, taking a message only from the
309
+ window and origin it expects (your app's page), and treat any other as content's untrusted word.
310
+ S7's rule now covers the outer page's frames: what content was given can be handed to any frame
311
+ the outer page shows, so the widest network among them is content's way out.
286
312
  - Under the app runtime, run `defineRuntimeConformance` with `api` in CI (§7).
287
313
 
288
314
  ### S1. Inline widgets in a conversation
@@ -550,6 +576,14 @@ the attacker (c), and its readers are strangers.
550
576
  so it is never punycode for another name; pages say `noindex`; a file of a type Porthole
551
577
  doesn't know is served as a download.
552
578
  - `authorize` is the host's takedown switch.
579
+ - An embedded document (P143, `Grant.embed`, only where the host set `embeds`): its answers say
580
+ `frame-ancestors *` for that session alone, never a reader's; it is anonymous, with no level or
581
+ user, an artifact's page that isn't nested; its plan names no host, so it hears no one, Porthole
582
+ tells no parent anything, no capability or runtime host function runs, and no door is minted. The
583
+ flag is signed into the session and the sealed address. Every other session's answers are, byte
584
+ for byte, what the same server without `embeds` answers, while an embed session of the same
585
+ artifact exists; cookies stay host-only. The host kit never mints one from `access` (its reader's
586
+ issue endpoint and clean addresses refuse an `embed` answer, P145).
553
587
  - A page opened in a tab of its own has its frame's powers and no more (P099): its CSP header
554
588
  carries the frame's sandbox (scripts on its own origin; no popups, forms, downloads, browser
555
589
  dialogs, or navigation of another window, its opener's included), and its `Permissions-Policy`
@@ -583,6 +617,17 @@ the attacker (c), and its readers are strangers.
583
617
  - Check pages for secrets before publishing them: `lintContent` has no rule for credentials.
584
618
  - Pass Porthole's `Content-Security-Policy` and `Permissions-Policy` headers on as they are,
585
619
  through any edge or proxy: on a tab they are the page's sandbox.
620
+ - For embeds (P143): mint `embed` from one route of yours alone (never a reader's ticket or door;
621
+ with the host kit, `host.server.issue`, never `access`, which it refuses, P145), keep that route
622
+ from widening grants, and blank a takedown within a bound you state (your `authorize` answers,
623
+ cached or not). The embedding site sees the page load and hears what the page itself posts to its
624
+ parent or top. The page learns where it is embedded (P145, measured in Chromium, Firefox and
625
+ WebKit): its document's request carries your outer page's address as `Referer` (its origin, under
626
+ the default referrer policy; Firefox also sends it as `Origin`, Chromium and WebKit don't),
627
+ `document.referrer` says the same,
628
+ and `location.ancestorOrigins` names every ancestor, the embedding site's origin included. A page
629
+ with any egress (a `connect-src`, an image source) can send that out; one with none can't. Treat
630
+ where an embed is shown as known to its author.
586
631
  - Treat a public link's clean address as a tab's (P125): to show what one names in a frame, resolve
587
632
  it through your issue endpoint (`client.resolve`, `<PortholeView address>`). Its refusals (signed
588
633
  out, denied, not found) are your backend's word, drawn as the fallback with no frame built: keep
@@ -724,6 +769,10 @@ can be handed to the display with the widest network.
724
769
 
725
770
  - Porthole doesn't enforce this: `defineDisplays` takes any kinds together, and
726
771
  `frameSources` is the union of all of theirs. Group displays by page yourself.
772
+ - Where another app frames yours (`framedBy`, P141, P144), the page is the outer page's, and its
773
+ frames are in the union too: content can post to the outer page and to every frame in its tree.
774
+ The outer page's own frames, and their network, are its authors' to group, and its listeners must
775
+ check `event.source` and `event.origin` (§6 "What every host must do").
727
776
  - An opaque frame also inherits the page's own CSP, so a strict page narrows its opaque frames
728
777
  further (P058). A served frame has only its own policy.
729
778
 
@@ -1282,6 +1331,7 @@ found P124 held only for a nested display or one alone in its scope; in 0.14.6:
1282
1331
  | P101 | Merged | Under https Porthole read unprefixed `porthole-*` cookies a sibling label can plant; the entered mark carried no label; url mode checked neither `Origin` nor `Sec-Fetch-Site`. Now only `__Host-` names are read, the mark names its label, and a url-mode app answers its own origin and navigations. | S3, S6 |
1283
1332
  | P102 | Merged | This document. | |
1284
1333
  | P103 | Merged | A live widget's capabilities could add origins; bearer-mode assets skipped the code re-check; `callTool` had no rate. Now the preset refuses them and its config is frozen, every load asks the current config (its ETag says which answer), and `callTool` has 30 a minute. | S2, S5, §7 |
1334
+ | P143 | Merged (0.15.0) | Embeds: a public grant's documents framed by any page (`frame-ancestors *`) only for a session the host minted with `embed`, never a reader's. Such a frame has no host: it hears no one, Porthole tells no parent anything, no capability or runtime host function runs, no door. Accepted: the embedding site sees the page load and hears what the page itself posts to its parent or top. The host must keep its embed entry from widening grants, and blank takedowns within its stated bound. | S4 |
1285
1335
 
1286
1336
  Open with no decision yet; until then they are the host's to cover:
1287
1337
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botiverse/porthole",
3
- "version": "0.14.18",
3
+ "version": "0.15.1",
4
4
  "description": "A host-side sandbox for agent-made HTML: isolation, egress hardening, a themed shell, gated host functions, and the agent manual, from one config.",
5
5
  "homepage": "https://github.com/botiverse/porthole#readme",
6
6
  "bugs": {
@@ -67,10 +67,37 @@ export function isHostOrigin(origin: unknown): origin is string {
67
67
  return typeof origin === "string" && origin.length <= 300 && HOST_ORIGIN.test(origin);
68
68
  }
69
69
 
70
+ /**
71
+ * Whether an origin that matched `HOST_ORIGIN` is one a browser can serialize as it is written
72
+ * (P145): a port, where it names one, is 1 to 65535 in plain decimal (never `:0`, `:99999` or
73
+ * `:0443`), and an `http`/`https` host is as the URL parser gives it back (never `0x7f.0.0.1` for
74
+ * `127.0.0.1`). A default port (`:443`) is still taken: browsers drop it, and `normalOrigin`
75
+ * compares it so (P144). Such an origin matches no frame and no message, so refusing it only says
76
+ * so early.
77
+ */
78
+ function serializable(origin: string): boolean {
79
+ const port = /:(\d+)$/u.exec(origin)?.[1];
80
+ if (port !== undefined && !(/^[1-9]\d{0,4}$/u.test(port) && Number(port) <= 65_535)) {
81
+ return false;
82
+ }
83
+ const scheme = origin.slice(0, origin.indexOf(":"));
84
+ if (scheme !== "http" && scheme !== "https") {
85
+ return true;
86
+ }
87
+ try {
88
+ const url = new URL(origin);
89
+ return url.hostname === origin.slice(scheme.length + 3).replace(/:\d+$/u, "");
90
+ } catch {
91
+ return false;
92
+ }
93
+ }
94
+
70
95
  /** Why `origin` can't be a host origin, in words a host's developer can act on; null if it can. */
71
96
  export function hostOriginProblem(origin: unknown): string | null {
72
97
  if (isHostOrigin(origin)) {
73
- return null;
98
+ return serializable(origin)
99
+ ? null
100
+ : `${JSON.stringify(origin)} is not an origin a browser serializes so (a port is 1 to 65535, no leading zero; a host as the URL parser gives it)`;
74
101
  }
75
102
  if (origin === "null") {
76
103
  return 'the host page\'s origin is opaque ("null"): serve it from a real origin (an Electron custom protocol must be registered as standard, and file: pages have none)';
@@ -78,6 +105,31 @@ export function hostOriginProblem(origin: unknown): string | null {
78
105
  return `${JSON.stringify(origin)} is not an exact origin (scheme://host[:port], lowercase, no path)`;
79
106
  }
80
107
 
108
+ /**
109
+ * An origin as a browser serializes it, for comparing two (P144):
110
+ * scheme and host lowercase, and for `http`/`https` a default port dropped, so
111
+ * `https://app.example:443` is `https://app.example`. Any other scheme's origin (a desktop app's) is
112
+ * only lowercased.
113
+ */
114
+ export function normalOrigin(origin: string): string {
115
+ const lower = origin.toLowerCase();
116
+ if (lower.startsWith("https://") || lower.startsWith("http://")) {
117
+ try {
118
+ const serialized = new URL(lower).origin;
119
+ if (serialized !== "null") {
120
+ return serialized;
121
+ }
122
+ } catch {
123
+ // Not a URL: compared as it is, lowercase.
124
+ }
125
+ }
126
+ return lower;
127
+ }
128
+
129
+ /** Whether `origin` is one of `origins`, compared as browsers serialize them (`normalOrigin`). */
130
+ export const includesOrigin = (origins: readonly string[], origin: string): boolean =>
131
+ origins.some((each) => normalOrigin(each) === normalOrigin(origin));
132
+
81
133
  const LOOPBACK_HOST = (host: string): boolean =>
82
134
  host === "localhost" || host.endsWith(".localhost") || host === "127.0.0.1" || host === "[::1]";
83
135
 
@@ -86,7 +138,8 @@ const LOOPBACK_HOST = (host: string): boolean =>
86
138
  * ancestor of every frame the host shows, above the host's own page, and never a host origin. An
87
139
  * exact web origin, `https://host[:port]` (lowercase, no path, no wildcard), or `http://` on
88
140
  * loopback alone (`localhost`, `*.localhost`, `127.0.0.1`, `[::1]`) for development: never a
89
- * desktop scheme, `"null"`, a CSP keyword or a list. Null if it can be.
141
+ * desktop scheme, `"null"`, a CSP keyword or a list. Its port, where it names one, is 1 to 65535
142
+ * in plain decimal, and its host is as the URL parser gives it back (P145). Null if it can be.
90
143
  */
91
144
  export function framedByProblem(origin: unknown): string | null {
92
145
  const parsed = typeof origin === "string" && isHostOrigin(origin) ? parseOrigin(origin) : null;
@@ -96,6 +149,9 @@ export function framedByProblem(origin: unknown): string | null {
96
149
  ) {
97
150
  return `${JSON.stringify(origin)} is not an exact https origin (https://host[:port], lowercase, no path; http only on loopback)`;
98
151
  }
152
+ if (!serializable(origin as string)) {
153
+ return `${JSON.stringify(origin)} is not an origin a browser serializes so (a port is 1 to 65535, no leading zero; a host as the URL parser gives it)`;
154
+ }
99
155
  return null;
100
156
  }
101
157
 
@@ -120,6 +120,17 @@ export interface ContentHostOptions<V> {
120
120
  * own `frame-ancestors` (its page's, which Porthole doesn't send) is the app's to set.
121
121
  */
122
122
  readonly framedBy?: readonly string[];
123
+ /**
124
+ * Whether `server.issue` takes an embed grant (P143, `Grant.embed`): a public artifact page that
125
+ * any site may frame, with no host (`ServerOptions.embeds`). Default false: an embed grant is
126
+ * refused at issue. Mint one from a route of your own that decides the page is public
127
+ * (`host.server.issue(instance, { anonymous: true, embed: true })`), never from `access`: `access`
128
+ * answers your readers (the issue endpoint, a clean address), and the kit refuses an `access`
129
+ * answer with `embed` (409 at the issue endpoint and a clean address's resolve; a clean address's
130
+ * tab gets its 409 page, as `enterBy` refuses it) (P145). Only an embed session's answers say
131
+ * `frame-ancestors *`; every other answer is as without it.
132
+ */
133
+ readonly embeds?: boolean;
123
134
  /** At least 32 random bytes (or a string of at least 32 bytes). */
124
135
  readonly secret: Uint8Array | string;
125
136
  readonly tickets?: TicketStore;
@@ -160,7 +171,11 @@ export interface ContentHostOptions<V> {
160
171
  viewer: V | null,
161
172
  request: Request,
162
173
  ) => Awaitable<InstanceRef | null>;
163
- /** Policy 2, access at issue: may this viewer see it, and with what grant (null: 401/403). */
174
+ /**
175
+ * Policy 2, access at issue: may this viewer see it, and with what grant (null: 401/403). It
176
+ * answers readers, so never with `embed` (refused, P145): an embed grant is minted from a route
177
+ * of your own through `host.server.issue`.
178
+ */
164
179
  readonly access: (
165
180
  instance: InstanceRef,
166
181
  viewer: V | null,
@@ -692,6 +707,7 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
692
707
  secret,
693
708
  hostOrigins: options.appOrigins,
694
709
  ...(options.framedBy === undefined ? {} : { framedBy: options.framedBy }),
710
+ ...(options.embeds === undefined ? {} : { embeds: options.embeds }),
695
711
  configs,
696
712
  ...(options.source === undefined ? {} : { artifacts: { get: options.source } }),
697
713
  ...(options.assets === undefined
@@ -1121,6 +1137,15 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
1121
1137
  request: Request,
1122
1138
  more: { readonly page?: string; readonly resolved?: boolean } = {},
1123
1139
  ): Promise<Response> {
1140
+ // `access` answers readers, here and at a clean address: an embed grant (P143) is never
1141
+ // theirs, whatever `embeds` says (P145). A host mints it from a route of its own.
1142
+ if ((grant as { readonly embed?: unknown }).embed !== undefined) {
1143
+ return refusal(
1144
+ 409,
1145
+ "refused",
1146
+ "access never answers an embed grant: mint it from a route of your own with host.server.issue (P145)",
1147
+ );
1148
+ }
1124
1149
  let location: FrameLocation;
1125
1150
  try {
1126
1151
  location = await server!.issue(
@@ -1,5 +1,5 @@
1
1
  import { DOOR_SANDBOX_TOKENS } from "../compile/policy.ts";
2
- import { framedByProblem } from "../isolation/served.ts";
2
+ import { framedByProblem, includesOrigin, normalOrigin } from "../isolation/served.ts";
3
3
  import { FRAME_STATUS_METHOD } from "../isolation/types.ts";
4
4
  import type { FrameBlock } from "../host/types.ts";
5
5
  import { base64url, sha256, utf8 } from "./crypto.ts";
@@ -24,9 +24,12 @@ const heldToHosts = (frameAncestors: string, hostOrigins: readonly string[]): bo
24
24
  .filter((each) => each !== "")
25
25
  .every((each) => hostOrigins.includes(each));
26
26
 
27
+ /** Whether a page is strict: its parent isn't held to its hosts (`heldToHosts`). */
28
+ const isStrict = (frameAncestors: string, hostOrigins: readonly string[]): boolean =>
29
+ !heldToHosts(frameAncestors, hostOrigins);
30
+
27
31
  /** The attribute that says so, on a page's `<main>`: none where its parent is held to its hosts. */
28
- const strictParent = (frameAncestors: string, hostOrigins: readonly string[]): string =>
29
- heldToHosts(frameAncestors, hostOrigins) ? "" : ' data-porthole-strict-parent=""';
32
+ const strictParent = (strict: boolean): string => (strict ? ' data-porthole-strict-parent=""' : "");
30
33
 
31
34
  /**
32
35
  * Who may frame a page: the host origins, then a host's `framedBy` (P141), each checked (they go
@@ -41,13 +44,15 @@ export function ancestorsOf(
41
44
  if (problem !== null) {
42
45
  throw new TypeError(`framedBy: ${problem}`);
43
46
  }
44
- if (hostOrigins.includes(origin)) {
47
+ if (includesOrigin(hostOrigins, origin)) {
45
48
  throw new TypeError(`framedBy: ${origin} is a host origin already`);
46
49
  }
47
50
  }
48
- return [...hostOrigins, ...framedBy.filter((each, at) => framedBy.indexOf(each) === at)].join(
49
- " ",
50
- );
51
+ const normal = framedBy.map(normalOrigin);
52
+ return [
53
+ ...hostOrigins,
54
+ ...framedBy.filter((_, at) => normal.indexOf(normal[at] ?? "") === at),
55
+ ].join(" ");
51
56
  }
52
57
 
53
58
  const escape = (text: string): string =>
@@ -59,6 +64,12 @@ const STYLE =
59
64
  /** Where the pages' scripts are served, on every content origin. */
60
65
  export const STATUS_SCRIPT_PATH = "/__porthole/status.js";
61
66
  export const ENTER_SCRIPT_PATH = "/__porthole/enter.js";
67
+ /**
68
+ * A strict page's scripts (P141): a page whose parent may be an outer page loads these, and every
69
+ * other page 0.14.16's at the paths above, byte for byte (P144).
70
+ */
71
+ export const STRICT_STATUS_SCRIPT_PATH = "/__porthole/status-strict.js";
72
+ export const STRICT_ENTER_SCRIPT_PATH = "/__porthole/enter-strict.js";
62
73
  /** Answers 204 when the request carries a good session for its origin's app, 401 otherwise. */
63
74
  export const SESSION_PATH = "/__porthole/session";
64
75
 
@@ -70,40 +81,42 @@ export const SESSION_PATH = "/__porthole/session";
70
81
  * they say is no secret (P070). Where it names an outer page too (`framedBy`, P141), the parent may be
71
82
  * the outer page: then `*` goes only to a parent the engine names (`location.ancestorOrigins`,
72
83
  * not masked as "null") as one of the host origins, so an outer page is never told. One origin
73
- * failing never stops the page.
84
+ * failing never stops the page. Only a strict page's scripts (`strict`) carry that check: every other
85
+ * page's are 0.14.16's, byte for byte, so their hashes are too (P144).
74
86
  */
75
- const say = (): string =>
76
- `const strict = main.dataset.portholeStrictParent !== undefined;
77
- const say = (params) => {
87
+ const say = (strict: boolean): string =>
88
+ `${strict ? "const strict = main.dataset.portholeStrictParent !== undefined;\n " : ""}const say = (params) => {
78
89
  if (window.parent === window) return;
79
90
  const message = { jsonrpc: "2.0", method: ${JSON.stringify(FRAME_STATUS_METHOD)}, params };
80
91
  const web = hosts.filter((origin) => origin.startsWith("https://") || origin.startsWith("http://"));
81
92
  for (const origin of web) { try { window.parent.postMessage(message, origin); } catch (_) {} }
82
93
  const parent = location.ancestorOrigins && location.ancestorOrigins.length > 0 ? location.ancestorOrigins[0] : null;
83
- if (web.length < hosts.length && (parent === null || !web.includes(parent)) && (!strict || (parent !== null && hosts.includes(parent)))) { try { window.parent.postMessage(message, "*"); } catch (_) {} }
94
+ if (web.length < hosts.length && (parent === null || !web.includes(parent))${strict ? " && (!strict || (parent !== null && hosts.includes(parent)))" : ""}) { try { window.parent.postMessage(message, "*"); } catch (_) {} }
84
95
  };`;
85
96
 
86
97
  /** Tells the host the page is blocked, and why (from the page's data attributes). */
87
- const STATUS_SCRIPT = `(() => {
98
+ const statusScript = (strict: boolean): string => `(() => {
88
99
  const main = document.querySelector("[data-porthole-status]");
89
100
  if (main === null) return;
90
101
  const hosts = JSON.parse(main.dataset.portholeHosts || "[]");
91
- ${say()}
102
+ ${say(strict)}
92
103
  const blocked = { state: "blocked", reason: main.dataset.portholeReason || "error", status: Number(main.dataset.portholeStatus) };
93
104
  if (main.dataset.portholeCode) blocked.code = main.dataset.portholeCode;
94
105
  say(blocked);
95
106
  })();`;
107
+ const STATUS_SCRIPT = statusScript(false);
108
+ const STRICT_STATUS_SCRIPT = statusScript(true);
96
109
 
97
110
  /**
98
111
  * Enters a framed app: says so, checks that the browser kept the session cookie this page's own
99
112
  * answer set (WebKit keeps none in a cross-site frame, P025), then, once this page has loaded,
100
113
  * goes on to the app, or says it is blocked and why.
101
114
  */
102
- const ENTER_SCRIPT = `(async () => {
115
+ const enterScript = (strict: boolean): string => `(async () => {
103
116
  const main = document.querySelector("[data-porthole-enter]");
104
117
  if (main === null) return;
105
118
  const hosts = JSON.parse(main.dataset.portholeHosts || "[]");
106
- ${say()}
119
+ ${say(strict)}
107
120
  say({ state: "entering" });
108
121
  let kept = false;
109
122
  try {
@@ -123,16 +136,21 @@ const ENTER_SCRIPT = `(async () => {
123
136
  main.querySelector("h1").textContent = "Open this app in a new tab";
124
137
  main.querySelector("p").textContent = "This browser keeps no sign-in for it inside a frame.";
125
138
  })();`;
139
+ const ENTER_SCRIPT = enterScript(false);
140
+ const STRICT_ENTER_SCRIPT = enterScript(true);
141
+
142
+ /** The pages' scripts, by path. */
143
+ const PAGE_SCRIPTS: ReadonlyMap<string, string> = new Map([
144
+ [STATUS_SCRIPT_PATH, STATUS_SCRIPT],
145
+ [ENTER_SCRIPT_PATH, ENTER_SCRIPT],
146
+ [STRICT_STATUS_SCRIPT_PATH, STRICT_STATUS_SCRIPT],
147
+ [STRICT_ENTER_SCRIPT_PATH, STRICT_ENTER_SCRIPT],
148
+ ]);
126
149
 
127
150
  /** The pages' scripts, by path: served with the pages' own policy in mind (`script-src 'self'`). */
128
151
  export function pageScript(pathname: string): Response | null {
129
- const body =
130
- pathname === STATUS_SCRIPT_PATH
131
- ? STATUS_SCRIPT
132
- : pathname === ENTER_SCRIPT_PATH
133
- ? ENTER_SCRIPT
134
- : null;
135
- return body === null
152
+ const body = PAGE_SCRIPTS.get(pathname);
153
+ return body === undefined
136
154
  ? null
137
155
  : new Response(body, {
138
156
  headers: {
@@ -166,7 +184,8 @@ export function statusPage(
166
184
  hostOrigins: readonly string[] = [],
167
185
  code?: string,
168
186
  ): Response {
169
- const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escape(title)}</title><style>${STYLE}</style></head><body><main data-porthole-status="${status}" data-porthole-reason="${escape(reason)}"${code === undefined ? "" : ` data-porthole-code="${escape(code)}"`} data-porthole-hosts="${escape(JSON.stringify(hostOrigins))}"${strictParent(frameAncestors, hostOrigins)}><h1>${escape(title)}</h1><p>${escape(detail)}</p></main><script src="${STATUS_SCRIPT_PATH}"></script></body></html>`;
187
+ const strict = isStrict(frameAncestors, hostOrigins);
188
+ const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escape(title)}</title><style>${STYLE}</style></head><body><main data-porthole-status="${status}" data-porthole-reason="${escape(reason)}"${code === undefined ? "" : ` data-porthole-code="${escape(code)}"`} data-porthole-hosts="${escape(JSON.stringify(hostOrigins))}"${strictParent(strict)}><h1>${escape(title)}</h1><p>${escape(detail)}</p></main><script src="${strict ? STRICT_STATUS_SCRIPT_PATH : STATUS_SCRIPT_PATH}"></script></body></html>`;
170
189
  return new Response(method === "HEAD" ? null : body, {
171
190
  status,
172
191
  headers: pageHeaders(frameAncestors, false),
@@ -180,7 +199,8 @@ export function enterPage(
180
199
  hostOrigins: readonly string[],
181
200
  cookie: string,
182
201
  ): Response {
183
- const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Opening the app</title><style>${STYLE}</style></head><body><main data-porthole-enter="" data-porthole-target="${escape(target)}" data-porthole-hosts="${escape(JSON.stringify(hostOrigins))}"${strictParent(frameAncestors, hostOrigins)}><h1>Opening the app…</h1><p></p></main><script src="${ENTER_SCRIPT_PATH}"></script></body></html>`;
202
+ const strict = isStrict(frameAncestors, hostOrigins);
203
+ const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Opening the app</title><style>${STYLE}</style></head><body><main data-porthole-enter="" data-porthole-target="${escape(target)}" data-porthole-hosts="${escape(JSON.stringify(hostOrigins))}"${strictParent(strict)}><h1>Opening the app…</h1><p></p></main><script src="${strict ? STRICT_ENTER_SCRIPT_PATH : ENTER_SCRIPT_PATH}"></script></body></html>`;
184
204
  const headers = new Headers(pageHeaders(frameAncestors, true));
185
205
  headers.set("set-cookie", cookie);
186
206
  return new Response(body, { status: 200, headers });
@@ -194,8 +214,18 @@ const hashOf = (script: string): string => {
194
214
  const padding = (4 - (hash.length % 4)) % 4;
195
215
  return `'sha256-${hash}${"=".repeat(padding)}'`;
196
216
  };
197
- let statusHash: string | null = null;
198
- const hashOfStatus = (): string => (statusHash ??= hashOf(STATUS_SCRIPT));
217
+ const hashes = new Map<string, string>();
218
+ /** An inline script's hash, worked out once. */
219
+ const hashOfScript = (script: string): string => {
220
+ let hash = hashes.get(script);
221
+ if (hash === undefined) {
222
+ hash = hashOf(script);
223
+ hashes.set(script, hash);
224
+ }
225
+ return hash;
226
+ };
227
+ /** The status script a page carries inline: a strict page's (P141), or 0.14.16's. */
228
+ const statusScriptOf = (strict: boolean): string => (strict ? STRICT_STATUS_SCRIPT : STATUS_SCRIPT);
199
229
 
200
230
  /**
201
231
  * A redirect entry's page on the app's own origin (P068): why it shows nothing, told to the page
@@ -216,13 +246,15 @@ export function appStatusPage(
216
246
  link === undefined
217
247
  ? ""
218
248
  : `<p><a href="${escape(link.href)}" target="_top" rel="noopener">${escape(link.text)}</a></p>`;
219
- const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escape(title)}</title><style>${STYLE}a{color:inherit}</style></head><body><main data-porthole-status="${status}" data-porthole-reason="${escape(reason)}" data-porthole-hosts="${escape(JSON.stringify(hostOrigins))}"${strictParent(frameAncestors, hostOrigins)}><h1>${escape(title)}</h1><p>${escape(detail)}</p>${more}</main><script>${STATUS_SCRIPT}</script></body></html>`;
249
+ const strict = isStrict(frameAncestors, hostOrigins);
250
+ const script = statusScriptOf(strict);
251
+ const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escape(title)}</title><style>${STYLE}a{color:inherit}</style></head><body><main data-porthole-status="${status}" data-porthole-reason="${escape(reason)}" data-porthole-hosts="${escape(JSON.stringify(hostOrigins))}"${strictParent(strict)}><h1>${escape(title)}</h1><p>${escape(detail)}</p>${more}</main><script>${script}</script></body></html>`;
220
252
  return new Response(method === "HEAD" ? null : body, {
221
253
  status,
222
254
  headers: {
223
255
  "content-type": "text/html; charset=utf-8",
224
256
  "cache-control": "no-store",
225
- "content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; script-src ${hashOfStatus()}; base-uri 'none'; form-action 'none'; frame-ancestors ${frameAncestors}`,
257
+ "content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; script-src ${hashOfScript(script)}; base-uri 'none'; form-action 'none'; frame-ancestors ${frameAncestors}`,
226
258
  "referrer-policy": "no-referrer",
227
259
  "x-content-type-options": "nosniff",
228
260
  "x-robots-tag": "noindex, nofollow",
@@ -230,16 +262,8 @@ export function appStatusPage(
230
262
  });
231
263
  }
232
264
 
233
- /**
234
- * A page saying why a frame shows nothing, for a relay of the app's own (P072): told to the page
235
- * that frames it, at each web host origin and (a desktop scheme among them) to its parent (P070),
236
- * its one script inline under its hash, so it works on any origin.
237
- */
238
- export function statusPageOf(options: {
239
- readonly status: number;
240
- readonly title: string;
241
- readonly detail: string;
242
- readonly reason?: FrameBlock;
265
+ /** Who a page is framed by and tells: the host origins, and whom else may frame it. */
266
+ export interface HostedPage {
243
267
  readonly hostOrigins: readonly string[];
244
268
  /**
245
269
  * Origins of an outer page that may be an ancestor above a host origin's page (P141): added to its
@@ -248,31 +272,71 @@ export function statusPageOf(options: {
248
272
  readonly framedBy?: readonly string[];
249
273
  /** Who may frame it (`frame-ancestors`): default, the host origins, then `framedBy`. */
250
274
  readonly frameAncestors?: string;
251
- readonly link?: { readonly href: string; readonly text: string };
252
- readonly method?: string;
253
- }): Response {
275
+ readonly embed?: false;
276
+ }
277
+
278
+ /**
279
+ * An embedded document's page (P143, `Grant.embed`): framed by any page (`frame-ancestors *`), and
280
+ * told to no one (it names no host, `data-porthole-hosts="[]"`). For a content Worker's answer
281
+ * before an embed session exists (not public, rate-limited), shown where the embed is.
282
+ */
283
+ export interface EmbedPage {
284
+ readonly embed: true;
285
+ readonly hostOrigins?: never;
286
+ readonly framedBy?: never;
287
+ readonly frameAncestors?: never;
288
+ }
289
+
290
+ /** Whom a page tells, and who may frame it: the host origins' (P141), or an embed's (P143). */
291
+ const framingOf = (
292
+ options: HostedPage | EmbedPage,
293
+ ): { readonly hosts: readonly string[]; readonly ancestors: string } =>
294
+ options.embed === true
295
+ ? { hosts: [], ancestors: "*" }
296
+ : {
297
+ hosts: options.hostOrigins,
298
+ ancestors: options.frameAncestors ?? ancestorsOf(options.hostOrigins, options.framedBy),
299
+ };
300
+
301
+ /**
302
+ * A page saying why a frame shows nothing, for a relay of the app's own (P072): told to the page
303
+ * that frames it, at each web host origin and (a desktop scheme among them) to its parent (P070),
304
+ * its one script inline under its hash, so it works on any origin. With `embed` (P143), framed by
305
+ * any page and told to no one.
306
+ */
307
+ export function statusPageOf(
308
+ options: {
309
+ readonly status: number;
310
+ readonly title: string;
311
+ readonly detail: string;
312
+ readonly reason?: FrameBlock;
313
+ readonly link?: { readonly href: string; readonly text: string };
314
+ readonly method?: string;
315
+ } & (HostedPage | EmbedPage),
316
+ ): Response {
317
+ const { hosts, ancestors } = framingOf(options);
254
318
  return appStatusPage(
255
319
  options.status,
256
320
  options.title,
257
321
  options.detail,
258
- options.frameAncestors ?? ancestorsOf(options.hostOrigins, options.framedBy),
322
+ ancestors,
259
323
  options.reason ?? "error",
260
- options.hostOrigins,
324
+ hosts,
261
325
  options.link,
262
326
  options.method,
263
327
  );
264
328
  }
265
329
 
266
330
  /** A door's word that its display may be framed (P125), from the page's data attributes. */
267
- const DOOR_SCRIPT = `(() => {
331
+ const doorScript = (strict: boolean): string => `(() => {
268
332
  const main = document.querySelector("[data-porthole-door]");
269
333
  if (main === null) return;
270
334
  const hosts = JSON.parse(main.dataset.portholeHosts || "[]");
271
- ${say()}
335
+ ${say(strict)}
272
336
  say({ state: "open" });
273
337
  })();`;
274
- let doorHash: string | null = null;
275
- const hashOfDoor = (): string => (doorHash ??= hashOf(DOOR_SCRIPT));
338
+ const DOOR_SCRIPT = doorScript(false);
339
+ const STRICT_DOOR_SCRIPT = doorScript(true);
276
340
 
277
341
  /**
278
342
  * A door's headers (P125): its one script by its hash (an opaque document has no `'self'` to load
@@ -310,10 +374,12 @@ export interface DoorOptions {
310
374
  export function doorResponse(options: DoorOptions): Response {
311
375
  const hosts = escape(JSON.stringify(options.hostOrigins));
312
376
  const ancestors = options.frameAncestors ?? ancestorsOf(options.hostOrigins, options.framedBy);
313
- const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Opening</title></head><body><main data-porthole-door="" data-porthole-hosts="${hosts}"${strictParent(ancestors, options.hostOrigins)}></main><script>${DOOR_SCRIPT}</script></body></html>`;
377
+ const strict = isStrict(ancestors, options.hostOrigins);
378
+ const script = strict ? STRICT_DOOR_SCRIPT : DOOR_SCRIPT;
379
+ const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Opening</title></head><body><main data-porthole-door="" data-porthole-hosts="${hosts}"${strictParent(strict)}></main><script>${script}</script></body></html>`;
314
380
  return new Response(options.method?.toUpperCase() === "HEAD" ? null : body, {
315
381
  status: 200,
316
- headers: doorHeaders(hashOfDoor(), ancestors),
382
+ headers: doorHeaders(hashOfScript(script), ancestors),
317
383
  });
318
384
  }
319
385
 
@@ -321,22 +387,29 @@ export function doorResponse(options: DoorOptions): Response {
321
387
  * A door that doesn't open (P125): why, said `blocked` to the page that frames it, as a content
322
388
  * origin's status page says it (`session` 401: no ticket, or one used, ended, or not a door's of
323
389
  * this instance on this origin; `denied` 403 with the host's code; `not-found` 404: no document, or
324
- * a file set whose entry isn't a page; `error` 500).
390
+ * a file set whose entry isn't a page; `error` 500). With `embed` (P143), for a content Worker's
391
+ * refusal before an embed session exists: framed by any page and told to no one.
325
392
  */
326
393
  export function doorStatusResponse(
327
- options: DoorOptions & {
394
+ options: (
395
+ | (DoorOptions & { readonly embed?: false })
396
+ | (EmbedPage & { readonly method?: string })
397
+ ) & {
328
398
  readonly status: number;
329
399
  readonly reason: FrameBlock;
330
400
  readonly code?: string;
331
401
  },
332
402
  ): Response {
333
403
  const { status, reason, code } = options;
334
- const hosts = escape(JSON.stringify(options.hostOrigins));
335
- const ancestors = options.frameAncestors ?? ancestorsOf(options.hostOrigins, options.framedBy);
336
- const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Not shown</title></head><body><main data-porthole-status="${status}" data-porthole-reason="${escape(reason)}"${code === undefined ? "" : ` data-porthole-code="${escape(code)}"`} data-porthole-hosts="${hosts}"${strictParent(ancestors, options.hostOrigins)}></main><script>${STATUS_SCRIPT}</script></body></html>`;
404
+ const framing = framingOf(options);
405
+ const hosts = escape(JSON.stringify(framing.hosts));
406
+ const ancestors = framing.ancestors;
407
+ const strict = isStrict(ancestors, framing.hosts);
408
+ const script = statusScriptOf(strict);
409
+ const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Not shown</title></head><body><main data-porthole-status="${status}" data-porthole-reason="${escape(reason)}"${code === undefined ? "" : ` data-porthole-code="${escape(code)}"`} data-porthole-hosts="${hosts}"${strictParent(strict)}></main><script>${script}</script></body></html>`;
337
410
  return new Response(options.method?.toUpperCase() === "HEAD" ? null : body, {
338
411
  status,
339
- headers: doorHeaders(hashOfStatus(), ancestors),
412
+ headers: doorHeaders(hashOfScript(script), ancestors),
340
413
  });
341
414
  }
342
415