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:
Alejandro Martinez
2026-04-07 15:36:17 +02:00
parent 6148b5012d
commit 08846c9c63
8 changed files with 51 additions and 39 deletions

View File

@@ -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))
}

View File

@@ -2,38 +2,43 @@ import Database from 'better-sqlite3'
import { mkdirSync } from 'fs'
import { dirname } from 'path'
const config = useRuntimeConfig()
const dbPath = config.dbPath as string
let _db: InstanceType<typeof Database> | null = null
mkdirSync(dirname(dbPath), { recursive: true })
export function useDb() {
if (_db) return _db
const db = new Database(dbPath)
db.pragma('journal_mode = WAL')
db.pragma('foreign_keys = ON')
const dbPath = process.env.DB_PATH || './data/brainstorm.db'
db.exec(`
CREATE TABLE IF NOT EXISTS ideas (
id INTEGER PRIMARY KEY AUTOINCREMENT,
text TEXT NOT NULL,
category TEXT NOT NULL DEFAULT 'General',
votes INTEGER NOT NULL DEFAULT 0,
hidden INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
mkdirSync(dirname(dbPath), { recursive: true })
CREATE TABLE IF NOT EXISTS vote_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
idea_id INTEGER NOT NULL REFERENCES ideas(id) ON DELETE CASCADE,
voter_hash TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
UNIQUE(idea_id, voter_hash)
);
_db = new Database(dbPath)
_db.pragma('journal_mode = WAL')
_db.pragma('foreign_keys = ON')
CREATE TABLE IF NOT EXISTS sessions (
token TEXT PRIMARY KEY,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
expires_at TEXT NOT NULL
);
`)
_db.exec(`
CREATE TABLE IF NOT EXISTS ideas (
id INTEGER PRIMARY KEY AUTOINCREMENT,
text TEXT NOT NULL,
category TEXT NOT NULL DEFAULT 'General',
votes INTEGER NOT NULL DEFAULT 0,
hidden INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
export default db
CREATE TABLE IF NOT EXISTS vote_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
idea_id INTEGER NOT NULL REFERENCES ideas(id) ON DELETE CASCADE,
voter_hash TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
UNIQUE(idea_id, voter_hash)
);
CREATE TABLE IF NOT EXISTS sessions (
token TEXT PRIMARY KEY,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
expires_at TEXT NOT NULL
);
`)
return _db
}