46 lines
2.0 KiB
TypeScript
46 lines
2.0 KiB
TypeScript
// 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 { findConnectionByWebhookSubscription, 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;
|
|
}
|
|
|
|
const connection = await findConnectionByWebhookSubscription(channelId);
|
|
// The channel token is the connection id (set at subscribe time). Verify it
|
|
// matches the resolved connection — a mismatch is a spoofed/stale channel.
|
|
if (!connection || connection.id !== channelToken) {
|
|
return OK;
|
|
}
|
|
|
|
// `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;
|