Elffuss BraidHub

kikocis/gaiax-credentials-tool public

main · 1.9 KiBRawPermalink
1import { logger } from "./log.js";
2import { exec } from 'child_process';
3import { promises as fs } from 'fs';
4import path from 'path';
5import { validateCertificate } from './certificate-validator.js';
6
7export async function getLetsEncryptCert(domain) {
8 logger.info(`Generando certificado Let's Encrypt para ${domain}...`);
9
10 try {
11 // Crear directorio temporal para certificados
12 const certDir = path.join(process.cwd(), 'certs');
13 await fs.mkdir(certDir, { recursive: true });
14
15 const certPath = path.join(certDir, `${domain}.crt`);
16 const keyPath = path.join(certDir, `${domain}.key`);
17
18 // Para desarrollo/pruebas, generamos un certificado autofirmado
19 if (domain === 'localhost') {
20 await generateSelfSignedCert(domain, certPath, keyPath);
21 } else {
22 // En producción, usaríamos el cliente ACME para Let's Encrypt
23 throw new Error('Certificados Let\'s Encrypt para dominios no-localhost aún no implementados');
24 }
25
26 // Validar el certificado generado
27 const certInfo = await validateCertificate(certPath);
28
29 logger.info('Certificado generado exitosamente');
30 logger.debug('Información del certificado:', certInfo);
31
32 return {
33 path: certPath,
34 keyPath: keyPath,
35 info: certInfo
36 };
37
38 } catch (error) {
39 logger.error('Error generando certificado:', error);
40 throw new Error(`Error generando certificado Let's Encrypt: ${error.message}`);
41 }
42}
43
44async function generateSelfSignedCert(domain, certPath, keyPath) {
45 return new Promise((resolve, reject) => {
46 const command = `openssl req -x509 -newkey rsa:4096 -keyout "${keyPath}" -out "${certPath}" -days 365 -nodes -subj "/CN=${domain}"`;
47
48 exec(command, (error, stdout, stderr) => {
49 if (error) {
50 reject(new Error(`Error generando certificado autofirmado: ${error.message}`));
51 return;
52 }
53 resolve();
54 });
55 });
56}