/** * Browser helpers: mint / clear / read first-party portal session after any login method. */ export type AuthMethod = "email" | "wallet" | "konnos" | "demo"; export function userIdFromEngineBody( data: Record, ): string | null { const user = data.user as { id?: string } | undefined; const session = data.session as { userId?: string } | undefined; const id = user?.id || session?.userId || (typeof data.userId === "string" ? data.userId : null); return id || null; } export async function establishPortalSession(input: { userId: string; email?: string; method?: AuthMethod; walletAddress?: string; }): Promise { if (typeof window === "undefined") return; try { await fetch("/api/session", { method: "POST", credentials: "include", headers: { "content-type": "application/json" }, body: JSON.stringify({ userId: input.userId, email: input.email, method: input.method ?? "email", walletAddress: input.walletAddress, }), }); } catch { /* soft gate */ } } export async function clearPortalSession(): Promise { if (typeof window === "undefined") return; try { await fetch("/api/session", { method: "DELETE", credentials: "include" }); } catch { /* ignore */ } } export type PortalSessionState = | { authenticated: true; userId: string; email?: string | null; method?: AuthMethod | null; walletAddress?: string | null; } | { authenticated: false }; export async function fetchPortalSession(): Promise { try { const res = await fetch("/api/session", { credentials: "include" }); const data = (await res.json()) as { authenticated?: boolean; userId?: string; email?: string | null; method?: AuthMethod | null; walletAddress?: string | null; }; if (data.authenticated && data.userId) { let email: string | null = data.email ?? null; let method: AuthMethod | null = data.method ?? null; let walletAddress: string | null = data.walletAddress ?? null; if (typeof document !== "undefined") { const em = document.cookie.match(/(?:^|;\s*)krypco_email=([^;]+)/); if (!email && em?.[1]) email = decodeURIComponent(em[1]); const m = document.cookie.match(/(?:^|;\s*)krypco_method=([^;]+)/); if (!method && m?.[1]) method = decodeURIComponent(m[1]) as AuthMethod; const w = document.cookie.match(/(?:^|;\s*)krypco_wallet=([^;]+)/); if (!walletAddress && w?.[1]) walletAddress = decodeURIComponent(w[1]); } return { authenticated: true, userId: data.userId, email, method, walletAddress, }; } return { authenticated: false }; } catch { return { authenticated: false }; } }