Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -10,6 +10,25 @@ export type NotificationInput = {
payloadMetadata?: Record<string, JsonValue> | 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<string, JsonValue> | null;
};
export type NotificationPreferenceChannel = "IN_APP" | "EMAIL";
export type NotificationDeliveryStatus = "PENDING" | "SENT" | "FAILED" | "SKIPPED" | "READ";
export type NotificationPayloadMetadata = Record<string, string | number | boolean | null>;
@@ -52,7 +71,7 @@ export type NotificationClient = {
}): Promise<unknown>;
upsert?(args: {
where: {
tenantId_userId_channel_sourceKey: {
notification_delivery_source_key: {
tenantId: string;
userId: string;
channel: NotificationPreferenceChannel;
@@ -89,6 +108,36 @@ export type NotificationClient = {
};
};
export type PlatformNotificationClient = {
notificationDelivery: {
findFirst(args: {
where: {
tenantId: null;
userId: string;
channel: NotificationPreferenceChannel;
sourceKey: string;
};
}): Promise<unknown | null>;
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<unknown>;
};
};
export async function notify(input: NotificationInput, client: NotificationClient, preferences: readonly NotificationPreference[] = []): Promise<unknown> {
const tenantId = requireNotificationTenantScope(input.tenantId);
const enabled = isNotificationEnabled(input, preferences);
@@ -102,7 +151,7 @@ export async function notify(input: NotificationInput, client: NotificationClien
category: normalizeNotificationCategory(input.category),
messageKey: input.messageKey,
sourceKey,
status: enabled ? channel === "IN_APP" ? "SENT" as const : "PENDING" as const : "SKIPPED" as const,
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",
@@ -114,7 +163,7 @@ export async function notify(input: NotificationInput, client: NotificationClien
if (sourceKey && userId && client.notificationDelivery.upsert) {
return client.notificationDelivery.upsert({
where: {
tenantId_userId_channel_sourceKey: {
notification_delivery_source_key: {
tenantId,
userId,
channel,
@@ -139,19 +188,90 @@ export async function notify(input: NotificationInput, client: NotificationClien
return client.notificationDelivery.create({ data });
}
export async function notifyPlatform(input: PlatformNotificationInput, client: PlatformNotificationClient): Promise<unknown> {
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<string> = 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);
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");
// 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;
}
@@ -165,16 +285,14 @@ export function bundleNotifications(inputs: readonly NotificationInput[]): reado
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: {},
};
const existing = bundles.get(key) ?? {
tenantId,
userId,
channel,
category,
messageKeys: [],
payloadMetadata: {},
};
existing.messageKeys.push(input.messageKey);
if (input.payloadMetadata) {
@@ -210,6 +328,79 @@ function requireNotificationTenantScope(tenantId: string | null | undefined): st
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<string, JsonValue> | 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<string, JsonValue> | null): NotificationPayloadMetadata | null {
if (!payloadMetadata) {
@@ -240,7 +431,7 @@ function sanitizeNotificationPayloadMetadata(payloadMetadata?: Record<string, Js
export async function notifyMany(
inputs: readonly NotificationInput[],
client: NotificationClient,
preferences: readonly NotificationPreference[] = [],
preferences: readonly NotificationPreference[] = []
): Promise<unknown[]> {
return Promise.all(inputs.map((input) => notify(input, client, preferences)));
}