@mostra/runtime 0.6.1 → 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,24 @@ 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
+ };
208
+ /**
209
+ * Logs every connection and request of every listener (`MOSTRA_TEST_REQUEST_LOG`, #66): tests
210
+ * only, so a request a browser saw go unanswered shows whether it reached the gateway.
211
+ */
212
+ readonly traceRequests?: boolean;
128
213
  /** The browser-protocol revisions served; `BROWSER_PROTOCOL_REVISIONS` unless a test adds one. */
129
214
  readonly revisions?: readonly string[];
130
215
  /**
@@ -154,17 +239,46 @@ export interface GatewayOptions {
154
239
 
155
240
  /** The gateway of one instance. */
156
241
  export interface Gateway {
157
- /** 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). */
158
243
  start(): Promise<void>;
159
- /** The shell's origin. */
244
+ /** The loopback shell's origin. */
160
245
  readonly shellOrigin: () => string;
161
- /** The artifact's default link (D97 item 3), shown again or minted: the publish receipt's URL. */
162
- 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 }>;
163
251
  /**
164
252
  * Mints a link with every scope, for a version only when `version` names its number (D97
165
253
  * item 9): what `view/url` mints, for callers inside the instance (a verify run's sandbox).
166
254
  */
167
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;
168
282
  /** The handlers of `view/url`, `view/rotate` and `view/revoke`. */
169
283
  methods(): MethodHandler[];
170
284
  /** The origins of the artifact listeners that are bound, by artifact ID. */
@@ -181,17 +295,56 @@ const NO_STORE = { "cache-control": "no-store" };
181
295
  /** How recently an artifact must have been viewed for its port to be bound at start (D129). */
182
296
  const RECENT_VIEW_MS = 7 * 24 * 60 * 60 * 1000;
183
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
+
184
334
  /**
185
335
  * The browser-protocol routes of INTERFACES §4 (D96): WP-06 serves `fields`, `submit`, `signal`,
186
- * `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.
187
337
  */
