import { isAdminNetworkAllowed, json, MIN_PASSWORD_LENGTH, readJsonBody, sameOrigin, setPassword } from "../../../_lib/auth"; import { readAuth } from "../../../_lib/store"; export const dynamic = "force-dynamic"; /** First-run only: sets the admin password when none exists yet. */ export async function POST(request: Request) { if (!isAdminNetworkAllowed(request.headers)) return json({ error: "Admin is only available on the home network." }, 403); if (!sameOrigin(request)) return json({ error: "Cross-origin request refused." }, 403); if ((await readAuth()).passwordHash) return json({ error: "A password is already set. Sign in instead." }, 409); const body = await readJsonBody<{ password?: string }>(request); const password = typeof body?.password === "string" ? body.password : ""; if (password.length < MIN_PASSWORD_LENGTH || password.length > 256) { return json({ error: `Use at least ${MIN_PASSWORD_LENGTH} characters.` }, 400); } return json({ ok: true }, 200, { "Set-Cookie": await setPassword(password) }); }