@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
@@ -7,6 +7,27 @@ export interface DoctorOptions {
7
7
  peer?: string;
8
8
  timeoutMs?: number;
9
9
  }
10
+ export declare function evaluatePeers(list: Array<{
11
+ agentId: string;
12
+ paired: boolean | null;
13
+ }>, peer?: string): {
14
+ state?: string;
15
+ reason?: string;
16
+ detail: string;
17
+ fixHint?: string;
18
+ };
19
+ /**
20
+ * How a silent probe reads. A daemon older than 2.11.0 never answers one, so silence alone is
21
+ * not the same finding as an unreachable peer (#292). A signed message this store persisted
22
+ * from that peer recently proves the transport in one direction; without that evidence the
23
+ * timeout stays a failure, and null tells the caller to let it through as one.
24
+ */
25
+ export declare function evaluateSilentPeer(peer: string, lastInboundAt: string | null, now?: number): {
26
+ state: string;
27
+ reason: string;
28
+ detail: string;
29
+ fixHint: string;
30
+ } | null;
10
31
  export declare function probeRoundtrip(c: ServiceContext, config: AgentConfig, peerId: string, connection: NatsConnection, timeoutMs: number): Promise<{
11
32
  msgId: string;
12
33
  replyMsgId: string;
@@ -29,6 +50,15 @@ export declare function runDoctor({ context, adapter, peer, timeoutMs }: DoctorO
29
50
  reason: string;
30
51
  fixHint: string;
31
52
  } | null;
53
+ wakeReaders: {
54
+ active: number | null;
55
+ measuredAt: string;
56
+ unknownReason: string;
57
+ } | {
58
+ active: number;
59
+ measuredAt: string;
60
+ unknownReason: null;
61
+ };
32
62
  stages: Record<string, unknown>[];
33
63
  summary: {
34
64
  worst: string;
@@ -6,9 +6,41 @@ import { realpath } from 'node:fs/promises';
6
6
  import { buildNatsConnectionOptions } from '@murmurv2/broker-nats';
7
7
  import { channelSubjectRoutes, resolveMessageSubject, SQLiteDedupeOutboxStore, stableEnvelopePayload, isEnvelopeV1 } from '@murmurv2/core';
8
8
  import { encryptPayload, signEnvelope, verifyEnvelopeSignature, decryptPayload } from '@murmurv2/security';
9
+ import { claudeWakeHookState } from './clients.js';
9
10
  import { loadConfig, readJson, safeError } from './config.js';
11
+ import { validateConfiguredTlsFiles } from './broker-input.js';
10
12
  import { pairFingerprint, readStatus } from './status.js';
11
13
  import { writeState } from './state.js';
14
+ // With --peer the peers stage answers for that peer: a fresh two-way proof for it is the evidence, and
15
+ // unmeasured pairs of other contacts do not hide it (#282). Without --peer every contact has to be measured.
16
+ export function evaluatePeers(list, peer) {
17
+ const hint = 'Run murmur doctor --peer <configured-agent-id> --json';
18
+ if (peer) {
19
+ return list.find(p => p.agentId === peer)?.paired === true
20
+ ? { detail: `Fresh two-way proof exists for ${peer}` }
21
+ : { state: 'warn', reason: 'peers.unmeasured', detail: `No fresh two-way proof for ${peer} yet; a completed roundtrip in this run records one`, fixHint: `${hint} once more` };
22
+ }
23
+ const measured = list.filter(p => p.paired === true).length;
24
+ return measured === list.length ? { detail: 'Fresh two-way proofs exist for configured peers' }
25
+ : { state: 'warn', reason: 'peers.unmeasured', detail: `Fresh two-way proofs exist for ${measured} of ${list.length} configured peers; local keys alone do not prove mutual pairing`, fixHint: hint };
26
+ }
27
+ // How recent an ordinary signed message must be to say the transport was proven "now" rather
28
+ // than once. An hour outlives a restart or a short outage without excusing a dead channel.
29
+ const PEER_TRAFFIC_WINDOW_MS = 3600_000;
30
+ /**
31
+ * How a silent probe reads. A daemon older than 2.11.0 never answers one, so silence alone is
32
+ * not the same finding as an unreachable peer (#292). A signed message this store persisted
33
+ * from that peer recently proves the transport in one direction; without that evidence the
34
+ * timeout stays a failure, and null tells the caller to let it through as one.
35
+ */
36
+ export function evaluateSilentPeer(peer, lastInboundAt, now = Date.now()) {
37
+ const at = lastInboundAt === null ? NaN : Date.parse(lastInboundAt);
38
+ if (!Number.isFinite(at) || now - at >= PEER_TRAFFIC_WINDOW_MS || at > now)
39
+ return null;
40
+ return { state: 'warn', reason: 'roundtrip.peer-silent',
41
+ detail: `No probe reply from ${peer}; a signed message from it was persisted at ${lastInboundAt}`,
42
+ fixHint: `The channel may be fine: a daemon older than 2.11.0 does not answer probes. Ask ${peer} for murmur --version, and check an ordinary message both ways.` };
43
+ }
12
44
  const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
13
45
  export async function probeRoundtrip(c, config, peerId, connection, timeoutMs) {
14
46
  const peer = config.peers[peerId];
@@ -89,6 +121,7 @@ const failureHints = (serviceName) => ({
89
121
  'config.missing': 'No profile here yet: run murmur join --data-dir <this profile> --agent-id <your-agent-id> --invite-file <invite file> --reply-out <new reply file>',
90
122
  'daemon.not-running': `Install or start the service: murmur service install --data-dir <this profile> --service-name ${serviceName} (or service start with the same options if installed; on Windows from an administrator terminal)`,
91
123
  'accepted-turn-unobservable': 'Inspect the Assistant session. After reviewing the unknown outcome, use murmur wake dismiss --data-dir <this profile> --msg-id <message-id> --expected-agent <your-identity> to acknowledge it without running it again.',
124
+ 'roundtrip.timeout': 'The peer sent no probe reply. A daemon older than 2.11.0 never answers one, so the channel may still be fine: ask the peer for murmur --version, and check an ordinary message in both directions before treating this as a broken channel.',
92
125
  });
93
126
  export async function runDoctor({ context, adapter, peer, timeoutMs = 10000 }) {
94
127
  if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 100 || timeoutMs > 60000)
@@ -120,7 +153,11 @@ export async function runDoctor({ context, adapter, peer, timeoutMs = 10000 }) {
120
153
  }
121
154
  };
122
155
  try {
123
- await stage('config', 'Configuration', async () => { config = await loadConfig(context); return { detail: 'Identity, keys and peer configuration validated' }; });
156
+ await stage('config', 'Configuration', async () => {
157
+ config = await loadConfig(context);
158
+ await validateConfiguredTlsFiles(config);
159
+ return { detail: 'Identity, keys, peer configuration, and referenced TLS files validated' };
160
+ });
124
161
  await stage('daemon', 'Daemon and store', async () => {
125
162
  snapshot = await readStatus({ context, adapter });
126
163
  if (!['running', 'running-unmanaged'].includes(snapshot.service.state))
@@ -131,7 +168,8 @@ export async function runDoctor({ context, adapter, peer, timeoutMs = 10000 }) {
131
168
  });
132
169
  await stage('broker', 'Broker authentication and RTT', async () => {
133
170
  try {
134
- connection = await connect({ ...buildNatsConnectionOptions({ url: config.natsUrl, token: config.natsToken }), reconnect: false, waitOnFirstConnect: false, timeout: timeoutMs });
171
+ connection = await connect({ ...buildNatsConnectionOptions({ url: config.natsUrl, token: config.natsToken,
172
+ user: config.natsUser, password: config.natsPassword, tls: config.natsTls }), reconnect: false, waitOnFirstConnect: false, timeout: timeoutMs });
135
173
  await connection.rtt();
136
174
  }
137
175
  catch (e) {
@@ -144,14 +182,23 @@ export async function runDoctor({ context, adapter, peer, timeoutMs = 10000 }) {
144
182
  throw new Error('peers.unknown');
145
183
  if (!Object.keys(config.peers).length)
146
184
  throw new Error('peers.none');
147
- const list = snapshot.peers.list ?? [];
148
- return list.every(p => p.paired === true) ? { detail: 'Fresh two-way proofs exist for configured peers' }
149
- : { state: 'warn', reason: 'peers.unmeasured', detail: 'Local keys alone do not prove mutual pairing', fixHint: 'Run murmur doctor --peer <configured-agent-id> --json' };
185
+ return evaluatePeers(snapshot.peers.list ?? [], peer);
150
186
  });
151
187
  await stage('roundtrip', 'Encrypted signed roundtrip', async () => {
152
188
  if (!peer)
153
189
  return { state: 'warn', reason: 'roundtrip.peer-required', detail: 'No diagnostic peer selected; no message sent', fixHint: 'Run murmur doctor --peer <configured-agent-id> --json' };
154
- const proof = await probeRoundtrip(context, config, peer, connection, timeoutMs);
190
+ let proof;
191
+ try {
192
+ proof = await probeRoundtrip(context, config, peer, connection, timeoutMs);
193
+ }
194
+ catch (e) {
195
+ if (safeError(e) !== 'roundtrip.timeout')
196
+ throw e;
197
+ const silent = evaluateSilentPeer(peer, snapshot?.peers.list?.find(row => row.agentId === peer)?.lastInboundAt ?? null);
198
+ if (!silent)
199
+ throw e;
200
+ return silent;
201
+ }
155
202
  peerCheck = { peerId: peer, state: 'connected', lastExchangeAt: proof.verifiedAt,
156
203
  requestMsgId: proof.msgId, replyMsgId: proof.replyMsgId, reason: null };
157
204
  return { detail: `Authenticated reply persisted from ${proof.peerId}` };
@@ -166,8 +213,20 @@ export async function runDoctor({ context, adapter, peer, timeoutMs = 10000 }) {
166
213
  return { state: 'warn', reason: 'wake.mode-mismatch', detail: 'Configured and effective wake differ', fixHint: 'Run murmur wake pause --apply or murmur wake resume --apply for the intended mode' };
167
214
  if (!s.wake.effective.enabled)
168
215
  return { state: 'warn', reason: 'wake.paused', detail: 'Wake is paused; pending messages remain queued' };
169
- if (s.wake.config.mode === 'none' || s.wake.config.responder === 'none')
170
- return { state: 'warn', reason: 'wake.no-responder', detail: 'No wake responder configured' };
216
+ if (s.wake.config.mode === 'none' || s.wake.config.responder === 'none') {
217
+ // Claude Code is woken by the Stop hook clients configure writes, not by a responder in
218
+ // the daemon. Reporting no-responder there told a working setup it was misconfigured (#293).
219
+ const hook = await claudeWakeHookState(context, adapter);
220
+ if (hook === 'outdated')
221
+ return { state: 'warn', reason: 'wake.hook-outdated',
222
+ detail: 'Claude Code Stop hook differs from the one this version installs',
223
+ fixHint: 'Run murmur clients configure --client claude-code --replace' };
224
+ if (hook === 'absent')
225
+ return { state: 'warn', reason: 'wake.no-responder', detail: 'No wake responder configured' };
226
+ // This stage reads configuration: the hook is installed and current. Whether a live
227
+ // session was woken is the separate proof the responder branch below also withholds.
228
+ return { detail: 'Claude Code Stop hook installed for this profile; a live session receipt is separate proof' };
229
+ }
171
230
  if (s.wake.faults.lastFault)
172
231
  throw new Error(s.wake.faults.lastFault);
173
232
  // A reply is not evidence that a particular UI/session was awakened.
@@ -179,7 +238,10 @@ export async function runDoctor({ context, adapter, peer, timeoutMs = 10000 }) {
179
238
  }
180
239
  if (peerCheck && peerCheck.state !== 'connected') {
181
240
  peerCheck.state = 'failed';
182
- peerCheck.reason = String(stages.find(s => s.state === 'fail')?.reason ?? 'roundtrip.not-checked');
241
+ // A silent peer with recent verified traffic leaves no failed stage, so carry that stage's
242
+ // own reason rather than saying the check never ran (#292).
243
+ const silent = stages.find(s => s.id === 'roundtrip' && s.state === 'warn')?.reason;
244
+ peerCheck.reason = String(stages.find(s => s.state === 'fail')?.reason ?? silent ?? 'roundtrip.not-checked');
183
245
  }
184
246
  // A local accepted-outcome fault is useful even when an earlier network stage
185
247
  // blocked the wake probe. This read sends no message and changes no state.
@@ -187,5 +249,5 @@ export async function runDoctor({ context, adapter, peer, timeoutMs = 10000 }) {
187
249
  const wakeFault = local.wake.faults.lastFault === 'accepted-turn-unobservable'
188
250
  ? { reason: 'accepted-turn-unobservable', fixHint: failureHints(context.serviceName)['accepted-turn-unobservable'] } : null;
189
251
  return { schema: 'murmur.doctor/1', generatedAt, agentId: config?.agentId ?? null,
190
- peerCheck, wakeFault, stages, summary: { worst, failedStage } };
252
+ peerCheck, wakeFault, wakeReaders: local.wake.readers, stages, summary: { worst, failedStage } };
191
253
  }
@@ -0,0 +1,25 @@
1
+ import type { ServiceContext } from './types.js';
2
+ export declare function showInstallation(file?: string): {
3
+ descriptorFile: string;
4
+ schema?: "murmur.installation/1" | undefined;
5
+ dataDir?: string | undefined;
6
+ agentId?: string | undefined;
7
+ identityFingerprint?: string | undefined;
8
+ };
9
+ export declare function checkInstallationSelection(c: ServiceContext, options?: {
10
+ file?: string;
11
+ replace?: boolean;
12
+ }): void;
13
+ /** Explicitly register an existing profile; never relocate it, rotate keys or rewrite client/service settings. */
14
+ export declare function selectInstallation(c: ServiceContext, options?: {
15
+ file?: string;
16
+ replace?: boolean;
17
+ }): Promise<{
18
+ descriptorFile: string;
19
+ changed: boolean;
20
+ existingConsumersChanged: boolean;
21
+ schema: "murmur.installation/1";
22
+ dataDir: string;
23
+ agentId: string;
24
+ identityFingerprint: string;
25
+ }>;
@@ -0,0 +1,89 @@
1
+ import { constants } from 'node:fs';
2
+ import { lstat, mkdir, open, rename, rmdir, unlink } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { isDeepStrictEqual } from 'node:util';
6
+ import { installationFile, installationIdentity, readInstallationDescriptor, resolveInstallation } from '@murmurv2/core';
7
+ import { protectPrivateFile } from './private-file.js';
8
+ import { loadConfig } from './config.js';
9
+ export function showInstallation(file) {
10
+ const descriptorFile = installationFile({ installationFile: file });
11
+ // Show the registered choice, not an ambient DATA_DIR override.
12
+ const selected = resolveInstallation({ installationFile: descriptorFile, env: {} });
13
+ return { ...selected.descriptor, descriptorFile };
14
+ }
15
+ export function checkInstallationSelection(c, options = {}) {
16
+ const file = installationFile({ installationFile: options.file });
17
+ const relative = path.relative(c.dataDir, file);
18
+ if ((!relative.startsWith('..' + path.sep) && relative !== '..' && !path.isAbsolute(relative))
19
+ && relative !== 'installation.json')
20
+ throw new Error('installation.file-conflict');
21
+ try {
22
+ const previous = readInstallationDescriptor(file);
23
+ if (!options.replace && (previous.dataDir !== c.dataDir || !isDeepStrictEqual({ agentId: previous.agentId, identityFingerprint: previous.identityFingerprint }, installationIdentity(c.dataDir)))) {
24
+ throw new Error('installation.selection-conflict');
25
+ }
26
+ }
27
+ catch (error) {
28
+ if (!(error instanceof Error && error.message === 'installation.descriptor-missing'))
29
+ throw error;
30
+ }
31
+ }
32
+ /** Explicitly register an existing profile; never relocate it, rotate keys or rewrite client/service settings. */
33
+ export async function selectInstallation(c, options = {}) {
34
+ checkInstallationSelection(c, options);
35
+ await loadConfig(c);
36
+ const identity = installationIdentity(c.dataDir), file = installationFile({ installationFile: options.file });
37
+ if (file === c.configPath || file === c.storePath)
38
+ throw new Error('installation.file-conflict');
39
+ const desired = { schema: 'murmur.installation/1', dataDir: c.dataDir, ...identity };
40
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
41
+ const lock = `${file}.murmur-lock`;
42
+ await mkdir(lock, { mode: 0o700 });
43
+ const read = () => {
44
+ try {
45
+ return readInstallationDescriptor(file);
46
+ }
47
+ catch (error) {
48
+ if (error instanceof Error && error.message === 'installation.descriptor-missing')
49
+ return null;
50
+ throw error;
51
+ }
52
+ };
53
+ const temporary = `${file}.${randomUUID()}.tmp`;
54
+ try {
55
+ const previous = read();
56
+ if (isDeepStrictEqual(previous, desired))
57
+ return { ...desired, descriptorFile: file, changed: false, existingConsumersChanged: false };
58
+ if (previous && !options.replace)
59
+ throw new Error('installation.selection-conflict');
60
+ const handle = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);
61
+ try {
62
+ await protectPrivateFile(temporary, handle);
63
+ await handle.writeFile(JSON.stringify(desired, null, 2) + '\n');
64
+ await handle.sync();
65
+ }
66
+ finally {
67
+ await handle.close();
68
+ }
69
+ if (!isDeepStrictEqual(previous, read()) || !isDeepStrictEqual(identity, installationIdentity(c.dataDir)))
70
+ throw new Error('installation.selection-changed');
71
+ if (!previous) {
72
+ // A non-cooperating creator appearing while we prepared the descriptor must not be overwritten.
73
+ try {
74
+ await lstat(file);
75
+ throw new Error('installation.selection-changed');
76
+ }
77
+ catch (error) {
78
+ if (error.code !== 'ENOENT')
79
+ throw error;
80
+ }
81
+ }
82
+ await rename(temporary, file);
83
+ return { ...desired, descriptorFile: file, changed: true, existingConsumersChanged: false };
84
+ }
85
+ finally {
86
+ await unlink(temporary).catch(() => { });
87
+ await rmdir(lock);
88
+ }
89
+ }
@@ -1,4 +1,5 @@
1
1
  import type { DatabaseSync } from 'node:sqlite';
2
+ export declare const personalInboxSql = "COALESCE(conversation_id, '') NOT LIKE 'murmur:doctor:%'";
2
3
  /** Older stores remain readable without a migration or an invented wake result. */
3
4
  export declare function wakeColumns(db: DatabaseSync): string;
4
5
  export declare function assistantRead(wakeStatus: unknown): boolean | null;
@@ -1,3 +1,6 @@
1
+ // Reserved machine-only conversations remain in history for diagnosis, but do
2
+ // not fill a person's inbox or unread badge. Never infer this from message text.
3
+ export const personalInboxSql = "COALESCE(conversation_id, '') NOT LIKE 'murmur:doctor:%'";
1
4
  /** Older stores remain readable without a migration or an invented wake result. */
2
5
  export function wakeColumns(db) {
3
6
  const columns = new Set(db.prepare('PRAGMA table_info(local_messages)').all().map(row => row.name));
@@ -1,9 +1,9 @@
1
+ import { type BrokerInputFiles } from './broker-input.js';
1
2
  import type { ServiceContext } from './types.js';
2
3
  export declare function initialize(c: ServiceContext, options: {
3
4
  agentId: string;
4
5
  brokerUrl: string;
5
- tokenFile?: string;
6
- }): Promise<{
6
+ } & BrokerInputFiles): Promise<{
7
7
  schema: string;
8
8
  agentId: string;
9
9
  dataDir: string;
@@ -12,19 +12,24 @@ export declare function initialize(c: ServiceContext, options: {
12
12
  }>;
13
13
  export declare function invite(c: ServiceContext, outFile?: string, options?: {
14
14
  brokerUrl?: string;
15
+ printSecret?: boolean;
15
16
  }): Promise<{
16
- schema: string;
17
- file: string | null;
18
- invitation: string;
19
17
  containsBrokerCredential: boolean;
20
18
  instruction: string;
19
+ invitation?: string | undefined;
20
+ outFile?: string | undefined;
21
+ secretRedacted?: boolean | undefined;
22
+ schema: string;
23
+ file: string | null;
21
24
  }>;
22
25
  export declare function join(c: ServiceContext, options: {
23
26
  agentId: string;
24
27
  inviteFile?: string;
25
28
  invitation?: string;
29
+ inviteArgument?: string;
26
30
  replyOut?: string;
27
- }): Promise<{
31
+ connect?: boolean;
32
+ } & BrokerInputFiles): Promise<{
28
33
  schema: string;
29
34
  agentId: string;
30
35
  peerId: any;
@@ -7,6 +7,7 @@ import { execFile } from 'node:child_process';
7
7
  import { SQLiteDedupeOutboxStore } from '@murmurv2/core';
8
8
  import { createKeyPair, createSigningKeyPair } from '@murmurv2/security';
9
9
  import { loadConfig, validateConfig, validAgentId } from './config.js';
10
+ import { readBrokerInputs } from './broker-input.js';
10
11
  import { writeState } from './state.js';
11
12
  import { refuseVirtualizedAppData } from './appdata.js';
12
13
  import { protectPrivateFile } from './private-file.js';
@@ -15,7 +16,7 @@ async function privateText(file, role) {
15
16
  if (!path.isAbsolute(file))
16
17
  throw new Error('onboarding.file-must-be-absolute');
17
18
  // Name the option and the reason, never the path or contents: this is what a new user acts on.
18
- const handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)).catch((e) => {
19
+ const handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)).catch((e) => {
19
20
  if (e.code === 'ENOENT')
20
21
  throw new Error(`onboarding.${role}-not-found`);
21
22
  if (e.code === 'EPERM' || e.code === 'EACCES')
@@ -26,7 +27,18 @@ async function privateText(file, role) {
26
27
  const info = await handle.stat();
27
28
  if (!info.isFile() || info.size > 16384)
28
29
  throw new Error('onboarding.file-invalid');
29
- return (await handle.readFile('utf8')).trim();
30
+ // Bound the read even if the file grows after stat.
31
+ const buffer = Buffer.alloc(16385);
32
+ let size = 0;
33
+ while (size < buffer.length) {
34
+ const { bytesRead } = await handle.read(buffer, size, buffer.length - size, null);
35
+ if (!bytesRead)
36
+ break;
37
+ size += bytesRead;
38
+ }
39
+ if (size > 16384)
40
+ throw new Error('onboarding.input-too-large');
41
+ return buffer.subarray(0, size).toString('utf8').trim();
30
42
  }
31
43
  finally {
32
44
  await handle.close();
@@ -109,16 +121,23 @@ async function restrictToCurrentUser(target, directory) {
109
121
  await execFileAsync(system32('icacls.exe'), [target, '/inheritance:r', '/grant:r', `*${sid}:${inherit}(F)`, `*S-1-5-18:${inherit}(F)`], { windowsHide: true })
110
122
  .catch(() => { throw new Error('onboarding.private-acl-failed'); });
111
123
  }
112
- const encodeBlob = (value) => {
113
- const text = 'MURMUR:' + Buffer.from(JSON.stringify(value)).toString('base64url');
124
+ const encodeBlob = (value, prefix = 'MURMUR:') => {
125
+ const text = prefix + Buffer.from(JSON.stringify(value)).toString('base64url');
114
126
  if (Buffer.byteLength(text + '\n') > 16384)
115
127
  throw new Error('onboarding.input-too-large');
116
128
  return text;
117
129
  };
118
- async function outputBlob(file, text, beforeWrite) {
130
+ async function outputBlob(file, text, beforeWrite, skipOccupied = false) {
119
131
  if (!path.isAbsolute(file))
120
132
  throw new Error('onboarding.output-must-be-absolute');
121
- const handle = await open(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);
133
+ const handle = await open(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600)
134
+ .catch((error) => {
135
+ if (skipOccupied && error.code === 'EEXIST')
136
+ return null;
137
+ throw error;
138
+ });
139
+ if (!handle)
140
+ return false;
122
141
  let written = false;
123
142
  try {
124
143
  // Protect the still-empty output before writing the invitation credential.
@@ -133,6 +152,7 @@ async function outputBlob(file, text, beforeWrite) {
133
152
  if (!written)
134
153
  await unlink(file).catch(() => { });
135
154
  }
155
+ return true;
136
156
  }
137
157
  async function locked(c, fn) {
138
158
  // mkdir reports a path only when it created something: never rewrite an existing profile's ACL.
@@ -171,10 +191,10 @@ async function existing(c) {
171
191
  throw e;
172
192
  }
173
193
  }
174
- async function newConfig(agentId, url, token) {
194
+ async function newConfig(agentId, url, auth = {}) {
175
195
  if (!validAgentId(agentId))
176
196
  throw new Error('config.identity-invalid');
177
- return validateConfig({ agentId, subject: `msg.${agentId}`, natsUrl: url, ...(token ? { natsToken: token } : {}),
197
+ return validateConfig({ agentId, subject: `msg.${agentId}`, natsUrl: url, ...auth,
178
198
  keys: { encryption: await createKeyPair(), signing: await createSigningKeyPair() }, peers: {},
179
199
  wake: { enabled: true }, ackSecurity: { emitSigned: true, requireSigned: true } });
180
200
  }
@@ -192,6 +212,32 @@ async function saveChanged(c, previous, next) {
192
212
  }
193
213
  const publicPeer = (c) => ({ agentId: c.agentId, subject: c.subject,
194
214
  encryption: { publicKey: c.keys.encryption.publicKey }, signing: { publicKey: c.keys.signing.publicKey } });
215
+ async function connectInviteText(options) {
216
+ let text = options.invitation ?? options.inviteArgument ?? '';
217
+ if (options.inviteFile !== undefined)
218
+ text = await privateText(path.resolve(options.inviteFile), 'invite-file');
219
+ // Text with line breaks cannot be a normal CLI file argument. A single-line
220
+ // argument may instead name an existing file (including a relative path).
221
+ else if (options.inviteArgument && !/[\x00-\x1f\x7f]/.test(text) && Buffer.byteLength(text) < 4096) {
222
+ const file = path.resolve(text);
223
+ try {
224
+ text = await privateText(file, 'invite-file');
225
+ }
226
+ catch (error) {
227
+ if (!(error instanceof Error && error.message === 'onboarding.invite-file-not-found')
228
+ && !['ENAMETOOLONG', 'ENOTDIR', 'EINVAL'].includes(error.code ?? ''))
229
+ throw error;
230
+ }
231
+ }
232
+ if (Buffer.byteLength(text) > 16384)
233
+ throw new Error('onboarding.input-too-large');
234
+ const tokens = [...new Set(text.match(/MURMUR:[A-Za-z0-9+/=_-]+/g) ?? [])];
235
+ if (tokens.length > 1)
236
+ throw new Error('connect.multiple-invitations');
237
+ if (!tokens.length)
238
+ throw new Error('onboarding.invalid-blob');
239
+ return tokens[0];
240
+ }
195
241
  async function readBlob(input, type) {
196
242
  if ((input.file === undefined) === (input.text === undefined))
197
243
  throw new Error('onboarding.input-required');
@@ -235,18 +281,17 @@ function addPeer(config, peer) {
235
281
  }
236
282
  export async function initialize(c, options) {
237
283
  await refuseVirtualizedAppData(c.dataDir);
284
+ const supplied = await readBrokerInputs(options);
238
285
  return locked(c, async () => {
239
286
  const previous = await existing(c);
240
287
  if (previous) {
241
- if (previous.agentId !== options.agentId || previous.natsUrl !== options.brokerUrl)
288
+ if (previous.agentId !== options.agentId || previous.natsUrl !== options.brokerUrl
289
+ || Object.keys(supplied).some(key => !isDeepStrictEqual(previous[key], supplied[key])))
242
290
  throw new Error('onboarding.existing-profile-conflict');
243
291
  // Re-running init never rotates keys or replaces credentials.
244
292
  return { schema: 'murmur.init/1', agentId: previous.agentId, dataDir: c.dataDir, serviceName: c.serviceName, existing: true };
245
293
  }
246
- const token = options.tokenFile ? await privateText(options.tokenFile, 'token-file') : undefined;
247
- if (token?.includes('\n') || token?.includes('\r'))
248
- throw new Error('onboarding.token-file-invalid');
249
- const config = await newConfig(options.agentId, options.brokerUrl, token);
294
+ const config = await newConfig(options.agentId, options.brokerUrl, supplied);
250
295
  await saveChanged(c, null, config);
251
296
  return { schema: 'murmur.init/1', agentId: config.agentId, dataDir: c.dataDir, serviceName: c.serviceName, existing: false };
252
297
  });
@@ -260,7 +305,10 @@ export async function invite(c, outFile, options = {}) {
260
305
  if (outFile !== undefined)
261
306
  await outputBlob(outFile, invitation);
262
307
  const containsBrokerCredential = !!config.natsToken;
263
- return { schema: 'murmur.invite/1', file: outFile ?? null, invitation, containsBrokerCredential,
308
+ const secretRedacted = outFile !== undefined && !options.printSecret;
309
+ return { schema: 'murmur.invite/1', file: outFile ?? null,
310
+ ...(outFile !== undefined ? { outFile, secretRedacted } : {}),
311
+ ...(!secretRedacted ? { invitation } : {}), containsBrokerCredential,
264
312
  instruction: containsBrokerCredential
265
313
  ? 'This Invitation contains a Server access key. Send it personally to your colleague. After exchanging the Reply, check the connection.'
266
314
  : 'This Invitation contains your Identity and the Server address. Send it to your colleague. After exchanging the Reply, check the connection.' };
@@ -268,25 +316,48 @@ export async function invite(c, outFile, options = {}) {
268
316
  export async function join(c, options) {
269
317
  if (options.replyOut !== undefined)
270
318
  await validateOutput(c, options.replyOut);
271
- const incoming = await readBlob({ file: options.inviteFile, text: options.invitation }, 'invite');
319
+ const incoming = await readBlob(options.connect
320
+ ? { text: await connectInviteText(options) }
321
+ : { file: options.inviteFile, text: options.invitation }, 'invite');
322
+ const supplied = await readBrokerInputs(options);
323
+ if (incoming.natsToken && (supplied.natsUser || supplied.natsPassword || supplied.natsToken && supplied.natsToken !== incoming.natsToken))
324
+ throw new Error('nats-auth-methods-conflict');
325
+ const auth = { ...(incoming.natsToken ? { natsToken: incoming.natsToken } : {}), ...supplied };
272
326
  // Before anything is created: a profile the service cannot see must not be written at all.
273
327
  await refuseVirtualizedAppData(c.dataDir);
274
328
  return locked(c, async () => {
275
329
  const previous = await existing(c);
276
- if (previous && (previous.agentId !== options.agentId || previous.natsUrl !== incoming.natsUrl))
330
+ if (previous && (previous.agentId !== options.agentId || previous.natsUrl !== incoming.natsUrl
331
+ || Object.keys(auth).some(key => !isDeepStrictEqual(previous[key], auth[key]))))
277
332
  throw new Error('onboarding.existing-profile-conflict');
278
- const config = previous ?? await newConfig(options.agentId, incoming.natsUrl, incoming.natsToken);
333
+ const config = previous ?? await newConfig(options.agentId, incoming.natsUrl, auth);
279
334
  const next = addPeer(config, incoming);
280
335
  let backup = null;
281
336
  // Reserve the reply path before changing config: an existing output must not half-import a profile.
282
- const reply = encodeBlob({ v: 1, type: 'reply', ...publicPeer(next) });
337
+ const reply = encodeBlob({ v: 1, type: 'reply', ...publicPeer(next) }, options.connect ? 'MURMUR-REPLY:' : 'MURMUR:');
283
338
  const save = async () => { backup = await saveChanged(c, previous, next); };
284
- if (options.replyOut !== undefined)
285
- await outputBlob(options.replyOut, reply, save);
339
+ let replyFile = options.replyOut ?? null;
340
+ if (replyFile !== null)
341
+ await outputBlob(replyFile, reply, save);
342
+ else if (options.connect) {
343
+ const stem = path.join(path.dirname(c.dataDir), `${next.agentId}-reply`);
344
+ // The profile parent now exists. Reserve without overwriting even a
345
+ // symlink or an unrelated file with the suggested name.
346
+ for (let attempt = 1; attempt <= 100; attempt++) {
347
+ const candidate = stem + (attempt === 1 ? '' : `-${attempt}`) + '.txt';
348
+ await validateOutput(c, candidate);
349
+ if (await outputBlob(candidate, reply, save, true)) {
350
+ replyFile = candidate;
351
+ break;
352
+ }
353
+ }
354
+ if (replyFile === null)
355
+ throw new Error('connect.reply-output-occupied');
356
+ }
286
357
  else
287
358
  await save();
288
359
  return { schema: 'murmur.join/1', agentId: next.agentId, peerId: incoming.agentId, paired: null,
289
- replyFile: options.replyOut ?? null, reply, backup, restartRequired: false,
360
+ replyFile, reply, backup, restartRequired: false,
290
361
  contactsReload: { mechanism: 'config-file', state: 'pending' }, serviceName: c.serviceName };
291
362
  });
292
363
  }
@@ -1,4 +1,7 @@
1
1
  import type { ServiceContext } from "./types.js";
2
+ /** Homebrew resolves process.execPath into a versioned Cellar. Persist a stable
3
+ * executable only when it is executable and resolves to this very same Node. */
4
+ export declare function stableNodeExecutable(executable: string, platform?: NodeJS.Platform, inspect?: (candidate: string) => string): string;
2
5
  export declare function resolveContext(options?: {
3
6
  dataDir?: string;
4
7
  repoRoot?: string;
@@ -7,4 +10,8 @@ export declare function resolveContext(options?: {
7
10
  platform?: NodeJS.Platform;
8
11
  home?: string;
9
12
  env?: NodeJS.ProcessEnv;
13
+ installationFile?: string;
14
+ clientProjectDir?: string;
10
15
  }): ServiceContext;
16
+ /** New CLI profiles live beside, not inside, any selected installation. */
17
+ export declare function defaultProfileDir(agentId: string, platform?: NodeJS.Platform, home?: string, env?: NodeJS.ProcessEnv): string;