@mostra/runtime 0.9.0 → 0.10.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.
Files changed (65) hide show
  1. package/dist/bin.js +2879 -8
  2. package/dist/bin.js.map +1 -1
  3. package/dist/builder/child/main.js +2 -2
  4. package/dist/{child-Chiavhdx.js → child-BmNZ4a70.js} +2 -2
  5. package/dist/{child-Chiavhdx.js.map → child-BmNZ4a70.js.map} +1 -1
  6. package/dist/deps/child/install.js +1 -1
  7. package/dist/{directories-mJ1qlVht.js → directories-BLJjeSPD.js} +5 -5
  8. package/dist/directories-BLJjeSPD.js.map +1 -0
  9. package/dist/{files-FygSJIzK.js → files-DGeWuE4I.js} +2 -2
  10. package/dist/{files-FygSJIzK.js.map → files-DGeWuE4I.js.map} +1 -1
  11. package/dist/index.d.ts +2 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +2 -2
  14. package/dist/{instance-EnaZPs14.js → instance-FExcyENK.js} +3341 -396
  15. package/dist/instance-FExcyENK.js.map +1 -0
  16. package/package.json +7 -5
  17. package/src/actions/index.ts +163 -10
  18. package/src/bin.ts +78 -1
  19. package/src/gateway/actions.ts +20 -4
  20. package/src/gateway/browser.ts +118 -95
  21. package/src/gateway/capabilities.ts +15 -6
  22. package/src/gateway/index.ts +112 -15
  23. package/src/gateway/routes.ts +15 -7
  24. package/src/gc/index.ts +14 -0
  25. package/src/instance/index.ts +41 -2
  26. package/src/interaction/ephemeral.ts +32 -23
  27. package/src/interaction/events.ts +21 -1
  28. package/src/interaction/imports.ts +317 -0
  29. package/src/interaction/index.ts +172 -19
  30. package/src/interaction/outbox.ts +9 -0
  31. package/src/interaction/results.ts +8 -1
  32. package/src/interaction/runs.ts +52 -2
  33. package/src/interaction/submissions.ts +17 -1
  34. package/src/interaction/tally.ts +129 -0
  35. package/src/ledger/index.ts +104 -9
  36. package/src/ledger/migrations.ts +183 -0
  37. package/src/ledger/types.ts +8 -0
  38. package/src/link/binding.ts +289 -0
  39. package/src/link/hosted.ts +65 -0
  40. package/src/link/http.ts +136 -0
  41. package/src/link/index.ts +8 -0
  42. package/src/link/manager.ts +1385 -0
  43. package/src/link/relay.ts +512 -0
  44. package/src/live/index.ts +112 -2
  45. package/src/platform/filesystems.ts +78 -0
  46. package/src/platform/index.ts +1 -0
  47. package/src/protocol-server/index.ts +18 -1
  48. package/src/protocol-server/server.ts +38 -7
  49. package/src/protocol-server/websocket.ts +161 -0
  50. package/src/publish/bundle.ts +398 -0
  51. package/src/publish/manifest.ts +9 -0
  52. package/src/publish/methods.ts +12 -1
  53. package/src/publish/publisher.ts +127 -0
  54. package/src/registry/index.ts +35 -14
  55. package/src/server/api.ts +439 -0
  56. package/src/server/auth.ts +613 -0
  57. package/src/server/config.ts +221 -0
  58. package/src/server/data.ts +369 -0
  59. package/src/server/directory.ts +141 -0
  60. package/src/server/hosted.ts +822 -0
  61. package/src/server/index.ts +368 -0
  62. package/src/server/relay.ts +1163 -0
  63. package/src/share/index.ts +110 -6
  64. package/dist/directories-mJ1qlVht.js.map +0 -1
  65. package/dist/instance-EnaZPs14.js.map +0 -1
@@ -177,6 +177,8 @@ export interface BrowserRoutes {
177
177
  readonly stream: Handler;
178
178
  readonly poll: Handler;
179
179
  /** The shell's trusted Submit (the `shell` channel, D40), on the shell origin. */
180
+ /** `events/poll` on the shell origin: the same, without the frame's run and live updates (#119). */
181
+ readonly shellPoll: Handler;
180
182
  readonly shellSubmit: Handler;
181
183
  /** The shell's trusted Choose (D65, D113), on the shell origin. */
182
184
  readonly choose: Handler;
@@ -439,107 +441,117 @@ export function browserRoutes(options: BrowserRoutesOptions): BrowserRoutes {
439
441
  });
