@mostra/runtime 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/bin.js +2879 -8
  2. package/dist/bin.js.map +1 -1
  3. package/dist/builder/child/main.js +2 -2
  4. package/dist/{child-Chiavhdx.js → child-BmNZ4a70.js} +2 -2
  5. package/dist/{child-Chiavhdx.js.map → child-BmNZ4a70.js.map} +1 -1
  6. package/dist/deps/child/install.js +1 -1
  7. package/dist/{directories-mJ1qlVht.js → directories-BLJjeSPD.js} +5 -5
  8. package/dist/directories-BLJjeSPD.js.map +1 -0
  9. package/dist/{files-FygSJIzK.js → files-DGeWuE4I.js} +2 -2
  10. package/dist/{files-FygSJIzK.js.map → files-DGeWuE4I.js.map} +1 -1
  11. package/dist/index.d.ts +2 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +2 -2
  14. package/dist/{instance-EnaZPs14.js → instance-FExcyENK.js} +3341 -396
  15. package/dist/instance-FExcyENK.js.map +1 -0
  16. package/package.json +7 -5
  17. package/src/actions/index.ts +163 -10
  18. package/src/bin.ts +78 -1
  19. package/src/gateway/actions.ts +20 -4
  20. package/src/gateway/browser.ts +118 -95
  21. package/src/gateway/capabilities.ts +15 -6
  22. package/src/gateway/index.ts +112 -15
  23. package/src/gateway/routes.ts +15 -7
  24. package/src/gc/index.ts +14 -0
  25. package/src/instance/index.ts +41 -2
  26. package/src/interaction/ephemeral.ts +32 -23
  27. package/src/interaction/events.ts +21 -1
  28. package/src/interaction/imports.ts +317 -0
  29. package/src/interaction/index.ts +172 -19
  30. package/src/interaction/outbox.ts +9 -0
  31. package/src/interaction/results.ts +8 -1
  32. package/src/interaction/runs.ts +52 -2
  33. package/src/interaction/submissions.ts +17 -1
  34. package/src/interaction/tally.ts +129 -0
  35. package/src/ledger/index.ts +104 -9
  36. package/src/ledger/migrations.ts +183 -0
  37. package/src/ledger/types.ts +8 -0
  38. package/src/link/binding.ts +289 -0
  39. package/src/link/hosted.ts +65 -0
  40. package/src/link/http.ts +136 -0
  41. package/src/link/index.ts +8 -0
  42. package/src/link/manager.ts +1385 -0
  43. package/src/link/relay.ts +512 -0
  44. package/src/live/index.ts +112 -2
  45. package/src/platform/filesystems.ts +78 -0
  46. package/src/platform/index.ts +1 -0
  47. package/src/protocol-server/index.ts +18 -1
  48. package/src/protocol-server/server.ts +38 -7
  49. package/src/protocol-server/websocket.ts +161 -0
  50. package/src/publish/bundle.ts +398 -0
  51. package/src/publish/manifest.ts +9 -0
  52. package/src/publish/methods.ts +12 -1
  53. package/src/publish/publisher.ts +127 -0
  54. package/src/registry/index.ts +35 -14
  55. package/src/server/api.ts +439 -0
  56. package/src/server/auth.ts +613 -0
  57. package/src/server/config.ts +221 -0
  58. package/src/server/data.ts +369 -0
  59. package/src/server/directory.ts +141 -0
  60. package/src/server/hosted.ts +822 -0
  61. package/src/server/index.ts +368 -0
  62. package/src/server/relay.ts +1163 -0
  63. package/src/share/index.ts +110 -6
  64. package/dist/directories-mJ1qlVht.js.map +0 -1
  65. package/dist/instance-EnaZPs14.js.map +0 -1
