@botiverse/porthole 0.15.3 → 0.16.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.
Files changed (107) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/dist/bridge/bridge.d.ts +1 -8
  3. package/dist/bridge/bridge.js +0 -7
  4. package/dist/check/page-source.js +1 -1
  5. package/dist/check/page.js +1 -1
  6. package/dist/compile/policy.d.ts +0 -7
  7. package/dist/compile/policy.js +1 -10
  8. package/dist/config/capabilities.d.ts +8 -14
  9. package/dist/config/capabilities.js +4 -5
  10. package/dist/config/schema.d.ts +2 -13
  11. package/dist/config/validate.js +0 -24
  12. package/dist/conformance/behavior.js +26 -37
  13. package/dist/conformance/clipboard.js +47 -1
  14. package/dist/conformance/harness-source.js +1 -1
  15. package/dist/displays/displays.js +1 -3
  16. package/dist/guide/limits.js +1 -1
  17. package/dist/guide/runtime.js +1 -1
  18. package/dist/host/create-host.d.ts +1 -1
  19. package/dist/host/create-host.js +6 -51
  20. package/dist/host/door.d.ts +1 -1
  21. package/dist/host/locate.d.ts +1 -1
  22. package/dist/host/locate.js +2 -2
  23. package/dist/host/outcome.d.ts +5 -12
  24. package/dist/host/outcome.js +8 -16
  25. package/dist/host/types.d.ts +6 -22
  26. package/dist/index.d.ts +2 -4
  27. package/dist/index.js +2 -4
  28. package/dist/isolation/served.d.ts +4 -14
  29. package/dist/isolation/served.js +7 -28
  30. package/dist/isolation/types.d.ts +2 -25
  31. package/dist/isolation/types.js +0 -23
  32. package/dist/platform/focus-field.d.ts +11 -0
  33. package/dist/platform/focus-field.js +18 -0
  34. package/dist/platform/types.d.ts +6 -22
  35. package/dist/platform/web.js +8 -106
  36. package/dist/presets/presets.d.ts +0 -2
  37. package/dist/presets/presets.js +0 -1
  38. package/dist/react/frame.d.ts +0 -8
  39. package/dist/react/frame.js +0 -4
  40. package/dist/runtime/contract.d.ts +2 -2
  41. package/dist/runtime/contract.js +2 -2
  42. package/dist/runtime/types.generated.js +6 -6
  43. package/dist/server/files.js +7 -23
  44. package/dist/server/host.d.ts +1 -1
  45. package/dist/server/index.d.ts +1 -1
  46. package/dist/server/index.js +4 -6
  47. package/dist/server/naming.js +1 -1
  48. package/dist/server/server.js +28 -166
  49. package/dist/server/types.d.ts +7 -7
  50. package/dist/shell/plan.d.ts +0 -5
  51. package/dist/shell/plan.js +2 -4
  52. package/dist/shell/runtime.js +1 -268
  53. package/docs/ADOPTING.md +42 -138
  54. package/docs/ARCHITECTURE.md +0 -33
  55. package/docs/DECISIONS.md +115 -10
  56. package/docs/DESIGN.md +27 -64
  57. package/docs/THREAT_MODEL.md +128 -255
  58. package/package.json +1 -1
  59. package/src/bridge/bridge.ts +1 -17
  60. package/src/check/page.ts +1 -1
  61. package/src/compile/policy.ts +1 -11
  62. package/src/config/capabilities.ts +8 -14
  63. package/src/config/schema.ts +2 -13
  64. package/src/config/validate.ts +0 -28
  65. package/src/conformance/behavior.ts +50 -52
  66. package/src/conformance/clipboard.ts +56 -1
  67. package/src/displays/displays.ts +1 -3
  68. package/src/guide/limits.ts +1 -1
  69. package/src/guide/runtime.ts +1 -1
  70. package/src/host/create-host.ts +6 -52
  71. package/src/host/door.ts +1 -1
  72. package/src/host/locate.ts +2 -2
  73. package/src/host/outcome.ts +8 -21
  74. package/src/host/types.ts +6 -20
  75. package/src/index.ts +2 -4
  76. package/src/isolation/served.ts +6 -34
  77. package/src/isolation/types.ts +2 -31
  78. package/src/platform/focus-field.ts +18 -0
  79. package/src/platform/types.ts +6 -21
  80. package/src/platform/web.ts +8 -129
  81. package/src/presets/presets.ts +0 -3
  82. package/src/react/frame.tsx +0 -10
  83. package/src/runtime/contract.ts +4 -4
  84. package/src/runtime/types.generated.ts +6 -6
  85. package/src/server/files.ts +4 -19
  86. package/src/server/host.ts +1 -1
  87. package/src/server/index.ts +4 -16
  88. package/src/server/naming.ts +1 -1
  89. package/src/server/server.ts +29 -189
  90. package/src/server/types.ts +7 -7
  91. package/src/shell/plan.ts +2 -9
  92. package/src/shell/runtime.ts +1 -268
  93. package/types/runtime/v1/artifact.d.ts +2 -3
  94. package/types/runtime/v1/assets.d.ts +1 -1
  95. package/types/runtime/v1/chat.d.ts +2 -2
  96. package/types/runtime/v1/comments.d.ts +1 -1
  97. package/types/runtime/v1/downloads.d.ts +2 -2
  98. package/types/runtime/v1/links.d.ts +2 -2
  99. package/dist/platform/focus-guard.d.ts +0 -288
  100. package/dist/platform/focus-guard.js +0 -838
  101. package/dist/server/nested.d.ts +0 -66
  102. package/dist/server/nested.js +0 -121
  103. package/dist/shell/frame.d.ts +0 -28
  104. package/dist/shell/frame.js +0 -407
  105. package/src/platform/focus-guard.ts +0 -1114
  106. package/src/server/nested.ts +0 -157
  107. package/src/shell/frame.ts +0 -444
