easy-devops 1.4.0 → 1.4.2

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.
@@ -1,4 +1,4 @@
1
- import"./index-gndgYe3K.js";const w=new Set;function L(e){return w.add(e),()=>{w.delete(e)}}const u=e=>new Date(Date.now()+e*864e5).toISOString(),H=()=>({nginx_down:{enabled:!0,channelIds:[]},cert_expiry:{enabled:!0,channelIds:[]},domain_health:{enabled:!0,channelIds:[]}});function h(e){const t=u(-40);return{backendHost:"127.0.0.1",upstreamType:"http",www:!1,wildcard:!1,enabled:!0,configFile:`/etc/nginx/conf.d/${e.name}.conf`,createdAt:t,updatedAt:t,ssl:{enabled:!1,certPath:"",keyPath:"",redirect:!0,hsts:!1,hstsMaxAge:31536e3},performance:{maxBodySize:"10m",readTimeout:60,connectTimeout:10,proxyBuffers:!1,gzip:!0,gzipTypes:"text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript"},security:{rateLimit:!1,rateLimitRate:10,rateLimitBurst:20,securityHeaders:!1,custom404:!1,custom50x:!1},advanced:{accessLog:!0,customLocations:""},certExpiry:null,daysLeft:null,notifications:H(),...e}}const x=e=>({certPath:`/etc/easy-devops/ssl/${e}/fullchain.pem`,keyPath:`/etc/easy-devops/ssl/${e}/privkey.pem`});function $(){return[h({name:"app.example.com",port:3e3,www:!0,ssl:{enabled:!0,...x("app.example.com"),redirect:!0,hsts:!0,hstsMaxAge:31536e3},certExpiry:u(95),daysLeft:95,security:{rateLimit:!0,rateLimitRate:10,rateLimitBurst:20,securityHeaders:!0,custom404:!1,custom50x:!1},notifications:{nginx_down:{enabled:!0,channelIds:["ch-discord-ops"]},cert_expiry:{enabled:!0,channelIds:["ch-discord-ops","ch-telegram-oncall"]},domain_health:{enabled:!1,channelIds:[]}}}),h({name:"api.example.com",port:8080,upstreamType:"https",ssl:{enabled:!0,...x("api.example.com"),redirect:!1,hsts:!1,hstsMaxAge:31536e3},certExpiry:u(12),daysLeft:12,notifications:{nginx_down:{enabled:!1,channelIds:[]},cert_expiry:{enabled:!0,channelIds:["ch-telegram-oncall"]},domain_health:{enabled:!0,channelIds:["ch-telegram-oncall"]}}}),h({name:"blog.example.com",port:4e3,backendHost:"10.0.0.12",security:{rateLimit:!1,rateLimitRate:10,rateLimitBurst:20,securityHeaders:!1,custom404:!0,custom50x:!1},notifications:{nginx_down:{enabled:!1,channelIds:[]},cert_expiry:{enabled:!1,channelIds:[]},domain_health:{enabled:!0,channelIds:["ch-discord-ops"]}}}),h({name:"staging.example.com",port:5e3,enabled:!1,configFile:"/etc/nginx/conf.d/staging.example.com.conf.disabled"})]}function N(){return[{domain:"app.example.com",expiry:u(95),daysLeft:95,status:"valid",autoRenew:"auto",autoRenewDays:7},{domain:"api.example.com",expiry:u(12),daysLeft:12,status:"expiring",autoRenew:"manual",autoRenewDays:7},{domain:"legacy.example.com",expiry:u(-3),daysLeft:-3,status:"expired"},{domain:"pending.example.com",expiry:null,daysLeft:null,status:"not_issued",label:"Not issued yet"},{domain:"broken.example.com",expiry:null,daysLeft:null,status:"unreadable",label:null},{domain:"blog.example.com",expiry:u(64),daysLeft:64,status:"valid",autoRenew:"unused",autoRenewDays:7}]}function j(){return[{id:"ch-discord-ops",name:"Ops Discord",type:"discord",webhookUrl:"https://discord.com/api/webhooks/123456789012345678/example-token",message:"Easy DevOps alert",lastTest:"passed"},{id:"ch-telegram-oncall",name:"On-call Telegram",type:"telegram",botToken:"7123456789:AAExampleTokenForMockOnly",chatId:"-1001234567890",lastTest:"failed"},{id:"ch-discord-builds",name:"Builds Discord",type:"discord",webhookUrl:"https://discord.com/api/webhooks/987654321098765432/example-token",lastTest:null},{id:"ch-telegram-releases",name:"Releases Telegram",type:"telegram",botToken:"7987654321:AAExampleTokenForMockOnly",chatId:"-1009876543210"}]}function C(){return{running:!0,version:"1.24.0",pid:1421}}function B(){return{"app.example.com.conf":`# Generated by Easy DevOps — manual edits are preserved on save only.
1
+ import"./index-N9XxmjHR.js";const w=new Set;function L(e){return w.add(e),()=>{w.delete(e)}}const u=e=>new Date(Date.now()+e*864e5).toISOString(),H=()=>({nginx_down:{enabled:!0,channelIds:[]},cert_expiry:{enabled:!0,channelIds:[]},domain_health:{enabled:!0,channelIds:[]}});function h(e){const t=u(-40);return{backendHost:"127.0.0.1",upstreamType:"http",www:!1,wildcard:!1,enabled:!0,configFile:`/etc/nginx/conf.d/${e.name}.conf`,createdAt:t,updatedAt:t,ssl:{enabled:!1,certPath:"",keyPath:"",redirect:!0,hsts:!1,hstsMaxAge:31536e3},performance:{maxBodySize:"10m",readTimeout:60,connectTimeout:10,proxyBuffers:!1,gzip:!0,gzipTypes:"text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript"},security:{rateLimit:!1,rateLimitRate:10,rateLimitBurst:20,securityHeaders:!1,custom404:!1,custom50x:!1},advanced:{accessLog:!0,customLocations:""},certExpiry:null,daysLeft:null,notifications:H(),...e}}const x=e=>({certPath:`/etc/easy-devops/ssl/${e}/fullchain.pem`,keyPath:`/etc/easy-devops/ssl/${e}/privkey.pem`});function $(){return[h({name:"app.example.com",port:3e3,www:!0,ssl:{enabled:!0,...x("app.example.com"),redirect:!0,hsts:!0,hstsMaxAge:31536e3},certExpiry:u(95),daysLeft:95,security:{rateLimit:!0,rateLimitRate:10,rateLimitBurst:20,securityHeaders:!0,custom404:!1,custom50x:!1},notifications:{nginx_down:{enabled:!0,channelIds:["ch-discord-ops"]},cert_expiry:{enabled:!0,channelIds:["ch-discord-ops","ch-telegram-oncall"]},domain_health:{enabled:!1,channelIds:[]}}}),h({name:"api.example.com",port:8080,upstreamType:"https",ssl:{enabled:!0,...x("api.example.com"),redirect:!1,hsts:!1,hstsMaxAge:31536e3},certExpiry:u(12),daysLeft:12,notifications:{nginx_down:{enabled:!1,channelIds:[]},cert_expiry:{enabled:!0,channelIds:["ch-telegram-oncall"]},domain_health:{enabled:!0,channelIds:["ch-telegram-oncall"]}}}),h({name:"blog.example.com",port:4e3,backendHost:"10.0.0.12",security:{rateLimit:!1,rateLimitRate:10,rateLimitBurst:20,securityHeaders:!1,custom404:!0,custom50x:!1},notifications:{nginx_down:{enabled:!1,channelIds:[]},cert_expiry:{enabled:!1,channelIds:[]},domain_health:{enabled:!0,channelIds:["ch-discord-ops"]}}}),h({name:"staging.example.com",port:5e3,enabled:!1,configFile:"/etc/nginx/conf.d/staging.example.com.conf.disabled"})]}function N(){return[{domain:"app.example.com",expiry:u(95),daysLeft:95,status:"valid",autoRenew:"auto",autoRenewDays:7},{domain:"api.example.com",expiry:u(12),daysLeft:12,status:"expiring",autoRenew:"manual",autoRenewDays:7},{domain:"legacy.example.com",expiry:u(-3),daysLeft:-3,status:"expired"},{domain:"pending.example.com",expiry:null,daysLeft:null,status:"not_issued",label:"Not issued yet"},{domain:"broken.example.com",expiry:null,daysLeft:null,status:"unreadable",label:null},{domain:"blog.example.com",expiry:u(64),daysLeft:64,status:"valid",autoRenew:"unused",autoRenewDays:7}]}function j(){return[{id:"ch-discord-ops",name:"Ops Discord",type:"discord",webhookUrl:"https://discord.com/api/webhooks/123456789012345678/example-token",message:"Easy DevOps alert",lastTest:"passed"},{id:"ch-telegram-oncall",name:"On-call Telegram",type:"telegram",botToken:"7123456789:AAExampleTokenForMockOnly",chatId:"-1001234567890",lastTest:"failed"},{id:"ch-discord-builds",name:"Builds Discord",type:"discord",webhookUrl:"https://discord.com/api/webhooks/987654321098765432/example-token",lastTest:null},{id:"ch-telegram-releases",name:"Releases Telegram",type:"telegram",botToken:"7987654321:AAExampleTokenForMockOnly",chatId:"-1009876543210"}]}function C(){return{running:!0,version:"1.24.0",pid:1421}}function B(){return{"app.example.com.conf":`# Generated by Easy DevOps — manual edits are preserved on save only.
2
2
  server {
3
3
  listen 80;
4
4
  server_name app.example.com www.app.example.com;
@@ -62,8 +62,8 @@
62
62
  }
63
63
  })();
