easy-devops 1.2.1 → 1.3.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.
Files changed (126) hide show
  1. package/README.md +97 -6
  2. package/dist/ui/assets/index-CMRzkIKj.css +1 -0
  3. package/dist/ui/assets/index-DEouL3IK.js +452 -0
  4. package/dist/ui/assets/socket-DwLPrgsr.js +1 -0
  5. package/dist/ui/assets/socket-K5ttLD2q.js +65 -0
  6. package/dist/ui/brand/apple-touch-icon.png +0 -0
  7. package/dist/ui/brand/favicon-16.png +0 -0
  8. package/dist/ui/brand/favicon-32.png +0 -0
  9. package/dist/ui/brand/favicon-light-16.png +0 -0
  10. package/dist/ui/brand/favicon-light-32.png +0 -0
  11. package/dist/ui/brand/favicon.ico +0 -0
  12. package/dist/ui/brand/icon-192.png +0 -0
  13. package/dist/ui/brand/icon-48.png +0 -0
  14. package/dist/ui/brand/icon-512.png +0 -0
  15. package/dist/ui/brand/icon-64-light.png +0 -0
  16. package/dist/ui/brand/icon-64.png +0 -0
  17. package/dist/ui/brand/logo-dark.png +0 -0
  18. package/dist/ui/brand/logo-light.png +0 -0
  19. package/dist/ui/brand/mark-dark.png +0 -0
  20. package/dist/ui/brand/mark-light.png +0 -0
  21. package/dist/ui/index.html +71 -0
  22. package/install.ps1 +188 -1
  23. package/install.sh +254 -29
  24. package/package.json +15 -4
  25. package/src/cli/dash.js +110 -0
  26. package/src/cli/index.js +237 -106
  27. package/src/cli/managers/domain-manager.js +60 -40
  28. package/src/cli/managers/ssl-manager.js +47 -330
  29. package/src/cli/menu.js +156 -0
  30. package/src/cli/menus/cleanup.js +205 -0
  31. package/src/cli/menus/dashboard.js +92 -1
  32. package/src/cli/menus/runtime.js +236 -0
  33. package/src/cli/menus/service.js +764 -0
  34. package/src/cli/menus/settings.js +176 -8
  35. package/src/cli/menus/uninstall.js +167 -0
  36. package/src/cli/menus/update.js +222 -47
  37. package/src/core/acme-challenge.js +273 -0
  38. package/src/core/cert-operations.js +189 -0
  39. package/src/{dashboard/lib → core}/cert-reader.js +2 -2
  40. package/src/core/cert-renewal.js +494 -0
  41. package/src/core/cleanup.js +600 -0
  42. package/src/core/config.js +169 -2
  43. package/src/core/daemon/ipc.js +292 -0
  44. package/src/core/daemon/lock.js +294 -0
  45. package/src/core/daemon/run.js +241 -0
  46. package/src/core/daemon/stopRequest.js +162 -0
  47. package/src/core/db.js +37 -8
  48. package/src/core/deploy/apps.js +491 -0
  49. package/src/core/deploy/domainLink.js +200 -0
  50. package/src/core/deploy/engine.js +973 -0
  51. package/src/core/deploy/ezfile.js +361 -0
  52. package/src/core/deploy/github.js +239 -0
  53. package/src/core/deploy/githubApi.js +261 -0
  54. package/src/core/deploy/hookServer.js +325 -0
  55. package/src/core/deploy/hubCommands.js +267 -0
  56. package/src/core/deploy/launcher.js +57 -0
  57. package/src/core/deploy/status.js +91 -0
  58. package/src/core/deploy/store.js +398 -0
  59. package/src/core/domainNotifier.js +94 -28
  60. package/src/core/domains-db.js +234 -0
  61. package/src/core/events.js +94 -2
  62. package/src/core/hub/agent.js +842 -0
  63. package/src/core/hubLink.js +306 -0
  64. package/src/core/hubPermissions.js +430 -0
  65. package/src/core/installSource.js +162 -0
  66. package/src/core/jobs/bus.js +120 -0
  67. package/src/core/jobs/index.js +371 -0
  68. package/src/core/jobs/monitors.js +368 -0
  69. package/src/core/jobs/owner.js +217 -0
  70. package/src/core/jobs/revisionWatcher.js +106 -0
  71. package/src/core/nginx-apply.js +213 -0
  72. package/src/core/nginx-conf-generator.js +253 -17
  73. package/src/{dashboard/lib → core}/nginx-service.js +18 -9
  74. package/src/core/notifications/claim.js +214 -0
  75. package/src/core/notifications/dispatch.js +154 -0
  76. package/src/core/notifier.js +31 -1
  77. package/src/core/passwords.js +172 -0
  78. package/src/core/permissions.js +8 -4
  79. package/src/core/platform.js +709 -2
  80. package/src/core/probeCache.js +258 -0
  81. package/src/core/purge.js +372 -0
  82. package/src/core/runner.js +488 -0
  83. package/src/core/service/acl.js +226 -0
  84. package/src/core/service/dataDir.js +345 -0
  85. package/src/core/service/index.js +1128 -0
  86. package/src/core/service/legacy.js +218 -0
  87. package/src/core/service/runtime.js +446 -0
  88. package/src/core/service/runtimeUpdate.js +800 -0
  89. package/src/core/service/systemd.js +458 -0
  90. package/src/core/service/windowsPersonal.js +530 -0
  91. package/src/core/service/windowsService.js +576 -0
  92. package/src/core/service/winsw.js +260 -0
  93. package/src/core/setupCode.js +331 -0
  94. package/src/core/shell.js +70 -7
  95. package/src/core/ssl-issuer.js +627 -0
  96. package/src/core/updater.js +295 -0
  97. package/src/core/validators.js +99 -0
  98. package/src/dashboard/controllers/authController.js +302 -15
  99. package/src/dashboard/controllers/deploymentsController.js +479 -0
  100. package/src/dashboard/controllers/domainsController.js +80 -61
  101. package/src/dashboard/controllers/hubController.js +135 -0
  102. package/src/dashboard/controllers/nginxController.js +21 -3
  103. package/src/dashboard/controllers/processesController.js +368 -0
  104. package/src/dashboard/controllers/settingsController.js +180 -12
  105. package/src/dashboard/controllers/sslController.js +288 -10
  106. package/src/dashboard/lib/daemonBridge.js +163 -0
  107. package/src/dashboard/lib/localRequest.js +235 -0
  108. package/src/dashboard/lib/loginRateLimit.js +119 -0
  109. package/src/dashboard/lib/requireAuth.js +80 -0
  110. package/src/dashboard/public/js/app.js +489 -19
  111. package/src/dashboard/routes/auth.js +10 -10
  112. package/src/dashboard/routes/deployments.js +46 -0
  113. package/src/dashboard/routes/domains.js +9 -0
  114. package/src/dashboard/routes/hub.js +22 -0
  115. package/src/dashboard/routes/nginx.js +9 -0
  116. package/src/dashboard/routes/processes.js +29 -0
  117. package/src/dashboard/routes/settings.js +9 -0
  118. package/src/dashboard/routes/ssl.js +10 -0
  119. package/src/dashboard/server.js +288 -21
  120. package/src/dashboard/socketManager.js +171 -207
  121. package/src/dashboard/views/index.ejs +1 -0
  122. package/src/dashboard/views/partials/login.ejs +68 -7
  123. package/src/dashboard/views/partials/processes-panel.ejs +261 -0
  124. package/src/dashboard/views/partials/settings-panel.ejs +287 -0
  125. package/src/dashboard/views/partials/sidebar.ejs +2 -0
  126. package/src/dashboard/lib/domains-db.js +0 -51
