pi-remote-call 0.3.1 → 0.3.3
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/CHANGELOG.md +31 -0
- package/README.md +14 -11
- package/package.json +1 -1
- package/src/exit-marker.ts +58 -0
- package/src/host-key.ts +42 -5
- package/src/host-manager.ts +2 -1
- package/src/proxy.ts +81 -0
- package/src/python-protocol.ts +10 -1
- package/src/remote-helper.ts +7 -0
- package/src/ssh-config.ts +18 -2
- package/src/transport.ts +180 -57
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,36 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.3 - 2026-11-29
|
|
4
|
+
|
|
5
|
+
### Security
|
|
6
|
+
|
|
7
|
+
- Apply the effective OpenSSH `HostKeyAlgorithms` allowlist to every SSH hop. Configuration with no supported host-key algorithm fails closed instead of silently widening policy.
|
|
8
|
+
- Refuse non-`none` `RevokedHostKeys`/KRL configuration before DNS, known-hosts lookup, authentication, or proxy setup; full KRL evaluation remains unsupported. Existing `@revoked` known-hosts entries are still enforced.
|
|
9
|
+
|
|
10
|
+
### Fixed
|
|
11
|
+
|
|
12
|
+
- Preserve network, timeout, proxy, and authentication error categories instead of reporting every failed connection as `E_AUTH`.
|
|
13
|
+
- Absorb repeated SSH errors while a failed handshake is being cleaned up, and retain the active ProxyJump/ProxyCommand context in diagnostics.
|
|
14
|
+
- Treat numeric exit status 1 from `ssh-keygen -F` as no known-hosts match on all supported platforms.
|
|
15
|
+
- Report a sanitized `helperCacheError` stage and reason when cache initialization falls back to the inline helper.
|
|
16
|
+
|
|
17
|
+
### Tests
|
|
18
|
+
|
|
19
|
+
- Add real OpenSSH coverage for session loss without exit status, cancellation and remote process-group cleanup, corrupted helper caches, inline-cache fallback diagnostics, and injected `fsync` failure without target modification.
|
|
20
|
+
|
|
21
|
+
## 0.3.2 - 2026-11-28
|
|
22
|
+
|
|
23
|
+
### Added
|
|
24
|
+
|
|
25
|
+
- ProxyJump and ProxyCommand transports with per-hop noninteractive authentication and strict known_hosts verification.
|
|
26
|
+
- Real OpenSSH CI coverage using temporary direct and jump servers, generated credentials, random ports, file operations, and proxy paths.
|
|
27
|
+
|
|
28
|
+
### Changed
|
|
29
|
+
|
|
30
|
+
- Watchdog commands emit a random completion marker so a missing SSH exit-status no longer hides the real command exit code. Ordinary stderr remains streamed without protocol bytes.
|
|
31
|
+
- A complete helper success response can establish the outcome when both SSH exit-status and the marker are absent; incomplete output remains an unknown outcome and writes are never replayed.
|
|
32
|
+
- CA-only `@cert-authority` trust now fails explicitly because `ssh2` cannot verify certificate host-key handshakes; this release does not claim CA support.
|
|
33
|
+
|
|
3
34
|
## 0.3.1 - 2026-11-28
|
|
4
35
|
|
|
5
36
|
### Changed
|
package/README.md
CHANGED
|
@@ -18,20 +18,20 @@ Remote machine:
|
|
|
18
18
|
- `sshd`, Bash, and SFTP already enabled
|
|
19
19
|
- Optional but recommended: `python3` 3.8+ for remote-side text reads and edits. No pip packages are needed.
|
|
20
20
|
- Without Python, text tools retain the SFTP behavior from version 0.1.1.
|
|
21
|
-
- Standard `hostname`, `id`, `uname`, `kill`, and `
|
|
21
|
+
- Standard `hostname`, `id`, `uname`, `kill`, `sleep`, and `rm` commands
|
|
22
22
|
|
|
23
23
|
## Install
|
|
24
24
|
|
|
25
25
|
### npm
|
|
26
26
|
|
|
27
27
|
```sh
|
|
28
|
-
pi install npm:pi-remote-call@0.3.
|
|
28
|
+
pi install npm:pi-remote-call@0.3.3
|
|
29
29
|
```
|
|
30
30
|
|
|
31
31
|
### GitHub
|
|
32
32
|
|
|
33
33
|
```sh
|
|
34
|
-
pi install git:github.com/therainisme/pi-remote-call@v0.3.
|
|
34
|
+
pi install git:github.com/therainisme/pi-remote-call@v0.3.3
|
|
35
35
|
```
|
|
36
36
|
|
|
37
37
|
### Local directory
|
|
@@ -49,7 +49,7 @@ Create `~/.pi/agent/pi-remote-call.json`:
|
|
|
49
49
|
}
|
|
50
50
|
```
|
|
51
51
|
|
|
52
|
-
Only aliases in `hosts[]` can be used. User, hostname, port, identity files, agent, `HostKeyAlias`, and known-hosts paths come from the existing OpenSSH configuration via `ssh -G <alias>`; secrets and connection fields are not duplicated into this file.
|
|
52
|
+
Only aliases in `hosts[]` can be used. User, hostname, port, identity files, agent, `HostKeyAlias`, `HostKeyAlgorithms`, and known-hosts paths come from the existing OpenSSH configuration via `ssh -G <alias>`; secrets and connection fields are not duplicated into this file.
|
|
53
53
|
|
|
54
54
|
Set `PI_REMOTE_CALL_CONFIG` to use a different local config path.
|
|
55
55
|
|
|
@@ -64,7 +64,7 @@ Each new connection probes for Python 3 and reports `fileMode` in host status an
|
|
|
64
64
|
|
|
65
65
|
Python is never installed by this extension. The helper runs without a daemon, remote Pi, Node.js, or MCP server. Its source is cached at `~/.pi/agent/cache/pi-remote-call/helper-v1-<sha256>.py`; the directory is mode `0700` and the helper is `0600`. Each connection verifies the regular file, size, and SHA-256 before its first cached operation, and concurrent callers share that initialization. Cache installation uses a temporary file, `fsync`, and atomic rename. Old versions are not deleted automatically.
|
|
66
66
|
|
|
67
|
-
If the cache cannot be prepared, the helper source is sent inline instead. Fallback is selected before an operation starts: a Python operation that fails is never replayed through SFTP. Host status reports `helperCache` as `installed`, `hit`, or `inline` after initialization.
|
|
67
|
+
If the cache cannot be prepared, the helper source is sent inline instead. Fallback is selected before an operation starts: a Python operation that fails is never replayed through SFTP. Host status reports `helperCache` as `installed`, `hit`, or `inline` after initialization. Inline fallback also exposes a sanitized `helperCacheError` with the failed stage and reason.
|
|
68
68
|
|
|
69
69
|
## Tools
|
|
70
70
|
|
|
@@ -150,21 +150,22 @@ Connections also close during Pi session shutdown. A later call reconnects on de
|
|
|
150
150
|
## Failure behavior
|
|
151
151
|
|
|
152
152
|
- Unknown or changed host keys fail. The extension never disables host-key checks or automatically trusts a new key.
|
|
153
|
+
- Effective `HostKeyAlgorithms` are enforced on every hop. If no configured algorithm is supported by the transport, the connection fails closed. Non-`none` `RevokedHostKeys`/KRL configuration is also refused before connection setup because full KRL evaluation is not implemented; `@revoked` known-hosts entries remain supported.
|
|
153
154
|
- Passwords, private-key passphrases, interactive 2FA, and keyboard-interactive authentication are not requested. Fix `ssh <alias>` so it works noninteractively first.
|
|
154
155
|
- A failed command or write is not automatically replayed after reconnecting.
|
|
155
|
-
-
|
|
156
|
+
- Bash commands use a random stderr completion marker to recover the real exit code if SSH omits `exit-status`. If both are absent, the outcome remains unknown. A Python helper success is accepted without either status only when its complete JSON envelope contains `result`; writes are never replayed.
|
|
156
157
|
- Python is probed when a connection opens. There is no mid-operation fallback: once a helper starts, its failure is returned and the operation is not replayed through SFTP.
|
|
157
158
|
- There are deliberately no request queues, concurrency limits, file locks, or forced serial writes. Avoid conflicting parallel edits. Concurrent writes to one path can overwrite one another.
|
|
158
159
|
|
|
159
160
|
## Limitations
|
|
160
161
|
|
|
161
|
-
-
|
|
162
|
-
- Standard `known_hosts` public keys are supported
|
|
162
|
+
- `ProxyJump` (including comma-separated hops) and `ProxyCommand` are supported. Every SSH hop requires noninteractive authentication and its own verified `known_hosts` entry. ProxyCommand supports `%h`, `%p`, `%r`, `%n`, and `%%` expansion.
|
|
163
|
+
- Standard `known_hosts` public keys are supported. CA-based `@cert-authority` trust fails explicitly: the current `ssh2` transport cannot verify certificate host-key handshakes. It must not be bypassed with a plain-key assumption.
|
|
163
164
|
- Remote targets are Linux/Bash systems, not Windows shells.
|
|
164
165
|
- Remote paths use POSIX `/`. Local Windows is supported. However, when Pi runs on Windows, `remote_read` cannot address a remote POSIX file name containing a literal backslash (`\`), because Pi's native read parser treats it as a path separator. Normal `/` paths and the other remote tools are unaffected.
|
|
165
166
|
- No interactive terminal, port forwarding, remote Pi worker, or separate search tool. Use `remote_bash` with existing remote tools such as `rg` for search.
|
|
166
167
|
- SFTP compatibility mode retains 0.1.1 behavior, including whole-file network reads and whole-file edit download/upload. Use Python mode for large remote text files.
|
|
167
|
-
- Python edit loads file content into remote memory
|
|
168
|
+
- Python edit loads file content into remote memory. Read retains only the requested lines but scans to EOF for exact `totalFileLines`, matching Pi's native read behavior. Atomic rename reduces partial-file writes but cannot eliminate the small check/rename race or make a disconnected operation's outcome certain.
|
|
168
169
|
- Python mode refuses hard-linked files, special mode bits, and metadata it cannot preserve. SFTP mode has the original 0.1.1 metadata and race limitations.
|
|
169
170
|
|
|
170
171
|
## Development
|
|
@@ -174,9 +175,9 @@ npm install
|
|
|
174
175
|
npm run check
|
|
175
176
|
```
|
|
176
177
|
|
|
177
|
-
`npm run check` typechecks, builds, and runs unit/integration tests
|
|
178
|
+
`npm run check` typechecks, builds, and runs unit/integration tests. It does not open SSH connections unless `PI_REMOTE_CALL_E2E=1` is explicitly set on Linux.
|
|
178
179
|
|
|
179
|
-
Helper integration tests run when `python3` is available. Set `PI_REMOTE_CALL_PYTHON` to select a specific local interpreter; CI provisions Python explicitly.
|
|
180
|
+
Helper integration tests run when `python3` is available. Set `PI_REMOTE_CALL_PYTHON` to select a specific local interpreter; CI provisions Python explicitly. Ordinary local tests do not open SSH connections. Ubuntu CI additionally installs OpenSSH server and sets `PI_REMOTE_CALL_E2E=1` to run direct, ProxyJump, ProxyCommand, file-operation, host-key diagnostics, session loss, cancellation, cache corruption/fallback, and injected `fsync` failure against temporary local `sshd` instances with generated keys and random ports.
|
|
180
181
|
|
|
181
182
|
Package layout:
|
|
182
183
|
|
|
@@ -192,6 +193,8 @@ src/python-files.ts Python result validation and native read formatting
|
|
|
192
193
|
src/remote_helper.py one-shot remote text read/write/edit helper
|
|
193
194
|
src/remote-helper.ts helper source identity and versioned cache path
|
|
194
195
|
src/python-protocol.ts helper stdout/stderr and JSON response handling
|
|
196
|
+
src/exit-marker.ts streaming watchdog completion-marker recovery
|
|
197
|
+
src/proxy.ts ProxyJump destinations and ProxyCommand streams
|
|
195
198
|
```
|
|
196
199
|
|
|
197
200
|
MIT
|
package/package.json
CHANGED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
export class ExitMarkerFilter {
|
|
2
|
+
private readonly marker: Buffer;
|
|
3
|
+
private pending = Buffer.alloc(0);
|
|
4
|
+
private completed = false;
|
|
5
|
+
private code?: number;
|
|
6
|
+
|
|
7
|
+
constructor(token: string) {
|
|
8
|
+
this.marker = Buffer.from(`\n${token}:`, "utf8");
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
get status(): number | undefined {
|
|
12
|
+
return this.code;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
push(data: Buffer): Buffer {
|
|
16
|
+
if (this.completed) return data;
|
|
17
|
+
this.pending = this.pending.length === 0 ? Buffer.from(data) : Buffer.concat([this.pending, data]);
|
|
18
|
+
const start = this.pending.indexOf(this.marker);
|
|
19
|
+
if (start >= 0) {
|
|
20
|
+
const before = this.pending.subarray(0, start);
|
|
21
|
+
const remainder = this.pending.subarray(start);
|
|
22
|
+
const newline = remainder.indexOf(0x0a, this.marker.length);
|
|
23
|
+
if (newline >= 0) {
|
|
24
|
+
const text = remainder.subarray(this.marker.length, newline).toString("ascii");
|
|
25
|
+
if (/^[0-9]{1,3}$/.test(text) && Number(text) <= 255) {
|
|
26
|
+
this.code = Number(text);
|
|
27
|
+
this.completed = true;
|
|
28
|
+
this.pending = Buffer.alloc(0);
|
|
29
|
+
return Buffer.concat([before, remainder.subarray(newline + 1)]);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
if (remainder.length <= this.marker.length + 4) {
|
|
33
|
+
this.pending = remainder;
|
|
34
|
+
return Buffer.from(before);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
const maximum = Math.min(this.pending.length, this.marker.length - 1);
|
|
38
|
+
let keep = 0;
|
|
39
|
+
for (let length = 1; length <= maximum; length += 1) {
|
|
40
|
+
if (this.pending.subarray(-length).equals(this.marker.subarray(0, length))) keep = length;
|
|
41
|
+
}
|
|
42
|
+
if (keep === 0) {
|
|
43
|
+
const visible = this.pending;
|
|
44
|
+
this.pending = Buffer.alloc(0);
|
|
45
|
+
return visible;
|
|
46
|
+
}
|
|
47
|
+
const visible = this.pending.subarray(0, -keep);
|
|
48
|
+
this.pending = this.pending.subarray(-keep);
|
|
49
|
+
return Buffer.from(visible);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
finish(): Buffer {
|
|
53
|
+
if (this.completed) return Buffer.alloc(0);
|
|
54
|
+
const visible = this.pending;
|
|
55
|
+
this.pending = Buffer.alloc(0);
|
|
56
|
+
return visible;
|
|
57
|
+
}
|
|
58
|
+
}
|
package/src/host-key.ts
CHANGED
|
@@ -1,11 +1,39 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
2
|
import { existsSync } from "node:fs";
|
|
3
|
+
import type { ServerHostKeyAlgorithm } from "ssh2";
|
|
3
4
|
import type { EffectiveSshConfig } from "./ssh-config.ts";
|
|
4
5
|
import { RemoteCallError } from "./errors.ts";
|
|
5
6
|
|
|
6
7
|
export interface KnownHostEntry {
|
|
7
8
|
key: string;
|
|
8
9
|
revoked: boolean;
|
|
10
|
+
certAuthority?: boolean;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const SSH2_HOST_KEY_ALGORITHMS = new Set<string>([
|
|
14
|
+
"ssh-ed25519",
|
|
15
|
+
"ecdsa-sha2-nistp256",
|
|
16
|
+
"ecdsa-sha2-nistp384",
|
|
17
|
+
"ecdsa-sha2-nistp521",
|
|
18
|
+
"rsa-sha2-512",
|
|
19
|
+
"rsa-sha2-256",
|
|
20
|
+
"ssh-rsa",
|
|
21
|
+
"ssh-dss",
|
|
22
|
+
]);
|
|
23
|
+
|
|
24
|
+
export function selectServerHostKeyAlgorithms(config: EffectiveSshConfig): ServerHostKeyAlgorithm[] | undefined {
|
|
25
|
+
if (!config.hostKeyAlgorithms?.length) return undefined;
|
|
26
|
+
const selected = [...new Set(config.hostKeyAlgorithms.filter((algorithm): algorithm is ServerHostKeyAlgorithm =>
|
|
27
|
+
SSH2_HOST_KEY_ALGORITHMS.has(algorithm)
|
|
28
|
+
))];
|
|
29
|
+
if (selected.length === 0) {
|
|
30
|
+
throw new RemoteCallError(
|
|
31
|
+
"E_UNSUPPORTED_SSH_OPTION",
|
|
32
|
+
`None of the HostKeyAlgorithms configured for ${config.alias} are supported by the ssh2 transport`,
|
|
33
|
+
"Certificate and security-key host algorithms require separate transport support",
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
return selected;
|
|
9
37
|
}
|
|
10
38
|
|
|
11
39
|
export function parseKnownHosts(output: string): KnownHostEntry[] {
|
|
@@ -14,11 +42,12 @@ export function parseKnownHosts(output: string): KnownHostEntry[] {
|
|
|
14
42
|
const line = rawLine.trim();
|
|
15
43
|
if (!line || line.startsWith("#")) continue;
|
|
16
44
|
const revoked = line.startsWith("@revoked ");
|
|
17
|
-
|
|
45
|
+
const certAuthority = line.startsWith("@cert-authority ");
|
|
46
|
+
if (line.startsWith("@") && !revoked && !certAuthority) continue;
|
|
18
47
|
const fields = line.split(/\s+/);
|
|
19
48
|
for (let i = 0; i < fields.length - 1; i++) {
|
|
20
49
|
if (/^(?:ssh|ecdsa|sk)-/.test(fields[i]) && /^[A-Za-z0-9+/]+={0,3}$/.test(fields[i + 1])) {
|
|
21
|
-
entries.push({ key: fields[i + 1], revoked });
|
|
50
|
+
entries.push({ key: fields[i + 1], revoked, ...(certAuthority ? { certAuthority: true } : {}) });
|
|
22
51
|
break;
|
|
23
52
|
}
|
|
24
53
|
}
|
|
@@ -30,7 +59,8 @@ async function lookupKnownHosts(target: string, file: string): Promise<KnownHost
|
|
|
30
59
|
if (!existsSync(file)) return [];
|
|
31
60
|
return new Promise((resolve, reject) => {
|
|
32
61
|
execFile("ssh-keygen", ["-F", target, "-f", file], { timeout: 10_000, windowsHide: true }, (error, stdout) => {
|
|
33
|
-
|
|
62
|
+
const exitCode = error ? (error as unknown as { code?: unknown }).code : undefined;
|
|
63
|
+
if (error && exitCode !== 1 && exitCode !== "1") {
|
|
34
64
|
// A missing known_hosts file is equivalent to no matching entries.
|
|
35
65
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return resolve([]);
|
|
36
66
|
return reject(error);
|
|
@@ -58,16 +88,23 @@ export async function loadKnownHostEntries(config: EffectiveSshConfig): Promise<
|
|
|
58
88
|
}
|
|
59
89
|
}
|
|
60
90
|
}
|
|
61
|
-
return [...new Map(entries.map((entry) => [`${entry.revoked}:${entry.key}`, entry])).values()];
|
|
91
|
+
return [...new Map(entries.map((entry) => [`${entry.revoked}:${entry.certAuthority}:${entry.key}`, entry])).values()];
|
|
62
92
|
}
|
|
63
93
|
|
|
64
94
|
export function verifyKnownHostKey(config: EffectiveSshConfig, entries: KnownHostEntry[], key: Buffer): void {
|
|
65
95
|
const encoded = key.toString("base64");
|
|
66
|
-
const matches = entries.filter((entry) => entry.key === encoded);
|
|
96
|
+
const matches = entries.filter((entry) => !entry.certAuthority && entry.key === encoded);
|
|
67
97
|
if (matches.some((entry) => entry.revoked)) {
|
|
68
98
|
throw new RemoteCallError("E_HOST_KEY_CHANGED", `The host key for ${config.alias} is revoked`);
|
|
69
99
|
}
|
|
70
100
|
if (matches.length > 0) return;
|
|
101
|
+
if (entries.some((entry) => entry.certAuthority)) {
|
|
102
|
+
throw new RemoteCallError(
|
|
103
|
+
"E_UNSUPPORTED_SSH_OPTION",
|
|
104
|
+
`${config.alias} uses a CA host certificate, which the ssh2 transport cannot verify during its handshake`,
|
|
105
|
+
"Use a plain verified host key for this alias; do not bypass host-key verification",
|
|
106
|
+
);
|
|
107
|
+
}
|
|
71
108
|
if (entries.length > 0) {
|
|
72
109
|
throw new RemoteCallError(
|
|
73
110
|
"E_HOST_KEY_CHANGED",
|
package/src/host-manager.ts
CHANGED
|
@@ -13,7 +13,7 @@ export class HostManager {
|
|
|
13
13
|
|
|
14
14
|
constructor(readonly config: RemoteCallConfig) {}
|
|
15
15
|
|
|
16
|
-
list(): Array<{ host: string; connected: boolean; home?: string; hostname?: string; user?: string; platform?: string; fileMode?: "python" | "sftp"; pythonVersion?: string; helperCache?: "hit" | "installed" | "inline" }> {
|
|
16
|
+
list(): Array<{ host: string; connected: boolean; home?: string; hostname?: string; user?: string; platform?: string; fileMode?: "python" | "sftp"; pythonVersion?: string; helperCache?: "hit" | "installed" | "inline"; helperCacheError?: string }> {
|
|
17
17
|
return this.config.hosts.map((host) => {
|
|
18
18
|
const connection = this.entries.get(host)?.connection;
|
|
19
19
|
return {
|
|
@@ -28,6 +28,7 @@ export class HostManager {
|
|
|
28
28
|
fileMode: connection.facts.fileMode,
|
|
29
29
|
pythonVersion: connection.facts.python?.version,
|
|
30
30
|
...(connection.facts.helperCache ? { helperCache: connection.facts.helperCache } : {}),
|
|
31
|
+
...(connection.facts.helperCacheError ? { helperCacheError: connection.facts.helperCacheError } : {}),
|
|
31
32
|
}
|
|
32
33
|
: {}),
|
|
33
34
|
};
|
package/src/proxy.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { Duplex } from "node:stream";
|
|
3
|
+
import { RemoteCallError } from "./errors.ts";
|
|
4
|
+
import type { EffectiveSshConfig } from "./ssh-config.ts";
|
|
5
|
+
|
|
6
|
+
export interface ProxyJumpDestination {
|
|
7
|
+
host: string;
|
|
8
|
+
user?: string;
|
|
9
|
+
port?: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function parseProxyJumpDestination(specification: string): ProxyJumpDestination {
|
|
13
|
+
const value = specification.trim();
|
|
14
|
+
if (!value) throw new RemoteCallError("E_SSH_CONFIG", "ProxyJump contains an empty destination");
|
|
15
|
+
const at = value.lastIndexOf("@");
|
|
16
|
+
const user = at >= 0 ? value.slice(0, at) : undefined;
|
|
17
|
+
let address = at >= 0 ? value.slice(at + 1) : value;
|
|
18
|
+
if (!address || user === "") throw new RemoteCallError("E_SSH_CONFIG", `Invalid ProxyJump destination: ${specification}`);
|
|
19
|
+
let host: string;
|
|
20
|
+
let port: number | undefined;
|
|
21
|
+
if (address.startsWith("[")) {
|
|
22
|
+
const close = address.indexOf("]");
|
|
23
|
+
if (close < 0) throw new RemoteCallError("E_SSH_CONFIG", `Invalid ProxyJump destination: ${specification}`);
|
|
24
|
+
host = address.slice(1, close);
|
|
25
|
+
const remainder = address.slice(close + 1);
|
|
26
|
+
if (remainder) {
|
|
27
|
+
if (!remainder.startsWith(":")) throw new RemoteCallError("E_SSH_CONFIG", `Invalid ProxyJump destination: ${specification}`);
|
|
28
|
+
port = Number(remainder.slice(1));
|
|
29
|
+
}
|
|
30
|
+
address = address.slice(close + 1);
|
|
31
|
+
} else {
|
|
32
|
+
const firstColon = address.indexOf(":");
|
|
33
|
+
const lastColon = address.lastIndexOf(":");
|
|
34
|
+
if (firstColon >= 0 && firstColon === lastColon) {
|
|
35
|
+
host = address.slice(0, firstColon);
|
|
36
|
+
port = Number(address.slice(firstColon + 1));
|
|
37
|
+
} else {
|
|
38
|
+
host = address;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
if (!host || (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65535))) {
|
|
42
|
+
throw new RemoteCallError("E_SSH_CONFIG", `Invalid ProxyJump destination: ${specification}`);
|
|
43
|
+
}
|
|
44
|
+
return { host, ...(user ? { user } : {}), ...(port !== undefined ? { port } : {}) };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function expandProxyCommand(command: string, config: EffectiveSshConfig): string {
|
|
48
|
+
return command.replace(/%%|%[hprn]/g, (token) => {
|
|
49
|
+
switch (token) {
|
|
50
|
+
case "%%": return "%";
|
|
51
|
+
case "%h": return config.host;
|
|
52
|
+
case "%p": return String(config.port);
|
|
53
|
+
case "%r": return config.user;
|
|
54
|
+
case "%n": return config.alias;
|
|
55
|
+
default: return token;
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function openProxyCommand(config: EffectiveSshConfig): Duplex {
|
|
61
|
+
const command = expandProxyCommand(config.proxyCommand ?? "", config);
|
|
62
|
+
const child = spawn(command, { shell: true, windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
|
|
63
|
+
const stream = Duplex.from({ readable: child.stdout, writable: child.stdin });
|
|
64
|
+
let stderr = "";
|
|
65
|
+
child.stderr.on("data", (data: Buffer) => {
|
|
66
|
+
stderr = (stderr + data.toString("utf8")).slice(-4000);
|
|
67
|
+
});
|
|
68
|
+
child.once("error", (error) => stream.destroy(error));
|
|
69
|
+
child.once("exit", (code) => {
|
|
70
|
+
if (code !== 0 && !stream.destroyed) {
|
|
71
|
+
stream.destroy(new RemoteCallError(
|
|
72
|
+
"E_CONNECT",
|
|
73
|
+
`ProxyCommand for ${config.alias} exited with status ${code}${stderr.trim() ? `: ${stderr.trim()}` : ""}`,
|
|
74
|
+
));
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
stream.once("close", () => {
|
|
78
|
+
if (child.exitCode === null && child.signalCode === null) child.kill();
|
|
79
|
+
});
|
|
80
|
+
return stream;
|
|
81
|
+
}
|
package/src/python-protocol.ts
CHANGED
|
@@ -5,6 +5,7 @@ export function parsePythonHelperResponse(
|
|
|
5
5
|
stdout: string,
|
|
6
6
|
stderr: string,
|
|
7
7
|
exitCode: number | null,
|
|
8
|
+
missingExitStatus = false,
|
|
8
9
|
): unknown {
|
|
9
10
|
const output = stdout.trim();
|
|
10
11
|
const diagnostic = stderr.trim().slice(0, 2000);
|
|
@@ -12,6 +13,9 @@ export function parsePythonHelperResponse(
|
|
|
12
13
|
try {
|
|
13
14
|
envelope = JSON.parse(output) as typeof envelope;
|
|
14
15
|
} catch (error) {
|
|
16
|
+
if (missingExitStatus) {
|
|
17
|
+
throw new RemoteCallError("E_DISCONNECTED", `Python helper on ${alias} ended without an exit status and returned an incomplete JSON response; its outcome is unknown`, undefined, { cause: error });
|
|
18
|
+
}
|
|
15
19
|
throw new RemoteCallError(
|
|
16
20
|
"E_REMOTE_HELPER",
|
|
17
21
|
`Python helper on ${alias} returned invalid output (exit ${exitCode}): ${output.slice(0, 2000)}${diagnostic ? `\nRemote stderr: ${diagnostic}` : ""}`,
|
|
@@ -19,7 +23,12 @@ export function parsePythonHelperResponse(
|
|
|
19
23
|
{ cause: error },
|
|
20
24
|
);
|
|
21
25
|
}
|
|
22
|
-
if (envelope.ok === true && exitCode === 0)
|
|
26
|
+
if (envelope.ok === true && (exitCode === 0 || missingExitStatus)) {
|
|
27
|
+
if (missingExitStatus && !Object.hasOwn(envelope, "result")) {
|
|
28
|
+
throw new RemoteCallError("E_DISCONNECTED", `Python helper on ${alias} returned a success flag without a result after its exit status was lost; its outcome is unknown`);
|
|
29
|
+
}
|
|
30
|
+
return envelope.result;
|
|
31
|
+
}
|
|
23
32
|
const code = typeof envelope.error?.code === "string" ? envelope.error.code : "E_REMOTE_HELPER";
|
|
24
33
|
const message = typeof envelope.error?.message === "string"
|
|
25
34
|
? envelope.error.message
|
package/src/remote-helper.ts
CHANGED
|
@@ -10,3 +10,10 @@ export const PYTHON_HELPER_BYTES = Buffer.byteLength(PYTHON_HELPER_SOURCE, "utf8
|
|
|
10
10
|
export function pythonHelperCachePath(home: string): string {
|
|
11
11
|
return posix.join(home, ".pi", "agent", "cache", "pi-remote-call", `helper-v${PYTHON_HELPER_PROTOCOL}-${PYTHON_HELPER_SHA256}.py`);
|
|
12
12
|
}
|
|
13
|
+
|
|
14
|
+
export function helperCacheErrorMessage(stage: string, error: unknown, home: string): string {
|
|
15
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
16
|
+
const withoutHome = home ? message.split(home).join("~") : message;
|
|
17
|
+
const sanitized = withoutHome.replace(/[\u0000-\u001f\u007f]+/g, " ").trim();
|
|
18
|
+
return `${stage}: ${sanitized || "unknown error"}`.slice(0, 400);
|
|
19
|
+
}
|
package/src/ssh-config.ts
CHANGED
|
@@ -18,6 +18,8 @@ export interface EffectiveSshConfig {
|
|
|
18
18
|
proxyJump?: string;
|
|
19
19
|
proxyCommand?: string;
|
|
20
20
|
hostKeyAlias?: string;
|
|
21
|
+
hostKeyAlgorithms?: string[];
|
|
22
|
+
revokedHostKeys?: string;
|
|
21
23
|
}
|
|
22
24
|
|
|
23
25
|
function unquote(value: string): string {
|
|
@@ -110,6 +112,11 @@ export function parseSshG(alias: string, output: string): EffectiveSshConfig {
|
|
|
110
112
|
].map((path) => normalizeLocalSshPath(path));
|
|
111
113
|
if (knownHostsFiles.length === 0) knownHostsFiles.push(join(homedir(), ".ssh", "known_hosts"));
|
|
112
114
|
const proxyJump = one("proxyjump");
|
|
115
|
+
const hostKeyAlgorithms = one("hostkeyalgorithms")?.split(",").map((value) => value.trim()).filter(Boolean);
|
|
116
|
+
const revokedHostKeysValue = one("revokedhostkeys");
|
|
117
|
+
const revokedHostKeys = revokedHostKeysValue && revokedHostKeysValue.toLowerCase() !== "none"
|
|
118
|
+
? normalizeLocalSshPath(revokedHostKeysValue)
|
|
119
|
+
: undefined;
|
|
113
120
|
return {
|
|
114
121
|
alias,
|
|
115
122
|
host,
|
|
@@ -122,12 +129,21 @@ export function parseSshG(alias: string, output: string): EffectiveSshConfig {
|
|
|
122
129
|
proxyJump: proxyJump && proxyJump !== "none" ? proxyJump : undefined,
|
|
123
130
|
proxyCommand: one("proxycommand") && one("proxycommand") !== "none" ? one("proxycommand") : undefined,
|
|
124
131
|
hostKeyAlias: one("hostkeyalias"),
|
|
132
|
+
...(hostKeyAlgorithms?.length ? { hostKeyAlgorithms } : {}),
|
|
133
|
+
...(revokedHostKeys ? { revokedHostKeys } : {}),
|
|
125
134
|
};
|
|
126
135
|
}
|
|
127
136
|
|
|
128
|
-
export async function resolveSshConfig(
|
|
137
|
+
export async function resolveSshConfig(
|
|
138
|
+
alias: string,
|
|
139
|
+
destination?: { host: string; user?: string; port?: number },
|
|
140
|
+
): Promise<EffectiveSshConfig> {
|
|
129
141
|
try {
|
|
130
|
-
const
|
|
142
|
+
const args = ["-G"];
|
|
143
|
+
if (destination?.user) args.push("-l", destination.user);
|
|
144
|
+
if (destination?.port !== undefined) args.push("-p", String(destination.port));
|
|
145
|
+
args.push(destination?.host ?? alias);
|
|
146
|
+
const { stdout } = await execFileAsync("ssh", args, {
|
|
131
147
|
timeout: 10_000,
|
|
132
148
|
windowsHide: true,
|
|
133
149
|
maxBuffer: 4 * 1024 * 1024,
|
package/src/transport.ts
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
import { randomBytes } from "node:crypto";
|
|
2
2
|
import { readFile } from "node:fs/promises";
|
|
3
3
|
import { posix } from "node:path";
|
|
4
|
-
import
|
|
4
|
+
import type { Duplex } from "node:stream";
|
|
5
|
+
import { Client, type ClientChannel, type ConnectConfig, type ServerHostKeyAlgorithm, type SFTPWrapper } from "ssh2";
|
|
5
6
|
import type { BashOperations, EditOperations, ReadOperations, WriteOperations } from "@earendil-works/pi-coding-agent";
|
|
6
7
|
import { asRemoteCallError, RemoteCallError } from "./errors.ts";
|
|
7
|
-
import {
|
|
8
|
+
import { ExitMarkerFilter } from "./exit-marker.ts";
|
|
9
|
+
import { loadKnownHostEntries, selectServerHostKeyAlgorithms, verifyKnownHostKey, type KnownHostEntry } from "./host-key.ts";
|
|
8
10
|
import type { PythonFileRequest } from "./python-files.ts";
|
|
9
|
-
import { PYTHON_HELPER_BYTES, PYTHON_HELPER_SHA256, PYTHON_HELPER_SOURCE, pythonHelperCachePath } from "./remote-helper.ts";
|
|
11
|
+
import { PYTHON_HELPER_BYTES, PYTHON_HELPER_SHA256, PYTHON_HELPER_SOURCE, helperCacheErrorMessage, pythonHelperCachePath } from "./remote-helper.ts";
|
|
10
12
|
import { parsePythonHelperResponse } from "./python-protocol.ts";
|
|
13
|
+
import { openProxyCommand, parseProxyJumpDestination } from "./proxy.ts";
|
|
11
14
|
import { remoteCommandScript, shellQuote } from "./remote-path.ts";
|
|
12
15
|
import { resolveSshConfig, type EffectiveSshConfig } from "./ssh-config.ts";
|
|
13
16
|
import {
|
|
@@ -32,13 +35,14 @@ export interface RemoteHostFacts {
|
|
|
32
35
|
fileMode: "python" | "sftp";
|
|
33
36
|
python?: { path: string; version: string };
|
|
34
37
|
helperCache?: "hit" | "installed" | "inline";
|
|
38
|
+
helperCacheError?: string;
|
|
35
39
|
}
|
|
36
40
|
|
|
37
41
|
type AuthAttempt =
|
|
38
42
|
| { kind: "agent"; agent: string; label: string }
|
|
39
43
|
| { kind: "privateKey"; privateKey: Buffer; label: string };
|
|
40
44
|
|
|
41
|
-
export function watchdogScript(command: string, cwd: string): string {
|
|
45
|
+
export function watchdogScript(command: string, cwd: string, completionMarker?: string): string {
|
|
42
46
|
return `set -m
|
|
43
47
|
${remoteCommandScript(`bash -c ${shellQuote(command)} </dev/null &`, cwd)}
|
|
44
48
|
command_pid=$!
|
|
@@ -54,7 +58,7 @@ wait "$command_pid"
|
|
|
54
58
|
status=$?
|
|
55
59
|
disown %2 2>/dev/null
|
|
56
60
|
kill "$watchdog_pid" 2>/dev/null
|
|
57
|
-
exit "$status"
|
|
61
|
+
${completionMarker ? `printf '\\n%s:%s\\n' ${shellQuote(completionMarker)} "$status" >&2\n` : ""}exit "$status"
|
|
58
62
|
`;
|
|
59
63
|
}
|
|
60
64
|
|
|
@@ -102,10 +106,13 @@ async function connectWithAttempt(
|
|
|
102
106
|
config: EffectiveSshConfig,
|
|
103
107
|
knownHosts: KnownHostEntry[],
|
|
104
108
|
attempt: AuthAttempt,
|
|
109
|
+
sock?: Duplex,
|
|
110
|
+
hostKeyAlgorithms?: ServerHostKeyAlgorithm[],
|
|
105
111
|
): Promise<Client> {
|
|
106
112
|
return new Promise((resolve, reject) => {
|
|
107
113
|
const client = new Client();
|
|
108
114
|
let hostKeyError: RemoteCallError | undefined;
|
|
115
|
+
let settled = false;
|
|
109
116
|
const options: ConnectConfig = {
|
|
110
117
|
host: config.host,
|
|
111
118
|
port: config.port,
|
|
@@ -125,15 +132,20 @@ async function connectWithAttempt(
|
|
|
125
132
|
}
|
|
126
133
|
},
|
|
127
134
|
};
|
|
135
|
+
if (sock) options.sock = sock;
|
|
136
|
+
if (hostKeyAlgorithms) options.algorithms = { serverHostKey: hostKeyAlgorithms };
|
|
128
137
|
if (attempt.kind === "agent") options.agent = attempt.agent;
|
|
129
138
|
else options.privateKey = attempt.privateKey;
|
|
130
139
|
const onError = (error: Error) => {
|
|
131
140
|
client.end();
|
|
141
|
+
if (settled) return;
|
|
142
|
+
settled = true;
|
|
132
143
|
if (hostKeyError) return reject(hostKeyError);
|
|
133
144
|
reject(error);
|
|
134
145
|
};
|
|
135
|
-
client.
|
|
146
|
+
client.on("error", onError);
|
|
136
147
|
client.once("ready", () => {
|
|
148
|
+
settled = true;
|
|
137
149
|
client.removeListener("error", onError);
|
|
138
150
|
client.on("error", () => undefined);
|
|
139
151
|
resolve(client);
|
|
@@ -157,6 +169,117 @@ async function authAttempts(config: EffectiveSshConfig): Promise<AuthAttempt[]>
|
|
|
157
169
|
return attempts;
|
|
158
170
|
}
|
|
159
171
|
|
|
172
|
+
export function isAuthenticationFailure(error: unknown): boolean {
|
|
173
|
+
if (error instanceof RemoteCallError) return error.code === "E_AUTH";
|
|
174
|
+
const candidate = error as { level?: unknown } | undefined;
|
|
175
|
+
if (candidate?.level === "client-authentication") return true;
|
|
176
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
177
|
+
return /Cannot parse privateKey|encrypted private key|private key.*passphrase|All configured authentication methods failed/i.test(message);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export type SshConfigResolver = (specification: string) => Promise<EffectiveSshConfig>;
|
|
181
|
+
|
|
182
|
+
interface ClientTransport {
|
|
183
|
+
client: Client;
|
|
184
|
+
parents: Client[];
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function closeClients(clients: Client[]): void {
|
|
188
|
+
for (let index = clients.length - 1; index >= 0; index -= 1) clients[index].end();
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
async function defaultJumpResolver(specification: string): Promise<EffectiveSshConfig> {
|
|
192
|
+
return resolveSshConfig(specification, parseProxyJumpDestination(specification));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function forwardOut(client: Client, host: string, port: number): Promise<ClientChannel> {
|
|
196
|
+
return new Promise((resolve, reject) => {
|
|
197
|
+
client.forwardOut("127.0.0.1", 0, host, port, (error, channel) => (error ? reject(error) : resolve(channel)));
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async function connectClient(
|
|
202
|
+
config: EffectiveSshConfig,
|
|
203
|
+
resolver: SshConfigResolver,
|
|
204
|
+
stack: string[] = [],
|
|
205
|
+
via?: () => Promise<Duplex>,
|
|
206
|
+
): Promise<ClientTransport> {
|
|
207
|
+
if (stack.includes(config.alias)) throw new RemoteCallError("E_SSH_CONFIG", `ProxyJump cycle detected at ${config.alias}`);
|
|
208
|
+
if (!via && config.proxyJump && config.proxyCommand) {
|
|
209
|
+
throw new RemoteCallError("E_SSH_CONFIG", `${config.alias} has both ProxyJump and ProxyCommand; use one proxy method`);
|
|
210
|
+
}
|
|
211
|
+
if (config.revokedHostKeys) {
|
|
212
|
+
throw new RemoteCallError(
|
|
213
|
+
"E_UNSUPPORTED_SSH_OPTION",
|
|
214
|
+
`${config.alias} uses RevokedHostKeys/KRL, which this transport cannot enforce`,
|
|
215
|
+
"The connection was refused before authentication. KRL support is required for this alias",
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
const hostKeyAlgorithms = selectServerHostKeyAlgorithms(config);
|
|
219
|
+
let transportDescription = via ? `ProxyJump forwarding for ${config.alias}` : `SSH transport for ${config.alias}`;
|
|
220
|
+
const parents: Client[] = [];
|
|
221
|
+
try {
|
|
222
|
+
// A socket supplied by an explicit ProxyJump list defines this hop's route.
|
|
223
|
+
// Do not apply the hop's own proxy configuration a second time.
|
|
224
|
+
let socketFactory = via;
|
|
225
|
+
if (!socketFactory && config.proxyJump) {
|
|
226
|
+
transportDescription = `ProxyJump transport for ${config.alias}`;
|
|
227
|
+
const specifications = config.proxyJump.split(",").map((value) => value.trim()).filter(Boolean);
|
|
228
|
+
if (specifications.length === 0) throw new RemoteCallError("E_SSH_CONFIG", `ProxyJump is empty for ${config.alias}`);
|
|
229
|
+
let previous: Client | undefined;
|
|
230
|
+
for (const specification of specifications) {
|
|
231
|
+
const jumpConfig = await resolver(specification);
|
|
232
|
+
const upstream = previous;
|
|
233
|
+
const nextVia = upstream ? () => forwardOut(upstream, jumpConfig.host, jumpConfig.port) : undefined;
|
|
234
|
+
const jump = await connectClient(jumpConfig, resolver, [...stack, config.alias], nextVia);
|
|
235
|
+
parents.push(...jump.parents, jump.client);
|
|
236
|
+
previous = jump.client;
|
|
237
|
+
}
|
|
238
|
+
if (!previous) throw new RemoteCallError("E_SSH_CONFIG", `ProxyJump is empty for ${config.alias}`);
|
|
239
|
+
const jump = previous;
|
|
240
|
+
socketFactory = () => forwardOut(jump, config.host, config.port);
|
|
241
|
+
} else if (!socketFactory && config.proxyCommand) {
|
|
242
|
+
transportDescription = `ProxyCommand transport for ${config.alias}`;
|
|
243
|
+
socketFactory = async () => openProxyCommand(config);
|
|
244
|
+
}
|
|
245
|
+
const knownHosts = await loadKnownHostEntries(config);
|
|
246
|
+
if (knownHosts.some((entry) => entry.certAuthority) && !knownHosts.some((entry) => !entry.certAuthority)) {
|
|
247
|
+
throw new RemoteCallError(
|
|
248
|
+
"E_UNSUPPORTED_SSH_OPTION",
|
|
249
|
+
`${config.alias} uses CA host certificates, which the ssh2 transport cannot verify during its handshake`,
|
|
250
|
+
"Use a plain verified host key for this alias; do not bypass host-key verification",
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
const attempts = await authAttempts(config);
|
|
254
|
+
if (attempts.length === 0) {
|
|
255
|
+
throw new RemoteCallError("E_AUTH", `No local ssh-agent or readable private key found for ${config.alias}`, `Run: ssh ${config.alias}`);
|
|
256
|
+
}
|
|
257
|
+
let lastError: unknown;
|
|
258
|
+
for (const attempt of attempts) {
|
|
259
|
+
try {
|
|
260
|
+
const sock = socketFactory ? await socketFactory() : undefined;
|
|
261
|
+
const client = await connectWithAttempt(config, knownHosts, attempt, sock, hostKeyAlgorithms);
|
|
262
|
+
return { client, parents };
|
|
263
|
+
} catch (error) {
|
|
264
|
+
lastError = error;
|
|
265
|
+
if (error instanceof RemoteCallError && (error.code.startsWith("E_HOST_KEY") || error.code === "E_UNSUPPORTED_SSH_OPTION")) throw error;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
if (isAuthenticationFailure(lastError)) {
|
|
269
|
+
throw new RemoteCallError(
|
|
270
|
+
"E_AUTH",
|
|
271
|
+
`Non-interactive SSH authentication failed for ${config.alias}`,
|
|
272
|
+
`Make ssh ${config.alias} work without a password or passphrase, then retry. Last error: ${lastError instanceof Error ? lastError.message : String(lastError)}`,
|
|
273
|
+
{ cause: lastError },
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
throw asRemoteCallError(lastError, "E_CONNECT", `Cannot establish ${transportDescription}`);
|
|
277
|
+
} catch (error) {
|
|
278
|
+
closeClients(parents);
|
|
279
|
+
throw error;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
160
283
|
export class SshConnection {
|
|
161
284
|
readonly facts: RemoteHostFacts;
|
|
162
285
|
onClose?: () => void;
|
|
@@ -167,57 +290,35 @@ export class SshConnection {
|
|
|
167
290
|
readonly client: Client,
|
|
168
291
|
readonly sftp: SFTPWrapper,
|
|
169
292
|
facts: RemoteHostFacts,
|
|
293
|
+
readonly parentClients: Client[] = [],
|
|
170
294
|
) {
|
|
171
295
|
this.facts = facts;
|
|
172
296
|
client.on("error", () => undefined);
|
|
173
297
|
client.once("close", () => {
|
|
174
298
|
this.closed = true;
|
|
299
|
+
closeClients(parentClients);
|
|
175
300
|
this.onClose?.();
|
|
176
301
|
});
|
|
177
302
|
}
|
|
178
303
|
|
|
179
304
|
static async connect(alias: string): Promise<SshConnection> {
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
305
|
+
return this.connectResolved(await resolveSshConfig(alias), defaultJumpResolver);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
static async connectResolved(config: EffectiveSshConfig, resolver: SshConfigResolver = defaultJumpResolver): Promise<SshConnection> {
|
|
309
|
+
const { client, parents } = await connectClient(config, resolver);
|
|
310
|
+
try {
|
|
311
|
+
const sftp = await new Promise<SFTPWrapper>((resolve, reject) =>
|
|
312
|
+
client.sftp((error, value) => (error ? reject(error) : resolve(value))),
|
|
186
313
|
);
|
|
314
|
+
const home = await sftpRealpath(sftp, ".");
|
|
315
|
+
const facts = await probeHost(client, config.alias, home);
|
|
316
|
+
return new SshConnection(client, sftp, facts, parents);
|
|
317
|
+
} catch (error) {
|
|
318
|
+
client.end();
|
|
319
|
+
closeClients(parents);
|
|
320
|
+
throw asRemoteCallError(error, "E_CONNECT", `SSH connected to ${config.alias}, but SFTP/Bash initialization failed`);
|
|
187
321
|
}
|
|
188
|
-
const knownHosts = await loadKnownHostEntries(config);
|
|
189
|
-
const attempts = await authAttempts(config);
|
|
190
|
-
if (attempts.length === 0) {
|
|
191
|
-
throw new RemoteCallError("E_AUTH", `No local ssh-agent or readable private key found for ${alias}`, `Run: ssh ${alias}`);
|
|
192
|
-
}
|
|
193
|
-
let lastError: unknown;
|
|
194
|
-
for (const attempt of attempts) {
|
|
195
|
-
let client: Client;
|
|
196
|
-
try {
|
|
197
|
-
client = await connectWithAttempt(config, knownHosts, attempt);
|
|
198
|
-
} catch (error) {
|
|
199
|
-
lastError = error;
|
|
200
|
-
if (error instanceof RemoteCallError && error.code.startsWith("E_HOST_KEY")) throw error;
|
|
201
|
-
continue;
|
|
202
|
-
}
|
|
203
|
-
try {
|
|
204
|
-
const sftp = await new Promise<SFTPWrapper>((resolve, reject) =>
|
|
205
|
-
client.sftp((error, value) => (error ? reject(error) : resolve(value))),
|
|
206
|
-
);
|
|
207
|
-
const home = await sftpRealpath(sftp, ".");
|
|
208
|
-
const facts = await probeHost(client, alias, home);
|
|
209
|
-
return new SshConnection(client, sftp, facts);
|
|
210
|
-
} catch (error) {
|
|
211
|
-
client.end();
|
|
212
|
-
throw asRemoteCallError(error, "E_CONNECT", `SSH connected to ${alias}, but SFTP/Bash initialization failed`);
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
throw new RemoteCallError(
|
|
216
|
-
"E_AUTH",
|
|
217
|
-
`Non-interactive SSH authentication failed for ${alias}`,
|
|
218
|
-
`Make ssh ${alias} work without a password or passphrase, then retry. Last error: ${lastError instanceof Error ? lastError.message : String(lastError)}`,
|
|
219
|
-
{ cause: lastError },
|
|
220
|
-
);
|
|
221
322
|
}
|
|
222
323
|
|
|
223
324
|
get isOpen(): boolean {
|
|
@@ -261,11 +362,16 @@ export class SshConnection {
|
|
|
261
362
|
private async exec(
|
|
262
363
|
command: string,
|
|
263
364
|
cwd: string,
|
|
264
|
-
options: { onData: (data: Buffer) => void; onStderr?: (data: Buffer) => void; signal?: AbortSignal; timeout?: number },
|
|
265
|
-
): Promise<{ exitCode: number | null }> {
|
|
365
|
+
options: { onData: (data: Buffer) => void; onStderr?: (data: Buffer) => void; signal?: AbortSignal; timeout?: number; allowMissingExitStatus?: boolean },
|
|
366
|
+
): Promise<{ exitCode: number | null; missingExitStatus: boolean }> {
|
|
266
367
|
if (this.closed) throw new RemoteCallError("E_CLOSED", `SSH connection is closed for ${this.facts.alias}`);
|
|
267
368
|
if (options.signal?.aborted) throw new Error("Operation aborted");
|
|
268
|
-
const
|
|
369
|
+
const completionMarker = `pi-remote-call-exit-${randomBytes(12).toString("hex")}`;
|
|
370
|
+
const channel = await openChannel(this.client, `bash -c ${shellQuote(watchdogScript(command, cwd, completionMarker))}`);
|
|
371
|
+
const marker = new ExitMarkerFilter(completionMarker);
|
|
372
|
+
const forwardStderr = (data: Buffer) => {
|
|
373
|
+
if (data.length > 0) (options.onStderr ?? options.onData)(data);
|
|
374
|
+
};
|
|
269
375
|
let exitCode: number | null = null;
|
|
270
376
|
let exitSeen = false;
|
|
271
377
|
let timedOut = false;
|
|
@@ -286,7 +392,7 @@ export class SshConnection {
|
|
|
286
392
|
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
287
393
|
if (options.signal?.aborted) onAbort();
|
|
288
394
|
channel.stdout.on("data", options.onData);
|
|
289
|
-
channel.stderr.on("data",
|
|
395
|
+
channel.stderr.on("data", (data: Buffer) => forwardStderr(marker.push(data)));
|
|
290
396
|
channel.on("exit", (code: number | null) => {
|
|
291
397
|
exitSeen = true;
|
|
292
398
|
exitCode = typeof code === "number" ? code : null;
|
|
@@ -294,6 +400,7 @@ export class SshConnection {
|
|
|
294
400
|
return new Promise((resolve, reject) => {
|
|
295
401
|
channel.once("error", (error: Error) => {
|
|
296
402
|
if (settled) return;
|
|
403
|
+
forwardStderr(marker.finish());
|
|
297
404
|
settled = true;
|
|
298
405
|
if (timer) clearTimeout(timer);
|
|
299
406
|
if (forceTimer) clearTimeout(forceTimer);
|
|
@@ -302,14 +409,17 @@ export class SshConnection {
|
|
|
302
409
|
});
|
|
303
410
|
channel.once("close", () => {
|
|
304
411
|
if (settled) return;
|
|
412
|
+
forwardStderr(marker.finish());
|
|
305
413
|
settled = true;
|
|
306
414
|
if (timer) clearTimeout(timer);
|
|
307
415
|
if (forceTimer) clearTimeout(forceTimer);
|
|
308
416
|
options.signal?.removeEventListener("abort", onAbort);
|
|
309
417
|
if (options.signal?.aborted) reject(new Error("aborted"));
|
|
310
418
|
else if (timedOut) reject(new Error(`timeout:${options.timeout}`));
|
|
311
|
-
else if (!exitSeen
|
|
312
|
-
else resolve({ exitCode });
|
|
419
|
+
else if (!exitSeen && marker.status !== undefined) resolve({ exitCode: marker.status, missingExitStatus: false });
|
|
420
|
+
else if (!exitSeen && options.allowMissingExitStatus) resolve({ exitCode: null, missingExitStatus: true });
|
|
421
|
+
else if (!exitSeen) reject(new RemoteCallError("E_DISCONNECTED", `Remote command on ${this.facts.alias} ended without an exit status or completion marker; its outcome is unknown`));
|
|
422
|
+
else resolve({ exitCode, missingExitStatus: false });
|
|
313
423
|
});
|
|
314
424
|
});
|
|
315
425
|
}
|
|
@@ -335,21 +445,31 @@ export class SshConnection {
|
|
|
335
445
|
this.helperReady = (async () => {
|
|
336
446
|
const cachePath = pythonHelperCachePath(this.facts.home);
|
|
337
447
|
const cacheDirectory = posix.dirname(cachePath);
|
|
448
|
+
let stage = "inspect cache";
|
|
338
449
|
try {
|
|
339
450
|
const cached = await sftpLstat(this.sftp, cachePath).catch(() => undefined);
|
|
340
|
-
if (cached?.isFile() && cached.size === PYTHON_HELPER_BYTES && (cached.mode & 0o077) === 0
|
|
341
|
-
|
|
342
|
-
|
|
451
|
+
if (cached?.isFile() && cached.size === PYTHON_HELPER_BYTES && (cached.mode & 0o077) === 0) {
|
|
452
|
+
stage = "verify cached helper";
|
|
453
|
+
if (await this.verifyPythonHelper(cachePath)) {
|
|
454
|
+
this.facts.helperCache = "hit";
|
|
455
|
+
delete this.facts.helperCacheError;
|
|
456
|
+
return cachePath;
|
|
457
|
+
}
|
|
343
458
|
}
|
|
459
|
+
stage = "create cache directory";
|
|
344
460
|
await sftpMkdirP(this.sftp, cacheDirectory);
|
|
345
461
|
await sftpSetStat(this.sftp, cacheDirectory, { mode: 0o700 });
|
|
462
|
+
stage = "install helper";
|
|
346
463
|
await sftpWriteFileAtomic(this.sftp, cachePath, PYTHON_HELPER_SOURCE, true);
|
|
347
464
|
await sftpSetStat(this.sftp, cachePath, { mode: 0o600 });
|
|
465
|
+
stage = "verify installed helper";
|
|
348
466
|
if (!await this.verifyPythonHelper(cachePath)) throw new Error("Cached helper hash verification failed");
|
|
349
467
|
this.facts.helperCache = "installed";
|
|
468
|
+
delete this.facts.helperCacheError;
|
|
350
469
|
return cachePath;
|
|
351
|
-
} catch {
|
|
470
|
+
} catch (error) {
|
|
352
471
|
this.facts.helperCache = "inline";
|
|
472
|
+
this.facts.helperCacheError = helperCacheErrorMessage(stage, error, this.facts.home);
|
|
353
473
|
return undefined;
|
|
354
474
|
}
|
|
355
475
|
})();
|
|
@@ -376,17 +496,19 @@ export class SshConnection {
|
|
|
376
496
|
? `${shellQuote(python.path)} ${shellQuote(helperPath)} ${shellQuote(requestPath)}`
|
|
377
497
|
: `${shellQuote(python.path)} -c ${shellQuote(PYTHON_HELPER_SOURCE)} ${shellQuote(requestPath)}`;
|
|
378
498
|
const command = `${helperCommand}; helper_status=$?; rm -f -- ${shellQuote(requestPath)}; exit "$helper_status"`;
|
|
379
|
-
const { exitCode } = await this.exec(command, this.facts.home, {
|
|
499
|
+
const { exitCode, missingExitStatus } = await this.exec(command, this.facts.home, {
|
|
380
500
|
onData: (data) => stdoutChunks.push(Buffer.from(data)),
|
|
381
501
|
onStderr: (data) => stderrChunks.push(Buffer.from(data)),
|
|
382
502
|
signal,
|
|
503
|
+
allowMissingExitStatus: true,
|
|
383
504
|
});
|
|
384
|
-
remoteCleanup =
|
|
505
|
+
remoteCleanup = !missingExitStatus;
|
|
385
506
|
return parsePythonHelperResponse(
|
|
386
507
|
this.facts.alias,
|
|
387
508
|
Buffer.concat(stdoutChunks).toString("utf8"),
|
|
388
509
|
Buffer.concat(stderrChunks).toString("utf8"),
|
|
389
510
|
exitCode,
|
|
511
|
+
missingExitStatus,
|
|
390
512
|
);
|
|
391
513
|
} finally {
|
|
392
514
|
if (requestCreated && !remoteCleanup) await sftpUnlink(this.sftp, requestPath).catch(() => undefined);
|
|
@@ -397,5 +519,6 @@ export class SshConnection {
|
|
|
397
519
|
if (this.closed) return;
|
|
398
520
|
this.closed = true;
|
|
399
521
|
this.client.end();
|
|
522
|
+
closeClients(this.parentClients);
|
|
400
523
|
}
|
|
401
524
|
}
|