depops 0.2.0 → 0.4.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/README.md CHANGED
@@ -61,6 +61,35 @@ file in the repo root works the same way. Projects without Docker can be added b
61
61
  - NEXT_PUBLIC_API_URL
62
62
  ```
63
63
 
64
+ ## Open a terminal on the server
65
+
66
+ ```bash
67
+ depops enter backend # logs in and opens the backend server folder (alias: depops ssh)
68
+ depops enter # pick a project, or the home folder
69
+ ```
70
+
71
+ No server password to type — only the vault password (or none while unlocked). Type `exit` to come back.
72
+
73
+ ## Unlock for a while (scripts and assistants)
74
+
75
+ ```bash
76
+ depops unlock --for=30m # default 30m, max 12h
77
+ depops lock # end it now
78
+ ```
79
+
80
+ While unlocked, every depops command in this project works without a password prompt, including when a
81
+ script or a coding assistant runs it for you, for example to investigate and fix a problem:
82
+
83
+ ```bash
84
+ depops run "docker compose ps" --target=backend
85
+ depops run "docker compose logs --tail 200" --target=backend
86
+ depops deploy backend
87
+ ```
88
+
89
+ The master password and server credentials are never printed or handed out as text. The session is held by
90
+ a small background process that only your OS user can reach (private socket + random token), like
91
+ `ssh-agent`. Without a session, non-interactive commands stop with "Vault is locked" instead of hanging.
92
+
64
93
  ## Other deploy types
65
94
 
66
95
  | Type | What happens |
@@ -77,12 +106,15 @@ All steps are editable later with `depops edit`.
77
106
  ```
78
107
  depops init create the vault
79
108
  depops deploy [name…] [--skip-local] [--skip-remote]
109
+ depops enter [name] terminal on the server (alias: ssh)
110
+ depops unlock [--for=30m] / lock password-free session for scripts and assistants
80
111
  depops test check SSH + sudo
81
112
  depops run "<cmd>" [--target=name] [--no-sudo]
82
113
  depops edit add/remove projects, steps, server, sudo, registry
83
114
  depops env list|set KEY|rm KEY|import [file] [--target=name]
84
115
  depops show [--reveal] summary (server details hidden unless --reveal)
85
116
  depops passwd change master password
