@linxin666/dsh-ssh 0.4.20 → 0.4.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import z from "@deepseek-ai/schemastery";
2
- import { closeSync, createReadStream, createWriteStream, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
2
+ import { closeSync, createReadStream, createWriteStream, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { StringDecoder } from "node:string_decoder";
3
4
  import { Client } from "ssh2";
4
5
  import { randomBytes, randomUUID } from "node:crypto";
5
6
  import { homedir, tmpdir } from "node:os";
6
- import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
7
+ import { basename, dirname, isAbsolute, join, posix, relative, resolve } from "node:path";
7
8
  import { isAbsolute as isAbsolute$1, join as join$1 } from "node:path/posix";
8
9
  import { spawn } from "node:child_process";
9
10
  import { Duplex } from "node:stream";
@@ -195,19 +196,27 @@ function storePath() {
195
196
  function sshConfigPath() {
196
197
  return join(homedir(), ".ssh", "config");
197
198
  }
199
+ /** Validate an auth block shape; returns an error message or undefined. */
200
+ function validateAuth(auth) {
201
+ if (typeof auth !== "object" || auth === null) return "auth must be an object";
202
+ const a = auth;
203
+ if (a.kind !== "key" && a.kind !== "password" && a.kind !== "agent") return "auth.kind must be key, password or agent";
204
+ if (a.kind === "key") {
205
+ if (typeof a.keyPath !== "string" || a.keyPath.trim() === "") return "auth.keyPath is required for key auth";
206
+ if (a.passphrase !== void 0 && typeof a.passphrase !== "string") return "auth.passphrase must be a string when provided";
207
+ }
208
+ if (a.kind === "password" && a.password !== void 0 && typeof a.password !== "string") return "auth.password must be a string when provided";
209
+ if (a.kind === "agent" && a.agentPath !== void 0 && typeof a.agentPath !== "string") return "auth.agentPath must be a string when provided";
210
+ }
198
211
  /** Validate the wire shape of a host payload; returns a message or undefined. */
199
212
  function validateHostPayload(payload) {
200
213
  if (typeof payload !== "object" || payload === null) return "body must be a JSON object";
201
214
  const p = payload;
202
215
  if (typeof p.host !== "string" || p.host.trim() === "") return "host is required";
203
216
  if (typeof p.user !== "string" || p.user.trim() === "") return "user is required";
204
- 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";
217
+ if (p.auth !== void 0) {
218
+ const authError = validateAuth(p.auth);
219
+ if (authError !== void 0) return authError;
211
220
  }
212
221
  if (p.port !== void 0 && (typeof p.port !== "number" || !Number.isInteger(p.port) || p.port < 1 || p.port > 65535)) return "port must be an integer in 1..65535";
213
222
  if (p.proxyJump !== void 0 && (!Array.isArray(p.proxyJump) || p.proxyJump.some((x) => typeof x !== "string" || x === ""))) return "proxyJump must be an array of alias strings";
@@ -218,6 +227,38 @@ function validateHostPayload(payload) {
218
227
  if (p.tags !== void 0 && (!Array.isArray(p.tags) || p.tags.some((x) => typeof x !== "string"))) return "tags must be an array of strings";
219
228
  if (p.forwardAgent !== void 0 && typeof p.forwardAgent !== "boolean") return "forwardAgent must be a boolean";
220
229
  }
230
+ /** Validate a full creation payload and build its normalized entry. */
231
+ function buildValidatedHostEntry(payload, now) {
232
+ const alias = payload.alias?.trim();
233
+ if (!alias) throw new Error("alias is required");
234
+ const aliasError = validateAlias(alias);
235
+ if (aliasError !== void 0) throw new Error(aliasError);
236
+ const bodyError = validateHostPayload(payload);
237
+ if (bodyError !== void 0) throw new Error(bodyError);
238
+ if (payload.auth === void 0) throw new Error("auth is required");
239
+ return {
240
+ alias,
241
+ host: payload.host.trim(),
242
+ port: payload.port ?? 22,
243
+ user: payload.user.trim(),
244
+ auth: {
245
+ kind: payload.auth.kind,
246
+ keyPath: payload.auth.kind === "key" ? expandHome(payload.auth.keyPath?.trim() ?? "") : void 0,
247
+ passphrase: payload.auth.kind === "key" ? payload.auth.passphrase || void 0 : void 0,
248
+ password: payload.auth.kind === "password" ? payload.auth.password : void 0,
249
+ agentPath: payload.auth.kind === "agent" ? normalizeAgentPath(payload.auth.agentPath) : void 0
250
+ },
251
+ proxyJump: [...payload.proxyJump ?? []],
252
+ proxyCommand: normalizeProxyCommand(payload.proxyCommand),
253
+ description: payload.description?.trim() || void 0,
254
+ environment: payload.environment?.trim() || void 0,
255
+ tags: [...payload.tags ?? []].map((tag) => tag.trim()).filter((tag) => tag !== ""),
256
+ location: payload.location?.trim() || void 0,
257
+ forwardAgent: payload.forwardAgent === true ? true : void 0,
258
+ createdAt: now,
259
+ updatedAt: now
260
+ };
261
+ }
221
262
  /** Alias grammar: letters/digits plus dots, hyphens, underscores (IP/domain aliases included). */
222
263
  const ALIAS_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
223
264
  /** Validate an alias for creation. */
@@ -244,17 +285,17 @@ var HostStore = class {
244
285
  list(query) {
245
286
  const file = this.load();
246
287
  const needle = query?.trim().toLowerCase();
247
- if (needle === void 0 || needle === "") return file.hosts;
288
+ if (needle === void 0 || needle === "") return [...file.hosts];
248
289
  return file.hosts.filter((entry) => entry.alias.toLowerCase().includes(needle) || (entry.description ?? "").toLowerCase().includes(needle) || entry.host.toLowerCase().includes(needle) || entry.tags.some((tag) => tag.toLowerCase().includes(needle)));
249
290
  }
250
291
  /** Find one entry by alias. */
251
292
  find(alias) {
252
- return this.list().find((entry) => entry.alias === alias);
293
+ return this.load().hosts.find((entry) => entry.alias === alias);
253
294
  }
254
295
  /** Secret-free projection for the browser and agent surfaces. */
255
296
  summarize(entry) {
256
297
  let keyReady = true;
257
- if (entry.auth.kind === "key" && entry.auth.keyPath) keyReady = existsSync(expandHome(entry.auth.keyPath));
298
+ if (entry.auth.kind === "key") keyReady = entry.auth.keyPath !== void 0 && entry.auth.keyPath !== "" && existsSync(expandHome(entry.auth.keyPath));
258
299
  else if (entry.auth.kind === "agent") keyReady = false;
259
300
  return {
260
301
  alias: entry.alias,
@@ -283,47 +324,23 @@ var HostStore = class {
283
324
  }
284
325
  /** Create one entry. Throws on alias collision or invalid payload. */
285
326
  create(payload) {
286
- const alias = payload.alias?.trim();
287
- if (!alias) throw new Error("alias is required");
288
- const aliasError = validateAlias(alias);
289
- if (aliasError !== void 0) throw new Error(aliasError);
290
- const bodyError = validateHostPayload(payload);
291
- if (bodyError !== void 0) throw new Error(bodyError);
292
- if (payload.auth === void 0) throw new Error("auth is required");
327
+ const entry = buildValidatedHostEntry(payload, Date.now());
293
328
  const file = this.load();
294
- if (file.hosts.some((entry) => entry.alias === alias)) throw new Error(`alias '${alias}' already exists`);
295
- const now = Date.now();
296
- const entry = {
297
- alias,
298
- host: payload.host.trim(),
299
- port: payload.port ?? 22,
300
- user: payload.user.trim(),
301
- auth: {
302
- kind: payload.auth.kind,
303
- keyPath: payload.auth.kind === "key" ? expandHome(payload.auth.keyPath?.trim() ?? "") : void 0,
304
- passphrase: payload.auth.kind === "key" ? payload.auth.passphrase || void 0 : void 0,
305
- password: payload.auth.kind === "password" ? payload.auth.password : void 0,
306
- agentPath: payload.auth.kind === "agent" ? normalizeAgentPath(payload.auth.agentPath) : void 0
307
- },
308
- proxyJump: [...payload.proxyJump ?? []],
309
- proxyCommand: normalizeProxyCommand(payload.proxyCommand),
310
- description: payload.description?.trim() || void 0,
311
- environment: payload.environment?.trim() || void 0,
312
- tags: [...payload.tags ?? []].map((tag) => tag.trim()).filter((tag) => tag !== ""),
313
- location: payload.location?.trim() || void 0,
314
- forwardAgent: payload.forwardAgent === true ? true : void 0,
315
- createdAt: now,
316
- updatedAt: now
329
+ if (file.hosts.some((existing) => existing.alias === entry.alias)) throw new Error(`alias '${entry.alias}' already exists`);
330
+ const nextFile = {
331
+ version: file.version,
332
+ hosts: [...file.hosts, entry],
333
+ ...file.keys !== void 0 ? { keys: file.keys } : {}
317
334
  };
318
- file.hosts.push(entry);
319
- this.save(file);
335
+ this.save(nextFile);
320
336
  return entry;
321
337
  }
322
338
  /** Update the fields present in `patch`; unknown aliases throw. */
323
339
  update(alias, patch) {
324
340
  const file = this.load();
325
- const entry = file.hosts.find((candidate) => candidate.alias === alias);
326
- if (entry === void 0) throw new Error(`alias '${alias}' not found`);
341
+ const index = file.hosts.findIndex((candidate) => candidate.alias === alias);
342
+ if (index < 0) throw new Error(`alias '${alias}' not found`);
343
+ const entry = file.hosts[index];
327
344
  if (patch.host !== void 0 && (typeof patch.host !== "string" || patch.host.trim() === "")) throw new Error("host is required");
328
345
  if (patch.user !== void 0 && (typeof patch.user !== "string" || patch.user.trim() === "")) throw new Error("user is required");
329
346
  if (patch.port !== void 0 && (typeof patch.port !== "number" || !Number.isInteger(patch.port) || patch.port < 1 || patch.port > 65535)) throw new Error("port must be an integer in 1..65535");
@@ -333,17 +350,18 @@ var HostStore = class {
333
350
  const mergedProxyCommand = patch.proxyCommand !== void 0 ? normalizeProxyCommand(patch.proxyCommand) : entry.proxyCommand;
334
351
  if (mergedProxyCommand !== void 0 && (patch.proxyJump ?? entry.proxyJump).length > 0) throw new Error("proxyCommand and proxyJump cannot be combined — pick one transport per host");
335
352
  if (patch.tags !== void 0 && (!Array.isArray(patch.tags) || patch.tags.some((x) => typeof x !== "string"))) throw new Error("tags must be an array of strings");
336
- if (patch.host !== void 0) entry.host = patch.host.trim();
337
- if (patch.port !== void 0) entry.port = patch.port;
338
- if (patch.user !== void 0) entry.user = patch.user.trim();
353
+ if (patch.description !== void 0 && typeof patch.description !== "string") throw new Error("description must be a string when provided");
354
+ if (patch.environment !== void 0 && typeof patch.environment !== "string") throw new Error("environment must be a string when provided");
355
+ if (patch.location !== void 0 && typeof patch.location !== "string") throw new Error("location must be a string when provided");
356
+ if (patch.auth !== void 0) {
357
+ const authError = validateAuth(patch.auth);
358
+ if (authError !== void 0) throw new Error(authError);
359
+ }
360
+ let nextAuth = entry.auth;
339
361
  if (patch.auth !== void 0) {
340
362
  const auth = patch.auth;
341
- if (auth.kind !== "key" && auth.kind !== "password" && auth.kind !== "agent") throw new Error("auth.kind must be key, password or agent");
342
- if (auth.kind === "key" && (typeof auth.keyPath !== "string" || auth.keyPath.trim() === "")) throw new Error("auth.keyPath is required for key auth");
343
- if (auth.kind === "password" && auth.password !== void 0 && typeof auth.password !== "string") throw new Error("auth.password must be a string when provided");
344
- if (auth.kind === "agent" && auth.agentPath !== void 0 && typeof auth.agentPath !== "string") throw new Error("auth.agentPath must be a string when provided");
345
363
  const keyChanged = auth.kind === "key" && auth.keyPath !== void 0 && expandHome(auth.keyPath.trim()) !== entry.auth.keyPath;
346
- entry.auth = {
364
+ nextAuth = {
347
365
  kind: auth.kind,
348
366
  keyPath: auth.kind === "key" ? expandHome(auth.keyPath?.trim() ?? "") : void 0,
349
367
  passphrase: auth.kind === "key" ? auth.passphrase !== void 0 ? auth.passphrase || void 0 : keyChanged ? void 0 : entry.auth.passphrase : void 0,
@@ -351,29 +369,48 @@ var HostStore = class {
351
369
  agentPath: auth.kind === "agent" ? auth.agentPath !== void 0 ? normalizeAgentPath(auth.agentPath) : entry.auth.agentPath : void 0
352
370
  };
353
371
  }
354
- if (patch.proxyJump !== void 0) entry.proxyJump = [...patch.proxyJump];
355
- if (patch.proxyCommand !== void 0) entry.proxyCommand = mergedProxyCommand;
356
- if (patch.description !== void 0) entry.description = patch.description.trim() || void 0;
357
- if (patch.environment !== void 0) entry.environment = patch.environment.trim() || void 0;
358
- if (patch.tags !== void 0) entry.tags = [...patch.tags].map((tag) => tag.trim()).filter((tag) => tag !== "");
359
- if (patch.location !== void 0) entry.location = patch.location.trim() || void 0;
360
- if (patch.forwardAgent !== void 0) entry.forwardAgent = patch.forwardAgent === true ? true : void 0;
361
- entry.updatedAt = Date.now();
362
- this.save(file);
363
- return entry;
372
+ const nextEntry = {
373
+ ...entry,
374
+ host: patch.host !== void 0 ? patch.host.trim() : entry.host,
375
+ port: patch.port !== void 0 ? patch.port : entry.port,
376
+ user: patch.user !== void 0 ? patch.user.trim() : entry.user,
377
+ auth: nextAuth,
378
+ proxyJump: patch.proxyJump !== void 0 ? [...patch.proxyJump] : entry.proxyJump,
379
+ proxyCommand: patch.proxyCommand !== void 0 ? mergedProxyCommand : entry.proxyCommand,
380
+ description: patch.description !== void 0 ? patch.description.trim() || void 0 : entry.description,
381
+ environment: patch.environment !== void 0 ? patch.environment.trim() || void 0 : entry.environment,
382
+ tags: patch.tags !== void 0 ? [...patch.tags].map((tag) => tag.trim()).filter((tag) => tag !== "") : entry.tags,
383
+ location: patch.location !== void 0 ? patch.location.trim() || void 0 : entry.location,
384
+ forwardAgent: patch.forwardAgent !== void 0 ? patch.forwardAgent === true ? true : void 0 : entry.forwardAgent,
385
+ updatedAt: Date.now()
386
+ };
387
+ const nextFile = {
388
+ version: file.version,
389
+ hosts: file.hosts.map((candidate, candidateIndex) => candidateIndex === index ? nextEntry : candidate),
390
+ ...file.keys !== void 0 ? { keys: file.keys } : {}
391
+ };
392
+ this.save(nextFile);
393
+ return nextEntry;
364
394
  }
365
395
  /** Remove one entry. */
366
396
  delete(alias) {
367
397
  const file = this.load();
368
398
  const index = file.hosts.findIndex((candidate) => candidate.alias === alias);
369
399
  if (index < 0) throw new Error(`alias '${alias}' not found`);
370
- file.hosts.splice(index, 1);
371
- this.save(file);
400
+ const nextFile = {
401
+ version: file.version,
402
+ hosts: file.hosts.filter((_, candidateIndex) => candidateIndex !== index),
403
+ ...file.keys !== void 0 ? { keys: file.keys } : {}
404
+ };
405
+ this.save(nextFile);
372
406
  }
373
407
  /** List managed keys with file-existence and host-reference metadata. */
374
408
  listKeys() {
375
409
  const file = this.load();
376
- return (file.keys ?? []).map((key) => this.summarizeKey(key, file));
410
+ const keys = file.keys ?? [];
411
+ if (keys.length === 0) return [];
412
+ const usedByPath = buildUsedByPathMap(file.hosts);
413
+ return keys.map((key) => this.summarizeKey(key, file, usedByPath));
377
414
  }
378
415
  /** Create one managed key reference without reading its contents. */
379
416
  createKey(payload) {
@@ -386,34 +423,57 @@ var HostStore = class {
386
423
  name,
387
424
  path,
388
425
  passphrase: typeof payload.passphrase === "string" && payload.passphrase !== "" ? payload.passphrase : void 0,
389
- note: payload.note?.trim() || void 0,
426
+ note: typeof payload.note === "string" ? payload.note.trim() || void 0 : void 0,
390
427
  createdAt: now,
391
428
  updatedAt: now
392
429
  };
393
- (file.keys ??= []).push(entry);
394
- this.save(file);
395
- return this.summarizeKey(entry, file);
430
+ const nextFile = {
431
+ version: file.version,
432
+ hosts: file.hosts,
433
+ keys: [...file.keys ?? [], entry]
434
+ };
435
+ this.save(nextFile);
436
+ return this.summarizeKey(entry, nextFile);
396
437
  }
397
438
  /** Update a managed key; omitted fields and a blank passphrase keep old values. */
398
439
  updateKey(id, patch) {
399
440
  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);
441
+ const keys = file.keys ?? [];
442
+ const index = keys.findIndex((candidate) => candidate.id === id);
443
+ if (index < 0) throw new Error(`managed key '${id}' not found`);
444
+ const entry = keys[index];
445
+ const nextName = patch.name !== void 0 ? requiredKeyName(patch.name) : entry.name;
446
+ const nextPath = patch.path !== void 0 ? requiredKeyPath(patch.path) : entry.path;
447
+ const nextPassphrase = patch.passphrase !== void 0 ? patch.passphrase === null || patch.passphrase === "" ? void 0 : patch.passphrase : entry.passphrase;
448
+ const nextNote = patch.note !== void 0 ? typeof patch.note === "string" ? patch.note.trim() || void 0 : void 0 : entry.note;
449
+ const nextEntry = {
450
+ ...entry,
451
+ name: nextName,
452
+ path: nextPath,
453
+ passphrase: nextPassphrase,
454
+ note: nextNote,
455
+ updatedAt: Date.now()
456
+ };
457
+ const nextFile = {
458
+ version: file.version,
459
+ hosts: file.hosts,
460
+ keys: keys.map((candidate, candidateIndex) => candidateIndex === index ? nextEntry : candidate)
461
+ };
462
+ this.save(nextFile);
463
+ return this.summarizeKey(nextEntry, nextFile);
409
464
  }
410
465
  /** Delete only the managed reference; stored host auth.keyPath values stay untouched. */
411
466
  deleteKey(id) {
412
467
  const file = this.load();
413
- const index = file.keys?.findIndex((candidate) => candidate.id === id) ?? -1;
468
+ const keys = file.keys ?? [];
469
+ const index = keys.findIndex((candidate) => candidate.id === id);
414
470
  if (index < 0) throw new Error(`managed key '${id}' not found`);
415
- file.keys.splice(index, 1);
416
- this.save(file);
471
+ const nextFile = {
472
+ version: file.version,
473
+ hosts: file.hosts,
474
+ keys: keys.filter((_, candidateIndex) => candidateIndex !== index)
475
+ };
476
+ this.save(nextFile);
417
477
  }
418
478
  /** Resolve a transient managedKeyId into the host's existing keyPath/passphrase shape. */
419
479
  resolveManagedKey(payload) {
@@ -433,15 +493,17 @@ var HostStore = class {
433
493
  }
434
494
  };
435
495
  }
436
- summarizeKey(key, file) {
496
+ summarizeKey(key, file, usedByPath) {
497
+ const resolvedPath = expandHome(key.path);
498
+ const usedBy = usedByPath !== void 0 ? [...usedByPath.get(resolvedPath) ?? []] : file.hosts.filter((host) => host.auth.kind === "key" && host.auth.keyPath !== void 0 && host.auth.keyPath !== "" && expandHome(host.auth.keyPath) === resolvedPath).map((host) => host.alias);
437
499
  return {
438
500
  id: key.id,
439
501
  name: key.name,
440
502
  path: key.path,
441
503
  hasPassphrase: key.passphrase !== void 0 && key.passphrase !== "",
442
504
  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),
505
+ exists: existsSync(resolvedPath),
506
+ usedBy,
445
507
  createdAt: key.createdAt,
446
508
  updatedAt: key.updatedAt
447
509
  };
@@ -456,7 +518,6 @@ var HostStore = class {
456
518
  * @returns import statistics.
457
519
  */
458
520
  importFromSshConfig() {
459
- this.skippedBlocks = [];
460
521
  const configPath = this.sshConfigOverride ?? sshConfigPath();
461
522
  if (!existsSync(configPath)) return {
462
523
  parsed: 0,
@@ -465,23 +526,27 @@ var HostStore = class {
465
526
  skippedBlocks: []
466
527
  };
467
528
  const { blocks, skipped } = readSshConfigBlocks(configPath);
468
- this.skippedBlocks = [...skipped];
529
+ const skippedBlocks = [...skipped];
530
+ const skippedNames = new Set(skipped.map((block) => block.name));
469
531
  const skip = (name, reason) => {
470
- if (name === "") return;
471
- if (this.skippedBlocks.some((block) => block.name === name)) return;
472
- this.skippedBlocks.push({
532
+ if (name === "" || skippedNames.has(name)) return;
533
+ skippedNames.add(name);
534
+ skippedBlocks.push({
473
535
  name,
474
536
  reason
475
537
  });
476
538
  };
477
- let added = 0;
539
+ const file = this.load();
540
+ const existingAliases = new Set(file.hosts.map((entry) => entry.alias));
541
+ const addedEntries = [];
542
+ const now = Date.now();
478
543
  for (const block of blocks) {
479
544
  const pattern = block.pattern.split(/\s+/)[0];
480
545
  if (pattern.includes("*") || pattern.includes("?")) {
481
546
  skip(pattern, "wildcard");
482
547
  continue;
483
548
  }
484
- if (this.list().some((entry) => entry.alias === pattern)) {
549
+ if (existingAliases.has(pattern)) {
485
550
  skip(pattern, "existing");
486
551
  continue;
487
552
  }
@@ -505,20 +570,28 @@ var HostStore = class {
505
570
  forwardAgent: parseForwardAgentValue(block.props.forwardagent)
506
571
  };
507
572
  try {
508
- this.create(payload);
509
- added += 1;
573
+ const entry = buildValidatedHostEntry(payload, now);
574
+ existingAliases.add(entry.alias);
575
+ addedEntries.push(entry);
510
576
  } catch {
511
577
  skip(pattern, "invalid");
512
578
  }
513
579
  }
580
+ if (addedEntries.length > 0) {
581
+ const nextFile = {
582
+ version: file.version,
583
+ hosts: [...file.hosts, ...addedEntries],
584
+ ...file.keys !== void 0 ? { keys: file.keys } : {}
585
+ };
586
+ this.save(nextFile);
587
+ }
514
588
  return {
515
589
  parsed: blocks.length,
516
- added,
517
- skipped: this.skippedBlocks.length,
518
- skippedBlocks: [...this.skippedBlocks]
590
+ added: addedEntries.length,
591
+ skipped: skippedBlocks.length,
592
+ skippedBlocks
519
593
  };
520
594
  }
521
- skippedBlocks = [];
522
595
  /**
523
596
  * Last parsed store keyed by file identity. list/find ride every acquire
524
597
  * and GUI refresh; re-reading and re-parsing the whole file each call is
@@ -563,15 +636,34 @@ var HostStore = class {
563
636
  recursive: true,
564
637
  mode: 448
565
638
  });
566
- const tmp = this.path + ".tmp";
567
- writeFileSync(tmp, JSON.stringify(file, null, 2) + "\n", {
568
- encoding: "utf8",
569
- mode: 384
570
- });
571
- renameSync(tmp, this.path);
639
+ const tmp = `${this.path}.tmp-${process.pid}-${randomBytes(4).toString("hex")}`;
640
+ try {
641
+ writeFileSync(tmp, JSON.stringify(file, null, 2) + "\n", {
642
+ encoding: "utf8",
643
+ mode: 384
644
+ });
645
+ renameSync(tmp, this.path);
646
+ } catch (error) {
647
+ try {
648
+ unlinkSync(tmp);
649
+ } catch {}
650
+ throw error;
651
+ }
572
652
  this.cache = void 0;
573
653
  }
574
654
  };
655
+ /** Group aliases by expanded private-key path in a single pass. */
656
+ function buildUsedByPathMap(hosts) {
657
+ const usedByPath = /* @__PURE__ */ new Map();
658
+ for (const host of hosts) {
659
+ if (host.auth.kind !== "key" || !host.auth.keyPath) continue;
660
+ const resolvedPath = expandHome(host.auth.keyPath);
661
+ const existing = usedByPath.get(resolvedPath);
662
+ if (existing === void 0) usedByPath.set(resolvedPath, [host.alias]);
663
+ else existing.push(host.alias);
664
+ }
665
+ return usedByPath;
666
+ }
575
667
  /** Normalize an agent endpoint for storage: trim, expand `~`, and resolve the SSH_AUTH_SOCK token. */
576
668
  function normalizeAgentPath(agentPath) {
577
669
  const trimmed = agentPath?.trim();
@@ -688,8 +780,15 @@ function startProxyCommand(rawCommand, target) {
688
780
  stderr = (stderr + chunk.toString("utf8")).slice(-4096);
689
781
  });
690
782
  let killed = false;
783
+ let exited = false;
784
+ let escalateTimer;
785
+ const clearEscalate = () => {
786
+ if (escalateTimer === void 0) return;
787
+ clearTimeout(escalateTimer);
788
+ escalateTimer = void 0;
789
+ };
691
790
  const kill = () => {
692
- if (killed) return;
791
+ if (killed || exited || child.exitCode !== null || child.signalCode !== null) return;
693
792
  killed = true;
694
793
  const pid = child.pid;
695
794
  const group = process.platform !== "win32" && pid !== void 0;
@@ -697,12 +796,15 @@ function startProxyCommand(rawCommand, target) {
697
796
  if (group) process.kill(-pid, "SIGTERM");
698
797
  else child.kill();
699
798
  } catch {}
700
- setTimeout(() => {
799
+ escalateTimer = setTimeout(() => {
800
+ escalateTimer = void 0;
801
+ if (exited || child.exitCode !== null || child.signalCode !== null) return;
701
802
  try {
702
803
  if (group) process.kill(-pid, "SIGKILL");
703
804
  else child.kill("SIGKILL");
704
805
  } catch {}
705
- }, KILL_GRACE_MS).unref();
806
+ }, KILL_GRACE_MS);
807
+ escalateTimer.unref();
706
808
  };
707
809
  function formatExitError(code, signal, stderrDetail) {
708
810
  const status = signal !== null ? "signal " + signal : "code " + String(code ?? "unknown");
@@ -775,7 +877,6 @@ function startProxyCommand(rawCommand, target) {
775
877
  stream.destroy(error);
776
878
  };
777
879
  let stdoutEnded = false;
778
- let exited = false;
779
880
  const finishIfClean = () => {
780
881
  if (exited && stdoutEnded && !failed && !stream.destroyed) stream.push(null);
781
882
  };
@@ -789,25 +890,34 @@ function startProxyCommand(rawCommand, target) {
789
890
  child.stdout?.on("error", (error) => {
790
891
  fail(/* @__PURE__ */ new Error("ProxyCommand stdout error: " + error.message));
791
892
  });
893
+ let stdinErrorPending = false;
792
894
  child.stdin?.on("error", (error) => {
793
895
  if (child.exitCode !== null && child.exitCode !== 0 || child.signalCode !== null) {
794
896
  fail(formatExitError(child.exitCode, child.signalCode, stderr));
795
897
  return;
796
898
  }
899
+ if (exited || child.exitCode !== null || stdinErrorPending || failed || stream.destroyed) return;
900
+ stdinErrorPending = true;
901
+ const onExit = (code, signal) => {
902
+ stdinErrorPending = false;
903
+ clearTimeout(timer);
904
+ if (code !== null && code !== 0 || signal !== null) fail(formatExitError(code, signal, stderr));
905
+ };
797
906
  const timer = setTimeout(() => {
907
+ stdinErrorPending = false;
908
+ child.removeListener("exit", onExit);
798
909
  fail(/* @__PURE__ */ new Error("ProxyCommand transport error: " + error.message));
799
910
  }, 200);
800
911
  timer.unref();
801
- child.once("exit", (code, signal) => {
802
- clearTimeout(timer);
803
- if (code !== null && code !== 0 || signal !== null) fail(formatExitError(code, signal, stderr));
804
- });
912
+ child.once("exit", onExit);
805
913
  });
806
914
  child.on("error", (error) => {
915
+ clearEscalate();
807
916
  fail(/* @__PURE__ */ new Error("ProxyCommand could not start: " + error.message));
808
917
  });
809
918
  child.on("exit", (code, signal) => {
810
919
  exited = true;
920
+ clearEscalate();
811
921
  if (code !== null && code !== 0 || signal !== null) {
812
922
  fail(formatExitError(code, signal, stderr));
813
923
  return;
@@ -942,14 +1052,19 @@ function connectClient(config, onKeyboardInteractive) {
942
1052
  const cause = error instanceof Error ? error : new Error(String(error));
943
1053
  reject(isReadyTimeout(cause) ? new Error(readyTimeoutMessage(config.readyTimeout, handshakeComplete)) : cause);
944
1054
  };
1055
+ const onPreReadyClose = () => {
1056
+ fail(/* @__PURE__ */ new Error("SSH connection closed before ready"));
1057
+ };
945
1058
  client.once("handshake", () => {
946
1059
  handshakeComplete = true;
947
1060
  });
948
1061
  client.once("ready", () => {
949
1062
  if (settled) return;
950
1063
  settled = true;
1064
+ client.removeListener?.("close", onPreReadyClose);
951
1065
  resolve(client);
952
1066
  });
1067
+ client.once("close", onPreReadyClose);
953
1068
  client.on("keyboard-interactive", (name, instructions, instructionsLang, prompts, finish) => {
954
1069
  if (onKeyboardInteractive !== void 0) {
955
1070
  onKeyboardInteractive(name, instructions, instructionsLang, prompts.map((p) => ({
@@ -972,17 +1087,40 @@ function connectClient(config, onKeyboardInteractive) {
972
1087
  }
973
1088
  });
974
1089
  }
975
- /** Cap captured output at the configured byte budget (marks truncation). */
976
- function appendOutput(target, chunk, maxBytes) {
977
- if (target.truncated) return;
978
- if (target.text.length + chunk.length > maxBytes) {
979
- let cut = chunk.toString("utf8").slice(0, maxBytes - target.text.length);
980
- if (/[\uD800-\uDBFF]$/.test(cut)) cut = cut.slice(0, -1);
1090
+ /** Truncate `text` so its UTF-8 encoding fits within `maxBytes` without splitting code points. */
1091
+ function sliceUtf8ToBytes(text, maxBytes) {
1092
+ if (maxBytes <= 0 || text === "") return "";
1093
+ if (Buffer.byteLength(text, "utf8") <= maxBytes) return text;
1094
+ let bytes = 0;
1095
+ let end = 0;
1096
+ for (const char of text) {
1097
+ const code = char.codePointAt(0);
1098
+ const charBytes = code < 128 ? 1 : code < 2048 ? 2 : code < 65536 ? 3 : 4;
1099
+ if (bytes + charBytes > maxBytes) break;
1100
+ bytes += charBytes;
1101
+ end += char.length;
1102
+ }
1103
+ return text.slice(0, end);
1104
+ }
1105
+ /** Append an already-decoded string chunk under a UTF-8 byte budget. */
1106
+ function appendDecodedOutput(target, decoded, maxBytes) {
1107
+ if (target.truncated || decoded === "") return;
1108
+ const usedBytes = target.bytes ?? Buffer.byteLength(target.text, "utf8");
1109
+ const decodedBytes = Buffer.byteLength(decoded, "utf8");
1110
+ if (usedBytes + decodedBytes > maxBytes) {
1111
+ const cut = sliceUtf8ToBytes(decoded, maxBytes - usedBytes);
981
1112
  target.text += cut + "…[output truncated]";
1113
+ target.bytes = maxBytes;
982
1114
  target.truncated = true;
983
1115
  return;
984
1116
  }
985
- target.text += chunk.toString("utf8");
1117
+ target.text += decoded;
1118
+ target.bytes = usedBytes + decodedBytes;
1119
+ }
1120
+ /** Cap captured output at the configured UTF-8 byte budget (marks truncation). */
1121
+ function appendOutput(target, chunk, maxBytes, decoder) {
1122
+ if (target.truncated) return;
1123
+ appendDecodedOutput(target, decoder !== void 0 ? decoder.write(chunk) : chunk.toString("utf8"), maxBytes);
986
1124
  }
987
1125
  /** The ProxyCommand token source for one entry. */
988
1126
  function proxyTargetOf(entry) {
@@ -1131,8 +1269,36 @@ async function connectChain(engine, entry, onKeyboardInteractive) {
1131
1269
  throw error;
1132
1270
  }
1133
1271
  }
1272
+ const poolLifecycles = /* @__PURE__ */ new WeakMap();
1273
+ function lifecycleOf(engine) {
1274
+ let state = poolLifecycles.get(engine);
1275
+ if (state === void 0) {
1276
+ state = {
1277
+ disposed: false,
1278
+ generations: /* @__PURE__ */ new Map()
1279
+ };
1280
+ poolLifecycles.set(engine, state);
1281
+ }
1282
+ return state;
1283
+ }
1284
+ /**
1285
+ * Invalidate any in-flight acquire for `alias` so a connection still handshaking
1286
+ * under stale config or before a delete cannot enter `engine.pool` after completion.
1287
+ */
1288
+ function invalidateAlias(engine, alias) {
1289
+ const state = lifecycleOf(engine);
1290
+ state.generations.set(alias, (state.generations.get(alias) ?? 0) + 1);
1291
+ engine.acquireQueue.delete(alias);
1292
+ }
1293
+ /** Mark the pool disposed so in-flight acquires tear down instead of entering the pool. */
1294
+ function markPoolDisposed(engine) {
1295
+ const state = lifecycleOf(engine);
1296
+ state.disposed = true;
1297
+ engine.acquireQueue.clear();
1298
+ }
1134
1299
  /** Connect (or reuse) the pooled chain for one alias; pins nothing. */
1135
1300
  async function acquire(engine, alias) {
1301
+ if (lifecycleOf(engine).disposed) throw new Error("ssh engine has been disposed");
1136
1302
  const pending = engine.acquireQueue.get(alias);
1137
1303
  if (pending !== void 0) return pending;
1138
1304
  const task = doAcquire(engine, alias);
@@ -1144,6 +1310,9 @@ async function acquire(engine, alias) {
1144
1310
  }
1145
1311
  }
1146
1312
  async function doAcquire(engine, alias) {
1313
+ const state = lifecycleOf(engine);
1314
+ if (state.disposed) throw new Error("ssh engine has been disposed");
1315
+ const gen = state.generations.get(alias) ?? 0;
1147
1316
  const entry = engine.store.find(alias);
1148
1317
  if (entry === void 0) throw new Error("alias '" + alias + "' not found — add it first");
1149
1318
  const { client, hops } = await connectChain(engine, entry);
@@ -1155,12 +1324,25 @@ async function doAcquire(engine, alias) {
1155
1324
  broken: false,
1156
1325
  inFlight: 0
1157
1326
  };
1158
- client.on("error", () => {
1327
+ if (state.disposed || (state.generations.get(alias) ?? 0) !== gen) {
1328
+ endRecordChain(record);
1329
+ throw new Error(state.disposed ? "ssh engine disposed while connecting '" + alias + "'" : "host '" + alias + "' configuration changed while connecting");
1330
+ }
1331
+ const markBroken = () => {
1159
1332
  record.broken = true;
1160
- });
1161
- client.on("close", () => {
1333
+ };
1334
+ const onTargetClosed = () => {
1162
1335
  record.broken = true;
1163
- });
1336
+ for (const hop of record.hops) try {
1337
+ hop.end();
1338
+ } catch {}
1339
+ };
1340
+ client.on("error", markBroken);
1341
+ client.on("close", onTargetClosed);
1342
+ for (const hop of hops) {
1343
+ hop.on("error", markBroken);
1344
+ hop.on("close", markBroken);
1345
+ }
1164
1346
  engine.pool.set(alias, record);
1165
1347
  return record;
1166
1348
  }
@@ -1194,6 +1376,28 @@ function sweepPool(engine) {
1194
1376
  function isAborted(signal) {
1195
1377
  return signal?.aborted === true;
1196
1378
  }
1379
+ /** Race an in-flight promise against an optional AbortSignal without leaving an unhandled rejection behind. */
1380
+ function waitWithSignal(promise, signal) {
1381
+ if (signal === void 0) return promise;
1382
+ if (signal.aborted) {
1383
+ promise.catch(() => void 0);
1384
+ return Promise.reject(/* @__PURE__ */ new Error("command cancelled by the caller"));
1385
+ }
1386
+ return new Promise((resolve, reject) => {
1387
+ const onAbort = () => {
1388
+ promise.catch(() => void 0);
1389
+ reject(/* @__PURE__ */ new Error("command cancelled by the caller"));
1390
+ };
1391
+ signal.addEventListener("abort", onAbort, { once: true });
1392
+ promise.then((value) => {
1393
+ signal.removeEventListener("abort", onAbort);
1394
+ resolve(value);
1395
+ }, (error) => {
1396
+ signal.removeEventListener("abort", onAbort);
1397
+ reject(error);
1398
+ });
1399
+ });
1400
+ }
1197
1401
  /**
1198
1402
  * Run `fn` with a live client for `alias`, reconnecting (up to the
1199
1403
  * attempt budget) when the connection broke mid-flight.
@@ -1205,7 +1409,7 @@ async function withClient(engine, alias, fn, attempts = 3, signal) {
1205
1409
  let record = engine.pool.get(alias);
1206
1410
  if (record === void 0 || record.broken) {
1207
1411
  if (record !== void 0) disposeRecord(engine, alias, record);
1208
- record = await acquire(engine, alias);
1412
+ record = await waitWithSignal(acquire(engine, alias), signal);
1209
1413
  }
1210
1414
  record.idleAt = Date.now();
1211
1415
  record.inFlight += 1;
@@ -1244,11 +1448,21 @@ async function execCommand(engine, alias, command, timeoutMs, signal) {
1244
1448
  let settled = false;
1245
1449
  const stdout = {
1246
1450
  text: "",
1247
- truncated: false
1451
+ truncated: false,
1452
+ bytes: 0
1248
1453
  };
1249
1454
  const stderr = {
1250
1455
  text: "",
1251
- truncated: false
1456
+ truncated: false,
1457
+ bytes: 0
1458
+ };
1459
+ const stdoutDecoder = new StringDecoder("utf8");
1460
+ const stderrDecoder = new StringDecoder("utf8");
1461
+ const flushDecoders = () => {
1462
+ const outTail = stdoutDecoder.end();
1463
+ if (outTail !== "") appendDecodedOutput(stdout, outTail, engine.opts.maxOutputBytes);
1464
+ const errTail = stderrDecoder.end();
1465
+ if (errTail !== "") appendDecodedOutput(stderr, errTail, engine.opts.maxOutputBytes);
1252
1466
  };
1253
1467
  let timer;
1254
1468
  let kill = () => {};
@@ -1267,6 +1481,7 @@ async function execCommand(engine, alias, command, timeoutMs, signal) {
1267
1481
  settled = true;
1268
1482
  if (timer !== void 0) clearTimeout(timer);
1269
1483
  signal?.removeEventListener("abort", onAbort);
1484
+ flushDecoders();
1270
1485
  resolve(cancelledResult());
1271
1486
  };
1272
1487
  const onAbort = () => {
@@ -1308,6 +1523,7 @@ async function execCommand(engine, alias, command, timeoutMs, signal) {
1308
1523
  settled = true;
1309
1524
  if (timer !== void 0) clearTimeout(timer);
1310
1525
  signal?.removeEventListener("abort", onAbort);
1526
+ flushDecoders();
1311
1527
  resolve({
1312
1528
  success: false,
1313
1529
  exitCode: null,
@@ -1328,13 +1544,14 @@ async function execCommand(engine, alias, command, timeoutMs, signal) {
1328
1544
  } catch {}
1329
1545
  finish();
1330
1546
  }, budget);
1331
- stream.on("data", (chunk) => appendOutput(stdout, chunk, engine.opts.maxOutputBytes));
1332
- stream.stderr.on("data", (chunk) => appendOutput(stderr, chunk, engine.opts.maxOutputBytes));
1547
+ stream.on("data", (chunk) => appendOutput(stdout, chunk, engine.opts.maxOutputBytes, stdoutDecoder));
1548
+ stream.stderr.on("data", (chunk) => appendOutput(stderr, chunk, engine.opts.maxOutputBytes, stderrDecoder));
1333
1549
  stream.on("close", (code) => {
1334
1550
  if (settled) return;
1335
1551
  settled = true;
1336
1552
  if (timer !== void 0) clearTimeout(timer);
1337
1553
  signal?.removeEventListener("abort", onAbort);
1554
+ flushDecoders();
1338
1555
  if (aborted) {
1339
1556
  resolve(cancelledResult());
1340
1557
  return;
@@ -1357,6 +1574,7 @@ async function execCommand(engine, alias, command, timeoutMs, signal) {
1357
1574
  settled = true;
1358
1575
  if (timer !== void 0) clearTimeout(timer);
1359
1576
  signal?.removeEventListener("abort", onAbort);
1577
+ flushDecoders();
1360
1578
  if (aborted) {
1361
1579
  resolve(cancelledResult());
1362
1580
  return;
@@ -1494,20 +1712,24 @@ async function upload(engine, alias, localPath, remotePath, recursive, onProgres
1494
1712
  if (!existsSync(local)) throw new Error("local path not found: '" + localPath + "'");
1495
1713
  return withClient(engine, alias, (client) => withSftp(client, async (sftp) => {
1496
1714
  const stat = statSync(local);
1715
+ const ensuredDirs = /* @__PURE__ */ new Set();
1497
1716
  let files;
1498
1717
  if (stat.isDirectory()) {
1499
1718
  if (!recursive) throw new Error("'" + localPath + "' is a directory — enable recursive upload");
1500
1719
  files = walkLocalDir(local);
1501
- await ensureRemoteDir(sftp, remotePath);
1720
+ await ensureRemoteDir(sftp, remotePath, ensuredDirs);
1502
1721
  } else {
1503
1722
  files = [""];
1504
- await ensureRemoteDir(sftp, dirname(remotePath));
1723
+ await ensureRemoteDir(sftp, posix.dirname(remotePath), ensuredDirs);
1505
1724
  }
1506
1725
  let bytes = 0;
1726
+ const baseRemote = remotePath.replace(/\/$/, "");
1507
1727
  for (const rel of files) {
1508
1728
  const src = rel === "" ? local : join(local, rel);
1509
1729
  const remoteRel = rel.split(/[\\/]/).join("/");
1510
- await fastPut(sftp, src, rel === "" ? remotePath : remotePath.replace(/\/$/, "") + "/" + remoteRel, engine.opts.sftpConcurrency, onProgress);
1730
+ const dst = rel === "" ? remotePath : baseRemote + "/" + remoteRel;
1731
+ if (rel !== "") await ensureRemoteDir(sftp, posix.dirname(dst), ensuredDirs);
1732
+ await fastPut(sftp, src, dst, engine.opts.sftpConcurrency, onProgress);
1511
1733
  bytes += statSync(src).size;
1512
1734
  }
1513
1735
  return {
@@ -1576,33 +1798,54 @@ function sftpChannel(client) {
1576
1798
  client.sftp((error, sftp) => error !== void 0 ? reject(error) : resolve(sftp));
1577
1799
  });
1578
1800
  }
1579
- /** Create a remote directory chain (stat-then-mkdir per segment). */
1580
- function ensureRemoteDir(sftp, remote) {
1801
+ function normalizeRemoteDir(remote) {
1802
+ const cleaned = remote.replace(/\/+$/, "");
1803
+ return cleaned === "" ? "/" : cleaned;
1804
+ }
1805
+ function recordEnsuredPrefixes(segments, upToIndex, ensuredDirs) {
1806
+ if (ensuredDirs === void 0) return;
1807
+ for (let index = 0; index <= upToIndex; index += 1) ensuredDirs.add("/" + segments.slice(0, index + 1).join("/"));
1808
+ }
1809
+ function statRemote(sftp, path) {
1810
+ return new Promise((resolve) => {
1811
+ sftp.stat(path, (error) => {
1812
+ resolve(error === void 0);
1813
+ });
1814
+ });
1815
+ }
1816
+ function mkdirRemote(sftp, path) {
1581
1817
  return new Promise((resolve, reject) => {
1582
- const segments = remote.replace(/^\/+/, "").split("/").filter((segment) => segment !== "");
1583
- const walk = (index) => {
1584
- if (index >= segments.length) {
1585
- resolve();
1586
- return;
1587
- }
1588
- const current = "/" + segments.slice(0, index + 1).join("/");
1589
- sftp.stat(current, (statError) => {
1590
- if (statError === void 0) {
1591
- walk(index + 1);
1592
- return;
1593
- }
1594
- sftp.mkdir(current, (mkdirError) => {
1595
- if (mkdirError !== void 0) {
1596
- reject(mkdirError);
1597
- return;
1598
- }
1599
- walk(index + 1);
1600
- });
1601
- });
1602
- };
1603
- walk(0);
1818
+ sftp.mkdir(path, (error) => {
1819
+ if (error !== void 0) reject(error);
1820
+ else resolve();
1821
+ });
1604
1822
  });
1605
1823
  }
1824
+ /** Create a remote directory chain (with a 1-RTT stat fast path and prefix cache). */
1825
+ async function ensureRemoteDir(sftp, remote, ensuredDirs) {
1826
+ const normalized = normalizeRemoteDir(remote);
1827
+ if (normalized === "/" || ensuredDirs?.has(normalized) === true) return;
1828
+ const segments = normalized.slice(1).split("/").filter((segment) => segment !== "");
1829
+ if (segments.length === 0) return;
1830
+ if (segments.length > 1 && await statRemote(sftp, normalized)) {
1831
+ recordEnsuredPrefixes(segments, segments.length - 1, ensuredDirs);
1832
+ return;
1833
+ }
1834
+ for (let index = 0; index < segments.length; index += 1) {
1835
+ const current = "/" + segments.slice(0, index + 1).join("/");
1836
+ if (ensuredDirs?.has(current) === true) continue;
1837
+ if (!(segments.length > 1 && index === segments.length - 1) && await statRemote(sftp, current)) {
1838
+ ensuredDirs?.add(current);
1839
+ continue;
1840
+ }
1841
+ try {
1842
+ await mkdirRemote(sftp, current);
1843
+ } catch (error) {
1844
+ if (!await statRemote(sftp, current)) throw error;
1845
+ }
1846
+ ensuredDirs?.add(current);
1847
+ }
1848
+ }
1606
1849
  /** One fastPut/fastGet transfer with throttled progress (the two directions share everything but the verb). */
1607
1850
  function fastTransfer(sftp, kind, src, dst, concurrency, onProgress) {
1608
1851
  return new Promise((resolve, reject) => {
@@ -1610,7 +1853,7 @@ function fastTransfer(sftp, kind, src, dst, concurrency, onProgress) {
1610
1853
  const finalSize = () => statSync(kind === "put" ? src : dst).size;
1611
1854
  let last = 0;
1612
1855
  let lastEmit = 0;
1613
- const started = Date.now();
1856
+ let prevEmit = Date.now();
1614
1857
  if (kind === "put") onProgress?.({
1615
1858
  phase: "transferring",
1616
1859
  file,
@@ -1622,19 +1865,20 @@ function fastTransfer(sftp, kind, src, dst, concurrency, onProgress) {
1622
1865
  const now = Date.now();
1623
1866
  if (now - lastEmit < 100 && transferred < total) return;
1624
1867
  lastEmit = now;
1625
- const elapsed = (now - started) / 1e3;
1868
+ const windowSec = (now - prevEmit) / 1e3;
1626
1869
  onProgress?.({
1627
1870
  phase: "transferring",
1628
1871
  file,
1629
1872
  transferred,
1630
1873
  total,
1631
1874
  percent: total > 0 ? Math.round(transferred / total * 1e3) / 10 : 0,
1632
- speedBps: elapsed > 0 ? Math.round((transferred - last) / elapsed) : void 0
1875
+ speedBps: windowSec > 0 ? Math.round((transferred - last) / windowSec) : void 0
1633
1876
  });
1877
+ prevEmit = now;
1634
1878
  last = transferred;
1635
1879
  };
1636
1880
  const done = (error) => {
1637
- if (error !== void 0) {
1881
+ if (error !== void 0 && error !== null) {
1638
1882
  onProgress?.({
1639
1883
  phase: "error",
1640
1884
  file,
@@ -1645,11 +1889,12 @@ function fastTransfer(sftp, kind, src, dst, concurrency, onProgress) {
1645
1889
  });
1646
1890
  reject(error);
1647
1891
  } else {
1892
+ const size = finalSize();
1648
1893
  onProgress?.({
1649
1894
  phase: "done",
1650
1895
  file,
1651
- transferred: finalSize(),
1652
- total: finalSize(),
1896
+ transferred: size,
1897
+ total: size,
1653
1898
  percent: 100
1654
1899
  });
1655
1900
  resolve();
@@ -1740,6 +1985,13 @@ async function startTunnel(engine, alias, options) {
1740
1985
  destroyQuietly(socket);
1741
1986
  return;
1742
1987
  }
1988
+ if (socket.destroyed) {
1989
+ try {
1990
+ stream.close();
1991
+ } catch {}
1992
+ destroyQuietly(stream);
1993
+ return;
1994
+ }
1743
1995
  const destroy = () => {
1744
1996
  destroyQuietly(socket);
1745
1997
  try {
@@ -1757,6 +2009,7 @@ async function startTunnel(engine, alias, options) {
1757
2009
  abortTunnel(engine, id);
1758
2010
  }
1759
2011
  });
2012
+ record.inFlight += 1;
1760
2013
  try {
1761
2014
  await new Promise((resolve, reject) => {
1762
2015
  server.once("error", reject);
@@ -1766,10 +2019,15 @@ async function startTunnel(engine, alias, options) {
1766
2019
  });
1767
2020
  });
1768
2021
  } catch (error) {
2022
+ record.inFlight -= 1;
1769
2023
  if (!record.pinned && record.inFlight === 0) disposeRecord(engine, alias, record);
1770
2024
  throw error;
1771
2025
  }
1772
2026
  record.pinned = true;
2027
+ record.inFlight -= 1;
2028
+ server.on("error", () => {
2029
+ abortTunnel(engine, id);
2030
+ });
1773
2031
  const address = server.address();
1774
2032
  info.localPort = typeof address === "object" && address !== null ? address.port : 0;
1775
2033
  info.state = "forwarding";
@@ -1806,7 +2064,10 @@ function stopTunnel(engine, id) {
1806
2064
  } catch {}
1807
2065
  for (const socket of tunnel.sockets) destroyQuietly(socket);
1808
2066
  tunnel.sockets.clear();
1809
- if (![...engine.tunnels.values()].some((candidate) => candidate.record === tunnel.record)) if (engine.pool.get(tunnel.alias) === tunnel.record) disposeRecord(engine, tunnel.alias, tunnel.record);
2067
+ if (![...engine.tunnels.values()].some((candidate) => candidate.record === tunnel.record)) if (engine.pool.get(tunnel.alias) === tunnel.record) if (!tunnel.record.broken && tunnel.record.inFlight > 0) {
2068
+ tunnel.record.pinned = false;
2069
+ tunnel.record.idleAt = Date.now();
2070
+ } else disposeRecord(engine, tunnel.alias, tunnel.record);
1810
2071
  else endRecordChain(tunnel.record);
1811
2072
  return true;
1812
2073
  }
@@ -1821,16 +2082,32 @@ function stopAllTunnels(engine, alias) {
1821
2082
  }
1822
2083
  //#endregion
1823
2084
  //#region src/engine/cluster.ts
2085
+ function normalizeStringList(values) {
2086
+ if (!Array.isArray(values)) return void 0;
2087
+ return values.filter((value) => typeof value === "string").map((value) => value.trim()).filter((value) => value !== "");
2088
+ }
2089
+ /** Whether at least one trimmed non-empty cluster target filter is present. */
2090
+ function hasClusterSelector(options) {
2091
+ const aliases = normalizeStringList(options.aliases);
2092
+ if (aliases !== void 0 && aliases.length > 0) return true;
2093
+ if (typeof options.environment === "string" && options.environment.trim() !== "") return true;
2094
+ const tags = normalizeStringList(options.tags);
2095
+ return tags !== void 0 && tags.length > 0;
2096
+ }
1824
2097
  /** Run one command against many hosts concurrently. */
1825
2098
  async function cluster(engine, options) {
1826
- const hasAliases = Array.isArray(options.aliases) && options.aliases.some((alias) => typeof alias === "string" && alias.trim() !== "");
1827
- const hasEnvironment = typeof options.environment === "string" && options.environment.trim() !== "";
1828
- const hasTags = Array.isArray(options.tags) && options.tags.some((tag) => typeof tag === "string" && tag.trim() !== "");
1829
- if (!hasAliases && !hasEnvironment && !hasTags) throw new Error("ssh_cluster requires aliases, environment, or tags to limit the target set");
2099
+ const aliases = normalizeStringList(options.aliases);
2100
+ const environment = typeof options.environment === "string" && options.environment.trim() !== "" ? options.environment.trim() : void 0;
2101
+ const tags = normalizeStringList(options.tags);
2102
+ if (!hasClusterSelector({
2103
+ aliases,
2104
+ environment,
2105
+ tags
2106
+ })) throw new Error("ssh_cluster requires aliases, environment, or tags to limit the target set");
1830
2107
  let targets = engine.store.list();
1831
- if (options.aliases !== void 0 && options.aliases.length > 0) targets = targets.filter((entry) => options.aliases.includes(entry.alias));
1832
- if (options.environment !== void 0 && options.environment !== "") targets = targets.filter((entry) => entry.environment === options.environment);
1833
- if (options.tags !== void 0 && options.tags.length > 0) targets = targets.filter((entry) => options.tags.every((tag) => entry.tags.includes(tag)));
2108
+ if (aliases !== void 0 && aliases.length > 0) targets = targets.filter((entry) => aliases.includes(entry.alias));
2109
+ if (environment !== void 0) targets = targets.filter((entry) => entry.environment === environment);
2110
+ if (tags !== void 0 && tags.length > 0) targets = targets.filter((entry) => tags.every((tag) => entry.tags.includes(tag)));
1834
2111
  if (targets.length === 0) return [];
1835
2112
  if (options.maxWorkers !== void 0 && (!Number.isInteger(options.maxWorkers) || options.maxWorkers < 1)) throw new Error("maxWorkers must be a positive integer");
1836
2113
  const workers = Math.min(engine.opts.defaultMaxWorkers, options.maxWorkers ?? engine.opts.defaultMaxWorkers, targets.length);
@@ -1848,7 +2125,8 @@ async function cluster(engine, options) {
1848
2125
  timedOut: result.timedOut,
1849
2126
  stdout: result.stdout,
1850
2127
  stderr: result.stderr,
1851
- durationMs: result.durationMs
2128
+ durationMs: result.durationMs,
2129
+ ...result.error !== void 0 ? { error: result.error } : {}
1852
2130
  });
1853
2131
  } catch (error) {
1854
2132
  results.push({
@@ -1954,6 +2232,7 @@ var SshEngine = class {
1954
2232
  * connection — the next operation re-connects from the current config.
1955
2233
  */
1956
2234
  dropAlias(alias) {
2235
+ invalidateAlias(this, alias);
1957
2236
  stopAllTunnels(this, alias);
1958
2237
  disposeRecord(this, alias);
1959
2238
  }
@@ -1980,6 +2259,7 @@ var SshEngine = class {
1980
2259
  }
1981
2260
  /** Close every pooled connection and tunnel. */
1982
2261
  dispose() {
2262
+ markPoolDisposed(this);
1983
2263
  if (this.sweepTimer !== void 0) clearInterval(this.sweepTimer);
1984
2264
  for (const id of [...this.tunnels.keys()]) stopTunnel(this, id);
1985
2265
  for (const alias of [...this.pool.keys()]) disposeRecord(this, alias);
@@ -2007,6 +2287,11 @@ const DEFAULT_MAX_BUFFER_BYTES = 256 * 1024;
2007
2287
  const DEFAULT_IDLE_MS = 600 * 1e3;
2008
2288
  /** An exited session is kept this long for a reattaching view. */
2009
2289
  const DEFAULT_EXIT_GRACE_MS = 60 * 1e3;
2290
+ /** Clamp a terminal column/row dimension to an integer >= `min`. */
2291
+ function clampDimension(value, min, fallback) {
2292
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
2293
+ return Math.max(min, Math.trunc(value));
2294
+ }
2010
2295
  /**
2011
2296
  * The host's terminal session table: open one session per connect, attach any
2012
2297
  * number of sockets, and keep the shell alive across detach.
@@ -2029,10 +2314,17 @@ var TerminalSessionRegistry = class {
2029
2314
  id: randomBytes(9).toString("hex"),
2030
2315
  alias,
2031
2316
  sockets: /* @__PURE__ */ new Set(),
2317
+ decoder: new StringDecoder("utf8"),
2032
2318
  buffer: [],
2319
+ bufferChunkBytes: [],
2320
+ bufferHead: 0,
2033
2321
  bufferBytes: 0,
2322
+ paused: false,
2034
2323
  exited: false
2035
2324
  };
2325
+ session.onDrain = () => {
2326
+ if (session.paused) this.applyBackpressure(session);
2327
+ };
2036
2328
  this.sessions.set(session.id, session);
2037
2329
  this.bind(ws, session);
2038
2330
  try {
@@ -2043,7 +2335,8 @@ var TerminalSessionRegistry = class {
2043
2335
  }
2044
2336
  session.shell = shell;
2045
2337
  shell.onData = (data) => {
2046
- this.pushOutput(session, data.toString("utf8"));
2338
+ const text = session.decoder.write(data);
2339
+ if (text !== "") this.pushOutput(session, text);
2047
2340
  };
2048
2341
  shell.onExit = (code, error) => {
2049
2342
  this.finish(session, code, error);
@@ -2054,12 +2347,12 @@ var TerminalSessionRegistry = class {
2054
2347
  sessionId: session.id
2055
2348
  });
2056
2349
  } catch (error) {
2057
- this.sessions.delete(session.id);
2058
2350
  this.send(session, {
2059
2351
  type: "exit",
2060
2352
  code: null,
2061
2353
  error: error instanceof Error ? error.message : String(error)
2062
2354
  });
2355
+ this.end(session);
2063
2356
  }
2064
2357
  }
2065
2358
  /**
@@ -2071,31 +2364,31 @@ var TerminalSessionRegistry = class {
2071
2364
  if (session === void 0) return false;
2072
2365
  this.bind(ws, session);
2073
2366
  this.clearReap(session);
2074
- for (const chunk of session.buffer) this.sendTo(session, ws, {
2367
+ for (let index = session.bufferHead; index < session.buffer.length; index += 1) this.sendPayload(session, ws, JSON.stringify({
2075
2368
  type: "output",
2076
- data: chunk
2077
- });
2078
- this.sendTo(session, ws, {
2369
+ data: session.buffer[index]
2370
+ }));
2371
+ this.sendPayload(session, ws, JSON.stringify({
2079
2372
  type: "ready",
2080
2373
  alias: session.alias,
2081
2374
  sessionId: session.id
2082
- });
2375
+ }));
2083
2376
  if (session.exited) {
2084
- this.sendTo(session, ws, {
2377
+ this.sendPayload(session, ws, JSON.stringify({
2085
2378
  type: "exit",
2086
2379
  code: session.exit?.code ?? null,
2087
2380
  error: session.exit?.error
2088
- });
2381
+ }));
2089
2382
  this.scheduleReap(session, this.exitGraceMs);
2090
2383
  } else {
2091
- session.shell?.resize(Math.max(2, size.cols), Math.max(1, size.rows));
2092
- session.shell?.resume();
2384
+ session.shell?.resize(clampDimension(size.cols, 2, 80), clampDimension(size.rows, 1, 24));
2385
+ this.applyBackpressure(session);
2093
2386
  }
2094
2387
  return true;
2095
2388
  }
2096
2389
  /** End every session (host teardown, plugin dispose). */
2097
2390
  dispose() {
2098
- for (const session of [...this.sessions.values()]) this.end(session, false);
2391
+ for (const session of [...this.sessions.values()]) this.end(session);
2099
2392
  this.sessions.clear();
2100
2393
  }
2101
2394
  /** Number of live sessions (introspection for tests and diagnostics). */
@@ -2112,15 +2405,18 @@ var TerminalSessionRegistry = class {
2112
2405
  } catch {
2113
2406
  return;
2114
2407
  }
2115
- if (frame.type === "input") session.shell?.send(frame.data ?? "");
2116
- else if (frame.type === "resize") session.shell?.resize(Math.max(2, frame.cols ?? 80), Math.max(1, frame.rows ?? 24));
2408
+ if (typeof frame !== "object" || frame === null) return;
2409
+ if (frame.type === "input") {
2410
+ if (typeof frame.data === "string") session.shell?.send(frame.data);
2411
+ } else if (frame.type === "resize") session.shell?.resize(clampDimension(frame.cols, 2, 80), clampDimension(frame.rows, 1, 24));
2117
2412
  else if (frame.type === "auth_response") {
2118
2413
  const finish = session.pendingAuthFinish;
2119
2414
  session.pendingAuthFinish = void 0;
2415
+ const responses = Array.isArray(frame.responses) ? frame.responses.filter((item) => typeof item === "string") : [];
2120
2416
  try {
2121
- finish?.(frame.responses ?? []);
2417
+ finish?.(responses);
2122
2418
  } catch {}
2123
- } else if (frame.type === "close") this.end(session, true);
2419
+ } else if (frame.type === "close") this.end(session);
2124
2420
  else if (frame.type === "detach") this.detach(ws);
2125
2421
  });
2126
2422
  ws.on("close", () => {
@@ -2135,20 +2431,26 @@ var TerminalSessionRegistry = class {
2135
2431
  for (const session of this.sessions.values()) {
2136
2432
  if (!session.sockets.delete(ws)) continue;
2137
2433
  if (session.sockets.size === 0) this.scheduleReap(session, session.exited ? this.exitGraceMs : this.idleMs);
2434
+ if (session.paused) this.applyBackpressure(session);
2138
2435
  return;
2139
2436
  }
2140
2437
  }
2141
- /** End the session a socket is attached to (explicit close from the view). */
2142
- end(session, notify) {
2438
+ /** End the session and close every socket still attached to it. */
2439
+ end(session) {
2143
2440
  this.clearReap(session);
2144
- if (this.sessions.delete(session.id) && notify) {
2145
- if (session.pendingAuthFinish !== void 0) {
2146
- const finish = session.pendingAuthFinish;
2147
- session.pendingAuthFinish = void 0;
2148
- try {
2149
- finish([]);
2150
- } catch {}
2151
- }
2441
+ this.sessions.delete(session.id);
2442
+ if (session.pendingAuthFinish !== void 0) {
2443
+ const finish = session.pendingAuthFinish;
2444
+ session.pendingAuthFinish = void 0;
2445
+ try {
2446
+ finish([]);
2447
+ } catch {}
2448
+ }
2449
+ for (const ws of [...session.sockets]) {
2450
+ session.sockets.delete(ws);
2451
+ try {
2452
+ ws.close(1e3);
2453
+ } catch {}
2152
2454
  }
2153
2455
  try {
2154
2456
  session.shell?.close();
@@ -2157,6 +2459,8 @@ var TerminalSessionRegistry = class {
2157
2459
  /** Mark a session exited and keep it briefly so a reattaching view sees it. */
2158
2460
  finish(session, code, error) {
2159
2461
  if (session.exited) return;
2462
+ const tail = session.decoder.end();
2463
+ if (tail !== "") this.pushOutput(session, tail);
2160
2464
  session.exited = true;
2161
2465
  session.exit = {
2162
2466
  code,
@@ -2175,13 +2479,47 @@ var TerminalSessionRegistry = class {
2175
2479
  }
2176
2480
  this.scheduleReap(session, this.exitGraceMs);
2177
2481
  }
2178
- /** Append output to the replay buffer, trimmed to the byte cap. */
2482
+ /** Keep at most `maxBytes` from the tail of `data` on a valid UTF-8 boundary. */
2483
+ trimTailToUtf8Bytes(data, maxBytes) {
2484
+ if (maxBytes <= 0) return {
2485
+ text: "",
2486
+ bytes: 0
2487
+ };
2488
+ const buf = Buffer.from(data, "utf8");
2489
+ if (buf.byteLength <= maxBytes) return {
2490
+ text: data,
2491
+ bytes: buf.byteLength
2492
+ };
2493
+ let start = buf.byteLength - maxBytes;
2494
+ while (start < buf.byteLength && (buf[start] & 192) === 128) start += 1;
2495
+ const tail = buf.subarray(start);
2496
+ return {
2497
+ text: tail.toString("utf8"),
2498
+ bytes: tail.byteLength
2499
+ };
2500
+ }
2501
+ /** Append output to the O(1) replay ring, trimmed to the byte cap. */
2179
2502
  pushOutput(session, data) {
2180
- session.buffer.push(data);
2181
- session.bufferBytes += Buffer.byteLength(data);
2182
- while (session.bufferBytes > this.maxBufferBytes && session.buffer.length > 1) {
2183
- const dropped = session.buffer.shift();
2184
- session.bufferBytes -= Buffer.byteLength(dropped ?? "");
2503
+ const chunkBytes = Buffer.byteLength(data, "utf8");
2504
+ if (chunkBytes > this.maxBufferBytes) {
2505
+ const trimmed = this.trimTailToUtf8Bytes(data, this.maxBufferBytes);
2506
+ session.buffer = trimmed.text === "" ? [] : [trimmed.text];
2507
+ session.bufferChunkBytes = trimmed.text === "" ? [] : [trimmed.bytes];
2508
+ session.bufferHead = 0;
2509
+ session.bufferBytes = trimmed.bytes;
2510
+ } else {
2511
+ session.buffer.push(data);
2512
+ session.bufferChunkBytes.push(chunkBytes);
2513
+ session.bufferBytes += chunkBytes;
2514
+ while (session.bufferBytes > this.maxBufferBytes && session.buffer.length - session.bufferHead > 1) {
2515
+ session.bufferBytes -= session.bufferChunkBytes[session.bufferHead];
2516
+ session.bufferHead += 1;
2517
+ }
2518
+ if (session.bufferHead >= 64 && session.bufferHead * 2 >= session.buffer.length) {
2519
+ session.buffer = session.buffer.slice(session.bufferHead);
2520
+ session.bufferChunkBytes = session.bufferChunkBytes.slice(session.bufferHead);
2521
+ session.bufferHead = 0;
2522
+ }
2185
2523
  }
2186
2524
  this.send(session, {
2187
2525
  type: "output",
@@ -2190,27 +2528,34 @@ var TerminalSessionRegistry = class {
2190
2528
  }
2191
2529
  /** Broadcast one frame to every attached socket, honoring backpressure. */
2192
2530
  send(session, frame) {
2193
- for (const ws of session.sockets) this.sendTo(session, ws, frame);
2531
+ const payload = JSON.stringify(frame);
2532
+ for (const ws of session.sockets) this.sendPayload(session, ws, payload);
2194
2533
  this.applyBackpressure(session);
2195
2534
  }
2196
- sendTo(session, ws, frame) {
2535
+ sendPayload(session, ws, payload) {
2197
2536
  if (ws.readyState !== WebSocket.OPEN) return;
2198
2537
  try {
2199
- ws.send(JSON.stringify(frame));
2538
+ if ((session.paused || ws.bufferedAmount + payload.length > BACKPRESSURE_LOW_WATER) && session.onDrain !== void 0) ws.send(payload, session.onDrain);
2539
+ else ws.send(payload);
2200
2540
  } catch {}
2201
2541
  }
2202
2542
  /** Pause while any attached socket is backed up; resume once all drained. */
2203
2543
  applyBackpressure(session) {
2204
2544
  const shell = session.shell;
2205
- if (shell === void 0) return;
2545
+ if (shell === void 0 || session.exited) return;
2206
2546
  let high = false;
2207
2547
  let low = true;
2208
2548
  for (const ws of session.sockets) {
2209
2549
  if (ws.bufferedAmount > BACKPRESSURE_HIGH_WATER) high = true;
2210
2550
  if (ws.bufferedAmount > BACKPRESSURE_LOW_WATER) low = false;
2211
2551
  }
2212
- if (high) shell.pause();
2213
- else if (low) shell.resume();
2552
+ if (high && !session.paused) {
2553
+ session.paused = true;
2554
+ shell.pause();
2555
+ } else if (low && session.paused) {
2556
+ session.paused = false;
2557
+ shell.resume();
2558
+ }
2214
2559
  }
2215
2560
  /** Answer a keyboard-interactive challenge through whoever is attached. */
2216
2561
  keyboardInteractive(session) {
@@ -2232,7 +2577,7 @@ var TerminalSessionRegistry = class {
2232
2577
  const timer = setTimeout(() => {
2233
2578
  session.reapTimer = void 0;
2234
2579
  if (session.sockets.size > 0) return;
2235
- this.end(session, false);
2580
+ this.end(session);
2236
2581
  }, delayMs);
2237
2582
  timer.unref?.();
2238
2583
  session.reapTimer = timer;
@@ -2440,6 +2785,16 @@ function queryParam(url, name) {
2440
2785
  const value = url.searchParams.get(name);
2441
2786
  return value === null ? void 0 : value;
2442
2787
  }
2788
+ /** Strip control characters, quotes, and backslashes from a Content-Disposition filename. */
2789
+ function safeAttachmentFilename(raw) {
2790
+ let clean = "";
2791
+ for (let i = 0; i < raw.length; i += 1) {
2792
+ const code = raw.charCodeAt(i);
2793
+ if (code < 32 || code === 127 || code === 34 || code === 92) continue;
2794
+ clean += raw[i];
2795
+ }
2796
+ return clean === "" ? "download" : clean;
2797
+ }
2443
2798
  /**
2444
2799
  * Build every /api/dsh-ssh route (exact paths) plus the terminal upgrade.
2445
2800
  * @param deps - store, engine, staging dir.
@@ -2511,8 +2866,9 @@ function makeRoutes(deps) {
2511
2866
  return;
2512
2867
  }
2513
2868
  try {
2514
- const entry = store.update(alias, store.resolveManagedKey(body));
2515
- const patch = body;
2869
+ const resolved = store.resolveManagedKey(body);
2870
+ const entry = store.update(alias, resolved);
2871
+ const patch = resolved;
2516
2872
  if ([
2517
2873
  "host",
2518
2874
  "port",
@@ -2664,10 +3020,11 @@ function makeRoutes(deps) {
2664
3020
  const environment = typeof body?.environment === "string" ? body.environment : void 0;
2665
3021
  const timeoutMs = typeof body?.timeoutMs === "number" ? body.timeoutMs : void 0;
2666
3022
  const maxWorkers = typeof body?.maxWorkers === "number" ? body.maxWorkers : void 0;
2667
- const hasAliases = aliases?.some((alias) => alias.trim() !== "") === true;
2668
- const hasEnvironment = typeof environment === "string" && environment.trim() !== "";
2669
- const hasTags = tags?.some((tag) => tag.trim() !== "") === true;
2670
- if (!hasAliases && !hasEnvironment && !hasTags) {
3023
+ if (!hasClusterSelector({
3024
+ aliases,
3025
+ environment,
3026
+ tags
3027
+ })) {
2671
3028
  writeJson(res, 400, { error: "ssh_cluster requires aliases, environment, or tags to limit the target set" });
2672
3029
  return;
2673
3030
  }
@@ -2777,6 +3134,10 @@ function makeRoutes(deps) {
2777
3134
  res.write(JSON.stringify(line) + "\n");
2778
3135
  } catch {}
2779
3136
  };
3137
+ mkdirSync(staging, {
3138
+ recursive: true,
3139
+ mode: 448
3140
+ });
2780
3141
  const tmp = join(staging, `upload-${randomBytes(6).toString("hex")}`);
2781
3142
  const sink = createWriteStream(tmp, { mode: 384 });
2782
3143
  let settled = false;
@@ -2884,20 +3245,60 @@ function makeRoutes(deps) {
2884
3245
  }
2885
3246
  const tmp = join(staging, `download-${randomBytes(6).toString("hex")}`);
2886
3247
  try {
3248
+ mkdirSync(staging, {
3249
+ recursive: true,
3250
+ mode: 448
3251
+ });
2887
3252
  closeSync(openSync(tmp, "w", 384));
2888
3253
  const outcome = await engine.download(alias, remotePath, tmp);
3254
+ if (req.destroyed || res.destroyed) return;
2889
3255
  res.writeHead(200, {
2890
3256
  "content-type": "application/octet-stream",
2891
3257
  "content-length": String(outcome.bytes),
2892
- "content-disposition": `attachment; filename="${basename(remotePath).replace(/"/g, "")}"`,
3258
+ "content-disposition": `attachment; filename="${safeAttachmentFilename(basename(remotePath))}"`,
2893
3259
  "referrer-policy": "no-referrer"
2894
3260
  });
2895
3261
  await new Promise((resolve, reject) => {
2896
3262
  const source = createReadStream(tmp);
2897
- source.on("error", reject);
2898
- res.on("error", reject);
3263
+ let settled = false;
3264
+ const finish = (err) => {
3265
+ if (settled) return;
3266
+ settled = true;
3267
+ res.off("error", onResError);
3268
+ res.off("close", onResClose);
3269
+ if (err !== void 0) reject(err);
3270
+ else resolve();
3271
+ };
3272
+ const abortSource = (err) => {
3273
+ if (settled) return;
3274
+ if (source.closed) {
3275
+ finish(err);
3276
+ return;
3277
+ }
3278
+ source.once("close", () => {
3279
+ finish(err);
3280
+ });
3281
+ if (!source.destroyed) try {
3282
+ source.destroy();
3283
+ } catch {
3284
+ finish(err);
3285
+ }
3286
+ };
3287
+ const onResError = (err) => {
3288
+ abortSource(err);
3289
+ };
3290
+ const onResClose = () => {
3291
+ if (!res.writableEnded) abortSource();
3292
+ };
3293
+ source.on("error", (err) => {
3294
+ abortSource(err);
3295
+ });
3296
+ source.on("close", () => {
3297
+ finish();
3298
+ });
3299
+ res.on("error", onResError);
3300
+ res.on("close", onResClose);
2899
3301
  source.pipe(res);
2900
- source.on("end", resolve);
2901
3302
  });
2902
3303
  } catch (error) {
2903
3304
  if (!res.headersSent) writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
@@ -3470,13 +3871,14 @@ function sshTunnelTool(engine) {
3470
3871
  if (args.action === "start") {
3471
3872
  if (args.alias === void 0 || args.remotePort === void 0) throw new Error("alias and remotePort are required for start");
3472
3873
  try {
3874
+ const tunnel = await engine.startTunnel(args.alias, {
3875
+ remotePort: args.remotePort,
3876
+ remoteHost: args.remoteHost,
3877
+ localPort: args.localPort
3878
+ });
3473
3879
  return {
3474
- ok: true,
3475
- tunnel: await engine.startTunnel(args.alias, {
3476
- remotePort: args.remotePort,
3477
- remoteHost: args.remoteHost,
3478
- localPort: args.localPort
3479
- })
3880
+ ok: tunnel.state !== "failed",
3881
+ tunnel
3480
3882
  };
3481
3883
  } catch (error) {
3482
3884
  return {
@@ -3579,7 +3981,7 @@ function sshClusterTool(engine) {
3579
3981
  render: (_args, value) => text(renderCluster(value.results ?? []))
3580
3982
  },
3581
3983
  async execute(args, exec) {
3582
- 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");
3984
+ if (!hasClusterSelector(args)) throw new Error("ssh_cluster requires aliases, environment, or tags to limit the target set");
3583
3985
  return { results: await engine.cluster({
3584
3986
  ...args,
3585
3987
  signal: exec.signal
@@ -3894,29 +4296,32 @@ function applyImpl(ctx, config) {
3894
4296
  const sync = () => {
3895
4297
  engine.setConnectTimeout(readConfigField(config?.connectTimeoutMs, DEFAULT_CONNECT_TIMEOUT_MS));
3896
4298
  const value = resolve();
3897
- if (disposeSection !== void 0) {
4299
+ const wantSection = value.enabled && value.announceToAgent;
4300
+ if (!wantSection && disposeSection !== void 0) {
3898
4301
  disposeSection();
3899
4302
  disposeSection = void 0;
3900
4303
  }
3901
- if (disposeRoutes !== void 0) {
3902
- disposeRoutes();
3903
- disposeRoutes = void 0;
3904
- }
3905
- if (disposeTools !== void 0) {
3906
- disposeTools();
3907
- disposeTools = void 0;
3908
- }
3909
- if (disposeService !== void 0 && !value.enabled) {
3910
- disposeService();
3911
- disposeService = void 0;
4304
+ if (!value.enabled) {
4305
+ if (disposeRoutes !== void 0) {
4306
+ disposeRoutes();
4307
+ disposeRoutes = void 0;
4308
+ }
4309
+ if (disposeTools !== void 0) {
4310
+ disposeTools();
4311
+ disposeTools = void 0;
4312
+ }
4313
+ if (disposeService !== void 0) {
4314
+ disposeService();
4315
+ disposeService = void 0;
4316
+ }
4317
+ return;
3912
4318
  }
3913
- if (!value.enabled) return;
3914
- if (value.announceToAgent) disposeSection = ctx.systemPrompt.section({
4319
+ if (wantSection && disposeSection === void 0) disposeSection = ctx.systemPrompt.section({
3915
4320
  name: "plugin:dsh-ssh",
3916
4321
  order: SECTION_ORDER,
3917
4322
  text: visibleToolText(ctx.tools, SSH_TOOL_NAMES, SSH_GUIDANCE)
3918
4323
  });
3919
- disposeRoutes = ctx.effect(() => {
4324
+ if (disposeRoutes === void 0) disposeRoutes = ctx.effect(() => {
3920
4325
  const disposers = routes.map((route) => ctx.webServer.register(route));
3921
4326
  const upgradeDisposer = ctx.webServer.registerUpgrade(upgrade);
3922
4327
  return () => {
@@ -3925,7 +4330,7 @@ function applyImpl(ctx, config) {
3925
4330
  terminalSessions.dispose();
3926
4331
  };
3927
4332
  }, "dsh-ssh: routes");
3928
- disposeTools = ctx.effect(() => {
4333
+ if (disposeTools === void 0) disposeTools = ctx.effect(() => {
3929
4334
  const disposers = tools.map((tool) => ctx.tools.register(tool));
3930
4335
  return () => {
3931
4336
  for (const dispose of disposers) dispose();