Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/db/src/notifications.server.test.ts
T

1108 lines
37 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import {
createNotificationDelivery,
createAdminPlatformNotificationDelivery,
createPlatformNotificationDelivery,
getNotificationDeliveryDiagnostics,
getPlatformNotificationStreamSnapshot,
getNotificationStreamSnapshot,
getUserNotificationPreferences,
markAllInAppNotificationDeliveriesRead,
markInAppNotificationDeliveryRead,
markNotificationDeliveryStatus,
markPlatformInAppNotificationDeliveryRead,
markPlatformNotificationDeliveryStatus,
NOTIFICATION_DELIVERY_LAST_ERROR_MAX_LENGTH,
redactNotificationDiagnosticText,
upsertUserNotificationPreference,
type NotificationsClient,
} from "./notifications.server.js";
function createNotificationsClient(): NotificationsClient {
return {
userNotificationPreference: {
upsert: vi.fn().mockResolvedValue({ id: "pref_1" }),
findMany: vi.fn().mockResolvedValue([]),
},
notificationDelivery: {
create: vi.fn().mockResolvedValue({ id: "delivery_1" }),
upsert: vi.fn().mockResolvedValue({ id: "delivery_1" }),
update: vi.fn().mockResolvedValue({ id: "delivery_1" }),
updateMany: vi.fn().mockResolvedValue({ count: 1 }),
findFirst: vi.fn().mockResolvedValue(null),
findMany: vi.fn().mockResolvedValue([]),
},
};
}
describe("notification preference boundary", () => {
it("upserts by trimmed tenant, user, normalized channel, and default category", async () => {
const client = createNotificationsClient();
await upsertUserNotificationPreference(
{
tenantId: " tenant_1 ",
userId: " user_1 ",
channel: "in-app",
enabled: null,
},
client
);
expect(client.userNotificationPreference.upsert).toHaveBeenCalledWith({
where: {
user_notification_preference_scope_key: {
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
category: "default",
},
},
create: {
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
category: "default",
enabled: true,
},
update: { enabled: true },
});
});
it("rejects missing preference tenant or user scope before writing", async () => {
const client = createNotificationsClient();
await expect(
upsertUserNotificationPreference(
{
tenantId: " ",
userId: "user_1",
channel: "email",
},
client
)
).rejects.toThrow("Notification preference tenant and user scope is required.");
await expect(getUserNotificationPreferences({ tenantId: "tenant_1", userId: " " }, client)).rejects.toThrow(
"Notification preference tenant and user scope is required."
);
expect(client.userNotificationPreference.upsert).not.toHaveBeenCalled();
expect(client.userNotificationPreference.findMany).not.toHaveBeenCalled();
});
it("normalizes lookup filters while preserving tenant/user scoping", async () => {
const client = createNotificationsClient();
await getUserNotificationPreferences(
{
tenantId: " tenant_1 ",
userId: " user_1 ",
channel: "email",
category: " Billing ",
},
client
);
expect(client.userNotificationPreference.findMany).toHaveBeenCalledWith({
where: {
tenantId: "tenant_1",
userId: "user_1",
channel: "EMAIL",
category: "billing",
},
orderBy: [{ category: "asc" }, { channel: "asc" }],
});
});
it("always includes tenant/user scope when optional lookup filters are omitted", async () => {
const client = createNotificationsClient();
await getUserNotificationPreferences({ tenantId: "tenant_1", userId: "user_1" }, client);
expect(client.userNotificationPreference.findMany).toHaveBeenCalledWith({
where: {
tenantId: "tenant_1",
userId: "user_1",
},
orderBy: [{ category: "asc" }, { channel: "asc" }],
});
});
});
describe("notification delivery boundary", () => {
it("redacts sensitive provider diagnostics before storing last errors", () => {
expect(redactNotificationDiagnosticText("SMTP token=secret-token failed for user@example.com with Authorization: Bearer abc123 and payload-secret")).toBe(
"SMTP token=[redacted] failed for [redacted-email] with Authorization: Bearer [redacted] and payload-[redacted]"
);
});
it("creates delivery records with normalized defaults and redacted scalar metadata", async () => {
const client = createNotificationsClient();
await createNotificationDelivery(
{
tenantId: "tenant_1",
userId: "user_1",
channel: "email",
messageKey: "invoice.ready",
payloadMetadata: {
template: "invoice-ready",
entityCount: 2,
dryRun: false,
authorization: "Bearer secret-token",
nested: { token: "secret" },
},
},
client
);
expect(client.notificationDelivery.create).toHaveBeenCalledWith({
data: {
tenantId: "tenant_1",
userId: "user_1",
channel: "EMAIL",
category: "default",
messageKey: "invoice.ready",
sourceKey: null,
status: "PENDING",
attemptsMade: 0,
providerMessageId: null,
lastError: null,
payloadMetadata: {
template: "invoice-ready",
entityCount: 2,
dryRun: false,
authorization: "[redacted]",
},
sentAt: null,
readAt: null,
},
});
expect(JSON.stringify(vi.mocked(client.notificationDelivery.create).mock.calls[0]?.[0])).not.toContain("secret-token");
});
it("upserts delivery records by source key when the producer supplies one", async () => {
const client = createNotificationsClient();
await createNotificationDelivery(
{
tenantId: " tenant_1 ",
userId: " user_1 ",
channel: "email",
messageKey: "invoice.ready",
sourceKey: " notification:invoice_1:user_1 ",
status: "sent",
attemptsMade: 1,
},
client
);
expect(client.notificationDelivery.upsert).toHaveBeenCalledWith({
where: {
notification_delivery_source_key: {
tenantId: "tenant_1",
userId: "user_1",
channel: "EMAIL",
sourceKey: "notification:invoice_1:user_1",
},
},
create: expect.objectContaining({
tenantId: "tenant_1",
userId: "user_1",
channel: "EMAIL",
messageKey: "invoice.ready",
sourceKey: "notification:invoice_1:user_1",
status: "SENT",
}),
update: expect.objectContaining({
messageKey: "invoice.ready",
status: "SENT",
attemptsMade: 1,
}),
});
expect(client.notificationDelivery.create).not.toHaveBeenCalled();
});
it("does not persist raw payload-like fields accidentally included by callers", async () => {
const client = createNotificationsClient();
await createNotificationDelivery(
{
tenantId: "tenant_1",
userId: "user_1",
channel: "in_app",
category: "Announcements",
messageKey: "announcement.created",
payloadMetadata: { payload: "secret-body", headers: "authorization: Bearer secret" },
body: "secret-body",
headers: { authorization: "Bearer secret" },
} as Parameters<typeof createNotificationDelivery>[0] & Record<string, unknown>,
client
);
const createCall = vi.mocked(client.notificationDelivery.create).mock.calls[0]?.[0];
expect(createCall).toBeDefined();
expect(JSON.stringify(createCall)).not.toContain("secret-body");
expect(JSON.stringify(createCall)).not.toContain("Bearer secret");
});
it("rejects unsupported delivery channels before creating diagnostics", async () => {
const client = createNotificationsClient();
await expect(
createNotificationDelivery(
{
tenantId: "tenant_1",
userId: "user_1",
channel: "sms",
messageKey: "announcement.created",
},
client
)
).rejects.toThrow("Unsupported notification channel: sms");
expect(client.notificationDelivery.create).not.toHaveBeenCalled();
});
it("rejects delivery writes without a tenant scope", async () => {
const client = createNotificationsClient();
await expect(
createNotificationDelivery(
{
tenantId: " ",
userId: "user_1",
channel: "in_app",
messageKey: "announcement.created",
},
client
)
).rejects.toThrow("Notification delivery tenant scope is required.");
expect(client.notificationDelivery.create).not.toHaveBeenCalled();
});
it("updates status diagnostics with redacted and truncated last errors", async () => {
const client = createNotificationsClient();
const oversizedError = `SMTP token=secret-token failed for user@example.com with Authorization: Bearer abc123 ${"x".repeat(
NOTIFICATION_DELIVERY_LAST_ERROR_MAX_LENGTH + 50
)}`;
const sentAt = new Date("2026-05-08T12:00:00.000Z");
await markNotificationDeliveryStatus(
{
id: "delivery_1",
tenantId: " tenant_1 ",
status: "sent",
attemptsMade: 2,
providerMessageId: "provider_1",
lastError: oversizedError,
sentAt,
},
client
);
const updateCall = vi.mocked(client.notificationDelivery.updateMany).mock.calls[0]?.[0];
expect(updateCall).toMatchObject({
where: { id: "delivery_1", tenantId: "tenant_1" },
data: {
status: "SENT",
attemptsMade: 2,
providerMessageId: "provider_1",
sentAt,
},
});
expect((updateCall?.data as { lastError?: string }).lastError).toHaveLength(NOTIFICATION_DELIVERY_LAST_ERROR_MAX_LENGTH);
expect((updateCall?.data as { lastError?: string }).lastError).not.toContain("secret-token");
expect((updateCall?.data as { lastError?: string }).lastError).not.toContain("user@example.com");
expect((updateCall?.data as { lastError?: string }).lastError).not.toContain("abc123");
});
it("marks in-app deliveries as read only within the current tenant/user scope", async () => {
const client = createNotificationsClient();
const readAt = new Date("2026-05-08T12:30:00.000Z");
await markInAppNotificationDeliveryRead(
{
id: " delivery_1 ",
tenantId: " tenant_1 ",
userId: " user_1 ",
readAt,
},
client
);
expect(client.notificationDelivery.updateMany).toHaveBeenCalledWith({
where: {
id: "delivery_1",
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
status: "SENT",
},
data: { status: "READ", readAt },
});
expect(client.notificationDelivery.update).not.toHaveBeenCalled();
});
it("rejects missing scoped read inputs before planning an update", async () => {
const client = createNotificationsClient();
await expect(
markInAppNotificationDeliveryRead(
{
id: "delivery_1",
tenantId: " ",
userId: "user_1",
},
client
)
).rejects.toThrow("Notification delivery read scope is required.");
expect(client.notificationDelivery.updateMany).not.toHaveBeenCalled();
});
it("does not accept caller-supplied channel for scoped read updates", async () => {
const client = createNotificationsClient();
await markInAppNotificationDeliveryRead(
{
id: "delivery_1",
tenantId: "tenant_1",
userId: "user_1",
channel: "EMAIL",
} as Parameters<typeof markInAppNotificationDeliveryRead>[0] & { channel: string },
client
);
expect(client.notificationDelivery.updateMany).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({ channel: "IN_APP" }),
})
);
expect(vi.mocked(client.notificationDelivery.updateMany).mock.calls[0]?.[0]).toEqual(
expect.objectContaining({
where: expect.objectContaining({ status: "SENT" }),
})
);
expect(JSON.stringify(vi.mocked(client.notificationDelivery.updateMany).mock.calls[0]?.[0])).not.toContain("EMAIL");
});
it("rejects scoped read updates that do not match exactly one delivery", async () => {
const client = createNotificationsClient();
vi.mocked(client.notificationDelivery.updateMany).mockResolvedValueOnce({ count: 0 });
await expect(
markInAppNotificationDeliveryRead(
{
id: "delivery_1",
tenantId: "tenant_1",
userId: "user_1",
},
client
)
).rejects.toThrow("Notification delivery read scope did not match exactly one delivery.");
});
it("treats marking an already-read delivery as an idempotent no-op instead of throwing", async () => {
const client = createNotificationsClient();
vi.mocked(client.notificationDelivery.updateMany).mockResolvedValueOnce({ count: 0 });
vi.mocked(client.notificationDelivery.findFirst).mockResolvedValueOnce({ id: "delivery_1" });
await expect(
markInAppNotificationDeliveryRead({ id: "delivery_1", tenantId: "tenant_1", userId: "user_1" }, client)
).resolves.toEqual({ count: 0 });
expect(client.notificationDelivery.findFirst).toHaveBeenCalledWith({
where: { id: "delivery_1", tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", status: "READ" },
select: { id: true },
});
});
it("bulk-clears every unread in-app delivery within the current tenant/user scope", async () => {
const client = createNotificationsClient();
vi.mocked(client.notificationDelivery.updateMany).mockResolvedValueOnce({ count: 3 });
const readAt = new Date("2026-05-08T13:00:00.000Z");
const cleared = await markAllInAppNotificationDeliveriesRead(
{
tenantId: " tenant_1 ",
userId: " user_1 ",
readAt,
},
client
);
expect(client.notificationDelivery.updateMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", status: "SENT" },
data: { status: "READ", readAt },
});
expect(cleared).toBe(3);
});
it("tolerates a bulk clear that matches no unread deliveries", async () => {
const client = createNotificationsClient();
vi.mocked(client.notificationDelivery.updateMany).mockResolvedValueOnce({ count: 0 });
await expect(markAllInAppNotificationDeliveriesRead({ tenantId: "tenant_1", userId: "user_1" }, client)).resolves.toBe(0);
});
it("rejects a bulk clear without tenant or user scope before writing", async () => {
const client = createNotificationsClient();
await expect(markAllInAppNotificationDeliveriesRead({ tenantId: " ", userId: "user_1" }, client)).rejects.toThrow(
"Notification delivery bulk read scope is required."
);
expect(client.notificationDelivery.updateMany).not.toHaveBeenCalled();
});
it("queries newest-first diagnostics with indexed tenant/user/status/channel/category filters", async () => {
const client = createNotificationsClient();
await getNotificationDeliveryDiagnostics(
{
tenantId: "tenant_1",
userId: "user_1",
status: "failed",
channel: "email",
category: "Billing",
take: 25,
},
client
);
expect(client.notificationDelivery.findMany).toHaveBeenCalledWith({
where: {
tenantId: "tenant_1",
userId: "user_1",
status: "FAILED",
channel: "EMAIL",
category: "billing",
},
orderBy: { createdAt: "desc" },
take: 25,
});
});
it("rejects diagnostics reads without a tenant scope", async () => {
const client = createNotificationsClient();
await expect(
getNotificationDeliveryDiagnostics(
{
tenantId: " ",
userId: "user_1",
},
client
)
).rejects.toThrow("Notification delivery tenant scope is required.");
expect(client.notificationDelivery.findMany).not.toHaveBeenCalled();
});
it("keeps tenant/user filters when diagnostics status/channel/category filters are supplied", async () => {
const client = createNotificationsClient();
await getNotificationDeliveryDiagnostics(
{
tenantId: "tenant_scope",
userId: "user_scope",
status: "sent",
channel: "in-app",
category: " Alerts ",
},
client
);
const findManyCall = vi.mocked(client.notificationDelivery.findMany).mock.calls[0]?.[0];
expect(findManyCall?.where).toEqual({
tenantId: "tenant_scope",
userId: "user_scope",
status: "SENT",
channel: "IN_APP",
category: "alerts",
});
expect(findManyCall?.where).not.toEqual(expect.not.objectContaining({ tenantId: "tenant_scope", userId: "user_scope" }));
});
it("pushes diagnostics multi-status visibility filters into the DB query before pagination", async () => {
const client = createNotificationsClient();
await getNotificationDeliveryDiagnostics(
{
tenantId: "tenant_scope",
userId: "user_scope",
statuses: ["sent", "READ", "sent"],
channel: "in-app",
take: 50,
},
client
);
expect(client.notificationDelivery.findMany).toHaveBeenCalledWith({
where: {
tenantId: "tenant_scope",
userId: "user_scope",
status: { in: ["SENT", "READ"] },
channel: "IN_APP",
},
orderBy: { createdAt: "desc" },
take: 50,
});
});
});
describe("platform notification delivery boundary", () => {
it("creates an owner-bound AdminUser intent without a tenant User foreign key", async () => {
const client = createNotificationsClient();
await createAdminPlatformNotificationDelivery(
{
adminUserId: " admin-1 ",
channel: "IN_APP",
category: "Admin Sales Email",
messageKey: "admin.sales.email.notifications.opened",
sourceKey: " admin-email-open:event-1 ",
payloadMetadata: { emailMessageId: "message-1" },
},
client as never
);
expect(client.notificationDelivery.findFirst).toHaveBeenCalledWith({
where: {
tenantId: null,
userId: null,
adminUserId: "admin-1",
channel: "IN_APP",
sourceKey: "admin-email-open:event-1",
},
});
expect(client.notificationDelivery.create).toHaveBeenCalledWith({
data: expect.objectContaining({
tenantId: null,
userId: null,
adminUserId: "admin-1",
status: "PENDING",
}),
});
});
it("creates a PENDING tenantless intent through a transaction-compatible client", async () => {
const client = createNotificationsClient();
await createPlatformNotificationDelivery(
{
userId: " user_haris ",
channel: "EMAIL",
category: "Leads",
messageKey: "platform.leads.captured",
sourceKey: " platform-lead:lead_1:email ",
payloadMetadata: {
leadId: "lead_1",
sourceId: "hivegrid-website",
deeplink: "/leads/lead_1",
email: "lead@example.test",
message: "private message",
},
},
client
);
expect(client.notificationDelivery.findFirst).toHaveBeenCalledWith({
where: {
tenantId: null,
userId: "user_haris",
channel: "EMAIL",
sourceKey: "platform-lead:lead_1:email",
},
});
expect(client.notificationDelivery.create).toHaveBeenCalledWith({
data: {
tenantId: null,
userId: "user_haris",
channel: "EMAIL",
category: "leads",
messageKey: "platform.leads.captured",
sourceKey: "platform-lead:lead_1:email",
status: "PENDING",
attemptsMade: 0,
providerMessageId: null,
lastError: null,
payloadMetadata: {
leadId: "lead_1",
sourceId: "hivegrid-website",
deeplink: "/leads/lead_1",
},
sentAt: null,
readAt: null,
},
});
expect(JSON.stringify(vi.mocked(client.notificationDelivery.create).mock.calls[0]?.[0])).not.toContain("lead@example.test");
expect(JSON.stringify(vi.mocked(client.notificationDelivery.create).mock.calls[0]?.[0])).not.toContain("private message");
});
it("updates only the tenantless delivery owned by the required platform user", async () => {
const client = createNotificationsClient();
await markPlatformNotificationDeliveryStatus(
{
id: " delivery_1 ",
userId: " user_haris ",
status: "sent",
attemptsMade: 2,
providerMessageId: "provider_1",
sentAt: new Date("2026-07-16T12:00:00.000Z"),
},
client
);
expect(client.notificationDelivery.updateMany).toHaveBeenCalledWith({
where: { id: "delivery_1", tenantId: null, userId: "user_haris" },
data: {
status: "SENT",
attemptsMade: 2,
providerMessageId: "provider_1",
sentAt: new Date("2026-07-16T12:00:00.000Z"),
},
});
});
it("marks only the recipient's tenantless in-app delivery as read", async () => {
const client = createNotificationsClient();
const readAt = new Date("2026-07-16T12:05:00.000Z");
await markPlatformInAppNotificationDeliveryRead({ id: "delivery_1", userId: "user_haris", readAt }, client);
expect(client.notificationDelivery.updateMany).toHaveBeenCalledWith({
where: { id: "delivery_1", tenantId: null, userId: "user_haris", channel: "IN_APP", status: "SENT" },
data: { status: "READ", readAt },
});
});
it("treats an already-read scoped platform delivery as an idempotent success", async () => {
const client = createNotificationsClient();
vi.mocked(client.notificationDelivery.updateMany).mockResolvedValue({ count: 0 });
vi.mocked(client.notificationDelivery.findFirst).mockResolvedValue({ id: "delivery_1" });
await expect(
markPlatformInAppNotificationDeliveryRead({ id: "delivery_1", userId: "user_haris" }, client)
).resolves.toEqual({ count: 0 });
expect(client.notificationDelivery.findFirst).toHaveBeenCalledWith({
where: { id: "delivery_1", tenantId: null, userId: "user_haris", channel: "IN_APP", status: "READ" },
select: { id: true },
});
vi.mocked(client.notificationDelivery.findFirst).mockResolvedValue(null);
await expect(
markPlatformInAppNotificationDeliveryRead({ id: "delivery_1", userId: "other_user" }, client)
).rejects.toThrow("did not match exactly one delivery");
});
it("returns only tenantless in-app rows for the required platform user", async () => {
const client = createNotificationsClient();
vi.mocked(client.notificationDelivery.findMany).mockResolvedValue([
{
id: "platform_delivery_1",
tenantId: null,
userId: "user_haris",
channel: "IN_APP",
category: "leads",
messageKey: "platform.leads.captured",
status: "SENT",
attemptsMade: 1,
createdAt: new Date("2026-07-16T12:00:00.000Z"),
updatedAt: new Date("2026-07-16T12:00:00.000Z"),
sentAt: new Date("2026-07-16T12:00:00.000Z"),
readAt: null,
payloadMetadata: { deeplink: "/leads/lead_1" },
},
{
id: "tenant_delivery_1",
tenantId: "tenant_1",
userId: "user_haris",
channel: "IN_APP",
category: "leads",
messageKey: "platform.leads.captured",
status: "SENT",
attemptsMade: 1,
createdAt: new Date("2026-07-16T12:00:00.000Z"),
updatedAt: new Date("2026-07-16T12:00:00.000Z"),
},
]);
const snapshot = await getPlatformNotificationStreamSnapshot({ userId: "user_haris" }, client);
expect(snapshot.items).toHaveLength(1);
expect(snapshot.items[0]).toMatchObject({ id: "platform_delivery_1", tenantId: null, userId: "user_haris" });
expect(client.notificationDelivery.findMany).toHaveBeenCalledWith({
where: { tenantId: null, userId: "user_haris", channel: "IN_APP", status: { in: ["SENT", "READ"] } },
orderBy: [{ updatedAt: "desc" }, { createdAt: "desc" }, { id: "desc" }],
take: 50,
});
});
it("rejects missing platform user scope before writes or reads", async () => {
const client = createNotificationsClient();
await expect(markPlatformNotificationDeliveryStatus({ id: "delivery_1", userId: " ", status: "sent" }, client)).rejects.toThrow(
"Platform notification delivery status scope is required"
);
await expect(getPlatformNotificationStreamSnapshot({ userId: " " }, client)).rejects.toThrow("Platform notification stream user scope is required");
expect(client.notificationDelivery.updateMany).not.toHaveBeenCalled();
expect(client.notificationDelivery.findMany).not.toHaveBeenCalled();
});
});
describe("notification stream snapshot boundary", () => {
it("queries tenant/user scoped in-app diagnostics with a bounded default and returns newest-first serializable items", async () => {
const client = createNotificationsClient();
vi.mocked(client.notificationDelivery.findMany).mockResolvedValue([
{
id: "delivery_2",
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
category: "billing",
messageKey: "invoice.paid",
status: "READ",
attemptsMade: 1,
createdAt: new Date("2026-05-08T12:00:00.000Z"),
updatedAt: new Date("2026-05-08T12:05:00.000Z"),
sentAt: new Date("2026-05-08T12:01:00.000Z"),
readAt: new Date("2026-05-08T12:06:00.000Z"),
},
{
id: "delivery_1",
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
category: "billing",
messageKey: "invoice.ready",
status: "SENT",
attemptsMade: 1,
createdAt: new Date("2026-05-08T11:00:00.000Z"),
updatedAt: new Date("2026-05-08T11:05:00.000Z"),
sentAt: null,
readAt: null,
},
{
id: "delivery_skipped",
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
category: "billing",
messageKey: "invoice.skipped",
status: "SKIPPED",
attemptsMade: 0,
createdAt: new Date("2026-05-08T12:30:00.000Z"),
updatedAt: new Date("2026-05-08T12:30:00.000Z"),
sentAt: null,
readAt: null,
},
]);
const snapshot = await getNotificationStreamSnapshot({ tenantId: "tenant_1", userId: "user_1" }, client);
expect(client.notificationDelivery.findMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", status: { in: ["SENT", "READ"] } },
orderBy: [{ updatedAt: "desc" }, { createdAt: "desc" }, { id: "desc" }],
take: 50,
});
expect(snapshot).toEqual({
cursor: "2026-05-08T12:05:00.000Z:delivery_2",
items: [
{
id: "delivery_2",
cursor: "2026-05-08T12:05:00.000Z:delivery_2",
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
category: "billing",
messageKey: "invoice.paid",
status: "READ",
attemptsMade: 1,
createdAt: "2026-05-08T12:00:00.000Z",
updatedAt: "2026-05-08T12:05:00.000Z",
sentAt: "2026-05-08T12:01:00.000Z",
readAt: "2026-05-08T12:06:00.000Z",
deeplink: null,
lastError: null,
},
{
id: "delivery_1",
cursor: "2026-05-08T11:05:00.000Z:delivery_1",
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
category: "billing",
messageKey: "invoice.ready",
status: "SENT",
attemptsMade: 1,
createdAt: "2026-05-08T11:00:00.000Z",
updatedAt: "2026-05-08T11:05:00.000Z",
sentAt: null,
readAt: null,
deeplink: null,
lastError: null,
},
],
});
expect(JSON.stringify(snapshot)).toEqual(expect.any(String));
expect(JSON.stringify(snapshot)).not.toContain("delivery_skipped");
expect(JSON.stringify(snapshot)).not.toContain("invoice.skipped");
});
it("applies afterCursor without broadening tenant/user scope and caps requested take at 50", async () => {
const client = createNotificationsClient();
vi.mocked(client.notificationDelivery.findMany).mockResolvedValue([
{
id: "delivery_new",
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
category: "default",
messageKey: "new",
status: "SENT",
attemptsMade: 1,
createdAt: new Date("2026-05-08T13:00:00.000Z"),
updatedAt: new Date("2026-05-08T13:00:00.000Z"),
sentAt: null,
readAt: null,
},
{
id: "delivery_foreign_tenant",
tenantId: "tenant_foreign",
userId: "user_1",
channel: "IN_APP",
category: "default",
messageKey: "foreign.tenant",
status: "SENT",
attemptsMade: 1,
createdAt: new Date("2026-05-08T14:00:00.000Z"),
updatedAt: new Date("2026-05-08T14:00:00.000Z"),
sentAt: null,
readAt: null,
},
{
id: "delivery_foreign_user",
tenantId: "tenant_1",
userId: "user_foreign",
channel: "IN_APP",
category: "default",
messageKey: "foreign.user",
status: "SENT",
attemptsMade: 1,
createdAt: new Date("2026-05-08T14:30:00.000Z"),
updatedAt: new Date("2026-05-08T14:30:00.000Z"),
sentAt: null,
readAt: null,
},
{
id: "delivery_old",
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
category: "default",
messageKey: "old",
status: "SENT",
attemptsMade: 1,
createdAt: new Date("2026-05-08T10:00:00.000Z"),
updatedAt: new Date("2026-05-08T10:00:00.000Z"),
sentAt: null,
readAt: null,
},
]);
const snapshot = await getNotificationStreamSnapshot(
{ tenantId: "tenant_1", userId: "user_1", afterCursor: "2026-05-08T12:00:00.000Z:any", take: 500 },
client
);
expect(client.notificationDelivery.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", status: { in: ["SENT", "READ"] } },
take: 50,
})
);
expect(snapshot.items).toHaveLength(1);
expect(snapshot.items[0]?.id).toBe("delivery_new");
expect(JSON.stringify(snapshot)).not.toContain("foreign");
expect(JSON.stringify(snapshot)).not.toContain("delivery_old");
});
it("sorts stream snapshots by update cursor after filtering diagnostics", async () => {
const client = createNotificationsClient();
vi.mocked(client.notificationDelivery.findMany).mockResolvedValue([
{
id: "delivery_old_created",
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
category: "default",
messageKey: "old.created.updated",
status: "READ",
attemptsMade: 1,
createdAt: new Date("2026-05-01T09:00:00.000Z"),
updatedAt: new Date("2026-05-08T15:00:00.000Z"),
sentAt: null,
readAt: new Date("2026-05-08T15:00:00.000Z"),
},
{
id: "delivery_new_created",
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
category: "default",
messageKey: "new.created",
status: "SENT",
attemptsMade: 1,
createdAt: new Date("2026-05-08T14:00:00.000Z"),
updatedAt: new Date("2026-05-08T14:00:00.000Z"),
sentAt: null,
readAt: null,
},
]);
const snapshot = await getNotificationStreamSnapshot({ tenantId: "tenant_1", userId: "user_1" }, client);
expect(snapshot.cursor).toBe("2026-05-08T15:00:00.000Z:delivery_old_created");
expect(snapshot.items.map((item) => item.id)).toEqual(["delivery_old_created", "delivery_new_created"]);
});
it("returns an empty snapshot without querying when take is zero", async () => {
const client = createNotificationsClient();
await expect(getNotificationStreamSnapshot({ tenantId: "tenant_1", userId: "user_1", take: 0 }, client)).resolves.toEqual({
cursor: null,
items: [],
});
expect(client.notificationDelivery.findMany).not.toHaveBeenCalled();
});
it("omits provider payload, token, raw metadata, and unknown record fields from stream output", async () => {
const client = createNotificationsClient();
vi.mocked(client.notificationDelivery.findMany).mockResolvedValue([
{
id: "delivery_1",
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
category: "default",
messageKey: "announcement.created",
status: "READ",
attemptsMade: 3,
createdAt: new Date("2026-05-08T12:00:00.000Z"),
updatedAt: new Date("2026-05-08T12:01:00.000Z"),
sentAt: null,
readAt: null,
providerMessageId: "provider-secret-id",
payloadMetadata: { token: "secret-token", body: "raw-body", deeplink: "/acme/announcements/a1" },
authorization: "Bearer secret-token",
body: "raw-body",
headers: { cookie: "secret" },
unknownField: "do-not-serialize",
lastError: "token=secret-token failed",
},
]);
const snapshot = await getNotificationStreamSnapshot({ tenantId: "tenant_1", userId: "user_1" }, client);
const serialized = JSON.stringify(snapshot);
// AK-P3 DoD 4: only the validated app-relative deeplink scalar and the
// redacted error ride along — payloadMetadata itself never enters the
// stream, and secrets must never appear serialized.
expect(snapshot.items[0]).toEqual({
id: "delivery_1",
cursor: "2026-05-08T12:01:00.000Z:delivery_1",
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
category: "default",
messageKey: "announcement.created",
status: "READ",
attemptsMade: 3,
createdAt: "2026-05-08T12:00:00.000Z",
updatedAt: "2026-05-08T12:01:00.000Z",
sentAt: null,
readAt: null,
deeplink: "/acme/announcements/a1",
lastError: "token=[redacted] failed",
});
expect(serialized).not.toContain("provider-secret-id");
expect(serialized).not.toContain("secret-token");
expect(serialized).not.toContain("raw-body");
expect(serialized).not.toContain("unknownField");
expect(serialized).not.toContain("payloadMetadata");
});
it("drops unsafe deeplink candidates from the stream", async () => {
const client = createNotificationsClient();
vi.mocked(client.notificationDelivery.findMany).mockResolvedValue([
{
id: "delivery_evil",
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
category: "default",
messageKey: "announcement.created",
status: "SENT",
attemptsMade: 1,
createdAt: new Date("2026-05-08T12:00:00.000Z"),
updatedAt: new Date("2026-05-08T12:01:00.000Z"),
sentAt: null,
readAt: null,
payloadMetadata: { deeplink: "https://evil.example/phish" },
},
]);
const snapshot = await getNotificationStreamSnapshot({ tenantId: "tenant_1", userId: "user_1" }, client);
expect(snapshot.items[0]?.deeplink).toBeNull();
expect(JSON.stringify(snapshot)).not.toContain("evil.example");
});
});
describe("notification package exports", () => {
it("exposes the notification boundary from the package root", async () => {
const rootBoundary = await import(".");
expect(rootBoundary).toEqual(
expect.objectContaining({
upsertUserNotificationPreference,
getUserNotificationPreferences,
createNotificationDelivery,
createPlatformNotificationDelivery,
markInAppNotificationDeliveryRead,
markNotificationDeliveryStatus,
markPlatformInAppNotificationDeliveryRead,
markPlatformNotificationDeliveryStatus,
getNotificationDeliveryDiagnostics,
getNotificationStreamSnapshot,
getPlatformNotificationStreamSnapshot,
})
);
});
it("exposes the notification boundary subpath export", async () => {
const notificationBoundary = await import("@hivegrid/db/notifications.server");
expect(notificationBoundary).toEqual(
expect.objectContaining({
upsertUserNotificationPreference,
getUserNotificationPreferences,
createNotificationDelivery,
createPlatformNotificationDelivery,
markInAppNotificationDeliveryRead,
markNotificationDeliveryStatus,
markPlatformInAppNotificationDeliveryRead,
markPlatformNotificationDeliveryStatus,
getNotificationDeliveryDiagnostics,
getNotificationStreamSnapshot,
getPlatformNotificationStreamSnapshot,
})
);
});
});