pi-remote-call 0.3.1 → 0.3.2
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 +13 -0
- package/README.md +10 -8
- package/package.json +1 -1
- package/src/exit-marker.ts +58 -0
- package/src/host-key.ts +13 -4
- package/src/proxy.ts +81 -0
- package/src/python-protocol.ts +10 -1
- package/src/ssh-config.ts +9 -2
- package/src/transport.ts +133 -49
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.2 - 2026-11-28
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- ProxyJump and ProxyCommand transports with per-hop noninteractive authentication and strict known_hosts verification.
|
|
8
|
+
- Real OpenSSH CI coverage using temporary direct and jump servers, generated credentials, random ports, file operations, and proxy paths.
|
|
9
|
+
|
|
10
|
+
### Changed
|
|
11
|
+
|
|
12
|
+
- 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.
|
|
13
|
+
- 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.
|
|
14
|
+
- CA-only `@cert-authority` trust now fails explicitly because `ssh2` cannot verify certificate host-key handshakes; this release does not claim CA support.
|
|
15
|
+
|
|
3
16
|
## 0.3.1 - 2026-11-28
|
|
4
17
|
|
|
5
18
|
### 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.2
|
|
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.2
|
|
35
35
|
```
|
|
36
36
|
|
|
37
37
|
### Local directory
|
|
@@ -152,14 +152,14 @@ Connections also close during Pi session shutdown. A later call reconnects on de
|
|
|
152
152
|
- Unknown or changed host keys fail. The extension never disables host-key checks or automatically trusts a new key.
|
|
153
153
|
- Passwords, private-key passphrases, interactive 2FA, and keyboard-interactive authentication are not requested. Fix `ssh <alias>` so it works noninteractively first.
|
|
154
154
|
- A failed command or write is not automatically replayed after reconnecting.
|
|
155
|
-
-
|
|
155
|
+
- 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
156
|
- 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
157
|
- 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
158
|
|
|
159
159
|
## Limitations
|
|
160
160
|
|
|
161
|
-
-
|
|
162
|
-
- Standard `known_hosts` public keys are supported
|
|
161
|
+
- `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.
|
|
162
|
+
- 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
163
|
- Remote targets are Linux/Bash systems, not Windows shells.
|
|
164
164
|
- 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
165
|
- No interactive terminal, port forwarding, remote Pi worker, or separate search tool. Use `remote_bash` with existing remote tools such as `rg` for search.
|
|
@@ -174,9 +174,9 @@ npm install
|
|
|
174
174
|
npm run check
|
|
175
175
|
```
|
|
176
176
|
|
|
177
|
-
`npm run check` typechecks, builds, and runs unit/integration tests
|
|
177
|
+
`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
178
|
|
|
179
|
-
Helper integration tests run when `python3` is available. Set `PI_REMOTE_CALL_PYTHON` to select a specific local interpreter; CI provisions Python explicitly.
|
|
179
|
+
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, and host-key diagnostics against temporary local `sshd` instances with generated keys and random ports.
|
|
180
180
|
|
|
181
181
|
Package layout:
|
|
182
182
|
|
|
@@ -192,6 +192,8 @@ src/python-files.ts Python result validation and native read formatting
|
|
|
192
192
|
src/remote_helper.py one-shot remote text read/write/edit helper
|
|
193
193
|
src/remote-helper.ts helper source identity and versioned cache path
|
|
194
194
|
src/python-protocol.ts helper stdout/stderr and JSON response handling
|
|
195
|
+
src/exit-marker.ts streaming watchdog completion-marker recovery
|
|
196
|
+
src/proxy.ts ProxyJump destinations and ProxyCommand streams
|
|
195
197
|
```
|
|
196
198
|
|
|
197
199
|
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
|
@@ -6,6 +6,7 @@ import { RemoteCallError } from "./errors.ts";
|
|
|
6
6
|
export interface KnownHostEntry {
|
|
7
7
|
key: string;
|
|
8
8
|
revoked: boolean;
|
|
9
|
+
certAuthority?: boolean;
|
|
9
10
|
}
|
|
10
11
|
|
|
11
12
|
export function parseKnownHosts(output: string): KnownHostEntry[] {
|
|
@@ -14,11 +15,12 @@ export function parseKnownHosts(output: string): KnownHostEntry[] {
|
|
|
14
15
|
const line = rawLine.trim();
|
|
15
16
|
if (!line || line.startsWith("#")) continue;
|
|
16
17
|
const revoked = line.startsWith("@revoked ");
|
|
17
|
-
|
|
18
|
+
const certAuthority = line.startsWith("@cert-authority ");
|
|
19
|
+
if (line.startsWith("@") && !revoked && !certAuthority) continue;
|
|
18
20
|
const fields = line.split(/\s+/);
|
|
19
21
|
for (let i = 0; i < fields.length - 1; i++) {
|
|
20
22
|
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 });
|
|
23
|
+
entries.push({ key: fields[i + 1], revoked, ...(certAuthority ? { certAuthority: true } : {}) });
|
|
22
24
|
break;
|
|
23
25
|
}
|
|
24
26
|
}
|
|
@@ -58,16 +60,23 @@ export async function loadKnownHostEntries(config: EffectiveSshConfig): Promise<
|
|
|
58
60
|
}
|
|
59
61
|
}
|
|
60
62
|
}
|
|
61
|
-
return [...new Map(entries.map((entry) => [`${entry.revoked}:${entry.key}`, entry])).values()];
|
|
63
|
+
return [...new Map(entries.map((entry) => [`${entry.revoked}:${entry.certAuthority}:${entry.key}`, entry])).values()];
|
|
62
64
|
}
|
|
63
65
|
|
|
64
66
|
export function verifyKnownHostKey(config: EffectiveSshConfig, entries: KnownHostEntry[], key: Buffer): void {
|
|
65
67
|
const encoded = key.toString("base64");
|
|
66
|
-
const matches = entries.filter((entry) => entry.key === encoded);
|
|
68
|
+
const matches = entries.filter((entry) => !entry.certAuthority && entry.key === encoded);
|
|
67
69
|
if (matches.some((entry) => entry.revoked)) {
|
|
68
70
|
throw new RemoteCallError("E_HOST_KEY_CHANGED", `The host key for ${config.alias} is revoked`);
|
|
69
71
|
}
|
|
70
72
|
if (matches.length > 0) return;
|
|
73
|
+
if (entries.some((entry) => entry.certAuthority)) {
|
|
74
|
+
throw new RemoteCallError(
|
|
75
|
+
"E_UNSUPPORTED_SSH_OPTION",
|
|
76
|
+
`${config.alias} uses a CA host certificate, which the ssh2 transport cannot verify during its handshake`,
|
|
77
|
+
"Use a plain verified host key for this alias; do not bypass host-key verification",
|
|
78
|
+
);
|
|
79
|
+
}
|
|
71
80
|
if (entries.length > 0) {
|
|
72
81
|
throw new RemoteCallError(
|
|
73
82
|
"E_HOST_KEY_CHANGED",
|
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/ssh-config.ts
CHANGED
|
@@ -125,9 +125,16 @@ export function parseSshG(alias: string, output: string): EffectiveSshConfig {
|
|
|
125
125
|
};
|
|
126
126
|
}
|
|
127
127
|
|
|
128
|
-
export async function resolveSshConfig(
|
|
128
|
+
export async function resolveSshConfig(
|
|
129
|
+
alias: string,
|
|
130
|
+
destination?: { host: string; user?: string; port?: number },
|
|
131
|
+
): Promise<EffectiveSshConfig> {
|
|
129
132
|
try {
|
|
130
|
-
const
|
|
133
|
+
const args = ["-G"];
|
|
134
|
+
if (destination?.user) args.push("-l", destination.user);
|
|
135
|
+
if (destination?.port !== undefined) args.push("-p", String(destination.port));
|
|
136
|
+
args.push(destination?.host ?? alias);
|
|
137
|
+
const { stdout } = await execFileAsync("ssh", args, {
|
|
131
138
|
timeout: 10_000,
|
|
132
139
|
windowsHide: true,
|
|
133
140
|
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 type { Duplex } from "node:stream";
|
|
4
5
|
import { Client, type ClientChannel, type ConnectConfig, 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";
|
|
8
|
+
import { ExitMarkerFilter } from "./exit-marker.ts";
|
|
7
9
|
import { loadKnownHostEntries, verifyKnownHostKey, type KnownHostEntry } from "./host-key.ts";
|
|
8
10
|
import type { PythonFileRequest } from "./python-files.ts";
|
|
9
11
|
import { PYTHON_HELPER_BYTES, PYTHON_HELPER_SHA256, PYTHON_HELPER_SOURCE, 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 {
|
|
@@ -38,7 +41,7 @@ type AuthAttempt =
|
|
|
38
41
|
| { kind: "agent"; agent: string; label: string }
|
|
39
42
|
| { kind: "privateKey"; privateKey: Buffer; label: string };
|
|
40
43
|
|
|
41
|
-
export function watchdogScript(command: string, cwd: string): string {
|
|
44
|
+
export function watchdogScript(command: string, cwd: string, completionMarker?: string): string {
|
|
42
45
|
return `set -m
|
|
43
46
|
${remoteCommandScript(`bash -c ${shellQuote(command)} </dev/null &`, cwd)}
|
|
44
47
|
command_pid=$!
|
|
@@ -54,7 +57,7 @@ wait "$command_pid"
|
|
|
54
57
|
status=$?
|
|
55
58
|
disown %2 2>/dev/null
|
|
56
59
|
kill "$watchdog_pid" 2>/dev/null
|
|
57
|
-
exit "$status"
|
|
60
|
+
${completionMarker ? `printf '\\n%s:%s\\n' ${shellQuote(completionMarker)} "$status" >&2\n` : ""}exit "$status"
|
|
58
61
|
`;
|
|
59
62
|
}
|
|
60
63
|
|
|
@@ -102,6 +105,7 @@ async function connectWithAttempt(
|
|
|
102
105
|
config: EffectiveSshConfig,
|
|
103
106
|
knownHosts: KnownHostEntry[],
|
|
104
107
|
attempt: AuthAttempt,
|
|
108
|
+
sock?: Duplex,
|
|
105
109
|
): Promise<Client> {
|
|
106
110
|
return new Promise((resolve, reject) => {
|
|
107
111
|
const client = new Client();
|
|
@@ -125,6 +129,7 @@ async function connectWithAttempt(
|
|
|
125
129
|
}
|
|
126
130
|
},
|
|
127
131
|
};
|
|
132
|
+
if (sock) options.sock = sock;
|
|
128
133
|
if (attempt.kind === "agent") options.agent = attempt.agent;
|
|
129
134
|
else options.privateKey = attempt.privateKey;
|
|
130
135
|
const onError = (error: Error) => {
|
|
@@ -157,6 +162,95 @@ async function authAttempts(config: EffectiveSshConfig): Promise<AuthAttempt[]>
|
|
|
157
162
|
return attempts;
|
|
158
163
|
}
|
|
159
164
|
|
|
165
|
+
export type SshConfigResolver = (specification: string) => Promise<EffectiveSshConfig>;
|
|
166
|
+
|
|
167
|
+
interface ClientTransport {
|
|
168
|
+
client: Client;
|
|
169
|
+
parents: Client[];
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function closeClients(clients: Client[]): void {
|
|
173
|
+
for (let index = clients.length - 1; index >= 0; index -= 1) clients[index].end();
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async function defaultJumpResolver(specification: string): Promise<EffectiveSshConfig> {
|
|
177
|
+
return resolveSshConfig(specification, parseProxyJumpDestination(specification));
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function forwardOut(client: Client, host: string, port: number): Promise<ClientChannel> {
|
|
181
|
+
return new Promise((resolve, reject) => {
|
|
182
|
+
client.forwardOut("127.0.0.1", 0, host, port, (error, channel) => (error ? reject(error) : resolve(channel)));
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function connectClient(
|
|
187
|
+
config: EffectiveSshConfig,
|
|
188
|
+
resolver: SshConfigResolver,
|
|
189
|
+
stack: string[] = [],
|
|
190
|
+
via?: () => Promise<Duplex>,
|
|
191
|
+
): Promise<ClientTransport> {
|
|
192
|
+
if (stack.includes(config.alias)) throw new RemoteCallError("E_SSH_CONFIG", `ProxyJump cycle detected at ${config.alias}`);
|
|
193
|
+
if (!via && config.proxyJump && config.proxyCommand) {
|
|
194
|
+
throw new RemoteCallError("E_SSH_CONFIG", `${config.alias} has both ProxyJump and ProxyCommand; use one proxy method`);
|
|
195
|
+
}
|
|
196
|
+
const parents: Client[] = [];
|
|
197
|
+
try {
|
|
198
|
+
// A socket supplied by an explicit ProxyJump list defines this hop's route.
|
|
199
|
+
// Do not apply the hop's own proxy configuration a second time.
|
|
200
|
+
let socketFactory = via;
|
|
201
|
+
if (!socketFactory && config.proxyJump) {
|
|
202
|
+
const specifications = config.proxyJump.split(",").map((value) => value.trim()).filter(Boolean);
|
|
203
|
+
if (specifications.length === 0) throw new RemoteCallError("E_SSH_CONFIG", `ProxyJump is empty for ${config.alias}`);
|
|
204
|
+
let previous: Client | undefined;
|
|
205
|
+
for (const specification of specifications) {
|
|
206
|
+
const jumpConfig = await resolver(specification);
|
|
207
|
+
const upstream = previous;
|
|
208
|
+
const nextVia = upstream ? () => forwardOut(upstream, jumpConfig.host, jumpConfig.port) : undefined;
|
|
209
|
+
const jump = await connectClient(jumpConfig, resolver, [...stack, config.alias], nextVia);
|
|
210
|
+
parents.push(...jump.parents, jump.client);
|
|
211
|
+
previous = jump.client;
|
|
212
|
+
}
|
|
213
|
+
if (!previous) throw new RemoteCallError("E_SSH_CONFIG", `ProxyJump is empty for ${config.alias}`);
|
|
214
|
+
const jump = previous;
|
|
215
|
+
socketFactory = () => forwardOut(jump, config.host, config.port);
|
|
216
|
+
} else if (!socketFactory && config.proxyCommand) {
|
|
217
|
+
socketFactory = async () => openProxyCommand(config);
|
|
218
|
+
}
|
|
219
|
+
const knownHosts = await loadKnownHostEntries(config);
|
|
220
|
+
if (knownHosts.some((entry) => entry.certAuthority) && !knownHosts.some((entry) => !entry.certAuthority)) {
|
|
221
|
+
throw new RemoteCallError(
|
|
222
|
+
"E_UNSUPPORTED_SSH_OPTION",
|
|
223
|
+
`${config.alias} uses CA host certificates, which the ssh2 transport cannot verify during its handshake`,
|
|
224
|
+
"Use a plain verified host key for this alias; do not bypass host-key verification",
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
const attempts = await authAttempts(config);
|
|
228
|
+
if (attempts.length === 0) {
|
|
229
|
+
throw new RemoteCallError("E_AUTH", `No local ssh-agent or readable private key found for ${config.alias}`, `Run: ssh ${config.alias}`);
|
|
230
|
+
}
|
|
231
|
+
let lastError: unknown;
|
|
232
|
+
for (const attempt of attempts) {
|
|
233
|
+
try {
|
|
234
|
+
const sock = socketFactory ? await socketFactory() : undefined;
|
|
235
|
+
const client = await connectWithAttempt(config, knownHosts, attempt, sock);
|
|
236
|
+
return { client, parents };
|
|
237
|
+
} catch (error) {
|
|
238
|
+
lastError = error;
|
|
239
|
+
if (error instanceof RemoteCallError && (error.code.startsWith("E_HOST_KEY") || error.code === "E_UNSUPPORTED_SSH_OPTION")) throw error;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
throw new RemoteCallError(
|
|
243
|
+
"E_AUTH",
|
|
244
|
+
`Non-interactive SSH authentication failed for ${config.alias}`,
|
|
245
|
+
`Make ssh ${config.alias} work without a password or passphrase, then retry. Last error: ${lastError instanceof Error ? lastError.message : String(lastError)}`,
|
|
246
|
+
{ cause: lastError },
|
|
247
|
+
);
|
|
248
|
+
} catch (error) {
|
|
249
|
+
closeClients(parents);
|
|
250
|
+
throw error;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
160
254
|
export class SshConnection {
|
|
161
255
|
readonly facts: RemoteHostFacts;
|
|
162
256
|
onClose?: () => void;
|
|
@@ -167,57 +261,35 @@ export class SshConnection {
|
|
|
167
261
|
readonly client: Client,
|
|
168
262
|
readonly sftp: SFTPWrapper,
|
|
169
263
|
facts: RemoteHostFacts,
|
|
264
|
+
readonly parentClients: Client[] = [],
|
|
170
265
|
) {
|
|
171
266
|
this.facts = facts;
|
|
172
267
|
client.on("error", () => undefined);
|
|
173
268
|
client.once("close", () => {
|
|
174
269
|
this.closed = true;
|
|
270
|
+
closeClients(parentClients);
|
|
175
271
|
this.onClose?.();
|
|
176
272
|
});
|
|
177
273
|
}
|
|
178
274
|
|
|
179
275
|
static async connect(alias: string): Promise<SshConnection> {
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
276
|
+
return this.connectResolved(await resolveSshConfig(alias), defaultJumpResolver);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
static async connectResolved(config: EffectiveSshConfig, resolver: SshConfigResolver = defaultJumpResolver): Promise<SshConnection> {
|
|
280
|
+
const { client, parents } = await connectClient(config, resolver);
|
|
281
|
+
try {
|
|
282
|
+
const sftp = await new Promise<SFTPWrapper>((resolve, reject) =>
|
|
283
|
+
client.sftp((error, value) => (error ? reject(error) : resolve(value))),
|
|
186
284
|
);
|
|
285
|
+
const home = await sftpRealpath(sftp, ".");
|
|
286
|
+
const facts = await probeHost(client, config.alias, home);
|
|
287
|
+
return new SshConnection(client, sftp, facts, parents);
|
|
288
|
+
} catch (error) {
|
|
289
|
+
client.end();
|
|
290
|
+
closeClients(parents);
|
|
291
|
+
throw asRemoteCallError(error, "E_CONNECT", `SSH connected to ${config.alias}, but SFTP/Bash initialization failed`);
|
|
187
292
|
}
|
|
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
293
|
}
|
|
222
294
|
|
|
223
295
|
get isOpen(): boolean {
|
|
@@ -261,11 +333,16 @@ export class SshConnection {
|
|
|
261
333
|
private async exec(
|
|
262
334
|
command: string,
|
|
263
335
|
cwd: string,
|
|
264
|
-
options: { onData: (data: Buffer) => void; onStderr?: (data: Buffer) => void; signal?: AbortSignal; timeout?: number },
|
|
265
|
-
): Promise<{ exitCode: number | null }> {
|
|
336
|
+
options: { onData: (data: Buffer) => void; onStderr?: (data: Buffer) => void; signal?: AbortSignal; timeout?: number; allowMissingExitStatus?: boolean },
|
|
337
|
+
): Promise<{ exitCode: number | null; missingExitStatus: boolean }> {
|
|
266
338
|
if (this.closed) throw new RemoteCallError("E_CLOSED", `SSH connection is closed for ${this.facts.alias}`);
|
|
267
339
|
if (options.signal?.aborted) throw new Error("Operation aborted");
|
|
268
|
-
const
|
|
340
|
+
const completionMarker = `pi-remote-call-exit-${randomBytes(12).toString("hex")}`;
|
|
341
|
+
const channel = await openChannel(this.client, `bash -c ${shellQuote(watchdogScript(command, cwd, completionMarker))}`);
|
|
342
|
+
const marker = new ExitMarkerFilter(completionMarker);
|
|
343
|
+
const forwardStderr = (data: Buffer) => {
|
|
344
|
+
if (data.length > 0) (options.onStderr ?? options.onData)(data);
|
|
345
|
+
};
|
|
269
346
|
let exitCode: number | null = null;
|
|
270
347
|
let exitSeen = false;
|
|
271
348
|
let timedOut = false;
|
|
@@ -286,7 +363,7 @@ export class SshConnection {
|
|
|
286
363
|
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
287
364
|
if (options.signal?.aborted) onAbort();
|
|
288
365
|
channel.stdout.on("data", options.onData);
|
|
289
|
-
channel.stderr.on("data",
|
|
366
|
+
channel.stderr.on("data", (data: Buffer) => forwardStderr(marker.push(data)));
|
|
290
367
|
channel.on("exit", (code: number | null) => {
|
|
291
368
|
exitSeen = true;
|
|
292
369
|
exitCode = typeof code === "number" ? code : null;
|
|
@@ -294,6 +371,7 @@ export class SshConnection {
|
|
|
294
371
|
return new Promise((resolve, reject) => {
|
|
295
372
|
channel.once("error", (error: Error) => {
|
|
296
373
|
if (settled) return;
|
|
374
|
+
forwardStderr(marker.finish());
|
|
297
375
|
settled = true;
|
|
298
376
|
if (timer) clearTimeout(timer);
|
|
299
377
|
if (forceTimer) clearTimeout(forceTimer);
|
|
@@ -302,14 +380,17 @@ export class SshConnection {
|
|
|
302
380
|
});
|
|
303
381
|
channel.once("close", () => {
|
|
304
382
|
if (settled) return;
|
|
383
|
+
forwardStderr(marker.finish());
|
|
305
384
|
settled = true;
|
|
306
385
|
if (timer) clearTimeout(timer);
|
|
307
386
|
if (forceTimer) clearTimeout(forceTimer);
|
|
308
387
|
options.signal?.removeEventListener("abort", onAbort);
|
|
309
388
|
if (options.signal?.aborted) reject(new Error("aborted"));
|
|
310
389
|
else if (timedOut) reject(new Error(`timeout:${options.timeout}`));
|
|
311
|
-
else if (!exitSeen
|
|
312
|
-
else resolve({ exitCode });
|
|
390
|
+
else if (!exitSeen && marker.status !== undefined) resolve({ exitCode: marker.status, missingExitStatus: false });
|
|
391
|
+
else if (!exitSeen && options.allowMissingExitStatus) resolve({ exitCode: null, missingExitStatus: true });
|
|
392
|
+
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`));
|
|
393
|
+
else resolve({ exitCode, missingExitStatus: false });
|
|
313
394
|
});
|
|
314
395
|
});
|
|
315
396
|
}
|
|
@@ -376,17 +457,19 @@ export class SshConnection {
|
|
|
376
457
|
? `${shellQuote(python.path)} ${shellQuote(helperPath)} ${shellQuote(requestPath)}`
|
|
377
458
|
: `${shellQuote(python.path)} -c ${shellQuote(PYTHON_HELPER_SOURCE)} ${shellQuote(requestPath)}`;
|
|
378
459
|
const command = `${helperCommand}; helper_status=$?; rm -f -- ${shellQuote(requestPath)}; exit "$helper_status"`;
|
|
379
|
-
const { exitCode } = await this.exec(command, this.facts.home, {
|
|
460
|
+
const { exitCode, missingExitStatus } = await this.exec(command, this.facts.home, {
|
|
380
461
|
onData: (data) => stdoutChunks.push(Buffer.from(data)),
|
|
381
462
|
onStderr: (data) => stderrChunks.push(Buffer.from(data)),
|
|
382
463
|
signal,
|
|
464
|
+
allowMissingExitStatus: true,
|
|
383
465
|
});
|
|
384
|
-
remoteCleanup =
|
|
466
|
+
remoteCleanup = !missingExitStatus;
|
|
385
467
|
return parsePythonHelperResponse(
|
|
386
468
|
this.facts.alias,
|
|
387
469
|
Buffer.concat(stdoutChunks).toString("utf8"),
|
|
388
470
|
Buffer.concat(stderrChunks).toString("utf8"),
|
|
389
471
|
exitCode,
|
|
472
|
+
missingExitStatus,
|
|
390
473
|
);
|
|
391
474
|
} finally {
|
|
392
475
|
if (requestCreated && !remoteCleanup) await sftpUnlink(this.sftp, requestPath).catch(() => undefined);
|
|
@@ -397,5 +480,6 @@ export class SshConnection {
|
|
|
397
480
|
if (this.closed) return;
|
|
398
481
|
this.closed = true;
|
|
399
482
|
this.client.end();
|
|
483
|
+
closeClients(this.parentClients);
|
|
400
484
|
}
|
|
401
485
|
}
|