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.
- package/README.md +87 -44
- package/cli/index.js +27 -5
- package/cli/managers/domain-manager.js +143 -35
- package/cli/managers/nginx-manager.js +33 -9
- package/cli/managers/ssl-manager.js +386 -671
- package/cli/menus/settings.js +27 -8
- package/core/config.js +5 -2
- package/core/detector.js +50 -87
- package/core/nginx-conf-generator.js +101 -64
- package/core/platform.js +61 -0
- package/core/shell.js +2 -2
- package/core/validators.js +96 -0
- package/dashboard/lib/cert-reader.js +5 -5
- package/dashboard/lib/nginx-service.js +47 -77
- package/dashboard/public/img/icon.png +0 -0
- package/dashboard/public/img/icon_b.png +0 -0
- package/dashboard/public/js/app.js +193 -29
- package/dashboard/routes/domains.js +96 -72
- package/dashboard/routes/settings.js +19 -11
- package/dashboard/routes/ssl.js +215 -74
- package/dashboard/views/index.ejs +481 -260
- package/dashboard/views/partials/domain-form.ejs +332 -256
- package/dashboard/views/partials/domains-panel.ejs +100 -62
- package/dashboard/views/partials/login.ejs +157 -40
- package/dashboard/views/partials/nginx-panel.ejs +126 -84
- package/dashboard/views/partials/overview.ejs +124 -49
- package/dashboard/views/partials/settings-panel.ejs +66 -35
- package/dashboard/views/partials/sidebar.ejs +84 -33
- package/dashboard/views/partials/ssl-panel.ejs +174 -93
- package/install.sh +8 -9
- package/lib/installer/nvm-bootstrap.sh +8 -8
- package/lib/installer/picker.sh +32 -15
- package/package.json +4 -2
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* cli/managers/ssl-manager.js
|
|
3
3
|
*
|
|
4
|
-
* SSL Manager — view certificate status, renew certificates
|
|
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
|
-
*
|
|
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
|
|
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
|
-
|
|
26
|
+
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
|
23
27
|
|
|
24
|
-
|
|
28
|
+
function getSslDir() {
|
|
29
|
+
const { sslDir } = loadConfig();
|
|
30
|
+
return sslDir;
|
|
31
|
+
}
|
|
25
32
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
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
|
-
// ───
|
|
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
|
-
|
|
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,523 +177,96 @@ function renderCertRow(cert) {
|
|
|
200
177
|
}
|
|
201
178
|
}
|
|
202
179
|
|
|
203
|
-
// ───
|
|
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
|
-
}
|
|
233
|
-
|
|
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 ───────────────────────────────────────────────────────────
|
|
180
|
+
// ─── Certificate Issuance ─────────────────────────────────────────────────────
|
|
275
181
|
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
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;
|
|
308
|
-
}
|
|
309
|
-
const whereResult = await run('where.exe wacs 2>$null');
|
|
310
|
-
return whereResult.success && whereResult.stdout.trim();
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
const hasCurl = (await run('where.exe curl.exe 2>$null')).success;
|
|
314
|
-
let lastDownloadError = '';
|
|
315
|
-
|
|
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`;
|
|
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();
|
|
322
206
|
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
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
|
+
},
|
|
334
221
|
};
|
|
335
|
-
|
|
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
222
|
}
|
|
391
223
|
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
console.log(chalk.gray(`\n [${methodNum}] ${label}\n`));
|
|
396
|
-
}
|
|
224
|
+
// Ensure certificate directory exists
|
|
225
|
+
const certDir = path.join(sslDir, domainName);
|
|
226
|
+
await fs.mkdir(certDir, { recursive: true });
|
|
397
227
|
|
|
398
|
-
//
|
|
399
|
-
|
|
400
|
-
const wingetCheck = await run('where.exe winget 2>$null');
|
|
401
|
-
wingetAvailable = wingetCheck.success && wingetCheck.stdout.trim();
|
|
228
|
+
// Load or create account key
|
|
229
|
+
const accountKey = await getAccountKey(sslDir);
|
|
402
230
|
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
231
|
+
// Create ACME client (Let's Encrypt production)
|
|
232
|
+
const client = new acme.Client({
|
|
233
|
+
directoryUrl: acme.directory.letsencrypt.production,
|
|
234
|
+
accountKey,
|
|
235
|
+
});
|
|
406
236
|
|
|
407
|
-
|
|
408
|
-
|
|
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
|
-
}
|
|
461
|
-
}
|
|
462
|
-
}
|
|
463
|
-
|
|
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
|
-
}
|
|
512
|
-
|
|
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;
|
|
522
|
-
}
|
|
523
|
-
}
|
|
524
|
-
|
|
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
|
-
}
|
|
574
|
-
|
|
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`));
|
|
605
|
-
}
|
|
606
|
-
}
|
|
607
|
-
}
|
|
608
|
-
|
|
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'));
|
|
615
|
-
|
|
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 };
|
|
643
|
-
}
|
|
644
|
-
|
|
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 }; }
|
|
655
|
-
|
|
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
|
-
}
|
|
661
|
-
|
|
662
|
-
const ext = path.extname(localPath.trim().toLowerCase());
|
|
663
|
-
|
|
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
|
-
}
|
|
678
|
-
}
|
|
679
|
-
|
|
680
|
-
return { success: false };
|
|
681
|
-
}
|
|
682
|
-
|
|
683
|
-
// ─── issueCert ────────────────────────────────────────────────────────────────
|
|
684
|
-
|
|
685
|
-
/**
|
|
686
|
-
* Issues a new SSL certificate using the installed ACME client.
|
|
687
|
-
* Stops nginx before the challenge and restarts it afterwards (always).
|
|
688
|
-
*
|
|
689
|
-
* @param {string} domainName - The primary domain name
|
|
690
|
-
* @param {{ www?: boolean }} options
|
|
691
|
-
* @returns {Promise<{ success: boolean, certPath: string|null, keyPath: string|null, error: object|null }>}
|
|
692
|
-
*/
|
|
693
|
-
export async function issueCert(domainName, { www = false } = {}) {
|
|
694
|
-
// Guard: ACME client must be installed
|
|
695
|
-
const certbotExe = await getCertbotExe();
|
|
696
|
-
if (!certbotExe) {
|
|
237
|
+
// Wildcard requires DNS-01 — enforce it here
|
|
238
|
+
if (wildcard && validationMethod === 'http') {
|
|
697
239
|
return {
|
|
698
240
|
success: false,
|
|
699
241
|
certPath: null,
|
|
700
242
|
keyPath: null,
|
|
701
243
|
error: {
|
|
702
|
-
step: '
|
|
703
|
-
cause: '
|
|
704
|
-
consequence: 'No certificate was issued.
|
|
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.',
|
|
705
247
|
nginxRunning: true,
|
|
706
248
|
configSaved: false,
|
|
707
249
|
},
|
|
708
250
|
};
|
|
709
251
|
}
|
|
710
252
|
|
|
711
|
-
|
|
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
|
+
});
|
|
712
261
|
|
|
713
|
-
//
|
|
714
|
-
|
|
262
|
+
// ─── HTTP-01 Challenge ─────────────────────────────────────────────────────
|
|
263
|
+
if (validationMethod === 'http') {
|
|
264
|
+
// Stop nginx to free port 80
|
|
265
|
+
await stopNginx();
|
|
715
266
|
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
if (portCheck.busy) {
|
|
267
|
+
// Check port 80 is free
|
|
268
|
+
const portFree = await isPort80Free();
|
|
269
|
+
if (!portFree) {
|
|
720
270
|
await startNginx();
|
|
721
271
|
return {
|
|
722
272
|
success: false,
|
|
@@ -724,68 +274,197 @@ export async function issueCert(domainName, { www = false } = {}) {
|
|
|
724
274
|
keyPath: null,
|
|
725
275
|
error: {
|
|
726
276
|
step: 'port 80 check',
|
|
727
|
-
cause:
|
|
728
|
-
consequence: '
|
|
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.',
|
|
729
279
|
nginxRunning: true,
|
|
730
280
|
configSaved: false,
|
|
731
281
|
},
|
|
732
282
|
};
|
|
733
283
|
}
|
|
734
284
|
|
|
735
|
-
//
|
|
736
|
-
const
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
285
|
+
// Create temporary HTTP server for challenge
|
|
286
|
+
const challengeTokens = new Map();
|
|
287
|
+
let httpServer;
|
|
288
|
+
|
|
289
|
+
const challengeCreateFn = async (authz, challenge, keyAuthorization) => {
|
|
290
|
+
challengeTokens.set(challenge.token, keyAuthorization);
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
const challengeRemoveFn = async (authz, challenge, keyAuthorization) => {
|
|
294
|
+
challengeTokens.delete(challenge.token);
|
|
295
|
+
};
|
|
296
|
+
|
|
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;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
res.writeHead(404);
|
|
310
|
+
res.end('Not found');
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
await new Promise((resolve, reject) => {
|
|
314
|
+
httpServer.listen(80, (err) => {
|
|
315
|
+
if (err) reject(err);
|
|
316
|
+
else resolve();
|
|
317
|
+
});
|
|
318
|
+
});
|
|
319
|
+
|
|
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();
|
|
740
337
|
|
|
741
|
-
|
|
338
|
+
// Write certificate files
|
|
339
|
+
const certPath = path.join(certDir, 'fullchain.pem');
|
|
340
|
+
const keyPath = path.join(certDir, 'privkey.pem');
|
|
742
341
|
|
|
743
|
-
|
|
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));
|
|
744
349
|
await startNginx();
|
|
745
350
|
return {
|
|
746
351
|
success: false,
|
|
747
352
|
certPath: null,
|
|
748
353
|
keyPath: null,
|
|
749
354
|
error: {
|
|
750
|
-
step: 'ACME
|
|
751
|
-
cause: '
|
|
355
|
+
step: 'ACME validation',
|
|
356
|
+
cause: err.message || 'HTTP-01 challenge failed.',
|
|
752
357
|
consequence: 'No certificate was issued. nginx has been restarted.',
|
|
753
358
|
nginxRunning: true,
|
|
754
359
|
configSaved: false,
|
|
755
360
|
},
|
|
756
361
|
};
|
|
757
362
|
}
|
|
363
|
+
}
|
|
758
364
|
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
const
|
|
762
|
-
|
|
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;
|
|
763
370
|
|
|
764
|
-
|
|
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);
|
|
376
|
+
}
|
|
377
|
+
// challengeCreateFn returning here signals acme-client to proceed with validation.
|
|
378
|
+
};
|
|
765
379
|
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
try { await startNginx(); } catch { /* best effort */ }
|
|
769
|
-
return {
|
|
770
|
-
success: false,
|
|
771
|
-
certPath: null,
|
|
772
|
-
keyPath: null,
|
|
773
|
-
error: {
|
|
774
|
-
step: 'certificate issuance',
|
|
775
|
-
cause: err.message,
|
|
776
|
-
consequence: 'An unexpected error occurred during certificate issuance. nginx restart was attempted.',
|
|
777
|
-
nginxRunning: false,
|
|
778
|
-
configSaved: false,
|
|
779
|
-
},
|
|
380
|
+
const challengeRemoveFn = async () => {
|
|
381
|
+
// No-op: TXT record cleanup is the user's responsibility.
|
|
780
382
|
};
|
|
383
|
+
|
|
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
|
+
}
|
|
781
419
|
}
|
|
420
|
+
|
|
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
|
+
};
|
|
782
434
|
}
|
|
783
435
|
|
|
784
|
-
|
|
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
|
+
}
|
|
443
|
+
|
|
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 [];
|
|
450
|
+
|
|
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
|
+
});
|
|
459
|
+
}
|
|
460
|
+
return results;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// ─── CLI Menu ────────────────────────────────────────────────────────────────
|
|
785
464
|
|
|
786
465
|
export async function showSslManager() {
|
|
787
466
|
while (true) {
|
|
788
|
-
const liveDir =
|
|
467
|
+
const liveDir = getLiveDir();
|
|
789
468
|
|
|
790
469
|
const spinner = ora('Loading certificates…').start();
|
|
791
470
|
const certs = await listCerts(liveDir);
|
|
@@ -807,7 +486,6 @@ export async function showSslManager() {
|
|
|
807
486
|
'Create new certificate',
|
|
808
487
|
'Renew a certificate',
|
|
809
488
|
'Renew all expiring (< 30 days)',
|
|
810
|
-
'Install certbot',
|
|
811
489
|
new inquirer.Separator(),
|
|
812
490
|
'← Back',
|
|
813
491
|
];
|
|
@@ -827,13 +505,31 @@ export async function showSslManager() {
|
|
|
827
505
|
|
|
828
506
|
switch (choice) {
|
|
829
507
|
case 'Create new certificate': {
|
|
830
|
-
const
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
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
|
+
}
|
|
834
530
|
}
|
|
835
531
|
|
|
836
|
-
let domainInput, wwwInput;
|
|
532
|
+
let domainInput, wwwInput, method;
|
|
837
533
|
try {
|
|
838
534
|
({ domainInput } = await inquirer.prompt([{
|
|
839
535
|
type: 'input',
|
|
@@ -847,37 +543,69 @@ export async function showSslManager() {
|
|
|
847
543
|
message: 'Include www subdomain?',
|
|
848
544
|
default: false,
|
|
849
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
|
+
}]));
|
|
850
555
|
} catch (err) {
|
|
851
556
|
if (err.name === 'ExitPromptError') return;
|
|
852
557
|
throw err;
|
|
853
558
|
}
|
|
854
559
|
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
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
|
+
}
|
|
858
592
|
|
|
859
593
|
if (result.success) {
|
|
860
594
|
console.log(chalk.green('\n ✓ Certificate created successfully'));
|
|
861
|
-
console.log(chalk.gray(`
|
|
862
|
-
console.log(chalk.gray(`
|
|
595
|
+
console.log(chalk.gray(` Cert: ${result.certPath}`));
|
|
596
|
+
console.log(chalk.gray(` Key: ${result.keyPath}\n`));
|
|
863
597
|
} else {
|
|
864
598
|
const e = result.error;
|
|
865
599
|
console.log(chalk.red('\n ✗ Certificate creation failed'));
|
|
866
|
-
console.log(chalk.yellow(`
|
|
867
|
-
console.log(chalk.yellow(`
|
|
868
|
-
console.log(chalk.yellow(`
|
|
869
|
-
console.log(chalk.gray(`
|
|
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`));
|
|
870
604
|
}
|
|
871
605
|
break;
|
|
872
606
|
}
|
|
873
607
|
|
|
874
608
|
case 'Renew a certificate': {
|
|
875
|
-
const installed = await isCertbotInstalled();
|
|
876
|
-
if (!installed) {
|
|
877
|
-
console.log(chalk.yellow('\n ⚠ certbot/win-acme not found — select "Install certbot" first\n'));
|
|
878
|
-
break;
|
|
879
|
-
}
|
|
880
|
-
|
|
881
609
|
if (certs.length === 0) {
|
|
882
610
|
console.log(chalk.gray('\n No certificates found to renew\n'));
|
|
883
611
|
break;
|
|
@@ -896,23 +624,28 @@ export async function showSslManager() {
|
|
|
896
624
|
throw err;
|
|
897
625
|
}
|
|
898
626
|
|
|
899
|
-
const
|
|
900
|
-
|
|
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) {
|
|
901
636
|
console.log(chalk.green('\n ✓ Renewed successfully\n'));
|
|
902
637
|
} else {
|
|
903
|
-
|
|
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`));
|
|
904
642
|
}
|
|
905
643
|
break;
|
|
906
644
|
}
|
|
907
645
|
|
|
908
646
|
case 'Renew all expiring (< 30 days)': {
|
|
909
|
-
const
|
|
910
|
-
|
|
911
|
-
console.log(chalk.yellow('\n ⚠ certbot/win-acme not found — select "Install certbot" first\n'));
|
|
912
|
-
break;
|
|
913
|
-
}
|
|
914
|
-
|
|
915
|
-
const results = await renewExpiring(certs);
|
|
647
|
+
const config = loadConfig();
|
|
648
|
+
const results = await renewExpiring(certs, { email: config.acmeEmail });
|
|
916
649
|
if (results.length === 0) {
|
|
917
650
|
console.log(chalk.gray('\n No certificates expiring within 30 days\n'));
|
|
918
651
|
} else {
|
|
@@ -929,24 +662,6 @@ export async function showSslManager() {
|
|
|
929
662
|
break;
|
|
930
663
|
}
|
|
931
664
|
|
|
932
|
-
case 'Install certbot': {
|
|
933
|
-
const alreadyInstalled = await isCertbotInstalled();
|
|
934
|
-
if (alreadyInstalled) {
|
|
935
|
-
const clientType = await getAcmeClientType();
|
|
936
|
-
console.log(chalk.gray(`\n ${clientType === 'winacme' ? 'win-acme' : 'certbot'} is already installed\n`));
|
|
937
|
-
break;
|
|
938
|
-
}
|
|
939
|
-
|
|
940
|
-
const installResult = await installCertbot();
|
|
941
|
-
if (installResult.success) {
|
|
942
|
-
const clientName = installResult.client === 'winacme' ? 'win-acme' : 'certbot';
|
|
943
|
-
console.log(chalk.green(`\n ✓ ${clientName} installed successfully\n`));
|
|
944
|
-
} else {
|
|
945
|
-
console.log(chalk.red('\n ✗ Installation failed\n'));
|
|
946
|
-
}
|
|
947
|
-
break;
|
|
948
|
-
}
|
|
949
|
-
|
|
950
665
|
case '← Back':
|
|
951
666
|
return;
|
|
952
667
|
}
|