@mostra/runtime 0.6.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,16 +1,26 @@
1
1
  /**
2
- * The gateway (ARCHITECTURE §5, §10; D38, D96 to D99): the HTTP side of an instance. It serves
3
- * the shell on the shell's leased port and each opened artifact on its own leased port, all on one
4
- * host, so the shell and every artifact are same-site but different origins. Only capability
5
- * holders get in: a link's token becomes a shell session, the shell hands the artifact's frame a
6
- * single-use ticket, and the frame's session lets it load its version's files. Every request goes
7
- * through the same checks (`routes.ts`), and published versions are served straight from disk,
8
- * with no process (RT-05). It also serves `view/url`, `view/rotate` and `view/revoke`.
2
+ * The gateway (ARCHITECTURE §5, §10; D38, D96 to D99, D158): the HTTP side of an instance. It
3
+ * serves the shell on the shell's leased port and each opened artifact on its own leased port, all
4
+ * on one host, so the shell and every artifact are same-site but different origins. Only
5
+ * capability holders get in: a link's token becomes a shell session, the shell hands the
6
+ * artifact's frame a single-use ticket, and the frame's session lets it load its version's files.
7
+ * Every request goes through the same checks (`routes.ts`), and published versions are served
8
+ * straight from disk, with no process (RT-05). It also serves `view/url`, `view/rotate` and
9
+ * `view/revoke`.
10
+ *
11
+ * Beside those loopback listeners, the gateway has **faces** (D158 item 1): external addresses of
12
+ * the shell or one artifact (a tailnet, Funnel or Cloudflare address a share set up, or a host's
13
+ * external base), each its own listener on loopback with one origin and one exact `Host`. Which
14
+ * face a request came through is the socket it arrived on, so a tunnel's visitor can't claim
15
+ * another address. A face pairs with the faces of its group (a share's, a host's): its shell opens
16
+ * frames on the group's artifact face, in cookie mode when both are one site and in worker mode
17
+ * (D70) when they are two.
9
18
  *
10
19
  * ```ts
11
20
  * const gateway = createGateway({ ledger, log, addressing, capabilities, artifacts, shellDir });
12
21
  * await gateway.start();
13
22
  * const { url } = await gateway.defaultLink(artifactId); // the publish receipt's URL
23
+ * const face = await gateway.openFace({ by: "cloudflare", group, listener: "shell", … });
14
24
  * ```
15
25
  */
16
26
  import { existsSync, readFileSync } from "node:fs";