117
+ depops update update to the newest version
86
118
  ```
87
119
 
88
120
  For scripts, set `DEPOPS_PASSWORD` in the environment instead of typing it.
@@ -109,6 +141,9 @@ server. During deploy the server logs in, pulls, and **logs out again**, so cred
109
141
  - **Encryption:** scrypt (N=2^17, r=8, p=1, 128 MiB per guess) → AES-256-GCM. The header is authenticated,
110
142
  so any change to the file is detected. Node built-in crypto only.
111
143
  - **Master password** is never stored; minimum 12 characters with strength checks.
144
+ - **Lockout:** after 3 wrong passwords on a computer, unlocking is blocked for 30s, then 1m, 2m, … up to 1h.
145
+ Offline guessing against a copied vault file is what scrypt + a strong password protect against; a
146
+ "self-destruct" counter could not stop that (the attacker never runs depops), so the vault is never deleted.
112
147
  - **Host key pinning:** the server fingerprint is confirmed on first connect and stored in the vault.
113
148
  A changed key aborts the deploy (man-in-the-middle protection).
114
149
  - **No secrets on command lines:** the sudo password is passed via stdin and the deploy script goes to a
@@ -120,6 +155,17 @@ server. During deploy the server logs in, pulls, and **logs out again**, so cred
120
155
  **The vault is only as strong as the master password.** Use a long, unique one and share it through a
121
156
  password manager. Anyone with the repo *and* the password can deploy.
122
157
 
158
+ ## Updates
159
+
160
+ depops checks npm for a new version at most every 12 hours (1.5s timeout, never blocks when offline):
161
+
162
+ - **npx:** runs the newest version automatically.
163
+ - **Global install** (`npm i -g depops`): updates itself, then re-runs your command.
164
+ - **Project install** (`node_modules`): shows the update command, never edits your `package.json`.
165
+
166
+ `depops update` updates on demand; `depops --version` shows the installed version.
167
+ Turn it off with `--no-update` or `DEPOPS_NO_UPDATE=1`. It is always off in CI.
168
+
123
169
  ## Requirements
124
170
 
125
171
  - Node.js 18.17+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "depops",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Deploy to any VPS from your machine over SSH. All server details live in one encrypted vault file you can safely commit.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/agent.js ADDED
@@ -0,0 +1,116 @@
1
+ // Unlock session (like ssh-agent): a small background process keeps the master password in memory
2
+ // for a limited time, so `depops run/enter/deploy` (and assistants or scripts you start) work without
3
+ // asking again. Only the same OS user can use it: a random token in a private file is required.
4
+ import net from 'node:net';
5
+ import os from 'node:os';
6
+ import fs from 'node:fs/promises';
7
+ import path from 'node:path';
8
+ import { spawn } from 'node:child_process';
9
+ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
10
+ import { fileURLToPath } from 'node:url';
11
+
12
+ const DIR = path.join(os.homedir(), '.depops');
13
+ const isWin = process.platform === 'win32';
14
+
15
+ function ids(vaultFile) {
16
+ const id = createHash('sha256').update(path.resolve(vaultFile)).digest('hex').slice(0, 16);
17
+ const user = createHash('sha256').update(os.userInfo().username).digest('hex').slice(0, 8);
18
+ return {
19
+ socket: isWin ? `\\\\.\\pipe\\depops-${user}-${id}` : path.join(DIR, `agent-${id}.sock`),
20
+ tokenFile: path.join(DIR, `agent-${id}.token`),
21
+ };
22
+ }
23
+
24
+ function request(vaultFile, line, timeoutMs = 800) {
25
+ const { socket, tokenFile } = ids(vaultFile);
26
+ return new Promise(async (resolve) => {
27
+ let token;
28
+ try {
29
+ token = (await fs.readFile(tokenFile, 'utf8')).trim();
30
+ } catch {
31
+ return resolve(null);
32
+ }
33
+ let buf = '';
34
+ const c = net.connect(socket);
35
+ const done = (v) => {
36
+ clearTimeout(timer);
37
+ c.destroy();
38
+ resolve(v);
39
+ };
40
+ const timer = setTimeout(() => done(null), timeoutMs);
41
+ c.on('connect', () => c.write(`${line} ${token}\n`));
42
+ c.on('data', (d) => (buf += d));
43
+ c.on('end', () => {
44
+ try {
45
+ done(JSON.parse(buf));
46
+ } catch {
47
+ done(null);
48
+ }
49
+ });
50
+ c.on('error', () => done(null));
51
+ });
52
+ }
53
+
54
+ /** Returns { password, expiresAt } from a running session, or null. */
55
+ export const askAgent = (vaultFile) => request(vaultFile, 'GET');
56
+ export const stopAgent = (vaultFile) => request(vaultFile, 'STOP');
57
+
58
+ export async function startAgent(vaultFile, password, ttlMs) {
59
+ await fs.mkdir(DIR, { recursive: true, mode: 0o700 });
60
+ await stopAgent(vaultFile);
61
+ const { tokenFile } = ids(vaultFile);
62
+ const token = randomBytes(32).toString('hex');
63
+ await fs.writeFile(tokenFile, token, { mode: 0o600 });
64
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url), '--serve', path.resolve(vaultFile), String(ttlMs)], {
65
+ detached: true,
66
+ stdio: ['pipe', 'ignore', 'ignore'],
67
+ windowsHide: true,
68
+ });
69
+ child.stdin.end(JSON.stringify({ password, token }));
70
+ child.unref();
71
+ for (let i = 0; i < 40; i++) {
72
+ if (await askAgent(vaultFile)) return true;
73
+ await new Promise((r) => setTimeout(r, 50));
74
+ }
75
+ return false;
76
+ }
77
+
78
+ async function serve(vaultFile, ttlMs) {
79
+ let input = '';
80
+ for await (const chunk of process.stdin) input += chunk;
81
+ const { password, token } = JSON.parse(input);
82
+ const tokenBuf = Buffer.from(token);
83
+ const expiresAt = Date.now() + ttlMs;
84
+ const { socket, tokenFile } = ids(vaultFile);
85
+ if (!isWin) await fs.rm(socket, { force: true });
86
+
87
+ const shutdown = async () => {
88
+ server.close();
89
+ await fs.rm(tokenFile, { force: true }).catch(() => {});
90
+ if (!isWin) await fs.rm(socket, { force: true }).catch(() => {});
91
+ process.exit(0);
92
+ };
93
+
94
+ const server = net.createServer((c) => {
95
+ let buf = '';
96
+ c.on('data', (d) => {
97
+ buf += d;
98
+ if (!buf.includes('\n')) return;
99
+ const [cmd, given = ''] = buf.trim().split(' ');
100
+ const g = Buffer.from(given);
101
+ if (g.length !== tokenBuf.length || !timingSafeEqual(g, tokenBuf)) return c.end('{}');
102
+ if (cmd === 'STOP') {
103
+ c.end(JSON.stringify({ stopped: true }));
104
+ return shutdown();
105
+ }
106
+ c.end(JSON.stringify({ password, expiresAt }));
107
+ });
108
+ c.on('error', () => {});
109
+ });
110
+ server.listen(socket, async () => {
111
+ if (!isWin) await fs.chmod(socket, 0o600).catch(() => {});
112
+ });
113
+ setTimeout(shutdown, ttlMs);
114
+ }
115
+
116
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url) && process.argv[2] === '--serve') serve(process.argv[3], Number(process.argv[4]));
package/src/cli.js CHANGED
@@ -1,11 +1,14 @@
1
1
  import * as p from '@clack/prompts';
2
2
  import { spawn } from 'node:child_process';
3
- import { randomBytes } from 'node:crypto';
3
+ import { randomBytes, createHash } from 'node:crypto';
4
+ import os from 'node:os';
4
5
  import fs from 'node:fs/promises';
5
6
  import path from 'node:path';
6
7
  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 { interactiveShell, connect, exec, runScript, installPublicKey, generateKeyPair, upload, shQuote as q, scrub } from './ssh.js';
8
9
  import { APP_TYPES, presetSteps } from './presets.js';
10
+ import { askAgent, startAgent, stopAgent } from './agent.js';
11
+ import { autoUpdate, manualUpdate, currentVersion } from './update.js';
9
12
  import { detectProjects, findCompose, loadCompose, analyze, buildArgv, serverCompose } from './compose.js';
10
13
 
11
14
  // ───────────────────────── helpers ─────────────────────────
@@ -62,22 +65,62 @@ async function newMasterPassword() {
62
65
  }
63
66
  }
64
67
 
68
+ // Lockout after wrong master passwords (per vault, per computer): 3 free tries, then 30s, 1m, 2m … max 1h.
69
+ const attemptsFile = (vault) =>
70
+ path.join(os.homedir(), '.depops', `attempts-${createHash('sha256').update(path.resolve(vault)).digest('hex').slice(0, 16)}.json`);
71
+
72
+ async function readAttempts(vault) {
73
+ try {
74
+ return JSON.parse(await fs.readFile(attemptsFile(vault), 'utf8'));
75
+ } catch {
76
+ return { fails: 0, lockedUntil: 0 };
77
+ }
78
+ }
79
+
80
+ async function recordFailure(vault) {
81
+ const a = await readAttempts(vault);
82
+ a.fails += 1;
83
+ if (a.fails >= 3) a.lockedUntil = Date.now() + Math.min(30000 * 2 ** (a.fails - 3), 3600000);
84
+ await fs.mkdir(path.dirname(attemptsFile(vault)), { recursive: true, mode: 0o700 });
85
+ await fs.writeFile(attemptsFile(vault), JSON.stringify(a), { mode: 0o600 });
86
+ return a;
87
+ }
88
+
89
+ async function assertNotLocked(vault) {
90
+ const a = await readAttempts(vault);
91
+ const wait = a.lockedUntil - Date.now();
92
+ if (wait > 0) fail(`Too many wrong passwords (${a.fails}). Locked for ${Math.ceil(wait / 1000)}s more.`);
93
+ }
94
+
65
95
  async function unlock() {
66
96
  const file = await findVault();
67
97
  if (!file) fail(`No ${VAULT_FILE} found. Run \`depops init\` in your project first.`);
