@botiverse/porthole 0.13.0 → 0.14.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 (68) hide show
  1. package/dist/annotate/types.d.ts +32 -3
  2. package/dist/annotate/types.js +4 -0
  3. package/dist/annotate/validate.js +19 -2
  4. package/dist/check/page-source.js +1 -1
  5. package/dist/compile/policy.d.ts +7 -0
  6. package/dist/compile/policy.js +13 -1
  7. package/dist/config/schema.d.ts +11 -0
  8. package/dist/config/validate.js +19 -0
  9. package/dist/conformance/harness-source.js +1 -1
  10. package/dist/displays/displays.js +3 -1
  11. package/dist/guide/limits.js +1 -1
  12. package/dist/host/create-host.d.ts +2 -0
  13. package/dist/host/create-host.js +73 -3
  14. package/dist/host/pass-on.d.ts +15 -0
  15. package/dist/host/pass-on.js +65 -0
  16. package/dist/host/types.d.ts +22 -0
  17. package/dist/index.d.ts +4 -1
  18. package/dist/index.js +4 -1
  19. package/dist/isolation/types.d.ts +8 -0
  20. package/dist/isolation/types.js +8 -0
  21. package/dist/platform/focus-guard.d.ts +71 -2
  22. package/dist/platform/focus-guard.js +187 -12
  23. package/dist/platform/types.d.ts +8 -1
  24. package/dist/platform/web.js +60 -4
  25. package/dist/presets/presets.d.ts +2 -0
  26. package/dist/presets/presets.js +1 -0
  27. package/dist/server/files.js +19 -3
  28. package/dist/server/index.d.ts +1 -0
  29. package/dist/server/index.js +4 -0
  30. package/dist/server/nested.d.ts +37 -0
  31. package/dist/server/nested.js +70 -0
  32. package/dist/server/server.js +57 -7
  33. package/dist/shell/annotate.d.ts +1 -1
  34. package/dist/shell/annotate.js +157 -7
  35. package/dist/shell/frame.d.ts +45 -0
  36. package/dist/shell/frame.js +250 -0
  37. package/dist/shell/plan.js +2 -1
  38. package/dist/shell/runtime.js +49 -14
  39. package/docs/ADOPTING.md +56 -2
  40. package/docs/ARCHITECTURE.md +23 -0
  41. package/docs/DECISIONS.md +209 -0
  42. package/docs/DESIGN.md +9 -0
  43. package/docs/THREAT_MODEL.md +75 -5
  44. package/package.json +1 -1
  45. package/src/annotate/types.ts +28 -3
  46. package/src/annotate/validate.ts +23 -2
  47. package/src/compile/policy.ts +14 -1
  48. package/src/config/schema.ts +11 -0
  49. package/src/config/validate.ts +23 -0
  50. package/src/displays/displays.ts +3 -1
  51. package/src/guide/limits.ts +1 -1
  52. package/src/host/create-host.ts +76 -4
  53. package/src/host/pass-on.ts +73 -0
  54. package/src/host/types.ts +20 -0
  55. package/src/index.ts +4 -1
  56. package/src/isolation/types.ts +12 -0
  57. package/src/platform/focus-guard.ts +258 -15
  58. package/src/platform/types.ts +8 -1
  59. package/src/platform/web.ts +81 -9
  60. package/src/presets/presets.ts +3 -0
  61. package/src/server/files.ts +19 -3
  62. package/src/server/index.ts +10 -0
  63. package/src/server/nested.ts +86 -0
  64. package/src/server/server.ts +65 -6
  65. package/src/shell/annotate.ts +157 -7
  66. package/src/shell/frame.ts +268 -0
  67. package/src/shell/plan.ts +2 -1
  68. package/src/shell/runtime.ts +49 -14
@@ -54,6 +54,33 @@ export const TAKES = {
54
54
  typing: { most: 3, withinMs: 10_000 },
55
55
  any: { most: 5, withinMs: 2_000 },
56
56
  };
