@murmurv2/cli 2.11.0 → 2.13.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 (69) hide show
  1. package/README.md +85 -19
  2. package/package.json +8 -6
  3. package/runtime/bin/murmur-svc.exe +0 -0
  4. package/runtime/npm-runtime-manifest.json +193 -81
  5. package/runtime/package.json +1 -1
  6. package/runtime/packages/mcp-server/dist/src/agent-config.js +1 -0
  7. package/runtime/packages/setup/bin/murmur.mjs +6 -3
  8. package/runtime/packages/setup/dist/src/backups.d.ts +36 -0
  9. package/runtime/packages/setup/dist/src/backups.js +128 -0
  10. package/runtime/packages/setup/dist/src/broker-input.d.ts +24 -0
  11. package/runtime/packages/setup/dist/src/broker-input.js +98 -0
  12. package/runtime/packages/setup/dist/src/broker-migration.d.ts +35 -0
  13. package/runtime/packages/setup/dist/src/broker-migration.js +138 -0
  14. package/runtime/packages/setup/dist/src/cli-error.d.ts +2 -0
  15. package/runtime/packages/setup/dist/src/cli-error.js +30 -0
  16. package/runtime/packages/setup/dist/src/cli.d.ts +1 -1
  17. package/runtime/packages/setup/dist/src/cli.js +111 -14
  18. package/runtime/packages/setup/dist/src/clients.d.ts +28 -76
  19. package/runtime/packages/setup/dist/src/clients.js +166 -26
  20. package/runtime/packages/setup/dist/src/commands.d.ts +3 -1
  21. package/runtime/packages/setup/dist/src/commands.js +18 -7
  22. package/runtime/packages/setup/dist/src/config.d.ts +10 -0
  23. package/runtime/packages/setup/dist/src/config.js +119 -10
  24. package/runtime/packages/setup/dist/src/connect.d.ts +143 -0
  25. package/runtime/packages/setup/dist/src/connect.js +126 -0
  26. package/runtime/packages/setup/dist/src/doctor.d.ts +42 -0
  27. package/runtime/packages/setup/dist/src/doctor.js +89 -10
  28. package/runtime/packages/setup/dist/src/installation.d.ts +25 -0
  29. package/runtime/packages/setup/dist/src/installation.js +89 -0
  30. package/runtime/packages/setup/dist/src/invitation-server.d.ts +2 -0
  31. package/runtime/packages/setup/dist/src/invitation-server.js +45 -0
  32. package/runtime/packages/setup/dist/src/message-status.d.ts +5 -0
  33. package/runtime/packages/setup/dist/src/message-status.js +13 -0
  34. package/runtime/packages/setup/dist/src/onboarding.d.ts +28 -10
  35. package/runtime/packages/setup/dist/src/onboarding.js +129 -34
  36. package/runtime/packages/setup/dist/src/outbox-attention.js +3 -21
  37. package/runtime/packages/setup/dist/src/paths.d.ts +7 -0
  38. package/runtime/packages/setup/dist/src/paths.js +39 -24
  39. package/runtime/packages/setup/dist/src/platform/darwin.d.ts +3 -0
  40. package/runtime/packages/setup/dist/src/platform/darwin.js +241 -9
  41. package/runtime/packages/setup/dist/src/platform/linux.js +152 -17
  42. package/runtime/packages/setup/dist/src/platform/profile-usage.d.ts +20 -0
  43. package/runtime/packages/setup/dist/src/platform/profile-usage.js +89 -0
  44. package/runtime/packages/setup/dist/src/platform/windows.js +89 -4
  45. package/runtime/packages/setup/dist/src/private-file.d.ts +4 -1
  46. package/runtime/packages/setup/dist/src/private-file.js +39 -3
  47. package/runtime/packages/setup/dist/src/state.d.ts +4 -0
  48. package/runtime/packages/setup/dist/src/state.js +65 -1
  49. package/runtime/packages/setup/dist/src/status.d.ts +26 -2
  50. package/runtime/packages/setup/dist/src/status.js +84 -20
  51. package/runtime/packages/setup/dist/src/types.d.ts +21 -1
  52. package/runtime/packages/setup/dist/src/verdict.js +4 -2
  53. package/runtime/packages/setup/dist/src/wake-attention.d.ts +11 -0
  54. package/runtime/packages/setup/dist/src/wake-attention.js +44 -0
  55. package/runtime/packages/setup/dist/src/wake-readers.d.ts +12 -0
  56. package/runtime/packages/setup/dist/src/wake-readers.js +65 -0
  57. package/runtime/packages/setup/package.json +1 -1
  58. package/runtime/scripts/auth-security.mjs +93 -0
  59. package/runtime/scripts/codex-app-server-wake.mjs +182 -32
  60. package/runtime/scripts/daemon-contacts.mjs +56 -0
  61. package/runtime/scripts/daemon-flush-tick.mjs +25 -0
  62. package/runtime/scripts/daemon-link-watch.mjs +60 -0
  63. package/runtime/scripts/daemon-observation.mjs +74 -18
  64. package/runtime/scripts/murmur-auth-token.mjs +140 -0
  65. package/runtime/scripts/murmur-daemon.mjs +66 -36
  66. package/runtime/scripts/murmur-jetstream-advisory.mjs +27 -0
  67. package/runtime/scripts/murmur-shell-send.mjs +3 -3
  68. package/runtime/scripts/wake-drain-claude.mjs +193 -39
  69. package/runtime/scripts/wake-monitor.mjs +46 -18
