@linxin666/dsh-ssh 0.4.19 → 0.4.20

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/lib/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import z from "@deepseek-ai/schemastery";
2
2
  import { closeSync, createReadStream, createWriteStream, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
3
3
  import { Client } from "ssh2";
4
+ import { randomBytes, randomUUID } from "node:crypto";
4
5
  import { homedir, tmpdir } from "node:os";
5
6
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
6
7
  import { isAbsolute as isAbsolute$1, join as join$1 } from "node:path/posix";
@@ -8,7 +9,6 @@ import { spawn } from "node:child_process";
8
9
  import { Duplex } from "node:stream";
9
10
  import { createServer } from "node:net";
10
11
  import { unlink } from "node:fs/promises";
11
- import { randomBytes } from "node:crypto";
12
12
  import { WebSocket, WebSocketServer } from "ws";
13
13
  import { defineTool } from "@deepseek-ai/dsh-tools";
14
14
  //#region src/dsh-home.ts
@@ -240,9 +240,12 @@ var HostStore = class {
240
240
  this.path = resolve(path ?? storePath());
241
241
  this.sshConfigOverride = sshConfigOverride;
242
242
  }
243
- /** Load all entries (empty store when the file is absent). */
244
- list() {
245
- return this.load().hosts;
243
+ /** Load host entries, optionally filtered by the panel's search text. */
244
+ list(query) {
245
+ const file = this.load();
246
+ const needle = query?.trim().toLowerCase();
247
+ if (needle === void 0 || needle === "") return file.hosts;
248
+ return file.hosts.filter((entry) => entry.alias.toLowerCase().includes(needle) || (entry.description ?? "").toLowerCase().includes(needle) || entry.host.toLowerCase().includes(needle) || entry.tags.some((tag) => tag.toLowerCase().includes(needle)));
246
249
  }
247
250
  /** Find one entry by alias. */
248
251
  find(alias) {
@@ -271,6 +274,13 @@ var HostStore = class {
271
274
  updatedAt: entry.updatedAt
272
275
  };
273
276
  }
277
+ /** Browser-only projection that can match a stored path to a managed key. */
278
+ summarizePanel(entry) {
279
+ return {
280
+ ...this.summarize(entry),
281
+ ...entry.auth.kind === "key" && entry.auth.keyPath !== void 0 && entry.auth.keyPath !== "" ? { keyPath: entry.auth.keyPath } : {}
282
+ };
283
+ }
274
284
  /** Create one entry. Throws on alias collision or invalid payload. */
275
285
  create(payload) {
276
286
  const alias = payload.alias?.trim();
@@ -291,7 +301,7 @@ var HostStore = class {
291
301
  auth: {
292
302
  kind: payload.auth.kind,
293
303
  keyPath: payload.auth.kind === "key" ? expandHome(payload.auth.keyPath?.trim() ?? "") : void 0,
294
- passphrase: payload.auth.kind === "key" ? payload.auth.passphrase ?? void 0 : void 0,
304
+ passphrase: payload.auth.kind === "key" ? payload.auth.passphrase || void 0 : void 0,
295
305
  password: payload.auth.kind === "password" ? payload.auth.password : void 0,
296
306
  agentPath: payload.auth.kind === "agent" ? normalizeAgentPath(payload.auth.agentPath) : void 0
297
307
  },
@@ -336,7 +346,7 @@ var HostStore = class {
336
346
  entry.auth = {
337
347
  kind: auth.kind,
338
348
  keyPath: auth.kind === "key" ? expandHome(auth.keyPath?.trim() ?? "") : void 0,
339
- passphrase: auth.kind === "key" ? auth.passphrase !== void 0 ? auth.passphrase : keyChanged ? void 0 : entry.auth.passphrase : void 0,
349
+ passphrase: auth.kind === "key" ? auth.passphrase !== void 0 ? auth.passphrase || void 0 : keyChanged ? void 0 : entry.auth.passphrase : void 0,
340
350
  password: auth.kind === "password" ? auth.password : void 0,
341
351
  agentPath: auth.kind === "agent" ? auth.agentPath !== void 0 ? normalizeAgentPath(auth.agentPath) : entry.auth.agentPath : void 0
342
352
  };
@@ -360,6 +370,82 @@ var HostStore = class {
360
370
  file.hosts.splice(index, 1);
361
371
  this.save(file);
362
372
  }
373
+ /** List managed keys with file-existence and host-reference metadata. */
374
+ listKeys() {
375
+ const file = this.load();
376
+ return (file.keys ?? []).map((key) => this.summarizeKey(key, file));
377
+ }
378
+ /** Create one managed key reference without reading its contents. */
379
+ createKey(payload) {
380
+ const name = requiredKeyName(payload.name);
381
+ const path = requiredKeyPath(payload.path);
382
+ const file = this.load();
383
+ const now = Date.now();
384
+ const entry = {
385
+ id: randomUUID(),
386
+ name,
387
+ path,
388
+ passphrase: typeof payload.passphrase === "string" && payload.passphrase !== "" ? payload.passphrase : void 0,
389
+ note: payload.note?.trim() || void 0,
390
+ createdAt: now,
391
+ updatedAt: now
392
+ };
393
+ (file.keys ??= []).push(entry);
394
+ this.save(file);
395
+ return this.summarizeKey(entry, file);
396
+ }
397
+ /** Update a managed key; omitted fields and a blank passphrase keep old values. */
398
+ updateKey(id, patch) {
399
+ const file = this.load();
400
+ const entry = file.keys?.find((candidate) => candidate.id === id);
401
+ if (entry === void 0) throw new Error(`managed key '${id}' not found`);
402
+ if (patch.name !== void 0) entry.name = requiredKeyName(patch.name);
403
+ if (patch.path !== void 0) entry.path = requiredKeyPath(patch.path);
404
+ if (patch.passphrase !== void 0) entry.passphrase = patch.passphrase === null || patch.passphrase === "" ? void 0 : patch.passphrase;
405
+ if (patch.note !== void 0) entry.note = patch.note.trim() || void 0;
406
+ entry.updatedAt = Date.now();
407
+ this.save(file);
408
+ return this.summarizeKey(entry, file);
409
+ }
410
+ /** Delete only the managed reference; stored host auth.keyPath values stay untouched. */
411
+ deleteKey(id) {
412
+ const file = this.load();
413
+ const index = file.keys?.findIndex((candidate) => candidate.id === id) ?? -1;
414
+ if (index < 0) throw new Error(`managed key '${id}' not found`);
415
+ file.keys.splice(index, 1);
416
+ this.save(file);
417
+ }
418
+ /** Resolve a transient managedKeyId into the host's existing keyPath/passphrase shape. */
419
+ resolveManagedKey(payload) {
420
+ if (payload.managedKeyId === void 0) return payload;
421
+ if (typeof payload.managedKeyId !== "string" || payload.managedKeyId === "") throw new Error("managedKeyId must be a non-empty string");
422
+ if (payload.auth !== void 0 && payload.auth.kind !== "key") throw new Error("managedKeyId requires key auth");
423
+ const key = this.load().keys?.find((candidate) => candidate.id === payload.managedKeyId);
424
+ if (key === void 0) throw new Error(`managed key '${payload.managedKeyId}' not found`);
425
+ const { managedKeyId: _managedKeyId, ...rest } = payload;
426
+ return {
427
+ ...rest,
428
+ auth: {
429
+ ...payload.auth,
430
+ kind: "key",
431
+ keyPath: key.path,
432
+ passphrase: key.passphrase ?? ""
433
+ }
434
+ };
435
+ }
436
+ summarizeKey(key, file) {
437
+ return {
438
+ id: key.id,
439
+ name: key.name,
440
+ path: key.path,
441
+ hasPassphrase: key.passphrase !== void 0 && key.passphrase !== "",
442
+ note: key.note,
443
+ exists: existsSync(expandHome(key.path)),
444
+ usedBy: file.hosts.filter((host) => host.auth.kind === "key" && host.auth.keyPath === expandHome(key.path)).map((host) => host.alias),
445
+ createdAt: key.createdAt,
446
+ updatedAt: key.updatedAt
447
+ };
448
+ }
363
449
  /**
364
450
  * Import hosts from `~/.ssh/config`: Host blocks with a single non-wildcard
365
451
  * pattern become entries (a missing HostName falls back to the pattern
@@ -516,6 +602,16 @@ function parseForwardAgentValue(raw) {
516
602
  const value = raw?.trim().toLowerCase();
517
603
  return value === "yes" || value === "true" || value === "on";
518
604
  }
605
+ function requiredKeyName(value) {
606
+ if (typeof value !== "string" || value.trim() === "") throw new Error("key name is required");
607
+ return value.trim();
608
+ }
609
+ function requiredKeyPath(value) {
610
+ if (typeof value !== "string" || value.trim() === "") throw new Error("key path is required");
611
+ const path = expandHome(value.trim());
612
+ if (!isAbsolute(path)) throw new Error("key path must be absolute");
613
+ return path;
614
+ }
519
615
  /** Expand a leading `~` in a filesystem path. */
520
616
  function expandHome(path) {
521
617
  if (path === "~") return homedir();
@@ -1094,6 +1190,10 @@ function sweepPool(engine) {
1094
1190
  const cutoff = Date.now() - engine.opts.idleTimeoutMs;
1095
1191
  for (const [alias, record] of engine.pool) if (!record.pinned && record.inFlight === 0 && record.idleAt < cutoff) disposeRecord(engine, alias, record);
1096
1192
  }
1193
+ /** Read live abort state through a function call so TypeScript does not narrow across `await`. */
1194
+ function isAborted(signal) {
1195
+ return signal?.aborted === true;
1196
+ }
1097
1197
  /**
1098
1198
  * Run `fn` with a live client for `alias`, reconnecting (up to the
1099
1199
  * attempt budget) when the connection broke mid-flight.
@@ -1101,6 +1201,7 @@ function sweepPool(engine) {
1101
1201
  async function withClient(engine, alias, fn, attempts = 3, signal) {
1102
1202
  let lastError;
1103
1203
  for (let attempt = 1; attempt <= attempts; attempt += 1) {
1204
+ if (isAborted(signal)) throw new Error("command cancelled by the caller");
1104
1205
  let record = engine.pool.get(alias);
1105
1206
  if (record === void 0 || record.broken) {
1106
1207
  if (record !== void 0) disposeRecord(engine, alias, record);
@@ -1114,7 +1215,7 @@ async function withClient(engine, alias, fn, attempts = 3, signal) {
1114
1215
  return result;
1115
1216
  } catch (error) {
1116
1217
  lastError = error;
1117
- if (signal?.aborted === true) throw error;
1218
+ if (isAborted(signal)) throw error;
1118
1219
  if (!record.broken) throw error;
1119
1220
  disposeRecord(engine, alias, record);
1120
1221
  } finally {
@@ -1126,31 +1227,21 @@ async function withClient(engine, alias, fn, attempts = 3, signal) {
1126
1227
  /** Run one command on `alias` (reusing the pooled connection). */
1127
1228
  async function execCommand(engine, alias, command, timeoutMs, signal) {
1128
1229
  const started = Date.now();
1230
+ if (isAborted(signal)) return {
1231
+ success: false,
1232
+ exitCode: null,
1233
+ timedOut: false,
1234
+ stdout: "",
1235
+ stderr: "",
1236
+ durationMs: Date.now() - started,
1237
+ error: "command cancelled by the caller"
1238
+ };
1129
1239
  const budget = timeoutMs !== void 0 && timeoutMs > 0 ? timeoutMs : engine.opts.defaultExecTimeoutMs;
1130
- return withClient(engine, alias, async (client) => {
1131
- return await new Promise((resolve, reject) => {
1132
- let aborted = signal !== void 0 && signal.aborted;
1133
- let kill = () => {};
1134
- const onAbort = () => {
1135
- aborted = true;
1136
- kill();
1137
- };
1138
- if (signal !== void 0 && !signal.aborted) signal.addEventListener("abort", onAbort, { once: true });
1139
- client.exec(command, (error, stream) => {
1140
- if (error !== void 0) {
1141
- signal?.removeEventListener("abort", onAbort);
1142
- reject(error);
1143
- return;
1144
- }
1145
- kill = () => {
1146
- try {
1147
- stream.signal("KILL");
1148
- } catch {}
1149
- try {
1150
- stream.close();
1151
- } catch {}
1152
- };
1153
- if (aborted) kill();
1240
+ try {
1241
+ return await withClient(engine, alias, async (client) => {
1242
+ return await new Promise((resolve, reject) => {
1243
+ let aborted = signal !== void 0 && signal.aborted;
1244
+ let settled = false;
1154
1245
  const stdout = {
1155
1246
  text: "",
1156
1247
  truncated: false
@@ -1159,8 +1250,8 @@ async function execCommand(engine, alias, command, timeoutMs, signal) {
1159
1250
  text: "",
1160
1251
  truncated: false
1161
1252
  };
1162
- let timedOut = false;
1163
- let settled = false;
1253
+ let timer;
1254
+ let kill = () => {};
1164
1255
  /** One cancelled outcome: the remote channel was killed on caller request. */
1165
1256
  const cancelledResult = () => ({
1166
1257
  success: false,
@@ -1171,69 +1262,122 @@ async function execCommand(engine, alias, command, timeoutMs, signal) {
1171
1262
  durationMs: Date.now() - started,
1172
1263
  error: "command cancelled by the caller"
1173
1264
  });
1174
- const finish = () => {
1265
+ const settleCancelled = () => {
1175
1266
  if (settled) return;
1176
1267
  settled = true;
1177
- clearTimeout(timer);
1268
+ if (timer !== void 0) clearTimeout(timer);
1178
1269
  signal?.removeEventListener("abort", onAbort);
1179
- resolve({
1180
- success: false,
1181
- exitCode: null,
1182
- timedOut,
1183
- stdout: stdout.text,
1184
- stderr: stderr.text,
1185
- durationMs: Date.now() - started,
1186
- error: timedOut ? "command timed out after " + budget + " ms" : void 0
1187
- });
1270
+ resolve(cancelledResult());
1188
1271
  };
1189
- const timer = setTimeout(() => {
1190
- timedOut = true;
1191
- try {
1192
- stream.signal("KILL");
1193
- } catch {}
1194
- try {
1195
- stream.close();
1196
- } catch {}
1197
- finish();
1198
- }, budget);
1199
- stream.on("data", (chunk) => appendOutput(stdout, chunk, engine.opts.maxOutputBytes));
1200
- stream.stderr.on("data", (chunk) => appendOutput(stderr, chunk, engine.opts.maxOutputBytes));
1201
- stream.on("close", (code) => {
1202
- if (settled) return;
1203
- settled = true;
1204
- clearTimeout(timer);
1205
- signal?.removeEventListener("abort", onAbort);
1206
- if (aborted) {
1207
- resolve(cancelledResult());
1208
- return;
1209
- }
1210
- if (typeof code !== "number" && !timedOut) {
1211
- reject(/* @__PURE__ */ new Error("ssh: connection lost mid-flight (channel closed without an exit status)"));
1272
+ const onAbort = () => {
1273
+ aborted = true;
1274
+ kill();
1275
+ settleCancelled();
1276
+ };
1277
+ if (aborted) {
1278
+ settleCancelled();
1279
+ return;
1280
+ }
1281
+ if (signal !== void 0) signal.addEventListener("abort", onAbort, { once: true });
1282
+ client.exec(command, (error, stream) => {
1283
+ if (error !== void 0) {
1284
+ signal?.removeEventListener("abort", onAbort);
1285
+ if (aborted) {
1286
+ settleCancelled();
1287
+ return;
1288
+ }
1289
+ reject(error);
1212
1290
  return;
1213
1291
  }
1214
- resolve({
1215
- success: code === 0,
1216
- exitCode: code,
1217
- timedOut,
1218
- stdout: stdout.text,
1219
- stderr: stderr.text,
1220
- durationMs: Date.now() - started
1221
- });
1222
- });
1223
- stream.on("error", (streamError) => {
1224
- if (settled) return;
1225
- settled = true;
1226
- clearTimeout(timer);
1227
- signal?.removeEventListener("abort", onAbort);
1292
+ kill = () => {
1293
+ try {
1294
+ stream.signal("KILL");
1295
+ } catch {}
1296
+ try {
1297
+ stream.close();
1298
+ } catch {}
1299
+ };
1228
1300
  if (aborted) {
1229
- resolve(cancelledResult());
1301
+ kill();
1302
+ settleCancelled();
1230
1303
  return;
1231
1304
  }
1232
- reject(streamError);
1305
+ let timedOut = false;
1306
+ const finish = () => {
1307
+ if (settled) return;
1308
+ settled = true;
1309
+ if (timer !== void 0) clearTimeout(timer);
1310
+ signal?.removeEventListener("abort", onAbort);
1311
+ resolve({
1312
+ success: false,
1313
+ exitCode: null,
1314
+ timedOut,
1315
+ stdout: stdout.text,
1316
+ stderr: stderr.text,
1317
+ durationMs: Date.now() - started,
1318
+ error: timedOut ? "command timed out after " + budget + " ms" : void 0
1319
+ });
1320
+ };
1321
+ timer = setTimeout(() => {
1322
+ timedOut = true;
1323
+ try {
1324
+ stream.signal("KILL");
1325
+ } catch {}
1326
+ try {
1327
+ stream.close();
1328
+ } catch {}
1329
+ finish();
1330
+ }, budget);
1331
+ stream.on("data", (chunk) => appendOutput(stdout, chunk, engine.opts.maxOutputBytes));
1332
+ stream.stderr.on("data", (chunk) => appendOutput(stderr, chunk, engine.opts.maxOutputBytes));
1333
+ stream.on("close", (code) => {
1334
+ if (settled) return;
1335
+ settled = true;
1336
+ if (timer !== void 0) clearTimeout(timer);
1337
+ signal?.removeEventListener("abort", onAbort);
1338
+ if (aborted) {
1339
+ resolve(cancelledResult());
1340
+ return;
1341
+ }
1342
+ if (typeof code !== "number" && !timedOut) {
1343
+ reject(/* @__PURE__ */ new Error("ssh: connection lost mid-flight (channel closed without an exit status)"));
1344
+ return;
1345
+ }
1346
+ resolve({
1347
+ success: code === 0,
1348
+ exitCode: code,
1349
+ timedOut,
1350
+ stdout: stdout.text,
1351
+ stderr: stderr.text,
1352
+ durationMs: Date.now() - started
1353
+ });
1354
+ });
1355
+ stream.on("error", (streamError) => {
1356
+ if (settled) return;
1357
+ settled = true;
1358
+ if (timer !== void 0) clearTimeout(timer);
1359
+ signal?.removeEventListener("abort", onAbort);
1360
+ if (aborted) {
1361
+ resolve(cancelledResult());
1362
+ return;
1363
+ }
1364
+ reject(streamError);
1365
+ });
1233
1366
  });
1234
1367
  });
1235
- });
1236
- });
1368
+ }, void 0, signal);
1369
+ } catch (error) {
1370
+ if (isAborted(signal)) return {
1371
+ success: false,
1372
+ exitCode: null,
1373
+ timedOut: false,
1374
+ stdout: "",
1375
+ stderr: "",
1376
+ durationMs: Date.now() - started,
1377
+ error: "command cancelled by the caller"
1378
+ };
1379
+ throw error;
1380
+ }
1237
1381
  }
1238
1382
  //#endregion
1239
1383
  //#region src/engine/pty.ts
@@ -1756,8 +1900,7 @@ var SshEngine = class {
1756
1900
  }
1757
1901
  /** Secret-free host list (filtered by the optional query). */
1758
1902
  list(query) {
1759
- const needle = query?.trim().toLowerCase();
1760
- return this.store.list().filter((entry) => needle === void 0 || needle === "" || entry.alias.toLowerCase().includes(needle) || (entry.description ?? "").toLowerCase().includes(needle) || entry.host.toLowerCase().includes(needle) || entry.tags.some((tag) => tag.toLowerCase().includes(needle))).map((entry) => this.store.summarize(entry));
1903
+ return this.store.list(query).map((entry) => this.store.summarize(entry));
1761
1904
  }
1762
1905
  /** One host summary by alias. */
1763
1906
  find(alias) {
@@ -2218,9 +2361,52 @@ function isLoopbackRequest(request) {
2218
2361
  }
2219
2362
  }
2220
2363
  //#endregion
2364
+ //#region src/connection-trust.ts
2365
+ function resolveConnection(ctx) {
2366
+ try {
2367
+ const candidate = typeof ctx.get === "function" ? ctx.get("connection", false) ?? ctx.get("connection") : ctx.connection;
2368
+ return candidate !== void 0 && candidate !== null && (typeof candidate.admit === "function" || typeof candidate.requestRejection === "function") ? candidate : void 0;
2369
+ } catch {
2370
+ return;
2371
+ }
2372
+ }
2373
+ /** Whether the Host's own authenticated/trusted-host decision admits a request. */
2374
+ function connectionAdmits(connection, request) {
2375
+ if (connection === void 0) return false;
2376
+ try {
2377
+ if (typeof connection.admit === "function") {
2378
+ const admission = connection.admit(request);
2379
+ return admission.rejection === void 0 && "peer" in admission && admission.peer !== void 0;
2380
+ }
2381
+ if (typeof connection.requestRejection === "function") return connection.requestRejection(request) === void 0;
2382
+ return false;
2383
+ } catch {
2384
+ return false;
2385
+ }
2386
+ }
2387
+ /**
2388
+ * Capture connection in a scope that also injects connection.authentication:
2389
+ * admit(request) resolves that service through the calling fiber. The returned
2390
+ * reader falls back to a bare optional lookup on cohorts without that service.
2391
+ */
2392
+ function captureConnection(ctx, effectName) {
2393
+ let captured;
2394
+ const inject = ctx.inject;
2395
+ if (typeof inject === "function") inject.call(ctx, ["connection", "connection.authentication"], (scoped) => {
2396
+ scoped.effect(() => {
2397
+ captured = resolveConnection(scoped);
2398
+ return () => {
2399
+ captured = void 0;
2400
+ };
2401
+ }, effectName);
2402
+ });
2403
+ return () => captured ?? resolveConnection(ctx);
2404
+ }
2405
+ //#endregion
2221
2406
  //#region src/protocol.ts
2222
2407
  const SSH_API = {
2223
2408
  hosts: "/api/dsh-ssh/hosts",
2409
+ keys: "/api/dsh-ssh/keys",
2224
2410
  importSshConfig: "/api/dsh-ssh/hosts/import-ssh-config",
2225
2411
  test: "/api/dsh-ssh/test",
2226
2412
  exec: "/api/dsh-ssh/exec",
@@ -2267,9 +2453,10 @@ function makeRoutes(deps) {
2267
2453
  recursive: true,
2268
2454
  mode: 448
2269
2455
  });
2270
- /** Guard helper: fence + method check. */
2456
+ const allowed = (req) => connectionAdmits(deps.connection?.(), req) || isLoopbackRequest(req);
2457
+ /** Guard helper: Host connection trust or loopback fence + method check. */
2271
2458
  const guard = (req, res, method) => {
2272
- if (!isLoopbackRequest(req)) {
2459
+ if (!allowed(req)) {
2273
2460
  writeJson(res, 403, { error: "forbidden: loopback-only" });
2274
2461
  return false;
2275
2462
  }
@@ -2285,13 +2472,13 @@ function makeRoutes(deps) {
2285
2472
  path: SSH_API.hosts,
2286
2473
  handler: async (req, res) => {
2287
2474
  const method = req.method ?? "GET";
2288
- if (!isLoopbackRequest(req)) {
2475
+ if (!allowed(req)) {
2289
2476
  writeJson(res, 403, { error: "forbidden: loopback-only" });
2290
2477
  return;
2291
2478
  }
2292
2479
  const url = new URL(req.url ?? "/", "http://localhost");
2293
2480
  if (method === "GET") {
2294
- writeJson(res, 200, { hosts: engine.list(queryParam(url, "query")) });
2481
+ writeJson(res, 200, { hosts: store.list(queryParam(url, "query")).map((entry) => store.summarizePanel(entry)) });
2295
2482
  return;
2296
2483
  }
2297
2484
  if (method === "POST") {
@@ -2301,8 +2488,8 @@ function makeRoutes(deps) {
2301
2488
  return;
2302
2489
  }
2303
2490
  try {
2304
- const entry = store.create(body);
2305
- writeJson(res, 201, { host: store.summarize(entry) });
2491
+ const entry = store.create(store.resolveManagedKey(body));
2492
+ writeJson(res, 201, { host: store.summarizePanel(entry) });
2306
2493
  } catch (error) {
2307
2494
  writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
2308
2495
  }
@@ -2324,7 +2511,7 @@ function makeRoutes(deps) {
2324
2511
  return;
2325
2512
  }
2326
2513
  try {
2327
- const entry = store.update(alias, body);
2514
+ const entry = store.update(alias, store.resolveManagedKey(body));
2328
2515
  const patch = body;
2329
2516
  if ([
2330
2517
  "host",
@@ -2335,7 +2522,7 @@ function makeRoutes(deps) {
2335
2522
  "proxyCommand",
2336
2523
  "forwardAgent"
2337
2524
  ].some((key) => patch[key] !== void 0)) engine.dropAlias(alias);
2338
- writeJson(res, 200, { host: store.summarize(entry) });
2525
+ writeJson(res, 200, { host: store.summarizePanel(entry) });
2339
2526
  } catch (error) {
2340
2527
  writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
2341
2528
  }
@@ -2354,6 +2541,63 @@ function makeRoutes(deps) {
2354
2541
  writeJson(res, 405, { error: `method not allowed: ${method}` });
2355
2542
  }
2356
2543
  },
2544
+ {
2545
+ kind: "exact",
2546
+ path: SSH_API.keys,
2547
+ handler: async (req, res) => {
2548
+ const method = req.method ?? "GET";
2549
+ if (!allowed(req)) {
2550
+ writeJson(res, 403, { error: "forbidden: loopback-only" });
2551
+ return;
2552
+ }
2553
+ if (method === "GET") {
2554
+ writeJson(res, 200, { keys: store.listKeys() });
2555
+ return;
2556
+ }
2557
+ const url = new URL(req.url ?? "/", "http://localhost");
2558
+ if (method === "POST") {
2559
+ const body = await readJsonBody(req);
2560
+ if (body === null) {
2561
+ writeJson(res, 400, { error: "invalid JSON body" });
2562
+ return;
2563
+ }
2564
+ try {
2565
+ writeJson(res, 201, { key: store.createKey(body) });
2566
+ } catch (error) {
2567
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
2568
+ }
2569
+ return;
2570
+ }
2571
+ if (method !== "PATCH" && method !== "DELETE") {
2572
+ writeJson(res, 405, { error: `method not allowed: ${method}` });
2573
+ return;
2574
+ }
2575
+ const id = queryParam(url, "id");
2576
+ if (id === void 0 || id === "") {
2577
+ writeJson(res, 400, { error: "id query parameter is required" });
2578
+ return;
2579
+ }
2580
+ if (method === "DELETE") {
2581
+ try {
2582
+ store.deleteKey(id);
2583
+ writeJson(res, 200, { ok: true });
2584
+ } catch (error) {
2585
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
2586
+ }
2587
+ return;
2588
+ }
2589
+ const body = await readJsonBody(req);
2590
+ if (body === null) {
2591
+ writeJson(res, 400, { error: "invalid JSON body" });
2592
+ return;
2593
+ }
2594
+ try {
2595
+ writeJson(res, 200, { key: store.updateKey(id, body) });
2596
+ } catch (error) {
2597
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
2598
+ }
2599
+ }
2600
+ },
2357
2601
  {
2358
2602
  kind: "exact",
2359
2603
  path: SSH_API.importSshConfig,
@@ -2665,54 +2909,83 @@ function makeRoutes(deps) {
2665
2909
  }
2666
2910
  ];
2667
2911
  const terminalSessions = new TerminalSessionRegistry({ openShell: (alias, size, onKeyboardInteractive) => engine.openShell(alias, size, onKeyboardInteractive) });
2668
- return {
2669
- routes,
2670
- upgrade: {
2671
- path: SSH_API.terminal,
2672
- handler: (req, socket, head) => {
2673
- if (!isLoopbackRequest(req)) {
2674
- socket.write("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n");
2675
- socket.destroy();
2676
- return;
2677
- }
2678
- const url = new URL(req.url ?? "/", "http://localhost");
2679
- const alias = queryParam(url, "alias");
2680
- const sessionId = queryParam(url, "session");
2681
- if (alias === void 0 && sessionId === void 0) {
2682
- socket.write("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n");
2683
- socket.destroy();
2912
+ const upgrade = {
2913
+ path: SSH_API.terminal,
2914
+ handler: (req, socket, head) => {
2915
+ if (!allowed(req)) {
2916
+ socket.write("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n");
2917
+ socket.destroy();
2918
+ return;
2919
+ }
2920
+ const url = new URL(req.url ?? "/", "http://localhost");
2921
+ const alias = queryParam(url, "alias");
2922
+ const sessionId = queryParam(url, "session");
2923
+ if (alias === void 0 && sessionId === void 0) {
2924
+ socket.write("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n");
2925
+ socket.destroy();
2926
+ return;
2927
+ }
2928
+ const cols = Number.parseInt(queryParam(url, "cols") ?? "80", 10);
2929
+ const rows = Number.parseInt(queryParam(url, "rows") ?? "24", 10);
2930
+ const size = {
2931
+ cols: Number.isFinite(cols) ? cols : 80,
2932
+ rows: Number.isFinite(rows) ? rows : 24
2933
+ };
2934
+ terminalWss.handleUpgrade(req, socket, head, (ws) => {
2935
+ if (sessionId !== void 0) {
2936
+ if (terminalSessions.attach(ws, sessionId, size)) return;
2937
+ const expired = {
2938
+ type: "exit",
2939
+ code: null,
2940
+ error: "terminal session expired"
2941
+ };
2942
+ try {
2943
+ ws.send(JSON.stringify(expired));
2944
+ } catch {}
2945
+ try {
2946
+ ws.close(1e3);
2947
+ } catch {}
2684
2948
  return;
2685
2949
  }
2686
- const cols = Number.parseInt(queryParam(url, "cols") ?? "80", 10);
2687
- const rows = Number.parseInt(queryParam(url, "rows") ?? "24", 10);
2688
- const size = {
2689
- cols: Number.isFinite(cols) ? cols : 80,
2690
- rows: Number.isFinite(rows) ? rows : 24
2691
- };
2692
- terminalWss.handleUpgrade(req, socket, head, (ws) => {
2693
- if (sessionId !== void 0) {
2694
- if (terminalSessions.attach(ws, sessionId, size)) return;
2695
- const expired = {
2696
- type: "exit",
2697
- code: null,
2698
- error: "terminal session expired"
2699
- };
2700
- try {
2701
- ws.send(JSON.stringify(expired));
2702
- } catch {}
2703
- try {
2704
- ws.close(1e3);
2705
- } catch {}
2706
- return;
2707
- }
2708
- terminalSessions.open(ws, alias, size);
2709
- });
2710
- }
2950
+ terminalSessions.open(ws, alias, size);
2951
+ });
2952
+ }
2953
+ };
2954
+ return {
2955
+ routes: routes.map((route) => ({
2956
+ ...route,
2957
+ auth: "anonymous"
2958
+ })),
2959
+ upgrade: {
2960
+ ...upgrade,
2961
+ auth: "anonymous"
2711
2962
  },
2712
2963
  terminalSessions
2713
2964
  };
2714
2965
  }
2715
2966
  //#endregion
2967
+ //#region src/service.ts
2968
+ /**
2969
+ * The cordis service `dsh-ssh` publishes to sibling plugins.
2970
+ *
2971
+ * A plugin that needs the host inventory or the shared connection pool injects
2972
+ * this service (`ctx.inject(['dshSsh'], ...)`) instead of importing this
2973
+ * package. The face is a thin forwarder over the same `SshEngine` instance the
2974
+ * routes, the agent tools and the panel drive, so a consumer shares one host
2975
+ * store and one connection pool with the surfaces the user already operates.
2976
+ *
2977
+ * This module is the published contract and is deliberately import-free: a
2978
+ * consuming package restates these declarations verbatim and resolves the
2979
+ * service by {@link DSH_SSH_SERVICE} at runtime, so the two packages share a
2980
+ * shape without sharing a module. Only the members named here exist — the web
2981
+ * terminal, tunnels, cluster runs, directory listing and any streaming log
2982
+ * stay behind the plugin's own surfaces.
2983
+ *
2984
+ * @module @linxin666/dsh-ssh/service
2985
+ */
2986
+ /** Cordis service name the host half publishes the face under. */
2987
+ const DSH_SSH_SERVICE = "dshSsh";
2988
+ //#endregion
2716
2989
  //#region src/tools.ts
2717
2990
  /**
2718
2991
  * Agent tools: the DSH-native counterpart of ssh-skill's CLI. Every tool
@@ -3545,7 +3818,44 @@ const SSH_TOOL_NAMES = [
3545
3818
  /** Model-facing announcement: plugin presence, capabilities, and limits. */
3546
3819
  const SSH_GUIDANCE = "本机已安装 dsh-ssh 插件(DSH 远程 SSH 运维):侧边栏「SSH」入口;在 dsh-web 插件全家桶仓库(packages/dsh-ssh)统一维护。能力:主机配置存 $DSH_HOME/dsh-ssh.json(默认 ~/.dsh)(可从 ~/.ssh/config 导入);持久连接池复用长连接(空闲 30 分钟自动断开);ssh_list 列出主机、ssh_exec 执行远程命令、ssh_upload/ssh_download 传输文件、ssh_tunnel 本地端口转发(访问远程数据库/内网服务)、ssh_cluster 按 aliases/environment/tags 至少一种非空 selector 筛选后集群并发执行;支持密钥/密码/ssh-agent 认证、passphrase 密钥、ProxyJump 跳板机(别名或 [user@]host[:port] 地址)与 OpenSSH 语义的 ProxyCommand(跳过堡垒机客户端场景,只能由用户在 GUI 配置,agent 不可写);Web 终端走 WebSocket。限制:主机操作由用户在 GUI 中配置后 agent 方可使用;密码以明文存在用户主目录私有文件(权限 0600);命令输出原样返回、可能含敏感信息;断线重连可能重放非幂等命令;传输/执行消耗真实远程资源,先确认再操作。路径区分:本机(dsh host)上的文件与命令一律用本地工具(read / write / edit / bash),ssh_* 工具只针对远程主机上的路径。用户提到「SSH / 远程服务器 / 服务器操作 / 跳板机 / 隧道 / 部署 / 上传下载」时即指本插件,请据此协作。";
3547
3820
  /**
3548
- * Mount the SSH engine, routes, tools, and announcement.
3821
+ * Project one stored-host summary onto the service face.
3822
+ *
3823
+ * Everything the summary publishes is forwarded except the ProxyCommand text:
3824
+ * the command is a shell line the host process executes with its own
3825
+ * privileges, and a sibling plugin drives the host without ever needing it.
3826
+ * @param summary - the plugin's own secret-free projection.
3827
+ * @returns the same host as the service face reports it.
3828
+ */
3829
+ function toServiceHost(summary) {
3830
+ const { proxyCommand: _proxyCommand, ...host } = summary;
3831
+ return host;
3832
+ }
3833
+ /**
3834
+ * Build the face a sibling plugin receives.
3835
+ *
3836
+ * Every member forwards to the engine instance this plugin already serves its
3837
+ * routes, tools and panel from, so a consumer shares one host store and one
3838
+ * connection pool with them instead of opening its own.
3839
+ * @param engine - the plugin's engine for this apply.
3840
+ * @returns the published service face.
3841
+ */
3842
+ function createService(engine) {
3843
+ return {
3844
+ apiVersion: 1,
3845
+ hosts: {
3846
+ list: () => engine.list().map(toServiceHost),
3847
+ find: (alias) => {
3848
+ const summary = engine.find(alias);
3849
+ return summary === void 0 ? void 0 : toServiceHost(summary);
3850
+ }
3851
+ },
3852
+ exec: (alias, command, options) => engine.exec(alias, command, options?.timeoutMs, options?.signal),
3853
+ upload: (alias, localPath, remotePath) => engine.upload(alias, localPath, remotePath, false),
3854
+ download: (alias, remotePath, localPath) => engine.download(alias, remotePath, localPath)
3855
+ };
3856
+ }
3857
+ /**
3858
+ * Mount the SSH engine, routes, tools, the sibling-plugin service, and announcement.
3549
3859
  * @param ctx - host plugin context carrying webServer/tools/systemPrompt.
3550
3860
  * @param config - resolved plugin config (schema defaults applied by the loader).
3551
3861
  */
@@ -3566,7 +3876,8 @@ function applyImpl(ctx, config) {
3566
3876
  };
3567
3877
  const { routes, upgrade, terminalSessions } = makeRoutes({
3568
3878
  store,
3569
- engine
3879
+ engine,
3880
+ connection: captureConnection(ctx, "dsh-ssh: connection trust")
3570
3881
  });
3571
3882
  let disposeRoutes;
3572
3883
  const tools = [
@@ -3579,6 +3890,7 @@ function applyImpl(ctx, config) {
3579
3890
  ];
3580
3891
  let disposeTools;
3581
3892
  let disposeSection;
3893
+ let disposeService;
3582
3894
  const sync = () => {
3583
3895
  engine.setConnectTimeout(readConfigField(config?.connectTimeoutMs, DEFAULT_CONNECT_TIMEOUT_MS));
3584
3896
  const value = resolve();
@@ -3594,6 +3906,10 @@ function applyImpl(ctx, config) {
3594
3906
  disposeTools();
3595
3907
  disposeTools = void 0;
3596
3908
  }
3909
+ if (disposeService !== void 0 && !value.enabled) {
3910
+ disposeService();
3911
+ disposeService = void 0;
3912
+ }
3597
3913
  if (!value.enabled) return;
3598
3914
  if (value.announceToAgent) disposeSection = ctx.systemPrompt.section({
3599
3915
  name: "plugin:dsh-ssh",
@@ -3615,6 +3931,7 @@ function applyImpl(ctx, config) {
3615
3931
  for (const dispose of disposers) dispose();
3616
3932
  };
3617
3933
  }, "dsh-ssh: tools");
3934
+ if (disposeService === void 0 && typeof ctx.provide === "function") disposeService = ctx.provide(DSH_SSH_SERVICE, createService(engine));
3618
3935
  };
3619
3936
  ctx.on("loader/volatile-update", () => {
3620
3937
  sync();