session-peer 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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}
package/dist/output.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  export type OutputFormat = 'json' | 'text';
2
- export declare function renderOutput(value: Record<string, unknown>, format: OutputFormat): string;
2
+ export declare function renderOutput(value: Record<string, unknown> | Record<string, unknown>[], format: OutputFormat): string;
package/dist/output.js CHANGED
@@ -1,8 +1,11 @@
1
- // Escape terminal control characters in user-controlled names/paths; preserve Unicode.
2
- const safe = (value) => String(value ?? '').replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g, char => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
1
+ // Escape terminal controls plus bidi/zero-width format characters in
2
+ // user-controlled names/paths; preserve other Unicode.
3
+ const safe = (value) => String(value ?? '').replace(/[\x00-\x1f\x7f-\x9f\u061c\u200b-\u200f\u2028-\u202e\u2060-\u2069\ufeff]/g, char => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
3
4
  export function renderOutput(value, format) {
4
5
  if (format === 'json')
5
6
  return JSON.stringify(value);
7
+ if (Array.isArray(value))
8
+ return value.map(item => `Host: ${safe(item.host)}\n${renderOutput(item, format)}`).join('\n\n');
6
9
  const lines = [];
7
10
  if (value.command === 'list') {
8
11
  const sessions = Array.isArray(value.sessions) ? value.sessions : [];
@@ -23,6 +26,17 @@ export function renderOutput(value, format) {
23
26
  lines.push(`Ready: ${value.ready === true ? 'yes' : 'no'}`);
24
27
  lines.push(`Agents: ${safe(JSON.stringify(value.agents ?? {}))}`);
25
28
  lines.push(`Capabilities: ${safe(JSON.stringify(value.capabilities ?? {}))}`);
29
+ const route = value.returnRoute;
30
+ lines.push(route ? `Return route: ${safe(route.status)} via ${safe(route.transport)} (${safe(route.reason)})` : 'Return route: not checked (use --check-return-route)');
31
+ }
32
+ else if (value.command === 'update' && value.ok === true) {
33
+ lines.push(`session-peer ${safe(value.current)} (typescript): ${value.status === 'update_available' ? `${safe(value.latest)} available` :
34
+ value.status === 'ahead' ? `newer than ${safe(value.latest)}` : 'up to date'} on npm dist-tag ${safe(value.distTag)}.`);
35
+ if (value.outdated === true)
36
+ lines.push(value.updateCommand ? `Upgrade with: ${safe(value.updateCommand)}` : safe(value.guidance));
37
+ if (value.cache === 'skipped_stale_lock')
38
+ lines.push('Update cache not written: a stale npm-update.lock remains; delete it while no session-peer process runs.');
39
+ lines.push('Skills, Python installations and remote hosts are updated separately.');
26
40
  }
27
41
  else if (value.ok === true) {
28
42
  const target = value.target;
@@ -35,6 +49,8 @@ export function renderOutput(value, format) {
35
49
  }
36
50
  if (value.ok === false) {
37
51
  lines.push(`Error: ${safe(value.error ?? 'operation_failed')}`);
52
+ if (value.command === 'update' && value.error === 'self_update_unsupported')
53
+ lines.push(value.updateCommand ? `This installation is managed by ${safe(value.managedBy)}. Upgrade with: ${safe(value.updateCommand)}` : safe(value.guidance));
38
54
  if (value.command === 'send')
39
55
  lines.push(value.submitted === null ? 'Submission outcome unknown. Do not retry automatically.' : 'Nothing submitted.');
40
56
  }
package/dist/process.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export declare class UnknownOutcome extends Error {
2
2
  }
3
+ export declare const batchShim: (path: string) => boolean;
3
4
  export declare function executable(name: string): string;
4
5
  export type Done = {
5
6
  code: number | null;
package/dist/process.js CHANGED
@@ -4,28 +4,105 @@ import { delimiter, isAbsolute, join } from 'node:path';
4
4
  import { Refusal } from './discovery.js';
5
5
  export class UnknownOutcome extends Error {
6
6
  }
7
+ // Node refuses to spawn .cmd/.bat without a shell (CVE-2024-27980), and a shell
8
+ // would interpret the message argv, so Windows batch shims are unsupported.
9
+ export const batchShim = (path) => process.platform === 'win32' && /\.(?:cmd|bat)$/i.test(path);
7
10
  export function executable(name) {
8
11
  const windows = process.platform === 'win32';
9
12
  const names = windows && !/\.(?:exe|cmd|bat)$/i.test(name) ? [name + '.exe', name + '.cmd', name] : [name];
10
13
  const paths = isAbsolute(name) ? [name] : name.includes('/') || name.includes('\\') ? [] :
11
14
  (process.env.PATH ?? '').split(delimiter).filter(Boolean).flatMap(p => names.map(n => join(p, n)));
12
15
  for (const path of paths) {
16
+ let found = false;
13
17
  try {
14
18
  accessSync(path, constants.X_OK);
15
- if (statSync(path).isFile())
16
- return realpathSync(path);
19
+ found = statSync(path).isFile();
20
+ }
21
+ catch { }
22
+ if (!found)
23
+ continue;
24
+ // Keep PATH precedence: a first-match shim is refused, not bypassed.
25
+ if (batchShim(path))
26
+ throw new Refusal('executable_unsupported', 1);
27
+ try {
28
+ return realpathSync(path);
17
29
  }
18
30
  catch { }
19
31
  }
20
32
  throw new Refusal('executable_unavailable', 1);
21
33
  }
34
+ // On POSIX every child is started detached: a new session and process group
35
+ // with no controlling terminal. A timeout, an output overflow or a signal to
36
+ // this CLI reaps that group, which includes descendants such as a jump
37
+ // ProxyCommand, and nothing else; a descendant that calls setsid() itself has
38
+ // left the group and is out of scope (there is no PID scanning). Windows has no
39
+ // equivalent here: only the child is killed and descendants may linger.
40
+ const groups = new Set();
41
+ const posix = process.platform !== 'win32';
42
+ const reap = (pid) => { if (pid)
43
+ try {
44
+ process.kill(-pid, 'SIGKILL');
45
+ }
46
+ catch { /* Already gone (ESRCH). */ } };
47
+ const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
48
+ // A detached group no longer receives the terminal's Ctrl-C, so forward
49
+ // termination signals as a group kill, then re-raise with default handling.
50
+ function forward(signal) {
51
+ for (const pid of groups)
52
+ reap(pid);
53
+ groups.clear();
54
+ for (const name of signals)
55
+ process.removeListener(name, forward);
56
+ process.kill(process.pid, signal);
57
+ }
22
58
  export function run(binary, args, options = {}) {
23
59
  return new Promise(resolve => {
24
- let stdout = '', stderr = '', bytes = 0, spawned = false, interrupted = false;
25
- const child = spawn(binary, args, { shell: false, env: options.env ?? process.env, stdio: ['pipe', 'pipe', 'pipe'] });
26
- const stop = () => { interrupted = true; child.kill('SIGKILL'); };
60
+ let stdout = '', stderr = '', bytes = 0, spawned = false, interrupted = false, finished = false, stopped = false;
61
+ const child = spawn(binary, args, { shell: false, env: options.env ?? process.env, stdio: ['pipe', 'pipe', 'pipe'], detached: posix });
62
+ const release = () => {
63
+ if (child.pid === undefined || !groups.delete(child.pid) || groups.size)
64
+ return;
65
+ for (const name of signals)
66
+ process.removeListener(name, forward);
67
+ };
68
+ const finish = (code) => {
69
+ if (finished)
70
+ return;
71
+ finished = true;
72
+ clearTimeout(timer);
73
+ release();
74
+ resolve({ code, stdout, stderr, spawned, interrupted });
75
+ };
76
+ const stop = () => {
77
+ if (stopped || finished)
78
+ return;
79
+ stopped = interrupted = true;
80
+ if (posix)
81
+ reap(child.pid);
82
+ else
83
+ child.kill('SIGKILL');
84
+ // A descendant outside our reach (Windows) may still hold the pipes:
85
+ // stop reading so completion depends on the exit, not on their close.
86
+ child.stdin.destroy();
87
+ child.stdout.destroy();
88
+ child.stderr.destroy();
89
+ // Already exited (only a descendant was left): complete after the grace.
90
+ if (child.exitCode !== null || child.signalCode !== null)
91
+ setTimeout(() => finish(child.exitCode), 100);
92
+ };
27
93
  const timer = setTimeout(stop, options.timeout ?? 3000);
28
- child.once('spawn', () => { spawned = true; });
94
+ const register = () => {
95
+ if (!posix || child.pid === undefined || groups.has(child.pid))
96
+ return;
97
+ if (!groups.size)
98
+ for (const name of signals)
99
+ process.on(name, forward);
100
+ groups.add(child.pid);
101
+ };
102
+ // Register as soon as the PID exists, so a signal arriving before the
103
+ // 'spawn' event still reaps the group; 'spawn' remains the fallback.
104
+ register();
105
+ child.once('spawn', () => { spawned = true; register(); });
29
106
  child.stdin.on('error', () => { });
30
107
  child.stdout.setEncoding('utf8');
31
108
  child.stdout.on('data', (part) => {
@@ -45,7 +122,13 @@ export function run(binary, args, options = {}) {
45
122
  stop();
46
123
  });
47
124
  child.once('error', () => { interrupted = true; });
48
- child.once('close', code => { clearTimeout(timer); resolve({ code, stdout, stderr, spawned, interrupted }); });
125
+ // After a kill, the exit plus a short fixed grace bounds completion even if
126
+ // a pipe never closes; otherwise 'close' (all output read) completes it.
127
+ // A descendant that keeps the pipes open after the child exits runs into
128
+ // the same deadline and is reaped with the group.
129
+ child.once('exit', code => { if (stopped)
130
+ setTimeout(() => finish(code), 100); });
131
+ child.once('close', code => finish(code));
49
132
  child.stdin.end(options.input);
50
133
  });
51
134
  }
@@ -1,9 +1,12 @@
1
- export declare const VERSION = "0.2.0";
2
- export declare const VERSION_LINE = "session-peer 0.2.0 (typescript)";
1
+ export declare const VERSION = "0.3.0";
2
+ export declare const VERSION_LINE = "session-peer 0.3.0 (typescript)";
3
3
  export declare function host(value: string): string;
4
4
  export declare function reply(value: string): {
5
5
  to: string;
6
6
  host?: string;
7
7
  home?: string;
8
8
  };
9
- export declare function envelope(text: string, noFrom: boolean, address?: string): string;
9
+ export declare function envelope(text: string, noFrom: boolean, address?: string, sender?: {
10
+ agent: string;
11
+ id: string;
12
+ } | null): string;
package/dist/protocol.js CHANGED
@@ -1,11 +1,19 @@
1
+ import { isIPv6 } from 'node:net';
1
2
  import { Refusal } from './discovery.js';
2
3
  import { uuid } from './writer.js';
3
- export const VERSION = '0.2.0';
4
+ export const VERSION = '0.3.0';
4
5
  export const VERSION_LINE = `session-peer ${VERSION} (typescript)`;
6
+ // Return the OpenSSH destination: [user@]name, or an IPv6 literal with any
7
+ // brackets removed (`ssh` does not strip `[...]` outside ssh:// URIs). Zone IDs
8
+ // (`%`) and other characters that OpenSSH might expand are refused.
5
9
  export function host(value) {
6
- if (value.length > 255 || !/^(?:[A-Za-z0-9_][A-Za-z0-9_.-]*@)?[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(value))
10
+ const match = value.length <= 255 ? /^((?:[A-Za-z0-9_][A-Za-z0-9_.-]*@)?)(?:\[([0-9A-Fa-f:.]+)\]|([A-Za-z0-9][A-Za-z0-9_.-]*)|([0-9A-Fa-f.]*:[0-9A-Fa-f:.]*))$/.exec(value) : null;
11
+ if (match?.[3] !== undefined)
12
+ return value;
13
+ const literal = match?.[2] ?? match?.[4];
14
+ if (literal === undefined || !isIPv6(literal))
7
15
  throw new Refusal('invalid_ssh_host');
8
- return value;
16
+ return match[1] + literal;
9
17
  }
10
18
  export function reply(value) {
11
19
  if (value.length > 4096 || /[\x00-\x20\x7f]/.test(value) || /%(?![\da-f]{2})/i.test(value))
@@ -32,6 +40,9 @@ export function reply(value) {
32
40
  throw new Refusal('invalid_reply_uri');
33
41
  if (agent !== 'codex' && fields.has('codexHome'))
34
42
  throw new Refusal('invalid_reply_uri');
43
+ // Match Python: a POSIX or Windows absolute path, never cwd- or ~-relative.
44
+ if (fields.has('codexHome') && !/^(?:\/|[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/][^\\/]+)/.test(fields.get('codexHome')))
45
+ throw new Refusal('invalid_reply_uri');
35
46
  if (transport === 'local' && fields.has('host'))
36
47
  throw new Refusal('invalid_reply_uri');
37
48
  if (transport === 'ssh' && !fields.has('host'))
@@ -40,11 +51,20 @@ export function reply(value) {
40
51
  ...(transport === 'ssh' ? { host: host(fields.get('host')) } : {}),
41
52
  ...(fields.has('codexHome') ? { home: fields.get('codexHome') } : {}) };
42
53
  }
43
- export function envelope(text, noFrom, address) {
44
- const sender = process.env.CODEX_THREAD_ID || process.env.CODEX_SESSION_ID;
45
- const from = !noFrom && sender && uuid(sender) ? `From: codex:${sender}\n\n` : '';
54
+ // `sender` is an already-detected identity (null: none). Omitted, a valid
55
+ // Codex environment UUID is used, as in earlier versions.
56
+ export function envelope(text, noFrom, address, sender) {
57
+ const thread = process.env.CODEX_THREAD_ID || process.env.CODEX_SESSION_ID;
58
+ const identity = sender !== undefined ? sender : thread && uuid(thread) ? { agent: 'codex', id: thread } : null;
59
+ const from = !noFrom && identity ? `From: ${identity.agent}:${identity.id}\n\n` : '';
46
60
  if (address)
47
61
  reply(address);
62
+ // Trim edge newlines by index: /\n+$/ is quadratic on long interior newline runs.
63
+ let start = 0, end = text.length;
64
+ while (start < end && text[start] === '\n')
65
+ start++;
66
+ while (end > start && text[end - 1] === '\n')
67
+ end--;
48
68
  // No inferred identity/reverse route and no executable Reply command.
49
- return from + text.replace(/^\n+|\n+$/g, '') + (address ? `\n\n---\nReply-To: ${address}` : '');
69
+ return from + text.slice(start, end) + (address ? `\n\n---\nReply-To: ${address}` : '');
50
70
  }
@@ -0,0 +1,30 @@
1
+ export type Sender = {
2
+ agent: 'claude' | 'codex';
3
+ id: string;
4
+ codexHome?: string;
5
+ };
6
+ type Node = Record<string, unknown>;
7
+ export type Tailnet = {
8
+ magicDNS: boolean;
9
+ self?: Node;
10
+ nodes: Node[];
11
+ };
12
+ export declare function sender(): Sender | undefined;
13
+ export declare function tailnet(): Promise<Tailnet | undefined>;
14
+ export type Route = {
15
+ canonical: string;
16
+ hostName?: string;
17
+ hostKeyAlias?: string;
18
+ };
19
+ export declare function route(destination: string, status?: Tailnet): Route;
20
+ export declare function unsafeReturnHost(destination: string): boolean;
21
+ export declare function localName(destination: string): boolean;
22
+ export declare function namesThisMachine(destination: string, status?: Tailnet): boolean;
23
+ export declare function localUser(): string | undefined;
24
+ export declare function isSelf(destination: string, status?: Tailnet): boolean;
25
+ export declare function detectedHost(status?: Tailnet): string | undefined;
26
+ export declare function configuredHost(explicit?: string): string | undefined;
27
+ export declare function returnHost(value: string): string;
28
+ export declare function replyUri(identity: Sender, destination?: string): string;
29
+ export declare function probeReturnRoute(destination: string | undefined, status?: Tailnet, remote?: boolean): Promise<Record<string, unknown>>;
30
+ export {};
@@ -0,0 +1,283 @@
1
+ // Sender context, Tailscale routing hints and the opt-in return-route probe.
2
+ // Everything here is metadata: none of it authenticates a peer or authorizes a send.
3
+ import { isIPv6 } from 'node:net';
4
+ import { hostname, userInfo } from 'node:os';
5
+ import { isAbsolute } from 'node:path';
6
+ import { casefold } from './casefold.js';
7
+ import { canonical, claude, Refusal } from './discovery.js';
8
+ import { executable, run } from './process.js';
9
+ import { host, reply } from './protocol.js';
10
+ import { sshUser } from './ssh.js';
11
+ import { uuid } from './writer.js';
12
+ // Claude Code exports its own inbox path to child processes; Codex exports its
13
+ // thread UUID. Both together (a nested agent) or a non-unique match is
14
+ // ambiguous, so no identity is claimed.
15
+ export function sender() {
16
+ const socket = process.env.CLAUDE_CODE_MESSAGING_SOCKET ?? '';
17
+ let claudeSender, claudeClaimed = false;
18
+ if (socket) {
19
+ claudeClaimed = true;
20
+ const pid = /(\d+)\.sock$/.exec(socket)?.[1];
21
+ let rows = [];
22
+ try {
23
+ rows = claude(true).sessions;
24
+ }
25
+ catch {
26
+ rows = [];
27
+ }
28
+ const matches = rows.filter(row => row.alive === true && (pid !== undefined ? row.pid === Number(pid) : row.socket === socket));
29
+ if (matches.length === 1) {
30
+ const row = matches[0], name = typeof row.name === 'string' ? row.name : '';
31
+ // A name is a reply target only if it is printable, cannot be read as a PID
32
+ // or agent prefix, and is unique by casefold; otherwise the PID is used.
33
+ const unique = name && !/[\x00-\x1f\x7f-\x9f\u2028\u2029:]/.test(name) && !/^\d+$/.test(name) && name.length <= 256 &&
34
+ rows.filter(other => other.alive === true && typeof other.name === 'string' && casefold(other.name) === casefold(name)).length === 1;
35
+ claudeSender = { agent: 'claude', id: unique ? name : String(row.pid) };
36
+ }
37
+ }
38
+ const thread = process.env.CODEX_THREAD_ID || process.env.CODEX_SESSION_ID || '';
39
+ const conflicting = !!process.env.CODEX_THREAD_ID && !!process.env.CODEX_SESSION_ID && process.env.CODEX_THREAD_ID.toLowerCase() !== process.env.CODEX_SESSION_ID.toLowerCase();
40
+ if (thread && (claudeClaimed || conflicting))
41
+ return undefined;
42
+ if (claudeSender)
43
+ return claudeSender;
44
+ if (!thread || !uuid(thread))
45
+ return undefined;
46
+ const result = { agent: 'codex', id: thread.toLowerCase() };
47
+ const home = process.env.CODEX_HOME;
48
+ if (home && isAbsolute(home)) {
49
+ try {
50
+ result.codexHome = canonical(home);
51
+ }
52
+ catch { /* Omit an unresolvable home. */ }
53
+ }
54
+ return result;
55
+ }
56
+ const lower = (value) => typeof value === 'string' ? value.replace(/\.$/, '').toLowerCase() : '';
57
+ function names(node) {
58
+ const result = new Set(), dns = lower(node.DNSName), name = lower(node.HostName);
59
+ if (dns) {
60
+ result.add(dns);
61
+ result.add(dns.split('.')[0]);
62
+ }
63
+ if (name)
64
+ result.add(name);
65
+ if (Array.isArray(node.TailscaleIPs))
66
+ for (const address of node.TailscaleIPs)
67
+ if (typeof address === 'string')
68
+ result.add(address.toLowerCase());
69
+ return result;
70
+ }
71
+ // `tailscale status --json` is only a routing hint. Absent, stopped, slow or
72
+ // malformed status means ordinary SSH. SESSION_PEER_TAILSCALE=off skips it.
73
+ export async function tailnet() {
74
+ if (process.env.SESSION_PEER_TAILSCALE === 'off')
75
+ return undefined;
76
+ const candidates = [];
77
+ // The macOS app bundle is a fallback only when no CLI is on PATH.
78
+ try {
79
+ candidates.push(executable('tailscale'));
80
+ }
81
+ catch {
82
+ if (process.platform === 'darwin')
83
+ candidates.push('/Applications/Tailscale.app/Contents/MacOS/Tailscale');
84
+ }
85
+ for (const binary of candidates) {
86
+ const done = await run(binary, ['status', '--json'], { timeout: 3000, limit: 8 * 1024 * 1024 });
87
+ if (!done.spawned || done.interrupted || done.code !== 0)
88
+ continue;
89
+ let status;
90
+ try {
91
+ status = JSON.parse(done.stdout);
92
+ }
93
+ catch {
94
+ continue;
95
+ }
96
+ if (!status || typeof status !== 'object' || status.BackendState !== 'Running')
97
+ continue;
98
+ const tailnetInfo = status.CurrentTailnet;
99
+ const self = status.Self && typeof status.Self === 'object' ? status.Self : undefined;
100
+ const peers = status.Peer && typeof status.Peer === 'object' ? Object.values(status.Peer).filter(p => p && typeof p === 'object') : [];
101
+ return { magicDNS: !!tailnetInfo && tailnetInfo.MagicDNSEnabled === true, ...(self ? { self } : {}), nodes: [...(self ? [self] : []), ...peers] };
102
+ }
103
+ return undefined;
104
+ }
105
+ const split = (destination) => {
106
+ const at = destination.lastIndexOf('@');
107
+ return { user: at < 0 ? '' : destination.slice(0, at), name: destination.slice(at + 1) };
108
+ };
109
+ // Resolve a known tailnet node to its MagicDNS name. The requested alias stays
110
+ // the SSH destination (keeping Host/User/Port/IdentityFile config); HostName
111
+ // connects to the verified name and HostKeyAlias keeps the original known_hosts
112
+ // key unless ssh_config already sets one (decided by the caller from ssh -G).
113
+ // Exact states only: Online === true resolves, Online === false refuses, and any
114
+ // other value is ordinary SSH. Without MagicDNS a known-offline peer is still
115
+ // refused, but nothing is canonicalized because the DNS name may not resolve.
116
+ export function route(destination, status) {
117
+ const { user, name } = split(destination);
118
+ if (!status)
119
+ return { canonical: destination };
120
+ const lookup = lower(name), matches = status.nodes.filter(node => names(node).has(lookup));
121
+ if (!matches.length)
122
+ return { canonical: destination };
123
+ if (new Set(matches.map((node, index) => String(node.ID ?? node.PublicKey ?? `#${index}`))).size !== 1)
124
+ throw new Refusal('tailscale_destination_ambiguous', 1);
125
+ const node = matches[0], dns = lower(node.DNSName);
126
+ if (node.Online === false)
127
+ throw new Refusal('tailscale_peer_offline', 1);
128
+ if (node.Online !== true || !status.magicDNS || !dns || !/^[a-z0-9][a-z0-9.-]*$/.test(dns))
129
+ return { canonical: destination };
130
+ const resolved = user ? `${user}@${dns}` : dns;
131
+ return resolved === destination ? { canonical: resolved } : { canonical: resolved, hostName: dns, hostKeyAlias: name };
132
+ }
133
+ // A loopback name always means the machine that evaluates it. Sent to another
134
+ // machine as a return host, it would name the receiver, not the origin.
135
+ // Two deliberately separate predicates. Non-canonical numeric host names
136
+ // (leading zeros, fewer than four parts, hex/octal, single integers, overflow)
137
+ // mean different addresses on different resolvers, so they are never guessed:
138
+ // they always fail closed for a return host and never count as local.
139
+ const OCTET = '(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)';
140
+ const canonicalIPv4 = (name) => new RegExp(`^${OCTET}(?:\\.${OCTET}){3}$`).test(name) ? name.split('.').map(Number) : undefined;
141
+ const numericLike = (name) => /^(?:0x[0-9a-f]*|\d+)(?:\.(?:0x[0-9a-f]*|\d+))*$/.test(name);
142
+ // Canonical IPv6 text, or undefined for anything that is not an IPv6 literal.
143
+ function ipv6(name) {
144
+ const literal = name.replace(/^\[|\]$/g, '');
145
+ return literal.includes(':') && isIPv6(literal) ? new URL(`http://[${literal}]`).hostname.slice(1, -1) : undefined;
146
+ }
147
+ const mapped = (canonical) => {
148
+ const match = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(canonical);
149
+ return match ? [parseInt(match[1], 16) >> 8, parseInt(match[1], 16) & 255, parseInt(match[2], 16) >> 8, parseInt(match[2], 16) & 255] : undefined;
150
+ };
151
+ const loopbackOctets = (octets) => !!octets && (octets[0] === 127 || octets[0] === 0);
152
+ // Conservative: refuse anything that might name the machine evaluating it.
153
+ // Used only to refuse return/reply hosts that would point at a receiver.
154
+ export function unsafeReturnHost(destination) {
155
+ const name = lower(split(destination).name);
156
+ if (name === 'localhost' || name.endsWith('.localhost'))
157
+ return true;
158
+ const v6 = ipv6(name);
159
+ if (v6 !== undefined)
160
+ return v6 === '::1' || v6 === '::' || loopbackOctets(mapped(v6)) || /^::[0-9a-f]{1,4}:[0-9a-f]{1,4}$/.test(v6);
161
+ const v4 = canonicalIPv4(name);
162
+ return v4 ? loopbackOctets(v4) : numericLike(name);
163
+ }
164
+ // Strict: only exact, canonical spellings of this machine's loopback may
165
+ // normalize a route to local delivery. IPv4-compatible IPv6 (RFC 4291
166
+ // section 2.5.5.1, deprecated) and non-canonical numerics never qualify.
167
+ export function localName(destination) {
168
+ const name = lower(split(destination).name);
169
+ if (name === 'localhost')
170
+ return true;
171
+ const v6 = ipv6(name);
172
+ if (v6 !== undefined)
173
+ return v6 === '::1' || mapped(v6)?.[0] === 127;
174
+ return canonicalIPv4(name)?.[0] === 127;
175
+ }
176
+ // Whether a host name (any user) may name this machine: a known self name or an
177
+ // unprovable numeric form. Known names are only the exact OS host name and the
178
+ // Tailscale self names/addresses; other DNS or LAN aliases are not detected.
179
+ // Conservative, for the receiver side of a return-route probe; independent of
180
+ // the login user's name.
181
+ export function namesThisMachine(destination, status) {
182
+ const name = lower(split(destination).name);
183
+ if (unsafeReturnHost(name) || name === lower(hostname()))
184
+ return true;
185
+ return !!status?.self && names(status.self).has(name);
186
+ }
187
+ export function localUser() {
188
+ try {
189
+ const name = userInfo().username;
190
+ return /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/.test(name) ? name : undefined;
191
+ }
192
+ catch {
193
+ return undefined;
194
+ }
195
+ }
196
+ // Same machine only when the destination names this OS user explicitly and a
197
+ // local name; a missing or different user stays an SSH route.
198
+ export function isSelf(destination, status) {
199
+ const { user, name } = split(destination);
200
+ if (!user || user !== localUser())
201
+ return false;
202
+ const plain = lower(name);
203
+ if (numericLike(plain) && !canonicalIPv4(plain))
204
+ return false;
205
+ if (localName(destination) || plain === lower(hostname()))
206
+ return true;
207
+ // Tailscale self names and addresses, compared exactly.
208
+ return !!status?.self && names(status.self).has(plain);
209
+ }
210
+ // This machine's tailnet address: MagicDNS name, else a 100.64.0.0/10 IPv4.
211
+ export function detectedHost(status) {
212
+ if (!status?.self)
213
+ return undefined;
214
+ const dns = lower(status.self.DNSName);
215
+ if (dns && status.magicDNS)
216
+ return dns;
217
+ const addresses = Array.isArray(status.self.TailscaleIPs) ? status.self.TailscaleIPs : [];
218
+ return addresses.find((item) => typeof item === 'string' &&
219
+ /^100\.(\d{1,3})\.\d{1,3}\.\d{1,3}$/.test(item) && Number(item.split('.')[1]) >= 64 && Number(item.split('.')[1]) < 128 && item.split('.').every(part => Number(part) <= 255));
220
+ }
221
+ export function configuredHost(explicit) {
222
+ return explicit || process.env.SESSION_PEER_REPLY_HOST || process.env.CC_PEER_REPLY_HOST || undefined;
223
+ }
224
+ // Qualify a return host with this user, then validate it as an SSH destination.
225
+ export function returnHost(value) {
226
+ const user = localUser();
227
+ const qualified = value.includes('@') ? value : user ? `${user}@${value}` : value;
228
+ try {
229
+ return host(qualified);
230
+ }
231
+ catch {
232
+ throw new Refusal('invalid_reply_host');
233
+ }
234
+ }
235
+ // Build a structured URI and accept it only if the parser accepts it back.
236
+ export function replyUri(identity, destination) {
237
+ const fields = new URLSearchParams([['agent', identity.agent], ['session', identity.id], ['transport', destination ? 'ssh' : 'local'],
238
+ ...(destination ? [['host', destination]] : []), ...(identity.codexHome ? [['codexHome', identity.codexHome]] : [])]);
239
+ const uri = `session-peer://v1/reply?${fields}`;
240
+ reply(uri);
241
+ return uri;
242
+ }
243
+ // Reverse SSH reachability from this machine: fixed `exit 0` command, no prompts,
244
+ // no host-key changes, no stderr in the result, and no retry.
245
+ const PROBE = ['-T', '-o', 'BatchMode=yes', '-o', 'PasswordAuthentication=no', '-o', 'KbdInteractiveAuthentication=no',
246
+ '-o', 'NumberOfPasswordPrompts=0', '-o', 'StrictHostKeyChecking=yes', '-o', 'UpdateHostKeys=no', '-o', 'ConnectTimeout=5',
247
+ '-o', 'ConnectionAttempts=1', '-o', 'ControlMaster=no', '-o', 'ControlPath=none'];
248
+ // `remote`: the probe runs on a receiver for another origin. A name for the
249
+ // receiver itself (loopback, its host name or tailnet self) cannot verify the
250
+ // origin, so it fails instead of normalizing to a local route.
251
+ export async function probeReturnRoute(destination, status, remote = false) {
252
+ if (!destination)
253
+ return { status: 'failed', transport: 'ssh', host: null, reason: 'return_host_unavailable' };
254
+ if (remote && namesThisMachine(destination, status))
255
+ return { status: 'failed', transport: 'ssh', host: destination, reason: 'return_host_is_receiver' };
256
+ if (isSelf(destination, status))
257
+ return { status: 'verified', transport: 'local', host: hostname(), reason: 'self_route_normalized' };
258
+ let ssh;
259
+ try {
260
+ ssh = executable('ssh');
261
+ }
262
+ catch {
263
+ return { status: 'failed', transport: 'ssh', host: destination, reason: 'ssh_executable_missing' };
264
+ }
265
+ const user = await sshUser(ssh, destination, { args: [] });
266
+ // `exit 0` is a no-op in POSIX shells, cmd.exe and PowerShell alike.
267
+ const done = await run(ssh, [...PROBE, '--', destination, 'exit 0'], { timeout: 8000 });
268
+ const result = (status, reason) => ({ status, transport: 'ssh', host: destination, reason, ...user });
269
+ if (done.interrupted && done.spawned)
270
+ return result('failed', 'timeout');
271
+ if (!done.spawned)
272
+ return result('failed', 'transport_failed');
273
+ if (done.code === 0)
274
+ return result('verified', 'ssh_command_succeeded');
275
+ const detail = done.stderr;
276
+ if (/permission denied|authentication failed|no supported authentication methods|too many authentication failures/i.test(detail))
277
+ return result('failed', 'authentication_failed');
278
+ if (/host key verification failed|remote host identification has changed|offending key in|known_hosts|no [^\n]*host key is known/i.test(detail))
279
+ return result('failed', 'host_key_failed');
280
+ if (/timed out|connect timeout/i.test(detail))
281
+ return result('failed', 'timeout');
282
+ return result('failed', done.code === 255 ? 'transport_failed' : 'remote_command_failed');
283
+ }