add auth
This commit is contained in:
25
src/lib/secret.ts
Normal file
25
src/lib/secret.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import path from 'path'
|
||||
import fs from 'fs'
|
||||
import crypto from 'crypto'
|
||||
|
||||
const CONFIG_PATH = process.env.CONFIG_PATH ?? process.cwd()
|
||||
const SECRET_FILE = path.resolve(CONFIG_PATH, '.session_secret')
|
||||
|
||||
export function initializeSecret(): void {
|
||||
if (process.env.SESSION_SECRET) return
|
||||
|
||||
if (fs.existsSync(SECRET_FILE)) {
|
||||
process.env.SESSION_SECRET = fs.readFileSync(SECRET_FILE, 'utf8').trim()
|
||||
return
|
||||
}
|
||||
|
||||
const secret = crypto.randomBytes(32).toString('hex')
|
||||
fs.writeFileSync(SECRET_FILE, secret, { mode: 0o600 })
|
||||
process.env.SESSION_SECRET = secret
|
||||
}
|
||||
|
||||
export function getSessionSecret(): string {
|
||||
const secret = process.env.SESSION_SECRET
|
||||
if (!secret) throw new Error('SESSION_SECRET is not set — call initializeSecret() at startup')
|
||||
return secret
|
||||
}
|
||||
Reference in New Issue
Block a user