64
64
  </script>
65
- <script type="module" crossorigin src="./assets/index-gndgYe3K.js"></script>
66
- <link rel="stylesheet" crossorigin href="./assets/index-Bu7af-Kj.css">
65
+ <script type="module" crossorigin src="./assets/index-N9XxmjHR.js"></script>
66
+ <link rel="stylesheet" crossorigin href="./assets/index-2znyQBNP.css">
67
67
  </head>
68
68
  <body>
69
69
  <div id="root"></div>
package/install.bat CHANGED
@@ -21,18 +21,25 @@ if errorlevel 1 (
21
21
  exit /b 1
22
22
  )
23
23
 
24
- :: Verify minimum PowerShell version (5.1)
25
- for /f "usebackq tokens=*" %%v in (
26
- `powershell.exe -NoProfile -Command "$PSVersionTable.PSVersion.Major" 2^>nul`
27
- ) do set PS_MAJOR=%%v
24
+ :: Verify minimum PowerShell version (5.1). Windows PowerShell 5.0 and the
25
+ :: 4.x that ships with older Windows releases cannot run install.ps1.
26
+ for /f "usebackq tokens=1,2 delims=." %%a in (
27
+ `powershell.exe -NoProfile -Command "$PSVersionTable.PSVersion.Major.ToString() + '.' + $PSVersionTable.PSVersion.Minor.ToString()" 2^>nul`
28
+ ) do (
29
+ set PS_MAJOR=%%a
30
+ set PS_MINOR=%%b
31
+ )
28
32
 
