feat: generate secure secret key and prevent default

This commit is contained in:
Lin, Hung-Shin committed 2023-11-01 14:19:18 +08:00
1 parent b9a79eb435
commit f18ec35a9f
11 files changed
+45 -5

No files matched your search

+2
View File
@@ -7,6 +7,7 @@
"start": "node src/index.js",
"dev": "nodemon src/index.js",
"test": "yarn node --experimental-vm-modules $(yarn bin jest)",
"setup": "node src/cli/setup.js",
"clean": "node src/cli/clean.js"
},
"dependencies": {
@@ -20,6 +21,7 @@
"express": "^4.18.2",
"express-rate-limit": "^7.1.3",
"express-session": "^1.17.3",
"express-validator": "^7.0.1",
"jsonwebtoken": "^9.0.1",
"minimist": "^1.2.8",
"mongoose": "^7.4.0",
+1 -1
View File
@@ -3,7 +3,7 @@ import config from '../config.js'
const jwtOptions = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: config.jwtSecret,
secretOrKey: config.secret,
}
function verifyJwt(jwtPayload, done) {
+9
View File
@@ -0,0 +1,9 @@
import { genSecret } from '../utils/env.js'
function setup() {
console.log('Setting up .env file...')
const secret = genSecret()
console.log(`SECRET_KEY=${secret}`)
}
setup()
+9 -2
View File
@@ -1,10 +1,10 @@
import { get } from './utils/env.js'
import { get, genSecret } from './utils/env.js'
const config = {
host: get('HOST', 'localhost'),
port: get('PORT', 3000),
db: get('MONGO_URL', 'mongodb://localhost:27017/odyssey-test'),
jwtSecret: get('JWT_SECRET', 'secret'),
secret: get('SECRET_KEY', ''),
dockerNetwork: get('DOCKER_NETWORK', 'linux-odyssey-players'),
isProduction: process.env.NODE_ENV === 'production',
hostPwd: get('HOST_PWD', ''),
@@ -22,4 +22,11 @@ const config = {
config.baseUrl = get('BASE_URL', `http://${config.host}:${config.port}`)
if (!config.secret) {
config.secret = genSecret()
console.warn(
'No SECRET_KEY found in .env! A temporary secret key has been generated. To set up a persistent key, please run the setup script.'
)
}
export default config
+1 -1
View File
@@ -4,7 +4,7 @@ import MongoStore from 'connect-mongo'
import config from '../config.js'
export default session({
secret: config.jwtSecret,
secret: config.secret,
resave: false,
saveUninitialized: false,
rolling: true,
+6 -1
View File
@@ -1,4 +1,5 @@
/* eslint-disable import/prefer-default-export */
import crypto from 'crypto'
export function get(key, defaultValue) {
const value = process.env[key]
if (value != null) {
@@ -6,3 +7,7 @@ export function get(key, defaultValue) {
}
return defaultValue
}
export function genSecret() {
return crypto.randomUUID()
}