@mostra/runtime 0.0.0-placeholder → 0.1.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 (114) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +38 -1
  3. package/dist/bin.d.ts +1 -0
  4. package/dist/bin.js +236 -0
  5. package/dist/bin.js.map +1 -0
  6. package/dist/builder/child/main.d.ts +1 -0
  7. package/dist/builder/child/main.js +1408 -0
  8. package/dist/builder/child/main.js.map +1 -0
  9. package/dist/child-xrHmytks.js +49 -0
  10. package/dist/child-xrHmytks.js.map +1 -0
  11. package/dist/deps/child/install.d.ts +1 -0
  12. package/dist/deps/child/install.js +33 -0
  13. package/dist/deps/child/install.js.map +1 -0
  14. package/dist/index.d.ts +221 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +3 -0
  17. package/dist/instance-D7_UVdoN.js +15752 -0
  18. package/dist/instance-D7_UVdoN.js.map +1 -0
  19. package/dist/types-NjNy7gXX.js +57 -0
  20. package/dist/types-NjNy7gXX.js.map +1 -0
  21. package/package.json +87 -4
  22. package/src/actions/index.ts +622 -0
  23. package/src/addressing/index.ts +281 -0
  24. package/src/bin.ts +240 -0
  25. package/src/builder/child/dev.ts +383 -0
  26. package/src/builder/child/fields.ts +363 -0
  27. package/src/builder/child/main.ts +47 -0
  28. package/src/builder/child/plugins.ts +195 -0
  29. package/src/builder/child/scan.ts +459 -0
  30. package/src/builder/child/spa.ts +348 -0
  31. package/src/builder/coverage.ts +72 -0
  32. package/src/builder/index.ts +406 -0
  33. package/src/builder/types.ts +180 -0
  34. package/src/deps/child/install.ts +30 -0
  35. package/src/deps/index.ts +918 -0
  36. package/src/deps/installer.ts +321 -0
  37. package/src/deps/lock.ts +82 -0
  38. package/src/deps/scan.ts +266 -0
  39. package/src/deps/specifier.ts +64 -0
  40. package/src/deps/warm.ts +57 -0
  41. package/src/dev/index.ts +518 -0
  42. package/src/faults.ts +65 -0
  43. package/src/gate.ts +55 -0
  44. package/src/gateway/actions.ts +268 -0
  45. package/src/gateway/browser.ts +650 -0
  46. package/src/gateway/capabilities.ts +739 -0
  47. package/src/gateway/controls.ts +91 -0
  48. package/src/gateway/dev.ts +119 -0
  49. package/src/gateway/http.ts +229 -0
  50. package/src/gateway/index.ts +1209 -0
  51. package/src/gateway/integrity.ts +117 -0
  52. package/src/gateway/listener.ts +217 -0
  53. package/src/gateway/routes.ts +197 -0
  54. package/src/gateway/serve.ts +138 -0
  55. package/src/gc/index.ts +451 -0
  56. package/src/home/acquire.ts +276 -0
  57. package/src/home/index.ts +16 -0
  58. package/src/home/paths.ts +192 -0
  59. package/src/home/platform.ts +34 -0
  60. package/src/home/record.ts +76 -0
  61. package/src/home/settings.ts +113 -0
  62. package/src/index.ts +30 -0
  63. package/src/instance/index.ts +942 -0
  64. package/src/interaction/ephemeral.ts +300 -0
  65. package/src/interaction/events.ts +355 -0
  66. package/src/interaction/fields.ts +392 -0
  67. package/src/interaction/index.ts +1009 -0
  68. package/src/interaction/outbox.ts +493 -0
  69. package/src/interaction/policy.ts +26 -0
  70. package/src/interaction/results.ts +341 -0
  71. package/src/interaction/runs.ts +313 -0
  72. package/src/interaction/signals.ts +120 -0
  73. package/src/interaction/submissions.ts +585 -0
  74. package/src/interaction/subscriptions.ts +258 -0
  75. package/src/interaction/viewers.ts +173 -0
  76. package/src/interaction/wait.ts +201 -0
  77. package/src/ledger/index.ts +442 -0
  78. package/src/ledger/migrations.ts +583 -0
  79. package/src/ledger/requests.ts +105 -0
  80. package/src/ledger/types.ts +28 -0
  81. package/src/live/index.ts +573 -0
  82. package/src/log.ts +316 -0
  83. package/src/processes/child.ts +67 -0
  84. package/src/processes/environment.ts +64 -0
  85. package/src/processes/identity.ts +191 -0
  86. package/src/processes/index.ts +19 -0
  87. package/src/processes/manager.ts +543 -0
  88. package/src/protocol-server/client.ts +94 -0
  89. package/src/protocol-server/index.ts +91 -0
  90. package/src/protocol-server/server.ts +509 -0
  91. package/src/protocol-server/streams.ts +81 -0
  92. package/src/publish/checks.ts +92 -0
  93. package/src/publish/digest.ts +87 -0
  94. package/src/publish/index.ts +23 -0
  95. package/src/publish/manifest.ts +409 -0
  96. package/src/publish/methods.ts +96 -0
  97. package/src/publish/publisher.ts +913 -0
  98. package/src/publish/source.ts +272 -0
  99. package/src/publish/tar.ts +110 -0
  100. package/src/registry/index.ts +481 -0
  101. package/src/registry/store.ts +136 -0
  102. package/src/secrets/index.ts +223 -0
  103. package/src/service/idle.ts +64 -0
  104. package/src/service/index.ts +3 -0
  105. package/src/service/unit.ts +250 -0
  106. package/src/verify/fields.ts +125 -0
  107. package/src/verify/index.ts +913 -0
  108. package/src/verify/regression.ts +157 -0
  109. package/src/verify/runner.ts +230 -0
  110. package/src/verify/sandbox.ts +407 -0
  111. package/src/verify/typecheck.ts +371 -0
  112. package/src/workers/index.ts +17 -0
  113. package/src/workers/launcher.ts +260 -0
  114. package/src/workers/pool.ts +708 -0
