easy-devops 1.4.0 → 1.4.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.
@@ -28,11 +28,13 @@ import fs from 'fs';
28
28
  import path from 'path';
29
29
 
30
30
  import { run as shellRun } from '../shell.js';
31
- import { programDataDir, isWindows } from '../platform.js';
31
+ import { programDataDir, isWindows, WINDOWS_SC, windowsElevationCheckCmd } from '../platform.js';
32
32
  import {
33
33
  SERVICE_ID,
34
34
  SERVICE_DISPLAY_NAME,
35
- WINSW_ASSET,
35
+ WINSW_EXE_NAME,
36
+ WINSW_XML_NAME,
37
+ LEGACY_WINSW_NAME,
36
38
  buildServiceXml,
37
39
  downloadWinsw,
38
40
  verifyWinsw,
@@ -44,15 +46,22 @@ import { runtimeDir, copyRuntime, verifyNativeModules } from './runtime.js';
44
46
  export function binDir() {
45
47
  return path.join(programDataDir(), 'bin');
46
48
  }
49
+ /**
50
+ * The wrapper and its definition: `EasyDevOps.exe` beside `EasyDevOps.xml`.
51
+ *
52
+ * WinSW v2 reads its configuration only from `<own base name>.xml` in its own
53
+ * directory — a path given on the command line is ignored — so the two names
54
+ * must share a stem. Both come from winsw.js, derived from SERVICE_ID.
55
+ */
47
56
  export function winswPath() {
48
- return path.join(binDir(), WINSW_ASSET);
57
+ return path.join(binDir(), WINSW_EXE_NAME);
49
58
  }
50
59
  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`);
60
+ return path.join(binDir(), WINSW_XML_NAME);
61
+ }
62
+ /** Where 1.4.0 left the wrapper. Only ever removed, never run. */
63
+ export function legacyWinswPath() {
64
+ return path.join(binDir(), LEGACY_WINSW_NAME);
56
65
  }
57
66
  export function logDir() {
58
67
  return path.join(programDataDir(), 'logs');
@@ -97,20 +106,128 @@ export function canWriteProgramData() {
97
106
  }
98
107
  }
99
108
 
109
+ /** Where the troubleshooting guide lives, for links in messages. */
110
+ export const TROUBLESHOOTING_URL = 'https://easy-devops.devxor.team/docs/troubleshooting';
111
+
100
112
  /** The message to print when elevation is missing. */
101
- export function elevationMessage() {
113
+ export function elevationMessage(command = 'ezz service install') {
102
114
  return [
103
- 'Installing the Windows service needs an Administrator terminal.',
115
+ 'Server mode needs an elevated terminal, and this one is not.',
116
+ 'Nothing was copied, migrated or registered.',
104
117
  '',
105
- 'Right-click PowerShell → "Run as administrator", then:',
118
+ 'Open PowerShell with "Run as administrator" and run the command again:',
106
119
  '',
107
- ' ezz service install',
120
+ ` ${command}`,
108
121
  '',
109
122
  'You will not be asked for a password: the service runs as the virtual',
110
123
  'account NT SERVICE\\EasyDevOps, which Windows manages itself.',
124
+ `More: ${TROUBLESHOOTING_URL}#uac-unknown-publisher`,
111
125
  ].join('\n');
112
126
  }
113
127
 
