easy-devops 1.4.1 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "easy-devops",
3
- "version": "1.4.1",
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",
@@ -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
+ }
@@ -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();
@@ -4,7 +4,7 @@ import { run } from '../../core/shell.js';
4
4
  import { loadConfig } from '../../core/config.js';
5
5
  import { getDomains, saveDomains, findDomain, createDomain, DOMAIN_DEFAULTS } from '../../core/domains-db.js';
6
6
  import { writeConfWithTest } from '../../core/nginx-apply.js';
7
- import { getDefaultCertPaths } from '../../core/nginx-conf-generator.js';
7
+ import { missingCertFiles, CERT_MISSING_HINT } from '../../core/cert-usage.js';
8
8
  import { getCertExpiry } from '../../core/cert-reader.js';
9
9
  import { findCertificateForDomain } from '../../core/cert-suggest.js';
10
10
  import { isWindows, nginxTestCmd, nginxReloadCmd, isNginxTestOk, hasBackslashPath } from '../../core/platform.js';
@@ -30,37 +30,8 @@ function applyErrorResponse(applied) {
30
30
  return { error: 'nginx config test failed', details: applied.error, output };
31
31
  }
32
32
 
33
- /**
34
- * Resolves the paths nginx will load and reports them when either file is
35
- * missing. Blank fields use the same `${sslDir}/${name}` fallback as the
36
- * config generator, so this check matches the generated config.
37
- * @param {{ name: string, ssl?: { enabled?: boolean, certPath?: string, keyPath?: string } }} domain
38
- * @returns {Promise<{ certPath: string, keyPath: string } | null>}
39
- */
40
- async function missingCertFiles(domain) {
41
- if (!domain.ssl?.enabled) return null;
42
-
43
- const { sslDir } = loadConfig();
44
- const defaults = getDefaultCertPaths(domain.name, process.platform, sslDir);
45
- const certPath = domain.ssl.certPath || defaults.certPath;
46
- const keyPath = domain.ssl.keyPath || defaults.keyPath;
47
-
48
- try {
49
- await fs.access(certPath, fs.constants.F_OK);
50
- await fs.access(keyPath, fs.constants.F_OK);
51
- return null;
52
- } catch {
53
- return { certPath, keyPath };
54
- }
55
- }
56
-
57
33
  function certMissingBody({ certPath, keyPath }) {
58
- return {
59
- error: 'cert_missing',
60
- certPath,
61
- keyPath,
62
- hint: 'The SSL certificate files do not exist at the configured paths. Create the certificate first, or disable SSL.',
63
- };
34
+ return { error: 'cert_missing', certPath, keyPath, hint: CERT_MISSING_HINT };
64
35
  }
65
36
 
66
37
  class DomainsController {