-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttps.mjs
More file actions
85 lines (75 loc) · 1.92 KB
/
Copy pathhttps.mjs
File metadata and controls
85 lines (75 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { spawnSync } from 'node:child_process';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, '..');
const certDir = path.join(repoRoot, 'certs');
const keyPath = path.join(certDir, 'dev-key.pem');
const certPath = path.join(certDir, 'dev-cert.pem');
function getLocalIPv4Addresses() {
const ips = new Set();
const nets = os.networkInterfaces();
for (const ifname of Object.keys(nets)) {
const entries = nets[ifname] || [];
for (const net of entries) {
if (!net) continue;
if (net.family !== 'IPv4') continue;
if (net.internal) continue;
if (net.address.startsWith('169.254.')) continue;
ips.add(net.address);
}
}
return Array.from(ips);
}
export function ensureDevHttpsCert() {
try {
if (fs.existsSync(keyPath) && fs.existsSync(certPath)) {
return {
key: fs.readFileSync(keyPath),
cert: fs.readFileSync(certPath)
};
}
} catch (_) {
// fall through to regenerate
}
fs.mkdirSync(certDir, { recursive: true });
const ips = getLocalIPv4Addresses();
const subjectAltName = [
'DNS:localhost',
'IP:127.0.0.1',
...ips.map((ip) => `IP:${ip}`)
].join(',');
const cmd = spawnSync(
'openssl',
[
'req',
'-x509',
'-newkey',
'rsa:2048',
'-sha256',
'-nodes',
'-keyout',
keyPath,
'-out',
certPath,
'-days',
'365',
'-subj',
'/CN=localhost',
'-addext',
`subjectAltName=${subjectAltName}`
],
{ encoding: 'utf8' }
);
if (cmd.status !== 0) {
throw new Error(
`Failed to generate dev HTTPS certificate with openssl.\n${cmd.stderr || cmd.stdout || ''}`
);
}
return {
key: fs.readFileSync(keyPath),
cert: fs.readFileSync(certPath)
};
}