pi-remote-call 0.3.0 → 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 +24 -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/sftp.ts +16 -0
- package/src/ssh-config.ts +9 -2
- package/src/transport.ts +141 -51
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,29 @@
|
|
|
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
|
+
|
|
16
|
+
## 0.3.1 - 2026-11-28
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
|
|
20
|
+
- Python helper requests now use exclusive direct writes (`wx`, mode `0600`), removing redundant request-file stat and rename round trips.
|
|
21
|
+
- Successful helper commands clean up their request file in the same remote command while preserving the helper exit status. Interrupted setup or execution retains best-effort SFTP cleanup.
|
|
22
|
+
|
|
23
|
+
### Performance
|
|
24
|
+
|
|
25
|
+
- Real SSH benchmarks measured 25–34% lower small-file cached-read p50 latency and 28–38% lower large-file ranged-read p50 latency.
|
|
26
|
+
|
|
3
27
|
## 0.3.0 - 2026-11-28
|
|
4
28
|
|
|
5
29
|
### Added
|
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/sftp.ts
CHANGED
|
@@ -80,6 +80,22 @@ async function sftpFsyncFile(sftp: SFTPWrapper, path: string): Promise<void> {
|
|
|
80
80
|
}
|
|
81
81
|
}
|
|
82
82
|
|
|
83
|
+
export async function sftpWriteNewFile(sftp: SFTPWrapper, path: string, content: string): Promise<void> {
|
|
84
|
+
let created = false;
|
|
85
|
+
try {
|
|
86
|
+
await new Promise<void>((resolve, reject) => {
|
|
87
|
+
const stream = sftp.createWriteStream(path, { flags: "wx", mode: 0o600 });
|
|
88
|
+
stream.once("open", () => (created = true));
|
|
89
|
+
stream.once("error", reject);
|
|
90
|
+
stream.once("close", resolve);
|
|
91
|
+
stream.end(content, "utf8");
|
|
92
|
+
});
|
|
93
|
+
} catch (error) {
|
|
94
|
+
if (created) await sftpUnlink(sftp, path).catch(() => undefined);
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
83
99
|
export async function sftpWriteFileAtomic(sftp: SFTPWrapper, path: string, content: string, durable = false): Promise<void> {
|
|
84
100
|
const stats = await sftpStat(sftp, path).catch(() => undefined);
|
|
85
101
|
const temporary = posix.join(
|
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 {
|
|
@@ -20,6 +23,7 @@ import {
|
|
|
20
23
|
sftpSetStat,
|
|
21
24
|
sftpUnlink,
|
|
22
25
|
sftpWriteFileAtomic,
|
|
26
|
+
sftpWriteNewFile,
|
|
23
27
|
} from "./sftp.ts";
|
|
24
28
|
|
|
25
29
|
export interface RemoteHostFacts {
|
|
@@ -37,7 +41,7 @@ type AuthAttempt =
|
|
|
37
41
|
| { kind: "agent"; agent: string; label: string }
|
|
38
42
|
| { kind: "privateKey"; privateKey: Buffer; label: string };
|
|
39
43
|
|
|
40
|
-
export function watchdogScript(command: string, cwd: string): string {
|
|
44
|
+
export function watchdogScript(command: string, cwd: string, completionMarker?: string): string {
|
|
41
45
|
return `set -m
|
|
42
46
|
${remoteCommandScript(`bash -c ${shellQuote(command)} </dev/null &`, cwd)}
|
|
43
47
|
command_pid=$!
|
|
@@ -53,7 +57,7 @@ wait "$command_pid"
|
|
|
53
57
|
status=$?
|
|
54
58
|
disown %2 2>/dev/null
|
|
55
59
|
kill "$watchdog_pid" 2>/dev/null
|
|
56
|
-
exit "$status"
|
|
60
|
+
${completionMarker ? `printf '\\n%s:%s\\n' ${shellQuote(completionMarker)} "$status" >&2\n` : ""}exit "$status"
|
|
57
61
|
`;
|
|
58
62
|
}
|
|
59
63
|
|
|
@@ -101,6 +105,7 @@ async function connectWithAttempt(
|
|
|
101
105
|
config: EffectiveSshConfig,
|
|
102
106
|
knownHosts: KnownHostEntry[],
|
|
103
107
|
attempt: AuthAttempt,
|
|
108
|
+
sock?: Duplex,
|
|
104
109
|
): Promise<Client> {
|
|
105
110
|
return new Promise((resolve, reject) => {
|
|
106
111
|
const client = new Client();
|
|
@@ -124,6 +129,7 @@ async function connectWithAttempt(
|
|
|
124
129
|
}
|
|
125
130
|
},
|
|
126
131
|
};
|
|
132
|
+
if (sock) options.sock = sock;
|
|
127
133
|
if (attempt.kind === "agent") options.agent = attempt.agent;
|
|
128
134
|
else options.privateKey = attempt.privateKey;
|
|
129
135
|
const onError = (error: Error) => {
|
|
@@ -156,6 +162,95 @@ async function authAttempts(config: EffectiveSshConfig): Promise<AuthAttempt[]>
|
|
|
156
162
|
return attempts;
|
|
157
163
|
}
|
|
158
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
|
+
|
|
159
254
|
export class SshConnection {
|
|
160
255
|
readonly facts: RemoteHostFacts;
|
|
161
256
|
onClose?: () => void;
|
|
@@ -166,57 +261,35 @@ export class SshConnection {
|
|
|
166
261
|
readonly client: Client,
|
|
167
262
|
readonly sftp: SFTPWrapper,
|
|
168
263
|
facts: RemoteHostFacts,
|
|
264
|
+
readonly parentClients: Client[] = [],
|
|
169
265
|
) {
|
|
170
266
|
this.facts = facts;
|
|
171
267
|
client.on("error", () => undefined);
|
|
172
268
|
client.once("close", () => {
|
|
173
269
|
this.closed = true;
|
|
270
|
+
closeClients(parentClients);
|
|
174
271
|
this.onClose?.();
|
|
175
272
|
});
|
|
176
273
|
}
|
|
177
274
|
|
|
178
275
|
static async connect(alias: string): Promise<SshConnection> {
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
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))),
|
|
185
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`);
|
|
186
292
|
}
|
|
187
|
-
const knownHosts = await loadKnownHostEntries(config);
|
|
188
|
-
const attempts = await authAttempts(config);
|
|
189
|
-
if (attempts.length === 0) {
|
|
190
|
-
throw new RemoteCallError("E_AUTH", `No local ssh-agent or readable private key found for ${alias}`, `Run: ssh ${alias}`);
|
|
191
|
-
}
|
|
192
|
-
let lastError: unknown;
|
|
193
|
-
for (const attempt of attempts) {
|
|
194
|
-
let client: Client;
|
|
195
|
-
try {
|
|
196
|
-
client = await connectWithAttempt(config, knownHosts, attempt);
|
|
197
|
-
} catch (error) {
|
|
198
|
-
lastError = error;
|
|
199
|
-
if (error instanceof RemoteCallError && error.code.startsWith("E_HOST_KEY")) throw error;
|
|
200
|
-
continue;
|
|
201
|
-
}
|
|
202
|
-
try {
|
|
203
|
-
const sftp = await new Promise<SFTPWrapper>((resolve, reject) =>
|
|
204
|
-
client.sftp((error, value) => (error ? reject(error) : resolve(value))),
|
|
205
|
-
);
|
|
206
|
-
const home = await sftpRealpath(sftp, ".");
|
|
207
|
-
const facts = await probeHost(client, alias, home);
|
|
208
|
-
return new SshConnection(client, sftp, facts);
|
|
209
|
-
} catch (error) {
|
|
210
|
-
client.end();
|
|
211
|
-
throw asRemoteCallError(error, "E_CONNECT", `SSH connected to ${alias}, but SFTP/Bash initialization failed`);
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
throw new RemoteCallError(
|
|
215
|
-
"E_AUTH",
|
|
216
|
-
`Non-interactive SSH authentication failed for ${alias}`,
|
|
217
|
-
`Make ssh ${alias} work without a password or passphrase, then retry. Last error: ${lastError instanceof Error ? lastError.message : String(lastError)}`,
|
|
218
|
-
{ cause: lastError },
|
|
219
|
-
);
|
|
220
293
|
}
|
|
221
294
|
|
|
222
295
|
get isOpen(): boolean {
|
|
@@ -260,11 +333,16 @@ export class SshConnection {
|
|
|
260
333
|
private async exec(
|
|
261
334
|
command: string,
|
|
262
335
|
cwd: string,
|
|
263
|
-
options: { onData: (data: Buffer) => void; onStderr?: (data: Buffer) => void; signal?: AbortSignal; timeout?: number },
|
|
264
|
-
): 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 }> {
|
|
265
338
|
if (this.closed) throw new RemoteCallError("E_CLOSED", `SSH connection is closed for ${this.facts.alias}`);
|
|
266
339
|
if (options.signal?.aborted) throw new Error("Operation aborted");
|
|
267
|
-
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
|
+
};
|
|
268
346
|
let exitCode: number | null = null;
|
|
269
347
|
let exitSeen = false;
|
|
270
348
|
let timedOut = false;
|
|
@@ -285,7 +363,7 @@ export class SshConnection {
|
|
|
285
363
|
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
286
364
|
if (options.signal?.aborted) onAbort();
|
|
287
365
|
channel.stdout.on("data", options.onData);
|
|
288
|
-
channel.stderr.on("data",
|
|
366
|
+
channel.stderr.on("data", (data: Buffer) => forwardStderr(marker.push(data)));
|
|
289
367
|
channel.on("exit", (code: number | null) => {
|
|
290
368
|
exitSeen = true;
|
|
291
369
|
exitCode = typeof code === "number" ? code : null;
|
|
@@ -293,6 +371,7 @@ export class SshConnection {
|
|
|
293
371
|
return new Promise((resolve, reject) => {
|
|
294
372
|
channel.once("error", (error: Error) => {
|
|
295
373
|
if (settled) return;
|
|
374
|
+
forwardStderr(marker.finish());
|
|
296
375
|
settled = true;
|
|
297
376
|
if (timer) clearTimeout(timer);
|
|
298
377
|
if (forceTimer) clearTimeout(forceTimer);
|
|
@@ -301,14 +380,17 @@ export class SshConnection {
|
|
|
301
380
|
});
|
|
302
381
|
channel.once("close", () => {
|
|
303
382
|
if (settled) return;
|
|
383
|
+
forwardStderr(marker.finish());
|
|
304
384
|
settled = true;
|
|
305
385
|
if (timer) clearTimeout(timer);
|
|
306
386
|
if (forceTimer) clearTimeout(forceTimer);
|
|
307
387
|
options.signal?.removeEventListener("abort", onAbort);
|
|
308
388
|
if (options.signal?.aborted) reject(new Error("aborted"));
|
|
309
389
|
else if (timedOut) reject(new Error(`timeout:${options.timeout}`));
|
|
310
|
-
else if (!exitSeen
|
|
311
|
-
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 });
|
|
312
394
|
});
|
|
313
395
|
});
|
|
314
396
|
}
|
|
@@ -363,27 +445,34 @@ export class SshConnection {
|
|
|
363
445
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
364
446
|
const helperPath = await this.preparePythonHelper();
|
|
365
447
|
const requestPath = posix.join("/tmp", `pi-remote-call-${process.pid}-${randomBytes(12).toString("hex")}.json`);
|
|
448
|
+
let requestCreated = false;
|
|
449
|
+
let remoteCleanup = false;
|
|
366
450
|
try {
|
|
367
|
-
await
|
|
451
|
+
await sftpWriteNewFile(this.sftp, requestPath, JSON.stringify(request));
|
|
452
|
+
requestCreated = true;
|
|
368
453
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
369
454
|
const stdoutChunks: Buffer[] = [];
|
|
370
455
|
const stderrChunks: Buffer[] = [];
|
|
371
|
-
const
|
|
456
|
+
const helperCommand = helperPath
|
|
372
457
|
? `${shellQuote(python.path)} ${shellQuote(helperPath)} ${shellQuote(requestPath)}`
|
|
373
458
|
: `${shellQuote(python.path)} -c ${shellQuote(PYTHON_HELPER_SOURCE)} ${shellQuote(requestPath)}`;
|
|
374
|
-
const
|
|
459
|
+
const command = `${helperCommand}; helper_status=$?; rm -f -- ${shellQuote(requestPath)}; exit "$helper_status"`;
|
|
460
|
+
const { exitCode, missingExitStatus } = await this.exec(command, this.facts.home, {
|
|
375
461
|
onData: (data) => stdoutChunks.push(Buffer.from(data)),
|
|
376
462
|
onStderr: (data) => stderrChunks.push(Buffer.from(data)),
|
|
377
463
|
signal,
|
|
464
|
+
allowMissingExitStatus: true,
|
|
378
465
|
});
|
|
466
|
+
remoteCleanup = !missingExitStatus;
|
|
379
467
|
return parsePythonHelperResponse(
|
|
380
468
|
this.facts.alias,
|
|
381
469
|
Buffer.concat(stdoutChunks).toString("utf8"),
|
|
382
470
|
Buffer.concat(stderrChunks).toString("utf8"),
|
|
383
471
|
exitCode,
|
|
472
|
+
missingExitStatus,
|
|
384
473
|
);
|
|
385
474
|
} finally {
|
|
386
|
-
await sftpUnlink(this.sftp, requestPath).catch(() => undefined);
|
|
475
|
+
if (requestCreated && !remoteCleanup) await sftpUnlink(this.sftp, requestPath).catch(() => undefined);
|
|
387
476
|
}
|
|
388
477
|
}
|
|
389
478
|
|
|
@@ -391,5 +480,6 @@ export class SshConnection {
|
|
|
391
480
|
if (this.closed) return;
|
|
392
481
|
this.closed = true;
|
|
393
482
|
this.client.end();
|
|
483
|
+
closeClients(this.parentClients);
|
|
394
484
|
}
|
|
395
485
|
}
|