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.
@@ -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,104 +1,280 @@
1
1
  import express from 'express';
2
- import { run } from '../../core/shell.js';
3
2
  import { listAllCerts } from '../lib/cert-reader.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';
4
6
 
5
7
  const router = express.Router();
6
8
 
7
- 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.
8
12
 
9
- // Returns the PS-safe certbot invocation string, or null if not installed.
10
- async function getCertbotCmd() {
11
- if (process.platform !== 'win32') {
12
- const r = await run('certbot --version', { timeout: 10000 });
13
- return r.success ? 'certbot' : null;
13
+ const pendingDnsChallenges = new Map();
14
+
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
+ }
22
+ }
23
+ }, 60000);
24
+
25
+ // ─── POST /api/ssl/create ─────────────────────────────────────────────────────
26
+
27
+ router.post('/create', async (req, res) => {
28
+ const { domain, www = false, validationMethod = 'http', email = null } = req.body ?? {};
29
+
30
+ if (!domain || typeof domain !== 'string' || !domain.trim()) {
31
+ return res.status(400).json({ error: 'domain is required' });
32
+ }
33
+
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;
14
115
  }
15
116
 
16
- // Try PATH first
17
- const whereResult = await run('where.exe certbot', { timeout: 5000 });
18
- if (whereResult.success && whereResult.stdout.trim()) return 'certbot';
117
+ // HTTP validation path (synchronous — responds when complete)
118
+ const result = await issueCert(domainKey, { www: !!www, validationMethod: 'http', email: acmeEmail });
119
+
120
+ if (result.success) {
121
+ return res.json({ success: true, certPath: result.certPath, keyPath: result.keyPath });
122
+ }
123
+
124
+ const { step } = result.error;
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.',
129
+ });
130
+ }
131
+ if (step === 'port 80 check') {
132
+ return res.status(409).json({
133
+ error: 'port_busy',
134
+ detail: result.error.cause,
135
+ hint: 'Stop the process using port 80 and try again.',
136
+ });
137
+ }
138
+ return res.status(500).json({ success: false, error: result.error });
139
+ });
19
140
 
20
- // Check known Windows install location
21
- const testResult = await run(`Test-Path "${CERTBOT_WIN_EXE}"`, { timeout: 5000 });
22
- if (testResult.stdout.trim() === 'True') return `& "${CERTBOT_WIN_EXE}"`;
141
+ // ─── POST /api/ssl/create-confirm ────────────────────────────────────────────
23
142
 
24
- return null;
25
- }
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;
26
147
 
27
- async function renewDomain(domain, certbotCmd) {
28
- if (process.platform === 'win32') {
29
- const certResult = await run(
30
- `${certbotCmd} certonly --standalone --non-interactive --agree-tos -d ${domain}`,
31
- { timeout: 120000 }
32
- );
33
- const output = [certResult.stdout, certResult.stderr].filter(Boolean).join('\n').trim();
34
- return { success: certResult.success, output };
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
+ });
35
153
  }
36
154
 
37
- await run('systemctl stop nginx', { timeout: 15000 });
38
- let certResult;
39
155
  try {
40
- certResult = await run(
41
- `${certbotCmd} certonly --standalone --non-interactive --agree-tos -d ${domain}`,
42
- { timeout: 120000 }
43
- );
44
- } finally {
45
- await run('systemctl start nginx', { timeout: 15000 });
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
+ });
46
174
  }
47
- const output = [certResult.stdout, certResult.stderr].filter(Boolean).join('\n').trim();
48
- return { success: certResult.success, output };
49
- }
175
+ // Signal issueCert() to continue with the ACME process
176
+ await state.confirmDeferred.resolve();
50
177
 
51
- router.get('/', async (req, res) => {
52
- const certbotCmd = await getCertbotCmd();
53
- if (!certbotCmd) {
54
- return res.status(503).json({
55
- error: 'certbot not installed',
56
- instructions: 'Install certbot: https://certbot.eff.org/instructions',
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.',
57
199
  });
58
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) => {
59
212
  const certs = await listAllCerts();
60
213
  res.json(certs);
61
214
  });
62
215
 
216
+ // ─── POST /api/ssl/renew/:domain ─────────────────────────────────────────────
217
+
63
218
  router.post('/renew/:domain', async (req, res) => {
64
- const certbotCmd = await getCertbotCmd();
65
- if (!certbotCmd) {
66
- return res.status(503).json({
67
- error: 'certbot not installed',
68
- 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.',
69
226
  });
70
227
  }
71
- const domain = req.params.domain;
228
+
72
229
  const certs = await listAllCerts();
73
230
  const found = certs.find(cert => cert.domain === domain);
74
231
  if (!found) {
75
- 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 });
76
239
  }
77
- const result = await renewDomain(domain, certbotCmd);
78
- 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') {
79
243
  return res.status(409).json({
80
- error: 'Port 80 is busy',
81
- 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.',
82
247
  });
83
248
  }
84
- res.json({ success: result.success, output: result.output });
249
+ return res.status(500).json({ success: false, error: result.error });
85
250
  });
86
251
 
252
+ // ─── POST /api/ssl/renew-all ─────────────────────────────────────────────────
253
+
87
254
  router.post('/renew-all', async (req, res) => {
88
- const certbotCmd = await getCertbotCmd();
89
- if (!certbotCmd) {
90
- return res.status(503).json({
91
- error: 'certbot not installed',
92
- 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.',
93
261
  });
94
262
  }
263
+
95
264
  const certs = await listAllCerts();
96
265
  const expiring = certs.filter(c => c.daysLeft !== null && c.daysLeft < 30);
97
266
  const results = [];
267
+
98
268
  for (const cert of expiring) {
99
- const r = await renewDomain(cert.domain, certbotCmd);
100
- 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
+ });
101
276
  }
277
+
102
278
  res.json(results);
103
279
  });
104
280