easy-devops 0.2.7 → 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
 
@@ -66,8 +69,11 @@ createApp({
66
69
  ssl: {
67
70
  certs: [], loading: false, error: '', renewingDomain: null,
68
71
  showCreateForm: false,
69
- createDomain: '', createWww: false,
72
+ createDomain: '', createWww: false, createEmail: '',
70
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
71
77
  },
72
78
 
73
79
  // T017-T019: Updated domains state
@@ -78,9 +84,12 @@ createApp({
78
84
  saving: false,
79
85
  dirty: false, // T019: Track unsaved changes
80
86
  form: JSON.parse(JSON.stringify(DEFAULT_FORM)), // T025: Nested v2 structure
81
- certMissing: null, // { certPath, keyPath, hint } set when POST /api/domains returns 422
87
+ certMissing: null, // { certPath, keyPath, hint } set when POST /api/domains returns 422
82
88
  certCreating: false, // true while POST /api/ssl/create is in-flight
83
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
84
93
  },
85
94
 
86
95
  // T018: Collapsible section state
@@ -93,7 +102,7 @@ createApp({
93
102
  },
94
103
 
95
104
  settings: {
96
- dashboardPort: '', nginxDir: '', certbotDir: '',
105
+ dashboardPort: '', nginxDir: '', sslDir: '', acmeEmail: '',
97
106
  password: '', loading: false, msg: '', error: '',
98
107
  platform: 'linux', // T022: Platform from settings API
99
108
  },
@@ -103,6 +112,21 @@ createApp({
103
112
  computed: {
104
113
  isDark() { return this.theme === 'dark'; },
105
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
+ },
106
130
  },
107
131
 
108
132
  watch: {
@@ -110,6 +134,13 @@ createApp({
110
134
  localStorage.setItem('ed-theme', val);
111
135
  document.documentElement.classList.toggle('dark', val === 'dark');
112
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
+ },
113
144
 
114
145
  // T019: Deep watch form for dirty tracking
115
146
  'domains.form': {
@@ -127,6 +158,13 @@ createApp({
127
158
  this.autoPopulateCertPaths();
128
159
  }
129
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
+ },
130
168
  },
131
169
 
132
170
  // T020: beforeunload guard for unsaved changes
@@ -141,6 +179,7 @@ createApp({
141
179
 
142
180
  async mounted() {
143
181
  document.documentElement.classList.toggle('dark', this.theme === 'dark');
182
+ document.documentElement.setAttribute('data-accent', this.accent);
144
183
 
145
184
  // Check if already authenticated
146
185
  try {
@@ -171,6 +210,7 @@ createApp({
171
210
 
172
211
  // ── Theme ─────────────────────────────────────────────────────────────────
173
212
  toggleTheme() { this.theme = this.theme === 'dark' ? 'light' : 'dark'; },
213
+ setAccent(color) { this.accent = color; },
174
214
 
175
215
  // ── Auth ──────────────────────────────────────────────────────────────────
176
216
  async doLogin() {
@@ -188,11 +228,17 @@ createApp({
188
228
 
189
229
  // ── Navigation (T021: Nav click guard) ────────────────────────────────────
190
230
  async navigateTo(pageId) {
191
- // T021: Check for unsaved changes before navigation
192
231
  if (this.domains.dirty && this.domains.showForm) {
193
- if (!confirm('You have unsaved changes. Discard them and continue?')) {
194
- return;
195
- }
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;
196
242
  this.resetDomainForm();
197
243
  }
198
244
  await this.loadPage(pageId);
@@ -289,15 +335,21 @@ createApp({
289
335
  const r = await this.api('POST', '/api/ssl/create', {
290
336
  domain: this.ssl.createDomain.trim(),
291
337
  www: this.ssl.createWww,
338
+ email: this.ssl.createEmail.trim(),
339
+ validationMethod: this.ssl.createMethod,
292
340
  });
293
341
  this.ssl.creating = false;
294
- if (r.ok) {
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) {
295
346
  this.ssl.createResult = r.data;
296
347
  this.ssl.createDomain = '';
297
348
  this.ssl.createWww = false;
349
+ this.ssl.createEmail = '';
298
350
  await this.loadSSL();
299
- } else if (r.status === 503) {
300
- this.ssl.createError = { step: 'ACME client detection', cause: r.data.hint, consequence: 'Install certbot or win-acme first using the SSL Manager CLI.', nginxRunning: true };
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 };
301
353
  } else if (r.status === 409) {
302
354
  this.ssl.createError = { step: 'port 80 check', cause: r.data.detail, consequence: r.data.hint, nginxRunning: true };
303
355
  } else {
@@ -305,6 +357,30 @@ createApp({
305
357
  }
306
358
  },
307
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
+
308
384
  certStatus(cert) {
309
385
  if (cert.daysLeft === null || cert.daysLeft === undefined) return 'Unknown';
310
386
  if (cert.daysLeft > 30) return 'Healthy';
@@ -332,7 +408,7 @@ createApp({
332
408
  return 'neutral';
333
409
  },
334
410
 
335
- // ── Domains ───────────────────────────────────────────────────────────────
411
+ // ── Domains ───────────────────────────────────────────────────────
336
412
  async loadDomains() {
337
413
  this.domains.loading = true;
338
414
  const r = await this.api('GET', '/api/domains');
@@ -340,9 +416,18 @@ createApp({
340
416
  if (r.ok) this.domains.list = r.data;
341
417
  },
342
418
 
343
- toggleDomainForm() {
419
+ async toggleDomainForm() {
344
420
  if (this.domains.showForm && this.domains.dirty) {
345
- 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;
346
431
  }
347
432
  this.domains.showForm = !this.domains.showForm;
348
433
  if (!this.domains.showForm) {
@@ -357,6 +442,9 @@ createApp({
357
442
  this.domains.error = '';
358
443
  this.domains.certMissing = null;
359
444
  this.domains.certCreateError = null;
445
+ this.domains.certMethod = 'http';
446
+ this.domains.certDnsWaiting = null;
447
+ this.domains.certDnsConfirming = false;
360
448
  // Reset sections
361
449
  this.sections = {
362
450
  basic: true,
@@ -367,11 +455,18 @@ createApp({
367
455
  };
368
456
  },
369
457
 
370
- // T023: editDomain method
371
458
  async editDomain(name) {
372
- // Check for unsaved changes
373
459
  if (this.domains.dirty && this.domains.showForm) {
374
- 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;
375
470
  }
376
471
 
377
472
  // Fetch domain data
@@ -394,6 +489,7 @@ createApp({
394
489
  backendHost: domain.backendHost || '127.0.0.1',
395
490
  upstreamType: domain.upstreamType || 'http',
396
491
  www: domain.www || false,
492
+ wildcard: domain.wildcard || false,
397
493
  ssl: {
398
494
  enabled: domain.ssl?.enabled || false,
399
495
  certPath: domain.ssl?.certPath || '',
@@ -469,18 +565,21 @@ createApp({
469
565
  this.domains.certCreateError = null;
470
566
  const domain = this.domains.form.name;
471
567
  const www = this.domains.form.www;
472
- const r = await this.api('POST', '/api/ssl/create', { domain, www });
568
+ const r = await this.api('POST', '/api/ssl/create', { domain, www, validationMethod: this.domains.certMethod });
473
569
  this.domains.certCreating = false;
474
570
 
475
- if (r.ok) {
476
- // Update cert paths in the form with what certbot actually wrote
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
477
576
  this.domains.form.ssl.certPath = r.data.certPath;
478
577
  this.domains.form.ssl.keyPath = r.data.keyPath;
479
578
  this.domains.certMissing = null;
480
579
  // Retry the domain save now that the cert exists
481
580
  await this.saveDomain();
482
- } else if (r.status === 503) {
483
- this.domains.certCreateError = { step: 'ACME client detection', cause: r.data.hint, consequence: 'Install certbot or win-acme first.', nginxRunning: true };
581
+ } else if (r.status === 400) {
582
+ this.domains.certCreateError = { step: 'email configuration', cause: r.data.hint, consequence: 'Configure acmeEmail in settings.', nginxRunning: true };
484
583
  } else if (r.status === 409) {
485
584
  this.domains.certCreateError = { step: 'port 80 check', cause: r.data.detail, consequence: r.data.hint, nginxRunning: true };
486
585
  } else {
@@ -488,21 +587,61 @@ createApp({
488
587
  }
489
588
  },
490
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
+
491
613
  disableSslAndSave() {
492
614
  this.domains.form.ssl.enabled = false;
493
615
  this.domains.certMissing = null;
494
616
  this.domains.certCreateError = null;
617
+ this.domains.certDnsWaiting = null;
495
618
  this.saveDomain();
496
619
  },
497
620
 
498
621
  dismissCertMissing() {
499
622
  this.domains.certMissing = null;
500
623
  this.domains.certCreateError = null;
624
+ this.domains.certDnsWaiting = null;
501
625
  },
502
626
 
503
627
  async deleteDomain(name) {
504
- if (!confirm(`Delete domain "${name}"? This cannot be undone.`)) return;
505
- 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' : ''}`);
506
645
  await this.loadDomains();
507
646
  },
508
647
 
@@ -510,6 +649,29 @@ createApp({
510
649
  await this.api('POST', `/api/domains/${name}/reload`);
511
650
  },
512
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
+
513
675
  // T024: Auto-populate SSL paths when SSL is enabled
514
676
  autoPopulateCertPaths() {
515
677
  if (this.domains.form.ssl.enabled) {
@@ -518,11 +680,11 @@ createApp({
518
680
  if (domain) {
519
681
  const platform = this.settings.platform;
520
682
  if (platform === 'win32') {
521
- this.domains.form.ssl.certPath = `C:\\Certbot\\live\\${domain}\\fullchain.pem`;
522
- 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`;
523
685
  } else {
524
- this.domains.form.ssl.certPath = `/etc/letsencrypt/live/${domain}/fullchain.pem`;
525
- 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`;
526
688
  }
527
689
  }
528
690
  }
@@ -537,7 +699,8 @@ createApp({
537
699
  if (r.ok) {
538
700
  this.settings.dashboardPort = r.data.dashboardPort;
539
701
  this.settings.nginxDir = r.data.nginxDir;
540
- this.settings.certbotDir = r.data.certbotDir;
702
+ this.settings.sslDir = r.data.sslDir;
703
+ this.settings.acmeEmail = r.data.acmeEmail || '';
541
704
  this.settings.platform = r.data.platform || 'linux'; // T022
542
705
  }
543
706
  },
@@ -547,7 +710,8 @@ createApp({
547
710
  const payload = {
548
711
  dashboardPort: this.settings.dashboardPort,
549
712
  nginxDir: this.settings.nginxDir,
550
- certbotDir: this.settings.certbotDir,
713
+ sslDir: this.settings.sslDir,
714
+ acmeEmail: this.settings.acmeEmail,
551
715
  };
552
716
  if (this.settings.password) payload.dashboardPassword = this.settings.password;
553
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,6 +98,8 @@ 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
 
159
105
  // Cert existence check (FR-001): prevent saving a config that references non-existent cert files
@@ -202,8 +148,9 @@ router.put('/:name', async (req, res) => {
202
148
 
203
149
  const body = req.body ?? {};
204
150
 
205
- // Validate port if provided
206
- 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) {
207
154
  const portError = validatePort(body.port);
208
155
  if (portError) {
209
156
  return res.status(400).json({ error: portError });
@@ -230,6 +177,7 @@ router.put('/:name', async (req, res) => {
230
177
  performance: { ...existing.performance, ...updates.performance },
231
178
  security: { ...existing.security, ...updates.security },
232
179
  advanced: { ...existing.advanced, ...updates.advanced },
180
+ wildcard: updates.wildcard ?? existing.wildcard ?? false,
233
181
  updatedAt: new Date().toISOString(),
234
182
  };
235
183
 
@@ -272,11 +220,13 @@ router.put('/:name', async (req, res) => {
272
220
 
273
221
  router.delete('/:name', async (req, res) => {
274
222
  const { name } = req.params;
223
+ const deleteCert = req.query.deleteCert === 'true';
275
224
  const domain = findDomain(name);
276
225
  if (!domain) {
277
226
  return res.status(404).json({ error: `Domain not found: ${name}` });
278
227
  }
279
228
 
229
+ // Delete nginx conf file
280
230
  if (domain.configFile) {
281
231
  try {
282
232
  await fs.unlink(domain.configFile);
@@ -287,10 +237,84 @@ router.delete('/:name', async (req, res) => {
287
237
  }
288
238
  }
289
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
+
290
249
  const domains = getDomains().filter((d) => d.name !== name);
291
250
  saveDomains(domains);
292
251
 
293
- 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
+ }
294
318
  });
295
319
 
296
320
  // ─── POST /api/domains/:name/reload ──────────────────────────────────────────