mcp-ssh-manager 3.8.7 → 4.0.1
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/.eslintignore +5 -0
- package/.gitattributes +5 -0
- package/CHANGELOG.md +371 -6
- package/CLAUDE.md +6 -0
- package/CODE_OF_CONDUCT.md +18 -0
- package/CONTRIBUTING.md +30 -0
- package/Formula/ssh-manager.rb +60 -0
- package/README.md +484 -964
- package/ROADMAP-V4.md +451 -0
- package/brand/README.md +43 -0
- package/brand/icon.svg +32 -0
- package/brand/mark.svg +18 -0
- package/brand/wordmark.svg +30 -0
- package/cli/app.js +230 -0
- package/cli/control.js +116 -0
- package/cli/lib/colors.sh +15 -0
- package/cli/lib/menu.sh +145 -96
- package/cli/portability.js +186 -0
- package/cli/ssh-manager +197 -91
- package/cli/ssh-manager.js +14 -0
- package/cli/style.js +17 -0
- package/cli/vault.js +411 -0
- package/desktop/ControlPlaneApp.swift +219 -0
- package/desktop/build.sh +58 -0
- package/desktop/electron/after-pack.cjs +39 -0
- package/desktop/electron/electron-builder.yml +148 -0
- package/desktop/electron/finalize-artifacts.mjs +83 -0
- package/desktop/electron/main.js +815 -0
- package/desktop/electron/package-lock.json +3656 -0
- package/desktop/electron/package.json +30 -0
- package/desktop/electron/prepare-engine.mjs +84 -0
- package/desktop/electron/resources/entitlements.mac.plist +22 -0
- package/desktop/electron/resources/icon.png +0 -0
- package/desktop/electron/resources/trayTemplate.png +0 -0
- package/desktop/electron/resources/trayTemplate@2x.png +0 -0
- package/desktop/electron/smoke-test.mjs +184 -0
- package/dist/ui/app.css +1 -0
- package/dist/ui/app.js +501 -0
- package/dist/ui/assets/Forum-Regular.woff2 +0 -0
- package/dist/ui/assets/JetBrainsMono-Bold.woff2 +0 -0
- package/dist/ui/assets/JetBrainsMono-Regular.woff2 +0 -0
- package/dist/ui/assets/Karla-Variable.woff2 +0 -0
- package/dist/ui/index.html +16 -0
- package/docs/DISTRIBUTION.md +136 -0
- package/docs/FINAL-TEST-V4.md +209 -0
- package/docs/MIGRATION.md +334 -0
- package/docs/TESTING-V4.md +119 -0
- package/docs/superpowers/specs/2026-10-08-desktop-from-npm-and-cli-design.md +187 -0
- package/docs/videos/control-plane.mp4 +0 -0
- package/package.json +61 -30
- package/scripts/build-interface.mjs +73 -0
- package/scripts/capture-screenshots.mjs +191 -0
- package/scripts/demo-env.mjs +461 -0
- package/scripts/frame-screenshots.py +176 -0
- package/scripts/macbook-mockup.py +296 -0
- package/scripts/make-tray-icon.py +61 -0
- package/scripts/preview-candidate.mjs +291 -0
- package/scripts/publish-desktop.mjs +46 -0
- package/scripts/record-demo.mjs +229 -0
- package/scripts/release-version.mjs +32 -0
- package/scripts/render-cli-menu.py +157 -0
- package/scripts/requirements-dev.in +12 -0
- package/scripts/requirements-dev.txt +424 -0
- package/scripts/run-ui-regression.mjs +48 -0
- package/scripts/setup-hooks.sh +7 -13
- package/scripts/smoke-desktop.mjs +80 -0
- package/scripts/test-drag-and-drop.mjs +114 -0
- package/scripts/test-first-run.mjs +5 -0
- package/scripts/test-import-ui.mjs +5 -0
- package/scripts/test-preferences-persist.mjs +5 -0
- package/scripts/test-upgrade-from-published.mjs +226 -0
- package/scripts/verify-mac-build.sh +153 -0
- package/scripts/verify-windows-build.ps1 +15 -0
- package/server.json +3 -3
- package/skills/README.md +42 -0
- package/skills/ssh-incident/SKILL.md +55 -0
- package/skills/ssh-operations/SKILL.md +62 -0
- package/skills/ssh-restricted/SKILL.md +57 -0
- package/src/agent-clients.js +482 -0
- package/src/approval.js +291 -0
- package/src/audit.js +11 -1
- package/src/command-log.js +162 -0
- package/src/config-loader.js +119 -4
- package/src/config-paths.js +101 -0
- package/src/control-plane.js +2730 -0
- package/src/desktop-install.js +747 -0
- package/src/index.js +179 -213
- package/src/live-stream.js +261 -0
- package/src/saved-commands.js +150 -0
- package/src/secret-store.js +573 -0
- package/src/server-aliases.js +8 -7
- package/src/server-config-manager.js +33 -7
- package/src/server-export.js +106 -0
- package/src/server-groups.js +82 -21
- package/src/server-import.js +477 -0
- package/src/shell-quote.js +9 -2
- package/src/ssh-connection.js +155 -0
- package/src/ssh-manager.js +186 -13
- package/src/tunnel-manager.js +79 -0
- package/src/vault-recovery.js +206 -0
- package/src/xlsx.js +322 -0
- package/docs/images/social-preview.png +0 -0
- package/docs/images/social-preview@2x.png +0 -0
- package/docs/images/ssh-manager-cli-menu.png +0 -0
|
@@ -0,0 +1,573 @@
|
|
|
1
|
+
// Encrypted local store for server credentials — the v4 vault.
|
|
2
|
+
//
|
|
3
|
+
// Why this exists: until now the only way to give a server a password was to
|
|
4
|
+
// write it in clear text in a .env or TOML file. That file sits in a project
|
|
5
|
+
// directory, gets copied into backups, and shows up in `cat`. Competing MCP SSH
|
|
6
|
+
// servers put credentials in the OS keychain, and it is the last substantive
|
|
7
|
+
// gap we have against them.
|
|
8
|
+
//
|
|
9
|
+
// Design constraints, in order:
|
|
10
|
+
//
|
|
11
|
+
// 1. **Nothing changes for existing users.** The vault is one more source in
|
|
12
|
+
// the loader's chain, consulted only when it exists. No vault, no change.
|
|
13
|
+
// 2. **No new npm dependency.** Encryption uses Node's built-in crypto; the
|
|
14
|
+
// master key lives in the OS keychain, reached through the tools already
|
|
15
|
+
// present on each platform, with a file fallback when there is none.
|
|
16
|
+
// 3. **The engine stays headless.** A GUI can drive this module, but nothing
|
|
17
|
+
// here requires one — the CLI and the MCP server use the same API.
|
|
18
|
+
//
|
|
19
|
+
// The file format is deliberately boring JSON so it can be inspected, backed up
|
|
20
|
+
// and diffed. Only the secret values are ciphertext; hosts, users, ports and
|
|
21
|
+
// modes stay readable, because hiding them buys nothing and makes the file
|
|
22
|
+
// impossible to reason about.
|
|
23
|
+
|
|
24
|
+
import crypto from 'crypto';
|
|
25
|
+
import fs from 'fs';
|
|
26
|
+
import os from 'os';
|
|
27
|
+
import path from 'path';
|
|
28
|
+
import { execFileSync } from 'child_process';
|
|
29
|
+
import { logger } from './logger.js';
|
|
30
|
+
|
|
31
|
+
const VAULT_VERSION = 1;
|
|
32
|
+
const ALGORITHM = 'aes-256-gcm';
|
|
33
|
+
const KEY_BYTES = 32;
|
|
34
|
+
const IV_BYTES = 12;
|
|
35
|
+
|
|
36
|
+
// Keychain coordinates. One service name per platform tool, one account.
|
|
37
|
+
const KEYCHAIN_SERVICE = 'mcp-ssh-manager';
|
|
38
|
+
const KEYCHAIN_ACCOUNT = 'vault-master-key';
|
|
39
|
+
|
|
40
|
+
/** Fields whose values are encrypted rather than stored as-is. */
|
|
41
|
+
export const SECRET_FIELDS = ['password', 'passphrase', 'sudoPassword'];
|
|
42
|
+
|
|
43
|
+
/** Apply a transform to credentials, including those in additional accounts.
|
|
44
|
+
* @param {any} value
|
|
45
|
+
* @param {(secret: any) => any} transform
|
|
46
|
+
* @returns {any}
|
|
47
|
+
*/
|
|
48
|
+
function mapSecrets(value, transform) {
|
|
49
|
+
if (Array.isArray(value)) return value.map(item => mapSecrets(item, transform));
|
|
50
|
+
if (!value || typeof value !== 'object') return value;
|
|
51
|
+
return Object.fromEntries(Object.entries(value).map(([field, item]) => [field,
|
|
52
|
+
SECRET_FIELDS.includes(field) ? transform(item) : mapSecrets(item, transform)]));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** @param {Record<string, any>} servers @returns {any[]} */
|
|
56
|
+
function secretValues(servers) {
|
|
57
|
+
const values = [];
|
|
58
|
+
for (const config of Object.values(servers)) {
|
|
59
|
+
mapSecrets(config, value => { values.push(value); return value; });
|
|
60
|
+
}
|
|
61
|
+
return values;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** A browser receives presence flags, never secrets, including nested accounts.
|
|
65
|
+
* @param {any} value
|
|
66
|
+
* @returns {any}
|
|
67
|
+
*/
|
|
68
|
+
export function publicServerConfig(value) {
|
|
69
|
+
if (Array.isArray(value)) return value.map(publicServerConfig);
|
|
70
|
+
if (!value || typeof value !== 'object') return value;
|
|
71
|
+
return Object.fromEntries(Object.entries(value).map(([field, item]) =>
|
|
72
|
+
SECRET_FIELDS.includes(field)
|
|
73
|
+
? [`has${field[0].toUpperCase()}${field.slice(1)}`, true]
|
|
74
|
+
: [field, publicServerConfig(item)]));
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Default vault location. Kept next to the other per-user state
|
|
79
|
+
* (~/.ssh-manager/) rather than in the project directory, so it is not caught
|
|
80
|
+
* by a `git add .` or copied with the repository.
|
|
81
|
+
* @returns {string} Absolute path to the vault file
|
|
82
|
+
*/
|
|
83
|
+
export function defaultVaultPath() {
|
|
84
|
+
return process.env.SSH_MANAGER_VAULT
|
|
85
|
+
|| path.join(process.env.SSH_MANAGER_HOME || path.join(os.homedir(), '.ssh-manager'), 'vault.json');
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* How long a keychain call may take before it is abandoned.
|
|
90
|
+
*
|
|
91
|
+
* These helpers talk to a user session, and this software mostly runs where
|
|
92
|
+
* there is not one: a server over SSH, a container, a CI runner, a launchd
|
|
93
|
+
* agent. `secret-tool` with no D-Bus to answer it, or `security` raising a
|
|
94
|
+
* modal in a process that has no window, can sit there indefinitely — and the
|
|
95
|
+
* vault read is on the path of every command, so everything sits with it.
|
|
96
|
+
*
|
|
97
|
+
* Five seconds, then give up: the answer after five hours would be the same
|
|
98
|
+
* one, and falling back to the key file is already the supported path.
|
|
99
|
+
*/
|
|
100
|
+
const KEYCHAIN_TIMEOUT_MS = 5000;
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Read the master key from the OS keychain.
|
|
104
|
+
*
|
|
105
|
+
* macOS uses `security`, Linux `secret-tool` (libsecret), both of which ship
|
|
106
|
+
* with the desktop. Windows has no equivalent CLI, so it falls through to the
|
|
107
|
+
* file fallback. Returns null when the platform has no store, the tool is
|
|
108
|
+
* missing, or no key has been stored yet — all normal conditions, not errors.
|
|
109
|
+
*
|
|
110
|
+
* @returns {Buffer|null} The 32-byte key, or null when unavailable
|
|
111
|
+
*/
|
|
112
|
+
function readKeyFromKeychain() {
|
|
113
|
+
try {
|
|
114
|
+
if (process.platform === 'darwin') {
|
|
115
|
+
const out = execFileSync('security', [
|
|
116
|
+
'find-generic-password', '-s', KEYCHAIN_SERVICE, '-a', KEYCHAIN_ACCOUNT, '-w'
|
|
117
|
+
], { stdio: ['ignore', 'pipe', 'ignore'], encoding: 'utf8', timeout: KEYCHAIN_TIMEOUT_MS });
|
|
118
|
+
return Buffer.from(out.trim(), 'base64');
|
|
119
|
+
}
|
|
120
|
+
if (process.platform === 'linux') {
|
|
121
|
+
const out = execFileSync('secret-tool', [
|
|
122
|
+
'lookup', 'service', KEYCHAIN_SERVICE, 'account', KEYCHAIN_ACCOUNT
|
|
123
|
+
], { stdio: ['ignore', 'pipe', 'ignore'], encoding: 'utf8', timeout: KEYCHAIN_TIMEOUT_MS });
|
|
124
|
+
const trimmed = out.trim();
|
|
125
|
+
return trimmed ? Buffer.from(trimmed, 'base64') : null;
|
|
126
|
+
}
|
|
127
|
+
} catch {
|
|
128
|
+
// No entry, no tool, the user declined the prompt, or the deadline passed.
|
|
129
|
+
// All of them mean the same thing here: no key from the keychain.
|
|
130
|
+
}
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Store the master key in the OS keychain.
|
|
136
|
+
* @param {Buffer} key - The key to store
|
|
137
|
+
* @returns {boolean} True when the keychain accepted it
|
|
138
|
+
*/
|
|
139
|
+
function writeKeyToKeychain(key) {
|
|
140
|
+
const encoded = key.toString('base64');
|
|
141
|
+
try {
|
|
142
|
+
if (process.platform === 'darwin') {
|
|
143
|
+
execFileSync('security', [
|
|
144
|
+
'add-generic-password', '-s', KEYCHAIN_SERVICE, '-a', KEYCHAIN_ACCOUNT,
|
|
145
|
+
'-w', encoded, '-U'
|
|
146
|
+
], { stdio: 'ignore', timeout: KEYCHAIN_TIMEOUT_MS });
|
|
147
|
+
return true;
|
|
148
|
+
}
|
|
149
|
+
if (process.platform === 'linux') {
|
|
150
|
+
execFileSync('secret-tool', [
|
|
151
|
+
'store', '--label=MCP SSH Manager vault key',
|
|
152
|
+
'service', KEYCHAIN_SERVICE, 'account', KEYCHAIN_ACCOUNT
|
|
153
|
+
], { input: encoded, stdio: ['pipe', 'ignore', 'ignore'], timeout: KEYCHAIN_TIMEOUT_MS });
|
|
154
|
+
return true;
|
|
155
|
+
}
|
|
156
|
+
} catch {
|
|
157
|
+
// Fall through to the file fallback.
|
|
158
|
+
}
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Path of the fallback key file, used where no OS keychain is reachable.
|
|
164
|
+
* @returns {string} Absolute path
|
|
165
|
+
*/
|
|
166
|
+
function fallbackKeyPath() {
|
|
167
|
+
return path.join(path.dirname(defaultVaultPath()), 'vault.key');
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Resolve the master key, creating one on first use.
|
|
172
|
+
*
|
|
173
|
+
* Prefers the OS keychain. Falls back to a 0600 file, which is weaker — the key
|
|
174
|
+
* then sits next to the data it protects — but still strictly better than the
|
|
175
|
+
* clear-text .env it replaces, and it keeps the vault usable on Windows, in
|
|
176
|
+
* containers and over SSH sessions with no desktop keyring.
|
|
177
|
+
*
|
|
178
|
+
* `minted` says the key did not exist and was created here. The caller needs
|
|
179
|
+
* that: a fresh key against an existing vault means every secret in it is
|
|
180
|
+
* unreadable, and generating one silently is how an operator finds out weeks
|
|
181
|
+
* later, from a failed deploy, that their credentials are gone.
|
|
182
|
+
*
|
|
183
|
+
* @param {{ create?: boolean, replaceInvalidFile?: boolean }} [options]
|
|
184
|
+
* @returns {{ key: Buffer, source: 'keychain'|'file', minted: boolean }}
|
|
185
|
+
*/
|
|
186
|
+
function resolveMasterKey({ create = true, replaceInvalidFile = false } = {}) {
|
|
187
|
+
// SSH_MANAGER_KEY_SOURCE=file skips the OS keychain entirely. Needed wherever
|
|
188
|
+
// there is no desktop session to prompt — CI, containers, a plain SSH login —
|
|
189
|
+
// and it is what makes the vault testable without touching the developer's
|
|
190
|
+
// real keychain.
|
|
191
|
+
const forceFile = process.env.SSH_MANAGER_KEY_SOURCE === 'file';
|
|
192
|
+
|
|
193
|
+
const fromKeychain = forceFile ? null : readKeyFromKeychain();
|
|
194
|
+
if (fromKeychain && fromKeychain.length === KEY_BYTES) {
|
|
195
|
+
return { key: fromKeychain, source: 'keychain', minted: false };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const keyFile = fallbackKeyPath();
|
|
199
|
+
if (fs.existsSync(keyFile)) {
|
|
200
|
+
const key = Buffer.from(fs.readFileSync(keyFile, 'utf8').trim(), 'base64');
|
|
201
|
+
if (key.length === KEY_BYTES) return { key, source: 'file', minted: false };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
if (!create) {
|
|
205
|
+
throw Object.assign(new Error('The vault is encrypted with a key this machine no longer has. '
|
|
206
|
+
+ 'Restore a recovery file or re-import the original configuration. No new key was created.'),
|
|
207
|
+
{ code: 'VAULT_KEY_MISMATCH' });
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// First use: mint a key and try to put it somewhere safe.
|
|
211
|
+
const key = crypto.randomBytes(KEY_BYTES);
|
|
212
|
+
if (!forceFile && writeKeyToKeychain(key)) {
|
|
213
|
+
return { key, source: 'keychain', minted: true };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
fs.mkdirSync(path.dirname(keyFile), { recursive: true, mode: 0o700 });
|
|
217
|
+
try {
|
|
218
|
+
fs.writeFileSync(keyFile, key.toString('base64'), { mode: 0o600, flag: 'wx' });
|
|
219
|
+
} catch (error) {
|
|
220
|
+
if (error.code !== 'EEXIST') throw error;
|
|
221
|
+
const existing = Buffer.from(fs.readFileSync(keyFile, 'utf8').trim(), 'base64');
|
|
222
|
+
if (existing.length === KEY_BYTES) return { key: existing, source: 'file', minted: false };
|
|
223
|
+
if (!replaceInvalidFile) throw new Error(`Invalid vault key file: ${keyFile}`);
|
|
224
|
+
// Only explicit recovery may repair invalid key bytes. Its caller holds
|
|
225
|
+
// the shared key-file lock, and a failed write leaves the old file intact.
|
|
226
|
+
const temporary = `${keyFile}.${crypto.randomUUID()}.tmp`;
|
|
227
|
+
try {
|
|
228
|
+
fs.writeFileSync(temporary, key.toString('base64'), { mode: 0o600, flag: 'wx' });
|
|
229
|
+
fs.renameSync(temporary, keyFile);
|
|
230
|
+
} finally {
|
|
231
|
+
fs.rmSync(temporary, { force: true });
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
logger.warn('Vault key stored in a file: no OS keychain available', { keyFile });
|
|
235
|
+
return { key, source: 'file', minted: true };
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Encrypt one secret value.
|
|
240
|
+
* @param {string} plaintext - Value to encrypt
|
|
241
|
+
* @param {Buffer} key - Master key
|
|
242
|
+
* @returns {string} `v1:<iv>:<tag>:<ciphertext>`, all base64
|
|
243
|
+
*/
|
|
244
|
+
export function encryptValue(plaintext, key) {
|
|
245
|
+
const iv = crypto.randomBytes(IV_BYTES);
|
|
246
|
+
const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
|
|
247
|
+
const ciphertext = Buffer.concat([cipher.update(String(plaintext), 'utf8'), cipher.final()]);
|
|
248
|
+
const tag = cipher.getAuthTag();
|
|
249
|
+
return `v1:${iv.toString('base64')}:${tag.toString('base64')}:${ciphertext.toString('base64')}`;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Decrypt one secret value.
|
|
254
|
+
*
|
|
255
|
+
* GCM authenticates as well as encrypts: a tampered vault throws here rather
|
|
256
|
+
* than silently yielding a wrong password that would then be sent to a server.
|
|
257
|
+
*
|
|
258
|
+
* @param {string} encoded - Value produced by encryptValue
|
|
259
|
+
* @param {Buffer} key - Master key
|
|
260
|
+
* @returns {string} The plaintext
|
|
261
|
+
*/
|
|
262
|
+
export function decryptValue(encoded, key) {
|
|
263
|
+
const parts = String(encoded).split(':');
|
|
264
|
+
if (parts.length !== 4 || parts[0] !== 'v1') {
|
|
265
|
+
throw new Error('Malformed encrypted value');
|
|
266
|
+
}
|
|
267
|
+
const [, iv, tag, ciphertext] = parts;
|
|
268
|
+
const decipher = crypto.createDecipheriv(ALGORITHM, key, Buffer.from(iv, 'base64'));
|
|
269
|
+
decipher.setAuthTag(Buffer.from(tag, 'base64'));
|
|
270
|
+
return Buffer.concat([
|
|
271
|
+
decipher.update(Buffer.from(ciphertext, 'base64')),
|
|
272
|
+
decipher.final()
|
|
273
|
+
]).toString('utf8');
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* An encrypted, file-backed store of server definitions.
|
|
278
|
+
*
|
|
279
|
+
* Every method reads and writes the file immediately: there is no in-memory
|
|
280
|
+
* cache to go stale when the CLI and the MCP server are both running.
|
|
281
|
+
*/
|
|
282
|
+
export class SecretStore {
|
|
283
|
+
/**
|
|
284
|
+
* @param {string} [vaultPath] - Vault file location; defaults to defaultVaultPath()
|
|
285
|
+
*/
|
|
286
|
+
constructor(vaultPath = defaultVaultPath()) {
|
|
287
|
+
this.vaultPath = vaultPath;
|
|
288
|
+
/** @type {Buffer|null} */
|
|
289
|
+
this.key = null;
|
|
290
|
+
/** @type {'keychain'|'file'|null} */
|
|
291
|
+
this.keySource = null;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Whether the vault on disk holds anything encrypted. Read straight from the
|
|
296
|
+
* file rather than through the store, because this runs before a key exists.
|
|
297
|
+
*
|
|
298
|
+
* @returns {boolean}
|
|
299
|
+
*/
|
|
300
|
+
#vaultHoldsSecrets() {
|
|
301
|
+
if (!fs.existsSync(this.vaultPath)) return false;
|
|
302
|
+
try {
|
|
303
|
+
const raw = JSON.parse(fs.readFileSync(this.vaultPath, 'utf8'));
|
|
304
|
+
return secretValues(raw.servers || {}).length > 0;
|
|
305
|
+
} catch {
|
|
306
|
+
// An unreadable vault is a different problem, reported where it is read.
|
|
307
|
+
return false;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* Can this machine's key actually open what is in the vault?
|
|
314
|
+
*
|
|
315
|
+
* Separate from unlock() because the commands that reassure an operator —
|
|
316
|
+
* `vault list`, `vault status` — read the file without ever decrypting a
|
|
317
|
+
* value, and so reported "3 servers, encrypted: password" for a vault whose
|
|
318
|
+
* key was gone. Something that looks like confirmation has to be
|
|
319
|
+
* confirmation.
|
|
320
|
+
*
|
|
321
|
+
* @returns {{ ok: boolean, reason?: string, checked: number }}
|
|
322
|
+
*/
|
|
323
|
+
checkKey() {
|
|
324
|
+
if (!fs.existsSync(this.vaultPath)) return { ok: true, checked: 0 };
|
|
325
|
+
|
|
326
|
+
/** @type {any} */
|
|
327
|
+
let raw;
|
|
328
|
+
try {
|
|
329
|
+
raw = this.read();
|
|
330
|
+
} catch (error) {
|
|
331
|
+
return { ok: false, reason: `The vault file is unreadable: ${error.message}`, checked: 0 };
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const encrypted = secretValues(raw.servers || {});
|
|
335
|
+
if (encrypted.length === 0) return { ok: true, checked: 0 };
|
|
336
|
+
|
|
337
|
+
// GCM authenticates each value separately. One good value says nothing
|
|
338
|
+
// about damage to a later value, or a vault assembled under different keys.
|
|
339
|
+
try {
|
|
340
|
+
this.getAllDecrypted();
|
|
341
|
+
return { ok: true, checked: encrypted.length };
|
|
342
|
+
} catch (error) {
|
|
343
|
+
return {
|
|
344
|
+
ok: false,
|
|
345
|
+
checked: encrypted.length,
|
|
346
|
+
reason: error.message,
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** @returns {boolean} True when a vault file exists on disk */
|
|
352
|
+
exists() {
|
|
353
|
+
return fs.existsSync(this.vaultPath);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Load (or create) the master key. Idempotent.
|
|
358
|
+
*
|
|
359
|
+
* Existing ciphertext requires an existing key that decrypts every value.
|
|
360
|
+
* A missing key never creates a replacement as a side effect of reading:
|
|
361
|
+
* repeated failures must not quietly produce a vault encrypted by two keys.
|
|
362
|
+
* Explicit recovery is the separate operation that can replace lost data.
|
|
363
|
+
*
|
|
364
|
+
* @throws {Error} when the key cannot open the vault that is there
|
|
365
|
+
*/
|
|
366
|
+
unlock() {
|
|
367
|
+
if (this.key) return;
|
|
368
|
+
const { key, source } = resolveMasterKey({ create: !this.#vaultHoldsSecrets() });
|
|
369
|
+
try {
|
|
370
|
+
for (const value of secretValues(this.read().servers)) decryptValue(value, key);
|
|
371
|
+
} catch {
|
|
372
|
+
throw Object.assign(
|
|
373
|
+
new Error(
|
|
374
|
+
`The key cannot decrypt every secret in ${this.vaultPath}.\n`
|
|
375
|
+
+ 'The key is wrong or a stored secret is damaged. Nothing has been overwritten.\n\n'
|
|
376
|
+
+ 'If you have a recovery file: ssh-manager vault restore <file>\n'
|
|
377
|
+
+ 'If the servers are still in a .env: delete the vault and run ssh-manager vault import\n'
|
|
378
|
+
+ `Otherwise the secrets in it are unrecoverable — move ${this.vaultPath} aside and start again.`
|
|
379
|
+
),
|
|
380
|
+
{ code: 'VAULT_KEY_MISMATCH' }
|
|
381
|
+
);
|
|
382
|
+
}
|
|
383
|
+
this.key = key;
|
|
384
|
+
this.keySource = source;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* Read the raw vault file.
|
|
389
|
+
* @returns {{ version: number, servers: Record<string, any> }}
|
|
390
|
+
*/
|
|
391
|
+
read() {
|
|
392
|
+
try {
|
|
393
|
+
const parsed = JSON.parse(fs.readFileSync(this.vaultPath, 'utf8'));
|
|
394
|
+
if (parsed.version !== VAULT_VERSION) {
|
|
395
|
+
throw new Error(`Unsupported vault version ${parsed.version}`);
|
|
396
|
+
}
|
|
397
|
+
if (!parsed.servers || typeof parsed.servers !== 'object' || Array.isArray(parsed.servers)
|
|
398
|
+
|| Object.values(parsed.servers).some(server => !server || typeof server !== 'object' || Array.isArray(server))) {
|
|
399
|
+
throw new Error('Invalid vault server data');
|
|
400
|
+
}
|
|
401
|
+
return parsed;
|
|
402
|
+
} catch (error) {
|
|
403
|
+
if (error.code === 'ENOENT') return { version: VAULT_VERSION, servers: {} };
|
|
404
|
+
throw error;
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Write the vault, owner-readable only.
|
|
410
|
+
* @param {{ version: number, servers: Record<string, any> }} data - Vault contents
|
|
411
|
+
*/
|
|
412
|
+
write(data) {
|
|
413
|
+
fs.mkdirSync(path.dirname(this.vaultPath), { recursive: true, mode: 0o700 });
|
|
414
|
+
const temporary = `${this.vaultPath}.${crypto.randomUUID()}.tmp`;
|
|
415
|
+
try {
|
|
416
|
+
fs.writeFileSync(temporary, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
|
|
417
|
+
fs.renameSync(temporary, this.vaultPath);
|
|
418
|
+
} finally {
|
|
419
|
+
fs.rmSync(temporary, { force: true });
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/** Serialise CLI/desktop writers without exposing partial JSON to readers.
|
|
424
|
+
* @template T
|
|
425
|
+
* @param {() => T} update
|
|
426
|
+
* @param {string} [targetPath]
|
|
427
|
+
* @returns {T}
|
|
428
|
+
*/
|
|
429
|
+
#withWriteLock(update, targetPath = this.vaultPath) {
|
|
430
|
+
fs.mkdirSync(path.dirname(targetPath), { recursive: true, mode: 0o700 });
|
|
431
|
+
const lock = `${targetPath}.lock`;
|
|
432
|
+
let descriptor;
|
|
433
|
+
try {
|
|
434
|
+
descriptor = fs.openSync(lock, 'wx', 0o600);
|
|
435
|
+
} catch (error) {
|
|
436
|
+
if (error.code !== 'EEXIST') throw error;
|
|
437
|
+
// An interrupted writer may leave its lock. Reclaim only when the OS
|
|
438
|
+
// confirms that recorded process is gone, never on an arbitrary timeout.
|
|
439
|
+
try {
|
|
440
|
+
const owner = Number(fs.readFileSync(lock, 'utf8'));
|
|
441
|
+
if (!Number.isSafeInteger(owner) || owner <= 0) throw new Error('Unknown lock owner');
|
|
442
|
+
try { process.kill(owner, 0); } catch (probe) {
|
|
443
|
+
if (probe.code !== 'ESRCH') throw probe;
|
|
444
|
+
fs.rmSync(lock);
|
|
445
|
+
descriptor = fs.openSync(lock, 'wx', 0o600);
|
|
446
|
+
}
|
|
447
|
+
} catch { /* Another writer owns it, or ownership cannot be proved. */ }
|
|
448
|
+
if (descriptor === undefined) throw Object.assign(new Error('The vault is being updated. Try again.'), { code: 'VAULT_BUSY' });
|
|
449
|
+
}
|
|
450
|
+
try {
|
|
451
|
+
fs.writeFileSync(descriptor, String(process.pid));
|
|
452
|
+
return update();
|
|
453
|
+
} finally {
|
|
454
|
+
fs.closeSync(descriptor);
|
|
455
|
+
fs.rmSync(lock, { force: true });
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* Add or replace a server. Secret fields are encrypted; everything else is
|
|
461
|
+
* stored as-is so the file stays readable.
|
|
462
|
+
*
|
|
463
|
+
* @param {string} name - Server name (normalised to lowercase, as elsewhere)
|
|
464
|
+
* @param {Record<string, any>} config - Server config in loader (camelCase) shape
|
|
465
|
+
*/
|
|
466
|
+
setServer(name, config) {
|
|
467
|
+
return this.#withWriteLock(() => {
|
|
468
|
+
// A cached key must not permit an edit to conceal damage that happened
|
|
469
|
+
// since unlocking. Backups and edits are all-or-nothing reads.
|
|
470
|
+
this.getAllDecrypted();
|
|
471
|
+
const data = this.read();
|
|
472
|
+
// A metadata-only vault gives us no ciphertext against which to test a
|
|
473
|
+
// cached key. Resolve it afresh before introducing a credential.
|
|
474
|
+
if (secretValues(data.servers).length === 0) this.key = null;
|
|
475
|
+
if (this.keySource === 'file' && this.key && !fs.existsSync(fallbackKeyPath())) {
|
|
476
|
+
throw Object.assign(new Error('The vault key file is missing. Back up the unlocked vault before restoring it.'),
|
|
477
|
+
{ code: 'VAULT_KEY_MISMATCH' });
|
|
478
|
+
}
|
|
479
|
+
this.unlock();
|
|
480
|
+
/** @type {Record<string, any>} */
|
|
481
|
+
const stored = {};
|
|
482
|
+
for (const [field, value] of Object.entries(config)) {
|
|
483
|
+
if (value === undefined || value === null) continue;
|
|
484
|
+
stored[field] = value;
|
|
485
|
+
}
|
|
486
|
+
Object.defineProperty(data.servers, name.toLowerCase(), { value: mapSecrets(stored,
|
|
487
|
+
value => encryptValue(value, /** @type {Buffer} */ (this.key))), enumerable: true, configurable: true, writable: true });
|
|
488
|
+
this.write(data);
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* Remove a server.
|
|
494
|
+
* @param {string} name - Server name
|
|
495
|
+
* @returns {boolean} True when a server was actually removed
|
|
496
|
+
*/
|
|
497
|
+
removeServer(name) {
|
|
498
|
+
return this.#withWriteLock(() => {
|
|
499
|
+
const data = this.read();
|
|
500
|
+
const key = name.toLowerCase();
|
|
501
|
+
if (!(key in data.servers)) return false;
|
|
502
|
+
delete data.servers[key];
|
|
503
|
+
this.write(data);
|
|
504
|
+
return true;
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/**
|
|
509
|
+
* Server names held in the vault. Does not need the key — listing what exists
|
|
510
|
+
* should not require unlocking anything.
|
|
511
|
+
* @returns {string[]} Sorted names
|
|
512
|
+
*/
|
|
513
|
+
listServers() {
|
|
514
|
+
return Object.keys(this.read().servers).sort();
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/**
|
|
518
|
+
* All servers with their secrets decrypted, in the shape the loader expects.
|
|
519
|
+
* @returns {Record<string, any>} Server configs keyed by lowercase name
|
|
520
|
+
*/
|
|
521
|
+
getAllDecrypted() {
|
|
522
|
+
const data = this.read();
|
|
523
|
+
if (Object.keys(data.servers).length === 0) return {};
|
|
524
|
+
const decrypt = () => Object.fromEntries(Object.entries(data.servers).map(([name, stored]) => [name,
|
|
525
|
+
mapSecrets(stored, value => decryptValue(value, /** @type {Buffer} */ (this.key)))]));
|
|
526
|
+
if (secretValues(data.servers).length === 0) return decrypt();
|
|
527
|
+
const hadCachedKey = this.key !== null;
|
|
528
|
+
this.unlock();
|
|
529
|
+
try {
|
|
530
|
+
return decrypt();
|
|
531
|
+
} catch (error) {
|
|
532
|
+
if (!hadCachedKey) throw error;
|
|
533
|
+
// Another process can restore the same vault under a new key. Retry a
|
|
534
|
+
// stale cached key once, without ever minting a replacement for lost data.
|
|
535
|
+
this.key = null;
|
|
536
|
+
this.unlock();
|
|
537
|
+
return decrypt();
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/** Restore an already decrypted recovery file in one atomic replacement.
|
|
542
|
+
* Unreadable existing data is replaced only after an explicit CLI confirmation.
|
|
543
|
+
* @param {Record<string, any>} servers
|
|
544
|
+
* @param {{ replaceUnreadable?: boolean, expectedRevision?: string }} [options]
|
|
545
|
+
*/
|
|
546
|
+
restoreServers(servers, { replaceUnreadable = false, expectedRevision } = {}) {
|
|
547
|
+
if (!servers || typeof servers !== 'object' || Array.isArray(servers)
|
|
548
|
+
|| Object.values(servers).some(config => !config || typeof config !== 'object' || Array.isArray(config))) {
|
|
549
|
+
throw new Error('Invalid recovery server data');
|
|
550
|
+
}
|
|
551
|
+
return this.#withWriteLock(() => {
|
|
552
|
+
if (expectedRevision !== undefined) {
|
|
553
|
+
let revision = 'missing';
|
|
554
|
+
try { revision = crypto.createHash('sha256').update(fs.readFileSync(this.vaultPath)).digest('hex'); }
|
|
555
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
556
|
+
if (expectedRevision !== revision) throw Object.assign(
|
|
557
|
+
new Error('The vault changed. Preview the recovery file again before restoring.'), { code: 'VAULT_CHANGED' });
|
|
558
|
+
}
|
|
559
|
+
let existing = {};
|
|
560
|
+
try { existing = this.getAllDecrypted(); } catch (error) {
|
|
561
|
+
if (!replaceUnreadable) throw error;
|
|
562
|
+
}
|
|
563
|
+
const { key, source } = this.#withWriteLock(
|
|
564
|
+
() => resolveMasterKey({ replaceInvalidFile: true }), fallbackKeyPath());
|
|
565
|
+
const all = { ...existing, ...servers };
|
|
566
|
+
const encrypted = Object.fromEntries(Object.entries(all).map(([name, config]) => [name.toLowerCase(),
|
|
567
|
+
mapSecrets(config, value => encryptValue(value, key))]));
|
|
568
|
+
this.write({ version: VAULT_VERSION, servers: encrypted });
|
|
569
|
+
this.key = key;
|
|
570
|
+
this.keySource = source;
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
}
|
package/src/server-aliases.js
CHANGED
|
@@ -49,17 +49,18 @@ function saveAliases(aliases) {
|
|
|
49
49
|
export function resolveServerName(nameOrAlias, servers) {
|
|
50
50
|
const aliases = loadAliases();
|
|
51
51
|
|
|
52
|
-
//
|
|
53
|
-
|
|
54
|
-
return aliases[nameOrAlias];
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
// Check if it's a direct server name
|
|
52
|
+
// A canonical name always identifies itself, even if an old alias has the
|
|
53
|
+
// same spelling. Policy checks and connection lookup must agree on identity.
|
|
58
54
|
const normalizedName = nameOrAlias.toLowerCase();
|
|
59
|
-
if (servers
|
|
55
|
+
if (Object.hasOwn(servers, normalizedName)) {
|
|
60
56
|
return normalizedName;
|
|
61
57
|
}
|
|
62
58
|
|
|
59
|
+
if (Object.hasOwn(aliases, nameOrAlias)) {
|
|
60
|
+
const target = String(aliases[nameOrAlias]).toLowerCase();
|
|
61
|
+
return Object.hasOwn(servers, target) ? target : null;
|
|
62
|
+
}
|
|
63
|
+
|
|
63
64
|
// Try to find partial match
|
|
64
65
|
const serverNames = Object.keys(servers);
|
|
65
66
|
const matches = serverNames.filter(name => name.includes(normalizedName));
|
|
@@ -1,13 +1,20 @@
|
|
|
1
1
|
import fs from 'fs';
|
|
2
2
|
import { ConfigLoader } from './config-loader.js';
|
|
3
3
|
import { logger } from './logger.js';
|
|
4
|
+
import os from 'os';
|
|
5
|
+
import path from 'path';
|
|
6
|
+
import { resolveEnvFilePath } from './config-paths.js';
|
|
7
|
+
import { defaultVaultPath } from './secret-store.js';
|
|
4
8
|
|
|
5
9
|
/** @typedef {import('./config-loader.js').ServerConfig} ServerConfig */
|
|
6
10
|
|
|
7
11
|
export class ServerConfigManager {
|
|
8
|
-
constructor({ envPath
|
|
12
|
+
constructor({ envPath = resolveEnvFilePath(),
|
|
13
|
+
tomlPath = process.env.SSH_CONFIG_PATH || path.join(os.homedir(), '.codex', 'ssh-config.toml'),
|
|
14
|
+
vaultPath = defaultVaultPath(), preferToml = false, configLoader = new ConfigLoader() } = {}) {
|
|
9
15
|
this.envPath = envPath;
|
|
10
16
|
this.tomlPath = tomlPath;
|
|
17
|
+
this.vaultPath = vaultPath;
|
|
11
18
|
this.preferToml = preferToml;
|
|
12
19
|
this.configLoader = configLoader;
|
|
13
20
|
/**
|
|
@@ -18,6 +25,8 @@ export class ServerConfigManager {
|
|
|
18
25
|
this.servers = {};
|
|
19
26
|
/** @type {string|null} */
|
|
20
27
|
this.fileSignature = null;
|
|
28
|
+
/** @type {Error|null} Blocks cached configuration after a vault read failure. */
|
|
29
|
+
this.configError = null;
|
|
21
30
|
}
|
|
22
31
|
|
|
23
32
|
/** @returns {Promise<Record<string, ServerConfig>>} */
|
|
@@ -32,6 +41,7 @@ export class ServerConfigManager {
|
|
|
32
41
|
await this.reload();
|
|
33
42
|
}
|
|
34
43
|
|
|
44
|
+
if (this.configError) throw this.configError;
|
|
35
45
|
return this.servers;
|
|
36
46
|
}
|
|
37
47
|
|
|
@@ -48,6 +58,7 @@ export class ServerConfigManager {
|
|
|
48
58
|
const loadedServers = await this.configLoader.load({
|
|
49
59
|
envPath: this.envPath,
|
|
50
60
|
tomlPath: this.tomlPath,
|
|
61
|
+
vaultPath: this.vaultPath,
|
|
51
62
|
preferToml: this.preferToml
|
|
52
63
|
});
|
|
53
64
|
|
|
@@ -58,12 +69,23 @@ export class ServerConfigManager {
|
|
|
58
69
|
}
|
|
59
70
|
|
|
60
71
|
this.servers = nextServers;
|
|
72
|
+
this.configError = null;
|
|
61
73
|
this.fileSignature = this.getFileSignature();
|
|
62
74
|
return this.servers;
|
|
63
75
|
} catch (error) {
|
|
76
|
+
if (error.code === 'VAULT_UNREADABLE') {
|
|
77
|
+
// Do not keep an older permissive snapshot after vault adoption fails.
|
|
78
|
+
// Remember the failure even when the files stay unchanged, and retry
|
|
79
|
+
// automatically after recovery changes the vault or its key.
|
|
80
|
+
this.servers = {};
|
|
81
|
+
this.configError = error;
|
|
82
|
+
this.fileSignature = this.getFileSignature();
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
64
85
|
this.servers = previousServers;
|
|
65
86
|
this.fileSignature = previousSignature;
|
|
66
87
|
logger.error('Failed to reload server configuration', { error: error.message });
|
|
88
|
+
if (this.configError) throw this.configError;
|
|
67
89
|
return this.servers;
|
|
68
90
|
}
|
|
69
91
|
}
|
|
@@ -71,16 +93,20 @@ export class ServerConfigManager {
|
|
|
71
93
|
getFileSignature() {
|
|
72
94
|
return [
|
|
73
95
|
this.getSingleFileSignature(this.tomlPath),
|
|
74
|
-
this.getSingleFileSignature(this.envPath)
|
|
96
|
+
this.getSingleFileSignature(this.envPath),
|
|
97
|
+
this.getSingleFileSignature(this.vaultPath),
|
|
98
|
+
this.getSingleFileSignature(path.join(path.dirname(defaultVaultPath()), 'vault.key'))
|
|
75
99
|
].join('|');
|
|
76
100
|
}
|
|
77
101
|
|
|
78
102
|
getSingleFileSignature(filePath) {
|
|
79
|
-
if (!filePath
|
|
80
|
-
|
|
103
|
+
if (!filePath) return ':missing';
|
|
104
|
+
try {
|
|
105
|
+
const stats = fs.statSync(filePath);
|
|
106
|
+
return `${filePath}:${stats.ino}:${stats.mtimeMs}:${stats.ctimeMs}:${stats.size}`;
|
|
107
|
+
} catch (error) {
|
|
108
|
+
if (error.code === 'ENOENT') return `${filePath}:missing`;
|
|
109
|
+
throw error;
|
|
81
110
|
}
|
|
82
|
-
|
|
83
|
-
const stats = fs.statSync(filePath);
|
|
84
|
-
return `${filePath}:${stats.mtimeMs}:${stats.size}`;
|
|
85
111
|
}
|
|
86
112
|
}
|