返回源码地图

packages/env/src/ssh.ts

v1.3.0 · 71023aec1546 · 21:主机密钥、部署与惰性连接

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1import { spawn } from "node:child_process";
2import { createHash, randomBytes } from "node:crypto";
3import { existsSync } from "node:fs";
4import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
5import { tmpdir } from "node:os";
6import { dirname, join } from "node:path";
7import { fileURLToPath } from "node:url";
8import { Connection, type ConnectionOptions } from "./connection.ts";
9
10/** A remote system the package ships a daemon for. */
11export type RemotePlatform = {
12 platform: "linux" | "android" | "darwin" | "windows";
13 arch: "x64" | "arm64";
14 /** The remote home directory, in the remote system's own spelling. */
15 home: string;
16 /** Windows: the shell `sshd` runs commands with (`DefaultShell`). */
17 shell?: "cmd" | "powershell";
18 /** Problems worth telling the owner about, such as Termux without `termux-exec`. */
19 warnings: string[];
20};
21
22/** How to reach a machine with the system `ssh`. */
23export interface SshTarget {
24 /** Host name or `~/.ssh/config` alias. */
25 host: string;
26 user?: string;
27 port?: number;
28 identityFile?: string;
29 /** Host keys this application trusts; `acceptHostKey` adds to it. */
30 knownHostsFile: string;
31 /** The name keys are stored under, independent of aliases, ports and jump hosts, e.g. `pi-env-<env name>`. */
32 hostKeyAlias: string;
33 /** The `ssh` program; default `ssh`. */
34 ssh?: string;
35 /** An `ssh` configuration file instead of `~/.ssh/config` (`-F`). */
36 configFile?: string;
37}
38
39/** The remote host's key is not in `knownHostsFile`; `scanHostKey` shows it so the owner can accept it. */
40export class HostKeyUnknownError extends Error {}
41
42/** The remote host's key differs from the one in `knownHostsFile`; it is never accepted automatically. */
43export class HostKeyChangedError extends Error {}
44
45/** An `ssh` invocation that failed for another reason, with its exit code and diagnostics. */
46export class SshError extends Error {
47 readonly exitCode: number | null;
48 readonly stderr: string;
49
50 constructor(message: string, exitCode: number | null, stderr: string) {
51 super(message);
52 this.exitCode = exitCode;
53 this.stderr = stderr;
54 }
55}
56
57const packageRoot = fileURLToPath(new URL("..", import.meta.url));
58
59/** No leading `-` (it would be read as an `ssh` option) and no whitespace or control characters. */
60function checkField(name: string, value: string): void {
61 if (value === "" || value.startsWith("-") || /[\s\x00-\x1f\x7f]/.test(value)) {
62 throw new Error(`Invalid ${name}: ${JSON.stringify(value)}`);
63 }
64}
65
66/** A path for an `ssh` option that expands `%` tokens: quoted, with `%` literal. */
67function configPath(name: string, path: string): string {
68 if (path === "" || /["\x00-\x1f\x7f]/.test(path)) throw new Error(`Invalid ${name}: ${JSON.stringify(path)}`);
69 return `"${path.replaceAll("%", "%%")}"`;
70}
71
72/**
73 * Arguments for `ssh` up to the host: no prompts, no forwarding of any kind, no shared connections, no commands from
74 * the configuration, no locale forwarding (the remote uses its own), and host keys checked strictly against the
75 * application's own file under a fixed alias.
76 */
77export function sshArguments(
78 target: SshTarget,
79 strictHostKeys = true,
80 knownHostsFile = target.knownHostsFile,
81): string[] {
82 checkField("host", target.host);
83 checkField("host key alias", target.hostKeyAlias);
84 if (target.user !== undefined) checkField("user", target.user);
85 if (target.port !== undefined && (!Number.isInteger(target.port) || target.port < 1 || target.port > 65535)) {
86 throw new Error(`Invalid port: ${target.port}`);
87 }
88 const option = (setting: string) => ["-o", setting];
89 return [
90 ...(target.configFile === undefined ? [] : ["-F", target.configFile]),
91 "-T",
92 "-a",
93 "-x",
94 ...option("BatchMode=yes"),
95 ...option("ClearAllForwardings=yes"),
96 ...option("ForwardAgent=no"),
97 ...option("ForwardX11=no"),
98 ...option("ControlMaster=no"),
99 ...option("ControlPath=none"),
100 ...option("RemoteCommand=none"),
101 ...option("PermitLocalCommand=no"),
102 ...option("SendEnv=-*"),
103 ...option("ServerAliveInterval=15"),
104 ...option(`StrictHostKeyChecking=${strictHostKeys ? "yes" : "accept-new"}`),
105 ...option(`UserKnownHostsFile=${configPath("known hosts file", knownHostsFile)}`),
106 ...option("GlobalKnownHostsFile=none"),
107 ...option("HashKnownHosts=no"),
108 ...option(`HostKeyAlias=${target.hostKeyAlias}`),
109 ...(target.user === undefined ? [] : ["-l", target.user]),
110 ...(target.port === undefined ? [] : ["-p", String(target.port)]),
111 ...(target.identityFile === undefined
112 ? []
113 : [
114 ...option(`IdentityFile=${configPath("identity file", target.identityFile)}`),
115 ...option("IdentitiesOnly=yes"),
116 ]),
117 "--",
118 target.host,
119 ];
120}
121
122/** How long a detection, check or upload over `ssh` may take before it is abandoned. */
123const SSH_TIMEOUT_MS = 60_000;
124const UPLOAD_TIMEOUT_MS = 300_000;
125
126/** Run one remote command over `ssh`, optionally feeding stdin; resolves with stdout, rejects on failure. */
127function runSsh(
128 target: SshTarget,
129 command: string,
130 options: { stdin?: Uint8Array; args?: string[]; timeoutMs?: number } = {},
131): Promise<string> {
132 return new Promise((resolve, reject) => {
133 const args = options.args ?? sshArguments(target);
134 const child = spawn(target.ssh ?? "ssh", [...args, command], { stdio: ["pipe", "pipe", "pipe"] });
135 const timeoutMs = options.timeoutMs ?? SSH_TIMEOUT_MS;
136 const timer = setTimeout(() => {
137 child.kill();
138 const diagnostics = Buffer.concat(stderr).toString("utf8");
139 reject(
140 new SshError(
141 `ssh ${target.host} did not finish within ${timeoutMs / 1000} s: ${diagnostics.trim()}`,
142 null,
143 diagnostics,
144 ),
145 );
146 }, timeoutMs);
147 const stdout: Buffer[] = [];
148 const stderr: Buffer[] = [];
149 child.stdout.on("data", (chunk: Buffer) => stdout.push(chunk));
150 child.stderr.on("data", (chunk: Buffer) => stderr.push(chunk));
151 child.stdin.on("error", () => {});
152 child.on("error", (error) => {
153 clearTimeout(timer);
154 reject(new SshError(error.message, null, ""));
155 });
156 child.on("close", (code) => {
157 clearTimeout(timer);
158 const output = Buffer.concat(stdout).toString("utf8");
159 const diagnostics = Buffer.concat(stderr).toString("utf8");
160 if (code === 0) return resolve(output);
161 if (/REMOTE HOST IDENTIFICATION HAS CHANGED/.test(diagnostics)) {
162 return reject(
163 new HostKeyChangedError(`The host key of ${target.host} changed; remove the old key to continue`),
164 );
165 }
166 if (/Host key verification failed|No .* host key is known/.test(diagnostics)) {
167 return reject(new HostKeyUnknownError(`The host key of ${target.host} is not trusted yet`));
168 }
169 reject(
170 new SshError(`ssh ${target.host} failed with exit code ${code}: ${diagnostics.trim()}`, code, diagnostics),
171 );
172 });
173 child.stdin.end(options.stdin ?? new Uint8Array(0));
174 });
175}
176
177/**
178 * Connect once with `accept-new` against a temporary known-hosts file to capture the key the host presents, through
179 * the same route (`~/.ssh/config`, jump hosts) as real connections. Returns its known-hosts lines and fingerprints.
180 * Showing a fingerprint is not authentication: compare it with one obtained out of band before accepting it.
181 */
182export async function scanHostKey(target: SshTarget): Promise<{ lines: string[]; fingerprints: string[] }> {
183 const directory = await mkdtemp(join(tmpdir(), "pi-env-hostkey-"));
184 try {
185 const scanned = join(directory, "known_hosts");
186 // Authentication may fail without the key; the key is recorded before authentication.
187 await runSsh(target, "exit 0", { args: sshArguments(target, false, scanned) }).catch((error: unknown) => {
188 if (!(error instanceof SshError) && !(error instanceof HostKeyUnknownError)) throw error;
189 });
190 const lines = existsSync(scanned)
191 ? (await readFile(scanned, "utf8")).split("\n").filter((line) => line.trim() !== "")
192 : [];
193 if (lines.length === 0) throw new Error(`No host key received from ${target.host}`);
194 const fingerprints = await new Promise<string[]>((resolve, reject) => {
195 const child = spawn("ssh-keygen", ["-lf", scanned], { stdio: ["ignore", "pipe", "pipe"] });
196 let output = "";
197 child.stdout.on("data", (chunk: Buffer) => {
198 output += chunk.toString("utf8");
199 });
200 child.on("error", reject);
201 child.on("close", () => resolve(output.split("\n").filter((line) => line.trim() !== "")));
202 });
203 return { lines, fingerprints };
204 } finally {
205 await rm(directory, { recursive: true, force: true });
206 }
207}
208
209/** A known-hosts line for `alias`: `alias type key [comment]`, no markers, patterns or hashed names. */
210function parseHostKeyLine(alias: string, line: string): { type: string; key: string } {
211 const [host, type, key] = line.trim().split(/\s+/);
212 if (
213 host !== alias ||
214 type === undefined ||
215 key === undefined ||
216 !/^(ssh-[a-z0-9-]+|ecdsa-sha2-[a-z0-9-]+|sk-[a-z0-9@.-]+)$/.test(type) ||
217 !/^[A-Za-z0-9+/]+={0,2}$/.test(key)
218 ) {
219 throw new Error(`Not a host key line for ${alias}: ${JSON.stringify(line)}`);
220 }
221 return { type, key };
222}
223
224/** Known-hosts files being changed, so changes to one file happen one at a time. */
225const knownHostsChanges = new Map<string, Promise<unknown>>();
226
227/** Rewrite the known-hosts file one change at a time, atomically. */
228async function changeKnownHosts(file: string, change: (lines: string[]) => string[]): Promise<void> {
229 const previous = knownHostsChanges.get(file) ?? Promise.resolve();
230 const next = previous
231 .catch(() => {})
232 .then(async () => {
233 await mkdir(dirname(file), { recursive: true, mode: 0o700 });
234 const existing = existsSync(file)
235 ? (await readFile(file, "utf8")).split("\n").filter((line) => line !== "")
236 : [];
237 const lines = change(existing);
238 const temporary = `${file}.${randomBytes(6).toString("hex")}.tmp`;
239 await writeFile(temporary, lines.length === 0 ? "" : `${lines.join("\n")}\n`, { mode: 0o600, flag: "wx" });
240 await rename(temporary, file).catch(async (error: unknown) => {
241 await rm(temporary, { force: true });
242 throw error;
243 });
244 });
245 knownHostsChanges.set(file, next);
246 try {
247 await next;
248 } finally {
249 if (knownHostsChanges.get(file) === next) knownHostsChanges.delete(file);
250 }
251}
252
253/**
254 * Trust host-key lines from `scanHostKey` by adding them to the target's known-hosts file. Only plain lines for the
255 * target's alias are accepted. A key that differs from a trusted key of the same type is refused with
256 * `HostKeyChangedError`; `forgetHostKey` must remove the old keys first.
257 */
258export async function acceptHostKey(target: SshTarget, lines: readonly string[]): Promise<void> {
259 const alias = target.hostKeyAlias;
260 const accepted = lines.map((line) => ({ line: line.trim(), ...parseHostKeyLine(alias, line) }));
261 await changeKnownHosts(target.knownHostsFile, (existing) => {
262 const trusted = new Map<string, string>();
263 for (const line of existing) {
264 const [host, type, key] = line.trim().split(/\s+/);
265 if (host === alias && type !== undefined && key !== undefined) trusted.set(type, key);
266 }
267 const added: string[] = [];
268 for (const { line, type, key } of accepted) {
269 const known = trusted.get(type);
270 if (known === key) continue;
271 if (known !== undefined) {
272 throw new HostKeyChangedError(`The ${type} host key of ${target.host} changed; forget the old key first`);
273 }
274 trusted.set(type, key);
275 added.push(line);
276 }
277 return [...existing, ...added];
278 });
279}
280
281/** Stop trusting every key stored for the target's alias, e.g. after the owner confirmed a changed host key. */
282export async function forgetHostKey(target: SshTarget): Promise<void> {
283 await changeKnownHosts(target.knownHostsFile, (existing) =>
284 existing.filter((line) => line.trim().split(/\s+/)[0] !== target.hostKeyAlias),
285 );
286}
287
288/** POSIX detection, run by the remote login shell; a Windows host answers through PowerShell instead. */
289const POSIX_PROBE = `sh -c 'echo PI-ENV-PROBE; uname -s; uname -m; uname -o 2>/dev/null || echo -; printf "%s\\n" "$HOME" "\${TMPDIR:--}" "\${LD_PRELOAD:--}"'`;
290
291function powershell(script: string): string {
292 return `powershell -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(script, "utf16le").toString("base64")}`;
293}
294
295const WINDOWS_PROBE = powershell(
296 "'PI-ENV-PROBE'; 'Windows'; [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString(); '-'; $HOME; '-'; '-'",
297);
298
299function normalizeArch(machine: string): RemotePlatform["arch"] {
300 const lower = machine.toLowerCase();
301 if (lower === "x86_64" || lower === "amd64" || lower === "x64") return "x64";
302 if (lower === "aarch64" || lower === "arm64") return "arm64";
303 throw new Error(`Unsupported remote architecture: ${machine}`);
304}
305
306type Probe = { system: string; machine: string; os: string; home: string; tmpdir: string; preload: string };
307
308function parseProbe(target: SshTarget, output: string): Probe {
309 // Login shells may print a banner first.
310 const lines = output.split(/\r?\n/);
311 const start = lines.indexOf("PI-ENV-PROBE");
312 if (start === -1) throw new Error(`Unexpected answer from ${target.host}: ${output.trim()}`);
313 const [system = "", machine = "", os = "", home = "", tmpdir = "-", preload = "-"] = lines.slice(start + 1);
314 return { system, machine, os, home, tmpdir, preload };
315}
316
317/** Termux works only with its own `TMPDIR` and with `termux-exec`, which makes `#!/usr/bin/env` shebangs work. */
318function termuxWarnings(probe: Probe): string[] {
319 const warnings: string[] = [];
320 if (probe.tmpdir === "-") warnings.push("TMPDIR is not set; Termux's sshd normally sets it to $PREFIX/tmp.");
321 if (!probe.preload.includes("termux-exec")) {
322 warnings.push("termux-exec is not loaded (LD_PRELOAD); scripts with #!/usr/bin/env shebangs will fail.");
323 }
324 warnings.push("Android may suspend Termux; run termux-wake-lock on the device to keep the connection alive.");
325 return warnings;
326}
327
328/** Which system the target runs: `uname` through the login shell, or PowerShell on Windows. */
329export async function detectPlatform(target: SshTarget): Promise<RemotePlatform> {
330 let probe: Probe;
331 try {
332 probe = parseProbe(target, await runSsh(target, POSIX_PROBE));
333 } catch (error) {
334 // cmd.exe or PowerShell as the remote shell: no `sh`, or one that gets the probe's quotes wrong.
335 if (error instanceof HostKeyUnknownError || error instanceof HostKeyChangedError) throw error;
336 probe = parseProbe(target, await runSsh(target, WINDOWS_PROBE));
337 }
338 // Git Bash as Windows' default SSH shell: ask PowerShell for Windows' own architecture and home spelling.
339 if (/^(MINGW|MSYS|CYGWIN)/.test(probe.system)) probe = parseProbe(target, await runSsh(target, WINDOWS_PROBE));
340 const arch = normalizeArch(probe.machine);
341 const { system, os, home } = probe;
342 if (system === "Windows") {
343 // cmd.exe expands %OS%; PowerShell prints it as is.
344 const shell = (await runSsh(target, "echo %OS%")).includes("Windows_NT") ? "cmd" : "powershell";
345 return { platform: "windows", arch, home, shell, warnings: [] };
346 }
347 if (system === "Darwin") return { platform: "darwin", arch, home, warnings: [] };
348 if (system === "Linux") {
349 const android = os === "Android";
350 return { platform: android ? "android" : "linux", arch, home, warnings: android ? termuxWarnings(probe) : [] };
351 }
352 throw new Error(`Unsupported remote system: ${system}`);
353}
354
355/** The daemon binary this package ships for a remote system. */
356export function packagedDaemon(remote: Pick<RemotePlatform, "platform" | "arch">): string {
357 const name = `pi-env-${remote.platform}-${remote.arch}`;
358 return join(packageRoot, "bin", name, remote.platform === "windows" ? "pi-env.exe" : "pi-env");
359}
360
361/** The daemon this package ships for the machine it runs on, e.g. for terminals of local sessions. */
362export function localDaemon(): string {
363 const platform = process.platform === "win32" ? "windows" : process.platform;
364 if (platform !== "linux" && platform !== "android" && platform !== "darwin" && platform !== "windows") {
365 throw new Error(`No pi-env daemon for ${process.platform}`);
366 }
367 return packagedDaemon({ platform, arch: normalizeArch(process.arch) });
368}
369
370function quotePosix(text: string): string {
371 return `'${text.replaceAll("'", "'\\''")}'`;
372}
373
374function quotePowerShell(text: string): string {
375 return `'${text.replaceAll("'", "''")}'`;
376}
377
378/** Where a daemon with this content lives on the remote machine: named by its SHA-256, so versions never collide. */
379function daemonPath(remote: RemotePlatform, sha256: string): string {
380 const name = `pi-env-${sha256.slice(0, 32)}`;
381 return remote.platform === "windows"
382 ? `${remote.home}\\.pi\\mobile\\tools\\${name}.exe`
383 : `${remote.home}/.pi/mobile/tools/${name}`;
384}
385
386const POSIX_HASH = `hash() { if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | cut -d' ' -f1; elif command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | cut -d' ' -f1; elif command -v openssl >/dev/null 2>&1; then openssl dgst -sha256 "$1" | sed 's/.*= //'; else echo none; fi; }`;
387
388/** Whether the remote file has this content: `present`, `missing`, or (POSIX without a hash tool) `nohash`. */
389async function checkDaemon(target: SshTarget, remote: RemotePlatform, file: string, sha256: string): Promise<string> {
390 if (remote.platform === "windows") {
391 const check = powershell(
392 `$f = ${quotePowerShell(file)}; if ((Test-Path -LiteralPath $f) -and ((Get-FileHash -Algorithm SHA256 -LiteralPath $f).Hash.ToLower() -eq '${sha256}')) { 'present' } else { 'missing' }`,
393 );
394 return (await runSsh(target, check)).trim().endsWith("present") ? "present" : "missing";
395 }
396 const check = `${POSIX_HASH}; f=${quotePosix(file)}; if [ -f "$f" ] && [ "$(hash "$f")" = ${sha256} ]; then echo present; elif [ "$(hash /dev/null)" = none ]; then echo nohash; else echo missing; fi`;
397 return (await runSsh(target, `sh -c ${quotePosix(check)}`)).trim().split("\n").at(-1) ?? "missing";
398}
399
400/**
401 * Make sure the daemon is on the remote machine, verified by its SHA-256 before it ever runs, and remove daemons of
402 * other contents. The upload goes to a new temporary file and is renamed into place only once its hash matches.
403 * Returns the remote path of the binary.
404 */
405export async function deployDaemon(
406 target: SshTarget,
407 remote: RemotePlatform,
408 binary = packagedDaemon(remote),
409): Promise<string> {
410 if (!existsSync(binary)) throw new Error(`No pi-env daemon for ${remote.platform}-${remote.arch} at ${binary}`);
411 const bytes = await readFile(binary);
412 const sha256 = createHash("sha256").update(bytes).digest("hex");
413 const file = daemonPath(remote, sha256);
414 const state = await checkDaemon(target, remote, file, sha256);
415 if (state === "present") return file;
416 if (state === "nohash") throw new Error(`${target.host} has no sha256sum, shasum or openssl to verify pi-env`);
417 if (remote.platform === "windows") {
418 const upload = powershell(
419 [
420 "$ErrorActionPreference = 'Stop'",
421 `$f = ${quotePowerShell(file)}`,
422 "$d = Split-Path -Parent $f",
423 "New-Item -ItemType Directory -Force -Path $d | Out-Null",
424 "$t = Join-Path $d ('.pi-env-' + [guid]::NewGuid().ToString() + '.tmp')",
425 // PowerShell reads redirected stdin itself, as text lines for `$input`, so the binary comes as base64 lines
426 // up to an end marker: Windows' sshd may never pass on the end of stdin.
427 "$text = New-Object System.Text.StringBuilder",
428 "foreach ($line in $input) { if ($line -eq 'PI-ENV-END') { break }; [void]$text.Append($line) }",
429 "$bytes = [Convert]::FromBase64String($text.ToString())",
430 "$out = [IO.File]::Open($t, 'CreateNew', 'Write', 'None'); $out.Write($bytes, 0, $bytes.Length); $out.Close()",
431 `if ((Get-FileHash -Algorithm SHA256 -LiteralPath $t).Hash.ToLower() -ne '${sha256}') { Remove-Item -LiteralPath $t; throw 'pi-env upload is corrupt' }`,
432 // A running daemon or a virus scanner can hold the old file for a moment.
433 "for ($i = 0; ; $i++) { try { Move-Item -Force -LiteralPath $t -Destination $f; break } catch { if ($i -ge 20) { throw }; Start-Sleep -Milliseconds 250 } }",
434 // Older daemons; one that is running stays until it exits.
435 "Get-ChildItem -LiteralPath $d -Filter 'pi-env-*.exe' | Where-Object { $_.FullName -ne $f } | ForEach-Object { Remove-Item -LiteralPath $_.FullName -ErrorAction SilentlyContinue }",
436 "'deployed'",
437 ].join("; "),
438 );
439 const lines = bytes.toString("base64").replace(/.{1,76}/g, "$&\n");
440 await runSsh(target, upload, { stdin: Buffer.from(`${lines}PI-ENV-END\n`), timeoutMs: UPLOAD_TIMEOUT_MS });
441 return file;
442 }
443 const upload = [
444 "set -e",
445 POSIX_HASH,
446 `f=${quotePosix(file)}`,
447 'd=$(dirname "$f")',
448 'mkdir -p "$d"',
449 'chmod 700 "$d"',
450 't=$(mktemp "$d/.pi-env.XXXXXX")',
451 'cat > "$t"',
452 `if [ "$(hash "$t")" != ${sha256} ]; then rm -f "$t"; echo "pi-env upload is corrupt" >&2; exit 1; fi`,
453 'chmod 700 "$t"',
454 'mv -f "$t" "$f"',
455 // Older daemons; running ones keep their file open until they exit.
456 'for old in "$d"/pi-env-*; do [ "$old" = "$f" ] || rm -f "$old"; done',
457 "echo deployed",
458 ].join("\n");
459 await runSsh(target, `sh -c ${quotePosix(upload)}`, { stdin: bytes, timeoutMs: UPLOAD_TIMEOUT_MS });
460 return file;
461}
462
463/** Options for `sshConnection` and `connectSsh`: the target, plus the binary to deploy (default: the one this package ships). */
464export interface SshConnectOptions extends SshTarget {
465 binary?: string;
466 /**
467 * POSIX: start the daemon through the user's login shell (`$SHELL -l`), so commands see the environment of
468 * `~/.profile` and similar files. Off by default: `ssh` runs commands without a login shell.
469 */
470 loginShell?: boolean;
471 onLog?: ConnectionOptions["onLog"];
472}
473
474/** The remote command that starts the daemon at `file`, before the `serve` arguments. */
475function launchCommand(remote: RemotePlatform, file: string, loginShell: boolean): string {
476 if (remote.platform === "windows") {
477 // PowerShell runs a quoted path only with the call operator; cmd.exe keeps one pair of quotes around a program.
478 if (remote.shell === "powershell") return `& ${quotePowerShell(file)}`;
479 return file.includes(" ") ? `"${file}"` : file;
480 }
481 // `$0` is the daemon, `"$@"` its arguments; `$SHELL` is the login shell's own name for itself.
482 if (loginShell) return `exec "$SHELL" -lc 'exec "$0" "$@"' ${quotePosix(file)}`;
483 return quotePosix(file);
484}
485
486/** What an SSH connection learned about its remote system, and the daemon it verified last. */
487type SshState = { remote?: RemotePlatform; verified?: string };
488
489/** A `Connection` whose every start detects the remote system (once), verifies or deploys the daemon, then starts it. */
490function sshConnectionFor(options: SshConnectOptions, state: SshState): Connection {
491 return new Connection({
492 command: async () => {
493 if (state.remote === undefined) {
494 const remote = await detectPlatform(options);
495 for (const warning of remote.warnings) options.onLog?.(`${warning}\n`);
496 state.remote = remote;
497 }
498 // A deployment that just verified the binary counts for the first start.
499 const file =
500 state.verified ??
501 (await deployDaemon(options, state.remote, options.binary ?? packagedDaemon(state.remote)));
502 state.verified = undefined;
503 return [
504 options.ssh ?? "ssh",
505 ...sshArguments(options),
506 launchCommand(state.remote, file, options.loginShell === true),
507 ];
508 },
509 ...(options.onLog === undefined ? {} : { onLog: options.onLog }),
510 });
511}
512
513/**
514 * A `Connection` to the target that does nothing until its first request. Each start detects the remote system (the
515 * first time), verifies the daemon and deploys it if it is missing or changed, then starts it over `ssh`. A failure
516 * (no network, an untrusted or changed host key) fails the requests waiting for that start with code `spawn_error`
517 * and the `ssh` diagnostics as message; the next request tries again. `remote()` is the detected system, once known.
518 */
519export function sshConnection(options: SshConnectOptions): {
520 connection: Connection;
521 remote(): RemotePlatform | undefined;
522} {
523 const state: SshState = {};
524 return { connection: sshConnectionFor(options, state), remote: () => state.remote };
525}
526
527/**
528 * Detect the remote system and deploy the daemon now, then return a `Connection` that starts it over `ssh`, like
529 * `sshConnection`. Failures reject here: host keys must already be trusted (`scanHostKey`, `acceptHostKey`), otherwise
530 * this rejects with `HostKeyUnknownError`.
531 */
532export async function connectSsh(
533 options: SshConnectOptions,
534): Promise<{ connection: Connection; remote: RemotePlatform }> {
535 const remote = await detectPlatform(options);
536 const verified = await deployDaemon(options, remote, options.binary ?? packagedDaemon(remote));
537 for (const warning of remote.warnings) options.onLog?.(`${warning}\n`);
538 return { connection: sshConnectionFor(options, { remote, verified }), remote };
539}