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
@@ -3,12 +3,365 @@
3
3
  *
4
4
  * Shared platform constants and nginx command-building helpers.
5
5
  * Used by CLI managers, dashboard routes, and dashboard lib.
6
- * Centralises the isWindows guard and nginx shell invocations so they
7
- * are defined exactly once and behave identically everywhere.
6
+ * Centralises the isWindows guard, the persistent data directory, and nginx
7
+ * shell invocations so they are defined exactly once and behave identically
8
+ * everywhere. This module imports nothing from the project, so it is safe to
9
+ * load before the database is initialised.
8
10
  */
9
11
 
12
+ import fs from 'fs';
13
+ import path from 'path';
14
+ import os from 'os';
15
+ import { createHash } from 'crypto';
16
+
10
17
  export const isWindows = process.platform === 'win32';
11
18
 
19
+ /** Env var that redirects every persistent artifact to a chosen directory. */
20
+ export const DATA_DIR_ENV = 'EASY_DEVOPS_DATA_DIR';
21
+
22
+ /**
23
+ * Env var that marks a test run. When set to '1', getDataDir() REFUSES to
24
+ * resolve the real data directory — see assertTestDataDir().
25
+ */
26
+ export const TEST_MODE_ENV = 'EZ_TEST';
27
+
28
+ /**
29
+ * The per-user data directory: where a normal, non-service install lives.
30
+ */
31
+ function userDataDir() {
32
+ return isWindows
33
+ ? path.join(process.env.APPDATA || os.homedir(), 'easy-devops')
34
+ : path.join(os.homedir(), '.config', 'easy-devops');
35
+ }
36
+
37
+ /**
38
+ * The machine-wide data directory, used when the Windows service is installed.
39
+ *
40
+ * A Windows service running as `NT SERVICE\EasyDevOps` has no `%APPDATA%` of
41
+ * the installing user — a virtual account's profile is not that user's — so a
42
+ * per-user directory cannot be shared between the service and the CLI. Putting
43
+ * the data under ProgramData is what lets the service, the CLI and the
44
+ * dashboard all see one database.
45
+ */
46
+ export function programDataDir() {
47
+ return path.join(process.env.ProgramData || 'C:\\ProgramData', 'easy-devops');
48
+ }
49
+
50
+ /**
51
+ * Marker written by `ezz service install` in Server mode.
52
+ *
53
+ * Its presence — not the service's running state — is what selects the
54
+ * machine-wide directory. That distinction matters: a stopped or uninstalled
55
+ * service must not silently move the data back to `%APPDATA%`, because the
56
+ * data in ProgramData is then the real data and the per-user directory is a
57
+ * stale copy. `ezz service uninstall` asks before moving anything and removes
58
+ * this marker only if the user chooses to move back.
59
+ */
60
+ export function serverModeMarkerPath() {
61
+ return path.join(programDataDir(), '.server-mode');
62
+ }
63
+
64
+ /**
65
+ * Cached because getDataDir() is called on nearly every code path and this
66
+ * would otherwise be a filesystem stat each time. The migration is the only
67
+ * thing that changes the answer within one process's life, and it calls
68
+ * resetDataDirCache() when it does.
69
+ */
70
+ let serverModeCache = null;
71
+
72
+ /** True when this machine is in Server mode (the marker exists). */
73
+ export function isServerMode() {
74
+ if (!isWindows) return false;
75
+ if (serverModeCache !== null) return serverModeCache;
76
+
77
+ try {
78
+ serverModeCache = fs.existsSync(serverModeMarkerPath());
79
+ } catch {
80
+ // An unreadable ProgramData is not Server mode. Erring toward the per-user
81
+ // directory keeps a non-elevated CLI working rather than failing outright.
82
+ serverModeCache = false;
83
+ }
84
+
85
+ return serverModeCache;
86
+ }
87
+
88
+ /** Forgets the cached Server-mode answer. Called by the data-dir migration. */
89
+ export function resetDataDirCache() {
90
+ serverModeCache = null;
91
+ }
92
+
93
+ /**
94
+ * The data directory a normal installation uses, Server mode included.
95
+ */
96
+ function realDataDir() {
97
+ return isServerMode() ? programDataDir() : userDataDir();
98
+ }
99
+
100
+ /** Case-insensitive on Windows, where paths are not case-sensitive. */
101
+ function isSameDir(a, b) {
102
+ const norm = (p) => (isWindows ? path.resolve(p).toLowerCase() : path.resolve(p));
103
+ return norm(a) === norm(b);
104
+ }
105
+
106
+ /** True when `child` is `parent` or lives inside it. */
107
+ function isDirWithin(child, parent) {
108
+ const norm = (p) => (isWindows ? path.resolve(p).toLowerCase() : path.resolve(p));
109
+ const c = norm(child);
110
+ const p = norm(parent);
111
+ return c === p || c.startsWith(p + path.sep);
112
+ }
113
+
114
+ /**
115
+ * Refuses to let a test run touch the real installation.
116
+ *
117
+ * Five separate incidents have ended with a test suite reading or writing the
118
+ * real `%APPDATA%\easy-devops` / `~/.config/easy-devops`, every one of them
119
+ * the same root cause: core/db.js resolves its directory ONCE at module load,
120
+ * and a static ESM import graph is fully evaluated before the first line of
121
+ * the importing file runs. Setting the environment variable at the top of a
122
+ * test is therefore too late, and no amount of care in the test files fixes
123
+ * that ordering.
124
+ *
125
+ * So the refusal lives here, at the one function every path goes through:
126
+ * with EZ_TEST=1, resolving the real directory throws instead of returning.
127
+ * A test can only ever get a directory it was explicitly given.
128
+ *
129
+ * Use e2e/run.mjs, which sets both variables before Node starts.
130
+ *
131
+ * @param {string|undefined} override The raw EASY_DEVOPS_DATA_DIR value
132
+ */
133
+ function assertTestDataDir(override) {
134
+ // Every directory a real installation could be using, not just the one it
135
+ // would resolve to right now. Server mode depends on a marker file, so
136
+ // whether `realDataDir()` returns ProgramData varies with machine state —
137
+ // and a guard that protected only the currently-selected directory would
138
+ // leave the other one exposed on exactly the machines where it matters.
139
+ // Both are refused unconditionally.
140
+ const real = realDataDir();
141
+ const forbidden = [userDataDir()];
142
+ if (isWindows) forbidden.push(programDataDir());
143
+
144
+ const fail = (reason) => {
145
+ throw new Error(
146
+ `${TEST_MODE_ENV}=1 is set, so refusing to use the real data directory.\n` +
147
+ ` reason : ${reason}\n` +
148
+ ` ${DATA_DIR_ENV}: ${override || '(unset)'}\n` +
149
+ ` real dir: ${real}\n` +
150
+ '\n' +
151
+ 'Run the e2e suites through the runner, which sets both variables before\n' +
152
+ 'Node starts and gives each suite its own temporary directory:\n' +
153
+ '\n' +
154
+ ' npm run test:e2e (all suites)\n' +
155
+ ' npm run test:e2e -- service (one suite)\n'
156
+ );
157
+ };
158
+
159
+ // The failure behind all five incidents: no override at all, so the real
160
+ // directory got resolved by default.
161
+ if (!override) fail(`${DATA_DIR_ENV} is not set`);
162
+
163
+ const resolved = path.resolve(override);
164
+
165
+ // A directory under the system temp folder is throwaway by construction, so
166
+ // it is accepted without further checks.
167
+ //
168
+ // This exception is needed, not merely convenient: several suites isolate
169
+ // themselves by redirecting APPDATA/HOME into their temp directory, which
170
+ // makes realDataDir() compute a path inside — or equal to — that same temp
171
+ // directory. Comparing against it would then reject the safest pattern in
172
+ // the suite while telling the user their temp directory "is" the real one.
173
+ if (isDirWithin(resolved, os.tmpdir())) return;
174
+
175
+ // Anywhere else, no real directory may be reachable: not the same directory,
176
+ // not inside it, and not a parent of it (%APPDATA% or ProgramData itself).
177
+ for (const dir of forbidden) {
178
+ if (isSameDir(resolved, dir)) fail(`it points at a real data directory (${dir})`);
179
+ if (isDirWithin(resolved, dir)) fail(`it points inside a real data directory (${dir})`);
180
+ if (isDirWithin(dir, resolved)) fail(`it contains a real data directory (${dir})`);
181
+ }
182
+ }
183
+
184
+ /**
185
+ * Returns the directory holding all persistent user data: the SQLite database,
186
+ * dashboard sessions and logs.
187
+ *
188
+ * Resolution order:
189
+ * 1. EASY_DEVOPS_DATA_DIR — set by `--dev` (and inherited by child processes)
190
+ * 2. Windows: %APPDATA%\easy-devops (home directory if APPDATA is unset)
191
+ * 3. Otherwise: ~/.config/easy-devops
192
+ *
193
+ * Principle IV: never inside the package directory, which `npm update` wipes.
194
+ *
195
+ * Throws when EZ_TEST=1 and the resolved directory would be the real one.
196
+ *
197
+ * @returns {string} Absolute path to the data directory
198
+ */
199
+ export function getDataDir() {
200
+ const override = process.env[DATA_DIR_ENV]?.trim();
201
+
202
+ if (process.env[TEST_MODE_ENV] === '1') {
203
+ assertTestDataDir(override);
204
+ return path.resolve(override);
205
+ }
206
+
207
+ if (override) return path.resolve(override);
208
+
209
+ return realDataDir();
210
+ }
211
+
212
+ /**
213
+ * Env var that explicitly marks a development run.
214
+ *
215
+ * Exists because "dev mode" and "a redirected data directory" are different
216
+ * questions, and conflating them caused a real incident — see below.
217
+ */
218
+ export const DEV_MODE_ENV = 'EZ_DEV';
219
+
220
+ /** The project-local directory `--dev` points at. */
221
+ const DEV_DIR_NAME = '.dev-data';
222
+
223
+ /**
224
+ * True for a DEVELOPMENT run: Let's Encrypt staging, `-dev` process names, and
225
+ * the legacy data migration skipped.
226
+ *
227
+ * It used to be `Boolean(process.env.EASY_DEVOPS_DATA_DIR)` — the mere presence
228
+ * of a redirected data directory. That was wrong and shipped a serious bug: the
229
+ * Windows Personal-mode launcher sets `EASY_DEVOPS_DATA_DIR` to the ordinary
230
+ * `%APPDATA%\easy-devops` so the service and the CLI agree on one location, and
231
+ * that alone put the daemon into dev mode — issuing **staging certificates**,
232
+ * which browsers reject, on a user's real domains. The same trap applied to the
233
+ * systemd unit and the Windows service, both of which also set the variable.
234
+ *
235
+ * So dev mode is now decided by intent, never by a side effect:
236
+ *
237
+ * 1. `EZ_DEV=1` — set explicitly by `--dev`.
238
+ * 2. the resolved directory IS a `.dev-data` directory — which is what
239
+ * `--dev` points at, so an inherited environment still reads as dev
240
+ * without the flag having to be passed down.
241
+ *
242
+ * A redirected directory that is neither of those is a production install that
243
+ * simply keeps its data somewhere specific. That is the normal case for every
244
+ * installed service.
245
+ *
246
+ * @returns {boolean}
247
+ */
248
+ export function isDevDataDir() {
249
+ if (process.env[DEV_MODE_ENV] === '1') return true;
250
+
251
+ const override = process.env[DATA_DIR_ENV]?.trim();
252
+ if (!override) return false;
253
+
254
+ // Compared on the final path segment rather than against one absolute path,
255
+ // so a checkout anywhere still reads as dev.
256
+ return path.basename(path.resolve(override)).toLowerCase() === DEV_DIR_NAME;
257
+ }
258
+
259
+ /**
260
+ * True when `dir` is exactly what getDataDir() would resolve to with no
261
+ * override at all.
262
+ *
263
+ * Service and launcher definitions use this to decide whether to pass
264
+ * `EASY_DEVOPS_DATA_DIR` in the environment. When the answer is the default,
265
+ * passing it is redundant — and redundant environment variables are not free:
266
+ * the one that was being passed here turned on dev mode, because dev mode used
267
+ * to be inferred from its mere presence. That inference is fixed, and the
268
+ * variable is also no longer set needlessly, so a future regression of either
269
+ * one on its own cannot reproduce the bug.
270
+ *
271
+ * @param {string} dir
272
+ * @returns {boolean}
273
+ */
274
+ export function isDefaultDataDir(dir) {
275
+ if (!dir) return false;
276
+ return isSameDir(dir, realDataDir());
277
+ }
278
+
279
+ /**
280
+ * Command that reports whether this is a Windows Server edition.
281
+ *
282
+ * `InstallationType` in the CurrentVersion key is `Client`, `Server` or
283
+ * `Server Core`. It is the right signal and the cheapest: `os.release()` does
284
+ * not distinguish a server from a workstation at all (both report 10.0.x), and
285
+ * the WMI route (`Get-CimInstance Win32_OperatingSystem`) takes seconds to
286
+ * start its service on a cold machine. Measured on Windows 10: this returns
287
+ * `Client` immediately.
288
+ *
289
+ * Returns the raw value on stdout, so the caller decides what it means.
290
+ *
291
+ * @returns {string}
292
+ */
293
+ export function windowsEditionQueryCmd() {
294
+ return "(Get-ItemProperty 'HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion')"
295
+ + '.InstallationType';
296
+ }
297
+
298
+ /**
299
+ * Command that reports the Windows product name, for display.
300
+ * @returns {string}
301
+ */
302
+ export function windowsProductNameCmd() {
303
+ return "(Get-ItemProperty 'HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion').ProductName";
304
+ }
305
+
306
+ /**
307
+ * Address the daemon listens on for local event delivery to a dashboard.
308
+ *
309
+ * Two different kinds of thing behind one name, which is why it lives here:
310
+ *
311
+ * - Windows: a named pipe. `\\.\pipe\...` is a name in a kernel namespace,
312
+ * not a path on disk — it cannot live in the data directory, so the data
313
+ * directory is HASHED into the name instead. That keeps a dev instance
314
+ * (`--dev`, its own data dir) from talking to the real one, which sharing a
315
+ * fixed pipe name would otherwise allow.
316
+ * - Everything else: a Unix socket file inside the data directory, which
317
+ * gives the same isolation for free and inherits the directory's
318
+ * permissions.
319
+ *
320
+ * @param {string} dataDir
321
+ * @returns {string}
322
+ */
323
+ export function daemonIpcPath(dataDir) {
324
+ if (!isWindows) return path.join(dataDir, 'daemon.sock');
325
+
326
+ // A short, stable hash: the pipe namespace is flat and a full path would be
327
+ // both too long and full of characters that are not allowed in a pipe name.
328
+ const key = createHash('sha256').update(path.resolve(dataDir).toLowerCase()).digest('hex').slice(0, 12);
329
+ return `\\\\.\\pipe\\easy-devops-${key}`;
330
+ }
331
+
332
+ /**
333
+ * Where an nginx log file actually lives.
334
+ *
335
+ * The only correct resolver, and the reason it exists: three places resolved
336
+ * this independently and one of them was wrong. `getLogs()` in
337
+ * core/nginx-service.js read `<nginxDir>/logs/error.log` unconditionally,
338
+ * which is the Windows layout — so on Linux, where a distribution nginx logs
339
+ * to /var/log/nginx, the dashboard's log view was permanently empty. The live
340
+ * tail in the socket layer had the branch right, which is why the bug showed
341
+ * up as "the tail works but the log page does not".
342
+ *
343
+ * @param {string} nginxDir
344
+ * @param {'error'|'access'} [which]
345
+ * @returns {string}
346
+ */
347
+ export function nginxLogPath(nginxDir, which = 'error') {
348
+ const file = which === 'access' ? 'access.log' : 'error.log';
349
+
350
+ // A Windows nginx is a self-contained directory: binary, conf and logs.
351
+ if (isWindows) return path.join(nginxDir, 'logs', file);
352
+
353
+ // On Linux the package puts logs under /var/log, not under the config
354
+ // directory, and nginxDir there is /etc/nginx.
355
+ return `/var/log/nginx/${file}`;
356
+ }
357
+
358
+ /**
359
+ * Raw Node platform identifier ('win32', 'linux', 'darwin', …).
360
+ * Exported so consumers that need to *report* the platform (e.g. to the Hub or
361
+ * the settings API) do not have to read `process.platform` themselves.
362
+ */
363
+ export const platformName = process.platform;
364
+
12
365
  /**
13
366
  * Returns the nginx binary invocation string suitable for use in shell commands.
14
367
  * On Windows returns `& "path\nginx.exe"` (PowerShell call operator + quoted path).
@@ -50,6 +403,72 @@ export function nginxReloadCmd(nginxDir) {
50
403
  return 'nginx -s reload';
51
404
  }
52
405
 
406
+ // ─── NGINX SERVICE CONTROL ────────────────────────────────────────────────────
407
+ //
408
+ // On Linux every command here MUST match a rule written by core/permissions.js
409
+ // into /etc/sudoers.d/easy-devops, byte for byte, or `sudo -n` fails silently:
410
+ // /usr/bin/systemctl start nginx
411
+ // /usr/bin/systemctl stop nginx
412
+ // /usr/bin/systemctl reload nginx
413
+ //
414
+ // On Windows nginx.exe must be launched detached with the nginx directory as
415
+ // its working directory, otherwise it resolves relative paths such as
416
+ // logs/error.log against our cwd and dies on startup. This is the same
417
+ // Start-Process form core/nginx-service.js already uses successfully.
418
+
419
+ /**
420
+ * Command that starts nginx as a long-running service.
421
+ * @param {string} nginxDir
422
+ * @returns {string}
423
+ */
424
+ export function nginxServiceStartCmd(nginxDir) {
425
+ if (isWindows) {
426
+ const exe = path.join(nginxDir, 'nginx.exe');
427
+ const conf = path.join(nginxDir, 'conf', 'nginx.conf');
428
+ return `Start-Process -FilePath "${exe}" -ArgumentList '-c','"${conf}"' -WorkingDirectory "${nginxDir}" -WindowStyle Hidden`;
429
+ }
430
+ return 'sudo -n /usr/bin/systemctl start nginx';
431
+ }
432
+
433
+ /**
434
+ * Command that stops nginx.
435
+ * @param {string} nginxDir
436
+ * @returns {string}
437
+ */
438
+ export function nginxServiceStopCmd(nginxDir) {
439
+ if (isWindows) return 'taskkill /f /IM nginx.exe';
440
+ return 'sudo -n /usr/bin/systemctl stop nginx';
441
+ }
442
+
443
+ /**
444
+ * Command that gracefully reloads nginx without dropping connections.
445
+ * @param {string} nginxDir
446
+ * @returns {string}
447
+ */
448
+ export function nginxServiceReloadCmd(nginxDir) {
449
+ if (isWindows) return `${getNginxExe(nginxDir)} -s reload`;
450
+ return 'sudo -n /usr/bin/systemctl reload nginx';
451
+ }
452
+
453
+ /** Command that reports whether nginx is currently running. */
454
+ export function nginxIsRunningCmd() {
455
+ return isWindows
456
+ ? 'tasklist /FI "IMAGENAME eq nginx.exe" /NH'
457
+ : 'pgrep -x nginx';
458
+ }
459
+
460
+ /**
461
+ * Interprets the output of nginxIsRunningCmd().
462
+ * @param {{ success: boolean, stdout: string, stderr: string }} result
463
+ * @returns {boolean}
464
+ */
465
+ export function isNginxRunning(result) {
466
+ if (isWindows) {
467
+ return combineOutput(result).toLowerCase().includes('nginx.exe');
468
+ }
469
+ return result.success && result.stdout.trim().length > 0;
470
+ }
471
+
53
472
  /**
54
473
  * Merges stdout and stderr from a shell result into a single trimmed string.
55
474
  * Useful for surfacing nginx output that may come from either stream.
@@ -60,6 +479,110 @@ export function combineOutput(result) {
60
479
  return [result.stdout, result.stderr].filter(Boolean).join('\n').trim();
61
480
  }
62
481
 
482
+ // ─── NGINX PATH FORMATTING ────────────────────────────────────────────────────
483
+ //
484
+ // nginx on Windows accepts forward slashes, and its config lexer treats a
485
+ // backslash as an escape character. An unquoted path such as
486
+ // ssl_certificate C:\nginx\test\certs\fullchain.pem;
487
+ // therefore has \n and \t read as a newline and a tab, which is why some
488
+ // machines accept a config and others fail `nginx -t` purely because of the
489
+ // folder names involved. Forward slashes sidestep the lexer entirely.
490
+ //
491
+ // On Linux these helpers are deliberately identity functions: paths there
492
+ // contain no backslashes and must be emitted byte-for-byte unchanged.
493
+
494
+ /**
495
+ * Converts a filesystem path into the form nginx should see in a config file.
496
+ * Windows: backslashes become forward slashes and duplicate separators are
497
+ * collapsed. Linux/macOS: returned unchanged.
498
+ * @param {string} p
499
+ * @returns {string}
500
+ */
501
+ export function toNginxPath(p) {
502
+ const value = String(p ?? '');
503
+ if (!isWindows) return value;
504
+ return value.replace(/\\/g, '/').replace(/\/{2,}/g, '/');
505
+ }
506
+
507
+ /**
508
+ * Converts a path into a quoted, escape-safe backslash form for nginx.
509
+ * Used only as the Windows fallback when the forward-slash form is rejected.
510
+ * Every backslash is doubled and the result is quoted, so nginx's lexer reads
511
+ * each pair as one literal backslash instead of an escape sequence.
512
+ * C:\nginx\certs\a.pem -> "C:\\nginx\\certs\\a.pem"
513
+ * @param {string} p
514
+ * @returns {string}
515
+ */
516
+ export function toEscapedNginxPath(p) {
517
+ const native = String(p ?? '').replace(/\//g, '\\');
518
+ return `"${native.replace(/\\/g, '\\\\')}"`;
519
+ }
520
+
521
+ /**
522
+ * Returns true when a path still contains a backslash separator.
523
+ * Used to report (never auto-rewrite) existing configs that predate the fix.
524
+ * @param {string} p
525
+ * @returns {boolean}
526
+ */
527
+ export function hasBackslashPath(p) {
528
+ return typeof p === 'string' && p.includes('\\');
529
+ }
530
+
531
+ /**
532
+ * Extracts the config file paths nginx mentions in a failed test.
533
+ * nginx reports the offending file as `... in <file>:<line>`.
534
+ * @param {string} output
535
+ * @returns {string[]} File paths, in the order nginx reported them
536
+ */
537
+ export function parseNginxErrorFiles(output) {
538
+ const files = [];
539
+ const re = / in (.+?):\d+/g;
540
+ let match;
541
+ while ((match = re.exec(String(output ?? ''))) !== null) {
542
+ files.push(match[1].trim());
543
+ }
544
+ return files;
545
+ }
546
+
547
+ /** True when two paths refer to the same file (Windows: separator- and case-insensitive). */
548
+ function samePath(a, b) {
549
+ const norm = (v) => {
550
+ const slashed = String(v ?? '').replace(/\\/g, '/').replace(/\/{2,}/g, '/');
551
+ return isWindows ? slashed.toLowerCase() : slashed;
552
+ };
553
+ return norm(a) === norm(b);
554
+ }
555
+
556
+ /**
557
+ * Returns true when a failed `nginx -t` blames the certificate directives of a
558
+ * specific config file.
559
+ *
560
+ * Both halves matter: the error must be about loading a certificate AND must
561
+ * name this config file. A cert problem in some *other* config must not cause
562
+ * this domain's paths to be rewritten.
563
+ *
564
+ * @param {string} output Combined nginx test output
565
+ * @param {string} confPath The config file we just wrote
566
+ * @returns {boolean}
567
+ */
568
+ export function isCertPathErrorFor(output, confPath) {
569
+ const text = String(output ?? '');
570
+ if (!text) return false;
571
+
572
+ const mentionsCert =
573
+ /cannot load certificate/i.test(text) ||
574
+ /BIO_new_file/i.test(text) ||
575
+ /ssl_certificate(_key)?/i.test(text) ||
576
+ /PEM_read_bio/i.test(text);
577
+ if (!mentionsCert) return false;
578
+
579
+ const blamed = parseNginxErrorFiles(text);
580
+ // No file attribution at all: fall back to the cert signal alone.
581
+ if (blamed.length === 0) return true;
582
+
583
+ return blamed.some((file) => samePath(file, confPath));
584
+ }
585
+
63
586
  /**
64
587
  * Returns true if an `nginx -t` result indicates a valid config.
65
588
  *
@@ -75,3 +598,187 @@ export function isNginxTestOk(result) {
75
598
  const output = (result.stdout || '') + (result.stderr || '');
76
599
  return output.includes('syntax is ok');
77
600
  }
601
+
602
+ // ─── PM2 / BACKGROUND SERVICE ─────────────────────────────────────────────────
603
+ //
604
+ // Easy DevOps does not implement its own daemon: PM2 keeps the dashboard alive
605
+ // and brings it back after a crash or a reboot. Every PM2 invocation is built
606
+ // here so the OS differences live in one place, and all of them are executed
607
+ // through core/shell.js by core/runner.js.
608
+ //
609
+ // `pm2 startup` covers the init systems PM2 knows (systemd, launchd, openrc,
610
+ // …) but has no Windows support at all, so Windows gets its own two paths —
611
+ // see getStartupFolder() and windowsBootTaskCmd() below.
612
+
613
+ /** Name of the Windows Task Scheduler task that resurrects PM2 at boot. */
614
+ export const WINDOWS_BOOT_TASK = 'EasyDevOps-PM2';
615
+
616
+ /** Filename of the logon launcher dropped into the user's Startup folder. */
617
+ export const WINDOWS_STARTUP_FILE = 'easy-devops-pm2.cmd';
618
+
619
+ /**
620
+ * Quotes a path for the current shell.
621
+ * PowerShell needs the call operator for a quoted executable path; bash does
622
+ * not, and quoting is enough there.
623
+ * @param {string} p
624
+ * @returns {string}
625
+ */
626
+ export function quoteExe(p) {
627
+ return isWindows ? `& "${p}"` : `"${p}"`;
628
+ }
629
+
630
+ /**
631
+ * The user's per-user Startup folder (what `shell:startup` opens).
632
+ *
633
+ * Resolved from APPDATA rather than through a shell call so it can be swapped
634
+ * for a temporary directory in tests — nothing may write to the real Startup
635
+ * folder outside a real install.
636
+ *
637
+ * @returns {string|null} Absolute path, or null on non-Windows
638
+ */
639
+ export function getStartupFolder() {
640
+ if (!isWindows) return null;
641
+ const appData = process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming');
642
+ return path.join(appData, 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup');
643
+ }
644
+
645
+ /**
646
+ * Contents of the logon launcher.
647
+ *
648
+ * A `.cmd` file is used rather than the traditional `.vbs` wrapper: VBScript
649
+ * is deprecated and slated for removal from Windows, so a .vbs launcher would
650
+ * stop working on exactly the machines this targets. The cost is that the
651
+ * .cmd's own console window flashes briefly at logon; `start /b` plus
652
+ * `-WindowStyle Hidden` keeps the actual work invisible.
653
+ *
654
+ * @param {string} pm2Path Absolute path to the pm2 executable
655
+ * @returns {string}
656
+ */
657
+ export function windowsStartupLauncher(pm2Path) {
658
+ return [
659
+ '@echo off',
660
+ 'REM Easy DevOps - restores PM2 apps at logon.',
661
+ 'REM Created and removed by `ezz service install` / `ezz service uninstall`.',
662
+ 'REM Do not edit: it is rewritten on every install.',
663
+ `start "" /b powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -Command "& '${pm2Path}' resurrect"`,
664
+ '',
665
+ ].join('\r\n');
666
+ }
667
+
668
+ /**
669
+ * Command that registers the at-boot Task Scheduler task.
670
+ *
671
+ * `/RP *` makes schtasks itself prompt for the password on the console, so the
672
+ * password never reaches Easy DevOps: it is not in this string, not in argv,
673
+ * not stored and not logged. That is also why this path needs a real terminal
674
+ * and cannot be driven from the dashboard.
675
+ *
676
+ * `/DELAY` is only valid for ONSTART/ONLOGON/ONEVENT and takes mmmm:ss. The
677
+ * delay gives the network stack time to come up before nginx is reloaded.
678
+ *
679
+ * The `--%` stop-parsing token is REQUIRED, not decoration. shell.js runs
680
+ * commands through `powershell -Command`, and PowerShell rewrites the quotes
681
+ * inside /TR on the way to a native exe. Measured against a stand-in exe that
682
+ * printed the argv it received, the `\"..\"`, '..' and backtick-escaped forms
683
+ * all arrived truncated at the first space ("C:\Program"), and doubled quotes
684
+ * failed to parse at all. Only `--%` passes the value through byte for byte.
685
+ * It also means nothing after it is expanded by PowerShell.
686
+ *
687
+ * No hidden-window wrapper is used around pm2 here: an ONSTART task runs in
688
+ * session 0, which has no desktop, so there is no window to hide.
689
+ *
690
+ * @param {Object} opts
691
+ * @param {string} opts.pm2Path Absolute path to the pm2 executable
692
+ * @param {string} opts.user Account the task runs as, e.g. 'DOMAIN\user'
693
+ * @param {number} [opts.delaySeconds=30]
694
+ * @returns {string}
695
+ */
696
+ export function windowsBootTaskCmd({ pm2Path, user, delaySeconds = 30 }) {
697
+ const mm = String(Math.floor(delaySeconds / 60)).padStart(4, '0');
698
+ const ss = String(delaySeconds % 60).padStart(2, '0');
699
+ // `\"` is how the Windows CRT delivers a literal quote to schtasks.
700
+ return [
701
+ 'schtasks --% /Create',
702
+ `/TN "${WINDOWS_BOOT_TASK}"`,
703
+ '/SC ONSTART',
704
+ `/DELAY ${mm}:${ss}`,
705
+ `/RU "${user}"`,
706
+ '/RP *',
707
+ `/TR "\\"${pm2Path}\\" resurrect"`,
708
+ '/F',
709
+ ].join(' ');
710
+ }
711
+
712
+ /** Command that removes the at-boot task. */
713
+ export function windowsBootTaskDeleteCmd() {
714
+ return `schtasks --% /Delete /TN "${WINDOWS_BOOT_TASK}" /F`;
715
+ }
716
+
717
+ /** Command that reports whether the at-boot task exists. */
718
+ export function windowsBootTaskQueryCmd() {
719
+ return `schtasks --% /Query /TN "${WINDOWS_BOOT_TASK}" /FO LIST`;
720
+ }
721
+
722
+ /**
723
+ * Command that prints 1 when this Windows session is elevated, else 0.
724
+ * The at-boot task needs administrator rights; the logon launcher does not.
725
+ */
726
+ export function windowsIsElevatedCmd() {
727
+ return '[int]([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent())' +
728
+ '.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)';
729
+ }
730
+
731
+ /**
732
+ * Command that prints the OS product type: 1 workstation, 2 domain
733
+ * controller, 3 server. Used to default the boot mode on Windows Server.
734
+ */
735
+ export function windowsProductTypeCmd() {
736
+ return '(Get-CimInstance Win32_OperatingSystem).ProductType';
737
+ }
738
+
739
+ /**
740
+ * Name of the systemd unit `pm2 startup` installs for a user.
741
+ * PM2 always uses this shape, which is what makes the unit detectable without
742
+ * asking PM2 anything.
743
+ * @param {string} user
744
+ * @returns {string}
745
+ */
746
+ export function pm2SystemdUnit(user) {
747
+ return `pm2-${user}`;
748
+ }
749
+
750
+ /** Command that reports whether systemd is available on this machine. */
751
+ export function hasSystemctlCmd() {
752
+ return 'command -v systemctl';
753
+ }
754
+
755
+ /**
756
+ * Read-only check of whether PM2's init-system unit is enabled.
757
+ *
758
+ * Deliberately NOT `pm2 startup`: that command INSTALLS the hook when it has
759
+ * the rights to do so (running as root it does it silently), so it can never
760
+ * be used to merely detect state. `systemctl is-enabled` only reads.
761
+ *
762
+ * Prints `enabled`, `disabled`, or fails when the unit does not exist.
763
+ *
764
+ * @param {string} user
765
+ * @returns {string}
766
+ */
767
+ export function systemdIsEnabledCmd(user) {
768
+ return `systemctl is-enabled ${pm2SystemdUnit(user)}`;
769
+ }
770
+
771
+ /**
772
+ * Command that asks PM2 to print the init-system hook for this platform.
773
+ * Linux/macOS only; PM2 exits non-zero when it cannot detect an init system.
774
+ * @param {string} pm2Path
775
+ * @returns {string}
776
+ */
777
+ export function pm2StartupCmd(pm2Path) {
778
+ return `${quoteExe(pm2Path)} startup`;
779
+ }
780
+
781
+ /** Command that removes PM2's init-system hook (Linux/macOS). */
782
+ export function pm2UnstartupCmd(pm2Path) {
783
+ return `${quoteExe(pm2Path)} unstartup`;
784
+ }