@mostra/runtime 0.1.0 → 0.3.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 +7 -7
  2. package/dist/bin.js.map +1 -1
  3. package/dist/builder/child/main.js +18 -17
  4. package/dist/builder/child/main.js.map +1 -1
  5. package/dist/{child-xrHmytks.js → child-BQc3arf7.js} +5 -2
  6. package/dist/{child-xrHmytks.js.map → child-BQc3arf7.js.map} +1 -1
  7. package/dist/deps/child/install.js +9 -6
  8. package/dist/deps/child/install.js.map +1 -1
  9. package/dist/files-KxzOxckl.js +674 -0
  10. package/dist/files-KxzOxckl.js.map +1 -0
  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-D7_UVdoN.js → instance-DiKSe7s6.js} +1331 -752
  15. package/dist/instance-DiKSe7s6.js.map +1 -0
  16. package/package.json +5 -5
  17. package/src/bin.ts +4 -10
  18. package/src/builder/child/dev.ts +4 -3
  19. package/src/builder/child/plugins.ts +12 -7
  20. package/src/builder/child/spa.ts +15 -9
  21. package/src/builder/index.ts +3 -6
  22. package/src/deps/child/install.ts +3 -2
  23. package/src/deps/index.ts +21 -16
  24. package/src/deps/warm.ts +3 -16
  25. package/src/faults.ts +9 -2
  26. package/src/gateway/actions.ts +1 -1
  27. package/src/gateway/browser.ts +1 -1
  28. package/src/gateway/capabilities.ts +28 -7
  29. package/src/gateway/identity.ts +101 -0
  30. package/src/gateway/index.ts +96 -6
  31. package/src/home/acquire.ts +27 -11
  32. package/src/home/paths.ts +45 -135
  33. package/src/home/platform.ts +17 -9
  34. package/src/home/record.ts +3 -3
  35. package/src/home/settings.ts +5 -16
  36. package/src/instance/index.ts +73 -12
  37. package/src/interaction/index.ts +4 -0
  38. package/src/interaction/viewers.ts +16 -2
  39. package/src/ledger/index.ts +5 -27
  40. package/src/ledger/migrations.ts +13 -0
  41. package/src/platform/control.ts +409 -0
  42. package/src/platform/directories.ts +212 -0
  43. package/src/platform/environment.ts +64 -0
  44. package/src/platform/files.ts +368 -0
  45. package/src/platform/helper.ts +152 -0
  46. package/src/{processes → platform}/identity.ts +40 -8
  47. package/src/platform/index.ts +46 -0
  48. package/src/platform/launch.ts +373 -0
  49. package/src/processes/child.ts +4 -1
  50. package/src/processes/environment.ts +22 -3
  51. package/src/processes/index.ts +2 -1
  52. package/src/processes/manager.ts +76 -179
  53. package/src/protocol-server/client.ts +19 -18
  54. package/src/protocol-server/server.ts +84 -54
  55. package/src/publish/publisher.ts +16 -9
  56. package/src/publish/source.ts +7 -4
  57. package/src/registry/store.ts +7 -65
  58. package/src/secrets/index.ts +3 -3
  59. package/src/service/unit.ts +3 -2
  60. package/src/verify/index.ts +5 -3
  61. package/src/verify/typecheck.ts +3 -2
  62. package/src/workers/launcher.ts +3 -1
  63. package/dist/instance-D7_UVdoN.js.map +0 -1
  64. package/dist/types-NjNy7gXX.js +0 -57
  65. package/dist/types-NjNy7gXX.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mostra/runtime",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "The Mostra runtime: the supervisor that owns a home, its ledger, its child processes and the host protocol server (mostra-runtime host|daemon).",
5
5
  "license": "Apache-2.0",
6
6
  "author": "The Mostra Authors",
@@ -36,7 +36,7 @@
36
36
  "dependencies": {
37
37
  "@hono/node-server": "2.1.3",
38
38
  "@mdx-js/mdx": "3.1.1",
39
- "@mostra/protocol": "0.1.0",
39
+ "@mostra/protocol": "0.3.0",
40
40
  "@tailwindcss/vite": "4.3.3",
41
41
  "@vitejs/plugin-react": "6.1.1",
42
42
  "better-sqlite3": "13.0.3",
@@ -54,11 +54,11 @@
54
54
  "zod": "4.6.5"
55
55
  },
