Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/routes/webhooks.email.google.tsx
T

87 lines
3.3 KiB
TypeScript

// 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<ReturnType<typeof resolveGmailMailboxRlsIdentities>>;
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;