@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.
@@ -1,10 +1,10 @@
1
1
  import { C as STAGING_FILES, S as LIVE_DECLARATION, _ as DEV_METHOD, a as nameKey, c as removeTree, d as replaceDirectoryLink, f as samePath, g as DEV_CHANGED_METHOD, h as BUILD_METHOD, i as linkTarget, l as renamePath, m as sealTree, o as pathKey, p as sealPlaced, r as linkDirectory, s as realPath, t as fsyncPath, u as renamePathSync, v as DEV_RELOAD_METHOD, y as DEV_SECRET_HEADER } from "./files-FygSJIzK.js";
2
2
  import { a as pathsOf, c as currentUserSid, d as runtimeRoot$1, f as serviceLauncherPath, i as ownedDirectory, l as helperPath, n as WINDOWS, o as runtimeDirFor, p as stopServiceLauncher, r as defaultHome, s as socketPathLimit, t as OS, u as runHelperAsync } from "./directories-mJ1qlVht.js";
3
3
  import { builtinModules, createRequire } from "node:module";
4
- import { appendFileSync, chmodSync, closeSync, constants, createReadStream, createWriteStream, existsSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, watch, writeFileSync, writeSync } from "node:fs";
4
+ import { accessSync, appendFileSync, chmodSync, closeSync, constants, createReadStream, createWriteStream, existsSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, watch, writeFileSync, writeSync } from "node:fs";
5
5
  import { basename, delimiter, dirname, extname, join, relative, resolve, sep, win32 } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
- import { ACTION_ARGS_MAX, ACTION_RESULT_MAX, ALL_SCOPES, ARTIFACT_MANIFEST_KEYS, ARTIFACT_PROGRESS, ArtifactId, ArtifactManifest, BROWSER_PROTOCOL_REVISION, BROWSER_PROTOCOL_REVISIONS, BUNDLE_NAME, CLI_CLIENT_NAME, CallRequest, ChooseRequest, DEFAULT_WORKER_LIMITS, DEV_NOTIFY, DeliveryId, EVENTS_NOTIFY, FieldsRequest, FollowRequest, HOST_PROTOCOL_REVISIONS, LIVE_RING_DEFAULT, LIVE_RING_MAX, LIVE_VALUE_MAX, LineSplitter, LiveRequest, MAX_LINE_LENGTH, MutationId, RUN_LOG_MAX, RUN_LOG_TRUNCATED, RpcError, RpcPeer, RunAttachRequest, RunCancelRequest, RunId, RunRequest, SECRET_NAME_PATTERN, SECRET_VALUE_MAX, SIGNAL_NAME_PATTERN, SIGNAL_PAYLOAD_MAX_BYTES, ServerEmitParams, ServerLiveValueParams, ServerSecretParams, ServerSignalParams, ServerStateGetParams, ServerStatePatchParams, ShellSubmitRequest, SignalRequest, SubmissionId, SubmissionPolicy, SubmitRequest, TokenId, VERIFY_RUNNER_METHODS, VerifyVerdict, VersionId, ViewId, ViewerId, WORKER_METHODS, WorkerBatchParams, WorkerCallOutcome, WorkerPingResult, WorkerStartResult, ariaSummary, artifactCreateMethod, artifactGetMethod, artifactListMethod, artifactPublishMethod, artifactVerifyMethod, canonicalJson, checkArgumentFrames, checkRequest, createDiagnostic, depsAddMethod, devStartMethod, devStopMethod, durationMs, encodeLine, estimateImageTokens, eventsAckMethod, eventsReadMethod, eventsSubscribeMethod, eventsUnsubscribeMethod, fromBase64, gcRunMethod, instanceCheckMethod, instanceStatusMethod, isFieldId, isFinalRunStatus, livePushMethod, mostraInitializeMethod, mostraShutdownMethod, negotiateRevision, normalizeScopes, parseParams, portDraftsMirrorMethod, portIdentityResolveMethod, portSecretsGetMethod, portSubmissionsDeliverMethod, portTrustedControlsActivatedMethod, portTrustedControlsPolicyMethod, refusal, resultsGetMethod, safeEqual, safePath, scopeAllows, secretDeleteMethod, secretListMethod, secretSetMethod, serializeAll, stateGetMethod, statePatchMethod, toBase64, viewDefaultMethod, viewLaunchMethod, viewRevokeMethod, viewRotateMethod, viewUrlMethod, viewportsFor, waitMethod } from "@mostra/protocol";
7
+ import { ACTION_ARGS_MAX, ACTION_RESULT_MAX, ALL_SCOPES, ARTIFACT_MANIFEST_KEYS, ARTIFACT_PROGRESS, ArtifactId, ArtifactManifest, BROWSER_PROTOCOL_REVISION, BROWSER_PROTOCOL_REVISIONS, BUNDLE_NAME, CLI_CLIENT_NAME, CallRequest, ChooseRequest, DEFAULT_WORKER_LIMITS, DEV_NOTIFY, DeliveryId, EVENTS_NOTIFY, EnterRequest, FRAME_SESSION_HEADER, FieldsRequest, FollowRequest, HOST_PROTOCOL_REVISIONS, LIVE_RING_DEFAULT, LIVE_RING_MAX, LIVE_VALUE_MAX, LineSplitter, LiveRequest, MAX_LINE_LENGTH, MutationId, PUBLIC_SHARE_DEFAULT_TTL, PUBLIC_SHARE_MAX_TTL_MS, RUN_LOG_MAX, RUN_LOG_TRUNCATED, RpcError, RpcPeer, RunAttachRequest, RunCancelRequest, RunId, RunRequest, SECRET_NAME_PATTERN, SECRET_VALUE_MAX, SIGNAL_NAME_PATTERN, SIGNAL_PAYLOAD_MAX_BYTES, ServerEmitParams, ServerLiveValueParams, ServerSecretParams, ServerSignalParams, ServerStateGetParams, ServerStatePatchParams, ShareId, ShellSubmitRequest, SignalRequest, StreamTicketRequest, SubmissionId, SubmissionPolicy, SubmitRequest, TokenId, VERIFY_RUNNER_METHODS, VerifyVerdict, VersionId, ViewId, ViewerId, WORKER_METHODS, WorkerBatchParams, WorkerCallOutcome, WorkerPingResult, WorkerStartResult, ariaSummary, artifactCreateMethod, artifactGetMethod, artifactListMethod, artifactPublishMethod, artifactVerifyMethod, canonicalJson, checkArgumentFrames, checkRequest, createDiagnostic, depsAddMethod, devStartMethod, devStopMethod, durationMs, encodeLine, estimateImageTokens, eventsAckMethod, eventsReadMethod, eventsSubscribeMethod, eventsUnsubscribeMethod, fromBase64, gcRunMethod, instanceCheckMethod, instanceStatusMethod, isFieldId, isFinalRunStatus, livePushMethod, mostraInitializeMethod, mostraShutdownMethod, negotiateRevision, normalizeScopes, parseParams, portAddressingExternalBaseMethod, portDraftsMirrorMethod, portIdentityResolveMethod, portSecretsGetMethod, portSubmissionsDeliverMethod, portTrustedControlsActivatedMethod, portTrustedControlsPolicyMethod, refusal, resultsGetMethod, safeEqual, safePath, scopeAllows, secretDeleteMethod, secretListMethod, secretSetMethod, serializeAll, shareListMethod, shareStartMethod, shareStopMethod, stateGetMethod, statePatchMethod, toBase64, viewDefaultMethod, viewLaunchMethod, viewRevokeMethod, viewRotateMethod, viewUrlMethod, viewportsFor, waitMethod } from "@mostra/protocol";
8
8
  import { createHash, createHmac, randomBytes, randomInt, randomUUID } from "node:crypto";
9
9
  import { connect, createConnection, createServer, isIP } from "node:net";
10
10
  import { execFile, execFileSync, spawn } from "node:child_process";
@@ -22,6 +22,7 @@ import { getRequestListener } from "@hono/node-server";
22
22
  import { Hono } from "hono";
23
23
  import ignore from "ignore";
24
24
  import { AsyncLocalStorage } from "node:async_hooks";
25
+ import { Resolver } from "node:dns/promises";
25
26
  //#region src/log.ts
26
27
  /**
27
28
  * The supervisor's log: JSON lines in `<home>/logs/supervisor.log`, rotated by size (DATA_MODEL
@@ -709,6 +710,16 @@ const LEASE_FIRST_PORT = 2e4;
709
710
  const LEASE_LAST_PORT = 32767;
710
711
  /** How many free ports to try before giving up on a lease. */
711
712
  const LEASE_ATTEMPTS = 64;
713
+ /** The address every face listens on: loopback, whatever `--bind` says (D158 item 1). */
714
+ const FACE_BIND_ADDRESS = "127.0.0.1";
715
+ /**
716
+ * The exact `Host` a browser sends for an origin: its host, with the port only when it isn't the
717
+ * scheme's default (`https://a.ts.net` is `a.ts.net`, `https://a.ts.net:8443` is
718
+ * `a.ts.net:8443`), lowercase. Registered tunnel addresses join the allowlist this way.
719
+ */
720
+ function hostOf(origin) {
721
+ return new URL(origin).host.toLowerCase();
722
+ }
712
723
  /** The unspecified addresses, as {@link authorityHost} writes them: each listens everywhere. */
713
724
  const WILDCARDS = /* @__PURE__ */ new Set([
714
725
  "0.0.0.0",
@@ -789,6 +800,37 @@ function createAddressing(options) {
789
800
  });
790
801
  };
791
802
  const taken = () => new Set(ledger.read((db) => db.all("SELECT port FROM port_lease")).map((row) => row.port));
803
+ /**
804
+ * Binds `server` to the owner's leased port on `address`, or to a newly leased one when it has
805
+ * none or another program holds it (`MOSTRA_ENV_PORT_TAKEN`).
806
+ */
807
+ const leaseAndListen = async (server, owner, address) => {
808
+ const previous = leased(owner);
809
+ if (previous !== void 0) {
810
+ if (await tryListen(server, previous, address)) return previous;
811
+ log.warn("addressing.port_taken", {
812
+ code: "MOSTRA_ENV_PORT_TAKEN",
813
+ purpose: owner.purpose,
814
+ owner: owner.owner,
815
+ port: previous
816
+ });
817
+ }
818
+ const others = taken();
819
+ for (let attempt = 0; attempt < LEASE_ATTEMPTS; attempt++) {
820
+ const port = randomInt(LEASE_FIRST_PORT, 32768);
821
+ if (others.has(port)) continue;
822
+ if (!await tryListen(server, port, address)) continue;
823
+ record(owner, port);
824
+ if (previous !== void 0) log.warn("addressing.port_released", {
825
+ purpose: owner.purpose,
826
+ owner: owner.owner,
827
+ from: previous,
828
+ to: port
829
+ });
830
+ return port;
831
+ }
832
+ throw bindFailed(`No free port between ${LEASE_FIRST_PORT} and ${LEASE_LAST_PORT} on ${address} after ${LEASE_ATTEMPTS} attempts.`);
833
+ };
792
834
  return {
793
835
  bindAddress,
794
836
  urlHost,
@@ -808,35 +850,27 @@ function createAddressing(options) {
808
850
  if (address === null || typeof address === "string") throw new Error("not a TCP listener");
809
851
  return address.port;
810
852
  }
811
- const previous = leased(owner);
812
- if (previous !== void 0) {
813
- if (await tryListen(server, previous, bindAddress)) return previous;
814
- log.warn("addressing.port_taken", {
815
- code: "MOSTRA_ENV_PORT_TAKEN",
816
- purpose: owner.purpose,
817
- owner: owner.owner,
818
- port: previous
819
- });
820
- }
821
- const others = taken();
822
- for (let attempt = 0; attempt < LEASE_ATTEMPTS; attempt++) {
823
- const port = randomInt(LEASE_FIRST_PORT, 32768);
824
- if (others.has(port)) continue;
825
- if (!await tryListen(server, port, bindAddress)) continue;
826
- record(owner, port);
827
- if (previous !== void 0) log.warn("addressing.port_released", {
828
- purpose: owner.purpose,
829
- owner: owner.owner,
830
- from: previous,
831
- to: port
832
- });
833
- return port;
834
- }
835
- throw bindFailed(`No free port between ${LEASE_FIRST_PORT} and ${LEASE_LAST_PORT} on ${bindAddress} after ${LEASE_ATTEMPTS} attempts.`);
853
+ return leaseAndListen(server, owner, bindAddress);
836
854
  },
837
855
  frameMode(shellOrigin, artifactOrigin) {
838
856
  return new URL(shellOrigin).hostname === new URL(artifactOrigin).hostname ? "cookie" : "worker";
839
- }
857
+ },
858
+ async listenFace(server, face) {
859
+ if (!face.lease) {
860
+ if (!await tryListen(server, 0, "127.0.0.1")) throw bindFailed(`No port is free on ${FACE_BIND_ADDRESS}.`);
861
+ const address = server.address();
862
+ if (address === null || typeof address === "string") throw new Error("not a TCP listener");
863
+ return address.port;
864
+ }
865
+ return leaseAndListen(server, {
866
+ purpose: "face",
867
+ owner: face.key
868
+ }, FACE_BIND_ADDRESS);
869
+ },
870
+ releaseFace(key) {
871
+ ledger.write((db) => db.run("DELETE FROM port_lease WHERE purpose = 'face' AND owner_ref = ?", key));
872
+ },
873
+ faceLocal: (port) => `http://${FACE_BIND_ADDRESS}:${port}`
840
874
  };
841
875
  }
842
876
  //#endregion
@@ -1686,6 +1720,114 @@ function baseEnvironment(env) {
1686
1720
  }
1687
1721
  return result;
1688
1722
  }
1723
+ //#endregion
1724
+ //#region src/platform/tools.ts
1725
+ /**
1726
+ * Where this system keeps the tunnel tools a share drives (D158 item 4): `tailscale` and
1727
+ * `cloudflared`, which Mostra never bundles or downloads. A daemon started by a login service may
1728
+ * run with a short `PATH`, so the tools' usual install locations are searched after it, and an
1729
+ * environment variable names one outright. How to install each is said here too, per system.
1730
+ */
1731
+ /** The variable that names a tool's executable outright. */
1732
+ const TOOL_VARIABLES = {
1733
+ tailscale: "MOSTRA_TAILSCALE",
1734
+ cloudflared: "MOSTRA_CLOUDFLARED"
1735
+ };
1736
+ /** The usual install locations of each tool, per system, after `PATH`. */
1737
+ function usualLocations(tool, env) {
1738
+ if (WINDOWS) {
1739
+ const programs = env["ProgramFiles"] ?? "C:\\Program Files";
1740
+ const programs86 = env["ProgramFiles(x86)"] ?? "C:\\Program Files (x86)";
1741
+ return tool === "tailscale" ? [join(programs, "Tailscale", "tailscale.exe")] : [join(programs86, "cloudflared", "cloudflared.exe"), join(programs, "cloudflared", "cloudflared.exe")];
1742
+ }
1743
+ if (OS === "darwin") return tool === "tailscale" ? [
1744
+ "/opt/homebrew/bin/tailscale",
1745
+ "/usr/local/bin/tailscale",
1746
+ "/opt/homebrew/opt/tailscale/bin/tailscale",
1747
+ "/usr/local/opt/tailscale/bin/tailscale",
1748
+ "/Applications/Tailscale.app/Contents/MacOS/Tailscale"
1749
+ ] : [
1750
+ "/opt/homebrew/bin/cloudflared",
1751
+ "/usr/local/bin/cloudflared",
1752
+ "/opt/homebrew/opt/cloudflared/bin/cloudflared",
1753
+ "/usr/local/opt/cloudflared/bin/cloudflared"
1754
+ ];
1755
+ return tool === "tailscale" ? [
1756
+ "/usr/bin/tailscale",
1757
+ "/usr/local/bin/tailscale",
1758
+ "/usr/sbin/tailscale"
1759
+ ] : ["/usr/bin/cloudflared", "/usr/local/bin/cloudflared"];
1760
+ }
1761
+ function executable(path) {
1762
+ try {
1763
+ if (!statSync(path).isFile()) return false;
1764
+ if (!WINDOWS) accessSync(path, constants.X_OK);
1765
+ return true;
1766
+ } catch {
1767
+ return false;
1768
+ }
1769
+ }
1770
+ /**
1771
+ * The tool's executable: the variable's (which must exist), else the first on `PATH`, else the
1772
+ * first usual location that exists; `undefined` when there is none.
1773
+ */
1774
+ function findTool(tool, env) {
1775
+ const named = env[TOOL_VARIABLES[tool]];
1776
+ if (named !== void 0 && named !== "") return executable(named) ? named : void 0;
1777
+ const names = WINDOWS ? [`${tool}.exe`] : [tool];
1778
+ const path = (WINDOWS ? env["Path"] ?? env["PATH"] : env["PATH"]) ?? "";
1779
+ for (const dir of path.split(delimiter)) {
1780
+ if (dir === "") continue;
1781
+ for (const name of names) {
1782
+ const candidate = join(dir, name);
1783
+ if (executable(candidate)) return candidate;
1784
+ }
1785
+ }
1786
+ return usualLocations(tool, env).find(executable);
1787
+ }
1788
+ /**
1789
+ * The variable that replaces both tools with local fakes for tests (`<dir>/tailscale.mjs` and
1790
+ * `<dir>/cloudflared.mjs`, run on this Node.js): the conformance kit's and the suites' own, which
1791
+ * forward on loopback as the real tools forward from their networks (STANDARDS: real side effects
1792
+ * in tests go to local fakes).
1793
+ */
1794
+ const TEST_TUNNELS_VARIABLE = "MOSTRA_TEST_TUNNELS";
1795
+ /** How to run a tool: {@link findTool}'s executable, or the test fake; `undefined` when missing. */
1796
+ function toolCommand(tool, env) {
1797
+ const fakes = env[TEST_TUNNELS_VARIABLE];
1798
+ if (fakes !== void 0 && fakes !== "") {
1799
+ const script = join(fakes, `${tool}.mjs`);
1800
+ return regularFile(script) ? {
1801
+ command: process.execPath,
1802
+ args: [script],
1803
+ fake: true
1804
+ } : void 0;
1805
+ }
1806
+ const found = findTool(tool, env);
1807
+ return found === void 0 ? void 0 : {
1808
+ command: found,
1809
+ args: [],
1810
+ fake: false
1811
+ };
1812
+ }
1813
+ function regularFile(path) {
1814
+ try {
1815
+ return statSync(path).isFile();
1816
+ } catch {
1817
+ return false;
1818
+ }
1819
+ }
1820
+ /** How to install a tool on this system, as one sentence. */
1821
+ function installHint(tool) {
1822
+ if (tool === "tailscale") {
1823
+ if (WINDOWS) return "Install Tailscale from https://tailscale.com/download/windows (or `winget install tailscale.tailscale`) and sign in.";
1824
+ if (OS === "darwin") return "Install Tailscale from https://tailscale.com/download/mac (or `brew install tailscale`) and sign in.";
1825
+ return "Install Tailscale with `curl -fsSL https://tailscale.com/install.sh | sh` (https://tailscale.com/download/linux), then run `sudo tailscale up`.";
1826
+ }
1827
+ if (WINDOWS) return "Install cloudflared with `winget install --id Cloudflare.cloudflared` (https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/).";
1828
+ if (OS === "darwin") return "Install cloudflared with `brew install cloudflared` (https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/).";
1829
+ return "Install cloudflared from your distribution's Cloudflare package repository or https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/.";
1830
+ }
1689
1831
  /** Packages whose versions define the SPA build; they are part of `buildConfigDigest` (VR-01). */
