@botiverse/porthole 0.14.15 → 0.14.17

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 (45) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/dist/annotate/types.d.ts +10 -1
  3. package/dist/annotate/validate.d.ts +9 -2
  4. package/dist/annotate/validate.js +9 -2
  5. package/dist/check/page-source.js +1 -1
  6. package/dist/conformance/harness-source.js +1 -1
  7. package/dist/host/create-host.js +11 -8
  8. package/dist/host/types.d.ts +13 -6
  9. package/dist/isolation/served.d.ts +8 -0
  10. package/dist/isolation/served.js +16 -0
  11. package/dist/react/frame.d.ts +9 -1
  12. package/dist/react/frame.js +23 -3
  13. package/dist/server/host.d.ts +14 -1
  14. package/dist/server/host.js +8 -3
  15. package/dist/server/nested.d.ts +5 -4
  16. package/dist/server/nested.js +8 -6
  17. package/dist/server/pages.d.ts +16 -2
  18. package/dist/server/pages.js +51 -16
  19. package/dist/server/server.js +26 -2
  20. package/dist/server/types.d.ts +8 -0
  21. package/dist/shell/annotate.d.ts +5 -3
  22. package/dist/shell/annotate.js +36 -16
  23. package/dist/shell/frame.d.ts +6 -0
  24. package/dist/shell/frame.js +16 -3
  25. package/dist/shell/runtime.d.ts +10 -0
  26. package/dist/shell/runtime.js +72 -26
  27. package/docs/ADOPTING.md +40 -22
  28. package/docs/DECISIONS.md +318 -3
  29. package/docs/DESIGN.md +19 -10
  30. package/docs/THREAT_MODEL.md +39 -7
  31. package/package.json +1 -1
  32. package/src/annotate/types.ts +10 -1
  33. package/src/annotate/validate.ts +15 -3
  34. package/src/host/create-host.ts +13 -14
  35. package/src/host/types.ts +13 -6
  36. package/src/isolation/served.ts +21 -0
  37. package/src/react/frame.tsx +36 -5
  38. package/src/server/host.ts +22 -4
  39. package/src/server/nested.ts +13 -5
  40. package/src/server/pages.ts +72 -18
  41. package/src/server/server.ts +32 -1
  42. package/src/server/types.ts +8 -0
  43. package/src/shell/annotate.ts +36 -16
  44. package/src/shell/frame.ts +22 -3
  45. package/src/shell/runtime.ts +73 -26
@@ -1,9 +1,4 @@
1
- import {
2
- ANNOTATE_METHODS,
3
- type AnnotateMode,
4
- type AnnotationMark,
5
- type AnnotationReport,
6
- } from "../annotate/types.ts";
1
+ import { ANNOTATE_METHODS, type AnnotationMark, type AnnotationReport } from "../annotate/types.ts";
7
2
  import {
8
3
  annotateMode,
9
4
  checkMarks,
@@ -12,6 +7,7 @@ import {
12
7
  hasMarker,
13
8
  inViewport,
14
9
  parseReport,
10
+ type StartedMode,
15
11
  } from "../annotate/validate.ts";
16
12
  import { FIND_LIMITS, FIND_METHODS, type FindReport, type FindResult } from "../find/types.ts";
17
13
  import { blankQuery, checkFindQuery, parseFindReport, parseFindResult } from "../find/validate.ts";
@@ -234,7 +230,7 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
234
230
  const replay = new Map<string, unknown[]>();
235
231
  // Annotations: the host's state, given to each frame once it finished its handshake.
236
232
  const annotates = config.capabilities.annotate !== undefined;
237
- let annotating: Required<AnnotateMode> | null = null;
233
+ let annotating: StartedMode | null = null;
238
234
  let marks: AnnotationMark[] = [];
239
235
  let activeMark: string | null = null;
240
236
  // The mark the host follows (P112), or whether it follows the selection instead (P138), and
@@ -452,6 +448,12 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
452
448
  if (type === undefined) {
453
449
  return;
454
450
  }
451
+ // The followed selection (P138) only while the host follows it, and dropped unread
452
+ // otherwise (P140): a host that doesn't follow it takes it as 0.14.14 took a method it
453
+ // didn't know, so a malformed one is no refusal either.
454
+ if (type === "selectionTracked" && !trackingSelection) {
455
+ return;
456
+ }
455
457
  let report = parseReport({ ...(isRecord(raw.params) ? raw.params : {}), type });
456
458
  if (report === null) {
457
459
  void through.call("annotate", null);
@@ -476,12 +478,9 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
476
478
  emit("annotation", withinFrame(report));
477
479
  return;
478
480
  }
479
- // The followed selection (P138): only while the host follows it, on the same 60 a second
480
- // (one followed thing at a time), past the bridge's rate as the followed mark's.
481
+ // The followed selection (P138): only while the host follows it (above), on the same 60 a
482
+ // second (one followed thing at a time), past the bridge's rate as the followed mark's.
481
483
  if (report.type === "selectionTracked") {
482
- if (!trackingSelection) {
483
- return;
484
- }
485
484
  const at = Date.now();
486
485
  while (trackedTimes.length > 0 && at - (trackedTimes[0] as number) >= 1_000) {
487
486
  trackedTimes.shift();
@@ -504,7 +503,7 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
504
503
  }
505
504
  // A pick ends with it; holding a block (P112) lasts until the host stops it.
506
505
  if (kind === "element" && annotating.elements === true) {
507
- annotating = annotating.text ? { elements: false, text: true } : null;
506
+ annotating = annotating.text ? { ...annotating, elements: false } : null;
508
507
  }
509
508
  break;
510
509
  }
@@ -520,7 +519,7 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
520
519
  return;
521
520
  }
