52 lines
2.2 KiB
TypeScript
52 lines
2.2 KiB
TypeScript
// 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 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 (providerError || !code || !state) {
|
|
return settingsRedirect(state, "error");
|
|
}
|
|
try {
|
|
const { tenantSlug } = await 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 <main data-ui-id="ui.email.oauth.callback.google" />;
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|