depops 0.0.0-stage → 0.2.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/src/cli.js ADDED
@@ -0,0 +1,925 @@
1
+ import * as p from '@clack/prompts';
2
+ import { spawn } from 'node:child_process';
3
+ import { randomBytes } from 'node:crypto';
4
+ import fs from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import { VAULT_FILE, VaultError, findVault, readVault, writeVault, checkPasswordStrength } from './vault.js';
7
+ import { connect, exec, runScript, installPublicKey, generateKeyPair, upload, shQuote as q, scrub } from './ssh.js';
8
+ import { APP_TYPES, presetSteps } from './presets.js';
9
+ import { detectProjects, findCompose, loadCompose, analyze, buildArgv, serverCompose } from './compose.js';
10
+
11
+ // ───────────────────────── helpers ─────────────────────────
12
+
13
+ function guard(v) {
14
+ if (p.isCancel(v)) {
15
+ p.cancel('Cancelled.');
16
+ process.exit(1);
17
+ }
18
+ return v;
19
+ }
20
+
21
+ function fail(msg) {
22
+ p.log.error(msg);
23
+ process.exit(1);
24
+ }
25
+
26
+ const ask = {
27
+ text: async (o) => guard(await p.text(o)),
28
+ secret: async (o) => guard(await p.password({ mask: '•', ...o })),
29
+ confirm: async (o) => guard(await p.confirm(o)),
30
+ select: async (o) => guard(await p.select(o)),
31
+ };
32
+
33
+ const required = (v) => (!v || !String(v).trim() ? 'Required' : undefined);
34
+
35
+ function parseEnv(text) {
36
+ const out = {};
37
+ for (const line of text.split(/\r?\n/)) {
38
+ const m = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
39
+ if (m) out[m[1]] = m[2].trim();
40
+ }
41
+ return out;
42
+ }
43
+
44
+ function unquote(v) {
45
+ const s = String(v);
46
+ if (s.length >= 2 && ((s[0] === '"' && s.at(-1) === '"') || (s[0] === "'" && s.at(-1) === "'"))) return s.slice(1, -1);
47
+ return s;
48
+ }
49
+
50
+ async function newMasterPassword() {
51
+ p.note(
52
+ 'This password encrypts ALL server details in .depops.vault.\n' +
53
+ 'It is never stored anywhere. If you lose it, the vault cannot be recovered.\n' +
54
+ 'Share it with teammates only through a password manager.',
55
+ 'Master password',
56
+ );
57
+ for (;;) {
58
+ const pw = await ask.secret({ message: 'Create master password', validate: (v) => checkPasswordStrength(v || '') ?? undefined });
59
+ const again = await ask.secret({ message: 'Repeat master password' });
60
+ if (pw === again) return pw;
61
+ p.log.warn('Passwords do not match. Try again.');
62
+ }
63
+ }
64
+
65
+ async function unlock() {
66
+ const file = await findVault();
67
+ if (!file) fail(`No ${VAULT_FILE} found. Run \`depops init\` in your project first.`);
68
+ const fromEnv = process.env.DEPOPS_PASSWORD;
69
+ for (let attempt = 1; attempt <= 3; attempt++) {
70
+ const pw = fromEnv ?? (await ask.secret({ message: 'Vault password' }));
71
+ const s = p.spinner();
72
+ s.start('Unlocking vault');
73
+ try {
74
+ const data = normalize(await readVault(file, pw));
75
+ s.stop('Vault unlocked');
76
+ return { file, data, password: pw };
77
+ } catch (e) {
78
+ s.stop('Unlock failed', 1);
79
+ if (!(e instanceof VaultError)) throw e;
80
+ p.log.error(e.message);
81
+ if (fromEnv) process.exit(1);
82
+ }
83
+ }
84
+ fail('Too many failed attempts.');
85
+ }
86
+
87
+ async function save(ctx) {
88
+ const s = p.spinner();
89
+ s.start('Encrypting vault');
90
+ await writeVault(ctx.file, ctx.data, ctx.password);
91
+ s.stop(`Saved ${path.basename(ctx.file)}`);
92
+ }
93
+
94
+ function trustPrompt(fp) {
95
+ p.note(
96
+ `${fp}\n\nCompare this with the server's fingerprint if you can:\n ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub`,
97
+ 'New server host key',
98
+ );
99
+ return ask.confirm({ message: 'Trust this server?', initialValue: true });
100
+ }
101
+
102
+ async function withConnection(data, fn) {
103
+ const s = p.spinner();
104
+ s.start('Connecting to server');
105
+ let conn;
106
+ try {
107
+ conn = await connect(data.server);
108
+ s.stop('Connected');
109
+ } catch (e) {
110
+ s.stop('Connection failed', 1);
111
+ fail(e.message);
112
+ }
113
+ try {
114
+ return await fn(conn);
115
+ } catch (e) {
116
+ fail(scrub(e.message, data.server));
117
+ } finally {
118
+ conn.end();
119
+ }
120
+ }
121
+
122
+ async function editSteps(label, current, hint) {
123
+ p.note(current.length ? current.map((s, i) => `${i + 1}. ${s}`).join('\n') : '(none)', label);
124
+ const action = await ask.select({
125
+ message: `${label}:`,
126
+ options: [
127
+ { value: 'keep', label: 'Keep as is' },
128
+ { value: 'add', label: 'Add steps at the end' },
129
+ { value: 'replace', label: 'Replace all steps' },
130
+ ],
131
+ });
132
+ if (action === 'keep') return current;
133
+ const steps = action === 'add' ? [...current] : [];
134
+ for (;;) {
135
+ const s = await ask.text({ message: `Step ${steps.length + 1} (leave empty to finish)`, placeholder: hint, defaultValue: '' });
136
+ if (!s.trim()) break;
137
+ steps.push(s.trim());
138
+ }
139
+ return steps;
140
+ }
141
+
142
+ // ───────────────────────── server setup ─────────────────────────
143
+
144
+ async function setupServer(existing = {}) {
145
+ const host = (await ask.text({ message: 'Server IP or hostname', initialValue: existing.host, validate: required })).trim();
146
+ const port = Number(await ask.text({ message: 'SSH port', initialValue: String(existing.port ?? 22), validate: (v) => (/^\d+$/.test(v) && +v > 0 && +v < 65536 ? undefined : 'Invalid port') }));
147
+ const username = (await ask.text({ message: 'SSH username', initialValue: existing.username ?? 'root', validate: required })).trim();
148
+ const method = await ask.select({
149
+ message: 'How do you log in?',
150
+ options: [
151
+ { value: 'password-to-key', label: 'Password → auto-create a secure SSH key', hint: 'recommended' },
152
+ { value: 'generate', label: 'Generate a new SSH key — I will add the public key to the server myself' },
153
+ { value: 'key', label: 'Use my existing private key file' },
154
+ { value: 'password', label: 'Password only' },
155
+ { value: 'agent', label: 'SSH agent', hint: 'key stays only on this computer' },
156
+ ],
157
+ });
158
+
159
+ let auth;
160
+ let loginPassword = null;
161
+ if (method === 'password-to-key' || method === 'password') {
162
+ loginPassword = await ask.secret({ message: 'SSH password', validate: required });
163
+ auth = { type: 'password', password: loginPassword };
164
+ } else if (method === 'generate') {
165
+ const kp = generateKeyPair(`depops@${username}`);
166
+ p.note(
167
+ `${kp.publicKey.trim()}\n\nAdd this line to ~/.ssh/authorized_keys of "${username}" on the server\n` +
168
+ '(or paste it in your VPS provider panel under "SSH keys").',
169
+ 'Your new public key',
170
+ );
171
+ auth = { type: 'key', privateKey: kp.privateKey };
172
+ } else if (method === 'key') {
173
+ const keyPath = await ask.text({ message: 'Private key path', placeholder: '~/.ssh/id_ed25519', validate: required });
174
+ const resolved = keyPath.trim().replace(/^~(?=$|[\\/])/, process.env.HOME || process.env.USERPROFILE || '~');
175
+ let privateKey = '';
176
+ try {
177
+ privateKey = await fs.readFile(resolved, 'utf8');
178
+ } catch {}
179
+ if (!/PRIVATE KEY-----/.test(privateKey)) {
180
+ p.log.error('That file is missing or is not a private key (did you pick the .pub file?).');
181
+ return setupServer({ ...existing, host, port, username });
182
+ }
183
+ const passphrase = await ask.secret({ message: 'Key passphrase (empty if none)' });
184
+ auth = { type: 'key', privateKey, ...(passphrase ? { passphrase } : {}) };
185
+ } else {
186
+ auth = { type: 'agent' };
187
+ }
188
+
189
+ const server = { host, port, username, auth };
190
+ let conn;
191
+ for (;;) {
192
+ if (method === 'generate') await ask.confirm({ message: 'Added the public key on the server? Press Enter to test the connection', initialValue: true });
193
+ const s = p.spinner();
194
+ s.start('Checking connection');
195
+ try {
196
+ conn = await connect(server, {
197
+ onNewHostKey: async (fp) => {
198
+ s.stop('Server reached');
199
+ return trustPrompt(fp);
200
+ },
201
+ });
202
+ s.stop('Connected');
203
+ break;
204
+ } catch (e) {
205
+ s.stop('Connection failed', 1);
206
+ p.log.error(scrub(e.message, server));
207
+ const next = await ask.select({
208
+ message: 'What now?',
209
+ options: [
210
+ { value: 'retry', label: 'Try again with the same details' },
211
+ { value: 'change', label: 'Change server / login details' },
212
+ { value: 'quit', label: 'Quit' },
213
+ ],
214
+ });
215
+ if (next === 'quit') fail('Setup cancelled.');
216
+ if (next === 'change') return setupServer({ ...existing, host, port, username });
217
+ }
218
+ }
219
+ server.hostKey = conn.hostKey;
220
+ p.log.success('Logged in — connection verified');
221
+
222
+ if (method === 'password-to-key') {
223
+ const s2 = p.spinner();
224
+ s2.start('Creating ed25519 key and installing it on the server');
225
+ try {
226
+ const kp = generateKeyPair(`depops@${username}`);
227
+ await installPublicKey(conn, kp.publicKey);
228
+ conn.end();
229
+ server.auth = { type: 'key', privateKey: kp.privateKey };
230
+ conn = await connect(server);
231
+ s2.stop('SSH key installed and verified — the vault stores the key, not the password');
232
+ } catch (e) {
233
+ s2.stop('Key setup failed', 1);
234
+ fail(scrub(e.message, server));
235
+ }
236
+ }
237
+
238
+ const sudo = await setupSudo(conn, server, username, loginPassword, existing.sudo);
239
+ conn.end();
240
+ return { server, sudo };
241
+ }
242
+
243
+ async function setupSudo(conn, server, username, loginPassword, existing) {
244
+ const enabled = await ask.confirm({ message: 'Run deploy commands with sudo?', initialValue: existing?.enabled ?? username !== 'root' });
245
+ if (!enabled) return { enabled: false };
246
+ let password = '';
247
+ if (loginPassword && (await ask.confirm({ message: 'Is the sudo password the same as the SSH password?', initialValue: true }))) {
248
+ password = loginPassword;
249
+ } else {
250
+ password = await ask.secret({ message: 'sudo password (empty if NOPASSWD)' });
251
+ }
252
+ const sudo = { enabled: true, ...(password ? { password } : {}) };
253
+ const s = p.spinner();
254
+ s.start('Checking sudo');
255
+ const code = await runScript(conn, 'true', { sudo });
256
+ if (code !== 0) {
257
+ s.stop('sudo check failed', 1);
258
+ fail('sudo did not work with that password.');
259
+ }
260
+ s.stop('sudo works');
261
+ return sudo;
262
+ }
263
+
264
+ // ───────────────────────── projects (deploy targets) ─────────────────────────
265
+
266
+ // Vaults from v0.1 stored one app at the top level; treat it as a single project.
267
+ function normalize(d) {
268
+ if (!d.targets) {
269
+ d.targets = { [d.name || 'app']: { localDir: '.', ...d.app, env: d.env || {} } };
270
+ delete d.app;
271
+ delete d.env;
272
+ delete d.name;
273
+ }
274
+ return d;
275
+ }
276
+
277
+ const names = (d) => Object.keys(d.targets);
278
+ const hasType = (d, type) => Object.values(d.targets || {}).some((t) => t.type === type);
279
+ const usesDocker = (d) => Object.values(d.targets || {}).some((t) => t.type.startsWith('docker'));
280
+
281
+ async function pickTarget(d, flags, message = 'Which project?') {
282
+ const list = names(d);
283
+ if (flags.target) {
284
+ if (!d.targets[flags.target]) fail(`Unknown project "${flags.target}". Projects: ${list.join(', ')}`);
285
+ return flags.target;
286
+ }
287
+ if (list.length === 1) return list[0];
288
+ return ask.select({ message, options: list.map((n) => ({ value: n, label: n, hint: d.targets[n].localDir })) });
289
+ }
290
+
291
+ const validName = (taken) => (v) => {
292
+ if (!/^[A-Za-z0-9._-]+$/.test(v || '')) return 'Use letters, digits, ".", "_" or "-"';
293
+ if (taken.includes(v)) return 'That name is already used';
294
+ };
295
+
296
+ async function askPlatform() {
297
+ return ask.select({
298
+ message: 'Server CPU architecture',
299
+ options: [
300
+ { value: 'linux/amd64', label: 'amd64 / x86_64', hint: 'most VPS' },
301
+ { value: 'linux/arm64', label: 'arm64' },
302
+ { value: 'linux/amd64,linux/arm64', label: 'both' },
303
+ ],
304
+ });
305
+ }
306
+
307
+ async function importEnvFile(file, label) {
308
+ if (!(await fs.stat(file).then((s) => s.isFile(), () => false))) return {};
309
+ if (!(await ask.confirm({ message: `Import ${label} into the vault?`, initialValue: true }))) return {};
310
+ const env = parseEnv(await fs.readFile(file, 'utf8'));
311
+ p.log.success(`Imported ${Object.keys(env).length} variables from ${label}. Keep it out of git (.gitignore).`);
312
+ return env;
313
+ }
314
+
315
+ const localEnvOf = (t) => {
316
+ const env = { ...process.env };
317
+ for (const [k, v] of Object.entries(t.env || {})) env[k] = unquote(v);
318
+ return env;
319
+ };
320
+
321
+ function planNote(name, t) {
322
+ const lines = [`Server folder: ${t.dir}`];
323
+ if (t.type === 'docker-registry') lines.push('On this computer: build every image from the compose file and push it');
324
+ for (const s of t.localSteps) lines.push(`On this computer: ${s}`);
325
+ for (const u of t.uploads) lines.push(`Upload: ${u.from} → ${u.to}`);
326
+ if (t.type === 'docker-registry') lines.push('Send to server: docker-compose.yml (without build:)');
327
+ if (t.envFile && Object.keys(t.env || {}).length) lines.push(`Send to server: ${t.envFile} (${Object.keys(t.env).length} vars, chmod 600)`);
328
+ for (const s of t.remoteSteps) lines.push(`On the server: ${s}`);
329
+ p.note(lines.join('\n'), `Deploy plan — ${name}`);
330
+ }
331
+
332
+ /** A project that has its own docker-compose file. */
333
+ async function setupComposeTarget(root, found, mode, platform, taken) {
334
+ const name = (await ask.text({ message: `Name for "${found.localDir}"`, initialValue: found.name, validate: validName(taken) })).trim();
335
+ const dir = (await ask.text({ message: `Folder on the server for "${name}"`, initialValue: `/var/www/${name}`, validate: required })).trim();
336
+ const projectDir = path.join(root, found.localDir);
337
+ const env = await importEnvFile(path.join(projectDir, '.env'), path.join(found.localDir, '.env'));
338
+ const t = { type: mode, localDir: found.localDir, composeFile: found.composeFile, platform, dir, envFile: '.env', env, uploads: [], ...presetSteps(mode) };
339
+
340
+ if (mode === 'docker-registry') {
341
+ const doc = await loadCompose(path.join(projectDir, found.composeFile));
342
+ const { builds, problems, warnings } = analyze(doc, localEnvOf(t));
343
+ if (builds.length) p.log.info(`Images to build:\n${builds.map((b) => ` ${b.service} → ${b.image}`).join('\n')}`);
344
+ for (const w of warnings) p.log.warn(w);
345
+ if (problems.length) p.log.warn(`Fix these in ${path.join(found.localDir, found.composeFile)} before deploying:\n ${problems.join('\n ')}`);
346
+ }
347
+ planNote(name, t);
348
+ if (!(await ask.confirm({ message: 'Use this plan? (change later with `depops edit`)', initialValue: true }))) {
349
+ t.localSteps = await editSteps('Extra local steps', t.localSteps);
350
+ t.remoteSteps = await editSteps('Server steps', t.remoteSteps);
351
+ }
352
+ return { name, t };
353
+ }
354
+
355
+ /** A project without a compose file (or added by hand): PM2, static, custom, or Docker with a chosen folder. */
356
+ async function setupManualTarget(root, taken) {
357
+ const localDir = (await ask.text({ message: 'Project folder (relative to repo root)', initialValue: '.', validate: required })).trim().replace(/\/+$/, '') || '.';
358
+ const projectDir = path.join(root, localDir);
359
+ if (!(await fs.stat(projectDir).then((s) => s.isDirectory(), () => false))) {
360
+ p.log.error(`Folder not found: ${localDir}`);
361
+ return setupManualTarget(root, taken);
362
+ }
363
+ const fallback = localDir === '.' ? path.basename(path.resolve(root)) : path.basename(localDir);
364
+ const type = await ask.select({ message: 'How is it deployed?', options: APP_TYPES, initialValue: 'docker-registry' });
365
+ if (type.startsWith('docker')) {
366
+ const composeFile = await findCompose(projectDir);
367
+ if (!composeFile) {
368
+ p.log.error(`No docker-compose.yml in ${localDir}. Add one, or pick another deploy type.`);
369
+ return setupManualTarget(root, taken);
370
+ }
371
+ return setupComposeTarget(root, { name: fallback, localDir, composeFile }, type, type === 'docker-registry' ? await askPlatform() : null, taken);
372
+ }
373
+
374
+ const name = (await ask.text({ message: 'Project name', initialValue: taken.includes(fallback) ? '' : fallback, validate: validName(taken) })).trim();
375
+ const dir = (await ask.text({ message: `Folder on the server for "${name}"`, initialValue: type === 'static' ? `/var/www/${name}/html` : `/var/www/${name}`, validate: required })).trim();
376
+ const t = { type, localDir, dir, envFile: '', env: {}, uploads: [], ...presetSteps(type) };
377
+ if (type === 'static') {
378
+ const buildCmd = (await ask.text({ message: 'Local build command (empty for none)', initialValue: 'npm run build', defaultValue: '' })).trim();
379
+ t.localSteps = buildCmd ? [buildCmd] : [];
380
+ t.uploads.push({ from: (await ask.text({ message: 'Folder to upload', initialValue: 'dist', validate: required })).trim(), to: '.' });
381
+ }
382
+ if (type === 'custom') {
383
+ t.localSteps = await editSteps('Local steps (run in the project folder on this computer)', [], 'e.g. npm run build');
384
+ t.remoteSteps = await editSteps('Server steps (run inside the server folder)', [], 'e.g. sudo systemctl restart myapp');
385
+ }
386
+ if (type !== 'static') {
387
+ t.env = await importEnvFile(path.join(projectDir, '.env'), path.join(localDir, '.env'));
388
+ if (Object.keys(t.env).length) t.envFile = '.env';
389
+ }
390
+ planNote(name, t);
391
+ if (type !== 'custom' && !(await ask.confirm({ message: 'Use this plan? (change later with `depops edit`)', initialValue: true }))) {
392
+ t.localSteps = await editSteps('Local steps', t.localSteps);
393
+ t.remoteSteps = await editSteps('Server steps', t.remoteSteps);
394
+ }
395
+ return { name, t };
396
+ }
397
+
398
+ async function setupTargets(root, existing = {}) {
399
+ const targets = {};
400
+ const taken = () => [...Object.keys(existing), ...Object.keys(targets)];
401
+ const known = new Set(Object.values(existing).map((t) => t.localDir));
402
+ const found = (await detectProjects(root)).filter((f) => !known.has(f.localDir));
403
+
404
+ if (found.length) {
405
+ p.note(found.map((f) => `• ${f.name} (${path.join(f.localDir, f.composeFile)})`).join('\n'), `Found ${found.length} Docker Compose project(s)`);
406
+ p.log.info('Recommended: build images on this computer, push them to a registry, and send only docker-compose.yml + .env to the server. No source code ends up on the server.');
407
+ const chosen =
408
+ found.length === 1
409
+ ? (await ask.confirm({ message: `Deploy "${found[0].name}"?`, initialValue: true })) ? [found[0].localDir] : []
410
+ : guard(await p.multiselect({ message: 'Which projects do you deploy? (space to toggle)', options: found.map((f) => ({ value: f.localDir, label: f.name, hint: f.localDir })), initialValues: found.map((f) => f.localDir), required: false }));
411
+ if (chosen.length) {
412
+ const mode = await ask.select({ message: 'How should they be deployed?', options: APP_TYPES.filter((o) => o.value.startsWith('docker')), initialValue: 'docker-registry' });
413
+ const platform = mode === 'docker-registry' ? await askPlatform() : null;
414
+ for (const f of found.filter((x) => chosen.includes(x.localDir))) {
415
+ const { name, t } = await setupComposeTarget(root, f, mode, platform, taken());
416
+ targets[name] = t;
417
+ }
418
+ }
419
+ } else if (!Object.keys(existing).length) {
420
+ p.log.info('No docker-compose file found. Pick how this project is deployed.');
421
+ }
422
+
423
+ const askMore = () => ask.confirm({ message: 'Add another project by hand (PM2, static site, custom, …)?', initialValue: false });
424
+ if (!Object.keys(targets).length && !Object.keys(existing).length) {
425
+ const { name, t } = await setupManualTarget(root, taken());
426
+ targets[name] = t;
427
+ }
428
+ while (await askMore()) {
429
+ const { name, t } = await setupManualTarget(root, taken());
430
+ targets[name] = t;
431
+ }
432
+ return targets;
433
+ }
434
+
435
+ // ───────────────────────── docker registry ─────────────────────────
436
+
437
+ const regArg = (reg) => (reg.server ? ` ${q(reg.server)}` : '');
438
+
439
+ // Logs in for this deploy only and logs out on exit, so credentials don't stay on the server.
440
+ function dockerLoginScript(reg) {
441
+ const eof = `DEPOPS_EOF_${randomBytes(8).toString('hex')}`;
442
+ return [
443
+ `echo ${q(`==> Docker login${reg.server ? ' to ' + reg.server : ''}`)}`,
444
+ `docker login${regArg(reg)} -u ${q(reg.username)} --password-stdin >/dev/null <<'${eof}'`,
445
+ reg.password,
446
+ eof,
447
+ `trap 'docker logout${regArg(reg)} >/dev/null 2>&1 || true' EXIT`,
448
+ ].join('\n');
449
+ }
450
+
451
+ function dockerLoginLocal(reg) {
452
+ return new Promise((resolve) => {
453
+ const args = ['login', ...(reg.server ? [reg.server] : []), '-u', reg.username, '--password-stdin'];
454
+ const child = spawn('docker', args, { stdio: ['pipe', 'ignore', 'pipe'] });
455
+ let err = '';
456
+ child.stderr.on('data', (d) => (err += d));
457
+ child.on('error', () => resolve({ ok: false, err: 'Docker is not installed or not running on this computer.' }));
458
+ child.on('close', (code) => resolve({ ok: code === 0, err: err.trim() }));
459
+ child.stdin.end(reg.password + '\n');
460
+ });
461
+ }
462
+
463
+ async function checkRegistry(data, reg) {
464
+ if (hasType(data, 'docker-registry')) {
465
+ const s = p.spinner();
466
+ s.start('Checking Docker login on this computer');
467
+ const r = await dockerLoginLocal(reg);
468
+ if (!r.ok) {
469
+ s.stop('Docker login failed here', 1);
470
+ p.log.error(r.err || 'Login failed');
471
+ return false;
472
+ }
473
+ s.stop('Docker login OK on this computer');
474
+ }
475
+ let conn;
476
+ try {
477
+ conn = await connect(data.server);
478
+ } catch (e) {
479
+ p.log.error(e.message);
480
+ return false;
481
+ }
482
+ try {
483
+ p.log.step('Checking Docker login on the server');
484
+ const code = await runScript(conn, `set -e\n${dockerLoginScript(reg)}\necho 'Docker login OK on the server'\n`, { sudo: data.sudo });
485
+ return code === 0;
486
+ } finally {
487
+ conn.end();
488
+ }
489
+ }
490
+
491
+ async function setupRegistry(data, existing) {
492
+ const needed = await ask.confirm({
493
+ message: 'Do your Docker images need a registry login (pushing, or private images)?',
494
+ initialValue: existing ? true : hasType(data, 'docker-registry'),
495
+ });
496
+ if (!needed) return null;
497
+ const known = ['', 'ghcr.io'];
498
+ let server = await ask.select({
499
+ message: 'Registry',
500
+ initialValue: existing && !known.includes(existing.server) ? 'other' : existing?.server ?? '',
501
+ options: [
502
+ { value: '', label: 'Docker Hub' },
503
+ { value: 'ghcr.io', label: 'GitHub Container Registry (ghcr.io)' },
504
+ { value: 'other', label: 'Other (GitLab, AWS ECR, self-hosted…)' },
505
+ ],
506
+ });
507
+ if (server === 'other') server = (await ask.text({ message: 'Registry address', initialValue: existing?.server, placeholder: 'registry.example.com', validate: required })).trim();
508
+ const username = (await ask.text({ message: 'Registry username', initialValue: existing?.username, validate: required })).trim();
509
+ p.log.info('Tip: use an access token instead of your account password (Docker Hub → Account settings → Personal access tokens).');
510
+ const password = await ask.secret({ message: 'Password or access token', validate: required });
511
+ const reg = { server, username, password };
512
+
513
+ for (;;) {
514
+ if (await checkRegistry(data, reg)) {
515
+ p.log.success('Docker registry login verified');
516
+ return reg;
517
+ }
518
+ const next = await ask.select({
519
+ message: 'Docker login did not work. What now?',
520
+ options: [
521
+ { value: 'change', label: 'Enter the details again' },
522
+ { value: 'retry', label: 'Try again' },
523
+ { value: 'skip', label: 'Save anyway (check later)' },
524
+ { value: 'quit', label: 'Quit' },
525
+ ],
526
+ });
527
+ if (next === 'quit') fail('Setup cancelled.');
528
+ if (next === 'skip') return reg;
529
+ if (next === 'change') return setupRegistry(data, reg);
530
+ }
531
+ }
532
+
533
+ // Warn about plaintext copies of the server details lying around in the project.
534
+ async function scanForLeaks(dir, server, registry) {
535
+ const needles = [server.host, server.auth?.password, registry?.password].filter((x) => x && x.length > 3);
536
+ const hits = [];
537
+ for (const name of await fs.readdir(dir).catch(() => [])) {
538
+ if (name === VAULT_FILE || name.startsWith('.git') || name === 'node_modules') continue;
539
+ const file = path.join(dir, name);
540
+ const st = await fs.stat(file).catch(() => null);
541
+ if (!st?.isFile() || st.size > 1024 * 1024) continue;
542
+ const text = await fs.readFile(file, 'utf8').catch(() => '');
543
+ if (needles.some((n) => text.includes(n))) hits.push(name);
544
+ }
545
+ if (hits.length) {
546
+ p.log.warn(`These files contain your server address or password in plain text. Delete them or remove the values before committing:\n ${hits.join('\n ')}`);
547
+ }
548
+ }
549
+
550
+ // ───────────────────────── server side ─────────────────────────
551
+
552
+ function heredoc(target, content, mode600 = false) {
553
+ const eof = `DEPOPS_EOF_${randomBytes(8).toString('hex')}`;
554
+ const body = content.endsWith('\n') ? content : content + '\n';
555
+ return `( ${mode600 ? 'umask 077; ' : ''}cat > ${q(target)} <<'${eof}'\n${body}${eof}\n)${mode600 ? `\nchmod 600 -- ${q(target)}` : ''}`;
556
+ }
557
+
558
+ /**
559
+ * The script that runs in the project's server folder.
560
+ * opts.steps=false → only create the folder and write docker-compose.yml + .env (first-time setup).
561
+ */
562
+ async function remoteScript(data, root, t, stagings = [], { steps = true } = {}) {
563
+ const L = ['set -e', `mkdir -p -- ${q(t.dir)}`, `cd -- ${q(t.dir)}`];
564
+ if (steps && data.registry && t.type.startsWith('docker')) L.push(dockerLoginScript(data.registry));
565
+ for (const { staging, to } of stagings) {
566
+ L.push(`echo ${q(`==> Syncing uploaded files → ${to}`)}`, `mkdir -p -- ${q(to)}`, `cp -R -- ${q(staging)}/. ${q(to)}/`);
567
+ }
568
+ if (t.type === 'docker-registry') {
569
+ const doc = await loadCompose(path.join(root, t.localDir, t.composeFile));
570
+ L.push(`echo '==> Writing docker-compose.yml'`, heredoc('docker-compose.yml', serverCompose(doc)), 'export COMPOSE_FILE=docker-compose.yml');
571
+ }
572
+ const env = t.env || {};
573
+ const keys = Object.keys(env);
574
+ if (t.envFile && keys.length) {
575
+ L.push(`echo ${q(`==> Writing ${t.envFile} (${keys.length} variables)`)}`, heredoc(t.envFile, keys.map((k) => `${k}=${env[k]}`).join('\n'), true));
576
+ }
577
+ if (steps) t.remoteSteps.forEach((s, i) => L.push(`echo ${q(`==> [${i + 1}/${t.remoteSteps.length}] ${s}`)}`, s));
578
+ return L.join('\n') + '\n';
579
+ }
580
+
581
+ async function prepareServer(data, root, list) {
582
+ await withConnection(data, async (conn) => {
583
+ for (const name of list) {
584
+ const t = data.targets[name];
585
+ p.log.step(`[${name}] Preparing server folder`);
586
+ const code = await runScript(conn, await remoteScript(data, root, t, [], { steps: false }), { sudo: data.sudo });
587
+ if (code !== 0) throw new Error(`[${name}] Server setup failed (exit ${code}).`);
588
+ }
589
+ });
590
+ }
591
+
592
+ // ───────────────────────── local side ─────────────────────────
593
+
594
+ function runLocal(cmd, args, { env, cwd, shell = false }) {
595
+ return new Promise((resolve) => {
596
+ const child = spawn(cmd, args, { shell, stdio: 'inherit', env, cwd });
597
+ child.on('close', (code) => resolve(code ?? 1));
598
+ child.on('error', () => resolve(1));
599
+ });
600
+ }
601
+
602
+ async function buildLocal(name, t, root) {
603
+ const projectDir = path.join(root, t.localDir);
604
+ const env = localEnvOf(t);
605
+ if (t.type === 'docker-registry') {
606
+ const doc = await loadCompose(path.join(projectDir, t.composeFile));
607
+ const { builds, problems } = analyze(doc, env);
608
+ if (problems.length) fail(`[${name}] ${path.join(t.localDir, t.composeFile)}:\n ${problems.join('\n ')}`);
609
+ if (!builds.length) p.log.info(`[${name}] Nothing to build (only ready-made images)`);
610
+ for (const b of builds) {
611
+ p.log.step(`[${name}] Build & push ${b.service} → ${b.image}`);
612
+ const code = await runLocal('docker', buildArgv(projectDir, b, t.platform || 'linux/amd64'), { env, cwd: projectDir });
613
+ if (code !== 0) fail(`[${name}] Build failed (exit ${code}). Nothing was changed on the server.`);
614
+ }
615
+ }
616
+ for (const [i, step] of t.localSteps.entries()) {
617
+ p.log.step(`[${name}] Local ${i + 1}/${t.localSteps.length}: ${step}`);
618
+ const code = await runLocal(step, [], { env, cwd: projectDir, shell: true });
619
+ if (code !== 0) fail(`[${name}] Local step failed (exit ${code}). Nothing was changed on the server.`);
620
+ }
621
+ }
622
+
623
+ async function deployRemote(conn, data, root, name, t) {
624
+ const projectDir = path.join(root, t.localDir);
625
+ const stagings = [];
626
+ try {
627
+ for (const u of t.uploads) {
628
+ const from = path.resolve(projectDir, u.from);
629
+ const st = await fs.stat(from).catch(() => null);
630
+ if (!st) throw new Error(`[${name}] Upload source not found: ${path.join(t.localDir, u.from)}`);
631
+ const mk = await exec(conn, 'umask 077; mktemp -d /tmp/depops-up.XXXXXXXXXX', { capture: true });
632
+ const staging = mk.stdout.trim();
633
+ if (mk.code !== 0 || !/^\/tmp\/depops-up\.[A-Za-z0-9]+$/.test(staging)) throw new Error('Could not create upload folder on server.');
634
+ stagings.push({ staging, to: u.to });
635
+ const s = p.spinner();
636
+ s.start(`[${name}] Uploading ${u.from}`);
637
+ let n = 0;
638
+ await upload(conn, from, st.isDirectory() ? staging : `${staging}/${path.basename(from)}`, () => s.message(`[${name}] Uploading ${u.from} (${++n} files)`));
639
+ s.stop(`[${name}] Uploaded ${u.from}`);
640
+ }
641
+ p.log.step(`[${name}] Server steps`);
642
+ const code = await runScript(conn, await remoteScript(data, root, t, stagings), { sudo: data.sudo });
643
+ if (code !== 0) throw new Error(`[${name}] Server step failed (exit ${code}).`);
644
+ } finally {
645
+ for (const { staging } of stagings) await exec(conn, `rm -rf -- ${q(staging)}`, { capture: true }).catch(() => {});
646
+ }
647
+ }
648
+
649
+ // ───────────────────────── commands ─────────────────────────
650
+
651
+ async function cmdInit() {
652
+ p.intro('depops init');
653
+ const file = path.resolve(VAULT_FILE);
654
+ const root = path.dirname(file);
655
+ if (await fs.access(file).then(() => true, () => false)) fail(`${VAULT_FILE} already exists. Use \`depops edit\` to change it.`);
656
+
657
+ const { server, sudo } = await setupServer();
658
+ const targets = await setupTargets(root);
659
+ const data = { version: 2, server, sudo, targets, registry: null };
660
+ if (usesDocker(data)) data.registry = await setupRegistry(data);
661
+ const password = await newMasterPassword();
662
+ await save({ file, password, data });
663
+ await scanForLeaks(root, server, data.registry);
664
+
665
+ if (await ask.confirm({ message: 'Create the server folders and copy docker-compose.yml + .env there now?', initialValue: true })) {
666
+ await prepareServer(data, root, names(data));
667
+ p.log.success('Server folders are ready');
668
+ }
669
+ p.outro(
670
+ `Done! Commit ${VAULT_FILE} safely.\n` +
671
+ ` Deploy everything: npx depops deploy\n` +
672
+ ` Deploy one project: npx depops deploy ${names(data)[0]}`,
673
+ );
674
+ }
675
+
676
+ async function cmdDeploy(args, flags) {
677
+ p.intro('depops deploy');
678
+ const { file, data } = await unlock();
679
+ const root = path.dirname(file);
680
+ const list = args.length ? args : names(data);
681
+ const unknown = list.filter((n) => !data.targets[n]);
682
+ if (unknown.length) fail(`Unknown project(s): ${unknown.join(', ')}. Projects: ${names(data).join(', ')}`);
683
+ const started = Date.now();
684
+ p.log.info(`Deploying: ${list.join(', ')}`);
685
+
686
+ if (!flags['skip-local']) {
687
+ if (data.registry && list.some((n) => data.targets[n].type === 'docker-registry')) {
688
+ const r = await dockerLoginLocal(data.registry);
689
+ if (!r.ok) fail(`Docker login failed on this computer: ${r.err}`);
690
+ p.log.success('Docker login OK');
691
+ }
692
+ // Build everything first: if any build fails, no server is touched.
693
+ for (const n of list) await buildLocal(n, data.targets[n], root);
694
+ }
695
+ if (flags['skip-remote']) return p.outro('Local steps done (server skipped).');
696
+
697
+ await withConnection(data, async (conn) => {
698
+ for (const n of list) {
699
+ await deployRemote(conn, data, root, n, data.targets[n]);
700
+ p.log.success(`[${n}] deployed`);
701
+ }
702
+ });
703
+ p.outro(`Deployed ${list.join(', ')} in ${Math.round((Date.now() - started) / 1000)}s ✔`);
704
+ }
705
+
706
+ async function cmdRun(args, flags) {
707
+ const command = args.join(' ').trim();
708
+ if (!command) fail('Usage: depops run "<command>" [--target=name]');
709
+ const { data } = await unlock();
710
+ const t = data.targets[await pickTarget(data, flags, 'Run it in which project folder?')];
711
+ const sudo = flags['no-sudo'] ? null : data.sudo;
712
+ await withConnection(data, async (conn) => {
713
+ process.exitCode = await runScript(conn, `set -e\ncd -- ${q(t.dir)}\n${command}\n`, { sudo });
714
+ });
715
+ }
716
+
717
+ async function cmdTest() {
718
+ p.intro('depops test');
719
+ const { data } = await unlock();
720
+ await withConnection(data, async (conn) => {
721
+ const r = await exec(conn, 'uname -sm', { capture: true });
722
+ p.log.success(`SSH OK (${r.stdout.trim()})`);
723
+ if (data.sudo?.enabled) {
724
+ const code = await runScript(conn, 'true', { sudo: data.sudo });
725
+ code === 0 ? p.log.success('sudo OK') : p.log.error('sudo FAILED');
726
+ }
727
+ });
728
+ p.outro('All good');
729
+ }
730
+
731
+ const mask = (v) => (v ? '•'.repeat(8) : '(empty)');
732
+
733
+ async function cmdShow(flags) {
734
+ const { data } = await unlock();
735
+ const reveal = flags.reveal && (await ask.confirm({ message: 'Show server address on screen?', initialValue: false }));
736
+ const { server, sudo, registry } = data;
737
+ p.note(
738
+ [
739
+ `Server : ${reveal ? `${server.username}@${server.host}:${server.port}` : mask(1)}`,
740
+ `Auth : ${server.auth.type}`,
741
+ `Host key : ${reveal ? server.hostKey : mask(server.hostKey)}`,
742
+ `sudo : ${sudo?.enabled ? 'yes' : 'no'}`,
743
+ `Registry : ${registry ? `${registry.server || 'Docker Hub'} (${reveal ? registry.username : mask(1)})` : '(none)'}`,
744
+ ].join('\n'),
745
+ 'Shared',
746
+ );
747
+ for (const [n, t] of Object.entries(data.targets)) {
748
+ p.note(
749
+ [
750
+ `Local folder : ${t.localDir}`,
751
+ `Type : ${t.type}${t.platform ? ` (${t.platform})` : ''}`,
752
+ `Server folder: ${reveal ? t.dir : mask(t.dir)}`,
753
+ `Local steps : ${t.localSteps.length ? '\n ' + t.localSteps.join('\n ') : '(none)'}`,
754
+ `Uploads : ${t.uploads.length ? '\n ' + t.uploads.map((u) => `${u.from} → ${u.to}`).join('\n ') : '(none)'}`,
755
+ `Server steps : ${t.remoteSteps.length ? '\n ' + t.remoteSteps.join('\n ') : '(none)'}`,
756
+ `Env file : ${t.envFile || '(not managed)'} [${Object.keys(t.env || {}).length} vars]`,
757
+ ].join('\n'),
758
+ `Project: ${n}`,
759
+ );
760
+ }
761
+ }
762
+
763
+ async function cmdEnv(args, flags) {
764
+ const [sub, ...rest] = args;
765
+ const ctx = await unlock();
766
+ const t = ctx.data.targets[await pickTarget(ctx.data, flags, 'Env of which project?')];
767
+ t.env ??= {};
768
+ const env = t.env;
769
+ if (sub === 'list' || !sub) {
770
+ const keys = Object.keys(env);
771
+ return p.note(keys.length ? keys.join('\n') : '(none)', 'Env vars (values hidden)');
772
+ }
773
+ if (sub === 'set') {
774
+ const arg = rest.join(' ');
775
+ let key = arg;
776
+ let value;
777
+ if (arg.includes('=')) {
778
+ key = arg.slice(0, arg.indexOf('='));
779
+ value = arg.slice(arg.indexOf('=') + 1);
780
+ p.log.warn('Tip: `depops env set KEY` (without a value) asks for it hidden, so it stays out of your shell history.');
781
+ }
782
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) fail('Usage: depops env set KEY [--target=name]');
783
+ value ??= await ask.secret({ message: `Value for ${key}` });
784
+ if (/[\r\n]/.test(value)) fail('Values cannot contain line breaks.');
785
+ env[key] = value;
786
+ } else if (sub === 'rm') {
787
+ for (const k of rest) delete env[k];
788
+ } else if (sub === 'import') {
789
+ const file = rest[0] || path.join(path.dirname(ctx.file), t.localDir, '.env');
790
+ const imported = parseEnv(await fs.readFile(file, 'utf8').catch(() => fail(`Cannot read ${file}`)));
791
+ Object.assign(env, imported);
792
+ p.log.success(`Imported ${Object.keys(imported).length} variables from ${file}`);
793
+ } else {
794
+ fail('Usage: depops env [list | set KEY | rm KEY... | import [file]] [--target=name]');
795
+ }
796
+ if (!t.envFile && Object.keys(env).length) t.envFile = '.env';
797
+ await save(ctx);
798
+ }
799
+
800
+ async function cmdPasswd() {
801
+ p.intro('depops passwd');
802
+ const ctx = await unlock();
803
+ ctx.password = await newMasterPassword();
804
+ await save(ctx);
805
+ p.outro('Master password changed. Commit the updated vault and tell your team the new password.');
806
+ }
807
+
808
+ async function cmdEdit(flags) {
809
+ p.intro('depops edit');
810
+ const ctx = await unlock();
811
+ const d = ctx.data;
812
+ const root = path.dirname(ctx.file);
813
+ for (;;) {
814
+ const choice = await ask.select({
815
+ message: 'What do you want to change?',
816
+ options: [
817
+ { value: 'add', label: 'Add project(s)' },
818
+ { value: 'remove', label: 'Remove a project' },
819
+ { value: 'dir', label: 'Server folder of a project' },
820
+ { value: 'local', label: 'Local steps of a project' },
821
+ { value: 'remote', label: 'Server steps of a project' },
822
+ { value: 'uploads', label: 'Uploads of a project' },
823
+ { value: 'prepare', label: 'Re-copy docker-compose.yml + .env to the server' },
824
+ { value: 'server', label: 'Server connection (IP / user / login / sudo)' },
825
+ { value: 'hostkey', label: 'Re-trust server host key (after server rebuild)' },
826
+ { value: 'sudo', label: 'sudo settings' },
827
+ { value: 'registry', label: 'Docker registry login' },
828
+ { value: 'save', label: 'Save and exit' },
829
+ { value: 'quit', label: 'Exit without saving' },
830
+ ],
831
+ });
832
+ if (choice === 'quit') return p.outro('No changes saved.');
833
+ if (choice === 'save') {
834
+ await save(ctx);
835
+ return p.outro('Saved. Commit .depops.vault to share the change.');
836
+ }
837
+ if (choice === 'add') Object.assign(d.targets, await setupTargets(root, d.targets));
838
+ if (choice === 'remove') {
839
+ if (names(d).length === 1) p.log.warn('This is the only project; add another one first.');
840
+ else {
841
+ const n = await pickTarget(d, {}, 'Remove which project? (files on the server are not touched)');
842
+ if (await ask.confirm({ message: `Remove "${n}" from the vault?`, initialValue: false })) delete d.targets[n];
843
+ }
844
+ }
845
+ if (['dir', 'local', 'remote', 'uploads'].includes(choice)) {
846
+ const t = d.targets[await pickTarget(d, flags)];
847
+ if (choice === 'dir') t.dir = (await ask.text({ message: 'Folder on the server', initialValue: t.dir, validate: required })).trim();
848
+ if (choice === 'local') t.localSteps = await editSteps('Local steps', t.localSteps);
849
+ if (choice === 'remote') t.remoteSteps = await editSteps('Server steps', t.remoteSteps);
850
+ if (choice === 'uploads') {
851
+ p.note(t.uploads.map((u) => `${u.from} → ${u.to}`).join('\n') || '(none)', 'Uploads');
852
+ if (await ask.confirm({ message: 'Replace uploads?', initialValue: false })) {
853
+ t.uploads = [];
854
+ for (;;) {
855
+ const from = (await ask.text({ message: 'Local file/folder, relative to the project (empty to finish)', defaultValue: '' })).trim();
856
+ if (!from) break;
857
+ const to = (await ask.text({ message: 'Server path (relative to the server folder)', initialValue: '.' })).trim();
858
+ t.uploads.push({ from, to });
859
+ }
860
+ }
861
+ }
862
+ }
863
+ if (choice === 'prepare') await prepareServer(d, root, [await pickTarget(d, flags)]);
864
+ if (choice === 'server') Object.assign(d, await setupServer(d.server));
865
+ if (choice === 'hostkey') {
866
+ const server = { ...d.server, hostKey: undefined };
867
+ const conn = await connect(server, { onNewHostKey: trustPrompt }).catch((e) => fail(scrub(e.message, server)));
868
+ d.server.hostKey = conn.hostKey;
869
+ conn.end();
870
+ p.log.success('Host key updated');
871
+ }
872
+ if (choice === 'sudo') {
873
+ await withConnection(d, async (conn) => {
874
+ d.sudo = await setupSudo(conn, d.server, d.server.username, null, d.sudo);
875
+ });
876
+ }
877
+ if (choice === 'registry') d.registry = await setupRegistry(d, d.registry);
878
+ }
879
+ }
880
+
881
+ // ───────────────────────── entry ─────────────────────────
882
+
883
+ const HELP = `depops — encrypted VPS deployments
884
+
885
+ Usage:
886
+ depops init Set up server + projects, create .depops.vault
887
+ depops deploy Deploy ALL projects
888
+ depops deploy <name> [name…] Deploy only these projects (e.g. depops deploy backend)
889
+ --skip-local Skip building / local steps
890
+ --skip-remote Only build / run local steps
891
+ depops test Check SSH and sudo
892
+ depops run "<command>" Run a command in a project's server folder (--target=name, --no-sudo)
893
+ depops edit Add/remove projects, change steps, server, sudo, registry
894
+ depops env [list|set KEY|rm KEY|import [file]] [--target=name]
895
+ depops show [--reveal] Vault summary (server details hidden by default)
896
+ depops passwd Change the master password
897
+
898
+ Non-interactive (scripts): set DEPOPS_PASSWORD in the environment.
899
+ `;
900
+
901
+ export async function main(argv) {
902
+ const flags = {};
903
+ const args = [];
904
+ for (const a of argv) {
905
+ if (!a.startsWith('--')) args.push(a);
906
+ else if (a.includes('=')) flags[a.slice(2, a.indexOf('='))] = a.slice(a.indexOf('=') + 1);
907
+ else flags[a.slice(2)] = true;
908
+ }
909
+ const [cmd, ...rest] = args;
910
+ try {
911
+ switch (cmd) {
912
+ case 'init': return await cmdInit();
913
+ case 'deploy': return await cmdDeploy(rest, flags);
914
+ case 'test': return await cmdTest();
915
+ case 'run': return await cmdRun(rest, flags);
916
+ case 'edit': return await cmdEdit(flags);
917
+ case 'env': return await cmdEnv(rest, flags);
918
+ case 'show': return await cmdShow(flags);
919
+ case 'passwd': return await cmdPasswd();
920
+ default: process.stdout.write(HELP);
921
+ }
922
+ } catch (e) {
923
+ fail(e?.message || String(e));
924
+ }
925
+ }