@linxin666/dsh-ssh 0.4.19 → 0.4.21
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.i18n.yaml +2 -2
- package/README.md +13 -2
- package/README.zh.md +13 -2
- package/lib/client.js +726 -109
- package/lib/client.js.map +1 -1
- package/lib/index.js +1074 -352
- package/lib/types/client/api.d.ts +8 -4
- package/lib/types/client/locales.d.ts +27 -1
- package/lib/types/client/panel/HostFormDialog.d.ts +3 -3
- package/lib/types/client/panel/HostsTab.d.ts +3 -3
- package/lib/types/client/panel/KeysTab.d.ts +8 -0
- package/lib/types/client/panel/controller.d.ts +1 -1
- package/lib/types/connection-trust.d.ts +26 -0
- package/lib/types/engine/cluster.d.ts +7 -2
- package/lib/types/engine/connection-pool.d.ts +11 -2
- package/lib/types/engine/sftp.d.ts +5 -0
- package/lib/types/engine/terminal-sessions.d.ts +5 -3
- package/lib/types/index.d.ts +6 -5
- package/lib/types/protocol.d.ts +41 -0
- package/lib/types/routes.d.ts +3 -0
- package/lib/types/service.d.ts +148 -0
- package/lib/types/store.d.ts +16 -4
- package/package.json +1 -1
- package/src/client/api.ts +147 -58
- package/src/client/locales.ts +55 -2
- package/src/client/panel/HostFormDialog.tsx +76 -17
- package/src/client/panel/HostsTab.tsx +50 -25
- package/src/client/panel/KeysTab.tsx +192 -0
- package/src/client/panel/SshPanel.tsx +4 -1
- package/src/client/panel/TerminalTab.tsx +14 -9
- package/src/client/panel/TunnelsTab.tsx +24 -7
- package/src/client/panel/controller.ts +77 -12
- package/src/client/panel/helpers.ts +3 -2
- package/src/connection-trust.ts +70 -0
- package/src/engine/cluster.ts +45 -13
- package/src/engine/connection-pool.ts +279 -96
- package/src/engine/proxy-command.ts +27 -10
- package/src/engine/sftp.ts +69 -35
- package/src/engine/terminal-sessions.ts +110 -35
- package/src/engine/tunnel.ts +20 -2
- package/src/engine.ts +5 -8
- package/src/index.ts +113 -39
- package/src/protocol.ts +45 -0
- package/src/routes.ts +130 -23
- package/src/service.ts +158 -0
- package/src/store.ts +324 -104
- package/src/tools.ts +3 -5
package/lib/index.js
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
import z from "@deepseek-ai/schemastery";
|
|
2
|
-
import { closeSync, createReadStream, createWriteStream, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { closeSync, createReadStream, createWriteStream, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { StringDecoder } from "node:string_decoder";
|
|
3
4
|
import { Client } from "ssh2";
|
|
5
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
4
6
|
import { homedir, tmpdir } from "node:os";
|
|
5
|
-
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
7
|
+
import { basename, dirname, isAbsolute, join, posix, relative, resolve } from "node:path";
|
|
6
8
|
import { isAbsolute as isAbsolute$1, join as join$1 } from "node:path/posix";
|
|
7
9
|
import { spawn } from "node:child_process";
|
|
8
10
|
import { Duplex } from "node:stream";
|
|
9
11
|
import { createServer } from "node:net";
|
|
10
12
|
import { unlink } from "node:fs/promises";
|
|
11
|
-
import { randomBytes } from "node:crypto";
|
|
12
13
|
import { WebSocket, WebSocketServer } from "ws";
|
|
13
14
|
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
14
15
|
//#region src/dsh-home.ts
|
|
@@ -195,19 +196,27 @@ function storePath() {
|
|
|
195
196
|
function sshConfigPath() {
|
|
196
197
|
return join(homedir(), ".ssh", "config");
|
|
197
198
|
}
|
|
199
|
+
/** Validate an auth block shape; returns an error message or undefined. */
|
|
200
|
+
function validateAuth(auth) {
|
|
201
|
+
if (typeof auth !== "object" || auth === null) return "auth must be an object";
|
|
202
|
+
const a = auth;
|
|
203
|
+
if (a.kind !== "key" && a.kind !== "password" && a.kind !== "agent") return "auth.kind must be key, password or agent";
|
|
204
|
+
if (a.kind === "key") {
|
|
205
|
+
if (typeof a.keyPath !== "string" || a.keyPath.trim() === "") return "auth.keyPath is required for key auth";
|
|
206
|
+
if (a.passphrase !== void 0 && typeof a.passphrase !== "string") return "auth.passphrase must be a string when provided";
|
|
207
|
+
}
|
|
208
|
+
if (a.kind === "password" && a.password !== void 0 && typeof a.password !== "string") return "auth.password must be a string when provided";
|
|
209
|
+
if (a.kind === "agent" && a.agentPath !== void 0 && typeof a.agentPath !== "string") return "auth.agentPath must be a string when provided";
|
|
210
|
+
}
|
|
198
211
|
/** Validate the wire shape of a host payload; returns a message or undefined. */
|
|
199
212
|
function validateHostPayload(payload) {
|
|
200
213
|
if (typeof payload !== "object" || payload === null) return "body must be a JSON object";
|
|
201
214
|
const p = payload;
|
|
202
215
|
if (typeof p.host !== "string" || p.host.trim() === "") return "host is required";
|
|
203
216
|
if (typeof p.user !== "string" || p.user.trim() === "") return "user is required";
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
if (
|
|
207
|
-
if (auth.kind !== "key" && auth.kind !== "password" && auth.kind !== "agent") return "auth.kind must be key, password or agent";
|
|
208
|
-
if (auth.kind === "key" && (typeof auth.keyPath !== "string" || auth.keyPath.trim() === "")) return "auth.keyPath is required for key auth";
|
|
209
|
-
if (auth.kind === "password" && auth.password !== void 0 && typeof auth.password !== "string") return "auth.password must be a string when provided";
|
|
210
|
-
if (auth.kind === "agent" && auth.agentPath !== void 0 && typeof auth.agentPath !== "string") return "auth.agentPath must be a string when provided";
|
|
217
|
+
if (p.auth !== void 0) {
|
|
218
|
+
const authError = validateAuth(p.auth);
|
|
219
|
+
if (authError !== void 0) return authError;
|
|
211
220
|
}
|
|
212
221
|
if (p.port !== void 0 && (typeof p.port !== "number" || !Number.isInteger(p.port) || p.port < 1 || p.port > 65535)) return "port must be an integer in 1..65535";
|
|
213
222
|
if (p.proxyJump !== void 0 && (!Array.isArray(p.proxyJump) || p.proxyJump.some((x) => typeof x !== "string" || x === ""))) return "proxyJump must be an array of alias strings";
|
|
@@ -218,6 +227,38 @@ function validateHostPayload(payload) {
|
|
|
218
227
|
if (p.tags !== void 0 && (!Array.isArray(p.tags) || p.tags.some((x) => typeof x !== "string"))) return "tags must be an array of strings";
|
|
219
228
|
if (p.forwardAgent !== void 0 && typeof p.forwardAgent !== "boolean") return "forwardAgent must be a boolean";
|
|
220
229
|
}
|
|
230
|
+
/** Validate a full creation payload and build its normalized entry. */
|
|
231
|
+
function buildValidatedHostEntry(payload, now) {
|
|
232
|
+
const alias = payload.alias?.trim();
|
|
233
|
+
if (!alias) throw new Error("alias is required");
|
|
234
|
+
const aliasError = validateAlias(alias);
|
|
235
|
+
if (aliasError !== void 0) throw new Error(aliasError);
|
|
236
|
+
const bodyError = validateHostPayload(payload);
|
|
237
|
+
if (bodyError !== void 0) throw new Error(bodyError);
|
|
238
|
+
if (payload.auth === void 0) throw new Error("auth is required");
|
|
239
|
+
return {
|
|
240
|
+
alias,
|
|
241
|
+
host: payload.host.trim(),
|
|
242
|
+
port: payload.port ?? 22,
|
|
243
|
+
user: payload.user.trim(),
|
|
244
|
+
auth: {
|
|
245
|
+
kind: payload.auth.kind,
|
|
246
|
+
keyPath: payload.auth.kind === "key" ? expandHome(payload.auth.keyPath?.trim() ?? "") : void 0,
|
|
247
|
+
passphrase: payload.auth.kind === "key" ? payload.auth.passphrase || void 0 : void 0,
|
|
248
|
+
password: payload.auth.kind === "password" ? payload.auth.password : void 0,
|
|
249
|
+
agentPath: payload.auth.kind === "agent" ? normalizeAgentPath(payload.auth.agentPath) : void 0
|
|
250
|
+
},
|
|
251
|
+
proxyJump: [...payload.proxyJump ?? []],
|
|
252
|
+
proxyCommand: normalizeProxyCommand(payload.proxyCommand),
|
|
253
|
+
description: payload.description?.trim() || void 0,
|
|
254
|
+
environment: payload.environment?.trim() || void 0,
|
|
255
|
+
tags: [...payload.tags ?? []].map((tag) => tag.trim()).filter((tag) => tag !== ""),
|
|
256
|
+
location: payload.location?.trim() || void 0,
|
|
257
|
+
forwardAgent: payload.forwardAgent === true ? true : void 0,
|
|
258
|
+
createdAt: now,
|
|
259
|
+
updatedAt: now
|
|
260
|
+
};
|
|
261
|
+
}
|
|
221
262
|
/** Alias grammar: letters/digits plus dots, hyphens, underscores (IP/domain aliases included). */
|
|
222
263
|
const ALIAS_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
|
|
223
264
|
/** Validate an alias for creation. */
|
|
@@ -240,18 +281,21 @@ var HostStore = class {
|
|
|
240
281
|
this.path = resolve(path ?? storePath());
|
|
241
282
|
this.sshConfigOverride = sshConfigOverride;
|
|
242
283
|
}
|
|
243
|
-
/** Load
|
|
244
|
-
list() {
|
|
245
|
-
|
|
284
|
+
/** Load host entries, optionally filtered by the panel's search text. */
|
|
285
|
+
list(query) {
|
|
286
|
+
const file = this.load();
|
|
287
|
+
const needle = query?.trim().toLowerCase();
|
|
288
|
+
if (needle === void 0 || needle === "") return [...file.hosts];
|
|
289
|
+
return file.hosts.filter((entry) => entry.alias.toLowerCase().includes(needle) || (entry.description ?? "").toLowerCase().includes(needle) || entry.host.toLowerCase().includes(needle) || entry.tags.some((tag) => tag.toLowerCase().includes(needle)));
|
|
246
290
|
}
|
|
247
291
|
/** Find one entry by alias. */
|
|
248
292
|
find(alias) {
|
|
249
|
-
return this.
|
|
293
|
+
return this.load().hosts.find((entry) => entry.alias === alias);
|
|
250
294
|
}
|
|
251
295
|
/** Secret-free projection for the browser and agent surfaces. */
|
|
252
296
|
summarize(entry) {
|
|
253
297
|
let keyReady = true;
|
|
254
|
-
if (entry.auth.kind === "key" && entry.auth.keyPath
|
|
298
|
+
if (entry.auth.kind === "key") keyReady = entry.auth.keyPath !== void 0 && entry.auth.keyPath !== "" && existsSync(expandHome(entry.auth.keyPath));
|
|
255
299
|
else if (entry.auth.kind === "agent") keyReady = false;
|
|
256
300
|
return {
|
|
257
301
|
alias: entry.alias,
|
|
@@ -271,49 +315,32 @@ var HostStore = class {
|
|
|
271
315
|
updatedAt: entry.updatedAt
|
|
272
316
|
};
|
|
273
317
|
}
|
|
318
|
+
/** Browser-only projection that can match a stored path to a managed key. */
|
|
319
|
+
summarizePanel(entry) {
|
|
320
|
+
return {
|
|
321
|
+
...this.summarize(entry),
|
|
322
|
+
...entry.auth.kind === "key" && entry.auth.keyPath !== void 0 && entry.auth.keyPath !== "" ? { keyPath: entry.auth.keyPath } : {}
|
|
323
|
+
};
|
|
324
|
+
}
|
|
274
325
|
/** Create one entry. Throws on alias collision or invalid payload. */
|
|
275
326
|
create(payload) {
|
|
276
|
-
const
|
|
277
|
-
if (!alias) throw new Error("alias is required");
|
|
278
|
-
const aliasError = validateAlias(alias);
|
|
279
|
-
if (aliasError !== void 0) throw new Error(aliasError);
|
|
280
|
-
const bodyError = validateHostPayload(payload);
|
|
281
|
-
if (bodyError !== void 0) throw new Error(bodyError);
|
|
282
|
-
if (payload.auth === void 0) throw new Error("auth is required");
|
|
327
|
+
const entry = buildValidatedHostEntry(payload, Date.now());
|
|
283
328
|
const file = this.load();
|
|
284
|
-
if (file.hosts.some((
|
|
285
|
-
const
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
port: payload.port ?? 22,
|
|
290
|
-
user: payload.user.trim(),
|
|
291
|
-
auth: {
|
|
292
|
-
kind: payload.auth.kind,
|
|
293
|
-
keyPath: payload.auth.kind === "key" ? expandHome(payload.auth.keyPath?.trim() ?? "") : void 0,
|
|
294
|
-
passphrase: payload.auth.kind === "key" ? payload.auth.passphrase ?? void 0 : void 0,
|
|
295
|
-
password: payload.auth.kind === "password" ? payload.auth.password : void 0,
|
|
296
|
-
agentPath: payload.auth.kind === "agent" ? normalizeAgentPath(payload.auth.agentPath) : void 0
|
|
297
|
-
},
|
|
298
|
-
proxyJump: [...payload.proxyJump ?? []],
|
|
299
|
-
proxyCommand: normalizeProxyCommand(payload.proxyCommand),
|
|
300
|
-
description: payload.description?.trim() || void 0,
|
|
301
|
-
environment: payload.environment?.trim() || void 0,
|
|
302
|
-
tags: [...payload.tags ?? []].map((tag) => tag.trim()).filter((tag) => tag !== ""),
|
|
303
|
-
location: payload.location?.trim() || void 0,
|
|
304
|
-
forwardAgent: payload.forwardAgent === true ? true : void 0,
|
|
305
|
-
createdAt: now,
|
|
306
|
-
updatedAt: now
|
|
329
|
+
if (file.hosts.some((existing) => existing.alias === entry.alias)) throw new Error(`alias '${entry.alias}' already exists`);
|
|
330
|
+
const nextFile = {
|
|
331
|
+
version: file.version,
|
|
332
|
+
hosts: [...file.hosts, entry],
|
|
333
|
+
...file.keys !== void 0 ? { keys: file.keys } : {}
|
|
307
334
|
};
|
|
308
|
-
|
|
309
|
-
this.save(file);
|
|
335
|
+
this.save(nextFile);
|
|
310
336
|
return entry;
|
|
311
337
|
}
|
|
312
338
|
/** Update the fields present in `patch`; unknown aliases throw. */
|
|
313
339
|
update(alias, patch) {
|
|
314
340
|
const file = this.load();
|
|
315
|
-
const
|
|
316
|
-
if (
|
|
341
|
+
const index = file.hosts.findIndex((candidate) => candidate.alias === alias);
|
|
342
|
+
if (index < 0) throw new Error(`alias '${alias}' not found`);
|
|
343
|
+
const entry = file.hosts[index];
|
|
317
344
|
if (patch.host !== void 0 && (typeof patch.host !== "string" || patch.host.trim() === "")) throw new Error("host is required");
|
|
318
345
|
if (patch.user !== void 0 && (typeof patch.user !== "string" || patch.user.trim() === "")) throw new Error("user is required");
|
|
319
346
|
if (patch.port !== void 0 && (typeof patch.port !== "number" || !Number.isInteger(patch.port) || patch.port < 1 || patch.port > 65535)) throw new Error("port must be an integer in 1..65535");
|
|
@@ -323,42 +350,163 @@ var HostStore = class {
|
|
|
323
350
|
const mergedProxyCommand = patch.proxyCommand !== void 0 ? normalizeProxyCommand(patch.proxyCommand) : entry.proxyCommand;
|
|
324
351
|
if (mergedProxyCommand !== void 0 && (patch.proxyJump ?? entry.proxyJump).length > 0) throw new Error("proxyCommand and proxyJump cannot be combined — pick one transport per host");
|
|
325
352
|
if (patch.tags !== void 0 && (!Array.isArray(patch.tags) || patch.tags.some((x) => typeof x !== "string"))) throw new Error("tags must be an array of strings");
|
|
326
|
-
if (patch.
|
|
327
|
-
if (patch.
|
|
328
|
-
if (patch.
|
|
353
|
+
if (patch.description !== void 0 && typeof patch.description !== "string") throw new Error("description must be a string when provided");
|
|
354
|
+
if (patch.environment !== void 0 && typeof patch.environment !== "string") throw new Error("environment must be a string when provided");
|
|
355
|
+
if (patch.location !== void 0 && typeof patch.location !== "string") throw new Error("location must be a string when provided");
|
|
356
|
+
if (patch.auth !== void 0) {
|
|
357
|
+
const authError = validateAuth(patch.auth);
|
|
358
|
+
if (authError !== void 0) throw new Error(authError);
|
|
359
|
+
}
|
|
360
|
+
let nextAuth = entry.auth;
|
|
329
361
|
if (patch.auth !== void 0) {
|
|
330
362
|
const auth = patch.auth;
|
|
331
|
-
if (auth.kind !== "key" && auth.kind !== "password" && auth.kind !== "agent") throw new Error("auth.kind must be key, password or agent");
|
|
332
|
-
if (auth.kind === "key" && (typeof auth.keyPath !== "string" || auth.keyPath.trim() === "")) throw new Error("auth.keyPath is required for key auth");
|
|
333
|
-
if (auth.kind === "password" && auth.password !== void 0 && typeof auth.password !== "string") throw new Error("auth.password must be a string when provided");
|
|
334
|
-
if (auth.kind === "agent" && auth.agentPath !== void 0 && typeof auth.agentPath !== "string") throw new Error("auth.agentPath must be a string when provided");
|
|
335
363
|
const keyChanged = auth.kind === "key" && auth.keyPath !== void 0 && expandHome(auth.keyPath.trim()) !== entry.auth.keyPath;
|
|
336
|
-
|
|
364
|
+
nextAuth = {
|
|
337
365
|
kind: auth.kind,
|
|
338
366
|
keyPath: auth.kind === "key" ? expandHome(auth.keyPath?.trim() ?? "") : void 0,
|
|
339
|
-
passphrase: auth.kind === "key" ? auth.passphrase !== void 0 ? auth.passphrase : keyChanged ? void 0 : entry.auth.passphrase : void 0,
|
|
367
|
+
passphrase: auth.kind === "key" ? auth.passphrase !== void 0 ? auth.passphrase || void 0 : keyChanged ? void 0 : entry.auth.passphrase : void 0,
|
|
340
368
|
password: auth.kind === "password" ? auth.password : void 0,
|
|
341
369
|
agentPath: auth.kind === "agent" ? auth.agentPath !== void 0 ? normalizeAgentPath(auth.agentPath) : entry.auth.agentPath : void 0
|
|
342
370
|
};
|
|
343
371
|
}
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
372
|
+
const nextEntry = {
|
|
373
|
+
...entry,
|
|
374
|
+
host: patch.host !== void 0 ? patch.host.trim() : entry.host,
|
|
375
|
+
port: patch.port !== void 0 ? patch.port : entry.port,
|
|
376
|
+
user: patch.user !== void 0 ? patch.user.trim() : entry.user,
|
|
377
|
+
auth: nextAuth,
|
|
378
|
+
proxyJump: patch.proxyJump !== void 0 ? [...patch.proxyJump] : entry.proxyJump,
|
|
379
|
+
proxyCommand: patch.proxyCommand !== void 0 ? mergedProxyCommand : entry.proxyCommand,
|
|
380
|
+
description: patch.description !== void 0 ? patch.description.trim() || void 0 : entry.description,
|
|
381
|
+
environment: patch.environment !== void 0 ? patch.environment.trim() || void 0 : entry.environment,
|
|
382
|
+
tags: patch.tags !== void 0 ? [...patch.tags].map((tag) => tag.trim()).filter((tag) => tag !== "") : entry.tags,
|
|
383
|
+
location: patch.location !== void 0 ? patch.location.trim() || void 0 : entry.location,
|
|
384
|
+
forwardAgent: patch.forwardAgent !== void 0 ? patch.forwardAgent === true ? true : void 0 : entry.forwardAgent,
|
|
385
|
+
updatedAt: Date.now()
|
|
386
|
+
};
|
|
387
|
+
const nextFile = {
|
|
388
|
+
version: file.version,
|
|
389
|
+
hosts: file.hosts.map((candidate, candidateIndex) => candidateIndex === index ? nextEntry : candidate),
|
|
390
|
+
...file.keys !== void 0 ? { keys: file.keys } : {}
|
|
391
|
+
};
|
|
392
|
+
this.save(nextFile);
|
|
393
|
+
return nextEntry;
|
|
354
394
|
}
|
|
355
395
|
/** Remove one entry. */
|
|
356
396
|
delete(alias) {
|
|
357
397
|
const file = this.load();
|
|
358
398
|
const index = file.hosts.findIndex((candidate) => candidate.alias === alias);
|
|
359
399
|
if (index < 0) throw new Error(`alias '${alias}' not found`);
|
|
360
|
-
|
|
361
|
-
|
|
400
|
+
const nextFile = {
|
|
401
|
+
version: file.version,
|
|
402
|
+
hosts: file.hosts.filter((_, candidateIndex) => candidateIndex !== index),
|
|
403
|
+
...file.keys !== void 0 ? { keys: file.keys } : {}
|
|
404
|
+
};
|
|
405
|
+
this.save(nextFile);
|
|
406
|
+
}
|
|
407
|
+
/** List managed keys with file-existence and host-reference metadata. */
|
|
408
|
+
listKeys() {
|
|
409
|
+
const file = this.load();
|
|
410
|
+
const keys = file.keys ?? [];
|
|
411
|
+
if (keys.length === 0) return [];
|
|
412
|
+
const usedByPath = buildUsedByPathMap(file.hosts);
|
|
413
|
+
return keys.map((key) => this.summarizeKey(key, file, usedByPath));
|
|
414
|
+
}
|
|
415
|
+
/** Create one managed key reference without reading its contents. */
|
|
416
|
+
createKey(payload) {
|
|
417
|
+
const name = requiredKeyName(payload.name);
|
|
418
|
+
const path = requiredKeyPath(payload.path);
|
|
419
|
+
const file = this.load();
|
|
420
|
+
const now = Date.now();
|
|
421
|
+
const entry = {
|
|
422
|
+
id: randomUUID(),
|
|
423
|
+
name,
|
|
424
|
+
path,
|
|
425
|
+
passphrase: typeof payload.passphrase === "string" && payload.passphrase !== "" ? payload.passphrase : void 0,
|
|
426
|
+
note: typeof payload.note === "string" ? payload.note.trim() || void 0 : void 0,
|
|
427
|
+
createdAt: now,
|
|
428
|
+
updatedAt: now
|
|
429
|
+
};
|
|
430
|
+
const nextFile = {
|
|
431
|
+
version: file.version,
|
|
432
|
+
hosts: file.hosts,
|
|
433
|
+
keys: [...file.keys ?? [], entry]
|
|
434
|
+
};
|
|
435
|
+
this.save(nextFile);
|
|
436
|
+
return this.summarizeKey(entry, nextFile);
|
|
437
|
+
}
|
|
438
|
+
/** Update a managed key; omitted fields and a blank passphrase keep old values. */
|
|
439
|
+
updateKey(id, patch) {
|
|
440
|
+
const file = this.load();
|
|
441
|
+
const keys = file.keys ?? [];
|
|
442
|
+
const index = keys.findIndex((candidate) => candidate.id === id);
|
|
443
|
+
if (index < 0) throw new Error(`managed key '${id}' not found`);
|
|
444
|
+
const entry = keys[index];
|
|
445
|
+
const nextName = patch.name !== void 0 ? requiredKeyName(patch.name) : entry.name;
|
|
446
|
+
const nextPath = patch.path !== void 0 ? requiredKeyPath(patch.path) : entry.path;
|
|
447
|
+
const nextPassphrase = patch.passphrase !== void 0 ? patch.passphrase === null || patch.passphrase === "" ? void 0 : patch.passphrase : entry.passphrase;
|
|
448
|
+
const nextNote = patch.note !== void 0 ? typeof patch.note === "string" ? patch.note.trim() || void 0 : void 0 : entry.note;
|
|
449
|
+
const nextEntry = {
|
|
450
|
+
...entry,
|
|
451
|
+
name: nextName,
|
|
452
|
+
path: nextPath,
|
|
453
|
+
passphrase: nextPassphrase,
|
|
454
|
+
note: nextNote,
|
|
455
|
+
updatedAt: Date.now()
|
|
456
|
+
};
|
|
457
|
+
const nextFile = {
|
|
458
|
+
version: file.version,
|
|
459
|
+
hosts: file.hosts,
|
|
460
|
+
keys: keys.map((candidate, candidateIndex) => candidateIndex === index ? nextEntry : candidate)
|
|
461
|
+
};
|
|
462
|
+
this.save(nextFile);
|
|
463
|
+
return this.summarizeKey(nextEntry, nextFile);
|
|
464
|
+
}
|
|
465
|
+
/** Delete only the managed reference; stored host auth.keyPath values stay untouched. */
|
|
466
|
+
deleteKey(id) {
|
|
467
|
+
const file = this.load();
|
|
468
|
+
const keys = file.keys ?? [];
|
|
469
|
+
const index = keys.findIndex((candidate) => candidate.id === id);
|
|
470
|
+
if (index < 0) throw new Error(`managed key '${id}' not found`);
|
|
471
|
+
const nextFile = {
|
|
472
|
+
version: file.version,
|
|
473
|
+
hosts: file.hosts,
|
|
474
|
+
keys: keys.filter((_, candidateIndex) => candidateIndex !== index)
|
|
475
|
+
};
|
|
476
|
+
this.save(nextFile);
|
|
477
|
+
}
|
|
478
|
+
/** Resolve a transient managedKeyId into the host's existing keyPath/passphrase shape. */
|
|
479
|
+
resolveManagedKey(payload) {
|
|
480
|
+
if (payload.managedKeyId === void 0) return payload;
|
|
481
|
+
if (typeof payload.managedKeyId !== "string" || payload.managedKeyId === "") throw new Error("managedKeyId must be a non-empty string");
|
|
482
|
+
if (payload.auth !== void 0 && payload.auth.kind !== "key") throw new Error("managedKeyId requires key auth");
|
|
483
|
+
const key = this.load().keys?.find((candidate) => candidate.id === payload.managedKeyId);
|
|
484
|
+
if (key === void 0) throw new Error(`managed key '${payload.managedKeyId}' not found`);
|
|
485
|
+
const { managedKeyId: _managedKeyId, ...rest } = payload;
|
|
486
|
+
return {
|
|
487
|
+
...rest,
|
|
488
|
+
auth: {
|
|
489
|
+
...payload.auth,
|
|
490
|
+
kind: "key",
|
|
491
|
+
keyPath: key.path,
|
|
492
|
+
passphrase: key.passphrase ?? ""
|
|
493
|
+
}
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
summarizeKey(key, file, usedByPath) {
|
|
497
|
+
const resolvedPath = expandHome(key.path);
|
|
498
|
+
const usedBy = usedByPath !== void 0 ? [...usedByPath.get(resolvedPath) ?? []] : file.hosts.filter((host) => host.auth.kind === "key" && host.auth.keyPath !== void 0 && host.auth.keyPath !== "" && expandHome(host.auth.keyPath) === resolvedPath).map((host) => host.alias);
|
|
499
|
+
return {
|
|
500
|
+
id: key.id,
|
|
501
|
+
name: key.name,
|
|
502
|
+
path: key.path,
|
|
503
|
+
hasPassphrase: key.passphrase !== void 0 && key.passphrase !== "",
|
|
504
|
+
note: key.note,
|
|
505
|
+
exists: existsSync(resolvedPath),
|
|
506
|
+
usedBy,
|
|
507
|
+
createdAt: key.createdAt,
|
|
508
|
+
updatedAt: key.updatedAt
|
|
509
|
+
};
|
|
362
510
|
}
|
|
363
511
|
/**
|
|
364
512
|
* Import hosts from `~/.ssh/config`: Host blocks with a single non-wildcard
|
|
@@ -370,7 +518,6 @@ var HostStore = class {
|
|
|
370
518
|
* @returns import statistics.
|
|
371
519
|
*/
|
|
372
520
|
importFromSshConfig() {
|
|
373
|
-
this.skippedBlocks = [];
|
|
374
521
|
const configPath = this.sshConfigOverride ?? sshConfigPath();
|
|
375
522
|
if (!existsSync(configPath)) return {
|
|
376
523
|
parsed: 0,
|
|
@@ -379,23 +526,27 @@ var HostStore = class {
|
|
|
379
526
|
skippedBlocks: []
|
|
380
527
|
};
|
|
381
528
|
const { blocks, skipped } = readSshConfigBlocks(configPath);
|
|
382
|
-
|
|
529
|
+
const skippedBlocks = [...skipped];
|
|
530
|
+
const skippedNames = new Set(skipped.map((block) => block.name));
|
|
383
531
|
const skip = (name, reason) => {
|
|
384
|
-
if (name === "") return;
|
|
385
|
-
|
|
386
|
-
|
|
532
|
+
if (name === "" || skippedNames.has(name)) return;
|
|
533
|
+
skippedNames.add(name);
|
|
534
|
+
skippedBlocks.push({
|
|
387
535
|
name,
|
|
388
536
|
reason
|
|
389
537
|
});
|
|
390
538
|
};
|
|
391
|
-
|
|
539
|
+
const file = this.load();
|
|
540
|
+
const existingAliases = new Set(file.hosts.map((entry) => entry.alias));
|
|
541
|
+
const addedEntries = [];
|
|
542
|
+
const now = Date.now();
|
|
392
543
|
for (const block of blocks) {
|
|
393
544
|
const pattern = block.pattern.split(/\s+/)[0];
|
|
394
545
|
if (pattern.includes("*") || pattern.includes("?")) {
|
|
395
546
|
skip(pattern, "wildcard");
|
|
396
547
|
continue;
|
|
397
548
|
}
|
|
398
|
-
if (
|
|
549
|
+
if (existingAliases.has(pattern)) {
|
|
399
550
|
skip(pattern, "existing");
|
|
400
551
|
continue;
|
|
401
552
|
}
|
|
@@ -419,20 +570,28 @@ var HostStore = class {
|
|
|
419
570
|
forwardAgent: parseForwardAgentValue(block.props.forwardagent)
|
|
420
571
|
};
|
|
421
572
|
try {
|
|
422
|
-
|
|
423
|
-
|
|
573
|
+
const entry = buildValidatedHostEntry(payload, now);
|
|
574
|
+
existingAliases.add(entry.alias);
|
|
575
|
+
addedEntries.push(entry);
|
|
424
576
|
} catch {
|
|
425
577
|
skip(pattern, "invalid");
|
|
426
578
|
}
|
|
427
579
|
}
|
|
580
|
+
if (addedEntries.length > 0) {
|
|
581
|
+
const nextFile = {
|
|
582
|
+
version: file.version,
|
|
583
|
+
hosts: [...file.hosts, ...addedEntries],
|
|
584
|
+
...file.keys !== void 0 ? { keys: file.keys } : {}
|
|
585
|
+
};
|
|
586
|
+
this.save(nextFile);
|
|
587
|
+
}
|
|
428
588
|
return {
|
|
429
589
|
parsed: blocks.length,
|
|
430
|
-
added,
|
|
431
|
-
skipped:
|
|
432
|
-
skippedBlocks
|
|
590
|
+
added: addedEntries.length,
|
|
591
|
+
skipped: skippedBlocks.length,
|
|
592
|
+
skippedBlocks
|
|
433
593
|
};
|
|
434
594
|
}
|
|
435
|
-
skippedBlocks = [];
|
|
436
595
|
/**
|
|
437
596
|
* Last parsed store keyed by file identity. list/find ride every acquire
|
|
438
597
|
* and GUI refresh; re-reading and re-parsing the whole file each call is
|
|
@@ -477,15 +636,34 @@ var HostStore = class {
|
|
|
477
636
|
recursive: true,
|
|
478
637
|
mode: 448
|
|
479
638
|
});
|
|
480
|
-
const tmp = this.path
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
639
|
+
const tmp = `${this.path}.tmp-${process.pid}-${randomBytes(4).toString("hex")}`;
|
|
640
|
+
try {
|
|
641
|
+
writeFileSync(tmp, JSON.stringify(file, null, 2) + "\n", {
|
|
642
|
+
encoding: "utf8",
|
|
643
|
+
mode: 384
|
|
644
|
+
});
|
|
645
|
+
renameSync(tmp, this.path);
|
|
646
|
+
} catch (error) {
|
|
647
|
+
try {
|
|
648
|
+
unlinkSync(tmp);
|
|
649
|
+
} catch {}
|
|
650
|
+
throw error;
|
|
651
|
+
}
|
|
486
652
|
this.cache = void 0;
|
|
487
653
|
}
|
|
488
654
|
};
|
|
655
|
+
/** Group aliases by expanded private-key path in a single pass. */
|
|
656
|
+
function buildUsedByPathMap(hosts) {
|
|
657
|
+
const usedByPath = /* @__PURE__ */ new Map();
|
|
658
|
+
for (const host of hosts) {
|
|
659
|
+
if (host.auth.kind !== "key" || !host.auth.keyPath) continue;
|
|
660
|
+
const resolvedPath = expandHome(host.auth.keyPath);
|
|
661
|
+
const existing = usedByPath.get(resolvedPath);
|
|
662
|
+
if (existing === void 0) usedByPath.set(resolvedPath, [host.alias]);
|
|
663
|
+
else existing.push(host.alias);
|
|
664
|
+
}
|
|
665
|
+
return usedByPath;
|
|
666
|
+
}
|
|
489
667
|
/** Normalize an agent endpoint for storage: trim, expand `~`, and resolve the SSH_AUTH_SOCK token. */
|
|
490
668
|
function normalizeAgentPath(agentPath) {
|
|
491
669
|
const trimmed = agentPath?.trim();
|
|
@@ -516,6 +694,16 @@ function parseForwardAgentValue(raw) {
|
|
|
516
694
|
const value = raw?.trim().toLowerCase();
|
|
517
695
|
return value === "yes" || value === "true" || value === "on";
|
|
518
696
|
}
|
|
697
|
+
function requiredKeyName(value) {
|
|
698
|
+
if (typeof value !== "string" || value.trim() === "") throw new Error("key name is required");
|
|
699
|
+
return value.trim();
|
|
700
|
+
}
|
|
701
|
+
function requiredKeyPath(value) {
|
|
702
|
+
if (typeof value !== "string" || value.trim() === "") throw new Error("key path is required");
|
|
703
|
+
const path = expandHome(value.trim());
|
|
704
|
+
if (!isAbsolute(path)) throw new Error("key path must be absolute");
|
|
705
|
+
return path;
|
|
706
|
+
}
|
|
519
707
|
/** Expand a leading `~` in a filesystem path. */
|
|
520
708
|
function expandHome(path) {
|
|
521
709
|
if (path === "~") return homedir();
|
|
@@ -592,8 +780,15 @@ function startProxyCommand(rawCommand, target) {
|
|
|
592
780
|
stderr = (stderr + chunk.toString("utf8")).slice(-4096);
|
|
593
781
|
});
|
|
594
782
|
let killed = false;
|
|
783
|
+
let exited = false;
|
|
784
|
+
let escalateTimer;
|
|
785
|
+
const clearEscalate = () => {
|
|
786
|
+
if (escalateTimer === void 0) return;
|
|
787
|
+
clearTimeout(escalateTimer);
|
|
788
|
+
escalateTimer = void 0;
|
|
789
|
+
};
|
|
595
790
|
const kill = () => {
|
|
596
|
-
if (killed) return;
|
|
791
|
+
if (killed || exited || child.exitCode !== null || child.signalCode !== null) return;
|
|
597
792
|
killed = true;
|
|
598
793
|
const pid = child.pid;
|
|
599
794
|
const group = process.platform !== "win32" && pid !== void 0;
|
|
@@ -601,12 +796,15 @@ function startProxyCommand(rawCommand, target) {
|
|
|
601
796
|
if (group) process.kill(-pid, "SIGTERM");
|
|
602
797
|
else child.kill();
|
|
603
798
|
} catch {}
|
|
604
|
-
setTimeout(() => {
|
|
799
|
+
escalateTimer = setTimeout(() => {
|
|
800
|
+
escalateTimer = void 0;
|
|
801
|
+
if (exited || child.exitCode !== null || child.signalCode !== null) return;
|
|
605
802
|
try {
|
|
606
803
|
if (group) process.kill(-pid, "SIGKILL");
|
|
607
804
|
else child.kill("SIGKILL");
|
|
608
805
|
} catch {}
|
|
609
|
-
}, KILL_GRACE_MS)
|
|
806
|
+
}, KILL_GRACE_MS);
|
|
807
|
+
escalateTimer.unref();
|
|
610
808
|
};
|
|
611
809
|
function formatExitError(code, signal, stderrDetail) {
|
|
612
810
|
const status = signal !== null ? "signal " + signal : "code " + String(code ?? "unknown");
|
|
@@ -679,7 +877,6 @@ function startProxyCommand(rawCommand, target) {
|
|
|
679
877
|
stream.destroy(error);
|
|
680
878
|
};
|
|
681
879
|
let stdoutEnded = false;
|
|
682
|
-
let exited = false;
|
|
683
880
|
const finishIfClean = () => {
|
|
684
881
|
if (exited && stdoutEnded && !failed && !stream.destroyed) stream.push(null);
|
|
685
882
|
};
|
|
@@ -693,25 +890,34 @@ function startProxyCommand(rawCommand, target) {
|
|
|
693
890
|
child.stdout?.on("error", (error) => {
|
|
694
891
|
fail(/* @__PURE__ */ new Error("ProxyCommand stdout error: " + error.message));
|
|
695
892
|
});
|
|
893
|
+
let stdinErrorPending = false;
|
|
696
894
|
child.stdin?.on("error", (error) => {
|
|
697
895
|
if (child.exitCode !== null && child.exitCode !== 0 || child.signalCode !== null) {
|
|
698
896
|
fail(formatExitError(child.exitCode, child.signalCode, stderr));
|
|
699
897
|
return;
|
|
700
898
|
}
|
|
899
|
+
if (exited || child.exitCode !== null || stdinErrorPending || failed || stream.destroyed) return;
|
|
900
|
+
stdinErrorPending = true;
|
|
901
|
+
const onExit = (code, signal) => {
|
|
902
|
+
stdinErrorPending = false;
|
|
903
|
+
clearTimeout(timer);
|
|
904
|
+
if (code !== null && code !== 0 || signal !== null) fail(formatExitError(code, signal, stderr));
|
|
905
|
+
};
|
|
701
906
|
const timer = setTimeout(() => {
|
|
907
|
+
stdinErrorPending = false;
|
|
908
|
+
child.removeListener("exit", onExit);
|
|
702
909
|
fail(/* @__PURE__ */ new Error("ProxyCommand transport error: " + error.message));
|
|
703
910
|
}, 200);
|
|
704
911
|
timer.unref();
|
|
705
|
-
child.once("exit",
|
|
706
|
-
clearTimeout(timer);
|
|
707
|
-
if (code !== null && code !== 0 || signal !== null) fail(formatExitError(code, signal, stderr));
|
|
708
|
-
});
|
|
912
|
+
child.once("exit", onExit);
|
|
709
913
|
});
|
|
710
914
|
child.on("error", (error) => {
|
|
915
|
+
clearEscalate();
|
|
711
916
|
fail(/* @__PURE__ */ new Error("ProxyCommand could not start: " + error.message));
|
|
712
917
|
});
|
|
713
918
|
child.on("exit", (code, signal) => {
|
|
714
919
|
exited = true;
|
|
920
|
+
clearEscalate();
|
|
715
921
|
if (code !== null && code !== 0 || signal !== null) {
|
|
716
922
|
fail(formatExitError(code, signal, stderr));
|
|
717
923
|
return;
|
|
@@ -846,14 +1052,19 @@ function connectClient(config, onKeyboardInteractive) {
|
|
|
846
1052
|
const cause = error instanceof Error ? error : new Error(String(error));
|
|
847
1053
|
reject(isReadyTimeout(cause) ? new Error(readyTimeoutMessage(config.readyTimeout, handshakeComplete)) : cause);
|
|
848
1054
|
};
|
|
1055
|
+
const onPreReadyClose = () => {
|
|
1056
|
+
fail(/* @__PURE__ */ new Error("SSH connection closed before ready"));
|
|
1057
|
+
};
|
|
849
1058
|
client.once("handshake", () => {
|
|
850
1059
|
handshakeComplete = true;
|
|
851
1060
|
});
|
|
852
1061
|
client.once("ready", () => {
|
|
853
1062
|
if (settled) return;
|
|
854
1063
|
settled = true;
|
|
1064
|
+
client.removeListener?.("close", onPreReadyClose);
|
|
855
1065
|
resolve(client);
|
|
856
1066
|
});
|
|
1067
|
+
client.once("close", onPreReadyClose);
|
|
857
1068
|
client.on("keyboard-interactive", (name, instructions, instructionsLang, prompts, finish) => {
|
|
858
1069
|
if (onKeyboardInteractive !== void 0) {
|
|
859
1070
|
onKeyboardInteractive(name, instructions, instructionsLang, prompts.map((p) => ({
|
|
@@ -876,17 +1087,40 @@ function connectClient(config, onKeyboardInteractive) {
|
|
|
876
1087
|
}
|
|
877
1088
|
});
|
|
878
1089
|
}
|
|
879
|
-
/**
|
|
880
|
-
function
|
|
881
|
-
if (
|
|
882
|
-
if (
|
|
883
|
-
|
|
884
|
-
|
|
1090
|
+
/** Truncate `text` so its UTF-8 encoding fits within `maxBytes` without splitting code points. */
|
|
1091
|
+
function sliceUtf8ToBytes(text, maxBytes) {
|
|
1092
|
+
if (maxBytes <= 0 || text === "") return "";
|
|
1093
|
+
if (Buffer.byteLength(text, "utf8") <= maxBytes) return text;
|
|
1094
|
+
let bytes = 0;
|
|
1095
|
+
let end = 0;
|
|
1096
|
+
for (const char of text) {
|
|
1097
|
+
const code = char.codePointAt(0);
|
|
1098
|
+
const charBytes = code < 128 ? 1 : code < 2048 ? 2 : code < 65536 ? 3 : 4;
|
|
1099
|
+
if (bytes + charBytes > maxBytes) break;
|
|
1100
|
+
bytes += charBytes;
|
|
1101
|
+
end += char.length;
|
|
1102
|
+
}
|
|
1103
|
+
return text.slice(0, end);
|
|
1104
|
+
}
|
|
1105
|
+
/** Append an already-decoded string chunk under a UTF-8 byte budget. */
|
|
1106
|
+
function appendDecodedOutput(target, decoded, maxBytes) {
|
|
1107
|
+
if (target.truncated || decoded === "") return;
|
|
1108
|
+
const usedBytes = target.bytes ?? Buffer.byteLength(target.text, "utf8");
|
|
1109
|
+
const decodedBytes = Buffer.byteLength(decoded, "utf8");
|
|
1110
|
+
if (usedBytes + decodedBytes > maxBytes) {
|
|
1111
|
+
const cut = sliceUtf8ToBytes(decoded, maxBytes - usedBytes);
|
|
885
1112
|
target.text += cut + "…[output truncated]";
|
|
1113
|
+
target.bytes = maxBytes;
|
|
886
1114
|
target.truncated = true;
|
|
887
1115
|
return;
|
|
888
1116
|
}
|
|
889
|
-
target.text +=
|
|
1117
|
+
target.text += decoded;
|
|
1118
|
+
target.bytes = usedBytes + decodedBytes;
|
|
1119
|
+
}
|
|
1120
|
+
/** Cap captured output at the configured UTF-8 byte budget (marks truncation). */
|
|
1121
|
+
function appendOutput(target, chunk, maxBytes, decoder) {
|
|
1122
|
+
if (target.truncated) return;
|
|
1123
|
+
appendDecodedOutput(target, decoder !== void 0 ? decoder.write(chunk) : chunk.toString("utf8"), maxBytes);
|
|
890
1124
|
}
|
|
891
1125
|
/** The ProxyCommand token source for one entry. */
|
|
892
1126
|
function proxyTargetOf(entry) {
|
|
@@ -1035,8 +1269,36 @@ async function connectChain(engine, entry, onKeyboardInteractive) {
|
|
|
1035
1269
|
throw error;
|
|
1036
1270
|
}
|
|
1037
1271
|
}
|
|
1272
|
+
const poolLifecycles = /* @__PURE__ */ new WeakMap();
|
|
1273
|
+
function lifecycleOf(engine) {
|
|
1274
|
+
let state = poolLifecycles.get(engine);
|
|
1275
|
+
if (state === void 0) {
|
|
1276
|
+
state = {
|
|
1277
|
+
disposed: false,
|
|
1278
|
+
generations: /* @__PURE__ */ new Map()
|
|
1279
|
+
};
|
|
1280
|
+
poolLifecycles.set(engine, state);
|
|
1281
|
+
}
|
|
1282
|
+
return state;
|
|
1283
|
+
}
|
|
1284
|
+
/**
|
|
1285
|
+
* Invalidate any in-flight acquire for `alias` so a connection still handshaking
|
|
1286
|
+
* under stale config or before a delete cannot enter `engine.pool` after completion.
|
|
1287
|
+
*/
|
|
1288
|
+
function invalidateAlias(engine, alias) {
|
|
1289
|
+
const state = lifecycleOf(engine);
|
|
1290
|
+
state.generations.set(alias, (state.generations.get(alias) ?? 0) + 1);
|
|
1291
|
+
engine.acquireQueue.delete(alias);
|
|
1292
|
+
}
|
|
1293
|
+
/** Mark the pool disposed so in-flight acquires tear down instead of entering the pool. */
|
|
1294
|
+
function markPoolDisposed(engine) {
|
|
1295
|
+
const state = lifecycleOf(engine);
|
|
1296
|
+
state.disposed = true;
|
|
1297
|
+
engine.acquireQueue.clear();
|
|
1298
|
+
}
|
|
1038
1299
|
/** Connect (or reuse) the pooled chain for one alias; pins nothing. */
|
|
1039
1300
|
async function acquire(engine, alias) {
|
|
1301
|
+
if (lifecycleOf(engine).disposed) throw new Error("ssh engine has been disposed");
|
|
1040
1302
|
const pending = engine.acquireQueue.get(alias);
|
|
1041
1303
|
if (pending !== void 0) return pending;
|
|
1042
1304
|
const task = doAcquire(engine, alias);
|
|
@@ -1048,6 +1310,9 @@ async function acquire(engine, alias) {
|
|
|
1048
1310
|
}
|
|
1049
1311
|
}
|
|
1050
1312
|
async function doAcquire(engine, alias) {
|
|
1313
|
+
const state = lifecycleOf(engine);
|
|
1314
|
+
if (state.disposed) throw new Error("ssh engine has been disposed");
|
|
1315
|
+
const gen = state.generations.get(alias) ?? 0;
|
|
1051
1316
|
const entry = engine.store.find(alias);
|
|
1052
1317
|
if (entry === void 0) throw new Error("alias '" + alias + "' not found — add it first");
|
|
1053
1318
|
const { client, hops } = await connectChain(engine, entry);
|
|
@@ -1059,12 +1324,25 @@ async function doAcquire(engine, alias) {
|
|
|
1059
1324
|
broken: false,
|
|
1060
1325
|
inFlight: 0
|
|
1061
1326
|
};
|
|
1062
|
-
|
|
1327
|
+
if (state.disposed || (state.generations.get(alias) ?? 0) !== gen) {
|
|
1328
|
+
endRecordChain(record);
|
|
1329
|
+
throw new Error(state.disposed ? "ssh engine disposed while connecting '" + alias + "'" : "host '" + alias + "' configuration changed while connecting");
|
|
1330
|
+
}
|
|
1331
|
+
const markBroken = () => {
|
|
1063
1332
|
record.broken = true;
|
|
1064
|
-
}
|
|
1065
|
-
|
|
1333
|
+
};
|
|
1334
|
+
const onTargetClosed = () => {
|
|
1066
1335
|
record.broken = true;
|
|
1067
|
-
|
|
1336
|
+
for (const hop of record.hops) try {
|
|
1337
|
+
hop.end();
|
|
1338
|
+
} catch {}
|
|
1339
|
+
};
|
|
1340
|
+
client.on("error", markBroken);
|
|
1341
|
+
client.on("close", onTargetClosed);
|
|
1342
|
+
for (const hop of hops) {
|
|
1343
|
+
hop.on("error", markBroken);
|
|
1344
|
+
hop.on("close", markBroken);
|
|
1345
|
+
}
|
|
1068
1346
|
engine.pool.set(alias, record);
|
|
1069
1347
|
return record;
|
|
1070
1348
|
}
|
|
@@ -1094,6 +1372,32 @@ function sweepPool(engine) {
|
|
|
1094
1372
|
const cutoff = Date.now() - engine.opts.idleTimeoutMs;
|
|
1095
1373
|
for (const [alias, record] of engine.pool) if (!record.pinned && record.inFlight === 0 && record.idleAt < cutoff) disposeRecord(engine, alias, record);
|
|
1096
1374
|
}
|
|
1375
|
+
/** Read live abort state through a function call so TypeScript does not narrow across `await`. */
|
|
1376
|
+
function isAborted(signal) {
|
|
1377
|
+
return signal?.aborted === true;
|
|
1378
|
+
}
|
|
1379
|
+
/** Race an in-flight promise against an optional AbortSignal without leaving an unhandled rejection behind. */
|
|
1380
|
+
function waitWithSignal(promise, signal) {
|
|
1381
|
+
if (signal === void 0) return promise;
|
|
1382
|
+
if (signal.aborted) {
|
|
1383
|
+
promise.catch(() => void 0);
|
|
1384
|
+
return Promise.reject(/* @__PURE__ */ new Error("command cancelled by the caller"));
|
|
1385
|
+
}
|
|
1386
|
+
return new Promise((resolve, reject) => {
|
|
1387
|
+
const onAbort = () => {
|
|
1388
|
+
promise.catch(() => void 0);
|
|
1389
|
+
reject(/* @__PURE__ */ new Error("command cancelled by the caller"));
|
|
1390
|
+
};
|
|
1391
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1392
|
+
promise.then((value) => {
|
|
1393
|
+
signal.removeEventListener("abort", onAbort);
|
|
1394
|
+
resolve(value);
|
|
1395
|
+
}, (error) => {
|
|
1396
|
+
signal.removeEventListener("abort", onAbort);
|
|
1397
|
+
reject(error);
|
|
1398
|
+
});
|
|
1399
|
+
});
|
|
1400
|
+
}
|
|
1097
1401
|
/**
|
|
1098
1402
|
* Run `fn` with a live client for `alias`, reconnecting (up to the
|
|
1099
1403
|
* attempt budget) when the connection broke mid-flight.
|
|
@@ -1101,10 +1405,11 @@ function sweepPool(engine) {
|
|
|
1101
1405
|
async function withClient(engine, alias, fn, attempts = 3, signal) {
|
|
1102
1406
|
let lastError;
|
|
1103
1407
|
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
|
1408
|
+
if (isAborted(signal)) throw new Error("command cancelled by the caller");
|
|
1104
1409
|
let record = engine.pool.get(alias);
|
|
1105
1410
|
if (record === void 0 || record.broken) {
|
|
1106
1411
|
if (record !== void 0) disposeRecord(engine, alias, record);
|
|
1107
|
-
record = await acquire(engine, alias);
|
|
1412
|
+
record = await waitWithSignal(acquire(engine, alias), signal);
|
|
1108
1413
|
}
|
|
1109
1414
|
record.idleAt = Date.now();
|
|
1110
1415
|
record.inFlight += 1;
|
|
@@ -1114,7 +1419,7 @@ async function withClient(engine, alias, fn, attempts = 3, signal) {
|
|
|
1114
1419
|
return result;
|
|
1115
1420
|
} catch (error) {
|
|
1116
1421
|
lastError = error;
|
|
1117
|
-
if (signal
|
|
1422
|
+
if (isAborted(signal)) throw error;
|
|
1118
1423
|
if (!record.broken) throw error;
|
|
1119
1424
|
disposeRecord(engine, alias, record);
|
|
1120
1425
|
} finally {
|
|
@@ -1126,41 +1431,41 @@ async function withClient(engine, alias, fn, attempts = 3, signal) {
|
|
|
1126
1431
|
/** Run one command on `alias` (reusing the pooled connection). */
|
|
1127
1432
|
async function execCommand(engine, alias, command, timeoutMs, signal) {
|
|
1128
1433
|
const started = Date.now();
|
|
1434
|
+
if (isAborted(signal)) return {
|
|
1435
|
+
success: false,
|
|
1436
|
+
exitCode: null,
|
|
1437
|
+
timedOut: false,
|
|
1438
|
+
stdout: "",
|
|
1439
|
+
stderr: "",
|
|
1440
|
+
durationMs: Date.now() - started,
|
|
1441
|
+
error: "command cancelled by the caller"
|
|
1442
|
+
};
|
|
1129
1443
|
const budget = timeoutMs !== void 0 && timeoutMs > 0 ? timeoutMs : engine.opts.defaultExecTimeoutMs;
|
|
1130
|
-
|
|
1131
|
-
return await
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
aborted = true;
|
|
1136
|
-
kill();
|
|
1137
|
-
};
|
|
1138
|
-
if (signal !== void 0 && !signal.aborted) signal.addEventListener("abort", onAbort, { once: true });
|
|
1139
|
-
client.exec(command, (error, stream) => {
|
|
1140
|
-
if (error !== void 0) {
|
|
1141
|
-
signal?.removeEventListener("abort", onAbort);
|
|
1142
|
-
reject(error);
|
|
1143
|
-
return;
|
|
1144
|
-
}
|
|
1145
|
-
kill = () => {
|
|
1146
|
-
try {
|
|
1147
|
-
stream.signal("KILL");
|
|
1148
|
-
} catch {}
|
|
1149
|
-
try {
|
|
1150
|
-
stream.close();
|
|
1151
|
-
} catch {}
|
|
1152
|
-
};
|
|
1153
|
-
if (aborted) kill();
|
|
1444
|
+
try {
|
|
1445
|
+
return await withClient(engine, alias, async (client) => {
|
|
1446
|
+
return await new Promise((resolve, reject) => {
|
|
1447
|
+
let aborted = signal !== void 0 && signal.aborted;
|
|
1448
|
+
let settled = false;
|
|
1154
1449
|
const stdout = {
|
|
1155
1450
|
text: "",
|
|
1156
|
-
truncated: false
|
|
1451
|
+
truncated: false,
|
|
1452
|
+
bytes: 0
|
|
1157
1453
|
};
|
|
1158
1454
|
const stderr = {
|
|
1159
1455
|
text: "",
|
|
1160
|
-
truncated: false
|
|
1456
|
+
truncated: false,
|
|
1457
|
+
bytes: 0
|
|
1161
1458
|
};
|
|
1162
|
-
|
|
1163
|
-
|
|
1459
|
+
const stdoutDecoder = new StringDecoder("utf8");
|
|
1460
|
+
const stderrDecoder = new StringDecoder("utf8");
|
|
1461
|
+
const flushDecoders = () => {
|
|
1462
|
+
const outTail = stdoutDecoder.end();
|
|
1463
|
+
if (outTail !== "") appendDecodedOutput(stdout, outTail, engine.opts.maxOutputBytes);
|
|
1464
|
+
const errTail = stderrDecoder.end();
|
|
1465
|
+
if (errTail !== "") appendDecodedOutput(stderr, errTail, engine.opts.maxOutputBytes);
|
|
1466
|
+
};
|
|
1467
|
+
let timer;
|
|
1468
|
+
let kill = () => {};
|
|
1164
1469
|
/** One cancelled outcome: the remote channel was killed on caller request. */
|
|
1165
1470
|
const cancelledResult = () => ({
|
|
1166
1471
|
success: false,
|
|
@@ -1171,69 +1476,126 @@ async function execCommand(engine, alias, command, timeoutMs, signal) {
|
|
|
1171
1476
|
durationMs: Date.now() - started,
|
|
1172
1477
|
error: "command cancelled by the caller"
|
|
1173
1478
|
});
|
|
1174
|
-
const
|
|
1479
|
+
const settleCancelled = () => {
|
|
1175
1480
|
if (settled) return;
|
|
1176
1481
|
settled = true;
|
|
1177
|
-
clearTimeout(timer);
|
|
1482
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
1178
1483
|
signal?.removeEventListener("abort", onAbort);
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
exitCode: null,
|
|
1182
|
-
timedOut,
|
|
1183
|
-
stdout: stdout.text,
|
|
1184
|
-
stderr: stderr.text,
|
|
1185
|
-
durationMs: Date.now() - started,
|
|
1186
|
-
error: timedOut ? "command timed out after " + budget + " ms" : void 0
|
|
1187
|
-
});
|
|
1484
|
+
flushDecoders();
|
|
1485
|
+
resolve(cancelledResult());
|
|
1188
1486
|
};
|
|
1189
|
-
const
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
resolve(cancelledResult());
|
|
1208
|
-
return;
|
|
1209
|
-
}
|
|
1210
|
-
if (typeof code !== "number" && !timedOut) {
|
|
1211
|
-
reject(/* @__PURE__ */ new Error("ssh: connection lost mid-flight (channel closed without an exit status)"));
|
|
1487
|
+
const onAbort = () => {
|
|
1488
|
+
aborted = true;
|
|
1489
|
+
kill();
|
|
1490
|
+
settleCancelled();
|
|
1491
|
+
};
|
|
1492
|
+
if (aborted) {
|
|
1493
|
+
settleCancelled();
|
|
1494
|
+
return;
|
|
1495
|
+
}
|
|
1496
|
+
if (signal !== void 0) signal.addEventListener("abort", onAbort, { once: true });
|
|
1497
|
+
client.exec(command, (error, stream) => {
|
|
1498
|
+
if (error !== void 0) {
|
|
1499
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1500
|
+
if (aborted) {
|
|
1501
|
+
settleCancelled();
|
|
1502
|
+
return;
|
|
1503
|
+
}
|
|
1504
|
+
reject(error);
|
|
1212
1505
|
return;
|
|
1213
1506
|
}
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
}
|
|
1222
|
-
});
|
|
1223
|
-
stream.on("error", (streamError) => {
|
|
1224
|
-
if (settled) return;
|
|
1225
|
-
settled = true;
|
|
1226
|
-
clearTimeout(timer);
|
|
1227
|
-
signal?.removeEventListener("abort", onAbort);
|
|
1507
|
+
kill = () => {
|
|
1508
|
+
try {
|
|
1509
|
+
stream.signal("KILL");
|
|
1510
|
+
} catch {}
|
|
1511
|
+
try {
|
|
1512
|
+
stream.close();
|
|
1513
|
+
} catch {}
|
|
1514
|
+
};
|
|
1228
1515
|
if (aborted) {
|
|
1229
|
-
|
|
1516
|
+
kill();
|
|
1517
|
+
settleCancelled();
|
|
1230
1518
|
return;
|
|
1231
1519
|
}
|
|
1232
|
-
|
|
1520
|
+
let timedOut = false;
|
|
1521
|
+
const finish = () => {
|
|
1522
|
+
if (settled) return;
|
|
1523
|
+
settled = true;
|
|
1524
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
1525
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1526
|
+
flushDecoders();
|
|
1527
|
+
resolve({
|
|
1528
|
+
success: false,
|
|
1529
|
+
exitCode: null,
|
|
1530
|
+
timedOut,
|
|
1531
|
+
stdout: stdout.text,
|
|
1532
|
+
stderr: stderr.text,
|
|
1533
|
+
durationMs: Date.now() - started,
|
|
1534
|
+
error: timedOut ? "command timed out after " + budget + " ms" : void 0
|
|
1535
|
+
});
|
|
1536
|
+
};
|
|
1537
|
+
timer = setTimeout(() => {
|
|
1538
|
+
timedOut = true;
|
|
1539
|
+
try {
|
|
1540
|
+
stream.signal("KILL");
|
|
1541
|
+
} catch {}
|
|
1542
|
+
try {
|
|
1543
|
+
stream.close();
|
|
1544
|
+
} catch {}
|
|
1545
|
+
finish();
|
|
1546
|
+
}, budget);
|
|
1547
|
+
stream.on("data", (chunk) => appendOutput(stdout, chunk, engine.opts.maxOutputBytes, stdoutDecoder));
|
|
1548
|
+
stream.stderr.on("data", (chunk) => appendOutput(stderr, chunk, engine.opts.maxOutputBytes, stderrDecoder));
|
|
1549
|
+
stream.on("close", (code) => {
|
|
1550
|
+
if (settled) return;
|
|
1551
|
+
settled = true;
|
|
1552
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
1553
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1554
|
+
flushDecoders();
|
|
1555
|
+
if (aborted) {
|
|
1556
|
+
resolve(cancelledResult());
|
|
1557
|
+
return;
|
|
1558
|
+
}
|
|
1559
|
+
if (typeof code !== "number" && !timedOut) {
|
|
1560
|
+
reject(/* @__PURE__ */ new Error("ssh: connection lost mid-flight (channel closed without an exit status)"));
|
|
1561
|
+
return;
|
|
1562
|
+
}
|
|
1563
|
+
resolve({
|
|
1564
|
+
success: code === 0,
|
|
1565
|
+
exitCode: code,
|
|
1566
|
+
timedOut,
|
|
1567
|
+
stdout: stdout.text,
|
|
1568
|
+
stderr: stderr.text,
|
|
1569
|
+
durationMs: Date.now() - started
|
|
1570
|
+
});
|
|
1571
|
+
});
|
|
1572
|
+
stream.on("error", (streamError) => {
|
|
1573
|
+
if (settled) return;
|
|
1574
|
+
settled = true;
|
|
1575
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
1576
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1577
|
+
flushDecoders();
|
|
1578
|
+
if (aborted) {
|
|
1579
|
+
resolve(cancelledResult());
|
|
1580
|
+
return;
|
|
1581
|
+
}
|
|
1582
|
+
reject(streamError);
|
|
1583
|
+
});
|
|
1233
1584
|
});
|
|
1234
1585
|
});
|
|
1235
|
-
});
|
|
1236
|
-
})
|
|
1586
|
+
}, void 0, signal);
|
|
1587
|
+
} catch (error) {
|
|
1588
|
+
if (isAborted(signal)) return {
|
|
1589
|
+
success: false,
|
|
1590
|
+
exitCode: null,
|
|
1591
|
+
timedOut: false,
|
|
1592
|
+
stdout: "",
|
|
1593
|
+
stderr: "",
|
|
1594
|
+
durationMs: Date.now() - started,
|
|
1595
|
+
error: "command cancelled by the caller"
|
|
1596
|
+
};
|
|
1597
|
+
throw error;
|
|
1598
|
+
}
|
|
1237
1599
|
}
|
|
1238
1600
|
//#endregion
|
|
1239
1601
|
//#region src/engine/pty.ts
|
|
@@ -1350,20 +1712,24 @@ async function upload(engine, alias, localPath, remotePath, recursive, onProgres
|
|
|
1350
1712
|
if (!existsSync(local)) throw new Error("local path not found: '" + localPath + "'");
|
|
1351
1713
|
return withClient(engine, alias, (client) => withSftp(client, async (sftp) => {
|
|
1352
1714
|
const stat = statSync(local);
|
|
1715
|
+
const ensuredDirs = /* @__PURE__ */ new Set();
|
|
1353
1716
|
let files;
|
|
1354
1717
|
if (stat.isDirectory()) {
|
|
1355
1718
|
if (!recursive) throw new Error("'" + localPath + "' is a directory — enable recursive upload");
|
|
1356
1719
|
files = walkLocalDir(local);
|
|
1357
|
-
await ensureRemoteDir(sftp, remotePath);
|
|
1720
|
+
await ensureRemoteDir(sftp, remotePath, ensuredDirs);
|
|
1358
1721
|
} else {
|
|
1359
1722
|
files = [""];
|
|
1360
|
-
await ensureRemoteDir(sftp, dirname(remotePath));
|
|
1723
|
+
await ensureRemoteDir(sftp, posix.dirname(remotePath), ensuredDirs);
|
|
1361
1724
|
}
|
|
1362
1725
|
let bytes = 0;
|
|
1726
|
+
const baseRemote = remotePath.replace(/\/$/, "");
|
|
1363
1727
|
for (const rel of files) {
|
|
1364
1728
|
const src = rel === "" ? local : join(local, rel);
|
|
1365
1729
|
const remoteRel = rel.split(/[\\/]/).join("/");
|
|
1366
|
-
|
|
1730
|
+
const dst = rel === "" ? remotePath : baseRemote + "/" + remoteRel;
|
|
1731
|
+
if (rel !== "") await ensureRemoteDir(sftp, posix.dirname(dst), ensuredDirs);
|
|
1732
|
+
await fastPut(sftp, src, dst, engine.opts.sftpConcurrency, onProgress);
|
|
1367
1733
|
bytes += statSync(src).size;
|
|
1368
1734
|
}
|
|
1369
1735
|
return {
|
|
@@ -1432,33 +1798,54 @@ function sftpChannel(client) {
|
|
|
1432
1798
|
client.sftp((error, sftp) => error !== void 0 ? reject(error) : resolve(sftp));
|
|
1433
1799
|
});
|
|
1434
1800
|
}
|
|
1435
|
-
|
|
1436
|
-
|
|
1801
|
+
function normalizeRemoteDir(remote) {
|
|
1802
|
+
const cleaned = remote.replace(/\/+$/, "");
|
|
1803
|
+
return cleaned === "" ? "/" : cleaned;
|
|
1804
|
+
}
|
|
1805
|
+
function recordEnsuredPrefixes(segments, upToIndex, ensuredDirs) {
|
|
1806
|
+
if (ensuredDirs === void 0) return;
|
|
1807
|
+
for (let index = 0; index <= upToIndex; index += 1) ensuredDirs.add("/" + segments.slice(0, index + 1).join("/"));
|
|
1808
|
+
}
|
|
1809
|
+
function statRemote(sftp, path) {
|
|
1810
|
+
return new Promise((resolve) => {
|
|
1811
|
+
sftp.stat(path, (error) => {
|
|
1812
|
+
resolve(error === void 0);
|
|
1813
|
+
});
|
|
1814
|
+
});
|
|
1815
|
+
}
|
|
1816
|
+
function mkdirRemote(sftp, path) {
|
|
1437
1817
|
return new Promise((resolve, reject) => {
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
return;
|
|
1443
|
-
}
|
|
1444
|
-
const current = "/" + segments.slice(0, index + 1).join("/");
|
|
1445
|
-
sftp.stat(current, (statError) => {
|
|
1446
|
-
if (statError === void 0) {
|
|
1447
|
-
walk(index + 1);
|
|
1448
|
-
return;
|
|
1449
|
-
}
|
|
1450
|
-
sftp.mkdir(current, (mkdirError) => {
|
|
1451
|
-
if (mkdirError !== void 0) {
|
|
1452
|
-
reject(mkdirError);
|
|
1453
|
-
return;
|
|
1454
|
-
}
|
|
1455
|
-
walk(index + 1);
|
|
1456
|
-
});
|
|
1457
|
-
});
|
|
1458
|
-
};
|
|
1459
|
-
walk(0);
|
|
1818
|
+
sftp.mkdir(path, (error) => {
|
|
1819
|
+
if (error !== void 0) reject(error);
|
|
1820
|
+
else resolve();
|
|
1821
|
+
});
|
|
1460
1822
|
});
|
|
1461
1823
|
}
|
|
1824
|
+
/** Create a remote directory chain (with a 1-RTT stat fast path and prefix cache). */
|
|
1825
|
+
async function ensureRemoteDir(sftp, remote, ensuredDirs) {
|
|
1826
|
+
const normalized = normalizeRemoteDir(remote);
|
|
1827
|
+
if (normalized === "/" || ensuredDirs?.has(normalized) === true) return;
|
|
1828
|
+
const segments = normalized.slice(1).split("/").filter((segment) => segment !== "");
|
|
1829
|
+
if (segments.length === 0) return;
|
|
1830
|
+
if (segments.length > 1 && await statRemote(sftp, normalized)) {
|
|
1831
|
+
recordEnsuredPrefixes(segments, segments.length - 1, ensuredDirs);
|
|
1832
|
+
return;
|
|
1833
|
+
}
|
|
1834
|
+
for (let index = 0; index < segments.length; index += 1) {
|
|
1835
|
+
const current = "/" + segments.slice(0, index + 1).join("/");
|
|
1836
|
+
if (ensuredDirs?.has(current) === true) continue;
|
|
1837
|
+
if (!(segments.length > 1 && index === segments.length - 1) && await statRemote(sftp, current)) {
|
|
1838
|
+
ensuredDirs?.add(current);
|
|
1839
|
+
continue;
|
|
1840
|
+
}
|
|
1841
|
+
try {
|
|
1842
|
+
await mkdirRemote(sftp, current);
|
|
1843
|
+
} catch (error) {
|
|
1844
|
+
if (!await statRemote(sftp, current)) throw error;
|
|
1845
|
+
}
|
|
1846
|
+
ensuredDirs?.add(current);
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1462
1849
|
/** One fastPut/fastGet transfer with throttled progress (the two directions share everything but the verb). */
|
|
1463
1850
|
function fastTransfer(sftp, kind, src, dst, concurrency, onProgress) {
|
|
1464
1851
|
return new Promise((resolve, reject) => {
|
|
@@ -1466,7 +1853,7 @@ function fastTransfer(sftp, kind, src, dst, concurrency, onProgress) {
|
|
|
1466
1853
|
const finalSize = () => statSync(kind === "put" ? src : dst).size;
|
|
1467
1854
|
let last = 0;
|
|
1468
1855
|
let lastEmit = 0;
|
|
1469
|
-
|
|
1856
|
+
let prevEmit = Date.now();
|
|
1470
1857
|
if (kind === "put") onProgress?.({
|
|
1471
1858
|
phase: "transferring",
|
|
1472
1859
|
file,
|
|
@@ -1478,19 +1865,20 @@ function fastTransfer(sftp, kind, src, dst, concurrency, onProgress) {
|
|
|
1478
1865
|
const now = Date.now();
|
|
1479
1866
|
if (now - lastEmit < 100 && transferred < total) return;
|
|
1480
1867
|
lastEmit = now;
|
|
1481
|
-
const
|
|
1868
|
+
const windowSec = (now - prevEmit) / 1e3;
|
|
1482
1869
|
onProgress?.({
|
|
1483
1870
|
phase: "transferring",
|
|
1484
1871
|
file,
|
|
1485
1872
|
transferred,
|
|
1486
1873
|
total,
|
|
1487
1874
|
percent: total > 0 ? Math.round(transferred / total * 1e3) / 10 : 0,
|
|
1488
|
-
speedBps:
|
|
1875
|
+
speedBps: windowSec > 0 ? Math.round((transferred - last) / windowSec) : void 0
|
|
1489
1876
|
});
|
|
1877
|
+
prevEmit = now;
|
|
1490
1878
|
last = transferred;
|
|
1491
1879
|
};
|
|
1492
1880
|
const done = (error) => {
|
|
1493
|
-
if (error !== void 0) {
|
|
1881
|
+
if (error !== void 0 && error !== null) {
|
|
1494
1882
|
onProgress?.({
|
|
1495
1883
|
phase: "error",
|
|
1496
1884
|
file,
|
|
@@ -1501,11 +1889,12 @@ function fastTransfer(sftp, kind, src, dst, concurrency, onProgress) {
|
|
|
1501
1889
|
});
|
|
1502
1890
|
reject(error);
|
|
1503
1891
|
} else {
|
|
1892
|
+
const size = finalSize();
|
|
1504
1893
|
onProgress?.({
|
|
1505
1894
|
phase: "done",
|
|
1506
1895
|
file,
|
|
1507
|
-
transferred:
|
|
1508
|
-
total:
|
|
1896
|
+
transferred: size,
|
|
1897
|
+
total: size,
|
|
1509
1898
|
percent: 100
|
|
1510
1899
|
});
|
|
1511
1900
|
resolve();
|
|
@@ -1596,6 +1985,13 @@ async function startTunnel(engine, alias, options) {
|
|
|
1596
1985
|
destroyQuietly(socket);
|
|
1597
1986
|
return;
|
|
1598
1987
|
}
|
|
1988
|
+
if (socket.destroyed) {
|
|
1989
|
+
try {
|
|
1990
|
+
stream.close();
|
|
1991
|
+
} catch {}
|
|
1992
|
+
destroyQuietly(stream);
|
|
1993
|
+
return;
|
|
1994
|
+
}
|
|
1599
1995
|
const destroy = () => {
|
|
1600
1996
|
destroyQuietly(socket);
|
|
1601
1997
|
try {
|
|
@@ -1613,6 +2009,7 @@ async function startTunnel(engine, alias, options) {
|
|
|
1613
2009
|
abortTunnel(engine, id);
|
|
1614
2010
|
}
|
|
1615
2011
|
});
|
|
2012
|
+
record.inFlight += 1;
|
|
1616
2013
|
try {
|
|
1617
2014
|
await new Promise((resolve, reject) => {
|
|
1618
2015
|
server.once("error", reject);
|
|
@@ -1622,10 +2019,15 @@ async function startTunnel(engine, alias, options) {
|
|
|
1622
2019
|
});
|
|
1623
2020
|
});
|
|
1624
2021
|
} catch (error) {
|
|
2022
|
+
record.inFlight -= 1;
|
|
1625
2023
|
if (!record.pinned && record.inFlight === 0) disposeRecord(engine, alias, record);
|
|
1626
2024
|
throw error;
|
|
1627
2025
|
}
|
|
1628
2026
|
record.pinned = true;
|
|
2027
|
+
record.inFlight -= 1;
|
|
2028
|
+
server.on("error", () => {
|
|
2029
|
+
abortTunnel(engine, id);
|
|
2030
|
+
});
|
|
1629
2031
|
const address = server.address();
|
|
1630
2032
|
info.localPort = typeof address === "object" && address !== null ? address.port : 0;
|
|
1631
2033
|
info.state = "forwarding";
|
|
@@ -1662,7 +2064,10 @@ function stopTunnel(engine, id) {
|
|
|
1662
2064
|
} catch {}
|
|
1663
2065
|
for (const socket of tunnel.sockets) destroyQuietly(socket);
|
|
1664
2066
|
tunnel.sockets.clear();
|
|
1665
|
-
if (![...engine.tunnels.values()].some((candidate) => candidate.record === tunnel.record)) if (engine.pool.get(tunnel.alias) === tunnel.record)
|
|
2067
|
+
if (![...engine.tunnels.values()].some((candidate) => candidate.record === tunnel.record)) if (engine.pool.get(tunnel.alias) === tunnel.record) if (!tunnel.record.broken && tunnel.record.inFlight > 0) {
|
|
2068
|
+
tunnel.record.pinned = false;
|
|
2069
|
+
tunnel.record.idleAt = Date.now();
|
|
2070
|
+
} else disposeRecord(engine, tunnel.alias, tunnel.record);
|
|
1666
2071
|
else endRecordChain(tunnel.record);
|
|
1667
2072
|
return true;
|
|
1668
2073
|
}
|
|
@@ -1677,16 +2082,32 @@ function stopAllTunnels(engine, alias) {
|
|
|
1677
2082
|
}
|
|
1678
2083
|
//#endregion
|
|
1679
2084
|
//#region src/engine/cluster.ts
|
|
2085
|
+
function normalizeStringList(values) {
|
|
2086
|
+
if (!Array.isArray(values)) return void 0;
|
|
2087
|
+
return values.filter((value) => typeof value === "string").map((value) => value.trim()).filter((value) => value !== "");
|
|
2088
|
+
}
|
|
2089
|
+
/** Whether at least one trimmed non-empty cluster target filter is present. */
|
|
2090
|
+
function hasClusterSelector(options) {
|
|
2091
|
+
const aliases = normalizeStringList(options.aliases);
|
|
2092
|
+
if (aliases !== void 0 && aliases.length > 0) return true;
|
|
2093
|
+
if (typeof options.environment === "string" && options.environment.trim() !== "") return true;
|
|
2094
|
+
const tags = normalizeStringList(options.tags);
|
|
2095
|
+
return tags !== void 0 && tags.length > 0;
|
|
2096
|
+
}
|
|
1680
2097
|
/** Run one command against many hosts concurrently. */
|
|
1681
2098
|
async function cluster(engine, options) {
|
|
1682
|
-
const
|
|
1683
|
-
const
|
|
1684
|
-
const
|
|
1685
|
-
if (!
|
|
2099
|
+
const aliases = normalizeStringList(options.aliases);
|
|
2100
|
+
const environment = typeof options.environment === "string" && options.environment.trim() !== "" ? options.environment.trim() : void 0;
|
|
2101
|
+
const tags = normalizeStringList(options.tags);
|
|
2102
|
+
if (!hasClusterSelector({
|
|
2103
|
+
aliases,
|
|
2104
|
+
environment,
|
|
2105
|
+
tags
|
|
2106
|
+
})) throw new Error("ssh_cluster requires aliases, environment, or tags to limit the target set");
|
|
1686
2107
|
let targets = engine.store.list();
|
|
1687
|
-
if (
|
|
1688
|
-
if (
|
|
1689
|
-
if (
|
|
2108
|
+
if (aliases !== void 0 && aliases.length > 0) targets = targets.filter((entry) => aliases.includes(entry.alias));
|
|
2109
|
+
if (environment !== void 0) targets = targets.filter((entry) => entry.environment === environment);
|
|
2110
|
+
if (tags !== void 0 && tags.length > 0) targets = targets.filter((entry) => tags.every((tag) => entry.tags.includes(tag)));
|
|
1690
2111
|
if (targets.length === 0) return [];
|
|
1691
2112
|
if (options.maxWorkers !== void 0 && (!Number.isInteger(options.maxWorkers) || options.maxWorkers < 1)) throw new Error("maxWorkers must be a positive integer");
|
|
1692
2113
|
const workers = Math.min(engine.opts.defaultMaxWorkers, options.maxWorkers ?? engine.opts.defaultMaxWorkers, targets.length);
|
|
@@ -1704,7 +2125,8 @@ async function cluster(engine, options) {
|
|
|
1704
2125
|
timedOut: result.timedOut,
|
|
1705
2126
|
stdout: result.stdout,
|
|
1706
2127
|
stderr: result.stderr,
|
|
1707
|
-
durationMs: result.durationMs
|
|
2128
|
+
durationMs: result.durationMs,
|
|
2129
|
+
...result.error !== void 0 ? { error: result.error } : {}
|
|
1708
2130
|
});
|
|
1709
2131
|
} catch (error) {
|
|
1710
2132
|
results.push({
|
|
@@ -1756,8 +2178,7 @@ var SshEngine = class {
|
|
|
1756
2178
|
}
|
|
1757
2179
|
/** Secret-free host list (filtered by the optional query). */
|
|
1758
2180
|
list(query) {
|
|
1759
|
-
|
|
1760
|
-
return this.store.list().filter((entry) => needle === void 0 || needle === "" || entry.alias.toLowerCase().includes(needle) || (entry.description ?? "").toLowerCase().includes(needle) || entry.host.toLowerCase().includes(needle) || entry.tags.some((tag) => tag.toLowerCase().includes(needle))).map((entry) => this.store.summarize(entry));
|
|
2181
|
+
return this.store.list(query).map((entry) => this.store.summarize(entry));
|
|
1761
2182
|
}
|
|
1762
2183
|
/** One host summary by alias. */
|
|
1763
2184
|
find(alias) {
|
|
@@ -1811,6 +2232,7 @@ var SshEngine = class {
|
|
|
1811
2232
|
* connection — the next operation re-connects from the current config.
|
|
1812
2233
|
*/
|
|
1813
2234
|
dropAlias(alias) {
|
|
2235
|
+
invalidateAlias(this, alias);
|
|
1814
2236
|
stopAllTunnels(this, alias);
|
|
1815
2237
|
disposeRecord(this, alias);
|
|
1816
2238
|
}
|
|
@@ -1837,6 +2259,7 @@ var SshEngine = class {
|
|
|
1837
2259
|
}
|
|
1838
2260
|
/** Close every pooled connection and tunnel. */
|
|
1839
2261
|
dispose() {
|
|
2262
|
+
markPoolDisposed(this);
|
|
1840
2263
|
if (this.sweepTimer !== void 0) clearInterval(this.sweepTimer);
|
|
1841
2264
|
for (const id of [...this.tunnels.keys()]) stopTunnel(this, id);
|
|
1842
2265
|
for (const alias of [...this.pool.keys()]) disposeRecord(this, alias);
|
|
@@ -1864,6 +2287,11 @@ const DEFAULT_MAX_BUFFER_BYTES = 256 * 1024;
|
|
|
1864
2287
|
const DEFAULT_IDLE_MS = 600 * 1e3;
|
|
1865
2288
|
/** An exited session is kept this long for a reattaching view. */
|
|
1866
2289
|
const DEFAULT_EXIT_GRACE_MS = 60 * 1e3;
|
|
2290
|
+
/** Clamp a terminal column/row dimension to an integer >= `min`. */
|
|
2291
|
+
function clampDimension(value, min, fallback) {
|
|
2292
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
|
|
2293
|
+
return Math.max(min, Math.trunc(value));
|
|
2294
|
+
}
|
|
1867
2295
|
/**
|
|
1868
2296
|
* The host's terminal session table: open one session per connect, attach any
|
|
1869
2297
|
* number of sockets, and keep the shell alive across detach.
|
|
@@ -1886,10 +2314,17 @@ var TerminalSessionRegistry = class {
|
|
|
1886
2314
|
id: randomBytes(9).toString("hex"),
|
|
1887
2315
|
alias,
|
|
1888
2316
|
sockets: /* @__PURE__ */ new Set(),
|
|
2317
|
+
decoder: new StringDecoder("utf8"),
|
|
1889
2318
|
buffer: [],
|
|
2319
|
+
bufferChunkBytes: [],
|
|
2320
|
+
bufferHead: 0,
|
|
1890
2321
|
bufferBytes: 0,
|
|
2322
|
+
paused: false,
|
|
1891
2323
|
exited: false
|
|
1892
2324
|
};
|
|
2325
|
+
session.onDrain = () => {
|
|
2326
|
+
if (session.paused) this.applyBackpressure(session);
|
|
2327
|
+
};
|
|
1893
2328
|
this.sessions.set(session.id, session);
|
|
1894
2329
|
this.bind(ws, session);
|
|
1895
2330
|
try {
|
|
@@ -1900,7 +2335,8 @@ var TerminalSessionRegistry = class {
|
|
|
1900
2335
|
}
|
|
1901
2336
|
session.shell = shell;
|
|
1902
2337
|
shell.onData = (data) => {
|
|
1903
|
-
|
|
2338
|
+
const text = session.decoder.write(data);
|
|
2339
|
+
if (text !== "") this.pushOutput(session, text);
|
|
1904
2340
|
};
|
|
1905
2341
|
shell.onExit = (code, error) => {
|
|
1906
2342
|
this.finish(session, code, error);
|
|
@@ -1911,12 +2347,12 @@ var TerminalSessionRegistry = class {
|
|
|
1911
2347
|
sessionId: session.id
|
|
1912
2348
|
});
|
|
1913
2349
|
} catch (error) {
|
|
1914
|
-
this.sessions.delete(session.id);
|
|
1915
2350
|
this.send(session, {
|
|
1916
2351
|
type: "exit",
|
|
1917
2352
|
code: null,
|
|
1918
2353
|
error: error instanceof Error ? error.message : String(error)
|
|
1919
2354
|
});
|
|
2355
|
+
this.end(session);
|
|
1920
2356
|
}
|
|
1921
2357
|
}
|
|
1922
2358
|
/**
|
|
@@ -1928,31 +2364,31 @@ var TerminalSessionRegistry = class {
|
|
|
1928
2364
|
if (session === void 0) return false;
|
|
1929
2365
|
this.bind(ws, session);
|
|
1930
2366
|
this.clearReap(session);
|
|
1931
|
-
for (
|
|
2367
|
+
for (let index = session.bufferHead; index < session.buffer.length; index += 1) this.sendPayload(session, ws, JSON.stringify({
|
|
1932
2368
|
type: "output",
|
|
1933
|
-
data:
|
|
1934
|
-
});
|
|
1935
|
-
this.
|
|
2369
|
+
data: session.buffer[index]
|
|
2370
|
+
}));
|
|
2371
|
+
this.sendPayload(session, ws, JSON.stringify({
|
|
1936
2372
|
type: "ready",
|
|
1937
2373
|
alias: session.alias,
|
|
1938
2374
|
sessionId: session.id
|
|
1939
|
-
});
|
|
2375
|
+
}));
|
|
1940
2376
|
if (session.exited) {
|
|
1941
|
-
this.
|
|
2377
|
+
this.sendPayload(session, ws, JSON.stringify({
|
|
1942
2378
|
type: "exit",
|
|
1943
2379
|
code: session.exit?.code ?? null,
|
|
1944
2380
|
error: session.exit?.error
|
|
1945
|
-
});
|
|
2381
|
+
}));
|
|
1946
2382
|
this.scheduleReap(session, this.exitGraceMs);
|
|
1947
2383
|
} else {
|
|
1948
|
-
session.shell?.resize(
|
|
1949
|
-
|
|
2384
|
+
session.shell?.resize(clampDimension(size.cols, 2, 80), clampDimension(size.rows, 1, 24));
|
|
2385
|
+
this.applyBackpressure(session);
|
|
1950
2386
|
}
|
|
1951
2387
|
return true;
|
|
1952
2388
|
}
|
|
1953
2389
|
/** End every session (host teardown, plugin dispose). */
|
|
1954
2390
|
dispose() {
|
|
1955
|
-
for (const session of [...this.sessions.values()]) this.end(session
|
|
2391
|
+
for (const session of [...this.sessions.values()]) this.end(session);
|
|
1956
2392
|
this.sessions.clear();
|
|
1957
2393
|
}
|
|
1958
2394
|
/** Number of live sessions (introspection for tests and diagnostics). */
|
|
@@ -1969,15 +2405,18 @@ var TerminalSessionRegistry = class {
|
|
|
1969
2405
|
} catch {
|
|
1970
2406
|
return;
|
|
1971
2407
|
}
|
|
1972
|
-
if (frame
|
|
1973
|
-
|
|
2408
|
+
if (typeof frame !== "object" || frame === null) return;
|
|
2409
|
+
if (frame.type === "input") {
|
|
2410
|
+
if (typeof frame.data === "string") session.shell?.send(frame.data);
|
|
2411
|
+
} else if (frame.type === "resize") session.shell?.resize(clampDimension(frame.cols, 2, 80), clampDimension(frame.rows, 1, 24));
|
|
1974
2412
|
else if (frame.type === "auth_response") {
|
|
1975
2413
|
const finish = session.pendingAuthFinish;
|
|
1976
2414
|
session.pendingAuthFinish = void 0;
|
|
2415
|
+
const responses = Array.isArray(frame.responses) ? frame.responses.filter((item) => typeof item === "string") : [];
|
|
1977
2416
|
try {
|
|
1978
|
-
finish?.(
|
|
2417
|
+
finish?.(responses);
|
|
1979
2418
|
} catch {}
|
|
1980
|
-
} else if (frame.type === "close") this.end(session
|
|
2419
|
+
} else if (frame.type === "close") this.end(session);
|
|
1981
2420
|
else if (frame.type === "detach") this.detach(ws);
|
|
1982
2421
|
});
|
|
1983
2422
|
ws.on("close", () => {
|
|
@@ -1992,20 +2431,26 @@ var TerminalSessionRegistry = class {
|
|
|
1992
2431
|
for (const session of this.sessions.values()) {
|
|
1993
2432
|
if (!session.sockets.delete(ws)) continue;
|
|
1994
2433
|
if (session.sockets.size === 0) this.scheduleReap(session, session.exited ? this.exitGraceMs : this.idleMs);
|
|
2434
|
+
if (session.paused) this.applyBackpressure(session);
|
|
1995
2435
|
return;
|
|
1996
2436
|
}
|
|
1997
2437
|
}
|
|
1998
|
-
/** End the session
|
|
1999
|
-
end(session
|
|
2438
|
+
/** End the session and close every socket still attached to it. */
|
|
2439
|
+
end(session) {
|
|
2000
2440
|
this.clearReap(session);
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2441
|
+
this.sessions.delete(session.id);
|
|
2442
|
+
if (session.pendingAuthFinish !== void 0) {
|
|
2443
|
+
const finish = session.pendingAuthFinish;
|
|
2444
|
+
session.pendingAuthFinish = void 0;
|
|
2445
|
+
try {
|
|
2446
|
+
finish([]);
|
|
2447
|
+
} catch {}
|
|
2448
|
+
}
|
|
2449
|
+
for (const ws of [...session.sockets]) {
|
|
2450
|
+
session.sockets.delete(ws);
|
|
2451
|
+
try {
|
|
2452
|
+
ws.close(1e3);
|
|
2453
|
+
} catch {}
|
|
2009
2454
|
}
|
|
2010
2455
|
try {
|
|
2011
2456
|
session.shell?.close();
|
|
@@ -2014,6 +2459,8 @@ var TerminalSessionRegistry = class {
|
|
|
2014
2459
|
/** Mark a session exited and keep it briefly so a reattaching view sees it. */
|
|
2015
2460
|
finish(session, code, error) {
|
|
2016
2461
|
if (session.exited) return;
|
|
2462
|
+
const tail = session.decoder.end();
|
|
2463
|
+
if (tail !== "") this.pushOutput(session, tail);
|
|
2017
2464
|
session.exited = true;
|
|
2018
2465
|
session.exit = {
|
|
2019
2466
|
code,
|
|
@@ -2032,13 +2479,47 @@ var TerminalSessionRegistry = class {
|
|
|
2032
2479
|
}
|
|
2033
2480
|
this.scheduleReap(session, this.exitGraceMs);
|
|
2034
2481
|
}
|
|
2035
|
-
/**
|
|
2482
|
+
/** Keep at most `maxBytes` from the tail of `data` on a valid UTF-8 boundary. */
|
|
2483
|
+
trimTailToUtf8Bytes(data, maxBytes) {
|
|
2484
|
+
if (maxBytes <= 0) return {
|
|
2485
|
+
text: "",
|
|
2486
|
+
bytes: 0
|
|
2487
|
+
};
|
|
2488
|
+
const buf = Buffer.from(data, "utf8");
|
|
2489
|
+
if (buf.byteLength <= maxBytes) return {
|
|
2490
|
+
text: data,
|
|
2491
|
+
bytes: buf.byteLength
|
|
2492
|
+
};
|
|
2493
|
+
let start = buf.byteLength - maxBytes;
|
|
2494
|
+
while (start < buf.byteLength && (buf[start] & 192) === 128) start += 1;
|
|
2495
|
+
const tail = buf.subarray(start);
|
|
2496
|
+
return {
|
|
2497
|
+
text: tail.toString("utf8"),
|
|
2498
|
+
bytes: tail.byteLength
|
|
2499
|
+
};
|
|
2500
|
+
}
|
|
2501
|
+
/** Append output to the O(1) replay ring, trimmed to the byte cap. */
|
|
2036
2502
|
pushOutput(session, data) {
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
session.
|
|
2503
|
+
const chunkBytes = Buffer.byteLength(data, "utf8");
|
|
2504
|
+
if (chunkBytes > this.maxBufferBytes) {
|
|
2505
|
+
const trimmed = this.trimTailToUtf8Bytes(data, this.maxBufferBytes);
|
|
2506
|
+
session.buffer = trimmed.text === "" ? [] : [trimmed.text];
|
|
2507
|
+
session.bufferChunkBytes = trimmed.text === "" ? [] : [trimmed.bytes];
|
|
2508
|
+
session.bufferHead = 0;
|
|
2509
|
+
session.bufferBytes = trimmed.bytes;
|
|
2510
|
+
} else {
|
|
2511
|
+
session.buffer.push(data);
|
|
2512
|
+
session.bufferChunkBytes.push(chunkBytes);
|
|
2513
|
+
session.bufferBytes += chunkBytes;
|
|
2514
|
+
while (session.bufferBytes > this.maxBufferBytes && session.buffer.length - session.bufferHead > 1) {
|
|
2515
|
+
session.bufferBytes -= session.bufferChunkBytes[session.bufferHead];
|
|
2516
|
+
session.bufferHead += 1;
|
|
2517
|
+
}
|
|
2518
|
+
if (session.bufferHead >= 64 && session.bufferHead * 2 >= session.buffer.length) {
|
|
2519
|
+
session.buffer = session.buffer.slice(session.bufferHead);
|
|
2520
|
+
session.bufferChunkBytes = session.bufferChunkBytes.slice(session.bufferHead);
|
|
2521
|
+
session.bufferHead = 0;
|
|
2522
|
+
}
|
|
2042
2523
|
}
|
|
2043
2524
|
this.send(session, {
|
|
2044
2525
|
type: "output",
|
|
@@ -2047,27 +2528,34 @@ var TerminalSessionRegistry = class {
|
|
|
2047
2528
|
}
|
|
2048
2529
|
/** Broadcast one frame to every attached socket, honoring backpressure. */
|
|
2049
2530
|
send(session, frame) {
|
|
2050
|
-
|
|
2531
|
+
const payload = JSON.stringify(frame);
|
|
2532
|
+
for (const ws of session.sockets) this.sendPayload(session, ws, payload);
|
|
2051
2533
|
this.applyBackpressure(session);
|
|
2052
2534
|
}
|
|
2053
|
-
|
|
2535
|
+
sendPayload(session, ws, payload) {
|
|
2054
2536
|
if (ws.readyState !== WebSocket.OPEN) return;
|
|
2055
2537
|
try {
|
|
2056
|
-
ws.send(
|
|
2538
|
+
if ((session.paused || ws.bufferedAmount + payload.length > BACKPRESSURE_LOW_WATER) && session.onDrain !== void 0) ws.send(payload, session.onDrain);
|
|
2539
|
+
else ws.send(payload);
|
|
2057
2540
|
} catch {}
|
|
2058
2541
|
}
|
|
2059
2542
|
/** Pause while any attached socket is backed up; resume once all drained. */
|
|
2060
2543
|
applyBackpressure(session) {
|
|
2061
2544
|
const shell = session.shell;
|
|
2062
|
-
if (shell === void 0) return;
|
|
2545
|
+
if (shell === void 0 || session.exited) return;
|
|
2063
2546
|
let high = false;
|
|
2064
2547
|
let low = true;
|
|
2065
2548
|
for (const ws of session.sockets) {
|
|
2066
2549
|
if (ws.bufferedAmount > BACKPRESSURE_HIGH_WATER) high = true;
|
|
2067
2550
|
if (ws.bufferedAmount > BACKPRESSURE_LOW_WATER) low = false;
|
|
2068
2551
|
}
|
|
2069
|
-
if (high
|
|
2070
|
-
|
|
2552
|
+
if (high && !session.paused) {
|
|
2553
|
+
session.paused = true;
|
|
2554
|
+
shell.pause();
|
|
2555
|
+
} else if (low && session.paused) {
|
|
2556
|
+
session.paused = false;
|
|
2557
|
+
shell.resume();
|
|
2558
|
+
}
|
|
2071
2559
|
}
|
|
2072
2560
|
/** Answer a keyboard-interactive challenge through whoever is attached. */
|
|
2073
2561
|
keyboardInteractive(session) {
|
|
@@ -2089,7 +2577,7 @@ var TerminalSessionRegistry = class {
|
|
|
2089
2577
|
const timer = setTimeout(() => {
|
|
2090
2578
|
session.reapTimer = void 0;
|
|
2091
2579
|
if (session.sockets.size > 0) return;
|
|
2092
|
-
this.end(session
|
|
2580
|
+
this.end(session);
|
|
2093
2581
|
}, delayMs);
|
|
2094
2582
|
timer.unref?.();
|
|
2095
2583
|
session.reapTimer = timer;
|
|
@@ -2218,9 +2706,52 @@ function isLoopbackRequest(request) {
|
|
|
2218
2706
|
}
|
|
2219
2707
|
}
|
|
2220
2708
|
//#endregion
|
|
2709
|
+
//#region src/connection-trust.ts
|
|
2710
|
+
function resolveConnection(ctx) {
|
|
2711
|
+
try {
|
|
2712
|
+
const candidate = typeof ctx.get === "function" ? ctx.get("connection", false) ?? ctx.get("connection") : ctx.connection;
|
|
2713
|
+
return candidate !== void 0 && candidate !== null && (typeof candidate.admit === "function" || typeof candidate.requestRejection === "function") ? candidate : void 0;
|
|
2714
|
+
} catch {
|
|
2715
|
+
return;
|
|
2716
|
+
}
|
|
2717
|
+
}
|
|
2718
|
+
/** Whether the Host's own authenticated/trusted-host decision admits a request. */
|
|
2719
|
+
function connectionAdmits(connection, request) {
|
|
2720
|
+
if (connection === void 0) return false;
|
|
2721
|
+
try {
|
|
2722
|
+
if (typeof connection.admit === "function") {
|
|
2723
|
+
const admission = connection.admit(request);
|
|
2724
|
+
return admission.rejection === void 0 && "peer" in admission && admission.peer !== void 0;
|
|
2725
|
+
}
|
|
2726
|
+
if (typeof connection.requestRejection === "function") return connection.requestRejection(request) === void 0;
|
|
2727
|
+
return false;
|
|
2728
|
+
} catch {
|
|
2729
|
+
return false;
|
|
2730
|
+
}
|
|
2731
|
+
}
|
|
2732
|
+
/**
|
|
2733
|
+
* Capture connection in a scope that also injects connection.authentication:
|
|
2734
|
+
* admit(request) resolves that service through the calling fiber. The returned
|
|
2735
|
+
* reader falls back to a bare optional lookup on cohorts without that service.
|
|
2736
|
+
*/
|
|
2737
|
+
function captureConnection(ctx, effectName) {
|
|
2738
|
+
let captured;
|
|
2739
|
+
const inject = ctx.inject;
|
|
2740
|
+
if (typeof inject === "function") inject.call(ctx, ["connection", "connection.authentication"], (scoped) => {
|
|
2741
|
+
scoped.effect(() => {
|
|
2742
|
+
captured = resolveConnection(scoped);
|
|
2743
|
+
return () => {
|
|
2744
|
+
captured = void 0;
|
|
2745
|
+
};
|
|
2746
|
+
}, effectName);
|
|
2747
|
+
});
|
|
2748
|
+
return () => captured ?? resolveConnection(ctx);
|
|
2749
|
+
}
|
|
2750
|
+
//#endregion
|
|
2221
2751
|
//#region src/protocol.ts
|
|
2222
2752
|
const SSH_API = {
|
|
2223
2753
|
hosts: "/api/dsh-ssh/hosts",
|
|
2754
|
+
keys: "/api/dsh-ssh/keys",
|
|
2224
2755
|
importSshConfig: "/api/dsh-ssh/hosts/import-ssh-config",
|
|
2225
2756
|
test: "/api/dsh-ssh/test",
|
|
2226
2757
|
exec: "/api/dsh-ssh/exec",
|
|
@@ -2254,6 +2785,16 @@ function queryParam(url, name) {
|
|
|
2254
2785
|
const value = url.searchParams.get(name);
|
|
2255
2786
|
return value === null ? void 0 : value;
|
|
2256
2787
|
}
|
|
2788
|
+
/** Strip control characters, quotes, and backslashes from a Content-Disposition filename. */
|
|
2789
|
+
function safeAttachmentFilename(raw) {
|
|
2790
|
+
let clean = "";
|
|
2791
|
+
for (let i = 0; i < raw.length; i += 1) {
|
|
2792
|
+
const code = raw.charCodeAt(i);
|
|
2793
|
+
if (code < 32 || code === 127 || code === 34 || code === 92) continue;
|
|
2794
|
+
clean += raw[i];
|
|
2795
|
+
}
|
|
2796
|
+
return clean === "" ? "download" : clean;
|
|
2797
|
+
}
|
|
2257
2798
|
/**
|
|
2258
2799
|
* Build every /api/dsh-ssh route (exact paths) plus the terminal upgrade.
|
|
2259
2800
|
* @param deps - store, engine, staging dir.
|
|
@@ -2267,9 +2808,10 @@ function makeRoutes(deps) {
|
|
|
2267
2808
|
recursive: true,
|
|
2268
2809
|
mode: 448
|
|
2269
2810
|
});
|
|
2270
|
-
|
|
2811
|
+
const allowed = (req) => connectionAdmits(deps.connection?.(), req) || isLoopbackRequest(req);
|
|
2812
|
+
/** Guard helper: Host connection trust or loopback fence + method check. */
|
|
2271
2813
|
const guard = (req, res, method) => {
|
|
2272
|
-
if (!
|
|
2814
|
+
if (!allowed(req)) {
|
|
2273
2815
|
writeJson(res, 403, { error: "forbidden: loopback-only" });
|
|
2274
2816
|
return false;
|
|
2275
2817
|
}
|
|
@@ -2285,13 +2827,13 @@ function makeRoutes(deps) {
|
|
|
2285
2827
|
path: SSH_API.hosts,
|
|
2286
2828
|
handler: async (req, res) => {
|
|
2287
2829
|
const method = req.method ?? "GET";
|
|
2288
|
-
if (!
|
|
2830
|
+
if (!allowed(req)) {
|
|
2289
2831
|
writeJson(res, 403, { error: "forbidden: loopback-only" });
|
|
2290
2832
|
return;
|
|
2291
2833
|
}
|
|
2292
2834
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
2293
2835
|
if (method === "GET") {
|
|
2294
|
-
writeJson(res, 200, { hosts:
|
|
2836
|
+
writeJson(res, 200, { hosts: store.list(queryParam(url, "query")).map((entry) => store.summarizePanel(entry)) });
|
|
2295
2837
|
return;
|
|
2296
2838
|
}
|
|
2297
2839
|
if (method === "POST") {
|
|
@@ -2301,8 +2843,8 @@ function makeRoutes(deps) {
|
|
|
2301
2843
|
return;
|
|
2302
2844
|
}
|
|
2303
2845
|
try {
|
|
2304
|
-
const entry = store.create(body);
|
|
2305
|
-
writeJson(res, 201, { host: store.
|
|
2846
|
+
const entry = store.create(store.resolveManagedKey(body));
|
|
2847
|
+
writeJson(res, 201, { host: store.summarizePanel(entry) });
|
|
2306
2848
|
} catch (error) {
|
|
2307
2849
|
writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
|
|
2308
2850
|
}
|
|
@@ -2324,8 +2866,9 @@ function makeRoutes(deps) {
|
|
|
2324
2866
|
return;
|
|
2325
2867
|
}
|
|
2326
2868
|
try {
|
|
2327
|
-
const
|
|
2328
|
-
const
|
|
2869
|
+
const resolved = store.resolveManagedKey(body);
|
|
2870
|
+
const entry = store.update(alias, resolved);
|
|
2871
|
+
const patch = resolved;
|
|
2329
2872
|
if ([
|
|
2330
2873
|
"host",
|
|
2331
2874
|
"port",
|
|
@@ -2335,7 +2878,7 @@ function makeRoutes(deps) {
|
|
|
2335
2878
|
"proxyCommand",
|
|
2336
2879
|
"forwardAgent"
|
|
2337
2880
|
].some((key) => patch[key] !== void 0)) engine.dropAlias(alias);
|
|
2338
|
-
writeJson(res, 200, { host: store.
|
|
2881
|
+
writeJson(res, 200, { host: store.summarizePanel(entry) });
|
|
2339
2882
|
} catch (error) {
|
|
2340
2883
|
writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
|
|
2341
2884
|
}
|
|
@@ -2354,6 +2897,63 @@ function makeRoutes(deps) {
|
|
|
2354
2897
|
writeJson(res, 405, { error: `method not allowed: ${method}` });
|
|
2355
2898
|
}
|
|
2356
2899
|
},
|
|
2900
|
+
{
|
|
2901
|
+
kind: "exact",
|
|
2902
|
+
path: SSH_API.keys,
|
|
2903
|
+
handler: async (req, res) => {
|
|
2904
|
+
const method = req.method ?? "GET";
|
|
2905
|
+
if (!allowed(req)) {
|
|
2906
|
+
writeJson(res, 403, { error: "forbidden: loopback-only" });
|
|
2907
|
+
return;
|
|
2908
|
+
}
|
|
2909
|
+
if (method === "GET") {
|
|
2910
|
+
writeJson(res, 200, { keys: store.listKeys() });
|
|
2911
|
+
return;
|
|
2912
|
+
}
|
|
2913
|
+
const url = new URL(req.url ?? "/", "http://localhost");
|
|
2914
|
+
if (method === "POST") {
|
|
2915
|
+
const body = await readJsonBody(req);
|
|
2916
|
+
if (body === null) {
|
|
2917
|
+
writeJson(res, 400, { error: "invalid JSON body" });
|
|
2918
|
+
return;
|
|
2919
|
+
}
|
|
2920
|
+
try {
|
|
2921
|
+
writeJson(res, 201, { key: store.createKey(body) });
|
|
2922
|
+
} catch (error) {
|
|
2923
|
+
writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
|
|
2924
|
+
}
|
|
2925
|
+
return;
|
|
2926
|
+
}
|
|
2927
|
+
if (method !== "PATCH" && method !== "DELETE") {
|
|
2928
|
+
writeJson(res, 405, { error: `method not allowed: ${method}` });
|
|
2929
|
+
return;
|
|
2930
|
+
}
|
|
2931
|
+
const id = queryParam(url, "id");
|
|
2932
|
+
if (id === void 0 || id === "") {
|
|
2933
|
+
writeJson(res, 400, { error: "id query parameter is required" });
|
|
2934
|
+
return;
|
|
2935
|
+
}
|
|
2936
|
+
if (method === "DELETE") {
|
|
2937
|
+
try {
|
|
2938
|
+
store.deleteKey(id);
|
|
2939
|
+
writeJson(res, 200, { ok: true });
|
|
2940
|
+
} catch (error) {
|
|
2941
|
+
writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
|
|
2942
|
+
}
|
|
2943
|
+
return;
|
|
2944
|
+
}
|
|
2945
|
+
const body = await readJsonBody(req);
|
|
2946
|
+
if (body === null) {
|
|
2947
|
+
writeJson(res, 400, { error: "invalid JSON body" });
|
|
2948
|
+
return;
|
|
2949
|
+
}
|
|
2950
|
+
try {
|
|
2951
|
+
writeJson(res, 200, { key: store.updateKey(id, body) });
|
|
2952
|
+
} catch (error) {
|
|
2953
|
+
writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
|
|
2954
|
+
}
|
|
2955
|
+
}
|
|
2956
|
+
},
|
|
2357
2957
|
{
|
|
2358
2958
|
kind: "exact",
|
|
2359
2959
|
path: SSH_API.importSshConfig,
|
|
@@ -2420,10 +3020,11 @@ function makeRoutes(deps) {
|
|
|
2420
3020
|
const environment = typeof body?.environment === "string" ? body.environment : void 0;
|
|
2421
3021
|
const timeoutMs = typeof body?.timeoutMs === "number" ? body.timeoutMs : void 0;
|
|
2422
3022
|
const maxWorkers = typeof body?.maxWorkers === "number" ? body.maxWorkers : void 0;
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
3023
|
+
if (!hasClusterSelector({
|
|
3024
|
+
aliases,
|
|
3025
|
+
environment,
|
|
3026
|
+
tags
|
|
3027
|
+
})) {
|
|
2427
3028
|
writeJson(res, 400, { error: "ssh_cluster requires aliases, environment, or tags to limit the target set" });
|
|
2428
3029
|
return;
|
|
2429
3030
|
}
|
|
@@ -2533,6 +3134,10 @@ function makeRoutes(deps) {
|
|
|
2533
3134
|
res.write(JSON.stringify(line) + "\n");
|
|
2534
3135
|
} catch {}
|
|
2535
3136
|
};
|
|
3137
|
+
mkdirSync(staging, {
|
|
3138
|
+
recursive: true,
|
|
3139
|
+
mode: 448
|
|
3140
|
+
});
|
|
2536
3141
|
const tmp = join(staging, `upload-${randomBytes(6).toString("hex")}`);
|
|
2537
3142
|
const sink = createWriteStream(tmp, { mode: 384 });
|
|
2538
3143
|
let settled = false;
|
|
@@ -2640,20 +3245,60 @@ function makeRoutes(deps) {
|
|
|
2640
3245
|
}
|
|
2641
3246
|
const tmp = join(staging, `download-${randomBytes(6).toString("hex")}`);
|
|
2642
3247
|
try {
|
|
3248
|
+
mkdirSync(staging, {
|
|
3249
|
+
recursive: true,
|
|
3250
|
+
mode: 448
|
|
3251
|
+
});
|
|
2643
3252
|
closeSync(openSync(tmp, "w", 384));
|
|
2644
3253
|
const outcome = await engine.download(alias, remotePath, tmp);
|
|
3254
|
+
if (req.destroyed || res.destroyed) return;
|
|
2645
3255
|
res.writeHead(200, {
|
|
2646
3256
|
"content-type": "application/octet-stream",
|
|
2647
3257
|
"content-length": String(outcome.bytes),
|
|
2648
|
-
"content-disposition": `attachment; filename="${basename(remotePath)
|
|
3258
|
+
"content-disposition": `attachment; filename="${safeAttachmentFilename(basename(remotePath))}"`,
|
|
2649
3259
|
"referrer-policy": "no-referrer"
|
|
2650
3260
|
});
|
|
2651
3261
|
await new Promise((resolve, reject) => {
|
|
2652
3262
|
const source = createReadStream(tmp);
|
|
2653
|
-
|
|
2654
|
-
|
|
3263
|
+
let settled = false;
|
|
3264
|
+
const finish = (err) => {
|
|
3265
|
+
if (settled) return;
|
|
3266
|
+
settled = true;
|
|
3267
|
+
res.off("error", onResError);
|
|
3268
|
+
res.off("close", onResClose);
|
|
3269
|
+
if (err !== void 0) reject(err);
|
|
3270
|
+
else resolve();
|
|
3271
|
+
};
|
|
3272
|
+
const abortSource = (err) => {
|
|
3273
|
+
if (settled) return;
|
|
3274
|
+
if (source.closed) {
|
|
3275
|
+
finish(err);
|
|
3276
|
+
return;
|
|
3277
|
+
}
|
|
3278
|
+
source.once("close", () => {
|
|
3279
|
+
finish(err);
|
|
3280
|
+
});
|
|
3281
|
+
if (!source.destroyed) try {
|
|
3282
|
+
source.destroy();
|
|
3283
|
+
} catch {
|
|
3284
|
+
finish(err);
|
|
3285
|
+
}
|
|
3286
|
+
};
|
|
3287
|
+
const onResError = (err) => {
|
|
3288
|
+
abortSource(err);
|
|
3289
|
+
};
|
|
3290
|
+
const onResClose = () => {
|
|
3291
|
+
if (!res.writableEnded) abortSource();
|
|
3292
|
+
};
|
|
3293
|
+
source.on("error", (err) => {
|
|
3294
|
+
abortSource(err);
|
|
3295
|
+
});
|
|
3296
|
+
source.on("close", () => {
|
|
3297
|
+
finish();
|
|
3298
|
+
});
|
|
3299
|
+
res.on("error", onResError);
|
|
3300
|
+
res.on("close", onResClose);
|
|
2655
3301
|
source.pipe(res);
|
|
2656
|
-
source.on("end", resolve);
|
|
2657
3302
|
});
|
|
2658
3303
|
} catch (error) {
|
|
2659
3304
|
if (!res.headersSent) writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
|
|
@@ -2665,54 +3310,83 @@ function makeRoutes(deps) {
|
|
|
2665
3310
|
}
|
|
2666
3311
|
];
|
|
2667
3312
|
const terminalSessions = new TerminalSessionRegistry({ openShell: (alias, size, onKeyboardInteractive) => engine.openShell(alias, size, onKeyboardInteractive) });
|
|
2668
|
-
|
|
2669
|
-
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
2679
|
-
|
|
2680
|
-
|
|
2681
|
-
|
|
2682
|
-
|
|
2683
|
-
|
|
3313
|
+
const upgrade = {
|
|
3314
|
+
path: SSH_API.terminal,
|
|
3315
|
+
handler: (req, socket, head) => {
|
|
3316
|
+
if (!allowed(req)) {
|
|
3317
|
+
socket.write("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n");
|
|
3318
|
+
socket.destroy();
|
|
3319
|
+
return;
|
|
3320
|
+
}
|
|
3321
|
+
const url = new URL(req.url ?? "/", "http://localhost");
|
|
3322
|
+
const alias = queryParam(url, "alias");
|
|
3323
|
+
const sessionId = queryParam(url, "session");
|
|
3324
|
+
if (alias === void 0 && sessionId === void 0) {
|
|
3325
|
+
socket.write("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n");
|
|
3326
|
+
socket.destroy();
|
|
3327
|
+
return;
|
|
3328
|
+
}
|
|
3329
|
+
const cols = Number.parseInt(queryParam(url, "cols") ?? "80", 10);
|
|
3330
|
+
const rows = Number.parseInt(queryParam(url, "rows") ?? "24", 10);
|
|
3331
|
+
const size = {
|
|
3332
|
+
cols: Number.isFinite(cols) ? cols : 80,
|
|
3333
|
+
rows: Number.isFinite(rows) ? rows : 24
|
|
3334
|
+
};
|
|
3335
|
+
terminalWss.handleUpgrade(req, socket, head, (ws) => {
|
|
3336
|
+
if (sessionId !== void 0) {
|
|
3337
|
+
if (terminalSessions.attach(ws, sessionId, size)) return;
|
|
3338
|
+
const expired = {
|
|
3339
|
+
type: "exit",
|
|
3340
|
+
code: null,
|
|
3341
|
+
error: "terminal session expired"
|
|
3342
|
+
};
|
|
3343
|
+
try {
|
|
3344
|
+
ws.send(JSON.stringify(expired));
|
|
3345
|
+
} catch {}
|
|
3346
|
+
try {
|
|
3347
|
+
ws.close(1e3);
|
|
3348
|
+
} catch {}
|
|
2684
3349
|
return;
|
|
2685
3350
|
}
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
error: "terminal session expired"
|
|
2699
|
-
};
|
|
2700
|
-
try {
|
|
2701
|
-
ws.send(JSON.stringify(expired));
|
|
2702
|
-
} catch {}
|
|
2703
|
-
try {
|
|
2704
|
-
ws.close(1e3);
|
|
2705
|
-
} catch {}
|
|
2706
|
-
return;
|
|
2707
|
-
}
|
|
2708
|
-
terminalSessions.open(ws, alias, size);
|
|
2709
|
-
});
|
|
2710
|
-
}
|
|
3351
|
+
terminalSessions.open(ws, alias, size);
|
|
3352
|
+
});
|
|
3353
|
+
}
|
|
3354
|
+
};
|
|
3355
|
+
return {
|
|
3356
|
+
routes: routes.map((route) => ({
|
|
3357
|
+
...route,
|
|
3358
|
+
auth: "anonymous"
|
|
3359
|
+
})),
|
|
3360
|
+
upgrade: {
|
|
3361
|
+
...upgrade,
|
|
3362
|
+
auth: "anonymous"
|
|
2711
3363
|
},
|
|
2712
3364
|
terminalSessions
|
|
2713
3365
|
};
|
|
2714
3366
|
}
|
|
2715
3367
|
//#endregion
|
|
3368
|
+
//#region src/service.ts
|
|
3369
|
+
/**
|
|
3370
|
+
* The cordis service `dsh-ssh` publishes to sibling plugins.
|
|
3371
|
+
*
|
|
3372
|
+
* A plugin that needs the host inventory or the shared connection pool injects
|
|
3373
|
+
* this service (`ctx.inject(['dshSsh'], ...)`) instead of importing this
|
|
3374
|
+
* package. The face is a thin forwarder over the same `SshEngine` instance the
|
|
3375
|
+
* routes, the agent tools and the panel drive, so a consumer shares one host
|
|
3376
|
+
* store and one connection pool with the surfaces the user already operates.
|
|
3377
|
+
*
|
|
3378
|
+
* This module is the published contract and is deliberately import-free: a
|
|
3379
|
+
* consuming package restates these declarations verbatim and resolves the
|
|
3380
|
+
* service by {@link DSH_SSH_SERVICE} at runtime, so the two packages share a
|
|
3381
|
+
* shape without sharing a module. Only the members named here exist — the web
|
|
3382
|
+
* terminal, tunnels, cluster runs, directory listing and any streaming log
|
|
3383
|
+
* stay behind the plugin's own surfaces.
|
|
3384
|
+
*
|
|
3385
|
+
* @module @linxin666/dsh-ssh/service
|
|
3386
|
+
*/
|
|
3387
|
+
/** Cordis service name the host half publishes the face under. */
|
|
3388
|
+
const DSH_SSH_SERVICE = "dshSsh";
|
|
3389
|
+
//#endregion
|
|
2716
3390
|
//#region src/tools.ts
|
|
2717
3391
|
/**
|
|
2718
3392
|
* Agent tools: the DSH-native counterpart of ssh-skill's CLI. Every tool
|
|
@@ -3197,13 +3871,14 @@ function sshTunnelTool(engine) {
|
|
|
3197
3871
|
if (args.action === "start") {
|
|
3198
3872
|
if (args.alias === void 0 || args.remotePort === void 0) throw new Error("alias and remotePort are required for start");
|
|
3199
3873
|
try {
|
|
3874
|
+
const tunnel = await engine.startTunnel(args.alias, {
|
|
3875
|
+
remotePort: args.remotePort,
|
|
3876
|
+
remoteHost: args.remoteHost,
|
|
3877
|
+
localPort: args.localPort
|
|
3878
|
+
});
|
|
3200
3879
|
return {
|
|
3201
|
-
ok:
|
|
3202
|
-
tunnel
|
|
3203
|
-
remotePort: args.remotePort,
|
|
3204
|
-
remoteHost: args.remoteHost,
|
|
3205
|
-
localPort: args.localPort
|
|
3206
|
-
})
|
|
3880
|
+
ok: tunnel.state !== "failed",
|
|
3881
|
+
tunnel
|
|
3207
3882
|
};
|
|
3208
3883
|
} catch (error) {
|
|
3209
3884
|
return {
|
|
@@ -3306,7 +3981,7 @@ function sshClusterTool(engine) {
|
|
|
3306
3981
|
render: (_args, value) => text(renderCluster(value.results ?? []))
|
|
3307
3982
|
},
|
|
3308
3983
|
async execute(args, exec) {
|
|
3309
|
-
if (!(
|
|
3984
|
+
if (!hasClusterSelector(args)) throw new Error("ssh_cluster requires aliases, environment, or tags to limit the target set");
|
|
3310
3985
|
return { results: await engine.cluster({
|
|
3311
3986
|
...args,
|
|
3312
3987
|
signal: exec.signal
|
|
@@ -3545,7 +4220,44 @@ const SSH_TOOL_NAMES = [
|
|
|
3545
4220
|
/** Model-facing announcement: plugin presence, capabilities, and limits. */
|
|
3546
4221
|
const SSH_GUIDANCE = "本机已安装 dsh-ssh 插件(DSH 远程 SSH 运维):侧边栏「SSH」入口;在 dsh-web 插件全家桶仓库(packages/dsh-ssh)统一维护。能力:主机配置存 $DSH_HOME/dsh-ssh.json(默认 ~/.dsh)(可从 ~/.ssh/config 导入);持久连接池复用长连接(空闲 30 分钟自动断开);ssh_list 列出主机、ssh_exec 执行远程命令、ssh_upload/ssh_download 传输文件、ssh_tunnel 本地端口转发(访问远程数据库/内网服务)、ssh_cluster 按 aliases/environment/tags 至少一种非空 selector 筛选后集群并发执行;支持密钥/密码/ssh-agent 认证、passphrase 密钥、ProxyJump 跳板机(别名或 [user@]host[:port] 地址)与 OpenSSH 语义的 ProxyCommand(跳过堡垒机客户端场景,只能由用户在 GUI 配置,agent 不可写);Web 终端走 WebSocket。限制:主机操作由用户在 GUI 中配置后 agent 方可使用;密码以明文存在用户主目录私有文件(权限 0600);命令输出原样返回、可能含敏感信息;断线重连可能重放非幂等命令;传输/执行消耗真实远程资源,先确认再操作。路径区分:本机(dsh host)上的文件与命令一律用本地工具(read / write / edit / bash),ssh_* 工具只针对远程主机上的路径。用户提到「SSH / 远程服务器 / 服务器操作 / 跳板机 / 隧道 / 部署 / 上传下载」时即指本插件,请据此协作。";
|
|
3547
4222
|
/**
|
|
3548
|
-
*
|
|
4223
|
+
* Project one stored-host summary onto the service face.
|
|
4224
|
+
*
|
|
4225
|
+
* Everything the summary publishes is forwarded except the ProxyCommand text:
|
|
4226
|
+
* the command is a shell line the host process executes with its own
|
|
4227
|
+
* privileges, and a sibling plugin drives the host without ever needing it.
|
|
4228
|
+
* @param summary - the plugin's own secret-free projection.
|
|
4229
|
+
* @returns the same host as the service face reports it.
|
|
4230
|
+
*/
|
|
4231
|
+
function toServiceHost(summary) {
|
|
4232
|
+
const { proxyCommand: _proxyCommand, ...host } = summary;
|
|
4233
|
+
return host;
|
|
4234
|
+
}
|
|
4235
|
+
/**
|
|
4236
|
+
* Build the face a sibling plugin receives.
|
|
4237
|
+
*
|
|
4238
|
+
* Every member forwards to the engine instance this plugin already serves its
|
|
4239
|
+
* routes, tools and panel from, so a consumer shares one host store and one
|
|
4240
|
+
* connection pool with them instead of opening its own.
|
|
4241
|
+
* @param engine - the plugin's engine for this apply.
|
|
4242
|
+
* @returns the published service face.
|
|
4243
|
+
*/
|
|
4244
|
+
function createService(engine) {
|
|
4245
|
+
return {
|
|
4246
|
+
apiVersion: 1,
|
|
4247
|
+
hosts: {
|
|
4248
|
+
list: () => engine.list().map(toServiceHost),
|
|
4249
|
+
find: (alias) => {
|
|
4250
|
+
const summary = engine.find(alias);
|
|
4251
|
+
return summary === void 0 ? void 0 : toServiceHost(summary);
|
|
4252
|
+
}
|
|
4253
|
+
},
|
|
4254
|
+
exec: (alias, command, options) => engine.exec(alias, command, options?.timeoutMs, options?.signal),
|
|
4255
|
+
upload: (alias, localPath, remotePath) => engine.upload(alias, localPath, remotePath, false),
|
|
4256
|
+
download: (alias, remotePath, localPath) => engine.download(alias, remotePath, localPath)
|
|
4257
|
+
};
|
|
4258
|
+
}
|
|
4259
|
+
/**
|
|
4260
|
+
* Mount the SSH engine, routes, tools, the sibling-plugin service, and announcement.
|
|
3549
4261
|
* @param ctx - host plugin context carrying webServer/tools/systemPrompt.
|
|
3550
4262
|
* @param config - resolved plugin config (schema defaults applied by the loader).
|
|
3551
4263
|
*/
|
|
@@ -3566,7 +4278,8 @@ function applyImpl(ctx, config) {
|
|
|
3566
4278
|
};
|
|
3567
4279
|
const { routes, upgrade, terminalSessions } = makeRoutes({
|
|
3568
4280
|
store,
|
|
3569
|
-
engine
|
|
4281
|
+
engine,
|
|
4282
|
+
connection: captureConnection(ctx, "dsh-ssh: connection trust")
|
|
3570
4283
|
});
|
|
3571
4284
|
let disposeRoutes;
|
|
3572
4285
|
const tools = [
|
|
@@ -3579,28 +4292,36 @@ function applyImpl(ctx, config) {
|
|
|
3579
4292
|
];
|
|
3580
4293
|
let disposeTools;
|
|
3581
4294
|
let disposeSection;
|
|
4295
|
+
let disposeService;
|
|
3582
4296
|
const sync = () => {
|
|
3583
4297
|
engine.setConnectTimeout(readConfigField(config?.connectTimeoutMs, DEFAULT_CONNECT_TIMEOUT_MS));
|
|
3584
4298
|
const value = resolve();
|
|
3585
|
-
|
|
4299
|
+
const wantSection = value.enabled && value.announceToAgent;
|
|
4300
|
+
if (!wantSection && disposeSection !== void 0) {
|
|
3586
4301
|
disposeSection();
|
|
3587
4302
|
disposeSection = void 0;
|
|
3588
4303
|
}
|
|
3589
|
-
if (
|
|
3590
|
-
disposeRoutes
|
|
3591
|
-
|
|
3592
|
-
|
|
3593
|
-
|
|
3594
|
-
disposeTools
|
|
3595
|
-
|
|
4304
|
+
if (!value.enabled) {
|
|
4305
|
+
if (disposeRoutes !== void 0) {
|
|
4306
|
+
disposeRoutes();
|
|
4307
|
+
disposeRoutes = void 0;
|
|
4308
|
+
}
|
|
4309
|
+
if (disposeTools !== void 0) {
|
|
4310
|
+
disposeTools();
|
|
4311
|
+
disposeTools = void 0;
|
|
4312
|
+
}
|
|
4313
|
+
if (disposeService !== void 0) {
|
|
4314
|
+
disposeService();
|
|
4315
|
+
disposeService = void 0;
|
|
4316
|
+
}
|
|
4317
|
+
return;
|
|
3596
4318
|
}
|
|
3597
|
-
if (
|
|
3598
|
-
if (value.announceToAgent) disposeSection = ctx.systemPrompt.section({
|
|
4319
|
+
if (wantSection && disposeSection === void 0) disposeSection = ctx.systemPrompt.section({
|
|
3599
4320
|
name: "plugin:dsh-ssh",
|
|
3600
4321
|
order: SECTION_ORDER,
|
|
3601
4322
|
text: visibleToolText(ctx.tools, SSH_TOOL_NAMES, SSH_GUIDANCE)
|
|
3602
4323
|
});
|
|
3603
|
-
disposeRoutes = ctx.effect(() => {
|
|
4324
|
+
if (disposeRoutes === void 0) disposeRoutes = ctx.effect(() => {
|
|
3604
4325
|
const disposers = routes.map((route) => ctx.webServer.register(route));
|
|
3605
4326
|
const upgradeDisposer = ctx.webServer.registerUpgrade(upgrade);
|
|
3606
4327
|
return () => {
|
|
@@ -3609,12 +4330,13 @@ function applyImpl(ctx, config) {
|
|
|
3609
4330
|
terminalSessions.dispose();
|
|
3610
4331
|
};
|
|
3611
4332
|
}, "dsh-ssh: routes");
|
|
3612
|
-
disposeTools = ctx.effect(() => {
|
|
4333
|
+
if (disposeTools === void 0) disposeTools = ctx.effect(() => {
|
|
3613
4334
|
const disposers = tools.map((tool) => ctx.tools.register(tool));
|
|
3614
4335
|
return () => {
|
|
3615
4336
|
for (const dispose of disposers) dispose();
|
|
3616
4337
|
};
|
|
3617
4338
|
}, "dsh-ssh: tools");
|
|
4339
|
+
if (disposeService === void 0 && typeof ctx.provide === "function") disposeService = ctx.provide(DSH_SSH_SERVICE, createService(engine));
|
|
3618
4340
|
};
|
|
3619
4341
|
ctx.on("loader/volatile-update", () => {
|
|
3620
4342
|
sync();
|