1690
1832
  const BUILD_PACKAGES = [
1691
1833
  "vite",
@@ -2457,6 +2599,58 @@ const MIGRATIONS = [
2457
2599
  up(db) {
2458
2600
  db.exec(`
2459
2601
  ALTER TABLE session ADD COLUMN viewer_id TEXT REFERENCES viewer(id);
2602
+ `);
2603
+ }
2604
+ },
2605
+ {
2606
+ version: 11,
2607
+ name: "shares and faces",
2608
+ up(db) {
2609
+ db.exec(`
2610
+ CREATE TABLE port_lease_new (
2611
+ port INTEGER PRIMARY KEY CHECK (port BETWEEN 1 AND 65535),
2612
+ purpose TEXT NOT NULL CHECK (purpose IN ('shell', 'artifact', 'demo', 'face')),
2613
+ owner_ref TEXT NOT NULL,
2614
+ leased_at TEXT NOT NULL,
2615
+ UNIQUE (purpose, owner_ref)
2616
+ );
2617
+ INSERT INTO port_lease_new (port, purpose, owner_ref, leased_at)
2618
+ SELECT port, purpose, owner_ref, leased_at FROM port_lease;
2619
+ DROP TABLE port_lease;
2620
+ ALTER TABLE port_lease_new RENAME TO port_lease;
2621
+ CREATE TABLE share (
2622
+ id TEXT PRIMARY KEY,
2623
+ artifact_id TEXT NOT NULL REFERENCES artifact(id),
2624
+ via TEXT NOT NULL CHECK (via IN ('tailnet', 'funnel', 'cloudflare')),
2625
+ hostname TEXT NOT NULL,
2626
+ token_id TEXT NOT NULL REFERENCES token(id),
2627
+ mode TEXT NOT NULL CHECK (mode IN ('cookie', 'worker')),
2628
+ plan_json TEXT NOT NULL,
2629
+ started_at TEXT NOT NULL,
2630
+ expires_at TEXT,
2631
+ stopped_at TEXT,
2632
+ stop_reason TEXT,
2633
+ CHECK ((stopped_at IS NULL) = (stop_reason IS NULL))
2634
+ );
2635
+ CREATE INDEX share_artifact ON share (artifact_id);
2636
+ CREATE INDEX share_active ON share (stopped_at) WHERE stopped_at IS NULL;
2637
+ CREATE TRIGGER share_ends_once BEFORE UPDATE ON share
2638
+ WHEN OLD.stopped_at IS NOT NULL OR NEW.id IS NOT OLD.id
2639
+ OR NEW.artifact_id IS NOT OLD.artifact_id OR NEW.via IS NOT OLD.via
2640
+ OR NEW.token_id IS NOT OLD.token_id OR NEW.started_at IS NOT OLD.started_at
2641
+ OR NEW.expires_at IS NOT OLD.expires_at
2642
+ BEGIN
2643
+ SELECT RAISE(ABORT, 'a share only ever ends, once');
2644
+ END;
2645
+ CREATE TABLE external_base (
2646
+ key TEXT PRIMARY KEY,
2647
+ listener TEXT NOT NULL CHECK (listener IN ('shell', 'artifact')),
2648
+ artifact_id TEXT NOT NULL REFERENCES artifact(id),
2649
+ origin TEXT NOT NULL,
2650
+ mode TEXT CHECK (mode IN ('cookie', 'worker')),
2651
+ client TEXT NOT NULL,
2652
+ updated_at TEXT NOT NULL
2653
+ );
2460
2654
  `);
2461
2655
  }
2462
2656
  }
@@ -2999,9 +3193,11 @@ function createManager({ ledger, log, redactor, faults = noFaults }) {
2999
3193
  const lines = createInterface({ input: child.stderr });
3000
3194
  drained.push(new Promise((resolve) => lines.once("close", resolve)));
3001
3195
  lines.on("line", (line) => {
3002
- stderrTail.push(redactor.redact(line));
3196
+ const redacted = redactor.redact(line);
3197
+ stderrTail.push(redacted);
3003
3198
  if (stderrTail.length > STDERR_TAIL) stderrTail.shift();
3004
- log.info("process.stderr", {
3199
+ if (spec.onStderr) spec.onStderr(redacted);
3200
+ else log.info("process.stderr", {
3005
3201
  kind: spec.kind,
3006
3202
  pid,
3007
3203
  line
@@ -4774,6 +4970,7 @@ function sessionMethods(options) {
4774
4970
  ...gateway ? { gateway } : {},
4775
4971
  ...options.deliveries ? { deliveries: [...options.deliveries()] } : {},
4776
4972
  ...options.workers ? { workers: [...options.workers()] } : {},
4973
+ ...options.shares ? { shares: [...options.shares()] } : {},
4777
4974
  ...(() => {
4778
4975
  const at = options.idleExitAt?.();
4779
4976
  return at === void 0 ? {} : { idleExitAt: at };
@@ -5295,7 +5492,7 @@ function viewerOf(row) {
5295
5492
  id: row.id,
5296
5493
  kind: row.kind,
5297
5494
  ...row.name !== null ? { name: row.name } : {},
5298
- ...row.kind === "token" || row.kind === "host" ? { ref: row.external_ref } : {}
5495
+ ...row.kind === "token" || row.kind === "host" || row.kind === "tailnet" ? { ref: row.external_ref } : {}
5299
5496
  };
5300
5497
  }
5301
5498
  /** The home's local user (created on first use): who every session acts as without a viewer. */
@@ -5320,6 +5517,24 @@ function viewerForSpec(db, spec) {
5320
5517
  function viewerForHost(db, spec) {
5321
5518
  return viewerByRef(db, "host", spec);
5322
5519
  }
5520
+ /**
5521
+ * A tailnet person (D158 item 2): one viewer of kind `tailnet` per Tailscale login, named by the
5522
+ * display name Tailscale Serve sends.
5523
+ */
5524
+ function viewerForTailnet(db, spec) {
5525
+ return viewerByRef(db, "tailnet", spec);
5526
+ }
5527
+ /**
5528
+ * A link's own viewer (D158 item 2): whoever opens a link over a tunnel without being named (a
5529
+ * public share, a tagged tailnet device) acts as one viewer per link, never as the home's local
5530
+ * user, so a visitor's answers never mix into the owner's draft.
5531
+ */
5532
+ function viewerForLink(db, tokenId, name) {
5533
+ return viewerByRef(db, "token", {
5534
+ ref: `link:${tokenId}`,
5535
+ name
5536
+ });
5537
+ }
5323
5538
  function viewerByRef(db, kind, spec) {
5324
5539
  const found = db.get("SELECT * FROM viewer WHERE kind = ? AND external_ref = ?", kind, spec.ref);
5325
5540
  if (found) {
@@ -6903,6 +7118,8 @@ function createInteraction(options) {
6903
7118
  viewer: (viewerId) => ledger.read((db) => viewer(db, viewerId)),
6904
7119
  viewerForSpec,
6905
7120
  viewerForHost: (spec) => ledger.write((db) => viewerForHost(db, spec)),
7121
+ viewerForTailnet: (spec) => ledger.write((db) => viewerForTailnet(db, spec)),
7122
+ viewerForLink: (tokenId, name) => ledger.write((db) => viewerForLink(db, tokenId, name)),
6906
7123
  openView(input) {
6907
7124
  return ledger.write((db) => openView(db, input));
6908
7125
  },
@@ -7822,6 +8039,7 @@ function headerPairs(incoming) {
7822
8039
  }
7823
8040
  /** Whether a request is a navigation that should get an HTML page rather than JSON. */
7824
8041
  function wantsDocument(headers) {
8042
+ if (headers.get("x-mostra-navigation") === "1") return true;
7825
8043
  const dest = headers.get("sec-fetch-dest");
7826
8044
  if (dest !== null) return dest === "document" || dest === "iframe" || dest === "frame";
7827
8045
  return (headers.get("accept") ?? "").includes("text/html");
@@ -7885,9 +8103,12 @@ function cookieValues(header, name) {
7885
8103
  }
7886
8104
  return values;
7887
8105
  }
7888
- /** The `Set-Cookie` value of a session cookie (D98 item 1); never `Secure` over loopback HTTP. */
7889
- function sessionCookie(name, value, path, maxAgeSeconds) {
7890
- return `${name}=${value}; Path=${path}; Max-Age=${maxAgeSeconds}; HttpOnly; SameSite=Strict`;
8106
+ /**
8107
+ * The `Set-Cookie` value of a session cookie (D98 item 1): never `Secure` over loopback HTTP,
8108
+ * always over a tunnel's HTTPS address (D158), where it must never travel in clear.
8109
+ */
8110
+ function sessionCookie(name, value, path, maxAgeSeconds, secure = false) {
8111
+ return `${name}=${value}; Path=${path}; Max-Age=${maxAgeSeconds}; HttpOnly; SameSite=Strict${secure ? "; Secure" : ""}`;
7891
8112
  }
7892
8113
  /**
7893
8114
  * Reads a JSON object body of at most `maxBytes` (default {@link MAX_JSON_BODY}) bytes; a larger,
@@ -8324,7 +8545,7 @@ function browserRoutes(options) {
8324
8545
  };
8325
8546
  const body = new ReadableStream({
8326
8547
  start(controller) {
8327
- let text = "retry: 2000\n\n";
8548
+ let text = "retry: 2000\n\nevent: ready\ndata: {}\n\n";
8328
8549
  if (resume === void 0) text += snapshotText(interaction.pageSnapshot(page));
8329
8550
  controller.enqueue(encoder.encode(text));
8330
8551
  },
@@ -8584,11 +8805,23 @@ function browserRoutes(options) {
8584
8805
  const CROCKFORD$2 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
8585
8806
  /** How long a frame ticket works (D98). */
8586
8807
  const TICKET_TTL_MS = 6e4;
8808
+ /** How often expired tickets are swept at most. */
8809
+ const SWEEP_INTERVAL_MS = 1e3;
8587
8810
  const FAILURE_WINDOW_MS = 6e4;
8588
8811
  /** How long a session the browser no longer presents is kept: the cookie's own lifetime. */
8589
8812
  const SESSION_MAX_AGE_S = 3456e4;
8590
8813
  /** How often a session's `last_seen_at` is written at most. */
8591
8814
  const TOUCH_INTERVAL_MS = 36e5;
8815
+ /** Whether two origins are on the same scheme and host, whatever their ports. */
8816
+ function sameHost(a, b) {
8817
+ try {
8818
+ const one = new URL(a);
8819
+ const two = new URL(b);
8820
+ return one.protocol === two.protocol && one.hostname === two.hostname;
8821
+ } catch {
8822
+ return false;
8823
+ }
8824
+ }
8592
8825
  /** Encodes the first 130 bits of `bytes` as 26 Crockford base32 characters. */
8593
8826
  function crockford(bytes) {
8594
8827
  let bits = 0;
@@ -8676,9 +8909,17 @@ var Capabilities = class {
8676
8909
  #key;
8677
8910
  #now;
8678
8911
  #shellOrigin;
8912
+ #servesShell;
8913
+ /** Single-use stream and socket tickets (D158 item 5), by the SHA-256 of their secret. */
8914
+ #streamTickets = /* @__PURE__ */ new Map();
8679
8915
  #tickets = /* @__PURE__ */ new Map();
8680
8916
  /** One-time launch tickets (D140 item 15), by the SHA-256 of their secret. */
8681
8917
  #launches = /* @__PURE__ */ new Map();
8918
+ /** The frame tickets and the stream tickets each session holds, oldest first. */
8919
+ #ticketsBySession = /* @__PURE__ */ new Map();
8920
+ #streamTicketsBySession = /* @__PURE__ */ new Map();
8921
+ /** When the tickets were last swept. */
8922
+ #swept = Number.NEGATIVE_INFINITY;
8682
8923
  /** Failure times per artifact (`""` for tokens of no artifact in this home). */
8683
8924
  #failures = /* @__PURE__ */ new Map();
8684
8925
  #touched = /* @__PURE__ */ new Map();
@@ -8688,6 +8929,7 @@ var Capabilities = class {
8688
8929
  this.#key = options.key;
8689
8930
  this.#now = options.now;
8690
8931
  this.#shellOrigin = options.shellOrigin;
8932
+ this.#servesShell = options.servesShell ?? ((origin) => origin === this.#shellOrigin());
8691
8933
  }
8692
8934
  /** Runs `fn` in the caller's transaction, or in a new one. */
8693
8935
  #tx(db, fn) {
@@ -8707,7 +8949,7 @@ var Capabilities = class {
8707
8949
  const tokenId = input.tokenId ?? TokenId.create();
8708
8950
  const secret = this.secretOf(tokenId);
8709
8951
  const scopes = normalizeScopes(input.scopes);
8710
- const shellOrigin = this.#shellOrigin();
8952
+ const shellOrigin = input.shellOrigin ?? this.#shellOrigin();
8711
8953
  db.run("INSERT INTO token (id, secret_hash, artifact_id, scopes_json, viewer_id, expires_at, revoked_at, created_at, is_default, pinned_version, shell_origin) VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?)", tokenId, hashSecret(secret), input.artifactId, JSON.stringify(scopes), input.viewerId ?? null, input.expiresAt ?? null, this.#iso(this.#now()), input.isDefault ? 1 : 0, input.pinnedVersion ?? null, shellOrigin);
8712
8954
  return {
8713
8955
  tokenId,
@@ -8729,7 +8971,8 @@ var Capabilities = class {
8729
8971
  expiresAt: input.ttlMs === void 0 ? void 0 : this.#iso(this.#now() + input.ttlMs),
8730
8972
  pinnedVersion: input.pinnedVersion,
8731
8973
  isDefault: false,
8732
- viewerId: input.viewerId
8974
+ viewerId: input.viewerId,
8975
+ shellOrigin: input.shellOrigin
8733
8976
  }));
8734
8977
  }
8735
8978
  /**
@@ -8738,12 +8981,13 @@ var Capabilities = class {
8738
8981
  * key was replaced) stays valid for whoever holds it, and a new default takes its place; so does
8739
8982
  * one minted for another shell address, which works again if the gateway returns there.
8740
8983
  */
8741
- defaultLink(artifactId) {
8984
+ defaultLink(artifactId, shellOrigin) {
8985
+ const origin = shellOrigin ?? this.#shellOrigin();
8742
8986
  return this.#ledger.write((db) => {
8743
8987
  const row = db.get("SELECT * FROM token WHERE artifact_id = ? AND is_default = 1", artifactId);
8744
8988
  if (row) {
8745
8989
  const secret = this.secretOf(row.id);
8746
- const here = row.shell_origin === this.#shellOrigin();
8990
+ const here = row.shell_origin === origin;
8747
8991
  if (here && safeEqual(hashSecret(secret), row.secret_hash)) return {
8748
8992
  ...grantOf(row),
8749
8993
  secret
@@ -8758,7 +9002,8 @@ var Capabilities = class {
8758
9002
  return this.#insert(db, {
8759
9003
  artifactId,
8760
9004
  scopes: ALL_SCOPES,
8761
- isDefault: true
9005
+ isDefault: true,
9006
+ shellOrigin: origin
8762
9007
  });
8763
9008
  });
8764
9009
  }
@@ -8770,6 +9015,19 @@ var Capabilities = class {
8770
9015
  live: this.#live(row)
8771
9016
  } : void 0;
8772
9017
  }
9018
+ /**
9019
+ * The token that stands for `tokenId` now: itself, or the token its rotations led to (D97 item
9020
+ * 6), so what holds a token ID (a share) follows its link through `view/rotate`.
9021
+ */
9022
+ current(tokenId) {
9023
+ let id = tokenId;
9024
+ for (let hop = 0; hop < 1e3; hop++) {
9025
+ const next = this.#ledger.read((db) => db.get("SELECT replaced_by FROM token WHERE id = ?", id)?.replaced_by ?? null);
9026
+ if (next === null) return id;
9027
+ id = next;
9028
+ }
9029
+ return id;
9030
+ }
8773
9031
  /** The token's link again, from its derived secret, when the current key still derives it. */
8774
9032
  reveal(tokenId) {
8775
9033
  const row = this.#ledger.read((db) => db.get("SELECT * FROM token WHERE id = ?", tokenId));
@@ -8818,7 +9076,8 @@ var Capabilities = class {
8818
9076
  expiresAt: grant.expiresAt,
8819
9077
  pinnedVersion: grant.pinnedVersion,
8820
9078
  isDefault: grant.isDefault,
8821
- viewerId: grant.viewerId
9079
+ viewerId: grant.viewerId,
9080
+ shellOrigin: sameHost(grant.shellOrigin, this.#shellOrigin()) && !this.#servesShell(grant.shellOrigin) ? void 0 : grant.shellOrigin
8822
9081
  });
8823
9082
  appendEvent(db, {
8824
9083
  artifactId: grant.artifactId,
@@ -8867,7 +9126,7 @@ var Capabilities = class {
8867
9126
  * artifact, is `MOSTRA_HYGIENE_TOKEN_INVALID`; a revoked or expired one, or one minted for
8868
9127
  * another shell address, `_TOKEN_REVOKED`. Unknown secrets count towards the limit.
8869
9128
  */
8870
- presentToken(secret, artifactId) {
9129
+ presentToken(secret, artifactId, shellOrigin) {
8871
9130
  const limited = this.limited(artifactId);
8872
9131
  if (limited) return limited;
8873
9132
  if (!looksLikeSecret(secret)) {
@@ -8880,7 +9139,7 @@ var Capabilities = class {
8880
9139
  return refusal("MOSTRA_HYGIENE_TOKEN_INVALID", "No capability token in this home matches this link.");
8881
9140
  }
8882
9141
  if (!this.#live(row)) return refusal("MOSTRA_HYGIENE_TOKEN_REVOKED", row.revoked_at !== null ? "This link was revoked." : "This link has expired.");
8883
- if (row.shell_origin !== this.#shellOrigin()) return refusal("MOSTRA_HYGIENE_TOKEN_REVOKED", `This link was made for ${row.shell_origin}, an address this Mostra no longer serves.`);
9142
+ if (row.shell_origin !== (shellOrigin ?? this.#shellOrigin())) return refusal("MOSTRA_HYGIENE_TOKEN_REVOKED", `This link was made for ${row.shell_origin}, not this address.`);
8884
9143
  return grantOf(row);
8885
9144
  }
8886
9145
  /** Starts a session for a grant on one origin; returns the cookie secret and CSRF token. */
@@ -8889,7 +9148,7 @@ var Capabilities = class {
8889
9148
  const csrf = csrfOf(cookie);
8890
9149
  const id = hashSecret(cookie);
8891
9150
  const now = this.#iso(this.#now());
8892
- this.#ledger.write((db) => db.run("INSERT INTO session (id, token_id, origin, mode, csrf, version_id, created_at, last_seen_at, viewer_id) VALUES (?, ?, ?, 'cookie', ?, ?, ?, ?, ?)", id, input.tokenId, input.origin, hashSecret(csrf), input.versionId ?? null, now, now, input.viewerId ?? null));
9151
+ this.#ledger.write((db) => db.run("INSERT INTO session (id, token_id, origin, mode, csrf, version_id, created_at, last_seen_at, viewer_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", id, input.tokenId, input.origin, input.mode ?? "cookie", hashSecret(csrf), input.versionId ?? null, now, now, input.viewerId ?? null));
8893
9152
  return {
8894
9153
  cookie,
8895
9154
  csrf,
@@ -8901,13 +9160,13 @@ var Capabilities = class {
8901
9160
  * value is tried, since another page of the host may have set a cookie of the same name (D98):
8902
9161
  * only a session issued for this origin, whose token is live and grants this artifact, counts.
8903
9162
  */
8904
- session(cookies, origin, artifactId) {
9163
+ session(cookies, origin, artifactId, mode = "cookie") {
8905
9164
  let revoked = false;
8906
9165
  for (const value of cookies) {
8907
9166
  if (!looksLikeSecret(value)) continue;
8908
9167
  const found = this.#ledger.read((db) => {
8909
9168
  const session = db.get("SELECT * FROM session WHERE id = ?", hashSecret(value));
8910
- if (!session || session.origin !== origin) return void 0;
9169
+ if (!session || session.origin !== origin || session.mode !== mode) return void 0;
8911
9170
  const token = db.get("SELECT * FROM token WHERE id = ?", session.token_id);
8912
9171
  return token && token.artifact_id === artifactId ? {
8913
9172
  session,
@@ -8927,6 +9186,7 @@ var Capabilities = class {
8927
9186
  return {
8928
9187
  id: found.session.id,
8929
9188
  csrf,
9189
+ mode,
8930
9190
  ...found.session.version_id !== null ? { versionId: found.session.version_id } : {},
8931
9191
  grant,
8932
9192
  ...viewerId !== void 0 ? { viewerId } : {}
@@ -8945,17 +9205,30 @@ var Capabilities = class {
8945
9205
  this.#touched.set(sessionId, now);
8946
9206
  this.#ledger.write((db) => db.run("UPDATE session SET last_seen_at = ? WHERE id = ?", this.#iso(now), sessionId));
8947
9207
  }
8948
- /** Mints a single-use frame ticket (D98 item 3). */
9208
+ /** Mints a single-use frame ticket (D98 item 3); a shell session holds at most a few at once. */
8949
9209
  mintTicket(grant) {
8950
9210
  const ticket = randomSecret();
8951
9211
  this.#sweepTickets();
8952
- this.#tickets.set(hashSecret(ticket), {
9212
+ const key = hashSecret(ticket);
9213
+ this.#tickets.set(key, {
8953
9214
  ...grant,
8954
9215
  expires: this.#now() + TICKET_TTL_MS
8955
9216
  });
9217
+ this.#hold(this.#ticketsBySession, this.#tickets, grant.shellSessionId, key);
8956
9218
  return ticket;
8957
9219
  }
8958
9220
  /**
9221
+ * Records a session's new ticket and drops its oldest beyond {@link TICKETS_PER_SESSION}, so no
9222
+ * link holder can make the maps grow without bound by asking for tickets in a loop (Opus review
9223
+ * of WP-13). A page uses one or two at a time.
9224
+ */
9225
+ #hold(bySession, tickets, sessionId, key) {
9226
+ const held = (bySession.get(sessionId) ?? []).filter((one) => tickets.has(one));
9227
+ held.push(key);
9228
+ while (held.length > 8) tickets.delete(held.shift());
9229
+ bySession.set(sessionId, held);
9230
+ }
9231
+ /**
8959
9232
  * Redeems a ticket on `origin`, once, while the shell session that asked for it lives and its
8960
9233
  * link is live (D98 item 3).
8961
9234
  */
@@ -8964,15 +9237,78 @@ var Capabilities = class {
8964
9237
  const key = looksLikeSecret(ticket) ? hashSecret(ticket) : void 0;
8965
9238
  const entry = key === void 0 ? void 0 : this.#tickets.get(key);
8966
9239
  if (key !== void 0) this.#tickets.delete(key);
8967
- if (!entry || entry.origin !== origin) return refusal("MOSTRA_HYGIENE_TOKEN_INVALID", "The frame ticket is unknown, used or expired.");
9240
+ if (!entry || entry.expires <= this.#now() || entry.origin !== origin) return refusal("MOSTRA_HYGIENE_TOKEN_INVALID", "The frame ticket is unknown, used or expired.");
8968
9241
  if (this.#ledger.read((db) => db.get("SELECT token_id FROM session WHERE id = ?", entry.shellSessionId))?.token_id !== entry.tokenId) return refusal("MOSTRA_HYGIENE_SESSION_MISSING", "The shell session that asked for this frame ticket has ended.");
8969
9242
  if (!this.grant(entry.tokenId)?.live) return refusal("MOSTRA_HYGIENE_TOKEN_REVOKED", "The link behind this frame was revoked or has expired.");
8970
9243
  const { expires: _expires, ...rest } = entry;
8971
9244
  return rest;
8972
9245
  }
9246
+ /**
9247
+ * Mints a single-use ticket that opens one event stream, long poll or WebSocket of a session
9248
+ * without the session's credential (D158 item 5): a worker-mode page's streams bypass its
9249
+ * service worker, which can't carry them. It lives 60 s in memory and is never recorded.
9250
+ */
9251
+ mintStreamTicket(input) {
9252
+ this.#sweepTickets();
9253
+ const ticket = randomSecret();
9254
+ const expires = this.#now() + TICKET_TTL_MS;
9255
+ const key = hashSecret(ticket);
9256
+ this.#streamTickets.set(key, {
9257
+ ...input,
9258
+ expires
9259
+ });
9260
+ this.#hold(this.#streamTicketsBySession, this.#streamTickets, input.sessionId, key);
9261
+ return {
9262
+ ticket,
9263
+ expiresAt: this.#iso(expires)
9264
+ };
9265
+ }
9266
+ /**
9267
+ * Spends a stream ticket on `origin` for `artifactId` and `purpose`, and resolves its session
9268
+ * as a request carrying the session's credential would, its link's liveness included. The
9269
+ * session's CSRF token isn't known here: a ticket opens reads only (streams, polls, sockets).
9270
+ */
9271
+ redeemStreamTicket(ticket, origin, artifactId, purpose) {
9272
+ this.#sweepTickets();
9273
+ const key = looksLikeSecret(ticket) ? hashSecret(ticket) : void 0;
9274
+ const entry = key === void 0 ? void 0 : this.#streamTickets.get(key);
9275
+ if (key !== void 0) this.#streamTickets.delete(key);
9276
+ if (!entry || entry.expires <= this.#now() || entry.origin !== origin || entry.artifactId !== artifactId || entry.purpose !== purpose) return refusal("MOSTRA_HYGIENE_TOKEN_INVALID", "The stream ticket is unknown, used or expired.");
9277
+ const found = this.#ledger.read((db) => {
9278
+ const session = db.get("SELECT * FROM session WHERE id = ?", entry.sessionId);
9279
+ if (!session || session.origin !== origin) return void 0;
9280
+ const token = db.get("SELECT * FROM token WHERE id = ?", session.token_id);
9281
+ return token && token.artifact_id === artifactId ? {
9282
+ session,
9283
+ token
9284
+ } : void 0;
9285
+ });
9286
+ if (!found) return refusal("MOSTRA_HYGIENE_SESSION_MISSING", "The session behind this ticket has ended.");
9287
+ if (!this.#live(found.token)) return refusal("MOSTRA_HYGIENE_TOKEN_REVOKED", "The link this session came from was revoked or has expired.");
9288
+ const grant = grantOf(found.token);
9289
+ const viewerId = grant.viewerId ?? found.session.viewer_id ?? void 0;
9290
+ return {
9291
+ id: found.session.id,
9292
+ csrf: "",
9293
+ mode: found.session.mode,
9294
+ ...found.session.version_id !== null ? { versionId: found.session.version_id } : {},
9295
+ grant,
9296
+ ...viewerId !== void 0 ? { viewerId } : {}
9297
+ };
9298
+ }
9299
+ /**
9300
+ * Drops expired tickets, at most once a second: every use checks a ticket's expiry itself, so a
9301
+ * sweep only frees memory, and a burst of requests never makes each one walk every ticket (Opus
9302
+ * review of WP-13).
9303
+ */
8973
9304
  #sweepTickets() {
8974
9305
  const now = this.#now();
9306
+ if (now - this.#swept < SWEEP_INTERVAL_MS && now >= this.#swept) return;
9307
+ this.#swept = now;
9308
+ for (const [sessionId, held] of this.#ticketsBySession) if (!held.some((key) => this.#tickets.has(key))) this.#ticketsBySession.delete(sessionId);
9309
+ for (const [sessionId, held] of this.#streamTicketsBySession) if (!held.some((key) => this.#streamTickets.has(key))) this.#streamTicketsBySession.delete(sessionId);
8975
9310
  for (const [key, entry] of this.#tickets) if (entry.expires <= now) this.#tickets.delete(key);
9311
+ for (const [key, entry] of this.#streamTickets) if (entry.expires <= now) this.#streamTickets.delete(key);
8976
9312
  for (const [key, entry] of this.#launches) if (entry.expires <= now) this.#launches.delete(key);
8977
9313
  }
8978
9314
  /**
@@ -8984,7 +9320,7 @@ var Capabilities = class {
8984
9320
  mintLaunch(tokenId) {
8985
9321
  const grant = this.grant(tokenId);
8986
9322
  if (!grant) return void 0;
8987
- if (!grant.live || grant.shellOrigin !== this.#shellOrigin()) return "dead";
9323
+ if (!grant.live || !this.#servesShell(grant.shellOrigin)) return "dead";
8988
9324
  this.#sweepTickets();
8989
9325
  const ticket = randomSecret();
8990
9326
  const expires = this.#now() + TICKET_TTL_MS;
@@ -9005,18 +9341,19 @@ var Capabilities = class {
9005
9341
  * once a session exists, so a viewer who chooses between two links (D98 item 8) can still use it
9006
9342
  * within its minute.
9007
9343
  */
9008
- presentLaunch(ticket, artifactId, spend) {
9344
+ presentLaunch(ticket, artifactId, spend, shellOrigin) {
9009
9345
  const limited = this.limited(artifactId);
9010
9346
  if (limited) return limited;
9011
9347
  this.#sweepTickets();
9012
9348
  const key = looksLikeSecret(ticket) ? hashSecret(ticket) : void 0;
9013
- const entry = key === void 0 ? void 0 : this.#launches.get(key);
9349
+ const found = key === void 0 ? void 0 : this.#launches.get(key);
9350
+ const entry = found && found.expires > this.#now() ? found : void 0;
9014
9351
  const grant = entry ? this.grant(entry.tokenId) : void 0;
9015
9352
  if (!entry || !grant || grant.artifactId !== artifactId) {
9016
9353
  this.#fail(artifactId);
9017
9354
  return refusal("MOSTRA_HYGIENE_TOKEN_INVALID", "The launch ticket is unknown, used or expired.");
9018
9355
  }
9019
- if (!grant.live || grant.shellOrigin !== this.#shellOrigin()) return refusal("MOSTRA_HYGIENE_TOKEN_REVOKED", "The link behind this launch ticket was revoked or has expired.");
9356
+ if (!grant.live || grant.shellOrigin !== (shellOrigin ?? this.#shellOrigin())) return refusal("MOSTRA_HYGIENE_TOKEN_REVOKED", "The link behind this launch ticket was revoked, has expired, or is for another address.");
9020
9357
  if (spend && key !== void 0) this.#launches.delete(key);
9021
9358
  const { live: _live, ...rest } = grant;
9022
9359
  return rest;
@@ -9028,7 +9365,11 @@ var Capabilities = class {
9028
9365
  */
9029
9366
  spendLaunch(ticket) {
9030
9367
  this.#sweepTickets();
9031
- return looksLikeSecret(ticket) && this.#launches.delete(hashSecret(ticket));
9368
+ if (!looksLikeSecret(ticket)) return false;
9369
+ const key = hashSecret(ticket);
9370
+ const entry = this.#launches.get(key);
9371
+ if (!entry || entry.expires <= this.#now()) return false;
9372
+ return this.#launches.delete(key);
9032
9373
  }
9033
9374
  /** Removes sessions unseen for longer than their cookie lives; no browser holds them any more. */
9034
9375
  prune() {
@@ -9135,6 +9476,144 @@ function devUpgrade(upstream, incoming, socket, head) {
9135
9476
  });
9136
9477
  }
9137
9478
  //#endregion
9479
+ //#region src/gateway/identity.ts
9480
+ /**
9481
+ * Who a browser is (D143 item 2). A link minted with a viewer acts for that viewer (D104) and asks
9482
+ * nothing. For a link without one, a host that registered the `identity` port names the person
9483
+ * from the request's headers; without such a host, the session acts as the home's local user.
9484
+ */
9485
+ /** How long a host has to answer `port/identity.resolve`: a page waits for it, as for D108. */
9486
+ const IDENTITY_TIMEOUT_MS = 5e3;
9487
+ /**
9488
+ * The headers a host sees: names in lower case, without `cookie` (Mostra's sessions and every
9489
+ * other page's of this host) and without Mostra's own `x-mostra-*` headers.
9490
+ */
9491
+ function identityHeaders(headers) {
9492
+ const seen = {};
9493
+ headers.forEach((value, name) => {
9494
+ const key = name.toLowerCase();
9495
+ if (key === "cookie" || key.startsWith("x-mostra-")) return;
9496
+ seen[key] = value;
9497
+ });
9498
+ return seen;
9499
+ }
9500
+ /**
9501
+ * Asks the host that took identity over. Its outage never makes the session someone else: a
9502
+ * failure, a timeout, an answer the schema refuses, or an expected host that isn't connected is
9503
+ * `unavailable`, and the exchange is refused.
9504
+ */
9505
+ async function resolveIdentity(input) {
9506
+ const registrant = input.registrant();
9507
+ const unavailable = (message) => ({
9508
+ kind: "unavailable",
9509
+ diagnostic: createDiagnostic("MOSTRA_HOST_IDENTITY_UNAVAILABLE", { message })
9510
+ });
9511
+ if (registrant) try {
9512
+ const answer = await input.call(registrant.session, {
9513
+ artifactId: input.artifactId,
9514
+ via: input.via,
9515
+ headers: identityHeaders(input.headers)
9516
+ });
9517
+ const parsed = portIdentityResolveMethod.result.safeParse(answer);
9518
+ if (parsed.success) return parsed.data === null ? { kind: "default" } : {
9519
+ kind: "person",
9520
+ viewer: parsed.data
9521
+ };
9522
+ input.log.warn("gateway.identity_invalid", {
9523
+ owner: registrant.owner,
9524
+ artifactId: input.artifactId
9525
+ });
9526
+ return unavailable(`The host ${registrant.owner} answered who this is in a form Mostra refuses.`);
9527
+ } catch (error) {
9528
+ input.log.warn("gateway.identity_failed", {
9529
+ owner: registrant.owner,
9530
+ artifactId: input.artifactId,
9531
+ error: error.message
9532
+ });
9533
+ return unavailable(`The host ${registrant.owner} didn't say who this is.`);
9534
+ }
9535
+ const away = input.expected();
9536
+ if (away.length > 0) {
9537
+ input.log.warn("gateway.identity_host_away", {
9538
+ owners: away,
9539
+ artifactId: input.artifactId
9540
+ });
9541
+ return unavailable(`The host that identifies this home's viewers (${away.join(", ")}) isn't running.`);
9542
+ }
9543
+ return { kind: "default" };
9544
+ }
9545
+ /**
9546
+ * Decodes RFC 2047 encoded words (`=?utf-8?q?Ferris_B=C3=BCller?=`, and `b` for base64), as
9547
+ * Tailscale Serve writes a non-ASCII name; text outside encoded words is kept, and whitespace
9548
+ * between two encoded words is dropped (RFC 2047 §6.2). Anything malformed is kept as written.
9549
+ */
9550
+ function decodeEncodedWords(value) {
9551
+ const word = /=\?([^?\s]+)\?([qQbB])\?([^?\s]*)\?=/g;
9552
+ const decodeOne = (charset, encoding, text) => {
9553
+ let bytes;
9554
+ if (encoding.toLowerCase() === "b") bytes = Buffer.from(text, "base64");
9555
+ else {
9556
+ const out = [];
9557
+ for (let index = 0; index < text.length; index++) {
9558
+ const char = text[index];
9559
+ if (char === "_") out.push(32);
9560
+ else if (char === "=" && /^[0-9A-Fa-f]{2}$/.test(text.slice(index + 1, index + 3))) {
9561
+ out.push(Number.parseInt(text.slice(index + 1, index + 3), 16));
9562
+ index += 2;
9563
+ } else out.push(char.charCodeAt(0) & 255);
9564
+ }
9565
+ bytes = Uint8Array.from(out);
9566
+ }
9567
+ try {
9568
+ return new TextDecoder(charset, { fatal: true }).decode(bytes);
9569
+ } catch {
9570
+ return;
9571
+ }
9572
+ };
9573
+ let result = "";
9574
+ let last = 0;
9575
+ let previousWasWord = false;
9576
+ for (const match of value.matchAll(word)) {
9577
+ const between = value.slice(last, match.index);
9578
+ const decoded = decodeOne(match[1], match[2], match[3]);
9579
+ if (decoded === void 0) {
9580
+ result += between + match[0];
9581
+ previousWasWord = false;
9582
+ } else {
9583
+ result += previousWasWord && /^\s*$/.test(between) ? "" : between;
9584
+ result += decoded;
9585
+ previousWasWord = true;
9586
+ }
9587
+ last = match.index + match[0].length;
9588
+ }
9589
+ return result + value.slice(last);
9590
+ }
9591
+ /** Whether a connection's peer is this machine: the only way a tunnel tool reaches a face. */
9592
+ function isLoopbackPeer(remote) {
9593
+ if (remote === void 0) return false;
9594
+ const address = remote.startsWith("::ffff:") ? remote.slice(7) : remote;
9595
+ return address === "::1" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(address);
9596
+ }
9597
+ /**
9598
+ * The tailnet person Tailscale Serve names in a request (D158 item 2): `Tailscale-User-Login` and
9599
+ * `Tailscale-User-Name`, which Serve sets on every tailnet request after removing any a client
9600
+ * sent. They are believed only from a loopback peer (faces bind loopback, so only `tailscaled` and
9601
+ * this machine's own programs reach them) and never beside `Tailscale-Funnel-Request`, which
9602
+ * marks a public request. A tagged device sends no login, so nobody is named.
9603
+ */
9604
+ function tailnetPerson(headers, remote) {
9605
+ if (!isLoopbackPeer(remote) || headers.has("tailscale-funnel-request")) return void 0;
9606
+ const login = headers.get("tailscale-user-login");
9607
+ if (login === null) return void 0;
9608
+ const ref = decodeEncodedWords(login).trim();
9609
+ if (ref === "" || ref.length > 512) return void 0;
9610
+ const name = decodeEncodedWords(headers.get("tailscale-user-name") ?? "").trim();
9611
+ return {
9612
+ ref,
9613
+ ...name !== "" && name.length <= 256 ? { name } : {}
9614
+ };
9615
+ }
9616
+ //#endregion
9138
9617
  //#region src/gateway/integrity.ts
9139
9618
  /**
9140
9619
  * Integrity of served versions (FAILURE_MODEL §3: reads verify content). Before a version's
@@ -9236,7 +9715,9 @@ function versionIntegrity(store, log) {
9236
9715
  * 1. the `Origin` and content type its intent needs (`checkRequest`; the envelope was checked
9237
9716
  * before routing);
9238
9717
  * 2. the rate limit, on token paths;
9239
- * 3. the session, bound to this origin, with a live token (401, 410);
9718
+ * 3. the session, bound to this origin, with a live token (401, 410): its cookie in cookie mode,
9719
+ * its frame header in worker mode (D70), or a single-use stream ticket on stream routes
9720
+ * (D158 item 5);
9240
9721
  * 4. the session's CSRF token, on mutations;
9241
9722
  * 5. the scope.
9242
9723
  *
@@ -9290,9 +9771,12 @@ function mount(app, checks, routes) {
9290
9771
  const limited = checks.capabilities.limited(artifactId);
9291
9772
  if (limited) return refuse(checks, limited, meta);
9292
9773
  }
9774
+ const mode = checks.mode?.() ?? "cookie";
9775
+ const ticket = route.intent === "stream" ? url.searchParams.get("ticket") : null;
9776
+ if (route.sse && (checks.streams?.() === false || mode === "worker" && ticket === null)) return refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", checks.streams?.() === false ? "Event streams don't pass this address; long-poll instead (events/poll)." : "A worker-mode frame opens its event stream with a ticket; long-poll instead.", 503), meta);
9293
9777
  let session;
9294
9778
  if (route.auth === "session" && artifactId !== void 0) {
9295
- const resolved = checks.capabilities.session(cookieValues(request.headers.get("cookie"), checks.cookieName()), policy.origin, artifactId);
9779
+ const resolved = ticket !== null ? checks.capabilities.redeemStreamTicket(ticket, policy.origin, artifactId, "stream") : mode === "worker" ? checks.capabilities.session([request.headers.get(FRAME_SESSION_HEADER) ?? ""], policy.origin, artifactId, "worker") : checks.capabilities.session(cookieValues(request.headers.get("cookie"), checks.cookieName()), policy.origin, artifactId);
9296
9780
  if (isRefusal(resolved)) return refuse(checks, resolved, meta);
9297
9781
  session = resolved;
9298
9782
  if (route.intent === "mutation") {
@@ -9312,7 +9796,8 @@ function mount(app, checks, routes) {
9312
9796
  params,
9313
9797
  artifactId,
9314
9798
  ...session ? { session } : {},
9315
- document
9799
+ document,
9800
+ remote: incoming.socket.remoteAddress
9316
9801
  });
9317
9802
  };
9318
9803
  if (route.method === "GET") app.get(route.path, handle);
@@ -9669,6 +10154,207 @@ function fileResponse(file, request, headers) {
9669
10154
  });
9670
10155
  }
9671
10156
  //#endregion
10157
+ //#region src/gateway/worker.ts
10158
+ /**
10159
+ * Worker-mode frame sessions (D70, D158 item 5): where the shell and the artifact are two sites,
10160
+ * no cookie reaches the artifact's frame (VERIFIED_FACTS, cross-site frames). The frame enters
10161
+ * through a bootstrap page instead: it exchanges the shell's single-use ticket for a frame
10162
+ * session, installs Mostra's service worker at `/`, and enters the version, whose every
10163
+ * same-origin request then carries the session in a header. Event streams, polls and WebSockets
10164
+ * bypass the worker with single-use tickets, since Firefox stalls on endless responses a worker
10165
+ * passes on.
10166
+ *
10167
+ * This module holds the two documents the browser runs: the bootstrap page and the worker. Both
10168
+ * are plain scripts with no imports, served by the gateway from the artifact's origin.
10169
+ */
10170
+ /** Where the service worker is served; its registration's scope is `/`. */
10171
+ const SERVICE_WORKER_PATH = "/_mostra/sw.js";
10172
+ /** The IndexedDB the frame session's secret is kept in, per artifact origin and top-level site. */
10173
+ const DB = "mostra-frame";
10174
+ /**
10175
+ * The service worker (D70): it adds the frame session's header to every same-origin request but
10176
+ * its own script, the bootstrap's, and ticketed ones (`?ticket=`: streams, polls and sockets),
10177
+ * and keeps the secret in IndexedDB, since a browser stops idle workers and their memory goes.
10178
+ * A request a header can't be added to as made (a `no-cors` script or image, a navigation) is
10179
+ * sent again as a same-origin request, which carries it.
10180
+ */
10181
+ const SERVICE_WORKER_SOURCE = `// Mostra's frame-session worker (D70). It signs this origin's requests for the artifact's frame.
10182
+ "use strict";
10183
+ const HEADER = ${JSON.stringify(FRAME_SESSION_HEADER)};
10184
+ const DB = ${JSON.stringify(DB)};
10185
+ const STORE = "session";
10186
+ let secret;
10187
+ function store(mode, act) {
10188
+ return new Promise((resolve, reject) => {
10189
+ const open = indexedDB.open(DB, 1);
10190
+ open.onupgradeneeded = () => open.result.createObjectStore(STORE);
10191
+ open.onerror = () => reject(open.error);
10192
+ open.onsuccess = () => {
10193
+ const db = open.result;
10194
+ const tx = db.transaction(STORE, mode);
10195
+ const request = act(tx.objectStore(STORE));
10196
+ tx.oncomplete = () => { db.close(); resolve(request.result); };
10197
+ tx.onerror = tx.onabort = () => { db.close(); reject(tx.error); };
10198
+ };
10199
+ });
10200
+ }
10201
+ async function current() {
10202
+ if (secret === undefined) {
10203
+ try { secret = await store("readonly", (s) => s.get("secret")); } catch { secret = undefined; }
10204
+ }
10205
+ return secret;
10206
+ }
10207
+ self.addEventListener("install", () => { self.skipWaiting(); });
10208
+ self.addEventListener("activate", (event) => { event.waitUntil(self.clients.claim()); });
10209
+ self.addEventListener("message", (event) => {
10210
+ const data = event.data;
10211
+ if (!data || data.type !== "mostra/frame-session" || typeof data.secret !== "string") return;
10212
+ secret = data.secret;
10213
+ const port = event.ports[0];
10214
+ event.waitUntil(
10215
+ store("readwrite", (s) => s.put(data.secret, "secret")).then(
10216
+ () => port && port.postMessage({ ok: true }),
10217
+ (error) => port && port.postMessage({ ok: false, message: String(error) }),
10218
+ ),
10219
+ );
10220
+ });
10221
+ self.addEventListener("fetch", (event) => {
10222
+ const request = event.request;
10223
+ const url = new URL(request.url);
10224
+ if (url.origin !== self.location.origin) return;
10225
+ if (url.pathname === ${JSON.stringify(SERVICE_WORKER_PATH)} || url.pathname === "/_mostra/enter") return;
10226
+ if (url.searchParams.has("ticket")) return;
10227
+ event.respondWith(signed(request));
10228
+ });
10229
+ async function signed(request) {
10230
+ const value = await current();
10231
+ if (!value) return fetch(request);
10232
+ const headers = new Headers(request.headers);
10233
+ headers.set(HEADER, value);
10234
+ const navigate = request.mode === "navigate";
10235
+ // Sent on, a navigation is an ordinary request: the gateway learns it was one from this header.
10236
+ if (navigate) headers.set("x-mostra-navigation", "1");
10237
+ const init = {
10238
+ method: request.method,
10239
+ headers,
10240
+ mode: navigate || request.mode === "no-cors" ? "same-origin" : request.mode,
10241
+ credentials: request.credentials,
10242
+ cache: request.cache === "only-if-cached" ? "default" : request.cache,
10243
+ redirect: navigate ? "manual" : request.redirect,
10244
+ referrerPolicy: request.referrerPolicy,
10245
+ integrity: request.integrity,
10246
+ keepalive: request.keepalive,
10247
+ signal: request.signal,
10248
+ };
10249
+ if (request.method !== "GET" && request.method !== "HEAD") init.body = await request.arrayBuffer();
10250
+ return fetch(new Request(request.url, init));
10251
+ }
10252
+ `;
10253
+ /**
10254
+ * The bootstrap page at `/_mostra/enter#t=<ticket>` (D70): it takes the ticket from the fragment
10255
+ * (so no server, log or `Referer` sees it), exchanges it at `POST /_mostra/enter` (sending the
10256
+ * session it kept, so a frame that re-enters keeps its session and switches version), installs
10257
+ * the worker at `/`, hands it the secret, tells the shell (`mostra/frameSession.entered`) and
10258
+ * enters the version at `/`. Whatever stops it is reported to the shell as
10259
+ * `mostra/frameSession.failed` with `MOSTRA_HYGIENE_FRAME_SESSION`.
10260
+ */
10261
+ const BOOTSTRAP_PAGE = `<!doctype html>
10262
+ <html lang="en">
10263
+ <head>
10264
+ <meta charset="utf-8">
10265
+ <meta name="referrer" content="no-referrer">
10266
+ <meta name="viewport" content="width=device-width, initial-scale=1">
10267
+ <title>Mostra</title>
10268
+ <style>body{font-family:system-ui,sans-serif;margin:0;min-height:100vh;display:flex;justify-content:center;align-items:center;padding:2rem;text-align:center;color-scheme:light dark;opacity:.8}</style>
10269
+ </head>
10270
+ <body>
10271
+ <script>
10272
+ (async () => {
10273
+ "use strict";
10274
+ const HEADER = ${JSON.stringify(FRAME_SESSION_HEADER)};
10275
+ let shell = "*";
10276
+ const fail = (reason, message) => {
10277
+ document.body.textContent = message;
10278
+ parent.postMessage(
10279
+ { jsonrpc: "2.0", method: "mostra/frameSession.failed",
10280
+ params: { code: "MOSTRA_HYGIENE_FRAME_SESSION", reason, message } },
10281
+ shell,
10282
+ );
10283
+ };
10284
+ const kept = () => new Promise((resolve) => {
10285
+ try {
10286
+ const open = indexedDB.open(${JSON.stringify(DB)}, 1);
10287
+ open.onupgradeneeded = () => open.result.createObjectStore("session");
10288
+ open.onerror = () => resolve(undefined);
10289
+ open.onsuccess = () => {
10290
+ const db = open.result;
10291
+ try {
10292
+ const read = db.transaction("session", "readonly").objectStore("session").get("secret");
10293
+ read.onsuccess = () => { db.close(); resolve(typeof read.result === "string" ? read.result : undefined); };
10294
+ read.onerror = () => { db.close(); resolve(undefined); };
10295
+ } catch { db.close(); resolve(undefined); }
10296
+ };
10297
+ } catch { resolve(undefined); }
10298
+ });
10299
+ const ticket = new URLSearchParams(location.hash.slice(1)).get("t");
10300
+ history.replaceState(null, "", location.pathname);
10301
+ if (!ticket) return fail("refused", "This frame was opened without a ticket.");
10302
+ if (!("serviceWorker" in navigator) || typeof indexedDB === "undefined") {
10303
+ return fail("unsupported", "This browser offers the artifact's frame no service worker here, which this link needs.");
10304
+ }
10305
+ let answer;
10306
+ try {
10307
+ const previous = await kept();
10308
+ const response = await fetch("/_mostra/enter", {
10309
+ method: "POST",
10310
+ credentials: "omit",
10311
+ cache: "no-store",
10312
+ headers: { "content-type": "application/json", ...(previous ? { [HEADER]: previous } : {}) },
10313
+ body: JSON.stringify({ ticket }),
10314
+ });
10315
+ answer = await response.json().catch(() => ({}));
10316
+ if (!response.ok) return fail("refused", answer.message || "The frame's entry was refused.");
10317
+ } catch (error) {
10318
+ return fail("refused", "The frame couldn't reach Mostra: " + error);
10319
+ }
10320
+ shell = answer.shellOrigin;
10321
+ try {
10322
+ const found = await navigator.serviceWorker.getRegistration("/");
10323
+ const script = found && (found.active || found.waiting || found.installing);
10324
+ if (script && new URL(script.scriptURL).pathname !== ${JSON.stringify(SERVICE_WORKER_PATH)}) {
10325
+ console.warn("Mostra replaced another service worker at / on this origin: a worker-mode frame needs its own there (MOSTRA_HYGIENE_FRAME_SESSION).");
10326
+ }
10327
+ const registration = await navigator.serviceWorker.register(${JSON.stringify(SERVICE_WORKER_PATH)}, { scope: "/", updateViaCache: "none" });
10328
+ const worker = registration.installing || registration.waiting || registration.active;
10329
+ if (!worker) throw new Error("no worker");
10330
+ if (worker.state !== "activated") {
10331
+ await new Promise((resolve, reject) => {
10332
+ const timer = setTimeout(() => reject(new Error("the worker didn't activate in 20 s")), 20000);
10333
+ worker.addEventListener("statechange", () => {
10334
+ if (worker.state === "activated") { clearTimeout(timer); resolve(); }
10335
+ if (worker.state === "redundant") { clearTimeout(timer); reject(new Error("the worker was replaced")); }
10336
+ });
10337
+ });
10338
+ }
10339
+ const stored = await new Promise((resolve) => {
10340
+ const channel = new MessageChannel();
10341
+ const timer = setTimeout(() => resolve({ ok: false, message: "no answer" }), 10000);
10342
+ channel.port1.onmessage = (event) => { clearTimeout(timer); resolve(event.data); };
10343
+ worker.postMessage({ type: "mostra/frame-session", secret: answer.session }, [channel.port2]);
10344
+ });
10345
+ if (!stored || !stored.ok) throw new Error(stored && stored.message);
10346
+ } catch (error) {
10347
+ return fail("blocked", "This browser didn't let the artifact's frame install the service worker this link needs (" + error + ").");
10348
+ }
10349
+ // The shell waits for the page from here: this page's own load wasn't the page's.
10350
+ parent.postMessage({ jsonrpc: "2.0", method: "mostra/frameSession.entered", params: {} }, shell);
10351
+ location.replace("/");
10352
+ })();
10353
+ <\/script>
10354
+ </body>
10355
+ </html>
10356
+ `;
10357
+ //#endregion
9672
10358
  //#region src/gateway/controls.ts
9673
10359
  /**
9674
10360
  * The submit channels and trusted controls in force for a view (D40, D108). A host that
@@ -9727,108 +10413,56 @@ function normalize(policy) {
9727
10413
  };
9728
10414
  }
9729
10415
  //#endregion
9730
- //#region src/gateway/identity.ts
10416
+ //#region src/gateway/index.ts
9731
10417
  /**
9732
- * Who a browser is (D143 item 2). A link minted with a viewer acts for that viewer (D104) and asks
9733
- * nothing. For a link without one, a host that registered the `identity` port names the person
9734
- * from the request's headers; without such a host, the session acts as the home's local user.
10418
+ * The gateway (ARCHITECTURE §5, §10; D38, D96 to D99, D158): the HTTP side of an instance. It
10419
+ * serves the shell on the shell's leased port and each opened artifact on its own leased port, all
10420
+ * on one host, so the shell and every artifact are same-site but different origins. Only
10421
+ * capability holders get in: a link's token becomes a shell session, the shell hands the
10422
+ * artifact's frame a single-use ticket, and the frame's session lets it load its version's files.
10423
+ * Every request goes through the same checks (`routes.ts`), and published versions are served
10424
+ * straight from disk, with no process (RT-05). It also serves `view/url`, `view/rotate` and
10425
+ * `view/revoke`.
10426
+ *
10427
+ * Beside those loopback listeners, the gateway has **faces** (D158 item 1): external addresses of
10428
+ * the shell or one artifact (a tailnet, Funnel or Cloudflare address a share set up, or a host's
10429
+ * external base), each its own listener on loopback with one origin and one exact `Host`. Which
10430
+ * face a request came through is the socket it arrived on, so a tunnel's visitor can't claim
10431
+ * another address. A face pairs with the faces of its group (a share's, a host's): its shell opens
10432
+ * frames on the group's artifact face, in cookie mode when both are one site and in worker mode
10433
+ * (D70) when they are two.
10434
+ *
10435
+ * ```ts
10436
+ * const gateway = createGateway({ ledger, log, addressing, capabilities, artifacts, shellDir });
10437
+ * await gateway.start();
10438
+ * const { url } = await gateway.defaultLink(artifactId); // the publish receipt's URL
10439
+ * const face = await gateway.openFace({ by: "cloudflare", group, listener: "shell", … });
10440
+ * ```
9735
10441
  */
9736
- /** How long a host has to answer `port/identity.resolve`: a page waits for it, as for D108. */
9737
- const IDENTITY_TIMEOUT_MS = 5e3;
10442
+ const NO_STORE = { "cache-control": "no-store" };
10443
+ /** How recently an artifact must have been viewed for its port to be bound at start (D129). */
10444
+ const RECENT_VIEW_MS = 6048e5;
10445
+ /** How long a host's answer for an artifact's frame address is reused (D158 item 6). */
10446
+ const EXTERNAL_BASE_REUSE_MS = 3e4;
9738
10447
  /**
9739
- * The headers a host sees: names in lower case, without `cookie` (Mostra's sessions and every
9740
- * other page's of this host) and without Mostra's own `x-mostra-*` headers.
10448
+ * How long a withdrawn face's listener stays open, refusing everything, so the request that
10449
+ * learned of the withdrawal still gets its answer (D158 item 6).
9741
10450
  */
9742
- function identityHeaders(headers) {
9743
- const seen = {};
9744
- headers.forEach((value, name) => {
9745
- const key = name.toLowerCase();
9746
- if (key === "cookie" || key.startsWith("x-mostra-")) return;
9747
- seen[key] = value;
9748
- });
9749
- return seen;
10451
+ const FACE_LINGER_MS = 2e3;
10452
+ /** The key of a face: `<group>:shell`, or `<group>:<artifactId>` for an artifact's. */
10453
+ function faceKey(group, listener, artifactId) {
10454
+ return `${group}:${listener === "shell" ? "shell" : artifactId ?? ""}`;
9750
10455
  }
9751
10456
  /**
9752
- * Asks the host that took identity over. Its outage never makes the session someone else: a
9753
- * failure, a timeout, an answer the schema refuses, or an expected host that isn't connected is
9754
- * `unavailable`, and the exchange is refused.
9755
- */
9756
- async function resolveIdentity(input) {
9757
- const registrant = input.registrant();
9758
- const unavailable = (message) => ({
9759
- kind: "unavailable",
9760
- diagnostic: createDiagnostic("MOSTRA_HOST_IDENTITY_UNAVAILABLE", { message })
9761
- });
9762
- if (registrant) try {
9763
- const answer = await input.call(registrant.session, {
9764
- artifactId: input.artifactId,
9765
- via: input.via,
9766
- headers: identityHeaders(input.headers)
9767
- });
9768
- const parsed = portIdentityResolveMethod.result.safeParse(answer);
9769
- if (parsed.success) return parsed.data === null ? { kind: "default" } : {
9770
- kind: "person",
9771
- viewer: parsed.data
9772
- };
9773
- input.log.warn("gateway.identity_invalid", {
9774
- owner: registrant.owner,
9775
- artifactId: input.artifactId
9776
- });
9777
- return unavailable(`The host ${registrant.owner} answered who this is in a form Mostra refuses.`);
9778
- } catch (error) {
9779
- input.log.warn("gateway.identity_failed", {
9780
- owner: registrant.owner,
9781
- artifactId: input.artifactId,
9782
- error: error.message
9783
- });
9784
- return unavailable(`The host ${registrant.owner} didn't say who this is.`);
9785
- }
9786
- const away = input.expected();
9787
- if (away.length > 0) {
9788
- input.log.warn("gateway.identity_host_away", {
9789
- owners: away,
9790
- artifactId: input.artifactId
9791
- });
9792
- return unavailable(`The host that identifies this home's viewers (${away.join(", ")}) isn't running.`);
9793
- }
9794
- return { kind: "default" };
9795
- }
9796
- //#endregion
9797
- //#region src/gateway/index.ts
9798
- /**
9799
- * The gateway (ARCHITECTURE §5, §10; D38, D96 to D99): the HTTP side of an instance. It serves
9800
- * the shell on the shell's leased port and each opened artifact on its own leased port, all on one
9801
- * host, so the shell and every artifact are same-site but different origins. Only capability
9802
- * holders get in: a link's token becomes a shell session, the shell hands the artifact's frame a
9803
- * single-use ticket, and the frame's session lets it load its version's files. Every request goes
9804
- * through the same checks (`routes.ts`), and published versions are served straight from disk,
9805
- * with no process (RT-05). It also serves `view/url`, `view/rotate` and `view/revoke`.
9806
- *
9807
- * ```ts
9808
- * const gateway = createGateway({ ledger, log, addressing, capabilities, artifacts, shellDir });
9809
- * await gateway.start();
9810
- * const { url } = await gateway.defaultLink(artifactId); // the publish receipt's URL
9811
- * ```
9812
- */
9813
- const NO_STORE = { "cache-control": "no-store" };
9814
- /** How recently an artifact must have been viewed for its port to be bound at start (D129). */
9815
- const RECENT_VIEW_MS = 6048e5;
9816
- /**
9817
10457
  * The browser-protocol routes of INTERFACES §4 (D96): WP-06 serves `fields`, `submit`, `signal`,
9818
- * `events` and `events/poll`; the others answer 501 until their package attaches a handler.
10458
+ * `events` and `events/poll`; WP-08 the calls, runs and live sources; WP-13 the stream tickets.
9819
10459
  */
9820
- function laterArtifactRoutes(served, acting) {
10460
+ function laterArtifactRoutes(served, acting, ticket) {
9821
10461
  const action = (params) => {
9822
10462
  const id = params["fn"];
9823
10463
  return id ? `action:${id}` : "any-action";
9824
10464
  };
9825
10465
  return [
9826
- {
9827
- method: "GET",
9828
- path: "/_mostra/sw.js",
9829
- intent: "read",
9830
- auth: "none"
9831
- },
9832
10466
  {
9833
10467
  method: "POST",
9834
10468
  path: "/_mostra/v/:rev/fields",
@@ -9896,13 +10530,15 @@ function laterArtifactRoutes(served, acting) {
9896
10530
  method: "POST",
9897
10531
  path: "/_mostra/v/:rev/ticket",
9898
10532
  intent: "mutation",
9899
- auth: "session"
10533
+ auth: "session",
10534
+ handler: ticket
9900
10535
  },
9901
10536
  {
9902
10537
  method: "GET",
9903
10538
  path: "/_mostra/v/:rev/events",
9904
10539
  intent: "stream",
9905
10540
  auth: "session",
10541
+ sse: true,
9906
10542
  handler: served.stream
9907
10543
  },
9908
10544
  {
@@ -9947,17 +10583,70 @@ function createGateway(options) {
9947
10583
  };
9948
10584
  const artifactListeners = /* @__PURE__ */ new Map();
9949
10585
  const opening = /* @__PURE__ */ new Map();
10586
+ const faces = /* @__PURE__ */ new Map();
10587
+ const openingFaces = /* @__PURE__ */ new Map();
10588
+ /** A host's recent answers for artifacts' frame addresses, by face key (D158 item 6). */
10589
+ const askedRecently = /* @__PURE__ */ new Map();
9950
10590
  const integrity = versionIntegrity(artifacts, log);
10591
+ const loopbackShell = {
10592
+ listener: "shell",
10593
+ by: "loopback",
10594
+ via: "local",
10595
+ artifactId: void 0,
10596
+ port: () => shellPort ?? 0,
10597
+ origin: () => shellOrigin(),
10598
+ hosts: () => addressing.hosts(shellPort ?? 0),
10599
+ streams: () => true
10600
+ };
10601
+ const loopbackArtifact = (artifactId, port) => ({
10602
+ listener: "artifact",
10603
+ by: "loopback",
10604
+ via: "local",
10605
+ artifactId,
10606
+ port,
10607
+ origin: () => addressing.origin(port()),
10608
+ hosts: () => addressing.hosts(port()),
10609
+ streams: () => true
10610
+ });
10611
+ const faceWay = (entry) => ({
10612
+ listener: entry.spec.listener,
10613
+ by: entry.spec.by,
10614
+ via: entry.spec.via,
10615
+ artifactId: entry.spec.artifactId,
10616
+ port: () => entry.port,
10617
+ origin: () => entry.origin,
10618
+ hosts: () => entry.origin === void 0 ? [] : [hostOf(entry.origin)],
10619
+ streams: () => entry.spec.streams !== false
10620
+ });
10621
+ /** The shell of a way's group: the loopback shell, or the group's shell face. */
10622
+ const shellOf = (way, group) => {
10623
+ if (way.by === "loopback" || group === void 0) return loopbackShell;
10624
+ const entry = faces.get(faceKey(group, "shell"));
10625
+ return entry ? faceWay(entry) : void 0;
10626
+ };
10627
+ /** How an artifact way's frames authenticate: by the pair, unless its keeper said (D70). */
10628
+ const modeOf = (artifact, group) => {
10629
+ if (artifact.by === "loopback" || group === void 0) return "cookie";
10630
+ const entry = faces.get(faceKey(group, "artifact", artifact.artifactId));
10631
+ if (entry?.spec.mode) return entry.spec.mode;
10632
+ const shell = shellOf(artifact, group)?.origin();
10633
+ const own = artifact.origin();
10634
+ return shell !== void 0 && own !== void 0 ? addressing.frameMode(shell, own) : "worker";
10635
+ };
10636
+ /** Whether an origin is `https:`, where every cookie is `Secure`. */
10637
+ const secure = (origin) => origin?.startsWith("https:") === true;
10638
+ /** Whether the gateway serves a shell at this origin now: launch tickets go only there. */
10639
+ const servesShell = (origin) => origin === shellOrigin() || [...faces.values()].some((entry) => entry.spec.listener === "shell" && entry.origin === origin);
9951
10640
  /** The answer for a damaged version: a plain page for a navigation, else the diagnostic. */
9952
- const damaged = (number, damage, document) => refusalResponse({
10641
+ const damaged = (number, damage, document, frameAncestors) => refusalResponse({
9953
10642
  status: 500,
9954
10643
  diagnostic: createDiagnostic("MOSTRA_HOME_INTEGRITY", { message: `${number === void 0 ? "A version" : `Version ${number}`} of this artifact is damaged: ${damage}.` })
9955
10644
  }, {
9956
10645
  document,
9957
- frameAncestors: shellOrigin()
10646
+ frameAncestors
9958
10647
  });
9959
10648
  const link = (token) => ({
9960
- url: `${shellOrigin()}/a/${token.artifactId}${token.pinnedVersion !== void 0 ? `/v/${token.pinnedVersion}` : ""}#t=${token.secret}`,
10649
+ url: `${token.shellOrigin}/a/${token.artifactId}${token.pinnedVersion !== void 0 ? `/v/${token.pinnedVersion}` : ""}#t=${token.secret}`,
9961
10650
  tokenId: token.tokenId,
9962
10651
  scopes: token.scopes,
9963
10652
  ...token.expiresAt !== void 0 ? { expiresAt: token.expiresAt } : {},
@@ -9972,57 +10661,246 @@ function createGateway(options) {
9972
10661
  ...found.collected !== void 0 ? { collected: found.collected } : {}
9973
10662
  } : void 0;
9974
10663
  };
9975
- const shellKind = () => ({
10664
+ const openFace = (spec, origin) => {
10665
+ const key = faceKey(spec.group, spec.listener, spec.artifactId);
10666
+ const open = faces.get(key);
10667
+ if (open) return Promise.resolve(open);
10668
+ const pending = openingFaces.get(key);
10669
+ if (pending) return pending;
10670
+ const started = (async () => {
10671
+ let entry;
10672
+ const way = () => entry ? faceWay(entry) : {
10673
+ ...loopbackShell,
10674
+ origin: () => void 0,
10675
+ hosts: () => []
10676
+ };
10677
+ const listener = createListener({
10678
+ policy: () => ({
10679
+ origin: entry?.origin ?? "",
10680
+ hosts: way().hosts()
10681
+ }),
10682
+ log,
10683
+ frameAncestors: () => spec.listener === "shell" ? "'none'" : shellOf(way(), spec.group)?.origin() ?? "'none'",
10684
+ configure: (app) => {
10685
+ if (spec.listener === "shell") mount(app, shellChecks(way), shellRoutes(way, spec.group));
10686
+ else {
10687
+ const artifactId = spec.artifactId;
10688
+ mount(app, artifactChecks(artifactId, way, spec.group), artifactRoutes(artifactId, way, spec.group));
10689
+ }
10690
+ },
10691
+ ...spec.listener === "artifact" ? { upgrade: socketUpgrade(spec.artifactId, way, spec.group) } : {},
10692
+ ...options.traceRequests ? { traceRequests: true } : {}
10693
+ });
10694
+ await endLingering(key);
10695
+ const port = await addressing.listenFace(listener.server, {
10696
+ key,
10697
+ lease: spec.lease
10698
+ });
10699
+ entry = {
10700
+ key,
10701
+ spec,
10702
+ listener,
10703
+ port,
10704
+ origin
10705
+ };
10706
+ faces.set(key, entry);
10707
+ log.info("gateway.face_open", {
10708
+ key,
10709
+ by: spec.by,
10710
+ local: addressing.faceLocal(port),
10711
+ ...origin !== void 0 ? { origin } : {}
10712
+ });
10713
+ return entry;
10714
+ })().finally(() => openingFaces.delete(key));
10715
+ openingFaces.set(key, started);
10716
+ return started;
10717
+ };
10718
+ const handleOf = (entry) => ({
10719
+ key: entry.key,
10720
+ port: entry.port,
10721
+ local: addressing.faceLocal(entry.port),
10722
+ origin: () => entry.origin,
10723
+ setOrigin: (origin) => {
10724
+ if (entry.origin !== origin) log.info("gateway.face_address", {
10725
+ key: entry.key,
10726
+ ...origin !== void 0 ? { origin } : {}
10727
+ });
10728
+ entry.origin = origin;
10729
+ }
10730
+ });
10731
+ const closeFace = async (key, release = false) => {
10732
+ const pending = openingFaces.get(key);
10733
+ if (pending) await pending.catch(() => void 0);
10734
+ const entry = faces.get(key);
10735
+ if (entry) {
10736
+ faces.delete(key);
10737
+ await entry.listener.close();
10738
+ log.info("gateway.face_closed", { key });
10739
+ }
10740
+ if (release) addressing.releaseFace(key);
10741
+ };
10742
+ /**
10743
+ * Withdrawn faces' listeners, by face key, closing after {@link FACE_LINGER_MS}; a face of the
10744
+ * same key opened meanwhile, or the gateway's close, closes one at once.
10745
+ */
10746
+ const lingering = /* @__PURE__ */ new Map();
10747
+ /** Closes a withdrawn face's listener now, if one still lingers, freeing its port. */
10748
+ const endLingering = async (key) => {
10749
+ const listener = lingering.get(key);
10750
+ if (!listener) return;
10751
+ lingering.delete(key);
10752
+ await listener.close();
10753
+ };
10754
+ /**
10755
+ * Withdraws a face at once and closes its listener a moment later: from now on its `Host` is
10756
+ * served nowhere (every request is refused, 421), while the request that learned of the
10757
+ * withdrawal (an exchange that asked the host) still gets its own answer, 410, rather than a
10758
+ * connection closed under it.
10759
+ */
10760
+ const withdrawFace = (key) => {
10761
+ const entry = faces.get(key);
10762
+ if (!entry) {
10763
+ addressing.releaseFace(key);
10764
+ return;
10765
+ }
10766
+ faces.delete(key);
10767
+ entry.origin = void 0;
10768
+ lingering.set(key, entry.listener);
10769
+ log.info("gateway.face_withdrawn", { key });
10770
+ setTimeout(() => {
10771
+ if (lingering.get(key) !== entry.listener) return;
10772
+ endLingering(key).then(() => {
10773
+ if (!faces.has(key)) addressing.releaseFace(key);
10774
+ });
10775
+ }, FACE_LINGER_MS).unref?.();
10776
+ };
10777
+ /** The kept external bases, so a restart serves their links before the host answers again. */
10778
+ const keptBases = () => options.ledger.read((db) => db.all("SELECT key, listener, artifact_id, origin, mode FROM external_base"));
10779
+ const hostSpec = (artifactId, listener, mode) => ({
10780
+ by: "host",
10781
+ group: `host:${artifactId}`,
10782
+ listener,
10783
+ artifactId,
10784
+ via: "token",
10785
+ lease: true,
10786
+ ...mode ? { mode } : {}
10787
+ });
10788
+ /**
10789
+ * The host's face of one of an artifact's listeners, asked again now: the address it gives
10790
+ * (kept, so its links work after a restart), or none. `null`, or another origin, withdraws the
10791
+ * face given before, whose links stop working; a host that fails or is away keeps what it gave.
10792
+ */
10793
+ const hostFaceTurns = /* @__PURE__ */ new Map();
10794
+ /**
10795
+ * One question to the host per face at a time (Opus review of WP-13): a question that fails
10796
+ * never closes a face another question just set up, and every question reads what the one
10797
+ * before it left.
10798
+ */
10799
+ const hostFace = (artifactId, listener) => {
10800
+ const key = faceKey(`host:${artifactId}`, listener, artifactId);
10801
+ const turn = (hostFaceTurns.get(key) ?? Promise.resolve()).then(() => askHostFace(artifactId, listener), () => askHostFace(artifactId, listener));
10802
+ const settled = turn.catch(() => void 0);
10803
+ hostFaceTurns.set(key, settled);
10804
+ settled.then(() => {
10805
+ if (hostFaceTurns.get(key) === settled) hostFaceTurns.delete(key);
10806
+ });
10807
+ return turn;
10808
+ };
10809
+ const askHostFace = async (artifactId, listener) => {
10810
+ try {
10811
+ artifacts.get({ artifactId });
10812
+ } catch {
10813
+ return;
10814
+ }
10815
+ const port = options.externalBase;
10816
+ const key = faceKey(`host:${artifactId}`, listener, artifactId);
10817
+ const kept = faces.get(key);
10818
+ if (!port?.registered()) return kept?.origin !== void 0 ? kept : void 0;
10819
+ if (listener === "artifact" && kept && Date.now() - (askedRecently.get(key) ?? 0) < EXTERNAL_BASE_REUSE_MS) return kept;
10820
+ const entry = kept ?? await openFace(hostSpec(artifactId, listener));
10821
+ const answer = await port.ask({
10822
+ artifactId,
10823
+ listener,
10824
+ local: addressing.faceLocal(entry.port)
10825
+ });
10826
+ if (answer.kind === "failed" || answer.kind === "away") {
10827
+ if (kept?.origin !== void 0) return kept;
10828
+ if (!kept) await closeFace(key, true);
10829
+ return;
10830
+ }
10831
+ if (answer.kind === "none") {
10832
+ options.ledger.write((db) => db.run("DELETE FROM external_base WHERE key = ?", key));
10833
+ if (kept?.origin !== void 0) withdrawFace(key);
10834
+ else await closeFace(key, true);
10835
+ return;
10836
+ }
10837
+ const origin = answer.base.origin;
10838
+ const mode = answer.base.mode;
10839
+ if (entry.origin !== origin || (entry.spec.mode ?? null) !== (mode ?? null)) {
10840
+ if ((entry.spec.mode ?? null) !== (mode ?? null)) await closeFace(key);
10841
+ const fresh = faces.get(key) ?? await openFace(hostSpec(artifactId, listener, mode), origin);
10842
+ fresh.origin = origin;
10843
+ options.ledger.write((db) => db.run("INSERT INTO external_base (key, listener, artifact_id, origin, mode, client, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(key) DO UPDATE SET origin = excluded.origin, mode = excluded.mode, updated_at = excluded.updated_at", key, listener, artifactId, origin, mode ?? null, answer.owner, (/* @__PURE__ */ new Date()).toISOString()));
10844
+ askedRecently.set(key, Date.now());
10845
+ return fresh;
10846
+ }
10847
+ askedRecently.set(key, Date.now());
10848
+ return entry;
10849
+ };
10850
+ /** Where an artifact's links point: a host's external base when it gives one, else loopback. */
10851
+ const linkBase = async (artifactId) => {
10852
+ return (await hostFace(artifactId, "shell"))?.origin ?? shellOrigin();
10853
+ };
10854
+ /** The artifact way a shell way opens frames on, or why there is none. */
10855
+ const artifactWayFor = async (shell, group, artifactId) => {
10856
+ if (shell.by === "loopback" || group === void 0) {
10857
+ const port = await openArtifact(artifactId);
10858
+ return {
10859
+ way: loopbackArtifact(artifactId, () => port),
10860
+ group: void 0
10861
+ };
10862
+ }
10863
+ if (shell.by === "host") {
10864
+ const entry = await hostFace(artifactId, "artifact");
10865
+ if (entry?.origin === void 0) return refusal("MOSTRA_HYGIENE_NOT_SERVED", "The host gives this artifact's frame no address here.", 503);
10866
+ return {
10867
+ way: faceWay(entry),
10868
+ group
10869
+ };
10870
+ }
10871
+ const entry = faces.get(faceKey(group, "artifact", artifactId));
10872
+ if (entry?.origin === void 0) return refusal("MOSTRA_HYGIENE_NOT_SERVED", "This artifact isn't shared at this address.");
10873
+ return {
10874
+ way: faceWay(entry),
10875
+ group
10876
+ };
10877
+ };
10878
+ const shellKind = (way) => ({
9976
10879
  kind: "shell",
9977
- origin: shellOrigin(),
9978
- shellOrigin: shellOrigin()
10880
+ origin: way.origin() ?? "",
10881
+ shellOrigin: way.origin() ?? ""
9979
10882
  });
9980
- const shellChecks = {
10883
+ const shellChecks = (way) => ({
9981
10884
  policy: () => ({
9982
- origin: shellOrigin(),
9983
- hosts: addressing.hosts(shellPort ?? 0)
10885
+ origin: way().origin() ?? "",
10886
+ hosts: way().hosts()
9984
10887
  }),
9985
10888
  capabilities,
9986
10889
  log,
9987
- cookieName: () => `mostra-${shellPort}`,
10890
+ cookieName: () => `mostra-${way().port()}`,
9988
10891
  frameAncestors: () => "'none'",
9989
10892
  artifactOf: (params) => {
9990
10893
  const id = params["artifactId"];
9991
- return id !== void 0 && ArtifactId.is(id) ? id : void 0;
9992
- }
9993
- };
10894
+ const own = way().artifactId;
10895
+ return id !== void 0 && ArtifactId.is(id) && (own === void 0 || own === id) ? id : void 0;
10896
+ },
10897
+ streams: () => way().streams()
10898
+ });
9994
10899
  const shellMissing = () => jsonResponse(createDiagnostic("MOSTRA_ENV_SHELL_MISSING", { message: "This Mostra runtime has no built shell." }), { status: 503 });
9995
- /** The shell's page: the same for every artifact; it learns everything from its session. */
9996
- const shellPage = (context) => {
9997
- if (options.shellDir === void 0) return shellMissing();
9998
- if (context.artifactId === void 0) return refuse(shellChecks, refusal("MOSTRA_HYGIENE_NOT_SERVED", "No artifact is named at this path."), {
9999
- method: context.request.method,
10000
- path: new URL(context.request.url).pathname,
10001
- document: true
10002
- });
10003
- const html = readFileSync(join(options.shellDir, "index.html"));
10004
- return new Response(context.request.method === "HEAD" ? null : html, { headers: {
10005
- ...BASE_HEADERS,
10006
- ...documentHeaders(shellKind(), `http://${addressing.urlHost}:*`),
10007
- "content-type": "text/html; charset=utf-8",
10008
- "cache-control": "no-cache"
10009
- } });
10010
- };
10011
- const shellAsset = async (context) => {
10012
- if (options.shellDir === void 0) return shellMissing();
10013
- const url = new URL(context.request.url);
10014
- const path = safePath(url.pathname)?.slice(14) ?? "";
10015
- const file = path.startsWith("/assets/") ? await findFile(options.shellDir, path) : void 0;
10016
- if (!file) return refuse(shellChecks, refusal("MOSTRA_HYGIENE_NOT_SERVED", "No shell file at this path."), {
10017
- method: context.request.method,
10018
- path: url.pathname,
10019
- document: false
10020
- });
10021
- return fileResponse(file, context.request, {
10022
- ...documentHeaders(shellKind(), `http://${addressing.urlHost}:*`),
10023
- "cache-control": "public, max-age=31536000, immutable"
10024
- });
10025
- };
10900
+ /** The exchanges each browser made, by artifact (WP-12; see `exchange`). */
10901
+ const madeSessions = /* @__PURE__ */ new Map();
10902
+ let exchangeOrder = 0;
10903
+ const browserKey = (artifactId, browser) => typeof browser === "string" && /^[A-Za-z0-9_-]{16,64}$/.test(browser) ? `${artifactId}\u0000${browser}` : void 0;
10026
10904
  /** What a link allows, as the shell shows it when two links meet. */
10027
10905
  const access = (grant) => ({
10028
10906
  scopes: grant.scopes,
@@ -10040,295 +10918,371 @@ function createGateway(options) {
10040
10918
  ...access(grant)
10041
10919
  };
10042
10920
  };
10043
- /**
10044
- * The sessions exchanges made, by artifact and browser (the shell's own random key, kept in its
10045
- * origin's storage and sent with every exchange), each with the order it was made in. An
10046
- * exchange that waited (the identity port answering) checks here whether another link's
10047
- * session was made for the same browser meanwhile: its request carried no cookie of that session,
10048
- * so D98 item 8's check alone would let the later answer silently replace it (Opus review of
10049
- * WP-12, finding 2). Only the last few thousand are kept; the window that matters is seconds.
10050
- */
10051
- const madeSessions = /* @__PURE__ */ new Map();
10052
- let exchangeOrder = 0;
10053
- const browserKey = (artifactId, browser) => typeof browser === "string" && /^[A-Za-z0-9_-]{16,64}$/.test(browser) ? `${artifactId}\u0000${browser}` : void 0;
10054
- const exchange = async (context) => {
10055
- const artifactId = context.artifactId;
10056
- const startedAt = exchangeOrder;
10057
- const meta = {
10058
- method: "POST",
10059
- path: new URL(context.request.url).pathname,
10060
- document: false
10921
+ const shellRoutes = (wayOf, group) => {
10922
+ const checks = shellChecks(wayOf);
10923
+ /** The shell's page: the same for every artifact; it learns everything from its session. */
10924
+ const shellPage = async (context) => {
10925
+ if (options.shellDir === void 0) return shellMissing();
10926
+ const way = wayOf();
10927
+ if (context.artifactId === void 0) return refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", "No artifact is named at this path."), {
10928
+ method: context.request.method,
10929
+ path: new URL(context.request.url).pathname,
10930
+ document: true
10931
+ });
10932
+ let frames = `http://${addressing.urlHost}:*`;
10933
+ if (way.by !== "loopback") {
10934
+ const found = await artifactWayFor(way, group, context.artifactId).catch(() => void 0);
10935
+ frames = found && !isRefusal(found) ? found.way.origin() ?? "'none'" : "'none'";
10936
+ }
10937
+ const html = readFileSync(join(options.shellDir, "index.html"));
10938
+ return new Response(context.request.method === "HEAD" ? null : html, { headers: {
10939
+ ...BASE_HEADERS,
10940
+ ...documentHeaders(shellKind(way), frames),
10941
+ "content-type": "text/html; charset=utf-8",
10942
+ "cache-control": "no-cache"
10943
+ } });
10061
10944
  };
10062
- const body = await readJsonObject(context.request);
10063
- if (isRefusal(body)) return refuse(shellChecks, body, meta);
10064
- const launch = body["token"] === void 0 && body["launch"] !== void 0;
10065
- const browser = browserKey(artifactId, body["browser"]);
10066
- let grant = launch ? capabilities.presentLaunch(body["launch"], artifactId, false) : capabilities.presentToken(body["token"], artifactId);
10067
- if (isRefusal(grant)) return refuse(shellChecks, grant, meta);
10068
- const existing = capabilities.session(cookieValues(context.request.headers.get("cookie"), shellChecks.cookieName()), shellOrigin(), artifactId);
10069
- if (!isRefusal(existing)) {
10070
- if (existing.grant.tokenId === grant.tokenId) {
10071
- if (launch) capabilities.spendLaunch(body["launch"]);
10072
- return jsonResponse({
10073
- csrf: existing.csrf,
10074
- ...sessionFacts(artifactId, existing.grant)
10075
- });
10945
+ const shellAsset = async (context) => {
10946
+ if (options.shellDir === void 0) return shellMissing();
10947
+ const url = new URL(context.request.url);
10948
+ const path = safePath(url.pathname)?.slice(14) ?? "";
10949
+ const file = path.startsWith("/assets/") ? await findFile(options.shellDir, path) : void 0;
10950
+ if (!file) return refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", "No shell file at this path."), {
10951
+ method: context.request.method,
10952
+ path: url.pathname,
10953
+ document: false
10954
+ });
10955
+ return fileResponse(file, context.request, {
10956
+ ...documentHeaders(shellKind(wayOf()), `http://${addressing.urlHost}:*`),
10957
+ "cache-control": "public, max-age=31536000, immutable"
10958
+ });
10959
+ };
10960
+ /**
10961
+ * Who the session acts as when the link names nobody and no host did (D143 item 2, D158 item
10962
+ * 2): the home's local user on loopback; over a tunnel the tailnet person Tailscale Serve
10963
+ * named, else the link's own viewer, never the home's local user.
10964
+ */
10965
+ const defaultViewer = (way, context, grant) => {
10966
+ if (way.via === "local") return void 0;
10967
+ if (way.via === "tailnet") {
10968
+ const person = tailnetPerson(context.request.headers, context.remote);
10969
+ if (person) return interaction.viewerForTailnet(person);
10076
10970
  }
10077
- if (body["replace"] !== true) {
10971
+ return interaction.viewerForLink(grant.tokenId, "Shared link");
10972
+ };
10973
+ const exchange = async (context) => {
10974
+ const way = wayOf();
10975
+ const origin = way.origin() ?? "";
10976
+ const startedAt = exchangeOrder;
10977
+ const meta = {
10978
+ method: "POST",
10979
+ path: new URL(context.request.url).pathname,
10980
+ document: false
10981
+ };
10982
+ if (context.artifactId === void 0) return refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", "No artifact is served at this path."), meta);
10983
+ const artifactId = context.artifactId;
10984
+ const body = await readJsonObject(context.request);
10985
+ if (isRefusal(body)) return refuse(checks, body, meta);
10986
+ if (way.by === "host") {
10987
+ if ((await hostFace(artifactId, "shell"))?.origin !== origin) return refuse(checks, refusal("MOSTRA_HYGIENE_TOKEN_REVOKED", "The host no longer serves this address.", 410), meta);
10988
+ }
10989
+ const launch = body["token"] === void 0 && body["launch"] !== void 0;
10990
+ const browser = browserKey(artifactId, body["browser"]);
10991
+ let grant = launch ? capabilities.presentLaunch(body["launch"], artifactId, false, origin) : capabilities.presentToken(body["token"], artifactId, origin);
10992
+ if (isRefusal(grant)) return refuse(checks, grant, meta);
10993
+ const existing = capabilities.session(cookieValues(context.request.headers.get("cookie"), checks.cookieName()), origin, artifactId);
10994
+ if (!isRefusal(existing)) {
10995
+ if (existing.grant.tokenId === grant.tokenId) {
10996
+ if (launch) capabilities.spendLaunch(body["launch"]);
10997
+ return jsonResponse({
10998
+ csrf: existing.csrf,
10999
+ ...sessionFacts(artifactId, existing.grant)
11000
+ });
11001
+ }
11002
+ if (body["replace"] !== true) {
11003
+ log.info("gateway.session_conflict", {
11004
+ artifactId,
11005
+ origin
11006
+ });
11007
+ return jsonResponse({
11008
+ ...refusal("MOSTRA_HYGIENE_SESSION_CONFLICT", "This browser already has this artifact open from another link.").diagnostic,
11009
+ current: access(existing.grant),
11010
+ offered: access(grant)
11011
+ }, { status: 409 });
11012
+ }
11013
+ }
11014
+ let viewerId;
11015
+ if (grant.viewerId === void 0) {
11016
+ const outcome = options.identity ? await options.identity({
11017
+ artifactId,
11018
+ via: way.via,
11019
+ headers: context.request.headers
11020
+ }) : { kind: "default" };
11021
+ if (outcome.kind === "unavailable") {
11022
+ log.warn("gateway.session_refused", {
11023
+ artifactId,
11024
+ code: outcome.diagnostic.code
11025
+ });
11026
+ return jsonResponse(outcome.diagnostic, { status: 503 });
11027
+ }
11028
+ viewerId = outcome.kind === "person" ? interaction.viewerForHost(outcome.viewer) : defaultViewer(way, context, grant);
11029
+ }
11030
+ const now = launch ? capabilities.presentLaunch(body["launch"], artifactId, true, origin) : capabilities.presentToken(body["token"], artifactId, origin);
11031
+ if (isRefusal(now)) return refuse(checks, now, meta);
11032
+ grant = now;
11033
+ const made = browser === void 0 ? void 0 : madeSessions.get(browser);
11034
+ if (made !== void 0 && made.order > startedAt && made.grant.tokenId !== grant.tokenId && body["replace"] !== true) {
10078
11035
  log.info("gateway.session_conflict", {
10079
11036
  artifactId,
10080
- origin: shellOrigin()
11037
+ origin
10081
11038
  });
10082
11039
  return jsonResponse({
10083
11040
  ...refusal("MOSTRA_HYGIENE_SESSION_CONFLICT", "This browser already has this artifact open from another link.").diagnostic,
10084
- current: access(existing.grant),
11041
+ current: access(made.grant),
10085
11042
  offered: access(grant)
10086
11043
  }, { status: 409 });
10087
11044
  }
10088
- }
10089
- let viewerId;
10090
- if (grant.viewerId === void 0 && options.identity) {
10091
- const outcome = await options.identity({
10092
- artifactId,
10093
- via: "local",
10094
- headers: context.request.headers
11045
+ const session = capabilities.createSession({
11046
+ tokenId: grant.tokenId,
11047
+ origin,
11048
+ viewerId
10095
11049
  });
10096
- if (outcome.kind === "unavailable") {
10097
- log.warn("gateway.session_refused", {
10098
- artifactId,
10099
- code: outcome.diagnostic.code
11050
+ if (browser !== void 0) {
11051
+ exchangeOrder += 1;
11052
+ madeSessions.delete(browser);
11053
+ madeSessions.set(browser, {
11054
+ order: exchangeOrder,
11055
+ grant
10100
11056
  });
10101
- return jsonResponse(outcome.diagnostic, { status: 503 });
11057
+ if (madeSessions.size > 4096) madeSessions.delete(madeSessions.keys().next().value);
10102
11058
  }
10103
- if (outcome.kind === "person") viewerId = interaction.viewerForHost(outcome.viewer);
10104
- }
10105
- const now = launch ? capabilities.presentLaunch(body["launch"], artifactId, true) : capabilities.presentToken(body["token"], artifactId);
10106
- if (isRefusal(now)) return refuse(shellChecks, now, meta);
10107
- grant = now;
10108
- const made = browser === void 0 ? void 0 : madeSessions.get(browser);
10109
- if (made !== void 0 && made.order > startedAt && made.grant.tokenId !== grant.tokenId && body["replace"] !== true) {
10110
- log.info("gateway.session_conflict", {
11059
+ log.info("gateway.session_started", {
11060
+ origin,
10111
11061
  artifactId,
10112
- origin: shellOrigin()
11062
+ tokenId: grant.tokenId
10113
11063
  });
10114
11064
  return jsonResponse({
10115
- ...refusal("MOSTRA_HYGIENE_SESSION_CONFLICT", "This browser already has this artifact open from another link.").diagnostic,
10116
- current: access(made.grant),
10117
- offered: access(grant)
10118
- }, { status: 409 });
10119
- }
10120
- const session = capabilities.createSession({
10121
- tokenId: grant.tokenId,
10122
- origin: shellOrigin(),
10123
- viewerId
10124
- });
10125
- if (browser !== void 0) {
10126
- exchangeOrder += 1;
10127
- madeSessions.delete(browser);
10128
- madeSessions.set(browser, {
10129
- order: exchangeOrder,
10130
- grant
11065
+ csrf: session.csrf,
11066
+ ...sessionFacts(artifactId, grant)
11067
+ }, { headers: { "set-cookie": sessionCookie(checks.cookieName(), session.cookie, `/a/${artifactId}`, SESSION_MAX_AGE_S, secure(origin)) } });
11068
+ };
11069
+ const readShellSession = (context) => {
11070
+ const session = context.session;
11071
+ if (!session || context.artifactId === void 0) throw new Error("session route without a session");
11072
+ return jsonResponse({
11073
+ csrf: session.csrf,
11074
+ ...sessionFacts(context.artifactId, session.grant)
10131
11075
  });
10132
- if (madeSessions.size > 4096) madeSessions.delete(madeSessions.keys().next().value);
10133
- }
10134
- log.info("gateway.session_started", {
10135
- origin: shellOrigin(),
10136
- artifactId,
10137
- tokenId: grant.tokenId
10138
- });
10139
- return jsonResponse({
10140
- csrf: session.csrf,
10141
- ...sessionFacts(artifactId, grant)
10142
- }, { headers: { "set-cookie": sessionCookie(shellChecks.cookieName(), session.cookie, `/a/${artifactId}`, SESSION_MAX_AGE_S) } });
10143
- };
10144
- const readShellSession = (context) => {
10145
- const session = context.session;
10146
- if (!session || context.artifactId === void 0) throw new Error("session route without a session");
10147
- return jsonResponse({
10148
- csrf: session.csrf,
10149
- ...sessionFacts(context.artifactId, session.grant)
10150
- });
10151
- };
10152
- const ticket = async (context) => {
10153
- const session = context.session;
10154
- const artifactId = context.artifactId;
10155
- if (!session || artifactId === void 0) throw new Error("session route without a session");
10156
- const meta = {
10157
- method: "POST",
10158
- path: new URL(context.request.url).pathname,
10159
- document: false
10160
11076
  };
10161
- const body = await readJsonObject(context.request);
10162
- if (isRefusal(body)) return refuse(shellChecks, body, meta);
10163
- const asked = body["version"];
10164
- if (asked !== void 0 && !(Number.isSafeInteger(asked) && asked >= 1)) return refuse(shellChecks, refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", "`version` must be a version number."), meta);
10165
- const pinned = session.grant.pinnedVersion;
10166
- if (pinned !== void 0 && asked !== void 0 && asked !== pinned) return refuse(shellChecks, refusal("MOSTRA_HYGIENE_SCOPE_DENIED", `This link opens version ${pinned} only.`), meta);
10167
- const detail = artifacts.get({ artifactId });
10168
- const version = versionOf(detail, asked ?? pinned);
10169
- const latest = versionOf(detail, void 0);
10170
- if (!version || !latest) return jsonResponse(createDiagnostic("MOSTRA_ARTIFACT_VERSION_NOT_FOUND", { message: `This artifact has no version ${asked ?? session.grant.pinnedVersion ?? ""}.`.replace(" .", ".") }), { status: 404 });
10171
- if (version.collected !== void 0) return jsonResponse(collectedDiagnostic(version.number), { status: 410 });
10172
- const damage = options.dev ? void 0 : await integrity.check(version.id);
10173
- if (damage !== void 0) return damaged(version.number, damage, false);
10174
- const port = await openArtifact(artifactId);
10175
- const artifactOrigin = addressing.origin(port);
10176
- if (addressing.frameMode(shellOrigin(), artifactOrigin) === "worker") return refuse(shellChecks, refusal("MOSTRA_HYGIENE_NOT_SERVED", "Cross-site frame sessions arrive with sharing.", 501), meta);
10177
- const value = capabilities.mintTicket({
10178
- tokenId: session.grant.tokenId,
10179
- artifactId,
10180
- versionId: version.id,
10181
- origin: artifactOrigin,
10182
- shellOrigin: shellOrigin(),
10183
- shellSessionId: session.id,
10184
- viewerId: session.viewerId
10185
- });
10186
- const controls = await options.controls(detail);
10187
- const viewerId = interaction.viewerOf(session.viewerId);
10188
- return jsonResponse({
10189
- artifactId,
10190
- viewId: interaction.openView({
11077
+ const ticket = async (context) => {
11078
+ const way = wayOf();
11079
+ const session = context.session;
11080
+ const artifactId = context.artifactId;
11081
+ if (!session || artifactId === void 0) throw new Error("session route without a session");
11082
+ const meta = {
11083
+ method: "POST",
11084
+ path: new URL(context.request.url).pathname,
11085
+ document: false
11086
+ };
11087
+ const body = await readJsonObject(context.request);
11088
+ if (isRefusal(body)) return refuse(checks, body, meta);
11089
+ const asked = body["version"];
11090
+ if (asked !== void 0 && !(Number.isSafeInteger(asked) && asked >= 1)) return refuse(checks, refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", "`version` must be a version number."), meta);
11091
+ const pinned = session.grant.pinnedVersion;
11092
+ if (pinned !== void 0 && asked !== void 0 && asked !== pinned) return refuse(checks, refusal("MOSTRA_HYGIENE_SCOPE_DENIED", `This link opens version ${pinned} only.`), meta);
11093
+ const detail = artifacts.get({ artifactId });
11094
+ const version = versionOf(detail, asked ?? pinned);
11095
+ const latest = versionOf(detail, void 0);
11096
+ if (!version || !latest) return jsonResponse(createDiagnostic("MOSTRA_ARTIFACT_VERSION_NOT_FOUND", { message: `This artifact has no version ${asked ?? session.grant.pinnedVersion ?? ""}.`.replace(" .", ".") }), { status: 404 });
11097
+ if (version.collected !== void 0) return jsonResponse(collectedDiagnostic(version.number), { status: 410 });
11098
+ const damage = options.dev ? void 0 : await integrity.check(version.id);
11099
+ if (damage !== void 0) return damaged(version.number, damage, false, "'none'");
11100
+ const found = await artifactWayFor(way, group, artifactId);
11101
+ if (isRefusal(found)) return refuse(checks, found, meta);
11102
+ const artifactOrigin = found.way.origin();
11103
+ const mode = modeOf(found.way, found.group);
11104
+ const value = capabilities.mintTicket({
11105
+ tokenId: session.grant.tokenId,
10191
11106
  artifactId,
10192
11107
  versionId: version.id,
10193
- viewerId,
10194
- tokenId: session.grant.tokenId,
10195
- controls
10196
- }),
10197
- src: `${artifactOrigin}/_mostra/enter?ticket=${value}`,
10198
- artifactOrigin,
10199
- version,
10200
- latest,
10201
- policy: detail.policy ?? {
10202
- policy: "once",
10203
- scope: "per-artifact"
10204
- },
10205
- submitChannels: controls.submitChannels,
10206
- controls: (controls.controls ?? [
10207
- "submit",
10208
- "choose",
10209
- "approve"
10210
- ]).filter((control) => control === "submit" ? scopeAllows(session.grant.scopes, "submit") : control === "choose" ? scopeAllows(session.grant.scopes, "review") : true),
10211
- target: options.target ?? "live",
10212
- follow: interaction.following({
11108
+ origin: artifactOrigin,
11109
+ shellOrigin: way.origin() ?? "",
11110
+ shellSessionId: session.id,
11111
+ viewerId: session.viewerId
11112
+ });
11113
+ const controls = await options.controls(detail);
11114
+ const viewerId = interaction.viewerOf(session.viewerId);
11115
+ return jsonResponse({
10213
11116
  artifactId,
10214
- viewerId
10215
- }),
10216
- pinned: pinned !== void 0,
10217
- ...options.parked?.(version.id) ? { serverParked: true } : {},
10218
- ...options.dev ? { devPreview: true } : {}
10219
- });
10220
- };
10221
- const shellRoutes = [
10222
- {
10223
- method: "GET",
10224
- path: "/a/:artifactId",
10225
- intent: "read",
10226
- auth: "none",
10227
- handler: shellPage
10228
- },
10229
- {
10230
- method: "GET",
10231
- path: "/a/:artifactId/",
10232
- intent: "read",
10233
- auth: "none",
10234
- handler: shellPage
10235
- },
10236
- {
10237
- method: "GET",
10238
- path: "/a/:artifactId/v/:number{[1-9][0-9]{0,8}}",
10239
- intent: "read",
10240
- auth: "none",
10241
- handler: shellPage
10242
- },
10243
- {
10244
- method: "GET",
10245
- path: "/_mostra/shell/*",
10246
- intent: "read",
10247
- auth: "none",
10248
- handler: shellAsset
10249
- },
10250
- {
10251
- method: "POST",
10252
- path: "/a/:artifactId/_mostra/session",
10253
- intent: "exchange",
10254
- auth: "none",
10255
- tokenPath: true,
10256
- handler: exchange
10257
- },
10258
- {
10259
- method: "GET",
10260
- path: "/a/:artifactId/_mostra/session",
10261
- intent: "read",
10262
- auth: "session",
10263
- handler: readShellSession
10264
- },
10265
- {
10266
- method: "POST",
10267
- path: "/a/:artifactId/_mostra/ticket",
10268
- intent: "mutation",
10269
- auth: "session",
10270
- handler: ticket
10271
- },
10272
- {
10273
- method: "POST",
10274
- path: "/a/:artifactId/_mostra/v/:rev/submit",
10275
- intent: "mutation",
10276
- auth: "session",
10277
- scope: () => "submit",
10278
- handler: served.shellSubmit
10279
- },
10280
- {
10281
- method: "POST",
10282
- path: "/a/:artifactId/_mostra/v/:rev/review/choose",
10283
- intent: "mutation",
10284
- auth: "session",
10285
- scope: () => "review",
10286
- handler: served.choose
10287
- },
10288
- {
10289
- method: "POST",
10290
- path: "/a/:artifactId/_mostra/v/:rev/follow",
10291
- intent: "mutation",
10292
- auth: "session",
10293
- handler: served.follow
10294
- },
10295
- {
10296
- method: "GET",
10297
- path: "/a/:artifactId/_mostra/v/:rev/carry",
10298
- intent: "read",
10299
- auth: "session",
10300
- handler: served.carry
10301
- },
10302
- {
10303
- method: "GET",
10304
- path: "/a/:artifactId/_mostra/v/:rev/events",
10305
- intent: "stream",
10306
- auth: "session",
10307
- handler: served.stream
10308
- },
10309
- {
10310
- method: "GET",
10311
- path: "/a/:artifactId/_mostra/v/:rev/events/poll",
10312
- intent: "stream",
10313
- auth: "session",
10314
- handler: served.poll
10315
- },
10316
- {
10317
- method: "POST",
10318
- path: "/a/:artifactId/_mostra/v/:rev/review/*",
10319
- intent: "mutation",
10320
- auth: "session",
10321
- scope: () => "review"
10322
- }
10323
- ];
10324
- const artifactRoutes = (artifactId, port) => {
10325
- const origin = () => addressing.origin(port());
11117
+ viewId: interaction.openView({
11118
+ artifactId,
11119
+ versionId: version.id,
11120
+ viewerId,
11121
+ tokenId: session.grant.tokenId,
11122
+ controls
11123
+ }),
11124
+ src: mode === "worker" ? `${artifactOrigin}/_mostra/enter#t=${value}` : `${artifactOrigin}/_mostra/enter?ticket=${value}`,
11125
+ artifactOrigin,
11126
+ version,
11127
+ latest,
11128
+ policy: detail.policy ?? {
11129
+ policy: "once",
11130
+ scope: "per-artifact"
11131
+ },
11132
+ submitChannels: controls.submitChannels,
11133
+ controls: (controls.controls ?? [
11134
+ "submit",
11135
+ "choose",
11136
+ "approve"
11137
+ ]).filter((control) => control === "submit" ? scopeAllows(session.grant.scopes, "submit") : control === "choose" ? scopeAllows(session.grant.scopes, "review") : true),
11138
+ target: options.target ?? "live",
11139
+ follow: interaction.following({
11140
+ artifactId,
11141
+ viewerId
11142
+ }),
11143
+ pinned: pinned !== void 0,
11144
+ ...options.parked?.(version.id) ? { serverParked: true } : {},
11145
+ ...options.dev ? { devPreview: true } : {},
11146
+ ...mode === "worker" ? { mode: "worker" } : {}
11147
+ });
11148
+ };
11149
+ return [
11150
+ {
11151
+ method: "GET",
11152
+ path: "/a/:artifactId",
11153
+ intent: "read",
11154
+ auth: "none",
11155
+ handler: shellPage
11156
+ },
11157
+ {
11158
+ method: "GET",
11159
+ path: "/a/:artifactId/",
11160
+ intent: "read",
11161
+ auth: "none",
11162
+ handler: shellPage
11163
+ },
11164
+ {
11165
+ method: "GET",
11166
+ path: "/a/:artifactId/v/:number{[1-9][0-9]{0,8}}",
11167
+ intent: "read",
11168
+ auth: "none",
11169
+ handler: shellPage
11170
+ },
11171
+ {
11172
+ method: "GET",
11173
+ path: "/_mostra/shell/*",
11174
+ intent: "read",
11175
+ auth: "none",
11176
+ handler: shellAsset
11177
+ },
11178
+ {
11179
+ method: "POST",
11180
+ path: "/a/:artifactId/_mostra/session",
11181
+ intent: "exchange",
11182
+ auth: "none",
11183
+ tokenPath: true,
11184
+ handler: exchange
11185
+ },
11186
+ {
11187
+ method: "GET",
11188
+ path: "/a/:artifactId/_mostra/session",
11189
+ intent: "read",
11190
+ auth: "session",
11191
+ handler: readShellSession
11192
+ },
11193
+ {
11194
+ method: "POST",
11195
+ path: "/a/:artifactId/_mostra/ticket",
11196
+ intent: "mutation",
11197
+ auth: "session",
11198
+ handler: ticket
11199
+ },
11200
+ {
11201
+ method: "POST",
11202
+ path: "/a/:artifactId/_mostra/v/:rev/submit",
11203
+ intent: "mutation",
11204
+ auth: "session",
11205
+ scope: () => "submit",
11206
+ handler: served.shellSubmit
11207
+ },
11208
+ {
11209
+ method: "POST",
11210
+ path: "/a/:artifactId/_mostra/v/:rev/review/choose",
11211
+ intent: "mutation",
11212
+ auth: "session",
11213
+ scope: () => "review",
11214
+ handler: served.choose
11215
+ },
11216
+ {
11217
+ method: "POST",
11218
+ path: "/a/:artifactId/_mostra/v/:rev/follow",
11219
+ intent: "mutation",
11220
+ auth: "session",
11221
+ handler: served.follow
11222
+ },
11223
+ {
11224
+ method: "GET",
11225
+ path: "/a/:artifactId/_mostra/v/:rev/carry",
11226
+ intent: "read",
11227
+ auth: "session",
11228
+ handler: served.carry
11229
+ },
11230
+ {
11231
+ method: "GET",
11232
+ path: "/a/:artifactId/_mostra/v/:rev/events",
11233
+ intent: "stream",
11234
+ auth: "session",
11235
+ sse: true,
11236
+ handler: served.stream
11237
+ },
11238
+ {
11239
+ method: "GET",
11240
+ path: "/a/:artifactId/_mostra/v/:rev/events/poll",
11241
+ intent: "stream",
11242
+ auth: "session",
11243
+ handler: served.poll
11244
+ },
11245
+ {
11246
+ method: "POST",
11247
+ path: "/a/:artifactId/_mostra/v/:rev/review/*",
11248
+ intent: "mutation",
11249
+ auth: "session",
11250
+ scope: () => "review"
11251
+ }
11252
+ ];
11253
+ };
11254
+ const artifactChecks = (artifactId, wayOf, group) => ({
11255
+ policy: () => ({
11256
+ origin: wayOf().origin() ?? "",
11257
+ hosts: wayOf().hosts()
11258
+ }),
11259
+ capabilities,
11260
+ log,
11261
+ cookieName: () => `mostra-${wayOf().port()}`,
11262
+ frameAncestors: () => shellOf(wayOf(), group)?.origin() ?? "'none'",
11263
+ artifactOf: () => artifactId,
11264
+ mode: () => modeOf(wayOf(), group),
11265
+ streams: () => wayOf().streams()
11266
+ });
11267
+ const artifactRoutes = (artifactId, wayOf, group) => {
11268
+ const origin = () => wayOf().origin() ?? "";
11269
+ const shell = () => shellOf(wayOf(), group)?.origin() ?? "";
10326
11270
  const kind = () => ({
10327
11271
  kind: "artifact",
10328
11272
  origin: origin(),
10329
- shellOrigin: shellOrigin()
11273
+ shellOrigin: shell()
10330
11274
  });
10331
- const checks = () => artifactChecks(artifactId, port);
11275
+ const checks = artifactChecks(artifactId, wayOf, group);
11276
+ const mode = () => modeOf(wayOf(), group);
11277
+ const notServed = (context, message) => refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", message), {
11278
+ method: context.request.method,
11279
+ path: new URL(context.request.url).pathname,
11280
+ document: context.document
11281
+ });
11282
+ /**
11283
+ * `GET /_mostra/enter`: in cookie mode the frame's entry with its ticket (D98 item 3); in
11284
+ * worker mode the bootstrap page, whose ticket is in the fragment (D70).
11285
+ */
10332
11286
  const enter = (context) => {
10333
11287
  const url = new URL(context.request.url);
10334
11288
  const meta = {
@@ -10336,16 +11290,25 @@ function createGateway(options) {
10336
11290
  path: url.pathname,
10337
11291
  document: true
10338
11292
  };
10339
- if (context.request.headers.get("sec-fetch-site") === "cross-site") return refuse(checks(), refusal("MOSTRA_HYGIENE_ORIGIN_REFUSED", "A frame enters only from its shell."), meta);
11293
+ if (mode() === "worker") {
11294
+ if (url.searchParams.has("ticket")) return notServed(context, "A worker-mode frame enters through its bootstrap page.");
11295
+ return new Response(context.request.method === "HEAD" ? null : BOOTSTRAP_PAGE, { headers: {
11296
+ ...BASE_HEADERS,
11297
+ ...documentHeaders(kind(), ""),
11298
+ ...NO_STORE,
11299
+ "content-type": "text/html; charset=utf-8"
11300
+ } });
11301
+ }
11302
+ if (context.request.headers.get("sec-fetch-site") === "cross-site") return refuse(checks, refusal("MOSTRA_HYGIENE_ORIGIN_REFUSED", "A frame enters only from its shell."), meta);
10340
11303
  const redeemed = capabilities.redeemTicket(url.searchParams.get("ticket"), origin());
10341
- if (isRefusal(redeemed)) return refuse(checks(), redeemed, meta);
10342
- if (redeemed.artifactId !== artifactId) return refuse(checks(), refusal("MOSTRA_HYGIENE_TOKEN_INVALID", "The ticket is for another artifact."), meta);
11304
+ if (isRefusal(redeemed)) return refuse(checks, redeemed, meta);
11305
+ if (redeemed.artifactId !== artifactId) return refuse(checks, refusal("MOSTRA_HYGIENE_TOKEN_INVALID", "The ticket is for another artifact."), meta);
10343
11306
  const headers = {
10344
11307
  ...BASE_HEADERS,
10345
11308
  ...NO_STORE,
10346
11309
  location: "/"
10347
11310
  };
10348
- const existing = capabilities.session(cookieValues(context.request.headers.get("cookie"), checks().cookieName()), origin(), artifactId);
11311
+ const existing = capabilities.session(cookieValues(context.request.headers.get("cookie"), checks.cookieName()), origin(), artifactId);
10349
11312
  if (!isRefusal(existing) && existing.grant.tokenId === redeemed.tokenId && existing.viewerId === redeemed.viewerId) capabilities.enterVersion(existing.id, redeemed.versionId);
10350
11313
  else {
10351
11314
  const session = capabilities.createSession({
@@ -10354,7 +11317,7 @@ function createGateway(options) {
10354
11317
  versionId: redeemed.versionId,
10355
11318
  viewerId: redeemed.viewerId
10356
11319
  });
10357
- headers["set-cookie"] = sessionCookie(checks().cookieName(), session.cookie, "/", SESSION_MAX_AGE_S);
11320
+ headers["set-cookie"] = sessionCookie(checks.cookieName(), session.cookie, "/", SESSION_MAX_AGE_S, secure(origin()));
10358
11321
  log.info("gateway.session_started", {
10359
11322
  origin: origin(),
10360
11323
  artifactId,
@@ -10366,6 +11329,81 @@ function createGateway(options) {
10366
11329
  headers
10367
11330
  });
10368
11331
  };
11332
+ /**
11333
+ * `POST /_mostra/enter` (worker mode, D70): the bootstrap page exchanges the shell's ticket
11334
+ * for a frame session whose secret it hands the service worker. A frame that presents the
11335
+ * session it kept, from the same link and viewer, keeps it and switches version.
11336
+ */
11337
+ const enterWorker = async (context) => {
11338
+ const meta = {
11339
+ method: "POST",
11340
+ path: new URL(context.request.url).pathname,
11341
+ document: false
11342
+ };
11343
+ if (mode() !== "worker") return notServed(context, "This frame enters in cookie mode, with `GET /_mostra/enter`.");
11344
+ const body = await readJsonObject(context.request);
11345
+ if (isRefusal(body)) return refuse(checks, body, meta);
11346
+ const parsed = EnterRequest.safeParse(body);
11347
+ if (!parsed.success) return refuse(checks, refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", "The entry needs the frame's `ticket`."), meta);
11348
+ const redeemed = capabilities.redeemTicket(parsed.data.ticket, origin());
11349
+ if (isRefusal(redeemed)) return refuse(checks, redeemed, meta);
11350
+ if (redeemed.artifactId !== artifactId) return refuse(checks, refusal("MOSTRA_HYGIENE_TOKEN_INVALID", "The ticket is for another artifact."), meta);
11351
+ const kept = context.request.headers.get(FRAME_SESSION_HEADER);
11352
+ const existing = kept === null ? void 0 : capabilities.session([kept], origin(), artifactId, "worker");
11353
+ let secret;
11354
+ if (kept !== null && existing !== void 0 && !isRefusal(existing) && existing.grant.tokenId === redeemed.tokenId && existing.viewerId === redeemed.viewerId) {
11355
+ capabilities.enterVersion(existing.id, redeemed.versionId);
11356
+ secret = kept;
11357
+ } else {
11358
+ secret = capabilities.createSession({
11359
+ tokenId: redeemed.tokenId,
11360
+ origin: origin(),
11361
+ versionId: redeemed.versionId,
11362
+ viewerId: redeemed.viewerId,
11363
+ mode: "worker"
11364
+ }).cookie;
11365
+ log.info("gateway.session_started", {
11366
+ origin: origin(),
11367
+ artifactId,
11368
+ tokenId: redeemed.tokenId,
11369
+ mode: "worker"
11370
+ });
11371
+ }
11372
+ return jsonResponse({
11373
+ session: secret,
11374
+ shellOrigin: redeemed.shellOrigin
11375
+ });
11376
+ };
11377
+ /** `GET /_mostra/sw.js`: the worker-mode service worker, allowed to control `/` (D70). */
11378
+ const serviceWorker = (context) => {
11379
+ if (mode() !== "worker") return notServed(context, "This frame enters in cookie mode and has no service worker.");
11380
+ return new Response(context.request.method === "HEAD" ? null : SERVICE_WORKER_SOURCE, { headers: {
11381
+ ...BASE_HEADERS,
11382
+ "content-type": "text/javascript; charset=utf-8",
11383
+ "service-worker-allowed": "/",
11384
+ "cache-control": "no-cache"
11385
+ } });
11386
+ };
11387
+ /** `POST /_mostra/v/{rev}/ticket`: a single-use ticket for one stream, poll or socket. */
11388
+ const streamTicket = async (context) => {
11389
+ const session = context.session;
11390
+ if (!session) throw new Error("session route without a session");
11391
+ const meta = {
11392
+ method: "POST",
11393
+ path: new URL(context.request.url).pathname,
11394
+ document: false
11395
+ };
11396
+ const body = await readJsonObject(context.request);
11397
+ if (isRefusal(body)) return refuse(checks, body, meta);
11398
+ const parsed = StreamTicketRequest.safeParse(body);
11399
+ if (!parsed.success) return refuse(checks, refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", "`purpose` is `stream` or `socket`."), meta);
11400
+ return jsonResponse(capabilities.mintStreamTicket({
11401
+ sessionId: session.id,
11402
+ origin: origin(),
11403
+ artifactId,
11404
+ purpose: parsed.data.purpose ?? "stream"
11405
+ }));
11406
+ };
10369
11407
  const frameSession = (context) => {
10370
11408
  const session = context.session;
10371
11409
  if (!session) throw new Error("session route without a session");
@@ -10373,13 +11411,15 @@ function createGateway(options) {
10373
11411
  return jsonResponse({
10374
11412
  csrf: session.csrf,
10375
11413
  artifactId,
10376
- shellOrigin: shellOrigin(),
11414
+ shellOrigin: shell(),
10377
11415
  scopes: session.grant.scopes,
10378
11416
  viewer: interaction.viewer(interaction.viewerOf(session.viewerId)),
10379
11417
  ...version ? { version: {
10380
11418
  id: version.id,
10381
11419
  number: version.number
10382
- } } : {}
11420
+ } } : {},
11421
+ ...mode() === "worker" ? { mode: "worker" } : {},
11422
+ ...wayOf().streams() ? {} : { streams: false }
10383
11423
  });
10384
11424
  };
10385
11425
  const files = async (context) => {
@@ -10391,13 +11431,13 @@ function createGateway(options) {
10391
11431
  document: context.document
10392
11432
  };
10393
11433
  const path = safePath(url.pathname);
10394
- if (path === void 0 || !session?.versionId || path === "/_mostra" || path.startsWith("/_mostra/")) return refuse(checks(), refusal("MOSTRA_HYGIENE_NOT_SERVED", "Nothing is served at this path."), meta);
11434
+ if (path === void 0 || !session?.versionId || path === "/_mostra" || path.startsWith("/_mostra/")) return refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", "Nothing is served at this path."), meta);
10395
11435
  const headers = { ...documentHeaders(kind(), "") };
10396
11436
  if (options.dev) {
10397
11437
  const upstream = options.dev.upstream();
10398
- if (!upstream) return refuse(checks(), refusal("MOSTRA_HYGIENE_NOT_SERVED", "The dev server isn't running.", 503), meta);
11438
+ if (!upstream) return refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", "The dev server isn't running.", 503), meta);
10399
11439
  const answered = await devFetch(upstream, context.request, url.pathname + url.search).catch(() => void 0);
10400
- if (!answered) return refuse(checks(), refusal("MOSTRA_HYGIENE_NOT_SERVED", "The dev server didn't answer.", 502), meta);
11440
+ if (!answered) return refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", "The dev server didn't answer.", 502), meta);
10401
11441
  const bodiless = context.request.method === "HEAD" || [
10402
11442
  204,
10403
11443
  205,
@@ -10429,7 +11469,7 @@ function createGateway(options) {
10429
11469
  const damage = await integrity.serve(from, checked);
10430
11470
  if (damage !== void 0) {
10431
11471
  const number = artifacts.get({ artifactId }).versions.find((v) => v.id === from)?.number;
10432
- return damaged(number, damage, context.document);
11472
+ return damaged(number, damage, context.document, shell() || "'none'");
10433
11473
  }
10434
11474
  }
10435
11475
  if (file && options.target === "verify" && file.path.endsWith(".html")) return verifyDocument(file.path, context.request, {
@@ -10449,7 +11489,7 @@ function createGateway(options) {
10449
11489
  ...headers,
10450
11490
  "cache-control": "no-cache"
10451
11491
  });
10452
- return refuse(checks(), refusal("MOSTRA_HYGIENE_NOT_SERVED", "This version has no file at this path."), meta);
11492
+ return refuse(checks, refusal("MOSTRA_HYGIENE_NOT_SERVED", "This version has no file at this path."), meta);
10453
11493
  };
10454
11494
  return [
10455
11495
  {
@@ -10459,6 +11499,20 @@ function createGateway(options) {
10459
11499
  auth: "none",
10460
11500
  handler: enter
10461
11501
  },
11502
+ {
11503
+ method: "POST",
11504
+ path: "/_mostra/enter",
11505
+ intent: "exchange",
11506
+ auth: "none",
11507
+ handler: enterWorker
11508
+ },
11509
+ {
11510
+ method: "GET",
11511
+ path: SERVICE_WORKER_PATH,
11512
+ intent: "read",
11513
+ auth: "none",
11514
+ handler: serviceWorker
11515
+ },
10462
11516
  {
10463
11517
  method: "GET",
10464
11518
  path: "/_mostra/session",
@@ -10466,7 +11520,7 @@ function createGateway(options) {
10466
11520
  auth: "session",
10467
11521
  handler: frameSession
10468
11522
  },
10469
- ...laterArtifactRoutes(served, acting),
11523
+ ...laterArtifactRoutes(served, acting, streamTicket),
10470
11524
  {
10471
11525
  method: "GET",
10472
11526
  path: "/*",
@@ -10476,28 +11530,30 @@ function createGateway(options) {
10476
11530
  }
10477
11531
  ];
10478
11532
  };
10479
- const artifactChecks = (artifactId, port) => ({
10480
- policy: () => ({
10481
- origin: addressing.origin(port()),
10482
- hosts: addressing.hosts(port())
10483
- }),
10484
- capabilities,
10485
- log,
10486
- cookieName: () => `mostra-${port()}`,
10487
- frameAncestors: () => shellOrigin(),
10488
- artifactOf: () => artifactId
10489
- });
10490
11533
  /**
10491
- * The HMR WebSocket of a dev sandbox's artifact origin (D140 item 12): after the listener checked
10492
- * Host and Origin, only a live frame session of this origin reaches the dev server.
11534
+ * WebSocket upgrades on an artifact's listener, after the listener checked Host, target and
11535
+ * Origin: a dev sandbox's HMR socket (D140 item 12), and the browser protocol's sockets
11536
+ * (`/_mostra/v/{rev}/term/{session}`), which open with a single-use socket ticket (D158 item 5)
11537
+ * and arrive with the terminals (WP-22, WP-23).
10493
11538
  */
10494
- const devSocket = (artifactId, port) => (incoming, socket, head) => {
10495
- const upstream = options.dev?.upstream();
10496
- if (!upstream) return refusal("MOSTRA_HYGIENE_NOT_SERVED", "The dev server isn't running.", 503);
10497
- const cookie = incoming.headers.cookie;
10498
- const session = capabilities.session(cookieValues(typeof cookie === "string" ? cookie : null, `mostra-${port()}`), addressing.origin(port()), artifactId);
10499
- if (isRefusal(session)) return session;
10500
- devUpgrade(upstream, incoming, socket, head);
11539
+ const socketUpgrade = (artifactId, wayOf, group) => (incoming, socket, head) => {
11540
+ const way = wayOf();
11541
+ const url = new URL(incoming.url ?? "/", "http://gateway.invalid");
11542
+ if (/^\/_mostra\/v\/[^/]+\/term\/[^/]+$/.test(url.pathname)) {
11543
+ const redeemed = capabilities.redeemStreamTicket(url.searchParams.get("ticket"), way.origin() ?? "", artifactId, "socket");
11544
+ if (isRefusal(redeemed)) return redeemed;
11545
+ return refusal("MOSTRA_HYGIENE_NOT_SERVED", "Live terminals arrive with a later Mostra release.", 501);
11546
+ }
11547
+ if (options.dev && way.by === "loopback" && group === void 0) {
11548
+ const upstream = options.dev.upstream();
11549
+ if (!upstream) return refusal("MOSTRA_HYGIENE_NOT_SERVED", "The dev server isn't running.", 503);
11550
+ const cookie = incoming.headers.cookie;
11551
+ const session = capabilities.session(cookieValues(typeof cookie === "string" ? cookie : null, `mostra-${way.port()}`), way.origin() ?? "", artifactId);
11552
+ if (isRefusal(session)) return session;
11553
+ devUpgrade(upstream, incoming, socket, head);
11554
+ return;
11555
+ }
11556
+ return refusal("MOSTRA_HYGIENE_NOT_SERVED", "This gateway serves no WebSocket here.");
10501
11557
  };
10502
11558
  /** Binds the artifact's listener on its leased port, once; resolves with the port. */
10503
11559
  const openArtifact = (artifactId) => {
@@ -10507,6 +11563,7 @@ function createGateway(options) {
10507
11563
  if (pending) return pending;
10508
11564
  const started = (async () => {
10509
11565
  let port = 0;
11566
+ const way = loopbackArtifact(artifactId, () => port);
10510
11567
  const listener = createListener({
10511
11568
  policy: () => ({
10512
11569
  origin: addressing.origin(port),
@@ -10514,8 +11571,8 @@ function createGateway(options) {
10514
11571
  }),
10515
11572
  log,
10516
11573
  frameAncestors: () => shellOrigin(),
10517
- configure: (app) => mount(app, artifactChecks(artifactId, () => port), artifactRoutes(artifactId, () => port)),
10518
- ...options.dev ? { upgrade: devSocket(artifactId, () => port) } : {},
11574
+ configure: (app) => mount(app, artifactChecks(artifactId, () => way, void 0), artifactRoutes(artifactId, () => way, void 0)),
11575
+ upgrade: socketUpgrade(artifactId, () => way, void 0),
10519
11576
  ...options.traceRequests ? { traceRequests: true } : {}
10520
11577
  });
10521
11578
  port = await addressing.listen(listener.server, {
@@ -10559,16 +11616,39 @@ function createGateway(options) {
10559
11616
  const fail = (refused) => {
10560
11617
  throw new RpcError(refused.diagnostic);
10561
11618
  };
11619
+ /** Opens the faces a host gave before a restart, so their links work before it answers again. */
11620
+ const restoreBases = async () => {
11621
+ for (const row of keptBases()) {
11622
+ if (row.artifact_id === null) continue;
11623
+ try {
11624
+ artifacts.get({ artifactId: row.artifact_id });
11625
+ } catch {
11626
+ continue;
11627
+ }
11628
+ try {
11629
+ const entry = await openFace(hostSpec(row.artifact_id, row.listener, row.mode ?? void 0), row.origin);
11630
+ entry.origin = row.origin;
11631
+ } catch (error) {
11632
+ log.warn("gateway.face_restore_failed", {
11633
+ key: row.key,
11634
+ error: error.message
11635
+ });
11636
+ }
11637
+ }
11638
+ };
10562
11639
  return {
10563
11640
  shellOrigin,
10564
11641
  async start() {
10565
11642
  const pruned = capabilities.prune();
10566
11643
  if (pruned > 0) log.info("gateway.sessions_pruned", { count: pruned });
10567
11644
  shellListener = createListener({
10568
- policy: () => shellChecks.policy(),
11645
+ policy: () => ({
11646
+ origin: shellOrigin(),
11647
+ hosts: addressing.hosts(shellPort ?? 0)
11648
+ }),
10569
11649
  log,
10570
11650
  frameAncestors: () => "'none'",
10571
- configure: (app) => mount(app, shellChecks, shellRoutes),
11651
+ configure: (app) => mount(app, shellChecks(() => loopbackShell), shellRoutes(() => loopbackShell, void 0)),
10572
11652
  ...options.traceRequests ? { traceRequests: true } : {}
10573
11653
  });
10574
11654
  shellPort = await addressing.listen(shellListener.server, {
@@ -10590,9 +11670,11 @@ function createGateway(options) {
10590
11670
  }
10591
11671
  await openArtifact(lease.owner);
10592
11672
  }
11673
+ await restoreBases();
10593
11674
  },
10594
- defaultLink(artifactId) {
10595
- const { url, tokenId } = link(capabilities.defaultLink(artifactId));
11675
+ async defaultLink(artifactId) {
11676
+ const base = await linkBase(artifactId);
11677
+ const { url, tokenId } = link(capabilities.defaultLink(artifactId, base));
10596
11678
  return {
10597
11679
  url,
10598
11680
  tokenId
@@ -10604,23 +11686,53 @@ function createGateway(options) {
10604
11686
  ...input.version !== void 0 ? { pinnedVersion: input.version } : {}
10605
11687
  })).url;
10606
11688
  },
11689
+ mintAt(input, within) {
11690
+ return link(capabilities.mint({
11691
+ artifactId: input.artifactId,
11692
+ scopes: input.scopes,
11693
+ ttlMs: input.ttlMs,
11694
+ viewerId: input.viewerId,
11695
+ shellOrigin: input.shellOrigin
11696
+ }, within));
11697
+ },
11698
+ reveal(tokenId) {
11699
+ const shown = capabilities.reveal(tokenId);
11700
+ return shown ? link(shown).url : void 0;
11701
+ },
11702
+ async openFace(spec) {
11703
+ return handleOf(await openFace(spec));
11704
+ },
11705
+ face(key) {
11706
+ const entry = faces.get(key);
11707
+ return entry ? handleOf(entry) : void 0;
11708
+ },
11709
+ closeFace,
11710
+ faces: () => [...faces.values()].filter((entry) => entry.origin !== void 0).map((entry) => ({
11711
+ origin: entry.origin,
11712
+ local: addressing.faceLocal(entry.port),
11713
+ listener: entry.spec.listener,
11714
+ ...entry.spec.artifactId !== void 0 ? { artifactId: entry.spec.artifactId } : {},
11715
+ by: entry.spec.by
11716
+ })),
10607
11717
  methods: () => [
10608
- handler(viewUrlMethod, (params) => {
11718
+ handler(viewUrlMethod, async (params) => {
10609
11719
  const detail = artifacts.get(params.artifact);
10610
11720
  const version = versionOf(detail, params.version);
10611
11721
  if (!version) throw new RpcError(createDiagnostic("MOSTRA_ARTIFACT_VERSION_NOT_FOUND", { message: params.version === void 0 ? `The artifact ${detail.id} has no published version.` : `The artifact ${detail.id} has no version ${params.version}.` }));
10612
11722
  if (version.collected !== void 0) throw new RpcError(collectedDiagnostic(version.number));
11723
+ const base = await linkBase(detail.id);
10613
11724
  return recorded(requestKey("view/url", params), (db) => capabilities.mint({
10614
11725
  artifactId: detail.id,
10615
11726
  scopes: params.scopes,
10616
11727
  ttlMs: params.ttl === void 0 ? void 0 : durationMs(params.ttl),
10617
11728
  pinnedVersion: params.version === void 0 ? void 0 : version.number,
10618
- viewerId: params.viewer === void 0 ? void 0 : interaction.viewerForSpec(db, params.viewer)
11729
+ viewerId: params.viewer === void 0 ? void 0 : interaction.viewerForSpec(db, params.viewer),
11730
+ shellOrigin: base
10619
11731
  }, db));
10620
11732
  }),
10621
- handler(viewDefaultMethod, (params) => {
11733
+ handler(viewDefaultMethod, async (params) => {
10622
11734
  const detail = artifacts.get(params.artifact);
10623
- return link(capabilities.defaultLink(detail.id));
11735
+ return link(capabilities.defaultLink(detail.id, await linkBase(detail.id)));
10624
11736
  }),
10625
11737
  handler(viewLaunchMethod, (params) => {
10626
11738
  const minted = capabilities.mintLaunch(params.tokenId);
@@ -10628,7 +11740,7 @@ function createGateway(options) {
10628
11740
  if (minted === "dead") return fail(refusal("MOSTRA_HYGIENE_TOKEN_REVOKED", `The token ${params.tokenId} was revoked, has expired, or was made for another address.`));
10629
11741
  const { grant } = minted;
10630
11742
  return {
10631
- url: `${shellOrigin()}/a/${grant.artifactId}${grant.pinnedVersion !== void 0 ? `/v/${grant.pinnedVersion}` : ""}#l=${minted.ticket}`,
11743
+ url: `${grant.shellOrigin}/a/${grant.artifactId}${grant.pinnedVersion !== void 0 ? `/v/${grant.pinnedVersion}` : ""}#l=${minted.ticket}`,
10632
11744
  expiresAt: minted.expiresAt
10633
11745
  };
10634
11746
  }),
@@ -10647,9 +11759,16 @@ function createGateway(options) {
10647
11759
  ],
10648
11760
  artifactOrigins: () => new Map([...artifactListeners].map(([artifactId, entry]) => [artifactId, addressing.origin(entry.port)])),
10649
11761
  async close() {
10650
- await Promise.allSettled([...opening.values()]);
10651
- await Promise.all([shellListener?.close(), ...[...artifactListeners.values()].map((entry) => entry.listener.close())]);
10652
- }
11762
+ await Promise.allSettled([...opening.values(), ...openingFaces.values()]);
11763
+ await Promise.all([
11764
+ shellListener?.close(),
11765
+ ...[...artifactListeners.values()].map((entry) => entry.listener.close()),
11766
+ ...[...faces.values()].map((entry) => entry.listener.close()),
11767
+ ...[...lingering.keys()].map((key) => endLingering(key))
11768
+ ]);
11769
+ faces.clear();
11770
+ },
11771
+ servesShell
10653
11772
  };
10654
11773
  }
10655
11774
  /** The answer for a version `mostra gc` collected (D140 item 14). */
@@ -10806,7 +11925,15 @@ function createLive(options) {
10806
11925
  try {
10807
11926
  const handle = await pool.acquire(version);
10808
11927
  described.set(versionId, handle.started.live);
10809
- if (!handle.started.live.some((source) => source.key === key)) return;
11928
+ const source = handle.started.live.find((info) => info.key === key);
11929
+ if (!source) return;
11930
+ if (source.load === false) bus.publishLive(artifactId, {
11931
+ kind: "live",
11932
+ live: {
11933
+ key,
11934
+ awaiting: false
11935
+ }
11936
+ });
10810
11937
  running.set(id, {
10811
11938
  artifactId,
10812
11939
  key,
@@ -10887,6 +12014,8 @@ function createLive(options) {
10887
12014
  const stateOf = (db, artifactId, key, window) => {
10888
12015
  const row = db.get("SELECT revision, value_json, at FROM live_value WHERE artifact_id = ? AND key = ?", artifactId, key);
10889
12016
  const failure = failures.get(keyOf(artifactId, key));
12017
+ const latest = options.latest(artifactId);
12018
+ const producing = latest?.sources.some((source) => source.key === key) === true && (described.get(latest.versionId)?.find((source) => source.key === key)?.load ?? true);
10890
12019
  const ring = window === void 0 ? void 0 : db.all("SELECT revision, value_json, at FROM live_ring WHERE artifact_id = ? AND key = ? ORDER BY revision DESC LIMIT ?", artifactId, key, window).reverse().map((entry) => ({
10891
12020
  revision: String(entry.revision),
10892
12021
  at: entry.at,
@@ -10900,7 +12029,8 @@ function createLive(options) {
10900
12029
  value: JSON.parse(row.value_json)
10901
12030
  } : {},
10902
12031
  ...ring ? { ring } : {},
10903
- ...failure ? { error: failure } : {}
12032
+ ...failure ? { error: failure } : {},
12033
+ ...!row && !failure && producing ? { awaiting: true } : {}
10904
12034
  };
10905
12035
  };
10906
12036
  return {
@@ -13276,6 +14406,74 @@ function extractManifest(file, text) {
13276
14406
  return file.endsWith(".mdx") ? extractFrontmatter(file, text) : extractScript(file, text);
13277
14407
  }
13278
14408
  //#endregion
14409
+ //#region src/publish/scaffold.ts
14410
+ /** The files a new artifact gets, in the order `artifact/create` reports them. */
14411
+ const SCAFFOLD_PATHS = [
14412
+ "index.tsx",
14413
+ "AGENTS.md",
14414
+ "CLAUDE.md"
14415
+ ];
14416
+ function entry({ artifactId, title }) {
14417
+ return [
14418
+ "import { defineArtifact } from \"@mostra/react\";",
14419
+ "",
14420
+ "export const artifact = defineArtifact({",
14421
+ ` id: ${JSON.stringify(artifactId)},`,
14422
+ ` title: ${JSON.stringify(title)},`,
14423
+ "});",
14424
+ "",
14425
+ "export default function Page() {",
14426
+ " return (",
14427
+ " <main className=\"mx-auto max-w-2xl p-8\">",
14428
+ " <h1 className=\"text-2xl font-semibold\">{artifact.title}</h1>",
14429
+ " </main>",
14430
+ " );",
14431
+ "}",
14432
+ ""
14433
+ ].join("\n");
14434
+ }
14435
+ /** A Markdown heading's text: one line, nothing that reads as Markdown syntax at its start. */
14436
+ function headingText(title) {
14437
+ const line = title.replace(/\s+/g, " ").trim();
14438
+ return line === "" ? "Mostra artifact" : line;
14439
+ }
14440
+ function agents({ title, version }) {
14441
+ return [
14442
+ `# ${headingText(title)}`,
14443
+ "",
14444
+ "This directory is a Mostra artifact: a page people open from a private link, read, answer and act on. Their answers come back to you as results.",
14445
+ "",
14446
+ "## Work on it",
14447
+ "",
14448
+ "1. Edit `index.tsx`: ordinary React 19 and TypeScript with Tailwind CSS 4, with no `package.json` or build configuration.",
14449
+ "2. Run `mostra verify .` until it reports `pass`, and look at both screenshots it lists (`--screenshots always` lists them every time).",
14450
+ "3. Run `mostra publish .`. It prints the private link: whoever holds it can use the page.",
14451
+ "4. Give the link to the person, saying who is asking and why. Then run `mostra wait . --until submitted` and `mostra results .`.",
14452
+ "",
14453
+ `Where \`mostra\` isn't installed, run \`npx -y @mostra/cli@${version}\` in its place.`,
14454
+ "",
14455
+ "## Keep in mind",
14456
+ "",
14457
+ "- Every answer is a field with an ID that stays the same on every render and in every version: `useField(\"budget\", 0, { label: \"Budget\" })`, or a template on your data's own ID for a list. Answers carry over to a new version by ID.",
14458
+ "- Keep the `id` in `defineArtifact`: it is this artifact's identity. Manifest values are literals.",
14459
+ "- Code that must run on this machine (send, save, call an API) goes in a module that starts with `\"use server\"`; live data in `live.ts`; static files in `public/`.",
14460
+ "- Imports stay inside this directory, or name an npm package.",
14461
+ "",
14462
+ "## More",
14463
+ "",
14464
+ "`mostra docs guide` is the full guide to writing artifacts, and `mostra docs <CODE>` explains any diagnostic. The same guide is the Mostra Agent Skill: `npx skills add mostra-dev/mostra`.",
14465
+ ""
14466
+ ].join("\n");
14467
+ }
14468
+ /** The files of a new artifact, by path. */
14469
+ function scaffoldFiles(input) {
14470
+ return /* @__PURE__ */ new Map([
14471
+ ["index.tsx", entry(input)],
14472
+ ["AGENTS.md", agents(input)],
14473
+ ["CLAUDE.md", "@AGENTS.md\n"]
14474
+ ]);
14475
+ }
14476
+ //#endregion
13279
14477
  //#region src/publish/source.ts
13280
14478
  /**
13281
14479
  * Artifact sources (INTERFACES §2.1, DATA_MODEL §2): finding an artifact's entry, listing its files
@@ -13647,46 +14845,40 @@ async function archiveSnapshot(source, files, target) {
13647
14845
  fsyncPath(dirname(target), true);
13648
14846
  return true;
13649
14847
  }
13650
- /** The entry `artifact/create` writes: a manifest with the generated `id` and a minimal page. */
13651
- function scaffold(artifactId, title) {
13652
- return [
13653
- "import { defineArtifact } from \"@mostra/react\";",
13654
- "",
13655
- "export const artifact = defineArtifact({",
13656
- ` id: ${JSON.stringify(artifactId)},`,
13657
- ` title: ${JSON.stringify(title)},`,
13658
- "});",
13659
- "",
13660
- "export default function Page() {",
13661
- " return (",
13662
- " <main className=\"mx-auto max-w-2xl p-8\">",
13663
- " <h1 className=\"text-2xl font-semibold\">{artifact.title}</h1>",
13664
- " </main>",
13665
- " );",
13666
- "}",
13667
- ""
13668
- ].join("\n");
14848
+ /** The text of each of `paths` (of {@link scaffoldFiles}) for `input`. */
14849
+ function scaffoldText(paths, input) {
14850
+ const all = scaffoldFiles(input);
14851
+ return Object.fromEntries(paths.flatMap((path) => {
14852
+ const text = all.get(path);
14853
+ return text === void 0 ? [] : [[path, text]];
14854
+ }));
13669
14855
  }
13670
14856
  /**
13671
- * Writes `artifact/create`'s entry into `dir`, completing an interrupted write: an existing file
13672
- * that is the expected text or a prefix of it (a write cut short) ends as the expected text, and
13673
- * anything else the author has written since is left alone.
14857
+ * Writes `artifact/create`'s files (`files`, path to text) into `dir`, completing an interrupted
14858
+ * write: an existing file whose bytes are the expected text's or a prefix of them (a write cut
14859
+ * short, even inside a character) ends as the expected text, and anything else the author has
14860
+ * written since is left alone.
13674
14861
  */
13675
- async function writeScaffold(dir, artifactId, title) {
13676
- const expected = scaffold(artifactId, title);
13677
- const file = join(dir, "index.tsx");
14862
+ async function writeScaffold(dir, files) {
13678
14863
  await mkdir(dir, { recursive: true });
13679
- let current;
13680
- try {
13681
- current = await readFile(file, "utf8");
13682
- } catch {
13683
- current = void 0;
14864
+ let wrote = false;
14865
+ for (const [path, text] of Object.entries(files)) {
14866
+ const expected = Buffer.from(text, "utf8");
14867
+ const file = join(dir, path);
14868
+ let current;
14869
+ try {
14870
+ current = await readFile(file);
14871
+ } catch {
14872
+ current = void 0;
14873
+ }
14874
+ if (current !== void 0) {
14875
+ if (!(current.length <= expected.length && expected.subarray(0, current.length).equals(current)) || current.length === expected.length) continue;
14876
+ }
14877
+ await writeFile(file, expected);
14878
+ fsyncPath(file);
14879
+ wrote = true;
13684
14880
  }
13685
- if (current !== void 0 && !expected.startsWith(current)) return;
13686
- if (current === expected) return;
13687
- await writeFile(file, expected);
13688
- fsyncPath(file);
13689
- fsyncPath(dir, true);
14881
+ if (wrote) fsyncPath(dir, true);
13690
14882
  }
13691
14883
  /**
13692
14884
  * What is wrong with a stored version directory, or `undefined` when it is intact: its
@@ -14097,10 +15289,18 @@ function createPublisher(options) {
14097
15289
  async function create(params) {
14098
15290
  const key = requestKey("artifact/create", params);
14099
15291
  if (key !== void 0) {
14100
- const result = ledger.read((db) => recordedResult(db, key));
14101
- if (result !== void 0) {
14102
- await writeScaffold(result.dir, result.artifactId, params.title ?? basename(result.dir));
14103
- return result;
15292
+ const recorded = ledger.read((db) => recordedResult(db, key));
15293
+ if (recorded !== void 0) {
15294
+ if ("result" in recorded) {
15295
+ await writeScaffold(recorded.result.dir, recorded.scaffold.files);
15296
+ return recorded.result;
15297
+ }
15298
+ await writeScaffold(recorded.dir, scaffoldText(recorded.files, {
15299
+ artifactId: recorded.artifactId,
15300
+ title: params.title ?? basename(recorded.dir),
15301
+ version: options.runtimeVersion
15302
+ }));
15303
+ return recorded;
14104
15304
  }
14105
15305
  }
14106
15306
  if (params.template !== void 0) throw new RpcError(createDiagnostic("MOSTRA_ARTIFACT_TEMPLATE_UNKNOWN", { message: `This Mostra release provides no template "${params.template}"; create the artifact without one.` }));
@@ -14112,11 +15312,19 @@ function createPublisher(options) {
14112
15312
  const result = {
14113
15313
  artifactId: ArtifactId.create(),
14114
15314
  dir,
14115
- files: ["index.tsx"]
15315
+ files: [...SCAFFOLD_PATHS]
14116
15316
  };
14117
- record(key, result);
15317
+ const files = scaffoldText(result.files, {
15318
+ artifactId: result.artifactId,
15319
+ title: params.title ?? basename(dir),
15320
+ version: options.runtimeVersion
15321
+ });
15322
+ record(key, {
15323
+ result,
15324
+ scaffold: { files }
15325
+ });
14118
15326
  faults.at("create:after-record");
14119
- await writeScaffold(dir, result.artifactId, params.title ?? basename(dir));
15327
+ await writeScaffold(dir, files);
14120
15328
  return result;
14121
15329
  }
14122
15330
  }
@@ -14215,7 +15423,7 @@ function artifactMethods(options) {
14215
15423
  options.published?.(receipt.artifactId);
14216
15424
  return options.link ? {
14217
15425
  ...receipt,
14218
- ...options.link(receipt.artifactId)
15426
+ ...await options.link(receipt.artifactId)
14219
15427
  } : receipt;
14220
15428
  }),
14221
15429
  handler(depsAddMethod, async (params) => {
@@ -15341,7 +16549,7 @@ function markHostConfigured(home, client, at = /* @__PURE__ */ new Date()) {
15341
16549
  */
15342
16550
  const HOME_SCOPE = "home";
15343
16551
  const ARTIFACT_SCOPE = /^art_[0-9A-HJKMNP-TV-Z]{26}$/;
15344
- function missing(name, detail) {
16552
+ function missing$1(name, detail) {
15345
16553
  return new RpcError(createDiagnostic("MOSTRA_SECRET_MISSING", {
15346
16554
  message: `No secret named ${name} is set${detail ? ` (${detail})` : ""}.`,
15347
16555
  hint: `Set it with \`mostra secret set ${name}\`, reading the value from stdin.`
@@ -15428,7 +16636,7 @@ function openSecrets(options) {
15428
16636
  return true;
15429
16637
  },
15430
16638
  async resolve(artifactId, name) {
15431
- if (!SECRET_NAME_PATTERN.test(name)) throw missing(name, "not a secret name");
16639
+ if (!SECRET_NAME_PATTERN.test(name)) throw missing$1(name, "not a secret name");
15432
16640
  const port = options.port?.();
15433
16641
  if (port) {
15434
16642
  let value;
@@ -15442,7 +16650,7 @@ function openSecrets(options) {
15442
16650
  name,
15443
16651
  error: String(error?.message ?? error)
15444
16652
  });
15445
- throw missing(name, "the host's secrets port didn't answer");
16653
+ throw missing$1(name, "the host's secrets port didn't answer");
15446
16654
  }
15447
16655
  if (typeof value === "string") {
15448
16656
  options.redactor.protectSecret(value);
@@ -15453,7 +16661,7 @@ function openSecrets(options) {
15453
16661
  kind: "artifact",
15454
16662
  artifactId
15455
16663
  }), name) ?? read(dirOf({ kind: "home" }), name);
15456
- if (value === void 0) throw missing(name);
16664
+ if (value === void 0) throw missing$1(name);
15457
16665
  options.redactor.protectSecret(value);
15458
16666
  return value;
15459
16667
  }
@@ -15947,65 +17155,987 @@ async function shutDownInstance(home, client) {
15947
17155
  name: "mostra-service",
15948
17156
  version: "0"
15949
17157
  });
15950
- await session.client.peer.call(mostraShutdownMethod, {}, { timeoutMs: 1e4 }).catch(() => void 0);
15951
- session.client.close();
15952
- } catch {
15953
- return;
17158
+ await session.client.peer.call(mostraShutdownMethod, {}, { timeoutMs: 1e4 }).catch(() => void 0);
17159
+ session.client.close();
17160
+ } catch {
17161
+ return;
17162
+ }
17163
+ const deadline = Date.now() + 2e4;
17164
+ while (Date.now() < deadline && await isSameProcess(record.pid, record.startTime)) await new Promise((resolve) => setTimeout(resolve, 100));
17165
+ }
17166
+ /** Whether Task Scheduler holds the home's task. */
17167
+ function taskRegistered(status) {
17168
+ try {
17169
+ run("schtasks", [
17170
+ "/Query",
17171
+ "/TN",
17172
+ status.name
17173
+ ]);
17174
+ return true;
17175
+ } catch {
17176
+ return false;
17177
+ }
17178
+ }
17179
+ /**
17180
+ * Stops and removes the home's login service; a home without one is left as it is. On Windows a
17181
+ * task Task Scheduler still holds is removed though the home lost its definition (restored from a
17182
+ * backup, removed by hand), or the task would keep starting the daemon at every logon (Opus review
17183
+ * of WP-W2, finding 5).
17184
+ */
17185
+ async function uninstallService(spec, options = {}) {
17186
+ const status = serviceFor(spec);
17187
+ const orphaned = !status.installed && status.manager === "task-scheduler" && !options.noStart && taskRegistered(status);
17188
+ if (!status.installed && !orphaned) return status;
17189
+ if (!options.noStart) await stopService(status, spec.home, options);
17190
+ rmSync(status.file, { force: true });
17191
+ if (!options.noStart && status.manager === "systemd") try {
17192
+ run("systemctl", ["--user", "daemon-reload"]);
17193
+ } catch {}
17194
+ return {
17195
+ ...status,
17196
+ installed: false
17197
+ };
17198
+ }
17199
+ /**
17200
+ * Whether the home has a login service whose file runs this home's daemon (`mostra doctor`); on
17201
+ * Windows also whether Task Scheduler holds its task (`registered`).
17202
+ */
17203
+ function serviceStatus(spec) {
17204
+ const status = serviceFor(spec);
17205
+ const registered = status.manager === "task-scheduler" ? { registered: taskRegistered(status) } : {};
17206
+ if (!status.installed) return {
17207
+ ...status,
17208
+ current: false,
17209
+ ...registered
17210
+ };
17211
+ return {
17212
+ ...status,
17213
+ current: readDefinition(status) === serviceFile(spec, status),
17214
+ ...registered
17215
+ };
17216
+ }
17217
+ //#endregion
17218
+ //#region src/share/tunnel.ts
17219
+ /**
17220
+ * A tunnel tool's process (D158 item 4): `tailscale serve`, `tailscale funnel` or `cloudflared`,
17221
+ * started through the process manager (recorded, gated, reaped after a crash, RT-09), its output
17222
+ * read line by line until it says it serves, fails, or runs out of time. A tunnel that serves
17223
+ * keeps running until it is stopped; `ended` says when it ends by itself.
17224
+ */
17225
+ const TAIL = 20;
17226
+ /** Starts a tunnel tool and resolves once it serves; rejects with a `MOSTRA_SHARE_*` RpcError. */
17227
+ async function runTunnel(options) {
17228
+ const lines = [];
17229
+ let origin = options.origin;
17230
+ let settle;
17231
+ const settled = new Promise((resolve) => {
17232
+ settle = resolve;
17233
+ });
17234
+ let serving = false;
17235
+ const onLine = (line) => {
17236
+ lines.push(line);
17237
+ if (lines.length > TAIL) lines.shift();
17238
+ if (serving) return;
17239
+ const verdict = options.read(line);
17240
+ if (verdict === void 0) return;
17241
+ if (verdict.kind === "origin") {
17242
+ origin = verdict.origin;
17243
+ return;
17244
+ }
17245
+ if (verdict.kind === "failed") {
17246
+ settle?.({
17247
+ ok: false,
17248
+ diagnostic: verdict.diagnostic
17249
+ });
17250
+ return;
17251
+ }
17252
+ if (verdict.origin !== void 0) origin = verdict.origin;
17253
+ if (origin !== void 0) {
17254
+ serving = true;
17255
+ settle?.({ ok: true });
17256
+ }
17257
+ };
17258
+ let child;
17259
+ try {
17260
+ child = await options.processes.spawn({
17261
+ kind: options.kind,
17262
+ ownerRef: options.ownerRef,
17263
+ command: options.command,
17264
+ args: options.args,
17265
+ env: options.env,
17266
+ onStdout: onLine,
17267
+ onStderr: onLine
17268
+ });
17269
+ } catch (error) {
17270
+ throw new RpcError(createDiagnostic("MOSTRA_SHARE_TOOL_NOT_READY", { message: `${options.label} couldn't start: ${error.message}` }));
17271
+ }
17272
+ let stopping = false;
17273
+ const exited = child.exited.then((exit) => {
17274
+ if (!serving) settle?.({
17275
+ ok: false,
17276
+ diagnostic: createDiagnostic("MOSTRA_SHARE_TUNNEL_FAILED", { message: `${options.label} ended before it served (exit ${exit.code ?? exit.signal}): ${lastWords(lines)}` })
17277
+ });
17278
+ return exit;
17279
+ });
17280
+ const timer = setTimeout(() => {
17281
+ settle?.({
17282
+ ok: false,
17283
+ diagnostic: createDiagnostic("MOSTRA_SHARE_TUNNEL_FAILED", { message: `${options.label} didn't serve within ${Math.round(options.timeoutMs / 1e3)} s: ${lastWords(lines)}` })
17284
+ });
17285
+ }, options.timeoutMs);
17286
+ const outcome = await settled;
17287
+ clearTimeout(timer);
17288
+ if (!outcome.ok) {
17289
+ stopping = true;
17290
+ await child.stop(3e3).catch(() => void 0);
17291
+ throw new RpcError(outcome.diagnostic);
17292
+ }
17293
+ options.log.info("share.tunnel_serving", {
17294
+ kind: options.kind,
17295
+ owner: options.ownerRef,
17296
+ origin
17297
+ });
17298
+ const ended = exited.then((exit) => new Promise((resolve) => {
17299
+ if (!stopping) resolve({
17300
+ code: exit.code,
17301
+ lines: [...lines]
17302
+ });
17303
+ }));
17304
+ return {
17305
+ origin,
17306
+ ended,
17307
+ async stop() {
17308
+ stopping = true;
17309
+ await child.stop(3e3).catch(() => void 0);
17310
+ }
17311
+ };
17312
+ }
17313
+ /** The last meaningful lines of a tool's output, for a message. */
17314
+ function lastWords(lines) {
17315
+ const meaningful = lines.filter((line) => line.trim() !== "").slice(-3);
17316
+ return meaningful.length === 0 ? "it said nothing" : meaningful.join(" / ").slice(0, 600);
17317
+ }
17318
+ /**
17319
+ * Runs a tool to its end and resolves with its standard output (a status query), or rejects with
17320
+ * `MOSTRA_SHARE_TOOL_NOT_READY` naming what it said.
17321
+ */
17322
+ async function runToCompletion(options) {
17323
+ const stdout = [];
17324
+ const stderr = [];
17325
+ let child;
17326
+ try {
17327
+ child = await options.processes.spawn({
17328
+ kind: options.kind,
17329
+ ownerRef: options.ownerRef,
17330
+ command: options.command,
17331
+ args: options.args,
17332
+ env: options.env,
17333
+ onStdout: (line) => stdout.push(line),
17334
+ onStderr: (line) => stderr.push(line)
17335
+ });
17336
+ } catch (error) {
17337
+ throw new RpcError(createDiagnostic("MOSTRA_SHARE_TOOL_NOT_READY", { message: `${options.label} couldn't start: ${error.message}` }));
15954
17338
  }
15955
- const deadline = Date.now() + 2e4;
15956
- while (Date.now() < deadline && await isSameProcess(record.pid, record.startTime)) await new Promise((resolve) => setTimeout(resolve, 100));
17339
+ const timer = setTimeout(() => void child.stop(1e3), options.timeoutMs);
17340
+ const exit = await child.exited;
17341
+ clearTimeout(timer);
17342
+ return {
17343
+ code: exit.code,
17344
+ stdout: stdout.join("\n"),
17345
+ stderr: stderr.join("\n")
17346
+ };
15957
17347
  }
15958
- /** Whether Task Scheduler holds the home's task. */
15959
- function taskRegistered(status) {
17348
+ //#endregion
17349
+ //#region src/share/cloudflare.ts
17350
+ /**
17351
+ * The Cloudflare driver (D158 item 4): a Cloudflare quick tunnel per face, `cloudflared tunnel
17352
+ * --url http://127.0.0.1:<port>`, which needs no account and gets a random `trycloudflare.com`
17353
+ * hostname. Each hostname is its own site (`trycloudflare.com` is a public suffix), so a share's
17354
+ * shell and artifact are cross-site and its frames use worker mode (D70). Quick tunnels hold every
17355
+ * response back until it ends, so pages long-poll (VERIFIED_FACTS, WP-13). A quick tunnel's
17356
+ * hostname dies with its process, so a Cloudflare share ends with its tunnel.
17357
+ */
17358
+ /** How long a quick tunnel may take to serve: registering and the hostname's first answer. */
17359
+ const QUICK_TUNNEL_TIMEOUT_MS = 6e4;
17360
+ /** How `cloudflared` runs, or `MOSTRA_SHARE_TOOL_MISSING`. */
17361
+ function cloudflared(context) {
17362
+ const tool = toolCommand("cloudflared", context.env);
17363
+ if (!tool) throw new RpcError(createDiagnostic("MOSTRA_SHARE_TOOL_MISSING", { message: `cloudflared isn't installed on this machine. ${installHint("cloudflared")}` }));
17364
+ return tool;
17365
+ }
17366
+ /**
17367
+ * Reads `cloudflared`'s log: it names the quick tunnel's address in a banner, and serves once a
17368
+ * connection to Cloudflare's edge is registered.
17369
+ */
17370
+ function quickTunnelReader(fake) {
17371
+ return (line) => {
17372
+ const local = fake ? /\b(http:\/\/[a-z0-9-]+\.localhost:\d+)\b/.exec(line) : null;
17373
+ if (local) return {
17374
+ kind: "origin",
17375
+ origin: local[1].toLowerCase()
17376
+ };
17377
+ const address = /https:\/\/([a-z0-9-]+\.trycloudflare\.com)\b/i.exec(line);
17378
+ if (address) return {
17379
+ kind: "origin",
17380
+ origin: `https://${address[1].toLowerCase()}`
17381
+ };
17382
+ if (/Registered tunnel connection/i.test(line)) return { kind: "serving" };
17383
+ if (/failed to (request|create) quick tunnel|error unmarshaling QuickTunnel|429 Too Many Requests/i.test(line)) return {
17384
+ kind: "failed",
17385
+ diagnostic: createDiagnostic("MOSTRA_SHARE_TUNNEL_FAILED", { message: `Cloudflare didn't open a quick tunnel: ${line.trim().slice(0, 300)}` })
17386
+ };
17387
+ };
17388
+ }
17389
+ /**
17390
+ * Opens a quick tunnel to `local`. It never reads the user's own `cloudflared` configuration (a
17391
+ * file with ingress rules would turn the quick tunnel off): it runs with an empty one of its own.
17392
+ */
17393
+ function quickTunnel(context, input) {
17394
+ const tool = cloudflared(context);
17395
+ mkdirSync(context.cacheDir, {
17396
+ recursive: true,
17397
+ mode: 448
17398
+ });
17399
+ const config = join(context.cacheDir, "cloudflared.yml");
17400
+ writeFileSync(config, "# Mostra's quick tunnels read no other configuration.\nno-autoupdate: true\n", { mode: 384 });
17401
+ return runTunnel({
17402
+ processes: context.processes,
17403
+ log: context.log,
17404
+ kind: "tunnel-cloudflare",
17405
+ ownerRef: input.ownerRef,
17406
+ command: tool.command,
17407
+ args: [
17408
+ ...tool.args,
17409
+ "tunnel",
17410
+ "--config",
17411
+ config,
17412
+ "--no-autoupdate",
17413
+ "--metrics",
17414
+ "127.0.0.1:0",
17415
+ "--management-diagnostics=false",
17416
+ "--url",
17417
+ input.local
17418
+ ],
17419
+ env: context.env,
17420
+ read: quickTunnelReader(tool.fake),
17421
+ timeoutMs: QUICK_TUNNEL_TIMEOUT_MS,
17422
+ label: "A Cloudflare quick tunnel"
17423
+ });
17424
+ }
17425
+ /**
17426
+ * Waits until a quick tunnel's hostname resolves at Cloudflare's own resolvers (1.1.1.1 and
17427
+ * 1.0.0.1), asked directly, past this machine's cache. A new `trycloudflare.com` name takes a few
17428
+ * seconds to appear, and a resolver that is asked too early caches the miss for many minutes
17429
+ * (observed: the link never opened on this machine after an early probe, WP-13), so neither this
17430
+ * machine nor a viewer's phone may ask before the name exists. Resolves `false` when the budget
17431
+ * runs out (a network that blocks outside resolvers): the share goes on, since a viewer's
17432
+ * resolver may still answer.
17433
+ */
17434
+ async function hostnameResolves(hostname, budgetMs) {
17435
+ const resolver = new Resolver({
17436
+ timeout: 2e3,
17437
+ tries: 1
17438
+ });
17439
+ resolver.setServers(["1.1.1.1", "1.0.0.1"]);
17440
+ const until = Date.now() + budgetMs;
17441
+ while (Date.now() < until) {
17442
+ try {
17443
+ if ((await resolver.resolve4(hostname)).length > 0) return true;
17444
+ } catch {}
17445
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
17446
+ }
17447
+ return false;
17448
+ }
17449
+ //#endregion
17450
+ //#region src/share/tailscale.ts
17451
+ /**
17452
+ * The Tailscale driver (D158 item 4): Tailscale Serve for tailnet shares and Funnel for public
17453
+ * ones, through foreground `tailscale serve` and `tailscale funnel` children, one per address.
17454
+ * A foreground configuration lives as long as its command, so a stopped or crashed share leaves
17455
+ * nothing exposed. The device's name comes from `tailscale status --json`; a port this device's
17456
+ * own configuration already uses is never taken over.
17457
+ */
17458
+ const FUNNEL_ARTIFACT_PORTS = [8443, 1e4];
17459
+ /** How long `tailscale serve` or `funnel` may take to serve. */
17460
+ const SERVE_TIMEOUT_MS = 3e4;
17461
+ const missing = () => new RpcError(createDiagnostic("MOSTRA_SHARE_TOOL_MISSING", { message: `Tailscale isn't installed on this machine (no \`tailscale\` found). ${installHint("tailscale")}` }));
17462
+ /** Finds Tailscale and this device, or explains what is missing. */
17463
+ async function tailnetDevice(context) {
17464
+ const tool = toolCommand("tailscale", context.env);
17465
+ if (!tool) throw missing();
17466
+ const status = await runToCompletion({
17467
+ processes: context.processes,
17468
+ kind: "tunnel-query",
17469
+ ownerRef: "tailscale",
17470
+ command: tool.command,
17471
+ args: [
17472
+ ...tool.args,
17473
+ "status",
17474
+ "--json"
17475
+ ],
17476
+ env: context.env,
17477
+ timeoutMs: 15e3,
17478
+ label: "Tailscale"
17479
+ });
17480
+ let parsed;
15960
17481
  try {
15961
- run("schtasks", [
15962
- "/Query",
15963
- "/TN",
15964
- status.name
15965
- ]);
15966
- return true;
17482
+ parsed = JSON.parse(status.stdout);
15967
17483
  } catch {
15968
- return false;
17484
+ throw new RpcError(createDiagnostic("MOSTRA_SHARE_TOOL_NOT_READY", { message: `Tailscale didn't report its status: ${(status.stderr || status.stdout).trim().slice(0, 400) || `exit ${status.code}`}. Start Tailscale and sign in (\`tailscale up\`).` }));
15969
17485
  }
17486
+ if (parsed.BackendState !== "Running") throw new RpcError(createDiagnostic("MOSTRA_SHARE_TOOL_NOT_READY", { message: `Tailscale is ${parsed.BackendState ?? "not running"} on this machine. Start it and sign in (\`tailscale up\`).` }));
17487
+ const dns = parsed.Self?.DNSName?.replace(/\.$/, "").toLowerCase();
17488
+ if (!dns || parsed.CurrentTailnet?.MagicDNSEnabled === false) throw new RpcError(createDiagnostic("MOSTRA_SHARE_NOT_ENABLED", { message: "This tailnet has MagicDNS off, which Tailscale Serve and Funnel need for the device's name. Turn it on in the tailnet's DNS settings (https://login.tailscale.com/admin/dns)." }));
17489
+ return {
17490
+ tool,
17491
+ hostname: dns,
17492
+ served: await servedPorts(context, tool)
17493
+ };
17494
+ }
17495
+ /** The ports this device's Serve and Funnel configuration uses now. */
17496
+ async function servedPorts(context, tool) {
17497
+ const status = await runToCompletion({
17498
+ processes: context.processes,
17499
+ kind: "tunnel-query",
17500
+ ownerRef: "tailscale",
17501
+ command: tool.command,
17502
+ args: [
17503
+ ...tool.args,
17504
+ "serve",
17505
+ "status",
17506
+ "--json"
17507
+ ],
17508
+ env: context.env,
17509
+ timeoutMs: 15e3,
17510
+ label: "Tailscale"
17511
+ });
17512
+ const ports = /* @__PURE__ */ new Set();
17513
+ try {
17514
+ const config = JSON.parse(status.stdout || "{}");
17515
+ for (const key of Object.keys(config.TCP ?? {})) ports.add(Number(key));
17516
+ for (const session of Object.values(config.Foreground ?? {})) for (const key of Object.keys(session.TCP ?? {})) ports.add(Number(key));
17517
+ } catch {}
17518
+ return ports;
15970
17519
  }
15971
17520
  /**
15972
- * Stops and removes the home's login service; a home without one is left as it is. On Windows a
15973
- * task Task Scheduler still holds is removed though the home lost its definition (restored from a
15974
- * backup, removed by hand), or the task would keep starting the daemon at every logon (Opus review
15975
- * of WP-W2, finding 5).
17521
+ * Reads `tailscale serve` and `funnel` output: they serve once they print where; a tailnet
17522
+ * without the feature prints the address where an admin turns it on, which the share reports.
15976
17523
  */
15977
- async function uninstallService(spec, options = {}) {
15978
- const status = serviceFor(spec);
15979
- const orphaned = !status.installed && status.manager === "task-scheduler" && !options.noStart && taskRegistered(status);
15980
- if (!status.installed && !orphaned) return status;
15981
- if (!options.noStart) await stopService(status, spec.home, options);
15982
- rmSync(status.file, { force: true });
15983
- if (!options.noStart && status.manager === "systemd") try {
15984
- run("systemctl", ["--user", "daemon-reload"]);
15985
- } catch {}
15986
- return {
15987
- ...status,
15988
- installed: false
17524
+ function serveReader(feature, device, port) {
17525
+ let notEnabled = false;
17526
+ const expected = tailnetOrigin(device.hostname, port);
17527
+ return (line) => {
17528
+ const text = line.trim();
17529
+ const printed = /^(https?:\/\/\S+?)\/?$/.exec(text)?.[1]?.toLowerCase();
17530
+ if (printed !== void 0 && (printed === expected || device.tool.fake && /^http:\/\/(\[::1\]|127\.0\.0\.1|localhost):\d+$/.test(printed))) return {
17531
+ kind: "origin",
17532
+ origin: printed
17533
+ };
17534
+ if (/not enabled on your tailnet|isn't enabled|is not enabled/i.test(text)) {
17535
+ notEnabled = true;
17536
+ return;
17537
+ }
17538
+ const consent = /https:\/\/login\.tailscale\.com\/\S+/.exec(text);
17539
+ if (consent && notEnabled) return {
17540
+ kind: "failed",
17541
+ diagnostic: createDiagnostic("MOSTRA_SHARE_NOT_ENABLED", { message: `Tailscale ${feature} isn't enabled for this device's tailnet. An admin of the tailnet turns it on at ${consent[0]}` })
17542
+ };
17543
+ if (/^Available (within your tailnet|on the internet)/i.test(text) || /Press Ctrl\+C to exit/i.test(text)) return { kind: "serving" };
17544
+ if (/already|in use|conflict/i.test(text) && /port|serve|listen/i.test(text)) return {
17545
+ kind: "failed",
17546
+ diagnostic: createDiagnostic("MOSTRA_SHARE_PORTS_EXHAUSTED", { message: `Tailscale refused the port: ${text.slice(0, 300)}` })
17547
+ };
17548
+ if (/^(error|failed)|permission denied|access denied/i.test(text)) return {
17549
+ kind: "failed",
17550
+ diagnostic: createDiagnostic("MOSTRA_SHARE_TOOL_NOT_READY", { message: `Tailscale ${feature} refused the share: ${text.slice(0, 300)}` })
17551
+ };
15989
17552
  };
15990
17553
  }
15991
17554
  /**
15992
- * Whether the home has a login service whose file runs this home's daemon (`mostra doctor`); on
15993
- * Windows also whether Task Scheduler holds its task (`registered`).
17555
+ * Serves `local` at `https://<device>:<port>` on the tailnet (`serve`) or on the internet
17556
+ * (`funnel`), until the tunnel is stopped.
15994
17557
  */
15995
- function serviceStatus(spec) {
15996
- const status = serviceFor(spec);
15997
- const registered = status.manager === "task-scheduler" ? { registered: taskRegistered(status) } : {};
15998
- if (!status.installed) return {
15999
- ...status,
16000
- current: false,
16001
- ...registered
17558
+ function expose(context, device, input) {
17559
+ const label = input.feature === "serve" ? "Tailscale Serve" : "Tailscale Funnel";
17560
+ return runTunnel({
17561
+ processes: context.processes,
17562
+ log: context.log,
17563
+ kind: `tunnel-${input.feature}`,
17564
+ ownerRef: input.ownerRef,
17565
+ command: device.tool.command,
17566
+ args: [
17567
+ ...device.tool.args,
17568
+ input.feature,
17569
+ `--https=${input.port}`,
17570
+ input.local
17571
+ ],
17572
+ env: context.env,
17573
+ read: serveReader(input.feature === "serve" ? "Serve" : "Funnel", device, input.port),
17574
+ ...device.tool.fake ? {} : { origin: tailnetOrigin(device.hostname, input.port) },
17575
+ timeoutMs: SERVE_TIMEOUT_MS,
17576
+ label
17577
+ });
17578
+ }
17579
+ /** `https://<device>` with the port only when it isn't 443, as a browser writes the origin. */
17580
+ function tailnetOrigin(hostname, port) {
17581
+ return port === 443 ? `https://${hostname}` : `https://${hostname}:${port}`;
17582
+ }
17583
+ //#endregion
17584
+ //#region src/share/index.ts
17585
+ /**
17586
+ * Shares (HY-04, HY-05, D158): an artifact opened to viewers beyond this machine through a tunnel
17587
+ * the instance drives. A share opens the gateway's faces for its tunnel (D158 item 1), the tunnel
17588
+ * tool's processes that forward to them, and a link of its own at the tunnel's shell address
17589
+ * (D97 item 10); it ends at its TTL, on `share/stop`, when its link is revoked, or when its tunnel
17590
+ * can't continue, and every end revokes its link and stops what only it used.
17591
+ *
17592
+ * - **Tailnet** (Tailscale Serve): the shell's and each artifact's face keep leased ports, served
17593
+ * on the device's name at the same port numbers, so tailnet links survive restarts. Requests
17594
+ * carry the tailnet person, who becomes the viewer (D158 item 2).
17595
+ * - **Funnel**: the shell on 443 and two artifacts on 8443 and 10000 (D158 item 4), public.
17596
+ * - **Cloudflare** quick tunnels: one per face, each a site of its own, so worker-mode frames
17597
+ * (D70), and pages long-poll, since quick tunnels hold responses back. A quick tunnel's address
17598
+ * dies with its process, so its share ends with it, a restart included.
17599
+ *
17600
+ * ```ts
17601
+ * const shares = createShares({ ledger, log, gateway, capabilities, interaction, artifacts, … });
17602
+ * const share = await shares.start({ artifact: { artifactId }, via: "cloudflare", ttl: "1h" });
17603
+ * share.url; // https://<random>.trycloudflare.com/a/art_…#t=…
17604
+ * ```
17605
+ */
17606
+ /** How often active shares are checked for an expired or revoked link. */
17607
+ const SWEEP_MS = 3e4;
17608
+ /** How a tailnet or Funnel tunnel that ended by itself is set up again: after 1, 4 and 16 s. */
17609
+ const RESTART_DELAYS_MS = [
17610
+ 1e3,
17611
+ 4e3,
17612
+ 16e3
17613
+ ];
17614
+ /** How long a restart keeps trying to set a share up again before ending it (Tailscale starting). */
17615
+ const RECOVERY_DELAYS_MS = [
17616
+ 0,
17617
+ 5e3,
17618
+ 15e3,
17619
+ 3e4,
17620
+ 6e4
17621
+ ];
17622
+ /** How long a quick tunnel's name may take to appear before its link is handed out anyway. */
17623
+ const PROBE_MS = 3e4;
17624
+ /** Creates the shares of one instance. */
17625
+ function createShares(options) {
17626
+ const { ledger, log, gateway, capabilities, interaction } = options;
17627
+ const exposures = /* @__PURE__ */ new Map();
17628
+ const timers = /* @__PURE__ */ new Map();
17629
+ const inflight = new InflightRequests();
17630
+ let closed = false;
17631
+ let chain = Promise.resolve();
17632
+ /** Share starts and stops run one at a time, so refcounts and port plans never race. */
17633
+ const serial = (task) => {
17634
+ const run = chain.then(task, task);
17635
+ chain = run.catch(() => void 0);
17636
+ return run;
17637
+ };
17638
+ const toolContext = {
17639
+ processes: options.processes,
17640
+ log,
17641
+ env: {
17642
+ ...options.toolEnvironment,
17643
+ ...pick(options.environment)
17644
+ }
17645
+ };
17646
+ const iso = (ms) => new Date(ms).toISOString();
17647
+ const row = (shareId) => ledger.read((db) => db.get("SELECT * FROM share WHERE id = ?", shareId));
17648
+ const toShare = (found) => {
17649
+ const tokenId = capabilities.current(found.token_id);
17650
+ const url = found.stopped_at === null ? gateway.reveal(tokenId) : void 0;
17651
+ const artifactKey = JSON.parse(found.plan_json).faces.find((face) => face.listener === "artifact")?.key;
17652
+ const artifactOrigin = found.stopped_at === null && artifactKey !== void 0 ? gateway.face(artifactKey)?.origin() : void 0;
17653
+ return {
17654
+ shareId: found.id,
17655
+ artifactId: found.artifact_id,
17656
+ via: found.via,
17657
+ ...url !== void 0 ? { url } : {},
17658
+ hostname: found.hostname,
17659
+ ...artifactOrigin !== void 0 ? { artifactOrigin } : {},
17660
+ mode: found.mode,
17661
+ tokenId,
17662
+ startedAt: found.started_at,
17663
+ ...found.expires_at !== null ? { expiresAt: found.expires_at } : {},
17664
+ state: found.stopped_at === null ? "active" : "stopped",
17665
+ ...found.stopped_at !== null ? { stoppedAt: found.stopped_at } : {},
17666
+ ...found.stop_reason !== null ? { stopReason: found.stop_reason } : {}
17667
+ };
17668
+ };
17669
+ const activeRows = () => ledger.read((db) => db.all("SELECT * FROM share WHERE stopped_at IS NULL ORDER BY started_at DESC"));
17670
+ /**
17671
+ * The tunnel of a face, started for `shareId` or joined when it runs already. A tunnel that
17672
+ * ends by itself is set up again (Tailscale, whose address is the device's) or ends every share
17673
+ * that used it (Cloudflare, whose address died with it).
17674
+ */
17675
+ const acquire = async (key, shareId, via, start) => {
17676
+ const running = exposures.get(key);
17677
+ if (running?.restarting) throw new RpcError(createDiagnostic("MOSTRA_SHARE_TUNNEL_FAILED", { message: "This share's tunnel stopped a moment ago and is being started again; try again in a few seconds." }));
17678
+ if (running) {
17679
+ running.refs.add(shareId);
17680
+ return running.tunnel;
17681
+ }
17682
+ const tunnel = await start();
17683
+ const exposure = {
17684
+ tunnel,
17685
+ refs: /* @__PURE__ */ new Set([shareId]),
17686
+ start,
17687
+ via,
17688
+ restarting: false
17689
+ };
17690
+ exposures.set(key, exposure);
17691
+ watch(key, exposure);
17692
+ return tunnel;
17693
+ };
17694
+ const watch = (key, exposure) => {
17695
+ const current = exposure.tunnel;
17696
+ current.ended.then(async (end) => {
17697
+ if (closed || exposures.get(key) !== exposure || exposure.tunnel !== current) return;
17698
+ log.warn("share.tunnel_dropped", {
17699
+ key,
17700
+ code: end.code,
17701
+ lines: end.lines.slice(-3)
17702
+ });
17703
+ if (exposure.via !== "cloudflare") {
17704
+ exposure.restarting = true;
17705
+ for (const delay of RESTART_DELAYS_MS) {
17706
+ await new Promise((resolve) => setTimeout(resolve, delay));
17707
+ if (closed || exposures.get(key) !== exposure) return;
17708
+ try {
17709
+ if (!await serial(async () => {
17710
+ if (closed || exposures.get(key) !== exposure) return false;
17711
+ const tunnel = await exposure.start();
17712
+ if (closed || exposures.get(key) !== exposure) {
17713
+ await tunnel.stop();
17714
+ return false;
17715
+ }
17716
+ exposure.tunnel = tunnel;
17717
+ return true;
17718
+ })) return;
17719
+ exposure.restarting = false;
17720
+ log.info("share.tunnel_restored", { key });
17721
+ watch(key, exposure);
17722
+ return;
17723
+ } catch (error) {
17724
+ log.warn("share.tunnel_restart_failed", {
17725
+ key,
17726
+ error: error.message
17727
+ });
17728
+ }
17729
+ }
17730
+ }
17731
+ for (const shareId of [...exposure.refs]) await serial(() => stop(shareId, "tunnel")).catch((error) => log.error("share.stop_failed", {
17732
+ shareId,
17733
+ error
17734
+ }));
17735
+ });
17736
+ };
17737
+ /** Drops a share's hold on a face's tunnel, stopping it and closing the face when unused. */
17738
+ const release = async (key, shareId) => {
17739
+ const exposure = exposures.get(key);
17740
+ if (exposure) {
17741
+ exposure.refs.delete(shareId);
17742
+ if (exposure.refs.size > 0) return;
17743
+ exposures.delete(key);
17744
+ await exposure.tunnel.stop();
17745
+ }
17746
+ externalPorts.delete(key);
17747
+ await gateway.closeFace(key, !key.startsWith("tailnet:"));
17748
+ };
17749
+ /** The ttl a share's link gets: public shares 1 hour by default and at most 7 days (D158). */
17750
+ const lifetime = (via, ttl) => {
17751
+ if (via === "tailnet") return ttl === void 0 ? void 0 : durationMs(ttl);
17752
+ const ms = durationMs(ttl ?? PUBLIC_SHARE_DEFAULT_TTL);
17753
+ if (ms > PUBLIC_SHARE_MAX_TTL_MS) throw new RpcError(createDiagnostic("MOSTRA_SHARE_TTL_INVALID", { message: `A public share lasts at most 7 days; ${ttl} is longer.` }));
17754
+ return ms;
17755
+ };
17756
+ /** Opens a face and its tunnel for a share, or joins the ones that run already. */
17757
+ const faceFor = async (spec, shareId, tunnel, held) => {
17758
+ const face = await gateway.openFace(spec);
17759
+ held.push(face.key);
17760
+ const running = await acquire(face.key, shareId, spec.by, () => tunnel(face));
17761
+ face.setOrigin(running.origin);
17762
+ return face;
17763
+ };
17764
+ /** Sets up a share's faces and tunnels; on failure releases what it took. */
17765
+ const setUp = async (shareId, artifactId, via, planned) => {
17766
+ const held = [];
17767
+ try {
17768
+ if (via === "cloudflare") {
17769
+ const group = `cloudflare:${shareId}`;
17770
+ const context = {
17771
+ ...toolContext,
17772
+ cacheDir: options.cacheDir
17773
+ };
17774
+ const spec = (listener) => ({
17775
+ by: "cloudflare",
17776
+ group,
17777
+ listener,
17778
+ ...listener === "artifact" ? {
17779
+ artifactId,
17780
+ mode: "worker"
17781
+ } : {},
17782
+ via: "token",
17783
+ lease: false,
17784
+ streams: false
17785
+ });
17786
+ const settled = await Promise.allSettled([faceFor(spec("shell"), shareId, (face) => quickTunnel(context, {
17787
+ local: face.local,
17788
+ ownerRef: face.key
17789
+ }), held), faceFor(spec("artifact"), shareId, (face) => quickTunnel(context, {
17790
+ local: face.local,
17791
+ ownerRef: face.key
17792
+ }), held)]);
17793
+ const failed = settled.find((outcome) => outcome.status === "rejected");
17794
+ if (failed) throw failed.reason;
17795
+ const [shell, artifact] = settled.map((outcome) => outcome.value);
17796
+ await Promise.all([probe(shell.origin()), probe(artifact.origin())]);
17797
+ return {
17798
+ shell,
17799
+ artifact,
17800
+ plan: { faces: [{
17801
+ key: shell.key,
17802
+ listener: "shell"
17803
+ }, {
17804
+ key: artifact.key,
17805
+ listener: "artifact"
17806
+ }] },
17807
+ hostname: new URL(shell.origin()).hostname
17808
+ };
17809
+ }
17810
+ const device = await tailnetDevice(toolContext);
17811
+ const ours = (port) => [...exposures.entries()].some(([key, exposure]) => exposure.via !== "cloudflare" && planPort(key) === port);
17812
+ const free = (port) => !device.served.has(port) || ours(port);
17813
+ if (via === "tailnet") {
17814
+ const spec = (listener) => ({
17815
+ by: "tailnet",
17816
+ group: "tailnet",
17817
+ listener,
17818
+ ...listener === "artifact" ? { artifactId } : {},
17819
+ via: "tailnet",
17820
+ lease: true
17821
+ });
17822
+ const serveAt = (face) => {
17823
+ if (!free(face.port)) throw portTaken(face.port, "Serve");
17824
+ return tailnetTunnel(device, "serve", face.port, face);
17825
+ };
17826
+ const shell = await faceFor(spec("shell"), shareId, serveAt, held);
17827
+ const artifact = await faceFor(spec("artifact"), shareId, serveAt, held);
17828
+ return {
17829
+ shell,
17830
+ artifact,
17831
+ plan: { faces: [{
17832
+ key: shell.key,
17833
+ listener: "shell",
17834
+ external: shell.port
17835
+ }, {
17836
+ key: artifact.key,
17837
+ listener: "artifact",
17838
+ external: artifact.port
17839
+ }] },
17840
+ hostname: device.hostname
17841
+ };
17842
+ }
17843
+ const spec = (listener) => ({
17844
+ by: "funnel",
17845
+ group: "funnel",
17846
+ listener,
17847
+ ...listener === "artifact" ? { artifactId } : {},
17848
+ via: "token",
17849
+ lease: true
17850
+ });
17851
+ const shellKey = faceKey("funnel", "shell");
17852
+ if (!exposures.has(shellKey) && !free(443)) throw portTaken(443, "Funnel");
17853
+ const shell = await faceFor(spec("shell"), shareId, (face) => tailnetTunnel(device, "funnel", 443, face), held);
17854
+ const artifactKey = faceKey("funnel", "artifact", artifactId);
17855
+ const plannedPort = planned?.faces.find((face) => face.key === artifactKey)?.external;
17856
+ const port = planPort(artifactKey) ?? [plannedPort, ...FUNNEL_ARTIFACT_PORTS].find((candidate) => candidate !== void 0 && free(candidate) && ![...externalPorts].some(([key, taken]) => key !== artifactKey && taken === candidate));
17857
+ if (port === void 0) throw new RpcError(createDiagnostic("MOSTRA_SHARE_PORTS_EXHAUSTED", { 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.` }));
17858
+ const artifact = await faceFor(spec("artifact"), shareId, (face) => tailnetTunnel(device, "funnel", port, face), held);
17859
+ return {
17860
+ shell,
17861
+ artifact,
17862
+ plan: { faces: [{
17863
+ key: shell.key,
17864
+ listener: "shell",
17865
+ external: 443
17866
+ }, {
17867
+ key: artifact.key,
17868
+ listener: "artifact",
17869
+ external: port
17870
+ }] },
17871
+ hostname: device.hostname
17872
+ };
17873
+ } catch (error) {
17874
+ for (const key of held) await release(key, shareId).catch(() => void 0);
17875
+ throw error;
17876
+ }
17877
+ };
17878
+ /** The external ports of running Tailscale tunnels, by face key. */
17879
+ const externalPorts = /* @__PURE__ */ new Map();
17880
+ const planPort = (key) => externalPorts.get(key);
17881
+ const tailnetTunnel = async (device, feature, port, face) => {
17882
+ const tunnel = await expose(toolContext, device, {
17883
+ feature,
17884
+ port,
17885
+ local: face.local,
17886
+ ownerRef: face.key
17887
+ });
17888
+ externalPorts.set(face.key, port);
17889
+ return tunnel;
17890
+ };
17891
+ const portTaken = (port, feature) => new RpcError(createDiagnostic("MOSTRA_SHARE_PORTS_EXHAUSTED", { message: `Port ${port} of this device is in use by its own Tailscale ${feature} configuration, which Mostra never takes over.` }));
17892
+ /**
17893
+ * Waits until a quick tunnel's name exists at Cloudflare's resolvers, so the link never meets a
17894
+ * cached miss on this machine or a viewer's phone; nothing here resolves it before then.
17895
+ */
17896
+ const probe = async (origin) => {
17897
+ const budget = options.probeMs ?? PROBE_MS;
17898
+ if (origin === void 0 || budget <= 0) return;
17899
+ const hostname = new URL(origin).hostname;
17900
+ if (!hostname.endsWith(".trycloudflare.com")) return;
17901
+ if (!await hostnameResolves(hostname, budget)) log.warn("share.name_unresolved", {
17902
+ hostname,
17903
+ budgetMs: budget
17904
+ });
17905
+ };
17906
+ const start = async (params) => {
17907
+ const detail = options.artifacts.get(params.artifact);
17908
+ if (!detail.latestVersion && detail.versions.length === 0) throw new RpcError(createDiagnostic("MOSTRA_ARTIFACT_VERSION_NOT_FOUND", { message: `The artifact ${detail.id} has no published version to share.` }));
17909
+ const key = requestKey("share/start", params);
17910
+ if (key !== void 0) {
17911
+ const replay = ledger.read((db) => recordedResult(db, key));
17912
+ const found = replay ? row(replay.shareId) : void 0;
17913
+ if (found) return withUrl(toShare(found));
17914
+ }
17915
+ const ttlMs = lifetime(params.via, params.ttl);
17916
+ const shareId = ShareId.create();
17917
+ const { shell, artifact, plan, hostname } = await setUp(shareId, detail.id, params.via, void 0);
17918
+ const shellOrigin = shell.origin();
17919
+ const startedAt = options.now();
17920
+ const record = () => ledger.write((db) => {
17921
+ const viewerId = params.viewer === void 0 ? void 0 : interaction.viewerForSpec(db, params.viewer);
17922
+ const link = gateway.mintAt({
17923
+ artifactId: detail.id,
17924
+ shellOrigin,
17925
+ scopes: params.scopes,
17926
+ ttlMs,
17927
+ viewerId
17928
+ }, db);
17929
+ db.run("INSERT INTO share (id, artifact_id, via, hostname, token_id, mode, plan_json, started_at, expires_at, stopped_at, stop_reason) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL)", shareId, detail.id, params.via, hostname, link.tokenId, params.via === "cloudflare" ? "worker" : "cookie", JSON.stringify(plan), iso(startedAt), link.expiresAt ?? null);
17930
+ appendEvent(db, {
17931
+ artifactId: detail.id,
17932
+ type: "share.started",
17933
+ payload: {
17934
+ shareId,
17935
+ via: params.via,
17936
+ hostname,
17937
+ artifactOrigin: artifact.origin()
17938
+ }
17939
+ });
17940
+ if (key !== void 0) recordResult(db, key, { shareId });
17941
+ return link;
17942
+ });
17943
+ let minted;
17944
+ try {
17945
+ minted = record();
17946
+ } catch (error) {
17947
+ for (const face of plan.faces) await release(face.key, shareId).catch(() => void 0);
17948
+ throw error;
17949
+ }
17950
+ schedule(shareId, minted.expiresAt);
17951
+ log.info("share.started", {
17952
+ shareId,
17953
+ artifactId: detail.id,
17954
+ via: params.via,
17955
+ hostname
17956
+ });
17957
+ const started = row(shareId);
17958
+ return {
17959
+ ...toShare(started),
17960
+ url: minted.url
17961
+ };
17962
+ };
17963
+ const withUrl = (share) => ({
17964
+ ...share,
17965
+ url: share.url ?? gateway.reveal(share.tokenId) ?? ""
17966
+ });
17967
+ const schedule = (shareId, expiresAt) => {
17968
+ if (expiresAt === void 0) return;
17969
+ const delay = Math.max(0, Date.parse(expiresAt) - options.now());
17970
+ if (delay > 2 ** 31 - 1) return;
17971
+ const timer = setTimeout(() => {
17972
+ timers.delete(shareId);
17973
+ serial(() => stop(shareId, "expired")).catch((error) => log.error("share.stop_failed", {
17974
+ shareId,
17975
+ error
17976
+ }));
17977
+ }, delay);
17978
+ timer.unref?.();
17979
+ timers.set(shareId, timer);
17980
+ };
17981
+ /**
17982
+ * Ends a share once: its link is revoked (unless it expired or was revoked already), the
17983
+ * ledger records why, and its faces' tunnels stop when no other share uses them.
17984
+ */
17985
+ const stop = async (shareId, reason) => {
17986
+ const found = row(shareId);
17987
+ if (!found || found.stopped_at !== null) return void 0;
17988
+ const at = options.now();
17989
+ ledger.write((db) => {
17990
+ db.run("UPDATE share SET stopped_at = ?, stop_reason = ? WHERE id = ?", iso(at), reason, shareId);
17991
+ if (reason !== "expired" && reason !== "revoked") capabilities.revoke(capabilities.current(found.token_id), db);
17992
+ appendEvent(db, {
17993
+ artifactId: found.artifact_id,
17994
+ type: "share.stopped",
17995
+ payload: {
17996
+ shareId,
17997
+ via: found.via,
17998
+ hostname: found.hostname,
17999
+ reason
18000
+ }
18001
+ });
18002
+ });
18003
+ const timer = timers.get(shareId);
18004
+ if (timer !== void 0) clearTimeout(timer);
18005
+ timers.delete(shareId);
18006
+ const plan = JSON.parse(found.plan_json);
18007
+ for (const face of plan.faces) await release(face.key, shareId);
18008
+ log.info("share.stopped", {
18009
+ shareId,
18010
+ via: found.via,
18011
+ reason
18012
+ });
18013
+ return toShare(row(shareId));
18014
+ };
18015
+ /** Ends shares whose link expired or was revoked since (`view/revoke` of a share's link). */
18016
+ const sweep = async () => {
18017
+ for (const found of activeRows()) {
18018
+ if (capabilities.grant(capabilities.current(found.token_id))?.live) continue;
18019
+ const expired = found.expires_at !== null && Date.parse(found.expires_at) <= options.now();
18020
+ await serial(() => stop(found.id, expired ? "expired" : "revoked"));
18021
+ }
18022
+ };
18023
+ const sweeper = setInterval(() => {
18024
+ sweep().catch((error) => log.error("share.sweep_failed", { error }));
18025
+ }, options.sweepMs ?? SWEEP_MS);
18026
+ sweeper.unref?.();
18027
+ const restore = async (found) => {
18028
+ const plan = JSON.parse(found.plan_json);
18029
+ let last;
18030
+ for (const delay of RECOVERY_DELAYS_MS) {
18031
+ if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay));
18032
+ if (closed) return;
18033
+ try {
18034
+ if (!await serial(async () => {
18035
+ const current = row(found.id);
18036
+ if (closed || !current || current.stopped_at !== null) return false;
18037
+ await setUp(found.id, found.artifact_id, found.via, plan);
18038
+ return true;
18039
+ })) return;
18040
+ schedule(found.id, found.expires_at ?? void 0);
18041
+ log.info("share.restored", {
18042
+ shareId: found.id,
18043
+ via: found.via
18044
+ });
18045
+ return;
18046
+ } catch (error) {
18047
+ last = error;
18048
+ log.warn("share.restore_failed", {
18049
+ shareId: found.id,
18050
+ error: error.message
18051
+ });
18052
+ }
18053
+ }
18054
+ log.warn("share.restore_gave_up", {
18055
+ shareId: found.id,
18056
+ error: last instanceof Error ? last.message : String(last)
18057
+ });
18058
+ await serial(() => stop(found.id, "tunnel"));
16002
18059
  };
16003
18060
  return {
16004
- ...status,
16005
- current: readDefinition(status) === serviceFile(spec, status),
16006
- ...registered
18061
+ methods: () => [
18062
+ handler(shareStartMethod, (params) => {
18063
+ const key = requestKey("share/start", params);
18064
+ const run = () => serial(() => start(params));
18065
+ return key === void 0 ? run() : inflight.run(key, run);
18066
+ }),
18067
+ handler(shareStopMethod, (params) => serial(async () => {
18068
+ if (params.shareId === void 0 === (params.artifact === void 0)) throw new RpcError(createDiagnostic("MOSTRA_HOST_INVALID_PARAMS", { message: "share/stop names either `shareId` or `artifact`, not both or neither." }), -32602);
18069
+ let ids;
18070
+ if (params.shareId !== void 0) {
18071
+ if (!row(params.shareId)) throw new RpcError(createDiagnostic("MOSTRA_SHARE_NOT_FOUND", { message: `No share ${params.shareId} exists in this home.` }));
18072
+ ids = [params.shareId];
18073
+ } else {
18074
+ const artifactId = options.artifacts.get(params.artifact).id;
18075
+ ids = activeRows().filter((found) => found.artifact_id === artifactId).map((found) => found.id);
18076
+ }
18077
+ const stopped = [];
18078
+ for (const id of ids) {
18079
+ const ended = await stop(id, "stopped");
18080
+ if (ended) stopped.push(ended);
18081
+ }
18082
+ return { stopped };
18083
+ })),
18084
+ handler(shareListMethod, (params) => {
18085
+ const artifactId = params.artifact === void 0 ? void 0 : options.artifacts.get(params.artifact).id;
18086
+ return { shares: ledger.read((db) => db.all(params.all === true ? "SELECT * FROM share ORDER BY stopped_at IS NOT NULL, started_at DESC" : "SELECT * FROM share WHERE stopped_at IS NULL ORDER BY started_at DESC")).filter((found) => artifactId === void 0 || found.artifact_id === artifactId).map(toShare) };
18087
+ })
18088
+ ],
18089
+ count: () => ledger.read((db) => db.get("SELECT COUNT(*) AS count FROM share WHERE stopped_at IS NULL")?.count ?? 0),
18090
+ active: () => activeRows().map((found) => {
18091
+ const { url: _url, ...rest } = toShare(found);
18092
+ return rest;
18093
+ }),
18094
+ async recover() {
18095
+ const pending = [];
18096
+ for (const found of activeRows()) {
18097
+ const grant = capabilities.grant(capabilities.current(found.token_id));
18098
+ const expired = found.expires_at !== null && Date.parse(found.expires_at) <= options.now();
18099
+ if (expired || !grant?.live) await serial(() => stop(found.id, expired ? "expired" : "revoked"));
18100
+ else if (found.via === "cloudflare") await serial(() => stop(found.id, "restart"));
18101
+ else pending.push(restore(found));
18102
+ }
18103
+ await Promise.all(pending);
18104
+ },
18105
+ async close() {
18106
+ closed = true;
18107
+ clearInterval(sweeper);
18108
+ for (const timer of timers.values()) clearTimeout(timer);
18109
+ timers.clear();
18110
+ const running = [...exposures.values()];
18111
+ exposures.clear();
18112
+ await Promise.all(running.map((exposure) => exposure.tunnel.stop()));
18113
+ }
16007
18114
  };
16008
18115
  }
18116
+ /** The variables that name the tools outright, passed to the lookup from the instance's own. */
18117
+ function pick(env) {
18118
+ const out = {};
18119
+ if (env["MOSTRA_TEST_TUNNELS"]) {
18120
+ for (const [name, value] of Object.entries(env)) if ((name === "MOSTRA_TEST_TUNNELS" || name.startsWith("MOSTRA_FAKE_")) && value !== void 0) out[name] = value;
18121
+ }
18122
+ for (const name of [
18123
+ "MOSTRA_TAILSCALE",
18124
+ "MOSTRA_CLOUDFLARED",
18125
+ "PATH",
18126
+ "Path",
18127
+ "ProgramFiles",
18128
+ "ProgramFiles(x86)"
18129
+ ]) {
18130
+ const value = env[name];
18131
+ if (value !== void 0) out[name] = value;
18132
+ }
18133
+ return out;
18134
+ }
18135
+ /** The directory of a home's share files (the quick tunnel's empty configuration). */
18136
+ function shareCacheDir(home) {
18137
+ return join(home, "cache", "share");
18138
+ }
16009
18139
  //#endregion
16010
18140
  //#region src/instance/index.ts
16011
18141
  /**
@@ -16047,8 +18177,11 @@ const SUPPORTED_PORTS = [
16047
18177
  "submissions",
16048
18178
  "drafts",
16049
18179
  "trustedControls",
16050
- "secrets"
18180
+ "secrets",
18181
+ "addressing"
16051
18182
  ];
18183
+ /** How long a host's `addressing` port has to answer: a page or a minted link waits (D158). */
18184
+ const ADDRESSING_TIMEOUT_MS = 5e3;
16052
18185
  /**
16053
18186
  * Starts an instance for a home (RT-06): the platform gate, then the home's lock, migrations,
16054
18187
  * reaping, the socket and `instance.json`. A daemon starter that finds the home owned attaches
@@ -16239,7 +18372,8 @@ async function assemble(home, options) {
16239
18372
  log,
16240
18373
  key: capabilityKey(home.path, log),
16241
18374
  now: () => Date.now() + clockOffset,
16242
- shellOrigin: () => gateway.shellOrigin()
18375
+ shellOrigin: () => gateway.shellOrigin(),
18376
+ servesShell: (origin) => gateway.servesShell(origin)
16243
18377
  });
16244
18378
  const interaction = createInteraction({
16245
18379
  ledger: home.ledger,
@@ -16398,6 +18532,7 @@ async function assemble(home, options) {
16398
18532
  if (shellDir === void 0) log.warn("gateway.shell_missing", { code: "MOSTRA_ENV_SHELL_MISSING" });
16399
18533
  const traceRequests = Boolean(environment["MOSTRA_TEST_REQUEST_LOG"]);
16400
18534
  if (traceRequests) log.warn("instance.test_request_log", {});
18535
+ if (environment["MOSTRA_TEST_TUNNELS"]) log.warn("instance.test_tunnels", {});
16401
18536
  const gateway = createGateway({
16402
18537
  ledger: home.ledger,
16403
18538
  log,
@@ -16434,6 +18569,36 @@ async function assemble(home, options) {
16434
18569
  registrant: () => server.registrants("identity").at(-1),
16435
18570
  call: (session, params) => server.callSession(session, portIdentityResolveMethod.method, params, IDENTITY_TIMEOUT_MS)
16436
18571
  }),
18572
+ externalBase: {
18573
+ registered: () => server.registrants("addressing").length > 0,
18574
+ ask: async (input) => {
18575
+ const registrant = server.registrants("addressing").at(-1);
18576
+ if (!registrant) return { kind: "away" };
18577
+ try {
18578
+ const answer = await server.callSession(registrant.session, portAddressingExternalBaseMethod.method, input, ADDRESSING_TIMEOUT_MS);
18579
+ const parsed = portAddressingExternalBaseMethod.result.safeParse(answer);
18580
+ if (!parsed.success) {
18581
+ log.warn("gateway.addressing_invalid", {
18582
+ owner: registrant.owner,
18583
+ artifactId: input.artifactId
18584
+ });
18585
+ return { kind: "failed" };
18586
+ }
18587
+ return parsed.data === null ? { kind: "none" } : {
18588
+ kind: "base",
18589
+ base: parsed.data,
18590
+ owner: registrant.owner
18591
+ };
18592
+ } catch (error) {
18593
+ log.warn("gateway.addressing_failed", {
18594
+ owner: registrant.owner,
18595
+ artifactId: input.artifactId,
18596
+ error: error.message
18597
+ });
18598
+ return { kind: "failed" };
18599
+ }
18600
+ }
18601
+ },
16437
18602
  activated: (event) => {
16438
18603
  for (const registrant of server.registrants("trustedControls")) {
16439
18604
  const params = {
@@ -16450,6 +18615,21 @@ async function assemble(home, options) {
16450
18615
  }
16451
18616
  }
16452
18617
  });
18618
+ const shares = createShares({
18619
+ ledger: home.ledger,
18620
+ log,
18621
+ gateway,
18622
+ capabilities,
18623
+ interaction,
18624
+ artifacts: { get: (ref) => registry.get(canonicalRef(ref)) },
18625
+ processes: manager,
18626
+ environment,
18627
+ toolEnvironment: artifactEnvironment(environment),
18628
+ cacheDir: shareCacheDir(home.path),
18629
+ now: () => Date.now() + clockOffset,
18630
+ ...environment["MOSTRA_TEST_SHARE_PROBE_MS"] !== void 0 ? { probeMs: Number(environment["MOSTRA_TEST_SHARE_PROBE_MS"]) } : {},
18631
+ ...environment["MOSTRA_TEST_SHARE_SWEEP_MS"] !== void 0 ? { sweepMs: Number(environment["MOSTRA_TEST_SHARE_SWEEP_MS"]) } : {}
18632
+ });
16453
18633
  let gatewayStarted = false;
16454
18634
  let idle;
16455
18635
  const info = {
@@ -16530,6 +18710,7 @@ async function assemble(home, options) {
16530
18710
  }),
16531
18711
  ...dev.methods(),
16532
18712
  ...gateway.methods(),
18713
+ ...shares.methods(),
16533
18714
  ...interaction.methods(),
16534
18715
  ...secretMethods(secrets, (ref) => registry.get(canonicalRef(ref)).id),
16535
18716
  ...gcMethods(createGc({
@@ -16556,8 +18737,10 @@ async function assemble(home, options) {
16556
18737
  artifacts: [...gateway.artifactOrigins()].map(([artifactId, origin]) => ({
16557
18738
  artifactId,
16558
18739
  origin
16559
- }))
18740
+ })),
18741
+ faces: [...gateway.faces()]
16560
18742
  } : void 0,
18743
+ shares: () => shares.active(),
16561
18744
  deliveries: () => interaction.deliveries(),
16562
18745
  workers: () => pool.status(),
16563
18746
  idleExitAt: () => idle?.exitAt(),
@@ -16593,6 +18776,7 @@ async function assemble(home, options) {
16593
18776
  interaction.stop();
16594
18777
  await server.close();
16595
18778
  await dev.stopAll();
18779
+ await shares.close();
16596
18780
  await gateway.close();
16597
18781
  await pool.stopAll();
16598
18782
  await runner?.close();
@@ -16650,6 +18834,7 @@ async function assemble(home, options) {
16650
18834
  });
16651
18835
  interaction.start();
16652
18836
  live.start();
18837
+ shares.recover().catch((error) => log.error("share.recover_failed", { error }));
16653
18838
  home.publish(options.mode, server.socketPath ?? home.socketPath);
16654
18839
  if (options.mode === "host" && markHostConfigured(home.path, "mostra-runtime host")) log.info("home.host_configured", { client: "mostra-runtime host" });
16655
18840
  } catch (error) {
@@ -16675,6 +18860,7 @@ async function assemble(home, options) {
16675
18860
  producers: live.activity(),
16676
18861
  subscriptions: interaction.subscriptionCount(),
16677
18862
  devSessions: dev.count(),
18863
+ shares: shares.count(),
16678
18864
  loginService: hasLoginService(home.path, environment) ? 1 : 0
16679
18865
  }),
16680
18866
  onIdle: () => {
@@ -16747,4 +18933,4 @@ function sourceDirectory(path) {
16747
18933
  //#endregion
16748
18934
  export { uninstallService as a, serviceStatus as i, startInstance as n, checkPlatform as o, installService as r, resolveHomePath as s, runtimeVersion as t };
16749
18935
 
16750
- //# sourceMappingURL=instance-DpD340-W.js.map
18936
+ //# sourceMappingURL=instance-BRfg27Rg.js.map