128
+ /**
129
+ * One line explaining the UAC prompt, printed before the wrapper is called
130
+ * when elevation could not be confirmed. WinSW is not code-signed, so Windows
131
+ * shows "Unknown publisher" for EasyDevOps.exe; it is still the pinned binary.
132
+ */
133
+ export const UAC_NOTE = `If Windows asks for permission for ${WINSW_EXE_NAME} ("Unknown publisher"): `
134
+ + 'it is WinSW, the open-source service wrapper, verified by SHA-256 before use and not code-signed.';
135
+
136
+ /**
137
+ * Whether this process runs elevated — asked of Windows, not inferred.
138
+ *
139
+ * canWriteProgramData() alone was not enough: when `C:\ProgramData\easy-devops`
140
+ * does not exist yet it probes ProgramData itself, where ordinary users may
141
+ * create folders, so a normal terminal passed it, migrated the data, and then
142
+ * triggered a UAC prompt for the unsigned wrapper. This is the check that runs
143
+ * before any Server-mode step.
144
+ *
145
+ * @returns {Promise<boolean|null>} null when PowerShell gave no usable answer
146
+ */
147
+ export async function isElevated({ run = shellRun } = {}) {
148
+ const result = await run(windowsElevationCheckCmd(), { timeout: 20_000 });
149
+ const output = `${result?.stdout ?? ''}`.trim();
150
+ if (/^true$/im.test(output)) return true;
151
+ if (/^false$/im.test(output)) return false;
152
+ return null;
153
+ }
154
+
155
+ /** Combined output of a shell result, trimmed. */
156
+ function outputOf(result) {
157
+ return `${result?.stdout ?? ''}\n${result?.stderr ?? ''}`.trim();
158
+ }
159
+
160
+ /**
161
+ * Whether the Service Control Manager knows a service called SERVICE_ID.
162
+ *
163
+ * Asked of `sc`, not of WinSW: a registration left behind by a failed or
164
+ * interrupted install may point at a wrapper that no longer exists, and `sc`
165
+ * still answers for it. 1060 is "The specified service does not exist".
166
+ *
167
+ * @returns {Promise<boolean|null>} null when `sc` itself gave no usable answer
168
+ */
169
+ export async function isRegistered({ run = shellRun } = {}) {
170
+ const result = await run(`${WINDOWS_SC} query ${SERVICE_ID}`, { timeout: 20_000 });
171
+ const output = outputOf(result);
172
+ if (result.success || /STATE\s*:/i.test(output)) return true;
173
+ if (/1060|does not exist/i.test(output)) return false;
174
+ return null;
175
+ }
176
+
177
+ /**
178
+ * Removes a registration of SERVICE_ID, whatever state it is in.
179
+ *
180
+ * WinSW's own `stop`/`uninstall` first, when the wrapper is present and has
181
+ * its definition beside it — that is the clean path. Then, if the Service
182
+ * Control Manager still knows the name, `sc stop` + `sc delete`, which work
183
+ * without the wrapper. A service that is marked for deletion while a handle
184
+ * is open (services.msc, for instance) disappears once that handle closes;
185
+ * `sc delete` reports success in that case, and so does this.
186
+ *
187
+ * @returns {Promise<{ ok: boolean, removed: boolean, reason?: string }>}
188
+ */
189
+ export async function unregister({ run = shellRun, log = () => {} } = {}) {
190
+ let removed = false;
191
+
192
+ if (fs.existsSync(winswPath()) && fs.existsSync(serviceXmlPath())) {
193
+ await run(`& "${winswPath()}" stop`, { timeout: 60_000 });
194
+ const viaWinsw = await run(`& "${winswPath()}" uninstall`, { timeout: 60_000 });
195
+ if (viaWinsw.success) removed = true;
196
+ }
197
+
198
+ const still = await isRegistered({ run });
199
+ if (still === false) return { ok: true, removed };
200
+
201
+ await run(`${WINDOWS_SC} stop ${SERVICE_ID}`, { timeout: 60_000 });
202
+ const deleted = await run(`${WINDOWS_SC} delete ${SERVICE_ID}`, { timeout: 30_000 });
203
+ const output = outputOf(deleted);
204
+
205
+ if (deleted.success || /1060|does not exist/i.test(output)) {
206
+ log(`Removed the ${SERVICE_ID} service registration.`);
207
+ return { ok: true, removed: true };
208
+ }
209
+ if (/1072|marked for deletion/i.test(output)) {
210
+ return {
211
+ ok: true,
212
+ removed: true,
213
+ reason: 'Windows has marked the service for deletion; close services.msc (or reboot) to finish it.',
214
+ };
215
+ }
216
+ return { ok: false, removed, reason: output.slice(0, 400) || `${WINDOWS_SC} delete ${SERVICE_ID} failed` };
217
+ }
218
+
219
+ /** Removes the wrapper 1.4.0 left under its release name. Best effort. */
220
+ function removeLegacyWinsw(log) {
221
+ const legacy = legacyWinswPath();
222
+ if (legacy === winswPath() || !fs.existsSync(legacy)) return;
223
+ try {
224
+ fs.rmSync(legacy, { force: true });
225
+ log(`Removed ${legacy} (the wrapper's old name).`);
226
+ } catch (err) {
227
+ log(` warning: could not remove ${legacy}: ${err.message}`);
228
+ }
229
+ }
230
+
114
231
  /**
115
232
  * Installs the service.
116
233
  *
@@ -134,7 +251,10 @@ export function elevationMessage() {
134
251
  * @param {(line: string) => void} [opts.log]
135
252
  * @param {Function} [opts.run]
136
253
  * @param {Function} [opts.fetchImpl]
137
- * @returns {Promise<{ ok: boolean, reason?: string, granted?: string[], runtime?: Object }>}
254
+ * @param {Object} [opts.deps] Injected for tests: canWrite, isWindows, copyRuntime, verifyNativeModules,
255
+ * verifyWinsw
256
+ * @returns {Promise<{ ok: boolean, reason?: string, granted?: string[], runtime?: Object,
257
+ * registrationFailed?: boolean }>}
138
258
  */
