@murmurv2/cli 2.12.0 → 2.14.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 (64) hide show
  1. package/README.md +65 -24
  2. package/package.json +7 -6
  3. package/runtime/bin/murmur-svc.exe +0 -0
  4. package/runtime/npm-runtime-manifest.json +175 -79
  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 +3 -2
  8. package/runtime/packages/setup/dist/src/autoreply.d.ts +23 -0
  9. package/runtime/packages/setup/dist/src/autoreply.js +71 -0
  10. package/runtime/packages/setup/dist/src/backups.d.ts +36 -0
  11. package/runtime/packages/setup/dist/src/backups.js +128 -0
  12. package/runtime/packages/setup/dist/src/broker-input.d.ts +24 -0
  13. package/runtime/packages/setup/dist/src/broker-input.js +98 -0
  14. package/runtime/packages/setup/dist/src/broker-migration.d.ts +35 -0
  15. package/runtime/packages/setup/dist/src/broker-migration.js +138 -0
  16. package/runtime/packages/setup/dist/src/cli-error.d.ts +2 -0
  17. package/runtime/packages/setup/dist/src/cli-error.js +30 -0
  18. package/runtime/packages/setup/dist/src/cli.js +113 -10
  19. package/runtime/packages/setup/dist/src/clients.d.ts +33 -81
  20. package/runtime/packages/setup/dist/src/clients.js +159 -25
  21. package/runtime/packages/setup/dist/src/commands.d.ts +1 -0
  22. package/runtime/packages/setup/dist/src/commands.js +18 -6
  23. package/runtime/packages/setup/dist/src/config.d.ts +8 -0
  24. package/runtime/packages/setup/dist/src/config.js +58 -10
  25. package/runtime/packages/setup/dist/src/connect.d.ts +143 -0
  26. package/runtime/packages/setup/dist/src/connect.js +128 -0
  27. package/runtime/packages/setup/dist/src/conversations.d.ts +193 -0
  28. package/runtime/packages/setup/dist/src/conversations.js +674 -0
  29. package/runtime/packages/setup/dist/src/doctor.d.ts +30 -0
  30. package/runtime/packages/setup/dist/src/doctor.js +72 -10
  31. package/runtime/packages/setup/dist/src/installation.d.ts +25 -0
  32. package/runtime/packages/setup/dist/src/installation.js +89 -0
  33. package/runtime/packages/setup/dist/src/message-status.d.ts +1 -0
  34. package/runtime/packages/setup/dist/src/message-status.js +3 -0
  35. package/runtime/packages/setup/dist/src/onboarding.d.ts +11 -6
  36. package/runtime/packages/setup/dist/src/onboarding.js +92 -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 +247 -9
  41. package/runtime/packages/setup/dist/src/platform/linux.js +156 -12
  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 +48 -8
  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 +9 -0
  50. package/runtime/packages/setup/dist/src/status.js +7 -3
  51. package/runtime/packages/setup/dist/src/types.d.ts +11 -1
  52. package/runtime/packages/setup/dist/src/wake-readers.d.ts +12 -0
  53. package/runtime/packages/setup/dist/src/wake-readers.js +65 -0
  54. package/runtime/packages/setup/package.json +1 -1
  55. package/runtime/scripts/auth-security.mjs +93 -0
  56. package/runtime/scripts/codex-app-server-wake.mjs +36 -4
  57. package/runtime/scripts/daemon-contacts.mjs +1 -1
  58. package/runtime/scripts/murmur-auth-token.mjs +140 -0
  59. package/runtime/scripts/murmur-daemon.mjs +27 -8
  60. package/runtime/scripts/murmur-jetstream-advisory.mjs +27 -0
  61. package/runtime/scripts/murmur-shell-send.mjs +7 -3
  62. package/runtime/scripts/owner-review-store.mjs +54 -0
  63. package/runtime/scripts/wake-drain-claude.mjs +124 -7
  64. package/runtime/scripts/wake-monitor.mjs +49 -10
