// Node-side authentication: the database-stored access key plus route guards. // // The stored key lets someone sign in without touching Space Secrets, while the // Space Secret keeps working for anyone who prefers it (and survives a DB // reset). Either key is accepted everywhere. import { NextResponse } from "next/server"; import { db } from "./db"; import { extractCredential, readSessionToken, verifyApiKey, maskApiKey, type CredentialSource, type SessionLevel, } from "./auth"; import { DEFAULT_USERNAME, envLoginPassword, envUsername, hashPassword, normalizeUsername, safeEqualStrings, shouldResetStoredPassword, verifyPasswordAgainstHash, } from "./password"; export const ACCESS_KEY_SETTING = "access_api_key"; /** Minimum length for a key set through the UI. */ export const MIN_KEY_LENGTH = 8; /** Read the access key stored in the database, if any. */ export async function getStoredApiKey(): Promise { try { const row = await db.setting.findUnique({ where: { key: ACCESS_KEY_SETTING } }); const value = row?.value?.trim(); if (!value || value === "***set***") return null; return value; } catch { return null; } } export async function setStoredApiKey(key: string): Promise { const value = key.trim(); await db.setting.upsert({ where: { key: ACCESS_KEY_SETTING }, create: { key: ACCESS_KEY_SETTING, value }, update: { value }, }); } export async function clearStoredApiKey(): Promise { await db.setting.deleteMany({ where: { key: ACCESS_KEY_SETTING } }); } export async function describeStoredApiKey(): Promise<{ set: boolean; hint: string | null }> { const key = await getStoredApiKey(); return { set: Boolean(key), hint: key ? maskApiKey(key) : null }; } /** Accept an environment key OR the database-stored key. */ export async function verifyAnyKey(candidate: string | null | undefined): Promise< false | "env-key" | "stored-key" > { if (!candidate) return false; if (verifyApiKey(candidate)) return "env-key"; const stored = await getStoredApiKey(); if (stored && stored.length === candidate.length && stored === candidate) { return "stored-key"; } return false; } /** * Full credential check for Node route handlers: signed session cookie, * environment key, or database-stored key. */ export async function verifyRequestFull(req: CredentialSource): Promise<{ ok: boolean; via: "session" | "env-key" | "stored-key" | null; level: SessionLevel | null; }> { const credential = extractCredential(req); if (!credential) return { ok: false, via: null, level: null }; const session = await readSessionToken(credential); if (session.ok) return { ok: true, via: "session", level: session.level }; const keyMatch = await verifyAnyKey(credential); // A raw key (env or in-app) is machine-grade: media yes, web UI no. if (keyMatch) return { ok: true, via: keyMatch, level: "key" }; return { ok: false, via: null, level: null }; } /** * Guard for API routes that middleware forwards without verifying (DEOVR feed, * stream proxy, thumbnails — they may carry a database-stored key that Edge * middleware cannot check). Returns a 401 response, or null when allowed. */ export async function requireApiAuth(req: CredentialSource): Promise { const verdict = await verifyRequestFull(req); if (verdict.ok) return null; return NextResponse.json( { error: "Unauthorized", hint: "Append ?token= or sign in first" }, { status: 401 } ); } // --------------------------------------------------------------------------- // The web UI account: username + password // // The API key is no longer a human credential. Once an account is configured // the browser signs in with username + password, and the server reads the API // key from the Space secret itself - only machines ever present it, as the // ?token= on DEOVR / PLAY'A URLs. // --------------------------------------------------------------------------- export const LOGIN_PASSWORD_SETTING = "login_password_hash"; export const LOGIN_USERNAME_SETTING = "login_username"; export { MIN_PASSWORD_LENGTH, DEFAULT_USERNAME } from "./password"; /** The stored hash, or null. Honours RESET_LOGIN_PASSWORD by deleting it. */ export async function getStoredPasswordHash(): Promise { try { if (shouldResetStoredPassword()) { await db.setting.deleteMany({ where: { key: { in: [LOGIN_PASSWORD_SETTING, LOGIN_USERNAME_SETTING] } }, }); return null; } const row = await db.setting.findUnique({ where: { key: LOGIN_PASSWORD_SETTING } }); const value = row?.value?.trim(); return value && value.startsWith("pbkdf2$") ? value : null; } catch { return null; } } export async function getStoredUsername(): Promise { try { const row = await db.setting.findUnique({ where: { key: LOGIN_USERNAME_SETTING } }); const value = row?.value?.trim(); return value ? value : null; } catch { return null; } } /** Space secret first, then the in-app value, then "admin". */ export async function getExpectedUsername(): Promise { return envUsername() ?? (await getStoredUsername()) ?? DEFAULT_USERNAME; } export async function setLoginPassword(password: string): Promise { const hash = await hashPassword(password); await db.setting.upsert({ where: { key: LOGIN_PASSWORD_SETTING }, create: { key: LOGIN_PASSWORD_SETTING, value: hash }, update: { value: hash }, }); } export async function setLoginUsername(username: string): Promise { const value = username.trim(); if (!value) return; await db.setting.upsert({ where: { key: LOGIN_USERNAME_SETTING }, create: { key: LOGIN_USERNAME_SETTING, value }, update: { value }, }); } /** Remove the in-app account entirely (username and password). */ export async function clearLoginAccount(): Promise { await db.setting.deleteMany({ where: { key: { in: [LOGIN_PASSWORD_SETTING, LOGIN_USERNAME_SETTING] } }, }); } /** Legacy name kept so older call sites keep working. */ export const clearLoginPassword = clearLoginAccount; /** True when the browser must sign in with username + password. */ export async function areCredentialsConfigured(): Promise { if (envLoginPassword()) return true; return (await getStoredPasswordHash()) !== null; } /** Legacy alias - the password is what switches the mode on. */ export const isLoginPasswordRequired = areCredentialsConfigured; export type LoginAccount = { configured: boolean; username: string; usernameSource: "env" | "stored" | "default"; passwordSource: "env" | "stored" | null; /** False while APP_LOGIN_PASSWORD is set: a Space secret always wins. */ changeable: boolean; }; export async function describeLoginAccount(): Promise { const envPassword = envLoginPassword(); const storedHash = envPassword ? null : await getStoredPasswordHash(); const envUser = envUsername(); const storedUser = await getStoredUsername(); return { configured: Boolean(envPassword) || storedHash !== null, username: envUser ?? storedUser ?? DEFAULT_USERNAME, usernameSource: envUser ? "env" : storedUser ? "stored" : "default", passwordSource: envPassword ? "env" : storedHash ? "stored" : null, changeable: !envPassword, }; } /** Legacy shape, still used by the diagnostics rows. */ export async function describeLoginPassword(): Promise<{ required: boolean; source: "env" | "stored" | null; changeable: boolean; }> { const account = await describeLoginAccount(); return { required: account.configured, source: account.passwordSource, changeable: account.changeable, }; } /** Check a password against the Space secret, then the stored hash. */ export async function verifyLoginPassword(candidate: string): Promise { const submitted = candidate.trim(); if (!submitted) return false; const fromEnv = envLoginPassword(); if (fromEnv && safeEqualStrings(submitted, fromEnv)) return true; const stored = await getStoredPasswordHash(); if (stored) return verifyPasswordAgainstHash(submitted, stored); return false; } /** Check the username and password together. Both must match. */ export async function verifyLoginCredentials( username: string, password: string ): Promise { const expected = normalizeUsername(await getExpectedUsername()); const submitted = normalizeUsername(username ?? ""); // Always run the password check too, so a wrong username is not measurably // faster to reject than a wrong password. const passwordOk = await verifyLoginPassword(password ?? ""); return safeEqualStrings(submitted, expected) && passwordOk; }