57
+ /**
58
+ * A nested page's shell (P111) says its own activation turned on: a press or key of the person's
59
+ * in that page (activation goes up to ancestors, never down, so nothing on the host's page turns
60
+ * it on). A move of focus into the frame within this long of it, with no press or key on the
61
+ * host's page since, is the person's; so is a `comments.open` the page sends within it.
62
+ */
63
+ export const SHELL_GESTURE_MS = 1_000;
64
+ /**
65
+ * How long a move into a nested page's frame waits for its shell's word before it is taken for
66
+ * the page's: the shell says what it saw at its next animation frame, after the host's page
67
+ * already heard the move. A shell that says nothing in time (gone, stalled) has its frame's move
68
+ * taken back, as any page's.
69
+ */
70
+ export const SHELL_WAIT_MS = 500;
71
+ /**
72
+ * A shell's word that came this long before the host's page heard the move is about that move
73
+ * (the shell's frame can come first); one from before then is about an earlier one.
74
+ */
75
+ export const SHELL_EARLY_MS = 150;
76
+ /**
77
+ * A shell that went this long without a look, or without a word to the host (its heartbeat is every
78
+ * 50 ms), was stalled (P111, after its review): where the page shares the shell's thread (WebKit,
79
+ * Firefox), a page that holds it from its own click handler pushes the moment the shell sees its
80
+ * activation turn on past the person's next keys on the host's page. An activation it saw then is
81
+ * uncertain: it is no one's gesture until it lapses.
82
+ */
83
+ export const SHELL_STALL_MS = 100;
57
84
  /**
58
85
  * Whether the person moved focus into the frame themselves:
59
86
  * - the host did (`DisplayHandle.focus()`);
@@ -78,12 +105,28 @@ export function personMoved(move) {
78
105
  if (move.lastKey !== null && move.lastKey.key === "Tab" && move.now - move.lastKey.at <= TAB_MS) {
79
106
  return true;
80
107
  }
108
+ // A nested page (P111): its shell's activation turned on within the last second, and the host's
109
+ // page had no press or key of its own since (the person went back to it); or, where the engine
110
+ // tells it, a press on the frame. Nothing else: no pointer over it, no host-wide activation.
111
+ if (move.shell !== undefined && move.shell.word.supported) {
112
+ return ((move.seen && move.pressed) || shellGesture(move.shell.word, move.shell.hostInputAt, move.now));
113
+ }
81
114
  if (move.seen ? move.pressed : move.over && move.overSince > Math.max(move.typedAt, move.focusedAt)) {
82
115
  return true;
83
116
  }
84
117
  return (move.activation === true &&
85
118
  move.now - Math.max(move.gestureAt, move.focusedAt) > ACTIVATION_SPAN_MS);
86
119
  }
120
+ /**
121
+ * Whether a nested page's shell saw the person's gesture just now (P111): its activation turned on
122
+ * within `SHELL_GESTURE_MS`, after the host's page's last trusted press or key.
123
+ */
124
+ export function shellGesture(word, hostInputAt, now) {
125
+ return (word.supported &&
126
+ now - word.activatedAt <= SHELL_GESTURE_MS &&
127
+ now >= word.activatedAt &&
128
+ hostInputAt < word.activatedAt);
129
+ }
87
130
  /** Keys that type nothing on their own: they don't count as typing (a gesture still). */
88
131
  const MODIFIERS = new Set(["Shift", "Control", "Alt", "Meta", "AltGraph", "CapsLock", "Fn"]);
89
132
  /** The `<input>` types that take typed text (an unknown type is `text`). */
@@ -126,6 +169,14 @@ export function focusGuard(view) {
126
169
  let typedAt = -Infinity;
127
170
  let gestureAt = -Infinity;
128
171
  let pressAt = -Infinity;
172
+ /** The host's page's last trusted press or key (P111: a nested page's gesture must be later). */
173
+ let inputAt = -Infinity;
174
+ /**
175
+ * A move into a nested page's frame waiting for its shell's word (P111): from a text field
176
+ * (`field`: taken back unless the shell says the person's), or from anything else (null: only
177
+ * whether the frame is the person's for a gesture gate).
178
+ */
179
+ let waiting = null;
129
180
  /** When focus last went into a guarded frame, and whether the person moved it there. */
130
181
  let enteredAt = -Infinity;
131
182
  let earned = false;
@@ -149,8 +200,12 @@ export function focusGuard(view) {
149
200
  return undefined;
150
201
  }
151
202
  };