@@ -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
+ }
@@ -17,6 +17,13 @@ export function helperReason(stderr) {
17
17
  const object = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
18
18
  const natural = (v) => Number.isSafeInteger(v) && Number(v) >= 0;
19
19
  const textOrNull = (v) => v === null || typeof v === 'string';
20
+ const usageUnknown = () => ({ state: 'unknown', reason: 'profile.probe-unavailable' });
21
+ const profileUsageReasons = new Map([
22
+ ['profile.store-held', 'in-use'], ['profile.store-unheld', 'free'],
23
+ ['profile.store-missing', 'unknown'], ['profile.store-invalid', 'unknown'],
24
+ ['profile.probe-unavailable', 'unknown'], ['profile.managed-running-unobserved', 'unknown'],
25
+ ['profile.service-unverifiable', 'unknown'],
26
+ ]);
20
27
  function absolute(value) {
21
28
  if (typeof value !== 'string' || !paths.isAbsolute(value) || paths.normalize(value) !== value || /[\x00-\x1f\x7f]/.test(value))
22
29
  fail('invalid-path');
@@ -77,7 +84,7 @@ export function createWindowsAdapter(options = {}) {
77
84
  }
78
85
  async function invoke(c, action) {
79
86
  validate(c);
80
- const result = await run(await helper(c), [action], { env: selectedEnvironment(c), timeout: action === 'status' ? 8000 : 55000 });
87
+ const result = await run(await helper(c), [action], { env: selectedEnvironment(c), timeout: action === 'status' || action === 'profile-usage' ? 8000 : 55000 });
81
88
  if (result.code !== 0)
82
89
  fail(helperReason(result.stderr));
83
90
  return result.stdout;
@@ -227,26 +234,59 @@ export function createWindowsAdapter(options = {}) {
227
234
  }
228
235
  },
229
236
  install: c => mutate(c, 'install'), start: c => mutate(c, 'start'), stop: c => mutate(c, 'stop'), uninstall: c => mutate(c, 'uninstall'),
237
+ async profileUsage(c) {
238
+ try {
239
+ const value = JSON.parse(await invoke(c, 'profile-usage'));
240
+ if (!object(value) || Object.keys(value).sort().join(',') !== 'reason,schema,state'
241
+ || value.schema !== 'murmur.windows-profile-usage/1'
242
+ || !['free', 'in-use', 'unknown'].includes(value.state)
243
+ || typeof value.reason !== 'string' || profileUsageReasons.get(value.reason) !== value.state)
244
+ return usageUnknown();
245
+ return { state: value.state, reason: value.reason };
246
+ }
247
+ catch {
248
+ return usageUnknown();
249
+ }
250
+ },
230
251
  async detectClients() {
231
- const rows = [];
232
- for (const [id, command, configPath, format] of [
233
- ['claude-code', 'claude', env.CLAUDE_CONFIG_DIR ? null : paths.join(home, '.claude.json'), 'json'],
234
- ['codex-cli', 'codex', paths.join(env.CODEX_HOME || paths.join(home, '.codex'), 'config.toml'), 'toml'],
235
- ]) {
236
- let installed = false;
252
+ const hasExecutable = async (command) => {
237
253
  for (const dir of (env.PATH ?? env.Path ?? '').split(';')) {
238
254
  if (!paths.isAbsolute(dir))
239
255
  continue;
240
256
  for (const suffix of ['.exe', '.cmd', '.bat']) {
241
257
  try {
242
258
  if ((await stat(paths.join(dir, command + suffix))).isFile())
243
- installed = true;
259
+ return true;
244
260
  }
245
261
  catch { }
246
262
  }
247
263
  }
264
+ return false;
265
+ };
266
+ const hasDirectory = async (dirPath) => (await stat(dirPath).catch(() => null))?.isDirectory() === true;
267
+ const joinFs = process.platform === 'win32' || /^[A-Za-z]:/.test(home) || home.includes('\\') ? paths.join : path.join;
268
+ const rows = [];
269
+ for (const [id, command, configPath, format] of [
270
+ ['claude-code', 'claude', env.CLAUDE_CONFIG_DIR ? null : paths.join(home, '.claude.json'), 'json'],
271
+ ['codex-cli', 'codex', paths.join(env.CODEX_HOME || paths.join(home, '.codex'), 'config.toml'), 'toml'],
272
+ ]) {
273
+ const installed = await hasExecutable(command);
248
274
  rows.push({ id, installed, configPath: configPath && paths.isAbsolute(configPath) ? configPath : null, format });
249
275
  }
276
+ const cursorConfig = paths.join(home, '.cursor', 'mcp.json');
277
+ rows.push({
278
+ id: 'cursor',
279
+ installed: (await hasExecutable('cursor')) || (await hasExecutable('agent')) || (await hasDirectory(joinFs(home, '.cursor'))),
280
+ configPath: paths.isAbsolute(cursorConfig) ? cursorConfig : null,
281
+ format: 'json',
282
+ });
283
+ const geminiConfig = paths.join(home, '.gemini', 'config', 'mcp_config.json');
284
+ rows.push({
285
+ id: 'gemini',
286
+ installed: (await hasExecutable('agy')) || (await hasExecutable('gemini')) || (await hasDirectory(joinFs(home, '.gemini'))),
287
+ configPath: paths.isAbsolute(geminiConfig) ? geminiConfig : null,
288
+ format: 'json',
289
+ });
250
290
  return rows;
251
291
  },
252
292
  };
@@ -1,5 +1,8 @@
1
1
  import { type FileHandle } from 'node:fs/promises';
2
+ import type { BigIntStats } from 'node:fs';
2
3
  /** Protect a newly created, still-empty setup output before writing credentials. */
3
4
  export declare function protectPrivateFile(file: string, handle: FileHandle): Promise<void>;
4
- /** Existing Windows files keep their access policy, including intentional sandbox readers. */
5
+ /** Existing Windows files keep their owner and access policy, including intentional sandbox readers. */
5
6
  export declare function preparePrivateReplacement(file: string, handle: FileHandle, previous: string): Promise<void>;
7
+ /** Read-only verification for backup cleanup; never repair an unexpectedly public backup. */
8
+ export declare function verifyPrivateFileAccess(file: string, info: BigIntStats): Promise<void>;
@@ -28,7 +28,11 @@ if ($source) {
28
28
  $expected = $original.GetSecurityDescriptorSddlForm($section)
29
29
  $security.SetSecurityDescriptorSddlForm($expected, $section)
30
30
  $expectedPolicy = AccessPolicy $original
31
+ $expectedOwner = $original.GetOwner([System.Security.Principal.SecurityIdentifier])
31
32
  } else {
33
+ # An elevated token may default new files to the Administrators group owner.
34
+ # Pin this still-empty output to its actual creator before writing any secrets.
35
+ $expectedOwner = New-Object System.Security.Principal.SecurityIdentifier($user)
32
36
  $security.SetAccessRuleProtection($true, $false)
33
37
  foreach ($id in $allowed) {
34
38
  $sid = New-Object System.Security.Principal.SecurityIdentifier($id)
@@ -36,11 +40,15 @@ if ($source) {
36
40
  $security.AddAccessRule($rule)
37
41
  }
38
42
  }
43
+ $security.SetOwner($expectedOwner)
39
44
  Set-Acl -LiteralPath $file -AclObject $security
40
45
  $actual = Get-Acl -LiteralPath $file
46
+ if ($actual.GetOwner([System.Security.Principal.SecurityIdentifier]).Value -ne $expectedOwner.Value) { throw 'unexpected owner' }
41
47
  if ($source) {
48
+ $sourceAfter = Get-Acl -LiteralPath $source
42
49
  if ((AccessPolicy $actual) -cne $expectedPolicy -or
43
- (AccessPolicy (Get-Acl -LiteralPath $source)) -cne $expectedPolicy) { throw 'changed access policy' }
50
+ (AccessPolicy $sourceAfter) -cne $expectedPolicy -or
51
+ $sourceAfter.GetOwner([System.Security.Principal.SecurityIdentifier]).Value -ne $expectedOwner.Value) { throw 'changed access policy' }
44
52
  exit 0
45
53
  }
46
54
  if (!$actual.AreAccessRulesProtected) { throw 'unprotected ACL' }
@@ -76,7 +84,7 @@ async function prepareFile(file, handle, accessSource) {
76
84
  catch (error) {
77
85
  // Keep paths, command text and arbitrary PowerShell stderr out of diagnostics.
78
86
  const failure = error;
79
- const rejection = ['changed access policy', 'unprotected ACL', 'unexpected ACL entries', 'unexpected ACL']
87
+ const rejection = ['changed access policy', 'unprotected ACL', 'unexpected ACL entries', 'unexpected ACL', 'unexpected owner']
80
88
  .find(reason => failure.stderr?.includes(reason));
81
89
  const reason = failure.killed ? 'timeout' : failure.code === 'ENOENT' ? 'powershell-unavailable'
82
90
  : rejection?.replaceAll(' ', '-') ?? 'command-failed';
@@ -95,7 +103,35 @@ async function prepareFile(file, handle, accessSource) {
95
103
  export async function protectPrivateFile(file, handle) {
96
104
  return prepareFile(file, handle);
97
105
  }
98
- /** Existing Windows files keep their access policy, including intentional sandbox readers. */
106
+ /** Existing Windows files keep their owner and access policy, including intentional sandbox readers. */
99
107
  export async function preparePrivateReplacement(file, handle, previous) {
100
108
  return prepareFile(file, handle, previous);
101
109
  }
110
+ /** Read-only verification for backup cleanup; never repair an unexpectedly public backup. */
111
+ export async function verifyPrivateFileAccess(file, info) {
112
+ if (process.platform !== 'win32') {
113
+ if ((info.mode & 63n) !== 0n)
114
+ throw new Error('backups.permissions-invalid');
115
+ return;
116
+ }
117
+ const script = `
118
+ $ErrorActionPreference = 'Stop'
119
+ $env:PSModulePath = [System.IO.Path]::Combine($PSHOME, 'Modules')
120
+ $acl = Get-Acl -LiteralPath $env:MURMUR_SETUP_PRIVATE_FILE
121
+ $user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value
122
+ $allowed = @($user, 'S-1-5-18') | Select-Object -Unique
123
+ if (!$acl.AreAccessRulesProtected -or $acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Value -ne $user) { throw 'invalid' }
124
+ $rules = @($acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier]))
125
+ if ($rules.Count -ne $allowed.Count) { throw 'invalid' }
126
+ foreach ($rule in $rules) {
127
+ if ($allowed -notcontains $rule.IdentityReference.Value -or $rule.AccessControlType -ne 'Allow' -or
128
+ $rule.FileSystemRights -ne [System.Security.AccessControl.FileSystemRights]::FullControl -or $rule.IsInherited) { throw 'invalid' }
129
+ }
130
+ `;
131
+ try {
132
+ await exec(path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'), ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], { env: { ...process.env, MURMUR_SETUP_PRIVATE_FILE: file }, windowsHide: true, timeout: 60_000, maxBuffer: 64 * 1024 });
133
+ }
134
+ catch {
135
+ throw new Error('backups.permissions-invalid');
136
+ }
137
+ }
@@ -1,3 +1,7 @@
1
1
  import type { ServiceContext } from "./types.js";
2
2
  /** Reuse the runtime's existing private-state writer; setup ships with that runtime. */
3
3
  export declare function writeState(c: ServiceContext, file: string, value: unknown): Promise<void>;
4
+ /** Create a byte-exact, private, non-overwriting recovery file beside the profile. */
5
+ export declare function writeExactBackup(c: ServiceContext, file: string, bytes: Buffer): Promise<void>;
6
+ /** Restore exact reviewed bytes atomically while retaining the backup until verification succeeds. */
7
+ export declare function restoreExactBackup(c: ServiceContext, backup: string, target: string, bytes: Buffer): Promise<void>;
@@ -1,6 +1,9 @@
1
+ import { constants } from "node:fs";
2
+ import { open, rename, unlink } from "node:fs/promises";
3
+ import { randomUUID } from "node:crypto";
1
4
  import path from "node:path";
2
5
  import { pathToFileURL } from "node:url";
3
- import { preparePrivateReplacement } from "./private-file.js";
6
+ import { preparePrivateReplacement, protectPrivateFile } from "./private-file.js";
4
7
  /** Reuse the runtime's existing private-state writer; setup ships with that runtime. */
5
8
  export async function writeState(c, file, value) {
6
9
  if (path.dirname(file) !== c.dataDir)
@@ -10,3 +13,64 @@ export async function writeState(c, file, value) {
10
13
  beforeWrite: (temporary, handle) => preparePrivateReplacement(temporary, handle, file),
11
14
  });
12
15
  }
16
+ async function syncDirectory(dir) {
17
+ if (process.platform === "win32")
18
+ return;
19
+ const handle = await open(dir, constants.O_RDONLY | constants.O_DIRECTORY);
20
+ try {
21
+ await handle.sync();
22
+ }
23
+ finally {
24
+ await handle.close();
25
+ }
26
+ }
27
+ /** Create a byte-exact, private, non-overwriting recovery file beside the profile. */
28
+ export async function writeExactBackup(c, file, bytes) {
29
+ if (path.dirname(file) !== c.dataDir || bytes.length > 4 * 1024 * 1024)
30
+ throw new Error("state.backup-invalid");
31
+ let handle;
32
+ let created = false;
33
+ try {
34
+ handle = await open(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);
35
+ created = true;
36
+ await protectPrivateFile(file, handle);
37
+ await handle.writeFile(bytes);
38
+ await handle.sync();
39
+ await handle.close();
40
+ handle = undefined;
41
+ await syncDirectory(c.dataDir);
42
+ }
43
+ catch (error) {
44
+ if (handle)
45
+ await handle.close().catch(() => { });
46
+ if (created)
47
+ await unlink(file).catch(() => { });
48
+ throw error;
49
+ }
50
+ }
51
+ /** Restore exact reviewed bytes atomically while retaining the backup until verification succeeds. */
52
+ export async function restoreExactBackup(c, backup, target, bytes) {
53
+ if (path.dirname(backup) !== c.dataDir || target !== c.configPath)
54
+ throw new Error("state.restore-invalid");
55
+ const temp = path.join(c.dataDir, `.agent-config.restore-${process.pid}-${randomUUID()}.tmp`);
56
+ let handle;
57
+ let created = false;
58
+ try {
59
+ handle = await open(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);
60
+ created = true;
61
+ await preparePrivateReplacement(temp, handle, target);
62
+ await handle.writeFile(bytes);
63
+ await handle.sync();
64
+ await handle.close();
65
+ handle = undefined;
66
+ await rename(temp, target);
67
+ await syncDirectory(c.dataDir);
68
+ }
69
+ catch (error) {
70
+ if (handle)
71
+ await handle.close().catch(() => { });
72
+ if (created)
73
+ await unlink(temp).catch(() => { });
74
+ throw error;
75
+ }
76
+ }
@@ -119,6 +119,15 @@ export declare function readStatus({ context: c, adapter, now }: StatusOptions):
119
119
  };
120
120
  };
121
121
  wake: {
122
+ readers: {
123
+ active: number | null;
124
+ measuredAt: string;
125
+ unknownReason: string;
126
+ } | {
127
+ active: number;
128
+ measuredAt: string;
129
+ unknownReason: null;
130
+ };
122
131
  config: {
123
132
  enabled: boolean | null;
124
133
  mode: "none" | "hook" | "monitor" | null;
@@ -4,7 +4,8 @@ import { realpath } from "node:fs/promises";
4
4
  import { createHash } from "node:crypto";
5
5
  import { loadConfig, readJson, safeError, validAgentId } from "./config.js";
6
6
  import { readOutboxAttention } from "./outbox-attention.js";
7
- import { assistantRead, wakeColumns } from "./message-status.js";
7
+ import { assistantRead, wakeColumns, personalInboxSql } from "./message-status.js";
8
+ import { readWakeReaders } from './wake-readers.js';
8
9
  const measured = (at) => ({ measuredAt: at, unknownReason: null });
9
10
  const unknown = (reason) => ({ measuredAt: null, unknownReason: reason });
10
11
  export const pairFingerprint = (config, peerId) => createHash("sha256").update(JSON.stringify([
@@ -119,7 +120,9 @@ export async function readStatus({ context: c, adapter, now = Date.now }) {
119
120
  try {
120
121
  db = new DatabaseSync(c.storePath, { readOnly: true });
121
122
  db.exec("PRAGMA busy_timeout=1000; BEGIN");
122
- const summary = db.prepare("SELECT COUNT(*) AS total, MAX(created_at) AS lastAt, COALESCE(MAX(rowid),0) AS tip FROM local_messages WHERE direction='inbound'").get();
123
+ const summary = db.prepare(`SELECT COUNT(CASE WHEN ${personalInboxSql} THEN 1 END) AS total,
124
+ MAX(CASE WHEN ${personalInboxSql} THEN created_at END) AS lastAt,
125
+ COALESCE(MAX(rowid),0) AS tip FROM local_messages WHERE direction='inbound'`).get();
123
126
  inbox.total = Number(summary.total);
124
127
  inbox.lastAt = summary.lastAt;
125
128
  inbox.measurements.store = measured(at);
@@ -128,7 +131,7 @@ export async function readStatus({ context: c, adapter, now = Date.now }) {
128
131
  if (cursor.schema !== "murmur.read/1" || cursor.agentId !== config?.agentId || !Number.isSafeInteger(cursor.rowid)
129
132
  || cursor.rowid < 0 || cursor.rowid > Number(summary.tip))
130
133
  throw new Error("inbox.cursor-invalid");
131
- inbox.unread = Number(db.prepare("SELECT COUNT(*) AS n FROM local_messages WHERE direction='inbound' AND rowid>?").get(cursor.rowid).n);
134
+ inbox.unread = Number(db.prepare(`SELECT COUNT(*) AS n FROM local_messages WHERE direction='inbound' AND ${personalInboxSql} AND rowid>?`).get(cursor.rowid).n);
132
135
  inbox.measurements.cursor = measured(at);
133
136
  }
134
137
  catch { /* A missing cursor is not an empty inbox. */ }
@@ -233,6 +236,7 @@ export async function readStatus({ context: c, adapter, now = Date.now }) {
233
236
  unknownReason: outbox.measurements.store.unknownReason, source: "durable-outbox" },
234
237
  },
235
238
  wake: {
239
+ readers: await readWakeReaders(c),
236
240
  config: { enabled: config ? config.wake?.enabled !== false : null,
237
241
  mode: config ? configuredWakeMode(config) : null,
238
242
  responder: config ? configuredWakeMode(config) === "monitor" ? "codex" : config.onReceive ? null : "none" : null,
@@ -7,6 +7,8 @@ export interface ServiceContext {
7
7
  nodePath: string;
8
8
  logDir: string;
9
9
  serviceName: string;
10
+ /** Explicit project-scoped Claude Code connection; never inferred from cwd. */
11
+ clientProjectDir?: string;
10
12
  }
11
13
  export type ServiceManager = "windows-service" | "scheduled-task" | "launchd" | "systemd" | "none";
12
14
  export interface ServiceSnapshot {
@@ -23,12 +25,18 @@ export interface ServiceSnapshot {
23
25
  detail?: string;
24
26
  }
25
27
  export interface ClientDetection {
26
- id: "claude-code" | "claude-desktop" | "codex-cli" | "codex-desktop";
28
+ id: "claude-code" | "claude-desktop" | "codex-cli" | "codex-desktop" | "cursor" | "gemini";
27
29
  installed: boolean;
28
30
  configPath: string | null;
29
31
  format: "json" | "toml";
30
32
  detail?: string;
31
33
  }
34
+ /** Point-in-time, read-only evidence about use of one resolved profile. */
35
+ export interface ProfileUsageSnapshot {
36
+ state: "free" | "in-use" | "unknown";
37
+ /** Stable, non-secret reason code. Callers must not treat it as proof beyond this observation. */
38
+ reason: string;
39
+ }
32
40
  export interface PlatformAdapter {
33
41
  manager: ServiceManager;
34
42
  status(context: ServiceContext): Promise<ServiceSnapshot>;
@@ -47,4 +55,6 @@ export interface PlatformAdapter {
47
55
  detectClients(context: ServiceContext): Promise<ClientDetection[]>;
48
56
  /** Native log location, after verifying the selected service owns this profile. */
49
57
  logDirectory?(context: ServiceContext): Promise<string>;
58
+ /** Optional until a platform has an independently reviewed native profile-usage probe. */
59
+ profileUsage?(context: ServiceContext): Promise<ProfileUsageSnapshot>;
50
60
  }
@@ -0,0 +1,12 @@
1
+ import type { ServiceContext } from './types.js';
2
+ /** A lock alone is not a live reader. Verify its PID and the drain's selected DB.
3
+ * Unknown process inspection stays unknown; this never deletes stale locks. */
4
+ export declare function readWakeReaders(c: ServiceContext, home?: string): Promise<{
5
+ active: number | null;
6
+ measuredAt: string;
7
+ unknownReason: string;
8
+ } | {
9
+ active: number;
10
+ measuredAt: string;
11
+ unknownReason: null;
12
+ }>;
@@ -0,0 +1,65 @@
1
+ import { readdir, readFile, lstat } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import path from 'node:path';
4
+ import { createHash } from 'node:crypto';
5
+ import { execFile } from 'node:child_process';
6
+ import { promisify } from 'node:util';
7
+ const run = promisify(execFile);
8
+ /** A lock alone is not a live reader. Verify its PID and the drain's selected DB.
9
+ * Unknown process inspection stays unknown; this never deletes stale locks. */
10
+ export async function readWakeReaders(c, home = homedir()) {
11
+ const measuredAt = new Date().toISOString();
12
+ const unknown = (reason) => ({ active: null, measuredAt, unknownReason: reason });
13
+ if (!['linux', 'darwin'].includes(process.platform))
14
+ return unknown('wake.readers-platform-unavailable');
15
+ const store = path.resolve(c.storePath);
16
+ const key = createHash('sha256').update(store).digest('hex').slice(0, 8);
17
+ let files;
18
+ try {
19
+ files = (await readdir(home)).filter(name => new RegExp(`^\\.murmur-wake-lock-${key}(?:-[A-Za-z0-9_-]{1,8})?$`).test(name));
20
+ }
21
+ catch {
22
+ return unknown('wake.readers-directory-unavailable');
23
+ }
24
+ let active = 0;
25
+ for (const name of files) {
26
+ const file = path.join(home, name);
27
+ try {
28
+ const info = await lstat(file);
29
+ if (!info.isFile() || info.size > 64)
30
+ return unknown('wake.reader-lock-unverified');
31
+ const raw = await readFile(file, 'utf8'), pid = Number(raw.trim());
32
+ if (!Number.isSafeInteger(pid) || pid <= 0)
33
+ return unknown('wake.reader-lock-unverified');
34
+ try {
35
+ process.kill(pid, 0);
36
+ }
37
+ catch (error) {
38
+ if (error.code === 'ESRCH')
39
+ continue;
40
+ return unknown('wake.reader-process-unavailable');
41
+ }
42
+ let matches = false;
43
+ if (process.platform === 'linux') {
44
+ const args = (await readFile(`/proc/${pid}/cmdline`, 'utf8')).split('\0');
45
+ matches = args.some(arg => arg.endsWith('/wake-drain-claude.mjs'))
46
+ && args[args.indexOf('--db') + 1] === store;
47
+ }
48
+ else {
49
+ const { stdout } = await run('/bin/ps', ['-p', String(pid), '-o', 'command='], { timeout: 2000, maxBuffer: 32768 });
50
+ matches = stdout.includes('/wake-drain-claude.mjs ') && stdout.includes(`--db ${store} `);
51
+ }
52
+ if (await readFile(file, 'utf8') !== raw)
53
+ return unknown('wake.reader-lock-changed');
54
+ if (!matches)
55
+ return unknown('wake.reader-process-unverified');
56
+ active++;
57
+ }
58
+ catch (error) {
59
+ if (error.code !== 'ENOENT')
60
+ return unknown('wake.reader-inspection-failed');
61
+ // The reader can finish between listing its lock and inspecting the process.
62
+ }
63
+ }
64
+ return { active, measuredAt, unknownReason: null };
65
+ }
@@ -1 +1 @@
1
- {"name":"@murmurv2/cli","private":true,"version":"2.12.0","type":"module","main":"dist/src/index.js","types":"dist/src/index.d.ts"}
1
+ {"name":"@murmurv2/cli","private":true,"version":"2.14.0","type":"module","main":"dist/src/index.js","types":"dist/src/index.d.ts"}
@@ -0,0 +1,93 @@
1
+ import path from "node:path";
2
+ import { RosterStore, authorizeInbound, parseAddress } from "@murmurv2/federation";
3
+ import { readPrivateJson } from "./secure-state.mjs";
4
+
5
+ export function normalizeAuthSecurity(config = {}, env = process.env, dataDir = ".") {
6
+ const settings = config.authz ?? {};
7
+ const rawEnforce = env.MURMUR_ENFORCE_AUTH ?? settings.enforce;
8
+ let enforce = false;
9
+ if (rawEnforce !== undefined) {
10
+ if (env.MURMUR_ENFORCE_AUTH !== undefined) {
11
+ if (rawEnforce === "1" || rawEnforce === "true") enforce = true;
12
+ else if (rawEnforce === "0" || rawEnforce === "false") enforce = false;
13
+ else throw new Error("auth-security-invalid:enforce");
14
+ } else if (typeof rawEnforce === "boolean") {
15
+ enforce = rawEnforce;
16
+ } else {
17
+ throw new Error("auth-security-invalid:enforce");
18
+ }
19
+ }
20
+ const localOrg = String(env.MURMUR_AUTH_LOCAL_ORG ?? settings.localOrg ?? "local").trim();
21
+ const agentId = String(config.agentId ?? "probe").trim();
22
+ const audience = parseAddress(agentId, localOrg);
23
+ const explicitRoster = env.MURMUR_ROSTER_PATH ?? settings.rosterPath;
24
+ const rosterPath = explicitRoster
25
+ ? path.resolve(dataDir, String(explicitRoster))
26
+ : path.join(dataDir, "federation-roster.json");
27
+ const rawScopes = settings.requiredScopes ?? ["murmur:send"];
28
+ if (!Array.isArray(rawScopes) || rawScopes.length === 0 || !rawScopes.every((s) => typeof s === "string" && s.length > 0)) {
29
+ throw new Error("auth-security-invalid:requiredScopes");
30
+ }
31
+ return {
32
+ enforce,
33
+ localOrg,
34
+ audience,
35
+ rosterPath,
36
+ rosterExplicit: Boolean(explicitRoster),
37
+ requiredScopes: [...rawScopes],
38
+ };
39
+ }
40
+
41
+ export async function loadRosterStoreFromBundle(rosterPath) {
42
+ const bundle = await readPrivateJson(rosterPath);
43
+ if (!bundle || typeof bundle !== "object" || typeof bundle.pinnedOrgKeys !== "object" || bundle.pinnedOrgKeys === null || !Array.isArray(bundle.rosters)) {
44
+ throw new Error("auth-roster-bundle-invalid");
45
+ }
46
+ const store = new RosterStore(bundle.pinnedOrgKeys);
47
+ for (const roster of bundle.rosters) {
48
+ const offered = await store.offer(roster);
49
+ if (!offered.accepted) {
50
+ throw new Error(`auth-roster-rejected:${roster?.org ?? "unknown"}:${offered.reason ?? "denied"}`);
51
+ }
52
+ }
53
+ return store;
54
+ }
55
+
56
+ export async function createDaemonInboundAuthorizer({ config = {}, env = process.env, dataDir = ".", log = () => {} }) {
57
+ const policy = normalizeAuthSecurity(config, env, dataDir);
58
+ if (!policy.enforce && !policy.rosterExplicit) {
59
+ return {
60
+ summary: { enforce: false, active: false, localOrg: policy.localOrg },
61
+ authorize: undefined,
62
+ };
63
+ }
64
+ const rosters = await loadRosterStoreFromBundle(policy.rosterPath);
65
+ const authorize = async (envelope) => {
66
+ const verdict = await authorizeInbound(envelope, rosters, {
67
+ localOrg: policy.localOrg,
68
+ audience: policy.audience,
69
+ requiredScopes: policy.requiredScopes,
70
+ enforce: policy.enforce,
71
+ });
72
+ if (!verdict.accepted) {
73
+ // Never log envelope.authToken; record only msgId, sender, audience and reject reason.
74
+ log("warn", "Inbound authorization rejected", {
75
+ reason: verdict.reason ?? "denied",
76
+ senderId: envelope.senderAgentId,
77
+ msgId: envelope.msgId,
78
+ conversationId: envelope.conversationId,
79
+ });
80
+ }
81
+ return verdict;
82
+ };
83
+ return {
84
+ summary: {
85
+ enforce: policy.enforce,
86
+ active: true,
87
+ localOrg: policy.localOrg,
88
+ rosterPath: policy.rosterPath,
89
+ requiredScopes: policy.requiredScopes,
90
+ },
91
+ authorize,
92
+ };
93
+ }