@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.
@@ -25,12 +25,22 @@ export declare function isExactOrigin(origin: unknown): origin is string;
25
25
  export declare function isHostOrigin(origin: unknown): origin is string;
26
26
  /** Why `origin` can't be a host origin, in words a host's developer can act on; null if it can. */
27
27
  export declare function hostOriginProblem(origin: unknown): string | null;
28
+ /**
29
+ * An origin as a browser serializes it, for comparing two (P144):
30
+ * scheme and host lowercase, and for `http`/`https` a default port dropped, so
31
+ * `https://app.example:443` is `https://app.example`. Any other scheme's origin (a desktop app's) is
32
+ * only lowercased.
33
+ */
34
+ export declare function normalOrigin(origin: string): string;
35
+ /** Whether `origin` is one of `origins`, compared as browsers serialize them (`normalOrigin`). */
36
+ export declare const includesOrigin: (origins: readonly string[], origin: string) => boolean;
28
37
  /**
29
38
  * Why `origin` can't be one of a host's `framedBy` (P141): an outer page that may be an
30
39
  * ancestor of every frame the host shows, above the host's own page, and never a host origin. An
31
40
  * exact web origin, `https://host[:port]` (lowercase, no path, no wildcard), or `http://` on
32
41
  * loopback alone (`localhost`, `*.localhost`, `127.0.0.1`, `[::1]`) for development: never a
33
- * desktop scheme, `"null"`, a CSP keyword or a list. Null if it can be.
42
+ * desktop scheme, `"null"`, a CSP keyword or a list. Its port, where it names one, is 1 to 65535
43
+ * in plain decimal, and its host is as the URL parser gives it back (P145). Null if it can be.
34
44
  */
35
45
  export declare function framedByProblem(origin: unknown): string | null;
36
46
  /**
@@ -48,23 +48,74 @@ const HOST_ORIGIN = /^[a-z][a-z0-9+.-]*:\/\/([a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-
48
48
  export function isHostOrigin(origin) {
49
49
  return typeof origin === "string" && origin.length <= 300 && HOST_ORIGIN.test(origin);
50
50
  }
51
+ /**
52
+ * Whether an origin that matched `HOST_ORIGIN` is one a browser can serialize as it is written
53
+ * (P145): a port, where it names one, is 1 to 65535 in plain decimal (never `:0`, `:99999` or
54
+ * `:0443`), and an `http`/`https` host is as the URL parser gives it back (never `0x7f.0.0.1` for
55
+ * `127.0.0.1`). A default port (`:443`) is still taken: browsers drop it, and `normalOrigin`
56
+ * compares it so (P144). Such an origin matches no frame and no message, so refusing it only says
57
+ * so early.
58
+ */
59
+ function serializable(origin) {
60
+ const port = /:(\d+)$/u.exec(origin)?.[1];
61
+ if (port !== undefined && !(/^[1-9]\d{0,4}$/u.test(port) && Number(port) <= 65_535)) {
62
+ return false;
63
+ }
64
+ const scheme = origin.slice(0, origin.indexOf(":"));
65
+ if (scheme !== "http" && scheme !== "https") {
66
+ return true;
67
+ }
68
+ try {
69
+ const url = new URL(origin);
70
+ return url.hostname === origin.slice(scheme.length + 3).replace(/:\d+$/u, "");
71
+ }
72
+ catch {
73
+ return false;
74
+ }
75
+ }
51
76
  /** Why `origin` can't be a host origin, in words a host's developer can act on; null if it can. */
52
77
  export function hostOriginProblem(origin) {
53
78
  if (isHostOrigin(origin)) {
54
- return null;
79
+ return serializable(origin)
80
+ ? null
81
+ : `${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)`;
55
82
  }
56
83
  if (origin === "null") {
57
84
  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)';
58
85
  }
59
86
  return `${JSON.stringify(origin)} is not an exact origin (scheme://host[:port], lowercase, no path)`;
60
87
  }
