easy-devops 1.2.0 → 1.2.1

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.
@@ -0,0 +1,291 @@
1
+ import { listAllCerts } from '../lib/cert-reader.js';
2
+ import { issueCert, renewCert } from '../../cli/managers/ssl-manager.js';
3
+ import { loadConfig } from '../../core/config.js';
4
+ import { promises as dns } from 'dns';
5
+
6
+ // In-memory DNS challenge state
7
+ // Keyed by domain name. Entries are cleaned up when the ACME process exits
8
+ // or when cancelled. Entries older than 10 minutes are forcibly removed.
9
+ const pendingDnsChallenges = new Map();
10
+
11
+ setInterval(() => {
12
+ const now = Date.now();
13
+ for (const [domain, state] of pendingDnsChallenges) {
14
+ if (now - state.createdAt > 10 * 60 * 1000) {
15
+ state.confirmDeferred.reject(new Error('DNS challenge timed out after 10 minutes'));
16
+ pendingDnsChallenges.delete(domain);
17
+ }
18
+ }
19
+ }, 60000);
20
+
21
+ class SslController {
22
+ async create(req, res, next) {
23
+ try {
24
+ const { domain, www = false, validationMethod = 'http', email = null } = req.body ?? {};
25
+
26
+ if (!domain || typeof domain !== 'string' || !domain.trim()) {
27
+ return res.status(400).json({ error: 'domain is required' });
28
+ }
29
+
30
+ const domainKey = domain.trim();
31
+ const config = loadConfig();
32
+ const acmeEmail = email || config.acmeEmail;
33
+
34
+ if (validationMethod === 'dns') {
35
+ // Two-phase flow: spawn ACME process, wait for TXT record, respond 202, pause until confirm.
36
+ let confirmResolve, confirmReject;
37
+ const confirmPromise = new Promise((resolve, reject) => {
38
+ confirmResolve = resolve;
39
+ confirmReject = reject;
40
+ });
41
+
42
+ let resultResolve;
43
+ const resultPromise = new Promise((resolve) => { resultResolve = resolve; });
44
+
45
+ // Track whether a response has already been sent (202 from onDnsChallenge)
46
+ let responseSent = false;
47
+
48
+ const onDnsChallenge = async (txtName, txtValue) => {
49
+ responseSent = true;
50
+ pendingDnsChallenges.set(domainKey, {
51
+ domain: domainKey,
52
+ txtName,
53
+ txtValue,
54
+ confirmDeferred: { resolve: confirmResolve, reject: confirmReject },
55
+ resultPromise,
56
+ createdAt: Date.now(),
57
+ });
58
+
59
+ res.status(202).json({
60
+ status: 'waiting_dns',
61
+ domain: domainKey,
62
+ txtName,
63
+ txtValue,
64
+ hint: 'Add a DNS TXT record with the name and value above, then call POST /api/ssl/create-confirm',
65
+ });
66
+
67
+ // Pause until user calls /create-confirm (resolves) or /create-cancel (rejects)
68
+ await confirmPromise;
69
+ };
70
+
71
+ // Run issueCert in the background — it will call onDnsChallenge which sends 202 and pauses.
72
+ issueCert(domainKey, { www: !!www, validationMethod: 'dns', email: acmeEmail, onDnsChallenge })
73
+ .then(result => {
74
+ resultResolve(result);
75
+ pendingDnsChallenges.delete(domainKey);
76
+ if (!responseSent) {
77
+ responseSent = true;
78
+ if (result.success) {
79
+ return res.json({ success: true, certPath: result.certPath, keyPath: result.keyPath });
80
+ }
81
+ const { step } = result.error ?? {};
82
+ if (step === 'email configuration') {
83
+ return res.status(400).json({ error: 'email_required', hint: 'Configure acmeEmail in settings or provide email parameter.' });
84
+ }
85
+ return res.status(500).json({ success: false, error: result.error });
86
+ }
87
+ })
88
+ .catch(err => {
89
+ const errResult = {
90
+ success: false,
91
+ certPath: null,
92
+ keyPath: null,
93
+ error: {
94
+ step: 'certificate issuance',
95
+ cause: err.message,
96
+ consequence: 'Unexpected error during DNS certificate issuance.',
97
+ nginxRunning: true,
98
+ configSaved: false,
99
+ },
100
+ };
101
+ resultResolve(errResult);
102
+ pendingDnsChallenges.delete(domainKey);
103
+ if (!responseSent) {
104
+ responseSent = true;
105
+ return res.status(500).json({ success: false, error: errResult.error });
106
+ }
107
+ });
108
+
109
+ // The response is sent either by onDnsChallenge (202) or by the .then()/.catch() above.
110
+ return;
111
+ }
112
+
113
+ // HTTP validation path (synchronous — responds when complete)
114
+ const result = await issueCert(domainKey, { www: !!www, validationMethod: 'http', email: acmeEmail });
115
+
116
+ if (result.success) {
117
+ return res.json({ success: true, certPath: result.certPath, keyPath: result.keyPath });
118
+ }
119
+
120
+ const { step } = result.error;
121
+ if (step === 'email configuration') {
122
+ return res.status(400).json({
123
+ error: 'email_required',
124
+ hint: 'Configure acmeEmail in settings or provide email parameter.',
125
+ });
126
+ }
127
+ if (step === 'port 80 check') {
128
+ return res.status(409).json({
129
+ error: 'port_busy',
130
+ detail: result.error.cause,
131
+ hint: 'Stop the process using port 80 and try again.',
132
+ });
133
+ }
134
+ return res.status(500).json({ success: false, error: result.error });
135
+ } catch (error) {
136
+ next(error);
137
+ }
138
+ }
139
+
140
+ async createConfirm(req, res, next) {
141
+ try {
142
+ const { domain } = req.body ?? {};
143
+ const domainKey = domain?.trim();
144
+ const state = domainKey ? pendingDnsChallenges.get(domainKey) : null;
145
+
146
+ if (!state) {
147
+ return res.status(404).json({
148
+ error: 'no_pending_challenge',
149
+ hint: 'No DNS challenge is pending for this domain. Start a new certificate issuance.',
150
+ });
151
+ }
152
+
153
+ try {
154
+ const records = await dns.resolveTxt(`_acme-challenge.${domainKey}`);
155
+ const flatRecords = records.flat();
156
+
157
+ const found = flatRecords.includes(state.txtValue);
158
+ if (!found) {
159
+ return res.status(400).json({
160
+ error: 'dns_not_propagated',
161
+ hint: 'The expected TXT record value was not found. Make sure you added the correct TXT record and wait a few minutes for DNS propagation.',
162
+ expected: state.txtValue,
163
+ found: flatRecords,
164
+ });
165
+ }
166
+ } catch (err) {
167
+ return res.status(400).json({
168
+ error: 'dns_lookup_failed',
169
+ hint: 'Failed to lookup the expected TXT record. Make sure you added the correct TXT record.',
170
+ detail: err.message,
171
+ });
172
+ }
173
+ // Signal issueCert() to continue with the ACME process
174
+ await state.confirmDeferred.resolve();
175
+
176
+ // Wait for the ACME process to complete
177
+ const result = await state.resultPromise;
178
+ pendingDnsChallenges.delete(domainKey);
179
+
180
+ if (result.success) {
181
+ return res.json({ success: true, certPath: result.certPath, keyPath: result.keyPath });
182
+ }
183
+ return res.status(500).json({ success: false, error: result.error });
184
+ } catch (error) {
185
+ next(error);
186
+ }
187
+ }
188
+
189
+ async createCancel(req, res, next) {
190
+ try {
191
+ const { domain } = req.body ?? {};
192
+ const domainKey = domain?.trim();
193
+ const state = domainKey ? pendingDnsChallenges.get(domainKey) : null;
194
+
195
+ if (!state) {
196
+ return res.status(404).json({
197
+ error: 'no_pending_challenge',
198
+ hint: 'No DNS challenge is pending for this domain.',
199
+ });
200
+ }
201
+
202
+ // Reject the deferred — issueCert() will return a failure result
203
+ state.confirmDeferred.reject(new Error('cancelled by user'));
204
+ pendingDnsChallenges.delete(domainKey);
205
+
206
+ return res.json({ cancelled: true });
207
+ } catch (error) {
208
+ next(error);
209
+ }
210
+ }
211
+
212
+ async list(req, res, next) {
213
+ try {
214
+ const certs = await listAllCerts();
215
+ res.json(certs);
216
+ } catch (error) {
217
+ next(error);
218
+ }
219
+ }
220
+
221
+ async renew(req, res, next) {
222
+ try {
223
+ const domain = req.params.domain;
224
+ const config = loadConfig();
225
+
226
+ if (!config.acmeEmail) {
227
+ return res.status(400).json({
228
+ error: 'email_required',
229
+ hint: 'Configure acmeEmail in settings first.',
230
+ });
231
+ }
232
+
233
+ const certs = await listAllCerts();
234
+ const found = certs.find(cert => cert.domain === domain);
235
+ if (!found) {
236
+ return res.status(404).json({ error: `Domain '${domain}' not found` });
237
+ }
238
+
239
+ const result = await renewCert(domain, { validationMethod: 'http', email: config.acmeEmail });
240
+
241
+ if (result.success) {
242
+ return res.json({ success: true, certPath: result.certPath, keyPath: result.keyPath });
243
+ }
244
+
245
+ const { step } = result.error;
246
+ if (step === 'port 80 check') {
247
+ return res.status(409).json({
248
+ error: 'port_busy',
249
+ detail: result.error.cause,
250
+ hint: 'Stop the process using port 80 and try again.',
251
+ });
252
+ }
253
+ return res.status(500).json({ success: false, error: result.error });
254
+ } catch (error) {
255
+ next(error);
256
+ }
257
+ }
258
+
259
+ async renewAll(req, res, next) {
260
+ try {
261
+ const config = loadConfig();
262
+
263
+ if (!config.acmeEmail) {
264
+ return res.status(400).json({
265
+ error: 'email_required',
266
+ hint: 'Configure acmeEmail in settings first.',
267
+ });
268
+ }
269
+
270
+ const certs = await listAllCerts();
271
+ const expiring = certs.filter(c => c.daysLeft !== null && c.daysLeft < 30);
272
+ const results = [];
273
+
274
+ for (const cert of expiring) {
275
+ const result = await renewCert(cert.domain, { validationMethod: 'http', email: config.acmeEmail });
276
+ results.push({
277
+ domain: cert.domain,
278
+ success: result.success,
279
+ certPath: result.certPath,
280
+ keyPath: result.keyPath,
281
+ });
282
+ }
283
+
284
+ res.json(results);
285
+ } catch (error) {
286
+ next(error);
287
+ }
288
+ }
289
+ }
290
+
291
+ export default SslController;
Binary file
Binary file
@@ -37,6 +37,11 @@ const DEFAULT_FORM = {
37
37
  accessLog: true,
38
38
  customLocations: '',
39
39
  },
