// VA-P23 · Gmail OAuth callback (M09 Block B). NOT tenant-scoped — the Google // app registers exactly this URI; tenant + user + provider travel in the signed // `state`. Exchanges the code, seals the tokens, upserts the per-user mailbox, // then redirects back to the tenant's email settings. CSRF/replay is bounded by // the HMAC-signed, 10-minute, provider-pinned state token. import { type LoaderFunctionArgs, redirect } from "react-router"; import { completeOAuthCallback } from "~/modules/emailInbox/services/MailboxConnectionService.server"; import { verifyEmailOAuthState } from "~/modules/emailInbox/services/oauthState.server"; import { emailSettingsPath } from "~/modules/emailInbox/routes/emailInboxRoutePaths"; import { runAuthenticatedProviderOAuthCallback } from "~/utils/integrations/providerOAuthCallbackAccess.server"; import ServerError from "~/components/ui/errors/ServerError"; function settingsRedirect(state: string | null, flag: "connected" | "error"): Response { // Best-effort: recover the tenant slug from the (verified) state so the user // lands back on their own settings page even on the error path. if (state) { const verified = verifyEmailOAuthState(state, "gmail"); if (verified.ok) { return redirect(`${emailSettingsPath(verified.payload.tenantSlug)}?email=${flag}`); } } return redirect(`/?email=${flag}`); } export const loader = async ({ request }: LoaderFunctionArgs) => { const url = new URL(request.url); const code = url.searchParams.get("code"); const state = url.searchParams.get("state"); const providerError = url.searchParams.get("error"); if (!state) { return settingsRedirect(state, "error"); } const verified = verifyEmailOAuthState(state, "gmail"); if (!verified.ok || providerError || !code) return settingsRedirect(state, "error"); try { const { tenantSlug } = await runAuthenticatedProviderOAuthCallback({ request, tenantId: verified.payload.tenantId, userId: verified.payload.userId, callback: () => completeOAuthCallback({ code, state, provider: "gmail" }), }); // The initial 90-day sync runs in the worker (resumable cursor rows were // created as pending); the settings page shows the progress line. return redirect(`${emailSettingsPath(tenantSlug)}?email=connected`); } catch { return settingsRedirect(state, "error"); } }; export default function GmailOAuthCallbackRoute() { // The loader always redirects; this renders only if navigated to without flow. return
; } export function ErrorBoundary() { return ; }