139
259
  export async function install({
140
260
  dataDir,
@@ -143,21 +263,24 @@ export async function install({
143
263
  log = () => {},
144
264
  run = shellRun,
145
265
  fetchImpl = fetch,
266
+ deps = {},
146
267
  } = {}) {
147
- if (!isWindows) return { ok: false, reason: 'Server mode is Windows-only' };
268
+ if (!(deps.isWindows ?? isWindows)) return { ok: false, reason: 'Server mode is Windows-only' };
148
269
 
149
- if (!canWriteProgramData()) {
270
+ // A real elevation check first; the write probe stays as a second opinion.
271
+ const elevated = await (deps.isElevated ?? (() => isElevated({ run })))();
272
+ if (elevated === false || !(deps.canWrite ?? canWriteProgramData)()) {
150
273
  return { ok: false, reason: elevationMessage(), needsElevation: true };
151
274
  }
152
275
 
153
276
  // ── 1. The pinned runtime ────────────────────────────────────────────────
154
277
  log('Copying the runtime…');
155
- const runtime = copyRuntime({ dataDir, appRoot, log });
278
+ const runtime = (deps.copyRuntime ?? copyRuntime)({ dataDir, appRoot, log });
156
279
  if (!runtime.ok) return { ok: false, reason: runtime.reason };
157
280
 
158
281
  // ── 2. Prove it can actually run ─────────────────────────────────────────
159
282
  log('Checking that native modules load with the copied node.exe…');
160
- const native = await verifyNativeModules({
283
+ const native = await (deps.verifyNativeModules ?? verifyNativeModules)({
161
284
  nodeExe: runtime.nodeExe,
162
285
  appDir: path.join(runtime.dir, 'app'),
163
286
  });
@@ -169,9 +292,10 @@ export async function install({
169
292
  }
170
293
  log(` ok — Node ${native.version}, ABI ${native.abi}`);
171
294
 
172
- // ── 3. WinSW, hash-verified ──────────────────────────────────────────────
173
- const winsw = await downloadWinsw({ dest: winswPath(), log, fetchImpl });
295
+ // ── 3. WinSW, hash-verified, stored as EasyDevOps.exe ────────────────────
296
+ const winsw = await downloadWinsw({ dest: winswPath(), log, fetchImpl, verify: deps.verifyWinsw });
174
297
  if (!winsw.ok) return { ok: false, reason: winsw.reason };
298
+ removeLegacyWinsw(log);
175
299
 
176
300
  // ── 4. The service definition ────────────────────────────────────────────
177
301
  const xml = buildServiceXml({
@@ -195,11 +319,53 @@ export async function install({
195
319
  // The ACL grants have to come AFTER this: `NT SERVICE\EasyDevOps` does not
196
320
  // exist as a security principal until a service of that name is registered,
197
321
  // and icacls refuses an unknown account.
322
+ //
323
+ // A registration left by an earlier attempt (an interrupted install, or one
324
+ // that pointed at a wrapper that has since moved) is removed first:
325
+ // `winsw install` refuses a name that already exists, and re-registering is
326
+ // the only way to make it point at this wrapper and this definition.
327
+ const existing = await isRegistered({ run });
328
+ if (existing) {
329
+ log(`A ${SERVICE_ID} service is already registered; removing it before registering again…`);
330
+ const cleared = await unregister({ run, log });
331
+ if (!cleared.ok) {
332
+ return {
333
+ ok: false,
334
+ registrationFailed: true,
335
+ reason: `an existing ${SERVICE_ID} service could not be removed first:\n${cleared.reason}\n\n`
336
+ + `Hint: stop and delete it in an Administrator PowerShell (sc.exe stop ${SERVICE_ID}; `
337
+ + `sc.exe delete ${SERVICE_ID}), then run ezz service install again.`,
338
+ };
339
+ }
340
+ }
341
+
342
+ // No path argument: WinSW v2 ignores it and reads `EasyDevOps.xml` beside
343
+ // `EasyDevOps.exe`. Passing it suggested otherwise, which is how the name
344
+ // mismatch went unnoticed.
198
345
  log('Registering the service…');
199
- const registered = await run(`& "${winswPath()}" install "${serviceXmlPath()}"`, { timeout: 120_000 });
346
+ // Elevation is confirmed in the normal case, so no prompt appears. When it
347
+ // could not be confirmed, say what a prompt would be before it shows up.
348
+ if (elevated !== true) log(UAC_NOTE);
349
+ const registered = await run(`& "${winswPath()}" install`, { timeout: 120_000 });
200
350
  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)}` };
351
+ const output = outputOf(registered);
352
+
353
+ // WinSW can fail after the Service Control Manager accepted the name, so
354
+ // a failed register is followed by a clean-up: nothing half-registered is
355
+ // left for the next attempt to trip over.
356
+ const cleanup = await unregister({ run, log });
357
+ const leftover = cleanup.ok
358
+ ? 'Nothing was left registered.'
359
+ : `A partial registration could not be removed (${cleanup.reason}); `
360
+ + `remove it with: sc.exe delete ${SERVICE_ID}`;
361
+
362
+ return {
363
+ ok: false,
364
+ registrationFailed: true,
365
+ reason: `WinSW could not register the service:\n${output.slice(0, 600)}\n\n`
366
+ + `Hint: ${WINSW_EXE_NAME} and ${WINSW_XML_NAME} must sit side by side in ${binDir()}; `
367
+ + `fix the cause above and run ezz service install again in an Administrator PowerShell. ${leftover}`,
368
+ };
203
369
  }
204
370
 
205
371
  // ── 6. ACLs, from the live Settings — never a hardcoded path ─────────────
@@ -230,8 +396,13 @@ export async function install({
230
396
  return {
231
397
  ok: false,
232
398
  reason: `the service was registered but would not start:\n${output.slice(0, 400)}\n\n`
233
- + `Logs: ${errLogPath()}`,
399
+ + `Logs: ${errLogPath()} — more at ${TROUBLESHOOTING_URL}#logs`,
234
400
  registered: true,
401
+ // Registration and the grants did succeed, and the caller records them:
402
+ // status must not report a registered service as "not installed".
403
+ granted: acl.applied.map((g) => g.path),
404
+ aclFailures: acl.failed,
405
+ runtime: { nodeExe: runtime.nodeExe, entry: runtime.entry, version: native.version, abi: native.abi },
235
406
  };
236
407
  }
237
408
 
@@ -254,7 +425,7 @@ export async function install({
254
425
  export async function uninstall({ dataDir, config = {}, log = () => {}, run = shellRun } = {}) {
255
426
  if (!isWindows) return { ok: false, reason: 'Server mode is Windows-only' };
256
427
 
257
- if (!canWriteProgramData()) {
428
+ if ((await isElevated({ run })) === false || !canWriteProgramData()) {
258
429
  return {
259
430
  ok: false,
260
431
  needsElevation: true,
@@ -265,21 +436,18 @@ export async function uninstall({ dataDir, config = {}, log = () => {}, run = sh
265
436
 
266
437
  const notes = [];
267
438
 
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`);
439
+ // WinSW's own stop + uninstall when the wrapper is there, and `sc delete`
440
+ // for a registration whose wrapper is missing — so a service left behind by
441
+ // a failed or interrupted install can always be removed.
442
+ const removed = await unregister({ run, log });
443
+ if (!removed.ok) {
444
+ return { ok: false, reason: `the service could not be unregistered:\n${removed.reason}` };
282
445
  }
446
+ if (removed.reason) notes.push(removed.reason);
447
+ if (removed.removed) log('Service unregistered.');
448
+ else notes.push('no service was registered, so there was nothing to unregister');
449
+
450
+ removeLegacyWinsw(log);
283
451
 
284
452
  // Revoked while the account still resolves. After the service is gone the
285
453
  // SID may no longer map to a name, and icacls would refuse — so the order
@@ -297,11 +465,15 @@ export async function uninstall({ dataDir, config = {}, log = () => {}, run = sh
297
465
  return { ok: true, notes };
298
466
  }
299
467
 
300
- /** `winsw restart`. */
468
+ /** `winsw restart`. Calls the wrapper, so it needs elevation like install. */
301
469
  export async function restart({ run = shellRun } = {}) {
302
470
  if (!fs.existsSync(winswPath())) {
303
471
  return { ok: false, reason: 'the service is not installed' };
304
472
  }
473
+ const elevated = await isElevated({ run });
474
+ if (elevated === false) {
475
+ return { ok: false, needsElevation: true, reason: elevationFor('Restarting') };
476
+ }
305
477
  const result = await run(`& "${winswPath()}" restart`, { timeout: 90_000 });
306
478
  return {
307
479
  ok: result.success,
@@ -309,6 +481,38 @@ export async function restart({ run = shellRun } = {}) {
309
481
  };
310
482
  }
311
483
 
484
+ /**
485
+ * The Service Control Manager's state for SERVICE_ID: 'RUNNING', 'STOPPED',
486
+ * 'START_PENDING'…, 'MISSING' (1060) or null when `sc.exe` gave no answer.
487
+ */
488
+ export async function queryState({ run = shellRun } = {}) {
489
+ const result = await run(`${WINDOWS_SC} query ${SERVICE_ID}`, { timeout: 20_000 });
490
+ const output = outputOf(result);
491
+ const match = output.match(/STATE\s*:\s*\d+\s+(\w+)/i);
492
+ if (match) return match[1].toUpperCase();
493
+ if (/1060|does not exist/i.test(output)) return 'MISSING';
494
+ return null;
495
+ }
496
+
497
+ /**
498
+ * Polls until the service reaches `wanted`, or the time runs out.
499
+ *
500
+ * Needed after a stop: `sc.exe stop` returns while the service is still
501
+ * STOP_PENDING, and node.exe stays locked until its process has exited — a
502
+ * copy over it in that window fails with EBUSY, which is how 1.4.0's repair
503
+ * failed. STOPPED is reported only once the wrapper's child is gone.
504
+ */
505
+ export async function waitForState({ wanted, run = shellRun, timeoutMs = 30_000, intervalMs = 500 } = {}) {
506
+ const deadline = Date.now() + timeoutMs;
507
+ let state = null;
508
+ while (Date.now() < deadline) {
509
+ state = await queryState({ run });
510
+ if (state === wanted || (wanted === 'STOPPED' && state === 'MISSING')) return { reached: true, state };
511
+ await new Promise((r) => setTimeout(r, intervalMs));
512
+ }
513
+ return { reached: false, state };
514
+ }
515
+
312
516
  /**
313
517
  * The message for an operation that needs elevation it does not have.
314
518
  *
@@ -318,9 +522,11 @@ export async function restart({ run = shellRun } = {}) {
318
522
  * "Access is denied" with no explanation.
319
523
  */
320
524
  function elevationFor(action) {
525
+ // "Stopping" → `ezz service stop`. It used to print `ezz service stopping`.
526
+ const verb = { Stopping: 'stop', Starting: 'start', Restarting: 'restart' }[action] ?? action.toLowerCase();
321
527
  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`
528
+ + ' Open PowerShell with "Run as administrator" and run the command again:\n'
529
+ + ` ezz service ${verb}\n\n`
324
530
  + ' No password is needed — only elevation.';
325
531
  }
326
532
 
@@ -329,19 +535,20 @@ function elevationFor(action) {
329
535
  * it starts again at the next boot. `ezz service uninstall` is the permanent
330
536
  * removal.
331
537
  */
332
- export async function stop({ run = shellRun } = {}) {
333
- if (!fs.existsSync(winswPath())) {
538
+ export async function stop({ run = shellRun, stopWaitMs = 30_000 } = {}) {
539
+ // Windows is asked, not the files: a registration whose wrapper is gone can
540
+ // still be stopped, and files without a registration cannot.
541
+ if ((await isRegistered({ run })) === false) {
334
542
  return { ok: false, reason: 'the service is not installed, so there is nothing to stop' };
335
543
  }
336
544
 
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 });
545
+ // `sc.exe stop` rather than `winsw stop`: it is the Service Control
546
+ // Manager's own verb, so it works even when the WinSW wrapper binary is
547
+ // missing or broken, and its "Access is denied" is the authoritative answer
548
+ // on elevation.
549
+ const result = await run(`${WINDOWS_SC} stop ${SERVICE_ID}`, { timeout: 60_000 });
341
550
  const output = `${result.stdout ?? ''}\n${result.stderr ?? ''}`;
342
551
 
343
- if (result.success) return { ok: true };
344
-
345
552
  if (/Access is denied/i.test(output)) {
346
553
  return { ok: false, needsElevation: true, reason: elevationFor('Stopping') };
347
554
  }
@@ -349,17 +556,30 @@ export async function stop({ run = shellRun } = {}) {
349
556
  if (/1062|has not been started/i.test(output)) {
350
557
  return { ok: true, alreadyStopped: true };
351
558
  }
559
+ if (!result.success) {
560
+ return { ok: false, reason: output.trim().slice(0, 400) || `${WINDOWS_SC} stop ${SERVICE_ID} failed` };
561
+ }
352
562
 
353
- return { ok: false, reason: output.trim().slice(0, 400) || `sc stop ${SERVICE_ID} failed` };
563
+ // Accepted is not stopped. Callers replace files the process holds open
564
+ // (repair, update, runtime update), so this returns only once it is gone.
565
+ const settled = await waitForState({ wanted: 'STOPPED', run, timeoutMs: stopWaitMs });
566
+ if (!settled.reached) {
567
+ return {
568
+ ok: false,
569
+ reason: `the stop was accepted but the service was still ${settled.state ?? 'not reporting'} after `
570
+ + `${Math.round(stopWaitMs / 1000)}s. Check the wrapper log: ${wrapperLogPath()}`,
571
+ };
572
+ }
573
+ return { ok: true };
354
574
  }
355
575
 
356
- /** `sc start`. */
576
+ /** `sc.exe start`. */
357
577
  export async function start({ run = shellRun } = {}) {
358
- if (!fs.existsSync(winswPath())) {
578
+ if ((await isRegistered({ run })) === false) {
359
579
  return { ok: false, reason: 'the service is not installed; run `ezz service install` first' };
360
580
  }
361
581
 
362
- const result = await run(`sc start ${SERVICE_ID}`, { timeout: 60_000 });
582
+ const result = await run(`${WINDOWS_SC} start ${SERVICE_ID}`, { timeout: 60_000 });
363
583
  const output = `${result.stdout ?? ''}\n${result.stderr ?? ''}`;
364
584
 
365
585
  if (result.success) return { ok: true };
@@ -372,7 +592,7 @@ export async function start({ run = shellRun } = {}) {
372
592
  return { ok: true, alreadyRunning: true };
373
593
  }
374
594
 
375
- return { ok: false, reason: output.trim().slice(0, 400) || `sc start ${SERVICE_ID} failed` };
595
+ return { ok: false, reason: output.trim().slice(0, 400) || `${WINDOWS_SC} start ${SERVICE_ID} failed` };
376
596
  }
377
597
 
378
598
  /**
@@ -384,48 +604,88 @@ export async function start({ run = shellRun } = {}) {
384
604
  * Manager. WinSW logs each start, and counting those within a window is what
385
605
  * actually reveals it.
386
606
  *
607
+ * ── What counts ────────────────────────────────────────────────────────────
608
+ *
609
+ * Only a real process start: WinSW's "Started process <pid>", which the
610
+ * service-mode instance writes when it launches the daemon. 1.4.0 counted
611
+ * every line containing "Starting", and every CLI call of the wrapper writes
612
+ * "Starting WinSW in console mode" — so `install`, `start` and `restart`
613
+ * alone produced a "crash loop" on a perfectly healthy service.
614
+ *
615
+ * And a start is a CRASH restart only when the process before it did not stop
616
+ * cleanly. A service stop, restart, update or repair logs "Stopping …" and
617
+ * "Process <pid> canceled with code 0" first; a daemon that died on its own
618
+ * does not. So a stop followed by a start is a restart, not a crash.
619
+ *
387
620
  * @param {Object} [opts]
388
621
  * @param {number} [opts.windowMs] How far back to look (default 10 minutes)
389
- * @returns {{ restarts: number, crashLooping: boolean, since: Date|null }}
622
+ * @param {string} [opts.text] The log text, for tests (default: the wrapper log)
623
+ * @returns {{ restarts: number, cleanRestarts: number, crashRestarts: number,
624
+ * crashLooping: boolean, since: Date|null }}
390
625
  */
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 };
626
+ export function countRecentRestarts({ windowMs = 10 * 60_000, now = Date.now(), text = null } = {}) {
627
+ const none = { restarts: 0, cleanRestarts: 0, crashRestarts: 0, crashLooping: false, since: null };
628
+
629
+ if (text === null) {
630
+ try {
631
+ text = fs.readFileSync(wrapperLogPath(), 'utf8');
632
+ } catch {
633
+ return none;
634
+ }
397
635
  }
398
636
 
399
637
  // WinSW writes lines like:
400
- // 2026-11-14 04:17:03,123 INFO - Starting <exe>
638
+ // 2026-11-14 04:17:03,123 INFO - Started process 12700
401
639
  // Only the tail is examined: a months-old log is large and its early history
402
640
  // says nothing about whether the service is looping right now.
403
641
  const lines = text.split(/\r?\n/).slice(-4000);
404
642
  const cutoff = now - windowMs;
405
643
 
644
+ const CLEAN_STOP = /\bStopping\b|canceled with code 0\b|finished with (code )?0\b|exited with code 0\b/i;
645
+ const STARTED = /\bStarted process\s+\d+/i;
646
+
647
+ let sawProcess = false; // a daemon process was started earlier in the log
648
+ let cleanSince = false; // ...and it was stopped cleanly since then
406
649
  let restarts = 0;
407
- let earliest = null;
650
+ let cleanRestarts = 0;
651
+ let crashRestarts = 0;
652
+ let earliestCrash = null;
408
653
 
409
654
  for (const line of lines) {
410
- if (!/\b(Starting|Restarting)\b/i.test(line)) continue;
655
+ if (CLEAN_STOP.test(line)) {
656
+ cleanSince = true;
657
+ continue;
658
+ }
659
+ if (!STARTED.test(line)) continue;
411
660
 
412
661
  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;
662
+ const at = stamp ? Date.parse(`${stamp[1]}T${stamp[2]}`) : NaN;
663
+ const inWindow = Number.isFinite(at) && at >= cutoff;
664
+
665
+ // The first process in the log is a start, not a restart.
666
+ if (sawProcess && inWindow) {
667
+ restarts++;
668
+ if (cleanSince) {
669
+ cleanRestarts++;
670
+ } else {
671
+ crashRestarts++;
672
+ if (earliestCrash === null || at < earliestCrash) earliestCrash = at;
673
+ }
674
+ }
417
675
 
418
- restarts++;
419
- if (earliest === null || at < earliest) earliest = at;
676
+ sawProcess = true;
677
+ cleanSince = false;
420
678
  }
421
679
 
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.
680
+ // Three unclean restarts in ten minutes is not normal operation: WinSW's
681
+ // backoff is 5 s, 20 s, then a minute, so that is a daemon dying on its own.
682
+ // Deliberate restarts never count towards it.
425
683
  return {
426
684
  restarts,
427
- crashLooping: restarts >= 3,
428
- since: earliest ? new Date(earliest) : null,
685
+ cleanRestarts,
686
+ crashRestarts,
687
+ crashLooping: crashRestarts >= 3,
688
+ since: earliestCrash ? new Date(earliestCrash) : null,
429
689
  };
430
690
  }
431
691
 
@@ -436,29 +696,37 @@ export function countRecentRestarts({ windowMs = 10 * 60_000, now = Date.now() }
436
696
  * @returns {Promise<Object>}
437
697
  */
438
698
  export async function status({ dataDir, config = {}, run = shellRun, granted = [] } = {}) {
439
- const installed = fs.existsSync(winswPath()) && fs.existsSync(serviceXmlPath());
699
+ const filesPresent = fs.existsSync(winswPath()) && fs.existsSync(serviceXmlPath());
700
+
701
+ // Windows is the authority on whether the service exists — not the files.
702
+ // 1.4.0 said "Installed: yes" from the files alone while `sc query` answered
703
+ // 1060, and (through the Set-Content alias) could not read the state at all.
704
+ const scState = await queryState({ run });
705
+ const registered = scState === 'MISSING' ? false : scState ? true : null;
440
706
 
441
- if (!installed) {
707
+ if (registered === false || (registered === null && !filesPresent)) {
442
708
  return {
443
709
  installed: false,
710
+ registered,
711
+ filesPresent,
444
712
  running: false,
445
713
  enabledOnBoot: false,
446
714
  state: 'not installed',
447
715
  restarts: 0,
716
+ cleanRestarts: 0,
717
+ crashRestarts: 0,
448
718
  crashLooping: false,
449
719
  winswPath: winswPath(),
720
+ // Files left behind without a registration: a removed or never-finished
721
+ // install. Said explicitly, because "not installed" alone is confusing
722
+ // when the wrapper is sitting right there.
723
+ mismatch: filesPresent && registered === false
724
+ ? `${WINSW_EXE_NAME} and ${WINSW_XML_NAME} are in ${binDir()}, but Windows has no ${SERVICE_ID} service`
725
+ : null,
450
726
  };
451
727
  }
452
728
 
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 });
729
+ const config2 = await run(`${WINDOWS_SC} qc ${SERVICE_ID}`, { timeout: 20_000 });
462
730
  const startType = `${config2.stdout ?? ''}`.match(/START_TYPE\s*:\s*\d+\s+([\w_]+)/i)?.[1] ?? null;
463
731
 
464
732
  const loop = countRecentRestarts();
@@ -475,11 +743,20 @@ export async function status({ dataDir, config = {}, run = shellRun, granted = [
475
743
 
476
744
  return {
477
745
  installed: true,
746
+ registered,
747
+ filesPresent,
748
+ // Registered, but the wrapper or its definition is missing: the service
749
+ // cannot start. A reinstall puts them back.
750
+ mismatch: registered && !filesPresent
751
+ ? `Windows has a ${SERVICE_ID} service, but ${WINSW_EXE_NAME} or ${WINSW_XML_NAME} is missing from ${binDir()}`
752
+ : null,
478
753
  running: scState === 'RUNNING',
479
754
  enabledOnBoot: startType ? /AUTO_START/i.test(startType) : null,
480
755
  state: scState ? scState.toLowerCase() : 'unknown',
481
756
  startType,
482
757
  restarts: loop.restarts,
758
+ cleanRestarts: loop.cleanRestarts,
759
+ crashRestarts: loop.crashRestarts,
483
760
  crashLooping: loop.crashLooping,
484
761
  crashLoopSince: loop.since,
485
762
  acl: aclCheck,
@@ -516,54 +793,122 @@ export function readLogs({ lines = 50, which = 'out' } = {}) {
516
793
  * and the runtime copy, when the application is upgraded under it. Both are
517
794
  * re-done; the service is then restarted so it picks them up.
518
795
  */
519
- export async function repair({ dataDir, appRoot, config = {}, log = () => {}, run = shellRun } = {}) {
520
- if (!isWindows) return { ok: false, reason: 'Server mode is Windows-only' };
796
+ export async function repair({
797
+ dataDir,
798
+ appRoot,
799
+ config = {},
800
+ log = () => {},
801
+ run = shellRun,
802
+ waitForStart = async () => ({ alive: true }),
803
+ deps = {},
804
+ } = {}) {
805
+ if (!(deps.isWindows ?? isWindows)) return { ok: false, reason: 'Server mode is Windows-only' };
521
806
 
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
- };
807
+ const elevated = await (deps.isElevated ?? (() => isElevated({ run })))();
808
+ if (elevated === false || !(deps.canWrite ?? canWriteProgramData)()) {
809
+ return { ok: false, needsElevation: true, reason: elevationMessage('ezz service repair') };
529
810
  }
530
811
 
531
- if (!fs.existsSync(winswPath())) {
812
+ if (!fs.existsSync(winswPath()) || (await isRegistered({ run })) === false) {
532
813
  return { ok: false, reason: 'the service is not installed; run `ezz service install` instead' };
533
814
  }
534
815
 
535
816
  // The wrapper itself is re-verified: a tampered or truncated WinSW is worth
536
817
  // catching at repair time too, not only at install.
537
- const wrapper = await verifyWinsw(winswPath());
818
+ const wrapper = await (deps.verifyWinsw ?? verifyWinsw)(winswPath());
538
819
  if (!wrapper.ok) {
539
820
  log('The installed WinSW did not verify; re-downloading.');
540
- const again = await downloadWinsw({ dest: winswPath(), log });
821
+ const again = await downloadWinsw({ dest: winswPath(), log, verify: deps.verifyWinsw });
541
822
  if (!again.ok) return { ok: false, reason: again.reason };
542
823
  }
543
824
 
825
+ // ── The runtime copy cannot be replaced while the service runs ──────────
826
+ //
827
+ // Windows locks a running executable: 1.4.0 copied over runtime\node.exe
828
+ // with the service up and failed with EBUSY. So: stop, keep the current
829
+ // copy aside as `runtime.prev` (a rename — same volume, instant), copy,
830
+ // verify, start, and wait for the daemon's own heartbeat. Any failure after
831
+ // the stop puts the previous copy back and starts it again.
832
+ const dir = runtimeDir(dataDir);
833
+ const prev = `${dir}.prev`;
834
+
835
+ log('Stopping the service so the runtime copy can be replaced…');
836
+ const stopped = await stop({ run, stopWaitMs: deps.stopWaitMs ?? 30_000 });
837
+ if (!stopped.ok) {
838
+ return { ok: false, reason: `the service could not be stopped first, so nothing was changed: ${stopped.reason}` };
839
+ }
840
+
841
+ const startAgain = async () => {
842
+ const started = await start({ run });
843
+ if (!started.ok) return { ok: false, reason: started.reason };
844
+ const alive = await waitForStart();
845
+ return alive.alive ? { ok: true } : { ok: false, reason: 'the daemon did not report in' };
846
+ };
847
+
848
+ const restorePrevious = async (why) => {
849
+ log(`Restoring the previous runtime copy (${why})…`);
850
+ // A new copy that started but never reported in still holds its files.
851
+ await stop({ run, stopWaitMs: deps.stopWaitMs ?? 30_000 });
852
+ let restored = false;
853
+ try {
854
+ if (fs.existsSync(prev)) {
855
+ fs.rmSync(dir, { recursive: true, force: true });
856
+ fs.renameSync(prev, dir);
857
+ restored = true;
858
+ }
859
+ } catch (err) {
860
+ log(` could not restore ${prev}: ${err.message}`);
861
+ }
862
+ const back = await startAgain();
863
+ return {
864
+ ok: false,
865
+ reason: `${why}. `
866
+ + (restored ? 'The previous runtime copy was restored' : 'The previous runtime copy could not be restored')
867
+ + (back.ok ? ' and the service is running on it again.' : `, and the service did not start again: ${back.reason}.`)
868
+ + `\nLogs: ${errLogPath()} — more at ${TROUBLESHOOTING_URL}#repair-while-running`,
869
+ restored,
870
+ restarted: back.ok,
871
+ };
872
+ };
873
+
874
+ try {
875
+ fs.rmSync(prev, { recursive: true, force: true });
876
+ if (fs.existsSync(dir)) fs.renameSync(dir, prev);
877
+ } catch (err) {
878
+ const back = await startAgain();
879
+ return {
880
+ ok: false,
881
+ reason: `could not set the current runtime copy aside (${err.code ?? err.message}), so nothing was changed`
882
+ + (back.ok ? '; the service is running again.' : `; the service did not start again: ${back.reason}`),
883
+ };
884
+ }
885
+
544
886
  log('Refreshing the runtime copy…');
545
- const runtime = copyRuntime({ dataDir, appRoot, log });
546
- if (!runtime.ok) return { ok: false, reason: runtime.reason };
887
+ const runtime = (deps.copyRuntime ?? copyRuntime)({ dataDir, appRoot, log });
888
+ if (!runtime.ok) return restorePrevious(`the new runtime copy failed: ${runtime.reason}`);
547
889
 
548
- const native = await verifyNativeModules({
890
+ const native = await (deps.verifyNativeModules ?? verifyNativeModules)({
549
891
  nodeExe: runtime.nodeExe,
550
892
  appDir: path.join(runtime.dir, 'app'),
551
893
  });
552
- if (!native.ok) return { ok: false, reason: `${native.reason}\n\n${native.fix ?? ''}`.trim() };
894
+ if (!native.ok) {
895
+ return restorePrevious(`the new runtime cannot load its native modules: ${`${native.reason} ${native.fix ?? ''}`.trim()}`);
896
+ }
553
897
 
554
898
  log('Re-applying the service account grants…');
555
899
  const grants = requiredGrants({
556
900
  dataDir,
557
- runtimeDir: runtimeDir(dataDir),
901
+ runtimeDir: dir,
558
902
  nginxDir: config.nginxDir ?? null,
559
903
  sslDir: config.sslDir ?? null,
560
904
  });
561
905
  const acl = await applyGrants({ grants, run, log });
562
906
 
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
- }
907
+ log('Starting the service…');
908
+ const started = await startAgain();
909
+ if (!started.ok) return restorePrevious(`the service did not come up on the new copy: ${started.reason}`);
910
+
911
+ try { fs.rmSync(prev, { recursive: true, force: true }); } catch { /* `ezz cleanup` offers it later */ }
567
912
 
568
913
  return {
569
914
  ok: true,