40
+ notifications: {
41
+ domain_health: { enabled: true, channelIds: [] },
42
+ cert_expiry: { enabled: true, channelIds: [] },
43
+ nginx_down: { enabled: true, channelIds: [] },
44
+ },
40
45
  };
41
46
 
42
47
  createApp({
@@ -104,6 +109,7 @@ createApp({
104
109
  performance: false,
105
110
  security: false,
106
111
  advanced: false,
112
+ notifications: false,
107
113
  },
108
114
 
109
115
  logs: {
@@ -118,6 +124,7 @@ createApp({
118
124
  password: '', loading: false, msg: '', error: '',
119
125
  platform: 'linux', // T022: Platform from settings API
120
126
  },
127
+ settingsTab: 'general', // 'general' | 'notifications'
121
128
 
122
129
  permissions: {
123
130
  configured: false, loading: false, password: '', msg: '', error: '',
@@ -127,6 +134,20 @@ createApp({
127
134
  restoring: false, msg: '', error: '',
128
135
  },
129
136
 
137
+ channels: {
138
+ list: [],
139
+ loading: false,
140
+ testingId: null,
141
+ testResults: {},
142
+ },
143
+ channelModal: {
144
+ open: false,
145
+ editing: null, // null = add new, string = channel id being edited
146
+ form: { name: '', type: 'discord', webhookUrl: '', botToken: '', chatId: '', message: '' },
147
+ saving: false,
148
+ error: '',
149
+ },
150
+
130
151
  notifications: {
131
152
  items: [], // { id, type, severity, message, domain?, timestamp }
132
153
  panelOpen: false,
@@ -304,7 +325,7 @@ createApp({
304
325
  } else if (p === 'ssl') { await this.loadSSL(); }
305
326
  else if (p === 'domains') { await this.loadDomains(); }
306
327
  else if (p === 'logs') { this.subscribeToLogs(this.logs.activeLog); }
307
- else if (p === 'settings') { await Promise.all([this.loadSettings(), this.loadPermissionsStatus()]); }
328
+ else if (p === 'settings') { await Promise.all([this.loadSettings(), this.loadPermissionsStatus(), this.loadChannels()]); }
308
329
  },
309
330
 
310
331
  // ── Collapsible Sections ────────────────────────────────────────────
@@ -482,7 +503,9 @@ createApp({
482
503
  if (!isConfirmed) return;
483
504
  }
484
505
  this.domains.showForm = !this.domains.showForm;
485
- if (!this.domains.showForm) {
506
+ if (this.domains.showForm) {
507
+ await this.loadChannels();
508
+ } else {
486
509
  this.resetDomainForm();
487
510
  }
488
511
  },
@@ -504,6 +527,7 @@ createApp({
504
527
  performance: false,
505
528
  security: false,
506
529
  advanced: false,
530
+ notifications: false,
507
531
  };
508
532
  },
509
533
 
@@ -521,6 +545,9 @@ createApp({
521
545
  if (!isConfirmed) return;
522
546
  }
523
547
 
548
+ // Ensure channels are loaded for the notifications section
549
+ await this.loadChannels();
550
+
524
551
  // Fetch domain data
525
552
  const r = await this.api('GET', `/api/domains`);
526
553
  if (!r.ok) {
@@ -570,6 +597,11 @@ createApp({
570
597
  accessLog: domain.advanced?.accessLog ?? true,
571
598
  customLocations: domain.advanced?.customLocations || '',
572
599
  },
600
+ notifications: {
601
+ domain_health: domain.notifications?.domain_health ?? { enabled: true, channelIds: [] },
602
+ cert_expiry: domain.notifications?.cert_expiry ?? { enabled: true, channelIds: [] },
603
+ nginx_down: domain.notifications?.nginx_down ?? { enabled: true, channelIds: [] },
604
+ },
573
605
  };
574
606
 
575
607
  this.domains.editingName = name;
@@ -583,6 +615,7 @@ createApp({
583
615
  performance: true,
584
616
  security: true,
585
617
  advanced: true,
618
+ notifications: true,
586
619
  };
587
620
  },
588
621
 
@@ -763,6 +796,13 @@ createApp({
763
796
  if (r.ok) this.permissions.configured = r.data.configured;
764
797
  },
765
798
 
799
+ async loadChannels() {
800
+ this.channels.loading = true;
801
+ const r = await this.api('GET', '/api/settings/channels');
802
+ this.channels.loading = false;
803
+ if (r.ok) this.channels.list = Array.isArray(r.data) ? r.data : [];
804
+ },
805
+
766
806
  async setupPermissions() {
767
807
  this.permissions.loading = true; this.permissions.msg = ''; this.permissions.error = '';
768
808
  const r = await this.api('POST', '/api/settings/permissions/setup', { password: this.permissions.password });
@@ -870,6 +910,72 @@ createApp({
870
910
  if (r.ok) { this.settings.msg = 'Settings saved ✓'; this.settings.password = ''; }
871
911
  else { this.settings.error = r.data.error || 'Save failed'; }
872
912
  },
913
+
914
+ openAddChannel() {
915
+ this.channelModal.editing = null;
916
+ this.channelModal.form = { name: '', type: 'discord', webhookUrl: '', botToken: '', chatId: '', message: '' };
917
+ this.channelModal.error = '';
918
+ this.channelModal.open = true;
919
+ },
920
+
921
+ openEditChannel(channel) {
922
+ this.channelModal.editing = channel.id;
923
+ this.channelModal.form = {
924
+ name: channel.name,
925
+ type: channel.type,
926
+ webhookUrl: channel.webhookUrl || '',
927
+ botToken: channel.botToken || '',
928
+ chatId: channel.chatId || '',
929
+ message: channel.message || '',
930
+ };
931
+ this.channelModal.error = '';
932
+ this.channelModal.open = true;
933
+ },
934
+
935
+ async saveChannel() {
936
+ this.channelModal.saving = true;
937
+ this.channelModal.error = '';
938
+ const { name, type, webhookUrl, botToken, chatId, message } = this.channelModal.form;
939
+ const payload = { name, type, webhookUrl, botToken, chatId, message };
940
+ const r = this.channelModal.editing
941
+ ? await this.api('PUT', `/api/settings/channels/${this.channelModal.editing}`, payload)
942
+ : await this.api('POST', '/api/settings/channels', payload);
943
+ this.channelModal.saving = false;
944
+ if (r.ok) {
945
+ this.channelModal.open = false;
946
+ await this.loadChannels();
947
+ } else {
948
+ this.channelModal.error = r.data.error || 'Save failed';
949
+ }
950
+ },
951
+
952
+ async deleteChannel(id) {
953
+ const { isConfirmed } = await Swal.fire({
954
+ title: 'Delete channel?',
955
+ text: 'This cannot be undone.',
956
+ icon: 'warning',
957
+ showCancelButton: true,
958
+ confirmButtonText: 'Delete',
959
+ cancelButtonText: 'Cancel',
960
+ ...this.swalTheme,
961
+ });
962
+ if (!isConfirmed) return;
963
+ await this.api('DELETE', `/api/settings/channels/${id}`);
964
+ await this.loadChannels();
965
+ },
966
+
967
+ async testChannelById(id) {
968
+ this.channels.testingId = id;
969
+ this.channels.testResults = { ...this.channels.testResults, [id]: { msg: '', error: '' } };
970
+ const r = await this.api('POST', `/api/settings/channels/${id}/test`);
971
+ this.channels.testingId = null;
972
+ this.channels.testResults = {
973
+ ...this.channels.testResults,
974
+ [id]: r.ok
975
+ ? { msg: 'Test sent ✓', error: '' }
976
+ : { msg: '', error: r.data.error || 'Test failed' },
977
+ };
978
+ },
873
979
  },
874
980
  })
875
981
  .directive('click-outside', {
@@ -1,8 +1,9 @@
1
1
  import { Router } from 'express';
2
2
  import rateLimit from 'express-rate-limit';
3
- import { loadConfig } from '../../core/config.js';
3
+ import AuthController from '../controllers/authController.js';
4
4
 
5
5
  const router = Router();
6
+ const controller = new AuthController();
6
7
 
7
8
  const loginLimiter = rateLimit({
8
9
  windowMs: 15 * 60 * 1000, // 15 minutes
@@ -12,28 +13,8 @@ const loginLimiter = rateLimit({
12
13
  message: { ok: false, error: 'Too many login attempts. Try again in 15 minutes.' },
13
14
  });
14
15
 
15
- router.post('/login', loginLimiter, (req, res) => {
16
- const { password } = req.body;
17
- const { dashboardPassword } = loadConfig();
18
- if (password === dashboardPassword) {
19
- req.session.authenticated = true;
20
- res.json({ ok: true });
21
- } else {
22
- res.status(401).json({ ok: false, error: 'Invalid password' });
23
- }
24
- });
25
-
26
- router.get('/auth', (req, res) => {
27
- if (req.session.authenticated === true) {
28
- res.json({ authenticated: true });
29
- } else {
30
- res.json({ authenticated: false });
31
- }
32
- });
33
-
34
- router.post('/logout', (req, res) => {
35
- req.session.destroy();
36
- res.json({ ok: true });
37
- });
16
+ router.post('/login', loginLimiter, (req, res, next) => controller.login(req, res, next));
17
+ router.get('/auth', (req, res, next) => controller.check(req, res, next));
18
+ router.post('/logout', (req, res, next) => controller.logout(req, res, next));
38
19
 
39
20
  export default router;