@fish-under-sea/dsh-ssh-fish 2.2.2 → 2.3.0

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.
Files changed (42) hide show
  1. package/README.en.md +4 -4
  2. package/README.md +4 -4
  3. package/package.json +5 -4
  4. package/README.i18n.yaml +0 -6
  5. package/README.zh.md +0 -31
  6. package/lib/client.js +0 -17100
  7. package/lib/client.js.map +0 -1
  8. package/lib/index.js +0 -3625
  9. package/lib/types/client/api.d.ts +0 -162
  10. package/lib/types/client/index.d.ts +0 -37
  11. package/lib/types/client/locales.d.ts +0 -175
  12. package/lib/types/client/native-panel.d.ts +0 -70
  13. package/lib/types/client/panel/ClusterTab.d.ts +0 -7
  14. package/lib/types/client/panel/HostFormDialog.d.ts +0 -12
  15. package/lib/types/client/panel/HostsTab.d.ts +0 -25
  16. package/lib/types/client/panel/SshPanel.d.ts +0 -14
  17. package/lib/types/client/panel/TerminalTab.d.ts +0 -27
  18. package/lib/types/client/panel/TransferTab.d.ts +0 -7
  19. package/lib/types/client/panel/TunnelsTab.d.ts +0 -19
  20. package/lib/types/client/panel/controller.d.ts +0 -253
  21. package/lib/types/client/panel/helpers.d.ts +0 -45
  22. package/lib/types/client/panel/xterm.css.d.ts +0 -2
  23. package/lib/types/client/settings-binding.d.ts +0 -61
  24. package/lib/types/dsh-home.d.ts +0 -16
  25. package/lib/types/engine/cluster.d.ts +0 -19
  26. package/lib/types/engine/connection-pool.d.ts +0 -163
  27. package/lib/types/engine/proxy-command.d.ts +0 -36
  28. package/lib/types/engine/pty.d.ts +0 -32
  29. package/lib/types/engine/sftp.d.ts +0 -20
  30. package/lib/types/engine/terminal-sessions.d.ts +0 -67
  31. package/lib/types/engine/tunnel.d.ts +0 -36
  32. package/lib/types/engine.d.ts +0 -96
  33. package/lib/types/http.d.ts +0 -59
  34. package/lib/types/index.d.ts +0 -93
  35. package/lib/types/loopback.d.ts +0 -64
  36. package/lib/types/mount-once.d.ts +0 -55
  37. package/lib/types/protocol.d.ts +0 -256
  38. package/lib/types/routes.d.ts +0 -33
  39. package/lib/types/ssh-config.d.ts +0 -34
  40. package/lib/types/store.d.ts +0 -78
  41. package/lib/types/tool-surface.d.ts +0 -72
  42. package/lib/types/tools.d.ts +0 -43
