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,13 +1,14 @@
1
1
  /**
2
2
  * cli/managers/ssl-manager.js
3
3
  *
4
- * SSL Manager — view certificate status, renew certificates, install certbot/win-acme.
4
+ * SSL Manager — view certificate status, issue and renew certificates using acme-client.
5
5
  *
6
6
  * Exported functions:
7
7
  * - showSslManager() — interactive menu for managing SSL certificates
8
+ * - issueCert() — issue new certificate via Let's Encrypt (HTTP-01 or DNS-01)
9
+ * - renewCert() — renew an existing certificate
8
10
  *
9
- * All shell calls go through core/shell.js (run / runLive).
10
- * Platform differences (Windows/Linux) are handled via isWindows guards.
11
+ * Pure Node.js implementation — no external ACME binaries required.
11
12
  */
12
13
 
13
14
  import chalk from 'chalk';
@@ -15,20 +16,76 @@ import inquirer from 'inquirer';
15
16
  import ora from 'ora';
16
17
  import fs from 'fs/promises';
17
18
  import path from 'path';
18
- import { fileURLToPath } from 'url';
19
+ import http from 'http';
20
+ import net from 'net';
21
+ import * as acme from 'acme-client';
19
22
  import { run, runLive } from '../../core/shell.js';
20
23
  import { loadConfig } from '../../core/config.js';
24
+ import { isWindows } from '../../core/platform.js';
21
25
 
22
- const isWindows = process.platform === 'win32';
26
+ // ─── Helpers ──────────────────────────────────────────────────────────────────
23
27
 
24
- // ─── getCertbotDir ────────────────────────────────────────────────────────────
28
+ function getSslDir() {
29
+ const { sslDir } = loadConfig();
30
+ return sslDir;
31
+ }
25
32
 