68
98
  const fromEnv = process.env.DEPOPS_PASSWORD;
99
+ if (!fromEnv) {
100
+ const session = await askAgent(file);
101
+ if (session?.password) {
102
+ try {
103
+ return { file, data: normalize(await readVault(file, session.password)), password: session.password };
104
+ } catch {}
105
+ }
106
+ if (!process.stdin.isTTY) fail('Vault is locked. Run `depops unlock` in your terminal first (or set DEPOPS_PASSWORD).');
107
+ }
69
108
  for (let attempt = 1; attempt <= 3; attempt++) {
109
+ await assertNotLocked(file);
70
110
  const pw = fromEnv ?? (await ask.secret({ message: 'Vault password' }));
71
111
  const s = p.spinner();
72
112
  s.start('Unlocking vault');
73
113
  try {
74
114
  const data = normalize(await readVault(file, pw));
75
115
  s.stop('Vault unlocked');
116
+ await fs.rm(attemptsFile(file), { force: true });
76
117
  return { file, data, password: pw };
77
118
  } catch (e) {
78
119
  s.stop('Unlock failed', 1);
79
120
  if (!(e instanceof VaultError)) throw e;
80
121
  p.log.error(e.message);
122
+ const a = await recordFailure(file);
123
+ if (a.lockedUntil > Date.now()) fail(`${a.fails} wrong passwords. Locked for ${Math.ceil((a.lockedUntil - Date.now()) / 1000)}s.`);
81
124
  if (fromEnv) process.exit(1);
82
125
  }
83
126
  }