188
- 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[] {
189
343
  const action = (params: Readonly<Record<string, string>>): CapabilityScope | "any-action" => {
190
344
  const id = params["fn"];
191
345
  return id ? (`action:${id}` as CapabilityScope) : "any-action";
192
346
  };
193
347
  return [
194
- { method: "GET", path: "/_mostra/sw.js", intent: "read", auth: "none" },
195
348
  {
196
349
  method: "POST",
197
350
  path: "/_mostra/v/:rev/fields",
@@ -258,12 +411,20 @@ function laterArtifactRoutes(served: BrowserRoutes, acting: ActionRoutes | undef
258
411
  auth: "session",
259
412
  ...(acting ? { handler: acting.live } : {}),
260
413
  },
261
- { 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
+ },
262
422
  {
263
423
  method: "GET",
264
424
  path: "/_mostra/v/:rev/events",
265
425
  intent: "stream",
266
426
  auth: "session",
427
+ sse: true,
267
428
  handler: served.stream,
268
429
  },
269
430
  {
@@ -276,6 +437,15 @@ function laterArtifactRoutes(served: BrowserRoutes, acting: ActionRoutes | undef
276
437
  ];
277
438
  }
278
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
+
279
449
  /** Creates the gateway; nothing is bound until {@link Gateway.start}. */
280
450
  export function createGateway(options: GatewayOptions): Gateway {
281
451
  const { addressing, capabilities, artifacts, log, interaction } = options;
@@ -317,10 +487,79 @@ export function createGateway(options: GatewayOptions): Gateway {
317
487
  { readonly listener: Listener; readonly port: number }
318
488
  >();
319
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>();
320
494
  const integrity = versionIntegrity(artifacts, log);
321
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
+
322
556
  /** The answer for a damaged version: a plain page for a navigation, else the diagnostic. */
323
- 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 =>
324
563
  refusalResponse(
325
564
  {
326
565
  status: 500,
@@ -328,11 +567,11 @@ export function createGateway(options: GatewayOptions): Gateway {
328
567
  message: `${number === undefined ? "A version" : `Version ${number}`} of this artifact is damaged: ${damage}.`,
329
568
  }),
330
569
  },
331
- { document, frameAncestors: shellOrigin() },
570
+ { document, frameAncestors },
332
571
  );
333
572
 
334
573
  const link = (token: MintedToken): CapabilityLink => ({
335
- 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}`,
336
575
  tokenId: token.tokenId,
337
576
  scopes: token.scopes,
338
577
  ...(token.expiresAt !== undefined ? { expiresAt: token.expiresAt } : {}),
@@ -359,24 +598,322 @@ export function createGateway(options: GatewayOptions): Gateway {
359
598
  : undefined;
360
599
  };
361
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
+
362
892
  // ── The shell ────────────────────────────────────────────────────────────────────────────
363
893
 
364
- const shellKind = (): ListenerKind => ({
894
+ const shellKind = (way: Way): ListenerKind => ({
365
895
  kind: "shell",
366
- origin: shellOrigin(),
367
- shellOrigin: shellOrigin(),
896
+ origin: way.origin() ?? "",
897
+ shellOrigin: way.origin() ?? "",
368
898
  });
369
- const shellChecks: ListenerChecks = {
370
- policy: () => ({ origin: shellOrigin(), hosts: addressing.hosts(shellPort ?? 0) }),
899
+ const shellChecks = (way: () => Way): ListenerChecks => ({
900
+ policy: () => ({ origin: way().origin() ?? "", hosts: way().hosts() }),
371
901
  capabilities,
372
902
  log,
373
- cookieName: () => `mostra-${shellPort}`,
903
+ cookieName: () => `mostra-${way().port()}`,
374
904
  frameAncestors: () => "'none'",
375
905
  artifactOf: (params) => {
376
906
  const id = params["artifactId"];
377
- 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;
378
913
  },
379
- };
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
+ });
380
917
 
381
918
  const shellMissing = (): Response =>
382
919
  jsonResponse(
@@ -386,52 +923,13 @@ export function createGateway(options: GatewayOptions): Gateway {
386
923
  { status: 503 },
387
924
  );
388
925
 
389
- /** The shell's page: the same for every artifact; it learns everything from its session. */
390
- const shellPage = (context: RouteContext): Response => {
391
- if (options.shellDir === undefined) return shellMissing();
392
- if (context.artifactId === undefined) {
393
- return refuse(
394
- shellChecks,
395
- refusal("MOSTRA_HYGIENE_NOT_SERVED", "No artifact is named at this path."),
396
- {
397
- method: context.request.method,
398
- path: new URL(context.request.url).pathname,
399
- document: true,
400
- },
401
- );
402
- }
403
- const html = readFileSync(join(options.shellDir, "index.html"));
404
- return new Response(context.request.method === "HEAD" ? null : html, {
405
- headers: {
406
- ...BASE_HEADERS,
407
- ...documentHeaders(shellKind(), `http://${addressing.urlHost}:*`),
408
- "content-type": "text/html; charset=utf-8",
409
- "cache-control": "no-cache",
410
- },
411
- });
412
- };
413
-
414
- const shellAsset = async (context: RouteContext): Promise<Response> => {
415
- if (options.shellDir === undefined) return shellMissing();
416
- const url = new URL(context.request.url);
417
- const path = safePath(url.pathname)?.slice("/_mostra/shell".length) ?? "";
418
- const file = path.startsWith("/assets/") ? await findFile(options.shellDir, path) : undefined;
419
- if (!file) {
420
- return refuse(
421
- shellChecks,
422
- refusal("MOSTRA_HYGIENE_NOT_SERVED", "No shell file at this path."),
423
- {
424
- method: context.request.method,
425
- path: url.pathname,
426
- document: false,
427
- },
428
- );
429
- }
430
- return fileResponse(file, context.request, {
431
- ...documentHeaders(shellKind(), `http://${addressing.urlHost}:*`),
432
- "cache-control": "public, max-age=31536000, immutable",
433
- });
434
- };
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;
435
933
 
436
934
  /** What a link allows, as the shell shows it when two links meet. */
437
935
  const access = (grant: Grant) => ({
@@ -446,364 +944,491 @@ export function createGateway(options: GatewayOptions): Gateway {
446
944
  return { artifact: { id: detail.id, title: detail.title }, ...access(grant) };
447
945
  };
448
946
 
449
- /**
450
- * The sessions exchanges made, by artifact and browser (the shell's own random key, kept in its
451
- * origin's storage and sent with every exchange), each with the order it was made in. An
452
- * exchange that waited (the identity port answering) checks here whether another link's
453
- * session was made for the same browser meanwhile: its request carried no cookie of that session,
454
- * so D98 item 8's check alone would let the later answer silently replace it (Opus review of
455
- * WP-12, finding 2). Only the last few thousand are kept; the window that matters is seconds.
456
- */
457
- const madeSessions = new Map<string, { readonly order: number; readonly grant: Grant }>();
458
- let exchangeOrder = 0;
459
- const browserKey = (artifactId: string, browser: unknown): string | undefined =>
460
- typeof browser === "string" && /^[A-Za-z0-9_-]{16,64}$/.test(browser)
461
- ? `${artifactId}\u0000${browser}`
462
- : undefined;
947
+ const shellRoutes = (wayOf: () => Way, group: string | undefined): RouteSpec[] => {
948
+ const checks = shellChecks(wayOf);
463
949
 
464
- const exchange = async (context: RouteContext): Promise<Response> => {
465
- const artifactId = context.artifactId as string;
466
- const startedAt = exchangeOrder;
467
- const meta = { method: "POST", path: new URL(context.request.url).pathname, document: false };
468
- const body = await readJsonObject(context.request);
469
- if (isRefusal(body)) return refuse(shellChecks, body, meta);
470
- // A link's token, or a one-time launch ticket from `mostra open` (D140 item 15), which is
471
- // spent only once it started (or reused) a session.
472
- const launch = body["token"] === undefined && body["launch"] !== undefined;
473
- const browser = browserKey(artifactId, body["browser"]);
474
- let grant = launch
475
- ? capabilities.presentLaunch(body["launch"], artifactId, false)
476
- : capabilities.presentToken(body["token"], artifactId);
477
- if (isRefusal(grant)) return refuse(shellChecks, grant, meta);
478
- // A live session from another link is never replaced silently (D98 item 8): a page elsewhere
479
- // could send the viewer to its own, narrower link and take over their tabs.
480
- const existing = capabilities.session(
481
- cookieValues(context.request.headers.get("cookie"), shellChecks.cookieName()),
482
- shellOrigin(),
483
- artifactId,
484
- );
485
- if (!isRefusal(existing)) {
486
- if (existing.grant.tokenId === grant.tokenId) {
487
- if (launch) capabilities.spendLaunch(body["launch"]);
488
- 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
+ );
489
964
  }
490
- if (body["replace"] !== true) {
491
- 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 });
492
1111
  return jsonResponse(
493
1112
  {
494
1113
  ...refusal(
495
1114
  "MOSTRA_HYGIENE_SESSION_CONFLICT",
496
1115
  "This browser already has this artifact open from another link.",
497
1116
  ).diagnostic,
498
- current: access(existing.grant),
1117
+ current: access(made.grant),
499
1118
  offered: access(grant),
500
1119
  },
501
1120
  { status: 409 },
502
1121
  );
503
1122
  }
504
- }
505
- // A link without a viewer acts for whoever the host's identity port names (D143 item 2);
506
- // a host that took identity over and can't answer refuses the link, never a guess.
507
- let viewerId: string | undefined;
508
- if (grant.viewerId === undefined && options.identity) {
509
- const outcome = await options.identity({
510
- artifactId,
511
- via: "local",
512
- headers: context.request.headers,
513
- });
514
- if (outcome.kind === "unavailable") {
515
- log.warn("gateway.session_refused", { artifactId, code: outcome.diagnostic.code });
516
- 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);
517
1130
  }
518
- if (outcome.kind === "person") viewerId = interaction.viewerForHost(outcome.viewer);
519
- }
520
- // Everything is judged again after the await, in one synchronous step with the session's
521
- // creation: a link revoked or expired meanwhile gets no session (Opus review of WP-12,
522
- // finding 3), and a launch ticket is spent here, so it opens one session however many
523
- // exchanges presented it while the identity port answered (GPT review finding 1).
524
- const now = launch
525
- ? capabilities.presentLaunch(body["launch"], artifactId, true)
526
- : capabilities.presentToken(body["token"], artifactId);
527
- if (isRefusal(now)) return refuse(shellChecks, now, meta);
528
- grant = now;
529
- const made = browser === undefined ? undefined : madeSessions.get(browser);
530
- if (
531
- made !== undefined &&
532
- made.order > startedAt &&
533
- made.grant.tokenId !== grant.tokenId &&
534
- body["replace"] !== true
535
- ) {
536
- log.info("gateway.session_conflict", { artifactId, origin: shellOrigin() });
1131
+ log.info("gateway.session_started", { origin, artifactId, tokenId: grant.tokenId });
537
1132
  return jsonResponse(
1133
+ { csrf: session.csrf, ...sessionFacts(artifactId, grant) },
538
1134
  {
539
- ...refusal(
540
- "MOSTRA_HYGIENE_SESSION_CONFLICT",
541
- "This browser already has this artifact open from another link.",
542
- ).diagnostic,
543
- current: access(made.grant),
544
- 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
+ },
545
1144
  },
546
- { status: 409 },
547
1145
  );
548
- }
549
- const session = capabilities.createSession({
550
- tokenId: grant.tokenId,
551
- origin: shellOrigin(),
552
- viewerId,
553
- });
554
- if (browser !== undefined) {
555
- exchangeOrder += 1;
556
- madeSessions.delete(browser);
557
- madeSessions.set(browser, { order: exchangeOrder, grant });
558
- if (madeSessions.size > 4096) madeSessions.delete(madeSessions.keys().next().value as string);
559
- }
560
- log.info("gateway.session_started", {
561
- origin: shellOrigin(),
562
- artifactId,
563
- tokenId: grant.tokenId,
564
- });
565
- return jsonResponse(
566
- { csrf: session.csrf, ...sessionFacts(artifactId, grant) },
567
- {
568
- headers: {
569
- "set-cookie": sessionCookie(
570
- shellChecks.cookieName(),
571
- session.cookie,
572
- `/a/${artifactId}`,
573
- SESSION_MAX_AGE_S,
574
- ),
575
- },
576
- },
577
- );
578
- };
1146
+ };
579
1147
 
