// AK-P16a · Google OAuth callback (M25 Block C). NOT tenant-scoped — EXT-10
// registered exactly this URI; the tenant + user travel in the signed `state`.
// Exchanges the code, seals the tokens, upserts the per-user connection, then
// redirects back to the tenant's calendar settings. CSRF/replay is bounded by the
// HMAC-signed, 10-minute state token (verified inside completeOAuthCallback).
import { type LoaderFunctionArgs, redirect } from "react-router";
import { completeOAuthCallback } from "~/modules/calendar/services/CalendarConnectionService.server";
import { syncConnection } from "~/modules/calendar/services/CalendarSyncService.server";
import { verifyCalendarOAuthState } from "~/modules/calendar/services/oauthState.server";
import { calendarConnectionsPath } from "~/modules/calendar/routes/calendarRoutePaths";
import { runAuthenticatedProviderOAuthCallback } from "~/utils/integrations/providerOAuthCallbackAccess.server";
import ServerError from "~/components/ui/errors/ServerError";
function settingsRedirect(state: string | null, messageKey: string): 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 = verifyCalendarOAuthState(state);
if (verified.ok) {
return redirect(`${calendarConnectionsPath(verified.payload.tenantSlug)}?toast=${encodeURIComponent(messageKey)}`);
}
}
return redirect("/");
}
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, "calendar.toast.connectFailed");
}
const verified = verifyCalendarOAuthState(state);
if (!verified.ok || providerError || !code) return settingsRedirect(state, "calendar.toast.connectFailed");
try {
const { tenantSlug } = await runAuthenticatedProviderOAuthCallback({
request,
tenantId: verified.payload.tenantId,
userId: verified.payload.userId,
callback: async () => {
const completed = await completeOAuthCallback({ code, state });
// Best-effort initial pull so the calendar is populated right after connect.
await syncConnection(completed.tenantId, completed.connectionId).catch(() => undefined);
return completed;
},
});
return redirect(`${calendarConnectionsPath(tenantSlug)}?toast=${encodeURIComponent("calendar.toast.connected")}`);
} catch {
return settingsRedirect(state, "calendar.toast.connectFailed");
}
};
export default function GoogleOAuthCallbackRoute() {
// The loader always redirects; this renders only if navigated to without flow.
return ;
}
export function ErrorBoundary() {
return ;
}