68 lines
2.6 KiB
TypeScript
68 lines
2.6 KiB
TypeScript
// VA-P23 · Microsoft Graph change-notification webhook (M09 Block D). PUBLIC
|
|
// endpoint. Two contracts:
|
|
// 1. Validation handshake: Graph POSTs ?validationToken=… and expects the
|
|
// token echoed back as text/plain 200 within 10 seconds.
|
|
// 2. Notifications: each item carries the per-mailbox `clientState` secret —
|
|
// the ONLY auth mechanism — which must equal the stored value on the
|
|
// mailbox the subscription id resolves to. Mismatches are ack'd without
|
|
// persisting (a non-2xx would make Graph retry + eventually kill the
|
|
// subscription). Valid items are persisted `pending`; the worker drain
|
|
// cron runs the per-folder delta sync.
|
|
|
|
import { type ActionFunctionArgs } from "react-router";
|
|
import { findMailboxByWebhookSubscription, recordEmailWebhookEvent } from "~/modules/emailInbox/db/emailInbox.db.server";
|
|
|
|
const ACCEPTED = new Response(null, { status: 202 });
|
|
|
|
interface GraphNotification {
|
|
subscriptionId?: string;
|
|
clientState?: string;
|
|
changeType?: string;
|
|
resource?: string;
|
|
resourceData?: { id?: string };
|
|
}
|
|
|
|
export const action = async ({ request }: ActionFunctionArgs) => {
|
|
if (request.method !== "POST") {
|
|
return new Response(null, { status: 405 });
|
|
}
|
|
// 1) Subscription validation handshake — echo the token as text/plain.
|
|
const validationToken = new URL(request.url).searchParams.get("validationToken");
|
|
if (validationToken) {
|
|
return new Response(validationToken, { status: 200, headers: { "content-type": "text/plain" } });
|
|
}
|
|
|
|
let body: { value?: GraphNotification[] };
|
|
try {
|
|
body = (await request.json()) as { value?: GraphNotification[] };
|
|
} catch {
|
|
return ACCEPTED;
|
|
}
|
|
|
|
for (const notification of body.value ?? []) {
|
|
if (!notification.subscriptionId || !notification.clientState) {
|
|
continue;
|
|
}
|
|
const mailbox = await findMailboxByWebhookSubscription(notification.subscriptionId);
|
|
// clientState is the only auth: constant per mailbox, generated at subscribe.
|
|
if (!mailbox || !mailbox.webhookClientState || mailbox.webhookClientState !== notification.clientState) {
|
|
continue;
|
|
}
|
|
await recordEmailWebhookEvent({
|
|
tenantId: mailbox.tenantId,
|
|
mailboxId: mailbox.id,
|
|
provider: "microsoft",
|
|
notificationPayload: {
|
|
subscriptionId: notification.subscriptionId,
|
|
changeType: notification.changeType ?? null,
|
|
resource: notification.resource ?? null,
|
|
resourceId: notification.resourceData?.id ?? null,
|
|
},
|
|
});
|
|
}
|
|
return ACCEPTED;
|
|
};
|
|
|
|
// Resource route: no default component. A GET (e.g. health probe) just 200s.
|
|
export const loader = () => new Response(null, { status: 200 });
|