envcraft-cli 0.0.0-stage → 1.0.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.
@@ -0,0 +1,360 @@
1
+ import { exec } from 'child_process';
2
+ import { promisify } from 'util';
3
+ import { SecureEncryption } from './encryption.js';
4
+ import { resolveVmSettings } from '../config.js';
5
+
6
+ const execAsync = promisify(exec);
7
+
8
+ /**
9
+ * SSH-based file storage for encrypted secrets
10
+ *
11
+ * Stores encrypted database file on remote server via SSH
12
+ *
13
+ * Setup:
14
+ * Settings come from `envman config set vm.host|vm.user|vm.key`, or override with:
15
+ * export SSH_HOST="<your-server>"
16
+ * export SSH_USER="<user>"
17
+ * export SSH_KEY="~/.ssh/id_rsa"
18
+ * export REMOTE_DB_PATH="~/env-secrets.json"
19
+ */
20
+ export class SSHFileDB {
21
+ constructor(encryptionKey, sshConfig = {}) {
22
+ if (!encryptionKey) {
23
+ throw new Error('Encryption key is required');
24
+ }
25
+
26
+ this.encryption = new SecureEncryption(encryptionKey);
27
+
28
+ // SSH Configuration: explicit options > SSH_* env vars > `envman config` settings
29
+ const vm = resolveVmSettings({
30
+ host: sshConfig.host || process.env.SSH_HOST,
31
+ user: sshConfig.user || process.env.SSH_USER,
32
+ keyPath: sshConfig.keyPath || process.env.SSH_KEY,
33
+ });
34
+ this.ssh = {
35
+ host: vm.host,
36
+ user: vm.user,
37
+ keyPath: vm.keyPath,
38
+ port: sshConfig.port || process.env.SSH_PORT || 22,
39
+ remoteDbPath: sshConfig.remoteDbPath || process.env.REMOTE_DB_PATH || '~/env-secrets.json'
40
+ };
41
+
42
+ // Local cache
43
+ this.localCache = { secrets: {}, logs: [] };
44
+ this.cacheValid = false;
45
+ }
46
+
47
+ /**
48
+ * Build SSH command
49
+ */
50
+ _sshCmd(remoteCommand) {
51
+ return `ssh -i ${this.ssh.keyPath} -p ${this.ssh.port} ${this.ssh.user}@${this.ssh.host} "${remoteCommand}"`;
52
+ }
53
+
54
+ /**
55
+ * Initialize - test SSH connection
56
+ */
57
+ async init() {
58
+ try {
59
+ await this._testSSHConnection();
60
+ await this._ensureRemoteFileExists();
61
+ await this._loadFromRemote();
62
+ console.log('✓ SSH file database initialized');
63
+ } catch (error) {
64
+ throw new Error(`SSH init failed: ${error.message}`);
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Test SSH connection
70
+ */
71
+ async _testSSHConnection() {
72
+ const cmd = this._sshCmd('echo OK');
73
+ try {
74
+ const { stdout } = await execAsync(cmd, { timeout: 10000 });
75
+ if (!stdout.includes('OK')) {
76
+ throw new Error('SSH connection test failed');
77
+ }
78
+ } catch (error) {
79
+ throw new Error(`SSH connection failed: ${error.message}`);
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Ensure remote file exists
85
+ */
86
+ async _ensureRemoteFileExists() {
87
+ const initCmd = `test -f ${this.ssh.remoteDbPath} || echo '{"secrets":{},"logs":[]}' > ${this.ssh.remoteDbPath}`;
88
+ const cmd = this._sshCmd(initCmd);
89
+
90
+ try {
91
+ await execAsync(cmd, { timeout: 10000 });
92
+ } catch (error) {
93
+ throw new Error(`Failed to ensure remote file: ${error.message}`);
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Load database from remote server
99
+ */
100
+ async _loadFromRemote() {
101
+ const cmd = this._sshCmd(`cat ${this.ssh.remoteDbPath}`);
102
+
103
+ try {
104
+ const { stdout } = await execAsync(cmd, { timeout: 10000 });
105
+ this.localCache = JSON.parse(stdout);
106
+ this.cacheValid = true;
107
+ } catch (error) {
108
+ throw new Error(`Failed to load from remote: ${error.message}`);
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Save database to remote server
114
+ */
115
+ async _saveToRemote() {
116
+ if (!this.localCache) {
117
+ throw new Error('Database not initialized');
118
+ }
119
+
120
+ const jsonData = JSON.stringify(this.localCache, null, 2);
121
+
122
+ // Use heredoc to safely pass data with special characters
123
+ const cmd = `ssh -i ${this.ssh.keyPath} -p ${this.ssh.port} ${this.ssh.user}@${this.ssh.host} 'cat > ${this.ssh.remoteDbPath} << 'EOF'\n${jsonData}\nEOF'`;
124
+
125
+ try {
126
+ await execAsync(cmd, { timeout: 10000 });
127
+ this.cacheValid = true;
128
+ } catch (error) {
129
+ throw new Error(`Failed to save to remote: ${error.message}`);
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Set a secret value
135
+ */
136
+ async set(key, value, createdBy = 'unknown', description = '') {
137
+ try {
138
+ await this._loadFromRemote();
139
+
140
+ const encryptedValue = this.encryption.encrypt(value);
141
+ const valueHash = SecureEncryption.hash(value);
142
+
143
+ if (!this.localCache.secrets) {
144
+ this.localCache.secrets = {};
145
+ }
146
+
147
+ this.localCache.secrets[key] = {
148
+ key,
149
+ encrypted_value: encryptedValue,
150
+ value_hash: valueHash,
151
+ created_at: new Date().toISOString(),
152
+ updated_at: new Date().toISOString(),
153
+ created_by: createdBy,
154
+ description
155
+ };
156
+
157
+ await this._saveToRemote();
158
+ return key;
159
+ } catch (error) {
160
+ throw new Error(`Failed to set secret: ${error.message}`);
161
+ }
162
+ }
163
+
164
+ /**
165
+ * Get and decrypt a secret value
166
+ */
167
+ async get(key, user = 'unknown') {
168
+ try {
169
+ await this._loadFromRemote();
170
+
171
+ if (!this.localCache.secrets || !this.localCache.secrets[key]) {
172
+ return null;
173
+ }
174
+
175
+ const secretData = this.localCache.secrets[key];
176
+ const decrypted = this.encryption.decrypt(secretData.encrypted_value);
177
+
178
+ // Log access
179
+ this._logAccess(key, 'READ', user);
180
+ await this._saveToRemote();
181
+
182
+ return decrypted;
183
+ } catch (error) {
184
+ throw new Error(`Failed to get secret: ${error.message}`);
185
+ }
186
+ }
187
+
188
+ /**
189
+ * List all secret keys
190
+ */
191
+ async listKeys() {
192
+ try {
193
+ await this._loadFromRemote();
194
+
195
+ if (!this.localCache.secrets) {
196
+ return [];
197
+ }
198
+
199
+ return Object.values(this.localCache.secrets).map(s => ({
200
+ key: s.key,
201
+ created_at: s.created_at,
202
+ updated_at: s.updated_at,
203
+ created_by: s.created_by,
204
+ description: s.description
205
+ }));
206
+ } catch (error) {
207
+ throw new Error(`Failed to list keys: ${error.message}`);
208
+ }
209
+ }
210
+
211
+ /**
212
+ * Delete a secret
213
+ */
214
+ async delete(key, user = 'unknown') {
215
+ try {
216
+ await this._loadFromRemote();
217
+
218
+ if (!this.localCache.secrets || !this.localCache.secrets[key]) {
219
+ return false;
220
+ }
221
+
222
+ delete this.localCache.secrets[key];
223
+ this._logAccess(key, 'DELETE', user);
224
+ await this._saveToRemote();
225
+
226
+ return true;
227
+ } catch (error) {
228
+ throw new Error(`Failed to delete secret: ${error.message}`);
229
+ }
230
+ }
231
+
232
+ /**
233
+ * Verify secret integrity
234
+ */
235
+ async verify(key, value) {
236
+ try {
237
+ await this._loadFromRemote();
238
+
239
+ if (!this.localCache.secrets || !this.localCache.secrets[key]) {
240
+ return false;
241
+ }
242
+
243
+ const valueHash = this.localCache.secrets[key].value_hash;
244
+ return SecureEncryption.verify(value, valueHash);
245
+ } catch (error) {
246
+ throw new Error(`Failed to verify secret: ${error.message}`);
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Get access logs for a specific secret
252
+ */
253
+ async getAccessLogs(key, limit = 50) {
254
+ try {
255
+ await this._loadFromRemote();
256
+
257
+ if (!this.localCache.logs) {
258
+ return [];
259
+ }
260
+
261
+ return this.localCache.logs
262
+ .filter(log => log.secret_id === key)
263
+ .sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
264
+ .slice(0, limit);
265
+ } catch (error) {
266
+ throw new Error(`Failed to get logs: ${error.message}`);
267
+ }
268
+ }
269
+
270
+ /**
271
+ * Get all access logs
272
+ */
273
+ async getAllAccessLogs(limit = 100) {
274
+ try {
275
+ await this._loadFromRemote();
276
+
277
+ if (!this.localCache.logs) {
278
+ return [];
279
+ }
280
+
281
+ return this.localCache.logs
282
+ .sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
283
+ .slice(0, limit);
284
+ } catch (error) {
285
+ throw new Error(`Failed to get all logs: ${error.message}`);
286
+ }
287
+ }
288
+
289
+ /**
290
+ * Export to encrypted file
291
+ */
292
+ async exportToFile(exportKey) {
293
+ try {
294
+ await this._loadFromRemote();
295
+
296
+ const secrets = {};
297
+ for (const [key, data] of Object.entries(this.localCache.secrets || {})) {
298
+ const decrypted = this.encryption.decrypt(data.encrypted_value);
299
+ secrets[key] = decrypted;
300
+ }
301
+
302
+ const exportEncryption = new SecureEncryption(exportKey);
303
+ const encryptedExport = exportEncryption.encrypt(JSON.stringify(secrets));
304
+
305
+ return { secrets, encryptedExport };
306
+ } catch (error) {
307
+ throw new Error(`Failed to export: ${error.message}`);
308
+ }
309
+ }
310
+
311
+ /**
312
+ * Import from encrypted file
313
+ */
314
+ async importFromFile(encryptedData, exportKey, importedBy = 'unknown') {
315
+ try {
316
+ const exportEncryption = new SecureEncryption(exportKey);
317
+ const decrypted = exportEncryption.decrypt(encryptedData);
318
+ const secrets = JSON.parse(decrypted);
319
+
320
+ let count = 0;
321
+ for (const [key, value] of Object.entries(secrets)) {
322
+ await this.set(key, value, importedBy, 'Imported');
323
+ count++;
324
+ }
325
+
326
+ return count;
327
+ } catch (error) {
328
+ throw new Error(`Failed to import: ${error.message}`);
329
+ }
330
+ }
331
+
332
+ /**
333
+ * Internal: Log access
334
+ */
335
+ _logAccess(secretId, action, user, ipAddress = null) {
336
+ if (!this.localCache.logs) {
337
+ this.localCache.logs = [];
338
+ }
339
+
340
+ this.localCache.logs.push({
341
+ secret_id: secretId,
342
+ action,
343
+ user,
344
+ timestamp: new Date().toISOString(),
345
+ ip_address: ipAddress
346
+ });
347
+ }
348
+
349
+ /**
350
+ * Health check
351
+ */
352
+ async health() {
353
+ try {
354
+ await this._testSSHConnection();
355
+ return { status: 'healthy', database: 'SSH File' };
356
+ } catch (error) {
357
+ return { status: 'error', error: error.message };
358
+ }
359
+ }
360
+ }
package/src/tui.js ADDED
@@ -0,0 +1,130 @@
1
+ #!/usr/bin/env node
2
+
3
+ import readline from 'node:readline';
4
+ import { CONFIG_PATH, listSettings, setSetting, unsetSetting } from './config.js';
5
+
6
+ const ESC = '\x1b[';
7
+ const c = {
8
+ reset: `${ESC}0m`,
9
+ bold: `${ESC}1m`,
10
+ dim: `${ESC}2m`,
11
+ cyan: `${ESC}36m`,
12
+ green: `${ESC}32m`,
13
+ yellow: `${ESC}33m`,
14
+ };
15
+
16
+ const HINTS = {
17
+ 'vm.host': 'Server IP or hostname',
18
+ 'vm.user': 'SSH user (default: local username)',
19
+ 'vm.key': 'Path to SSH private key',
20
+ 'vm.env-path': 'Remote env file path (default: ~/.env)',
21
+ };
22
+
23
+ let selected = 0;
24
+ let items = [];
25
+ let message = '';
26
+
27
+ function refresh() {
28
+ items = listSettings();
29
+ if (selected >= items.length) selected = items.length - 1;
30
+ }
31
+
32
+ function render() {
33
+ const lines = [];
34
+ lines.push(`${c.bold}envman settings${c.reset} ${c.dim}${CONFIG_PATH}${c.reset}`);
35
+ lines.push('');
36
+ items.forEach((item, i) => {
37
+ const marker = i === selected ? `${c.cyan}›${c.reset}` : ' ';
38
+ const name = i === selected ? `${c.bold}${item.name.padEnd(14)}${c.reset}` : item.name.padEnd(14);
39
+ const value = item.value === undefined
40
+ ? `${c.dim}(not set)${c.reset}`
41
+ : `${c.green}${item.value}${c.reset}`;
42
+ lines.push(` ${marker} ${name} ${value}`);
43
+ lines.push(` ${c.dim}${HINTS[item.name]}${c.reset}`);
44
+ });
45
+ lines.push('');
46
+ lines.push(`${c.dim}↑/↓ move enter edit d unset q quit${c.reset}`);
47
+ if (message) lines.push(`${c.yellow}${message}${c.reset}`);
48
+
49
+ process.stdout.write(`${ESC}2J${ESC}H${lines.join('\n')}\n`);
50
+ }
51
+
52
+ function ask(question, initial = '') {
53
+ return new Promise((resolve) => {
54
+ process.stdin.setRawMode(false);
55
+ process.stdin.pause();
56
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
57
+ rl.question(question, (answer) => {
58
+ rl.close();
59
+ resolve(answer.trim());
60
+ });
61
+ rl.write(initial);
62
+ });
63
+ }
64
+
65
+ async function edit() {
66
+ const item = items[selected];
67
+ const current = item.value ?? '';
68
+ const answer = await ask(`${c.cyan}${item.name}${c.reset} > `, current);
69
+ if (answer === '') {
70
+ message = 'Empty value ignored. Use "d" to unset.';
71
+ } else if (answer !== current) {
72
+ setSetting(item.name, answer);
73
+ message = `Saved ${item.name}`;
74
+ } else {
75
+ message = 'No change';
76
+ }
77
+ refresh();
78
+ }
79
+
80
+ function unset() {
81
+ const item = items[selected];
82
+ if (item.value === undefined) {
83
+ message = `${item.name} is already unset`;
84
+ return;
85
+ }
86
+ unsetSetting(item.name);
87
+ message = `Unset ${item.name}`;
88
+ refresh();
89
+ }
90
+
91
+ function exit(code = 0) {
92
+ process.stdout.write(`${ESC}?25h\n`);
93
+ if (process.stdin.isTTY) process.stdin.setRawMode(false);
94
+ process.exit(code);
95
+ }
96
+
97
+ async function onKey(str, key = {}) {
98
+ if (key.ctrl && key.name === 'c') return exit(0);
99
+ if (key.name === 'q' || key.name === 'escape') return exit(0);
100
+
101
+ message = '';
102
+ if (key.name === 'up') selected = (selected - 1 + items.length) % items.length;
103
+ else if (key.name === 'down') selected = (selected + 1) % items.length;
104
+ else if (key.name === 'd') unset();
105
+ else if (key.name === 'return') {
106
+ process.stdin.removeListener('keypress', onKey);
107
+ await edit();
108
+ process.stdin.setRawMode(true);
109
+ process.stdin.resume();
110
+ process.stdin.on('keypress', onKey);
111
+ }
112
+ render();
113
+ }
114
+
115
+ function main() {
116
+ if (!process.stdin.isTTY) {
117
+ console.error('envman setting needs an interactive terminal.');
118
+ process.exit(1);
119
+ }
120
+
121
+ refresh();
122
+ readline.emitKeypressEvents(process.stdin);
123
+ process.stdin.setRawMode(true);
124
+ process.stdin.resume();
125
+ process.stdout.write(`${ESC}?25l`);
126
+ process.stdin.on('keypress', onKey);
127
+ render();
128
+ }
129
+
130
+ main();
@@ -0,0 +1,78 @@
1
+ // Color codes for terminal output
2
+ const colors = {
3
+ reset: '\x1b[0m',
4
+ red: '\x1b[31m',
5
+ green: '\x1b[32m',
6
+ yellow: '\x1b[33m',
7
+ blue: '\x1b[34m',
8
+ cyan: '\x1b[36m',
9
+ gray: '\x1b[90m'
10
+ };
11
+
12
+ export function logError(message) {
13
+ console.error(`${colors.red}✖ ${message}${colors.reset}`);
14
+ }
15
+
16
+ export function logSuccess(message) {
17
+ console.log(`${colors.green}✓ ${message}${colors.reset}`);
18
+ }
19
+
20
+ export function logInfo(message) {
21
+ console.log(`${colors.blue}ℹ ${message}${colors.reset}`);
22
+ }
23
+
24
+ export function logWarning(message) {
25
+ console.log(`${colors.yellow}⚠ ${message}${colors.reset}`);
26
+ }
27
+
28
+ export function table(vars) {
29
+ if (Object.keys(vars).length === 0) {
30
+ console.log('No variables found');
31
+ return;
32
+ }
33
+
34
+ // Calculate column widths
35
+ const keys = Object.keys(vars);
36
+ const maxKeyLength = Math.max(...keys.map(k => k.length), 'KEY'.length);
37
+ const maxValueLength = Math.max(...Object.values(vars).map(v => String(v).length), 'VALUE'.length);
38
+
39
+ // Print header
40
+ const keyHeader = 'KEY'.padEnd(maxKeyLength);
41
+ const valueHeader = 'VALUE'.padEnd(maxValueLength);
42
+ console.log(`${colors.cyan}${keyHeader} ${valueHeader}${colors.reset}`);
43
+ console.log(`${'-'.repeat(maxKeyLength)} ${'-'.repeat(maxValueLength)}`);
44
+
45
+ // Print rows
46
+ for (const [key, value] of Object.entries(vars)) {
47
+ const paddedKey = key.padEnd(maxKeyLength);
48
+ const paddedValue = String(value).padEnd(maxValueLength);
49
+ console.log(`${paddedKey} ${paddedValue}`);
50
+ }
51
+ }
52
+
53
+ // Table like table(), but each section is printed under its comment heading
54
+ export function sectionTable(sections) {
55
+ const all = sections.flatMap((section) => section.vars);
56
+ if (all.length === 0) {
57
+ console.log('No variables found');
58
+ return;
59
+ }
60
+
61
+ // Use one width for every section so the columns line up
62
+ const maxKeyLength = Math.max(...all.map(v => v.key.length), 'KEY'.length);
63
+ const maxValueLength = Math.max(...all.map(v => v.value.length), 'VALUE'.length);
64
+
65
+ const keyHeader = 'KEY'.padEnd(maxKeyLength);
66
+ const valueHeader = 'VALUE'.padEnd(maxValueLength);
67
+ console.log(`${colors.cyan}${keyHeader} ${valueHeader}${colors.reset}`);
68
+ console.log(`${'-'.repeat(maxKeyLength)} ${'-'.repeat(maxValueLength)}`);
69
+
70
+ for (const section of sections) {
71
+ if (section.vars.length === 0) continue;
72
+ console.log('');
73
+ if (section.title) console.log(`${colors.gray}# ${section.title}${colors.reset}`);
74
+ for (const { key, value } of section.vars) {
75
+ console.log(`${key.padEnd(maxKeyLength)} ${value.padEnd(maxValueLength)}`);
76
+ }
77
+ }
78
+ }
@@ -0,0 +1,45 @@
1
+ // Parse command-line arguments
2
+ export function parseArgs(argv) {
3
+ const args = {
4
+ command: null,
5
+ params: [],
6
+ options: {}
7
+ };
8
+
9
+ let i = 0;
10
+ while (i < argv.length) {
11
+ const arg = argv[i];
12
+
13
+ if (arg.startsWith('--')) {
14
+ // Long flag
15
+ const key = arg.slice(2);
16
+ if (argv[i + 1] && !argv[i + 1].startsWith('-')) {
17
+ args.options[key] = argv[i + 1];
18
+ i += 2;
19
+ } else {
20
+ args.options[key] = true;
21
+ i += 1;
22
+ }
23
+ } else if (arg.startsWith('-') && arg !== '-') {
24
+ // Short flag
25
+ const key = arg.slice(1);
26
+ if (argv[i + 1] && !argv[i + 1].startsWith('-')) {
27
+ args.options[key] = argv[i + 1];
28
+ i += 2;
29
+ } else {
30
+ args.options[key] = true;
31
+ i += 1;
32
+ }
33
+ } else {
34
+ // Positional argument
35
+ if (!args.command) {
36
+ args.command = arg;
37
+ } else {
38
+ args.params.push(arg);
39
+ }
40
+ i += 1;
41
+ }
42
+ }
43
+
44
+ return args;
45
+ }
package/src/vm.js ADDED
@@ -0,0 +1,49 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { mkdir, writeFile, chmod } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { resolveVmSettings } from './config.js';
6
+
7
+ /**
8
+ * Run ssh with an argument array (no shell), resolving with stdout.
9
+ */
10
+ function sshCat(settings, remote) {
11
+ return new Promise((resolve, reject) => {
12
+ const args = [
13
+ '-i', settings.keyPath,
14
+ '-o', 'BatchMode=yes',
15
+ '-o', 'ConnectTimeout=15',
16
+ `${settings.user}@${settings.host}`,
17
+ 'cat', remote,
18
+ ];
19
+ const child = spawn('ssh', args, { stdio: ['ignore', 'pipe', 'pipe'] });
20
+ const chunks = [];
21
+ let stderr = '';
22
+ child.stdout.on('data', (chunk) => chunks.push(chunk));
23
+ child.stderr.on('data', (chunk) => { stderr += chunk; });
24
+ child.on('error', reject);
25
+ child.on('close', (code) => {
26
+ if (code === 0) resolve(Buffer.concat(chunks).toString('utf8'));
27
+ else reject(new Error(`ssh exited with code ${code}: ${stderr.trim()}`));
28
+ });
29
+ });
30
+ }
31
+
32
+ /**
33
+ * Download the remote env file over SSH and save it locally (mode 0600).
34
+ * Returns the settings used and the path written.
35
+ */
36
+ export async function fetchVmEnv(outFile) {
37
+ const settings = resolveVmSettings();
38
+ const target = outFile
39
+ ? path.resolve(outFile)
40
+ : path.join(homedir(), '.config', 'envman', 'vm.env');
41
+
42
+ const content = await sshCat(settings, settings.envPath);
43
+
44
+ await mkdir(path.dirname(target), { recursive: true, mode: 0o700 });
45
+ await writeFile(target, content, { mode: 0o600 });
46
+ await chmod(target, 0o600);
47
+
48
+ return { settings, file: target };
49
+ }