41 lines
1.4 KiB
TypeScript
41 lines
1.4 KiB
TypeScript
|
|
// app/api/auth/login/route.ts
|
||
|
|
// POST — exchanges APP_PASSWORD for a signed session cookie.
|
||
|
|
//
|
||
|
|
// This is the only place the password is compared, and it happens entirely
|
||
|
|
// on the server. The password is never sent anywhere except this app.
|
||
|
|
|
||
|
|
import { NextRequest, NextResponse } from "next/server";
|
||
|
|
import { createSessionToken, secretsMatch, SESSION_COOKIE, SESSION_TTL_SECONDS, sessionCookieOptions } from "@/lib/auth";
|
||
|
|
|
||
|
|
export const dynamic = "force-dynamic";
|
||
|
|
|
||
|
|
export async function POST(req: NextRequest) {
|
||
|
|
const expected = process.env.APP_PASSWORD;
|
||
|
|
const secret = process.env.AUTH_SECRET;
|
||
|
|
|
||
|
|
if (!expected || !secret) {
|
||
|
|
return NextResponse.json(
|
||
|
|
{ error: "Login is not configured. Set APP_PASSWORD and AUTH_SECRET." },
|
||
|
|
{ status: 503 }
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
let password = "";
|
||
|
|
try {
|
||
|
|
const body = await req.json();
|
||
|
|
if (typeof body?.password === "string") password = body.password;
|
||
|
|
} catch {
|
||
|
|
// fall through — empty password will simply fail the check
|
||
|
|
}
|
||
|
|
|
||
|
|
if (!secretsMatch(password, expected)) {
|
||
|
|
// Slow down online guessing; a wrong guess costs the caller ~0.6s.
|
||
|
|
await new Promise((r) => setTimeout(r, 600));
|
||
|
|
return NextResponse.json({ error: "Wrong password." }, { status: 401 });
|
||
|
|
}
|
||
|
|
|
||
|
|
const token = await createSessionToken(secret);
|
||
|
|
const res = NextResponse.json({ ok: true });
|
||
|
|
res.cookies.set(SESSION_COOKIE, token, sessionCookieOptions(req, SESSION_TTL_SECONDS));
|
||
|
|
return res;
|
||
|
|
}
|