|
| 1 | +import { |
| 2 | + fetchClerkUserPrimaryEmail, |
| 3 | + fetchClerkUserPrimaryEmailStatus, |
| 4 | + verifyClerkBearerToken, |
| 5 | +} from "@cheatcode/auth"; |
| 6 | +import { createDb, resolveInternalUserId, upsertClerkUser } from "@cheatcode/db"; |
| 7 | +import { resolveWorkerSecret, type WorkerSecret } from "@cheatcode/env"; |
| 8 | +import { APIError } from "@cheatcode/observability"; |
| 9 | +import type { UserId } from "@cheatcode/types"; |
| 10 | + |
| 11 | +/** |
| 12 | + * Narrow env surface the auth helpers depend on. `GatewayEnv` structurally |
| 13 | + * satisfies it, so route handlers keep passing their full `c.env`. |
| 14 | + */ |
| 15 | +export interface AuthEnv { |
| 16 | + CLERK_JWT_KEY?: WorkerSecret; |
| 17 | + CLERK_SECRET_KEY?: WorkerSecret; |
| 18 | + HYPERDRIVE: Hyperdrive; |
| 19 | +} |
| 20 | + |
| 21 | +export async function authenticate( |
| 22 | + request: Request, |
| 23 | + env: AuthEnv, |
| 24 | + ctx: ExecutionContext, |
| 25 | +): Promise<UserId> { |
| 26 | + const jwtKey = await readOptionalSecret(env.CLERK_JWT_KEY, "CLERK_JWT_KEY"); |
| 27 | + const secretKey = await readOptionalSecret(env.CLERK_SECRET_KEY, "CLERK_SECRET_KEY"); |
| 28 | + if (!jwtKey && !secretKey) { |
| 29 | + throw new APIError(503, "unavailable_maintenance", "Clerk verification is not configured", { |
| 30 | + hint: "Set CLERK_JWT_KEY or CLERK_SECRET_KEY in the gateway Worker environment.", |
| 31 | + retriable: false, |
| 32 | + }); |
| 33 | + } |
| 34 | + const verificationOptions: { jwtKey?: string; secretKey?: string } = {}; |
| 35 | + if (jwtKey) { |
| 36 | + verificationOptions.jwtKey = jwtKey; |
| 37 | + } |
| 38 | + if (secretKey) { |
| 39 | + verificationOptions.secretKey = secretKey; |
| 40 | + } |
| 41 | + const session = await verifyClerkBearerToken(request, verificationOptions); |
| 42 | + const { db, close } = createDb(env.HYPERDRIVE); |
| 43 | + try { |
| 44 | + const userId = await resolveInternalUserId(db, session.clerkUserId); |
| 45 | + if (userId) { |
| 46 | + return userId; |
| 47 | + } |
| 48 | + if (!secretKey) { |
| 49 | + throw new APIError(404, "not_found_user", "Authenticated user is not synced", { |
| 50 | + hint: "Wait for the Clerk user.created webhook to finish, then retry.", |
| 51 | + retriable: true, |
| 52 | + }); |
| 53 | + } |
| 54 | + const email = await fetchClerkUserEmail(session.clerkUserId, secretKey); |
| 55 | + if (!email) { |
| 56 | + throw new APIError(404, "not_found_user", "Authenticated user is missing an email", { |
| 57 | + hint: "Add a primary email address to the Clerk user, then retry.", |
| 58 | + retriable: false, |
| 59 | + }); |
| 60 | + } |
| 61 | + const syncedUser = await upsertClerkUser(db, { clerkId: session.clerkUserId, email }); |
| 62 | + return syncedUser.userId; |
| 63 | + } finally { |
| 64 | + ctx.waitUntil(close()); |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +async function fetchClerkUserEmail(clerkUserId: string, secretKey: string): Promise<string | null> { |
| 69 | + try { |
| 70 | + return await fetchClerkUserPrimaryEmail({ clerkUserId, secretKey }); |
| 71 | + } catch { |
| 72 | + throw new APIError(503, "unavailable_maintenance", "Unable to sync Clerk user", { |
| 73 | + hint: "Verify CLERK_SECRET_KEY and Clerk Backend API availability.", |
| 74 | + retriable: true, |
| 75 | + }); |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +export async function requireVerifiedClerkEmail(request: Request, env: AuthEnv): Promise<void> { |
| 80 | + const secretKey = await readRequiredSecret(env.CLERK_SECRET_KEY, "CLERK_SECRET_KEY"); |
| 81 | + const session = await verifyClerkBearerToken(request, { secretKey }); |
| 82 | + const emailStatus = await fetchClerkEmailStatus(session.clerkUserId, secretKey); |
| 83 | + if (emailStatus.verified) { |
| 84 | + return; |
| 85 | + } |
| 86 | + throw new APIError(403, "permission_denied", "Verify your email before starting a sandbox run", { |
| 87 | + details: { email: emailStatus.email }, |
| 88 | + hint: "Complete Clerk email verification, refresh the app, and start the run again.", |
| 89 | + retriable: false, |
| 90 | + }); |
| 91 | +} |
| 92 | + |
| 93 | +async function fetchClerkEmailStatus(clerkUserId: string, secretKey: string) { |
| 94 | + try { |
| 95 | + return await fetchClerkUserPrimaryEmailStatus({ clerkUserId, secretKey }); |
| 96 | + } catch { |
| 97 | + throw new APIError(503, "unavailable_maintenance", "Unable to verify Clerk email status", { |
| 98 | + hint: "Verify CLERK_SECRET_KEY and Clerk Backend API availability.", |
| 99 | + retriable: true, |
| 100 | + }); |
| 101 | + } |
| 102 | +} |
| 103 | + |
| 104 | +export async function readOptionalSecret( |
| 105 | + secret: WorkerSecret | undefined, |
| 106 | + name: string, |
| 107 | +): Promise<string | undefined> { |
| 108 | + try { |
| 109 | + return await resolveWorkerSecret(secret); |
| 110 | + } catch { |
| 111 | + throw new APIError(503, "unavailable_maintenance", `${name} is unavailable`, { |
| 112 | + hint: `Verify the ${name} Cloudflare Secrets Store binding and secret value.`, |
| 113 | + retriable: false, |
| 114 | + }); |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +export async function readRequiredSecret( |
| 119 | + secret: WorkerSecret | undefined, |
| 120 | + name: string, |
| 121 | +): Promise<string> { |
| 122 | + const value = await readOptionalSecret(secret, name); |
| 123 | + if (!value) { |
| 124 | + throw new APIError(503, "unavailable_maintenance", `${name} is not configured`, { |
| 125 | + hint: `Set ${name} in the gateway Worker environment.`, |
| 126 | + retriable: false, |
| 127 | + }); |
| 128 | + } |
| 129 | + return value; |
| 130 | +} |
0 commit comments