Become a Pro / website · becomeapro.ai / src / lib / provider-sign-in.ts
| 1 | import { createHash, randomBytes } from "node:crypto"; |
| 2 | import type { AuthDatabase, ProviderIDs, createResourceAuth } from "./d1-auth.ts"; |
| 3 | |
| 4 | const cookieName = "__Host-airesource-login"; |
| 5 | const challengeAge = 600; |
| 6 | const digest = (nonce: string) => createHash("sha256").update(nonce).digest("hex"); |
| 7 | |
| 8 | const json = (data: unknown, status: number, headers = new Headers()) => { |
| 9 | headers.set("Cache-Control", "no-store"); |
| 10 | return Response.json(data, { status, headers }); |
| 11 | }; |
| 12 | const challengeCookie = (nonce: string, age: number) => |
| 13 | `${cookieName}=${nonce}; Path=/; Max-Age=${age}; Secure; HttpOnly; SameSite=Strict`; |
| 14 | |
| 15 | export async function browserSignIn( |
| 16 | request: Request, |
| 17 | { db, origin, providers, auth }: { |
| 18 | db: AuthDatabase; |
| 19 | origin: string; |
| 20 | providers: ProviderIDs; |
| 21 | auth: ReturnType<typeof createResourceAuth>; |
| 22 | }, |
| 23 | ) { |
| 24 | if (request.headers.get("origin") !== origin) return json({ error: "Sign-in origin rejected." }, 403); |
| 25 | const now = Math.floor(Date.now() / 1000); |
| 26 | if (new URL(request.url).pathname.endsWith("/challenge")) { |
| 27 | const nonce = randomBytes(32).toString("hex"); |
| 28 | const headers = new Headers({ "Set-Cookie": challengeCookie(nonce, challengeAge) }); |
| 29 | await db.batch([ |
| 30 | db.prepare("DELETE FROM sign_in_challenge WHERE expires_at <= ?").bind(now), |
| 31 | db.prepare("INSERT INTO sign_in_challenge (digest, expires_at) VALUES (?, ?)").bind(digest(nonce), now + challengeAge), |
| 32 | ]); |
| 33 | return json({ nonce, providers, appleReturnURL: origin + "/api/auth/callback/apple" }, 200, headers); |
| 34 | } |
| 35 | |
| 36 | if (!request.headers.get("content-type")?.startsWith("application/json") |
| 37 | || Number(request.headers.get("content-length")) > 20_000) return json({ error: "Invalid sign-in request." }, 400); |
| 38 | const payload = await request.json().catch(() => null) as { provider?: unknown; token?: unknown } | null; |
| 39 | const provider = payload?.provider; |
| 40 | const token = payload?.token; |
| 41 | if ((provider !== "google" && provider !== "apple") || typeof token !== "string" || token.length > 16_000 |
| 42 | || !/^[\w-]+\.[\w-]+\.[\w-]+$/.test(token)) return json({ error: "Invalid sign-in request." }, 400); |
| 43 | |
| 44 | const nonce = request.headers.get("cookie")?.split(";").map(value => value.trim()) |
| 45 | .find(value => value.startsWith(cookieName + "="))?.slice(cookieName.length + 1); |
| 46 | if (!nonce || !/^[a-f0-9]{64}$/.test(nonce)) return json({ error: "Sign-in expired. Try again." }, 401); |
| 47 | const used = await db.prepare("DELETE FROM sign_in_challenge WHERE digest = ? AND expires_at > ? RETURNING digest") |
| 48 | .bind(digest(nonce), now).first(); |
| 49 | if (!used) return json({ error: "Sign-in expired. Try again." }, 401); |
| 50 | const responseHeaders = new Headers({ "Set-Cookie": challengeCookie("", 0) }); |
| 51 | // The public sign-in route is closed. Better Auth verifies provider signatures, |
| 52 | // audience, issuer, freshness and this single-use server nonce before creating a session. |
| 53 | const response = await auth.api.signInSocial({ |
| 54 | headers: request.headers, |
| 55 | body: { provider, idToken: { token, nonce } }, |
| 56 | asResponse: true, |
| 57 | }); |
| 58 | if (!response.ok) return json({ error: "Sign-in couldn’t be verified. Try again." }, response.status, responseHeaders); |
| 59 | for (const cookie of response.headers.getSetCookie()) responseHeaders.append("Set-Cookie", cookie); |
| 60 | return json({ signedIn: true }, 200, responseHeaders); |
| 61 | } |