29
33
  if not defined PS_MAJOR (
30
34
  echo Error: Could not determine PowerShell version. >&2
31
35
  exit /b 1
32
36
  )
33
- if %PS_MAJOR% LSS 5 (
34
- echo Error: PowerShell 5.1 or later is required. Found version %PS_MAJOR%. >&2
35
- echo Please upgrade PowerShell: https://github.com/PowerShell/PowerShell/releases >&2
37
+ if not defined PS_MINOR set PS_MINOR=0
38
+ set /a PS_VERSION_NUM=PS_MAJOR*100+PS_MINOR
39
+ if %PS_VERSION_NUM% LSS 501 (
40
+ echo Error: PowerShell 5.1 or later is required. Found %PS_MAJOR%.%PS_MINOR%. >&2
41
+ echo Install Windows Management Framework 5.1, which upgrades Windows PowerShell to 5.1: >&2
42
+ echo https://www.microsoft.com/download/details.aspx?id=54616 >&2
36
43
  exit /b 1
37
44
  )
38
45
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "easy-devops",
3
- "version": "1.4.0",
3
+ "version": "1.4.2",
4
4
  "description": "A unified DevOps management tool with CLI and web dashboard for managing Nginx, SSL certificates, deployment apps, and Node.js on Linux and Windows servers.",
5
5
  "keywords": [
6
6
  "devops",
@@ -32,6 +32,8 @@ import {
32
32
  } from '../../core/hubLink.js';
33
33
  import { inspect } from '../../core/daemon/lock.js';
34
34
  import { connectToDaemon } from '../../core/daemon/ipc.js';
35
+ import { readAgentStateFromFile } from '../../core/daemon/stateFile.js';
36
+ import { getDataDir } from '../../core/platform.js';
35
37
  import { page, pause, BACK } from '../ui/page.js';
36
38
 
37
39
  const ACTIONS = ['connect', 'status', 'unlink'];
@@ -75,6 +77,11 @@ function say(line = '') {
75
77
  * frames over IPC (server → client only). Its hello frame carries the state at
76
78
  * connect time, so a CLI that starts after the agent connected still sees it.
77
79
  *
80
+ * In Windows Server mode the pipe belongs to NT SERVICE\EasyDevOps and the CLI
81
+ * cannot open it, so the same state is also read from the file the running
82
+ * daemon keeps in the data directory (core/daemon/stateFile.js) — trusted only
83
+ * while its pid holds the live daemon lock. Whichever answers first wins.
84
+ *
78
85
  * @param {Object} opts
79
86
  * @param {number} opts.timeoutMs
80
87
  * @param {(state: Object|null) => boolean} [opts.until]
@@ -86,16 +93,30 @@ function waitForAgentState({ timeoutMs, until = () => false }) {
86
93
  let finished = false;
87
94
  let client = null;
88
95
 
96
+ const dataDir = getDataDir();
97
+ let filePoll = null;
98
+
89
99
  const finish = (timedOut) => {
90
100
  if (finished) return;
91
101
  finished = true;
92
102
  clearTimeout(timer);
103
+ clearInterval(filePoll);
93
104
  try { client?.close(); } catch { /* already closed */ }
94
105
  resolve({ state: latest, timedOut });
95
106
  };
96
107
 
97
108
  const timer = setTimeout(() => finish(true), timeoutMs);
98
109
 
110
+ const fromFile = () => {
111
+ if (finished) return;
112
+ const state = readAgentStateFromFile({ dataDir });
113
+ if (!state) return;
114
+ latest = state;
115
+ if (until(latest)) finish(false);
116
+ };
117
+ fromFile();
118
+ filePoll = setInterval(fromFile, 500);
119
+
99
120
  client = connectToDaemon({
100
121
  onEvent(event, payload) {
101
122
  if (finished) return;
@@ -172,8 +172,16 @@ export async function showStatus() {
172
172
  const daemonDot = d.running ? dot(true) : s.stoppedByUser ? chalk.yellow('●') : dot(false);
173
173
  console.log(` Daemon ${daemonDot} ${daemonLine}`);
174
174
 
175
+ // Clean restarts (a stop, restart, update or repair) and crash restarts are
176
+ // told apart: only the second kind is a problem, and only it can make a
177
+ // crash loop.
175
178
  if (s.service.restarts) {
176
- console.log(` Restarts ${s.service.crashLooping ? chalk.red(s.service.restarts) : s.service.restarts}`);
179
+ const crashes = s.service.crashRestarts ?? 0;
180
+ const clean = s.service.cleanRestarts ?? (s.service.restarts - crashes);
181
+ const parts = [];
182
+ if (clean) parts.push(`${clean} clean (stop/restart)`);
183
+ if (crashes) parts.push(s.service.crashLooping ? chalk.red(`${crashes} after a crash`) : `${crashes} after a crash`);
184
+ console.log(` Restarts ${parts.join(', ')} ${chalk.gray('in the last 10 min')}`);
177
185
  }
178
186
 
179
187
  console.log(` Data directory ${chalk.gray(s.dataDir)}${s.serverMode ? chalk.gray(' (server mode)') : ''}`);
@@ -252,7 +260,30 @@ async function doInstall() {
252
260
  message: 'Install in Server mode?',
253
261
  default: true,
254
262
  }]);
255
- mode = confirmServer ? service.MODES.SERVER : service.MODES.PERSONAL;
263
+ if (confirmServer) {
264
+ mode = service.MODES.SERVER;
265
+ } else {
266
+ // Allowed, but not without saying what it costs on a server: Personal
267
+ // mode is tied to this user's logon session.
268
+ console.log();
269
+ console.log(' ' + chalk.yellow('Personal mode instead:'));
270
+ console.log(' ' + chalk.gray('• It only runs while this user is logged in.'));
271
+ console.log(' ' + chalk.gray('• Signing out of RDP stops it; disconnecting the RDP window keeps it running.'));
272
+ console.log(' ' + chalk.gray('• It does not start at boot before someone logs in.'));
273
+ console.log();
274
+
275
+ const { confirmPersonal } = await inquirer.prompt([{
276
+ type: 'confirm',
277
+ name: 'confirmPersonal',
278
+ message: 'Install in Personal mode?',
279
+ default: true,
280
+ }]);
281
+ if (!confirmPersonal) {
282
+ console.log(' ' + chalk.gray('Nothing was changed.'));
283
+ return 0;
284
+ }
285
+ mode = service.MODES.PERSONAL;
286
+ }
256
287
  } else {
257
288
  const { chosen } = await inquirer.prompt([{
258
289
  type: 'list',
@@ -351,6 +382,8 @@ async function doInstall() {
351
382
  console.log(' ' + chalk.gray('No password is needed — only elevation.'));
352
383
  }
353
384
  console.log();
385
+ console.log(' ' + chalk.gray('Troubleshooting: https://easy-devops.devxor.team/docs/troubleshooting'));
386
+ console.log();
354
387
  return 1;
355
388
  }
356
389
 
@@ -359,7 +392,8 @@ async function doInstall() {
359
392
 
360
393
  if (result.migrated) {
361
394
  console.log(' ' + chalk.gray(`Data moved to ${result.dataDir}`));
362
- if (result.backup) console.log(' ' + chalk.gray(`Backup kept at ${result.backup}`));
395
+ const original = service.describeOriginal(result);
396
+ console.log(' ' + chalk.gray(`${original[0].toUpperCase()}${original.slice(1)}.`));
363
397
  }
364
398
 
365
399
  if (result.legacy?.removed?.length) {
@@ -393,6 +427,17 @@ async function doInstall() {
393
427
  console.log(' ' + chalk.gray(`Daemon reported in after ${Math.round(result.daemon.waitedMs / 1000)}s (pid ${result.daemon.pid})`));
394
428
  }
395
429
 
430
+ // Out of waiting time while Windows reports the service RUNNING: installed,
431
+ // just slow to initialise on its first start. Not a failure, so the status
432
+ // table (which would show the daemon as not yet running) is not printed.
433
+ if (result.stillInitialising) {
434
+ console.log(' ' + chalk.yellow('Started, still initialising.'));
435
+ console.log(' ' + chalk.gray('The first start can be slow while Windows scans the new runtime.'));
436
+ console.log(' ' + chalk.gray('Check with ') + chalk.white('ezz service status') + chalk.gray(' in a minute.'));
437
+ console.log();
438
+ return 0;
439
+ }
440
+
396
441
  console.log();
397
442
  return showStatus();
398
443
  }
@@ -671,6 +716,8 @@ async function doStart() {
671
716
  console.log(' ' + chalk.gray('No password is needed — only elevation.'));
672
717
  }
673
718
  console.log();
719
+ console.log(' ' + chalk.gray('Troubleshooting: https://easy-devops.devxor.team/docs/troubleshooting'));
720
+ console.log();
674
721
  return 1;
675
722
  }
676
723
 
@@ -769,6 +816,8 @@ async function doRepair() {
769
816
  console.log(' ' + chalk.gray('No password is needed — only elevation.'));
770
817
  }
771
818
  console.log();
819
+ console.log(' ' + chalk.gray('Troubleshooting: https://easy-devops.devxor.team/docs/troubleshooting'));
820
+ console.log();
772
821
  return 1;
773
822
  }
774
823
 
@@ -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
+ }
@@ -35,6 +35,8 @@ import { startIpcServer } from './ipc.js';
35
35
  import { inspect } from './lock.js';
36
36
  import { watchForStop } from './stopRequest.js';
37
37
  import { getHubAgentStatus } from '../hub/agent.js';
38
+ import { subscribe } from '../jobs/bus.js';
39
+ import { writeDaemonState, removeDaemonState } from './stateFile.js';
38
40
  import { loadConfig } from '../config.js';
39
41
  import { ensureCode as ensureSetupCode, describe as describeSetupCode } from '../setupCode.js';
40
42
 
@@ -115,6 +117,14 @@ export async function startDaemon({
115
117
  const agent = getHubAgentStatus();
116
118
  log(` hub agent : ${agent?.status ?? 'unknown'}`);
117
119
 
120
+ // The same agent state, in the data directory, for a CLI that cannot open
121
+ // the pipe — in Windows Server mode it belongs to NT SERVICE\EasyDevOps. See
122
+ // core/daemon/stateFile.js. Rewritten on every transition the bus carries.
123
+ writeDaemonState({ dataDir, pid: process.pid, version, hub: agent });
124
+ const unsubscribeState = subscribe('hub:agentState', (payload) => {
125
+ writeDaemonState({ dataDir, pid: process.pid, version, hub: payload });
126
+ });
127
+
118
128
  // The first-run setup code, while the dashboard still has no password.
119
129
  // The daemon's stdout IS the service log (WinSW, systemd, the Startup
120
130
  // supervisor all capture it), which is the second of the two places the
@@ -150,6 +160,8 @@ export async function startDaemon({
150
160
  stopping = (async () => {
151
161
  log('Stopping...');
152
162
  stopWatch.stop();
163
+ try { unsubscribeState?.(); } catch { /* best effort */ }
164
+ removeDaemonState({ dataDir, pid: process.pid });
153
165
  if (ipc) {
154
166
  try { await ipc.close(); } catch { /* best effort */ }
155
167
  }