@@ -878,6 +921,62 @@ async function cmdEdit(flags) {
878
921
  }
879
922
  }
880
923
 
924
+ function parseDuration(v, fallback) {
925
+ if (v === undefined || v === true) return fallback;
926
+ const m = String(v).match(/^(\d+)\s*([smh]?)$/i);
927
+ if (!m) fail('Use a duration like 30m, 2h or 90s.');
928
+ const ms = Number(m[1]) * { s: 1000, m: 60000, h: 3600000, '': 60000 }[m[2].toLowerCase()];
929
+ return Math.min(Math.max(ms, 60000), 12 * 3600000);
930
+ }
931
+
932
+ async function cmdUnlock(flags) {
933
+ p.intro('depops unlock');
934
+ const ttl = parseDuration(flags.for, 30 * 60000);
935
+ const { file, password } = await unlock();
936
+ if (!(await startAgent(file, password, ttl))) fail('Could not start the unlock session.');
937
+ const until = new Date(Date.now() + ttl).toLocaleTimeString();
938
+ p.note(
939
+ 'depops commands in this project now work without asking for the password —\n' +
940
+ 'also when an assistant or script runs them for you, e.g.:\n' +
941
+ ' depops run "docker compose ps" --target=backend\n' +
942
+ ' depops run "docker compose logs --tail 200" --target=backend\n' +
943
+ ' depops deploy backend\n\n' +
944
+ 'The master password and server credentials are never printed.',
945
+ `Unlocked until ${until}`,
946
+ );
947
+ p.outro('Lock again any time with: depops lock');
948
+ }
949
+
950
+ async function cmdLock() {
951
+ const file = await findVault();
952
+ if (!file) fail(`No ${VAULT_FILE} found.`);
953
+ const r = await stopAgent(file);
954
+ p.log.success(r?.stopped ? 'Locked.' : 'Already locked.');
955
+ }
956
+
957
+ async function cmdEnter(args, flags) {
958
+ if (!process.stdin.isTTY) fail('`depops enter` needs an interactive terminal. In scripts use: depops run "<command>" --target=name');
959
+ const { data } = await unlock();
960
+ const want = args[0] || (typeof flags.target === 'string' ? flags.target : null);
961
+ let dir = null;
962
+ if (want) {
963
+ if (!data.targets[want]) fail(`Unknown project "${want}". Projects: ${names(data).join(', ')}`);
964
+ dir = data.targets[want].dir;
965
+ } else if (names(data).length === 1) {
966
+ dir = data.targets[names(data)[0]].dir;
967
+ } else {
968
+ const v = await ask.select({
969
+ message: 'Open the server in which folder?',
970
+ options: [...names(data).map((n) => ({ value: n, label: n })), { value: '', label: 'Home folder' }],
971
+ });
972
+ dir = v ? data.targets[v].dir : null;
973
+ }
974
+ p.log.info('You are entering the server. Type exit to come back.');
975
+ await withConnection(data, async (conn) => {
976
+ process.exitCode = await interactiveShell(conn, dir);
977
+ });
978
+ }
979
+
881
980
  // ───────────────────────── entry ─────────────────────────
