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.
@@ -8,6 +8,11 @@ import { loadConfig } from './config.js';
8
8
  import { isWindows, nginxTestCmd, nginxReloadCmd, isNginxTestOk } from './platform.js';
9
9
  import { saveDomainNotifConfig } from './domainNotifier.js';
10
10
  import { bumpHubRevision } from './hubLink.js';
11
+ import { missingCertFiles, CERT_MISSING_HINT } from './cert-usage.js';
12
+ import {
13
+ validateDomainName, validatePort, validateUpstreamType,
14
+ validateMaxBodySize, validateBehindCloudflare,
15
+ } from './validators.js';
11
16
 
12
17
  // Re-export DOMAIN_DEFAULTS for consumers
13
18
  export { DOMAIN_DEFAULTS, migrateDomain };
@@ -71,6 +76,48 @@ export function createDomain(partial) {
71
76
  // Called by hubAgent when the hub dispatches a hub:manageDomain event.
72
77
  // Payload shape: { action: 'create'|'update'|'delete'|'toggle'|'reload', name?, domain? }
73
78
 
79
+ /**
80
+ * The checks the dashboard's domain controller runs, applied to a Hub payload.
81
+ * On update only the fields present are checked, as the dashboard does.
82
+ *
83
+ * @param {Object} input The payload's `domain`
84
+ * @param {{ creating: boolean, existing?: Object }} options
85
+ * @returns {string|null} The first problem, or null
86
+ */
87
+ function hubDomainInputError(input, { creating, existing = null }) {
88
+ if (creating) {
89
+ const nameError = validateDomainName(input.name);
90
+ if (nameError) return nameError;
91
+ }
92
+
93
+ const backendIsUrl = /^https?:\/\//i.test(input.backendHost ?? existing?.backendHost ?? '');
94
+ if ((creating || input.port !== undefined) && !backendIsUrl) {
95
+ const portError = validatePort(input.port);
96
+ if (portError) return portError;
97
+ }
98
+ if (input.upstreamType !== undefined) {
99
+ const upstreamError = validateUpstreamType(input.upstreamType);
100
+ if (upstreamError) return upstreamError;
101
+ }
102
+ if (input.performance?.maxBodySize !== undefined) {
103
+ const sizeError = validateMaxBodySize(input.performance.maxBodySize);
104
+ if (sizeError) return sizeError;
105
+ }
106
+ if (input.behindCloudflare !== undefined) {
107
+ const cloudflareError = validateBehindCloudflare(input.behindCloudflare);
108
+ if (cloudflareError) return cloudflareError;
109
+ }
110
+ return null;
111
+ }
112
+
113
+ /**
114
+ * The dashboard's 422 `cert_missing`, as a Hub refusal: the resolved paths
115
+ * and the hint travel to the Hub as the command's data.
116
+ */
117
+ function certMissingResult({ certPath, keyPath }) {
118
+ return { ok: false, code: 'cert_missing', certPath, keyPath, hint: CERT_MISSING_HINT, error: CERT_MISSING_HINT };
119
+ }
120
+
74
121
  export async function handleHubDomainCommand(payload) {
75
122
  const { action, name, domain, deleteCert } = payload ?? {};
76
123
  const { nginxDir } = loadConfig();
@@ -79,6 +126,10 @@ export async function handleHubDomainCommand(payload) {
79
126
 
80
127
  case 'create': {
81
128
  if (!domain?.name) return { ok: false, error: 'domain.name is required' };
129
+ // The same checks the dashboard runs. The name becomes a config file
130
+ // name, so it must be a plain hostname before anything is written.
131
+ const invalid = hubDomainInputError(domain, { creating: true });
132
+ if (invalid) return { ok: false, error: invalid };
82
133
  if (findDomain(domain.name)) return { ok: false, error: `Domain ${domain.name} already exists` };
83
134
 
84
135
  const newDomain = createDomain({
@@ -96,6 +147,11 @@ export async function handleHubDomainCommand(payload) {
96
147
  advanced: { ...DOMAIN_DEFAULTS.advanced, ...domain.advanced },
97
148
  });
98
149
 
150
+ // Same refusal as the dashboard: never point nginx at certificate files
151
+ // that are not on disk. The Hub offers Create certificate on this code.
152
+ const missingNew = await missingCertFiles(newDomain);
153
+ if (missingNew) return certMissingResult(missingNew);
154
+
99
155
  // Shared core apply (same path as the CLI and the dashboard API).
100
156
  const created = await writeConfWithTest(newDomain);
101
157
  if (!created.ok) {
@@ -120,7 +176,12 @@ export async function handleHubDomainCommand(payload) {
120
176
  const existing = targetName ? findDomain(targetName) : null;
121
177
  if (!existing) return { ok: false, error: `Domain ${targetName} not found` };
122
178
 
123
- const updates = domain ?? {};
179
+ // Fields the agent owns are never taken from the Hub: the config path is
180
+ // derived from the name, and enabling is hub:manageDomain toggle, which
181
+ // has its own permission.
182
+ const { configFile: _cf, enabled: _en, createdAt: _ca, ...updates } = domain ?? {};
183
+ const invalid = hubDomainInputError(updates, { creating: false, existing });
184
+ if (invalid) return { ok: false, error: invalid };
124
185
  const updatedDomain = {
125
186
  ...existing,
126
187
  ...updates,
@@ -132,6 +193,11 @@ export async function handleHubDomainCommand(payload) {
132
193
  updatedAt: new Date().toISOString(),
133
194
  };
134
195
 
196
+ // Same refusal as the dashboard: never point nginx at certificate files
197
+ // that are not on disk. The Hub offers Create certificate on this code.
198
+ const missingUpdated = await missingCertFiles(updatedDomain);
199
+ if (missingUpdated) return certMissingResult(missingUpdated);
200
+
135
201
  // Shared core apply — restores the previous config exactly if it fails,
136
202
  // so the .bak dance is no longer needed here.
137
203
  const updatedResult = await writeConfWithTest(updatedDomain);
@@ -426,6 +426,24 @@ export function createCommandProgress(requestId) {
426
426
  };
427
427
  }
428
428
 
429
+ /**
430
+ * An Error carrying a handler's own { ok: false, ... } result as `data`, so a
431
+ * refusal reaches the Hub with its details (the failed stage, the domains that
432
+ * still use a certificate) instead of only a message. Handlers build that
433
+ * result from fields meant for the Hub; nothing secret goes in it.
434
+ *
435
+ * @param {Object} result
436
+ * @param {string} fallback
437
+ */
438
+ function refusalError(result, fallback) {
439
+ const message = typeof result?.error === 'string'
440
+ ? result.error
441
+ : (result?.error?.cause || fallback);
442
+ const err = new Error(message);
443
+ err.data = result;
444
+ return err;
445
+ }
446
+
429
447
  /** Emits the acknowledgement the Hub and its browser clients wait for. */
430
448
  function sendResult(requestId, ok, { error = null, data = null } = {}, ack = null) {
431
449
  if (!requestId) return;
@@ -488,7 +506,9 @@ async function runCommand(command, payload, fn, ack = null) {
488
506
  } catch (err) {
489
507
  console.error('[hubAgent]', command, 'failed:', err.message);
490
508
  logCommandTiming(command, startedAt, false);
491
- sendResult(requestId, false, { error: err.message }, ack);
509
+ // A handler may attach a structured refusal (refusalError above) so the
510
+ // Hub can show it as well as the message.
511
+ sendResult(requestId, false, { error: err.message, data: err.data ?? null }, ack);
492
512
  }
493
513
  }
494
514
 
@@ -627,7 +647,7 @@ async function handleManageDomain(payload, ack) {
627
647
  return runCommand('hub:manageDomain', payload, async (p) => {
628
648
  const { handleHubDomainCommand } = await import('../domains-db.js');
629
649
  const result = await handleHubDomainCommand(p);
630
- if (result && result.ok === false) throw new Error(result.error || 'domain command failed');
650
+ if (result && result.ok === false) throw refusalError(result, 'domain command failed');
631
651
 
632
652
  // Re-sync to the hub and refresh any open local dashboard tab.
633
653
  pushDomainHealth();
@@ -643,7 +663,7 @@ async function handleManageSSL(payload, ack) {
643
663
  const result = await handleHubSslCommand(p, {
644
664
  onProgress: createCommandProgress(p?.requestId),
645
665
  });
646
- if (result && result.ok === false) throw new Error(result.error || 'ssl command failed');
666
+ if (result && result.ok === false) throw refusalError(result, 'ssl command failed');
647
667
 
648
668
  pushCertExpiry();
649
669
  pushDomainConfigs();
@@ -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
  *
@@ -56,6 +56,7 @@ import * as windowsPersonal from './windowsPersonal.js';
56
56
  import * as legacy from './legacy.js';
57
57
  import { enableServerMode, disableServerMode, describeOriginal } from './dataDir.js';
58
58
  import { linkRuntime, inspectRuntime, runtimeNodePath } from './runtime.js';
59
+ import { resolveOperator } from './operator.js';
59
60
 
60
61
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
61
62
 
@@ -477,10 +478,16 @@ async function installWindowsServer({ entry, root, log, legacyResult, deps = {}
477
478
 
478
479
  const config = loadConfig();
479
480
 
481
+ // Who may start and stop the service afterwards without elevation: the
482
+ // account that asked for the install (operator.js). Resolved here, in the
483
+ // elevated process, from Windows itself or from the relaunch that started it.
484
+ const operator = await (deps.resolveOperator ?? resolveOperator)({});
485
+
480
486
  const installed = await ws.install({
481
487
  dataDir,
482
488
  appRoot: root,
483
489
  config,
490
+ operator,
484
491
  log,
485
492
  ...(deps.windowsServiceOpts ?? {}),
486
493
  });
@@ -497,6 +504,7 @@ async function installWindowsServer({ entry, root, log, legacyResult, deps = {}
497
504
  entry: installed.runtime?.entry ?? entry,
498
505
  dataDir,
499
506
  granted: installed.granted ?? [],
507
+ operator: installed.operator ?? null,
500
508
  });
501
509
  }
502
510
 
@@ -668,9 +676,14 @@ export async function uninstall({
668
676
  if (!removed.ok) return { ok: false, ...result, reason: removed.reason };
669
677
  } else if (mech.mode === MODES.SERVER) {
670
678
  const config = loadConfig();
679
+ const operator = (dbGet(STATE_KEY) ?? {}).operator ?? null;
671
680
  const removed = await (deps.windowsService ?? windowsService).uninstall({
672
681
  dataDir: getDataDir(),
673
682
  config,
683
+ // The start/stop right goes with the service. The data directory grant
684
+ // is removed only when the data leaves ProgramData: while the CLI keeps
685
+ // using it there, removing it would bring back the read-only database.
686
+ operator: keepServerDataLocation ? null : operator,
674
687
  log,
675
688
  ...(deps.windowsServiceOpts ?? {}),
676
689
  });
@@ -685,6 +698,12 @@ export async function uninstall({
685
698
  + 'the dashboard keep reading it. Run `ezz service uninstall` again and choose to move it '
686
699
  + 'back if you change your mind.',
687
700
  );
701
+ if (operator?.dataDir) {
702
+ result.notes.push(
703
+ `${operator.name ?? 'Your account'} keeps write access to ${programDataDir()} so the CLI can still use it; `
704
+ + 'it is removed when the data is moved back or purged.',
705
+ );
706
+ }
688
707
  result.dataDir = programDataDir();
689
708
  } else {
690
709
  log('Moving the data back to %APPDATA%…');
@@ -722,7 +741,12 @@ export async function uninstall({
722
741
  }
723
742
 
724
743
  const existing = dbGet(STATE_KEY) ?? {};
725
- dbSet(STATE_KEY, { ...existing, mode: null, mechanism: null, uninstalledAt: new Date().toISOString() });
744
+ const keptOperator = mech.mode === MODES.SERVER && keepServerDataLocation && existing.operator?.dataDir
745
+ ? { ...existing.operator, serviceControl: false }
746
+ : null;
747
+ dbSet(STATE_KEY, {
748
+ ...existing, mode: null, mechanism: null, operator: keptOperator, uninstalledAt: new Date().toISOString(),
749
+ });
726
750
 
727
751
  return { ok: true, ...result };
728
752
  }
@@ -925,7 +949,7 @@ export async function restart({ log = () => {}, deps = {} } = {}) {
925
949
  if (!result.ok) return { ok: false, reason: result.reason };
926
950
  } else {
927
951
  const result = await (deps.windowsService ?? windowsService).restart(deps.windowsServiceOpts ?? {});
928
- if (!result.ok) return { ok: false, reason: result.reason };
952
+ if (!result.ok) return { ok: false, reason: result.reason, needsElevation: result.needsElevation ?? false };
929
953
  }
930
954
 
931
955
  // A restart also ends a deliberate stop: the service is running again, so
@@ -1049,6 +1073,7 @@ export async function status({ cache = false, coldWaitMs, deps = {} } = {}) {
1049
1073
  dataDir,
1050
1074
  config,
1051
1075
  granted: recorded.granted ?? [],
1076
+ operatorSid: recorded.operator?.sid ?? null,
1052
1077
  ...(deps.windowsServiceOpts ?? {}),
1053
1078
  });
1054
1079
  }
@@ -1088,6 +1113,36 @@ export async function status({ cache = false, coldWaitMs, deps = {} } = {}) {
1088
1113
  if (isWindows && mech.mode === MODES.SERVER && out.service.acl && !out.service.acl.ok) {
1089
1114
  out.warnings.push(out.service.acl.reason);
1090
1115
  }
1116
+
1117
+ // Who may start and stop it without elevation. The record says who it was
1118
+ // granted to; the service's DACL (read by the probe) says whether it still is.
1119
+ if (isWindows && mech.mode === MODES.SERVER) {
1120
+ const op = recorded.operator ?? null;
1121
+ const control = out.service.operatorControl ?? null;
1122
+ out.operator = op
1123
+ ? {
1124
+ name: op.name ?? null,
1125
+ sid: op.sid,
1126
+ serviceControl: control ? control.granted : Boolean(op.serviceControl),
1127
+ dataDir: Boolean(op.dataDir),
1128
+ grantedAt: op.grantedAt ?? null,
1129
+ verified: Boolean(control),
1130
+ }
1131
+ : null;
1132
+
1133
+ if (out.service.installed && (!op || !op.dataDir || (control && !control.granted))) {
1134
+ out.warnings.push(
1135
+ 'Starting and stopping the service, and writing its data, need an Administrator terminal for your '
1136
+ + 'account. Run `ezz service repair` once from an Administrator PowerShell to allow it without elevation.',
1137
+ );
1138
+ }
1139
+ if (control?.excessive) {
1140
+ out.warnings.push(
1141
+ `The service permissions give ${op?.name ?? op?.sid} more than start, stop and query. `
1142
+ + 'Run `ezz service repair` from an Administrator PowerShell to reset them.',
1143
+ );
1144
+ }
1145
+ }
1091
1146
  if (isWindows && mech.mode !== MODES.SERVER) {
1092
1147
  out.warnings.push(...(out.service.warnings ?? []));
1093
1148
  }
@@ -1247,6 +1302,8 @@ export async function repair({ log = () => {}, deps = {} } = {}) {
1247
1302
  dataDir,
1248
1303
  appRoot: appRoot(),
1249
1304
  config: loadConfig(),
1305
+ // Repair is how an install from before 1.4.3 gets these rights.
1306
+ operator: await (deps.resolveOperator ?? resolveOperator)({}),
1250
1307
  log,
1251
1308
  // Repair restores the previous runtime if the daemon does not come up,
1252
1309
  // and "came up" means its heartbeat — not the service manager's word.
@@ -1259,7 +1316,12 @@ export async function repair({ log = () => {}, deps = {} } = {}) {
1259
1316
  });
1260
1317
  if (result.ok) {
1261
1318
  const existing = dbGet(STATE_KEY) ?? {};
1262
- dbSet(STATE_KEY, { ...existing, granted: result.granted ?? existing.granted ?? [], repairedAt: new Date().toISOString() });
1319
+ dbSet(STATE_KEY, {
1320
+ ...existing,
1321
+ granted: result.granted ?? existing.granted ?? [],
1322
+ operator: result.operator ?? existing.operator ?? null,
1323
+ repairedAt: new Date().toISOString(),
1324
+ });
1263
1325
  }
1264
1326
  return { ...result, mechanism: 'winsw' };
1265
1327
  }