import { createHash, randomBytes } from "node:crypto"; import type { AuthDatabase, ProviderIDs, createResourceAuth } from "./d1-auth.ts"; const cookieName = "__Host-airesource-login"; const challengeAge = 600; const digest = (nonce: string) => createHash("sha256").update(nonce).digest("hex"); const json = (data: unknown, status: number, headers = new Headers()) => { headers.set("Cache-Control", "no-store"); return Response.json(data, { status, headers }); }; const challengeCookie = (nonce: string, age: number) => `${cookieName}=${nonce}; Path=/; Max-Age=${age}; Secure; HttpOnly; SameSite=Strict`; export async function browserSignIn( request: Request, { db, origin, providers, auth }: { db: AuthDatabase; origin: string; providers: ProviderIDs; auth: ReturnType; }, ) { if (request.headers.get("origin") !== origin) return json({ error: "Sign-in origin rejected." }, 403); const now = Math.floor(Date.now() / 1000); if (new URL(request.url).pathname.endsWith("/challenge")) { const nonce = randomBytes(32).toString("hex"); const headers = new Headers({ "Set-Cookie": challengeCookie(nonce, challengeAge) }); await db.batch([ db.prepare("DELETE FROM sign_in_challenge WHERE expires_at <= ?").bind(now), db.prepare("INSERT INTO sign_in_challenge (digest, expires_at) VALUES (?, ?)").bind(digest(nonce), now + challengeAge), ]); return json({ nonce, providers, appleReturnURL: origin + "/api/auth/callback/apple" }, 200, headers); } if (!request.headers.get("content-type")?.startsWith("application/json") || Number(request.headers.get("content-length")) > 20_000) return json({ error: "Invalid sign-in request." }, 400); const payload = await request.json().catch(() => null) as { provider?: unknown; token?: unknown } | null; const provider = payload?.provider; const token = payload?.token; if ((provider !== "google" && provider !== "apple") || typeof token !== "string" || token.length > 16_000 || !/^[\w-]+\.[\w-]+\.[\w-]+$/.test(token)) return json({ error: "Invalid sign-in request." }, 400); const nonce = request.headers.get("cookie")?.split(";").map(value => value.trim()) .find(value => value.startsWith(cookieName + "="))?.slice(cookieName.length + 1); if (!nonce || !/^[a-f0-9]{64}$/.test(nonce)) return json({ error: "Sign-in expired. Try again." }, 401); const used = await db.prepare("DELETE FROM sign_in_challenge WHERE digest = ? AND expires_at > ? RETURNING digest") .bind(digest(nonce), now).first(); if (!used) return json({ error: "Sign-in expired. Try again." }, 401); const responseHeaders = new Headers({ "Set-Cookie": challengeCookie("", 0) }); // The public sign-in route is closed. Better Auth verifies provider signatures, // audience, issuer, freshness and this single-use server nonce before creating a session. const response = await auth.api.signInSocial({ headers: request.headers, body: { provider, idToken: { token, nonce } }, asResponse: true, }); if (!response.ok) return json({ error: "Sign-in couldn’t be verified. Try again." }, response.status, responseHeaders); for (const cookie of response.headers.getSetCookie()) responseHeaders.append("Set-Cookie", cookie); return json({ signedIn: true }, 200, responseHeaders); }