882
981
 
883
982
  const HELP = `depops — encrypted VPS deployments
@@ -888,14 +987,20 @@ Usage:
888
987
  depops deploy <name> [name…] Deploy only these projects (e.g. depops deploy backend)
889
988
  --skip-local Skip building / local steps
890
989
  --skip-remote Only build / run local steps
990
+ depops enter [name] Open a terminal on the server (alias: depops ssh)
991
+ depops unlock [--for=30m] Stay unlocked for a while (for you, scripts and assistants)
992
+ depops lock End the unlock session now
891
993
  depops test Check SSH and sudo
892
994
  depops run "<command>" Run a command in a project's server folder (--target=name, --no-sudo)
893
995
  depops edit Add/remove projects, change steps, server, sudo, registry
894
996
  depops env [list|set KEY|rm KEY|import [file]] [--target=name]
895
997
  depops show [--reveal] Vault summary (server details hidden by default)
896
998
  depops passwd Change the master password
999
+ depops update Update depops to the newest version
1000
+ depops --version Show the installed version
897
1001
 
898
1002
  Non-interactive (scripts): set DEPOPS_PASSWORD in the environment.
1003
+ Auto-update: checks npm every 12h. Turn off with --no-update or DEPOPS_NO_UPDATE=1 (always off in CI).
899
1004
  `;
900
1005
 
