easy-devops 1.2.1 → 1.3.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.
Files changed (126) hide show
  1. package/README.md +97 -6
  2. package/dist/ui/assets/index-B6zdwEnG.css +1 -0
  3. package/dist/ui/assets/index-Cy0oNmul.js +442 -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 +221 -65
  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 +39 -52
  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 +171 -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 +9 -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,218 @@
1
+ /**
2
+ * core/service/legacy.js
3
+ *
4
+ * Finding and removing what the previous background-service design left behind.
5
+ *
6
+ * Easy DevOps used to keep itself running through PM2, with three different
7
+ * boot hooks depending on platform and mode:
8
+ *
9
+ * - a PM2 app named `ez-dashboard` (or `ez-dashboard-dev`)
10
+ * - a Windows Task Scheduler task `EasyDevOps-PM2`, which needed the user's
11
+ * password — the reason the whole approach was replaced
12
+ * - a Windows Startup-folder launcher `easy-devops-pm2.cmd`
13
+ *
14
+ * None of these are created any more. They are still DETECTED, because an
15
+ * upgrade finds them on a machine that used the old design, and leaving them
16
+ * in place means two things trying to run the dashboard at boot.
17
+ *
18
+ * ── The rule that matters ──────────────────────────────────────────────────
19
+ *
20
+ * **Only our own PM2 apps are ever touched.** `runner.js` still exists and the
21
+ * Processes page still manages the user's own applications, which is a
22
+ * supported feature. An over-eager cleanup that stopped or deleted somebody's
23
+ * production app while "uninstalling our service" would be unforgivable, so
24
+ * every PM2 operation here is by exact name from `EZ_APP_NAMES` and nothing
25
+ * iterates over the full app list to decide what to remove.
26
+ *
27
+ * Removal is also never automatic: install and uninstall OFFER it. The user
28
+ * may have reasons for what is on their machine.
29
+ */
30
+
31
+ import fs from 'fs';
32
+
33
+ import * as runner from '../runner.js';
34
+ import {
35
+ isWindows,
36
+ getStartupFolder,
37
+ WINDOWS_BOOT_TASK,
38
+ WINDOWS_STARTUP_FILE,
39
+ windowsBootTaskDeleteCmd,
40
+ windowsBootTaskQueryCmd,
41
+ } from '../platform.js';
42
+ import { run as shellRun } from '../shell.js';
43
+ import path from 'path';
44
+
45
+ /**
46
+ * Everything from the old design that is still present.
47
+ *
48
+ * Deliberately read-only and cheap: it is called by `status`, by install and
49
+ * by uninstall, and a status read must never change anything — nor start the
50
+ * PM2 daemon, which every pm2 command would (see runner.isDaemonRunning).
51
+ *
52
+ * @param {Object} [overrides]
53
+ * @param {Function} [overrides.run]
54
+ * @param {string|null} [overrides.startupDir]
55
+ * @returns {Promise<{ found: boolean, items: Array<{ kind: string, name: string, detail: string, removal: string }> }>}
56
+ */
57
+ export async function detectLegacy(overrides = {}) {
58
+ const run = overrides.run ?? shellRun;
59
+ const startupDir = overrides.startupDir ?? getStartupFolder();
60
+
61
+ const items = [];
62
+
63
+ // ── The PM2 app ───────────────────────────────────────────────────────────
64
+ //
65
+ // Only asked if the daemon is already up. If PM2 is not running then no PM2
66
+ // app is running either, and starting its daemon to discover that would be a
67
+ // side effect in a status read.
68
+ try {
69
+ if (runner.isDaemonRunning()) {
70
+ const pm2 = await runner.detect({ probeVersion: false });
71
+ if (pm2.installed) {
72
+ const listed = await runner.list({ pm2Path: pm2.path ?? 'pm2' });
73
+ if (listed.ok) {
74
+ for (const app of listed.apps ?? []) {
75
+ if (!runner.isEzApp(app.name)) continue;
76
+ items.push({
77
+ kind: 'pm2-app',
78
+ name: app.name,
79
+ detail: `PM2 app "${app.name}" (${app.status ?? 'unknown'}) — the old way of keeping the dashboard running.`,
80
+ removal: `pm2 delete ${app.name} && pm2 save`,
81
+ });
82
+ }
83
+ }
84
+ }
85
+ }
86
+ } catch { /* PM2 absent or unreadable: nothing to report */ }
87
+
88
+ if (isWindows) {
89
+ // ── The scheduled task ──────────────────────────────────────────────────
90
+ try {
91
+ const task = await run(windowsBootTaskQueryCmd(), { timeout: 15_000 });
92
+ if (task.success && new RegExp(WINDOWS_BOOT_TASK, 'i').test(task.stdout)) {
93
+ items.push({
94
+ kind: 'scheduled-task',
95
+ name: WINDOWS_BOOT_TASK,
96
+ detail: `Task Scheduler task "${WINDOWS_BOOT_TASK}" starts the old PM2 service at boot. `
97
+ + 'It holds a stored password, which is why this mode was removed.',
98
+ removal: `schtasks /Delete /TN "${WINDOWS_BOOT_TASK}" /F`,
99
+ });
100
+ }
101
+ } catch { /* schtasks missing: nothing to report */ }
102
+
103
+ // ── The Startup launcher ────────────────────────────────────────────────
104
+ const launcher = startupDir ? path.join(startupDir, WINDOWS_STARTUP_FILE) : null;
105
+ if (launcher && fs.existsSync(launcher)) {
106
+ items.push({
107
+ kind: 'startup-file',
108
+ name: WINDOWS_STARTUP_FILE,
109
+ path: launcher,
110
+ detail: `${launcher} runs \`pm2 resurrect\` when you log in.`,
111
+ removal: `del "${launcher}"`,
112
+ });
113
+ }
114
+ }
115
+
116
+ return { found: items.length > 0, items };
117
+ }
118
+
119
+ /**
120
+ * Removes the legacy items it is given.
121
+ *
122
+ * Takes the detected items rather than re-detecting, so the user is acting on
123
+ * exactly what they were shown.
124
+ *
125
+ * @param {Object} opts
126
+ * @param {Array} opts.items From detectLegacy()
127
+ * @param {Function} [opts.run]
128
+ * @param {(line: string) => void} [opts.log]
129
+ * @returns {Promise<{ ok: boolean, removed: string[], failed: Array<{ name: string, reason: string }> }>}
130
+ */
131
+ export async function removeLegacy({ items = [], run = shellRun, log = () => {} } = {}) {
132
+ const removed = [];
133
+ const failed = [];
134
+
135
+ for (const item of items) {
136
+ try {
137
+ if (item.kind === 'pm2-app') {
138
+ // Guarded again at the point of deletion, not only at detection: this
139
+ // function can be called with a list from anywhere, and deleting a PM2
140
+ // app that is not ours must be impossible rather than merely unlikely.
141
+ if (!runner.isEzApp(item.name)) {
142
+ failed.push({ name: item.name, reason: 'refusing to delete a PM2 app that is not ours' });
143
+ continue;
144
+ }
145
+
146
+ const pm2 = await runner.detect({ probeVersion: false });
147
+ const pm2Path = pm2.path ?? 'pm2';
148
+
149
+ const del = await runner.del(item.name, { pm2Path });
150
+ if (!del.ok) {
151
+ failed.push({ name: item.name, reason: del.output || 'pm2 delete failed' });
152
+ continue;
153
+ }
154
+
155
+ // `pm2 save` rewrites the resurrect list. Without it the app comes back
156
+ // on the next `pm2 resurrect` — and crucially, saving also PRESERVES
157
+ // every other app the user has, which is why the whole list is saved
158
+ // rather than the entry being edited out of the dump file.
159
+ await runner.save({ pm2Path });
160
+
161
+ removed.push(item.name);
162
+ log(` removed PM2 app ${item.name}`);
163
+ continue;
164
+ }
165
+
166
+ if (item.kind === 'scheduled-task') {
167
+ // `--%` is the PowerShell stop-parsing token. Without it PowerShell
168
+ // mangles the quotes around the task name before schtasks sees them —
169
+ // measured against a stand-in executable that printed its argv.
170
+ const result = await run(windowsBootTaskDeleteCmd(), { timeout: 20_000 });
171
+ if (!result.success) {
172
+ const output = `${result.stdout ?? ''}${result.stderr ?? ''}`;
173
+ failed.push({
174
+ name: item.name,
175
+ reason: /access is denied/i.test(output)
176
+ ? 'deleting a scheduled task needs an Administrator PowerShell'
177
+ : output.trim().slice(0, 300) || 'schtasks failed',
178
+ });
179
+ continue;
180
+ }
181
+ removed.push(item.name);
182
+ log(` removed scheduled task ${item.name}`);
183
+ continue;
184
+ }
185
+
186
+ if (item.kind === 'startup-file') {
187
+ if (!item.path) {
188
+ failed.push({ name: item.name, reason: 'the item carries no launcher path' });
189
+ continue;
190
+ }
191
+ const launcher = item.path;
192
+ fs.rmSync(launcher, { force: true });
193
+ removed.push(item.name);
194
+ log(` removed startup launcher ${launcher}`);
195
+ continue;
196
+ }
197
+
198
+ failed.push({ name: item.name, reason: `unknown legacy item kind: ${item.kind}` });
199
+ } catch (err) {
200
+ failed.push({ name: item.name, reason: err.message });
201
+ }
202
+ }
203
+
204
+ return { ok: failed.length === 0, removed, failed };
205
+ }
206
+
207
+ /** A short human summary for a prompt. */
208
+ export function describeLegacy(items) {
209
+ if (!items?.length) return 'Nothing from the old PM2-based service was found.';
210
+
211
+ return [
212
+ 'The old PM2-based service is still set up on this machine:',
213
+ ...items.map((i) => ` • ${i.detail}`),
214
+ '',
215
+ 'Leaving it in place means two things try to run Easy DevOps at boot.',
216
+ 'Your own PM2 applications are never touched.',
217
+ ].join('\n');
218
+ }
@@ -0,0 +1,446 @@
1
+ /**
2
+ * core/service/runtime.js
3
+ *
4
+ * Pinning the Node runtime the service uses, so a version manager cannot break
5
+ * it later.
6
+ *
7
+ * ── The problem this solves ────────────────────────────────────────────────
8
+ *
9
+ * A service unit records an absolute path to a `node` binary. If that path is
10
+ * inside nvm — `~/.nvm/versions/node/v20.11.0/bin/node`, or on Windows the
11
+ * `nvm use` shim — then the service breaks the moment the user runs
12
+ * `nvm install 22` and the old version is removed, or `nvm use` repoints the
13
+ * shim. The failure is confusing: the service simply stops starting, with a
14
+ * "file not found" in a log nobody is watching.
15
+ *
16
+ * Three strategies, because the three situations are genuinely different:
17
+ *
18
+ * - **Linux**: a symlink at `<dataDir>/runtime/node` pointing at one specific
19
+ * Node binary. The systemd unit uses the link, so re-pointing it is a
20
+ * one-line fix (`ezz service repair`) rather than editing a unit file and
21
+ * reloading systemd.
22
+ *
23
+ * - **Windows Server mode**: `node.exe` and the application are COPIED into
24
+ * `C:\ProgramData\easy-devops\runtime`, which only administrators can
25
+ * write. Copying rather than linking because the service runs as a virtual
26
+ * account that may not be able to read the user's profile at all, and
27
+ * because `npm update` replaces the package directory under the user — an
28
+ * upgrade would otherwise swap the code under a running service.
29
+ *
30
+ * - **Windows Personal mode**: the absolute path of the current `node.exe` is
31
+ * recorded at install and checked by `status`. No copy: a personal install
32
+ * has no elevation and nowhere admin-only to put one. The honest trade-off
33
+ * is that nvm-windows can still break it, which is why `status` says so
34
+ * explicitly instead of pretending otherwise.
35
+ *
36
+ * ── Native modules ─────────────────────────────────────────────────────────
37
+ *
38
+ * `better-sqlite3` (under `good.db`) is a compiled addon, built for ONE Node
39
+ * ABI. A runtime copy that pairs a different `node.exe` with the existing
40
+ * `.node` file fails at `require` time with a version error that does not
41
+ * mention Node versions at all. So the copy is verified by actually loading
42
+ * the module with the copied binary, and the fix is named in the message.
43
+ */
44
+
45
+ import fs from 'fs';
46
+ import os from 'os';
47
+ import path from 'path';
48
+
49
+ import { run } from '../shell.js';
50
+ import { isWindows, programDataDir, quoteExe } from '../platform.js';
51
+
52
+ /** Where the pinned runtime lives, per platform. */
53
+ export function runtimeDir(dataDir) {
54
+ return isWindows ? path.join(programDataDir(), 'runtime') : path.join(dataDir, 'runtime');
55
+ }
56
+
57
+ /** The path the service unit should invoke. */
58
+ export function runtimeNodePath(dataDir) {
59
+ return isWindows
60
+ ? path.join(runtimeDir(dataDir), 'node.exe')
61
+ : path.join(runtimeDir(dataDir), 'node');
62
+ }
63
+
64
+ /** Node's ABI number for the running process. Addons are built per ABI. */
65
+ export function currentAbi() {
66
+ return process.versions.modules;
67
+ }
68
+
69
+ /**
70
+ * Looks like a path a version manager owns.
71
+ *
72
+ * Used to warn rather than to refuse: pinning handles it either way, but a
73
+ * user who sees "your node is in nvm" understands why the pin exists.
74
+ *
75
+ * @param {string} nodePath
76
+ * @returns {{ managed: boolean, manager: string|null }}
77
+ */
78
+ export function detectVersionManager(nodePath) {
79
+ const p = String(nodePath).replace(/\\/g, '/').toLowerCase();
80
+
81
+ if (p.includes('/.nvm/')) return { managed: true, manager: 'nvm' };
82
+ if (p.includes('/appdata/roaming/nvm/') || p.includes('/nvm4w/')) return { managed: true, manager: 'nvm-windows' };
83
+ if (p.includes('/.volta/')) return { managed: true, manager: 'Volta' };
84
+ if (p.includes('/.fnm/') || p.includes('/fnm_multishells/')) return { managed: true, manager: 'fnm' };
85
+ if (p.includes('/.asdf/')) return { managed: true, manager: 'asdf' };
86
+ if (p.includes('/scoop/')) return { managed: true, manager: 'Scoop' };
87
+
88
+ return { managed: false, manager: null };
89
+ }
90
+
91
+ /**
92
+ * On Windows, whether an nvm-managed node and an MSI-installed node are both
93
+ * present. That combination is the one that produces the worst confusion: the
94
+ * shell's `node` is nvm's, `C:\Program Files\nodejs\node.exe` is the MSI's,
95
+ * and a service pinned to one while `npm install` ran under the other leaves
96
+ * native modules built for the wrong ABI.
97
+ *
98
+ * @returns {{ mixed: boolean, msiPath: string|null, managed: string|null }}
99
+ */
100
+ export function detectMixedWindowsInstalls(nodePath = process.execPath) {
101
+ if (!isWindows) return { mixed: false, msiPath: null, managed: null };
102
+
103
+ const msi = path.join(process.env.ProgramFiles || 'C:\\Program Files', 'nodejs', 'node.exe');
104
+ const msiPresent = fs.existsSync(msi);
105
+ const { managed, manager } = detectVersionManager(nodePath);
106
+
107
+ const samePath = path.resolve(nodePath).toLowerCase() === msi.toLowerCase();
108
+
109
+ return {
110
+ mixed: msiPresent && managed && !samePath,
111
+ msiPath: msiPresent ? msi : null,
112
+ managed: manager,
113
+ };
114
+ }
115
+
116
+ // ─── Linux: the symlink ───────────────────────────────────────────────────────
117
+
118
+ /**
119
+ * Creates or re-points `<dataDir>/runtime/node`.
120
+ *
121
+ * The target is resolved with `realpath` first, so a symlink chain through a
122
+ * version manager's shim is collapsed to the actual binary. Pointing the link
123
+ * at another symlink would defeat the purpose entirely.
124
+ *
125
+ * @param {Object} opts
126
+ * @param {string} opts.dataDir
127
+ * @param {string} [opts.nodeExe] Defaults to the running node
128
+ * @returns {{ ok: boolean, link?: string, target?: string, reason?: string }}
129
+ */
130
+ export function linkRuntime({ dataDir, nodeExe = process.execPath } = {}) {
131
+ const dir = runtimeDir(dataDir);
132
+ const link = runtimeNodePath(dataDir);
133
+
134
+ let target;
135
+ try {
136
+ target = fs.realpathSync(nodeExe);
137
+ } catch (err) {
138
+ return { ok: false, reason: `cannot resolve ${nodeExe}: ${err.message}` };
139
+ }
140
+
141
+ try {
142
+ fs.mkdirSync(dir, { recursive: true });
143
+ // Removed rather than overwritten: symlink() fails with EEXIST, and
144
+ // forcing it any other way risks following the old link and replacing the
145
+ // Node binary it points at.
146
+ try { fs.unlinkSync(link); } catch { /* nothing there */ }
147
+ fs.symlinkSync(target, link);
148
+ } catch (err) {
149
+ return { ok: false, reason: `could not create ${link}: ${err.message}` };
150
+ }
151
+
152
+ return { ok: true, link, target };
153
+ }
154
+
155
+ /**
156
+ * The state of the Linux runtime link.
157
+ *
158
+ * @param {string} dataDir
159
+ * @returns {{ exists: boolean, broken: boolean, link: string, target: string|null, reason: string }}
160
+ */
161
+ export function inspectLink(dataDir) {
162
+ const link = runtimeNodePath(dataDir);
163
+
164
+ let target = null;
165
+ try {
166
+ target = fs.readlinkSync(link);
167
+ } catch (err) {
168
+ if (err.code === 'EINVAL') {
169
+ // Not a symlink but it exists — someone copied a binary here. That works,
170
+ // so it is not broken; it is just not what we would have made.
171
+ return { exists: true, broken: false, link, target: link, reason: 'a real file, not a symlink' };
172
+ }
173
+ return { exists: false, broken: false, link, target: null, reason: 'the runtime link does not exist' };
174
+ }
175
+
176
+ if (!fs.existsSync(link)) {
177
+ return {
178
+ exists: true,
179
+ broken: true,
180
+ link,
181
+ target,
182
+ reason: `the runtime link points at ${target}, which no longer exists `
183
+ + '(a version manager probably removed that Node version). Fix it with: ezz service repair',
184
+ };
185
+ }
186
+
187
+ return { exists: true, broken: false, link, target, reason: 'ok' };
188
+ }
189
+
190
+ // ─── Windows Server: the copy ────────────────────────────────────────────────
191
+
192
+ /**
193
+ * What gets copied into the admin-only runtime directory.
194
+ *
195
+ * `node_modules` is included because the service must not depend on the user's
196
+ * package directory, which `npm update` replaces wholesale. `dist/ui` is
197
+ * included so a dashboard started from the copy can serve the built UI.
198
+ */
199
+ const COPY_ENTRIES = ['package.json', 'src', 'node_modules', 'dist'];
200
+
201
+ /**
202
+ * Copies node.exe and the application into the runtime directory.
203
+ *
204
+ * @param {Object} opts
205
+ * @param {string} opts.dataDir
206
+ * @param {string} opts.appRoot Repository/package root to copy from
207
+ * @param {string} [opts.nodeExe]
208
+ * @param {(line: string) => void} [opts.log]
209
+ * @returns {{ ok: boolean, dir?: string, nodeExe?: string, entry?: string, reason?: string }}
210
+ */
211
+ export function copyRuntime({ dataDir, appRoot, nodeExe = process.execPath, log = () => {} } = {}) {
212
+ const dir = runtimeDir(dataDir);
213
+ const destNode = runtimeNodePath(dataDir);
214
+ const appDir = path.join(dir, 'app');
215
+
216
+ try {
217
+ fs.mkdirSync(appDir, { recursive: true });
218
+ } catch (err) {
219
+ return {
220
+ ok: false,
221
+ reason: `could not create ${dir}: ${err.message}. `
222
+ + 'Writing under ProgramData needs an elevated terminal.',
223
+ };
224
+ }
225
+
226
+ try {
227
+ fs.copyFileSync(fs.realpathSync(nodeExe), destNode);
228
+ log(`Copied node.exe → ${destNode}`);
229
+ } catch (err) {
230
+ return { ok: false, reason: `could not copy node.exe: ${err.message}` };
231
+ }
232
+
233
+ for (const entry of COPY_ENTRIES) {
234
+ const from = path.join(appRoot, entry);
235
+ if (!fs.existsSync(from)) {
236
+ // `dist` is absent in a source checkout that has not run build:ui, and
237
+ // that is not a failure: the dashboard falls back to the classic UI.
238
+ log(` ${entry}: not present, skipped`);
239
+ continue;
240
+ }
241
+ try {
242
+ fs.cpSync(from, path.join(appDir, entry), { recursive: true, force: true });
243
+ log(` ${entry}: copied`);
244
+ } catch (err) {
245
+ return { ok: false, reason: `could not copy ${entry}: ${err.message}` };
246
+ }
247
+ }
248
+
249
+ // The entry point inside the copy, which is what the service XML invokes.
250
+ const entry = path.join(appDir, 'src', 'cli', 'index.js');
251
+ if (!fs.existsSync(entry)) {
252
+ return { ok: false, reason: `the copy is missing its entry point: ${entry}` };
253
+ }
254
+
255
+ return { ok: true, dir, nodeExe: destNode, entry };
256
+ }
257
+
258
+ // ─── Verification ────────────────────────────────────────────────────────────
259
+
260
+ /**
261
+ * Proves a Node binary can actually run the application's native module.
262
+ *
263
+ * Running the real `require` rather than comparing version numbers: an ABI
264
+ * number match is necessary but not sufficient — a half-copied `node_modules`
265
+ * or a module built for a different architecture both pass a number check and
266
+ * fail at load. This is the check that matters, so it is the one performed.
267
+ *
268
+ * @param {Object} opts
269
+ * @param {string} opts.nodeExe
270
+ * @param {string} opts.appDir Directory whose node_modules should be used
271
+ * @returns {Promise<{ ok: boolean, abi?: string, version?: string, reason?: string, fix?: string }>}
272
+ */
273
+ export async function verifyNativeModules({ nodeExe, appDir } = {}) {
274
+ // better-sqlite3 is reached through good.db. Opening an in-memory database
275
+ // and closing it exercises the addon's load path and its entry points
276
+ // without touching any file.
277
+ //
278
+ // Written to a file rather than passed with `node -e`: run() goes through a
279
+ // shell, and PowerShell mangles an inline script's quotes beyond rescue —
280
+ // measured, not assumed. A file sidesteps the quoting problem entirely.
281
+ const probe = [
282
+ 'const { createRequire } = require("module");',
283
+ `const r = createRequire(${JSON.stringify(path.join(appDir, 'package.json'))});`,
284
+ 'const Database = r("better-sqlite3");',
285
+ 'const db = new Database(":memory:");',
286
+ 'db.close();',
287
+ 'process.stdout.write(JSON.stringify({ abi: process.versions.modules, version: process.version }));',
288
+ ].join('\n');
289
+
290
+ const probeFile = path.join(
291
+ os.tmpdir(),
292
+ `ez-runtime-probe-${process.pid}-${Date.now()}.cjs`,
293
+ );
294
+
295
+ let result;
296
+ try {
297
+ fs.writeFileSync(probeFile, probe, 'utf8');
298
+ // quoteExe() is the single owner of this: on Windows a quoted executable
299
+ // path needs PowerShell's `&` call operator, and three places here got it
300
+ // wrong by hand-rolling the quoting instead.
301
+ const invoke = `${quoteExe(nodeExe)} "${probeFile}"`;
302
+ result = await run(invoke, { cwd: appDir, timeout: 30_000 });
303
+ } catch (err) {
304
+ return { ok: false, reason: `could not run the runtime probe: ${err.message}` };
305
+ } finally {
306
+ try { fs.rmSync(probeFile, { force: true }); } catch { /* best effort */ }
307
+ }
308
+
309
+ if (result.success) {
310
+ try {
311
+ const parsed = JSON.parse(result.stdout.trim());
312
+ return { ok: true, abi: parsed.abi, version: parsed.version };
313
+ } catch {
314
+ return { ok: true, abi: null, version: null };
315
+ }
316
+ }
317
+
318
+ const output = `${result.stdout}\n${result.stderr}`;
319
+
320
+ // The ABI error names a module version, not a Node version, which is why
321
+ // the fix has to be spelled out.
322
+ if (/NODE_MODULE_VERSION|was compiled against a different Node\.js version/i.test(output)) {
323
+ const wanted = output.match(/NODE_MODULE_VERSION (\d+)/g)?.join(' vs ') ?? 'a different ABI';
324
+ return {
325
+ ok: false,
326
+ reason: `the native module better-sqlite3 was built for a different Node ABI (${wanted}).`,
327
+ fix: 'Rebuild it against the Node version the service will use:\n'
328
+ + ` cd ${appDir}\n`
329
+ + ' npm rebuild better-sqlite3\n'
330
+ + 'then run `ezz service repair`. This happens when the service runs a different Node '
331
+ + 'version than the one `npm install` used — most often with nvm.',
332
+ };
333
+ }
334
+
335
+ if (/Cannot find module/i.test(output)) {
336
+ return {
337
+ ok: false,
338
+ reason: 'the runtime copy is missing its dependencies.',
339
+ fix: `Run \`npm install\` in ${appDir}, then \`ezz service repair\`.`,
340
+ };
341
+ }
342
+
343
+ return { ok: false, reason: `the runtime could not load better-sqlite3: ${output.trim().slice(0, 400)}` };
344
+ }
345
+
346
+ /**
347
+ * Everything `ezz service status` needs to say about runtimes.
348
+ *
349
+ * @param {Object} opts
350
+ * @param {string} opts.dataDir
351
+ * @param {string|null} [opts.recordedNodeExe] What install recorded (Personal mode)
352
+ * @returns {Promise<Object>}
353
+ */
354
+ export async function inspectRuntime({ dataDir, recordedNodeExe = null } = {}) {
355
+ const systemNode = { path: process.execPath, version: process.version, abi: currentAbi() };
356
+ const mixed = detectMixedWindowsInstalls(systemNode.path);
357
+ const manager = detectVersionManager(systemNode.path);
358
+
359
+ const out = {
360
+ systemNode,
361
+ manager,
362
+ mixed,
363
+ pinned: null,
364
+ warnings: [],
365
+ };
366
+
367
+ if (mixed.mixed) {
368
+ out.warnings.push(
369
+ `Both ${mixed.managed} and the Node MSI installer are present on this machine `
370
+ + `(${mixed.msiPath}). If \`npm install\` runs under one and the service under the other, `
371
+ + 'native modules will be built for the wrong ABI. The service is pinned to one specific '
372
+ + 'binary to avoid this; `ezz service repair` re-pins it to the Node you are using now.',
373
+ );
374
+ }
375
+
376
+ if (!isWindows) {
377
+ const link = inspectLink(dataDir);
378
+ out.pinned = {
379
+ kind: 'symlink',
380
+ path: link.link,
381
+ target: link.target,
382
+ exists: link.exists,
383
+ broken: link.broken,
384
+ };
385
+ if (link.broken) out.warnings.push(link.reason);
386
+
387
+ if (link.exists && !link.broken) {
388
+ const probe = await run(`${quoteExe(link.link)} --version`, { timeout: 10_000 });
389
+ out.pinned.version = probe.success ? probe.stdout.trim() : null;
390
+ if (!probe.success) {
391
+ out.warnings.push(`${link.link} exists but did not run: ${probe.stderr.trim() || 'no output'}`);
392
+ } else if (out.pinned.version !== systemNode.version) {
393
+ // Not a warning: a service deliberately pinned to an older Node than
394
+ // the shell's is the normal state after the user upgrades. It is
395
+ // reported so the difference is visible rather than surprising.
396
+ out.pinned.differsFromSystem = true;
397
+ }
398
+ }
399
+
400
+ return out;
401
+ }
402
+
403
+ // Windows: either the Server-mode copy or the recorded Personal-mode path.
404
+ const copied = runtimeNodePath(dataDir);
405
+ if (fs.existsSync(copied)) {
406
+ const probe = await run(`${quoteExe(copied)} --version`, { timeout: 10_000 });
407
+ out.pinned = {
408
+ kind: 'copy',
409
+ path: copied,
410
+ version: probe.success ? probe.stdout.trim() : null,
411
+ exists: true,
412
+ broken: !probe.success,
413
+ };
414
+ if (!probe.success) {
415
+ out.warnings.push(`${copied} exists but did not run. Re-create it with: ezz service repair`);
416
+ }
417
+ return out;
418
+ }
419
+
420
+ if (recordedNodeExe) {
421
+ const exists = fs.existsSync(recordedNodeExe);
422
+ const probe = exists ? await run(`${quoteExe(recordedNodeExe)} --version`, { timeout: 10_000 }) : null;
423
+ out.pinned = {
424
+ kind: 'recorded',
425
+ path: recordedNodeExe,
426
+ version: probe?.success ? probe.stdout.trim() : null,
427
+ exists,
428
+ broken: !exists || !probe?.success,
429
+ };
430
+
431
+ if (!exists) {
432
+ const { manager: who } = detectVersionManager(recordedNodeExe);
433
+ out.warnings.push(
434
+ `The Node the service was installed with no longer exists:\n ${recordedNodeExe}\n`
435
+ + (who
436
+ ? `That path belongs to ${who}, so the version was probably removed or switched. `
437
+ : '')
438
+ + 'Fix it with: ezz service repair',
439
+ );
440
+ }
441
+ return out;
442
+ }
443
+
444
+ out.pinned = { kind: 'none', path: null, version: null, exists: false, broken: false };
445
+ return out;
446
+ }