@botiverse/porthole 0.15.2 → 0.15.3

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.
@@ -22,6 +22,11 @@ export declare const isNestedLabel: (label: string) => boolean;
22
22
  export declare function onNestedLabel(origin: string): boolean;
23
23
  /** Whether `origin` is an exact origin (`https://host[:port]`, lowercase, no path). */
24
24
  export declare function isExactOrigin(origin: unknown): origin is string;
25
+ /**
26
+ * Whether `origin` can be a host origin: written as one, and one a browser serializes as it is
27
+ * written (`serializable`: never `:0`, a port past 65535 or with a leading zero, a host the URL
28
+ * parser would rewrite). `hostOriginProblem` says why not.
29
+ */
25
30
  export declare function isHostOrigin(origin: unknown): origin is string;
26
31
  /** Why `origin` can't be a host origin, in words a host's developer can act on; null if it can. */
27
32
  export declare function hostOriginProblem(origin: unknown): string | null;
@@ -45,8 +45,15 @@ export function isExactOrigin(origin) {
45
45
  * page says "null") and never a path. The shell takes messages only from these, exactly.
46
46
  */
47
47
  const HOST_ORIGIN = /^[a-z][a-z0-9+.-]*:\/\/([a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*|\[[0-9a-f:.]+\])(:\d{1,5})?$/u;
48
+ /** Whether `origin` is written as an origin is (`HOST_ORIGIN`), whatever a browser makes of it. */
49
+ const shapedAsOrigin = (origin) => typeof origin === "string" && origin.length <= 300 && HOST_ORIGIN.test(origin);
50
+ /**
51
+ * Whether `origin` can be a host origin: written as one, and one a browser serializes as it is
52
+ * written (`serializable`: never `:0`, a port past 65535 or with a leading zero, a host the URL
53
+ * parser would rewrite). `hostOriginProblem` says why not.
54
+ */
48
55
  export function isHostOrigin(origin) {
49
- return typeof origin === "string" && origin.length <= 300 && HOST_ORIGIN.test(origin);
56
+ return shapedAsOrigin(origin) && serializable(origin);
50
57
  }
51
58
  /**
52
59
  * Whether an origin that matched `HOST_ORIGIN` is one a browser can serialize as it is written
@@ -75,7 +82,7 @@ function serializable(origin) {
75
82
  }
76
83
  /** Why `origin` can't be a host origin, in words a host's developer can act on; null if it can. */
77
84
  export function hostOriginProblem(origin) {
78
- if (isHostOrigin(origin)) {
85
+ if (shapedAsOrigin(origin)) {
79
86
  return serializable(origin)
80
87
  ? null
81
88
  : `${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)`;
@@ -118,7 +125,7 @@ const LOOPBACK_HOST = (host) => host === "localhost" || host.endsWith(".localhos
118
125
  * in plain decimal, and its host is as the URL parser gives it back (P145). Null if it can be.
119
126
  */
120
127
  export function framedByProblem(origin) {
121
- const parsed = typeof origin === "string" && isHostOrigin(origin) ? parseOrigin(origin) : null;
128
+ const parsed = shapedAsOrigin(origin) ? parseOrigin(origin) : null;
122
129
  if (parsed === null ||
123
130
  !(parsed.scheme === "https" || (parsed.scheme === "http" && LOOPBACK_HOST(parsed.host)))) {
124
131
  return `${JSON.stringify(origin)} is not an exact https origin (https://host[:port], lowercase, no path; http only on loopback)`;
@@ -109,6 +109,12 @@ export declare const SHELL_LOOK_METHOD = "porthole/shell/look";
109
109
  * `display.focus()` alone; a page has no way to say it.
110
110
  */
111
111
  export declare const SHELL_FOCUS_METHOD = "porthole/shell/focus";
112
+ /**
113
+ * A nested page's shell's word to its page's runtime (P148): one `MessagePort`, sent at each load
114
+ * of the page's frame, over which the runtime tells the shell each real press in the page. The
115
+ * runtime takes the first one alone, before any content runs, and no content ever holds it.
116
+ */
117
+ export declare const SHELL_PRESS_PORT_METHOD = "porthole/shell/press-port";
112
118
  /** The shell's own namespace (P111): the shell drops a page's message that names a method in it. */
113
119
  export declare const SHELL_METHOD_PREFIX = "porthole/shell/";
114
120
  /** A page's word that it used storage, once per load (P111): never a key or a value. */
@@ -17,6 +17,12 @@ export const SHELL_LOOK_METHOD = "porthole/shell/look";
17
17
  * `display.focus()` alone; a page has no way to say it.
18
18
  */
19
19
  export const SHELL_FOCUS_METHOD = "porthole/shell/focus";
20
+ /**
21
+ * A nested page's shell's word to its page's runtime (P148): one `MessagePort`, sent at each load
22
+ * of the page's frame, over which the runtime tells the shell each real press in the page. The
23
+ * runtime takes the first one alone, before any content runs, and no content ever holds it.
24
+ */
25
+ export const SHELL_PRESS_PORT_METHOD = "porthole/shell/press-port";
20
26
  /** The shell's own namespace (P111): the shell drops a page's message that names a method in it. */
21
27
  export const SHELL_METHOD_PREFIX = "porthole/shell/";
22
28
  /** A page's word that it used storage, once per load (P111): never a key or a value. */
@@ -106,6 +106,14 @@ export declare const SHELL_EARLY_MS = 150;
106
106
  * uncertain: it is no one's gesture until it lapses.
107
107
  */
108
108
  export declare const SHELL_STALL_MS = 100;
109
+ /**
110
+ * A press a nested page's runtime told its shell (P148) within this long after the shell was seen
111
+ * to have stalled is no one's. The shell notes a press when it hears it, and a page that holds the
112
+ * thread it shares with its shell makes that late, by as long as it likes: when the page lets go,
113
+ * what waited behind it runs at once, the shell's own look among it, which may come first and say
114
+ * the stall, the press following a moment later as if it were new.
115
+ */
116
+ export declare const SHELL_AFTER_STALL_MS = 500;
109
117
  /** What a nested page's shell last said (P111), on the host's clock. */
110
118
  export interface ShellWord {
111
119
  /** Whether its engine tells activation at all (`navigator.userActivation`). */
@@ -123,6 +131,15 @@ export interface ShellWord {
123
131
  * host's page sees the pointer, their key landing in the page, no press (P120).
124
132
  */
125
133
  readonly keyed?: boolean;
134
+ /**
135
+ * When it last heard a real press from its page's runtime (P148); -Infinity, or absent, if it
136
+ * heard none, or the one it heard is uncertain (judged as an activation that turned on is).
137
+ */
138
+ readonly pressedAt?: number;
139
+ /** How many presses it said it had heard, the last time it spoke: more is a new one. */
140
+ readonly presses?: number;
141
+ /** `keyed`, for the press at `pressedAt`: judged as the shell told it. */
142
+ readonly pressKeyed?: boolean;
126
143
  }
127
144
  /** One move of the keyboard the guard undid. */
128
145
  export interface FocusTake {
@@ -194,6 +211,19 @@ export declare function personMoved(move: FocusMove): boolean;
194
211
  * within `SHELL_GESTURE_MS`, after the host's page's last trusted press or key.
195
212
  */
196
213
  export declare function shellGesture(word: ShellWord, hostInputAt: number, now: number): boolean;
214
+ /**
215
+ * Whether a nested page's runtime told its shell a real press just now (P148): the shell heard it
216
+ * within `SHELL_GESTURE_MS`, after the host's page's last trusted press or key. What the shell's
217
+ * activation can't say: a press while it is already on (within 5 s of the last gesture).
218
+ */
219
+ export declare function shellPress(word: ShellWord, hostInputAt: number, now: number): boolean;
220
+ /**
221
+ * Whether a nested page's shell saw the person's gesture just now, either way: its activation
222
+ * turned on (`shellGesture`, P111), or its page's runtime told it a press (`shellPress`, P148);
223
+ * each only where a press could have made it (P120: `shown`, the host's page sees the pointer over
224
+ * its frames, and the word is `keyed`, the person's key landing in the page).
225
+ */
226
+ export declare function shellSaw(word: ShellWord, hostInputAt: number, now: number, shown: boolean): boolean;
197
227
  /**
198
228
  * Whether the person could have pressed the frame just before `at` (P120): a nested page's shell
199
229
  * says its activation turned on, which a key typed into the page does as well as a press. Where the
@@ -225,6 +255,12 @@ export interface FocusGuard {
225
255
  readonly gap: number;
226
256
  /** The ask this report answers (P120), if it answers one. */
227
257
  readonly asked?: number;
258
+ /**
259
+ * Its page's runtime's real presses (P148): how long ago the shell heard the last (null:
260
+ * none since the frame's last load), and how many it has heard. Absent from an older shell.
261
+ */
262
+ readonly pressed?: number | null;
263
+ readonly presses?: number;
228
264
  }): void;
229
265
  /** A nested page's shell's heartbeat (P111): it is looking. */
230
266
  beat(frame: HTMLIFrameElement): void;
@@ -100,6 +100,14 @@ export const SHELL_EARLY_MS = 150;
100
100
  * uncertain: it is no one's gesture until it lapses.
101
101
  */
102
102
  export const SHELL_STALL_MS = 100;
103
+ /**
104
+ * A press a nested page's runtime told its shell (P148) within this long after the shell was seen
105
+ * to have stalled is no one's. The shell notes a press when it hears it, and a page that holds the
106
+ * thread it shares with its shell makes that late, by as long as it likes: when the page lets go,
107
+ * what waited behind it runs at once, the shell's own look among it, which may come first and say
108
+ * the stall, the press following a moment later as if it were new.
109
+ */
110
+ export const SHELL_AFTER_STALL_MS = 500;
103
111
  /**
104
112
  * Whether the person moved focus into the frame themselves:
105
113
  * - the host did (`DisplayHandle.focus()`);
@@ -132,8 +140,7 @@ export function personMoved(move) {
132
140
  if (move.shell !== undefined && move.shell.word.supported) {
133
141
  return ((move.seen && move.pressed) ||
134
142
  (move.now - move.typedAt >= KEY_PRESS_MS &&
135
- shellGesture(move.shell.word, move.shell.hostInputAt, move.now) &&
136
- !(move.shell.pointerShown === true && move.shell.word.keyed === true)));
143
+ shellSaw(move.shell.word, move.shell.hostInputAt, move.now, move.shell.pointerShown === true)));
137
144
  }
138
145
  if (move.seen ? move.pressed : move.over && move.overSince > Math.max(move.typedAt, move.focusedAt)) {
139
146
  return true;
@@ -151,6 +158,28 @@ export function shellGesture(word, hostInputAt, now) {
151
158
  now >= word.activatedAt &&
152
159
  hostInputAt < word.activatedAt);
153
160
  }
161
+ /**
162
+ * Whether a nested page's runtime told its shell a real press just now (P148): the shell heard it
163
+ * within `SHELL_GESTURE_MS`, after the host's page's last trusted press or key. What the shell's
164
+ * activation can't say: a press while it is already on (within 5 s of the last gesture).
165
+ */
166
+ export function shellPress(word, hostInputAt, now) {
167
+ const pressedAt = word.pressedAt ?? -Infinity;
168
+ return (word.supported &&
169
+ now - pressedAt <= SHELL_GESTURE_MS &&
170
+ now >= pressedAt &&
171
+ hostInputAt < pressedAt);
172
+ }
173
+ /**
174
+ * Whether a nested page's shell saw the person's gesture just now, either way: its activation
175
+ * turned on (`shellGesture`, P111), or its page's runtime told it a press (`shellPress`, P148);
176
+ * each only where a press could have made it (P120: `shown`, the host's page sees the pointer over
177
+ * its frames, and the word is `keyed`, the person's key landing in the page).
178
+ */
179
+ export function shellSaw(word, hostInputAt, now, shown) {
180
+ return ((shellGesture(word, hostInputAt, now) && !(shown && word.keyed === true)) ||
181
+ (shellPress(word, hostInputAt, now) && !(shown && word.pressKeyed === true)));
182
+ }
154
183
  /**
155
184
  * Whether the person could have pressed the frame just before `at` (P120): a nested page's shell
156
185
  * says its activation turned on, which a key typed into the page does as well as a press. Where the
@@ -349,7 +378,7 @@ export function focusGuard(view) {
349
378
  // The shell's activation, where a press could have made it: within a second of the person's
350
379
  // typing on the host's page with the pointer elsewhere, it is their keys landing in the page
351
380
  // (P120). Read as of the move.
352
- const theirs = word !== null && shellGesture(word, inputAt, at) && !(pointerShown && word.keyed === true);
381
+ const theirs = word !== null && shellSaw(word, inputAt, at, pointerShown);
353
382
  // It said focus came in around the move, or answered the ask the move made with focus in it.
354
383
  const spoke = word !== null &&
355
384
  (word.focusedAt >= held.since - SHELL_EARLY_MS || (guarded.answered && word.focused));
@@ -625,6 +654,7 @@ export function focusGuard(view) {
625
654
  taken: new Set(),
626
655
  overSince: -Infinity,
627
656
  heardAt: -Infinity,
657
+ stalledAt: -Infinity,
628
658
  ask: options?.nested === true ? options.ask : undefined,
629
659
  asked: 0,
630
660
  answered: false,
@@ -664,6 +694,9 @@ export function focusGuard(view) {
664
694
  // before it (P122): that key's successor, landing in the page.
665
695
  const turnedOn = said.ago !== null && before.activatedAt === -Infinity && !before.uncertain;
666
696
  const stalled = said.gap > SHELL_STALL_MS || at - guarded.heardAt > SHELL_STALL_MS;
697
+ if (stalled) {
698
+ guarded.stalledAt = at;
699
+ }
667
700
  const fought = contest !== null && contest.fight && contest.frame === frame;
668
701
  // The typing before it, never after: a key the person typed on the host's page after they
669
702
  // pressed the page, before the shell's word came, says nothing of that press (P122, after
@@ -686,6 +719,32 @@ export function focusGuard(view) {
686
719
  : turnedOn
687
720
  ? !pressPossible(true, frame.matches(":hover"), guarded.overSince, typing, turnedAt)
688
721
  : before.keyed === true;
722
+ // A press its page's runtime told it (P148), new when it has heard more than it had: judged
723
+ // as an activation that turned on is. Heard in or just after a stall
724
+ // (`SHELL_AFTER_STALL_MS`), in a fight for a text field, or within `KEY_PRESS_MS` of a key
725
+ // the person typed on the host's page before it, it is no one's (a press says nothing of
726
+ // when it was until the shell hears it, and Enter or Space on a button the page put the
727
+ // focus on is the person's key landing in the page); and whether a press could have made
728
+ // it is judged now, as the shell tells it (P120).
729
+ const pressNew = typeof said.presses === "number" && said.presses !== (before.presses ?? 0);
730
+ const pressHeardAt = typeof said.pressed === "number"
731
+ ? at - said.pressed - Math.min(said.gap, SHELL_STALL_MS)
732
+ : -Infinity;
733
+ const pressTyping = typedBefore(pressHeardAt);
734
+ const pressedAt = typeof said.pressed !== "number"
735
+ ? -Infinity
736
+ : !pressNew
737
+ ? (before.pressedAt ?? -Infinity)
738
+ : at - guarded.stalledAt <= SHELL_AFTER_STALL_MS ||
739
+ fought ||
740
+ pressHeardAt - pressTyping < KEY_PRESS_MS
741
+ ? -Infinity
742
+ : at - said.pressed;
743
+ const pressKeyed = pressedAt === -Infinity
744
+ ? false
745
+ : pressNew
746
+ ? !pressPossible(true, frame.matches(":hover"), guarded.overSince, pressTyping, pressHeardAt)
747
+ : before.pressKeyed === true;
689
748
  guarded.word = {
690
749
  supported: said.supported,
691
750
  activatedAt,
@@ -693,15 +752,33 @@ export function focusGuard(view) {
693
752
  focusedAt: said.focused && !before.focused ? at : before.focusedAt,
694
753
  ...(uncertain ? { uncertain: true } : {}),
695
754
  ...(keyed ? { keyed: true } : {}),
755
+ ...(said.presses === undefined ? {} : { pressedAt, presses: said.presses }),
756
+ ...(pressKeyed ? { pressKeyed: true } : {}),
696
757
  };
697
758
  if (waiting?.frame === frame) {
698
759
  settle(at);
699
760
  }
761
+ else if (pressNew &&
762
+ known === frame &&
763
+ document.activeElement === frame &&
764
+ contest === null &&
765
+ shellPress(guarded.word, inputAt, at) &&
766
+ !(pointerShown && pressKeyed)) {
767
+ // Focus is in the frame already and the person pressed in its page: theirs from here on,
768
+ // as a move into it they made is (the shell's word on the move may have come before the
769
+ // press's did).
770
+ earned = true;
771
+ }
700
772
  },
701
773
  beat(frame) {
702
774
  const guarded = frames.get(frame);
703
775
  if (guarded !== undefined && guarded.word !== null) {
704
- guarded.heardAt = now();
776
+ const at = now();
777
+ // The first word after a silence may be a heartbeat: the stall is the same.
778
+ if (at - guarded.heardAt > SHELL_STALL_MS) {
779
+ guarded.stalledAt = at;
780
+ }
781
+ guarded.heardAt = at;
705
782
  }
706
783
  },
707
784
  gesture(frame) {
@@ -710,10 +787,7 @@ export function focusGuard(view) {
710
787
  const at = now();
711
788
  // Where a press could have made it (P120): a key the person typed into the page, meant for
712
789
  // the host's composer, turns the shell's activation on too.
713
- return (guarded !== undefined &&
714
- word !== null &&
715
- shellGesture(word, inputAt, at) &&
716
- !(pointerShown && word.keyed === true));
790
+ return guarded !== undefined && word !== null && shellSaw(word, inputAt, at, pointerShown);
717
791
  },
718
792
  focus(frame) {
719
793
  hostMove = { frame, at: now() };
@@ -24,7 +24,7 @@ function shellWords(opened, frame, guard) {
24
24
  if (params === null || typeof params !== "object") {
25
25
  return;
26
26
  }
27
- const { supported, ago, focused, gap, asked } = params;
27
+ const { supported, ago, focused, gap, asked, pressed, presses } = params;
28
28
  const span = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
29
29
  if (message.method === SHELL_BEAT_METHOD) {
30
30
  if (span(gap)) {
@@ -37,7 +37,12 @@ function shellWords(opened, frame, guard) {
37
37
  typeof focused !== "boolean" ||
38
38
  !(ago === null || span(ago)) ||
39
39
  !span(gap) ||
40
- !(asked === undefined || (Number.isSafeInteger(asked) && asked >= 0))) {
40
+ !(asked === undefined || (Number.isSafeInteger(asked) && asked >= 0)) ||
41
+ // The page's presses (P148): absent from a shell older than them, or both there.
42
+ !((pressed === undefined && presses === undefined) ||
43
+ ((pressed === null || span(pressed)) &&
44
+ Number.isSafeInteger(presses) &&
45
+ presses >= 0))) {
41
46
  return;
42
47
  }
43
48
  guard.shell(frame, {
@@ -46,6 +51,9 @@ function shellWords(opened, frame, guard) {
46
51
  focused,
47
52
  gap: gap,
48
53
  ...(asked === undefined ? {} : { asked: asked }),
54
+ ...(presses === undefined
55
+ ? {}
56
+ : { pressed: pressed, presses: presses }),
49
57
  });
50
58
  });
51
59
  return {
@@ -2,7 +2,7 @@ import { INERT_FILE_CSP, PAGE_SANDBOX_TOKENS, servedPermissionsPolicy, serialize
2
2
  import { frameShellDocument, frameShellScript } from "../shell/frame.js";
3
3
  import { onNestedLabel, PORTHOLE_LABEL_PREFIX } from "../isolation/served.js";
4
4
  import { sha256, utf8 } from "./crypto.js";
5
- import { ancestorsOf } from "./pages.js";
5
+ import { ancestorsOf, checkHostOrigins } from "./pages.js";
6
6
  import { base32 } from "./keys.js";
7
7
  export { isNestedLabel, PORTHOLE_LABEL_PREFIX } from "../isolation/served.js";
8
8
  /**
@@ -38,6 +38,7 @@ const base64 = (bytes) => btoa(String.fromCharCode(...bytes));
38
38
  * document of its own, which inherits none of this (a framed URL's document never does).
39
39
  */
40
40
  export function nestedShellCsp(script, origin, hostOrigins, framedBy = []) {
41
+ checkHostOrigins("nestedShellCsp", hostOrigins);
41
42
  const files = `${origin}${NESTED_FILES_PREFIX}`;
42
43
  const directives = [
43
44
  ["default-src", "'none'"],
@@ -1,7 +1,14 @@
1
1
  import type { FrameBlock } from "../host/types.ts";
2
2
  /**
3
- * Who may frame a page: the host origins, then a host's `framedBy` (P141), each checked (they go
4
- * into a header).
3
+ * The host origins a helper was given, each checked as a config's are (`hostOriginProblem`, P145):
4
+ * they go into a header (`frame-ancestors`) and into the page's own list of whom it tells, and a
5
+ * content Worker of a host's own passes them here itself. `who` names the helper in the error.
6
+ */
7
+ export declare function checkHostOrigins(who: string, hostOrigins: readonly string[]): void;
8
+ /**
9
+ * Who may frame a page: the host origins, then a host's `framedBy` (P141), each `framedBy`
10
+ * checked here (they go into a header); the host origins by whoever was given them (a config's by
11
+ * `createServer`, a helper's by `checkHostOrigins`).
5
12
  */
6
13
  export declare function ancestorsOf(hostOrigins: readonly string[], framedBy?: readonly string[]): string;
7
14
  /** Where the pages' scripts are served, on every content origin. */
@@ -1,5 +1,5 @@
1
1
  import { DOOR_SANDBOX_TOKENS } from "../compile/policy.js";
2
- import { framedByProblem, includesOrigin, normalOrigin } from "../isolation/served.js";
2
+ import { framedByProblem, hostOriginProblem, 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
  /**
@@ -24,8 +24,22 @@ const isStrict = (frameAncestors, hostOrigins) => !heldToHosts(frameAncestors, h
24
24
  /** The attribute that says so, on a page's `<main>`: none where its parent is held to its hosts. */
25
25
  const strictParent = (strict) => (strict ? ' data-porthole-strict-parent=""' : "");
26
26
  /**
27
- * Who may frame a page: the host origins, then a host's `framedBy` (P141), each checked (they go
28
- * into a header).
27
+ * The host origins a helper was given, each checked as a config's are (`hostOriginProblem`, P145):
28
+ * they go into a header (`frame-ancestors`) and into the page's own list of whom it tells, and a
29
+ * content Worker of a host's own passes them here itself. `who` names the helper in the error.
30
+ */
31
+ export function checkHostOrigins(who, hostOrigins) {
32
+ for (const origin of hostOrigins) {
33
+ const problem = hostOriginProblem(origin);
34
+ if (problem !== null) {
35
+ throw new TypeError(`${who}: hostOrigins: ${problem}`);
36
+ }
37
+ }
38
+ }
39
+ /**
40
+ * Who may frame a page: the host origins, then a host's `framedBy` (P141), each `framedBy`
41
+ * checked here (they go into a header); the host origins by whoever was given them (a config's by
42
+ * `createServer`, a helper's by `checkHostOrigins`).
29
43
  */
30
44
  export function ancestorsOf(hostOrigins, framedBy = []) {
31
45
  for (const origin of framedBy) {
@@ -209,12 +223,17 @@ export function appStatusPage(status, title, detail, frameAncestors, reason, hos
209
223
  });
210
224
  }
211
225
  /** 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
- : {
226
+ const framingOf = (who, options) => {
227
+ if (options.embed === true) {
228
+ return { hosts: [], ancestors: "*" };
229
+ }
230
+ // Checked here too: with `frameAncestors` given, `ancestorsOf` never sees them.
231
+ checkHostOrigins(who, options.hostOrigins);
232
+ return {
215
233
  hosts: options.hostOrigins,
216
234
  ancestors: options.frameAncestors ?? ancestorsOf(options.hostOrigins, options.framedBy),
217
235
  };
236
+ };
218
237
  /**
219
238
  * A page saying why a frame shows nothing, for a relay of the app's own (P072): told to the page
220
239
  * that frames it, at each web host origin and (a desktop scheme among them) to its parent (P070),
@@ -222,7 +241,7 @@ const framingOf = (options) => options.embed === true
222
241
  * any page and told to no one.
223
242
  */
224
243
  export function statusPageOf(options) {
225
- const { hosts, ancestors } = framingOf(options);
244
+ const { hosts, ancestors } = framingOf("statusPage", options);
226
245
  return appStatusPage(options.status, options.title, options.detail, ancestors, options.reason ?? "error", hosts, options.link, options.method);
227
246
  }
228
247
  /** A door's word that its display may be framed (P125), from the page's data attributes. */
@@ -256,6 +275,7 @@ const doorHeaders = (script, frameAncestors) => new Headers({
256
275
  * own ticket was taken and the checks the content's address runs passed for the same grant.
257
276
  */
258
277
  export function doorResponse(options) {
278
+ checkHostOrigins("doorResponse", options.hostOrigins);
259
279
  const hosts = escape(JSON.stringify(options.hostOrigins));
260
280
  const ancestors = options.frameAncestors ?? ancestorsOf(options.hostOrigins, options.framedBy);
261
281
  const strict = isStrict(ancestors, options.hostOrigins);
@@ -275,7 +295,7 @@ export function doorResponse(options) {
275
295
  */
276
296
  export function doorStatusResponse(options) {
277
297
  const { status, reason, code } = options;
278
- const framing = framingOf(options);
298
+ const framing = framingOf("doorStatusResponse", options);
279
299
  const hosts = escape(JSON.stringify(framing.hosts));
280
300
  const ancestors = framing.ancestors;
281
301
  const strict = isStrict(ancestors, framing.hosts);
@@ -2,7 +2,7 @@
2
2
  export declare const FRAME_SHELL_RUNTIME: string;
3
3
  /** A strict shell's runtime (P141): its parent may be an outer page. */
4
4
  export declare const STRICT_FRAME_SHELL_RUNTIME: string;
5
- export { SHELL_METHOD_PREFIX, SHELL_STATE_METHOD } from "../isolation/types.ts";
5
+ export { SHELL_METHOD_PREFIX, SHELL_PRESS_PORT_METHOD, SHELL_STATE_METHOD, } from "../isolation/types.ts";
6
6
  export interface FrameShellOptions {
7
7
  /** The host origins: the shell takes messages from its parent only from these. */
8
8
  readonly origins: readonly string[];
@@ -22,6 +22,15 @@ import { framedByProblem, hostOriginProblem, includesOrigin, onNestedLabel, } fr
22
22
  * before the shell's next frame would turn its activation on as a press does). What it can't
23
23
  * see: a gesture while its activation is already on (within 5 s of the last one) turns nothing
24
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);
25
34
  * - renews the page's sealed files' address before it ends, and gives the page the new one
26
35
  * (`porthole/files-renewed`): the page's own loads aren't its origin's (an opaque origin's never
27
36
  * are), so only the shell, on that origin, may renew it (P083);
@@ -76,6 +85,63 @@ const frameShellRuntime = (strict) => String.raw `(() => {
76
85
  frame.style.width = "100%";
77
86
  frame.style.height = "100%";
78
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
+ });
79
145
  frame.src = page.href;
80
146
  document.body.append(frame);
81
147
 
@@ -120,6 +186,9 @@ const frameShellRuntime = (strict) => String.raw `(() => {
120
186
  ago: active ? Math.max(0, Math.round(performance.now() - since)) : null,
121
187
  focused,
122
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,
123
192
  };
124
193
  // The answer to the host's ask (P120), by its number.
125
194
  if (asked !== undefined) {
@@ -127,7 +196,7 @@ const frameShellRuntime = (strict) => String.raw `(() => {
127
196
  }
128
197
  toHost({ jsonrpc: "2.0", method: PREFIX + "state", params });
129
198
  };
130
- const look = (asked) => {
199
+ const look = (asked, pressed) => {
131
200
  const now = performance.now();
132
201
  const gap = now - lookedAt;
133
202
  lookedAt = now;
@@ -145,7 +214,7 @@ const frameShellRuntime = (strict) => String.raw `(() => {
145
214
  focused = inside;
146
215
  changed = true;
147
216
  }
148
- if (changed || typeof asked === "number") {
217
+ if (changed || pressed === true || typeof asked === "number") {
149
218
  tell(gap, typeof asked === "number" ? asked : undefined);
150
219
  } else if (now - toldAt >= 50) {
151
220
  // The heartbeat: the host knows the shell was looking, every 50 ms.
@@ -274,7 +343,7 @@ const STRICT_CONDITION = `
274
343
  export const FRAME_SHELL_RUNTIME = frameShellRuntime(false);
275
344
  /** A strict shell's runtime (P141): its parent may be an outer page. */
276
345
  export const STRICT_FRAME_SHELL_RUNTIME = frameShellRuntime(true);
277
- export { SHELL_METHOD_PREFIX, SHELL_STATE_METHOD } from "../isolation/types.js";
346
+ export { SHELL_METHOD_PREFIX, SHELL_PRESS_PORT_METHOD, SHELL_STATE_METHOD, } from "../isolation/types.js";
278
347
  /** JSON that is safe inside a `<script>`. */
279
348
  const scriptJson = (value) => JSON.stringify(value)
280
349
  .replace(/</gu, "\\u003c")
@@ -56,5 +56,10 @@ export interface ShellPlan {
56
56
  * those iframes and removes every other frame-like element. Absent: it removes them all.
57
57
  */
58
58
  readonly nestedFrames?: "own";
59
+ /**
60
+ * A nested page's (P148): its runtime tells its shell each real press, over the port the shell
61
+ * sends it. Absent for every other plan: their runtime listens for no port and tells no press.
62
+ */
63
+ readonly press?: true;
59
64
  }
60
65
  export declare function shellPlan(config: PortholeConfig): ShellPlan | null;
@@ -46,5 +46,7 @@ export function shellPlan(config) {
46
46
  protocolVersion: MCP_APPS_PROTOCOL_VERSION,
47
47
  // Only where opted into (P128): every other plan is the same as before it.
48
48
  ...(config.nestedFrames === "own" ? { nestedFrames: "own" } : {}),
49
+ // A nested page's alone (P148): every other plan is the same as before it.
50
+ ...(config.nested === true ? { press: true } : {}),
49
51
  };
50
52
  }