// AK-P16a · Google Calendar push webhook (M25 Block E). PUBLIC endpoint (Google // posts here, no user auth). Security = the per-connection channel token echoed in // X-Goog-Channel-Token, which must match the connection the channel id resolves to. // We persist the notification as `pending` and return 200 FAST (Google's <10s // limit); a worker cron drains pending rows and runs the incremental sync. This // keeps the request handler trivial and idempotent. import { type ActionFunctionArgs } from "react-router"; import { resolveCalendarWebhookRlsIdentity } from "@hivegrid/db/rls-resolvers.server"; import { runWithRlsContext } from "@hivegrid/db/rls-context.server"; import { getGoogleWebhookConnection, recordWebhookEvent } from "~/modules/calendar/db/calendar.db.server"; const OK = new Response(null, { status: 200 }); export const action = async ({ request }: ActionFunctionArgs) => { if (request.method !== "POST") { return new Response(null, { status: 405 }); } const channelId = request.headers.get("x-goog-channel-id"); const channelToken = request.headers.get("x-goog-channel-token"); const resourceState = request.headers.get("x-goog-resource-state"); if (!channelId || !channelToken) { // Malformed notification — ack anyway so Google does not retry-storm us. return OK; } let identity: Awaited>; try { identity = await resolveCalendarWebhookRlsIdentity(channelId, channelToken); } catch { return OK; } if (!identity) { return OK; } await runWithRlsContext({ tenantId: identity.tenantId, userId: identity.userId }, async () => { const connection = await getGoogleWebhookConnection({ tenantId: identity.tenantId, userId: identity.userId, connectionId: identity.resourceId, channelId, channelToken, }); if (!connection) return; // `sync` is Google's initial handshake ping (no change) — nothing to enqueue. if (resourceState && resourceState !== "sync") { await recordWebhookEvent({ tenantId: connection.tenantId, connectionId: connection.id, notificationPayload: { channelId, resourceState, resourceId: request.headers.get("x-goog-resource-id") }, externalResourceState: resourceState, }); } }); return OK; }; // Resource route: no default component. A GET (e.g. health probe) just 200s. export const loader = () => OK;