// VA-P23 ยท Gmail Pub/Sub push webhook (M09 Block D). PUBLIC endpoint (Google's // Pub/Sub posts here, no user auth). Security = a shared verification token in // the query string (GOOGLE_GMAIL_PUBSUB_VERIFICATION_TOKEN, configured on the // push subscription) โ€” Gmail pushes carry only {emailAddress, historyId}, so // there is no per-mailbox secret to echo. We resolve the mailbox by address, // persist the notification as `pending` and return 200 FAST; the worker drain // cron runs the incremental history sync. Unknown addresses/bad tokens are // ack'd (204/200) so Pub/Sub does not retry-storm us โ€” nothing is persisted. import { type ActionFunctionArgs } from "react-router"; import { resolveGmailMailboxRlsIdentities } from "@hivegrid/db/rls-resolvers.server"; import { runWithRlsContext } from "@hivegrid/db/rls-context.server"; import { getGmailWebhookMailbox, recordEmailWebhookEvent } from "~/modules/emailInbox/db/emailInbox.db.server"; const OK = new Response(null, { status: 200 }); interface PubSubPushBody { message?: { data?: string; messageId?: string }; subscription?: string; } function decodePubSubData(data: string | undefined): { emailAddress?: string; historyId?: number | string } | null { if (!data) return null; try { const pad = data.length % 4 === 0 ? "" : "=".repeat(4 - (data.length % 4)); const json = Buffer.from(data.replace(/-/g, "+").replace(/_/g, "/") + pad, "base64").toString("utf8"); return JSON.parse(json) as { emailAddress?: string; historyId?: number | string }; } catch { return null; } } export const action = async ({ request }: ActionFunctionArgs) => { if (request.method !== "POST") { return new Response(null, { status: 405 }); } const expectedToken = process.env.GOOGLE_GMAIL_PUBSUB_VERIFICATION_TOKEN; const token = new URL(request.url).searchParams.get("token"); if (!expectedToken || token !== expectedToken) { // Ack without persisting โ€” a NACK would make Pub/Sub retry forever. return OK; } let body: PubSubPushBody; try { body = (await request.json()) as PubSubPushBody; } catch { return OK; } const payload = decodePubSubData(body.message?.data); if (!payload?.emailAddress) { return OK; } const emailAddress = payload.emailAddress.trim().toLowerCase(); if (!emailAddress || emailAddress.length > 320) { return OK; } let identities: Awaited>; try { identities = await resolveGmailMailboxRlsIdentities("gmail", emailAddress); } catch { return OK; } for (const identity of identities) { await runWithRlsContext({ tenantId: identity.tenantId, userId: identity.userId }, async () => { const mailbox = await getGmailWebhookMailbox({ tenantId: identity.tenantId, ownerUserId: identity.userId, mailboxId: identity.resourceId, emailAddress, }); if (!mailbox) return; await recordEmailWebhookEvent({ tenantId: mailbox.tenantId, mailboxId: mailbox.id, provider: "gmail", notificationPayload: { emailAddress, historyId: String(payload.historyId ?? ""), pubsubMessageId: body.message?.messageId ?? null }, }); }); } return OK; }; // Resource route: no default component. A GET (e.g. health probe) just 200s. export const loader = () => OK;