26
- function getCertbotDir() {
27
- const config = loadConfig();
28
- return path.join(config.certbotDir, 'live');
33
+ /**
34
+ * Loads or generates the ACME account private key.
35
+ * The key is persisted at {sslDir}/.account/account.key
36
+ */
37
+ async function getAccountKey(sslDir) {
38
+ const keyPath = path.join(sslDir, '.account', 'account.key');
39
+ await fs.mkdir(path.dirname(keyPath), { recursive: true });
40
+ try {
41
+ return await fs.readFile(keyPath);
42
+ } catch {
43
+ const key = await acme.crypto.createPrivateKey();
44
+ await fs.writeFile(keyPath, key);
45
+ return key;
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Checks if port 80 is free (can be bound).
51
+ * Used for HTTP-01 challenge validation.
52
+ */
53
+ async function isPort80Free() {
54
+ return new Promise((resolve) => {
55
+ const srv = net.createServer();
56
+ srv.listen(80, () => {
57
+ srv.close(() => resolve(true));
58
+ });
59
+ srv.on('error', () => resolve(false));
60
+ });
61
+ }
62
+
63
+ /**
64
+ * Stops nginx to free port 80 for HTTP-01 challenge.
65
+ */
66
+ async function stopNginx() {
67
+ const cmd = isWindows
68
+ ? 'taskkill /f /IM nginx.exe'
69
+ : 'systemctl stop nginx';
70
+ await run(cmd);
71
+ }
72
+
73
+ /**
74
+ * Starts nginx after HTTP-01 challenge completes.
75
+ */
76
+ async function startNginx() {
77
+ const { nginxDir } = loadConfig();
78
+ const cmd = isWindows
79
+ ? `& "${nginxDir}\\nginx.exe"`
80
+ : 'systemctl start nginx';
81
+ await run(cmd);
29
82
  }
30
83
 
31
- // ─── parseCertExpiry ──────────────────────────────────────────────────────────
84
+ // ─── Certificate Listing ──────────────────────────────────────────────────────
85
+
86
+ function getLiveDir() {
87
+ return getSslDir();
88
+ }
32
89
 
33
90
  async function parseCertExpiry(certPath) {
34
91
  const result = await run(`openssl x509 -enddate -noout -in "${certPath}"`);
@@ -53,87 +110,6 @@ async function parseCertExpiry(certPath) {
53
110
  }
54
111
  }
55
112
 
56
- // ─── ACME Client Detection ────────────────────────────────────────────────────
57
- // Supports both certbot and win-acme on Windows
58
-
59
- const CERTBOT_WIN_EXE = 'C:\\Program Files\\Certbot\\bin\\certbot.exe';
60
- const WINACME_EXE = 'C:\\Program Files\\win-acme\\wacs.exe';
61
-
62
- async function getCertbotExe() {
63
- if (!isWindows) {
64
- const r = await run('which certbot');
65
- return (r.exitCode === 0 && r.stdout.trim()) ? 'certbot' : null;
66
- }
67
-
68
- // 1. certbot on PATH?
69
- const pathResult = await run('where.exe certbot');
70
- if (pathResult.exitCode === 0 && pathResult.stdout.trim()) {
71
- return 'certbot';
72
- }
73
-
74
- // 2. certbot well-known location
75
- const exeCheck = await run(`Test-Path "${CERTBOT_WIN_EXE}"`);
76
- if (exeCheck.stdout.trim().toLowerCase() === 'true') {
77
- return `& "${CERTBOT_WIN_EXE}"`;
78
- }
79
-
80
- // 3. win-acme on PATH?
81
- const wacsPathResult = await run('where.exe wacs');
82
- if (wacsPathResult.exitCode === 0 && wacsPathResult.stdout.trim()) {
83
- return 'wacs';
84
- }
85
-
86
- // 4. win-acme well-known location
87
- const wacsCheck = await run(`Test-Path "${WINACME_EXE}"`);
88
- if (wacsCheck.stdout.trim().toLowerCase() === 'true') {
89
- return `& "${WINACME_EXE}"`;
90
- }
91
-
92
- return null;
93
- }
94
-
95
- async function isCertbotInstalled() {
96
- return (await getCertbotExe()) !== null;
97
- }
98
-
99
- async function getAcmeClientType() {
100
- const exe = await getCertbotExe();
101
- if (!exe) return null;
102
- if (exe.includes('wacs')) return 'winacme';
103
- return 'certbot';
104
- }
105
-
106
- // ─── isPort80Busy ─────────────────────────────────────────────────────────────
107
-
108
- async function isPort80Busy() {
109
- const cmd = isWindows
110
- ? 'netstat -ano | findstr ":80"'
111
- : "ss -tlnp | grep ':80 '";
112
- const result = await run(cmd);
113
- const busy = result.success && result.stdout.length > 0;
114
- return { busy, detail: busy ? result.stdout.split('\n')[0].trim() : null };
115
- }
116
-
117
- // ─── stopNginx / startNginx ───────────────────────────────────────────────────
118
-
119
- async function stopNginx() {
120
- const { nginxDir } = loadConfig();
121
- const cmd = isWindows
122
- ? 'taskkill /f /IM nginx.exe'
123
- : 'systemctl stop nginx';
124
- await run(cmd);
125
- }
126
-
127
- async function startNginx() {
128
- const { nginxDir } = loadConfig();
129
- const cmd = isWindows
130
- ? `& "${nginxDir}\\nginx.exe"`
131
- : 'systemctl start nginx';
132
- await run(cmd);
133
- }
134
-
135
- // ─── listCerts ────────────────────────────────────────────────────────────────
136
-
137
113
  async function listCerts(liveDir) {
138
114
  let entries;
139
115
  try {
@@ -146,7 +122,10 @@ async function listCerts(liveDir) {
146
122
  const certs = [];
147
123
 
148
124
  for (const domain of domains) {
149
- const certPath = path.join(liveDir, domain, 'cert.pem');
125
+ // Skip hidden directories like .account
126
+ if (domain.startsWith('.')) continue;
127
+
128
+ const certPath = path.join(liveDir, domain, 'fullchain.pem');
150
129
 
151
130
  let status = 'error';
152
131
  let expiryDate = null;
@@ -176,8 +155,6 @@ async function listCerts(liveDir) {
176
155
  return certs;
177
156
  }
178
157
 
179
- // ─── renderCertRow ────────────────────────────────────────────────────────────
180
-
181
158
  function renderCertRow(cert) {
182
159
  const domainPadded = cert.domain.padEnd(35);
183
160
 
@@ -200,491 +177,294 @@ function renderCertRow(cert) {
200
177
  }
201
178
  }
202
179
 
203
- // ─── renewCert ────────────────────────────────────────────────────────────────
204
-
205
- async function renewCert(domain) {
206
- const certbotExe = await getCertbotExe();
207
- if (!certbotExe) {
208
- console.log(chalk.red('\n certbot/win-acme not found — install it first\n'));
209
- return { domain, success: false, exitCode: null };
210
- }
211
-
212
- const clientType = await getAcmeClientType();
213
-
214
- await stopNginx();
215
-
216
- try {
217
- const portCheck = await isPort80Busy();
218
- if (portCheck.busy) {
219
- console.log(chalk.yellow(`\n ⚠ Port 80 is in use: ${portCheck.detail}`));
220
- console.log(chalk.yellow(' Stop that process before renewing.\n'));
221
- return { domain, success: false, exitCode: null };
222
- }
223
-
224
- let cmd;
225
- if (clientType === 'winacme') {
226
- // win-acme interactive mode - needs manual input
227
- console.log(chalk.cyan('\n win-acme will open. Follow the prompts to renew the certificate.'));
228
- console.log(chalk.cyan(' Select: N) Create new certificate → 2) Manual input → enter domain\n'));
229
- cmd = certbotExe;
230
- } else {
231
- cmd = `${certbotExe} certonly --standalone -d "${domain}"`;
232
- }
180
+ // ─── Certificate Issuance ─────────────────────────────────────────────────────
233
181
 
234
- const exitCode = await runLive(cmd, { timeout: 120000 });
235
- return { domain, success: exitCode === 0, exitCode };
236
- } finally {
237
- await startNginx();
238
- }
239
- }
240
-
241
- // ─── renewExpiring ────────────────────────────────────────────────────────────
242
-
243
- async function renewExpiring(certs) {
244
- const expiring = certs.filter(c => c.daysLeft !== null && c.daysLeft < 30);
245
- if (expiring.length === 0) return [];
246
-
247
- const certbotExe = await getCertbotExe();
248
- if (!certbotExe) return [];
249
-
250
- const clientType = await getAcmeClientType();
251
-
252
- await stopNginx();
253
-
254
- const results = [];
255
- try {
256
- for (const cert of expiring) {
257
- let cmd;
258
- if (clientType === 'winacme') {
259
- console.log(chalk.cyan(`\n Renewing ${cert.domain} with win-acme - follow the prompts\n`));
260
- cmd = certbotExe;
261
- } else {
262
- cmd = `${certbotExe} certonly --standalone -d "${cert.domain}"`;
263
- }
264
- const exitCode = await runLive(cmd, { timeout: 120000 });
265
- results.push({ domain: cert.domain, success: exitCode === 0, exitCode });
266
- }
267
- } finally {
268
- await startNginx();
269
- }
270
-
271
- return results;
272
- }
273
-
274
- // ─── installCertbot ───────────────────────────────────────────────────────────
182
+ /**
183
+ * Issues a new SSL certificate using Let's Encrypt (acme-client).
184
+ *
185
+ * HTTP-01: stops nginx, starts temp HTTP server on port 80, validates, restarts nginx.
186
+ * DNS-01: no nginx interaction; caller handles TXT record via onDnsChallenge callback.
187
+ *
188
+ * @param {string} domainName - The primary domain name
189
+ * @param {{
190
+ * www?: boolean,
191
+ * validationMethod?: 'http' | 'dns',
192
+ * email?: string | null,
193
+ * onDnsChallenge?: (txtName: string, txtValue: string) => Promise<void>
194
+ * }} options
195
+ * @returns {Promise<{ success: boolean, certPath: string|null, keyPath: string|null, error: object|null }>}
196
+ */
197
+ export async function issueCert(domainName, {
198
+ www = false,
199
+ wildcard = false,
200
+ validationMethod = 'http',
201
+ email = null,
202
+ onDnsChallenge = null,
203
+ } = {}) {
204
+ const sslDir = getSslDir();
205
+ const config = loadConfig();
275
206
 
276
- async function installCertbot() {
277
- if (!isWindows) {
278
- const exitCode = await runLive('sudo apt-get install -y certbot', { timeout: 180000 });
279
- return { success: exitCode === 0 };
207
+ // Email is required for Let's Encrypt
208
+ const acmeEmail = email || config.acmeEmail;
209
+ if (!acmeEmail) {
210
+ return {
211
+ success: false,
212
+ certPath: null,
213
+ keyPath: null,
214
+ error: {
215
+ step: 'email configuration',
216
+ cause: 'No email address configured. Let\'s Encrypt requires an email for account creation.',
217
+ consequence: 'No certificate was issued. Configure acmeEmail in settings or provide email parameter.',
218
+ nginxRunning: true,
219
+ configSaved: false,
220
+ },
221
+ };
280
222
  }
281
223
 
282
- // ── Shared helpers ────────────────────────────────────────────────────────────
283
-
284
- async function verifyCertbot() {
285
- const whereResult = await run('where.exe certbot 2>$null');
286
- if (whereResult.success && whereResult.stdout.trim()) return true;
287
- const paths = [
288
- CERTBOT_WIN_EXE,
289
- 'C:\\Program Files (x86)\\Certbot\\bin\\certbot.exe',
290
- 'C:\\Certbot\\bin\\certbot.exe',
291
- ];
292
- for (const p of paths) {
293
- const r = await run(`Test-Path '${p}'`);
294
- if (r.stdout.trim().toLowerCase() === 'true') return true;
295
- }
296
- return false;
224
+ // Ensure certificate directory exists
225
+ const certDir = path.join(sslDir, domainName);
226
+ await fs.mkdir(certDir, { recursive: true });
227
+
228
+ // Load or create account key
229
+ const accountKey = await getAccountKey(sslDir);
230
+
231
+ // Create ACME client (Let's Encrypt production)
232
+ const client = new acme.Client({
233
+ directoryUrl: acme.directory.letsencrypt.production,
234
+ accountKey,
235
+ });
236
+
237
+ // Wildcard requires DNS-01 — enforce it here
238
+ if (wildcard && validationMethod === 'http') {
239
+ return {
240
+ success: false,
241
+ certPath: null,
242
+ keyPath: null,
243
+ error: {
244
+ step: 'validation method',
245
+ cause: 'Wildcard certificates require DNS-01 validation, not HTTP-01.',
246
+ consequence: 'No certificate was issued. Change validation method to DNS.',
247
+ nginxRunning: true,
248
+ configSaved: false,
249
+ },
250
+ };
297
251
  }
298
252
 
299
- async function verifyWinAcme() {
300
- const paths = [
301
- WINACME_EXE,
302
- 'C:\\Program Files (x86)\\win-acme\\wacs.exe',
303
- 'C:\\win-acme\\wacs.exe',
304
- ];
305
- for (const p of paths) {
306
- const r = await run(`Test-Path '${p}'`);
307
- if (r.stdout.trim().toLowerCase() === 'true') return true;
253
+ // altNames: wildcard includes both bare domain and *.domain
254
+ const altNames = wildcard
255
+ ? [domainName, `*.${domainName}`]
256
+ : (www ? [domainName, `www.${domainName}`] : [domainName]);
257
+ const [domainKey, csr] = await acme.crypto.createCsr({
258
+ commonName: domainName,
259
+ altNames,
260
+ });
261
+
262
+ // ─── HTTP-01 Challenge ─────────────────────────────────────────────────────
263
+ if (validationMethod === 'http') {
264
+ // Stop nginx to free port 80
265
+ await stopNginx();
266
+
267
+ // Check port 80 is free
268
+ const portFree = await isPort80Free();
269
+ if (!portFree) {
270
+ await startNginx();
271
+ return {
272
+ success: false,
273
+ certPath: null,
274
+ keyPath: null,
275
+ error: {
276
+ step: 'port 80 check',
277
+ cause: 'Port 80 is still in use after stopping nginx. Another process may be binding it.',
278
+ consequence: 'No certificate was issued. nginx has been restarted.',
279
+ nginxRunning: true,
280
+ configSaved: false,
281
+ },
282
+ };
308
283
  }
309
- const whereResult = await run('where.exe wacs 2>$null');
310
- return whereResult.success && whereResult.stdout.trim();
311
- }
312
284
 
313
- const hasCurl = (await run('where.exe curl.exe 2>$null')).success;
314
- let lastDownloadError = '';
285
+ // Create temporary HTTP server for challenge
286
+ const challengeTokens = new Map();
287
+ let httpServer;
315
288
 
316
- async function downloadFile(url, dest, showErrors = false) {
317
- const safeUrl = url.replace(/'/g, "''");
318
- const safeDest = dest.replace(/'/g, "''");
319
-
320
- // Enable all TLS versions (1.0, 1.1, 1.2, 1.3) for maximum compatibility
321
- const tlsSetup = `[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls13`;
322
-
323
- // Helper to safely run a command and catch EPERM errors
324
- const safeRun = async (cmd, opts) => {
325
- try {
326
- return await run(cmd, opts);
327
- } catch (err) {
328
- // Re-throw EPERM so caller can handle Windows Defender blocks
329
- if (err.code === 'EPERM' || err.message?.includes('EPERM')) {
330
- throw err;
331
- }
332
- return { success: false, stdout: '', stderr: err.message, exitCode: null };
333
- }
289
+ const challengeCreateFn = async (authz, challenge, keyAuthorization) => {
290
+ challengeTokens.set(challenge.token, keyAuthorization);
334
291
  };
335
292
 
336
- // Method 1: Invoke-WebRequest with all TLS versions
337
- let r = await safeRun(
338
- `${tlsSetup}; $ProgressPreference='SilentlyContinue'; Invoke-WebRequest -Uri '${safeUrl}' -OutFile '${safeDest}' -UseBasicParsing -TimeoutSec 120`,
339
- { timeout: 130000 },
340
- );
341
- if (r.success) return true;
342
- if (showErrors && r.stderr) lastDownloadError = `Invoke-WebRequest: ${r.stderr}`;
343
-
344
- // Method 2: curl.exe (works on Windows 10+, often bypasses AV detection)
345
- if (hasCurl) {
346
- r = await safeRun(
347
- `curl.exe -L --ssl-no-revoke --max-time 120 -o '${safeDest}' '${safeUrl}'`,
348
- { timeout: 130000 },
349
- );
350
- if (r.success) return true;
351
- if (showErrors && r.stderr && !lastDownloadError) lastDownloadError = `curl: ${r.stderr}`;
352
- }
353
-
354
- // Method 3: WebClient with TLS
355
- r = await safeRun(
356
- `${tlsSetup}; (New-Object System.Net.WebClient).DownloadFile('${safeUrl}','${safeDest}')`,
357
- { timeout: 130000 },
358
- );
359
- if (r.success) return true;
360
- if (showErrors && r.stderr && !lastDownloadError) lastDownloadError = `WebClient: ${r.stderr}`;
361
-
362
- // Method 4: HttpClient with custom handler
363
- r = await safeRun(
364
- `${tlsSetup}; $handler=[System.Net.Http.HttpClientHandler]::new(); $handler.ServerCertificateCustomValidationCallback={$true}; $handler.AllowAutoRedirect=$true; $hc=[System.Net.Http.HttpClient]::new($handler); $hc.DefaultRequestHeaders.Add('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64)'); $hc.Timeout=[TimeSpan]::FromSeconds(120); $bytes=$hc.GetByteArrayAsync('${safeUrl}').GetAwaiter().GetResult(); [System.IO.File]::WriteAllBytes('${safeDest}',$bytes)`,
365
- { timeout: 130000 },
366
- );
367
- if (r.success) return true;
368
- if (showErrors && r.stderr && !lastDownloadError) lastDownloadError = `HttpClient: ${r.stderr}`;
369
-
370
- // Method 5: BITS Transfer (background transfers)
371
- r = await safeRun(
372
- `Import-Module BitsTransfer -ErrorAction SilentlyContinue; Start-BitsTransfer -Source '${safeUrl}' -Destination '${safeDest}' -ErrorAction Stop`,
373
- { timeout: 130000 },
374
- );
375
- if (r.success) return true;
376
- if (showErrors && r.stderr && !lastDownloadError) lastDownloadError = `BITS: ${r.stderr}`;
377
-
378
- // Note: certutil.exe removed - it triggers Trojan:Win32/Ceprolad.A detection
379
-
380
- return false;
381
- }
382
-
383
- async function runNsisInstaller(exePath) {
384
- await run(
385
- `$p = Start-Process -FilePath '${exePath}' -ArgumentList '/S' -PassThru -Wait; $p.ExitCode`,
386
- { timeout: 120000 },
387
- );
388
- await new Promise(res => setTimeout(res, 4000));
389
- return verifyCertbot();
390
- }
391
-
392
- let methodNum = 0;
393
- function step(label) {
394
- methodNum++;
395
- console.log(chalk.gray(`\n [${methodNum}] ${label}\n`));
396
- }
397
-
398
- // ── Check winget availability and offer to install if missing ─────────────────
399
- let wingetAvailable = false;
400
- const wingetCheck = await run('where.exe winget 2>$null');
401
- wingetAvailable = wingetCheck.success && wingetCheck.stdout.trim();
402
-
403
- if (!wingetAvailable) {
404
- console.log(chalk.yellow('\n ⚠ winget is not installed on this system.'));
405
- console.log(chalk.gray(' winget (Windows Package Manager) provides the easiest installation method.'));
293
+ const challengeRemoveFn = async (authz, challenge, keyAuthorization) => {
294
+ challengeTokens.delete(challenge.token);
295
+ };
406
296
 
407
- let installWinget;
408
- try {
409
- ({ installWinget } = await inquirer.prompt([{
410
- type: 'confirm',
411
- name: 'installWinget',
412
- message: 'Would you like to install winget automatically?',
413
- default: true,
414
- }]));
415
- } catch { /* user cancelled */ }
416
-
417
- if (installWinget) {
418
- console.log(chalk.cyan('\n Opening winget installer in a new window...'));
419
- console.log(chalk.gray(' The installer will run in a separate PowerShell window.'));
420
- console.log(chalk.gray(' Please complete the installation in that window.\n'));
421
-
422
- // Use the embedded winget-install.ps1 script
423
- const scriptDir = path.dirname(fileURLToPath(import.meta.url));
424
- const wingetScriptPath = path.join(scriptDir, '..', '..', 'lib', 'installer', 'winget-install.ps1');
425
-
426
- // Check if the embedded script exists
427
- const scriptExists = await run(`Test-Path "${wingetScriptPath}"`);
428
- if (scriptExists.stdout.trim().toLowerCase() !== 'true') {
429
- console.log(chalk.red('\n Embedded winget installer script not found.'));
430
- console.log(chalk.gray(' Expected location: ' + wingetScriptPath + '\n'));
431
- } else {
432
- // Run the installer in a new PowerShell window with -NoExit so user can see output
433
- // The script has a built-in -NoExit parameter we can use
434
- await run(`Start-Process powershell.exe -ArgumentList '-ExecutionPolicy Bypass -NoProfile -File "${wingetScriptPath}" -NoExit' -Verb RunAs -Wait`);
435
-
436
- console.log(chalk.gray('\n Winget installer window has closed.'));
437
- console.log(chalk.cyan(' Checking if winget is now available...\n'));
438
-
439
- // Give a moment for PATH to update
440
- await new Promise(res => setTimeout(res, 2000));
441
-
442
- // Re-check for winget
443
- const recheck = await run('where.exe winget 2>$null');
444
- if (recheck.success && recheck.stdout.trim()) {
445
- console.log(chalk.green(' ✓ winget installed successfully!\n'));
446
- wingetAvailable = true;
447
- } else {
448
- // Try refreshing PATH from registry and check again
449
- console.log(chalk.yellow(' winget not immediately detected. Refreshing PATH...'));
450
- await run(`$env:PATH = [System.Environment]::GetEnvironmentVariable('PATH', 'Machine') + ';' + [System.Environment]::GetEnvironmentVariable('PATH', 'User')`);
451
- await new Promise(res => setTimeout(res, 1000));
452
-
453
- const recheck2 = await run('where.exe winget 2>$null');
454
- if (recheck2.success && recheck2.stdout.trim()) {
455
- console.log(chalk.green('\n ✓ winget installed successfully!\n'));
456
- wingetAvailable = true;
457
- } else {
458
- console.log(chalk.yellow('\n winget may have been installed but is not in PATH yet.'));
459
- console.log(chalk.gray(' You may need to restart your terminal or computer.\n'));
460
- }
297
+ // Start temp HTTP server on port 80
298
+ httpServer = http.createServer((req, res) => {
299
+ const url = new URL(req.url, `http://${req.headers.host}`);
300
+ if (url.pathname.startsWith('/.well-known/acme-challenge/')) {
301
+ const token = url.pathname.split('/').pop();
302
+ const keyAuth = challengeTokens.get(token);
303
+ if (keyAuth) {
304
+ res.writeHead(200, { 'Content-Type': 'application/octet-stream' });
305
+ res.end(keyAuth);
306
+ return;
461
307
  }
462
308
  }
309
+ res.writeHead(404);
310
+ res.end('Not found');
311
+ });
463
312
 
464
- // If still no winget, continue with other methods
465
- if (!wingetAvailable) {
466
- console.log(chalk.gray(' Continuing with alternative installation methods...\n'));
467
- }
468
- } else {
469
- console.log(chalk.gray(' Skipping winget installation. Using alternative methods...\n'));
470
- }
471
- }
472
-
473
- // ── Method 1: winget (certbot EFF - most reliable) ────────────────────────────
474
- if (wingetAvailable) {
475
- step('Trying winget (EFF.Certbot) ...');
476
- console.log(chalk.gray(' Running: winget install EFF.Certbot\n'));
477
- const exitCode = await runLive(
478
- 'winget install -e --id EFF.Certbot --accept-package-agreements --accept-source-agreements',
479
- { timeout: 180000 },
480
- );
481
- if (exitCode === 0 || await verifyCertbot()) return { success: true };
482
- console.log(chalk.yellow(' winget certbot failed, trying next...\n'));
483
- }
484
-
485
- // ── Method 2: winget (win-acme) ───────────────────────────────────────────────
486
- if (wingetAvailable) {
487
- step('Trying winget (win-acme) ...');
488
- console.log(chalk.gray(' Running: winget install win-acme.win-acme\n'));
489
- const exitCode = await runLive(
490
- 'winget install -e --id win-acme.win-acme --accept-package-agreements --accept-source-agreements',
491
- { timeout: 180000 },
492
- );
493
- if (exitCode === 0 || await verifyWinAcme()) return { success: true, client: 'winacme' };
494
- console.log(chalk.yellow(' winget win-acme failed, trying next...\n'));
495
- }
496
-
497
- // ── Method 3: Chocolatey (win-acme) ───────────────────────────────────────────
498
- if ((await run('where.exe choco 2>$null')).success) {
499
- step('Trying Chocolatey (win-acme) ...');
500
- const exitCode = await runLive('choco install win-acme -y', { timeout: 180000 });
501
- if (exitCode === 0 || await verifyWinAcme()) return { success: true, client: 'winacme' };
502
- console.log(chalk.yellow(' Chocolatey win-acme failed, trying next...\n'));
503
- }
504
-
505
- // ── Method 4: Chocolatey (certbot) ────────────────────────────────────────────
506
- if ((await run('where.exe choco 2>$null')).success) {
507
- step('Trying Chocolatey (certbot) ...');
508
- const exitCode = await runLive('choco install certbot -y', { timeout: 180000 });
509
- if (exitCode === 0 || await verifyCertbot()) return { success: true };
510
- console.log(chalk.yellow(' Chocolatey certbot failed, trying next...\n'));
511
- }
313
+ await new Promise((resolve, reject) => {
314
+ httpServer.listen(80, (err) => {
315
+ if (err) reject(err);
316
+ else resolve();
317
+ });
318
+ });
512
319
 
513
- // ── Method 5: pip (certbot) ───────────────────────────────────────────────────
514
- for (const pip of ['pip', 'pip3']) {
515
- const check = await run(`where.exe ${pip} 2>$null`);
516
- if (check.success && check.stdout.trim()) {
517
- step(`Trying ${pip} install certbot ...`);
518
- const exitCode = await runLive(`${pip} install certbot`, { timeout: 180000 });
519
- if (exitCode === 0 || await verifyCertbot()) return { success: true };
520
- console.log(chalk.yellow(` ${pip} did not install certbot, trying next...\n`));
521
- break;
320
+ try {
321
+ // Execute ACME challenge — returns the signed certificate PEM
322
+ // challengePriority forces http-01 only so acme-client never falls back to dns-01
323
+ const cert = await client.auto({
324
+ csr,
325
+ email: acmeEmail,
326
+ termsOfServiceAgreed: true,
327
+ challengePriority: ['http-01'],
328
+ challengeCreateFn,
329
+ challengeRemoveFn,
330
+ });
331
+
332
+ // Close HTTP server
333
+ await new Promise((resolve) => httpServer.close(resolve));
334
+
335
+ // Restart nginx
336
+ await startNginx();
337
+
338
+ // Write certificate files
339
+ const certPath = path.join(certDir, 'fullchain.pem');
340
+ const keyPath = path.join(certDir, 'privkey.pem');
341
+
342
+ await fs.writeFile(keyPath, domainKey);
343
+ await fs.writeFile(certPath, cert);
344
+
345
+ return { success: true, certPath, keyPath, error: null };
346
+ } catch (err) {
347
+ // Ensure server is closed and nginx restarted on error
348
+ await new Promise((resolve) => httpServer.close(resolve));
349
+ await startNginx();
350
+ return {
351
+ success: false,
352
+ certPath: null,
353
+ keyPath: null,
354
+ error: {
355
+ step: 'ACME validation',
356
+ cause: err.message || 'HTTP-01 challenge failed.',
357
+ consequence: 'No certificate was issued. nginx has been restarted.',
358
+ nginxRunning: true,
359
+ configSaved: false,
360
+ },
361
+ };
522
362
  }
523
363
  }
524
364
 
525
- // ── Method 6: Scoop (win-acme) ────────────────────────────────────────────────
526
- if ((await run('where.exe scoop 2>$null')).success) {
527
- step('Trying Scoop (win-acme) ...');
528
- await runLive('scoop bucket add extras', { timeout: 60000 });
529
- const exitCode = await runLive('scoop install win-acme', { timeout: 180000 });
530
- if (exitCode === 0 || await verifyWinAcme()) return { success: true, client: 'winacme' };
531
- console.log(chalk.yellow(' Scoop win-acme failed, trying next...\n'));
532
- }
533
-
534
- // ── Method 7: Direct download win-acme (ZIP - smaller, no installer) ──────────
535
- const WINACME_DEST = 'C:\\Program Files\\win-acme';
536
-
537
- step('Downloading win-acme from GitHub ...');
538
- const winAcmeUrls = [
539
- 'https://github.com/win-acme/win-acme/releases/latest/download/win-acme.zip',
540
- 'https://github.com/win-acme/win-acme/releases/download/v2.2.9.1/win-acme.v2.2.9.1.zip',
541
- ];
542
-
543
- for (const url of winAcmeUrls) {
544
- const hostname = new URL(url).hostname;
545
- console.log(chalk.gray(` Downloading from ${hostname} ...`));
546
-
547
- const zipDest = `$env:TEMP\\win-acme.zip`;
548
- lastDownloadError = '';
549
- let dlOk = false;
550
- try { dlOk = await downloadFile(url, zipDest, true); } catch (err) {
551
- if (err.code === 'EPERM' || err.message?.includes('EPERM')) {
552
- console.log(chalk.red('Windows Defender blocked this download.'));
553
- console.log(chalk.gray('Use the manual installer option or add a Windows Defender exclusion.'));
554
- }
555
- }
556
- if (dlOk) {
557
- console.log(chalk.gray(' Extracting win-acme ...\n'));
558
- await run(`New-Item -ItemType Directory -Force -Path '${WINACME_DEST}'`);
559
- await run(`Expand-Archive -Path '${zipDest}' -DestinationPath '${WINACME_DEST}' -Force`);
560
- await run(`Remove-Item -Force '${zipDest}' -ErrorAction SilentlyContinue`);
561
-
562
- if (await verifyWinAcme()) {
563
- console.log(chalk.green(` win-acme installed to ${WINACME_DEST}\n`));
564
- return { success: true, client: 'winacme' };
565
- }
566
- console.log(chalk.yellow(' Extraction succeeded but verification failed, trying next...\n'));
567
- } else {
568
- console.log(chalk.yellow(` Could not download from ${hostname}`));
569
- if (lastDownloadError) {
570
- console.log(chalk.gray(` Error: ${lastDownloadError.substring(0, 200)}\n`));
571
- }
572
- }
573
- }
365
+ // ─── DNS-01 Challenge ──────────────────────────────────────────────────────
366
+ if (validationMethod === 'dns') {
367
+ const challengeCreateFn = async (authz, challenge, keyAuthorization) => {
368
+ const txtName = `_acme-challenge.${domainName}`;
369
+ const txtValue = keyAuthorization;
574
370
 
575
- // ── Method 8: Direct download certbot installer ────────────────────────────────
576
- const INSTALLER_FILENAME = 'certbot-beta-installer-win_amd64_signed.exe';
577
- const INSTALLER_DEST = `$env:TEMP\\${INSTALLER_FILENAME}`;
578
- const certbotUrls = [
579
- `https://dl.eff.org/${INSTALLER_FILENAME}`,
580
- `https://github.com/certbot/certbot/releases/latest/download/${INSTALLER_FILENAME}`,
581
- ];
582
-
583
- for (const url of certbotUrls) {
584
- const hostname = new URL(url).hostname;
585
- step(`Downloading certbot installer from ${hostname} ...`);
586
-
587
- lastDownloadError = '';
588
- let dlOk = false;
589
- try { dlOk = await downloadFile(url, INSTALLER_DEST, true); } catch (err) {
590
- if (err.code === 'EPERM' || err.message?.includes('EPERM')) {
591
- console.log(chalk.red('Windows Defender blocked this download.'));
592
- console.log(chalk.gray('Use the manual installer option or add a Windows Defender exclusion.'));
593
- }
594
- }
595
- if (dlOk) {
596
- console.log(chalk.gray(' Running installer silently ...\n'));
597
- const ok = await runNsisInstaller(INSTALLER_DEST);
598
- await run(`Remove-Item -Force '${INSTALLER_DEST}' -ErrorAction SilentlyContinue`);
599
- if (ok) return { success: true };
600
- console.log(chalk.yellow(' Installer ran but certbot not detected, trying next...\n'));
601
- } else {
602
- console.log(chalk.yellow(` Could not download from ${hostname}`));
603
- if (lastDownloadError) {
604
- console.log(chalk.gray(` Error: ${lastDownloadError.substring(0, 200)}\n`));
371
+ // Yield TXT record to caller and pause until they confirm DNS is set.
372
+ // onDnsChallenge is async — it returns only after the user confirms
373
+ // (dashboard: /create-confirm resolves the deferred; CLI: inquirer prompt).
374
+ if (onDnsChallenge) {
375
+ await onDnsChallenge(txtName, txtValue);
605
376
  }
606
- }
607
- }
377
+ // challengeCreateFn returning here signals acme-client to proceed with validation.
378
+ };
608
379
 
609
- // ── Method 9: Manual installer path ───────────────────────────────────────────
610
- console.log(chalk.yellow('\n All automatic methods failed.'));
611
- console.log(chalk.gray(' You can manually download one of these on another PC:'));
612
- console.log(chalk.gray(' • certbot: https://certbot.eff.org/instructions?ws=other&os=windows'));
613
- console.log(chalk.gray(' • win-acme: https://github.com/win-acme/win-acme/releases'));
614
- console.log(chalk.gray(' Then transfer to this server and use "Specify local installer" below.\n'));
380
+ const challengeRemoveFn = async () => {
381
+ // No-op: TXT record cleanup is the user's responsibility.
382
+ };
615
383
 
616
- let localChoice;
617
- try {
618
- ({ localChoice } = await inquirer.prompt([{
619
- type: 'list',
620
- name: 'localChoice',
621
- message: 'What would you like to do?',
622
- choices: [
623
- 'Open download page in browser',
624
- 'Specify local installer path',
625
- 'Cancel'
626
- ],
627
- }]));
628
- } catch { return { success: false }; }
629
-
630
- if (localChoice === 'Open download page in browser') {
631
- console.log(chalk.cyan('\n Opening download pages in browser...'));
632
- console.log(chalk.gray(' Download either win-acme.zip or certbot installer, then re-run this tool.\n'));
633
-
634
- // Open win-acme releases
635
- await run('Start-Process "https://github.com/win-acme/win-acme/releases/latest"');
636
- // Also open EFF certbot page
637
- await run('Start-Process "https://certbot.eff.org/instructions?ws=other&os=windows"');
638
-
639
- console.log(chalk.green('✓ Browser opened. Download the installer, then run:'));
640
- console.log(chalk.cyan(' easy-devops → SSL Manager → Install certbot → Specify local installer path\n'));
641
-
642
- return { success: false };
384
+ try {
385
+ // Execute ACME challenge — returns the signed certificate PEM
386
+ // challengePriority forces dns-01 only so acme-client never tries http-01
387
+
388
+ const cert = await client.auto({
389
+ csr,
390
+ email: acmeEmail,
391
+ termsOfServiceAgreed: true,
392
+ challengePriority: ['dns-01'],
393
+ challengeCreateFn,
394
+ challengeRemoveFn,
395
+ });
396
+
397
+ // Write certificate files
398
+ const certPath = path.join(certDir, 'fullchain.pem');
399
+ const keyPath = path.join(certDir, 'privkey.pem');
400
+
401
+ await fs.writeFile(keyPath, domainKey);
402
+ await fs.writeFile(certPath, cert);
403
+
404
+ return { success: true, certPath, keyPath, error: null };
405
+ } catch (err) {
406
+ return {
407
+ success: false,
408
+ certPath: null,
409
+ keyPath: null,
410
+ error: {
411
+ step: 'ACME validation',
412
+ cause: err.message || 'DNS-01 challenge failed.',
413
+ consequence: 'No certificate was issued. nginx was not affected.',
414
+ nginxRunning: true,
415
+ configSaved: false,
416
+ },
417
+ };
418
+ }
643
419
  }
644
420
 
645
- if (localChoice === 'Specify local installer path') {
646
- let localPath;
647
- try {
648
- ({ localPath } = await inquirer.prompt([{
649
- type: 'input',
650
- name: 'localPath',
651
- message: 'Full path to installer (.exe or .zip):',
652
- validate: v => v.trim().length > 0 || 'Required',
653
- }]));
654
- } catch { return { success: false }; }
421
+ // Invalid validation method
422
+ return {
423
+ success: false,
424
+ certPath: null,
425
+ keyPath: null,
426
+ error: {
427
+ step: 'validation method',
428
+ cause: `Invalid validation method: ${validationMethod}. Must be 'http' or 'dns'.`,
429
+ consequence: 'No certificate was issued.',
430
+ nginxRunning: true,
431
+ configSaved: false,
432
+ },
433
+ };
434
+ }
655
435
 
656
- const exists = await run(`Test-Path '${localPath.trim()}'`);
657
- if (exists.stdout.trim().toLowerCase() !== 'true') {
658
- console.log(chalk.red(` File not found: ${localPath}\n`));
659
- return { success: false };
660
- }
436
+ /**
437
+ * Renews a certificate by re-issuing it.
438
+ * acme-client's auto() handles renewal transparently.
439
+ */
440
+ export async function renewCert(domainName, options = {}) {
441
+ return issueCert(domainName, options);
442
+ }
661
443
 
662
- const ext = path.extname(localPath.trim().toLowerCase());
444
+ /**
445
+ * Renews all certificates expiring within 30 days.
446
+ */
447
+ export async function renewExpiring(certs) {
448
+ const expiring = certs.filter(c => c.daysLeft !== null && c.daysLeft < 30);
449
+ if (expiring.length === 0) return [];
663
450
 
664
- if (ext === '.zip') {
665
- step('Extracting ZIP archive ...');
666
- await run(`New-Item -ItemType Directory -Force -Path '${WINACME_DEST}'`);
667
- await run(`Expand-Archive -Path '${localPath.trim()}' -DestinationPath '${WINACME_DEST}' -Force`);
668
- if (await verifyWinAcme()) {
669
- return { success: true, client: 'winacme' };
670
- }
671
- console.log(chalk.red(' Extraction succeeded but win-acme not found.\n'));
672
- } else {
673
- step('Running installer silently ...');
674
- const ok = await runNsisInstaller(localPath.trim());
675
- if (ok) return { success: true };
676
- console.log(chalk.red(' Installer ran but certbot was not detected.\n'));
677
- }
451
+ const results = [];
452
+ for (const cert of expiring) {
453
+ const result = await issueCert(cert.domain, { validationMethod: 'http' });
454
+ results.push({
455
+ domain: cert.domain,
456
+ success: result.success,
457
+ exitCode: result.success ? 0 : 1,
458
+ });
678
459
  }
679
-
680
- return { success: false };
460
+ return results;
681
461
  }
682
462
 
683
- // ─── showSslManager ───────────────────────────────────────────────────────────
463
+ // ─── CLI Menu ────────────────────────────────────────────────────────────────
684
464
 
685
465
  export async function showSslManager() {
686
466
  while (true) {
687
- const liveDir = getCertbotDir();
467
+ const liveDir = getLiveDir();
688
468
 
689
469
  const spinner = ora('Loading certificates…').start();
690
470
  const certs = await listCerts(liveDir);
@@ -703,9 +483,9 @@ export async function showSslManager() {
703
483
  console.log();
704
484
 
705
485
  const choices = [
486
+ 'Create new certificate',
706
487
  'Renew a certificate',
707
488
  'Renew all expiring (< 30 days)',
708
- 'Install certbot',
709
489
  new inquirer.Separator(),
710
490
  '← Back',
711
491
  ];
@@ -724,13 +504,108 @@ export async function showSslManager() {
724
504
  }
725
505
 
726
506
  switch (choice) {
727
- case 'Renew a certificate': {
728
- const installed = await isCertbotInstalled();
729
- if (!installed) {
730
- console.log(chalk.yellow('\n ⚠ certbot/win-acme not found — select "Install certbot" first\n'));
731
- break;
507
+ case 'Create new certificate': {
508
+ const config = loadConfig();
509
+
510
+ // Prompt for email if not configured
511
+ let acmeEmail = config.acmeEmail;
512
+ if (!acmeEmail) {
513
+ let emailInput;
514
+ try {
515
+ ({ emailInput } = await inquirer.prompt([{
516
+ type: 'input',
517
+ name: 'emailInput',
518
+ message: 'Email address (required for Let\'s Encrypt):',
519
+ validate: v => v.trim() && v.includes('@') ? true : 'Valid email required',
520
+ }]));
521
+ acmeEmail = emailInput;
522
+ // Save to config
523
+ config.acmeEmail = acmeEmail;
524
+ const { saveConfig } = await import('../../core/config.js');
525
+ saveConfig(config);
526
+ } catch (err) {
527
+ if (err.name === 'ExitPromptError') return;
528
+ throw err;
529
+ }
732
530
  }
733
531
 
532
+ let domainInput, wwwInput, method;
533
+ try {
534
+ ({ domainInput } = await inquirer.prompt([{
535
+ type: 'input',
536
+ name: 'domainInput',
537
+ message: 'Domain name:',
538
+ validate: v => v.trim() ? true : 'Required',
539
+ }]));
540
+ ({ wwwInput } = await inquirer.prompt([{
541
+ type: 'confirm',
542
+ name: 'wwwInput',
543
+ message: 'Include www subdomain?',
544
+ default: false,
545
+ }]));
546
+ ({ method } = await inquirer.prompt([{
547
+ type: 'list',
548
+ name: 'method',
549
+ message: 'How should we validate domain ownership?',
550
+ choices: [
551
+ { name: 'HTTP challenge (domain DNS points to this server)', value: 'http' },
552
+ { name: 'DNS challenge (I\'ll add a TXT record manually)', value: 'dns' },
553
+ ],
554
+ }]));
555
+ } catch (err) {
556
+ if (err.name === 'ExitPromptError') return;
557
+ throw err;
558
+ }
559
+
560
+ let result;
561
+ if (method === 'dns') {
562
+ const onDnsChallenge = async (txtName, txtValue) => {
563
+ console.log(chalk.yellow('\n Add this DNS TXT record:'));
564
+ console.log(chalk.white(` Name: ${txtName}`));
565
+ console.log(chalk.white(` Value: ${txtValue}\n`));
566
+ try {
567
+ await inquirer.prompt([{
568
+ type: 'input',
569
+ name: '_',
570
+ message: 'Add the TXT record to your DNS, then press Enter to continue...',
571
+ }]);
572
+ } catch (err) {
573
+ if (err.name !== 'ExitPromptError') throw err;
574
+ }
575
+ };
576
+ console.log(chalk.cyan(`\n Starting DNS challenge for ${domainInput.trim()}…\n`));
577
+ result = await issueCert(domainInput.trim(), {
578
+ www: wwwInput,
579
+ validationMethod: 'dns',
580
+ email: acmeEmail,
581
+ onDnsChallenge,
582
+ });
583
+ } else {
584
+ const spinner = ora(`Creating certificate for ${domainInput.trim()}…`).start();
585
+ result = await issueCert(domainInput.trim(), {
586
+ www: wwwInput,
587
+ validationMethod: 'http',
588
+ email: acmeEmail,
589
+ });
590
+ spinner.stop();
591
+ }
592
+
593
+ if (result.success) {
594
+ console.log(chalk.green('\n ✓ Certificate created successfully'));
595
+ console.log(chalk.gray(` Cert: ${result.certPath}`));
596
+ console.log(chalk.gray(` Key: ${result.keyPath}\n`));
597
+ } else {
598
+ const e = result.error;
599
+ console.log(chalk.red('\n ✗ Certificate creation failed'));
600
+ console.log(chalk.yellow(` Step: ${e.step}`));
601
+ console.log(chalk.yellow(` Cause: ${e.cause}`));
602
+ console.log(chalk.yellow(` Consequence: ${e.consequence}`));
603
+ console.log(chalk.gray(` nginx running: ${e.nginxRunning ? 'yes' : 'no'}\n`));
604
+ }
605
+ break;
606
+ }
607
+
608
+ case 'Renew a certificate': {
734
609
  if (certs.length === 0) {
735
610
  console.log(chalk.gray('\n No certificates found to renew\n'));
736
611
  break;
@@ -749,23 +624,28 @@ export async function showSslManager() {
749
624
  throw err;
750
625
  }
751
626
 
752
- const renewResult = await renewCert(selectedDomain);
753
- if (renewResult.success) {
627
+ const config = loadConfig();
628
+ const spinner = ora(`Renewing certificate for ${selectedDomain}…`).start();
629
+ const result = await renewCert(selectedDomain, {
630
+ validationMethod: 'http',
631
+ email: config.acmeEmail,
632
+ });
633
+ spinner.stop();
634
+
635
+ if (result.success) {
754
636
  console.log(chalk.green('\n ✓ Renewed successfully\n'));
755
637
  } else {
756
- console.log(chalk.red('\n ✗ Renewal failed — see output above\n'));
638
+ const e = result.error;
639
+ console.log(chalk.red('\n ✗ Renewal failed'));
640
+ console.log(chalk.yellow(` Step: ${e.step}`));
641
+ console.log(chalk.yellow(` Cause: ${e.cause}\n`));
757
642
  }
758
643
  break;
759
644
  }
760
645
 
761
646
  case 'Renew all expiring (< 30 days)': {
762
- const installed = await isCertbotInstalled();
763
- if (!installed) {
764
- console.log(chalk.yellow('\n ⚠ certbot/win-acme not found — select "Install certbot" first\n'));
765
- break;
766
- }
767
-
768
- const results = await renewExpiring(certs);
647
+ const config = loadConfig();
648
+ const results = await renewExpiring(certs, { email: config.acmeEmail });
769
649
  if (results.length === 0) {
770
650
  console.log(chalk.gray('\n No certificates expiring within 30 days\n'));
771
651
  } else {
@@ -782,24 +662,6 @@ export async function showSslManager() {
782
662
  break;
783
663
  }
784
664
 
785
- case 'Install certbot': {
786
- const alreadyInstalled = await isCertbotInstalled();
787
- if (alreadyInstalled) {
788
- const clientType = await getAcmeClientType();
789
- console.log(chalk.gray(`\n ${clientType === 'winacme' ? 'win-acme' : 'certbot'} is already installed\n`));
790
- break;
791
- }
792
-
793
- const installResult = await installCertbot();
794
- if (installResult.success) {
795
- const clientName = installResult.client === 'winacme' ? 'win-acme' : 'certbot';
796
- console.log(chalk.green(`\n ✓ ${clientName} installed successfully\n`));
797
- } else {
798
- console.log(chalk.red('\n ✗ Installation failed\n'));
799
- }
800
- break;
801
- }
802
-
803
665
  case '← Back':
804
666
  return;
805
667
  }