session-peer 0.2.1 → 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/process.js CHANGED
@@ -31,13 +31,78 @@ export function executable(name) {
31
31
  }
32
32
  throw new Refusal('executable_unavailable', 1);
33
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
+ }
34
58
  export function run(binary, args, options = {}) {
35
59
  return new Promise(resolve => {
36
- let stdout = '', stderr = '', bytes = 0, spawned = false, interrupted = false;
37
- const child = spawn(binary, args, { shell: false, env: options.env ?? process.env, stdio: ['pipe', 'pipe', 'pipe'] });
38
- 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
+ };
39
93
  const timer = setTimeout(stop, options.timeout ?? 3000);
40
- 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(); });
41
106
  child.stdin.on('error', () => { });
42
107
  child.stdout.setEncoding('utf8');
43
108
  child.stdout.on('data', (part) => {
@@ -57,7 +122,13 @@ export function run(binary, args, options = {}) {
57
122
  stop();
58
123
  });
59
124
  child.once('error', () => { interrupted = true; });
60
- 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));
61
132
  child.stdin.end(options.input);
62
133
  });
63
134
  }
@@ -1,9 +1,12 @@
1
- export declare const VERSION = "0.2.1";
2
- export declare const VERSION_LINE = "session-peer 0.2.1 (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.1';
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))
@@ -43,9 +51,12 @@ export function reply(value) {
43
51
  ...(transport === 'ssh' ? { host: host(fields.get('host')) } : {}),
44
52
  ...(fields.has('codexHome') ? { home: fields.get('codexHome') } : {}) };
45
53
  }
