68 lines
2.6 KiB
TypeScript
68 lines
2.6 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 { findMailboxByEmailAddress, 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 mailbox = await findMailboxByEmailAddress("gmail", payload.emailAddress);
|
|
if (!mailbox) {
|
|
return OK;
|
|
}
|
|
await recordEmailWebhookEvent({
|
|
tenantId: mailbox.tenantId,
|
|
mailboxId: mailbox.id,
|
|
provider: "gmail",
|
|
notificationPayload: { emailAddress: payload.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;
|