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,576 @@
1
+ /**
2
+ * core/service/windowsService.js
3
+ *
4
+ * Windows "Server" mode: a real Windows Service, via WinSW.
5
+ *
6
+ * What this gives the user that the old Task Scheduler approach did not:
7
+ *
8
+ * - It starts at boot, before anyone logs in. A scheduled task at logon
9
+ * meant a rebooted server stayed unmonitored until someone signed in.
10
+ * - It needs **no password, ever**. The service runs as the virtual account
11
+ * `NT SERVICE\EasyDevOps`, which Windows creates and manages itself. The
12
+ * old task needed the user's own password stored in Task Scheduler, which
13
+ * is what made that design unacceptable.
14
+ * - Restart on failure with backoff, and rolling logs, both from WinSW.
15
+ *
16
+ * The cost is elevation: registering a service, writing under ProgramData and
17
+ * setting ACLs all need an Administrator terminal. UAC asks once, at install.
18
+ *
19
+ * ── Why the data directory moves ───────────────────────────────────────────
20
+ *
21
+ * The virtual account has no access to the installing user's `%APPDATA%`, so
22
+ * `C:\ProgramData\easy-devops` becomes the data directory for the service, the
23
+ * CLI and the dashboard alike. See core/service/dataDir.js — it is migrated
24
+ * once, with a verified copy and a backup.
25
+ */
26
+
27
+ import fs from 'fs';
28
+ import path from 'path';
29
+
30
+ import { run as shellRun } from '../shell.js';
31
+ import { programDataDir, isWindows } from '../platform.js';
32
+ import {
33
+ SERVICE_ID,
34
+ SERVICE_DISPLAY_NAME,
35
+ WINSW_ASSET,
36
+ buildServiceXml,
37
+ downloadWinsw,
38
+ verifyWinsw,
39
+ } from './winsw.js';
40
+ import { requiredGrants, applyGrants, revokeGrants, compareGrants } from './acl.js';
41
+ import { runtimeDir, copyRuntime, verifyNativeModules } from './runtime.js';
42
+
43
+ /** Where the wrapper, its config and its logs live. Admin-writable only. */
44
+ export function binDir() {
45
+ return path.join(programDataDir(), 'bin');
46
+ }
47
+ export function winswPath() {
48
+ return path.join(binDir(), WINSW_ASSET);
49
+ }
50
+ export function serviceXmlPath() {
51
+ // WinSW requires the XML to sit beside the executable with the same stem,
52
+ // OR to be named as an argument. It is named explicitly here, but keeping it
53
+ // in the same directory means a `WinSW-x64.xml` convention also works if a
54
+ // future WinSW version insists on it.
55
+ return path.join(binDir(), `${SERVICE_ID}.xml`);
56
+ }
57
+ export function logDir() {
58
+ return path.join(programDataDir(), 'logs');
59
+ }
60
+
61
+ /** The rolling log WinSW writes the daemon's stdout to. */
62
+ export function wrapperLogPath() {
63
+ return path.join(logDir(), `${SERVICE_ID}.wrapper.log`);
64
+ }
65
+ export function outLogPath() {
66
+ return path.join(logDir(), `${SERVICE_ID}.out.log`);
67
+ }
68
+ export function errLogPath() {
69
+ return path.join(logDir(), `${SERVICE_ID}.err.log`);
70
+ }
71
+
72
+ /**
73
+ * Whether this process can write under ProgramData — the practical test for
74
+ * "are we elevated enough to do this".
75
+ *
76
+ * Attempted rather than inferred from a token check: group membership does not
77
+ * tell you whether the process is actually running elevated, and a directory
78
+ * write is exactly the permission that matters here.
79
+ */
80
+ export function canWriteProgramData() {
81
+ const dir = programDataDir();
82
+
83
+ // Probes the directory if it already exists, and otherwise probes its
84
+ // PARENT. Creating `C:\ProgramData\easy-devops` as a side effect of asking
85
+ // "am I elevated?" would leave a directory behind on a machine that never
86
+ // installed anything — and this question is asked on paths that then
87
+ // decline to proceed. Install creates the directory explicitly.
88
+ const target = fs.existsSync(dir) ? dir : path.dirname(dir);
89
+ const probe = path.join(target, `.ez-write-probe-${process.pid}`);
90
+
91
+ try {
92
+ fs.writeFileSync(probe, 'probe');
93
+ fs.rmSync(probe, { force: true });
94
+ return true;
95
+ } catch {
96
+ return false;
97
+ }
98
+ }
99
+
100
+ /** The message to print when elevation is missing. */
101
+ export function elevationMessage() {
102
+ return [
103
+ 'Installing the Windows service needs an Administrator terminal.',
104
+ '',
105
+ 'Right-click PowerShell → "Run as administrator", then:',
106
+ '',
107
+ ' ezz service install',
108
+ '',
109
+ 'You will not be asked for a password: the service runs as the virtual',
110
+ 'account NT SERVICE\\EasyDevOps, which Windows manages itself.',
111
+ ].join('\n');
112
+ }
113
+
114
+ /**
115
+ * Installs the service.
116
+ *
117
+ * Order matters and is deliberate:
118
+ * 1. the runtime copy, so there is something to run
119
+ * 2. verify native modules load with the copied node.exe — before a service
120
+ * is registered against a runtime that cannot start
121
+ * 3. WinSW, verified against its pinned hash
122
+ * 4. the XML
123
+ * 5. ACLs, so the service account can reach what it needs
124
+ * 6. register, then start
125
+ *
126
+ * Steps 2 and 3 are refusals, not warnings. Registering a service that cannot
127
+ * run, or installing an unverified binary with service privileges, are both
128
+ * worse than stopping with an explanation.
129
+ *
130
+ * @param {Object} opts
131
+ * @param {string} opts.dataDir
132
+ * @param {string} opts.appRoot
133
+ * @param {Object} [opts.config] Live settings, for the ACL paths
134
+ * @param {(line: string) => void} [opts.log]
135
+ * @param {Function} [opts.run]
136
+ * @param {Function} [opts.fetchImpl]
137
+ * @returns {Promise<{ ok: boolean, reason?: string, granted?: string[], runtime?: Object }>}
138
+ */
139
+ export async function install({
140
+ dataDir,
141
+ appRoot,
142
+ config = {},
143
+ log = () => {},
144
+ run = shellRun,
145
+ fetchImpl = fetch,
146
+ } = {}) {
147
+ if (!isWindows) return { ok: false, reason: 'Server mode is Windows-only' };
148
+
149
+ if (!canWriteProgramData()) {
150
+ return { ok: false, reason: elevationMessage(), needsElevation: true };
151
+ }
152
+
153
+ // ── 1. The pinned runtime ────────────────────────────────────────────────
154
+ log('Copying the runtime…');
155
+ const runtime = copyRuntime({ dataDir, appRoot, log });
156
+ if (!runtime.ok) return { ok: false, reason: runtime.reason };
157
+
158
+ // ── 2. Prove it can actually run ─────────────────────────────────────────
159
+ log('Checking that native modules load with the copied node.exe…');
160
+ const native = await verifyNativeModules({
161
+ nodeExe: runtime.nodeExe,
162
+ appDir: path.join(runtime.dir, 'app'),
163
+ });
164
+ if (!native.ok) {
165
+ return {
166
+ ok: false,
167
+ reason: `${native.reason}\n\n${native.fix ?? ''}`.trim(),
168
+ };
169
+ }
170
+ log(` ok — Node ${native.version}, ABI ${native.abi}`);
171
+
172
+ // ── 3. WinSW, hash-verified ──────────────────────────────────────────────
173
+ const winsw = await downloadWinsw({ dest: winswPath(), log, fetchImpl });
174
+ if (!winsw.ok) return { ok: false, reason: winsw.reason };
175
+
176
+ // ── 4. The service definition ────────────────────────────────────────────
177
+ const xml = buildServiceXml({
178
+ nodeExe: runtime.nodeExe,
179
+ entry: runtime.entry,
180
+ dataDir,
181
+ logDir: logDir(),
182
+ workingDir: path.join(runtime.dir, 'app'),
183
+ });
184
+
185
+ try {
186
+ fs.mkdirSync(logDir(), { recursive: true });
187
+ fs.writeFileSync(serviceXmlPath(), xml, 'utf8');
188
+ log(`Wrote ${serviceXmlPath()}`);
189
+ } catch (err) {
190
+ return { ok: false, reason: `could not write the service definition: ${err.message}` };
191
+ }
192
+
193
+ // ── 5. Register, so the virtual account exists ───────────────────────────
194
+ //
195
+ // The ACL grants have to come AFTER this: `NT SERVICE\EasyDevOps` does not
196
+ // exist as a security principal until a service of that name is registered,
197
+ // and icacls refuses an unknown account.
198
+ log('Registering the service…');
199
+ const registered = await run(`& "${winswPath()}" install "${serviceXmlPath()}"`, { timeout: 120_000 });
200
+ if (!registered.success) {
201
+ const output = `${registered.stdout ?? ''}\n${registered.stderr ?? ''}`.trim();
202
+ return { ok: false, reason: `WinSW could not register the service:\n${output.slice(0, 600)}` };
203
+ }
204
+
205
+ // ── 6. ACLs, from the live Settings — never a hardcoded path ─────────────
206
+ log('Granting the service account access…');
207
+ const grants = requiredGrants({
208
+ dataDir,
209
+ runtimeDir: runtimeDir(dataDir),
210
+ nginxDir: config.nginxDir ?? null,
211
+ sslDir: config.sslDir ?? null,
212
+ });
213
+ const acl = await applyGrants({ grants, run, log });
214
+
215
+ if (!acl.ok) {
216
+ // Not fatal: the service is registered and the data directory grant is the
217
+ // one that must work. A missing nginxDir grant degrades specific features
218
+ // and is reported rather than rolled back, because rolling back a working
219
+ // install over a directory that does not exist yet would be worse.
220
+ for (const failure of acl.failed) {
221
+ log(` warning: ${failure.path} — ${failure.reason}`);
222
+ }
223
+ }
224
+
225
+ // ── 7. Start ─────────────────────────────────────────────────────────────
226
+ log('Starting the service…');
227
+ const started = await run(`& "${winswPath()}" start`, { timeout: 60_000 });
228
+ if (!started.success) {
229
+ const output = `${started.stdout ?? ''}\n${started.stderr ?? ''}`.trim();
230
+ return {
231
+ ok: false,
232
+ reason: `the service was registered but would not start:\n${output.slice(0, 400)}\n\n`
233
+ + `Logs: ${errLogPath()}`,
234
+ registered: true,
235
+ };
236
+ }
237
+
238
+ return {
239
+ ok: true,
240
+ granted: acl.applied.map((g) => g.path),
241
+ aclFailures: acl.failed,
242
+ runtime: { nodeExe: runtime.nodeExe, entry: runtime.entry, version: native.version, abi: native.abi },
243
+ };
244
+ }
245
+
246
+ /**
247
+ * Stops, unregisters and cleans up.
248
+ *
249
+ * The ACL grants are revoked but the DATA is never touched here: whether the
250
+ * data moves back to `%APPDATA%` is a separate, explicit question asked by the
251
+ * uninstall flow (decision 5), because the ProgramData directory holds the
252
+ * live data and silently relocating it would be a surprise.
253
+ */
254
+ export async function uninstall({ dataDir, config = {}, log = () => {}, run = shellRun } = {}) {
255
+ if (!isWindows) return { ok: false, reason: 'Server mode is Windows-only' };
256
+
257
+ if (!canWriteProgramData()) {
258
+ return {
259
+ ok: false,
260
+ needsElevation: true,
261
+ reason: 'Removing the Windows service needs an Administrator terminal.\n\n'
262
+ + ' Right-click PowerShell → "Run as administrator", then: ezz service uninstall',
263
+ };
264
+ }
265
+
266
+ const notes = [];
267
+
268
+ if (fs.existsSync(winswPath())) {
269
+ // Stop first. A stop of something already stopped exits non-zero, which is
270
+ // not a failure worth aborting on.
271
+ const stopped = await run(`& "${winswPath()}" stop`, { timeout: 60_000 });
272
+ if (!stopped.success) notes.push('the service was not running');
273
+
274
+ const removed = await run(`& "${winswPath()}" uninstall`, { timeout: 60_000 });
275
+ if (!removed.success) {
276
+ const output = `${removed.stdout ?? ''}\n${removed.stderr ?? ''}`.trim();
277
+ return { ok: false, reason: `WinSW could not unregister the service:\n${output.slice(0, 600)}` };
278
+ }
279
+ log('Service unregistered.');
280
+ } else {
281
+ notes.push(`${WINSW_ASSET} was not found, so there was nothing to unregister`);
282
+ }
283
+
284
+ // Revoked while the account still resolves. After the service is gone the
285
+ // SID may no longer map to a name, and icacls would refuse — so the order
286
+ // here is the reverse of install's for a reason.
287
+ log('Removing the service account grants…');
288
+ const revoked = await revokeGrants({
289
+ paths: [dataDir, runtimeDir(dataDir), config.nginxDir, config.sslDir].filter(Boolean),
290
+ run,
291
+ log,
292
+ });
293
+ if (!revoked.ok) {
294
+ for (const failure of revoked.failed) notes.push(`could not clear grants on ${failure.path}`);
295
+ }
296
+
297
+ return { ok: true, notes };
298
+ }
299
+
300
+ /** `winsw restart`. */
301
+ export async function restart({ run = shellRun } = {}) {
302
+ if (!fs.existsSync(winswPath())) {
303
+ return { ok: false, reason: 'the service is not installed' };
304
+ }
305
+ const result = await run(`& "${winswPath()}" restart`, { timeout: 90_000 });
306
+ return {
307
+ ok: result.success,
308
+ reason: result.success ? null : `${result.stdout ?? ''}${result.stderr ?? ''}`.trim().slice(0, 400),
309
+ };
310
+ }
311
+
312
+ /**
313
+ * The message for an operation that needs elevation it does not have.
314
+ *
315
+ * Stopping and starting a Windows service require SERVICE_STOP / SERVICE_START
316
+ * rights, which an ordinary user does not have for a service they installed
317
+ * elevated. So this says so plainly rather than letting `sc` return
318
+ * "Access is denied" with no explanation.
319
+ */
320
+ function elevationFor(action) {
321
+ return `${action} the Windows service needs an Administrator terminal.\n\n`
322
+ + ' Right-click PowerShell → "Run as administrator", then:\n'
323
+ + ` ezz service ${action.toLowerCase()}\n\n`
324
+ + ' No password is needed — only elevation.';
325
+ }
326
+
327
+ /**
328
+ * `sc stop` — temporary. The service stays registered and set to Automatic, so
329
+ * it starts again at the next boot. `ezz service uninstall` is the permanent
330
+ * removal.
331
+ */
332
+ export async function stop({ run = shellRun } = {}) {
333
+ if (!fs.existsSync(winswPath())) {
334
+ return { ok: false, reason: 'the service is not installed, so there is nothing to stop' };
335
+ }
336
+
337
+ // `sc stop` rather than `winsw stop`: it is the Service Control Manager's own
338
+ // verb, so it works even when the WinSW wrapper binary is missing or broken,
339
+ // and its "Access is denied" is the authoritative answer on elevation.
340
+ const result = await run(`sc stop ${SERVICE_ID}`, { timeout: 60_000 });
341
+ const output = `${result.stdout ?? ''}\n${result.stderr ?? ''}`;
342
+
343
+ if (result.success) return { ok: true };
344
+
345
+ if (/Access is denied/i.test(output)) {
346
+ return { ok: false, needsElevation: true, reason: elevationFor('Stopping') };
347
+ }
348
+ // 1062: the service has not been started. Already stopped is a success.
349
+ if (/1062|has not been started/i.test(output)) {
350
+ return { ok: true, alreadyStopped: true };
351
+ }
352
+
353
+ return { ok: false, reason: output.trim().slice(0, 400) || `sc stop ${SERVICE_ID} failed` };
354
+ }
355
+
356
+ /** `sc start`. */
357
+ export async function start({ run = shellRun } = {}) {
358
+ if (!fs.existsSync(winswPath())) {
359
+ return { ok: false, reason: 'the service is not installed; run `ezz service install` first' };
360
+ }
361
+
362
+ const result = await run(`sc start ${SERVICE_ID}`, { timeout: 60_000 });
363
+ const output = `${result.stdout ?? ''}\n${result.stderr ?? ''}`;
364
+
365
+ if (result.success) return { ok: true };
366
+
367
+ if (/Access is denied/i.test(output)) {
368
+ return { ok: false, needsElevation: true, reason: elevationFor('Starting') };
369
+ }
370
+ // 1056: an instance is already running.
371
+ if (/1056|already running/i.test(output)) {
372
+ return { ok: true, alreadyRunning: true };
373
+ }
374
+
375
+ return { ok: false, reason: output.trim().slice(0, 400) || `sc start ${SERVICE_ID} failed` };
376
+ }
377
+
378
+ /**
379
+ * Counts recent restarts in WinSW's wrapper log.
380
+ *
381
+ * This is how a crash loop is detected on Windows. `sc query` reports the
382
+ * service as RUNNING between restarts, so a daemon that dies every five
383
+ * seconds looks healthy to anything that only asks the Service Control
384
+ * Manager. WinSW logs each start, and counting those within a window is what
385
+ * actually reveals it.
386
+ *
387
+ * @param {Object} [opts]
388
+ * @param {number} [opts.windowMs] How far back to look (default 10 minutes)
389
+ * @returns {{ restarts: number, crashLooping: boolean, since: Date|null }}
390
+ */
391
+ export function countRecentRestarts({ windowMs = 10 * 60_000, now = Date.now() } = {}) {
392
+ let text;
393
+ try {
394
+ text = fs.readFileSync(wrapperLogPath(), 'utf8');
395
+ } catch {
396
+ return { restarts: 0, crashLooping: false, since: null };
397
+ }
398
+
399
+ // WinSW writes lines like:
400
+ // 2026-11-14 04:17:03,123 INFO - Starting <exe>
401
+ // Only the tail is examined: a months-old log is large and its early history
402
+ // says nothing about whether the service is looping right now.
403
+ const lines = text.split(/\r?\n/).slice(-4000);
404
+ const cutoff = now - windowMs;
405
+
406
+ let restarts = 0;
407
+ let earliest = null;
408
+
409
+ for (const line of lines) {
410
+ if (!/\b(Starting|Restarting)\b/i.test(line)) continue;
411
+
412
+ const stamp = line.match(/^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2})/);
413
+ if (!stamp) continue;
414
+
415
+ const at = Date.parse(`${stamp[1]}T${stamp[2]}`);
416
+ if (!Number.isFinite(at) || at < cutoff) continue;
417
+
418
+ restarts++;
419
+ if (earliest === null || at < earliest) earliest = at;
420
+ }
421
+
422
+ // Three starts in ten minutes is not normal operation: the daemon is meant
423
+ // to start once and stay up. One or two can be a deliberate restart plus an
424
+ // upgrade, so the threshold is above that.
425
+ return {
426
+ restarts,
427
+ crashLooping: restarts >= 3,
428
+ since: earliest ? new Date(earliest) : null,
429
+ };
430
+ }
431
+
432
+ /**
433
+ * The service's state.
434
+ *
435
+ * @param {Object} [opts]
436
+ * @returns {Promise<Object>}
437
+ */
438
+ export async function status({ dataDir, config = {}, run = shellRun, granted = [] } = {}) {
439
+ const installed = fs.existsSync(winswPath()) && fs.existsSync(serviceXmlPath());
440
+
441
+ if (!installed) {
442
+ return {
443
+ installed: false,
444
+ running: false,
445
+ enabledOnBoot: false,
446
+ state: 'not installed',
447
+ restarts: 0,
448
+ crashLooping: false,
449
+ winswPath: winswPath(),
450
+ };
451
+ }
452
+
453
+ // `sc query` rather than `winsw status`: it does not depend on the wrapper
454
+ // being runnable, so a broken WinSW still reports a registered service.
455
+ const query = await run(`sc query ${SERVICE_ID}`, { timeout: 20_000 });
456
+ const output = `${query.stdout ?? ''}\n${query.stderr ?? ''}`;
457
+
458
+ const stateMatch = output.match(/STATE\s*:\s*\d+\s+(\w+)/i);
459
+ const scState = stateMatch ? stateMatch[1].toUpperCase() : null;
460
+
461
+ const config2 = await run(`sc qc ${SERVICE_ID}`, { timeout: 20_000 });
462
+ const startType = `${config2.stdout ?? ''}`.match(/START_TYPE\s*:\s*\d+\s+([\w_]+)/i)?.[1] ?? null;
463
+
464
+ const loop = countRecentRestarts();
465
+
466
+ const aclCheck = compareGrants({
467
+ granted,
468
+ required: requiredGrants({
469
+ dataDir,
470
+ runtimeDir: runtimeDir(dataDir),
471
+ nginxDir: config.nginxDir ?? null,
472
+ sslDir: config.sslDir ?? null,
473
+ }),
474
+ });
475
+
476
+ return {
477
+ installed: true,
478
+ running: scState === 'RUNNING',
479
+ enabledOnBoot: startType ? /AUTO_START/i.test(startType) : null,
480
+ state: scState ? scState.toLowerCase() : 'unknown',
481
+ startType,
482
+ restarts: loop.restarts,
483
+ crashLooping: loop.crashLooping,
484
+ crashLoopSince: loop.since,
485
+ acl: aclCheck,
486
+ winswPath: winswPath(),
487
+ logs: { out: outLogPath(), err: errLogPath(), wrapper: wrapperLogPath() },
488
+ };
489
+ }
490
+
491
+ /** Recent log lines, newest last. */
492
+ export function readLogs({ lines = 50, which = 'out' } = {}) {
493
+ const file = which === 'err' ? errLogPath() : which === 'wrapper' ? wrapperLogPath() : outLogPath();
494
+
495
+ let text;
496
+ try {
497
+ text = fs.readFileSync(file, 'utf8');
498
+ } catch (err) {
499
+ return {
500
+ ok: false,
501
+ file,
502
+ output: err.code === 'ENOENT'
503
+ ? `No log yet at ${file}. The service may not have started.`
504
+ : `Could not read ${file}: ${err.message}`,
505
+ };
506
+ }
507
+
508
+ const all = text.split(/\r?\n/).filter(Boolean);
509
+ return { ok: true, file, output: all.slice(-Math.max(1, Math.min(5000, Number(lines) || 50))).join('\n') };
510
+ }
511
+
512
+ /**
513
+ * Re-applies what install set up, without unregistering the service.
514
+ *
515
+ * The two things that drift: the ACL grants, when a path changes in Settings,
516
+ * and the runtime copy, when the application is upgraded under it. Both are
517
+ * re-done; the service is then restarted so it picks them up.
518
+ */
519
+ export async function repair({ dataDir, appRoot, config = {}, log = () => {}, run = shellRun } = {}) {
520
+ if (!isWindows) return { ok: false, reason: 'Server mode is Windows-only' };
521
+
522
+ if (!canWriteProgramData()) {
523
+ return {
524
+ ok: false,
525
+ needsElevation: true,
526
+ reason: 'Repairing the Windows service needs an Administrator terminal.\n\n'
527
+ + ' Right-click PowerShell → "Run as administrator", then: ezz service repair',
528
+ };
529
+ }
530
+
531
+ if (!fs.existsSync(winswPath())) {
532
+ return { ok: false, reason: 'the service is not installed; run `ezz service install` instead' };
533
+ }
534
+
535
+ // The wrapper itself is re-verified: a tampered or truncated WinSW is worth
536
+ // catching at repair time too, not only at install.
537
+ const wrapper = await verifyWinsw(winswPath());
538
+ if (!wrapper.ok) {
539
+ log('The installed WinSW did not verify; re-downloading.');
540
+ const again = await downloadWinsw({ dest: winswPath(), log });
541
+ if (!again.ok) return { ok: false, reason: again.reason };
542
+ }
543
+
544
+ log('Refreshing the runtime copy…');
545
+ const runtime = copyRuntime({ dataDir, appRoot, log });
546
+ if (!runtime.ok) return { ok: false, reason: runtime.reason };
547
+
548
+ const native = await verifyNativeModules({
549
+ nodeExe: runtime.nodeExe,
550
+ appDir: path.join(runtime.dir, 'app'),
551
+ });
552
+ if (!native.ok) return { ok: false, reason: `${native.reason}\n\n${native.fix ?? ''}`.trim() };
553
+
554
+ log('Re-applying the service account grants…');
555
+ const grants = requiredGrants({
556
+ dataDir,
557
+ runtimeDir: runtimeDir(dataDir),
558
+ nginxDir: config.nginxDir ?? null,
559
+ sslDir: config.sslDir ?? null,
560
+ });
561
+ const acl = await applyGrants({ grants, run, log });
562
+
563
+ const restarted = await restart({ run });
564
+ if (!restarted.ok) {
565
+ return { ok: false, reason: `permissions were re-applied but the restart failed: ${restarted.reason}` };
566
+ }
567
+
568
+ return {
569
+ ok: true,
570
+ granted: acl.applied.map((g) => g.path),
571
+ aclFailures: acl.failed,
572
+ runtime: { version: native.version, abi: native.abi },
573
+ };
574
+ }
575
+
576
+ export { SERVICE_ID, SERVICE_DISPLAY_NAME };