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