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.
package/src/cli/index.js CHANGED
@@ -225,43 +225,101 @@ if (flags.has('new-ui') && !flags.has('classic-ui')) {
225
225
 
226
226
  // ─── Dispatch ─────────────────────────────────────────────────────────────────
227
227
 
228
- if (flags.has('dash')) {
229
- const { runDashboard } = await import('./dash.js');
230
- await runDashboard();
231
- } else if (command === 'system-info') {
232
- const { systemInfo } = await import('./menu.js');
233
- await systemInfo();
234
- process.exit(0);
235
- } else if (command === 'daemon') {
236
- // Runs in the foreground and never returns: the service managers that start
237
- // it (WinSW, systemd, the Startup supervisor) all expect a process they can
238
- // watch, and one that forks into the background looks to them like a crash.
239
- const { runDaemon } = await import('../core/daemon/run.js');
240
- process.exit(await runDaemon());
241
- } else if (command === 'service') {
242
- const { serviceCommand } = await import('./menus/service.js');
243
- process.exit(await serviceCommand(args[0] ?? 'status'));
244
- } else if (command === 'runtime') {
245
- const { runtimeCommand } = await import('./menus/runtime.js');
246
- process.exit(await runtimeCommand(args[0] ?? 'status', { yes: flags.has('yes') }));
247
- } else if (command === 'update') {
248
- const { updateCommand } = await import('./menus/update.js');
249
- process.exit(await updateCommand({ yes: flags.has('yes') }));
250
- } else if (command === 'hub') {
251
- const { hubCommand } = await import('./menus/hub.js');
252
- process.exit(await hubCommand(args[0] ?? 'status', args.slice(1), { yes: flags.has('yes') }));
253
- } else if (command === 'cleanup') {
254
- const { cleanupCommand } = await import('./menus/cleanup.js');
255
- process.exit(await cleanupCommand({ days: options.days, yes: flags.has('yes') }));
256
- } else if (command === 'uninstall') {
257
- const { uninstallCommand } = await import('./menus/uninstall.js');
258
- process.exit(await uninstallCommand({ purge: flags.has('purge'), yes: flags.has('yes') }));
259
- } else if (command === 'dashboard') {
260
- const { dashboardCommand } = await import('./menus/dashboard.js');
261
- process.exit(await dashboardCommand(args[0] ?? 'setup-code'));
262
- } else {
263
- // Interactive menu: Ctrl+C simply quits.
264
- process.on('SIGINT', () => process.exit(0));
265
- const { run } = await import('./menu.js');
266
- await run();
228
+ /**
229
+ * A database this account cannot write is a permissions problem, not a crash.
230
+ *
231
+ * It is what a normal terminal met in Windows Server mode before 1.4.3: the
232
+ * data lives in C:\ProgramData\easy-devops, created by an elevated install,
233
+ * and every write failed with "SqliteError: attempt to write a readonly
234
+ * database" and a stack trace. Install and repair now give the installing
235
+ * account access; this says so for an install that has not been repaired yet.
236
+ *
237
+ * @returns {Promise<boolean>} true when the error was explained
238
+ */
239
+ async function explainDatabaseError(err) {
240
+ const code = String(err?.code ?? '');
241
+ const readOnly = code === 'SQLITE_READONLY' || code.startsWith('SQLITE_READONLY_')
242
+ || /attempt to write a readonly database/i.test(String(err?.message ?? ''));
243
+ if (!readOnly) return false;
244
+
245
+ const { isWindows, isServerMode, getDataDir } = await import('../core/platform.js');
246
+ let dir = '(unknown)';
247
+ try { dir = getDataDir(); } catch { /* the message still helps */ }
248
+
249
+ const lines = ['', ' Easy DevOps cannot write its database with this account:', ` ${dir}`, ''];
250
+ if (isWindows && isServerMode()) {
251
+ lines.push(
252
+ ' In Windows Server mode the data is shared with the service. Run this once',
253
+ ' from PowerShell opened with "Run as administrator":',
254
+ '',
255
+ ' ezz service repair',
256
+ '',
257
+ ' It lets your account use the data, and start, stop and restart the service,',
258
+ ' without elevation from then on. No password is needed. Nothing was changed.',
259
+ );
260
+ } else {
261
+ lines.push(
262
+ ' Check that your account owns that folder and can write to it, then run the',
263
+ ' command again. Nothing was changed.',
264
+ );
265
+ }
266
+ process.stderr.write(`${lines.join('\n')}\n\n`);
267
+ return true;
268
+ }
269
+
270
+ // Errors thrown later, from callbacks the dispatch below does not await. Not
271
+ // for the daemon or the dashboard: they own their crash handling (releasing
272
+ // the lock and the jobs marker), and an exit from here would pre-empt it.
273
+ if (command !== 'daemon' && !flags.has('dash')) {
274
+ process.on('uncaughtException', async (err) => {
275
+ if (await explainDatabaseError(err)) process.exit(1);
276
+ process.stderr.write(`${err?.stack ?? err}\n`);
277
+ process.exit(1);
278
+ });
279
+ }
280
+
281
+ try {
282
+ if (flags.has('dash')) {
283
+ const { runDashboard } = await import('./dash.js');
284
+ await runDashboard();
285
+ } else if (command === 'system-info') {
286
+ const { systemInfo } = await import('./menu.js');
287
+ await systemInfo();
288
+ process.exit(0);
289
+ } else if (command === 'daemon') {
290
+ // Runs in the foreground and never returns: the service managers that start
291
+ // it (WinSW, systemd, the Startup supervisor) all expect a process they can
292
+ // watch, and one that forks into the background looks to them like a crash.
293
+ const { runDaemon } = await import('../core/daemon/run.js');
294
+ process.exit(await runDaemon());
295
+ } else if (command === 'service') {
296
+ const { serviceCommand } = await import('./menus/service.js');
297
+ process.exit(await serviceCommand(args[0] ?? 'status'));
298
+ } else if (command === 'runtime') {
299
+ const { runtimeCommand } = await import('./menus/runtime.js');
300
+ process.exit(await runtimeCommand(args[0] ?? 'status', { yes: flags.has('yes') }));
301
+ } else if (command === 'update') {
302
+ const { updateCommand } = await import('./menus/update.js');
303
+ process.exit(await updateCommand({ yes: flags.has('yes') }));
304
+ } else if (command === 'hub') {
305
+ const { hubCommand } = await import('./menus/hub.js');
306
+ process.exit(await hubCommand(args[0] ?? 'status', args.slice(1), { yes: flags.has('yes') }));
307
+ } else if (command === 'cleanup') {
308
+ const { cleanupCommand } = await import('./menus/cleanup.js');
309
+ process.exit(await cleanupCommand({ days: options.days, yes: flags.has('yes') }));
310
+ } else if (command === 'uninstall') {
311
+ const { uninstallCommand } = await import('./menus/uninstall.js');
312
+ process.exit(await uninstallCommand({ purge: flags.has('purge'), yes: flags.has('yes') }));
313
+ } else if (command === 'dashboard') {
314
+ const { dashboardCommand } = await import('./menus/dashboard.js');
315
+ process.exit(await dashboardCommand(args[0] ?? 'setup-code'));
316
+ } else {
317
+ // Interactive menu: Ctrl+C simply quits.
318
+ process.on('SIGINT', () => process.exit(0));
319
+ const { run } = await import('./menu.js');
320
+ await run();
321
+ }
322
+ } catch (err) {
323
+ if (!(await explainDatabaseError(err))) throw err;
324
+ process.exit(1);
267
325
  }
@@ -16,10 +16,11 @@ import chalk from 'chalk';
16
16
  import inquirer from 'inquirer';
17
17
  import ora from 'ora';
18
18
 
19
- import { isWindows } from '../../core/platform.js';
19
+ import { isWindows, isServerMode } from '../../core/platform.js';
20
20
  import * as runtimeUpdate from '../../core/service/runtimeUpdate.js';
21
21
  import * as service from '../../core/service/index.js';
22
22
  import { page, pause } from '../ui/page.js';
23
+ import { requireElevation } from '../elevation.js';
23
24
 
24
25
  const ACTIONS = ['status', 'update'];
25
26
 
@@ -134,6 +135,16 @@ async function doUpdate({ yes = false } = {}) {
134
135
  // its own and its outcome is held until Enter (a no-op without a TTY).
135
136
  page(['Runtime', 'Update']);
136
137
 
138
+ // Server mode: the service's node.exe lives in an administrator-only folder.
139
+ // Asked before anything is read or offered, so a normal terminal changes nothing.
140
+ if (isWindows && isServerMode()) {
141
+ const gate = await requireElevation({
142
+ args: ['runtime', 'update', ...(yes ? ['--yes'] : [])],
143
+ what: 'Moving the service to another Node version',
144
+ });
145
+ if (!gate.proceed) return gate.code;
146
+ }
147
+
137
148
  const code = await runUpdate({ yes });
138
149
  await pause();
139
150
  return code;
@@ -17,10 +17,11 @@ import chalk from 'chalk';
17
17
  import inquirer from 'inquirer';
18
18
  import ora from 'ora';
19
19
 
20
- import { isWindows, isDevDataDir, getDataDir } from '../../core/platform.js';
20
+ import { isWindows, isDevDataDir, getDataDir, isServerMode } from '../../core/platform.js';
21
21
  import * as service from '../../core/service/index.js';
22
22
  import { describeLegacy } from '../../core/service/legacy.js';
23
23
  import { page, pause } from '../ui/page.js';
24
+ import { requireElevation, offerRelaunchFor } from '../elevation.js';
24
25
 
25
26
  const ACTIONS = ['install', 'uninstall', 'status', 'start', 'stop', 'restart', 'logs', 'repair'];
26
27
 
@@ -187,6 +188,18 @@ export async function showStatus() {
187
188
  console.log(` Data directory ${chalk.gray(s.dataDir)}${s.serverMode ? chalk.gray(' (server mode)') : ''}`);
188
189
  console.log(` Dashboard UI ${chalk.gray(s.dashboardUi ?? 'unknown')}`);
189
190
 
191
+ // Server mode: who may start/stop it and use the data without elevation.
192
+ if (s.mode === service.MODES.SERVER && s.service.installed) {
193
+ const op = s.operator;
194
+ if (!op) {
195
+ console.log(` Without admin ${dot(false)} nobody ${chalk.gray('(ezz service repair as administrator allows your account)')}`);
196
+ } else {
197
+ const rights = [op.serviceControl && 'start/stop/restart', op.dataDir && 'data'].filter(Boolean).join(', ') || 'nothing';
198
+ console.log(` Without admin ${dot(op.serviceControl && op.dataDir)} ${op.name ?? op.sid}: ${rights}`
199
+ + chalk.gray(op.verified ? ' (checked on the service)' : ''));
200
+ }
201
+ }
202
+
190
203
  // Runtime: the service's pinned Node next to the one in this shell.
191
204
  const rt = s.runtime;
192
205
  console.log();
@@ -304,6 +317,13 @@ async function doInstall() {
304
317
  mode = chosen;
305
318
  }
306
319
 
320
+ // Before anything else is asked or changed: Server mode registers a
321
+ // service and writes under ProgramData, and a normal terminal cannot.
322
+ if (mode === service.MODES.SERVER) {
323
+ const gate = await requireElevation({ args: ['service', 'install'], what: 'Installing in Server mode' });
324
+ if (!gate.proceed) return gate.code;
325
+ }
326
+
307
327
  if (mode === service.MODES.SERVER) {
308
328
  console.log();
309
329
  console.log(' ' + chalk.yellow('Server mode will move your data to C:\\ProgramData\\easy-devops'));
@@ -480,6 +500,12 @@ async function offerToStart() {
480
500
 
481
501
  async function doUninstall() {
482
502
  page(['Service', 'Uninstall']);
503
+
504
+ if (isWindows && isServerMode()) {
505
+ const gate = await requireElevation({ args: ['service', 'uninstall'], what: 'Removing the Windows service' });
506
+ if (!gate.proceed) return gate.code;
507
+ }
508
+
483
509
  const current = await service.status().catch(() => null);
484
510
 
485
511
  console.log();
@@ -663,6 +689,9 @@ async function doStop() {
663
689
 
664
690
  if (!result.ok) {
665
691
  console.log();
692
+ // An install from before 1.4.3 has no start/stop grant for this account.
693
+ const handed = await offerRelaunchFor(result, ['service', 'stop']);
694
+ if (handed !== null) return handed;
666
695
  console.log(' ' + chalk.red('Could not stop it.'));
667
696
  console.log(String(result.reason).split('\n').map((l) => ` ${l}`).join('\n'));
668
697
  console.log();
@@ -709,6 +738,8 @@ async function doStart() {
709
738
  console.log();
710
739
  return 0;
711
740
  }
741
+ const handed = await offerRelaunchFor(result, ['service', 'start']);
742
+ if (handed !== null) return handed;
712
743
  console.log(' ' + chalk.red('Could not start it.'));
713
744
  console.log(String(result.reason).split('\n').map((l) => ` ${l}`).join('\n'));
714
745
  if (result.needsElevation) {
@@ -743,6 +774,8 @@ async function doRestart() {
743
774
 
744
775
  if (!result.ok) {
745
776
  spinner.stop();
777
+ const handed = await offerRelaunchFor(result, ['service', 'restart']);
778
+ if (handed !== null) return handed;
746
779
  console.log();
747
780
  console.log(' ' + chalk.red('Restart failed.'));
748
781
  console.log(String(result.reason).split('\n').map((l) => ` ${l}`).join('\n'));
@@ -793,6 +826,11 @@ async function doRepair() {
793
826
  console.log(' ' + chalk.gray('Re-pins the Node runtime, re-applies permissions, and restarts it.'));
794
827
  console.log();
795
828
 
829
+ if (isWindows && isServerMode()) {
830
+ const gate = await requireElevation({ args: ['service', 'repair'], what: 'Repairing the Windows service' });
831
+ if (!gate.proceed) return gate.code;
832
+ }
833
+
796
834
  const spinner = ora('Repairing…').start();
797
835
  const lines = [];
798
836
 
@@ -14,11 +14,12 @@ import chalk from 'chalk';
14
14
  import inquirer from 'inquirer';
15
15
  import ora from 'ora';
16
16
 
17
- import { getDataDir } from '../../core/platform.js';
17
+ import { getDataDir, isWindows, isServerMode } from '../../core/platform.js';
18
18
  import { loadConfig } from '../../core/config.js';
19
19
  import * as purgeCore from '../../core/purge.js';
20
20
  import { humanBytes } from '../../core/cleanup.js';
21
21
  import { page, pause } from '../ui/page.js';
22
+ import { requireElevation } from '../elevation.js';
22
23
 
23
24
  /**
24
25
  * @param {Object} [opts]
@@ -59,6 +60,15 @@ async function runUninstall({ purge = false, yes = false } = {}) {
59
60
  return 0;
60
61
  }
61
62
 
63
+ // Server mode: purging removes a Windows service and ProgramData folders.
64
+ if (isWindows && isServerMode()) {
65
+ const gate = await requireElevation({
66
+ args: ['uninstall', '--purge', ...(yes ? ['--yes'] : [])],
67
+ what: 'Purging a Server-mode install',
68
+ });
69
+ if (!gate.proceed) return gate.code;
70
+ }
71
+
62
72
  const dataDir = getDataDir();
63
73
  const config = loadConfig();
64
74
 
@@ -26,6 +26,8 @@ import { dbGet, dbSet } from '../../core/db.js';
26
26
  import { loadConfig } from '../../core/config.js';
27
27
  import { getDashboardStatus, startDashboard, stopDashboard } from '../../core/dashboardProcess.js';
28
28
  import { page, pause } from '../ui/page.js';
29
+ import { isWindows, isServerMode } from '../../core/platform.js';
30
+ import { requireElevation } from '../elevation.js';
29
31
 
30
32
 
31
33
  // ─── Recover interrupted update ───────────────────────────────────────────────
@@ -215,6 +217,14 @@ async function runUpdate({ yes = false, heading = true } = {}) {
215
217
  for (const line of updater.whyCliOnly()) console.log(' ' + chalk.gray(line));
216
218
  console.log();
217
219
 
220
+ // Server mode replaces the service's administrator-only runtime copy. Asked
221
+ // before the confirmation and before the dashboard is stopped, so a normal
222
+ // terminal changes nothing; the elevated window asks the question itself.
223
+ if (isWindows && isServerMode()) {
224
+ const gate = await requireElevation({ args: ['update', ...(yes ? ['--yes'] : [])], what: 'Updating Easy DevOps' });
225
+ if (!gate.proceed) return gate.code;
226
+ }
227
+
218
228
  if (!yes) {
219
229
  let confirm = false;
220
230
  try {
@@ -65,6 +65,7 @@ import {
65
65
  EZ_FILE_LOCATIONS, parseEzFile, resolveSettings, parseStartCommand,
66
66
  } from './ezfile.js';
67
67
  import { LAUNCHER_FILE, LAUNCHER_SOURCE, LAUNCHER_COMMAND_ENV } from './launcher.js';
68
+ import { RUN_STAGES, plannedSkippedStages, stageForStep } from './stages.js';
68
69
  import {
69
70
  acquireLock, appPaths, ensureAppDirs, isId, listReleases, logFile, newReleaseId, pathsIn, pruneReleases, pruneRuns,
70
71
  readRun, readState, releaseDir, validateDeployDir, writeRun, writeState,
@@ -1002,6 +1003,10 @@ export function startDeployment(appId, { trigger = 'manual', ref = null, actor =
1002
1003
  releaseId: runId,
1003
1004
  status: RUN_STATUS.RUNNING,
1004
1005
  step: 'fetch',
1006
+ /** The canonical stage `step` maps to (see stages.js), for the stage bar. */
1007
+ stage: 'fetch',
1008
+ /** Stages this run will not perform; filled in once the settings are read. */
1009
+ skippedStages: [],
1005
1010
  startedAt: d.now(),
1006
1011
  finishedAt: null,
1007
1012
  error: null,
@@ -1041,6 +1046,8 @@ async function executeDeployment(app, run, d) {
1041
1046
 
1042
1047
  const setStep = (step, title) => {
1043
1048
  run.step = step;
1049
+ // A custom step is "step N" in `step`; the stage it continues goes in `stage`.
1050
+ run.stage = stageForStep(step, run.stage);
1044
1051
  writeRun(run);
1045
1052
  log.step(title);
1046
1053
  };
@@ -1152,6 +1159,11 @@ async function executeDeployment(app, run, d) {
1152
1159
  const env = appEnvironment(app, settings, run.releaseId);
1153
1160
  const strict = sources.healthPath !== 'default';
1154
1161
 
1162
+ // Which stages this run will not perform is known as soon as the settings
1163
+ // are, and the bar should show them as skipped from the start.
1164
+ run.skippedStages = plannedSkippedStages(settings);
1165
+ writeRun(run);
1166
+
1155
1167
  // ── 3. pre → steps (install/build/migrate/custom) ───────────────────────
1156
1168
  await userCommands('pre', 'Pre-deploy hook', settings.pre, env);
1157
1169
  for (let i = 0; i < settings.steps.length; i++) {
@@ -1248,6 +1260,9 @@ async function executeDeployment(app, run, d) {
1248
1260
  const bootCrash = err?.bootCrash === true;
1249
1261
  run.error = err?.message ?? String(err);
1250
1262
  run.step = err?.step ?? run.step;
1263
+ // The stage stays where the failure happened. A custom step is "step N",
1264
+ // which has no stage of its own, so only a canonical step moves `stage`.
1265
+ if (RUN_STAGES.includes(run.step)) run.stage = run.step;
1251
1266
  run.reason = err?.reason ?? null;
1252
1267
  log.line(`ERROR: ${run.error}`);
1253
1268
  run.status = RUN_STATUS.FAILED;
@@ -1315,7 +1330,10 @@ async function executeDeployment(app, run, d) {
1315
1330
  }
1316
1331
 
1317
1332
  run.finishedAt = d.now();
1318
- if (run.status !== RUN_STATUS.RUNNING) run.step = run.status === RUN_STATUS.SUCCESS ? 'done' : run.step;
1333
+ if (run.status === RUN_STATUS.SUCCESS) {
1334
+ run.step = 'done';
1335
+ run.stage = stageForStep('done', run.stage);
1336
+ }
1319
1337
  writeRun(run);
1320
1338
  try { pruneRuns(app.id); } catch { /* ignore */ }
1321
1339
  await notify(app, run, d);
@@ -1367,6 +1385,9 @@ export function startRollback(appId, { releaseId = null, actor = null, deps = {}
1367
1385
  releaseId: target,
1368
1386
  status: RUN_STATUS.RUNNING,
1369
1387
  step: 'start',
1388
+ /** A rollback starts nothing and builds nothing: only start > health. */
1389
+ stage: 'start',
1390
+ skippedStages: ['fetch', 'settings', 'pre', 'install', 'build', 'migrate', 'post'],
1370
1391
  startedAt: d.now(),
1371
1392
  finishedAt: null,
1372
1393
  error: null,
@@ -1394,6 +1415,7 @@ export function startRollback(appId, { releaseId = null, actor = null, deps = {}
1394
1415
  if (!started.ok) throw new StepError('start', 'PM2 could not start that release.');
1395
1416
 
1396
1417
  run.step = 'health';
1418
+ run.stage = stageForStep('health', run.stage);
1397
1419
  writeRun(run);
1398
1420
  log.step('Checking that the app is healthy');
1399
1421
  const health = await waitHealthy({
@@ -1407,12 +1429,14 @@ export function startRollback(appId, { releaseId = null, actor = null, deps = {}
1407
1429
  await d.runner.save({ run: d.run, pm2Path });
1408
1430
  run.status = RUN_STATUS.SUCCESS;
1409
1431
  run.step = 'done';
1432
+ run.stage = stageForStep('done', run.stage);
1410
1433
  log.line('Rollback succeeded.');
1411
1434
  } catch (err) {
1412
1435
  run.status = RUN_STATUS.FAILED;
1413
1436
  run.error = err?.message ?? String(err);
1414
1437
  run.reason = err?.reason ?? null;
1415
1438
  run.step = err?.step ?? run.step;
1439
+ if (RUN_STAGES.includes(run.step)) run.stage = run.step;
1416
1440
  log.line(`ERROR: ${run.error}`);
1417
1441
 
1418
1442
  // Put back what was running, so a failed rollback is not also an outage.
@@ -0,0 +1,80 @@
1
+ /**
2
+ * core/deploy/stages.js
3
+ *
4
+ * The canonical stage bar of one deployment run.
5
+ *
6
+ * A run record's `step` is precise but not uniform: the reserved steps are
7
+ * named ids, while a custom step is "step N", which says nothing about where
8
+ * the run is on the bar. `stage` is the canonical answer — one of RUN_STAGES,
9
+ * or `done` — so the dashboard and the Hub can draw the same bar without
10
+ * parsing `step`.
11
+ *
12
+ * `skippedStages` is the other half: which stages this run will not perform at
13
+ * all. A project with no post hook never reaches `post`, and a project whose
14
+ * build is part of `start` has no `build` stage. Knowing that up front lets a
15
+ * bar show those stages as skipped rather than pending forever.
16
+ *
17
+ * `step` keeps its old meaning; this module only adds to it.
18
+ */
19
+
20
+ /** The stages a normal run can be in, in order. */
21
+ export const RUN_STAGES = Object.freeze([
22
+ 'fetch', 'settings', 'pre', 'install', 'build', 'migrate', 'start', 'health', 'post', 'finish',
23
+ ]);
24
+
25
+ /** The three stages a custom step can be part of. */
26
+ const COMMAND_STAGES = Object.freeze(['install', 'build', 'migrate']);
27
+
28
+ function commandsPresent(commands) {
29
+ return Array.isArray(commands) && commands.length > 0;
30
+ }
31
+
32
+ /**
33
+ * The stage a run is in when its `step` is `stepId`.
34
+ *
35
+ * A canonical id is its own stage. A custom step (`step N`) has no stage of
36
+ * its own: it continues install/build/migrate when it follows one of those,
37
+ * and counts as `build` otherwise.
38
+ *
39
+ * @param {string} stepId The value a run record's `step` holds
40
+ * @param {string|null} [previousStage] The stage before this step
41
+ * @returns {string}
42
+ */
43
+ export function stageForStep(stepId, previousStage = null) {
44
+ if (stepId === 'done') return 'done';
45
+ if (RUN_STAGES.includes(stepId)) return stepId;
46
+ return COMMAND_STAGES.includes(previousStage) ? previousStage : 'build';
47
+ }
48
+
49
+ /**
50
+ * The stages this run will not perform, in RUN_STAGES order.
51
+ *
52
+ * Read from the resolved settings, so it can be recorded as soon as the
53
+ * project's settings are known and before any step runs. A disabled step
54
+ * counts as skipped, and a custom step uses whatever stageForStep gives it.
55
+ *
56
+ * @param {Object|null} settings Resolved project settings (see ezfile.js)
57
+ * @returns {string[]}
58
+ */
59
+ export function plannedSkippedStages(settings = {}) {
60
+ const skipped = new Set();
61
+ if (!commandsPresent(settings?.pre)) skipped.add('pre');
62
+ if (!commandsPresent(settings?.post)) skipped.add('post');
63
+
64
+ const steps = Array.isArray(settings?.steps) ? settings.steps : [];
65
+ const reached = new Set();
66
+ let stage = 'pre';
67
+
68
+ steps.forEach((step, index) => {
69
+ if (!step || step.enabled === false) return;
70
+ const stepId = step.kind === 'custom' ? `step ${index + 1}` : step.kind;
71
+ stage = stageForStep(stepId, stage);
72
+ if (COMMAND_STAGES.includes(stage)) reached.add(stage);
73
+ });
74
+
75
+ for (const commandStage of COMMAND_STAGES) {
76
+ if (!reached.has(commandStage)) skipped.add(commandStage);
77
+ }
78
+
79
+ return RUN_STAGES.filter((stageId) => skipped.has(stageId));
80
+ }
@@ -274,7 +274,7 @@ export function createDeployProgress({
274
274
  return parts.map((line) => (line.endsWith('\r') ? line.slice(0, -1) : line));
275
275
  }
276
276
 
277
- function emitProgress(state, { status, steps, done, now }) {
277
+ function emitProgress(state, { status, steps, stage, skippedStages, done, now }) {
278
278
  const pending = state.pending;
279
279
  state.pending = [];
280
280
 
@@ -290,6 +290,10 @@ export function createDeployProgress({
290
290
  runId: state.runId,
291
291
  status,
292
292
  steps,
293
+ // The canonical stage bar. `stage` is null and `skippedStages` empty for
294
+ // an agent old enough to send neither; readers fall back to `steps`.
295
+ stage,
296
+ skippedStages,
293
297
  lines,
294
298
  done,
295
299
  at: new Date(now).toISOString(),
@@ -338,13 +342,15 @@ export function createDeployProgress({
338
342
 
339
343
  const status = typeof run.status === 'string' ? run.status : RUNNING;
340
344
  const steps = stepsFromRun(run);
345
+ const stage = typeof run.stage === 'string' && run.stage !== '' ? run.stage : null;
346
+ const skippedStages = Array.isArray(run.skippedStages) ? run.skippedStages : [];
341
347
  const done = status !== RUNNING || !lockHeld;
342
- const fingerprint = `${status}|${done}|${steps.map((s) => `${s.name}:${s.status}`).join(',')}`;
348
+ const fingerprint = `${status}|${done}|${stage ?? ''}|${skippedStages.join(',')}|${steps.map((s) => `${s.name}:${s.status}`).join(',')}`;
343
349
  const now = nowFn();
344
350
 
345
351
  const changed = done || state.pending.length > 0 || fingerprint !== state.lastFingerprint;
346
352
  if (changed && (done || now - state.lastEmitAt >= emitMs)) {
347
- emitProgress(state, { status, steps, done, now });
353
+ emitProgress(state, { status, steps, stage, skippedStages, done, now });
348
354
  state.lastEmitAt = now;
349
355
  state.lastFingerprint = fingerprint;
350
356
  }
@@ -320,6 +320,68 @@ export function windowsElevationCheckCmd() {
320
320
  + '.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)';
321
321
  }
322
322
 
323
+ /**
324
+ * Command that prints `<SID>|<DOMAIN\name>` for the account this process runs as.
325
+ *
326
+ * The SID is what an ACL or a service DACL is written against; the name is only
327
+ * for display. Asked of Windows rather than read from %USERNAME%, which a
328
+ * caller can set to anything.
329
+ * @returns {string}
330
+ */
331
+ export function windowsCurrentUserCmd() {
332
+ return '$i = [Security.Principal.WindowsIdentity]::GetCurrent(); "$($i.User.Value)|$($i.Name)"';
333
+ }
334
+
335
+ /** A PowerShell single-quoted literal: the only escape inside is a doubled quote. */
336
+ function psLiteral(value) {
337
+ return `'${String(value).replace(/'/g, "''")}'`;
338
+ }
339
+
340
+ /**
341
+ * Command that opens a NEW elevated PowerShell window running one CLI command.
342
+ *
343
+ * Windows has exactly one way to gain elevation, and it is a UAC prompt for a
344
+ * new process; a running process can never elevate itself. So the elevated
345
+ * copy is a separate window with its own console: it shows its own output,
346
+ * asks its own questions, and stays open at the end (`-NoExit`) so the result
347
+ * can be read. No password passes through here — UAC asks Windows, not us.
348
+ *
349
+ * The script for that window is passed as `-EncodedCommand` (UTF-16LE base64),
350
+ * so no argument is ever re-parsed by a shell on the way: every value inside it
351
+ * is a single-quoted PowerShell literal, and the outer command carries only
352
+ * base64. `env` is limited to names matching `EZ_[A-Z_]+` and values made of
353
+ * SID characters — it exists to tell the elevated copy who asked for it.
354
+ *
355
+ * @param {Object} opts
356
+ * @param {string} opts.execPath node.exe of this process
357
+ * @param {string} opts.script The CLI entry this process runs
358
+ * @param {string[]} opts.args The same arguments, unchanged
359
+ * @param {string} opts.cwd
360
+ * @param {Object<string,string>} [opts.env]
361
+ * @returns {string}
362
+ */
363
+ export function windowsElevatedRelaunchCmd({ execPath, script, args = [], cwd, env = {} }) {
364
+ const lines = [];
365
+ for (const [name, value] of Object.entries(env)) {
366
+ if (!/^EZ_[A-Z_]+$/.test(name) || !/^[A-Za-z0-9-]+$/.test(String(value))) {
367
+ throw new Error(`refusing to pass ${name} to an elevated process`);
368
+ }
369
+ lines.push(`$env:${name} = ${psLiteral(value)}`);
370
+ }
371
+ lines.push(
372
+ `Set-Location -LiteralPath ${psLiteral(cwd)}`,
373
+ `& ${psLiteral(execPath)} ${[script, ...args].map(psLiteral).join(' ')}`,
374
+ '$ezExit = $LASTEXITCODE',
375
+ "Write-Host ''",
376
+ 'Write-Host "Easy DevOps finished (exit code $ezExit). This window stays open; close it when you are done."',
377
+ );
378
+
379
+ const encoded = Buffer.from(lines.join('\n'), 'utf16le').toString('base64');
380
+ return 'try { Start-Process -FilePath powershell.exe -Verb RunAs -ErrorAction Stop '
381
+ + `-ArgumentList '-NoExit','-NoProfile','-EncodedCommand','${encoded}'; 'relaunched' } `
382
+ + "catch { 'relaunch-failed: ' + $_.Exception.Message; exit 1 }";
383
+ }
384
+
323
385
  /**
324
386
  * The Service Control Manager's command-line tool, always with its extension.
325
387
  *