580
- const readShellSession = (context: RouteContext): Response => {
581
- const session = context.session;
582
- if (!session || context.artifactId === undefined)
583
- throw new Error("session route without a session");
584
- return jsonResponse({ csrf: session.csrf, ...sessionFacts(context.artifactId, session.grant) });
585
- };
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
+ };
586
1157
 
587
- const ticket = async (context: RouteContext): Promise<Response> => {
588
- const session = context.session;
589
- const artifactId = context.artifactId;
590
- if (!session || artifactId === undefined) throw new Error("session route without a session");
591
- const meta = { method: "POST", path: new URL(context.request.url).pathname, document: false };
592
- const body = await readJsonObject(context.request);
593
- if (isRefusal(body)) return refuse(shellChecks, body, meta);
594
- const asked = body["version"];
595
- if (asked !== undefined && !(Number.isSafeInteger(asked) && (asked as number) >= 1)) {
596
- return refuse(
597
- shellChecks,
598
- refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", "`version` must be a version number."),
599
- meta,
600
- );
601
- }
602
- const pinned = session.grant.pinnedVersion;
603
- // A link that names a version opens that version only (D97 item 9).
604
- if (pinned !== undefined && asked !== undefined && asked !== pinned) {
605
- return refuse(
606
- shellChecks,
607
- refusal("MOSTRA_HYGIENE_SCOPE_DENIED", `This link opens version ${pinned} only.`),
608
- meta,
609
- );
610
- }
611
- const detail = artifacts.get({ artifactId });
612
- const version = versionOf(detail, (asked as number | undefined) ?? pinned);
613
- const latest = versionOf(detail, undefined);
614
- if (!version || !latest) {
615
- return jsonResponse(
616
- createDiagnostic("MOSTRA_ARTIFACT_VERSION_NOT_FOUND", {
617
- message:
618
- `This artifact has no version ${asked ?? session.grant.pinnedVersion ?? ""}.`.replace(
619
- " .",
620
- ".",
621
- ),
622
- }),
623
- { status: 404 },
624
- );
625
- }
626
- // A collected version's files are gone until its source is published again (D140 item 14).
627
- if (version.collected !== undefined) {
628
- return jsonResponse(collectedDiagnostic(version.number), { status: 410 });
629
- }
630
- // A damaged version is never shown (FAILURE_MODEL §3).
631
- // A dev preview has no stored build to check: Vite serves the source (D140 item 12).
632
- const damage = options.dev ? undefined : await integrity.check(version.id);
633
- if (damage !== undefined) return damaged(version.number, damage, false);
634
- const port = await openArtifact(artifactId);
635
- const artifactOrigin = addressing.origin(port);
636
- if (addressing.frameMode(shellOrigin(), artifactOrigin) === "worker") {
637
- // Cross-site frames use worker mode (D70), which WP-13 builds; nothing here pretends otherwise.
638
- return refuse(
639
- shellChecks,
640
- refusal("MOSTRA_HYGIENE_NOT_SERVED", "Cross-site frame sessions arrive with sharing.", 501),
641
- meta,
642
- );
643
- }
644
- const value = capabilities.mintTicket({
645
- tokenId: session.grant.tokenId,
646
- artifactId,
647
- versionId: version.id,
648
- origin: artifactOrigin,
649
- shellOrigin: shellOrigin(),
650
- shellSessionId: session.id,
651
- viewerId: session.viewerId,
652
- });
653
- // One frame load is one view, of exactly this version, by this link's viewer (D104), with
654
- // the channels and controls in force for it (D108).
655
- const controls = await options.controls(detail);
656
- const viewerId = interaction.viewerOf(session.viewerId);
657
- const viewId = interaction.openView({
658
- artifactId,
659
- versionId: version.id,
660
- viewerId,
661
- tokenId: session.grant.tokenId,
662
- controls,
663
- });
664
- const answer: TicketAnswer = {
665
- artifactId,
666
- viewId,
667
- src: `${artifactOrigin}/_mostra/enter?ticket=${value}`,
668
- artifactOrigin,
669
- version,
670
- latest,
671
- policy: detail.policy ?? { policy: "once", scope: "per-artifact" },
672
- submitChannels: controls.submitChannels,
673
- // What the shell offers this link: a control its scopes can't use isn't shown (D97).
674
- controls: (controls.controls ?? ["submit", "choose", "approve"]).filter((control) =>
675
- control === "submit"
676
- ? scopeAllows(session.grant.scopes, "submit")
677
- : control === "choose"
678
- ? scopeAllows(session.grant.scopes, "review")
679
- : true,
680
- ),
681
- target: options.target ?? "live",
682
- follow: interaction.following({ artifactId, viewerId }),
683
- pinned: pinned !== undefined,
684
- ...(options.parked?.(version.id) ? { serverParked: true as const } : {}),
685
- ...(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);
686
1261
  };
687
- return jsonResponse(answer);
688
- };
689
1262
 