@@ -0,0 +1,1209 @@
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`.
9
+ *
10
+ * ```ts
11
+ * const gateway = createGateway({ ledger, log, addressing, capabilities, artifacts, shellDir });
12
+ * await gateway.start();
13
+ * const { url } = await gateway.defaultLink(artifactId); // the publish receipt's URL
14
+ * ```
15
+ */
16
+ import { existsSync, readFileSync } from "node:fs";
17
+ import { readFile } from "node:fs/promises";
18
+ import type { IncomingMessage } from "node:http";
19
+ import { join, resolve } from "node:path";
20
+ import type { Duplex } from "node:stream";
21
+ import {
22
+ type ArtifactDetail,
23
+ ArtifactId,
24
+ type ArtifactRef,
25
+ BROWSER_PROTOCOL_REVISIONS,
26
+ type CapabilityLink,
27
+ type CapabilityScope,
28
+ type ControlsPolicy,
29
+ createDiagnostic,
30
+ type Diagnostic,
31
+ durationMs,
32
+ type FrameTicket,
33
+ type Refusal,
34
+ RpcError,
35
+ refusal,
36
+ safePath,
37
+ scopeAllows,
38
+ viewDefaultMethod,
39
+ viewLaunchMethod,
40
+ viewRevokeMethod,
41
+ viewRotateMethod,
42
+ viewUrlMethod,
43
+ } from "@mostra/protocol";
44
+ import type { Actions } from "../actions/index.ts";
45
+ import type { Addressing } from "../addressing/index.ts";
46
+ import { runtimeRoot } from "../deps/index.ts";
47
+ import type { EphemeralBus, Interaction } from "../interaction/index.ts";
48
+ import {
49
+ type Ledger,
50
+ type LedgerDb,
51
+ type RequestKey,
52
+ recordedResult,
53
+ recordResult,
54
+ requestKey,
55
+ } from "../ledger/index.ts";
56
+ import type { Live } from "../live/index.ts";
57
+ import type { Environment, Log } from "../log.ts";
58
+ import { handler, type MethodHandler } from "../protocol-server/index.ts";
59
+ import { type ActionRoutes, actionRoutes } from "./actions.ts";
60
+ import { type BrowserRoutes, type BrowserRoutesOptions, browserRoutes } from "./browser.ts";
61
+ import {
62
+ type Capabilities,
63
+ type Grant,
64
+ type MintedToken,
65
+ SESSION_MAX_AGE_S,
66
+ } from "./capabilities.ts";
67
+ import { type DevUpstream, devFetch, devUpgrade } from "./dev.ts";
68
+ import {
69
+ BASE_HEADERS,
70
+ cookieValues,
71
+ documentHeaders,
72
+ isRefusal,
73
+ jsonResponse,
74
+ type ListenerKind,
75
+ readJsonObject,
76
+ refusalResponse,
77
+ sessionCookie,
78
+ } from "./http.ts";
79
+ import { versionIntegrity } from "./integrity.ts";
80
+ import { createListener, type Listener } from "./listener.ts";
81
+ import { type ListenerChecks, mount, type RouteContext, type RouteSpec, refuse } from "./routes.ts";
82
+ import { fileResponse, findFile } from "./serve.ts";
83
+
84
+ export { Capabilities, capabilityKey } from "./capabilities.ts";
85
+ export { CONTROLS_POLICY_TIMEOUT_MS, controlsPolicy } from "./controls.ts";
86
+ export type { DevUpstream } from "./dev.ts";
87
+
88
+ /** What the gateway reads about artifacts and versions. */
89
+ export interface GatewayArtifacts {
90
+ /** An artifact in full; throws `MOSTRA_ARTIFACT_NOT_FOUND` for an unknown one. */
91
+ get(ref: ArtifactRef): ArtifactDetail;
92
+ /** The directory of a published version (`versions/<id>`). */
93
+ versionDir(versionId: string): string;
94
+ /** What is wrong with a version's stored files, or `undefined` when they match their digest. */
95
+ damage(versionId: string): Promise<string | undefined>;
96
+ }
97
+
98
+ /** Options for {@link createGateway}. */
99
+ export interface GatewayOptions {
100
+ readonly ledger: Ledger;
101
+ readonly log: Log;
102
+ readonly addressing: Addressing;
103
+ readonly capabilities: Capabilities;
104
+ readonly artifacts: GatewayArtifacts;
105
+ /** The shell's built files, or `undefined` when the runtime lacks them (`MOSTRA_ENV_SHELL_MISSING`). */
106
+ readonly shellDir: string | undefined;
107
+ /** The interaction core the browser protocol's routes hand their work to (WP-06). */
108
+ readonly interaction: Interaction;
109
+ /**
110
+ * The submit channels and trusted controls in force for a new view of an artifact (D108): the
111
+ * `trustedControls` port's answer, the home's `submitChannels`, or both channels.
112
+ */
113
+ readonly controls: (artifact: ArtifactDetail) => Promise<ControlsPolicy>;
114
+ /** Tells hosts with a `trustedControls` port that a trusted control was used (D108). */
115
+ readonly activated: BrowserRoutesOptions["activated"];
116
+ /** The browser-protocol revisions served; `BROWSER_PROTOCOL_REVISIONS` unless a test adds one. */
117
+ readonly revisions?: readonly string[];
118
+ /**
119
+ * Server functions and live data (WP-08): plain calls, action runs and live sources. Absent,
120
+ * their routes answer 501 behind their checks, as before WP-08.
121
+ */
122
+ readonly actions?: Actions;
123
+ readonly live?: Live;
124
+ /** Run and live updates for page streams and polls (WP-08). */
125
+ readonly bus?: EphemeralBus;
126
+ /** Whether a version's worker is parked (WP-08): its frame ticket tells the shell. */
127
+ readonly parked?: (versionId: string) => boolean;
128
+ /**
129
+ * The delivery target the gateway serves pages for (D111): `live` for viewers, `verify` for a
130
+ * verify run's sandbox (D138), whose tickets name it and whose documents get
131
+ * `<meta name="mostra-target" content="verify">` as they are served. The stored build never
132
+ * holds the tag, so what publish promotes is byte-identical to what verify built.
133
+ */
134
+ readonly target?: "live" | "verify";
135
+ /**
136
+ * `mostra dev`'s sandbox (D140 item 12): the artifact origin's files and its HMR WebSocket come
137
+ * from the session's Vite server, behind the same checks, and frame tickets say the page is a
138
+ * development preview. `upstream` is where that server listens now.
139
+ */
140
+ readonly dev?: { readonly upstream: () => DevUpstream | undefined };
141
+ }
142
+
143
+ /** The gateway of one instance. */
144
+ export interface Gateway {
145
+ /** Binds the shell's port and every leased artifact port (D99). */
146
+ start(): Promise<void>;
147
+ /** The shell's origin. */
148
+ readonly shellOrigin: () => string;
149
+ /** The artifact's default link (D97 item 3), shown again or minted: the publish receipt's URL. */
150
+ defaultLink(artifactId: string): { readonly url: string; readonly tokenId: string };
151
+ /**
152
+ * Mints a link with every scope, for a version only when `version` names its number (D97
153
+ * item 9): what `view/url` mints, for callers inside the instance (a verify run's sandbox).
154
+ */
155
+ link(input: { readonly artifactId: string; readonly version?: number }): string;
156
+ /** The handlers of `view/url`, `view/rotate` and `view/revoke`. */
157
+ methods(): MethodHandler[];
158
+ /** The origins of the artifact listeners that are bound, by artifact ID. */
159
+ artifactOrigins(): ReadonlyMap<string, string>;
160
+ /** Stops every listener. */
161
+ close(): Promise<void>;
162
+ }
163
+
164
+ /** A frame ticket's answer to the shell: the view it opens and its controls (D104, D108). */
165
+ type TicketAnswer = FrameTicket;
166
+
167
+ const NO_STORE = { "cache-control": "no-store" };
168
+
169
+ /** How recently an artifact must have been viewed for its port to be bound at start (D129). */
170
+ const RECENT_VIEW_MS = 7 * 24 * 60 * 60 * 1000;
171
+
172
+ /**
173
+ * The browser-protocol routes of INTERFACES §4 (D96): WP-06 serves `fields`, `submit`, `signal`,
174
+ * `events` and `events/poll`; the others answer 501 until their package attaches a handler.
175
+ */
176
+ function laterArtifactRoutes(served: BrowserRoutes, acting: ActionRoutes | undefined): RouteSpec[] {
177
+ const action = (params: Readonly<Record<string, string>>): CapabilityScope | "any-action" => {
178
+ const id = params["fn"];
179
+ return id ? (`action:${id}` as CapabilityScope) : "any-action";
180
+ };
181
+ return [
182
+ { method: "GET", path: "/_mostra/sw.js", intent: "read", auth: "none" },
183
+ {
184
+ method: "POST",
185
+ path: "/_mostra/v/:rev/fields",
186
+ intent: "mutation",
187
+ auth: "session",
188
+ scope: () => "draft",
189
+ handler: served.fields,
190
+ },
191
+ {
192
+ method: "POST",
193
+ path: "/_mostra/v/:rev/submit",
194
+ intent: "mutation",
195
+ auth: "session",
196
+ scope: () => "submit",
197
+ handler: served.submit,
198
+ },
199
+ {
200
+ method: "POST",
201
+ path: "/_mostra/v/:rev/signal",
202
+ intent: "mutation",
203
+ auth: "session",
204
+ scope: () => "signal",
205
+ handler: served.signal,
206
+ },
207
+ // A function ID may hold `/` (`lib/mail.ts#send`), so the call path takes the rest of the path.
208
+ {
209
+ method: "POST",
210
+ path: "/_mostra/v/:rev/call/:fn{.+}",
211
+ intent: "mutation",
212
+ auth: "session",
213
+ scope: action,
214
+ ...(acting ? { handler: acting.call } : {}),
215
+ },
216
+ {
217
+ method: "POST",
218
+ path: "/_mostra/v/:rev/runs",
219
+ intent: "mutation",
220
+ auth: "session",
221
+ scope: () => "any-action",
222
+ ...(acting ? { handler: acting.runs } : {}),
223
+ },
224
+ // WP-08: read runs and follow them (re-attach), by ID or by function and key.
225
+ {
226
+ method: "POST",
227
+ path: "/_mostra/v/:rev/runs/attach",
228
+ intent: "mutation",
229
+ auth: "session",
230
+ scope: () => "any-action",
231
+ ...(acting ? { handler: acting.attach } : {}),
232
+ },
233
+ {
234
+ method: "POST",
235
+ path: "/_mostra/v/:rev/runs/:run/cancel",
236
+ intent: "mutation",
237
+ auth: "session",
238
+ scope: () => "any-action",
239
+ ...(acting ? { handler: acting.cancel } : {}),
240
+ },
241
+ // WP-08: live sources a page reads and keeps produced; every link may (`view`).
242
+ {
243
+ method: "POST",
244
+ path: "/_mostra/v/:rev/live",
245
+ intent: "mutation",
246
+ auth: "session",
247
+ ...(acting ? { handler: acting.live } : {}),
248
+ },
249
+ { method: "POST", path: "/_mostra/v/:rev/ticket", intent: "mutation", auth: "session" },
250
+ {
251
+ method: "GET",
252
+ path: "/_mostra/v/:rev/events",
253
+ intent: "stream",
254
+ auth: "session",
255
+ handler: served.stream,
256
+ },
257
+ {
258
+ method: "GET",
259
+ path: "/_mostra/v/:rev/events/poll",
260
+ intent: "stream",
261
+ auth: "session",
262
+ handler: served.poll,
263
+ },
264
+ ];
265
+ }
266
+
267
+ /** Creates the gateway; nothing is bound until {@link Gateway.start}. */
268
+ export function createGateway(options: GatewayOptions): Gateway {
269
+ const { addressing, capabilities, artifacts, log, interaction } = options;
270
+ const served = browserRoutes({
271
+ interaction,
272
+ capabilities,
273
+ log,
274
+ versionOf: (artifactId, number) => {
275
+ const found = artifacts.get({ artifactId }).versions.find((v) => v.number === number);
276
+ return found
277
+ ? {
278
+ id: found.id,
279
+ number: found.number,
280
+ ...(found.collected !== undefined ? { collected: found.collected } : {}),
281
+ }
282
+ : undefined;
283
+ },
284
+ activated: options.activated,
285
+ ...(options.revisions ? { revisions: options.revisions } : {}),
286
+ ...(options.bus ? { bus: options.bus } : {}),
287
+ });
288
+ const acting: ActionRoutes | undefined =
289
+ options.actions && options.live
290
+ ? actionRoutes({
291
+ interaction,
292
+ actions: options.actions,
293
+ live: options.live,
294
+ log,
295
+ revisions: options.revisions ?? BROWSER_PROTOCOL_REVISIONS,
296
+ })
297
+ : undefined;
298
+ let shellPort: number | undefined;
299
+ const shellOrigin = (): string => {
300
+ if (shellPort === undefined) throw new Error("The gateway hasn't started.");
301
+ return addressing.origin(shellPort);
302
+ };
303
+ const artifactListeners = new Map<
304
+ string,
305
+ { readonly listener: Listener; readonly port: number }
306
+ >();
307
+ const opening = new Map<string, Promise<number>>();
308
+ const integrity = versionIntegrity(artifacts, log);
309
+
310
+ /** The answer for a damaged version: a plain page for a navigation, else the diagnostic. */
311
+ const damaged = (number: number | undefined, damage: string, document: boolean): Response =>
312
+ refusalResponse(
313
+ {
314
+ status: 500,
315
+ diagnostic: createDiagnostic("MOSTRA_HOME_INTEGRITY", {
316
+ message: `${number === undefined ? "A version" : `Version ${number}`} of this artifact is damaged: ${damage}.`,
317
+ }),
318
+ },
319
+ { document, frameAncestors: shellOrigin() },
320
+ );
321
+
322
+ const link = (token: MintedToken): CapabilityLink => ({
323
+ url: `${shellOrigin()}/a/${token.artifactId}${token.pinnedVersion !== undefined ? `/v/${token.pinnedVersion}` : ""}#t=${token.secret}`,
324
+ tokenId: token.tokenId,
325
+ scopes: token.scopes,
326
+ ...(token.expiresAt !== undefined ? { expiresAt: token.expiresAt } : {}),
327
+ ...(token.viewerId !== undefined ? { viewer: interaction.viewer(token.viewerId) } : {}),
328
+ });
329
+
330
+ /** The version a request names (number or ID), or the latest; `undefined` when there is none. */
331
+ const versionOf = (
332
+ detail: ArtifactDetail,
333
+ wanted: number | string | undefined,
334
+ ): { readonly id: string; readonly number: number; readonly collected?: string } | undefined => {
335
+ const found =
336
+ wanted === undefined
337
+ ? (detail.latestVersion ?? detail.versions[0])
338
+ : detail.versions.find((version) =>
339
+ typeof wanted === "number" ? version.number === wanted : version.id === wanted,
340
+ );
341
+ return found
342
+ ? {
343
+ id: found.id,
344
+ number: found.number,
345
+ ...(found.collected !== undefined ? { collected: found.collected } : {}),
346
+ }
347
+ : undefined;
348
+ };
349
+
350
+ // ── The shell ────────────────────────────────────────────────────────────────────────────
351
+
352
+ const shellKind = (): ListenerKind => ({
353
+ kind: "shell",
354
+ origin: shellOrigin(),
355
+ shellOrigin: shellOrigin(),
356
+ });
357
+ const shellChecks: ListenerChecks = {
358
+ policy: () => ({ origin: shellOrigin(), hosts: addressing.hosts(shellPort ?? 0) }),
359
+ capabilities,
360
+ log,
361
+ cookieName: () => `mostra-${shellPort}`,
362
+ frameAncestors: () => "'none'",
363
+ artifactOf: (params) => {
364
+ const id = params["artifactId"];
365
+ return id !== undefined && ArtifactId.is(id) ? id : undefined;
366
+ },
367
+ };
368
+
369
+ const shellMissing = (): Response =>
370
+ jsonResponse(
371
+ createDiagnostic("MOSTRA_ENV_SHELL_MISSING", {
372
+ message: "This Mostra runtime has no built shell.",
373
+ }),
374
+ { status: 503 },
375
+ );
376
+
377
+ /** The shell's page: the same for every artifact; it learns everything from its session. */
378
+ const shellPage = (context: RouteContext): Response => {
379
+ if (options.shellDir === undefined) return shellMissing();
380
+ if (context.artifactId === undefined) {
381
+ return refuse(
382
+ shellChecks,
383
+ refusal("MOSTRA_HYGIENE_NOT_SERVED", "No artifact is named at this path."),
384
+ {
385
+ method: context.request.method,
386
+ path: new URL(context.request.url).pathname,
387
+ document: true,
388
+ },
389
+ );
390
+ }
391
+ const html = readFileSync(join(options.shellDir, "index.html"));
392
+ return new Response(context.request.method === "HEAD" ? null : html, {
393
+ headers: {
394
+ ...BASE_HEADERS,
395
+ ...documentHeaders(shellKind(), `http://${addressing.urlHost}:*`),
396
+ "content-type": "text/html; charset=utf-8",
397
+ "cache-control": "no-cache",
398
+ },
399
+ });
400
+ };
401
+
402
+ const shellAsset = async (context: RouteContext): Promise<Response> => {
403
+ if (options.shellDir === undefined) return shellMissing();
404
+ const url = new URL(context.request.url);
405
+ const path = safePath(url.pathname)?.slice("/_mostra/shell".length) ?? "";
406
+ const file = path.startsWith("/assets/") ? await findFile(options.shellDir, path) : undefined;
407
+ if (!file) {
408
+ return refuse(
409
+ shellChecks,
410
+ refusal("MOSTRA_HYGIENE_NOT_SERVED", "No shell file at this path."),
411
+ {
412
+ method: context.request.method,
413
+ path: url.pathname,
414
+ document: false,
415
+ },
416
+ );
417
+ }
418
+ return fileResponse(file, context.request, {
419
+ ...documentHeaders(shellKind(), `http://${addressing.urlHost}:*`),
420
+ "cache-control": "public, max-age=31536000, immutable",
421
+ });
422
+ };
423
+
424
+ /** What a link allows, as the shell shows it when two links meet. */
425
+ const access = (grant: Grant) => ({
426
+ scopes: grant.scopes,
427
+ ...(grant.expiresAt !== undefined ? { expiresAt: grant.expiresAt } : {}),
428
+ ...(grant.pinnedVersion !== undefined ? { version: grant.pinnedVersion } : {}),
429
+ });
430
+
431
+ /** The session's facts, for the shell and the frame alike. */
432
+ const sessionFacts = (artifactId: string, grant: Grant) => {
433
+ const detail = artifacts.get({ artifactId });
434
+ return { artifact: { id: detail.id, title: detail.title }, ...access(grant) };
435
+ };
436
+
437
+ const exchange = async (context: RouteContext): Promise<Response> => {
438
+ const artifactId = context.artifactId as string;
439
+ const meta = { method: "POST", path: new URL(context.request.url).pathname, document: false };
440
+ const body = await readJsonObject(context.request);
441
+ if (isRefusal(body)) return refuse(shellChecks, body, meta);
442
+ // A link's token, or a one-time launch ticket from `mostra open` (D140 item 15), which is
443
+ // spent only once it started (or reused) a session.
444
+ const launch = body["token"] === undefined && body["launch"] !== undefined;
445
+ const grant = launch
446
+ ? capabilities.presentLaunch(body["launch"], artifactId, false)
447
+ : capabilities.presentToken(body["token"], artifactId);
448
+ if (isRefusal(grant)) return refuse(shellChecks, grant, meta);
449
+ // A live session from another link is never replaced silently (D98 item 8): a page elsewhere
450
+ // could send the viewer to its own, narrower link and take over their tabs.
451
+ const existing = capabilities.session(
452
+ cookieValues(context.request.headers.get("cookie"), shellChecks.cookieName()),
453
+ shellOrigin(),
454
+ artifactId,
455
+ );
456
+ if (!isRefusal(existing)) {
457
+ if (existing.grant.tokenId === grant.tokenId) {
458
+ if (launch) capabilities.spendLaunch(body["launch"]);
459
+ return jsonResponse({ csrf: existing.csrf, ...sessionFacts(artifactId, existing.grant) });
460
+ }
461
+ if (body["replace"] !== true) {
462
+ log.info("gateway.session_conflict", { artifactId, origin: shellOrigin() });
463
+ return jsonResponse(
464
+ {
465
+ ...refusal(
466
+ "MOSTRA_HYGIENE_SESSION_CONFLICT",
467
+ "This browser already has this artifact open from another link.",
468
+ ).diagnostic,
469
+ current: access(existing.grant),
470
+ offered: access(grant),
471
+ },
472
+ { status: 409 },
473
+ );
474
+ }
475
+ }
476
+ const session = capabilities.createSession({ tokenId: grant.tokenId, origin: shellOrigin() });
477
+ if (launch) capabilities.spendLaunch(body["launch"]);
478
+ log.info("gateway.session_started", {
479
+ origin: shellOrigin(),
480
+ artifactId,
481
+ tokenId: grant.tokenId,
482
+ });
483
+ return jsonResponse(
484
+ { csrf: session.csrf, ...sessionFacts(artifactId, grant) },
485
+ {
486
+ headers: {
487
+ "set-cookie": sessionCookie(
488
+ shellChecks.cookieName(),
489
+ session.cookie,
490
+ `/a/${artifactId}`,
491
+ SESSION_MAX_AGE_S,
492
+ ),
493
+ },
494
+ },
495
+ );
496
+ };
497
+
498
+ const readShellSession = (context: RouteContext): Response => {
499
+ const session = context.session;
500
+ if (!session || context.artifactId === undefined)
501
+ throw new Error("session route without a session");
502
+ return jsonResponse({ csrf: session.csrf, ...sessionFacts(context.artifactId, session.grant) });
503
+ };
504
+
505
+ const ticket = async (context: RouteContext): Promise<Response> => {
506
+ const session = context.session;
507
+ const artifactId = context.artifactId;
508
+ if (!session || artifactId === undefined) throw new Error("session route without a session");
509
+ const meta = { method: "POST", path: new URL(context.request.url).pathname, document: false };
510
+ const body = await readJsonObject(context.request);
511
+ if (isRefusal(body)) return refuse(shellChecks, body, meta);
512
+ const asked = body["version"];
513
+ if (asked !== undefined && !(Number.isSafeInteger(asked) && (asked as number) >= 1)) {
514
+ return refuse(
515
+ shellChecks,
516
+ refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", "`version` must be a version number."),
517
+ meta,
518
+ );
519
+ }
520
+ const pinned = session.grant.pinnedVersion;
521
+ // A link that names a version opens that version only (D97 item 9).
522
+ if (pinned !== undefined && asked !== undefined && asked !== pinned) {
523
+ return refuse(
524
+ shellChecks,
525
+ refusal("MOSTRA_HYGIENE_SCOPE_DENIED", `This link opens version ${pinned} only.`),
526
+ meta,
527
+ );
528
+ }
529
+ const detail = artifacts.get({ artifactId });
530
+ const version = versionOf(detail, (asked as number | undefined) ?? pinned);
531
+ const latest = versionOf(detail, undefined);
532
+ if (!version || !latest) {
533
+ return jsonResponse(
534
+ createDiagnostic("MOSTRA_ARTIFACT_VERSION_NOT_FOUND", {
535
+ message:
536
+ `This artifact has no version ${asked ?? session.grant.pinnedVersion ?? ""}.`.replace(
537
+ " .",
538
+ ".",
539
+ ),
540
+ }),
541
+ { status: 404 },
542
+ );
543
+ }
544
+ // A collected version's files are gone until its source is published again (D140 item 14).
545
+ if (version.collected !== undefined) {
546
+ return jsonResponse(collectedDiagnostic(version.number), { status: 410 });
547
+ }
548
+ // A damaged version is never shown (FAILURE_MODEL §3).
549
+ // A dev preview has no stored build to check: Vite serves the source (D140 item 12).
550
+ const damage = options.dev ? undefined : await integrity.check(version.id);
551
+ if (damage !== undefined) return damaged(version.number, damage, false);
552
+ const port = await openArtifact(artifactId);
553
+ const artifactOrigin = addressing.origin(port);
554
+ if (addressing.frameMode(shellOrigin(), artifactOrigin) === "worker") {
555
+ // Cross-site frames use worker mode (D70), which WP-13 builds; nothing here pretends otherwise.
556
+ return refuse(
557
+ shellChecks,
558
+ refusal("MOSTRA_HYGIENE_NOT_SERVED", "Cross-site frame sessions arrive with sharing.", 501),
559
+ meta,
560
+ );
561
+ }
562
+ const value = capabilities.mintTicket({
563
+ tokenId: session.grant.tokenId,
564
+ artifactId,
565
+ versionId: version.id,
566
+ origin: artifactOrigin,
567
+ shellOrigin: shellOrigin(),
568
+ shellSessionId: session.id,
569
+ });
570
+ // One frame load is one view, of exactly this version, by this link's viewer (D104), with
571
+ // the channels and controls in force for it (D108).
572
+ const controls = await options.controls(detail);
573
+ const viewerId = interaction.viewerOf(session.grant.viewerId);
574
+ const viewId = interaction.openView({
575
+ artifactId,
576
+ versionId: version.id,
577
+ viewerId,
578
+ tokenId: session.grant.tokenId,
579
+ controls,
580
+ });
581
+ const answer: TicketAnswer = {
582
+ artifactId,
583
+ viewId,
584
+ src: `${artifactOrigin}/_mostra/enter?ticket=${value}`,
585
+ artifactOrigin,
586
+ version,
587
+ latest,
588
+ policy: detail.policy ?? { policy: "once", scope: "per-artifact" },
589
+ submitChannels: controls.submitChannels,
590
+ // What the shell offers this link: a control its scopes can't use isn't shown (D97).
591
+ controls: (controls.controls ?? ["submit", "choose", "approve"]).filter((control) =>
592
+ control === "submit"
593
+ ? scopeAllows(session.grant.scopes, "submit")
594
+ : control === "choose"
595
+ ? scopeAllows(session.grant.scopes, "review")
596
+ : true,
597
+ ),
598
+ target: options.target ?? "live",
599
+ follow: interaction.following({ artifactId, viewerId }),
600
+ pinned: pinned !== undefined,
601
+ ...(options.parked?.(version.id) ? { serverParked: true as const } : {}),
602
+ ...(options.dev ? { devPreview: true as const } : {}),
603
+ };
604
+ return jsonResponse(answer);
605
+ };
606
+
607
+ const shellRoutes: RouteSpec[] = [
608
+ { method: "GET", path: "/a/:artifactId", intent: "read", auth: "none", handler: shellPage },
609
+ { method: "GET", path: "/a/:artifactId/", intent: "read", auth: "none", handler: shellPage },
610
+ {
611
+ method: "GET",
612
+ path: "/a/:artifactId/v/:number{[1-9][0-9]{0,8}}",
613
+ intent: "read",
614
+ auth: "none",
615
+ handler: shellPage,
616
+ },
617
+ { method: "GET", path: "/_mostra/shell/*", intent: "read", auth: "none", handler: shellAsset },
618
+ {
619
+ method: "POST",
620
+ path: "/a/:artifactId/_mostra/session",
621
+ intent: "exchange",
622
+ auth: "none",
623
+ tokenPath: true,
624
+ handler: exchange,
625
+ },
626
+ {
627
+ method: "GET",
628
+ path: "/a/:artifactId/_mostra/session",
629
+ intent: "read",
630
+ auth: "session",
631
+ handler: readShellSession,
632
+ },
633
+ {
634
+ method: "POST",
635
+ path: "/a/:artifactId/_mostra/ticket",
636
+ intent: "mutation",
637
+ auth: "session",
638
+ handler: ticket,
639
+ },
640
+ // The trusted controls, the version banner's sources and follow (WP-07), and review
641
+ // (WP-20), behind the shell's session (D96). The specific routes come before the wildcard.
642
+ {
643
+ method: "POST",
644
+ path: "/a/:artifactId/_mostra/v/:rev/submit",
645
+ intent: "mutation",
646
+ auth: "session",
647
+ scope: () => "submit",
648
+ handler: served.shellSubmit,
649
+ },
650
+ {
651
+ method: "POST",
652
+ path: "/a/:artifactId/_mostra/v/:rev/review/choose",
653
+ intent: "mutation",
654
+ auth: "session",
655
+ scope: () => "review",
656
+ handler: served.choose,
657
+ },
658
+ {
659
+ method: "POST",
660
+ path: "/a/:artifactId/_mostra/v/:rev/follow",
661
+ intent: "mutation",
662
+ auth: "session",
663
+ handler: served.follow,
664
+ },
665
+ {
666
+ method: "GET",
667
+ path: "/a/:artifactId/_mostra/v/:rev/carry",
668
+ intent: "read",
669
+ auth: "session",
670
+ handler: served.carry,
671
+ },
672
+ {
673
+ method: "GET",
674
+ path: "/a/:artifactId/_mostra/v/:rev/events",
675
+ intent: "stream",
676
+ auth: "session",
677
+ handler: served.stream,
678
+ },
679
+ {
680
+ method: "GET",
681
+ path: "/a/:artifactId/_mostra/v/:rev/events/poll",
682
+ intent: "stream",
683
+ auth: "session",
684
+ handler: served.poll,
685
+ },
686
+ {
687
+ method: "POST",
688
+ path: "/a/:artifactId/_mostra/v/:rev/review/*",
689
+ intent: "mutation",
690
+ auth: "session",
691
+ scope: () => "review",
692
+ },
693
+ ];
694
+
695
+ // ── Artifacts ────────────────────────────────────────────────────────────────────────────
696
+
697
+ const artifactRoutes = (artifactId: string, port: () => number): RouteSpec[] => {
698
+ const origin = (): string => addressing.origin(port());
699
+ const kind = (): ListenerKind => ({
700
+ kind: "artifact",
701
+ origin: origin(),
702
+ shellOrigin: shellOrigin(),
703
+ });
704
+ const checks = (): ListenerChecks => artifactChecks(artifactId, port);
705
+
706
+ const enter = (context: RouteContext): Response => {
707
+ const url = new URL(context.request.url);
708
+ const meta = { method: "GET", path: url.pathname, document: true };
709
+ // A frame enters from its shell, which is same-site. A page elsewhere can navigate a hidden
710
+ // frame here with junk tickets; its entries are refused before redeeming, so they never
711
+ // count towards the guessing limit and can't lock real viewers out (D97 item 8).
712
+ if (context.request.headers.get("sec-fetch-site") === "cross-site") {
713
+ return refuse(
714
+ checks(),
715
+ refusal("MOSTRA_HYGIENE_ORIGIN_REFUSED", "A frame enters only from its shell."),
716
+ meta,
717
+ );
718
+ }
719
+ const redeemed = capabilities.redeemTicket(url.searchParams.get("ticket"), origin());
720
+ if (isRefusal(redeemed)) return refuse(checks(), redeemed, meta);
721
+ if (redeemed.artifactId !== artifactId) {
722
+ return refuse(
723
+ checks(),
724
+ refusal("MOSTRA_HYGIENE_TOKEN_INVALID", "The ticket is for another artifact."),
725
+ meta,
726
+ );
727
+ }
728
+ const headers: Record<string, string> = { ...BASE_HEADERS, ...NO_STORE, location: "/" };
729
+ // A frame that has a session from the same link keeps it and switches version (D98 item 5).
730
+ const existing = capabilities.session(
731
+ cookieValues(context.request.headers.get("cookie"), checks().cookieName()),
732
+ origin(),
733
+ artifactId,
734
+ );
735
+ if (!isRefusal(existing) && existing.grant.tokenId === redeemed.tokenId) {
736
+ capabilities.enterVersion(existing.id, redeemed.versionId);
737
+ } else {
738
+ const session = capabilities.createSession({
739
+ tokenId: redeemed.tokenId,
740
+ origin: origin(),
741
+ versionId: redeemed.versionId,
742
+ });
743
+ headers["set-cookie"] = sessionCookie(
744
+ checks().cookieName(),
745
+ session.cookie,
746
+ "/",
747
+ SESSION_MAX_AGE_S,
748
+ );
749
+ log.info("gateway.session_started", {
750
+ origin: origin(),
751
+ artifactId,
752
+ tokenId: redeemed.tokenId,
753
+ });
754
+ }
755
+ return new Response(null, { status: 303, headers });
756
+ };
757
+
758
+ const frameSession = (context: RouteContext): Response => {
759
+ const session = context.session;
760
+ if (!session) throw new Error("session route without a session");
761
+ const detail = artifacts.get({ artifactId });
762
+ const version = detail.versions.find((entry) => entry.id === session.versionId);
763
+ return jsonResponse({
764
+ csrf: session.csrf,
765
+ artifactId,
766
+ shellOrigin: shellOrigin(),
767
+ scopes: session.grant.scopes,
768
+ // The viewer the page acts as, so edits made before its first snapshot are journaled
769
+ // under it (WP-07; Claude review finding 4).
770
+ viewer: interaction.viewer(interaction.viewerOf(session.grant.viewerId)),
771
+ ...(version ? { version: { id: version.id, number: version.number } } : {}),
772
+ });
773
+ };
774
+
775
+ const files = async (context: RouteContext): Promise<Response> => {
776
+ const session = context.session;
777
+ const url = new URL(context.request.url);
778
+ const meta = {
779
+ method: context.request.method,
780
+ path: url.pathname,
781
+ document: context.document,
782
+ };
783
+ // `checkRequest` refused unsafe targets already; an unsafe one here is still never served.
784
+ const path = safePath(url.pathname);
785
+ if (
786
+ path === undefined ||
787
+ !session?.versionId ||
788
+ path === "/_mostra" ||
789
+ path.startsWith("/_mostra/")
790
+ ) {
791
+ return refuse(
792
+ checks(),
793
+ refusal("MOSTRA_HYGIENE_NOT_SERVED", "Nothing is served at this path."),
794
+ meta,
795
+ );
796
+ }
797
+ const headers = { ...documentHeaders(kind(), "") };
798
+ if (options.dev) {
799
+ // A development preview: the session's Vite server answers, never a stored version.
800
+ const upstream = options.dev.upstream();
801
+ if (!upstream) {
802
+ return refuse(
803
+ checks(),
804
+ refusal("MOSTRA_HYGIENE_NOT_SERVED", "The dev server isn't running.", 503),
805
+ meta,
806
+ );
807
+ }
808
+ const answered = await devFetch(upstream, context.request, url.pathname + url.search).catch(
809
+ () => undefined,
810
+ );
811
+ if (!answered) {
812
+ return refuse(
813
+ checks(),
814
+ refusal("MOSTRA_HYGIENE_NOT_SERVED", "The dev server didn't answer.", 502),
815
+ meta,
816
+ );
817
+ }
818
+ // Statuses that carry no body (a 304 to a revalidation above all, RFC 9110 §15.4.5).
819
+ const bodiless =
820
+ context.request.method === "HEAD" || [204, 205, 304].includes(answered.status);
821
+ return new Response(bodiless ? null : new Uint8Array(answered.body), {
822
+ status: answered.status,
823
+ headers: { ...answered.headers, ...headers, "cache-control": "no-cache" },
824
+ });
825
+ }
826
+ const root = (versionId: string): string => join(artifacts.versionDir(versionId), "client");
827
+ const versionId = session.versionId;
828
+ let file = await findFile(root(versionId), path);
829
+ let from = versionId;
830
+ // Content-hashed chunks stay reachable after another tab moved the session on (D98 item 5),
831
+ // from the versions the link may open: a pinned link's own only (D97 item 9).
832
+ if (!file && path.startsWith("/assets/") && session.grant.pinnedVersion === undefined) {
833
+ for (const version of artifacts.get({ artifactId }).versions) {
834
+ if (version.id === versionId) continue;
835
+ file = await findFile(root(version.id), path);
836
+ if (file) {
837
+ from = version.id;
838
+ break;
839
+ }
840
+ }
841
+ }
842
+ // Every file served comes from a version whose stored files match their digest, checked
843
+ // again whenever a file changed since (FAILURE_MODEL §3).
844
+ const checked =
845
+ file ?? (context.document ? await findFile(root(versionId), "/index.html") : undefined);
846
+ if (checked) {
847
+ const damage = await integrity.serve(from, checked);
848
+ if (damage !== undefined) {
849
+ const number = artifacts.get({ artifactId }).versions.find((v) => v.id === from)?.number;
850
+ return damaged(number, damage, context.document);
851
+ }
852
+ }
853
+ if (file && options.target === "verify" && file.path.endsWith(".html")) {
854
+ return verifyDocument(file.path, context.request, {
855
+ ...headers,
856
+ "cache-control": "no-cache",
857
+ });
858
+ }
859
+ if (file) {
860
+ return fileResponse(file, context.request, {
861
+ ...headers,
862
+ "cache-control": path.startsWith("/assets/")
863
+ ? "private, max-age=31536000, immutable"
864
+ : "no-cache",
865
+ });
866
+ }
867
+ // A deep link inside the artifact's routes (D57) gets its page.
868
+ const page = context.document
869
+ ? await findFile(root(session.versionId), "/index.html")
870
+ : undefined;
871
+ if (page && options.target === "verify") {
872
+ return verifyDocument(page.path, context.request, {
873
+ ...headers,
874
+ "cache-control": "no-cache",
875
+ });
876
+ }
877
+ if (page)
878
+ return fileResponse(page, context.request, { ...headers, "cache-control": "no-cache" });
879
+ return refuse(
880
+ checks(),
881
+ refusal("MOSTRA_HYGIENE_NOT_SERVED", "This version has no file at this path."),
882
+ meta,
883
+ );
884
+ };
885
+
886
+ return [
887
+ {
888
+ method: "GET",
889
+ path: "/_mostra/enter",
890
+ intent: "read",
891
+ auth: "none",
892
+ handler: enter,
893
+ },
894
+ {
895
+ method: "GET",
896
+ path: "/_mostra/session",
897
+ intent: "read",
898
+ auth: "session",
899
+ handler: frameSession,
900
+ },
901
+ ...laterArtifactRoutes(served, acting),
902
+ { method: "GET", path: "/*", intent: "read", auth: "session", handler: files },
903
+ ];
904
+ };
905
+
906
+ const artifactChecks = (artifactId: string, port: () => number): ListenerChecks => ({
907
+ policy: () => ({ origin: addressing.origin(port()), hosts: addressing.hosts(port()) }),
908
+ capabilities,
909
+ log,
910
+ cookieName: () => `mostra-${port()}`,
911
+ frameAncestors: () => shellOrigin(),
912
+ artifactOf: () => artifactId,
913
+ });
914
+
915
+ /**
916
+ * The HMR WebSocket of a dev sandbox's artifact origin (D140 item 12): after the listener checked
917
+ * Host and Origin, only a live frame session of this origin reaches the dev server.
918
+ */
919
+ const devSocket =
920
+ (artifactId: string, port: () => number) =>
921
+ (incoming: IncomingMessage, socket: Duplex, head: Buffer): Refusal | undefined => {
922
+ const upstream = options.dev?.upstream();
923
+ if (!upstream)
924
+ return refusal("MOSTRA_HYGIENE_NOT_SERVED", "The dev server isn't running.", 503);
925
+ const cookie = incoming.headers.cookie;
926
+ const session = capabilities.session(
927
+ cookieValues(typeof cookie === "string" ? cookie : null, `mostra-${port()}`),
928
+ addressing.origin(port()),
929
+ artifactId,
930
+ );
931
+ if (isRefusal(session)) return session;
932
+ devUpgrade(upstream, incoming, socket, head);
933
+ return undefined;
934
+ };
935
+
936
+ /** Binds the artifact's listener on its leased port, once; resolves with the port. */
937
+ const openArtifact = (artifactId: string): Promise<number> => {
938
+ const bound = artifactListeners.get(artifactId);
939
+ if (bound) return Promise.resolve(bound.port);
940
+ const pending = opening.get(artifactId);
941
+ if (pending) return pending;
942
+ const started = (async () => {
943
+ let port = 0;
944
+ const listener = createListener({
945
+ policy: () => ({ origin: addressing.origin(port), hosts: addressing.hosts(port) }),
946
+ log,
947
+ frameAncestors: () => shellOrigin(),
948
+ configure: (app) =>
949
+ mount(
950
+ app,
951
+ artifactChecks(artifactId, () => port),
952
+ artifactRoutes(artifactId, () => port),
953
+ ),
954
+ ...(options.dev ? { upgrade: devSocket(artifactId, () => port) } : {}),
955
+ });
956
+ port = await addressing.listen(listener.server, { purpose: "artifact", owner: artifactId });
957
+ artifactListeners.set(artifactId, { listener, port });
958
+ log.info("gateway.artifact_listening", { artifactId, origin: addressing.origin(port) });
959
+ return port;
960
+ })().finally(() => opening.delete(artifactId));
961
+ opening.set(artifactId, started);
962
+ return started;
963
+ };
964
+
965
+ let shellListener: Listener | undefined;
966
+
967
+ // ── View methods ─────────────────────────────────────────────────────────────────────────
968
+
969
+ /**
970
+ * Replays a request recorded with the same parameters (H-03), or runs `fn` and records
971
+ * `{ tokenId }` in the same transaction. The same `requestId` with other parameters is
972
+ * `MOSTRA_HOST_REQUEST_ID_REUSED`, never another link.
973
+ */
974
+ const recorded = (
975
+ key: RequestKey | undefined,
976
+ fn: (db: LedgerDb) => MintedToken,
977
+ ): CapabilityLink => {
978
+ const token = options.ledger.write((db) => {
979
+ if (key !== undefined) {
980
+ const row = recordedResult<{ tokenId: string }>(db, key);
981
+ if (row) return { replay: row.tokenId };
982
+ }
983
+ const minted = fn(db);
984
+ // Only the token ID is recorded: the ledger never holds a link's secret (D97 item 2).
985
+ if (key !== undefined) recordResult(db, key, { tokenId: minted.tokenId });
986
+ return { minted };
987
+ });
988
+ if ("minted" in token) return link(token.minted);
989
+ const shown = capabilities.reveal(token.replay);
990
+ if (!shown) {
991
+ throw new RpcError(
992
+ createDiagnostic("MOSTRA_HYGIENE_TOKEN_REVOKED", {
993
+ message:
994
+ "The link this request created can't be shown again: the home's capability key changed.",
995
+ }),
996
+ );
997
+ }
998
+ return link(shown);
999
+ };
1000
+
1001
+ const fail = (refused: Refusal): never => {
1002
+ throw new RpcError(refused.diagnostic);
1003
+ };
1004
+
1005
+ return {
1006
+ shellOrigin,
1007
+ async start() {
1008
+ const pruned = capabilities.prune();
1009
+ if (pruned > 0) log.info("gateway.sessions_pruned", { count: pruned });
1010
+ shellListener = createListener({
1011
+ policy: () => shellChecks.policy(),
1012
+ log,
1013
+ frameAncestors: () => "'none'",
1014
+ configure: (app) => mount(app, shellChecks, shellRoutes),
1015
+ });
1016
+ shellPort = await addressing.listen(shellListener.server, {
1017
+ purpose: "shell",
1018
+ owner: "shell",
1019
+ });
1020
+ log.info("gateway.listening", { origin: shellOrigin(), bind: addressing.bindAddress });
1021
+ // The ports of artifacts viewed lately are bound now, so their open frames reload after a
1022
+ // restart (D62, FAILURE_MODEL §8). Every other lease stays leased and is bound when its next
1023
+ // frame ticket is issued, so a home with thousands of artifacts holds no thousand listeners
1024
+ // (D129, amending D99); a lease never moves, so links keep their origins.
1025
+ const since = new Date(Date.now() - RECENT_VIEW_MS).toISOString();
1026
+ const recent = new Set(
1027
+ options.ledger.read((db) =>
1028
+ db
1029
+ .all<{ artifact_id: string }>(
1030
+ "SELECT DISTINCT artifact_id FROM view WHERE opened_at >= ?",
1031
+ since,
1032
+ )
1033
+ .map((row) => row.artifact_id),
1034
+ ),
1035
+ );
1036
+ for (const lease of addressing.leases()) {
1037
+ if (lease.purpose !== "artifact" || !recent.has(lease.owner)) continue;
1038
+ try {
1039
+ artifacts.get({ artifactId: lease.owner });
1040
+ } catch {
1041
+ continue;
1042
+ }
1043
+ await openArtifact(lease.owner);
1044
+ }
1045
+ },
1046
+ defaultLink(artifactId) {
1047
+ const { url, tokenId } = link(capabilities.defaultLink(artifactId));
1048
+ return { url, tokenId };
1049
+ },
1050
+ link(input) {
1051
+ return link(
1052
+ capabilities.mint({
1053
+ artifactId: input.artifactId,
1054
+ ...(input.version !== undefined ? { pinnedVersion: input.version } : {}),
1055
+ }),
1056
+ ).url;
1057
+ },
1058
+ methods: () => [
1059
+ handler(viewUrlMethod, (params) => {
1060
+ const detail = artifacts.get(params.artifact);
1061
+ const version = versionOf(detail, params.version);
1062
+ if (!version) {
1063
+ throw new RpcError(
1064
+ createDiagnostic("MOSTRA_ARTIFACT_VERSION_NOT_FOUND", {
1065
+ message:
1066
+ params.version === undefined
1067
+ ? `The artifact ${detail.id} has no published version.`
1068
+ : `The artifact ${detail.id} has no version ${params.version}.`,
1069
+ }),
1070
+ );
1071
+ }
1072
+ if (version.collected !== undefined)
1073
+ throw new RpcError(collectedDiagnostic(version.number));
1074
+ return recorded(requestKey("view/url", params), (db) =>
1075
+ capabilities.mint(
1076
+ {
1077
+ artifactId: detail.id,
1078
+ scopes: params.scopes,
1079
+ ttlMs: params.ttl === undefined ? undefined : durationMs(params.ttl),
1080
+ pinnedVersion: params.version === undefined ? undefined : version.number,
1081
+ viewerId:
1082
+ params.viewer === undefined
1083
+ ? undefined
1084
+ : interaction.viewerForSpec(db, params.viewer),
1085
+ },
1086
+ db,
1087
+ ),
1088
+ );
1089
+ }),
1090
+ handler(viewDefaultMethod, (params) => {
1091
+ const detail = artifacts.get(params.artifact);
1092
+ return link(capabilities.defaultLink(detail.id));
1093
+ }),
1094
+ handler(viewLaunchMethod, (params) => {
1095
+ const minted = capabilities.mintLaunch(params.tokenId);
1096
+ if (minted === undefined) {
1097
+ return fail(
1098
+ refusal(
1099
+ "MOSTRA_HYGIENE_TOKEN_INVALID",
1100
+ `No capability token ${params.tokenId} exists in this home.`,
1101
+ ),
1102
+ );
1103
+ }
1104
+ if (minted === "dead") {
1105
+ return fail(
1106
+ refusal(
1107
+ "MOSTRA_HYGIENE_TOKEN_REVOKED",
1108
+ `The token ${params.tokenId} was revoked, has expired, or was made for another address.`,
1109
+ ),
1110
+ );
1111
+ }
1112
+ const { grant } = minted;
1113
+ return {
1114
+ url: `${shellOrigin()}/a/${grant.artifactId}${grant.pinnedVersion !== undefined ? `/v/${grant.pinnedVersion}` : ""}#l=${minted.ticket}`,
1115
+ expiresAt: minted.expiresAt,
1116
+ };
1117
+ }),
1118
+ handler(viewRotateMethod, (params) =>
1119
+ recorded(requestKey("view/rotate", params), (db) => {
1120
+ const rotated = capabilities.rotate(params.tokenId, db);
1121
+ if (rotated === undefined) {
1122
+ return fail(
1123
+ refusal(
1124
+ "MOSTRA_HYGIENE_TOKEN_INVALID",
1125
+ `No capability token ${params.tokenId} exists in this home.`,
1126
+ ),
1127
+ );
1128
+ }
1129
+ if (rotated === "dead") {
1130
+ return fail(
1131
+ refusal(
1132
+ "MOSTRA_HYGIENE_TOKEN_REVOKED",
1133
+ `The token ${params.tokenId} was revoked or has expired.`,
1134
+ ),
1135
+ );
1136
+ }
1137
+ return rotated;
1138
+ }),
1139
+ ),
1140
+ handler(viewRevokeMethod, (params) => {
1141
+ // Revoking is idempotent by itself, so a retried request needs no record.
1142
+ const outcome = capabilities.revoke(params.tokenId);
1143
+ if (outcome === "unknown") {
1144
+ fail(
1145
+ refusal(
1146
+ "MOSTRA_HYGIENE_TOKEN_INVALID",
1147
+ `No capability token ${params.tokenId} exists in this home.`,
1148
+ ),
1149
+ );
1150
+ }
1151
+ if (outcome === "revoked") log.info("gateway.token_revoked", { tokenId: params.tokenId });
1152
+ return {};
1153
+ }),
1154
+ ],
1155
+ artifactOrigins: () =>
1156
+ new Map(
1157
+ [...artifactListeners].map(([artifactId, entry]) => [
1158
+ artifactId,
1159
+ addressing.origin(entry.port),
1160
+ ]),
1161
+ ),
1162
+ async close() {
1163
+ await Promise.allSettled([...opening.values()]);
1164
+ await Promise.all([
1165
+ shellListener?.close(),
1166
+ ...[...artifactListeners.values()].map((entry) => entry.listener.close()),
1167
+ ]);
1168
+ },
1169
+ };
1170
+ }
1171
+
1172
+ /** The answer for a version `mostra gc` collected (D140 item 14). */
1173
+ function collectedDiagnostic(number: number): Diagnostic {
1174
+ return createDiagnostic("MOSTRA_ARTIFACT_VERSION_COLLECTED", {
1175
+ message: `Version ${number} of this artifact was collected by gc; its files are gone until its source is published again.`,
1176
+ });
1177
+ }
1178
+
1179
+ /** The tag that tells the client runtime it runs for `verify` (D111, D138). */
1180
+ const VERIFY_TARGET_TAG = '<meta name="mostra-target" content="verify" />';
1181
+
1182
+ /**
1183
+ * A version's HTML document as a verify run's sandbox serves it: the stored file with the verify
1184
+ * target's tag added at the start of its head, so the build itself never carries it (D138).
1185
+ */
1186
+ async function verifyDocument(
1187
+ path: string,
1188
+ request: Request,
1189
+ headers: Record<string, string>,
1190
+ ): Promise<Response> {
1191
+ const text = await readFile(path, "utf8");
1192
+ const head = /<head[^>]*>/i.exec(text);
1193
+ const at = head ? head.index + head[0].length : 0;
1194
+ const body = `${text.slice(0, at)}\n ${VERIFY_TARGET_TAG}\n${text.slice(at)}`;
1195
+ return new Response(request.method === "HEAD" ? null : body, {
1196
+ headers: { ...BASE_HEADERS, ...headers, "content-type": "text/html; charset=utf-8" },
1197
+ });
1198
+ }
1199
+
1200
+ /**
1201
+ * Finds the shell's built files: `MOSTRA_SHELL_DIR`, else `shell/dist` beside the runtime package,
1202
+ * as the runtime bundle and this repository lay them out. `undefined` when they're missing: the
1203
+ * instance still starts, artifact frames are still served, and the shell's pages answer
1204
+ * `MOSTRA_ENV_SHELL_MISSING`.
1205
+ */
1206
+ export function locateShell(env: Environment): string | undefined {
1207
+ const dir = env["MOSTRA_SHELL_DIR"] ?? resolve(runtimeRoot(), "..", "shell", "dist");
1208
+ return existsSync(join(dir, "index.html")) ? dir : undefined;
1209
+ }