@mostra/runtime 0.6.2 → 0.8.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.
@@ -0,0 +1,823 @@
1
+ /**
2
+ * Shares (HY-04, HY-05, D158): an artifact opened to viewers beyond this machine through a tunnel
3
+ * the instance drives. A share opens the gateway's faces for its tunnel (D158 item 1), the tunnel
4
+ * tool's processes that forward to them, and a link of its own at the tunnel's shell address
5
+ * (D97 item 10); it ends at its TTL, on `share/stop`, when its link is revoked, or when its tunnel
6
+ * can't continue, and every end revokes its link and stops what only it used.
7
+ *
8
+ * - **Tailnet** (Tailscale Serve): the shell's and each artifact's face keep leased ports, served
9
+ * on the device's name at the same port numbers, so tailnet links survive restarts. Requests
10
+ * carry the tailnet person, who becomes the viewer (D158 item 2).
11
+ * - **Funnel**: the shell on 443 and two artifacts on 8443 and 10000 (D158 item 4), public.
12
+ * - **Cloudflare** quick tunnels: one per face, each a site of its own, so worker-mode frames
13
+ * (D70), and pages long-poll, since quick tunnels hold responses back. A quick tunnel's address
14
+ * dies with its process, so its share ends with it, a restart included.
15
+ *
16
+ * ```ts
17
+ * const shares = createShares({ ledger, log, gateway, capabilities, interaction, artifacts, … });
18
+ * const share = await shares.start({ artifact: { artifactId }, via: "cloudflare", ttl: "1h" });
19
+ * share.url; // https://<random>.trycloudflare.com/a/art_…#t=…
20
+ * ```
21
+ */
22
+ import { join } from "node:path";
23
+ import {
24
+ type ArtifactDetail,
25
+ type ArtifactRef,
26
+ createDiagnostic,
27
+ durationMs,
28
+ PUBLIC_SHARE_DEFAULT_TTL,
29
+ PUBLIC_SHARE_MAX_TTL_MS,
30
+ RpcError,
31
+ type Share,
32
+ ShareId,
33
+ type ShareListParams,
34
+ type ShareStartParams,
35
+ type ShareStartResult,
36
+ type ShareStopParams,
37
+ type ShareVia,
38
+ shareListMethod,
39
+ shareStartMethod,
40
+ shareStopMethod,
41
+ } from "@mostra/protocol";
42
+ import type { Capabilities, FaceHandle, FaceSpec, Gateway } from "../gateway/index.ts";
43
+ import { faceKey } from "../gateway/index.ts";
44
+ import { appendEvent, type Interaction } from "../interaction/index.ts";
45
+ import {
46
+ InflightRequests,
47
+ type Ledger,
48
+ type LedgerDb,
49
+ recordedResult,
50
+ recordResult,
51
+ requestKey,
52
+ } from "../ledger/index.ts";
53
+ import type { Environment, Log } from "../log.ts";
54
+ import type { ProcessManager } from "../processes/index.ts";
55
+ import { handler, type MethodHandler } from "../protocol-server/index.ts";
56
+ import { hostnameResolves, quickTunnel } from "./cloudflare.ts";
57
+ import {
58
+ expose,
59
+ FUNNEL_ARTIFACT_PORTS,
60
+ FUNNEL_SHELL_PORT,
61
+ type TailnetDevice,
62
+ tailnetDevice,
63
+ } from "./tailscale.ts";
64
+ import type { Tunnel } from "./tunnel.ts";
65
+
66
+ /** How often active shares are checked for an expired or revoked link. */
67
+ const SWEEP_MS = 30_000;
68
+
69
+ /** How a tailnet or Funnel tunnel that ended by itself is set up again: after 1, 4 and 16 s. */
70
+ const RESTART_DELAYS_MS: readonly number[] = [1_000, 4_000, 16_000];
71
+
72
+ /** How long a restart keeps trying to set a share up again before ending it (Tailscale starting). */
73
+ const RECOVERY_DELAYS_MS: readonly number[] = [0, 5_000, 15_000, 30_000, 60_000];
74
+
75
+ /** How long a quick tunnel's name may take to appear before its link is handed out anyway. */
76
+ const PROBE_MS = 30_000;
77
+
78
+ /** Options for {@link createShares}. */
79
+ export interface SharesOptions {
80
+ readonly ledger: Ledger;
81
+ readonly log: Log;
82
+ readonly gateway: Gateway;
83
+ readonly capabilities: Capabilities;
84
+ readonly interaction: Interaction;
85
+ readonly artifacts: { get(ref: ArtifactRef): ArtifactDetail };
86
+ readonly processes: ProcessManager;
87
+ /** Where the tools are looked up (`PATH`, `MOSTRA_TAILSCALE`, `MOSTRA_CLOUDFLARED`). */
88
+ readonly environment: Environment;
89
+ /** The tools' own environment: the artifact allowlist (proxies, certificates, `PATH`). */
90
+ readonly toolEnvironment: Environment;
91
+ /** The home's cache, for the quick tunnel's empty configuration. */
92
+ readonly cacheDir: string;
93
+ /** The clock, in milliseconds. */
94
+ readonly now: () => number;
95
+ /** How long a public address is probed before its link goes out; 0 turns probing off (tests). */
96
+ readonly probeMs?: number;
97
+ /** How often active shares are checked for an expired or revoked link (tests shorten it). */
98
+ readonly sweepMs?: number;
99
+ }
100
+
101
+ /** The shares of one instance. */
102
+ export interface Shares {
103
+ /** `share/start`, `share/stop` and `share/list`. */
104
+ methods(): MethodHandler[];
105
+ /** How many shares are active: each keeps a daemon from its idle exit (D133). */
106
+ count(): number;
107
+ /** The active shares, for `instance/status`: without their links, which carry secrets. */
108
+ active(): Share[];
109
+ /** Sets tailnet and Funnel shares up again after a restart, and ends what can't continue. */
110
+ recover(): Promise<void>;
111
+ /** Stops every tunnel; shares stay active in the ledger, for the next start to set up again. */
112
+ close(): Promise<void>;
113
+ }
114
+
115
+ interface ShareRow {
116
+ id: string;
117
+ artifact_id: string;
118
+ via: ShareVia;
119
+ hostname: string;
120
+ token_id: string;
121
+ mode: "cookie" | "worker";
122
+ plan_json: string;
123
+ started_at: string;
124
+ expires_at: string | null;
125
+ stopped_at: string | null;
126
+ stop_reason: string | null;
127
+ }
128
+
129
+ /** One face a share uses, as its plan records it. */
130
+ interface PlannedFace {
131
+ readonly key: string;
132
+ readonly listener: "shell" | "artifact";
133
+ /** The tunnel's external port (Tailscale), or none (Cloudflare). */
134
+ readonly external?: number;
135
+ }
136
+
137
+ interface Plan {
138
+ readonly faces: readonly PlannedFace[];
139
+ }
140
+
141
+ /** A running tunnel and the shares that use it. */
142
+ interface Exposure {
143
+ tunnel: Tunnel;
144
+ readonly refs: Set<string>;
145
+ readonly start: () => Promise<Tunnel>;
146
+ readonly via: ShareVia;
147
+ restarting: boolean;
148
+ }
149
+
150
+ /** Creates the shares of one instance. */
151
+ export function createShares(options: SharesOptions): Shares {
152
+ const { ledger, log, gateway, capabilities, interaction } = options;
153
+ const exposures = new Map<string, Exposure>();
154
+ const timers = new Map<string, ReturnType<typeof setTimeout>>();
155
+ const inflight = new InflightRequests();
156
+ let closed = false;
157
+ let chain: Promise<unknown> = Promise.resolve();
158
+ /** Share starts and stops run one at a time, so refcounts and port plans never race. */
159
+ const serial = <T>(task: () => Promise<T>): Promise<T> => {
160
+ const run = chain.then(task, task);
161
+ chain = run.catch(() => undefined);
162
+ return run;
163
+ };
164
+ const toolContext = {
165
+ processes: options.processes,
166
+ log,
167
+ env: { ...options.toolEnvironment, ...pick(options.environment) },
168
+ };
169
+ const iso = (ms: number): string => new Date(ms).toISOString();
170
+
171
+ const row = (shareId: string): ShareRow | undefined =>
172
+ ledger.read((db) => db.get<ShareRow>("SELECT * FROM share WHERE id = ?", shareId));
173
+
174
+ const toShare = (found: ShareRow): Share => {
175
+ // A share follows its link through rotations (`view/rotate`): its token now.
176
+ const tokenId = capabilities.current(found.token_id);
177
+ const url = found.stopped_at === null ? gateway.reveal(tokenId) : undefined;
178
+ const artifactKey = (JSON.parse(found.plan_json) as Plan).faces.find(
179
+ (face) => face.listener === "artifact",
180
+ )?.key;
181
+ const artifactOrigin =
182
+ found.stopped_at === null && artifactKey !== undefined
183
+ ? gateway.face(artifactKey)?.origin()
184
+ : undefined;
185
+ return {
186
+ shareId: found.id,
187
+ artifactId: found.artifact_id,
188
+ via: found.via,
189
+ ...(url !== undefined ? { url } : {}),
190
+ hostname: found.hostname,
191
+ ...(artifactOrigin !== undefined ? { artifactOrigin } : {}),
192
+ mode: found.mode,
193
+ tokenId,
194
+ startedAt: found.started_at,
195
+ ...(found.expires_at !== null ? { expiresAt: found.expires_at } : {}),
196
+ state: found.stopped_at === null ? "active" : "stopped",
197
+ ...(found.stopped_at !== null ? { stoppedAt: found.stopped_at } : {}),
198
+ ...(found.stop_reason !== null ? { stopReason: found.stop_reason } : {}),
199
+ };
200
+ };
201
+
202
+ const activeRows = (): ShareRow[] =>
203
+ ledger.read((db) =>
204
+ db.all<ShareRow>("SELECT * FROM share WHERE stopped_at IS NULL ORDER BY started_at DESC"),
205
+ );
206
+
207
+ // ── Tunnels ──────────────────────────────────────────────────────────────────────────────
208
+
209
+ /**
210
+ * The tunnel of a face, started for `shareId` or joined when it runs already. A tunnel that
211
+ * ends by itself is set up again (Tailscale, whose address is the device's) or ends every share
212
+ * that used it (Cloudflare, whose address died with it).
213
+ */
214
+ const acquire = async (
215
+ key: string,
216
+ shareId: string,
217
+ via: ShareVia,
218
+ start: () => Promise<Tunnel>,
219
+ ): Promise<Tunnel> => {
220
+ const running = exposures.get(key);
221
+ if (running?.restarting) {
222
+ // Its process ended and is being started again (Opus review of WP-13): a new share never
223
+ // gets a link through a tunnel that isn't there. This runs inside the lifecycle's turn,
224
+ // which the restart waits for, so it can't wait for the restart in turn.
225
+ throw new RpcError(
226
+ createDiagnostic("MOSTRA_SHARE_TUNNEL_FAILED", {
227
+ message:
228
+ "This share's tunnel stopped a moment ago and is being started again; try again in a few seconds.",
229
+ }),
230
+ );
231
+ }
232
+ if (running) {
233
+ running.refs.add(shareId);
234
+ return running.tunnel;
235
+ }
236
+ const tunnel = await start();
237
+ const exposure: Exposure = { tunnel, refs: new Set([shareId]), start, via, restarting: false };
238
+ exposures.set(key, exposure);
239
+ watch(key, exposure);
240
+ return tunnel;
241
+ };
242
+
243
+ const watch = (key: string, exposure: Exposure): void => {
244
+ const current = exposure.tunnel;
245
+ void current.ended.then(async (end) => {
246
+ if (closed || exposures.get(key) !== exposure || exposure.tunnel !== current) return;
247
+ log.warn("share.tunnel_dropped", { key, code: end.code, lines: end.lines.slice(-3) });
248
+ if (exposure.via !== "cloudflare") {
249
+ exposure.restarting = true;
250
+ for (const delay of RESTART_DELAYS_MS) {
251
+ await new Promise((resolve) => setTimeout(resolve, delay));
252
+ if (closed || exposures.get(key) !== exposure) return;
253
+ try {
254
+ // One at a time with starts and stops (GPT review of WP-13): a share stopped while
255
+ // this start was under way must not be left with the tunnel it started.
256
+ const restored = await serial(async () => {
257
+ if (closed || exposures.get(key) !== exposure) return false;
258
+ const tunnel = await exposure.start();
259
+ if (closed || exposures.get(key) !== exposure) {
260
+ await tunnel.stop();
261
+ return false;
262
+ }
263
+ exposure.tunnel = tunnel;
264
+ return true;
265
+ });
266
+ if (!restored) return;
267
+ exposure.restarting = false;
268
+ log.info("share.tunnel_restored", { key });
269
+ watch(key, exposure);
270
+ return;
271
+ } catch (error) {
272
+ log.warn("share.tunnel_restart_failed", { key, error: (error as Error).message });
273
+ }
274
+ }
275
+ }
276
+ // The tunnel can't continue: every share that used it ends, and says why.
277
+ for (const shareId of [...exposure.refs]) {
278
+ await serial(() => stop(shareId, "tunnel")).catch((error: unknown) =>
279
+ log.error("share.stop_failed", { shareId, error }),
280
+ );
281
+ }
282
+ });
283
+ };
284
+
285
+ /** Drops a share's hold on a face's tunnel, stopping it and closing the face when unused. */
286
+ const release = async (key: string, shareId: string): Promise<void> => {
287
+ const exposure = exposures.get(key);
288
+ if (exposure) {
289
+ exposure.refs.delete(shareId);
290
+ if (exposure.refs.size > 0) return;
291
+ exposures.delete(key);
292
+ await exposure.tunnel.stop();
293
+ }
294
+ // Its external port (Funnel's 8443 or 10000) is free for the next share (GPT review of WP-13).
295
+ externalPorts.delete(key);
296
+ // A tailnet face keeps its lease, so the next tailnet share has the same address.
297
+ await gateway.closeFace(key, !key.startsWith("tailnet:"));
298
+ };
299
+
300
+ // ── Starting ─────────────────────────────────────────────────────────────────────────────
301
+
302
+ /** The ttl a share's link gets: public shares 1 hour by default and at most 7 days (D158). */
303
+ const lifetime = (via: ShareVia, ttl: ShareStartParams["ttl"]): number | undefined => {
304
+ if (via === "tailnet") return ttl === undefined ? undefined : durationMs(ttl);
305
+ const ms = durationMs(ttl ?? PUBLIC_SHARE_DEFAULT_TTL);
306
+ if (ms > PUBLIC_SHARE_MAX_TTL_MS) {
307
+ throw new RpcError(
308
+ createDiagnostic("MOSTRA_SHARE_TTL_INVALID", {
309
+ message: `A public share lasts at most 7 days; ${ttl} is longer.`,
310
+ }),
311
+ );
312
+ }
313
+ return ms;
314
+ };
315
+
316
+ /** Opens a face and its tunnel for a share, or joins the ones that run already. */
317
+ const faceFor = async (
318
+ spec: FaceSpec,
319
+ shareId: string,
320
+ tunnel: (face: FaceHandle) => Promise<Tunnel>,
321
+ held: string[],
322
+ ): Promise<FaceHandle> => {
323
+ const face = await gateway.openFace(spec);
324
+ held.push(face.key);
325
+ const running = await acquire(face.key, shareId, spec.by as ShareVia, () => tunnel(face));
326
+ face.setOrigin(running.origin);
327
+ return face;
328
+ };
329
+
330
+ /** Sets up a share's faces and tunnels; on failure releases what it took. */
331
+ const setUp = async (
332
+ shareId: string,
333
+ artifactId: string,
334
+ via: ShareVia,
335
+ planned: Plan | undefined,
336
+ ): Promise<{ shell: FaceHandle; artifact: FaceHandle; plan: Plan; hostname: string }> => {
337
+ const held: string[] = [];
338
+ try {
339
+ if (via === "cloudflare") {
340
+ const group = `cloudflare:${shareId}`;
341
+ const context = { ...toolContext, cacheDir: options.cacheDir };
342
+ const spec = (listener: "shell" | "artifact"): FaceSpec => ({
343
+ by: "cloudflare",
344
+ group,
345
+ listener,
346
+ ...(listener === "artifact" ? { artifactId, mode: "worker" as const } : {}),
347
+ via: "token",
348
+ lease: false,
349
+ streams: false,
350
+ });
351
+ // Both tunnels start at once; both outcomes are awaited before either is judged, so a
352
+ // failure never releases a sibling still starting, whose tunnel would outlive it (GPT
353
+ // review of WP-13).
354
+ const settled = await Promise.allSettled([
355
+ faceFor(
356
+ spec("shell"),
357
+ shareId,
358
+ (face) => quickTunnel(context, { local: face.local, ownerRef: face.key }),
359
+ held,
360
+ ),
361
+ faceFor(
362
+ spec("artifact"),
363
+ shareId,
364
+ (face) => quickTunnel(context, { local: face.local, ownerRef: face.key }),
365
+ held,
366
+ ),
367
+ ]);
368
+ const failed = settled.find((outcome) => outcome.status === "rejected");
369
+ if (failed) throw failed.reason;
370
+ const [shell, artifact] = settled.map(
371
+ (outcome) => (outcome as PromiseFulfilledResult<FaceHandle>).value,
372
+ ) as [FaceHandle, FaceHandle];
373
+ await Promise.all([probe(shell.origin()), probe(artifact.origin())]);
374
+ return {
375
+ shell,
376
+ artifact,
377
+ plan: {
378
+ faces: [
379
+ { key: shell.key, listener: "shell" },
380
+ { key: artifact.key, listener: "artifact" },
381
+ ],
382
+ },
383
+ hostname: new URL(shell.origin() as string).hostname,
384
+ };
385
+ }
386
+ const device = await tailnetDevice(toolContext);
387
+ const ours = (port: number): boolean =>
388
+ [...exposures.entries()].some(
389
+ ([key, exposure]) => exposure.via !== "cloudflare" && planPort(key) === port,
390
+ );
391
+ const free = (port: number): boolean => !device.served.has(port) || ours(port);
392
+ if (via === "tailnet") {
393
+ const spec = (listener: "shell" | "artifact"): FaceSpec => ({
394
+ by: "tailnet",
395
+ group: "tailnet",
396
+ listener,
397
+ ...(listener === "artifact" ? { artifactId } : {}),
398
+ via: "tailnet",
399
+ lease: true,
400
+ });
401
+ const serveAt = (face: FaceHandle): Promise<Tunnel> => {
402
+ if (!free(face.port)) throw portTaken(face.port, "Serve");
403
+ return tailnetTunnel(device, "serve", face.port, face);
404
+ };
405
+ const shell = await faceFor(spec("shell"), shareId, serveAt, held);
406
+ const artifact = await faceFor(spec("artifact"), shareId, serveAt, held);
407
+ return {
408
+ shell,
409
+ artifact,
410
+ plan: {
411
+ faces: [
412
+ { key: shell.key, listener: "shell", external: shell.port },
413
+ { key: artifact.key, listener: "artifact", external: artifact.port },
414
+ ],
415
+ },
416
+ hostname: device.hostname,
417
+ };
418
+ }
419
+ // Funnel: the shell on 443, each artifact on one of the two other ports.
420
+ const spec = (listener: "shell" | "artifact"): FaceSpec => ({
421
+ by: "funnel",
422
+ group: "funnel",
423
+ listener,
424
+ ...(listener === "artifact" ? { artifactId } : {}),
425
+ via: "token",
426
+ // Leased, so a restart reopens its faces on the same local ports and the session cookies
427
+ // their names carry keep working at the same public addresses (GPT review of WP-13).
428
+ lease: true,
429
+ });
430
+ const shellKey = faceKey("funnel", "shell");
431
+ if (!exposures.has(shellKey) && !free(FUNNEL_SHELL_PORT))
432
+ throw portTaken(FUNNEL_SHELL_PORT, "Funnel");
433
+ const shell = await faceFor(
434
+ spec("shell"),
435
+ shareId,
436
+ (face) => tailnetTunnel(device, "funnel", FUNNEL_SHELL_PORT, face),
437
+ held,
438
+ );
439
+ const artifactKey = faceKey("funnel", "artifact", artifactId);
440
+ const plannedPort = planned?.faces.find((face) => face.key === artifactKey)?.external;
441
+ const port =
442
+ planPort(artifactKey) ??
443
+ // The port its recorded plan names (after a restart) when no other face took it, else
444
+ // the first free one.
445
+ [plannedPort, ...FUNNEL_ARTIFACT_PORTS].find(
446
+ (candidate): candidate is number =>
447
+ candidate !== undefined &&
448
+ free(candidate) &&
449
+ ![...externalPorts].some(([key, taken]) => key !== artifactKey && taken === candidate),
450
+ );
451
+ if (port === undefined) {
452
+ throw new RpcError(
453
+ createDiagnostic("MOSTRA_SHARE_PORTS_EXHAUSTED", {
454
+ message: `Tailscale Funnel's ports for artifacts (${FUNNEL_ARTIFACT_PORTS.join(" and ")}) are in use: two artifacts are shared through Funnel already, or this device's own configuration uses them.`,
455
+ }),
456
+ );
457
+ }
458
+ const artifact = await faceFor(
459
+ spec("artifact"),
460
+ shareId,
461
+ (face) => tailnetTunnel(device, "funnel", port, face),
462
+ held,
463
+ );
464
+ return {
465
+ shell,
466
+ artifact,
467
+ plan: {
468
+ faces: [
469
+ { key: shell.key, listener: "shell", external: FUNNEL_SHELL_PORT },
470
+ { key: artifact.key, listener: "artifact", external: port },
471
+ ],
472
+ },
473
+ hostname: device.hostname,
474
+ };
475
+ } catch (error) {
476
+ for (const key of held) await release(key, shareId).catch(() => undefined);
477
+ throw error;
478
+ }
479
+ };
480
+
481
+ /** The external ports of running Tailscale tunnels, by face key. */
482
+ const externalPorts = new Map<string, number>();
483
+ const planPort = (key: string): number | undefined => externalPorts.get(key);
484
+
485
+ const tailnetTunnel = async (
486
+ device: TailnetDevice,
487
+ feature: "serve" | "funnel",
488
+ port: number,
489
+ face: FaceHandle,
490
+ ): Promise<Tunnel> => {
491
+ const tunnel = await expose(toolContext, device, {
492
+ feature,
493
+ port,
494
+ local: face.local,
495
+ ownerRef: face.key,
496
+ });
497
+ externalPorts.set(face.key, port);
498
+ return tunnel;
499
+ };
500
+
501
+ const portTaken = (port: number, feature: string): RpcError =>
502
+ new RpcError(
503
+ createDiagnostic("MOSTRA_SHARE_PORTS_EXHAUSTED", {
504
+ message: `Port ${port} of this device is in use by its own Tailscale ${feature} configuration, which Mostra never takes over.`,
505
+ }),
506
+ );
507
+
508
+ /**
509
+ * Waits until a quick tunnel's name exists at Cloudflare's resolvers, so the link never meets a
510
+ * cached miss on this machine or a viewer's phone; nothing here resolves it before then.
511
+ */
512
+ const probe = async (origin: string | undefined): Promise<void> => {
513
+ const budget = options.probeMs ?? PROBE_MS;
514
+ if (origin === undefined || budget <= 0) return;
515
+ const hostname = new URL(origin).hostname;
516
+ // Only a real quick tunnel's name is new to the world's resolvers.
517
+ if (!hostname.endsWith(".trycloudflare.com")) return;
518
+ if (!(await hostnameResolves(hostname, budget))) {
519
+ log.warn("share.name_unresolved", { hostname, budgetMs: budget });
520
+ }
521
+ };
522
+
523
+ const start = async (params: ShareStartParams): Promise<ShareStartResult> => {
524
+ const detail = options.artifacts.get(params.artifact);
525
+ if (!detail.latestVersion && detail.versions.length === 0) {
526
+ throw new RpcError(
527
+ createDiagnostic("MOSTRA_ARTIFACT_VERSION_NOT_FOUND", {
528
+ message: `The artifact ${detail.id} has no published version to share.`,
529
+ }),
530
+ );
531
+ }
532
+ const key = requestKey("share/start", params);
533
+ if (key !== undefined) {
534
+ const replay = ledger.read((db) => recordedResult<{ shareId: string }>(db, key));
535
+ const found = replay ? row(replay.shareId) : undefined;
536
+ if (found) return withUrl(toShare(found));
537
+ }
538
+ const ttlMs = lifetime(params.via, params.ttl);
539
+ const shareId = ShareId.create();
540
+ const { shell, artifact, plan, hostname } = await setUp(
541
+ shareId,
542
+ detail.id,
543
+ params.via,
544
+ undefined,
545
+ );
546
+ const shellOrigin = shell.origin() as string;
547
+ const startedAt = options.now();
548
+ const record = (): ReturnType<typeof gateway.mintAt> =>
549
+ ledger.write((db) => {
550
+ const viewerId =
551
+ params.viewer === undefined ? undefined : interaction.viewerForSpec(db, params.viewer);
552
+ const link = gateway.mintAt(
553
+ { artifactId: detail.id, shellOrigin, scopes: params.scopes, ttlMs, viewerId },
554
+ db,
555
+ );
556
+ db.run(
557
+ "INSERT INTO share (id, artifact_id, via, hostname, token_id, mode, plan_json, started_at, expires_at, stopped_at, stop_reason) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL)",
558
+ shareId,
559
+ detail.id,
560
+ params.via,
561
+ hostname,
562
+ link.tokenId,
563
+ params.via === "cloudflare" ? "worker" : "cookie",
564
+ JSON.stringify(plan),
565
+ iso(startedAt),
566
+ link.expiresAt ?? null,
567
+ );
568
+ appendEvent(db, {
569
+ artifactId: detail.id,
570
+ type: "share.started",
571
+ payload: { shareId, via: params.via, hostname, artifactOrigin: artifact.origin() },
572
+ });
573
+ if (key !== undefined) recordResult(db, key, { shareId });
574
+ return link;
575
+ });
576
+ let minted: ReturnType<typeof gateway.mintAt>;
577
+ try {
578
+ minted = record();
579
+ } catch (error) {
580
+ // Nothing was recorded: what the share set up goes again.
581
+ for (const face of plan.faces) await release(face.key, shareId).catch(() => undefined);
582
+ throw error;
583
+ }
584
+ schedule(shareId, minted.expiresAt);
585
+ log.info("share.started", { shareId, artifactId: detail.id, via: params.via, hostname });
586
+ const started = row(shareId) as ShareRow;
587
+ return { ...toShare(started), url: minted.url };
588
+ };
589
+
590
+ const withUrl = (share: Share): ShareStartResult => ({
591
+ ...share,
592
+ url: share.url ?? gateway.reveal(share.tokenId) ?? "",
593
+ });
594
+
595
+ // ── Ending ───────────────────────────────────────────────────────────────────────────────
596
+
597
+ const schedule = (shareId: string, expiresAt: string | undefined): void => {
598
+ if (expiresAt === undefined) return;
599
+ const delay = Math.max(0, Date.parse(expiresAt) - options.now());
600
+ // Timers past ~24.8 days overflow; the sweep ends those.
601
+ if (delay > 2 ** 31 - 1) return;
602
+ const timer = setTimeout(() => {
603
+ timers.delete(shareId);
604
+ void serial(() => stop(shareId, "expired")).catch((error: unknown) =>
605
+ log.error("share.stop_failed", { shareId, error }),
606
+ );
607
+ }, delay);
608
+ timer.unref?.();
609
+ timers.set(shareId, timer);
610
+ };
611
+
612
+ /**
613
+ * Ends a share once: its link is revoked (unless it expired or was revoked already), the
614
+ * ledger records why, and its faces' tunnels stop when no other share uses them.
615
+ */
616
+ const stop = async (shareId: string, reason: string): Promise<Share | undefined> => {
617
+ const found = row(shareId);
618
+ if (!found || found.stopped_at !== null) return undefined;
619
+ const at = options.now();
620
+ ledger.write((db: LedgerDb) => {
621
+ db.run(
622
+ "UPDATE share SET stopped_at = ?, stop_reason = ? WHERE id = ?",
623
+ iso(at),
624
+ reason,
625
+ shareId,
626
+ );
627
+ if (reason !== "expired" && reason !== "revoked") {
628
+ capabilities.revoke(capabilities.current(found.token_id), db);
629
+ }
630
+ appendEvent(db, {
631
+ artifactId: found.artifact_id,
632
+ type: "share.stopped",
633
+ payload: { shareId, via: found.via, hostname: found.hostname, reason },
634
+ });
635
+ });
636
+ const timer = timers.get(shareId);
637
+ if (timer !== undefined) clearTimeout(timer);
638
+ timers.delete(shareId);
639
+ const plan = JSON.parse(found.plan_json) as Plan;
640
+ for (const face of plan.faces) await release(face.key, shareId);
641
+ log.info("share.stopped", { shareId, via: found.via, reason });
642
+ return toShare(row(shareId) as ShareRow);
643
+ };
644
+
645
+ /** Ends shares whose link expired or was revoked since (`view/revoke` of a share's link). */
646
+ const sweep = async (): Promise<void> => {
647
+ for (const found of activeRows()) {
648
+ const grant = capabilities.grant(capabilities.current(found.token_id));
649
+ if (grant?.live) continue;
650
+ const expired = found.expires_at !== null && Date.parse(found.expires_at) <= options.now();
651
+ await serial(() => stop(found.id, expired ? "expired" : "revoked"));
652
+ }
653
+ };
654
+ const sweeper = setInterval(() => {
655
+ void sweep().catch((error: unknown) => log.error("share.sweep_failed", { error }));
656
+ }, options.sweepMs ?? SWEEP_MS);
657
+ sweeper.unref?.();
658
+
659
+ // ── After a restart ──────────────────────────────────────────────────────────────────────
660
+
661
+ const restore = async (found: ShareRow): Promise<void> => {
662
+ const plan = JSON.parse(found.plan_json) as Plan;
663
+ let last: unknown;
664
+ for (const delay of RECOVERY_DELAYS_MS) {
665
+ if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay));
666
+ if (closed) return;
667
+ try {
668
+ // The share is judged inside the lifecycle's turn (Opus review of WP-13): a `share/stop`
669
+ // queued meanwhile ran first, and nothing is set up for a share that ended.
670
+ const restored = await serial(async () => {
671
+ const current = row(found.id);
672
+ if (closed || !current || current.stopped_at !== null) return false;
673
+ await setUp(found.id, found.artifact_id, found.via, plan);
674
+ return true;
675
+ });
676
+ if (!restored) return;
677
+ schedule(found.id, found.expires_at ?? undefined);
678
+ log.info("share.restored", { shareId: found.id, via: found.via });
679
+ return;
680
+ } catch (error) {
681
+ last = error;
682
+ log.warn("share.restore_failed", { shareId: found.id, error: (error as Error).message });
683
+ }
684
+ }
685
+ log.warn("share.restore_gave_up", {
686
+ shareId: found.id,
687
+ error: last instanceof Error ? last.message : String(last),
688
+ });
689
+ await serial(() => stop(found.id, "tunnel"));
690
+ };
691
+
692
+ return {
693
+ methods: () => [
694
+ handler(shareStartMethod, (params) => {
695
+ const key = requestKey("share/start", params);
696
+ const run = (): Promise<ShareStartResult> => serial(() => start(params));
697
+ return key === undefined ? run() : inflight.run(key, run);
698
+ }),
699
+ handler(shareStopMethod, (params: ShareStopParams) =>
700
+ serial(async () => {
701
+ if ((params.shareId === undefined) === (params.artifact === undefined)) {
702
+ throw new RpcError(
703
+ createDiagnostic("MOSTRA_HOST_INVALID_PARAMS", {
704
+ message: "share/stop names either `shareId` or `artifact`, not both or neither.",
705
+ }),
706
+ -32602,
707
+ );
708
+ }
709
+ let ids: string[];
710
+ if (params.shareId !== undefined) {
711
+ if (!row(params.shareId)) {
712
+ throw new RpcError(
713
+ createDiagnostic("MOSTRA_SHARE_NOT_FOUND", {
714
+ message: `No share ${params.shareId} exists in this home.`,
715
+ }),
716
+ );
717
+ }
718
+ ids = [params.shareId];
719
+ } else {
720
+ const artifactId = options.artifacts.get(params.artifact as ArtifactRef).id;
721
+ ids = activeRows()
722
+ .filter((found) => found.artifact_id === artifactId)
723
+ .map((found) => found.id);
724
+ }
725
+ const stopped: Share[] = [];
726
+ for (const id of ids) {
727
+ const ended = await stop(id, "stopped");
728
+ if (ended) stopped.push(ended);
729
+ }
730
+ return { stopped };
731
+ }),
732
+ ),
733
+ handler(shareListMethod, (params: ShareListParams) => {
734
+ const artifactId =
735
+ params.artifact === undefined ? undefined : options.artifacts.get(params.artifact).id;
736
+ const rows = ledger.read((db) =>
737
+ db.all<ShareRow>(
738
+ params.all === true
739
+ ? "SELECT * FROM share ORDER BY stopped_at IS NOT NULL, started_at DESC"
740
+ : "SELECT * FROM share WHERE stopped_at IS NULL ORDER BY started_at DESC",
741
+ ),
742
+ );
743
+ return {
744
+ shares: rows
745
+ .filter((found) => artifactId === undefined || found.artifact_id === artifactId)
746
+ .map(toShare),
747
+ };
748
+ }),
749
+ ],
750
+ count: () =>
751
+ ledger.read(
752
+ (db) =>
753
+ db.get<{ count: number }>("SELECT COUNT(*) AS count FROM share WHERE stopped_at IS NULL")
754
+ ?.count ?? 0,
755
+ ),
756
+ // Status is read by tools that print it (`mostra inspect`, bug reports): a share's link and
757
+ // its secret appear only where asked for, `share/start` and `share/list` (Opus review of
758
+ // WP-13; capability tokens stay out of every other output).
759
+ active: () =>
760
+ activeRows().map((found) => {
761
+ const { url: _url, ...rest } = toShare(found);
762
+ return rest;
763
+ }),
764
+ async recover() {
765
+ const pending: Promise<void>[] = [];
766
+ for (const found of activeRows()) {
767
+ const grant = capabilities.grant(capabilities.current(found.token_id));
768
+ const expired = found.expires_at !== null && Date.parse(found.expires_at) <= options.now();
769
+ if (expired || !grant?.live) {
770
+ await serial(() => stop(found.id, expired ? "expired" : "revoked"));
771
+ } else if (found.via === "cloudflare") {
772
+ // A quick tunnel's address died with the instance that ran it.
773
+ await serial(() => stop(found.id, "restart"));
774
+ } else {
775
+ pending.push(restore(found));
776
+ }
777
+ }
778
+ await Promise.all(pending);
779
+ },
780
+ async close() {
781
+ closed = true;
782
+ clearInterval(sweeper);
783
+ for (const timer of timers.values()) clearTimeout(timer);
784
+ timers.clear();
785
+ const running = [...exposures.values()];
786
+ exposures.clear();
787
+ await Promise.all(running.map((exposure) => exposure.tunnel.stop()));
788
+ },
789
+ };
790
+ }
791
+
792
+ /** The variables that name the tools outright, passed to the lookup from the instance's own. */
793
+ function pick(env: Environment): Environment {
794
+ const out: Record<string, string> = {};
795
+ // The test fakes (`MOSTRA_TEST_TUNNELS`) and what they are told to play.
796
+ if (env["MOSTRA_TEST_TUNNELS"]) {
797
+ for (const [name, value] of Object.entries(env)) {
798
+ if (
799
+ (name === "MOSTRA_TEST_TUNNELS" || name.startsWith("MOSTRA_FAKE_")) &&
800
+ value !== undefined
801
+ ) {
802
+ out[name] = value;
803
+ }
804
+ }
805
+ }
806
+ for (const name of [
807
+ "MOSTRA_TAILSCALE",
808
+ "MOSTRA_CLOUDFLARED",
809
+ "PATH",
810
+ "Path",
811
+ "ProgramFiles",
812
+ "ProgramFiles(x86)",
813
+ ]) {
814
+ const value = env[name];
815
+ if (value !== undefined) out[name] = value;
816
+ }
817
+ return out;
818
+ }
819
+
820
+ /** The directory of a home's share files (the quick tunnel's empty configuration). */
821
+ export function shareCacheDir(home: string): string {
822
+ return join(home, "cache", "share");
823
+ }