88
+ /**
89
+ * An origin as a browser serializes it, for comparing two (P144):
90
+ * scheme and host lowercase, and for `http`/`https` a default port dropped, so
91
+ * `https://app.example:443` is `https://app.example`. Any other scheme's origin (a desktop app's) is
92
+ * only lowercased.
93
+ */
94
+ export function normalOrigin(origin) {
95
+ const lower = origin.toLowerCase();
96
+ if (lower.startsWith("https://") || lower.startsWith("http://")) {
97
+ try {
98
+ const serialized = new URL(lower).origin;
99
+ if (serialized !== "null") {
100
+ return serialized;
101
+ }
102
+ }
103
+ catch {
104
+ // Not a URL: compared as it is, lowercase.
105
+ }
106
+ }
107
+ return lower;
108
+ }
109
+ /** Whether `origin` is one of `origins`, compared as browsers serialize them (`normalOrigin`). */
110
+ export const includesOrigin = (origins, origin) => origins.some((each) => normalOrigin(each) === normalOrigin(origin));
61
111
  const LOOPBACK_HOST = (host) => host === "localhost" || host.endsWith(".localhost") || host === "127.0.0.1" || host === "[::1]";
62
112
  /**
63
113
  * Why `origin` can't be one of a host's `framedBy` (P141): an outer page that may be an
64
114
  * ancestor of every frame the host shows, above the host's own page, and never a host origin. An
65
115
  * exact web origin, `https://host[:port]` (lowercase, no path, no wildcard), or `http://` on
66
116
  * loopback alone (`localhost`, `*.localhost`, `127.0.0.1`, `[::1]`) for development: never a
67
- * desktop scheme, `"null"`, a CSP keyword or a list. Null if it can be.
117
+ * desktop scheme, `"null"`, a CSP keyword or a list. Its port, where it names one, is 1 to 65535
118
+ * in plain decimal, and its host is as the URL parser gives it back (P145). Null if it can be.
68
119
  */
