import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' import path from 'node:path' import crypto from 'node:crypto' export interface Config { dataDir: string artworkDir: string dbPath: string port: number sessionSecret: string } export function loadConfig(env: Record = process.env): Config { const dataDir = env.DATA_DIR ?? path.resolve('data') mkdirSync(dataDir, { recursive: true }) const artworkDir = path.join(dataDir, 'artwork-cache') mkdirSync(artworkDir, { recursive: true }) return { dataDir, artworkDir, dbPath: path.join(dataDir, 'record-shop.db'), port: Number(env.PORT ?? 3000), sessionSecret: getOrCreateSecret(dataDir), } } function getOrCreateSecret(dataDir: string): string { const secretPath = path.join(dataDir, 'session-secret') try { const existing = readFileSync(secretPath, 'utf8').trim() if (existing) return existing } catch { // first boot — create below } const secret = crypto.randomBytes(32).toString('hex') writeFileSync(secretPath, secret, { mode: 0o600 }) return secret }