@botiverse/porthole 0.14.4 → 0.14.6

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 (78) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/dist/check/page-source.js +1 -1
  3. package/dist/check/page.js +5 -1
  4. package/dist/compile/policy.d.ts +6 -0
  5. package/dist/compile/policy.js +6 -0
  6. package/dist/conformance/entry.d.ts +25 -6
  7. package/dist/conformance/entry.js +69 -18
  8. package/dist/conformance/harness/page.d.ts +12 -0
  9. package/dist/conformance/harness/page.js +95 -51
  10. package/dist/conformance/harness-source.js +1 -1
  11. package/dist/conformance/host-kit.js +39 -13
  12. package/dist/conformance/served.js +140 -0
  13. package/dist/files/paths.d.ts +2 -2
  14. package/dist/files/paths.js +12 -2
  15. package/dist/host/client.d.ts +8 -0
  16. package/dist/host/client.js +47 -17
  17. package/dist/host/create-host.d.ts +10 -0
  18. package/dist/host/create-host.js +126 -10
  19. package/dist/host/door.d.ts +41 -0
  20. package/dist/host/door.js +55 -0
  21. package/dist/host/locate.js +2 -0
  22. package/dist/host/locator.d.ts +55 -3
  23. package/dist/host/locator.js +152 -42
  24. package/dist/host/outcome.d.ts +58 -1
  25. package/dist/host/outcome.js +74 -6
  26. package/dist/host/types.d.ts +20 -4
  27. package/dist/isolation/served.d.ts +1 -1
  28. package/dist/isolation/served.js +35 -0
  29. package/dist/isolation/types.d.ts +20 -2
  30. package/dist/isolation/types.js +2 -0
  31. package/dist/platform/types.d.ts +22 -0
  32. package/dist/platform/web.js +55 -12
  33. package/dist/react/frame.d.ts +2 -1
  34. package/dist/react/view.d.ts +13 -0
  35. package/dist/react/view.js +101 -2
  36. package/dist/server/files.d.ts +11 -0
  37. package/dist/server/files.js +26 -4
  38. package/dist/server/host.js +106 -28
  39. package/dist/server/index.d.ts +2 -1
  40. package/dist/server/index.js +6 -1
  41. package/dist/server/pages.d.ts +32 -0
  42. package/dist/server/pages.js +82 -6
  43. package/dist/server/server.js +140 -11
  44. package/dist/server/types.d.ts +15 -1
  45. package/dist/transport/post-message.d.ts +1 -9
  46. package/dist/transport/post-message.js +2 -8
  47. package/docs/ADOPTING.md +58 -0
  48. package/docs/DECISIONS.md +290 -0
  49. package/docs/DESIGN.md +24 -16
  50. package/docs/THREAT_MODEL.md +98 -3
  51. package/package.json +1 -1
  52. package/src/check/page.ts +6 -1
  53. package/src/compile/policy.ts +7 -0
  54. package/src/conformance/entry.ts +129 -24
  55. package/src/conformance/harness/page.ts +112 -49
  56. package/src/conformance/host-kit.ts +53 -16
  57. package/src/conformance/served.ts +175 -0
  58. package/src/files/paths.ts +11 -2
  59. package/src/host/client.ts +59 -22
  60. package/src/host/create-host.ts +146 -18
  61. package/src/host/door.ts +97 -0
  62. package/src/host/locate.ts +2 -0
  63. package/src/host/locator.ts +208 -57
  64. package/src/host/outcome.ts +88 -7
  65. package/src/host/types.ts +20 -4
  66. package/src/isolation/served.ts +40 -1
  67. package/src/isolation/types.ts +19 -2
  68. package/src/platform/types.ts +21 -0
  69. package/src/platform/web.ts +55 -20
  70. package/src/react/frame.tsx +2 -1
  71. package/src/react/view.tsx +149 -2
  72. package/src/server/files.ts +37 -5
  73. package/src/server/host.ts +131 -46
  74. package/src/server/index.ts +6 -1
  75. package/src/server/pages.ts +101 -6
  76. package/src/server/server.ts +186 -19
  77. package/src/server/types.ts +16 -1
  78. package/src/transport/post-message.ts +1 -9
@@ -1,4 +1,5 @@
1
1
  import type { Limits, PortholeConfig } from "../config/schema.ts";
2
+ import { isPagePath } from "./types.ts";
2
3
 
