import { randomUUID } from "node:crypto"; import { getPlatformNotificationStreamSnapshot, markPlatformInAppNotificationDeliveryRead, } from "@hivegrid/db/notifications.server"; import { REALTIME_EVENT_NAMES, serializeRealtimeEvent } from "@hivegrid/realtime"; import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router"; import { platformLeadNotFound, requirePlatformLeadRead, runAsPlatformLeadOperator, } from "~/services/admin/platform-leads.server"; import { validateCSRFToken } from "~/utils/session.server"; const MAX_READ_IDS = 100; const IDENTIFIER_PATTERN = /^[A-Za-z0-9_-]{1,191}$/u; export const loader = async ({ request }: LoaderFunctionArgs) => runAsPlatformLeadOperator(request, async ({ access }) => { requirePlatformLeadRead(access); const requestUrl = new URL(request.url); const rawCursor = request.headers.get("last-event-id") ?? requestUrl.searchParams.get("afterCursor"); const afterCursor = rawCursor?.trim().slice(0, 500) || null; const snapshot = await getPlatformNotificationStreamSnapshot({ userId: access.actorAdminUserId, afterCursor, }); if (snapshot.items.some((item) => item.tenantId !== null || item.userId !== access.actorAdminUserId)) { throw platformLeadNotFound(); } const cursor = snapshot.cursor ?? afterCursor ?? "initial"; const body = serializeRealtimeEvent({ event: REALTIME_EVENT_NAMES.notificationSnapshot, requestId: randomUUID(), tenantId: null, userId: access.actorAdminUserId, cursor, items: snapshot.items, }); return new Response(body, { headers: { "cache-control": "no-cache", "content-type": "text/event-stream; charset=utf-8", "x-content-type-options": "nosniff", }, }); }); export const action = async ({ request }: ActionFunctionArgs) => { await validateCSRFToken(request); const form = await request.formData(); const deliveryIds = [...new Set(form.getAll("deliveryId").map(String).map((value) => value.trim()))]; if (deliveryIds.length > MAX_READ_IDS || deliveryIds.some((id) => !IDENTIFIER_PATTERN.test(id))) { return Response.json({ error: "invalid_request" }, { status: 400 }); } return runAsPlatformLeadOperator(request, async ({ access }) => { requirePlatformLeadRead(access); for (const id of deliveryIds) { await markPlatformInAppNotificationDeliveryRead({ id, userId: access.actorAdminUserId, readAt: new Date(), }); } return Response.json({ ok: true, marked: deliveryIds.length }); }); }; export default function PlatformLeadNotificationStreamRoute(): null { return null; }