@ethanfly/sshx 1.2.1 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +37 -2
  2. package/dist/cli/connect.d.ts.map +1 -1
  3. package/dist/cli/connect.js +15 -10
  4. package/dist/cli/connect.js.map +1 -1
  5. package/dist/cli/host.d.ts +3 -3
  6. package/dist/cli/host.d.ts.map +1 -1
  7. package/dist/cli/host.js +87 -54
  8. package/dist/cli/host.js.map +1 -1
  9. package/dist/cli/keygen.d.ts.map +1 -1
  10. package/dist/cli/keygen.js +18 -6
  11. package/dist/cli/keygen.js.map +1 -1
  12. package/dist/cli/tunnel.d.ts.map +1 -1
  13. package/dist/cli/tunnel.js +54 -39
  14. package/dist/cli/tunnel.js.map +1 -1
  15. package/dist/core/client.d.ts +8 -6
  16. package/dist/core/client.d.ts.map +1 -1
  17. package/dist/core/client.js +122 -74
  18. package/dist/core/client.js.map +1 -1
  19. package/dist/core/config.d.ts +77 -25
  20. package/dist/core/config.d.ts.map +1 -1
  21. package/dist/core/config.js +308 -217
  22. package/dist/core/config.js.map +1 -1
  23. package/dist/core/exec.d.ts.map +1 -1
  24. package/dist/core/exec.js +12 -3
  25. package/dist/core/exec.js.map +1 -1
  26. package/dist/core/keygen.d.ts.map +1 -1
  27. package/dist/core/keygen.js +31 -22
  28. package/dist/core/keygen.js.map +1 -1
  29. package/dist/core/known-hosts.d.ts +1 -0
  30. package/dist/core/known-hosts.d.ts.map +1 -1
  31. package/dist/core/known-hosts.js +45 -57
  32. package/dist/core/known-hosts.js.map +1 -1
  33. package/dist/core/metrics.d.ts.map +1 -1
  34. package/dist/core/metrics.js +13 -8
  35. package/dist/core/metrics.js.map +1 -1
  36. package/dist/core/sftp.d.ts.map +1 -1
  37. package/dist/core/sftp.js +25 -6
  38. package/dist/core/sftp.js.map +1 -1
  39. package/dist/core/split-session.d.ts +4 -1
  40. package/dist/core/split-session.d.ts.map +1 -1
  41. package/dist/core/split-session.js +42 -24
  42. package/dist/core/split-session.js.map +1 -1
  43. package/dist/core/tunnel.d.ts.map +1 -1
  44. package/dist/core/tunnel.js +9 -21
  45. package/dist/core/tunnel.js.map +1 -1
  46. package/dist/skill/tools.d.ts +21 -4
  47. package/dist/skill/tools.d.ts.map +1 -1
  48. package/dist/skill/tools.js.map +1 -1
  49. package/dist/sync/crypto.d.ts +7 -0
  50. package/dist/sync/crypto.d.ts.map +1 -1
  51. package/dist/sync/crypto.js +77 -36
  52. package/dist/sync/crypto.js.map +1 -1
  53. package/dist/sync/manager.d.ts.map +1 -1
  54. package/dist/sync/manager.js +54 -19
  55. package/dist/sync/manager.js.map +1 -1
  56. package/dist/sync/provider.d.ts +6 -2
  57. package/dist/sync/provider.d.ts.map +1 -1
  58. package/dist/sync/provider.js +75 -38
  59. package/dist/sync/provider.js.map +1 -1
  60. package/dist/tui/app.d.ts +2 -2
  61. package/dist/tui/app.d.ts.map +1 -1
  62. package/dist/tui/app.js +24 -24
  63. package/dist/tui/app.js.map +1 -1
  64. package/dist/tui/sidebar.d.ts +1 -1
  65. package/dist/tui/sidebar.d.ts.map +1 -1
  66. package/dist/tui/sidebar.js +8 -3
  67. package/dist/tui/sidebar.js.map +1 -1
  68. package/package.json +5 -2