3
4
  /**
4
5
  * A version made of files (P081): the rules a published path follows, the limits a version is
@@ -124,8 +125,8 @@ const sizeOf = (bytes: number): string =>
124
125
  /**
125
126
  * Checks a version's files before it is published (P081): every path by `filePathProblem`; no
126
127
  * two paths that differ only in case, and no path that is both a file and a directory; the
127
- * entry is one of them; the count, each size and the total within the limits (a config's, see
128
- * `fileLimits`). Empty when it may be published.
128
+ * entry is one of them, and a page (`.html` or `.htm`, P125); the count, each size and the total
129
+ * within the limits (a config's, see `fileLimits`). Empty when it may be published.
129
130
  */
130
131
  export function checkFileSet(
131
132
  files: Readonly<Record<string, FileSetEntryLike>>,
@@ -200,6 +201,14 @@ export function checkFileSet(
200
201
  code: "entry",
201
202
  message: `No ${JSON.stringify(entry)}: the page the version opens at is one of its files`,
202
203
  });
204
+ } else if (!isPagePath(entry)) {
205
+ // A version opens at a page (P125, P124-2): any other file is served inert, says nothing, and
206
+ // would show only Porthole's fallback.
207
+ problems.push({
208
+ path: entry,
209
+ code: "entry",
210
+ message: `${JSON.stringify(entry)} isn't a page: the version opens at an .html (or .htm) file of its own`,
211
+ });
203
212
  }
204
213
  return problems;
205
214
  }
@@ -1,7 +1,7 @@
1
1
  import type { PortholeConfig } from "../config/schema.ts";
2
2
  import type { Displays } from "../displays/displays.ts";
3
3
  import type { FrameLocation, InstanceLocator, InstanceRef } from "../isolation/types.ts";
4
- import { LocateError } from "./locator.ts";
4
+ import { LocateError, locationOf, outcomeOfRefusal, refusalOf, type Resolved } from "./locator.ts";
5
5
  import type { FrameOutcome } from "./types.ts";
6
6
 
7
7
  /**
@@ -65,6 +65,13 @@ export interface PortholeClient<N extends string = string> extends InstanceLocat
65
65
  config(this: void, kind: N): PortholeConfig | null;
66
66
  /** The same, for an instance's kind. */
67
67
  configFor(this: void, instance: InstanceRef): PortholeConfig | null;
68
+ /**
69
+ * What a clean address names, for this viewer (P125): its instance and an issued location (a
70
+ * door, a ticket) for the caller's own first frame (`oneShot(location, locator)`), or the outcome
71
+ * the frame endpoint answered instead (signed out, denied, not found), with no frame built. A
72
+ * clean address is for a tab: never frame one directly (`checkFrameLocation` refuses it).
73
+ */
74
+ resolve(this: void, address: string, signal?: AbortSignal): Promise<Resolved>;
68
75
  /** An instance's clean address (`entry.pathOf` on the server), or null. */
69
76
  link(this: void, instance: InstanceRef): Promise<string | null>;
70
77
  /** The clean address if already known (from locating the instance), for rendering. */
@@ -199,7 +206,7 @@ export function portholeClient<N extends string>(
199
206
  }
200
207
  };
201
208
 
