import { NextRequest, NextResponse } from 'next/server'; import { isSecureCookie, resetCookieName } from '@/core/lib/auth-cookie'; import { isPlausibleResetToken } from '@/core/lib/reset-token'; const RESET_TOKEN_COOKIE = resetCookieName(); const RESET_TOKEN_MAX_AGE = 10 * 60; // 10 minutes function isSecure(): boolean { return isSecureCookie(); } /** * Password-reset callback handler. * The email link lands on /reset-password?token=..., whose server component * redirects here so the token can be moved into a cookie. * We store the token in an httpOnly cookie and redirect to /reset-password (clean URL). * This mirrors the OAuth callback pattern — the token never reaches client JS. * * CF-085: only a token of the shape the backend issues is stored. Anything else (`?token=abc`, a 10 KB * string) sets NO cookie and lands on /reset-password, which then shows the "invalid link" state. * This is a shape check only: see `core/lib/reset-token.ts` for why the token cannot be bound to a * reset requested in this browser. */ export async function GET(request: NextRequest) { const { searchParams } = request.nextUrl; const token = searchParams.get('token'); if (!token) { const redirectUrl = new URL('/forgot-password', request.url); return NextResponse.redirect(redirectUrl); } const redirectUrl = new URL('/reset-password', request.url); const response = NextResponse.redirect(redirectUrl); // Prevent token leaking via Referer header response.headers.set('Referrer-Policy', 'no-referrer'); if (!isPlausibleResetToken(token)) return response; // Set httpOnly cookie with the reset token (short-lived) response.cookies.set(RESET_TOKEN_COOKIE, token, { httpOnly: true, secure: isSecure(), sameSite: 'lax', path: '/', maxAge: RESET_TOKEN_MAX_AGE, }); return response; }