easy-devops 0.2.6 → 1.0.0

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,7 @@ const DEFAULT_FORM = {
8
8
  backendHost: '127.0.0.1',
9
9
  upstreamType: 'http',
10
10
  www: false,
11
+ wildcard: false,
11
12
  ssl: {
12
13
  enabled: false,
13
14
  certPath: '',
@@ -42,6 +43,8 @@ createApp({
42
43
  data() {
43
44
  return {
44
45
  theme: localStorage.getItem('ed-theme') || 'dark',
46
+ accent: localStorage.getItem('ed-accent') || 'teal',
47
+ sidebarCollapsed: localStorage.getItem('ed-sidebar') === 'true',
45
48
  authenticated: false,
46
49
  page: 'overview',
47
50
 
@@ -63,7 +66,15 @@ createApp({
63
66
  logs: [], logsLoading: false,
64
67
  },
65
68
 
66
- ssl: { certs: [], loading: false, error: '', renewingDomain: null },
69
+ ssl: {
70
+ certs: [], loading: false, error: '', renewingDomain: null,
71
+ showCreateForm: false,
72
+ createDomain: '', createWww: false, createEmail: '',
73
+ creating: false, createResult: null, createError: null,
74
+ createMethod: 'http', // 'http' | 'dns'
75
+ dnsWaiting: null, // { txtName, txtValue, domain } | null
76
+ dnsConfirming: false, // true while confirm call is in-flight
77
+ },
67
78
 
68
79
  // T017-T019: Updated domains state
69
80
  domains: {
@@ -73,6 +84,12 @@ createApp({
73
84
  saving: false,
74
85
  dirty: false, // T019: Track unsaved changes
75
86
  form: JSON.parse(JSON.stringify(DEFAULT_FORM)), // T025: Nested v2 structure
87
+ certMissing: null, // { certPath, keyPath, hint } set when POST /api/domains returns 422
88
+ certCreating: false, // true while POST /api/ssl/create is in-flight
89
+ certCreateError: null, // structured error from a failed cert creation
90
+ certMethod: 'http', // 'http' | 'dns' — method selected in cert_missing section
91
+ certDnsWaiting: null, // { txtName, txtValue, domain } while DNS two-phase is in progress
92
+ certDnsConfirming: false, // true while /create-confirm call is in-flight
76
93
  },
77
94
 
78
95
  // T018: Collapsible section state
@@ -85,7 +102,7 @@ createApp({
85
102
  },
86
103
 
87
104
  settings: {
88
- dashboardPort: '', nginxDir: '', certbotDir: '',
105
+ dashboardPort: '', nginxDir: '', sslDir: '', acmeEmail: '',
89
106
  password: '', loading: false, msg: '', error: '',
90
107
  platform: 'linux', // T022: Platform from settings API
91
108
  },
@@ -95,6 +112,21 @@ createApp({
95
112
  computed: {
96
113
  isDark() { return this.theme === 'dark'; },
97
114
  expiringCount() { return this.ssl.certs.filter(c => c.daysLeft !== null && c.daysLeft < 30).length; },
115
+ swalTheme() {
116
+ // Create dynamically evaluated properties based on current CSS variables
117
+ const rootStyle = getComputedStyle(document.documentElement);
118
+ return {
119
+ background: 'var(--color-surface)',
120
+ color: 'var(--color-text)',
121
+ confirmButtonColor: rootStyle.getPropertyValue('--color-primary').trim(),
122
+ cancelButtonColor: 'transparent',
123
+ customClass: {
124
+ confirmButton: 'btn btn-primary',
125
+ cancelButton: 'btn btn-secondary',
126
+ popup: 'swal2-popup'
127
+ }
128
+ };
129
+ },
98
130
  },
99
131
 
100
132
  watch: {
@@ -102,6 +134,13 @@ createApp({
102
134
  localStorage.setItem('ed-theme', val);
103
135
  document.documentElement.classList.toggle('dark', val === 'dark');
104
136
  },
137
+ accent(val) {
138
+ localStorage.setItem('ed-accent', val);
139
+ document.documentElement.setAttribute('data-accent', val);
140
+ },
141
+ sidebarCollapsed(val) {
142
+ localStorage.setItem('ed-sidebar', val);
143
+ },
105
144
 
106
145
  // T019: Deep watch form for dirty tracking
107
146
  'domains.form': {
@@ -119,6 +158,13 @@ createApp({
119
158
  this.autoPopulateCertPaths();
120
159
  }
121
160
  },
161
+
162
+ // Wildcard: force DNS cert method when wildcard is enabled
163
+ 'domains.form.wildcard'(newVal) {
164
+ if (newVal) {
165
+ this.domains.certMethod = 'dns';
166
+ }
167
+ },
122
168
  },
123
169
 
124
170
  // T020: beforeunload guard for unsaved changes
@@ -133,6 +179,7 @@ createApp({
133
179
 
134
180
  async mounted() {
135
181
  document.documentElement.classList.toggle('dark', this.theme === 'dark');
182
+ document.documentElement.setAttribute('data-accent', this.accent);
136
183
 
137
184
  // Check if already authenticated
138
185
  try {
@@ -163,6 +210,7 @@ createApp({
163
210
 
164
211
  // ── Theme ─────────────────────────────────────────────────────────────────
165
212
  toggleTheme() { this.theme = this.theme === 'dark' ? 'light' : 'dark'; },
213
+ setAccent(color) { this.accent = color; },
166
214
 
167
215
  // ── Auth ──────────────────────────────────────────────────────────────────
168
216
  async doLogin() {
@@ -180,11 +228,17 @@ createApp({
180
228
 
181
229
  // ── Navigation (T021: Nav click guard) ────────────────────────────────────
182
230
  async navigateTo(pageId) {
183
- // T021: Check for unsaved changes before navigation
184
231
  if (this.domains.dirty && this.domains.showForm) {
185
- if (!confirm('You have unsaved changes. Discard them and continue?')) {
186
- return;
187
- }
232
+ const { isConfirmed } = await Swal.fire({
233
+ title: 'Unsaved changes',
234
+ text: 'Discard changes and continue?',
235
+ icon: 'warning',
236
+ showCancelButton: true,
237
+ confirmButtonText: 'Discard',
238
+ cancelButtonText: 'Stay',
239
+ ...this.swalTheme,
240
+ });
241
+ if (!isConfirmed) return;
188
242
  this.resetDomainForm();
189
243
  }
190
244
  await this.loadPage(pageId);
@@ -273,6 +327,60 @@ createApp({
273
327
  await this.loadSSL();
274
328
  },
275
329
 
330
+ async createCert() {
331
+ if (!this.ssl.createDomain.trim()) return;
332
+ this.ssl.creating = true;
333
+ this.ssl.createResult = null;
334
+ this.ssl.createError = null;
335
+ const r = await this.api('POST', '/api/ssl/create', {
336
+ domain: this.ssl.createDomain.trim(),
337
+ www: this.ssl.createWww,
338
+ email: this.ssl.createEmail.trim(),
339
+ validationMethod: this.ssl.createMethod,
340
+ });
341
+ this.ssl.creating = false;
342
+ if (r.status === 202 && r.data.status === 'waiting_dns') {
343
+ this.ssl.dnsWaiting = r.data; // { domain, txtName, txtValue }
344
+ // Do not hide the form or clear the domain — show DNS waiting state
345
+ } else if (r.ok) {
346
+ this.ssl.createResult = r.data;
347
+ this.ssl.createDomain = '';
348
+ this.ssl.createWww = false;
349
+ this.ssl.createEmail = '';
350
+ await this.loadSSL();
351
+ } else if (r.status === 400) {
352
+ this.ssl.createError = { step: 'email configuration', cause: r.data.hint, consequence: 'Configure acmeEmail in settings or provide email.', nginxRunning: true };
353
+ } else if (r.status === 409) {
354
+ this.ssl.createError = { step: 'port 80 check', cause: r.data.detail, consequence: r.data.hint, nginxRunning: true };
355
+ } else {
356
+ this.ssl.createError = r.data.error || { step: 'certificate issuance', cause: 'Unknown error', consequence: 'No certificate was issued.' };
357
+ }
358
+ },
359
+
360
+ async confirmDns() {
361
+ if (!this.ssl.dnsWaiting) return;
362
+ this.ssl.dnsConfirming = true;
363
+ const r = await this.api('POST', '/api/ssl/create-confirm', { domain: this.ssl.dnsWaiting.domain });
364
+ this.ssl.dnsConfirming = false;
365
+ if (r.ok) {
366
+ this.ssl.createResult = r.data;
367
+ this.ssl.dnsWaiting = null;
368
+ this.ssl.createDomain = '';
369
+ this.ssl.createWww = false;
370
+ this.ssl.createEmail = '';
371
+ await this.loadSSL();
372
+ } else {
373
+ this.ssl.createError = r.data.error || { step: 'DNS validation', cause: 'Certificate issuance failed after DNS confirmation.', consequence: 'No certificate was issued.' };
374
+ this.ssl.dnsWaiting = null;
375
+ }
376
+ },
377
+
378
+ async cancelDns() {
379
+ if (!this.ssl.dnsWaiting) return;
380
+ await this.api('POST', '/api/ssl/create-cancel', { domain: this.ssl.dnsWaiting.domain });
381
+ this.ssl.dnsWaiting = null;
382
+ },
383
+
276
384
  certStatus(cert) {
277
385
  if (cert.daysLeft === null || cert.daysLeft === undefined) return 'Unknown';
278
386
  if (cert.daysLeft > 30) return 'Healthy';
@@ -300,7 +408,7 @@ createApp({
300
408
  return 'neutral';
301
409
  },
302
410
 
303
- // ── Domains ───────────────────────────────────────────────────────────────
411
+ // ── Domains ───────────────────────────────────────────────────────
304
412
  async loadDomains() {
305
413
  this.domains.loading = true;
306
414
  const r = await this.api('GET', '/api/domains');
@@ -308,9 +416,18 @@ createApp({
308
416
  if (r.ok) this.domains.list = r.data;
309
417
  },
310
418
 
311
- toggleDomainForm() {
419
+ async toggleDomainForm() {
312
420
  if (this.domains.showForm && this.domains.dirty) {
313
- if (!confirm('Discard unsaved changes?')) return;
421
+ const { isConfirmed } = await Swal.fire({
422
+ title: 'Unsaved changes',
423
+ text: 'Discard changes and close?',
424
+ icon: 'warning',
425
+ showCancelButton: true,
426
+ confirmButtonText: 'Discard',
427
+ cancelButtonText: 'Stay',
428
+ ...this.swalTheme,
429
+ });
430
+ if (!isConfirmed) return;
314
431
  }
315
432
  this.domains.showForm = !this.domains.showForm;
316
433
  if (!this.domains.showForm) {
@@ -323,6 +440,11 @@ createApp({
323
440
  this.domains.editingName = null;
324
441
  this.domains.dirty = false;
325
442
  this.domains.error = '';
443
+ this.domains.certMissing = null;
444
+ this.domains.certCreateError = null;
445
+ this.domains.certMethod = 'http';
446
+ this.domains.certDnsWaiting = null;
447
+ this.domains.certDnsConfirming = false;
326
448
  // Reset sections
327
449
  this.sections = {
328
450
  basic: true,
@@ -333,11 +455,18 @@ createApp({
333
455
  };
334
456
  },
335
457
 
336
- // T023: editDomain method
337
458
  async editDomain(name) {
338
- // Check for unsaved changes
339
459
  if (this.domains.dirty && this.domains.showForm) {
340
- if (!confirm('Discard unsaved changes?')) return;
460
+ const { isConfirmed } = await Swal.fire({
461
+ title: 'Unsaved changes',
462
+ text: 'Discard changes and edit this domain?',
463
+ icon: 'warning',
464
+ showCancelButton: true,
465
+ confirmButtonText: 'Discard',
466
+ cancelButtonText: 'Stay',
467
+ ...this.swalTheme,
468
+ });
469
+ if (!isConfirmed) return;
341
470
  }
342
471
 
343
472
  // Fetch domain data
@@ -360,6 +489,7 @@ createApp({
360
489
  backendHost: domain.backendHost || '127.0.0.1',
361
490
  upstreamType: domain.upstreamType || 'http',
362
491
  www: domain.www || false,
492
+ wildcard: domain.wildcard || false,
363
493
  ssl: {
364
494
  enabled: domain.ssl?.enabled || false,
365
495
  certPath: domain.ssl?.certPath || '',
@@ -422,14 +552,96 @@ createApp({
422
552
  this.domains.editingName = null;
423
553
  this.resetDomainForm();
424
554
  await this.loadDomains();
555
+ } else if (r.status === 422 && r.data.error === 'cert_missing') {
556
+ this.domains.certMissing = r.data;
557
+ this.domains.certCreateError = null;
425
558
  } else {
426
559
  this.domains.error = r.data.error || 'Failed to save domain';
427
560
  }
428
561
  },
429
562
 
563
+ async createCertAndRetry() {
564
+ this.domains.certCreating = true;
565
+ this.domains.certCreateError = null;
566
+ const domain = this.domains.form.name;
567
+ const www = this.domains.form.www;
568
+ const r = await this.api('POST', '/api/ssl/create', { domain, www, validationMethod: this.domains.certMethod });
569
+ this.domains.certCreating = false;
570
+
571
+ if (r.status === 202 && r.data.status === 'waiting_dns') {
572
+ this.domains.certDnsWaiting = r.data; // { domain, txtName, txtValue }
573
+ // Stay in cert_missing section — show DNS waiting state
574
+ } else if (r.ok) {
575
+ // Update cert paths in the form with what was actually written
576
+ this.domains.form.ssl.certPath = r.data.certPath;
577
+ this.domains.form.ssl.keyPath = r.data.keyPath;
578
+ this.domains.certMissing = null;
579
+ // Retry the domain save now that the cert exists
580
+ await this.saveDomain();
581
+ } else if (r.status === 400) {
582
+ this.domains.certCreateError = { step: 'email configuration', cause: r.data.hint, consequence: 'Configure acmeEmail in settings.', nginxRunning: true };
583
+ } else if (r.status === 409) {
584
+ this.domains.certCreateError = { step: 'port 80 check', cause: r.data.detail, consequence: r.data.hint, nginxRunning: true };
585
+ } else {
586
+ this.domains.certCreateError = r.data.error || { step: 'certificate issuance', cause: 'Unknown error', consequence: 'No certificate was issued.' };
587
+ }
588
+ },
589
+
590
+ async confirmCertDns() {
591
+ if (!this.domains.certDnsWaiting) return;
592
+ this.domains.certDnsConfirming = true;
593
+ const r = await this.api('POST', '/api/ssl/create-confirm', { domain: this.domains.certDnsWaiting.domain });
594
+ this.domains.certDnsConfirming = false;
595
+ if (r.ok) {
596
+ this.domains.form.ssl.certPath = r.data.certPath;
597
+ this.domains.form.ssl.keyPath = r.data.keyPath;
598
+ this.domains.certDnsWaiting = null;
599
+ this.domains.certMissing = null;
600
+ await this.saveDomain();
601
+ } else {
602
+ this.domains.certCreateError = r.data.error || { step: 'DNS validation', cause: 'Certificate issuance failed after DNS confirmation.', consequence: 'No certificate was issued.' };
603
+ this.domains.certDnsWaiting = null;
604
+ }
605
+ },
606
+
607
+ async cancelCertDns() {
608
+ if (!this.domains.certDnsWaiting) return;
609
+ await this.api('POST', '/api/ssl/create-cancel', { domain: this.domains.certDnsWaiting.domain });
610
+ this.domains.certDnsWaiting = null;
611
+ },
612
+
613
+ disableSslAndSave() {
614
+ this.domains.form.ssl.enabled = false;
615
+ this.domains.certMissing = null;
616
+ this.domains.certCreateError = null;
617
+ this.domains.certDnsWaiting = null;
618
+ this.saveDomain();
619
+ },
620
+
621
+ dismissCertMissing() {
622
+ this.domains.certMissing = null;
623
+ this.domains.certCreateError = null;
624
+ this.domains.certDnsWaiting = null;
625
+ },
626
+
430
627
  async deleteDomain(name) {
431
- if (!confirm(`Delete domain "${name}"? This cannot be undone.`)) return;
432
- await this.api('DELETE', `/api/domains/${name}`);
628
+ const domain = this.domains.list.find(d => d.name === name);
629
+ const hasCert = domain?.ssl?.enabled;
630
+ const { isConfirmed, value: deleteCertChecked } = await Swal.fire({
631
+ title: `Delete "${name}"?`,
632
+ text: 'This cannot be undone.',
633
+ icon: 'warning',
634
+ showCancelButton: true,
635
+ confirmButtonText: 'Delete',
636
+ cancelButtonText: 'Cancel',
637
+ input: hasCert ? 'checkbox' : undefined,
638
+ inputValue: 0,
639
+ inputPlaceholder: 'Also delete SSL certificate files',
640
+ ...this.swalTheme,
641
+ });
642
+ if (!isConfirmed) return;
643
+ const deleteCert = hasCert && deleteCertChecked === 1;
644
+ await this.api('DELETE', `/api/domains/${name}${deleteCert ? '?deleteCert=true' : ''}`);
433
645
  await this.loadDomains();
434
646
  },
435
647
 
@@ -437,6 +649,29 @@ createApp({
437
649
  await this.api('POST', `/api/domains/${name}/reload`);
438
650
  },
439
651
 
652
+ async toggleDomain(name) {
653
+ const domain = this.domains.list.find(d => d.name === name);
654
+ const isEnabled = domain?.enabled !== false;
655
+ const action = isEnabled ? 'disable' : 'enable';
656
+ const { isConfirmed } = await Swal.fire({
657
+ title: `${isEnabled ? 'Disable' : 'Enable'} "${name}"?`,
658
+ text: isEnabled
659
+ ? 'Nginx will stop serving this domain until re-enabled.'
660
+ : 'Nginx will resume serving this domain.',
661
+ icon: 'question',
662
+ showCancelButton: true,
663
+ confirmButtonText: isEnabled ? 'Disable' : 'Enable',
664
+ cancelButtonText: 'Cancel',
665
+ ...this.swalTheme,
666
+ });
667
+ if (!isConfirmed) return;
668
+ const r = await this.api('PUT', `/api/domains/${name}/toggle`);
669
+ if (!r.ok) {
670
+ await Swal.fire({ title: 'Error', text: r.data.error || `Failed to ${action} domain`, icon: 'error', ...this.swalTheme });
671
+ }
672
+ await this.loadDomains();
673
+ },
674
+
440
675
  // T024: Auto-populate SSL paths when SSL is enabled
441
676
  autoPopulateCertPaths() {
442
677
  if (this.domains.form.ssl.enabled) {
@@ -445,11 +680,11 @@ createApp({
445
680
  if (domain) {
446
681
  const platform = this.settings.platform;
447
682
  if (platform === 'win32') {
448
- this.domains.form.ssl.certPath = `C:\\Certbot\\live\\${domain}\\fullchain.pem`;
449
- this.domains.form.ssl.keyPath = `C:\\Certbot\\live\\${domain}\\privkey.pem`;
683
+ this.domains.form.ssl.certPath = `C:\\easy-devops\\ssl\\${domain}\\fullchain.pem`;
684
+ this.domains.form.ssl.keyPath = `C:\\easy-devops\\ssl\\${domain}\\privkey.pem`;
450
685
  } else {
451
- this.domains.form.ssl.certPath = `/etc/letsencrypt/live/${domain}/fullchain.pem`;
452
- this.domains.form.ssl.keyPath = `/etc/letsencrypt/live/${domain}/privkey.pem`;
686
+ this.domains.form.ssl.certPath = `/etc/easy-devops/ssl/${domain}/fullchain.pem`;
687
+ this.domains.form.ssl.keyPath = `/etc/easy-devops/ssl/${domain}/privkey.pem`;
453
688
  }
454
689
  }
455
690
  }
@@ -464,7 +699,8 @@ createApp({
464
699
  if (r.ok) {
465
700
  this.settings.dashboardPort = r.data.dashboardPort;
466
701
  this.settings.nginxDir = r.data.nginxDir;
467
- this.settings.certbotDir = r.data.certbotDir;
702
+ this.settings.sslDir = r.data.sslDir;
703
+ this.settings.acmeEmail = r.data.acmeEmail || '';
468
704
  this.settings.platform = r.data.platform || 'linux'; // T022
469
705
  }
470
706
  },
@@ -474,7 +710,8 @@ createApp({
474
710
  const payload = {
475
711
  dashboardPort: this.settings.dashboardPort,
476
712
  nginxDir: this.settings.nginxDir,
477
- certbotDir: this.settings.certbotDir,
713
+ sslDir: this.settings.sslDir,
714
+ acmeEmail: this.settings.acmeEmail,
478
715
  };
479
716
  if (this.settings.password) payload.dashboardPassword = this.settings.password;
480
717
  const r = await this.api('POST', '/api/settings', payload);
@@ -1,79 +1,19 @@
1
1
  import express from 'express';
2
2
  import fs from 'fs/promises';
3
+ import path from 'path';
3
4
  import { run } from '../../core/shell.js';
4
5
  import { loadConfig } from '../../core/config.js';
5
6
  import { getDomains, saveDomains, findDomain, createDomain, DOMAIN_DEFAULTS } from '../lib/domains-db.js';
6
7
  import { generateConf, getDefaultCertPaths } from '../lib/nginx-conf-generator.js';
7
8
  import { getCertExpiry } from '../lib/cert-reader.js';
9
+ import { nginxTestCmd, nginxReloadCmd } from '../../core/platform.js';
10
+ import {
11
+ validateDomainName, validatePort, validateUpstreamType,
12
+ validateMaxBodySize, validatePositiveInteger,
13
+ } from '../../core/validators.js';
8
14
 
9
15
  const router = express.Router();
10
16
 
11
- // ─── shared nginx helpers ─────────────────────────────────────────────────────
12
-
13
- const isWindows = process.platform === 'win32';
14
-
15
- function getNginxExe(nginxDir) {
16
- return isWindows ? `${nginxDir}\\nginx.exe` : 'nginx';
17
- }
18
-
19
- function nginxTestCmd(nginxDir) {
20
- const exe = getNginxExe(nginxDir);
21
- // Use explicit -c flag on Windows to avoid path issues
22
- if (isWindows) {
23
- const confPath = `${nginxDir}\\conf\\nginx.conf`;
24
- return `& "${exe}" -c "${confPath}" -t`;
25
- }
26
- return 'nginx -t';
27
- }
28
-
29
- function nginxReloadCmd(nginxDir) {
30
- const exe = getNginxExe(nginxDir);
31
- return isWindows ? `& "${exe}" -s reload` : 'nginx -s reload';
32
- }
33
-
34
- // ─── Validation helpers ───────────────────────────────────────────────────────
35
-
36
- function validateDomainName(name) {
37
- if (!name || typeof name !== 'string') {
38
- return 'name is required';
39
- }
40
- // Allow wildcards and standard hostnames
41
- const validPattern = /^(\*\.)?[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*$/;
42
- if (!validPattern.test(name) || name.includes('/') || name.includes(' ')) {
43
- return 'Invalid domain name format';
44
- }
45
- return null;
46
- }
47
-
48
- function validatePort(port) {
49
- const portNum = Number(port);
50
- if (!Number.isInteger(portNum) || portNum < 1 || portNum > 65535) {
51
- return 'Invalid port: must be 1-65535';
52
- }
53
- return null;
54
- }
55
-
56
- function validateUpstreamType(type) {
57
- if (type && !['http', 'https', 'ws'].includes(type)) {
58
- return 'Invalid upstreamType: must be http, https, or ws';
59
- }
60
- return null;
61
- }
62
-
63
- function validateMaxBodySize(size) {
64
- if (size && !/^\d+[kmgKMG]?$/.test(size)) {
65
- return 'Invalid maxBodySize format (e.g., 10m, 1g)';
66
- }
67
- return null;
68
- }
69
-
70
- function validatePositiveInteger(val, field) {
71
- if (val !== undefined && (!Number.isInteger(Number(val)) || Number(val) < 1)) {
72
- return `Invalid ${field}: must be a positive integer`;
73
- }
74
- return null;
75
- }
76
-
77
17
  // ─── GET /api/domains ─────────────────────────────────────────────────────────
78
18
 
79
19
  router.get('/', async (_req, res) => {
@@ -98,9 +38,13 @@ router.post('/', async (req, res) => {
98
38
  return res.status(400).json({ error: nameError });
99
39
  }
100
40
 
101
- const portError = validatePort(body.port);
102
- if (portError) {
103
- return res.status(400).json({ error: portError });
41
+ // Port validation is skipped when backendHost is a full external URL
42
+ const backendIsUrl = /^https?:\/\//i.test(body.backendHost ?? '');
43
+ if (!backendIsUrl) {
44
+ const portError = validatePort(body.port);
45
+ if (portError) {
46
+ return res.status(400).json({ error: portError });
47
+ }
104
48
  }
105
49
 
106
50
  // Validate optional fields
@@ -154,8 +98,24 @@ router.post('/', async (req, res) => {
154
98
  accessLog: body.advanced?.accessLog ?? true,
155
99
  customLocations: body.advanced?.customLocations ?? '',
156
100
  },
101
+ wildcard: body.wildcard ?? false,
102
+ enabled: true,
157
103
  });
158
104
 
105
+ // Cert existence check (FR-001): prevent saving a config that references non-existent cert files
106
+ if (domain.ssl.enabled && domain.ssl.certPath) {
107
+ try {
108
+ await fs.access(domain.ssl.certPath, fs.constants.F_OK);
109
+ } catch {
110
+ return res.status(422).json({
111
+ error: 'cert_missing',
112
+ certPath: domain.ssl.certPath,
113
+ keyPath: domain.ssl.keyPath,
114
+ hint: 'The SSL certificate files do not exist at the configured paths. Create the certificate first, or disable SSL.',
115
+ });
116
+ }
117
+ }
118
+
159
119
  const { nginxDir } = loadConfig();
160
120
 
161
121
  try {
@@ -188,8 +148,9 @@ router.put('/:name', async (req, res) => {
188
148
 
189
149
  const body = req.body ?? {};
190
150
 
191
- // Validate port if provided
192
- if (body.port !== undefined) {
151
+ // Validate port if provided (skip when backendHost is a full external URL)
152
+ const backendIsUrl = /^https?:\/\//i.test(body.backendHost ?? existing.backendHost ?? '');
153
+ if (body.port !== undefined && !backendIsUrl) {
193
154
  const portError = validatePort(body.port);
194
155
  if (portError) {
195
156
  return res.status(400).json({ error: portError });
@@ -216,6 +177,7 @@ router.put('/:name', async (req, res) => {
216
177
  performance: { ...existing.performance, ...updates.performance },
217
178
  security: { ...existing.security, ...updates.security },
218
179
  advanced: { ...existing.advanced, ...updates.advanced },
180
+ wildcard: updates.wildcard ?? existing.wildcard ?? false,
219
181
  updatedAt: new Date().toISOString(),
220
182
  };
221
183
 
@@ -258,11 +220,13 @@ router.put('/:name', async (req, res) => {
258
220
 
259
221
  router.delete('/:name', async (req, res) => {
260
222
  const { name } = req.params;
223
+ const deleteCert = req.query.deleteCert === 'true';
261
224
  const domain = findDomain(name);
262
225
  if (!domain) {
263
226
  return res.status(404).json({ error: `Domain not found: ${name}` });
264
227
  }
265
228
 
229
+ // Delete nginx conf file
266
230
  if (domain.configFile) {
267
231
  try {
268
232
  await fs.unlink(domain.configFile);
@@ -273,10 +237,84 @@ router.delete('/:name', async (req, res) => {
273
237
  }
274
238
  }
275
239
 
240
+ // Optionally delete the SSL certificate directory for this domain
241
+ if (deleteCert && domain.ssl?.enabled) {
242
+ const { sslDir } = loadConfig();
243
+ const certDir = path.join(sslDir, name);
244
+ try {
245
+ await fs.rm(certDir, { recursive: true, force: true });
246
+ } catch { /* ignore — cert dir may not exist */ }
247
+ }
248
+
276
249
  const domains = getDomains().filter((d) => d.name !== name);
277
250
  saveDomains(domains);
278
251
 
279
- res.json({ message: `Domain deleted: ${name}` });
252
+ res.json({ deleted: name, certDeleted: deleteCert && domain.ssl?.enabled });
253
+ });
254
+
255
+ // ─── PUT /api/domains/:name/toggle ───────────────────────────────────────────
256
+
257
+ router.put('/:name/toggle', async (req, res) => {
258
+ const { name } = req.params;
259
+ const domain = findDomain(name);
260
+ if (!domain) {
261
+ return res.status(404).json({ error: `Domain not found: ${name}` });
262
+ }
263
+
264
+ const { nginxDir } = loadConfig();
265
+ const isEnabled = domain.enabled !== false;
266
+ const confPath = domain.configFile;
267
+
268
+ if (!confPath) {
269
+ return res.status(400).json({ error: 'Domain has no config file path stored' });
270
+ }
271
+
272
+ // Normalise paths regardless of current stored extension
273
+ const basePath = confPath.replace(/\.disabled$/, '');
274
+ const enabledPath = basePath;
275
+ const disabledPath = `${basePath}.disabled`;
276
+
277
+ if (isEnabled) {
278
+ // Disable: rename .conf → .conf.disabled, then reload nginx
279
+ try {
280
+ await fs.rename(enabledPath, disabledPath);
281
+ } catch (err) {
282
+ return res.status(500).json({ error: 'Failed to rename config file', details: err.message });
283
+ }
284
+
285
+ const domains = getDomains();
286
+ const idx = domains.findIndex(d => d.name === name);
287
+ domains[idx] = { ...domain, enabled: false, configFile: disabledPath, updatedAt: new Date().toISOString() };
288
+ saveDomains(domains);
289
+
290
+ // Reload so nginx stops serving this domain
291
+ await run(nginxReloadCmd(nginxDir), { cwd: nginxDir });
292
+
293
+ return res.json({ enabled: false });
294
+ } else {
295
+ // Enable: rename .conf.disabled → .conf, test, reload
296
+ try {
297
+ await fs.rename(disabledPath, enabledPath);
298
+ } catch (err) {
299
+ return res.status(500).json({ error: 'Failed to rename config file', details: err.message });
300
+ }
301
+
302
+ const testResult = await run(nginxTestCmd(nginxDir), { cwd: nginxDir });
303
+ if (!testResult.success) {
304
+ // Roll back rename
305
+ await fs.rename(enabledPath, disabledPath).catch(() => {});
306
+ return res.status(500).json({ error: 'nginx config test failed', output: testResult.stderr || testResult.stdout });
307
+ }
308
+
309
+ const domains = getDomains();
310
+ const idx = domains.findIndex(d => d.name === name);
311
+ domains[idx] = { ...domain, enabled: true, configFile: enabledPath, updatedAt: new Date().toISOString() };
312
+ saveDomains(domains);
313
+
314
+ await run(nginxReloadCmd(nginxDir), { cwd: nginxDir });
315
+
316
+ return res.json({ enabled: true });
317
+ }
280
318
  });
281
319
 
282
320
  // ─── POST /api/domains/:name/reload ──────────────────────────────────────────