package/lib/index.js DELETED
@@ -1,3625 +0,0 @@
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";
3
- import { Client } from "ssh2";
4
- import { homedir, tmpdir } from "node:os";
5
- import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
6
- import { isAbsolute as isAbsolute$1, join as join$1 } from "node:path/posix";
7
- import { spawn } from "node:child_process";
8
- import { Duplex } from "node:stream";
9
- import { createServer } from "node:net";
10
- import { unlink } from "node:fs/promises";
11
- import { randomBytes } from "node:crypto";
12
- import { WebSocket, WebSocketServer } from "ws";
13
- import { defineTool } from "@deepseek-ai/dsh-tools";
14
- //#region src/dsh-home.ts
15
- /**
16
- * DSH_HOME resolution shared by the plugin family's Host halves: the
17
- * environment override wins, the platform home fallback follows. Mirrors
18
- * what dsh-pet and dsh-liangshen each used to implement locally.
19
- */
20
- /** Expand a leading ~ (or ~user) in a path, platform-style. */
21
- function expandHome$1(path, home = homedir()) {
22
- const j = home.startsWith("/") ? join$1 : join;
23
- if (path === "~") return home;
24
- if (path.startsWith("~/") || path.startsWith("~\\")) return j(home, path.slice(2));
25
- return path;
26
- }
27
- /**
28
- * Resolve the DSH home directory.
29
- * @param env - process environment to read DSH_HOME from.
30
- * @param home - platform home directory fallback (test seam).
31
- * @returns the absolute DSH home path.
32
- */
33
- function resolveDshHome(env = process.env, home = homedir()) {
34
- const isPosix = home.startsWith("/");
35
- const j = isPosix ? join$1 : join;
36
- const isAbs = isPosix ? isAbsolute$1 : isAbsolute;
37
- const raw = env.DSH_HOME;
38
- if (raw !== void 0 && raw.trim() !== "") {
39
- const expanded = expandHome$1(raw.trim(), home);
40
- return isAbs(expanded) ? expanded : j(process.cwd(), expanded);
41
- }
42
- return j(home, ".dsh");
43
- }
44
- /** Resolve the DSH home directory from the live environment. */
45
- function dshHome() {
46
- return resolveDshHome();
47
- }
48
- //#endregion
49
- //#region src/ssh-config.ts
50
- /**
51
- * Minimal `~/.ssh/config` reader for the one-shot host import: Host blocks with
52
- * `Include` expansion and explicit skip reasons. Values stay raw strings; the
53
- * store maps them onto a HostPayload.
54
- *
55
- * Deliberate simplifications (documented in the package README):
56
- * - `Match` blocks are skipped — their options are conditional and must never
57
- * merge into the Host block above them.
58
- * - A multi-pattern `Host a b` line only exposes its first pattern.
59
- * - Include pathnames accept `~`, globs, and several whitespace-separated
60
- * pathnames, but not environment variables, `%` tokens, or quoting.
61
- * - Relative Include pathnames resolve against the directory of the config
62
- * file the import started from (OpenSSH: `~/.ssh` for a user config).
63
- * - A file that already contributed lines is never read twice, which doubles
64
- * as the Include cycle guard.
65
- */
66
- /** Include recursion guard: a cycle or a runaway chain stops here. */
67
- const MAX_INCLUDE_DEPTH = 16;
68
- /** The only line shape ssh_config knows: `Keyword value...` (case-insensitive). */
69
- const LINE_RE = /^([A-Za-z0-9_-]+)\s+(.+)$/;
70
- /** Expand a leading `~` the way OpenSSH does for user configuration files. */
71
- function expandTilde(path) {
72
- if (path === "~") return homedir();
73
- if (path.startsWith("~/")) return join(homedir(), path.slice(2));
74
- return path;
75
- }
76
- /** Turn one glob segment into a matcher (`*` and `?` only). */
77
- function segmentMatcher(segment) {
78
- const escaped = segment.replace(/[.+^${}()|[\]\\]/g, "\\$&");
79
- return new RegExp("^" + escaped.replace(/\*/g, ".*").replace(/\?/g, ".") + "$");
80
- }
81
- /**
82
- * Expand a segment list against the filesystem. Wildcards match whole segments
83
- * only; matches are sorted so a glob import stays deterministic.
84
- */
85
- function globSegments(prefix, segments) {
86
- const [head, ...rest] = segments;
87
- if (head === void 0) return [prefix];
88
- if (!/[*?]/.test(head)) return globSegments(join(prefix, head), rest);
89
- let names;
90
- try {
91
- names = readdirSync(prefix);
92
- } catch {
93
- return [];
94
- }
95
- const matcher = segmentMatcher(head);
96
- return names.filter((name) => matcher.test(name)).sort().flatMap((name) => globSegments(join(prefix, name), rest));
97
- }
98
- /** Resolve one Include pathname into the existing regular files it names. */
99
- function resolveInclude(spec, baseDir) {
100
- const expanded = expandTilde(spec);
101
- const full = isAbsolute(expanded) ? expanded : join(baseDir, expanded);
102
- if (!/[*?]/.test(full)) return existsSync(full) ? [full] : [];
103
- const root = /^([A-Za-z]:[\\/]|[\\/])/.exec(full)?.[1] ?? "";
104
- const segments = full.slice(root.length).split(/[\\/]+/).filter((part) => part !== "");
105
- return globSegments(root === "" ? "." : root, segments).filter((path) => {
106
- try {
107
- return statSync(path).isFile();
108
- } catch {
109
- return false;
110
- }
111
- });
112
- }
113
- /** Read one file into lines, splicing every `Include` in place. */
114
- function readLines(file, baseDir, visited, depth) {
115
- if (depth > MAX_INCLUDE_DEPTH) return [];
116
- let key;
117
- try {
118
- key = realpathSync(file);
119
- } catch {
120
- return [];
121
- }
122
- if (visited.has(key)) return [];
123
- visited.add(key);
124
- let text;
125
- try {
126
- text = readFileSync(key, "utf8");
127
- } catch {
128
- return [];
129
- }
130
- const out = [];
131
- for (const raw of text.split(/\r?\n/)) {
132
- const match = LINE_RE.exec(raw.trim());
133
- if (match === null || match[1].toLowerCase() !== "include") {
134
- out.push(raw);
135
- continue;
136
- }
137
- for (const spec of match[2].trim().split(/\s+/).filter((part) => part !== "")) for (const included of resolveInclude(spec, baseDir)) out.push(...readLines(included, baseDir, visited, depth + 1));
138
- }
139
- return out;
140
- }
141
- /**
142
- * Parse one ssh_config file (Include expanded) into Host blocks plus the
143
- * `Match` blocks that were deliberately skipped.
144
- */
145
- function readSshConfigBlocks(configPath) {
146
- const blocks = [];
147
- const skipped = [];
148
- const lines = readLines(configPath, dirname(configPath), /* @__PURE__ */ new Set(), 0);
149
- let current;
150
- for (const raw of lines) {
151
- const match = LINE_RE.exec(raw.trim());
152
- if (match === null) continue;
153
- const key = match[1].toLowerCase();
154
- const value = match[2].trim();
155
- if (key === "host") {
156
- current = {
157
- pattern: value,
158
- props: {}
159
- };
160
- blocks.push(current);
161
- continue;
162
- }
163
- if (key === "match") {
164
- skipped.push({
165
- name: "Match " + value,
166
- reason: "match"
167
- });
168
- current = void 0;
169
- continue;
170
- }
171
- if (current !== void 0) current.props[key] = value;
172
- }
173
- return {
174
- blocks,
175
- skipped
176
- };
177
- }
178
- //#endregion
179
- //#region src/store.ts
180
- /**
181
- * Host config store: one JSON file (`$DSH_HOME/dsh-ssh.json`, defaulting
182
- * to `~/.dsh`) holding every
183
- * SSH host entry, written atomically (tmp + rename). Also parses the user's
184
- * standard `~/.ssh/config` for one-shot import. Secrets (passwords,
185
- * passphrases) live in this user-owned file in plaintext — same trust model
186
- * as ssh-skill's annotated ssh-config comments; document it, never log it.
187
- */
188
- /** File format version. */
189
- const FORMAT_VERSION = 1;
190
- /** Store file location: $DSH_HOME/dsh-ssh.json (defaults to ~/.dsh). */
191
- function storePath() {
192
- return join(dshHome(), "dsh-ssh.json");
193
- }
194
- /** The user's standard OpenSSH config path. */
195
- function sshConfigPath() {
196
- return join(homedir(), ".ssh", "config");
197
- }
198
- /** Validate the wire shape of a host payload; returns a message or undefined. */
199
- function validateHostPayload(payload) {
200
- if (typeof payload !== "object" || payload === null) return "body must be a JSON object";
201
- const p = payload;
202
- if (typeof p.host !== "string" || p.host.trim() === "") return "host is required";
203
- if (typeof p.user !== "string" || p.user.trim() === "") return "user is required";
204
- const auth = p.auth;
205
- if (auth !== void 0) {
206
- if (typeof auth !== "object" || auth === null) return "auth must be an object";
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";
211
- }
212
- 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
- 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";
214
- if (p.proxyCommand !== void 0 && typeof p.proxyCommand !== "string") return "proxyCommand must be a string when provided";
215
- const proxyCommand = typeof p.proxyCommand === "string" ? normalizeProxyCommand(p.proxyCommand) : void 0;
216
- const proxyJump = Array.isArray(p.proxyJump) ? p.proxyJump : [];
217
- if (proxyCommand !== void 0 && proxyJump.length > 0) return "proxyCommand and proxyJump cannot be combined — pick one transport per host";
218
- 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
- if (p.forwardAgent !== void 0 && typeof p.forwardAgent !== "boolean") return "forwardAgent must be a boolean";
220
- }
221
- /** Alias grammar: letters/digits plus dots, hyphens, underscores (IP/domain aliases included). */
222
- const ALIAS_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
223
- /** Validate an alias for creation. */
224
- function validateAlias(alias) {
225
- if (!ALIAS_RE.test(alias)) return "alias must be letters, digits, dots, hyphens or underscores";
226
- }
227
- /**
228
- * The host store. Pure file I/O — no cordis dependency, unit-testable.
229
- */
230
- var HostStore = class {
231
- /** The JSON file path. */
232
- path;
233
- /** Optional override of the ~/.ssh/config path (tests). */
234
- sshConfigOverride;
235
- /**
236
- * @param path - store file path (defaults to the standard location).
237
- * @param sshConfigOverride - ssh config path override (tests only).
238
- */
239
- constructor(path, sshConfigOverride) {
240
- this.path = resolve(path ?? storePath());
241
- this.sshConfigOverride = sshConfigOverride;
242
- }
243
- /** Load all entries (empty store when the file is absent). */
244
- list() {
245
- return this.load().hosts;
246
- }
247
- /** Find one entry by alias. */
248
- find(alias) {
249
- return this.list().find((entry) => entry.alias === alias);
250
- }
251
- /** Secret-free projection for the browser and agent surfaces. */
252
- summarize(entry) {
253
- let keyReady = true;
254
- if (entry.auth.kind === "key" && entry.auth.keyPath) keyReady = existsSync(expandHome(entry.auth.keyPath));
255
- else if (entry.auth.kind === "agent") keyReady = false;
256
- return {
257
- alias: entry.alias,
258
- host: entry.host,
259
- port: entry.port,
260
- user: entry.user,
261
- auth: entry.auth.kind,
262
- keyReady,
263
- proxyJump: [...entry.proxyJump],
264
- ...entry.proxyCommand !== void 0 ? { proxyCommand: entry.proxyCommand } : {},
265
- ...entry.description !== void 0 ? { description: entry.description } : {},
266
- ...entry.environment !== void 0 ? { environment: entry.environment } : {},
267
- tags: [...entry.tags],
268
- ...entry.location !== void 0 ? { location: entry.location } : {},
269
- forwardAgent: entry.forwardAgent === true,
270
- createdAt: entry.createdAt,
271
- updatedAt: entry.updatedAt
272
- };
273
- }
274
- /** Create one entry. Throws on alias collision or invalid payload. */
275
- create(payload) {
276
- const alias = payload.alias?.trim();
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");
283
- const file = this.load();
284
- if (file.hosts.some((entry) => entry.alias === alias)) throw new Error(`alias '${alias}' already exists`);
285
- const now = Date.now();
286
- const entry = {
287
- alias,
288
- host: payload.host.trim(),
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
307
- };
308
- file.hosts.push(entry);
309
- this.save(file);
310
- return entry;
311
- }
312
- /** Update the fields present in `patch`; unknown aliases throw. */
313
- update(alias, patch) {
314
- const file = this.load();
315
- const entry = file.hosts.find((candidate) => candidate.alias === alias);
316
- if (entry === void 0) throw new Error(`alias '${alias}' not found`);
317
- if (patch.host !== void 0 && (typeof patch.host !== "string" || patch.host.trim() === "")) throw new Error("host is required");
318
- if (patch.user !== void 0 && (typeof patch.user !== "string" || patch.user.trim() === "")) throw new Error("user is required");
319
- 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");
320
- if (patch.proxyJump !== void 0 && (!Array.isArray(patch.proxyJump) || patch.proxyJump.some((x) => typeof x !== "string" || x === ""))) throw new Error("proxyJump must be an array of alias strings");
321
- if (patch.proxyCommand !== void 0 && typeof patch.proxyCommand !== "string") throw new Error("proxyCommand must be a string when provided");
322
- if (patch.forwardAgent !== void 0 && typeof patch.forwardAgent !== "boolean") throw new Error("forwardAgent must be a boolean");
323
- const mergedProxyCommand = patch.proxyCommand !== void 0 ? normalizeProxyCommand(patch.proxyCommand) : entry.proxyCommand;
324
- 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
- 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.host !== void 0) entry.host = patch.host.trim();
327
- if (patch.port !== void 0) entry.port = patch.port;
328
- if (patch.user !== void 0) entry.user = patch.user.trim();
329
- if (patch.auth !== void 0) {
330
- 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
- const keyChanged = auth.kind === "key" && auth.keyPath !== void 0 && expandHome(auth.keyPath.trim()) !== entry.auth.keyPath;
336
- entry.auth = {
337
- kind: auth.kind,
338
- 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,
340
- password: auth.kind === "password" ? auth.password : void 0,
341
- agentPath: auth.kind === "agent" ? auth.agentPath !== void 0 ? normalizeAgentPath(auth.agentPath) : entry.auth.agentPath : void 0
342
- };
343
- }
344
- if (patch.proxyJump !== void 0) entry.proxyJump = [...patch.proxyJump];
345
- if (patch.proxyCommand !== void 0) entry.proxyCommand = mergedProxyCommand;
346
- if (patch.description !== void 0) entry.description = patch.description.trim() || void 0;
347
- if (patch.environment !== void 0) entry.environment = patch.environment.trim() || void 0;
348
- if (patch.tags !== void 0) entry.tags = [...patch.tags].map((tag) => tag.trim()).filter((tag) => tag !== "");
349
- if (patch.location !== void 0) entry.location = patch.location.trim() || void 0;
350
- if (patch.forwardAgent !== void 0) entry.forwardAgent = patch.forwardAgent === true ? true : void 0;
351
- entry.updatedAt = Date.now();
352
- this.save(file);
353
- return entry;
354
- }
355
- /** Remove one entry. */
356
- delete(alias) {
357
- const file = this.load();
358
- const index = file.hosts.findIndex((candidate) => candidate.alias === alias);
359
- if (index < 0) throw new Error(`alias '${alias}' not found`);
360
- file.hosts.splice(index, 1);
361
- this.save(file);
362
- }
363
- /**
364
- * Import hosts from `~/.ssh/config`: Host blocks with a single non-wildcard
365
- * pattern become entries (a missing HostName falls back to the pattern
366
- * itself; key auth via IdentityFile; jump hosts via ProxyJump; ProxyCommand
367
- * kept verbatim). `Include` files are expanded, and `Match` blocks,
368
- * wildcard patterns, and aliases that already exist are skipped with a
369
- * reason instead of silently disappearing.
370
- * @returns import statistics.
371
- */
372
- importFromSshConfig() {
373
- this.skippedBlocks = [];
374
- const configPath = this.sshConfigOverride ?? sshConfigPath();
375
- if (!existsSync(configPath)) return {
376
- parsed: 0,
377
- added: 0,
378
- skipped: 0,
379
- skippedBlocks: []
380
- };
381
- const { blocks, skipped } = readSshConfigBlocks(configPath);
382
- this.skippedBlocks = [...skipped];
383
- const skip = (name, reason) => {
384
- if (name === "") return;
385
- if (this.skippedBlocks.some((block) => block.name === name)) return;
386
- this.skippedBlocks.push({
387
- name,
388
- reason
389
- });
390
- };
391
- let added = 0;
392
- for (const block of blocks) {
393
- const pattern = block.pattern.split(/\s+/)[0];
394
- if (pattern.includes("*") || pattern.includes("?")) {
395
- skip(pattern, "wildcard");
396
- continue;
397
- }
398
- if (this.list().some((entry) => entry.alias === pattern)) {
399
- skip(pattern, "existing");
400
- continue;
401
- }
402
- const payload = {
403
- alias: pattern,
404
- host: block.props.hostname !== void 0 && block.props.hostname !== "" ? block.props.hostname : pattern,
405
- port: block.props.port !== void 0 ? Number.parseInt(block.props.port, 10) : 22,
406
- user: block.props.user ?? process.env.USER ?? "root",
407
- auth: {
408
- kind: block.props.identityfile !== void 0 ? "key" : block.props.identityagent !== void 0 && block.props.identityagent.toLowerCase() !== "none" ? "agent" : "password",
409
- keyPath: block.props.identityfile,
410
- password: block.props.password,
411
- agentPath: block.props.identityagent !== void 0 && block.props.identityagent.toLowerCase() !== "none" ? normalizeAgentPath(block.props.identityagent) : void 0
412
- },
413
- proxyJump: block.props.proxyjump !== void 0 ? block.props.proxyjump.split(",").map((hop) => hop.trim()).filter((hop) => hop !== "") : [],
414
- proxyCommand: block.props.proxycommand,
415
- description: block.props.description,
416
- environment: block.props.environment,
417
- tags: (block.props.tags ?? "").split(",").map((tag) => tag.trim()).filter((tag) => tag !== ""),
418
- location: block.props.location,
419
- forwardAgent: parseForwardAgentValue(block.props.forwardagent)
420
- };
421
- try {
422
- this.create(payload);
423
- added += 1;
424
- } catch {
425
- skip(pattern, "invalid");
426
- }
427
- }
428
- return {
429
- parsed: blocks.length,
430
- added,
431
- skipped: this.skippedBlocks.length,
432
- skippedBlocks: [...this.skippedBlocks]
433
- };
434
- }
435
- skippedBlocks = [];
436
- /**
437
- * Last parsed store keyed by file identity. list/find ride every acquire
438
- * and GUI refresh; re-reading and re-parsing the whole file each call is
439
- * wasted work when the file has not changed. Any save invalidates.
440
- */
441
- cache;
442
- load() {
443
- let stats;
444
- try {
445
- stats = statSync(this.path);
446
- } catch {
447
- this.cache = void 0;
448
- return {
449
- version: FORMAT_VERSION,
450
- hosts: []
451
- };
452
- }
453
- if (this.cache !== void 0 && this.cache.mtimeMs === stats.mtimeMs && this.cache.size === stats.size) return this.cache.file;
454
- try {
455
- const parsed = JSON.parse(readFileSync(this.path, "utf8"));
456
- if (typeof parsed !== "object" || parsed === null || !Array.isArray(parsed.hosts)) throw new Error("store file shape invalid");
457
- this.cache = {
458
- mtimeMs: stats.mtimeMs,
459
- size: stats.size,
460
- file: parsed
461
- };
462
- return parsed;
463
- } catch {
464
- this.cache = void 0;
465
- try {
466
- renameSync(this.path, `${this.path}.corrupt-${Date.now()}`);
467
- } catch {}
468
- return {
469
- version: FORMAT_VERSION,
470
- hosts: []
471
- };
472
- }
473
- }
474
- save(file) {
475
- const dir = dirname(this.path);
476
- if (!existsSync(dir)) mkdirSync(dir, {
477
- recursive: true,
478
- mode: 448
479
- });
480
- const tmp = this.path + ".tmp";
481
- writeFileSync(tmp, JSON.stringify(file, null, 2) + "\n", {
482
- encoding: "utf8",
483
- mode: 384
484
- });
485
- renameSync(tmp, this.path);
486
- this.cache = void 0;
487
- }
488
- };
489
- /** Normalize an agent endpoint for storage: trim, expand `~`, and resolve the SSH_AUTH_SOCK token. */
490
- function normalizeAgentPath(agentPath) {
491
- const trimmed = agentPath?.trim();
492
- if (trimmed === void 0 || trimmed === "") return void 0;
493
- if (trimmed === "SSH_AUTH_SOCK" || trimmed === "$SSH_AUTH_SOCK") {
494
- const sock = process.env.SSH_AUTH_SOCK;
495
- return sock !== void 0 && sock !== "" ? sock : void 0;
496
- }
497
- return expandHome(trimmed);
498
- }
499
- /**
500
- * Normalize a ProxyCommand for storage: trim, and treat an empty value or
501
- * OpenSSH's `none` keyword as "no proxy command" (an explicit clear).
502
- */
503
- function normalizeProxyCommand(raw) {
504
- const trimmed = raw?.trim();
505
- if (trimmed === void 0 || trimmed === "") return void 0;
506
- if (trimmed.toLowerCase() === "none") return void 0;
507
- return trimmed;
508
- }
509
- /**
510
- * Read an ssh_config `ForwardAgent` value into the stored boolean flag. Only
511
- * an explicit yes/true/on enables forwarding; an absent value, no/false/off,
512
- * and anything unrecognized leave it off instead of failing the import — an
513
- * unknown keyword must never cost the user the whole Host block.
514
- */
515
- function parseForwardAgentValue(raw) {
516
- const value = raw?.trim().toLowerCase();
517
- return value === "yes" || value === "true" || value === "on";
518
- }
519
- /** Expand a leading `~` in a filesystem path. */
520
- function expandHome(path) {
521
- if (path === "~") return homedir();
522
- if (path.startsWith("~/")) return join(homedir(), path.slice(2));
523
- return path;
524
- }
525
- //#endregion
526
- //#region src/engine/proxy-command.ts
527
- /**
528
- * OpenSSH-compatible ProxyCommand transport: run the command with the user's
529
- * shell and expose its stdio as a Duplex that ssh2 accepts as `sock`.
530
- *
531
- * The command comes verbatim from the user's own 0600 store file and runs with
532
- * the DSH host process's privileges — the same trust the `ssh(1)` client gives
533
- * the identical line in `~/.ssh/config`.
534
- */
535
- /** How long a killed proxy command may linger before SIGKILL (ms). */
536
- const KILL_GRACE_MS = 2e3;
537
- /** Expand the OpenSSH ProxyCommand tokens; unknown %X sequences stay verbatim. */
538
- function expandProxyTokens(command, target) {
539
- return command.replace(/%[hprn%]/g, (token) => {
540
- switch (token) {
541
- case "%h": return target.host;
542
- case "%p": return String(target.port);
543
- case "%r": return target.user;
544
- case "%n": return target.alias;
545
- default: return "%";
546
- }
547
- });
548
- }
549
- /**
550
- * The shell OpenSSH itself would use on this platform: the user's shell with
551
- * `-c` on POSIX, cmd.exe on Windows (where the whole command must stay one
552
- * verbatim argument, exactly as Node's own `shell: true` does it).
553
- */
554
- function spawnSpec(command) {
555
- if (process.platform === "win32") return {
556
- file: process.env.ComSpec ?? "cmd.exe",
557
- args: [
558
- "/d",
559
- "/s",
560
- "/c",
561
- "\"" + command + "\""
562
- ],
563
- windowsVerbatimArguments: true
564
- };
565
- return {
566
- file: process.env.SHELL ?? "/bin/sh",
567
- args: ["-c", command]
568
- };
569
- }
570
- /**
571
- * Start one ProxyCommand and bridge its stdio into a Duplex.
572
- *
573
- * Failure modes are reported through the stream: a spawn error, or an exit
574
- * before the SSH handshake finished, destroys it with the exit status and the
575
- * tail of the command's stderr instead of letting ssh2 wait for its own
576
- * `readyTimeout`.
577
- */
578
- function startProxyCommand(rawCommand, target) {
579
- const spec = spawnSpec(expandProxyTokens(rawCommand, target));
580
- const child = spawn(spec.file, spec.args, {
581
- stdio: [
582
- "pipe",
583
- "pipe",
584
- "pipe"
585
- ],
586
- windowsHide: true,
587
- ...spec.windowsVerbatimArguments === true ? { windowsVerbatimArguments: true } : {},
588
- ...process.platform === "win32" ? {} : { detached: true }
589
- });
590
- let stderr = "";
591
- child.stderr?.on("data", (chunk) => {
592
- stderr = (stderr + chunk.toString("utf8")).slice(-4096);
593
- });
594
- let killed = false;
595
- const kill = () => {
596
- if (killed) return;
597
- killed = true;
598
- const pid = child.pid;
599
- const group = process.platform !== "win32" && pid !== void 0;
600
- try {
601
- if (group) process.kill(-pid, "SIGTERM");
602
- else child.kill();
603
- } catch {}
604
- setTimeout(() => {
605
- try {
606
- if (group) process.kill(-pid, "SIGKILL");
607
- else child.kill("SIGKILL");
608
- } catch {}
609
- }, KILL_GRACE_MS).unref();
610
- };
611
- function formatExitError(code, signal, stderrDetail) {
612
- const status = signal !== null ? "signal " + signal : "code " + String(code ?? "unknown");
613
- const detail = stderrDetail.trim();
614
- return /* @__PURE__ */ new Error("ProxyCommand exited (" + status + ")" + (detail === "" ? "" : ": " + detail));
615
- }
616
- const stream = new Duplex({
617
- read() {
618
- child.stdout?.resume();
619
- },
620
- write(chunk, _encoding, callback) {
621
- const stdin = child.stdin;
622
- if (stream.destroyed || stdin === null || stdin.destroyed) {
623
- callback(/* @__PURE__ */ new Error("ProxyCommand stdin is already closed"));
624
- return;
625
- }
626
- stdin.write(chunk, (err) => {
627
- if (!err) {
628
- callback();
629
- return;
630
- }
631
- if (child.exitCode !== null && child.exitCode !== 0 || child.signalCode !== null) {
632
- const exitErr = formatExitError(child.exitCode, child.signalCode, stderr);
633
- fail(exitErr);
634
- callback(exitErr);
635
- return;
636
- }
637
- let resolved = false;
638
- const onExit = (code, signal) => {
639
- if (resolved) return;
640
- resolved = true;
641
- clearTimeout(timer);
642
- const exitErr = code !== null && code !== 0 || signal !== null ? formatExitError(code, signal, stderr) : /* @__PURE__ */ new Error("ProxyCommand transport write failed: " + err.message);
643
- fail(exitErr);
644
- callback(exitErr);
645
- };
646
- const timer = setTimeout(() => {
647
- if (resolved) return;
648
- resolved = true;
649
- child.removeListener("exit", onExit);
650
- const transportErr = /* @__PURE__ */ new Error("ProxyCommand transport write failed: " + err.message);
651
- fail(transportErr);
652
- callback(transportErr);
653
- }, 200);
654
- timer.unref();
655
- child.once("exit", onExit);
656
- });
657
- },
658
- final(callback) {
659
- const stdin = child.stdin;
660
- if (stdin === null || stdin.destroyed) {
661
- callback();
662
- return;
663
- }
664
- stdin.end((err) => {
665
- if (err) callback(/* @__PURE__ */ new Error("ProxyCommand transport close failed: " + err.message));
666
- else callback();
667
- });
668
- },
669
- destroy(error, callback) {
670
- kill();
671
- callback(error);
672
- }
673
- });
674
- stream.on("error", () => {});
675
- let failed = false;
676
- const fail = (error) => {
677
- if (failed || stream.destroyed) return;
678
- failed = true;
679
- stream.destroy(error);
680
- };
681
- let stdoutEnded = false;
682
- let exited = false;
683
- const finishIfClean = () => {
684
- if (exited && stdoutEnded && !failed && !stream.destroyed) stream.push(null);
685
- };
686
- child.stdout?.on("data", (chunk) => {
687
- if (stream.push(chunk) === false) child.stdout?.pause();
688
- });
689
- child.stdout?.on("end", () => {
690
- stdoutEnded = true;
691
- finishIfClean();
692
- });
693
- child.stdout?.on("error", (error) => {
694
- fail(/* @__PURE__ */ new Error("ProxyCommand stdout error: " + error.message));
695
- });
696
- child.stdin?.on("error", (error) => {
697
- if (child.exitCode !== null && child.exitCode !== 0 || child.signalCode !== null) {
698
- fail(formatExitError(child.exitCode, child.signalCode, stderr));
699
- return;
700
- }
701
- const timer = setTimeout(() => {
702
- fail(/* @__PURE__ */ new Error("ProxyCommand transport error: " + error.message));
703
- }, 200);
704
- timer.unref();
705
- child.once("exit", (code, signal) => {
706
- clearTimeout(timer);
707
- if (code !== null && code !== 0 || signal !== null) fail(formatExitError(code, signal, stderr));
708
- });
709
- });
710
- child.on("error", (error) => {
711
- fail(/* @__PURE__ */ new Error("ProxyCommand could not start: " + error.message));
712
- });
713
- child.on("exit", (code, signal) => {
714
- exited = true;
715
- if (code !== null && code !== 0 || signal !== null) {
716
- fail(formatExitError(code, signal, stderr));
717
- return;
718
- }
719
- finishIfClean();
720
- });
721
- return {
722
- stream,
723
- child
724
- };
725
- }
726
- //#endregion
727
- //#region src/engine/connection-pool.ts
728
- /**
729
- * Connection pool: per-alias persistent ssh2 connections with multi-hop jump
730
- * support, the acquire / dispose / sweep lifecycle, and the pooled exec path.
731
- */
732
- /**
733
- * Default ceiling for TCP connect, SSH key exchange and user authentication
734
- * together (ms). Password authentication behind PAM / LDAP can outlast the
735
- * previous 15 s ceiling while the server still eventually accepts it.
736
- */
737
- const DEFAULT_CONNECT_TIMEOUT_MS = 3e4;
738
- /** Default engine knobs (applied when an option is omitted). */
739
- const DEFAULTS = {
740
- idleTimeoutMs: 30 * 6e4,
741
- connectTimeoutMs: DEFAULT_CONNECT_TIMEOUT_MS,
742
- keepaliveIntervalMs: 15e3,
743
- maxOutputBytes: 2 * 1024 * 1024,
744
- defaultExecTimeoutMs: 6e4,
745
- defaultMaxWorkers: 8,
746
- sftpConcurrency: 8
747
- };
748
- /** Build the ssh2 connect config for one entry (key read from disk). */
749
- function buildConnectConfig(entry, sock, opts) {
750
- const config = {
751
- host: entry.host,
752
- port: entry.port,
753
- username: entry.user,
754
- readyTimeout: opts.connectTimeoutMs,
755
- keepaliveInterval: opts.keepaliveIntervalMs,
756
- keepaliveCountMax: 3,
757
- tryKeyboard: true
758
- };
759
- if (sock !== void 0) config.sock = sock;
760
- if (entry.auth.kind === "password") config.password = entry.auth.password;
761
- else if (entry.auth.kind === "agent") {
762
- const agentPath = resolveAgentPath(entry.auth.agentPath);
763
- if (agentPath === void 0) throw new Error("ssh-agent is not available: set SSH_AUTH_SOCK or configure an agent path (use 'pageant' for PuTTY Pageant on Windows)");
764
- config.agent = agentPath;
765
- } else {
766
- const keyPath = entry.auth.keyPath === void 0 ? void 0 : expandHome(entry.auth.keyPath);
767
- if (keyPath === void 0 || !existsSync(keyPath)) throw new Error("private key not found: " + (entry.auth.keyPath ?? "(unset)"));
768
- config.privateKey = readFileSync(keyPath, "utf8");
769
- if (entry.auth.passphrase !== void 0 && entry.auth.passphrase !== "") config.passphrase = entry.auth.passphrase;
770
- }
771
- if (entry.forwardAgent === true) {
772
- const agentPath = typeof config.agent === "string" ? config.agent : resolveForwardAgentPath(entry.auth.agentPath);
773
- if (agentPath === void 0) throw new Error("agent forwarding is enabled for this host but no ssh-agent endpoint is available: set SSH_AUTH_SOCK, start Pageant on Windows, or configure an agent path");
774
- config.agent = agentPath;
775
- config.agentForward = true;
776
- }
777
- return config;
778
- }
779
- /**
780
- * The default ssh-agent endpoint on Windows: the named pipe the native
781
- * OpenSSH ssh-agent service listens on. ssh2 connects to a named pipe for any
782
- * path matching its Windows pipe form, so the default is a real endpoint
783
- * rather than a protocol name (#1910). PuTTY Pageant is still reachable — it
784
- * is what the literal `pageant` agent path selects — but it is no longer the
785
- * assumption.
786
- */
787
- const WINDOWS_AGENT_PIPE = "\\\\.\\pipe\\openssh-ssh-agent";
788
- /** Resolve the ssh2 agent path for 'agent' auth. */
789
- function resolveAgentPath(agentPath) {
790
- const explicit = normalizeAgentPath(agentPath);
791
- if (explicit !== void 0) return explicit;
792
- const sock = process.env.SSH_AUTH_SOCK;
793
- if (sock !== void 0 && sock !== "") return sock;
794
- if (process.platform === "win32") return WINDOWS_AGENT_PIPE;
795
- }
796
- /**
797
- * Resolve the ssh-agent endpoint that forwarding brokers signatures through:
798
- * an explicitly configured agent path wins, then SSH_AUTH_SOCK, then the
799
- * native OpenSSH named pipe on Windows. Undefined means no endpoint exists on
800
- * this machine.
801
- *
802
- * Forwarding shares the auth resolution on purpose — the endpoint a host
803
- * signs through is the same one it authenticates with — but it is a separate
804
- * name so the forwarding path can evolve without touching auth.
805
- */
806
- function resolveForwardAgentPath(agentPath) {
807
- return resolveAgentPath(agentPath);
808
- }
809
- /**
810
- * Name the phase that actually stalled. ssh2 reports every pre-ready timeout
811
- * as "Timed out while waiting for handshake", including one that expires
812
- * during user authentication after a completed key exchange.
813
- *
814
- * @param timeoutMs - the configured `readyTimeout` (0 disables it).
815
- * @param handshakeComplete - whether ssh2 completed the key exchange.
816
- * @returns the operator-facing timeout message.
817
- */
818
- function readyTimeoutMessage(timeoutMs, handshakeComplete) {
819
- const budget = typeof timeoutMs === "number" && timeoutMs > 0 ? " after " + timeoutMs + " ms" : "";
820
- return handshakeComplete ? "SSH authentication timed out" + budget + ": TCP connect and key exchange completed, but the server did not finish authenticating the user - raise the dsh-ssh connectTimeoutMs setting if this host is slow" : "SSH connection timed out" + budget + " before key exchange completed: TCP connect or the SSH key exchange did not finish - raise the dsh-ssh connectTimeoutMs setting if this host is slow";
821
- }
822
- /**
823
- * Whether ssh2 ended the attempt with its pre-ready timeout. The level is the
824
- * stable discriminator; the message is reused for connect, key exchange and
825
- * authentication alike.
826
- */
827
- function isReadyTimeout(error) {
828
- return error.level === "client-timeout";
829
- }
830
- /** Connect one ssh2 client (resolve on ready, reject on error/close). */
831
- function connectClient(config, onKeyboardInteractive) {
832
- return new Promise((resolve, reject) => {
833
- const client = new Client();
834
- let settled = false;
835
- let handshakeComplete = false;
836
- const fail = (error) => {
837
- if (settled) return;
838
- settled = true;
839
- const sock = config.sock;
840
- if (sock !== void 0 && typeof sock.destroy === "function") try {
841
- sock.destroy();
842
- } catch {}
843
- try {
844
- client.destroy();
845
- } catch {}
846
- const cause = error instanceof Error ? error : new Error(String(error));
847
- reject(isReadyTimeout(cause) ? new Error(readyTimeoutMessage(config.readyTimeout, handshakeComplete)) : cause);
848
- };
849
- client.once("handshake", () => {
850
- handshakeComplete = true;
851
- });
852
- client.once("ready", () => {
853
- if (settled) return;
854
- settled = true;
855
- resolve(client);
856
- });
857
- client.on("keyboard-interactive", (name, instructions, instructionsLang, prompts, finish) => {
858
- if (onKeyboardInteractive !== void 0) {
859
- onKeyboardInteractive(name, instructions, instructionsLang, prompts.map((p) => ({
860
- prompt: p.prompt,
861
- echo: Boolean(p.echo)
862
- })), finish);
863
- return;
864
- }
865
- if (config.password !== void 0 && prompts.length > 0 && prompts.every((p) => /password/i.test(p.prompt))) {
866
- finish(prompts.map(() => config.password));
867
- return;
868
- }
869
- fail(/* @__PURE__ */ new Error("Authentication failed (keyboard-interactive): " + (prompts.map((p) => p.prompt.trim()).join(", ") || "unsupported interactive challenge")));
870
- });
871
- client.on("error", fail);
872
- try {
873
- client.connect(config);
874
- } catch (error) {
875
- fail(error);
876
- }
877
- });
878
- }
879
- /** Cap captured output at the configured byte budget (marks truncation). */
880
- function appendOutput(target, chunk, maxBytes) {
881
- if (target.truncated) return;
882
- if (target.text.length + chunk.length > maxBytes) {
883
- let cut = chunk.toString("utf8").slice(0, maxBytes - target.text.length);
884
- if (/[\uD800-\uDBFF]$/.test(cut)) cut = cut.slice(0, -1);
885
- target.text += cut + "…[output truncated]";
886
- target.truncated = true;
887
- return;
888
- }
889
- target.text += chunk.toString("utf8");
890
- }
891
- /** The ProxyCommand token source for one entry. */
892
- function proxyTargetOf(entry) {
893
- return {
894
- host: entry.host,
895
- port: entry.port,
896
- user: entry.user,
897
- alias: entry.alias
898
- };
899
- }
900
- /**
901
- * Parse an OpenSSH jump hop written as an address: `[user@]host[:port]`
902
- * (an IPv6 literal must be bracketed). Returns undefined when the value is not
903
- * an address at all.
904
- */
905
- function parseJumpSpec(spec) {
906
- const trimmed = spec.trim();
907
- if (trimmed === "") return void 0;
908
- const at = trimmed.lastIndexOf("@");
909
- const user = at >= 0 ? trimmed.slice(0, at) : void 0;
910
- const rest = at >= 0 ? trimmed.slice(at + 1) : trimmed;
911
- if (rest === "") return void 0;
912
- let host = rest;
913
- let portText;
914
- if (rest.startsWith("[")) {
915
- const end = rest.indexOf("]");
916
- if (end < 0) return void 0;
917
- host = rest.slice(1, end);
918
- const tail = rest.slice(end + 1);
919
- if (tail.startsWith(":")) portText = tail.slice(1);
920
- else if (tail !== "") return void 0;
921
- } else {
922
- const colon = rest.indexOf(":");
923
- if (colon >= 0) {
924
- host = rest.slice(0, colon);
925
- portText = rest.slice(colon + 1);
926
- }
927
- }
928
- if (host === "") return void 0;
929
- let port;
930
- if (portText !== void 0) {
931
- port = Number(portText);
932
- if (!Number.isInteger(port) || port < 1 || port > 65535) return void 0;
933
- }
934
- return {
935
- host,
936
- ...port !== void 0 ? { port } : {},
937
- ...user !== void 0 && user !== "" ? { user } : {}
938
- };
939
- }
940
- /**
941
- * Resolve one ProxyJump spec: an alias configured in this plugin wins, and any
942
- * other value is read as an OpenSSH address whose credentials come from the
943
- * target entry (an ad-hoc hop has no stored auth of its own).
944
- *
945
- * An address hop deliberately carries no forwardAgent flag: OpenSSH's
946
- * ForwardAgent is a per-Host setting and an ad-hoc address was never
947
- * configured, so it must never inherit the target's opt-in. A hop written as
948
- * an alias uses that alias's own entry, which is how a user forwards on a
949
- * bastion on purpose.
950
- */
951
- function resolveHop(engine, entry, spec) {
952
- const configured = engine.store.find(spec);
953
- if (configured !== void 0) return configured;
954
- const parsed = parseJumpSpec(spec);
955
- if (parsed === void 0) throw new Error("proxyJump '" + spec + "' is neither a configured alias nor a [user@]host[:port] address");
956
- const now = Date.now();
957
- return {
958
- alias: spec,
959
- host: parsed.host,
960
- port: parsed.port ?? 22,
961
- user: parsed.user ?? process.env.USER ?? entry.user,
962
- auth: entry.auth,
963
- proxyJump: [],
964
- tags: [],
965
- createdAt: now,
966
- updatedAt: now
967
- };
968
- }
969
- /**
970
- * Build one full jump chain for an entry: hop clients connected through in
971
- * order, each forwarding a stream to the next destination, ending with the
972
- * target client. Shared by the pool and standalone shell sessions.
973
- *
974
- * A ProxyCommand is the transport that reaches its own host, so the entry's
975
- * own command seeds the chain when there is no jump chain, and the first hop's
976
- * command is used when the hop carries one.
977
- */
978
- async function connectChain(engine, entry, onKeyboardInteractive) {
979
- const hops = [];
980
- const chain = entry.proxyJump;
981
- if (chain.length > 0 && entry.proxyCommand !== void 0) throw new Error("entry '" + entry.alias + "' declares both proxyCommand and proxyJump — pick one transport per host");
982
- /** Transports this call started; destroyed on every failure path. */
983
- const transports = [];
984
- const startTransport = (owner) => {
985
- const { stream } = startProxyCommand(owner.proxyCommand, proxyTargetOf(owner));
986
- transports.push(stream);
987
- return stream;
988
- };
989
- let sock = entry.proxyCommand !== void 0 ? startTransport(entry) : void 0;
990
- try {
991
- for (let index = 0; index < chain.length; index += 1) {
992
- const spec = chain[index];
993
- const hop = resolveHop(engine, entry, spec);
994
- if (index > 0 && hop.proxyCommand !== void 0) throw new Error("proxyJump hop '" + spec + "' declares a proxyCommand, which is only supported on the first hop");
995
- const hopSock = index === 0 && hop.proxyCommand !== void 0 ? startTransport(hop) : sock;
996
- let hopClient;
997
- try {
998
- hopClient = await connectClient(buildConnectConfig(hop, hopSock, engine.opts), onKeyboardInteractive);
999
- } catch (error) {
1000
- throw new Error("proxyJump hop '" + spec + "' (" + hop.user + "@" + hop.host + ":" + hop.port + "): " + (error instanceof Error ? error.message : String(error)));
1001
- }
1002
- hops.push(hopClient);
1003
- const next = index + 1 < chain.length ? resolveHop(engine, entry, chain[index + 1]) : void 0;
1004
- const nextHost = next !== void 0 ? next.host : entry.host;
1005
- const nextPort = next !== void 0 ? next.port : entry.port;
1006
- sock = await new Promise((resolve, reject) => {
1007
- hopClient.forwardOut("127.0.0.1", 0, nextHost, nextPort, (error, stream) => {
1008
- if (error !== void 0) reject(/* @__PURE__ */ new Error("proxyJump hop '" + spec + "' could not forward to " + nextHost + ":" + nextPort + ": " + error.message));
1009
- else resolve(stream);
1010
- });
1011
- });
1012
- }
1013
- } catch (error) {
1014
- for (const client of hops) client.end();
1015
- for (const stream of transports) try {
1016
- stream.destroy();
1017
- } catch {}
1018
- throw error;
1019
- }
1020
- let target;
1021
- try {
1022
- target = await connectClient(buildConnectConfig(entry, sock, engine.opts), onKeyboardInteractive);
1023
- return {
1024
- client: target,
1025
- hops
1026
- };
1027
- } catch (error) {
1028
- for (const client of hops) client.end();
1029
- for (const stream of transports) try {
1030
- stream.destroy();
1031
- } catch {}
1032
- if (target !== void 0) try {
1033
- target.destroy();
1034
- } catch {}
1035
- throw error;
1036
- }
1037
- }
1038
- /** Connect (or reuse) the pooled chain for one alias; pins nothing. */
1039
- async function acquire(engine, alias) {
1040
- const pending = engine.acquireQueue.get(alias);
1041
- if (pending !== void 0) return pending;
1042
- const task = doAcquire(engine, alias);
1043
- engine.acquireQueue.set(alias, task);
1044
- try {
1045
- return await task;
1046
- } finally {
1047
- if (engine.acquireQueue.get(alias) === task) engine.acquireQueue.delete(alias);
1048
- }
1049
- }
1050
- async function doAcquire(engine, alias) {
1051
- const entry = engine.store.find(alias);
1052
- if (entry === void 0) throw new Error("alias '" + alias + "' not found — add it first");
1053
- const { client, hops } = await connectChain(engine, entry);
1054
- const record = {
1055
- client,
1056
- hops,
1057
- idleAt: Date.now(),
1058
- pinned: false,
1059
- broken: false,
1060
- inFlight: 0
1061
- };
1062
- client.on("error", () => {
1063
- record.broken = true;
1064
- });
1065
- client.on("close", () => {
1066
- record.broken = true;
1067
- });
1068
- engine.pool.set(alias, record);
1069
- return record;
1070
- }
1071
- /**
1072
- * Tear down one alias's record. When `record` is given and no longer the
1073
- * pooled record for the alias (a concurrent acquire replaced it), nothing
1074
- * is torn down — the connection belongs to someone else now.
1075
- */
1076
- function disposeRecord(engine, alias, record) {
1077
- const current = engine.pool.get(alias);
1078
- if (record !== void 0 && current !== record) return;
1079
- if (current === void 0) return;
1080
- engine.pool.delete(alias);
1081
- endRecordChain(current);
1082
- }
1083
- /** End one record's client and hop chain (best-effort, safe to repeat). */
1084
- function endRecordChain(record) {
1085
- try {
1086
- record.client.end();
1087
- } catch {}
1088
- for (const hop of record.hops) try {
1089
- hop.end();
1090
- } catch {}
1091
- }
1092
- /** Close connections idle beyond the threshold (skips pinned and in-flight). */
1093
- function sweepPool(engine) {
1094
- const cutoff = Date.now() - engine.opts.idleTimeoutMs;
1095
- for (const [alias, record] of engine.pool) if (!record.pinned && record.inFlight === 0 && record.idleAt < cutoff) disposeRecord(engine, alias, record);
1096
- }
1097
- /**
1098
- * Run `fn` with a live client for `alias`, reconnecting (up to the
1099
- * attempt budget) when the connection broke mid-flight.
1100
- */
1101
- async function withClient(engine, alias, fn, attempts = 3, signal) {
1102
- let lastError;
1103
- for (let attempt = 1; attempt <= attempts; attempt += 1) {
1104
- let record = engine.pool.get(alias);
1105
- if (record === void 0 || record.broken) {
1106
- if (record !== void 0) disposeRecord(engine, alias, record);
1107
- record = await acquire(engine, alias);
1108
- }
1109
- record.idleAt = Date.now();
1110
- record.inFlight += 1;
1111
- try {
1112
- const result = await fn(record.client);
1113
- record.idleAt = Date.now();
1114
- return result;
1115
- } catch (error) {
1116
- lastError = error;
1117
- if (signal?.aborted === true) throw error;
1118
- if (!record.broken) throw error;
1119
- disposeRecord(engine, alias, record);
1120
- } finally {
1121
- record.inFlight -= 1;
1122
- }
1123
- }
1124
- throw lastError instanceof Error ? lastError : new Error(String(lastError));
1125
- }
1126
- /** Run one command on `alias` (reusing the pooled connection). */
1127
- async function execCommand(engine, alias, command, timeoutMs, signal) {
1128
- const started = Date.now();
1129
- const budget = timeoutMs !== void 0 && timeoutMs > 0 ? timeoutMs : engine.opts.defaultExecTimeoutMs;
1130
- return withClient(engine, alias, async (client) => {
1131
- return await new Promise((resolve, reject) => {
1132
- let aborted = signal !== void 0 && signal.aborted;
1133
- let kill = () => {};
1134
- const onAbort = () => {
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();
1154
- const stdout = {
1155
- text: "",
1156
- truncated: false
1157
- };
1158
- const stderr = {
1159
- text: "",
1160
- truncated: false
1161
- };
1162
- let timedOut = false;
1163
- let settled = false;
1164
- /** One cancelled outcome: the remote channel was killed on caller request. */
1165
- const cancelledResult = () => ({
1166
- success: false,
1167
- exitCode: null,
1168
- timedOut: false,
1169
- stdout: stdout.text,
1170
- stderr: stderr.text,
1171
- durationMs: Date.now() - started,
1172
- error: "command cancelled by the caller"
1173
- });
1174
- const finish = () => {
1175
- if (settled) return;
1176
- settled = true;
1177
- clearTimeout(timer);
1178
- signal?.removeEventListener("abort", onAbort);
1179
- resolve({
1180
- success: false,
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
- });
1188
- };
1189
- const timer = setTimeout(() => {
1190
- timedOut = true;
1191
- try {
1192
- stream.signal("KILL");
1193
- } catch {}
1194
- try {
1195
- stream.close();
1196
- } catch {}
1197
- finish();
1198
- }, budget);
1199
- stream.on("data", (chunk) => appendOutput(stdout, chunk, engine.opts.maxOutputBytes));
1200
- stream.stderr.on("data", (chunk) => appendOutput(stderr, chunk, engine.opts.maxOutputBytes));
1201
- stream.on("close", (code) => {
1202
- if (settled) return;
1203
- settled = true;
1204
- clearTimeout(timer);
1205
- signal?.removeEventListener("abort", onAbort);
1206
- if (aborted) {
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)"));
1212
- return;
1213
- }
1214
- resolve({
1215
- success: code === 0,
1216
- exitCode: code,
1217
- timedOut,
1218
- stdout: stdout.text,
1219
- stderr: stderr.text,
1220
- durationMs: Date.now() - started
1221
- });
1222
- });
1223
- stream.on("error", (streamError) => {
1224
- if (settled) return;
1225
- settled = true;
1226
- clearTimeout(timer);
1227
- signal?.removeEventListener("abort", onAbort);
1228
- if (aborted) {
1229
- resolve(cancelledResult());
1230
- return;
1231
- }
1232
- reject(streamError);
1233
- });
1234
- });
1235
- });
1236
- });
1237
- }
1238
- //#endregion
1239
- //#region src/engine/pty.ts
1240
- /**
1241
- * PTY shell sessions for the web terminal: a standalone (non-pooled)
1242
- * ssh2 connection with a long-lived shell channel, resize, and pausable
1243
- * output delivery.
1244
- */
1245
- /**
1246
- * Open a PTY shell session for the web terminal (standalone connection).
1247
- * The shell is a long-lived exclusive stream: it uses its own connection so
1248
- * closing it can never tear down a pooled exec/tunnel sharing the alias.
1249
- */
1250
- async function openShell(engine, alias, size, onKeyboardInteractive) {
1251
- const entry = engine.store.find(alias);
1252
- if (entry === void 0) throw new Error("alias '" + alias + "' not found — add it first");
1253
- const { client, hops } = await connectChain(engine, entry, onKeyboardInteractive);
1254
- return await new Promise((resolve, reject) => {
1255
- client.shell({
1256
- term: "xterm-256color",
1257
- cols: size.cols,
1258
- rows: size.rows
1259
- }, (error, stream) => {
1260
- if (error !== void 0) {
1261
- try {
1262
- client.end();
1263
- } catch {}
1264
- for (const hop of hops) try {
1265
- hop.end();
1266
- } catch {}
1267
- reject(error);
1268
- return;
1269
- }
1270
- let tornDown = false;
1271
- const teardown = () => {
1272
- if (tornDown) return;
1273
- tornDown = true;
1274
- try {
1275
- client.end();
1276
- } catch {}
1277
- for (const hop of hops) try {
1278
- hop.end();
1279
- } catch {}
1280
- };
1281
- const session = {
1282
- send: (data) => {
1283
- try {
1284
- stream.write(data);
1285
- } catch {}
1286
- },
1287
- resize: (cols, rows) => {
1288
- try {
1289
- stream.setWindow(rows, cols, rows, cols);
1290
- } catch {}
1291
- },
1292
- close: () => {
1293
- try {
1294
- stream.close();
1295
- } catch {}
1296
- teardown();
1297
- },
1298
- pause: () => {
1299
- try {
1300
- stream.pause();
1301
- } catch {}
1302
- },
1303
- resume: () => {
1304
- try {
1305
- stream.resume();
1306
- } catch {}
1307
- }
1308
- };
1309
- stream.on("data", (chunk) => {
1310
- session.onData?.(chunk);
1311
- });
1312
- stream.on("close", (code) => {
1313
- teardown();
1314
- session.onExit?.(code);
1315
- });
1316
- stream.on("error", (streamError) => {
1317
- teardown();
1318
- session.onExit?.(null, streamError instanceof Error ? streamError.message : String(streamError));
1319
- });
1320
- resolve(session);
1321
- });
1322
- });
1323
- }
1324
- //#endregion
1325
- //#region src/engine/sftp.ts
1326
- /**
1327
- * SFTP transfers: upload (file or recursive tree), single-file download, and
1328
- * remote directory listing. Every channel is opened once per operation and
1329
- * released exactly once so sshd's MaxSessions cap is never exhausted.
1330
- */
1331
- /** Walk a local directory, collecting relative paths of every file. */
1332
- function walkLocalDir(root) {
1333
- const files = [];
1334
- const visit = (dir) => {
1335
- for (const name of readdirSync(dir)) {
1336
- const full = join(dir, name);
1337
- const stat = lstatSync(full);
1338
- if (stat.isSymbolicLink()) continue;
1339
- if (stat.isDirectory()) visit(full);
1340
- else if (stat.isFile()) files.push(relative(root, full).replaceAll("\\", "/"));
1341
- }
1342
- };
1343
- visit(root);
1344
- return files;
1345
- }
1346
- /** Upload one local file (or directory tree) to a remote path. */
1347
- async function upload(engine, alias, localPath, remotePath, recursive, onProgress) {
1348
- if (!remotePath.startsWith("/")) throw new Error("remotePath must be an absolute path (got '" + remotePath + "')");
1349
- const local = resolve(localPath);
1350
- if (!existsSync(local)) throw new Error("local path not found: '" + localPath + "'");
1351
- return withClient(engine, alias, (client) => withSftp(client, async (sftp) => {
1352
- const stat = statSync(local);
1353
- let files;
1354
- if (stat.isDirectory()) {
1355
- if (!recursive) throw new Error("'" + localPath + "' is a directory — enable recursive upload");
1356
- files = walkLocalDir(local);
1357
- await ensureRemoteDir(sftp, remotePath);
1358
- } else {
1359
- files = [""];
1360
- await ensureRemoteDir(sftp, dirname(remotePath));
1361
- }
1362
- let bytes = 0;
1363
- for (const rel of files) {
1364
- const src = rel === "" ? local : join(local, rel);
1365
- const remoteRel = rel.split(/[\\/]/).join("/");
1366
- await fastPut(sftp, src, rel === "" ? remotePath : remotePath.replace(/\/$/, "") + "/" + remoteRel, engine.opts.sftpConcurrency, onProgress);
1367
- bytes += statSync(src).size;
1368
- }
1369
- return {
1370
- bytes,
1371
- files: files.length
1372
- };
1373
- }));
1374
- }
1375
- /** Download one remote file to a local path. */
1376
- async function download(engine, alias, remotePath, localPath, onProgress) {
1377
- return withClient(engine, alias, (client) => withSftp(client, async (sftp) => {
1378
- if ((await new Promise((resolve, reject) => {
1379
- sftp.stat(remotePath, (error, stats) => error !== void 0 ? reject(error) : resolve(stats));
1380
- })).isDirectory()) throw new Error("'" + remotePath + "' is a directory — directory download is not supported yet (download individual files)");
1381
- const local = resolve(localPath);
1382
- if (!existsSync(dirname(local))) mkdirSync(dirname(local), { recursive: true });
1383
- await fastGet(sftp, remotePath, local, engine.opts.sftpConcurrency, onProgress);
1384
- return { bytes: statSync(local).size };
1385
- }));
1386
- }
1387
- /** List a remote directory (file browser). */
1388
- async function ls(engine, alias, path) {
1389
- return withClient(engine, alias, (client) => withSftp(client, async (sftp) => {
1390
- return await new Promise((resolve, reject) => {
1391
- sftp.readdir(path, (error, list) => {
1392
- if (error !== void 0) {
1393
- reject(error);
1394
- return;
1395
- }
1396
- resolve(list.map((item) => ({
1397
- name: item.filename,
1398
- type: item.attrs.isDirectory() ? "dir" : item.attrs.isFile() ? "file" : "other",
1399
- size: item.attrs.size,
1400
- mtimeMs: item.attrs.mtime * 1e3,
1401
- mode: item.attrs.mode
1402
- })));
1403
- });
1404
- });
1405
- }));
1406
- }
1407
- /**
1408
- * Open one SFTP channel, run the operation, and release the channel exactly
1409
- * once when the operation settles (success or error). ssh2 keeps each
1410
- * subsystem channel open until end(); without this, every transfer leaks a
1411
- * channel until sshd's MaxSessions cap makes all later opens fail.
1412
- */
1413
- async function withSftp(client, run) {
1414
- const sftp = await sftpChannel(client);
1415
- let ended = false;
1416
- const endOnce = () => {
1417
- if (ended) return;
1418
- ended = true;
1419
- try {
1420
- sftp.end();
1421
- } catch {}
1422
- };
1423
- sftp.once("close", endOnce);
1424
- try {
1425
- return await run(sftp);
1426
- } finally {
1427
- endOnce();
1428
- }
1429
- }
1430
- function sftpChannel(client) {
1431
- return new Promise((resolve, reject) => {
1432
- client.sftp((error, sftp) => error !== void 0 ? reject(error) : resolve(sftp));
1433
- });
1434
- }
1435
- /** Create a remote directory chain (stat-then-mkdir per segment). */
1436
- function ensureRemoteDir(sftp, remote) {
1437
- return new Promise((resolve, reject) => {
1438
- const segments = remote.replace(/^\/+/, "").split("/").filter((segment) => segment !== "");
1439
- const walk = (index) => {
1440
- if (index >= segments.length) {
1441
- resolve();
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);
1460
- });
1461
- }
1462
- /** One fastPut/fastGet transfer with throttled progress (the two directions share everything but the verb). */
1463
- function fastTransfer(sftp, kind, src, dst, concurrency, onProgress) {
1464
- return new Promise((resolve, reject) => {
1465
- const file = kind === "put" ? dst : src;
1466
- const finalSize = () => statSync(kind === "put" ? src : dst).size;
1467
- let last = 0;
1468
- let lastEmit = 0;
1469
- const started = Date.now();
1470
- if (kind === "put") onProgress?.({
1471
- phase: "transferring",
1472
- file,
1473
- transferred: 0,
1474
- total: statSync(src).size,
1475
- percent: 0
1476
- });
1477
- const step = (transferred, _chunk, total) => {
1478
- const now = Date.now();
1479
- if (now - lastEmit < 100 && transferred < total) return;
1480
- lastEmit = now;
1481
- const elapsed = (now - started) / 1e3;
1482
- onProgress?.({
1483
- phase: "transferring",
1484
- file,
1485
- transferred,
1486
- total,
1487
- percent: total > 0 ? Math.round(transferred / total * 1e3) / 10 : 0,
1488
- speedBps: elapsed > 0 ? Math.round((transferred - last) / elapsed) : void 0
1489
- });
1490
- last = transferred;
1491
- };
1492
- const done = (error) => {
1493
- if (error !== void 0) {
1494
- onProgress?.({
1495
- phase: "error",
1496
- file,
1497
- transferred: 0,
1498
- total: 0,
1499
- percent: 0,
1500
- error: String(error)
1501
- });
1502
- reject(error);
1503
- } else {
1504
- onProgress?.({
1505
- phase: "done",
1506
- file,
1507
- transferred: finalSize(),
1508
- total: finalSize(),
1509
- percent: 100
1510
- });
1511
- resolve();
1512
- }
1513
- };
1514
- if (kind === "put") sftp.fastPut(src, dst, {
1515
- concurrency,
1516
- step
1517
- }, done);
1518
- else sftp.fastGet(src, dst, {
1519
- concurrency,
1520
- step
1521
- }, done);
1522
- });
1523
- }
1524
- function fastPut(sftp, src, dst, concurrency, onProgress) {
1525
- return fastTransfer(sftp, "put", src, dst, concurrency, onProgress);
1526
- }
1527
- function fastGet(sftp, src, dst, concurrency, onProgress) {
1528
- return fastTransfer(sftp, "get", src, dst, concurrency, onProgress);
1529
- }
1530
- //#endregion
1531
- //#region src/engine/tunnel.ts
1532
- /**
1533
- * Local port-forward tunnels: one loopback-only listener per tunnel, pinned
1534
- * to a pooled connection so an idle sweep never closes it, with per-tunnel
1535
- * socket tracking and stop (single / alias-scoped / all).
1536
- */
1537
- /** Destroy one socket or channel stream, tolerating an already-dead peer. */
1538
- function destroyQuietly(target) {
1539
- try {
1540
- target.destroy();
1541
- } catch {}
1542
- }
1543
- /**
1544
- * Tear down one tunnel because the SSH link behind it is gone. Idempotent: the
1545
- * tunnel registry is the guard, so a socket callback or a link-death hook that
1546
- * arrives after a manual stop does nothing instead of tearing down twice, and
1547
- * no teardown error can escape into the net connection handler — an exception
1548
- * there terminates the whole host process.
1549
- */
1550
- function abortTunnel(engine, id) {
1551
- try {
1552
- stopTunnel(engine, id);
1553
- } catch {}
1554
- }
1555
- /** Start a local port-forward tunnel (listens on 127.0.0.1 only). */
1556
- async function startTunnel(engine, alias, options) {
1557
- if (!Number.isInteger(options.remotePort) || options.remotePort < 1 || options.remotePort > 65535) throw new Error("remotePort must be an integer in 1..65535");
1558
- if (options.localPort !== void 0 && (!Number.isInteger(options.localPort) || options.localPort < 1 || options.localPort > 65535)) throw new Error("localPort must be an integer in 1..65535");
1559
- if (engine.store.find(alias) === void 0) throw new Error("alias '" + alias + "' not found — add it first");
1560
- const remoteHost = options.remoteHost ?? "127.0.0.1";
1561
- const id = "tun-" + engine.nextTunnelId;
1562
- engine.nextTunnelId += 1;
1563
- const info = {
1564
- id,
1565
- alias,
1566
- localPort: 0,
1567
- remoteHost,
1568
- remotePort: options.remotePort,
1569
- state: "connecting",
1570
- startedAt: Date.now()
1571
- };
1572
- const existing = engine.pool.get(alias);
1573
- if (existing !== void 0 && existing.broken) disposeRecord(engine, alias, existing);
1574
- const record = engine.pool.get(alias) ?? await acquire(engine, alias);
1575
- const client = record.client;
1576
- const sockets = /* @__PURE__ */ new Set();
1577
- const onLinkClosed = () => {
1578
- abortTunnel(engine, id);
1579
- };
1580
- const detachLink = () => {
1581
- client.off("close", onLinkClosed);
1582
- };
1583
- const server = createServer((socket) => {
1584
- sockets.add(socket);
1585
- socket.on("close", () => {
1586
- sockets.delete(socket);
1587
- });
1588
- if (record.broken) {
1589
- destroyQuietly(socket);
1590
- abortTunnel(engine, id);
1591
- return;
1592
- }
1593
- try {
1594
- client.forwardOut("127.0.0.1", 0, remoteHost, options.remotePort, (error, stream) => {
1595
- if (error !== void 0) {
1596
- destroyQuietly(socket);
1597
- return;
1598
- }
1599
- const destroy = () => {
1600
- destroyQuietly(socket);
1601
- try {
1602
- stream.close();
1603
- } catch {}
1604
- };
1605
- stream.on("error", destroy);
1606
- socket.on("error", destroy);
1607
- stream.on("close", destroy);
1608
- socket.on("close", destroy);
1609
- stream.pipe(socket).pipe(stream);
1610
- });
1611
- } catch {
1612
- destroyQuietly(socket);
1613
- abortTunnel(engine, id);
1614
- }
1615
- });
1616
- try {
1617
- await new Promise((resolve, reject) => {
1618
- server.once("error", reject);
1619
- server.listen(options.localPort ?? 0, "127.0.0.1", () => {
1620
- server.removeListener("error", reject);
1621
- resolve();
1622
- });
1623
- });
1624
- } catch (error) {
1625
- if (!record.pinned && record.inFlight === 0) disposeRecord(engine, alias, record);
1626
- throw error;
1627
- }
1628
- record.pinned = true;
1629
- const address = server.address();
1630
- info.localPort = typeof address === "object" && address !== null ? address.port : 0;
1631
- info.state = "forwarding";
1632
- engine.tunnels.set(id, {
1633
- info,
1634
- server,
1635
- alias,
1636
- record,
1637
- sockets,
1638
- detachLink
1639
- });
1640
- client.once("close", onLinkClosed);
1641
- if (record.broken) {
1642
- info.state = "failed";
1643
- info.error = "ssh link closed while the tunnel was starting";
1644
- abortTunnel(engine, id);
1645
- }
1646
- return info;
1647
- }
1648
- /** All active tunnels. */
1649
- function listTunnels(engine) {
1650
- return [...engine.tunnels.values()].map((tunnel) => ({ ...tunnel.info }));
1651
- }
1652
- /** Stop one tunnel (closes the listener, live sockets, and the pinned connection). */
1653
- function stopTunnel(engine, id) {
1654
- const tunnel = engine.tunnels.get(id);
1655
- if (tunnel === void 0) return false;
1656
- engine.tunnels.delete(id);
1657
- try {
1658
- tunnel.detachLink?.();
1659
- } catch {}
1660
- try {
1661
- tunnel.server.close();
1662
- } catch {}
1663
- for (const socket of tunnel.sockets) destroyQuietly(socket);
1664
- tunnel.sockets.clear();
1665
- if (![...engine.tunnels.values()].some((candidate) => candidate.record === tunnel.record)) if (engine.pool.get(tunnel.alias) === tunnel.record) disposeRecord(engine, tunnel.alias, tunnel.record);
1666
- else endRecordChain(tunnel.record);
1667
- return true;
1668
- }
1669
- /** Stop all tunnels (optionally for one alias). */
1670
- function stopAllTunnels(engine, alias) {
1671
- let count = 0;
1672
- for (const [id, tunnel] of [...engine.tunnels]) if (alias === void 0 || tunnel.alias === alias) {
1673
- stopTunnel(engine, id);
1674
- count += 1;
1675
- }
1676
- return count;
1677
- }
1678
- //#endregion
1679
- //#region src/engine/cluster.ts
1680
- /** Run one command against many hosts concurrently. */
1681
- async function cluster(engine, options) {
1682
- const hasAliases = Array.isArray(options.aliases) && options.aliases.some((alias) => typeof alias === "string" && alias.trim() !== "");
1683
- const hasEnvironment = typeof options.environment === "string" && options.environment.trim() !== "";
1684
- const hasTags = Array.isArray(options.tags) && options.tags.some((tag) => typeof tag === "string" && tag.trim() !== "");
1685
- if (!hasAliases && !hasEnvironment && !hasTags) throw new Error("ssh_cluster requires aliases, environment, or tags to limit the target set");
1686
- let targets = engine.store.list();
1687
- if (options.aliases !== void 0 && options.aliases.length > 0) targets = targets.filter((entry) => options.aliases.includes(entry.alias));
1688
- if (options.environment !== void 0 && options.environment !== "") targets = targets.filter((entry) => entry.environment === options.environment);
1689
- if (options.tags !== void 0 && options.tags.length > 0) targets = targets.filter((entry) => options.tags.every((tag) => entry.tags.includes(tag)));
1690
- if (targets.length === 0) return [];
1691
- if (options.maxWorkers !== void 0 && (!Number.isInteger(options.maxWorkers) || options.maxWorkers < 1)) throw new Error("maxWorkers must be a positive integer");
1692
- const workers = Math.min(engine.opts.defaultMaxWorkers, options.maxWorkers ?? engine.opts.defaultMaxWorkers, targets.length);
1693
- const results = [];
1694
- const queue = [...targets];
1695
- const run = async () => {
1696
- while (queue.length > 0) {
1697
- const entry = queue.shift();
1698
- try {
1699
- const result = await execCommand(engine, entry.alias, options.command, options.timeoutMs, options.signal);
1700
- results.push({
1701
- alias: entry.alias,
1702
- ok: result.success,
1703
- exitCode: result.exitCode,
1704
- timedOut: result.timedOut,
1705
- stdout: result.stdout,
1706
- stderr: result.stderr,
1707
- durationMs: result.durationMs
1708
- });
1709
- } catch (error) {
1710
- results.push({
1711
- alias: entry.alias,
1712
- ok: false,
1713
- error: error instanceof Error ? error.message : String(error)
1714
- });
1715
- }
1716
- }
1717
- };
1718
- await Promise.all(Array.from({ length: workers }, () => run()));
1719
- return results;
1720
- }
1721
- //#endregion
1722
- //#region src/engine.ts
1723
- /**
1724
- * The engine. Owns the pool, tunnels, and all operations. One instance per
1725
- * plugin apply; dispose() closes every connection.
1726
- */
1727
- var SshEngine = class {
1728
- store;
1729
- opts;
1730
- pool = /* @__PURE__ */ new Map();
1731
- acquireQueue = /* @__PURE__ */ new Map();
1732
- tunnels = /* @__PURE__ */ new Map();
1733
- nextTunnelId = 1;
1734
- sweepTimer;
1735
- /**
1736
- * @param store - the host config store.
1737
- * @param options - engine knobs (defaults applied).
1738
- */
1739
- constructor(store, options) {
1740
- this.store = store;
1741
- this.opts = {
1742
- ...DEFAULTS,
1743
- ...options
1744
- };
1745
- this.sweepTimer = setInterval(() => sweepPool(this), Math.max(1e4, this.opts.idleTimeoutMs / 4));
1746
- this.sweepTimer.unref?.();
1747
- }
1748
- /**
1749
- * Change the pre-ready ceiling (TCP connect + key exchange + user
1750
- * authentication) for connections opened from now on. A pooled connection
1751
- * keeps serving until it reconnects, because the ceiling governs the
1752
- * connect path only.
1753
- */
1754
- setConnectTimeout(timeoutMs) {
1755
- this.opts.connectTimeoutMs = timeoutMs;
1756
- }
1757
- /** Secret-free host list (filtered by the optional query). */
1758
- list(query) {
1759
- const needle = query?.trim().toLowerCase();
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));
1761
- }
1762
- /** One host summary by alias. */
1763
- find(alias) {
1764
- const entry = this.store.find(alias);
1765
- return entry === void 0 ? void 0 : this.store.summarize(entry);
1766
- }
1767
- /** Run one command on `alias` (reusing the pooled connection). */
1768
- async exec(alias, command, timeoutMs, signal) {
1769
- return execCommand(this, alias, command, timeoutMs, signal);
1770
- }
1771
- /** Run one command against many hosts concurrently. */
1772
- async cluster(options) {
1773
- return cluster(this, options);
1774
- }
1775
- /** Open a PTY shell session for the web terminal (standalone connection). */
1776
- async openShell(alias, size, onKeyboardInteractive) {
1777
- return openShell(this, alias, size, onKeyboardInteractive);
1778
- }
1779
- /** Upload one local file (or directory tree) to a remote path. */
1780
- async upload(alias, localPath, remotePath, recursive, onProgress) {
1781
- return upload(this, alias, localPath, remotePath, recursive, onProgress);
1782
- }
1783
- /** Download one remote file to a local path. */
1784
- async download(alias, remotePath, localPath, onProgress) {
1785
- return download(this, alias, remotePath, localPath, onProgress);
1786
- }
1787
- /** List a remote directory (file browser). */
1788
- async ls(alias, path) {
1789
- return ls(this, alias, path);
1790
- }
1791
- /** Start a local port-forward tunnel (listens on 127.0.0.1 only). */
1792
- async startTunnel(alias, options) {
1793
- return startTunnel(this, alias, options);
1794
- }
1795
- /** All active tunnels. */
1796
- listTunnels() {
1797
- return listTunnels(this);
1798
- }
1799
- /** Stop one tunnel (closes the listener, live sockets, and the pinned connection). */
1800
- stopTunnel(id) {
1801
- return stopTunnel(this, id);
1802
- }
1803
- /** Stop all tunnels (optionally for one alias). */
1804
- stopAllTunnels(alias) {
1805
- return stopAllTunnels(this, alias);
1806
- }
1807
- /**
1808
- * Drop every live artifact bound to one alias: stop its tunnels and close
1809
- * the pooled connection. Host entries that are deleted or whose connection
1810
- * fields change must never keep serving a stale, previously authenticated
1811
- * connection — the next operation re-connects from the current config.
1812
- */
1813
- dropAlias(alias) {
1814
- stopAllTunnels(this, alias);
1815
- disposeRecord(this, alias);
1816
- }
1817
- /** Probe connectivity with a cross-platform shell command. */
1818
- async test(alias) {
1819
- const started = Date.now();
1820
- try {
1821
- const result = await this.exec(alias, "echo ok", 1e4);
1822
- return result.success ? {
1823
- ok: true,
1824
- latencyMs: result.durationMs
1825
- } : {
1826
- ok: false,
1827
- latencyMs: result.durationMs,
1828
- error: "remote exit code " + result.exitCode
1829
- };
1830
- } catch (error) {
1831
- return {
1832
- ok: false,
1833
- latencyMs: Date.now() - started,
1834
- error: error instanceof Error ? error.message : String(error)
1835
- };
1836
- }
1837
- }
1838
- /** Close every pooled connection and tunnel. */
1839
- dispose() {
1840
- if (this.sweepTimer !== void 0) clearInterval(this.sweepTimer);
1841
- for (const id of [...this.tunnels.keys()]) stopTunnel(this, id);
1842
- for (const alias of [...this.pool.keys()]) disposeRecord(this, alias);
1843
- }
1844
- };
1845
- //#endregion
1846
- //#region src/engine/terminal-sessions.ts
1847
- /**
1848
- * Host-side terminal sessions for the web terminal.
1849
- *
1850
- * The PTY shell is owned here, not by the browser view: a view can detach
1851
- * (panel switch, page unmount, a dropped socket) and reattach by session id
1852
- * without tearing the remote shell down, which is what makes the terminal
1853
- * survival property the old DOM takeover used to provide. A session with no
1854
- * attached socket is reaped after an idle window, and an exited one is kept
1855
- * for a short grace window so a reattaching view still sees the final screen.
1856
- */
1857
- /** Pause the shell when an attached socket's send buffer exceeds this… */
1858
- const BACKPRESSURE_HIGH_WATER = 1024 * 1024;
1859
- /** …and resume once every attached socket drains below this. */
1860
- const BACKPRESSURE_LOW_WATER = 512 * 1024;
1861
- /** Scrollback retained for a reattaching view (bytes of UTF-8 output). */
1862
- const DEFAULT_MAX_BUFFER_BYTES = 256 * 1024;
1863
- /** A detached session is reaped after this long. */
1864
- const DEFAULT_IDLE_MS = 600 * 1e3;
1865
- /** An exited session is kept this long for a reattaching view. */
1866
- const DEFAULT_EXIT_GRACE_MS = 60 * 1e3;
1867
- /**
1868
- * The host's terminal session table: open one session per connect, attach any
1869
- * number of sockets, and keep the shell alive across detach.
1870
- */
1871
- var TerminalSessionRegistry = class {
1872
- sessions = /* @__PURE__ */ new Map();
1873
- deps;
1874
- maxBufferBytes;
1875
- idleMs;
1876
- exitGraceMs;
1877
- constructor(deps) {
1878
- this.deps = deps;
1879
- this.maxBufferBytes = deps.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;
1880
- this.idleMs = deps.idleMs ?? DEFAULT_IDLE_MS;
1881
- this.exitGraceMs = deps.exitGraceMs ?? DEFAULT_EXIT_GRACE_MS;
1882
- }
1883
- /** Open a new session for the alias and attach the requesting socket to it. */
1884
- async open(ws, alias, size) {
1885
- const session = {
1886
- id: randomBytes(9).toString("hex"),
1887
- alias,
1888
- sockets: /* @__PURE__ */ new Set(),
1889
- buffer: [],
1890
- bufferBytes: 0,
1891
- exited: false
1892
- };
1893
- this.sessions.set(session.id, session);
1894
- this.bind(ws, session);
1895
- try {
1896
- const shell = await this.deps.openShell(alias, size, this.keyboardInteractive(session));
1897
- if (!this.sessions.has(session.id)) {
1898
- shell.close();
1899
- return;
1900
- }
1901
- session.shell = shell;
1902
- shell.onData = (data) => {
1903
- this.pushOutput(session, data.toString("utf8"));
1904
- };
1905
- shell.onExit = (code, error) => {
1906
- this.finish(session, code, error);
1907
- };
1908
- this.send(session, {
1909
- type: "ready",
1910
- alias,
1911
- sessionId: session.id
1912
- });
1913
- } catch (error) {
1914
- this.sessions.delete(session.id);
1915
- this.send(session, {
1916
- type: "exit",
1917
- code: null,
1918
- error: error instanceof Error ? error.message : String(error)
1919
- });
1920
- }
1921
- }
1922
- /**
1923
- * Attach a socket to an existing session, replaying its scrollback first.
1924
- * @returns false when the session is unknown (expired or already reaped).
1925
- */
1926
- attach(ws, sessionId, size) {
1927
- const session = this.sessions.get(sessionId);
1928
- if (session === void 0) return false;
1929
- this.bind(ws, session);
1930
- this.clearReap(session);
1931
- for (const chunk of session.buffer) this.sendTo(session, ws, {
1932
- type: "output",
1933
- data: chunk
1934
- });
1935
- this.sendTo(session, ws, {
1936
- type: "ready",
1937
- alias: session.alias,
1938
- sessionId: session.id
1939
- });
1940
- if (session.exited) {
1941
- this.sendTo(session, ws, {
1942
- type: "exit",
1943
- code: session.exit?.code ?? null,
1944
- error: session.exit?.error
1945
- });
1946
- this.scheduleReap(session, this.exitGraceMs);
1947
- } else {
1948
- session.shell?.resize(Math.max(2, size.cols), Math.max(1, size.rows));
1949
- session.shell?.resume();
1950
- }
1951
- return true;
1952
- }
1953
- /** End every session (host teardown, plugin dispose). */
1954
- dispose() {
1955
- for (const session of [...this.sessions.values()]) this.end(session, false);
1956
- this.sessions.clear();
1957
- }
1958
- /** Number of live sessions (introspection for tests and diagnostics). */
1959
- size() {
1960
- return this.sessions.size;
1961
- }
1962
- /** Wire one socket's frames and lifecycle onto a session. */
1963
- bind(ws, session) {
1964
- session.sockets.add(ws);
1965
- ws.on("message", (data) => {
1966
- let frame;
1967
- try {
1968
- frame = JSON.parse(String(data));
1969
- } catch {
1970
- return;
1971
- }
1972
- if (frame.type === "input") session.shell?.send(frame.data ?? "");
1973
- else if (frame.type === "resize") session.shell?.resize(Math.max(2, frame.cols ?? 80), Math.max(1, frame.rows ?? 24));
1974
- else if (frame.type === "auth_response") {
1975
- const finish = session.pendingAuthFinish;
1976
- session.pendingAuthFinish = void 0;
1977
- try {
1978
- finish?.(frame.responses ?? []);
1979
- } catch {}
1980
- } else if (frame.type === "close") this.end(session, true);
1981
- else if (frame.type === "detach") this.detach(ws);
1982
- });
1983
- ws.on("close", () => {
1984
- this.detach(ws);
1985
- });
1986
- ws.on("error", () => {
1987
- this.detach(ws);
1988
- });
1989
- }
1990
- /** Remove a socket from its session, keeping the shell alive. */
1991
- detach(ws) {
1992
- for (const session of this.sessions.values()) {
1993
- if (!session.sockets.delete(ws)) continue;
1994
- if (session.sockets.size === 0) this.scheduleReap(session, session.exited ? this.exitGraceMs : this.idleMs);
1995
- return;
1996
- }
1997
- }
1998
- /** End the session a socket is attached to (explicit close from the view). */
1999
- end(session, notify) {
2000
- this.clearReap(session);
2001
- if (this.sessions.delete(session.id) && notify) {
2002
- if (session.pendingAuthFinish !== void 0) {
2003
- const finish = session.pendingAuthFinish;
2004
- session.pendingAuthFinish = void 0;
2005
- try {
2006
- finish([]);
2007
- } catch {}
2008
- }
2009
- }
2010
- try {
2011
- session.shell?.close();
2012
- } catch {}
2013
- }
2014
- /** Mark a session exited and keep it briefly so a reattaching view sees it. */
2015
- finish(session, code, error) {
2016
- if (session.exited) return;
2017
- session.exited = true;
2018
- session.exit = {
2019
- code,
2020
- error
2021
- };
2022
- this.send(session, {
2023
- type: "exit",
2024
- code,
2025
- error
2026
- });
2027
- for (const ws of [...session.sockets]) {
2028
- session.sockets.delete(ws);
2029
- try {
2030
- ws.close(1e3);
2031
- } catch {}
2032
- }
2033
- this.scheduleReap(session, this.exitGraceMs);
2034
- }
2035
- /** Append output to the replay buffer, trimmed to the byte cap. */
2036
- pushOutput(session, data) {
2037
- session.buffer.push(data);
2038
- session.bufferBytes += Buffer.byteLength(data);
2039
- while (session.bufferBytes > this.maxBufferBytes && session.buffer.length > 1) {
2040
- const dropped = session.buffer.shift();
2041
- session.bufferBytes -= Buffer.byteLength(dropped ?? "");
2042
- }
2043
- this.send(session, {
2044
- type: "output",
2045
- data
2046
- });
2047
- }
2048
- /** Broadcast one frame to every attached socket, honoring backpressure. */
2049
- send(session, frame) {
2050
- for (const ws of session.sockets) this.sendTo(session, ws, frame);
2051
- this.applyBackpressure(session);
2052
- }
2053
- sendTo(session, ws, frame) {
2054
- if (ws.readyState !== WebSocket.OPEN) return;
2055
- try {
2056
- ws.send(JSON.stringify(frame));
2057
- } catch {}
2058
- }
2059
- /** Pause while any attached socket is backed up; resume once all drained. */
2060
- applyBackpressure(session) {
2061
- const shell = session.shell;
2062
- if (shell === void 0) return;
2063
- let high = false;
2064
- let low = true;
2065
- for (const ws of session.sockets) {
2066
- if (ws.bufferedAmount > BACKPRESSURE_HIGH_WATER) high = true;
2067
- if (ws.bufferedAmount > BACKPRESSURE_LOW_WATER) low = false;
2068
- }
2069
- if (high) shell.pause();
2070
- else if (low) shell.resume();
2071
- }
2072
- /** Answer a keyboard-interactive challenge through whoever is attached. */
2073
- keyboardInteractive(session) {
2074
- return (name, instructions, _lang, prompts, finish) => {
2075
- session.pendingAuthFinish = finish;
2076
- this.send(session, {
2077
- type: "auth_prompt",
2078
- name,
2079
- instructions,
2080
- prompts: prompts.map((p) => ({
2081
- prompt: p.prompt,
2082
- echo: p.echo
2083
- }))
2084
- });
2085
- };
2086
- }
2087
- scheduleReap(session, delayMs) {
2088
- this.clearReap(session);
2089
- const timer = setTimeout(() => {
2090
- session.reapTimer = void 0;
2091
- if (session.sockets.size > 0) return;
2092
- this.end(session, false);
2093
- }, delayMs);
2094
- timer.unref?.();
2095
- session.reapTimer = timer;
2096
- }
2097
- clearReap(session) {
2098
- if (session.reapTimer !== void 0) {
2099
- clearTimeout(session.reapTimer);
2100
- session.reapTimer = void 0;
2101
- }
2102
- }
2103
- };
2104
- //#endregion
2105
- //#region src/http.ts
2106
- /** Default body cap for readJsonBody: 64 KiB. */
2107
- const DEFAULT_JSON_BODY_MAX_BYTES = 64 * 1024;
2108
- /** Family-default JSON response headers; callers may append or override. */
2109
- const JSON_HEADERS = {
2110
- "content-type": "application/json; charset=utf-8",
2111
- "referrer-policy": "no-referrer"
2112
- };
2113
- /**
2114
- * Lenient bounded body reader: parse a request body as JSON, or null on an
2115
- * empty body, invalid JSON, or a body past maxBytes (default 64 KiB).
2116
- * Overflow destroys the request instead of draining the remainder (no drain
2117
- * call, matching the current repo-wide behavior); callers must not keep
2118
- * reading the request afterwards. With objectOnly, non-JSON-object payloads
2119
- * also yield null.
2120
- */
2121
- async function readJsonBody(req, opts = {}) {
2122
- const maxBytes = opts.maxBytes ?? DEFAULT_JSON_BODY_MAX_BYTES;
2123
- const chunks = [];
2124
- let size = 0;
2125
- for await (const chunk of req) {
2126
- const buffer = chunk;
2127
- size += buffer.length;
2128
- if (size > maxBytes) {
2129
- req.destroy();
2130
- return null;
2131
- }
2132
- chunks.push(buffer);
2133
- }
2134
- const text = Buffer.concat(chunks).toString("utf8");
2135
- if (text === "") return null;
2136
- try {
2137
- const parsed = JSON.parse(text);
2138
- if (opts.objectOnly && !isJsonObject(parsed)) return null;
2139
- return parsed;
2140
- } catch {
2141
- return null;
2142
- }
2143
- }
2144
- /** Whether a value is a JSON object: typeof object, not null, not an array. */
2145
- function isJsonObject(value) {
2146
- return typeof value === "object" && value !== null && !Array.isArray(value);
2147
- }
2148
- /**
2149
- * Write one JSON response. Default headers are the family defaults
2150
- * (content-type and referrer-policy); caller headers are appended or
2151
- * override them.
2152
- */
2153
- function writeJson(res, status, body, headers = {}) {
2154
- const payload = JSON.stringify(body);
2155
- res.writeHead(status, {
2156
- ...JSON_HEADERS,
2157
- ...headers
2158
- });
2159
- res.end(payload);
2160
- }
2161
- //#endregion
2162
- //#region src/loopback.ts
2163
- /** IPv4 127/8 predicate (four decimal octets, first == 127). */
2164
- function isIPv4Loopback(v4) {
2165
- const parts = v4.split(".");
2166
- return parts.length === 4 && parts[0] === "127" && parts.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255);
2167
- }
2168
- /** Whether a socket remote address names the loopback range (127/8, ::1, IPv4-mapped). */
2169
- function isLoopbackAddress(address) {
2170
- if (address === void 0) return false;
2171
- const normalized = address.toLowerCase();
2172
- if (normalized === "::1") return true;
2173
- if (normalized.startsWith("::ffff:")) return isIPv4Loopback(normalized.slice(7));
2174
- return isIPv4Loopback(normalized);
2175
- }
2176
- /** Whether a normalized URL hostname names the loopback authority (localhost, [::1], 127/8). */
2177
- function isLoopbackHostname(hostname) {
2178
- if (hostname === "localhost" || hostname === "[::1]") return true;
2179
- return isIPv4Loopback(hostname);
2180
- }
2181
- /**
2182
- * Whether a reverse proxy stood between the client and this host: the request
2183
- * carries CF-Connecting-IP or X-Forwarded-For. Either header is stamped by a
2184
- * hop that forwards traffic, so the request did not originate on this machine.
2185
- * @param request - node HTTP request.
2186
- * @returns true when a forwarding header is present.
2187
- */
2188
- function isProxiedRequest(request) {
2189
- return request.headers["cf-connecting-ip"] !== void 0 || request.headers["x-forwarded-for"] !== void 0;
2190
- }
2191
- /**
2192
- * Request-level trust fence: a loopback socket address AND a loopback Host
2193
- * header, plus browser same-origin markers. The socket address is
2194
- * authoritative for a direct connection; a request that carries a forwarding
2195
- * header is refused outright, because a proxy in front of the host makes both
2196
- * the socket address and the Host header describe the proxy rather than the
2197
- * client. X-Forwarded-For is therefore never evidence *for* loopback.
2198
- */
2199
- function isLoopbackRequest(request) {
2200
- if (!isLoopbackAddress(request.socket.remoteAddress)) return false;
2201
- if (isProxiedRequest(request)) return false;
2202
- const host = request.headers.host;
2203
- if (typeof host !== "string") return false;
2204
- let hostUrl;
2205
- try {
2206
- hostUrl = new URL("http://" + host);
2207
- } catch {
2208
- return false;
2209
- }
2210
- if (!isLoopbackHostname(hostUrl.hostname)) return false;
2211
- if (request.headers["sec-fetch-site"] === "cross-site") return false;
2212
- const origin = request.headers.origin;
2213
- if (origin === void 0) return true;
2214
- try {
2215
- return new URL(origin).host === hostUrl.host;
2216
- } catch {
2217
- return false;
2218
- }
2219
- }
2220
- //#endregion
2221
- //#region src/protocol.ts
2222
- const SSH_API = {
2223
- hosts: "/api/dsh-ssh/hosts",
2224
- importSshConfig: "/api/dsh-ssh/hosts/import-ssh-config",
2225
- test: "/api/dsh-ssh/test",
2226
- exec: "/api/dsh-ssh/exec",
2227
- cluster: "/api/dsh-ssh/cluster",
2228
- upload: "/api/dsh-ssh/upload",
2229
- download: "/api/dsh-ssh/download",
2230
- ls: "/api/dsh-ssh/ls",
2231
- tunnel: "/api/dsh-ssh/tunnel",
2232
- terminal: "/api/dsh-ssh/terminal"
2233
- };
2234
- //#endregion
2235
- //#region src/routes.ts
2236
- /**
2237
- * The /api/dsh-ssh route family: host CRUD, exec, cluster, SFTP transfer
2238
- * (NDJSON progress stream for uploads, binary stream for downloads), remote
2239
- * listing, tunnels, and the WebSocket PTY terminal upgrade. Every route
2240
- * carries a loopback-only trust fence (plus browser same-origin markers) —
2241
- * these endpoints execute commands on remote servers, so LAN-exposed dsh web
2242
- * deployments must not serve them.
2243
- */
2244
- /** Cap on declared upload bodies (staged to disk before SFTP). */
2245
- const MAX_UPLOAD_BYTES = 4 * 1024 * 1024 * 1024;
2246
- /**
2247
- * One noServer WebSocket server for terminal upgrades: the browser half uses
2248
- * a standards-compliant WebSocket, so the host must speak real RFC 6455
2249
- * frames (the webserver hands us the raw upgraded socket).
2250
- */
2251
- const terminalWss = new WebSocketServer({ noServer: true });
2252
- /** URL query helper (first value, decoded). */
2253
- function queryParam(url, name) {
2254
- const value = url.searchParams.get(name);
2255
- return value === null ? void 0 : value;
2256
- }
2257
- /**
2258
- * Build every /api/dsh-ssh route (exact paths) plus the terminal upgrade.
2259
- * @param deps - store, engine, staging dir.
2260
- * @returns routes and the upgrade route.
2261
- */
2262
- function makeRoutes(deps) {
2263
- const { store, engine } = deps;
2264
- const staging = deps.stagingDir ?? join(tmpdir(), "dsh-ssh-uploads");
2265
- const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES;
2266
- mkdirSync(staging, {
2267
- recursive: true,
2268
- mode: 448
2269
- });
2270
- /** Guard helper: fence + method check. */
2271
- const guard = (req, res, method) => {
2272
- if (!isLoopbackRequest(req)) {
2273
- writeJson(res, 403, { error: "forbidden: loopback-only" });
2274
- return false;
2275
- }
2276
- if (req.method !== method) {
2277
- writeJson(res, 405, { error: `method not allowed: ${req.method}` });
2278
- return false;
2279
- }
2280
- return true;
2281
- };
2282
- const routes = [
2283
- {
2284
- kind: "exact",
2285
- path: SSH_API.hosts,
2286
- handler: async (req, res) => {
2287
- const method = req.method ?? "GET";
2288
- if (!isLoopbackRequest(req)) {
2289
- writeJson(res, 403, { error: "forbidden: loopback-only" });
2290
- return;
2291
- }
2292
- const url = new URL(req.url ?? "/", "http://localhost");
2293
- if (method === "GET") {
2294
- writeJson(res, 200, { hosts: engine.list(queryParam(url, "query")) });
2295
- return;
2296
- }
2297
- if (method === "POST") {
2298
- const body = await readJsonBody(req);
2299
- if (body === null) {
2300
- writeJson(res, 400, { error: "invalid JSON body" });
2301
- return;
2302
- }
2303
- try {
2304
- const entry = store.create(body);
2305
- writeJson(res, 201, { host: store.summarize(entry) });
2306
- } catch (error) {
2307
- writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
2308
- }
2309
- return;
2310
- }
2311
- if (method !== "PATCH" && method !== "DELETE") {
2312
- writeJson(res, 405, { error: `method not allowed: ${method}` });
2313
- return;
2314
- }
2315
- const alias = queryParam(url, "alias");
2316
- if (alias === void 0 || alias === "") {
2317
- writeJson(res, 400, { error: "alias query parameter is required" });
2318
- return;
2319
- }
2320
- if (method === "PATCH") {
2321
- const body = await readJsonBody(req);
2322
- if (body === null) {
2323
- writeJson(res, 400, { error: "invalid JSON body" });
2324
- return;
2325
- }
2326
- try {
2327
- const entry = store.update(alias, body);
2328
- const patch = body;
2329
- if ([
2330
- "host",
2331
- "port",
2332
- "user",
2333
- "auth",
2334
- "proxyJump",
2335
- "proxyCommand",
2336
- "forwardAgent"
2337
- ].some((key) => patch[key] !== void 0)) engine.dropAlias(alias);
2338
- writeJson(res, 200, { host: store.summarize(entry) });
2339
- } catch (error) {
2340
- writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
2341
- }
2342
- return;
2343
- }
2344
- if (method === "DELETE") {
2345
- try {
2346
- engine.dropAlias(alias);
2347
- store.delete(alias);
2348
- writeJson(res, 200, { ok: true });
2349
- } catch (error) {
2350
- writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
2351
- }
2352
- return;
2353
- }
2354
- writeJson(res, 405, { error: `method not allowed: ${method}` });
2355
- }
2356
- },
2357
- {
2358
- kind: "exact",
2359
- path: SSH_API.importSshConfig,
2360
- handler: async (req, res) => {
2361
- if (!guard(req, res, "POST")) return;
2362
- try {
2363
- writeJson(res, 200, { result: store.importFromSshConfig() });
2364
- } catch (error) {
2365
- writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) });
2366
- }
2367
- }
2368
- },
2369
- {
2370
- kind: "exact",
2371
- path: SSH_API.test,
2372
- handler: async (req, res) => {
2373
- if (!guard(req, res, "POST")) return;
2374
- const body = await readJsonBody(req);
2375
- const alias = typeof body?.alias === "string" ? body.alias : "";
2376
- if (alias === "") {
2377
- writeJson(res, 400, { error: "alias is required" });
2378
- return;
2379
- }
2380
- try {
2381
- writeJson(res, 200, { result: await engine.test(alias) });
2382
- } catch (error) {
2383
- writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) });
2384
- }
2385
- }
2386
- },
2387
- {
2388
- kind: "exact",
2389
- path: SSH_API.exec,
2390
- handler: async (req, res) => {
2391
- if (!guard(req, res, "POST")) return;
2392
- const body = await readJsonBody(req);
2393
- const alias = typeof body?.alias === "string" ? body.alias : "";
2394
- const command = typeof body?.command === "string" ? body.command : "";
2395
- if (alias === "" || command === "") {
2396
- writeJson(res, 400, { error: "alias and command are required" });
2397
- return;
2398
- }
2399
- const timeoutMs = typeof body?.timeoutMs === "number" ? body.timeoutMs : void 0;
2400
- try {
2401
- writeJson(res, 200, { result: await engine.exec(alias, command, timeoutMs) });
2402
- } catch (error) {
2403
- writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) });
2404
- }
2405
- }
2406
- },
2407
- {
2408
- kind: "exact",
2409
- path: SSH_API.cluster,
2410
- handler: async (req, res) => {
2411
- if (!guard(req, res, "POST")) return;
2412
- const body = await readJsonBody(req);
2413
- const command = typeof body?.command === "string" ? body.command : "";
2414
- if (command === "") {
2415
- writeJson(res, 400, { error: "command is required" });
2416
- return;
2417
- }
2418
- const aliases = Array.isArray(body?.aliases) ? body.aliases.filter((x) => typeof x === "string") : void 0;
2419
- const tags = Array.isArray(body?.tags) ? body.tags.filter((x) => typeof x === "string") : void 0;
2420
- const environment = typeof body?.environment === "string" ? body.environment : void 0;
2421
- const timeoutMs = typeof body?.timeoutMs === "number" ? body.timeoutMs : void 0;
2422
- const maxWorkers = typeof body?.maxWorkers === "number" ? body.maxWorkers : void 0;
2423
- const hasAliases = aliases?.some((alias) => alias.trim() !== "") === true;
2424
- const hasEnvironment = typeof environment === "string" && environment.trim() !== "";
2425
- const hasTags = tags?.some((tag) => tag.trim() !== "") === true;
2426
- if (!hasAliases && !hasEnvironment && !hasTags) {
2427
- writeJson(res, 400, { error: "ssh_cluster requires aliases, environment, or tags to limit the target set" });
2428
- return;
2429
- }
2430
- try {
2431
- writeJson(res, 200, { results: await engine.cluster({
2432
- command,
2433
- aliases,
2434
- environment,
2435
- tags,
2436
- timeoutMs,
2437
- maxWorkers
2438
- }) });
2439
- } catch (error) {
2440
- writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) });
2441
- }
2442
- }
2443
- },
2444
- {
2445
- kind: "exact",
2446
- path: SSH_API.ls,
2447
- handler: async (req, res) => {
2448
- if (!guard(req, res, "GET")) return;
2449
- const url = new URL(req.url ?? "/", "http://localhost");
2450
- const alias = queryParam(url, "alias");
2451
- const path = queryParam(url, "path") ?? "/";
2452
- if (alias === void 0 || alias === "") {
2453
- writeJson(res, 400, { error: "alias query parameter is required" });
2454
- return;
2455
- }
2456
- try {
2457
- writeJson(res, 200, { entries: await engine.ls(alias, path) });
2458
- } catch (error) {
2459
- writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
2460
- }
2461
- }
2462
- },
2463
- {
2464
- kind: "exact",
2465
- path: SSH_API.tunnel,
2466
- handler: async (req, res) => {
2467
- if (!guard(req, res, "POST")) return;
2468
- const body = await readJsonBody(req);
2469
- const action = typeof body?.action === "string" ? body.action : "";
2470
- if (action === "list") {
2471
- writeJson(res, 200, { tunnels: engine.listTunnels() });
2472
- return;
2473
- }
2474
- if (action === "start") {
2475
- const alias = typeof body?.alias === "string" ? body.alias : "";
2476
- const remotePort = typeof body?.remotePort === "number" ? body.remotePort : void 0;
2477
- if (alias === "" || remotePort === void 0) {
2478
- writeJson(res, 400, { error: "alias and remotePort are required" });
2479
- return;
2480
- }
2481
- try {
2482
- writeJson(res, 200, { tunnel: await engine.startTunnel(alias, {
2483
- remotePort,
2484
- remoteHost: typeof body?.remoteHost === "string" && body.remoteHost !== "" ? body.remoteHost : void 0,
2485
- localPort: typeof body?.localPort === "number" ? body.localPort : void 0
2486
- }) });
2487
- } catch (error) {
2488
- writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) });
2489
- }
2490
- return;
2491
- }
2492
- if (action === "stop") {
2493
- const id = typeof body?.tunnelId === "string" ? body.tunnelId : "";
2494
- if (id === "") {
2495
- writeJson(res, 400, { error: "tunnelId is required" });
2496
- return;
2497
- }
2498
- writeJson(res, 200, { ok: engine.stopTunnel(id) });
2499
- return;
2500
- }
2501
- if (action === "stop-all") {
2502
- const alias = typeof body?.alias === "string" ? body.alias : void 0;
2503
- writeJson(res, 200, { stopped: engine.stopAllTunnels(alias === "" ? void 0 : alias) });
2504
- return;
2505
- }
2506
- writeJson(res, 400, { error: `unknown action '${action}'` });
2507
- }
2508
- },
2509
- {
2510
- kind: "exact",
2511
- path: SSH_API.upload,
2512
- handler: async (req, res) => {
2513
- if (!guard(req, res, "POST")) return;
2514
- const url = new URL(req.url ?? "/", "http://localhost");
2515
- const alias = queryParam(url, "alias");
2516
- const remotePath = queryParam(url, "remotePath");
2517
- if (alias === void 0 || remotePath === void 0) {
2518
- writeJson(res, 400, { error: "alias and remotePath query parameters are required" });
2519
- return;
2520
- }
2521
- const declared = Number(req.headers["content-length"]);
2522
- if (Number.isFinite(declared) && declared > maxUploadBytes) {
2523
- writeJson(res, 413, { error: "upload body too large" });
2524
- return;
2525
- }
2526
- res.writeHead(200, {
2527
- "content-type": "application/x-ndjson; charset=utf-8",
2528
- "cache-control": "no-cache",
2529
- "referrer-policy": "no-referrer"
2530
- });
2531
- const emit = (line) => {
2532
- try {
2533
- res.write(JSON.stringify(line) + "\n");
2534
- } catch {}
2535
- };
2536
- const tmp = join(staging, `upload-${randomBytes(6).toString("hex")}`);
2537
- const sink = createWriteStream(tmp, { mode: 384 });
2538
- let settled = false;
2539
- const fail = (error) => {
2540
- if (settled) return;
2541
- settled = true;
2542
- emit({
2543
- type: "result",
2544
- ok: false,
2545
- error: error instanceof Error ? error.message : String(error)
2546
- });
2547
- const cleanup = () => {
2548
- unlink(tmp).catch(() => void 0).finally(() => {
2549
- try {
2550
- res.end();
2551
- } catch {}
2552
- });
2553
- };
2554
- if (sink.destroyed) cleanup();
2555
- else {
2556
- sink.once("close", cleanup);
2557
- try {
2558
- sink.destroy();
2559
- } catch {
2560
- cleanup();
2561
- }
2562
- }
2563
- };
2564
- const done = () => {
2565
- if (settled) return;
2566
- settled = true;
2567
- try {
2568
- res.end();
2569
- } catch {}
2570
- };
2571
- sink.on("error", (error) => fail(error));
2572
- req.on("error", (error) => fail(error));
2573
- req.on("aborted", () => fail("upload aborted by the client"));
2574
- res.on("error", () => fail("response stream closed"));
2575
- res.on("close", () => {
2576
- if (!res.writableEnded) fail("connection closed");
2577
- });
2578
- let received = 0;
2579
- let capped = false;
2580
- req.on("data", (chunk) => {
2581
- received += chunk.byteLength;
2582
- if (received > maxUploadBytes && !capped) {
2583
- capped = true;
2584
- fail("upload body too large");
2585
- res.on("finish", () => {
2586
- try {
2587
- req.destroy();
2588
- } catch {}
2589
- });
2590
- req.resume();
2591
- }
2592
- });
2593
- req.pipe(sink);
2594
- sink.on("finish", async () => {
2595
- if (settled) return;
2596
- emit({
2597
- type: "progress",
2598
- progress: {
2599
- phase: "connecting",
2600
- file: remotePath,
2601
- transferred: 0,
2602
- total: 0,
2603
- percent: 0
2604
- }
2605
- });
2606
- try {
2607
- const outcome = await engine.upload(alias, tmp, remotePath, false, (progress) => emit({
2608
- type: "progress",
2609
- progress
2610
- }));
2611
- emit({
2612
- type: "result",
2613
- ok: true,
2614
- transferredBytes: outcome.bytes
2615
- });
2616
- } catch (error) {
2617
- emit({
2618
- type: "result",
2619
- ok: false,
2620
- error: error instanceof Error ? error.message : String(error)
2621
- });
2622
- } finally {
2623
- await unlink(tmp).catch(() => void 0);
2624
- done();
2625
- }
2626
- });
2627
- }
2628
- },
2629
- {
2630
- kind: "exact",
2631
- path: SSH_API.download,
2632
- handler: async (req, res) => {
2633
- if (!guard(req, res, "GET")) return;
2634
- const url = new URL(req.url ?? "/", "http://localhost");
2635
- const alias = queryParam(url, "alias");
2636
- const remotePath = queryParam(url, "remotePath");
2637
- if (alias === void 0 || remotePath === void 0) {
2638
- writeJson(res, 400, { error: "alias and remotePath query parameters are required" });
2639
- return;
2640
- }
2641
- const tmp = join(staging, `download-${randomBytes(6).toString("hex")}`);
2642
- try {
2643
- closeSync(openSync(tmp, "w", 384));
2644
- const outcome = await engine.download(alias, remotePath, tmp);
2645
- res.writeHead(200, {
2646
- "content-type": "application/octet-stream",
2647
- "content-length": String(outcome.bytes),
2648
- "content-disposition": `attachment; filename="${basename(remotePath).replace(/"/g, "")}"`,
2649
- "referrer-policy": "no-referrer"
2650
- });
2651
- await new Promise((resolve, reject) => {
2652
- const source = createReadStream(tmp);
2653
- source.on("error", reject);
2654
- res.on("error", reject);
2655
- source.pipe(res);
2656
- source.on("end", resolve);
2657
- });
2658
- } catch (error) {
2659
- if (!res.headersSent) writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
2660
- else res.destroy();
2661
- } finally {
2662
- await unlink(tmp).catch(() => void 0);
2663
- }
2664
- }
2665
- }
2666
- ];
2667
- const terminalSessions = new TerminalSessionRegistry({ openShell: (alias, size, onKeyboardInteractive) => engine.openShell(alias, size, onKeyboardInteractive) });
2668
- return {
2669
- routes,
2670
- upgrade: {
2671
- path: SSH_API.terminal,
2672
- handler: (req, socket, head) => {
2673
- if (!isLoopbackRequest(req)) {
2674
- socket.write("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n");
2675
- socket.destroy();
2676
- return;
2677
- }
2678
- const url = new URL(req.url ?? "/", "http://localhost");
2679
- const alias = queryParam(url, "alias");
2680
- const sessionId = queryParam(url, "session");
2681
- if (alias === void 0 && sessionId === void 0) {
2682
- socket.write("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n");
2683
- socket.destroy();
2684
- return;
2685
- }
2686
- const cols = Number.parseInt(queryParam(url, "cols") ?? "80", 10);
2687
- const rows = Number.parseInt(queryParam(url, "rows") ?? "24", 10);
2688
- const size = {
2689
- cols: Number.isFinite(cols) ? cols : 80,
2690
- rows: Number.isFinite(rows) ? rows : 24
2691
- };
2692
- terminalWss.handleUpgrade(req, socket, head, (ws) => {
2693
- if (sessionId !== void 0) {
2694
- if (terminalSessions.attach(ws, sessionId, size)) return;
2695
- const expired = {
2696
- type: "exit",
2697
- code: null,
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
- }
2711
- },
2712
- terminalSessions
2713
- };
2714
- }
2715
- //#endregion
2716
- //#region src/tools.ts
2717
- /**
2718
- * Agent tools: the DSH-native counterpart of ssh-skill's CLI. Every tool
2719
- * talks to the same engine the web UI uses, so a host configured in the GUI
2720
- * is immediately operable by any agent, and vice versa.
2721
- */
2722
- /** One text content block (the only render shape these tools emit). */
2723
- function text(value) {
2724
- return [{
2725
- type: "text",
2726
- text: value
2727
- }];
2728
- }
2729
- /** Project one summary onto the agent-facing row shape. */
2730
- function toAgentHostRow(host) {
2731
- const { proxyCommand, ...rest } = host;
2732
- return {
2733
- ...rest,
2734
- proxyCommandConfigured: proxyCommand !== void 0
2735
- };
2736
- }
2737
- /** Host table render shared by list surfaces. */
2738
- function renderHosts(hosts) {
2739
- if (hosts.length === 0) return "no hosts configured";
2740
- return [
2741
- "alias | host | port | user | auth | proxy | forward | environment | tags | description",
2742
- "--- | --- | --- | --- | --- | --- | --- | --- | --- | ---",
2743
- ...hosts.map((host) => [
2744
- host.alias,
2745
- host.host,
2746
- String(host.port),
2747
- host.user,
2748
- host.auth,
2749
- host.proxyJump.length > 0 ? "jump:" + host.proxyJump.join(",") : host.proxyCommandConfigured ? "proxy-command" : "-",
2750
- host.forwardAgent ? "yes" : "-",
2751
- host.environment ?? "-",
2752
- host.tags.length > 0 ? host.tags.join(",") : "-",
2753
- host.description ?? ""
2754
- ].join(" | "))
2755
- ].join("\n");
2756
- }
2757
- /** Render one exec result (mirrors the bash-tool exit-code convention). */
2758
- function renderExec(result) {
2759
- const parts = [result.timedOut ? "[timed out]" : `[exit code: ${result.exitCode ?? "null"}]`];
2760
- if (result.stdout !== "") parts.push("stdout:\n" + result.stdout);
2761
- if (result.stderr !== "") parts.push("stderr:\n" + result.stderr);
2762
- if (result.error !== void 0) parts.push("error: " + result.error);
2763
- parts.push(`duration: ${result.durationMs} ms`);
2764
- return parts.join("\n");
2765
- }
2766
- /** Render cluster outcomes compactly. */
2767
- function renderCluster(results) {
2768
- if (results.length === 0) return "no hosts matched";
2769
- return results.map((result) => {
2770
- const status = result.ok ? "ok" : result.timedOut === true ? "timed out" : "failed";
2771
- const tail = result.error !== void 0 ? " (" + result.error + ")" : "";
2772
- return `${result.alias}: ${status} [exit code: ${result.exitCode ?? "null"}]${tail}`;
2773
- }).join("\n");
2774
- }
2775
- /** One tunnel line. */
2776
- function renderTunnel(tunnel) {
2777
- return `${tunnel.id} ${tunnel.alias} 127.0.0.1:${tunnel.localPort} -> ${tunnel.remoteHost}:${tunnel.remotePort} [${tunnel.state}]`;
2778
- }
2779
- /** The host-list tool. */
2780
- function sshListTool(engine) {
2781
- return defineTool({
2782
- name: "ssh_list",
2783
- description: "List configured SSH hosts (alias, host, user, auth, agent forwarding, environment, tags, description). Use ssh_exec etc. with the alias.",
2784
- parameters: { query: {
2785
- type: "string",
2786
- description: "Optional fuzzy match against alias, description, host, and tags."
2787
- } },
2788
- output: {
2789
- schema: {
2790
- type: "object",
2791
- additionalProperties: false,
2792
- properties: { hosts: {
2793
- type: "array",
2794
- required: true,
2795
- items: {
2796
- type: "object",
2797
- additionalProperties: false,
2798
- properties: {
2799
- alias: {
2800
- type: "string",
2801
- required: true
2802
- },
2803
- host: {
2804
- type: "string",
2805
- required: true
2806
- },
2807
- port: {
2808
- type: "integer",
2809
- required: true
2810
- },
2811
- user: {
2812
- type: "string",
2813
- required: true
2814
- },
2815
- auth: {
2816
- type: "string",
2817
- enum: [
2818
- "key",
2819
- "password",
2820
- "agent"
2821
- ],
2822
- required: true
2823
- },
2824
- keyReady: {
2825
- type: "boolean",
2826
- required: true
2827
- },
2828
- proxyJump: {
2829
- type: "array",
2830
- items: { type: "string" },
2831
- required: true
2832
- },
2833
- proxyCommandConfigured: {
2834
- type: "boolean",
2835
- required: true
2836
- },
2837
- forwardAgent: {
2838
- type: "boolean",
2839
- required: true
2840
- },
2841
- description: { type: "string" },
2842
- environment: { type: "string" },
2843
- tags: {
2844
- type: "array",
2845
- items: { type: "string" },
2846
- required: true
2847
- },
2848
- location: { type: "string" },
2849
- createdAt: {
2850
- type: "integer",
2851
- required: true
2852
- },
2853
- updatedAt: {
2854
- type: "integer",
2855
- required: true
2856
- }
2857
- }
2858
- }
2859
- } }
2860
- },
2861
- render: (_args, value) => text(renderHosts(value.hosts ?? []))
2862
- },
2863
- isConcurrencySafe: () => true,
2864
- async execute(args) {
2865
- return { hosts: engine.list(args.query).map(toAgentHostRow) };
2866
- }
2867
- });
2868
- }
2869
- /** The command-execution tool. */
2870
- function sshExecTool(engine) {
2871
- return defineTool({
2872
- name: "ssh_exec",
2873
- description: "Execute a shell command on a REMOTE SSH host by alias; the command runs on the remote host, never on this machine. For commands on this machine, use the local bash tool. Prefer combining independent read-only queries into one command.",
2874
- parameters: {
2875
- alias: {
2876
- type: "string",
2877
- required: true,
2878
- description: "Host alias from ssh_list."
2879
- },
2880
- command: {
2881
- type: "string",
2882
- required: true,
2883
- description: "The shell command to run remotely."
2884
- },
2885
- timeoutMs: {
2886
- type: "integer",
2887
- description: "Remote command execution timeout in milliseconds (default 60000); it starts after the connection is ready. The connection and authentication ceiling is the dsh-ssh connectTimeoutMs setting, not this argument."
2888
- }
2889
- },
2890
- output: {
2891
- schema: {
2892
- type: "object",
2893
- additionalProperties: false,
2894
- properties: {
2895
- success: {
2896
- type: "boolean",
2897
- required: true
2898
- },
2899
- exitCode: {
2900
- oneOf: [{ type: "integer" }, { type: "null" }],
2901
- required: true
2902
- },
2903
- timedOut: {
2904
- type: "boolean",
2905
- required: true
2906
- },
2907
- stdout: {
2908
- type: "string",
2909
- required: true
2910
- },
2911
- stderr: {
2912
- type: "string",
2913
- required: true
2914
- },
2915
- durationMs: {
2916
- type: "integer",
2917
- required: true
2918
- },
2919
- error: { type: "string" }
2920
- }
2921
- },
2922
- render: (_args, value) => text(renderExec(value))
2923
- },
2924
- async execute(args, exec) {
2925
- try {
2926
- return await engine.exec(args.alias, args.command, args.timeoutMs, exec.signal);
2927
- } catch (error) {
2928
- return {
2929
- success: false,
2930
- exitCode: null,
2931
- timedOut: false,
2932
- stdout: "",
2933
- stderr: "",
2934
- durationMs: 0,
2935
- error: error instanceof Error ? error.message : String(error)
2936
- };
2937
- }
2938
- }
2939
- });
2940
- }
2941
- /** The upload tool. */
2942
- function sshUploadTool(engine) {
2943
- return defineTool({
2944
- name: "ssh_upload",
2945
- description: "Transfer a file FROM this machine (the dsh host) TO a remote SSH host. Use this only when the file must be copied to the remote host. Files that stay on this machine are handled with the local file tools (read / write / edit), not ssh_upload.",
2946
- parameters: {
2947
- alias: {
2948
- type: "string",
2949
- required: true,
2950
- description: "Host alias from ssh_list."
2951
- },
2952
- localPath: {
2953
- type: "string",
2954
- required: true,
2955
- description: "Absolute path of the source file on THIS machine (the dsh host) — not a path on the remote host."
2956
- },
2957
- remotePath: {
2958
- type: "string",
2959
- required: true,
2960
- description: "Absolute destination path on the remote SSH host (parent dirs are created)."
2961
- }
2962
- },
2963
- output: {
2964
- schema: {
2965
- type: "object",
2966
- additionalProperties: false,
2967
- properties: {
2968
- ok: {
2969
- type: "boolean",
2970
- required: true
2971
- },
2972
- transferredBytes: { type: "integer" },
2973
- files: { type: "integer" },
2974
- error: { type: "string" }
2975
- }
2976
- },
2977
- render: (_args, value) => text(value.ok ? `uploaded ${value.files ?? 1} file(s), ${value.transferredBytes ?? 0} bytes` : `upload failed: ${value.error ?? "unknown error"}`)
2978
- },
2979
- async execute(args) {
2980
- try {
2981
- const outcome = await engine.upload(args.alias, args.localPath, args.remotePath, false);
2982
- return {
2983
- ok: true,
2984
- transferredBytes: outcome.bytes,
2985
- files: outcome.files
2986
- };
2987
- } catch (error) {
2988
- return {
2989
- ok: false,
2990
- error: error instanceof Error ? error.message : String(error)
2991
- };
2992
- }
2993
- }
2994
- });
2995
- }
2996
- /** The download tool. */
2997
- function sshDownloadTool(engine) {
2998
- return defineTool({
2999
- name: "ssh_download",
3000
- description: "Copy a remote FILE from a configured SSH host to this machine (the dsh host). Use this only when the source is on the remote host; files already on this machine are read with the local file tools (read / write / edit), not ssh_download. Directory download is not supported — download files individually.",
3001
- parameters: {
3002
- alias: {
3003
- type: "string",
3004
- required: true,
3005
- description: "Host alias from ssh_list."
3006
- },
3007
- remotePath: {
3008
- type: "string",
3009
- required: true,
3010
- description: "Absolute path of the source file on the remote SSH host."
3011
- },
3012
- localPath: {
3013
- type: "string",
3014
- required: true,
3015
- description: "Absolute destination path on THIS machine (the dsh host)."
3016
- }
3017
- },
3018
- output: {
3019
- schema: {
3020
- type: "object",
3021
- additionalProperties: false,
3022
- properties: {
3023
- ok: {
3024
- type: "boolean",
3025
- required: true
3026
- },
3027
- bytes: { type: "integer" },
3028
- error: { type: "string" }
3029
- }
3030
- },
3031
- render: (_args, value) => text(value.ok ? `downloaded ${value.bytes ?? 0} bytes` : `download failed: ${value.error ?? "unknown error"}`)
3032
- },
3033
- async execute(args) {
3034
- try {
3035
- return {
3036
- ok: true,
3037
- bytes: (await engine.download(args.alias, args.remotePath, args.localPath)).bytes
3038
- };
3039
- } catch (error) {
3040
- return {
3041
- ok: false,
3042
- error: error instanceof Error ? error.message : String(error)
3043
- };
3044
- }
3045
- }
3046
- });
3047
- }
3048
- /** The tunnel tool. */
3049
- function sshTunnelTool(engine) {
3050
- return defineTool({
3051
- name: "ssh_tunnel",
3052
- description: "Manage local port-forward tunnels to a configured SSH host. Start a tunnel to reach a remote internal service (database, web UI, API) through 127.0.0.1 on this machine.",
3053
- parameters: {
3054
- action: {
3055
- type: "string",
3056
- required: true,
3057
- enum: [
3058
- "start",
3059
- "list",
3060
- "stop",
3061
- "stop-all"
3062
- ],
3063
- description: "start / list / stop / stop-all."
3064
- },
3065
- alias: {
3066
- type: "string",
3067
- description: "Host alias (required for start, optional for stop-all)."
3068
- },
3069
- remotePort: {
3070
- type: "integer",
3071
- description: "Port on the remote side (required for start)."
3072
- },
3073
- remoteHost: {
3074
- type: "string",
3075
- description: "Remote host to forward to (default 127.0.0.1 — the server itself)."
3076
- },
3077
- localPort: {
3078
- type: "integer",
3079
- description: "Local listening port (default: auto-assigned)."
3080
- },
3081
- tunnelId: {
3082
- type: "string",
3083
- description: "Tunnel id (required for stop)."
3084
- }
3085
- },
3086
- output: {
3087
- schema: {
3088
- type: "object",
3089
- additionalProperties: false,
3090
- properties: {
3091
- ok: {
3092
- type: "boolean",
3093
- required: true
3094
- },
3095
- tunnel: {
3096
- type: "object",
3097
- additionalProperties: false,
3098
- properties: {
3099
- id: {
3100
- type: "string",
3101
- required: true
3102
- },
3103
- alias: {
3104
- type: "string",
3105
- required: true
3106
- },
3107
- localPort: {
3108
- type: "integer",
3109
- required: true
3110
- },
3111
- remoteHost: {
3112
- type: "string",
3113
- required: true
3114
- },
3115
- remotePort: {
3116
- type: "integer",
3117
- required: true
3118
- },
3119
- state: {
3120
- type: "string",
3121
- enum: [
3122
- "forwarding",
3123
- "connecting",
3124
- "failed"
3125
- ],
3126
- required: true
3127
- },
3128
- error: { type: "string" },
3129
- startedAt: {
3130
- type: "integer",
3131
- required: true
3132
- }
3133
- }
3134
- },
3135
- tunnels: {
3136
- type: "array",
3137
- items: {
3138
- type: "object",
3139
- additionalProperties: false,
3140
- properties: {
3141
- id: {
3142
- type: "string",
3143
- required: true
3144
- },
3145
- alias: {
3146
- type: "string",
3147
- required: true
3148
- },
3149
- localPort: {
3150
- type: "integer",
3151
- required: true
3152
- },
3153
- remoteHost: {
3154
- type: "string",
3155
- required: true
3156
- },
3157
- remotePort: {
3158
- type: "integer",
3159
- required: true
3160
- },
3161
- state: {
3162
- type: "string",
3163
- enum: [
3164
- "forwarding",
3165
- "connecting",
3166
- "failed"
3167
- ],
3168
- required: true
3169
- },
3170
- error: { type: "string" },
3171
- startedAt: {
3172
- type: "integer",
3173
- required: true
3174
- }
3175
- }
3176
- }
3177
- },
3178
- stopped: { type: "integer" },
3179
- error: { type: "string" }
3180
- }
3181
- },
3182
- render: (_args, value) => {
3183
- if (value.error !== void 0) return text(`tunnel error: ${value.error}`);
3184
- if (value.tunnel !== void 0) {
3185
- if (value.tunnel.state === "failed") return text(`tunnel failed: ${value.tunnel.error ?? "unknown error"}`);
3186
- return text(`tunnel started: ${renderTunnel(value.tunnel)}`);
3187
- }
3188
- if (value.tunnels !== void 0) return text(value.tunnels.length === 0 ? "no active tunnels" : value.tunnels.map(renderTunnel).join("\n"));
3189
- return text(`stopped ${value.stopped ?? 0} tunnel(s)`);
3190
- }
3191
- },
3192
- async execute(args) {
3193
- if (args.action === "list") return {
3194
- ok: true,
3195
- tunnels: engine.listTunnels()
3196
- };
3197
- if (args.action === "start") {
3198
- if (args.alias === void 0 || args.remotePort === void 0) throw new Error("alias and remotePort are required for start");
3199
- try {
3200
- return {
3201
- ok: true,
3202
- tunnel: await engine.startTunnel(args.alias, {
3203
- remotePort: args.remotePort,
3204
- remoteHost: args.remoteHost,
3205
- localPort: args.localPort
3206
- })
3207
- };
3208
- } catch (error) {
3209
- return {
3210
- ok: false,
3211
- tunnel: {
3212
- id: "",
3213
- alias: args.alias,
3214
- localPort: 0,
3215
- remoteHost: args.remoteHost ?? "127.0.0.1",
3216
- remotePort: args.remotePort,
3217
- state: "failed",
3218
- error: error instanceof Error ? error.message : String(error),
3219
- startedAt: Date.now()
3220
- }
3221
- };
3222
- }
3223
- }
3224
- if (args.action === "stop") {
3225
- if (args.tunnelId === void 0) throw new Error("tunnelId is required for stop");
3226
- return engine.stopTunnel(args.tunnelId) ? {
3227
- ok: true,
3228
- stopped: 1
3229
- } : {
3230
- ok: false,
3231
- stopped: 0,
3232
- error: `tunnel '${args.tunnelId}' not found`
3233
- };
3234
- }
3235
- if (args.action === "stop-all") return {
3236
- ok: true,
3237
- stopped: engine.stopAllTunnels(args.alias)
3238
- };
3239
- throw new Error(`unknown action '${String(args.action)}'`);
3240
- }
3241
- });
3242
- }
3243
- /** The cluster tool. */
3244
- function sshClusterTool(engine) {
3245
- return defineTool({
3246
- name: "ssh_cluster",
3247
- description: "Run one command concurrently across selected SSH hosts; at least one aliases, environment, or tags filter is required.",
3248
- parameters: {
3249
- command: {
3250
- type: "string",
3251
- required: true,
3252
- description: "The shell command to run on every matched host."
3253
- },
3254
- aliases: {
3255
- type: "array",
3256
- items: { type: "string" },
3257
- description: "Optional alias filter; at least one of aliases, environment, or tags is required."
3258
- },
3259
- environment: {
3260
- type: "string",
3261
- description: "Optional environment filter; at least one selector is required."
3262
- },
3263
- tags: {
3264
- type: "array",
3265
- items: { type: "string" },
3266
- description: "Optional ALL-tags filter; at least one selector is required."
3267
- },
3268
- timeoutMs: {
3269
- type: "integer",
3270
- description: "Per-host command execution timeout in milliseconds (default 60000); it does not extend the connection and authentication ceiling (the dsh-ssh connectTimeoutMs setting)."
3271
- },
3272
- maxWorkers: {
3273
- type: "integer",
3274
- description: "Concurrency cap (default 8)."
3275
- }
3276
- },
3277
- output: {
3278
- schema: {
3279
- type: "object",
3280
- additionalProperties: false,
3281
- properties: { results: {
3282
- type: "array",
3283
- required: true,
3284
- items: {
3285
- type: "object",
3286
- additionalProperties: false,
3287
- properties: {
3288
- alias: {
3289
- type: "string",
3290
- required: true
3291
- },
3292
- ok: {
3293
- type: "boolean",
3294
- required: true
3295
- },
3296
- exitCode: { oneOf: [{ type: "integer" }, { type: "null" }] },
3297
- timedOut: { type: "boolean" },
3298
- stdout: { type: "string" },
3299
- stderr: { type: "string" },
3300
- durationMs: { type: "integer" },
3301
- error: { type: "string" }
3302
- }
3303
- }
3304
- } }
3305
- },
3306
- render: (_args, value) => text(renderCluster(value.results ?? []))
3307
- },
3308
- async execute(args, exec) {
3309
- if (!(Array.isArray(args.aliases) && args.aliases.some((alias) => typeof alias === "string" && alias.trim() !== "") || typeof args.environment === "string" && args.environment.trim() !== "" || Array.isArray(args.tags) && args.tags.some((tag) => typeof tag === "string" && tag.trim() !== ""))) throw new Error("ssh_cluster requires aliases, environment, or tags to limit the target set");
3310
- return { results: await engine.cluster({
3311
- ...args,
3312
- signal: exec.signal
3313
- }) };
3314
- }
3315
- });
3316
- }
3317
- //#endregion
3318
- //#region src/mount-once.ts
3319
- /**
3320
- * Host single-instance guard shared by the plugin family. The family bundle
3321
- * (dsh-web-all / dsh-skins) namespaces every child row id (web-ui-*), so
3322
- * the loader accepts a standalone install of the same package side by side;
3323
- * without this guard the second instance would still re-register the same
3324
- * webserver routes, tools, settings namespaces, and system-prompt sections
3325
- * and fail the boot. mountOnce makes a mount of an already-mounted package a
3326
- * no-op for as long as the first instance lives (the browser half is already
3327
- * deduped by package name in the client module host).
3328
- *
3329
- * A no-op is only safe while the holder is ALIVE. The holder can be disposed
3330
- * long after the refused mount ran its course: the Host reloads a profile by
3331
- * creating the new loader entries before the old ones are torn down (a
3332
- * plugin-manager enable/disable/install write, a settings-driven row reload,
3333
- * HMR), so the new aggregate shell entry mounts its family plugin while the
3334
- * previous entry still owns the name. Dropping that refused mount lost the
3335
- * plugin for good - the previous entry then disposed its own mount, releasing
3336
- * the name with nobody left to take it, and the family row stayed listed as
3337
- * active while its host routes 404ed (the task-board panel showed
3338
- * "board.hostError.notMounted", no degraded record appeared, and only a Host
3339
- * restart recovered it).
3340
- *
3341
- * The refused mount is therefore QUEUED, not dropped, and replayed the moment
3342
- * the holder releases the name - if the waiting fiber is still alive then. The
3343
- * single-instance guarantee is unchanged: exactly one mount is live per
3344
- * package name, and the replay re-enters the guard so a later mount still
3345
- * dedupes against it.
3346
- *
3347
- * The registry rides a global symbol so two module instances of the same
3348
- * package (npm copy vs repository link) still share one verdict. That symbol
3349
- * is a CROSS-REPOSITORY contract, not this file's private state: the four
3350
- * satellite packages (dsh-skins / dsh-pet / dsh-presets /
3351
- * dsh-community-plugins) are separate repositories carrying their own copy of
3352
- * this guard, rebuilt on their own schedule, so the value under `MOUNTED`
3353
- * must keep the shape every published copy reads (a `Set` of package names
3354
- * with `has`/`add`/`delete`). The wait queues this guard added therefore live
3355
- * under their own additive key, and the registry reads back a `Set` even when
3356
- * some other build left a different value there. Changing `MOUNTED`'s shape
3357
- * in place broke that contract once: a satellite's legacy copy created a
3358
- * `Set`, the family's new copy read it as a `Map`, and every family row
3359
- * mounted after it failed with "claims.get is not a function".
3360
- *
3361
- * cordis `ctx.effect` runs its callback immediately and treats the callback's
3362
- * return value as the fiber disposer, so the unmarker is returned, not run.
3363
- */
3364
- /** Published cross-repository contract: package names currently mounted. */
3365
- const MOUNTED = Symbol.for("dsh-web.mounted-plugins");
3366
- /** Additive key this guard owns: refused mounts waiting for the name. */
3367
- const WAITERS = Symbol.for("dsh-web.mounted-plugins.waiters");
3368
- /**
3369
- * The shared name registry, always a `Set` whatever another build stored here:
3370
- * a foreign value (an interim shape, a hand-written global) must not take every
3371
- * family plugin down with it.
3372
- * @returns the process-wide set of mounted package names.
3373
- */
3374
- function mountedSet() {
3375
- const registry = globalThis;
3376
- const existing = registry[MOUNTED];
3377
- if (existing instanceof Set) return existing;
3378
- const created = /* @__PURE__ */ new Set();
3379
- registry[MOUNTED] = created;
3380
- return created;
3381
- }
3382
- /** Queue per package name for mounts refused while a holder was alive. */
3383
- function mountWaiters() {
3384
- const registry = globalThis;
3385
- return registry[WAITERS] ??= /* @__PURE__ */ new Map();
3386
- }
3387
- /**
3388
- * Wrap a cordis plugin apply so the package runs at most once per process.
3389
- * The first mount registers normally and releases the name when its fiber
3390
- * disposes; a mount refused while that name is held waits for the release and
3391
- * then runs, unless its own fiber disposes first.
3392
- * @param packageName - npm package identity shared by every install source.
3393
- * @param fn - the original plugin apply.
3394
- * @returns an apply of the same shape.
3395
- */
3396
- function mountOnce(packageName, fn) {
3397
- const mount = (...args) => {
3398
- const mounted = mountedSet();
3399
- const ctx = args[0];
3400
- if (mounted.has(packageName)) {
3401
- const waiters = mountWaiters();
3402
- const queue = waiters.get(packageName) ?? [];
3403
- let alive = true;
3404
- const pending = { run: () => {
3405
- if (alive) mount(...args);
3406
- } };
3407
- ctx?.effect?.(() => () => {
3408
- alive = false;
3409
- const index = queue.indexOf(pending);
3410
- if (index >= 0) queue.splice(index, 1);
3411
- });
3412
- queue.push(pending);
3413
- waiters.set(packageName, queue);
3414
- return;
3415
- }
3416
- mounted.add(packageName);
3417
- ctx?.effect?.(() => () => {
3418
- mounted.delete(packageName);
3419
- const waiters = mountWaiters();
3420
- const queue = waiters.get(packageName);
3421
- if (queue === void 0) return;
3422
- waiters.delete(packageName);
3423
- for (const waiter of queue.splice(0)) queueMicrotask(() => {
3424
- waiter.run();
3425
- });
3426
- });
3427
- return fn(...args);
3428
- };
3429
- return mount;
3430
- }
3431
- //#endregion
3432
- //#region src/tool-surface.ts
3433
- /**
3434
- * Family-shared tool-surface conventions for the packages that register
3435
- * model-facing tools.
3436
- *
3437
- * One home for the prompt-section placement and the visibility gate this
3438
- * family previously restated per package.
3439
- *
3440
- * Modelled on the official tool packages:
3441
- * - `@deepseek-ai/dsh-tool-subagent` renders its section through
3442
- * `tools.get(name, context.scope) === undefined ? '' : text`, so guidance
3443
- * disappears together with a restricted tool.
3444
- * - 21 of the 22 official tool packages register their tools GLOBALLY and gate
3445
- * them with a setting, not per agent. Only the Agent Teams tool package —
3446
- * whose tools belong to one membership — installs into each `agent.ctx`.
3447
- * This family follows the majority: registration stays global so the
3448
- * registry's per-scope `restrict()` mask (which filters inherited global
3449
- * tools and REJECTS scope-local names) can still withhold these tools.
3450
- *
3451
- * Structural types only: this copy lands in packages that do not all depend on
3452
- * the same SDK service packages.
3453
- */
3454
- /**
3455
- * Prompt-section order for each package's tool guidance.
3456
- *
3457
- * These sit in the family band between the deployment persona and the SDK's
3458
- * `PLAN_POLICY` (500). Values are owned here rather than written per package so
3459
- * the host plugins whose guidance shares one prompt cannot drift into an
3460
- * accidental tie.
3461
- */
3462
- const PLUGIN_TOOL_SECTION_ORDERS = {
3463
- ssh: 150,
3464
- "task-board": 200,
3465
- agents: 220
3466
- };
3467
- /**
3468
- * Build a section provider that renders \`text\` only while at least one of
3469
- * \`toolNames\` is visible to the rendering scope.
3470
- *
3471
- * The native convention: a tool that a restriction, a preset, or a missing
3472
- * registry removed must not leave guidance behind telling the model to call it.
3473
- * An unreadable registry renders the text unchanged — guidance that outlives a
3474
- * momentary read failure is recoverable; guidance for a tool that is gone is
3475
- * not.
3476
- * @param tools - the scoped tool registry, when the deployment serves one.
3477
- * @param toolNames - registered names the guidance describes.
3478
- * @param text - the guidance rendered while they are reachable.
3479
- * @returns the section text provider.
3480
- */
3481
- function visibleToolText(tools, toolNames, text) {
3482
- if (tools === void 0) return () => text;
3483
- return (context) => {
3484
- for (const name of toolNames) try {
3485
- if (tools.get(name, context.scope) !== void 0) return text;
3486
- } catch {
3487
- return text;
3488
- }
3489
- return "";
3490
- };
3491
- }
3492
- //#endregion
3493
- //#region src/index.ts
3494
- /** Stable cordis plugin name. */
3495
- const name = "ssh";
3496
- /** Services required before the SSH surfaces can mount. */
3497
- const inject = [
3498
- "webServer",
3499
- "tools",
3500
- "systemPrompt"
3501
- ];
3502
- /**
3503
- * Plugin config schema. Under the 0.1.7 settings model this schema IS the
3504
- * entry's settings page: the Host derives one form per profile entry from it
3505
- * and serves it through the shared configuration forms. Every field is
3506
- * `volatile()`, which is what puts it on that page and what lets an edit reach
3507
- * a running instance without a remount: the loader commits the new value into
3508
- * the field's reference and announces `loader/volatile-update` on this fiber.
3509
- */
3510
- const Config = z.object({
3511
- announceToAgent: z.boolean().default(false).volatile(),
3512
- enabled: z.boolean().default(true).volatile(),
3513
- terminalFontFamily: z.string().default("").volatile(),
3514
- connectTimeoutMs: z.number().step(1).min(1e3).max(6e5).default(DEFAULT_CONNECT_TIMEOUT_MS).volatile().description("TCP connect, SSH key exchange and user authentication timeout in milliseconds; raise it for hosts whose authentication is slow.")
3515
- });
3516
- /** Schema defaults, re-read for hand-built test contexts (the loader applies them normally). */
3517
- const DEFAULT_ANNOUNCE = false;
3518
- const DEFAULT_ENABLED = true;
3519
- /** Read one resolved config field, following the live reference the schema produces. */
3520
- function readConfigField(field, fallback) {
3521
- if (field === void 0) return fallback;
3522
- if (typeof field === "object" && field !== null && typeof field.get === "function") {
3523
- const value = field.get();
3524
- return value === void 0 ? fallback : value;
3525
- }
3526
- return field;
3527
- }
3528
- /** Raw config the profile declares for this entry, when the loader exposes it. */
3529
- function profileConfig(ctx) {
3530
- const config = ctx.fiber.entry?.options?.config;
3531
- if (typeof config !== "object" || config === null || Array.isArray(config)) return void 0;
3532
- return config;
3533
- }
3534
- /** Order of the announcement section within the shared tool-guidance band. */
3535
- const SECTION_ORDER = PLUGIN_TOOL_SECTION_ORDERS.ssh;
3536
- /** The six agent-tool names this plugin's announcement describes. */
3537
- const SSH_TOOL_NAMES = [
3538
- "ssh_list",
3539
- "ssh_exec",
3540
- "ssh_upload",
3541
- "ssh_download",
3542
- "ssh_tunnel",
3543
- "ssh_cluster"
3544
- ];
3545
- /** Model-facing announcement: plugin presence, capabilities, and limits. */
3546
- 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
- /**
3548
- * Mount the SSH engine, routes, tools, and announcement.
3549
- * @param ctx - host plugin context carrying webServer/tools/systemPrompt.
3550
- * @param config - resolved plugin config (schema defaults applied by the loader).
3551
- */
3552
- const apply = mountOnce("@fish-under-sea/dsh-ssh-fish", applyImpl);
3553
- function applyImpl(ctx, config) {
3554
- const store = new HostStore();
3555
- const engine = new SshEngine(store, { connectTimeoutMs: readConfigField(config?.connectTimeoutMs, DEFAULT_CONNECT_TIMEOUT_MS) });
3556
- ctx.effect(() => () => {
3557
- engine.dispose();
3558
- }, "dsh-ssh: engine");
3559
- const resolve = () => {
3560
- let enabled = readConfigField(config?.enabled, DEFAULT_ENABLED);
3561
- if (enabled === false && profileConfig(ctx)?.enabled === void 0 && store.list().length > 0) enabled = true;
3562
- return {
3563
- announceToAgent: readConfigField(config?.announceToAgent, DEFAULT_ANNOUNCE),
3564
- enabled
3565
- };
3566
- };
3567
- const { routes, upgrade, terminalSessions } = makeRoutes({
3568
- store,
3569
- engine
3570
- });
3571
- let disposeRoutes;
3572
- const tools = [
3573
- sshListTool(engine),
3574
- sshExecTool(engine),
3575
- sshUploadTool(engine),
3576
- sshDownloadTool(engine),
3577
- sshTunnelTool(engine),
3578
- sshClusterTool(engine)
3579
- ];
3580
- let disposeTools;
3581
- let disposeSection;
3582
- const sync = () => {
3583
- engine.setConnectTimeout(readConfigField(config?.connectTimeoutMs, DEFAULT_CONNECT_TIMEOUT_MS));
3584
- const value = resolve();
3585
- if (disposeSection !== void 0) {
3586
- disposeSection();
3587
- disposeSection = void 0;
3588
- }
3589
- if (disposeRoutes !== void 0) {
3590
- disposeRoutes();
3591
- disposeRoutes = void 0;
3592
- }
3593
- if (disposeTools !== void 0) {
3594
- disposeTools();
3595
- disposeTools = void 0;
3596
- }
3597
- if (!value.enabled) return;
3598
- if (value.announceToAgent) disposeSection = ctx.systemPrompt.section({
3599
- name: "plugin:dsh-ssh",
3600
- order: SECTION_ORDER,
3601
- text: visibleToolText(ctx.tools, SSH_TOOL_NAMES, SSH_GUIDANCE)
3602
- });
3603
- disposeRoutes = ctx.effect(() => {
3604
- const disposers = routes.map((route) => ctx.webServer.register(route));
3605
- const upgradeDisposer = ctx.webServer.registerUpgrade(upgrade);
3606
- return () => {
3607
- for (const dispose of disposers) dispose();
3608
- upgradeDisposer();
3609
- terminalSessions.dispose();
3610
- };
3611
- }, "dsh-ssh: routes");
3612
- disposeTools = ctx.effect(() => {
3613
- const disposers = tools.map((tool) => ctx.tools.register(tool));
3614
- return () => {
3615
- for (const dispose of disposers) dispose();
3616
- };
3617
- }, "dsh-ssh: tools");
3618
- };
3619
- ctx.on("loader/volatile-update", () => {
3620
- sync();
3621
- });
3622
- sync();
3623
- }
3624
- //#endregion
3625
- export { Config, SSH_GUIDANCE, apply, inject, name };