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.
@@ -1,5 +1,6 @@
1
1
  import express from 'express';
2
2
  import { loadConfig, saveConfig } from '../../core/config.js';
3
+ import { validatePort, validateEmail } from '../../core/validators.js';
3
4
 
4
5
  const router = express.Router();
5
6
 
@@ -9,11 +10,12 @@ router.get('/settings', (req, res) => {
9
10
  try {
10
11
  const config = loadConfig();
11
12
  // Never return the password (write-only field)
12
- const { dashboardPort, nginxDir, certbotDir } = config;
13
+ const { dashboardPort, nginxDir, sslDir, acmeEmail } = config;
13
14
  res.json({
14
15
  dashboardPort,
15
16
  nginxDir,
16
- certbotDir,
17
+ sslDir,
18
+ acmeEmail,
17
19
  platform: process.platform === 'win32' ? 'win32' : 'linux',
18
20
  });
19
21
  } catch (err) {
@@ -25,14 +27,12 @@ router.get('/settings', (req, res) => {
25
27
 
26
28
  router.post('/settings', (req, res) => {
27
29
  try {
28
- const { dashboardPort, dashboardPassword, nginxDir, certbotDir } = req.body;
30
+ const { dashboardPort, dashboardPassword, nginxDir, sslDir, acmeEmail } = req.body;
29
31
 
30
32
  // Validate port if provided
31
33
  if (dashboardPort !== undefined) {
32
- const port = parseInt(dashboardPort, 10);
33
- if (isNaN(port) || port < 1 || port > 65535) {
34
- return res.status(400).json({ error: 'Invalid port number' });
35
- }
34
+ const portError = validatePort(parseInt(dashboardPort, 10));
35
+ if (portError) return res.status(400).json({ error: portError });
36
36
  }
37
37
 
38
38
  // Validate password if provided
@@ -44,9 +44,14 @@ router.post('/settings', (req, res) => {
44
44
  if (nginxDir !== undefined && (typeof nginxDir !== 'string' || nginxDir.trim() === '')) {
45
45
  return res.status(400).json({ error: 'Nginx directory must be a non-empty string' });
46
46
  }
47
+ if (sslDir !== undefined && (typeof sslDir !== 'string' || sslDir.trim() === '')) {
48
+ return res.status(400).json({ error: 'SSL directory must be a non-empty string' });
49
+ }
47
50
 
48
- if (certbotDir !== undefined && (typeof certbotDir !== 'string' || certbotDir.trim() === '')) {
49
- return res.status(400).json({ error: 'Certbot directory must be a non-empty string' });
51
+ // Validate email if provided
52
+ if (acmeEmail !== undefined) {
53
+ const emailError = validateEmail(acmeEmail);
54
+ if (emailError) return res.status(400).json({ error: emailError });
50
55
  }
51
56
 
52
57
  // Load current config and merge updates
@@ -62,8 +67,11 @@ router.post('/settings', (req, res) => {
62
67
  if (nginxDir !== undefined) {
63
68
  updates.nginxDir = nginxDir.trim();
64
69
  }
65
- if (certbotDir !== undefined) {
66
- updates.certbotDir = certbotDir.trim();
70
+ if (sslDir !== undefined) {
71
+ updates.sslDir = sslDir.trim();
72
+ }
73
+ if (acmeEmail !== undefined) {
74
+ updates.acmeEmail = acmeEmail.trim();
67
75
  }
68
76
 
69
77
  const newConfig = { ...currentConfig, ...updates };
@@ -1,74 +1,131 @@
1
1
  import express from 'express';
2
- import { run } from '../../core/shell.js';
3
2
  import { listAllCerts } from '../lib/cert-reader.js';
4
- import { issueCert } from '../../cli/managers/ssl-manager.js';
3
+ import { issueCert, renewCert } from '../../cli/managers/ssl-manager.js';
4
+ import { loadConfig } from '../../core/config.js';
5
+ import { promises as dns } from 'dns';
5
6
 
6
7
  const router = express.Router();
7
8
 
8
- const CERTBOT_WIN_EXE = 'C:\\Program Files\\Certbot\\bin\\certbot.exe';
9
+ // ─── In-memory DNS challenge state ────────────────────────────────────────────
10
+ // Keyed by domain name. Entries are cleaned up when the ACME process exits
11
+ // or when cancelled. Entries older than 10 minutes are forcibly removed.
9
12
 
10
- // Returns the PS-safe certbot invocation string, or null if not installed.
11
- async function getCertbotCmd() {
12
- if (process.platform !== 'win32') {
13
- const r = await run('certbot --version', { timeout: 10000 });
14
- return r.success ? 'certbot' : null;
15
- }
16
-
17
- // Try PATH first
18
- const whereResult = await run('where.exe certbot', { timeout: 5000 });
19
- if (whereResult.success && whereResult.stdout.trim()) return 'certbot';
20
-
21
- // Check known Windows install location
22
- const testResult = await run(`Test-Path "${CERTBOT_WIN_EXE}"`, { timeout: 5000 });
23
- if (testResult.stdout.trim() === 'True') return `& "${CERTBOT_WIN_EXE}"`;
13
+ const pendingDnsChallenges = new Map();
24
14
 
25
- return null;
26
- }
27
-
28
- async function renewDomain(domain, certbotCmd) {
29
- if (process.platform === 'win32') {
30
- const certResult = await run(
31
- `${certbotCmd} certonly --standalone --non-interactive --agree-tos -d ${domain}`,
32
- { timeout: 120000 }
33
- );
34
- const output = [certResult.stdout, certResult.stderr].filter(Boolean).join('\n').trim();
35
- return { success: certResult.success, output };
15
+ setInterval(() => {
16
+ const now = Date.now();
17
+ for (const [domain, state] of pendingDnsChallenges) {
18
+ if (now - state.createdAt > 10 * 60 * 1000) {
19
+ state.confirmDeferred.reject(new Error('DNS challenge timed out after 10 minutes'));
20
+ pendingDnsChallenges.delete(domain);
21
+ }
36
22
  }
37
-
38
- await run('systemctl stop nginx', { timeout: 15000 });
39
- let certResult;
40
- try {
41
- certResult = await run(
42
- `${certbotCmd} certonly --standalone --non-interactive --agree-tos -d ${domain}`,
43
- { timeout: 120000 }
44
- );
45
- } finally {
46
- await run('systemctl start nginx', { timeout: 15000 });
47
- }
48
- const output = [certResult.stdout, certResult.stderr].filter(Boolean).join('\n').trim();
49
- return { success: certResult.success, output };
50
- }
23
+ }, 60000);
51
24
 
52
25
  // ─── POST /api/ssl/create ─────────────────────────────────────────────────────
53
26
 
54
27
  router.post('/create', async (req, res) => {
55
- const { domain, www = false } = req.body ?? {};
28
+ const { domain, www = false, validationMethod = 'http', email = null } = req.body ?? {};
56
29
 
57
30
  if (!domain || typeof domain !== 'string' || !domain.trim()) {
58
31
  return res.status(400).json({ error: 'domain is required' });
59
32
  }
60
33
 
61
- const result = await issueCert(domain.trim(), { www: !!www });
34
+ const domainKey = domain.trim();
35
+ const config = loadConfig();
36
+ const acmeEmail = email || config.acmeEmail;
37
+
38
+ if (validationMethod === 'dns') {
39
+ // Two-phase flow: spawn ACME process, wait for TXT record, respond 202, pause until confirm.
40
+ let confirmResolve, confirmReject;
41
+ const confirmPromise = new Promise((resolve, reject) => {
42
+ confirmResolve = resolve;
43
+ confirmReject = reject;
44
+ });
45
+
46
+ let resultResolve;
47
+ const resultPromise = new Promise((resolve) => { resultResolve = resolve; });
48
+
49
+ // Track whether a response has already been sent (202 from onDnsChallenge)
50
+ let responseSent = false;
51
+
52
+ const onDnsChallenge = async (txtName, txtValue) => {
53
+ responseSent = true;
54
+ pendingDnsChallenges.set(domainKey, {
55
+ domain: domainKey,
56
+ txtName,
57
+ txtValue,
58
+ confirmDeferred: { resolve: confirmResolve, reject: confirmReject },
59
+ resultPromise,
60
+ createdAt: Date.now(),
61
+ });
62
+
63
+ res.status(202).json({
64
+ status: 'waiting_dns',
65
+ domain: domainKey,
66
+ txtName,
67
+ txtValue,
68
+ hint: 'Add a DNS TXT record with the name and value above, then call POST /api/ssl/create-confirm',
69
+ });
70
+
71
+ // Pause until user calls /create-confirm (resolves) or /create-cancel (rejects)
72
+ await confirmPromise;
73
+ };
74
+
75
+ // Run issueCert in the background — it will call onDnsChallenge which sends 202 and pauses.
76
+ issueCert(domainKey, { www: !!www, validationMethod: 'dns', email: acmeEmail, onDnsChallenge })
77
+ .then(result => {
78
+ resultResolve(result);
79
+ pendingDnsChallenges.delete(domainKey);
80
+ if (!responseSent) {
81
+ responseSent = true;
82
+ if (result.success) {
83
+ return res.json({ success: true, certPath: result.certPath, keyPath: result.keyPath });
84
+ }
85
+ const { step } = result.error ?? {};
86
+ if (step === 'email configuration') {
87
+ return res.status(400).json({ error: 'email_required', hint: 'Configure acmeEmail in settings or provide email parameter.' });
88
+ }
89
+ return res.status(500).json({ success: false, error: result.error });
90
+ }
91
+ })
92
+ .catch(err => {
93
+ const errResult = {
94
+ success: false,
95
+ certPath: null,
96
+ keyPath: null,
97
+ error: {
98
+ step: 'certificate issuance',
99
+ cause: err.message,
100
+ consequence: 'Unexpected error during DNS certificate issuance.',
101
+ nginxRunning: true,
102
+ configSaved: false,
103
+ },
104
+ };
105
+ resultResolve(errResult);
106
+ pendingDnsChallenges.delete(domainKey);
107
+ if (!responseSent) {
108
+ responseSent = true;
109
+ return res.status(500).json({ success: false, error: errResult.error });
110
+ }
111
+ });
112
+
113
+ // The response is sent either by onDnsChallenge (202) or by the .then()/.catch() above.
114
+ return;
115
+ }
116
+
117
+ // HTTP validation path (synchronous — responds when complete)
118
+ const result = await issueCert(domainKey, { www: !!www, validationMethod: 'http', email: acmeEmail });
62
119
 
63
120
  if (result.success) {
64
121
  return res.json({ success: true, certPath: result.certPath, keyPath: result.keyPath });
65
122
  }
66
123
 
67
124
  const { step } = result.error;
68
- if (step === 'ACME client detection') {
69
- return res.status(503).json({
70
- error: 'no_acme_client',
71
- hint: 'Install certbot or win-acme first using the SSL Manager.',
125
+ if (step === 'email configuration') {
126
+ return res.status(400).json({
127
+ error: 'email_required',
128
+ hint: 'Configure acmeEmail in settings or provide email parameter.',
72
129
  });
73
130
  }
74
131
  if (step === 'port 80 check') {
@@ -81,59 +138,143 @@ router.post('/create', async (req, res) => {
81
138
  return res.status(500).json({ success: false, error: result.error });
82
139
  });
83
140
 
84
- // ─── GET /api/ssl ─────────────────────────────────────────────────────────────
141
+ // ─── POST /api/ssl/create-confirm ────────────────────────────────────────────
85
142
 
86
- router.get('/', async (req, res) => {
87
- const certbotCmd = await getCertbotCmd();
88
- if (!certbotCmd) {
89
- return res.status(503).json({
90
- error: 'certbot not installed',
91
- instructions: 'Install certbot: https://certbot.eff.org/instructions',
143
+ router.post('/create-confirm', async (req, res) => {
144
+ const { domain } = req.body ?? {};
145
+ const domainKey = domain?.trim();
146
+ const state = domainKey ? pendingDnsChallenges.get(domainKey) : null;
147
+
148
+ if (!state) {
149
+ return res.status(404).json({
150
+ error: 'no_pending_challenge',
151
+ hint: 'No DNS challenge is pending for this domain. Start a new certificate issuance.',
152
+ });
153
+ }
154
+
155
+ try {
156
+ const records = await dns.resolveTxt(`_acme-challenge.${domainKey}`);
157
+ const flatRecords = records.flat();
158
+
159
+ const found = flatRecords.includes(state.txtValue);
160
+ if (!found) {
161
+ return res.status(400).json({
162
+ error: 'dns_not_propagated',
163
+ 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.',
164
+ expected: state.txtValue,
165
+ found: flatRecords,
166
+ });
167
+ }
168
+ } catch (err) {
169
+ return res.status(400).json({
170
+ error: 'dns_lookup_failed',
171
+ hint: 'Failed to lookup the expected TXT record. Make sure you added the correct TXT record.',
172
+ detail: err.message,
173
+ });
174
+ }
175
+ // Signal issueCert() to continue with the ACME process
176
+ await state.confirmDeferred.resolve();
177
+
178
+ // Wait for the ACME process to complete
179
+ const result = await state.resultPromise;
180
+ pendingDnsChallenges.delete(domainKey);
181
+
182
+ if (result.success) {
183
+ return res.json({ success: true, certPath: result.certPath, keyPath: result.keyPath });
184
+ }
185
+ return res.status(500).json({ success: false, error: result.error });
186
+ });
187
+
188
+ // ─── POST /api/ssl/create-cancel ─────────────────────────────────────────────
189
+
190
+ router.post('/create-cancel', async (req, res) => {
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.',
92
199
  });
93
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
+ });
208
+
209
+ // ─── GET /api/ssl ─────────────────────────────────────────────────────────────
210
+
211
+ router.get('/', async (req, res) => {
94
212
  const certs = await listAllCerts();
95
213
  res.json(certs);
96
214
  });
97
215
 
216
+ // ─── POST /api/ssl/renew/:domain ─────────────────────────────────────────────
217
+
98
218
  router.post('/renew/:domain', async (req, res) => {
99
- const certbotCmd = await getCertbotCmd();
100
- if (!certbotCmd) {
101
- return res.status(503).json({
102
- error: 'certbot not installed',
103
- instructions: 'Install certbot: https://certbot.eff.org/instructions',
219
+ const domain = req.params.domain;
220
+ const config = loadConfig();
221
+
222
+ if (!config.acmeEmail) {
223
+ return res.status(400).json({
224
+ error: 'email_required',
225
+ hint: 'Configure acmeEmail in settings first.',
104
226
  });
105
227
  }
106
- const domain = req.params.domain;
228
+
107
229
  const certs = await listAllCerts();
108
230
  const found = certs.find(cert => cert.domain === domain);
109
231
  if (!found) {
110
- return res.status(404).json({ error: `Domain '${domain}' not found in certbot` });
232
+ return res.status(404).json({ error: `Domain '${domain}' not found` });
233
+ }
234
+
235
+ const result = await renewCert(domain, { validationMethod: 'http', email: config.acmeEmail });
236
+
237
+ if (result.success) {
238
+ return res.json({ success: true, certPath: result.certPath, keyPath: result.keyPath });
111
239
  }
112
- const result = await renewDomain(domain, certbotCmd);
113
- if (result.output.includes('binding to port 80') || result.output.includes('Address already in use')) {
240
+
241
+ const { step } = result.error;
242
+ if (step === 'port 80 check') {
114
243
  return res.status(409).json({
115
- error: 'Port 80 is busy',
116
- message: 'stop nginx first or use --webroot',
244
+ error: 'port_busy',
245
+ detail: result.error.cause,
246
+ hint: 'Stop the process using port 80 and try again.',
117
247
  });
118
248
  }
119
- res.json({ success: result.success, output: result.output });
249
+ return res.status(500).json({ success: false, error: result.error });
120
250
  });
121
251
 
252
+ // ─── POST /api/ssl/renew-all ─────────────────────────────────────────────────
253
+
122
254
  router.post('/renew-all', async (req, res) => {
123
- const certbotCmd = await getCertbotCmd();
124
- if (!certbotCmd) {
125
- return res.status(503).json({
126
- error: 'certbot not installed',
127
- instructions: 'Install certbot: https://certbot.eff.org/instructions',
255
+ const config = loadConfig();
256
+
257
+ if (!config.acmeEmail) {
258
+ return res.status(400).json({
259
+ error: 'email_required',
260
+ hint: 'Configure acmeEmail in settings first.',
128
261
  });
129
262
  }
263
+
130
264
  const certs = await listAllCerts();
131
265
  const expiring = certs.filter(c => c.daysLeft !== null && c.daysLeft < 30);
132
266
  const results = [];
267
+
133
268
  for (const cert of expiring) {
134
- const r = await renewDomain(cert.domain, certbotCmd);
135
- results.push({ domain: cert.domain, success: r.success, output: r.output });
269
+ const result = await renewCert(cert.domain, { validationMethod: 'http', email: config.acmeEmail });
270
+ results.push({
271
+ domain: cert.domain,
272
+ success: result.success,
273
+ certPath: result.certPath,
274
+ keyPath: result.keyPath,
275
+ });
136
276
  }
277
+
137
278
  res.json(results);
138
279
  });
139
280