Reorganize repo structure and standards references

This commit is contained in:
david committed 2026-06-29 05:03:42 +02:00
1 parent 3cb93a81be
commit be2054274d
5885 files changed
+2588 -195

No files matched your search

@@ -0,0 +1,193 @@
import { describe, expect, it, vi } from "vitest";
import { createUniqueTenantIpAddressRecord } from "./auth-boundary.server.js";
import {
adminGetAllLegacyTenants,
adminGetAllLegacyTenantSummaries,
createUniqueLegacyTenantIpAddress,
findLegacyTenantById,
findLegacyTenantByIdOrSlug,
getLegacyTenantMembershipsForUser,
legacyTenantDetailsInclude,
type LegacyTenantAccountReaderClient,
type LegacyTenantIpAddressWriterClient,
} from "./accounts.server.js";
function createTenantClient(items: unknown[] = []): LegacyTenantAccountReaderClient {
return {
tenant: {
findMany: vi.fn().mockResolvedValue(items),
findUnique: vi.fn().mockResolvedValue(items[0] ?? null),
findFirst: vi.fn().mockResolvedValue(items[0] ?? null),
},
} as unknown as LegacyTenantAccountReaderClient;
}
describe("legacy account tenant reads", () => {
it("fetches all tenants with the account API details shape", async () => {
const client = createTenantClient([]);
await expect(adminGetAllLegacyTenants(client)).resolves.toEqual([]);
expect(client.tenant.findMany).toHaveBeenCalledWith({
include: legacyTenantDetailsInclude,
orderBy: { createdAt: "desc" },
});
});
it("fetches tenant summaries for admin filters", async () => {
const client = createTenantClient([{ id: "tenant_1", name: "Acme", slug: "acme" }]);
await expect(adminGetAllLegacyTenantSummaries(client)).resolves.toEqual([{ id: "tenant_1", name: "Acme", slug: "acme" }]);
expect(client.tenant.findMany).toHaveBeenCalledWith({
select: { id: true, name: true, slug: true },
});
});
it("fetches simple tenant memberships for API authorization", async () => {
const client = createTenantClient([{ id: "tenant_1", name: "Acme", slug: "acme" }]);
await expect(getLegacyTenantMembershipsForUser("user_1", client)).resolves.toEqual([{ id: "tenant_1", name: "Acme", slug: "acme" }]);
expect(client.tenant.findMany).toHaveBeenCalledWith({
where: { active: true, users: { some: { userId: "user_1", status: 2 } } },
select: {
id: true,
name: true,
slug: true,
icon: true,
logo: true,
deactivatedReason: true,
types: true,
active: true,
theme: true,
themeConfig: true,
},
orderBy: { name: "asc" },
});
});
it("fetches one tenant by id with the account API details shape", async () => {
const tenant = { id: "tenant_1" };
const client = createTenantClient([tenant]);
await expect(findLegacyTenantById("tenant_1", client)).resolves.toBe(tenant);
expect(client.tenant.findUnique).toHaveBeenCalledWith({
where: { id: "tenant_1" },
include: legacyTenantDetailsInclude,
});
});
it("fetches the tenant identity by id or slug before loading details", async () => {
const tenant = { id: "tenant_1", slug: "acme", subscription: null };
const client = createTenantClient([tenant]);
await expect(findLegacyTenantByIdOrSlug("acme", client)).resolves.toBe(tenant);
expect(client.tenant.findFirst).toHaveBeenCalledWith({
where: {
OR: [{ id: "acme" }, { slug: "acme" }],
},
include: {
subscription: true,
types: true,
},
});
});
});
describe("legacy tenant IP address writes", () => {
it("creates a tenant IP address only when the tenant/user/key tuple is new", async () => {
const client: LegacyTenantIpAddressWriterClient = {
tenantIpAddress: {
findFirst: vi.fn().mockResolvedValue(null),
create: vi.fn().mockResolvedValue({ id: "ip_1" }),
},
} as unknown as LegacyTenantIpAddressWriterClient;
await expect(
createUniqueLegacyTenantIpAddress(
{
ip: "127.0.0.1",
fromUrl: "/api/widgets",
tenantId: "tenant_1",
apiKeyId: "api_key_1",
},
client,
),
).resolves.toEqual({ id: "ip_1" });
expect(client.tenantIpAddress.findFirst).toHaveBeenCalledWith({
where: {
ip: "127.0.0.1",
tenantId: "tenant_1",
userId: undefined,
apiKeyId: "api_key_1",
},
});
expect(client.tenantIpAddress.create).toHaveBeenCalledWith({
data: {
ip: "127.0.0.1",
fromUrl: "/api/widgets",
tenantId: "tenant_1",
apiKeyId: "api_key_1",
},
});
});
it("does not recreate an existing tenant IP address", async () => {
const client: LegacyTenantIpAddressWriterClient = {
tenantIpAddress: {
findFirst: vi.fn().mockResolvedValue({ id: "ip_1" }),
create: vi.fn(),
},
} as unknown as LegacyTenantIpAddressWriterClient;
await expect(
createUniqueLegacyTenantIpAddress(
{
ip: "127.0.0.1",
fromUrl: "/api/widgets",
tenantId: "tenant_1",
},
client,
),
).resolves.toBeUndefined();
expect(client.tenantIpAddress.create).not.toHaveBeenCalled();
});
it("exposes the tenant IP address write through the auth boundary alias", async () => {
const client: LegacyTenantIpAddressWriterClient = {
tenantIpAddress: {
findFirst: vi.fn().mockResolvedValue(null),
create: vi.fn().mockResolvedValue({ id: "ip_1" }),
},
} as unknown as LegacyTenantIpAddressWriterClient;
await expect(
createUniqueTenantIpAddressRecord(
{
ip: "127.0.0.1",
fromUrl: "/app/acme",
tenantId: "tenant_1",
userId: "user_1",
},
client,
),
).resolves.toEqual({ id: "ip_1" });
expect(client.tenantIpAddress.findFirst).toHaveBeenCalledWith({
where: {
ip: "127.0.0.1",
tenantId: "tenant_1",
userId: "user_1",
apiKeyId: undefined,
},
});
expect(client.tenantIpAddress.create).toHaveBeenCalledWith({
data: {
ip: "127.0.0.1",
fromUrl: "/app/acme",
tenantId: "tenant_1",
userId: "user_1",
},
});
});
});
@@ -0,0 +1,301 @@
import { getDbClient } from "./client.server.js";
import type { Tenant, TenantInboundAddress, TenantIpAddress, TenantSettingsRow, TenantType, TenantUser } from "./prisma-browser.js";
import type { TenantSubscriptionWithDetails } from "./subscriptions.server.js";
const ACTIVE_TENANT_USER_STATUS = 2;
export type LegacyTenantSimple = Tenant & {
subscription: { id: string } | null;
types: TenantType[];
};
export type LegacyTenantSummary = Pick<Tenant, "id" | "name" | "slug">;
export type LegacyTenantMemberSimple = Pick<
Tenant,
"id" | "name" | "slug" | "icon" | "logo" | "deactivatedReason" | "active" | "theme" | "themeConfig"
> & {
types: TenantType[];
};
export type AuthBoundaryTenantMembership = TenantUser & {
tenant: Tenant;
user: LegacyTenantUserSummary;
};
export type LegacyTenantUserSummary = {
id: string;
email: string;
firstName: string;
lastName: string;
phone: string | null;
locale: string | null;
createdAt: Date;
};
export type LegacyTenantWithDetails = Tenant & {
inboundAddresses: TenantInboundAddress[];
users: (TenantUser & {
user: LegacyTenantUserSummary;
})[];
subscription: TenantSubscriptionWithDetails | null;
tenantSettingsRow: (TenantSettingsRow & { row: unknown }) | null;
types: TenantType[];
};
export type LegacyTenantAccountReaderClient = {
tenant: {
findMany(args: {
include: typeof legacyTenantDetailsInclude;
orderBy: { createdAt: "desc" };
}): Promise<LegacyTenantWithDetails[]>;
findMany(args: {
select: { id: true; name: true; slug: true };
}): Promise<LegacyTenantSummary[]>;
findMany(args: {
where: { active: true; users: { some: { userId: string; status: typeof ACTIVE_TENANT_USER_STATUS } } };
select: typeof selectLegacyTenantMemberSimple;
orderBy: { name: "asc" };
}): Promise<LegacyTenantMemberSimple[]>;
findMany(args: {
where: { active: true };
select: typeof selectLegacyTenantMemberSimple;
orderBy: { name: "asc" };
}): Promise<LegacyTenantMemberSimple[]>;
findUnique(args: {
where: { id: string };
include: typeof legacyTenantDetailsInclude;
}): Promise<LegacyTenantWithDetails | null>;
findFirst(args: {
where: { OR: [{ id: string }, { slug: string }] };
include: { subscription: true; types: true };
}): Promise<LegacyTenantSimple | null>;
};
tenantUser: {
findFirst(args: {
where: { tenantId: string; userId: string; status: typeof ACTIVE_TENANT_USER_STATUS; tenant: { active: true } };
include: typeof includeAuthBoundaryTenantMembership;
}): Promise<AuthBoundaryTenantMembership | null>;
};
};
export type LegacyTenantIpAddressCreateData = {
ip: string;
fromUrl: string;
tenantId: string;
userId?: string | null;
apiKeyId?: string | null;
};
export type LegacyTenantIpAddressWriterClient = {
tenantIpAddress: {
findFirst(args: {
where: {
ip: string;
tenantId: string;
userId?: string | null;
apiKeyId?: string | null;
};
}): Promise<TenantIpAddress | null>;
create(args: { data: LegacyTenantIpAddressCreateData }): Promise<TenantIpAddress>;
};
};
const selectLegacyTenantUserSummary = {
id: true,
email: true,
firstName: true,
lastName: true,
phone: true,
locale: true,
createdAt: true,
} as const;
const selectLegacyTenantMemberSimple = {
id: true,
name: true,
slug: true,
icon: true,
logo: true,
deactivatedReason: true,
types: true,
active: true,
theme: true,
themeConfig: true,
} as const;
const includeLegacyTenantSubscriptionProductDetails = {
subscriptionProduct: { include: { features: true } },
prices: { include: { subscriptionPrice: true, subscriptionUsageBasedPrice: { include: { tiers: true } } } },
} as const;
const includeAuthBoundaryTenantMembership = {
tenant: true,
user: { select: selectLegacyTenantUserSummary },
} as const;
const includeLegacyRowDetails = {
createdByUser: { select: selectLegacyTenantUserSummary },
createdByApiKey: true,
tenant: true,
values: { include: { media: true, multiple: true, range: true } },
tags: { include: { tag: true } },
parentRows: {
include: {
parent: {
include: {
createdByUser: { select: selectLegacyTenantUserSummary },
createdByApiKey: true,
values: { include: { media: true, multiple: true, range: true } },
},
},
},
},
childRows: {
include: {
child: {
include: {
createdByUser: { select: selectLegacyTenantUserSummary },
createdByApiKey: true,
values: { include: { media: true, multiple: true, range: true } },
parentRows: {
include: {
parent: {
include: {
values: { include: { media: true, multiple: true, range: true } },
},
},
},
},
childRows: {
include: {
child: {
include: {
values: { include: { media: true, multiple: true, range: true } },
},
},
},
},
},
},
},
},
permissions: true,
sampleCustomEntity: true,
} as const;
export const legacyTenantDetailsInclude = {
inboundAddresses: true,
users: {
include: {
user: {
select: selectLegacyTenantUserSummary,
},
},
},
subscription: {
include: {
products: {
include: includeLegacyTenantSubscriptionProductDetails,
},
},
},
tenantSettingsRow: { include: { row: { include: includeLegacyRowDetails } } },
types: true,
} as const;
export async function adminGetAllLegacyTenants(
client: LegacyTenantAccountReaderClient = getDbClient() as unknown as LegacyTenantAccountReaderClient,
): Promise<LegacyTenantWithDetails[]> {
return client.tenant.findMany({
include: legacyTenantDetailsInclude,
orderBy: { createdAt: "desc" },
});
}
export async function adminGetAllLegacyTenantSummaries(
client: LegacyTenantAccountReaderClient = getDbClient() as unknown as LegacyTenantAccountReaderClient,
): Promise<LegacyTenantSummary[]> {
return client.tenant.findMany({
select: { id: true, name: true, slug: true },
});
}
export async function getLegacyTenantMembershipsForUser(
userId: string,
client: LegacyTenantAccountReaderClient = getDbClient() as unknown as LegacyTenantAccountReaderClient,
): Promise<LegacyTenantMemberSimple[]> {
return client.tenant.findMany({
where: { active: true, users: { some: { userId, status: ACTIVE_TENANT_USER_STATUS } } },
select: selectLegacyTenantMemberSimple,
orderBy: { name: "asc" },
});
}
export async function adminGetAllActiveLegacyTenants(
client: LegacyTenantAccountReaderClient = getDbClient() as unknown as LegacyTenantAccountReaderClient,
): Promise<LegacyTenantMemberSimple[]> {
return client.tenant.findMany({
where: { active: true },
select: selectLegacyTenantMemberSimple,
orderBy: { name: "asc" },
});
}
export async function findTenantMembershipByIds(
tenantId: string,
userId: string,
client: LegacyTenantAccountReaderClient = getDbClient() as unknown as LegacyTenantAccountReaderClient,
): Promise<AuthBoundaryTenantMembership | null> {
return client.tenantUser.findFirst({
where: { tenantId, userId, status: ACTIVE_TENANT_USER_STATUS, tenant: { active: true } },
include: includeAuthBoundaryTenantMembership,
});
}
export async function createUniqueLegacyTenantIpAddress(
data: LegacyTenantIpAddressCreateData,
client: LegacyTenantIpAddressWriterClient = getDbClient() as unknown as LegacyTenantIpAddressWriterClient,
): Promise<TenantIpAddress | undefined> {
const existing = await client.tenantIpAddress.findFirst({
where: {
ip: data.ip,
tenantId: data.tenantId,
userId: data.userId,
apiKeyId: data.apiKeyId,
},
});
if (existing) {
return undefined;
}
return client.tenantIpAddress.create({
data,
});
}
export async function findLegacyTenantById(
id: string,
client: LegacyTenantAccountReaderClient = getDbClient() as unknown as LegacyTenantAccountReaderClient,
): Promise<LegacyTenantWithDetails | null> {
return client.tenant.findUnique({
where: { id },
include: legacyTenantDetailsInclude,
});
}
export async function findLegacyTenantByIdOrSlug(
idOrSlug: string,
client: LegacyTenantAccountReaderClient = getDbClient() as unknown as LegacyTenantAccountReaderClient,
): Promise<LegacyTenantSimple | null> {
return client.tenant.findFirst({
where: {
OR: [{ id: idOrSlug }, { slug: idOrSlug }],
},
include: {
subscription: true,
types: true,
},
});
}
@@ -0,0 +1,525 @@
import { describe, expect, it, vi } from "vitest";
import {
createAnalyticsEvent,
createAnalyticsPageView,
defaultAnalyticsPeriod,
findFeatureFlagByName,
getAnalyticsEventFilterOptions,
getAnalyticsEventList,
getAnalyticsOverview,
getAnalyticsPageViewFilterOptions,
getAnalyticsPageViewList,
getAnalyticsSettings,
getAnalyticsVisitorList,
getOrCreateAnalyticsSettings,
deleteAllAnalyticsData,
removeAnalyticsIgnoredPage,
sanitizeAnalyticsReferrer,
sanitizeAnalyticsUrl,
updateAnalyticsSettingsPreferences,
getOrCreateAnalyticsUniqueVisitor,
isAnalyticsPeriod,
updateAnalyticsUniqueVisitorSource,
type AnalyticsClient,
type AnalyticsUniqueVisitor,
} from "./analytics.server.js";
function createAnalyticsClient(): AnalyticsClient {
return {
analyticsSettings: {
findFirst: vi.fn().mockResolvedValue({ id: "settings_1", public: false, ignorePages: "/health", onlyPages: "" }),
create: vi.fn().mockResolvedValue({ id: "settings_1", public: false, ignorePages: "/analytics,/admin/analytics", onlyPages: "" }),
update: vi.fn().mockResolvedValue({ id: "settings_1", public: true, ignorePages: "/health,/docs", onlyPages: "" }),
},
analyticsUniqueVisitor: {
count: vi.fn().mockResolvedValue(4),
findFirst: vi.fn().mockResolvedValue(null),
findUnique: vi.fn().mockResolvedValue(null),
create: vi.fn().mockResolvedValue(createVisitor()),
update: vi.fn().mockResolvedValue(createVisitor()),
findMany: vi.fn().mockResolvedValue([{ id: "visitor_1" }]),
deleteMany: vi.fn().mockResolvedValue({ count: 1 }),
groupBy: vi.fn().mockImplementation(({ by }) => {
const field = by[0];
if (field === "createdAt") {
return Promise.resolve([
{ createdAt: new Date("2024-06-15T01:00:00.000Z"), _count: 1 },
{ createdAt: new Date("2024-06-15T18:30:00.000Z"), _count: 2 },
{ createdAt: new Date("2024-06-16T01:00:00.000Z"), _count: 3 },
]);
}
return Promise.resolve([
{ [field]: "low", _count: 1 },
{ [field]: "high", _count: 7 },
{ [field]: null, _count: 3 },
]);
}),
},
analyticsEvent: {
count: vi.fn().mockResolvedValue(8),
groupBy: vi.fn().mockImplementation(({ by }) => Promise.resolve([{ [by[0]]: `${by[0]}_1` }])),
findMany: vi.fn().mockResolvedValue([{ id: "event_1" }]),
create: vi.fn().mockResolvedValue({ id: "event_1" }),
deleteMany: vi.fn().mockResolvedValue({ count: 1 }),
},
analyticsPageView: {
count: vi.fn().mockResolvedValue(12),
findMany: vi.fn().mockResolvedValue([{ id: "page_view_1" }]),
groupBy: vi.fn().mockImplementation(({ by }) => {
const field = by[0];
if (field === "uniqueVisitorId") {
return Promise.resolve([
{ uniqueVisitorId: "visitor_1", _count: 3 },
{ uniqueVisitorId: "visitor_2", _count: 1 },
]);
}
if (field === "createdAt") {
return Promise.resolve([
{ createdAt: new Date("2024-06-15T05:00:00.000Z"), _count: 4 },
{ createdAt: new Date("2024-06-15T23:30:00.000Z"), _count: 5 },
{ createdAt: new Date("2024-06-16T05:00:00.000Z"), _count: 6 },
]);
}
if (field === "url") {
return Promise.resolve(Array.from({ length: 12 }, (_, index) => ({ [field]: `/url-${index}`, _count: 12 - index })));
}
return Promise.resolve([
{ [field]: "low", _count: 2 },
{ [field]: "high", _count: 9 },
]);
}),
create: vi.fn().mockResolvedValue({ id: "page_view_1" }),
deleteMany: vi.fn().mockResolvedValue({ count: 1 }),
},
user: {
findMany: vi.fn().mockResolvedValue([
{ id: "user_1", email: "ada@example.com", firstName: "Ada", lastName: "Lovelace" },
{ id: "user_2", email: "grace@example.com", firstName: null, lastName: null },
]),
},
featureFlag: {
findFirst: vi.fn().mockResolvedValue({ id: "flag_1" }),
findMany: vi.fn().mockResolvedValue([{ id: "flag_1", name: "New home" }]),
},
portal: {
findMany: vi.fn().mockResolvedValue([{ id: "portal_1", title: "Docs portal" }]),
},
};
}
function createVisitor(overrides: Partial<AnalyticsUniqueVisitor> = {}): AnalyticsUniqueVisitor {
return {
id: "visitor_1",
cookie: "cookie_1",
source: "google",
medium: "cpc",
campaign: "spring",
content: "hero",
term: "analytics",
country: "DE",
city: "Berlin",
userId: "user_1",
portalUserId: "portal_user_1",
...overrides,
};
}
describe("analytics period helpers", () => {
it("exposes a default period and rejects invalid periods", () => {
expect(defaultAnalyticsPeriod).toBe("last-30-days");
expect(isAnalyticsPeriod("last-hour")).toBe(true);
expect(isAnalyticsPeriod("last-7-days")).toBe(true);
expect(isAnalyticsPeriod("not-a-period")).toBe(false);
});
});
describe("analytics redaction helpers", () => {
it("strips sensitive query data from stored analytics URLs and referrers", () => {
expect(sanitizeAnalyticsUrl("/reset?token=secret&utm_source=newsletter&email=ada@example.com")).toBe("/reset?utm_source=newsletter");
expect(sanitizeAnalyticsUrl("https://example.com/callback?code=secret&ref=docs#ignored")).toBe("https://example.com/callback?ref=docs");
expect(sanitizeAnalyticsReferrer("https://referrer.example.com/path?token=secret")).toBe("https://referrer.example.com");
});
});
describe("analytics overview aggregation", () => {
it("passes portal and last-7-days createdAt filters to count and groupBy calls", async () => {
const client = createAnalyticsClient();
const now = new Date("2024-06-20T12:00:00.000Z");
await getAnalyticsOverview({ period: "last-7-days", portalId: "portal_1", now }, client);
expect(client.analyticsUniqueVisitor.count).toHaveBeenCalledWith({
where: { portalId: "portal_1", createdAt: { gte: new Date("2024-06-13T12:00:00.000Z") } },
});
expect(client.analyticsPageView.count).toHaveBeenCalledWith({
where: { portalId: "portal_1", createdAt: { gte: new Date("2024-06-13T12:00:00.000Z") } },
});
expect(client.analyticsEvent.count).toHaveBeenCalledWith({
where: { portalId: "portal_1", createdAt: { gte: new Date("2024-06-13T12:00:00.000Z") } },
});
expect(client.analyticsUniqueVisitor.groupBy).toHaveBeenCalledWith(
expect.objectContaining({
by: ["source"],
where: { portalId: "portal_1", createdAt: { gte: new Date("2024-06-13T12:00:00.000Z") } },
}),
);
});
it("uses a last-hour window for totals and a one-minute window for live visitors", async () => {
const client = createAnalyticsClient();
const now = new Date("2024-06-20T12:30:00.000Z");
await getAnalyticsOverview({ period: "last-hour", portalId: null, now }, client);
expect(client.analyticsPageView.count).toHaveBeenCalledWith({
where: { portalId: null, createdAt: { gte: new Date("2024-06-20T11:30:00.000Z") } },
});
expect(client.analyticsPageView.groupBy).toHaveBeenCalledWith(
expect.objectContaining({
by: ["uniqueVisitorId"],
where: { portalId: null, createdAt: { gte: new Date("2024-06-20T12:29:00.000Z") } },
}),
);
});
it("anchors all-time ranges to the first tracked visitor for totals and charts", async () => {
const client = createAnalyticsClient();
vi.mocked(client.analyticsUniqueVisitor.findFirst).mockResolvedValue({ createdAt: new Date("2024-01-02T03:04:05.000Z") });
await getAnalyticsOverview({ period: "all-time", portalId: "portal_2", now: new Date("2024-06-20T12:00:00.000Z") }, client);
expect(client.analyticsUniqueVisitor.findFirst).toHaveBeenCalledWith({ where: { portalId: "portal_2" }, orderBy: { createdAt: "asc" } });
expect(client.analyticsUniqueVisitor.count).toHaveBeenCalledWith({
where: { portalId: "portal_2", createdAt: { gte: new Date("2024-01-02T03:04:05.000Z") } },
});
expect(client.analyticsPageView.groupBy).toHaveBeenCalledWith(
expect.objectContaining({
by: ["createdAt"],
where: { portalId: "portal_2", createdAt: { gte: new Date("2024-01-02T03:04:05.000Z") } },
}),
);
});
it("sorts top counts, caps URLs, counts live visitor groups, skips users by default, and aggregates chart labels", async () => {
const client = createAnalyticsClient();
const overview = await getAnalyticsOverview({ period: "last-7-days", portalId: "portal_1", now: new Date("2024-06-20T12:00:00.000Z") }, client);
expect(overview).toMatchObject({ uniqueVisitors: 4, pageViews: 12, events: 8, liveVisitors: 2 });
expect(overview.top.sources).toEqual([
{ name: "high", count: 7 },
{ name: null, count: 3 },
{ name: "low", count: 1 },
]);
expect(overview.top.urls).toHaveLength(10);
expect(overview.top.urls[0]).toEqual({ name: "/url-0", count: 12 });
expect(overview.top.user).toEqual([]);
expect(client.user.findMany).not.toHaveBeenCalled();
expect(client.analyticsUniqueVisitor.groupBy).not.toHaveBeenCalledWith(expect.objectContaining({ by: ["userId"] }));
expect(overview.charts.pageViewsAndUniqueVisitors).toEqual([
{ date: "Jun 15", "Page views": 9, "Unique visitors": 3 },
{ date: "Jun 16", "Page views": 6, "Unique visitors": 3 },
]);
});
it("formats chart bucket labels with the requested locale without changing counts", async () => {
const client = createAnalyticsClient();
const overview = await getAnalyticsOverview(
{ period: "last-7-days", portalId: "portal_1", locale: "de", now: new Date("2024-06-20T12:00:00.000Z") },
client,
);
expect(overview.charts.pageViewsAndUniqueVisitors).toEqual([
{ date: "15. Juni", "Page views": 9, "Unique visitors": 3 },
{ date: "16. Juni", "Page views": 6, "Unique visitors": 3 },
]);
});
it("looks up top user display names only when requested without selecting password fields", async () => {
const client = createAnalyticsClient();
vi.mocked(client.analyticsUniqueVisitor.groupBy).mockImplementation(({ by }) => {
const field = by[0];
if (field === "userId") {
return Promise.resolve([
{ userId: "user_1", _count: 5 },
{ userId: "user_2", _count: 3 },
{ userId: null, _count: 1 },
]);
}
if (field === "createdAt") {
return Promise.resolve([{ createdAt: new Date("2024-06-16T01:00:00.000Z"), _count: 3 }]);
}
return Promise.resolve([{ [field]: "high", _count: 7 }]);
});
const overview = await getAnalyticsOverview({ period: "last-7-days", portalId: "portal_1", withUsers: true, now: new Date("2024-06-20T12:00:00.000Z") }, client);
expect(client.analyticsUniqueVisitor.groupBy).toHaveBeenCalledWith({
by: ["userId"],
_count: true,
where: { portalId: "portal_1", createdAt: { gte: new Date("2024-06-13T12:00:00.000Z") } },
});
expect(client.user.findMany).toHaveBeenCalledWith({
select: { id: true, email: true, firstName: true, lastName: true },
where: { id: { in: ["user_1", "user_2"] } },
});
expect(overview.top.user).toEqual([
{ name: "Ada Lovelace", count: 5 },
{ name: "grace@example.com", count: 3 },
{ name: null, count: 1 },
]);
});
});
describe("analytics list read models", () => {
it("reads visitor pages with pagination, count filters, and relation counts", async () => {
const client = createAnalyticsClient();
const where = { source: "google" };
await expect(getAnalyticsVisitorList({ take: 25, skip: 50, where }, client)).resolves.toEqual({ items: [{ id: "visitor_1" }], totalItems: 4 });
expect(client.analyticsUniqueVisitor.findMany).toHaveBeenCalledWith({
take: 25,
skip: 50,
where,
include: {
_count: {
select: {
pageViews: true,
events: true,
},
},
},
orderBy: { createdAt: "desc" },
});
expect(client.analyticsUniqueVisitor.count).toHaveBeenCalledWith({ where });
});
it("reads event pages with pass-through filters and unique visitor include", async () => {
const client = createAnalyticsClient();
const where = { action: "click", category: { not: null } };
await expect(getAnalyticsEventList({ take: 10, skip: 20, where }, client)).resolves.toEqual({ items: [{ id: "event_1" }], totalItems: 8 });
expect(client.analyticsEvent.findMany).toHaveBeenCalledWith({
take: 10,
skip: 20,
include: { uniqueVisitor: true },
orderBy: { createdAt: "desc" },
where,
});
expect(client.analyticsEvent.count).toHaveBeenCalledWith({ where });
});
it("reads page-view pages with visitor user email and portal title only", async () => {
const client = createAnalyticsClient();
const where = { uniqueVisitor: { userId: "user_1" } };
await expect(getAnalyticsPageViewList({ take: 15, skip: 30, where }, client)).resolves.toEqual({ items: [{ id: "page_view_1" }], totalItems: 12 });
expect(client.analyticsPageView.findMany).toHaveBeenCalledWith({
take: 15,
skip: 30,
include: {
uniqueVisitor: {
include: {
user: {
select: { email: true },
},
},
},
portal: { select: { id: true, title: true } },
},
orderBy: { createdAt: "desc" },
where,
});
expect(client.analyticsPageView.count).toHaveBeenCalledWith({ where });
});
it("provides event action/category/label/value and feature flag filter option shapes", async () => {
const client = createAnalyticsClient();
await expect(getAnalyticsEventFilterOptions(client)).resolves.toEqual({
actions: [{ value: "action_1", name: "action_1" }],
categories: [{ value: "category_1", name: "category_1" }],
labels: [{ value: "label_1", name: "label_1" }],
values: [{ value: "value_1", name: "value_1" }],
featureFlags: [{ value: "flag_1", name: "New home" }],
});
expect(client.analyticsEvent.groupBy).toHaveBeenCalledWith({ by: ["action"] });
expect(client.analyticsEvent.groupBy).toHaveBeenCalledWith({ where: { category: { not: null } }, by: ["category"] });
expect(client.analyticsEvent.groupBy).toHaveBeenCalledWith({ where: { label: { not: null } }, by: ["label"] });
expect(client.analyticsEvent.groupBy).toHaveBeenCalledWith({ where: { value: { not: null } }, by: ["value"] });
expect(client.featureFlag.findMany).toHaveBeenCalledWith({ select: { id: true, name: true }, where: { enabled: undefined } });
});
it("provides page-view route, portal, and display-only user option shapes", async () => {
const client = createAnalyticsClient();
vi.mocked(client.analyticsUniqueVisitor.groupBy).mockResolvedValue([{ userId: "user_1" }, { userId: null }]);
await expect(getAnalyticsPageViewFilterOptions({ includePortals: true }, client)).resolves.toEqual({
routes: [
{ value: "low", name: "low" },
{ value: "high", name: "high" },
],
users: [
{ value: "user_1", name: "ada@example.com" },
{ value: "user_2", name: "grace@example.com" },
],
portals: [{ value: "portal_1", name: "Docs portal" }],
});
expect(client.analyticsPageView.groupBy).toHaveBeenCalledWith({ by: ["route"] });
expect(client.analyticsUniqueVisitor.groupBy).toHaveBeenCalledWith({ by: ["userId"] });
expect(client.user.findMany).toHaveBeenCalledWith({
select: { id: true, email: true },
where: { id: { in: ["user_1", ""] } },
});
expect(client.portal.findMany).toHaveBeenCalledWith({ select: { id: true, title: true } });
});
});
describe("analytics write helpers", () => {
it("creates and updates unique visitors through the injected analytics client", async () => {
const client = createAnalyticsClient();
vi.mocked(client.analyticsUniqueVisitor.findUnique).mockResolvedValue(null);
await getOrCreateAnalyticsUniqueVisitor(
{
cookie: "cookie_2",
fromUrl: "/from",
fromRoute: "/route",
analytics: {
userAgent: { type: "desktop", os: { family: "macOS", version: "14" }, browser: { name: "Chrome", version: "120" } },
referrer: {
http: "https://example.com/path?token=secret",
via: "web",
source: "newsletter",
utm_medium: "email",
utm_campaign: "launch",
utm_content: "button",
utm_term: "toolctrl",
},
region: { country: "US", city: "Austin" },
userId: "user_2",
portalId: "portal_1",
portalUserId: "portal_user_2",
},
},
client,
);
expect(client.analyticsUniqueVisitor.create).toHaveBeenCalledWith({
data: {
cookie: "cookie_2",
httpReferrer: "https://example.com",
via: "web",
browser: "Chrome",
browserVersion: "120",
os: "macOS",
osVersion: "14",
device: "desktop",
source: "newsletter",
medium: "email",
campaign: "launch",
content: "button",
term: "toolctrl",
country: "US",
city: "Austin",
fromUrl: "/from",
fromRoute: "/route",
userId: "user_2",
portalId: "portal_1",
portalUserId: "portal_user_2",
},
});
await updateAnalyticsUniqueVisitorSource(createVisitor({ source: "old", medium: "old" }), { referrer: { source: "new", utm_medium: "organic" } }, client);
expect(client.analyticsUniqueVisitor.update).toHaveBeenCalledWith({
where: { id: "visitor_1" },
data: { source: "new", medium: "organic" },
});
});
it("does not update a visitor when no tracked fields changed", async () => {
const client = createAnalyticsClient();
await updateAnalyticsUniqueVisitorSource(createVisitor(), { referrer: { source: "google", utm_medium: "cpc", utm_campaign: "spring" }, region: { country: "DE", city: "Berlin" }, userId: "user_1", portalUserId: "portal_user_1" }, client);
expect(client.analyticsUniqueVisitor.update).not.toHaveBeenCalled();
});
it("creates page views, events, reads settings, and looks up feature flags", async () => {
const client = createAnalyticsClient();
await createAnalyticsPageView({ uniqueVisitorId: "visitor_1", url: "/docs?token=secret&utm_source=newsletter", route: "/docs", portalId: "portal_1", portalUserId: "portal_user_1" }, client);
await createAnalyticsEvent({ uniqueVisitorId: "visitor_1", action: "click", category: "cta", url: "/event?email=ada@example.com", portalId: "portal_1", featureFlagId: "flag_1" }, client);
await expect(getAnalyticsSettings(client)).resolves.toEqual({ id: "settings_1", public: false, ignorePages: "/health", onlyPages: "" });
await expect(findFeatureFlagByName("new-home", client)).resolves.toEqual({ id: "flag_1" });
expect(client.analyticsPageView.create).toHaveBeenCalledWith({ data: { uniqueVisitorId: "visitor_1", url: "/docs?utm_source=newsletter", route: "/docs", portalId: "portal_1", portalUserId: "portal_user_1" } });
expect(client.analyticsEvent.create).toHaveBeenCalledWith({ data: { uniqueVisitorId: "visitor_1", action: "click", category: "cta", url: "/event", portalId: "portal_1", featureFlagId: "flag_1" } });
expect(client.analyticsSettings.findFirst).toHaveBeenCalledWith({ select: { public: true, ignorePages: true } });
expect(client.featureFlag.findFirst).toHaveBeenCalledWith({ where: { name: "new-home" }, select: { id: true } });
});
it("gets or creates analytics settings with the package-owned defaults", async () => {
const client = createAnalyticsClient();
vi.mocked(client.analyticsSettings.findFirst).mockResolvedValueOnce(null);
await expect(getOrCreateAnalyticsSettings(client)).resolves.toEqual({ id: "settings_1", public: false, ignorePages: "/analytics,/admin/analytics", onlyPages: "" });
expect(client.analyticsSettings.findFirst).toHaveBeenCalledWith({});
expect(client.analyticsSettings.create).toHaveBeenCalledWith({ data: { public: false, ignorePages: "/analytics", onlyPages: "" } });
});
it("updates analytics public and ignored-page preferences without duplicating existing pages", async () => {
const client = createAnalyticsClient();
await updateAnalyticsSettingsPreferences({ public: true, ignorePage: "/docs" }, client);
expect(client.analyticsSettings.update).toHaveBeenCalledWith({
where: { id: "settings_1" },
data: { public: true, ignorePages: "/health,/docs" },
});
await updateAnalyticsSettingsPreferences({ public: false, ignorePage: "/health" }, client);
expect(client.analyticsSettings.update).toHaveBeenLastCalledWith({
where: { id: "settings_1" },
data: { public: false, ignorePages: "/health" },
});
});
it("removes ignored pages while leaving non-existing removals as a safe no-op list update", async () => {
const client = createAnalyticsClient();
await removeAnalyticsIgnoredPage("/missing", client);
expect(client.analyticsSettings.update).toHaveBeenCalledWith({
where: { id: "settings_1" },
data: { ignorePages: "/health" },
});
vi.mocked(client.analyticsSettings.findFirst).mockResolvedValueOnce({ id: "settings_1", public: false, ignorePages: "/health,/docs", onlyPages: "" });
await removeAnalyticsIgnoredPage("/health", client);
expect(client.analyticsSettings.update).toHaveBeenLastCalledWith({
where: { id: "settings_1" },
data: { ignorePages: "/docs" },
});
});
it("deletes analytics data through relation-safe package-owned delete calls", async () => {
const client = createAnalyticsClient();
await deleteAllAnalyticsData(client);
expect(client.analyticsEvent.deleteMany).toHaveBeenCalledWith({});
expect(client.analyticsPageView.deleteMany).toHaveBeenCalledWith({});
expect(client.analyticsUniqueVisitor.deleteMany).toHaveBeenCalledWith({});
expect(vi.mocked(client.analyticsEvent.deleteMany).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(client.analyticsPageView.deleteMany).mock.invocationCallOrder[0]);
expect(vi.mocked(client.analyticsPageView.deleteMany).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(client.analyticsUniqueVisitor.deleteMany).mock.invocationCallOrder[0]);
});
});
@@ -0,0 +1,920 @@
import { getDbClient } from "./client.server.js";
export type AnalyticsInfo = {
userAgent?: {
type?: string;
os: {
family?: string;
version?: string;
};
browser: {
name?: string;
version?: string;
};
};
referrer?: {
via?: string | null;
http?: string;
source?: string;
utm_medium?: string;
utm_campaign?: string;
utm_content?: string;
utm_term?: string;
};
region?: {
country?: string;
city?: string;
};
userId?: string | null;
portalId?: string | null;
portalUserId?: string | null;
userAnalyticsId?: string;
};
export const analyticsPeriods = [
"all-time",
"last-year",
"last-3-months",
"last-30-days",
"last-7-days",
"last-24-hours",
"year-to-date",
"month-to-date",
"week-to-date",
"last-hour",
"last-10-minutes",
] as const;
export type AnalyticsPeriod = (typeof analyticsPeriods)[number];
export const defaultAnalyticsPeriod: AnalyticsPeriod = "last-30-days";
export type AnalyticsTopCount = {
name: string | null;
count: number;
};
export type AnalyticsOverview = {
uniqueVisitors: number;
pageViews: number;
events: number;
liveVisitors: number;
top: {
sources: AnalyticsTopCount[];
httpReferrers: AnalyticsTopCount[];
urls: AnalyticsTopCount[];
routes: AnalyticsTopCount[];
os: AnalyticsTopCount[];
devices: AnalyticsTopCount[];
countries: AnalyticsTopCount[];
via: AnalyticsTopCount[];
medium: AnalyticsTopCount[];
campaign: AnalyticsTopCount[];
user: AnalyticsTopCount[];
};
charts: {
pageViewsAndUniqueVisitors: Array<{
date: string;
"Page views": number;
"Unique visitors": number;
}>;
};
};
export type AnalyticsOverviewOptions = {
period?: AnalyticsPeriod;
portalId: string | null | undefined;
withUsers?: boolean;
now?: Date;
locale?: string;
};
export type AnalyticsUniqueVisitor = {
id: string;
cookie: string;
source: string | null;
medium: string | null;
campaign: string | null;
content: string | null;
term: string | null;
country: string | null;
city: string | null;
userId: string | null;
portalUserId: string | null;
createdAt?: Date;
fromUrl?: string | null;
fromRoute?: string | null;
via?: string | null;
browser?: string | null;
browserVersion?: string | null;
os?: string | null;
osVersion?: string | null;
device?: string | null;
portalId?: string | null;
httpReferrer?: string | null;
};
export type AnalyticsListReadOptions<Where> = {
take: number;
skip: number;
where?: Where;
};
export type AnalyticsVisitorWhereInput = Record<string, unknown>;
export type AnalyticsEventWhereInput = Record<string, unknown>;
export type AnalyticsEvent = {
id: string;
uniqueVisitorId: string;
action: string;
category: string | null;
label: string | null;
value: string | null;
url: string | null;
route: string | null;
featureFlagId: string | null;
portalId: string | null;
portalUserId: string | null;
createdAt?: Date;
};
export type AnalyticsPageViewWhereInput = Record<string, unknown>;
export type AnalyticsPageView = {
id: string;
uniqueVisitorId: string;
url: string;
route: string | null;
portalId: string | null;
portalUserId: string | null;
createdAt?: Date;
};
export type AnalyticsOption = {
value: string;
name: string;
};
export type AnalyticsSettings = {
id: string;
public: boolean;
ignorePages: string;
onlyPages: string;
};
export type AnalyticsSettingsUpdateInput = {
public: boolean;
ignorePage?: string;
};
export const defaultAnalyticsSettingsPreferences = {
public: false,
ignorePages: "/analytics",
onlyPages: "",
} as const;
const SENSITIVE_ANALYTICS_QUERY_KEYS = new Set(["token", "code", "email", "secret", "key", "api_key", "apikey", "session", "session_id", "password"]);
const ALLOWED_ANALYTICS_QUERY_PREFIXES = ["utm_"];
const ALLOWED_ANALYTICS_QUERY_KEYS = new Set(["ref", "source"]);
export function sanitizeAnalyticsUrl(value: string | null | undefined): string | null {
if (!value) {
return value ?? null;
}
try {
const url = new URL(value);
return serializeSanitizedAnalyticsUrl(url, true);
} catch {
try {
const url = new URL(value, "https://analytics.local");
return serializeSanitizedAnalyticsUrl(url, false);
} catch {
return value.split("?")[0] ?? value;
}
}
}
export function sanitizeAnalyticsReferrer(value: string | null | undefined): string | null {
if (!value) {
return value ?? null;
}
try {
return new URL(value).origin;
} catch {
return sanitizeAnalyticsUrl(value);
}
}
function serializeSanitizedAnalyticsUrl(url: URL, includeOrigin: boolean): string {
const searchParams = new URLSearchParams();
url.searchParams.forEach((value, key) => {
const normalizedKey = key.toLowerCase();
if (SENSITIVE_ANALYTICS_QUERY_KEYS.has(normalizedKey)) {
return;
}
if (ALLOWED_ANALYTICS_QUERY_KEYS.has(normalizedKey) || ALLOWED_ANALYTICS_QUERY_PREFIXES.some((prefix) => normalizedKey.startsWith(prefix))) {
searchParams.append(key, value);
}
});
const search = searchParams.toString();
return `${includeOrigin ? url.origin : ""}${url.pathname}${search ? `?${search}` : ""}`;
}
type AnalyticsUniqueVisitorCreateData = {
cookie: string;
httpReferrer?: string | null;
via?: string | null;
browser?: string | null;
browserVersion?: string | null;
os?: string | null;
osVersion?: string | null;
device?: string | null;
source?: string;
medium?: string;
campaign?: string;
content?: string;
term?: string;
country?: string;
city?: string;
fromUrl?: string;
fromRoute?: string;
userId?: string | null;
portalId: string | null;
portalUserId?: string | null;
};
type AnalyticsUniqueVisitorUpdateData = Partial<
Pick<AnalyticsUniqueVisitor, "source" | "medium" | "campaign" | "content" | "term" | "country" | "city" | "userId" | "portalUserId">
>;
export type AnalyticsClient = {
analyticsSettings: {
findFirst(args: { select: { public: true; ignorePages: true } }): Promise<{ public: boolean; ignorePages: string } | null>;
findFirst(args: Record<string, never>): Promise<AnalyticsSettings | null>;
create(args: { data: typeof defaultAnalyticsSettingsPreferences }): Promise<AnalyticsSettings>;
update(args: { where: { id: string }; data: { public?: boolean; ignorePages?: string } }): Promise<AnalyticsSettings>;
};
analyticsUniqueVisitor: {
count(args: { where: { portalId: string | null | undefined; createdAt: AnalyticsDateRange } } | { where?: AnalyticsVisitorWhereInput }): Promise<number>;
findFirst(args: { where: { portalId: string | null | undefined }; orderBy: { createdAt: "asc" } }): Promise<{ createdAt: Date } | null>;
findUnique(args: { where: { cookie: string } }): Promise<AnalyticsUniqueVisitor | null>;
create(args: { data: AnalyticsUniqueVisitorCreateData }): Promise<AnalyticsUniqueVisitor>;
update(args: { where: { id: string }; data: AnalyticsUniqueVisitorUpdateData }): Promise<AnalyticsUniqueVisitor>;
groupBy(args: {
by: string[];
_count?: true;
where?: Record<string, unknown>;
}): Promise<Array<Record<string, unknown> & { _count?: number }>>;
findMany(args: {
take: number;
skip: number;
include: { _count: { select: { pageViews: true; events: true } } };
orderBy: { createdAt: "desc" };
where?: AnalyticsVisitorWhereInput;
}): Promise<Array<AnalyticsUniqueVisitor & { _count: { pageViews: number; events: number } }>>;
deleteMany(args: Record<string, never>): Promise<unknown>;
};
analyticsEvent: {
count(args: { where?: AnalyticsEventWhereInput | { portalId: string | null | undefined; createdAt: AnalyticsDateRange } }): Promise<number>;
groupBy(args: { by: string[]; where?: Record<string, unknown> }): Promise<Array<Record<string, unknown>>>;
findMany(args: {
take: number;
skip: number;
include: { uniqueVisitor: true };
orderBy: { createdAt: "desc" };
where?: AnalyticsEventWhereInput;
}): Promise<Array<AnalyticsEvent & { uniqueVisitor: AnalyticsUniqueVisitor }>>;
create(args: {
data: {
uniqueVisitorId: string;
action: string;
category?: string;
label?: string;
value?: string;
url?: string;
route?: string;
featureFlagId?: string;
portalId: string | null;
portalUserId?: string | null;
};
}): Promise<unknown>;
deleteMany(args: Record<string, never>): Promise<unknown>;
};
analyticsPageView: {
count(args: { where?: AnalyticsPageViewWhereInput | { portalId: string | null | undefined; createdAt: AnalyticsDateRange } }): Promise<number>;
groupBy(args: {
by: string[];
_count?: true;
where?: Record<string, unknown>;
}): Promise<Array<Record<string, unknown> & { _count?: number }>>;
findMany(args: {
take: number;
skip: number;
include: {
uniqueVisitor: { include: { user: { select: { email: true } } } };
portal: { select: { id: true; title: true } };
};
orderBy: { createdAt: "desc" };
where?: AnalyticsPageViewWhereInput;
}): Promise<Array<AnalyticsPageView & { uniqueVisitor: AnalyticsUniqueVisitor & { user: { email: string } | null }; portal: { id: string; title: string } | null }>>;
create(args: {
data: {
uniqueVisitorId: string;
url: string;
route?: string;
portalId: string | null;
portalUserId?: string | null;
};
}): Promise<unknown>;
deleteMany(args: Record<string, never>): Promise<unknown>;
};
user: {
findMany(args: {
select: { id: true; email: true; firstName: true; lastName: true };
where: { id: { in: string[] } };
}): Promise<Array<{ id: string; email: string | null; firstName: string | null; lastName: string | null }>>;
findMany(args: {
select: { id: true; email: true };
where: { id: { in: string[] } };
}): Promise<Array<{ id: string; email: string | null }>>;
};
featureFlag: {
findFirst(args: { where: { name: string }; select: { id: true } }): Promise<{ id: string } | null>;
findMany(args: { select: { id: true; name: true }; where?: { enabled?: boolean } }): Promise<Array<{ id: string; name: string }>>;
};
portal: {
findMany(args: { select: { id: true; title: true } }): Promise<Array<{ id: string; title: string }>>;
};
};
type AnalyticsDateRange = {
gte?: Date;
lte?: Date;
};
function getAnalyticsClient(): AnalyticsClient {
return getDbClient() as unknown as AnalyticsClient;
}
export async function getAnalyticsSettings(client: AnalyticsClient = getAnalyticsClient()): Promise<{ public: boolean; ignorePages: string } | null> {
return client.analyticsSettings.findFirst({
select: { public: true, ignorePages: true },
});
}
export async function getOrCreateAnalyticsSettings(client: AnalyticsClient = getAnalyticsClient()): Promise<AnalyticsSettings> {
const settings = await client.analyticsSettings.findFirst({});
if (settings) {
return settings;
}
return client.analyticsSettings.create({ data: defaultAnalyticsSettingsPreferences });
}
export async function updateAnalyticsSettingsPreferences(
{ public: isPublic, ignorePage }: AnalyticsSettingsUpdateInput,
client: AnalyticsClient = getAnalyticsClient(),
): Promise<AnalyticsSettings> {
const settings = await getOrCreateAnalyticsSettings(client);
const ignorePages = appendIgnoredPage(settings.ignorePages, ignorePage);
return client.analyticsSettings.update({
where: { id: settings.id },
data: {
public: isPublic,
ignorePages,
},
});
}
export async function removeAnalyticsIgnoredPage(ignoredPage: string, client: AnalyticsClient = getAnalyticsClient()): Promise<AnalyticsSettings> {
const settings = await getOrCreateAnalyticsSettings(client);
const ignorePages = settings.ignorePages
.split(",")
.filter((page) => page !== "" && page !== ignoredPage)
.join(",");
return client.analyticsSettings.update({
where: { id: settings.id },
data: { ignorePages },
});
}
export async function deleteAllAnalyticsData(client: AnalyticsClient = getAnalyticsClient()): Promise<void> {
await client.analyticsEvent.deleteMany({});
await client.analyticsPageView.deleteMany({});
await client.analyticsUniqueVisitor.deleteMany({});
}
function appendIgnoredPage(ignorePages: string, ignorePage?: string): string {
const pages = ignorePages.split(",");
if (ignorePage && !pages.includes(ignorePage)) {
pages.push(ignorePage);
}
return pages.join(",");
}
export async function getOrCreateAnalyticsUniqueVisitor(
{
cookie,
fromUrl,
fromRoute,
analytics,
}: {
cookie: string;
fromUrl?: string;
fromRoute?: string;
analytics: AnalyticsInfo;
},
client: AnalyticsClient = getAnalyticsClient(),
): Promise<AnalyticsUniqueVisitor> {
const visitor = await client.analyticsUniqueVisitor.findUnique({
where: { cookie },
});
if (visitor) {
return visitor;
}
return client.analyticsUniqueVisitor.create({
data: {
cookie,
httpReferrer: sanitizeAnalyticsReferrer(analytics.referrer?.http),
via: analytics.referrer?.via ?? null,
browser: analytics.userAgent?.browser?.name ?? null,
browserVersion: analytics.userAgent?.browser?.version ?? null,
os: analytics.userAgent?.os?.family ?? null,
osVersion: analytics.userAgent?.os?.version ?? null,
device: analytics.userAgent?.type ?? null,
source: analytics.referrer?.source,
medium: analytics.referrer?.utm_medium,
campaign: analytics.referrer?.utm_campaign,
content: analytics.referrer?.utm_content,
term: analytics.referrer?.utm_term,
country: analytics.region?.country,
city: analytics.region?.city,
fromUrl: sanitizeAnalyticsUrl(fromUrl) ?? undefined,
fromRoute,
userId: analytics.userId ?? null,
portalId: analytics.portalId ?? null,
portalUserId: analytics.portalUserId ?? null,
},
});
}
export async function updateAnalyticsUniqueVisitorSource(
visitor: AnalyticsUniqueVisitor,
analytics: AnalyticsInfo,
client: AnalyticsClient = getAnalyticsClient(),
): Promise<void> {
const data: AnalyticsUniqueVisitorUpdateData = {};
if (analytics.referrer?.source && visitor.source !== analytics.referrer.source) {
data.source = analytics.referrer.source;
}
if (analytics.referrer?.utm_medium && visitor.medium !== analytics.referrer.utm_medium) {
data.medium = analytics.referrer.utm_medium;
}
if (analytics.referrer?.utm_campaign && visitor.campaign !== analytics.referrer.utm_campaign) {
data.campaign = analytics.referrer.utm_campaign;
}
if (analytics.referrer?.utm_content && visitor.content !== analytics.referrer.utm_content) {
data.content = analytics.referrer.utm_content;
}
if (analytics.referrer?.utm_term && visitor.term !== analytics.referrer.utm_term) {
data.term = analytics.referrer.utm_term;
}
if (analytics.region?.country && visitor.country !== analytics.region.country) {
data.country = analytics.region.country;
}
if (analytics.region?.city && visitor.city !== analytics.region.city) {
data.city = analytics.region.city;
}
if (analytics.userId && visitor.userId !== analytics.userId) {
data.userId = analytics.userId;
}
if (analytics.portalUserId && visitor.portalUserId !== analytics.portalUserId) {
data.portalUserId = analytics.portalUserId;
}
if (Object.keys(data).length === 0) {
return;
}
await client.analyticsUniqueVisitor.update({
where: { id: visitor.id },
data,
});
}
export async function findFeatureFlagByName(name: string, client: AnalyticsClient = getAnalyticsClient()): Promise<{ id: string } | null> {
return client.featureFlag.findFirst({
where: { name },
select: { id: true },
});
}
export async function getAnalyticsVisitorList(
{ take, skip, where }: AnalyticsListReadOptions<AnalyticsVisitorWhereInput>,
client: AnalyticsClient = getAnalyticsClient(),
): Promise<{ items: Array<AnalyticsUniqueVisitor & { _count: { pageViews: number; events: number } }>; totalItems: number }> {
const [items, totalItems] = await Promise.all([
client.analyticsUniqueVisitor.findMany({
take,
skip,
...(where ? { where } : {}),
include: {
_count: {
select: {
pageViews: true,
events: true,
},
},
},
orderBy: {
createdAt: "desc",
},
}),
client.analyticsUniqueVisitor.count(where ? { where } : {}),
]);
return { items, totalItems };
}
export async function getAnalyticsEventList(
{ take, skip, where }: AnalyticsListReadOptions<AnalyticsEventWhereInput>,
client: AnalyticsClient = getAnalyticsClient(),
): Promise<{ items: Array<AnalyticsEvent & { uniqueVisitor: AnalyticsUniqueVisitor }>; totalItems: number }> {
const [items, totalItems] = await Promise.all([
client.analyticsEvent.findMany({
take,
skip,
include: { uniqueVisitor: true },
orderBy: {
createdAt: "desc",
},
...(where ? { where } : {}),
}),
client.analyticsEvent.count(where ? { where } : {}),
]);
return { items, totalItems };
}
export async function getAnalyticsPageViewList(
{ take, skip, where }: AnalyticsListReadOptions<AnalyticsPageViewWhereInput>,
client: AnalyticsClient = getAnalyticsClient(),
): Promise<{ items: Array<AnalyticsPageView & { uniqueVisitor: AnalyticsUniqueVisitor & { user: { email: string } | null }; portal: { id: string; title: string } | null }>; totalItems: number }> {
const [items, totalItems] = await Promise.all([
client.analyticsPageView.findMany({
take,
skip,
include: {
uniqueVisitor: {
include: {
user: {
select: { email: true },
},
},
},
portal: { select: { id: true, title: true } },
},
orderBy: {
createdAt: "desc",
},
...(where ? { where } : {}),
}),
client.analyticsPageView.count(where ? { where } : {}),
]);
return { items, totalItems };
}
export async function getAnalyticsEventFilterOptions(client: AnalyticsClient = getAnalyticsClient()): Promise<{
actions: AnalyticsOption[];
categories: AnalyticsOption[];
labels: AnalyticsOption[];
values: AnalyticsOption[];
featureFlags: AnalyticsOption[];
}> {
const [actions, categories, labels, values, featureFlags] = await Promise.all([
client.analyticsEvent.groupBy({ by: ["action"] }),
client.analyticsEvent.groupBy({ where: { category: { not: null } }, by: ["category"] }),
client.analyticsEvent.groupBy({ where: { label: { not: null } }, by: ["label"] }),
client.analyticsEvent.groupBy({ where: { value: { not: null } }, by: ["value"] }),
client.featureFlag.findMany({ select: { id: true, name: true }, where: { enabled: undefined } }),
]);
return {
actions: toOptions(actions, "action"),
categories: toOptions(categories, "category"),
labels: toOptions(labels, "label"),
values: toOptions(values, "value"),
featureFlags: featureFlags.map((featureFlag) => ({ value: featureFlag.id, name: featureFlag.name })),
};
}
export async function getAnalyticsPageViewFilterOptions(
{ includePortals = false }: { includePortals?: boolean } = {},
client: AnalyticsClient = getAnalyticsClient(),
): Promise<{
routes: AnalyticsOption[];
users: AnalyticsOption[];
portals: AnalyticsOption[];
}> {
const [routes, userIds, portals] = await Promise.all([
client.analyticsPageView.groupBy({ by: ["route"] }),
client.analyticsUniqueVisitor.groupBy({ by: ["userId"] }),
includePortals ? client.portal.findMany({ select: { id: true, title: true } }) : Promise.resolve([]),
]);
const users = await client.user.findMany({
select: { id: true, email: true },
where: { id: { in: userIds.map((row) => (typeof row.userId === "string" ? row.userId : "")) } },
});
return {
routes: toOptions(routes, "route"),
users: users.map((user) => ({ value: user.id, name: user.email ?? "Unknown user" })),
portals: portals.map((portal) => ({ value: portal.id, name: portal.title })),
};
}
function toOptions(rows: Array<Record<string, unknown>>, field: string): AnalyticsOption[] {
return rows
.map((row) => (typeof row[field] === "string" ? { value: row[field], name: row[field] } : null))
.filter((option): option is AnalyticsOption => option !== null);
}
export async function createAnalyticsEvent(
data: {
uniqueVisitorId: string;
action: string;
category?: string;
label?: string;
value?: string;
url?: string;
route?: string;
featureFlagId?: string;
portalId: string | null;
portalUserId?: string | null;
},
client: AnalyticsClient = getAnalyticsClient(),
): Promise<void> {
await client.analyticsEvent.create({ data: { ...data, url: sanitizeAnalyticsUrl(data.url) ?? undefined } });
}
export async function createAnalyticsPageView(
data: {
uniqueVisitorId: string;
url: string;
route?: string;
portalId: string | null;
portalUserId?: string | null;
},
client: AnalyticsClient = getAnalyticsClient(),
): Promise<void> {
await client.analyticsPageView.create({ data: { ...data, url: sanitizeAnalyticsUrl(data.url) ?? data.url } });
}
export function isAnalyticsPeriod(value: string): value is AnalyticsPeriod {
return analyticsPeriods.includes(value as AnalyticsPeriod);
}
export async function getAnalyticsOverview(
{ period = defaultAnalyticsPeriod, portalId, withUsers = false, now = new Date(), locale }: AnalyticsOverviewOptions,
client: AnalyticsClient = getAnalyticsClient(),
): Promise<AnalyticsOverview> {
const createdAt = getAnalyticsCreatedAt(period, now);
if (period === "all-time") {
const firstDate = await client.analyticsUniqueVisitor.findFirst({
where: { portalId },
orderBy: { createdAt: "asc" },
});
if (firstDate) {
createdAt.gte = firstDate.createdAt;
}
}
const [uniqueVisitors, pageViews, events, liveVisitors, httpReferrers, sources, urls, routes, os, devices, countries, via, medium, campaign, user, charts] =
await Promise.all([
client.analyticsUniqueVisitor.count({ where: { portalId, createdAt } }),
client.analyticsPageView.count({ where: { portalId, createdAt } }),
client.analyticsEvent.count({ where: { portalId, createdAt } }),
client.analyticsPageView.groupBy({
by: ["uniqueVisitorId"],
_count: true,
where: { portalId, createdAt: { gte: new Date(now.getTime() - 60_000) } },
}),
groupUniqueVisitorsBy(client, "httpReferrer", portalId, createdAt),
groupUniqueVisitorsBy(client, "source", portalId, createdAt),
groupPageViewsBy(client, "url", portalId, createdAt),
groupPageViewsBy(client, "route", portalId, createdAt),
groupUniqueVisitorsBy(client, "os", portalId, createdAt),
groupUniqueVisitorsBy(client, "device", portalId, createdAt),
groupUniqueVisitorsBy(client, "country", portalId, createdAt),
groupUniqueVisitorsBy(client, "via", portalId, createdAt),
groupUniqueVisitorsBy(client, "medium", portalId, createdAt),
groupUniqueVisitorsBy(client, "campaign", portalId, createdAt),
getAnalyticsOverviewTopUsers(client, portalId, createdAt, withUsers),
getAnalyticsOverviewCharts({ period, portalId, now, locale }, client),
]);
return {
uniqueVisitors,
pageViews,
events,
liveVisitors: liveVisitors.length,
top: {
httpReferrers,
sources,
urls: urls.slice(0, 10),
routes,
os,
devices,
countries,
via,
medium,
campaign,
user,
},
charts,
};
}
async function getAnalyticsOverviewTopUsers(
client: AnalyticsClient,
portalId: string | null | undefined,
createdAt: AnalyticsDateRange,
withUsers: boolean,
): Promise<AnalyticsTopCount[]> {
if (!withUsers) {
return [];
}
const userCounts = await groupUniqueVisitorsBy(client, "userId", portalId, createdAt);
const userIds = userCounts.map((row) => row.name).filter((name): name is string => name !== null);
if (userIds.length === 0) {
return userCounts;
}
const users = await client.user.findMany({
select: { id: true, email: true, firstName: true, lastName: true },
where: { id: { in: userIds } },
});
const displayNames = new Map(users.map((user) => [user.id, formatUserDisplayName(user)]));
return userCounts.map((row) => ({
name: row.name ? (displayNames.get(row.name) ?? row.name) : null,
count: row.count,
}));
}
function formatUserDisplayName(user: { email: string | null; firstName: string | null; lastName: string | null }): string {
const fullName = [user.firstName, user.lastName].filter(Boolean).join(" ").trim();
return fullName || user.email || "Unknown user";
}
async function getAnalyticsOverviewCharts(
{ period, portalId, now, locale }: { period: AnalyticsPeriod; portalId: string | null | undefined; now: Date; locale?: string },
client: AnalyticsClient,
): Promise<AnalyticsOverview["charts"]> {
const createdAt = getAnalyticsCreatedAt(period, now);
if (period === "all-time") {
const firstDate = await client.analyticsUniqueVisitor.findFirst({
where: { portalId },
orderBy: { createdAt: "asc" },
});
if (firstDate) {
createdAt.gte = firstDate.createdAt;
}
}
const [pageViewsByDate, uniqueVisitorsByDate] = await Promise.all([
client.analyticsPageView.groupBy({
by: ["createdAt"],
_count: true,
where: { portalId, createdAt },
}),
client.analyticsUniqueVisitor.groupBy({
by: ["createdAt"],
_count: true,
where: { portalId, createdAt },
}),
]);
const pageViews = aggregateDateCounts(pageViewsByDate, period, locale);
const uniqueVisitors = aggregateDateCounts(uniqueVisitorsByDate, period, locale);
const labels = Array.from(new Set([...pageViews.keys(), ...uniqueVisitors.keys()]));
return {
pageViewsAndUniqueVisitors: labels.map((date) => ({
date,
"Page views": pageViews.get(date) ?? 0,
"Unique visitors": uniqueVisitors.get(date) ?? 0,
})),
};
}
async function groupUniqueVisitorsBy(
client: AnalyticsClient,
field: string,
portalId: string | null | undefined,
createdAt?: AnalyticsDateRange,
): Promise<AnalyticsTopCount[]> {
return toTopCounts(
field,
await client.analyticsUniqueVisitor.groupBy({
by: [field],
_count: true,
where: { portalId, createdAt },
}),
);
}
async function groupPageViewsBy(
client: AnalyticsClient,
field: string,
portalId: string | null | undefined,
createdAt?: AnalyticsDateRange,
): Promise<AnalyticsTopCount[]> {
return toTopCounts(
field,
await client.analyticsPageView.groupBy({
by: [field],
_count: true,
where: { portalId, createdAt },
}),
);
}
function toTopCounts(field: string, rows: Array<Record<string, unknown> & { _count?: number }>): AnalyticsTopCount[] {
return rows
.map((row) => ({
name: typeof row[field] === "string" ? row[field] : null,
count: row._count ?? 0,
}))
.sort((a, b) => b.count - a.count);
}
function aggregateDateCounts(rows: Array<Record<string, unknown> & { _count?: number }>, period: AnalyticsPeriod, locale?: string) {
const counts = new Map<string, number>();
for (const row of rows) {
const createdAt = row.createdAt;
if (!(createdAt instanceof Date)) {
continue;
}
const key = formatAnalyticsDate(createdAt, period, locale);
counts.set(key, (counts.get(key) ?? 0) + (row._count ?? 0));
}
return counts;
}
function formatAnalyticsDate(date: Date, period: AnalyticsPeriod, locale = "en-US") {
if (period === "last-hour" || period === "last-10-minutes") {
return new Intl.DateTimeFormat(locale, { hour: "numeric", minute: "2-digit", timeZone: "UTC" }).format(date);
}
if (period === "last-24-hours") {
return new Intl.DateTimeFormat(locale, { hour: "numeric", timeZone: "UTC" }).format(date);
}
return new Intl.DateTimeFormat(locale, { month: "short", day: "numeric", timeZone: "UTC" }).format(date);
}
function getAnalyticsCreatedAt(period: AnalyticsPeriod, now: Date): AnalyticsDateRange {
switch (period) {
case "all-time":
return {};
case "last-year":
return { gte: daysFromDate(now, -365) };
case "last-3-months":
return { gte: daysFromDate(now, -90) };
case "last-30-days":
return { gte: daysFromDate(now, -30) };
case "last-7-days":
return { gte: daysFromDate(now, -7) };
case "last-24-hours":
return { gte: daysFromDate(now, -1) };
case "year-to-date":
return { gte: new Date(now.getFullYear(), 0, 1) };
case "month-to-date":
return { gte: new Date(now.getFullYear(), now.getMonth(), 1) };
case "week-to-date":
return { gte: weekStartDate(now) };
case "last-hour":
return { gte: minutesFromDate(now, -60) };
case "last-10-minutes":
return { gte: minutesFromDate(now, -10) };
}
}
function daysFromDate(date: Date, days: number) {
return new Date(date.getTime() + days * 24 * 60 * 60 * 1000);
}
function minutesFromDate(date: Date, minutes: number) {
return new Date(date.getTime() + minutes * 60 * 1000);
}
function weekStartDate(date: Date) {
const start = new Date(date);
const day = start.getDay();
const diff = start.getDate() - day + (day === 0 ? -6 : 1);
start.setDate(diff);
start.setHours(0, 0, 0, 0);
return start;
}
@@ -0,0 +1,58 @@
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
const repoRoot = resolve(__dirname, "../../..");
const schemaPath = resolve(repoRoot, "prisma/schema/core.prisma");
const migrationPath = resolve(repoRoot, "prisma/migrations/20260507123000_api_key_hash_columns/migration.sql");
async function readApiKeyModel() {
const schema = await readFile(schemaPath, "utf8");
const match = schema.match(/model ApiKey \{(?<body>[\s\S]*?)\n\}/);
expect(match?.groups?.body, "ApiKey model exists in core Prisma schema").toBeTruthy();
return match?.groups?.body ?? "";
}
describe("ApiKey hash schema contract", () => {
it("keeps the legacy plaintext key while defining nullable hash metadata", async () => {
const apiKeyModel = await readApiKeyModel();
expect(apiKeyModel, "legacy plaintext key remains available for cutover").toMatch(
/^\s*key\s+String\s+@default\(uuid\(\)\)/m,
);
expect(apiKeyModel, "keyHash is nullable until existing keys are backfilled").toMatch(/^\s*keyHash\s+String\?/m);
expect(apiKeyModel, "keyPrefix is nullable lookup/display metadata").toMatch(/^\s*keyPrefix\s+String\?/m);
expect(apiKeyModel, "keyLastFour is nullable display metadata").toMatch(/^\s*keyLastFour\s+String\?/m);
expect(apiKeyModel, "hashedAt is nullable until each key is hashed").toMatch(/^\s*hashedAt\s+DateTime\?/m);
expect(apiKeyModel, "keyVersion defaults new rows onto the initial hash version").toMatch(
/^\s*keyVersion\s+Int\s+@default\(1\)/m,
);
});
it("adds forward-only hash columns and lookup index without raw key fixtures", async () => {
const migrationSql = await readFile(migrationPath, "utf8");
expect(migrationSql, "migration adds nullable keyHash storage").toMatch(
/ADD\s+COLUMN\s+(?:IF\s+NOT\s+EXISTS\s+)?["`]keyHash["`]\s+TEXT/i,
);
expect(migrationSql, "migration adds nullable keyPrefix metadata").toMatch(
/ADD\s+COLUMN\s+(?:IF\s+NOT\s+EXISTS\s+)?["`]keyPrefix["`]\s+TEXT/i,
);
expect(migrationSql, "migration adds nullable keyLastFour metadata").toMatch(
/ADD\s+COLUMN\s+(?:IF\s+NOT\s+EXISTS\s+)?["`]keyLastFour["`]\s+TEXT/i,
);
expect(migrationSql, "migration adds nullable hashedAt metadata").toMatch(
/ADD\s+COLUMN\s+(?:IF\s+NOT\s+EXISTS\s+)?["`]hashedAt["`]\s+TIMESTAMP(?:\(\d+\))?/i,
);
expect(migrationSql, "migration adds defaulted keyVersion metadata").toMatch(
/ADD\s+COLUMN\s+(?:IF\s+NOT\s+EXISTS\s+)?["`]keyVersion["`]\s+INTEGER\s+NOT\s+NULL\s+DEFAULT\s+1/i,
);
expect(migrationSql, "migration creates the unique hash lookup index").toMatch(
/CREATE\s+UNIQUE\s+INDEX\s+["`]api_key_hash_key["`]\s+ON\s+["`]ApiKey["`]\s*\(\s*["`]keyHash["`]\s*\)/i,
);
expect(migrationSql, "migration must not persist raw API-key fixtures").not.toContain("raw-secret");
});
});
@@ -0,0 +1,750 @@
import { describe, expect, it, vi } from "vitest";
import {
adminFindLegacyApiKeyById,
adminDeleteLegacyApiKeyLogsByIds,
countLegacyApiKeyLogsForKey,
countLegacyTenantApiKeyLogs,
countLegacyApiKeyLogs,
createLegacyApiKeyLog,
createLegacyApiKey,
deleteLegacyApiKey,
deleteTenantLegacyApiKeyLogsByIds,
findLegacyApiKeyByKey,
findLegacyApiKeyByAlias,
findLegacyApiKeyById,
findFirstLegacyActiveApiKey,
getAllLegacyApiKeys,
getLegacyApiKeyLogsForKey,
getLegacyApiKeysForTenant,
getLegacyApiKeyLogAdminDetails,
groupLegacyApiKeyLogs,
legacyApiKeyDetailsInclude,
rotateLegacyApiKey,
setLegacyApiKeyLogStatus,
tenantLegacyApiKeyLogScope,
updateLegacyApiKey,
deriveLegacyApiKeyHashMetadata,
backfillLegacyApiKeyHashes,
DEFAULT_LEGACY_API_KEY_HASH_BACKFILL_BATCH_SIZE,
type LegacyApiKeyHashBackfillClient,
type LegacyApiKeyLogWriterClient,
type LegacyApiKeyRotationClient,
type LegacyApiKeyReaderClient,
} from "./api-keys.server.js";
function createApiKeyHashBackfillClient(rows: Awaited<ReturnType<LegacyApiKeyHashBackfillClient["apiKey"]["findMany"]>>): LegacyApiKeyHashBackfillClient {
return {
apiKey: {
findMany: vi.fn().mockResolvedValue(rows),
update: vi.fn().mockResolvedValue({}),
},
};
}
function createApiKeyRotationClient(): LegacyApiKeyRotationClient {
return {
apiKey: {
updateMany: vi.fn().mockResolvedValue({ count: 1 }),
findFirst: vi.fn().mockImplementation(() => Promise.resolve({ id: "api_key_1", tenantId: "tenant_1", key: "rotated-secret" })),
},
};
}
function createApiKeyLogClient(): LegacyApiKeyLogWriterClient & LegacyApiKeyReaderClient {
return {
apiKey: {
create: vi.fn().mockResolvedValue({ id: "api_key_1", key: "raw-secret" }),
updateMany: vi.fn().mockResolvedValue({ count: 1 }),
findUnique: vi.fn().mockResolvedValue({ id: "api_key_1", tenantId: "tenant_1", key: "updated-secret" }),
findFirst: vi.fn().mockResolvedValue(null),
deleteMany: vi.fn().mockResolvedValue({ count: 1 }),
findMany: vi.fn().mockResolvedValue([]),
},
apiKeyEntity: {
create: vi.fn().mockResolvedValue({}),
deleteMany: vi.fn().mockResolvedValue({ count: 1 }),
},
entity: {
findMany: vi.fn().mockImplementation(({ where }: { where: { id: { in: string[] } } }) => {
return Promise.resolve(where.id.in.map((id) => ({ id })));
}),
},
apiKeyLog: {
create: vi.fn().mockResolvedValue({ id: "log_1" }),
findMany: vi.fn().mockResolvedValue([]),
groupBy: vi.fn().mockResolvedValue([]),
update: vi.fn().mockResolvedValue({}),
updateMany: vi.fn().mockResolvedValue({ count: 1 }),
count: vi.fn().mockResolvedValue(3),
deleteMany: vi.fn().mockResolvedValue({ count: 2 }),
},
} as unknown as LegacyApiKeyLogWriterClient & LegacyApiKeyReaderClient;
}
describe("legacy API key log writes", () => {
it("updates status and calculates duration when a start time is provided", async () => {
const client = createApiKeyLogClient();
vi.spyOn(performance, "now").mockReturnValue(25);
await setLegacyApiKeyLogStatus({ id: "log_1", tenantId: "tenant_1" }, { status: 200, startTime: 10 }, client);
expect(client.apiKeyLog.updateMany).toHaveBeenCalledWith({
where: { id: "log_1", tenantId: "tenant_1" },
data: {
status: 200,
error: undefined,
duration: 15,
},
});
});
it("persists errors without calculating duration for synthetic failures", async () => {
const client = createApiKeyLogClient();
await setLegacyApiKeyLogStatus({ id: "log_1", tenantId: "tenant_1" }, { status: 400, startTime: null, error: "Invalid API key" }, client);
expect(client.apiKeyLog.updateMany).toHaveBeenCalledWith({
where: { id: "log_1", tenantId: "tenant_1" },
data: {
status: 400,
error: "Invalid API key",
duration: null,
},
});
});
it("updates status with tenant scope when provided", async () => {
const client = createApiKeyLogClient();
await expect(setLegacyApiKeyLogStatus({ id: "log_1", tenantId: "tenant_1" }, { status: 200, startTime: null }, client)).resolves.toEqual({
count: 1,
});
expect(client.apiKeyLog.updateMany).toHaveBeenCalledWith({
where: { id: "log_1", tenantId: "tenant_1" },
data: {
status: 200,
error: undefined,
duration: null,
},
});
expect(client.apiKeyLog.update).not.toHaveBeenCalled();
});
it("rejects tenant-scoped status updates that miss", async () => {
const client = createApiKeyLogClient();
vi.mocked(client.apiKeyLog.updateMany).mockResolvedValue({ count: 0 });
await expect(setLegacyApiKeyLogStatus({ id: "log_foreign", tenantId: "tenant_1" }, { status: 404, startTime: null }, client)).rejects.toThrow(
"API key log log_foreign not found"
);
});
it("counts tenant API key logs through the package boundary", async () => {
const client = createApiKeyLogClient();
await expect(countLegacyTenantApiKeyLogs("tenant_1", client)).resolves.toBe(3);
expect(client.apiKeyLog.count).toHaveBeenCalledWith({
where: tenantLegacyApiKeyLogScope("tenant_1"),
});
});
it("fetches API key lists and details through the package boundary", async () => {
const client = createApiKeyLogClient();
const apiKey = {
id: "api_key_1",
alias: "Production",
expires: null,
tenantId: "tenant_1",
active: true,
entities: [],
tenant: { id: "tenant_1", name: "Acme", slug: "acme", deactivatedReason: null },
_count: { apiKeyLogs: 0 },
};
vi.mocked(client.apiKey.findMany).mockResolvedValue([apiKey] as never);
vi.mocked(client.apiKey.findUnique).mockResolvedValue(apiKey as never);
vi.mocked(client.apiKey.findFirst).mockResolvedValue(apiKey as never);
await expect(getAllLegacyApiKeys(client)).resolves.toEqual([apiKey]);
expect(client.apiKey.findMany).toHaveBeenCalledWith({
include: legacyApiKeyDetailsInclude,
orderBy: { createdAt: "desc" },
});
await expect(getLegacyApiKeysForTenant("tenant_1", client)).resolves.toEqual([apiKey]);
expect(client.apiKey.findMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_1" },
include: legacyApiKeyDetailsInclude,
orderBy: { createdAt: "desc" },
});
await expect(adminFindLegacyApiKeyById("api_key_1", client)).resolves.toBe(apiKey);
expect(client.apiKey.findUnique).toHaveBeenCalledWith({
where: { id: "api_key_1" },
include: legacyApiKeyDetailsInclude,
});
await expect(findLegacyApiKeyById({ id: "api_key_1", tenantId: "tenant_1" }, client)).resolves.toBe(apiKey);
expect(client.apiKey.findFirst).toHaveBeenCalledWith({
where: { id: "api_key_1", tenantId: "tenant_1" },
include: legacyApiKeyDetailsInclude,
});
await expect(findLegacyApiKeyByAlias("tenant_1", "Production", client)).resolves.toBe(apiKey);
expect(client.apiKey.findFirst).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", alias: "Production" },
include: legacyApiKeyDetailsInclude,
});
});
it("fetches logs for one API key with tenant details", async () => {
const client = createApiKeyLogClient();
await expect(getLegacyApiKeyLogsForKey({ id: "api_key_1", tenantId: "tenant_1" }, client)).resolves.toEqual([]);
expect(client.apiKeyLog.findMany).toHaveBeenCalledWith({
where: {
apiKeyId: "api_key_1",
tenantId: "tenant_1",
},
include: {
apiKey: {
include: {
tenant: true,
},
},
},
orderBy: {
createdAt: "desc",
},
});
});
it("counts logs for one API key through direct tenant scope", async () => {
const client = createApiKeyLogClient();
await expect(countLegacyApiKeyLogsForKey({ id: "api_key_1", tenantId: "tenant_1" }, client)).resolves.toBe(3);
expect(client.apiKeyLog.count).toHaveBeenCalledWith({
where: {
apiKeyId: "api_key_1",
tenantId: "tenant_1",
},
});
});
it("groups API key logs for admin summaries", async () => {
const client = createApiKeyLogClient();
await expect(groupLegacyApiKeyLogs({ by: ["method", "endpoint"], where: { tenantId: "tenant_1" } }, client)).resolves.toEqual([]);
expect(client.apiKeyLog.groupBy).toHaveBeenCalledWith({
by: ["method", "endpoint"],
where: { tenantId: "tenant_1" },
_avg: { duration: true },
_count: { _all: true },
orderBy: {
_avg: { duration: "desc" },
},
});
});
it("fetches paginated API key log admin details", async () => {
const client = createApiKeyLogClient();
await expect(
getLegacyApiKeyLogAdminDetails(
{
take: 10,
skip: 20,
where: { tenantId: "tenant_1" },
includeTenant: true,
orderBy: { createdAt: "desc" },
},
client,
),
).resolves.toEqual([]);
expect(client.apiKeyLog.findMany).toHaveBeenCalledWith({
take: 10,
skip: 20,
where: { tenantId: "tenant_1" },
include: {
apiKey: {
select: { alias: true, tenant: { select: { id: true, name: true } } },
},
tenant: { select: { id: true, name: true, slug: true } },
},
orderBy: { createdAt: "desc" },
});
});
it("counts and deletes API key logs through the package boundary", async () => {
const client = createApiKeyLogClient();
await expect(countLegacyApiKeyLogs({ tenantId: "tenant_1" }, client)).resolves.toBe(3);
expect(client.apiKeyLog.count).toHaveBeenCalledWith({
where: { tenantId: "tenant_1" },
});
await expect(adminDeleteLegacyApiKeyLogsByIds(["log_1", "log_2"], client)).resolves.toEqual({ count: 2 });
expect(client.apiKeyLog.deleteMany).toHaveBeenCalledWith({
where: { id: { in: ["log_1", "log_2"] } },
});
await expect(deleteTenantLegacyApiKeyLogsByIds({ ids: ["log_1", "log_2"], tenantId: "tenant_1" }, client)).resolves.toEqual({ count: 2 });
expect(client.apiKeyLog.deleteMany).toHaveBeenLastCalledWith({
where: {
id: { in: ["log_1", "log_2"] },
...tenantLegacyApiKeyLogScope("tenant_1"),
},
});
});
it("fetches the first active tenant API key", async () => {
const client = createApiKeyLogClient();
const apiKey = { id: "api_key_1", tenantId: "tenant_1", active: true };
vi.mocked(client.apiKey.findFirst).mockResolvedValue(apiKey as never);
await expect(findFirstLegacyActiveApiKey("tenant_1", client)).resolves.toBe(apiKey);
expect(client.apiKey.findFirst).toHaveBeenCalledWith({
where: {
tenantId: "tenant_1",
active: true,
},
});
});
it("creates API keys with deterministic hash metadata and returns plaintext only once", async () => {
const client = createApiKeyLogClient();
const expires = new Date("2026-05-01T00:00:00.000Z");
const key = "api_test_plaintext_secret";
const expectedMetadata = deriveLegacyApiKeyHashMetadata(key, "hash-secret");
await expect(
createLegacyApiKey(
{
tenantId: "tenant_1",
createdByUserId: "user_1",
alias: "Production",
expires,
active: false,
key,
},
[{ entityId: "entity_1", create: true, read: true, update: false, delete: false }],
client,
"hash-secret",
),
).resolves.toEqual({ id: "api_key_1", key });
expect(client.apiKey.create).toHaveBeenCalledWith({
data: expect.objectContaining({
tenantId: "tenant_1",
createdByUserId: "user_1",
alias: "Production",
expires,
active: false,
key,
keyHash: expectedMetadata.keyHash,
keyPrefix: "api_test",
keyLastFour: "cret",
keyVersion: 1,
}),
});
expect(vi.mocked(client.apiKey.create).mock.calls[0]?.[0].data.hashedAt).toBeInstanceOf(Date);
expect(client.apiKeyEntity.create).toHaveBeenCalledWith({
data: {
apiKeyId: "api_key_1",
entityId: "entity_1",
create: true,
read: true,
update: false,
delete: false,
},
});
expect(client.entity.findMany).toHaveBeenCalledWith({
where: {
id: { in: ["entity_1"] },
active: true,
hasApi: true,
type: { in: ["app", "all"] },
},
select: { id: true },
});
});
it("rejects API key entity scopes outside tenant API-eligible entities", async () => {
const client = createApiKeyLogClient();
vi.mocked(client.entity.findMany).mockResolvedValue([{ id: "entity_allowed" }]);
await expect(
createLegacyApiKey(
{
tenantId: "tenant_1",
createdByUserId: "user_1",
alias: "Production",
expires: null,
active: true,
key: "api_test_plaintext_secret",
},
[
{ entityId: "entity_allowed", create: true, read: true, update: false, delete: false },
{ entityId: "entity_admin", create: true, read: true, update: true, delete: true },
],
client,
"hash-secret",
),
).rejects.toThrow("API key entity scope is not allowed");
expect(client.apiKey.create).not.toHaveBeenCalled();
expect(client.apiKeyEntity.create).not.toHaveBeenCalled();
});
it("derives stable and distinct API key hashes", () => {
const hashedAt = new Date("2026-05-07T12:30:00.000Z");
const first = deriveLegacyApiKeyHashMetadata("api_test_plaintext_secret", "hash-secret", hashedAt);
const second = deriveLegacyApiKeyHashMetadata("api_test_plaintext_secret", "hash-secret", hashedAt);
const different = deriveLegacyApiKeyHashMetadata("api_test_plaintext_other", "hash-secret", hashedAt);
expect(first).toEqual(second);
expect(first.keyHash).not.toBe(different.keyHash);
expect(first).toMatchObject({
keyPrefix: "api_test",
keyLastFour: "cret",
hashedAt,
keyVersion: 1,
});
});
it("backfills legacy plaintext API key hash metadata in a bounded batch", async () => {
const hashedAt = new Date("2026-05-07T13:00:00.000Z");
const client = createApiKeyHashBackfillClient([
{ id: "api_key_1", key: "api_test_plaintext_secret", keyHash: null, hashedAt: null },
{ id: "api_key_2", key: "api_test_plaintext_other", keyHash: null, hashedAt: null },
]);
await expect(backfillLegacyApiKeyHashes({ batchSize: 2, hashSecret: "hash-secret", now: hashedAt, client })).resolves.toEqual({
scanned: 2,
updated: 2,
skipped: 0,
failed: 0,
failures: [],
});
expect(client.apiKey.findMany).toHaveBeenCalledWith({
take: 2,
where: { OR: [{ keyHash: null }, { hashedAt: null }] },
select: { id: true, key: true, keyHash: true, hashedAt: true },
orderBy: { createdAt: "asc" },
});
expect(client.apiKey.update).toHaveBeenNthCalledWith(1, {
where: { id: "api_key_1" },
data: deriveLegacyApiKeyHashMetadata("api_test_plaintext_secret", "hash-secret", hashedAt),
});
expect(client.apiKey.update).toHaveBeenNthCalledWith(2, {
where: { id: "api_key_2" },
data: deriveLegacyApiKeyHashMetadata("api_test_plaintext_other", "hash-secret", hashedAt),
});
});
it("uses the default backfill batch size and skips guarded rows", async () => {
const existingHash = deriveLegacyApiKeyHashMetadata("api_test_already_hashed", "hash-secret");
const client = createApiKeyHashBackfillClient([
{ id: "api_key_empty", key: "", keyHash: null, hashedAt: null },
{ id: "api_key_hashed", key: "api_test_already_hashed", keyHash: existingHash.keyHash, hashedAt: null },
{ id: "api_key_timestamped", key: "api_test_timestamped", keyHash: null, hashedAt: existingHash.hashedAt },
]);
await expect(backfillLegacyApiKeyHashes({ client })).resolves.toEqual({
scanned: 3,
updated: 0,
skipped: 3,
failed: 0,
failures: [],
});
expect(client.apiKey.findMany).toHaveBeenCalledWith(expect.objectContaining({ take: DEFAULT_LEGACY_API_KEY_HASH_BACKFILL_BATCH_SIZE }));
expect(client.apiKey.update).not.toHaveBeenCalled();
});
it("records per-row backfill failures by id only and continues the batch", async () => {
const leakedSecret = "api_test_plaintext_secret";
const client = createApiKeyHashBackfillClient([
{ id: "api_key_fails", key: leakedSecret, keyHash: null, hashedAt: null },
{ id: "api_key_succeeds", key: "api_test_plaintext_other", keyHash: null, hashedAt: null },
]);
vi.mocked(client.apiKey.update)
.mockRejectedValueOnce(new Error(`unique constraint leaked ${leakedSecret}`))
.mockResolvedValueOnce({});
const result = await backfillLegacyApiKeyHashes({ hashSecret: "hash-secret", now: new Date("2026-05-07T13:00:00.000Z"), client });
expect(result).toEqual({
scanned: 2,
updated: 1,
skipped: 0,
failed: 1,
failures: [{ id: "api_key_fails", error: "Error" }],
});
expect(JSON.stringify(result)).not.toContain(leakedSecret);
expect(client.apiKey.update).toHaveBeenCalledTimes(2);
});
it("rotates API keys with new plaintext and persisted hash metadata", async () => {
const client = createApiKeyRotationClient();
const oldMetadata = deriveLegacyApiKeyHashMetadata("old-secret", "hash-secret");
const rotated = await rotateLegacyApiKey({ id: "api_key_1", tenantId: "tenant_1" }, client, "hash-secret");
expect(rotated.key).toEqual(expect.any(String));
expect(rotated.key).not.toBe("old-secret");
expect(client.apiKey.updateMany).toHaveBeenCalledWith({
where: { id: "api_key_1", tenantId: "tenant_1" },
data: expect.objectContaining({
key: rotated.key,
keyHash: deriveLegacyApiKeyHashMetadata(rotated.key, "hash-secret").keyHash,
keyPrefix: rotated.key.slice(0, 8),
keyLastFour: rotated.key.slice(-4),
keyVersion: 1,
}),
});
expect(client.apiKey.findFirst).toHaveBeenCalledWith({
where: { id: "api_key_1", tenantId: "tenant_1" },
});
expect(vi.mocked(client.apiKey.updateMany).mock.calls[0]?.[0].data.keyHash).not.toBe(oldMetadata.keyHash);
expect(vi.mocked(client.apiKey.updateMany).mock.calls[0]?.[0].data.hashedAt).toBeInstanceOf(Date);
});
it("redacts generated plaintext from rotation update errors", async () => {
const client = createApiKeyRotationClient();
vi.mocked(client.apiKey.updateMany).mockRejectedValue(new Error("database unavailable"));
await expect(rotateLegacyApiKey({ id: "api_key_1", tenantId: "tenant_1" }, client, "hash-secret")).rejects.toThrow("database unavailable");
const generatedKey = vi.mocked(client.apiKey.updateMany).mock.calls[0]?.[0].data.key;
await expect(rotateLegacyApiKey({ id: "api_key_1", tenantId: "tenant_1" }, client, "hash-secret")).rejects.not.toThrow(generatedKey);
});
it("keeps rotated API key validation hash-first and rejects old plaintext after persistence", async () => {
const client = createApiKeyLogClient();
const oldKey = "api_test_old_plaintext";
const newKey = "api_test_new_plaintext";
const apiKey = {
id: "api_key_1",
alias: "Production",
expires: null,
tenantId: "tenant_1",
active: true,
entities: [],
tenant: { id: "tenant_1", name: "Acme", slug: "acme", deactivatedReason: null },
};
vi.mocked(client.apiKey.findFirst).mockImplementation(({ where }) => {
if ("keyHash" in where && where.keyHash === deriveLegacyApiKeyHashMetadata(newKey, "hash-secret").keyHash) {
return Promise.resolve(apiKey) as never;
}
return Promise.resolve(null) as never;
});
await expect(findLegacyApiKeyByKey(newKey, client, "hash-secret")).resolves.toBe(apiKey);
await expect(findLegacyApiKeyByKey(oldKey, client, "hash-secret")).resolves.toBeNull();
expect(client.apiKey.findFirst).toHaveBeenNthCalledWith(1, {
where: { keyHash: deriveLegacyApiKeyHashMetadata(newKey, "hash-secret").keyHash },
select: expect.any(Object),
});
expect(client.apiKey.findFirst).toHaveBeenNthCalledWith(2, expect.objectContaining({
where: { keyHash: deriveLegacyApiKeyHashMetadata(oldKey, "hash-secret").keyHash },
}));
});
it("updates API keys and replaces entity permissions", async () => {
const client = createApiKeyLogClient();
const expires = new Date("2026-05-01T00:00:00.000Z");
vi.mocked(client.apiKey.findFirst).mockResolvedValue({ id: "api_key_1", tenantId: "tenant_1", key: "updated-secret" } as never);
await expect(
updateLegacyApiKey(
"api_key_1",
{
tenantId: "tenant_1",
alias: "Production",
expires,
active: true,
},
[{ entityId: "entity_1", create: false, read: true, update: true, delete: false }],
client,
),
).resolves.toEqual({ id: "api_key_1", tenantId: "tenant_1", key: "updated-secret" });
expect(client.apiKey.updateMany).toHaveBeenCalledWith({
where: { id: "api_key_1", tenantId: "tenant_1" },
data: {
tenantId: "tenant_1",
alias: "Production",
expires,
active: true,
},
});
expect(client.apiKeyEntity.deleteMany).toHaveBeenCalledWith({
where: {
apiKeyId: "api_key_1",
apiKey: { tenantId: "tenant_1" },
},
});
expect(client.apiKeyEntity.create).toHaveBeenCalledWith({
data: {
apiKeyId: "api_key_1",
entityId: "entity_1",
create: false,
read: true,
update: true,
delete: false,
},
});
expect(client.apiKey.findFirst).toHaveBeenCalledWith({
where: { id: "api_key_1", tenantId: "tenant_1" },
});
});
it("deletes API keys through the package boundary", async () => {
const client = createApiKeyLogClient();
vi.mocked(client.apiKey.findFirst).mockResolvedValue({ id: "api_key_1", tenantId: "tenant_1", key: "deleted-secret" } as never);
await expect(deleteLegacyApiKey({ id: "api_key_1", tenantId: "tenant_1" }, client)).resolves.toEqual({ id: "api_key_1", tenantId: "tenant_1", key: "deleted-secret" });
expect(client.apiKey.findFirst).toHaveBeenCalledWith({
where: { id: "api_key_1", tenantId: "tenant_1" },
});
expect(client.apiKey.deleteMany).toHaveBeenCalledWith({
where: { id: "api_key_1", tenantId: "tenant_1" },
});
});
it("returns null when no tenant id is provided for first active API key lookup", async () => {
const client = createApiKeyLogClient();
await expect(findFirstLegacyActiveApiKey(null, client)).resolves.toBeNull();
expect(client.apiKey.findFirst).not.toHaveBeenCalled();
});
it("finds tenant API keys by hash without selecting the secret back out", async () => {
const client = createApiKeyLogClient();
const apiKey = {
id: "api_key_1",
alias: "Production",
expires: null,
tenantId: "tenant_1",
active: true,
entities: [],
tenant: { id: "tenant_1", name: "Acme", slug: "acme", deactivatedReason: null },
};
vi.mocked(client.apiKey.findFirst).mockResolvedValue(apiKey);
await expect(findLegacyApiKeyByKey("raw-secret", client, "hash-secret", { allowPlaintextFallback: true })).resolves.toBe(apiKey);
expect(client.apiKey.findFirst).toHaveBeenCalledTimes(1);
expect(client.apiKey.findFirst).toHaveBeenCalledWith({
where: { keyHash: deriveLegacyApiKeyHashMetadata("raw-secret", "hash-secret").keyHash },
select: {
id: true,
alias: true,
expires: true,
tenantId: true,
active: true,
entities: { select: { create: true, read: true, update: true, delete: true, entityId: true } },
tenant: { select: { id: true, name: true, slug: true, deactivatedReason: true } },
},
});
});
it("creates API key logs from normalized request data", async () => {
const client = createApiKeyLogClient();
const data = {
tenantId: "tenant_1",
apiKeyId: "api_key_1",
endpoint: "/v1/usage",
ip: "127.0.0.1",
method: "GET",
params: "tenantId=tenant_1",
status: 200,
};
await expect(createLegacyApiKeyLog(data, client)).resolves.toEqual({ id: "log_1" });
expect(client.apiKeyLog.create).toHaveBeenCalledWith({
data,
});
});
it("falls back to legacy raw-key lookup when hash lookup misses", async () => {
const client = createApiKeyLogClient();
const apiKey = {
id: "api_key_1",
alias: "Production",
expires: null,
tenantId: "tenant_1",
active: true,
entities: [],
tenant: { id: "tenant_1", name: "Acme", slug: "acme", deactivatedReason: null },
};
vi.mocked(client.apiKey.findFirst).mockResolvedValueOnce(null).mockResolvedValueOnce(apiKey);
await expect(findLegacyApiKeyByKey("raw-secret", client, "hash-secret", { allowPlaintextFallback: true })).resolves.toBe(apiKey);
expect(client.apiKey.findFirst).toHaveBeenNthCalledWith(1, {
where: { keyHash: deriveLegacyApiKeyHashMetadata("raw-secret", "hash-secret").keyHash },
select: expect.any(Object),
});
expect(client.apiKey.findFirst).toHaveBeenNthCalledWith(2, {
where: { key: "raw-secret" },
select: expect.any(Object),
});
});
it("can disable legacy raw-key fallback after cutover", async () => {
const client = createApiKeyLogClient();
vi.mocked(client.apiKey.findFirst).mockResolvedValue(null);
await expect(findLegacyApiKeyByKey("raw-secret", client, "hash-secret", { allowPlaintextFallback: false })).resolves.toBeNull();
expect(client.apiKey.findFirst).toHaveBeenCalledTimes(1);
expect(client.apiKey.findFirst).toHaveBeenCalledWith({
where: { keyHash: deriveLegacyApiKeyHashMetadata("raw-secret", "hash-secret").keyHash },
select: expect.any(Object),
});
});
it("does not fall back to raw-key lookup when hash lookup fails and fallback is disabled", async () => {
const client = createApiKeyLogClient();
vi.mocked(client.apiKey.findFirst).mockRejectedValueOnce(new Error("hash index unavailable"));
await expect(findLegacyApiKeyByKey("raw-secret", client, "hash-secret", { allowPlaintextFallback: false })).resolves.toBeNull();
expect(client.apiKey.findFirst).toHaveBeenCalledTimes(1);
});
it("falls back to legacy raw-key lookup when hash lookup fails", async () => {
const client = createApiKeyLogClient();
const apiKey = {
id: "api_key_1",
alias: "Production",
expires: null,
tenantId: "tenant_1",
active: true,
entities: [],
tenant: { id: "tenant_1", name: "Acme", slug: "acme", deactivatedReason: null },
};
vi.mocked(client.apiKey.findFirst).mockRejectedValueOnce(new Error("hash index unavailable")).mockResolvedValueOnce(apiKey);
await expect(findLegacyApiKeyByKey("raw-secret", client, "hash-secret", { allowPlaintextFallback: true })).resolves.toBe(apiKey);
expect(client.apiKey.findFirst).toHaveBeenCalledTimes(2);
});
it("keeps legacy raw-key fallback disabled by default", async () => {
const client = createApiKeyLogClient();
vi.mocked(client.apiKey.findFirst).mockResolvedValue(null);
await expect(findLegacyApiKeyByKey("raw-secret", client, "hash-secret")).resolves.toBeNull();
expect(client.apiKey.findFirst).toHaveBeenCalledTimes(1);
expect(client.apiKey.findFirst).toHaveBeenCalledWith({
where: { keyHash: deriveLegacyApiKeyHashMetadata("raw-secret", "hash-secret").keyHash },
select: expect.any(Object),
});
});
it("preserves legacy null behavior when both API key lookups fail", async () => {
const client = createApiKeyLogClient();
vi.mocked(client.apiKey.findFirst).mockRejectedValue(new Error("database unavailable"));
await expect(findLegacyApiKeyByKey("raw-secret", client)).resolves.toBeNull();
});
});
@@ -0,0 +1,848 @@
import { createHmac, randomUUID } from "node:crypto";
import { getDbClient } from "./client.server.js";
import type { ApiKey, ApiKeyEntity, ApiKeyLog, Prisma, Tenant } from "./prisma-browser.js";
export type LegacyApiKeyUserSummary = {
id: string;
email: string;
firstName: string;
lastName: string;
phone: string | null;
locale: string | null;
createdAt: Date;
};
export type LegacyApiKeyWithDetails = ApiKey & {
tenant: { id: string; name: string; slug: string; deactivatedReason: string | null };
entities: (ApiKeyEntity & { entity: { id: string; title: string; titlePlural: string; slug: string } })[];
createdByUser: LegacyApiKeyUserSummary;
_count: { apiKeyLogs: number };
};
export type LegacyApiKeyLogWithDetails = ApiKeyLog & {
apiKey: (ApiKey & { tenant: Tenant }) | null;
};
export type LegacyApiKeyLogAdminDetails = ApiKeyLog & {
apiKey: { alias: string; tenant: { id: string; name: string } } | null;
tenant?: { id: string; name: string; slug: string } | null;
};
export type LegacyApiKeyLogSummary = Record<string, unknown> & {
_avg: { duration: number | null };
_count: { _all: number };
};
export type LegacyApiKeyLogWhereInput = Prisma.ApiKeyLogWhereInput;
export type LegacyApiKeyLogOrderByInput = Prisma.ApiKeyLogOrderByWithRelationInput;
export type LegacyApiKeySimple = {
id: string;
alias: string;
expires: Date | null;
tenantId: string;
active: boolean;
entities: {
create: boolean;
read: boolean;
update: boolean;
delete: boolean;
entityId: string;
}[];
tenant: { id: string; name: string; slug: string; deactivatedReason: string | null };
};
export type LegacyActiveApiKey = ApiKey;
export type LegacyApiKeyLogCreateData = {
tenantId: string | null;
apiKeyId: string | null;
endpoint: string;
ip: string;
method: string;
params: string;
error?: string;
status?: number;
alias?: string;
tenantName?: string;
};
export type LegacyApiKeyHashMetadata = {
keyHash: string;
keyPrefix: string;
keyLastFour: string;
hashedAt: Date;
keyVersion: 1;
};
export type LegacyApiKeyCreateData = {
tenantId: string;
createdByUserId: string;
alias: string;
expires: Date | null;
active: boolean;
key?: string;
};
export type LegacyApiKeyCreateStoredData = LegacyApiKeyCreateData & LegacyApiKeyHashMetadata & { key: string };
export type LegacyApiKeyCreateResult = ApiKey & { key: string };
export type LegacyApiKeyRotationResult = ApiKey & { key: string };
export type LegacyApiKeyBackfillRow = {
id: string;
key: string;
keyHash: string | null;
hashedAt: Date | null;
};
export type LegacyApiKeyBackfillFailure = {
id: string;
error: string;
};
export type LegacyApiKeyHashBackfillResult = {
scanned: number;
updated: number;
skipped: number;
failed: number;
failures: LegacyApiKeyBackfillFailure[];
};
export type LegacyApiKeyHashBackfillClient = {
apiKey: {
findMany(args: {
take: number;
where: {
OR: [{ keyHash: null }, { hashedAt: null }];
};
select: { id: true; key: true; keyHash: true; hashedAt: true };
orderBy: { createdAt: "asc" };
}): Promise<LegacyApiKeyBackfillRow[]>;
update(args: {
where: { id: string };
data: LegacyApiKeyHashMetadata;
}): Promise<unknown>;
};
};
export type LegacyApiKeyHashBackfillOptions = {
batchSize?: number;
hashSecret?: string | null;
now?: Date;
client?: LegacyApiKeyHashBackfillClient;
};
export type LegacyApiKeyRotationClient = {
apiKey: {
updateMany(args: {
where: { id: string; tenantId: string };
data: { key: string } & LegacyApiKeyHashMetadata;
}): Promise<Prisma.BatchPayload>;
findFirst(args: { where: { id: string; tenantId: string } }): Promise<ApiKey | null>;
};
};
export type LegacyApiKeyUpdateData = {
tenantId: string;
alias: string;
expires: Date | null;
active: boolean;
};
export type LegacyApiKeyEntityPermissionData = {
entityId: string;
create: boolean;
read: boolean;
update: boolean;
delete: boolean;
};
export type LegacyApiKeyReaderClient = {
apiKey: {
findMany(args: {
where?: { tenantId: string };
include: typeof legacyApiKeyDetailsInclude;
orderBy: { createdAt: "desc" };
}): Promise<LegacyApiKeyWithDetails[]>;
findUnique(args: {
where: { id: string };
include: typeof legacyApiKeyDetailsInclude;
}): Promise<LegacyApiKeyWithDetails | null>;
findFirst(args: {
where: { key: string } | { keyHash: string } | { id: string; tenantId: string } | { tenantId: string; alias: string } | { tenantId: string; active: true };
select?: typeof legacyApiKeySimpleSelect;
include?: typeof legacyApiKeyDetailsInclude;
}): Promise<LegacyApiKeySimple | LegacyApiKeyWithDetails | ApiKey | null>;
};
apiKeyLog: {
findMany(args: {
where: { apiKeyId: string; tenantId: string };
include: { apiKey: { include: { tenant: true } } };
orderBy: { createdAt: "desc" };
}): Promise<LegacyApiKeyLogWithDetails[]>;
findMany(args: {
take: number;
skip: number;
where: LegacyApiKeyLogWhereInput;
include: {
apiKey: { select: { alias: true; tenant: { select: { id: true; name: true } } } };
tenant?: { select: { id: true; name: true; slug: true } };
};
orderBy: LegacyApiKeyLogOrderByInput | LegacyApiKeyLogOrderByInput[];
}): Promise<LegacyApiKeyLogAdminDetails[]>;
count(args: { where: LegacyApiKeyLogWhereInput }): Promise<number>;
groupBy(args: {
by: string[];
where: LegacyApiKeyLogWhereInput;
_avg: { duration: true };
_count: { _all: true };
orderBy: { _avg: { duration: "desc" } };
}): Promise<LegacyApiKeyLogSummary[]>;
};
};
export type LegacyApiKeyLookupOptions = {
allowPlaintextFallback?: boolean;
};
export function tenantLegacyApiKeyLogScope(tenantId: string): Prisma.ApiKeyLogWhereInput {
return {
tenantId,
OR: [{ apiKeyId: null }, { apiKey: { tenantId } }],
};
}
export type LegacyApiKeyLogStatusUpdate = {
status: number;
startTime: number | null;
error?: string | null;
};
export type LegacyApiKeyLogWriterClient = {
apiKey: {
create(args: { data: LegacyApiKeyCreateStoredData & { active: boolean } }): Promise<ApiKey>;
updateMany(args: { where: { id: string; tenantId: string }; data: LegacyApiKeyUpdateData }): Promise<Prisma.BatchPayload>;
findFirst(args: { where: { id: string; tenantId: string } }): Promise<ApiKey | null>;
deleteMany(args: { where: { id: string; tenantId: string } }): Promise<Prisma.BatchPayload>;
};
apiKeyEntity: {
create(args: { data: LegacyApiKeyEntityPermissionData & { apiKeyId: string } }): Promise<unknown>;
deleteMany(args: { where: Prisma.ApiKeyEntityWhereInput }): Promise<unknown>;
};
entity: {
findMany(args: {
where: {
id: { in: string[] };
active: true;
hasApi: true;
type: { in: ["app", "all"] };
};
select: { id: true };
}): Promise<{ id: string }[]>;
};
apiKeyLog: {
create(args: {
data: LegacyApiKeyLogCreateData;
}): Promise<ApiKeyLog>;
update(args: {
where: { id: string };
data: {
status: number;
error?: string | null;
duration: number | null;
};
}): Promise<unknown>;
updateMany(args: {
where: Prisma.ApiKeyLogWhereInput;
data: {
status: number;
error?: string | null;
duration: number | null;
};
}): Promise<Prisma.BatchPayload>;
count(args: { where: Prisma.ApiKeyLogWhereInput }): Promise<number>;
deleteMany(args: { where: Prisma.ApiKeyLogWhereInput }): Promise<unknown>;
};
};
async function validateLegacyApiKeyEntityScopes({
tenantId,
entities,
client,
}: {
tenantId: string;
entities: LegacyApiKeyEntityPermissionData[];
client: LegacyApiKeyLogWriterClient;
}): Promise<void> {
const entityIds = [...new Set(entities.map((entity) => entity.entityId).filter(Boolean))];
if (entityIds.length === 0) {
return;
}
const allowedEntities = await client.entity.findMany({
where: {
id: { in: entityIds },
active: true,
hasApi: true,
type: { in: ["app", "all"] },
},
select: { id: true },
});
const allowedIds = new Set(allowedEntities.map((entity) => entity.id));
const invalidEntityIds = entityIds.filter((entityId) => !allowedIds.has(entityId));
if (invalidEntityIds.length > 0) {
throw new Error(`API key entity scope is not allowed for tenant ${tenantId}.`);
}
}
const selectLegacyApiKeyUserSummary = {
id: true,
email: true,
firstName: true,
lastName: true,
phone: true,
locale: true,
createdAt: true,
} as const;
export const LEGACY_API_KEY_HASH_VERSION = 1 as const;
export const DEFAULT_LEGACY_API_KEY_HASH_SECRET = "boilerplate-api-key-hash-v1";
export const DEFAULT_LEGACY_API_KEY_HASH_BACKFILL_BATCH_SIZE = 100;
export const LEGACY_API_KEY_PREFIX_LENGTH = 8;
export const LEGACY_API_KEY_LAST_FOUR_LENGTH = 4;
export function normalizeLegacyApiKeyHashSecret(secret: string | undefined | null): string {
const normalized = secret?.trim();
if (!normalized) {
return DEFAULT_LEGACY_API_KEY_HASH_SECRET;
}
return normalized;
}
export function deriveLegacyApiKeyHashMetadata(
key: string,
hashSecret: string | undefined | null,
hashedAt: Date = new Date(),
): LegacyApiKeyHashMetadata {
const secret = normalizeLegacyApiKeyHashSecret(hashSecret);
return {
keyHash: createHmac("sha256", secret).update(key).digest("hex"),
keyPrefix: key.slice(0, LEGACY_API_KEY_PREFIX_LENGTH),
keyLastFour: key.slice(-LEGACY_API_KEY_LAST_FOUR_LENGTH),
hashedAt,
keyVersion: LEGACY_API_KEY_HASH_VERSION,
};
}
function normalizeLegacyApiKeyHashBackfillBatchSize(batchSize: number | undefined): number {
if (!Number.isFinite(batchSize) || batchSize === undefined) {
return DEFAULT_LEGACY_API_KEY_HASH_BACKFILL_BATCH_SIZE;
}
return Math.max(1, Math.floor(batchSize));
}
function redactLegacyApiKeyBackfillError(error: unknown): string {
if (error instanceof Error) {
return error.name || "Error";
}
return "UnknownError";
}
export async function backfillLegacyApiKeyHashes({
batchSize,
hashSecret,
now = new Date(),
client = getDbClient() as unknown as LegacyApiKeyHashBackfillClient,
}: LegacyApiKeyHashBackfillOptions = {}): Promise<LegacyApiKeyHashBackfillResult> {
const rows = await client.apiKey.findMany({
take: normalizeLegacyApiKeyHashBackfillBatchSize(batchSize),
where: {
OR: [{ keyHash: null }, { hashedAt: null }],
},
select: { id: true, key: true, keyHash: true, hashedAt: true },
orderBy: { createdAt: "asc" },
});
const result: LegacyApiKeyHashBackfillResult = {
scanned: rows.length,
updated: 0,
skipped: 0,
failed: 0,
failures: [],
};
for (const row of rows) {
if (!row.key || row.keyHash || row.hashedAt) {
result.skipped += 1;
continue;
}
try {
await client.apiKey.update({
where: { id: row.id },
data: deriveLegacyApiKeyHashMetadata(row.key, hashSecret, now),
});
result.updated += 1;
} catch (error) {
result.failed += 1;
result.failures.push({ id: row.id, error: redactLegacyApiKeyBackfillError(error) });
}
}
return result;
}
export const legacyApiKeyDetailsInclude = {
tenant: { select: { id: true, name: true, slug: true, deactivatedReason: true } },
entities: {
include: {
entity: { select: { id: true, title: true, titlePlural: true, slug: true } },
},
},
createdByUser: {
select: selectLegacyApiKeyUserSummary,
},
_count: {
select: {
apiKeyLogs: true,
},
},
} as const;
const legacyApiKeySimpleSelect = {
id: true,
alias: true,
expires: true,
tenantId: true,
active: true,
entities: { select: { create: true, read: true, update: true, delete: true, entityId: true } },
tenant: { select: { id: true, name: true, slug: true, deactivatedReason: true } },
} as const;
export async function getAllLegacyApiKeys(
client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient,
): Promise<LegacyApiKeyWithDetails[]> {
return client.apiKey.findMany({
include: legacyApiKeyDetailsInclude,
orderBy: {
createdAt: "desc",
},
});
}
export async function getLegacyApiKeysForTenant(
tenantId: string,
client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient,
): Promise<LegacyApiKeyWithDetails[]> {
return client.apiKey.findMany({
where: {
tenantId,
},
include: legacyApiKeyDetailsInclude,
orderBy: {
createdAt: "desc",
},
});
}
export async function adminFindLegacyApiKeyById(
id: string,
client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient,
): Promise<LegacyApiKeyWithDetails | null> {
return client.apiKey.findUnique({
where: { id },
include: legacyApiKeyDetailsInclude,
});
}
export async function findLegacyApiKeyById(
{ id, tenantId }: { id: string; tenantId: string },
client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient,
): Promise<LegacyApiKeyWithDetails | null> {
return (await client.apiKey.findFirst({
where: { id, tenantId },
include: legacyApiKeyDetailsInclude,
})) as LegacyApiKeyWithDetails | null;
}
export async function findLegacyApiKeyByAlias(
tenantId: string,
alias: string,
client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient,
): Promise<LegacyApiKeyWithDetails | null> {
return (await client.apiKey.findFirst({
where: { tenantId, alias },
include: legacyApiKeyDetailsInclude,
})) as LegacyApiKeyWithDetails | null;
}
export async function getLegacyApiKeyLogsForKey(
{ id, tenantId }: { id: string; tenantId: string },
client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient,
): Promise<LegacyApiKeyLogWithDetails[]> {
return client.apiKeyLog.findMany({
where: {
apiKeyId: id,
tenantId,
},
include: {
apiKey: {
include: {
tenant: true,
},
},
},
orderBy: {
createdAt: "desc",
},
});
}
export async function countLegacyApiKeyLogsForKey(
{ id, tenantId }: { id: string; tenantId: string },
client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient,
): Promise<number> {
return client.apiKeyLog.count({
where: {
apiKeyId: id,
tenantId,
},
});
}
export async function groupLegacyApiKeyLogs(
args: {
by: string[];
where: LegacyApiKeyLogWhereInput;
},
client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient,
): Promise<LegacyApiKeyLogSummary[]> {
return client.apiKeyLog.groupBy({
by: args.by,
where: args.where,
_avg: { duration: true },
_count: { _all: true },
orderBy: {
_avg: { duration: "desc" },
},
});
}
export async function getLegacyApiKeyLogAdminDetails(
args: {
take: number;
skip: number;
where: LegacyApiKeyLogWhereInput;
includeTenant: boolean;
orderBy: LegacyApiKeyLogOrderByInput | LegacyApiKeyLogOrderByInput[];
},
client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient,
): Promise<LegacyApiKeyLogAdminDetails[]> {
const include: {
apiKey: { select: { alias: true; tenant: { select: { id: true; name: true } } } };
tenant?: { select: { id: true; name: true; slug: true } };
} = {
apiKey: {
select: { alias: true, tenant: { select: { id: true, name: true } } },
},
};
if (args.includeTenant) {
include.tenant = { select: { id: true, name: true, slug: true } };
}
return client.apiKeyLog.findMany({
take: args.take,
skip: args.skip,
where: args.where,
include,
orderBy: args.orderBy,
});
}
export async function countLegacyApiKeyLogs(
where: LegacyApiKeyLogWhereInput,
client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient,
): Promise<number> {
return client.apiKeyLog.count({
where,
});
}
export async function findFirstLegacyActiveApiKey(
tenantId: string | null,
client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient,
): Promise<LegacyActiveApiKey | null> {
if (!tenantId) {
return null;
}
return (await client.apiKey
.findFirst({
where: {
tenantId,
active: true,
},
})
.catch(() => null)) as LegacyActiveApiKey | null;
}
export async function createLegacyApiKey(
data: LegacyApiKeyCreateData,
entities: LegacyApiKeyEntityPermissionData[],
client: LegacyApiKeyLogWriterClient = getDbClient() as unknown as LegacyApiKeyLogWriterClient,
hashSecret?: string | null,
): Promise<LegacyApiKeyCreateResult> {
await validateLegacyApiKeyEntityScopes({ tenantId: data.tenantId, entities, client });
const key = data.key ?? randomUUID();
const hashMetadata = deriveLegacyApiKeyHashMetadata(key, hashSecret);
const apiKey = await client.apiKey.create({
data: {
...data,
key,
...hashMetadata,
active: data.active ?? true,
},
});
await Promise.all(
entities.map(async (entity) => {
return client.apiKeyEntity.create({
data: {
apiKeyId: apiKey.id,
...entity,
},
});
}),
);
return {
...apiKey,
key,
} as LegacyApiKeyCreateResult;
}
export async function updateLegacyApiKey(
id: string,
data: LegacyApiKeyUpdateData,
entities: LegacyApiKeyEntityPermissionData[],
client: LegacyApiKeyLogWriterClient = getDbClient() as unknown as LegacyApiKeyLogWriterClient,
): Promise<ApiKey> {
await validateLegacyApiKeyEntityScopes({ tenantId: data.tenantId, entities, client });
const updated = await client.apiKey.updateMany({
where: { id, tenantId: data.tenantId },
data,
});
if (updated.count !== 1) {
throw new Error(`API key ${id} not found`);
}
await client.apiKeyEntity.deleteMany({
where: {
apiKeyId: id,
apiKey: { tenantId: data.tenantId },
},
});
await Promise.all(
entities.map(async (entity) => {
return client.apiKeyEntity.create({
data: {
apiKeyId: id,
...entity,
},
});
}),
);
const apiKey = await client.apiKey.findFirst({ where: { id, tenantId: data.tenantId } });
if (!apiKey) {
throw new Error(`API key ${id} could not be reloaded`);
}
return apiKey;
}
export async function rotateLegacyApiKey(
{ id, tenantId }: { id: string; tenantId: string },
client: LegacyApiKeyRotationClient = getDbClient() as unknown as LegacyApiKeyRotationClient,
hashSecret?: string | null,
): Promise<LegacyApiKeyRotationResult> {
const key = randomUUID();
const updated = await client.apiKey.updateMany({
where: { id, tenantId },
data: {
key,
...deriveLegacyApiKeyHashMetadata(key, hashSecret),
},
});
if (updated.count !== 1) {
throw new Error(`API key ${id} not found`);
}
const apiKey = await client.apiKey.findFirst({ where: { id, tenantId } });
if (!apiKey) {
throw new Error(`API key ${id} could not be reloaded`);
}
return {
...apiKey,
key,
} as LegacyApiKeyRotationResult;
}
export async function deleteLegacyApiKey(
{ id, tenantId }: { id: string; tenantId: string },
client: LegacyApiKeyLogWriterClient = getDbClient() as unknown as LegacyApiKeyLogWriterClient,
): Promise<ApiKey> {
const apiKey = await client.apiKey.findFirst({ where: { id, tenantId } });
if (!apiKey) {
throw new Error(`API key ${id} not found`);
}
const deleted = await client.apiKey.deleteMany({
where: { id, tenantId },
});
if (deleted.count !== 1) {
throw new Error(`API key ${id} not found`);
}
return apiKey;
}
export async function setLegacyApiKeyLogStatus(
scope: { id: string; tenantId: string },
data: LegacyApiKeyLogStatusUpdate,
client: LegacyApiKeyLogWriterClient = getDbClient() as unknown as LegacyApiKeyLogWriterClient,
): Promise<unknown> {
let duration: number | null = null;
if (data.startTime) {
const endTime = performance.now();
duration = Number(endTime - data.startTime);
}
const updateData = {
status: data.status,
error: data.error,
duration,
};
const updated = await client.apiKeyLog.updateMany({
where: { id: scope.id, tenantId: scope.tenantId },
data: updateData,
});
if (updated.count !== 1) {
throw new Error(`API key log ${scope.id} not found`);
}
return updated;
}
export async function createLegacyApiKeyLog(
data: LegacyApiKeyLogCreateData,
client: LegacyApiKeyLogWriterClient = getDbClient() as unknown as LegacyApiKeyLogWriterClient,
): Promise<ApiKeyLog> {
return client.apiKeyLog.create({
data,
});
}
export async function findLegacyApiKeyByKey(
key: string,
client: LegacyApiKeyReaderClient = getDbClient() as unknown as LegacyApiKeyReaderClient,
hashSecret?: string | null,
options: LegacyApiKeyLookupOptions = {},
): Promise<LegacyApiKeySimple | null> {
const allowPlaintextFallback = options.allowPlaintextFallback ?? false;
const { keyHash } = deriveLegacyApiKeyHashMetadata(key, hashSecret);
const hashedApiKey = await client.apiKey
.findFirst({
where: { keyHash },
select: legacyApiKeySimpleSelect,
})
.then((apiKey) => apiKey as LegacyApiKeySimple | null)
.catch(() => null);
if (hashedApiKey) {
return hashedApiKey;
}
if (!allowPlaintextFallback) {
return null;
}
return client.apiKey
.findFirst({
where: { key },
select: legacyApiKeySimpleSelect,
})
.then((apiKey) => apiKey as LegacyApiKeySimple | null)
.catch(() => {
return null;
});
}
export async function countLegacyTenantApiKeyLogs(
tenantId: string,
client: LegacyApiKeyLogWriterClient = getDbClient() as unknown as LegacyApiKeyLogWriterClient,
): Promise<number> {
return client.apiKeyLog.count({
where: tenantLegacyApiKeyLogScope(tenantId),
});
}
export async function countLegacyTenantApiKeyUsage(
{
tenantId,
statuses,
ignoredEndpoints,
period,
}: {
tenantId: string;
statuses: number[];
ignoredEndpoints: string[];
period?: { start: Date; end: Date };
},
client: LegacyApiKeyLogWriterClient = getDbClient() as unknown as LegacyApiKeyLogWriterClient,
): Promise<number> {
return client.apiKeyLog.count({
where: {
tenantId,
status: { in: statuses },
endpoint: { notIn: ignoredEndpoints },
...(period
? {
createdAt: {
gte: period.start,
lt: period.end,
},
}
: {}),
},
});
}
export async function adminDeleteLegacyApiKeyLogsByIds(
ids: string[],
client: LegacyApiKeyLogWriterClient = getDbClient() as unknown as LegacyApiKeyLogWriterClient,
): Promise<unknown> {
return client.apiKeyLog.deleteMany({
where: {
id: { in: ids },
},
});
}
export async function deleteTenantLegacyApiKeyLogsByIds(
{ ids, tenantId }: { ids: string[]; tenantId: string | null },
client: LegacyApiKeyLogWriterClient = getDbClient() as unknown as LegacyApiKeyLogWriterClient,
): Promise<unknown> {
return client.apiKeyLog.deleteMany({
where: {
id: { in: ids },
...(tenantId ? tenantLegacyApiKeyLogScope(tenantId) : { tenantId: null, apiKeyId: null }),
},
});
}
@@ -0,0 +1,271 @@
import { describe, expect, it, vi } from "vitest";
import { AUDIT_EVENT_OUTBOX_TYPE, auditEvent, buildAuditEventCreateData, createAuditEvent, publishAuditEventViaOutbox, sanitizeAuditMetadata, type AuditEventWriterClient } from "./audit-events.server.js";
import type { AuditEvent, OutboxEvent } from "../generated/prisma/client/client.js";
import type { OutboxPublisherTransaction } from "./outbox.js";
function createAuditEventClient(opts: { previousHash?: string | null } = {}): AuditEventWriterClient {
return {
auditEvent: {
create: vi.fn(
async ({ data }) =>
({
id: "audit_event_1",
createdAt: new Date("2026-05-11T12:00:00.000Z"),
...data,
}) as AuditEvent
),
findFirst: vi.fn(async () => ({ eventHash: opts.previousHash ?? null })),
},
};
}
describe("audit event persistence", () => {
it("normalizes nullable fields and defaults actorType to system", async () => {
const client = createAuditEventClient();
await expect(
createAuditEvent(
{
action: "widget.created",
},
client
)
).resolves.toMatchObject({
actorType: "system",
action: "widget.created",
tenantId: null,
actorId: null,
targetType: null,
targetId: null,
requestId: null,
metadata: null,
outcome: "success",
dataSensitivity: "internal",
regulatoryScope: [],
eventHash: expect.stringMatching(/^[0-9a-f]{64}$/),
});
const call = (client.auditEvent.create as ReturnType<typeof vi.fn>).mock.calls[0]?.[0];
expect(call?.data).toMatchObject({
tenantId: null,
actorId: null,
actorType: "system",
action: "widget.created",
targetType: null,
targetId: null,
requestId: null,
metadata: null,
outcome: "success",
dataSensitivity: "internal",
regulatoryScope: [],
previousHash: null,
});
expect(call?.data?.eventHash).toMatch(/^[0-9a-f]{64}$/);
});
it("trims actorType before falling back and preserves provided values", async () => {
const client = createAuditEventClient();
await auditEvent(
{
tenantId: "tenant_1",
actorId: "user_1",
actorType: " user ",
action: "widget.updated",
targetType: "widget",
targetId: "widget_1",
requestId: "request_1",
metadata: { changed: true, token: "secret-token" },
},
client
);
const call = (client.auditEvent.create as ReturnType<typeof vi.fn>).mock.calls[0]?.[0];
expect(call?.data).toMatchObject({
tenantId: "tenant_1",
actorId: "user_1",
actorType: "user",
action: "widget.updated",
targetType: "widget",
targetId: "widget_1",
requestId: "request_1",
metadata: { changed: true, token: "[REDACTED]" },
});
});
it("redacts nested secret-like audit metadata without mutating the original object", () => {
const metadata = { nested: { authorization: "Bearer secret", kept: "value" }, notes: "token=secret-token" };
expect(sanitizeAuditMetadata(metadata)).toEqual({
nested: { authorization: "[REDACTED]", kept: "value" },
notes: "token=[REDACTED]",
});
expect(metadata.nested.authorization).toBe("Bearer secret");
});
it("builds Prisma create data without mutating input objects", () => {
const metadata = { value: "kept" };
const input = {
action: "thing.changed",
actorType: " ",
metadata,
};
expect(buildAuditEventCreateData(input)).toEqual({
tenantId: null,
actorId: null,
actorType: "system",
actorEmail: null,
actorIp: null,
actorUserAgent: null,
action: "thing.changed",
targetType: null,
targetId: null,
requestId: null,
sourceModule: null,
outcome: "success",
dataSensitivity: "internal",
regulatoryScope: [],
metadata,
});
expect(input).toEqual({ action: "thing.changed", actorType: " ", metadata });
});
it("captures compliance fields (ip, ua, regulatoryScope) and links hash chain", async () => {
const client = createAuditEventClient({ previousHash: "deadbeef" });
await createAuditEvent(
{
tenantId: "tenant_1",
actorId: "user_1",
actorType: "user",
actorIp: "10.0.0.1",
actorUserAgent: "vitest/1.0",
action: "user.read",
targetType: "user",
targetId: "user_2",
sourceModule: "auth",
outcome: "success",
dataSensitivity: "pii",
regulatoryScope: ["gdpr", "soc2"],
metadata: { reason: "login" },
},
client
);
const call = (client.auditEvent.create as ReturnType<typeof vi.fn>).mock.calls[0]?.[0];
expect(call?.data).toMatchObject({
actorIp: "10.0.0.1",
actorUserAgent: "vitest/1.0",
sourceModule: "auth",
outcome: "success",
dataSensitivity: "pii",
regulatoryScope: ["gdpr", "soc2"],
previousHash: "deadbeef",
});
expect(call?.data?.eventHash).toMatch(/^[0-9a-f]{64}$/);
});
it("normalizes invalid outcome/sensitivity to safe defaults", () => {
const data = buildAuditEventCreateData({
action: "x",
outcome: "haxx" as unknown as "success",
dataSensitivity: "ULTRA" as unknown as "pii",
regulatoryScope: ["GDPR", "gdpr", ""] as unknown as ReadonlyArray<"gdpr">,
});
expect(data.outcome).toBe("success");
expect(data.dataSensitivity).toBe("internal");
expect(data.regulatoryScope).toEqual(["gdpr"]);
});
});
function makeOutboxTx(): OutboxPublisherTransaction & {
outboxEvent: {
create: ReturnType<typeof vi.fn>;
findUnique: ReturnType<typeof vi.fn>;
};
} {
const tx = {
outboxEvent: {
create: vi.fn(async ({ data }: { data: Record<string, unknown> }) => ({
id: "outbox_1",
tenantId: (data.tenantId as string | null) ?? null,
eventType: data.eventType as string,
payload: data.payload,
dispatchKey: (data.dispatchKey as string | null) ?? null,
retries: 0,
createdAt: new Date(),
scheduledAt: new Date(),
priority: 0,
} as unknown as OutboxEvent)),
findUnique: vi.fn(async () => null),
},
};
return tx as unknown as OutboxPublisherTransaction & {
outboxEvent: {
create: ReturnType<typeof vi.fn>;
findUnique: ReturnType<typeof vi.fn>;
};
};
}
describe("publishAuditEventViaOutbox", () => {
it("publishes an outbox event with the canonical audit payload", async () => {
const tx = makeOutboxTx();
await publishAuditEventViaOutbox(tx, {
tenantId: "tenant_1",
actorId: "user_1",
actorType: "user",
action: "widget.created",
targetType: "widget",
targetId: "widget_1",
sourceModule: "crm",
outcome: "success",
dataSensitivity: "confidential",
regulatoryScope: ["soc2"],
metadata: { kept: true },
});
expect(tx.outboxEvent.create).toHaveBeenCalledTimes(1);
const args = tx.outboxEvent.create.mock.calls[0]?.[0] as { data: Record<string, unknown> };
expect(args.data.eventType).toBe(AUDIT_EVENT_OUTBOX_TYPE);
expect(args.data.tenantId).toBe("tenant_1");
const payload = args.data.payload as Record<string, unknown>;
expect(payload).toMatchObject({
tenantId: "tenant_1",
actorId: "user_1",
actorType: "user",
action: "widget.created",
targetType: "widget",
targetId: "widget_1",
sourceModule: "crm",
outcome: "success",
dataSensitivity: "confidential",
regulatoryScope: ["soc2"],
metadata: { kept: true },
});
// hash chain fields are NOT in the payload — the worker computes them
expect(payload.previousHash).toBeUndefined();
expect(payload.eventHash).toBeUndefined();
});
it("defaults actorType to system and sanitizes metadata", async () => {
const tx = makeOutboxTx();
await publishAuditEventViaOutbox(tx, {
action: "x.run",
metadata: { password: "hunter2", note: "ok" },
});
const args = tx.outboxEvent.create.mock.calls[0]?.[0] as { data: Record<string, unknown> };
const payload = args.data.payload as Record<string, unknown>;
expect(payload.actorType).toBe("system");
expect(payload.metadata).toEqual({ password: "[REDACTED]", note: "ok" });
});
it("routes platform-scope (tenantId=null) events through the outbox unchanged", async () => {
const tx = makeOutboxTx();
await publishAuditEventViaOutbox(tx, { tenantId: null, action: "platform.maintenance" });
const args = tx.outboxEvent.create.mock.calls[0]?.[0] as { data: Record<string, unknown> };
expect(args.data.tenantId).toBeNull();
expect(args.data.eventType).toBe(AUDIT_EVENT_OUTBOX_TYPE);
});
});
@@ -0,0 +1,305 @@
import { getDbClient } from "./client.server.js";
import type { AuditEvent, Prisma } from "../generated/prisma/client/client.js";
import { computeAuditHash, type AuditHashPayload } from "./audit-hash.js";
import { publishOutboxEvent, type OutboxPublisherTransaction } from "./outbox.js";
/**
* Phase 10 Task #67 — Compliance-Audit-Export.
*
* `createAuditEvent` is the single write-path for the AuditEvent table.
* Callers may supply compliance-relevant fields directly (actorIp,
* actorUserAgent, regulatoryScope, dataSensitivity, outcome, sourceModule);
* everything is sanitized and a tamper-evident `eventHash` is computed at
* insertion time using the preceding event's hash as a salt.
*
* The hash chain is per-tenant: each tenant's events form an independent
* chain so a tenant deletion does not break other tenants. Platform-level
* events (tenantId === null) form their own chain.
*/
export type AuditOutcome = "success" | "failure" | "blocked";
export type AuditDataSensitivity = "public" | "internal" | "confidential" | "pii";
export type AuditRegulatoryScope = "gdpr" | "hipaa" | "soc2" | "pci" | "none";
export type AuditEventInput = {
tenantId?: string | null;
actorId?: string | null;
actorType?: string | null;
actorEmail?: string | null;
actorIp?: string | null;
actorUserAgent?: string | null;
action: string;
targetType?: string | null;
targetId?: string | null;
requestId?: string | null;
sourceModule?: string | null;
outcome?: AuditOutcome | string | null;
dataSensitivity?: AuditDataSensitivity | string | null;
regulatoryScope?: ReadonlyArray<AuditRegulatoryScope | string> | null;
metadata?: Prisma.InputJsonValue | null;
};
export type AuditEventCreateData = {
tenantId: string | null;
actorId: string | null;
actorType: string;
actorEmail: string | null;
actorIp: string | null;
actorUserAgent: string | null;
action: string;
targetType: string | null;
targetId: string | null;
requestId: string | null;
sourceModule: string | null;
outcome: string;
dataSensitivity: string;
regulatoryScope: string[];
metadata: Prisma.InputJsonValue | null;
};
export type AuditEventWriterClient = {
auditEvent: {
create(args: { data: AuditEventCreateData & { previousHash?: string | null; eventHash?: string | null } }): Promise<AuditEvent>;
findFirst?(args: {
where: { tenantId: string | null; eventHash: { not: null } };
orderBy: { createdAt: "desc" };
select: { eventHash: true };
}): Promise<{ eventHash: string | null } | null>;
};
};
const SENSITIVE_AUDIT_METADATA_KEY_PATTERN = /authorization|cookie|password|secret|token|api[-_]?key|payload|body|header/i;
const VALID_OUTCOMES: ReadonlySet<string> = new Set(["success", "failure", "blocked"]);
const VALID_DATA_SENSITIVITY: ReadonlySet<string> = new Set(["public", "internal", "confidential", "pii"]);
export function buildAuditEventCreateData(input: AuditEventInput): AuditEventCreateData {
return {
tenantId: input.tenantId ?? null,
actorId: input.actorId ?? null,
actorType: input.actorType?.trim() || "system",
actorEmail: normalizeOptionalString(input.actorEmail),
actorIp: normalizeOptionalString(input.actorIp),
actorUserAgent: normalizeOptionalString(input.actorUserAgent),
action: input.action,
targetType: input.targetType ?? null,
targetId: input.targetId ?? null,
requestId: input.requestId ?? null,
sourceModule: normalizeOptionalString(input.sourceModule),
outcome: normalizeOutcome(input.outcome),
dataSensitivity: normalizeDataSensitivity(input.dataSensitivity),
regulatoryScope: normalizeRegulatoryScope(input.regulatoryScope),
metadata: sanitizeAuditMetadata(input.metadata),
};
}
function normalizeOptionalString(value: string | null | undefined): string | null {
if (typeof value !== "string") return null;
const trimmed = value.trim();
return trimmed.length === 0 ? null : trimmed;
}
function normalizeOutcome(value: string | null | undefined): string {
const candidate = typeof value === "string" ? value.trim().toLowerCase() : "";
return VALID_OUTCOMES.has(candidate) ? candidate : "success";
}
function normalizeDataSensitivity(value: string | null | undefined): string {
const candidate = typeof value === "string" ? value.trim().toLowerCase() : "";
return VALID_DATA_SENSITIVITY.has(candidate) ? candidate : "internal";
}
function normalizeRegulatoryScope(value: ReadonlyArray<string> | null | undefined): string[] {
if (!Array.isArray(value)) return [];
const seen = new Set<string>();
for (const entry of value) {
if (typeof entry === "string") {
const trimmed = entry.trim().toLowerCase();
if (trimmed.length > 0) seen.add(trimmed);
}
}
return Array.from(seen).sort();
}
export function sanitizeAuditMetadata(metadata?: Prisma.InputJsonValue | null): Prisma.InputJsonValue | null {
if (metadata === undefined || metadata === null) {
return null;
}
return sanitizeAuditMetadataValue(metadata) as Prisma.InputJsonValue;
}
function sanitizeAuditMetadataValue(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map(sanitizeAuditMetadataValue);
}
if (value && typeof value === "object") {
return Object.fromEntries(
Object.entries(value as Record<string, unknown>).map(([key, entry]) => [key, SENSITIVE_AUDIT_METADATA_KEY_PATTERN.test(key) ? "[REDACTED]" : sanitizeAuditMetadataValue(entry)]),
);
}
if (typeof value === "string") {
return value
.replace(/(authorization)\s*=\s*Bearer\s+\S+/gi, "$1=Bearer [REDACTED]")
.replace(/Bearer\s+\S+/gi, "Bearer [REDACTED]")
.replace(/(password|secret|token|api[-_]?key)=\S+/gi, "$1=[REDACTED]");
}
return value;
}
/**
* Look up the most-recent event hash for a tenant. Returns null when no
* prior event exists or the writer doesn't support findFirst (test
* doubles). The chain is unbroken so long as new writes consistently
* supply the returned hash as `previousHash`.
*/
export async function getPreviousAuditHash(
tenantId: string | null,
client: AuditEventWriterClient = getDbClient() as unknown as AuditEventWriterClient
): Promise<string | null> {
if (typeof client.auditEvent.findFirst !== "function") return null;
const row = await client.auditEvent.findFirst({
where: { tenantId, eventHash: { not: null } },
orderBy: { createdAt: "desc" },
select: { eventHash: true },
});
return row?.eventHash ?? null;
}
export async function createAuditEvent(
input: AuditEventInput,
client: AuditEventWriterClient = getDbClient() as unknown as AuditEventWriterClient
): Promise<AuditEvent> {
const data = buildAuditEventCreateData(input);
const previousHash = await getPreviousAuditHash(data.tenantId, client);
const eventHash = computeAuditHash({
previousHash,
payload: toHashPayload(data),
});
return client.auditEvent.create({ data: { ...data, previousHash, eventHash } });
}
/**
* Outbox-driven event type for audit-event inserts. Routed by the
* dispatcher to the `outbox.audit` BullMQ queue (see
* apps/worker/src/outbox/event-router.ts) and consumed by
* `apps/worker/src/jobs/audit-event-persist.ts`.
*/
export const AUDIT_EVENT_OUTBOX_TYPE = "audit.event.create" as const;
export type AuditEventOutboxPayload = AuditEventCreateData;
/**
* Transaction-aware audit-event writer.
*
* When called from inside a Prisma `$transaction` callback, the helper
* writes the audit event via the outbox (`publishOutboxEvent`) so the
* audit insert commits atomically with the surrounding business write.
* The hash chain is then computed asynchronously by the worker handler
* (`audit-event-persist`) which performs the prevHash lookup + chain
* link in a separate short transaction — this avoids long-held row
* locks on the audit table during business transactions.
*
* Callers without a transaction continue to use {@link createAuditEvent}
* directly (back-compat legacy path).
*
* See docs/improvement-plan/10-compliance-polish/compliance-audit-export.md.
*/
export async function publishAuditEventViaOutbox(
tx: OutboxPublisherTransaction,
input: AuditEventInput
): Promise<void> {
const data = buildAuditEventCreateData(input);
const payload: Prisma.InputJsonValue = {
tenantId: data.tenantId,
actorId: data.actorId,
actorType: data.actorType,
actorEmail: data.actorEmail,
actorIp: data.actorIp,
actorUserAgent: data.actorUserAgent,
action: data.action,
targetType: data.targetType,
targetId: data.targetId,
requestId: data.requestId,
sourceModule: data.sourceModule,
outcome: data.outcome,
dataSensitivity: data.dataSensitivity,
regulatoryScope: data.regulatoryScope,
metadata: data.metadata as Prisma.InputJsonValue,
};
await publishOutboxEvent(tx, {
tenantId: data.tenantId,
type: AUDIT_EVENT_OUTBOX_TYPE,
payload,
});
}
function toHashPayload(data: AuditEventCreateData): AuditHashPayload {
return {
// `id` and `createdAt` aren't known at hash time (DB assigns them); we
// include a sentinel so the chain hash binds the conceptual event but
// is deterministic. Replay verifiers re-compute using the *stored*
// id/createdAt, so we always include them — see verifyAuditChain.
id: "",
createdAt: "",
tenantId: data.tenantId,
actorType: data.actorType,
actorId: data.actorId,
actorEmail: data.actorEmail,
actorIp: data.actorIp,
actorUserAgent: data.actorUserAgent,
action: data.action,
targetType: data.targetType,
targetId: data.targetId,
requestId: data.requestId,
sourceModule: data.sourceModule,
outcome: data.outcome,
dataSensitivity: data.dataSensitivity,
regulatoryScope: data.regulatoryScope,
metadata: data.metadata,
};
}
/**
* Re-derive the canonical hash payload for an event row returned from the
* DB. Used by the verifier CLI / export integrity check.
*/
export function toAuditHashPayloadFromRow(row: {
tenantId: string | null;
actorType: string;
actorId: string | null;
actorEmail: string | null;
actorIp: string | null;
actorUserAgent: string | null;
action: string;
targetType: string | null;
targetId: string | null;
requestId: string | null;
sourceModule: string | null;
outcome: string;
dataSensitivity: string;
regulatoryScope: string[];
metadata: unknown;
}): AuditHashPayload {
return {
id: "",
createdAt: "",
tenantId: row.tenantId,
actorType: row.actorType,
actorId: row.actorId,
actorEmail: row.actorEmail,
actorIp: row.actorIp,
actorUserAgent: row.actorUserAgent,
action: row.action,
targetType: row.targetType,
targetId: row.targetId,
requestId: row.requestId,
sourceModule: row.sourceModule,
outcome: row.outcome,
dataSensitivity: row.dataSensitivity,
regulatoryScope: row.regulatoryScope,
metadata: row.metadata,
};
}
export const writeAuditEvent = createAuditEvent;
export const auditEvent = createAuditEvent;
@@ -0,0 +1,138 @@
import { describe, expect, it } from "vitest";
import { canonicalizeAuditPayload, computeAuditHash, verifyAuditChain, type AuditChainEvent, type AuditHashPayload } from "./audit-hash.js";
function makePayload(overrides: Partial<AuditHashPayload> = {}): AuditHashPayload {
return {
id: "audit_1",
createdAt: "2026-05-17T10:00:00.000Z",
tenantId: "tenant_1",
actorType: "user",
actorId: "user_1",
actorEmail: "alice@example.com",
actorIp: "10.0.0.1",
actorUserAgent: "vitest/1.0",
action: "user.read",
targetType: "user",
targetId: "user_2",
requestId: "req_1",
sourceModule: "auth",
outcome: "success",
dataSensitivity: "pii",
regulatoryScope: ["gdpr"],
metadata: { reason: "login" },
...overrides,
};
}
describe("canonicalizeAuditPayload", () => {
it("sorts object keys deterministically", () => {
expect(canonicalizeAuditPayload({ b: 1, a: 2 })).toBe(canonicalizeAuditPayload({ a: 2, b: 1 }));
});
it("preserves array order", () => {
expect(canonicalizeAuditPayload({ s: ["b", "a"] })).not.toBe(canonicalizeAuditPayload({ s: ["a", "b"] }));
});
it("treats undefined as missing and null as null", () => {
expect(canonicalizeAuditPayload({ a: undefined, b: null })).toBe('{"b":null}');
});
});
describe("computeAuditHash", () => {
it("is deterministic for identical payloads", () => {
const payload = makePayload();
expect(computeAuditHash({ previousHash: null, payload, secret: "shh" })).toBe(computeAuditHash({ previousHash: null, payload, secret: "shh" }));
});
it("differs when previousHash changes", () => {
const payload = makePayload();
expect(computeAuditHash({ previousHash: null, payload, secret: "shh" })).not.toBe(computeAuditHash({ previousHash: "abc", payload, secret: "shh" }));
});
it("differs when any payload field flips", () => {
const base = computeAuditHash({ previousHash: null, payload: makePayload(), secret: "shh" });
expect(computeAuditHash({ previousHash: null, payload: makePayload({ action: "user.write" }), secret: "shh" })).not.toBe(base);
expect(computeAuditHash({ previousHash: null, payload: makePayload({ outcome: "failure" }), secret: "shh" })).not.toBe(base);
expect(computeAuditHash({ previousHash: null, payload: makePayload({ regulatoryScope: ["soc2"] }), secret: "shh" })).not.toBe(base);
});
it("uses HMAC when secret present, SHA-256 fallback otherwise", () => {
const payload = makePayload();
const hmac = computeAuditHash({ previousHash: null, payload, secret: "shh" });
const sha = computeAuditHash({ previousHash: null, payload, secret: null });
expect(hmac).not.toBe(sha);
expect(hmac).toMatch(/^[0-9a-f]{64}$/);
expect(sha).toMatch(/^[0-9a-f]{64}$/);
});
});
describe("verifyAuditChain", () => {
it("returns ok for a valid 3-event chain", () => {
const secret = "shh";
const e1Payload = makePayload({ id: "e1" });
const e1Hash = computeAuditHash({ previousHash: null, payload: e1Payload, secret });
const e2Payload = makePayload({ id: "e2", action: "user.write" });
const e2Hash = computeAuditHash({ previousHash: e1Hash, payload: e2Payload, secret });
const e3Payload = makePayload({ id: "e3", action: "user.delete" });
const e3Hash = computeAuditHash({ previousHash: e2Hash, payload: e3Payload, secret });
const events: AuditChainEvent[] = [
{ ...e1Payload, previousHash: null, eventHash: e1Hash },
{ ...e2Payload, previousHash: e1Hash, eventHash: e2Hash },
{ ...e3Payload, previousHash: e2Hash, eventHash: e3Hash },
];
expect(verifyAuditChain(events, { secret })).toEqual({ ok: true, inspected: 3, firstBreak: null });
});
it("detects a tampered metadata field on the second event", () => {
const secret = "shh";
const e1Payload = makePayload({ id: "e1" });
const e1Hash = computeAuditHash({ previousHash: null, payload: e1Payload, secret });
const e2Payload = makePayload({ id: "e2", action: "user.write" });
const e2Hash = computeAuditHash({ previousHash: e1Hash, payload: e2Payload, secret });
const events: AuditChainEvent[] = [
{ ...e1Payload, previousHash: null, eventHash: e1Hash },
// metadata was tampered after the hash was stored
{ ...e2Payload, metadata: { reason: "forged" }, previousHash: e1Hash, eventHash: e2Hash },
];
const result = verifyAuditChain(events, { secret });
expect(result.ok).toBe(false);
expect(result.firstBreak?.eventId).toBe("e2");
expect(result.firstBreak?.reason).toBe("hash-mismatch");
});
it("detects a previousHash discontinuity (event injected mid-chain)", () => {
const secret = "shh";
const e1Payload = makePayload({ id: "e1" });
const e1Hash = computeAuditHash({ previousHash: null, payload: e1Payload, secret });
const injectedPayload = makePayload({ id: "injected", action: "user.delete" });
// The injected event claims to follow a nonexistent predecessor.
const injectedHash = computeAuditHash({ previousHash: "deadbeef", payload: injectedPayload, secret });
const events: AuditChainEvent[] = [
{ ...e1Payload, previousHash: null, eventHash: e1Hash },
{ ...injectedPayload, previousHash: "deadbeef", eventHash: injectedHash },
];
const result = verifyAuditChain(events, { secret });
expect(result.ok).toBe(false);
expect(result.firstBreak?.eventId).toBe("injected");
expect(result.firstBreak?.reason).toBe("previous-hash-mismatch");
});
it("skips pre-migration events without eventHash", () => {
const secret = "shh";
const legacy: AuditChainEvent = { ...makePayload({ id: "legacy" }), previousHash: null, eventHash: null };
const e1Payload = makePayload({ id: "e1" });
const e1Hash = computeAuditHash({ previousHash: null, payload: e1Payload, secret });
const events: AuditChainEvent[] = [
legacy,
{ ...e1Payload, previousHash: null, eventHash: e1Hash },
];
expect(verifyAuditChain(events, { secret })).toEqual({ ok: true, inspected: 1, firstBreak: null });
});
});
@@ -0,0 +1,214 @@
import { createHash, createHmac } from "node:crypto";
/**
* Tamper-evident hash chain for AuditEvent rows.
*
* Each event's `eventHash` is derived from the previous event's `eventHash`
* plus a canonical JSON encoding of the event payload. A platform-level
* secret (`AUDIT_CHAIN_SECRET`) is HMAC-mixed in so a DB-only attacker
* cannot forge a continuation of the chain without also stealing the
* secret — see docs/compliance/audit-trails.md.
*
* The canonical encoding sorts object keys recursively and stringifies
* with no whitespace so two semantically-equivalent payloads always hash
* to the same digest regardless of insertion order.
*/
export const AUDIT_CHAIN_SECRET_ENV = "AUDIT_CHAIN_SECRET";
export type AuditHashPayload = {
/** Stable identifier of the event (`AuditEvent.id`). */
id: string;
/** ISO-8601 createdAt of the event. */
createdAt: string;
/** Tenant scope (null = platform-level). */
tenantId: string | null;
/** Actor type (user | admin | api_key | system | plugin). */
actorType: string;
/** Actor identifier (null for system). */
actorId: string | null;
actorEmail: string | null;
actorIp: string | null;
actorUserAgent: string | null;
action: string;
targetType: string | null;
targetId: string | null;
requestId: string | null;
sourceModule: string | null;
outcome: string;
dataSensitivity: string;
regulatoryScope: string[];
metadata: unknown;
};
export type ComputeAuditHashArgs = {
previousHash: string | null;
payload: AuditHashPayload;
/**
* Optional explicit secret. When omitted the helper reads
* `process.env.AUDIT_CHAIN_SECRET`; when neither is set the helper falls
* back to plain SHA-256 (still tamper-evident for read-only attackers but
* not forgery-resistant).
*/
secret?: string | null;
};
/**
* Canonical JSON encoding: sort keys recursively, no whitespace, strict
* UTF-8 output. Arrays preserve order (chain payloads only contain
* deterministic arrays).
*/
export function canonicalizeAuditPayload(payload: unknown): string {
return JSON.stringify(sortValue(payload));
}
function sortValue(value: unknown): unknown {
if (value === null || value === undefined) {
return null;
}
if (Array.isArray(value)) {
return value.map(sortValue);
}
if (typeof value === "object") {
const entries = Object.entries(value as Record<string, unknown>)
.filter(([, v]) => v !== undefined)
.map(([k, v]) => [k, sortValue(v)] as const)
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
return Object.fromEntries(entries);
}
return value;
}
/**
* Compute the eventHash for a single event given its predecessor's hash.
*
* - When `AUDIT_CHAIN_SECRET` is set (env or explicit), uses
* HMAC-SHA-256(secret, previousHash || canonicalPayload).
* - Otherwise falls back to plain SHA-256(previousHash || canonicalPayload).
*/
export function computeAuditHash(args: ComputeAuditHashArgs): string {
const canonical = canonicalizeAuditPayload(args.payload);
const input = `${args.previousHash ?? ""}\n${canonical}`;
const secret = resolveSecret(args.secret);
if (secret) {
return createHmac("sha256", secret).update(input, "utf8").digest("hex");
}
return createHash("sha256").update(input, "utf8").digest("hex");
}
function resolveSecret(explicit: string | null | undefined): string | null {
if (typeof explicit === "string" && explicit.length > 0) {
return explicit;
}
if (explicit === null) {
return null;
}
const fromEnv = process.env[AUDIT_CHAIN_SECRET_ENV];
if (typeof fromEnv === "string" && fromEnv.length > 0) {
return fromEnv;
}
return null;
}
export type AuditChainEvent = AuditHashPayload & {
previousHash: string | null;
eventHash: string | null;
};
export type AuditChainBreak = {
eventId: string;
expectedHash: string;
actualHash: string | null;
expectedPreviousHash: string | null;
actualPreviousHash: string | null;
reason: "hash-mismatch" | "previous-hash-mismatch" | "missing-hash";
};
export type VerifyAuditChainResult = {
ok: boolean;
inspected: number;
firstBreak: AuditChainBreak | null;
};
/**
* Re-compute hashes for an ordered sequence of audit events (oldest →
* newest) and report the first break in the chain.
*
* Events without `eventHash` set are treated as pre-migration history and
* skipped silently — they predate the chain. The first event with a hash
* anchors the chain (its `previousHash` is compared against the prior
* event's `eventHash`, or `null` if it is the chain root).
*/
export function verifyAuditChain(
events: ReadonlyArray<AuditChainEvent>,
options: { secret?: string | null } = {}
): VerifyAuditChainResult {
let inspected = 0;
let lastHash: string | null = null;
for (const event of events) {
if (event.eventHash === null) {
// Pre-chain history: still update lastHash to null sentinel.
lastHash = null;
continue;
}
inspected += 1;
if (event.previousHash !== lastHash) {
return {
ok: false,
inspected,
firstBreak: {
eventId: event.id,
expectedHash: event.eventHash,
actualHash: event.eventHash,
expectedPreviousHash: lastHash,
actualPreviousHash: event.previousHash,
reason: "previous-hash-mismatch",
},
};
}
const recomputed = computeAuditHash({
previousHash: event.previousHash,
payload: stripChainFields(event),
secret: options.secret,
});
if (recomputed !== event.eventHash) {
return {
ok: false,
inspected,
firstBreak: {
eventId: event.id,
expectedHash: recomputed,
actualHash: event.eventHash,
expectedPreviousHash: event.previousHash,
actualPreviousHash: event.previousHash,
reason: "hash-mismatch",
},
};
}
lastHash = event.eventHash;
}
return { ok: true, inspected, firstBreak: null };
}
function stripChainFields(event: AuditChainEvent): AuditHashPayload {
// `previousHash` and `eventHash` are NOT part of the payload digest.
return {
id: event.id,
createdAt: event.createdAt,
tenantId: event.tenantId,
actorType: event.actorType,
actorId: event.actorId,
actorEmail: event.actorEmail,
actorIp: event.actorIp,
actorUserAgent: event.actorUserAgent,
action: event.action,
targetType: event.targetType,
targetId: event.targetId,
requestId: event.requestId,
sourceModule: event.sourceModule,
outcome: event.outcome,
dataSensitivity: event.dataSensitivity,
regulatoryScope: event.regulatoryScope,
metadata: event.metadata,
};
}
@@ -0,0 +1,246 @@
import { describe, expect, it, vi } from "vitest";
import {
authBoundaryTenantDetailsInclude,
adminGetAllActiveTenants,
getAuthUserById,
getAuthUserWithoutPasswordById,
getLoginUserByEmail,
getTenantById,
getTenantByIdOrSlug,
getTenantMembershipByIds,
getTenantsForUser,
recordLogin,
type AuthUserReaderClient,
type AuthUserWithoutPasswordReaderClient,
type LoginLogWriterClient,
type LoginUserReaderClient,
type TenantAccountReaderClient,
} from "./auth-boundary.server.js";
function createTenantClient(items: unknown[] = [], membership: unknown = null): TenantAccountReaderClient {
return {
tenant: {
findMany: vi.fn().mockResolvedValue(items),
findUnique: vi.fn().mockResolvedValue(items[0] ?? null),
findFirst: vi.fn().mockResolvedValue(items[0] ?? null),
},
tenantUser: {
findFirst: vi.fn().mockResolvedValue(membership),
},
} as unknown as TenantAccountReaderClient;
}
describe("auth boundary user reads", () => {
it("selects only auth user fields by id", async () => {
const findUnique = vi.fn().mockResolvedValue({
id: "user_123",
email: "user@example.com",
passwordHash: "should-not-leak",
});
const client = { user: { findUnique } } as unknown as AuthUserReaderClient;
await expect(getAuthUserById("user_123", client)).resolves.toEqual({
id: "user_123",
email: "user@example.com",
});
expect(findUnique).toHaveBeenCalledWith({
where: { id: "user_123" },
select: { id: true, email: true },
});
});
it("returns null when the auth user does not exist", async () => {
const client: AuthUserReaderClient = {
user: { findUnique: vi.fn().mockResolvedValue(null) },
};
await expect(getAuthUserById("missing", client)).resolves.toBeNull();
});
it("selects user fields without password hash", async () => {
const user = {
id: "user_123",
email: "user@example.com",
firstName: "Ada",
lastName: "Lovelace",
avatar: null,
phone: null,
admin: null,
defaultTenantId: null,
createdAt: new Date("2026-05-01T00:00:00.000Z"),
locale: "de",
lightOrDarkMode: "dark",
};
const findUnique = vi.fn().mockResolvedValue(user);
const client = { user: { findUnique } } as unknown as AuthUserWithoutPasswordReaderClient;
await expect(getAuthUserWithoutPasswordById("user_123", client)).resolves.toEqual(user);
expect(findUnique).toHaveBeenCalledWith({
where: { id: "user_123" },
select: {
id: true,
email: true,
firstName: true,
lastName: true,
avatar: true,
phone: true,
admin: true,
defaultTenantId: true,
createdAt: true,
locale: true,
lightOrDarkMode: true,
},
});
expect(findUnique.mock.calls[0]?.[0].select).not.toHaveProperty("passwordHash");
});
it("returns null when no user id is provided for passwordless auth user", async () => {
const client: AuthUserWithoutPasswordReaderClient = {
user: { findUnique: vi.fn() },
};
await expect(getAuthUserWithoutPasswordById(undefined, client)).resolves.toBeNull();
expect(client.user.findUnique).not.toHaveBeenCalled();
});
it("keeps password hash selection limited to the login helper", async () => {
const findUnique = vi.fn().mockResolvedValue({
id: "user_123",
email: "user@example.com",
passwordHash: "hash",
});
const client = { user: { findUnique } } as unknown as LoginUserReaderClient;
await expect(getLoginUserByEmail("user@example.com", client)).resolves.toEqual({
id: "user_123",
email: "user@example.com",
passwordHash: "hash",
});
expect(findUnique).toHaveBeenCalledWith({
where: { email: "user@example.com" },
select: { id: true, email: true, passwordHash: true },
});
});
it("records login through the boundary alias", async () => {
const create = vi.fn().mockResolvedValue({});
const client: LoginLogWriterClient = { log: { create } };
await recordLogin("user_123", client);
expect(create).toHaveBeenCalledWith({
data: {
userId: "user_123",
url: "",
action: "Login",
details: "",
},
});
});
});
describe("auth boundary tenant reads", () => {
it("uses the detailed tenant query shape for tenant-by-id", async () => {
const tenant = { id: "tenant_1" };
const client = createTenantClient([tenant]);
await expect(getTenantById("tenant_1", client)).resolves.toBe(tenant);
expect(client.tenant.findUnique).toHaveBeenCalledWith({
where: { id: "tenant_1" },
include: authBoundaryTenantDetailsInclude,
});
});
it("uses a scoped OR query for tenant-by-id-or-slug", async () => {
const tenant = { id: "tenant_1", slug: "acme", subscription: null };
const client = createTenantClient([tenant]);
await expect(getTenantByIdOrSlug("acme", client)).resolves.toBe(tenant);
expect(client.tenant.findFirst).toHaveBeenCalledWith({
where: {
OR: [{ id: "acme" }, { slug: "acme" }],
},
include: {
subscription: true,
types: true,
},
});
});
it("keeps tenant memberships scoped to the requested user", async () => {
const memberships = [{ id: "tenant_1", name: "Acme", slug: "acme" }];
const client = createTenantClient(memberships);
await expect(getTenantsForUser("user_123", client)).resolves.toBe(memberships);
expect(client.tenant.findMany).toHaveBeenCalledWith({
where: { active: true, users: { some: { userId: "user_123", status: 2 } } },
select: {
id: true,
name: true,
slug: true,
icon: true,
logo: true,
deactivatedReason: true,
types: true,
active: true,
theme: true,
themeConfig: true,
},
orderBy: { name: "asc" },
});
});
it("allows admin tenant selection through the auth boundary", async () => {
const tenants = [{ id: "tenant_1", name: "Acme", slug: "acme" }];
const client = createTenantClient(tenants);
await expect(adminGetAllActiveTenants(client)).resolves.toBe(tenants);
expect(client.tenant.findMany).toHaveBeenCalledWith({
where: { active: true },
select: {
id: true,
name: true,
slug: true,
icon: true,
logo: true,
deactivatedReason: true,
types: true,
active: true,
theme: true,
themeConfig: true,
},
orderBy: { name: "asc" },
});
});
it("looks up tenant membership by tenant and user ids", async () => {
const membership = { id: "membership_1", tenantId: "tenant_1", userId: "user_123" };
const client = createTenantClient([], membership);
await expect(getTenantMembershipByIds("tenant_1", "user_123", client)).resolves.toBe(membership);
expect(client.tenantUser.findFirst).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", userId: "user_123", status: 2, tenant: { active: true } },
include: {
tenant: true,
user: {
select: {
id: true,
email: true,
firstName: true,
lastName: true,
phone: true,
locale: true,
createdAt: true,
},
},
},
});
});
it("returns null when tenant membership does not exist", async () => {
const client = createTenantClient([], null);
await expect(getTenantMembershipByIds("tenant_1", "missing_user", client)).resolves.toBeNull();
});
});
@@ -0,0 +1,32 @@
export {
findLegacyAuthUserById as getAuthUserById,
findLegacyLoginUserByEmail as getLoginUserByEmail,
findLegacyUserWithoutPasswordById as getAuthUserWithoutPasswordById,
recordLegacyLogin as recordLogin,
updateLegacyUserDefaultTenantId as updateAuthUserDefaultTenantId,
type LegacyAuthUser as AuthUser,
type LegacyAuthUserReaderClient as AuthUserReaderClient,
type LegacyLoginLogWriterClient as LoginLogWriterClient,
type LegacyLoginUser as LoginUser,
type LegacyLoginUserReaderClient as LoginUserReaderClient,
type LegacyUserWithoutPassword as AuthUserWithoutPassword,
type LegacyUserDefaultTenantWriterClient as AuthUserDefaultTenantWriterClient,
type LegacyUserWithoutPasswordReaderClient as AuthUserWithoutPasswordReaderClient,
} from "./users.server.js";
export {
adminGetAllActiveLegacyTenants as adminGetAllActiveTenants,
createUniqueLegacyTenantIpAddress as createUniqueTenantIpAddressRecord,
findLegacyTenantById as getTenantById,
findLegacyTenantByIdOrSlug as getTenantByIdOrSlug,
findTenantMembershipByIds as getTenantMembershipByIds,
getLegacyTenantMembershipsForUser as getTenantsForUser,
legacyTenantDetailsInclude as authBoundaryTenantDetailsInclude,
type AuthBoundaryTenantMembership as AuthTenantMembership,
type LegacyTenantAccountReaderClient as TenantAccountReaderClient,
type LegacyTenantIpAddressCreateData as TenantIpAddressCreateData,
type LegacyTenantIpAddressWriterClient as TenantIpAddressWriterClient,
type LegacyTenantMemberSimple as AuthTenantMember,
type LegacyTenantSimple as AuthTenantSimple,
type LegacyTenantWithDetails as AuthTenantWithDetails,
} from "./accounts.server.js";
@@ -0,0 +1,187 @@
import { readFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it, vi } from "vitest";
import {
TENANT_USER_STATUS_ACTIVE,
WorkspaceContextRevalidationError,
listWorkspaceAuthProviders,
revalidateWorkspaceContext,
serializeWorkspaceAuthProvider,
type WorkspaceAuthProviderClient,
} from "./auth-providers.server.js";
const now = new Date("2026-05-08T15:30:00.000Z");
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
function membership(overrides: Partial<ReturnType<typeof baseMembership>> = {}) {
return { ...baseMembership(), ...overrides };
}
function baseMembership() {
return {
id: "membership_1",
createdAt: now,
tenantId: "tenant_1",
userId: "user_1",
type: 2 as number,
joined: 1 as number,
status: TENANT_USER_STATUS_ACTIVE as number,
};
}
function provider(overrides: Partial<ReturnType<typeof baseProvider>> = {}) {
return { ...baseProvider(), ...overrides };
}
function baseProvider() {
return {
id: "provider_1",
createdAt: now,
updatedAt: now,
tenantId: "tenant_1",
kind: "oidc",
name: "Acme OIDC",
slug: "acme-oidc",
enabled: true,
issuer: "https://idp.example.com",
authorizationUrl: "https://idp.example.com/oauth/authorize",
tokenUrl: "https://idp.example.com/oauth/token",
jwksUrl: "https://idp.example.com/.well-known/jwks.json",
clientId: "public-client-id",
entityId: null as string | null,
ssoUrl: null as string | null,
certificateFingerprint: null as string | null,
metadataUpdatedAt: now,
};
}
function createAuthProviderClient(rows: ReturnType<typeof provider>[] = [], tenantMembership: ReturnType<typeof membership> | null = membership()): WorkspaceAuthProviderClient {
return {
workspaceAuthProvider: {
findMany: vi.fn().mockResolvedValue(rows),
},
tenantUser: {
findFirst: vi.fn().mockResolvedValue(tenantMembership),
},
} as unknown as WorkspaceAuthProviderClient;
}
describe("workspace context revalidation", () => {
it("returns a valid context for active tenant membership", async () => {
const activeMembership = membership();
const client = createAuthProviderClient([], activeMembership);
await expect(revalidateWorkspaceContext({ tenantId: " tenant_1 ", userId: " user_1 " }, client)).resolves.toEqual({
valid: true,
tenantId: "tenant_1",
userId: "user_1",
membership: activeMembership,
});
expect(client.tenantUser.findFirst).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", userId: "user_1", tenant: { active: true } },
orderBy: { id: "asc" },
});
});
it("rejects missing membership and cross-tenant contexts", async () => {
const client = createAuthProviderClient([], null);
await expect(revalidateWorkspaceContext({ tenantId: "tenant_2", userId: "user_1" }, client)).rejects.toMatchObject({
code: "context_membership_not_found",
});
expect(client.tenantUser.findFirst).toHaveBeenCalledWith({
where: { tenantId: "tenant_2", userId: "user_1", tenant: { active: true } },
orderBy: { id: "asc" },
});
});
it("requires the tenant attached to the membership to still be active", async () => {
const client = createAuthProviderClient([], null);
await expect(revalidateWorkspaceContext({ tenantId: "tenant_1", userId: "user_1" }, client)).rejects.toMatchObject({
code: "context_membership_not_found",
});
expect(client.tenantUser.findFirst).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", userId: "user_1", tenant: { active: true } },
orderBy: { id: "asc" },
});
});
it("rejects finalized or inactive memberships with stable non-secret codes", async () => {
const client = createAuthProviderClient([], membership({ status: 3 }));
await expect(revalidateWorkspaceContext({ tenantId: "tenant_1", userId: "user_1" }, client)).rejects.toBeInstanceOf(
WorkspaceContextRevalidationError,
);
await expect(revalidateWorkspaceContext({ tenantId: "tenant_1", userId: "user_1" }, client)).rejects.toMatchObject({
code: "context_membership_not_active",
message: "context_membership_not_active",
});
});
it("rejects malformed payloads before querying", async () => {
const client = createAuthProviderClient();
await expect(revalidateWorkspaceContext({ tenantId: "", userId: "user_1" }, client)).rejects.toMatchObject({
code: "context_missing_tenant_id",
});
await expect(revalidateWorkspaceContext({ tenantId: "tenant_1", userId: " " }, client)).rejects.toMatchObject({
code: "context_missing_user_id",
});
expect(client.tenantUser.findFirst).not.toHaveBeenCalled();
});
});
describe("workspace auth provider serialization", () => {
it("lists providers with tenant-scoped filters and enabled providers first", async () => {
const rows = [provider({ enabled: true }), provider({ id: "provider_2", slug: "acme-saml", kind: "saml", enabled: false })];
const client = createAuthProviderClient(rows);
await expect(listWorkspaceAuthProviders({ tenantId: "tenant_1", kind: "saml", enabled: false }, client)).resolves.toEqual([
expect.objectContaining({ id: "provider_1", status: "enabled" }),
expect.objectContaining({ id: "provider_2", status: "disabled" }),
]);
expect(client.workspaceAuthProvider.findMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", kind: "saml", enabled: false },
orderBy: [{ enabled: "desc" }, { kind: "asc" }, { name: "asc" }, { id: "asc" }],
});
});
it("serializes disabled providers without secret-like fields", () => {
const dto = serializeWorkspaceAuthProvider(
provider({
kind: "saml",
enabled: false,
entityId: "urn:acme:saml",
ssoUrl: "https://idp.example.com/saml/sso",
certificateFingerprint: "SHA256:abc123",
}),
);
expect(dto).toEqual(
expect.objectContaining({
kind: "saml",
enabled: false,
status: "disabled",
entityId: "urn:acme:saml",
certificateFingerprint: "SHA256:abc123",
}),
);
expect(JSON.stringify(dto)).not.toMatch(/secret|privateKey|tokenHash|assertion/i);
});
it("guards the WorkspaceAuthProvider schema against secret-like columns", () => {
const schema = readFileSync(resolve(repoRoot, "prisma/schema/accounts.prisma"), "utf8");
const modelBody = schema.match(/model WorkspaceAuthProvider \{([\s\S]*?)\n\}/)?.[1] ?? "";
const fieldNames = modelBody
.split("\n")
.map((line) => line.trim().match(/^(\w+)\s/)?.[1])
.filter(Boolean);
const secretBearingFieldNames = fieldNames.filter((fieldName) => fieldName !== "tokenUrl").join("\n");
expect(secretBearingFieldNames).not.toMatch(/\b\w*(secret|privateKey|token|assertion)\w*\b/i);
});
});
@@ -0,0 +1,167 @@
import { getDbClient } from "./client.server.js";
import type { Prisma, TenantUser, WorkspaceAuthProvider } from "./prisma-browser.js";
export const WORKSPACE_AUTH_PROVIDER_KIND_OIDC = "oidc" as const;
export const WORKSPACE_AUTH_PROVIDER_KIND_SAML = "saml" as const;
export const WORKSPACE_AUTH_PROVIDER_STATUS_ENABLED = "enabled" as const;
export const WORKSPACE_AUTH_PROVIDER_STATUS_DISABLED = "disabled" as const;
export const TENANT_USER_STATUS_ACTIVE = 2 as const;
export type WorkspaceAuthProviderKind = typeof WORKSPACE_AUTH_PROVIDER_KIND_OIDC | typeof WORKSPACE_AUTH_PROVIDER_KIND_SAML;
export type WorkspaceAuthProviderStatus = typeof WORKSPACE_AUTH_PROVIDER_STATUS_ENABLED | typeof WORKSPACE_AUTH_PROVIDER_STATUS_DISABLED;
export type WorkspaceContextRevalidationErrorCode =
| "context_missing_tenant_id"
| "context_missing_user_id"
| "context_membership_not_found"
| "context_membership_not_active";
export class WorkspaceContextRevalidationError extends Error {
readonly code: WorkspaceContextRevalidationErrorCode;
constructor(code: WorkspaceContextRevalidationErrorCode) {
super(code);
this.name = "WorkspaceContextRevalidationError";
this.code = code;
}
}
export type WorkspaceAuthProviderDto = {
id: string;
tenantId: string;
kind: string;
name: string;
slug: string;
enabled: boolean;
status: WorkspaceAuthProviderStatus;
issuer: string | null;
authorizationUrl: string | null;
tokenUrl: string | null;
jwksUrl: string | null;
clientId: string | null;
entityId: string | null;
ssoUrl: string | null;
certificateFingerprint: string | null;
metadataUpdatedAt: Date | null;
createdAt: Date;
updatedAt: Date;
};
export type WorkspaceAuthProviderListInput = {
tenantId: string;
kind?: WorkspaceAuthProviderKind | string;
enabled?: boolean;
};
export type WorkspaceContextRevalidationInput = {
tenantId?: string | null;
userId?: string | null;
};
export type WorkspaceContextRevalidationResult = {
valid: true;
tenantId: string;
userId: string;
membership: TenantUser;
};
export type WorkspaceAuthProviderClient = {
workspaceAuthProvider: {
findMany(args: {
where: Prisma.WorkspaceAuthProviderWhereInput;
orderBy: Prisma.WorkspaceAuthProviderOrderByWithRelationInput | Prisma.WorkspaceAuthProviderOrderByWithRelationInput[];
}): Promise<WorkspaceAuthProvider[]>;
};
tenantUser: {
findFirst(args: {
where: Prisma.TenantUserWhereInput;
orderBy?: Prisma.TenantUserOrderByWithRelationInput | Prisma.TenantUserOrderByWithRelationInput[];
}): Promise<TenantUser | null>;
};
};
function getClient(client?: WorkspaceAuthProviderClient): WorkspaceAuthProviderClient {
return client ?? (getDbClient() as unknown as WorkspaceAuthProviderClient);
}
function requireNonBlank(value: string | null | undefined): string | null {
const normalized = value?.trim();
return normalized ? normalized : null;
}
function isActiveMembership(membership: TenantUser): boolean {
return membership.status === TENANT_USER_STATUS_ACTIVE;
}
export function serializeWorkspaceAuthProvider(provider: WorkspaceAuthProvider): WorkspaceAuthProviderDto {
return {
id: provider.id,
tenantId: provider.tenantId,
kind: provider.kind,
name: provider.name,
slug: provider.slug,
enabled: provider.enabled,
status: provider.enabled ? WORKSPACE_AUTH_PROVIDER_STATUS_ENABLED : WORKSPACE_AUTH_PROVIDER_STATUS_DISABLED,
issuer: provider.issuer,
authorizationUrl: provider.authorizationUrl,
tokenUrl: provider.tokenUrl,
jwksUrl: provider.jwksUrl,
clientId: provider.clientId,
entityId: provider.entityId,
ssoUrl: provider.ssoUrl,
certificateFingerprint: provider.certificateFingerprint,
metadataUpdatedAt: provider.metadataUpdatedAt,
createdAt: provider.createdAt,
updatedAt: provider.updatedAt,
};
}
export async function listWorkspaceAuthProviders(
input: WorkspaceAuthProviderListInput,
client?: WorkspaceAuthProviderClient,
): Promise<WorkspaceAuthProviderDto[]> {
const db = getClient(client);
const providers = await db.workspaceAuthProvider.findMany({
where: {
tenantId: input.tenantId,
...(input.kind ? { kind: input.kind } : {}),
...(input.enabled === undefined ? {} : { enabled: input.enabled }),
},
orderBy: [{ enabled: "desc" }, { kind: "asc" }, { name: "asc" }, { id: "asc" }],
});
return providers.map(serializeWorkspaceAuthProvider);
}
export async function revalidateWorkspaceContext(
input: WorkspaceContextRevalidationInput,
client?: WorkspaceAuthProviderClient,
): Promise<WorkspaceContextRevalidationResult> {
const tenantId = requireNonBlank(input.tenantId);
if (!tenantId) {
throw new WorkspaceContextRevalidationError("context_missing_tenant_id");
}
const userId = requireNonBlank(input.userId);
if (!userId) {
throw new WorkspaceContextRevalidationError("context_missing_user_id");
}
const db = getClient(client);
const membership = await db.tenantUser.findFirst({
where: { tenantId, userId, tenant: { active: true } },
orderBy: { id: "asc" },
});
if (!membership) {
throw new WorkspaceContextRevalidationError("context_membership_not_found");
}
if (!isActiveMembership(membership)) {
throw new WorkspaceContextRevalidationError("context_membership_not_active");
}
return { valid: true, tenantId, userId, membership };
}
@@ -0,0 +1,128 @@
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
__resetDbClientSingletonsForTests,
createDbClient,
getDbClient,
getExtendedDbClient,
getReadDbClient,
getWriteDbClient,
} from "./client.server.js";
const clientServerSourcePath = path.join(path.dirname(fileURLToPath(import.meta.url)), "./client.server.ts");
const clientServerSource = () => readFileSync(clientServerSourcePath, "utf8");
describe("@toolctrl/db server client boundary", () => {
it("exports a createDbClient factory from the package-owned generated client", () => {
expect(createDbClient).toEqual(expect.any(Function));
});
it("reuses a singleton across runtime environments", () => {
const existingClient = {} as ReturnType<typeof createDbClient>;
global.__db = existingClient;
expect(getDbClient({ nodeEnv: "development" })).toBe(existingClient);
expect(getDbClient({ nodeEnv: "production" })).toBe(existingClient);
global.__db = undefined;
});
it("keeps explicit client options isolated from the process singleton", () => {
const existingClient = {} as ReturnType<typeof createDbClient>;
global.__db = existingClient;
expect(getDbClient({ connectionString: "postgresql://user:pass@example.test:5432/db" })).not.toBe(existingClient);
global.__db = undefined;
});
it("wires database error diagnostics through the structured logger while preserving custom callbacks", () => {
const source = clientServerSource();
expect(source).toContain('import { createChildLogger, defaultLogger } from "@toolctrl/logger";');
expect(source).toContain('const dbLogger = createChildLogger(defaultLogger, { component: "db" });');
expect(source).toContain('dbLogger.error({ error: event }, "database error");');
expect(source).toContain("options.onError ?? logDatabaseError");
});
it("does not leave active console diagnostics in the server database client", () => {
const source = clientServerSource();
const withoutLineComments = source.replaceAll(/\/\/.*$/gm, "");
expect(withoutLineComments).not.toMatch(/\bconsole\.(?:log|error|warn|info)\s*\(/);
});
});
describe("R/W-split singletons", () => {
const originalReadUrl = process.env.DATABASE_READ_URL;
afterEach(() => {
if (originalReadUrl === undefined) {
delete process.env.DATABASE_READ_URL;
} else {
process.env.DATABASE_READ_URL = originalReadUrl;
}
__resetDbClientSingletonsForTests();
});
it("falls back to the write singleton when DATABASE_READ_URL is unset", () => {
delete process.env.DATABASE_READ_URL;
const existingWriter = {} as ReturnType<typeof createDbClient>;
global.__db = existingWriter;
global.__dbRead = undefined;
const read = getReadDbClient();
const write = getWriteDbClient();
expect(read).toBe(existingWriter);
expect(read).toBe(write);
});
it("falls back to the write singleton when DATABASE_READ_URL is an empty string", () => {
process.env.DATABASE_READ_URL = "";
const existingWriter = {} as ReturnType<typeof createDbClient>;
global.__db = existingWriter;
global.__dbRead = undefined;
expect(getReadDbClient()).toBe(existingWriter);
});
it("creates a distinct read client when DATABASE_READ_URL is set", () => {
process.env.DATABASE_READ_URL = "postgresql://reader:pw@replica.test:5432/db";
const existingWriter = {} as ReturnType<typeof createDbClient>;
global.__db = existingWriter;
global.__dbRead = undefined;
const read = getReadDbClient();
expect(read).not.toBe(existingWriter);
expect(getReadDbClient()).toBe(read); // memoised
});
it("exposes .read and .write accessors via $extends and lets default API flow to the write client", () => {
delete process.env.DATABASE_READ_URL;
const existingWriter = createDbClient({ connectionString: "postgresql://user:pass@primary.test:5432/db" });
global.__db = existingWriter;
global.__dbRead = undefined;
const extended = getExtendedDbClient();
expect(extended.write).toBe(existingWriter);
expect(extended.read).toBe(existingWriter); // fallback semantics
// Default API (e.g. extended.user) must still be present — $extends preserves it.
expect(extended).toHaveProperty("user");
});
it("routes .read and .write to different underlying clients when a replica URL is configured", () => {
process.env.DATABASE_READ_URL = "postgresql://reader:pw@replica.test:5432/db";
global.__db = undefined;
global.__dbRead = undefined;
const extended = getExtendedDbClient();
expect(extended.read).not.toBe(extended.write);
});
});
@@ -0,0 +1,141 @@
import { Prisma, PrismaClient } from "../generated/prisma/client/client.js";
import { PrismaPg } from "@prisma/adapter-pg";
import { createChildLogger, defaultLogger } from "@toolctrl/logger";
export type DbClient = PrismaClient;
export type DbClientOptions = {
connectionString?: string;
onError?: (event: Prisma.LogEvent) => void;
};
export type DbClientSingletonOptions = DbClientOptions & {
nodeEnv?: string;
};
declare global {
// eslint-disable-next-line no-var
var __db: DbClient | undefined;
// eslint-disable-next-line no-var
var __dbRead: DbClient | undefined;
}
const dbLogger = createChildLogger(defaultLogger, { component: "db" });
function logDatabaseError(event: Prisma.LogEvent) {
dbLogger.error({ error: event }, "database error");
}
export function createDbClient(options: DbClientOptions = {}): DbClient {
const adapter = new PrismaPg({
connectionString: options.connectionString ?? process.env.DATABASE_URL,
});
const client = new PrismaClient({
adapter,
log: [{ emit: "event", level: "error" }],
});
client.$on("error" as never, (event: Prisma.LogEvent) => {
(options.onError ?? logDatabaseError)(event);
});
return client;
}
export function getDbClient(options: DbClientSingletonOptions = {}): DbClient {
if (options.connectionString || options.onError) {
return createDbClient(options);
}
if (!global.__db) {
global.__db = createDbClient(options);
}
return global.__db;
}
/**
* Returns the explicit write-target Prisma client. Always points at the
* primary Postgres (`DATABASE_URL`).
*
* Use for mutations, auth-flow reads that must be strictly consistent
* (read-after-write), Stripe webhook handlers that read state they just
* wrote, and the outbox dispatcher reading PENDING events.
*
* Functionally identical to {@link getDbClient} — both return the same
* singleton — but call-sites that explicitly need primary should prefer
* `getWriteDbClient()` for clarity.
*/
export function getWriteDbClient(): DbClient {
return getDbClient();
}
/**
* Returns the read-replica Prisma client. Falls back to the write client
* when `DATABASE_READ_URL` is unset, so call-sites can opt into replica
* routing without breaking single-DB dev / self-hosted setups.
*
* **Replication lag:** typical < 1 s, but bursts of writes can push lag
* to 5-10 s. Never read on the replica immediately after writing on the
* primary inside the same request — see `docs/architecture/rw-split.md`.
*
* Use for: list endpoints, dashboards, public KB / sites / portals,
* analytics aggregations, search results — read-only workloads where
* eventual consistency is acceptable.
*/
export function getReadDbClient(): DbClient {
const readUrl = process.env.DATABASE_READ_URL;
if (!readUrl || readUrl.length === 0) {
return getDbClient();
}
if (!global.__dbRead) {
global.__dbRead = createDbClient({ connectionString: readUrl });
}
return global.__dbRead;
}
/**
* Internal helper for tests — clears both singletons so the next
* `getDbClient()` / `getReadDbClient()` call reinitialises against
* fresh environment variables. Production code MUST NOT call this.
*/
export function __resetDbClientSingletonsForTests(): void {
global.__db = undefined;
global.__dbRead = undefined;
}
/**
* Returns a Prisma client extended via `$extends` with `.write` and
* `.read` accessors. The base client (and all default-API calls like
* `extended.user.findMany(...)`) routes to the **write** primary,
* preserving backwards compatibility with code that wasn't migrated.
*
* - `extended.write.<model>.<op>` — explicit primary route
* - `extended.read.<model>.<op>` — replica route (falls back to primary
* when `DATABASE_READ_URL` is unset)
*
* Fallback semantics: when no replica URL is configured, both accessors
* return the same underlying client instance, so single-DB dev / CI
* works identically to a replicated production setup.
*/
export function getExtendedDbClient() {
const writeClient = getWriteDbClient();
const readClient = getReadDbClient();
return writeClient.$extends({
name: "rw-split",
client: {
get write(): DbClient {
return writeClient;
},
get read(): DbClient {
return readClient;
},
},
});
}
export type ExtendedDbClient = ReturnType<typeof getExtendedDbClient>;
@@ -0,0 +1,176 @@
import { describe, it, expect } from "vitest";
import {
defaultPushProviderFor,
findDeviceTokenByToken,
listActiveDeviceTokens,
parseDevicePlatform,
parsePushProvider,
registerDeviceToken,
revokeDeviceToken,
revokeDeviceTokensForUser,
type DeviceTokenClient,
type DeviceTokenRecord,
} from "./device-tokens.server.js";
type StoredRow = DeviceTokenRecord;
function createStubClient(): DeviceTokenClient & { _rows: StoredRow[] } {
const rows: StoredRow[] = [];
let serial = 0;
return {
_rows: rows,
deviceToken: {
async upsert(args) {
const existing = rows.find((r) => r.token === args.where.token);
const now = new Date();
if (existing) {
existing.userId = args.update.userId;
existing.tenantId = args.update.tenantId;
existing.platform = args.update.platform;
existing.pushProvider = args.update.pushProvider;
existing.appVersion = args.update.appVersion ?? null;
existing.lastSeenAt = args.update.lastSeenAt;
existing.revokedAt = args.update.revokedAt;
existing.updatedAt = now;
return existing;
}
serial += 1;
const row: StoredRow = {
id: `dt-${serial}`,
createdAt: now,
updatedAt: now,
userId: args.create.userId,
tenantId: args.create.tenantId,
platform: args.create.platform,
token: args.create.token,
pushProvider: args.create.pushProvider,
appVersion: args.create.appVersion ?? null,
lastSeenAt: now,
revokedAt: null,
};
rows.push(row);
return row;
},
async update(args) {
const found = rows.find((r) => r.token === args.where.token);
if (!found) throw new Error("not found");
found.revokedAt = args.data.revokedAt;
found.updatedAt = new Date();
return found;
},
async updateMany(args) {
let count = 0;
for (const row of rows) {
if (row.userId === args.where.userId && row.revokedAt === null) {
row.revokedAt = args.data.revokedAt;
row.updatedAt = new Date();
count += 1;
}
}
return { count };
},
async findMany(args) {
return rows
.filter((r) => {
if (args.where.userId && r.userId !== args.where.userId) return false;
if (args.where.tenantId && r.tenantId !== args.where.tenantId) return false;
if (args.where.revokedAt === null && r.revokedAt !== null) return false;
return true;
})
.slice(0, args.take ?? rows.length);
},
async findUnique(args) {
return rows.find((r) => r.token === args.where.token) ?? null;
},
},
};
}
describe("parseDevicePlatform / parsePushProvider", () => {
it("accepts the documented values and rejects everything else", () => {
expect(parseDevicePlatform("ios")).toBe("ios");
expect(parseDevicePlatform("android")).toBe("android");
expect(parseDevicePlatform("web")).toBe("web");
expect(parseDevicePlatform("desktop")).toBeNull();
expect(parseDevicePlatform(123)).toBeNull();
expect(parsePushProvider("fcm")).toBe("fcm");
expect(parsePushProvider("apns")).toBe("apns");
expect(parsePushProvider("webpush")).toBe("webpush");
expect(parsePushProvider("onesignal")).toBeNull();
});
});
describe("defaultPushProviderFor", () => {
it("maps platform -> provider", () => {
expect(defaultPushProviderFor("ios")).toBe("apns");
expect(defaultPushProviderFor("android")).toBe("fcm");
expect(defaultPushProviderFor("web")).toBe("webpush");
});
});
describe("registerDeviceToken", () => {
it("creates a new row when the token is unseen", async () => {
const client = createStubClient();
const row = await registerDeviceToken(
{ userId: "u-1", tenantId: "t-1", platform: "ios", token: "tok-1" },
client,
);
expect(row.pushProvider).toBe("apns");
expect(row.revokedAt).toBeNull();
expect(client._rows).toHaveLength(1);
});
it("bumps lastSeenAt and clears revokedAt on re-registration", async () => {
const client = createStubClient();
await registerDeviceToken(
{ userId: "u-1", tenantId: "t-1", platform: "android", token: "tok-x" },
client,
);
await revokeDeviceToken("tok-x", client);
expect(client._rows[0]?.revokedAt).not.toBeNull();
await registerDeviceToken(
{ userId: "u-1", tenantId: "t-1", platform: "android", token: "tok-x" },
client,
);
expect(client._rows[0]?.revokedAt).toBeNull();
expect(client._rows).toHaveLength(1);
});
});
describe("revokeDeviceTokensForUser", () => {
it("revokes only the active tokens belonging to the user", async () => {
const client = createStubClient();
await registerDeviceToken({ userId: "u-1", tenantId: null, platform: "ios", token: "t1" }, client);
await registerDeviceToken({ userId: "u-1", tenantId: null, platform: "android", token: "t2" }, client);
await registerDeviceToken({ userId: "u-2", tenantId: null, platform: "ios", token: "t3" }, client);
const count = await revokeDeviceTokensForUser("u-1", client);
expect(count).toBe(2);
const remaining = client._rows.filter((r) => r.revokedAt === null);
expect(remaining.map((r) => r.token)).toEqual(["t3"]);
});
});
describe("listActiveDeviceTokens", () => {
it("returns only non-revoked tokens for the requested user (+optional tenant)", async () => {
const client = createStubClient();
await registerDeviceToken({ userId: "u-1", tenantId: "t-1", platform: "ios", token: "ta" }, client);
await registerDeviceToken({ userId: "u-1", tenantId: "t-2", platform: "ios", token: "tb" }, client);
await registerDeviceToken({ userId: "u-1", tenantId: "t-1", platform: "android", token: "tc" }, client);
await revokeDeviceToken("tc", client);
const allForUser = await listActiveDeviceTokens({ userId: "u-1" }, client);
expect(allForUser.map((r) => r.token).sort()).toEqual(["ta", "tb"]);
const scoped = await listActiveDeviceTokens({ userId: "u-1", tenantId: "t-1" }, client);
expect(scoped.map((r) => r.token)).toEqual(["ta"]);
});
});
describe("findDeviceTokenByToken", () => {
it("returns null for unknown tokens", async () => {
const client = createStubClient();
expect(await findDeviceTokenByToken("missing", client)).toBeNull();
});
});
@@ -0,0 +1,188 @@
/**
* Server-side helpers for the DeviceToken Prisma model (Phase 08 #65).
*
* The mobile-wrapper register-device endpoint upserts on the unique
* `token` column, the push-worker job filters by `revokedAt IS NULL`
* for fan-out, and the cron prune script revokes rows older than 90d.
*
* Keeping these functions narrow and prisma-shape-only lets unit tests
* inject a stub client without pulling in `@prisma/client` at all.
*/
import { getDbClient, type DbClient } from "./client.server.js";
export type DevicePlatform = "ios" | "android" | "web";
export type PushProvider = "fcm" | "apns" | "webpush";
const DEVICE_PLATFORMS = new Set<DevicePlatform>(["ios", "android", "web"]);
const PUSH_PROVIDERS = new Set<PushProvider>(["fcm", "apns", "webpush"]);
export function parseDevicePlatform(value: unknown): DevicePlatform | null {
return typeof value === "string" && DEVICE_PLATFORMS.has(value as DevicePlatform) ? (value as DevicePlatform) : null;
}
export function parsePushProvider(value: unknown): PushProvider | null {
return typeof value === "string" && PUSH_PROVIDERS.has(value as PushProvider) ? (value as PushProvider) : null;
}
/** Default provider for a given platform when the client omits it. */
export function defaultPushProviderFor(platform: DevicePlatform): PushProvider {
if (platform === "ios") return "apns";
if (platform === "android") return "fcm";
return "webpush";
}
export type DeviceTokenRecord = {
id: string;
createdAt: Date;
updatedAt: Date;
userId: string;
tenantId: string | null;
platform: string;
token: string;
pushProvider: string;
appVersion: string | null;
lastSeenAt: Date;
revokedAt: Date | null;
};
export type DeviceTokenClient = {
deviceToken: {
upsert(args: {
where: { token: string };
create: {
userId: string;
tenantId: string | null;
platform: DevicePlatform;
token: string;
pushProvider: PushProvider;
appVersion?: string | null;
};
update: {
userId: string;
tenantId: string | null;
platform: DevicePlatform;
pushProvider: PushProvider;
appVersion?: string | null;
lastSeenAt: Date;
revokedAt: null;
};
}): Promise<DeviceTokenRecord>;
update(args: {
where: { token: string };
data: { revokedAt: Date };
}): Promise<DeviceTokenRecord>;
updateMany(args: {
where: { userId: string; revokedAt: null };
data: { revokedAt: Date };
}): Promise<{ count: number }>;
findMany(args: {
where: { userId?: string; tenantId?: string; revokedAt?: null };
orderBy?: { createdAt: "desc" | "asc" };
take?: number;
}): Promise<readonly DeviceTokenRecord[]>;
findUnique(args: { where: { token: string } }): Promise<DeviceTokenRecord | null>;
};
};
export type RegisterDeviceTokenInput = {
userId: string;
tenantId: string | null;
platform: DevicePlatform;
token: string;
pushProvider?: PushProvider;
appVersion?: string | null;
};
/**
* Idempotent upsert keyed by `token`. Re-registration of the same token
* (typical on app cold-start) just bumps `lastSeenAt` and clears any
* prior `revokedAt`.
*/
export async function registerDeviceToken(
input: RegisterDeviceTokenInput,
client: DeviceTokenClient = getDbClient() as unknown as DeviceTokenClient,
): Promise<DeviceTokenRecord> {
const provider = input.pushProvider ?? defaultPushProviderFor(input.platform);
const now = new Date();
return client.deviceToken.upsert({
where: { token: input.token },
create: {
userId: input.userId,
tenantId: input.tenantId,
platform: input.platform,
token: input.token,
pushProvider: provider,
appVersion: input.appVersion ?? null,
},
update: {
userId: input.userId,
tenantId: input.tenantId,
platform: input.platform,
pushProvider: provider,
appVersion: input.appVersion ?? null,
lastSeenAt: now,
revokedAt: null,
},
});
}
/**
* Mark a single token revoked. Called when the push provider responds
* with `Unregistered` / `InvalidRegistration` so the next fan-out pass
* skips this token.
*/
export async function revokeDeviceToken(
token: string,
client: DeviceTokenClient = getDbClient() as unknown as DeviceTokenClient,
): Promise<DeviceTokenRecord | null> {
try {
return await client.deviceToken.update({
where: { token },
data: { revokedAt: new Date() },
});
} catch {
return null;
}
}
/** Revoke all active tokens for a user (logout / password-change hook). */
export async function revokeDeviceTokensForUser(
userId: string,
client: DeviceTokenClient = getDbClient() as unknown as DeviceTokenClient,
): Promise<number> {
const { count } = await client.deviceToken.updateMany({
where: { userId, revokedAt: null },
data: { revokedAt: new Date() },
});
return count;
}
/**
* List active tokens for fan-out. Scoped by user (always required) plus
* optional tenant. Returns at most `take` tokens, newest first.
*/
export async function listActiveDeviceTokens(
args: { userId: string; tenantId?: string; take?: number },
client: DeviceTokenClient = getDbClient() as unknown as DeviceTokenClient,
): Promise<readonly DeviceTokenRecord[]> {
return client.deviceToken.findMany({
where: {
userId: args.userId,
...(args.tenantId ? { tenantId: args.tenantId } : {}),
revokedAt: null,
},
orderBy: { createdAt: "desc" },
take: args.take ?? 100,
});
}
export async function findDeviceTokenByToken(
token: string,
client: DeviceTokenClient = getDbClient() as unknown as DeviceTokenClient,
): Promise<DeviceTokenRecord | null> {
return client.deviceToken.findUnique({ where: { token } });
}
// Re-export DbClient so call-sites in the API / worker can keep their
// type assertion narrow without needing an extra import path.
export type { DbClient };
@@ -0,0 +1,80 @@
import { describe, expect, it } from "vitest";
import { anonymizeIp, buildUserPseudonymizationUpdate, pseudonymize } from "./pseudonymize.js";
describe("pseudonymize()", () => {
it("is deterministic for the same userId", () => {
const a = pseudonymize("user-1");
const b = pseudonymize("user-1");
expect(a).toEqual(b);
});
it("produces distinct pseudonyms for distinct userIds", () => {
const a = pseudonymize("user-1");
const b = pseudonymize("user-2");
expect(a.pseudoEmail).not.toBe(b.pseudoEmail);
expect(a.pseudoId).not.toBe(b.pseudoId);
});
it("emits a synthetic email under the .invalid TLD by default", () => {
const result = pseudonymize("user-1");
expect(result.pseudoEmail).toMatch(/^deleted-user-[a-f0-9]{16}@pseudonymized\.invalid$/);
});
it("strips PII fields (phone, avatar) to null", () => {
const result = pseudonymize("user-1");
expect(result.pseudoPhone).toBeNull();
expect(result.pseudoAvatar).toBeNull();
});
it("changes the hash when a pepper is supplied", () => {
const plain = pseudonymize("user-1");
const peppered = pseudonymize("user-1", { pepper: "deployment-X" });
expect(plain.pseudoEmail).not.toBe(peppered.pseudoEmail);
});
it("respects a custom email domain", () => {
const result = pseudonymize("user-1", { emailDomain: "anon.example" });
expect(result.pseudoEmail).toMatch(/^deleted-user-[a-f0-9]{16}@anon\.example$/);
});
it("rejects an empty userId", () => {
expect(() => pseudonymize("")).toThrow(/non-empty string/);
});
});
describe("anonymizeIp()", () => {
it("masks the last octet of an IPv4 address", () => {
expect(anonymizeIp("203.0.113.42")).toBe("203.0.113.0");
});
it("returns null for invalid IPv4 (octet out of range)", () => {
expect(anonymizeIp("999.0.0.1")).toBeNull();
});
it("masks the interface identifier of an IPv6 address (/48)", () => {
expect(anonymizeIp("2001:0db8:85a3:0000:0000:8a2e:0370:7334")).toBe("2001:0db8:85a3:::::0");
});
it("returns null for empty or non-string inputs", () => {
expect(anonymizeIp("")).toBeNull();
expect(anonymizeIp(null)).toBeNull();
expect(anonymizeIp(undefined)).toBeNull();
});
});
describe("buildUserPseudonymizationUpdate()", () => {
it("produces a prisma User.update payload with the terminal flags set", () => {
const update = buildUserPseudonymizationUpdate("user-1");
expect(update.pseudonymized).toBe(true);
expect(update.pseudonymizedAt).toBeInstanceOf(Date);
expect(update.pendingDeletion).toBe(false);
expect(update.scheduledDeletionAt).toBeNull();
expect(update.email).toMatch(/^deleted-user-[a-f0-9]{16}@pseudonymized\.invalid$/);
expect(update.firstName).toBe("Anonymized");
expect(update.lastName).toMatch(/^User-[a-f0-9]{8}$/);
expect(update.passwordHash).toMatch(/^\$2a\$10\$pseudonymized-[a-f0-9]{12}$/);
expect(update.avatar).toBeNull();
expect(update.phone).toBeNull();
});
});
@@ -0,0 +1,142 @@
import { createHash } from "node:crypto";
/**
* Phase 10 Task #68 — DSGVO deterministic pseudonymization helper.
*
* Given a `userId`, derives a deterministic pseudonym set that can be
* substituted into retention-bound rows (AuditEvents, support tickets,
* etc.) without losing referential coherence — the same userId always
* maps to the same pseudonym, so historical reports keep grouping the
* user's activity together while the original PII is gone.
*
* Determinism property:
* pseudonymize("u1").pseudoEmail === pseudonymize("u1").pseudoEmail
*
* No external secret is mixed in: re-identification is intentionally
* *not* possible from the pseudonym alone — that is the whole point of
* pseudonymization under Art. 4(5) DSGVO. The optional `pepper` argument
* exists for cases where the operator wants per-deployment salting; a
* caller that omits it gets the stable global hash.
*/
const PSEUDO_PREFIX = "deleted-user";
export interface PseudonymizedIdentity {
/** Stable pseudonym hash (first 16 hex chars of SHA-256(userId|pepper)). */
pseudoId: string;
/** Replacement email — deterministic and obviously synthetic. */
pseudoEmail: string;
/** Replacement first name — fixed string, no PII. */
pseudoFirstName: string;
/** Replacement last name — short hash suffix to keep rows distinguishable. */
pseudoLastName: string;
/** Replacement phone — empty by design (Art. 17). */
pseudoPhone: null;
/** Replacement avatar — empty by design. */
pseudoAvatar: null;
}
export interface PseudonymizeOptions {
/**
* Optional per-deployment salt. When set the hash changes across
* deployments which is desirable for tenant isolation, but for the
* test-fixture scenarios we expose deterministic output without it.
*/
pepper?: string;
/** Override domain for the synthetic email (default: `pseudonymized.invalid`). */
emailDomain?: string;
}
const DEFAULT_EMAIL_DOMAIN = "pseudonymized.invalid";
/**
* Compute a deterministic pseudonym for `userId`. Caller supplies the
* userId; everything else is derived.
*/
export function pseudonymize(userId: string, options: PseudonymizeOptions = {}): PseudonymizedIdentity {
if (typeof userId !== "string" || userId.length === 0) {
throw new Error("pseudonymize(): userId must be a non-empty string");
}
const pepper = options.pepper ?? "";
const digest = createHash("sha256").update(userId).update(pepper).digest("hex");
const pseudoId = digest.slice(0, 16);
const domain = (options.emailDomain ?? DEFAULT_EMAIL_DOMAIN).replace(/^@/, "");
return {
pseudoId,
pseudoEmail: `${PSEUDO_PREFIX}-${pseudoId}@${domain}`,
pseudoFirstName: "Anonymized",
pseudoLastName: `User-${pseudoId.slice(0, 8)}`,
pseudoPhone: null,
pseudoAvatar: null,
};
}
/**
* IP-anonymisation helper used when pseudonymising AuditEvent.actorIp.
* Strips the last octet for IPv4 (/24) and the last 80 bits for IPv6
* (/48 standard for GeoIP-safe anonymisation per BSI / ENISA guidance).
*
* Returns `null` when the input is not a recognisable IP string so the
* caller can store NULL instead of a malformed value.
*/
export function anonymizeIp(input: string | null | undefined): string | null {
if (typeof input !== "string") return null;
const trimmed = input.trim();
if (!trimmed) return null;
// IPv4: 4 dot-separated octets, each 0-255.
const ipv4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.\d{1,3}$/.exec(trimmed);
if (ipv4) {
const [, a, b, c] = ipv4;
if ([a, b, c].every((octet) => Number(octet) >= 0 && Number(octet) <= 255)) {
return `${a}.${b}.${c}.0`;
}
return null;
}
// IPv6 — keep the first three hextets (/48) which preserves the
// routing prefix but drops the interface identifier and the subnet.
// Accept shorthand `::` notation by expanding via `URL`.
if (trimmed.includes(":")) {
const parts = trimmed.split(":");
if (parts.length < 2) return null;
return [parts[0] ?? "0", parts[1] ?? "0", parts[2] ?? "0", "", "", "", "", "0"].join(":");
}
return null;
}
/**
* Build the prisma `User.update` payload that flips the row into the
* pseudonymized terminal state. Centralised here so callers (worker job,
* admin override, CLI) emit the same field set.
*/
export function buildUserPseudonymizationUpdate(userId: string, options: PseudonymizeOptions = {}): {
email: string;
firstName: string;
lastName: string;
avatar: string | null;
phone: string | null;
passwordHash: string;
pseudonymized: true;
pseudonymizedAt: Date;
pendingDeletion: false;
scheduledDeletionAt: null;
} {
const id = pseudonymize(userId, options);
return {
email: id.pseudoEmail,
firstName: id.pseudoFirstName,
lastName: id.pseudoLastName,
avatar: id.pseudoAvatar,
phone: id.pseudoPhone,
// Replace the password with a non-recoverable bcrypt-shaped placeholder.
// The terminal `$2a$` prefix keeps callers that probe the hash format
// happy without ever resolving to a real password.
passwordHash: `$2a$10$pseudonymized-${id.pseudoId.slice(0, 12)}`,
pseudonymized: true,
pseudonymizedAt: new Date(),
pendingDeletion: false,
scheduledDeletionAt: null,
};
}
@@ -0,0 +1,82 @@
import { readFileSync, readdirSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import { USER_FK_MAP, USER_FK_MAP_BY_STRATEGY, findUserFkEntry } from "./user-fk-map.js";
const __dirname = dirname(fileURLToPath(import.meta.url));
const SCHEMA_DIR = resolve(__dirname, "../../../../prisma/schema");
type GrepEntry = { model: string; column: string; source: string };
/**
* Re-implements the grep that informs the static USER_FK_MAP. The test
* fails whenever a new prisma model adds a `fields: [xxx], references:
* [id]` reference to `User` without updating the map.
*/
function grepUserFks(): GrepEntry[] {
const files = readdirSync(SCHEMA_DIR).filter((f) => f.endsWith(".prisma"));
const out: GrepEntry[] = [];
for (const file of files) {
const text = readFileSync(join(SCHEMA_DIR, file), "utf8");
let currentModel: string | null = null;
for (const line of text.split("\n")) {
const modelMatch = /^model\s+(\w+)\s*\{/.exec(line);
if (modelMatch) {
currentModel = modelMatch[1] ?? null;
continue;
}
if (!line.includes("references: [id]")) continue;
if (!/\bUser\??\s/.test(line)) continue;
const fieldsMatch = /fields:\s*\[(\w+)\]/.exec(line);
if (!fieldsMatch || !currentModel) continue;
out.push({ model: currentModel, column: fieldsMatch[1] ?? "", source: file });
}
}
return out;
}
describe("USER_FK_MAP", () => {
it("covers every User foreign-key relation declared in prisma/schema", () => {
const greppedEntries = grepUserFks();
expect(greppedEntries.length).toBeGreaterThan(0);
for (const entry of greppedEntries) {
const match = findUserFkEntry(entry.model, entry.column);
expect(match, `missing user-fk-map entry for ${entry.model}.${entry.column}`).toBeDefined();
expect(match!.source).toBe(entry.source);
}
});
it("uses only the three documented strategies", () => {
const valid = new Set(["hard-delete", "pseudonymize", "retain-tombstone"]);
for (const entry of USER_FK_MAP) {
expect(valid.has(entry.strategy)).toBe(true);
}
});
it("partitions every entry into exactly one strategy bucket", () => {
const total =
USER_FK_MAP_BY_STRATEGY.hardDelete.length +
USER_FK_MAP_BY_STRATEGY.pseudonymize.length +
USER_FK_MAP_BY_STRATEGY.retainTombstone.length;
expect(total).toBe(USER_FK_MAP.length);
});
it("retains AuditEvent.actorId via pseudonymization (SOC2-CC6.1 audit-trail integrity)", () => {
const auditEntry = findUserFkEntry("AuditEvent", "actorId");
expect(auditEntry).toBeDefined();
expect(auditEntry!.strategy).toBe("pseudonymize");
});
it("entries are alphabetically sorted by model+column for review-friendly diffs", () => {
const sorted = [...USER_FK_MAP].slice().sort((a, b) => {
const byModel = a.model.localeCompare(b.model);
return byModel !== 0 ? byModel : a.column.localeCompare(b.column);
});
// Order-preserved equality check — same length, same elements, same order.
expect(USER_FK_MAP.map((e) => `${e.model}.${e.column}`)).toEqual(sorted.map((e) => `${e.model}.${e.column}`));
});
});
@@ -0,0 +1,125 @@
/**
* Phase 10 Task #68 — DSGVO bulk-ops user-FK map.
*
* Enumerates every Prisma model that holds a foreign key (or a logical
* reference) to `User.id`. Each entry declares an explicit cascade
* strategy used by the deletion pipeline (`dsgvo-deletion.ts`) and the
* export pipeline (`dsgvo-export.ts`).
*
* Strategies:
*
* • `hard-delete` — delete rows when the user is deleted. Used
* for join tables, ephemeral data and rows
* with no retention requirement.
*
* • `pseudonymize` — keep the row but null/replace the user FK
* with the deterministic pseudonym. Used for
* retention-bound rows such as AuditEvents,
* help-desk tickets and historical analytics
* where regulatory or business intent
* requires the record to survive deletion.
*
* • `retain-tombstone` — keep the row but set the FK to NULL
* (existing schema-level `onDelete: SetNull`
* handles the column update). Used when the
* row outlives the user but no audit reference
* is required.
*
* The companion test (`user-fk-map.test.ts`) asserts that the grep over
* `prisma/schema/*.prisma` finds exactly the relations enumerated here.
* If a future migration adds a new User-FK without updating this map,
* the test fails and the cascade silently leaking PII is blocked at
* CI time.
*/
export type DsgvoCascadeStrategy = "hard-delete" | "pseudonymize" | "retain-tombstone";
export interface UserFkMapEntry {
/** Prisma model name (matches `model X { ... }`). */
model: string;
/** Foreign-key column on `model` that references `User.id`. */
column: string;
/** Cascade strategy applied by the deletion worker. */
strategy: DsgvoCascadeStrategy;
/** Schema source file (debug/audit aid). */
source: string;
/** Whether this table is included in the personal-data export bundle. */
includeInExport: boolean;
}
/**
* Sorted alphabetically by `model` + `column` so diffs against future
* additions stay reviewable.
*/
export const USER_FK_MAP: ReadonlyArray<UserFkMapEntry> = Object.freeze([
{ model: "AdminUser", column: "userId", strategy: "hard-delete", source: "accounts.prisma", includeInExport: true },
{ model: "AnalyticsUniqueVisitor", column: "userId", strategy: "pseudonymize", source: "analytics.prisma", includeInExport: false },
{ model: "ApiKey", column: "createdByUserId", strategy: "hard-delete", source: "core.prisma", includeInExport: true },
{ model: "App", column: "installedByUserId", strategy: "retain-tombstone", source: "appsEngine.prisma", includeInExport: true },
{ model: "AppSyncRun", column: "createdByUserId", strategy: "retain-tombstone", source: "appsEngine.prisma", includeInExport: false },
// AuditEvent has no FK relation in the schema (actorId is a free
// string column) — we list it here as a *logical* reference. The
// pseudonymization strategy is mandatory: SOC2-CC6.1 requires the
// audit trail to survive user deletion, only its PII fields are
// rewritten.
{ model: "AuditEvent", column: "actorId", strategy: "pseudonymize", source: "core.prisma", includeInExport: true },
{ model: "Credit", column: "userId", strategy: "pseudonymize", source: "subscriptions.prisma", includeInExport: true },
{ model: "DeviceToken", column: "userId", strategy: "hard-delete", source: "notifications.prisma", includeInExport: false },
{ model: "EmailRead", column: "userId", strategy: "hard-delete", source: "email.prisma", includeInExport: true },
{ model: "EntityView", column: "createdByUserId", strategy: "hard-delete", source: "entityBuilder.prisma", includeInExport: true },
{ model: "EntityView", column: "userId", strategy: "hard-delete", source: "entityBuilder.prisma", includeInExport: true },
{ model: "Event", column: "userId", strategy: "pseudonymize", source: "core.prisma", includeInExport: true },
{ model: "Feedback", column: "userId", strategy: "pseudonymize", source: "helpDesk.prisma", includeInExport: true },
{ model: "FormulaLog", column: "userId", strategy: "pseudonymize", source: "entityBuilder.prisma", includeInExport: false },
{ model: "Group", column: "createdByUserId", strategy: "retain-tombstone", source: "permissions.prisma", includeInExport: true },
{ model: "GroupUser", column: "userId", strategy: "hard-delete", source: "permissions.prisma", includeInExport: true },
{ model: "ImpersonationAudit", column: "actorUserId", strategy: "pseudonymize", source: "accounts.prisma", includeInExport: true },
{ model: "ImpersonationAudit", column: "targetUserId", strategy: "pseudonymize", source: "accounts.prisma", includeInExport: true },
{ model: "KnowledgeBaseArticle", column: "createdByUserId", strategy: "pseudonymize", source: "knowledgeBase.prisma", includeInExport: true },
{ model: "Log", column: "userId", strategy: "pseudonymize", source: "core.prisma", includeInExport: true },
{ model: "MagicLinkToken", column: "userId", strategy: "hard-delete", source: "accounts.prisma", includeInExport: false },
{ model: "MetricLog", column: "userId", strategy: "pseudonymize", source: "core.prisma", includeInExport: false },
{ model: "NotificationDelivery", column: "userId", strategy: "pseudonymize", source: "notifications.prisma", includeInExport: true },
{ model: "OnboardingSession", column: "userId", strategy: "hard-delete", source: "onboarding.prisma", includeInExport: true },
{ model: "Portal", column: "createdByUserId", strategy: "retain-tombstone", source: "portals.prisma", includeInExport: true },
{ model: "Row", column: "createdByUserId", strategy: "pseudonymize", source: "entityBuilder.prisma", includeInExport: true },
{ model: "RowComment", column: "createdByUserId", strategy: "pseudonymize", source: "entityBuilder.prisma", includeInExport: true },
{ model: "RowCommentReaction", column: "createdByUserId", strategy: "hard-delete", source: "entityBuilder.prisma", includeInExport: true },
{ model: "RowPermission", column: "userId", strategy: "hard-delete", source: "entityBuilder.prisma", includeInExport: true },
{ model: "RowTask", column: "assignedToUserId", strategy: "retain-tombstone", source: "entityBuilder.prisma", includeInExport: true },
{ model: "RowTask", column: "completedByUserId", strategy: "retain-tombstone", source: "entityBuilder.prisma", includeInExport: true },
{ model: "RowTask", column: "createdByUserId", strategy: "pseudonymize", source: "entityBuilder.prisma", includeInExport: true },
{ model: "Site", column: "createdByUserId", strategy: "retain-tombstone", source: "sites.prisma", includeInExport: true },
{ model: "SupportTicket", column: "userId", strategy: "pseudonymize", source: "helpDesk.prisma", includeInExport: true },
{ model: "TenantIpAddress", column: "userId", strategy: "hard-delete", source: "accounts.prisma", includeInExport: true },
{ model: "TenantUser", column: "userId", strategy: "hard-delete", source: "accounts.prisma", includeInExport: true },
{ model: "TenantUserInvitation", column: "acceptedByUserId", strategy: "retain-tombstone", source: "accounts.prisma", includeInExport: true },
{ model: "TenantUserInvitation", column: "createdUserId", strategy: "retain-tombstone", source: "accounts.prisma", includeInExport: true },
{ model: "TenantUserInvitation", column: "fromUserId", strategy: "retain-tombstone", source: "accounts.prisma", includeInExport: true },
{ model: "TenantUserInvitation", column: "revokedByUserId", strategy: "retain-tombstone", source: "accounts.prisma", includeInExport: true },
// Auth session/device artifacts (R-P2b). They already declare
// `onDelete: Cascade`, so hard-delete is the matching DSGVO strategy; not user
// content, so excluded from export.
{ model: "TrustedDevice", column: "userId", strategy: "hard-delete", source: "auth.prisma", includeInExport: false },
{ model: "UserNotificationPreference", column: "userId", strategy: "hard-delete", source: "notifications.prisma", includeInExport: true },
{ model: "UserRole", column: "userId", strategy: "hard-delete", source: "permissions.prisma", includeInExport: true },
{ model: "UserSession", column: "userId", strategy: "hard-delete", source: "auth.prisma", includeInExport: false },
{ model: "Workflow", column: "createdByUserId", strategy: "retain-tombstone", source: "workflows.prisma", includeInExport: true },
{ model: "WorkflowCredential", column: "userId", strategy: "retain-tombstone", source: "workflows.prisma", includeInExport: true },
{ model: "WorkflowExecution", column: "createdByUserId", strategy: "pseudonymize", source: "workflows.prisma", includeInExport: false },
{ model: "WorkflowVariable", column: "userId", strategy: "retain-tombstone", source: "workflows.prisma", includeInExport: true },
]);
export const USER_FK_MAP_BY_STRATEGY = Object.freeze({
hardDelete: USER_FK_MAP.filter((e) => e.strategy === "hard-delete"),
pseudonymize: USER_FK_MAP.filter((e) => e.strategy === "pseudonymize"),
retainTombstone: USER_FK_MAP.filter((e) => e.strategy === "retain-tombstone"),
});
export function getUserFkEntriesForExport(): readonly UserFkMapEntry[] {
return USER_FK_MAP.filter((entry) => entry.includeInExport);
}
export function findUserFkEntry(model: string, column: string): UserFkMapEntry | undefined {
return USER_FK_MAP.find((entry) => entry.model === model && entry.column === column);
}
@@ -0,0 +1,115 @@
import { describe, expect, it, vi } from "vitest";
import {
markEmailSequenceDeliveryBounced,
type EmailSequenceProviderWebhookClient,
type EmailSequenceProviderWebhookTransactionClient,
} from "./email-sequences.server.js";
describe("email sequence provider webhook helpers", () => {
it("marks the correlated delivery bounced and fails the run", async () => {
const bouncedAt = new Date("2026-01-02T03:04:05.000Z");
const tx = createTransactionClient({
delivery: {
id: "delivery_1",
runId: "run_1",
status: "sent",
bouncedAt: null,
run: { id: "run_1", status: "running" },
},
});
const client = createClient(tx);
await expect(
markEmailSequenceDeliveryBounced(
{
providerMessageId: "msg_1",
bouncedAt,
errorMessage: "activity.hard_bounced",
},
client
)
).resolves.toEqual({ status: "bounced", deliveryId: "delivery_1", runId: "run_1" });
expect(tx.emailSequenceStepDelivery.findFirst).toHaveBeenCalledWith({
where: { providerMessageId: "msg_1" },
include: { run: { select: { id: true, status: true } } },
});
expect(tx.emailSequenceStepDelivery.updateMany).toHaveBeenCalledWith({
where: { id: "delivery_1", status: { not: "bounced" } },
data: { status: "bounced", bouncedAt, errorMessage: "activity.hard_bounced" },
});
expect(tx.emailSequenceRun.updateMany).toHaveBeenCalledWith({
where: { id: "run_1", status: { notIn: ["cancelled", "unsubscribed"] } },
data: { status: "failed", completedAt: bouncedAt },
});
});
it("treats repeated bounce webhooks as idempotent", async () => {
const bouncedAt = new Date("2026-01-02T03:04:05.000Z");
const tx = createTransactionClient({
delivery: {
id: "delivery_1",
runId: "run_1",
status: "bounced",
bouncedAt,
run: { id: "run_1", status: "failed" },
},
});
await expect(
markEmailSequenceDeliveryBounced(
{
providerMessageId: "msg_1",
bouncedAt,
errorMessage: "activity.hard_bounced",
},
createClient(tx)
)
).resolves.toEqual({ status: "already_bounced", deliveryId: "delivery_1", runId: "run_1" });
expect(tx.emailSequenceStepDelivery.updateMany).not.toHaveBeenCalled();
expect(tx.emailSequenceRun.updateMany).not.toHaveBeenCalled();
});
it("returns unknown_delivery without writes when the provider id is not known", async () => {
const tx = createTransactionClient({ delivery: null });
await expect(
markEmailSequenceDeliveryBounced(
{
providerMessageId: "missing",
bouncedAt: new Date("2026-01-02T03:04:05.000Z"),
errorMessage: "activity.hard_bounced",
},
createClient(tx)
)
).resolves.toEqual({ status: "unknown_delivery" });
expect(tx.emailSequenceStepDelivery.updateMany).not.toHaveBeenCalled();
expect(tx.emailSequenceRun.updateMany).not.toHaveBeenCalled();
});
});
function createTransactionClient({
delivery,
}: {
delivery: Awaited<ReturnType<EmailSequenceProviderWebhookTransactionClient["emailSequenceStepDelivery"]["findFirst"]>>;
}): EmailSequenceProviderWebhookTransactionClient {
return {
emailSequenceStepDelivery: {
findFirst: vi.fn().mockResolvedValue(delivery),
updateMany: vi.fn().mockResolvedValue({ count: 1 }),
},
emailSequenceRun: {
updateMany: vi.fn().mockResolvedValue({ count: 1 }),
},
};
}
function createClient(tx: EmailSequenceProviderWebhookTransactionClient): EmailSequenceProviderWebhookClient {
return {
...tx,
$transaction: vi.fn((runner) => runner(tx)),
};
}
@@ -0,0 +1,81 @@
import { getDbClient } from "./client.server.js";
const NON_RETRYABLE_TERMINAL_RUN_STATUSES = ["cancelled", "unsubscribed"] as const;
export type EmailSequenceProviderWebhookResult =
| { status: "bounced"; deliveryId: string; runId: string }
| { status: "already_bounced"; deliveryId: string; runId: string }
| { status: "unknown_delivery" };
export type MarkEmailSequenceDeliveryBouncedInput = {
providerMessageId: string;
bouncedAt: Date;
errorMessage: string;
};
type EmailSequenceDeliveryWithRun = {
id: string;
runId: string;
status: string;
bouncedAt: Date | null;
run: {
id: string;
status: string;
};
};
export type EmailSequenceProviderWebhookTransactionClient = {
emailSequenceStepDelivery: {
findFirst(args: {
where: { providerMessageId: string };
include: { run: { select: { id: true; status: true } } };
}): Promise<EmailSequenceDeliveryWithRun | null>;
updateMany(args: {
where: { id: string; status?: { not: string } };
data: { status: "bounced"; bouncedAt: Date; errorMessage: string };
}): Promise<{ count: number }>;
};
emailSequenceRun: {
updateMany(args: {
where: { id: string; status?: { notIn: readonly string[] } };
data: { status: "failed"; completedAt: Date };
}): Promise<{ count: number }>;
};
};
export type EmailSequenceProviderWebhookClient = EmailSequenceProviderWebhookTransactionClient & {
$transaction<T>(runner: (tx: EmailSequenceProviderWebhookTransactionClient) => Promise<T>): Promise<T>;
};
export function markEmailSequenceDeliveryBounced(
input: MarkEmailSequenceDeliveryBouncedInput,
client: EmailSequenceProviderWebhookClient = getDbClient() as unknown as EmailSequenceProviderWebhookClient
): Promise<EmailSequenceProviderWebhookResult> {
return client.$transaction(async (tx) => {
const delivery = await tx.emailSequenceStepDelivery.findFirst({
where: { providerMessageId: input.providerMessageId },
include: { run: { select: { id: true, status: true } } },
});
if (!delivery) {
return { status: "unknown_delivery" };
}
if (delivery.status === "bounced" && delivery.bouncedAt) {
return { status: "already_bounced", deliveryId: delivery.id, runId: delivery.runId };
}
await tx.emailSequenceStepDelivery.updateMany({
where: { id: delivery.id, status: { not: "bounced" } },
data: {
status: "bounced",
bouncedAt: input.bouncedAt,
errorMessage: input.errorMessage,
},
});
await tx.emailSequenceRun.updateMany({
where: { id: delivery.run.id, status: { notIn: NON_RETRYABLE_TERMINAL_RUN_STATUSES } },
data: { status: "failed", completedAt: input.bouncedAt },
});
return { status: "bounced", deliveryId: delivery.id, runId: delivery.runId };
});
}
@@ -0,0 +1,222 @@
import { describe, expect, it, vi } from "vitest";
import {
findLegacyEntityByIdNameOrSlug,
findLegacyEntityByName,
findLegacySimpleEntityBySlug,
findOptionalLegacyEntityByName,
getAllLegacyEntities,
type LegacyEntityReaderClient,
} from "./entities.server.js";
describe("findLegacyEntityByName", () => {
it("fetches the legacy entity detail graph by name", async () => {
const entity = { id: "entity_1", name: "contact", properties: [] };
const findUnique = vi.fn().mockResolvedValue(entity);
const client: LegacyEntityReaderClient = {
entity: { findMany: vi.fn(), findUnique, findFirst: vi.fn() },
};
await expect(findLegacyEntityByName({ tenantId: null, name: "contact" }, client)).resolves.toBe(entity);
expect(findUnique).toHaveBeenCalledWith(
expect.objectContaining({
where: { name: "contact" },
include: expect.objectContaining({
views: { where: { tenantId: null }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
tags: true,
parentEntities: expect.objectContaining({
include: expect.objectContaining({
childEntityView: expect.objectContaining({ where: { tenantId: null } }),
parentEntityView: expect.objectContaining({ where: { tenantId: null } }),
}),
}),
childEntities: expect.objectContaining({
include: expect.objectContaining({
childEntityView: expect.objectContaining({ where: { tenantId: null } }),
parentEntityView: expect.objectContaining({ where: { tenantId: null } }),
}),
}),
properties: expect.objectContaining({
where: { tenantId: null },
orderBy: { order: "asc" },
}),
templates: { where: { tenantId: null } },
}),
}),
);
});
it("can restrict name lookups to active legacy entities for API access", async () => {
const entity = { id: "entity_1", name: "contact", active: true, properties: [] };
const findFirst = vi.fn().mockResolvedValue(entity);
const findUnique = vi.fn();
const client: LegacyEntityReaderClient = {
entity: { findMany: vi.fn(), findUnique, findFirst },
};
await expect(findLegacyEntityByName({ tenantId: "tenant_1", name: "contact", active: true }, client)).resolves.toBe(entity);
expect(findFirst).toHaveBeenCalledWith(
expect.objectContaining({
where: { name: "contact", active: true },
include: expect.objectContaining({
properties: expect.objectContaining({
where: { OR: [{ tenantId: null }, { tenantId: "tenant_1" }] },
}),
}),
}),
);
expect(findUnique).not.toHaveBeenCalled();
});
it("throws the legacy not found error when the entity does not exist", async () => {
const client: LegacyEntityReaderClient = {
entity: {
findMany: vi.fn(),
findUnique: vi.fn().mockResolvedValue(null),
findFirst: vi.fn(),
},
};
await expect(findLegacyEntityByName({ tenantId: null, name: "missing" }, client)).rejects.toThrow("Entity with name missing not found");
});
it("returns null for optional legacy entity lookups", async () => {
const client: LegacyEntityReaderClient = {
entity: {
findMany: vi.fn(),
findUnique: vi.fn().mockResolvedValue(null),
findFirst: vi.fn(),
},
};
await expect(findOptionalLegacyEntityByName({ tenantId: null, name: "tenantSettings" }, client)).resolves.toBeNull();
});
it("fetches simple entity metadata by slug", async () => {
const entity = {
id: "entity_1",
order: 1,
name: "contact",
title: "Contact",
titlePlural: "Contacts",
active: true,
slug: "contacts",
type: "app",
hasApi: true,
showInSidebar: true,
icon: "user",
onEdit: null,
isAutogenerated: false,
};
const findUnique = vi.fn().mockResolvedValue(entity);
const client: LegacyEntityReaderClient = {
entity: { findMany: vi.fn(), findUnique, findFirst: vi.fn() },
};
await expect(findLegacySimpleEntityBySlug("contacts", client)).resolves.toBe(entity);
expect(findUnique).toHaveBeenCalledWith({
where: {
slug: "contacts",
},
select: {
id: true,
order: true,
name: true,
title: true,
titlePlural: true,
active: true,
slug: true,
type: true,
hasApi: true,
showInSidebar: true,
icon: true,
onEdit: true,
isAutogenerated: true,
},
});
});
it("fetches a legacy entity detail graph by id, name, or slug", async () => {
const entity = { id: "entity_1", name: "contact", slug: "contacts", properties: [] };
const findFirst = vi.fn().mockResolvedValue(entity);
const client: LegacyEntityReaderClient = {
entity: { findMany: vi.fn(), findUnique: vi.fn(), findFirst },
};
await expect(findLegacyEntityByIdNameOrSlug({ tenantId: "tenant_1", idNameOrSlug: "contacts" }, client)).resolves.toBe(entity);
expect(findFirst).toHaveBeenCalledWith(
expect.objectContaining({
where: {
OR: [{ id: "contacts" }, { name: "contacts" }, { slug: "contacts" }],
},
include: expect.objectContaining({
views: { where: { OR: [{ tenantId: null }, { tenantId: "tenant_1" }] }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
tags: true,
parentEntities: expect.objectContaining({
orderBy: { order: "asc" },
include: expect.objectContaining({
childEntityView: expect.objectContaining({ where: { OR: [{ tenantId: null }, { tenantId: "tenant_1" }] } }),
parentEntityView: expect.objectContaining({ where: { OR: [{ tenantId: null }, { tenantId: "tenant_1" }] } }),
}),
}),
childEntities: expect.objectContaining({
orderBy: { order: "asc" },
include: expect.objectContaining({
childEntityView: expect.objectContaining({ where: { OR: [{ tenantId: null }, { tenantId: "tenant_1" }] } }),
parentEntityView: expect.objectContaining({ where: { OR: [{ tenantId: null }, { tenantId: "tenant_1" }] } }),
}),
}),
properties: expect.objectContaining({
where: { OR: [{ tenantId: null }, { tenantId: "tenant_1" }] },
orderBy: { order: "asc" },
include: expect.objectContaining({
attributes: true,
options: { orderBy: { order: "asc" } },
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
}),
}),
templates: { where: { OR: [{ tenantId: null }, { tenantId: "tenant_1" }] } },
}),
}),
);
});
it("throws Entity not found for missing id, name, or slug lookups", async () => {
const findFirst = vi.fn().mockResolvedValue(null);
const findUnique = vi.fn();
const client: LegacyEntityReaderClient = {
entity: { findMany: vi.fn(), findUnique, findFirst },
};
await expect(findLegacyEntityByIdNameOrSlug({ tenantId: null, idNameOrSlug: "missing" }, client)).rejects.toThrow("Entity not found");
expect(findFirst).toHaveBeenCalledWith(expect.objectContaining({ where: { OR: [{ id: "missing" }, { name: "missing" }, { slug: "missing" }] } }));
expect(findUnique).not.toHaveBeenCalled();
});
it("fetches all active entity detail graphs for API specs", async () => {
const entity = { id: "entity_1", name: "contact", properties: [] };
const findMany = vi.fn().mockResolvedValue([entity]);
const client: LegacyEntityReaderClient = {
entity: {
findMany,
findUnique: vi.fn(),
findFirst: vi.fn(),
},
} as unknown as LegacyEntityReaderClient;
await expect(getAllLegacyEntities({ tenantId: null, active: true }, client)).resolves.toEqual([entity]);
expect(findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { active: true },
orderBy: [{ type: "asc" }, { order: "asc" }],
include: expect.objectContaining({
properties: expect.objectContaining({
where: { tenantId: null },
orderBy: { order: "asc" },
}),
templates: { where: { tenantId: null } },
}),
}),
);
});
});
@@ -0,0 +1,259 @@
import { getDbClient } from "./client.server.js";
import type {
Entity,
EntityRelationship,
EntityTag,
EntityTemplate,
Prisma,
Property,
PropertyAttribute,
PropertyOption,
} from "./prisma-browser.js";
export type LegacyEntity = unknown;
export type LegacySimpleEntity = {
id: string;
order: number;
name: string;
title: string;
titlePlural: string;
active: boolean;
slug: string;
type: string;
hasApi: boolean;
showInSidebar: boolean;
icon: string;
onEdit: string | null;
isAutogenerated: boolean;
};
export type LegacyPropertyWithDetails = Property & {
attributes: PropertyAttribute[];
options: PropertyOption[];
parent?: LegacyPropertyWithDetails;
formula: { name: string; resultAs: string; calculationTrigger: string } | null;
};
export type LegacyEntityRelationshipWithDetails = EntityRelationship & {
parent: { id: string; name: string; title: string; titlePlural: string; slug: string; onEdit: string | null };
child: { id: string; name: string; title: string; titlePlural: string; slug: string; onEdit: string | null };
childEntityView: unknown;
parentEntityView: unknown;
};
export type LegacyEntityWithDetails = Entity & {
properties: LegacyPropertyWithDetails[];
views: unknown[];
tags: EntityTag[];
parentEntities: LegacyEntityRelationshipWithDetails[];
childEntities: LegacyEntityRelationshipWithDetails[];
templates: EntityTemplate[];
};
export type LegacyEntityReaderClient = {
entity: {
findMany(args: {
where: Prisma.EntityWhereInput;
orderBy: [{ type: "asc" }, { order: "asc" }];
include: ReturnType<typeof createLegacyEntityDetailsInclude>;
}): Promise<LegacyEntityWithDetails[]>;
findUnique(args:
| {
where: { name: string };
include: typeof legacyEntityDetailsInclude;
}
| {
where: { slug: string };
select: typeof selectLegacySimpleEntityProperties;
}): Promise<LegacyEntity | LegacySimpleEntity | null>;
findFirst(args: {
where: Prisma.EntityWhereInput;
include: typeof legacyEntityDetailsInclude;
}): Promise<LegacyEntity | null>;
};
};
const selectLegacySimpleEntityProperties = {
id: true,
order: true,
name: true,
title: true,
titlePlural: true,
active: true,
slug: true,
type: true,
hasApi: true,
showInSidebar: true,
icon: true,
onEdit: true,
isAutogenerated: true,
} as const;
const selectLegacyEntityWithoutIcon = {
id: true,
name: true,
title: true,
titlePlural: true,
slug: true,
onEdit: true,
};
const includeLegacyEntityViewDetails = {
properties: true,
filters: true,
sort: true,
groupByProperty: true,
};
function filterTenantId(tenantId: string | null | undefined) {
const filter: { tenantId?: string | null; OR?: { tenantId?: string | null }[] } = {};
if (tenantId === undefined) {
return filter;
}
if (tenantId === null) {
filter.tenantId = null;
} else {
filter.OR = [{ tenantId: null }, { tenantId }];
}
return filter;
}
function createLegacyEntityDetailsInclude(tenantId: string | null | undefined) {
return {
views: { where: { ...filterTenantId(tenantId) }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
tags: true,
parentEntities: {
include: {
parent: { select: selectLegacyEntityWithoutIcon },
child: { select: selectLegacyEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: includeLegacyEntityViewDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: includeLegacyEntityViewDetails },
},
orderBy: { order: "asc" },
},
childEntities: {
include: {
parent: { select: selectLegacyEntityWithoutIcon },
child: { select: selectLegacyEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: includeLegacyEntityViewDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: includeLegacyEntityViewDetails },
},
orderBy: { order: "asc" },
},
properties: {
where: { ...filterTenantId(tenantId) },
orderBy: { order: "asc" },
include: {
attributes: true,
options: {
orderBy: {
order: "asc",
},
},
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
},
},
templates: {
where: { ...filterTenantId(tenantId) },
},
} as const;
}
const legacyEntityDetailsInclude = createLegacyEntityDetailsInclude(null);
export async function findLegacyEntityByName(
{ tenantId, name, active }: { tenantId: string | null | undefined; name: string; active?: boolean },
client: LegacyEntityReaderClient = getDbClient() as unknown as LegacyEntityReaderClient,
): Promise<LegacyEntity> {
const include = createLegacyEntityDetailsInclude(tenantId);
const entity =
active === undefined
? await client.entity.findUnique({
where: { name },
include,
})
: await client.entity.findFirst({
where: { name, active },
include,
});
if (!entity) {
throw new Error(`Entity with name ${name} not found`);
}
return entity;
}
export async function findLegacyEntityByIdNameOrSlug(
{
tenantId,
idNameOrSlug,
}: {
tenantId: string | null | undefined;
idNameOrSlug: string;
},
client: LegacyEntityReaderClient = getDbClient() as unknown as LegacyEntityReaderClient,
): Promise<LegacyEntity> {
const entity = await client.entity.findFirst({
where: {
OR: [{ id: idNameOrSlug }, { name: idNameOrSlug }, { slug: idNameOrSlug }],
},
include: createLegacyEntityDetailsInclude(tenantId),
});
if (!entity) {
throw new Error("Entity not found");
}
return entity;
}
export async function getAllLegacyEntities(
{
tenantId,
active,
types,
}: {
tenantId: string | null | undefined;
active?: boolean;
types?: string[];
},
client: LegacyEntityReaderClient = getDbClient() as unknown as LegacyEntityReaderClient,
): Promise<LegacyEntityWithDetails[]> {
let where: Prisma.EntityWhereInput = {};
if (active) {
where = { active };
}
if (types) {
where = { ...where, type: { in: types } };
}
return client.entity.findMany({
where,
orderBy: [{ type: "asc" }, { order: "asc" }],
include: createLegacyEntityDetailsInclude(tenantId),
});
}
export async function findOptionalLegacyEntityByName(
{ tenantId, name }: { tenantId: string | null | undefined; name: string },
client: LegacyEntityReaderClient = getDbClient() as unknown as LegacyEntityReaderClient,
): Promise<LegacyEntity | null> {
return client.entity.findUnique({
where: { name },
include: createLegacyEntityDetailsInclude(tenantId),
});
}
export async function findLegacySimpleEntityBySlug(
slug: string,
client: LegacyEntityReaderClient = getDbClient() as unknown as LegacyEntityReaderClient,
): Promise<LegacySimpleEntity | null> {
return (await client.entity.findUnique({
where: {
slug,
},
select: selectLegacySimpleEntityProperties,
})) as LegacySimpleEntity | null;
}
@@ -0,0 +1,160 @@
import { describe, expect, it, vi } from "vitest";
import { entitlementLimitTypes, standardEntitlementPlans, type EntitlementPlanStub } from "@toolctrl/entitlements";
import { getEntitlementPlanStripeId, redactSeedError, seedStandardEntitlements, type EntitlementsSeedClient } from "./entitlements-seed.server.js";
function createSeedClient(existingProduct: { id: string } | null = null): EntitlementsSeedClient {
return {
subscriptionProduct: {
findFirst: vi.fn().mockResolvedValue(existingProduct),
create: vi.fn().mockResolvedValue({ id: "created_product" }),
update: vi.fn().mockResolvedValue(existingProduct ?? { id: "updated_product" }),
},
subscriptionFeature: {
deleteMany: vi.fn().mockResolvedValue({ count: existingProduct ? 2 : 0 }),
create: vi.fn().mockResolvedValue({ id: "feature_1" }),
},
} as unknown as EntitlementsSeedClient;
}
const singlePlan = standardEntitlementPlans[0];
describe("seedStandardEntitlements", () => {
it("creates a missing subscription product and its features from entitlement plan stubs", async () => {
const client = createSeedClient(null);
await expect(seedStandardEntitlements({ client, plans: [singlePlan] })).resolves.toEqual({
planCount: 1,
featureCount: singlePlan.features.length,
createdProducts: 1,
updatedProducts: 0,
deletedFeatures: 0,
createdFeatures: singlePlan.features.length,
});
expect(client.subscriptionProduct.findFirst).toHaveBeenCalledWith({
where: { OR: [{ stripeId: getEntitlementPlanStripeId(singlePlan) }, { title: singlePlan.metadata.publicName }] },
});
expect(client.subscriptionProduct.create).toHaveBeenCalledWith({
data: expect.objectContaining({
stripeId: getEntitlementPlanStripeId(singlePlan),
order: singlePlan.metadata.sortOrder,
title: singlePlan.metadata.publicName,
model: 0,
public: true,
active: true,
description: singlePlan.metadata.description,
badge: null,
}),
});
expect(client.subscriptionFeature.create).toHaveBeenCalledTimes(singlePlan.features.length);
expect(client.subscriptionFeature.create).toHaveBeenNthCalledWith(1, {
data: expect.objectContaining({
subscriptionProductId: "created_product",
name: singlePlan.features[0]?.featureKey,
type: singlePlan.features[0]?.limitType,
// The seed maps null limits onto the limitType numeric (`limit ?? limitType`)
// so "included" assignments materialize with value === limitType.
value: singlePlan.features[0]?.limit ?? singlePlan.features[0]?.limitType,
accumulate: false,
order: singlePlan.features[0]?.order,
}),
});
});
it("updates an existing product found by deterministic stripe id or title and replaces features", async () => {
const existingProduct = { id: "existing_product" };
const client = createSeedClient(existingProduct);
await expect(seedStandardEntitlements({ client, plans: [singlePlan] })).resolves.toMatchObject({
createdProducts: 0,
updatedProducts: 1,
deletedFeatures: 2,
createdFeatures: singlePlan.features.length,
});
expect(client.subscriptionProduct.update).toHaveBeenCalledWith({
where: { id: existingProduct.id },
data: expect.objectContaining({
stripeId: getEntitlementPlanStripeId(singlePlan),
order: singlePlan.metadata.sortOrder,
title: singlePlan.metadata.publicName,
}),
});
expect(client.subscriptionFeature.deleteMany).toHaveBeenCalledWith({ where: { subscriptionProductId: existingProduct.id } });
expect(client.subscriptionFeature.create).toHaveBeenCalledTimes(singlePlan.features.length);
});
it("emits start, per-plan, and success diagnostics with counts", async () => {
const client = createSeedClient(null);
const diagnostics = vi.fn();
await seedStandardEntitlements({ client, plans: [singlePlan], diagnostics });
expect(diagnostics).toHaveBeenCalledTimes(3);
expect(diagnostics).toHaveBeenNthCalledWith(1, {
phase: "start",
planCount: 1,
featureCount: singlePlan.features.length,
createdProducts: 0,
updatedProducts: 0,
deletedFeatures: 0,
createdFeatures: 0,
});
expect(diagnostics).toHaveBeenNthCalledWith(2, expect.objectContaining({ phase: "plan-seeded", planId: singlePlan.id, createdProducts: 1 }));
expect(diagnostics).toHaveBeenNthCalledWith(3, expect.objectContaining({ phase: "success", createdFeatures: singlePlan.features.length }));
});
it("rejects unknown feature keys before writing that feature", async () => {
const client = createSeedClient(null);
const invalidPlan: EntitlementPlanStub = {
...singlePlan,
features: [{ ...singlePlan.features[0]!, featureKey: "unknown-feature" as never }],
};
await expect(seedStandardEntitlements({ client, plans: [invalidPlan] })).rejects.toThrow("Unknown feature key");
expect(client.subscriptionFeature.create).not.toHaveBeenCalled();
});
it("redacts failure diagnostics without swallowing the original error", async () => {
const client = createSeedClient(null);
const diagnostics = vi.fn();
const error = new Error("failed for cus_live_123 tenant_abc sub_raw_456 postgres://user:password@example.com/db admin@example.com");
vi.mocked(client.subscriptionFeature.deleteMany).mockRejectedValueOnce(error);
await expect(seedStandardEntitlements({ client, plans: [singlePlan], diagnostics })).rejects.toBe(error);
expect(diagnostics).toHaveBeenLastCalledWith(
expect.objectContaining({
phase: "failure",
error: {
name: "Error",
message: "failed for [redacted] [redacted] [redacted] [redacted] [redacted]",
},
}),
);
});
it("maps monthly feature limits to accumulated seeded features", async () => {
const client = createSeedClient(null);
const monthlyFeature = singlePlan.features.find((feature) => feature.limitType === entitlementLimitTypes.monthly)!;
await seedStandardEntitlements({ client, plans: [{ ...singlePlan, features: [monthlyFeature] }] });
expect(client.subscriptionFeature.create).toHaveBeenCalledWith({
data: expect.objectContaining({
name: monthlyFeature.featureKey,
type: entitlementLimitTypes.monthly,
value: monthlyFeature.limit,
accumulate: true,
}),
});
});
it("redacts standalone seed errors", () => {
expect(redactSeedError("Stripe secret sk_live_123 for prod_abc")).toEqual({
name: "Error",
message: "Stripe secret [redacted] for [redacted]",
});
});
});
@@ -0,0 +1,237 @@
import {
assertKnownFeatureKey,
getFeatureGate,
standardEntitlementPlans,
type EntitlementLimitType,
type EntitlementPlanStub,
type FeatureKey,
} from "@toolctrl/entitlements";
import { getDbClient } from "./client.server.js";
import type { SubscriptionFeature, SubscriptionProduct } from "./prisma-browser.js";
import type { SubscriptionFeatureCreateInput, SubscriptionProductCreateInput, SubscriptionProductUpdateInput } from "./subscriptions.server.js";
const SEEDED_STRIPE_ID_PREFIX = "toolctrl_entitlement_plan";
const REDACTED = "[redacted]";
export type EntitlementsSeedPhase = "start" | "plan-seeded" | "success" | "failure";
export type EntitlementsSeedDiagnosticEvent = {
phase: EntitlementsSeedPhase;
planCount: number;
featureCount: number;
createdProducts: number;
updatedProducts: number;
deletedFeatures: number;
createdFeatures: number;
planId?: string;
error?: {
name: string;
message: string;
};
};
export type EntitlementsSeedDiagnostics = (event: EntitlementsSeedDiagnosticEvent) => void | Promise<void>;
export type EntitlementsSeedResult = {
planCount: number;
featureCount: number;
createdProducts: number;
updatedProducts: number;
deletedFeatures: number;
createdFeatures: number;
};
export type EntitlementsSeedSubscriptionProductClient = {
findFirst(args: { where: { OR: [{ stripeId: string }, { title: string }] } }): Promise<Pick<SubscriptionProduct, "id"> | null>;
create(args: { data: SubscriptionProductCreateInput }): Promise<Pick<SubscriptionProduct, "id">>;
update(args: { where: { id: string }; data: SubscriptionProductUpdateInput }): Promise<Pick<SubscriptionProduct, "id">>;
};
export type EntitlementsSeedSubscriptionFeatureClient = {
deleteMany(args: { where: { subscriptionProductId: string } }): Promise<{ count: number }>;
create(args: { data: SubscriptionFeatureCreateInput & { subscriptionProductId: string } }): Promise<SubscriptionFeature>;
};
export type EntitlementsSeedClient = {
subscriptionProduct: EntitlementsSeedSubscriptionProductClient;
subscriptionFeature: EntitlementsSeedSubscriptionFeatureClient;
};
export type SeedStandardEntitlementsOptions = {
client?: EntitlementsSeedClient;
plans?: readonly EntitlementPlanStub[];
diagnostics?: EntitlementsSeedDiagnostics;
};
function getInitialResult(plans: readonly EntitlementPlanStub[]): EntitlementsSeedResult {
return {
planCount: plans.length,
featureCount: plans.reduce((total, plan) => total + plan.features.length, 0),
createdProducts: 0,
updatedProducts: 0,
deletedFeatures: 0,
createdFeatures: 0,
};
}
function diagnosticFromResult(phase: EntitlementsSeedPhase, result: EntitlementsSeedResult, planId?: string): EntitlementsSeedDiagnosticEvent {
return {
phase,
planCount: result.planCount,
featureCount: result.featureCount,
createdProducts: result.createdProducts,
updatedProducts: result.updatedProducts,
deletedFeatures: result.deletedFeatures,
createdFeatures: result.createdFeatures,
...(planId ? { planId } : {}),
};
}
async function emitDiagnostic(diagnostics: EntitlementsSeedDiagnostics | undefined, event: EntitlementsSeedDiagnosticEvent): Promise<void> {
await diagnostics?.(event);
}
export function getEntitlementPlanStripeId(plan: Pick<EntitlementPlanStub, "id">): string {
return `${SEEDED_STRIPE_ID_PREFIX}_${plan.id}`;
}
function mapPlanToProductCreateInput(plan: EntitlementPlanStub): SubscriptionProductCreateInput {
return {
stripeId: getEntitlementPlanStripeId(plan),
order: plan.metadata.sortOrder,
title: plan.metadata.publicName,
model: 0,
public: plan.metadata.isPublic,
active: true,
description: plan.metadata.description,
badge: null,
groupTitle: null,
groupDescription: null,
billingAddressCollection: "auto",
hasQuantity: false,
canBuyAgain: false,
};
}
function mapPlanToProductUpdateInput(plan: EntitlementPlanStub): SubscriptionProductUpdateInput {
const product = mapPlanToProductCreateInput(plan);
return {
stripeId: product.stripeId,
order: product.order,
title: product.title,
model: product.model,
public: product.public,
description: product.description,
badge: product.badge,
groupTitle: product.groupTitle,
groupDescription: product.groupDescription,
billingAddressCollection: product.billingAddressCollection,
hasQuantity: product.hasQuantity,
canBuyAgain: product.canBuyAgain,
};
}
function getFeatureValue(limitType: EntitlementLimitType, limit: number | null): number {
return limit ?? limitType;
}
function mapPlanFeatureToCreateInput(feature: EntitlementPlanStub["features"][number]): SubscriptionFeatureCreateInput {
assertKnownFeatureKey(feature.featureKey);
const registryItem = getFeatureGate(feature.featureKey as FeatureKey);
if (!registryItem) {
throw new RangeError(`Unknown feature key: ${feature.featureKey}`);
}
return {
order: feature.order,
title: feature.label,
name: feature.featureKey,
type: feature.limitType,
value: getFeatureValue(feature.limitType, feature.limit),
href: null,
badge: registryItem.title,
accumulate: feature.limitType === 2,
};
}
function redactMessage(value: string): string {
return value
.replace(/\b(?:prod|price|sub|cus|tenant|user|acct|sk|pk|rk|cs|plan)_[A-Za-z0-9_-]+\b/g, REDACTED)
.replace(/postgres(?:ql)?:\/\/\S+/gi, REDACTED)
.replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, REDACTED);
}
export function redactSeedError(error: unknown): { name: string; message: string } {
if (error instanceof Error) {
return {
name: error.name || "Error",
message: redactMessage(error.message),
};
}
return {
name: "Error",
message: redactMessage(String(error)),
};
}
async function seedOnePlan(client: EntitlementsSeedClient, plan: EntitlementPlanStub): Promise<Omit<EntitlementsSeedResult, "planCount" | "featureCount">> {
const productData = mapPlanToProductCreateInput(plan);
const existingProduct = await client.subscriptionProduct.findFirst({
where: { OR: [{ stripeId: productData.stripeId }, { title: productData.title }] },
});
const product = existingProduct
? await client.subscriptionProduct.update({
where: { id: existingProduct.id },
data: mapPlanToProductUpdateInput(plan),
})
: await client.subscriptionProduct.create({ data: productData });
const deletedFeatures = await client.subscriptionFeature.deleteMany({ where: { subscriptionProductId: product.id } });
for (const feature of plan.features) {
await client.subscriptionFeature.create({
data: {
subscriptionProductId: product.id,
...mapPlanFeatureToCreateInput(feature),
},
});
}
return {
createdProducts: existingProduct ? 0 : 1,
updatedProducts: existingProduct ? 1 : 0,
deletedFeatures: deletedFeatures.count,
createdFeatures: plan.features.length,
};
}
export async function seedStandardEntitlements({
client = getDbClient(),
plans = standardEntitlementPlans,
diagnostics,
}: SeedStandardEntitlementsOptions = {}): Promise<EntitlementsSeedResult> {
const result = getInitialResult(plans);
await emitDiagnostic(diagnostics, diagnosticFromResult("start", result));
try {
for (const plan of plans) {
const planResult = await seedOnePlan(client, plan);
result.createdProducts += planResult.createdProducts;
result.updatedProducts += planResult.updatedProducts;
result.deletedFeatures += planResult.deletedFeatures;
result.createdFeatures += planResult.createdFeatures;
await emitDiagnostic(diagnostics, diagnosticFromResult("plan-seeded", result, plan.id));
}
await emitDiagnostic(diagnostics, diagnosticFromResult("success", result));
return result;
} catch (error) {
await emitDiagnostic(diagnostics, {
...diagnosticFromResult("failure", result),
error: redactSeedError(error),
});
throw error;
}
}
@@ -0,0 +1,62 @@
import { describe, expect, it, vi } from "vitest";
import {
findLegacyEventWebhookAttemptById,
updateLegacyEventWebhookAttempt,
type LegacyEventWebhookAttemptClient,
} from "./event-webhook-attempts.server.js";
describe("legacy event webhook attempt helpers", () => {
it("loads attempts with their tenant scope", async () => {
const findUnique = vi.fn().mockResolvedValue({
id: "attempt_1",
endpoint: "https://example.test/webhook",
event: { tenantId: "tenant_1" },
});
const client = createClient({ findUnique });
await expect(findLegacyEventWebhookAttemptById("attempt_1", client)).resolves.toEqual({
id: "attempt_1",
endpoint: "https://example.test/webhook",
tenantId: "tenant_1",
});
expect(findUnique).toHaveBeenCalledWith({
where: { id: "attempt_1" },
select: { id: true, endpoint: true, event: { select: { tenantId: true } } },
});
});
it("updates attempts through id and tenant scope", async () => {
const updateMany = vi.fn().mockResolvedValue({ count: 1 });
const client = createClient({ updateMany });
const finishedAt = new Date("2026-01-01T00:00:00.000Z");
await updateLegacyEventWebhookAttempt({ id: "attempt_1", tenantId: "tenant_1" }, { finishedAt, success: true }, client);
expect(updateMany).toHaveBeenCalledWith({
where: { id: "attempt_1", event: { tenantId: "tenant_1" } },
data: { finishedAt, success: true },
});
});
it("throws when scoped attempt update does not match one row", async () => {
const client = createClient({ updateMany: vi.fn().mockResolvedValue({ count: 0 }) });
await expect(updateLegacyEventWebhookAttempt({ id: "missing", tenantId: "tenant_1" }, { success: false }, client)).rejects.toThrow("Event webhook attempt missing not found");
});
});
function createClient({
findUnique = vi.fn().mockResolvedValue(null),
updateMany = vi.fn().mockResolvedValue({ count: 0 }),
}: {
findUnique?: ReturnType<typeof vi.fn>;
updateMany?: ReturnType<typeof vi.fn>;
} = {}): LegacyEventWebhookAttemptClient {
return {
eventWebhookAttempt: {
findUnique,
updateMany,
},
} as unknown as LegacyEventWebhookAttemptClient;
}
@@ -0,0 +1,58 @@
import { getDbClient } from "./client.server.js";
export type LegacyEventWebhookAttempt = {
id: string;
endpoint: string;
tenantId: string | null;
};
export type LegacyEventWebhookAttemptUpdate = {
startedAt?: Date;
finishedAt?: Date;
success?: boolean;
status?: number;
message?: string;
body?: string;
};
export type LegacyEventWebhookAttemptClient = {
eventWebhookAttempt: {
findUnique(args: {
where: { id: string };
select: { id: true; endpoint: true; event: { select: { tenantId: true } } };
}): Promise<{ id: string; endpoint: string; event: { tenantId: string | null } } | null>;
updateMany(args: {
where: { id: string; event: { tenantId: string | null } };
data: LegacyEventWebhookAttemptUpdate;
}): Promise<{ count: number }>;
};
};
export async function findLegacyEventWebhookAttemptById(
id: string,
client: LegacyEventWebhookAttemptClient = getDbClient(),
): Promise<LegacyEventWebhookAttempt | null> {
const attempt = await client.eventWebhookAttempt.findUnique({
where: { id },
select: {
id: true,
endpoint: true,
event: { select: { tenantId: true } },
},
});
return attempt ? { id: attempt.id, endpoint: attempt.endpoint, tenantId: attempt.event.tenantId } : null;
}
export async function updateLegacyEventWebhookAttempt(
{ id, tenantId }: { id: string; tenantId: string | null },
data: LegacyEventWebhookAttemptUpdate,
client: LegacyEventWebhookAttemptClient = getDbClient(),
): Promise<void> {
const updated = await client.eventWebhookAttempt.updateMany({
where: { id, event: { tenantId } },
data,
});
if (updated.count !== 1) {
throw new Error(`Event webhook attempt ${id} not found`);
}
}
@@ -0,0 +1,23 @@
import { getDbClient } from "./client.server.js";
import type { Event } from "./prisma-browser.js";
export type LegacyEventCreateData = {
tenantId: string | null;
userId: string | null;
name: string;
data: string;
description: string | null;
};
export type LegacyEventWriterClient = {
event: {
create(args: { data: LegacyEventCreateData }): Promise<Event>;
};
};
export async function createLegacyEvent(
data: LegacyEventCreateData,
client: LegacyEventWriterClient = getDbClient() as unknown as LegacyEventWriterClient,
): Promise<Event> {
return client.event.create({ data });
}
@@ -0,0 +1,521 @@
import { describe, expect, it, vi } from "vitest";
import {
EXPORT_JOB_ERROR_MESSAGE_MAX_LENGTH,
EXPORT_JOB_RETENTION_DEFAULT_TAKE,
EXPORT_JOB_RETENTION_MAX_TAKE,
createExportJob,
findExportJobForDownload,
listExpiredCompletedExportJobs,
markExportJobExpired,
markExportJobFailed,
markExportJobPaused,
markExportJobResumed,
markExportJobRunning,
markExportJobSucceeded,
type ExportJobDownloadRecord,
type ExportJobReaderClient,
type ExportJobRetentionReaderClient,
type ExportJobRetentionRecord,
type ExportJobWriterClient,
} from "./export-jobs.server.js";
function createExportJobClient(): ExportJobWriterClient {
return {
exportJob: {
create: vi.fn().mockResolvedValue({ id: "export_job_1" }),
update: vi.fn().mockResolvedValue({ id: "export_job_1" }),
updateMany: vi.fn().mockResolvedValue({ count: 1 }),
},
};
}
function createExportJobReader(record: ExportJobDownloadRecord | null): ExportJobReaderClient {
return {
exportJob: {
findFirst: vi.fn().mockResolvedValue(record),
},
};
}
function createExportJobRetentionReader(records: ExportJobRetentionRecord[]): ExportJobRetentionReaderClient {
return {
exportJob: {
findMany: vi.fn().mockResolvedValue(records),
},
};
}
describe("export job download lookups", () => {
it("finds completed export jobs with scalar download fields only", async () => {
const expiresAt = new Date("2026-05-10T14:00:00.000Z");
const record: ExportJobDownloadRecord = {
id: "export_job_1",
tenantId: "tenant_1",
requestedByUserId: "user_1",
format: "csv",
status: "COMPLETED",
artifactBucket: "exports",
artifactKey: "tenant_1/members.csv",
rowCount: 42,
expiresAt,
deletedAt: null,
hardDeletedAt: null,
errorName: null,
requestId: "request_1",
};
const client = createExportJobReader(record);
await expect(
findExportJobForDownload({ id: "export_job_1", tenantId: "tenant_1" }, client),
).resolves.toEqual(record);
expect(client.exportJob.findFirst).toHaveBeenCalledWith({
where: { id: "export_job_1", tenantId: "tenant_1" },
select: {
id: true,
tenantId: true,
requestedByUserId: true,
format: true,
status: true,
artifactBucket: true,
artifactKey: true,
rowCount: true,
expiresAt: true,
deletedAt: true,
hardDeletedAt: true,
errorName: true,
requestId: true,
},
});
expect(JSON.stringify(vi.mocked(client.exportJob.findFirst).mock.calls[0]?.[0])).not.toContain("payload");
expect(JSON.stringify(vi.mocked(client.exportJob.findFirst).mock.calls[0]?.[0])).not.toContain("filter");
expect(JSON.stringify(vi.mocked(client.exportJob.findFirst).mock.calls[0]?.[0])).not.toContain("body");
});
it("rejects download lookups without tenant scope", async () => {
const client = createExportJobReader(null);
await expect(
findExportJobForDownload({ id: "export_job_1", tenantId: " " }, client),
).rejects.toThrow("Export job download tenant scope is required.");
expect(client.exportJob.findFirst).not.toHaveBeenCalled();
});
it("returns null for missing export jobs", async () => {
const client = createExportJobReader(null);
await expect(
findExportJobForDownload({ id: "missing_export_job", tenantId: "tenant_1" }, client),
).resolves.toBeNull();
});
it("returns missing artifact fields as caller-checkable scalar state", async () => {
const record: ExportJobDownloadRecord = {
id: "export_job_1",
tenantId: "tenant_1",
requestedByUserId: null,
format: "csv",
status: "COMPLETED",
artifactBucket: null,
artifactKey: null,
rowCount: null,
expiresAt: null,
deletedAt: null,
hardDeletedAt: null,
errorName: null,
requestId: "request_1",
};
const client = createExportJobReader(record);
await expect(findExportJobForDownload({ id: "export_job_1", tenantId: "tenant_1" }, client)).resolves.toEqual(record);
});
it("returns expired and non-completed records as caller-checkable scalar states", async () => {
const expiresAt = new Date("2026-05-01T00:00:00.000Z");
const record: ExportJobDownloadRecord = {
id: "export_job_1",
tenantId: "tenant_1",
requestedByUserId: "user_1",
format: "csv",
status: "FAILED",
artifactBucket: "exports",
artifactKey: "tenant_1/members.csv",
rowCount: 42,
expiresAt,
deletedAt: null,
hardDeletedAt: null,
errorName: "ExportPaused",
requestId: "request_1",
};
const client = createExportJobReader(record);
await expect(findExportJobForDownload({ id: "export_job_1", tenantId: "tenant_1" }, client)).resolves.toEqual(record);
});
});
describe("export job retention lookups", () => {
it("lists only expired completed jobs with artifact summary fields", async () => {
const now = new Date("2026-05-11T00:00:00.000Z");
const expiresAt = new Date("2026-05-10T00:00:00.000Z");
const record: ExportJobRetentionRecord = {
id: "export_job_1",
tenantId: "tenant_1",
status: "COMPLETED",
artifactBucket: "exports",
artifactKey: "tenant_1/members.csv",
rowCount: 42,
expiresAt,
requestId: "request_1",
};
const client = createExportJobRetentionReader([record]);
await expect(listExpiredCompletedExportJobs({ now, take: 25 }, client)).resolves.toEqual([record]);
const findManyCall = vi.mocked(client.exportJob.findMany).mock.calls[0]?.[0];
expect(findManyCall).toEqual({
where: {
status: "COMPLETED",
expiresAt: { not: null, lte: now },
artifactBucket: { not: null },
artifactKey: { not: null },
rowCount: { not: null },
},
orderBy: [{ expiresAt: "asc" }, { id: "asc" }],
take: 25,
select: {
id: true,
tenantId: true,
status: true,
artifactBucket: true,
artifactKey: true,
rowCount: true,
expiresAt: true,
requestId: true,
},
});
expect(JSON.stringify(findManyCall)).not.toContain("payload");
expect(JSON.stringify(findManyCall)).not.toContain("body");
});
it("uses the default take for invalid or omitted bounds", async () => {
const client = createExportJobRetentionReader([]);
await listExpiredCompletedExportJobs({ now: new Date("2026-05-11T00:00:00.000Z") }, client);
expect(vi.mocked(client.exportJob.findMany).mock.calls[0]?.[0].take).toBe(EXPORT_JOB_RETENTION_DEFAULT_TAKE);
});
it("caps and floors take to the safe retention bounds", async () => {
const client = createExportJobRetentionReader([]);
const now = new Date("2026-05-11T00:00:00.000Z");
await listExpiredCompletedExportJobs({ now, take: EXPORT_JOB_RETENTION_MAX_TAKE + 1 }, client);
await listExpiredCompletedExportJobs({ now, take: 0 }, client);
await listExpiredCompletedExportJobs({ now, take: 1.9 }, client);
expect(vi.mocked(client.exportJob.findMany).mock.calls[0]?.[0].take).toBe(EXPORT_JOB_RETENTION_MAX_TAKE);
expect(vi.mocked(client.exportJob.findMany).mock.calls[1]?.[0].take).toBe(1);
expect(vi.mocked(client.exportJob.findMany).mock.calls[2]?.[0].take).toBe(1);
});
});
describe("export job writes", () => {
it("creates pending export jobs with nullable lifecycle and artifact fields", async () => {
const client = createExportJobClient();
const expiresAt = new Date("2026-05-09T12:00:00.000Z");
await createExportJob(
{
tenantId: "tenant_1",
requestedByUserId: "user_1",
exportType: "members",
format: "csv",
requestId: "request_1",
attemptsMade: null,
expiresAt,
},
client,
);
expect(client.exportJob.create).toHaveBeenCalledWith({
data: {
tenantId: "tenant_1",
requestedByUserId: "user_1",
exportType: "members",
format: "csv",
status: "PENDING",
requestId: "request_1",
attemptsMade: 0,
artifactBucket: null,
artifactKey: null,
rowCount: null,
errorName: null,
errorMessage: null,
retentionErrorMessage: null,
expiresAt,
deletedAt: null,
hardDeletedAt: null,
startedAt: null,
finishedAt: null,
},
});
});
it("marks export jobs running with attempt count and start timestamp", async () => {
const client = createExportJobClient();
const startedAt = new Date("2026-05-09T13:00:00.000Z");
await markExportJobRunning(
{
id: "export_job_1",
tenantId: "tenant_1",
attemptsMade: 2,
startedAt,
},
client,
);
expect(client.exportJob.updateMany).toHaveBeenCalledWith({
where: { id: "export_job_1", tenantId: "tenant_1" },
data: {
status: "RUNNING",
attemptsMade: 2,
artifactBucket: null,
artifactKey: null,
rowCount: null,
errorName: null,
errorMessage: null,
retentionErrorMessage: null,
deletedAt: null,
hardDeletedAt: null,
startedAt,
finishedAt: null,
},
});
});
it("marks export jobs completed with artifact summary fields", async () => {
const client = createExportJobClient();
const finishedAt = new Date("2026-05-09T14:00:00.000Z");
const expiresAt = new Date("2026-05-10T14:00:00.000Z");
await markExportJobSucceeded(
{
id: "export_job_1",
tenantId: "tenant_1",
artifactBucket: "exports",
artifactKey: "tenant_1/members.csv",
rowCount: 42,
attemptsMade: 3,
finishedAt,
expiresAt,
},
client,
);
expect(client.exportJob.updateMany).toHaveBeenCalledWith({
where: { id: "export_job_1", tenantId: "tenant_1" },
data: {
status: "COMPLETED",
attemptsMade: 3,
artifactBucket: "exports",
artifactKey: "tenant_1/members.csv",
rowCount: 42,
errorName: null,
errorMessage: null,
retentionErrorMessage: null,
expiresAt,
deletedAt: null,
hardDeletedAt: null,
finishedAt,
},
});
});
it("marks export jobs failed with scalar diagnostics and ignores payload-like inputs", async () => {
const client = createExportJobClient();
const finishedAt = new Date("2026-05-09T15:00:00.000Z");
await markExportJobFailed(
{
id: "export_job_1",
tenantId: "tenant_1",
attemptsMade: 4,
errorName: "ExportError",
errorMessage: "S3 denied token=secret-token Authorization=Bearer secret",
finishedAt,
payload: { secret: "secret-payload" },
headers: { authorization: "Bearer secret" },
body: "secret-body",
} as Parameters<typeof markExportJobFailed>[0] & Record<string, unknown>,
client,
);
const updateCall = vi.mocked(client.exportJob.updateMany).mock.calls[0]?.[0];
expect(updateCall).toEqual({
where: { id: "export_job_1", tenantId: "tenant_1" },
data: {
status: "FAILED",
attemptsMade: 4,
artifactBucket: null,
artifactKey: null,
rowCount: null,
errorName: "ExportError",
errorMessage: "S3 denied token=[REDACTED] Authorization=Bearer [REDACTED]",
finishedAt,
},
});
expect(JSON.stringify(updateCall)).not.toContain("secret-payload");
expect(JSON.stringify(updateCall)).not.toContain("secret-token");
expect(JSON.stringify(updateCall)).not.toContain("authorization");
expect(JSON.stringify(updateCall)).not.toContain("secret-body");
});
it("truncates oversized failure messages before writing", async () => {
const client = createExportJobClient();
const oversizedMessage = "x".repeat(EXPORT_JOB_ERROR_MESSAGE_MAX_LENGTH + 100);
await markExportJobFailed(
{
id: "export_job_2",
tenantId: "tenant_1",
attemptsMade: 5,
errorName: "RangeError",
errorMessage: oversizedMessage,
},
client,
);
const updateCall = vi.mocked(client.exportJob.updateMany).mock.calls[0]?.[0];
expect(updateCall?.data.errorMessage).toHaveLength(EXPORT_JOB_ERROR_MESSAGE_MAX_LENGTH);
});
it("marks export jobs paused as pending with redacted scalar diagnostics", async () => {
const client = createExportJobClient();
await markExportJobPaused(
{
id: "export_job_1",
tenantId: "tenant_1",
attemptsMade: 6,
reason: "Tenant hold active token=secret-token",
payload: { filters: { email: "person@example.com" } },
headers: { authorization: "Bearer secret" },
body: "secret-body",
} as Parameters<typeof markExportJobPaused>[0] & Record<string, unknown>,
client,
);
const updateCall = vi.mocked(client.exportJob.updateMany).mock.calls[0]?.[0];
expect(updateCall).toEqual({
where: { id: "export_job_1", tenantId: "tenant_1" },
data: {
status: "PENDING",
attemptsMade: 6,
artifactBucket: null,
artifactKey: null,
rowCount: null,
errorName: "ExportPaused",
errorMessage: "Tenant hold active token=[REDACTED]",
retentionErrorMessage: null,
expiresAt: null,
deletedAt: null,
hardDeletedAt: null,
startedAt: null,
finishedAt: null,
},
});
expect(JSON.stringify(updateCall)).not.toContain("secret-token");
expect(JSON.stringify(updateCall)).not.toContain("person@example.com");
expect(JSON.stringify(updateCall)).not.toContain("authorization");
expect(JSON.stringify(updateCall)).not.toContain("secret-body");
});
it("truncates oversized pause reasons before writing", async () => {
const client = createExportJobClient();
const oversizedReason = "pause-".repeat(EXPORT_JOB_ERROR_MESSAGE_MAX_LENGTH);
await markExportJobPaused(
{
id: "export_job_2",
tenantId: "tenant_1",
reason: oversizedReason,
},
client,
);
const updateCall = vi.mocked(client.exportJob.updateMany).mock.calls[0]?.[0];
expect(updateCall?.data.errorMessage).toHaveLength(EXPORT_JOB_ERROR_MESSAGE_MAX_LENGTH);
});
it("marks export jobs resumed by clearing pause diagnostics and artifact fields", async () => {
const client = createExportJobClient();
await markExportJobResumed(
{
id: "export_job_1",
tenantId: "tenant_1",
attemptsMade: 7,
payload: { filters: { role: "admin" } },
body: "secret-body",
} as Parameters<typeof markExportJobResumed>[0] & Record<string, unknown>,
client,
);
const updateCall = vi.mocked(client.exportJob.updateMany).mock.calls[0]?.[0];
expect(updateCall).toEqual({
where: { id: "export_job_1", tenantId: "tenant_1" },
data: {
status: "PENDING",
attemptsMade: 7,
artifactBucket: null,
artifactKey: null,
rowCount: null,
errorName: null,
errorMessage: null,
retentionErrorMessage: null,
expiresAt: null,
deletedAt: null,
hardDeletedAt: null,
startedAt: null,
finishedAt: null,
},
});
expect(JSON.stringify(updateCall)).not.toContain("filters");
expect(JSON.stringify(updateCall)).not.toContain("secret-body");
});
it("marks export jobs expired with scalar retention diagnostics", async () => {
const client = createExportJobClient();
const deletedAt = new Date("2026-05-11T01:00:00.000Z");
await markExportJobExpired(
{
id: "export_job_1",
tenantId: "tenant_1",
deletedAt,
artifactBucket: "secret-bucket",
artifactKey: "tenant_1/secret.csv",
} as Parameters<typeof markExportJobExpired>[0] & Record<string, unknown>,
client,
);
const updateCall = vi.mocked(client.exportJob.updateMany).mock.calls[0]?.[0];
expect(updateCall).toEqual({
where: { id: "export_job_1", tenantId: "tenant_1" },
data: {
status: "FAILED",
errorName: "ExportRetentionExpired",
errorMessage: "Export artifact expired by retention policy.",
retentionErrorMessage: null,
deletedAt,
hardDeletedAt: null,
finishedAt: deletedAt,
},
});
expect(JSON.stringify(updateCall)).not.toContain("secret-bucket");
expect(JSON.stringify(updateCall)).not.toContain("secret.csv");
});
});
@@ -0,0 +1,570 @@
import { getDbClient, type DbClient } from "./client.server.js";
export const EXPORT_JOB_ERROR_MESSAGE_MAX_LENGTH = 2_000;
export const EXPORT_JOB_RETENTION_ERROR_MESSAGE_MAX_LENGTH = 2_000;
export const EXPORT_JOB_RETENTION_DEFAULT_TAKE = 100;
export const EXPORT_JOB_RETENTION_MAX_TAKE = 500;
export type ExportJobStatus = "PENDING" | "RUNNING" | "COMPLETED" | "FAILED";
export type ExportJobCreateInput = {
tenantId: string;
requestedByUserId?: string | null;
exportType: string;
format: string;
requestId: string;
attemptsMade?: number | null;
expiresAt?: Date | null;
};
export type ExportJobRunningInput = {
id: string;
tenantId: string;
attemptsMade: number;
startedAt?: Date | null;
};
export type ExportJobSucceededInput = {
id: string;
tenantId: string;
artifactBucket: string;
artifactKey: string;
rowCount: number;
attemptsMade?: number | null;
finishedAt?: Date | null;
expiresAt?: Date | null;
};
export type ExportJobFailedInput = {
id: string;
tenantId: string;
attemptsMade: number;
errorName?: string | null;
errorMessage?: string | null;
finishedAt?: Date | null;
};
export type ExportJobPausedInput = {
id: string;
tenantId: string;
attemptsMade?: number | null;
reason?: string | null;
};
export type ExportJobResumedInput = {
id: string;
tenantId: string;
attemptsMade?: number | null;
};
export type ExportJobDownloadRecord = {
id: string;
tenantId: string;
requestedByUserId: string | null;
format: string;
status: ExportJobStatus;
artifactBucket: string | null;
artifactKey: string | null;
rowCount: number | null;
expiresAt: Date | null;
deletedAt?: Date | null;
hardDeletedAt?: Date | null;
errorName: string | null;
requestId: string;
};
export type ExportJobDownloadLookupInput = {
id: string;
tenantId: string;
};
export type ExportJobRetentionRecord = {
id: string;
tenantId: string;
status: ExportJobStatus;
artifactBucket: string;
artifactKey: string;
rowCount: number | null;
expiresAt: Date | null;
deletedAt?: Date | null;
requestId: string;
};
export type ExportJobRetentionListInput = {
now: Date;
take?: number | null;
};
export type ExportJobExpiredInput = {
id: string;
tenantId: string;
deletedAt?: Date | null;
};
export type ExportJobHardDeleteSucceededInput = {
id: string;
tenantId: string;
hardDeletedAt?: Date | null;
};
export type ExportJobHardDeleteFailedInput = {
id: string;
tenantId: string;
errorMessage?: string | null;
};
type ExportJobCreateData = {
tenantId: string;
requestedByUserId: string | null;
exportType: string;
format: string;
status: Extract<ExportJobStatus, "PENDING">;
requestId: string;
attemptsMade: number;
artifactBucket: null;
artifactKey: null;
rowCount: null;
errorName: null;
errorMessage: null;
retentionErrorMessage: null;
expiresAt: Date | null;
deletedAt: null;
hardDeletedAt: null;
startedAt: null;
finishedAt: null;
};
type ExportJobUpdateData = Partial<{
status: ExportJobStatus;
attemptsMade: number;
artifactBucket: string | null;
artifactKey: string | null;
rowCount: number | null;
errorName: string | null;
errorMessage: string | null;
retentionErrorMessage: string | null;
expiresAt: Date | null;
deletedAt: Date | null;
hardDeletedAt: Date | null;
startedAt: Date | null;
finishedAt: Date | null;
}>;
export type ExportJobWriterClient = {
exportJob: {
create(args: { data: ExportJobCreateData }): Promise<unknown>;
update(args: { where: { id: string }; data: ExportJobUpdateData }): Promise<unknown>;
updateMany(args: { where: { id: string; tenantId: string }; data: ExportJobUpdateData }): Promise<{ count?: number }>;
};
};
export type ExportJobReaderClient = {
exportJob: {
findFirst(args: {
where: { id: string; tenantId?: string };
select: {
id: true;
tenantId: true;
requestedByUserId: true;
format: true;
status: true;
artifactBucket: true;
artifactKey: true;
rowCount: true;
expiresAt: true;
deletedAt: true;
hardDeletedAt: true;
errorName: true;
requestId: true;
};
}): Promise<ExportJobDownloadRecord | null>;
};
};
export type ExportJobRetentionReaderClient = {
exportJob: {
findMany(args: {
where:
| {
status: Extract<ExportJobStatus, "COMPLETED">;
expiresAt: { not: null; lte: Date };
artifactBucket: { not: null };
artifactKey: { not: null };
rowCount: { not: null };
}
| {
status: Extract<ExportJobStatus, "FAILED">;
deletedAt: { not: null; lte: Date };
hardDeletedAt: null;
artifactBucket: { not: null };
artifactKey: { not: null };
};
orderBy: [{ expiresAt: "asc" }, { id: "asc" }] | [{ deletedAt: "asc" }, { id: "asc" }];
take: number;
select: {
id: true;
tenantId: true;
status: true;
artifactBucket: true;
artifactKey: true;
rowCount: true;
expiresAt: true;
deletedAt?: true;
requestId: true;
};
}): Promise<ExportJobRetentionRecord[]>;
};
};
function normalizeAttemptsMade(attemptsMade?: number | null): number {
return attemptsMade ?? 0;
}
function truncateErrorMessage(errorMessage: string): string {
if (errorMessage.length <= EXPORT_JOB_ERROR_MESSAGE_MAX_LENGTH) {
return errorMessage;
}
return errorMessage.slice(0, EXPORT_JOB_ERROR_MESSAGE_MAX_LENGTH);
}
function redactExportErrorMessage(errorMessage: string): string {
return truncateErrorMessage(redactDiagnosticText(errorMessage));
}
function redactDiagnosticText(value: string): string {
return value
.replace(/(authorization)\s*=\s*Bearer\s+\S+/gi, "$1=Bearer [REDACTED]")
.replace(/Bearer\s+\S+/gi, "Bearer [REDACTED]")
.replace(/(password|secret|token|api[-_]?key)=\S+/gi, "$1=[REDACTED]");
}
function redactExportPauseReason(reason: string): string {
return truncateErrorMessage(redactDiagnosticText(reason));
}
function redactRetentionErrorMessage(errorMessage: string): string {
const redacted = redactDiagnosticText(errorMessage);
if (redacted.length <= EXPORT_JOB_RETENTION_ERROR_MESSAGE_MAX_LENGTH) {
return redacted;
}
return redacted.slice(0, EXPORT_JOB_RETENTION_ERROR_MESSAGE_MAX_LENGTH);
}
function normalizeRetentionTake(take?: number | null): number {
if (typeof take !== "number" || !Number.isFinite(take)) {
return EXPORT_JOB_RETENTION_DEFAULT_TAKE;
}
return Math.max(1, Math.min(EXPORT_JOB_RETENTION_MAX_TAKE, Math.floor(take)));
}
async function updateExportJobForTenant(
client: ExportJobWriterClient,
data: { id: string; tenantId: string; update: ExportJobUpdateData },
): Promise<unknown> {
const id = data.id.trim();
const tenantId = data.tenantId.trim();
if (!id || !tenantId) {
throw new Error("Export job tenant scope is required.");
}
const result = await client.exportJob.updateMany({
where: { id, tenantId },
data: data.update,
});
if (typeof result.count === "number" && result.count !== 1) {
throw new Error("Export job tenant scope did not match exactly one job.");
}
return result;
}
export async function findExportJobForDownload(
data: ExportJobDownloadLookupInput,
client: ExportJobReaderClient = getDbClient() as DbClient & ExportJobReaderClient,
): Promise<ExportJobDownloadRecord | null> {
const id = data.id.trim();
const tenantId = data.tenantId.trim();
if (!id || !tenantId) {
throw new Error("Export job download tenant scope is required.");
}
return client.exportJob.findFirst({
where: {
id,
tenantId,
},
select: {
id: true,
tenantId: true,
requestedByUserId: true,
format: true,
status: true,
artifactBucket: true,
artifactKey: true,
rowCount: true,
expiresAt: true,
deletedAt: true,
hardDeletedAt: true,
errorName: true,
requestId: true,
},
});
}
export async function listSoftDeletedExportJobsForHardDelete(
data: ExportJobRetentionListInput,
client: ExportJobRetentionReaderClient = getDbClient() as DbClient & ExportJobRetentionReaderClient,
): Promise<ExportJobRetentionRecord[]> {
return client.exportJob.findMany({
where: {
status: "FAILED",
deletedAt: { not: null, lte: data.now },
hardDeletedAt: null,
artifactBucket: { not: null },
artifactKey: { not: null },
},
orderBy: [{ deletedAt: "asc" }, { id: "asc" }],
take: normalizeRetentionTake(data.take),
select: {
id: true,
tenantId: true,
status: true,
artifactBucket: true,
artifactKey: true,
rowCount: true,
expiresAt: true,
deletedAt: true,
requestId: true,
},
});
}
export async function listExpiredCompletedExportJobs(
data: ExportJobRetentionListInput,
client: ExportJobRetentionReaderClient = getDbClient() as DbClient & ExportJobRetentionReaderClient,
): Promise<ExportJobRetentionRecord[]> {
return client.exportJob.findMany({
where: {
status: "COMPLETED",
expiresAt: { not: null, lte: data.now },
artifactBucket: { not: null },
artifactKey: { not: null },
rowCount: { not: null },
},
orderBy: [{ expiresAt: "asc" }, { id: "asc" }],
take: normalizeRetentionTake(data.take),
select: {
id: true,
tenantId: true,
status: true,
artifactBucket: true,
artifactKey: true,
rowCount: true,
expiresAt: true,
requestId: true,
},
});
}
export async function createExportJob(
data: ExportJobCreateInput,
client: ExportJobWriterClient = getDbClient() as DbClient & ExportJobWriterClient,
): Promise<unknown> {
return client.exportJob.create({
data: {
tenantId: data.tenantId,
requestedByUserId: data.requestedByUserId ?? null,
exportType: data.exportType,
format: data.format,
status: "PENDING",
requestId: data.requestId,
attemptsMade: normalizeAttemptsMade(data.attemptsMade),
artifactBucket: null,
artifactKey: null,
rowCount: null,
errorName: null,
errorMessage: null,
retentionErrorMessage: null,
expiresAt: data.expiresAt ?? null,
deletedAt: null,
hardDeletedAt: null,
startedAt: null,
finishedAt: null,
},
});
}
export async function markExportJobRunning(
data: ExportJobRunningInput,
client: ExportJobWriterClient = getDbClient() as DbClient & ExportJobWriterClient,
): Promise<unknown> {
return updateExportJobForTenant(client, {
id: data.id,
tenantId: data.tenantId,
update: {
status: "RUNNING",
attemptsMade: normalizeAttemptsMade(data.attemptsMade),
artifactBucket: null,
artifactKey: null,
rowCount: null,
errorName: null,
errorMessage: null,
retentionErrorMessage: null,
deletedAt: null,
hardDeletedAt: null,
startedAt: data.startedAt ?? new Date(),
finishedAt: null,
},
});
}
export async function markExportJobSucceeded(
data: ExportJobSucceededInput,
client: ExportJobWriterClient = getDbClient() as DbClient & ExportJobWriterClient,
): Promise<unknown> {
return updateExportJobForTenant(client, {
id: data.id,
tenantId: data.tenantId,
update: {
status: "COMPLETED",
attemptsMade: normalizeAttemptsMade(data.attemptsMade),
artifactBucket: data.artifactBucket,
artifactKey: data.artifactKey,
rowCount: data.rowCount,
errorName: null,
errorMessage: null,
retentionErrorMessage: null,
expiresAt: data.expiresAt ?? null,
deletedAt: null,
hardDeletedAt: null,
finishedAt: data.finishedAt ?? new Date(),
},
});
}
export async function markExportJobFailed(
data: ExportJobFailedInput,
client: ExportJobWriterClient = getDbClient() as DbClient & ExportJobWriterClient,
): Promise<unknown> {
return updateExportJobForTenant(client, {
id: data.id,
tenantId: data.tenantId,
update: {
status: "FAILED",
attemptsMade: normalizeAttemptsMade(data.attemptsMade),
artifactBucket: null,
artifactKey: null,
rowCount: null,
errorName: data.errorName ?? "Error",
errorMessage: redactExportErrorMessage(data.errorMessage ?? ""),
finishedAt: data.finishedAt ?? new Date(),
},
});
}
export async function markExportJobPaused(
data: ExportJobPausedInput,
client: ExportJobWriterClient = getDbClient() as DbClient & ExportJobWriterClient,
): Promise<unknown> {
return updateExportJobForTenant(client, {
id: data.id,
tenantId: data.tenantId,
update: {
status: "PENDING",
attemptsMade: normalizeAttemptsMade(data.attemptsMade),
artifactBucket: null,
artifactKey: null,
rowCount: null,
errorName: "ExportPaused",
errorMessage: redactExportPauseReason(data.reason ?? ""),
retentionErrorMessage: null,
expiresAt: null,
deletedAt: null,
hardDeletedAt: null,
startedAt: null,
finishedAt: null,
},
});
}
export async function markExportJobResumed(
data: ExportJobResumedInput,
client: ExportJobWriterClient = getDbClient() as DbClient & ExportJobWriterClient,
): Promise<unknown> {
return updateExportJobForTenant(client, {
id: data.id,
tenantId: data.tenantId,
update: {
status: "PENDING",
attemptsMade: normalizeAttemptsMade(data.attemptsMade),
artifactBucket: null,
artifactKey: null,
rowCount: null,
errorName: null,
errorMessage: null,
retentionErrorMessage: null,
expiresAt: null,
deletedAt: null,
hardDeletedAt: null,
startedAt: null,
finishedAt: null,
},
});
}
export async function markExportJobExpired(
data: ExportJobExpiredInput,
client: ExportJobWriterClient = getDbClient() as DbClient & ExportJobWriterClient,
): Promise<unknown> {
const deletedAt = data.deletedAt ?? new Date();
return updateExportJobForTenant(client, {
id: data.id,
tenantId: data.tenantId,
update: {
status: "FAILED",
errorName: "ExportRetentionExpired",
errorMessage: "Export artifact expired by retention policy.",
retentionErrorMessage: null,
deletedAt,
hardDeletedAt: null,
finishedAt: deletedAt,
},
});
}
export async function markExportJobHardDeleteSucceeded(
data: ExportJobHardDeleteSucceededInput,
client: ExportJobWriterClient = getDbClient() as DbClient & ExportJobWriterClient,
): Promise<unknown> {
return updateExportJobForTenant(client, {
id: data.id,
tenantId: data.tenantId,
update: {
artifactBucket: null,
artifactKey: null,
retentionErrorMessage: null,
hardDeletedAt: data.hardDeletedAt ?? new Date(),
},
});
}
export async function markExportJobHardDeleteFailed(
data: ExportJobHardDeleteFailedInput,
client: ExportJobWriterClient = getDbClient() as DbClient & ExportJobWriterClient,
): Promise<unknown> {
return updateExportJobForTenant(client, {
id: data.id,
tenantId: data.tenantId,
update: {
retentionErrorMessage: redactRetentionErrorMessage(data.errorMessage ?? ""),
},
});
}
@@ -0,0 +1,90 @@
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
const repoRoot = resolve(__dirname, "../../..");
const schemaPath = resolve(repoRoot, "prisma/schema/core.prisma");
const migrationPath = resolve(repoRoot, "prisma/migrations/20260507133000_file_object_metadata/migration.sql");
async function readFileObjectModel() {
const schema = await readFile(schemaPath, "utf8");
const match = schema.match(/model FileObject \{(?<body>[\s\S]*?)\n\}/);
expect(match?.groups?.body, "FileObject model exists in core Prisma schema").toBeTruthy();
return match?.groups?.body ?? "";
}
describe("FileObject metadata schema contract", () => {
it("defines durable object identity and content metadata fields", async () => {
const fileObjectModel = await readFileObjectModel();
expect(fileObjectModel, "id uses the existing cuid string convention").toMatch(
/^\s*id\s+String\s+@id\s+@default\(cuid\(\)\)/m,
);
expect(fileObjectModel, "createdAt is tracked for row lifecycle auditing").toMatch(
/^\s*createdAt\s+DateTime\s+@default\(now\(\)\)/m,
);
expect(fileObjectModel, "updatedAt is maintained by Prisma").toMatch(/^\s*updatedAt\s+DateTime\s+@updatedAt/m);
expect(fileObjectModel, "provider is required for S3-compatible adapter identity").toMatch(/^\s*provider\s+String/m);
expect(fileObjectModel, "bucket is required for object identity").toMatch(/^\s*bucket\s+String/m);
expect(fileObjectModel, "key is required for object identity").toMatch(/^\s*key\s+String/m);
expect(fileObjectModel, "contentType is required upload metadata").toMatch(/^\s*contentType\s+String/m);
expect(fileObjectModel, "byteSize is required upload metadata").toMatch(/^\s*byteSize\s+Int/m);
expect(fileObjectModel, "checksumSha256 stores optional integrity metadata").toMatch(/^\s*checksumSha256\s+String\?/m);
expect(fileObjectModel, "publicUrl stores optional public object location").toMatch(/^\s*publicUrl\s+String\?/m);
expect(fileObjectModel, "uploadedAt tracks completed uploads").toMatch(/^\s*uploadedAt\s+DateTime\?/m);
expect(fileObjectModel, "lastSignedUploadAt tracks upload signing activity").toMatch(
/^\s*lastSignedUploadAt\s+DateTime\?/m,
);
expect(fileObjectModel, "lastSignedDownloadAt tracks download signing activity").toMatch(
/^\s*lastSignedDownloadAt\s+DateTime\?/m,
);
expect(fileObjectModel, "metadata is nullable JSON for provider-specific details").toMatch(/^\s*metadata\s+Json\?/m);
});
it("protects duplicate object identity and expected lookup patterns", async () => {
const fileObjectModel = await readFileObjectModel();
expect(fileObjectModel, "object identity is unique per provider, bucket, and key").toMatch(
/@@unique\(\[provider,\s*bucket,\s*key\],\s*name:\s*"file_object_provider_bucket_key"\)/,
);
expect(fileObjectModel, "provider and bucket lookup is indexed for scoped storage operations").toMatch(
/@@index\(\[provider,\s*bucket\],\s*name:\s*"file_object_provider_bucket_idx"\)/,
);
expect(fileObjectModel, "uploadedAt is indexed for upload-time listing and cleanup").toMatch(
/@@index\(\[uploadedAt\],\s*name:\s*"file_object_uploaded_at_idx"\)/,
);
});
it("keeps the migration in sync with schema fields and constraints", async () => {
const migrationSql = await readFile(migrationPath, "utf8");
expect(migrationSql, "migration creates the FileObject table").toMatch(/CREATE\s+TABLE\s+["`]FileObject["`]/i);
expect(migrationSql, "provider is required").toMatch(/["`]provider["`]\s+TEXT\s+NOT\s+NULL/i);
expect(migrationSql, "bucket is required").toMatch(/["`]bucket["`]\s+TEXT\s+NOT\s+NULL/i);
expect(migrationSql, "key is required").toMatch(/["`]key["`]\s+TEXT\s+NOT\s+NULL/i);
expect(migrationSql, "contentType is required").toMatch(/["`]contentType["`]\s+TEXT\s+NOT\s+NULL/i);
expect(migrationSql, "byteSize is required").toMatch(/["`]byteSize["`]\s+INTEGER\s+NOT\s+NULL/i);
expect(migrationSql, "checksumSha256 is nullable").toMatch(/["`]checksumSha256["`]\s+TEXT[,\n]/i);
expect(migrationSql, "publicUrl is nullable").toMatch(/["`]publicUrl["`]\s+TEXT[,\n]/i);
expect(migrationSql, "uploadedAt is nullable").toMatch(/["`]uploadedAt["`]\s+TIMESTAMP(?:\(\d+\))?[,\n]/i);
expect(migrationSql, "lastSignedUploadAt is nullable").toMatch(
/["`]lastSignedUploadAt["`]\s+TIMESTAMP(?:\(\d+\))?[,\n]/i,
);
expect(migrationSql, "lastSignedDownloadAt is nullable").toMatch(
/["`]lastSignedDownloadAt["`]\s+TIMESTAMP(?:\(\d+\))?[,\n]/i,
);
expect(migrationSql, "metadata uses a JSON-capable column").toMatch(/["`]metadata["`]\s+JSONB/i);
expect(migrationSql, "migration creates unique provider/bucket/key protection").toMatch(
/CREATE\s+UNIQUE\s+INDEX\s+["`]file_object_provider_bucket_key["`]\s+ON\s+["`]FileObject["`]\s*\(\s*["`]provider["`]\s*,\s*["`]bucket["`]\s*,\s*["`]key["`]\s*\)/i,
);
expect(migrationSql, "migration indexes provider and bucket lookups").toMatch(
/CREATE\s+INDEX\s+["`]file_object_provider_bucket_idx["`]\s+ON\s+["`]FileObject["`]\s*\(\s*["`]provider["`]\s*,\s*["`]bucket["`]\s*\)/i,
);
expect(migrationSql, "migration indexes upload timestamps").toMatch(
/CREATE\s+INDEX\s+["`]file_object_uploaded_at_idx["`]\s+ON\s+["`]FileObject["`]\s*\(\s*["`]uploadedAt["`]\s*\)/i,
);
});
});
@@ -0,0 +1,180 @@
import { describe, expect, it, vi } from "vitest";
import {
DEFAULT_IDEMPOTENCY_SCOPE,
createIdempotencyKeyResponse,
createStoredIdempotencyResponse,
findIdempotencyKeyByScopeAndKey,
findStoredIdempotencyResponse,
mapIdempotencyKeyToResponse,
normalizeIdempotencyScope,
type IdempotencyKeyClient,
} from "./idempotency-keys.server.js";
import type { IdempotencyKey } from "../generated/prisma/client/client.js";
function createIdempotencyClient(row: IdempotencyKey | null = null): IdempotencyKeyClient {
return {
idempotencyKey: {
findUnique: vi.fn(async () => row),
create: vi.fn(async ({ data }) => ({
id: "idempotency_key_1",
createdAt: new Date("2026-05-11T12:00:00.000Z"),
updatedAt: new Date("2026-05-11T12:00:00.000Z"),
...data,
})),
},
};
}
function createStoredRow(patch: Partial<IdempotencyKey> = {}): IdempotencyKey {
return {
id: "idempotency_key_1",
createdAt: new Date("2026-05-11T12:00:00.000Z"),
updatedAt: new Date("2026-05-11T12:00:00.000Z"),
expiresAt: new Date("2026-05-12T12:00:00.000Z"),
scope: "tenant_1",
key: "request_1",
requestHash: "hash_1",
responseStatus: 201,
responseBody: { ok: true },
responseHeaders: { location: "/widgets/widget_1", ignored: 123 },
...patch,
};
}
describe("idempotency key persistence", () => {
it("normalizes missing and blank scopes to the default scope", () => {
expect(DEFAULT_IDEMPOTENCY_SCOPE).toBe("default");
expect(normalizeIdempotencyScope()).toBe("default");
expect(normalizeIdempotencyScope(" ")).toBe("default");
expect(normalizeIdempotencyScope(" tenant_1 ")).toBe("tenant_1");
});
it("looks up rows by the generated compound unique idempotency_key_scope_key", async () => {
const row = createStoredRow();
const client = createIdempotencyClient(row);
await expect(
findIdempotencyKeyByScopeAndKey(
{
scope: " tenant_1 ",
key: "request_1",
},
client
)
).resolves.toBe(row);
expect(client.idempotencyKey.findUnique).toHaveBeenCalledWith({
where: {
idempotency_key_scope_key: {
scope: "tenant_1",
key: "request_1",
},
},
});
});
it("creates stored responses using Prisma IdempotencyKey fields", async () => {
const client = createIdempotencyClient();
const expiresAt = new Date("2026-05-12T12:00:00.000Z");
await expect(
createStoredIdempotencyResponse(
{
scope: "tenant_1",
key: "request_1",
requestHash: "hash_1",
response: {
status: 202,
body: { accepted: true },
headers: { location: "/jobs/job_1" },
},
expiresAt,
},
client
)
).resolves.toMatchObject({
scope: "tenant_1",
key: "request_1",
requestHash: "hash_1",
responseStatus: 202,
responseBody: { accepted: true },
responseHeaders: { location: "/jobs/job_1" },
expiresAt,
});
expect(client.idempotencyKey.create).toHaveBeenCalledWith({
data: {
scope: "tenant_1",
key: "request_1",
requestHash: "hash_1",
responseStatus: 202,
responseBody: { accepted: true },
responseHeaders: { location: "/jobs/job_1" },
expiresAt,
},
});
});
it("normalizes absent stored response body, headers, and expiry to null on create", async () => {
const client = createIdempotencyClient();
await createIdempotencyKeyResponse(
{
key: "request_1",
requestHash: "hash_1",
response: { status: 204 },
},
client
);
expect(client.idempotencyKey.create).toHaveBeenCalledWith({
data: {
scope: "default",
key: "request_1",
requestHash: "hash_1",
responseStatus: 204,
responseBody: null,
responseHeaders: null,
expiresAt: null,
},
});
});
it("maps stored DB rows to reusable response shape", async () => {
const row = createStoredRow();
const client = createIdempotencyClient(row);
expect(mapIdempotencyKeyToResponse(row)).toEqual({
requestHash: "hash_1",
status: 201,
body: { ok: true },
headers: { location: "/widgets/widget_1" },
expiresAt: new Date("2026-05-12T12:00:00.000Z"),
});
await expect(findStoredIdempotencyResponse({ scope: "tenant_1", key: "request_1" }, client)).resolves.toEqual({
requestHash: "hash_1",
status: 201,
body: { ok: true },
headers: { location: "/widgets/widget_1" },
expiresAt: new Date("2026-05-12T12:00:00.000Z"),
});
});
it("omits null body and non-object response headers when mapping stored rows", () => {
expect(
mapIdempotencyKeyToResponse(
createStoredRow({
expiresAt: null,
responseBody: null,
responseHeaders: null,
})
)
).toEqual({
requestHash: "hash_1",
status: 201,
expiresAt: null,
});
});
});
@@ -0,0 +1,121 @@
import { getDbClient } from "./client.server.js";
import type { IdempotencyKey, Prisma } from "../generated/prisma/client/client.js";
export const DEFAULT_IDEMPOTENCY_SCOPE = "default";
export type IdempotencyResponse = {
status: number;
body?: Prisma.JsonValue;
headers?: Record<string, string>;
};
export type IdempotencyKeyLookup = {
scope?: string | null;
key: string;
};
export type StoredIdempotencyResponse = IdempotencyResponse & {
requestHash: string;
expiresAt: Date | null;
};
export type CreateStoredIdempotencyResponseInput = IdempotencyKeyLookup & {
requestHash: string;
response: IdempotencyResponse;
expiresAt?: Date | null;
};
export type IdempotencyKeyReaderClient = {
idempotencyKey: {
findUnique(args: {
where: {
idempotency_key_scope_key: {
scope: string;
key: string;
};
};
}): Promise<IdempotencyKey | null>;
};
};
export type IdempotencyKeyWriterClient = {
idempotencyKey: {
create(args: {
data: {
scope: string;
key: string;
requestHash: string;
responseStatus: number;
responseBody: Prisma.JsonValue | null;
responseHeaders: Record<string, string> | null;
expiresAt: Date | null;
};
}): Promise<IdempotencyKey>;
};
};
export type IdempotencyKeyClient = IdempotencyKeyReaderClient & IdempotencyKeyWriterClient;
export function normalizeIdempotencyScope(scope?: string | null): string {
return scope?.trim() || DEFAULT_IDEMPOTENCY_SCOPE;
}
export function mapIdempotencyKeyToResponse(row: IdempotencyKey): StoredIdempotencyResponse {
return {
requestHash: row.requestHash,
status: row.responseStatus,
body: row.responseBody ?? undefined,
headers: mapResponseHeaders(row.responseHeaders),
expiresAt: row.expiresAt ?? null,
};
}
export async function findIdempotencyKeyByScopeAndKey(
input: IdempotencyKeyLookup,
client: IdempotencyKeyReaderClient = getDbClient() as unknown as IdempotencyKeyReaderClient
): Promise<IdempotencyKey | null> {
return client.idempotencyKey.findUnique({
where: {
idempotency_key_scope_key: {
scope: normalizeIdempotencyScope(input.scope),
key: input.key,
},
},
});
}
export async function findStoredIdempotencyResponse(
input: IdempotencyKeyLookup,
client: IdempotencyKeyReaderClient = getDbClient() as unknown as IdempotencyKeyReaderClient
): Promise<StoredIdempotencyResponse | null> {
const row = await findIdempotencyKeyByScopeAndKey(input, client);
return row ? mapIdempotencyKeyToResponse(row) : null;
}
export async function createStoredIdempotencyResponse(
input: CreateStoredIdempotencyResponseInput,
client: IdempotencyKeyWriterClient = getDbClient() as unknown as IdempotencyKeyWriterClient
): Promise<IdempotencyKey> {
return client.idempotencyKey.create({
data: {
scope: normalizeIdempotencyScope(input.scope),
key: input.key,
requestHash: input.requestHash,
responseStatus: input.response.status,
responseBody: input.response.body ?? null,
responseHeaders: input.response.headers ?? null,
expiresAt: input.expiresAt ?? null,
},
});
}
export const createIdempotencyKeyResponse = createStoredIdempotencyResponse;
function mapResponseHeaders(headers: Prisma.JsonValue | null): Record<string, string> | undefined {
if (!headers || typeof headers !== "object" || Array.isArray(headers)) {
return undefined;
}
const entries = Object.entries(headers).filter((entry): entry is [string, string] => typeof entry[1] === "string");
return entries.length > 0 ? Object.fromEntries(entries) : undefined;
}
@@ -0,0 +1 @@
export const IMPERSONATED_DESTRUCTIVE_ACTION_CONFIRMATION = "confirm impersonated destructive action";
@@ -0,0 +1,113 @@
import { describe, expect, it, vi } from "vitest";
import {
createImpersonationAudit,
IMPERSONATED_DESTRUCTIVE_ACTION_CONFIRMATION,
serializeImpersonationAuditMetadata,
type ImpersonationAuditWriterClient,
} from "./impersonation-audit.server.js";
function createAuditClient(): ImpersonationAuditWriterClient {
return {
impersonationAudit: {
create: vi.fn().mockResolvedValue({ id: "impersonation_audit_1" }),
},
} as unknown as ImpersonationAuditWriterClient;
}
describe("impersonation audit persistence", () => {
it("exports the destructive action confirmation phrase", () => {
expect(IMPERSONATED_DESTRUCTIVE_ACTION_CONFIRMATION).toBe("confirm impersonated destructive action");
});
it("writes the expected audit shape", async () => {
const client = createAuditClient();
await expect(
createImpersonationAudit(
{
actorUserId: "actor_user_1",
targetUserId: "target_user_1",
tenantId: "tenant_1",
action: "start",
reason: "Support investigation",
requestPath: "/admin/users/user_1/impersonate",
metadata: { ip: "127.0.0.1", userAgent: "Vitest" },
},
client,
),
).resolves.toEqual({ id: "impersonation_audit_1" });
expect(client.impersonationAudit.create).toHaveBeenCalledWith({
data: {
actorUserId: "actor_user_1",
targetUserId: "target_user_1",
tenantId: "tenant_1",
action: "start",
reason: "Support investigation",
requestPath: "/admin/users/user_1/impersonate",
metadata: JSON.stringify({ ip: "127.0.0.1", userAgent: "Vitest" }),
},
});
});
it("normalizes nullable optional fields", async () => {
const client = createAuditClient();
await createImpersonationAudit(
{
actorUserId: "actor_user_1",
targetUserId: "target_user_1",
action: "start",
requestPath: "/admin/impersonate",
},
client,
);
expect(client.impersonationAudit.create).toHaveBeenCalledWith({
data: {
actorUserId: "actor_user_1",
targetUserId: "target_user_1",
tenantId: null,
action: "start",
reason: null,
requestPath: "/admin/impersonate",
metadata: null,
},
});
});
it("strips sensitive metadata keys before serializing", () => {
const serialized = serializeImpersonationAuditMetadata({
ip: "127.0.0.1",
cookie: "session=secret",
password: "password-1",
totpCode: "123456",
recoveryCode: "abc",
accessToken: "token-1",
api_secret: "secret-1",
nested: { allowed: true },
});
expect(serialized).toBe(JSON.stringify({ ip: "127.0.0.1", nested: JSON.stringify({ allowed: true }) }));
expect(serialized).not.toContain("session=secret");
expect(serialized).not.toContain("password-1");
expect(serialized).not.toContain("123456");
expect(serialized).not.toContain("abc");
expect(serialized).not.toContain("token-1");
expect(serialized).not.toContain("secret-1");
});
it("returns null when metadata only contains sensitive keys", () => {
expect(
serializeImpersonationAuditMetadata({
cookie: "session=secret",
password: "password-1",
totp: "123456",
recovery: "recovery-1",
token: "token-1",
secret: "secret-1",
}),
).toBeNull();
});
});
@@ -0,0 +1,98 @@
import { getDbClient } from "./client.server.js";
export { IMPERSONATED_DESTRUCTIVE_ACTION_CONFIRMATION } from "./impersonation-audit.constants.js";
const SENSITIVE_METADATA_KEY_PATTERN = /cookie|password|totp|recovery|token|secret/i;
export type ImpersonationAuditAction = "start" | "destructive_action_blocked" | (string & {});
export type ImpersonationAuditCreateData = {
actorUserId: string;
targetUserId: string;
tenantId?: string | null;
action: ImpersonationAuditAction;
reason?: string | null;
requestPath: string;
metadata?: Record<string, unknown> | null;
};
export type ImpersonationAuditRecord = {
id: string;
createdAt: Date;
actorUserId: string;
targetUserId: string;
tenantId: string | null;
action: string;
reason: string | null;
requestPath: string;
metadata: string | null;
};
export type ImpersonationAuditWriterClient = {
impersonationAudit: {
create(args: {
data: {
actorUserId: string;
targetUserId: string;
tenantId: string | null;
action: string;
reason: string | null;
requestPath: string;
metadata: string | null;
};
}): Promise<ImpersonationAuditRecord>;
};
};
function redactMetadataValue(value: unknown): string {
if (value === null || value === undefined) {
return "";
}
if (typeof value === "string") {
return value;
}
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
return String(value);
}
if (value instanceof Date) {
return value.toISOString();
}
return JSON.stringify(value);
}
export function serializeImpersonationAuditMetadata(metadata?: Record<string, unknown> | null): string | null {
if (!metadata) {
return null;
}
const redactedEntries = Object.entries(metadata)
.filter(([key]) => !SENSITIVE_METADATA_KEY_PATTERN.test(key))
.map(([key, value]) => [key, redactMetadataValue(value)] as const)
.filter(([, value]) => value.length > 0);
if (redactedEntries.length === 0) {
return null;
}
return JSON.stringify(Object.fromEntries(redactedEntries));
}
export async function createImpersonationAudit(
data: ImpersonationAuditCreateData,
client: ImpersonationAuditWriterClient = getDbClient() as unknown as ImpersonationAuditWriterClient,
): Promise<ImpersonationAuditRecord> {
return client.impersonationAudit.create({
data: {
actorUserId: data.actorUserId,
targetUserId: data.targetUserId,
tenantId: data.tenantId ?? null,
action: data.action,
reason: data.reason ?? null,
requestPath: data.requestPath,
metadata: serializeImpersonationAuditMetadata(data.metadata),
},
});
}
@@ -0,0 +1,299 @@
import { describe, expect, it, vi } from "vitest";
import {
IMPORT_JOB_ERROR_MESSAGE_MAX_LENGTH,
createImportJob,
findImportJobForInspection,
markImportJobFailed,
markImportJobRunning,
markImportJobSucceeded,
type ImportJobInspectionRecord,
type ImportJobReaderClient,
type ImportJobWriterClient,
} from "./import-jobs.server.js";
function createImportJobClient(): ImportJobWriterClient {
return {
importJob: {
create: vi.fn().mockResolvedValue({ id: "import_job_1" }),
update: vi.fn().mockResolvedValue({ id: "import_job_1" }),
updateMany: vi.fn().mockResolvedValue({ count: 1 }),
},
};
}
function createImportJobReader(record: ImportJobInspectionRecord | null): ImportJobReaderClient {
return {
importJob: {
findFirst: vi.fn().mockResolvedValue(record),
},
};
}
describe("import job inspection lookups", () => {
it("finds import jobs with scalar inspection fields only", async () => {
const startedAt = new Date("2026-05-10T14:00:00.000Z");
const finishedAt = new Date("2026-05-10T14:05:00.000Z");
const record: ImportJobInspectionRecord = {
id: "import_job_1",
tenantId: "tenant_1",
requestedByUserId: "user_1",
importType: "members",
format: "csv",
status: "COMPLETED",
requestId: "request_1",
attemptsMade: 2,
sourceBucket: "imports",
sourceKey: "tenants/tenant_1/members.csv",
fileName: "members.csv",
contentType: "text/csv",
rowCount: 42,
acceptedRows: 40,
rejectedRows: 2,
errorName: null,
errorMessage: null,
errorReportBucket: "reports",
errorReportKey: "tenant_1/reports/import_job_1.json",
startedAt,
finishedAt,
};
const client = createImportJobReader(record);
await expect(
findImportJobForInspection({ id: "import_job_1", tenantId: "tenant_1" }, client),
).resolves.toEqual(record);
const findFirstCall = vi.mocked(client.importJob.findFirst).mock.calls[0]?.[0];
expect(findFirstCall).toEqual({
where: { id: "import_job_1", tenantId: "tenant_1" },
select: {
id: true,
tenantId: true,
requestedByUserId: true,
importType: true,
format: true,
status: true,
requestId: true,
attemptsMade: true,
sourceBucket: true,
sourceKey: true,
fileName: true,
contentType: true,
rowCount: true,
acceptedRows: true,
rejectedRows: true,
errorName: true,
errorMessage: true,
errorReportBucket: true,
errorReportKey: true,
startedAt: true,
finishedAt: true,
},
});
expect(JSON.stringify(findFirstCall)).not.toContain("payload");
expect(JSON.stringify(findFirstCall)).not.toContain("body");
expect(JSON.stringify(findFirstCall)).not.toContain("headers");
expect(JSON.stringify(findFirstCall)).not.toContain("rawRows");
});
it("requires tenant filtering for inspection lookups", async () => {
const client = createImportJobReader(null);
await findImportJobForInspection({ id: "import_job_1", tenantId: " tenant_1 " }, client);
expect(client.importJob.findFirst).toHaveBeenCalledWith(
expect.objectContaining({ where: { id: "import_job_1", tenantId: "tenant_1" } }),
);
});
it("rejects blank tenant inspection scope", async () => {
const client = createImportJobReader(null);
await expect(findImportJobForInspection({ id: "import_job_1", tenantId: " " }, client)).rejects.toThrow("Import job inspection requires tenantId.");
expect(client.importJob.findFirst).not.toHaveBeenCalled();
});
it("returns null for missing import jobs", async () => {
const client = createImportJobReader(null);
await expect(
findImportJobForInspection({ id: "missing_import_job", tenantId: "tenant_1" }, client),
).resolves.toBeNull();
});
});
describe("import job writes", () => {
it("creates pending import jobs with nullable lifecycle, counters, and diagnostics", async () => {
const client = createImportJobClient();
await createImportJob(
{
tenantId: "tenant_1",
requestedByUserId: "user_1",
importType: "members",
format: "csv",
requestId: "request_1",
sourceBucket: "imports",
sourceKey: "tenants/tenant_1/members.csv",
fileName: "members.csv",
contentType: "text/csv",
attemptsMade: null,
payload: { secret: "secret-payload" },
body: "secret-body",
headers: { authorization: "Bearer secret" },
rawRows: [{ password: "secret" }],
} as Parameters<typeof createImportJob>[0] & Record<string, unknown>,
client,
);
const createCall = vi.mocked(client.importJob.create).mock.calls[0]?.[0];
expect(createCall).toEqual({
data: {
tenantId: "tenant_1",
requestedByUserId: "user_1",
importType: "members",
format: "csv",
status: "PENDING",
requestId: "request_1",
attemptsMade: 0,
sourceBucket: "imports",
sourceKey: "tenants/tenant_1/members.csv",
fileName: "members.csv",
contentType: "text/csv",
rowCount: null,
acceptedRows: 0,
rejectedRows: 0,
errorName: null,
errorMessage: null,
errorReportBucket: null,
errorReportKey: null,
startedAt: null,
finishedAt: null,
},
});
expect(JSON.stringify(createCall)).not.toContain("secret-payload");
expect(JSON.stringify(createCall)).not.toContain("secret-body");
expect(JSON.stringify(createCall)).not.toContain("authorization");
expect(JSON.stringify(createCall)).not.toContain("password");
});
it("marks import jobs running and clears stale counters and error report fields", async () => {
const client = createImportJobClient();
const startedAt = new Date("2026-05-10T13:00:00.000Z");
await markImportJobRunning(
{
id: "import_job_1",
tenantId: "tenant_1",
attemptsMade: 2,
startedAt,
errorReportBucket: "stale-report-bucket",
errorReportKey: "stale-report-key",
} as Parameters<typeof markImportJobRunning>[0] & Record<string, unknown>,
client,
);
const updateCall = vi.mocked(client.importJob.updateMany).mock.calls[0]?.[0];
expect(updateCall).toEqual({
where: { id: "import_job_1", tenantId: "tenant_1" },
data: {
status: "RUNNING",
attemptsMade: 2,
rowCount: null,
acceptedRows: 0,
rejectedRows: 0,
errorName: null,
errorMessage: null,
errorReportBucket: null,
errorReportKey: null,
startedAt,
finishedAt: null,
},
});
expect(JSON.stringify(updateCall)).not.toContain("stale-report-bucket");
expect(JSON.stringify(updateCall)).not.toContain("stale-report-key");
});
it("marks import jobs completed with row counters and cleared diagnostics", async () => {
const client = createImportJobClient();
const finishedAt = new Date("2026-05-10T14:00:00.000Z");
await markImportJobSucceeded(
{
id: "import_job_1",
tenantId: "tenant_1",
rowCount: 42,
acceptedRows: 40,
rejectedRows: 2,
attemptsMade: 3,
finishedAt,
},
client,
);
expect(client.importJob.updateMany).toHaveBeenCalledWith({
where: { id: "import_job_1", tenantId: "tenant_1" },
data: {
status: "COMPLETED",
attemptsMade: 3,
rowCount: 42,
acceptedRows: 40,
rejectedRows: 2,
errorName: null,
errorMessage: null,
errorReportBucket: null,
errorReportKey: null,
finishedAt,
},
});
});
it("marks import jobs failed with truncated scalar diagnostics and ignores payload-like inputs", async () => {
const client = createImportJobClient();
const finishedAt = new Date("2026-05-10T15:00:00.000Z");
const oversizedMessage = "x".repeat(IMPORT_JOB_ERROR_MESSAGE_MAX_LENGTH + 100);
await markImportJobFailed(
{
id: "import_job_1",
tenantId: "tenant_1",
attemptsMade: 4,
rowCount: 42,
acceptedRows: 40,
rejectedRows: 2,
errorName: "ImportValidationError",
errorMessage: oversizedMessage,
errorReportBucket: "reports",
errorReportKey: "tenant_1/reports/import_job_1.json",
finishedAt,
payload: { secret: "secret-payload" },
headers: { authorization: "Bearer secret" },
body: "secret-body",
rawRows: [{ password: "secret" }],
} as Parameters<typeof markImportJobFailed>[0] & Record<string, unknown>,
client,
);
const updateCall = vi.mocked(client.importJob.updateMany).mock.calls[0]?.[0];
expect(updateCall).toEqual({
where: { id: "import_job_1", tenantId: "tenant_1" },
data: {
status: "FAILED",
attemptsMade: 4,
rowCount: 42,
acceptedRows: 40,
rejectedRows: 2,
errorName: "ImportValidationError",
errorMessage: "x".repeat(IMPORT_JOB_ERROR_MESSAGE_MAX_LENGTH),
errorReportBucket: "reports",
errorReportKey: "tenant_1/reports/import_job_1.json",
finishedAt,
},
});
expect(updateCall?.data.errorMessage).toHaveLength(IMPORT_JOB_ERROR_MESSAGE_MAX_LENGTH);
expect(JSON.stringify(updateCall)).not.toContain("secret-payload");
expect(JSON.stringify(updateCall)).not.toContain("authorization");
expect(JSON.stringify(updateCall)).not.toContain("secret-body");
expect(JSON.stringify(updateCall)).not.toContain("password");
});
});
@@ -0,0 +1,325 @@
import { getDbClient, type DbClient } from "./client.server.js";
export const IMPORT_JOB_ERROR_MESSAGE_MAX_LENGTH = 2_000;
export type ImportJobStatus = "PENDING" | "RUNNING" | "COMPLETED" | "FAILED";
export type ImportJobCreateInput = {
tenantId: string;
requestedByUserId?: string | null;
importType: string;
format: string;
requestId: string;
sourceBucket: string;
sourceKey: string;
fileName?: string | null;
contentType?: string | null;
attemptsMade?: number | null;
};
export type ImportJobRunningInput = {
id: string;
tenantId: string;
attemptsMade: number;
startedAt?: Date | null;
};
export type ImportJobSucceededInput = {
id: string;
tenantId: string;
rowCount: number;
acceptedRows: number;
rejectedRows: number;
attemptsMade?: number | null;
finishedAt?: Date | null;
};
export type ImportJobFailedInput = {
id: string;
tenantId: string;
attemptsMade: number;
rowCount?: number | null;
acceptedRows?: number | null;
rejectedRows?: number | null;
errorName?: string | null;
errorMessage?: string | null;
errorReportBucket?: string | null;
errorReportKey?: string | null;
finishedAt?: Date | null;
};
export type ImportJobInspectionRecord = {
id: string;
tenantId: string;
requestedByUserId: string | null;
importType: string;
format: string;
status: ImportJobStatus;
requestId: string;
attemptsMade: number;
sourceBucket: string;
sourceKey: string;
fileName: string | null;
contentType: string | null;
rowCount: number | null;
acceptedRows: number;
rejectedRows: number;
errorName: string | null;
errorMessage: string | null;
errorReportBucket: string | null;
errorReportKey: string | null;
startedAt: Date | null;
finishedAt: Date | null;
};
export type ImportJobInspectionLookupInput = {
id: string;
tenantId: string;
};
type ImportJobCreateData = {
tenantId: string;
requestedByUserId: string | null;
importType: string;
format: string;
status: Extract<ImportJobStatus, "PENDING">;
requestId: string;
attemptsMade: number;
sourceBucket: string;
sourceKey: string;
fileName: string | null;
contentType: string | null;
rowCount: null;
acceptedRows: number;
rejectedRows: number;
errorName: null;
errorMessage: null;
errorReportBucket: null;
errorReportKey: null;
startedAt: null;
finishedAt: null;
};
type ImportJobUpdateData = Partial<{
status: ImportJobStatus;
attemptsMade: number;
rowCount: number | null;
acceptedRows: number;
rejectedRows: number;
errorName: string | null;
errorMessage: string | null;
errorReportBucket: string | null;
errorReportKey: string | null;
startedAt: Date | null;
finishedAt: Date | null;
}>;
export type ImportJobWriterClient = {
importJob: {
create(args: { data: ImportJobCreateData }): Promise<unknown>;
update(args: { where: { id: string }; data: ImportJobUpdateData }): Promise<unknown>;
updateMany(args: { where: { id: string; tenantId: string }; data: ImportJobUpdateData }): Promise<{ count?: number }>;
};
};
export type ImportJobReaderClient = {
importJob: {
findFirst(args: {
where: { id: string; tenantId: string };
select: {
id: true;
tenantId: true;
requestedByUserId: true;
importType: true;
format: true;
status: true;
requestId: true;
attemptsMade: true;
sourceBucket: true;
sourceKey: true;
fileName: true;
contentType: true;
rowCount: true;
acceptedRows: true;
rejectedRows: true;
errorName: true;
errorMessage: true;
errorReportBucket: true;
errorReportKey: true;
startedAt: true;
finishedAt: true;
};
}): Promise<ImportJobInspectionRecord | null>;
};
};
function normalizeAttemptsMade(attemptsMade?: number | null): number {
return attemptsMade ?? 0;
}
function truncateErrorMessage(errorMessage: string): string {
if (errorMessage.length <= IMPORT_JOB_ERROR_MESSAGE_MAX_LENGTH) {
return errorMessage;
}
return errorMessage.slice(0, IMPORT_JOB_ERROR_MESSAGE_MAX_LENGTH);
}
async function updateImportJobForTenant(
client: ImportJobWriterClient,
data: { id: string; tenantId: string; update: ImportJobUpdateData },
): Promise<unknown> {
const id = data.id.trim();
const tenantId = data.tenantId.trim();
if (!id || !tenantId) {
throw new Error("Import job tenant scope is required.");
}
const result = await client.importJob.updateMany({
where: { id, tenantId },
data: data.update,
});
if (typeof result.count === "number" && result.count !== 1) {
throw new Error("Import job tenant scope did not match exactly one job.");
}
return result;
}
export async function createImportJob(
data: ImportJobCreateInput,
client: ImportJobWriterClient = getDbClient() as DbClient & ImportJobWriterClient,
): Promise<unknown> {
return client.importJob.create({
data: {
tenantId: data.tenantId,
requestedByUserId: data.requestedByUserId ?? null,
importType: data.importType,
format: data.format,
status: "PENDING",
requestId: data.requestId,
attemptsMade: normalizeAttemptsMade(data.attemptsMade),
sourceBucket: data.sourceBucket,
sourceKey: data.sourceKey,
fileName: data.fileName ?? null,
contentType: data.contentType ?? null,
rowCount: null,
acceptedRows: 0,
rejectedRows: 0,
errorName: null,
errorMessage: null,
errorReportBucket: null,
errorReportKey: null,
startedAt: null,
finishedAt: null,
},
});
}
export async function markImportJobRunning(
data: ImportJobRunningInput,
client: ImportJobWriterClient = getDbClient() as DbClient & ImportJobWriterClient,
): Promise<unknown> {
return updateImportJobForTenant(client, {
id: data.id,
tenantId: data.tenantId,
update: {
status: "RUNNING",
attemptsMade: normalizeAttemptsMade(data.attemptsMade),
rowCount: null,
acceptedRows: 0,
rejectedRows: 0,
errorName: null,
errorMessage: null,
errorReportBucket: null,
errorReportKey: null,
startedAt: data.startedAt ?? new Date(),
finishedAt: null,
},
});
}
export async function markImportJobSucceeded(
data: ImportJobSucceededInput,
client: ImportJobWriterClient = getDbClient() as DbClient & ImportJobWriterClient,
): Promise<unknown> {
return updateImportJobForTenant(client, {
id: data.id,
tenantId: data.tenantId,
update: {
status: "COMPLETED",
attemptsMade: normalizeAttemptsMade(data.attemptsMade),
rowCount: data.rowCount,
acceptedRows: data.acceptedRows,
rejectedRows: data.rejectedRows,
errorName: null,
errorMessage: null,
errorReportBucket: null,
errorReportKey: null,
finishedAt: data.finishedAt ?? new Date(),
},
});
}
export async function markImportJobFailed(
data: ImportJobFailedInput,
client: ImportJobWriterClient = getDbClient() as DbClient & ImportJobWriterClient,
): Promise<unknown> {
return updateImportJobForTenant(client, {
id: data.id,
tenantId: data.tenantId,
update: {
status: "FAILED",
attemptsMade: normalizeAttemptsMade(data.attemptsMade),
rowCount: data.rowCount ?? null,
acceptedRows: data.acceptedRows ?? 0,
rejectedRows: data.rejectedRows ?? 0,
errorName: data.errorName ?? "Error",
errorMessage: truncateErrorMessage(data.errorMessage ?? ""),
errorReportBucket: data.errorReportBucket ?? null,
errorReportKey: data.errorReportKey ?? null,
finishedAt: data.finishedAt ?? new Date(),
},
});
}
export async function findImportJobForInspection(
data: ImportJobInspectionLookupInput,
client: ImportJobReaderClient = getDbClient() as DbClient & ImportJobReaderClient,
): Promise<ImportJobInspectionRecord | null> {
const tenantId = data.tenantId.trim();
if (!tenantId) {
throw new Error("Import job inspection requires tenantId.");
}
return client.importJob.findFirst({
where: {
id: data.id,
tenantId,
},
select: {
id: true,
tenantId: true,
requestedByUserId: true,
importType: true,
format: true,
status: true,
requestId: true,
attemptsMade: true,
sourceBucket: true,
sourceKey: true,
fileName: true,
contentType: true,
rowCount: true,
acceptedRows: true,
rejectedRows: true,
errorName: true,
errorMessage: true,
errorReportBucket: true,
errorReportKey: true,
startedAt: true,
finishedAt: true,
},
});
}
@@ -0,0 +1,93 @@
import { describe, expect, it } from "vitest";
import {
createAuditEvent,
createStoredIdempotencyResponse,
buildTenantSettingsRowCreateInput,
buildTenantSettingsRowUpdateInput,
databaseBoundary,
findOptionalTenantSettingsEntity,
findTenantSettingsEntity,
findTenantWithSettingsById,
getDatabaseBoundary,
PRISMA_GENERATED_CLIENT_PATH,
PRISMA_MIGRATIONS_PATH,
PRISMA_SCHEMA_PATH,
prismaOwnershipMetadata,
tenantSettingsDetailsInclude,
} from ".";
describe("@toolctrl/db boundary metadata", () => {
it("documents the current Prisma ownership boundary", () => {
expect(getDatabaseBoundary()).toBe(databaseBoundary);
expect(databaseBoundary).toMatchObject({
packageName: "@toolctrl/db",
orm: "prisma",
schemaPath: PRISMA_SCHEMA_PATH,
migrationsPath: PRISMA_MIGRATIONS_PATH,
generatedClientPath: PRISMA_GENERATED_CLIENT_PATH,
serverClientEntrypoint: "@toolctrl/db/client.server",
});
});
it("is immutable at runtime", () => {
expect(Object.isFrozen(databaseBoundary)).toBe(true);
expect(Object.isFrozen(prismaOwnershipMetadata)).toBe(true);
});
it("keeps the root Prisma config aligned with package metadata", async () => {
process.env.DATABASE_URL ??= "postgresql://test:test@localhost:5432/test";
const { default: prismaConfig } = await import("../../../prisma.config");
expect(prismaConfig.schema).toBe(prismaOwnershipMetadata.schemaPath);
expect(prismaConfig.migrations?.path).toBe(
prismaOwnershipMetadata.migrationsPath,
);
expect(prismaConfig.migrations?.seed).toBe(
prismaOwnershipMetadata.seedCommand,
);
expect(PRISMA_GENERATED_CLIENT_PATH).toBe(
prismaOwnershipMetadata.generatedClientPath,
);
});
it("exposes the tenant settings boundary from the package root", () => {
expect(createAuditEvent).toEqual(expect.any(Function));
expect(createStoredIdempotencyResponse).toEqual(expect.any(Function));
expect(findOptionalTenantSettingsEntity).toEqual(expect.any(Function));
expect(findTenantSettingsEntity).toEqual(expect.any(Function));
expect(findTenantWithSettingsById).toEqual(expect.any(Function));
expect(buildTenantSettingsRowCreateInput).toEqual(expect.any(Function));
expect(buildTenantSettingsRowUpdateInput).toEqual(expect.any(Function));
expect(tenantSettingsDetailsInclude).toEqual(
expect.objectContaining({
tenantSettingsRow: { include: { row: expect.any(Object) } },
}),
);
});
it("exposes the tenant settings boundary subpath export", async () => {
const settingsBoundary = await import("@toolctrl/db/settings.server");
expect(settingsBoundary).toEqual(
expect.objectContaining({
findOptionalTenantSettingsEntity,
findTenantSettingsEntity,
findTenantWithSettingsById,
buildTenantSettingsRowCreateInput,
buildTenantSettingsRowUpdateInput,
tenantSettingsDetailsInclude,
}),
);
});
it("exposes audit and idempotency boundary subpath exports", async () => {
const auditBoundary = await import("@toolctrl/db/audit-events.server");
const idempotencyBoundary = await import("@toolctrl/db/idempotency-keys.server");
expect(auditBoundary.createAuditEvent).toBe(createAuditEvent);
expect(idempotencyBoundary.createStoredIdempotencyResponse).toBe(
createStoredIdempotencyResponse,
);
});
});
@@ -0,0 +1,41 @@
import { PRISMA_GENERATED_CLIENT_PATH, PRISMA_MIGRATIONS_PATH, PRISMA_SCHEMA_PATH, PRISMA_SEED_COMMAND, prismaOwnershipMetadata } from "./prisma.js";
export { PRISMA_GENERATED_CLIENT_PATH, PRISMA_MIGRATIONS_PATH, PRISMA_SCHEMA_PATH, PRISMA_SEED_COMMAND, prismaOwnershipMetadata };
export type { PrismaOwnershipMetadata } from "./prisma.js";
export * from "./auth-boundary.server.js";
export * from "./audit-events.server.js";
export * from "./export-jobs.server.js";
export * from "./idempotency-keys.server.js";
export * from "./import-jobs.server.js";
export * from "./notifications.server.js";
export * from "./outbox.js";
export * from "./outbox-claim.js";
export * from "./outbox-retention.js";
export * from "./outbox-receiver.js";
export * from "./permissions-seed.server.js";
export * from "./seed.server.js";
export * from "./settings.server.js";
export * from "./transactions.server.js";
export * from "./workspace-invites.server.js";
export type DatabaseBoundary = {
packageName: "@toolctrl/db";
orm: "prisma";
schemaPath: typeof PRISMA_SCHEMA_PATH;
migrationsPath: typeof PRISMA_MIGRATIONS_PATH;
generatedClientPath: typeof PRISMA_GENERATED_CLIENT_PATH;
serverClientEntrypoint: "@toolctrl/db/client.server";
};
export const databaseBoundary: DatabaseBoundary = Object.freeze({
packageName: "@toolctrl/db",
orm: "prisma",
schemaPath: PRISMA_SCHEMA_PATH,
migrationsPath: PRISMA_MIGRATIONS_PATH,
generatedClientPath: PRISMA_GENERATED_CLIENT_PATH,
serverClientEntrypoint: "@toolctrl/db/client.server",
});
export function getDatabaseBoundary(): DatabaseBoundary {
return databaseBoundary;
}
@@ -0,0 +1,60 @@
import { describe, expect, it, vi } from "vitest";
import { getAdminActiveUserKpiCounts, getAdminTenantKpiCounts, type AdminKpiClient } from "./kpi.server.js";
function createKpiClient(): AdminKpiClient {
return {
tenant: {
count: vi.fn()
.mockResolvedValueOnce(10)
.mockResolvedValueOnce(2),
},
log: {
groupBy: vi.fn()
.mockResolvedValueOnce([{ userId: "user_1" }, { userId: "user_2" }])
.mockResolvedValueOnce([{ userId: "user_1" }]),
},
} as unknown as AdminKpiClient;
}
describe("admin tenant KPI counts", () => {
it("does not add a malformed createdAt filter when gte is undefined", async () => {
const client = createKpiClient();
await expect(getAdminTenantKpiCounts({}, client)).resolves.toEqual({ added: 2, total: 10 });
expect(client.tenant.count).toHaveBeenNthCalledWith(1);
expect(client.tenant.count).toHaveBeenNthCalledWith(2, undefined);
});
it("passes a createdAt.gte filter for period additions", async () => {
const client = createKpiClient();
const gte = new Date("2024-06-01T00:00:00.000Z");
await expect(getAdminTenantKpiCounts({ gte }, client)).resolves.toEqual({ added: 2, total: 10 });
expect(client.tenant.count).toHaveBeenNthCalledWith(1);
expect(client.tenant.count).toHaveBeenNthCalledWith(2, { where: { createdAt: { gte } } });
});
});
describe("admin active-user KPI counts", () => {
it("counts unique user groups without a malformed createdAt filter when gte is undefined", async () => {
const client = createKpiClient();
await expect(getAdminActiveUserKpiCounts({}, client)).resolves.toEqual({ added: 1, total: 2 });
expect(client.log.groupBy).toHaveBeenNthCalledWith(1, { by: ["userId"] });
expect(client.log.groupBy).toHaveBeenNthCalledWith(2, { by: ["userId"] });
});
it("passes a createdAt.gte filter for period active-user additions", async () => {
const client = createKpiClient();
const gte = new Date("2024-06-01T00:00:00.000Z");
await expect(getAdminActiveUserKpiCounts({ gte }, client)).resolves.toEqual({ added: 1, total: 2 });
expect(client.log.groupBy).toHaveBeenNthCalledWith(1, { by: ["userId"] });
expect(client.log.groupBy).toHaveBeenNthCalledWith(2, { by: ["userId"], where: { createdAt: { gte } } });
});
});
@@ -0,0 +1,38 @@
import { getDbClient, type DbClient } from "./client.server.js";
export type AdminKpiCounts = {
added: number;
total: number;
};
export type AdminKpiPeriod = {
gte?: Date;
};
export type AdminKpiClient = Pick<DbClient, "tenant" | "log">;
function buildCreatedAtWhere({ gte }: AdminKpiPeriod) {
return gte ? { createdAt: { gte } } : undefined;
}
export async function getAdminTenantKpiCounts(period: AdminKpiPeriod, client: AdminKpiClient = getDbClient()): Promise<AdminKpiCounts> {
const addedWhere = buildCreatedAtWhere(period);
const [total, added] = await Promise.all([
client.tenant.count(),
client.tenant.count(addedWhere ? { where: addedWhere } : undefined),
]);
return { added, total };
}
export async function getAdminActiveUserKpiCounts(period: AdminKpiPeriod, client: AdminKpiClient = getDbClient()): Promise<AdminKpiCounts> {
const addedWhere = buildCreatedAtWhere(period);
const [totalGroups, addedGroups] = await Promise.all([
client.log.groupBy({ by: ["userId"] }),
addedWhere
? client.log.groupBy({ by: ["userId"], where: addedWhere })
: client.log.groupBy({ by: ["userId"] }),
]);
return { added: addedGroups.length, total: totalGroups.length };
}
@@ -0,0 +1,355 @@
import { describe, expect, it, vi } from "vitest";
import {
buildAuditLogWhereFromFilters,
createLegacyEntityWebhookLog,
createLegacyRowLog,
getAdminAuditLogList,
getLegacyEntityWebhooksByAction,
getTenantAuditLogList,
redactLogDetails,
serializeAdminAuditLogsCsv,
type AdminAuditLogClient,
type AdminAuditLogRow,
type LegacyEntityWebhookClient,
type LegacyLogWriterClient,
} from "./logs.server.js";
describe("legacy row log writes", () => {
it("normalizes nullable row log fields before writing", async () => {
const client: LegacyLogWriterClient = {
log: {
create: vi.fn().mockResolvedValue({ id: "log_1" }),
},
} as unknown as LegacyLogWriterClient;
await expect(
createLegacyRowLog(
{
tenantId: "tenant_1",
apiKeyId: "api_key_1",
url: "/api/contacts",
rowId: "row_1",
action: "created",
},
client,
),
).resolves.toEqual({ id: "log_1" });
expect(client.log.create).toHaveBeenCalledWith({
data: {
tenantId: "tenant_1",
userId: null,
apiKeyId: "api_key_1",
url: "/api/contacts",
rowId: "row_1",
action: "created",
details: null,
commentId: null,
},
});
});
it("redacts sensitive row log details before writing", async () => {
const client: LegacyLogWriterClient = {
log: {
create: vi.fn().mockResolvedValue({ id: "log_1" }),
},
} as unknown as LegacyLogWriterClient;
await createLegacyRowLog(
{
tenantId: "tenant_1",
url: "/api/contacts",
action: "updated",
details: JSON.stringify({ token: "secret-token", nested: { authorization: "Bearer secret", kept: "value" } }),
},
client,
);
const details = vi.mocked(client.log.create).mock.calls[0]?.[0].data.details;
expect(details).toBe('{"token":"[REDACTED]","nested":{"authorization":"[REDACTED]","kept":"value"}}');
expect(details).not.toContain("secret-token");
expect(details).not.toContain("Bearer secret");
});
});
describe("legacy entity webhook reads and logs", () => {
it("fetches entity webhooks for an action", async () => {
const client: LegacyEntityWebhookClient = {
entityWebhook: {
findMany: vi.fn().mockResolvedValue([{ id: "webhook_1", method: "POST", endpoint: "/hook" }]),
},
entityWebhookLog: {
create: vi.fn(),
},
} as unknown as LegacyEntityWebhookClient;
await expect(getLegacyEntityWebhooksByAction("entity_1", "Created", client)).resolves.toEqual([
{ id: "webhook_1", method: "POST", endpoint: "/hook" },
]);
expect(client.entityWebhook.findMany).toHaveBeenCalledWith({
where: {
entityId: "entity_1",
action: "Created",
},
});
});
it("records entity webhook delivery status", async () => {
const client: LegacyEntityWebhookClient = {
entityWebhook: {
findMany: vi.fn(),
},
entityWebhookLog: {
create: vi.fn().mockResolvedValue({ id: "webhook_log_1" }),
},
} as unknown as LegacyEntityWebhookClient;
await expect(createLegacyEntityWebhookLog({ webhookId: "webhook_1", logId: "log_1", status: 202 }, client)).resolves.toEqual({
id: "webhook_log_1",
});
expect(client.entityWebhookLog.create).toHaveBeenCalledWith({
data: {
webhookId: "webhook_1",
logId: "log_1",
status: 202,
},
});
});
});
describe("admin audit log list filters", () => {
it("builds focused where input from supported filters", () => {
const where = buildAuditLogWhereFromFilters({
q: " contact ",
action: "update",
url: "/api/contacts",
tenantId: "tenant_1",
userId: "user_1",
createdAtFrom: "2024-01-02T00:00:00.000Z",
createdAtTo: "2024-01-03T00:00:00.000Z",
});
expect(where).toEqual({
action: "update",
url: { contains: "/api/contacts", mode: "insensitive" },
tenantId: "tenant_1",
userId: "user_1",
createdAt: {
gte: new Date("2024-01-02T00:00:00.000Z"),
lte: new Date("2024-01-03T00:00:00.000Z"),
},
AND: [
{
OR: [
{ action: { contains: "contact", mode: "insensitive" } },
{ url: { contains: "contact", mode: "insensitive" } },
{ details: { contains: "contact", mode: "insensitive" } },
{ tenantId: { contains: "contact", mode: "insensitive" } },
{ userId: { contains: "contact", mode: "insensitive" } },
],
},
],
});
});
it("ignores malformed date filters", () => {
expect(buildAuditLogWhereFromFilters({ createdAtFrom: "not-a-date", createdAtTo: "2024-01-03T00:00:00.000Z" })).toEqual({
createdAt: { lte: new Date("2024-01-03T00:00:00.000Z") },
});
expect(buildAuditLogWhereFromFilters({ createdAtFrom: "not-a-date", createdAtTo: "still-not-a-date" })).toEqual({});
});
it("queries newest first with bounded pagination and shared where input", async () => {
const rows = [makeAuditRow({ id: "log_1" })];
const client: AdminAuditLogClient = {
log: {
findMany: vi.fn().mockResolvedValue(rows),
count: vi.fn().mockResolvedValue(7),
},
} as unknown as AdminAuditLogClient;
await expect(
getAdminAuditLogList({ action: "create", take: 999, skip: 2, createdAtFrom: "bad-date" }, client),
).resolves.toEqual({ rows, total: 7, take: 500, skip: 2 });
expect(client.log.findMany).toHaveBeenCalledWith({
where: { action: "create" },
include: {
user: { select: { id: true, email: true, firstName: true, lastName: true } },
tenant: { select: { id: true, name: true, slug: true } },
apiKey: { select: { id: true, alias: true } },
comment: { select: { id: true, value: true } },
},
orderBy: { createdAt: "desc" },
take: 500,
skip: 2,
});
expect(client.log.count).toHaveBeenCalledWith({ where: { action: "create" } });
});
});
describe("tenant audit log list filters", () => {
it("forces tenant scoping while composing supported filters", async () => {
const rows = [makeAuditRow({ id: "log_1" })];
const client: AdminAuditLogClient = {
log: {
findMany: vi.fn().mockResolvedValue(rows),
count: vi.fn().mockResolvedValue(3),
},
} as unknown as AdminAuditLogClient;
await expect(
getTenantAuditLogList(
"tenant_forced",
{
q: " contact ",
action: "update",
url: "/api/contacts",
userId: "user_1",
createdAtFrom: "2024-01-02T00:00:00.000Z",
createdAtTo: "2024-01-03T00:00:00.000Z",
take: 25,
skip: 5,
},
client,
),
).resolves.toEqual({ rows, total: 3, take: 25, skip: 5 });
const where = {
action: "update",
url: { contains: "/api/contacts", mode: "insensitive" },
tenantId: "tenant_forced",
userId: "user_1",
createdAt: {
gte: new Date("2024-01-02T00:00:00.000Z"),
lte: new Date("2024-01-03T00:00:00.000Z"),
},
AND: [
{
OR: [
{ action: { contains: "contact", mode: "insensitive" } },
{ url: { contains: "contact", mode: "insensitive" } },
{ details: { contains: "contact", mode: "insensitive" } },
{ tenantId: { contains: "contact", mode: "insensitive" } },
{ userId: { contains: "contact", mode: "insensitive" } },
],
},
],
};
expect(client.log.findMany).toHaveBeenCalledWith({
where,
include: {
user: { select: { id: true, email: true, firstName: true, lastName: true } },
tenant: { select: { id: true, name: true, slug: true } },
apiKey: { select: { id: true, alias: true } },
comment: { select: { id: true, value: true } },
},
orderBy: { createdAt: "desc" },
take: 25,
skip: 5,
});
expect(client.log.count).toHaveBeenCalledWith({ where });
});
it("ignores caller-provided tenant overrides and bounds pagination", async () => {
const client: AdminAuditLogClient = {
log: {
findMany: vi.fn().mockResolvedValue([]),
count: vi.fn().mockResolvedValue(0),
},
} as unknown as AdminAuditLogClient;
await expect(
getTenantAuditLogList("tenant_forced", { tenantId: "tenant_other", take: 9999, skip: -10, createdAtFrom: "bad-date", createdAtTo: "also-bad" }, client),
).resolves.toEqual({ rows: [], total: 0, take: 500, skip: 0 });
expect(client.log.findMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_forced" },
include: {
user: { select: { id: true, email: true, firstName: true, lastName: true } },
tenant: { select: { id: true, name: true, slug: true } },
apiKey: { select: { id: true, alias: true } },
comment: { select: { id: true, value: true } },
},
orderBy: { createdAt: "desc" },
take: 500,
skip: 0,
});
expect(client.log.count).toHaveBeenCalledWith({ where: { tenantId: "tenant_forced" } });
});
});
describe("serializeAdminAuditLogsCsv", () => {
it("serializes stable headers and empty optional relations without crashing", () => {
expect(
serializeAdminAuditLogsCsv([
makeAuditRow({
createdAt: new Date("2024-01-02T03:04:05.000Z"),
tenantId: null,
userId: null,
apiKeyId: null,
tenant: null,
user: null,
apiKey: null,
comment: null,
details: null,
}),
]),
).toBe(
'"Created At","Tenant","Actor","Actor Type","Action","URL","Details"\n"2024-01-02T03:04:05.000Z","","System","System","create","/api/contacts",""\n',
);
});
it("quotes commas, quotes, newlines, and formula-like values as text", () => {
const csv = serializeAdminAuditLogsCsv([
makeAuditRow({
createdAt: new Date("2024-01-02T03:04:05.000Z"),
action: "=cmd",
url: "/api/contacts,one",
details: 'Changed "field"\nnext line',
tenant: { id: "tenant_1", name: "+Tenant", slug: "tenant" },
user: { id: "user_1", email: "ada@example.com", firstName: "Ada", lastName: "Lovelace" },
}),
]);
expect(csv).toBe(
'"Created At","Tenant","Actor","Actor Type","Action","URL","Details"\n"2024-01-02T03:04:05.000Z","\'+Tenant","Ada Lovelace <ada@example.com>","User","\'=cmd","/api/contacts,one","Changed ""field""\nnext line"\n',
);
});
it("redacts sensitive details before CSV export", () => {
const csv = serializeAdminAuditLogsCsv([
makeAuditRow({ details: JSON.stringify({ token: "secret-token", kept: "value" }) }),
]);
expect(csv).toContain('"{""token"":""[REDACTED]"",""kept"":""value""}"');
expect(csv).not.toContain("secret-token");
});
it("exports detail redaction for UI display paths", () => {
expect(redactLogDetails("token=secret-token Authorization=Bearer secret")).toBe("token=[REDACTED] Authorization=Bearer [REDACTED]");
});
});
function makeAuditRow(overrides: Partial<AdminAuditLogRow> = {}): AdminAuditLogRow {
return {
id: "log_1",
createdAt: new Date("2024-01-01T00:00:00.000Z"),
tenantId: "tenant_1",
userId: "user_1",
apiKeyId: null,
rowId: null,
url: "/api/contacts",
action: "create",
details: "Created contact",
commentId: null,
tenant: { id: "tenant_1", name: "Tenant One", slug: "tenant-one" },
user: { id: "user_1", email: "user@example.com", firstName: "User", lastName: "One" },
apiKey: null,
comment: null,
...overrides,
};
}
@@ -0,0 +1,301 @@
import { getDbClient } from "./client.server.js";
import type { EntityWebhook, EntityWebhookLog, Log, Prisma } from "./prisma-browser.js";
export type LegacyEntityWebhook = Pick<EntityWebhook, "id" | "method" | "endpoint">;
export type LegacyRowLogCreateData = {
tenantId: string | null;
userId?: string | null;
apiKeyId?: string | null;
url: string;
rowId?: string | null;
action: string;
details?: string | null;
commentId?: string | null;
};
export type LegacyLogWriterClient = {
log: {
create(args: {
data: {
tenantId: string | null;
userId: string | null;
apiKeyId: string | null;
url: string;
rowId: string | null;
action: string;
details: string | null;
commentId: string | null;
};
}): Promise<Log>;
};
};
export type LegacyEntityWebhookClient = {
entityWebhook: {
findMany(args: { where: { entityId: string; action: string } }): Promise<LegacyEntityWebhook[]>;
};
entityWebhookLog: {
create(args: { data: { webhookId: string; logId: string; status: number } }): Promise<EntityWebhookLog>;
};
};
export type AdminAuditLogFilters = {
q?: string | null;
action?: string | null;
url?: string | null;
tenantId?: string | null;
userId?: string | null;
createdAtFrom?: string | Date | null;
createdAtTo?: string | Date | null;
};
export type AdminAuditLogListArgs = AdminAuditLogFilters & {
take?: number | null;
skip?: number | null;
};
export type TenantAuditLogFilters = Omit<AdminAuditLogFilters, "tenantId"> & {
tenantId?: string | null;
};
export type TenantAuditLogListArgs = TenantAuditLogFilters & {
take?: number | null;
skip?: number | null;
};
export type AdminAuditLogRow = Log & {
tenant?: { id: string; name: string; slug?: string | null } | null;
user?: { id: string; email: string; firstName?: string | null; lastName?: string | null } | null;
apiKey?: { id: string; alias: string } | null;
comment?: { id: string; value: string } | null;
};
export type AdminAuditLogListResult = {
rows: AdminAuditLogRow[];
total: number;
take: number;
skip: number;
};
export type AdminAuditLogClient = {
log: {
findMany(args: {
where: Prisma.LogWhereInput;
include: typeof adminAuditLogInclude;
orderBy: Prisma.LogOrderByWithRelationInput;
take: number;
skip: number;
}): Promise<AdminAuditLogRow[]>;
count(args: { where: Prisma.LogWhereInput }): Promise<number>;
};
};
export const adminAuditLogInclude = {
user: { select: { id: true, email: true, firstName: true, lastName: true } },
tenant: { select: { id: true, name: true, slug: true } },
apiKey: { select: { id: true, alias: true } },
comment: { select: { id: true, value: true } },
} satisfies Prisma.LogInclude;
const DEFAULT_AUDIT_LOG_TAKE = 50;
const MAX_AUDIT_LOG_TAKE = 500;
const CSV_HEADERS = ["Created At", "Tenant", "Actor", "Actor Type", "Action", "URL", "Details"] as const;
const FORMULA_PREFIX_PATTERN = /^[=+\-@\t\r]/;
const SENSITIVE_LOG_KEY_PATTERN = /authorization|cookie|password|secret|token|api[-_]?key|payload|body|header/i;
export function buildAuditLogWhereFromFilters(filters: AdminAuditLogFilters): Prisma.LogWhereInput {
const where: Prisma.LogWhereInput = {};
const and: Prisma.LogWhereInput[] = [];
const q = normalizeFilter(filters.q);
if (q) {
and.push({
OR: [
{ action: { contains: q, mode: "insensitive" } },
{ url: { contains: q, mode: "insensitive" } },
{ details: { contains: q, mode: "insensitive" } },
{ tenantId: { contains: q, mode: "insensitive" } },
{ userId: { contains: q, mode: "insensitive" } },
],
});
}
const action = normalizeFilter(filters.action);
if (action) where.action = action;
const url = normalizeFilter(filters.url);
if (url) where.url = { contains: url, mode: "insensitive" };
const tenantId = normalizeFilter(filters.tenantId);
if (tenantId) where.tenantId = tenantId;
const userId = normalizeFilter(filters.userId);
if (userId) where.userId = userId;
const createdAt: Prisma.DateTimeFilter<"Log"> = {};
const createdAtFrom = parseValidDate(filters.createdAtFrom);
const createdAtTo = parseValidDate(filters.createdAtTo);
if (createdAtFrom) createdAt.gte = createdAtFrom;
if (createdAtTo) createdAt.lte = createdAtTo;
if (Object.keys(createdAt).length > 0) where.createdAt = createdAt;
if (and.length > 0) where.AND = and;
return where;
}
export async function getAdminAuditLogList(
args: AdminAuditLogListArgs,
client: AdminAuditLogClient = getDbClient() as unknown as AdminAuditLogClient,
): Promise<AdminAuditLogListResult> {
const where = buildAuditLogWhereFromFilters(args);
return getAuditLogListWithWhere(where, args, client);
}
export async function getTenantAuditLogList(
tenantId: string,
args: TenantAuditLogListArgs,
client: AdminAuditLogClient = getDbClient() as unknown as AdminAuditLogClient,
): Promise<AdminAuditLogListResult> {
const where = buildAuditLogWhereFromFilters(args);
where.tenantId = tenantId;
return getAuditLogListWithWhere(where, args, client);
}
export function serializeAdminAuditLogsCsv(rows: readonly AdminAuditLogRow[]): string {
const lines = [CSV_HEADERS.map(escapeCsvCell).join(",")];
for (const row of rows) {
lines.push(
[row.createdAt.toISOString(), formatTenant(row), formatActor(row), getActorType(row), row.action, row.url, redactLogDetails(row.details)]
.map(escapeCsvCell)
.join(","),
);
}
return `${lines.join("\n")}\n`;
}
export async function createLegacyRowLog(data: LegacyRowLogCreateData, client: LegacyLogWriterClient = getDbClient() as unknown as LegacyLogWriterClient): Promise<Log> {
return client.log.create({
data: {
tenantId: data.tenantId,
userId: data.userId ?? null,
apiKeyId: data.apiKeyId ?? null,
url: data.url,
rowId: data.rowId ?? null,
action: data.action,
details: redactLogDetails(data.details),
commentId: data.commentId ?? null,
},
});
}
export async function getLegacyEntityWebhooksByAction(entityId: string, action: string, client: LegacyEntityWebhookClient = getDbClient() as unknown as LegacyEntityWebhookClient): Promise<LegacyEntityWebhook[]> {
return client.entityWebhook.findMany({ where: { entityId, action } });
}
export async function createLegacyEntityWebhookLog(data: { webhookId: string; logId: string; status: number }, client: LegacyEntityWebhookClient = getDbClient() as unknown as LegacyEntityWebhookClient): Promise<EntityWebhookLog> {
return client.entityWebhookLog.create({ data });
}
async function getAuditLogListWithWhere(
where: Prisma.LogWhereInput,
args: { take?: number | null; skip?: number | null },
client: AdminAuditLogClient,
): Promise<AdminAuditLogListResult> {
const take = normalizeTake(args.take);
const skip = normalizeSkip(args.skip);
const queryArgs = {
where,
include: adminAuditLogInclude,
orderBy: { createdAt: "desc" } satisfies Prisma.LogOrderByWithRelationInput,
take,
skip,
};
const [rows, total] = await Promise.all([client.log.findMany(queryArgs), client.log.count({ where })]);
return { rows, total, take, skip };
}
function normalizeFilter(value: string | null | undefined): string | undefined {
const normalized = value?.trim();
return normalized ? normalized : undefined;
}
function parseValidDate(value: string | Date | null | undefined): Date | undefined {
if (!value) return undefined;
const date = value instanceof Date ? value : new Date(value);
return Number.isNaN(date.getTime()) ? undefined : date;
}
function normalizeTake(value: number | null | undefined): number {
if (!Number.isFinite(value) || !value || value < 1) return DEFAULT_AUDIT_LOG_TAKE;
return Math.min(Math.trunc(value), MAX_AUDIT_LOG_TAKE);
}
function normalizeSkip(value: number | null | undefined): number {
if (!Number.isFinite(value) || !value || value < 0) return 0;
return Math.trunc(value);
}
function formatTenant(row: AdminAuditLogRow): string {
if (row.tenant) return row.tenant.name || row.tenant.slug || row.tenant.id;
return row.tenantId ?? "";
}
function formatActor(row: AdminAuditLogRow): string {
if (row.user) {
const name = [row.user.firstName, row.user.lastName].filter(Boolean).join(" ").trim();
return name ? `${name} <${row.user.email}>` : row.user.email;
}
if (row.apiKey) return row.apiKey.alias;
return row.userId ?? row.apiKeyId ?? "System";
}
function getActorType(row: AdminAuditLogRow): string {
if (row.userId || row.user) return "User";
if (row.apiKeyId || row.apiKey) return "API Key";
return "System";
}
function escapeCsvCell(value: unknown): string {
const stringValue = String(value ?? "");
const safeValue = FORMULA_PREFIX_PATTERN.test(stringValue) ? `'${stringValue}` : stringValue;
return `"${safeValue.replaceAll('"', '""')}"`;
}
export function redactLogDetails(details?: string | null): string | null {
if (!details) {
return details ?? null;
}
try {
return JSON.stringify(redactLogValue(JSON.parse(details)));
} catch {
return redactSensitiveText(details);
}
}
function redactLogValue(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map(redactLogValue);
}
if (value && typeof value === "object") {
return Object.fromEntries(
Object.entries(value as Record<string, unknown>).map(([key, entry]) => [key, SENSITIVE_LOG_KEY_PATTERN.test(key) ? "[REDACTED]" : redactLogValue(entry)]),
);
}
if (typeof value === "string") {
return redactSensitiveText(value);
}
return value;
}
function redactSensitiveText(value: string): string {
return value
.replace(/(authorization)\s*=\s*Bearer\s+\S+/gi, "$1=Bearer [REDACTED]")
.replace(/Bearer\s+\S+/gi, "Bearer [REDACTED]")
.replace(/(password|secret|token|api[-_]?key)=\S+/gi, "$1=[REDACTED]");
}
@@ -0,0 +1,159 @@
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
const repoRoot = resolve(__dirname, "../../..");
const schemaPath = resolve(repoRoot, "prisma/schema/notifications.prisma");
const migrationPath = resolve(repoRoot, "prisma/migrations/20260508143000_notifications_preferences/migration.sql");
const sourceKeyMigrationPath = resolve(repoRoot, "prisma/migrations/20260514010000_notification_delivery_source_key/migration.sql");
async function readSchema() {
return readFile(schemaPath, "utf8");
}
function modelBody(schema: string, modelName: string) {
const match = schema.match(new RegExp(`model ${modelName} \\{(?<body>[\\s\\S]*?)\\n\\}`));
expect(match?.groups?.body, `${modelName} model exists in notification Prisma schema`).toBeTruthy();
return match?.groups?.body ?? "";
}
describe("notification Prisma schema contract", () => {
it("defines delivery and preference enums for persisted notification records", async () => {
const schema = await readSchema();
expect(schema, "delivery status enum includes worker and reader lifecycle states").toMatch(
/enum\s+NotificationDeliveryStatus\s+\{[\s\S]*PENDING[\s\S]*SENT[\s\S]*FAILED[\s\S]*SKIPPED[\s\S]*READ[\s\S]*\}/,
);
expect(schema, "preference channel enum includes product-supported channels").toMatch(
/enum\s+NotificationPreferenceChannel\s+\{[\s\S]*IN_APP[\s\S]*EMAIL[\s\S]*\}/,
);
});
it("models delivery diagnostics without raw payload or header storage", async () => {
const deliveryModel = modelBody(await readSchema(), "NotificationDelivery");
expect(deliveryModel, "tenant diagnostic foreign key is nullable for retained diagnostics").toMatch(
/^\s*tenantId\s+String\?/m,
);
expect(deliveryModel, "user diagnostic foreign key is nullable for retained diagnostics").toMatch(
/^\s*userId\s+String\?/m,
);
expect(deliveryModel, "channel uses the shared preference channel enum").toMatch(
/^\s*channel\s+NotificationPreferenceChannel/m,
);
expect(deliveryModel, "category stores normalized notification grouping").toMatch(/^\s*category\s+String/m);
expect(deliveryModel, "messageKey stores the editorial notification identity").toMatch(/^\s*messageKey\s+String/m);
expect(deliveryModel, "sourceKey stores producer-stable delivery idempotency keys").toMatch(/^\s*sourceKey\s+String\?/m);
expect(deliveryModel, "status defaults new diagnostics to pending").toMatch(
/^\s*status\s+NotificationDeliveryStatus\s+@default\(PENDING\)/m,
);
expect(deliveryModel, "attempt counter defaults to zero").toMatch(/^\s*attemptsMade\s+Int\s+@default\(0\)/m);
expect(deliveryModel, "provider id is retained for external diagnostics").toMatch(
/^\s*providerMessageId\s+String\?/m,
);
expect(deliveryModel, "lastError stores bounded failure diagnostics").toMatch(/^\s*lastError\s+String\?/m);
expect(deliveryModel, "payload metadata stores redacted diagnostic metadata only").toMatch(
/^\s*payloadMetadata\s+Json\?/m,
);
expect(deliveryModel, "sentAt tracks provider completion").toMatch(/^\s*sentAt\s+DateTime\?/m);
expect(deliveryModel, "readAt tracks user read state").toMatch(/^\s*readAt\s+DateTime\?/m);
expect(deliveryModel, "tenant deletion preserves delivery diagnostics").toMatch(/onDelete:\s*SetNull/);
expect(deliveryModel, "user deletion preserves delivery diagnostics").toMatch(/user\s+User\?.*onDelete:\s*SetNull/);
expect(deliveryModel, "tenant/user/status lookup is indexed").toMatch(
/@@index\(\[tenantId,\s*userId,\s*status\],\s*name:\s*"notification_delivery_tenant_user_status_idx"\)/,
);
expect(deliveryModel, "tenant/channel/category lookup is indexed").toMatch(
/@@index\(\[tenantId,\s*channel,\s*category\],\s*name:\s*"notification_delivery_tenant_channel_category_idx"\)/,
);
expect(deliveryModel, "status/update diagnostics are indexed for worker inspection").toMatch(
/@@index\(\[status,\s*updatedAt\],\s*name:\s*"notification_delivery_status_updated_at_idx"\)/,
);
expect(deliveryModel, "logical deliveries are unique when a source key is supplied").toMatch(
/@@unique\(\[tenantId,\s*userId,\s*channel,\s*sourceKey\],\s*name:\s*"notification_delivery_source_key"\)/,
);
expect(deliveryModel, "raw notification payload must not be persisted").not.toMatch(/^\s*payload\s+/m);
expect(deliveryModel, "raw provider headers must not be persisted").not.toMatch(/^\s*headers\s+/m);
});
it("models tenant-scoped user notification preferences with unique normalized scope", async () => {
const preferenceModel = modelBody(await readSchema(), "UserNotificationPreference");
expect(preferenceModel, "tenant preference foreign key is required").toMatch(/^\s*tenantId\s+String/m);
expect(preferenceModel, "user preference foreign key is required").toMatch(/^\s*userId\s+String/m);
expect(preferenceModel, "channel uses the shared preference channel enum").toMatch(
/^\s*channel\s+NotificationPreferenceChannel/m,
);
expect(preferenceModel, "category stores normalized preference grouping").toMatch(/^\s*category\s+String/m);
expect(preferenceModel, "preferences default to enabled").toMatch(/^\s*enabled\s+Boolean\s+@default\(true\)/m);
expect(preferenceModel, "tenant preference rows cascade with tenant deletion").toMatch(/tenant\s+Tenant.*onDelete:\s*Cascade/);
expect(preferenceModel, "user preference rows cascade with user deletion").toMatch(/user\s+User.*onDelete:\s*Cascade/);
expect(preferenceModel, "preference scope is unique per tenant, user, channel, and category").toMatch(
/@@unique\(\[tenantId,\s*userId,\s*channel,\s*category\],\s*name:\s*"user_notification_preference_scope_key"\)/,
);
expect(preferenceModel, "tenant/user/category preference lookup is indexed").toMatch(
/@@index\(\[tenantId,\s*userId,\s*category\],\s*name:\s*"user_notification_preference_tenant_user_category_idx"\)/,
);
expect(preferenceModel, "tenant/category diagnostics are indexed").toMatch(
/@@index\(\[tenantId,\s*category\],\s*name:\s*"user_notification_preference_tenant_category_idx"\)/,
);
});
it("keeps the migration in sync with notification tables, constraints, indexes, and delete policies", async () => {
const migrationSql = await readFile(migrationPath, "utf8");
expect(migrationSql, "migration creates delivery status enum").toMatch(/CREATE\s+TYPE\s+"NotificationDeliveryStatus"\s+AS\s+ENUM\s+\('PENDING',\s*'SENT',\s*'FAILED',\s*'READ'\)/i);
expect(migrationSql, "migration creates preference channel enum").toMatch(/CREATE\s+TYPE\s+"NotificationPreferenceChannel"\s+AS\s+ENUM\s+\('IN_APP',\s*'EMAIL'\)/i);
expect(migrationSql, "migration creates NotificationDelivery table").toMatch(/CREATE\s+TABLE\s+"NotificationDelivery"/i);
expect(migrationSql, "delivery payloadMetadata is JSONB redacted metadata").toMatch(/"payloadMetadata"\s+JSONB/i);
expect(migrationSql, "delivery status defaults to pending").toMatch(
/"status"\s+"NotificationDeliveryStatus"\s+NOT\s+NULL\s+DEFAULT\s+'PENDING'/i,
);
expect(migrationSql, "delivery attempts default to zero").toMatch(/"attemptsMade"\s+INTEGER\s+NOT\s+NULL\s+DEFAULT\s+0/i);
expect(migrationSql, "migration creates UserNotificationPreference table").toMatch(
/CREATE\s+TABLE\s+"UserNotificationPreference"/i,
);
expect(migrationSql, "preference enabled flag defaults true").toMatch(
/"enabled"\s+BOOLEAN\s+NOT\s+NULL\s+DEFAULT\s+true/i,
);
expect(migrationSql, "preference scope unique key exists").toMatch(
/CREATE\s+UNIQUE\s+INDEX\s+"user_notification_preference_scope_key"\s+ON\s+"UserNotificationPreference"\("tenantId",\s*"userId",\s*"channel",\s*"category"\)/i,
);
expect(migrationSql, "delivery tenant/user/status index exists").toMatch(
/CREATE\s+INDEX\s+"notification_delivery_tenant_user_status_idx"\s+ON\s+"NotificationDelivery"\("tenantId",\s*"userId",\s*"status"\)/i,
);
expect(migrationSql, "delivery tenant/channel/category index exists").toMatch(
/CREATE\s+INDEX\s+"notification_delivery_tenant_channel_category_idx"\s+ON\s+"NotificationDelivery"\("tenantId",\s*"channel",\s*"category"\)/i,
);
expect(migrationSql, "preference tenant/user/category index exists").toMatch(
/CREATE\s+INDEX\s+"user_notification_preference_tenant_user_category_idx"\s+ON\s+"UserNotificationPreference"\("tenantId",\s*"userId",\s*"category"\)/i,
);
expect(migrationSql, "delivery tenant foreign key preserves diagnostics").toMatch(
/NotificationDelivery_tenantId_fkey[\s\S]*ON\s+DELETE\s+SET\s+NULL/i,
);
expect(migrationSql, "delivery user foreign key preserves diagnostics").toMatch(
/NotificationDelivery_userId_fkey[\s\S]*ON\s+DELETE\s+SET\s+NULL/i,
);
expect(migrationSql, "preference tenant foreign key cascades").toMatch(
/UserNotificationPreference_tenantId_fkey[\s\S]*ON\s+DELETE\s+CASCADE/i,
);
expect(migrationSql, "preference user foreign key cascades").toMatch(
/UserNotificationPreference_userId_fkey[\s\S]*ON\s+DELETE\s+CASCADE/i,
);
expect(migrationSql, "raw payload column must not be introduced").not.toMatch(/"payload"\s+/i);
expect(migrationSql, "raw header column must not be introduced").not.toMatch(/"headers"\s+/i);
});
it("adds a source key migration for idempotent notification deliveries", async () => {
const migrationSql = await readFile(sourceKeyMigrationPath, "utf8");
expect(migrationSql, "migration adds a nullable source key for existing delivery diagnostics").toMatch(
/ALTER\s+TABLE\s+"NotificationDelivery"\s+ADD\s+COLUMN\s+"sourceKey"\s+TEXT/i,
);
expect(migrationSql, "migration creates the logical delivery unique key").toMatch(
/CREATE\s+UNIQUE\s+INDEX\s+"notification_delivery_source_key"\s+ON\s+"NotificationDelivery"\("tenantId",\s*"userId",\s*"channel",\s*"sourceKey"\)/i,
);
});
});
@@ -0,0 +1,802 @@
import { describe, expect, it, vi } from "vitest";
import {
createNotificationDelivery,
getNotificationDeliveryDiagnostics,
getNotificationStreamSnapshot,
getUserNotificationPreferences,
markInAppNotificationDeliveryRead,
markNotificationDeliveryStatus,
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 }),
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: {
tenantId_userId_channel_category: {
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: {
tenantId_userId_channel_sourceKey: {
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("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("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",
},
{
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,
},
],
});
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" },
authorization: "Bearer secret-token",
body: "raw-body",
headers: { cookie: "secret" },
unknownField: "do-not-serialize",
},
]);
const snapshot = await getNotificationStreamSnapshot({ tenantId: "tenant_1", userId: "user_1" }, client);
const serialized = JSON.stringify(snapshot);
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,
});
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");
});
});
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,
markInAppNotificationDeliveryRead,
markNotificationDeliveryStatus,
getNotificationDeliveryDiagnostics,
getNotificationStreamSnapshot,
}),
);
});
it("exposes the notification boundary subpath export", async () => {
const notificationBoundary = await import("@toolctrl/db/notifications.server");
expect(notificationBoundary).toEqual(
expect.objectContaining({
upsertUserNotificationPreference,
getUserNotificationPreferences,
createNotificationDelivery,
markInAppNotificationDeliveryRead,
markNotificationDeliveryStatus,
getNotificationDeliveryDiagnostics,
getNotificationStreamSnapshot,
}),
);
});
});
@@ -0,0 +1,607 @@
import { getDbClient, type DbClient } from "./client.server.js";
export const NOTIFICATION_DELIVERY_LAST_ERROR_MAX_LENGTH = 2_000;
export const NOTIFICATION_PAYLOAD_METADATA_STRING_MAX_LENGTH = 500;
export type NotificationPreferenceChannel = "IN_APP" | "EMAIL";
export type NotificationDeliveryStatus = "PENDING" | "SENT" | "FAILED" | "SKIPPED" | "READ";
export type NotificationPayloadMetadata = Record<string, string | number | boolean | null>;
export type UserNotificationPreferenceInput = {
tenantId: string;
userId: string;
channel: string;
category?: string | null;
enabled?: boolean | null;
};
type UserNotificationPreferenceWriteData = UserNotificationPreferenceInput & {
channel: NotificationPreferenceChannel;
category: string;
enabled: boolean;
};
export type UserNotificationPreferenceClient = {
userNotificationPreference: {
upsert(args: {
where: {
tenantId_userId_channel_category: {
tenantId: string;
userId: string;
channel: NotificationPreferenceChannel;
category: string;
};
};
create: UserNotificationPreferenceWriteData;
update: { enabled: boolean };
}): Promise<unknown>;
findMany(args: {
where: {
tenantId: string;
userId: string;
channel?: NotificationPreferenceChannel;
category?: string;
};
orderBy: [{ category: "asc" }, { channel: "asc" }];
}): Promise<unknown[]>;
};
};
export type CreateNotificationDeliveryInput = {
tenantId: string;
userId?: string | null;
channel: string;
category?: string | null;
messageKey: string;
sourceKey?: string | null;
status?: NotificationDeliveryStatus | string | null;
attemptsMade?: number | null;
providerMessageId?: string | null;
lastError?: string | null;
payloadMetadata?: Record<string, unknown> | null;
sentAt?: Date | null;
readAt?: Date | null;
};
type NotificationDeliveryCreateData = {
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;
};
export type MarkNotificationDeliveryStatusInput = {
id: string;
tenantId: string;
status: NotificationDeliveryStatus | string;
attemptsMade?: number | null;
providerMessageId?: string | null;
lastError?: string | null;
sentAt?: Date | null;
readAt?: Date | null;
};
export type MarkInAppNotificationDeliveryReadInput = {
id: string;
tenantId: string;
userId: string;
readAt?: Date | null;
};
type NotificationDeliveryUpdateData = {
status: NotificationDeliveryStatus;
attemptsMade?: number;
providerMessageId?: string | null;
lastError?: string | null;
sentAt?: Date | null;
readAt?: Date | null;
};
type NotificationDeliveryUpdateResult = {
count?: number;
};
export type NotificationDeliveryDiagnosticsFilters = {
tenantId: string;
userId?: string | null;
status?: NotificationDeliveryStatus | string | null;
statuses?: Array<NotificationDeliveryStatus | string> | null;
channel?: string | null;
category?: string | null;
take?: number;
};
export type NotificationStreamCursor = string;
export type NotificationStreamItem = {
id: string;
cursor: NotificationStreamCursor;
tenantId: string | null;
userId: string | null;
channel: "IN_APP";
category: string;
messageKey: string;
status: NotificationDeliveryStatus;
attemptsMade: number;
createdAt: string;
updatedAt: string;
sentAt: string | null;
readAt: string | null;
};
export type NotificationStreamSnapshot = {
cursor: NotificationStreamCursor | null;
items: NotificationStreamItem[];
};
export type NotificationStreamSnapshotFilters = {
tenantId: string;
userId: string;
afterCursor?: NotificationStreamCursor | null;
take?: number;
};
export type NotificationDeliveryClient = {
notificationDelivery: {
create(args: { data: NotificationDeliveryCreateData }): Promise<unknown>;
upsert(args: {
where: {
tenantId_userId_channel_sourceKey: {
tenantId: string;
userId: string;
channel: NotificationPreferenceChannel;
sourceKey: string;
};
};
create: NotificationDeliveryCreateData;
update: Omit<NotificationDeliveryCreateData, "tenantId" | "userId" | "channel" | "sourceKey">;
}): Promise<unknown>;
update(args: { where: { id: string }; data: NotificationDeliveryUpdateData }): Promise<unknown>;
updateMany(args:
| {
where: { id: string; tenantId: string };
data: NotificationDeliveryUpdateData;
}
| {
where: { id: string; tenantId: string; userId: string; channel: "IN_APP"; status: "SENT" };
data: { status: "READ"; readAt: Date };
}): Promise<NotificationDeliveryUpdateResult>;
findMany(args: {
where: {
tenantId?: string | null;
userId?: string | null;
status?: NotificationDeliveryStatus | { in: NotificationDeliveryStatus[] };
channel?: NotificationPreferenceChannel;
category?: string;
};
orderBy: { createdAt: "desc" } | [{ updatedAt: "desc" }, { createdAt: "desc" }, { id: "desc" }];
take: number;
}): Promise<unknown[]>;
};
};
export type NotificationsClient = UserNotificationPreferenceClient & NotificationDeliveryClient;
const NOTIFICATION_CHANNELS = new Set<NotificationPreferenceChannel>(["IN_APP", "EMAIL"]);
const NOTIFICATION_STATUSES = new Set<NotificationDeliveryStatus>(["PENDING", "SENT", "FAILED", "SKIPPED", "READ"]);
const USER_VISIBLE_IN_APP_NOTIFICATION_STATUSES: NotificationDeliveryStatus[] = ["SENT", "READ"];
const USER_VISIBLE_IN_APP_NOTIFICATION_STATUS_SET = new Set<NotificationDeliveryStatus>(USER_VISIBLE_IN_APP_NOTIFICATION_STATUSES);
const SENSITIVE_METADATA_KEY_PATTERN = /authorization|cookie|password|secret|token|api[-_]?key|payload|body|header/i;
const NOTIFICATION_STREAM_DEFAULT_TAKE = 50;
const NOTIFICATION_STREAM_MAX_TAKE = 50;
function normalizeChannel(channel: string): NotificationPreferenceChannel {
const normalized = channel.trim().replace(/-/g, "_").toUpperCase();
if (NOTIFICATION_CHANNELS.has(normalized as NotificationPreferenceChannel)) {
return normalized as NotificationPreferenceChannel;
}
throw new Error(`Unsupported notification channel: ${channel}`);
}
function normalizeStatus(status: NotificationDeliveryStatus | string): NotificationDeliveryStatus {
const normalized = status.trim().replace(/-/g, "_").toUpperCase();
if (NOTIFICATION_STATUSES.has(normalized as NotificationDeliveryStatus)) {
return normalized as NotificationDeliveryStatus;
}
throw new Error(`Unsupported notification delivery status: ${status}`);
}
function normalizeStatuses(statuses?: Array<NotificationDeliveryStatus | string> | null): NotificationDeliveryStatus[] | undefined {
if (!statuses) {
return undefined;
}
const normalized = [...new Set(statuses.map((status) => normalizeStatus(status)))];
return normalized.length > 0 ? normalized : undefined;
}
function normalizeCategory(category?: string | null): string {
const normalized = category?.trim().toLowerCase();
return normalized ? normalized : "default";
}
function normalizeNullableString(value?: string | null): string | null {
const normalized = value?.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;
}
function requireNotificationPreferenceScope(input: { tenantId: string | null | undefined; userId: string | null | undefined }): { tenantId: string; userId: string } {
const tenantId = input.tenantId?.trim();
const userId = input.userId?.trim();
if (!tenantId || !userId) {
throw new Error("Notification preference tenant and user scope is required.");
}
return { tenantId, userId };
}
function truncateLastError(lastError?: string | null): string | null {
if (!lastError) {
return null;
}
return redactNotificationDiagnosticText(lastError).slice(0, NOTIFICATION_DELIVERY_LAST_ERROR_MAX_LENGTH);
}
export function redactNotificationDiagnosticText(value: string): string {
return value
.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, "Bearer [redacted]")
.replace(/\b(token|secret|api[-_]?key|apikey|password|code)\s*[:=]\s*[^&\s;,)"']+/gi, "$1=[redacted]")
.replace(/\b(payload|body|template)[-_ ]?secret\b/gi, "$1-[redacted]")
.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi, "[redacted-email]");
}
function sanitizePayloadMetadata(
payloadMetadata?: Record<string, unknown> | 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_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;
}
function normalizePreferenceInput(input: UserNotificationPreferenceInput): UserNotificationPreferenceWriteData {
const scope = requireNotificationPreferenceScope(input);
return {
tenantId: scope.tenantId,
userId: scope.userId,
channel: normalizeChannel(input.channel),
category: normalizeCategory(input.category),
enabled: input.enabled ?? true,
};
}
function normalizeStreamTake(take?: number): number {
if (typeof take !== "number" || !Number.isFinite(take)) {
return NOTIFICATION_STREAM_DEFAULT_TAKE;
}
return Math.max(0, Math.min(Math.trunc(take), NOTIFICATION_STREAM_MAX_TAKE));
}
function serializeDate(value: unknown): string | null {
if (value instanceof Date) {
return value.toISOString();
}
if (typeof value === "string") {
const parsed = new Date(value);
return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString();
}
return null;
}
function createNotificationStreamCursor(record: { id?: unknown; updatedAt?: unknown; createdAt?: unknown }): NotificationStreamCursor | null {
if (typeof record.id !== "string") {
return null;
}
const timestamp = serializeDate(record.updatedAt) ?? serializeDate(record.createdAt);
return timestamp ? `${timestamp}:${record.id}` : null;
}
function isAfterNotificationStreamCursor(
record: { id?: unknown; updatedAt?: unknown; createdAt?: unknown },
afterCursor?: NotificationStreamCursor | null,
): boolean {
if (!afterCursor) {
return true;
}
const cursor = createNotificationStreamCursor(record);
return cursor !== null && cursor > afterCursor;
}
function toNotificationStreamItem(record: unknown): NotificationStreamItem | null {
if (!record || typeof record !== "object") {
return null;
}
const delivery = record as Record<string, unknown>;
const cursor = createNotificationStreamCursor(delivery);
const createdAt = serializeDate(delivery.createdAt);
const updatedAt = serializeDate(delivery.updatedAt);
if (
!cursor ||
typeof delivery.id !== "string" ||
typeof delivery.category !== "string" ||
typeof delivery.messageKey !== "string" ||
!NOTIFICATION_STATUSES.has(delivery.status as NotificationDeliveryStatus) ||
typeof delivery.attemptsMade !== "number" ||
!createdAt ||
!updatedAt
) {
return null;
}
return {
id: delivery.id,
cursor,
tenantId: typeof delivery.tenantId === "string" ? delivery.tenantId : null,
userId: typeof delivery.userId === "string" ? delivery.userId : null,
channel: "IN_APP",
category: delivery.category,
messageKey: delivery.messageKey,
status: delivery.status as NotificationDeliveryStatus,
attemptsMade: delivery.attemptsMade,
createdAt,
updatedAt,
sentAt: serializeDate(delivery.sentAt),
readAt: serializeDate(delivery.readAt),
};
}
export async function upsertUserNotificationPreference(
input: UserNotificationPreferenceInput,
client: UserNotificationPreferenceClient = getDbClient() as DbClient & UserNotificationPreferenceClient,
): Promise<unknown> {
const data = normalizePreferenceInput(input);
return client.userNotificationPreference.upsert({
where: {
tenantId_userId_channel_category: {
tenantId: data.tenantId,
userId: data.userId,
channel: data.channel,
category: data.category,
},
},
create: data,
update: { enabled: data.enabled },
});
}
export async function getUserNotificationPreferences(
filters: { tenantId: string; userId: string; channel?: string | null; category?: string | null },
client: UserNotificationPreferenceClient = getDbClient() as DbClient & UserNotificationPreferenceClient,
): Promise<unknown[]> {
const scope = requireNotificationPreferenceScope(filters);
return client.userNotificationPreference.findMany({
where: {
tenantId: scope.tenantId,
userId: scope.userId,
...(filters.channel ? { channel: normalizeChannel(filters.channel) } : {}),
...(filters.category ? { category: normalizeCategory(filters.category) } : {}),
},
orderBy: [{ category: "asc" }, { channel: "asc" }],
});
}
export async function createNotificationDelivery(
input: CreateNotificationDeliveryInput,
client: NotificationDeliveryClient = getDbClient() as DbClient & NotificationDeliveryClient,
): Promise<unknown> {
const tenantId = requireNotificationTenantScope(input.tenantId);
const userId = normalizeNullableString(input.userId);
const channel = normalizeChannel(input.channel);
const sourceKey = normalizeNullableString(input.sourceKey);
const data: NotificationDeliveryCreateData = {
tenantId,
userId,
channel,
category: normalizeCategory(input.category),
messageKey: input.messageKey,
sourceKey,
status: input.status ? normalizeStatus(input.status) : "PENDING",
attemptsMade: input.attemptsMade ?? 0,
providerMessageId: input.providerMessageId ?? null,
lastError: truncateLastError(input.lastError),
payloadMetadata: sanitizePayloadMetadata(input.payloadMetadata),
sentAt: input.sentAt ?? null,
readAt: input.readAt ?? null,
};
if (sourceKey && userId) {
return client.notificationDelivery.upsert({
where: {
tenantId_userId_channel_sourceKey: {
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 markNotificationDeliveryStatus(
input: MarkNotificationDeliveryStatusInput,
client: NotificationDeliveryClient = getDbClient() as DbClient & NotificationDeliveryClient,
): Promise<unknown> {
const id = input.id.trim();
const tenantId = input.tenantId.trim();
if (!id || !tenantId) {
throw new Error("Notification delivery status scope is required.");
}
const result = await client.notificationDelivery.updateMany({
where: { id, tenantId },
data: {
status: normalizeStatus(input.status),
...(input.attemptsMade === undefined || input.attemptsMade === null ? {} : { attemptsMade: input.attemptsMade }),
...(input.providerMessageId === undefined ? {} : { providerMessageId: input.providerMessageId }),
...(input.lastError === undefined ? {} : { lastError: truncateLastError(input.lastError) }),
...(input.sentAt === undefined ? {} : { sentAt: input.sentAt }),
...(input.readAt === undefined ? {} : { readAt: input.readAt }),
},
});
if (typeof result.count === "number" && result.count !== 1) {
throw new Error("Notification delivery status update scope did not match exactly one delivery.");
}
return result;
}
export async function markInAppNotificationDeliveryRead(
input: MarkInAppNotificationDeliveryReadInput,
client: NotificationDeliveryClient = getDbClient() as DbClient & NotificationDeliveryClient,
): Promise<unknown> {
const id = input.id.trim();
const tenantId = input.tenantId.trim();
const userId = input.userId.trim();
if (!id || !tenantId || !userId) {
throw new Error("Notification delivery read scope is required.");
}
const result = await client.notificationDelivery.updateMany({
where: { id, tenantId, userId, channel: "IN_APP", status: "SENT" },
data: { status: "READ", readAt: input.readAt ?? new Date() },
});
if (typeof result.count === "number" && result.count !== 1) {
throw new Error("Notification delivery read scope did not match exactly one delivery.");
}
return result;
}
export async function getNotificationDeliveryDiagnostics(
filters: NotificationDeliveryDiagnosticsFilters,
client: NotificationDeliveryClient = getDbClient() as DbClient & NotificationDeliveryClient,
): Promise<unknown[]> {
const tenantId = requireNotificationTenantScope(filters.tenantId);
const statuses = normalizeStatuses(filters.statuses);
return client.notificationDelivery.findMany({
where: {
tenantId,
...(filters.userId === undefined ? {} : { userId: filters.userId }),
...(statuses ? { status: { in: statuses } } : filters.status ? { status: normalizeStatus(filters.status) } : {}),
...(filters.channel ? { channel: normalizeChannel(filters.channel) } : {}),
...(filters.category ? { category: normalizeCategory(filters.category) } : {}),
},
orderBy: { createdAt: "desc" },
take: filters.take ?? 100,
});
}
export async function getNotificationStreamSnapshot(
filters: NotificationStreamSnapshotFilters,
client: NotificationDeliveryClient = getDbClient() as DbClient & NotificationDeliveryClient,
): Promise<NotificationStreamSnapshot> {
const take = normalizeStreamTake(filters.take);
if (take === 0) {
return { cursor: null, items: [] };
}
const diagnostics = await client.notificationDelivery.findMany({
where: {
tenantId: filters.tenantId,
userId: filters.userId,
channel: "IN_APP",
status: { in: USER_VISIBLE_IN_APP_NOTIFICATION_STATUSES },
},
orderBy: [{ updatedAt: "desc" }, { createdAt: "desc" }, { id: "desc" }],
take: NOTIFICATION_STREAM_MAX_TAKE,
});
const items = diagnostics
.filter((record) => {
if (!record || typeof record !== "object") {
return false;
}
const delivery = record as Record<string, unknown>;
return delivery.tenantId === filters.tenantId && delivery.userId === filters.userId && USER_VISIBLE_IN_APP_NOTIFICATION_STATUS_SET.has(delivery.status as NotificationDeliveryStatus);
})
.filter((record) => isAfterNotificationStreamCursor(record as { id?: unknown; updatedAt?: unknown; createdAt?: unknown }, filters.afterCursor))
.map(toNotificationStreamItem)
.filter((item): item is NotificationStreamItem => item !== null)
.sort((left, right) => right.cursor.localeCompare(left.cursor))
.slice(0, take);
return {
cursor: items[0]?.cursor ?? null,
items,
};
}
@@ -0,0 +1,167 @@
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { createDbClient } from "./client.server.js";
import {
OUTBOX_CLAIM_DEFAULT_LIMIT,
OUTBOX_CLAIM_LEASE_MS,
claimPendingOutboxEvents,
} from "./outbox-claim.js";
const DATABASE_URL = process.env.DATABASE_URL?.trim();
// Vitest setup defaults DATABASE_URL to example.invalid so unit tests do
// not need a live Postgres. Opt into the real Postgres integration suite
// by exporting `OUTBOX_TEST_DATABASE_URL` or by pointing DATABASE_URL at
// a real Postgres (anything that is not the vitest example.invalid stub).
const integrationUrl =
process.env.OUTBOX_TEST_DATABASE_URL?.trim() ||
(DATABASE_URL && !DATABASE_URL.includes("example.invalid") ? DATABASE_URL : undefined);
const skipIntegration = !integrationUrl;
const describeIntegration = skipIntegration ? describe.skip : describe;
describeIntegration("claimPendingOutboxEvents (integration)", () => {
const prisma = createDbClient({ connectionString: integrationUrl });
beforeAll(async () => {
await prisma.$connect();
});
afterAll(async () => {
await prisma.outboxEvent.deleteMany({
where: { eventType: { startsWith: "test.claim." } },
});
await prisma.$disconnect();
});
beforeEach(async () => {
await prisma.outboxEvent.deleteMany({
where: { eventType: { startsWith: "test.claim." } },
});
});
it("claims up to `limit` pending events and flips them to PROCESSING", async () => {
const now = new Date("2026-05-17T08:00:00.000Z");
const past = new Date(now.getTime() - 60 * 1000);
await prisma.outboxEvent.createMany({
data: [
{ eventType: "test.claim.alpha", payload: { i: 1 }, scheduledAt: past, priority: 0 },
{ eventType: "test.claim.alpha", payload: { i: 2 }, scheduledAt: past, priority: 5 },
{ eventType: "test.claim.alpha", payload: { i: 3 }, scheduledAt: past, priority: 5 },
],
});
const claimed = await claimPendingOutboxEvents(prisma, { limit: 2, now });
expect(claimed).toHaveLength(2);
for (const event of claimed) {
expect(event.status).toBe("PROCESSING");
expect(event.lockedUntil).not.toBeNull();
}
// Highest priority is dispatched first.
expect(claimed.map((event) => event.priority)).toEqual([5, 5]);
});
it("skips events whose scheduledAt is in the future", async () => {
const now = new Date("2026-05-17T08:00:00.000Z");
const past = new Date(now.getTime() - 60 * 1000);
const future = new Date(now.getTime() + 60 * 1000);
await prisma.outboxEvent.createMany({
data: [
{ eventType: "test.claim.scheduled", payload: { i: 1 }, scheduledAt: past },
{ eventType: "test.claim.scheduled", payload: { i: 2 }, scheduledAt: future },
],
});
const claimed = await claimPendingOutboxEvents(prisma, { now });
expect(claimed).toHaveLength(1);
expect((claimed[0]?.payload as { i: number }).i).toBe(1);
});
it("never claims the same event twice when two callers race", async () => {
const now = new Date("2026-05-17T08:00:00.000Z");
const past = new Date(now.getTime() - 60 * 1000);
await prisma.outboxEvent.createMany({
data: Array.from({ length: 20 }, (_, index) => ({
eventType: "test.claim.race",
payload: { i: index },
scheduledAt: past,
})),
});
const [batchA, batchB] = await Promise.all([
claimPendingOutboxEvents(prisma, { limit: 50, now }),
claimPendingOutboxEvents(prisma, { limit: 50, now }),
]);
const ids = new Set<string>();
for (const event of [...batchA, ...batchB]) {
expect(ids.has(event.id)).toBe(false);
ids.add(event.id);
}
expect(ids.size).toBe(20);
});
it("recovers events stuck in PROCESSING past their lease", async () => {
const now = new Date("2026-05-17T08:00:00.000Z");
const expired = new Date(now.getTime() - 60 * 1000);
const created = await prisma.outboxEvent.create({
data: {
eventType: "test.claim.recovery",
payload: { i: 1 },
status: "PROCESSING",
lockedUntil: expired,
},
});
const claimed = await claimPendingOutboxEvents(prisma, { now });
expect(claimed).toHaveLength(1);
expect(claimed[0]?.id).toBe(created.id);
});
it("does not touch FAILED or DONE rows", async () => {
const now = new Date("2026-05-17T08:00:00.000Z");
const past = new Date(now.getTime() - 60 * 1000);
await prisma.outboxEvent.createMany({
data: [
{ eventType: "test.claim.terminal", payload: { i: 1 }, status: "FAILED", scheduledAt: past },
{ eventType: "test.claim.terminal", payload: { i: 2 }, status: "DONE", scheduledAt: past },
],
});
const claimed = await claimPendingOutboxEvents(prisma, { now });
expect(claimed).toHaveLength(0);
});
it("exposes documented constants", () => {
expect(OUTBOX_CLAIM_DEFAULT_LIMIT).toBe(100);
expect(OUTBOX_CLAIM_LEASE_MS).toBe(5 * 60 * 1000);
});
});
describe("claimPendingOutboxEvents (unit fallback)", () => {
it("returns empty array when $queryRaw returns non-array", async () => {
const fakePrisma = {
$queryRaw: (async () => null) as unknown as import("./outbox-claim.js").OutboxClaimRunner["$queryRaw"],
};
const claimed = await claimPendingOutboxEvents(fakePrisma);
expect(claimed).toEqual([]);
});
it("clamps limit to the configured bounds", async () => {
const captured: Array<unknown> = [];
const fakePrisma = {
$queryRaw: (async (sql: unknown) => {
captured.push(sql);
return [];
}) as unknown as import("./outbox-claim.js").OutboxClaimRunner["$queryRaw"],
};
await claimPendingOutboxEvents(fakePrisma, { limit: 999_999 });
await claimPendingOutboxEvents(fakePrisma, { limit: -5 });
await claimPendingOutboxEvents(fakePrisma, { limit: Number.NaN });
expect(captured).toHaveLength(3);
});
});
@@ -0,0 +1,108 @@
import { Prisma, type OutboxEvent } from "../generated/prisma/client/client.js";
/**
* Atomic claim-batch query for the outbox dispatcher.
*
* Uses `UPDATE ... WHERE id IN (SELECT ... FOR UPDATE SKIP LOCKED)
* RETURNING *` so that multiple dispatcher replicas can poll the same
* table without ever picking the same event twice. The claim:
*
* 1. Selects up to `limit` rows whose `status = 'PENDING'` and
* `scheduledAt <= now`. Higher priority first, then oldest first.
* 2. `FOR UPDATE SKIP LOCKED` makes concurrent claims race-free —
* replica B simply sees fewer rows when replica A already locked some.
* 3. Flips the rows to `PROCESSING` and sets `lockedUntil = now + leaseMs`
* so a crashed dispatcher's events get recovered by the next pass.
*
* Returns the freshly claimed rows; caller (dispatcher) then enqueues each
* payload to the appropriate BullMQ queue.
*
* See docs/architecture/outbox-pattern.md.
*/
/**
* Default lease: a claimed event must finish dispatching within this
* window or the next polling pass treats it as crashed and re-claims it
* (the recovery query filters on `lockedUntil < now`).
*/
export const OUTBOX_CLAIM_LEASE_MS = 5 * 60 * 1000;
/** Default batch size; can be overridden via `OUTBOX_DISPATCH_BATCH_SIZE`. */
export const OUTBOX_CLAIM_DEFAULT_LIMIT = 100;
export type OutboxClaimRunner = {
$queryRaw<T = unknown>(query: Prisma.Sql, ...values: unknown[]): Promise<T>;
};
export type ClaimPendingOutboxEventsOptions = {
/** Max events claimed in one pass. */
limit?: number;
/** Clock injection for deterministic tests. */
now?: Date;
/** Override the claim lease. */
leaseMs?: number;
};
/**
* Atomically claim a batch of pending outbox events. Returns the claimed
* rows with status set to PROCESSING and `lockedUntil = now + leaseMs`.
*
* Always runs on the write-primary (not a replica): the row update happens
* inside the same statement as the select, so the read-from-replica race
* window does not exist.
*/
export async function claimPendingOutboxEvents(
prisma: OutboxClaimRunner,
options: ClaimPendingOutboxEventsOptions = {}
): Promise<OutboxEvent[]> {
const limit = clampLimit(options.limit);
const now = options.now ?? new Date();
const leaseMs = options.leaseMs ?? OUTBOX_CLAIM_LEASE_MS;
const lockedUntil = new Date(now.getTime() + leaseMs);
// Drift recovery: rows stuck in PROCESSING past their lease are treated
// as crashed and become eligible for re-claim. The status filter accepts
// either PENDING (normal) or PROCESSING-with-expired-lockedUntil.
const sql = Prisma.sql`
UPDATE "OutboxEvent"
SET "status" = 'PROCESSING',
"lockedUntil" = ${lockedUntil}
WHERE "id" IN (
SELECT "id"
FROM "OutboxEvent"
WHERE (
("status" = 'PENDING' AND "scheduledAt" <= ${now})
OR ("status" = 'PROCESSING' AND "lockedUntil" IS NOT NULL AND "lockedUntil" < ${now})
)
ORDER BY "priority" DESC, "createdAt" ASC
LIMIT ${limit}
FOR UPDATE SKIP LOCKED
)
RETURNING
"id",
"tenantId",
"eventType",
"payload",
"status",
"createdAt",
"processedAt",
"retries",
"lastError",
"scheduledAt",
"dispatchKey",
"priority",
"lockedUntil"
`;
const rows = await prisma.$queryRaw<OutboxEvent[]>(sql);
return Array.isArray(rows) ? rows : [];
}
function clampLimit(limit: number | undefined): number {
if (typeof limit !== "number" || !Number.isFinite(limit)) {
return OUTBOX_CLAIM_DEFAULT_LIMIT;
}
if (limit < 1) return 1;
if (limit > 1000) return 1000;
return Math.floor(limit);
}
@@ -0,0 +1,270 @@
/**
* End-to-end outbox integration test (Phase 03 #42).
*
* Provisions a real Postgres connection (via env var) and exercises the
* full producer → dispatcher → receiver pipeline:
*
* 1. Publish a synthetic `audit.test.fired` event from inside a Prisma
* transaction via {@link publishOutboxEvent}.
* 2. Claim the event via the production `claimPendingOutboxEvents`
* query (FOR UPDATE SKIP LOCKED). This represents the dispatcher
* tick. A custom prefix-routing rule maps `audit.test.` → a
* capture queue (in-memory Map), proving the routing pattern
* works for fan-out without touching production routing rules.
* 3. Invoke a test receiver against the captured envelope. The
* receiver writes a "marker" row (a follow-on OutboxEvent with
* eventType `audit.test.persisted`) — this stands in for the
* AuditEvent insert that the real audit-event receiver performs,
* and uses only schema that's guaranteed to exist on every
* Postgres the suite runs against. Persistence is wrapped in
* {@link withOutboxIdempotency} so a duplicate delivery is a
* no-op.
* 4. Assert exactly one marker exists, then re-invoke the receiver
* with the same envelope and assert the marker count stays at
* one.
*
* Opt-in via env vars, matching `outbox-claim.test.ts`:
* - OUTBOX_E2E_DATABASE_URL — Postgres URL to use, or
* - DATABASE_URL — when not the example.invalid sentinel
*
* Redis is not required: the dispatcher tick runs with an in-memory
* enqueue function, which is the same seam the unit tests use. The
* test still represents the dispatcher's full transactional contract
* against a real Postgres (claim + status flip).
*/
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import type { Prisma } from "../generated/prisma/client/client.js";
import { createDbClient } from "./client.server.js";
import { publishOutboxEvent, type OutboxPublisherTransaction } from "./outbox.js";
import { claimPendingOutboxEvents } from "./outbox-claim.js";
import {
withOutboxIdempotency,
type OutboxReceiverIdempotencyStore,
} from "./outbox-receiver.js";
const DATABASE_URL = process.env.DATABASE_URL?.trim();
const integrationUrl =
process.env.OUTBOX_E2E_DATABASE_URL?.trim() ||
(DATABASE_URL && !DATABASE_URL.includes("example.invalid") ? DATABASE_URL : undefined);
const skipIntegration = !integrationUrl;
const describeIntegration = skipIntegration ? describe.skip : describe;
const TEST_EVENT_TYPE = "audit.test.fired";
const TEST_MARKER_TYPE = "audit.test.persisted";
const TEST_QUEUE = "outbox.test-capture";
interface CapturedEnvelope {
outboxEventId: string;
tenantId: string | null;
eventType: string;
payload: unknown;
}
function inMemoryIdempotency(): OutboxReceiverIdempotencyStore & {
forget(key: string): Promise<void>;
} {
const claimed = new Set<string>();
const completed = new Map<string, unknown>();
return {
async claim(key: string): Promise<boolean> {
if (claimed.has(key) || completed.has(key)) return false;
claimed.add(key);
return true;
},
async complete(key: string, result: unknown): Promise<void> {
claimed.delete(key);
completed.set(key, result);
},
async get(key: string) {
if (completed.has(key)) {
return { state: "complete" as const, result: completed.get(key) };
}
if (claimed.has(key)) {
return { state: "pending" as const };
}
return null;
},
async forget(key: string): Promise<void> {
claimed.delete(key);
completed.delete(key);
},
};
}
describeIntegration("outbox end-to-end (integration)", () => {
const prisma = createDbClient({ connectionString: integrationUrl });
async function cleanupTestRows(): Promise<void> {
await prisma.outboxEvent.deleteMany({
where: { eventType: { startsWith: "audit.test." } },
});
}
beforeAll(async () => {
await prisma.$connect();
});
afterAll(async () => {
await cleanupTestRows();
await prisma.$disconnect();
});
beforeEach(async () => {
await cleanupTestRows();
});
it("publishes → claims → dispatches → persists → idempotent re-delivery", async () => {
const tenantId = `e2e-tenant-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const dispatchKey = `outbox-e2e:${tenantId}:fired`;
// 1. Producer: write the outbox event inside a transaction. This is
// the only way `publishOutboxEvent` accepts (TransactionClient
// type-guard). A real producer would write business rows in the
// same tx; here the outbox row is the only side effect.
const published = await prisma.$transaction(async (tx) => {
const event = await publishOutboxEvent(tx as unknown as OutboxPublisherTransaction, {
tenantId,
type: TEST_EVENT_TYPE,
payload: {
tenantId,
message: "outbox e2e fired",
firedAt: new Date().toISOString(),
},
dispatchKey,
});
return event;
});
expect(published.id).toBeTruthy();
expect(published.status).toBe("PENDING");
// Idempotent publish: only one outbox row exists for the
// dispatchKey, regardless of how many times a producer attempts
// to insert under it. (Real producers run each attempt in a
// separate transaction; we assert via count rather than re-running
// publishOutboxEvent here.)
const sameKeyCount = await prisma.outboxEvent.count({
where: { dispatchKey },
});
expect(sameKeyCount).toBe(1);
// 2. Dispatcher tick: claim the pending event via the production
// FOR UPDATE SKIP LOCKED query, "enqueue" it (here: capture
// into a list keyed by queue name), and flip status to DONE.
// This mirrors `runDispatcherTick` in the worker bundle exactly
// — we inline it so this package doesn't depend on apps/worker.
const captures: CapturedEnvelope[] = [];
const now = new Date();
const claimed = await claimPendingOutboxEvents(prisma, { limit: 50, now });
const ours = claimed.find((row) => row.id === published.id);
expect(ours, "the published event must be claimed").toBeDefined();
expect(ours!.status).toBe("PROCESSING");
expect(ours!.lockedUntil).not.toBeNull();
// Custom routing: audit.test.* → capture queue. Proves the
// prefix-routing pattern fan-outs correctly to a queue not
// declared in production rules.
const queue = ours!.eventType.startsWith("audit.test.") ? TEST_QUEUE : undefined;
expect(queue).toBe(TEST_QUEUE);
captures.push({
outboxEventId: ours!.id,
tenantId: ours!.tenantId,
eventType: ours!.eventType,
payload: ours!.payload,
});
await prisma.outboxEvent.update({
where: { id: ours!.id },
data: {
status: "DONE",
processedAt: now,
lockedUntil: null,
lastError: null,
},
});
const after = await prisma.outboxEvent.findUnique({ where: { id: published.id } });
expect(after?.status).toBe("DONE");
// 3. Receiver: pretend BullMQ just delivered the captured envelope
// to a subscriber. The receiver writes a "marker" row (a
// follow-on OutboxEvent in DONE state) — stands in for the
// real-world AuditEvent insert that audit-event-persist.ts
// performs. Wrapped in withOutboxIdempotency so re-delivery is
// a no-op.
expect(captures).toHaveLength(1);
const envelope = captures[0]!;
const idem = inMemoryIdempotency();
const persistMarker = async (): Promise<{ id: string }> => {
const inserted = await prisma.$transaction(async (tx) => {
return publishOutboxEvent(tx as unknown as OutboxPublisherTransaction, {
tenantId: envelope.tenantId,
type: TEST_MARKER_TYPE,
payload: {
persistedFor: envelope.outboxEventId,
originalPayload: envelope.payload as Prisma.InputJsonValue,
},
dispatchKey: `outbox-e2e:marker:${envelope.outboxEventId}`,
});
});
return { id: inserted.id };
};
const first = await withOutboxIdempotency(idem, envelope.outboxEventId, persistMarker);
expect(first.status).toBe("executed");
const markers = await prisma.outboxEvent.findMany({
where: { eventType: TEST_MARKER_TYPE, tenantId },
select: { id: true, dispatchKey: true },
});
expect(markers).toHaveLength(1);
// 4. Idempotent re-delivery: handing the same envelope to the
// receiver a second time MUST be a no-op. The marker count
// stays at one.
const second = await withOutboxIdempotency(idem, envelope.outboxEventId, persistMarker);
expect(second.status).toBe("skipped");
const markersAfter = await prisma.outboxEvent.findMany({
where: { eventType: TEST_MARKER_TYPE, tenantId },
select: { id: true },
});
expect(markersAfter).toHaveLength(1);
expect(markersAfter[0]!.id).toBe(markers[0]!.id);
});
it("future-scheduled events are not claimed by the dispatcher tick", async () => {
const tenantId = `e2e-tenant-future-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const futureAt = new Date(Date.now() + 60 * 60 * 1000);
const event = await prisma.$transaction(async (tx) => {
return publishOutboxEvent(tx as unknown as OutboxPublisherTransaction, {
tenantId,
type: TEST_EVENT_TYPE,
payload: { tenantId, scheduled: true },
scheduledAt: futureAt,
});
});
const claimed = await claimPendingOutboxEvents(prisma, { limit: 50, now: new Date() });
expect(claimed.some((row) => row.id === event.id)).toBe(false);
// Sanity: re-claiming with `now` past the scheduled time picks it up.
const claimed2 = await claimPendingOutboxEvents(prisma, {
limit: 50,
now: new Date(futureAt.getTime() + 1_000),
});
expect(claimed2.some((row) => row.id === event.id)).toBe(true);
});
});
// Unit-fallback test ensuring the suite doesn't trivially pass when
// skipped. Always runs, independent of any real Postgres.
describe("outbox-e2e harness invariants", () => {
it("opt-in env vars match the outbox-claim test contract", () => {
expect(typeof TEST_EVENT_TYPE).toBe("string");
expect(TEST_EVENT_TYPE.startsWith("audit.test.")).toBe(true);
expect(TEST_MARKER_TYPE.startsWith("audit.test.")).toBe(true);
});
});
@@ -0,0 +1,98 @@
import { describe, expect, it, vi } from "vitest";
import {
OutboxReceiverPendingError,
withOutboxIdempotency,
type OutboxReceiverIdempotencyEntry,
type OutboxReceiverIdempotencyStore,
} from "./outbox-receiver.js";
function createStore(initial?: {
claimResult?: boolean;
existing?: OutboxReceiverIdempotencyEntry | null;
}): OutboxReceiverIdempotencyStore & { forget(key: string): Promise<void> } {
return {
claim: vi.fn(async () => initial?.claimResult ?? true),
complete: vi.fn(async () => undefined),
get: vi.fn(async () => initial?.existing ?? null),
forget: vi.fn(async () => undefined),
};
}
describe("withOutboxIdempotency", () => {
it("executes the handler and marks the key complete on success", async () => {
const store = createStore();
const handler = vi.fn(async () => "result");
const outcome = await withOutboxIdempotency(store, "evt_1", handler);
expect(handler).toHaveBeenCalledTimes(1);
expect(outcome).toEqual({ status: "executed", result: "result" });
expect(store.claim).toHaveBeenCalledWith("outbox:evt_1");
expect(store.complete).toHaveBeenCalledWith("outbox:evt_1", "result");
expect(store.forget).not.toHaveBeenCalled();
});
it("skips and returns cached result when claim fails (already complete)", async () => {
const store = createStore({
claimResult: false,
existing: { state: "complete", result: "cached" },
});
const handler = vi.fn(async () => "should-not-run");
const outcome = await withOutboxIdempotency(store, "evt_2", handler);
expect(handler).not.toHaveBeenCalled();
expect(outcome).toEqual({ status: "skipped", result: "cached" });
});
it("throws a retryable pending error when claim fails and entry is still pending", async () => {
const store = createStore({
claimResult: false,
existing: { state: "pending" },
});
const handler = vi.fn();
await expect(withOutboxIdempotency(store, "evt_3", handler)).rejects.toBeInstanceOf(OutboxReceiverPendingError);
expect(handler).not.toHaveBeenCalled();
});
it("releases the claim when the handler throws so retries can re-claim", async () => {
const store = createStore();
const handler = vi.fn(async () => {
throw new Error("boom");
});
await expect(withOutboxIdempotency(store, "evt_4", handler)).rejects.toThrow("boom");
expect(store.forget).toHaveBeenCalledWith("outbox:evt_4");
expect(store.complete).not.toHaveBeenCalled();
});
it("tolerates a missing forget() implementation when the handler throws", async () => {
const minimal: OutboxReceiverIdempotencyStore = {
claim: vi.fn(async () => true),
complete: vi.fn(async () => undefined),
get: vi.fn(async () => null),
};
const handler = vi.fn(async () => {
throw new Error("nope");
});
await expect(withOutboxIdempotency(minimal, "evt_5", handler)).rejects.toThrow("nope");
expect(minimal.complete).not.toHaveBeenCalled();
});
it("tolerates complete() failure after a successful handler run", async () => {
const store: OutboxReceiverIdempotencyStore = {
claim: vi.fn(async () => true),
complete: vi.fn(async () => {
throw new Error("redis transient");
}),
get: vi.fn(async () => null),
};
const handler = vi.fn(async () => 42);
const outcome = await withOutboxIdempotency(store, "evt_6", handler);
expect(outcome).toEqual({ status: "executed", result: 42 });
});
});
@@ -0,0 +1,75 @@
/**
* Receiver-side idempotency helper for the outbox pattern.
*
* The dispatcher provides at-least-once delivery — if a receiver crashes
* after enqueueing succeeds but before processing finishes, the same
* BullMQ job may be re-delivered. Wrapping a handler in
* `withOutboxIdempotency(eventId, handler)` ensures the effect happens
* exactly once even under duplicate delivery, by claiming a key in the
* SharedStore-backed IdempotencyStore before running the handler.
*
* See docs/architecture/outbox-pattern.md.
*/
export type OutboxReceiverIdempotencyEntry =
| { state: "pending"; result?: undefined }
| { state: "complete"; result: unknown };
/**
* Minimal IdempotencyStore shape — keeps this helper testable without
* pulling the full SharedStore types.
*/
export interface OutboxReceiverIdempotencyStore {
claim(key: string): Promise<boolean>;
complete(key: string, result: unknown): Promise<void>;
get(key: string): Promise<OutboxReceiverIdempotencyEntry | null>;
}
export type WithOutboxIdempotencyResult<T> =
| { status: "executed"; result: T }
| { status: "skipped"; result: unknown };
export class OutboxReceiverPendingError extends Error {
override readonly name = "OutboxReceiverPendingError";
constructor(readonly key: string) {
super(`Outbox receiver key ${key} is already pending; retry delivery later.`);
}
}
export async function withOutboxIdempotency<T>(
store: OutboxReceiverIdempotencyStore & { forget?(key: string): Promise<void> },
eventId: string,
handler: () => Promise<T>
): Promise<WithOutboxIdempotencyResult<T>> {
const key = `outbox:${eventId}`;
const claimed = await store.claim(key);
if (!claimed) {
const existing = await store.get(key);
if (existing?.state === "pending") {
throw new OutboxReceiverPendingError(key);
}
return { status: "skipped", result: existing?.result };
}
let result: T;
try {
result = await handler();
} catch (error) {
if (typeof store.forget === "function") {
try {
await store.forget(key);
} catch {
// Failure to release the claim must not mask the original error.
}
}
throw error;
}
try {
await store.complete(key, result);
} catch {
// Best-effort idempotency: handler already succeeded.
}
return { status: "executed", result };
}
@@ -0,0 +1,40 @@
import { describe, expect, it, vi } from "vitest";
import {
OUTBOX_DONE_RETENTION_DEFAULT_TAKE,
OUTBOX_DONE_RETENTION_MAX_TAKE,
clampDoneRetentionTake,
deleteDoneOutboxEvents,
type OutboxDoneRetentionRunner,
} from "./outbox-retention.js";
describe("deleteDoneOutboxEvents", () => {
it("deletes bounded DONE rows older than the cutoff without loading payloads", async () => {
const execute = vi.fn(async () => 42);
const prisma: OutboxDoneRetentionRunner = {
$executeRaw: execute as unknown as OutboxDoneRetentionRunner["$executeRaw"],
};
const cutoff = new Date("2026-05-01T00:00:00.000Z");
const result = await deleteDoneOutboxEvents(prisma, { cutoff, take: 2500 });
expect(result).toEqual({ deleted: 42, cutoff, take: 2500 });
expect(execute).toHaveBeenCalledTimes(1);
const firstCall = execute.mock.calls as unknown as Array<[unknown]>;
const query = firstCall[0]?.[0] as { strings?: readonly string[] };
const sqlText = query.strings?.join("?");
expect(sqlText).toContain("WHERE \"status\" = 'DONE'");
expect(sqlText).toContain("\"processedAt\" IS NOT NULL");
expect(sqlText).toContain("\"processedAt\" <");
expect(sqlText).toContain("FOR UPDATE SKIP LOCKED");
expect(sqlText).toContain("DELETE FROM \"OutboxEvent\"");
});
it("clamps batch sizes to the documented retention bounds", () => {
expect(clampDoneRetentionTake(undefined)).toBe(OUTBOX_DONE_RETENTION_DEFAULT_TAKE);
expect(clampDoneRetentionTake(Number.NaN)).toBe(OUTBOX_DONE_RETENTION_DEFAULT_TAKE);
expect(clampDoneRetentionTake(0)).toBe(1);
expect(clampDoneRetentionTake(1.9)).toBe(1);
expect(clampDoneRetentionTake(OUTBOX_DONE_RETENTION_MAX_TAKE + 1)).toBe(OUTBOX_DONE_RETENTION_MAX_TAKE);
});
});
@@ -0,0 +1,55 @@
import { Prisma } from "../generated/prisma/client/client.js";
export const OUTBOX_DONE_RETENTION_DEFAULT_TAKE = 1000;
export const OUTBOX_DONE_RETENTION_MAX_TAKE = 10_000;
export type OutboxDoneRetentionRunner = {
$executeRaw(query: Prisma.Sql, ...values: unknown[]): Promise<number>;
};
export type DeleteDoneOutboxEventsOptions = {
cutoff: Date;
take?: number;
};
export type DeleteDoneOutboxEventsResult = {
deleted: number;
cutoff: Date;
take: number;
};
export async function deleteDoneOutboxEvents(
prisma: OutboxDoneRetentionRunner,
options: DeleteDoneOutboxEventsOptions
): Promise<DeleteDoneOutboxEventsResult> {
const take = clampDoneRetentionTake(options.take);
const deleted = await prisma.$executeRaw(Prisma.sql`
WITH doomed AS (
SELECT "id"
FROM "OutboxEvent"
WHERE "status" = 'DONE'
AND "processedAt" IS NOT NULL
AND "processedAt" < ${options.cutoff}
ORDER BY "processedAt" ASC
LIMIT ${take}
FOR UPDATE SKIP LOCKED
)
DELETE FROM "OutboxEvent"
WHERE "id" IN (SELECT "id" FROM doomed)
`);
return {
deleted,
cutoff: options.cutoff,
take,
};
}
export function clampDoneRetentionTake(take: number | undefined): number {
if (typeof take !== "number" || !Number.isFinite(take)) {
return OUTBOX_DONE_RETENTION_DEFAULT_TAKE;
}
if (take < 1) return 1;
if (take > OUTBOX_DONE_RETENTION_MAX_TAKE) return OUTBOX_DONE_RETENTION_MAX_TAKE;
return Math.floor(take);
}
@@ -0,0 +1,217 @@
import { describe, expect, it, vi } from "vitest";
import type { OutboxEvent, Prisma } from "../generated/prisma/client/client.js";
import {
OUTBOX_DISPATCH_KEY_PATTERN,
OUTBOX_EVENT_TYPE_PATTERN,
OUTBOX_MAX_PAYLOAD_BYTES,
OutboxPublishError,
publishOutboxEvent,
type OutboxEventWriterTx,
type OutboxPublisherTransaction,
} from "./outbox.js";
type FakeTx = OutboxEventWriterTx & { __isFakeTx: true };
function createFakeTx(overrides?: {
create?: OutboxEventWriterTx["outboxEvent"]["create"];
findUnique?: OutboxEventWriterTx["outboxEvent"]["findUnique"];
}): FakeTx {
const defaultCreate: OutboxEventWriterTx["outboxEvent"]["create"] = vi.fn(async ({ data }) => ({
id: "outbox_event_1",
tenantId: data.tenantId ?? null,
eventType: data.eventType,
payload: data.payload as Prisma.JsonValue,
status: data.status ?? "PENDING",
createdAt: new Date("2026-05-17T08:00:00.000Z"),
processedAt: null,
retries: data.retries ?? 0,
lastError: null,
scheduledAt: data.scheduledAt ? new Date(data.scheduledAt) : new Date("2026-05-17T08:00:00.000Z"),
dispatchKey: data.dispatchKey ?? null,
priority: data.priority ?? 0,
lockedUntil: null,
}) as OutboxEvent);
const defaultFindUnique: OutboxEventWriterTx["outboxEvent"]["findUnique"] = vi.fn(async () => null);
return {
__isFakeTx: true,
outboxEvent: {
create: overrides?.create ?? defaultCreate,
findUnique: overrides?.findUnique ?? defaultFindUnique,
},
};
}
function asPublisherTx(tx: FakeTx): OutboxPublisherTransaction {
return tx as unknown as OutboxPublisherTransaction;
}
describe("publishOutboxEvent", () => {
it("inserts an event with sensible defaults", async () => {
const tx = createFakeTx();
const created = await publishOutboxEvent(asPublisherTx(tx), {
tenantId: "tenant_1",
type: "billing.subscription.updated",
payload: { customerId: "cus_1" },
});
expect(tx.outboxEvent.create).toHaveBeenCalledTimes(1);
const createCall = (tx.outboxEvent.create as unknown as { mock: { calls: Array<[{ data: Prisma.OutboxEventUncheckedCreateInput }]> } }).mock.calls[0]?.[0];
expect(createCall?.data).toMatchObject({
tenantId: "tenant_1",
eventType: "billing.subscription.updated",
payload: { customerId: "cus_1" },
dispatchKey: null,
});
// scheduledAt/priority default to DB defaults — they are NOT passed when undefined.
expect(createCall?.data.scheduledAt).toBeUndefined();
expect(createCall?.data.priority).toBeUndefined();
expect(created.eventType).toBe("billing.subscription.updated");
});
it("passes scheduledAt and priority when provided", async () => {
const tx = createFakeTx();
const future = new Date("2026-05-17T10:00:00.000Z");
await publishOutboxEvent(asPublisherTx(tx), {
tenantId: null,
type: "audit.log.recorded",
payload: { actor: "system" },
scheduledAt: future,
priority: 10,
});
const callArgs = (tx.outboxEvent.create as unknown as { mock: { calls: Array<[{ data: Prisma.OutboxEventUncheckedCreateInput }]> } }).mock.calls[0]?.[0];
expect(callArgs?.data.scheduledAt).toBe(future);
expect(callArgs?.data.priority).toBe(10);
expect(callArgs?.data.tenantId).toBeNull();
});
it("returns the existing event when dispatchKey already exists", async () => {
const existing: OutboxEvent = {
id: "outbox_event_existing",
tenantId: "tenant_1",
eventType: "mail.send.queued",
payload: { to: "u@example.com" } as Prisma.JsonValue,
status: "PENDING",
createdAt: new Date("2026-05-17T07:00:00.000Z"),
processedAt: null,
retries: 0,
lastError: null,
scheduledAt: new Date("2026-05-17T07:00:00.000Z"),
dispatchKey: "stripe:evt_1ABC",
priority: 0,
lockedUntil: null,
};
const uniqueError = Object.assign(new Error("Unique constraint failed"), { code: "P2002" });
const tx = createFakeTx({
create: vi.fn(async () => {
throw uniqueError;
}),
findUnique: vi.fn(async () => existing),
});
const result = await publishOutboxEvent(asPublisherTx(tx), {
tenantId: "tenant_1",
type: "mail.send.queued",
payload: { to: "u@example.com" },
dispatchKey: "stripe:evt_1ABC",
});
expect(result.id).toBe("outbox_event_existing");
expect(tx.outboxEvent.findUnique).toHaveBeenCalledWith({
where: { dispatchKey: "stripe:evt_1ABC" },
});
});
it("rethrows unique violations when no dispatchKey was set", async () => {
const uniqueError = Object.assign(new Error("unique violation"), { code: "P2002" });
const tx = createFakeTx({
create: vi.fn(async () => {
throw uniqueError;
}),
});
await expect(
publishOutboxEvent(asPublisherTx(tx), {
type: "mail.send.queued",
payload: { to: "u@example.com" },
})
).rejects.toBe(uniqueError);
});
it("rethrows non-unique-violation errors", async () => {
const error = Object.assign(new Error("disk full"), { code: "P9999" });
const tx = createFakeTx({
create: vi.fn(async () => {
throw error;
}),
});
await expect(
publishOutboxEvent(asPublisherTx(tx), {
type: "mail.send.queued",
payload: {},
dispatchKey: "key-1",
})
).rejects.toBe(error);
});
it("rejects malformed eventType values", async () => {
const tx = createFakeTx();
await expect(
publishOutboxEvent(asPublisherTx(tx), {
type: "bad-format",
payload: {},
})
).rejects.toMatchObject({
name: "OutboxPublishError",
code: "INVALID_EVENT_TYPE",
});
expect(tx.outboxEvent.create).not.toHaveBeenCalled();
});
it("rejects malformed dispatchKey values", async () => {
const tx = createFakeTx();
await expect(
publishOutboxEvent(asPublisherTx(tx), {
type: "mail.send.queued",
payload: {},
dispatchKey: "has spaces and bad ;chars",
})
).rejects.toMatchObject({
name: "OutboxPublishError",
code: "INVALID_DISPATCH_KEY",
});
expect(tx.outboxEvent.create).not.toHaveBeenCalled();
});
it("rejects payloads larger than 64 KiB", async () => {
const tx = createFakeTx();
const huge = "x".repeat(OUTBOX_MAX_PAYLOAD_BYTES + 1);
await expect(
publishOutboxEvent(asPublisherTx(tx), {
type: "mail.send.queued",
payload: { blob: huge },
})
).rejects.toMatchObject({
name: "OutboxPublishError",
code: "PAYLOAD_TOO_LARGE",
});
});
it("constants are aligned with regex expectations", () => {
expect(OUTBOX_EVENT_TYPE_PATTERN.test("billing.subscription.updated")).toBe(true);
expect(OUTBOX_EVENT_TYPE_PATTERN.test("billing.subscription")).toBe(false);
expect(OUTBOX_DISPATCH_KEY_PATTERN.test("stripe:evt_1.subscription")).toBe(true);
expect(OUTBOX_DISPATCH_KEY_PATTERN.test("")).toBe(false);
});
it("exports OutboxPublishError with the documented codes", () => {
const error = new OutboxPublishError("nope", "INVALID_EVENT_TYPE");
expect(error.name).toBe("OutboxPublishError");
expect(error.code).toBe("INVALID_EVENT_TYPE");
});
});
@@ -0,0 +1,184 @@
import type { OutboxEvent, Prisma } from "../generated/prisma/client/client.js";
export type { OutboxEvent } from "../generated/prisma/client/client.js";
/**
* Publisher API for the transactional outbox pattern.
*
* Producers call `publishOutboxEvent(tx, args)` from inside a Prisma
* `$transaction` callback. The event row is committed atomically with the
* surrounding DB writes, guaranteeing crash-safe side-effect delivery: the
* dispatcher worker (apps/worker/src/outbox/dispatcher.ts) later claims
* PENDING rows and dispatches them to BullMQ queues.
*
* The first argument is typed as {@link Prisma.TransactionClient} (a Prisma
* client missing `$transaction`, `$connect`, etc) so that calling this helper
* with a top-level `PrismaClient` singleton fails to type-check.
*
* See docs/architecture/outbox-pattern.md.
*/
/**
* Event types follow the `<domain>.<entity>.<verb>` convention (lowercase,
* dot-separated). The dispatcher routes by the first segment, e.g.
* `billing.subscription.updated` → `notification` queue.
*/
export const OUTBOX_EVENT_TYPE_PATTERN = /^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*){2,}$/u;
/**
* dispatchKey must be safe to use as a unique row key and must not leak
* PII. The pattern allows alphanumerics, dashes, underscores, dots and
* colons (good for namespaced keys like `stripe:evt_1ABC.subscription`).
*/
export const OUTBOX_DISPATCH_KEY_PATTERN = /^[A-Za-z0-9._:-]{1,256}$/u;
export const OUTBOX_MAX_PAYLOAD_BYTES = 64 * 1024;
export type OutboxPublishArgs = {
/**
* Nullable for system events that have no tenant context (e.g.
* platform-wide maintenance). Set when the side-effect is tenant-scoped
* so receivers can enforce tenant boundary checks on the payload.
*/
tenantId?: string | null;
/** Event type, e.g. `billing.subscription.updated`. */
type: string;
/** JSON payload. Must serialize cleanly to JSONB and stay under 64 KiB. */
payload: Prisma.InputJsonValue;
/**
* Optional idempotency key. When set, repeated publishes with the same
* dispatchKey trigger a unique-constraint conflict and the helper returns
* the existing event rather than inserting a duplicate.
*/
dispatchKey?: string | null;
/** Schedule the event for later dispatch (default: immediately). */
scheduledAt?: Date;
/** Higher = dispatched first when multiple events compete for capacity. */
priority?: number;
};
/**
* Minimal Prisma transaction surface the publisher needs. Tests inject
* a fake matching this shape rather than a full PrismaClient stub.
*/
export type OutboxEventWriterTx = {
outboxEvent: {
create(args: { data: Prisma.OutboxEventUncheckedCreateInput }): Promise<OutboxEvent>;
findUnique(args: {
where: { dispatchKey: string };
}): Promise<OutboxEvent | null>;
};
};
/**
* Constrained TransactionClient type: the helper only accepts a
* `Prisma.TransactionClient`, never a full `PrismaClient`. This is the
* type-system guard that enforces "publish must run inside a transaction".
*/
export type OutboxPublisherTransaction = Prisma.TransactionClient & OutboxEventWriterTx;
export class OutboxPublishError extends Error {
public override readonly name = "OutboxPublishError";
public readonly code:
| "INVALID_EVENT_TYPE"
| "INVALID_DISPATCH_KEY"
| "PAYLOAD_TOO_LARGE"
| "INVALID_PAYLOAD";
constructor(message: string, code: OutboxPublishError["code"]) {
super(message);
this.code = code;
}
}
function validateEventType(type: string): void {
if (typeof type !== "string" || !OUTBOX_EVENT_TYPE_PATTERN.test(type)) {
throw new OutboxPublishError(
`Outbox eventType must match <domain>.<entity>.<verb> (got: ${JSON.stringify(type)}).`,
"INVALID_EVENT_TYPE"
);
}
}
function validateDispatchKey(dispatchKey: string | null | undefined): void {
if (dispatchKey === null || dispatchKey === undefined) {
return;
}
if (!OUTBOX_DISPATCH_KEY_PATTERN.test(dispatchKey)) {
throw new OutboxPublishError(
`Outbox dispatchKey must match ${OUTBOX_DISPATCH_KEY_PATTERN.source}.`,
"INVALID_DISPATCH_KEY"
);
}
}
function validatePayload(payload: Prisma.InputJsonValue): string {
let serialized: string;
try {
serialized = JSON.stringify(payload);
} catch (error) {
throw new OutboxPublishError(
`Outbox payload is not JSON-serializable: ${(error as Error).message}.`,
"INVALID_PAYLOAD"
);
}
if (typeof serialized !== "string") {
throw new OutboxPublishError("Outbox payload serialized to non-string.", "INVALID_PAYLOAD");
}
if (Buffer.byteLength(serialized, "utf8") > OUTBOX_MAX_PAYLOAD_BYTES) {
throw new OutboxPublishError(
`Outbox payload exceeds ${OUTBOX_MAX_PAYLOAD_BYTES} bytes.`,
"PAYLOAD_TOO_LARGE"
);
}
return serialized;
}
function isUniqueViolation(error: unknown): boolean {
if (!error || typeof error !== "object") return false;
const candidate = error as { code?: unknown };
return candidate.code === "P2002";
}
/**
* Insert an OutboxEvent row inside the surrounding Prisma transaction.
*
* - When `dispatchKey` collides with an existing row, the existing event is
* returned (idempotent publish).
* - When `scheduledAt` is set in the future, the event is queued but the
* dispatcher skips it until `now()` catches up.
* - When `payload` exceeds 64 KiB or fails JSON serialization, the helper
* throws {@link OutboxPublishError} so callers can surface validation
* errors before the surrounding transaction commits.
*/
export async function publishOutboxEvent(
tx: OutboxPublisherTransaction,
args: OutboxPublishArgs
): Promise<OutboxEvent> {
validateEventType(args.type);
validateDispatchKey(args.dispatchKey);
validatePayload(args.payload);
try {
return await tx.outboxEvent.create({
data: {
tenantId: args.tenantId ?? null,
eventType: args.type,
payload: args.payload,
dispatchKey: args.dispatchKey ?? null,
...(args.scheduledAt ? { scheduledAt: args.scheduledAt } : {}),
...(typeof args.priority === "number" ? { priority: args.priority } : {}),
},
});
} catch (error) {
if (isUniqueViolation(error) && args.dispatchKey) {
const existing = await tx.outboxEvent.findUnique({
where: { dispatchKey: args.dispatchKey },
});
if (existing) {
return existing;
}
}
throw error;
}
}
@@ -0,0 +1,185 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("./client.server.js", () => ({ getDbClient: vi.fn() }));
import {
defaultPermissionSeedDescriptors,
defaultPermissionSeeds,
isPermissionsSeedDirectExecution,
syncDefaultRolesAndPermissions,
toSafePermissionSeedDiagnosticEvent,
} from "./permissions-seed.server.js";
const roleRows = [
{ id: "role_super_admin", name: "SuperAdmin" },
{ id: "role_super_user", name: "SuperUser" },
{ id: "role_admin", name: "Admin" },
{ id: "role_billing", name: "Billing Admin" },
{ id: "role_user", name: "User" },
];
function createClientMock() {
return {
role: {
deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
findFirst: vi.fn().mockResolvedValue(null),
create: vi.fn().mockResolvedValue({}),
update: vi.fn().mockResolvedValue({}),
findMany: vi.fn().mockResolvedValue(roleRows),
},
permission: {
createMany: vi.fn(async ({ data }: { data: unknown[] }) => ({ count: data.length })),
findMany: vi.fn().mockResolvedValue(defaultPermissionSeeds.map((name) => ({ id: `perm_${name}`, name }))),
},
rolePermission: {
createMany: vi.fn(async ({ data }: { data: unknown[] }) => ({ count: data.length })),
deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
},
};
}
describe("syncDefaultRolesAndPermissions", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("creates the full default permission catalog without relying on the web seed", async () => {
const client = createClientMock();
const result = await syncDefaultRolesAndPermissions({ client: client as never });
expect(result.createdPermissions).toBe(defaultPermissionSeeds.length);
expect(client.role.create).toHaveBeenCalledWith({
data: expect.objectContaining({ name: "SuperAdmin", tenantId: null, isDefault: true }),
});
expect(client.permission.createMany).toHaveBeenCalledWith({
data: expect.arrayContaining([
expect.objectContaining({ name: "admin.accounts.view", description: "Default permission admin.accounts.view", type: "admin", isDefault: true }),
expect.objectContaining({ name: "app.dashboard.view", type: "app", isDefault: true }),
]),
skipDuplicates: true,
});
expect(client.permission.findMany).toHaveBeenCalledWith({
where: { name: { in: [...defaultPermissionSeeds] } },
select: { id: true, name: true },
});
expect(client.rolePermission.createMany).toHaveBeenCalledWith({
data: [{ roleId: "role_super_admin", permissionId: "perm_admin.accounts.view" }],
skipDuplicates: true,
});
expect(client.rolePermission.createMany).toHaveBeenCalledWith({
data: expect.arrayContaining([
{ roleId: "role_super_user", permissionId: "perm_app.dashboard.view" },
{ roleId: "role_admin", permissionId: "perm_app.dashboard.view" },
{ roleId: "role_user", permissionId: "perm_app.dashboard.view" },
]),
skipDuplicates: true,
});
expect(client.rolePermission.createMany).toHaveBeenCalledWith({
data: [{ roleId: "role_super_admin", permissionId: "perm_app.settings.members.impersonate" }],
skipDuplicates: true,
});
expect(client.rolePermission.createMany).not.toHaveBeenCalledWith({
data: [{ roleId: "role_admin", permissionId: "perm_app.settings.account.delete" }],
skipDuplicates: true,
});
expect(client.role.deleteMany).toHaveBeenCalledWith({
where: {
type: "admin",
isDefault: true,
name: { notIn: ["SuperAdmin"] },
},
});
});
it("updates existing global default roles without touching tenant-owned roles", async () => {
const client = createClientMock();
client.role.findFirst.mockResolvedValue({ id: "existing_global_role" });
await syncDefaultRolesAndPermissions({ client: client as never });
expect(client.role.findFirst).toHaveBeenCalledWith({
where: { name: "SuperAdmin", tenantId: null },
select: { id: true },
});
expect(client.role.update).toHaveBeenCalledWith({
where: { id: "existing_global_role" },
data: expect.objectContaining({ tenantId: null, isDefault: true }),
});
expect(client.role.findMany).toHaveBeenCalledWith({
where: { name: { in: ["SuperAdmin", "SuperUser", "Admin", "Billing Admin", "User"] }, tenantId: null },
select: { id: true, name: true },
});
});
it("exports structured permission descriptors as the package-owned static seed source", () => {
expect(defaultPermissionSeedDescriptors).toHaveLength(defaultPermissionSeeds.length);
expect(defaultPermissionSeedDescriptors.map((permission) => permission.name)).toEqual([...defaultPermissionSeeds]);
expect(defaultPermissionSeedDescriptors.find((permission) => permission.name === "admin.analytics.view")).toMatchObject({
type: "admin",
inRoles: ["SuperAdmin"],
});
expect(defaultPermissionSeedDescriptors.find((permission) => permission.name === "app.settings.account.delete")).toMatchObject({
type: "app",
inRoles: ["SuperUser"],
});
expect(defaultPermissionSeedDescriptors.find((permission) => permission.name === "app.plugins.manage")).toMatchObject({
type: "app",
inRoles: ["SuperUser", "Admin"],
});
expect(defaultPermissionSeedDescriptors.find((permission) => permission.name === "app.plugins.use")).toMatchObject({
type: "app",
inRoles: ["SuperUser", "Admin", "Billing Admin", "User"],
});
});
it("uses skipDuplicates so concurrent deploy permission syncs do not duplicate links", async () => {
const client = createClientMock();
client.permission.createMany.mockResolvedValue({ count: 0 });
client.rolePermission.createMany.mockResolvedValue({ count: 0 });
const result = await syncDefaultRolesAndPermissions({ client: client as never });
expect(result.createdPermissions).toBe(0);
expect(result.createdRolePermissions).toBe(0);
expect(client.permission.createMany).toHaveBeenCalledWith(
expect.objectContaining({
skipDuplicates: true,
})
);
expect(client.rolePermission.createMany).toHaveBeenCalledWith(
expect.objectContaining({
skipDuplicates: true,
})
);
});
it("redacts secrets from CLI-safe failure diagnostics", () => {
const safe = toSafePermissionSeedDiagnosticEvent({
phase: "failure",
roleCount: 10,
permissionCount: defaultPermissionSeeds.length,
error: new Error("failed postgresql://user:secret@db.example/app?token=abc password=hidden"),
});
expect(JSON.stringify(safe)).not.toContain("user:secret");
expect(JSON.stringify(safe)).not.toContain("token=abc");
expect(JSON.stringify(safe)).not.toContain("password=hidden");
expect(safe).toMatchObject({ phase: "failure", roleCount: 10, permissionCount: defaultPermissionSeeds.length });
});
it("does not run the CLI seed block when bundled into the production seed artifact", () => {
expect(
isPermissionsSeedDirectExecution(
"/myapp/packages/db/dist/production-seed.server.js",
"file:///myapp/packages/db/dist/production-seed.server.js"
)
).toBe(false);
expect(
isPermissionsSeedDirectExecution(
"/myapp/packages/db/dist/permissions-seed.server.js",
"file:///myapp/packages/db/dist/permissions-seed.server.js"
)
).toBe(true);
});
});
@@ -0,0 +1,452 @@
import path from "node:path";
import { fileURLToPath } from "node:url";
import { createChildLogger, defaultLogger } from "@toolctrl/logger";
import { getDbClient, type DbClient } from "./client.server.js";
const seedLogger = createChildLogger(defaultLogger, { component: "db", scope: "permissions-seed" });
export type DefaultRoleSeed = {
name: string;
description: string;
type: "admin" | "app";
assignToNewUsers: boolean;
};
export type PermissionSeedDiagnosticEvent =
| { phase: "start"; roleCount: number; permissionCount: number }
| { phase: "success"; roleCount: number; permissionCount: number; createdPermissions: number; createdRolePermissions: number; prunedRolePermissions: number }
| { phase: "failure"; roleCount: number; permissionCount: number; error: unknown };
export type PermissionSeedDiagnostics = (event: PermissionSeedDiagnosticEvent) => void | Promise<void>;
type SafePermissionSeedDiagnosticEvent =
| { phase: "start"; roleCount: number; permissionCount: number }
| { phase: "success"; roleCount: number; permissionCount: number; createdPermissions: number; createdRolePermissions: number; prunedRolePermissions: number }
| { phase: "failure"; roleCount: number; permissionCount: number; error: { name: string; message: string } };
export function toSafePermissionSeedDiagnosticEvent(event: PermissionSeedDiagnosticEvent): SafePermissionSeedDiagnosticEvent {
if (event.phase !== "failure") {
return event;
}
const error = event.error instanceof Error ? event.error : new Error("Unknown permissions seed failure");
return {
phase: "failure",
roleCount: event.roleCount,
permissionCount: event.permissionCount,
error: {
name: error.name || "Error",
message: redactDiagnosticMessage(error.message || "Permissions seed failed"),
},
};
}
function redactDiagnosticMessage(message: string) {
return message
.replace(/[a-z]+:\/\/[^\s"'<>]+/gi, "[redacted-url]")
.replace(/([?&](?:token|password|secret|key)=)[^&\s]+/gi, "$1[redacted]")
.replace(/\b(?:password|token|secret|api[_-]?key)=\S+/gi, "[redacted-secret]");
}
export const defaultAdminRoleSeeds: DefaultRoleSeed[] = [
{ name: "SuperAdmin", description: "Has all admin permissions", type: "admin", assignToNewUsers: false },
];
export const defaultAppRoleSeeds: DefaultRoleSeed[] = [
{ name: "SuperUser", description: "Has all app permissions", type: "app", assignToNewUsers: false },
{ name: "Admin", description: "Has all app permissions but account deletion", type: "app", assignToNewUsers: false },
{ name: "Billing Admin", description: "Has subscription permissions", type: "app", assignToNewUsers: false },
{ name: "User", description: "Has regular permissions", type: "app", assignToNewUsers: true },
];
export const defaultPermissionSeeds = [
"admin.dashboard.view",
"admin.accounts.view",
"admin.accounts.create",
"admin.account.view",
"admin.account.settings.update",
"admin.account.users",
"admin.account.subscription",
"admin.account.delete",
"admin.accountTypes.view",
"admin.accountTypes.create",
"admin.accountTypes.update",
"admin.accountTypes.delete",
"admin.users.view",
"admin.users.impersonate",
"admin.users.changePassword",
"admin.users.delete",
"admin.relationships.view",
"admin.relationships.create",
"admin.relationships.update",
"admin.relationships.delete",
"admin.blacklist.view",
"admin.tenantIpAddress.view",
"admin.blacklist.manage",
"admin.roles.view",
"admin.roles.create",
"admin.roles.update",
"admin.roles.delete",
"admin.roles.set",
"admin.analytics.view",
"admin.analytics.delete",
"admin.entities.view",
"admin.entities.create",
"admin.entities.update",
"admin.entities.delete",
"admin.apiKeys.view",
"admin.apiKeys.create",
"admin.apiKeys.update",
"admin.apiKeys.delete",
"admin.auditTrails.view",
"admin.events.view",
"admin.pricing.view",
"admin.pricing.create",
"admin.pricing.update",
"admin.pricing.delete",
"admin.emails.view",
"admin.emails.create",
"admin.emails.update",
"admin.emails.delete",
"admin.onboarding.view",
"admin.onboarding.create",
"admin.onboarding.update",
"admin.onboarding.delete",
"admin.notifications.view",
"admin.notifications.manage",
"admin.featureFlags.view",
"admin.featureFlags.manage",
"admin.marketing.leads.view",
"admin.marketing.leads.manage",
"admin.marketing.integrations.view",
"admin.marketing.integrations.manage",
"admin.marketing.funnels.view",
"admin.prompts.view",
"admin.prompts.create",
"admin.prompts.update",
"admin.prompts.delete",
"admin.formulas.view",
"admin.formulas.create",
"admin.formulas.update",
"admin.formulas.delete",
"admin.metrics.view",
"admin.metrics.update",
"admin.metrics.delete",
"admin.kb.view",
"admin.kb.create",
"admin.kb.update",
"admin.kb.delete",
"admin.settings.cookies.view",
"admin.settings.cookies.create",
"admin.settings.cookies.update",
"admin.settings.general.view",
"admin.settings.general.update",
"admin.settings.authentication.view",
"admin.settings.authentication.update",
"admin.settings.analytics.view",
"admin.settings.analytics.update",
"admin.settings.seo.update",
"admin.settings.internationalization.view",
"admin.settings.internationalization.update",
"admin.settings.danger.reset",
"app.dashboard.view",
"app.settings.members.view",
"app.settings.members.create",
"app.settings.members.update",
"app.settings.members.delete",
"app.settings.members.impersonate",
"app.settings.roles.view",
"app.settings.roles.set",
"app.settings.groups.full",
"app.settings.subscription.view",
"app.settings.subscription.update",
"app.settings.subscription.delete",
"app.settings.subscription.invoices.view",
"app.settings.account.view",
"app.settings.account.update",
"app.settings.account.delete",
"app.settings.accounts.view",
"app.settings.accounts.create",
"app.settings.accounts.update",
"app.settings.accounts.delete",
"app.settings.apiKeys.view",
"app.settings.apiKeys.create",
"app.settings.apiKeys.update",
"app.settings.apiKeys.delete",
"app.settings.auditTrails.view",
"app.plugins.use",
"app.plugins.manage",
// P4 Files (AK-P4a) — Files platform primitive. Bundle semantics (M23 §J):
// read_all ⊃ read_own; write ⊃ read_all; admin ⊃ write + delete. The
// implication is expanded at permission-check time; here we register the flat
// permissions + the default-role grants.
"files.read_own",
"files.read_all",
"files.write",
"files.delete",
"files.admin",
// P4 Tasks (AK-P4b) — cross-cutting task module. Bundle semantics mirror
// files: read_all ⊃ read_own; write ⊃ read_all; admin ⊃ write + delete.
"tasks.read_own",
"tasks.read_all",
"tasks.write",
"tasks.delete",
"tasks.admin",
] as const;
export type DefaultPermissionSeed = {
inRoles: string[];
name: (typeof defaultPermissionSeeds)[number];
description: string;
type: "admin" | "app";
};
const explicitPermissionRoleAssignments: Partial<Record<(typeof defaultPermissionSeeds)[number], string[]>> = {
"admin.dashboard.view": ["SuperAdmin"],
"admin.relationships.view": ["SuperAdmin"],
"admin.tenantIpAddress.view": ["SuperAdmin"],
"admin.analytics.view": ["SuperAdmin"],
"admin.entities.view": ["SuperAdmin"],
"admin.entities.create": ["SuperAdmin"],
"admin.entities.update": ["SuperAdmin"],
"admin.entities.delete": ["SuperAdmin"],
"admin.apiKeys.view": ["SuperAdmin"],
"admin.apiKeys.create": ["SuperAdmin"],
"admin.apiKeys.update": ["SuperAdmin"],
"admin.apiKeys.delete": ["SuperAdmin"],
"admin.auditTrails.view": ["SuperAdmin"],
"admin.events.view": ["SuperAdmin"],
"admin.pricing.view": ["SuperAdmin"],
"admin.pricing.create": ["SuperAdmin"],
"admin.pricing.update": ["SuperAdmin"],
"admin.pricing.delete": ["SuperAdmin"],
"admin.emails.view": ["SuperAdmin"],
"admin.emails.create": ["SuperAdmin"],
"admin.emails.update": ["SuperAdmin"],
"admin.emails.delete": ["SuperAdmin"],
"admin.onboarding.view": ["SuperAdmin"],
"admin.notifications.view": ["SuperAdmin"],
"admin.featureFlags.view": ["SuperAdmin"],
"admin.marketing.leads.view": ["SuperAdmin"],
"admin.marketing.integrations.view": ["SuperAdmin"],
"admin.marketing.funnels.view": ["SuperAdmin"],
"admin.prompts.view": ["SuperAdmin"],
"admin.formulas.view": ["SuperAdmin"],
"admin.metrics.view": ["SuperAdmin"],
"admin.kb.view": ["SuperAdmin"],
"admin.settings.cookies.view": ["SuperAdmin"],
"admin.settings.general.view": ["SuperAdmin"],
"admin.settings.authentication.view": ["SuperAdmin"],
"admin.settings.analytics.view": ["SuperAdmin"],
"admin.settings.internationalization.view": ["SuperAdmin"],
"app.dashboard.view": ["SuperUser", "Admin", "User"],
"app.settings.members.view": ["SuperUser", "Admin"],
"app.settings.members.impersonate": ["SuperAdmin"],
"app.settings.roles.view": ["SuperUser", "Admin"],
"app.settings.subscription.view": ["SuperUser", "Admin", "Billing Admin"],
"app.settings.subscription.invoices.view": ["SuperUser", "Admin", "Billing Admin"],
"app.settings.account.view": ["SuperUser", "Admin"],
"app.settings.account.delete": ["SuperUser"],
"app.settings.accounts.view": ["SuperUser", "Admin"],
"app.settings.apiKeys.view": ["SuperUser", "Admin"],
"app.settings.auditTrails.view": ["SuperUser", "Admin"],
"app.plugins.use": ["SuperUser", "Admin", "Billing Admin", "User"],
"app.plugins.manage": ["SuperUser", "Admin"],
// Files — `files.*` permissions do not carry the `app.`/`admin.` prefix, so
// the prefix-default in roleNamesForPermission() would leave them ungranted.
// Explicit grants are therefore mandatory. Field users (Monteure) upload and
// see their own files; Admin/SuperUser see all and may delete; admin =
// SuperUser only.
"files.read_own": ["SuperUser", "Admin", "User"],
"files.read_all": ["SuperUser", "Admin"],
"files.write": ["SuperUser", "Admin", "User"],
"files.delete": ["SuperUser", "Admin"],
"files.admin": ["SuperUser"],
// Tasks — `tasks.*` carries no `app.`/`admin.` prefix either, so explicit
// grants are mandatory. Regular users manage their own/assigned tasks;
// Admin/SuperUser see all and may delete; admin = SuperUser only.
"tasks.read_own": ["SuperUser", "Admin", "User"],
"tasks.read_all": ["SuperUser", "Admin"],
"tasks.write": ["SuperUser", "Admin", "User"],
"tasks.delete": ["SuperUser", "Admin"],
"tasks.admin": ["SuperUser"],
};
export type SyncDefaultRolesAndPermissionsOptions = {
client?: DbClient;
diagnostics?: PermissionSeedDiagnostics;
};
function roleNamesForPermission(permissionName: string): string[] {
const explicitRoles = explicitPermissionRoleAssignments[permissionName as (typeof defaultPermissionSeeds)[number]];
if (explicitRoles) {
return explicitRoles;
}
const roleNames = new Set<string>();
if (permissionName.startsWith("admin.")) {
roleNames.add("SuperAdmin");
}
if (permissionName.startsWith("app.")) {
roleNames.add("SuperUser");
roleNames.add("Admin");
}
if (permissionName.startsWith("app.settings.subscription.")) {
roleNames.add("Billing Admin");
}
if (permissionName === "app.dashboard.view") {
roleNames.add("User");
}
return [...roleNames];
}
export const defaultPermissionSeedDescriptors: DefaultPermissionSeed[] = defaultPermissionSeeds.map((name) => ({
inRoles: roleNamesForPermission(name),
name,
description: `Default permission ${name}`,
type: name.startsWith("admin.") ? "admin" : "app",
}));
async function ensureRolePermissions(client: DbClient, permissionId: string, roleIds: string[]): Promise<number> {
if (roleIds.length === 0) {
return 0;
}
const result = await client.rolePermission.createMany({
data: roleIds.map((roleId) => ({ roleId, permissionId })),
skipDuplicates: true,
});
return result.count;
}
export async function syncDefaultRolesAndPermissions({ client = getDbClient(), diagnostics }: SyncDefaultRolesAndPermissionsOptions = {}) {
const roles = [...defaultAdminRoleSeeds, ...defaultAppRoleSeeds];
await diagnostics?.({ phase: "start", roleCount: roles.length, permissionCount: defaultPermissionSeeds.length });
try {
await client.role.deleteMany({
where: {
type: "admin",
isDefault: true,
name: { notIn: defaultAdminRoleSeeds.map((role) => role.name) },
},
});
for (let index = 0; index < roles.length; index += 1) {
const role = roles[index];
const existingRole = await client.role.findFirst({
where: { name: role.name, tenantId: null },
select: { id: true },
});
if (existingRole) {
await client.role.update({
where: { id: existingRole.id },
data: { ...role, tenantId: null, order: index + 1, isDefault: true },
});
} else {
await client.role.create({
data: { ...role, tenantId: null, order: index + 1, isDefault: true },
});
}
}
const roleRows = await client.role.findMany({
where: { name: { in: roles.map((role) => role.name) }, tenantId: null },
select: { id: true, name: true },
});
const roleByName = new Map(roleRows.map((role) => [role.name, role]));
const defaultRoleIds = roleRows.map((role) => role.id);
let createdRolePermissions = 0;
let prunedRolePermissions = 0;
const permissionCreateResult = await client.permission.createMany({
data: defaultPermissionSeedDescriptors.map(({ name, description, type }, index) => ({
name,
description,
type,
order: index + 1,
isDefault: true,
entityId: null,
})),
skipDuplicates: true,
});
const permissionRows = await client.permission.findMany({
where: { name: { in: [...defaultPermissionSeeds] } },
select: { id: true, name: true },
});
const permissionByName = new Map(permissionRows.map((permission) => [permission.name, permission]));
for (const { name, inRoles } of defaultPermissionSeedDescriptors) {
const permission = permissionByName.get(name);
if (!permission) {
throw new Error(`Default permission ${name} was not found after seed insert`);
}
const roleIds = inRoles.map((roleName) => roleByName.get(roleName)?.id).filter((roleId): roleId is string => Boolean(roleId));
createdRolePermissions += await ensureRolePermissions(client, permission.id, roleIds);
// Prune stale default-role grants: a default role that previously held this
// permission but is no longer in inRoles (e.g. after the 2026-05 plugin
// permission split tightened the mapping) must lose it. Without this the
// sync was add-only, so tightening a mapping never propagated to existing
// tenants. Scoped to DEFAULT roles only — tenant/custom grants are untouched.
const staleRoleIds = defaultRoleIds.filter((roleId) => !roleIds.includes(roleId));
if (staleRoleIds.length > 0) {
const pruned = await client.rolePermission.deleteMany({
where: { permissionId: permission.id, roleId: { in: staleRoleIds } },
});
prunedRolePermissions += pruned.count;
}
}
const result = {
roleCount: roles.length,
permissionCount: defaultPermissionSeeds.length,
createdPermissions: permissionCreateResult.count,
createdRolePermissions,
prunedRolePermissions,
};
await diagnostics?.({ phase: "success", ...result });
return result;
} catch (error) {
await diagnostics?.({ phase: "failure", roleCount: roles.length, permissionCount: defaultPermissionSeeds.length, error });
throw error;
}
}
export function isPermissionsSeedDirectExecution(entrypoint = process.argv[1], moduleUrl = import.meta.url) {
if (!entrypoint) {
return false;
}
const modulePath = fileURLToPath(moduleUrl);
const moduleFilename = path.basename(modulePath);
return (moduleFilename === "permissions-seed.server.ts" || moduleFilename === "permissions-seed.server.js") && path.resolve(entrypoint) === modulePath;
}
if (isPermissionsSeedDirectExecution()) {
const client = getDbClient();
syncDefaultRolesAndPermissions({
client,
diagnostics: (event) => {
seedLogger.info(toSafePermissionSeedDiagnosticEvent(event), "permissions seed event");
},
})
.finally(async () => {
await client.$disconnect();
})
.catch((error) => {
seedLogger.error(
toSafePermissionSeedDiagnosticEvent({
phase: "failure",
roleCount: defaultAdminRoleSeeds.length + defaultAppRoleSeeds.length,
permissionCount: defaultPermissionSeeds.length,
error,
}),
"permissions seed failed"
);
process.exit(1);
});
}
@@ -0,0 +1,18 @@
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
const repoRoot = resolve(__dirname, "../../..");
const schemaPath = resolve(repoRoot, "prisma/schema/plugins.prisma");
const migrationPath = resolve(repoRoot, "prisma/migrations/20260528143000_06_plugin_enabled_default_false/migration.sql");
describe("plugin schema safety contracts", () => {
it("defaults installed plugins to disabled at the database layer", () => {
const schema = readFileSync(schemaPath, "utf8");
const migrationSql = readFileSync(migrationPath, "utf8");
expect(schema).toMatch(/enabled\s+Boolean\s+@default\(false\)/);
expect(migrationSql).toMatch(/ALTER\s+TABLE\s+"Plugin"\s+ALTER\s+COLUMN\s+"enabled"\s+SET\s+DEFAULT\s+false/i);
expect(migrationSql).not.toMatch(/UPDATE\s+"Plugin"/i);
});
});
@@ -0,0 +1,9 @@
import { describe, expect, it } from "vitest";
import * as prismaBrowser from "./prisma-browser.js";
describe("@toolctrl/db browser Prisma boundary", () => {
it("re-exports browser-safe Prisma symbols from the package-owned generated client", () => {
expect(prismaBrowser.Prisma).toBeDefined();
});
});
@@ -0,0 +1 @@
export * from "../generated/prisma/client/browser.js";
@@ -0,0 +1,19 @@
export const PRISMA_SCHEMA_PATH = "prisma/schema" as const;
export const PRISMA_MIGRATIONS_PATH = "prisma/migrations" as const;
export const PRISMA_SEED_COMMAND = "tsx prisma/seed.ts" as const;
export const PRISMA_GENERATED_CLIENT_PATH =
"packages/db/generated/prisma/client" as const;
export type PrismaOwnershipMetadata = {
schemaPath: typeof PRISMA_SCHEMA_PATH;
migrationsPath: typeof PRISMA_MIGRATIONS_PATH;
seedCommand: typeof PRISMA_SEED_COMMAND;
generatedClientPath: typeof PRISMA_GENERATED_CLIENT_PATH;
};
export const prismaOwnershipMetadata: PrismaOwnershipMetadata = Object.freeze({
schemaPath: PRISMA_SCHEMA_PATH,
migrationsPath: PRISMA_MIGRATIONS_PATH,
seedCommand: PRISMA_SEED_COMMAND,
generatedClientPath: PRISMA_GENERATED_CLIENT_PATH,
});
@@ -0,0 +1,197 @@
import { describe, expect, it, vi } from "vitest";
import {
QUEUE_FAILED_JOB_ERROR_MESSAGE_MAX_LENGTH,
redactQueueFailedJobErrorMessage,
recordQueueFailedJob,
type QueueFailedJobWriterClient,
} from "./queue-failed-jobs.server.js";
function createQueueFailedJobClient(): QueueFailedJobWriterClient {
return {
queueFailedJob: {
create: vi.fn().mockResolvedValue({ id: "failed_job_1" }),
upsert: vi.fn().mockResolvedValue({ id: "failed_job_1" }),
},
};
}
describe("queue failed job writes", () => {
it("redacts provider and payload diagnostics before storing failed jobs", () => {
expect(
redactQueueFailedJobErrorMessage("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("upserts terminal BullMQ failures by queue, job name, and job id", async () => {
const client = createQueueFailedJobClient();
const failedAt = new Date("2026-05-07T12:00:00.000Z");
await recordQueueFailedJob(
{
queueName: "email",
jobName: "send-email",
jobId: "job_1",
attemptsMade: 3,
attemptsLimit: 3,
errorName: "TypeError",
errorMessage: "Template missing",
failedAt,
},
client,
);
const expectedData = {
queueName: "email",
jobName: "send-email",
jobId: "job_1",
attemptsMade: 3,
attemptsLimit: 3,
errorName: "TypeError",
errorMessage: "Template missing",
failedAt,
};
expect(client.queueFailedJob.upsert).toHaveBeenCalledWith({
where: {
queueName_jobName_jobId: {
queueName: "email",
jobName: "send-email",
jobId: "job_1",
},
},
create: expectedData,
update: expectedData,
});
expect(client.queueFailedJob.create).not.toHaveBeenCalled();
});
it("creates inspectable rows when no job id is available", async () => {
const client = createQueueFailedJobClient();
await recordQueueFailedJob(
{
queueName: "email",
jobName: "send-email",
attemptsMade: 1,
errorMessage: "No job id",
},
client,
);
expect(client.queueFailedJob.create).toHaveBeenCalledWith({
data: {
queueName: "email",
jobName: "send-email",
jobId: null,
attemptsMade: 1,
attemptsLimit: null,
errorName: "Error",
errorMessage: "No job id",
failedAt: null,
},
});
expect(client.queueFailedJob.upsert).not.toHaveBeenCalled();
});
it("normalizes optional diagnostics to redacted scalar defaults", async () => {
const client = createQueueFailedJobClient();
await recordQueueFailedJob(
{
queueName: "sync",
jobName: "pull",
jobId: null,
attemptsMade: 2,
attemptsLimit: undefined,
errorName: null,
errorMessage: null,
failedAt: undefined,
},
client,
);
expect(client.queueFailedJob.create).toHaveBeenCalledWith({
data: {
queueName: "sync",
jobName: "pull",
jobId: null,
attemptsMade: 2,
attemptsLimit: null,
errorName: "Error",
errorMessage: "",
failedAt: null,
},
});
});
it("truncates oversized error messages before writing", async () => {
const client = createQueueFailedJobClient();
const oversizedMessage = "x".repeat(QUEUE_FAILED_JOB_ERROR_MESSAGE_MAX_LENGTH + 100);
await recordQueueFailedJob(
{
queueName: "reports",
jobName: "build-report",
jobId: "job_2",
attemptsMade: 5,
attemptsLimit: 5,
errorName: "RangeError",
errorMessage: oversizedMessage,
},
client,
);
const upsertCall = vi.mocked(client.queueFailedJob.upsert).mock.calls[0]?.[0];
expect(upsertCall?.create.errorMessage).toHaveLength(QUEUE_FAILED_JOB_ERROR_MESSAGE_MAX_LENGTH);
expect(upsertCall?.update.errorMessage).toHaveLength(QUEUE_FAILED_JOB_ERROR_MESSAGE_MAX_LENGTH);
});
it("redacts oversized error messages before writing", async () => {
const client = createQueueFailedJobClient();
await recordQueueFailedJob(
{
queueName: "notifications",
jobName: "send-email",
jobId: "job_secret",
attemptsMade: 3,
attemptsLimit: 3,
errorName: "ProviderError",
errorMessage: `SMTP token=secret-token failed for user@example.com with Authorization: Bearer abc123 ${"x".repeat(QUEUE_FAILED_JOB_ERROR_MESSAGE_MAX_LENGTH + 50)}`,
},
client,
);
const upsertCall = vi.mocked(client.queueFailedJob.upsert).mock.calls[0]?.[0];
expect(upsertCall?.create.errorMessage).toHaveLength(QUEUE_FAILED_JOB_ERROR_MESSAGE_MAX_LENGTH);
expect(upsertCall?.create.errorMessage).not.toContain("secret-token");
expect(upsertCall?.create.errorMessage).not.toContain("user@example.com");
expect(upsertCall?.create.errorMessage).not.toContain("abc123");
});
it("does not retain payload-like fields in the persisted write shape", async () => {
const client = createQueueFailedJobClient();
await recordQueueFailedJob(
{
queueName: "webhooks",
jobName: "deliver",
jobId: "job_3",
attemptsMade: 4,
attemptsLimit: 4,
errorName: "HttpError",
errorMessage: "Failed after retries",
body: "secret-body",
headers: { authorization: "Bearer secret" },
payload: { templateData: "secret" },
} as Parameters<typeof recordQueueFailedJob>[0] & Record<string, unknown>,
client,
);
const upsertCall = vi.mocked(client.queueFailedJob.upsert).mock.calls[0]?.[0];
expect(upsertCall).toBeDefined();
expect(JSON.stringify(upsertCall)).not.toContain("secret-body");
expect(JSON.stringify(upsertCall)).not.toContain("authorization");
expect(JSON.stringify(upsertCall)).not.toContain("templateData");
});
});
@@ -0,0 +1,94 @@
import { getDbClient, type DbClient } from "./client.server.js";
export const QUEUE_FAILED_JOB_ERROR_MESSAGE_MAX_LENGTH = 2_000;
export type QueueFailedJobRecordInput = {
queueName: string;
jobName: string;
jobId?: string | null;
attemptsMade: number;
attemptsLimit?: number | null;
errorName?: string | null;
errorMessage?: string | null;
failedAt?: Date | null;
};
type QueueFailedJobRecordData = {
queueName: string;
jobName: string;
jobId?: string | null;
attemptsMade: number;
attemptsLimit?: number | null;
errorName: string;
errorMessage: string;
failedAt?: Date | null;
};
export type QueueFailedJobWriterClient = {
queueFailedJob: {
create(args: { data: QueueFailedJobRecordData }): Promise<unknown>;
upsert(args: {
where: { queueName_jobName_jobId: { queueName: string; jobName: string; jobId: string } };
create: QueueFailedJobRecordData;
update: QueueFailedJobRecordData;
}): Promise<unknown>;
};
};
export function redactQueueFailedJobErrorMessage(errorMessage: string): string {
return errorMessage
.replace(/\b(authorization)\s*[:=]\s*Bearer\s+\S+/gi, "$1=Bearer [redacted]")
.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, "Bearer [redacted]")
.replace(/\b(token|secret|api[-_]?key|apikey|password|code)\s*[:=]\s*[^&\s;,)\"']+/gi, "$1=[redacted]")
.replace(/\b(payload|body|template)[-_ ]?secret\b/gi, "$1-[redacted]")
.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi, "[redacted-email]");
}
function truncateErrorMessage(errorMessage: string): string {
const redacted = redactQueueFailedJobErrorMessage(errorMessage);
if (redacted.length <= QUEUE_FAILED_JOB_ERROR_MESSAGE_MAX_LENGTH) {
return redacted;
}
return redacted.slice(0, QUEUE_FAILED_JOB_ERROR_MESSAGE_MAX_LENGTH);
}
function normalizeQueueFailedJobData(data: QueueFailedJobRecordInput): QueueFailedJobRecordData {
return {
queueName: data.queueName,
jobName: data.jobName,
jobId: data.jobId ?? null,
attemptsMade: data.attemptsMade,
attemptsLimit: data.attemptsLimit ?? null,
errorName: data.errorName ?? "Error",
errorMessage: truncateErrorMessage(data.errorMessage ?? ""),
failedAt: data.failedAt ?? null,
};
}
export async function recordQueueFailedJob(
data: QueueFailedJobRecordInput,
client: QueueFailedJobWriterClient = getDbClient() as DbClient & QueueFailedJobWriterClient,
): Promise<void> {
const normalizedData = normalizeQueueFailedJobData(data);
if (normalizedData.jobId) {
await client.queueFailedJob.upsert({
where: {
queueName_jobName_jobId: {
queueName: normalizedData.queueName,
jobName: normalizedData.jobName,
jobId: normalizedData.jobId,
},
},
create: normalizedData,
update: normalizedData,
});
return;
}
await client.queueFailedJob.create({
data: normalizedData,
});
}
@@ -0,0 +1,295 @@
import { describe, expect, it, vi } from "vitest";
import {
createLegacyRowRelationship,
deleteLegacyRowRelationship,
deleteLegacyRowRelationshipById,
findLegacyEntityRelationship,
findLegacyRowRelationshipById,
legacyRowRelationshipInclude,
type LegacyRelationshipClient,
type LegacyRowRelationshipEntity,
type LegacyRowRelationshipDetails,
} from "./relationships.server.js";
describe("legacy row relationship helpers", () => {
it("fetches a row relationship by id with relationship entity ids", async () => {
const relationship = rowRelationshipFixture("row_rel_1");
const client = createRelationshipClient({ findUnique: relationship });
await expect(findLegacyRowRelationshipById("row_rel_1", client)).resolves.toBe(relationship);
expect(client.rowRelationship.findUnique).toHaveBeenCalledWith({
where: { id: "row_rel_1" },
include: legacyRowRelationshipInclude,
});
});
it("fetches row relationships by id within tenant-scoped non-deleted parent and child rows", async () => {
const relationship = rowRelationshipFixture("row_rel_1");
const client = createRelationshipClient({ findFirstRelationship: relationship });
await expect(findLegacyRowRelationshipById("row_rel_1", "tenant_1", client)).resolves.toBe(relationship);
expect(client.rowRelationship.findFirst).toHaveBeenCalledWith({
where: {
id: "row_rel_1",
parent: { tenantId: "tenant_1", deletedAt: null },
child: { tenantId: "tenant_1", deletedAt: null },
},
include: legacyRowRelationshipInclude,
});
expect(client.rowRelationship.findUnique).not.toHaveBeenCalled();
});
it("returns null for missing row relationships", async () => {
const client = createRelationshipClient({ findUnique: null });
await expect(findLegacyRowRelationshipById("missing", client)).resolves.toBeNull();
});
it("creates a row relationship with parent child rows and nullable metadata", async () => {
const relationship = rowRelationshipFixture("row_rel_1");
const client = createRelationshipClient({ create: relationship });
await expect(
createLegacyRowRelationship(
{
relationshipId: "entity_rel_1",
parentId: "parent_row_1",
childId: "child_row_1",
},
client,
),
).resolves.toBe(relationship);
expect(client.rowRelationship.create).toHaveBeenCalledWith({
data: {
relationshipId: "entity_rel_1",
parentId: "parent_row_1",
childId: "child_row_1",
metadata: null,
},
include: legacyRowRelationshipInclude,
});
});
it("validates scoped row relationship creates against tenant and entity sides", async () => {
const relationship = rowRelationshipFixture("row_rel_1");
const client = createRelationshipClient({
create: relationship,
findFirst: { id: "entity_rel_1", parentId: "parent_entity_1", childId: "child_entity_1" },
rows: [{ id: "parent_row_1" }, { id: "child_row_1" }],
});
await expect(
createLegacyRowRelationship(
{
relationshipId: "entity_rel_1",
parentId: "parent_row_1",
childId: "child_row_1",
tenantId: "tenant_1",
},
client,
),
).resolves.toBe(relationship);
expect(client.entityRelationship.findFirst).toHaveBeenCalledWith({
where: { id: "entity_rel_1" },
select: { id: true, parentId: true, childId: true },
});
expect(client.row.findFirst).toHaveBeenNthCalledWith(1, {
where: { id: "parent_row_1", tenantId: "tenant_1", entityId: "parent_entity_1", deletedAt: null },
select: { id: true },
});
expect(client.row.findFirst).toHaveBeenNthCalledWith(2, {
where: { id: "child_row_1", tenantId: "tenant_1", entityId: "child_entity_1", deletedAt: null },
select: { id: true },
});
expect(client.rowRelationship.create).toHaveBeenCalledWith({
data: {
relationshipId: "entity_rel_1",
parentId: "parent_row_1",
childId: "child_row_1",
metadata: null,
},
include: legacyRowRelationshipInclude,
});
});
it("rejects scoped row relationship creates when either row fails tenant or entity validation", async () => {
const client = createRelationshipClient({
findFirst: { id: "entity_rel_1", parentId: "parent_entity_1", childId: "child_entity_1" },
rows: [{ id: "parent_row_1" }, null],
});
await expect(
createLegacyRowRelationship(
{
relationshipId: "entity_rel_1",
parentId: "parent_row_1",
childId: "foreign_child_row_1",
tenantId: "tenant_1",
},
client,
),
).rejects.toThrow("Relationship rows not found");
expect(client.rowRelationship.create).not.toHaveBeenCalled();
});
it("does not swallow create persistence errors", async () => {
const error = new Error("unique parent child constraint");
const client = createRelationshipClient({ createError: error });
await expect(
createLegacyRowRelationship(
{
relationshipId: "entity_rel_1",
parentId: "parent_row_1",
childId: "child_row_1",
metadata: "{\"source\":\"api\"}",
},
client,
),
).rejects.toThrow(error);
});
it("deletes a row relationship by scoped ids", async () => {
const deleted = { count: 1 };
const client = createRelationshipClient({ delete: deleted });
await expect(
deleteLegacyRowRelationshipById({ id: "row_rel_1", relationshipId: "entity_rel_1", parentId: "parent_row_1", childId: "child_row_1", tenantId: "tenant_1" }, client)
).resolves.toBe(deleted);
expect(client.rowRelationship.deleteMany).toHaveBeenCalledWith({
where: {
id: "row_rel_1",
relationshipId: "entity_rel_1",
parentId: "parent_row_1",
childId: "child_row_1",
parent: { tenantId: "tenant_1", deletedAt: null },
child: { tenantId: "tenant_1", deletedAt: null },
},
});
});
it("throws when scoped row relationship delete does not remove exactly one row", async () => {
const client = createRelationshipClient({ delete: { count: 0 } });
await expect(
deleteLegacyRowRelationshipById({ id: "missing", relationshipId: "entity_rel_1", parentId: "parent_row_1", childId: "child_row_1", tenantId: "tenant_1" }, client)
).rejects.toThrow("Relationship missing not found");
});
it("rejects row relationship deletes without tenant scope", async () => {
const client = createRelationshipClient({});
await expect(deleteLegacyRowRelationship({ parentId: "parent_row_1", childId: "child_row_1" }, client)).rejects.toThrow(
"Tenant id is required for relationship deletes",
);
expect(client.rowRelationship.deleteMany).not.toHaveBeenCalled();
});
it("deletes a scoped row relationship by resolved relationship row id", async () => {
const relationship = rowRelationshipFixture("row_rel_1");
const deleted = { count: 1 };
const client = createRelationshipClient({ findFirstRelationship: relationship, delete: deleted });
await expect(
deleteLegacyRowRelationship(
{
relationshipId: "entity_rel_1",
parentId: "parent_row_1",
childId: "child_row_1",
tenantId: "tenant_1",
},
client,
),
).resolves.toBe(deleted);
expect(client.rowRelationship.findFirst).toHaveBeenCalledWith({
where: {
relationshipId: "entity_rel_1",
parentId: "parent_row_1",
childId: "child_row_1",
parent: { tenantId: "tenant_1", deletedAt: null },
child: { tenantId: "tenant_1", deletedAt: null },
},
include: legacyRowRelationshipInclude,
});
expect(client.rowRelationship.deleteMany).toHaveBeenCalledWith({
where: {
id: "row_rel_1",
relationshipId: "entity_rel_1",
parentId: "parent_row_1",
childId: "child_row_1",
parent: { tenantId: "tenant_1", deletedAt: null },
child: { tenantId: "tenant_1", deletedAt: null },
},
});
});
it("rejects scoped row relationship deletes without an entity relationship id", async () => {
const client = createRelationshipClient({});
await expect(deleteLegacyRowRelationship({ parentId: "parent_row_1", childId: "child_row_1", tenantId: "tenant_1" }, client)).rejects.toThrow(
"Relationship id is required for scoped relationship deletes",
);
expect(client.rowRelationship.deleteMany).not.toHaveBeenCalled();
});
it("finds the entity relationship for a parent and child entity", async () => {
const entityRelationship = { id: "entity_rel_1", parentId: "parent_entity_1", childId: "child_entity_1" };
const client = createRelationshipClient({ findFirst: entityRelationship });
await expect(findLegacyEntityRelationship({ parentId: "parent_entity_1", childId: "child_entity_1" }, client)).resolves.toBe(entityRelationship);
expect(client.entityRelationship.findFirst).toHaveBeenCalledWith({
where: { parentId: "parent_entity_1", childId: "child_entity_1" },
select: { id: true, parentId: true, childId: true },
});
});
it("returns null for missing entity relationships", async () => {
const client = createRelationshipClient({ findFirst: null });
await expect(findLegacyEntityRelationship({ parentId: "parent_entity_1", childId: "missing_entity" }, client)).resolves.toBeNull();
});
});
function rowRelationshipFixture(id: string): LegacyRowRelationshipDetails {
return {
id,
relationshipId: "entity_rel_1",
parentId: "parent_row_1",
childId: "child_row_1",
metadata: null,
createdAt: new Date("2026-01-01T00:00:00.000Z"),
relationship: {
id: "entity_rel_1",
parentId: "parent_entity_1",
childId: "child_entity_1",
},
};
}
function createRelationshipClient(options: {
findUnique?: LegacyRowRelationshipDetails | null;
findFirstRelationship?: LegacyRowRelationshipDetails | null;
create?: LegacyRowRelationshipDetails;
createError?: Error;
delete?: unknown;
deleteMany?: unknown;
findFirst?: { id: string; parentId: string; childId: string } | null;
rows?: Array<LegacyRowRelationshipEntity | null>;
}): LegacyRelationshipClient {
let rowIndex = 0;
return {
rowRelationship: {
findUnique: vi.fn().mockResolvedValue(options.findUnique ?? null),
findFirst: vi.fn().mockResolvedValue(options.findFirstRelationship ?? null),
create: options.createError ? vi.fn().mockRejectedValue(options.createError) : vi.fn().mockResolvedValue(options.create ?? rowRelationshipFixture("row_rel_created")),
deleteMany: vi.fn().mockResolvedValue(options.delete ?? options.deleteMany ?? { count: 0 }),
},
entityRelationship: {
findFirst: vi.fn().mockResolvedValue(options.findFirst ?? null),
},
row: {
findFirst: vi.fn(async () => options.rows?.[rowIndex++] ?? null),
},
} as unknown as LegacyRelationshipClient;
}
@@ -0,0 +1,181 @@
import { getDbClient } from "./client.server.js";
import type { EntityRelationship, Prisma, RowRelationship } from "./prisma-browser.js";
export type LegacyRowRelationshipEntity = {
id: string;
};
export type LegacyRowRelationshipDetails = Pick<RowRelationship, "id" | "relationshipId" | "parentId" | "childId" | "metadata" | "createdAt"> & {
relationship: Pick<EntityRelationship, "id" | "parentId" | "childId">;
};
export type LegacyEntityRelationshipDetails = Pick<EntityRelationship, "id" | "parentId" | "childId">;
export type LegacyRowRelationshipCreateInput = {
relationshipId: string;
parentId: string;
childId: string;
tenantId?: string | null;
metadata?: string | null;
};
export type LegacyRowRelationshipDeleteByIdInput = Pick<RowRelationship, "id" | "relationshipId" | "parentId" | "childId"> & {
tenantId: string | null;
};
export type LegacyRelationshipClient = {
rowRelationship: {
findUnique(args: {
where: { id: string };
include: typeof legacyRowRelationshipInclude;
}): Promise<LegacyRowRelationshipDetails | null>;
findFirst(args: {
where: Prisma.RowRelationshipWhereInput;
include: typeof legacyRowRelationshipInclude;
}): Promise<LegacyRowRelationshipDetails | null>;
create(args: {
data: LegacyRowRelationshipCreateInput;
include: typeof legacyRowRelationshipInclude;
}): Promise<LegacyRowRelationshipDetails>;
deleteMany(args: { where: Prisma.RowRelationshipWhereInput }): Promise<Prisma.BatchPayload>;
};
entityRelationship: {
findFirst(args: {
where: Prisma.EntityRelationshipWhereInput;
select: typeof selectLegacyEntityRelationshipProperties;
}): Promise<LegacyEntityRelationshipDetails | null>;
};
row: {
findFirst(args: {
where: Prisma.RowWhereInput;
select: { id: true };
}): Promise<LegacyRowRelationshipEntity | null>;
};
};
export const legacyRowRelationshipInclude = {
relationship: { select: { id: true, parentId: true, childId: true } },
} as const;
const selectLegacyEntityRelationshipProperties = {
id: true,
parentId: true,
childId: true,
} as const;
export async function findLegacyRowRelationshipById(
id: string,
tenantIdOrClient?: string | null | LegacyRelationshipClient,
client?: LegacyRelationshipClient,
): Promise<LegacyRowRelationshipDetails | null> {
const tenantId = typeof tenantIdOrClient === "string" || tenantIdOrClient === null ? tenantIdOrClient : undefined;
const db = tenantIdOrClient && typeof tenantIdOrClient === "object" ? tenantIdOrClient : client ?? (getDbClient() as unknown as LegacyRelationshipClient);
if (tenantId !== undefined) {
return db.rowRelationship.findFirst({
where: {
id,
parent: { tenantId, deletedAt: null },
child: { tenantId, deletedAt: null },
},
include: legacyRowRelationshipInclude,
});
}
return db.rowRelationship.findUnique({
where: { id },
include: legacyRowRelationshipInclude,
});
}
export async function createLegacyRowRelationship(
data: LegacyRowRelationshipCreateInput,
client: LegacyRelationshipClient = getDbClient() as unknown as LegacyRelationshipClient,
): Promise<LegacyRowRelationshipDetails> {
if (data.tenantId !== undefined) {
const entityRelationship = await client.entityRelationship.findFirst({
where: { id: data.relationshipId },
select: selectLegacyEntityRelationshipProperties,
});
if (!entityRelationship) {
throw new Error("Entity relationship not found.");
}
const [parent, child] = await Promise.all([
client.row.findFirst({
where: { id: data.parentId, tenantId: data.tenantId, entityId: entityRelationship.parentId, deletedAt: null },
select: { id: true },
}),
client.row.findFirst({
where: { id: data.childId, tenantId: data.tenantId, entityId: entityRelationship.childId, deletedAt: null },
select: { id: true },
}),
]);
if (!parent || !child) {
throw new Error("Relationship rows not found.");
}
}
const createData = { relationshipId: data.relationshipId, parentId: data.parentId, childId: data.childId };
return client.rowRelationship.create({
data: { ...createData, metadata: data.metadata ?? null },
include: legacyRowRelationshipInclude,
});
}
export async function deleteLegacyRowRelationshipById(
{ id, relationshipId, parentId, childId, tenantId }: LegacyRowRelationshipDeleteByIdInput,
client: LegacyRelationshipClient = getDbClient() as unknown as LegacyRelationshipClient,
): Promise<Prisma.BatchPayload> {
const deleted = await client.rowRelationship.deleteMany({
where: {
id,
relationshipId,
parentId,
childId,
parent: { tenantId, deletedAt: null },
child: { tenantId, deletedAt: null },
},
});
if (deleted.count !== 1) {
throw new Error(`Relationship ${id} not found`);
}
return deleted;
}
export async function deleteLegacyRowRelationship(
{ parentId, childId, relationshipId, tenantId }: { parentId: string; childId: string; relationshipId?: string; tenantId?: string | null },
client: LegacyRelationshipClient = getDbClient() as unknown as LegacyRelationshipClient,
): Promise<Prisma.BatchPayload> {
if (tenantId === undefined) {
throw new Error("Tenant id is required for relationship deletes.");
}
if (!relationshipId) {
throw new Error("Relationship id is required for scoped relationship deletes.");
}
const relationship = await client.rowRelationship.findFirst({
where: {
relationshipId,
parentId,
childId,
parent: { tenantId, deletedAt: null },
child: { tenantId, deletedAt: null },
},
include: legacyRowRelationshipInclude,
});
if (!relationship) {
throw new Error("Relationship rows not found.");
}
return deleteLegacyRowRelationshipById({ ...relationship, tenantId }, client);
}
export async function findLegacyEntityRelationship(
{ parentId, childId }: { parentId: string; childId: string },
client: LegacyRelationshipClient = getDbClient() as unknown as LegacyRelationshipClient,
): Promise<LegacyEntityRelationshipDetails | null> {
return client.entityRelationship.findFirst({
where: { parentId, childId },
select: selectLegacyEntityRelationshipProperties,
});
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,170 @@
import { describe, expect, it, vi } from "vitest";
import { assertSafeSeedCredentials, runDbSeed, type DbSeedDiagnosticEvent } from "./seed.server.js";
describe("@toolctrl/db seed helpers", () => {
it("rejects production seed runs with the default admin email before invoking the callback", async () => {
const seed = vi.fn();
expect(() =>
assertSafeSeedCredentials({
nodeEnv: "production",
adminEmail: "admin@email.com",
adminPassword: "not-default",
})
).toThrow("default seed credentials");
await expect(
runDbSeed({
nodeEnv: "production",
adminEmail: "admin@email.com",
adminPassword: "not-default",
seed,
})
).rejects.toThrow("default seed credentials");
expect(seed).not.toHaveBeenCalled();
});
it("rejects production seed runs with the default admin password without exposing it", async () => {
const seed = vi.fn();
await expect(
runDbSeed({
nodeEnv: "production",
adminEmail: "admin@example.com",
adminPassword: "password",
seed,
})
).rejects.toThrow("default seed credentials");
await expect(
runDbSeed({
nodeEnv: "production",
adminEmail: "admin@example.com",
adminPassword: "password",
seed,
})
).rejects.not.toThrow("password");
expect(seed).not.toHaveBeenCalled();
});
it("rejects production seed runs with blank admin credentials before invoking the callback", async () => {
const seed = vi.fn();
await expect(
runDbSeed({
nodeEnv: "production",
adminEmail: " ",
adminPassword: "safe-production-secret",
seed,
})
).rejects.toThrow("missing seed credentials");
await expect(
runDbSeed({
nodeEnv: "production",
adminEmail: "owner@example.com",
adminPassword: "",
seed,
})
).rejects.toThrow("missing seed credentials");
expect(seed).not.toHaveBeenCalled();
});
it("allows default credentials outside production", async () => {
await expect(
runDbSeed({
nodeEnv: "development",
adminEmail: "admin@email.com",
adminPassword: "password",
seed: async () => "seeded",
})
).resolves.toBe("seeded");
});
it("rejects production seed runs when any additional credential uses a default demo email", async () => {
const seed = vi.fn();
await expect(
runDbSeed({
nodeEnv: "production",
adminEmail: "owner@example.com",
adminPassword: "safe-production-secret",
seedCredentials: [{ label: "demo-user", email: "john.doe@company.com", password: "safe-demo-secret" }],
seed,
})
).rejects.toThrow("default seed credentials");
expect(seed).not.toHaveBeenCalled();
});
it("rejects production seed runs when any additional credential uses a default password", async () => {
const seed = vi.fn();
await expect(
runDbSeed({
nodeEnv: "production",
adminEmail: "owner@example.com",
adminPassword: "safe-production-secret",
seedCredentials: [{ label: "demo-user", email: "demo@example.com", password: "password" }],
seed,
})
).rejects.toThrow("default seed credentials");
expect(seed).not.toHaveBeenCalled();
});
it("emits start and success diagnostics without password values", async () => {
const diagnostics = vi.fn();
await expect(
runDbSeed({
nodeEnv: "test",
adminEmail: "admin@email.com",
adminPassword: "password",
seed: async () => "ok",
diagnostics,
})
).resolves.toBe("ok");
expect(diagnostics).toHaveBeenCalledTimes(2);
expect(diagnostics).toHaveBeenNthCalledWith(1, {
phase: "start",
nodeEnv: "test",
adminEmail: "admin@email.com",
});
expect(diagnostics).toHaveBeenNthCalledWith(2, {
phase: "success",
nodeEnv: "test",
adminEmail: "admin@email.com",
});
for (const [event] of diagnostics.mock.calls as [DbSeedDiagnosticEvent][]) {
expect(event).not.toHaveProperty("adminPassword");
expect(JSON.stringify(event)).not.toContain("password");
}
});
it("emits failure diagnostics and rethrows the original seed error", async () => {
const diagnostics = vi.fn();
const originalError = new Error("seed failed");
await expect(
runDbSeed({
nodeEnv: "test",
adminEmail: "admin@example.com",
adminPassword: "safe-secret",
seed: async () => {
throw originalError;
},
diagnostics,
})
).rejects.toBe(originalError);
expect(diagnostics).toHaveBeenCalledTimes(2);
expect(diagnostics).toHaveBeenNthCalledWith(2, {
phase: "failure",
nodeEnv: "test",
adminEmail: "admin@example.com",
error: originalError,
});
const failureEvent = diagnostics.mock.calls[1]?.[0] as DbSeedDiagnosticEvent;
expect(failureEvent).not.toHaveProperty("adminPassword");
expect(JSON.stringify(failureEvent)).not.toContain("safe-secret");
});
});
@@ -0,0 +1,83 @@
export type SeedEnvironment = "production" | "development" | "test" | (string & {});
export type DbSeedDiagnosticPhase = "start" | "success" | "failure";
export type DbSeedDiagnosticEvent = {
phase: DbSeedDiagnosticPhase;
nodeEnv: SeedEnvironment;
adminEmail?: string;
error?: unknown;
};
export type DbSeedDiagnostics = (event: DbSeedDiagnosticEvent) => void | Promise<void>;
export type DbSeedCallback<TResult = void> = () => Promise<TResult> | TResult;
export type SeedCredential = {
label?: string;
email?: string;
password?: string;
};
export type SafeSeedCredentialOptions = {
nodeEnv?: SeedEnvironment;
adminEmail?: string;
adminPassword?: string;
seedCredentials?: SeedCredential[];
};
export type RunDbSeedOptions<TResult = void> = SafeSeedCredentialOptions & {
seed: DbSeedCallback<TResult>;
diagnostics?: DbSeedDiagnostics;
};
const DEFAULT_ADMIN_PASSWORD = "password";
const DEFAULT_SEED_EMAILS = new Set(["admin@email.com", "john.doe@company.com", "luna.davis@company.com"]);
export function assertSafeSeedCredentials({
nodeEnv = process.env.NODE_ENV ?? "development",
adminEmail,
adminPassword,
seedCredentials = [],
}: SafeSeedCredentialOptions): void {
if (nodeEnv !== "production") {
return;
}
const credentials: SeedCredential[] = [{ label: "admin", email: adminEmail, password: adminPassword }, ...seedCredentials];
if (credentials.some((credential) => !credential.email?.trim() || !credential.password?.trim())) {
throw new Error("Refusing to run database seed in production with missing seed credentials.");
}
if (
credentials.some((credential) => (credential.email ? DEFAULT_SEED_EMAILS.has(credential.email) : false) || credential.password === DEFAULT_ADMIN_PASSWORD)
) {
throw new Error("Refusing to run database seed in production with default seed credentials.");
}
}
async function emitSeedDiagnostic(diagnostics: DbSeedDiagnostics | undefined, event: DbSeedDiagnosticEvent): Promise<void> {
await diagnostics?.(event);
}
export async function runDbSeed<TResult = void>({
nodeEnv = process.env.NODE_ENV ?? "development",
adminEmail,
adminPassword,
seedCredentials,
seed,
diagnostics,
}: RunDbSeedOptions<TResult>): Promise<TResult> {
assertSafeSeedCredentials({ nodeEnv, adminEmail, adminPassword, seedCredentials });
await emitSeedDiagnostic(diagnostics, { phase: "start", nodeEnv, adminEmail });
try {
const result = await seed();
await emitSeedDiagnostic(diagnostics, { phase: "success", nodeEnv, adminEmail });
return result;
} catch (error) {
await emitSeedDiagnostic(diagnostics, { phase: "failure", nodeEnv, adminEmail, error });
throw error;
}
}
@@ -0,0 +1,115 @@
import { describe, expect, it, vi } from "vitest";
import {
buildTenantSettingsRowCreateInput,
buildTenantSettingsRowUpdateInput,
findOptionalTenantSettingsEntity,
findTenantSettingsEntity,
findTenantWithSettingsById,
tenantSettingsDetailsInclude,
type TenantSettingsReaderClient,
} from "./settings.server.js";
function createSettingsReaderClient(entity: unknown = { id: "entity_1" }, tenant: unknown = { id: "tenant_1" }): TenantSettingsReaderClient {
return {
entity: {
findUnique: vi.fn().mockResolvedValue(entity),
},
tenant: {
findUnique: vi.fn().mockResolvedValue(tenant),
},
} as unknown as TenantSettingsReaderClient;
}
describe("tenant settings entity lookups", () => {
it("uses global property and template filters for global tenant settings entity lookup", async () => {
const entity = { id: "entity_1", name: "tenantSettings" };
const client = createSettingsReaderClient(entity);
await expect(findTenantSettingsEntity({ tenantId: null }, client)).resolves.toBe(entity);
expect(client.entity.findUnique).toHaveBeenCalledWith(
expect.objectContaining({
where: { name: "tenantSettings" },
include: expect.objectContaining({
properties: expect.objectContaining({
where: { tenantId: null },
orderBy: { order: "asc" },
}),
templates: { where: { tenantId: null } },
}),
}),
);
});
it("includes global and tenant-scoped properties/templates for tenant lookups", async () => {
const entity = { id: "entity_1", name: "tenantSettings" };
const client = createSettingsReaderClient(entity);
await expect(findTenantSettingsEntity({ tenantId: "tenant_1" }, client)).resolves.toBe(entity);
expect(client.entity.findUnique).toHaveBeenCalledWith(
expect.objectContaining({
where: { name: "tenantSettings" },
include: expect.objectContaining({
views: { include: { properties: true, filters: true, sort: true, groupByProperty: true } },
tags: true,
parentEntities: expect.objectContaining({ orderBy: { order: "asc" } }),
childEntities: expect.objectContaining({ orderBy: { order: "asc" } }),
properties: expect.objectContaining({
where: { OR: [{ tenantId: null }, { tenantId: "tenant_1" }] },
orderBy: { order: "asc" },
include: expect.objectContaining({
attributes: true,
options: { orderBy: { order: "asc" } },
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
}),
}),
templates: { where: { OR: [{ tenantId: null }, { tenantId: "tenant_1" }] } },
}),
}),
);
});
it("returns null for optional missing entity lookups", async () => {
const client = createSettingsReaderClient(null);
await expect(findOptionalTenantSettingsEntity({ tenantId: "tenant_1" }, client)).resolves.toBeNull();
});
});
describe("tenant settings tenant reads", () => {
it("loads tenant details with the settings row backing row", async () => {
const tenant = { id: "tenant_1", tenantSettingsRow: { row: { id: "row_1" } } };
const client = createSettingsReaderClient({ id: "entity_1" }, tenant);
await expect(findTenantWithSettingsById("tenant_1", client)).resolves.toBe(tenant);
expect(client.tenant.findUnique).toHaveBeenCalledWith({
where: { id: "tenant_1" },
include: tenantSettingsDetailsInclude,
});
expect(tenantSettingsDetailsInclude.tenantSettingsRow).toEqual({
include: { row: expect.objectContaining({ include: expect.any(Object) }) },
});
});
});
describe("tenant settings row input builders", () => {
it("builds tenant settings row create input from the explicit tenant id", () => {
expect(buildTenantSettingsRowCreateInput({ tenantId: "tenant_1", rowId: "row_1" })).toEqual({
tenantSettingsRow: {
create: {
rowId: "row_1",
},
},
});
});
it("builds row replacement input without unrelated tenant fields", () => {
expect(buildTenantSettingsRowUpdateInput("row_2")).toEqual({
tenantSettingsRow: {
update: {
rowId: "row_2",
},
},
});
});
});
@@ -0,0 +1,225 @@
import { getDbClient } from "./client.server.js";
import type { LegacyEntity } from "./entities.server.js";
import type { LegacyTenantWithDetails } from "./accounts.server.js";
import type { Prisma } from "./prisma-browser.js";
const selectTenantSettingsEntityWithoutIcon = {
id: true,
name: true,
title: true,
titlePlural: true,
slug: true,
onEdit: true,
} as const;
const includeTenantSettingsEntityViewDetails = {
properties: true,
filters: true,
sort: true,
groupByProperty: true,
} as const;
const selectTenantSettingsUserSummary = {
id: true,
email: true,
firstName: true,
lastName: true,
phone: true,
locale: true,
createdAt: true,
} as const;
const includeTenantSettingsRowDetails = {
createdByUser: { select: selectTenantSettingsUserSummary },
createdByApiKey: true,
tenant: true,
values: { include: { media: true, multiple: true, range: true } },
tags: { include: { tag: true } },
parentRows: {
include: {
parent: {
include: {
createdByUser: { select: selectTenantSettingsUserSummary },
createdByApiKey: true,
values: { include: { media: true, multiple: true, range: true } },
},
},
},
},
childRows: {
include: {
child: {
include: {
createdByUser: { select: selectTenantSettingsUserSummary },
createdByApiKey: true,
values: { include: { media: true, multiple: true, range: true } },
parentRows: {
include: {
parent: {
include: {
values: { include: { media: true, multiple: true, range: true } },
},
},
},
},
childRows: {
include: {
child: {
include: {
values: { include: { media: true, multiple: true, range: true } },
},
},
},
},
},
},
},
},
permissions: true,
sampleCustomEntity: true,
} as const;
function filterTenantSettingsTenantId(tenantId: string | null | undefined) {
const filter: { tenantId?: string | null; OR?: { tenantId?: string | null }[] } = {};
if (tenantId === undefined) {
return filter;
}
if (tenantId === null) {
filter.tenantId = null;
} else {
filter.OR = [{ tenantId: null }, { tenantId }];
}
return filter;
}
export function createTenantSettingsEntityDetailsInclude(tenantId: string | null | undefined) {
return {
views: { include: { properties: true, filters: true, sort: true, groupByProperty: true } },
tags: true,
parentEntities: {
include: {
parent: { select: selectTenantSettingsEntityWithoutIcon },
child: { select: selectTenantSettingsEntityWithoutIcon },
childEntityView: { include: includeTenantSettingsEntityViewDetails },
parentEntityView: { include: includeTenantSettingsEntityViewDetails },
},
orderBy: { order: "asc" },
},
childEntities: {
include: {
parent: { select: selectTenantSettingsEntityWithoutIcon },
child: { select: selectTenantSettingsEntityWithoutIcon },
childEntityView: { include: includeTenantSettingsEntityViewDetails },
parentEntityView: { include: includeTenantSettingsEntityViewDetails },
},
orderBy: { order: "asc" },
},
properties: {
where: { ...filterTenantSettingsTenantId(tenantId) },
orderBy: { order: "asc" },
include: {
attributes: true,
options: {
orderBy: {
order: "asc",
},
},
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
},
},
templates: {
where: { ...filterTenantSettingsTenantId(tenantId) },
},
} as const;
}
export const tenantSettingsDetailsInclude = {
inboundAddresses: true,
users: {
include: {
user: {
select: selectTenantSettingsUserSummary,
},
},
},
subscription: {
include: {
products: {
include: {
subscriptionProduct: { include: { features: true } },
prices: { include: { subscriptionPrice: true, subscriptionUsageBasedPrice: { include: { tiers: true } } } },
},
},
},
},
tenantSettingsRow: { include: { row: { include: includeTenantSettingsRowDetails } } },
types: true,
} as const;
export type TenantSettingsReaderClient = {
entity: {
findUnique(args: {
where: { name: string };
include: ReturnType<typeof createTenantSettingsEntityDetailsInclude>;
}): Promise<LegacyEntity | null>;
};
tenant: {
findUnique(args: {
where: { id: string };
include: typeof tenantSettingsDetailsInclude;
}): Promise<LegacyTenantWithDetails | null>;
};
};
export async function findOptionalTenantSettingsEntity(
{ tenantId, name = "tenantSettings" }: { tenantId: string | null | undefined; name?: string },
client: TenantSettingsReaderClient = getDbClient() as unknown as TenantSettingsReaderClient,
): Promise<LegacyEntity | null> {
return client.entity.findUnique({
where: { name },
include: createTenantSettingsEntityDetailsInclude(tenantId),
});
}
export async function findTenantSettingsEntity(
{ tenantId, name = "tenantSettings" }: { tenantId: string | null | undefined; name?: string },
client: TenantSettingsReaderClient = getDbClient() as unknown as TenantSettingsReaderClient,
): Promise<LegacyEntity> {
const entity = await findOptionalTenantSettingsEntity({ tenantId, name }, client);
if (!entity) {
throw new Error(`Tenant settings entity with name ${name} not found`);
}
return entity;
}
export async function findTenantWithSettingsById(
tenantId: string,
client: TenantSettingsReaderClient = getDbClient() as unknown as TenantSettingsReaderClient,
): Promise<LegacyTenantWithDetails | null> {
return client.tenant.findUnique({
where: { id: tenantId },
include: tenantSettingsDetailsInclude,
});
}
export function buildTenantSettingsRowCreateInput({ rowId }: { tenantId: string; rowId: string }): Prisma.TenantUpdateInput {
return {
tenantSettingsRow: {
create: {
rowId,
},
},
};
}
export function buildTenantSettingsRowUpdateInput(rowId: string): Prisma.TenantUpdateInput {
return {
tenantSettingsRow: {
update: {
rowId,
},
},
};
}
@@ -0,0 +1,72 @@
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
const repoRoot = resolve(__dirname, "../../..");
function readRepoFile(path: string) {
return readFileSync(resolve(repoRoot, path), "utf8");
}
const migratedWrappers = [
"apps/web/app/utils/db/subscriptionProducts.db.server.ts",
"apps/web/app/utils/db/tenantSubscriptions.db.server.ts",
"apps/web/app/utils/db/subscriptions/tenantSubscriptionProducts.db.server.ts",
"apps/web/app/utils/db/stripe/checkoutSessions.db.server.ts",
];
const directBillingPrismaModels = [
"subscriptionProduct",
"subscriptionPrice",
"subscriptionFeature",
"subscriptionUsageBasedPrice",
"subscriptionUsageBasedTier",
"tenantSubscription",
"tenantSubscriptionProduct",
"tenantSubscriptionProductPrice",
"tenantSubscriptionUsageRecord",
"checkoutSessionStatus",
];
describe("subscription app boundary", () => {
it.each(migratedWrappers)("keeps %s behind @toolctrl/db/subscriptions.server", (path) => {
const source = readRepoFile(path);
expect(source).toContain("@toolctrl/db/subscriptions.server");
expect(source).not.toContain("~/utils/db.server");
expect(source).not.toContain("../../db.server");
expect(source).not.toContain("../db.server");
expect(source).not.toMatch(/\bdb\.[a-zA-Z]/);
});
it("keeps subscriptionService subscription billing persistence behind the package boundary", () => {
const source = readRepoFile("apps/web/app/utils/services/.server/subscriptionService.ts");
expect(source).toContain("@toolctrl/db/subscriptions.server");
expect(source).toContain("../../db.server");
expect(source).toContain("clearCacheKey");
expect(source).toContain("cancelStripeSubscription");
expect(source).toContain("EventsService.create");
for (const model of directBillingPrismaModels) {
expect(source).not.toMatch(new RegExp(`\\bdb\\.${model}\\b`));
}
});
it("keeps tenant subscription route writes behind cache-clearing web wrappers", () => {
const routePaths = [
"apps/web/app/routes/subscribe.$tenant.tsx",
"apps/web/app/routes/app.$tenant/settings/subscription.tsx",
];
for (const path of routePaths) {
const source = readRepoFile(path);
const directPackageImport = source.match(/import\s+\{([^}]+)\}\s+from\s+["']@toolctrl\/db\/subscriptions\.server["']/s);
const importedNames = directPackageImport?.[1] ?? "";
expect(importedNames).not.toMatch(/\bcreateTenantSubscription\b/);
expect(importedNames).not.toMatch(/\bupdateTenantSubscriptionCustomerId\b/);
expect(source).toContain("~/utils/db/tenantSubscriptions.db.server");
}
});
});
@@ -0,0 +1,730 @@
import { describe, expect, it, vi } from "vitest";
import {
addTenantSubscriptionProduct,
adminGetTenantSubscriptionProductById,
cancelTenantSubscriptionProduct,
createCheckoutSessionStatus,
createSubscriptionFeature,
createSubscriptionPrice,
createSubscriptionProduct,
createSubscriptionUsageBasedPrice,
createSubscriptionUsageBasedTier,
createTenantSubscription,
createTenantSubscriptionUsageRecord,
deleteSubscriptionFeatures,
deleteSubscriptionPrice,
deleteSubscriptionProduct,
deleteSubscriptionUsageBasedPrice,
deleteSubscriptionUsageBasedTier,
findTenantSubscriptionProductByStripeSubscriptionId,
getEffectiveTenantEntitlementPlanId,
getAllSubscriptionFeatures,
getAllSubscriptionProducts,
getAllSubscriptionProductsWithTenants,
getSubscriptionPrice,
getSubscriptionPriceByStripeId,
getSubscriptionPrices,
getSubscriptionProduct,
getSubscriptionProductByStripeId,
getSubscriptionProductsInIds,
getSubscriptionUsageBasedPriceByStripeId,
getTenantSubscription,
getTenantSubscriptionProduct,
getTenantSubscriptionProductById,
getTenantSubscriptionProductByStripeSubscriptionId,
getTenantSubscriptions,
getAllTenantSubscriptionProducts,
getCheckoutSessionStatus,
listTenantSubscriptionIds,
updateCheckoutSessionStatus,
updateSubscriptionPrice,
updateSubscriptionPriceStripeId,
updateSubscriptionProduct,
updateSubscriptionProductStripeId,
updateTenantSubscriptionCustomerId,
updateTenantSubscriptionProduct,
updateTenantSubscriptionProductCustomEntitlementPlan,
updateTenantSubscriptionProductFromStripe,
type StripeTenantSubscriptionProductClient,
type SubscriptionCatalogClient,
type TenantBillingClient,
type TenantSubscriptionReaderClient,
} from "./subscriptions.server.js";
function createSubscriptionProductClient(items: unknown[] = []): SubscriptionCatalogClient {
return {
subscriptionProduct: {
findMany: vi.fn().mockResolvedValue(items),
findUnique: vi.fn().mockResolvedValue(items[0] ?? null),
findFirst: vi.fn().mockResolvedValue(items[0] ?? null),
create: vi.fn().mockResolvedValue(items[0] ?? { id: "plan_1" }),
update: vi.fn().mockResolvedValue(items[0] ?? { id: "plan_1" }),
delete: vi.fn().mockResolvedValue(items[0] ?? { id: "plan_1" }),
},
subscriptionPrice: {
findMany: vi.fn().mockResolvedValue(items),
findUnique: vi.fn().mockResolvedValue(items[0] ?? null),
findFirst: vi.fn().mockResolvedValue(items[0] ?? null),
create: vi.fn().mockResolvedValue(items[0] ?? { id: "price_1" }),
update: vi.fn().mockResolvedValue(items[0] ?? { id: "price_1" }),
delete: vi.fn().mockResolvedValue(items[0] ?? { id: "price_1" }),
},
subscriptionUsageBasedPrice: {
findFirst: vi.fn().mockResolvedValue(items[0] ?? null),
create: vi.fn().mockResolvedValue(items[0] ?? { id: "usage_price_1" }),
delete: vi.fn().mockResolvedValue(items[0] ?? { id: "usage_price_1" }),
},
subscriptionUsageBasedTier: {
create: vi.fn().mockResolvedValue(items[0] ?? { id: "tier_1" }),
delete: vi.fn().mockResolvedValue(items[0] ?? { id: "tier_1" }),
},
subscriptionFeature: {
findMany: vi.fn().mockResolvedValue(items),
create: vi.fn().mockResolvedValue(items[0] ?? { id: "feature_1" }),
deleteMany: vi.fn().mockResolvedValue({ count: 1 }),
},
} as unknown as SubscriptionCatalogClient;
}
function createTenantSubscriptionClient(items: unknown[] = []): TenantSubscriptionReaderClient {
return {
tenantSubscription: {
findMany: vi.fn().mockResolvedValue(items),
findUnique: vi.fn().mockResolvedValue(items[0] ?? null),
},
} as unknown as TenantSubscriptionReaderClient;
}
function createStripeTenantSubscriptionProductClient(item: unknown = null): StripeTenantSubscriptionProductClient {
return {
tenantSubscriptionProduct: {
findFirst: vi.fn().mockResolvedValue(item),
update: vi.fn().mockResolvedValue({ tenantSubscription: { tenantId: "tenant_1" } }),
},
} as unknown as StripeTenantSubscriptionProductClient;
}
function createTenantBillingClient(items: unknown[] = []): TenantBillingClient {
return {
tenantSubscription: {
findMany: vi.fn().mockResolvedValue(items.length > 0 ? items : [{ tenantId: "tenant_1" }]),
findUnique: vi.fn().mockResolvedValue(items[0] ?? null),
create: vi.fn().mockResolvedValue(items[0] ?? { id: "tenant_sub_1", tenantId: "tenant_1", products: [] }),
update: vi.fn().mockResolvedValue(items[0] ?? { id: "tenant_sub_1", tenantId: "tenant_1", stripeCustomerId: "cus_1" }),
},
tenantSubscriptionProduct: {
findMany: vi.fn().mockResolvedValue(items),
count: vi.fn().mockResolvedValue(items.length),
findFirst: vi.fn().mockResolvedValue(items[0] ?? null),
findUnique: vi.fn().mockResolvedValue(items[0] ?? null),
create: vi.fn().mockResolvedValue(items[0] ?? { id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } }),
update: vi.fn().mockResolvedValue(items[0] ?? { id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } }),
},
checkoutSessionStatus: {
findUnique: vi.fn().mockResolvedValue(items[0] ?? null),
create: vi.fn().mockResolvedValue(items[0] ?? { id: "cs_1", pending: true }),
update: vi.fn().mockResolvedValue(items[0] ?? { id: "cs_1", pending: false }),
},
tenantSubscriptionUsageRecord: {
create: vi.fn().mockResolvedValue(items[0] ?? { id: "usage_1" }),
},
} as unknown as TenantBillingClient;
}
describe("subscription product reads", () => {
it("fetches public active products with details", async () => {
const client = createSubscriptionProductClient([]);
await expect(getAllSubscriptionProducts(true, client)).resolves.toEqual([]);
expect(client.subscriptionProduct.findMany).toHaveBeenCalledWith({
where: { active: true, public: true },
include: {
tenantProducts: true,
usageBasedPrices: { include: { tiers: { orderBy: { from: "asc" } } } },
prices: true,
assignsTenantTypes: true,
features: { orderBy: { order: "asc" } },
},
orderBy: { order: "asc" },
});
});
it("fetches all active products when public-only is not requested", async () => {
const client = createSubscriptionProductClient([]);
await expect(getAllSubscriptionProducts(false, client)).resolves.toEqual([]);
expect(client.subscriptionProduct.findMany).toHaveBeenCalledWith({
where: { active: true },
include: {
tenantProducts: true,
usageBasedPrices: { include: { tiers: { orderBy: { from: "asc" } } } },
prices: true,
assignsTenantTypes: true,
features: { orderBy: { order: "asc" } },
},
orderBy: { order: "asc" },
});
});
it("preserves legacy empty-list behavior when broad product reads fail", async () => {
const client = createSubscriptionProductClient([]);
vi.mocked(client.subscriptionProduct.findMany).mockRejectedValueOnce(new Error("database unavailable"));
await expect(getAllSubscriptionProductsWithTenants(client)).resolves.toEqual([]);
});
it("fetches selected products by id without swallowing errors", async () => {
const client = createSubscriptionProductClient([]);
await expect(getSubscriptionProductsInIds(["plan_a", "plan_b"], client)).resolves.toEqual([]);
expect(client.subscriptionProduct.findMany).toHaveBeenCalledWith({
where: { id: { in: ["plan_a", "plan_b"] } },
include: {
tenantProducts: true,
usageBasedPrices: { include: { tiers: { orderBy: { from: "asc" } } } },
prices: true,
assignsTenantTypes: true,
features: { orderBy: { order: "asc" } },
},
orderBy: { order: "asc" },
});
});
it("fetches one product by id", async () => {
const product = { id: "plan_a" };
const client = createSubscriptionProductClient([product]);
await expect(getSubscriptionProduct("plan_a", client)).resolves.toBe(product);
expect(client.subscriptionProduct.findUnique).toHaveBeenCalledWith({
where: { id: "plan_a" },
include: {
tenantProducts: true,
usageBasedPrices: { include: { tiers: { orderBy: { from: "asc" } } } },
prices: true,
assignsTenantTypes: true,
features: { orderBy: { order: "asc" } },
},
});
});
it("fetches subscription feature summaries", async () => {
const client = createSubscriptionProductClient([]);
await expect(getAllSubscriptionFeatures(client)).resolves.toEqual([]);
expect(client.subscriptionFeature.findMany).toHaveBeenCalledWith({
select: { name: true, order: true, title: true, type: true, value: true, accumulate: true },
});
});
});
describe("subscription catalog helpers", () => {
it("fetches a product by Stripe id", async () => {
const product = { id: "plan_a", stripeId: "prod_123" };
const client = createSubscriptionProductClient([product]);
await expect(getSubscriptionProductByStripeId("prod_123", client)).resolves.toBe(product);
expect(client.subscriptionProduct.findFirst).toHaveBeenCalledWith({
where: { stripeId: "prod_123" },
});
});
it("fetches prices with products in admin ordering", async () => {
const client = createSubscriptionProductClient([]);
await expect(getSubscriptionPrices(client)).resolves.toEqual([]);
expect(client.subscriptionPrice.findMany).toHaveBeenCalledWith({
include: { subscriptionProduct: true },
orderBy: [{ subscriptionProduct: { order: "asc" } }, { price: "asc" }],
});
});
it("keeps legacy null and empty read behavior for price lookup failures", async () => {
const client = createSubscriptionProductClient([]);
vi.mocked(client.subscriptionPrice.findMany).mockRejectedValueOnce(new Error("read failed"));
vi.mocked(client.subscriptionPrice.findUnique).mockRejectedValueOnce(new Error("read failed"));
vi.mocked(client.subscriptionPrice.findFirst).mockRejectedValueOnce(new Error("read failed"));
vi.mocked(client.subscriptionUsageBasedPrice.findFirst).mockRejectedValueOnce(new Error("read failed"));
await expect(getSubscriptionPrices(client)).resolves.toEqual([]);
await expect(getSubscriptionPrice("price_1", client)).resolves.toBeNull();
await expect(getSubscriptionPriceByStripeId("price_stripe_1", client)).resolves.toBeNull();
await expect(getSubscriptionUsageBasedPriceByStripeId("metered_stripe_1", client)).resolves.toBeNull();
});
it("creates catalog rows without coercing decimal-compatible values", async () => {
const client = createSubscriptionProductClient([]);
const productData = {
stripeId: "prod_123",
order: 1,
title: "Pro",
model: 1,
description: null,
badge: null,
groupTitle: null,
groupDescription: null,
active: true,
public: true,
billingAddressCollection: "auto",
hasQuantity: false,
canBuyAgain: false,
};
const priceData = {
subscriptionProductId: "plan_a",
stripeId: "price_123",
type: 1,
billingPeriod: 1,
price: "19.99",
currency: "usd",
trialDays: 0,
active: true,
};
const usagePriceData = {
subscriptionProductId: "plan_a",
stripeId: "metered_123",
currency: "usd",
billingPeriod: 1,
unit: "api_call",
unitTitle: "API call",
unitTitlePlural: "API calls",
usageType: "metered",
aggregateUsage: "sum",
tiersMode: "graduated",
billingScheme: "tiered",
};
const tierData = {
subscriptionUsageBasedPriceId: "usage_price_1",
from: 1,
to: null,
perUnitPrice: "0.10",
flatFeePrice: null,
};
await createSubscriptionProduct(productData, client);
await createSubscriptionPrice(priceData, client);
await createSubscriptionUsageBasedPrice(usagePriceData, client);
await createSubscriptionUsageBasedTier(tierData, client);
await createSubscriptionFeature("plan_a", {
order: 1,
title: "Seats",
name: "seats",
type: 1,
value: 5,
href: null,
badge: null,
accumulate: false,
}, client);
expect(client.subscriptionProduct.create).toHaveBeenCalledWith({ data: productData });
expect(client.subscriptionPrice.create).toHaveBeenCalledWith({ data: priceData });
expect(client.subscriptionUsageBasedPrice.create).toHaveBeenCalledWith({ data: usagePriceData });
expect(client.subscriptionUsageBasedTier.create).toHaveBeenCalledWith({ data: tierData });
expect(client.subscriptionFeature.create).toHaveBeenCalledWith({
data: {
subscriptionProductId: "plan_a",
order: 1,
title: "Seats",
name: "seats",
type: 1,
value: 5,
href: null,
badge: null,
accumulate: false,
},
});
});
it("updates product and price catalog rows", async () => {
const client = createSubscriptionProductClient([]);
await updateSubscriptionProduct("plan_a", { title: "Business", public: false }, client);
await updateSubscriptionProductStripeId("plan_a", { stripeId: "prod_new" }, client);
await updateSubscriptionPrice("price_a", { price: "29.99", active: false }, client);
await updateSubscriptionPriceStripeId("price_a", { stripeId: "price_new" }, client);
expect(client.subscriptionProduct.update).toHaveBeenNthCalledWith(1, {
where: { id: "plan_a" },
data: { title: "Business", public: false },
});
expect(client.subscriptionProduct.update).toHaveBeenNthCalledWith(2, {
where: { id: "plan_a" },
data: { stripeId: "prod_new" },
});
expect(client.subscriptionPrice.update).toHaveBeenNthCalledWith(1, {
where: { id: "price_a" },
data: { price: "29.99", active: false },
});
expect(client.subscriptionPrice.update).toHaveBeenNthCalledWith(2, {
where: { id: "price_a" },
data: { stripeId: "price_new" },
});
});
it("deletes catalog rows with direct ids and product-scoped features", async () => {
const client = createSubscriptionProductClient([]);
await deleteSubscriptionProduct("plan_a", client);
await deleteSubscriptionPrice("price_a", client);
await deleteSubscriptionUsageBasedTier("tier_a", client);
await deleteSubscriptionUsageBasedPrice("usage_price_a", client);
await deleteSubscriptionFeatures("plan_a", client);
expect(client.subscriptionProduct.delete).toHaveBeenCalledWith({ where: { id: "plan_a" } });
expect(client.subscriptionPrice.delete).toHaveBeenCalledWith({ where: { id: "price_a" } });
expect(client.subscriptionUsageBasedTier.delete).toHaveBeenCalledWith({ where: { id: "tier_a" } });
expect(client.subscriptionUsageBasedPrice.delete).toHaveBeenCalledWith({ where: { id: "usage_price_a" } });
expect(client.subscriptionFeature.deleteMany).toHaveBeenCalledWith({ where: { subscriptionProductId: "plan_a" } });
});
it("propagates mutation failures instead of hiding failed Stripe sync", async () => {
const client = createSubscriptionProductClient([]);
const error = new Error("write failed");
vi.mocked(client.subscriptionPrice.update).mockRejectedValueOnce(error);
await expect(updateSubscriptionPrice("price_a", { active: false }, client)).rejects.toBe(error);
});
});
describe("tenant subscription reads", () => {
it("fetches a tenant subscription with product details", async () => {
const subscription = { id: "sub_1" };
const client = createTenantSubscriptionClient([subscription]);
await expect(getTenantSubscription("tenant_1", client)).resolves.toBe(subscription);
expect(client.tenantSubscription.findUnique).toHaveBeenCalledWith({
where: { tenantId: "tenant_1" },
include: {
products: {
include: {
subscriptionProduct: { include: { features: true } },
prices: { include: { subscriptionPrice: true, subscriptionUsageBasedPrice: { include: { tiers: true } } } },
},
orderBy: { subscriptionProduct: { order: "desc" } },
},
},
});
});
it("fetches all tenant subscriptions with product details", async () => {
const client = createTenantSubscriptionClient([]);
await expect(getTenantSubscriptions(client)).resolves.toEqual([]);
expect(client.tenantSubscription.findMany).toHaveBeenCalledWith({
include: {
products: {
include: {
subscriptionProduct: { include: { features: true } },
prices: { include: { subscriptionPrice: true, subscriptionUsageBasedPrice: { include: { tiers: true } } } },
},
orderBy: { subscriptionProduct: { order: "desc" } },
},
},
});
});
});
describe("tenant billing boundary", () => {
it("creates and updates tenant subscriptions", async () => {
const client = createTenantBillingClient([]);
await createTenantSubscription({ tenantId: "tenant_1", stripeCustomerId: "cus_1" }, client);
await updateTenantSubscriptionCustomerId("tenant_1", { stripeCustomerId: "cus_2" }, client);
await expect(listTenantSubscriptionIds(client)).resolves.toEqual([{ tenantId: "tenant_1" }]);
expect(client.tenantSubscription.create).toHaveBeenCalledWith({
data: { tenantId: "tenant_1", stripeCustomerId: "cus_1" },
include: {
products: {
include: {
subscriptionProduct: { include: { features: true } },
prices: { include: { subscriptionPrice: true, subscriptionUsageBasedPrice: { include: { tiers: true } } } },
},
orderBy: { subscriptionProduct: { order: "desc" } },
},
},
});
expect(client.tenantSubscription.update).toHaveBeenCalledWith({
where: { tenantId: "tenant_1" },
data: { stripeCustomerId: "cus_2" },
});
expect(client.tenantSubscription.findMany).toHaveBeenCalledWith({ select: { tenantId: true } });
});
it("maps tenant product filters and pagination for admin lists", async () => {
const now = new Date("2026-05-06T12:00:00.000Z");
const client = createTenantBillingClient([]);
await getAllTenantSubscriptionProducts(
{ tenantId: "tenant_1", subscriptionProductId: "plan_1", status: "active-not-cancelled" },
{ page: 2, pageSize: 25 },
client,
now,
);
const where = {
subscriptionProductId: { equals: "plan_1" },
tenantSubscription: { tenantId: { equals: "tenant_1" } },
OR: [{ endsAt: { gte: now } }, { endsAt: null }],
cancelledAt: null,
};
expect(client.tenantSubscriptionProduct.findMany).toHaveBeenCalledWith({
skip: 25,
take: 25,
where,
include: {
subscriptionProduct: { include: { features: true } },
prices: { include: { subscriptionPrice: true, subscriptionUsageBasedPrice: { include: { tiers: true } } } },
tenantSubscription: {
include: {
tenant: {
select: {
id: true,
name: true,
slug: true,
icon: true,
logo: true,
deactivatedReason: true,
active: true,
theme: true,
themeConfig: true,
},
},
},
},
},
orderBy: { createdAt: "desc" },
});
expect(client.tenantSubscriptionProduct.count).toHaveBeenCalledWith({ where });
});
it("maps ended and active-cancelled tenant product filters", async () => {
const now = new Date("2026-05-06T12:00:00.000Z");
const client = createTenantBillingClient([]);
await getAllTenantSubscriptionProducts({ status: "ended" }, undefined, client, now);
await getAllTenantSubscriptionProducts({ status: "active-cancelled" }, undefined, client, now);
expect(client.tenantSubscriptionProduct.findMany).toHaveBeenNthCalledWith(
1,
expect.objectContaining({
where: expect.objectContaining({ endsAt: { lt: now, not: null } }),
}),
);
expect(client.tenantSubscriptionProduct.findMany).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
where: expect.objectContaining({ OR: [{ endsAt: { gte: now } }, { endsAt: null }], cancelledAt: { not: null } }),
}),
);
});
it("looks up tenant products by tenant/product, id, and Stripe subscription id", async () => {
const item = { id: "tenant_product_1" };
const client = createTenantBillingClient([item]);
await expect(getTenantSubscriptionProduct("tenant_1", "plan_1", client)).resolves.toBe(item);
await expect(adminGetTenantSubscriptionProductById("tenant_product_1", client)).resolves.toBe(item);
await expect(getTenantSubscriptionProductById({ id: "tenant_product_1", tenantId: "tenant_1" }, client)).resolves.toBe(item);
await expect(getTenantSubscriptionProductByStripeSubscriptionId("sub_1", client)).resolves.toBe(item);
expect(client.tenantSubscriptionProduct.findFirst).toHaveBeenNthCalledWith(1, expect.objectContaining({
where: { tenantSubscription: { tenantId: "tenant_1" }, subscriptionProductId: "plan_1" },
}));
expect(client.tenantSubscriptionProduct.findUnique).toHaveBeenCalledWith(expect.objectContaining({ where: { id: "tenant_product_1" } }));
expect(client.tenantSubscriptionProduct.findFirst).toHaveBeenNthCalledWith(2, expect.objectContaining({ where: { id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } } }));
expect(client.tenantSubscriptionProduct.findFirst).toHaveBeenNthCalledWith(3, expect.objectContaining({ where: { stripeSubscriptionId: "sub_1" } }));
});
it("uses the billing product id when no custom entitlement override exists", () => {
expect(
getEffectiveTenantEntitlementPlanId({
subscriptionProductId: "plan_standard",
customEntitlementPlanId: null,
}),
).toBe("plan_standard");
});
it("uses the custom entitlement override ahead of the billing product id", () => {
expect(
getEffectiveTenantEntitlementPlanId({
subscriptionProductId: "plan_standard",
customEntitlementPlanId: "entitlements_enterprise_override",
}),
).toBe("entitlements_enterprise_override");
});
it("adds, updates, and cancels tenant products while returning tenant ids for cache invalidation", async () => {
const client = createTenantBillingClient([{ id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } }]);
await addTenantSubscriptionProduct(
{
tenantSubscriptionId: "tenant_sub_1",
subscriptionProductId: "plan_1",
stripeSubscriptionId: "sub_1",
quantity: 2,
fromCheckoutSessionId: "cs_1",
prices: [{ subscriptionPriceId: "price_1" }, { subscriptionUsageBasedPriceId: "usage_price_1" }],
},
client,
);
await updateTenantSubscriptionProduct({ id: "tenant_product_1", tenantId: "tenant_1" }, { quantity: 3, endsAt: null }, client);
await expect(
cancelTenantSubscriptionProduct(
{ id: "tenant_product_1", tenantId: "tenant_1" },
{ cancelledAt: new Date("2026-05-06T00:00:00.000Z"), endsAt: new Date("2026-06-06T00:00:00.000Z") },
client,
),
).resolves.toEqual({ tenantId: "tenant_1" });
expect(client.tenantSubscriptionProduct.create).toHaveBeenCalledWith({
data: {
tenantSubscriptionId: "tenant_sub_1",
subscriptionProductId: "plan_1",
stripeSubscriptionId: "sub_1",
quantity: 2,
fromCheckoutSessionId: "cs_1",
customEntitlementPlanId: undefined,
endsAt: null,
cancelledAt: null,
prices: { create: [{ subscriptionPriceId: "price_1" }, { subscriptionUsageBasedPriceId: "usage_price_1" }] },
},
include: { tenantSubscription: true },
});
expect(client.tenantSubscriptionProduct.update).toHaveBeenNthCalledWith(1, {
where: { id: "tenant_product_1" },
data: { quantity: 3, endsAt: null },
include: { tenantSubscription: true },
});
expect(client.tenantSubscriptionProduct.update).toHaveBeenNthCalledWith(2, {
where: { id: "tenant_product_1" },
data: { cancelledAt: new Date("2026-05-06T00:00:00.000Z"), endsAt: new Date("2026-06-06T00:00:00.000Z") },
include: { tenantSubscription: true },
});
});
it("updates only the custom entitlement plan override and returns tenant id", async () => {
const client = createTenantBillingClient([{ id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } }]);
await expect(
updateTenantSubscriptionProductCustomEntitlementPlan(
{ id: "tenant_product_1", tenantId: "tenant_1" },
{ customEntitlementPlanId: "entitlements_scale_override" },
client,
),
).resolves.toEqual({ tenantId: "tenant_1" });
expect(client.tenantSubscriptionProduct.update).toHaveBeenCalledWith({
where: { id: "tenant_product_1" },
data: { customEntitlementPlanId: "entitlements_scale_override" },
select: {
tenantSubscription: {
select: {
tenantId: true,
},
},
},
});
});
it("propagates custom entitlement override update rejections", async () => {
const client = createTenantBillingClient([{ id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } }]);
const error = new Error("write rejected");
vi.mocked(client.tenantSubscriptionProduct.update).mockRejectedValueOnce(error);
await expect(
updateTenantSubscriptionProductCustomEntitlementPlan({ id: "tenant_product_1", tenantId: "tenant_1" }, { customEntitlementPlanId: null }, client),
).rejects.toBe(error);
});
it("handles checkout status idempotency reads, creates, updates, and missing status", async () => {
const client = createTenantBillingClient([]);
vi.mocked(client.checkoutSessionStatus.findUnique).mockResolvedValueOnce(null);
await expect(getCheckoutSessionStatus("cs_missing", client)).resolves.toBeNull();
await createCheckoutSessionStatus({ id: "cs_1", email: "user@example.com", fromUrl: "/subscribe/acme" }, client);
await updateCheckoutSessionStatus("cs_1", { pending: false, createdUserId: "user_1" }, client);
expect(client.checkoutSessionStatus.create).toHaveBeenCalledWith({
data: { id: "cs_1", pending: true, email: "user@example.com", fromUrl: "/subscribe/acme", fromUserId: null, fromTenantId: null },
});
expect(client.checkoutSessionStatus.update).toHaveBeenCalledWith({
where: { id: "cs_1" },
data: { pending: false, createdUserId: "user_1", createdTenantId: null },
});
});
it("creates usage records and propagates write rejections", async () => {
const client = createTenantBillingClient([{ id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } }]);
const usageData = {
tenantSubscriptionProductPriceId: "tenant_price_1",
timestamp: 1_777_777,
quantity: 1,
stripeSubscriptionItemId: "si_1",
};
await createTenantSubscriptionUsageRecord(usageData, client);
expect(client.tenantSubscriptionUsageRecord.create).toHaveBeenCalledWith({ data: usageData });
const error = new Error("write rejected");
vi.mocked(client.tenantSubscriptionProduct.update).mockRejectedValueOnce(error);
await expect(updateTenantSubscriptionProduct({ id: "tenant_product_1", tenantId: "tenant_1" }, { quantity: 4 }, client)).rejects.toBe(error);
});
});
describe("stripe tenant subscription products", () => {
it("fetches the tenant subscription product needed by Stripe webhooks", async () => {
const item = { id: "tenant_product_1" };
const client = createStripeTenantSubscriptionProductClient(item);
await expect(findTenantSubscriptionProductByStripeSubscriptionId("sub_123", client)).resolves.toBe(item);
expect(client.tenantSubscriptionProduct.findFirst).toHaveBeenCalledWith({
where: { stripeSubscriptionId: "sub_123" },
select: {
id: true,
endsAt: true,
cancelledAt: true,
customEntitlementPlanId: true,
tenantSubscription: {
select: {
tenantId: true,
tenant: {
select: {
id: true,
name: true,
},
},
},
},
subscriptionProduct: {
select: {
id: true,
title: true,
},
},
},
});
});
it("updates Stripe subscription dates and returns the owning tenant id", async () => {
const client = createStripeTenantSubscriptionProductClient();
const data = {
cancelledAt: new Date("2026-05-01T00:00:00.000Z"),
currentPeriodStart: new Date("2026-05-01T00:00:00.000Z"),
currentPeriodEnd: new Date("2026-06-01T00:00:00.000Z"),
endsAt: null,
};
await expect(updateTenantSubscriptionProductFromStripe("tenant_product_1", data, client)).resolves.toEqual({ tenantId: "tenant_1" });
expect(client.tenantSubscriptionProduct.update).toHaveBeenCalledWith({
where: { id: "tenant_product_1" },
data,
select: {
tenantSubscription: {
select: {
tenantId: true,
},
},
},
});
});
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,73 @@
import { describe, expect, it, vi } from "vitest";
import { createInboundSupportTicketFromEmail, type SupportTicketClient } from "./support-tickets.server.js";
function createClient({
existingTicket = null,
inboundAddress = { tenantId: "tenant_1" },
}: {
existingTicket?: { id: string; tenantId: string | null } | null;
inboundAddress?: { tenantId: string } | null;
} = {}): SupportTicketClient {
return {
supportTicket: {
findUnique: vi.fn().mockResolvedValue(existingTicket),
create: vi.fn().mockResolvedValue({ id: "ticket_1", tenantId: inboundAddress?.tenantId ?? null }),
},
tenantInboundAddress: {
findUnique: vi.fn().mockResolvedValue(inboundAddress),
},
} as unknown as SupportTicketClient;
}
const input = {
messageId: "message_1",
toEmail: "support-acme@example.test",
fromEmail: "customer@example.test",
subject: "Need help",
message: "Something is broken.",
};
describe("createInboundSupportTicketFromEmail", () => {
it("creates a tenant-scoped support ticket for a known inbound address", async () => {
const client = createClient();
await expect(createInboundSupportTicketFromEmail(input, client)).resolves.toEqual({
status: "created",
ticketId: "ticket_1",
tenantId: "tenant_1",
});
expect(client.tenantInboundAddress.findUnique).toHaveBeenCalledWith({
where: { address: "support-acme@example.test" },
select: { tenantId: true },
});
expect(client.supportTicket.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
tenantId: "tenant_1",
source: "email",
inboundMessageId: "message_1",
}),
}),
);
});
it("returns duplicate without creating another ticket", async () => {
const client = createClient({ existingTicket: { id: "ticket_existing", tenantId: "tenant_1" } });
await expect(createInboundSupportTicketFromEmail(input, client)).resolves.toEqual({
status: "duplicate",
ticketId: "ticket_existing",
tenantId: "tenant_1",
});
expect(client.supportTicket.create).not.toHaveBeenCalled();
});
it("ignores unknown inbound recipients", async () => {
const client = createClient({ inboundAddress: null });
await expect(createInboundSupportTicketFromEmail(input, client)).resolves.toEqual({
status: "unknown-recipient",
});
expect(client.supportTicket.create).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,73 @@
import { Prisma } from "../generated/prisma/client/client.js";
import { getDbClient, type DbClient } from "./client.server.js";
export type InboundSupportTicketInput = {
messageId: string;
toEmail: string;
fromEmail: string;
subject: string;
message: string;
};
export type InboundSupportTicketResult =
| { status: "created"; ticketId: string; tenantId: string | null }
| { status: "duplicate"; ticketId: string; tenantId: string | null }
| { status: "unknown-recipient" };
export type SupportTicketClient = Pick<DbClient, "tenantInboundAddress" | "supportTicket">;
export async function createInboundSupportTicketFromEmail(
input: InboundSupportTicketInput,
client: SupportTicketClient = getDbClient(),
): Promise<InboundSupportTicketResult> {
const existing = await client.supportTicket.findUnique({
where: { inboundMessageId: input.messageId },
select: { id: true, tenantId: true },
});
if (existing) {
return { status: "duplicate", ticketId: existing.id, tenantId: existing.tenantId };
}
const inboundAddress = await client.tenantInboundAddress.findUnique({
where: { address: input.toEmail },
select: { tenantId: true },
});
if (!inboundAddress) {
return { status: "unknown-recipient" };
}
try {
const ticket = await client.supportTicket.create({
data: {
tenantId: inboundAddress.tenantId,
userId: null,
source: "email",
subject: truncate(input.subject.trim() || "Support request", 160),
message: input.message,
fromEmail: input.fromEmail,
inboundMessageId: input.messageId,
},
select: { id: true, tenantId: true },
});
return { status: "created", ticketId: ticket.id, tenantId: ticket.tenantId };
} catch (error) {
if (isUniqueConstraintError(error)) {
const duplicate = await client.supportTicket.findUnique({
where: { inboundMessageId: input.messageId },
select: { id: true, tenantId: true },
});
if (duplicate) {
return { status: "duplicate", ticketId: duplicate.id, tenantId: duplicate.tenantId };
}
}
throw error;
}
}
function truncate(value: string, maxLength: number) {
return value.length > maxLength ? value.slice(0, maxLength) : value;
}
function isUniqueConstraintError(error: unknown) {
return error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002";
}
@@ -0,0 +1,121 @@
import { describe, expect, it, vi } from "vitest";
import {
attachPrismaTelemetry,
noopPrismaTelemetryRecorder,
type PrismaExtendableClient,
type PrismaTelemetryEvent,
} from "./telemetry.server.js";
type CapturedExtension = Parameters<PrismaExtendableClient["$extends"]>[0];
function makeStubClient() {
let captured: CapturedExtension | undefined;
const stub: PrismaExtendableClient = {
$extends(extension) {
captured = extension;
return { __extended: true };
},
};
function extension(): CapturedExtension {
if (!captured) throw new Error("$extends was never called");
return captured;
}
return { stub, extension };
}
describe("attachPrismaTelemetry", () => {
it("records a successful query with model, operation, client kind and duration", async () => {
const events: PrismaTelemetryEvent[] = [];
const { stub, extension } = makeStubClient();
const returned = attachPrismaTelemetry(stub, {
client: "read",
record: (event) => events.push(event),
});
expect(returned).toEqual({ __extended: true });
expect(extension().name).toBe("rw-split-telemetry-read");
const handler = extension().query.$allModels.$allOperations;
const result = await handler({
model: "User",
operation: "findMany",
args: { where: { id: "u1" } },
query: async (passed) => ({ echoed: passed }),
});
expect(result).toEqual({ echoed: { where: { id: "u1" } } });
expect(events).toHaveLength(1);
expect(events[0]).toMatchObject({
client: "read",
model: "User",
operation: "findMany",
ok: true,
});
expect(events[0]!.durationMs).toBeGreaterThanOrEqual(0);
});
it("records a failed query and re-throws the underlying error unchanged", async () => {
const events: PrismaTelemetryEvent[] = [];
const { stub, extension } = makeStubClient();
attachPrismaTelemetry(stub, { client: "write", record: (event) => events.push(event) });
const handler = extension().query.$allModels.$allOperations;
const boom = new Error("db down");
await expect(
handler({
model: "OutboxEvent",
operation: "create",
args: { data: {} },
query: async () => {
throw boom;
},
})
).rejects.toBe(boom);
expect(events).toHaveLength(1);
expect(events[0]).toMatchObject({
client: "write",
model: "OutboxEvent",
operation: "create",
ok: false,
});
});
it("falls back to model='$none' for raw operations that have no model context", async () => {
const events: PrismaTelemetryEvent[] = [];
const { stub, extension } = makeStubClient();
attachPrismaTelemetry(stub, { client: "read", record: (event) => events.push(event) });
await extension().query.$allModels.$allOperations({
model: undefined,
operation: "$queryRaw",
args: ["SELECT 1"],
query: async () => [{ "?column?": 1 }],
});
expect(events[0]).toMatchObject({
client: "read",
model: "$none",
operation: "$queryRaw",
ok: true,
});
});
it("invokes the recorder once per query and uses the provided client kind label", async () => {
const record = vi.fn();
const { stub, extension } = makeStubClient();
attachPrismaTelemetry(stub, { client: "write", record });
const handler = extension().query.$allModels.$allOperations;
await handler({ model: "Tenant", operation: "findUnique", args: {}, query: async () => null });
await handler({ model: "Tenant", operation: "update", args: {}, query: async () => null });
expect(record).toHaveBeenCalledTimes(2);
expect(record.mock.calls.every((call) => (call[0] as PrismaTelemetryEvent).client === "write")).toBe(true);
});
it("exposes a noop recorder for call-sites without a metrics sink", () => {
expect(() => noopPrismaTelemetryRecorder({ client: "read", model: "X", operation: "y", durationMs: 1, ok: true })).not.toThrow();
});
});
@@ -0,0 +1,116 @@
/**
* Prisma R/W-split telemetry.
*
* Attaches a query-counter to a Prisma client via `$extends({ query: ... })`
* — Prisma 7's replacement for the deprecated `$use` middleware API. The
* counter labels each query with `client="read"|"write"` plus the Prisma
* `model` and `operation`, so Grafana panels can visualise the split.
*
* The recorder is injected so this module stays decoupled from any concrete
* metrics SDK. The web/api/worker apps wire their `@toolctrl/metrics`
* `prismaQueryDurationSeconds` histogram (or, in the OTel-future, an OTel
* Meter) by passing a recorder closure.
*
* Counter contract (per the read-write-split spec):
* `prisma.queries.total{client="read|write",model,operation}`
*
* The duration is recorded in milliseconds as a second positional argument
* so callers can simultaneously feed a histogram if they want.
*/
export type PrismaTelemetryClientKind = "read" | "write";
export type PrismaTelemetryEvent = {
/** "read" when the caller wired this on the replica client. */
client: PrismaTelemetryClientKind;
/** Prisma model name, e.g. "User"; "$none" for `$queryRaw` / `$executeRaw`. */
model: string;
/** Prisma operation, e.g. "findMany", "create", "upsert". */
operation: string;
/** Wall-clock duration of the underlying query in milliseconds. */
durationMs: number;
/** Whether the underlying query threw. */
ok: boolean;
};
export type PrismaTelemetryRecorder = (event: PrismaTelemetryEvent) => void;
export type AttachPrismaTelemetryOptions = {
client: PrismaTelemetryClientKind;
record: PrismaTelemetryRecorder;
};
/**
* Shape we need from a Prisma client to attach query telemetry. Kept
* structural so unit tests can pass a tiny stub instead of a real
* PrismaClient.
*/
export type PrismaExtendableClient = {
$extends: (extension: {
name: string;
query: {
$allModels: {
$allOperations: (args: {
model: string | undefined;
operation: string;
args: unknown;
query: (args: unknown) => Promise<unknown>;
}) => Promise<unknown>;
};
};
}) => unknown;
};
/**
* Wraps a Prisma client with a `$extends({ query: ... })` that records
* every operation through `options.record`. Returns the extended client.
*
* Errors thrown by the underlying query are re-thrown unchanged after
* recording the failed attempt (so failed-query counters work too).
*/
export function attachPrismaTelemetry<TClient extends PrismaExtendableClient>(
client: TClient,
options: AttachPrismaTelemetryOptions
): ReturnType<TClient["$extends"]> {
const { client: clientKind, record } = options;
return client.$extends({
name: `rw-split-telemetry-${clientKind}`,
query: {
$allModels: {
async $allOperations({ model, operation, args, query }) {
const start = performance.now();
try {
const result = await query(args);
record({
client: clientKind,
model: model ?? "$none",
operation,
durationMs: performance.now() - start,
ok: true,
});
return result;
} catch (error) {
record({
client: clientKind,
model: model ?? "$none",
operation,
durationMs: performance.now() - start,
ok: false,
});
throw error;
}
},
},
},
}) as ReturnType<TClient["$extends"]>;
}
/**
* No-op recorder used as a safe default when no telemetry sink is wired.
* Keeps the call-site type-safe without forcing every consumer to provide
* a recorder.
*/
export const noopPrismaTelemetryRecorder: PrismaTelemetryRecorder = () => {
// intentionally empty
};
@@ -0,0 +1,69 @@
import { describe, expect, it, vi } from "vitest";
import type { Prisma } from "../generated/prisma/client/client.js";
import {
runDbTransaction,
runDbTransactionBatch,
type DbTransactionClient,
type DbTransactionRunner,
} from "./transactions.server.js";
describe("@toolctrl/db transaction helpers", () => {
it("returns the callback transaction result with an injected client", async () => {
const transaction = { user: { count: vi.fn() } } as unknown as DbTransactionClient;
const client = {
$transaction: vi.fn(async (callback: (tx: DbTransactionClient) => Promise<string>) =>
callback(transaction),
),
} as unknown as DbTransactionRunner;
await expect(
runDbTransaction(async (tx) => {
expect(tx).toBe(transaction);
return "committed";
}, client),
).resolves.toBe("committed");
expect(client.$transaction).toHaveBeenCalledTimes(1);
});
it("returns batch transaction results with an injected client", async () => {
const operations = [
Promise.resolve("first") as Prisma.PrismaPromise<string>,
Promise.resolve("second") as Prisma.PrismaPromise<string>,
];
const client = {
$transaction: vi.fn(async (batch: Prisma.PrismaPromise<string>[]) => Promise.all(batch)),
} as unknown as DbTransactionRunner;
await expect(runDbTransactionBatch(operations, client)).resolves.toEqual([
"first",
"second",
]);
expect(client.$transaction).toHaveBeenCalledWith(operations);
});
it("does not require the default client when an explicit client is provided", async () => {
const client = {
$transaction: vi.fn(async () => "explicit-client"),
} as unknown as DbTransactionRunner;
await expect(
runDbTransaction(async () => "unreachable", client),
).resolves.toBe("explicit-client");
});
it("propagates the original error from a rejected callback transaction", async () => {
const originalError = new Error("rollback me");
const client = {
$transaction: vi.fn(async (callback: (tx: DbTransactionClient) => Promise<never>) =>
callback({} as DbTransactionClient),
),
} as unknown as DbTransactionRunner;
await expect(
runDbTransaction(async () => {
throw originalError;
}, client),
).rejects.toBe(originalError);
});
});
@@ -0,0 +1,21 @@
import { Prisma } from "../generated/prisma/client/client.js";
import { getDbClient, type DbClient } from "./client.server.js";
export type DbTransactionClient = Omit<DbClient, "$connect" | "$disconnect" | "$on" | "$transaction" | "$use" | "$extends">;
export type DbTransactionRunner = Pick<DbClient, "$transaction">;
export function runDbTransaction<TResult>(
callback: (transaction: DbTransactionClient) => Promise<TResult>,
client: DbTransactionRunner = getDbClient(),
): Promise<TResult> {
return client.$transaction((transaction) => callback(transaction));
}
export function runDbTransactionBatch<TResult>(
operations: readonly Prisma.PrismaPromise<TResult>[],
client: DbTransactionRunner = getDbClient(),
): Promise<TResult[]> {
return client.$transaction([...operations]);
}
@@ -0,0 +1,127 @@
import { describe, expect, it, vi } from "vitest";
import {
formatTenantApiUsagePlanTitle,
getTenantApiUsage,
mergeApiSubscriptionFeatures,
SUBSCRIPTION_FEATURE_LIMIT,
} from "./usage.server.js";
import type { TenantSubscriptionWithDetails } from "./subscriptions.server.js";
import type { LegacyApiKeyLogWriterClient } from "./api-keys.server.js";
const API_USAGE_TITLE_TEMPLATE = "{0} API calls";
function createSubscription(
feature: { title?: string; type: number; value: number; accumulate?: boolean },
overrides: Partial<TenantSubscriptionWithDetails["products"][number]> = {},
): TenantSubscriptionWithDetails {
return {
id: "subscription_1",
tenantId: "tenant_1",
active: true,
stripeCustomerId: null,
createdAt: new Date("2026-01-01T00:00:00.000Z"),
updatedAt: new Date("2026-01-01T00:00:00.000Z"),
products: [
{
id: "tenant_product_1",
tenantSubscriptionId: "subscription_1",
subscriptionProductId: "product_1",
quantity: 1,
cancelledAt: null,
currentPeriodStart: new Date("2026-02-01T00:00:00.000Z"),
currentPeriodEnd: new Date("2026-03-01T00:00:00.000Z"),
endsAt: null,
stripeSubscriptionId: null,
createdAt: new Date("2026-01-01T00:00:00.000Z"),
updatedAt: new Date("2026-01-01T00:00:00.000Z"),
subscriptionProduct: {
id: "product_1",
order: 0,
title: "Pro",
model: 0,
public: true,
groupTitle: null,
groupDescription: null,
description: null,
badge: null,
billingAddressCollection: null,
hasQuantity: false,
canBuyAgain: false,
createdAt: new Date("2026-01-01T00:00:00.000Z"),
updatedAt: new Date("2026-01-01T00:00:00.000Z"),
features: [
{
id: "feature_1",
subscriptionProductId: "product_1",
order: 0,
name: "api",
title: feature.title ?? API_USAGE_TITLE_TEMPLATE,
type: feature.type,
value: feature.value,
href: null,
badge: null,
accumulate: feature.accumulate ?? false,
createdAt: new Date("2026-01-01T00:00:00.000Z"),
updatedAt: new Date("2026-01-01T00:00:00.000Z"),
},
],
},
prices: [],
...overrides,
},
],
} as unknown as TenantSubscriptionWithDetails;
}
function createUsageClient(count: number): LegacyApiKeyLogWriterClient {
return {
apiKeyLog: {
count: vi.fn().mockResolvedValue(count),
},
} as unknown as LegacyApiKeyLogWriterClient;
}
describe("tenant API usage boundary", () => {
it("resolves monthly usage through the tenant-scoped API key log boundary", async () => {
const subscription = createSubscription({ type: SUBSCRIPTION_FEATURE_LIMIT.monthly, value: 10 });
const client = createUsageClient(7);
const usage = await getTenantApiUsage("tenant_1", subscription, client);
expect(usage).toMatchObject({ enabled: true, used: 7, remaining: 3 });
expect(client.apiKeyLog.count).toHaveBeenCalledWith({
where: {
tenantId: "tenant_1",
status: { in: [200, 201, 202, 203, 204, 205, 206, 207, 208, 226] },
endpoint: { notIn: ["/v1/usage"] },
createdAt: {
gte: new Date("2026-02-01T00:00:00.000Z"),
lt: new Date("2026-03-01T00:00:00.000Z"),
},
},
});
});
it("marks usage disabled when a capped plan is exhausted", async () => {
const usage = await getTenantApiUsage("tenant_1", createSubscription({ type: SUBSCRIPTION_FEATURE_LIMIT.max, value: 2 }), createUsageClient(3));
expect(usage).toMatchObject({
enabled: false,
remaining: -1,
message: "You have reached the API usage limit (3/2).",
});
});
it("formats plan titles and merges accumulated feature quantities", () => {
const first = createSubscription({ type: SUBSCRIPTION_FEATURE_LIMIT.monthly, value: 5, accumulate: true }).products[0].subscriptionProduct.features[0];
const second = { ...first, id: "feature_2", value: 7 };
const merged = mergeApiSubscriptionFeatures([first, second]);
expect(merged).toMatchObject({ type: SUBSCRIPTION_FEATURE_LIMIT.monthly, value: 12 });
expect(formatTenantApiUsagePlanTitle({ title: API_USAGE_TITLE_TEMPLATE, type: 2, value: 12, used: 0, remaining: 12, enabled: true, message: "" })).toBe(
"12 API calls",
);
});
});
@@ -0,0 +1,129 @@
import { countLegacyTenantApiKeyUsage, type LegacyApiKeyLogWriterClient } from "./api-keys.server.js";
import type { TenantSubscriptionWithDetails } from "./subscriptions.server.js";
export const API_USAGE_FEATURE_NAME = "api";
export const API_KEY_CREDITABLE_STATUS_CODES = [200, 201, 202, 203, 204, 205, 206, 207, 208, 226];
export const API_KEY_USAGE_IGNORED_ENDPOINTS = ["/v1/usage"];
export const SUBSCRIPTION_FEATURE_LIMIT = {
notIncluded: 0,
included: 1,
monthly: 2,
max: 3,
unlimited: 4,
} as const;
const API_USAGE_NOT_INCLUDED_MESSAGE = "API usage is not included in this plan.";
export type TenantApiUsageFeature = {
title: string;
type: number;
value: number;
used: number;
remaining: number | "unlimited";
enabled: boolean;
message: string;
};
type SubscriptionFeature = TenantSubscriptionWithDetails["products"][number]["subscriptionProduct"]["features"][number];
export async function getTenantApiUsage(
tenantId: string,
subscription: TenantSubscriptionWithDetails | null,
client?: LegacyApiKeyLogWriterClient,
): Promise<TenantApiUsageFeature | undefined> {
const features = subscription?.products.flatMap((product) => {
const feature = product.subscriptionProduct.features.find((item) => item.name === API_USAGE_FEATURE_NAME);
if (!feature) return [];
const quantity = product.quantity && product.quantity > 0 ? product.quantity : 1;
return Array.from({ length: quantity }, () => feature);
});
const merged = mergeApiSubscriptionFeatures(features ?? []);
if (!merged) {
return undefined;
}
const usage: TenantApiUsageFeature = {
title: merged.title,
type: merged.type,
value: merged.value,
used: 0,
remaining: 0,
enabled: merged.type !== SUBSCRIPTION_FEATURE_LIMIT.notIncluded,
message: API_USAGE_NOT_INCLUDED_MESSAGE,
};
if (merged.type === SUBSCRIPTION_FEATURE_LIMIT.monthly || merged.type === SUBSCRIPTION_FEATURE_LIMIT.max) {
const period = merged.type === SUBSCRIPTION_FEATURE_LIMIT.monthly ? getCurrentSubscriptionPeriod(subscription) : undefined;
usage.used = await countLegacyTenantApiKeyUsage(
{
tenantId,
statuses: API_KEY_CREDITABLE_STATUS_CODES,
ignoredEndpoints: API_KEY_USAGE_IGNORED_ENDPOINTS,
period,
},
client,
);
usage.remaining = merged.value - usage.used;
if (usage.remaining <= 0) {
usage.enabled = false;
usage.message = createApiUsageLimitExceededMessage(merged.type, usage.used, usage.value);
}
} else if (merged.type === SUBSCRIPTION_FEATURE_LIMIT.unlimited) {
usage.remaining = "unlimited";
}
return usage;
}
function createApiUsageLimitExceededMessage(type: number, used: number, value: number): string {
return type === SUBSCRIPTION_FEATURE_LIMIT.monthly
? `You have reached the API usage limit this month (${used}/${value}).`
: `You have reached the API usage limit (${used}/${value}).`;
}
export function formatTenantApiUsagePlanTitle(usage: TenantApiUsageFeature): string {
return usage.title.replace("{0}", String(usage.value));
}
export function mergeApiSubscriptionFeatures(features: readonly SubscriptionFeature[]): { title: string; type: number; value: number; accumulate: boolean } | undefined {
if (features.length === 0) {
return undefined;
}
const merged: { title: string; type: number; value: number; accumulate: boolean } = {
title: features[0].title,
type: SUBSCRIPTION_FEATURE_LIMIT.notIncluded,
value: 0,
accumulate: features[0].accumulate,
};
let firstFeature = true;
for (const feature of features) {
if (merged.type < feature.type) {
merged.type = feature.type;
}
if (merged.accumulate || firstFeature) {
merged.value += feature.value;
}
firstFeature = false;
}
return merged;
}
export function getCurrentSubscriptionPeriod(subscription: TenantSubscriptionWithDetails | null): { start: Date; end: Date } {
const now = new Date();
let start = new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 1);
let end = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59);
if (now.getMonth() === 11) {
end = new Date(now.getFullYear() + 1, 0, 0, 23, 59, 59);
}
for (const product of subscription?.products ?? []) {
if (product.currentPeriodStart && product.currentPeriodEnd) {
start = product.currentPeriodStart;
end = product.currentPeriodEnd;
}
}
return { start, end };
}
@@ -0,0 +1,51 @@
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
const repoRoot = resolve(__dirname, "../../..");
const schemaPath = resolve(repoRoot, "prisma/schema/permissions.prisma");
const migrationPath = resolve(repoRoot, "prisma/migrations/20260528153000_user_role_assignment_uniqueness/migration.sql");
async function readUserRoleModel() {
const schema = await readFile(schemaPath, "utf8");
const match = schema.match(/model UserRole \{(?<body>[\s\S]*?)\n\}/);
expect(match?.groups?.body, "UserRole model exists in permissions Prisma schema").toBeTruthy();
return match?.groups?.body ?? "";
}
describe("UserRole schema contract", () => {
it("documents nullable tenant assignment uniqueness as migration-managed partial indexes", async () => {
const userRoleModel = await readUserRoleModel();
expect(userRoleModel, "tenant scope remains nullable for admin roles").toMatch(/^\s*tenantId\s+String\?/m);
expect(userRoleModel, "Prisma schema documents why uniqueness is migration-managed").toContain(
"Assignment uniqueness is enforced by partial indexes in migration SQL",
);
expect(userRoleModel, "lookup index remains available for user/role/tenant reads").toMatch(
/@@index\(\[userId,\s*roleId,\s*tenantId\],\s*name:\s*"user_role_user_role_tenant_idx"\)/,
);
expect(userRoleModel, "Prisma should not declare a nullable composite unique that misses NULL admin duplicates").not.toMatch(
/@@unique\(\[userId,\s*roleId,\s*tenantId\]/,
);
});
it("adds partial unique indexes for tenant and admin assignments with duplicate preflight checks", async () => {
const migrationSql = await readFile(migrationPath, "utf8");
expect(migrationSql, "migration rejects existing tenant-scope duplicates before indexing").toMatch(
/WHERE\s+"tenantId"\s+IS\s+NOT\s+NULL[\s\S]*GROUP\s+BY\s+"userId",\s*"roleId",\s*"tenantId"[\s\S]*HAVING\s+COUNT\(\*\)\s*>\s*1/i,
);
expect(migrationSql, "migration rejects existing admin-scope duplicates before indexing").toMatch(
/WHERE\s+"tenantId"\s+IS\s+NULL[\s\S]*GROUP\s+BY\s+"userId",\s*"roleId"[\s\S]*HAVING\s+COUNT\(\*\)\s*>\s*1/i,
);
expect(migrationSql, "tenant assignments are unique when tenantId is present").toMatch(
/CREATE\s+UNIQUE\s+INDEX\s+IF\s+NOT\s+EXISTS\s+"user_role_tenant_assignment_key"\s+ON\s+"UserRole"\s*\(\s*"userId"\s*,\s*"roleId"\s*,\s*"tenantId"\s*\)\s*WHERE\s+"tenantId"\s+IS\s+NOT\s+NULL/i,
);
expect(migrationSql, "admin assignments are unique when tenantId is null").toMatch(
/CREATE\s+UNIQUE\s+INDEX\s+IF\s+NOT\s+EXISTS\s+"user_role_admin_assignment_key"\s+ON\s+"UserRole"\s*\(\s*"userId"\s*,\s*"roleId"\s*\)\s*WHERE\s+"tenantId"\s+IS\s+NULL/i,
);
});
});
@@ -0,0 +1,142 @@
import { describe, expect, it, vi } from "vitest";
import {
findLegacyAuthUserById,
findLegacyLoginUserByEmail,
findLegacyUserWithoutPasswordById,
recordLegacyLogin,
type LegacyAuthUserReaderClient,
type LegacyLoginLogWriterClient,
type LegacyLoginUserReaderClient,
type LegacyUserWithoutPasswordReaderClient,
} from "./users.server.js";
describe("findLegacyAuthUserById", () => {
it("fetches only the legacy auth user fields by id", async () => {
const findUnique = vi.fn().mockResolvedValue({
id: "user_123",
email: "user@example.com",
passwordHash: "should-not-leak",
});
const client = {
user: { findUnique },
} as unknown as LegacyAuthUserReaderClient;
await expect(findLegacyAuthUserById("user_123", client)).resolves.toEqual({
id: "user_123",
email: "user@example.com",
});
expect(findUnique).toHaveBeenCalledWith({
where: { id: "user_123" },
select: { id: true, email: true },
});
});
it("returns null when the user does not exist", async () => {
const client: LegacyAuthUserReaderClient = {
user: {
findUnique: vi.fn().mockResolvedValue(null),
},
};
await expect(findLegacyAuthUserById("missing", client)).resolves.toBeNull();
});
it("fetches only the legacy login user fields by email", async () => {
const findUnique = vi.fn().mockResolvedValue({
id: "user_123",
email: "user@example.com",
passwordHash: "hash",
firstName: "should-not-leak",
});
const client = {
user: { findUnique },
} as unknown as LegacyLoginUserReaderClient;
await expect(findLegacyLoginUserByEmail("user@example.com", client)).resolves.toEqual({
id: "user_123",
email: "user@example.com",
passwordHash: "hash",
});
expect(findUnique).toHaveBeenCalledWith({
where: { email: "user@example.com" },
select: { id: true, email: true, passwordHash: true },
});
});
it("returns null when the login user does not exist", async () => {
const client: LegacyLoginUserReaderClient = {
user: {
findUnique: vi.fn().mockResolvedValue(null),
},
};
await expect(findLegacyLoginUserByEmail("missing@example.com", client)).resolves.toBeNull();
});
it("fetches the legacy user fields required by API bearer auth", async () => {
const user = {
id: "user_123",
email: "user@example.com",
firstName: "Ada",
lastName: "Lovelace",
avatar: null,
phone: null,
admin: null,
defaultTenantId: null,
createdAt: new Date("2026-05-01T00:00:00.000Z"),
locale: "de",
};
const findUnique = vi.fn().mockResolvedValue(user);
const client = {
user: { findUnique },
} as unknown as LegacyUserWithoutPasswordReaderClient;
await expect(findLegacyUserWithoutPasswordById("user_123", client)).resolves.toBe(user);
expect(findUnique).toHaveBeenCalledWith({
where: { id: "user_123" },
select: {
id: true,
email: true,
firstName: true,
lastName: true,
avatar: true,
phone: true,
admin: true,
defaultTenantId: true,
createdAt: true,
locale: true,
lightOrDarkMode: true,
},
});
});
it("returns null when no legacy user id is provided", async () => {
const client: LegacyUserWithoutPasswordReaderClient = {
user: {
findUnique: vi.fn(),
},
};
await expect(findLegacyUserWithoutPasswordById(undefined, client)).resolves.toBeNull();
expect(client.user.findUnique).not.toHaveBeenCalled();
});
it("records legacy login logs", async () => {
const create = vi.fn().mockResolvedValue({});
const client: LegacyLoginLogWriterClient = {
log: { create },
};
await recordLegacyLogin("user_123", client);
expect(create).toHaveBeenCalledWith({
data: {
userId: "user_123",
url: "",
action: "Login",
details: "",
},
});
});
});
@@ -0,0 +1,184 @@
import { getDbClient } from "./client.server.js";
export type LegacyAuthUser = {
id: string;
email: string;
};
export type LegacyUserWithoutPassword = {
id: string;
email: string;
firstName: string;
lastName: string;
avatar: string | null;
phone: string | null;
admin?: {
userId: string;
// Phase 09 #82 — Authentik SSO fields. Nullable for legacy/password-only
// admins predating the SSO rollout.
ssoProvider: string | null;
ssoSubjectId: string | null;
ssoGroups: string[];
lastSsoLoginAt: Date | null;
} | null;
defaultTenantId: string | null;
createdAt: Date;
locale: string | null;
lightOrDarkMode: string | null;
};
export type LegacyLoginUser = LegacyAuthUser & {
// Phase 01 / #20 — `User.passwordHash` is nullable for magic-link-only
// accounts (invitation flow). Login callers must reject `null` as
// "use magic-link" rather than falling through to a hash compare.
passwordHash: string | null;
};
export type LegacyAuthUserReaderClient = {
user: {
findUnique(args: {
where: { id: string };
select: { id: true; email: true };
}): Promise<LegacyAuthUser | null>;
};
};
export type LegacyUserWithoutPasswordReaderClient = {
user: {
findUnique(args: {
where: { id: string };
select: typeof selectLegacyUserWithoutPassword;
}): Promise<LegacyUserWithoutPassword | null>;
};
};
export type LegacyLoginUserReaderClient = {
user: {
findUnique(args: {
where: { email: string };
select: { id: true; email: true; passwordHash: true };
}): Promise<(LegacyAuthUser & { passwordHash: string | null }) | null>;
};
};
export type LegacyLoginLogWriterClient = {
log: {
create(args: {
data: {
userId: string;
url: string;
action: "Login";
details: string;
};
}): Promise<unknown>;
};
};
export type LegacyUserDefaultTenantWriterClient = {
user: {
update(args: {
where: { id: string };
data: { defaultTenantId: string };
}): Promise<unknown>;
};
};
const selectLegacyUserWithoutPassword = {
id: true,
email: true,
firstName: true,
lastName: true,
avatar: true,
phone: true,
admin: true,
defaultTenantId: true,
createdAt: true,
locale: true,
lightOrDarkMode: true,
} as const;
export async function findLegacyAuthUserById(
userId: string,
client: LegacyAuthUserReaderClient = getDbClient(),
): Promise<LegacyAuthUser | null> {
const user = await client.user.findUnique({
where: { id: userId },
select: { id: true, email: true },
});
if (!user) {
return null;
}
return {
id: user.id,
email: user.email,
};
}
export async function findLegacyLoginUserByEmail(
email: string,
client: LegacyLoginUserReaderClient = getDbClient(),
): Promise<LegacyLoginUser | null> {
const user = await client.user.findUnique({
where: { email },
select: { id: true, email: true, passwordHash: true },
});
if (!user) {
return null;
}
return {
id: user.id,
email: user.email,
passwordHash: user.passwordHash,
};
}
export async function findLegacyUserWithoutPasswordById(
userId?: string,
client: LegacyUserWithoutPasswordReaderClient = getDbClient() as unknown as LegacyUserWithoutPasswordReaderClient,
): Promise<LegacyUserWithoutPassword | null> {
if (!userId) {
return null;
}
try {
return await client.user.findUnique({
where: { id: userId },
select: selectLegacyUserWithoutPassword,
});
} catch {
return null;
}
}
export async function recordLegacyLogin(
userId: string,
client: LegacyLoginLogWriterClient = getDbClient(),
): Promise<void> {
await client.log.create({
data: {
userId,
url: "",
action: "Login",
details: "",
},
});
}
export async function updateLegacyUserDefaultTenantId(
data: { defaultTenantId: string },
userId: string,
client: LegacyUserDefaultTenantWriterClient = getDbClient(),
): Promise<unknown | null> {
if (!userId) {
return null;
}
return await client.user.update({
where: { id: userId },
data,
});
}
@@ -0,0 +1,36 @@
import { describe, expect, it, vi } from "vitest";
import { findLegacyWidgetById, type LegacyWidgetReaderClient } from "./widgets.server.js";
describe("findLegacyWidgetById", () => {
it("fetches the legacy widget record by id and tenant", async () => {
const widget = {
id: "widget_123",
createdAt: new Date("2026-01-01T00:00:00.000Z"),
updatedAt: new Date("2026-01-02T00:00:00.000Z"),
tenantId: "tenant_123",
name: "Support",
appearance: "{}",
metadata: "{}",
};
const findFirst = vi.fn().mockResolvedValue(widget);
const client: LegacyWidgetReaderClient = {
widget: { findFirst },
};
await expect(findLegacyWidgetById({ widgetId: "widget_123", tenantId: "tenant_123" }, client)).resolves.toBe(widget);
expect(findFirst).toHaveBeenCalledWith({
where: { id: "widget_123", tenantId: "tenant_123" },
});
});
it("returns null when the widget does not exist", async () => {
const client: LegacyWidgetReaderClient = {
widget: {
findFirst: vi.fn().mockResolvedValue(null),
},
};
await expect(findLegacyWidgetById({ widgetId: "missing", tenantId: "tenant_123" }, client)).resolves.toBeNull();
});
});
@@ -0,0 +1,33 @@
import { getDbClient } from "./client.server.js";
export type LegacyWidget = {
id: string;
createdAt: Date;
updatedAt: Date;
tenantId: string | null;
name: string;
appearance: string;
metadata: string;
};
export type LegacyWidgetReaderClient = {
widget: {
findFirst(args: {
where: { id: string; tenantId: string };
}): Promise<LegacyWidget | null>;
};
};
export type LegacyWidgetLookup = {
widgetId: string;
tenantId: string;
};
export async function findLegacyWidgetById(
{ widgetId, tenantId }: LegacyWidgetLookup,
client: LegacyWidgetReaderClient = getDbClient(),
): Promise<LegacyWidget | null> {
return client.widget.findFirst({
where: { id: widgetId, tenantId },
});
}
@@ -0,0 +1,234 @@
import { describe, expect, it, vi } from "vitest";
import {
acceptWorkspaceInvite,
createWorkspaceInvite,
getWorkspaceInviteByToken,
hashWorkspaceInviteToken,
listWorkspaceInvites,
revokeWorkspaceInvite,
serializeWorkspaceInvite,
WorkspaceInviteError,
WORKSPACE_INVITE_TTL_MS,
type WorkspaceInviteClient,
} from "./workspace-invites.server.js";
const now = new Date("2026-05-08T15:30:00.000Z");
const future = new Date("2026-05-09T15:30:00.000Z");
const past = new Date("2026-05-07T15:30:00.000Z");
const token = "workspace-invite-token-secret";
function invite(overrides: Partial<Omit<ReturnType<typeof baseInvite>, "acceptedAt" | "revokedAt"> & { acceptedAt: Date | null; revokedAt: Date | null }> = {}) {
return { ...baseInvite(), ...overrides };
}
function baseInvite() {
return {
id: "invite_1",
tenantId: "tenant_1",
email: "member@example.com",
firstName: "Member",
lastName: "One",
type: 2,
pending: true,
status: "pending",
tokenHash: hashWorkspaceInviteToken(token),
tokenPrefix: token.slice(0, 12),
expiresAt: future,
acceptedAt: null,
revokedAt: null,
createdUserId: null,
fromUserId: "admin_1",
acceptedByUserId: null,
revokedByUserId: null,
};
}
function createInviteClient(rows: ReturnType<typeof invite>[] = []): WorkspaceInviteClient {
return {
tenantUserInvitation: {
findFirst: vi.fn().mockResolvedValue(null),
findMany: vi.fn().mockResolvedValue(rows),
create: vi.fn().mockImplementation(({ data }) => Promise.resolve(invite(data))),
update: vi.fn().mockImplementation(({ data }) => Promise.resolve(invite(data))),
},
} as unknown as WorkspaceInviteClient;
}
describe("workspace invite lifecycle", () => {
it("rejects duplicate active invites for the same tenant and normalized email", async () => {
const client = createInviteClient();
vi.mocked(client.tenantUserInvitation.findFirst).mockResolvedValue(invite());
await expect(
createWorkspaceInvite(
{
tenantId: "tenant_1",
email: " Member@Example.COM ",
firstName: "Member",
lastName: "One",
type: 2,
now,
token,
},
client,
),
).rejects.toMatchObject({ code: "duplicate_active_invite" });
expect(client.tenantUserInvitation.findFirst).toHaveBeenCalledWith({
where: {
tenantId: "tenant_1",
email: "member@example.com",
status: "pending",
OR: [{ expiresAt: null }, { expiresAt: { gt: now } }],
},
orderBy: { id: "asc" },
});
expect(client.tenantUserInvitation.create).not.toHaveBeenCalled();
});
it("stores only token hash and prefix while returning plaintext token from create", async () => {
const client = createInviteClient();
const result = await createWorkspaceInvite(
{
tenantId: "tenant_1",
email: "Member@Example.COM",
firstName: "Member",
lastName: "One",
type: 2,
fromUserId: "admin_1",
expiresAt: future,
token,
now,
},
client,
);
expect(result.token).toBe(token);
expect(result).not.toHaveProperty("tokenHash");
expect(client.tenantUserInvitation.create).toHaveBeenCalledWith({
data: expect.objectContaining({
email: "member@example.com",
status: "pending",
pending: true,
tokenHash: hashWorkspaceInviteToken(token),
tokenPrefix: token.slice(0, 12),
}),
});
expect(JSON.stringify(vi.mocked(client.tenantUserInvitation.create).mock.calls[0])).not.toContain(`\"token\":\"${token}\"`);
});
it("defaults the invite expiry to 48h when the caller passes no expiresAt (DoD 'Einladung 48h')", async () => {
const client = createInviteClient();
await createWorkspaceInvite(
{ tenantId: "tenant_1", email: "member@example.com", firstName: "Member", lastName: "One", type: 2, fromUserId: "admin_1", token, now },
client,
);
const createArg = vi.mocked(client.tenantUserInvitation.create).mock.calls[0][0] as { data: { expiresAt: Date } };
expect(createArg.data.expiresAt.getTime()).toBe(now.getTime() + WORKSPACE_INVITE_TTL_MS);
expect(WORKSPACE_INVITE_TTL_MS).toBe(48 * 60 * 60 * 1000);
});
it("lists invites with tenant-scoped filters and redacted DTOs", async () => {
const client = createInviteClient([invite({ tenantId: "tenant_1" })]);
await expect(listWorkspaceInvites({ tenantId: "tenant_1", status: "pending", email: " MEMBER@example.com ", now }, client)).resolves.toEqual([
expect.objectContaining({ id: "invite_1", tenantId: "tenant_1", status: "pending", pending: true }),
]);
expect(client.tenantUserInvitation.findMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", status: "pending", email: "member@example.com" },
orderBy: [{ status: "asc" }, { expiresAt: "asc" }, { id: "asc" }],
});
});
it("looks up invites by token without accepting raw invite ids", async () => {
const client = createInviteClient([
invite({ id: "wrong_token", tokenHash: hashWorkspaceInviteToken("different-token") }),
invite({ id: "invite_1", tokenHash: hashWorkspaceInviteToken(token) }),
]);
await expect(getWorkspaceInviteByToken({ token, now }, client)).resolves.toEqual(
expect.objectContaining({ id: "invite_1", tenantId: "tenant_1", pending: true })
);
await expect(getWorkspaceInviteByToken({ token: "invite_1", now }, client)).resolves.toBeNull();
expect(client.tenantUserInvitation.findMany).toHaveBeenCalledWith({
where: { tokenPrefix: token.slice(0, 12) },
orderBy: [{ status: "asc" }, { expiresAt: "asc" }, { id: "asc" }],
});
});
it("rejects expired invite acceptance without updating", async () => {
const client = createInviteClient();
vi.mocked(client.tenantUserInvitation.findFirst).mockResolvedValue(invite({ expiresAt: past }));
await expect(acceptWorkspaceInvite({ tenantId: "tenant_1", inviteId: "invite_1", token, acceptedByUserId: "user_1", now }, client)).rejects.toMatchObject({
code: "invite_expired",
});
expect(client.tenantUserInvitation.update).not.toHaveBeenCalled();
});
it("rejects cross-tenant or stale-token acceptance as not found", async () => {
const client = createInviteClient();
vi.mocked(client.tenantUserInvitation.findFirst).mockResolvedValue(invite({ tokenHash: hashWorkspaceInviteToken("different-token") }));
await expect(acceptWorkspaceInvite({ tenantId: "tenant_2", inviteId: "invite_1", token, acceptedByUserId: "user_1", now }, client)).rejects.toMatchObject({
code: "invite_not_found",
});
expect(client.tenantUserInvitation.findFirst).toHaveBeenCalledWith({
where: { id: "invite_1", tenantId: "tenant_2", tokenPrefix: token.slice(0, 12) },
orderBy: { id: "asc" },
});
expect(client.tenantUserInvitation.update).not.toHaveBeenCalled();
});
it("transitions pending invite to accepted", async () => {
const client = createInviteClient();
vi.mocked(client.tenantUserInvitation.findFirst).mockResolvedValue(invite());
const result = await acceptWorkspaceInvite({ tenantId: "tenant_1", inviteId: "invite_1", token, acceptedByUserId: "user_1", now }, client);
expect(result).toEqual(expect.objectContaining({ status: "accepted", pending: false, acceptedAt: now, acceptedByUserId: "user_1" }));
expect(client.tenantUserInvitation.update).toHaveBeenCalledWith({
where: { id: "invite_1" },
data: { status: "accepted", pending: false, acceptedAt: now, acceptedByUserId: "user_1" },
});
});
it("transitions pending invite to revoked", async () => {
const client = createInviteClient();
vi.mocked(client.tenantUserInvitation.findFirst).mockResolvedValue(invite());
const result = await revokeWorkspaceInvite({ tenantId: "tenant_1", inviteId: "invite_1", revokedByUserId: "admin_1", now }, client);
expect(result).toEqual(expect.objectContaining({ status: "revoked", pending: false, revokedAt: now, revokedByUserId: "admin_1" }));
expect(client.tenantUserInvitation.update).toHaveBeenCalledWith({
where: { id: "invite_1" },
data: { status: "revoked", pending: false, revokedAt: now, revokedByUserId: "admin_1" },
});
});
it("rejects revoking finalized invites", async () => {
const client = createInviteClient();
vi.mocked(client.tenantUserInvitation.findFirst).mockResolvedValue(invite({ status: "accepted", pending: false, acceptedAt: now }));
await expect(revokeWorkspaceInvite({ tenantId: "tenant_1", inviteId: "invite_1", revokedByUserId: "admin_1", now }, client)).rejects.toMatchObject({
code: "invite_already_finalized",
});
expect(client.tenantUserInvitation.update).not.toHaveBeenCalled();
});
it("redacts token hash and plaintext token from serialized invite errors and DTOs", () => {
const dto = serializeWorkspaceInvite(invite(), now);
const error = new WorkspaceInviteError("invite_not_found");
expect(dto).not.toHaveProperty("tokenHash");
expect(dto).not.toHaveProperty("token");
expect(error.message).toBe("invite_not_found");
expect(error.message).not.toContain(token);
expect(error.message).not.toContain("member@example.com");
});
});
@@ -0,0 +1,323 @@
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
import { getDbClient } from "./client.server.js";
import type { Prisma, TenantUserInvitation } from "./prisma-browser.js";
export const WORKSPACE_INVITE_STATUS_PENDING = "pending" as const;
export const WORKSPACE_INVITE_STATUS_ACCEPTED = "accepted" as const;
export const WORKSPACE_INVITE_STATUS_REVOKED = "revoked" as const;
export const WORKSPACE_INVITE_STATUS_EXPIRED = "expired" as const;
export const WORKSPACE_INVITE_TOKEN_PREFIX_LENGTH = 12;
export const WORKSPACE_INVITE_TOKEN_BYTE_LENGTH = 32;
// R-P2b (User-Lifecycle) — Einladungen laufen nach 48h ab (DoD "Einladung 48h"). Single Source of
// Truth: createWorkspaceInvite setzt diesen Default, wenn der Aufrufer kein expiresAt uebergibt.
export const WORKSPACE_INVITE_TTL_MS = 48 * 60 * 60 * 1000;
export type WorkspaceInviteStatus =
| typeof WORKSPACE_INVITE_STATUS_PENDING
| typeof WORKSPACE_INVITE_STATUS_ACCEPTED
| typeof WORKSPACE_INVITE_STATUS_REVOKED
| typeof WORKSPACE_INVITE_STATUS_EXPIRED;
export type WorkspaceInviteErrorCode =
| "duplicate_active_invite"
| "invite_not_found"
| "invite_expired"
| "invite_already_finalized";
export class WorkspaceInviteError extends Error {
readonly code: WorkspaceInviteErrorCode;
constructor(code: WorkspaceInviteErrorCode) {
super(code);
this.name = "WorkspaceInviteError";
this.code = code;
}
}
export type WorkspaceInviteDto = {
id: string;
tenantId: string;
email: string;
firstName: string;
lastName: string;
type: number;
status: WorkspaceInviteStatus;
pending: boolean;
tokenPrefix: string | null;
createdUserId: string | null;
fromUserId: string | null;
acceptedByUserId: string | null;
revokedByUserId: string | null;
expiresAt: Date | null;
acceptedAt: Date | null;
revokedAt: Date | null;
};
export type WorkspaceInviteCreateResult = WorkspaceInviteDto & {
token: string;
};
export type WorkspaceInviteCreateInput = {
tenantId: string;
email: string;
firstName: string;
lastName: string;
type: number;
fromUserId?: string | null;
createdUserId?: string | null;
expiresAt?: Date | null;
token?: string;
now?: Date;
};
export type WorkspaceInviteListInput = {
tenantId: string;
status?: WorkspaceInviteStatus;
email?: string;
now?: Date;
};
export type WorkspaceInviteAcceptInput = {
tenantId: string;
inviteId: string;
token: string;
acceptedByUserId: string;
now?: Date;
};
export type WorkspaceInviteLookupInput = {
token: string;
now?: Date;
};
export type WorkspaceInviteRevokeInput = {
tenantId: string;
inviteId: string;
revokedByUserId: string;
now?: Date;
};
export type WorkspaceInviteClient = {
tenantUserInvitation: {
findFirst(args: {
where: Prisma.TenantUserInvitationWhereInput;
orderBy?: Prisma.TenantUserInvitationOrderByWithRelationInput | Prisma.TenantUserInvitationOrderByWithRelationInput[];
}): Promise<TenantUserInvitation | null>;
findMany(args: {
where: Prisma.TenantUserInvitationWhereInput;
orderBy: Prisma.TenantUserInvitationOrderByWithRelationInput | Prisma.TenantUserInvitationOrderByWithRelationInput[];
}): Promise<TenantUserInvitation[]>;
create(args: { data: Prisma.TenantUserInvitationUncheckedCreateInput }): Promise<TenantUserInvitation>;
update(args: { where: { id: string }; data: Prisma.TenantUserInvitationUncheckedUpdateInput }): Promise<TenantUserInvitation>;
};
};
function normalizeEmail(email: string): string {
return email.trim().toLowerCase();
}
export function generateWorkspaceInviteToken(): string {
return randomBytes(WORKSPACE_INVITE_TOKEN_BYTE_LENGTH).toString("base64url");
}
export function hashWorkspaceInviteToken(token: string): string {
return createHash("sha256").update(token).digest("hex");
}
export function getWorkspaceInviteTokenPrefix(token: string): string {
return token.slice(0, WORKSPACE_INVITE_TOKEN_PREFIX_LENGTH);
}
function tokenHashesMatch(actualHash: string | null, expectedHash: string): boolean {
if (!actualHash) {
return false;
}
const actual = Buffer.from(actualHash, "hex");
const expected = Buffer.from(expectedHash, "hex");
return actual.length === expected.length && timingSafeEqual(actual, expected);
}
function resolveInviteStatus(invite: Pick<TenantUserInvitation, "status" | "expiresAt" | "acceptedAt" | "revokedAt">, now = new Date()): WorkspaceInviteStatus {
if (invite.status === WORKSPACE_INVITE_STATUS_ACCEPTED || invite.acceptedAt) {
return WORKSPACE_INVITE_STATUS_ACCEPTED;
}
if (invite.status === WORKSPACE_INVITE_STATUS_REVOKED || invite.revokedAt) {
return WORKSPACE_INVITE_STATUS_REVOKED;
}
if (invite.status === WORKSPACE_INVITE_STATUS_EXPIRED || (invite.expiresAt && invite.expiresAt <= now)) {
return WORKSPACE_INVITE_STATUS_EXPIRED;
}
return WORKSPACE_INVITE_STATUS_PENDING;
}
export function serializeWorkspaceInvite(invite: TenantUserInvitation, now = new Date()): WorkspaceInviteDto {
const status = resolveInviteStatus(invite, now);
return {
id: invite.id,
tenantId: invite.tenantId,
email: invite.email,
firstName: invite.firstName,
lastName: invite.lastName,
type: invite.type,
status,
pending: status === WORKSPACE_INVITE_STATUS_PENDING,
tokenPrefix: invite.tokenPrefix,
createdUserId: invite.createdUserId,
fromUserId: invite.fromUserId,
acceptedByUserId: invite.acceptedByUserId,
revokedByUserId: invite.revokedByUserId,
expiresAt: invite.expiresAt,
acceptedAt: invite.acceptedAt,
revokedAt: invite.revokedAt,
};
}
function getClient(client?: WorkspaceInviteClient): WorkspaceInviteClient {
return client ?? getDbClient();
}
export async function createWorkspaceInvite(input: WorkspaceInviteCreateInput, client?: WorkspaceInviteClient): Promise<WorkspaceInviteCreateResult> {
const db = getClient(client);
const now = input.now ?? new Date();
const email = normalizeEmail(input.email);
const existing = await db.tenantUserInvitation.findFirst({
where: {
tenantId: input.tenantId,
email,
status: WORKSPACE_INVITE_STATUS_PENDING,
OR: [{ expiresAt: null }, { expiresAt: { gt: now } }],
},
orderBy: { id: "asc" },
});
if (existing) {
throw new WorkspaceInviteError("duplicate_active_invite");
}
const token = input.token ?? generateWorkspaceInviteToken();
const tokenHash = hashWorkspaceInviteToken(token);
const invite = await db.tenantUserInvitation.create({
data: {
tenantId: input.tenantId,
email,
firstName: input.firstName,
lastName: input.lastName,
type: input.type,
pending: true,
status: WORKSPACE_INVITE_STATUS_PENDING,
tokenHash,
tokenPrefix: getWorkspaceInviteTokenPrefix(token),
// DoD "Einladung 48h": Default-Ablauf, wenn der Aufrufer nichts vorgibt (kein null mehr).
expiresAt: input.expiresAt ?? new Date(now.getTime() + WORKSPACE_INVITE_TTL_MS),
createdUserId: input.createdUserId ?? null,
fromUserId: input.fromUserId ?? null,
},
});
return { ...serializeWorkspaceInvite(invite, now), token };
}
export async function listWorkspaceInvites(input: WorkspaceInviteListInput, client?: WorkspaceInviteClient): Promise<WorkspaceInviteDto[]> {
const db = getClient(client);
const invites = await db.tenantUserInvitation.findMany({
where: {
tenantId: input.tenantId,
...(input.status ? { status: input.status } : {}),
...(input.email ? { email: normalizeEmail(input.email) } : {}),
},
orderBy: [{ status: "asc" }, { expiresAt: "asc" }, { id: "asc" }],
});
return invites.map((invite) => serializeWorkspaceInvite(invite, input.now));
}
export async function getWorkspaceInviteByToken(input: WorkspaceInviteLookupInput, client?: WorkspaceInviteClient): Promise<WorkspaceInviteDto | null> {
const db = getClient(client);
const tokenHash = hashWorkspaceInviteToken(input.token);
const candidates = await db.tenantUserInvitation.findMany({
where: {
tokenPrefix: getWorkspaceInviteTokenPrefix(input.token),
},
orderBy: [{ status: "asc" }, { expiresAt: "asc" }, { id: "asc" }],
});
const invite = candidates.find((candidate) => tokenHashesMatch(candidate.tokenHash, tokenHash));
return invite ? serializeWorkspaceInvite(invite, input.now) : null;
}
export async function acceptWorkspaceInvite(input: WorkspaceInviteAcceptInput, client?: WorkspaceInviteClient): Promise<WorkspaceInviteDto> {
const db = getClient(client);
const now = input.now ?? new Date();
const tokenHash = hashWorkspaceInviteToken(input.token);
const candidate = await db.tenantUserInvitation.findFirst({
where: {
id: input.inviteId,
tenantId: input.tenantId,
tokenPrefix: getWorkspaceInviteTokenPrefix(input.token),
},
orderBy: { id: "asc" },
});
if (!candidate || !tokenHashesMatch(candidate.tokenHash, tokenHash)) {
throw new WorkspaceInviteError("invite_not_found");
}
const status = resolveInviteStatus(candidate, now);
if (status === WORKSPACE_INVITE_STATUS_EXPIRED) {
throw new WorkspaceInviteError("invite_expired");
}
if (status !== WORKSPACE_INVITE_STATUS_PENDING) {
throw new WorkspaceInviteError("invite_already_finalized");
}
const invite = await db.tenantUserInvitation.update({
where: { id: candidate.id },
data: {
status: WORKSPACE_INVITE_STATUS_ACCEPTED,
pending: false,
acceptedAt: now,
acceptedByUserId: input.acceptedByUserId,
},
});
return serializeWorkspaceInvite(invite, now);
}
export async function revokeWorkspaceInvite(input: WorkspaceInviteRevokeInput, client?: WorkspaceInviteClient): Promise<WorkspaceInviteDto> {
const db = getClient(client);
const now = input.now ?? new Date();
const candidate = await db.tenantUserInvitation.findFirst({
where: {
id: input.inviteId,
tenantId: input.tenantId,
},
orderBy: { id: "asc" },
});
if (!candidate) {
throw new WorkspaceInviteError("invite_not_found");
}
if (resolveInviteStatus(candidate, now) !== WORKSPACE_INVITE_STATUS_PENDING) {
throw new WorkspaceInviteError("invite_already_finalized");
}
const invite = await db.tenantUserInvitation.update({
where: { id: candidate.id },
data: {
status: WORKSPACE_INVITE_STATUS_REVOKED,
pending: false,
revokedAt: now,
revokedByUserId: input.revokedByUserId,
},
});
return serializeWorkspaceInvite(invite, now);
}