import { randomBytes, timingSafeEqual } from 'node:crypto'; import { env } from '../config/env.js'; /** * Bootstrap access to the configuration wizard (M16-T09). * * Before `.env` exists there is no Discord application to log in with, so the * wizard accepts a single shared token: either `WEB_SETUP_TOKEN`, or one * generated for the lifetime of `npm run setup` and printed in the console. */ let runtimeToken = null; export function generateRuntimeSetupToken() { runtimeToken = randomBytes(24).toString('base64url'); return runtimeToken; } export function hasSetupToken() { return Boolean(env.web.setupToken || runtimeToken); } export function isSetupTokenValid(candidate) { const value = String(candidate ?? ''); if (value.length === 0) return false; return [env.web.setupToken, runtimeToken].filter(Boolean).some((expected) => { const a = Buffer.from(expected); const b = Buffer.from(value); return a.length === b.length && timingSafeEqual(a, b); }); }