@botiverse/porthole 0.14.16 → 0.14.18

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.
@@ -24,7 +24,9 @@ export interface FileSetRef {
24
24
  * A notice (`porthole/navigating`, from the frame's window and content origin: the transport
25
25
  * takes nothing else) names a page and the version its files are. The leaving page's notice is
26
26
  * taken for the next load within `PAGE_OF_SET_MS`; the arriving page's (`arrived`) too, or for the
27
- * load it came after. A load no notice explained waits `LATE_NOTICE_MS`, holding the frame
27
+ * load it came after. A page whose document stayed (`same`, a navigation within it: WebKit fires
28
+ * the frame's load for one, P142) is taken for the load it came after, or for the next one within
29
+ * `LATE_NOTICE_MS` only. A load no notice explained waits `LATE_NOTICE_MS`, holding the frame
28
30
  * (`HELD_MOST` messages each way at most; past them, started again): nothing it says reaches the
29
31
  * display (no call is answered, no report taken), nothing is sent to it, and once the wait is
30
32
  * over without a notice for the
@@ -21,6 +21,7 @@ function noticeOf(raw, mounted) {
21
21
  return {
22
22
  url: typeof params.url === "string" ? params.url : "",
23
23
  arrived: params.arrived === true,
24
+ same: params.same === true,
24
25
  set: named === undefined
25
26
  ? "none"
26
27
  : isRecord(named) && named.id === mounted.id && named.version === mounted.version
@@ -37,7 +38,9 @@ const isHello = (raw) => isRecord(raw) && raw.method === MCP_APPS_METHODS.initia
37
38
  * A notice (`porthole/navigating`, from the frame's window and content origin: the transport
38
39
  * takes nothing else) names a page and the version its files are. The leaving page's notice is
39
40
  * taken for the next load within `PAGE_OF_SET_MS`; the arriving page's (`arrived`) too, or for the
40
- * load it came after. A load no notice explained waits `LATE_NOTICE_MS`, holding the frame
41
+ * load it came after. A page whose document stayed (`same`, a navigation within it: WebKit fires
42
+ * the frame's load for one, P142) is taken for the load it came after, or for the next one within
43
+ * `LATE_NOTICE_MS` only. A load no notice explained waits `LATE_NOTICE_MS`, holding the frame
41
44
  * (`HELD_MOST` messages each way at most; past them, started again): nothing it says reaches the
42
45
  * display (no call is answered, no report taken), nothing is sent to it, and once the wait is
43
46
  * over without a notice for the
@@ -105,15 +108,17 @@ export function pagesOfSet(options) {
105
108
  }
106
109
  const notice = noticeOf(message, set);
107
110
  if (notice !== null) {
108
- if (notice.set === "other" || (notice.arrived && notice.set !== "ok")) {
111
+ if (notice.set === "other" || ((notice.arrived || notice.same) && notice.set !== "ok")) {
109
112
  // Another version's page, or one that won't say which: never this display's.
110
113
  if (waiting > 0) {
111
114
  leave();
112
115
  }
113
116
  return;
114
117
  }
115
- if (waiting === 0 && notice.url === current) {
118
+ if (waiting === 0 && notice.url === current && !notice.same) {
116
119
  // A late copy for the page the frame is on (its leaving page's, or its own): no new page.
120
+ // (A document that stayed says so for each navigation within it, the same address again
121
+ // too: each may come with a load.)
117
122
  return;
118
123
  }
119
124
  if (waiting > 0) {
@@ -121,6 +126,15 @@ export function pagesOfSet(options) {
121
126
  taken(notice.url);
122
127
  }
123
128
  }
129
+ else if (notice.same) {
130
+ // A document that stayed is no page to come: its word is for a load at hand (WebKit fires
131
+ // it with the navigation within the document, before or after the frame's word, P142),
132
+ // and never shortens a page's word already given.
133
+ if (grantUntil <= Date.now()) {
134
+ grantUntil = Date.now() + LATE_NOTICE_MS;
135
+ grantFor = notice.url;
136
+ }
137
+ }
124
138
  else {
125
139
  // Either page's notice, for the next load within P084's ten seconds: the host hears the
126
140
  // frame's load only once its images and modules have loaded, which can be seconds after
@@ -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
@@ -79,9 +79,11 @@ export declare const NAVIGATION_BLOCKED_METHOD = "porthole/navigation-blocked";
79
79
  /**
80
80
  * Porthole's own notification from the shell (P084): a page that came with files is opening
81
81
  * another page of its set, `{ url }`, in the frame; and, as it arrives, the page a navigation
82
- * opened says so, `{ url, arrived: true }` (P098). The host takes the frame's next load (or the
83
- * load it came after, within `LATE_NOTICE_MS`) for that page rather than for content that left
84
- * (P031). The content's word: it only spares a restart.
82
+ * opened says so, `{ url, arrived: true }` (P098), with or without the Navigation API (P142); and a
83
+ * navigation within a page's document, `{ url, same: true }` (P142: WebKit fires the frame's load
84
+ * for one). The host takes the frame's next load (or the load it came after, within
85
+ * `LATE_NOTICE_MS`) for that page rather than for content that left (P031). The content's word: it
86
+ * only spares a restart.
85
87
  */
86
88
  export declare const NAVIGATING_METHOD = "porthole/navigating";
87
89
  /** The logger name the shell's error reports (`notifications/message`, level `error`) carry. */
@@ -126,9 +126,11 @@ export const NAVIGATION_BLOCKED_METHOD = "porthole/navigation-blocked";
126
126
  /**
127
127
  * Porthole's own notification from the shell (P084): a page that came with files is opening
128
128
  * another page of its set, `{ url }`, in the frame; and, as it arrives, the page a navigation
129
- * opened says so, `{ url, arrived: true }` (P098). The host takes the frame's next load (or the
130
- * load it came after, within `LATE_NOTICE_MS`) for that page rather than for content that left
131
- * (P031). The content's word: it only spares a restart.
129
+ * opened says so, `{ url, arrived: true }` (P098), with or without the Navigation API (P142); and a
130
+ * navigation within a page's document, `{ url, same: true }` (P142: WebKit fires the frame's load
131
+ * for one). The host takes the frame's next load (or the load it came after, within
132
+ * `LATE_NOTICE_MS`) for that page rather than for content that left (P031). The content's word: it
133
+ * only spares a restart.
132
134
  */
133
135
  export const NAVIGATING_METHOD = "porthole/navigating";
134
136
  /** The logger name the shell's error reports (`notifications/message`, level `error`) carry. */
@@ -249,6 +249,11 @@ export const shellAdapter = {
249
249
  calls.unwatch(params);
250
250
  return;
251
251
  case NAVIGATING_METHOD:
252
+ // A navigation within the page's document (P142): the page, its calls and what it
253
+ // follows stay.
254
+ if (params.same === true) {
255
+ return;
256
+ }
252
257
  // Another page of the set opens in the frame (P084): its next load is that page, which
253
258
  // follows nothing yet.
254
259
  forget();
@@ -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`).
@@ -37,6 +37,12 @@ export { SHELL_METHOD_PREFIX, SHELL_STATE_METHOD } from "../isolation/types.ts";
37
37
  export interface FrameShellOptions {
38
38
  /** The host origins: the shell takes messages from its parent only from these. */
39
39
  readonly origins: readonly string[];
40
+ /**
41
+ * Origins of an outer page that may be an ancestor above a host origin's page (P141): in the
42
+ * shell's `frame-ancestors` after `origins` (`nestedShellResponse`), never heard or told. Where
43
+ * there are any, the shell says `*` only to a parent the engine names as a host origin.
44
+ */
45
+ readonly framedBy?: readonly string[];
40
46
  /** The page's address: absolute, on the shell's own origin, under `/__porthole/f/`. */
41
47
  readonly page: string;
42
48
  /** The page frame's accessible name. */
@@ -1,5 +1,5 @@
1
1
  import { PAGE_SANDBOX_TOKENS } from "../compile/policy.js";
2
- import { hostOriginProblem, onNestedLabel } from "../isolation/served.js";
2
+ import { framedByProblem, hostOriginProblem, onNestedLabel } from "../isolation/served.js";
3
3
  /**
4
4
  * Porthole's shell for a nested page (P111): the whole document at the address the host frames,
5
5
  * with no content in it. It frames the page (the same origin's sealed files' address) in a child
@@ -80,7 +80,9 @@ export const FRAME_SHELL_RUNTIME = String.raw `(() => {
80
80
  const web = plan.origins.filter((origin) => origin.indexOf("https://") === 0 || origin.indexOf("http://") === 0);
81
81
  // To the host: each web host origin (only the parent's is delivered); a desktop app's own scheme
82
82
  // is no target a browser takes, so where one is listed and the parent isn't a known web origin,
83
- // "*" (frame-ancestors holds the parent to the host origins; nothing said here is secret).
83
+ // "*" (frame-ancestors holds the parent to the host origins; nothing said here is secret). Where
84
+ // it names an outer page above them too (the host's framedBy, P141: plan.strictParent), the parent
85
+ // may be the outer page: "*" then goes only to a parent the engine names as a host origin.
84
86
  const toHost = (message) => {
85
87
  if (!framed) {
86
88
  return;
@@ -91,7 +93,11 @@ export const FRAME_SHELL_RUNTIME = String.raw `(() => {
91
93
  } catch (_) {}
92
94
  }
93
95
  const parent = location.ancestorOrigins && location.ancestorOrigins.length > 0 ? location.ancestorOrigins[0] : null;
94
- if (web.length < plan.origins.length && (parent === null || web.indexOf(parent) === -1)) {
96
+ if (
97
+ web.length < plan.origins.length &&
98
+ (parent === null || web.indexOf(parent) === -1) &&
99
+ (plan.strictParent !== true || (parent !== null && plan.origins.indexOf(parent) !== -1))
100
+ ) {
95
101
  try {
96
102
  window.parent.postMessage(message, "*");
97
103
  } catch (_) {}
@@ -271,6 +277,12 @@ export function frameShellScript(options) {
271
277
  throw new TypeError(`frameShellScript: ${problem}`);
272
278
  }
273
279
  }
280
+ for (const origin of options.framedBy ?? []) {
281
+ const problem = framedByProblem(origin);
282
+ if (problem !== null || options.origins.includes(origin)) {
283
+ throw new TypeError(`frameShellScript: framedBy: ${problem ?? `${origin} is a host origin`}`);
284
+ }
285
+ }
274
286
  let page;
275
287
  try {
276
288
  page = new URL(options.page);
@@ -287,6 +299,7 @@ export function frameShellScript(options) {
287
299
  }
288
300
  return FRAME_SHELL_RUNTIME.replace("__PLAN__", () => scriptJson({
289
301
  origins: options.origins,
302
+ ...((options.framedBy ?? []).length === 0 ? {} : { strictParent: true }),
290
303
  page: page.href,
291
304
  sandbox: PAGE_SANDBOX_TOKENS.join(" "),
292
305
  ...(options.title === undefined ? {} : { title: options.title }),