easy-devops 1.4.2 → 1.4.3

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.
@@ -41,6 +41,7 @@ import {
41
41
  } from './winsw.js';
42
42
  import { requiredGrants, applyGrants, revokeGrants, compareGrants } from './acl.js';
43
43
  import { runtimeDir, copyRuntime, verifyNativeModules } from './runtime.js';
44
+ import { grantOperator, revokeOperator, readServiceSddl, operatorAceState, prepareProtectedDir } from './operator.js';
44
45
 
45
46
  /** Where the wrapper, its config and its logs live. Admin-writable only. */
46
47
  export function binDir() {
@@ -260,6 +261,7 @@ export async function install({
260
261
  dataDir,
261
262
  appRoot,
262
263
  config = {},
264
+ operator = null,
263
265
  log = () => {},
264
266
  run = shellRun,
265
267
  fetchImpl = fetch,
@@ -273,6 +275,17 @@ export async function install({
273
275
  return { ok: false, reason: elevationMessage(), needsElevation: true };
274
276
  }
275
277
 
278
+ // ── 0. The folders the service runs code from, protected while empty ──────
279
+ //
280
+ // An earlier install may have left the installing user a grant on the data
281
+ // directory, which a new folder would inherit. See operator.js.
282
+ for (const dir of [runtimeDir(dataDir), binDir()]) {
283
+ const prepared = await (deps.prepareProtectedDir ?? prepareProtectedDir)({
284
+ dir, sid: operator?.sid ?? null, serviceAccount: false, run, log,
285
+ });
286
+ if (!prepared.ok) return { ok: false, reason: `${prepared.reason}. Nothing was registered.` };
287
+ }
288
+
276
289
  // ── 1. The pinned runtime ────────────────────────────────────────────────
277
290
  log('Copying the runtime…');
278
291
  const runtime = (deps.copyRuntime ?? copyRuntime)({ dataDir, appRoot, log });
@@ -388,6 +401,20 @@ export async function install({
388
401
  }
389
402
  }
390
403
 
404
+ // ── 6b. The installing user: start/stop, and the data directory ─────────
405
+ //
406
+ // Before the first start, so the service never runs from a runtime folder
407
+ // that is not yet administrator-only. See operator.js.
408
+ log('Allowing your account to start and stop the service without elevation…');
409
+ const operatorGrant = await (deps.grantOperator ?? grantOperator)({
410
+ operator,
411
+ dataDir,
412
+ protectedDirs: [binDir(), runtimeDir(dataDir)],
413
+ run,
414
+ log,
415
+ });
416
+ for (const note of operatorGrant.notes) log(` note: ${note}`);
417
+
391
418
  // ── 7. Start ─────────────────────────────────────────────────────────────
392
419
  log('Starting the service…');
393
420
  const started = await run(`& "${winswPath()}" start`, { timeout: 60_000 });
@@ -402,6 +429,7 @@ export async function install({
402
429
  // status must not report a registered service as "not installed".
403
430
  granted: acl.applied.map((g) => g.path),
404
431
  aclFailures: acl.failed,
432
+ operator: operatorGrant.record,
405
433
  runtime: { nodeExe: runtime.nodeExe, entry: runtime.entry, version: native.version, abi: native.abi },
406
434
  };
407
435
  }
@@ -410,6 +438,8 @@ export async function install({
410
438
  ok: true,
411
439
  granted: acl.applied.map((g) => g.path),
412
440
  aclFailures: acl.failed,
441
+ operator: operatorGrant.record,
442
+ operatorNotes: operatorGrant.notes,
413
443
  runtime: { nodeExe: runtime.nodeExe, entry: runtime.entry, version: native.version, abi: native.abi },
414
444
  };
415
445
  }
@@ -422,7 +452,7 @@ export async function install({
422
452
  * uninstall flow (decision 5), because the ProgramData directory holds the
423
453
  * live data and silently relocating it would be a surprise.
424
454
  */
425
- export async function uninstall({ dataDir, config = {}, log = () => {}, run = shellRun } = {}) {
455
+ export async function uninstall({ dataDir, config = {}, operator = null, log = () => {}, run = shellRun } = {}) {
426
456
  if (!isWindows) return { ok: false, reason: 'Server mode is Windows-only' };
427
457
 
428
458
  if ((await isElevated({ run })) === false || !canWriteProgramData()) {
@@ -462,23 +492,36 @@ export async function uninstall({ dataDir, config = {}, log = () => {}, run = sh
462
492
  for (const failure of revoked.failed) notes.push(`could not clear grants on ${failure.path}`);
463
493
  }
464
494
 
495
+ // The installing user's data directory access. Its start/stop right was an
496
+ // entry on the service's own DACL, and went with the service.
497
+ const operatorRevoked = await revokeOperator({ operator, dataDir, run, log });
498
+ if (!operatorRevoked.ok) notes.push(`could not remove your account's data directory access: ${operatorRevoked.reason}`);
499
+
465
500
  return { ok: true, notes };
466
501
  }
467
502
 
468
- /** `winsw restart`. Calls the wrapper, so it needs elevation like install. */
469
- export async function restart({ run = shellRun } = {}) {
470
- if (!fs.existsSync(winswPath())) {
471
- return { ok: false, reason: 'the service is not installed' };
503
+ /**
504
+ * `sc.exe stop`, then `sc.exe start`.
505
+ *
506
+ * Not `winsw restart`: the Service Control Manager's own verbs are what the
507
+ * installing user is allowed to call without elevation (operator.js), and
508
+ * "Access is denied" from them is the authoritative answer when they are not.
509
+ * Nothing is pre-checked here, so an allowed user is never told to elevate.
510
+ */
511
+ export async function restart({ run = shellRun, stopWaitMs = 30_000 } = {}) {
512
+ const stopped = await stop({ run, stopWaitMs });
513
+ if (!stopped.ok) {
514
+ return stopped.needsElevation
515
+ ? { ok: false, needsElevation: true, reason: elevationFor('Restarting') }
516
+ : { ok: false, reason: stopped.reason };
472
517
  }
473
- const elevated = await isElevated({ run });
474
- if (elevated === false) {
475
- return { ok: false, needsElevation: true, reason: elevationFor('Restarting') };
518
+ const started = await start({ run });
519
+ if (!started.ok) {
520
+ return started.needsElevation
521
+ ? { ok: false, needsElevation: true, reason: elevationFor('Restarting') }
522
+ : { ok: false, reason: started.reason };
476
523
  }
477
- const result = await run(`& "${winswPath()}" restart`, { timeout: 90_000 });
478
- return {
479
- ok: result.success,
480
- reason: result.success ? null : `${result.stdout ?? ''}${result.stderr ?? ''}`.trim().slice(0, 400),
481
- };
524
+ return { ok: true };
482
525
  }
483
526
 
484
527
  /**
@@ -524,10 +567,11 @@ export async function waitForState({ wanted, run = shellRun, timeoutMs = 30_000,
524
567
  function elevationFor(action) {
525
568
  // "Stopping" → `ezz service stop`. It used to print `ezz service stopping`.
526
569
  const verb = { Stopping: 'stop', Starting: 'start', Restarting: 'restart' }[action] ?? action.toLowerCase();
527
- return `${action} the Windows service needs an Administrator terminal.\n\n`
528
- + ' Open PowerShell with "Run as administrator" and run the command again:\n'
570
+ return `${action} the Windows service was refused for this account.\n\n`
571
+ + ' Run it from PowerShell opened with "Run as administrator":\n'
529
572
  + ` ezz service ${verb}\n\n`
530
- + ' No password is needed — only elevation.';
573
+ + ' To let your account start, stop and restart it without elevation, run\n'
574
+ + ' `ezz service repair` once as administrator. No password is needed — only elevation.';
531
575
  }
532
576
 
533
577
  /**
@@ -695,7 +739,7 @@ export function countRecentRestarts({ windowMs = 10 * 60_000, now = Date.now(),
695
739
  * @param {Object} [opts]
696
740
  * @returns {Promise<Object>}
697
741
  */
698
- export async function status({ dataDir, config = {}, run = shellRun, granted = [] } = {}) {
742
+ export async function status({ dataDir, config = {}, run = shellRun, granted = [], operatorSid = null } = {}) {
699
743
  const filesPresent = fs.existsSync(winswPath()) && fs.existsSync(serviceXmlPath());
700
744
 
701
745
  // Windows is the authority on whether the service exists — not the files.
@@ -726,7 +770,10 @@ export async function status({ dataDir, config = {}, run = shellRun, granted = [
726
770
  };
727
771
  }
728
772
 
729
- const config2 = await run(`${WINDOWS_SC} qc ${SERVICE_ID}`, { timeout: 20_000 });
773
+ const [config2, sddl] = await Promise.all([
774
+ run(`${WINDOWS_SC} qc ${SERVICE_ID}`, { timeout: 20_000 }),
775
+ operatorSid ? readServiceSddl({ run }) : Promise.resolve(null),
776
+ ]);
730
777
  const startType = `${config2.stdout ?? ''}`.match(/START_TYPE\s*:\s*\d+\s+([\w_]+)/i)?.[1] ?? null;
731
778
 
732
779
  const loop = countRecentRestarts();
@@ -760,6 +807,10 @@ export async function status({ dataDir, config = {}, run = shellRun, granted = [
760
807
  crashLooping: loop.crashLooping,
761
808
  crashLoopSince: loop.since,
762
809
  acl: aclCheck,
810
+ // Whether the recorded installing user may still start and stop it — read
811
+ // from the service's DACL, not from the record. null: nobody recorded, or
812
+ // the DACL could not be read.
813
+ operatorControl: operatorSid && sddl ? operatorAceState(sddl, operatorSid) : null,
763
814
  winswPath: winswPath(),
764
815
  logs: { out: outLogPath(), err: errLogPath(), wrapper: wrapperLogPath() },
765
816
  };
@@ -797,6 +848,7 @@ export async function repair({
797
848
  dataDir,
798
849
  appRoot,
799
850
  config = {},
851
+ operator = null,
800
852
  log = () => {},
801
853
  run = shellRun,
802
854
  waitForStart = async () => ({ alive: true }),
@@ -883,6 +935,13 @@ export async function repair({
883
935
  };
884
936
  }
885
937
 
938
+ // The new folder is protected while it is still empty, before anything the
939
+ // service will run is copied into it.
940
+ const prepared = await (deps.prepareProtectedDir ?? prepareProtectedDir)({
941
+ dir, sid: operator?.sid ?? null, run, log,
942
+ });
943
+ if (!prepared.ok) return restorePrevious(`the new runtime folder could not be protected: ${prepared.reason}`);
944
+
886
945
  log('Refreshing the runtime copy…');
887
946
  const runtime = (deps.copyRuntime ?? copyRuntime)({ dataDir, appRoot, log });
888
947
  if (!runtime.ok) return restorePrevious(`the new runtime copy failed: ${runtime.reason}`);
@@ -904,6 +963,18 @@ export async function repair({
904
963
  });
905
964
  const acl = await applyGrants({ grants, run, log });
906
965
 
966
+ // The fresh runtime folder inherits again, so it is protected again before
967
+ // the service starts on it; then the installing user's rights are renewed.
968
+ log('Allowing your account to start and stop the service without elevation…');
969
+ const operatorGrant = await (deps.grantOperator ?? grantOperator)({
970
+ operator,
971
+ dataDir,
972
+ protectedDirs: [binDir(), dir],
973
+ run,
974
+ log,
975
+ });
976
+ for (const note of operatorGrant.notes) log(` note: ${note}`);
977
+
907
978
  log('Starting the service…');
908
979
  const started = await startAgain();
909
980
  if (!started.ok) return restorePrevious(`the service did not come up on the new copy: ${started.reason}`);
@@ -914,6 +985,8 @@ export async function repair({
914
985
  ok: true,
915
986
  granted: acl.applied.map((g) => g.path),
916
987
  aclFailures: acl.failed,
988
+ operator: operatorGrant.record,
989
+ operatorNotes: operatorGrant.notes,
917
990
  runtime: { version: native.version, abi: native.abi },
918
991
  };
919
992
  }
@@ -44,6 +44,7 @@ import { inspect as inspectLock } from './daemon/lock.js';
44
44
  import { loadConfig } from './config.js';
45
45
  import { copyRuntime, runtimeDir } from './service/runtime.js';
46
46
  import { MODES } from './service/index.js';
47
+ import { isElevated } from './service/windowsService.js';
47
48
 
48
49
  const require = createRequire(import.meta.url);
49
50
 
@@ -141,6 +142,26 @@ export async function performUpdate({
141
142
  const serviceInstalled = Boolean(installed?.service?.installed);
142
143
  const serverMode = installed?.mode === MODES.SERVER;
143
144
 
145
+ // 2b. Windows Server mode: the service runs from a copy under ProgramData
146
+ // that only administrators may replace, and that is deliberate (replacing
147
+ // node.exe would run code as the service account). Asked of Windows before
148
+ // anything is stopped, so a normal terminal changes nothing at all.
149
+ if (isWindows && serverMode) {
150
+ const elevated = await (deps.isElevated ?? isElevated)({});
151
+ if (elevated === false) {
152
+ return {
153
+ ok: false,
154
+ step: 'elevation',
155
+ from,
156
+ needsElevation: true,
157
+ untouched: true,
158
+ command: 'ezz update',
159
+ reason: 'Updating a Windows Server-mode install replaces the runtime copy the service runs, which only '
160
+ + 'administrators can change. Run `ezz update` from PowerShell opened with "Run as administrator".',
161
+ };
162
+ }
163
+ }
164
+
144
165
  // 3. Stop the service. Its files are the ones npm is about to replace, and
145
166
  // on Windows an open handle makes the install fail rather than wait.
146
167
  if (serviceInstalled) {
@@ -29,7 +29,8 @@ import crypto from 'crypto';
29
29
  import { spawn } from 'child_process';
30
30
  import { fileURLToPath } from 'url';
31
31
 
32
- import { getDataDir } from '../../core/platform.js';
32
+ import { getDataDir, isWindows, isServerMode } from '../../core/platform.js';
33
+ import { isElevated } from '../../core/service/windowsService.js';
33
34
  import { loadConfig } from '../../core/config.js';
34
35
  import { checkForUpdate, currentVersion } from '../../core/updater.js';
35
36
  import { detectInstallSource } from '../../core/installSource.js';
@@ -69,6 +70,26 @@ function spawnWorker({ args, logPath, dataDir }) {
69
70
  }
70
71
  }
71
72
 
73
+ /** The command and shell to name when this dashboard cannot run the update itself. */
74
+ const ELEVATED_UPDATE = Object.freeze({ command: 'ezz update', shell: 'Administrator PowerShell' });
75
+
76
+ /**
77
+ * Whether an update started from this dashboard would be refused for want of
78
+ * elevation.
79
+ *
80
+ * Windows Server mode keeps the service's runtime copy administrator-only on
81
+ * purpose, and a dashboard started from a normal terminal is not elevated —
82
+ * so the worker would stop at its first check. Saying so up front beats
83
+ * starting a run that can only fail. Elevation cannot change during this
84
+ * process's life, so it is asked of Windows once.
85
+ */
86
+ let elevatedOnce = null;
87
+ async function defaultElevationRequired() {
88
+ if (!isWindows || !isServerMode()) return false;
89
+ elevatedOnce ??= isElevated({}).catch(() => null);
90
+ return (await elevatedOnce) === false;
91
+ }
92
+
72
93
  function describeSource(source) {
73
94
  return {
74
95
  kind: source.kind,
@@ -89,6 +110,13 @@ class UpdateController {
89
110
  this.spawnWorker = deps.spawnWorker ?? spawnWorker;
90
111
  this.runId = deps.runId ?? (() => `${Date.now().toString(36)}-${crypto.randomBytes(3).toString('hex')}`);
91
112
  this.now = deps.now ?? (() => Date.now());
113
+ this.elevationRequired = deps.elevationRequired ?? defaultElevationRequired;
114
+ }
115
+
116
+ /** `{ required, command, shell }` for the response, from elevationRequired(). */
117
+ async describeElevation() {
118
+ const required = await this.elevationRequired();
119
+ return required ? { required: true, ...ELEVATED_UPDATE } : { required: false, command: null, shell: null };
92
120
  }
93
121
 
94
122
  /**
@@ -105,6 +133,7 @@ class UpdateController {
105
133
  reachable: check.reachable,
106
134
  updateAvailable: check.updateAvailable,
107
135
  source: describeSource(this.detectInstallSource()),
136
+ elevation: await this.describeElevation(),
108
137
  run: describeRun(this.readStatus(dataDir)),
109
138
  });
110
139
  } catch {
@@ -148,6 +177,18 @@ class UpdateController {
148
177
  return;
149
178
  }
150
179
 
180
+ const elevation = await this.describeElevation();
181
+ if (elevation.required) {
182
+ res.status(403).json({
183
+ error: 'elevation_required',
184
+ message: 'Updating this server replaces the runtime copy the service runs, which only administrators '
185
+ + 'can change. Run `ezz update` from PowerShell opened with "Run as administrator".',
186
+ command: elevation.command,
187
+ shell: elevation.shell,
188
+ });
189
+ return;
190
+ }
191
+
151
192
  const existing = describeRun(this.readStatus(dataDir));
152
193
  if (runIsActive(existing)) {
153
194
  res.status(409).json({