dsh-linked-workspace 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -22,7 +22,7 @@ import { mkdir, readdir, stat as fsStat } from 'node:fs/promises'
22
22
  import { homedir, tmpdir } from 'node:os'
23
23
  import { basename, dirname, extname, isAbsolute, join, posix, resolve, sep } from 'node:path'
24
24
  import { fileURLToPath } from 'node:url'
25
- import { listHosts, RemoteHost, SshError } from './ssh.js'
25
+ import { listHosts, RemoteHost, SshError, writeLocalCredential } from './ssh.js'
26
26
  import * as linkedFs from './linked.js'
27
27
  import * as git from './git.js'
28
28
 
@@ -754,8 +754,11 @@ function linkedManifestFor(record) {
754
754
  // ── connection pool ─────────────────────────────────────────────────────────
755
755
 
756
756
  class HostPool {
757
- constructor({ knownHostsFile }) {
757
+ constructor({ knownHostsFile, credentialFile }) {
758
758
  this.knownHostsFile = knownHostsFile
759
+ // Secrets the user stored from the add-workspace dialog. Kept apart from the
760
+ // SSH Manager so the plugin works without `dsh-ssh-tunnel`.
761
+ this.credentialFile = credentialFile || null
759
762
  this.records = new Map() // hostId -> HostRecord
760
763
  this.connections = new Map() // hostId -> { authority, remote: RemoteHost }
761
764
  this.connecting = new Map() // hostId -> { authority, promise }
@@ -849,6 +852,7 @@ class HostPool {
849
852
  const remote = new RemoteHost({
850
853
  host: hostRecord,
851
854
  knownHostsFile: this.knownHostsFile,
855
+ credentialFile: this.credentialFile,
852
856
  connectTimeoutMs: CONNECT_TIMEOUT_MS,
853
857
  logger: log,
854
858
  onLost: (info) => this.noteConnectionLost(hostRecord.id, remote, info && info.reason),
@@ -906,7 +910,10 @@ export function apply(ctx) {
906
910
  }
907
911
  }
908
912
  }
909
- const pool = new HostPool({ knownHostsFile: join(dir, 'known_hosts.json') })
913
+ const pool = new HostPool({
914
+ knownHostsFile: join(dir, 'known_hosts.json'),
915
+ credentialFile: join(dir, 'ssh-credentials.json'),
916
+ })
910
917
 
911
918
  let hostsCache = null
912
919
  let hostsRefreshedAt = 0
@@ -914,7 +921,7 @@ export function apply(ctx) {
914
921
  const refreshHosts = async (force) => {
915
922
  if (!force && hostsCache !== null && Date.now() - hostsRefreshedAt < 15_000) return hostsCache
916
923
  try {
917
- const hosts = await listHosts()
924
+ const hosts = await listHosts({ credentialFile: join(dir, 'ssh-credentials.json') })
918
925
  hostsCache = hosts
919
926
  hostsRefreshedAt = Date.now()
920
927
  pool.setHosts(hosts)
@@ -1979,10 +1986,50 @@ export function apply(ctx) {
1979
1986
  authType: host.authType,
1980
1987
  source: host.source,
1981
1988
  hasCredential: host.hasCredential,
1989
+ hasStoredPassword: Boolean(host.hasStoredPassword),
1982
1990
  })),
1983
1991
  }
1984
1992
  },
1985
1993
 
1994
+ /**
1995
+ * Store a credential for one SSH host on this machine.
1996
+ *
1997
+ * This is what makes the plugin usable without `dsh-ssh-tunnel`: a host from
1998
+ * `~/.ssh/config` that has no `IdentityFile` becomes selectable once a
1999
+ * password is stored here. The secret is written to
2000
+ * `<dataDir>/ssh-credentials.json` (mode 0600) and never returned.
2001
+ */
2002
+ async 'hosts.credentials'(params = {}) {
2003
+ const hostId = typeof params.hostId === 'string' ? params.hostId.trim() : ''
2004
+ if (!hostId) throw new ApiError('BAD_REQUEST', 'hostId is required')
2005
+ const clear = params.clear === true
2006
+ const password = typeof params.password === 'string' ? params.password : ''
2007
+ const passphrase = typeof params.passphrase === 'string' ? params.passphrase : ''
2008
+ const privateKey = typeof params.privateKey === 'string' ? params.privateKey : ''
2009
+ if (!clear && !password && !passphrase && !privateKey) {
2010
+ throw new ApiError('BAD_REQUEST', '请填写 SSH 密码(或用 clear 清除已保存的凭据)')
2011
+ }
2012
+ const host = await findHost(hostId)
2013
+ // A live socket authenticated with the old credential must be dropped so
2014
+ // the next request dials again.
2015
+ const live = pool.connection(hostId)
2016
+ if (live) {
2017
+ pool.connections.delete(hostId)
2018
+ live.dispose().catch(() => {})
2019
+ }
2020
+ await writeLocalCredential(join(dir, 'ssh-credentials.json'), hostId, clear
2021
+ ? null
2022
+ : { password, passphrase, privateKey })
2023
+ const hosts = await refreshHosts(true)
2024
+ const updated = hosts.find((item) => item.id === host.id) || host
2025
+ return {
2026
+ hostId: host.id,
2027
+ authType: updated.authType,
2028
+ hasCredential: Boolean(updated.hasCredential),
2029
+ hasStoredPassword: Boolean(updated.hasStoredPassword),
2030
+ }
2031
+ },
2032
+
1986
2033
  async 'hosts.browse'(params = {}) {
1987
2034
  const host = await findHost(params.hostId)
1988
2035
  const remote = await connectHost(host)
package/lib/ssh.js CHANGED
@@ -469,6 +469,16 @@ async function resolveSsh2() {
469
469
  // Host discovery - DSH SSH Manager store
470
470
  // ---------------------------------------------------------------------------
471
471
 
472
+ function mergeSecrets(base, override) {
473
+ if (!base && !override) return null;
474
+ const merged = { ...(base || {}) };
475
+ for (const key of Object.keys(override || {})) {
476
+ const value = override[key];
477
+ if (typeof value === 'string' && value) merged[key] = value;
478
+ }
479
+ return Object.keys(merged).length > 0 ? merged : null;
480
+ }
481
+
472
482
  /**
473
483
  * Read and normalize an SSH Manager secrets file.
474
484
  * The result never leaves this module: it is only used to authenticate and to
@@ -479,17 +489,89 @@ async function readSshManagerSecrets(dataDir) {
479
489
  const byHostId = isPlainObject(raw) && isPlainObject(raw.byHostId) ? raw.byHostId : {};
480
490
  const secrets = {};
481
491
  for (const id of Object.keys(byHostId)) {
482
- const value = byHostId[id];
483
- if (!isPlainObject(value)) continue;
484
- const entry = {};
485
- if (typeof value.password === 'string' && value.password) entry.password = value.password;
486
- if (typeof value.privateKey === 'string' && value.privateKey) entry.privateKey = value.privateKey;
487
- if (typeof value.passphrase === 'string' && value.passphrase) entry.passphrase = value.passphrase;
488
- if (Object.keys(entry).length > 0) secrets[id] = entry;
492
+ const entry = normalizeSecretEntry(byHostId[id]);
493
+ if (entry) secrets[id] = entry;
489
494
  }
490
495
  return secrets;
491
496
  }
492
497
 
498
+ // ---------------------------------------------------------------------------
499
+ // Host discovery - plugin-local credential store
500
+ // ---------------------------------------------------------------------------
501
+ //
502
+ // `dsh-ssh-tunnel` (the SSH Manager) is optional. Without it there is no place
503
+ // to keep a password, so hosts parsed from `~/.ssh/config` that have no
504
+ // `IdentityFile` used to be unusable. The plugin therefore keeps its own store
505
+ // at `<dataDir>/ssh-credentials.json`:
506
+ //
507
+ // { "version": 1, "byHostId": { "<hostId>": { "password"|"privateKey"|"passphrase": "..." } } }
508
+ //
509
+ // It is written with 0600 permissions and never leaves the Host process: the
510
+ // API only ever reports `authType` / `hasCredential` / `hasStoredPassword`.
511
+
512
+ const CREDENTIALS_VERSION = 1;
513
+
514
+ function normalizeSecretEntry(value) {
515
+ if (!isPlainObject(value)) return null;
516
+ const entry = {};
517
+ if (typeof value.password === 'string' && value.password) entry.password = value.password;
518
+ if (typeof value.privateKey === 'string' && value.privateKey) entry.privateKey = value.privateKey;
519
+ if (typeof value.passphrase === 'string' && value.passphrase) entry.passphrase = value.passphrase;
520
+ return Object.keys(entry).length > 0 ? entry : null;
521
+ }
522
+
523
+ /**
524
+ * Read the plugin's own credential store.
525
+ * @param {string} file
526
+ * @returns {Promise<Record<string, { password?: string, privateKey?: string, passphrase?: string }>>}
527
+ */
528
+ export async function readLocalCredentials(file) {
529
+ if (typeof file !== 'string' || !file.trim()) return {};
530
+ const raw = await readJsonFile(file);
531
+ const byHostId = isPlainObject(raw) && isPlainObject(raw.byHostId) ? raw.byHostId : {};
532
+ const secrets = {};
533
+ for (const id of Object.keys(byHostId)) {
534
+ const entry = normalizeSecretEntry(byHostId[id]);
535
+ if (entry) secrets[id] = entry;
536
+ }
537
+ return secrets;
538
+ }
539
+
540
+ /**
541
+ * Store (or delete) the plugin-local credential of one host.
542
+ * Passing `null` removes the entry. The secret is never returned.
543
+ *
544
+ * @param {string} file
545
+ * @param {string} hostId
546
+ * @param {{ password?: string, privateKey?: string, passphrase?: string } | null} patch
547
+ * @returns {Promise<boolean>} true when the host now has a stored credential
548
+ */
549
+ export async function writeLocalCredential(file, hostId, patch) {
550
+ if (typeof file !== 'string' || !file.trim()) {
551
+ throw new SshError('INTERNAL', 'A credentials file path is required');
552
+ }
553
+ const id = asString(hostId).trim();
554
+ if (!id) throw new SshError('BAD_REQUEST', 'A host id is required');
555
+ return withFileLock(file, async () => {
556
+ const current = await readJsonFile(file);
557
+ const byHostId = isPlainObject(current) && isPlainObject(current.byHostId) ? { ...current.byHostId } : {};
558
+ const entry = patch === null ? null : normalizeSecretEntry(patch);
559
+ if (entry) byHostId[id] = entry;
560
+ else delete byHostId[id];
561
+ const payload = `${JSON.stringify({ version: CREDENTIALS_VERSION, byHostId }, null, 2)}\n`;
562
+ await fs.mkdir(path.dirname(file), { recursive: true });
563
+ const temp = `${file}.${randomToken(6)}.tmp`;
564
+ await fs.writeFile(temp, payload, { encoding: 'utf8', mode: 0o600 });
565
+ await fs.rename(temp, file);
566
+ try {
567
+ await fs.chmod(file, 0o600);
568
+ } catch {
569
+ /* best effort on filesystems without POSIX modes */
570
+ }
571
+ return Boolean(entry);
572
+ });
573
+ }
574
+
493
575
  function normalizeAuthType(value, context = {}) {
494
576
  if (typeof value === 'string' && AUTH_TYPES.has(value)) return value;
495
577
  const secret = context.secret && typeof context.secret === 'object' ? context.secret : null;
@@ -522,7 +604,7 @@ function pickHostKeyAlgorithms(record) {
522
604
  * file yields an empty list. Secrets are only inspected to set
523
605
  * `hasCredential`; no secret value is ever placed on a returned record.
524
606
  *
525
- * @param {{ homeDir?: string, dataDir?: string }} [opts]
607
+ * @param {{ homeDir?: string, dataDir?: string, credentials?: Record<string, object> }} [opts]
526
608
  * @returns {Promise<Array<object>>}
527
609
  */
528
610
  export async function readSshManagerHosts(opts = {}) {
@@ -530,6 +612,7 @@ export async function readSshManagerHosts(opts = {}) {
530
612
  const raw = await readJsonFile(path.join(dataDir, 'hosts.json'));
531
613
  const list = Array.isArray(raw) ? raw : isPlainObject(raw) && Array.isArray(raw.hosts) ? raw.hosts : [];
532
614
  const secrets = await readSshManagerSecrets(dataDir);
615
+ const local = isPlainObject(opts.credentials) ? opts.credentials : {};
533
616
  const records = [];
534
617
 
535
618
  for (const entry of list) {
@@ -541,7 +624,9 @@ export async function readSshManagerHosts(opts = {}) {
541
624
  const id = asString(entry.id) || `ssh-manager:${username}@${host}:${port}`;
542
625
  const name = asString(entry.name) || host;
543
626
  const privateKeyPath = asString(entry.privateKeyPath) || asString(entry.identityFile) || undefined;
544
- const secret = secrets[id] || null;
627
+ // A credential stored by this plugin wins over the SSH Manager one, so a
628
+ // stale password can be fixed without the companion plugin.
629
+ const secret = mergeSecrets(secrets[id] || null, local[id] || null);
545
630
  const authType = normalizeAuthType(entry.authType, { privateKeyPath, secret });
546
631
  const record = {
547
632
  id,
@@ -554,6 +639,7 @@ export async function readSshManagerHosts(opts = {}) {
554
639
  hasCredential: await computeHasCredential(authType, privateKeyPath, secret),
555
640
  };
556
641
  if (privateKeyPath) record.privateKeyPath = privateKeyPath;
642
+ if (secret && secret.password) record.hasStoredPassword = true;
557
643
  const hostKeyAlgorithms = pickHostKeyAlgorithms(entry);
558
644
  if (hostKeyAlgorithms) record.hostKeyAlgorithms = hostKeyAlgorithms;
559
645
  records.push(record);
@@ -625,6 +711,21 @@ function resolveLocalConfigPath(value, homeDir) {
625
711
  return path.resolve(path.join(homeDir, '.ssh'), expanded);
626
712
  }
627
713
 
714
+ /**
715
+ * Auth type for a `~/.ssh/config` host.
716
+ * A stored password only wins when there is no usable key file, so a host with
717
+ * a working `IdentityFile` keeps using the key.
718
+ */
719
+ async function resolveConfigAuthType(privateKeyPath, secret) {
720
+ if (secret && secret.password) {
721
+ if (!privateKeyPath) return 'password';
722
+ return (await fileExists(privateKeyPath)) ? 'privateKey' : 'password';
723
+ }
724
+ if (privateKeyPath) return 'privateKey';
725
+ if (secret && secret.privateKey) return 'privateKey';
726
+ return 'agent';
727
+ }
728
+
628
729
  /**
629
730
  * Parse ~/.ssh/config into host records.
630
731
  *
@@ -632,11 +733,12 @@ function resolveLocalConfigPath(value, homeDir) {
632
733
  * wildcard, negated and `Match` blocks are skipped. `Include` is not followed.
633
734
  * The first definition of an alias wins, like OpenSSH.
634
735
  *
635
- * @param {{ homeDir?: string }} [opts]
736
+ * @param {{ homeDir?: string, credentials?: Record<string, object> }} [opts]
636
737
  * @returns {Promise<Array<object>>}
637
738
  */
638
739
  export async function readSshConfigHosts(opts = {}) {
639
740
  const homeDir = typeof opts.homeDir === 'string' && opts.homeDir ? opts.homeDir : os.homedir();
741
+ const local = isPlainObject(opts.credentials) ? opts.credentials : {};
640
742
  const configFile = path.join(homeDir, '.ssh', 'config');
641
743
  let text;
642
744
  try {
@@ -662,18 +764,21 @@ export async function readSshConfigHosts(opts = {}) {
662
764
  const port = asPort(options.port);
663
765
  const username = unquote(options.user || '') || defaultUser;
664
766
  const privateKeyPath = options.identityfile ? resolveLocalConfigPath(options.identityfile, homeDir) : undefined;
665
- const authType = privateKeyPath ? 'privateKey' : 'agent';
767
+ const id = `sshconfig:${alias}`;
768
+ const secret = mergeSecrets(null, local[id] || null);
769
+ const authType = await resolveConfigAuthType(privateKeyPath, secret);
666
770
  const record = {
667
- id: `sshconfig:${alias}`,
771
+ id,
668
772
  name: alias,
669
773
  host,
670
774
  port,
671
775
  username,
672
776
  authType,
673
777
  source: 'ssh-config',
674
- hasCredential: await computeHasCredential(authType, privateKeyPath, null),
778
+ hasCredential: await computeHasCredential(authType, privateKeyPath, secret),
675
779
  };
676
780
  if (privateKeyPath) record.privateKeyPath = privateKeyPath;
781
+ if (secret && secret.password) record.hasStoredPassword = true;
677
782
  seenAliases.add(alias);
678
783
  records.push(record);
679
784
  }
@@ -713,11 +818,19 @@ export async function readSshConfigHosts(opts = {}) {
713
818
  * Merge SSH Manager hosts and ~/.ssh/config hosts, de-duplicated by
714
819
  * username@host:port. Manager hosts win and appear first.
715
820
  *
716
- * @param {{ homeDir?: string, dataDir?: string }} [opts]
821
+ * `credentialFile` points at this plugin's own credential store, which makes a
822
+ * `~/.ssh/config` host without `IdentityFile` usable even when the SSH Manager
823
+ * (`dsh-ssh-tunnel`) is not installed.
824
+ *
825
+ * @param {{ homeDir?: string, dataDir?: string, credentialFile?: string }} [opts]
717
826
  * @returns {Promise<Array<object>>}
718
827
  */
719
828
  export async function listHosts(opts = {}) {
720
- const [managerHosts, configHosts] = await Promise.all([readSshManagerHosts(opts), readSshConfigHosts(opts)]);
829
+ const credentials = await readLocalCredentials(opts.credentialFile);
830
+ const [managerHosts, configHosts] = await Promise.all([
831
+ readSshManagerHosts({ ...opts, credentials }),
832
+ readSshConfigHosts({ ...opts, credentials }),
833
+ ]);
721
834
  const merged = [];
722
835
  const seen = new Set();
723
836
  for (const record of [...managerHosts, ...configHosts]) {
@@ -805,6 +918,7 @@ export class RemoteHost {
805
918
  #generation = 0;
806
919
  #logger;
807
920
  #dataDir;
921
+ #credentialFile = null;
808
922
  #onLost = null;
809
923
 
810
924
  /**
@@ -814,11 +928,12 @@ export class RemoteHost {
814
928
  * connectTimeoutMs?: number,
815
929
  * logger?: (level: 'info'|'warn'|'error', message: string) => void,
816
930
  * dataDir?: string,
931
+ * credentialFile?: string,
817
932
  * onLost?: (info: { reason: string, authority: string }) => void,
818
933
  * }} options
819
934
  */
820
935
  constructor(options = {}) {
821
- const { host, knownHostsFile, connectTimeoutMs, logger, dataDir, onLost } = options || {};
936
+ const { host, knownHostsFile, connectTimeoutMs, logger, dataDir, credentialFile, onLost } = options || {};
822
937
  if (!isPlainObject(host) || !asString(host.host).trim()) {
823
938
  throw new SshError('INTERNAL', 'RemoteHost requires a host record with a non-empty "host" field');
824
939
  }
@@ -838,6 +953,7 @@ export class RemoteHost {
838
953
  this.connectTimeoutMs = Number.isFinite(timeout) && timeout > 0 ? timeout : DEFAULT_CONNECT_TIMEOUT_MS;
839
954
  this.#logger = typeof logger === 'function' ? logger : null;
840
955
  this.#dataDir = typeof dataDir === 'string' && dataDir ? dataDir : null;
956
+ this.#credentialFile = typeof credentialFile === 'string' && credentialFile ? credentialFile : null;
841
957
  this.#onLost = typeof onLost === 'function' ? onLost : null;
842
958
  }
843
959
 
@@ -900,6 +1016,16 @@ export class RemoteHost {
900
1016
  this.#client = client;
901
1017
  this.#ready = false;
902
1018
 
1019
+ // Servers that route logins through PAM often accept only
1020
+ // `keyboard-interactive`. Answer those prompts with the same stored
1021
+ // password so one secret works for both methods.
1022
+ const interactivePassword = auth.password || '';
1023
+ if (interactivePassword) {
1024
+ client.on('keyboard-interactive', (_name, _instructions, _language, prompts, finish) => {
1025
+ finish(prompts.map(() => interactivePassword));
1026
+ });
1027
+ }
1028
+
903
1029
  const config = {
904
1030
  host: this.host.host,
905
1031
  port: this.host.port,
@@ -907,7 +1033,7 @@ export class RemoteHost {
907
1033
  readyTimeout: this.connectTimeoutMs,
908
1034
  keepaliveInterval: KEEPALIVE_INTERVAL_MS,
909
1035
  keepaliveCountMax: KEEPALIVE_COUNT_MAX,
910
- tryKeyboard: false,
1036
+ tryKeyboard: Boolean(interactivePassword),
911
1037
  hostHash: 'sha256',
912
1038
  hostVerifier: (hashedKey, callback) => this.#verifyHostKey(knownHosts, hashedKey, callback),
913
1039
  };
@@ -1072,9 +1198,14 @@ export class RemoteHost {
1072
1198
  // -- authentication -------------------------------------------------------
1073
1199
 
1074
1200
  async #secretForHost() {
1201
+ const local = this.#credentialFile
1202
+ ? (await readLocalCredentials(this.#credentialFile))[this.host.id] || null
1203
+ : null;
1075
1204
  const dataDir = this.#dataDir || defaultSshDataDir();
1076
- const secrets = await readSshManagerSecrets(dataDir);
1077
- return secrets[this.host.id] || null;
1205
+ const manager = (await readSshManagerSecrets(dataDir))[this.host.id] || null;
1206
+ // The plugin-local store wins, so a password set in the add-workspace dialog
1207
+ // takes effect even when the SSH Manager holds a stale one.
1208
+ return mergeSecrets(manager, local);
1078
1209
  }
1079
1210
 
1080
1211
  async #resolveAuth() {
@@ -1101,7 +1232,10 @@ export class RemoteHost {
1101
1232
  if (authType === 'password') {
1102
1233
  const password = asString(this.host.password) || (secret && secret.password) || '';
1103
1234
  if (!password) {
1104
- throw new SshError('AUTH_FAILED', `No password is stored for ${authority}. Add credentials in the SSH Tunnel tab.`);
1235
+ throw new SshError(
1236
+ 'AUTH_FAILED',
1237
+ `No password is stored for ${authority}. Enter it in the add-workspace dialog (it stays on this machine) or in the SSH Tunnel tab.`,
1238
+ );
1105
1239
  }
1106
1240
  return { username, password };
1107
1241
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-linked-workspace",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "description": "Linked local ⇄ remote workspaces and remote workspaces for DeepSeek Harness: theme-aware split editor, file-type icons, and agent tools that edit remote files directly.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -71,7 +71,7 @@
71
71
  },
72
72
  "scripts": {
73
73
  "build": "node scripts/build-client.mjs",
74
- "test": "node --test test/linked.test.mjs test/parts.test.mjs test/git.test.mjs test/file-creation.test.mjs && node test/client-smoke.mjs",
74
+ "test": "node --test test/linked.test.mjs test/parts.test.mjs test/git.test.mjs test/file-creation.test.mjs && node test/ssh-credentials.test.mjs && node test/client-smoke.mjs",
75
75
  "prepack": "node scripts/build-client.mjs"
76
76
  },
77
77
  "repository": {