session-peer 0.2.1 → 0.3.1

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.
package/dist/cli.js CHANGED
@@ -7,15 +7,37 @@ import { lstatSync } from 'node:fs';
7
7
  import { listing, Refusal } from './discovery.js';
8
8
  import { executable, run, UnknownOutcome } from './process.js';
9
9
  import { checkMessage, send, CodexUnknownOutcome } from './send.js';
10
- import { HomeRefusal } from './writer.js';
10
+ import { HomeRefusal, uuid } from './writer.js';
11
11
  import { envelope, host, reply, VERSION, VERSION_LINE } from './protocol.js';
12
- const FLAGS = ['--json', '--all', '--dry-run', '--no-from', '--no-reply-to', '--no-update-notice', '--allow-inactive-codex-home'];
13
- const VALUES = ['--agent', '--codex-home', '--codex-bin', '--output-format', '--to', '--message', '-m', '--host', '--remote-bin', '--remote-platform', '--ssh-control-path', '--reply-address'];
12
+ import { CHANNELS, checkUpdate, noticeText, refreshCache, refuseSelfUpdate, REFRESH_ARG, updateNotice, UpdateRefusal } from './updates.js';
13
+ import { jumpOptions, sshConfig, sshJump, sshOptions } from './ssh.js';
14
+ import { configuredHost, detectedHost, isSelf, probeReturnRoute, unsafeReturnHost, replyUri, returnHost, route, sender, tailnet } from './replies.js';
15
+ const FLAGS = ['--json', '--all', '--dry-run', '--no-from', '--no-reply-to', '--no-update-notice', '--allow-inactive-codex-home', '--check-return-route', '--check'];
16
+ const VALUES = ['--agent', '--codex-home', '--codex-bin', '--output-format', '--to', '--message', '-m', '--host', '--remote-bin', '--remote-platform', '--ssh-control-path', '--reply-address', '--ssh-opt', '--ssh-jump', '--reply-to', '--return-route-host', '--channel'];
17
+ // Repeated in order; every other value option is single.
18
+ const REPEATED = ['--host', '--ssh-opt'];
19
+ // Requested destinations, so a command-wide refusal can be attributed to each.
20
+ let requested = [];
14
21
  export function parse(args) {
15
22
  const command = args[0];
16
- if (command !== 'list' && command !== 'send' && command !== 'doctor')
23
+ if (command !== 'list' && command !== 'send' && command !== 'doctor' && command !== 'update')
17
24
  throw new Refusal('unsupported_command');
18
- const values = new Map(), flags = new Set();
25
+ // Collect requested hosts before any other validation, so that even a syntax
26
+ // refusal with several --host values is attributed to each of them. Value
27
+ // options consume their next token, as in the loop below; `--` ends options.
28
+ requested = [];
29
+ for (let i = 1; i < args.length && args[i] !== '--'; i++) {
30
+ const token = args[i], key = token.split('=')[0];
31
+ if (key === '--host') {
32
+ const value = token.includes('=') ? token.slice(7) : args[++i];
33
+ if (value !== undefined)
34
+ requested.push(value);
35
+ }
36
+ else if (VALUES.includes(key) && !token.includes('='))
37
+ i++;
38
+ }
39
+ let address;
40
+ const values = new Map(), flags = new Set(), repeated = new Map(REPEATED.map(k => [k, []]));
19
41
  let positional;
20
42
  let terminated = false;
21
43
  for (let i = 1; i < args.length; i++) {
@@ -45,11 +67,15 @@ export function parse(args) {
45
67
  const option = split > 0 ? '' : (value ?? '').split('=')[0];
46
68
  if (value === undefined || values.has(name) || [...FLAGS, ...VALUES, '--help', '-h', '--version', '--stdio-request'].includes(option))
47
69
  throw new Refusal('invalid_option');
48
- values.set(name, value);
70
+ if (REPEATED.includes(name))
71
+ repeated.get(name).push(value);
72
+ else
73
+ values.set(name, value);
49
74
  }
50
75
  else
51
76
  throw new Refusal('unsupported_option');
52
77
  }
78
+ let hosts = repeated.get('--host');
53
79
  if (positional !== undefined) {
54
80
  if (values.has('--message'))
55
81
  throw new Refusal('conflicting_message_sources');
@@ -61,6 +87,18 @@ export function parse(args) {
61
87
  throw new Refusal('conflicting_output_options');
62
88
  if (!flags.has('--json') && !values.has('--output-format'))
63
89
  throw new Refusal('json_output_required');
90
+ if (command === 'update') {
91
+ if (values.has('--channel') && !CHANNELS.includes(values.get('--channel')))
92
+ throw new Refusal('unsupported_update_channel');
93
+ // Local client only: remote hosts and other installations update through their own managers.
94
+ if ([...values.keys()].some(k => !['--output-format', '--channel'].includes(k)) || [...flags].some(k => !['--json', '--check', '--no-update-notice'].includes(k)))
95
+ throw new Refusal('inapplicable_option');
96
+ if (hosts.length || repeated.get('--ssh-opt').length)
97
+ throw new Refusal('inapplicable_option');
98
+ return { command, values, flags, hosts: [], ssh: { args: [] } };
99
+ }
100
+ if (flags.has('--check') || values.has('--channel'))
101
+ throw new Refusal('inapplicable_option');
64
102
  if (command === 'list' || command === 'doctor') {
65
103
  if (values.has('--agent') && !['claude', 'codex'].includes(values.get('--agent')))
66
104
  throw new Refusal('unsupported_agent');
@@ -68,24 +106,39 @@ export function parse(args) {
68
106
  throw new Refusal('invalid_codex_home');
69
107
  if (values.get('--agent') === 'claude' && values.has('--codex-home'))
70
108
  throw new Refusal('inapplicable_option');
71
- if (['--to', '--message', '--reply-address', ...(command === 'list' ? ['--codex-bin'] : [])].some(k => values.has(k)) || ['--dry-run', '--no-from', '--no-reply-to', '--allow-inactive-codex-home'].some(k => flags.has(k)))
109
+ if (['--to', '--message', '--reply-address', ...(command === 'list' ? ['--codex-bin', '--reply-to', '--return-route-host'] : [])].some(k => values.has(k)) || ['--dry-run', '--no-from', '--no-reply-to', '--allow-inactive-codex-home', ...(command === 'list' ? ['--check-return-route'] : [])].some(k => flags.has(k)))
72
110
  throw new Refusal('inapplicable_option');
73
111
  if (command === 'doctor' && (flags.has('--all') || (values.get('--agent') === 'claude' && values.has('--codex-bin'))))
74
112
  throw new Refusal('inapplicable_option');
113
+ // --reply-to names the return host to probe; the probe itself is opt-in.
114
+ if (command === 'doctor' && ((values.has('--reply-to') && !flags.has('--check-return-route')) || (values.has('--return-route-host') && flags.has('--check-return-route'))))
115
+ throw new Refusal('inapplicable_option');
116
+ for (const key of ['--reply-to', '--return-route-host'])
117
+ if (values.has(key))
118
+ returnHost(values.get(key));
75
119
  }
76
120
  else {
77
121
  if (!values.get('--to') || values.has('--agent') || flags.has('--all'))
78
122
  throw new Refusal('invalid_send_options');
79
- if (flags.has('--no-reply-to') && values.has('--reply-address'))
123
+ if (flags.has('--check-return-route') || values.has('--return-route-host'))
124
+ throw new Refusal('inapplicable_option');
125
+ if ([flags.has('--no-reply-to'), values.has('--reply-address'), values.has('--reply-to')].filter(Boolean).length > 1)
80
126
  throw new Refusal('conflicting_reply_options');
127
+ if (values.has('--reply-to'))
128
+ returnHost(values.get('--reply-to'));
81
129
  if (values.get('--to').startsWith('session-peer:')) {
82
130
  const route = reply(values.get('--to'));
83
- for (const [key, value] of [['--host', route.host], ['--codex-home', route.home]]) {
84
- if (values.has(key) && values.get(key) !== value)
85
- throw new Refusal('reply_route_conflict');
86
- if (value !== undefined)
87
- values.set(key, value);
88
- }
131
+ // Only a route taken from the URI alone may later normalize to local.
132
+ address = { uri: values.get('--to'), transport: route.host === undefined ? 'local' : 'ssh',
133
+ implicit: !hosts.length && !repeated.get('--ssh-opt').length && !['--remote-bin', '--remote-platform', '--ssh-control-path', '--ssh-jump'].some(k => values.has(k)) };
134
+ if (hosts.length && (hosts.length > 1 || host(hosts[0]) !== route.host))
135
+ throw new Refusal('reply_route_conflict');
136
+ if (route.host !== undefined)
137
+ hosts = [route.host];
138
+ if (values.has('--codex-home') && values.get('--codex-home') !== route.home)
139
+ throw new Refusal('reply_route_conflict');
140
+ if (route.home !== undefined)
141
+ values.set('--codex-home', route.home);
89
142
  values.set('--to', route.to);
90
143
  }
91
144
  }
@@ -97,10 +150,37 @@ export function parse(args) {
97
150
  }
98
151
  if (values.has('--codex-home') && !values.get('--codex-home'))
99
152
  throw new Refusal('invalid_codex_home');
100
- if (values.has('--host'))
101
- host(values.get('--host'));
153
+ // Validate every destination and option before any SSH process starts.
154
+ const destinations = new Set();
155
+ for (const item of hosts) {
156
+ const destination = host(item), at = destination.lastIndexOf('@');
157
+ // One attempt per destination: a repeated destination is refused, not sent twice.
158
+ const name = destination.slice(at + 1).toLowerCase(), key = destination.slice(0, at + 1) + (name.includes(':') ? new URL(`http://[${name}]`).hostname : name);
159
+ if (destinations.has(key))
160
+ throw new Refusal('duplicate_ssh_host');
161
+ destinations.add(key);
162
+ }
163
+ if (repeated.get('--ssh-opt').length && !hosts.length)
164
+ throw new Refusal('inapplicable_option');
165
+ const ssh = sshOptions(repeated.get('--ssh-opt'));
166
+ // `ssh -l` silently overrides USER@HOST, so both together are ambiguous.
167
+ if (ssh.user !== undefined && hosts.some(item => item.includes('@')))
168
+ throw new Refusal('conflicting_ssh_user');
169
+ let jump;
170
+ if (values.has('--ssh-jump')) {
171
+ if (!hosts.length)
172
+ throw new Refusal('inapplicable_option');
173
+ jump = sshJump(values.get('--ssh-jump'));
174
+ // An existing control master would bypass the hop entirely.
175
+ if (values.has('--ssh-control-path'))
176
+ throw new Refusal('conflicting_ssh_jump');
177
+ // Win32-OpenSSH starts ProxyCommand without a POSIX shell; not yet proven.
178
+ if (process.platform === 'win32')
179
+ throw new Refusal('ssh_jump_unsupported_platform');
180
+ }
102
181
  if (values.has('--ssh-control-path')) {
103
- if (!values.has('--host'))
182
+ // One control socket multiplexes one destination, never several.
183
+ if (hosts.length !== 1)
104
184
  throw new Refusal('inapplicable_option');
105
185
  try {
106
186
  if (!lstatSync(values.get('--ssh-control-path')).isSocket())
@@ -110,15 +190,15 @@ export function parse(args) {
110
190
  throw new Refusal('invalid_ssh_control_path');
111
191
  }
112
192
  }
113
- if (values.has('--remote-platform') && (!values.has('--host') || !['posix', 'win32'].includes(values.get('--remote-platform'))))
193
+ if (values.has('--remote-platform') && (!hosts.length || !['posix', 'win32'].includes(values.get('--remote-platform'))))
114
194
  throw new Refusal('invalid_remote_platform');
115
195
  if (values.has('--remote-bin')) {
116
196
  const binary = values.get('--remote-bin');
117
- if (!values.has('--host') || (values.get('--remote-platform') === 'win32' ?
197
+ if (!hosts.length || (values.get('--remote-platform') === 'win32' ?
118
198
  !/^[A-Za-z]:\\[^\r\n]+$/.test(binary) : !/^\/[\x20-\x7e]+$/.test(binary)))
119
199
  throw new Refusal('invalid_remote_bin');
120
200
  }
121
- return { command, values, flags };
201
+ return { command, values, flags, hosts, ssh, ...(jump ? { jump } : {}), ...(address ? { address } : {}) };
122
202
  }
123
203
  async function input() {
124
204
  const chunks = [];
@@ -163,9 +243,8 @@ export function sshPreflightFailure(result, expected) {
163
243
  return 'ssh_preflight_failed';
164
244
  return undefined;
165
245
  }
166
- async function remote(options, message) {
246
+ async function remote(options, ssh, target, resolved, message, returnTo) {
167
247
  const { values, flags, command } = options;
168
- const target = host(values.get('--host'));
169
248
  const binary = values.get('--remote-bin') ?? 'session-peer';
170
249
  const windows = values.get('--remote-platform') === 'win32';
171
250
  const invoke = (flag) => {
@@ -175,9 +254,11 @@ async function remote(options, message) {
175
254
  const code = `& '${binary.replace(/['\u2018-\u201b]/g, '$&$&')}' ${flag}`;
176
255
  return `powershell.exe -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(code, 'utf16le').toString('base64')}`;
177
256
  };
178
- const ssh = executable('ssh');
257
+ // OpenSSH keeps the first value obtained, so the fixed hardening options
258
+ // precede the allowlisted user options and cannot be overridden by them.
179
259
  const base = ['-T', '-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=yes', '-o', 'ConnectTimeout=10',
180
- ...(values.has('--ssh-control-path') ? ['-S', values.get('--ssh-control-path')] : []), '--', target];
260
+ ...(options.jump ? jumpOptions(ssh, options.jump) : []),
261
+ ...(values.has('--ssh-control-path') ? ['-S', values.get('--ssh-control-path')] : []), ...resolved.options, ...options.ssh.args, '--', target];
181
262
  const preflight = await run(ssh, [...base, invoke('--version')], { timeout: 15000 });
182
263
  const preflightError = sshPreflightFailure(preflight, VERSION_LINE);
183
264
  if (preflightError)
@@ -194,6 +275,9 @@ async function remote(options, message) {
194
275
  args.push('--allow-inactive-codex-home');
195
276
  if (command === 'send')
196
277
  args.push(`--message=${message}`, '--no-from', '--no-reply-to');
278
+ // The destination probes back to this machine; the request carries only the host.
279
+ if (returnTo)
280
+ args.push('--return-route-host', returnTo);
197
281
  const done = await run(ssh, [...base, invoke('--stdio-request')], {
198
282
  timeout: 90000, input: JSON.stringify({ schemaVersion: 1, args })
199
283
  });
@@ -213,15 +297,83 @@ async function remote(options, message) {
213
297
  return uncertain();
214
298
  if (command === 'doctor' && value.ok && (value.diagnosticCompleted !== true || typeof value.ready !== 'boolean' || value.implementation !== 'typescript' || !value.agents || typeof value.agents !== 'object' || Array.isArray(value.agents)))
215
299
  return uncertain();
300
+ const probe = value.returnRoute;
301
+ if (command === 'doctor' && value.ok && returnTo && (!probe || typeof probe !== 'object' || !['verified', 'failed'].includes(probe.status) || !['local', 'ssh'].includes(probe.transport)))
302
+ return uncertain();
216
303
  const expectedStatus = flags.has('--dry-run') ? 'validated' : values.get('--to')?.startsWith('codex:') ? 'queued' : 'posted';
217
304
  if (command === 'send' && (value.consumptionConfirmed !== false ||
218
305
  (value.ok && (value.submitted !== !flags.has('--dry-run') || value.status !== expectedStatus)) ||
219
306
  (!value.ok && !((value.submitted === false && value.status === 'refused') || (value.submitted === null && value.status === 'unknown')))))
220
307
  return uncertain();
221
- return { value: { ...value, host: target, sshHost: target }, exitCode: done.code };
308
+ if (command === 'send' && value.ok) {
309
+ const target = value.target;
310
+ const requestedTarget = values.get('--to') ?? '';
311
+ const requestedCodexThread = requestedTarget.startsWith('codex:') ? requestedTarget.slice(6) : undefined;
312
+ const validTarget = target && !Array.isArray(target) &&
313
+ (target.agent === undefined || target.agent === (requestedCodexThread ? 'codex' : 'claude')) &&
314
+ (requestedCodexThread
315
+ ? typeof target.id === 'string' && uuid(target.id) && target.id.toLowerCase() === requestedCodexThread.toLowerCase()
316
+ : Number.isSafeInteger(target.pid) && target.pid > 0 &&
317
+ (typeof target.name === 'string' || target.name === null));
318
+ if (!validTarget)
319
+ return uncertain();
320
+ }
321
+ // `clientUpdate` is client-local: a remote-supplied value is never trusted or shown.
322
+ delete value.clientUpdate;
323
+ return { value: { ...value, host: resolved.canonical, sshHost: target }, exitCode: done.code };
324
+ }
325
+ function failure(error, command, where) {
326
+ const unknown = error instanceof UnknownOutcome;
327
+ const refusal = error instanceof Refusal ? error : new Refusal('operation_failed', 1);
328
+ const homeResolution = error instanceof HomeRefusal || error instanceof CodexUnknownOutcome ? error.codexHomeResolution : undefined;
329
+ return { exitCode: unknown ? 1 : refusal.exitCode, value: { schemaVersion: 1, host: where, command, ok: false,
330
+ error: unknown ? 'outcome_unknown' : refusal.code, status: unknown ? 'unknown' : 'refused',
331
+ submitted: unknown ? null : false, consumptionConfirmed: false, retryAllowed: false,
332
+ ...(homeResolution === undefined ? {} : { codexHomeResolution: homeResolution }),
333
+ ...(error instanceof UpdateRefusal ? error.guidance : {}) } };
334
+ }
335
+ // Destinations run in order, one attempt each. A failure or unknown outcome is
336
+ // reported for that destination only; it is never retried or failed over.
337
+ async function remotes(options, status, message, returnTo) {
338
+ const ssh = executable('ssh'), results = [];
339
+ let exitCode = 0;
340
+ for (const requestedHost of options.hosts) {
341
+ const target = host(requestedHost);
342
+ let outcome, user = {}, canonical = target;
343
+ try {
344
+ // A known offline or ambiguous tailnet peer is refused before any SSH process.
345
+ const resolved = route(target, status);
346
+ canonical = resolved.canonical;
347
+ const hostName = resolved.hostName ? ['-o', `HostName=${resolved.hostName}`] : [];
348
+ // One `ssh -G` serves the user metadata and, for a resolved peer, shows
349
+ // whether ssh_config already pins a HostKeyAlias. Ours is added only when
350
+ // the configuration was read and has none; an unread one is never overridden.
351
+ let alias = [];
352
+ try {
353
+ const config = await sshConfig(ssh, target, { ...options.ssh, args: [...hostName, ...options.ssh.args] }, !!resolved.hostName);
354
+ user = config.user;
355
+ if (resolved.hostKeyAlias && config.read && !config.hostKeyAlias)
356
+ alias = ['-o', `HostKeyAlias=${resolved.hostKeyAlias}`];
357
+ }
358
+ catch {
359
+ user = { sshUser: null, sshUserSource: 'unknown' };
360
+ }
361
+ // Metadata never blocks or aborts a destination; earlier results are kept.
362
+ outcome = await remote(options, ssh, target, { canonical, options: [...hostName, ...alias] }, message, returnTo);
363
+ }
364
+ // One destination keeps the existing flat local-host failure shape.
365
+ catch (error) {
366
+ outcome = failure(error, options.command, options.hosts.length === 1 ? hostname() : canonical !== target ? canonical : requestedHost);
367
+ }
368
+ results.push({ ...outcome.value, ...(options.hosts.length > 1 && canonical === target ? { host: requestedHost } : {}), sshHost: target, ...user,
369
+ ...(options.jump ? { sshJump: options.jump.spec } : {}) });
370
+ exitCode = options.hosts.length === 1 ? outcome.exitCode : outcome.exitCode === 0 && exitCode === 0 ? 0 : 1;
371
+ }
372
+ return { value: results, exitCode };
222
373
  }
223
374
  let command = 'unknown';
224
375
  let format = 'json';
376
+ let wire = false;
225
377
  try {
226
378
  const [major, minor] = process.versions.node.split('.').map(Number);
227
379
  if (!((major === 22 && minor >= 13) || major === 24))
@@ -229,13 +381,15 @@ try {
229
381
  if (!['darwin', 'linux', 'win32'].includes(process.platform))
230
382
  throw new Refusal('unsupported_platform');
231
383
  let args = process.argv.slice(2);
232
- if (args.length === 1 && args[0] === '--version')
384
+ if (args.length === 1 && args[0] === REFRESH_ARG)
385
+ await refreshCache();
386
+ else if (args.length === 1 && args[0] === '--version')
233
387
  console.log(VERSION_LINE);
234
388
  else if ((args.length === 1 && ['--help', '-h'].includes(args[0])) ||
235
- (args.length === 2 && ['list', 'send', 'doctor'].includes(args[0]) && ['--help', '-h'].includes(args[1])))
389
+ (args.length === 2 && ['list', 'send', 'doctor', 'update'].includes(args[0]) && ['--help', '-h'].includes(args[1])))
236
390
  console.log(help(args.length === 2 ? args[0] : undefined));
237
391
  else {
238
- const wire = args.length === 1 && args[0] === '--stdio-request';
392
+ wire = args.length === 1 && args[0] === '--stdio-request';
239
393
  if (wire) {
240
394
  let request;
241
395
  try {
@@ -249,14 +403,25 @@ try {
249
403
  throw new Refusal('invalid_remote_request');
250
404
  args = record.args;
251
405
  }
252
- command = ['list', 'send', 'doctor'].includes(args[0] ?? '') ? args[0] : 'unknown';
406
+ command = ['list', 'send', 'doctor', 'update'].includes(args[0] ?? '') ? args[0] : 'unknown';
253
407
  const options = parse(args);
254
408
  format = !wire && options.values.get('--output-format') === 'text' ? 'text' : 'json';
255
409
  if (wire && options.values.get('--output-format') === 'text')
256
410
  throw new Refusal('remote_json_required');
257
- if (wire && (options.values.has('--host') || options.values.has('--remote-bin') || options.values.has('--remote-platform') || options.values.has('--ssh-control-path')))
411
+ if (wire && command === 'update')
412
+ throw new Refusal('remote_update_unsupported');
413
+ if (wire && (options.address || options.hosts.length || options.ssh.args.length || options.jump || options.values.has('--remote-bin') || options.values.has('--remote-platform') || options.values.has('--ssh-control-path') ||
414
+ options.values.has('--reply-to') || options.flags.has('--check-return-route')))
258
415
  throw new Refusal('nested_transport_forbidden');
259
- let message;
416
+ if (!wire && options.values.has('--return-route-host'))
417
+ throw new Refusal('unsupported_option');
418
+ // Tailscale status is queried at most once, and only when a route needs it.
419
+ let status, queried = false;
420
+ const tailnetStatus = async () => { if (!queried) {
421
+ queried = true;
422
+ status = await tailnet();
423
+ } return status; };
424
+ let message, routing = {};
260
425
  if (command === 'send') {
261
426
  message = options.values.get('--message');
262
427
  if (message === undefined || message === '-') {
@@ -265,30 +430,108 @@ try {
265
430
  message = await input();
266
431
  }
267
432
  checkMessage(message);
268
- message = envelope(message, options.flags.has('--no-from'), options.values.get('--reply-address'));
433
+ const noFrom = options.flags.has('--no-from'), noReply = options.flags.has('--no-reply-to');
434
+ if (options.address) {
435
+ const resolution = { uri: options.address.uri, transport: options.address.transport };
436
+ // A reply URI naming this user on this machine is delivered locally.
437
+ if (options.address.implicit && options.address.transport === 'ssh' && isSelf(host(options.hosts[0]), await tailnetStatus())) {
438
+ options.hosts = [];
439
+ requested = [];
440
+ Object.assign(resolution, { transport: 'local', normalizedFrom: 'ssh_self' });
441
+ }
442
+ routing.addressResolution = resolution;
443
+ }
444
+ const identity = wire || (noFrom && noReply) ? undefined : sender();
445
+ let address = options.values.get('--reply-address');
446
+ if (!address && !noReply && identity) {
447
+ const configured = configuredHost(options.values.get('--reply-to'));
448
+ let destination = configured ? route(returnHost(configured), await tailnetStatus()).canonical : undefined;
449
+ // Sent to another machine, a loopback or non-canonical numeric reply host could name the receiver.
450
+ if (destination && options.hosts.length && unsafeReturnHost(destination))
451
+ throw new Refusal('invalid_reply_host');
452
+ const local = !options.hosts.length && (!destination || isSelf(destination, await tailnetStatus()));
453
+ if (!local && !destination) {
454
+ const detected = detectedHost(await tailnetStatus());
455
+ try {
456
+ destination = detected ? returnHost(detected) : undefined;
457
+ }
458
+ catch {
459
+ destination = undefined;
460
+ }
461
+ }
462
+ // Generated routes are inert data; SSH routes stay unverified until doctor probes them.
463
+ try {
464
+ if (local) {
465
+ address = replyUri(identity);
466
+ routing.replyRoute = { uri: address, transport: 'local', status: 'verified', reason: 'same_machine_route' };
467
+ }
468
+ else if (destination) {
469
+ address = replyUri(identity, destination);
470
+ routing.replyRoute = { uri: address, transport: 'ssh', status: 'unverified', reason: 'reverse_ssh_not_checked' };
471
+ }
472
+ }
473
+ catch {
474
+ address = undefined;
475
+ delete routing.replyRoute;
476
+ }
477
+ }
478
+ message = envelope(message, noFrom, address, identity ?? null);
269
479
  checkMessage(message, options.values.get('--to').startsWith('codex:'));
270
480
  }
271
- let result, exitCode;
481
+ let returnTo;
482
+ if (command === 'doctor' && options.flags.has('--check-return-route')) {
483
+ const configured = configuredHost(options.values.get('--reply-to')) ?? detectedHost(await tailnetStatus());
484
+ try {
485
+ returnTo = configured ? returnHost(configured) : undefined;
486
+ }
487
+ catch (error) {
488
+ if (options.values.has('--reply-to') || configuredHost())
489
+ throw error;
490
+ }
491
+ // A remote executor would read a loopback name as itself, not as this origin.
492
+ if (returnTo && options.hosts.length && unsafeReturnHost(returnTo))
493
+ throw new Refusal('invalid_return_route');
494
+ }
495
+ let result = {}, exitCode, results;
272
496
  // Propagate the verified remote exit code so SSH and local refusals match.
273
- if (options.values.has('--host'))
274
- ({ value: result, exitCode } = await remote(options, message));
497
+ if (options.hosts.length)
498
+ ({ value: results, exitCode } = await remotes(options, await tailnetStatus(), message, returnTo));
275
499
  else if (command === 'send')
276
500
  result = await send({ to: options.values.get('--to'), home: options.values.get('--codex-home'), codexBin: options.values.get('--codex-bin'), message: message, dryRun: options.flags.has('--dry-run'), allowInactive: options.flags.has('--allow-inactive-codex-home') });
277
- else if (command === 'doctor')
501
+ else if (command === 'update')
502
+ result = options.flags.has('--check') ? await checkUpdate(options.values.get('--channel')) : refuseSelfUpdate(options.values.get('--channel'));
503
+ else if (command === 'doctor') {
278
504
  result = await doctor(options.values.get('--agent'), options.values.get('--codex-home'), options.values.get('--codex-bin'));
505
+ // Opt-in reverse probe: locally, or on the destination when it arrives over the wire.
506
+ const probeTo = wire ? options.values.get('--return-route-host') : returnTo;
507
+ if (options.flags.has('--check-return-route') || probeTo)
508
+ result.returnRoute = await probeReturnRoute(probeTo && returnHost(probeTo), await tailnetStatus(), wire);
509
+ }
279
510
  else
280
511
  result = await listing(options.values.get('--agent'), options.values.get('--codex-home'), options.flags.has('--all'));
281
- console.log(renderOutput({ schemaVersion: 1, host: hostname(), command, ok: result.ok !== false, version: VERSION, referenceVersion: '1.0.2', ...result }, format));
512
+ if (command === 'send') {
513
+ results = results?.map(item => ({ ...item, ...routing }));
514
+ result = { ...result, ...routing };
515
+ }
516
+ // Without a return host there is nothing to probe from the destination.
517
+ if (command === 'doctor' && options.flags.has('--check-return-route') && !returnTo)
518
+ results = results?.map(item => item.ok === false ? item : ({ ...item, returnRoute: { status: 'failed', transport: 'ssh', host: null, reason: 'return_host_unavailable' } }));
519
+ const shape = (item) => ({ schemaVersion: 1, host: hostname(), command, ok: item.ok !== false, version: VERSION, referenceVersion: '1.0.2', ...item });
520
+ // Cached advisory notice, computed once per invocation by this client and never
521
+ // in wire mode. JSON: additive `clientUpdate` on a flat (single-result) object
522
+ // only; a repeated --host array keeps its exact element shape. Text: one stderr line.
523
+ const notice = wire || command === 'update' ? undefined : updateNotice(options.flags.has('--no-update-notice'));
524
+ const array = !!results && results.length > 1;
525
+ // One destination stays flat; repeated --host returns an ordered array.
526
+ console.log(renderOutput(array ? results.map(shape) : { ...shape(results?.[0] ?? result), ...(notice && format === 'json' ? { clientUpdate: notice } : {}) }, format));
527
+ if (notice && format === 'text')
528
+ console.error(noticeText(notice));
282
529
  process.exitCode = exitCode ?? (result.ok === false ? 1 : 0);
283
530
  }
284
531
  }
285
532
  catch (error) {
286
- const unknown = error instanceof UnknownOutcome;
287
- const failure = error instanceof Refusal ? error : new Refusal('operation_failed', 1);
288
- const homeResolution = error instanceof HomeRefusal || error instanceof CodexUnknownOutcome ? error.codexHomeResolution : undefined;
289
- console.log(renderOutput({ schemaVersion: 1, host: hostname(), command, ok: false,
290
- error: unknown ? 'outcome_unknown' : failure.code, status: unknown ? 'unknown' : 'refused',
291
- submitted: unknown ? null : false, consumptionConfirmed: false, retryAllowed: false,
292
- ...(homeResolution === undefined ? {} : { codexHomeResolution: homeResolution }) }, format));
293
- process.exitCode = unknown ? 1 : failure.exitCode;
533
+ // A command-wide refusal before dispatch applies to every requested host.
534
+ const { value, exitCode } = failure(error, command, hostname());
535
+ console.log(renderOutput(!wire && requested.length > 1 ? requested.map(item => ({ ...value, host: item })) : value, format));
536
+ process.exitCode = exitCode;
294
537
  }
@@ -7,6 +7,8 @@ export declare const capabilities: {
7
7
  list: boolean;
8
8
  send: boolean;
9
9
  doctor: boolean;
10
+ updateCheck: boolean;
11
+ selfUpdate: boolean;
10
12
  wake: boolean;
11
13
  wait: boolean;
12
14
  ack: boolean;
@@ -13,7 +13,7 @@ const failure = (error, missing, unknown) => {
13
13
  { status: 'unknown', code: unknown };
14
14
  };
15
15
  export const capabilities = {
16
- list: true, send: true, doctor: true, wake: false, wait: false, ack: false,
16
+ list: true, send: true, doctor: true, updateCheck: true, selfUpdate: false, wake: false, wait: false, ack: false,
17
17
  consumptionConfirmation: false, transports: ['local', 'ssh'], agents: ['claude', 'codex']
18
18
  };
19
19
  function tool(name) {
package/dist/discovery.js CHANGED
@@ -1,8 +1,9 @@
1
1
  // Read-only discovery: no inbox connections, writer selection, queue or DB writes.
2
2
  // Windows Claude metadata uses native process inspection.
3
- import { lstatSync, readFileSync, readlinkSync, readdirSync, realpathSync, statSync } from 'node:fs';
3
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, readlinkSync, readSync, readdirSync, realpathSync, statSync } from 'node:fs';
4
4
  import { homedir } from 'node:os';
5
5
  import { dirname, isAbsolute, join, resolve } from 'node:path';
6
+ import { parse as parseTOML } from 'smol-toml';
6
7
  import { windowsProcessStart } from './windows.js';
7
8
  export class Refusal extends Error {
8
9
  code;
@@ -26,7 +27,12 @@ export function sqliteHome(home) {
26
27
  catch (error) {
27
28
  return ['ENOENT', 'ENOTDIR'].includes(error.code ?? '') ? 'default' : 'unknown';
28
29
  }
29
- return /^[ \t]*["']?sqlite_home["']?[ \t]*=/m.test(text) ? 'configured' : 'default';
30
+ try {
31
+ return Object.hasOwn(parseTOML(text), 'sqlite_home') ? 'configured' : 'default';
32
+ }
33
+ catch {
34
+ return 'unknown';
35
+ }
30
36
  }
31
37
  function missing(error) {
32
38
  return ['ENOENT', 'ENOTDIR'].includes(error.code ?? '');
@@ -76,6 +82,36 @@ function alive(pid) {
76
82
  return error.code === 'EPERM';
77
83
  }
78
84
  }
85
+ // Local Claude registry metadata is limited to 1 MiB per regular file. The
86
+ // descriptor checks and POSIX nonblocking open also cover replacement by a FIFO
87
+ // between lstat and open; this is not a deadline for network filesystem I/O.
88
+ function claudeRecord(file) {
89
+ const limit = 1024 * 1024, before = lstatSync(file);
90
+ if (!before.isFile() || before.size > limit)
91
+ return undefined;
92
+ const flags = constants.O_RDONLY | (process.platform === 'win32' ? 0 : constants.O_NONBLOCK | constants.O_NOFOLLOW);
93
+ const fd = openSync(file, flags);
94
+ try {
95
+ const opened = fstatSync(fd);
96
+ if (!opened.isFile() || opened.size > limit || opened.dev !== before.dev || opened.ino !== before.ino)
97
+ return undefined;
98
+ const bytes = Buffer.alloc(limit + 1);
99
+ let length = 0;
100
+ while (length < bytes.length) {
101
+ const count = readSync(fd, bytes, length, bytes.length - length, length);
102
+ if (!count)
103
+ break;
104
+ length += count;
105
+ }
106
+ // Read at most limit + 1 even if metadata grows after the descriptor check.
107
+ if (length > limit || fstatSync(fd).size > limit)
108
+ return undefined;
109
+ return JSON.parse(bytes.subarray(0, length).toString('utf8'));
110
+ }
111
+ finally {
112
+ closeSync(fd);
113
+ }
114
+ }
79
115
  export function claude(all) {
80
116
  const directory = join(process.env.CLAUDE_CONFIG_DIR || process.env.ANTHROPIC_CONFIG_DIR || join(homedir(), '.claude'), 'sessions');
81
117
  let entries;
@@ -94,7 +130,7 @@ export function claude(all) {
94
130
  continue;
95
131
  let record;
96
132
  try {
97
- const value = JSON.parse(readFileSync(join(directory, entry), 'utf8'));
133
+ const value = claudeRecord(join(directory, entry));
98
134
  if (!value || typeof value !== 'object' || Array.isArray(value))
99
135
  continue;
100
136
  record = value;
package/dist/help.js CHANGED
@@ -3,11 +3,19 @@ export function help(command) {
3
3
  const common = `Output (required for operations; no default):
4
4
  --json | --output-format json|text JSON stays one machine-readable object
5
5
  Transport:
6
- --host HOST SSH destination (no nested transports)
6
+ --host [USER@]HOST SSH destination; repeat for ordered per-host results
7
+ (IPv6: 2001:db8::1 or [2001:db8::1]; no nested transports)
8
+ --ssh-opt OPT Allowlisted ssh option, repeatable: -p PORT, -l USER,
9
+ -i IDENTITY_FILE, -o Port|User|IdentityFile|IdentitiesOnly=VALUE,
10
+ -4, -6. Other options (ProxyJump, ProxyCommand, -F...) are refused
11
+ --ssh-jump USER@HOST[:PORT] One hardened jump host for every --host (POSIX clients;
12
+ fixed ProxyCommand with BatchMode/StrictHostKeyChecking)
7
13
  --remote-bin ABSOLUTE_PATH Remote session-peer executable
8
14
  --remote-platform posix|win32 Remote shell platform
9
- --ssh-control-path SOCKET Existing SSH control socket
10
- --no-update-notice Accepted compatibility flag
15
+ --ssh-control-path SOCKET Existing SSH control socket (one --host only)
16
+ Tailscale status is a routing hint only (SESSION_PEER_TAILSCALE=off skips it):
17
+ known online peers use their MagicDNS name, known offline peers are refused.
18
+ --no-update-notice Suppress the opt-in cached update notice
11
19
  -h, --help Show command help`;
12
20
  if (command === 'list')
13
21
  return `Usage: session-peer list [options]
@@ -23,7 +31,21 @@ Successful diagnostics exit 0 even when ready=false. Check readiness separately.
23
31
  --agent claude|codex Filter one agent (default: both)
24
32
  --codex-home HOME Pin Codex metadata inspection
25
33
  --codex-bin PATH Inspect executable availability; never execute it
34
+ --check-return-route Probe noninteractive SSH back to the return host
35
+ --reply-to USER@HOST Return host to probe (default: reply-host env or tailnet)
36
+ Forward reachability never implies a working return route.
26
37
  ${common}`;
38
+ if (command === 'update')
39
+ return `Usage: session-peer update --check [options]
40
+ Check the npm registry for a newer session-peer. Never installs or replaces files.
41
+ Without --check, refuses (self_update_unsupported) and names the owning manager's command.
42
+ --check Read the npm dist-tag (one request, 3 s timeout)
43
+ --channel latest|preview npm dist-tag to compare (default: latest)
44
+ Output (required; no default):
45
+ --json | --output-format json|text JSON stays one machine-readable object
46
+ -h, --help Show command help
47
+ Skills, Python installations and remote hosts are updated separately.
48
+ Notices on other commands are opt-in: SESSION_PEER_UPDATE_NOTICE=1.`;
27
49
  if (command === 'send')
28
50
  return `Usage: session-peer send --to TARGET [MESSAGE | --message TEXT | -m TEXT] [options]
29
51
  TARGET: Claude name/PID, claude:NAME/PID, codex:UUID, or session-peer reply URI.
@@ -33,9 +55,13 @@ Unicode names use exact Unicode 14.0.0 default casefold; collisions require PID.
33
55
  --codex-home HOME Explicit Codex home; otherwise select unique live writer
34
56
  --codex-bin PATH Native Codex executable
35
57
  --allow-inactive-codex-home Queue only with explicit verified inactive home
36
- --no-from Omit sender envelope
58
+ --no-from Omit detected Claude/Codex sender (From)
37
59
  --no-reply-to Do not add a reply route
38
- --reply-address URI Explicit reply route (conflicts with --no-reply-to)
60
+ --reply-address URI Explicit reply route
61
+ --reply-to HOST Return host for the generated route; precedence:
62
+ --reply-to, SESSION_PEER_REPLY_HOST, CC_PEER_REPLY_HOST,
63
+ tailnet address. The three reply options are exclusive.
64
+ Sender and Reply-To are inert metadata, never authentication.
39
65
  Queued/posted is not ACK. Unknown outcomes must not be retried automatically.
40
66
  ${common}`;
41
67
  return `session-peer ${VERSION} (TypeScript)
@@ -43,6 +69,7 @@ Usage: session-peer <command> [options]
43
69
  list List Claude/Codex sessions
44
70
  send Submit one guarded message
45
71
  doctor Inspect read-only metadata and capabilities
72
+ update --check Check npm for a newer version (no self-update)
46
73
  --version Print exact runtime version
47
74
  --help, -h Show help; <command> --help for details
48
75
  ${common}