69
120
  export function framedByProblem(origin) {
70
121
  const parsed = typeof origin === "string" && isHostOrigin(origin) ? parseOrigin(origin) : null;
@@ -72,6 +123,9 @@ export function framedByProblem(origin) {
72
123
  !(parsed.scheme === "https" || (parsed.scheme === "http" && LOOPBACK_HOST(parsed.host)))) {
73
124
  return `${JSON.stringify(origin)} is not an exact https origin (https://host[:port], lowercase, no path; http only on loopback)`;
74
125
  }
126
+ if (!serializable(origin)) {
127
+ 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)`;
128
+ }
75
129
  return null;
76
130
  }
77
131
  /**
@@ -87,6 +87,17 @@ export interface ContentHostOptions<V> {
87
87
  * own `frame-ancestors` (its page's, which Porthole doesn't send) is the app's to set.
88
88
  */
89
89
  readonly framedBy?: readonly string[];
90
+ /**
91
+ * Whether `server.issue` takes an embed grant (P143, `Grant.embed`): a public artifact page that
92
+ * any site may frame, with no host (`ServerOptions.embeds`). Default false: an embed grant is
93
+ * refused at issue. Mint one from a route of your own that decides the page is public
94
+ * (`host.server.issue(instance, { anonymous: true, embed: true })`), never from `access`: `access`
95
+ * answers your readers (the issue endpoint, a clean address), and the kit refuses an `access`
96
+ * answer with `embed` (409 at the issue endpoint and a clean address's resolve; a clean address's
97
+ * tab gets its 409 page, as `enterBy` refuses it) (P145). Only an embed session's answers say
98
+ * `frame-ancestors *`; every other answer is as without it.
99
+ */
100
+ readonly embeds?: boolean;
90
101
  /** At least 32 random bytes (or a string of at least 32 bytes). */
91
102
  readonly secret: Uint8Array | string;
92
103
  readonly tickets?: TicketStore;
@@ -121,7 +132,11 @@ export interface ContentHostOptions<V> {
121
132
  * version), check its fields, refuse the rest. The client never chooses an origin.
122
133
  */
123
134
  readonly instance: (proposal: InstanceRef, viewer: V | null, request: Request) => Awaitable<InstanceRef | null>;
124
- /** Policy 2, access at issue: may this viewer see it, and with what grant (null: 401/403). */
135
+ /**
136
+ * Policy 2, access at issue: may this viewer see it, and with what grant (null: 401/403). It
137
+ * answers readers, so never with `embed` (refused, P145): an embed grant is minted from a route
138
+ * of your own through `host.server.issue`.
139
+ */
125
140
  readonly access: (instance: InstanceRef, viewer: V | null, request: Request) => Awaitable<Grant | null>;
126
141
  /** Policy 3, on every request after (P050): may this cookie still see it. */
127
142
  readonly authorize?: (request: AuthorizeRequest) => Awaitable<AuthorizeAnswer>;
@@ -288,6 +288,7 @@ export function createContentHost(options) {
288
288
  secret,
289
289
  hostOrigins: options.appOrigins,
290
290
  ...(options.framedBy === undefined ? {} : { framedBy: options.framedBy }),
291
+ ...(options.embeds === undefined ? {} : { embeds: options.embeds }),
291
292
  configs,
292
293
  ...(options.source === undefined ? {} : { artifacts: { get: options.source } }),
293
294
  ...(options.assets === undefined
@@ -668,6 +669,11 @@ export function createContentHost(options) {
668
669
  };
669
670
  /** A location issued for what the host's access granted, with its clean address. */
670
671
  async function issuedFor(instance, grant, request, more = {}) {
672
+ // `access` answers readers, here and at a clean address: an embed grant (P143) is never
673
+ // theirs, whatever `embeds` says (P145). A host mints it from a route of its own.
674
+ if (grant.embed !== undefined) {
675
+ return refusal(409, "refused", "access never answers an embed grant: mint it from a route of your own with host.server.issue (P145)");
676
+ }
671
677
  let location;
672
678
  try {
673
679
  location = await server.issue(instance, grant, more.page === undefined ? undefined : { page: more.page });
@@ -7,6 +7,12 @@ export declare function ancestorsOf(hostOrigins: readonly string[], framedBy?: r
7
7
  /** Where the pages' scripts are served, on every content origin. */
8
8
  export declare const STATUS_SCRIPT_PATH = "/__porthole/status.js";
9
9
  export declare const ENTER_SCRIPT_PATH = "/__porthole/enter.js";
10
+ /**
11
+ * A strict page's scripts (P141): a page whose parent may be an outer page loads these, and every
12
+ * other page 0.14.16's at the paths above, byte for byte (P144).
13
+ */
14
+ export declare const STRICT_STATUS_SCRIPT_PATH = "/__porthole/status-strict.js";
15
+ export declare const STRICT_ENTER_SCRIPT_PATH = "/__porthole/enter-strict.js";
10
16
  /** Answers 204 when the request carries a good session for its origin's app, 401 otherwise. */
11
17
  export declare const SESSION_PATH = "/__porthole/session";
12
18
  /** The pages' scripts, by path: served with the pages' own policy in mind (`script-src 'self'`). */
@@ -23,30 +29,46 @@ export declare function appStatusPage(status: number, title: string, detail: str
23
29
  readonly href: string;
24
30
  readonly text: string;
25
31
  }, method?: string): Response;
32
+ /** Who a page is framed by and tells: the host origins, and whom else may frame it. */
33
+ export interface HostedPage {
34
+ readonly hostOrigins: readonly string[];
35
+ /**
36
+ * Origins of an outer page that may be an ancestor above a host origin's page (P141): added to its
37
+ * `frame-ancestors` after the host origins, never told anything. Default none.
38
+ */
39
+ readonly framedBy?: readonly string[];
40
+ /** Who may frame it (`frame-ancestors`): default, the host origins, then `framedBy`. */
41
+ readonly frameAncestors?: string;
42
+ readonly embed?: false;
43
+ }
44
+ /**
45
+ * An embedded document's page (P143, `Grant.embed`): framed by any page (`frame-ancestors *`), and
46
+ * told to no one (it names no host, `data-porthole-hosts="[]"`). For a content Worker's answer
47
+ * before an embed session exists (not public, rate-limited), shown where the embed is.
48
+ */
49
+ export interface EmbedPage {
50
+ readonly embed: true;
51
+ readonly hostOrigins?: never;
52
+ readonly framedBy?: never;
53
+ readonly frameAncestors?: never;
54
+ }
26
55
  /**
27
56
  * A page saying why a frame shows nothing, for a relay of the app's own (P072): told to the page
28
57
  * that frames it, at each web host origin and (a desktop scheme among them) to its parent (P070),
29
- * its one script inline under its hash, so it works on any origin.
58
+ * its one script inline under its hash, so it works on any origin. With `embed` (P143), framed by
59
+ * any page and told to no one.
30
60
  */
31
61
  export declare function statusPageOf(options: {
32
62
  readonly status: number;
33
63
  readonly title: string;
34
64
  readonly detail: string;
35
65
  readonly reason?: FrameBlock;
36
- readonly hostOrigins: readonly string[];
37
- /**
38
- * Origins of an outer page that may be an ancestor above a host origin's page (P141): added to its
39
- * `frame-ancestors` after the host origins, never told anything. Default none.
40
- */
41
- readonly framedBy?: readonly string[];
42
- /** Who may frame it (`frame-ancestors`): default, the host origins, then `framedBy`. */
43
- readonly frameAncestors?: string;
44
66
  readonly link?: {
45
67
  readonly href: string;
46
68
  readonly text: string;
47
69
  };
48
70
  readonly method?: string;
49
- }): Response;
71
+ } & (HostedPage | EmbedPage)): Response;
50
72
  /**
51
73
  * What a door is given: the host origins it tells, and who may frame it (default, those and then
52
74
  * `framedBy`, P141: an outer page's origins above a host origin's page, never told anything).
@@ -68,9 +90,14 @@ export declare function doorResponse(options: DoorOptions): Response;
68
90
  * A door that doesn't open (P125): why, said `blocked` to the page that frames it, as a content
69
91
  * origin's status page says it (`session` 401: no ticket, or one used, ended, or not a door's of
70
92
  * this instance on this origin; `denied` 403 with the host's code; `not-found` 404: no document, or
71
- * a file set whose entry isn't a page; `error` 500).
93
+ * a file set whose entry isn't a page; `error` 500). With `embed` (P143), for a content Worker's
94
+ * refusal before an embed session exists: framed by any page and told to no one.
72
95
  */
73
- export declare function doorStatusResponse(options: DoorOptions & {
96
+ export declare function doorStatusResponse(options: ((DoorOptions & {
97
+ readonly embed?: false;
98
+ }) | (EmbedPage & {
99
+ readonly method?: string;
100
+ })) & {
74
101
  readonly status: number;
75
102
  readonly reason: FrameBlock;
76
103
  readonly code?: string;
@@ -1,5 +1,5 @@
1
1
  import { DOOR_SANDBOX_TOKENS } from "../compile/policy.js";
2
- import { framedByProblem } from "../isolation/served.js";
2
+ import { framedByProblem, includesOrigin, normalOrigin } from "../isolation/served.js";
3
3
  import { FRAME_STATUS_METHOD } from "../isolation/types.js";
4
4
  import { base64url, sha256, utf8 } from "./crypto.js";
5
5
  /**
@@ -19,8 +19,10 @@ const heldToHosts = (frameAncestors, hostOrigins) => frameAncestors
19
19
  .split(" ")
20
20
  .filter((each) => each !== "")
21
21
  .every((each) => hostOrigins.includes(each));
22
+ /** Whether a page is strict: its parent isn't held to its hosts (`heldToHosts`). */
23
+ const isStrict = (frameAncestors, hostOrigins) => !heldToHosts(frameAncestors, hostOrigins);
22
24
  /** The attribute that says so, on a page's `<main>`: none where its parent is held to its hosts. */
23
- const strictParent = (frameAncestors, hostOrigins) => heldToHosts(frameAncestors, hostOrigins) ? "" : ' data-porthole-strict-parent=""';
25
+ const strictParent = (strict) => (strict ? ' data-porthole-strict-parent=""' : "");
24
26
  /**
25
27
  * Who may frame a page: the host origins, then a host's `framedBy` (P141), each checked (they go
26
28
  * into a header).
@@ -31,17 +33,27 @@ export function ancestorsOf(hostOrigins, framedBy = []) {
31
33
  if (problem !== null) {
32
34
  throw new TypeError(`framedBy: ${problem}`);
33
35
  }
34
- if (hostOrigins.includes(origin)) {
36
+ if (includesOrigin(hostOrigins, origin)) {
35
37
  throw new TypeError(`framedBy: ${origin} is a host origin already`);
36
38
  }
37
39
  }
38
- return [...hostOrigins, ...framedBy.filter((each, at) => framedBy.indexOf(each) === at)].join(" ");
40
+ const normal = framedBy.map(normalOrigin);
41
+ return [
42
+ ...hostOrigins,
43
+ ...framedBy.filter((_, at) => normal.indexOf(normal[at] ?? "") === at),
44
+ ].join(" ");
39
45
  }
40
46
  const escape = (text) => text.replace(/[&<>"']/gu, (char) => `&#${char.charCodeAt(0)};`);
41
47
  const STYLE = ":root{color-scheme:light dark;font-family:system-ui,sans-serif}body{margin:0;min-height:100vh;display:grid;place-items:center;background:Canvas;color:CanvasText}main{max-width:420px;padding:24px}h1{font-size:17px;margin:0 0 8px}p{margin:0;opacity:.75;line-height:1.5}";
42
48
  /** Where the pages' scripts are served, on every content origin. */
43
49
  export const STATUS_SCRIPT_PATH = "/__porthole/status.js";
44
50
  export const ENTER_SCRIPT_PATH = "/__porthole/enter.js";
51
+ /**
52
+ * A strict page's scripts (P141): a page whose parent may be an outer page loads these, and every
53
+ * other page 0.14.16's at the paths above, byte for byte (P144).
54
+ */
55
+ export const STRICT_STATUS_SCRIPT_PATH = "/__porthole/status-strict.js";
56
+ export const STRICT_ENTER_SCRIPT_PATH = "/__porthole/enter-strict.js";
45
57
  /** Answers 204 when the request carries a good session for its origin's app, 401 otherwise. */
46
58
  export const SESSION_PATH = "/__porthole/session";
47
59
  /**
@@ -52,37 +64,39 @@ export const SESSION_PATH = "/__porthole/session";
52
64
  * they say is no secret (P070). Where it names an outer page too (`framedBy`, P141), the parent may be
53
65
  * the outer page: then `*` goes only to a parent the engine names (`location.ancestorOrigins`,
54
66
  * not masked as "null") as one of the host origins, so an outer page is never told. One origin
55
- * failing never stops the page.
67
+ * failing never stops the page. Only a strict page's scripts (`strict`) carry that check: every other
68
+ * page's are 0.14.16's, byte for byte, so their hashes are too (P144).
56
69
  */
57
- const say = () => `const strict = main.dataset.portholeStrictParent !== undefined;
58
- const say = (params) => {
70
+ const say = (strict) => `${strict ? "const strict = main.dataset.portholeStrictParent !== undefined;\n " : ""}const say = (params) => {
59
71
  if (window.parent === window) return;
60
72
  const message = { jsonrpc: "2.0", method: ${JSON.stringify(FRAME_STATUS_METHOD)}, params };
61
73
  const web = hosts.filter((origin) => origin.startsWith("https://") || origin.startsWith("http://"));
62
74
  for (const origin of web) { try { window.parent.postMessage(message, origin); } catch (_) {} }
63
75
  const parent = location.ancestorOrigins && location.ancestorOrigins.length > 0 ? location.ancestorOrigins[0] : null;
64
- if (web.length < hosts.length && (parent === null || !web.includes(parent)) && (!strict || (parent !== null && hosts.includes(parent)))) { try { window.parent.postMessage(message, "*"); } catch (_) {} }
76
+ if (web.length < hosts.length && (parent === null || !web.includes(parent))${strict ? " && (!strict || (parent !== null && hosts.includes(parent)))" : ""}) { try { window.parent.postMessage(message, "*"); } catch (_) {} }
65
77
  };`;
66
78
  /** Tells the host the page is blocked, and why (from the page's data attributes). */
67
- const STATUS_SCRIPT = `(() => {
79
+ const statusScript = (strict) => `(() => {
68
80
  const main = document.querySelector("[data-porthole-status]");
69
81
  if (main === null) return;
70
82
  const hosts = JSON.parse(main.dataset.portholeHosts || "[]");
71
- ${say()}
83
+ ${say(strict)}
72
84
  const blocked = { state: "blocked", reason: main.dataset.portholeReason || "error", status: Number(main.dataset.portholeStatus) };
73
85
  if (main.dataset.portholeCode) blocked.code = main.dataset.portholeCode;
74
86
  say(blocked);
75
87
  })();`;
88
+ const STATUS_SCRIPT = statusScript(false);
89
+ const STRICT_STATUS_SCRIPT = statusScript(true);
76
90
  /**
77
91
  * Enters a framed app: says so, checks that the browser kept the session cookie this page's own
78
92
  * answer set (WebKit keeps none in a cross-site frame, P025), then, once this page has loaded,
79
93
  * goes on to the app, or says it is blocked and why.
80
94
  */
81
- const ENTER_SCRIPT = `(async () => {
95
+ const enterScript = (strict) => `(async () => {
82
96
  const main = document.querySelector("[data-porthole-enter]");
83
97
  if (main === null) return;
84
98
  const hosts = JSON.parse(main.dataset.portholeHosts || "[]");
85
- ${say()}
99
+ ${say(strict)}
86
100
  say({ state: "entering" });
87
101
  let kept = false;
88
102
  try {
@@ -102,14 +116,19 @@ const ENTER_SCRIPT = `(async () => {
102
116
  main.querySelector("h1").textContent = "Open this app in a new tab";
103
117
  main.querySelector("p").textContent = "This browser keeps no sign-in for it inside a frame.";
104
118
  })();`;
119
+ const ENTER_SCRIPT = enterScript(false);
120
+ const STRICT_ENTER_SCRIPT = enterScript(true);
121
+ /** The pages' scripts, by path. */
122
+ const PAGE_SCRIPTS = new Map([
123
+ [STATUS_SCRIPT_PATH, STATUS_SCRIPT],
124
+ [ENTER_SCRIPT_PATH, ENTER_SCRIPT],
125
+ [STRICT_STATUS_SCRIPT_PATH, STRICT_STATUS_SCRIPT],
126
+ [STRICT_ENTER_SCRIPT_PATH, STRICT_ENTER_SCRIPT],
127
+ ]);
105
128
  /** The pages' scripts, by path: served with the pages' own policy in mind (`script-src 'self'`). */
106
129
  export function pageScript(pathname) {
107
- const body = pathname === STATUS_SCRIPT_PATH
108
- ? STATUS_SCRIPT
109
- : pathname === ENTER_SCRIPT_PATH
110
- ? ENTER_SCRIPT
111
- : null;
112
- return body === null
130
+ const body = PAGE_SCRIPTS.get(pathname);
131
+ return body === undefined
113
132
  ? null
114
133
  : new Response(body, {
115
134
  headers: {
@@ -130,7 +149,8 @@ const pageHeaders = (frameAncestors, connect) => ({
130
149
  "x-robots-tag": "noindex, nofollow",
131
150
  });
132
151
  export function statusPage(status, title, detail, frameAncestors, method = "GET", reason = "error", hostOrigins = [], code) {
133
- 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>`;
152
+ const strict = isStrict(frameAncestors, hostOrigins);
153
+ 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>`;
134
154
  return new Response(method === "HEAD" ? null : body, {
135
155
  status,
136
156
  headers: pageHeaders(frameAncestors, false),
@@ -138,7 +158,8 @@ export function statusPage(status, title, detail, frameAncestors, method = "GET"
138
158
  }
139
159
  /** The page a framed app is entered through (its answer also sets the session cookie). */
140
160
  export function enterPage(target, frameAncestors, hostOrigins, cookie) {
141
- 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>`;
161
+ const strict = isStrict(frameAncestors, hostOrigins);
162
+ 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>`;
142
163
  const headers = new Headers(pageHeaders(frameAncestors, true));
143
164
  headers.set("set-cookie", cookie);
144
165
  return new Response(body, { status: 200, headers });
@@ -151,8 +172,18 @@ const hashOf = (script) => {
151
172
  const padding = (4 - (hash.length % 4)) % 4;
152
173
  return `'sha256-${hash}${"=".repeat(padding)}'`;
153
174
  };
154
- let statusHash = null;
155
- const hashOfStatus = () => (statusHash ??= hashOf(STATUS_SCRIPT));
175
+ const hashes = new Map();
176
+ /** An inline script's hash, worked out once. */
177
+ const hashOfScript = (script) => {
178
+ let hash = hashes.get(script);
179
+ if (hash === undefined) {
180
+ hash = hashOf(script);
181
+ hashes.set(script, hash);
182
+ }
183
+ return hash;
184
+ };
185
+ /** The status script a page carries inline: a strict page's (P141), or 0.14.16's. */
186
+ const statusScriptOf = (strict) => (strict ? STRICT_STATUS_SCRIPT : STATUS_SCRIPT);
156
187
  /**
157
188
  * A redirect entry's page on the app's own origin (P068): why it shows nothing, told to the page
158
189
  * that frames it like a content origin's page. Plain, no app chrome; its one script inline under
@@ -162,37 +193,48 @@ export function appStatusPage(status, title, detail, frameAncestors, reason, hos
162
193
  const more = link === undefined
163
194
  ? ""
164
195
  : `<p><a href="${escape(link.href)}" target="_top" rel="noopener">${escape(link.text)}</a></p>`;
165
- 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>`;
196
+ const strict = isStrict(frameAncestors, hostOrigins);
197
+ const script = statusScriptOf(strict);
198
+ 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>`;
166
199
  return new Response(method === "HEAD" ? null : body, {
167
200
  status,
168
201
  headers: {
169
202
  "content-type": "text/html; charset=utf-8",
170
203
  "cache-control": "no-store",
171
- "content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; script-src ${hashOfStatus()}; base-uri 'none'; form-action 'none'; frame-ancestors ${frameAncestors}`,
204
+ "content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; script-src ${hashOfScript(script)}; base-uri 'none'; form-action 'none'; frame-ancestors ${frameAncestors}`,
172
205
  "referrer-policy": "no-referrer",
173
206
  "x-content-type-options": "nosniff",
174
207
  "x-robots-tag": "noindex, nofollow",
175
208
  },
176
209
  });
177
210
  }
211
+ /** Whom a page tells, and who may frame it: the host origins' (P141), or an embed's (P143). */
212
+ const framingOf = (options) => options.embed === true
213
+ ? { hosts: [], ancestors: "*" }
214
+ : {
215
+ hosts: options.hostOrigins,
216
+ ancestors: options.frameAncestors ?? ancestorsOf(options.hostOrigins, options.framedBy),
217
+ };
178
218
  /**
179
219
  * A page saying why a frame shows nothing, for a relay of the app's own (P072): told to the page
180
220
  * that frames it, at each web host origin and (a desktop scheme among them) to its parent (P070),
181
- * its one script inline under its hash, so it works on any origin.
221
+ * its one script inline under its hash, so it works on any origin. With `embed` (P143), framed by
222
+ * any page and told to no one.
182
223
  */
183
224
  export function statusPageOf(options) {
184
- return appStatusPage(options.status, options.title, options.detail, options.frameAncestors ?? ancestorsOf(options.hostOrigins, options.framedBy), options.reason ?? "error", options.hostOrigins, options.link, options.method);
225
+ const { hosts, ancestors } = framingOf(options);
226
+ return appStatusPage(options.status, options.title, options.detail, ancestors, options.reason ?? "error", hosts, options.link, options.method);
185
227
  }
186
228
  /** A door's word that its display may be framed (P125), from the page's data attributes. */
187
- const DOOR_SCRIPT = `(() => {
229
+ const doorScript = (strict) => `(() => {
188
230
  const main = document.querySelector("[data-porthole-door]");
189
231
  if (main === null) return;
190
232
  const hosts = JSON.parse(main.dataset.portholeHosts || "[]");
191
- ${say()}
233
+ ${say(strict)}
192
234
  say({ state: "open" });
193
235
  })();`;
194
- let doorHash = null;
195
- const hashOfDoor = () => (doorHash ??= hashOf(DOOR_SCRIPT));
236
+ const DOOR_SCRIPT = doorScript(false);
237
+ const STRICT_DOOR_SCRIPT = doorScript(true);
196
238
  /**
197
239
  * A door's headers (P125): its one script by its hash (an opaque document has no `'self'` to load
198
240
  * one from), nothing else loads, sandboxed with scripts alone in its header too (opaque on a tab, and
@@ -216,26 +258,32 @@ const doorHeaders = (script, frameAncestors) => new Headers({
216
258
  export function doorResponse(options) {
217
259
  const hosts = escape(JSON.stringify(options.hostOrigins));
218
260
  const ancestors = options.frameAncestors ?? ancestorsOf(options.hostOrigins, options.framedBy);
219
- 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>`;
261
+ const strict = isStrict(ancestors, options.hostOrigins);
262
+ const script = strict ? STRICT_DOOR_SCRIPT : DOOR_SCRIPT;
263
+ 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>`;
220
264
  return new Response(options.method?.toUpperCase() === "HEAD" ? null : body, {
221
265
  status: 200,
222
- headers: doorHeaders(hashOfDoor(), ancestors),
266
+ headers: doorHeaders(hashOfScript(script), ancestors),
223
267
  });
224
268
  }
225
269
  /**
226
270
  * A door that doesn't open (P125): why, said `blocked` to the page that frames it, as a content
227
271
  * origin's status page says it (`session` 401: no ticket, or one used, ended, or not a door's of
228
272
  * this instance on this origin; `denied` 403 with the host's code; `not-found` 404: no document, or
229
- * a file set whose entry isn't a page; `error` 500).
273
+ * a file set whose entry isn't a page; `error` 500). With `embed` (P143), for a content Worker's
274
+ * refusal before an embed session exists: framed by any page and told to no one.
230
275
  */
231
276
  export function doorStatusResponse(options) {
232
277
  const { status, reason, code } = options;
233
- const hosts = escape(JSON.stringify(options.hostOrigins));
234
- const ancestors = options.frameAncestors ?? ancestorsOf(options.hostOrigins, options.framedBy);
235
- 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>`;
278
+ const framing = framingOf(options);
279
+ const hosts = escape(JSON.stringify(framing.hosts));
280
+ const ancestors = framing.ancestors;
281
+ const strict = isStrict(ancestors, framing.hosts);
282
+ const script = statusScriptOf(strict);
283
+ 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>`;
236
284
  return new Response(options.method?.toUpperCase() === "HEAD" ? null : body, {
237
285
  status,
238
- headers: doorHeaders(hashOfStatus(), ancestors),
286
+ headers: doorHeaders(hashOfScript(script), ancestors),
239
287
  });
240
288
  }
241
289
  /**