@@ -1,66 +0,0 @@
1
- import type { CompiledConfig } from "../compile/compile.ts";
2
- import { type CspDirective } from "../compile/policy.ts";
3
- import { type FrameShellOptions } from "../shell/frame.ts";
4
- export { isNestedLabel, PORTHOLE_LABEL_PREFIX } from "../isolation/served.ts";
5
- /**
6
- * A nested page's serving (P111): what the address the host frames answers (Porthole's shell,
7
- * `nestedShellResponse`), and what changes on the page and its files below the sealed prefix
8
- * (`nestedAncestors`, `NESTED_FILE_HEADERS`). `/server` serves both for a config with `nested`;
9
- * a host serving its own content origin (its own Worker) answers the same.
10
- *
11
- * All of it is served on the shell's own label (P114, `nestedLabelOf`), never on the scope's: every
12
- * other display of the scope runs agent-made content on the scope's origin with
13
- * `allow-same-origin`, which would be same-origin with the shell, its realm and the page's sealed
14
- * address.
15
- */
16
- /**
17
- * The label a nested page's shell is served on (P114), for its scope's label: `porthole-` and 24
18
- * base32 characters of the label's SHA-256, one per scope, the same for every nested page of it. No
19
- * content label is ever one (a keyed label has no hyphen, a host's is refused the prefix), so
20
- * nothing but a nested page's shell, its opaque page, that page's files and Porthole's status pages
21
- * is ever served on it: no other display's content runs there with `allow-same-origin`. Not a
22
- * secret: anyone who knows the scope's label may work it out. A content Worker of a host's own
23
- * serves its nested pages on it too.
24
- */
25
- export declare function nestedLabelOf(label: string): string;
26
- /** Where every page and file of a nested page is, on its origin: its sealed files' prefix. */
27
- export declare const NESTED_FILES_PREFIX = "/__porthole/f/";
28
- /**
29
- * The shell's CSP (a header): its own script alone runs (by its hash), it frames and fetches
30
- * nothing but its origin's sealed files (the page, the renewal), and only the host origins frame
31
- * it (with, above them, a host's `framedBy`, P141). Nothing of the page's runs here: the page is a
32
- * document of its own, which inherits none of this (a framed URL's document never does).
33
- */
34
- export declare function nestedShellCsp(script: string, origin: string, hostOrigins: readonly string[], framedBy?: readonly string[]): string;
35
- /**
36
- * The answer at the address the host frames, for a nested page (P111): Porthole's shell, never
37
- * stored (it carries the page's sealed address), its page at `options.page`.
38
- */
39
- export declare function nestedShellResponse(compiled: CompiledConfig, options: FrameShellOptions & {
40
- readonly origin: string;
41
- readonly method?: string;
42
- }): Response;
43
- /**
44
- * Who may frame a nested page and its files' answers: its shell (the shell's own origin, P114) and,
45
- * above it, the host origins and a host's `framedBy` (`frame-ancestors` names every ancestor; P141):
46
- * `frameAncestors` is the server's whole list.
47
- */
48
- export declare const nestedAncestors: (origin: string, frameAncestors: string) => string;
49
- /**
50
- * A nested page's answer's CSP below its sealed prefix, by what it is (P111; the one source for
51
- * `/server` and a content Worker of a host's own, P121): a page its directives and
52
- * `sandbox allow-scripts`, so it is an opaque origin in the shell's child and on a tab of its own
53
- * (never `allow-same-origin`, which would give it the shell's origin and realm); a script its
54
- * directives and `sandbox` (a worker's policy is its script's; opened on its own it runs nothing on
55
- * the shell's origin); any other file nothing at all. `directives` are the page's: the compiled
56
- * config's, its files' prefix opened (`fileSetCspDirectives(compiled.cspDirectives, source)`) for
57
- * a page of a file set. Then who may frame it: `frame-ancestors` (`nestedAncestors`).
58
- */
59
- export declare function nestedFileCsp(role: "page" | "script" | "file", directives: readonly CspDirective[]): string;
60
- /**
61
- * What a nested page's files (not its pages) carry beyond a served file's (P111): its page's
62
- * origin is opaque, so a same-origin resource policy would refuse its own images and scripts, and
63
- * its fetches, modules and fonts are CORS requests from `null`. The sealed address in their path
64
- * is their access, never the request's origin.
65
- */
66
- export declare const NESTED_FILE_HEADERS: Readonly<Record<string, string>>;
@@ -1,121 +0,0 @@
1
- import { INERT_FILE_CSP, PAGE_SANDBOX_TOKENS, servedPermissionsPolicy, serializeCsp, } from "../compile/policy.js";
2
- import { frameShellDocument, frameShellScript } from "../shell/frame.js";
3
- import { onNestedLabel, PORTHOLE_LABEL_PREFIX } from "../isolation/served.js";
4
- import { sha256, utf8 } from "./crypto.js";
5
- import { ancestorsOf, checkHostOrigins } from "./pages.js";
6
- import { base32 } from "./keys.js";
7
- export { isNestedLabel, PORTHOLE_LABEL_PREFIX } from "../isolation/served.js";
8
- /**
9
- * A nested page's serving (P111): what the address the host frames answers (Porthole's shell,
10
- * `nestedShellResponse`), and what changes on the page and its files below the sealed prefix
11
- * (`nestedAncestors`, `NESTED_FILE_HEADERS`). `/server` serves both for a config with `nested`;
12
- * a host serving its own content origin (its own Worker) answers the same.
13
- *
14
- * All of it is served on the shell's own label (P114, `nestedLabelOf`), never on the scope's: every
15
- * other display of the scope runs agent-made content on the scope's origin with
16
- * `allow-same-origin`, which would be same-origin with the shell, its realm and the page's sealed
17
- * address.
18
- */
19
- /**
20
- * The label a nested page's shell is served on (P114), for its scope's label: `porthole-` and 24
21
- * base32 characters of the label's SHA-256, one per scope, the same for every nested page of it. No
22
- * content label is ever one (a keyed label has no hyphen, a host's is refused the prefix), so
23
- * nothing but a nested page's shell, its opaque page, that page's files and Porthole's status pages
24
- * is ever served on it: no other display's content runs there with `allow-same-origin`. Not a
25
- * secret: anyone who knows the scope's label may work it out. A content Worker of a host's own
26
- * serves its nested pages on it too.
27
- */
28
- export function nestedLabelOf(label) {
29
- return `${PORTHOLE_LABEL_PREFIX}${base32(sha256(utf8(`porthole/nested/${label}`)).subarray(0, 15))}`;
30
- }
31
- /** Where every page and file of a nested page is, on its origin: its sealed files' prefix. */
32
- export const NESTED_FILES_PREFIX = "/__porthole/f/";
33
- const base64 = (bytes) => btoa(String.fromCharCode(...bytes));
34
- /**
35
- * The shell's CSP (a header): its own script alone runs (by its hash), it frames and fetches
36
- * nothing but its origin's sealed files (the page, the renewal), and only the host origins frame
37
- * it (with, above them, a host's `framedBy`, P141). Nothing of the page's runs here: the page is a
38
- * document of its own, which inherits none of this (a framed URL's document never does).
39
- */
40
- export function nestedShellCsp(script, origin, hostOrigins, framedBy = []) {
41
- checkHostOrigins("nestedShellCsp", hostOrigins);
42
- const files = `${origin}${NESTED_FILES_PREFIX}`;
43
- const directives = [
44
- ["default-src", "'none'"],
45
- ["script-src", `'sha256-${base64(sha256(utf8(script)))}'`],
46
- ["frame-src", files],
47
- ["connect-src", files],
48
- ["base-uri", "'none'"],
49
- ["form-action", "'none'"],
50
- ["frame-ancestors", ...ancestorsOf(hostOrigins, framedBy).split(" ")],
51
- ];
52
- return serializeCsp(directives);
53
- }
54
- /**
55
- * The answer at the address the host frames, for a nested page (P111): Porthole's shell, never
56
- * stored (it carries the page's sealed address), its page at `options.page`.
57
- */
58
- export function nestedShellResponse(compiled, options) {
59
- // On the shell's own label alone (P114), its page on that origin (P121): a content Worker of a
60
- // host's own that would serve it beside other content is refused here, not left to its routes.
61
- if (!onNestedLabel(options.origin)) {
62
- throw new TypeError(`nestedShellResponse: origin ${options.origin} isn't on a nested page's own label (${PORTHOLE_LABEL_PREFIX}<24 base32>, nestedLabelOf)`);
63
- }
64
- if (new URL(options.page).origin !== options.origin) {
65
- throw new TypeError("nestedShellResponse: page is on the shell's own origin");
66
- }
67
- const script = frameShellScript(options);
68
- const headers = new Headers({
69
- "content-type": "text/html; charset=utf-8",
70
- "content-security-policy": nestedShellCsp(script, options.origin, options.origins, options.framedBy),
71
- "cache-control": "no-store",
72
- "referrer-policy": "no-referrer",
73
- "x-content-type-options": "nosniff",
74
- "x-robots-tag": "noindex, nofollow",
75
- });
76
- // Denied to the shell, so to its child too (a frame's features are its parent's at most).
77
- const permissions = servedPermissionsPolicy(compiled.config);
78
- if (permissions !== null) {
79
- headers.set("permissions-policy", permissions);
80
- }
81
- return new Response(options.method === "HEAD" ? null : frameShellDocument(script), {
82
- status: 200,
83
- headers,
84
- });
85
- }
86
- /**
87
- * Who may frame a nested page and its files' answers: its shell (the shell's own origin, P114) and,
88
- * above it, the host origins and a host's `framedBy` (`frame-ancestors` names every ancestor; P141):
89
- * `frameAncestors` is the server's whole list.
90
- */
91
- export const nestedAncestors = (origin, frameAncestors) => `${origin} ${frameAncestors}`;
92
- /**
93
- * A nested page's answer's CSP below its sealed prefix, by what it is (P111; the one source for
94
- * `/server` and a content Worker of a host's own, P121): a page its directives and
95
- * `sandbox allow-scripts`, so it is an opaque origin in the shell's child and on a tab of its own
96
- * (never `allow-same-origin`, which would give it the shell's origin and realm); a script its
97
- * directives and `sandbox` (a worker's policy is its script's; opened on its own it runs nothing on
98
- * the shell's origin); any other file nothing at all. `directives` are the page's: the compiled
99
- * config's, its files' prefix opened (`fileSetCspDirectives(compiled.cspDirectives, source)`) for
100
- * a page of a file set. Then who may frame it: `frame-ancestors` (`nestedAncestors`).
101
- */
102
- export function nestedFileCsp(role, directives) {
103
- switch (role) {
104
- case "page":
105
- return serializeCsp([...directives, ["sandbox", ...PAGE_SANDBOX_TOKENS]]);
106
- case "script":
107
- return serializeCsp([...directives, ["sandbox"]]);
108
- case "file":
109
- return INERT_FILE_CSP;
110
- }
111
- }
112
- /**
113
- * What a nested page's files (not its pages) carry beyond a served file's (P111): its page's
114
- * origin is opaque, so a same-origin resource policy would refuse its own images and scripts, and
115
- * its fetches, modules and fonts are CORS requests from `null`. The sealed address in their path
116
- * is their access, never the request's origin.
117
- */
118
- export const NESTED_FILE_HEADERS = {
119
- "cross-origin-resource-policy": "cross-origin",
120
- "access-control-allow-origin": "*",
121
- };
@@ -1,28 +0,0 @@
1
- /** The nested page's shell's runtime: 0.14.16's, byte for byte. */
2
- export declare const FRAME_SHELL_RUNTIME: string;
3
- /** A strict shell's runtime (P141): its parent may be an outer page. */
4
- export declare const STRICT_FRAME_SHELL_RUNTIME: string;
5
- export { SHELL_METHOD_PREFIX, SHELL_PRESS_PORT_METHOD, SHELL_STATE_METHOD, } from "../isolation/types.ts";
6
- export interface FrameShellOptions {
7
- /** The host origins: the shell takes messages from its parent only from these. */
8
- readonly origins: readonly string[];
9
- /**
10
- * Origins of an outer page that may be an ancestor above a host origin's page (P141): in the
11
- * shell's `frame-ancestors` after `origins` (`nestedShellResponse`), never heard or told. Where
12
- * there are any, the shell says `*` only to a parent the engine names as a host origin.
13
- */
14
- readonly framedBy?: readonly string[];
15
- /** The page's address: absolute, on the shell's own origin, under `/__porthole/f/`. */
16
- readonly page: string;
17
- /** The page frame's accessible name. */
18
- readonly title?: string;
19
- /** Where the page's sealed address is renewed (`<base>__porthole/renew`), and when it ends. */
20
- readonly renew?: {
21
- readonly url: string;
22
- readonly expires: number;
23
- };
24
- }
25
- /** The shell's script for `options`: what its document runs, and what its CSP's hash names. */
26
- export declare function frameShellScript(options: FrameShellOptions): string;
27
- /** The shell's document around its script: nothing else (its CSP allows that script alone). */
28
- export declare function frameShellDocument(script: string): string;
@@ -1,407 +0,0 @@
1
- import { PAGE_SANDBOX_TOKENS } from "../compile/policy.js";
2
- import { framedByProblem, hostOriginProblem, includesOrigin, onNestedLabel, } from "../isolation/served.js";
3
- /**
4
- * Porthole's shell for a nested page (P111): the whole document at the address the host frames,
5
- * with no content in it. It frames the page (the same origin's sealed files' address) in a child
6
- * sandboxed without `allow-same-origin`, so the page's origin is opaque and nothing of the shell's
7
- * realm is reachable from it: not its DOM, its globals, its storage, or the window the host hears.
8
- *
9
- * The shell:
10
- * - passes every message between the host (its parent, from the host origins) and the page (its
11
- * child's window, by `event.source` alone: the page's origin is "null") unchanged, and drops any
12
- * the page sends in the shell's own namespace (`porthole/shell/`), so the shell's words to the
13
- * host are only its own;
14
- * - tells the host its own state (`porthole/shell/state`): whether its transient activation is on,
15
- * and since when, and whether the page's focus is in it. A gesture in the page activates the
16
- * page and its ancestors, the shell among them, and nothing on the host's page activates the
17
- * shell (activation goes up, never down), so the shell's activation turning on is a press or
18
- * key of the person's in this page. It is read at every animation frame, on its window's focus
19
- * and blur, and before each message of the page's is passed on (a call made in a click's handler
20
- * arrives after the state that says so), and at once when the host asks (`porthole/shell/look`,
21
- * P120: the host heard focus move into the frame, and a key the person types into the page
22
- * before the shell's next frame would turn its activation on as a press does). What it can't
23
- * see: a gesture while its activation is already on (within 5 s of the last one) turns nothing
24
- * on;
25
- * - hears each real press in the page from the page's runtime (P148), over a `MessagePort` it makes
26
- * at each load of the page's frame and sends down (`porthole/shell/press-port`): the runtime
27
- * takes it before any content runs, and no content holds it. A message on it says only that
28
- * there was a press; the shell notes when it heard it, on its own clock, tells the host in its
29
- * state (how long ago, and how many it has heard), and then answers on the port, so what the
30
- * page says next arrives after the state that says so. Only the port of the frame's last load is
31
- * heard, and what was said of a press before it is forgotten; the port before is heard again
32
- * only if the runtime that holds it says, on it, that its document is still there (WebKit fires
33
- * a load for a navigation within the document, P142);
34
- * - renews the page's sealed files' address before it ends, and gives the page the new one
35
- * (`porthole/files-renewed`): the page's own loads aren't its origin's (an opaque origin's never
36
- * are), so only the shell, on that origin, may renew it (P083);
37
- * - passes its focus to the page: at the focus event where that takes (Firefox, from the host's
38
- * `<body>`), and on the host's word that it moved it there (`porthole/shell/focus`, P136), where
39
- * it doesn't: a frame's move inside the focus event that made it the focused frame sets the
40
- * shell's `activeElement` and goes no further (Chromium, WebKit), and from a focused element of
41
- * the host's the window hears no focus event at all (Firefox). A later task's `frame.focus()`
42
- * goes through on all of them, the frame blurred first as the failed one left it active.
43
- *
44
- * Plain ES2020, no imports and no build step, like the runtime. `__PLAN__` is its plan. A shell
45
- * whose parent may be an outer page (a host's `framedBy`, P141) runs the strict runtime, which
46
- * checks that parent before it says `*`; every other shell runs 0.14.16's, byte for byte, so its
47
- * hash is too (P144).
48
- */
49
- const frameShellRuntime = (strict) => String.raw `(() => {
50
- "use strict";
51
- const plan = __PLAN__;
52
- const PREFIX = "porthole/shell/";
53
- const own = location.origin;
54
- // A nested page's shell runs on a label of its own alone (P114, P121): on any other origin (its
55
- // scope's, where other displays run content with allow-same-origin) it frames nothing and says
56
- // nothing.
57
- if (!/^porthole-[a-z2-7]{24}\./.test(location.hostname + ".")) {
58
- return;
59
- }
60
- let page = null;
61
- try {
62
- page = new URL(plan.page);
63
- } catch (_) {}
64
- // Only a page of this origin's sealed files: nothing else is ever framed here.
65
- if (page === null || page.origin !== own || page.pathname.indexOf("/__porthole/f/") !== 0) {
66
- return;
67
- }
68
- // Belt and braces: a plan that would give the page this origin frames nothing.
69
- if (typeof plan.sandbox !== "string" || /allow-same-origin/i.test(plan.sandbox)) {
70
- return;
71
- }
72
- const root = document.documentElement;
73
- root.style.height = "100%";
74
- document.body.style.margin = "0";
75
- document.body.style.height = "100%";
76
- document.body.style.background = "transparent";
77
- const frame = document.createElement("iframe");
78
- // Scripts only: never allow-same-origin (the page would have this origin, and so this realm).
79
- frame.setAttribute("sandbox", plan.sandbox);
80
- frame.setAttribute("allow", "clipboard-read 'none'; clipboard-write 'none'");
81
- frame.setAttribute("referrerpolicy", "no-referrer");
82
- frame.title = typeof plan.title === "string" ? plan.title : "Content";
83
- frame.style.display = "block";
84
- frame.style.border = "0";
85
- frame.style.width = "100%";
86
- frame.style.height = "100%";
87
- frame.style.background = "transparent";
88
- // The page's real presses (P148): when the last one was heard (null: none since the frame's last
89
- // load), how many were heard in all, and the one port listened to.
90
- let pressedAt = null;
91
- let presses = 0;
92
- let pressPort = null;
93
- // The port a load set aside, until the next one: its document may still be there (below).
94
- let asidePort = null;
95
- const shut = (port) => {
96
- if (port !== null) {
97
- port.onmessage = null;
98
- port.close();
99
- }
100
- };
101
- const hear = (port) => {
102
- port.onmessage = (event) => {
103
- if (pressPort !== port || event.data !== 0) {
104
- return;
105
- }
106
- pressedAt = performance.now();
107
- presses += 1;
108
- // To the host first, then the answer: what the page held back follows the state.
109
- look(undefined, true);
110
- port.postMessage(0);
111
- };
112
- };
113
- frame.addEventListener("load", () => {
114
- shut(asidePort);
115
- const before = pressPort;
116
- asidePort = before;
117
- pressedAt = null;
118
- const child = frame.contentWindow;
119
- if (child === null || typeof MessageChannel !== "function") {
120
- shut(before);
121
- asidePort = null;
122
- pressPort = null;
123
- return;
124
- }
125
- const channel = new MessageChannel();
126
- const port = channel.port1;
127
- pressPort = port;
128
- hear(port);
129
- if (before !== null) {
130
- // A load is a new document, whose runtime takes this port, and the one before is heard no
131
- // more. But not every load is one: WebKit fires it for a navigation within the document
132
- // (P142), whose runtime is still there and takes no second port. It says so (1) on the port
133
- // it holds, which no one else can: that port is then the one again, and the new one is shut.
134
- before.onmessage = (event) => {
135
- if (event.data === 1 && pressPort === port && asidePort === before) {
136
- shut(port);
137
- asidePort = null;
138
- pressPort = before;
139
- hear(before);
140
- }
141
- };
142
- }
143
- child.postMessage({ jsonrpc: "2.0", method: PREFIX + "press-port" }, "*", [channel.port2]);
144
- });
145
- frame.src = page.href;
146
- document.body.append(frame);
147
-
148
- const framed = window.parent !== window;
149
- const web = plan.origins.filter((origin) => origin.indexOf("https://") === 0 || origin.indexOf("http://") === 0);
150
- // To the host: each web host origin (only the parent's is delivered); a desktop app's own scheme
151
- // is no target a browser takes, so where one is listed and the parent isn't a known web origin,
152
- // "*" (frame-ancestors holds the parent to the host origins; nothing said here is secret).${strict ? STRICT_NOTE : ""}
153
- const toHost = (message) => {
154
- if (!framed) {
155
- return;
156
- }
157
- for (const origin of web) {
158
- try {
159
- window.parent.postMessage(message, origin);
160
- } catch (_) {}
161
- }
162
- const parent = location.ancestorOrigins && location.ancestorOrigins.length > 0 ? location.ancestorOrigins[0] : null;
163
- if (${strict ? STRICT_CONDITION : "web.length < plan.origins.length && (parent === null || web.indexOf(parent) === -1)"}) {
164
- try {
165
- window.parent.postMessage(message, "*");
166
- } catch (_) {}
167
- }
168
- };
169
-
170
- // The shell's own state: its transient activation (and when it turned on), the page's focus.
171
- // "since" is when the shell saw activation turn on, which a page that holds the thread the shell
172
- // shares with it (WebKit, Firefox) can push later than the press: so the shell looks every 50 ms
173
- // and beats as often, and each report says how long it went without a look before (gap). The
174
- // host takes an activation the shell saw after a stall for uncertain (P111, after its review).
175
- const activation = navigator.userActivation;
176
- let active = false;
177
- let since = 0;
178
- let focused = false;
179
- let lookedAt = performance.now();
180
- let toldAt = 0;
181
- const tell = (gap, asked) => {
182
- toldAt = performance.now();
183
- const params = {
184
- supported: activation !== undefined,
185
- active,
186
- ago: active ? Math.max(0, Math.round(performance.now() - since)) : null,
187
- focused,
188
- gap: Math.max(0, Math.round(gap)),
189
- // The page's last real press (P148): how long ago the shell heard it, and how many so far.
190
- pressed: pressedAt === null ? null : Math.max(0, Math.round(performance.now() - pressedAt)),
191
- presses,
192
- };
193
- // The answer to the host's ask (P120), by its number.
194
- if (asked !== undefined) {
195
- params.asked = asked;
196
- }
197
- toHost({ jsonrpc: "2.0", method: PREFIX + "state", params });
198
- };
199
- const look = (asked, pressed) => {
200
- const now = performance.now();
201
- const gap = now - lookedAt;
202
- lookedAt = now;
203
- const on = activation !== undefined && activation.isActive === true;
204
- const inside = document.hasFocus();
205
- let changed = false;
206
- if (on !== active) {
207
- active = on;
208
- if (on) {
209
- since = performance.now();
210
- }
211
- changed = true;
212
- }
213
- if (inside !== focused) {
214
- focused = inside;
215
- changed = true;
216
- }
217
- if (changed || pressed === true || typeof asked === "number") {
218
- tell(gap, typeof asked === "number" ? asked : undefined);
219
- } else if (now - toldAt >= 50) {
220
- // The heartbeat: the host knows the shell was looking, every 50 ms.
221
- toldAt = now;
222
- toHost({ jsonrpc: "2.0", method: PREFIX + "beat", params: { gap: Math.max(0, Math.round(gap)) } });
223
- }
224
- };
225
- const tick = () => {
226
- look();
227
- requestAnimationFrame(tick);
228
- };
229
- requestAnimationFrame(tick);
230
- setInterval(look, 50);
231
-
232
- // Whether the focus is on the shell's own document, not through it on the page's (P136). Firefox
233
- // tells a move from a focused element of the host's on the document alone. The host's word needs
234
- // this: it never moves a focus that isn't here, and a page that has it hears no blur.
235
- let holds = false;
236
- // Until when a word that came ahead of the focus it speaks of holds (it crosses processes too).
237
- let wordUntil = 0;
238
- const handOn = () => {
239
- if (holds && document.hasFocus()) {
240
- frame.blur();
241
- frame.focus();
242
- }
243
- };
244
- const came = () => {
245
- holds = true;
246
- if (performance.now() < wordUntil) {
247
- wordUntil = 0;
248
- setTimeout(handOn, 0);
249
- }
250
- };
251
- document.addEventListener("focus", came);
252
- addEventListener("blur", () => {
253
- holds = false;
254
- look();
255
- });
256
- addEventListener("focus", (event) => {
257
- if (event.target === window) {
258
- came();
259
- // Where a move can go on from inside this event (P136): Firefox, from the host's <body>.
260
- if (document.activeElement !== frame) {
261
- frame.focus();
262
- }
263
- }
264
- look();
265
- });
266
- document.addEventListener("visibilitychange", look);
267
- tell(0);
268
-
269
- addEventListener("message", (event) => {
270
- const source = event.source;
271
- if (source !== null && source === frame.contentWindow) {
272
- const data = event.data;
273
- // Never the shell's words in the page's mouth.
274
- if (data !== null && typeof data === "object" && typeof data.method === "string" && data.method.indexOf(PREFIX) === 0) {
275
- return;
276
- }
277
- // What the shell knows now goes first: a call in a click's handler follows its activation.
278
- look();
279
- toHost(data);
280
- return;
281
- }
282
- if (framed && source === window.parent && plan.origins.indexOf(event.origin) !== -1) {
283
- const data = event.data;
284
- // The host's words to the shell are never the page's to hear (P120): its ask to look now.
285
- if (data !== null && typeof data === "object" && typeof data.method === "string" && data.method.indexOf(PREFIX) === 0) {
286
- const n = data.params !== null && typeof data.params === "object" ? data.params.n : undefined;
287
- if (data.method === PREFIX + "look" && typeof n === "number" && n >= 0 && Math.floor(n) === n) {
288
- look(n);
289
- }
290
- // The host's own move into the frame, done (P136): on to the page.
291
- if (data.method === PREFIX + "focus") {
292
- if (holds) {
293
- handOn();
294
- } else {
295
- wordUntil = performance.now() + 250;
296
- }
297
- }
298
- return;
299
- }
300
- const child = frame.contentWindow;
301
- if (child !== null) {
302
- child.postMessage(event.data, "*");
303
- }
304
- }
305
- });
306
-
307
- // The page's sealed address, renewed before it ends (P083): the page can't, the shell can.
308
- if (plan.renew && typeof plan.renew.url === "string" && typeof plan.renew.expires === "number") {
309
- const prefix = own + "/__porthole/f/";
310
- let renewUrl = plan.renew.url;
311
- const renewIn = (expires) => Math.max(30000, expires - Date.now() - 300000);
312
- const renew = () => {
313
- fetch(renewUrl, { credentials: "omit", cache: "no-store" })
314
- .then((answer) => (answer.ok ? answer.json() : null))
315
- .then((renewed) => {
316
- if (!renewed || typeof renewed.base !== "string" || typeof renewed.expires !== "number" || renewed.base.indexOf(prefix) !== 0) {
317
- setTimeout(renew, 60000);
318
- return;
319
- }
320
- renewUrl = renewed.base + "__porthole/renew";
321
- const child = frame.contentWindow;
322
- if (child !== null) {
323
- child.postMessage({ jsonrpc: "2.0", method: "porthole/files-renewed", params: { base: renewed.base } }, "*");
324
- }
325
- setTimeout(renew, renewIn(renewed.expires));
326
- })
327
- .catch(() => setTimeout(renew, 60000));
328
- };
329
- setTimeout(renew, renewIn(plan.renew.expires));
330
- }
331
- })();`;
332
- /** What a strict shell says of its `*` (P141), after the default's note. */
333
- const STRICT_NOTE = ` Where
334
- // it names an outer page above them too (the host's framedBy, P141: plan.strictParent), the parent
335
- // may be the outer page: "*" then goes only to a parent the engine names as a host origin.`;
336
- /** When a strict shell says `*` (P141): as 0.14.16's, and only to a parent named as a host origin. */
337
- const STRICT_CONDITION = `
338
- web.length < plan.origins.length &&
339
- (parent === null || web.indexOf(parent) === -1) &&
340
- (plan.strictParent !== true || (parent !== null && plan.origins.indexOf(parent) !== -1))
341
- `;
342
- /** The nested page's shell's runtime: 0.14.16's, byte for byte. */
343
- export const FRAME_SHELL_RUNTIME = frameShellRuntime(false);
344
- /** A strict shell's runtime (P141): its parent may be an outer page. */
345
- export const STRICT_FRAME_SHELL_RUNTIME = frameShellRuntime(true);
346
- export { SHELL_METHOD_PREFIX, SHELL_PRESS_PORT_METHOD, SHELL_STATE_METHOD, } from "../isolation/types.js";
347
- /** JSON that is safe inside a `<script>`. */
348
- const scriptJson = (value) => JSON.stringify(value)
349
- .replace(/</gu, "\\u003c")
350
- .replace(/\u2028/gu, "\\u2028")
351
- .replace(/\u2029/gu, "\\u2029");
352
- /** The shell's script for `options`: what its document runs, and what its CSP's hash names. */
353
- export function frameShellScript(options) {
354
- for (const origin of options.origins) {
355
- const problem = hostOriginProblem(origin);
356
- if (problem !== null) {
357
- throw new TypeError(`frameShellScript: ${problem}`);
358
- }
359
- }
360
- for (const origin of options.framedBy ?? []) {
361
- const problem = framedByProblem(origin);
362
- if (problem !== null || includesOrigin(options.origins, origin)) {
363
- throw new TypeError(`frameShellScript: framedBy: ${problem ?? `${origin} is a host origin`}`);
364
- }
365
- }
366
- let page;
367
- try {
368
- page = new URL(options.page);
369
- }
370
- catch {
371
- throw new TypeError("frameShellScript: page is an absolute URL");
372
- }
373
- if (!page.pathname.startsWith("/__porthole/f/") || page.hash !== "") {
374
- throw new TypeError("frameShellScript: page is under /__porthole/f/, with no fragment");
375
- }
376
- // The shell runs on a nested page's own label alone (P114), and its page is on its origin.
377
- if (!onNestedLabel(page.origin)) {
378
- throw new TypeError("frameShellScript: page is on a nested page's own label (porthole-<24 base32>, nestedLabelOf)");
379
- }
380
- const strict = (options.framedBy ?? []).length > 0;
381
- return (strict ? STRICT_FRAME_SHELL_RUNTIME : FRAME_SHELL_RUNTIME).replace("__PLAN__", () => scriptJson({
382
- origins: options.origins,
383
- ...(strict ? { strictParent: true } : {}),
384
- page: page.href,
385
- sandbox: PAGE_SANDBOX_TOKENS.join(" "),
386
- ...(options.title === undefined ? {} : { title: options.title }),
387
- ...(options.renew === undefined
388
- ? {}
389
- : { renew: { url: options.renew.url, expires: options.renew.expires } }),
390
- }));
391
- }
392
- /** The shell's document around its script: nothing else (its CSP allows that script alone). */
393
- export function frameShellDocument(script) {
394
- return `<!doctype html>
395
- <html lang="en">
396
- <head>
397
- <meta charset="utf-8">
398
- <meta name="color-scheme" content="light dark">
399
- <meta name="referrer" content="no-referrer">
400
- <title>Porthole</title>
401
- </head>
402
- <body>
403
- <script>${script}</script>
404
- </body>
405
- </html>
406
- `;
407
- }