690
- const shellRoutes: RouteSpec[] = [
691
- { method: "GET", path: "/a/:artifactId", intent: "read", auth: "none", handler: shellPage },
692
- { method: "GET", path: "/a/:artifactId/", intent: "read", auth: "none", handler: shellPage },
693
- {
694
- method: "GET",
695
- path: "/a/:artifactId/v/:number{[1-9][0-9]{0,8}}",
696
- intent: "read",
697
- auth: "none",
698
- handler: shellPage,
699
- },
700
- { method: "GET", path: "/_mostra/shell/*", intent: "read", auth: "none", handler: shellAsset },
701
- {
702
- method: "POST",
703
- path: "/a/:artifactId/_mostra/session",
704
- intent: "exchange",
705
- auth: "none",
706
- tokenPath: true,
707
- handler: exchange,
708
- },
709
- {
710
- method: "GET",
711
- path: "/a/:artifactId/_mostra/session",
712
- intent: "read",
713
- auth: "session",
714
- handler: readShellSession,
715
- },
716
- {
717
- method: "POST",
718
- path: "/a/:artifactId/_mostra/ticket",
719
- intent: "mutation",
720
- auth: "session",
721
- handler: ticket,
722
- },
723
- // The trusted controls, the version banner's sources and follow (WP-07), and review
724
- // (WP-20), behind the shell's session (D96). The specific routes come before the wildcard.
725
- {
726
- method: "POST",
727
- path: "/a/:artifactId/_mostra/v/:rev/submit",
728
- intent: "mutation",
729
- auth: "session",
730
- scope: () => "submit",
731
- handler: served.shellSubmit,
732
- },
733
- {
734
- method: "POST",
735
- path: "/a/:artifactId/_mostra/v/:rev/review/choose",
736
- intent: "mutation",
737
- auth: "session",
738
- scope: () => "review",
739
- handler: served.choose,
740
- },
741
- {
742
- method: "POST",
743
- path: "/a/:artifactId/_mostra/v/:rev/follow",
744
- intent: "mutation",
745
- auth: "session",
746
- handler: served.follow,
747
- },
748
- {
749
- method: "GET",
750
- path: "/a/:artifactId/_mostra/v/:rev/carry",
751
- intent: "read",
752
- auth: "session",
753
- handler: served.carry,
754
- },
755
- {
756
- method: "GET",
757
- path: "/a/:artifactId/_mostra/v/:rev/events",
758
- intent: "stream",
759
- auth: "session",
760
- handler: served.stream,
761
- },
762
- {
763
- method: "GET",
764
- path: "/a/:artifactId/_mostra/v/:rev/events/poll",
765
- intent: "stream",
766
- auth: "session",
767
- handler: served.poll,
768
- },
769
- {
770
- method: "POST",
771
- path: "/a/:artifactId/_mostra/v/:rev/review/*",
772
- intent: "mutation",
773
- auth: "session",
774
- scope: () => "review",
775
- },
776
- ];
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
+ };
777
1358
 