56
56
  "devDependencies": {
57
- "@mostra/shell": "0.1.0",
57
+ "@mostra/shell": "0.3.0",
58
58
  "@mostra/tools": "0.0.0",
59
- "@mostra/verify": "0.1.0",
59
+ "@mostra/verify": "0.3.0",
60
60
  "@mostra/warm": "0.0.0",
61
- "@mostra/worker": "0.1.0",
61
+ "@mostra/worker": "0.3.0",
62
62
  "@types/better-sqlite3": "9.6.0",
63
63
  "@types/node": "24.19.1",
64
64
  "@types/semver": "7.8.0",
package/src/bin.ts CHANGED
@@ -92,20 +92,14 @@ function refuseOverStdio(diagnostic: Diagnostic, exitCode: number): void {
92
92
  }
93
93
 
94
94
  function handleSignals(instance: Instance): void {
95
- for (const signal of ["SIGTERM", "SIGINT"] as const) {
95
+ // SIGTERM and SIGINT on POSIX; on Windows Ctrl+C and Ctrl+Break reach a console process as
96
+ // SIGINT and SIGBREAK, and everything else stops it over the protocol (`mostra/shutdown`, D87).
97
+ for (const signal of ["SIGTERM", "SIGINT", "SIGBREAK"] as const) {
96
98
  process.on(signal, () => void instance.stop(signal, EXIT.ok));
97
99
  }
98
100
  process.on("SIGPIPE", () => {});
99
101
  // Last resort: children never outlive an exiting supervisor (FAILURE_MODEL §2).
100
- process.on("exit", () => {
101
- for (const child of instance.processes.list()) {
102
- try {
103
- process.kill(-child.pid, "SIGKILL");
104
- } catch {
105
- // Already gone.
106
- }
107
- }
108
- });
102
+ process.on("exit", () => instance.processes.killAll());
109
103
  process.on("uncaughtException", (error) => {
110
104
  mirror(`${JSON.stringify({ level: "error", event: "uncaught", message: error.message })}\n`);
111
105
  void instance.stop("uncaught exception", EXIT.failure);
@@ -13,7 +13,7 @@
13
13
  * When `pages/`, `"use server"` modules or `live.ts` change, the generated entry is written again.
14
14
  */
15
15
  import { createHash, timingSafeEqual } from "node:crypto";
16
- import { mkdir, readdir, readFile, rm, symlink, writeFile } from "node:fs/promises";
16
+ import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
17
17
  import {
18
18
  createServer as createHttpServer,
19
19
  type IncomingMessage,
@@ -25,6 +25,7 @@ import tailwind from "@tailwindcss/vite";
25
25
  import react from "@vitejs/plugin-react";
26
26
  import { parseSync } from "oxc-parser";
27
27
  import { build, createServer, type Plugin, type ViteDevServer } from "vite";
28
+ import { linkDirectory, pathKey } from "../../platform/index.ts";
28
29
  import type { SupervisorConnection } from "../../processes/index.ts";
29
30
  import {
30
31
  DEV_SECRET_HEADER,
@@ -95,7 +96,7 @@ export async function startDev(
95
96
  await mkdir(generated, { recursive: true });
96
97
  for (const [name, text] of Object.entries(STAGING_FILES)) await writeFile(join(root, name), text);
97
98
  await rm(join(root, "node_modules"), { force: true, recursive: true });
98
- await symlink(request.nodeModules, join(root, "node_modules"), "dir");
99
+ await linkDirectory(request.nodeModules, join(root, "node_modules"));
99
100
  await writeFile(join(generated, "styles.css"), `@import "tailwindcss" source("../source");\n`);
100
101
  await mkdir(request.outDir, { recursive: true });
101
102
  // Vite's pre-bundled dependencies live in the session's root (`cacheDir` below); they are
@@ -114,7 +115,7 @@ export async function startDev(
114
115
  const refreshServerModules = (): void => {
115
116
  serverModules.clear();
116
117
  for (const [module, entries] of scan.serverModules)
117
- serverModules.set(join(sourceDir, module), entries);
118
+ serverModules.set(pathKey(join(sourceDir, module)), entries);
118
119
  };
119
120
  refreshServerModules();
120
121
  const writeEntry = async (): Promise<void> => {
@@ -10,6 +10,7 @@ import { compile } from "@mdx-js/mdx";
10
10
  import remarkFrontmatter from "remark-frontmatter";
11
11
  import remarkGfm from "remark-gfm";
12
12
  import type { Plugin } from "vite";
13
+ import { isUnder, pathKey } from "../../platform/index.ts";
13
14
  import type { ServerFunctionEntry } from "../types.ts";
14
15
  import { SCRIPT, startsWithUseServer } from "./scan.ts";
15
16
 
@@ -54,7 +55,7 @@ export function fieldHookUsePlugin(
54
55
  uses: FieldHookUse[],
55
56
  ): Plugin {
56
57
  const inside = (file: string, dir: string | undefined): boolean =>
57
- dir !== undefined && (file === dir || file.startsWith(`${dir}/`));
58
+ dir !== undefined && isUnder(file, dir);
58
59
  return {
59
60
  name: "mostra:field-hook-use",
60
61
  enforce: "pre",
@@ -68,7 +69,8 @@ export function fieldHookUsePlugin(
68
69
  inside(file, roots.runtimeDir)
69
70
  )
70
71
  return null;
71
- if (!uses.some((use) => use.importer === file)) uses.push({ importer: file });
72
+ if (!uses.some((use) => pathKey(use.importer) === pathKey(file)))
73
+ uses.push({ importer: file });
72
74
  return null;
73
75
  },
74
76
  };
@@ -92,7 +94,8 @@ const STUB_PREFIX = "\0mostra-server-reference:";
92
94
 
93
95
  /**
94
96
  * Replaces `"use server"` modules with their client stubs. `modules` maps each module's absolute
95
- * path to its exports, from the scan.
97
+ * path, as its {@link pathKey}, to its exports, from the scan: bundlers spell Windows paths with
98
+ * `/`, the file system with `\\`.
96
99
  */
97
100
  export function serverClientStubPlugin(
98
101
  modules: ReadonlyMap<string, readonly ServerFunctionEntry[]>,
@@ -107,7 +110,9 @@ export function serverClientStubPlugin(
107
110
  if (source.startsWith(STUB_PREFIX)) return source;
108
111
  const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });
109
112
  const file = resolved?.id.split("?")[0];
110
- return file !== undefined && modules.has(file) ? `${STUB_PREFIX}${file}.mjs` : null;
113
+ return file !== undefined && modules.has(pathKey(file))
114
+ ? `${STUB_PREFIX}${pathKey(file)}.mjs`
115
+ : null;
111
116
  },
112
117
  load(id) {
113
118
  if (!id.startsWith(STUB_PREFIX)) return null;
@@ -118,7 +123,7 @@ export function serverClientStubPlugin(
118
123
  // directive, but without a stub, would ship its server code to every viewer.
119
124
  transform(code, id) {
120
125
  const file = id.split("?")[0] ?? id;
121
- if (!file.startsWith(`${sourceDir}/`) || modules.has(file)) return null;
126
+ if (!isUnder(file, sourceDir) || modules.has(pathKey(file))) return null;
122
127
  if (!SCRIPT.has(extname(file))) return null;
123
128
  if (startsWithUseServer(file, code) !== true) return null;
124
129
  return this.error(
@@ -149,7 +154,7 @@ export interface BuildInputs {
149
154
  * later change to them would go unnoticed.
150
155
  */
151
156
  export function confinePlugin(inputs: BuildInputs): Plugin {
152
- const under = (file: string, dir: string): boolean => file.startsWith(`${dir}/`);
157
+ const under = (file: string, dir: string): boolean => isUnder(file, dir);
153
158
  const ours = (file: string): boolean =>
154
159
  under(file, inputs.sourceDir) || under(file, inputs.generatedDir);
155
160
  const packaged = (file: string): boolean => inputs.packageRoots.some((root) => under(file, root));
@@ -168,7 +173,7 @@ export function confinePlugin(inputs: BuildInputs): Plugin {
168
173
  if (from === undefined || source.startsWith("\0")) return null;
169
174
  const fromPackage = !ours(from);
170
175
  if (fromPackage && !packaged(from)) return null;
171
- const bare = !source.startsWith(".") && !source.startsWith("/");
176
+ const bare = !source.startsWith(".") && !source.startsWith("/") && !isAbsolute(source);
172
177
  const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });
173
178
  if (!resolved || resolved.external) return resolved;
174
179
  const id = resolved.id.split("?")[0] ?? resolved.id;
@@ -6,13 +6,14 @@
6
6
  * Nothing in the artifact runs.
7
7
  */
8
8
  import type { Dirent } from "node:fs";
9
- import { mkdir, readdir, realpath, rm, symlink, writeFile } from "node:fs/promises";
9
+ import { mkdir, readdir, realpath, rm, writeFile } from "node:fs/promises";
10
10
  import { join, relative } from "node:path";
11
11
  import { stripVTControlCharacters } from "node:util";
12
12
  import { createDiagnostic, type Diagnostic } from "@mostra/protocol";
13
13
  import tailwind from "@tailwindcss/vite";
14
14
  import react from "@vitejs/plugin-react";
15
15
  import { build, type InlineConfig, type PluginOption } from "vite";
16
+ import { isUnder, linkDirectory, pathKey } from "../../platform/index.ts";
16
17
  import type { FieldCoverage } from "../coverage.ts";
17
18
  import {
18
19
  type BuildRequest,
@@ -140,12 +141,16 @@ export function diagnose(error: unknown, sourceDir: string): Diagnostic {
140
141
  };
141
142
  const first = failure.errors?.[0] ?? failure;
142
143
  // Bundler messages carry terminal colours; diagnostics are plain text.
143
- const rawMessage = stripVTControlCharacters(first.message ?? String(error)).replaceAll(
144
- `${sourceDir}/`,
145
- "",
146
- );
144
+ // Paths in the message as the bundler spells them (`/`-separated on Windows too).
145
+ const rawMessage = stripVTControlCharacters(first.message ?? String(error))
146
+ .replaceAll(`${sourceDir}/`, "")
147
+ .replaceAll(`${sourceDir.replaceAll("\\", "/")}/`, "")
148
+ .replaceAll(`${sourceDir}\\`, "");
147
149
  const file = first.loc?.file ?? first.id;
148
- const inSource = file?.startsWith(sourceDir) ? relative(sourceDir, file) : undefined;
150
+ const inSource =
151
+ file !== undefined && isUnder(file, sourceDir)
152
+ ? relative(sourceDir, file).replaceAll("\\", "/")
153
+ : undefined;
149
154
  const location =
150
155
  inSource !== undefined
151
156
  ? { file: inSource, line: first.loc?.line ?? 1, column: (first.loc?.column ?? 0) + 1 }
@@ -216,7 +221,8 @@ export async function packageRoots(nodeModules: string): Promise<string[]> {
216
221
  } catch {
217
222
  continue; // A dangling link brings nothing in.
218
223
  }
219
- const store = dir.lastIndexOf("/.pnpm/");
224
+ // pnpm's store, found however the platform spells separators (the key keeps the length).
225
+ const store = pathKey(dir).lastIndexOf("/.pnpm/");
220
226
  const root = store === -1 ? dir : dir.slice(0, store + "/.pnpm".length);
221
227
  if (roots.has(root)) continue;
222
228
  roots.add(root);
@@ -257,7 +263,7 @@ export async function buildSpa(input: BuildRequest): Promise<BuildResponse> {
257
263
  packageRoots: await packageRoots(request.nodeModules),
258
264
  };
259
265
  await rm(join(request.stagingDir, "node_modules"), { force: true, recursive: true });
260
- await symlink(request.nodeModules, join(request.stagingDir, "node_modules"), "dir");
266
+ await linkDirectory(request.nodeModules, join(request.stagingDir, "node_modules"));
261
267
  await writeFile(
262
268
  join(request.stagingDir, "index.html"),
263
269
  html(request.manifest.title, request.versionId),
@@ -267,7 +273,7 @@ export async function buildSpa(input: BuildRequest): Promise<BuildResponse> {
267
273
  if (scan.hasLive) await writeFile(join(generated, "mostra-env.d.ts"), LIVE_DECLARATION);
268
274
 
269
275
  const serverModules = new Map<string, readonly ServerFunctionEntry[]>(
270
- [...scan.serverModules].map(([module, entries]) => [join(sourceDir, module), entries]),
276
+ [...scan.serverModules].map(([module, entries]) => [pathKey(join(sourceDir, module)), entries]),
271
277
  );
272
278
  // Packages that use the field hooks themselves open the version's coverage (D109).
273
279
  const hookUses: FieldHookUse[] = [];
@@ -48,6 +48,8 @@ export {
48
48
  type VersionRegistry,
49
49
  } from "./types.ts";
50
50
 
51
+ import { baseEnvironment } from "../platform/index.ts";
52
+
51
53
  /** How long one build may take (FAILURE_MODEL §9). */
52
54
  export const BUILD_TIMEOUT_MS = 180_000;
53
55
 
@@ -187,12 +189,7 @@ export function createSpaRenderMode(options: SpaRenderModeOptions): RenderMode {
187
189
  const timeoutMs = options.timeoutMs ?? BUILD_TIMEOUT_MS;
188
190
  const env = options.env ?? process.env;
189
191
  // The builder gets only what it needs: no secrets, nothing that could reach a bundle.
190
- const childEnv: Environment = {
191
- PATH: env["PATH"] ?? "/usr/bin:/bin",
192
- HOME: env["HOME"] ?? "/",
193
- NODE_ENV: "production",
194
- ...(env["TMPDIR"] ? { TMPDIR: env["TMPDIR"] } : {}),
195
- };
192
+ const childEnv: Environment = { ...baseEnvironment(env), NODE_ENV: "production" };
196
193
 
197
194
  return {
198
195
  id: "spa",
@@ -16,10 +16,11 @@ if (entry === undefined) {
16
16
  console.error("The install child needs the installer's entry as its first argument.");
17
17
  process.exit(2);
18
18
  }
19
- // Not detached: pnpm stays in this child's process group, which the supervisor and the disconnect
20
- // rule both end as a whole.
19
+ // Not detached: pnpm stays in this child's process group (on Windows its Job Object), which the
20
+ // supervisor and the disconnect rule both end as a whole. No console window opens on Windows.
21
21
  const installer = spawn(process.execPath, [entry, ...args], {
22
22
  stdio: ["ignore", "inherit", "inherit"],
23
+ windowsHide: true,
23
24
  });
24
25
  installer.on("error", (error) => {
25
26
  console.error(`The installer couldn't start: ${error.message}`);
package/src/deps/index.ts CHANGED
@@ -20,8 +20,8 @@
20
20
  * ```
21
21
  */
22
22
  import { randomBytes } from "node:crypto";
23
- import { existsSync, readlinkSync } from "node:fs";
24
- import { lstat, mkdir, readdir, readFile, rename, rm, symlink, writeFile } from "node:fs/promises";
23
+ import { existsSync } from "node:fs";
24
+ import { lstat, mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
25
25
  import { networkInterfaces } from "node:os";
26
26
  import { join } from "node:path";
27
27
  import {
@@ -43,6 +43,13 @@ import {
43
43
  recordResult,
44
44
  } from "../ledger/index.ts";
45
45
  import type { Environment, Log } from "../log.ts";
46
+ import {
47
+ linkDirectory,
48
+ linkTarget,
49
+ replaceDirectoryLink,
50
+ samePath,
51
+ WINDOWS,
52
+ } from "../platform/index.ts";
46
53
  import type { ProcessManager } from "../processes/index.ts";
47
54
  import { createInstaller, INSTALL_TIMEOUT_MS, type Installer } from "./installer.ts";
48
55
  import { type Lock, lockDigest, lockText, parseLock, pinnedPackages } from "./lock.ts";
@@ -223,8 +230,13 @@ export function isOffline(env: Environment): boolean {
223
230
  );
224
231
  }
225
232
 
226
- /** A shell-safe rendering of `value`, for the commands in diagnostics. */
233
+ /**
234
+ * A shell-safe rendering of `value`, for the commands in diagnostics: POSIX shell quoting, or on
235
+ * Windows the double quotes PowerShell and `cmd` both read (a Windows path holds no `"`), and a
236
+ * plain path with backslashes as it is.
237
+ */
227
238
  function shellQuote(value: string): string {
239
+ if (WINDOWS) return /^[\w@%+=:,./\\-]+$/.test(value) ? value : `"${value}"`;
228
240
  return /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
229
241
  }
230
242
 
@@ -369,7 +381,7 @@ export function createDependencies(options: DependenciesOptions): Dependencies {
369
381
  const work = join(dirs.tmp, `resolve-${randomBytes(6).toString("hex")}`);
370
382
  await mkdir(work);
371
383
  try {
372
- await symlink(warm.nodeModules, join(work, "warm"), "dir");
384
+ await linkDirectory(warm.nodeModules, join(work, "warm"));
373
385
  await writeFile(join(work, "package.json"), manifestOf(input.pins));
374
386
  if (input.previous !== undefined)
375
387
  await writeFile(join(work, "pnpm-lock.yaml"), input.previous);
@@ -412,16 +424,9 @@ export function createDependencies(options: DependenciesOptions): Dependencies {
412
424
  /** Points a layout's `warm` symlink at the current warm set (the runtime may have moved). */
413
425
  const relinkWarm = async (dir: string): Promise<void> => {
414
426
  const link = join(dir, "warm");
415
- let target: string | undefined;
416
- try {
417
- target = readlinkSync(link);
418
- } catch {
419
- target = undefined;
420
- }
421
- if (target === warm.nodeModules) return;
422
- const fresh = `${link}.${randomBytes(4).toString("hex")}`;
423
- await symlink(warm.nodeModules, fresh, "dir");
424
- await rename(fresh, link);
427
+ const target = await linkTarget(link);
428
+ if (target !== undefined && samePath(target, warm.nodeModules)) return;
429
+ await replaceDirectoryLink(warm.nodeModules, link);
425
430
  };
426
431
 
427
432
  /**
@@ -456,7 +461,7 @@ export function createDependencies(options: DependenciesOptions): Dependencies {
456
461
  await rm(dir, { recursive: true, force: true });
457
462
  await mkdir(dir, { recursive: true });
458
463
  try {
459
- await symlink(warm.nodeModules, join(dir, "warm"), "dir");
464
+ await linkDirectory(warm.nodeModules, join(dir, "warm"));
460
465
  await writeFile(join(dir, "package.json"), manifestOf(lock.packages));
461
466
  await writeFile(join(dir, "pnpm-lock.yaml"), pnpm);
462
467
  const outcome = await install().run({
@@ -536,7 +541,7 @@ export function createDependencies(options: DependenciesOptions): Dependencies {
536
541
  await rm(dir, { recursive: true, force: true });
537
542
  await mkdir(dir, { recursive: true });
538
543
  try {
539
- await symlink(warm.nodeModules, join(dir, "warm"), "dir");
544
+ await linkDirectory(warm.nodeModules, join(dir, "warm"));
540
545
  await writeFile(
541
546
  join(dir, "package.json"),
542
547
  `${JSON.stringify(
package/src/deps/warm.ts CHANGED
@@ -3,10 +3,10 @@
3
3
  * install. `@mostra/warm`'s `dependencies` are the warm packages; its `node_modules` is the layout.
4
4
  */
5
5
  import { existsSync, readFileSync, realpathSync } from "node:fs";
6
- import { dirname, join, resolve } from "node:path";
7
- import { fileURLToPath } from "node:url";
6
+ import { join, resolve } from "node:path";
8
7
  import { createDiagnostic, RpcError } from "@mostra/protocol";
9
8
  import type { Environment } from "../log.ts";
9
+ import { runtimeRoot } from "../platform/index.ts";
10
10
 
11
11
  /** The warm set: where its layout is and what versions it holds. */
12
12
  export interface WarmSet {
@@ -16,20 +16,7 @@ export interface WarmSet {
16
16
  readonly packages: Readonly<Record<string, string>>;
17
17
  }
18
18
 
19
- /** The directory of `@mostra/runtime`'s package.json. */
20
- export function runtimeRoot(): string {
21
- let dir = dirname(fileURLToPath(import.meta.url));
22
- for (;;) {
23
- const manifest = join(dir, "package.json");
24
- if (existsSync(manifest)) {
25
- const { name } = JSON.parse(readFileSync(manifest, "utf8")) as { name?: string };
26
- if (name === "@mostra/runtime") return dir;
27
- }
28
- const parent = dirname(dir);
29
- if (parent === dir) throw new Error("Couldn't find @mostra/runtime's package.json.");
30
- dir = parent;
31
- }
32
- }
19
+ export { runtimeRoot };
33
20
 
34
21
  function warmMissing(message: string): RpcError {
35
22
  return new RpcError(createDiagnostic("MOSTRA_ENV_WARM_MISSING", { message }));
package/src/faults.ts CHANGED
@@ -14,7 +14,7 @@
14
14
  import type { Environment } from "./log.ts";
15
15
 
16
16
  /** What a fault point does. */
17
- export type FaultAction = "throw" | "crash" | "hang";
17
+ export type FaultAction = "throw" | "throw-once" | "crash" | "hang";
18
18
 
19
19
  /** The test fault points of one instance. */
20
20
  export interface Faults {
@@ -47,7 +47,10 @@ export function faultsFrom(env: Environment): Faults {
47
47
  const separator = entry.lastIndexOf(":");
48
48
  const point = entry.slice(0, separator).trim();
49
49
  const action = entry.slice(separator + 1).trim();
50
- if (point && (action === "throw" || action === "crash" || action === "hang"))
50
+ if (
51
+ point &&
52
+ (action === "throw" || action === "throw-once" || action === "crash" || action === "hang")
53
+ )
51
54
  configured.set(point, action);
52
55
  }
53
56
  return {
@@ -55,6 +58,10 @@ export function faultsFrom(env: Environment): Faults {
55
58
  at(point) {
56
59
  const action = configured.get(point);
57
60
  if (action === "throw") throw new InjectedFault(point);
61
+ if (action === "throw-once") {
62
+ configured.delete(point);
63
+ throw new InjectedFault(point);
64
+ }
58
65
  if (action === "crash") {
59
66
  process.kill(process.pid, "SIGKILL");
60
67
  // The signal is delivered at once; block until it lands so no later step runs.
@@ -127,7 +127,7 @@ export function actionRoutes(options: ActionRoutesOptions): ActionRoutes {
127
127
  if (!session || artifactId === undefined) throw new Error("session route without a session");
128
128
  return {
129
129
  artifactId,
130
- viewerId: interaction.viewerOf(session.grant.viewerId),
130
+ viewerId: interaction.viewerOf(session.viewerId),
131
131
  tokenId: session.grant.tokenId,
132
132
  scopes: session.grant.scopes,
133
133
  };
@@ -199,7 +199,7 @@ export function browserRoutes(options: BrowserRoutesOptions): BrowserRoutes {
199
199
  if (!session || artifactId === undefined) throw new Error("session route without a session");
200
200
  return {
201
201
  artifactId,
202
- viewerId: interaction.viewerOf(session.grant.viewerId),
202
+ viewerId: interaction.viewerOf(session.viewerId),
203
203
  // A page names only views its own link opened (Claude review finding 11).
204
204
  tokenId: session.grant.tokenId,
205
205
  scopes: session.grant.scopes,
@@ -14,7 +14,6 @@ import {
14
14
  mkdirSync,
15
15
  openSync,
16
16
  readFileSync,
17
- renameSync,
18
17
  writeSync,
19
18
  } from "node:fs";
20
19
  import { join } from "node:path";
@@ -30,6 +29,7 @@ import {
30
29
  import { appendEvent } from "../interaction/index.ts";
31
30
  import type { Ledger, LedgerDb } from "../ledger/index.ts";
32
31
  import type { Log } from "../log.ts";
32
+ import { renamePathSync } from "../platform/index.ts";
33
33
 
34
34
  /** Crockford base32, the alphabet of every Mostra ID body (D77). */
35
35
  const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
@@ -127,7 +127,7 @@ export function capabilityKey(home: string, log: Log): Buffer {
127
127
  } finally {
128
128
  closeSync(fd);
129
129
  }
130
- renameSync(aside, file);
130
+ renamePathSync(aside, file);
131
131
  chmodSync(file, 0o600);
132
132
  return key;
133
133
  }
@@ -162,6 +162,11 @@ export interface ResolvedSession {
162
162
  /** The version a frame session entered (D98 item 5). */
163
163
  readonly versionId?: string;
164
164
  readonly grant: Grant;
165
+ /**
166
+ * The viewer the session acts as: its link's viewer (D104), else the one the host's identity
167
+ * port named when the link was exchanged (D143 item 2); absent: the home's local user.
168
+ */
169
+ readonly viewerId?: string;
165
170
  }
166
171
 
167
172
  /** What a redeemed frame ticket carries. */
@@ -175,6 +180,8 @@ export interface TicketGrant {
175
180
  readonly shellOrigin: string;
176
181
  /** The shell session that asked for it: the ticket works only while that session lives. */
177
182
  readonly shellSessionId: string;
183
+ /** The viewer that shell session acts as, which the frame's session acts as too (D143). */
184
+ readonly viewerId?: string | undefined;
178
185
  }
179
186
 
180
187
  interface TokenRow {
@@ -196,6 +203,7 @@ interface SessionRow {
196
203
  origin: string;
197
204
  csrf: string;
198
205
  version_id: string | null;
206
+ viewer_id: string | null;
199
207
  }
200
208
 
201
209
  const grantOf = (row: TokenRow): Grant => ({
@@ -522,6 +530,8 @@ export class Capabilities {
522
530
  readonly tokenId: string;
523
531
  readonly origin: string;
524
532
  readonly versionId?: string;
533
+ /** The person the host's identity port named, for a link without a viewer (D143 item 2). */
534
+ readonly viewerId?: string | undefined;
525
535
  }): {
526
536
  readonly cookie: string;
527
537
  readonly csrf: string;
@@ -533,7 +543,7 @@ export class Capabilities {
533
543
  const now = this.#iso(this.#now());
534
544
  this.#ledger.write((db) =>
535
545
  db.run(
536
- "INSERT INTO session (id, token_id, origin, mode, csrf, version_id, created_at, last_seen_at) VALUES (?, ?, ?, 'cookie', ?, ?, ?, ?)",
546
+ "INSERT INTO session (id, token_id, origin, mode, csrf, version_id, created_at, last_seen_at, viewer_id) VALUES (?, ?, ?, 'cookie', ?, ?, ?, ?, ?)",
537
547
  id,
538
548
  input.tokenId,
539
549
  input.origin,
@@ -541,6 +551,7 @@ export class Capabilities {
541
551
  input.versionId ?? null,
542
552
  now,
543
553
  now,
554
+ input.viewerId ?? null,
544
555
  ),
545
556
  );
546
557
  return { cookie, csrf, id };
@@ -574,11 +585,15 @@ export class Capabilities {
574
585
  // A row whose CSRF hash doesn't match was not made by this code: it doesn't count.
575
586
  if (!safeEqual(hashSecret(csrf), found.session.csrf)) continue;
576
587
  this.#touch(found.session.id);
588
+ const grant = grantOf(found.token);
589
+ // A link's own viewer always wins: a token's viewer never changes (D104).
590
+ const viewerId = grant.viewerId ?? found.session.viewer_id ?? undefined;
577
591
  return {
578
592
  id: found.session.id,
579
593
  csrf,
580
594
  ...(found.session.version_id !== null ? { versionId: found.session.version_id } : {}),
581
- grant: grantOf(found.token),
595
+ grant,
596
+ ...(viewerId !== undefined ? { viewerId } : {}),
582
597
  };
583
598
  }
584
599
  return revoked
@@ -724,9 +739,15 @@ export class Capabilities {
724
739
  return rest;
725
740
  }
726
741
 
727
- /** Spends a launch ticket that started a session. */
728
- spendLaunch(ticket: unknown): void {
729
- if (looksLikeSecret(ticket)) this.#launches.delete(hashSecret(ticket));
742
+ /**
743
+ * Spends a launch ticket that started a session: `true` only for the caller that spent it, so
744
+ * two exchanges that both presented it while a host's identity port was answering get one
745
+ * session between them (GPT review of WP-12, finding 1).
746
+ */
747
+ spendLaunch(ticket: unknown): boolean {
748
+ // An expired ticket is swept first, so it can't be spent (Opus review of WP-12, finding 3).
749
+ this.#sweepTickets();
750
+ return looksLikeSecret(ticket) && this.#launches.delete(hashSecret(ticket));
730
751
  }
731
752
 
732
753
  /** Removes sessions unseen for longer than their cookie lives; no browser holds them any more. */
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Who a browser is (D143 item 2). A link minted with a viewer acts for that viewer (D104) and asks
3
+ * nothing. For a link without one, a host that registered the `identity` port names the person
4
+ * from the request's headers; without such a host, the session acts as the home's local user.
5
+ */
6
+ import {
7
+ createDiagnostic,
8
+ type Diagnostic,
9
+ type IdentityVia,
10
+ portIdentityResolveMethod,
11
+ type ViewerSpec,
12
+ } from "@mostra/protocol";
13
+ import type { Log } from "../log.ts";
14
+
15
+ /** How long a host has to answer `port/identity.resolve`: a page waits for it, as for D108. */
16
+ export const IDENTITY_TIMEOUT_MS = 5_000;
17
+
18
+ /** What {@link resolveIdentity} reads. */
19
+ export interface IdentityInput {
20
+ /** The artifact whose link is being exchanged. */
21
+ readonly artifactId: string;
22
+ /** How the request reached the gateway. */
23
+ readonly via: IdentityVia;
24
+ /** The request's headers. */
25
+ readonly headers: Headers;
26
+ readonly log: Log;
27
+ /** Hosts that always provide `identity` (`HomeConfig.ports`), by client name. */
28
+ readonly expected: () => readonly string[];
29
+ /** The newest connection that registered `identity`, if any. */
30
+ readonly registrant: () => { readonly session: number; readonly owner: string } | undefined;
31
+ /** Calls the port on that connection; rejects on a transport failure or the timeout. */
32
+ readonly call: (session: number, params: unknown) => Promise<unknown>;
33
+ }
34
+
35
+ /** The person a host named, the standalone default, or why nobody can be named. */
36
+ export type IdentityOutcome =
37
+ | { readonly kind: "person"; readonly viewer: ViewerSpec }
38
+ | { readonly kind: "default" }
39
+ | { readonly kind: "unavailable"; readonly diagnostic: Diagnostic };
40
+
41
+ /**
42
+ * The headers a host sees: names in lower case, without `cookie` (Mostra's sessions and every
43
+ * other page's of this host) and without Mostra's own `x-mostra-*` headers.
44
+ */
45
+ export function identityHeaders(headers: Headers): Record<string, string> {
46
+ const seen: Record<string, string> = {};
47
+ headers.forEach((value, name) => {
48
+ const key = name.toLowerCase();
49
+ if (key === "cookie" || key.startsWith("x-mostra-")) return;
50
+ seen[key] = value;
51
+ });
52
+ return seen;
53
+ }
54
+
55
+ /**
56
+ * Asks the host that took identity over. Its outage never makes the session someone else: a
57
+ * failure, a timeout, an answer the schema refuses, or an expected host that isn't connected is
58
+ * `unavailable`, and the exchange is refused.
59
+ */
60
+ export async function resolveIdentity(input: IdentityInput): Promise<IdentityOutcome> {
61
+ const registrant = input.registrant();
62
+ const unavailable = (message: string): IdentityOutcome => ({
63
+ kind: "unavailable",
64
+ diagnostic: createDiagnostic("MOSTRA_HOST_IDENTITY_UNAVAILABLE", { message }),
65
+ });
66
+ if (registrant) {
67
+ try {
68
+ const answer = await input.call(registrant.session, {
69
+ artifactId: input.artifactId,
70
+ via: input.via,
71
+ headers: identityHeaders(input.headers),
72
+ });
73
+ const parsed = portIdentityResolveMethod.result.safeParse(answer);
74
+ if (parsed.success) {
75
+ return parsed.data === null ? { kind: "default" } : { kind: "person", viewer: parsed.data };
76
+ }
77
+ input.log.warn("gateway.identity_invalid", {
78
+ owner: registrant.owner,
79
+ artifactId: input.artifactId,
80
+ });
81
+ return unavailable(
82
+ `The host ${registrant.owner} answered who this is in a form Mostra refuses.`,
83
+ );
84
+ } catch (error) {
85
+ input.log.warn("gateway.identity_failed", {
86
+ owner: registrant.owner,
87
+ artifactId: input.artifactId,
88
+ error: (error as Error).message,
89
+ });
90
+ return unavailable(`The host ${registrant.owner} didn't say who this is.`);
91
+ }
92
+ }
93
+ const away = input.expected();
94
+ if (away.length > 0) {
95
+ input.log.warn("gateway.identity_host_away", { owners: away, artifactId: input.artifactId });
96
+ return unavailable(
97
+ `The host that identifies this home's viewers (${away.join(", ")}) isn't running.`,
98
+ );
99
+ }
100
+ return { kind: "default" };
101
+ }