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
|
import {existsSync} from 'fs';
import {readFile, writeFile} from "node:fs/promises";
import {generateKeyPairSync, createHash, createPublicKey, createPrivateKey} from 'node:crypto';
let privateKey, publicKey, fingerprint;
export async function initJwt() {
const secretPath = process.env.JWT_SECRET_PATH;
if (!secretPath || !existsSync(secretPath)) {
throw new Error('JWT secret path is not defined in environment variables, or the directory does not exist.');
}
const privateKeyPath = `${secretPath}/jwt.key`;
const publicKeyPath = `${secretPath}/jwt.key.pub`;
if (!existsSync(privateKeyPath)) {
console.log("[JWT] Generating new keypair");
const keyPair = generateKeyPairSync("ec", {
namedCurve: "secp521r1",
});
privateKey = keyPair.privateKey;
publicKey = keyPair.publicKey;
await Promise.all([
writeFile(
privateKeyPath,
privateKey.export({format: "pem", type: "sec1"}),
),
writeFile(
publicKeyPath,
publicKey.export({format: "pem", type: "spki"}),
),
]);
console.log("[JWT] Keypair generated successfully.");
} else {
console.log("[JWT] Using existing keypair");
const loadedPrivateKey = await readFile(privateKeyPath, 'utf8');
const loadedPublicKey = await readFile(publicKeyPath, 'utf8');
privateKey = createPrivateKey(loadedPrivateKey);
publicKey = createPublicKey(loadedPublicKey);
}
fingerprint = createHash("sha256")
.update(publicKey.export({format: "pem", type: "spki"}))
.digest("hex");
}
/**
* @type {import('jsonwebtoken').JwtOptions}
*/
const jwtOptions = {
algorithm: 'ES512',
}
export async function generateJwtToken(user) {
}
export async function validateJwtToken(token) {
}
|