@@ -96,6 +96,36 @@ export interface SharesOptions {
96
96
  readonly probeMs?: number;
97
97
  /** How often active shares are checked for an expired or revoked link (tests shorten it). */
98
98
  readonly sweepMs?: number;
99
+ /**
100
+ * Shares to a remote server (`via: "remote"`, D165, INTERFACES §18.2): the owner's link hosts
101
+ * the artifact and mints the link on its hosted home. Absent, `remote` shares are refused.
102
+ */
103
+ readonly remote?: RemoteShares;
104
+ }
105
+
106
+ /** What a `remote` share needs of the owner's link to a server (INTERFACES §18.2). */
107
+ export interface RemoteShares {
108
+ /**
109
+ * Pushes the artifact's latest version to the server (`server`, else the default) and mints a
110
+ * link on its hosted home, keeping the link's secret where only this home can read it.
111
+ */
112
+ mint(input: {
113
+ readonly artifactId: string;
114
+ readonly server?: string | undefined;
115
+ readonly scopes?: ShareStartParams["scopes"];
116
+ readonly ttl?: ShareStartParams["ttl"];
117
+ readonly viewer?: ShareStartParams["viewer"];
118
+ }): Promise<{
119
+ readonly server: string;
120
+ readonly url: string;
121
+ readonly tokenId: string;
122
+ readonly hostname: string;
123
+ readonly expiresAt?: string | undefined;
124
+ }>;
125
+ /** A minted link again, from what this home kept; `undefined` once it can't be. */
126
+ url(server: string, tokenId: string): string | undefined;
127
+ /** Revokes a link on the server's hosted home; fails with `MOSTRA_REMOTE_UNREACHABLE`. */
128
+ revoke(server: string, tokenId: string): Promise<void>;
99
129
  }
100
130
 
101
131
  /** The shares of one instance. */
