fix: lazy DB initialization — useDb() called inside handlers, not at import
useRuntimeConfig() and better-sqlite3 were being called at module top-level, which crashes during Nitro server startup. Now all DB access is lazy via useDb(), and auth uses process.env directly. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,8 +1,9 @@
|
||||
import { randomBytes, timingSafeEqual } from 'crypto'
|
||||
import type { H3Event } from 'h3'
|
||||
import db from './db'
|
||||
import { useDb } from './db'
|
||||
|
||||
export function createSession(): string {
|
||||
const db = useDb()
|
||||
const token = randomBytes(32).toString('hex')
|
||||
const expires = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString()
|
||||
db.prepare('INSERT INTO sessions (token, expires_at) VALUES (?, ?)').run(token, expires)
|
||||
@@ -10,6 +11,7 @@ export function createSession(): string {
|
||||
}
|
||||
|
||||
export function validateSession(token: string): boolean {
|
||||
const db = useDb()
|
||||
const row = db.prepare('SELECT expires_at FROM sessions WHERE token = ?').get(token) as any
|
||||
if (!row) return false
|
||||
if (new Date(row.expires_at) < new Date()) {
|
||||
@@ -20,12 +22,12 @@ export function validateSession(token: string): boolean {
|
||||
}
|
||||
|
||||
export function destroySession(token: string) {
|
||||
const db = useDb()
|
||||
db.prepare('DELETE FROM sessions WHERE token = ?').run(token)
|
||||
}
|
||||
|
||||
export function checkPassword(input: string): boolean {
|
||||
const config = useRuntimeConfig()
|
||||
const expected = config.adminPassword as string
|
||||
const expected = process.env.ADMIN_PASSWORD || 'admin'
|
||||
if (input.length !== expected.length) return false
|
||||
return timingSafeEqual(Buffer.from(input), Buffer.from(expected))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user