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/PARITY.md +329 -18
- package/README.ja.md +13 -5
- package/README.ko.md +13 -5
- package/README.md +13 -4
- package/README.zh-CN.md +12 -4
- package/RELEASING.md +109 -7
- package/SECURITY.md +1 -1
- package/VALIDATION.md +277 -7
- package/dist/cli.d.ts +10 -1
- package/dist/cli.js +288 -45
- package/dist/diagnostics.d.ts +2 -0
- package/dist/diagnostics.js +1 -1
- package/dist/discovery.js +39 -3
- package/dist/help.js +32 -5
- package/dist/output.d.ts +1 -1
- package/dist/output.js +30 -1
- package/dist/process.js +76 -5
- package/dist/protocol.d.ts +6 -3
- package/dist/protocol.js +21 -6
- package/dist/replies.d.ts +30 -0
- package/dist/replies.js +283 -0
- package/dist/ssh.d.ts +24 -0
- package/dist/ssh.js +114 -0
- package/dist/updates.d.ts +37 -0
- package/dist/updates.js +444 -0
- package/dist/windows.d.ts +1 -1
- package/dist/windows.js +4 -3
- package/dist/writer.js +5 -3
- package/docs/api.md +4 -4
- package/docs/design/remote-deployment.md +867 -0
- package/docs/guide.ja.md +118 -15
- package/docs/guide.ko.md +218 -22
- package/docs/guide.md +254 -23
- package/docs/guide.zh-CN.md +105 -14
- package/docs/shorthand.md +198 -0
- package/package.json +6 -4
- package/shorthand/sp.ps1 +11 -0
- package/shorthand/sp.sh +11 -0
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
|
|
2
|
+
export declare function renderOutput(value: Record<string, unknown> | Record<string, unknown>[], format: OutputFormat): string;
|
package/dist/output.js
CHANGED
|
@@ -1,9 +1,25 @@
|
|
|
1
1
|
// Escape terminal controls plus bidi/zero-width format characters in
|
|
2
2
|
// user-controlled names/paths; preserve other Unicode.
|
|
3
|
-
const safe = (value) =>
|
|
3
|
+
const safe = (value) => {
|
|
4
|
+
let text;
|
|
5
|
+
try {
|
|
6
|
+
text = String(value ?? '');
|
|
7
|
+
}
|
|
8
|
+
catch {
|
|
9
|
+
try {
|
|
10
|
+
text = JSON.stringify(value) ?? '[unprintable]';
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
text = '[unprintable]';
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return text.replace(/[\x00-\x1f\x7f-\x9f\u061c\u200b-\u200f\u2028-\u202e\u2060-\u2069\ufeff]/g, char => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
|
|
17
|
+
};
|
|
4
18
|
export function renderOutput(value, format) {
|
|
5
19
|
if (format === 'json')
|
|
6
20
|
return JSON.stringify(value);
|
|
21
|
+
if (Array.isArray(value))
|
|
22
|
+
return value.map(item => `Host: ${safe(item.host)}\n${renderOutput(item, format)}`).join('\n\n');
|
|
7
23
|
const lines = [];
|
|
8
24
|
if (value.command === 'list') {
|
|
9
25
|
const sessions = Array.isArray(value.sessions) ? value.sessions : [];
|
|
@@ -24,6 +40,17 @@ export function renderOutput(value, format) {
|
|
|
24
40
|
lines.push(`Ready: ${value.ready === true ? 'yes' : 'no'}`);
|
|
25
41
|
lines.push(`Agents: ${safe(JSON.stringify(value.agents ?? {}))}`);
|
|
26
42
|
lines.push(`Capabilities: ${safe(JSON.stringify(value.capabilities ?? {}))}`);
|
|
43
|
+
const route = value.returnRoute;
|
|
44
|
+
lines.push(route ? `Return route: ${safe(route.status)} via ${safe(route.transport)} (${safe(route.reason)})` : 'Return route: not checked (use --check-return-route)');
|
|
45
|
+
}
|
|
46
|
+
else if (value.command === 'update' && value.ok === true) {
|
|
47
|
+
lines.push(`session-peer ${safe(value.current)} (typescript): ${value.status === 'update_available' ? `${safe(value.latest)} available` :
|
|
48
|
+
value.status === 'ahead' ? `newer than ${safe(value.latest)}` : 'up to date'} on npm dist-tag ${safe(value.distTag)}.`);
|
|
49
|
+
if (value.outdated === true)
|
|
50
|
+
lines.push(value.updateCommand ? `Upgrade with: ${safe(value.updateCommand)}` : safe(value.guidance));
|
|
51
|
+
if (value.cache === 'skipped_stale_lock')
|
|
52
|
+
lines.push('Update cache not written: a stale npm-update.lock remains; delete it while no session-peer process runs.');
|
|
53
|
+
lines.push('Skills, Python installations and remote hosts are updated separately.');
|
|
27
54
|
}
|
|
28
55
|
else if (value.ok === true) {
|
|
29
56
|
const target = value.target;
|
|
@@ -36,6 +63,8 @@ export function renderOutput(value, format) {
|
|
|
36
63
|
}
|
|
37
64
|
if (value.ok === false) {
|
|
38
65
|
lines.push(`Error: ${safe(value.error ?? 'operation_failed')}`);
|
|
66
|
+
if (value.command === 'update' && value.error === 'self_update_unsupported')
|
|
67
|
+
lines.push(value.updateCommand ? `This installation is managed by ${safe(value.managedBy)}. Upgrade with: ${safe(value.updateCommand)}` : safe(value.guidance));
|
|
39
68
|
if (value.command === 'send')
|
|
40
69
|
lines.push(value.submitted === null ? 'Submission outcome unknown. Do not retry automatically.' : 'Nothing submitted.');
|
|
41
70
|
}
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
}
|
package/dist/protocol.d.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
|
-
export declare const VERSION = "0.
|
|
2
|
-
export declare const VERSION_LINE = "session-peer 0.
|
|
1
|
+
export declare const VERSION = "0.3.1";
|
|
2
|
+
export declare const VERSION_LINE = "session-peer 0.3.1 (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
|
|
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.
|
|
4
|
+
export const VERSION = '0.3.1';
|
|
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
|
-
|
|
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
|
|
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))
|
|
@@ -30,6 +38,10 @@ export function reply(value) {
|
|
|
30
38
|
throw new Refusal('invalid_reply_uri');
|
|
31
39
|
if (agent === 'codex' && !uuid(target))
|
|
32
40
|
throw new Refusal('invalid_reply_uri');
|
|
41
|
+
// `to` uses reserved prefixes for agent selection and Reply-To parsing.
|
|
42
|
+
// A forwarded value must not become Codex or another URI at the receiver.
|
|
43
|
+
if (agent === 'claude' && (target.startsWith('codex:') || target.startsWith('session-peer:')))
|
|
44
|
+
throw new Refusal('invalid_reply_uri');
|
|
33
45
|
if (agent !== 'codex' && fields.has('codexHome'))
|
|
34
46
|
throw new Refusal('invalid_reply_uri');
|
|
35
47
|
// Match Python: a POSIX or Windows absolute path, never cwd- or ~-relative.
|
|
@@ -43,9 +55,12 @@ export function reply(value) {
|
|
|
43
55
|
...(transport === 'ssh' ? { host: host(fields.get('host')) } : {}),
|
|
44
56
|
...(fields.has('codexHome') ? { home: fields.get('codexHome') } : {}) };
|
|
45
57
|
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
58
|
+
// `sender` is an already-detected identity (null: none). Omitted, a valid
|
|
59
|
+
// Codex environment UUID is used, as in earlier versions.
|
|
60
|
+
export function envelope(text, noFrom, address, sender) {
|
|
61
|
+
const thread = process.env.CODEX_THREAD_ID || process.env.CODEX_SESSION_ID;
|
|
62
|
+
const identity = sender !== undefined ? sender : thread && uuid(thread) ? { agent: 'codex', id: thread } : null;
|
|
63
|
+
const from = !noFrom && identity ? `From: ${identity.agent}:${identity.id}\n\n` : '';
|
|
49
64
|
if (address)
|
|
50
65
|
reply(address);
|
|
51
66
|
// 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 {};
|
package/dist/replies.js
ADDED
|
@@ -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>;
|