@@ -0,0 +1,800 @@
1
+ /**
2
+ * core/service/runtimeUpdate.js
3
+ *
4
+ * Moving the installed service onto a different Node runtime, safely.
5
+ *
6
+ * ── Why this needs a command of its own ────────────────────────────────────
7
+ *
8
+ * The service is pinned to ONE Node binary on purpose (see runtime.js): a unit
9
+ * that resolves `node` from PATH breaks the moment a version manager repoints
10
+ * or removes it. The cost of that pin is that upgrading Node no longer reaches
11
+ * the service — it keeps running the old binary until something re-points it.
12
+ * Doing that by hand means editing a unit file, or copying an exe into
13
+ * ProgramData, and then discovering at the next restart whether the native
14
+ * modules still load.
15
+ *
16
+ * ── The order, which is the whole design ───────────────────────────────────
17
+ *
18
+ * 1. Decide the target, and refuse one below the package's minimum.
19
+ * 2. SMOKE TEST the new binary while the old one is still in place and the
20
+ * service is still running. Nothing is touched until this passes.
21
+ * 3. Stop the service.
22
+ * 4. Swap, keeping whatever is needed to put the old one back.
23
+ * 5. Start, and wait for the daemon's own heartbeat - not the service
24
+ * manager's "started", which only means a process was spawned.
25
+ * 6. On any failure in 4 or 5: roll back, start again, and say what happened.
26
+ *
27
+ * Step 2 is the one that matters. A runtime that cannot load better-sqlite3 is
28
+ * the common failure (an ABI built for another Node), and it is detectable
29
+ * before the service is stopped. Verifying afterwards would mean discovering
30
+ * it with the service already down.
31
+ *
32
+ * ── What it deliberately does not do ───────────────────────────────────────
33
+ *
34
+ * - It NEVER uninstalls a Node version. The old one is what rollback needs,
35
+ * and a version manager's other consumers are none of our business.
36
+ * - It never downloads a runtime. Either a version manager installs it, or
37
+ * the target is the Node already on the machine.
38
+ * - It never asks for a password. On Windows Server mode the runtime lives
39
+ * under ProgramData, so the swap needs an Administrator terminal; that is
40
+ * checked BEFORE anything is stopped, and the answer is the command to run.
41
+ */
42
+
43
+ import fs from 'fs';
44
+ import path from 'path';
45
+ import { createRequire } from 'module';
46
+
47
+ import { run } from '../shell.js';
48
+ import { isWindows, getDataDir, quoteExe } from '../platform.js';
49
+ import { detectInstallSource } from '../installSource.js';
50
+ import * as windowsPersonal from './windowsPersonal.js';
51
+ import { canWriteProgramData } from './windowsService.js';
52
+ import {
53
+ runtimeDir,
54
+ runtimeNodePath,
55
+ inspectLink,
56
+ linkRuntime,
57
+ verifyNativeModules,
58
+ detectVersionManager,
59
+ } from './runtime.js';
60
+ import {
61
+ MODES,
62
+ resolveMechanism,
63
+ appRoot,
64
+ entryScript,
65
+ recordedState,
66
+ recordRuntime,
67
+ waitForDaemon,
68
+ } from './index.js';
69
+
70
+ const require = createRequire(import.meta.url);
71
+
72
+ /** How long to watch a restarted daemon before calling the update good. */
73
+ export const VERIFY_MS = 10_000;
74
+
75
+ /** The previous `node.exe`, kept beside the new one so rollback is a rename. */
76
+ export const PREV_SUFFIX = '.prev';
77
+
78
+ // ─── Versions ────────────────────────────────────────────────────────────────
79
+
80
+ /** `v20.11.1` / `20.11.1` -> [20, 11, 1]; null when unparseable. */
81
+ export function parseVersion(value) {
82
+ const m = String(value ?? '').match(/(\d+)\.(\d+)\.(\d+)/);
83
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
84
+ }
85
+
86
+ /** -1, 0 or 1. Unparseable sorts last. */
87
+ export function compareVersions(a, b) {
88
+ const pa = parseVersion(a);
89
+ const pb = parseVersion(b);
90
+ if (!pa && !pb) return 0;
91
+ if (!pa) return 1;
92
+ if (!pb) return -1;
93
+ for (let i = 0; i < 3; i += 1) {
94
+ if (pa[i] !== pb[i]) return pa[i] > pb[i] ? 1 : -1;
95
+ }
96
+ return 0;
97
+ }
98
+
99
+ /**
100
+ * The minimum Node this package supports.
101
+ *
102
+ * Read from `engines.node` rather than written here again: a second literal is
103
+ * a second thing to forget.
104
+ *
105
+ * @returns {{ raw: string, major: number }}
106
+ */
107
+ export function minimumNode() {
108
+ const raw = String(require('../../../package.json').engines?.node ?? '>=18.0.0');
109
+ const major = Number(raw.match(/(\d+)/)?.[1] ?? 18);
110
+ return { raw, major };
111
+ }
112
+
113
+ /** Whether a version satisfies the package minimum. */
114
+ export function meetsMinimum(version, minimum = minimumNode()) {
115
+ const parsed = parseVersion(version);
116
+ if (!parsed) return false;
117
+ return parsed[0] >= minimum.major;
118
+ }
119
+
120
+ // ─── What is available ───────────────────────────────────────────────────────
121
+
122
+ /**
123
+ * The LTS versions a version manager can install.
124
+ *
125
+ * Both tools are asked in their own syntax and both are allowed to be absent;
126
+ * nvm-windows prints a table, nvm (Unix) one version per line and needs its
127
+ * script sourced first because it is a shell function, not a binary.
128
+ *
129
+ * @param {Object} [opts]
130
+ * @returns {Promise<{ manager: string|null, versions: string[], reason: string }>}
131
+ */
132
+ export async function listManagerVersions({ deps = {} } = {}) {
133
+ const exec = deps.run ?? run;
134
+
135
+ if (isWindows) {
136
+ const probe = await exec('nvm version', { timeout: 20_000 });
137
+ if (!answered(probe)) return { manager: null, versions: [], reason: 'nvm-windows is not installed' };
138
+
139
+ const listed = await exec('nvm list available', { timeout: 60_000 });
140
+ if (!listed.success) {
141
+ return { manager: 'nvm-windows', versions: [], reason: 'could not read the available versions' };
142
+ }
143
+
144
+ // nvm-windows prints four columns: CURRENT | LTS | OLD STABLE | OLD
145
+ // UNSTABLE. The LTS one is what a service should run, and it is the SECOND
146
+ // column — which is not `split('|')[1]`, because the row begins with a pipe
147
+ // and that produces an empty first cell. Reading index 1 took the CURRENT
148
+ // column and offered 23.x as "LTS"; dropping the empty cells makes the
149
+ // index mean what it says.
150
+ const versions = [];
151
+ for (const line of listed.stdout.split('\n')) {
152
+ const cells = line.split('|').map((c) => c.trim()).filter((c) => c.length > 0);
153
+ const lts = cells[1]?.match(/^\d+\.\d+\.\d+$/) ? cells[1] : null;
154
+ if (lts) versions.push(lts);
155
+ }
156
+ return { manager: 'nvm-windows', versions: dedupeDesc(versions), reason: 'ok' };
157
+ }
158
+
159
+ const probe = await exec(nvmShell('nvm --version'), { timeout: 20_000 });
160
+ if (!answered(probe)) return { manager: null, versions: [], reason: 'nvm is not installed' };
161
+
162
+ const listed = await exec(nvmShell('nvm ls-remote --lts'), { timeout: 60_000 });
163
+ if (!listed.success) {
164
+ return { manager: 'nvm', versions: [], reason: 'could not read the available versions' };
165
+ }
166
+
167
+ const versions = [];
168
+ for (const line of listed.stdout.split('\n')) {
169
+ const m = line.match(/v(\d+\.\d+\.\d+)/);
170
+ if (m) versions.push(m[1]);
171
+ }
172
+ return { manager: 'nvm', versions: dedupeDesc(versions), reason: 'ok' };
173
+ }
174
+
175
+ /**
176
+ * Whether a version probe actually answered.
177
+ *
178
+ * Exit code alone is not enough. A leftover `%APPDATA%\nvm` directory with no
179
+ * nvm in it makes `nvm version` exit 0 with NO output through a shell -
180
+ * measured on a real machine, where it made this code report nvm-windows as
181
+ * installed and then offer an empty version list. A version probe has to print
182
+ * something version-shaped to count.
183
+ */
184
+ function answered(result) {
185
+ return Boolean(result?.success) && /\d+\.\d+/.test(String(result.stdout ?? ''));
186
+ }
187
+
188
+ /** nvm is a shell function, so it has to be sourced before it can be called. */
189
+ function nvmShell(command) {
190
+ return `export NVM_DIR="$HOME/.nvm"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"; ${command}`;
191
+ }
192
+
193
+ /** Newest first, no duplicates. */
194
+ function dedupeDesc(versions) {
195
+ return [...new Set(versions)].sort((a, b) => compareVersions(b, a));
196
+ }
197
+
198
+ /**
199
+ * The Node on PATH, which on a machine with no version manager is the only
200
+ * thing we can re-pin to.
201
+ *
202
+ * `process.execPath` is NOT used: this CLI may itself be running under the
203
+ * pinned runtime (the service invokes it that way), and the question is what
204
+ * the user's shell resolves.
205
+ *
206
+ * @returns {Promise<{ path: string|null, version: string|null }>}
207
+ */
208
+ export async function detectSystemNode({ deps = {} } = {}) {
209
+ const exec = deps.run ?? run;
210
+
211
+ const which = await exec(isWindows ? 'where.exe node' : 'command -v node', { timeout: 15_000 });
212
+ const first = which.success ? which.stdout.split('\n')[0]?.trim() : '';
213
+ if (!first) return { path: null, version: null };
214
+
215
+ const probe = await exec(`${quoteExe(first)} --version`, { timeout: 15_000 });
216
+ return {
217
+ path: first,
218
+ version: probe.success ? probe.stdout.trim().replace(/^v/, '') : null,
219
+ };
220
+ }
221
+
222
+ /**
223
+ * Everything `ezz runtime status` and the update picker need.
224
+ *
225
+ * @param {Object} [opts]
226
+ * @returns {Promise<Object>}
227
+ */
228
+ export async function listTargets({ dataDir = getDataDir(), deps = {} } = {}) {
229
+ const mech = deps.mechanism ?? resolveMechanism();
230
+ const minimum = minimumNode();
231
+ const pinned = await describePinned({ dataDir, mech, deps });
232
+ const manager = await (deps.listManagerVersions ?? listManagerVersions)({ deps });
233
+ const system = await (deps.detectSystemNode ?? detectSystemNode)({ deps });
234
+ const source = (deps.detectInstallSource ?? detectInstallSource)();
235
+
236
+ const candidates = [];
237
+
238
+ for (const version of manager.versions.slice(0, 12)) {
239
+ candidates.push({
240
+ version,
241
+ source: manager.manager,
242
+ installable: true,
243
+ meetsMinimum: meetsMinimum(version, minimum),
244
+ isPinned: pinned.version ? compareVersions(version, pinned.version) === 0 : false,
245
+ });
246
+ }
247
+
248
+ // With no version manager - or with one that cannot list anything, which a
249
+ // broken install does - the Node already on the machine is the target: the
250
+ // user upgrades it however they normally would (MSI, apt, brew) and this
251
+ // re-pins the service to it.
252
+ if ((!manager.manager || manager.versions.length === 0) && system.version) {
253
+ candidates.push({
254
+ version: system.version,
255
+ source: 'system',
256
+ path: system.path,
257
+ installable: false,
258
+ meetsMinimum: meetsMinimum(system.version, minimum),
259
+ isPinned: pinned.version ? compareVersions(system.version, pinned.version) === 0 : false,
260
+ });
261
+ }
262
+
263
+ const usable = candidates.filter((c) => c.meetsMinimum && !c.isPinned);
264
+
265
+ return {
266
+ mechanism: mech.mechanism,
267
+ mode: mech.mode,
268
+ dataDir,
269
+ minimum,
270
+ pinned,
271
+ manager,
272
+ systemNode: system,
273
+ installSource: source,
274
+ candidates,
275
+ // The one thing a caller has to know before offering anything.
276
+ nothingToUpdate: usable.length === 0,
277
+ hint: usable.length === 0 ? upgradeHint({ manager, system, pinned }) : null,
278
+ };
279
+ }
280
+
281
+ /** What the pinned runtime is, per mechanism. */
282
+ async function describePinned({ dataDir, mech, deps = {} }) {
283
+ const exec = deps.run ?? run;
284
+ const recorded = (deps.recordedState ?? recordedState)();
285
+
286
+ if (!isWindows) {
287
+ const link = inspectLink(dataDir);
288
+ const probe = link.exists && !link.broken
289
+ ? await exec(`${quoteExe(link.link)} --version`, { timeout: 15_000 })
290
+ : null;
291
+ return {
292
+ kind: 'symlink',
293
+ path: link.link,
294
+ target: link.target,
295
+ exists: link.exists,
296
+ broken: link.broken,
297
+ version: probe?.success ? probe.stdout.trim().replace(/^v/, '') : null,
298
+ };
299
+ }
300
+
301
+ const copied = runtimeNodePath(dataDir);
302
+ if (mech.mode === MODES.SERVER || fs.existsSync(copied)) {
303
+ const probe = fs.existsSync(copied)
304
+ ? await exec(`${quoteExe(copied)} --version`, { timeout: 15_000 })
305
+ : null;
306
+ return {
307
+ kind: 'copy',
308
+ path: copied,
309
+ exists: fs.existsSync(copied),
310
+ broken: Boolean(probe && !probe.success),
311
+ version: probe?.success ? probe.stdout.trim().replace(/^v/, '') : null,
312
+ };
313
+ }
314
+
315
+ const nodeExe = recorded.nodeExe ?? null;
316
+ const exists = Boolean(nodeExe && fs.existsSync(nodeExe));
317
+ const probe = exists ? await exec(`${quoteExe(nodeExe)} --version`, { timeout: 15_000 }) : null;
318
+ return {
319
+ kind: 'recorded',
320
+ path: nodeExe,
321
+ exists,
322
+ broken: Boolean(nodeExe && !exists),
323
+ version: probe?.success ? probe.stdout.trim().replace(/^v/, '') : null,
324
+ manager: nodeExe ? detectVersionManager(nodeExe) : { managed: false, manager: null },
325
+ };
326
+ }
327
+
328
+ /** What to tell someone who has nothing to update to. */
329
+ function upgradeHint({ manager, system, pinned }) {
330
+ const lines = [];
331
+
332
+ if (manager.manager) {
333
+ lines.push(`${manager.manager} has no LTS version newer than the pinned ${pinned.version ?? 'runtime'}.`);
334
+ lines.push('');
335
+ lines.push('Refresh its list and try again:');
336
+ lines.push(isWindows ? ' nvm list available' : ' nvm ls-remote --lts');
337
+ return lines;
338
+ }
339
+
340
+ lines.push(
341
+ system.version
342
+ ? `The Node on this machine (v${system.version}) is the one the service already uses.`
343
+ : 'No Node version manager is installed and no node was found on PATH.',
344
+ );
345
+ lines.push('');
346
+ lines.push('Upgrade Node first, then run `ezz runtime update` to re-pin the service:');
347
+ if (isWindows) {
348
+ lines.push(' nvm-windows https://github.com/coreybutler/nvm-windows/releases');
349
+ lines.push(' or the official installer https://nodejs.org/en/download');
350
+ } else {
351
+ lines.push(' nvm https://github.com/nvm-sh/nvm#installing-and-updating');
352
+ lines.push(' or your distribution\'s package manager / https://nodejs.org/en/download');
353
+ }
354
+ return lines;
355
+ }
356
+
357
+ // ─── Installing a target ─────────────────────────────────────────────────────
358
+
359
+ /**
360
+ * Installs a version with the detected version manager and returns the path to
361
+ * its binary.
362
+ *
363
+ * `system` targets are already installed by definition, so nothing runs.
364
+ *
365
+ * @param {Object} opts
366
+ * @returns {Promise<{ ok: boolean, nodeExe?: string, reason?: string }>}
367
+ */
368
+ export async function installTarget({ target, deps = {} } = {}) {
369
+ const exec = deps.run ?? run;
370
+
371
+ if (!target?.version) return { ok: false, reason: 'no target version given' };
372
+
373
+ if (target.source === 'system') {
374
+ if (!target.path) return { ok: false, reason: 'the system node path is unknown' };
375
+ return { ok: true, nodeExe: target.path };
376
+ }
377
+
378
+ if (target.source === 'nvm-windows') {
379
+ const installed = await exec(`nvm install ${target.version}`, { timeout: 600_000 });
380
+ if (!installed.success) {
381
+ return { ok: false, reason: `nvm install ${target.version} failed: ${trimOutput(installed)}` };
382
+ }
383
+ // nvm-windows keeps versions under its own root; ask it rather than guess.
384
+ const root = await exec('nvm root', { timeout: 15_000 });
385
+ const base = root.success ? root.stdout.replace(/^.*?:/, '').trim() : '';
386
+ const candidate = base ? path.join(base, `v${target.version}`, 'node.exe') : '';
387
+ if (candidate && fs.existsSync(candidate)) return { ok: true, nodeExe: candidate };
388
+ return {
389
+ ok: false,
390
+ reason: `nvm reported success but node.exe was not found for v${target.version}`,
391
+ };
392
+ }
393
+
394
+ const installed = await exec(nvmShell(`nvm install ${target.version}`), { timeout: 600_000 });
395
+ if (!installed.success) {
396
+ return { ok: false, reason: `nvm install ${target.version} failed: ${trimOutput(installed)}` };
397
+ }
398
+
399
+ const located = await exec(nvmShell(`nvm which ${target.version}`), { timeout: 20_000 });
400
+ const nodeExe = located.success ? located.stdout.trim().split('\n').pop()?.trim() : '';
401
+ if (nodeExe && fs.existsSync(nodeExe)) return { ok: true, nodeExe };
402
+
403
+ return { ok: false, reason: `nvm installed v${target.version} but its path could not be resolved` };
404
+ }
405
+
406
+ function trimOutput(result) {
407
+ return `${result.stdout ?? ''}\n${result.stderr ?? ''}`.trim().slice(0, 300);
408
+ }
409
+
410
+ // ─── The smoke test ──────────────────────────────────────────────────────────
411
+
412
+ /**
413
+ * Proves a candidate binary can actually run Easy DevOps, before anything is
414
+ * touched.
415
+ *
416
+ * Three checks, in increasing cost:
417
+ * 1. it runs at all, and its version meets the minimum
418
+ * 2. it can load the native module (`verifyNativeModules`, the usual failure)
419
+ * 3. it can execute the CLI entry point - against a THROWAWAY data
420
+ * directory, so a smoke test can never read or write the real one
421
+ *
422
+ * @param {Object} opts
423
+ * @returns {Promise<{ ok: boolean, version?: string, abi?: string, reason?: string, fix?: string }>}
424
+ */
425
+ export async function smokeTest({ nodeExe, appDir = appRoot(), entry = entryScript(), probeDataDir, deps = {} } = {}) {
426
+ const exec = deps.run ?? run;
427
+
428
+ const versionProbe = await exec(`${quoteExe(nodeExe)} --version`, { timeout: 20_000 });
429
+ if (!versionProbe.success) {
430
+ return { ok: false, reason: `${nodeExe} did not run: ${trimOutput(versionProbe)}` };
431
+ }
432
+
433
+ const version = versionProbe.stdout.trim().replace(/^v/, '');
434
+ const minimum = minimumNode();
435
+ if (!meetsMinimum(version, minimum)) {
436
+ return {
437
+ ok: false,
438
+ version,
439
+ reason: `v${version} is below the minimum this version of Easy DevOps supports (${minimum.raw}).`,
440
+ fix: `Choose Node ${minimum.major} or newer.`,
441
+ };
442
+ }
443
+
444
+ const native = await (deps.verifyNativeModules ?? verifyNativeModules)({ nodeExe, appDir });
445
+ if (!native.ok) return { ok: false, version, reason: native.reason, fix: native.fix };
446
+
447
+ // The entry point, with its own data directory. EZ_DEV is NOT set: this must
448
+ // exercise the production path, and the isolated directory is what keeps it
449
+ // harmless.
450
+ const dir = probeDataDir ?? path.join(runtimeDir(getDataDir()), 'smoke');
451
+ try {
452
+ fs.mkdirSync(dir, { recursive: true });
453
+ } catch (err) {
454
+ return { ok: false, version, reason: `could not create the smoke-test directory: ${err.message}` };
455
+ }
456
+
457
+ const entryProbe = await exec(`${quoteExe(nodeExe)} "${entry}" --version`, {
458
+ timeout: 60_000,
459
+ cwd: appDir,
460
+ env: { ...process.env, EASY_DEVOPS_DATA_DIR: dir },
461
+ });
462
+
463
+ try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ }
464
+
465
+ if (!entryProbe.success) {
466
+ return {
467
+ ok: false,
468
+ version,
469
+ abi: native.abi,
470
+ reason: `v${version} could not run Easy DevOps itself: ${trimOutput(entryProbe)}`,
471
+ };
472
+ }
473
+
474
+ return { ok: true, version, abi: native.abi };
475
+ }
476
+
477
+ // ─── The swap ────────────────────────────────────────────────────────────────
478
+
479
+ /**
480
+ * Points the service at a new binary, and returns how to undo it.
481
+ *
482
+ * Every branch returns a `rollback()` that restores exactly what it changed —
483
+ * the caller does not have to know which mechanism it was.
484
+ *
485
+ * @param {Object} opts
486
+ * @returns {Promise<{ ok: boolean, reason?: string, needsElevation?: boolean, rollback?: () => Promise<Object>, detail?: string }>}
487
+ */
488
+ export async function applyRuntime({
489
+ nodeExe,
490
+ dataDir = getDataDir(),
491
+ mech = resolveMechanism(),
492
+ log = () => {},
493
+ deps = {},
494
+ } = {}) {
495
+ if (!isWindows) return applyLinux({ nodeExe, dataDir, log, deps });
496
+ if (mech.mode === MODES.SERVER) return applyWindowsServer({ nodeExe, dataDir, log, deps });
497
+ return applyWindowsPersonal({ nodeExe, dataDir, log, deps });
498
+ }
499
+
500
+ /** Linux: re-point the symlink. */
501
+ async function applyLinux({ nodeExe, dataDir, log, deps = {} }) {
502
+ const before = inspectLink(dataDir);
503
+ const link = (deps.linkRuntime ?? linkRuntime)({ dataDir, nodeExe });
504
+ if (!link.ok) return { ok: false, reason: link.reason };
505
+
506
+ log(`Re-pointed ${link.link} at ${link.target}`);
507
+
508
+ return {
509
+ ok: true,
510
+ detail: `${link.link} -> ${link.target}`,
511
+ async rollback() {
512
+ if (!before.exists || !before.target) return { ok: false, reason: 'there was no previous link to restore' };
513
+ const back = (deps.linkRuntime ?? linkRuntime)({ dataDir, nodeExe: before.target });
514
+ return back.ok ? { ok: true, detail: `restored ${before.target}` } : back;
515
+ },
516
+ };
517
+ }
518
+
519
+ /**
520
+ * Windows Server mode: replace node.exe in the admin-only runtime directory,
521
+ * keeping the old one as node.exe.prev, and make the app copy's native modules
522
+ * match the new ABI.
523
+ *
524
+ * The app copy is the subtle part. `<runtime>/app/node_modules` holds
525
+ * better-sqlite3 built for the OLD ABI; pairing it with a new node.exe fails at
526
+ * require time with an error that never mentions Node versions. So after the
527
+ * swap the module is rebuilt in the copy, and if that fails (no build tools on
528
+ * a server, which is normal) the copy is refreshed from the package root, whose
529
+ * modules were built by whatever npm the user runs.
530
+ */
531
+ async function applyWindowsServer({ nodeExe, dataDir, log, deps = {} }) {
532
+ const canWrite = (deps.canWriteProgramData ?? canWriteProgramData)();
533
+ if (!canWrite) {
534
+ return {
535
+ ok: false,
536
+ needsElevation: true,
537
+ reason: [
538
+ 'Updating the runtime writes under ProgramData, which needs an Administrator terminal.',
539
+ '',
540
+ 'Right-click PowerShell -> "Run as administrator", then:',
541
+ '',
542
+ ' ezz runtime update',
543
+ '',
544
+ 'No password is needed - only elevation.',
545
+ ].join('\n'),
546
+ };
547
+ }
548
+
549
+ const dest = runtimeNodePath(dataDir);
550
+ const prev = `${dest}${PREV_SUFFIX}`;
551
+ const appDir = path.join(runtimeDir(dataDir), 'app');
552
+ const hadPrevious = fs.existsSync(dest);
553
+
554
+ try {
555
+ if (hadPrevious) {
556
+ // One generation only: the older .prev has already been superseded, and
557
+ // `ezz cleanup` is what removes it.
558
+ try { fs.rmSync(prev, { force: true }); } catch { /* nothing there */ }
559
+ fs.renameSync(dest, prev);
560
+ log(`Kept the previous runtime at ${prev}`);
561
+ }
562
+ fs.copyFileSync(fs.realpathSync(nodeExe), dest);
563
+ log(`Copied ${nodeExe} -> ${dest}`);
564
+ } catch (err) {
565
+ // Put it back immediately: a half-swapped runtime directory is the one
566
+ // state nobody can diagnose.
567
+ if (hadPrevious && !fs.existsSync(dest) && fs.existsSync(prev)) {
568
+ try { fs.renameSync(prev, dest); } catch { /* reported below */ }
569
+ }
570
+ return { ok: false, reason: `could not replace ${dest}: ${err.message}` };
571
+ }
572
+
573
+ const rollback = async () => {
574
+ if (!fs.existsSync(prev)) return { ok: false, reason: 'there is no previous runtime to restore' };
575
+ try {
576
+ fs.rmSync(dest, { force: true });
577
+ fs.renameSync(prev, dest);
578
+ return { ok: true, detail: `restored ${dest} from ${PREV_SUFFIX}` };
579
+ } catch (err) {
580
+ return { ok: false, reason: `could not restore ${dest}: ${err.message}` };
581
+ }
582
+ };
583
+
584
+ const native = await fixAppCopyModules({ nodeExe: dest, appDir, log, deps });
585
+ if (!native.ok) return { ok: false, reason: native.reason, fix: native.fix, rollback };
586
+
587
+ return { ok: true, detail: `${dest} (${native.detail})`, rollback };
588
+ }
589
+
590
+ /**
591
+ * Makes the app copy's native modules load under a new node.exe.
592
+ *
593
+ * Verify first: when the ABI did not change there is nothing to do, and
594
+ * rebuilding anyway would be a long pointless step on every patch upgrade.
595
+ */
596
+ async function fixAppCopyModules({ nodeExe, appDir, log, deps = {} }) {
597
+ const exec = deps.run ?? run;
598
+ const verify = deps.verifyNativeModules ?? verifyNativeModules;
599
+
600
+ if (!fs.existsSync(appDir)) {
601
+ return { ok: true, detail: 'no app copy to fix' };
602
+ }
603
+
604
+ const first = await verify({ nodeExe, appDir });
605
+ if (first.ok) return { ok: true, detail: 'native modules already match' };
606
+
607
+ log('The native modules were built for a different Node ABI; rebuilding in the copy...');
608
+ const rebuilt = await exec('npm rebuild better-sqlite3', { cwd: appDir, timeout: 600_000 });
609
+
610
+ if (rebuilt.success) {
611
+ const after = await verify({ nodeExe, appDir });
612
+ if (after.ok) return { ok: true, detail: 'native modules rebuilt' };
613
+ }
614
+
615
+ // No build tools is the normal case on a server. The package root's modules
616
+ // were built by the user's own npm, so copying them is the realistic fix.
617
+ log('Rebuilding did not work; refreshing node_modules from the package instead...');
618
+ const from = path.join(appRoot(), 'node_modules');
619
+ if (fs.existsSync(from)) {
620
+ try {
621
+ fs.cpSync(from, path.join(appDir, 'node_modules'), { recursive: true, force: true });
622
+ } catch (err) {
623
+ return { ok: false, reason: `could not refresh the runtime copy's node_modules: ${err.message}` };
624
+ }
625
+ const after = await verify({ nodeExe, appDir });
626
+ if (after.ok) return { ok: true, detail: 'node_modules refreshed from the package' };
627
+ return { ok: false, reason: after.reason, fix: after.fix };
628
+ }
629
+
630
+ return { ok: false, reason: first.reason, fix: first.fix };
631
+ }
632
+
633
+ /** Windows Personal mode: the recorded path, and the supervisor that uses it. */
634
+ async function applyWindowsPersonal({ nodeExe, dataDir, log, deps = {} }) {
635
+ const recorded = (deps.recordedState ?? recordedState)();
636
+ const before = recorded.nodeExe ?? null;
637
+
638
+ const repaired = (deps.windowsPersonal ?? windowsPersonal).repair({
639
+ dataDir,
640
+ entry: entryScript(),
641
+ nodeExe,
642
+ log,
643
+ });
644
+ if (!repaired.ok) return { ok: false, reason: repaired.reason };
645
+
646
+ (deps.recordRuntime ?? recordRuntime)({ nodeExe: repaired.nodeExe ?? nodeExe });
647
+ log(`Recorded the service runtime as ${repaired.nodeExe ?? nodeExe}`);
648
+
649
+ return {
650
+ ok: true,
651
+ detail: repaired.nodeExe ?? nodeExe,
652
+ async rollback() {
653
+ if (!before) return { ok: false, reason: 'there was no previous runtime path recorded' };
654
+ const back = (deps.windowsPersonal ?? windowsPersonal).repair({
655
+ dataDir,
656
+ entry: entryScript(),
657
+ nodeExe: before,
658
+ log,
659
+ });
660
+ if (!back.ok) return back;
661
+ (deps.recordRuntime ?? recordRuntime)({ nodeExe: before });
662
+ return { ok: true, detail: `restored ${before}` };
663
+ },
664
+ };
665
+ }
666
+
667
+ // ─── The whole operation ─────────────────────────────────────────────────────
668
+
669
+ /**
670
+ * Updates the service's runtime, verifying and rolling back on failure.
671
+ *
672
+ * @param {Object} opts
673
+ * @param {Object} opts.target A candidate from listTargets()
674
+ * @param {(line: string) => void} [opts.log]
675
+ * @returns {Promise<Object>}
676
+ */
677
+ export async function update({
678
+ target,
679
+ dataDir = getDataDir(),
680
+ log = () => {},
681
+ deps = {},
682
+ } = {}) {
683
+ const mech = deps.mechanism ?? resolveMechanism();
684
+ const service = deps.service ?? (await import('./index.js'));
685
+
686
+ // 1. The target has to be installable and allowed.
687
+ if (!target?.version) return { ok: false, step: 'target', reason: 'no target version was chosen' };
688
+ if (!meetsMinimum(target.version)) {
689
+ const minimum = minimumNode();
690
+ return {
691
+ ok: false,
692
+ step: 'target',
693
+ reason: `v${target.version} is below the minimum this version of Easy DevOps supports (${minimum.raw}).`,
694
+ };
695
+ }
696
+
697
+ log(`Installing Node v${target.version}...`);
698
+ const installed = await (deps.installTarget ?? installTarget)({ target, deps });
699
+ if (!installed.ok) return { ok: false, step: 'install', reason: installed.reason };
700
+ log(` runtime: ${installed.nodeExe}`);
701
+
702
+ // 2. Smoke test BEFORE anything is touched. The service is still running.
703
+ log('Smoke-testing Easy DevOps with it, before changing anything...');
704
+ const smoke = await (deps.smokeTest ?? smokeTest)({ nodeExe: installed.nodeExe, deps });
705
+ if (!smoke.ok) {
706
+ return {
707
+ ok: false,
708
+ step: 'smoke',
709
+ reason: smoke.reason,
710
+ fix: smoke.fix,
711
+ // Nothing was stopped or changed, which is worth saying plainly.
712
+ untouched: true,
713
+ };
714
+ }
715
+ log(` v${smoke.version} runs Easy DevOps and loads its native modules.`);
716
+
717
+ // 3. Stop.
718
+ log('Stopping the service...');
719
+ const stopped = await service.stop({ log });
720
+ if (!stopped.ok && !stopped.alreadyStopped) {
721
+ return {
722
+ ok: false,
723
+ step: 'stop',
724
+ reason: stopped.reason,
725
+ needsElevation: stopped.needsElevation ?? false,
726
+ untouched: true,
727
+ };
728
+ }
729
+
730
+ // 4. Swap.
731
+ log('Swapping the runtime...');
732
+ const applied = await (deps.applyRuntime ?? applyRuntime)({
733
+ nodeExe: installed.nodeExe,
734
+ dataDir,
735
+ mech,
736
+ log,
737
+ deps,
738
+ });
739
+
740
+ if (!applied.ok) {
741
+ // The swap can fail in two places: before the binary was replaced (an
742
+ // elevation refusal, a copy error) and after it (the app copy's native
743
+ // modules could not be made to load). The second one leaves a new binary
744
+ // in place, so it hands back a rollback and it has to be used.
745
+ const back = applied.rollback ? await applied.rollback() : null;
746
+ const restarted = await service.start({ log });
747
+ return {
748
+ ok: false,
749
+ step: 'swap',
750
+ reason: applied.reason,
751
+ fix: applied.fix,
752
+ needsElevation: applied.needsElevation ?? false,
753
+ rolledBack: back ? back.ok : false,
754
+ rollbackDetail: back ? (back.detail ?? back.reason) : null,
755
+ restarted: restarted.ok,
756
+ };
757
+ }
758
+
759
+ // 5. Start and verify against the daemon's own heartbeat.
760
+ log('Starting the service on the new runtime...');
761
+ const started = await service.start({ log });
762
+ const alive = started.ok
763
+ ? await (deps.waitForDaemon ?? waitForDaemon)({ dataDir, timeoutMs: deps.verifyMs ?? VERIFY_MS })
764
+ : { alive: false, waitedMs: 0 };
765
+
766
+ if (started.ok && alive.alive) {
767
+ log(` the daemon reported in after ${alive.waitedMs}ms (pid ${alive.lock?.pid ?? '?'}).`);
768
+ return {
769
+ ok: true,
770
+ version: smoke.version,
771
+ abi: smoke.abi,
772
+ nodeExe: installed.nodeExe,
773
+ mechanism: mech.mechanism,
774
+ detail: applied.detail,
775
+ waitedMs: alive.waitedMs,
776
+ };
777
+ }
778
+
779
+ // 6. Roll back.
780
+ const why = started.ok
781
+ ? `it started but the daemon did not report in within ${Math.round((deps.verifyMs ?? VERIFY_MS) / 1000)}s`
782
+ : `it could not be started: ${started.reason}`;
783
+
784
+ log(`The new runtime did not work (${why}). Rolling back...`);
785
+ const back = applied.rollback ? await applied.rollback() : { ok: false, reason: 'no rollback was available' };
786
+ const restarted = back.ok ? await service.start({ log }) : { ok: false };
787
+ const aliveAgain = restarted.ok
788
+ ? await (deps.waitForDaemon ?? waitForDaemon)({ dataDir, timeoutMs: deps.verifyMs ?? VERIFY_MS })
789
+ : { alive: false };
790
+
791
+ return {
792
+ ok: false,
793
+ step: 'verify',
794
+ reason: why,
795
+ rolledBack: back.ok,
796
+ rollbackDetail: back.detail ?? back.reason,
797
+ restored: Boolean(restarted.ok && aliveAgain.alive),
798
+ version: smoke.version,
799
+ };
800
+ }