import type { JsonValue } from "./errors.js"; export type NotificationInput = { tenantId: string; userId?: string | null; channel?: NotificationPreferenceChannel; category?: string | null; messageKey: string; sourceKey?: string | null; payloadMetadata?: Record | null; }; /** * Operator-wide notifications are deliberately a separate contract from * tenant notifications. Callers cannot provide a tenant scope, and both the * recipient and the producer-stable source key are mandatory. * * `notifyPlatform()` persists the durable delivery intent as PENDING. The * notification worker performs both IN_APP and EMAIL delivery after the * surrounding transaction has committed. */ export type PlatformNotificationInput = { tenantId?: never; userId: string; channel?: NotificationPreferenceChannel; category?: string | null; messageKey: string; sourceKey: string; payloadMetadata?: Record | null; }; export type NotificationPreferenceChannel = "IN_APP" | "EMAIL"; export type NotificationDeliveryStatus = "PENDING" | "SENT" | "FAILED" | "SKIPPED" | "READ"; export type NotificationPayloadMetadata = Record; export type NotificationPreference = { tenantId: string; userId: string; channel: NotificationPreferenceChannel; category: string; enabled: boolean; }; export type NotificationBundle = { tenantId: string; userId: string | null; channel: NotificationPreferenceChannel; category: string; messageKeys: readonly string[]; payloadMetadata: Record; }; export type NotificationClient = { notificationDelivery: { create(args: { data: { tenantId: string | null; userId: string | null; channel: NotificationPreferenceChannel; category: string; messageKey: string; sourceKey: string | null; status: NotificationDeliveryStatus; attemptsMade: number; providerMessageId: string | null; lastError: string | null; payloadMetadata: NotificationPayloadMetadata | null; sentAt: Date | null; readAt: Date | null; }; }): Promise; upsert?(args: { where: { notification_delivery_source_key: { tenantId: string; userId: string; channel: NotificationPreferenceChannel; sourceKey: string; }; }; create: { tenantId: string | null; userId: string | null; channel: NotificationPreferenceChannel; category: string; messageKey: string; sourceKey: string | null; status: NotificationDeliveryStatus; attemptsMade: number; providerMessageId: string | null; lastError: string | null; payloadMetadata: NotificationPayloadMetadata | null; sentAt: Date | null; readAt: Date | null; }; update: { category: string; messageKey: string; status: NotificationDeliveryStatus; attemptsMade: number; providerMessageId: string | null; lastError: string | null; payloadMetadata: NotificationPayloadMetadata | null; sentAt: Date | null; readAt: Date | null; }; }): Promise; }; }; export type PlatformNotificationClient = { notificationDelivery: { findFirst(args: { where: { tenantId: null; userId: string; channel: NotificationPreferenceChannel; sourceKey: string; }; }): Promise; create(args: { data: { tenantId: null; userId: string; channel: NotificationPreferenceChannel; category: string; messageKey: string; sourceKey: string; status: "PENDING"; attemptsMade: 0; providerMessageId: null; lastError: null; payloadMetadata: NotificationPayloadMetadata | null; sentAt: null; readAt: null; }; }): Promise; }; }; export async function notify(input: NotificationInput, client: NotificationClient, preferences: readonly NotificationPreference[] = []): Promise { const tenantId = requireNotificationTenantScope(input.tenantId); const enabled = isNotificationEnabled(input, preferences); const channel = input.channel ?? "IN_APP"; const userId = input.userId ?? null; const sourceKey = normalizeNotificationSourceKey(input.sourceKey); const data = { tenantId, userId, channel, category: normalizeNotificationCategory(input.category), messageKey: input.messageKey, sourceKey, status: enabled ? (channel === "IN_APP" ? ("SENT" as const) : ("PENDING" as const)) : ("SKIPPED" as const), attemptsMade: enabled && channel === "IN_APP" ? 1 : 0, providerMessageId: null, lastError: enabled ? null : "preference_disabled", payloadMetadata: sanitizeNotificationPayloadMetadata(input.payloadMetadata), sentAt: enabled && channel === "IN_APP" ? new Date() : null, readAt: null, }; if (sourceKey && userId && client.notificationDelivery.upsert) { return client.notificationDelivery.upsert({ where: { notification_delivery_source_key: { tenantId, userId, channel, sourceKey, }, }, create: data, update: { category: data.category, messageKey: data.messageKey, status: data.status, attemptsMade: data.attemptsMade, providerMessageId: data.providerMessageId, lastError: data.lastError, payloadMetadata: data.payloadMetadata, sentAt: data.sentAt, readAt: data.readAt, }, }); } return client.notificationDelivery.create({ data }); } export async function notifyPlatform(input: PlatformNotificationInput, client: PlatformNotificationClient): Promise { if (Object.prototype.hasOwnProperty.call(input, "tenantId")) { throw new Error("Platform notifications must not accept a tenant scope."); } const userId = requirePlatformNotificationIdentifier(input.userId, "userId"); const sourceKey = requirePlatformNotificationSourceKey(input.sourceKey); const channel = requirePlatformNotificationChannel(input.channel ?? "IN_APP"); const messageKey = assertI18nKey(input.messageKey.trim()); const where = { tenantId: null, userId, channel, sourceKey } as const; const existing = await client.notificationDelivery.findFirst({ where }); if (existing) { return existing; } try { return await client.notificationDelivery.create({ data: { tenantId: null, userId, channel, category: normalizeNotificationCategory(input.category), messageKey, sourceKey, status: "PENDING", attemptsMade: 0, providerMessageId: null, lastError: null, payloadMetadata: sanitizePlatformNotificationPayloadMetadata(input.payloadMetadata), sentAt: null, readAt: null, }, }); } catch (error) { // The merge migration's partial unique index closes the race between the // lookup above and this insert. Re-read after any failed insert so a // concurrent winner is returned; unrelated database failures still // propagate unchanged. const concurrentDelivery = await client.notificationDelivery.findFirst({ where }); if (concurrentDelivery) { return concurrentDelivery; } throw error; } } /** * Critical notification categories signal a functional-dependency failure the * recipient must act on — a broken integration halts that tenant's sync, a * failed billing charge, an expiring certificate. They are delivered regardless * of the user's notification preferences, the same way a password-reset mail is * never opt-out: suppressing them would hide that something the user relies on * stopped working. Keep this set tiny and reserved for genuine "your stuff * broke" alerts, never routine activity. * * This is the behavioral source of truth. The settings UI mirrors it as a * locked, always-on group via @hivegrid/view-models * NOTIFICATION_LOCKED_CATEGORY_REGISTRY — that display list MUST list the same * category strings (guarded by its own vm test). */ export const CRITICAL_NOTIFICATION_CATEGORIES: ReadonlySet = new Set(["critical"]); /** True when the category is delivered regardless of user preferences. */ export function isCriticalNotificationCategory(category: string | null | undefined): boolean { return CRITICAL_NOTIFICATION_CATEGORIES.has(normalizeNotificationCategory(category)); } export function isNotificationEnabled(input: NotificationInput, preferences: readonly NotificationPreference[]): boolean { const tenantId = requireNotificationTenantScope(input.tenantId); const userId = input.userId ?? null; const channel = input.channel ?? "IN_APP"; const category = normalizeNotificationCategory(input.category); // Critical categories are never suppressed by a user preference (functional // dependency alerts). Checked before any preference lookup so even an explicit // disabled row cannot switch them off. if (isCriticalNotificationCategory(category)) { return true; } const scopedPreferences = preferences.filter((candidate) => candidate.tenantId === tenantId && candidate.userId === userId && candidate.channel === channel); const preference = scopedPreferences.find((candidate) => candidate.category === category) ?? scopedPreferences.find((candidate) => candidate.category === "default"); return preference?.enabled ?? true; } export function bundleNotifications(inputs: readonly NotificationInput[]): readonly NotificationBundle[] { const bundles = new Map }>(); for (const input of inputs) { const tenantId = requireNotificationTenantScope(input.tenantId); const userId = input.userId ?? null; const channel = input.channel ?? "IN_APP"; const category = normalizeNotificationCategory(input.category); const key = [tenantId ?? "", userId ?? "", channel, category].join(":"); const existing = bundles.get(key) ?? { tenantId, userId, channel, category, messageKeys: [], payloadMetadata: {}, }; existing.messageKeys.push(input.messageKey); if (input.payloadMetadata) { Object.assign(existing.payloadMetadata, sanitizeNotificationPayloadMetadata(input.payloadMetadata) ?? {}); } bundles.set(key, existing); } return [...bundles.values()].map((bundle) => ({ ...bundle, messageKeys: [...new Set(bundle.messageKeys)], })); } function normalizeNotificationCategory(category: string | null | undefined) { return category?.trim().toLowerCase() || "default"; } function normalizeNotificationSourceKey(sourceKey: string | null | undefined): string | null { const normalized = sourceKey?.trim(); return normalized ? normalized : null; } function requireNotificationTenantScope(tenantId: string | null | undefined): string { const normalized = tenantId?.trim(); if (!normalized) { throw new Error("Notification delivery tenant scope is required."); } return normalized; } const SENSITIVE_NOTIFICATION_METADATA_KEY_PATTERN = /authorization|cookie|password|secret|token|api[-_]?key|payload|body|header/i; const NOTIFICATION_PAYLOAD_METADATA_STRING_MAX_LENGTH = 500; const PLATFORM_NOTIFICATION_IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/u; const PLATFORM_NOTIFICATION_DEEPLINK_PATTERN = /^\/[A-Za-z0-9/_-]{1,239}$/u; const PLATFORM_NOTIFICATION_METADATA_IDENTIFIER_KEYS = new Set(["deliveryId", "eventId", "leadId", "requestId", "sourceId"]); const PLATFORM_NOTIFICATION_METADATA_EVENT_KEYS = new Set(["eventType"]); function requirePlatformNotificationIdentifier(value: string, field: string): string { const normalized = value?.trim(); if (!normalized || !PLATFORM_NOTIFICATION_IDENTIFIER_PATTERN.test(normalized)) { throw new Error(`Platform notification ${field} must be a stable non-secret identifier.`); } return normalized; } function requirePlatformNotificationSourceKey(value: string): string { return requirePlatformNotificationIdentifier(value, "sourceKey"); } function requirePlatformNotificationChannel(value: string): NotificationPreferenceChannel { if (value !== "IN_APP" && value !== "EMAIL") { throw new Error("Platform notification channel must be IN_APP or EMAIL."); } return value; } /** * Platform delivery diagnostics use a positive allowlist. Contact data, * message bodies and arbitrary producer payloads therefore never reach the * NotificationDelivery metadata column or worker diagnostics. */ export function sanitizePlatformNotificationPayloadMetadata(payloadMetadata?: Record | null): NotificationPayloadMetadata | null { if (!payloadMetadata) { return null; } const sanitized: NotificationPayloadMetadata = {}; for (const [rawKey, value] of Object.entries(payloadMetadata)) { const key = rawKey.trim(); if (PLATFORM_NOTIFICATION_METADATA_IDENTIFIER_KEYS.has(key) && typeof value === "string") { const normalized = value.trim(); if (PLATFORM_NOTIFICATION_IDENTIFIER_PATTERN.test(normalized)) { sanitized[key] = normalized; } continue; } if (PLATFORM_NOTIFICATION_METADATA_EVENT_KEYS.has(key) && typeof value === "string") { const normalized = value.trim(); if (/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u.test(normalized)) { sanitized[key] = normalized; } continue; } if (key === "deeplink" && typeof value === "string") { const normalized = value.trim(); if (PLATFORM_NOTIFICATION_DEEPLINK_PATTERN.test(normalized)) { sanitized[key] = normalized; } continue; } if (key === "replay" && typeof value === "boolean") { sanitized[key] = value; } } return Object.keys(sanitized).length > 0 ? sanitized : null; } function sanitizeNotificationPayloadMetadata(payloadMetadata?: Record | null): NotificationPayloadMetadata | null { if (!payloadMetadata) { return null; } const sanitized: NotificationPayloadMetadata = {}; for (const [rawKey, value] of Object.entries(payloadMetadata)) { const key = rawKey.trim(); if (!key) { continue; } if (SENSITIVE_NOTIFICATION_METADATA_KEY_PATTERN.test(key)) { sanitized[key] = "[redacted]"; } else if (typeof value === "string") { sanitized[key] = value.slice(0, NOTIFICATION_PAYLOAD_METADATA_STRING_MAX_LENGTH); } else if (typeof value === "number" && Number.isFinite(value)) { sanitized[key] = value; } else if (typeof value === "boolean" || value === null) { sanitized[key] = value; } } return Object.keys(sanitized).length > 0 ? sanitized : null; } export async function notifyMany( inputs: readonly NotificationInput[], client: NotificationClient, preferences: readonly NotificationPreference[] = [] ): Promise { return Promise.all(inputs.map((input) => notify(input, client, preferences))); } export function assertI18nKey(key: string): string { if (!/^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/.test(key)) { throw new Error(`Invalid i18n key: ${key}`); } return key; }