summary refs log tree commit diff
path: root/src/util/jwtUtils.js
diff options
context:
space:
mode:
Diffstat (limited to 'src/util/jwtUtils.js')
-rw-r--r--src/util/jwtUtils.js63
1 files changed, 63 insertions, 0 deletions
diff --git a/src/util/jwtUtils.js b/src/util/jwtUtils.js
new file mode 100644

index 0000000..115c9c5 --- /dev/null +++ b/src/util/jwtUtils.js
@@ -0,0 +1,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) { + +} \ No newline at end of file