import { NextRequest, NextResponse } from 'next/server'; import { REFERRAL_COOKIE } from '@/core/lib/referral'; import { LEGACY_TOKEN_COOKIE, LOGGED_IN_COOKIE, expireCookie, isSecureCookie, oauthNonceCookieName, tokenCookieName, } from '@/core/lib/auth-cookie'; import { OAUTH_NONCE_PARAM, oauthNonceMatches, safeOAuthErrorCode } from '@/core/lib/oauth-nonce'; const TOKEN_COOKIE = tokenCookieName(); const NONCE_COOKIE = oauthNonceCookieName(); const COOKIE_MAX_AGE = 7 * 24 * 60 * 60; // 7 days const BACKEND_URL = (process.env.BRAINERCE_API_URL || 'https://api.brainerce.com').replace( /\/$/, '' ); function isSecure(): boolean { return isSecureCookie(); } /** * Forward a failure to the client callback page as a stable snake_case code. * * The backend uses the RFC 6749 §4.1.2.1 shape (`oauth_error` = code, * `error_description` = English developer detail), so codes are what the page * switches on to pick localized copy. The description is deliberately NOT * forwarded — it is not shopper-facing copy. The code itself is only forwarded * when it is a plain snake_case identifier (anything else becomes `server_error`), * because this URL is reachable by anyone. */ function errorRedirect(base: URL, code: string, spendNonce: boolean): NextResponse { base.searchParams.set('oauth_error', safeOAuthErrorCode(code)); const response = NextResponse.redirect(base); if (spendNonce) expireCookie(response.cookies, NONCE_COOKIE); response.headers.set('Referrer-Policy', 'no-referrer'); return response; } /** * OAuth callback handler. * * The backend redirects here with ?oauth_success=true&auth_code=&n=. * We exchange the auth_code for the real JWT via a server-to-server POST (so the * JWT never appears in any URL), then set an httpOnly cookie and redirect to the * client-side callback page. * * ⛔ CF-070 (login CSRF): the auth_code is a bearer value in a URL, so the request is only honoured when * the `n` it carries (put on the redirectUrl by the login button, stored and echoed back by the backend) * equals the nonce cookie that `/api/auth/oauth-state` set in THIS browser. A callback link built in * someone else's browser has no matching cookie and ends in `oauth_error=invalid_state` before the * code is ever exchanged. A request that does not match leaves the cookie alone, so a forged link cannot * break a shopper's own login in progress; a matching request spends it. See `core/lib/oauth-nonce.ts`. */ export async function GET(request: NextRequest) { const { searchParams } = request.nextUrl; const authCode = searchParams.get('auth_code'); const oauthSuccess = searchParams.get('oauth_success'); const oauthError = searchParams.get('oauth_error'); const nonceMatches = oauthNonceMatches( request.cookies.get(NONCE_COOKIE)?.value, searchParams.get(OAUTH_NONCE_PARAM) ); const redirectUrl = new URL('/auth/callback', request.url); if (oauthError) { return errorRedirect(redirectUrl, oauthError, nonceMatches); } if (oauthSuccess !== 'true' || !authCode) { return errorRedirect(redirectUrl, 'invalid_request', nonceMatches); } // Not started in this browser (or the nonce expired): do not exchange the code, do not set a session. if (!nonceMatches) { return errorRedirect(redirectUrl, 'invalid_state', false); } // Exchange the one-time auth_code for the real JWT. // This is a server-to-server call — the JWT never enters the browser URL. let token: string; try { const exchangeRes = await fetch(`${BACKEND_URL}/api/oauth/customer/exchange`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code: authCode }), }); if (!exchangeRes.ok) { throw new Error(`exchange responded ${exchangeRes.status}`); } const data = await exchangeRes.json(); if (!data.token) throw new Error('missing token in exchange response'); token = data.token; } catch (err) { console.error('[oauth-callback] auth_code exchange failed:', err); return errorRedirect(redirectUrl, 'server_error', true); } redirectUrl.searchParams.set('oauth_success', 'true'); const response = NextResponse.redirect(redirectUrl); // The nonce is spent: one login per start. expireCookie(response.cookies, NONCE_COOKIE); // A session from before the `__Host-` prefix must not survive next to the new one. if (TOKEN_COOKIE !== LEGACY_TOKEN_COOKIE) expireCookie(response.cookies, LEGACY_TOKEN_COOKIE); response.cookies.set(TOKEN_COOKIE, token, { httpOnly: true, secure: isSecure(), sameSite: 'lax', path: '/', maxAge: COOKIE_MAX_AGE, }); // NOT a secret, and deliberately readable by the browser (httpOnly: false): the constant "1", a // "someone is logged in" hint so the storefront can render the signed-in UI (account link, wishlist // source) before /api/auth/me answers. It carries no token and grants nothing; the real // credential is the httpOnly cookie above, and the server never trusts this one. response.cookies.set(LOGGED_IN_COOKIE, '1', { httpOnly: false, secure: isSecure(), sameSite: 'lax', path: '/', maxAge: COOKIE_MAX_AGE, }); // The referral code rode the OAuth state and is now spent (or ignored, for // an existing customer). Drop it so the next account created in this // browser is not attributed to the same referrer — same as /register does. response.cookies.set(REFERRAL_COOKIE, '', { path: '/', maxAge: 0, sameSite: 'lax' }); response.headers.set('Referrer-Policy', 'no-referrer'); return response; }