import { NextResponse } from "next/server"; import type { NextRequest } from "next/server"; import { PASSCODE_COOKIE_NAME, PASSCODE_PROTECTED_PATHS, emptyPasscodeAccessState, isPasscodeProtectedPath, normalizePath, } from "@/lib/passcode"; /** * /api/passcode — the original site's access endpoint (module 4278 calls it): * GET → current access state, e.g. {"/2026": false} * POST {scope, code} → validate the code, set the access cookie * POST {action: "logout"} → clear the access cookie * * The unlock code itself is a server secret (the original keeps it off the * client bundle). Configure it with PASSCODE_CODE (4 characters, matching * PASSCODE.slotCount); the default mirrors the theme year. */ const PASSCODE_CODE = process.env.PASSCODE_CODE ?? "2026"; const ONE_YEAR = 60 * 60 * 24 * 365; function readAccess(request: NextRequest): Record { const raw = request.cookies.get(PASSCODE_COOKIE_NAME)?.value; if (!raw) return emptyPasscodeAccessState(); try { const parsed = JSON.parse(decodeURIComponent(raw)) as Record; const state = emptyPasscodeAccessState(); for (const key of Object.keys(state)) { state[key] = parsed[key] === true; } return state; } catch { return emptyPasscodeAccessState(); } } export async function GET(request: NextRequest) { return NextResponse.json(readAccess(request)); } export async function POST(request: NextRequest) { let body: { scope?: string; code?: string; action?: string }; try { body = (await request.json()) as typeof body; } catch { return NextResponse.json({ ok: false }, { status: 400 }); } const response = NextResponse.json({ ok: true }); if (body.action === "logout") { response.cookies.delete(PASSCODE_COOKIE_NAME); return response; } const scope = body.scope ? normalizePath(body.scope) : ""; if (!scope || !isPasscodeProtectedPath(scope)) { return NextResponse.json({ ok: false }, { status: 400 }); } if (typeof body.code !== "string" || body.code !== PASSCODE_CODE) { return NextResponse.json({ ok: false }, { status: 401 }); } const access = readAccess(request); access[scope] = true; for (const key of PASSCODE_PROTECTED_PATHS) { if (!(key in access)) access[key] = false; } response.cookies.set({ name: PASSCODE_COOKIE_NAME, value: encodeURIComponent(JSON.stringify(access)), httpOnly: true, sameSite: "lax", path: "/", maxAge: ONE_YEAR, }); return response; }