@@ -4,6 +4,7 @@ import * as fs from "node:fs/promises";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { randomUUID } from "node:crypto";
7
+ import { classifyProfilePath, ProfileUsageUnknown, verifiedProfileRoot } from "./profile-usage.js";
7
8
  const marker = "<!-- Managed by Murmur setup: darwin-v1 -->";
8
9
  const launchctl = "/bin/launchctl";
9
10
  const xml = (s) => s.replace(/[&<>"']/g, c => ({
@@ -22,7 +23,7 @@ function validate(ctx) {
22
23
  if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(ctx.serviceName)) {
23
24
  throw new Error("darwin-invalid-service-name");
24
25
  }
25
- // The current daemon resolves both paths from DATA_DIR, ignoring STORE_PATH.
26
+ // The daemon pins DATA_DIR and requires derived store paths to agree.
26
27
  // Refuse an inconsistent context instead of starting against the wrong DB.
27
28
  if (ctx.configPath !== path.join(ctx.dataDir, "agent-config.json") ||
28
29
  ctx.storePath !== path.join(ctx.dataDir, "murmur.db") ||
@@ -30,15 +31,17 @@ function validate(ctx) {
30
31
  throw new Error("darwin-daemon-path-contract-mismatch");
31
32
  }
32
33
  }
33
- const defaultRun = (file, args) => new Promise(resolve => {
34
- execFile(file, args, {
35
- encoding: "utf8", timeout: 8_000, maxBuffer: 512 * 1024,
34
+ const commandRunner = (maxBuffer) => (file, args) => new Promise(resolve => {
35
+ const child = execFile(file, args, {
36
+ encoding: "utf8", timeout: 8_000, maxBuffer,
36
37
  env: { ...process.env, LC_ALL: "C", TZ: "UTC" },
37
38
  }, (error, stdout, stderr) => resolve({
38
39
  code: error ? (typeof error.code === "number" ? error.code : -1) : 0,
39
- stdout: String(stdout), stderr: String(stderr),
40
+ stdout: String(stdout), stderr: String(stderr), pid: child.pid,
40
41
  }));
41
42
  });
43
+ const defaultRun = commandRunner(512 * 1024);
44
+ const defaultProfileRun = commandRunner(8 * 1024 * 1024);
42
45
  const absent = (r) => r.code !== 0 &&
43
46
  /Could not find service|Could not find specified service/.test(r.stderr + r.stdout);
44
47
  const baseSnapshot = () => ({
@@ -62,6 +65,7 @@ export function createDarwinAdapter(options = {}) {
62
65
  throw new Error("darwin-invalid-user-id");
63
66
  const env = options.env ?? process.env;
64
67
  const run = options.run ?? defaultRun;
68
+ const profileRun = options.profileRun ?? options.run ?? defaultProfileRun;
65
69
  const domain = `gui/${uid}`;
66
70
  const plistPath = (ctx) => path.join(home, "Library", "LaunchAgents", `${ctx.serviceName}.plist`);
67
71
  const target = (ctx) => `${domain}/${ctx.serviceName}`;
@@ -70,6 +74,8 @@ export function createDarwinAdapter(options = {}) {
70
74
  const args = [ctx.nodePath, path.join(ctx.repoRoot, "scripts", "murmur-daemon.mjs")];
71
75
  const environment = {
72
76
  DATA_DIR: ctx.dataDir,
77
+ MURMUR_DATA_DIR: ctx.dataDir,
78
+ MURMUR_CHANNEL_ROSTER_PATH: path.join(ctx.dataDir, "channel-roster.db"),
73
79
  MURMUR_STORE_PATH: ctx.storePath,
74
80
  PATH: [path.dirname(ctx.nodePath), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"].join(":"),
75
81
  };
@@ -129,6 +135,190 @@ export function createDarwinAdapter(options = {}) {
129
135
  }
130
136
  return null;
131
137
  }
138
+ const usageUnknown = (reason = "profile-usage.probe-unavailable") => ({ state: "unknown", reason });
139
+ function lsofSnapshot(output) {
140
+ if (output.includes("\0") || !output.endsWith("\n"))
141
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
142
+ const lines = output.split("\n");
143
+ if (lines.at(-1) === "")
144
+ lines.pop();
145
+ if (lines.some(line => line === ""))
146
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
147
+ const records = [];
148
+ let pid = null, descriptor = null, type = null;
149
+ let processHasRecord = false;
150
+ const seen = new Set();
151
+ for (const line of lines) {
152
+ if (line.startsWith("p")) {
153
+ if (descriptor !== null || type !== null || pid !== null && !processHasRecord || !/^p[1-9]\d*$/.test(line)) {
154
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
155
+ }
156
+ pid = Number(line.slice(1));
157
+ if (!Number.isSafeInteger(pid) || seen.has(pid))
158
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
159
+ seen.add(pid);
160
+ processHasRecord = false;
161
+ }
162
+ else if (line.startsWith("f")) {
163
+ if (pid === null || descriptor !== null || type !== null || line.length < 2 || /[\0\r\n]/.test(line)) {
164
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
165
+ }
166
+ descriptor = line.slice(1);
167
+ }
168
+ else if (line.startsWith("t")) {
169
+ if (pid === null || descriptor === null || type !== null || line.length < 2 || /[\0\r\n]/.test(line)) {
170
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
171
+ }
172
+ type = line.slice(1);
173
+ }
174
+ else if (line.startsWith("n")) {
175
+ if (pid === null || descriptor === null || type === null) {
176
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
177
+ }
178
+ // Apple's process_netpolicy() sets NPOLICY but no name. Native lsof also
179
+ // emits unnamed NEXUS FDs; XNU gives that Skywalk controller its own
180
+ // fileops, separate from vnodes. Darwin process_pipe_common() leaves
181
+ // NAME empty when an anonymous pipe has no peer handle or byte count.
182
+ // PIPE is distinct from a filesystem FIFO. Only these numeric FD types may
183
+ // have an empty n; missing n, other empty types and pseudo-FDs refuse.
184
+ // https://github.com/apple-opensource/lsof/blob/da09c8c6436286e5bd8c400b42e86b54404f12a7/lsof/dialects/darwin/libproc/dnetpolicy.c
185
+ // https://github.com/apple-oss-distributions/xnu/blob/f6217f891ac0bb64f3d375211650a4c1ff8ca1ea/bsd/skywalk/nexus/nexus_syscalls.c
186
+ // https://github.com/lsof-org/lsof/blob/1ebf257c64db1b2ece5e4d5e922ed711c692f161/lib/dialects/darwin/dfile.c#L306-L340
187
+ if (line.length === 1 && !((type === "NPOLICY" || type === "NEXUS" || type === "PIPE") && /^\d+$/.test(descriptor))) {
188
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
189
+ }
190
+ records.push({ pid, descriptor, type, name: line.slice(1) });
191
+ descriptor = type = null;
192
+ processHasRecord = true;
193
+ }
194
+ else {
195
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
196
+ }
197
+ }
198
+ if (descriptor !== null || type !== null || pid !== null && !processHasRecord) {
199
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
200
+ }
201
+ return { pids: seen, records };
202
+ }
203
+ function processSnapshot(result) {
204
+ if (result.code !== 0 || result.stderr.trim() !== "" || !Number.isSafeInteger(result.pid) || result.pid <= 0) {
205
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
206
+ }
207
+ const observations = new Map();
208
+ const lines = result.stdout.split("\n");
209
+ if (lines.at(-1) === "")
210
+ lines.pop();
211
+ for (const line of lines) {
212
+ const match = /^\s*([1-9]\d*)\s+(\d+)\s+(\S+)\s+(.+?)\s*$/.exec(line);
213
+ if (!match)
214
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
215
+ const pid = Number(match[1]), uid = Number(match[2]);
216
+ if (!Number.isSafeInteger(pid) || !Number.isSafeInteger(uid) || observations.has(pid)) {
217
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
218
+ }
219
+ observations.set(pid, { uid, start: match[4], zombie: match[3].startsWith("Z") });
220
+ }
221
+ // /bin/ps is setuid-root on macOS, so its exact child PID may have UID 0.
222
+ // Verify and remove only that exact observer from the full process set.
223
+ if (!observations.has(result.pid) || !observations.has(process.pid)) {
224
+ throw new ProfileUsageUnknown("profile-usage.process-unverifiable");
225
+ }
226
+ observations.delete(result.pid);
227
+ for (const anchor of new Set([1, process.ppid])) {
228
+ if (!observations.has(anchor))
229
+ throw new ProfileUsageUnknown("profile-usage.process-visibility-incomplete");
230
+ }
231
+ return observations;
232
+ }
233
+ async function profileUsage(ctx) {
234
+ validate(ctx);
235
+ try {
236
+ const profile = await verifiedProfileRoot(ctx);
237
+ let control;
238
+ try {
239
+ control = await fs.open(ctx.configPath, constants.O_RDONLY | constants.O_NOFOLLOW);
240
+ const [opened, selected, canonical] = await Promise.all([
241
+ control.stat(), fs.lstat(ctx.configPath), fs.realpath(ctx.configPath),
242
+ ]);
243
+ const currentUid = process.getuid?.();
244
+ if (currentUid === undefined || !opened.isFile() || !selected.isFile() || selected.isSymbolicLink()
245
+ || opened.uid !== currentUid || selected.uid !== currentUid
246
+ || (opened.mode & 0o077) !== 0 || (selected.mode & 0o077) !== 0
247
+ || opened.dev !== selected.dev || opened.ino !== selected.ino || canonical !== ctx.configPath)
248
+ return usageUnknown();
249
+ // Apple's lsof 4.91 makes every +D entry a required search argument,
250
+ // so an unopened entry forces exit 1. Scan all processes and prove
251
+ // lsof coverage with stable ps snapshots around the observation.
252
+ const psArgs = ["-axo", "pid=,uid=,stat=,lstart="];
253
+ const before = processSnapshot(await profileRun("/bin/ps", psArgs));
254
+ const result = await profileRun("/usr/sbin/lsof", ["-n", "-P", "-Fpftn"]);
255
+ if (result.code !== 0 || result.stderr.trim() !== "")
256
+ return usageUnknown();
257
+ const snapshot = lsofSnapshot(result.stdout);
258
+ const after = processSnapshot(await profileRun("/bin/ps", psArgs));
259
+ const stable = new Set();
260
+ if (before.size !== after.size)
261
+ return usageUnknown("profile-usage.process-unverifiable");
262
+ for (const [pid, first] of before) {
263
+ const second = after.get(pid);
264
+ if (!second || first.uid !== second.uid || first.start !== second.start || first.zombie !== second.zombie) {
265
+ return usageUnknown("profile-usage.process-unverifiable");
266
+ }
267
+ if (!first.zombie)
268
+ stable.add(pid);
269
+ }
270
+ if ([...stable].some(pid => !snapshot.pids.has(pid))) {
271
+ return usageUnknown("profile-usage.process-unverifiable");
272
+ }
273
+ let controlSeen = false, held = false;
274
+ const filesystemTypes = new Set(["REG", "DIR", "LINK"]);
275
+ const otherTypes = new Set(["ATALK", "BLK", "CHR", "FIFO", "FSEVENTS", "IPv4", "IPv6", "KQUEUE",
276
+ "NPOLICY", "NEXUS", "PIPE", "PSXSEM", "PSXSHM", "key", "ndrv", "ppp", "rte", "sock", "systm", "unix",
277
+ "vsock", "vsockp"]);
278
+ const classifications = new Map();
279
+ for (const record of snapshot.records) {
280
+ if (!filesystemTypes.has(record.type)) {
281
+ if (!otherTypes.has(record.type))
282
+ return usageUnknown("profile-usage.process-unverifiable");
283
+ continue;
284
+ }
285
+ let classificationPromise = classifications.get(record.name);
286
+ if (!classificationPromise) {
287
+ classificationPromise = classifyProfilePath(profile.root, record.name);
288
+ classifications.set(record.name, classificationPromise);
289
+ }
290
+ const classification = await classificationPromise;
291
+ if (classification === "unknown")
292
+ return usageUnknown("profile-usage.process-unverifiable");
293
+ if (classification === "outside")
294
+ continue;
295
+ if (record.pid === process.pid) {
296
+ const [recordPath, recordInfo] = await Promise.all([fs.realpath(record.name), fs.stat(record.name)]);
297
+ if (recordPath === canonical && recordInfo.dev === opened.dev && recordInfo.ino === opened.ino)
298
+ controlSeen = true;
299
+ }
300
+ else {
301
+ held = true;
302
+ }
303
+ }
304
+ if (!controlSeen)
305
+ return usageUnknown("profile-usage.control-unobserved");
306
+ if (held)
307
+ return { state: "in-use", reason: "profile-usage.open-file" };
308
+ const profileAfter = await verifiedProfileRoot(ctx);
309
+ if (profileAfter.root !== profile.root || profileAfter.proof !== profile.proof) {
310
+ return usageUnknown("profile-usage.profile-changed");
311
+ }
312
+ return { state: "free", reason: "profile-usage.no-open-files" };
313
+ }
314
+ finally {
315
+ await control?.close();
316
+ }
317
+ }
318
+ catch (error) {
319
+ return usageUnknown(error instanceof ProfileUsageUnknown ? error.reason : undefined);
320
+ }
321
+ }
132
322
  async function status(ctx) {
133
323
  validate(ctx);
134
324
  const value = baseSnapshot();
@@ -219,7 +409,20 @@ export function createDarwinAdapter(options = {}) {
219
409
  if (loaded.code !== 0)
220
410
  throw new Error("darwin-cannot-inspect-service-before-stop");
221
411
  requireSameLoadedPath(ctx, loaded);
222
- if (await readOwned(ctx) !== plist(ctx))
412
+ let owned = await readOwned(ctx);
413
+ // Upgrading from a Cellar-bound Node must still allow Stop before Install.
414
+ // Accept only the known Homebrew spelling change; all profile/runtime fields
415
+ // and the ownership marker must otherwise match byte for byte.
416
+ const oldNode = owned?.match(/<key>ProgramArguments<\/key><array><string>((?:\/opt\/homebrew|\/usr\/local)\/Cellar\/(node(?:@\d+)?)\/[^<\/]+\/bin\/node)<\/string>/);
417
+ if (oldNode) {
418
+ const prefix = oldNode[1].split('/Cellar/')[0], formula = oldNode[2];
419
+ const stable = [`${prefix}/opt/${formula}/bin/node`, ...(formula === 'node' ? [`${prefix}/bin/node`] : [])];
420
+ if (stable.includes(ctx.nodePath))
421
+ owned = owned
422
+ .replace(`<array><string>${oldNode[1]}</string>`, `<array><string>${xml(ctx.nodePath)}</string>`)
423
+ .replace(`<key>PATH</key><string>${path.dirname(oldNode[1])}:`, `<key>PATH</key><string>${path.dirname(ctx.nodePath)}:`);
424
+ }
425
+ if (owned !== plist(ctx))
223
426
  throw new Error("darwin-stop-profile-mismatch");
224
427
  const result = await run(launchctl, ["bootout", target(ctx)]);
225
428
  if (result.code !== 0 && !absent(result))
@@ -258,13 +461,42 @@ export function createDarwinAdapter(options = {}) {
258
461
  // Do not guess a writable MCP target for non-default Claude profiles.
259
462
  // Shared setup may resolve it by a client-supported configuration query.
260
463
  const claudeConfig = env.CLAUDE_CONFIG_DIR ? null : path.join(home, ".claude.json");
464
+ const claudeDesktop = await hasApp(["Claude.app"], "com.anthropic.claudefordesktop");
465
+ async function hasBundledClaudeCode() {
466
+ if (!claudeDesktop)
467
+ return false;
468
+ const root = path.join(home, "Library", "Application Support", "Claude", "claude-code");
469
+ const directories = async (dir) => (await fs.readdir(dir, { withFileTypes: true }).catch(() => []))
470
+ .filter(entry => entry.isDirectory()).map(entry => path.join(dir, entry.name));
471
+ // Known desktop layouts: version/claude and version/build/claude.app/Contents/MacOS/claude.
472
+ // Inspect metadata only; never run a discovered binary or recurse through user files.
473
+ for (const version of await directories(root)) {
474
+ const builds = [version, ...await directories(version)];
475
+ for (const build of builds)
476
+ for (const candidate of [path.join(build, "claude"),
477
+ path.join(build, "claude.app", "Contents", "MacOS", "claude")]) {
478
+ if (await accessible(candidate, constants.X_OK) && await fs.stat(candidate).then(s => s.isFile(), () => false))
479
+ return true;
480
+ }
481
+ }
482
+ return false;
483
+ }
484
+ const claudeCli = await hasExecutable("claude");
485
+ const bundledCode = !claudeCli && await hasBundledClaudeCode();
261
486
  return [
262
- { id: "claude-code", installed: await hasExecutable("claude"), configPath: claudeConfig, format: "json",
487
+ { id: "claude-code", installed: claudeCli || bundledCode, configPath: claudeConfig, format: "json",
488
+ ...(bundledCode ? { detail: "Claude Code in the Claude desktop application" } : {}),
263
489
  ...(claudeConfig === null ? { detail: "Custom CLAUDE_CONFIG_DIR detected; MCP config target requires client verification" } : {}) },
264
- { id: "claude-desktop", installed: await hasApp(["Claude.app"], "com.anthropic.claudefordesktop"), configPath: path.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json"), format: "json" },
490
+ { id: "claude-desktop", installed: claudeDesktop, configPath: path.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json"), format: "json" },
265
491
  { id: "codex-cli", installed: await hasExecutable("codex"), configPath: codexConfig, format: "toml" },
266
492
  { id: "codex-desktop", installed: await hasApp(["Codex.app", "ChatGPT.app"], "com.openai.codex"), configPath: codexConfig, format: "toml" },
267
493
  ];
268
494
  }
269
- return { manager: "launchd", status, install, start, stop, detectClients };
495
+ return { manager: "launchd", status, install, start, stop, detectClients, profileUsage,
496
+ async observeStore(ctx, pid) {
497
+ validate(ctx);
498
+ if (!Number.isSafeInteger(pid) || pid <= 0)
499
+ return null;
500
+ return observedStore(pid, ctx.storePath);
501
+ } };
270
502
  }
@@ -1,10 +1,11 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { promisify } from "node:util";
3
3
  import { constants } from "node:fs";
4
- import { access, mkdir, open, readdir, readlink, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
4
+ import { access, mkdir, open, readFile, readdir, readlink, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
5
5
  import { homedir } from "node:os";
6
6
  import { randomUUID } from "node:crypto";
7
7
  import path from "node:path";
8
+ import { classifyProfilePath, ProfileUsageUnknown, verifiedProfileRoot } from "./profile-usage.js";
8
9
  const exec = promisify(execFile);
9
10
  const marker = "# Managed by Murmur setup: systemd-v1\n";
10
11
  const unit = (c) => `${c.serviceName}.service`;
@@ -24,10 +25,11 @@ export function renderLinuxUnit(c) {
24
25
  check(c);
25
26
  // ExecStart expands $ independently from specifiers; Environment values do not.
26
27
  const arg = (v) => q(v.replaceAll("$", () => "$$"));
27
- return `${marker}[Unit]\nDescription=Murmur agent daemon\nStartLimitIntervalSec=60\nStartLimitBurst=5\n\n[Service]\nType=simple\nWorkingDirectory=${c.repoRoot.replaceAll("%", "%%")}\nEnvironment=${q(`DATA_DIR=${c.dataDir}`)}\nExecStart=${arg(c.nodePath)} ${arg(path.join(c.repoRoot, "scripts", "murmur-daemon.mjs"))}\nStandardOutput=append:${path.join(c.logDir, `${c.serviceName}.out.log`).replaceAll("%", "%%")}\nStandardError=append:${path.join(c.logDir, `${c.serviceName}.err.log`).replaceAll("%", "%%")}\nRestart=on-failure\nRestartSec=5\nUMask=0077\n\n[Install]\nWantedBy=default.target\n`;
28
+ return `${marker}[Unit]\nDescription=Murmur agent daemon\nStartLimitIntervalSec=60\nStartLimitBurst=5\n\n[Service]\nType=simple\nWorkingDirectory=${c.repoRoot.replaceAll("%", "%%")}\nEnvironment=${q(`DATA_DIR=${c.dataDir}`)} ${q(`MURMUR_DATA_DIR=${c.dataDir}`)} ${q(`MURMUR_STORE_PATH=${c.storePath}`)} ${q(`MURMUR_CHANNEL_ROSTER_PATH=${path.join(c.dataDir, "channel-roster.db")}`)}\nExecStart=${arg(c.nodePath)} ${arg(path.join(c.repoRoot, "scripts", "murmur-daemon.mjs"))}\nStandardOutput=append:${path.join(c.logDir, `${c.serviceName}.out.log`).replaceAll("%", "%%")}\nStandardError=append:${path.join(c.logDir, `${c.serviceName}.err.log`).replaceAll("%", "%%")}\nRestart=on-failure\nRestartSec=5\nUMask=0077\n\n[Install]\nWantedBy=default.target\n`;
28
29
  }
29
30
  export function createLinuxAdapter(options = {}) {
30
31
  const env = options.env ?? process.env, home = options.homeDir ?? homedir();
32
+ const procRoot = options.procDir ?? "/proc";
31
33
  const run = options.run ?? (async (args) => {
32
34
  try {
33
35
  return (await exec("systemctl", ["--user", ...args], { timeout: 5000, maxBuffer: 256 * 1024 })).stdout;
@@ -76,8 +78,153 @@ export function createLinuxAdapter(options = {}) {
76
78
  if (await readOwned(c) !== renderLinuxUnit(c))
77
79
  throw new Error("service.profile-mismatch");
78
80
  }
81
+ async function observeStore(c, pid) {
82
+ check(c);
83
+ if (!Number.isSafeInteger(pid) || pid <= 0)
84
+ return null;
85
+ try {
86
+ const expected = await realpath(c.storePath), fdDir = path.join(options.procDir ?? "/proc", String(pid), "fd");
87
+ for (const fd of await readdir(fdDir)) {
88
+ try {
89
+ if (await realpath(path.join(fdDir, fd)) === expected)
90
+ return expected;
91
+ }
92
+ catch { }
93
+ }
94
+ }
95
+ catch { /* Inaccessible or exited processes are not liveness evidence. */ }
96
+ return null;
97
+ }
98
+ const usageUnknown = (reason = "profile-usage.probe-unavailable") => ({ state: "unknown", reason });
99
+ const processUnknown = (reason = "profile-usage.process-unverifiable") => { throw new ProfileUsageUnknown(reason); };
100
+ function startTime(pid, value) {
101
+ if (!value.startsWith(`${pid} (`))
102
+ return processUnknown();
103
+ const close = value.lastIndexOf(")");
104
+ if (close < pid.length + 2)
105
+ return processUnknown();
106
+ const fields = value.slice(close + 1).trim().split(/\s+/);
107
+ const started = fields[19];
108
+ if (fields.length < 20 || !/^\d+$/.test(started ?? ""))
109
+ return processUnknown();
110
+ return started;
111
+ }
112
+ function credentialUids(status) {
113
+ const matches = [...status.matchAll(/^Uid:[ \t]+(\d+)[ \t]+(\d+)[ \t]+(\d+)[ \t]+(\d+)[ \t]*$/gm)];
114
+ if (matches.length !== 1)
115
+ return processUnknown();
116
+ const uids = matches[0].slice(1).map(Number);
117
+ if (uids.length !== 4 || uids.some(uid => !Number.isSafeInteger(uid) || uid < 0))
118
+ return processUnknown();
119
+ return uids;
120
+ }
121
+ async function processIdentity(pid) {
122
+ try {
123
+ const statFile = path.join(procRoot, pid, "stat");
124
+ const before = startTime(pid, await readFile(statFile, "utf8"));
125
+ const statusFile = path.join(procRoot, pid, "status");
126
+ const firstUids = credentialUids(await readFile(statusFile, "utf8"));
127
+ const secondUids = credentialUids(await readFile(statusFile, "utf8"));
128
+ const after = startTime(pid, await readFile(statFile, "utf8"));
129
+ if (before !== after)
130
+ return processUnknown("profile-usage.process-set-changed");
131
+ if (firstUids.some((uid, index) => uid !== secondUids[index])) {
132
+ return processUnknown("profile-usage.process-identity-changed");
133
+ }
134
+ return { uids: firstUids, started: before, proof: `${before}:${firstUids.join(":")}` };
135
+ }
136
+ catch (error) {
137
+ if (error instanceof ProfileUsageUnknown)
138
+ throw error;
139
+ return processUnknown();
140
+ }
141
+ }
142
+ async function visibleProcesses() {
143
+ let entries;
144
+ try {
145
+ entries = await readdir(procRoot, { withFileTypes: true });
146
+ }
147
+ catch {
148
+ return processUnknown();
149
+ }
150
+ const result = new Map();
151
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name, "en"))) {
152
+ if (!/^\d+$/.test(entry.name))
153
+ continue;
154
+ if (!entry.isDirectory())
155
+ return processUnknown();
156
+ if (entry.name === String(process.pid))
157
+ continue;
158
+ const identity = await processIdentity(entry.name);
159
+ result.set(entry.name, identity.proof);
160
+ }
161
+ for (const anchor of new Set(["1", String(process.ppid)])) {
162
+ if (!result.has(anchor))
163
+ return processUnknown("profile-usage.process-visibility-incomplete");
164
+ }
165
+ return result;
166
+ }
167
+ const sameProcesses = (a, b) => a.size === b.size && [...a].every(([pid, proof]) => b.get(pid) === proof);
168
+ async function profileUsage(c) {
169
+ check(c);
170
+ try {
171
+ const uid = process.getuid?.();
172
+ if (!Number.isSafeInteger(uid) || uid < 0)
173
+ return usageUnknown();
174
+ const profile = await verifiedProfileRoot(c);
175
+ const before = await visibleProcesses();
176
+ let held = false;
177
+ for (const [pid, identity] of before) {
178
+ if ((await processIdentity(pid)).proof !== identity)
179
+ return usageUnknown("profile-usage.process-identity-changed");
180
+ let descriptors;
181
+ try {
182
+ descriptors = (await readdir(path.join(procRoot, pid, "fd"))).sort();
183
+ }
184
+ catch {
185
+ return usageUnknown("profile-usage.process-unverifiable");
186
+ }
187
+ for (const descriptor of descriptors) {
188
+ if (!/^\d+$/.test(descriptor))
189
+ return usageUnknown("profile-usage.process-unverifiable");
190
+ let target;
191
+ try {
192
+ target = await readlink(path.join(procRoot, pid, "fd", descriptor));
193
+ }
194
+ catch {
195
+ return usageUnknown("profile-usage.process-unverifiable");
196
+ }
197
+ if (/^(?:socket|pipe):\[\d+\]$/.test(target) || /^anon_inode:\[[^\]\r\n]+\]$/.test(target))
198
+ continue;
199
+ if (/^\/memfd:[^\r\n]+(?: \(deleted\))?$/.test(target))
200
+ continue;
201
+ const classification = await classifyProfilePath(profile.root, target);
202
+ if (classification === "unknown")
203
+ return usageUnknown("profile-usage.process-unverifiable");
204
+ if (classification === "inside")
205
+ held = true;
206
+ }
207
+ if ((await processIdentity(pid)).proof !== identity)
208
+ return usageUnknown("profile-usage.process-identity-changed");
209
+ }
210
+ if (held)
211
+ return { state: "in-use", reason: "profile-usage.open-file" };
212
+ const after = await visibleProcesses();
213
+ if (!sameProcesses(before, after))
214
+ return usageUnknown("profile-usage.process-set-changed");
215
+ const profileAfter = await verifiedProfileRoot(c);
216
+ if (profileAfter.root !== profile.root || profileAfter.proof !== profile.proof) {
217
+ return usageUnknown("profile-usage.profile-changed");
218
+ }
219
+ return { state: "free", reason: "profile-usage.no-open-files" };
220
+ }
221
+ catch (error) {
222
+ return usageUnknown(error instanceof ProfileUsageUnknown ? error.reason : undefined);
223
+ }
224
+ }
79
225
  return {
80
226
  manager: "systemd",
227
+ observeStore,
81
228
  async status(c) {
82
229
  check(c);
83
230
  const result = { state: "unknown", manager: "systemd", since: null, pid: null,
@@ -98,21 +245,8 @@ export function createLinuxAdapter(options = {}) {
98
245
  result.lastExitCode = /^\d+$/.test(values.ExecMainStatus ?? "") ? Number(values.ExecMainStatus) : null;
99
246
  const started = Date.parse(values.ActiveEnterTimestamp ?? "");
100
247
  result.since = Number.isFinite(started) ? new Date(started).toISOString() : null;
101
- if (result.pid) {
102
- try {
103
- const expected = await realpath(c.storePath), fdDir = path.join(options.procDir ?? "/proc", String(result.pid), "fd");
104
- for (const fd of await readdir(fdDir)) {
105
- try {
106
- if (await readlink(path.join(fdDir, fd)) === expected) {
107
- result.observedStorePath = expected;
108
- break;
109
- }
110
- }
111
- catch { }
112
- }
113
- }
114
- catch { /* Inaccessible descriptors mean unverified, not guessed from config. */ }
115
- }
248
+ if (result.pid)
249
+ result.observedStorePath = await observeStore(c, result.pid);
116
250
  return result;
117
251
  },
118
252
  async install(c) {
@@ -172,5 +306,6 @@ export function createLinuxAdapter(options = {}) {
172
306
  }
173
307
  return rows;
174
308
  },
309
+ profileUsage,
175
310
  };
176
311
  }
@@ -0,0 +1,20 @@
1
+ import type { ServiceContext } from "../types.js";
2
+ export interface VerifiedProfileRoot {
3
+ root: string;
4
+ /** Opaque tree identity used only to reject changes during a free snapshot. */
5
+ proof: string;
6
+ }
7
+ export declare class ProfileUsageUnknown extends Error {
8
+ readonly reason: string;
9
+ constructor(reason: string);
10
+ }
11
+ export declare function isWithinProfile(root: string, candidate: string): boolean;
12
+ /**
13
+ * Require an owner-only selected root, then inspect its tree without following
14
+ * aliases. Platform probes must still cover every visible process because a
15
+ * privileged foreign UID can traverse the root. Aliases, mount crossings,
16
+ * unsupported entries, hardlinks, or concurrent changes make the snapshot incomplete.
17
+ */
18
+ export declare function verifiedProfileRoot(context: ServiceContext): Promise<VerifiedProfileRoot>;
19
+ /** Classify one kernel/tool pathname after the profile tree passed verification. */
20
+ export declare function classifyProfilePath(root: string, raw: string): Promise<"inside" | "outside" | "unknown">;
@@ -0,0 +1,89 @@
1
+ import * as fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ const maximumEntries = 10_000;
4
+ export class ProfileUsageUnknown extends Error {
5
+ reason;
6
+ constructor(reason) {
7
+ super(reason);
8
+ this.reason = reason;
9
+ }
10
+ }
11
+ const unknown = (reason) => { throw new ProfileUsageUnknown(reason); };
12
+ export function isWithinProfile(root, candidate) {
13
+ const relative = path.relative(root, candidate);
14
+ return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative));
15
+ }
16
+ /**
17
+ * Require an owner-only selected root, then inspect its tree without following
18
+ * aliases. Platform probes must still cover every visible process because a
19
+ * privileged foreign UID can traverse the root. Aliases, mount crossings,
20
+ * unsupported entries, hardlinks, or concurrent changes make the snapshot incomplete.
21
+ */
22
+ export async function verifiedProfileRoot(context) {
23
+ let root;
24
+ try {
25
+ const selected = await fs.lstat(context.dataDir);
26
+ if (selected.isSymbolicLink() || !selected.isDirectory() || (selected.mode & 0o077) !== 0) {
27
+ return unknown("profile-usage.profile-unverifiable");
28
+ }
29
+ const uid = process.getuid?.();
30
+ if (uid === undefined || selected.uid !== uid)
31
+ return unknown("profile-usage.profile-unverifiable");
32
+ root = await fs.realpath(context.dataDir);
33
+ if (root !== context.dataDir)
34
+ return unknown("profile-usage.profile-unverifiable");
35
+ const rootInfo = await fs.stat(root);
36
+ if (selected.dev !== rootInfo.dev || selected.ino !== rootInfo.ino || rootInfo.uid !== uid || (rootInfo.mode & 0o077) !== 0) {
37
+ return unknown("profile-usage.profile-unverifiable");
38
+ }
39
+ const directories = [{ absolute: root, relative: "" }];
40
+ const proof = [["", rootInfo.dev, rootInfo.ino, rootInfo.mode, rootInfo.uid, rootInfo.gid, rootInfo.nlink]];
41
+ let seen = 0;
42
+ while (directories.length) {
43
+ const directory = directories.pop();
44
+ const names = [];
45
+ for await (const entry of await fs.opendir(directory.absolute)) {
46
+ if (++seen > maximumEntries)
47
+ return unknown("profile-usage.profile-unverifiable");
48
+ names.push(entry.name);
49
+ }
50
+ names.sort();
51
+ for (const name of names) {
52
+ const file = path.join(directory.absolute, name);
53
+ const relative = path.join(directory.relative, name);
54
+ const info = await fs.lstat(file);
55
+ if (info.isSymbolicLink() || info.dev !== rootInfo.dev)
56
+ return unknown("profile-usage.profile-unverifiable");
57
+ if (info.isFile() && info.nlink !== 1)
58
+ return unknown("profile-usage.profile-hard-linked");
59
+ proof.push([relative, info.dev, info.ino, info.mode, info.uid, info.gid, info.nlink]);
60
+ if (info.isDirectory())
61
+ directories.push({ absolute: file, relative });
62
+ else if (!info.isFile())
63
+ return unknown("profile-usage.profile-unverifiable");
64
+ }
65
+ }
66
+ return { root, proof: JSON.stringify(proof) };
67
+ }
68
+ catch (error) {
69
+ if (error instanceof ProfileUsageUnknown)
70
+ throw error;
71
+ return unknown("profile-usage.profile-unverifiable");
72
+ }
73
+ }
74
+ /** Classify one kernel/tool pathname after the profile tree passed verification. */
75
+ export async function classifyProfilePath(root, raw) {
76
+ if (!path.isAbsolute(raw) || /[\0\r\n]/.test(raw))
77
+ return "unknown";
78
+ const deleted = raw.endsWith(" (deleted)");
79
+ const candidate = path.normalize(deleted ? raw.slice(0, -" (deleted)".length) : raw);
80
+ if (deleted)
81
+ return "unknown";
82
+ try {
83
+ const canonical = await fs.realpath(candidate);
84
+ return isWithinProfile(root, canonical) ? "inside" : "outside";
85
+ }
86
+ catch {
87
+ return "unknown";
88
+ }
89
+ }