778
1359
  // ── Artifacts ────────────────────────────────────────────────────────────────────────────
779
1360
 
780
- const artifactRoutes = (artifactId: string, port: () => number): RouteSpec[] => {
781
- 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() ?? "";
782
1383
  const kind = (): ListenerKind => ({
783
1384
  kind: "artifact",
784
1385
  origin: origin(),
785
- shellOrigin: shellOrigin(),
1386
+ shellOrigin: shell(),
786
1387
  });
787
- 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
+ });
788
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
+ */
789
1401
  const enter = (context: RouteContext): Response => {
790
1402
  const url = new URL(context.request.url);
791
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
+ }
792
1417
  // A frame enters from its shell, which is same-site. A page elsewhere can navigate a hidden
793
1418
  // frame here with junk tickets; its entries are refused before redeeming, so they never
794
1419
  // count towards the guessing limit and can't lock real viewers out (D97 item 8).
795
1420
  if (context.request.headers.get("sec-fetch-site") === "cross-site") {
796
1421
  return refuse(
797
- checks(),
1422
+ checks,
798
1423
  refusal("MOSTRA_HYGIENE_ORIGIN_REFUSED", "A frame enters only from its shell."),
799
1424
  meta,
800
1425
  );
801
1426
  }
802
1427
  const redeemed = capabilities.redeemTicket(url.searchParams.get("ticket"), origin());