46
- export function envelope(text, noFrom, address) {
47
- const sender = process.env.CODEX_THREAD_ID || process.env.CODEX_SESSION_ID;
48
- 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` : '';
49
60
  if (address)
50
61
  reply(address);
51
62
  // Trim edge newlines by index: /\n+$/ is quadratic on long interior newline runs.
@@ -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
+ }
package/dist/ssh.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ export type SshOptions = {
2
+ args: string[];
3
+ user?: string;
4
+ };
5
+ export type SshUser = {
6
+ sshUser: string | null;
7
+ sshUserSource: 'explicit' | 'ssh_config_or_local_default' | 'unknown';
8
+ };
9
+ export declare function sshOptions(tokens: string[]): SshOptions;
10
+ export type SshJump = {
11
+ user: string;
12
+ host: string;
13
+ port?: string;
14
+ spec: string;
15
+ };
16
+ export declare function sshJump(value: string): SshJump;
17
+ export declare function proxyCommand(ssh: string, jump: SshJump): string;
18
+ export declare function jumpOptions(ssh: string, jump: SshJump): string[];
19
+ export declare function sshConfig(ssh: string, destination: string, options: SshOptions, force?: boolean): Promise<{
20
+ user: SshUser;
21
+ read: boolean;
22
+ hostKeyAlias?: string;
23
+ }>;
24
+ export declare function sshUser(ssh: string, destination: string, options: SshOptions): Promise<SshUser>;
package/dist/ssh.js ADDED
@@ -0,0 +1,114 @@
1
+ import { isIPv6 } from 'node:net';
2
+ import { Refusal } from './discovery.js';
3
+ import { run } from './process.js';
4
+ // An allowlist, not a blocklist: OpenSSH has many spellings that run local
5
+ // commands (ProxyCommand, LocalCommand, KnownHostsCommand, Match exec, Include,
6
+ // -F, PKCS11Provider...). Only these connection settings are accepted, and they
7
+ // are re-emitted in one canonical argv form. ProxyJump is excluded because the
8
+ // jump hop does not inherit BatchMode/StrictHostKeyChecking from the command line.
9
+ const FLAGS = { p: 'port', l: 'user', i: 'identityfile' };
10
+ const KEYS = ['port', 'user', 'identityfile', 'identitiesonly'];
11
+ const valid = {
12
+ port: value => /^[1-9]\d{0,4}$/.test(value) && Number(value) <= 65535,
13
+ user: value => value.length <= 255 && /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/.test(value),
14
+ // OpenSSH expands %tokens and ${ENV} in identity paths; refuse both.
15
+ identityfile: value => value.length <= 4096 && !value.startsWith('-') && !/[\x00-\x1f\x7f%$]/.test(value),
16
+ identitiesonly: value => value === 'yes' || value === 'no',
17
+ family: () => true
18
+ };
19
+ export function sshOptions(tokens) {
20
+ const seen = new Map();
21
+ for (let i = 0; i < tokens.length; i++) {
22
+ const token = tokens[i];
23
+ let key, value;
24
+ if (token === '-4' || token === '-6') {
25
+ key = 'family';
26
+ value = token;
27
+ }
28
+ else {
29
+ const match = /^-([plio])(.*)$/s.exec(token);
30
+ if (!match)
31
+ throw new Refusal('unsupported_ssh_option');
32
+ value = match[2] || tokens[++i];
33
+ if (value === undefined || value.startsWith('-'))
34
+ throw new Refusal('invalid_ssh_option');
35
+ if (match[1] === 'o') {
36
+ // Only Key=Value; OpenSSH would re-tokenize spaces and quotes in -o.
37
+ const pair = /^([A-Za-z]+)=(.*)$/s.exec(value);
38
+ if (!pair || !KEYS.includes(pair[1].toLowerCase()))
39
+ throw new Refusal('unsupported_ssh_option');
40
+ key = pair[1].toLowerCase();
41
+ value = pair[2];
42
+ }
43
+ else
44
+ key = FLAGS[match[1]];
45
+ }
46
+ if (seen.has(key) || !valid[key](value))
47
+ throw new Refusal('invalid_ssh_option');
48
+ seen.set(key, value);
49
+ }
50
+ const args = [];
51
+ if (seen.has('port'))
52
+ args.push('-p', seen.get('port'));
53
+ if (seen.has('user'))
54
+ args.push('-l', seen.get('user'));
55
+ if (seen.has('identityfile'))
56
+ args.push('-i', seen.get('identityfile'));
57
+ if (seen.has('identitiesonly'))
58
+ args.push('-o', `IdentitiesOnly=${seen.get('identitiesonly')}`);
59
+ if (seen.has('family'))
60
+ args.push(seen.get('family'));
61
+ return { args, ...(seen.has('user') ? { user: seen.get('user') } : {}) };
62
+ }
63
+ // --ssh-jump USER@HOST[:PORT]: one hop with an explicit user. IPv6 needs
64
+ // brackets. Every part is limited to characters that are inert in a POSIX
65
+ // shell and in OpenSSH % tokens, because the hop runs inside ProxyCommand.
66
+ export function sshJump(value) {
67
+ 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_.-]*))(?::([1-9]\d{0,4}))?$/.exec(value) : null;
68
+ if (!match || (match[2] !== undefined && !isIPv6(match[2])) || (match[4] !== undefined && Number(match[4]) > 65535))
69
+ throw new Refusal('invalid_ssh_jump');
70
+ return { user: match[1], host: match[2] ?? match[3], ...(match[4] ? { port: match[4] } : {}), spec: value };
71
+ }
72
+ // A fixed ProxyCommand instead of -J: OpenSSH's -J does not pass BatchMode or
73
+ // StrictHostKeyChecking to the hop. The hop's own ssh_config may not add a
74
+ // further proxy, control socket, forwarding or local command. OpenSSH runs
75
+ // ProxyCommand through the user's shell after %-token expansion (ssh_config(5)),
76
+ // so the executable path is shell-quoted and every % in it is doubled.
77
+ export function proxyCommand(ssh, jump) {
78
+ const path = `'${ssh.replace(/'/g, "'\\''")}'`.replace(/%/g, '%%');
79
+ return [path, '-T', '-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=yes', '-o', 'UpdateHostKeys=no', '-o', 'ConnectTimeout=10',
80
+ '-o', 'ConnectionAttempts=1', '-o', 'ProxyCommand=none', '-o', 'ProxyJump=none', '-o', 'ControlPath=none', '-o', 'ForwardAgent=no',
81
+ '-o', 'ClearAllForwardings=yes', '-o', 'PermitLocalCommand=no', ...(jump.port ? ['-p', jump.port] : []), '-l', jump.user,
82
+ '-W', "'[%h]:%p'", '--', jump.host].join(' ');
83
+ }
84
+ // Outer options for a jump: a configured ControlMaster/ControlPath could reuse
85
+ // an existing master and bypass the hop, and ProxyUseFdpass would change how the
86
+ // proxy hands over its connection, so all three are fixed before user options.
87
+ export function jumpOptions(ssh, jump) {
88
+ return ['-o', 'ControlMaster=no', '-o', 'ControlPath=none', '-o', 'ProxyUseFdpass=no', '-o', `ProxyCommand=${proxyCommand(ssh, jump)}`];
89
+ }
90
+ // Like Python, ask OpenSSH which login user applies without connecting. With
91
+ // `force`, `ssh -G` also runs for an explicit user so the caller can see a
92
+ // configured HostKeyAlias (`read` says whether the configuration was read).
93
+ export async function sshConfig(ssh, destination, options, force = false) {
94
+ const at = destination.lastIndexOf('@');
95
+ const explicit = at > 0 ? { sshUser: destination.slice(0, at), sshUserSource: 'explicit' } :
96
+ options.user ? { sshUser: options.user, sshUserSource: 'explicit' } : undefined;
97
+ if (explicit && !force)
98
+ return { user: explicit, read: false };
99
+ const done = await run(ssh, ['-G', ...options.args, '--', destination], { timeout: 5000 });
100
+ let user = explicit ?? { sshUser: null, sshUserSource: 'unknown' }, hostKeyAlias;
101
+ if (done.interrupted || done.code !== 0)
102
+ return { user, read: false };
103
+ for (const line of done.stdout.split(/\r?\n/)) {
104
+ const match = /^(user|hostkeyalias) (\S[^\x00-\x1f\x7f]{0,254})$/i.exec(line);
105
+ if (match?.[1].toLowerCase() === 'hostkeyalias')
106
+ hostKeyAlias = match[2].trim();
107
+ else if (match && !explicit)
108
+ user = { sshUser: match[2].trim(), sshUserSource: 'ssh_config_or_local_default' };
109
+ }
110
+ return { user, read: true, ...(hostKeyAlias ? { hostKeyAlias } : {}) };
111
+ }
112
+ export async function sshUser(ssh, destination, options) {
113
+ return (await sshConfig(ssh, destination, options)).user;
114
+ }
@@ -0,0 +1,37 @@
1
+ import { Refusal } from './discovery.js';
2
+ export declare const PACKAGE = "session-peer";
3
+ export declare const REFRESH_ARG = "--_refresh-update-cache";
4
+ export declare const CHANNELS: string[];
5
+ export declare class UpdateRefusal extends Refusal {
6
+ readonly guidance: Record<string, unknown>;
7
+ constructor(code: string, guidance: Record<string, unknown>);
8
+ }
9
+ export declare const validVersion: (text: unknown, stable?: boolean) => boolean;
10
+ export declare function compareVersions(a: string, b: string): number;
11
+ export type Manager = 'npm' | 'npm_project' | 'pnpm' | 'pnpm_project' | 'yarn' | 'bun' | 'volta' | 'npx' | 'source' | 'unknown';
12
+ export type Probe = {
13
+ read: (path: string) => string;
14
+ real: (path: string) => string;
15
+ };
16
+ export declare function manager(path?: string, platform?: NodeJS.Platform, probe?: Probe): Manager;
17
+ export declare const upgradeCommand: (owner: Manager, target: string) => string | null;
18
+ export declare const upgradeGuidance: (owner: Manager) => string;
19
+ export declare function registryUrl(env?: NodeJS.ProcessEnv): URL;
20
+ export declare function distTags(env?: NodeJS.ProcessEnv): Promise<Record<string, unknown>>;
21
+ export declare function cacheDirectory(env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): string;
22
+ type CacheState = {
23
+ status: 'missing' | 'invalid' | 'fresh' | 'expired';
24
+ latest?: string | null;
25
+ checkedAt?: number;
26
+ };
27
+ export declare function readCache(env?: NodeJS.ProcessEnv, now?: number): CacheState;
28
+ export declare function acquireLock(env?: NodeJS.ProcessEnv): string | undefined;
29
+ export declare function lockState(env?: NodeJS.ProcessEnv, now?: number): 'free' | 'held' | 'stale';
30
+ export declare function releaseLock(token: string | undefined, env?: NodeJS.ProcessEnv): boolean;
31
+ export declare function refreshCache(env?: NodeJS.ProcessEnv): Promise<void>;
32
+ export declare const noticesEnabled: (optOut: boolean, env?: NodeJS.ProcessEnv) => boolean;
33
+ export declare function updateNotice(optOut: boolean, env?: NodeJS.ProcessEnv, now?: number): Record<string, unknown> | undefined;
34
+ export declare const noticeText: (notice: Record<string, unknown>) => string;
35
+ export declare function checkUpdate(channel?: string, env?: NodeJS.ProcessEnv): Promise<Record<string, unknown>>;
36
+ export declare function refuseSelfUpdate(channel?: string): never;
37
+ export {};