import { NextRequest, NextResponse } from 'next/server'; import { checkCsrf } from '@/core/lib/csrf'; import { isSecureCookie, oauthNonceCookieName } from '@/core/lib/auth-cookie'; import { OAUTH_NONCE_MAX_AGE, createOAuthNonce } from '@/core/lib/oauth-nonce'; /** * Start of a social login: binds the round trip to THIS browser (CF-070). * * Makes a random nonce, keeps it in an httpOnly cookie and returns it, so the login button can put it on * the `redirectUrl` it gives the backend. `/api/auth/oauth-callback` only turns the one-time `auth_code` * into a session when the nonce on the URL equals this cookie, so a callback link built in someone * else's browser cannot sign a victim in as the attacker. See `core/lib/oauth-nonce.ts`. * * POST + the CSRF header, like every other state-changing route of this app: a cross-site page cannot * make a victim's browser call it (and could not read the answer anyway). */ export async function POST(request: NextRequest) { const csrfError = checkCsrf(request); if (csrfError) return csrfError; const nonce = createOAuthNonce(); const response = NextResponse.json({ nonce }, { headers: { 'Cache-Control': 'no-store' } }); response.cookies.set(oauthNonceCookieName(), nonce, { httpOnly: true, secure: isSecureCookie(), // `lax`, not `strict`: the callback is a top-level navigation that arrives from the backend, which // itself was reached from the provider. A `strict` cookie is not sent on that chain. sameSite: 'lax', path: '/', maxAge: OAUTH_NONCE_MAX_AGE, }); return response; }