152
- /** What the person's move would need, read now: see `personMoved`. */
203
+ /**
204
+ * What the person's move would need, read now: see `personMoved`. Into a nested page's frame
205
+ * whose shell hasn't spoken of this move yet, `wait` (P111).
206
+ */
153
207
  const judge = (frame, guarded, seen, at) => {
208
+ const word = guarded.word;
154
209
  const moved = personMoved({
155
210
  now: at,
156
211
  seen,
@@ -163,10 +218,57 @@ export function focusGuard(view) {
163
218
  gestureAt,
164
219
  activation: activation(),
165
220
  hostMoved: hostMove !== null && hostMove.frame === frame && at - hostMove.at <= TAB_MS,
221
+ ...(word === null ? {} : { shell: { word, hostInputAt: inputAt } }),
166
222
  });
167
223
  hostMove = null;
224
+ // The shell tells a move at its next frame, the host's page hears it first: until the shell
225
+ // said focus came in (around now), its activation may be on its way.
226
+ if (!moved && word !== null && word.supported && word.focusedAt < at - SHELL_EARLY_MS) {
227
+ return "wait";
228
+ }
168
229
  return moved;
169
230
  };
231
+ /** Waits for a nested page's shell's word on a move (P111): decided by `settle`. */
232
+ const wait = (field, frame, guarded, at, failed) => {
233
+ waiting = { field, frame, guarded, since: at, failed };
234
+ known = frame;
235
+ enteredAt = at;
236
+ earned = false;
237
+ schedule();
238
+ };
239
+ /**
240
+ * A waiting move, once its shell spoke or the wait is over: the person's (the frame keeps
241
+ * focus), or the page's (from a text field, taken back). A move elsewhere since ends it.
242
+ */
243
+ const settle = (at) => {
244
+ const held = waiting;
245
+ if (held === null) {
246
+ return;
247
+ }
248
+ const { field, frame, guarded } = held;
249
+ if (deepActive(document) !== frame || !frames.has(frame)) {
250
+ // Moved on since: from the frame, as the next look judges it.
251
+ waiting = null;
252
+ known = frame;
253
+ return;
254
+ }
255
+ const word = guarded.word;
256
+ const theirs = word !== null && shellGesture(word, inputAt, at);
257
+ const spoke = word !== null && word.focusedAt >= held.since - SHELL_EARLY_MS;
258
+ if (theirs) {
259
+ waiting = null;
260
+ known = frame;
261
+ earned = true;
262
+ return;
263
+ }
264
+ if (!spoke && at - held.since < SHELL_WAIT_MS) {
265
+ return;
266
+ }
267
+ waiting = null;
268
+ if (field !== null && field.isConnected) {
269
+ takeBack(field, frame, guarded, at, held.failed);
270
+ }
271
+ };
170
272
  /**
171
273
  * Focus goes back to `field` once the engine has finished the move: given back inside its blur
172
274
  * it stays with the frame on Chromium and WebKit, and Firefox takes it back only from a frame
@@ -234,12 +336,23 @@ export function focusGuard(view) {
234
336
  contest = null;
235
337
  return false;
236
338
  }
237
- if (active === frame && judge(frame, guarded, seen, at)) {
238
- contest = null;
239
- known = frame;
240
- enteredAt = at;
241
- earned = true;
242
- return true;
339
+ if (active === frame) {
340
+ const verdict = judge(frame, guarded, seen, at);
341
+ if (verdict === true) {
342
+ contest = null;
343
+ known = frame;
344
+ enteredAt = at;
345
+ earned = true;
346
+ return true;
347
+ }
348
+ if (verdict === "wait") {
349
+ // A nested page's frame took it again (P111): its shell decides, as it would at first.
350
+ if (watched.heldSince !== null || at - watched.gaveAt >= GIVE_BACK_MS) {
351
+ contest = null;
352
+ wait(field, frame, guarded, at, true);
353
+ }
354
+ return true;
355
+ }
243
356
  }
244
357
  // Taken again once it was back (within `HELD_MS`), or not back yet after `GIVE_BACK_MS`: a
245
358
  // take-back that failed, given again and counted.
@@ -252,6 +365,10 @@ export function focusGuard(view) {
252
365
  const look = (seen) => {
253
366
  const active = deepActive(document);
254
367
  const at = now();
368
+ if (waiting !== null) {
369
+ settle(at);
370
+ return;
371
+ }
255
372
  if (watch(seen, active, at)) {
256
373
  return;
257
374
  }
@@ -286,7 +403,13 @@ export function focusGuard(view) {
286
403
  // From a text field it is judged below; from anything else it is let be, but only the
287
404
  // person's own move makes the frame theirs for a gesture gate (`focused`).
288
405
  enteredAt = at;
289
- earned = takesText(was) || judge(active, entered, seen, at);
406
+ const verdict = takesText(was) || judge(active, entered, seen, at);
407
+ if (verdict === "wait") {
408
+ // A nested page's (P111): theirs once its shell says so; nothing to take back.
409
+ wait(null, active, entered, at, false);
410
+ return;
411
+ }
412
+ earned = verdict;
290
413
  }
291
414
  // Into a text field from a display's frame (the person pressed the composer while the frame
292
415
  // had focus): watched as a take-back is, since a page that takes focus back on its own blur
@@ -307,7 +430,12 @@ export function focusGuard(view) {
307
430
  return;
308
431
  }
309
432
  const frame = active;
310
- if (judge(frame, guarded, seen, at)) {
433
+ const verdict = judge(frame, guarded, seen, at);
434
+ if (verdict === true) {
435
+ return;
436
+ }
437
+ if (verdict === "wait") {
438
+ wait(was, frame, guarded, at, false);
311
439
  return;
312
440
  }
313
441
  takeBack(was, frame, guarded, at, false);
@@ -323,7 +451,7 @@ export function focusGuard(view) {
323
451
  schedule();
324
452
  };
325
453
  const schedule = () => {
326
- if (polling === 0 && (frames.size > 0 || contest !== null)) {
454
+ if (polling === 0 && (frames.size > 0 || contest !== null || waiting !== null)) {
327
455
  polling = view.requestAnimationFrame(poll);
328
456
  }
329
457
  };
@@ -332,6 +460,9 @@ export function focusGuard(view) {
332
460
  };
333
461
  const press = (event) => {
334
462
  pressAt = now();
463
+ if (event.isTrusted) {
464
+ inputAt = pressAt;
465
+ }
335
466
  gestureAt = pressAt;
336
467
  const target = event.composedPath()[0];
337
468
  pressed =
@@ -343,6 +474,9 @@ export function focusGuard(view) {
343
474
  const at = now();
344
475
  gestureAt = at;
345
476
  lastKey = { key: event.key, at };
477
+ if (event.isTrusted) {
478
+ inputAt = at;
479
+ }
346
480
  if (event.key !== "Tab" && !MODIFIERS.has(event.key)) {
347
481
  typedAt = at;
348
482
  }
@@ -376,10 +510,17 @@ export function focusGuard(view) {
376
510
  view.setTimeout(() => look(false), 0);
377
511
  }, true);
378
512
  const guard = {
379
- add(frame, taken) {
513
+ add(frame, taken, options) {
380
514
  let guarded = frames.get(frame);
381
515
  if (guarded === undefined) {
382
- const entry = { taken: new Set(), overSince: -Infinity };
516
+ const entry = {
517
+ taken: new Set(),
518
+ overSince: -Infinity,
519
+ heardAt: -Infinity,
520
+ word: options?.nested === true
521
+ ? { supported: true, activatedAt: -Infinity, focused: false, focusedAt: -Infinity }
522
+ : null,
523
+ };
383
524
  frame.addEventListener("pointerover", () => {
384
525
  entry.overSince = now();
385
526
  });
@@ -396,6 +537,40 @@ export function focusGuard(view) {
396
537
  }
397
538
  };
398
539
  },
540
+ shell(frame, said) {
541
+ const guarded = frames.get(frame);
542
+ const before = guarded?.word ?? null;
543
+ if (guarded === undefined || before === null) {
544
+ return;
545
+ }
546
+ const at = now();
547
+ // Off to on after a stall, the shell's or the host's (no word for longer than its beat
548
+ // allows): uncertain, and so until it goes off (P111, after its review).
549
+ const turnedOn = said.ago !== null && before.activatedAt === -Infinity && !before.uncertain;
550
+ const stalled = said.gap > SHELL_STALL_MS || at - guarded.heardAt > SHELL_STALL_MS;
551
+ const uncertain = said.ago !== null && (before.uncertain === true || (turnedOn && stalled));
552
+ guarded.heardAt = at;
553
+ guarded.word = {
554
+ supported: said.supported,
555
+ activatedAt: said.ago === null || uncertain ? -Infinity : at - said.ago,
556
+ focused: said.focused,
557
+ focusedAt: said.focused && !before.focused ? at : before.focusedAt,
558
+ ...(uncertain ? { uncertain: true } : {}),
559
+ };
560
+ if (waiting?.frame === frame) {
561
+ settle(at);
562
+ }
563
+ },
564
+ beat(frame) {
565
+ const guarded = frames.get(frame);
566
+ if (guarded !== undefined && guarded.word !== null) {
567
+ guarded.heardAt = now();
568
+ }
569
+ },
570
+ gesture(frame) {
571
+ const word = frames.get(frame)?.word ?? null;
572
+ return word !== null && shellGesture(word, inputAt, now());
573
+ },
399
574
  focus(frame) {
400
575
  hostMove = { frame, at: now() };
401
576
  frame.focus();
@@ -22,6 +22,12 @@ export interface SurfaceSpec {
22
22
  readonly fill?: boolean;
23
23
  /** The height to start at (a remembered height, so a frame mounting again doesn't jump). */
24
24
  readonly initialHeightPx: number;
25
+ /**
26
+ * The frame holds a nested page's shell (P111): the host's config says so, never the frame. What
27
+ * the shell says of itself (`porthole/shell/state`) decides moves of focus into it and the
28
+ * gesture its page's calls need; nothing else in that namespace reaches the transport.
29
+ */
30
+ readonly nested?: boolean;
25
31
  }
