diff --git a/.dockerignore b/.dockerignore index 6ea097f..be978ba 100644 --- a/.dockerignore +++ b/.dockerignore @@ -5,4 +5,5 @@ docker-compose.yaml LICENSE *.md -node_modules \ No newline at end of file +node_modules +*.pem \ No newline at end of file diff --git a/.gitignore b/.gitignore index 8562a9c..64b2f56 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ .env node_modules **/*.html -!examples \ No newline at end of file +!examples +*.pem \ No newline at end of file diff --git a/src/token.js b/src/token.js index cbd708b..df7d40b 100644 --- a/src/token.js +++ b/src/token.js @@ -2,7 +2,44 @@ const jwt = require("jsonwebtoken") const fs = require("fs") const path = require("path") -const privateKey = fs.readFileSync(path.join(__dirname, "./keys/private.key")) +const logger = require("./logger") + +const { generateKeyPairSync } = require("crypto") + +const keyPath = path.join(__dirname, "../secrets/private_key.pem") + +let privateKey + +function CheckForKey() { + if (fs.existsSync(keyPath)) { + privateKey = fs.readFileSync(keyPath, "utf8") + + logger.log("Loaded existing RSA private key") + } else { + const { privateKey: genPrivKey, publicKey: genPubKey } = + generateKeyPairSync("rsa", { + modulusLength: 2048, + publicKeyEncoding: { + type: "spki", + format: "pem", + }, + privateKeyEncoding: { + type: "pkcs8", + format: "pem", + }, + }) + + fs.mkdirSync(path.dirname(keyPath), { recursive: true }) + fs.writeFileSync(keyPath, genPrivKey) + fs.writeFileSync( + path.join(__dirname, "../secrets/public_key.pem"), + genPubKey + ) + privateKey = genPrivKey + + logger.log("Generated new RSA key pair") + } +} function SignToken(payload) { const options = { @@ -17,5 +54,8 @@ function DecodeToken(idToken) { return jwt.decode(idToken) } +CheckForKey() + exports.SignToken = SignToken exports.DecodeToken = DecodeToken +exports.CheckForKey = CheckForKey