This commit is contained in:
seb
2026-09-29 10:27:23 +02:00
parent 62d46a1df3
commit 3089cc7252
8 changed files with 454 additions and 34 deletions

71
src/util/cert.js Normal file
View File

@@ -0,0 +1,71 @@
import fs from 'fs';
import path from 'path';
import os from 'os';
import selfsigned from 'selfsigned';
import env from '../config/env.js';
function getLocalIPv4() {
const addresses = [];
for (const iface of Object.values(os.networkInterfaces())) {
if (!iface) continue;
for (const addr of iface) {
if (addr.family === 'IPv4' && !addr.internal) {
addresses.push(addr.address);
}
}
}
return addresses;
}
/**
* Loads existing TLS credentials or generates a self-signed certificate.
* @returns {Promise<{ key: Buffer | string, cert: Buffer | string }>}
*/
export async function getOrCreateCert() {
const keyPath = env.httpsKeyPath;
const certPath = env.httpsCertPath;
if (fs.existsSync(keyPath) && fs.existsSync(certPath)) {
return {
key: fs.readFileSync(keyPath),
cert: fs.readFileSync(certPath),
};
}
const keyDir = path.dirname(keyPath);
if (!fs.existsSync(keyDir)) {
fs.mkdirSync(keyDir, { recursive: true });
}
const certDir = path.dirname(certPath);
if (!fs.existsSync(certDir)) {
fs.mkdirSync(certDir, { recursive: true });
}
const altNames = [
{ type: 2, value: 'localhost' },
{ type: 7, ip: '127.0.0.1' },
];
for (const ip of getLocalIPv4()) {
altNames.push({ type: 7, ip });
}
const pems = await selfsigned.generate(
[{ name: 'commonName', value: 'localhost' }],
{
days: 365,
algorithm: 'sha256',
extensions: [{ name: 'subjectAltName', altNames }],
}
);
fs.writeFileSync(keyPath, pems.private, { mode: 0o600 });
fs.writeFileSync(certPath, pems.cert);
console.log(`[tls] Generated self-signed certificate at ${certPath}`);
return {
key: pems.private,
cert: pems.cert,
};
}