@@ -136,6 +166,8 @@ interface PlannedFace {
136
166
 
137
167
  interface Plan {
138
168
  readonly faces: readonly PlannedFace[];
169
+ /** A `remote` share's server: it has no faces of its own (its pages are the server's). */
170
+ readonly server?: string;
139
171
  }
140
172
 
141
173
  /** A running tunnel and the shares that use it. */
@@ -172,9 +204,16 @@ export function createShares(options: SharesOptions): Shares {
172
204
  ledger.read((db) => db.get<ShareRow>("SELECT * FROM share WHERE id = ?", shareId));
173
205
 
174
206
  const toShare = (found: ShareRow): Share => {
175
- // A share follows its link through rotations (`view/rotate`): its token now.
176
- const tokenId = capabilities.current(found.token_id);
177
- const url = found.stopped_at === null ? gateway.reveal(tokenId) : undefined;
207
+ const server = (JSON.parse(found.plan_json) as Plan).server;
208
+ // A share follows its link through rotations (`view/rotate`): its token now. A remote share's
209
+ // link is its hosted home's.
210
+ const tokenId = server === undefined ? capabilities.current(found.token_id) : found.token_id;
211
+ const url =
212
+ found.stopped_at !== null
213
+ ? undefined
214
+ : server === undefined
215
+ ? gateway.reveal(tokenId)
216
+ : options.remote?.url(server, tokenId);
178
217
  const artifactKey = (JSON.parse(found.plan_json) as Plan).faces.find(
179
218
  (face) => face.listener === "artifact",
180
219
  )?.key;
@@ -520,6 +559,53 @@ export function createShares(options: SharesOptions): Shares {
520
559
  }
521
560
  };
522
561
 
562
+ /** A share to a remote server: hosted there, its link minted there (INTERFACES §18.2). */
563
+ const startRemote = async (
564
+ params: ShareStartParams,
565
+ detail: { readonly id: string },
566
+ key: ReturnType<typeof requestKey>,
567
+ ): Promise<ShareStartResult> => {
568
+ const remote = options.remote;
569
+ if (!remote) {
570
+ throw new RpcError(
571
+ createDiagnostic("MOSTRA_HOST_INVALID_PARAMS", {
572
+ message: "This instance shares to no remote server.",
573
+ }),
574
+ -32602,
575
+ );
576
+ }
577
+ const minted = await remote.mint({
578
+ artifactId: detail.id,
579
+ server: params.server,
580
+ scopes: params.scopes,
581
+ ttl: params.ttl,
582
+ viewer: params.viewer,
583
+ });
584
+ const shareId = ShareId.create();
585
+ const startedAt = options.now();
586
+ ledger.write((db) => {
587
+ db.run(
588
+ "INSERT INTO share (id, artifact_id, via, hostname, token_id, mode, plan_json, started_at, expires_at, stopped_at, stop_reason) VALUES (?, ?, 'remote', ?, ?, 'worker', ?, ?, ?, NULL, NULL)",
589
+ shareId,
590
+ detail.id,
591
+ minted.hostname,
592
+ minted.tokenId,
593
+ JSON.stringify({ faces: [], server: minted.server } satisfies Plan),
594
+ iso(startedAt),
595
+ minted.expiresAt ?? null,
596
+ );
597
+ appendEvent(db, {
598
+ artifactId: detail.id,
599
+ type: "share.started",
600
+ payload: { shareId, via: "remote", hostname: minted.hostname, server: minted.server },
601
+ });
602
+ if (key !== undefined) recordResult(db, key, { shareId });
603
+ });
604
+ schedule(shareId, minted.expiresAt);
605
+ log.info("share.started", { shareId, artifactId: detail.id, via: "remote" });
606
+ return { ...toShare(row(shareId) as ShareRow), url: minted.url };
607
+ };
608
+
523
609
  const start = async (params: ShareStartParams): Promise<ShareStartResult> => {
524
610
  const detail = options.artifacts.get(params.artifact);
525
611
  if (!detail.latestVersion && detail.versions.length === 0) {
@@ -535,6 +621,7 @@ export function createShares(options: SharesOptions): Shares {
535
621
  const found = replay ? row(replay.shareId) : undefined;
536
622
  if (found) return withUrl(toShare(found));
537
623
  }
624
+ if (params.via === "remote") return startRemote(params, detail, key);
538
625
  const ttlMs = lifetime(params.via, params.ttl);
539
626
  const shareId = ShareId.create();
540
627
  const { shell, artifact, plan, hostname } = await setUp(
@@ -616,6 +703,12 @@ export function createShares(options: SharesOptions): Shares {
616
703
  const stop = async (shareId: string, reason: string): Promise<Share | undefined> => {
617
704
  const found = row(shareId);
618
705
  if (!found || found.stopped_at !== null) return undefined;
706
+ const server = (JSON.parse(found.plan_json) as Plan).server;
707
+ // A remote share's link lives on its hosted home: revoked there first, so a share listed as
708
+ // stopped never leaves a live link behind (`MOSTRA_REMOTE_UNREACHABLE` keeps it active).
709
+ if (server !== undefined && reason !== "expired" && reason !== "revoked") {
710
+ await options.remote?.revoke(server, found.token_id);
711
+ }
619
712
  const at = options.now();
620
713
  ledger.write((db: LedgerDb) => {
621
714
  db.run(
@@ -624,7 +717,7 @@ export function createShares(options: SharesOptions): Shares {
624
717
  reason,
625
718
  shareId,
626
719
  );
627
- if (reason !== "expired" && reason !== "revoked") {
720
+ if (server === undefined && reason !== "expired" && reason !== "revoked") {
628
721
  capabilities.revoke(capabilities.current(found.token_id), db);
629
722
  }
630
723
  appendEvent(db, {
@@ -645,9 +738,14 @@ export function createShares(options: SharesOptions): Shares {
645
738
  /** Ends shares whose link expired or was revoked since (`view/revoke` of a share's link). */
646
739
  const sweep = async (): Promise<void> => {
647
740
  for (const found of activeRows()) {
741
+ const expired = found.expires_at !== null && Date.parse(found.expires_at) <= options.now();
742
+ // A remote share's link is its hosted home's: only its lifetime is known here.
743
+ if (found.via === "remote") {
744
+ if (expired) await serial(() => stop(found.id, "expired"));
745
+ continue;
746
+ }
648
747
  const grant = capabilities.grant(capabilities.current(found.token_id));
649
748
  if (grant?.live) continue;
650
- const expired = found.expires_at !== null && Date.parse(found.expires_at) <= options.now();
651
749
  await serial(() => stop(found.id, expired ? "expired" : "revoked"));
652
750
  }
653
751
  };
@@ -764,8 +862,14 @@ export function createShares(options: SharesOptions): Shares {
764
862
  async recover() {
765
863
  const pending: Promise<void>[] = [];
766
864
  for (const found of activeRows()) {
767
- const grant = capabilities.grant(capabilities.current(found.token_id));
768
865
  const expired = found.expires_at !== null && Date.parse(found.expires_at) <= options.now();
866
+ // A remote share needs nothing set up again: its pages are the server's.
867
+ if (found.via === "remote") {
868
+ if (expired) await serial(() => stop(found.id, "expired"));
869
+ else schedule(found.id, found.expires_at ?? undefined);
870
+ continue;
871
+ }
872
+ const grant = capabilities.grant(capabilities.current(found.token_id));
769
873
  if (expired || !grant?.live) {
770
874
  await serial(() => stop(found.id, expired ? "expired" : "revoked"));
771
875
  } else if (found.via === "cloudflare") {
@@ -1 +0,0 @@
1
- {"version":3,"file":"directories-mJ1qlVht.js","names":["BUNDLE_NAME"],"sources":["../src/platform/helper.ts","../src/platform/directories.ts"],"sourcesContent":["/**\n * Running `mostra-win`, the Windows platform helper (`crates/mostra-win`, WP-W1): finding it and\n * reading its one-line JSON answers. The runtime asks it for what Node.js can't do on Windows:\n * owner-only access control, process identity by creation time, the child gate and reaping, and\n * the owner-only control pipe. Only this module's Windows code calls it.\n */\nimport { execFileSync, spawn } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\n\n/** The name `bundle.json` gives a runtime bundle (D142). */\nconst BUNDLE_NAME = \"mostra-runtime-bundle\";\n\n/** The directory of `@mostra/runtime`'s `package.json`, wherever the code runs from. */\nexport function runtimeRoot(): string {\n let dir = dirname(fileURLToPath(import.meta.url));\n for (;;) {\n const manifest = join(dir, \"package.json\");\n if (existsSync(manifest)) {\n const { name } = JSON.parse(readFileSync(manifest, \"utf8\")) as { name?: string };\n if (name === \"@mostra/runtime\") return dir;\n }\n const parent = dirname(dir);\n if (parent === dir) throw new Error(\"Couldn't find @mostra/runtime's package.json.\");\n dir = parent;\n }\n}\n\n/** The runtime bundle the runtime sits in (four levels above its package), if any. */\nfunction enclosingBundle(root: string): string | undefined {\n const bundle = resolve(root, \"..\", \"..\", \"..\", \"..\");\n try {\n const info = JSON.parse(readFileSync(join(bundle, \"bundle.json\"), \"utf8\")) as {\n name?: unknown;\n };\n return info.name === BUNDLE_NAME ? bundle : undefined;\n } catch {\n return undefined;\n }\n}\n\nlet located: string | undefined;\n\n/**\n * The helper's path: `MOSTRA_WIN_HELPER`; else the runtime bundle's `bin/mostra-win.exe`; else,\n * in a development checkout, the one Cargo built (`target/release`, then `target/debug`). Throws\n * `MOSTRA_ENV_HELPER_MISSING` when none exists.\n */\nexport function helperPath(env: NodeJS.ProcessEnv = process.env): string {\n const override = env[\"MOSTRA_WIN_HELPER\"];\n if (override) {\n if (!existsSync(override))\n throw missing(`MOSTRA_WIN_HELPER names ${override}, which doesn't exist.`);\n return override;\n }\n if (located !== undefined) return located;\n const root = runtimeRoot();\n const bundle = enclosingBundle(root);\n const candidates =\n bundle !== undefined\n ? [join(bundle, \"bin\", \"mostra-win.exe\")]\n : [\"release\", \"debug\"].map((profile) =>\n resolve(root, \"..\", \"..\", \"target\", profile, \"mostra-win.exe\"),\n );\n const found = candidates.find((candidate) => existsSync(candidate));\n if (found === undefined) {\n throw missing(`Mostra's Windows helper isn't installed; looked for ${candidates.join(\", \")}.`);\n }\n located = found;\n return found;\n}\n\nfunction missing(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_ENV_HELPER_MISSING\", { message }));\n}\n\n/** What the helper answers. */\ntype Answer<T> =\n | { readonly ok: true; readonly result: T }\n | { readonly ok: false; readonly error: { readonly message: string; readonly os?: number } };\n\n/** A failure the helper reported, with the Windows error code when there is one. */\nexport class HelperError extends Error {\n readonly os: number | undefined;\n constructor(command: string, message: string, os: number | undefined) {\n super(`mostra-win ${command}: ${message}`);\n this.os = os;\n }\n}\n\nfunction parse<T>(command: string, stdout: string): T {\n const line = stdout.trim().split(\"\\n\").at(-1) ?? \"\";\n let answer: Answer<T>;\n try {\n answer = JSON.parse(line) as Answer<T>;\n } catch {\n throw new HelperError(\n command,\n `answered something that isn't JSON: ${line.slice(0, 200)}`,\n undefined,\n );\n }\n if (!answer.ok)\n throw new HelperError(command, answer.error.message, answer.error.os ?? undefined);\n return answer.result;\n}\n\n/** Runs a helper command and returns its result; for the calls that must finish before going on. */\nexport function runHelper<T>(args: readonly string[]): T {\n const helper = helperPath();\n let stdout: string;\n try {\n stdout = execFileSync(helper, args, {\n encoding: \"utf8\",\n windowsHide: true,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n } catch (error) {\n const failed = error as { stdout?: string; message: string };\n if (failed.stdout) return parse<T>(args[0] ?? \"\", failed.stdout);\n throw new HelperError(args[0] ?? \"\", failed.message, undefined);\n }\n return parse<T>(args[0] ?? \"\", stdout);\n}\n\n/** Runs a helper command without blocking the event loop. */\nexport function runHelperAsync<T>(args: readonly string[]): Promise<T> {\n const helper = helperPath();\n return new Promise((resolvePromise, reject) => {\n const child = spawn(helper, args, { windowsHide: true, stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n let stdout = \"\";\n let stderr = \"\";\n child.stdout.setEncoding(\"utf8\");\n child.stderr.setEncoding(\"utf8\");\n child.stdout.on(\"data\", (chunk: string) => {\n stdout += chunk;\n });\n child.stderr.on(\"data\", (chunk: string) => {\n stderr += chunk;\n });\n child.once(\"error\", reject);\n child.once(\"close\", () => {\n try {\n resolvePromise(parse<T>(args[0] ?? \"\", stdout || stderr));\n } catch (error) {\n reject(error);\n }\n });\n });\n}\n\n/**\n * The login service's launcher on Windows, `mostra-win-service.exe` beside the helper (D151): a\n * program without a console that Task Scheduler runs at logon to keep the home's daemon running\n * without a window. Throws `MOSTRA_ENV_HELPER_MISSING` when it isn't there.\n */\nexport function serviceLauncherPath(env: NodeJS.ProcessEnv = process.env): string {\n const launcher = join(dirname(helperPath(env)), \"mostra-win-service.exe\");\n if (!existsSync(launcher)) {\n throw missing(`Mostra's Windows service launcher isn't installed; looked for ${launcher}.`);\n }\n return launcher;\n}\n\n/** This process's user as a SID string (`S-1-5-21-…`), from the helper's `whoami`. */\nexport function currentUserSid(): string {\n return runHelper<{ user: string }>([\"whoami\"]).user;\n}\n\n/**\n * Asks the login service's launcher waiting on `event` to stop its daemon cleanly, and waits for\n * it (at most the helper's 20 s): `stopped` is false when it still runs after that.\n */\nexport function stopServiceLauncher(event: string): { signalled: boolean; stopped: boolean } {\n return runHelper<{ signalled: boolean; stopped: boolean }>([\"service-stop\", event]);\n}\n","/**\n * Where a home and its control endpoint live on each operating system, and how a directory is\n * made owner-only (DATA_MODEL §1; D82, D84, D85; RT-10). Resolving a path never touches the file\n * system; `ownedDirectory` creates or checks one.\n *\n * - macOS: the home defaults to `~/.mostra`, the runtime directory to `~/.mostra/run`.\n * - Linux: `${XDG_DATA_HOME:-~/.local/share}/mostra`; `$XDG_RUNTIME_DIR/mostra` when that\n * directory is the user's and private, else `${XDG_STATE_HOME:-~/.local/state}/mostra/run`.\n * - Windows: `%LOCALAPPDATA%\\mostra`. The control endpoint is a named pipe, which lives in no\n * directory, so there is no runtime directory and `MOSTRA_RUNTIME_DIR` doesn't apply.\n *\n * Owner-only means mode 0700 on POSIX, and on Windows a protected access list that grants only the\n * user and `SYSTEM`, inherited by everything inside (the helper's `secure-dir`).\n */\nimport { chmodSync, mkdirSync, realpathSync, statSync } from \"node:fs\";\nimport { posix, win32 } from \"node:path\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport { runHelper } from \"./helper.ts\";\n\n/** The operating systems the runtime knows. */\nexport type OperatingSystem = \"darwin\" | \"linux\" | \"win32\" | (string & {});\n\n/** The operating system this process runs on. Every other module asks here. */\nexport const OS: OperatingSystem = process.platform;\n\n/** Whether this process runs on Windows. */\nexport const WINDOWS: boolean = OS === \"win32\";\n\ntype Environment = Readonly<Record<string, string | undefined>>;\n\nconst nonEmpty = (value: string | undefined): string | undefined =>\n value === undefined || value === \"\" ? undefined : value;\n\n/** The path rules of an operating system, so resolution for another one can be computed and tested. */\nexport function pathsOf(os: OperatingSystem): typeof posix {\n return os === \"win32\" ? win32 : posix;\n}\n\n/** The home a platform uses when neither `--home` nor `MOSTRA_HOME` names one. */\nexport function defaultHome(os: OperatingSystem, env: Environment, userHome: string): string {\n if (os === \"darwin\") return posix.join(userHome, \".mostra\");\n if (os === \"win32\") {\n const local = nonEmpty(env[\"LOCALAPPDATA\"]);\n return win32.join(\n local !== undefined && win32.isAbsolute(local)\n ? local\n : win32.join(userHome, \"AppData\", \"Local\"),\n \"mostra\",\n );\n }\n const data = nonEmpty(env[\"XDG_DATA_HOME\"]);\n return posix.join(\n data !== undefined && posix.isAbsolute(data) ? data : posix.join(userHome, \".local\", \"share\"),\n \"mostra\",\n );\n}\n\n/** What the runtime directory resolution decided, and why. */\nexport interface RuntimeDirChoice {\n readonly dir: string;\n /** `override` (MOSTRA_RUNTIME_DIR), `xdg` (the safe XDG runtime directory) or `fallback`. */\n readonly source: \"override\" | \"xdg\" | \"fallback\";\n /** Why `$XDG_RUNTIME_DIR` wasn't used, when it was set. */\n readonly rejected?: string;\n}\n\n/**\n * The runtime directory for control sockets (D82), or `undefined` on Windows, whose control pipe\n * lives in the system's pipe namespace.\n */\nexport function runtimeDirFor(inputs: {\n readonly os: OperatingSystem;\n readonly env: Environment;\n readonly userHome: string;\n readonly cwd: string;\n}): RuntimeDirChoice | undefined {\n if (inputs.os === \"win32\") return undefined;\n const override = nonEmpty(inputs.env[\"MOSTRA_RUNTIME_DIR\"]);\n if (override !== undefined)\n return { dir: posix.resolve(inputs.cwd, override), source: \"override\" };\n if (inputs.os === \"darwin\")\n return { dir: posix.join(inputs.userHome, \".mostra\", \"run\"), source: \"fallback\" };\n const xdg = nonEmpty(inputs.env[\"XDG_RUNTIME_DIR\"]);\n let rejected: string | undefined;\n if (xdg !== undefined) {\n rejected = unsafeXdgRuntimeDir(xdg);\n if (rejected === undefined) return { dir: posix.join(xdg, \"mostra\"), source: \"xdg\" };\n }\n const state = nonEmpty(inputs.env[\"XDG_STATE_HOME\"]);\n const base =\n state !== undefined && posix.isAbsolute(state)\n ? state\n : posix.join(inputs.userHome, \".local\", \"state\");\n const dir = posix.join(base, \"mostra\", \"run\");\n return rejected === undefined\n ? { dir, source: \"fallback\" }\n : { dir, source: \"fallback\", rejected };\n}\n\n/** The current user's ID on POSIX. */\nfunction uid(): number {\n return process.getuid?.() ?? -1;\n}\n\n/** Why `$XDG_RUNTIME_DIR` can't be used, or `undefined` when it can (XDG Base Directory spec). */\nfunction unsafeXdgRuntimeDir(dir: string): string | undefined {\n if (!posix.isAbsolute(dir)) return \"it isn't an absolute path\";\n let stats: ReturnType<typeof statSync>;\n try {\n stats = statSync(dir);\n } catch {\n return \"it doesn't exist\";\n }\n if (!stats.isDirectory()) return \"it isn't a directory\";\n if (stats.uid !== uid()) return \"another user owns it\";\n if ((stats.mode & 0o077) !== 0) return \"other users can access it\";\n return undefined;\n}\n\n/** The longest control socket path the operating system accepts, in bytes (VERIFIED_FACTS). */\nexport function socketPathLimit(os: OperatingSystem): number {\n return os === \"darwin\" ? 103 : 107;\n}\n\n/** The outcome of {@link ownedDirectory}. */\nexport interface PreparedDirectory {\n /** The directory's real path. */\n readonly realPath: string;\n /** Whether Mostra created it. */\n readonly created: boolean;\n /**\n * What it allowed before Mostra made it owner-only, when it did: the octal mode on POSIX, the\n * security descriptor (SDDL) on Windows.\n */\n readonly tightenedFrom?: string;\n}\n\nfunction notOwned(path: string, why: string): RpcError {\n return new RpcError(\n createDiagnostic(\"MOSTRA_HOME_NOT_OWNED\", { message: `Mostra can't use ${path}: ${why}.` }),\n );\n}\n\n/**\n * Makes `path` a directory only its owner can use (D85): creates it owner-only when missing,\n * tightens one the user owns, and throws `MOSTRA_HOME_NOT_OWNED` for one owned by another user or\n * a path that isn't a directory. Symlinks are followed.\n */\nexport function ownedDirectory(path: string): PreparedDirectory {\n if (WINDOWS) return ownedDirectoryWindows(path);\n try {\n return preparePosix(path);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === \"ENOTDIR\" || code === \"EEXIST\")\n throw notOwned(path, \"a part of the path isn't a directory\");\n if (code === \"EACCES\" || code === \"EPERM\")\n throw notOwned(path, \"you have no permission to use it\");\n throw error;\n }\n}\n\nfunction preparePosix(path: string): PreparedDirectory {\n let created = false;\n try {\n statSync(path);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n mkdirSync(path, { recursive: true, mode: 0o700 });\n created = true;\n }\n const realPath = realpathSync(path);\n const stats = statSync(realPath);\n if (!stats.isDirectory()) throw notOwned(path, \"it isn't a directory\");\n if (stats.uid !== uid()) throw notOwned(path, `it belongs to user ${stats.uid}, not to you`);\n const mode = stats.mode & 0o777;\n if (mode !== 0o700) {\n chmodSync(realPath, 0o700);\n return created ? { realPath, created } : { realPath, created, tightenedFrom: mode.toString(8) };\n }\n return { realPath, created };\n}\n\ntype Secured =\n | { readonly secured: \"created\" | \"kept\" }\n | { readonly secured: \"tightened\"; readonly from: string }\n | { readonly refused: \"not-owned\"; readonly owner: string }\n | { readonly refused: \"not-directory\" };\n\nfunction ownedDirectoryWindows(path: string): PreparedDirectory {\n let answer: Secured;\n try {\n answer = runHelper<Secured>([\"secure-dir\", path]);\n } catch (error) {\n // Access denied while creating or reading it: someone else's directory, or one above it.\n if ((error as { os?: number }).os === 5)\n throw notOwned(path, \"you have no permission to use it\");\n throw error;\n }\n if (\"refused\" in answer) {\n throw notOwned(\n path,\n answer.refused === \"not-owned\"\n ? `it belongs to ${answer.owner}, not to you`\n : \"it isn't a directory\",\n );\n }\n const realPath = realpathSync.native(path);\n if (answer.secured === \"tightened\")\n return { realPath, created: false, tightenedFrom: answer.from };\n return { realPath, created: answer.secured === \"created\" };\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,MAAMA,gBAAc;;AAGpB,SAAgB,cAAsB;CACpC,IAAI,MAAM,QAAQ,cAAc,YAAY,GAAG,CAAC;CAChD,SAAS;EACP,MAAM,WAAW,KAAK,KAAK,cAAc;EACzC,IAAI,WAAW,QAAQ,GAAG;GACxB,MAAM,EAAE,SAAS,KAAK,MAAM,a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