803
- if (isRefusal(redeemed)) return refuse(checks(), redeemed, meta);
1428
+ if (isRefusal(redeemed)) return refuse(checks, redeemed, meta);
804
1429
  if (redeemed.artifactId !== artifactId) {
805
1430
  return refuse(
806
- checks(),
1431
+ checks,
807
1432
  refusal("MOSTRA_HYGIENE_TOKEN_INVALID", "The ticket is for another artifact."),
808
1433
  meta,
809
1434
  );
@@ -811,7 +1436,7 @@ export function createGateway(options: GatewayOptions): Gateway {
811
1436
  const headers: Record<string, string> = { ...BASE_HEADERS, ...NO_STORE, location: "/" };
812
1437
  // A frame that has a session from the same link keeps it and switches version (D98 item 5).
813
1438
  const existing = capabilities.session(
814
- cookieValues(context.request.headers.get("cookie"), checks().cookieName()),
1439
+ cookieValues(context.request.headers.get("cookie"), checks.cookieName()),
815
1440
  origin(),
816
1441
  artifactId,
817
1442
  );
@@ -831,10 +1456,11 @@ export function createGateway(options: GatewayOptions): Gateway {
831
1456
  viewerId: redeemed.viewerId,
832
1457
  });
833
1458
  headers["set-cookie"] = sessionCookie(
834
- checks().cookieName(),
1459
+ checks.cookieName(),
835
1460
  session.cookie,
836
1461
  "/",
837
1462
  SESSION_MAX_AGE_S,
1463
+ secure(origin()),
838
1464
  );
839
1465
  log.info("gateway.session_started", {
840
1466
  origin: origin(),
@@ -845,21 +1471,126 @@ export function createGateway(options: GatewayOptions): Gateway {
845
1471
  return new Response(null, { status: 303, headers });
846
1472
  };
847
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
+
848
1576
  const frameSession = (context: RouteContext): Response => {
849
1577
  const session = context.session;
850
1578
  if (!session) throw new Error("session route without a session");
851
1579
  const detail = artifacts.get({ artifactId });
852
1580
  const version = detail.versions.find((entry) => entry.id === session.versionId);
853
- return jsonResponse({
1581
+ const facts: FrameSessionFacts = {
854
1582
  csrf: session.csrf,
855
1583
  artifactId,
856
- shellOrigin: shellOrigin(),
1584
+ shellOrigin: shell(),
857
1585
  scopes: session.grant.scopes,
858
1586
  // The viewer the page acts as, so edits made before its first snapshot are journaled
859
1587
  // under it (WP-07; Claude review finding 4).
860
1588
  viewer: interaction.viewer(interaction.viewerOf(session.viewerId)),
861
1589
  ...(version ? { version: { id: version.id, number: version.number } } : {}),
862
- });
1590
+ ...(mode() === "worker" ? { mode: "worker" as const } : {}),
1591
+ ...(wayOf().streams() ? {} : { streams: false }),
1592
+ };
1593
+ return jsonResponse(facts);
863
1594
  };
864
1595
 
865
1596
  const files = async (context: RouteContext): Promise<Response> => {
@@ -879,7 +1610,7 @@ export function createGateway(options: GatewayOptions): Gateway {
879
1610
  path.startsWith("/_mostra/")
880
1611
  ) {
881
1612
  return refuse(
882
- checks(),
1613
+ checks,
883
1614
  refusal("MOSTRA_HYGIENE_NOT_SERVED", "Nothing is served at this path."),
884
1615
  meta,
885
1616
  );
@@ -890,7 +1621,7 @@ export function createGateway(options: GatewayOptions): Gateway {
890
1621
  const upstream = options.dev.upstream();
891
1622
  if (!upstream) {
892
1623
  return refuse(
893
- checks(),
1624
+ checks,
894
1625
  refusal("MOSTRA_HYGIENE_NOT_SERVED", "The dev server isn't running.", 503),
895
1626
  meta,
896
1627
  );
@@ -900,7 +1631,7 @@ export function createGateway(options: GatewayOptions): Gateway {
900
1631
  );
901
1632
  if (!answered) {
902
1633
  return refuse(
903
- checks(),
1634
+ checks,
904
1635
  refusal("MOSTRA_HYGIENE_NOT_SERVED", "The dev server didn't answer.", 502),
905
1636
  meta,
906
1637
  );
@@ -937,7 +1668,7 @@ export function createGateway(options: GatewayOptions): Gateway {
937
1668
  const damage = await integrity.serve(from, checked);
938
1669
  if (damage !== undefined) {
939
1670
  const number = artifacts.get({ artifactId }).versions.find((v) => v.id === from)?.number;
940
- return damaged(number, damage, context.document);
1671
+ return damaged(number, damage, context.document, shell() || "'none'");
941
1672
  }
942
1673
  }
943
1674
  if (file && options.target === "verify" && file.path.endsWith(".html")) {
@@ -967,19 +1698,27 @@ export function createGateway(options: GatewayOptions): Gateway {
967
1698
  if (page)
968
1699
  return fileResponse(page, context.request, { ...headers, "cache-control": "no-cache" });
969
1700
  return refuse(
970
- checks(),
1701
+ checks,
971
1702
  refusal("MOSTRA_HYGIENE_NOT_SERVED", "This version has no file at this path."),
972
1703
  meta,
973
1704
  );
974
1705
  };
975
1706
 
976
1707
  return [
1708
+ { method: "GET", path: "/_mostra/enter", intent: "read", auth: "none", handler: enter },
977
1709
  {
978
- method: "GET",
1710
+ method: "POST",
979
1711
  path: "/_mostra/enter",
1712
+ intent: "exchange",
1713
+ auth: "none",
1714
+ handler: enterWorker,
1715
+ },
1716
+ {
1717
+ method: "GET",
1718
+ path: SERVICE_WORKER_PATH,
980
1719
  intent: "read",
981
1720
  auth: "none",
982
- handler: enter,
1721
+ handler: serviceWorker,
983
1722
  },
984
1723
  {
985
1724
  method: "GET",
@@ -988,39 +1727,51 @@ export function createGateway(options: GatewayOptions): Gateway {
988
1727
  auth: "session",
989
1728
  handler: frameSession,
990
1729
  },
991
- ...laterArtifactRoutes(served, acting),
1730
+ ...laterArtifactRoutes(served, acting, streamTicket),
992
1731
  { method: "GET", path: "/*", intent: "read", auth: "session", handler: files },
993
1732
  ];
994
1733
  };
995
1734
 
996
- const artifactChecks = (artifactId: string, port: () => number): ListenerChecks => ({
997
- policy: () => ({ origin: addressing.origin(port()), hosts: addressing.hosts(port()) }),
998
- capabilities,
999
- log,
1000
- cookieName: () => `mostra-${port()}`,
1001
- frameAncestors: () => shellOrigin(),
1002
- artifactOf: () => artifactId,
1003
- });
1004
-
1005
1735
  /**
1006
- * The HMR WebSocket of a dev sandbox's artifact origin (D140 item 12): after the listener checked
1007
- * 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).
1008
1740
  */
1009
- const devSocket =
1010
- (artifactId: string, port: () => number) =>
1741
+ const socketUpgrade =
1742
+ (artifactId: string, wayOf: () => Way, group: string | undefined) =>
1011
1743
  (incoming: IncomingMessage, socket: Duplex, head: Buffer): Refusal | undefined => {
1012
- const upstream = options.dev?.upstream();
1013
- if (!upstream)
1014
- return refusal("MOSTRA_HYGIENE_NOT_SERVED", "The dev server isn't running.", 503);
1015
- const cookie = incoming.headers.cookie;
1016
- const session = capabilities.session(
1017
- cookieValues(typeof cookie === "string" ? cookie : null, `mostra-${port()}`),
1018
- addressing.origin(port()),
1019
- artifactId,
1020
- );
1021
- if (isRefusal(session)) return session;
1022
- devUpgrade(upstream, incoming, socket, head);
1023
- 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.");
1024
1775
  };
1025
1776
 
1026
1777
  /** Binds the artifact's listener on its leased port, once; resolves with the port. */
@@ -1031,6 +1782,7 @@ export function createGateway(options: GatewayOptions): Gateway {
1031
1782
  if (pending) return pending;
1032
1783
  const started = (async () => {
1033
1784
  let port = 0;
1785
+ const way = loopbackArtifact(artifactId, () => port);
1034
1786
  const listener = createListener({
1035
1787
  policy: () => ({ origin: addressing.origin(port), hosts: addressing.hosts(port) }),
1036
1788
  log,
@@ -1038,10 +1790,11 @@ export function createGateway(options: GatewayOptions): Gateway {
1038
1790
  configure: (app) =>
1039
1791
  mount(
1040
1792
  app,
1041
- artifactChecks(artifactId, () => port),
1042
- artifactRoutes(artifactId, () => port),
1793
+ artifactChecks(artifactId, () => way, undefined),
1794
+ artifactRoutes(artifactId, () => way, undefined),
1043
1795
  ),
1044
- ...(options.dev ? { upgrade: devSocket(artifactId, () => port) } : {}),
1796
+ upgrade: socketUpgrade(artifactId, () => way, undefined),
1797
+ ...(options.traceRequests ? { traceRequests: true } : {}),
1045
1798
  });
1046
1799
  port = await addressing.listen(listener.server, { purpose: "artifact", owner: artifactId });
1047
1800
  artifactListeners.set(artifactId, { listener, port });
@@ -1092,16 +1845,43 @@ export function createGateway(options: GatewayOptions): Gateway {
1092
1845
  throw new RpcError(refused.diagnostic);
1093
1846
  };
1094
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
+
1095
1869
  return {
1096
1870
  shellOrigin,
1097
1871
  async start() {
1098
1872
  const pruned = capabilities.prune();
1099
1873
  if (pruned > 0) log.info("gateway.sessions_pruned", { count: pruned });
1100
1874
  shellListener = createListener({
1101
- policy: () => shellChecks.policy(),
1875
+ policy: () => ({ origin: shellOrigin(), hosts: addressing.hosts(shellPort ?? 0) }),
1102
1876
  log,
1103
1877
  frameAncestors: () => "'none'",
1104
- configure: (app) => mount(app, shellChecks, shellRoutes),
1878
+ configure: (app) =>
1879
+ mount(
1880
+ app,
1881
+ shellChecks(() => loopbackShell),
1882
+ shellRoutes(() => loopbackShell, undefined),
1883
+ ),
1884
+ ...(options.traceRequests ? { traceRequests: true } : {}),
1105
1885
  });
1106
1886
  shellPort = await addressing.listen(shellListener.server, {
1107
1887
  purpose: "shell",
@@ -1132,9 +1912,11 @@ export function createGateway(options: GatewayOptions): Gateway {
1132
1912
  }
1133
1913
  await openArtifact(lease.owner);
1134
1914
  }
1915
+ await restoreBases();
1135
1916
  },
1136
- defaultLink(artifactId) {
1137
- 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));
1138
1920
  return { url, tokenId };
1139
1921
  },
1140
1922
  link(input) {
@@ -1145,8 +1927,44 @@ export function createGateway(options: GatewayOptions): Gateway {
1145
1927
  }),
1146
1928
  ).url;
1147
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
+ })),
1148
1966
  methods: () => [
1149
- handler(viewUrlMethod, (params) => {
1967
+ handler(viewUrlMethod, async (params) => {
1150
1968
  const detail = artifacts.get(params.artifact);
1151
1969
  const version = versionOf(detail, params.version);
1152
1970
  if (!version) {
@@ -1161,6 +1979,7 @@ export function createGateway(options: GatewayOptions): Gateway {
1161
1979
  }
1162
1980
  if (version.collected !== undefined)
1163
1981
  throw new RpcError(collectedDiagnostic(version.number));
1982
+ const base = await linkBase(detail.id);
1164
1983
  return recorded(requestKey("view/url", params), (db) =>
1165
1984
  capabilities.mint(
1166
1985
  {
@@ -1172,14 +1991,15 @@ export function createGateway(options: GatewayOptions): Gateway {
1172
1991
  params.viewer === undefined
1173
1992
  ? undefined
1174
1993
  : interaction.viewerForSpec(db, params.viewer),
1994
+ shellOrigin: base,
1175
1995
  },
1176
1996
  db,
1177
1997
  ),
1178
1998
  );
1179
1999
  }),
1180
- handler(viewDefaultMethod, (params) => {
2000
+ handler(viewDefaultMethod, async (params) => {
1181
2001
  const detail = artifacts.get(params.artifact);
1182
- return link(capabilities.defaultLink(detail.id));
2002
+ return link(capabilities.defaultLink(detail.id, await linkBase(detail.id)));
1183
2003
  }),
1184
2004
  handler(viewLaunchMethod, (params) => {
1185
2005
  const minted = capabilities.mintLaunch(params.tokenId);
@@ -1201,7 +2021,7 @@ export function createGateway(options: GatewayOptions): Gateway {
1201
2021
  }
1202
2022
  const { grant } = minted;
1203
2023
  return {
1204
- 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}`,
1205
2025
  expiresAt: minted.expiresAt,
1206
2026
  };
1207
2027
  }),
@@ -1250,12 +2070,16 @@ export function createGateway(options: GatewayOptions): Gateway {
1250
2070
  ]),
1251
2071
  ),
1252
2072
  async close() {
1253
- await Promise.allSettled([...opening.values()]);
2073
+ await Promise.allSettled([...opening.values(), ...openingFaces.values()]);
1254
2074
  await Promise.all([
1255
2075
  shellListener?.close(),
1256
2076
  ...[...artifactListeners.values()].map((entry) => entry.listener.close()),
2077
+ ...[...faces.values()].map((entry) => entry.listener.close()),
2078
+ ...[...lingering.keys()].map((key) => endLingering(key)),
1257
2079
  ]);
2080
+ faces.clear();
1258
2081
  },
2082
+ servesShell,
1259
2083
  };
1260
2084
  }
1261
2085