440
442
  };
441
443
 
442
- const poll = async (context: RouteContext): Promise<Response> => {
443
- const refused = knownRevision(context);
444
- if (refused) return refused;
445
- const page = pageOf(context);
446
- const badView = viewOf(context, page);
447
- if (badView) return badView;
448
- const resume = cursorOf(context.request);
449
- if (resume === "invalid") return malformed("`cursor` must be an event cursor.");
450
- const waitParam = new URL(context.request.url).searchParams.get("wait");
451
- const waitS = waitParam === null ? POLL_MAX_WAIT_S : Number(waitParam);
452
- if (!Number.isInteger(waitS) || waitS < 0 || waitS > POLL_MAX_WAIT_S) {
453
- return malformed(`\`wait\` must be a whole number of seconds from 0 to ${POLL_MAX_WAIT_S}.`);
454
- }
455
- const viewId = viewIdOf(context);
456
- const bus = options.bus;
457
- // Polling views collect their run and live updates between polls (LL-04).
458
- // Taking what is queued also starts the queue, so updates during the wait are kept.
459
- let early = bus?.drain(page.artifactId, viewId) ?? [];
460
- const withEphemeral = <T extends object>(value: T): T & { ephemeral?: unknown[] } => {
461
- const ephemeral = [...early, ...(bus?.drain(page.artifactId, viewId) ?? [])];
462
- early = [];
463
- return ephemeral.length > 0 ? { ...value, ephemeral } : value;
464
- };
465
- if (resume === undefined) {
466
- const snapshot = interaction.pageSnapshot(page);
467
- return jsonResponse(withEphemeral({ cursor: snapshot.cursor, events: [], snapshot }));
468
- }
469
- const revoked = (): Response =>
470
- answer(
471
- refusal(
472
- "MOSTRA_HYGIENE_TOKEN_REVOKED",
473
- "The link this page came from was revoked or has expired.",
474
- 410,
475
- ).diagnostic,
476
- 410,
477
- );
478
- const once = () => {
479
- const read = next(page, resume);
480
- return "snapshot" in read
481
- ? { cursor: read.snapshot.cursor, events: [], snapshot: read.snapshot }
482
- : { cursor: String(read.cursor), events: read.events };
483
- };
484
- try {
485
- const first = once();
486
- if (first.events.length > 0 || "snapshot" in first || waitS === 0 || early.length > 0) {
487
- return jsonResponse(withEphemeral(first));
444
+ /**
445
+ * `events/poll`. The frame's poll also answers with the run and live updates its view collected
446
+ * (LL-04); the shell's poll of the same view leaves them to the frame, which is the one that shows
447
+ * them: taking them made a page on a quick tunnel learn of a finished run only at its next renewal,
448
+ * about 20 s later (#119).
449
+ */
450
+ const pollFor =
451
+ (ephemeral: boolean) =>
452
+ async (context: RouteContext): Promise<Response> => {
453
+ const refused = knownRevision(context);
454
+ if (refused) return refused;
455
+ const page = pageOf(context);
456
+ const badView = viewOf(context, page);
457
+ if (badView) return badView;
458
+ const resume = cursorOf(context.request);
459
+ if (resume === "invalid") return malformed("`cursor` must be an event cursor.");
460
+ const waitParam = new URL(context.request.url).searchParams.get("wait");
461
+ const waitS = waitParam === null ? POLL_MAX_WAIT_S : Number(waitParam);
462
+ if (!Number.isInteger(waitS) || waitS < 0 || waitS > POLL_MAX_WAIT_S) {
463
+ return malformed(
464
+ `\`wait\` must be a whole number of seconds from 0 to ${POLL_MAX_WAIT_S}.`,
465
+ );
488
466
  }
489
- let ended = false;
490
- const stopWaiting = new AbortController();
491
- const result = await new Promise<ReturnType<typeof once>>((resolve, reject) => {
492
- let done = false;
493
- const finish = (value?: ReturnType<typeof once>): void => {
494
- if (done) return;
495
- done = true;
496
- clearTimeout(timer);
497
- unsubscribe();
498
- context.request.signal.removeEventListener("abort", aborted);
499
- // A failing read here (the ledger closing at shutdown, say) answers this request; it
500
- // never escapes the timer as an uncaught exception (Claude review finding 8).
501
- try {
502
- resolve(value ?? once());
503
- } catch (error) {
504
- reject(error);
505
- }
506
- };
507
- const aborted = (): void => finish(first);
508
- const unsubscribe = interaction.onCommit(() =>
509
- setImmediate(() => {
467
+ const viewId = viewIdOf(context);
468
+ const bus = ephemeral ? options.bus : undefined;
469
+ // Polling views collect their run and live updates between polls (LL-04).
470
+ // Taking what is queued also starts the queue, so updates during the wait are kept.
471
+ let early = bus?.drain(page.artifactId, viewId) ?? [];
472
+ const withEphemeral = <T extends object>(value: T): T & { ephemeral?: unknown[] } => {
473
+ const ephemeral = [...early, ...(bus?.drain(page.artifactId, viewId) ?? [])];
474
+ early = [];
475
+ return ephemeral.length > 0 ? { ...value, ephemeral } : value;
476
+ };
477
+ if (resume === undefined) {
478
+ const snapshot = interaction.pageSnapshot(page);
479
+ return jsonResponse(withEphemeral({ cursor: snapshot.cursor, events: [], snapshot }));
480
+ }
481
+ const revoked = (): Response =>
482
+ answer(
483
+ refusal(
484
+ "MOSTRA_HYGIENE_TOKEN_REVOKED",
485
+ "The link this page came from was revoked or has expired.",
486
+ 410,
487
+ ).diagnostic,
488
+ 410,
489
+ );
490
+ const once = () => {
491
+ const read = next(page, resume);
492
+ return "snapshot" in read
493
+ ? { cursor: read.snapshot.cursor, events: [], snapshot: read.snapshot }
494
+ : { cursor: String(read.cursor), events: read.events };
495
+ };
496
+ try {
497
+ const first = once();
498
+ if (first.events.length > 0 || "snapshot" in first || waitS === 0 || early.length > 0) {
499
+ return jsonResponse(withEphemeral(first));
500
+ }
501
+ let ended = false;
502
+ const stopWaiting = new AbortController();
503
+ const result = await new Promise<ReturnType<typeof once>>((resolve, reject) => {
504
+ let done = false;
505
+ const finish = (value?: ReturnType<typeof once>): void => {
510
506
  if (done) return;
511
- // A revoked or expired link ends the poll before it reads anything more.
512
- if (!live(context)) {
513
- ended = true;
514
- finish(first);
515
- return;
516
- }
507
+ done = true;
508
+ clearTimeout(timer);
509
+ unsubscribe();
510
+ context.request.signal.removeEventListener("abort", aborted);
511
+ // A failing read here (the ledger closing at shutdown, say) answers this request; it
512
+ // never escapes the timer as an uncaught exception (Claude review finding 8).
517
513
  try {
518
- const value = once();
519
- if (value.events.length > 0 || "snapshot" in value) finish(value);
514
+ resolve(value ?? once());
520
515
  } catch (error) {
521
- done = true;
522
- clearTimeout(timer);
523
- unsubscribe();
524
516
  reject(error);
525
517
  }
526
- }),
527
- );
528
- const timer = setTimeout(() => finish(), waitS * 1000);
529
- context.request.signal.addEventListener("abort", aborted, { once: true });
530
- // A run or live update for this view answers the poll too.
531
- void bus?.wait(page.artifactId, viewId, waitS * 1000, stopWaiting.signal).then(() => {
532
- if (!done) finish(first);
518
+ };
519
+ const aborted = (): void => finish(first);
520
+ const unsubscribe = interaction.onCommit(() =>
521
+ setImmediate(() => {
522
+ if (done) return;
523
+ // A revoked or expired link ends the poll before it reads anything more.
524
+ if (!live(context)) {
525
+ ended = true;
526
+ finish(first);
527
+ return;
528
+ }
529
+ try {
530
+ const value = once();
531
+ if (value.events.length > 0 || "snapshot" in value) finish(value);
532
+ } catch (error) {
533
+ done = true;
534
+ clearTimeout(timer);
535
+ unsubscribe();
536
+ reject(error);
537
+ }
538
+ }),
539
+ );
540
+ const timer = setTimeout(() => finish(), waitS * 1000);
541
+ context.request.signal.addEventListener("abort", aborted, { once: true });
542
+ // A run or live update for this view answers the poll too.
543
+ void bus?.wait(page.artifactId, viewId, waitS * 1000, stopWaiting.signal).then(() => {
544
+ if (!done) finish(first);
545
+ });
533
546
  });
534
- });
535
- stopWaiting.abort();
536
- // The link is checked again at the end: nothing read after it died leaves (HY-03).
537
- if (ended || !live(context)) return revoked();
538
- return jsonResponse(withEphemeral(result));
539
- } catch (error) {
540
- return failure(error);
541
- }
542
- };
547
+ stopWaiting.abort();
548
+ // The link is checked again at the end: nothing read after it died leaves (HY-03).
549
+ if (ended || !live(context)) return revoked();
550
+ return jsonResponse(withEphemeral(result));
551
+ } catch (error) {
552
+ return failure(error);
553
+ }
554
+ };
543
555
 
544
556
  // ── The shell's own routes (WP-07) ─────────────────────────────────────────────────────
545
557
  // They run on the shell origin behind the shell's session, its exact Origin and its CSRF
@@ -648,5 +660,16 @@ export function browserRoutes(options: BrowserRoutesOptions): BrowserRoutes {
648
660
  }
649
661
  };
650
662
 
651
- return { fields, submit, signal, stream, poll, shellSubmit, choose, follow, carry };
663
+ return {
664
+ fields,
665
+ submit,
666
+ signal,
667
+ stream,
668
+ poll: pollFor(true),
669
+ shellPoll: pollFor(false),
670
+ shellSubmit,
671
+ choose,
672
+ follow,
673
+ carry,
674
+ };
652
675
  }
@@ -178,8 +178,11 @@ export interface ResolvedSession {
178
178
  readonly csrf: string;
179
179
  /** The version a frame session entered (D98 item 5). */
180
180
  readonly versionId?: string;
181
- /** How the session authenticates: a cookie, or the frame header of worker mode (D70). */
182
- readonly mode: "cookie" | "worker";
181
+ /**
182
+ * How the session authenticates: a cookie, the frame header of worker mode (D70), or a hosted
183
+ * shell's header (`X-Mostra-Shell`, D165 item 8).
184
+ */
185
+ readonly mode: SessionMode;
183
186
  readonly grant: Grant;
184
187
  /**
185
188
  * The viewer the session acts as: its link's viewer (D104), else the one the host's identity
@@ -216,11 +219,14 @@ interface TokenRow {
216
219
  viewer_id: string | null;
217
220
  }
218
221
 
222
+ /** How a session authenticates (DATA_MODEL §3 `session.mode`). */
223
+ export type SessionMode = "cookie" | "worker" | "header";
224
+
219
225
  interface SessionRow {
220
226
  id: string;
221
227
  token_id: string;
222
228
  origin: string;
223
- mode: "cookie" | "worker";
229
+ mode: SessionMode;
224
230
  csrf: string;
225
231
  version_id: string | null;
226
232
  viewer_id: string | null;
@@ -618,8 +624,11 @@ export class Capabilities {
618
624
  readonly versionId?: string;
619
625
  /** The person the host's identity port named, for a link without a viewer (D143 item 2). */
620
626
  readonly viewerId?: string | undefined;
621
- /** `worker` for a worker-mode frame (D70), whose secret travels in a header; default `cookie`. */
622
- readonly mode?: "cookie" | "worker";
627
+ /**
628
+ * `worker` for a worker-mode frame (D70) and `header` for a hosted shell (D165 item 8), whose
629
+ * secrets travel in headers; default `cookie`.
630
+ */
631
+ readonly mode?: SessionMode;
623
632
  }): {
624
633
  readonly cookie: string;
625
634
  readonly csrf: string;
@@ -655,7 +664,7 @@ export class Capabilities {
655
664
  cookies: readonly string[],
656
665
  origin: string,
657
666
  artifactId: string,
658
- mode: "cookie" | "worker" = "cookie",
667
+ mode: SessionMode = "cookie",
659
668
  ): ResolvedSession | Refusal {
660
669
  let revoked = false;
661
670
  for (const value of cookies) {
@@ -25,7 +25,7 @@
25
25
  */
26
26
  import { existsSync, readFileSync } from "node:fs";
27
27
  import { readFile } from "node:fs/promises";
28
- import type { IncomingMessage } from "node:http";
28
+ import type { IncomingMessage, ServerResponse } from "node:http";
29
29
  import { join, resolve } from "node:path";
30
30
  import type { Duplex } from "node:stream";
31
31
  import {
@@ -49,6 +49,7 @@ import {
49
49
  type Refusal,
50
50
  RpcError,
51
51
  refusal,
52
+ SHELL_SESSION_HEADER,
52
53
  StreamTicketRequest,
53
54
  safePath,
54
55
  scopeAllows,
@@ -116,7 +117,7 @@ export interface GatewayArtifacts {
116
117
  }
117
118
 
118
119
  /** 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
+ export type FaceBy = "tailnet" | "funnel" | "cloudflare" | "host" | "hosted";
120
121
 
121
122
  /** What a share asks the gateway to open: one external address of the shell or an artifact. */
122
123
  export interface FaceSpec {
@@ -216,8 +217,8 @@ export interface GatewayOptions {
216
217
  * Server functions and live data (WP-08): plain calls, action runs and live sources. Absent,
217
218
  * their routes answer 501 behind their checks, as before WP-08.
218
219
  */
219
- readonly actions?: Actions;
220
- readonly live?: Live;
220
+ readonly actions?: Pick<Actions, "call" | "startRun" | "attach" | "cancel">;
221
+ readonly live?: Pick<Live, "read">;
221
222
  /** Run and live updates for page streams and polls (WP-08). */
222
223
  readonly bus?: EphemeralBus;
223
224
  /** Whether a version's worker is parked (WP-08): its frame ticket tells the shell. */
@@ -235,6 +236,25 @@ export interface GatewayOptions {
235
236
  * development preview. `upstream` is where that server listens now.
236
237
  */
237
238
  readonly dev?: { readonly upstream: () => DevUpstream | undefined };
239
+ /**
240
+ * A hosted home's gateway on a remote server (ARCHITECTURE §15.6, INTERFACES §18.4): it binds
241
+ * nothing (the server's front hands it each request by exact `Host`, {@link Gateway.dispatch}),
242
+ * its shell lives on each user-content domain's apex at `/a/<routeId>` with its session in a
243
+ * header, and its frames on the route's label, always in worker mode.
244
+ */
245
+ readonly hosted?: HostedAddressing;
246
+ }
247
+
248
+ /** Where a hosted home's pages live (INTERFACES §18.4). */
249
+ export interface HostedAddressing {
250
+ /** The active domain's shell origin, where new links are minted (D137). */
251
+ readonly shellOrigin: () => string;
252
+ /** Whether an origin is a domain's shell the server serves (the active domain or a spare). */
253
+ readonly servesShell: (origin: string) => boolean;
254
+ /** The shell's path of an artifact: `/a/<routeId>`. */
255
+ readonly shellPath: (artifactId: string) => string;
256
+ /** The origin of an artifact's frames beside a domain's shell: its route's label there. */
257
+ readonly artifactOrigin: (artifactId: string, shellOrigin: string) => string | undefined;
238
258
  }
239
259
 
240
260
  /** The gateway of one instance. */
@@ -283,6 +303,11 @@ export interface Gateway {
283
303
  methods(): MethodHandler[];
284
304
  /** The origins of the artifact listeners that are bound, by artifact ID. */
285
305
  artifactOrigins(): ReadonlyMap<string, string>;
306
+ /**
307
+ * Hands a request to an open face's listener without binding it (a hosted home's faces, served
308
+ * by the server's front): `false` when no such face is open.
309
+ */
310
+ dispatch(key: string, request: IncomingMessage, response: ServerResponse): boolean;
286
311
  /** Stops every listener. */
287
312
  close(): Promise<void>;
288
313
  }
@@ -478,7 +503,9 @@ export function createGateway(options: GatewayOptions): Gateway {
478
503
  })
479
504
  : undefined;
480
505
  let shellPort: number | undefined;
506
+ const hosted = options.hosted;
481
507
  const shellOrigin = (): string => {
508
+ if (hosted) return hosted.shellOrigin();
482
509
  if (shellPort === undefined) throw new Error("The gateway hasn't started.");
483
510
  return addressing.origin(shellPort);
484
511
  };
@@ -550,7 +577,7 @@ export function createGateway(options: GatewayOptions): Gateway {
550
577
 
551
578
  /** Whether the gateway serves a shell at this origin now: launch tickets go only there. */
552
579
  const servesShell = (origin: string): boolean =>
553
- origin === shellOrigin() ||
580
+ (hosted ? hosted.servesShell(origin) : origin === shellOrigin()) ||
554
581
  [...faces.values()].some((entry) => entry.spec.listener === "shell" && entry.origin === origin);
555
582
 
556
583
  /** The answer for a damaged version: a plain page for a navigation, else the diagnostic. */
@@ -571,7 +598,7 @@ export function createGateway(options: GatewayOptions): Gateway {
571
598
  );
572
599
 
573
600
  const link = (token: MintedToken): CapabilityLink => ({
574
- url: `${token.shellOrigin}/a/${token.artifactId}${token.pinnedVersion !== undefined ? `/v/${token.pinnedVersion}` : ""}#t=${token.secret}`,
601
+ url: `${token.shellOrigin}${hosted ? hosted.shellPath(token.artifactId) : `/a/${token.artifactId}`}${token.pinnedVersion !== undefined ? `/v/${token.pinnedVersion}` : ""}#t=${token.secret}`,
575
602
  tokenId: token.tokenId,
576
603
  scopes: token.scopes,
577
604
  ...(token.expiresAt !== undefined ? { expiresAt: token.expiresAt } : {}),
@@ -637,9 +664,13 @@ export function createGateway(options: GatewayOptions): Gateway {
637
664
  : {}),
638
665
  ...(options.traceRequests ? { traceRequests: true } : {}),
639
666
  });
640
- // A withdrawn face of this key may still hold its leased port for a moment.
667
+ // A withdrawn face of this key may still hold its leased port for a moment. A hosted face
668
+ // binds nothing: the server's front hands it its requests (`dispatch`).
641
669
  await endLingering(key);
642
- const port = await addressing.listenFace(listener.server, { key, lease: spec.lease });
670
+ const port =
671
+ spec.by === "hosted"
672
+ ? 0
673
+ : await addressing.listenFace(listener.server, { key, lease: spec.lease });
643
674
  entry = { key, spec, listener, port, origin };
644
675
  faces.set(key, entry);
645
676
  log.info("gateway.face_open", {
@@ -871,6 +902,26 @@ export function createGateway(options: GatewayOptions): Gateway {
871
902
  const port = await openArtifact(artifactId);
872
903
  return { way: loopbackArtifact(artifactId, () => port), group: undefined };
873
904
  }
905
+ if (shell.by === "hosted") {
906
+ const origin = hosted?.artifactOrigin(artifactId, shell.origin() ?? "");
907
+ if (origin === undefined) {
908
+ return refusal("MOSTRA_HYGIENE_NOT_SERVED", "This artifact isn't hosted here.");
909
+ }
910
+ const entry = await openFace(
911
+ {
912
+ by: "hosted",
913
+ group,
914
+ listener: "artifact",
915
+ artifactId,
916
+ via: "token",
917
+ lease: false,
918
+ mode: "worker",
919
+ },
920
+ origin,
921
+ );
922
+ entry.origin = origin;
923
+ return { way: faceWay(entry), group };
924
+ }
874
925
  if (shell.by === "host") {
875
926
  const entry = await hostFace(artifactId, "artifact");
876
927
  if (entry?.origin === undefined) {
@@ -901,6 +952,8 @@ export function createGateway(options: GatewayOptions): Gateway {
901
952
  capabilities,
902
953
  log,
903
954
  cookieName: () => `mostra-${way().port()}`,
955
+ // A hosted shell's session travels in a header, never a cookie (D165 item 8).
956
+ mode: () => (way().by === "hosted" ? "header" : "cookie"),
904
957
  frameAncestors: () => "'none'",
905
958
  artifactOf: (params) => {
906
959
  const id = params["artifactId"];
@@ -1050,11 +1103,19 @@ export function createGateway(options: GatewayOptions): Gateway {
1050
1103
  if (isRefusal(grant)) return refuse(checks, grant, meta);
1051
1104
  // A live session from another link is never replaced silently (D98 item 8): a page elsewhere
1052
1105
  // 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
- );
1106
+ const inHeader = way.by === "hosted";
1107
+ const existing = inHeader
1108
+ ? capabilities.session(
1109
+ [context.request.headers.get(SHELL_SESSION_HEADER) ?? ""],
1110
+ origin,
1111
+ artifactId,
1112
+ "header",
1113
+ )
1114
+ : capabilities.session(
1115
+ cookieValues(context.request.headers.get("cookie"), checks.cookieName()),
1116
+ origin,
1117
+ artifactId,
1118
+ );
1058
1119
  if (!isRefusal(existing)) {
1059
1120
  if (existing.grant.tokenId === grant.tokenId) {
1060
1121
  if (launch) capabilities.spendLaunch(body["launch"]);
@@ -1120,7 +1181,12 @@ export function createGateway(options: GatewayOptions): Gateway {
1120
1181
  { status: 409 },
1121
1182
  );
1122
1183
  }
1123
- const session = capabilities.createSession({ tokenId: grant.tokenId, origin, viewerId });
1184
+ const session = capabilities.createSession({
1185
+ tokenId: grant.tokenId,
1186
+ origin,
1187
+ viewerId,
1188
+ ...(inHeader ? { mode: "header" as const } : {}),
1189
+ });
1124
1190
  if (browser !== undefined) {
1125
1191
  exchangeOrder += 1;
1126
1192
  madeSessions.delete(browser);
@@ -1129,6 +1195,15 @@ export function createGateway(options: GatewayOptions): Gateway {
1129
1195
  madeSessions.delete(madeSessions.keys().next().value as string);
1130
1196
  }
1131
1197
  log.info("gateway.session_started", { origin, artifactId, tokenId: grant.tokenId });
1198
+ // A hosted shell keeps its session's secret itself and sends it as a header (§18.4).
1199
+ if (inHeader) {
1200
+ return jsonResponse({
1201
+ csrf: session.csrf,
1202
+ session: session.cookie,
1203
+ hosted: true,
1204
+ ...sessionFacts(artifactId, grant),
1205
+ });
1206
+ }
1132
1207
  return jsonResponse(
1133
1208
  { csrf: session.csrf, ...sessionFacts(artifactId, grant) },
1134
1209
  {
@@ -1344,7 +1419,7 @@ export function createGateway(options: GatewayOptions): Gateway {
1344
1419
  path: "/a/:artifactId/_mostra/v/:rev/events/poll",
1345
1420
  intent: "stream",
1346
1421
  auth: "session",
1347
- handler: served.poll,
1422
+ handler: served.shellPoll,
1348
1423
  },
1349
1424
  {
1350
1425
  method: "POST",
@@ -1948,6 +2023,12 @@ export function createGateway(options: GatewayOptions): Gateway {
1948
2023
  async openFace(spec) {
1949
2024
  return handleOf(await openFace(spec));
1950
2025
  },
2026
+ dispatch(key, request, response) {
2027
+ const entry = faces.get(key);
2028
+ if (!entry) return false;
2029
+ entry.listener.server.emit("request", request, response);
2030
+ return true;
2031
+ },
1951
2032
  face(key) {
1952
2033
  const entry = faces.get(key);
1953
2034
  return entry ? handleOf(entry) : undefined;
@@ -2117,6 +2198,22 @@ async function verifyDocument(
2117
2198
  * instance still starts, artifact frames are still served, and the shell's pages answer
2118
2199
  * `MOSTRA_ENV_SHELL_MISSING`.
2119
2200
  */
2201
+ /**
2202
+ * Answers a request for one of the shell's own built files (`/_mostra/shell/assets/*`): a remote
2203
+ * server's front serves them on every user-content domain's apex before any hosted home is
2204
+ * known, since they are the same for every route (INTERFACES §18.4).
2205
+ */
2206
+ export async function shellAssetResponse(
2207
+ shellDir: string,
2208
+ request: Request,
2209
+ ): Promise<Response | undefined> {
2210
+ const path = safePath(new URL(request.url).pathname);
2211
+ if (path === undefined || !path.startsWith("/_mostra/shell/assets/")) return undefined;
2212
+ const file = await findFile(shellDir, path.slice("/_mostra/shell".length));
2213
+ if (!file) return undefined;
2214
+ return fileResponse(file, request, { "cache-control": "public, max-age=31536000, immutable" });
2215
+ }
2216
+
2120
2217
  export function locateShell(env: Environment): string | undefined {
2121
2218
  const dir = env["MOSTRA_SHELL_DIR"] ?? resolve(runtimeRoot(), "..", "shell", "dist");
2122
2219
  return existsSync(join(dir, "index.html")) ? dir : undefined;
@@ -24,11 +24,12 @@ import {
24
24
  type RequestIntent,
25
25
  type RequestPolicy,
26
26
  refusal,
27
+ SHELL_SESSION_HEADER,
27
28
  scopeAllows,
28
29
  } from "@mostra/protocol";
29
30
  import type { Context, Hono } from "hono";
30
31
  import type { Log } from "../log.ts";
31
- import type { Capabilities, ResolvedSession } from "./capabilities.ts";
32
+ import type { Capabilities, ResolvedSession, SessionMode } from "./capabilities.ts";
32
33
  import {
33
34
  cookieValues,
34
35
  type HttpEnv,
@@ -92,7 +93,7 @@ export interface ListenerChecks {
92
93
  * How this listener's sessions authenticate (D70): `cookie` (the default), or `worker`, where a
93
94
  * frame's service worker sends the session's secret as `X-Mostra-Frame`.
94
95
  */
95
- readonly mode?: () => "cookie" | "worker";
96
+ readonly mode?: () => SessionMode;
96
97
  /** Whether event streams pass to this listener's browsers; `false` behind a quick tunnel. */
97
98
  readonly streams?: () => boolean;
98
99
  }
@@ -195,11 +196,18 @@ export function mount(
195
196
  artifactId,
196
197
  "worker",
197
198
  )
198
- : checks.capabilities.session(
199
- cookieValues(request.headers.get("cookie"), checks.cookieName()),
200
- policy.origin,
201
- artifactId,
202
- );
199
+ : mode === "header"
200
+ ? checks.capabilities.session(
201
+ [request.headers.get(SHELL_SESSION_HEADER) ?? ""],
202
+ policy.origin,
203
+ artifactId,
204
+ "header",
205
+ )
206
+ : checks.capabilities.session(
207
+ cookieValues(request.headers.get("cookie"), checks.cookieName()),
208
+ policy.origin,
209
+ artifactId,
210
+ );
203
211
  if (isRefusal(resolved)) return refuse(checks, resolved, meta);
204
212
  session = resolved;
205
213
  // 4. The CSRF token of this session.
package/src/gc/index.ts CHANGED
@@ -112,6 +112,20 @@ export const REFERENCE_SOURCES: readonly ReferenceSource[] = [
112
112
  covers: ["view.version_id"],
113
113
  keep: (db) => column<string>(db, "SELECT version_id AS value FROM view"),
114
114
  },
115
+ {
116
+ // A publish waiting to reach a remote server needs its files until it gets there; a relayed
117
+ // run's version is its action run's (WP-29, DATA_MODEL §7.3).
118
+ name: "pushes and relayed runs",
119
+ covers: ["version_push.version_id", "relayed_run.version_id"],
120
+ keep: function* (db) {
121
+ if (!tableExists(db, "version_push")) return;
122
+ yield* column<string>(
123
+ db,
124
+ "SELECT version_id AS value FROM version_push WHERE state = 'pending'",
125
+ );
126
+ yield* column<string>(db, "SELECT version_id AS value FROM relayed_run");
127
+ },
128
+ },
115
129
  {
116
130
  name: "comment threads",
117
131
  covers: ["thread.version_id", "thread.anchor_json"],