26
32
  /** One isolated frame. */
27
33
  export interface Surface {
@@ -49,7 +55,8 @@ export interface Surface {
49
55
  /**
50
56
  * Whether the embedding page's focus is in this frame now, once the platform's focus guard
51
57
  * judged any move into it (P109); undefined, or absent, where the platform can't tell. A gesture
52
- * gate that asks for the person in the calling frame (`comments`) reads it: false refuses.
58
+ * gate that asks for the person in the calling frame (`comments`) reads it: false refuses. A
59
+ * nested page's frame (P111) is the person's too while its shell saw their gesture just now.
53
60
  */
54
61
  focused?(): boolean | undefined;
55
62
  /**
@@ -1,4 +1,4 @@
1
- import { FRAME_STATUS_METHOD } from "../isolation/types.js";
1
+ import { FRAME_STATUS_METHOD, SHELL_BEAT_METHOD, SHELL_METHOD_PREFIX, SHELL_STATE_METHOD, } from "../isolation/types.js";
2
2
  import { postMessageTransport } from "../transport/post-message.js";
3
3
  import { focusGuard } from "./focus-guard.js";
4
4
  /** A frame-status message (`porthole/notifications/frame-status`), by its method alone. */
@@ -6,6 +6,57 @@ const isFrameStatus = (data) => data !== null &&
6
6
  typeof data === "object" &&
7
7
  data.jsonrpc === "2.0" &&
8
8
  data.method === FRAME_STATUS_METHOD;
9
+ /** A shell's own message (P111), by its namespace. */
10
+ const isShellWord = (data) => data !== null &&
11
+ typeof data === "object" &&
12
+ typeof data.method === "string" &&
13
+ data.method.startsWith(SHELL_METHOD_PREFIX);
14
+ /**
15
+ * A nested page's transport (P111): the shell's state, checked, to the focus guard; the rest of
16
+ * the shell's namespace dropped; everything else as it came.
17
+ */
18
+ function shellWords(opened, frame, guard) {
19
+ const listeners = new Set();
20
+ opened.listen((message) => {
21
+ if (!isShellWord(message)) {
22
+ for (const listener of listeners) {
23
+ listener(message);
24
+ }
25
+ return;
26
+ }
27
+ const params = message.params;
28
+ if (params === null || typeof params !== "object") {
29
+ return;
30
+ }
31
+ const { supported, ago, focused, gap } = params;
32
+ const span = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
33
+ if (message.method === SHELL_BEAT_METHOD) {
34
+ if (span(gap)) {
35
+ guard.beat(frame);
36
+ }
37
+ return;
38
+ }
39
+ if (message.method !== SHELL_STATE_METHOD ||
40
+ typeof supported !== "boolean" ||
41
+ typeof focused !== "boolean" ||
42
+ !(ago === null || span(ago)) ||
43
+ !span(gap)) {
44
+ return;
45
+ }
46
+ guard.shell(frame, { supported, ago: ago, focused, gap: gap });
47
+ });
48
+ return {
49
+ send: (message) => opened.send(message),
50
+ listen(listener) {
51
+ listeners.add(listener);
52
+ return () => listeners.delete(listener);
53
+ },
54
+ close() {
55
+ listeners.clear();
56
+ opened.close();
57
+ },
58
+ };
59
+ }
9
60
  /**
10
61
  * The web platform: an `<iframe>` whose policy attributes are set before its document is given,
11
62
  * talking over `postMessage`. Its first load is the document it was given; any later load is the
@@ -61,17 +112,22 @@ export const webPlatform = {
61
112
  // fields that the person didn't make is undone.
62
113
  const guard = focusGuard(view);
63
114
  const taken = new Set();
115
+ const nested = spec.nested === true && spec.source.kind === "url";
64
116
  const unguard = guard.add(frame, (take) => {
65
117
  for (const listener of taken) {
66
118
  listener(take);
67
119
  }
68
- });
120
+ }, { nested });
69
121
  // A served frame may pass through the host's own pages (a redirect entry's, P068): what they
70
122
  // say of the frame's status is heard too, and nothing else from there.
71
123
  const own = view.origin;
72
- const transport = postMessageTransport(() => frame.contentWindow, origin, view, origin === "null" || own === "null" || own === origin
124
+ const opened = postMessageTransport(() => frame.contentWindow, origin, view, origin === "null" || own === "null" || own === origin
73
125
  ? undefined
74
126
  : { origin: own, accept: isFrameStatus });
127
+ // A nested page's shell (P111): its own words go to the guard, by the frame's window and the
128
+ // content origin (the transport's checks); the page's pass on. The shell drops any page
129
+ // message in its namespace, so there none is the page's.
130
+ const transport = nested ? shellWords(opened, frame, guard) : opened;
75
131
  return {
76
132
  transport,
77
133
  element: frame,
@@ -96,7 +152,7 @@ export const webPlatform = {
96
152
  return activation === undefined ? undefined : activation.isActive;
97
153
  },
98
154
  focused() {
99
- return guard.focused(frame);
155
+ return guard.focused(frame) || (nested && guard.gesture(frame));
100
156
  },
101
157
  onFocusTaken(listener) {
102
158
  taken.add(listener);
@@ -40,6 +40,8 @@ export interface PresetOptions {
40
40
  * be offered the runtime's own (`user`, `comments`, `artifact`, `assets`, `db`).
41
41
  */
42
42
  readonly runtime?: RuntimeVersion;
43
+ /** Domain isolation, artifact pages: the page in an opaque child of Porthole's shell (P111). */
44
+ readonly nested?: true;
43
45
  }
44
46
  /** What a live widget may say about a capability (P103): anything but origins of its own. */
45
47
  export type LiveCapabilityConfig = Omit<CapabilityConfig, "connect" | "resource">;
@@ -141,6 +141,7 @@ function build(mode, defaults, options) {
141
141
  ...(options.storage === undefined ? {} : { storage: options.storage }),
142
142
  ...(options.errors === undefined ? {} : { errors: options.errors }),
143
143
  ...(options.runtime === undefined ? {} : { runtime: options.runtime }),
144
+ ...(options.nested === undefined ? {} : { nested: options.nested }),
144
145
  });
