dsh-remote-go 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/README.md +1 -0
- package/dist/client.js +1348 -2095
- package/dist/src/admission.js +3 -28
- package/dist/src/api.js +37 -99
- package/dist/src/atomic-json.js +32 -66
- package/dist/src/bootstrap.js +17 -27
- package/dist/src/connect/attach.js +3 -25
- package/dist/src/connect/bootstrap.js +2 -8
- package/dist/src/connect/failures.js +3 -18
- package/dist/src/connect/guards.js +13 -8
- package/dist/src/connect/launch.js +11 -21
- package/dist/src/connect/links.js +11 -27
- package/dist/src/connect/ownership.js +33 -114
- package/dist/src/connect/pipeline.js +62 -159
- package/dist/src/connect/reattach.js +26 -44
- package/dist/src/connect/registry.js +0 -1
- package/dist/src/connect/repair.js +8 -37
- package/dist/src/connect/restart.js +36 -97
- package/dist/src/connect/stop.js +16 -50
- package/dist/src/connect/transport.js +10 -18
- package/dist/src/connect/verify.js +3 -12
- package/dist/src/connect/watchdog.js +6 -38
- package/dist/src/connect-log.js +16 -41
- package/dist/src/connect-progress.js +13 -45
- package/dist/src/constants.js +18 -43
- package/dist/src/context.js +13 -32
- package/dist/src/diagnostics.js +56 -25
- package/dist/src/download-jobs.js +11 -20
- package/dist/src/errors.js +175 -190
- package/dist/src/events.js +20 -84
- package/dist/src/host-lifecycle.js +69 -177
- package/dist/src/host-registry.js +27 -78
- package/dist/src/host-runtime.js +0 -9
- package/dist/src/host-view.js +6 -29
- package/dist/src/index.js +15 -35
- package/dist/src/kernel-adapter.js +34 -80
- package/dist/src/key-files.js +10 -23
- package/dist/src/known-hosts.js +13 -34
- package/dist/src/layout.js +3 -20
- package/dist/src/local-download.js +94 -163
- package/dist/src/local-ssh.js +12 -19
- package/dist/src/local-version.js +35 -49
- package/dist/src/node/download.js +1 -4
- package/dist/src/node-runtime.js +19 -38
- package/dist/src/probe.js +6 -7
- package/dist/src/prompts.js +56 -128
- package/dist/src/proxy/cookies.js +26 -60
- package/dist/src/proxy/headers.js +30 -125
- package/dist/src/proxy/http.js +33 -41
- package/dist/src/proxy/index.js +20 -34
- package/dist/src/proxy/limits.js +4 -6
- package/dist/src/proxy/routes.js +10 -17
- package/dist/src/proxy/upgrade.js +27 -42
- package/dist/src/redact.js +14 -33
- package/dist/src/remote-files.js +9 -21
- package/dist/src/remote-path.js +21 -62
- package/dist/src/remote-proc.js +35 -103
- package/dist/src/remote-web/registry.js +10 -50
- package/dist/src/remote-web/resolve.js +23 -104
- package/dist/src/remote-web/start.js +27 -64
- package/dist/src/remote-web/stop.js +6 -25
- package/dist/src/request-trust.js +15 -32
- package/dist/src/runtime/dispatch.js +33 -143
- package/dist/src/runtime/effects.js +7 -17
- package/dist/src/runtime/events.js +1 -1
- package/dist/src/runtime/fsm.js +11 -61
- package/dist/src/runtime/rules.js +121 -199
- package/dist/src/secrets.js +15 -38
- package/dist/src/service.js +22 -128
- package/dist/src/settings.js +41 -42
- package/dist/src/ssh-config.js +22 -41
- package/dist/src/ssh-failures.js +23 -74
- package/dist/src/ssh-sftp.js +47 -86
- package/dist/src/ssh.js +99 -179
- package/dist/src/store.js +31 -48
- package/dist/src/tool-shared.js +17 -52
- package/dist/src/tools-exec-policy.js +33 -79
- package/dist/src/tools-exec.js +87 -151
- package/dist/src/tools-report.js +100 -167
- package/dist/src/tools.js +59 -133
- package/dist/src/tunnel.js +9 -27
- package/dist/src/util.js +19 -56
- package/dist/src/version.js +6 -12
- package/dist/src/watchdog-bus.js +0 -8
- package/dist/src/watchdog.js +7 -47
- package/package.json +3 -3
package/dist/src/ssh.js
CHANGED
|
@@ -1,20 +1,12 @@
|
|
|
1
|
-
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
* `SshConnection` is the only class in `src/` that talks to `vendor/ssh2.bundle.cjs`; every other
|
|
5
|
-
* module depends on `src/ssh-port.ts`. The class name and its constructor are frozen until P7
|
|
6
|
-
* because four integration suites construct it directly against a real (simulated) SSH server.
|
|
7
|
-
*
|
|
8
|
-
* What lives here is the transport itself: auth-candidate fallback, the five-step host-key
|
|
9
|
-
* decision, the handshake lifecycle (including "emit `close` before rejecting during a
|
|
10
|
-
* handshake"), `exec`, `forwardOut` and `dispose`. Two concerns moved out without changing a call
|
|
11
|
-
* site: the SFTP capability (`ssh-sftp.ts`) and the failure classification (`ssh-failures.ts`).
|
|
12
|
-
*/
|
|
1
|
+
/** The ssh2 adapter for `SshPort`, the only class here that talks to `vendor/ssh2.bundle.cjs`; its name and constructor
|
|
2
|
+
* are frozen (four integration suites build it directly). It owns auth fallback, the host-key decision, the handshake
|
|
3
|
+
* lifecycle, `exec`/`forwardOut`/`dispose`; SFTP and failure classification live in the two sibling modules. */
|
|
13
4
|
import { EventEmitter } from 'node:events';
|
|
14
5
|
import { open } from 'node:fs/promises';
|
|
15
6
|
import { homedir } from 'node:os';
|
|
16
7
|
import path from 'node:path';
|
|
17
8
|
import ssh2 from '../vendor/ssh2.bundle.cjs';
|
|
9
|
+
import { SSH_KEEPALIVE_COUNT_MAX, SSH_KEEPALIVE_INTERVAL_MS } from './constants.js';
|
|
18
10
|
import { errors } from './errors.js';
|
|
19
11
|
import { fingerprintFromBlob } from './known-hosts.js';
|
|
20
12
|
import { classifySshFailure, closedError, isHostKeyError } from './ssh-failures.js';
|
|
@@ -22,7 +14,7 @@ import { DEFAULT_EXEC_MAX_BYTES, DEFAULT_EXEC_TIMEOUT_MS, } from './ssh-port.js'
|
|
|
22
14
|
import { endSftp, inspectSftpPath, openSftpSession, saveSftpFile, saveSftpTree } from './ssh-sftp.js';
|
|
23
15
|
import { expandHome } from './util.js';
|
|
24
16
|
const { Client } = ssh2;
|
|
25
|
-
/** Settle a promise at most once
|
|
17
|
+
/** Settle a promise at most once (later calls are ignored), so callers need no flag. */
|
|
26
18
|
function oneShot(resolve, reject, cleanup) {
|
|
27
19
|
let settled = false;
|
|
28
20
|
return (error, value) => {
|
|
@@ -30,12 +22,8 @@ function oneShot(resolve, reject, cleanup) {
|
|
|
30
22
|
return;
|
|
31
23
|
settled = true;
|
|
32
24
|
cleanup?.();
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
// The settled-once contract passes exactly one of error/value, so the success branch
|
|
36
|
-
// always carries the value this `as` restates (the optional parameter cannot express it).
|
|
37
|
-
else
|
|
38
|
-
resolve(value);
|
|
25
|
+
// The settled-once contract passes exactly one of error/value, so the success branch carries it.
|
|
26
|
+
error ? reject(error) : resolve(value);
|
|
39
27
|
};
|
|
40
28
|
}
|
|
41
29
|
export function parseSshKeyType(blob) {
|
|
@@ -52,14 +40,15 @@ export function parseSshKeyType(blob) {
|
|
|
52
40
|
return 'unknown';
|
|
53
41
|
}
|
|
54
42
|
}
|
|
55
|
-
/**
|
|
56
|
-
* The ssh2 implementation of `SshPort`.
|
|
57
|
-
*
|
|
58
|
-
* Every failure it produces is a `RemoteGoError` (through `classifySshFailure` / `closedError`),
|
|
59
|
-
* and the SFTP capabilities are declared, so `typeof port.saveRemoteFile === 'function'` is how a
|
|
60
|
-
* caller tells them from a transport that cannot download.
|
|
61
|
-
*/
|
|
43
|
+
/** The ssh2 implementation of `SshPort`: every failure is a `RemoteGoError`, and the download members are declared. */
|
|
62
44
|
export class SshConnection extends EventEmitter {
|
|
45
|
+
client = null;
|
|
46
|
+
fingerprint = null;
|
|
47
|
+
keyType = null;
|
|
48
|
+
closed = false;
|
|
49
|
+
disposed = false;
|
|
50
|
+
hostKeyDecision = null;
|
|
51
|
+
clientFactory = () => new Client();
|
|
63
52
|
constructor(options) {
|
|
64
53
|
super();
|
|
65
54
|
this.options = {
|
|
@@ -68,23 +57,16 @@ export class SshConnection extends EventEmitter {
|
|
|
68
57
|
pinnedFingerprint: null,
|
|
69
58
|
knownHostFingerprints: [],
|
|
70
59
|
readyTimeoutMs: 20_000,
|
|
71
|
-
keepaliveIntervalMs:
|
|
60
|
+
keepaliveIntervalMs: SSH_KEEPALIVE_INTERVAL_MS,
|
|
61
|
+
keepaliveCountMax: SSH_KEEPALIVE_COUNT_MAX,
|
|
72
62
|
home: homedir(),
|
|
73
63
|
...options,
|
|
74
64
|
identityFiles: options.identityFiles ?? [],
|
|
75
65
|
};
|
|
76
|
-
|
|
77
|
-
this.fingerprint = null;
|
|
78
|
-
this.keyType = null;
|
|
79
|
-
this.closed = false;
|
|
80
|
-
this.disposed = false;
|
|
81
|
-
this.hostKeyDecision = null;
|
|
82
|
-
// ssh2 clients emit `error` for every failed auth attempt and again while
|
|
83
|
-
// tearing down. EventEmitter treats an unhandled `error` as a thrown
|
|
84
|
-
// exception, which would take down the whole DSH host process; keep a
|
|
85
|
-
// permanent safety listener so failures stay inside this connection.
|
|
66
|
+
// ssh2 emits `error` on every failed auth attempt and while tearing down; unhandled, it would kill the Host.
|
|
86
67
|
this.on('error', () => { });
|
|
87
|
-
|
|
68
|
+
if (typeof options.clientFactory === 'function')
|
|
69
|
+
this.clientFactory = options.clientFactory;
|
|
88
70
|
}
|
|
89
71
|
get connected() {
|
|
90
72
|
return this.client !== null && !this.closed;
|
|
@@ -103,9 +85,7 @@ export class SshConnection extends EventEmitter {
|
|
|
103
85
|
for (const candidate of candidates) {
|
|
104
86
|
try {
|
|
105
87
|
const info = await this.connectOnce(candidate);
|
|
106
|
-
this.client?.on('error', (error) =>
|
|
107
|
-
this.emit('error', error);
|
|
108
|
-
});
|
|
88
|
+
this.client?.on('error', (error) => this.emit('error', error));
|
|
109
89
|
return info;
|
|
110
90
|
}
|
|
111
91
|
catch (error) {
|
|
@@ -122,48 +102,34 @@ export class SshConnection extends EventEmitter {
|
|
|
122
102
|
return new Promise((resolve, reject) => {
|
|
123
103
|
const settle = oneShot(resolve, reject);
|
|
124
104
|
const client = this.clientFactory();
|
|
105
|
+
const endpoint = { host: this.options.host, port: this.options.port };
|
|
125
106
|
this.client = client;
|
|
126
|
-
// A rejected
|
|
127
|
-
//
|
|
128
|
-
// fresh client, so it must clear the flag again; otherwise a successful
|
|
129
|
-
// fallback (agent -> key on a machine without an SSH agent) would report
|
|
130
|
-
// `connected === false` and every later `exec`/`forwardOut` would throw
|
|
131
|
-
// "SSH connection is not open" on a transport that is actually up.
|
|
107
|
+
// A rejected candidate was torn down by `cleanupClient()`, marking this closed; the new attempt owns a fresh
|
|
108
|
+
// client, so the flag must clear or a working fallback would report "not open".
|
|
132
109
|
this.closed = false;
|
|
133
|
-
// An attempt that
|
|
134
|
-
//
|
|
135
|
-
// connection that never existed - not a lost link. Without this flag the wrapper would
|
|
136
|
-
// emit `close`, the pipeline would read a transport drop and retry a first connection
|
|
137
|
-
// that never got off the ground (review: close-after-error).
|
|
110
|
+
// An attempt that already failed tears itself down (error+close in one tick): without this flag that close
|
|
111
|
+
// would look like a dropped link, and a first connection that never started would be retried as one.
|
|
138
112
|
let attemptFailed = false;
|
|
139
|
-
// Attach the close handling *before* dialling: a transport that dies during the
|
|
140
|
-
//
|
|
141
|
-
//
|
|
142
|
-
// !== client` filters a superseded auth attempt, whose teardown is not a lost link.
|
|
113
|
+
// Attach the close handling *before* dialling: a transport that dies during the handshake (while a host-key
|
|
114
|
+
// prompt is open) must reject the connect promise, and `this.client !== client` filters a superseded attempt,
|
|
115
|
+
// whose teardown is not a lost link.
|
|
143
116
|
client.once('close', () => {
|
|
144
|
-
if (attemptFailed)
|
|
145
|
-
return;
|
|
146
|
-
if (this.client !== client)
|
|
117
|
+
if (attemptFailed || this.client !== client)
|
|
147
118
|
return;
|
|
148
119
|
this.closed = true;
|
|
149
|
-
//
|
|
150
|
-
// event arriving for a handshake that died while a host-key prompt was parked.
|
|
120
|
+
// Emit before rejecting: connect-pipeline's watchers rely on the event for a parked prompt.
|
|
151
121
|
this.emit('close');
|
|
152
|
-
settle(classifySshFailure(new Error('the connection closed during the SSH handshake'),
|
|
153
|
-
host: this.options.host,
|
|
154
|
-
port: this.options.port,
|
|
155
|
-
}));
|
|
122
|
+
settle(classifySshFailure(new Error('the connection closed during the SSH handshake'), endpoint));
|
|
156
123
|
});
|
|
157
124
|
client.once('ready', () => {
|
|
158
125
|
const info = { fingerprint: this.fingerprint ?? '', keyType: this.keyType ?? '' };
|
|
159
126
|
this.emit('ready', info);
|
|
160
127
|
settle(null, info);
|
|
161
128
|
});
|
|
162
|
-
//
|
|
163
|
-
// later teardown errors (they are already reflected in the rejection).
|
|
129
|
+
// Settle on the first error and swallow any later teardown errors.
|
|
164
130
|
client.on('error', (error) => {
|
|
165
131
|
attemptFailed = true;
|
|
166
|
-
settle(classifySshFailure(error,
|
|
132
|
+
settle(classifySshFailure(error, endpoint));
|
|
167
133
|
});
|
|
168
134
|
const config = {
|
|
169
135
|
host: this.options.host,
|
|
@@ -171,13 +137,13 @@ export class SshConnection extends EventEmitter {
|
|
|
171
137
|
username: this.options.username ?? undefined,
|
|
172
138
|
readyTimeout: this.options.readyTimeoutMs,
|
|
173
139
|
keepaliveInterval: this.options.keepaliveIntervalMs,
|
|
174
|
-
keepaliveCountMax:
|
|
140
|
+
keepaliveCountMax: this.options.keepaliveCountMax,
|
|
175
141
|
tryKeyboard: false,
|
|
176
142
|
...(this.options.sock ? { sock: this.options.sock } : {}),
|
|
177
143
|
...authConfig,
|
|
178
144
|
hostVerifier: (keyBlob, verify) => {
|
|
179
145
|
this.verifyHostKey(keyBlob)
|
|
180
|
-
.then(
|
|
146
|
+
.then(verify)
|
|
181
147
|
.catch(() => verify(false));
|
|
182
148
|
},
|
|
183
149
|
};
|
|
@@ -186,15 +152,13 @@ export class SshConnection extends EventEmitter {
|
|
|
186
152
|
}
|
|
187
153
|
catch (error) {
|
|
188
154
|
attemptFailed = true;
|
|
189
|
-
settle(classifySshFailure(error,
|
|
155
|
+
settle(classifySshFailure(error, endpoint));
|
|
190
156
|
}
|
|
191
157
|
});
|
|
192
158
|
}
|
|
193
|
-
/**
|
|
194
|
-
*
|
|
195
|
-
*
|
|
196
|
-
* @internal exercised directly by `test/unit/ssh.test.js`; not part of `SshPort`.
|
|
197
|
-
*/
|
|
159
|
+
/** The five-level host-key decision: pin → known_hosts → acceptUnknown → a decision in flight → policy (strict or
|
|
160
|
+
* ask) → refuse. Emits `hostkey-*` as it goes.
|
|
161
|
+
* @internal exercised directly by `test/unit/ssh.test.js`; not part of `SshPort`. */
|
|
198
162
|
async verifyHostKey(keyBlob) {
|
|
199
163
|
const sha256 = fingerprintFromBlob(keyBlob);
|
|
200
164
|
const keyType = parseSshKeyType(keyBlob);
|
|
@@ -221,11 +185,8 @@ export class SshConnection extends EventEmitter {
|
|
|
221
185
|
}
|
|
222
186
|
if (this.hostKeyDecision)
|
|
223
187
|
return this.hostKeyDecision;
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
}
|
|
227
|
-
if (typeof this.options.onHostKey !== 'function') {
|
|
228
|
-
// No UI attached (tests/automation): refuse rather than silently trust.
|
|
188
|
+
// A strict policy, or no UI attached (tests/automation): refuse rather than silently trust.
|
|
189
|
+
if (this.options.hostKeyPolicy === 'strict' || typeof this.options.onHostKey !== 'function') {
|
|
229
190
|
throw errors.hostKeyUnknown(sha256);
|
|
230
191
|
}
|
|
231
192
|
this.emit('hostkey-pending', info);
|
|
@@ -235,29 +196,22 @@ export class SshConnection extends EventEmitter {
|
|
|
235
196
|
throw errors.hostKeyUnknown(sha256);
|
|
236
197
|
return true;
|
|
237
198
|
}
|
|
238
|
-
/**
|
|
239
|
-
*
|
|
240
|
-
*
|
|
241
|
-
* @internal exercised directly by `test/unit/ssh.test.js`; not part of `SshPort`.
|
|
242
|
-
*/
|
|
199
|
+
/** The candidate list: a password when one is set, otherwise key files only — deliberately no agent candidate. The
|
|
200
|
+
* configured path wins; the conventional names follow, so a host added with the default key path still connects.
|
|
201
|
+
* @internal exercised directly by `test/unit/ssh.test.js`; not part of `SshPort`. */
|
|
243
202
|
async resolveAuthCandidates() {
|
|
244
203
|
const auth = this.options.auth ?? { type: 'key' };
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
out.push({ password: auth.password, tryKeyboard: true });
|
|
249
|
-
return out;
|
|
250
|
-
}
|
|
251
|
-
// Key-file authentication only: there is deliberately no agent candidate. The
|
|
252
|
-
// configured path wins; when it is missing or unset the conventional names are
|
|
253
|
-
// tried, so a host added with the default key path still connects.
|
|
204
|
+
if (auth.type === 'password')
|
|
205
|
+
return auth.password ? [{ password: auth.password, tryKeyboard: true }] : [];
|
|
206
|
+
const sshDir = path.join(this.options.home, '.ssh');
|
|
254
207
|
const keyPaths = [
|
|
255
208
|
...(auth.keyPath ? [expandHome(auth.keyPath, this.options.home)] : []),
|
|
256
209
|
...(this.options.identityFiles ?? []),
|
|
257
|
-
path.join(
|
|
258
|
-
path.join(
|
|
259
|
-
path.join(
|
|
210
|
+
path.join(sshDir, 'id_ed25519'),
|
|
211
|
+
path.join(sshDir, 'id_rsa'),
|
|
212
|
+
path.join(sshDir, 'id_ecdsa'),
|
|
260
213
|
];
|
|
214
|
+
const out = [];
|
|
261
215
|
const seen = new Set();
|
|
262
216
|
for (const keyPath of keyPaths) {
|
|
263
217
|
if (!keyPath)
|
|
@@ -280,18 +234,27 @@ export class SshConnection extends EventEmitter {
|
|
|
280
234
|
reject(closedError());
|
|
281
235
|
return;
|
|
282
236
|
}
|
|
283
|
-
let timedOut = false;
|
|
284
237
|
let timer = null;
|
|
285
|
-
const
|
|
238
|
+
const result = { code: null, signal: null, stdout: '', stderr: '', timedOut: false };
|
|
286
239
|
const finish = oneShot(resolve, reject, () => {
|
|
287
240
|
if (timer)
|
|
288
241
|
clearTimeout(timer);
|
|
289
242
|
options.signal?.removeEventListener?.('abort', onAbort);
|
|
290
243
|
});
|
|
291
|
-
const onAbort = () =>
|
|
292
|
-
finish(new Error('aborted'));
|
|
293
|
-
};
|
|
244
|
+
const onAbort = () => finish(new Error('aborted'));
|
|
294
245
|
options.signal?.addEventListener?.('abort', onAbort, { once: true });
|
|
246
|
+
// `maxBytes` truncation is silent by contract: no error, no flag, the excess is dropped.
|
|
247
|
+
const collect = (target, text, listener) => {
|
|
248
|
+
if (result[target].length >= maxBytes)
|
|
249
|
+
return;
|
|
250
|
+
result[target] += text;
|
|
251
|
+
try {
|
|
252
|
+
listener?.(text);
|
|
253
|
+
}
|
|
254
|
+
catch {
|
|
255
|
+
// swallow-ok: stream listeners must not break the command
|
|
256
|
+
}
|
|
257
|
+
};
|
|
295
258
|
this.client.exec(command, { env: options.env }, (error, stream) => {
|
|
296
259
|
if (error) {
|
|
297
260
|
finish(error);
|
|
@@ -299,14 +262,13 @@ export class SshConnection extends EventEmitter {
|
|
|
299
262
|
}
|
|
300
263
|
if (timeoutMs > 0) {
|
|
301
264
|
timer = setTimeout(() => {
|
|
302
|
-
// A deadline is a result, not a rejection: `timedOut` is the caller's signal
|
|
303
|
-
//
|
|
304
|
-
timedOut = true;
|
|
265
|
+
// A deadline is a result, not a rejection: `timedOut` is the caller's signal and the result contract
|
|
266
|
+
// must not gain a throw path.
|
|
267
|
+
result.timedOut = true;
|
|
305
268
|
stream.destroy();
|
|
306
269
|
}, timeoutMs);
|
|
307
270
|
}
|
|
308
|
-
// Optional stdin (file uploads): the command reads it, so a secret never
|
|
309
|
-
// appears on the remote command line.
|
|
271
|
+
// Optional stdin (file uploads): the command reads it, so a secret never reaches the remote command line.
|
|
310
272
|
if (options.stdin !== undefined) {
|
|
311
273
|
try {
|
|
312
274
|
stream.end(String(options.stdin));
|
|
@@ -316,40 +278,12 @@ export class SshConnection extends EventEmitter {
|
|
|
316
278
|
return;
|
|
317
279
|
}
|
|
318
280
|
}
|
|
319
|
-
stream.on('data', (data) =>
|
|
320
|
-
|
|
321
|
-
// `maxBytes` truncation is silent by contract: no error, no flag, the excess is dropped.
|
|
322
|
-
if (chunks.stdout.length < maxBytes) {
|
|
323
|
-
chunks.stdout += text;
|
|
324
|
-
// The consumer is a progress reporter: its failure must not abort the command.
|
|
325
|
-
try {
|
|
326
|
-
options.onStdout?.(text);
|
|
327
|
-
}
|
|
328
|
-
catch {
|
|
329
|
-
// swallow-ok: stdout listeners must not break the command
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
});
|
|
333
|
-
stream.stderr.on('data', (data) => {
|
|
334
|
-
const text = data.toString('utf8');
|
|
335
|
-
if (chunks.stderr.length < maxBytes) {
|
|
336
|
-
chunks.stderr += text;
|
|
337
|
-
try {
|
|
338
|
-
options.onStderr?.(text);
|
|
339
|
-
}
|
|
340
|
-
catch {
|
|
341
|
-
// swallow-ok: stderr listeners must not break the command
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
});
|
|
281
|
+
stream.on('data', (data) => collect('stdout', data.toString('utf8'), options.onStdout));
|
|
282
|
+
stream.stderr.on('data', (data) => collect('stderr', data.toString('utf8'), options.onStderr));
|
|
345
283
|
stream.on('close', (code, signal) => {
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
stdout: chunks.stdout,
|
|
350
|
-
stderr: chunks.stderr,
|
|
351
|
-
timedOut,
|
|
352
|
-
});
|
|
284
|
+
result.code = code ?? null;
|
|
285
|
+
result.signal = signal ?? null;
|
|
286
|
+
finish(null, result);
|
|
353
287
|
});
|
|
354
288
|
stream.on('error', (streamError) => finish(streamError));
|
|
355
289
|
});
|
|
@@ -361,35 +295,27 @@ export class SshConnection extends EventEmitter {
|
|
|
361
295
|
return Promise.reject(closedError());
|
|
362
296
|
return openSftpSession(this.client);
|
|
363
297
|
}
|
|
364
|
-
/**
|
|
365
|
-
async
|
|
298
|
+
/** Run one download step on a fresh SFTP session and close it in `finally`: the three downloads share this. */
|
|
299
|
+
async withSftp(run) {
|
|
366
300
|
const sftp = await this.openSftp();
|
|
367
301
|
try {
|
|
368
|
-
return await
|
|
302
|
+
return await run(sftp);
|
|
369
303
|
}
|
|
370
304
|
finally {
|
|
371
305
|
endSftp(sftp);
|
|
372
306
|
}
|
|
373
307
|
}
|
|
308
|
+
/** Stream one remote file into a local path; the session is closed in `finally`. */
|
|
309
|
+
saveRemoteFile(remotePath, localPath, options = {}) {
|
|
310
|
+
return this.withSftp((sftp) => saveSftpFile(sftp, remotePath, localPath, options));
|
|
311
|
+
}
|
|
374
312
|
/** Inspect one remote path without reading it. */
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
try {
|
|
378
|
-
return await inspectSftpPath(sftp, remotePath);
|
|
379
|
-
}
|
|
380
|
-
finally {
|
|
381
|
-
endSftp(sftp);
|
|
382
|
-
}
|
|
313
|
+
inspectRemotePath(remotePath) {
|
|
314
|
+
return this.withSftp((sftp) => inspectSftpPath(sftp, remotePath));
|
|
383
315
|
}
|
|
384
316
|
/** Copy a remote directory to a local directory; see `saveSftpTree` for the exact contract. */
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
try {
|
|
388
|
-
return await saveSftpTree(sftp, remotePath, targetRoot, options);
|
|
389
|
-
}
|
|
390
|
-
finally {
|
|
391
|
-
endSftp(sftp);
|
|
392
|
-
}
|
|
317
|
+
saveRemoteTree(remotePath, targetRoot, options = {}) {
|
|
318
|
+
return this.withSftp((sftp) => saveSftpTree(sftp, remotePath, targetRoot, options));
|
|
393
319
|
}
|
|
394
320
|
forwardOut(destHost, destPort, srcHost = '127.0.0.1', srcPort = 0) {
|
|
395
321
|
return new Promise((resolve, reject) => {
|
|
@@ -411,6 +337,7 @@ export class SshConnection extends EventEmitter {
|
|
|
411
337
|
this.cleanupClient();
|
|
412
338
|
if (!client)
|
|
413
339
|
return;
|
|
340
|
+
// The remote never acknowledges, so bound the wait for our own transport to close.
|
|
414
341
|
await new Promise((resolve) => {
|
|
415
342
|
const timer = setTimeout(resolve, 1_500);
|
|
416
343
|
try {
|
|
@@ -430,26 +357,20 @@ export class SshConnection extends EventEmitter {
|
|
|
430
357
|
const client = this.client;
|
|
431
358
|
this.client = null;
|
|
432
359
|
this.closed = true;
|
|
433
|
-
if (client)
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
360
|
+
if (!client)
|
|
361
|
+
return;
|
|
362
|
+
try {
|
|
363
|
+
// Keep an error sink attached: ssh2 may still emit during teardown.
|
|
364
|
+
client.on('error', () => { });
|
|
365
|
+
client.end();
|
|
366
|
+
}
|
|
367
|
+
catch {
|
|
368
|
+
// swallow-ok: an error handler is installed above and end() must not throw
|
|
442
369
|
}
|
|
443
370
|
}
|
|
444
371
|
}
|
|
445
|
-
/**
|
|
446
|
-
*
|
|
447
|
-
*
|
|
448
|
-
* `ctx.deps.sshFactory` keeps its `(options) => SshPort` signature (decision D4); the default
|
|
449
|
-
* implementation moved from `new SshConnection(...)` to this factory so tests can override the
|
|
450
|
-
* injected client without touching the assembly.
|
|
451
|
-
* @param options - the port's connect options (plus the adapter's `@internal` client seam).
|
|
452
|
-
*/
|
|
372
|
+
/** The production `SshFactory`: one ssh2 adapter per dial attempt, keeping the `(options) => SshPort` signature
|
|
373
|
+
* `ctx.deps.sshFactory` expects, so tests can override the injected client without touching the assembly. */
|
|
453
374
|
export function createSsh2Port(options) {
|
|
454
375
|
return new SshConnection(options);
|
|
455
376
|
}
|
|
@@ -458,8 +379,7 @@ const MAX_KEY_BYTES = 1024 * 1024;
|
|
|
458
379
|
async function readKey(keyPath) {
|
|
459
380
|
let handle = null;
|
|
460
381
|
try {
|
|
461
|
-
// Measure and read through the *same* handle: a stat
|
|
462
|
-
// race (the file could be swapped in between), and a non-regular file has no place here.
|
|
382
|
+
// Measure and read through the *same* handle: a stat-then-read is a race, and a non-regular file has no place here.
|
|
463
383
|
handle = await open(keyPath, 'r');
|
|
464
384
|
const stats = await handle.stat();
|
|
465
385
|
if (stats.isFile?.() !== true)
|
package/dist/src/store.js
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Durable local state under `$DSH_HOME/remote-go/`: hosts.json, settings.json and secrets.json; writes are atomic, a corrupt file is kept aside before the next write replaces it.
|
|
3
|
-
*/
|
|
1
|
+
/** Durable local state under `$DSH_HOME/remote-go/`: hosts.json, settings.json and secrets.json; writes are atomic, a corrupt file is kept aside before the next write replaces it. */
|
|
4
2
|
import { promises as fs } from 'node:fs';
|
|
5
3
|
import path from 'node:path';
|
|
6
4
|
import { readJsonFile, withProcessLock, writeJsonAtomic } from './atomic-json.js';
|
|
@@ -10,15 +8,17 @@ import { defaultSettings, sanitizeHostEntry, sanitizeSettings } from './settings
|
|
|
10
8
|
function asArray(value) {
|
|
11
9
|
return Array.isArray(value) ? value : [];
|
|
12
10
|
}
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
* object to `typeof`, and the secrets file has always been adopted as-is in that case, so
|
|
16
|
-
* the type must not quietly tighten a persisted shape.
|
|
17
|
-
*/
|
|
11
|
+
// A JSON object or nothing. Deliberately looser than `isPlainObject`: an array *is* an object to
|
|
12
|
+
// `typeof` and the secrets file was always adopted as-is then, so the type must not tighten it.
|
|
18
13
|
function asRecord(value) {
|
|
19
14
|
return value !== null && typeof value === 'object' ? value : null;
|
|
20
15
|
}
|
|
21
16
|
export class HostStore {
|
|
17
|
+
data = { hosts: [], settings: defaultSettings() };
|
|
18
|
+
secrets = {};
|
|
19
|
+
/** Basenames of state files that were unreadable and moved aside on this load. */
|
|
20
|
+
corrupt = new Set();
|
|
21
|
+
loaded = false;
|
|
22
22
|
constructor(options) {
|
|
23
23
|
this.dir = options.dir;
|
|
24
24
|
this.logger = options.logger ?? console;
|
|
@@ -26,11 +26,6 @@ export class HostStore {
|
|
|
26
26
|
this.hostsFile = path.join(this.dir, 'hosts.json');
|
|
27
27
|
this.settingsFile = path.join(this.dir, 'settings.json');
|
|
28
28
|
this.secretsFile = path.join(this.dir, 'secrets.json');
|
|
29
|
-
this.data = { hosts: [], settings: defaultSettings() };
|
|
30
|
-
this.secrets = {};
|
|
31
|
-
/** Basenames of state files that were unreadable and moved aside on this load. */
|
|
32
|
-
this.corrupt = new Set();
|
|
33
|
-
this.loaded = false;
|
|
34
29
|
}
|
|
35
30
|
/** Whether `hosts.json` had to be quarantined, i.e. the host list is the empty fallback. */
|
|
36
31
|
get hostsCorrupt() {
|
|
@@ -45,10 +40,10 @@ export class HostStore {
|
|
|
45
40
|
catch (error) {
|
|
46
41
|
this.logger.warn?.('[dsh-remote-go] cannot create state directory:', error);
|
|
47
42
|
}
|
|
48
|
-
|
|
43
|
+
const hosts = asArray(await this.#readJson(this.hostsFile, []));
|
|
44
|
+
this.data.hosts = hosts.filter((item) => item !== null && typeof item === 'object');
|
|
49
45
|
this.data.settings = sanitizeSettings(await this.#readJson(this.settingsFile, null));
|
|
50
|
-
|
|
51
|
-
this.secrets = asRecord(secrets) ?? {};
|
|
46
|
+
this.secrets = asRecord(await this.#readJson(this.secretsFile, null)) ?? {};
|
|
52
47
|
this.loaded = true;
|
|
53
48
|
return this.data;
|
|
54
49
|
}
|
|
@@ -56,20 +51,14 @@ export class HostStore {
|
|
|
56
51
|
const result = await readJsonFile(file, { fs: this.fs, logger: this.logger });
|
|
57
52
|
if (result.status === 'ok')
|
|
58
53
|
return result.value;
|
|
59
|
-
// Only bytes that are not JSON are quarantined
|
|
60
|
-
//
|
|
61
|
-
//
|
|
62
|
-
// A corrupt file used to fall back to `[]` / defaults silently, and the next write then
|
|
63
|
-
// replaced it for good — losing every host, including the pinned fingerprints that make a
|
|
64
|
-
// host-key change detectable. Keep the bytes aside first, then recover.
|
|
54
|
+
// Only bytes that are not JSON are quarantined: a transient read error (EACCES) falls back for this run and is left
|
|
55
|
+
// in place, since renaming would turn a permission problem into an emptied host list. A corrupt file used to fall
|
|
56
|
+
// back silently and be replaced for good — losing hosts and the pinned fingerprints that detect a key change.
|
|
65
57
|
if (result.status === 'corrupt')
|
|
66
58
|
await this.#quarantine(file);
|
|
67
59
|
return fallback;
|
|
68
60
|
}
|
|
69
|
-
/**
|
|
70
|
-
* Rename one unreadable state file to `<name>.corrupt-<iso>` so it survives the recovery
|
|
71
|
-
* write. A failure here is logged and swallowed: recovery must not be blocked by it.
|
|
72
|
-
*/
|
|
61
|
+
/** Rename one unreadable state file to `<name>.corrupt-<iso>` so it survives the recovery write; a failure here is logged and swallowed, because it must not block that recovery. */
|
|
73
62
|
async #quarantine(file) {
|
|
74
63
|
const name = path.basename(file);
|
|
75
64
|
// The flag means "this file was unreadable", whether or not a copy could be made.
|
|
@@ -84,25 +73,20 @@ export class HostStore {
|
|
|
84
73
|
this.logger.warn?.(`[dsh-remote-go] cannot keep a copy of the unreadable ${name}:`, error);
|
|
85
74
|
}
|
|
86
75
|
}
|
|
87
|
-
#writeJson(file, value, mode = 0o600) {
|
|
88
|
-
|
|
76
|
+
async #writeJson(file, value, mode = 0o600) {
|
|
77
|
+
await withProcessLock(`${file}.lock`, { fs: this.fs, logger: this.logger }, () => writeJsonAtomic(file, value, {
|
|
89
78
|
dir: this.dir,
|
|
90
79
|
fs: this.fs,
|
|
91
80
|
logger: this.logger,
|
|
92
81
|
fileMode: mode,
|
|
93
|
-
}))
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
return result;
|
|
98
|
-
});
|
|
82
|
+
}));
|
|
83
|
+
// The recovered file is the authority again: the next successful write clears the flag, so a
|
|
84
|
+
// user who rebuilds the list is not warned forever about a file that is now valid.
|
|
85
|
+
this.corrupt.delete(path.basename(file));
|
|
99
86
|
}
|
|
100
87
|
async #persistHosts() {
|
|
101
88
|
await this.#writeJson(this.hostsFile, this.data.hosts);
|
|
102
89
|
}
|
|
103
|
-
async #persistSettings() {
|
|
104
|
-
await this.#writeJson(this.settingsFile, this.data.settings);
|
|
105
|
-
}
|
|
106
90
|
async #persistSecrets() {
|
|
107
91
|
await this.#writeJson(this.secretsFile, this.secrets);
|
|
108
92
|
}
|
|
@@ -115,10 +99,9 @@ export class HostStore {
|
|
|
115
99
|
}
|
|
116
100
|
async upsertHost(rawEntry, options = {}) {
|
|
117
101
|
await this.load();
|
|
118
|
-
// A caller may name an id only if this store already issued it: the id keys the secrets
|
|
119
|
-
//
|
|
120
|
-
//
|
|
121
|
-
// host always gets a fresh `h_…` and learns it from the returned HostView.
|
|
102
|
+
// A caller may name an id only if this store already issued it: the id keys the secrets file, the proxy's per-host
|
|
103
|
+
// routes and the client's host links, so a client-chosen id (malformed, too long, duplicate) is not adopted. A new
|
|
104
|
+
// host gets a fresh `h_…` from the returned HostView.
|
|
122
105
|
const rawId = isPlainObject(rawEntry) && typeof rawEntry.id === 'string' ? rawEntry.id : '';
|
|
123
106
|
const existing = rawId === '' ? null : this.getHost(rawId);
|
|
124
107
|
const entry = sanitizeHostEntry(rawEntry, { settings: options.settings ?? this.data.settings, existing });
|
|
@@ -157,12 +140,12 @@ export class HostStore {
|
|
|
157
140
|
}
|
|
158
141
|
async saveSettings(raw) {
|
|
159
142
|
await this.load();
|
|
160
|
-
const patch =
|
|
161
|
-
// Merge the patch onto the *current* settings. Spreading it over the defaults reset every
|
|
162
|
-
//
|
|
163
|
-
//
|
|
143
|
+
const patch = isPlainObject(raw) ? raw : {};
|
|
144
|
+
// Merge the patch onto the *current* settings. Spreading it over the defaults reset every field
|
|
145
|
+
// the patch did not name — a patch of `autoReconnect.maxAttempts` also rewound `baseDelayMs`
|
|
146
|
+
// from a configured 5000 back to 800 — which silently undid sibling settings.
|
|
164
147
|
this.data.settings = sanitizeSettings(deepMerge(this.data.settings, patch));
|
|
165
|
-
await this.#
|
|
148
|
+
await this.#writeJson(this.settingsFile, this.data.settings);
|
|
166
149
|
if (!this.data.settings.saveTokens) {
|
|
167
150
|
this.secrets = {};
|
|
168
151
|
await this.#persistSecrets();
|
|
@@ -170,8 +153,8 @@ export class HostStore {
|
|
|
170
153
|
return this.data.settings;
|
|
171
154
|
}
|
|
172
155
|
async saveToken(hostId, token) {
|
|
173
|
-
// Without this the first token save on a fresh process wrote `{}` over a secrets file that
|
|
174
|
-
//
|
|
156
|
+
// Without this the first token save on a fresh process wrote `{}` over a secrets file that still
|
|
157
|
+
// held other hosts' tokens.
|
|
175
158
|
await this.load();
|
|
176
159
|
if (!this.data.settings.saveTokens)
|
|
177
160
|
return;
|