import { NextRequest, NextResponse } from "next/server"; import { getPocketBaseConfig } from "@/config/services.config"; import { COOKIE_NAME, getCookieOptions, getHostFromRequest, } from "@/app/lib/auth-cookie"; function normalizeAnonymousUserId(value: unknown): string | undefined { return typeof value === "string" && /^user\d+$/.test(value) ? value : undefined; } export async function GET(request: NextRequest) { const cookie = request.cookies.get(COOKIE_NAME)?.value; if (!cookie) { return NextResponse.json({ ok: true, user: null }); } try { const payload = JSON.parse(Buffer.from(cookie, "base64url").toString("utf-8")); const { token, userId, email, anonymousUserId } = payload; const normalizedAnonymousUserId = normalizeAnonymousUserId(anonymousUserId); if (!token || !userId) { return NextResponse.json({ ok: true, user: null }); } const pb = getPocketBaseConfig(); const res = await fetch(`${pb.url}/api/collections/users/auth-refresh`, { method: "POST", headers: { Authorization: `Bearer ${token}` }, }); if (!res.ok) { const response = NextResponse.json({ ok: true, user: null }); response.cookies.set( COOKIE_NAME, "", getCookieOptions(true, getHostFromRequest(request)) as Record< string, string | number | boolean > ); return response; } const data = await res.json(); const newToken = data.token; const newRecord = data.record; if (newToken && newRecord?.id) { const nextPayload: Record = { token: newToken, userId: newRecord.id, email: newRecord.email ?? email, }; if (normalizedAnonymousUserId) { nextPayload.anonymousUserId = normalizedAnonymousUserId; } const encoded = Buffer.from(JSON.stringify(nextPayload), "utf-8").toString( "base64url" ); const response = NextResponse.json({ ok: true, user: { id: newRecord.id, email: newRecord.email ?? email, anonymousUserId: normalizedAnonymousUserId, }, token: newToken, }); response.cookies.set( COOKIE_NAME, encoded, getCookieOptions(false, getHostFromRequest(request)) as Record< string, string | number | boolean > ); return response; } return NextResponse.json({ ok: true, user: { id: data.record?.id ?? userId, email: data.record?.email ?? email, anonymousUserId: normalizedAnonymousUserId, }, token: data.token, }); } catch { return NextResponse.json({ ok: true, user: null }); } }