@@ -1,6 +1,106 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import os from 'node:os';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { z } from 'zod';
6
+ const hostProfileSchema = z.object({
7
+ id: z.string().min(1),
8
+ name: z.string().trim().min(1),
9
+ host: z.string().min(1),
10
+ port: z.union([z.number(), z.string().regex(/^\d+$/).transform(Number)])
11
+ .pipe(z.number().int().min(1).max(65535)),
12
+ username: z.string().min(1),
13
+ authType: z.enum(['password', 'privateKey', 'agent', 'keyboard-interactive', 'key'])
14
+ .transform(authType => authType === 'key' ? 'privateKey' : authType),
15
+ password: z.string().optional(),
16
+ privateKeyPath: z.string().optional(),
17
+ privateKey: z.string().optional(),
18
+ passphrase: z.string().optional(),
19
+ proxyJump: z.string().optional(),
20
+ proxyCommand: z.string().optional(),
21
+ keepaliveInterval: z.number().optional(),
22
+ keepaliveCountMax: z.number().optional(),
23
+ readyTimeout: z.number().optional(),
24
+ tags: z.array(z.string()).optional(),
25
+ group: z.string().optional(),
26
+ environment: z.record(z.string(), z.string()).optional(),
27
+ lastConnected: z.string().optional(),
28
+ favorite: z.boolean().optional(),
29
+ notes: z.string().optional()
30
+ });
31
+ const importedHostSchema = hostProfileSchema.partial({ id: true, port: true, username: true, authType: true });
32
+ const hostListSchema = z.array(hostProfileSchema);
33
+ const importedHostListSchema = z.array(importedHostSchema);
34
+ const appConfigSchema = z.object({
35
+ defaultPort: z.number().int().min(1).max(65535),
36
+ defaultUsername: z.string(),
37
+ defaultKeyPath: z.string().optional(),
38
+ strictHostKeyChecking: z.enum(['yes', 'no', 'accept-new']),
39
+ theme: z.enum(['dark', 'light', 'dracula', 'nord', 'catppuccin']),
40
+ terminalFontSize: z.number().positive(),
41
+ terminalFontFamily: z.string(),
42
+ recentHostsLimit: z.number().int().nonnegative()
43
+ });
44
+ export class DuplicateHostError extends Error {
45
+ constructor(name) {
46
+ super(`Host "${name}" already exists.`);
47
+ this.name = 'DuplicateHostError';
48
+ }
49
+ }
50
+ function hostNameKey(name) {
51
+ return name.trim().toLowerCase();
52
+ }
53
+ function requireUniqueHosts(hosts) {
54
+ const ids = new Set();
55
+ const names = new Set();
56
+ for (const host of hosts) {
57
+ const name = hostNameKey(host.name);
58
+ if (ids.has(host.id) || names.has(name)) {
59
+ throw new Error('Saved host profiles contain duplicate names or IDs. Rename or remove the duplicates before continuing.');
60
+ }
61
+ ids.add(host.id);
62
+ names.add(name);
63
+ }
64
+ }
65
+ function mergeHostProfile(profile, existing) {
66
+ const endpointChanged = existing && (profile.host !== existing.host ||
67
+ (profile.port ?? existing.port) !== existing.port || (profile.username ?? existing.username) !== existing.username);
68
+ const inherited = {
69
+ ...existing,
70
+ ...(endpointChanged ? {
71
+ authType: undefined,
72
+ password: undefined,
73
+ privateKeyPath: undefined,
74
+ privateKey: undefined,
75
+ passphrase: undefined,
76
+ proxyJump: undefined,
77
+ proxyCommand: undefined
78
+ } : {})
79
+ };
80
+ if (existing && !endpointChanged) {
81
+ const newPath = profile.privateKeyPath;
82
+ const oldPath = existing.privateKeyPath;
83
+ const pathChanged = newPath !== undefined && toPortablePath(newPath) !== toPortablePath(oldPath ?? '');
84
+ if (pathChanged && profile.privateKey === undefined)
85
+ inherited.privateKey = undefined;
86
+ const inlineKey = profile.privateKey ?? inherited.privateKey;
87
+ if (inlineKey !== existing.privateKey || (pathChanged && !inlineKey))
88
+ inherited.passphrase = undefined;
89
+ }
90
+ const normalized = hostProfileSchema.parse({
91
+ port: 22,
92
+ username: 'root',
93
+ tags: [],
94
+ ...inherited,
95
+ ...Object.fromEntries(Object.entries(profile).filter(([, value]) => value !== undefined)),
96
+ id: existing?.id ?? profile.id ?? `host_${randomUUID()}`,
97
+ authType: profile.authType ?? inherited.authType ?? (profile.privateKeyPath || profile.privateKey ? 'privateKey' : 'password')
98
+ });
99
+ if (normalized.privateKeyPath) {
100
+ normalized.privateKeyPath = toPortablePath(normalized.privateKeyPath);
101
+ }
102
+ return normalized;
103
+ }
4
104
  export class ConfigManager {
5
105
  configDir;
6
106
  hostsFilePath;
@@ -74,79 +174,93 @@ export class ConfigManager {
74
174
  }
75
175
  getAppConfig() {
76
176
  this.ensureDirs();
77
- if (!fs.existsSync(this.configFilePath)) {
78
- const def = this.getDefaultAppConfig();
79
- try {
80
- fs.writeFileSync(this.configFilePath, JSON.stringify(def, null, 2), { mode: 0o600 });
81
- }
82
- catch {
83
- // ignore
177
+ let raw;
178
+ try {
179
+ raw = fs.readFileSync(this.configFilePath, 'utf8');
180
+ }
181
+ catch (error) {
182
+ if (error.code !== 'ENOENT') {
183
+ throw new Error(`Could not read app configuration '${this.configFilePath}': ${error.message}`);
84
184
  }
85
- return def;
185
+ const defaults = this.getDefaultAppConfig();
186
+ this.saveAppConfig(defaults);
187
+ return defaults;
86
188
  }
189
+ let parsed;
87
190
  try {
88
- const raw = fs.readFileSync(this.configFilePath, 'utf8');
89
- return { ...this.getDefaultAppConfig(), ...JSON.parse(raw) };
191
+ parsed = JSON.parse(raw);
90
192
  }
91
193
  catch {
92
- return this.getDefaultAppConfig();
194
+ throw new Error(`Invalid JSON in app configuration '${this.configFilePath}'.`);
195
+ }
196
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
197
+ throw new Error(`Invalid app configuration '${this.configFilePath}' (at root).`);
93
198
  }
199
+ const result = appConfigSchema.safeParse({ ...this.getDefaultAppConfig(), ...parsed });
200
+ if (!result.success) {
201
+ const location = result.error.issues[0].path.join('.') || 'root';
202
+ throw new Error(`Invalid app configuration '${this.configFilePath}' (at ${location}).`);
203
+ }
204
+ return result.data;
94
205
  }
95
206
  saveAppConfig(config) {
207
+ const current = fs.existsSync(this.configFilePath) ? this.getAppConfig() : this.getDefaultAppConfig();
208
+ const updated = appConfigSchema.parse({ ...current, ...config });
96
209
  this.ensureDirs();
97
- let current;
98
- try {
99
- if (fs.existsSync(this.configFilePath)) {
100
- const raw = fs.readFileSync(this.configFilePath, 'utf8');
101
- current = { ...this.getDefaultAppConfig(), ...JSON.parse(raw) };
102
- }
103
- else {
104
- current = this.getDefaultAppConfig();
105
- }
106
- }
107
- catch {
108
- current = this.getDefaultAppConfig();
109
- }
110
- const updated = { ...current, ...config };
111
- fs.writeFileSync(this.configFilePath, JSON.stringify(updated, null, 2), {
112
- mode: 0o600
113
- });
210
+ writePrivateFile(this.configFilePath, JSON.stringify(updated, null, 2));
114
211
  return updated;
115
212
  }
116
- getHosts() {
213
+ getHosts(options = {}) {
117
214
  this.ensureDirs();
118
- if (!fs.existsSync(this.hostsFilePath)) {
119
- return [];
215
+ let raw;
216
+ try {
217
+ raw = fs.readFileSync(this.hostsFilePath, 'utf8');
218
+ }
219
+ catch (error) {
220
+ if (error.code === 'ENOENT') {
221
+ if (!options.requireExisting)
222
+ return [];
223
+ throw new Error(`No saved hosts file at '${this.hostsFilePath}'. Run 'sshx sync pull' first if restoring a remote backup.`);
224
+ }
225
+ throw new Error(`Could not read hosts file '${this.hostsFilePath}': ${error.message}`);
120
226
  }
227
+ let parsed;
121
228
  try {
122
- const raw = fs.readFileSync(this.hostsFilePath, 'utf8');
123
- const hosts = JSON.parse(raw);
124
- return Array.isArray(hosts) ? hosts : [];
229
+ parsed = JSON.parse(raw);
125
230
  }
126
231
  catch {
127
- return [];
232
+ throw new Error(`Invalid JSON in hosts file '${this.hostsFilePath}'.`);
233
+ }
234
+ const result = hostListSchema.safeParse(parsed);
235
+ if (!result.success) {
236
+ const location = result.error.issues[0].path.join('.') || 'root';
237
+ throw new Error(`Invalid host profiles in '${this.hostsFilePath}' (at ${location}).`);
128
238
  }
239
+ return result.data;
129
240
  }
130
241
  saveHosts(hosts) {
131
242
  this.ensureDirs();
132
- fs.writeFileSync(this.hostsFilePath, JSON.stringify(hosts, null, 2), {
133
- mode: 0o600
134
- });
243
+ const data = JSON.stringify(hostListSchema.parse(hosts), null, 2);
244
+ writePrivateFile(this.hostsFilePath, data);
135
245
  }
136
246
  getHost(idOrName) {
137
247
  const hosts = this.getHosts();
138
- const query = idOrName.trim().toLowerCase();
248
+ const query = hostNameKey(idOrName);
139
249
  // 1. Exact match by ID
140
250
  const byId = hosts.find(h => h.id === idOrName);
141
251
  if (byId)
142
252
  return byId;
143
253
  // 2. Exact match by Name (case-insensitive)
144
- const byName = hosts.find(h => h.name.toLowerCase() === query);
254
+ const byName = hosts.find(h => hostNameKey(h.name) === query);
145
255
  if (byName)
146
256
  return byName;
147
257
  // 3. Match by Host (case-insensitive)
148
258
  return hosts.find(h => h.host.toLowerCase() === query);
149
259
  }
260
+ getHostByName(name) {
261
+ const query = hostNameKey(name);
262
+ return this.getHosts().find(host => hostNameKey(host.name) === query);
263
+ }
150
264
  resolveKeyPath(keyPath) {
151
265
  if (!keyPath)
152
266
  return undefined;
@@ -210,17 +324,16 @@ export class ConfigManager {
210
324
  scored.sort((a, b) => a.score - b.score);
211
325
  return scored.slice(0, limit).map(s => s.host);
212
326
  }
213
- addHost(profile) {
327
+ addHost(profile, options = {}) {
214
328
  const hosts = this.getHosts();
215
- const newHost = {
216
- ...profile,
217
- id: profile.id || `host_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`,
218
- port: profile.port !== undefined ? Number(profile.port) : 22,
219
- authType: profile.authType || (profile.privateKeyPath || profile.privateKey ? 'privateKey' : 'password'),
220
- privateKeyPath: profile.privateKeyPath ? toPortablePath(profile.privateKeyPath) : undefined,
221
- tags: profile.tags || []
222
- };
223
- const existingIndex = hosts.findIndex(h => h.id === newHost.id || h.name.toLowerCase() === newHost.name.toLowerCase());
329
+ const profileName = hostNameKey(profile.name);
330
+ const byId = hosts.findIndex(host => host.id === profile.id);
331
+ const byName = hosts.findIndex(host => hostNameKey(host.name) === profileName);
332
+ const existingIndex = byId >= 0 ? byId : byName;
333
+ if (existingIndex >= 0 && (!options.overwrite || (byId >= 0 && byName >= 0 && byId !== byName))) {
334
+ throw new DuplicateHostError(profile.name);
335
+ }
336
+ const newHost = mergeHostProfile(profile, hosts[existingIndex]);
224
337
  if (existingIndex >= 0) {
225
338
  hosts[existingIndex] = newHost;
226
339
  }
@@ -232,26 +345,40 @@ export class ConfigManager {
232
345
  }
233
346
  updateHost(idOrName, updates) {
234
347
  const hosts = this.getHosts();
235
- const index = hosts.findIndex(h => h.id === idOrName || h.name.toLowerCase() === idOrName.toLowerCase());
348
+ const byId = hosts.findIndex(host => host.id === idOrName);
349
+ const index = byId >= 0 ? byId : hosts.findIndex(host => hostNameKey(host.name) === hostNameKey(idOrName));
236
350
  if (index === -1)
237
351
  return null;
238
- const normalizedUpdates = { ...updates };
239
- if (normalizedUpdates.port !== undefined) {
240
- normalizedUpdates.port = Number(normalizedUpdates.port);
352
+ const current = hosts[index];
353
+ const updated = hostProfileSchema.parse({
354
+ ...current,
355
+ ...updates,
356
+ id: current.id,
357
+ name: updates.name ?? current.name,
358
+ host: updates.host ?? current.host,
359
+ port: updates.port ?? current.port,
360
+ username: updates.username ?? current.username,
361
+ authType: updates.authType ?? current.authType
362
+ });
363
+ if (hostNameKey(updated.name) !== hostNameKey(current.name) &&
364
+ hosts.some(host => hostNameKey(host.name) === hostNameKey(updated.name))) {
365
+ throw new DuplicateHostError(updated.name);
241
366
  }
242
- if (normalizedUpdates.privateKeyPath) {
243
- normalizedUpdates.privateKeyPath = toPortablePath(normalizedUpdates.privateKeyPath);
367
+ if (updated.privateKeyPath) {
368
+ updated.privateKeyPath = toPortablePath(updated.privateKeyPath);
244
369
  }
245
- hosts[index] = { ...hosts[index], ...normalizedUpdates };
370
+ hosts[index] = updated;
246
371
  this.saveHosts(hosts);
247
- return hosts[index];
372
+ return updated;
248
373
  }
249
374
  deleteHost(idOrName) {
250
375
  const hosts = this.getHosts();
251
- const filtered = hosts.filter(h => h.id !== idOrName && h.name.toLowerCase() !== idOrName.toLowerCase());
252
- if (filtered.length === hosts.length)
376
+ const byId = hosts.findIndex(host => host.id === idOrName);
377
+ const index = byId >= 0 ? byId : hosts.findIndex(host => hostNameKey(host.name) === hostNameKey(idOrName));
378
+ if (index === -1)
253
379
  return false;
254
- this.saveHosts(filtered);
380
+ hosts.splice(index, 1);
381
+ this.saveHosts(hosts);
255
382
  return true;
256
383
  }
257
384
  recordConnection(idOrName) {
@@ -263,64 +390,69 @@ export class ConfigManager {
263
390
  * Export all host profiles to a portable JSON file or string
264
391
  */
265
392
  exportHosts(exportPath) {
266
- const hosts = this.getHosts();
267
- // Ensure all privateKeyPaths are stored as portable paths
268
- const portableHosts = hosts.map(h => ({
269
- ...h,
270
- privateKeyPath: h.privateKeyPath ? toPortablePath(h.privateKeyPath) : undefined
271
- }));
272
- const jsonStr = JSON.stringify(portableHosts, null, 2);
393
+ const { json } = this.exportHostSnapshot();
273
394
  if (exportPath) {
274
395
  const resolved = resolvePortablePath(exportPath);
275
396
  const dir = path.dirname(resolved);
276
397
  if (!fs.existsSync(dir))
277
398
  fs.mkdirSync(dir, { recursive: true });
278
- fs.writeFileSync(resolved, jsonStr, { mode: 0o600 });
399
+ fs.writeFileSync(resolved, json, { mode: 0o600 });
279
400
  }
280
- return jsonStr;
401
+ return json;
402
+ }
403
+ exportHostSnapshot(options = {}) {
404
+ const hosts = this.getHosts(options);
405
+ requireUniqueHosts(hosts);
406
+ const portableHosts = hosts.map(host => ({
407
+ ...host,
408
+ privateKeyPath: host.privateKeyPath ? toPortablePath(host.privateKeyPath) : undefined
409
+ }));
410
+ return { json: JSON.stringify(portableHosts, null, 2), count: hosts.length };
281
411
  }
282
412
  /**
283
413
  * Import host profiles from a JSON string directly
284
414
  */
285
415
  importHostsFromJson(content, mode = 'merge') {
286
416
  const parsed = JSON.parse(content);
287
- if (!Array.isArray(parsed)) {
288
- throw new Error(`Invalid configuration format: expected an array of host profiles.`);
289
- }
290
- let existing = mode === 'overwrite' ? [] : this.getHosts();
291
- let imported = 0;
417
+ const incoming = importedHostListSchema.parse(parsed);
418
+ const existing = mode === 'overwrite' ? [] : this.getHosts();
419
+ requireUniqueHosts(existing);
420
+ const hostsById = new Map(existing.map(profile => [profile.id, profile]));
421
+ const hostsByName = new Map(existing.map(profile => [hostNameKey(profile.name), profile]));
422
+ const mappedIds = new Map();
423
+ const changedIds = new Set();
424
+ const changedNames = new Set();
292
425
  let updated = 0;
293
- for (const raw of parsed) {
294
- if (!raw.name || !raw.host)
295
- continue;
296
- const profile = {
297
- id: raw.id || `host_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`,
298
- name: raw.name,
299
- host: raw.host,
300
- port: raw.port || 22,
301
- username: raw.username || 'root',
302
- authType: raw.authType || 'password',
303
- password: raw.password,
304
- privateKeyPath: raw.privateKeyPath ? toPortablePath(raw.privateKeyPath) : undefined,
305
- tags: Array.isArray(raw.tags) ? raw.tags : [],
306
- notes: raw.notes,
307
- proxyJump: raw.proxyJump,
308
- proxyCommand: raw.proxyCommand,
309
- lastConnected: raw.lastConnected,
310
- favorite: raw.favorite
311
- };
312
- const matchIdx = existing.findIndex(e => e.id === profile.id || e.name.toLowerCase() === profile.name.toLowerCase());
313
- if (matchIdx >= 0) {
314
- existing[matchIdx] = { ...existing[matchIdx], ...profile };
315
- updated++;
426
+ const changes = incoming.map(profile => {
427
+ const name = hostNameKey(profile.name);
428
+ const byId = profile.id === undefined ? undefined : hostsById.get(profile.id);
429
+ const byName = hostsByName.get(name);
430
+ if (byId && byName && byId !== byName) {
431
+ throw new DuplicateHostError(profile.name);
316
432
  }
317
- else {
318
- existing.push(profile);
319
- imported++;
433
+ const current = byId ?? byName;
434
+ const merged = mergeHostProfile(profile, current);
435
+ if (changedIds.has(merged.id) || changedNames.has(name) || (profile.id !== undefined && mappedIds.has(profile.id))) {
436
+ throw new DuplicateHostError(profile.name);
320
437
  }
321
- }
322
- this.saveHosts(existing);
323
- return { imported, updated, total: existing.length };
438
+ changedIds.add(merged.id);
439
+ changedNames.add(name);
440
+ if (profile.id !== undefined)
441
+ mappedIds.set(profile.id, merged.id);
442
+ if (current)
443
+ updated++;
444
+ return merged;
445
+ });
446
+ changes.forEach((profile, index) => {
447
+ const incomingJump = incoming[index].proxyJump;
448
+ if (incomingJump !== undefined) {
449
+ profile.proxyJump = mappedIds.get(incomingJump) ?? incomingJump;
450
+ }
451
+ hostsById.set(profile.id, profile);
452
+ });
453
+ const hosts = [...hostsById.values()];
454
+ this.saveHosts(hosts);
455
+ return { imported: changes.length - updated, updated, total: hosts.length };
324
456
  }
325
457
  /**
326
458
  * Import host profiles from a portable JSON file
@@ -343,22 +475,41 @@ export class ConfigManager {
343
475
  }
344
476
  const imported = parseOpenSSHConfigFile(targetPath);
345
477
  const existing = this.getHosts();
478
+ const names = new Set(existing.map(profile => hostNameKey(profile.name)));
346
479
  const result = [];
347
480
  for (const item of imported) {
348
- const match = existing.find(e => e.name.toLowerCase() === item.name.toLowerCase());
349
- if (match) {
350
- const updated = { ...match, ...item, id: match.id };
351
- this.updateHost(match.id, updated);
352
- result.push(updated);
353
- }
354
- else {
355
- const added = this.addHost(item);
356
- result.push(added);
357
- }
481
+ const name = hostNameKey(item.name);
482
+ if (names.has(name))
483
+ continue;
484
+ result.push(mergeHostProfile(item));
485
+ names.add(name);
358
486
  }
487
+ if (result.length > 0)
488
+ this.saveHosts([...existing, ...result]);
359
489
  return result;
360
490
  }
361
491
  }
492
+ export function writePrivateFile(filePath, content) {
493
+ const temporary = `${filePath}.${randomUUID()}.tmp`;
494
+ const descriptor = fs.openSync(temporary, 'wx', 0o600);
495
+ try {
496
+ try {
497
+ fs.writeFileSync(descriptor, content);
498
+ fs.fsyncSync(descriptor);
499
+ }
500
+ finally {
501
+ fs.closeSync(descriptor);
502
+ }
503
+ fs.renameSync(temporary, filePath);
504
+ }
505
+ catch (error) {
506
+ try {
507
+ fs.unlinkSync(temporary);
508
+ }
509
+ catch { }
510
+ throw error;
511
+ }
512
+ }
362
513
  /**
363
514
  * Resolves portable paths (~, environment variables, relative paths) to absolute paths on the local OS
364
515
  */
@@ -422,20 +573,19 @@ export function toPortablePath(filePath, baseDir) {
422
573
  * Compute edit distance between two strings for typo suggestions
423
574
  */
424
575
  export function calculateLevenshteinDistance(a, b) {
425
- const m = a.length;
426
- const n = b.length;
427
- const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
428
- for (let i = 0; i <= m; i++)
429
- dp[i][0] = i;
430
- for (let j = 0; j <= n; j++)
431
- dp[0][j] = j;
432
- for (let i = 1; i <= m; i++) {
433
- for (let j = 1; j <= n; j++) {
434
- const cost = a[i - 1] === b[j - 1] ? 0 : 1;
435
- dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost);
436
- }
437
- }
438
- return dp[m][n];
576
+ if (a.length < b.length)
577
+ [a, b] = [b, a];
578
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
579
+ let current = new Array(b.length + 1);
580
+ for (let row = 1; row <= a.length; row++) {
581
+ current[0] = row;
582
+ for (let column = 1; column <= b.length; column++) {
583
+ const cost = a[row - 1] === b[column - 1] ? 0 : 1;
584
+ current[column] = Math.min(previous[column] + 1, current[column - 1] + 1, previous[column - 1] + cost);
585
+ }
586
+ [previous, current] = [current, previous];
587
+ }
588
+ return previous[b.length];
439
589
  }
440
590
  /**
441
591
  * Parses OpenSSH config file resolving Include directives
@@ -448,100 +598,33 @@ export function parseOpenSSHConfigFile(filePath, visited = new Set()) {
448
598
  visited.add(resolvedPath);
449
599
  const baseDir = path.dirname(resolvedPath);
450
600
  const content = fs.readFileSync(resolvedPath, 'utf8');
451
- const lines = content.split('\n');
452
- const hosts = [];
453
- let currentHost = null;
454
- for (let line of lines) {
455
- line = line.trim();
456
- if (!line || line.startsWith('#'))
457
- continue;
458
- const parts = line.split(/\s+/);
459
- const keyword = parts[0].toLowerCase();
460
- const value = parts.slice(1).join(' ').replace(/^["']|["']$/g, '');
461
- if (keyword === 'include') {
462
- // Handle Include wildcard (e.g. config.d/*) or direct files
463
- const includePattern = value.startsWith('/') || value.startsWith('~')
464
- ? resolvePortablePath(value)
465
- : path.resolve(baseDir, value);
466
- const includeDir = path.dirname(includePattern);
467
- const filePattern = path.basename(includePattern);
468
- if (fs.existsSync(includeDir)) {
469
- try {
470
- const entries = fs.readdirSync(includeDir);
471
- const regex = new RegExp('^' + filePattern.replace(/\./g, '\\.').replace(/\*/g, '.*') + '$');
472
- for (const entry of entries) {
473
- if (regex.test(entry)) {
474
- const fullEntryPath = path.join(includeDir, entry);
475
- if (fs.statSync(fullEntryPath).isFile()) {
476
- const nestedHosts = parseOpenSSHConfigFile(fullEntryPath, visited);
477
- hosts.push(...nestedHosts);
478
- }
479
- }
480
- }
481
- }
482
- catch {
483
- // ignore read errors
484
- }
485
- }
486
- continue;
487
- }
488
- if (keyword === 'host') {
489
- if (currentHost && currentHost.name && currentHost.name !== '*') {
490
- finalizeHost(currentHost, hosts);
491
- }
492
- currentHost = {
493
- name: value,
494
- host: value,
495
- port: 22,
496
- username: os.userInfo().username || 'root',
497
- authType: 'privateKey',
498
- tags: ['imported-ssh-config']
499
- };
500
- }
501
- else if (currentHost) {
502
- switch (keyword) {
503
- case 'hostname':
504
- currentHost.host = value;
505
- break;
506
- case 'user':
507
- currentHost.username = value;
508
- break;
509
- case 'port':
510
- currentHost.port = parseInt(value, 10) || 22;
511
- break;
512
- case 'identityfile':
513
- currentHost.privateKeyPath = toPortablePath(value);
514
- currentHost.authType = 'privateKey';
515
- break;
516
- case 'preferredauthentications':
517
- if (value.toLowerCase().startsWith('password')) {
518
- currentHost.authType = 'password';
519
- }
520
- break;
521
- case 'proxyjump':
522
- currentHost.proxyJump = value;
523
- break;
524
- case 'proxycommand':
525
- currentHost.proxyCommand = value;
526
- break;
527
- case 'serveraliveinterval':
528
- currentHost.keepaliveInterval = (parseInt(value, 10) || 15) * 1000;
529
- break;
530
- case 'serveralivecountmax':
531
- currentHost.keepaliveCountMax = parseInt(value, 10) || 3;
532
- break;
533
- }
601
+ return parseOpenSSHConfigContents(content, value => {
602
+ const includePattern = value.startsWith('/') || value.startsWith('~')
603
+ ? resolvePortablePath(value)
604
+ : path.resolve(baseDir, value);
605
+ const includeDir = path.dirname(includePattern);
606
+ const filePattern = path.basename(includePattern);
607
+ if (!fs.existsSync(includeDir))
608
+ return [];
609
+ const regex = new RegExp(`^${filePattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')}$`);
610
+ const hosts = [];
611
+ for (const entry of fs.readdirSync(includeDir).sort()) {
612
+ if (!regex.test(entry))
613
+ continue;
614
+ const fullPath = path.join(includeDir, entry);
615
+ if (fs.statSync(fullPath).isFile())
616
+ hosts.push(...parseOpenSSHConfigFile(fullPath, visited));
534
617
  }
535
- }
536
- if (currentHost && currentHost.name && currentHost.name !== '*') {
537
- finalizeHost(currentHost, hosts);
538
- }
539
- return hosts;
618
+ return hosts;
619
+ });
540
620
  }
541
621
  /**
542
622
  * Parses OpenSSH ~/.ssh/config format string
543
623
  */
544
624
  export function parseOpenSSHConfig(content) {
625
+ return parseOpenSSHConfigContents(content);
626
+ }
627
+ function parseOpenSSHConfigContents(content, include) {
545
628
  const lines = content.split('\n');
546
629
  const hosts = [];
547
630
  let currentHost = null;
@@ -552,7 +635,11 @@ export function parseOpenSSHConfig(content) {
552
635
  const parts = line.split(/\s+/);
553
636
  const keyword = parts[0].toLowerCase();
554
637
  const value = parts.slice(1).join(' ').replace(/^["']|["']$/g, '');
555
- if (keyword === 'host') {
638
+ if (keyword === 'include') {
639
+ if (include)
640
+ hosts.push(...include(value));
641
+ }
642
+ else if (keyword === 'host') {
556
643
  if (currentHost && currentHost.name && currentHost.name !== '*') {
557
644
  finalizeHost(currentHost, hosts);
558
645
  }
@@ -580,6 +667,10 @@ export function parseOpenSSHConfig(content) {
580
667
  currentHost.privateKeyPath = toPortablePath(value);
581
668
  currentHost.authType = 'privateKey';
582
669
  break;
670
+ case 'preferredauthentications':
671
+ if (value.toLowerCase().startsWith('password'))
672
+ currentHost.authType = 'password';
673
+ break;
583
674
  case 'proxyjump':
584
675
  currentHost.proxyJump = value;
585
676
  break;