@@ -29,11 +39,17 @@ import {
29
39
  createDiagnostic,
30
40
  type Diagnostic,
31
41
  durationMs,
42
+ EnterRequest,
43
+ type FaceStatus,
44
+ FRAME_SESSION_HEADER,
45
+ type FrameSessionFacts,
32
46
  type FrameTicket,
33
47
  type IdentityVia,
48
+ type PortAddressingExternalBaseResult,
34
49
  type Refusal,
35
50
  RpcError,
36
51
  refusal,
52
+ StreamTicketRequest,
37
53
  safePath,
38
54
  scopeAllows,
39
55
  viewDefaultMethod,
@@ -43,7 +59,7 @@ import {
43
59
  viewUrlMethod,
44
60
  } from "@mostra/protocol";
45
61
  import type { Actions } from "../actions/index.ts";
46
- import type { Addressing } from "../addressing/index.ts";
62
+ import { type Addressing, type FrameMode, hostOf } from "../addressing/index.ts";
47
63
  import { runtimeRoot } from "../deps/index.ts";
48
64
  import type { EphemeralBus, Interaction } from "../interaction/index.ts";
49
65
  import {
@@ -77,11 +93,12 @@ import {
77
93
  refusalResponse,
78
94
  sessionCookie,
79
95
  } from "./http.ts";
80
- import type { IdentityOutcome } from "./identity.ts";
96
+ import { type IdentityOutcome, tailnetPerson } from "./identity.ts";
81
97
  import { versionIntegrity } from "./integrity.ts";
82
98
  import { createListener, type Listener } from "./listener.ts";
83
99
  import { type ListenerChecks, mount, type RouteContext, type RouteSpec, refuse } from "./routes.ts";
84
100
  import { fileResponse, findFile } from "./serve.ts";
101
+ import { BOOTSTRAP_PAGE, SERVICE_WORKER_PATH, SERVICE_WORKER_SOURCE } from "./worker.ts";
85
102
 
86
103
  export { Capabilities, capabilityKey } from "./capabilities.ts";
87
104
  export { CONTROLS_POLICY_TIMEOUT_MS, controlsPolicy } from "./controls.ts";
@@ -98,6 +115,56 @@ export interface GatewayArtifacts {
98
115
  damage(versionId: string): Promise<string | undefined>;
99
116
  }
100
117
 
118
+ /** Who keeps a face (D158 item 1): a share's tunnel, or a host's addressing port. */
119
+ export type FaceBy = "tailnet" | "funnel" | "cloudflare" | "host";
120
+
121
+ /** What a share asks the gateway to open: one external address of the shell or an artifact. */
122
+ export interface FaceSpec {
123
+ readonly by: FaceBy;
124
+ /**
125
+ * The faces that pair: a shell face opens frames on the artifact faces of its group (`tailnet`,
126
+ * `funnel`, a Cloudflare share's own, a host's per artifact).
127
+ */
128
+ readonly group: string;
129
+ readonly listener: "shell" | "artifact";
130
+ /** The artifact, for an artifact's face. */
131
+ readonly artifactId?: string;
132
+ /** How requests through it reach the gateway, as the identity port hears it (D143 item 2). */
133
+ readonly via: IdentityVia;
134
+ /** Keep a leased loopback port, so the face's address survives restarts. */
135
+ readonly lease: boolean;
136
+ /** Whether event streams pass; `false` behind a Cloudflare quick tunnel. Default `true`. */
137
+ readonly streams?: boolean;
138
+ /** An artifact face's frame mode, when its keeper knows it; else decided by the pair (D70). */
139
+ readonly mode?: FrameMode;
140
+ }
141
+
142
+ /** An open face. */
143
+ export interface FaceHandle {
144
+ /** Its key: `<group>:shell` or `<group>:<artifactId>`. */
145
+ readonly key: string;
146
+ /** The loopback port the tunnel forwards to. */
147
+ readonly port: number;
148
+ /** `http://127.0.0.1:<port>`. */
149
+ readonly local: string;
150
+ /** The origin browsers use; until it is set, the face refuses every request (421). */
151
+ origin(): string | undefined;
152
+ /** Sets the origin once the tunnel knows its address; `undefined` closes the address again. */
153
+ setOrigin(origin: string | undefined): void;
154
+ }
155
+
156
+ /** The answer a host's addressing port gave, or why there is none. */
157
+ export type ExternalBaseAnswer =
158
+ | {
159
+ readonly kind: "base";
160
+ readonly base: NonNullable<PortAddressingExternalBaseResult>;
161
+ /** The host that gave it, by its client name. */
162
+ readonly owner: string;
163
+ }
164
+ | { readonly kind: "none" }
165
+ | { readonly kind: "failed" }
166
+ | { readonly kind: "away" };
167
+
101
168
  /** Options for {@link createGateway}. */
102
169
  export interface GatewayOptions {
103
170
  readonly ledger: Ledger;
@@ -125,6 +192,19 @@ export interface GatewayOptions {
125
192
  readonly via: IdentityVia;
126
193
  readonly headers: Headers;
127
194
  }) => Promise<IdentityOutcome>;
195
+ /**
196
+ * Asks the host that registered the `addressing` port for a listener's external origin (HO-10,
197
+ * D158 item 6). Absent: no host addresses, links stay on loopback.
198
+ */
199
+ readonly externalBase?: {
200
+ /** Whether a connected host registered the port now: none asks nothing and opens no face. */
201
+ readonly registered: () => boolean;
202
+ readonly ask: (input: {
203
+ readonly artifactId: string;
204
+ readonly listener: "shell" | "artifact";
205
+ readonly local: string;
206
+ }) => Promise<ExternalBaseAnswer>;
207
+ };
128
208
  /**
129
209
  * Logs every connection and request of every listener (`MOSTRA_TEST_REQUEST_LOG`, #66): tests
130
210
  * only, so a request a browser saw go unanswered shows whether it reached the gateway.
@@ -159,17 +239,46 @@ export interface GatewayOptions {
159
239
 
160
240
  /** The gateway of one instance. */
161
241
  export interface Gateway {
162
- /** Binds the shell's port and every leased artifact port (D99). */
242
+ /** Binds the shell's port, recently viewed artifacts' ports and the hosts' kept faces (D99). */
163
243
  start(): Promise<void>;
164
- /** The shell's origin. */
244
+ /** The loopback shell's origin. */
165
245
  readonly shellOrigin: () => string;
166
- /** The artifact's default link (D97 item 3), shown again or minted: the publish receipt's URL. */
167
- defaultLink(artifactId: string): { readonly url: string; readonly tokenId: string };
246
+ /**
247
+ * The artifact's default link (D97 item 3), shown again or minted: the publish receipt's URL. A
248
+ * host's external base (D158 item 6), when it gives one, is the link's address.
249
+ */
250
+ defaultLink(artifactId: string): Promise<{ readonly url: string; readonly tokenId: string }>;
168
251
  /**
169
252
  * Mints a link with every scope, for a version only when `version` names its number (D97
170
253
  * item 9): what `view/url` mints, for callers inside the instance (a verify run's sandbox).
171
254
  */
172
255
  link(input: { readonly artifactId: string; readonly version?: number }): string;
256
+ /**
257
+ * Mints a link at a face's shell address (a share's, D158 item 3), in the caller's transaction
258
+ * when it passes one.
259
+ */
260
+ mintAt(
261
+ input: {
262
+ readonly artifactId: string;
263
+ readonly shellOrigin: string;
264
+ readonly scopes?: readonly CapabilityScope[] | undefined;
265
+ readonly ttlMs?: number | undefined;
266
+ readonly viewerId?: string | undefined;
267
+ },
268
+ within?: LedgerDb,
269
+ ): CapabilityLink;
270
+ /** A link minted before, shown again from its derived secret; `undefined` once it can't be. */
271
+ reveal(tokenId: string): string | undefined;
272
+ /** Opens a face (D158 item 1): its listener on loopback, refusing everything until its origin is set. */
273
+ openFace(spec: FaceSpec): Promise<FaceHandle>;
274
+ /** The face with this key, if it is open. */
275
+ face(key: string): FaceHandle | undefined;
276
+ /** Closes a face's listener; its leased port is released when `release` is set. */
277
+ closeFace(key: string, release?: boolean): Promise<void>;
278
+ /** The open faces, for `instance/status`. */
279
+ faces(): readonly FaceStatus[];
280
+ /** Whether a shell is served at this origin now: launch tickets are minted only for those. */
281
+ servesShell(origin: string): boolean;
173
282
  /** The handlers of `view/url`, `view/rotate` and `view/revoke`. */
174
283
  methods(): MethodHandler[];
175
284
  /** The origins of the artifact listeners that are bound, by artifact ID. */
@@ -186,17 +295,56 @@ const NO_STORE = { "cache-control": "no-store" };
186
295
  /** How recently an artifact must have been viewed for its port to be bound at start (D129). */
187
296
  const RECENT_VIEW_MS = 7 * 24 * 60 * 60 * 1000;
188
297
 
298
+ /** How long a host's answer for an artifact's frame address is reused (D158 item 6). */
299
+ const EXTERNAL_BASE_REUSE_MS = 30_000;
300
+
301
+ /**
302
+ * How long a withdrawn face's listener stays open, refusing everything, so the request that
303
+ * learned of the withdrawal still gets its answer (D158 item 6).
304
+ */
305
+ const FACE_LINGER_MS = 2_000;
306
+
307
+ /** The key of a face: `<group>:shell`, or `<group>:<artifactId>` for an artifact's. */
308
+ export function faceKey(
309
+ group: string,
310
+ listener: "shell" | "artifact",
311
+ artifactId?: string,
312
+ ): string {
313
+ return `${group}:${listener === "shell" ? "shell" : (artifactId ?? "")}`;
314
+ }
315
+
316
+ /**
317
+ * One way into the gateway, for the routes it serves: the loopback shell or an artifact's
318
+ * listener, or a face. Everything a route needs to know about where a request came in.
319
+ */
320
+ interface Way {
321
+ readonly listener: "shell" | "artifact";
322
+ /** `loopback` for the gateway's own listeners. */
323
+ readonly by: FaceBy | "loopback";
324
+ readonly via: IdentityVia;
325
+ readonly artifactId: string | undefined;
326
+ port(): number;
327
+ /** The origin browsers use; `undefined` while a face waits for its tunnel. */
328
+ origin(): string | undefined;
329
+ /** The exact `Host` values accepted. */
330
+ hosts(): readonly string[];
331
+ streams(): boolean;
332
+ }
333
+
189
334
  /**
190
335
  * The browser-protocol routes of INTERFACES §4 (D96): WP-06 serves `fields`, `submit`, `signal`,
191
- * `events` and `events/poll`; the others answer 501 until their package attaches a handler.
336
+ * `events` and `events/poll`; WP-08 the calls, runs and live sources; WP-13 the stream tickets.
192
337
  */
193
- function laterArtifactRoutes(served: BrowserRoutes, acting: ActionRoutes | undefined): RouteSpec[] {
338
+ function laterArtifactRoutes(
339
+ served: BrowserRoutes,
340
+ acting: ActionRoutes | undefined,
341
+ ticket: (context: RouteContext) => Promise<Response>,
342
+ ): RouteSpec[] {
194
343
  const action = (params: Readonly<Record<string, string>>): CapabilityScope | "any-action" => {
195
344
  const id = params["fn"];
196
345
  return id ? (`action:${id}` as CapabilityScope) : "any-action";
197
346
  };
198
347
  return [
199
- { method: "GET", path: "/_mostra/sw.js", intent: "read", auth: "none" },
200
348
  {
201
349
  method: "POST",
202
350
  path: "/_mostra/v/:rev/fields",
@@ -263,12 +411,20 @@ function laterArtifactRoutes(served: BrowserRoutes, acting: ActionRoutes | undef
263
411
  auth: "session",
264
412
  ...(acting ? { handler: acting.live } : {}),
265
413
  },
266
- { method: "POST", path: "/_mostra/v/:rev/ticket", intent: "mutation", auth: "session" },
414
+ // WP-13: single-use tickets for streams, polls and WebSockets that bypass the worker (D70).
415
+ {
416
+ method: "POST",
417
+ path: "/_mostra/v/:rev/ticket",
418
+ intent: "mutation",
419
+ auth: "session",
420
+ handler: ticket,
421
+ },
267
422
  {
268
423
  method: "GET",
269
424
  path: "/_mostra/v/:rev/events",
270
425
  intent: "stream",
271
426
  auth: "session",
427
+ sse: true,
272
428
  handler: served.stream,
273
429
  },
274
430
  {
@@ -281,6 +437,15 @@ function laterArtifactRoutes(served: BrowserRoutes, acting: ActionRoutes | undef
281
437
  ];
282
438
  }
283
439
 
440
+ /** A face as the gateway keeps it. */
441
+ interface FaceEntry {
442
+ readonly key: string;
443
+ readonly spec: FaceSpec;
444
+ readonly listener: Listener;
445
+ readonly port: number;
446
+ origin: string | undefined;
447
+ }
448
+
284
449
  /** Creates the gateway; nothing is bound until {@link Gateway.start}. */
285
450
  export function createGateway(options: GatewayOptions): Gateway {
286
451
  const { addressing, capabilities, artifacts, log, interaction } = options;
@@ -322,10 +487,79 @@ export function createGateway(options: GatewayOptions): Gateway {
322
487
  { readonly listener: Listener; readonly port: number }
323
488
  >();
324
489
  const opening = new Map<string, Promise<number>>();
490
+ const faces = new Map<string, FaceEntry>();
491
+ const openingFaces = new Map<string, Promise<FaceEntry>>();
492
+ /** A host's recent answers for artifacts' frame addresses, by face key (D158 item 6). */
493
+ const askedRecently = new Map<string, number>();
325
494
  const integrity = versionIntegrity(artifacts, log);
326
495
 
496
+ // ── Ways in: the loopback listeners and the faces ───────────────────────────────────────
497
+
498
+ const loopbackShell: Way = {
499
+ listener: "shell",
500
+ by: "loopback",
501
+ via: "local",
502
+ artifactId: undefined,
503
+ port: () => shellPort ?? 0,
504
+ origin: () => shellOrigin(),
505
+ hosts: () => addressing.hosts(shellPort ?? 0),
506
+ streams: () => true,
507
+ };
508
+
509
+ const loopbackArtifact = (artifactId: string, port: () => number): Way => ({
510
+ listener: "artifact",
511
+ by: "loopback",
512
+ via: "local",
513
+ artifactId,
514
+ port,
515
+ origin: () => addressing.origin(port()),
516
+ hosts: () => addressing.hosts(port()),
517
+ streams: () => true,
518
+ });
519
+
520
+ const faceWay = (entry: FaceEntry): Way => ({
521
+ listener: entry.spec.listener,
522
+ by: entry.spec.by,
523
+ via: entry.spec.via,
524
+ artifactId: entry.spec.artifactId,
525
+ port: () => entry.port,
526
+ origin: () => entry.origin,
527
+ hosts: () => (entry.origin === undefined ? [] : [hostOf(entry.origin)]),
528
+ streams: () => entry.spec.streams !== false,
529
+ });
530
+
531
+ /** The shell of a way's group: the loopback shell, or the group's shell face. */
532
+ const shellOf = (way: Way, group: string | undefined): Way | undefined => {
533
+ if (way.by === "loopback" || group === undefined) return loopbackShell;
534
+ const entry = faces.get(faceKey(group, "shell"));
535
+ return entry ? faceWay(entry) : undefined;
536
+ };
537
+
538
+ /** How an artifact way's frames authenticate: by the pair, unless its keeper said (D70). */
539
+ const modeOf = (artifact: Way, group: string | undefined): FrameMode => {
540
+ if (artifact.by === "loopback" || group === undefined) return "cookie";
541
+ const entry = faces.get(faceKey(group, "artifact", artifact.artifactId));
542
+ if (entry?.spec.mode) return entry.spec.mode;
543
+ const shell = shellOf(artifact, group)?.origin();
544
+ const own = artifact.origin();
545
+ return shell !== undefined && own !== undefined ? addressing.frameMode(shell, own) : "worker";
546
+ };
547
+
548
+ /** Whether an origin is `https:`, where every cookie is `Secure`. */
549
+ const secure = (origin: string | undefined): boolean => origin?.startsWith("https:") === true;
550
+
551
+ /** Whether the gateway serves a shell at this origin now: launch tickets go only there. */
552
+ const servesShell = (origin: string): boolean =>
553
+ origin === shellOrigin() ||
554
+ [...faces.values()].some((entry) => entry.spec.listener === "shell" && entry.origin === origin);
555
+
327
556
  /** The answer for a damaged version: a plain page for a navigation, else the diagnostic. */
328
- const damaged = (number: number | undefined, damage: string, document: boolean): Response =>
557
+ const damaged = (
558
+ number: number | undefined,
559
+ damage: string,
560
+ document: boolean,
561
+ frameAncestors: string,
562
+ ): Response =>
329
563
  refusalResponse(
330
564
  {
331
565
  status: 500,
@@ -333,11 +567,11 @@ export function createGateway(options: GatewayOptions): Gateway {
333
567
  message: `${number === undefined ? "A version" : `Version ${number}`} of this artifact is damaged: ${damage}.`,
334
568
  }),
335
569
  },
336
- { document, frameAncestors: shellOrigin() },
570
+ { document, frameAncestors },
337
571
  );
338
572
 
339
573
  const link = (token: MintedToken): CapabilityLink => ({
340
- url: `${shellOrigin()}/a/${token.artifactId}${token.pinnedVersion !== undefined ? `/v/${token.pinnedVersion}` : ""}#t=${token.secret}`,
574
+ url: `${token.shellOrigin}/a/${token.artifactId}${token.pinnedVersion !== undefined ? `/v/${token.pinnedVersion}` : ""}#t=${token.secret}`,
341
575
  tokenId: token.tokenId,
342
576
  scopes: token.scopes,
343
577
  ...(token.expiresAt !== undefined ? { expiresAt: token.expiresAt } : {}),
@@ -364,24 +598,322 @@ export function createGateway(options: GatewayOptions): Gateway {
364
598
  : undefined;
365
599
  };
366
600
 
601
+ // ── Faces (D158 item 1) ─────────────────────────────────────────────────────────────────
602
+
603
+ const openFace = (spec: FaceSpec, origin?: string): Promise<FaceEntry> => {
604
+ const key = faceKey(spec.group, spec.listener, spec.artifactId);
605
+ const open = faces.get(key);
606
+ if (open) return Promise.resolve(open);
607
+ const pending = openingFaces.get(key);
608
+ if (pending) return pending;
609
+ const started = (async () => {
610
+ let entry: FaceEntry | undefined;
611
+ const way = (): Way =>
612
+ entry
613
+ ? faceWay(entry)
614
+ : {
615
+ ...loopbackShell,
616
+ origin: () => undefined,
617
+ hosts: () => [],
618
+ };
619
+ const listener = createListener({
620
+ policy: () => ({ origin: entry?.origin ?? "", hosts: way().hosts() }),
621
+ log,
622
+ frameAncestors: () =>
623
+ spec.listener === "shell" ? "'none'" : (shellOf(way(), spec.group)?.origin() ?? "'none'"),
624
+ configure: (app) => {
625
+ if (spec.listener === "shell") mount(app, shellChecks(way), shellRoutes(way, spec.group));
626
+ else {
627
+ const artifactId = spec.artifactId as string;
628
+ mount(
629
+ app,
630
+ artifactChecks(artifactId, way, spec.group),
631
+ artifactRoutes(artifactId, way, spec.group),
632
+ );
633
+ }
634
+ },
635
+ ...(spec.listener === "artifact"
636
+ ? { upgrade: socketUpgrade(spec.artifactId as string, way, spec.group) }
637
+ : {}),
638
+ ...(options.traceRequests ? { traceRequests: true } : {}),
639
+ });
640
+ // A withdrawn face of this key may still hold its leased port for a moment.
641
+ await endLingering(key);
642
+ const port = await addressing.listenFace(listener.server, { key, lease: spec.lease });
643
+ entry = { key, spec, listener, port, origin };
644
+ faces.set(key, entry);
645
+ log.info("gateway.face_open", {
646
+ key,
647
+ by: spec.by,
648
+ local: addressing.faceLocal(port),
649
+ ...(origin !== undefined ? { origin } : {}),
650
+ });
651
+ return entry;
652
+ })().finally(() => openingFaces.delete(key));
653
+ openingFaces.set(key, started);
654
+ return started;
655
+ };
656
+
657
+ const handleOf = (entry: FaceEntry): FaceHandle => ({
658
+ key: entry.key,
659
+ port: entry.port,
660
+ local: addressing.faceLocal(entry.port),
661
+ origin: () => entry.origin,
662
+ setOrigin: (origin) => {
663
+ if (entry.origin !== origin) {
664
+ log.info("gateway.face_address", {
665
+ key: entry.key,
666
+ ...(origin !== undefined ? { origin } : {}),
667
+ });
668
+ }
669
+ entry.origin = origin;
670
+ },
671
+ });
672
+
673
+ const closeFace = async (key: string, release = false): Promise<void> => {
674
+ const pending = openingFaces.get(key);
675
+ if (pending) await pending.catch(() => undefined);
676
+ const entry = faces.get(key);
677
+ if (entry) {
678
+ faces.delete(key);
679
+ await entry.listener.close();
680
+ log.info("gateway.face_closed", { key });
681
+ }
682
+ if (release) addressing.releaseFace(key);
683
+ };
684
+
685
+ /**
686
+ * Withdrawn faces' listeners, by face key, closing after {@link FACE_LINGER_MS}; a face of the
687
+ * same key opened meanwhile, or the gateway's close, closes one at once.
688
+ */
689
+ const lingering = new Map<string, Listener>();
690
+
691
+ /** Closes a withdrawn face's listener now, if one still lingers, freeing its port. */
692
+ const endLingering = async (key: string): Promise<void> => {
693
+ const listener = lingering.get(key);
694
+ if (!listener) return;
695
+ lingering.delete(key);
696
+ await listener.close();
697
+ };
698
+
699
+ /**
700
+ * Withdraws a face at once and closes its listener a moment later: from now on its `Host` is
701
+ * served nowhere (every request is refused, 421), while the request that learned of the
702
+ * withdrawal (an exchange that asked the host) still gets its own answer, 410, rather than a
703
+ * connection closed under it.
704
+ */
705
+ const withdrawFace = (key: string): void => {
706
+ const entry = faces.get(key);
707
+ if (!entry) {
708
+ addressing.releaseFace(key);
709
+ return;
710
+ }
711
+ faces.delete(key);
712
+ entry.origin = undefined;
713
+ lingering.set(key, entry.listener);
714
+ log.info("gateway.face_withdrawn", { key });
715
+ const timer = setTimeout(() => {
716
+ if (lingering.get(key) !== entry.listener) return;
717
+ void endLingering(key).then(() => {
718
+ // Its lease goes once its port is free, unless a new face of the key holds it.
719
+ if (!faces.has(key)) addressing.releaseFace(key);
720
+ });
721
+ }, FACE_LINGER_MS);
722
+ timer.unref?.();
723
+ };
724
+
725
+ // ── A host's external bases (HO-10, D158 item 6) ────────────────────────────────────────
726
+
727
+ /** The kept external bases, so a restart serves their links before the host answers again. */
728
+ const keptBases = (): {
729
+ key: string;
730
+ listener: "shell" | "artifact";
731
+ artifact_id: string | null;
732
+ origin: string;
733
+ mode: FrameMode | null;
734
+ }[] =>
735
+ options.ledger.read((db) =>
736
+ db.all<{
737
+ key: string;
738
+ listener: "shell" | "artifact";
739
+ artifact_id: string | null;
740
+ origin: string;
741
+ mode: FrameMode | null;
742
+ }>("SELECT key, listener, artifact_id, origin, mode FROM external_base"),
743
+ );
744
+
745
+ const hostSpec = (
746
+ artifactId: string,
747
+ listener: "shell" | "artifact",
748
+ mode?: FrameMode,
749
+ ): FaceSpec => ({
750
+ by: "host",
751
+ group: `host:${artifactId}`,
752
+ listener,
753
+ artifactId,
754
+ via: "token",
755
+ lease: true,
756
+ ...(mode ? { mode } : {}),
757
+ });
758
+
759
+ /**
760
+ * The host's face of one of an artifact's listeners, asked again now: the address it gives
761
+ * (kept, so its links work after a restart), or none. `null`, or another origin, withdraws the
762
+ * face given before, whose links stop working; a host that fails or is away keeps what it gave.
763
+ */
764
+ const hostFaceTurns = new Map<string, Promise<unknown>>();
765
+ /**
766
+ * One question to the host per face at a time (Opus review of WP-13): a question that fails
767
+ * never closes a face another question just set up, and every question reads what the one
768
+ * before it left.
769
+ */
770
+ const hostFace = (
771
+ artifactId: string,
772
+ listener: "shell" | "artifact",
773
+ ): Promise<FaceEntry | undefined> => {
774
+ const key = faceKey(`host:${artifactId}`, listener, artifactId);
775
+ const before = hostFaceTurns.get(key) ?? Promise.resolve();
776
+ const turn = before.then(
777
+ () => askHostFace(artifactId, listener),
778
+ () => askHostFace(artifactId, listener),
779
+ );
780
+ const settled = turn.catch(() => undefined);
781
+ hostFaceTurns.set(key, settled);
782
+ void settled.then(() => {
783
+ if (hostFaceTurns.get(key) === settled) hostFaceTurns.delete(key);
784
+ });
785
+ return turn;
786
+ };
787
+
788
+ const askHostFace = async (
789
+ artifactId: string,
790
+ listener: "shell" | "artifact",
791
+ ): Promise<FaceEntry | undefined> => {
792
+ // Only an artifact of this home has a host's address: nothing is opened or asked for others.
793
+ try {
794
+ artifacts.get({ artifactId });
795
+ } catch {
796
+ return undefined;
797
+ }
798
+ const port = options.externalBase;
799
+ const group = `host:${artifactId}`;
800
+ const key = faceKey(group, listener, artifactId);
801
+ const kept = faces.get(key);
802
+ // Without a host to ask, a face a host gave before (kept across a restart) still serves.
803
+ if (!port?.registered()) return kept?.origin !== undefined ? kept : undefined;
804
+ if (
805
+ listener === "artifact" &&
806
+ kept &&
807
+ Date.now() - (askedRecently.get(key) ?? 0) < EXTERNAL_BASE_REUSE_MS
808
+ ) {
809
+ return kept;
810
+ }
811
+ // The face listens first, on its leased port, so the host is told where to forward.
812
+ const entry = kept ?? (await openFace(hostSpec(artifactId, listener)));
813
+ const answer = await port.ask({
814
+ artifactId,
815
+ listener,
816
+ local: addressing.faceLocal(entry.port),
817
+ });
818
+ if (answer.kind === "failed" || answer.kind === "away") {
819
+ if (kept?.origin !== undefined) return kept;
820
+ if (!kept) await closeFace(key, true);
821
+ return undefined;
822
+ }
823
+ if (answer.kind === "none") {
824
+ options.ledger.write((db) => db.run("DELETE FROM external_base WHERE key = ?", key));
825
+ if (kept?.origin !== undefined) withdrawFace(key);
826
+ else await closeFace(key, true);
827
+ return undefined;
828
+ }
829
+ const origin = answer.base.origin;
830
+ const mode = answer.base.mode;
831
+ if (entry.origin !== origin || (entry.spec.mode ?? null) !== (mode ?? null)) {
832
+ // Another origin withdraws the one before: its Host is no longer served. The same mode
833
+ // keeps the listener, whose Host and origin follow the entry at once; another mode needs a
834
+ // listener of its own, on the same leased port.
835
+ if ((entry.spec.mode ?? null) !== (mode ?? null)) await closeFace(key);
836
+ const fresh =
837
+ faces.get(key) ?? (await openFace(hostSpec(artifactId, listener, mode), origin));
838
+ fresh.origin = origin;
839
+ options.ledger.write((db) =>
840
+ db.run(
841
+ "INSERT INTO external_base (key, listener, artifact_id, origin, mode, client, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(key) DO UPDATE SET origin = excluded.origin, mode = excluded.mode, updated_at = excluded.updated_at",
842
+ key,
843
+ listener,
844
+ artifactId,
845
+ origin,
846
+ mode ?? null,
847
+ answer.owner,
848
+ new Date().toISOString(),
849
+ ),
850
+ );
851
+ askedRecently.set(key, Date.now());
852
+ return fresh;
853
+ }
854
+ askedRecently.set(key, Date.now());
855
+ return entry;
856
+ };
857
+
858
+ /** Where an artifact's links point: a host's external base when it gives one, else loopback. */
859
+ const linkBase = async (artifactId: string): Promise<string> => {
860
+ const face = await hostFace(artifactId, "shell");
861
+ return face?.origin ?? shellOrigin();
862
+ };
863
+
864
+ /** The artifact way a shell way opens frames on, or why there is none. */
865
+ const artifactWayFor = async (
866
+ shell: Way,
867
+ group: string | undefined,
868
+ artifactId: string,
869
+ ): Promise<{ readonly way: Way; readonly group: string | undefined } | Refusal> => {
870
+ if (shell.by === "loopback" || group === undefined) {
871
+ const port = await openArtifact(artifactId);
872
+ return { way: loopbackArtifact(artifactId, () => port), group: undefined };
873
+ }
874
+ if (shell.by === "host") {
875
+ const entry = await hostFace(artifactId, "artifact");
876
+ if (entry?.origin === undefined) {
877
+ return refusal(
878
+ "MOSTRA_HYGIENE_NOT_SERVED",
879
+ "The host gives this artifact's frame no address here.",
880
+ 503,
881
+ );
882
+ }
883
+ return { way: faceWay(entry), group };
884
+ }
885
+ const entry = faces.get(faceKey(group, "artifact", artifactId));
886
+ if (entry?.origin === undefined) {
887
+ return refusal("MOSTRA_HYGIENE_NOT_SERVED", "This artifact isn't shared at this address.");
888
+ }
889
+ return { way: faceWay(entry), group };
890
+ };
891
+
367
892
  // ── The shell ────────────────────────────────────────────────────────────────────────────
368
893
 
369
- const shellKind = (): ListenerKind => ({
894
+ const shellKind = (way: Way): ListenerKind => ({
370
895
  kind: "shell",
371
- origin: shellOrigin(),
372
- shellOrigin: shellOrigin(),
896
+ origin: way.origin() ?? "",
897
+ shellOrigin: way.origin() ?? "",
373
898
  });
374
- const shellChecks: ListenerChecks = {
375
- policy: () => ({ origin: shellOrigin(), hosts: addressing.hosts(shellPort ?? 0) }),
899
+ const shellChecks = (way: () => Way): ListenerChecks => ({
900
+ policy: () => ({ origin: way().origin() ?? "", hosts: way().hosts() }),
376
901
  capabilities,
377
902
  log,
378
- cookieName: () => `mostra-${shellPort}`,
903
+ cookieName: () => `mostra-${way().port()}`,
379
904
  frameAncestors: () => "'none'",
380
905
  artifactOf: (params) => {
381
906
  const id = params["artifactId"];
382
- return id !== undefined && ArtifactId.is(id) ? id : undefined;
907
+ // A face kept for one artifact (a host's external base) serves that artifact only: any
908
+ // other path is refused before anything is opened or asked (Opus review of WP-13).
909
+ const own = way().artifactId;
910
+ return id !== undefined && ArtifactId.is(id) && (own === undefined || own === id)
911
+ ? id
912
+ : undefined;
383
913
  },
384
- };
914
+ // The shell's own stream is refused where streams don't pass, as the frame's is (D158 item 5).
915
+ streams: () => way().streams(),
916
+ });
385
917
 
386
918
  const shellMissing = (): Response =>
387
919
  jsonResponse(
@@ -391,52 +923,13 @@ export function createGateway(options: GatewayOptions): Gateway {
391
923
  { status: 503 },
392
924
  );
393
925
 
394
- /** The shell's page: the same for every artifact; it learns everything from its session. */
395
- const shellPage = (context: RouteContext): Response => {
396
- if (options.shellDir === undefined) return shellMissing();
397
- if (context.artifactId === undefined) {
398
- return refuse(
399
- shellChecks,
400
- refusal("MOSTRA_HYGIENE_NOT_SERVED", "No artifact is named at this path."),
401
- {
402
- method: context.request.method,
403
- path: new URL(context.request.url).pathname,
404
- document: true,
405
- },
406
- );
407
- }
408
- const html = readFileSync(join(options.shellDir, "index.html"));
409
- return new Response(context.request.method === "HEAD" ? null : html, {
410
- headers: {
411
- ...BASE_HEADERS,
412
- ...documentHeaders(shellKind(), `http://${addressing.urlHost}:*`),
413
- "content-type": "text/html; charset=utf-8",
414
- "cache-control": "no-cache",
415
- },
416
- });
417
- };
418
-
419
- const shellAsset = async (context: RouteContext): Promise<Response> => {
420
- if (options.shellDir === undefined) return shellMissing();
421
- const url = new URL(context.request.url);
422
- const path = safePath(url.pathname)?.slice("/_mostra/shell".length) ?? "";
423
- const file = path.startsWith("/assets/") ? await findFile(options.shellDir, path) : undefined;
424
- if (!file) {
425
- return refuse(
426
- shellChecks,
427
- refusal("MOSTRA_HYGIENE_NOT_SERVED", "No shell file at this path."),
428
- {
429
- method: context.request.method,
430
- path: url.pathname,
431
- document: false,
432
- },
433
- );
434
- }
435
- return fileResponse(file, context.request, {
436
- ...documentHeaders(shellKind(), `http://${addressing.urlHost}:*`),
437
- "cache-control": "public, max-age=31536000, immutable",
438
- });
439
- };
926
+ /** The exchanges each browser made, by artifact (WP-12; see `exchange`). */
927
+ const madeSessions = new Map<string, { readonly order: number; readonly grant: Grant }>();
928
+ let exchangeOrder = 0;
929
+ const browserKey = (artifactId: string, browser: unknown): string | undefined =>
930
+ typeof browser === "string" && /^[A-Za-z0-9_-]{16,64}$/.test(browser)
931
+ ? `${artifactId}\u0000${browser}`
932
+ : undefined;
440
933
 
441
934
  /** What a link allows, as the shell shows it when two links meet. */
442
935
  const access = (grant: Grant) => ({
@@ -451,364 +944,491 @@ export function createGateway(options: GatewayOptions): Gateway {
451
944
  return { artifact: { id: detail.id, title: detail.title }, ...access(grant) };
452
945
  };
453
946
 
454
- /**
455
- * The sessions exchanges made, by artifact and browser (the shell's own random key, kept in its
456
- * origin's storage and sent with every exchange), each with the order it was made in. An
457
- * exchange that waited (the identity port answering) checks here whether another link's
458
- * session was made for the same browser meanwhile: its request carried no cookie of that session,
459
- * so D98 item 8's check alone would let the later answer silently replace it (Opus review of
460
- * WP-12, finding 2). Only the last few thousand are kept; the window that matters is seconds.
461
- */
462
- const madeSessions = new Map<string, { readonly order: number; readonly grant: Grant }>();
463
- let exchangeOrder = 0;
464
- const browserKey = (artifactId: string, browser: unknown): string | undefined =>
465
- typeof browser === "string" && /^[A-Za-z0-9_-]{16,64}$/.test(browser)
466
- ? `${artifactId}\u0000${browser}`
467
- : undefined;
947
+ const shellRoutes = (wayOf: () => Way, group: string | undefined): RouteSpec[] => {
948
+ const checks = shellChecks(wayOf);
468
949
 
469
- const exchange = async (context: RouteContext): Promise<Response> => {
470
- const artifactId = context.artifactId as string;
471
- const startedAt = exchangeOrder;
472
- const meta = { method: "POST", path: new URL(context.request.url).pathname, document: false };
473
- const body = await readJsonObject(context.request);
474
- if (isRefusal(body)) return refuse(shellChecks, body, meta);
475
- // A link's token, or a one-time launch ticket from `mostra open` (D140 item 15), which is
476
- // spent only once it started (or reused) a session.
477
- const launch = body["token"] === undefined && body["launch"] !== undefined;
478
- const browser = browserKey(artifactId, body["browser"]);
479
- let grant = launch
480
- ? capabilities.presentLaunch(body["launch"], artifactId, false)
481
- : capabilities.presentToken(body["token"], artifactId);
482
- if (isRefusal(grant)) return refuse(shellChecks, grant, meta);
483
- // A live session from another link is never replaced silently (D98 item 8): a page elsewhere
484
- // could send the viewer to its own, narrower link and take over their tabs.
485
- const existing = capabilities.session(
486
- cookieValues(context.request.headers.get("cookie"), shellChecks.cookieName()),
487
- shellOrigin(),
488
- artifactId,
489
- );
490
- if (!isRefusal(existing)) {
491
- if (existing.grant.tokenId === grant.tokenId) {
492
- if (launch) capabilities.spendLaunch(body["launch"]);
493
- return jsonResponse({ csrf: existing.csrf, ...sessionFacts(artifactId, existing.grant) });
950
+ /** The shell's page: the same for every artifact; it learns everything from its session. */
951
+ const shellPage = async (context: RouteContext): Promise<Response> => {
952
+ if (options.shellDir === undefined) return shellMissing();
953
+ const way = wayOf();
954
+ if (context.artifactId === undefined) {
955
+ return refuse(
956
+ checks,
957
+ refusal("MOSTRA_HYGIENE_NOT_SERVED", "No artifact is named at this path."),
958
+ {
959
+ method: context.request.method,
960
+ path: new URL(context.request.url).pathname,
961
+ document: true,
962
+ },
963
+ );
494
964
  }
495
- if (body["replace"] !== true) {
496
- log.info("gateway.session_conflict", { artifactId, origin: shellOrigin() });
965
+ // The page may frame only its artifact's origin: on loopback any port of the host, at an
966
+ // external address exactly the artifact's face there.
967
+ let frames = `http://${addressing.urlHost}:*`;
968
+ if (way.by !== "loopback") {
969
+ const found = await artifactWayFor(way, group, context.artifactId).catch(() => undefined);
970
+ frames = found && !isRefusal(found) ? (found.way.origin() ?? "'none'") : "'none'";
971
+ }
972
+ const html = readFileSync(join(options.shellDir, "index.html"));
973
+ return new Response(context.request.method === "HEAD" ? null : html, {
974
+ headers: {
975
+ ...BASE_HEADERS,
976
+ ...documentHeaders(shellKind(way), frames),
977
+ "content-type": "text/html; charset=utf-8",
978
+ "cache-control": "no-cache",
979
+ },
980
+ });
981
+ };
982
+
983
+ const shellAsset = async (context: RouteContext): Promise<Response> => {
984
+ if (options.shellDir === undefined) return shellMissing();
985
+ const url = new URL(context.request.url);
986
+ const path = safePath(url.pathname)?.slice("/_mostra/shell".length) ?? "";
987
+ const file = path.startsWith("/assets/") ? await findFile(options.shellDir, path) : undefined;
988
+ if (!file) {
989
+ return refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", "No shell file at this path."), {
990
+ method: context.request.method,
991
+ path: url.pathname,
992
+ document: false,
993
+ });
994
+ }
995
+ return fileResponse(file, context.request, {
996
+ ...documentHeaders(shellKind(wayOf()), `http://${addressing.urlHost}:*`),
997
+ "cache-control": "public, max-age=31536000, immutable",
998
+ });
999
+ };
1000
+
1001
+ /**
1002
+ * Who the session acts as when the link names nobody and no host did (D143 item 2, D158 item
1003
+ * 2): the home's local user on loopback; over a tunnel the tailnet person Tailscale Serve
1004
+ * named, else the link's own viewer, never the home's local user.
1005
+ */
1006
+ const defaultViewer = (way: Way, context: RouteContext, grant: Grant): string | undefined => {
1007
+ if (way.via === "local") return undefined;
1008
+ if (way.via === "tailnet") {
1009
+ const person = tailnetPerson(context.request.headers, context.remote);
1010
+ if (person) return interaction.viewerForTailnet(person);
1011
+ }
1012
+ return interaction.viewerForLink(grant.tokenId, "Shared link");
1013
+ };
1014
+
1015
+ const exchange = async (context: RouteContext): Promise<Response> => {
1016
+ const way = wayOf();
1017
+ const origin = way.origin() ?? "";
1018
+ const startedAt = exchangeOrder;
1019
+ const meta = { method: "POST", path: new URL(context.request.url).pathname, document: false };
1020
+ // No artifact this address serves (another's, at a host's address): nothing is read,
1021
+ // opened or asked (Opus review of WP-13).
1022
+ if (context.artifactId === undefined) {
1023
+ return refuse(
1024
+ checks,
1025
+ refusal("MOSTRA_HYGIENE_NOT_SERVED", "No artifact is served at this path."),
1026
+ meta,
1027
+ );
1028
+ }
1029
+ const artifactId = context.artifactId;
1030
+ const body = await readJsonObject(context.request);
1031
+ if (isRefusal(body)) return refuse(checks, body, meta);
1032
+ // A host's address is asked again at every exchange: one it withdrew stops working (D158).
1033
+ if (way.by === "host") {
1034
+ const still = await hostFace(artifactId, "shell");
1035
+ if (still?.origin !== origin) {
1036
+ return refuse(
1037
+ checks,
1038
+ refusal("MOSTRA_HYGIENE_TOKEN_REVOKED", "The host no longer serves this address.", 410),
1039
+ meta,
1040
+ );
1041
+ }
1042
+ }
1043
+ // A link's token, or a one-time launch ticket from `mostra open` (D140 item 15), which is
1044
+ // spent only once it started (or reused) a session.
1045
+ const launch = body["token"] === undefined && body["launch"] !== undefined;
1046
+ const browser = browserKey(artifactId, body["browser"]);
1047
+ let grant = launch
1048
+ ? capabilities.presentLaunch(body["launch"], artifactId, false, origin)
1049
+ : capabilities.presentToken(body["token"], artifactId, origin);
1050
+ if (isRefusal(grant)) return refuse(checks, grant, meta);
1051
+ // A live session from another link is never replaced silently (D98 item 8): a page elsewhere
1052
+ // could send the viewer to its own, narrower link and take over their tabs.
1053
+ const existing = capabilities.session(
1054
+ cookieValues(context.request.headers.get("cookie"), checks.cookieName()),
1055
+ origin,
1056
+ artifactId,
1057
+ );
1058
+ if (!isRefusal(existing)) {
1059
+ if (existing.grant.tokenId === grant.tokenId) {
1060
+ if (launch) capabilities.spendLaunch(body["launch"]);
1061
+ return jsonResponse({ csrf: existing.csrf, ...sessionFacts(artifactId, existing.grant) });
1062
+ }
1063
+ if (body["replace"] !== true) {
1064
+ log.info("gateway.session_conflict", { artifactId, origin });
1065
+ return jsonResponse(
1066
+ {
1067
+ ...refusal(
1068
+ "MOSTRA_HYGIENE_SESSION_CONFLICT",
1069
+ "This browser already has this artifact open from another link.",
1070
+ ).diagnostic,
1071
+ current: access(existing.grant),
1072
+ offered: access(grant),
1073
+ },
1074
+ { status: 409 },
1075
+ );
1076
+ }
1077
+ }
1078
+ // A link without a viewer acts for whoever the host's identity port names (D143 item 2);
1079
+ // a host that took identity over and can't answer refuses the link, never a guess.
1080
+ let viewerId: string | undefined;
1081
+ if (grant.viewerId === undefined) {
1082
+ const outcome: IdentityOutcome = options.identity
1083
+ ? await options.identity({ artifactId, via: way.via, headers: context.request.headers })
1084
+ : { kind: "default" };
1085
+ if (outcome.kind === "unavailable") {
1086
+ log.warn("gateway.session_refused", { artifactId, code: outcome.diagnostic.code });
1087
+ return jsonResponse(outcome.diagnostic, { status: 503 });
1088
+ }
1089
+ viewerId =
1090
+ outcome.kind === "person"
1091
+ ? interaction.viewerForHost(outcome.viewer)
1092
+ : defaultViewer(way, context, grant);
1093
+ }
1094
+ // Everything is judged again after the await, in one synchronous step with the session's
1095
+ // creation: a link revoked or expired meanwhile gets no session (Opus review of WP-12,
1096
+ // finding 3), and a launch ticket is spent here, so it opens one session however many
1097
+ // exchanges presented it while the identity port answered (GPT review finding 1).
1098
+ const now = launch
1099
+ ? capabilities.presentLaunch(body["launch"], artifactId, true, origin)
1100
+ : capabilities.presentToken(body["token"], artifactId, origin);
1101
+ if (isRefusal(now)) return refuse(checks, now, meta);
1102
+ grant = now;
1103
+ const made = browser === undefined ? undefined : madeSessions.get(browser);
1104
+ if (
1105
+ made !== undefined &&
1106
+ made.order > startedAt &&
1107
+ made.grant.tokenId !== grant.tokenId &&
1108
+ body["replace"] !== true
1109
+ ) {
1110
+ log.info("gateway.session_conflict", { artifactId, origin });
497
1111
  return jsonResponse(
498
1112
  {
499
1113
  ...refusal(
500
1114
  "MOSTRA_HYGIENE_SESSION_CONFLICT",
501
1115
  "This browser already has this artifact open from another link.",
502
1116
  ).diagnostic,
503
- current: access(existing.grant),
1117
+ current: access(made.grant),
504
1118
  offered: access(grant),
505
1119
  },
506
1120
  { status: 409 },
507
1121
  );
508
1122
  }
509
- }
510
- // A link without a viewer acts for whoever the host's identity port names (D143 item 2);
511
- // a host that took identity over and can't answer refuses the link, never a guess.
512
- let viewerId: string | undefined;
513
- if (grant.viewerId === undefined && options.identity) {
514
- const outcome = await options.identity({
515
- artifactId,
516
- via: "local",
517
- headers: context.request.headers,
518
- });
519
- if (outcome.kind === "unavailable") {
520
- log.warn("gateway.session_refused", { artifactId, code: outcome.diagnostic.code });
521
- return jsonResponse(outcome.diagnostic, { status: 503 });
1123
+ const session = capabilities.createSession({ tokenId: grant.tokenId, origin, viewerId });
1124
+ if (browser !== undefined) {
1125
+ exchangeOrder += 1;
1126
+ madeSessions.delete(browser);
1127
+ madeSessions.set(browser, { order: exchangeOrder, grant });
1128
+ if (madeSessions.size > 4096)
1129
+ madeSessions.delete(madeSessions.keys().next().value as string);
522
1130
  }
523
- if (outcome.kind === "person") viewerId = interaction.viewerForHost(outcome.viewer);
524
- }
525
- // Everything is judged again after the await, in one synchronous step with the session's
526
- // creation: a link revoked or expired meanwhile gets no session (Opus review of WP-12,
527
- // finding 3), and a launch ticket is spent here, so it opens one session however many
528
- // exchanges presented it while the identity port answered (GPT review finding 1).
529
- const now = launch
530
- ? capabilities.presentLaunch(body["launch"], artifactId, true)
531
- : capabilities.presentToken(body["token"], artifactId);
532
- if (isRefusal(now)) return refuse(shellChecks, now, meta);
533
- grant = now;
534
- const made = browser === undefined ? undefined : madeSessions.get(browser);
535
- if (
536
- made !== undefined &&
537
- made.order > startedAt &&
538
- made.grant.tokenId !== grant.tokenId &&
539
- body["replace"] !== true
540
- ) {
541
- log.info("gateway.session_conflict", { artifactId, origin: shellOrigin() });
1131
+ log.info("gateway.session_started", { origin, artifactId, tokenId: grant.tokenId });
542
1132
  return jsonResponse(
1133
+ { csrf: session.csrf, ...sessionFacts(artifactId, grant) },
543
1134
  {
544
- ...refusal(
545
- "MOSTRA_HYGIENE_SESSION_CONFLICT",
546
- "This browser already has this artifact open from another link.",
547
- ).diagnostic,
548
- current: access(made.grant),
549
- offered: access(grant),
1135
+ headers: {
1136
+ "set-cookie": sessionCookie(
1137
+ checks.cookieName(),
1138
+ session.cookie,
1139
+ `/a/${artifactId}`,
1140
+ SESSION_MAX_AGE_S,
1141
+ secure(origin),
1142
+ ),
1143
+ },
550
1144
  },
551
- { status: 409 },
552
1145
  );
553
- }
554
- const session = capabilities.createSession({
555
- tokenId: grant.tokenId,
556
- origin: shellOrigin(),
557
- viewerId,
558
- });
559
- if (browser !== undefined) {
560
- exchangeOrder += 1;
561
- madeSessions.delete(browser);
562
- madeSessions.set(browser, { order: exchangeOrder, grant });
563
- if (madeSessions.size > 4096) madeSessions.delete(madeSessions.keys().next().value as string);
564
- }
565
- log.info("gateway.session_started", {
566
- origin: shellOrigin(),
567
- artifactId,
568
- tokenId: grant.tokenId,
569
- });
570
- return jsonResponse(
571
- { csrf: session.csrf, ...sessionFacts(artifactId, grant) },
572
- {
573
- headers: {
574
- "set-cookie": sessionCookie(
575
- shellChecks.cookieName(),
576
- session.cookie,
577
- `/a/${artifactId}`,
578
- SESSION_MAX_AGE_S,
579
- ),
580
- },
581
- },
582
- );
583
- };
1146
+ };
584
1147
 
585
- const readShellSession = (context: RouteContext): Response => {
586
- const session = context.session;
587
- if (!session || context.artifactId === undefined)
588
- throw new Error("session route without a session");
589
- return jsonResponse({ csrf: session.csrf, ...sessionFacts(context.artifactId, session.grant) });
590
- };
1148
+ const readShellSession = (context: RouteContext): Response => {
1149
+ const session = context.session;
1150
+ if (!session || context.artifactId === undefined)
1151
+ throw new Error("session route without a session");
1152
+ return jsonResponse({
1153
+ csrf: session.csrf,
1154
+ ...sessionFacts(context.artifactId, session.grant),
1155
+ });
1156
+ };
591
1157
 
592
- const ticket = async (context: RouteContext): Promise<Response> => {
593
- const session = context.session;
594
- const artifactId = context.artifactId;
595
- if (!session || artifactId === undefined) throw new Error("session route without a session");
596
- const meta = { method: "POST", path: new URL(context.request.url).pathname, document: false };
597
- const body = await readJsonObject(context.request);
598
- if (isRefusal(body)) return refuse(shellChecks, body, meta);
599
- const asked = body["version"];
600
- if (asked !== undefined && !(Number.isSafeInteger(asked) && (asked as number) >= 1)) {
601
- return refuse(
602
- shellChecks,
603
- refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", "`version` must be a version number."),
604
- meta,
605
- );
606
- }
607
- const pinned = session.grant.pinnedVersion;
608
- // A link that names a version opens that version only (D97 item 9).
609
- if (pinned !== undefined && asked !== undefined && asked !== pinned) {
610
- return refuse(
611
- shellChecks,
612
- refusal("MOSTRA_HYGIENE_SCOPE_DENIED", `This link opens version ${pinned} only.`),
613
- meta,
614
- );
615
- }
616
- const detail = artifacts.get({ artifactId });
617
- const version = versionOf(detail, (asked as number | undefined) ?? pinned);
618
- const latest = versionOf(detail, undefined);
619
- if (!version || !latest) {
620
- return jsonResponse(
621
- createDiagnostic("MOSTRA_ARTIFACT_VERSION_NOT_FOUND", {
622
- message:
623
- `This artifact has no version ${asked ?? session.grant.pinnedVersion ?? ""}.`.replace(
624
- " .",
625
- ".",
626
- ),
627
- }),
628
- { status: 404 },
629
- );
630
- }
631
- // A collected version's files are gone until its source is published again (D140 item 14).
632
- if (version.collected !== undefined) {
633
- return jsonResponse(collectedDiagnostic(version.number), { status: 410 });
634
- }
635
- // A damaged version is never shown (FAILURE_MODEL §3).
636
- // A dev preview has no stored build to check: Vite serves the source (D140 item 12).
637
- const damage = options.dev ? undefined : await integrity.check(version.id);
638
- if (damage !== undefined) return damaged(version.number, damage, false);
639
- const port = await openArtifact(artifactId);
640
- const artifactOrigin = addressing.origin(port);
641
- if (addressing.frameMode(shellOrigin(), artifactOrigin) === "worker") {
642
- // Cross-site frames use worker mode (D70), which WP-13 builds; nothing here pretends otherwise.
643
- return refuse(
644
- shellChecks,
645
- refusal("MOSTRA_HYGIENE_NOT_SERVED", "Cross-site frame sessions arrive with sharing.", 501),
646
- meta,
647
- );
648
- }
649
- const value = capabilities.mintTicket({
650
- tokenId: session.grant.tokenId,
651
- artifactId,
652
- versionId: version.id,
653
- origin: artifactOrigin,
654
- shellOrigin: shellOrigin(),
655
- shellSessionId: session.id,
656
- viewerId: session.viewerId,
657
- });
658
- // One frame load is one view, of exactly this version, by this link's viewer (D104), with
659
- // the channels and controls in force for it (D108).
660
- const controls = await options.controls(detail);
661
- const viewerId = interaction.viewerOf(session.viewerId);
662
- const viewId = interaction.openView({
663
- artifactId,
664
- versionId: version.id,
665
- viewerId,
666
- tokenId: session.grant.tokenId,
667
- controls,
668
- });
669
- const answer: TicketAnswer = {
670
- artifactId,
671
- viewId,
672
- src: `${artifactOrigin}/_mostra/enter?ticket=${value}`,
673
- artifactOrigin,
674
- version,
675
- latest,
676
- policy: detail.policy ?? { policy: "once", scope: "per-artifact" },
677
- submitChannels: controls.submitChannels,
678
- // What the shell offers this link: a control its scopes can't use isn't shown (D97).
679
- controls: (controls.controls ?? ["submit", "choose", "approve"]).filter((control) =>
680
- control === "submit"
681
- ? scopeAllows(session.grant.scopes, "submit")
682
- : control === "choose"
683
- ? scopeAllows(session.grant.scopes, "review")
684
- : true,
685
- ),
686
- target: options.target ?? "live",
687
- follow: interaction.following({ artifactId, viewerId }),
688
- pinned: pinned !== undefined,
689
- ...(options.parked?.(version.id) ? { serverParked: true as const } : {}),
690
- ...(options.dev ? { devPreview: true as const } : {}),
1158
+ const ticket = async (context: RouteContext): Promise<Response> => {
1159
+ const way = wayOf();
1160
+ const session = context.session;
1161
+ const artifactId = context.artifactId;
1162
+ if (!session || artifactId === undefined) throw new Error("session route without a session");
1163
+ const meta = { method: "POST", path: new URL(context.request.url).pathname, document: false };
1164
+ const body = await readJsonObject(context.request);
1165
+ if (isRefusal(body)) return refuse(checks, body, meta);
1166
+ const asked = body["version"];
1167
+ if (asked !== undefined && !(Number.isSafeInteger(asked) && (asked as number) >= 1)) {
1168
+ return refuse(
1169
+ checks,
1170
+ refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", "`version` must be a version number."),
1171
+ meta,
1172
+ );
1173
+ }
1174
+ const pinned = session.grant.pinnedVersion;
1175
+ // A link that names a version opens that version only (D97 item 9).
1176
+ if (pinned !== undefined && asked !== undefined && asked !== pinned) {
1177
+ return refuse(
1178
+ checks,
1179
+ refusal("MOSTRA_HYGIENE_SCOPE_DENIED", `This link opens version ${pinned} only.`),
1180
+ meta,
1181
+ );
1182
+ }
1183
+ const detail = artifacts.get({ artifactId });
1184
+ const version = versionOf(detail, (asked as number | undefined) ?? pinned);
1185
+ const latest = versionOf(detail, undefined);
1186
+ if (!version || !latest) {
1187
+ return jsonResponse(
1188
+ createDiagnostic("MOSTRA_ARTIFACT_VERSION_NOT_FOUND", {
1189
+ message:
1190
+ `This artifact has no version ${asked ?? session.grant.pinnedVersion ?? ""}.`.replace(
1191
+ " .",
1192
+ ".",
1193
+ ),
1194
+ }),
1195
+ { status: 404 },
1196
+ );
1197
+ }
1198
+ // A collected version's files are gone until its source is published again (D140 item 14).
1199
+ if (version.collected !== undefined) {
1200
+ return jsonResponse(collectedDiagnostic(version.number), { status: 410 });
1201
+ }
1202
+ // A damaged version is never shown (FAILURE_MODEL §3).
1203
+ // A dev preview has no stored build to check: Vite serves the source (D140 item 12).
1204
+ const damage = options.dev ? undefined : await integrity.check(version.id);
1205
+ if (damage !== undefined) return damaged(version.number, damage, false, "'none'");
1206
+ // The frame opens on the artifact's way in this shell's group: its loopback listener, or
1207
+ // the artifact's face at this address (D158 item 1), in the mode the pair needs (D70).
1208
+ const found = await artifactWayFor(way, group, artifactId);
1209
+ if (isRefusal(found)) return refuse(checks, found, meta);
1210
+ const artifactOrigin = found.way.origin() as string;
1211
+ const mode = modeOf(found.way, found.group);
1212
+ const value = capabilities.mintTicket({
1213
+ tokenId: session.grant.tokenId,
1214
+ artifactId,
1215
+ versionId: version.id,
1216
+ origin: artifactOrigin,
1217
+ shellOrigin: way.origin() ?? "",
1218
+ shellSessionId: session.id,
1219
+ viewerId: session.viewerId,
1220
+ });
1221
+ // One frame load is one view, of exactly this version, by this link's viewer (D104), with
1222
+ // the channels and controls in force for it (D108).
1223
+ const controls = await options.controls(detail);
1224
+ const viewerId = interaction.viewerOf(session.viewerId);
1225
+ const viewId = interaction.openView({
1226
+ artifactId,
1227
+ versionId: version.id,
1228
+ viewerId,
1229
+ tokenId: session.grant.tokenId,
1230
+ controls,
1231
+ });
1232
+ const answer: TicketAnswer = {
1233
+ artifactId,
1234
+ viewId,
1235
+ // Worker mode takes its ticket in the fragment, which only the bootstrap page reads.
1236
+ src:
1237
+ mode === "worker"
1238
+ ? `${artifactOrigin}/_mostra/enter#t=${value}`
1239
+ : `${artifactOrigin}/_mostra/enter?ticket=${value}`,
1240
+ artifactOrigin,
1241
+ version,
1242
+ latest,
1243
+ policy: detail.policy ?? { policy: "once", scope: "per-artifact" },
1244
+ submitChannels: controls.submitChannels,
1245
+ // What the shell offers this link: a control its scopes can't use isn't shown (D97).
1246
+ controls: (controls.controls ?? ["submit", "choose", "approve"]).filter((control) =>
1247
+ control === "submit"
1248
+ ? scopeAllows(session.grant.scopes, "submit")
1249
+ : control === "choose"
1250
+ ? scopeAllows(session.grant.scopes, "review")
1251
+ : true,
1252
+ ),
1253
+ target: options.target ?? "live",
1254
+ follow: interaction.following({ artifactId, viewerId }),
1255
+ pinned: pinned !== undefined,
1256
+ ...(options.parked?.(version.id) ? { serverParked: true as const } : {}),
1257
+ ...(options.dev ? { devPreview: true as const } : {}),
1258
+ ...(mode === "worker" ? { mode: "worker" as const } : {}),
1259
+ };
1260
+ return jsonResponse(answer);
691
1261
  };
692
- return jsonResponse(answer);
693
- };
694
1262
 
695
- const shellRoutes: RouteSpec[] = [
696
- { method: "GET", path: "/a/:artifactId", intent: "read", auth: "none", handler: shellPage },
697
- { method: "GET", path: "/a/:artifactId/", intent: "read", auth: "none", handler: shellPage },
698
- {
699
- method: "GET",
700
- path: "/a/:artifactId/v/:number{[1-9][0-9]{0,8}}",
701
- intent: "read",
702
- auth: "none",
703
- handler: shellPage,
704
- },
705
- { method: "GET", path: "/_mostra/shell/*", intent: "read", auth: "none", handler: shellAsset },
706
- {
707
- method: "POST",
708
- path: "/a/:artifactId/_mostra/session",
709
- intent: "exchange",
710
- auth: "none",
711
- tokenPath: true,
712
- handler: exchange,
713
- },
714
- {
715
- method: "GET",
716
- path: "/a/:artifactId/_mostra/session",
717
- intent: "read",
718
- auth: "session",
719
- handler: readShellSession,
720
- },
721
- {
722
- method: "POST",
723
- path: "/a/:artifactId/_mostra/ticket",
724
- intent: "mutation",
725
- auth: "session",
726
- handler: ticket,
727
- },
728
- // The trusted controls, the version banner's sources and follow (WP-07), and review
729
- // (WP-20), behind the shell's session (D96). The specific routes come before the wildcard.
730
- {
731
- method: "POST",
732
- path: "/a/:artifactId/_mostra/v/:rev/submit",
733
- intent: "mutation",
734
- auth: "session",
735
- scope: () => "submit",
736
- handler: served.shellSubmit,
737
- },
738
- {
739
- method: "POST",
740
- path: "/a/:artifactId/_mostra/v/:rev/review/choose",
741
- intent: "mutation",
742
- auth: "session",
743
- scope: () => "review",
744
- handler: served.choose,
745
- },
746
- {
747
- method: "POST",
748
- path: "/a/:artifactId/_mostra/v/:rev/follow",
749
- intent: "mutation",
750
- auth: "session",
751
- handler: served.follow,
752
- },
753
- {
754
- method: "GET",
755
- path: "/a/:artifactId/_mostra/v/:rev/carry",
756
- intent: "read",
757
- auth: "session",
758
- handler: served.carry,
759
- },
760
- {
761
- method: "GET",
762
- path: "/a/:artifactId/_mostra/v/:rev/events",
763
- intent: "stream",
764
- auth: "session",
765
- handler: served.stream,
766
- },
767
- {
768
- method: "GET",
769
- path: "/a/:artifactId/_mostra/v/:rev/events/poll",
770
- intent: "stream",
771
- auth: "session",
772
- handler: served.poll,
773
- },
774
- {
775
- method: "POST",
776
- path: "/a/:artifactId/_mostra/v/:rev/review/*",
777
- intent: "mutation",
778
- auth: "session",
779
- scope: () => "review",
780
- },
781
- ];
1263
+ return [
1264
+ { method: "GET", path: "/a/:artifactId", intent: "read", auth: "none", handler: shellPage },
1265
+ { method: "GET", path: "/a/:artifactId/", intent: "read", auth: "none", handler: shellPage },
1266
+ {
1267
+ method: "GET",
1268
+ path: "/a/:artifactId/v/:number{[1-9][0-9]{0,8}}",
1269
+ intent: "read",
1270
+ auth: "none",
1271
+ handler: shellPage,
1272
+ },
1273
+ {
1274
+ method: "GET",
1275
+ path: "/_mostra/shell/*",
1276
+ intent: "read",
1277
+ auth: "none",
1278
+ handler: shellAsset,
1279
+ },
1280
+ {
1281
+ method: "POST",
1282
+ path: "/a/:artifactId/_mostra/session",
1283
+ intent: "exchange",
1284
+ auth: "none",
1285
+ tokenPath: true,
1286
+ handler: exchange,
1287
+ },
1288
+ {
1289
+ method: "GET",
1290
+ path: "/a/:artifactId/_mostra/session",
1291
+ intent: "read",
1292
+ auth: "session",
1293
+ handler: readShellSession,
1294
+ },
1295
+ {
1296
+ method: "POST",
1297
+ path: "/a/:artifactId/_mostra/ticket",
1298
+ intent: "mutation",
1299
+ auth: "session",
1300
+ handler: ticket,
1301
+ },
1302
+ // The trusted controls, the version banner's sources and follow (WP-07), and review
1303
+ // (WP-20), behind the shell's session (D96). The specific routes come before the wildcard.
1304
+ {
1305
+ method: "POST",
1306
+ path: "/a/:artifactId/_mostra/v/:rev/submit",
1307
+ intent: "mutation",
1308
+ auth: "session",
1309
+ scope: () => "submit",
1310
+ handler: served.shellSubmit,
1311
+ },
1312
+ {
1313
+ method: "POST",
1314
+ path: "/a/:artifactId/_mostra/v/:rev/review/choose",
1315
+ intent: "mutation",
1316
+ auth: "session",
1317
+ scope: () => "review",
1318
+ handler: served.choose,
1319
+ },
1320
+ {
1321
+ method: "POST",
1322
+ path: "/a/:artifactId/_mostra/v/:rev/follow",
1323
+ intent: "mutation",
1324
+ auth: "session",
1325
+ handler: served.follow,
1326
+ },
1327
+ {
1328
+ method: "GET",
1329
+ path: "/a/:artifactId/_mostra/v/:rev/carry",
1330
+ intent: "read",
1331
+ auth: "session",
1332
+ handler: served.carry,
1333
+ },
1334
+ {
1335
+ method: "GET",
1336
+ path: "/a/:artifactId/_mostra/v/:rev/events",
1337
+ intent: "stream",
1338
+ auth: "session",
1339
+ sse: true,
1340
+ handler: served.stream,
1341
+ },
1342
+ {
1343
+ method: "GET",
1344
+ path: "/a/:artifactId/_mostra/v/:rev/events/poll",
1345
+ intent: "stream",
1346
+ auth: "session",
1347
+ handler: served.poll,
1348
+ },
1349
+ {
1350
+ method: "POST",
1351
+ path: "/a/:artifactId/_mostra/v/:rev/review/*",
1352
+ intent: "mutation",
1353
+ auth: "session",
1354
+ scope: () => "review",
1355
+ },
1356
+ ];
1357
+ };
782
1358
 
783
1359
  // ── Artifacts ────────────────────────────────────────────────────────────────────────────
784
1360
 
785
- const artifactRoutes = (artifactId: string, port: () => number): RouteSpec[] => {
786
- const origin = (): string => addressing.origin(port());
1361
+ const artifactChecks = (
1362
+ artifactId: string,
1363
+ wayOf: () => Way,
1364
+ group: string | undefined,
1365
+ ): ListenerChecks => ({
1366
+ policy: () => ({ origin: wayOf().origin() ?? "", hosts: wayOf().hosts() }),
1367
+ capabilities,
1368
+ log,
1369
+ cookieName: () => `mostra-${wayOf().port()}`,
1370
+ frameAncestors: () => shellOf(wayOf(), group)?.origin() ?? "'none'",
1371
+ artifactOf: () => artifactId,
1372
+ mode: () => modeOf(wayOf(), group),
1373
+ streams: () => wayOf().streams(),
1374
+ });
1375
+
1376
+ const artifactRoutes = (
1377
+ artifactId: string,
1378
+ wayOf: () => Way,
1379
+ group: string | undefined,
1380
+ ): RouteSpec[] => {
1381
+ const origin = (): string => wayOf().origin() ?? "";
1382
+ const shell = (): string => shellOf(wayOf(), group)?.origin() ?? "";
787
1383
  const kind = (): ListenerKind => ({
788
1384
  kind: "artifact",
789
1385
  origin: origin(),
790
- shellOrigin: shellOrigin(),
1386
+ shellOrigin: shell(),
791
1387
  });
792
- const checks = (): ListenerChecks => artifactChecks(artifactId, port);
1388
+ const checks = artifactChecks(artifactId, wayOf, group);
1389
+ const mode = (): FrameMode => modeOf(wayOf(), group);
1390
+ const notServed = (context: RouteContext, message: string): Response =>
1391
+ refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", message), {
1392
+ method: context.request.method,
1393
+ path: new URL(context.request.url).pathname,
1394
+ document: context.document,
1395
+ });
793
1396
 
1397
+ /**
1398
+ * `GET /_mostra/enter`: in cookie mode the frame's entry with its ticket (D98 item 3); in
1399
+ * worker mode the bootstrap page, whose ticket is in the fragment (D70).
1400
+ */
794
1401
  const enter = (context: RouteContext): Response => {
795
1402
  const url = new URL(context.request.url);
796
1403
  const meta = { method: "GET", path: url.pathname, document: true };
1404
+ if (mode() === "worker") {
1405
+ if (url.searchParams.has("ticket")) {
1406
+ return notServed(context, "A worker-mode frame enters through its bootstrap page.");
1407
+ }
1408
+ return new Response(context.request.method === "HEAD" ? null : BOOTSTRAP_PAGE, {
1409
+ headers: {
1410
+ ...BASE_HEADERS,
1411
+ ...documentHeaders(kind(), ""),
1412
+ ...NO_STORE,
1413
+ "content-type": "text/html; charset=utf-8",
1414
+ },
1415
+ });
1416
+ }
797
1417
  // A frame enters from its shell, which is same-site. A page elsewhere can navigate a hidden
798
1418
  // frame here with junk tickets; its entries are refused before redeeming, so they never
799
1419
  // count towards the guessing limit and can't lock real viewers out (D97 item 8).
800
1420
  if (context.request.headers.get("sec-fetch-site") === "cross-site") {
801
1421
  return refuse(
802
- checks(),
1422
+ checks,
803
1423
  refusal("MOSTRA_HYGIENE_ORIGIN_REFUSED", "A frame enters only from its shell."),
804
1424
  meta,
805
1425
  );
806
1426
  }
807
1427
  const redeemed = capabilities.redeemTicket(url.searchParams.get("ticket"), origin());
808
- if (isRefusal(redeemed)) return refuse(checks(), redeemed, meta);
1428
+ if (isRefusal(redeemed)) return refuse(checks, redeemed, meta);
809
1429
  if (redeemed.artifactId !== artifactId) {
810
1430
  return refuse(
811
- checks(),
1431
+ checks,
812
1432
  refusal("MOSTRA_HYGIENE_TOKEN_INVALID", "The ticket is for another artifact."),
813
1433
  meta,
814
1434
  );
@@ -816,7 +1436,7 @@ export function createGateway(options: GatewayOptions): Gateway {
816
1436
  const headers: Record<string, string> = { ...BASE_HEADERS, ...NO_STORE, location: "/" };
817
1437
  // A frame that has a session from the same link keeps it and switches version (D98 item 5).
818
1438
  const existing = capabilities.session(
819
- cookieValues(context.request.headers.get("cookie"), checks().cookieName()),
1439
+ cookieValues(context.request.headers.get("cookie"), checks.cookieName()),
820
1440
  origin(),
821
1441
  artifactId,
822
1442
  );
@@ -836,10 +1456,11 @@ export function createGateway(options: GatewayOptions): Gateway {
836
1456
  viewerId: redeemed.viewerId,
837
1457
  });
838
1458
  headers["set-cookie"] = sessionCookie(
839
- checks().cookieName(),
1459
+ checks.cookieName(),
840
1460
  session.cookie,
841
1461
  "/",
842
1462
  SESSION_MAX_AGE_S,
1463
+ secure(origin()),
843
1464
  );
844
1465
  log.info("gateway.session_started", {
845
1466
  origin: origin(),
@@ -850,21 +1471,126 @@ export function createGateway(options: GatewayOptions): Gateway {
850
1471
  return new Response(null, { status: 303, headers });
851
1472
  };
852
1473
 
1474
+ /**
1475
+ * `POST /_mostra/enter` (worker mode, D70): the bootstrap page exchanges the shell's ticket
1476
+ * for a frame session whose secret it hands the service worker. A frame that presents the
1477
+ * session it kept, from the same link and viewer, keeps it and switches version.
1478
+ */
1479
+ const enterWorker = async (context: RouteContext): Promise<Response> => {
1480
+ const url = new URL(context.request.url);
1481
+ const meta = { method: "POST", path: url.pathname, document: false };
1482
+ if (mode() !== "worker") {
1483
+ return notServed(context, "This frame enters in cookie mode, with `GET /_mostra/enter`.");
1484
+ }
1485
+ const body = await readJsonObject(context.request);
1486
+ if (isRefusal(body)) return refuse(checks, body, meta);
1487
+ const parsed = EnterRequest.safeParse(body);
1488
+ if (!parsed.success) {
1489
+ return refuse(
1490
+ checks,
1491
+ refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", "The entry needs the frame's `ticket`."),
1492
+ meta,
1493
+ );
1494
+ }
1495
+ const redeemed = capabilities.redeemTicket(parsed.data.ticket, origin());
1496
+ if (isRefusal(redeemed)) return refuse(checks, redeemed, meta);
1497
+ if (redeemed.artifactId !== artifactId) {
1498
+ return refuse(
1499
+ checks,
1500
+ refusal("MOSTRA_HYGIENE_TOKEN_INVALID", "The ticket is for another artifact."),
1501
+ meta,
1502
+ );
1503
+ }
1504
+ const kept = context.request.headers.get(FRAME_SESSION_HEADER);
1505
+ const existing =
1506
+ kept === null ? undefined : capabilities.session([kept], origin(), artifactId, "worker");
1507
+ let secret: string;
1508
+ if (
1509
+ kept !== null &&
1510
+ existing !== undefined &&
1511
+ !isRefusal(existing) &&
1512
+ existing.grant.tokenId === redeemed.tokenId &&
1513
+ existing.viewerId === redeemed.viewerId
1514
+ ) {
1515
+ capabilities.enterVersion(existing.id, redeemed.versionId);
1516
+ secret = kept;
1517
+ } else {
1518
+ const session = capabilities.createSession({
1519
+ tokenId: redeemed.tokenId,
1520
+ origin: origin(),
1521
+ versionId: redeemed.versionId,
1522
+ viewerId: redeemed.viewerId,
1523
+ mode: "worker",
1524
+ });
1525
+ secret = session.cookie;
1526
+ log.info("gateway.session_started", {
1527
+ origin: origin(),
1528
+ artifactId,
1529
+ tokenId: redeemed.tokenId,
1530
+ mode: "worker",
1531
+ });
1532
+ }
1533
+ return jsonResponse({ session: secret, shellOrigin: redeemed.shellOrigin });
1534
+ };
1535
+
1536
+ /** `GET /_mostra/sw.js`: the worker-mode service worker, allowed to control `/` (D70). */
1537
+ const serviceWorker = (context: RouteContext): Response => {
1538
+ if (mode() !== "worker") {
1539
+ return notServed(context, "This frame enters in cookie mode and has no service worker.");
1540
+ }
1541
+ return new Response(context.request.method === "HEAD" ? null : SERVICE_WORKER_SOURCE, {
1542
+ headers: {
1543
+ ...BASE_HEADERS,
1544
+ "content-type": "text/javascript; charset=utf-8",
1545
+ "service-worker-allowed": "/",
1546
+ "cache-control": "no-cache",
1547
+ },
1548
+ });
1549
+ };
1550
+
1551
+ /** `POST /_mostra/v/{rev}/ticket`: a single-use ticket for one stream, poll or socket. */
1552
+ const streamTicket = async (context: RouteContext): Promise<Response> => {
1553
+ const session = context.session;
1554
+ if (!session) throw new Error("session route without a session");
1555
+ const meta = { method: "POST", path: new URL(context.request.url).pathname, document: false };
1556
+ const body = await readJsonObject(context.request);
1557
+ if (isRefusal(body)) return refuse(checks, body, meta);
1558
+ const parsed = StreamTicketRequest.safeParse(body);
1559
+ if (!parsed.success) {
1560
+ return refuse(
1561
+ checks,
1562
+ refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", "`purpose` is `stream` or `socket`."),
1563
+ meta,
1564
+ );
1565
+ }
1566
+ return jsonResponse(
1567
+ capabilities.mintStreamTicket({
1568
+ sessionId: session.id,
1569
+ origin: origin(),
1570
+ artifactId,
1571
+ purpose: parsed.data.purpose ?? "stream",
1572
+ }),
1573
+ );
1574
+ };
1575
+
853
1576
  const frameSession = (context: RouteContext): Response => {
854
1577
  const session = context.session;
855
1578
  if (!session) throw new Error("session route without a session");
856
1579
  const detail = artifacts.get({ artifactId });
857
1580
  const version = detail.versions.find((entry) => entry.id === session.versionId);
858
- return jsonResponse({
1581
+ const facts: FrameSessionFacts = {
859
1582
  csrf: session.csrf,
860
1583
  artifactId,
861
- shellOrigin: shellOrigin(),
1584
+ shellOrigin: shell(),
862
1585
  scopes: session.grant.scopes,
863
1586
  // The viewer the page acts as, so edits made before its first snapshot are journaled
864
1587
  // under it (WP-07; Claude review finding 4).
865
1588
  viewer: interaction.viewer(interaction.viewerOf(session.viewerId)),
866
1589
  ...(version ? { version: { id: version.id, number: version.number } } : {}),
867
- });
1590
+ ...(mode() === "worker" ? { mode: "worker" as const } : {}),
1591
+ ...(wayOf().streams() ? {} : { streams: false }),
1592
+ };
1593
+ return jsonResponse(facts);
868
1594
  };
869
1595
 
870
1596
  const files = async (context: RouteContext): Promise<Response> => {
@@ -884,7 +1610,7 @@ export function createGateway(options: GatewayOptions): Gateway {
884
1610
  path.startsWith("/_mostra/")
885
1611
  ) {
886
1612
  return refuse(
887
- checks(),
1613
+ checks,
888
1614
  refusal("MOSTRA_HYGIENE_NOT_SERVED", "Nothing is served at this path."),
889
1615
  meta,
890
1616
  );
@@ -895,7 +1621,7 @@ export function createGateway(options: GatewayOptions): Gateway {
895
1621
  const upstream = options.dev.upstream();
896
1622
  if (!upstream) {
897
1623
  return refuse(
898
- checks(),
1624
+ checks,
899
1625
  refusal("MOSTRA_HYGIENE_NOT_SERVED", "The dev server isn't running.", 503),
900
1626
  meta,
901
1627
  );
@@ -905,7 +1631,7 @@ export function createGateway(options: GatewayOptions): Gateway {
905
1631
  );
906
1632
  if (!answered) {
907
1633
  return refuse(
908
- checks(),
1634
+ checks,
909
1635
  refusal("MOSTRA_HYGIENE_NOT_SERVED", "The dev server didn't answer.", 502),
910
1636
  meta,
911
1637
  );
@@ -942,7 +1668,7 @@ export function createGateway(options: GatewayOptions): Gateway {
942
1668
  const damage = await integrity.serve(from, checked);
943
1669
  if (damage !== undefined) {
944
1670
  const number = artifacts.get({ artifactId }).versions.find((v) => v.id === from)?.number;
945
- return damaged(number, damage, context.document);
1671
+ return damaged(number, damage, context.document, shell() || "'none'");
946
1672
  }
947
1673
  }
948
1674
  if (file && options.target === "verify" && file.path.endsWith(".html")) {
@@ -972,19 +1698,27 @@ export function createGateway(options: GatewayOptions): Gateway {
972
1698
  if (page)
973
1699
  return fileResponse(page, context.request, { ...headers, "cache-control": "no-cache" });
974
1700
  return refuse(
975
- checks(),
1701
+ checks,
976
1702
  refusal("MOSTRA_HYGIENE_NOT_SERVED", "This version has no file at this path."),
977
1703
  meta,
978
1704
  );
979
1705
  };
980
1706
 
981
1707
  return [
1708
+ { method: "GET", path: "/_mostra/enter", intent: "read", auth: "none", handler: enter },
982
1709
  {
983
- method: "GET",
1710
+ method: "POST",
984
1711
  path: "/_mostra/enter",
1712
+ intent: "exchange",
1713
+ auth: "none",
1714
+ handler: enterWorker,
1715
+ },
1716
+ {
1717
+ method: "GET",
1718
+ path: SERVICE_WORKER_PATH,
985
1719
  intent: "read",
986
1720
  auth: "none",
987
- handler: enter,
1721
+ handler: serviceWorker,
988
1722
  },
989
1723
  {
990
1724
  method: "GET",
@@ -993,39 +1727,51 @@ export function createGateway(options: GatewayOptions): Gateway {
993
1727
  auth: "session",
994
1728
  handler: frameSession,
995
1729
  },
996
- ...laterArtifactRoutes(served, acting),
1730
+ ...laterArtifactRoutes(served, acting, streamTicket),
997
1731
  { method: "GET", path: "/*", intent: "read", auth: "session", handler: files },
998
1732
  ];
999
1733
  };
1000
1734
 
1001
- const artifactChecks = (artifactId: string, port: () => number): ListenerChecks => ({
1002
- policy: () => ({ origin: addressing.origin(port()), hosts: addressing.hosts(port()) }),
1003
- capabilities,
1004
- log,
1005
- cookieName: () => `mostra-${port()}`,
1006
- frameAncestors: () => shellOrigin(),
1007
- artifactOf: () => artifactId,
1008
- });
1009
-
1010
1735
  /**
1011
- * The HMR WebSocket of a dev sandbox's artifact origin (D140 item 12): after the listener checked
1012
- * Host and Origin, only a live frame session of this origin reaches the dev server.
1736
+ * WebSocket upgrades on an artifact's listener, after the listener checked Host, target and
1737
+ * Origin: a dev sandbox's HMR socket (D140 item 12), and the browser protocol's sockets
1738
+ * (`/_mostra/v/{rev}/term/{session}`), which open with a single-use socket ticket (D158 item 5)
1739
+ * and arrive with the terminals (WP-22, WP-23).
1013
1740
  */
1014
- const devSocket =
1015
- (artifactId: string, port: () => number) =>
1741
+ const socketUpgrade =
1742
+ (artifactId: string, wayOf: () => Way, group: string | undefined) =>
1016
1743
  (incoming: IncomingMessage, socket: Duplex, head: Buffer): Refusal | undefined => {
1017
- const upstream = options.dev?.upstream();
1018
- if (!upstream)
1019
- return refusal("MOSTRA_HYGIENE_NOT_SERVED", "The dev server isn't running.", 503);
1020
- const cookie = incoming.headers.cookie;
1021
- const session = capabilities.session(
1022
- cookieValues(typeof cookie === "string" ? cookie : null, `mostra-${port()}`),
1023
- addressing.origin(port()),
1024
- artifactId,
1025
- );
1026
- if (isRefusal(session)) return session;
1027
- devUpgrade(upstream, incoming, socket, head);
1028
- return undefined;
1744
+ const way = wayOf();
1745
+ const url = new URL(incoming.url ?? "/", "http://gateway.invalid");
1746
+ if (/^\/_mostra\/v\/[^/]+\/term\/[^/]+$/.test(url.pathname)) {
1747
+ const redeemed = capabilities.redeemStreamTicket(
1748
+ url.searchParams.get("ticket"),
1749
+ way.origin() ?? "",
1750
+ artifactId,
1751
+ "socket",
1752
+ );
1753
+ if (isRefusal(redeemed)) return redeemed;
1754
+ return refusal(
1755
+ "MOSTRA_HYGIENE_NOT_SERVED",
1756
+ "Live terminals arrive with a later Mostra release.",
1757
+ 501,
1758
+ );
1759
+ }
1760
+ if (options.dev && way.by === "loopback" && group === undefined) {
1761
+ const upstream = options.dev.upstream();
1762
+ if (!upstream)
1763
+ return refusal("MOSTRA_HYGIENE_NOT_SERVED", "The dev server isn't running.", 503);
1764
+ const cookie = incoming.headers.cookie;
1765
+ const session = capabilities.session(
1766
+ cookieValues(typeof cookie === "string" ? cookie : null, `mostra-${way.port()}`),
1767
+ way.origin() ?? "",
1768
+ artifactId,
1769
+ );
1770
+ if (isRefusal(session)) return session;
1771
+ devUpgrade(upstream, incoming, socket, head);
1772
+ return undefined;
1773
+ }
1774
+ return refusal("MOSTRA_HYGIENE_NOT_SERVED", "This gateway serves no WebSocket here.");
1029
1775
  };
1030
1776
 
1031
1777
  /** Binds the artifact's listener on its leased port, once; resolves with the port. */
@@ -1036,6 +1782,7 @@ export function createGateway(options: GatewayOptions): Gateway {
1036
1782
  if (pending) return pending;
1037
1783
  const started = (async () => {
1038
1784
  let port = 0;
1785
+ const way = loopbackArtifact(artifactId, () => port);
1039
1786
  const listener = createListener({
1040
1787
  policy: () => ({ origin: addressing.origin(port), hosts: addressing.hosts(port) }),
1041
1788
  log,
@@ -1043,10 +1790,10 @@ export function createGateway(options: GatewayOptions): Gateway {
1043
1790
  configure: (app) =>
1044
1791
  mount(
1045
1792
  app,
1046
- artifactChecks(artifactId, () => port),
1047
- artifactRoutes(artifactId, () => port),
1793
+ artifactChecks(artifactId, () => way, undefined),
1794
+ artifactRoutes(artifactId, () => way, undefined),
1048
1795
  ),
1049
- ...(options.dev ? { upgrade: devSocket(artifactId, () => port) } : {}),
1796
+ upgrade: socketUpgrade(artifactId, () => way, undefined),
1050
1797
  ...(options.traceRequests ? { traceRequests: true } : {}),
1051
1798
  });
1052
1799
  port = await addressing.listen(listener.server, { purpose: "artifact", owner: artifactId });
@@ -1098,16 +1845,42 @@ export function createGateway(options: GatewayOptions): Gateway {
1098
1845
  throw new RpcError(refused.diagnostic);
1099
1846
  };
1100
1847
 
1848
+ /** Opens the faces a host gave before a restart, so their links work before it answers again. */
1849
+ const restoreBases = async (): Promise<void> => {
1850
+ for (const row of keptBases()) {
1851
+ if (row.artifact_id === null) continue;
1852
+ try {
1853
+ artifacts.get({ artifactId: row.artifact_id });
1854
+ } catch {
1855
+ continue;
1856
+ }
1857
+ try {
1858
+ const entry = await openFace(
1859
+ hostSpec(row.artifact_id, row.listener, row.mode ?? undefined),
1860
+ row.origin,
1861
+ );
1862
+ entry.origin = row.origin;
1863
+ } catch (error) {
1864
+ log.warn("gateway.face_restore_failed", { key: row.key, error: (error as Error).message });
1865
+ }
1866
+ }
1867
+ };
1868
+
1101
1869
  return {
1102
1870
  shellOrigin,
1103
1871
  async start() {
1104
1872
  const pruned = capabilities.prune();
1105
1873
  if (pruned > 0) log.info("gateway.sessions_pruned", { count: pruned });
1106
1874
  shellListener = createListener({
1107
- policy: () => shellChecks.policy(),
1875
+ policy: () => ({ origin: shellOrigin(), hosts: addressing.hosts(shellPort ?? 0) }),
1108
1876
  log,
1109
1877
  frameAncestors: () => "'none'",
1110
- configure: (app) => mount(app, shellChecks, shellRoutes),
1878
+ configure: (app) =>
1879
+ mount(
1880
+ app,
1881
+ shellChecks(() => loopbackShell),
1882
+ shellRoutes(() => loopbackShell, undefined),
1883
+ ),
1111
1884
  ...(options.traceRequests ? { traceRequests: true } : {}),
1112
1885
  });
1113
1886
  shellPort = await addressing.listen(shellListener.server, {
@@ -1139,9 +1912,11 @@ export function createGateway(options: GatewayOptions): Gateway {
1139
1912
  }
1140
1913
  await openArtifact(lease.owner);
1141
1914
  }
1915
+ await restoreBases();
1142
1916
  },
1143
- defaultLink(artifactId) {
1144
- const { url, tokenId } = link(capabilities.defaultLink(artifactId));
1917
+ async defaultLink(artifactId) {
1918
+ const base = await linkBase(artifactId);
1919
+ const { url, tokenId } = link(capabilities.defaultLink(artifactId, base));
1145
1920
  return { url, tokenId };
1146
1921
  },
1147
1922
  link(input) {
@@ -1152,8 +1927,44 @@ export function createGateway(options: GatewayOptions): Gateway {
1152
1927
  }),
1153
1928
  ).url;
1154
1929
  },
1930
+ mintAt(input, within) {
1931
+ return link(
1932
+ capabilities.mint(
1933
+ {
1934
+ artifactId: input.artifactId,
1935
+ scopes: input.scopes,
1936
+ ttlMs: input.ttlMs,
1937
+ viewerId: input.viewerId,
1938
+ shellOrigin: input.shellOrigin,
1939
+ },
1940
+ within,
1941
+ ),
1942
+ );
1943
+ },
1944
+ reveal(tokenId) {
1945
+ const shown = capabilities.reveal(tokenId);
1946
+ return shown ? link(shown).url : undefined;
1947
+ },
1948
+ async openFace(spec) {
1949
+ return handleOf(await openFace(spec));
1950
+ },
1951
+ face(key) {
1952
+ const entry = faces.get(key);
1953
+ return entry ? handleOf(entry) : undefined;
1954
+ },
1955
+ closeFace,
1956
+ faces: () =>
1957
+ [...faces.values()]
1958
+ .filter((entry) => entry.origin !== undefined)
1959
+ .map((entry) => ({
1960
+ origin: entry.origin as string,
1961
+ local: addressing.faceLocal(entry.port),
1962
+ listener: entry.spec.listener,
1963
+ ...(entry.spec.artifactId !== undefined ? { artifactId: entry.spec.artifactId } : {}),
1964
+ by: entry.spec.by,
1965
+ })),
1155
1966
  methods: () => [
1156
- handler(viewUrlMethod, (params) => {
1967
+ handler(viewUrlMethod, async (params) => {
1157
1968
  const detail = artifacts.get(params.artifact);
1158
1969
  const version = versionOf(detail, params.version);
1159
1970
  if (!version) {
@@ -1168,6 +1979,7 @@ export function createGateway(options: GatewayOptions): Gateway {
1168
1979
  }
1169
1980
  if (version.collected !== undefined)
1170
1981
  throw new RpcError(collectedDiagnostic(version.number));
1982
+ const base = await linkBase(detail.id);
1171
1983
  return recorded(requestKey("view/url", params), (db) =>
1172
1984
  capabilities.mint(
1173
1985
  {
@@ -1179,14 +1991,15 @@ export function createGateway(options: GatewayOptions): Gateway {
1179
1991
  params.viewer === undefined
1180
1992
  ? undefined
1181
1993
  : interaction.viewerForSpec(db, params.viewer),
1994
+ shellOrigin: base,
1182
1995
  },
1183
1996
  db,
1184
1997
  ),
1185
1998
  );
1186
1999
  }),
1187
- handler(viewDefaultMethod, (params) => {
2000
+ handler(viewDefaultMethod, async (params) => {
1188
2001
  const detail = artifacts.get(params.artifact);
1189
- return link(capabilities.defaultLink(detail.id));
2002
+ return link(capabilities.defaultLink(detail.id, await linkBase(detail.id)));
1190
2003
  }),
1191
2004
  handler(viewLaunchMethod, (params) => {
1192
2005
  const minted = capabilities.mintLaunch(params.tokenId);
@@ -1208,7 +2021,7 @@ export function createGateway(options: GatewayOptions): Gateway {
1208
2021
  }
1209
2022
  const { grant } = minted;
1210
2023
  return {
1211
- url: `${shellOrigin()}/a/${grant.artifactId}${grant.pinnedVersion !== undefined ? `/v/${grant.pinnedVersion}` : ""}#l=${minted.ticket}`,
2024
+ url: `${grant.shellOrigin}/a/${grant.artifactId}${grant.pinnedVersion !== undefined ? `/v/${grant.pinnedVersion}` : ""}#l=${minted.ticket}`,
1212
2025
  expiresAt: minted.expiresAt,
1213
2026
  };
1214
2027
  }),
@@ -1257,12 +2070,16 @@ export function createGateway(options: GatewayOptions): Gateway {
1257
2070
  ]),
1258
2071
  ),
1259
2072
  async close() {
1260
- await Promise.allSettled([...opening.values()]);
2073
+ await Promise.allSettled([...opening.values(), ...openingFaces.values()]);
1261
2074
  await Promise.all([
1262
2075
  shellListener?.close(),
1263
2076
  ...[...artifactListeners.values()].map((entry) => entry.listener.close()),
2077
+ ...[...faces.values()].map((entry) => entry.listener.close()),
2078
+ ...[...lingering.keys()].map((key) => endLingering(key)),
1264
2079
  ]);
2080
+ faces.clear();
1265
2081
  },
2082
+ servesShell,
1266
2083
  };
1267
2084
  }
1268
2085