@botiverse/porthole 0.14.17 → 0.15.0

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.
@@ -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