middleware.ts previously 404'd every external request, which meant the app was unusable once hosted. There are no per-user accounts, so this adds a single-password gate: - /login page + POST /api/auth/login, POST /api/auth/logout - lib/auth.ts: HMAC-SHA256 signed session cookie (lib/auth), Web Crypto only so the same code runs in Edge middleware and Node handlers - middleware now admits: the signing flow (unchanged, still public), /login + /api/auth/*, local requests, and valid sessions. Everything else redirects to /login (pages) or returns 401 JSON (API calls). - password compared with a constant-time compare, wrong attempts delayed 600ms to slow online guessing - cookie is HttpOnly + SameSite=Lax, 12h, Secure when x-forwarded-proto says https (Coolify serves the proxy on http today) APP_PASSWORD / AUTH_SECRET added to .env.example, with a warning: an unquoted # in an env value starts a comment, which silently truncated the first generated password and made login fail. Verified against a real built server: anon->307 /login, anon API->401, wrong password->401, correct password->200+cookie, signed-in request reaches PocketBase, /resign/ still 200 without a cookie, forged cookie->401.
41 lines
No EOL
1.4 KiB
TypeScript
41 lines
No EOL
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;
|
|
} |