easy-devops 1.4.1 → 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.
@@ -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 {
@@ -9,7 +9,6 @@
9
9
  * command with command:result instead of leaving the Hub guessing.
10
10
  */
11
11
 
12
- import fs from 'fs/promises';
13
12
  import path from 'path';
14
13
  import { loadConfig } from './config.js';
15
14
  import { describeIssuance, issueCertificate, prepareDomainForHttpChallenge } from './ssl-issuer.js';
@@ -17,7 +16,9 @@ import { renewCertificate, describeRenewal, failureReason } from './cert-renewal
17
16
  import { bumpHubRevision } from './hubLink.js';
18
17
  import { listAllCerts } from './cert-reader.js';
19
18
  import { findCertificateForDomain } from './cert-suggest.js';
20
- import { getDomains, findDomain } from './domains-db.js';
19
+ import { findDomain } from './domains-db.js';
20
+ import { deleteCertificate } from './cert-usage.js';
21
+ import { validateDomainName } from './validators.js';
21
22
 
22
23
  /** Shape shared by every SSL result so the Hub can render it uniformly. */
23
24
  function issuanceResult(domain, result) {
@@ -33,6 +34,47 @@ function issuanceResult(domain, result) {
33
34
  };
34
35
  }
35
36
 
37
+ /**
38
+ * The failed stage, the real cause, the one-line fix and what it left
39
+ * behind — the same four things the dashboard shows. Nothing else from the
40
+ * internal error is passed on.
41
+ */
42
+ function failureDetail(result) {
43
+ const err = result?.error;
44
+ if (!err || typeof err !== 'object') return null;
45
+ return {
46
+ stage: err.stage ?? err.step ?? null,
47
+ cause: err.cause ?? 'Certificate operation failed',
48
+ fix: err.fix ?? null,
49
+ consequence: err.consequence ?? null,
50
+ };
51
+ }
52
+
53
+ /**
54
+ * A new certificate's result: the common shape, plus the preflight checks and
55
+ * the paths on success (the Hub's domain form fills them in), or the failure
56
+ * detail. On failure `error` is the object; the agent puts its `cause` in the
57
+ * command's top-level error string, which is all an older Hub reads.
58
+ */
59
+ function newCertificateResult(domain, result) {
60
+ const out = issuanceResult(domain, result);
61
+ out.preflight = result?.preflight
62
+ ? {
63
+ ok: Boolean(result.preflight.ok),
64
+ detail: result.preflight.detail ?? '',
65
+ results: Array.isArray(result.preflight.results) ? result.preflight.results : [],
66
+ proxied: Boolean(result.preflight.proxied),
67
+ }
68
+ : null;
69
+ if (out.ok) {
70
+ out.certPath = result.certPath ?? null;
71
+ out.keyPath = result.keyPath ?? null;
72
+ } else {
73
+ out.error = failureDetail(result) ?? { stage: null, cause: out.error, fix: null, consequence: null };
74
+ }
75
+ return out;
76
+ }
77
+
36
78
  /**
37
79
  * The same shape for a renewal, which additionally reports whether nginx was
38
80
  * reloaded onto the new certificate and whether the renewal was refused
@@ -132,7 +174,6 @@ export async function handleHubSslCommand(payload, options = {}) {
132
174
  // ── Issue a new certificate ───────────────────────────────────────────
133
175
  case 'issue': {
134
176
  if (!domain) return { ok: false, error: 'domain is required' };
135
- if (!config.acmeEmail) return { ok: false, error: 'No acmeEmail configured on this server.' };
136
177
 
137
178
  // Wildcards need a DNS TXT record the operator adds by hand, so they
138
179
  // cannot be driven from the Hub — ssl.issueDns is marked comingSoon.
@@ -143,6 +184,15 @@ export async function handleHubSslCommand(payload, options = {}) {
143
184
  };
144
185
  }
145
186
 
187
+ // The name becomes a directory under sslDir, so it must be a plain
188
+ // hostname before anything is written.
189
+ const nameError = validateDomainName(domain);
190
+ if (nameError) return { ok: false, error: `Invalid domain name: ${nameError}` };
191
+
192
+ if (!config.acmeEmail) {
193
+ return { ok: false, error: 'No acmeEmail configured on this server. Set it in the server’s dashboard: Settings → General.' };
194
+ }
195
+
146
196
  const prep = await prepare(domain);
147
197
  if (!prep.ok) return { ok: false, error: `Challenge setup failed: ${prep.error}` };
148
198
 
@@ -154,7 +204,7 @@ export async function handleHubSslCommand(payload, options = {}) {
154
204
  onProgress: progressFor(domain),
155
205
  });
156
206
 
157
- const out = issuanceResult(domain, result);
207
+ const out = newCertificateResult(domain, result);
158
208
  if (out.ok) bumpHubRevision();
159
209
  console.log('[hubAgent] ssl issue:', domain, out.ok ? 'OK' : 'FAILED', '—', out.summary || out.error);
160
210
  return out;
@@ -170,50 +220,41 @@ export async function handleHubSslCommand(payload, options = {}) {
170
220
  }
171
221
 
172
222
  // ── Delete a certificate ──────────────────────────────────────────────
223
+ // core/cert-usage.js resolves the directory from listAllCerts(), never
224
+ // from this payload, and refuses while an enabled domain or any nginx
225
+ // config still uses it — the same function the dashboard deletes with.
173
226
  case 'delete': {
174
227
  if (!domain) return { ok: false, error: 'domain is required' };
175
228
 
176
- // Refuse while an enabled domain still points at it: deleting would
177
- // leave nginx referencing a missing file and fail its next reload.
178
- const inUse = getDomains().filter(
179
- (d) => d.enabled !== false && d.ssl?.enabled && certBelongsTo(d, domain, config.sslDir)
180
- );
181
-
182
- if (inUse.length > 0) {
229
+ const outcome = await deleteCertificate(domain);
230
+ if (outcome.code === 'cert_not_found') {
231
+ return { ok: false, code: 'cert_not_found', domain: outcome.domain, error: `No certificate named ${outcome.domain} on this server.` };
232
+ }
233
+ if (outcome.code === 'cert_in_use') {
234
+ const names = outcome.usedBy.length ? outcome.usedBy.join(', ') : 'an nginx config';
183
235
  return {
184
236
  ok: false,
237
+ code: 'cert_in_use',
238
+ domain: outcome.domain,
239
+ usedBy: outcome.usedBy,
240
+ // File names and line numbers only: the Hub never receives config
241
+ // contents or full paths.
242
+ references: outcome.references.map((r) => ({ file: path.basename(r.file), line: r.line })),
185
243
  error:
186
- `Certificate for ${domain} is still used by ${inUse.map((d) => d.name).join(', ')}. ` +
244
+ `Certificate for ${outcome.domain} is still used by ${names}. ` +
187
245
  'Disable SSL on those domains (or disable the domains) before deleting it.',
188
246
  };
189
247
  }
190
-
191
- const certDir = path.join(config.sslDir, domain);
192
- try {
193
- await fs.rm(certDir, { recursive: true, force: true });
194
- } catch (err) {
195
- return { ok: false, error: `Could not delete ${certDir}: ${err.message}` };
248
+ if (outcome.code === 'delete_failed') {
249
+ return { ok: false, code: 'delete_failed', domain: outcome.domain, error: outcome.detail };
196
250
  }
197
251
 
198
252
  bumpHubRevision();
199
- console.log('[hubAgent] ssl delete:', domain, 'OK');
200
- return { ok: true, domain, deleted: certDir };
253
+ console.log('[hubAgent] ssl delete:', outcome.domain, 'OK');
254
+ return { ok: true, domain: outcome.domain, deleted: true };
201
255
  }
202
256
 
203
257
  default:
204
258
  return { ok: false, error: `Unknown SSL action: ${action}` };
205
259
  }
206
260
  }
207
-
208
- /**
209
- * True when a domain's configured certificate lives in the directory for
210
- * `certDomain`. Compares with forward slashes so Windows paths match whichever
211
- * separator style they were stored with.
212
- */
213
- function certBelongsTo(domain, certDomain, sslDir) {
214
- if (domain.name === certDomain) return true;
215
-
216
- const norm = (p) => String(p ?? '').replace(/\\/g, '/').toLowerCase();
217
- const dir = norm(path.join(sslDir, certDomain));
218
- return norm(domain.ssl?.certPath).startsWith(dir) || norm(domain.ssl?.keyPath).startsWith(dir);
219
- }
@@ -0,0 +1,181 @@
1
+ /**
2
+ * core/cert-usage.js
3
+ *
4
+ * Who uses a certificate, whether a domain's certificate files exist, and
5
+ * deleting a certificate safely. Shared by the dashboard's SSL and domain
6
+ * controllers and by the Hub agent, so the two cannot drift: the same refusal
7
+ * protects a certificate whichever side asks to delete it.
8
+ */
9
+
10
+ import fs from 'fs/promises';
11
+ import path from 'path';
12
+ import { loadConfig } from './config.js';
13
+ import { listAllCerts } from './cert-reader.js';
14
+ import { getDomains } from './domains-db.js';
15
+ import { getDefaultCertPaths } from './nginx-conf-generator.js';
16
+ import { isWindows } from './platform.js';
17
+
18
+ // nginx writes its logs and scratch files here; those can grow large and never
19
+ // contain certificate paths.
20
+ const NGINX_SKIP_DIRS = new Set([
21
+ 'logs', 'temp', 'client_body_temp', 'proxy_temp', 'fastcgi_temp', 'uwsgi_temp', 'scgi_temp',
22
+ ]);
23
+
24
+ /**
25
+ * Flattens a path so nginx configs written with forward slashes, Windows
26
+ * backslashes or doubled separators all compare equal.
27
+ */
28
+ function comparablePath(value) {
29
+ const slashed = String(value ?? '').replace(/\\/g, '/').replace(/\/{2,}/g, '/');
30
+ return isWindows ? slashed.toLowerCase() : slashed;
31
+ }
32
+
33
+ /**
34
+ * Collects every nginx configuration file under `dir` — the main nginx.conf,
35
+ * domain configs, and the `.conf.disabled` copies a disabled domain leaves.
36
+ */
37
+ async function collectConfigFiles(dir, found = []) {
38
+ let entries;
39
+ try {
40
+ entries = await fs.readdir(dir, { withFileTypes: true });
41
+ } catch {
42
+ return found;
43
+ }
44
+
45
+ for (const entry of entries) {
46
+ const full = path.join(dir, entry.name);
47
+ if (entry.isDirectory()) {
48
+ if (!NGINX_SKIP_DIRS.has(entry.name.toLowerCase())) {
49
+ await collectConfigFiles(full, found);
50
+ }
51
+ continue;
52
+ }
53
+ if (!entry.isFile() && !entry.isSymbolicLink()) continue;
54
+ const name = entry.name.toLowerCase();
55
+ if (name.endsWith('.conf') || name.endsWith('.conf.disabled')) found.push(full);
56
+ }
57
+
58
+ return found;
59
+ }
60
+
61
+ /**
62
+ * Finds every nginx config line that points at a file inside the certificate's
63
+ * directory, so deletion cannot leave nginx referencing missing files.
64
+ *
65
+ * @returns {Promise<Array<{ file: string, line: number, text: string }>>}
66
+ */
67
+ export async function findCertReferences(domain, config = loadConfig()) {
68
+ const target = `${comparablePath(path.join(config.sslDir, domain)).replace(/\/+$/, '')}/`;
69
+ const files = await collectConfigFiles(config.nginxDir);
70
+ const references = [];
71
+
72
+ for (const file of files) {
73
+ let content;
74
+ try {
75
+ content = await fs.readFile(file, 'utf8');
76
+ } catch {
77
+ continue;
78
+ }
79
+
80
+ content.split(/\r?\n/).forEach((text, index) => {
81
+ if (comparablePath(text).includes(target)) {
82
+ references.push({ file, line: index + 1, text: text.trim() });
83
+ }
84
+ });
85
+ }
86
+
87
+ return references;
88
+ }
89
+
90
+ /**
91
+ * The enabled domains with SSL on whose configured certificate lives in the
92
+ * directory for `certDomain` (or that are named `certDomain` themselves).
93
+ *
94
+ * @returns {string[]} domain names
95
+ */
96
+ export function domainsUsingCert(certDomain, config = loadConfig()) {
97
+ const dir = comparablePath(path.join(config.sslDir, certDomain)).replace(/\/+$/, '');
98
+ const inside = (p) => {
99
+ const value = comparablePath(p);
100
+ return value === dir || value.startsWith(`${dir}/`);
101
+ };
102
+
103
+ return getDomains()
104
+ .filter((d) => d.enabled !== false && d.ssl?.enabled)
105
+ .filter((d) => d.name === certDomain || inside(d.ssl?.certPath) || inside(d.ssl?.keyPath))
106
+ .map((d) => d.name);
107
+ }
108
+
109
+ /**
110
+ * Resolves the paths nginx will load and reports them when either file is
111
+ * missing. Blank fields use the same `${sslDir}/${name}` fallback as the
112
+ * config generator, so this check matches the generated config.
113
+ *
114
+ * @param {{ name: string, ssl?: { enabled?: boolean, certPath?: string, keyPath?: string } }} domain
115
+ * @returns {Promise<{ certPath: string, keyPath: string } | null>}
116
+ */
117
+ export async function missingCertFiles(domain) {
118
+ if (!domain?.ssl?.enabled) return null;
119
+
120
+ const { sslDir } = loadConfig();
121
+ const defaults = getDefaultCertPaths(domain.name, isWindows ? 'win32' : 'linux', sslDir);
122
+ const certPath = domain.ssl.certPath || defaults.certPath;
123
+ const keyPath = domain.ssl.keyPath || defaults.keyPath;
124
+
125
+ try {
126
+ await fs.access(certPath, fs.constants.F_OK);
127
+ await fs.access(keyPath, fs.constants.F_OK);
128
+ return null;
129
+ } catch {
130
+ return { certPath, keyPath };
131
+ }
132
+ }
133
+
134
+ export const CERT_MISSING_HINT =
135
+ 'The SSL certificate files do not exist at the configured paths. Create the certificate first, or disable SSL.';
136
+
137
+ /**
138
+ * Deletes one certificate directory under sslDir.
139
+ *
140
+ * The directory name is taken from listAllCerts(), never from the caller:
141
+ * listAllCerts() only returns direct children of sslDir, so a name such as
142
+ * `..` or `a/../../etc` simply is not found. This is the guard against path
143
+ * traversal and must stay that way — the caller's string never reaches fs.rm.
144
+ *
145
+ * Refuses while the certificate is in use: an enabled domain with SSL points
146
+ * at it, or any nginx config line references a file inside it (that covers
147
+ * disabled domains' `.conf.disabled` copies and hand-written configs too).
148
+ *
149
+ * @param {string} domain
150
+ * @returns {Promise<
151
+ * { ok: true, domain: string, directory: string } |
152
+ * { ok: false, code: 'cert_not_found', domain: string } |
153
+ * { ok: false, code: 'cert_in_use', domain: string, directory: string, usedBy: string[], references: Array<{ file: string, line: number, text: string }> } |
154
+ * { ok: false, code: 'delete_failed', domain: string, directory: string, detail: string }
155
+ * >}
156
+ */
157
+ export async function deleteCertificate(domain) {
158
+ const config = loadConfig();
159
+ const certs = await listAllCerts({ includeUnusable: true });
160
+ const cert = typeof domain === 'string' ? certs.find((entry) => entry.domain === domain) : null;
161
+ if (!cert) return { ok: false, code: 'cert_not_found', domain: String(domain ?? '') };
162
+
163
+ const directory = path.join(config.sslDir, cert.domain);
164
+ const usedBy = domainsUsingCert(cert.domain, config);
165
+ const references = await findCertReferences(cert.domain, config);
166
+
167
+ if (usedBy.length > 0 || references.length > 0) {
168
+ return { ok: false, code: 'cert_in_use', domain: cert.domain, directory, usedBy, references };
169
+ }
170
+
171
+ try {
172
+ await fs.rm(directory, { recursive: true, force: true });
173
+ } catch (error) {
174
+ return {
175
+ ok: false, code: 'delete_failed', domain: cert.domain, directory,
176
+ detail: `Could not delete ${directory}: ${error.message}`,
177
+ };
178
+ }
179
+
180
+ return { ok: true, domain: cert.domain, directory };
181
+ }
@@ -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
+ }