145
146
  }
146
147
  export const presets = {
@@ -3,6 +3,7 @@ import { DEFAULT_ENTRY, lookupFile, requestFilePath } from "../files/paths.js";
3
3
  import { fileTypeOf } from "../files/types.js";
4
4
  import { isCodeAsset } from "../runtime/requests.js";
5
5
  import { sha256, utf8 } from "./crypto.js";
6
+ import { NESTED_FILE_HEADERS } from "./nested.js";
6
7
  const HEX = /^[0-9a-f]{64}$/u;
7
8
  const YEAR = 31_536_000;
8
9
  const hex = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
@@ -156,6 +157,8 @@ export async function serveFile(serving) {
156
157
  return nothing(serving, 404, method);
157
158
  }
158
159
  const { type, role } = fileTypeOf(found.path);
160
+ // A nested page (P111): in its shell's child, an opaque origin.
161
+ const nested = serving.compiled.config.nested === true;
159
162
  // In a frame, the version's files are at a sealed address (P083), which their own loads of the
160
163
  // artifact's assets carry as their `Referer` (P091): to this origin only, never another.
161
164
  const referrer = serving.base.startsWith("/__porthole/f/") &&
@@ -167,11 +170,17 @@ export async function serveFile(serving) {
167
170
  // A page and a script (a worker's policy is its script's) get the page's CSP, a page with its
168
171
  // frame's sandbox, on a tab of its own too (P099); anything else runs nothing when opened on
169
172
  // its own.
173
+ // A nested page's files are on its shell's origin (P111, after the review): every one carries a
174
+ // sandbox, so none opened as a document on its own (a tab, "open image in new tab") runs on that
175
+ // origin. Pages run their scripts, opaque; anything else runs nothing (a file's is inert already,
176
+ // a script's gets one too).
170
177
  const csp = role === "file"
171
178
  ? INERT_FILE_CSP
172
179
  : role === "page"
173
180
  ? servedDocumentCsp(serving.compiled.config, directives)
174
- : serializeCsp(directives);
181
+ : nested
182
+ ? `${serializeCsp(directives)}; sandbox`
183
+ : serializeCsp(directives);
175
184
  const headers = new Headers({
176
185
  "content-type": type,
177
186
  "x-content-type-options": "nosniff",
@@ -186,7 +195,8 @@ export async function serveFile(serving) {
186
195
  if (role === "page") {
187
196
  // Every page of the set in the shell (P081): its hardening, its host functions, its theme.
188
197
  const html = serving.compiled.shellDocument({
189
- origins: serving.hostOrigins,
198
+ // A nested page hears its shell, on its own origin, never the host (P111).
199
+ origins: nested ? [serving.origin] : serving.hostOrigins,
190
200
  document: await textOf(body),
191
201
  cspMeta: false,
192
202
  ...(referrer === "same-origin" ? { referrer } : {}),
@@ -222,8 +232,14 @@ export async function serveFile(serving) {
222
232
  }
223
233
  headers.set("cache-control", serving.pinned ? `private, max-age=${YEAR}, immutable` : "private, no-cache");
224
234
  // Only this origin's own pages load it: no other content origin (a sibling, same-site without
225
- // the public suffix list) can embed it with the viewer's cookie.
235
+ // the public suffix list) can embed it with the viewer's cookie. A nested page's origin is
236
+ // opaque, and its files carry their access in their path, never a cookie (P111).
226
237
  headers.set("cross-origin-resource-policy", "same-origin");
238
+ if (nested) {
239
+ for (const [name, value] of Object.entries(NESTED_FILE_HEADERS)) {
240
+ headers.set(name, value);
241
+ }
242
+ }
227
243
  headers.set("accept-ranges", "bytes");
228
244
  if (role === "file" && type === "application/octet-stream") {
229
245
  headers.set("content-disposition", "attachment");
@@ -37,6 +37,7 @@ export { createContentHost, HEALTH_PATH, ISSUE_BODY_BYTES, type ContentHealthVie
37
37
  export { clashOf, contentDomain, ContentDomainError, hostnameOf, type ContentDomainInfo, type ContentDomainProblem, } from "./domain.ts";
38
38
  export { d1TicketSchema, d1TicketStore, memoryTicketStore, type D1Like, type D1StatementLike, } from "./tickets.ts";
39
39
  export { FRAME_STATUS_METHOD } from "../isolation/types.ts";
40
+ export { NESTED_FILE_HEADERS, NESTED_FILES_PREFIX, nestedAncestors, nestedShellCsp, nestedShellResponse, } from "./nested.ts";
40
41
  export { isHostLabel, prefixedName, type Naming } from "./naming.ts";
41
42
  export { conformancePage } from "../conformance/page.ts";
42
43
  export type { PortholeConfig } from "../config/schema.ts";
@@ -37,6 +37,10 @@ export { createContentHost, HEALTH_PATH, ISSUE_BODY_BYTES, ASSET_LIBRARY_PATH, i
37
37
  export { clashOf, contentDomain, ContentDomainError, hostnameOf, } from "./domain.js";
38
38
  export { d1TicketSchema, d1TicketStore, memoryTicketStore, } from "./tickets.js";
39
39
  export { FRAME_STATUS_METHOD } from "../isolation/types.js";
40
+ // A nested page (P111): Porthole's shell at the framed address, the page and its files below the
41
+ // sealed prefix. `/server` serves them for a config with `nested`; a content Worker of its own
42
+ // answers the same (docs/ADOPTING.md, "Nested pages").
43
+ export { NESTED_FILE_HEADERS, NESTED_FILES_PREFIX, nestedAncestors, nestedShellCsp, nestedShellResponse, } from "./nested.js";
40
44
  export { isHostLabel, prefixedName } from "./naming.js";
41
45
  // The page an app serves in conformance test mode (P071).
42
46
  export { conformancePage } from "../conformance/page.js";
@@ -0,0 +1,37 @@
1
+ import type { CompiledConfig } from "../compile/compile.ts";
2
+ import { type FrameShellOptions } from "../shell/frame.ts";
3
+ /**
4
+ * A nested page's serving (P111): what the address the host frames answers (Porthole's shell,
5
+ * `nestedShellResponse`), and what changes on the page and its files below the sealed prefix
6
+ * (`nestedAncestors`, `NESTED_FILE_HEADERS`). `/server` serves both for a config with `nested`;
7
+ * a host serving its own content origin (its own Worker) answers the same.
8
+ */
9
+ /** Where every page and file of a nested page is, on its origin: its sealed files' prefix. */
10
+ export declare const NESTED_FILES_PREFIX = "/__porthole/f/";
11
+ /**
12
+ * The shell's CSP (a header): its own script alone runs (by its hash), it frames and fetches
13
+ * nothing but its origin's sealed files (the page, the renewal), and only the host origins frame
14
+ * it. Nothing of the page's runs here: the page is a document of its own, which inherits none of
15
+ * this (a framed URL's document never does).
16
+ */
17
+ export declare function nestedShellCsp(script: string, origin: string, hostOrigins: readonly string[]): string;
18
+ /**
19
+ * The answer at the address the host frames, for a nested page (P111): Porthole's shell, never
20
+ * stored (it carries the page's sealed address), its page at `options.page`.
21
+ */
22
+ export declare function nestedShellResponse(compiled: CompiledConfig, options: FrameShellOptions & {
23
+ readonly origin: string;
24
+ readonly method?: string;
25
+ }): Response;
26
+ /**
27
+ * Who may frame a nested page and its files' answers: its shell (the content origin) and, above
28
+ * it, the host origins (`frame-ancestors` names every ancestor).
29
+ */
30
+ export declare const nestedAncestors: (origin: string, frameAncestors: string) => string;
31
+ /**
32
+ * What a nested page's files (not its pages) carry beyond a served file's (P111): its page's
33
+ * origin is opaque, so a same-origin resource policy would refuse its own images and scripts, and
34
+ * its fetches, modules and fonts are CORS requests from `null`. The sealed address in their path
35
+ * is their access, never the request's origin.
36
+ */
37
+ export declare const NESTED_FILE_HEADERS: Readonly<Record<string, string>>;
@@ -0,0 +1,70 @@
1
+ import { servedPermissionsPolicy, serializeCsp } from "../compile/policy.js";
2
+ import { frameShellDocument, frameShellScript } from "../shell/frame.js";
3
+ import { sha256, utf8 } from "./crypto.js";
4
+ /**
5
+ * A nested page's serving (P111): what the address the host frames answers (Porthole's shell,
6
+ * `nestedShellResponse`), and what changes on the page and its files below the sealed prefix
7
+ * (`nestedAncestors`, `NESTED_FILE_HEADERS`). `/server` serves both for a config with `nested`;
8
+ * a host serving its own content origin (its own Worker) answers the same.
9
+ */
10
+ /** Where every page and file of a nested page is, on its origin: its sealed files' prefix. */
11
+ export const NESTED_FILES_PREFIX = "/__porthole/f/";
12
+ const base64 = (bytes) => btoa(String.fromCharCode(...bytes));
13
+ /**
14
+ * The shell's CSP (a header): its own script alone runs (by its hash), it frames and fetches
15
+ * nothing but its origin's sealed files (the page, the renewal), and only the host origins frame
16
+ * it. Nothing of the page's runs here: the page is a document of its own, which inherits none of
17
+ * this (a framed URL's document never does).
18
+ */
19
+ export function nestedShellCsp(script, origin, hostOrigins) {
20
+ const files = `${origin}${NESTED_FILES_PREFIX}`;
21
+ const directives = [
22
+ ["default-src", "'none'"],
23
+ ["script-src", `'sha256-${base64(sha256(utf8(script)))}'`],
24
+ ["frame-src", files],
25
+ ["connect-src", files],
26
+ ["base-uri", "'none'"],
27
+ ["form-action", "'none'"],
28
+ ["frame-ancestors", ...hostOrigins],
29
+ ];
30
+ return serializeCsp(directives);
31
+ }
32
+ /**
33
+ * The answer at the address the host frames, for a nested page (P111): Porthole's shell, never
34
+ * stored (it carries the page's sealed address), its page at `options.page`.
35
+ */
36
+ export function nestedShellResponse(compiled, options) {
37
+ const script = frameShellScript(options);
38
+ const headers = new Headers({
39
+ "content-type": "text/html; charset=utf-8",
40
+ "content-security-policy": nestedShellCsp(script, options.origin, options.origins),
41
+ "cache-control": "no-store",
42
+ "referrer-policy": "no-referrer",
43
+ "x-content-type-options": "nosniff",
44
+ "x-robots-tag": "noindex, nofollow",
45
+ });
46
+ // Denied to the shell, so to its child too (a frame's features are its parent's at most).
47
+ const permissions = servedPermissionsPolicy(compiled.config);
48
+ if (permissions !== null) {
49
+ headers.set("permissions-policy", permissions);
50
+ }
51
+ return new Response(options.method === "HEAD" ? null : frameShellDocument(script), {
52
+ status: 200,
53
+ headers,
54
+ });
55
+ }
56
+ /**
57
+ * Who may frame a nested page and its files' answers: its shell (the content origin) and, above
58
+ * it, the host origins (`frame-ancestors` names every ancestor).
59
+ */
60
+ export const nestedAncestors = (origin, frameAncestors) => `${origin} ${frameAncestors}`;
61
+ /**
62
+ * What a nested page's files (not its pages) carry beyond a served file's (P111): its page's
63
+ * origin is opaque, so a same-origin resource policy would refuse its own images and scripts, and
64
+ * its fetches, modules and fonts are CORS requests from `null`. The sealed address in their path
65
+ * is their access, never the request's origin.
66
+ */
67
+ export const NESTED_FILE_HEADERS = {
68
+ "cross-origin-resource-policy": "cross-origin",
69
+ "access-control-allow-origin": "*",
70
+ };