202
- const issue = async (instance: InstanceRef, signal?: AbortSignal): Promise<FrameLocation> => {
209
+ const askFrames = async (body: Record<string, unknown>, signal?: AbortSignal) => {
203
210
  const headers = headersNow();
204
211
  headers.set("content-type", "application/json");
205
212
  headers.set("accept", "application/json");
@@ -208,37 +215,66 @@ export function portholeClient<N extends string>(
208
215
  headers,
209
216
  credentials,
210
217
  redirect: "error",
211
- body: JSON.stringify({ instance }),
218
+ body: JSON.stringify(body),
212
219
  ...(signal === undefined ? {} : { signal }),
213
220
  });
214
221
  const data: unknown = await answer.json().catch(() => null);
215
222
  if (!answer.ok) {
216
- const error = isRecord(data) && isRecord(data.error) ? data.error : {};
217
- const code = typeof error.code === "string" ? error.code : "failed";
218
- if (code === "not-served") {
223
+ const refused = refusalOf(answer, data);
224
+ if (refused.code === "not-served") {
219
225
  void refresh();
220
226
  }
221
- throw new LocateError(
222
- typeof error.message === "string"
223
- ? error.message
224
- : `The app's frame endpoint answered ${answer.status}`,
225
- answer.status,
226
- code,
227
- );
227
+ throw refused;
228
+ }
229
+ return { status: answer.status, data };
230
+ };
231
+
232
+ /** A location as the frame endpoint gave it: its door (P125) passed on, as it came. */
233
+ const located = (status: number, data: unknown): FrameLocation => {
234
+ const { viewer: _viewer, ...location } = locationOf(status, data);
235
+ return location;
236
+ };
237
+
238
+ const issue = async (instance: InstanceRef, signal?: AbortSignal): Promise<FrameLocation> => {
239
+ const key = keyOf(instance);
240
+ const { status, data } = await askFrames({ instance }, signal);
241
+ const location = located(status, data);
242
+ links.set(key, isRecord(data) && typeof data.link === "string" ? data.link : null);
243
+ return location;
244
+ };
245
+
246
+ const resolve = async (address: string, signal?: AbortSignal): Promise<Resolved> => {
247
+ let answer: { readonly status: number; readonly data: unknown };
248
+ try {
249
+ answer = await askFrames({ address }, signal);
250
+ } catch (error) {
251
+ // Signed out, denied, not found: the host's own answer, before any frame (P125).
252
+ const outcome = outcomeOfRefusal(error);
253
+ if (outcome !== null) {
254
+ return { outcome };
255
+ }
256
+ throw error;
228
257
  }
229
- if (!isRecord(data) || typeof data.url !== "string" || typeof data.origin !== "string") {
258
+ const { status, data } = answer;
259
+ const instance = isRecord(data) ? data.instance : undefined;
260
+ if (
261
+ !isRecord(instance) ||
262
+ typeof instance.scope !== "string" ||
263
+ !isRecord(instance.document) ||
264
+ typeof instance.document.kind !== "string"
265
+ ) {
230
266
  throw new LocateError(
231
- "The app's frame endpoint gave no location",
232
- answer.status,
267
+ "The app's frame endpoint resolved the address to no instance",
268
+ status,
233
269
  "bad-location",
234
270
  );
235
271
  }
236
- links.set(keyOf(instance), typeof data.link === "string" ? data.link : null);
237
- return {
238
- url: data.url,
239
- origin: data.origin,
240
- ...(typeof data.reports === "boolean" ? { reports: data.reports } : {}),
241
- };
272
+ const found = instance as unknown as InstanceRef;
273
+ const location = located(status, data);
274
+ // The location is the caller's, for its own first frame only (`oneShot`): never kept here,
275
+ // where another view of the same instance could take it.
276
+ links.set(keyOf(found), isRecord(data) && typeof data.link === "string" ? data.link : null);
277
+ return { instance: found, location };
242
278
  };
243
279
 
244
280
  let lastHandoff = 0;
@@ -297,6 +333,7 @@ export function portholeClient<N extends string>(
297
333
  config: (kind) => configOf(kind),
298
334
  configFor: (instance) => configOf(options.displays.kindOf(instance)),
299
335
  locate: issue,
336
+ resolve,
300
337
  link,
301
338
  knownLink: (instance) => links.get(keyOf(instance)) ?? null,
302
339
  openInTab: (instance) => {
@@ -28,10 +28,12 @@ import type { ColorScheme, PortholeConfig } from "../config/schema.ts";
28
28
  import { locateServed } from "./locate.ts";
29
29
  import { mayPassOn } from "./pass-on.ts";
30
30
  import { watchOutcome, type OutcomeWatch } from "./outcome.ts";
31
+ import { watchDoor, type DoorWatch } from "./door.ts";
32
+ import { outcomeOfRefusal } from "./locator.ts";
31
33
  import { STORAGE_USED_METHOD, type FrameSource } from "../isolation/types.ts";
32
34
  import { webPlatform } from "../platform/web.ts";
33
35
  import { TAKES } from "../platform/focus-guard.ts";
34
- import type { Surface } from "../platform/types.ts";
36
+ import type { DoorSurface, Surface } from "../platform/types.ts";
35
37
  import type { AdapterConnection, ProtocolAdapter, ShellConnection } from "../protocol/adapter.ts";
36
38
  import {
37
39
  MCP_APPS_STYLE_VARIABLES,
@@ -58,6 +60,22 @@ const DEFAULT_LOAD_TIMEOUT_MS = 15_000;
58
60
  /** How many times a display is started again after its content navigated its frame away. */
59
61
  const MAX_RESTARTS = 3;
60
62
 
63
+ /** What the host is told of a served display located without its door (P125), once a mount. */
64
+ export const NO_DOOR =
65
+ "A served display needs a door from issue (FrameLocation.door, P125), and this location has none, so no frame was made: upgrade the server (or content Worker) that issues it, and pass the door on from a locator of your own. A clean address is for a tab: to frame what it names, resolve it with client.resolve(address) or <PortholeView address>";
66
+
67
+ /**
68
+ * What the host is told when its locator gives a run the location an earlier run had (P125): its
69
+ * tickets were taken by that run, so its door says `blocked: session`. A locator issues anew for
70
+ * every run (a reload, a restart after the content navigated away).
71
+ */
72
+ export const REUSED_LOCATION =
73
+ "The locator gave this run a location an earlier run of this display already used (P125): its tickets are taken, so its door answers that the link has been used. A locator must issue anew for every run (InstanceLocator.locate is called for each one)";
74
+
75
+ /** What the host is told when its platform makes no doors (P125): no served frame is made. */
76
+ export const NO_DOOR_PLATFORM =
77
+ "This platform makes no door frames (PlatformHost.createDoor, P125), so no served display that isn't nested is framed on it";
78
+
61
79
  const BASE_KEYS = new Set(["hostContextChanged", "teardown", "close"]);
62
80
 
63
81
  /** The frame's annotation reports, by method. */
@@ -94,6 +112,10 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
94
112
  }
95
113
  // A url frame is someone else's app: no shell, no protocol, and its navigations are its own.
96
114
  const speaks = config.mode !== "url";
115
+ const nested = config.nested === true;
116
+ // A served display on its scope's origin, beside the scope's other content (P125): its door
117
+ // says how loading went, before its frame is made.
118
+ const hasDoor = config.isolation === "domain" && speaks && !nested;
97
119
  const adapter = (options.adapter ?? shellAdapter) as ProtocolAdapter<C>;
98
120
  const platform = options.platform ?? webPlatform;
99
121
  const hostInfo = options.hostInfo ?? { name: "porthole", version: "0" };
@@ -148,6 +170,11 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
148
170
 
149
171
  const listeners = new Map<keyof DisplayEvents, Set<(detail: never) => void>>();
150
172
  const emit = <E extends keyof DisplayEvents>(event: E, detail: DisplayEvents[E]) => {
173
+ // An outcome ends a loading episode: the next run (a restart, a reload) gets a clock of
174
+ // its own (P125).
175
+ if (event === "outcome") {
176
+ episodeBegan = null;
177
+ }
151
178
  for (const listener of listeners.get(event) ?? []) {
152
179
  (listener as (detail: DisplayEvents[E]) => void)(detail);
153
180
  }
@@ -172,6 +199,10 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
172
199
  let bridge: DisplayBridge | null = null;
173
200
  let destroyed = false;
174
201
  let restarts = 0;
202
+ // When the loading episode that has no outcome yet began: its first run, not each restart's
203
+ // (P125). However often a frame is started again (a sibling of its scope wiping or
204
+ // navigating it, P125 S7), the display's time runs out and it has an outcome.
205
+ let episodeBegan: number | null = null;
175
206
  let generation = 0;
176
207
  // The viewer's answer for this display (P079): asked once, kept across its frames; or the
177
208
  // host's refusal of them all (P080).
@@ -181,6 +212,10 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
181
212
  : onceConsent(options.consent);
182
213
  let abort: AbortController | null = null;
183
214
  let outcomeWatch: OutcomeWatch | null = null;
215
+ let door: { readonly frame: DoorSurface; readonly watch: DoorWatch } | null = null;
216
+ // The addresses earlier runs were located at (P125): a ticket opens once, so a run given one
217
+ // again is told to the host (its outcome is the server's word, unchanged).
218
+ const locatedAt = new Set<string>();
184
219
  let themeFrame: number | null = null;
185
220
  const view = container.ownerDocument.defaultView;
186
221
  // The adapter's own operations, the last call of each, replayed into every new frame.
@@ -492,6 +527,12 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
492
527
  }
493
528
  };
494
529
 
530
+ const closeDoor = () => {
531
+ door?.watch.stop();
532
+ door?.frame.destroy();
533
+ door = null;
534
+ };
535
+
495
536
  const stop = () => {
496
537
  // A run that ran a page with storage of its own making and never heard it used: no (P111).
497
538
  if (bridge !== null && handshaken && !storageTold && compiled.shell?.storage === "memory") {
@@ -507,13 +548,51 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
507
548
  abort = null;
508
549
  outcomeWatch?.stop();
509
550
  outcomeWatch = null;
551
+ closeDoor();
510
552
  connection?.close();
511
553
  connection = null;
512
554
  surface?.destroy();
513
555
  surface = null;
514
556
  };
515
557
 
516
- const start = (source: FrameSource) => {
558
+ const timeoutMs = config.limits.loadTimeoutMs ?? DEFAULT_LOAD_TIMEOUT_MS;
559
+
560
+ /**
561
+ * A served display with a door (P125): its door first, alone, in a frame of the host's own;
562
+ * its frame only once the door said `open`, within what is left of the run's time. A door
563
+ * that said `blocked` (or never ran, or never answered) is the run's outcome, and nothing of
564
+ * the content is framed. A location without a door (an older server, a locator that drops
565
+ * it, a clean address someone framed) is refused before any frame is made: `blocked:
566
+ * locate`, and the host hears why (`door`). Nothing infers a door's word from anything else.
567
+ */
568
+ const enter = (source: FrameSource, timeLeft = timeoutMs) => {
569
+ if (!hasDoor || source.kind !== "url") {
570
+ start(source, timeLeft);
571
+ return;
572
+ }
573
+ if (source.door === undefined || platform.createDoor === undefined) {
574
+ hostError(source.door === undefined ? NO_DOOR : NO_DOOR_PLATFORM, "door");
575
+ emit("outcome", { state: "blocked", reason: "locate" });
576
+ return;
577
+ }
578
+ const began = Date.now();
579
+ const frame = platform.createDoor(container, { url: source.door });
580
+ const watch = watchDoor({
581
+ door: frame,
582
+ timeoutMs: timeLeft,
583
+ onOpen: () => {
584
+ closeDoor();
585
+ start(source, Math.max(0, timeLeft - (Date.now() - began)));
586
+ },
587
+ onOutcome: (outcome) => {
588
+ closeDoor();
589
+ emit("outcome", outcome);
590
+ },
591
+ });
592
+ door = { frame, watch };
593
+ };
594
+
595
+ const start = (source: FrameSource, timeLeft: number) => {
517
596
  const navigatedAway = () => {
518
597
  emit("navigated", undefined);
519
598
  if (restarts < MAX_RESTARTS) {
@@ -522,6 +601,9 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
522
601
  } else {
523
602
  stop();
524
603
  contentError("The content kept navigating its frame away; it was stopped.");
604
+ // Every display ends with an outcome (P125): a frame stopped after its restarts ran out
605
+ // is one the host can draw a fallback for, never an empty box.
606
+ emit("outcome", { state: "blocked", reason: "error" });
525
607
  }
526
608
  };
527
609
  const framed = platform.createSurface(container, {
@@ -587,8 +669,11 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
587
669
  surface: created,
588
670
  source,
589
671
  speaks,
590
- timeoutMs: config.limits.loadTimeoutMs ?? DEFAULT_LOAD_TIMEOUT_MS,
672
+ nested,
673
+ timeoutMs: timeLeft,
591
674
  onOutcome: (outcome) => emit("outcome", outcome),
675
+ // A frame status from the content (P124): never shown, the host's to hear.
676
+ refused: (message) => hostError(message, "frame-status"),
592
677
  });
593
678
  outcomeWatch = watch;
594
679
  if (!speaks) {
@@ -677,16 +762,24 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
677
762
  return;
678
763
  }
679
764
  generation += 1;
765
+ if (episodeBegan === null) {
766
+ episodeBegan = Date.now();
767
+ }
768
+ // What is left of this episode's time: a restart doesn't start the clock again.
769
+ const timeLeft = Math.max(0, timeoutMs - (Date.now() - episodeBegan));
680
770
  if (config.isolation === "opaque") {
681
- start({
682
- kind: "srcdoc",
683
- html: compiled.shellDocument({
684
- origins: [container.ownerDocument.defaultView?.location.origin ?? ""],
685
- title: mount.title,
686
- ...nonceOf(options.nonce),
687
- ...(mount.document === undefined ? {} : { document: mount.document }),
688
- }),
689
- });
771
+ enter(
772
+ {
773
+ kind: "srcdoc",
774
+ html: compiled.shellDocument({
775
+ origins: [container.ownerDocument.defaultView?.location.origin ?? ""],
776
+ title: mount.title,
777
+ ...nonceOf(options.nonce),
778
+ ...(mount.document === undefined ? {} : { document: mount.document }),
779
+ }),
780
+ },
781
+ timeLeft,
782
+ );
690
783
  return;
691
784
  }
692
785
  const mine = generation;
@@ -698,18 +791,52 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
698
791
  return;
699
792
  }
700
793
  const hostOrigin = container.ownerDocument.defaultView?.location.origin ?? "";
794
+ // The run's time covers locating too: a backend that never answers is a timeout.
795
+ const began = Date.now();
796
+ let settled = false;
797
+ const late = setTimeout(() => {
798
+ if (!settled && mine === generation && !destroyed) {
799
+ settled = true;
800
+ controller.abort();
801
+ hostError("The host's backend didn't give a location in time", "locate");
802
+ emit("outcome", { state: "timeout" });
803
+ }
804
+ }, timeLeft);
805
+ // A run stopped (destroyed, started again) stops its clock too.
806
+ controller.signal.addEventListener("abort", () => clearTimeout(late), { once: true });
701
807
  locateServed(locator, instance, config, hostOrigin, controller.signal).then(
702
808
  (source) => {
703
- if (mine === generation && !destroyed) {
704
- start(source);
809
+ clearTimeout(late);
810
+ if (!settled && mine === generation && !destroyed) {
811
+ settled = true;
812
+ if (source.kind === "url") {
813
+ const seen = [source.url, ...(source.door === undefined ? [] : [source.door])];
814
+ if (seen.some((each) => locatedAt.has(each))) {
815
+ hostError(REUSED_LOCATION, "locate");
816
+ }
817
+ for (const each of seen) {
818
+ locatedAt.add(each);
819
+ }
820
+ }
821
+ enter(source, Math.max(0, timeLeft - (Date.now() - began)));
705
822
  }
706
823
  },
707
824
  (error: unknown) => {
708
- if (mine === generation && !controller.signal.aborted) {
709
- // The host's own failure (its backend down, access gone): never the content's.
710
- hostError(error instanceof Error ? error.message : String(error), "locate");
711
- emit("outcome", { state: "blocked", reason: "locate" });
825
+ clearTimeout(late);
826
+ if (settled || mine !== generation || controller.signal.aborted) {
827
+ return;
828
+ }
829
+ settled = true;
830
+ // The host's own issue endpoint refused (signed out, denied, not found, P125): its
831
+ // word, before any frame, never the content's. Anything else is the host's own failure
832
+ // (its backend down, a network error, a malformed answer): `locate`, never `denied`.
833
+ const refused = outcomeOfRefusal(error);
834
+ if (refused !== null) {
835
+ emit("outcome", refused);
836
+ return;
712
837
  }
838
+ hostError(error instanceof Error ? error.message : String(error), "locate");
839
+ emit("outcome", { state: "blocked", reason: "locate" });
713
840
  },
714
841
  );
715
842
  };
@@ -752,6 +879,7 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
752
879
  },
753
880
  reload() {
754
881
  restarts = 0;
882
+ episodeBegan = null;
755
883
  run();
756
884
  },
757
885
  focus() {
@@ -0,0 +1,97 @@
1
+ import type { DoorSurface } from "../platform/types.ts";
2
+ import { parseFrameStatus, SETTLE_MS } from "./outcome.ts";
3
+ import type { FrameOutcome } from "./types.ts";
4
+
5
+ /**
6
+ * A served display's door (P125). A served display that isn't nested (a served shell, a page, a
7
+ * view through the sandbox proxy) is framed on its scope's origin, where the scope's other displays
8
+ * run content with `allow-same-origin`: one of them reaches a new document there before its first
9
+ * script runs, so nothing its frame says, and nothing its silence suggests, is Porthole's word.
10
+ *
11
+ * So before its frame is made, the host frames its door: a page of Porthole's server on the same
12
+ * origin, in a frame of the host's own, hidden, sandboxed with scripts alone (an opaque origin, a
13
+ * new one each time, which no content is the same origin as), with no name (nothing targets it).
14
+ * The server takes the door's own ticket and runs the checks the content's address runs for the
15
+ * same grant (the host's check, the document, its entry), and the door says how loading went, once:
16
+ * `open` (frame the display), or `blocked` and why. The host takes that word only from the door
17
+ * frame's window, from an opaque origin (`"null"`), the first well-formed frame status it says; a
18
+ * door that loaded and said nothing never ran (`framing`: its server didn't let this page frame
19
+ * it). The door's frame is gone once it said, before the display's frame is made.
20
+ *
21
+ * "A `load` event is not a committed document" (DECISIONS P125): a document wiped and navigated
22
+ * while it parses never fires `load`, so no host may read a frame's first load as its first
23
+ * document. The door's "load, then `SETTLE_MS` of silence: framing" doesn't rest on that: no content
24
+ * ever runs in the door (its one script is Porthole's, by its hash, under `default-src 'none'`),
25
+ * so nothing navigates it from inside; and a sibling of its scope, which does get its `WindowProxy`
26
+ * while it loads, can't reach in: reading it throws (it is opaque), setting or replacing its
27
+ * `location` throws (the sibling's own sandbox navigates no frame not its own), and it has no
28
+ * name, so `window.open` and a link's or a form's `target` find nothing. The host hears it from
29
+ * `"null"` alone. `[door-reach]` and the `door-opaque` control hold that.
30
+ */
31
+
32
+ export interface DoorWatch {
33
+ stop(): void;
34
+ }
35
+
36
+ export function watchDoor(options: {
37
+ readonly door: DoorSurface;
38
+ readonly timeoutMs: number;
39
+ /** The door said `open`: the display may be framed. */
40
+ readonly onOpen: () => void;
41
+ /** The door said `blocked`, or loaded and said nothing (`framing`), or nothing came in time. */
42
+ readonly onOutcome: (outcome: Exclude<FrameOutcome, { state: "loaded" }>) => void;
43
+ }): DoorWatch {
44
+ const { door } = options;
45
+ let decided = false;
46
+ const timers = new Set<ReturnType<typeof setTimeout>>();
47
+ const later = (ms: number, run: () => void) => {
48
+ const timer = setTimeout(() => {
49
+ timers.delete(timer);
50
+ run();
51
+ }, ms);
52
+ timers.add(timer);
53
+ };
54
+ const stop = () => {
55
+ decided = true;
56
+ for (const timer of timers) {
57
+ clearTimeout(timer);
58
+ }
59
+ timers.clear();
60
+ unlisten();
61
+ unload();
62
+ };
63
+ const unlisten = door.transport.listen((data) => {
64
+ if (decided) {
65
+ return;
66
+ }
67
+ const status = parseFrameStatus(data);
68
+ // A door says `open` or `blocked`, nothing else: anything else is no door's word.
69
+ if (status?.state === "open") {
70
+ stop();
71
+ options.onOpen();
72
+ } else if (status?.state === "blocked") {
73
+ stop();
74
+ options.onOutcome({
75
+ state: "blocked",
76
+ reason: status.reason ?? "error",
77
+ ...(status.status === undefined ? {} : { status: status.status }),
78
+ ...(status.code === undefined ? {} : { code: status.code }),
79
+ });
80
+ }
81
+ });
82
+ const unload = door.onLoad(() =>
83
+ later(SETTLE_MS, () => {
84
+ if (!decided) {
85
+ stop();
86
+ options.onOutcome({ state: "blocked", reason: "framing" });
87
+ }
88
+ }),
89
+ );
90
+ later(options.timeoutMs, () => {
91
+ if (!decided) {
92
+ stop();
93
+ options.onOutcome({ state: "timeout" });
94
+ }
95
+ });
96
+ return { stop };
97
+ }
@@ -31,5 +31,7 @@ export async function locateServed(
31
31
  origin: location.origin,
32
32
  ...(location.reports === true ? { reports: true } : {}),
33
33
  ...(viewer === null ? {} : { viewer }),
34
+ // Its door (P125), checked with the location: the host frames it before `url`.
35
+ ...(location.door === undefined ? {} : { door: new URL(location.door.url).href }),
34
36
  };
35
37
  }