522
521
  if (annotating.elements === true) {
523
- annotating = annotating.text ? { elements: false, text: true } : null;
522
+ annotating = annotating.text ? { ...annotating, elements: false } : null;
524
523
  }
525
524
  break;
526
525
  case "anchored": {
package/src/host/types.ts CHANGED
@@ -300,7 +300,11 @@ export interface FindControls {
300
300
  * given to every frame the display runs (a reload, a navigation recovered from).
301
301
  */
302
302
  export interface AnnotationControls {
303
- /** Lets the person point at elements, select text, or both (default both). */
303
+ /**
304
+ * Lets the person point at elements, select text, or both (default both). With
305
+ * `keepSelection: true` (P140) the frame keeps what is selected for `track({ selection: true })`;
306
+ * without it, nothing is kept and a pick's outline goes with the pick.
307
+ */
304
308
  start(mode?: AnnotateMode): void;
305
309
  stop(): void;
306
310
  /** Marks these anchors (replacing the marks before); the frame reports where they are. */
@@ -320,14 +324,17 @@ export interface AnnotationControls {
320
324
  * highlights it while it is followed (an element in the outline it had while it was picked) and
321
325
  * reports `{ type: "selectionTracked", ... }` with the same boxes as `tracked` and `inView`, or
322
326
  * `state: "orphaned"` while it isn't in the page; at most 60 a second together with `tracked`.
323
- * A `show` leaves it, and `stop` (or a pick ending) too: it ends with `track(null)`, `track(id)`
327
+ * The frame keeps a selection to follow only for a host that said so at `start`
328
+ * (`keepSelection`, P140), or one that already follows the selection as it is made: without
329
+ * either, a follow asked after `selected` has nothing to follow and answers `orphaned`. A `show`
330
+ * leaves it, and `stop` (or a pick ending) too: it ends with `track(null)`, `track(id)`
324
331
  * or `clear` (comment posted, composer dismissed, Escape in it), and the highlight with it. A
325
332
  * newer shell answers at its next animation frame; an older one sends nothing (it reads the
326
333
  * message as `track(null)`), so until a `selectionTracked` comes, place by `selected`'s boxes.
327
- * Kept for a frame that runs later, which has no selection: it answers `orphaned`. The element
328
- * just picked stays outlined until then, so call it before a `start` or `stop` sent with it (a
329
- * stop ends that outline); while followed, `selected` isn't re-sent after a scroll (Tenny's
330
- * review).
334
+ * Kept for a frame that runs later, which has no selection: it answers `orphaned`. Under
335
+ * `keepSelection` the element just picked stays outlined until then, so call it before a `start`
336
+ * or `stop` sent with it (a stop ends that outline); while followed, `selected` isn't re-sent
337
+ * after a scroll (Tenny's review).
331
338
  */
332
339
  track(target: AnnotationTrackTarget): void;
333
340
  /** Removes every mark. */
@@ -78,6 +78,27 @@ export function hostOriginProblem(origin: unknown): string | null {
78
78
  return `${JSON.stringify(origin)} is not an exact origin (scheme://host[:port], lowercase, no path)`;
79
79
  }
80
80
 
81
+ const LOOPBACK_HOST = (host: string): boolean =>
82
+ host === "localhost" || host.endsWith(".localhost") || host === "127.0.0.1" || host === "[::1]";
83
+
84
+ /**
85
+ * Why `origin` can't be one of a host's `framedBy` (P141): an outer page that may be an
86
+ * ancestor of every frame the host shows, above the host's own page, and never a host origin. An
87
+ * exact web origin, `https://host[:port]` (lowercase, no path, no wildcard), or `http://` on
88
+ * loopback alone (`localhost`, `*.localhost`, `127.0.0.1`, `[::1]`) for development: never a
89
+ * desktop scheme, `"null"`, a CSP keyword or a list. Null if it can be.
90
+ */
91
+ export function framedByProblem(origin: unknown): string | null {
92
+ const parsed = typeof origin === "string" && isHostOrigin(origin) ? parseOrigin(origin) : null;
93
+ if (
94
+ parsed === null ||
95
+ !(parsed.scheme === "https" || (parsed.scheme === "http" && LOOPBACK_HOST(parsed.host)))
96
+ ) {
97
+ return `${JSON.stringify(origin)} is not an exact https origin (https://host[:port], lowercase, no path; http only on loopback)`;
98
+ }
99
+ return null;
100
+ }
101
+
81
102
  /**
82
103
  * Whether two hosts may be the same site. Without the public-suffix list this errs one way only:
83
104
  * it says "same site" whenever the hosts are equal or share their last two labels, so a pair it
@@ -680,7 +680,8 @@ export interface PortholeFrameProps {
680
680
  /**
681
681
  * Annotations, where the config declares `annotate` (P053): what the person may point at now
682
682
  * (elements, text, or both), or null to stop. A picked element ends element picking: set it
683
- * again to pick again.
683
+ * again to pick again. `keepSelection` is set for you on a start made while `trackedSelection` is
684
+ * given (P140).
684
685
  */
685
686
  readonly annotating?: AnnotateMode | null;
686
687
  /**
@@ -716,6 +717,13 @@ export interface PortholeFrameProps {
716
717
  * thing at a time); false, or leaving it out, ends it and its highlight (the comment posted, the
717
718
  * composer dismissed, Escape in it), and `trackedAnnotation`'s mark is followed again. Until a
718
719
  * `selectionTracked` comes, place by `selected`'s boxes: an older shell sends none.
720
+ *
721
+ * Give it from the first render, `false` until the composer opens (P140): each start of
722
+ * `annotating` made while it is given carries `keepSelection`, so the frame keeps what is picked
723
+ * or selected (and the picked element outlined) for the follow. It is read as a mode starts:
724
+ * giving it, or leaving it out, later restarts nothing, and counts from the next start. Left out
725
+ * when the mode started, the frame keeps nothing, and a follow asked after the pick has nothing
726
+ * to follow (`orphaned`).
719
727
  */
720
728
  readonly trackedSelection?: boolean;
721
729
  /** The display's imperative calls (`PortholeFrameHandle`, P118): React 19's `ref` prop. */
@@ -1292,10 +1300,18 @@ function Mount({
1292
1300
  : JSON.stringify([focusedAnnotation]);
1293
1301
  // By value: the same marks given again don't mark them again.
1294
1302
  const annotations = useByValue(frame.annotations);
1303
+ // The mode, by value: what the person may point at, and the host's own `keepSelection`. Not
1304
+ // whether `trackedSelection` is given (P140, Ferryman's review): that is read at each start, so
1305
+ // a composer's prop that appears or goes restarts no mode (which would turn a pick that ended
1306
+ // back on, for the person's next click to pick again).
1295
1307
  const mode =
1296
1308
  annotating === undefined || annotating === null
1297
1309
  ? ""
1298
- : JSON.stringify([annotating.elements ?? true, annotating.text ?? true]);
1310
+ : JSON.stringify([
1311
+ annotating.elements ?? true,
1312
+ annotating.text ?? true,
1313
+ annotating.keepSelection === true,
1314
+ ]);
1299
1315
  useEffect(() => {
1300
1316
  const display = handle.current;
1301
1317
  if (annotates && display !== null) {
@@ -1337,12 +1353,16 @@ function Mount({
1337
1353
  if (!annotates || display === null) {
1338
1354
  return;
1339
1355
  }
1340
- const wanted = mode === "" ? null : (JSON.parse(mode) as [boolean, boolean]);
1356
+ const wanted = mode === "" ? null : (JSON.parse(mode) as [boolean | "hold", boolean, boolean]);
1341
1357
  attempt(
1342
1358
  () =>
1343
1359
  wanted === null
1344
1360
  ? display.annotations.stop()
1345
- : display.annotations.start({ elements: wanted[0], text: wanted[1] }),
1361
+ : display.annotations.start({
1362
+ elements: wanted[0],
1363
+ text: wanted[1],
1364
+ ...(wanted[2] || keepsSelection(latest()) ? { keepSelection: true } : {}),
1365
+ }),
1346
1366
  latest(),
1347
1367
  );
1348
1368
  }, [annotates, mode]);
@@ -1442,7 +1462,9 @@ function applyAnnotations(display: DisplayHandle, frame: PortholeFrameProps): vo
1442
1462
  display.annotations.focus(focused);
1443
1463
  }
1444
1464
  if (frame.annotating !== undefined && frame.annotating !== null) {
1445
- display.annotations.start(frame.annotating);
1465
+ display.annotations.start(
1466
+ keepsSelection(frame) ? { ...frame.annotating, keepSelection: true } : frame.annotating,
1467
+ );
1446
1468
  }
1447
1469
  }, frame);
1448
1470
  }
@@ -1457,6 +1479,15 @@ function useByValue<T>(value: T): T {
1457
1479
  return useMemo(() => (key === "" ? undefined : JSON.parse(key)) as T, [key]);
1458
1480
  }
1459
1481
 
1482
+ /**
1483
+ * Whether a start keeps what is selected for a follow (P140): while `trackedSelection` is given
1484
+ * (true or false), or the host's own `keepSelection` says so. Read at each start, never a reason
1485
+ * for one.
1486
+ */
1487
+ function keepsSelection(frame: PortholeFrameProps): boolean {
1488
+ return frame.annotating?.keepSelection === true || frame.trackedSelection !== undefined;
1489
+ }
1490
+
1460
1491
  /** What a display follows (P118, P138): a mark's id, the selection (this one object), or nothing. */
1461
1492
  const SELECTION = Object.freeze({ selection: true } as const);
1462
1493
  type Followed = string | typeof SELECTION | null;
@@ -12,7 +12,7 @@ import {
12
12
  } from "./domain.ts";
13
13
  import { reservedLabels, type Naming } from "./naming.ts";
14
14
  import { peerAddress } from "./peer.ts";
15
- import { appStatusPage, tabOnlyPage } from "./pages.ts";
15
+ import { ancestorsOf, appStatusPage, tabOnlyPage } from "./pages.ts";
16
16
  import { createServer } from "./server.ts";
17
17
  import type {
18
18
  Access,
@@ -105,8 +105,21 @@ type Awaitable<T> = T | Promise<T>;
105
105
  export interface ContentHostOptions<V> {
106
106
  /** `content.example.com`, `content.localhost:8790`; empty: content off. Or parsed settings. */
107
107
  readonly domain: string | null | undefined | ContentDomainInfo;
108
- /** The app's own origins: they frame content (`frame-ancestors`) and are checked for clashes. */
108
+ /**
109
+ * The app's own origins: they frame content (`frame-ancestors`), are the only origins its frames
110
+ * hear and tell, and are checked for clashes.
111
+ */
109
112
  readonly appOrigins: readonly string[];
113
+ /**
114
+ * Origins of an outer page that frame the app itself (P141): each may be an ancestor of every frame
115
+ * the app shows, above an app origin's page, so it is in every `frame-ancestors` Porthole sends
116
+ * (content, nested pages, doors, status and entry pages, the authorize route's pages) after
117
+ * `appOrigins`, and nowhere else. Never an origin a frame hears or tells, never an app origin for
118
+ * redirect entry or the handoff; the app's own page must still be the frame's parent. Exact https
119
+ * origins (`http://` on loopback), none an app origin, none the content domain's site. The app's
120
+ * own `frame-ancestors` (its page's, which Porthole doesn't send) is the app's to set.
121
+ */
122
+ readonly framedBy?: readonly string[];
110
123
  /** At least 32 random bytes (or a string of at least 32 bytes). */
111
124
  readonly secret: Uint8Array | string;
112
125
  readonly tickets?: TicketStore;
@@ -636,6 +649,8 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
636
649
  let server: PortholeServer | null = null;
637
650
  let view: ContentHealthView = { state: "off" };
638
651
  let configs: Readonly<Record<string, PortholeConfig>> = {};
652
+ // Who may frame the authorize route's pages: the app origins, and the outer pages' once checked.
653
+ let appAncestors = options.appOrigins.join(" ");
639
654
 
640
655
  try {
641
656
  domain =
@@ -676,6 +691,7 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
676
691
  }),
677
692
  secret,
678
693
  hostOrigins: options.appOrigins,
694
+ ...(options.framedBy === undefined ? {} : { framedBy: options.framedBy }),
679
695
  configs,
680
696
  ...(options.source === undefined ? {} : { artifacts: { get: options.source } }),
681
697
  ...(options.assets === undefined
@@ -714,6 +730,8 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
714
730
  },
715
731
  }),
716
732
  });
733
+ // createServer checked them (P141): only then in a header of the app's.
734
+ appAncestors = ancestorsOf(options.appOrigins, options.framedBy);
717
735
  view = gate === undefined ? { state: "healthy" } : { state: "checking" };
718
736
  }
719
737
  } catch (error) {
@@ -1308,7 +1326,7 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
1308
1326
  status,
1309
1327
  title,
1310
1328
  detail,
1311
- options.appOrigins.join(" "),
1329
+ appAncestors,
1312
1330
  reason,
1313
1331
  options.appOrigins,
1314
1332
  link,
@@ -1337,7 +1355,7 @@ export function createContentHost<V>(options: ContentHostOptions<V>): ContentHos
1337
1355
  // sign-in or refusal there, and says nothing to the page that frames it.
1338
1356
  const dest = request.headers.get("sec-fetch-dest");
1339
1357
  if (dest === "iframe" || dest === "frame") {
1340
- return tabOnlyPage(options.appOrigins.join(" "), method);
1358
+ return tabOnlyPage(appAncestors, method);
1341
1359
  }
1342
1360
  const clean = `${domain.originOf(state.label)}${state.path}`;
1343
1361
  if (state.expired) {
@@ -9,6 +9,7 @@ import {
9
9
  import { frameShellDocument, frameShellScript, type FrameShellOptions } from "../shell/frame.ts";
10
10
  import { onNestedLabel, PORTHOLE_LABEL_PREFIX } from "../isolation/served.ts";
11
11
  import { sha256, utf8 } from "./crypto.ts";
12
+ import { ancestorsOf } from "./pages.ts";
12
13
  import { base32 } from "./keys.ts";
13
14
 
14
15
  export { isNestedLabel, PORTHOLE_LABEL_PREFIX } from "../isolation/served.ts";
@@ -46,13 +47,14 @@ const base64 = (bytes: Uint8Array): string => btoa(String.fromCharCode(...bytes)
46
47
  /**
47
48
  * The shell's CSP (a header): its own script alone runs (by its hash), it frames and fetches
48
49
  * nothing but its origin's sealed files (the page, the renewal), and only the host origins frame
49
- * it. Nothing of the page's runs here: the page is a document of its own, which inherits none of
50
- * this (a framed URL's document never does).
50
+ * it (with, above them, a host's `framedBy`, P141). Nothing of the page's runs here: the page is a
51
+ * document of its own, which inherits none of this (a framed URL's document never does).
51
52
  */
52
53
  export function nestedShellCsp(
53
54
  script: string,
54
55
  origin: string,
55
56
  hostOrigins: readonly string[],
57
+ framedBy: readonly string[] = [],
56
58
  ): string {
57
59
  const files = `${origin}${NESTED_FILES_PREFIX}`;
58
60
  const directives: CspDirective[] = [
@@ -62,7 +64,7 @@ export function nestedShellCsp(
62
64
  ["connect-src", files],
63
65
  ["base-uri", "'none'"],
64
66
  ["form-action", "'none'"],
65
- ["frame-ancestors", ...hostOrigins],
67
+ ["frame-ancestors", ...ancestorsOf(hostOrigins, framedBy).split(" ")],
66
68
  ];
67
69
  return serializeCsp(directives);
68
70
  }
@@ -88,7 +90,12 @@ export function nestedShellResponse(
88
90
  const script = frameShellScript(options);
89
91
  const headers = new Headers({
90
92
  "content-type": "text/html; charset=utf-8",
91
- "content-security-policy": nestedShellCsp(script, options.origin, options.origins),
93
+ "content-security-policy": nestedShellCsp(
94
+ script,
95
+ options.origin,
96
+ options.origins,
97
+ options.framedBy,
98
+ ),
92
99
  "cache-control": "no-store",
93
100
  "referrer-policy": "no-referrer",
94
101
  "x-content-type-options": "nosniff",
@@ -107,7 +114,8 @@ export function nestedShellResponse(
107
114
 
108
115
  /**
109
116
  * Who may frame a nested page and its files' answers: its shell (the shell's own origin, P114) and,
110
- * above it, the host origins (`frame-ancestors` names every ancestor).
117
+ * above it, the host origins and a host's `framedBy` (`frame-ancestors` names every ancestor; P141):
118
+ * `frameAncestors` is the server's whole list.
111
119
  */
112
120
  export const nestedAncestors = (origin: string, frameAncestors: string): string =>
113
121
  `${origin} ${frameAncestors}`;
@@ -1,16 +1,55 @@
1
1
  import { DOOR_SANDBOX_TOKENS } from "../compile/policy.ts";
2
+ import { framedByProblem } from "../isolation/served.ts";
2
3
  import { FRAME_STATUS_METHOD } from "../isolation/types.ts";
3
4
  import type { FrameBlock } from "../host/types.ts";
4
5
  import { base64url, sha256, utf8 } from "./crypto.ts";
5
6
 
6
7
  /**
7
8
  * The server's own pages on a content origin: why it shows nothing of the content, and the page a
8
- * framed app is entered through. Plain, framable only by the host origins, never cached. Each tells
9
- * the page that frames it how loading went (`porthole/notifications/frame-status`, P040), posted to
10
- * the host origins only, so a host can show its own fallback ("Open in a new tab"). Their words are
11
- * the host-agnostic mechanism's; a host that wants its own wording serves its own page in front.
9
+ * framed app is entered through. Plain, framable only by the host origins (and, above them, a
10
+ * host's `framedBy`, P141), never cached. Each tells the page that frames it how loading went
11
+ * (`porthole/notifications/frame-status`, P040), posted to the host origins only, so a host can show
12
+ * its own fallback ("Open in a new tab"). Their words are the host-agnostic mechanism's; a host that
13
+ * wants its own wording serves its own page in front.
12
14
  */
13
15
 
16
+ /**
17
+ * Whether a page's `frame-ancestors` holds its parent to its host origins: it names no one else.
18
+ * Where it does (a host's `framedBy`, P141), its parent may be an outer page, and the page says
19
+ * `*` only to a parent the engine names as a host origin (`strictParent`, below).
20
+ */
21
+ const heldToHosts = (frameAncestors: string, hostOrigins: readonly string[]): boolean =>
22
+ frameAncestors
23
+ .split(" ")
24
+ .filter((each) => each !== "")
25
+ .every((each) => hostOrigins.includes(each));
26
+
27
+ /** The attribute that says so, on a page's `<main>`: none where its parent is held to its hosts. */
28
+ const strictParent = (frameAncestors: string, hostOrigins: readonly string[]): string =>
29
+ heldToHosts(frameAncestors, hostOrigins) ? "" : ' data-porthole-strict-parent=""';
30
+
31
+ /**
32
+ * Who may frame a page: the host origins, then a host's `framedBy` (P141), each checked (they go
33
+ * into a header).
34
+ */
35
+ export function ancestorsOf(
36
+ hostOrigins: readonly string[],
37
+ framedBy: readonly string[] = [],
38
+ ): string {
39
+ for (const origin of framedBy) {
40
+ const problem = framedByProblem(origin);
41
+ if (problem !== null) {
42
+ throw new TypeError(`framedBy: ${problem}`);
43
+ }
44
+ if (hostOrigins.includes(origin)) {
45
+ throw new TypeError(`framedBy: ${origin} is a host origin already`);
46
+ }
47
+ }
48
+ return [...hostOrigins, ...framedBy.filter((each, at) => framedBy.indexOf(each) === at)].join(
49
+ " ",
50
+ );
51
+ }
52
+
14
53
  const escape = (text: string): string =>
15
54
  text.replace(/[&<>"']/gu, (char) => `&#${char.charCodeAt(0)};`);
16
55
 
@@ -27,17 +66,21 @@ export const SESSION_PATH = "/__porthole/session";
27
66
  * Tells the page that frames this one how loading went, at each web host origin. A desktop app's
28
67
  * own scheme (`ferry://app`) is no target origin a browser takes (postMessage throws), so where
29
68
  * the host origins hold one, and the parent isn't known to be a web host origin, the word goes to
30
- * the parent as `*`: these pages' `frame-ancestors` already hold their parent to the host origins,
31
- * and what they say is no secret (P070). One origin failing never stops the page.
69
+ * the parent as `*`: these pages' `frame-ancestors` hold their parent to the host origins, and what
70
+ * they say is no secret (P070). Where it names an outer page too (`framedBy`, P141), the parent may be
71
+ * the outer page: then `*` goes only to a parent the engine names (`location.ancestorOrigins`,
72
+ * not masked as "null") as one of the host origins, so an outer page is never told. One origin
73
+ * failing never stops the page.
32
74
  */
33
75
  const say = (): string =>
34
- `const say = (params) => {
76
+ `const strict = main.dataset.portholeStrictParent !== undefined;
77
+ const say = (params) => {
35
78
  if (window.parent === window) return;
36
79
  const message = { jsonrpc: "2.0", method: ${JSON.stringify(FRAME_STATUS_METHOD)}, params };
37
80
  const web = hosts.filter((origin) => origin.startsWith("https://") || origin.startsWith("http://"));
38
81
  for (const origin of web) { try { window.parent.postMessage(message, origin); } catch (_) {} }
39
82
  const parent = location.ancestorOrigins && location.ancestorOrigins.length > 0 ? location.ancestorOrigins[0] : null;
40
- if (web.length < hosts.length && (parent === null || !web.includes(parent))) { try { window.parent.postMessage(message, "*"); } catch (_) {} }
83
+ if (web.length < hosts.length && (parent === null || !web.includes(parent)) && (!strict || (parent !== null && hosts.includes(parent)))) { try { window.parent.postMessage(message, "*"); } catch (_) {} }
41
84
  };`;
42
85
 
43
86
  /** Tells the host the page is blocked, and why (from the page's data attributes). */
@@ -123,7 +166,7 @@ export function statusPage(
123
166
  hostOrigins: readonly string[] = [],
124
167
  code?: string,
125
168
  ): Response {
126
- const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escape(title)}</title><style>${STYLE}</style></head><body><main data-porthole-status="${status}" data-porthole-reason="${escape(reason)}"${code === undefined ? "" : ` data-porthole-code="${escape(code)}"`} data-porthole-hosts="${escape(JSON.stringify(hostOrigins))}"><h1>${escape(title)}</h1><p>${escape(detail)}</p></main><script src="${STATUS_SCRIPT_PATH}"></script></body></html>`;
169
+ const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escape(title)}</title><style>${STYLE}</style></head><body><main data-porthole-status="${status}" data-porthole-reason="${escape(reason)}"${code === undefined ? "" : ` data-porthole-code="${escape(code)}"`} data-porthole-hosts="${escape(JSON.stringify(hostOrigins))}"${strictParent(frameAncestors, hostOrigins)}><h1>${escape(title)}</h1><p>${escape(detail)}</p></main><script src="${STATUS_SCRIPT_PATH}"></script></body></html>`;
127
170
  return new Response(method === "HEAD" ? null : body, {
128
171
  status,
129
172
  headers: pageHeaders(frameAncestors, false),
@@ -137,7 +180,7 @@ export function enterPage(
137
180
  hostOrigins: readonly string[],
138
181
  cookie: string,
139
182
  ): Response {
140
- const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Opening the app</title><style>${STYLE}</style></head><body><main data-porthole-enter="" data-porthole-target="${escape(target)}" data-porthole-hosts="${escape(JSON.stringify(hostOrigins))}"><h1>Opening the app…</h1><p></p></main><script src="${ENTER_SCRIPT_PATH}"></script></body></html>`;
183
+ const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Opening the app</title><style>${STYLE}</style></head><body><main data-porthole-enter="" data-porthole-target="${escape(target)}" data-porthole-hosts="${escape(JSON.stringify(hostOrigins))}"${strictParent(frameAncestors, hostOrigins)}><h1>Opening the app…</h1><p></p></main><script src="${ENTER_SCRIPT_PATH}"></script></body></html>`;
141
184
  const headers = new Headers(pageHeaders(frameAncestors, true));
142
185
  headers.set("set-cookie", cookie);
143
186
  return new Response(body, { status: 200, headers });
@@ -173,7 +216,7 @@ export function appStatusPage(
173
216
  link === undefined
174
217
  ? ""
175
218
  : `<p><a href="${escape(link.href)}" target="_top" rel="noopener">${escape(link.text)}</a></p>`;
176
- const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escape(title)}</title><style>${STYLE}a{color:inherit}</style></head><body><main data-porthole-status="${status}" data-porthole-reason="${escape(reason)}" data-porthole-hosts="${escape(JSON.stringify(hostOrigins))}"><h1>${escape(title)}</h1><p>${escape(detail)}</p>${more}</main><script>${STATUS_SCRIPT}</script></body></html>`;
219
+ const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escape(title)}</title><style>${STYLE}a{color:inherit}</style></head><body><main data-porthole-status="${status}" data-porthole-reason="${escape(reason)}" data-porthole-hosts="${escape(JSON.stringify(hostOrigins))}"${strictParent(frameAncestors, hostOrigins)}><h1>${escape(title)}</h1><p>${escape(detail)}</p>${more}</main><script>${STATUS_SCRIPT}</script></body></html>`;
177
220
  return new Response(method === "HEAD" ? null : body, {
178
221
  status,
179
222
  headers: {
@@ -198,7 +241,12 @@ export function statusPageOf(options: {
198
241
  readonly detail: string;
199
242
  readonly reason?: FrameBlock;
200
243
  readonly hostOrigins: readonly string[];
201
- /** Who may frame it (`frame-ancestors`): default, the host origins. */
244
+ /**
245
+ * Origins of an outer page that may be an ancestor above a host origin's page (P141): added to its
246
+ * `frame-ancestors` after the host origins, never told anything. Default none.
247
+ */
248
+ readonly framedBy?: readonly string[];
249
+ /** Who may frame it (`frame-ancestors`): default, the host origins, then `framedBy`. */
202
250
  readonly frameAncestors?: string;
203
251
  readonly link?: { readonly href: string; readonly text: string };
204
252
  readonly method?: string;
@@ -207,7 +255,7 @@ export function statusPageOf(options: {
207
255
  options.status,
208
256
  options.title,
209
257
  options.detail,
210
- options.frameAncestors ?? options.hostOrigins.join(" "),
258
+ options.frameAncestors ?? ancestorsOf(options.hostOrigins, options.framedBy),
211
259
  options.reason ?? "error",
212
260
  options.hostOrigins,
213
261
  options.link,
@@ -242,9 +290,13 @@ const doorHeaders = (script: string, frameAncestors: string): Headers =>
242
290
  "x-robots-tag": "noindex, nofollow",
243
291
  });
244
292
 
245
- /** What a door is given: the host origins it tells, and who may frame it (default, those). */
293
+ /**
294
+ * What a door is given: the host origins it tells, and who may frame it (default, those and then
295
+ * `framedBy`, P141: an outer page's origins above a host origin's page, never told anything).
296
+ */
246
297
  export interface DoorOptions {
247
298
  readonly hostOrigins: readonly string[];
299
+ readonly framedBy?: readonly string[];
248
300
  readonly frameAncestors?: string;
249
301
  readonly method?: string;
250
302
  }
@@ -257,10 +309,11 @@ export interface DoorOptions {
257
309
  */
258
310
  export function doorResponse(options: DoorOptions): Response {
259
311
  const hosts = escape(JSON.stringify(options.hostOrigins));
260
- const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Opening</title></head><body><main data-porthole-door="" data-porthole-hosts="${hosts}"></main><script>${DOOR_SCRIPT}</script></body></html>`;
312
+ const ancestors = options.frameAncestors ?? ancestorsOf(options.hostOrigins, options.framedBy);
313
+ const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Opening</title></head><body><main data-porthole-door="" data-porthole-hosts="${hosts}"${strictParent(ancestors, options.hostOrigins)}></main><script>${DOOR_SCRIPT}</script></body></html>`;
261
314
  return new Response(options.method?.toUpperCase() === "HEAD" ? null : body, {
262
315
  status: 200,
263
- headers: doorHeaders(hashOfDoor(), options.frameAncestors ?? options.hostOrigins.join(" ")),
316
+ headers: doorHeaders(hashOfDoor(), ancestors),
264
317
  });
265
318
  }
266
319
 
@@ -279,10 +332,11 @@ export function doorStatusResponse(
279
332
  ): Response {
280
333
  const { status, reason, code } = options;
281
334
  const hosts = escape(JSON.stringify(options.hostOrigins));
282
- const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Not shown</title></head><body><main data-porthole-status="${status}" data-porthole-reason="${escape(reason)}"${code === undefined ? "" : ` data-porthole-code="${escape(code)}"`} data-porthole-hosts="${hosts}"></main><script>${STATUS_SCRIPT}</script></body></html>`;
335
+ const ancestors = options.frameAncestors ?? ancestorsOf(options.hostOrigins, options.framedBy);
336
+ const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Not shown</title></head><body><main data-porthole-status="${status}" data-porthole-reason="${escape(reason)}"${code === undefined ? "" : ` data-porthole-code="${escape(code)}"`} data-porthole-hosts="${hosts}"${strictParent(ancestors, options.hostOrigins)}></main><script>${STATUS_SCRIPT}</script></body></html>`;
283
337
  return new Response(options.method?.toUpperCase() === "HEAD" ? null : body, {
284
338
  status,
285
- headers: doorHeaders(hashOfStatus(), options.frameAncestors ?? options.hostOrigins.join(" ")),
339
+ headers: doorHeaders(hashOfStatus(), ancestors),
286
340
  });
287
341
  }
288
342
 
@@ -1,6 +1,7 @@
1
1
  import { compile, type CompiledConfig } from "../compile/compile.ts";
2
2
  import type { DisplayMode, EgressConfig } from "../config/schema.ts";
3
3
  import {
4
+ framedByProblem,
4
5
  hostOriginProblem,
5
6
  maybeSameSite,
6
7
  originMatchesSource,
@@ -438,7 +439,36 @@ export function createServer(options: ServerOptions): PortholeServer {
438
439
  );
439
440
  }
440
441
  }
441
- const frameAncestors = options.hostOrigins.join(" ");
442
+ // An outer page's origins (P141): ancestors above a host origin's page, in `frame-ancestors` alone.
443
+ const framedBy: string[] = [];
444
+ for (const origin of options.framedBy ?? []) {
445
+ const problem = framedByProblem(origin);
446
+ if (problem !== null) {
447
+ throw new TypeError(`framedBy: ${problem}`);
448
+ }
449
+ if (options.hostOrigins.includes(origin)) {
450
+ throw new TypeError(
451
+ `framedBy: ${origin} is a host origin already: framedBy names an ancestor that never talks to a frame`,
452
+ );
453
+ }
454
+ const parsed = parseOrigin(origin);
455
+ if (
456
+ parsed === null ||
457
+ parsed.host === domain ||
458
+ parsed.host.endsWith(`.${domain}`) ||
459
+ maybeSameSite(parsed.host, sampleHost)
460
+ ) {
461
+ throw new TypeError(
462
+ `framedBy: ${origin} may be the same site as the content domain ${domain}: serve content from a registrable domain the host uses for nothing else`,
463
+ );
464
+ }
465
+ if (!framedBy.includes(origin)) {
466
+ framedBy.push(origin);
467
+ }
468
+ }
469
+ // Who may be an ancestor of a frame served here: the host origins, then the outer pages' (P141).
470
+ // Every frame's `frame-ancestors` is this; whom a frame hears and tells is `hostOrigins` alone.
471
+ const frameAncestors = [...options.hostOrigins, ...framedBy].join(" ");
442
472
  let authorizeUrl: URL | null = null;
443
473
  if (options.entry !== undefined) {
444
474
  try {
@@ -1290,6 +1320,7 @@ export function createServer(options: ServerOptions): PortholeServer {
1290
1320
  const shell = nestedShellResponse(served.compiled, {
1291
1321
  origin: access.origin,
1292
1322
  origins: options.hostOrigins,
1323
+ framedBy,
1293
1324
  page: `${access.origin}${sealed.base}${rest}`,
1294
1325
  renew: { url: `${access.origin}${sealed.base}__porthole/renew`, expires: sealed.expires },
1295
1326
  method,
@@ -273,6 +273,14 @@ export interface ServerOptions {
273
273
  readonly secret: Uint8Array;
274
274
  /** The host origins that may embed content (`frame-ancestors`) and talk to a served shell. */
275
275
  readonly hostOrigins: readonly string[];
276
+ /**
277
+ * Further origins that may be an ancestor of every frame served here, above a host origin's
278
+ * page (P141): an outer page that frames the host's app. Added to each `frame-ancestors` after
279
+ * the host origins, and nowhere else: never an origin a shell, a door or a page takes a message
280
+ * from or says anything to, never a host origin for `entry` or the handoff. Exact https origins
281
+ * (`http://` on loopback), none a host origin, none the content domain's site. Default none.
282
+ */
283
+ readonly framedBy?: readonly string[];
276
284
  /**
277
285
  * The configs a served shell or page is served under, by the name a `ServedDocument` gives
278
286
  * (an artifact defaults to `artifact`, the MCP Apps sandbox proxy to `mcpApp`).