901
1006
  export async function main(argv) {
@@ -907,10 +1012,17 @@ export async function main(argv) {
907
1012
  else flags[a.slice(2)] = true;
908
1013
  }
909
1014
  const [cmd, ...rest] = args;
1015
+ if (flags.version || cmd === 'version') return process.stdout.write(`${await currentVersion()}\n`);
1016
+ if (cmd !== 'update') await autoUpdate(argv, flags);
910
1017
  try {
911
1018
  switch (cmd) {
1019
+ case 'update': return await manualUpdate();
912
1020
  case 'init': return await cmdInit();
913
1021
  case 'deploy': return await cmdDeploy(rest, flags);
1022
+ case 'enter':
1023
+ case 'ssh': return await cmdEnter(rest, flags);
1024
+ case 'unlock': return await cmdUnlock(flags);
1025
+ case 'lock': return await cmdLock();
914
1026
  case 'test': return await cmdTest();
915
1027
  case 'run': return await cmdRun(rest, flags);
916
1028
  case 'edit': return await cmdEdit(flags);
package/src/ssh.js CHANGED
@@ -186,3 +186,31 @@ export async function upload(conn, localPath, remotePath, onFile = () => {}) {
186
186
  sftp.end();
187
187
  }
188
188
  }
189
+
190
+ /** Interactive terminal on the server (like `ssh user@host`), optionally starting in a folder. */
191
+ export function interactiveShell(conn, startDir) {
192
+ return new Promise((resolve, reject) => {
193
+ const pty = { term: process.env.TERM || 'xterm-256color', cols: process.stdout.columns || 80, rows: process.stdout.rows || 24 };
194
+ const onStream = (err, stream) => {
195
+ if (err) return reject(err);
196
+ const stdin = process.stdin;
197
+ const wasRaw = stdin.isTTY && stdin.isRaw;
198
+ if (stdin.isTTY) stdin.setRawMode(true);
199
+ stdin.resume();
200
+ stdin.pipe(stream);
201
+ stream.pipe(process.stdout);
202
+ stream.stderr.pipe(process.stderr);
203
+ const onResize = () => stream.setWindow(process.stdout.rows, process.stdout.columns, 0, 0);
204
+ process.stdout.on('resize', onResize);
205
+ stream.on('close', (code) => {
206
+ process.stdout.off('resize', onResize);
207
+ stdin.unpipe(stream);
208
+ if (stdin.isTTY) stdin.setRawMode(wasRaw);
209
+ stdin.pause();
210
+ resolve(code ?? 0);
211
+ });
212
+ };
213
+ if (startDir) conn.exec(`cd ${shQuote(startDir)} 2>/dev/null; exec "\${SHELL:-/bin/bash}" -l`, { pty }, onStream);
214
+ else conn.shell(pty, onStream);
215
+ });
216
+ }
package/src/update.js ADDED
@@ -0,0 +1,142 @@
1
+ // Self-update: checks the npm registry (at most every 12h) and moves to the newest version.
2
+ import { spawn } from 'node:child_process';
3
+ import fs from 'node:fs/promises';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ const PKG = 'depops';
9
+ const REGISTRY_URL = `https://registry.npmjs.org/${PKG}/latest`;
10
+ const CHECK_EVERY_MS = 12 * 60 * 60 * 1000;
11
+ const CACHE_FILE = path.join(os.homedir(), '.depops', 'update.json');
12
+ const isWin = process.platform === 'win32';
13
+
14
+ export async function currentVersion() {
15
+ const pkg = JSON.parse(await fs.readFile(new URL('../package.json', import.meta.url), 'utf8'));
16
+ return pkg.version;
17
+ }
18
+
19
+ /** true when a > b for plain x.y.z versions (pre-releases are never offered). */
20
+ export function isNewer(a, b) {
21
+ const pa = String(a).split('.').map(Number);
22
+ const pb = String(b).split('.').map(Number);
23
+ if (pa.length !== 3 || pa.some(Number.isNaN) || /-/.test(a)) return false;
24
+ for (let i = 0; i < 3; i++) if (pa[i] !== pb[i]) return pa[i] > pb[i];
25
+ return false;
26
+ }
27
+
28
+ async function readCache() {
29
+ try {
30
+ return JSON.parse(await fs.readFile(CACHE_FILE, 'utf8'));
31
+ } catch {
32
+ return {};
33
+ }
34
+ }
35
+
36
+ async function writeCache(data) {
37
+ try {
38
+ await fs.mkdir(path.dirname(CACHE_FILE), { recursive: true, mode: 0o700 });
39
+ await fs.writeFile(CACHE_FILE, JSON.stringify(data));
40
+ } catch {}
41
+ }
42
+
43
+ export async function fetchLatest(timeoutMs = 1500) {
44
+ const res = await fetch(REGISTRY_URL, { signal: AbortSignal.timeout(timeoutMs), headers: { accept: 'application/json' } });
45
+ if (!res.ok) throw new Error(`registry responded ${res.status}`);
46
+ const { version } = await res.json();
47
+ if (!/^\d+\.\d+\.\d+$/.test(version)) throw new Error('unexpected version from registry');
48
+ return version;
49
+ }
50
+
51
+ /** npx | global | local — decides how an update can be applied. */
52
+ export async function installMode() {
53
+ const here = fileURLToPath(import.meta.url);
54
+ if (/[\\/]_npx[\\/]/.test(here)) return 'npx';
55
+ const globalRoot = await new Promise((resolve) => {
56
+ let out = '';
57
+ const c = spawn('npm', ['root', '-g'], { shell: isWin, stdio: ['ignore', 'pipe', 'ignore'] });
58
+ c.stdout.on('data', (d) => (out += d));
59
+ c.on('close', () => resolve(out.trim()));
60
+ c.on('error', () => resolve(''));
61
+ });
62
+ if (globalRoot && path.resolve(here).startsWith(path.resolve(globalRoot) + path.sep)) return 'global';
63
+ return 'local';
64
+ }
65
+
66
+ function run(cmd, args, env = process.env) {
67
+ return new Promise((resolve) => {
68
+ const c = spawn(cmd, args, { stdio: 'inherit', shell: isWin, env });
69
+ c.on('close', (code) => resolve(code ?? 1));
70
+ c.on('error', () => resolve(1));
71
+ });
72
+ }
73
+
74
+ const say = (msg) => process.stderr.write(`\x1b[36m›\x1b[0m ${msg}\n`);
75
+
76
+ /** Re-run the same command with the new version, then exit with its code. */
77
+ async function rerun(mode, latest, argv) {
78
+ const env = { ...process.env, DEPOPS_UPDATED: '1' };
79
+ const code = mode === 'npx' ? await run('npx', ['-y', `${PKG}@${latest}`, ...argv], env) : await run(PKG, argv, env);
80
+ process.exit(code);
81
+ }
82
+
83
+ export async function installLatest(latest) {
84
+ return run('npm', ['install', '-g', `${PKG}@${latest}`]);
85
+ }
86
+
87
+ /**
88
+ * Called on every start. Never throws and never blocks for more than ~1.5s.
89
+ * Skipped in CI, when DEPOPS_NO_UPDATE is set, with --no-update, and inside an already-updated run.
90
+ */
91
+ export async function autoUpdate(argv, flags) {
92
+ if (process.env.CI || process.env.DEPOPS_NO_UPDATE || process.env.DEPOPS_UPDATED || flags['no-update']) return;
93
+ try {
94
+ const current = await currentVersion();
95
+ const cache = await readCache();
96
+ let latest = cache.latest;
97
+ if (!latest || Date.now() - (cache.checkedAt || 0) > CHECK_EVERY_MS) {
98
+ latest = await fetchLatest();
99
+ await writeCache({ checkedAt: Date.now(), latest });
100
+ }
101
+ if (!isNewer(latest, current)) return;
102
+
103
+ const mode = await installMode();
104
+ if (mode === 'npx') {
105
+ say(`depops ${latest} is available (you have ${current}) — running the new version…`);
106
+ return rerun(mode, latest, argv);
107
+ }
108
+ if (mode === 'global') {
109
+ say(`Updating depops ${current} → ${latest}…`);
110
+ if ((await installLatest(latest)) === 0) {
111
+ say(`Updated to ${latest}.`);
112
+ return rerun(mode, latest, argv);
113
+ }
114
+ say(`Auto-update failed. Run manually: npm install -g ${PKG}@latest`);
115
+ return;
116
+ }
117
+ say(`depops ${latest} is available (you have ${current}). Update with: npm install -D ${PKG}@latest`);
118
+ } catch {
119
+ // Offline or registry down: never block the actual command.
120
+ }
121
+ }
122
+
123
+ /** `depops update` */
124
+ export async function manualUpdate() {
125
+ const current = await currentVersion();
126
+ let latest;
127
+ try {
128
+ latest = await fetchLatest(5000);
129
+ } catch (e) {
130
+ say(`Could not reach the npm registry: ${e.message}`);
131
+ process.exit(1);
132
+ }
133
+ await writeCache({ checkedAt: Date.now(), latest });
134
+ if (!isNewer(latest, current)) return say(`depops ${current} is the latest version.`);
135
+ const mode = await installMode();
136
+ if (mode === 'npx') return say(`npx always uses the newest version on the next run (${latest}).`);
137
+ if (mode === 'global') {
138
+ say(`Updating depops ${current} → ${latest}…`);
139
+ process.exit(await installLatest(latest));
140
+ }
141
+ say(`This project has depops ${current} installed locally. Update with: npm install -D ${PKG}@latest`);
142
+ }