@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,4 +1,4 @@
1
- import { ANNOTATE_METHODS, } from "../annotate/types.js";
1
+ import { ANNOTATE_METHODS } from "../annotate/types.js";
2
2
  import { annotateMode, checkMarks, clampRect, followsSelection, hasMarker, inViewport, parseReport, } from "../annotate/validate.js";
3
3
  import { FIND_LIMITS, FIND_METHODS } from "../find/types.js";
4
4
  import { blankQuery, checkFindQuery, parseFindReport, parseFindResult } from "../find/validate.js";
@@ -370,6 +370,12 @@ export function createHost(config, options = {}) {
370
370
  if (type === undefined) {
371
371
  return;
372
372
  }
373
+ // The followed selection (P138) only while the host follows it, and dropped unread
374
+ // otherwise (P140): a host that doesn't follow it takes it as 0.14.14 took a method it
375
+ // didn't know, so a malformed one is no refusal either.
376
+ if (type === "selectionTracked" && !trackingSelection) {
377
+ return;
378
+ }
373
379
  let report = parseReport({ ...(isRecord(raw.params) ? raw.params : {}), type });
374
380
  if (report === null) {
375
381
  void through.call("annotate", null);
@@ -394,12 +400,9 @@ export function createHost(config, options = {}) {
394
400
  emit("annotation", withinFrame(report));
395
401
  return;
396
402
  }
397
- // The followed selection (P138): only while the host follows it, on the same 60 a second
398
- // (one followed thing at a time), past the bridge's rate as the followed mark's.
403
+ // The followed selection (P138): only while the host follows it (above), on the same 60 a
404
+ // second (one followed thing at a time), past the bridge's rate as the followed mark's.
399
405
  if (report.type === "selectionTracked") {
400
- if (!trackingSelection) {
401
- return;
402
- }
403
406
  const at = Date.now();
404
407
  while (trackedTimes.length > 0 && at - trackedTimes[0] >= 1_000) {
405
408
  trackedTimes.shift();
@@ -420,7 +423,7 @@ export function createHost(config, options = {}) {
420
423
  }
421
424
  // A pick ends with it; holding a block (P112) lasts until the host stops it.
422
425
  if (kind === "element" && annotating.elements === true) {
423
- annotating = annotating.text ? { elements: false, text: true } : null;
426
+ annotating = annotating.text ? { ...annotating, elements: false } : null;
424
427
  }
425
428
  break;
426
429
  }
@@ -436,7 +439,7 @@ export function createHost(config, options = {}) {
436
439
  return;
437
440
  }
438
441
  if (annotating.elements === true) {
439
- annotating = annotating.text ? { elements: false, text: true } : null;
442
+ annotating = annotating.text ? { ...annotating, elements: false } : null;
440
443
  }
441
444
  break;
442
445
  case "anchored": {
@@ -301,7 +301,11 @@ export interface FindControls {
301
301
  * given to every frame the display runs (a reload, a navigation recovered from).
302
302
  */
303
303
  export interface AnnotationControls {
304
- /** Lets the person point at elements, select text, or both (default both). */
304
+ /**
305
+ * Lets the person point at elements, select text, or both (default both). With
306
+ * `keepSelection: true` (P140) the frame keeps what is selected for `track({ selection: true })`;
307
+ * without it, nothing is kept and a pick's outline goes with the pick.
308
+ */
305
309
  start(mode?: AnnotateMode): void;
306
310
  stop(): void;
307
311
  /** Marks these anchors (replacing the marks before); the frame reports where they are. */
@@ -321,14 +325,17 @@ export interface AnnotationControls {
321
325
  * highlights it while it is followed (an element in the outline it had while it was picked) and
322
326
  * reports `{ type: "selectionTracked", ... }` with the same boxes as `tracked` and `inView`, or
323
327
  * `state: "orphaned"` while it isn't in the page; at most 60 a second together with `tracked`.
324
- * A `show` leaves it, and `stop` (or a pick ending) too: it ends with `track(null)`, `track(id)`
328
+ * The frame keeps a selection to follow only for a host that said so at `start`
329
+ * (`keepSelection`, P140), or one that already follows the selection as it is made: without
330
+ * either, a follow asked after `selected` has nothing to follow and answers `orphaned`. A `show`
331
+ * leaves it, and `stop` (or a pick ending) too: it ends with `track(null)`, `track(id)`
325
332
  * or `clear` (comment posted, composer dismissed, Escape in it), and the highlight with it. A
326
333
  * newer shell answers at its next animation frame; an older one sends nothing (it reads the
327
334
  * message as `track(null)`), so until a `selectionTracked` comes, place by `selected`'s boxes.
328
- * Kept for a frame that runs later, which has no selection: it answers `orphaned`. The element
329
- * just picked stays outlined until then, so call it before a `start` or `stop` sent with it (a
330
- * stop ends that outline); while followed, `selected` isn't re-sent after a scroll (Tenny's
331
- * review).
335
+ * Kept for a frame that runs later, which has no selection: it answers `orphaned`. Under
336
+ * `keepSelection` the element just picked stays outlined until then, so call it before a `start`
337
+ * or `stop` sent with it (a stop ends that outline); while followed, `selected` isn't re-sent
338
+ * after a scroll (Tenny's review).
332
339
  */
333
340
  track(target: AnnotationTrackTarget): void;
334
341
  /** Removes every mark. */
@@ -25,6 +25,14 @@ export declare function isExactOrigin(origin: unknown): origin is string;
25
25
  export declare function isHostOrigin(origin: unknown): origin is string;
26
26
  /** Why `origin` can't be a host origin, in words a host's developer can act on; null if it can. */
27
27
  export declare function hostOriginProblem(origin: unknown): string | null;
28
+ /**
29
+ * Why `origin` can't be one of a host's `framedBy` (P141): an outer page that may be an
30
+ * ancestor of every frame the host shows, above the host's own page, and never a host origin. An
31
+ * exact web origin, `https://host[:port]` (lowercase, no path, no wildcard), or `http://` on
32
+ * loopback alone (`localhost`, `*.localhost`, `127.0.0.1`, `[::1]`) for development: never a
33
+ * desktop scheme, `"null"`, a CSP keyword or a list. Null if it can be.
34
+ */
35
+ export declare function framedByProblem(origin: unknown): string | null;
28
36
  /**
29
37
  * Whether two hosts may be the same site. Without the public-suffix list this errs one way only:
30
38
  * it says "same site" whenever the hosts are equal or share their last two labels, so a pair it
@@ -58,6 +58,22 @@ export function hostOriginProblem(origin) {
58
58
  }
59
59
  return `${JSON.stringify(origin)} is not an exact origin (scheme://host[:port], lowercase, no path)`;
60
60
  }
61
+ const LOOPBACK_HOST = (host) => host === "localhost" || host.endsWith(".localhost") || host === "127.0.0.1" || host === "[::1]";
62
+ /**
63
+ * Why `origin` can't be one of a host's `framedBy` (P141): an outer page that may be an
64
+ * ancestor of every frame the host shows, above the host's own page, and never a host origin. An
65
+ * exact web origin, `https://host[:port]` (lowercase, no path, no wildcard), or `http://` on
66
+ * loopback alone (`localhost`, `*.localhost`, `127.0.0.1`, `[::1]`) for development: never a
67
+ * desktop scheme, `"null"`, a CSP keyword or a list. Null if it can be.
68
+ */
69
+ export function framedByProblem(origin) {
70
+ const parsed = typeof origin === "string" && isHostOrigin(origin) ? parseOrigin(origin) : null;
71
+ if (parsed === null ||
72
+ !(parsed.scheme === "https" || (parsed.scheme === "http" && LOOPBACK_HOST(parsed.host)))) {
73
+ return `${JSON.stringify(origin)} is not an exact https origin (https://host[:port], lowercase, no path; http only on loopback)`;
74
+ }
75
+ return null;
76
+ }
61
77
  /**
62
78
  * Whether two hosts may be the same site. Without the public-suffix list this errs one way only:
63
79
  * it says "same site" whenever the hosts are equal or share their last two labels, so a pair it
@@ -311,7 +311,8 @@ export interface PortholeFrameProps {
311
311
  /**
312
312
  * Annotations, where the config declares `annotate` (P053): what the person may point at now
313
313
  * (elements, text, or both), or null to stop. A picked element ends element picking: set it
314
- * again to pick again.
314
+ * again to pick again. `keepSelection` is set for you on a start made while `trackedSelection` is
315
+ * given (P140).
315
316
  */
316
317
  readonly annotating?: AnnotateMode | null;
317
318
  /**
@@ -347,6 +348,13 @@ export interface PortholeFrameProps {
347
348
  * thing at a time); false, or leaving it out, ends it and its highlight (the comment posted, the
348
349
  * composer dismissed, Escape in it), and `trackedAnnotation`'s mark is followed again. Until a
349
350
  * `selectionTracked` comes, place by `selected`'s boxes: an older shell sends none.
351
+ *
352
+ * Give it from the first render, `false` until the composer opens (P140): each start of
353
+ * `annotating` made while it is given carries `keepSelection`, so the frame keeps what is picked
354
+ * or selected (and the picked element outlined) for the follow. It is read as a mode starts:
355
+ * giving it, or leaving it out, later restarts nothing, and counts from the next start. Left out
356
+ * when the mode started, the frame keeps nothing, and a follow asked after the pick has nothing
357
+ * to follow (`orphaned`).
350
358
  */
351
359
  readonly trackedSelection?: boolean;
352
360
  /** The display's imperative calls (`PortholeFrameHandle`, P118): React 19's `ref` prop. */
@@ -729,9 +729,17 @@ function Mount({ frame, page, running, findFor, initialHeightPx, placeholder, ru
729
729
  : JSON.stringify([focusedAnnotation]);
730
730
  // By value: the same marks given again don't mark them again.
731
731
  const annotations = useByValue(frame.annotations);
732
+ // The mode, by value: what the person may point at, and the host's own `keepSelection`. Not
733
+ // whether `trackedSelection` is given (P140, Ferryman's review): that is read at each start, so
734
+ // a composer's prop that appears or goes restarts no mode (which would turn a pick that ended
735
+ // back on, for the person's next click to pick again).
732
736
  const mode = annotating === undefined || annotating === null
733
737
  ? ""
734
- : JSON.stringify([annotating.elements ?? true, annotating.text ?? true]);
738
+ : JSON.stringify([
739
+ annotating.elements ?? true,
740
+ annotating.text ?? true,
741
+ annotating.keepSelection === true,
742
+ ]);
735
743
  useEffect(() => {
736
744
  const display = handle.current;
737
745
  if (annotates && display !== null) {
@@ -776,7 +784,11 @@ function Mount({ frame, page, running, findFor, initialHeightPx, placeholder, ru
776
784
  const wanted = mode === "" ? null : JSON.parse(mode);
777
785
  attempt(() => wanted === null
778
786
  ? display.annotations.stop()
779
- : display.annotations.start({ elements: wanted[0], text: wanted[1] }), latest());
787
+ : display.annotations.start({
788
+ elements: wanted[0],
789
+ text: wanted[1],
790
+ ...(wanted[2] || keepsSelection(latest()) ? { keepSelection: true } : {}),
791
+ }), latest());
780
792
  }, [annotates, mode]);
781
793
  useEffect(() => {
782
794
  const display = handle.current;
@@ -859,7 +871,7 @@ function applyAnnotations(display, frame) {
859
871
  display.annotations.focus(focused);
860
872
  }
861
873
  if (frame.annotating !== undefined && frame.annotating !== null) {
862
- display.annotations.start(frame.annotating);
874
+ display.annotations.start(keepsSelection(frame) ? { ...frame.annotating, keepSelection: true } : frame.annotating);
863
875
  }
864
876
  }, frame);
865
877
  }
@@ -872,6 +884,14 @@ function useByValue(value) {
872
884
  const key = value === undefined ? "" : JSON.stringify(value);
873
885
  return useMemo(() => (key === "" ? undefined : JSON.parse(key)), [key]);
874
886
  }
887
+ /**
888
+ * Whether a start keeps what is selected for a follow (P140): while `trackedSelection` is given
889
+ * (true or false), or the host's own `keepSelection` says so. Read at each start, never a reason
890
+ * for one.
891
+ */
892
+ function keepsSelection(frame) {
893
+ return frame.annotating?.keepSelection === true || frame.trackedSelection !== undefined;
894
+ }
875
895
  /** What a display follows (P118, P138): a mark's id, the selection (this one object), or nothing. */
876
896
  const SELECTION = Object.freeze({ selection: true });
877
897
  /** What the props ask to follow: the selection while `trackedSelection`, else the mark, if any. */
@@ -72,8 +72,21 @@ type Awaitable<T> = T | Promise<T>;
72
72
  export interface ContentHostOptions<V> {
73
73
  /** `content.example.com`, `content.localhost:8790`; empty: content off. Or parsed settings. */
74
74
  readonly domain: string | null | undefined | ContentDomainInfo;
75
- /** The app's own origins: they frame content (`frame-ancestors`) and are checked for clashes. */
75
+ /**
76
+ * The app's own origins: they frame content (`frame-ancestors`), are the only origins its frames
77
+ * hear and tell, and are checked for clashes.
78
+ */
76
79
  readonly appOrigins: readonly string[];
80
+ /**
81
+ * Origins of an outer page that frame the app itself (P141): each may be an ancestor of every frame
82
+ * the app shows, above an app origin's page, so it is in every `frame-ancestors` Porthole sends
83
+ * (content, nested pages, doors, status and entry pages, the authorize route's pages) after
84
+ * `appOrigins`, and nowhere else. Never an origin a frame hears or tells, never an app origin for
85
+ * redirect entry or the handoff; the app's own page must still be the frame's parent. Exact https
86
+ * origins (`http://` on loopback), none an app origin, none the content domain's site. The app's
87
+ * own `frame-ancestors` (its page's, which Porthole doesn't send) is the app's to set.
88
+ */
89
+ readonly framedBy?: readonly string[];
77
90
  /** At least 32 random bytes (or a string of at least 32 bytes). */
78
91
  readonly secret: Uint8Array | string;
79
92
  readonly tickets?: TicketStore;
@@ -3,7 +3,7 @@ import { base64url, fromBase64url, fromUtf8, hmacSha256, timingSafeEqual, utf8 }
3
3
  import { ContentDomainError, contentDomain, serverDomain, } from "./domain.js";
4
4
  import { reservedLabels } from "./naming.js";
5
5
  import { peerAddress } from "./peer.js";
6
- import { appStatusPage, tabOnlyPage } from "./pages.js";
6
+ import { ancestorsOf, appStatusPage, tabOnlyPage } from "./pages.js";
7
7
  import { createServer } from "./server.js";
8
8
  /**
9
9
  * The host kit (P066): everything around `/server` that every host wrote, so an app writes only
@@ -252,6 +252,8 @@ export function createContentHost(options) {
252
252
  let server = null;
253
253
  let view = { state: "off" };
254
254
  let configs = {};
255
+ // Who may frame the authorize route's pages: the app origins, and the outer pages' once checked.
256
+ let appAncestors = options.appOrigins.join(" ");
255
257
  try {
256
258
  domain =
257
259
  options.domain !== null && typeof options.domain === "object"
@@ -285,6 +287,7 @@ export function createContentHost(options) {
285
287
  }),
286
288
  secret,
287
289
  hostOrigins: options.appOrigins,
290
+ ...(options.framedBy === undefined ? {} : { framedBy: options.framedBy }),
288
291
  configs,
289
292
  ...(options.source === undefined ? {} : { artifacts: { get: options.source } }),
290
293
  ...(options.assets === undefined
@@ -320,6 +323,8 @@ export function createContentHost(options) {
320
323
  },
321
324
  }),
322
325
  });
326
+ // createServer checked them (P141): only then in a header of the app's.
327
+ appAncestors = ancestorsOf(options.appOrigins, options.framedBy);
323
328
  view = gate === undefined ? { state: "healthy" } : { state: "checking" };
324
329
  }
325
330
  }
@@ -839,7 +844,7 @@ export function createContentHost(options) {
839
844
  return server === null || !served() ? null : server.urlOf(scope, path);
840
845
  },
841
846
  authorize(viewerOf) {
842
- const appPage = (status, title, detail, reason, method, link) => appStatusPage(status, title, detail, options.appOrigins.join(" "), reason, options.appOrigins, link, method);
847
+ const appPage = (status, title, detail, reason, method, link) => appStatusPage(status, title, detail, appAncestors, reason, options.appOrigins, link, method);
843
848
  return async (request) => {
844
849
  const method = request.method.toUpperCase();
845
850
  if (method !== "GET" && method !== "HEAD") {
@@ -857,7 +862,7 @@ export function createContentHost(options) {
857
862
  // sign-in or refusal there, and says nothing to the page that frames it.
858
863
  const dest = request.headers.get("sec-fetch-dest");
859
864
  if (dest === "iframe" || dest === "frame") {
860
- return tabOnlyPage(options.appOrigins.join(" "), method);
865
+ return tabOnlyPage(appAncestors, method);
861
866
  }
862
867
  const clean = `${domain.originOf(state.label)}${state.path}`;
863
868
  if (state.expired) {
@@ -28,10 +28,10 @@ export declare const NESTED_FILES_PREFIX = "/__porthole/f/";
28
28
  /**
29
29
  * The shell's CSP (a header): its own script alone runs (by its hash), it frames and fetches
30
30
  * nothing but its origin's sealed files (the page, the renewal), and only the host origins frame
31
- * it. Nothing of the page's runs here: the page is a document of its own, which inherits none of
32
- * this (a framed URL's document never does).
31
+ * it (with, above them, a host's `framedBy`, P141). Nothing of the page's runs here: the page is a
32
+ * document of its own, which inherits none of this (a framed URL's document never does).
33
33
  */
34
- export declare function nestedShellCsp(script: string, origin: string, hostOrigins: readonly string[]): string;
34
+ export declare function nestedShellCsp(script: string, origin: string, hostOrigins: readonly string[], framedBy?: readonly string[]): string;
35
35
  /**
36
36
  * The answer at the address the host frames, for a nested page (P111): Porthole's shell, never
37
37
  * stored (it carries the page's sealed address), its page at `options.page`.
@@ -42,7 +42,8 @@ export declare function nestedShellResponse(compiled: CompiledConfig, options: F
42
42
  }): Response;
43
43
  /**
44
44
  * Who may frame a nested page and its files' answers: its shell (the shell's own origin, P114) and,
45
- * above it, the host origins (`frame-ancestors` names every ancestor).
45
+ * above it, the host origins and a host's `framedBy` (`frame-ancestors` names every ancestor; P141):
46
+ * `frameAncestors` is the server's whole list.
46
47
  */
47
48
  export declare const nestedAncestors: (origin: string, frameAncestors: string) => string;
48
49
  /**
@@ -2,6 +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
6
  import { base32 } from "./keys.js";
6
7
  export { isNestedLabel, PORTHOLE_LABEL_PREFIX } from "../isolation/served.js";
7
8
  /**
@@ -33,10 +34,10 @@ const base64 = (bytes) => btoa(String.fromCharCode(...bytes));
33
34
  /**
34
35
  * The shell's CSP (a header): its own script alone runs (by its hash), it frames and fetches
35
36
  * nothing but its origin's sealed files (the page, the renewal), and only the host origins frame
36
- * it. Nothing of the page's runs here: the page is a document of its own, which inherits none of
37
- * this (a framed URL's document never does).
37
+ * it (with, above them, a host's `framedBy`, P141). Nothing of the page's runs here: the page is a
38
+ * document of its own, which inherits none of this (a framed URL's document never does).
38
39
  */
39
- export function nestedShellCsp(script, origin, hostOrigins) {
40
+ export function nestedShellCsp(script, origin, hostOrigins, framedBy = []) {
40
41
  const files = `${origin}${NESTED_FILES_PREFIX}`;
41
42
  const directives = [
42
43
  ["default-src", "'none'"],
@@ -45,7 +46,7 @@ export function nestedShellCsp(script, origin, hostOrigins) {
45
46
  ["connect-src", files],
46
47
  ["base-uri", "'none'"],
47
48
  ["form-action", "'none'"],
48
- ["frame-ancestors", ...hostOrigins],
49
+ ["frame-ancestors", ...ancestorsOf(hostOrigins, framedBy).split(" ")],
49
50
  ];
50
51
  return serializeCsp(directives);
51
52
  }
@@ -65,7 +66,7 @@ export function nestedShellResponse(compiled, options) {
65
66
  const script = frameShellScript(options);
66
67
  const headers = new Headers({
67
68
  "content-type": "text/html; charset=utf-8",
68
- "content-security-policy": nestedShellCsp(script, options.origin, options.origins),
69
+ "content-security-policy": nestedShellCsp(script, options.origin, options.origins, options.framedBy),
69
70
  "cache-control": "no-store",
70
71
  "referrer-policy": "no-referrer",
71
72
  "x-content-type-options": "nosniff",
@@ -83,7 +84,8 @@ export function nestedShellResponse(compiled, options) {
83
84
  }
84
85
  /**
85
86
  * Who may frame a nested page and its files' answers: its shell (the shell's own origin, P114) and,
86
- * above it, the host origins (`frame-ancestors` names every ancestor).
87
+ * above it, the host origins and a host's `framedBy` (`frame-ancestors` names every ancestor; P141):
88
+ * `frameAncestors` is the server's whole list.
87
89
  */
88
90
  export const nestedAncestors = (origin, frameAncestors) => `${origin} ${frameAncestors}`;
89
91
  /**
@@ -1,4 +1,9 @@
1
1
  import type { FrameBlock } from "../host/types.ts";
2
+ /**
3
+ * Who may frame a page: the host origins, then a host's `framedBy` (P141), each checked (they go
4
+ * into a header).
5
+ */
6
+ export declare function ancestorsOf(hostOrigins: readonly string[], framedBy?: readonly string[]): string;
2
7
  /** Where the pages' scripts are served, on every content origin. */
3
8
  export declare const STATUS_SCRIPT_PATH = "/__porthole/status.js";
4
9
  export declare const ENTER_SCRIPT_PATH = "/__porthole/enter.js";
@@ -29,7 +34,12 @@ export declare function statusPageOf(options: {
29
34
  readonly detail: string;
30
35
  readonly reason?: FrameBlock;
31
36
  readonly hostOrigins: readonly string[];
32
- /** Who may frame it (`frame-ancestors`): default, the host origins. */
37
+ /**
38
+ * Origins of an outer page that may be an ancestor above a host origin's page (P141): added to its
39
+ * `frame-ancestors` after the host origins, never told anything. Default none.
40
+ */
41
+ readonly framedBy?: readonly string[];
42
+ /** Who may frame it (`frame-ancestors`): default, the host origins, then `framedBy`. */
33
43
  readonly frameAncestors?: string;
34
44
  readonly link?: {
35
45
  readonly href: string;
@@ -37,9 +47,13 @@ export declare function statusPageOf(options: {
37
47
  };
38
48
  readonly method?: string;
39
49
  }): Response;
40
- /** What a door is given: the host origins it tells, and who may frame it (default, those). */
50
+ /**
51
+ * What a door is given: the host origins it tells, and who may frame it (default, those and then
52
+ * `framedBy`, P141: an outer page's origins above a host origin's page, never told anything).
53
+ */
41
54
  export interface DoorOptions {
42
55
  readonly hostOrigins: readonly string[];
56
+ readonly framedBy?: readonly string[];
43
57
  readonly frameAncestors?: string;
44
58
  readonly method?: string;
45
59
  }
@@ -1,13 +1,42 @@
1
1
  import { DOOR_SANDBOX_TOKENS } from "../compile/policy.js";
2
+ import { framedByProblem } from "../isolation/served.js";
2
3
  import { FRAME_STATUS_METHOD } from "../isolation/types.js";
3
4
  import { base64url, sha256, utf8 } from "./crypto.js";
4
5
  /**
5
6
  * The server's own pages on a content origin: why it shows nothing of the content, and the page a
6
- * framed app is entered through. Plain, framable only by the host origins, never cached. Each tells
7
- * the page that frames it how loading went (`porthole/notifications/frame-status`, P040), posted to
8
- * the host origins only, so a host can show its own fallback ("Open in a new tab"). Their words are
9
- * the host-agnostic mechanism's; a host that wants its own wording serves its own page in front.
7
+ * framed app is entered through. Plain, framable only by the host origins (and, above them, a
8
+ * host's `framedBy`, P141), never cached. Each tells the page that frames it how loading went
9
+ * (`porthole/notifications/frame-status`, P040), posted to the host origins only, so a host can show
10
+ * its own fallback ("Open in a new tab"). Their words are the host-agnostic mechanism's; a host that
11
+ * wants its own wording serves its own page in front.
10
12
  */
13
+ /**
14
+ * Whether a page's `frame-ancestors` holds its parent to its host origins: it names no one else.
15
+ * Where it does (a host's `framedBy`, P141), its parent may be an outer page, and the page says
16
+ * `*` only to a parent the engine names as a host origin (`strictParent`, below).
17
+ */
18
+ const heldToHosts = (frameAncestors, hostOrigins) => frameAncestors
19
+ .split(" ")
20
+ .filter((each) => each !== "")
21
+ .every((each) => hostOrigins.includes(each));
22
+ /** The attribute that says so, on a page's `<main>`: none where its parent is held to its hosts. */
23
+ const strictParent = (frameAncestors, hostOrigins) => heldToHosts(frameAncestors, hostOrigins) ? "" : ' data-porthole-strict-parent=""';
24
+ /**
25
+ * Who may frame a page: the host origins, then a host's `framedBy` (P141), each checked (they go
26
+ * into a header).
27
+ */
28
+ export function ancestorsOf(hostOrigins, framedBy = []) {
29
+ for (const origin of framedBy) {
30
+ const problem = framedByProblem(origin);
31
+ if (problem !== null) {
32
+ throw new TypeError(`framedBy: ${problem}`);
33
+ }
34
+ if (hostOrigins.includes(origin)) {
35
+ throw new TypeError(`framedBy: ${origin} is a host origin already`);
36
+ }
37
+ }
38
+ return [...hostOrigins, ...framedBy.filter((each, at) => framedBy.indexOf(each) === at)].join(" ");
39
+ }
11
40
  const escape = (text) => text.replace(/[&<>"']/gu, (char) => `&#${char.charCodeAt(0)};`);
12
41
  const STYLE = ":root{color-scheme:light dark;font-family:system-ui,sans-serif}body{margin:0;min-height:100vh;display:grid;place-items:center;background:Canvas;color:CanvasText}main{max-width:420px;padding:24px}h1{font-size:17px;margin:0 0 8px}p{margin:0;opacity:.75;line-height:1.5}";
13
42
  /** Where the pages' scripts are served, on every content origin. */
@@ -19,16 +48,20 @@ export const SESSION_PATH = "/__porthole/session";
19
48
  * Tells the page that frames this one how loading went, at each web host origin. A desktop app's
20
49
  * own scheme (`ferry://app`) is no target origin a browser takes (postMessage throws), so where
21
50
  * the host origins hold one, and the parent isn't known to be a web host origin, the word goes to
22
- * the parent as `*`: these pages' `frame-ancestors` already hold their parent to the host origins,
23
- * and what they say is no secret (P070). One origin failing never stops the page.
51
+ * the parent as `*`: these pages' `frame-ancestors` hold their parent to the host origins, and what
52
+ * they say is no secret (P070). Where it names an outer page too (`framedBy`, P141), the parent may be
53
+ * the outer page: then `*` goes only to a parent the engine names (`location.ancestorOrigins`,
54
+ * not masked as "null") as one of the host origins, so an outer page is never told. One origin
55
+ * failing never stops the page.
24
56
  */
25
- const say = () => `const say = (params) => {
57
+ const say = () => `const strict = main.dataset.portholeStrictParent !== undefined;
58
+ const say = (params) => {
26
59
  if (window.parent === window) return;
27
60
  const message = { jsonrpc: "2.0", method: ${JSON.stringify(FRAME_STATUS_METHOD)}, params };
28
61
  const web = hosts.filter((origin) => origin.startsWith("https://") || origin.startsWith("http://"));
29
62
  for (const origin of web) { try { window.parent.postMessage(message, origin); } catch (_) {} }
30
63
  const parent = location.ancestorOrigins && location.ancestorOrigins.length > 0 ? location.ancestorOrigins[0] : null;
31
- if (web.length < hosts.length && (parent === null || !web.includes(parent))) { try { window.parent.postMessage(message, "*"); } catch (_) {} }
64
+ if (web.length < hosts.length && (parent === null || !web.includes(parent)) && (!strict || (parent !== null && hosts.includes(parent)))) { try { window.parent.postMessage(message, "*"); } catch (_) {} }
32
65
  };`;
33
66
  /** Tells the host the page is blocked, and why (from the page's data attributes). */
34
67
  const STATUS_SCRIPT = `(() => {
@@ -97,7 +130,7 @@ const pageHeaders = (frameAncestors, connect) => ({
97
130
  "x-robots-tag": "noindex, nofollow",
98
131
  });
99
132
  export function statusPage(status, title, detail, frameAncestors, method = "GET", reason = "error", hostOrigins = [], code) {
100
- 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>`;
133
+ 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>`;
101
134
  return new Response(method === "HEAD" ? null : body, {
102
135
  status,
103
136
  headers: pageHeaders(frameAncestors, false),
@@ -105,7 +138,7 @@ export function statusPage(status, title, detail, frameAncestors, method = "GET"
105
138
  }
106
139
  /** The page a framed app is entered through (its answer also sets the session cookie). */
107
140
  export function enterPage(target, frameAncestors, hostOrigins, cookie) {
108
- 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>`;
141
+ 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>`;
109
142
  const headers = new Headers(pageHeaders(frameAncestors, true));
110
143
  headers.set("set-cookie", cookie);
111
144
  return new Response(body, { status: 200, headers });
@@ -129,7 +162,7 @@ export function appStatusPage(status, title, detail, frameAncestors, reason, hos
129
162
  const more = link === undefined
130
163
  ? ""
131
164
  : `<p><a href="${escape(link.href)}" target="_top" rel="noopener">${escape(link.text)}</a></p>`;
132
- 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>`;
165
+ 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>`;
133
166
  return new Response(method === "HEAD" ? null : body, {
134
167
  status,
135
168
  headers: {
@@ -148,7 +181,7 @@ export function appStatusPage(status, title, detail, frameAncestors, reason, hos
148
181
  * its one script inline under its hash, so it works on any origin.
149
182
  */
150
183
  export function statusPageOf(options) {
151
- return appStatusPage(options.status, options.title, options.detail, options.frameAncestors ?? options.hostOrigins.join(" "), options.reason ?? "error", options.hostOrigins, options.link, options.method);
184
+ return appStatusPage(options.status, options.title, options.detail, options.frameAncestors ?? ancestorsOf(options.hostOrigins, options.framedBy), options.reason ?? "error", options.hostOrigins, options.link, options.method);
152
185
  }
153
186
  /** A door's word that its display may be framed (P125), from the page's data attributes. */
154
187
  const DOOR_SCRIPT = `(() => {
@@ -182,10 +215,11 @@ const doorHeaders = (script, frameAncestors) => new Headers({
182
215
  */
183
216
  export function doorResponse(options) {
184
217
  const hosts = escape(JSON.stringify(options.hostOrigins));
185
- 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>`;
218
+ const ancestors = options.frameAncestors ?? ancestorsOf(options.hostOrigins, options.framedBy);
219
+ 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>`;
186
220
  return new Response(options.method?.toUpperCase() === "HEAD" ? null : body, {
187
221
  status: 200,
188
- headers: doorHeaders(hashOfDoor(), options.frameAncestors ?? options.hostOrigins.join(" ")),
222
+ headers: doorHeaders(hashOfDoor(), ancestors),
189
223
  });
190
224
  }
191
225
  /**
@@ -197,10 +231,11 @@ export function doorResponse(options) {
197
231
  export function doorStatusResponse(options) {
198
232
  const { status, reason, code } = options;
199
233
  const hosts = escape(JSON.stringify(options.hostOrigins));
200
- 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>`;
234
+ const ancestors = options.frameAncestors ?? ancestorsOf(options.hostOrigins, options.framedBy);
235
+ 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>`;
201
236
  return new Response(options.method?.toUpperCase() === "HEAD" ? null : body, {
202
237
  status,
203
- headers: doorHeaders(hashOfStatus(), options.frameAncestors ?? options.hostOrigins.join(" ")),
238
+ headers: doorHeaders(hashOfStatus(), ancestors),
204
239
  });
205
240
  }
206
241
  /**
@@ -1,5 +1,5 @@
1
1
  import { compile } from "../compile/compile.js";
2
- import { hostOriginProblem, maybeSameSite, originMatchesSource, parseOrigin, } from "../isolation/served.js";
2
+ import { framedByProblem, hostOriginProblem, maybeSameSite, originMatchesSource, parseOrigin, } from "../isolation/served.js";
3
3
  import { DOOR_PATH, } from "../isolation/types.js";
4
4
  import { sandboxProxyDocument } from "../mcp/proxy.js";
5
5
  import { base32, createKeys, newTicket, ticketId } from "./keys.js";
@@ -318,7 +318,30 @@ export function createServer(options) {
318
318
  throw new TypeError(`hostOrigins: ${origin} may be the same site as the content domain ${domain}: serve content from a registrable domain the host uses for nothing else`);
319
319
  }
320
320
  }
321
- const frameAncestors = options.hostOrigins.join(" ");
321
+ // An outer page's origins (P141): ancestors above a host origin's page, in `frame-ancestors` alone.
322
+ const framedBy = [];
323
+ for (const origin of options.framedBy ?? []) {
324
+ const problem = framedByProblem(origin);
325
+ if (problem !== null) {
326
+ throw new TypeError(`framedBy: ${problem}`);
327
+ }
328
+ if (options.hostOrigins.includes(origin)) {
329
+ throw new TypeError(`framedBy: ${origin} is a host origin already: framedBy names an ancestor that never talks to a frame`);
330
+ }
331
+ const parsed = parseOrigin(origin);
332
+ if (parsed === null ||
333
+ parsed.host === domain ||
334
+ parsed.host.endsWith(`.${domain}`) ||
335
+ maybeSameSite(parsed.host, sampleHost)) {
336
+ throw new TypeError(`framedBy: ${origin} may be the same site as the content domain ${domain}: serve content from a registrable domain the host uses for nothing else`);
337
+ }
338
+ if (!framedBy.includes(origin)) {
339
+ framedBy.push(origin);
340
+ }
341
+ }
342
+ // Who may be an ancestor of a frame served here: the host origins, then the outer pages' (P141).
343
+ // Every frame's `frame-ancestors` is this; whom a frame hears and tells is `hostOrigins` alone.
344
+ const frameAncestors = [...options.hostOrigins, ...framedBy].join(" ");
322
345
  let authorizeUrl = null;
323
346
  if (options.entry !== undefined) {
324
347
  try {
@@ -1019,6 +1042,7 @@ export function createServer(options) {
1019
1042
  const shell = nestedShellResponse(served.compiled, {
1020
1043
  origin: access.origin,
1021
1044
  origins: options.hostOrigins,
1045
+ framedBy,
1022
1046
  page: `${access.origin}${sealed.base}${rest}`,
1023
1047
  renew: { url: `${access.origin}${sealed.base}__porthole/renew`, expires: sealed.expires },
1024
1048
  method,
@@ -258,6 +258,14 @@ export interface ServerOptions {
258
258
  readonly secret: Uint8Array;
259
259
  /** The host origins that may embed content (`frame-ancestors`) and talk to a served shell. */
260
260
  readonly hostOrigins: readonly string[];
261
+ /**
262
+ * Further origins that may be an ancestor of every frame served here, above a host origin's
263
+ * page (P141): an outer page that frames the host's app. Added to each `frame-ancestors` after
264
+ * the host origins, and nowhere else: never an origin a shell, a door or a page takes a message
265
+ * from or says anything to, never a host origin for `entry` or the handoff. Exact https origins
266
+ * (`http://` on loopback), none a host origin, none the content domain's site. Default none.
267
+ */
268
+ readonly framedBy?: readonly string[];
261
269
  /**
262
270
  * The configs a served shell or page is served under, by the name a `ServedDocument` gives
263
271
  * (an artifact defaults to `artifact`, the MCP Apps sandbox proxy to `mcpApp`).
@@ -61,9 +61,11 @@ export declare const WORD_LATE: string;
61
61
  * - the last line (P133): where a selection or a mark's words end, in the document's coordinates
62
62
  * too (`lastLineDocumentRect`), so a host places its UI after them;
63
63
  * - the selection followed (P138): what the last `selected` reported (the element picked, or the
64
- * words selected) is kept, and while the host follows it (`track` with `selection`) it is drawn
65
- * in the layer and its boxes are reported as a followed mark's are (`selectionTracked`), with
66
- * whether it is in view, or that it is gone; it takes no pointer, no focus and no key.
64
+ * words selected) is kept while the host follows the selection (`track` with `selection`) or said
65
+ * at `start` that it will (`keepSelection`, P140), and nothing is kept otherwise; while followed
66
+ * it is drawn in the layer and its boxes are reported as a followed mark's are
67
+ * (`selectionTracked`), with whether it is in view, or that it is gone; it takes no pointer, no
68
+ * focus and no key.
67
69
  *
68
70
  * It shares the realm with the content, which can interfere with all of it: the host takes its
69
71
  * reports as UI hints only.