Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
@@ -1,5 +1,5 @@
|
||||
import { getDbClient } from "./client.server.js";
|
||||
import type { Tenant, TenantInboundAddress, TenantIpAddress, TenantSettingsRow, TenantType, TenantUser } from "./prisma-browser.js";
|
||||
import type { Tenant, TenantInboundAddress, TenantIpAddress, TenantType, TenantUser } from "./prisma-browser.js";
|
||||
import type { TenantSubscriptionWithDetails } from "./subscriptions.server.js";
|
||||
|
||||
const ACTIVE_TENANT_USER_STATUS = 2;
|
||||
@@ -39,7 +39,6 @@ export type LegacyTenantWithDetails = Tenant & {
|
||||
user: LegacyTenantUserSummary;
|
||||
})[];
|
||||
subscription: TenantSubscriptionWithDetails | null;
|
||||
tenantSettingsRow: (TenantSettingsRow & { row: unknown }) | null;
|
||||
types: TenantType[];
|
||||
};
|
||||
|
||||
@@ -134,56 +133,6 @@ const includeAuthBoundaryTenantMembership = {
|
||||
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: {
|
||||
@@ -200,7 +149,6 @@ export const legacyTenantDetailsInclude = {
|
||||
},
|
||||
},
|
||||
},
|
||||
tenantSettingsRow: { include: { row: { include: includeLegacyRowDetails } } },
|
||||
types: true,
|
||||
} as const;
|
||||
|
||||
|
||||
@@ -401,7 +401,7 @@ describe("analytics write helpers", () => {
|
||||
utm_medium: "email",
|
||||
utm_campaign: "launch",
|
||||
utm_content: "button",
|
||||
utm_term: "toolctrl",
|
||||
utm_term: "hivegrid",
|
||||
},
|
||||
region: { country: "US", city: "Austin" },
|
||||
userId: "user_2",
|
||||
@@ -426,7 +426,7 @@ describe("analytics write helpers", () => {
|
||||
medium: "email",
|
||||
campaign: "launch",
|
||||
content: "button",
|
||||
term: "toolctrl",
|
||||
term: "hivegrid",
|
||||
country: "US",
|
||||
city: "Austin",
|
||||
fromUrl: "/from",
|
||||
|
||||
@@ -61,15 +61,6 @@ function createApiKeyLogClient(): LegacyApiKeyLogWriterClient & LegacyApiKeyRead
|
||||
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([]),
|
||||
@@ -157,8 +148,8 @@ describe("legacy API key log writes", () => {
|
||||
alias: "Production",
|
||||
expires: null,
|
||||
tenantId: "tenant_1",
|
||||
createdByUserId: "user_1",
|
||||
active: true,
|
||||
entities: [],
|
||||
tenant: { id: "tenant_1", name: "Acme", slug: "acme", deactivatedReason: null },
|
||||
_count: { apiKeyLogs: 0 },
|
||||
};
|
||||
@@ -328,7 +319,6 @@ describe("legacy API key log writes", () => {
|
||||
active: false,
|
||||
key,
|
||||
},
|
||||
[{ entityId: "entity_1", create: true, read: true, update: false, delete: false }],
|
||||
client,
|
||||
"hash-secret",
|
||||
),
|
||||
@@ -349,52 +339,6 @@ describe("legacy API key log writes", () => {
|
||||
}),
|
||||
});
|
||||
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", () => {
|
||||
@@ -531,8 +475,9 @@ describe("legacy API key log writes", () => {
|
||||
alias: "Production",
|
||||
expires: null,
|
||||
tenantId: "tenant_1",
|
||||
createdByUserId: "user_1",
|
||||
active: true,
|
||||
entities: [],
|
||||
scopes: ["public_api:read"],
|
||||
tenant: { id: "tenant_1", name: "Acme", slug: "acme", deactivatedReason: null },
|
||||
};
|
||||
vi.mocked(client.apiKey.findFirst).mockImplementation(({ where }) => {
|
||||
@@ -553,7 +498,7 @@ describe("legacy API key log writes", () => {
|
||||
}));
|
||||
});
|
||||
|
||||
it("updates API keys and replaces entity permissions", async () => {
|
||||
it("updates API keys and reloads the persisted record", 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);
|
||||
@@ -567,7 +512,6 @@ describe("legacy API key log writes", () => {
|
||||
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" });
|
||||
@@ -581,22 +525,6 @@ describe("legacy API key log writes", () => {
|
||||
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" },
|
||||
});
|
||||
@@ -628,8 +556,9 @@ describe("legacy API key log writes", () => {
|
||||
alias: "Production",
|
||||
expires: null,
|
||||
tenantId: "tenant_1",
|
||||
createdByUserId: "user_1",
|
||||
active: true,
|
||||
entities: [],
|
||||
scopes: ["public_api:read"],
|
||||
tenant: { id: "tenant_1", name: "Acme", slug: "acme", deactivatedReason: null },
|
||||
};
|
||||
vi.mocked(client.apiKey.findFirst).mockResolvedValue(apiKey);
|
||||
@@ -643,8 +572,9 @@ describe("legacy API key log writes", () => {
|
||||
alias: true,
|
||||
expires: true,
|
||||
tenantId: true,
|
||||
createdByUserId: true,
|
||||
active: true,
|
||||
entities: { select: { create: true, read: true, update: true, delete: true, entityId: true } },
|
||||
scopes: true,
|
||||
tenant: { select: { id: true, name: true, slug: true, deactivatedReason: true } },
|
||||
},
|
||||
});
|
||||
@@ -675,8 +605,9 @@ describe("legacy API key log writes", () => {
|
||||
alias: "Production",
|
||||
expires: null,
|
||||
tenantId: "tenant_1",
|
||||
createdByUserId: "user_1",
|
||||
active: true,
|
||||
entities: [],
|
||||
scopes: ["public_api:read"],
|
||||
tenant: { id: "tenant_1", name: "Acme", slug: "acme", deactivatedReason: null },
|
||||
};
|
||||
vi.mocked(client.apiKey.findFirst).mockResolvedValueOnce(null).mockResolvedValueOnce(apiKey);
|
||||
@@ -719,8 +650,9 @@ describe("legacy API key log writes", () => {
|
||||
alias: "Production",
|
||||
expires: null,
|
||||
tenantId: "tenant_1",
|
||||
createdByUserId: "user_1",
|
||||
active: true,
|
||||
entities: [],
|
||||
scopes: ["public_api:read"],
|
||||
tenant: { id: "tenant_1", name: "Acme", slug: "acme", deactivatedReason: null },
|
||||
};
|
||||
vi.mocked(client.apiKey.findFirst).mockRejectedValueOnce(new Error("hash index unavailable")).mockResolvedValueOnce(apiKey);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createHmac, randomUUID } from "node:crypto";
|
||||
|
||||
import { getDbClient } from "./client.server.js";
|
||||
import type { ApiKey, ApiKeyEntity, ApiKeyLog, Prisma, Tenant } from "./prisma-browser.js";
|
||||
import type { ApiKey, ApiKeyLog, Prisma, Tenant } from "./prisma-browser.js";
|
||||
|
||||
export type LegacyApiKeyUserSummary = {
|
||||
id: string;
|
||||
@@ -15,7 +15,6 @@ export type LegacyApiKeyUserSummary = {
|
||||
|
||||
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 };
|
||||
};
|
||||
@@ -42,14 +41,9 @@ export type LegacyApiKeySimple = {
|
||||
alias: string;
|
||||
expires: Date | null;
|
||||
tenantId: string;
|
||||
createdByUserId: string;
|
||||
active: boolean;
|
||||
entities: {
|
||||
create: boolean;
|
||||
read: boolean;
|
||||
update: boolean;
|
||||
delete: boolean;
|
||||
entityId: string;
|
||||
}[];
|
||||
scopes: unknown;
|
||||
tenant: { id: string; name: string; slug: string; deactivatedReason: string | null };
|
||||
};
|
||||
|
||||
@@ -83,6 +77,7 @@ export type LegacyApiKeyCreateData = {
|
||||
expires: Date | null;
|
||||
active: boolean;
|
||||
key?: string;
|
||||
scopes?: Prisma.InputJsonValue;
|
||||
};
|
||||
|
||||
export type LegacyApiKeyCreateStoredData = LegacyApiKeyCreateData & LegacyApiKeyHashMetadata & { key: string };
|
||||
@@ -150,14 +145,7 @@ export type LegacyApiKeyUpdateData = {
|
||||
alias: string;
|
||||
expires: Date | null;
|
||||
active: boolean;
|
||||
};
|
||||
|
||||
export type LegacyApiKeyEntityPermissionData = {
|
||||
entityId: string;
|
||||
create: boolean;
|
||||
read: boolean;
|
||||
update: boolean;
|
||||
delete: boolean;
|
||||
scopes?: Prisma.InputJsonValue;
|
||||
};
|
||||
|
||||
export type LegacyApiKeyReaderClient = {
|
||||
@@ -228,21 +216,6 @@ export type LegacyApiKeyLogWriterClient = {
|
||||
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;
|
||||
@@ -268,36 +241,6 @@ export type LegacyApiKeyLogWriterClient = {
|
||||
};
|
||||
};
|
||||
|
||||
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,
|
||||
@@ -309,7 +252,7 @@ const selectLegacyApiKeyUserSummary = {
|
||||
} 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_SECRET = "hivegrid-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;
|
||||
@@ -398,11 +341,6 @@ export async function backfillLegacyApiKeyHashes({
|
||||
|
||||
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,
|
||||
},
|
||||
@@ -418,8 +356,9 @@ const legacyApiKeySimpleSelect = {
|
||||
alias: true,
|
||||
expires: true,
|
||||
tenantId: true,
|
||||
createdByUserId: true,
|
||||
active: true,
|
||||
entities: { select: { create: true, read: true, update: true, delete: true, entityId: true } },
|
||||
scopes: true,
|
||||
tenant: { select: { id: true, name: true, slug: true, deactivatedReason: true } },
|
||||
} as const;
|
||||
|
||||
@@ -593,12 +532,9 @@ export async function findFirstLegacyActiveApiKey(
|
||||
|
||||
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({
|
||||
@@ -610,17 +546,6 @@ export async function createLegacyApiKey(
|
||||
},
|
||||
});
|
||||
|
||||
await Promise.all(
|
||||
entities.map(async (entity) => {
|
||||
return client.apiKeyEntity.create({
|
||||
data: {
|
||||
apiKeyId: apiKey.id,
|
||||
...entity,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
...apiKey,
|
||||
key,
|
||||
@@ -630,11 +555,8 @@ export async function createLegacyApiKey(
|
||||
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,
|
||||
@@ -643,24 +565,6 @@ export async function updateLegacyApiKey(
|
||||
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`);
|
||||
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("./client.server.js", () => ({ getDbClient: vi.fn() }));
|
||||
|
||||
import { getDbClient } from "./client.server.js";
|
||||
import {
|
||||
AUDIT_VIEWER_DEFAULT_PAGE_SIZE,
|
||||
AUDIT_VIEWER_MAX_PAGE_SIZE,
|
||||
listAuditEvents,
|
||||
} from "./audit-events-query.server.js";
|
||||
|
||||
type AuditQueryClient = {
|
||||
auditEvent: {
|
||||
findMany: ReturnType<typeof vi.fn>;
|
||||
count: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
};
|
||||
|
||||
function createClient(rows: Array<{ id: string }> = [], total = rows.length): AuditQueryClient {
|
||||
return {
|
||||
auditEvent: {
|
||||
findMany: vi.fn().mockResolvedValue(rows),
|
||||
count: vi.fn().mockResolvedValue(total),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function installClient(client: AuditQueryClient): void {
|
||||
vi.mocked(getDbClient).mockReturnValue(client as never);
|
||||
}
|
||||
|
||||
describe("listAuditEvents", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("applies newest-first ordering with default paging when no params are given", async () => {
|
||||
const rows = [{ id: "audit_1" }, { id: "audit_2" }];
|
||||
const client = createClient(rows, 42);
|
||||
installClient(client);
|
||||
|
||||
const result = await listAuditEvents();
|
||||
|
||||
expect(result).toEqual({ rows, total: 42, take: AUDIT_VIEWER_DEFAULT_PAGE_SIZE, skip: 0 });
|
||||
expect(client.auditEvent.findMany).toHaveBeenCalledWith({
|
||||
where: {},
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: AUDIT_VIEWER_DEFAULT_PAGE_SIZE,
|
||||
skip: 0,
|
||||
});
|
||||
// findMany + count must share the exact same filter so pagination metadata is consistent.
|
||||
expect(client.auditEvent.count).toHaveBeenCalledWith({ where: {} });
|
||||
});
|
||||
|
||||
it("forwards the caller filter to both the page query and the total count", async () => {
|
||||
const client = createClient([{ id: "audit_3" }], 1);
|
||||
installClient(client);
|
||||
const where = { tenantId: "tenant_1", outcome: "denied" } as never;
|
||||
|
||||
await listAuditEvents({ where, take: 10, skip: 30 });
|
||||
|
||||
expect(client.auditEvent.findMany).toHaveBeenCalledWith({ where, orderBy: { createdAt: "desc" }, take: 10, skip: 30 });
|
||||
expect(client.auditEvent.count).toHaveBeenCalledWith({ where });
|
||||
});
|
||||
|
||||
it("clamps an oversized page size down to the viewer maximum", async () => {
|
||||
const client = createClient();
|
||||
installClient(client);
|
||||
|
||||
const result = await listAuditEvents({ take: 5_000 });
|
||||
|
||||
expect(result.take).toBe(AUDIT_VIEWER_MAX_PAGE_SIZE);
|
||||
expect(client.auditEvent.findMany).toHaveBeenCalledWith(expect.objectContaining({ take: AUDIT_VIEWER_MAX_PAGE_SIZE }));
|
||||
});
|
||||
|
||||
it.each([
|
||||
["zero", 0],
|
||||
["negative", -25],
|
||||
["non-finite", Number.NaN],
|
||||
])("falls back to the default page size for a %s take", async (_label, take) => {
|
||||
const client = createClient();
|
||||
installClient(client);
|
||||
|
||||
const result = await listAuditEvents({ take });
|
||||
|
||||
expect(result.take).toBe(AUDIT_VIEWER_DEFAULT_PAGE_SIZE);
|
||||
});
|
||||
|
||||
it("truncates fractional take and skip values to whole rows", async () => {
|
||||
const client = createClient();
|
||||
installClient(client);
|
||||
|
||||
const result = await listAuditEvents({ take: 10.9, skip: 20.7 });
|
||||
|
||||
expect(result.take).toBe(10);
|
||||
expect(result.skip).toBe(20);
|
||||
expect(client.auditEvent.findMany).toHaveBeenCalledWith(expect.objectContaining({ take: 10, skip: 20 }));
|
||||
});
|
||||
|
||||
it.each([
|
||||
["negative", -3],
|
||||
["zero", 0],
|
||||
["non-finite", Number.POSITIVE_INFINITY],
|
||||
])("normalizes a %s skip to the first page", async (_label, skip) => {
|
||||
const client = createClient();
|
||||
installClient(client);
|
||||
|
||||
const result = await listAuditEvents({ skip });
|
||||
|
||||
expect(result.skip).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import { getDbClient } from "./client.server.js";
|
||||
import type { AuditEvent, Prisma } from "../generated/prisma/client/client.js";
|
||||
|
||||
/**
|
||||
* AK-P3 — read-path for the Audit-Viewer (`/admin/audit`).
|
||||
*
|
||||
* The write-path (`createAuditEvent`) and the export-path
|
||||
* (`audit-export.helpers.server`) already exist; this module adds the missing
|
||||
* paginated list query the viewer needs. It is a thin wrapper over Prisma so
|
||||
* the route stays free of direct `findMany` calls and the filters are applied
|
||||
* against the existing `(tenantId|action|outcome, createdAt)` indexes.
|
||||
*/
|
||||
|
||||
export type AuditEventListParams = {
|
||||
where?: Prisma.AuditEventWhereInput;
|
||||
take?: number;
|
||||
skip?: number;
|
||||
};
|
||||
|
||||
export type AuditEventListResult = {
|
||||
rows: AuditEvent[];
|
||||
total: number;
|
||||
take: number;
|
||||
skip: number;
|
||||
};
|
||||
|
||||
export const AUDIT_VIEWER_DEFAULT_PAGE_SIZE = 25;
|
||||
export const AUDIT_VIEWER_MAX_PAGE_SIZE = 100;
|
||||
|
||||
function clampPageSize(take: number | undefined): number {
|
||||
if (!Number.isFinite(take) || !take || take < 1) return AUDIT_VIEWER_DEFAULT_PAGE_SIZE;
|
||||
return Math.min(Math.trunc(take), AUDIT_VIEWER_MAX_PAGE_SIZE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists audit events newest-first with server-side filters + pagination.
|
||||
* Returns the page rows plus the total count for the same filter so the route
|
||||
* can build pagination metadata.
|
||||
*/
|
||||
export async function listAuditEvents(params: AuditEventListParams = {}): Promise<AuditEventListResult> {
|
||||
const db = getDbClient();
|
||||
const where = params.where ?? {};
|
||||
const take = clampPageSize(params.take);
|
||||
const skip = Number.isFinite(params.skip) && params.skip && params.skip > 0 ? Math.trunc(params.skip) : 0;
|
||||
|
||||
const [rows, total] = await Promise.all([
|
||||
db.auditEvent.findMany({ where, orderBy: { createdAt: "desc" }, take, skip }),
|
||||
db.auditEvent.count({ where }),
|
||||
]);
|
||||
|
||||
return { rows, total, take, skip };
|
||||
}
|
||||
@@ -128,10 +128,43 @@ describe("audit event persistence", () => {
|
||||
dataSensitivity: "internal",
|
||||
regulatoryScope: [],
|
||||
metadata,
|
||||
beforeDiff: null,
|
||||
afterDiff: null,
|
||||
summaryText: null,
|
||||
});
|
||||
expect(input).toEqual({ action: "thing.changed", actorType: " ", metadata });
|
||||
});
|
||||
|
||||
it("persists sanitized before/after diffs and a trimmed summary text (AK-P3 DoD 2)", async () => {
|
||||
const client = createAuditEventClient();
|
||||
|
||||
await createAuditEvent(
|
||||
{
|
||||
tenantId: "tenant_1",
|
||||
actorType: "user",
|
||||
action: "kontakt.updated",
|
||||
beforeDiff: { name: "Alt GmbH", apiKey: "secret-1" },
|
||||
afterDiff: { name: "Neu GmbH", apiKey: "secret-2" },
|
||||
summaryText: " Firma umbenannt ",
|
||||
},
|
||||
client
|
||||
);
|
||||
|
||||
const call = (client.auditEvent.create as ReturnType<typeof vi.fn>).mock.calls[0]?.[0];
|
||||
expect(call?.data).toMatchObject({
|
||||
beforeDiff: { name: "Alt GmbH", apiKey: "[REDACTED]" },
|
||||
afterDiff: { name: "Neu GmbH", apiKey: "[REDACTED]" },
|
||||
summaryText: "Firma umbenannt",
|
||||
});
|
||||
});
|
||||
|
||||
it("defaults diff fields to null and blanks summaryText when empty", () => {
|
||||
const data = buildAuditEventCreateData({ action: "x", summaryText: " " });
|
||||
expect(data.beforeDiff).toBeNull();
|
||||
expect(data.afterDiff).toBeNull();
|
||||
expect(data.summaryText).toBeNull();
|
||||
});
|
||||
|
||||
it("captures compliance fields (ip, ua, regulatoryScope) and links hash chain", async () => {
|
||||
const client = createAuditEventClient({ previousHash: "deadbeef" });
|
||||
|
||||
@@ -249,6 +282,22 @@ describe("publishAuditEventViaOutbox", () => {
|
||||
expect(payload.eventHash).toBeUndefined();
|
||||
});
|
||||
|
||||
it("carries diff fields and summary through the outbox payload (AK-P3 DoD 2)", async () => {
|
||||
const tx = makeOutboxTx();
|
||||
await publishAuditEventViaOutbox(tx, {
|
||||
tenantId: "tenant_1",
|
||||
action: "kontakt.updated",
|
||||
beforeDiff: { status: "kontakt" },
|
||||
afterDiff: { status: "kunde" },
|
||||
summaryText: "Status geändert",
|
||||
});
|
||||
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.beforeDiff).toEqual({ status: "kontakt" });
|
||||
expect(payload.afterDiff).toEqual({ status: "kunde" });
|
||||
expect(payload.summaryText).toBe("Status geändert");
|
||||
});
|
||||
|
||||
it("defaults actorType to system and sanitizes metadata", async () => {
|
||||
const tx = makeOutboxTx();
|
||||
await publishAuditEventViaOutbox(tx, {
|
||||
|
||||
@@ -37,6 +37,18 @@ export type AuditEventInput = {
|
||||
dataSensitivity?: AuditDataSensitivity | string | null;
|
||||
regulatoryScope?: ReadonlyArray<AuditRegulatoryScope | string> | null;
|
||||
metadata?: Prisma.InputJsonValue | null;
|
||||
/**
|
||||
* AK-P3 DoD 2 — optional structured field-level change capture.
|
||||
* Both diffs run through the same metadata sanitizer (sensitive keys are
|
||||
* redacted at write time). They are intentionally NOT part of the
|
||||
* eventHash digest: the chain payload shape is frozen and re-hashing
|
||||
* existing rows would break `verifyAuditChain` for all pre-existing
|
||||
* history. Binding diffs into the chain is a coordinated R-P1b follow-up.
|
||||
*/
|
||||
beforeDiff?: Prisma.InputJsonValue | null;
|
||||
afterDiff?: Prisma.InputJsonValue | null;
|
||||
/** Optional persisted German summary line (viewers derive one when null). */
|
||||
summaryText?: string | null;
|
||||
};
|
||||
|
||||
export type AuditEventCreateData = {
|
||||
@@ -55,6 +67,9 @@ export type AuditEventCreateData = {
|
||||
dataSensitivity: string;
|
||||
regulatoryScope: string[];
|
||||
metadata: Prisma.InputJsonValue | null;
|
||||
beforeDiff: Prisma.InputJsonValue | null;
|
||||
afterDiff: Prisma.InputJsonValue | null;
|
||||
summaryText: string | null;
|
||||
};
|
||||
|
||||
export type AuditEventWriterClient = {
|
||||
@@ -90,6 +105,9 @@ export function buildAuditEventCreateData(input: AuditEventInput): AuditEventCre
|
||||
dataSensitivity: normalizeDataSensitivity(input.dataSensitivity),
|
||||
regulatoryScope: normalizeRegulatoryScope(input.regulatoryScope),
|
||||
metadata: sanitizeAuditMetadata(input.metadata),
|
||||
beforeDiff: sanitizeAuditMetadata(input.beforeDiff),
|
||||
afterDiff: sanitizeAuditMetadata(input.afterDiff),
|
||||
summaryText: normalizeOptionalString(input.summaryText),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -225,6 +243,9 @@ export async function publishAuditEventViaOutbox(
|
||||
dataSensitivity: data.dataSensitivity,
|
||||
regulatoryScope: data.regulatoryScope,
|
||||
metadata: data.metadata as Prisma.InputJsonValue,
|
||||
beforeDiff: data.beforeDiff as Prisma.InputJsonValue,
|
||||
afterDiff: data.afterDiff as Prisma.InputJsonValue,
|
||||
summaryText: data.summaryText,
|
||||
};
|
||||
await publishOutboxEvent(tx, {
|
||||
tenantId: data.tenantId,
|
||||
@@ -234,6 +255,8 @@ export async function publishAuditEventViaOutbox(
|
||||
}
|
||||
|
||||
function toHashPayload(data: AuditEventCreateData): AuditHashPayload {
|
||||
// beforeDiff/afterDiff/summaryText are deliberately absent: the chain
|
||||
// payload shape is frozen (see AuditEventInput docs).
|
||||
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
|
||||
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
normalizeBillingSubscriptionStatus,
|
||||
resolveTenantBillingState,
|
||||
resolveTenantEntitlements,
|
||||
type TenantBillingStateClient,
|
||||
} from "./billing-domain.server.js";
|
||||
|
||||
function createClient(subscription: unknown): TenantBillingStateClient {
|
||||
return {
|
||||
tenantSubscription: {
|
||||
findUnique: vi.fn(async () => subscription),
|
||||
},
|
||||
} as unknown as TenantBillingStateClient;
|
||||
}
|
||||
|
||||
describe("billing-domain.server", () => {
|
||||
it("returns a local trial state when no subscription exists", async () => {
|
||||
const state = await resolveTenantBillingState("tenant_1", {
|
||||
client: createClient(null),
|
||||
});
|
||||
|
||||
expect(state).toMatchObject({
|
||||
tenantId: "tenant_1",
|
||||
status: "trial",
|
||||
readOnly: false,
|
||||
planCode: null,
|
||||
seatQuantity: 1,
|
||||
entitlements: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves active plan code, seats, provider references, period, and entitlements", async () => {
|
||||
const currentPeriodStart = new Date("2026-07-01T00:00:00.000Z");
|
||||
const currentPeriodEnd = new Date("2026-08-01T00:00:00.000Z");
|
||||
const client = createClient({
|
||||
tenantId: "tenant_2",
|
||||
status: "active",
|
||||
planCode: "business",
|
||||
seatQuantity: 12,
|
||||
lagoCustomerId: "lago_customer_1",
|
||||
mollieCustomerId: "mollie_customer_1",
|
||||
lastInvoiceExternalId: "invoice_1",
|
||||
lastPaymentExternalId: "payment_1",
|
||||
products: [
|
||||
{
|
||||
id: "tenant_product_1",
|
||||
createdAt: new Date("2026-07-01T00:00:00.000Z"),
|
||||
currentPeriodStart,
|
||||
currentPeriodEnd,
|
||||
subscriptionProduct: {
|
||||
id: "product_business",
|
||||
code: "business",
|
||||
lagoPlanCode: "lago_business",
|
||||
title: "Business",
|
||||
features: [
|
||||
{
|
||||
code: "crm-basic",
|
||||
name: "crm-basic",
|
||||
order: 1,
|
||||
title: "CRM",
|
||||
type: 1,
|
||||
value: 0,
|
||||
quotaValue: null,
|
||||
accumulate: false,
|
||||
},
|
||||
{
|
||||
code: "users",
|
||||
name: "users",
|
||||
order: 2,
|
||||
title: "Users",
|
||||
type: 3,
|
||||
value: 12,
|
||||
quotaValue: { max: 12 },
|
||||
accumulate: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const state = await resolveTenantBillingState("tenant_2", {
|
||||
client,
|
||||
now: new Date("2026-07-04T00:00:00.000Z"),
|
||||
});
|
||||
|
||||
expect(state.status).toBe("active");
|
||||
expect(state.readOnly).toBe(false);
|
||||
expect(state.planCode).toBe("business");
|
||||
expect(state.seatQuantity).toBe(12);
|
||||
expect(state.lagoCustomerId).toBe("lago_customer_1");
|
||||
expect(state.mollieCustomerId).toBe("mollie_customer_1");
|
||||
expect(state.lastInvoiceExternalId).toBe("invoice_1");
|
||||
expect(state.lastPaymentExternalId).toBe("payment_1");
|
||||
expect(state.currentPeriodStart).toBe(currentPeriodStart);
|
||||
expect(state.currentPeriodEnd).toBe(currentPeriodEnd);
|
||||
expect(state.entitlements.map((item) => item.featureKey)).toEqual(["crm-basic", "users"]);
|
||||
expect(state.entitlements.find((item) => item.featureKey === "users")).toMatchObject({
|
||||
enabled: true,
|
||||
limitType: 3,
|
||||
limit: 12,
|
||||
quotaValue: { max: 12 },
|
||||
sourceProductId: "product_business",
|
||||
sourcePlanCode: "business",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses product-level plan and seat fallback when subscription-level values are not set", async () => {
|
||||
const state = await resolveTenantBillingState("tenant_3", {
|
||||
client: createClient({
|
||||
tenantId: "tenant_3",
|
||||
status: "active",
|
||||
products: [
|
||||
{
|
||||
id: "tenant_product_1",
|
||||
createdAt: new Date("2026-07-01T00:00:00.000Z"),
|
||||
planCode: "pro",
|
||||
seatQuantity: 5,
|
||||
subscriptionProduct: {
|
||||
id: "product_pro",
|
||||
code: "pro",
|
||||
lagoPlanCode: "lago_pro",
|
||||
title: "Pro",
|
||||
features: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
expect(state.planCode).toBe("pro");
|
||||
expect(state.seatQuantity).toBe(5);
|
||||
});
|
||||
|
||||
it("normalizes frozen and cancelled states before raw status", () => {
|
||||
expect(normalizeBillingSubscriptionStatus("active", { frozenAt: new Date("2026-07-01T00:00:00.000Z") })).toBe("frozen");
|
||||
expect(normalizeBillingSubscriptionStatus("active", { cancelledAt: new Date("2026-07-01T00:00:00.000Z") })).toBe("cancelled");
|
||||
expect(normalizeBillingSubscriptionStatus("legacy")).toBe("trial");
|
||||
});
|
||||
|
||||
it("returns entitlements keyed by feature code", async () => {
|
||||
const entitlements = await resolveTenantEntitlements("tenant_4", {
|
||||
client: createClient({
|
||||
tenantId: "tenant_4",
|
||||
status: "frozen",
|
||||
frozenAt: new Date("2026-07-01T00:00:00.000Z"),
|
||||
products: [
|
||||
{
|
||||
id: "tenant_product_1",
|
||||
createdAt: new Date("2026-07-01T00:00:00.000Z"),
|
||||
quantity: 3,
|
||||
customEntitlementPlanId: "starter",
|
||||
subscriptionProduct: {
|
||||
id: "product_starter",
|
||||
code: "starter",
|
||||
lagoPlanCode: "lago_starter",
|
||||
title: "Starter",
|
||||
features: [
|
||||
{
|
||||
code: null,
|
||||
name: "billing",
|
||||
order: 1,
|
||||
title: "Billing",
|
||||
type: 1,
|
||||
value: 0,
|
||||
quotaValue: null,
|
||||
accumulate: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
expect(entitlements).toMatchObject({
|
||||
tenantId: "tenant_4",
|
||||
planCode: "starter",
|
||||
seatQuantity: 3,
|
||||
features: {
|
||||
billing: {
|
||||
enabled: true,
|
||||
sourceProductId: "product_starter",
|
||||
sourcePlanCode: "starter",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,254 @@
|
||||
import { getDbClient } from "./client.server.js";
|
||||
|
||||
export const billingSubscriptionStatuses = ["trial", "active", "past_due", "cancelled", "frozen"] as const;
|
||||
|
||||
export type BillingSubscriptionStatus = (typeof billingSubscriptionStatuses)[number];
|
||||
|
||||
export type TenantBillingEntitlement = {
|
||||
featureKey: string;
|
||||
title: string;
|
||||
enabled: boolean;
|
||||
limitType: number;
|
||||
limit: number;
|
||||
quotaValue: unknown | null;
|
||||
accumulate: boolean;
|
||||
sourceProductId: string;
|
||||
sourcePlanCode: string | null;
|
||||
};
|
||||
|
||||
export type TenantBillingState = {
|
||||
tenantId: string;
|
||||
status: BillingSubscriptionStatus;
|
||||
readOnly: boolean;
|
||||
planCode: string | null;
|
||||
seatQuantity: number;
|
||||
lagoCustomerId: string | null;
|
||||
mollieCustomerId: string | null;
|
||||
lastInvoiceExternalId: string | null;
|
||||
lastPaymentExternalId: string | null;
|
||||
trialStartsAt: Date | null;
|
||||
trialEndsAt: Date | null;
|
||||
pastDueSince: Date | null;
|
||||
frozenAt: Date | null;
|
||||
cancelledAt: Date | null;
|
||||
currentPeriodStart: Date | null;
|
||||
currentPeriodEnd: Date | null;
|
||||
entitlements: TenantBillingEntitlement[];
|
||||
};
|
||||
|
||||
export type TenantBillingEntitlements = {
|
||||
tenantId: string;
|
||||
planCode: string | null;
|
||||
seatQuantity: number;
|
||||
features: Record<string, TenantBillingEntitlement>;
|
||||
};
|
||||
|
||||
type TenantBillingFeatureRow = {
|
||||
code?: string | null;
|
||||
name: string;
|
||||
order: number;
|
||||
title: string;
|
||||
type: number;
|
||||
value: number;
|
||||
quotaValue?: unknown | null;
|
||||
accumulate: boolean;
|
||||
};
|
||||
|
||||
type TenantBillingProductRow = {
|
||||
id: string;
|
||||
createdAt: Date;
|
||||
customEntitlementPlanId?: string | null;
|
||||
cancelledAt?: Date | null;
|
||||
endsAt?: Date | null;
|
||||
planCode?: string | null;
|
||||
seatQuantity?: number | null;
|
||||
quantity?: number | null;
|
||||
currentPeriodStart?: Date | null;
|
||||
currentPeriodEnd?: Date | null;
|
||||
subscriptionProduct: {
|
||||
id: string;
|
||||
code?: string | null;
|
||||
lagoPlanCode?: string | null;
|
||||
title: string;
|
||||
features: TenantBillingFeatureRow[];
|
||||
};
|
||||
};
|
||||
|
||||
type TenantBillingSubscriptionRow = {
|
||||
tenantId: string;
|
||||
status?: string | null;
|
||||
planCode?: string | null;
|
||||
seatQuantity?: number | null;
|
||||
lagoCustomerId?: string | null;
|
||||
mollieCustomerId?: string | null;
|
||||
lastInvoiceExternalId?: string | null;
|
||||
lastPaymentExternalId?: string | null;
|
||||
trialStartsAt?: Date | null;
|
||||
trialEndsAt?: Date | null;
|
||||
pastDueSince?: Date | null;
|
||||
frozenAt?: Date | null;
|
||||
cancelledAt?: Date | null;
|
||||
products: TenantBillingProductRow[];
|
||||
};
|
||||
|
||||
export const tenantBillingStateInclude = {
|
||||
products: {
|
||||
include: {
|
||||
subscriptionProduct: {
|
||||
include: {
|
||||
features: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
||||
export type TenantBillingStateClient = {
|
||||
tenantSubscription: {
|
||||
findUnique(args: { where: { tenantId: string }; include: typeof tenantBillingStateInclude }): Promise<TenantBillingSubscriptionRow | null>;
|
||||
};
|
||||
};
|
||||
|
||||
const NOT_INCLUDED_LIMIT_TYPE = 0;
|
||||
|
||||
function getTenantBillingStateClient(): TenantBillingStateClient {
|
||||
return getDbClient() as unknown as TenantBillingStateClient;
|
||||
}
|
||||
|
||||
function isBillingSubscriptionStatus(value: string | null | undefined): value is BillingSubscriptionStatus {
|
||||
return billingSubscriptionStatuses.includes(value as BillingSubscriptionStatus);
|
||||
}
|
||||
|
||||
export function normalizeBillingSubscriptionStatus(
|
||||
value: string | null | undefined,
|
||||
markers: { frozenAt?: Date | null; cancelledAt?: Date | null } = {},
|
||||
): BillingSubscriptionStatus {
|
||||
if (markers.cancelledAt) return "cancelled";
|
||||
if (markers.frozenAt) return "frozen";
|
||||
return isBillingSubscriptionStatus(value) ? value : "trial";
|
||||
}
|
||||
|
||||
function isReadOnlyStatus(status: BillingSubscriptionStatus): boolean {
|
||||
return status === "past_due" || status === "cancelled" || status === "frozen";
|
||||
}
|
||||
|
||||
function positiveInteger(value: number | null | undefined): number | null {
|
||||
if (typeof value !== "number" || !Number.isFinite(value)) return null;
|
||||
const normalized = Math.trunc(value);
|
||||
return normalized > 0 ? normalized : null;
|
||||
}
|
||||
|
||||
function activeProducts(products: TenantBillingProductRow[], now: Date): TenantBillingProductRow[] {
|
||||
return products
|
||||
.filter((product) => !product.endsAt || product.endsAt > now)
|
||||
.sort((left, right) => right.createdAt.getTime() - left.createdAt.getTime());
|
||||
}
|
||||
|
||||
function resolveProductPlanCode(product: TenantBillingProductRow): string | null {
|
||||
return (
|
||||
product.planCode ??
|
||||
product.customEntitlementPlanId ??
|
||||
product.subscriptionProduct.code ??
|
||||
product.subscriptionProduct.lagoPlanCode ??
|
||||
product.subscriptionProduct.id ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
function resolvePlanCode(subscription: TenantBillingSubscriptionRow | null, products: TenantBillingProductRow[]): string | null {
|
||||
return subscription?.planCode ?? products.map(resolveProductPlanCode).find((value): value is string => Boolean(value)) ?? null;
|
||||
}
|
||||
|
||||
function resolveSeatQuantity(subscription: TenantBillingSubscriptionRow | null, products: TenantBillingProductRow[]): number {
|
||||
return subscription?.seatQuantity && subscription.seatQuantity > 0
|
||||
? subscription.seatQuantity
|
||||
: products.map((product) => positiveInteger(product.seatQuantity) ?? positiveInteger(product.quantity)).find((value): value is number => value !== null) ?? 1;
|
||||
}
|
||||
|
||||
function resolvePeriod(products: TenantBillingProductRow[]): Pick<TenantBillingState, "currentPeriodStart" | "currentPeriodEnd"> {
|
||||
const product = products.find((item) => item.currentPeriodStart || item.currentPeriodEnd);
|
||||
return {
|
||||
currentPeriodStart: product?.currentPeriodStart ?? null,
|
||||
currentPeriodEnd: product?.currentPeriodEnd ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveEntitlements(products: TenantBillingProductRow[]): TenantBillingEntitlement[] {
|
||||
const entitlements = new Map<string, TenantBillingEntitlement>();
|
||||
|
||||
for (const product of products) {
|
||||
const sourcePlanCode = resolveProductPlanCode(product);
|
||||
for (const feature of product.subscriptionProduct.features) {
|
||||
const featureKey = feature.code ?? feature.name;
|
||||
if (!featureKey) continue;
|
||||
|
||||
const current = entitlements.get(featureKey);
|
||||
const next: TenantBillingEntitlement = {
|
||||
featureKey,
|
||||
title: feature.title,
|
||||
enabled: feature.type !== NOT_INCLUDED_LIMIT_TYPE,
|
||||
limitType: feature.type,
|
||||
limit: feature.value,
|
||||
quotaValue: feature.quotaValue ?? null,
|
||||
accumulate: feature.accumulate,
|
||||
sourceProductId: product.subscriptionProduct.id,
|
||||
sourcePlanCode,
|
||||
};
|
||||
|
||||
if (!current || next.limitType > current.limitType || (next.limitType === current.limitType && next.limit > current.limit)) {
|
||||
entitlements.set(featureKey, next);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [...entitlements.values()].sort((left, right) => left.featureKey.localeCompare(right.featureKey));
|
||||
}
|
||||
|
||||
export async function resolveTenantBillingState(
|
||||
tenantId: string,
|
||||
options: { client?: TenantBillingStateClient; now?: Date } = {},
|
||||
): Promise<TenantBillingState> {
|
||||
const subscription = await (options.client ?? getTenantBillingStateClient()).tenantSubscription.findUnique({
|
||||
where: { tenantId },
|
||||
include: tenantBillingStateInclude,
|
||||
});
|
||||
const products = activeProducts(subscription?.products ?? [], options.now ?? new Date());
|
||||
const status = normalizeBillingSubscriptionStatus(subscription?.status, {
|
||||
frozenAt: subscription?.frozenAt,
|
||||
cancelledAt: subscription?.cancelledAt,
|
||||
});
|
||||
const period = resolvePeriod(products);
|
||||
|
||||
return {
|
||||
tenantId,
|
||||
status,
|
||||
readOnly: isReadOnlyStatus(status),
|
||||
planCode: resolvePlanCode(subscription, products),
|
||||
seatQuantity: resolveSeatQuantity(subscription, products),
|
||||
lagoCustomerId: subscription?.lagoCustomerId ?? null,
|
||||
mollieCustomerId: subscription?.mollieCustomerId ?? null,
|
||||
lastInvoiceExternalId: subscription?.lastInvoiceExternalId ?? null,
|
||||
lastPaymentExternalId: subscription?.lastPaymentExternalId ?? null,
|
||||
trialStartsAt: subscription?.trialStartsAt ?? null,
|
||||
trialEndsAt: subscription?.trialEndsAt ?? null,
|
||||
pastDueSince: subscription?.pastDueSince ?? null,
|
||||
frozenAt: subscription?.frozenAt ?? null,
|
||||
cancelledAt: subscription?.cancelledAt ?? null,
|
||||
currentPeriodStart: period.currentPeriodStart,
|
||||
currentPeriodEnd: period.currentPeriodEnd,
|
||||
entitlements: resolveEntitlements(products),
|
||||
};
|
||||
}
|
||||
|
||||
export async function resolveTenantEntitlements(
|
||||
tenantId: string,
|
||||
options: { client?: TenantBillingStateClient; now?: Date } = {},
|
||||
): Promise<TenantBillingEntitlements> {
|
||||
const state = await resolveTenantBillingState(tenantId, options);
|
||||
return {
|
||||
tenantId: state.tenantId,
|
||||
planCode: state.planCode,
|
||||
seatQuantity: state.seatQuantity,
|
||||
features: Object.fromEntries(state.entitlements.map((entitlement) => [entitlement.featureKey, entitlement])),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
applyLagoSubscriptionSync,
|
||||
applyMolliePaymentSync,
|
||||
BILLING_SYNC_IDEMPOTENCY_SCOPE,
|
||||
normalizeLagoSubscriptionStatus,
|
||||
normalizeMolliePaymentStatus,
|
||||
type BillingSyncClient,
|
||||
} from "./billing-sync.server.js";
|
||||
|
||||
type FakeState = {
|
||||
idempotency: Map<string, { responseBody: unknown }>;
|
||||
subscriptions: Map<string, Record<string, unknown>>;
|
||||
products: Array<{ id: string; code?: string | null; lagoPlanCode?: string | null }>;
|
||||
tenantProducts: Array<Record<string, unknown> & { id: string }>;
|
||||
auditEvents: unknown[];
|
||||
activities: unknown[];
|
||||
};
|
||||
|
||||
type IdempotencyFindUniqueArgs = Parameters<BillingSyncClient["idempotencyKey"]["findUnique"]>[0];
|
||||
type IdempotencyCreateArgs = Parameters<BillingSyncClient["idempotencyKey"]["create"]>[0];
|
||||
type AuditCreateArgs = Parameters<BillingSyncClient["auditEvent"]["create"]>[0];
|
||||
type ActivityCreateArgs = Parameters<BillingSyncClient["activity"]["create"]>[0];
|
||||
type TenantSubscriptionUpsertArgs = Parameters<BillingSyncClient["tenantSubscription"]["upsert"]>[0];
|
||||
type SubscriptionProductFindFirstArgs = Parameters<BillingSyncClient["subscriptionProduct"]["findFirst"]>[0];
|
||||
type TenantSubscriptionProductFindFirstArgs = Parameters<BillingSyncClient["tenantSubscriptionProduct"]["findFirst"]>[0];
|
||||
type TenantSubscriptionProductCreateArgs = Parameters<BillingSyncClient["tenantSubscriptionProduct"]["create"]>[0];
|
||||
type TenantSubscriptionProductUpdateArgs = Parameters<BillingSyncClient["tenantSubscriptionProduct"]["update"]>[0];
|
||||
type TenantSubscriptionProductUpdateManyArgs = Parameters<BillingSyncClient["tenantSubscriptionProduct"]["updateMany"]>[0];
|
||||
|
||||
function createFakeClient(state: Partial<FakeState> = {}): BillingSyncClient {
|
||||
const fake: FakeState = {
|
||||
idempotency: state.idempotency ?? new Map(),
|
||||
subscriptions: state.subscriptions ?? new Map(),
|
||||
products: state.products ?? [],
|
||||
tenantProducts: state.tenantProducts ?? [],
|
||||
auditEvents: state.auditEvents ?? [],
|
||||
activities: state.activities ?? [],
|
||||
};
|
||||
|
||||
return {
|
||||
idempotencyKey: {
|
||||
async findUnique({ where }: IdempotencyFindUniqueArgs) {
|
||||
const row = fake.idempotency.get(`${where.idempotency_key_scope_key.scope}:${where.idempotency_key_scope_key.key}`);
|
||||
return row
|
||||
? ({
|
||||
id: "idem_1",
|
||||
createdAt: new Date("2026-07-04T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-07-04T00:00:00.000Z"),
|
||||
expiresAt: null,
|
||||
scope: where.idempotency_key_scope_key.scope,
|
||||
key: where.idempotency_key_scope_key.key,
|
||||
requestHash: "hash",
|
||||
responseStatus: 200,
|
||||
responseBody: row.responseBody,
|
||||
responseHeaders: null,
|
||||
} as never)
|
||||
: null;
|
||||
},
|
||||
async create({ data }: IdempotencyCreateArgs) {
|
||||
fake.idempotency.set(`${data.scope}:${data.key}`, { responseBody: data.responseBody });
|
||||
return { id: `idem_${fake.idempotency.size}`, createdAt: new Date(), updatedAt: new Date(), ...data } as never;
|
||||
},
|
||||
},
|
||||
auditEvent: {
|
||||
async findFirst() {
|
||||
return null;
|
||||
},
|
||||
async create({ data }: AuditCreateArgs) {
|
||||
fake.auditEvents.push(data);
|
||||
return { id: `audit_${fake.auditEvents.length}`, createdAt: new Date(), ...data } as never;
|
||||
},
|
||||
},
|
||||
activity: {
|
||||
async create({ data }: ActivityCreateArgs) {
|
||||
fake.activities.push(data);
|
||||
return { id: `activity_${fake.activities.length}` };
|
||||
},
|
||||
},
|
||||
tenantSubscription: {
|
||||
async upsert({ where, create, update }: TenantSubscriptionUpsertArgs) {
|
||||
const current = fake.subscriptions.get(where.tenantId);
|
||||
const next = { ...(current ?? { id: `sub_${fake.subscriptions.size + 1}` }), ...(current ? update : create), tenantId: where.tenantId };
|
||||
fake.subscriptions.set(where.tenantId, next);
|
||||
return next as never;
|
||||
},
|
||||
},
|
||||
subscriptionProduct: {
|
||||
async findFirst({ where }: SubscriptionProductFindFirstArgs) {
|
||||
return (
|
||||
fake.products.find((product) =>
|
||||
where.OR.some((condition) => condition.id === product.id || condition.code === product.code || condition.lagoPlanCode === product.lagoPlanCode)
|
||||
) ?? null
|
||||
);
|
||||
},
|
||||
},
|
||||
tenantSubscriptionProduct: {
|
||||
async findFirst({ where }: TenantSubscriptionProductFindFirstArgs) {
|
||||
return (
|
||||
fake.tenantProducts.find(
|
||||
(product) =>
|
||||
product.tenantSubscriptionId === where.tenantSubscriptionId &&
|
||||
where.OR.some(
|
||||
(condition) =>
|
||||
condition.lagoSubscriptionId === product.lagoSubscriptionId ||
|
||||
condition.subscriptionProductId === product.subscriptionProductId ||
|
||||
condition.planCode === product.planCode
|
||||
)
|
||||
) ?? null
|
||||
);
|
||||
},
|
||||
async create({ data }: TenantSubscriptionProductCreateArgs) {
|
||||
const row = { id: `tenant_product_${fake.tenantProducts.length + 1}`, ...data };
|
||||
fake.tenantProducts.push(row);
|
||||
return row;
|
||||
},
|
||||
async update({ where, data }: TenantSubscriptionProductUpdateArgs) {
|
||||
const index = fake.tenantProducts.findIndex((row) => row.id === where.id);
|
||||
fake.tenantProducts[index] = { ...fake.tenantProducts[index], ...data };
|
||||
return fake.tenantProducts[index];
|
||||
},
|
||||
async updateMany({ where, data }: TenantSubscriptionProductUpdateManyArgs) {
|
||||
const now = new Date();
|
||||
let count = 0;
|
||||
for (let index = 0; index < fake.tenantProducts.length; index += 1) {
|
||||
const row = fake.tenantProducts[index];
|
||||
if (row.tenantSubscriptionId !== where.tenantSubscriptionId) continue;
|
||||
const idCondition = where.id as { not?: string } | undefined;
|
||||
if (idCondition?.not && row.id === idCondition.not) continue;
|
||||
if (row.cancelledAt !== null && row.cancelledAt !== undefined) continue;
|
||||
const endsAt = row.endsAt instanceof Date ? row.endsAt : row.endsAt ? new Date(String(row.endsAt)) : null;
|
||||
if (endsAt && endsAt <= now) continue;
|
||||
fake.tenantProducts[index] = { ...row, ...data };
|
||||
count += 1;
|
||||
}
|
||||
return { count };
|
||||
},
|
||||
},
|
||||
__state: fake,
|
||||
} as unknown as BillingSyncClient;
|
||||
}
|
||||
|
||||
function getFakeState(client: BillingSyncClient): FakeState {
|
||||
return (client as unknown as { __state: FakeState }).__state;
|
||||
}
|
||||
|
||||
describe("billing-sync.server", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["active", "active"],
|
||||
["trialing", "trial"],
|
||||
["payment_failed", "past_due"],
|
||||
["paused", "frozen"],
|
||||
["terminated", "cancelled"],
|
||||
] as const)("maps Lago status %s to %s", (input, expected) => {
|
||||
expect(normalizeLagoSubscriptionStatus(input)).toBe(expected);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["paid", "active"],
|
||||
["authorized", "active"],
|
||||
["failed", "past_due"],
|
||||
["expired", "past_due"],
|
||||
["refunded", "past_due"],
|
||||
["open", null],
|
||||
] as const)("maps Mollie payment status %s to %s", (input, expected) => {
|
||||
expect(normalizeMolliePaymentStatus(input)).toBe(expected);
|
||||
});
|
||||
|
||||
it("mirrors Lago subscription state into the local tenant subscription and product entitlement link", async () => {
|
||||
const client = createFakeClient({
|
||||
products: [{ id: "product_1", code: "pro", lagoPlanCode: "lago_pro" }],
|
||||
});
|
||||
|
||||
const result = await applyLagoSubscriptionSync(
|
||||
{
|
||||
tenantId: "tenant_1",
|
||||
eventKey: "lago:sub_1:active",
|
||||
lagoCustomerId: "cus_1",
|
||||
lagoSubscriptionId: "sub_1",
|
||||
status: "active",
|
||||
planCode: "lago_pro",
|
||||
seatQuantity: 7,
|
||||
invoiceExternalId: "inv_1",
|
||||
currentPeriodStart: new Date("2026-07-01T00:00:00.000Z"),
|
||||
currentPeriodEnd: new Date("2026-08-01T00:00:00.000Z"),
|
||||
},
|
||||
client
|
||||
);
|
||||
|
||||
const state = getFakeState(client);
|
||||
expect(result).toEqual({ tenantId: "tenant_1", provider: "lago", idempotencyKey: "lago:sub_1:active", replayed: false, status: "active" });
|
||||
expect(state.subscriptions.get("tenant_1")).toMatchObject({
|
||||
status: "active",
|
||||
lagoCustomerId: "cus_1",
|
||||
planCode: "lago_pro",
|
||||
seatQuantity: 7,
|
||||
lastInvoiceExternalId: "inv_1",
|
||||
pastDueSince: null,
|
||||
frozenAt: null,
|
||||
cancelledAt: null,
|
||||
});
|
||||
expect(state.tenantProducts).toHaveLength(1);
|
||||
expect(state.tenantProducts[0]).toMatchObject({ subscriptionProductId: "product_1", lagoSubscriptionId: "sub_1", planCode: "lago_pro", quantity: 7 });
|
||||
expect(state.idempotency.has(`${BILLING_SYNC_IDEMPOTENCY_SCOPE}:lago:sub_1:active`)).toBe(true);
|
||||
expect(state.auditEvents).toHaveLength(1);
|
||||
expect(state.activities).toHaveLength(1);
|
||||
expect(state.activities[0]).toMatchObject({ activityType: "billing_state_changed", subjectType: "tenant", subjectId: "tenant_1" });
|
||||
});
|
||||
|
||||
it("ends other active tenant products when a paid plan change becomes active", async () => {
|
||||
const receivedAt = new Date("2026-07-04T12:00:00.000Z");
|
||||
const client = createFakeClient({
|
||||
products: [
|
||||
{ id: "product_pro", code: "pro", lagoPlanCode: "pro" },
|
||||
{ id: "product_business", code: "business", lagoPlanCode: "business" },
|
||||
],
|
||||
subscriptions: new Map([["tenant_1", { id: "sub_1", tenantId: "tenant_1", status: "active", planCode: "pro" }]]),
|
||||
tenantProducts: [
|
||||
{
|
||||
id: "tenant_product_pro",
|
||||
tenantSubscriptionId: "sub_1",
|
||||
subscriptionProductId: "product_pro",
|
||||
planCode: "pro",
|
||||
lagoSubscriptionId: "lago_pro",
|
||||
cancelledAt: null,
|
||||
endsAt: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await applyLagoSubscriptionSync(
|
||||
{
|
||||
tenantId: "tenant_1",
|
||||
eventKey: "lago:business:active",
|
||||
lagoSubscriptionId: "lago_business",
|
||||
status: "active",
|
||||
planCode: "business",
|
||||
seatQuantity: 1,
|
||||
receivedAt,
|
||||
},
|
||||
client
|
||||
);
|
||||
|
||||
const state = getFakeState(client);
|
||||
expect(state.tenantProducts).toHaveLength(2);
|
||||
expect(state.tenantProducts.find((product) => product.id === "tenant_product_pro")).toMatchObject({
|
||||
cancelledAt: receivedAt,
|
||||
endsAt: receivedAt,
|
||||
});
|
||||
expect(state.tenantProducts.find((product) => product.subscriptionProductId === "product_business")).toMatchObject({
|
||||
cancelledAt: null,
|
||||
endsAt: null,
|
||||
lagoSubscriptionId: "lago_business",
|
||||
planCode: "business",
|
||||
});
|
||||
});
|
||||
|
||||
it("replays duplicate provider events without mutating or auditing again", async () => {
|
||||
const client = createFakeClient();
|
||||
|
||||
await applyMolliePaymentSync({ tenantId: "tenant_1", eventKey: "mollie:pay_1", paymentExternalId: "pay_1", status: "paid" }, client);
|
||||
const second = await applyMolliePaymentSync({ tenantId: "tenant_1", eventKey: "mollie:pay_1", paymentExternalId: "pay_1", status: "paid" }, client);
|
||||
|
||||
const state = getFakeState(client);
|
||||
expect(second.replayed).toBe(true);
|
||||
expect(second.status).toBe("active");
|
||||
expect(state.auditEvents).toHaveLength(1);
|
||||
expect(state.activities).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("marks failed Mollie payments as past_due and preserves invoice/payment references", async () => {
|
||||
const client = createFakeClient();
|
||||
const receivedAt = new Date("2026-07-04T12:00:00.000Z");
|
||||
|
||||
await applyMolliePaymentSync(
|
||||
{
|
||||
tenantId: "tenant_2",
|
||||
eventKey: "mollie:pay_failed",
|
||||
mollieCustomerId: "cst_1",
|
||||
paymentExternalId: "pay_failed",
|
||||
invoiceExternalId: "inv_failed",
|
||||
status: "failed",
|
||||
receivedAt,
|
||||
},
|
||||
client
|
||||
);
|
||||
|
||||
expect(getFakeState(client).subscriptions.get("tenant_2")).toMatchObject({
|
||||
status: "past_due",
|
||||
mollieCustomerId: "cst_1",
|
||||
lastInvoiceExternalId: "inv_failed",
|
||||
lastPaymentExternalId: "pay_failed",
|
||||
pastDueSince: receivedAt,
|
||||
frozenAt: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,345 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { createAuditEvent, type AuditEventWriterClient } from "./audit-events.server.js";
|
||||
import { getDbClient } from "./client.server.js";
|
||||
import { createStoredIdempotencyResponse, findStoredIdempotencyResponse, type IdempotencyKeyClient } from "./idempotency-keys.server.js";
|
||||
import type { Prisma } from "../generated/prisma/client/client.js";
|
||||
import type { BillingSubscriptionStatus } from "./billing-domain.server.js";
|
||||
|
||||
export const BILLING_SYNC_IDEMPOTENCY_SCOPE = "billing:provider-sync";
|
||||
|
||||
export type BillingSyncProvider = "lago" | "mollie";
|
||||
|
||||
export type BillingSyncResult = {
|
||||
tenantId: string;
|
||||
provider: BillingSyncProvider;
|
||||
idempotencyKey: string;
|
||||
replayed: boolean;
|
||||
status: BillingSubscriptionStatus | null;
|
||||
};
|
||||
|
||||
export type ApplyLagoSubscriptionSyncInput = {
|
||||
tenantId: string;
|
||||
eventKey: string;
|
||||
lagoCustomerId?: string | null;
|
||||
lagoSubscriptionId?: string | null;
|
||||
status?: string | null;
|
||||
planCode?: string | null;
|
||||
seatQuantity?: number | null;
|
||||
currentPeriodStart?: Date | null;
|
||||
currentPeriodEnd?: Date | null;
|
||||
invoiceExternalId?: string | null;
|
||||
receivedAt?: Date;
|
||||
};
|
||||
|
||||
export type ApplyMolliePaymentSyncInput = {
|
||||
tenantId: string;
|
||||
eventKey: string;
|
||||
mollieCustomerId?: string | null;
|
||||
paymentExternalId?: string | null;
|
||||
invoiceExternalId?: string | null;
|
||||
status?: string | null;
|
||||
receivedAt?: Date;
|
||||
};
|
||||
|
||||
type TenantSubscriptionRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
status?: string | null;
|
||||
cancelledAt?: Date | null;
|
||||
};
|
||||
|
||||
type SubscriptionProductRow = {
|
||||
id: string;
|
||||
code?: string | null;
|
||||
lagoPlanCode?: string | null;
|
||||
};
|
||||
|
||||
export type BillingSyncClient = IdempotencyKeyClient &
|
||||
AuditEventWriterClient & {
|
||||
activity: {
|
||||
create(args: { data: Record<string, unknown> }): Promise<{ id: string }>;
|
||||
};
|
||||
tenantSubscription: {
|
||||
upsert(args: { where: { tenantId: string }; create: Record<string, unknown>; update: Record<string, unknown> }): Promise<TenantSubscriptionRow>;
|
||||
};
|
||||
subscriptionProduct: {
|
||||
findFirst(args: {
|
||||
where: {
|
||||
OR: Array<{ code?: string; lagoPlanCode?: string; id?: string }>;
|
||||
};
|
||||
select: { id: true; code: true; lagoPlanCode: true };
|
||||
}): Promise<SubscriptionProductRow | null>;
|
||||
};
|
||||
tenantSubscriptionProduct: {
|
||||
findFirst(args: {
|
||||
where: {
|
||||
tenantSubscriptionId: string;
|
||||
OR: Array<{ lagoSubscriptionId?: string; subscriptionProductId?: string; planCode?: string }>;
|
||||
};
|
||||
select: { id: true };
|
||||
}): Promise<{ id: string } | null>;
|
||||
create(args: { data: Record<string, unknown> }): Promise<{ id: string }>;
|
||||
update(args: { where: { id: string }; data: Record<string, unknown> }): Promise<unknown>;
|
||||
updateMany(args: { where: Record<string, unknown>; data: Record<string, unknown> }): Promise<{ count: number }>;
|
||||
};
|
||||
};
|
||||
|
||||
function getBillingSyncClient(): BillingSyncClient {
|
||||
return getDbClient() as unknown as BillingSyncClient;
|
||||
}
|
||||
|
||||
function positiveInteger(value: number | null | undefined): number | null {
|
||||
if (typeof value !== "number" || !Number.isFinite(value)) return null;
|
||||
const normalized = Math.trunc(value);
|
||||
return normalized > 0 ? normalized : null;
|
||||
}
|
||||
|
||||
export function normalizeLagoSubscriptionStatus(value: string | null | undefined): BillingSubscriptionStatus {
|
||||
const normalized = value?.trim().toLowerCase().replaceAll("-", "_");
|
||||
if (normalized === "active") return "active";
|
||||
if (normalized === "trial" || normalized === "trialing") return "trial";
|
||||
if (normalized === "past_due" || normalized === "failed" || normalized === "payment_failed") return "past_due";
|
||||
if (normalized === "paused" || normalized === "suspended" || normalized === "frozen") return "frozen";
|
||||
if (normalized === "cancelled" || normalized === "canceled" || normalized === "terminated") return "cancelled";
|
||||
return "trial";
|
||||
}
|
||||
|
||||
export function normalizeMolliePaymentStatus(value: string | null | undefined): BillingSubscriptionStatus | null {
|
||||
const normalized = value?.trim().toLowerCase().replaceAll("-", "_");
|
||||
if (normalized === "paid" || normalized === "authorized") return "active";
|
||||
if (normalized === "failed" || normalized === "expired" || normalized === "refunded" || normalized === "charged_back") {
|
||||
return "past_due";
|
||||
}
|
||||
if (normalized === "canceled" || normalized === "cancelled") return "past_due";
|
||||
return null;
|
||||
}
|
||||
|
||||
function statusMarkers(status: BillingSubscriptionStatus, at: Date): Record<string, Date | null> {
|
||||
if (status === "active" || status === "trial") {
|
||||
return { pastDueSince: null, frozenAt: null, cancelledAt: null };
|
||||
}
|
||||
if (status === "past_due") {
|
||||
return { pastDueSince: at, frozenAt: null };
|
||||
}
|
||||
if (status === "frozen") {
|
||||
return { frozenAt: at };
|
||||
}
|
||||
return { cancelledAt: at };
|
||||
}
|
||||
|
||||
function requestHash(input: unknown): string {
|
||||
return createHash("sha256").update(JSON.stringify(input)).digest("hex");
|
||||
}
|
||||
|
||||
function idempotencyBody(result: Omit<BillingSyncResult, "replayed">): Prisma.JsonObject {
|
||||
return {
|
||||
tenantId: result.tenantId,
|
||||
provider: result.provider,
|
||||
idempotencyKey: result.idempotencyKey,
|
||||
status: result.status,
|
||||
};
|
||||
}
|
||||
|
||||
function readReplayResult(provider: BillingSyncProvider, tenantId: string, eventKey: string, body: Prisma.JsonValue | undefined): BillingSyncResult {
|
||||
const record = body && typeof body === "object" && !Array.isArray(body) ? (body as Record<string, unknown>) : {};
|
||||
const status = typeof record.status === "string" ? (record.status as BillingSubscriptionStatus) : null;
|
||||
return { tenantId, provider, idempotencyKey: eventKey, replayed: true, status };
|
||||
}
|
||||
|
||||
async function runOnce(
|
||||
client: BillingSyncClient,
|
||||
provider: BillingSyncProvider,
|
||||
tenantId: string,
|
||||
eventKey: string,
|
||||
input: unknown,
|
||||
apply: () => Promise<BillingSubscriptionStatus | null>
|
||||
): Promise<BillingSyncResult> {
|
||||
const existing = await findStoredIdempotencyResponse({ scope: BILLING_SYNC_IDEMPOTENCY_SCOPE, key: eventKey }, client);
|
||||
if (existing) {
|
||||
return readReplayResult(provider, tenantId, eventKey, existing.body);
|
||||
}
|
||||
|
||||
const status = await apply();
|
||||
const result = { tenantId, provider, idempotencyKey: eventKey, status };
|
||||
|
||||
try {
|
||||
await createStoredIdempotencyResponse(
|
||||
{
|
||||
scope: BILLING_SYNC_IDEMPOTENCY_SCOPE,
|
||||
key: eventKey,
|
||||
requestHash: requestHash(input),
|
||||
response: { status: 200, body: idempotencyBody(result) },
|
||||
},
|
||||
client
|
||||
);
|
||||
} catch (error) {
|
||||
if ((error as { code?: unknown }).code === "P2002") {
|
||||
const replay = await findStoredIdempotencyResponse({ scope: BILLING_SYNC_IDEMPOTENCY_SCOPE, key: eventKey }, client);
|
||||
if (replay) return readReplayResult(provider, tenantId, eventKey, replay.body);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
await createAuditEvent(
|
||||
{
|
||||
tenantId,
|
||||
actorType: "system",
|
||||
action: "BILLING_SYNC_APPLIED",
|
||||
targetType: "TenantSubscription",
|
||||
targetId: tenantId,
|
||||
sourceModule: "billing",
|
||||
outcome: "success",
|
||||
dataSensitivity: "internal",
|
||||
metadata: { provider, eventKey, status },
|
||||
},
|
||||
client
|
||||
);
|
||||
await client.activity.create({
|
||||
data: {
|
||||
tenantId,
|
||||
actorUserId: null,
|
||||
actorKind: "system",
|
||||
activityType: "billing_state_changed",
|
||||
subjectType: "tenant",
|
||||
subjectId: tenantId,
|
||||
summaryText: status ? `Billing-Status auf ${status} gesetzt` : `Billing-Event von ${provider} verarbeitet`,
|
||||
metadata: { provider, eventKey, status },
|
||||
},
|
||||
});
|
||||
|
||||
return { ...result, replayed: false };
|
||||
}
|
||||
|
||||
async function mirrorLagoProduct(
|
||||
client: BillingSyncClient,
|
||||
subscription: TenantSubscriptionRow,
|
||||
input: ApplyLagoSubscriptionSyncInput,
|
||||
receivedAt: Date,
|
||||
status: BillingSubscriptionStatus
|
||||
): Promise<void> {
|
||||
const planCode = input.planCode?.trim();
|
||||
if (!planCode) return;
|
||||
|
||||
const product = await client.subscriptionProduct.findFirst({
|
||||
where: { OR: [{ code: planCode }, { lagoPlanCode: planCode }, { id: planCode }] },
|
||||
select: { id: true, code: true, lagoPlanCode: true },
|
||||
});
|
||||
if (!product) return;
|
||||
|
||||
const existing = await client.tenantSubscriptionProduct.findFirst({
|
||||
where: {
|
||||
tenantSubscriptionId: subscription.id,
|
||||
OR: [...(input.lagoSubscriptionId ? [{ lagoSubscriptionId: input.lagoSubscriptionId }] : []), { subscriptionProductId: product.id }, { planCode }],
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
const data = {
|
||||
subscriptionProductId: product.id,
|
||||
lagoSubscriptionId: input.lagoSubscriptionId ?? null,
|
||||
planCode,
|
||||
seatQuantity: positiveInteger(input.seatQuantity),
|
||||
quantity: positiveInteger(input.seatQuantity) ?? 1,
|
||||
currentPeriodStart: input.currentPeriodStart ?? null,
|
||||
currentPeriodEnd: input.currentPeriodEnd ?? null,
|
||||
endsAt: null,
|
||||
cancelledAt: null,
|
||||
};
|
||||
|
||||
if (existing) {
|
||||
await client.tenantSubscriptionProduct.update({ where: { id: existing.id }, data });
|
||||
await endOtherActivePlanProducts(client, subscription.id, existing.id, receivedAt, status);
|
||||
return;
|
||||
}
|
||||
|
||||
const created = await client.tenantSubscriptionProduct.create({
|
||||
data: {
|
||||
tenantSubscriptionId: subscription.id,
|
||||
...data,
|
||||
},
|
||||
});
|
||||
await endOtherActivePlanProducts(client, subscription.id, created.id, receivedAt, status);
|
||||
}
|
||||
|
||||
async function endOtherActivePlanProducts(
|
||||
client: BillingSyncClient,
|
||||
tenantSubscriptionId: string,
|
||||
activeTenantSubscriptionProductId: string,
|
||||
receivedAt: Date,
|
||||
status: BillingSubscriptionStatus
|
||||
): Promise<void> {
|
||||
if (status !== "active" && status !== "trial") return;
|
||||
|
||||
await client.tenantSubscriptionProduct.updateMany({
|
||||
where: {
|
||||
tenantSubscriptionId,
|
||||
id: { not: activeTenantSubscriptionProductId },
|
||||
cancelledAt: null,
|
||||
OR: [{ endsAt: null }, { endsAt: { gt: receivedAt } }],
|
||||
},
|
||||
data: {
|
||||
cancelledAt: receivedAt,
|
||||
endsAt: receivedAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function applyLagoSubscriptionSync(
|
||||
input: ApplyLagoSubscriptionSyncInput,
|
||||
client: BillingSyncClient = getBillingSyncClient()
|
||||
): Promise<BillingSyncResult> {
|
||||
const receivedAt = input.receivedAt ?? new Date();
|
||||
const status = normalizeLagoSubscriptionStatus(input.status);
|
||||
const seatQuantity = positiveInteger(input.seatQuantity);
|
||||
return runOnce(client, "lago", input.tenantId, input.eventKey, input, async () => {
|
||||
const subscription = await client.tenantSubscription.upsert({
|
||||
where: { tenantId: input.tenantId },
|
||||
create: {
|
||||
tenantId: input.tenantId,
|
||||
lagoCustomerId: input.lagoCustomerId ?? null,
|
||||
planCode: input.planCode ?? null,
|
||||
seatQuantity: seatQuantity ?? 1,
|
||||
lastInvoiceExternalId: input.invoiceExternalId ?? null,
|
||||
status,
|
||||
...statusMarkers(status, receivedAt),
|
||||
},
|
||||
update: {
|
||||
lagoCustomerId: input.lagoCustomerId ?? undefined,
|
||||
planCode: input.planCode ?? undefined,
|
||||
seatQuantity: seatQuantity ?? undefined,
|
||||
lastInvoiceExternalId: input.invoiceExternalId ?? undefined,
|
||||
status,
|
||||
...statusMarkers(status, receivedAt),
|
||||
},
|
||||
});
|
||||
await mirrorLagoProduct(client, subscription, input, receivedAt, status);
|
||||
return status;
|
||||
});
|
||||
}
|
||||
|
||||
export async function applyMolliePaymentSync(
|
||||
input: ApplyMolliePaymentSyncInput,
|
||||
client: BillingSyncClient = getBillingSyncClient()
|
||||
): Promise<BillingSyncResult> {
|
||||
const receivedAt = input.receivedAt ?? new Date();
|
||||
const status = normalizeMolliePaymentStatus(input.status);
|
||||
return runOnce(client, "mollie", input.tenantId, input.eventKey, input, async () => {
|
||||
await client.tenantSubscription.upsert({
|
||||
where: { tenantId: input.tenantId },
|
||||
create: {
|
||||
tenantId: input.tenantId,
|
||||
mollieCustomerId: input.mollieCustomerId ?? null,
|
||||
lastInvoiceExternalId: input.invoiceExternalId ?? null,
|
||||
lastPaymentExternalId: input.paymentExternalId ?? null,
|
||||
status: status ?? "trial",
|
||||
...(status ? statusMarkers(status, receivedAt) : {}),
|
||||
},
|
||||
update: {
|
||||
mollieCustomerId: input.mollieCustomerId ?? undefined,
|
||||
lastInvoiceExternalId: input.invoiceExternalId ?? undefined,
|
||||
lastPaymentExternalId: input.paymentExternalId ?? undefined,
|
||||
...(status ? { status, ...statusMarkers(status, receivedAt) } : {}),
|
||||
},
|
||||
});
|
||||
return status;
|
||||
});
|
||||
}
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
const clientServerSourcePath = path.join(path.dirname(fileURLToPath(import.meta.url)), "./client.server.ts");
|
||||
const clientServerSource = () => readFileSync(clientServerSourcePath, "utf8");
|
||||
|
||||
describe("@toolctrl/db server client boundary", () => {
|
||||
describe("@hivegrid/db server client boundary", () => {
|
||||
it("exports a createDbClient factory from the package-owned generated client", () => {
|
||||
expect(createDbClient).toEqual(expect.any(Function));
|
||||
});
|
||||
@@ -42,7 +42,7 @@ describe("@toolctrl/db server client boundary", () => {
|
||||
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('import { createChildLogger, defaultLogger } from "@hivegrid/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");
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Prisma, PrismaClient } from "../generated/prisma/client/client.js";
|
||||
import { PrismaPg } from "@prisma/adapter-pg";
|
||||
import { createChildLogger, defaultLogger } from "@toolctrl/logger";
|
||||
import { createChildLogger, defaultLogger } from "@hivegrid/logger";
|
||||
|
||||
export type DbClient = PrismaClient;
|
||||
|
||||
@@ -60,7 +60,7 @@ export function getDbClient(options: DbClientSingletonOptions = {}): DbClient {
|
||||
* 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
|
||||
* (read-after-write), billing webhook handlers that read state they just
|
||||
* wrote, and the outbox dispatcher reading PENDING events.
|
||||
*
|
||||
* Functionally identical to {@link getDbClient} — both return the same
|
||||
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { EnvKeyWrapper } from "@hivegrid/foundation/crypto";
|
||||
import { clearTenantDekCache, decryptTenantField, destroyTenantDek, encryptTenantField, getOrCreateTenantDek } from "./tenant-envelope.server.js";
|
||||
|
||||
// R-P5 — per-tenant envelope orchestration. Uses an in-memory fake store (no PG)
|
||||
// so it always runs; proves per-tenant isolation + crypto-shredding without a DB.
|
||||
|
||||
type Row = { tenantId: string; wrappedDek: Uint8Array; keyVersion: number };
|
||||
|
||||
function makeFakeStore() {
|
||||
const rows = new Map<string, Row>();
|
||||
let creates = 0;
|
||||
return {
|
||||
creates: () => creates,
|
||||
size: () => rows.size,
|
||||
client: {
|
||||
tenantEncryptionKey: {
|
||||
findUnique: ({ where }: { where: { tenantId: string } }) => Promise.resolve(rows.get(where.tenantId) ?? null),
|
||||
create: ({ data }: { data: Row }) => {
|
||||
if (rows.has(data.tenantId)) {
|
||||
throw new Error("Unique constraint failed on tenantId");
|
||||
}
|
||||
creates += 1;
|
||||
rows.set(data.tenantId, data);
|
||||
return Promise.resolve(data);
|
||||
},
|
||||
deleteMany: ({ where }: { where: { tenantId: string } }) => {
|
||||
const had = rows.delete(where.tenantId);
|
||||
return Promise.resolve({ count: had ? 1 : 0 });
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const WRAPPER = new EnvKeyWrapper();
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.CRYPTO_SECRET = "test-master-key-aaaaaaaaaaaaaaaaaaaaaa";
|
||||
clearTenantDekCache();
|
||||
});
|
||||
|
||||
describe("tenant-envelope", () => {
|
||||
it("round-trips a field for a tenant", async () => {
|
||||
const store = makeFakeStore();
|
||||
const opts = { client: store.client, wrapper: WRAPPER };
|
||||
const ct = await encryptTenantField("tenant_1", "oauth-token-xyz", opts);
|
||||
expect(ct).not.toContain("oauth-token-xyz");
|
||||
expect(await decryptTenantField("tenant_1", ct, opts)).toBe("oauth-token-xyz");
|
||||
});
|
||||
|
||||
it("persists the wrapped DEK exactly once across many encrypts", async () => {
|
||||
const store = makeFakeStore();
|
||||
const opts = { client: store.client, wrapper: WRAPPER };
|
||||
await encryptTenantField("tenant_1", "a", opts);
|
||||
clearTenantDekCache(); // force a re-read path
|
||||
await encryptTenantField("tenant_1", "b", opts);
|
||||
await encryptTenantField("tenant_1", "c", opts);
|
||||
expect(store.creates()).toBe(1);
|
||||
expect(store.size()).toBe(1);
|
||||
});
|
||||
|
||||
it("isolates tenants: a foreign tenant cannot decrypt another's ciphertext", async () => {
|
||||
const store = makeFakeStore();
|
||||
const opts = { client: store.client, wrapper: WRAPPER };
|
||||
const ct = await encryptTenantField("tenant_A", "secret-A", opts);
|
||||
// tenant_B resolves its OWN distinct DEK → opening A's envelope fails closed.
|
||||
await expect(decryptTenantField("tenant_B", ct, opts)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("gives each tenant a distinct DEK", async () => {
|
||||
const store = makeFakeStore();
|
||||
const opts = { client: store.client, wrapper: WRAPPER };
|
||||
const a = await getOrCreateTenantDek("tenant_A", opts);
|
||||
const b = await getOrCreateTenantDek("tenant_B", opts);
|
||||
expect(Buffer.compare(a.dek, b.dek)).not.toBe(0);
|
||||
});
|
||||
|
||||
it("crypto-shredding: after destroyTenantDek the old ciphertext is unrecoverable", async () => {
|
||||
const store = makeFakeStore();
|
||||
const opts = { client: store.client, wrapper: WRAPPER };
|
||||
const ct = await encryptTenantField("tenant_1", "top-secret", opts);
|
||||
|
||||
const removed = await destroyTenantDek("tenant_1", opts);
|
||||
expect(removed).toBe(1);
|
||||
expect(store.size()).toBe(0);
|
||||
|
||||
// A fresh DEK is minted on next use → the old envelope can no longer be opened.
|
||||
await expect(decryptTenantField("tenant_1", ct, opts)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("requires a tenantId", async () => {
|
||||
const store = makeFakeStore();
|
||||
await expect(getOrCreateTenantDek("", { client: store.client, wrapper: WRAPPER })).rejects.toThrow(/tenantId/);
|
||||
});
|
||||
});
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
// R-P5 (P5) — per-tenant envelope-encryption orchestration (AD-8).
|
||||
//
|
||||
// Ties the pure primitives (@hivegrid/foundation/crypto) to the DB-backed
|
||||
// TenantEncryptionKey store. Shared by web + worker (both seal/open credentials),
|
||||
// so it lives in @hivegrid/db (the only layer with both Prisma and node access).
|
||||
//
|
||||
// Per tenant: ONE random DEK, stored only WRAPPED (master key via KeyWrapper).
|
||||
// On first use the DEK is generated + wrapped + persisted; thereafter the
|
||||
// unwrapped DEK is held in a short-lived in-memory cache (never persisted). Field
|
||||
// seal/open uses that DEK. Crypto-shredding = delete the tenant's row
|
||||
// (destroyTenantDek) → all that tenant's ciphertext is permanently unreadable.
|
||||
//
|
||||
// RLS-ready: every query is tenant-scoped (where: { tenantId }) and accepts an
|
||||
// optional `client` so a caller already inside withTenantRLS() can pass its tx.
|
||||
|
||||
import { generateDek, getKeyWrapper, open, seal, type KeyWrapper } from "@hivegrid/foundation/crypto";
|
||||
import { getDbClient } from "../client.server.js";
|
||||
|
||||
/** Minimal structural shape of the store, satisfied by the full client or a tx. */
|
||||
type TenantEncryptionKeyStore = {
|
||||
tenantEncryptionKey: {
|
||||
findUnique(args: { where: { tenantId: string }; select?: { wrappedDek: true; keyVersion: true } }): Promise<{ wrappedDek: Uint8Array; keyVersion: number } | null>;
|
||||
create(args: { data: { tenantId: string; wrappedDek: Uint8Array; keyVersion: number } }): Promise<unknown>;
|
||||
deleteMany(args: { where: { tenantId: string } }): Promise<{ count: number }>;
|
||||
};
|
||||
};
|
||||
|
||||
export type TenantEnvelopeOptions = {
|
||||
/** Active Prisma client/tx (defaults to the shared singleton). */
|
||||
client?: TenantEncryptionKeyStore;
|
||||
/** Master-key wrapper (defaults to the process wrapper, EnvKeyWrapper). */
|
||||
wrapper?: KeyWrapper;
|
||||
};
|
||||
|
||||
type DekCacheEntry = { dek: Buffer; keyVersion: number; expiresAt: number };
|
||||
|
||||
const DEK_CACHE_TTL_MS = 60_000;
|
||||
const dekCache = new Map<string, DekCacheEntry>();
|
||||
|
||||
function resolveStore(opts?: TenantEnvelopeOptions): TenantEncryptionKeyStore {
|
||||
return (opts?.client as TenantEncryptionKeyStore | undefined) ?? (getDbClient() as unknown as TenantEncryptionKeyStore);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load (or lazily create + persist) a tenant's DEK, unwrapped. The unwrapped DEK
|
||||
* is cached in-memory for a short TTL and never persisted. Concurrent first-use
|
||||
* is race-safe: a unique-constraint collision falls back to re-reading.
|
||||
*/
|
||||
export async function getOrCreateTenantDek(tenantId: string, opts?: TenantEnvelopeOptions): Promise<{ dek: Buffer; keyVersion: number }> {
|
||||
if (!tenantId) {
|
||||
throw new Error("tenant-envelope: tenantId is required");
|
||||
}
|
||||
const cached = dekCache.get(tenantId);
|
||||
if (cached && cached.expiresAt > Date.now()) {
|
||||
return { dek: cached.dek, keyVersion: cached.keyVersion };
|
||||
}
|
||||
const store = resolveStore(opts);
|
||||
const wrapper = opts?.wrapper ?? getKeyWrapper();
|
||||
|
||||
const existing = await store.tenantEncryptionKey.findUnique({ where: { tenantId }, select: { wrappedDek: true, keyVersion: true } });
|
||||
if (existing) {
|
||||
const dek = await wrapper.unwrap(Buffer.from(existing.wrappedDek));
|
||||
cacheDek(tenantId, dek, existing.keyVersion);
|
||||
return { dek, keyVersion: existing.keyVersion };
|
||||
}
|
||||
|
||||
const dek = generateDek();
|
||||
const wrapped = await wrapper.wrap(dek);
|
||||
try {
|
||||
await store.tenantEncryptionKey.create({ data: { tenantId, wrappedDek: wrapped, keyVersion: 1 } });
|
||||
cacheDek(tenantId, dek, 1);
|
||||
return { dek, keyVersion: 1 };
|
||||
} catch (error) {
|
||||
// Likely a concurrent create won the unique(tenantId) race — re-read.
|
||||
const row = await store.tenantEncryptionKey.findUnique({ where: { tenantId }, select: { wrappedDek: true, keyVersion: true } });
|
||||
if (row) {
|
||||
const raced = await wrapper.unwrap(Buffer.from(row.wrappedDek));
|
||||
cacheDek(tenantId, raced, row.keyVersion);
|
||||
return { dek: raced, keyVersion: row.keyVersion };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function cacheDek(tenantId: string, dek: Buffer, keyVersion: number): void {
|
||||
dekCache.set(tenantId, { dek, keyVersion, expiresAt: Date.now() + DEK_CACHE_TTL_MS });
|
||||
}
|
||||
|
||||
/** Encrypt a single sensitive field for a tenant (AD-8 envelope). */
|
||||
export async function encryptTenantField(tenantId: string, plaintext: string, opts?: TenantEnvelopeOptions): Promise<string> {
|
||||
const { dek, keyVersion } = await getOrCreateTenantDek(tenantId, opts);
|
||||
return seal(dek, plaintext, keyVersion);
|
||||
}
|
||||
|
||||
/** Decrypt a single sensitive field for a tenant. */
|
||||
export async function decryptTenantField(tenantId: string, ciphertext: string, opts?: TenantEnvelopeOptions): Promise<string> {
|
||||
const { dek } = await getOrCreateTenantDek(tenantId, opts);
|
||||
return open(dek, ciphertext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Crypto-shredding (M165 / AK-P21): delete the tenant's wrapped DEK and drop the
|
||||
* in-memory cache. After this, every envelope produced for that tenant is
|
||||
* permanently undecryptable. Returns the number of rows removed (0 or 1).
|
||||
*/
|
||||
export async function destroyTenantDek(tenantId: string, opts?: TenantEnvelopeOptions): Promise<number> {
|
||||
const store = resolveStore(opts);
|
||||
const result = await store.tenantEncryptionKey.deleteMany({ where: { tenantId } });
|
||||
dekCache.delete(tenantId);
|
||||
return result.count;
|
||||
}
|
||||
|
||||
/** Clear the in-memory DEK cache (tests; or after a key rotation). */
|
||||
export function clearTenantDekCache(tenantId?: string): void {
|
||||
if (tenantId) {
|
||||
dekCache.delete(tenantId);
|
||||
} else {
|
||||
dekCache.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The shared per-tenant field-crypto contract. Consumers (HR password safe via
|
||||
* the hrFieldCrypto seam, R-P5 DataConnection credentials) depend on this shape;
|
||||
* the production binding is {@link getTenantFieldCrypto}.
|
||||
*/
|
||||
export interface TenantFieldCrypto {
|
||||
encrypt(tenantId: string, plaintext: string): Promise<string>;
|
||||
decrypt(tenantId: string, ciphertext: string): Promise<string>;
|
||||
}
|
||||
|
||||
/** Default binding over the DB-backed envelope (what modules consume). */
|
||||
export function getTenantFieldCrypto(): TenantFieldCrypto {
|
||||
return {
|
||||
encrypt: (tenantId, plaintext) => encryptTenantField(tenantId, plaintext),
|
||||
decrypt: (tenantId, ciphertext) => decryptTenantField(tenantId, ciphertext),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("./client.server.js", () => ({ createDbClient: vi.fn() }));
|
||||
|
||||
import { createDbClient } from "./client.server.js";
|
||||
import { databaseTargetLabel, isDatabaseReachable } from "./database-reachable.js";
|
||||
|
||||
type ProbeClient = {
|
||||
$queryRaw: ReturnType<typeof vi.fn>;
|
||||
$disconnect: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
function installProbe(probe: ProbeClient): void {
|
||||
vi.mocked(createDbClient).mockReturnValue(probe as never);
|
||||
}
|
||||
|
||||
describe("databaseTargetLabel", () => {
|
||||
it("renders host:port for an explicit port", () => {
|
||||
expect(databaseTargetLabel("postgres://user:pw@db.example.com:6543/app")).toBe("db.example.com:6543");
|
||||
});
|
||||
|
||||
it("defaults the port to 5432 when the URL omits it", () => {
|
||||
expect(databaseTargetLabel("postgres://user:pw@db.example.com/app")).toBe("db.example.com:5432");
|
||||
});
|
||||
|
||||
it("never leaks credentials embedded in the URL", () => {
|
||||
const label = databaseTargetLabel("postgres://admin:s3cr3t@db.example.com:5432/app");
|
||||
expect(label).not.toContain("s3cr3t");
|
||||
expect(label).not.toContain("admin");
|
||||
});
|
||||
|
||||
it("returns a generic label for an unparseable URL", () => {
|
||||
expect(databaseTargetLabel("not a url")).toBe("configured database");
|
||||
});
|
||||
});
|
||||
|
||||
describe("isDatabaseReachable", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("resolves true when the probe query succeeds and disconnects afterwards", async () => {
|
||||
const probe: ProbeClient = {
|
||||
$queryRaw: vi.fn().mockResolvedValue([{ "?column?": 1 }]),
|
||||
$disconnect: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
installProbe(probe);
|
||||
|
||||
await expect(isDatabaseReachable("postgres://localhost:5432/app")).resolves.toBe(true);
|
||||
expect(createDbClient).toHaveBeenCalledWith(expect.objectContaining({ connectionString: "postgres://localhost:5432/app" }));
|
||||
expect(probe.$disconnect).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("resolves false when the probe query rejects (unreachable / auth failure)", async () => {
|
||||
const probe: ProbeClient = {
|
||||
// Build the rejected promise at call time so the source's `.then` rejection
|
||||
// handler attaches in the same tick (no spurious unhandled-rejection warning).
|
||||
$queryRaw: vi.fn().mockImplementation(() => Promise.reject(new Error("P1001 connection refused"))),
|
||||
$disconnect: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
installProbe(probe);
|
||||
|
||||
await expect(isDatabaseReachable("postgres://localhost:5432/app")).resolves.toBe(false);
|
||||
expect(probe.$disconnect).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("resolves false when the query outlives the timeout budget", async () => {
|
||||
const probe: ProbeClient = {
|
||||
$queryRaw: vi.fn().mockImplementation(() => new Promise(() => undefined)),
|
||||
$disconnect: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
installProbe(probe);
|
||||
|
||||
await expect(isDatabaseReachable("postgres://localhost:5432/app", 5)).resolves.toBe(false);
|
||||
expect(probe.$disconnect).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("swallows a disconnect failure on the cleanup path", async () => {
|
||||
const probe: ProbeClient = {
|
||||
$queryRaw: vi.fn().mockResolvedValue([{ "?column?": 1 }]),
|
||||
$disconnect: vi.fn().mockRejectedValue(new Error("disconnect boom")),
|
||||
};
|
||||
installProbe(probe);
|
||||
|
||||
await expect(isDatabaseReachable("postgres://localhost:5432/app")).resolves.toBe(true);
|
||||
expect(probe.$disconnect).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Shared reachability probe for opt-in Postgres integration suites.
|
||||
*
|
||||
* The integration tests in this package gate on a non-sentinel DATABASE_URL
|
||||
* being set. That is insufficient for the CI "Workspace package tests" job
|
||||
* (`pnpm -r test`): it injects a localhost DATABASE_URL but runs no Postgres
|
||||
* service, so gating on the URL alone makes those suites connect and fail with
|
||||
* `PrismaClientKnownRequestError P1001` instead of skipping. This helper
|
||||
* confirms the server is actually usable by running a trivial `SELECT 1` with
|
||||
* the package's own client factory, so local runs with a real DB still execute
|
||||
* while CI-without-DB skips. Mirrors the inline probe in
|
||||
* `apps/worker/src/jobs/workflow-trigger-e2e.test.ts`.
|
||||
*/
|
||||
import { createDbClient } from "./client.server.js";
|
||||
|
||||
/** Host:port label for logs — never includes credentials. */
|
||||
export function databaseTargetLabel(url: string): string {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
return `${parsed.hostname}:${parsed.port || "5432"}`;
|
||||
} catch {
|
||||
return "configured database";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Usability probe for the configured Postgres URL. Any connection problem
|
||||
* (unreachable / auth failure / missing database / timeout) resolves to
|
||||
* "not reachable". `onError` is silenced so the probe stays quiet on the skip
|
||||
* path.
|
||||
*/
|
||||
export async function isDatabaseReachable(url: string, timeoutMs = 4_000): Promise<boolean> {
|
||||
const probe = createDbClient({ connectionString: url, onError: () => undefined });
|
||||
// The query promise resolves to true/false and never rejects, so the losing
|
||||
// race branch can't surface as an unhandled rejection.
|
||||
const query = probe.$queryRaw`SELECT 1`.then(
|
||||
() => true,
|
||||
() => false
|
||||
);
|
||||
const timeout = new Promise<boolean>((resolve) => {
|
||||
setTimeout(() => resolve(false), timeoutMs).unref?.();
|
||||
});
|
||||
try {
|
||||
return await Promise.race([query, timeout]);
|
||||
} finally {
|
||||
await probe.$disconnect().catch(() => undefined);
|
||||
}
|
||||
}
|
||||
+14
-16
@@ -88,14 +88,14 @@ function createStubClient(): DeviceTokenClient & { _rows: StoredRow[] } {
|
||||
|
||||
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("ios")).toBeNull();
|
||||
expect(parseDevicePlatform("android")).toBeNull();
|
||||
expect(parseDevicePlatform("desktop")).toBeNull();
|
||||
expect(parseDevicePlatform(123)).toBeNull();
|
||||
|
||||
expect(parsePushProvider("fcm")).toBe("fcm");
|
||||
expect(parsePushProvider("apns")).toBe("apns");
|
||||
expect(parsePushProvider("fcm")).toBeNull();
|
||||
expect(parsePushProvider("apns")).toBeNull();
|
||||
expect(parsePushProvider("webpush")).toBe("webpush");
|
||||
expect(parsePushProvider("onesignal")).toBeNull();
|
||||
});
|
||||
@@ -103,8 +103,6 @@ describe("parseDevicePlatform / parsePushProvider", () => {
|
||||
|
||||
describe("defaultPushProviderFor", () => {
|
||||
it("maps platform -> provider", () => {
|
||||
expect(defaultPushProviderFor("ios")).toBe("apns");
|
||||
expect(defaultPushProviderFor("android")).toBe("fcm");
|
||||
expect(defaultPushProviderFor("web")).toBe("webpush");
|
||||
});
|
||||
});
|
||||
@@ -113,10 +111,10 @@ 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" },
|
||||
{ userId: "u-1", tenantId: "t-1", platform: "web", token: "tok-1" },
|
||||
client,
|
||||
);
|
||||
expect(row.pushProvider).toBe("apns");
|
||||
expect(row.pushProvider).toBe("webpush");
|
||||
expect(row.revokedAt).toBeNull();
|
||||
expect(client._rows).toHaveLength(1);
|
||||
});
|
||||
@@ -124,14 +122,14 @@ describe("registerDeviceToken", () => {
|
||||
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" },
|
||||
{ userId: "u-1", tenantId: "t-1", platform: "web", 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" },
|
||||
{ userId: "u-1", tenantId: "t-1", platform: "web", token: "tok-x" },
|
||||
client,
|
||||
);
|
||||
expect(client._rows[0]?.revokedAt).toBeNull();
|
||||
@@ -142,9 +140,9 @@ describe("registerDeviceToken", () => {
|
||||
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);
|
||||
await registerDeviceToken({ userId: "u-1", tenantId: null, platform: "web", token: "t1" }, client);
|
||||
await registerDeviceToken({ userId: "u-1", tenantId: null, platform: "web", token: "t2" }, client);
|
||||
await registerDeviceToken({ userId: "u-2", tenantId: null, platform: "web", token: "t3" }, client);
|
||||
const count = await revokeDeviceTokensForUser("u-1", client);
|
||||
expect(count).toBe(2);
|
||||
const remaining = client._rows.filter((r) => r.revokedAt === null);
|
||||
@@ -155,9 +153,9 @@ describe("revokeDeviceTokensForUser", () => {
|
||||
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 registerDeviceToken({ userId: "u-1", tenantId: "t-1", platform: "web", token: "ta" }, client);
|
||||
await registerDeviceToken({ userId: "u-1", tenantId: "t-2", platform: "web", token: "tb" }, client);
|
||||
await registerDeviceToken({ userId: "u-1", tenantId: "t-1", platform: "web", token: "tc" }, client);
|
||||
await revokeDeviceToken("tc", client);
|
||||
|
||||
const allForUser = await listActiveDeviceTokens({ userId: "u-1" }, client);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Server-side helpers for the DeviceToken Prisma model (Phase 08 #65).
|
||||
*
|
||||
* The mobile-wrapper register-device endpoint upserts on the unique
|
||||
* The Web Push 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.
|
||||
*
|
||||
@@ -10,11 +10,11 @@
|
||||
*/
|
||||
import { getDbClient, type DbClient } from "./client.server.js";
|
||||
|
||||
export type DevicePlatform = "ios" | "android" | "web";
|
||||
export type PushProvider = "fcm" | "apns" | "webpush";
|
||||
export type DevicePlatform = "web";
|
||||
export type PushProvider = "webpush";
|
||||
|
||||
const DEVICE_PLATFORMS = new Set<DevicePlatform>(["ios", "android", "web"]);
|
||||
const PUSH_PROVIDERS = new Set<PushProvider>(["fcm", "apns", "webpush"]);
|
||||
const DEVICE_PLATFORMS = new Set<DevicePlatform>(["web"]);
|
||||
const PUSH_PROVIDERS = new Set<PushProvider>(["webpush"]);
|
||||
|
||||
export function parseDevicePlatform(value: unknown): DevicePlatform | null {
|
||||
return typeof value === "string" && DEVICE_PLATFORMS.has(value as DevicePlatform) ? (value as DevicePlatform) : null;
|
||||
@@ -26,8 +26,7 @@ export function parsePushProvider(value: unknown): 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";
|
||||
void platform;
|
||||
return "webpush";
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,18 @@
|
||||
* 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.
|
||||
*
|
||||
* BARE-SCALAR user references (R-P6C, 2026-06-29): columns like
|
||||
* `createdByUserId` / `zustaendigerUserId` (crm.prisma) or
|
||||
* `createdByUserId` / `assignedToUserId` (tasks.prisma, hr.prisma) are
|
||||
* intentionally NOT enumerated here. They carry no DB-level `@relation`
|
||||
* to `User`, so there is no FK to cascade and the companion test's grep
|
||||
* (which matches `@relation ... references: [id]` to `User`) does not see
|
||||
* them — by design, repo-wide. They are metadata references; after user
|
||||
* deletion they become dangling cuids (no PII payload). Project-wide
|
||||
* pseudonymization of bare-scalar user references is a separate
|
||||
* cross-cutting hardening topic (not CRM-specific) — to be addressed when
|
||||
* the DSGVO deletion flow goes live, consistently across all modules.
|
||||
*/
|
||||
|
||||
export type DsgvoCascadeStrategy = "hard-delete" | "pseudonymize" | "retain-tombstone";
|
||||
@@ -52,11 +64,16 @@ export interface UserFkMapEntry {
|
||||
* additions stay reviewable.
|
||||
*/
|
||||
export const USER_FK_MAP: ReadonlyArray<UserFkMapEntry> = Object.freeze([
|
||||
// P19 admin tenant notes. Schema declares `author User? @relation(..., onDelete: SetNull)`
|
||||
// → `retain-tombstone` (note survives, FK nulled). `includeInExport: false`: an operator
|
||||
// note *about a tenant* is an internal admin record, not the author's personal data, so it
|
||||
// stays out of the author's export bundle. TODO(VR-P31): confirm DSGVO intent (retain-tombstone sign-off).
|
||||
{ model: "AdminTenantNote", column: "authorUserId", strategy: "retain-tombstone", source: "admin.prisma", includeInExport: false },
|
||||
{ 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 },
|
||||
// R-P5: Apps-Engine uses bare String scalars for createdByUserId (AD-21, like
|
||||
// tasks/files/hr) — no User @relation, so no USER_FK_MAP entry (retain by default).
|
||||
// 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
|
||||
@@ -90,7 +107,12 @@ export const USER_FK_MAP: ReadonlyArray<UserFkMapEntry> = Object.freeze([
|
||||
{ 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 },
|
||||
// Help-desk staff/author FKs (schema `onDelete: SetNull`) → retain-tombstone; the ticket
|
||||
// *owner* (`userId`) stays pseudonymize per the help-desk-retention note above.
|
||||
// TODO(VR-P31): confirm DSGVO intent for assignee/message-author rows.
|
||||
{ model: "SupportTicket", column: "assignedToUserId", strategy: "retain-tombstone", source: "helpDesk.prisma", includeInExport: true },
|
||||
{ model: "SupportTicket", column: "userId", strategy: "pseudonymize", source: "helpDesk.prisma", includeInExport: true },
|
||||
{ model: "SupportTicketMessage", column: "authorUserId", strategy: "retain-tombstone", source: "admin.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 },
|
||||
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
isEmailSuppressed,
|
||||
normalizeSuppressionAddress,
|
||||
recordEmailSuppression,
|
||||
type EmailSuppressionClient,
|
||||
type EmailSuppressionRow,
|
||||
} from "./email-suppression.server.js";
|
||||
|
||||
/** Minimal in-memory stand-in for the EmailSuppressionList Prisma delegate. */
|
||||
function createFakeClient(): EmailSuppressionClient & { rows: EmailSuppressionRow[] } {
|
||||
const rows: EmailSuppressionRow[] = [];
|
||||
let seq = 0;
|
||||
return {
|
||||
rows,
|
||||
emailSuppressionList: {
|
||||
async upsert(args) {
|
||||
const existing = rows.find((r) => r.tenantId === args.where.tenantId_emailAddress.tenantId && r.emailAddress === args.where.tenantId_emailAddress.emailAddress);
|
||||
if (existing) {
|
||||
existing.reason = args.update.reason;
|
||||
existing.detail = args.update.detail;
|
||||
return existing;
|
||||
}
|
||||
const created: EmailSuppressionRow = { id: `s${++seq}`, ...args.create };
|
||||
rows.push(created);
|
||||
return created;
|
||||
},
|
||||
async findUnique(args) {
|
||||
return rows.find((r) => r.tenantId === args.where.tenantId_emailAddress.tenantId && r.emailAddress === args.where.tenantId_emailAddress.emailAddress) ?? null;
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("normalizeSuppressionAddress", () => {
|
||||
it("trims and lower-cases", () => {
|
||||
expect(normalizeSuppressionAddress(" Foo@Bar.TEST ")).toBe("foo@bar.test");
|
||||
});
|
||||
});
|
||||
|
||||
describe("recordEmailSuppression", () => {
|
||||
it("creates a normalized entry", async () => {
|
||||
const client = createFakeClient();
|
||||
await recordEmailSuppression({ tenantId: "t1", emailAddress: "Hard@Bounce.test", reason: "bounce", detail: "550 mailbox unavailable" }, client);
|
||||
expect(client.rows).toEqual([{ id: "s1", tenantId: "t1", emailAddress: "hard@bounce.test", reason: "bounce", detail: "550 mailbox unavailable" }]);
|
||||
});
|
||||
|
||||
it("is idempotent on (tenantId, emailAddress) and updates the reason/detail", async () => {
|
||||
const client = createFakeClient();
|
||||
await recordEmailSuppression({ tenantId: "t1", emailAddress: "a@x.test", reason: "manual" }, client);
|
||||
await recordEmailSuppression({ tenantId: "t1", emailAddress: "A@X.test", reason: "complaint", detail: "spam report" }, client);
|
||||
expect(client.rows).toHaveLength(1);
|
||||
expect(client.rows[0]).toMatchObject({ reason: "complaint", detail: "spam report" });
|
||||
});
|
||||
|
||||
it("scopes entries per tenant", async () => {
|
||||
const client = createFakeClient();
|
||||
await recordEmailSuppression({ tenantId: "t1", emailAddress: "a@x.test", reason: "bounce" }, client);
|
||||
await recordEmailSuppression({ tenantId: "t2", emailAddress: "a@x.test", reason: "bounce" }, client);
|
||||
expect(client.rows).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isEmailSuppressed", () => {
|
||||
it("returns true only for a suppressed address in the same tenant", async () => {
|
||||
const client = createFakeClient();
|
||||
await recordEmailSuppression({ tenantId: "t1", emailAddress: "blocked@x.test", reason: "bounce" }, client);
|
||||
await expect(isEmailSuppressed({ tenantId: "t1", emailAddress: "Blocked@X.test" }, client)).resolves.toBe(true);
|
||||
await expect(isEmailSuppressed({ tenantId: "t1", emailAddress: "other@x.test" }, client)).resolves.toBe(false);
|
||||
await expect(isEmailSuppressed({ tenantId: "t2", emailAddress: "blocked@x.test" }, client)).resolves.toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
// AK-P14a · P14 Email — per-tenant suppression list service.
|
||||
//
|
||||
// The suppression list is the system-of-record for addresses that must NOT be
|
||||
// sent to: hard bounces and spam complaints (fed by the Mailjet event webhook)
|
||||
// plus manual additions from the senders/suppression screen. `recordEmailSuppression`
|
||||
// is idempotent (upsert on the (tenantId, emailAddress) unique) so a webhook that
|
||||
// re-fires never duplicates. `isEmailSuppressed` is the pre-send guard the
|
||||
// marketing path (AK-P14b) calls before every send.
|
||||
//
|
||||
// The client is injectable (a narrow structural interface) so the unit tests run
|
||||
// against an in-memory fake — same stance as email-sequences.server.ts.
|
||||
|
||||
import { getDbClient } from "./client.server.js";
|
||||
|
||||
export type EmailSuppressionReason = "bounce" | "complaint" | "manual";
|
||||
|
||||
export type RecordEmailSuppressionInput = {
|
||||
tenantId: string;
|
||||
emailAddress: string;
|
||||
reason: EmailSuppressionReason;
|
||||
detail?: string | null;
|
||||
};
|
||||
|
||||
export type EmailSuppressionRow = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
emailAddress: string;
|
||||
reason: EmailSuppressionReason;
|
||||
detail: string | null;
|
||||
};
|
||||
|
||||
export type EmailSuppressionClient = {
|
||||
emailSuppressionList: {
|
||||
upsert(args: {
|
||||
where: { tenantId_emailAddress: { tenantId: string; emailAddress: string } };
|
||||
create: { tenantId: string; emailAddress: string; reason: EmailSuppressionReason; detail: string | null };
|
||||
update: { reason: EmailSuppressionReason; detail: string | null };
|
||||
}): Promise<EmailSuppressionRow>;
|
||||
findUnique(args: {
|
||||
where: { tenantId_emailAddress: { tenantId: string; emailAddress: string } };
|
||||
}): Promise<EmailSuppressionRow | null>;
|
||||
};
|
||||
};
|
||||
|
||||
/** Normalize an address for storage + comparison: trimmed + lower-cased. */
|
||||
export function normalizeSuppressionAddress(emailAddress: string): string {
|
||||
return emailAddress.trim().toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Idempotently record a suppressed address. A repeat call updates the reason +
|
||||
* detail (e.g. a manual entry later confirmed by a real bounce) but never
|
||||
* duplicates. Returns the stored row.
|
||||
*/
|
||||
export function recordEmailSuppression(
|
||||
input: RecordEmailSuppressionInput,
|
||||
client: EmailSuppressionClient = getDbClient() as unknown as EmailSuppressionClient,
|
||||
): Promise<EmailSuppressionRow> {
|
||||
const emailAddress = normalizeSuppressionAddress(input.emailAddress);
|
||||
const detail = input.detail ?? null;
|
||||
return client.emailSuppressionList.upsert({
|
||||
where: { tenantId_emailAddress: { tenantId: input.tenantId, emailAddress } },
|
||||
create: { tenantId: input.tenantId, emailAddress, reason: input.reason, detail },
|
||||
update: { reason: input.reason, detail },
|
||||
});
|
||||
}
|
||||
|
||||
/** Pre-send guard: true when the address is on the tenant's suppression list. */
|
||||
export async function isEmailSuppressed(
|
||||
input: { tenantId: string; emailAddress: string },
|
||||
client: EmailSuppressionClient = getDbClient() as unknown as EmailSuppressionClient,
|
||||
): Promise<boolean> {
|
||||
const emailAddress = normalizeSuppressionAddress(input.emailAddress);
|
||||
const row = await client.emailSuppressionList.findUnique({
|
||||
where: { tenantId_emailAddress: { tenantId: input.tenantId, emailAddress } },
|
||||
});
|
||||
return row !== null;
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
anonymizeTrackingIp,
|
||||
recordEmailClick,
|
||||
recordEmailOpen,
|
||||
safeRedirectTarget,
|
||||
type EmailTrackingClient,
|
||||
} from "./email-tracking.server.js";
|
||||
|
||||
type Open = { id: string; outboundEmailId: string; firstOpen: boolean; ipHash: string | null };
|
||||
type Click = { id: string; outboundEmailId: string; link: string; ipHash: string | null };
|
||||
|
||||
function createFakeClient(existingEmailIds: string[]): EmailTrackingClient & { opens: Open[]; clicks: Click[] } {
|
||||
const opens: Open[] = [];
|
||||
const clicks: Click[] = [];
|
||||
let seq = 0;
|
||||
return {
|
||||
opens,
|
||||
clicks,
|
||||
outboundEmail: {
|
||||
async findUnique(args) {
|
||||
return existingEmailIds.includes(args.where.id) ? { id: args.where.id, tenantId: "t1" } : null;
|
||||
},
|
||||
},
|
||||
outboundEmailOpen: {
|
||||
async findFirst(args) {
|
||||
return opens.find((o) => o.outboundEmailId === args.where.outboundEmailId) ?? null;
|
||||
},
|
||||
async create(args) {
|
||||
const row = { id: `o${++seq}`, ...args.data };
|
||||
opens.push(row);
|
||||
return row;
|
||||
},
|
||||
},
|
||||
outboundEmailClick: {
|
||||
async create(args) {
|
||||
const row = { id: `c${++seq}`, ...args.data };
|
||||
clicks.push(row);
|
||||
return row;
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("anonymizeTrackingIp", () => {
|
||||
it("hashes + truncates to 32 hex chars and never returns the raw ip", () => {
|
||||
const hash = anonymizeTrackingIp("203.0.113.7");
|
||||
expect(hash).toMatch(/^[a-f0-9]{32}$/);
|
||||
expect(hash).not.toContain("203.0.113.7");
|
||||
});
|
||||
|
||||
it("returns null for empty/unknown ip", () => {
|
||||
expect(anonymizeTrackingIp(null)).toBeNull();
|
||||
expect(anonymizeTrackingIp(" ")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("safeRedirectTarget", () => {
|
||||
it("accepts absolute http(s) urls", () => {
|
||||
expect(safeRedirectTarget("https://acme.test/landing?x=1")).toBe("https://acme.test/landing?x=1");
|
||||
});
|
||||
|
||||
it("rejects javascript/data/relative/empty targets", () => {
|
||||
expect(safeRedirectTarget("javascript:alert(1)")).toBeNull();
|
||||
expect(safeRedirectTarget("data:text/html,evil")).toBeNull();
|
||||
expect(safeRedirectTarget("/relative/path")).toBeNull();
|
||||
expect(safeRedirectTarget(null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("recordEmailOpen", () => {
|
||||
it("flags the first open and not subsequent ones", async () => {
|
||||
const client = createFakeClient(["e1"]);
|
||||
await expect(recordEmailOpen({ outboundEmailId: "e1", ipHash: "h" }, client)).resolves.toEqual({ status: "recorded", firstOpen: true });
|
||||
await expect(recordEmailOpen({ outboundEmailId: "e1", ipHash: "h" }, client)).resolves.toEqual({ status: "recorded", firstOpen: false });
|
||||
expect(client.opens).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("returns unknown_email for a missing email", async () => {
|
||||
const client = createFakeClient([]);
|
||||
await expect(recordEmailOpen({ outboundEmailId: "nope", ipHash: null }, client)).resolves.toEqual({ status: "unknown_email" });
|
||||
expect(client.opens).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("recordEmailClick", () => {
|
||||
it("records a click for a known email", async () => {
|
||||
const client = createFakeClient(["e1"]);
|
||||
await expect(recordEmailClick({ outboundEmailId: "e1", link: "https://acme.test", ipHash: "h" }, client)).resolves.toEqual({ status: "recorded" });
|
||||
expect(client.clicks).toEqual([{ id: "c1", outboundEmailId: "e1", link: "https://acme.test", ipHash: "h" }]);
|
||||
});
|
||||
|
||||
it("returns unknown_email for a missing email", async () => {
|
||||
const client = createFakeClient([]);
|
||||
await expect(recordEmailClick({ outboundEmailId: "nope", link: "https://acme.test", ipHash: null }, client)).resolves.toEqual({ status: "unknown_email" });
|
||||
expect(client.clicks).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
// AK-P14a · P14 Email — open/click tracking service.
|
||||
//
|
||||
// Records pixel opens and link clicks for an OutboundEmail. The client IP is
|
||||
// stored ONLY as a truncated sha256 hash (never the raw address) — matching the
|
||||
// marketing-lead `lastIpHash` convention. `firstOpen` flags the first open of a
|
||||
// given email so the campaign KPI ("unique opens") can be derived without a
|
||||
// second pass.
|
||||
//
|
||||
// This is the tracking INFRASTRUCTURE only; embedding the pixel / rewriting the
|
||||
// links at send time belongs to the marketing send path (AK-P14b). The client is
|
||||
// injectable so the unit tests run against an in-memory fake.
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { getDbClient } from "./client.server.js";
|
||||
|
||||
/** Truncated sha256 of the client IP — never the raw address. Null when unknown. */
|
||||
export function anonymizeTrackingIp(ip: string | null | undefined): string | null {
|
||||
if (!ip || !ip.trim()) {
|
||||
return null;
|
||||
}
|
||||
return createHash("sha256").update(ip.trim()).digest("hex").slice(0, 32);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a click-through target before redirecting. Only absolute http(s)
|
||||
* URLs are allowed — prevents the tracking endpoint from becoming an
|
||||
* open-redirect to `javascript:` / `data:` / relative paths.
|
||||
*/
|
||||
export function safeRedirectTarget(raw: string | null | undefined): string | null {
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
||||
return null;
|
||||
}
|
||||
return parsed.toString();
|
||||
}
|
||||
|
||||
type OutboundEmailRef = { id: string; tenantId: string | null };
|
||||
|
||||
export type EmailTrackingClient = {
|
||||
outboundEmail: {
|
||||
findUnique(args: { where: { id: string }; select: { id: true; tenantId: true } }): Promise<OutboundEmailRef | null>;
|
||||
};
|
||||
outboundEmailOpen: {
|
||||
findFirst(args: { where: { outboundEmailId: string } }): Promise<{ id: string } | null>;
|
||||
create(args: { data: { outboundEmailId: string; firstOpen: boolean; ipHash: string | null } }): Promise<{ id: string }>;
|
||||
};
|
||||
outboundEmailClick: {
|
||||
create(args: { data: { outboundEmailId: string; link: string; ipHash: string | null } }): Promise<{ id: string }>;
|
||||
};
|
||||
};
|
||||
|
||||
export type RecordEmailOpenResult = { status: "recorded"; firstOpen: boolean } | { status: "unknown_email" };
|
||||
export type RecordEmailClickResult = { status: "recorded" } | { status: "unknown_email" };
|
||||
|
||||
/** Record a pixel open. The first open of an email is flagged `firstOpen`. */
|
||||
export async function recordEmailOpen(
|
||||
input: { outboundEmailId: string; ipHash: string | null },
|
||||
client: EmailTrackingClient = getDbClient() as unknown as EmailTrackingClient,
|
||||
): Promise<RecordEmailOpenResult> {
|
||||
const email = await client.outboundEmail.findUnique({ where: { id: input.outboundEmailId }, select: { id: true, tenantId: true } });
|
||||
if (!email) {
|
||||
return { status: "unknown_email" };
|
||||
}
|
||||
const prior = await client.outboundEmailOpen.findFirst({ where: { outboundEmailId: input.outboundEmailId } });
|
||||
const firstOpen = prior === null;
|
||||
await client.outboundEmailOpen.create({ data: { outboundEmailId: input.outboundEmailId, firstOpen, ipHash: input.ipHash } });
|
||||
return { status: "recorded", firstOpen };
|
||||
}
|
||||
|
||||
/** Record a link click (already-validated target). */
|
||||
export async function recordEmailClick(
|
||||
input: { outboundEmailId: string; link: string; ipHash: string | null },
|
||||
client: EmailTrackingClient = getDbClient() as unknown as EmailTrackingClient,
|
||||
): Promise<RecordEmailClickResult> {
|
||||
const email = await client.outboundEmail.findUnique({ where: { id: input.outboundEmailId }, select: { id: true, tenantId: true } });
|
||||
if (!email) {
|
||||
return { status: "unknown_email" };
|
||||
}
|
||||
await client.outboundEmailClick.create({ data: { outboundEmailId: input.outboundEmailId, link: input.link, ipHash: input.ipHash } });
|
||||
return { status: "recorded" };
|
||||
}
|
||||
@@ -1,222 +0,0 @@
|
||||
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 } },
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,259 +0,0 @@
|
||||
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;
|
||||
}
|
||||
+32
-8
@@ -1,7 +1,7 @@
|
||||
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";
|
||||
import { entitlementLimitTypes, standardEntitlementPlans, type EntitlementPlanStub } from "@hivegrid/entitlements";
|
||||
import { getEntitlementPlanBillingProviderId, redactSeedError, seedStandardEntitlements, type EntitlementsSeedClient } from "./entitlements-seed.server.js";
|
||||
|
||||
function createSeedClient(existingProduct: { id: string } | null = null): EntitlementsSeedClient {
|
||||
return {
|
||||
@@ -14,6 +14,11 @@ function createSeedClient(existingProduct: { id: string } | null = null): Entitl
|
||||
deleteMany: vi.fn().mockResolvedValue({ count: existingProduct ? 2 : 0 }),
|
||||
create: vi.fn().mockResolvedValue({ id: "feature_1" }),
|
||||
},
|
||||
subscriptionPrice: {
|
||||
findFirst: vi.fn().mockResolvedValue(null),
|
||||
create: vi.fn().mockResolvedValue({ id: "price_1" }),
|
||||
update: vi.fn().mockResolvedValue({ id: "price_1" }),
|
||||
},
|
||||
} as unknown as EntitlementsSeedClient;
|
||||
}
|
||||
|
||||
@@ -28,16 +33,18 @@ describe("seedStandardEntitlements", () => {
|
||||
featureCount: singlePlan.features.length,
|
||||
createdProducts: 1,
|
||||
updatedProducts: 0,
|
||||
createdPrices: 2,
|
||||
updatedPrices: 0,
|
||||
deletedFeatures: 0,
|
||||
createdFeatures: singlePlan.features.length,
|
||||
});
|
||||
|
||||
expect(client.subscriptionProduct.findFirst).toHaveBeenCalledWith({
|
||||
where: { OR: [{ stripeId: getEntitlementPlanStripeId(singlePlan) }, { title: singlePlan.metadata.publicName }] },
|
||||
where: { OR: [{ billingProviderId: getEntitlementPlanBillingProviderId(singlePlan) }, { title: singlePlan.metadata.publicName }] },
|
||||
});
|
||||
expect(client.subscriptionProduct.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
stripeId: getEntitlementPlanStripeId(singlePlan),
|
||||
billingProviderId: getEntitlementPlanBillingProviderId(singlePlan),
|
||||
order: singlePlan.metadata.sortOrder,
|
||||
title: singlePlan.metadata.publicName,
|
||||
model: 0,
|
||||
@@ -47,6 +54,19 @@ describe("seedStandardEntitlements", () => {
|
||||
badge: null,
|
||||
}),
|
||||
});
|
||||
expect(client.subscriptionPrice.create).toHaveBeenCalledTimes(2);
|
||||
expect(client.subscriptionPrice.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
subscriptionProductId: "created_product",
|
||||
billingProviderId: `hivegrid_entitlement_price_${singlePlan.id}_monthly`,
|
||||
lagoFeeCode: `${singlePlan.id}_monthly`,
|
||||
molliePriceReference: `hivegrid_entitlement_price_${singlePlan.id}_monthly`,
|
||||
billingPeriod: 3,
|
||||
currency: "eur",
|
||||
price: "199",
|
||||
active: true,
|
||||
}),
|
||||
});
|
||||
expect(client.subscriptionFeature.create).toHaveBeenCalledTimes(singlePlan.features.length);
|
||||
expect(client.subscriptionFeature.create).toHaveBeenNthCalledWith(1, {
|
||||
data: expect.objectContaining({
|
||||
@@ -62,7 +82,7 @@ describe("seedStandardEntitlements", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("updates an existing product found by deterministic stripe id or title and replaces features", async () => {
|
||||
it("updates an existing product found by deterministic billing id or title and replaces features", async () => {
|
||||
const existingProduct = { id: "existing_product" };
|
||||
const client = createSeedClient(existingProduct);
|
||||
|
||||
@@ -76,7 +96,9 @@ describe("seedStandardEntitlements", () => {
|
||||
expect(client.subscriptionProduct.update).toHaveBeenCalledWith({
|
||||
where: { id: existingProduct.id },
|
||||
data: expect.objectContaining({
|
||||
stripeId: getEntitlementPlanStripeId(singlePlan),
|
||||
billingProviderId: getEntitlementPlanBillingProviderId(singlePlan),
|
||||
code: singlePlan.id,
|
||||
lagoPlanCode: singlePlan.id,
|
||||
order: singlePlan.metadata.sortOrder,
|
||||
title: singlePlan.metadata.publicName,
|
||||
}),
|
||||
@@ -98,6 +120,8 @@ describe("seedStandardEntitlements", () => {
|
||||
featureCount: singlePlan.features.length,
|
||||
createdProducts: 0,
|
||||
updatedProducts: 0,
|
||||
createdPrices: 0,
|
||||
updatedPrices: 0,
|
||||
deletedFeatures: 0,
|
||||
createdFeatures: 0,
|
||||
});
|
||||
@@ -152,9 +176,9 @@ describe("seedStandardEntitlements", () => {
|
||||
});
|
||||
|
||||
it("redacts standalone seed errors", () => {
|
||||
expect(redactSeedError("Stripe secret sk_live_123 for prod_abc")).toEqual({
|
||||
expect(redactSeedError("Billing secret sk_live_123 for prod_abc")).toEqual({
|
||||
name: "Error",
|
||||
message: "Stripe secret [redacted] for [redacted]",
|
||||
message: "Billing secret [redacted] for [redacted]",
|
||||
});
|
||||
});
|
||||
});
|
||||
+112
-10
@@ -5,14 +5,29 @@ import {
|
||||
type EntitlementLimitType,
|
||||
type EntitlementPlanStub,
|
||||
type FeatureKey,
|
||||
} from "@toolctrl/entitlements";
|
||||
} from "@hivegrid/entitlements";
|
||||
|
||||
import { getDbClient } from "./client.server.js";
|
||||
import type { SubscriptionFeature, SubscriptionProduct } from "./prisma-browser.js";
|
||||
import type { SubscriptionFeatureCreateInput, SubscriptionProductCreateInput, SubscriptionProductUpdateInput } from "./subscriptions.server.js";
|
||||
import type { SubscriptionFeature, SubscriptionPrice, SubscriptionProduct } from "./prisma-browser.js";
|
||||
import type {
|
||||
SubscriptionFeatureCreateInput,
|
||||
SubscriptionPriceCreateInput,
|
||||
SubscriptionPriceUpdateInput,
|
||||
SubscriptionProductCreateInput,
|
||||
SubscriptionProductUpdateInput,
|
||||
} from "./subscriptions.server.js";
|
||||
|
||||
const SEEDED_STRIPE_ID_PREFIX = "toolctrl_entitlement_plan";
|
||||
const SEEDED_BILLING_PROVIDER_ID_PREFIX = "hivegrid_entitlement_plan";
|
||||
const SEEDED_PRICE_PROVIDER_ID_PREFIX = "hivegrid_entitlement_price";
|
||||
const REDACTED = "[redacted]";
|
||||
const PRICE_TYPE_RECURRING = 1;
|
||||
const BILLING_PERIOD_MONTHLY = 3;
|
||||
const BILLING_PERIOD_YEARLY = 4;
|
||||
const STANDARD_PLAN_PRICES_EUR: Record<string, { monthly: string; yearly: string }> = {
|
||||
starter: { monthly: "199", yearly: "179" },
|
||||
pro: { monthly: "499", yearly: "449" },
|
||||
business: { monthly: "999", yearly: "899" },
|
||||
};
|
||||
|
||||
export type EntitlementsSeedPhase = "start" | "plan-seeded" | "success" | "failure";
|
||||
|
||||
@@ -22,6 +37,8 @@ export type EntitlementsSeedDiagnosticEvent = {
|
||||
featureCount: number;
|
||||
createdProducts: number;
|
||||
updatedProducts: number;
|
||||
createdPrices: number;
|
||||
updatedPrices: number;
|
||||
deletedFeatures: number;
|
||||
createdFeatures: number;
|
||||
planId?: string;
|
||||
@@ -38,12 +55,14 @@ export type EntitlementsSeedResult = {
|
||||
featureCount: number;
|
||||
createdProducts: number;
|
||||
updatedProducts: number;
|
||||
createdPrices: number;
|
||||
updatedPrices: number;
|
||||
deletedFeatures: number;
|
||||
createdFeatures: number;
|
||||
};
|
||||
|
||||
export type EntitlementsSeedSubscriptionProductClient = {
|
||||
findFirst(args: { where: { OR: [{ stripeId: string }, { title: string }] } }): Promise<Pick<SubscriptionProduct, "id"> | null>;
|
||||
findFirst(args: { where: { OR: [{ billingProviderId: 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">>;
|
||||
};
|
||||
@@ -53,9 +72,16 @@ export type EntitlementsSeedSubscriptionFeatureClient = {
|
||||
create(args: { data: SubscriptionFeatureCreateInput & { subscriptionProductId: string } }): Promise<SubscriptionFeature>;
|
||||
};
|
||||
|
||||
export type EntitlementsSeedSubscriptionPriceClient = {
|
||||
findFirst(args: { where: { subscriptionProductId: string; currency: string; billingPeriod: number } }): Promise<Pick<SubscriptionPrice, "id"> | null>;
|
||||
create(args: { data: SubscriptionPriceCreateInput }): Promise<SubscriptionPrice>;
|
||||
update(args: { where: { id: string }; data: SubscriptionPriceUpdateInput }): Promise<SubscriptionPrice>;
|
||||
};
|
||||
|
||||
export type EntitlementsSeedClient = {
|
||||
subscriptionProduct: EntitlementsSeedSubscriptionProductClient;
|
||||
subscriptionFeature: EntitlementsSeedSubscriptionFeatureClient;
|
||||
subscriptionPrice: EntitlementsSeedSubscriptionPriceClient;
|
||||
};
|
||||
|
||||
export type SeedStandardEntitlementsOptions = {
|
||||
@@ -70,6 +96,8 @@ function getInitialResult(plans: readonly EntitlementPlanStub[]): EntitlementsSe
|
||||
featureCount: plans.reduce((total, plan) => total + plan.features.length, 0),
|
||||
createdProducts: 0,
|
||||
updatedProducts: 0,
|
||||
createdPrices: 0,
|
||||
updatedPrices: 0,
|
||||
deletedFeatures: 0,
|
||||
createdFeatures: 0,
|
||||
};
|
||||
@@ -82,6 +110,8 @@ function diagnosticFromResult(phase: EntitlementsSeedPhase, result: Entitlements
|
||||
featureCount: result.featureCount,
|
||||
createdProducts: result.createdProducts,
|
||||
updatedProducts: result.updatedProducts,
|
||||
createdPrices: result.createdPrices,
|
||||
updatedPrices: result.updatedPrices,
|
||||
deletedFeatures: result.deletedFeatures,
|
||||
createdFeatures: result.createdFeatures,
|
||||
...(planId ? { planId } : {}),
|
||||
@@ -92,13 +122,15 @@ async function emitDiagnostic(diagnostics: EntitlementsSeedDiagnostics | undefin
|
||||
await diagnostics?.(event);
|
||||
}
|
||||
|
||||
export function getEntitlementPlanStripeId(plan: Pick<EntitlementPlanStub, "id">): string {
|
||||
return `${SEEDED_STRIPE_ID_PREFIX}_${plan.id}`;
|
||||
export function getEntitlementPlanBillingProviderId(plan: Pick<EntitlementPlanStub, "id">): string {
|
||||
return `${SEEDED_BILLING_PROVIDER_ID_PREFIX}_${plan.id}`;
|
||||
}
|
||||
|
||||
function mapPlanToProductCreateInput(plan: EntitlementPlanStub): SubscriptionProductCreateInput {
|
||||
return {
|
||||
stripeId: getEntitlementPlanStripeId(plan),
|
||||
billingProviderId: getEntitlementPlanBillingProviderId(plan),
|
||||
code: plan.id,
|
||||
lagoPlanCode: plan.id,
|
||||
order: plan.metadata.sortOrder,
|
||||
title: plan.metadata.publicName,
|
||||
model: 0,
|
||||
@@ -117,7 +149,9 @@ function mapPlanToProductCreateInput(plan: EntitlementPlanStub): SubscriptionPro
|
||||
function mapPlanToProductUpdateInput(plan: EntitlementPlanStub): SubscriptionProductUpdateInput {
|
||||
const product = mapPlanToProductCreateInput(plan);
|
||||
return {
|
||||
stripeId: product.stripeId,
|
||||
billingProviderId: product.billingProviderId,
|
||||
code: product.code,
|
||||
lagoPlanCode: product.lagoPlanCode,
|
||||
order: product.order,
|
||||
title: product.title,
|
||||
model: product.model,
|
||||
@@ -132,6 +166,60 @@ function mapPlanToProductUpdateInput(plan: EntitlementPlanStub): SubscriptionPro
|
||||
};
|
||||
}
|
||||
|
||||
function getPriceBillingProviderId(plan: Pick<EntitlementPlanStub, "id">, billingPeriod: number): string {
|
||||
return `${SEEDED_PRICE_PROVIDER_ID_PREFIX}_${plan.id}_${billingPeriod === BILLING_PERIOD_YEARLY ? "yearly" : "monthly"}`;
|
||||
}
|
||||
|
||||
function getLagoFeeCode(plan: Pick<EntitlementPlanStub, "id">, billingPeriod: number): string {
|
||||
return `${plan.id}_${billingPeriod === BILLING_PERIOD_YEARLY ? "yearly" : "monthly"}`;
|
||||
}
|
||||
|
||||
function mapPlanPriceToInput(plan: EntitlementPlanStub, subscriptionProductId: string, billingPeriod: number, price: string): SubscriptionPriceCreateInput {
|
||||
const billingProviderId = getPriceBillingProviderId(plan, billingPeriod);
|
||||
return {
|
||||
subscriptionProductId,
|
||||
billingProviderId,
|
||||
lagoFeeCode: getLagoFeeCode(plan, billingPeriod),
|
||||
molliePriceReference: billingProviderId,
|
||||
type: PRICE_TYPE_RECURRING,
|
||||
billingPeriod,
|
||||
price,
|
||||
currency: "eur",
|
||||
trialDays: 0,
|
||||
active: true,
|
||||
};
|
||||
}
|
||||
|
||||
async function seedPlanPrice(client: EntitlementsSeedClient, plan: EntitlementPlanStub, productId: string, billingPeriod: number, price: string) {
|
||||
const priceData = mapPlanPriceToInput(plan, productId, billingPeriod, price);
|
||||
const existingPrice = await client.subscriptionPrice.findFirst({
|
||||
where: {
|
||||
subscriptionProductId: productId,
|
||||
currency: priceData.currency,
|
||||
billingPeriod: priceData.billingPeriod,
|
||||
},
|
||||
});
|
||||
|
||||
if (existingPrice) {
|
||||
await client.subscriptionPrice.update({
|
||||
where: { id: existingPrice.id },
|
||||
data: {
|
||||
billingProviderId: priceData.billingProviderId,
|
||||
lagoFeeCode: priceData.lagoFeeCode,
|
||||
molliePriceReference: priceData.molliePriceReference,
|
||||
type: priceData.type,
|
||||
price: priceData.price,
|
||||
trialDays: priceData.trialDays,
|
||||
active: priceData.active,
|
||||
},
|
||||
});
|
||||
return { createdPrices: 0, updatedPrices: 1 };
|
||||
}
|
||||
|
||||
await client.subscriptionPrice.create({ data: priceData });
|
||||
return { createdPrices: 1, updatedPrices: 0 };
|
||||
}
|
||||
|
||||
function getFeatureValue(limitType: EntitlementLimitType, limit: number | null): number {
|
||||
return limit ?? limitType;
|
||||
}
|
||||
@@ -179,7 +267,7 @@ export function redactSeedError(error: unknown): { name: string; message: string
|
||||
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 }] },
|
||||
where: { OR: [{ billingProviderId: productData.billingProviderId }, { title: productData.title }] },
|
||||
});
|
||||
|
||||
const product = existingProduct
|
||||
@@ -190,6 +278,16 @@ async function seedOnePlan(client: EntitlementsSeedClient, plan: EntitlementPlan
|
||||
: await client.subscriptionProduct.create({ data: productData });
|
||||
|
||||
const deletedFeatures = await client.subscriptionFeature.deleteMany({ where: { subscriptionProductId: product.id } });
|
||||
let createdPrices = 0;
|
||||
let updatedPrices = 0;
|
||||
const standardPrices = STANDARD_PLAN_PRICES_EUR[plan.id];
|
||||
if (standardPrices) {
|
||||
const monthly = await seedPlanPrice(client, plan, product.id, BILLING_PERIOD_MONTHLY, standardPrices.monthly);
|
||||
const yearly = await seedPlanPrice(client, plan, product.id, BILLING_PERIOD_YEARLY, standardPrices.yearly);
|
||||
createdPrices += monthly.createdPrices + yearly.createdPrices;
|
||||
updatedPrices += monthly.updatedPrices + yearly.updatedPrices;
|
||||
}
|
||||
|
||||
for (const feature of plan.features) {
|
||||
await client.subscriptionFeature.create({
|
||||
data: {
|
||||
@@ -202,6 +300,8 @@ async function seedOnePlan(client: EntitlementsSeedClient, plan: EntitlementPlan
|
||||
return {
|
||||
createdProducts: existingProduct ? 0 : 1,
|
||||
updatedProducts: existingProduct ? 1 : 0,
|
||||
createdPrices,
|
||||
updatedPrices,
|
||||
deletedFeatures: deletedFeatures.count,
|
||||
createdFeatures: plan.features.length,
|
||||
};
|
||||
@@ -220,6 +320,8 @@ export async function seedStandardEntitlements({
|
||||
const planResult = await seedOnePlan(client, plan);
|
||||
result.createdProducts += planResult.createdProducts;
|
||||
result.updatedProducts += planResult.updatedProducts;
|
||||
result.createdPrices += planResult.createdPrices;
|
||||
result.updatedPrices += planResult.updatedPrices;
|
||||
result.deletedFeatures += planResult.deletedFeatures;
|
||||
result.createdFeatures += planResult.createdFeatures;
|
||||
await emitDiagnostic(diagnostics, diagnosticFromResult("plan-seeded", result, plan.id));
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("./client.server.js", () => ({ getDbClient: vi.fn() }));
|
||||
|
||||
import { getDbClient } from "./client.server.js";
|
||||
import { createLegacyEvent, type LegacyEventWriterClient } from "./events.server.js";
|
||||
|
||||
function createWriterClient(created: Record<string, unknown> = { id: "event_1" }): LegacyEventWriterClient {
|
||||
return {
|
||||
event: {
|
||||
create: vi.fn().mockResolvedValue(created as never),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("createLegacyEvent", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("persists the legacy event payload through the injected writer client", async () => {
|
||||
const client = createWriterClient({ id: "event_42" });
|
||||
const data = {
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
name: "lead.created",
|
||||
data: '{"leadId":"lead_1"}',
|
||||
description: "Lead created via import",
|
||||
};
|
||||
|
||||
const result = await createLegacyEvent(data, client);
|
||||
|
||||
expect(result).toEqual({ id: "event_42" });
|
||||
expect(client.event.create).toHaveBeenCalledWith({ data });
|
||||
});
|
||||
|
||||
it("passes nullable tenant/user/description through untouched", async () => {
|
||||
const client = createWriterClient();
|
||||
const data = {
|
||||
tenantId: null,
|
||||
userId: null,
|
||||
name: "system.boot",
|
||||
data: "{}",
|
||||
description: null,
|
||||
};
|
||||
|
||||
await createLegacyEvent(data, client);
|
||||
|
||||
expect(client.event.create).toHaveBeenCalledWith({ data });
|
||||
});
|
||||
|
||||
it("defaults to the package db client when no writer is supplied", async () => {
|
||||
const client = createWriterClient({ id: "event_default" });
|
||||
vi.mocked(getDbClient).mockReturnValue(client as never);
|
||||
|
||||
const result = await createLegacyEvent({
|
||||
tenantId: "tenant_2",
|
||||
userId: "user_2",
|
||||
name: "auth.login",
|
||||
data: "{}",
|
||||
description: null,
|
||||
});
|
||||
|
||||
expect(getDbClient).toHaveBeenCalledTimes(1);
|
||||
expect(result).toEqual({ id: "event_default" });
|
||||
});
|
||||
});
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { serializeImpersonationAuditMetadata } from "./impersonation-audit.server.js";
|
||||
|
||||
describe("serializeImpersonationAuditMetadata value normalization", () => {
|
||||
it("stringifies scalar values (number, boolean, bigint)", () => {
|
||||
const serialized = serializeImpersonationAuditMetadata({
|
||||
attempts: 3,
|
||||
blocked: true,
|
||||
sequence: 9007199254740993n,
|
||||
});
|
||||
|
||||
expect(serialized).toBe(JSON.stringify({ attempts: "3", blocked: "true", sequence: "9007199254740993" }));
|
||||
});
|
||||
|
||||
it("serializes Date values as ISO-8601 strings", () => {
|
||||
const serialized = serializeImpersonationAuditMetadata({
|
||||
occurredAt: new Date("2026-06-25T08:30:00.000Z"),
|
||||
});
|
||||
|
||||
expect(serialized).toBe(JSON.stringify({ occurredAt: "2026-06-25T08:30:00.000Z" }));
|
||||
});
|
||||
|
||||
it("drops null and undefined values because they normalize to empty strings", () => {
|
||||
const serialized = serializeImpersonationAuditMetadata({
|
||||
ip: "127.0.0.1",
|
||||
reason: null,
|
||||
note: undefined,
|
||||
});
|
||||
|
||||
expect(serialized).toBe(JSON.stringify({ ip: "127.0.0.1" }));
|
||||
});
|
||||
|
||||
it("returns null when every value normalizes away to empty", () => {
|
||||
expect(serializeImpersonationAuditMetadata({ reason: null, note: undefined })).toBeNull();
|
||||
});
|
||||
|
||||
it("falsey-but-meaningful scalars survive normalization", () => {
|
||||
// 0 and false stringify to non-empty values, so they must be retained.
|
||||
const serialized = serializeImpersonationAuditMetadata({ count: 0, enabled: false });
|
||||
|
||||
expect(serialized).toBe(JSON.stringify({ count: "0", enabled: "false" }));
|
||||
});
|
||||
});
|
||||
@@ -3,30 +3,24 @@ 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", () => {
|
||||
describe("@hivegrid/db boundary metadata", () => {
|
||||
it("documents the current Prisma ownership boundary", () => {
|
||||
expect(getDatabaseBoundary()).toBe(databaseBoundary);
|
||||
expect(databaseBoundary).toMatchObject({
|
||||
packageName: "@toolctrl/db",
|
||||
packageName: "@hivegrid/db",
|
||||
orm: "prisma",
|
||||
schemaPath: PRISMA_SCHEMA_PATH,
|
||||
migrationsPath: PRISMA_MIGRATIONS_PATH,
|
||||
generatedClientPath: PRISMA_GENERATED_CLIENT_PATH,
|
||||
serverClientEntrypoint: "@toolctrl/db/client.server",
|
||||
serverClientEntrypoint: "@hivegrid/db/client.server",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -51,39 +45,14 @@ describe("@toolctrl/db boundary metadata", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("exposes the tenant settings boundary from the package root", () => {
|
||||
it("exposes the audit + idempotency 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");
|
||||
const auditBoundary = await import("@hivegrid/db/audit-events.server");
|
||||
const idempotencyBoundary = await import("@hivegrid/db/idempotency-keys.server");
|
||||
|
||||
expect(auditBoundary.createAuditEvent).toBe(createAuditEvent);
|
||||
expect(idempotencyBoundary.createStoredIdempotencyResponse).toBe(
|
||||
|
||||
@@ -4,6 +4,8 @@ export { PRISMA_GENERATED_CLIENT_PATH, PRISMA_MIGRATIONS_PATH, PRISMA_SCHEMA_PAT
|
||||
export type { PrismaOwnershipMetadata } from "./prisma.js";
|
||||
export * from "./auth-boundary.server.js";
|
||||
export * from "./audit-events.server.js";
|
||||
export * from "./billing-domain.server.js";
|
||||
export * from "./billing-sync.server.js";
|
||||
export * from "./export-jobs.server.js";
|
||||
export * from "./idempotency-keys.server.js";
|
||||
export * from "./import-jobs.server.js";
|
||||
@@ -14,26 +16,25 @@ 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";
|
||||
packageName: "@hivegrid/db";
|
||||
orm: "prisma";
|
||||
schemaPath: typeof PRISMA_SCHEMA_PATH;
|
||||
migrationsPath: typeof PRISMA_MIGRATIONS_PATH;
|
||||
generatedClientPath: typeof PRISMA_GENERATED_CLIENT_PATH;
|
||||
serverClientEntrypoint: "@toolctrl/db/client.server";
|
||||
serverClientEntrypoint: "@hivegrid/db/client.server";
|
||||
};
|
||||
|
||||
export const databaseBoundary: DatabaseBoundary = Object.freeze({
|
||||
packageName: "@toolctrl/db",
|
||||
packageName: "@hivegrid/db",
|
||||
orm: "prisma",
|
||||
schemaPath: PRISMA_SCHEMA_PATH,
|
||||
migrationsPath: PRISMA_MIGRATIONS_PATH,
|
||||
generatedClientPath: PRISMA_GENERATED_CLIENT_PATH,
|
||||
serverClientEntrypoint: "@toolctrl/db/client.server",
|
||||
serverClientEntrypoint: "@hivegrid/db/client.server",
|
||||
});
|
||||
|
||||
export function getDatabaseBoundary(): DatabaseBoundary {
|
||||
|
||||
@@ -2,123 +2,14 @@ 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({
|
||||
@@ -180,7 +71,6 @@ describe("admin audit log list filters", () => {
|
||||
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,
|
||||
@@ -245,7 +135,6 @@ describe("tenant audit log list filters", () => {
|
||||
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,
|
||||
@@ -272,7 +161,6 @@ describe("tenant audit log list filters", () => {
|
||||
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,
|
||||
@@ -294,7 +182,6 @@ describe("serializeAdminAuditLogsCsv", () => {
|
||||
tenant: null,
|
||||
user: null,
|
||||
apiKey: null,
|
||||
comment: null,
|
||||
details: null,
|
||||
}),
|
||||
]),
|
||||
@@ -341,15 +228,12 @@ function makeAuditRow(overrides: Partial<AdminAuditLogRow> = {}): AdminAuditLogR
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -1,44 +1,5 @@
|
||||
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>;
|
||||
};
|
||||
};
|
||||
import type { Log, Prisma } from "./prisma-browser.js";
|
||||
|
||||
export type AdminAuditLogFilters = {
|
||||
q?: string | null;
|
||||
@@ -68,7 +29,6 @@ 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 = {
|
||||
@@ -95,7 +55,6 @@ 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;
|
||||
@@ -177,29 +136,6 @@ export function serializeAdminAuditLogsCsv(rows: readonly AdminAuditLogRow[]): s
|
||||
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 },
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
|
||||
import { getDbClient } from "./client.server.js";
|
||||
import type { Prisma } from "./prisma-browser.js";
|
||||
|
||||
const DEFAULT_TOKEN_HASH_SECRET = "mcp-oauth-token-hash-v1";
|
||||
const CLIENT_ID_PREFIX = "hgomc_";
|
||||
const AUTH_CODE_PREFIX = "hgoc_";
|
||||
const ACCESS_TOKEN_PREFIX = "hgoa_";
|
||||
const REFRESH_TOKEN_PREFIX = "hgor_";
|
||||
const ACCESS_TOKEN_TTL_MS = 60 * 60 * 1000;
|
||||
const REFRESH_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
||||
const AUTH_CODE_TTL_MS = 10 * 60 * 1000;
|
||||
|
||||
export type McpOAuthClientSummary = {
|
||||
id: string;
|
||||
clientId: string;
|
||||
clientName: string;
|
||||
redirectUris: string[];
|
||||
scopes: string[];
|
||||
active: boolean;
|
||||
};
|
||||
|
||||
export type McpOAuthAuthorizationCodeInput = {
|
||||
clientId: string;
|
||||
userId: string;
|
||||
tenantId: string;
|
||||
tenantSlug: string;
|
||||
redirectUri: string;
|
||||
scopes: readonly string[];
|
||||
resource: string;
|
||||
codeChallenge: string;
|
||||
codeChallengeMethod: "S256";
|
||||
secret: string | undefined | null;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
export type McpOAuthConsumedAuthorizationCode = {
|
||||
id: string;
|
||||
client: McpOAuthClientSummary;
|
||||
userId: string;
|
||||
tenantId: string;
|
||||
tenantSlug: string;
|
||||
redirectUri: string;
|
||||
scopes: string[];
|
||||
resource: string;
|
||||
codeChallenge: string;
|
||||
codeChallengeMethod: string;
|
||||
};
|
||||
|
||||
export type McpOAuthTokenPairInput = {
|
||||
clientId: string;
|
||||
userId: string;
|
||||
tenantId: string;
|
||||
tenantSlug: string;
|
||||
scopes: readonly string[];
|
||||
resource: string;
|
||||
secret: string | undefined | null;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
export type McpOAuthTokenPair = {
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
accessTokenExpiresIn: number;
|
||||
refreshTokenExpiresAt: Date;
|
||||
};
|
||||
|
||||
export type McpOAuthAccessTokenPrincipal = {
|
||||
id: string;
|
||||
clientId: string;
|
||||
clientName: string;
|
||||
userId: string;
|
||||
tenantId: string;
|
||||
tenantSlug: string;
|
||||
scopes: string[];
|
||||
resource: string;
|
||||
expiresAt: Date;
|
||||
};
|
||||
|
||||
export type McpOAuthRefreshTokenRecord = {
|
||||
id: string;
|
||||
client: McpOAuthClientSummary;
|
||||
userId: string;
|
||||
tenantId: string;
|
||||
tenantSlug: string;
|
||||
scopes: string[];
|
||||
resource: string;
|
||||
expiresAt: Date;
|
||||
};
|
||||
|
||||
export function normalizeMcpOAuthTokenHashSecret(secret: string | undefined | null): string {
|
||||
const normalized = secret?.trim();
|
||||
return normalized || DEFAULT_TOKEN_HASH_SECRET;
|
||||
}
|
||||
|
||||
export function hashMcpOAuthToken(token: string, secret: string | undefined | null): string {
|
||||
return createHmac("sha256", normalizeMcpOAuthTokenHashSecret(secret)).update(token).digest("hex");
|
||||
}
|
||||
|
||||
export function verifyMcpOAuthPkceS256(codeVerifier: string, expectedChallenge: string): boolean {
|
||||
const challenge = createHashBase64Url(codeVerifier);
|
||||
return timingSafeStringEqual(challenge, expectedChallenge);
|
||||
}
|
||||
|
||||
export async function registerMcpOAuthClient(input: {
|
||||
clientName: string;
|
||||
redirectUris: readonly string[];
|
||||
scopes: readonly string[];
|
||||
grantTypes?: readonly string[];
|
||||
contacts?: readonly string[];
|
||||
metadata?: Prisma.InputJsonValue;
|
||||
}): Promise<McpOAuthClientSummary> {
|
||||
const client = await getDbClient().mcpOAuthClient.create({
|
||||
data: {
|
||||
clientId: `${CLIENT_ID_PREFIX}${randomToken(24)}`,
|
||||
clientName: input.clientName,
|
||||
redirectUris: [...input.redirectUris] as Prisma.InputJsonArray,
|
||||
scopes: [...input.scopes] as Prisma.InputJsonArray,
|
||||
grantTypes: [...(input.grantTypes ?? ["authorization_code", "refresh_token"])] as Prisma.InputJsonArray,
|
||||
contacts: input.contacts ? ([...input.contacts] as Prisma.InputJsonArray) : undefined,
|
||||
metadata: input.metadata,
|
||||
},
|
||||
});
|
||||
return toClientSummary(client);
|
||||
}
|
||||
|
||||
export async function findMcpOAuthClient(clientId: string): Promise<McpOAuthClientSummary | null> {
|
||||
const client = await getDbClient().mcpOAuthClient.findUnique({ where: { clientId } });
|
||||
return client ? toClientSummary(client) : null;
|
||||
}
|
||||
|
||||
export async function createMcpOAuthAuthorizationCode(input: McpOAuthAuthorizationCodeInput): Promise<{ code: string; expiresAt: Date }> {
|
||||
const now = input.now ?? new Date();
|
||||
const code = `${AUTH_CODE_PREFIX}${randomToken(32)}`;
|
||||
const expiresAt = new Date(now.getTime() + AUTH_CODE_TTL_MS);
|
||||
await getDbClient().mcpOAuthAuthorizationCode.create({
|
||||
data: {
|
||||
clientId: input.clientId,
|
||||
userId: input.userId,
|
||||
tenantId: input.tenantId,
|
||||
tenantSlug: input.tenantSlug,
|
||||
codeHash: hashMcpOAuthToken(code, input.secret),
|
||||
redirectUri: input.redirectUri,
|
||||
scopes: [...input.scopes] as Prisma.InputJsonArray,
|
||||
resource: input.resource,
|
||||
codeChallenge: input.codeChallenge,
|
||||
codeChallengeMethod: input.codeChallengeMethod,
|
||||
expiresAt,
|
||||
},
|
||||
});
|
||||
return { code, expiresAt };
|
||||
}
|
||||
|
||||
export async function consumeMcpOAuthAuthorizationCode(
|
||||
code: string,
|
||||
secret: string | undefined | null,
|
||||
now = new Date(),
|
||||
): Promise<McpOAuthConsumedAuthorizationCode | null> {
|
||||
const db = getDbClient();
|
||||
const codeHash = hashMcpOAuthToken(code, secret);
|
||||
const row = await db.mcpOAuthAuthorizationCode.findUnique({
|
||||
where: { codeHash },
|
||||
include: { client: true },
|
||||
});
|
||||
if (!row || row.consumedAt || row.expiresAt.getTime() <= now.getTime() || !row.client.active) {
|
||||
return null;
|
||||
}
|
||||
const update = await db.mcpOAuthAuthorizationCode.updateMany({
|
||||
where: { id: row.id, consumedAt: null, expiresAt: { gt: now } },
|
||||
data: { consumedAt: now },
|
||||
});
|
||||
if (update.count !== 1) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
id: row.id,
|
||||
client: toClientSummary(row.client),
|
||||
userId: row.userId,
|
||||
tenantId: row.tenantId,
|
||||
tenantSlug: row.tenantSlug,
|
||||
redirectUri: row.redirectUri,
|
||||
scopes: normalizeStringArray(row.scopes),
|
||||
resource: row.resource,
|
||||
codeChallenge: row.codeChallenge,
|
||||
codeChallengeMethod: row.codeChallengeMethod,
|
||||
};
|
||||
}
|
||||
|
||||
export async function issueMcpOAuthTokenPair(input: McpOAuthTokenPairInput): Promise<McpOAuthTokenPair> {
|
||||
const now = input.now ?? new Date();
|
||||
const accessToken = `${ACCESS_TOKEN_PREFIX}${randomToken(32)}`;
|
||||
const refreshToken = `${REFRESH_TOKEN_PREFIX}${randomToken(40)}`;
|
||||
const accessTokenExpiresAt = new Date(now.getTime() + ACCESS_TOKEN_TTL_MS);
|
||||
const refreshTokenExpiresAt = new Date(now.getTime() + REFRESH_TOKEN_TTL_MS);
|
||||
const db = getDbClient();
|
||||
const refreshRow = await db.mcpOAuthRefreshToken.create({
|
||||
data: {
|
||||
clientId: input.clientId,
|
||||
userId: input.userId,
|
||||
tenantId: input.tenantId,
|
||||
tenantSlug: input.tenantSlug,
|
||||
tokenHash: hashMcpOAuthToken(refreshToken, input.secret),
|
||||
scopes: [...input.scopes] as Prisma.InputJsonArray,
|
||||
resource: input.resource,
|
||||
expiresAt: refreshTokenExpiresAt,
|
||||
},
|
||||
});
|
||||
await db.mcpOAuthAccessToken.create({
|
||||
data: {
|
||||
clientId: input.clientId,
|
||||
userId: input.userId,
|
||||
tenantId: input.tenantId,
|
||||
tenantSlug: input.tenantSlug,
|
||||
tokenHash: hashMcpOAuthToken(accessToken, input.secret),
|
||||
scopes: [...input.scopes] as Prisma.InputJsonArray,
|
||||
resource: input.resource,
|
||||
expiresAt: accessTokenExpiresAt,
|
||||
refreshTokenId: refreshRow.id,
|
||||
},
|
||||
});
|
||||
return {
|
||||
accessToken,
|
||||
refreshToken,
|
||||
accessTokenExpiresIn: Math.floor((accessTokenExpiresAt.getTime() - now.getTime()) / 1000),
|
||||
refreshTokenExpiresAt,
|
||||
};
|
||||
}
|
||||
|
||||
export async function consumeMcpOAuthRefreshToken(
|
||||
token: string,
|
||||
secret: string | undefined | null,
|
||||
now = new Date(),
|
||||
): Promise<McpOAuthRefreshTokenRecord | null> {
|
||||
const db = getDbClient();
|
||||
const tokenHash = hashMcpOAuthToken(token, secret);
|
||||
const row = await db.mcpOAuthRefreshToken.findUnique({ where: { tokenHash }, include: { client: true } });
|
||||
if (!row || row.revokedAt || row.rotatedAt || row.expiresAt.getTime() <= now.getTime() || !row.client.active) {
|
||||
return null;
|
||||
}
|
||||
const update = await db.mcpOAuthRefreshToken.updateMany({
|
||||
where: { id: row.id, revokedAt: null, rotatedAt: null, expiresAt: { gt: now } },
|
||||
data: { rotatedAt: now },
|
||||
});
|
||||
if (update.count !== 1) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
id: row.id,
|
||||
client: toClientSummary(row.client),
|
||||
userId: row.userId,
|
||||
tenantId: row.tenantId,
|
||||
tenantSlug: row.tenantSlug,
|
||||
scopes: normalizeStringArray(row.scopes),
|
||||
resource: row.resource,
|
||||
expiresAt: row.expiresAt,
|
||||
};
|
||||
}
|
||||
|
||||
export async function findActiveMcpOAuthAccessToken(
|
||||
token: string,
|
||||
secret: string | undefined | null,
|
||||
now = new Date(),
|
||||
): Promise<McpOAuthAccessTokenPrincipal | null> {
|
||||
const row = await getDbClient().mcpOAuthAccessToken.findUnique({
|
||||
where: { tokenHash: hashMcpOAuthToken(token, secret) },
|
||||
include: { client: true },
|
||||
});
|
||||
if (!row || row.revokedAt || row.expiresAt.getTime() <= now.getTime() || !row.client.active) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
id: row.id,
|
||||
clientId: row.client.clientId,
|
||||
clientName: row.client.clientName,
|
||||
userId: row.userId,
|
||||
tenantId: row.tenantId,
|
||||
tenantSlug: row.tenantSlug,
|
||||
scopes: normalizeStringArray(row.scopes),
|
||||
resource: row.resource,
|
||||
expiresAt: row.expiresAt,
|
||||
};
|
||||
}
|
||||
|
||||
export async function revokeMcpOAuthToken(token: string, secret: string | undefined | null, now = new Date()): Promise<boolean> {
|
||||
const tokenHash = hashMcpOAuthToken(token, secret);
|
||||
const db = getDbClient();
|
||||
const [access, refresh] = await Promise.all([
|
||||
db.mcpOAuthAccessToken.updateMany({ where: { tokenHash, revokedAt: null }, data: { revokedAt: now } }),
|
||||
db.mcpOAuthRefreshToken.updateMany({ where: { tokenHash, revokedAt: null }, data: { revokedAt: now } }),
|
||||
]);
|
||||
return access.count + refresh.count > 0;
|
||||
}
|
||||
|
||||
function toClientSummary(client: {
|
||||
id: string;
|
||||
clientId: string;
|
||||
clientName: string;
|
||||
redirectUris: Prisma.JsonValue;
|
||||
scopes: Prisma.JsonValue;
|
||||
active: boolean;
|
||||
}): McpOAuthClientSummary {
|
||||
return {
|
||||
id: client.id,
|
||||
clientId: client.clientId,
|
||||
clientName: client.clientName,
|
||||
redirectUris: normalizeStringArray(client.redirectUris),
|
||||
scopes: normalizeStringArray(client.scopes),
|
||||
active: client.active,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeStringArray(value: unknown): string[] {
|
||||
return Array.isArray(value) ? value.filter((item): item is string => typeof item === "string" && item.length > 0) : [];
|
||||
}
|
||||
|
||||
function randomToken(bytes: number): string {
|
||||
return randomBytes(bytes).toString("base64url");
|
||||
}
|
||||
|
||||
function createHashBase64Url(value: string): string {
|
||||
return createHash("sha256").update(value).digest().toString("base64url");
|
||||
}
|
||||
|
||||
function timingSafeStringEqual(left: string, right: string): boolean {
|
||||
const leftBuffer = Buffer.from(left);
|
||||
const rightBuffer = Buffer.from(right);
|
||||
return leftBuffer.length === rightBuffer.length && timingSafeEqual(leftBuffer, rightBuffer);
|
||||
}
|
||||
+79
-2
@@ -5,6 +5,7 @@ import {
|
||||
getNotificationDeliveryDiagnostics,
|
||||
getNotificationStreamSnapshot,
|
||||
getUserNotificationPreferences,
|
||||
markAllInAppNotificationDeliveriesRead,
|
||||
markInAppNotificationDeliveryRead,
|
||||
markNotificationDeliveryStatus,
|
||||
NOTIFICATION_DELIVERY_LAST_ERROR_MAX_LENGTH,
|
||||
@@ -398,6 +399,46 @@ describe("notification delivery boundary", () => {
|
||||
).rejects.toThrow("Notification delivery read scope did not match exactly one delivery.");
|
||||
});
|
||||
|
||||
it("bulk-clears every unread in-app delivery within the current tenant/user scope", async () => {
|
||||
const client = createNotificationsClient();
|
||||
vi.mocked(client.notificationDelivery.updateMany).mockResolvedValueOnce({ count: 3 });
|
||||
const readAt = new Date("2026-05-08T13:00:00.000Z");
|
||||
|
||||
const cleared = await markAllInAppNotificationDeliveriesRead(
|
||||
{
|
||||
tenantId: " tenant_1 ",
|
||||
userId: " user_1 ",
|
||||
readAt,
|
||||
},
|
||||
client,
|
||||
);
|
||||
|
||||
expect(client.notificationDelivery.updateMany).toHaveBeenCalledWith({
|
||||
where: { tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", status: "SENT" },
|
||||
data: { status: "READ", readAt },
|
||||
});
|
||||
expect(cleared).toBe(3);
|
||||
});
|
||||
|
||||
it("tolerates a bulk clear that matches no unread deliveries", async () => {
|
||||
const client = createNotificationsClient();
|
||||
vi.mocked(client.notificationDelivery.updateMany).mockResolvedValueOnce({ count: 0 });
|
||||
|
||||
await expect(
|
||||
markAllInAppNotificationDeliveriesRead({ tenantId: "tenant_1", userId: "user_1" }, client),
|
||||
).resolves.toBe(0);
|
||||
});
|
||||
|
||||
it("rejects a bulk clear without tenant or user scope before writing", async () => {
|
||||
const client = createNotificationsClient();
|
||||
|
||||
await expect(
|
||||
markAllInAppNotificationDeliveriesRead({ tenantId: " ", userId: "user_1" }, client),
|
||||
).rejects.toThrow("Notification delivery bulk read scope is required.");
|
||||
|
||||
expect(client.notificationDelivery.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("queries newest-first diagnostics with indexed tenant/user/status/channel/category filters", async () => {
|
||||
const client = createNotificationsClient();
|
||||
|
||||
@@ -566,6 +607,8 @@ describe("notification stream snapshot boundary", () => {
|
||||
updatedAt: "2026-05-08T12:05:00.000Z",
|
||||
sentAt: "2026-05-08T12:01:00.000Z",
|
||||
readAt: "2026-05-08T12:06:00.000Z",
|
||||
deeplink: null,
|
||||
lastError: null,
|
||||
},
|
||||
{
|
||||
id: "delivery_1",
|
||||
@@ -581,6 +624,8 @@ describe("notification stream snapshot boundary", () => {
|
||||
updatedAt: "2026-05-08T11:05:00.000Z",
|
||||
sentAt: null,
|
||||
readAt: null,
|
||||
deeplink: null,
|
||||
lastError: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -733,17 +778,21 @@ describe("notification stream snapshot boundary", () => {
|
||||
sentAt: null,
|
||||
readAt: null,
|
||||
providerMessageId: "provider-secret-id",
|
||||
payloadMetadata: { token: "secret-token", body: "raw-body" },
|
||||
payloadMetadata: { token: "secret-token", body: "raw-body", deeplink: "/acme/announcements/a1" },
|
||||
authorization: "Bearer secret-token",
|
||||
body: "raw-body",
|
||||
headers: { cookie: "secret" },
|
||||
unknownField: "do-not-serialize",
|
||||
lastError: "token=secret-token failed",
|
||||
},
|
||||
]);
|
||||
|
||||
const snapshot = await getNotificationStreamSnapshot({ tenantId: "tenant_1", userId: "user_1" }, client);
|
||||
const serialized = JSON.stringify(snapshot);
|
||||
|
||||
// AK-P3 DoD 4: only the validated app-relative deeplink scalar and the
|
||||
// redacted error ride along — payloadMetadata itself never enters the
|
||||
// stream, and secrets must never appear serialized.
|
||||
expect(snapshot.items[0]).toEqual({
|
||||
id: "delivery_1",
|
||||
cursor: "2026-05-08T12:01:00.000Z:delivery_1",
|
||||
@@ -758,6 +807,8 @@ describe("notification stream snapshot boundary", () => {
|
||||
updatedAt: "2026-05-08T12:01:00.000Z",
|
||||
sentAt: null,
|
||||
readAt: null,
|
||||
deeplink: "/acme/announcements/a1",
|
||||
lastError: "token=[redacted] failed",
|
||||
});
|
||||
expect(serialized).not.toContain("provider-secret-id");
|
||||
expect(serialized).not.toContain("secret-token");
|
||||
@@ -765,6 +816,32 @@ describe("notification stream snapshot boundary", () => {
|
||||
expect(serialized).not.toContain("unknownField");
|
||||
expect(serialized).not.toContain("payloadMetadata");
|
||||
});
|
||||
|
||||
it("drops unsafe deeplink candidates from the stream", async () => {
|
||||
const client = createNotificationsClient();
|
||||
vi.mocked(client.notificationDelivery.findMany).mockResolvedValue([
|
||||
{
|
||||
id: "delivery_evil",
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
channel: "IN_APP",
|
||||
category: "default",
|
||||
messageKey: "announcement.created",
|
||||
status: "SENT",
|
||||
attemptsMade: 1,
|
||||
createdAt: new Date("2026-05-08T12:00:00.000Z"),
|
||||
updatedAt: new Date("2026-05-08T12:01:00.000Z"),
|
||||
sentAt: null,
|
||||
readAt: null,
|
||||
payloadMetadata: { deeplink: "https://evil.example/phish" },
|
||||
},
|
||||
]);
|
||||
|
||||
const snapshot = await getNotificationStreamSnapshot({ tenantId: "tenant_1", userId: "user_1" }, client);
|
||||
|
||||
expect(snapshot.items[0]?.deeplink).toBeNull();
|
||||
expect(JSON.stringify(snapshot)).not.toContain("evil.example");
|
||||
});
|
||||
});
|
||||
|
||||
describe("notification package exports", () => {
|
||||
@@ -785,7 +862,7 @@ describe("notification package exports", () => {
|
||||
});
|
||||
|
||||
it("exposes the notification boundary subpath export", async () => {
|
||||
const notificationBoundary = await import("@toolctrl/db/notifications.server");
|
||||
const notificationBoundary = await import("@hivegrid/db/notifications.server");
|
||||
|
||||
expect(notificationBoundary).toEqual(
|
||||
expect.objectContaining({
|
||||
|
||||
@@ -97,6 +97,12 @@ export type MarkInAppNotificationDeliveryReadInput = {
|
||||
readAt?: Date | null;
|
||||
};
|
||||
|
||||
export type MarkAllInAppNotificationDeliveriesReadInput = {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
readAt?: Date | null;
|
||||
};
|
||||
|
||||
type NotificationDeliveryUpdateData = {
|
||||
status: NotificationDeliveryStatus;
|
||||
attemptsMade?: number;
|
||||
@@ -136,6 +142,12 @@ export type NotificationStreamItem = {
|
||||
updatedAt: string;
|
||||
sentAt: string | null;
|
||||
readAt: string | null;
|
||||
// AK-P3 DoD 4 (additive): the stream deliberately carries only a validated
|
||||
// app-relative deeplink scalar (never payloadMetadata — the realtime guard
|
||||
// rejects metadata-shaped keys as secret-like) plus the redacted error, so
|
||||
// streamed items render identically to loader-built ones.
|
||||
deeplink: string | null;
|
||||
lastError: string | null;
|
||||
};
|
||||
|
||||
export type NotificationStreamSnapshot = {
|
||||
@@ -174,6 +186,10 @@ export type NotificationDeliveryClient = {
|
||||
| {
|
||||
where: { id: string; tenantId: string; userId: string; channel: "IN_APP"; status: "SENT" };
|
||||
data: { status: "READ"; readAt: Date };
|
||||
}
|
||||
| {
|
||||
where: { tenantId: string; userId: string; channel: "IN_APP"; status: "SENT" };
|
||||
data: { status: "READ"; readAt: Date };
|
||||
}): Promise<NotificationDeliveryUpdateResult>;
|
||||
findMany(args: {
|
||||
where: {
|
||||
@@ -396,9 +412,29 @@ function toNotificationStreamItem(record: unknown): NotificationStreamItem | nul
|
||||
updatedAt,
|
||||
sentAt: serializeDate(delivery.sentAt),
|
||||
readAt: serializeDate(delivery.readAt),
|
||||
deeplink: deriveStreamDeeplink(delivery.payloadMetadata),
|
||||
lastError: typeof delivery.lastError === "string" ? redactNotificationDiagnosticText(delivery.lastError) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Deeplink contract (AK-P3 DoD 4): `payloadMetadata.deeplink` must be an
|
||||
* app-relative path ("/…"); absolute URLs, protocol-relative, backslashes and
|
||||
* whitespace are rejected. Mirrors `deriveNotificationDeeplink` in
|
||||
* @hivegrid/view-models (client-side loader path) — keep both in sync.
|
||||
*/
|
||||
function deriveStreamDeeplink(payloadMetadata: unknown): string | null {
|
||||
if (typeof payloadMetadata !== "object" || payloadMetadata === null || Array.isArray(payloadMetadata)) {
|
||||
return null;
|
||||
}
|
||||
const candidate = (payloadMetadata as Record<string, unknown>).deeplink;
|
||||
if (typeof candidate !== "string") return null;
|
||||
const trimmed = candidate.trim();
|
||||
if (trimmed.length < 2 || !trimmed.startsWith("/")) return null;
|
||||
if (trimmed.startsWith("//") || trimmed.includes("\\") || /\s/.test(trimmed)) return null;
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
export async function upsertUserNotificationPreference(
|
||||
input: UserNotificationPreferenceInput,
|
||||
client: UserNotificationPreferenceClient = getDbClient() as DbClient & UserNotificationPreferenceClient,
|
||||
@@ -544,6 +580,28 @@ export async function markInAppNotificationDeliveryRead(
|
||||
return result;
|
||||
}
|
||||
|
||||
// Bulk "mark all as read" for the current tenant/user in-app inbox. Unlike the
|
||||
// single-delivery variant this tolerates a zero match (nothing unread) and
|
||||
// returns the number of cleared deliveries instead of asserting an exact count.
|
||||
export async function markAllInAppNotificationDeliveriesRead(
|
||||
input: MarkAllInAppNotificationDeliveriesReadInput,
|
||||
client: NotificationDeliveryClient = getDbClient() as DbClient & NotificationDeliveryClient,
|
||||
): Promise<number> {
|
||||
const tenantId = input.tenantId.trim();
|
||||
const userId = input.userId.trim();
|
||||
|
||||
if (!tenantId || !userId) {
|
||||
throw new Error("Notification delivery bulk read scope is required.");
|
||||
}
|
||||
|
||||
const result = await client.notificationDelivery.updateMany({
|
||||
where: { tenantId, userId, channel: "IN_APP", status: "SENT" },
|
||||
data: { status: "READ", readAt: input.readAt ?? new Date() },
|
||||
});
|
||||
|
||||
return typeof result.count === "number" ? result.count : 0;
|
||||
}
|
||||
|
||||
export async function getNotificationDeliveryDiagnostics(
|
||||
filters: NotificationDeliveryDiagnosticsFilters,
|
||||
client: NotificationDeliveryClient = getDbClient() as DbClient & NotificationDeliveryClient,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createDbClient } from "./client.server.js";
|
||||
import { databaseTargetLabel, isDatabaseReachable } from "./database-reachable.js";
|
||||
import {
|
||||
OUTBOX_CLAIM_DEFAULT_LIMIT,
|
||||
OUTBOX_CLAIM_LEASE_MS,
|
||||
@@ -15,9 +16,17 @@ const DATABASE_URL = process.env.DATABASE_URL?.trim();
|
||||
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;
|
||||
// A non-sentinel URL is necessary but not sufficient: the CI "Workspace
|
||||
// package tests" job injects a localhost DATABASE_URL without running a
|
||||
// Postgres service, so probe the server before connecting and skip (rather
|
||||
// than fail with P1001) when nothing is reachable.
|
||||
const databaseReachable = integrationUrl ? await isDatabaseReachable(integrationUrl) : false;
|
||||
if (integrationUrl && !databaseReachable) {
|
||||
console.warn(`[outbox-claim] skipped: no database reachable at ${databaseTargetLabel(integrationUrl)}`);
|
||||
}
|
||||
|
||||
const describeIntegration = databaseReachable ? describe : describe.skip;
|
||||
|
||||
describeIntegration("claimPendingOutboxEvents (integration)", () => {
|
||||
const prisma = createDbClient({ connectionString: integrationUrl });
|
||||
|
||||
@@ -37,6 +37,7 @@ 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 { databaseTargetLabel, isDatabaseReachable } from "./database-reachable.js";
|
||||
import { publishOutboxEvent, type OutboxPublisherTransaction } from "./outbox.js";
|
||||
import { claimPendingOutboxEvents } from "./outbox-claim.js";
|
||||
import {
|
||||
@@ -48,8 +49,16 @@ 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;
|
||||
|
||||
// A non-sentinel URL is necessary but not sufficient: the CI "Workspace
|
||||
// package tests" job injects a localhost DATABASE_URL without running a
|
||||
// Postgres service, so probe the server before connecting and skip (rather
|
||||
// than fail with P1001) when nothing is reachable.
|
||||
const databaseReachable = integrationUrl ? await isDatabaseReachable(integrationUrl) : false;
|
||||
if (integrationUrl && !databaseReachable) {
|
||||
console.warn(`[outbox-e2e] skipped: no database reachable at ${databaseTargetLabel(integrationUrl)}`);
|
||||
}
|
||||
const describeIntegration = databaseReachable ? describe : describe.skip;
|
||||
|
||||
const TEST_EVENT_TYPE = "audit.test.fired";
|
||||
const TEST_MARKER_TYPE = "audit.test.persisted";
|
||||
|
||||
@@ -100,7 +100,7 @@ describe("publishOutboxEvent", () => {
|
||||
retries: 0,
|
||||
lastError: null,
|
||||
scheduledAt: new Date("2026-05-17T07:00:00.000Z"),
|
||||
dispatchKey: "stripe:evt_1ABC",
|
||||
dispatchKey: "billing:evt_1ABC",
|
||||
priority: 0,
|
||||
lockedUntil: null,
|
||||
};
|
||||
@@ -117,12 +117,12 @@ describe("publishOutboxEvent", () => {
|
||||
tenantId: "tenant_1",
|
||||
type: "mail.send.queued",
|
||||
payload: { to: "u@example.com" },
|
||||
dispatchKey: "stripe:evt_1ABC",
|
||||
dispatchKey: "billing:evt_1ABC",
|
||||
});
|
||||
|
||||
expect(result.id).toBe("outbox_event_existing");
|
||||
expect(tx.outboxEvent.findUnique).toHaveBeenCalledWith({
|
||||
where: { dispatchKey: "stripe:evt_1ABC" },
|
||||
where: { dispatchKey: "billing:evt_1ABC" },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -205,7 +205,7 @@ describe("publishOutboxEvent", () => {
|
||||
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("billing:evt_1.subscription")).toBe(true);
|
||||
expect(OUTBOX_DISPATCH_KEY_PATTERN.test("")).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ export const OUTBOX_EVENT_TYPE_PATTERN = /^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*){2,}$
|
||||
/**
|
||||
* 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`).
|
||||
* colons (good for namespaced keys like `billing:evt_1ABC.subscription`).
|
||||
*/
|
||||
export const OUTBOX_DISPATCH_KEY_PATTERN = /^[A-Za-z0-9._:-]{1,256}$/u;
|
||||
|
||||
|
||||
+10
-5
@@ -1,4 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
vi.mock("./client.server.js", () => ({ getDbClient: vi.fn() }));
|
||||
|
||||
@@ -115,7 +117,7 @@ describe("syncDefaultRolesAndPermissions", () => {
|
||||
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({
|
||||
expect(defaultPermissionSeedDescriptors.find((permission) => permission.name === "admin.dashboard.view")).toMatchObject({
|
||||
type: "admin",
|
||||
inRoles: ["SuperAdmin"],
|
||||
});
|
||||
@@ -169,16 +171,19 @@ describe("syncDefaultRolesAndPermissions", () => {
|
||||
});
|
||||
|
||||
it("does not run the CLI seed block when bundled into the production seed artifact", () => {
|
||||
const productionSeedPath = path.resolve("packages/db/dist/production-seed.server.js");
|
||||
const permissionsSeedPath = path.resolve("packages/db/dist/permissions-seed.server.js");
|
||||
|
||||
expect(
|
||||
isPermissionsSeedDirectExecution(
|
||||
"/myapp/packages/db/dist/production-seed.server.js",
|
||||
"file:///myapp/packages/db/dist/production-seed.server.js"
|
||||
productionSeedPath,
|
||||
pathToFileURL(productionSeedPath).href
|
||||
)
|
||||
).toBe(false);
|
||||
expect(
|
||||
isPermissionsSeedDirectExecution(
|
||||
"/myapp/packages/db/dist/permissions-seed.server.js",
|
||||
"file:///myapp/packages/db/dist/permissions-seed.server.js"
|
||||
permissionsSeedPath,
|
||||
pathToFileURL(permissionsSeedPath).href
|
||||
)
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
+243
-26
@@ -1,7 +1,7 @@
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { createChildLogger, defaultLogger } from "@toolctrl/logger";
|
||||
import { createChildLogger, defaultLogger } from "@hivegrid/logger";
|
||||
|
||||
import { getDbClient, type DbClient } from "./client.server.js";
|
||||
|
||||
@@ -89,12 +89,6 @@ export const defaultPermissionSeeds = [
|
||||
"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",
|
||||
@@ -109,10 +103,6 @@ export const defaultPermissionSeeds = [
|
||||
"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",
|
||||
@@ -126,10 +116,6 @@ export const defaultPermissionSeeds = [
|
||||
"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",
|
||||
@@ -144,13 +130,23 @@ export const defaultPermissionSeeds = [
|
||||
"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",
|
||||
// P11 Dashboard (R-P11b). `dashboard.read` is the v1 surface gate;
|
||||
// `dashboard.customize` is limited to widget filters/periods until drag/drop
|
||||
// customization moves to v2.
|
||||
"dashboard.read",
|
||||
"dashboard.customize",
|
||||
// P12 Automation (R-P12a). Read opens lists/executions; manage edits rules
|
||||
// and templates; run starts manual/dry-run executions; admin manages tenant
|
||||
// credentials and guard overrides.
|
||||
"automation.read",
|
||||
"automation.manage",
|
||||
"automation.run",
|
||||
"automation.admin",
|
||||
"app.settings.members.view",
|
||||
"app.settings.members.create",
|
||||
"app.settings.members.update",
|
||||
@@ -163,6 +159,8 @@ export const defaultPermissionSeeds = [
|
||||
"app.settings.subscription.update",
|
||||
"app.settings.subscription.delete",
|
||||
"app.settings.subscription.invoices.view",
|
||||
"app.onboarding.demoData.manage",
|
||||
"app.onboarding.checklist.update",
|
||||
"app.settings.account.view",
|
||||
"app.settings.account.update",
|
||||
"app.settings.account.delete",
|
||||
@@ -193,6 +191,138 @@ export const defaultPermissionSeeds = [
|
||||
"tasks.write",
|
||||
"tasks.delete",
|
||||
"tasks.admin",
|
||||
// P6 CRM core (R-P6) — typed CRM contacts. Bundle semantics mirror files/tasks:
|
||||
// read_all ⊃ read_own; write ⊃ read_all; admin ⊃ write + delete.
|
||||
"crm.read_own",
|
||||
"crm.read_all",
|
||||
"crm.write",
|
||||
"crm.delete",
|
||||
"crm.admin",
|
||||
// P7 Lead-Inbox (R-P7) — lead intake and triage. Bundle semantics mirror CRM:
|
||||
// read_all ⊃ read_own; write ⊃ read_all; admin ⊃ write + delete/settings.
|
||||
"leads.read_own",
|
||||
"leads.read_all",
|
||||
"leads.write",
|
||||
"leads.delete",
|
||||
"leads.admin",
|
||||
// P8 Projekt/Pipelines (R-P8a) — project core + pipeline engine. Bundle
|
||||
// semantics mirror CRM; stage changes and member management are separate
|
||||
// capabilities because they are higher-risk than plain write.
|
||||
"projects.read_own",
|
||||
"projects.read_own_member",
|
||||
"projects.read_own_pl",
|
||||
"projects.read_all",
|
||||
"projects.write",
|
||||
"projects.change_stage",
|
||||
"projects.manage_members",
|
||||
"projects.delete",
|
||||
"projects.admin",
|
||||
// P9 Plantafel + Abnahme (R-P9b) — project scheduling and immutable
|
||||
// acceptance protocol capabilities.
|
||||
"plantafel.read_own",
|
||||
"plantafel.read_all",
|
||||
"plantafel.write",
|
||||
"plantafel.bulk_reassign",
|
||||
"acceptance.read",
|
||||
"acceptance.write",
|
||||
"acceptance.admin",
|
||||
"deals.read_volume_own",
|
||||
"deals.read_volume_all",
|
||||
"deals.read_aggregates",
|
||||
// P17 HR-Hub core (AK-P17a) — employee master data, locations, personnel
|
||||
// documents, encrypted password safe. Bundle semantics mirror files/tasks:
|
||||
// read_all ⊃ read_own; write ⊃ read_all; admin ⊃ write. The password-safe
|
||||
// permissions are SEPARATE: `hr.passwordsafe.use` is the capability to use the
|
||||
// safe at all (per-vault visibility is still governed by the
|
||||
// EmployeePasswordSafeAccess rows), `hr.passwordsafe.admin` gates the
|
||||
// tenant-wide vault-management view (/admin/hr/password-safe).
|
||||
"hr.read_own",
|
||||
"hr.read_all",
|
||||
"hr.write",
|
||||
"hr.admin",
|
||||
"hr.passwordsafe.use",
|
||||
"hr.passwordsafe.admin",
|
||||
// P17 HR-Hub workflows (AK-P17b) — leave/sick, announcements, payslips, upload
|
||||
// reminders, requests and surveys reuse the coarse hr.read_own/read_all/write/
|
||||
// admin bundle above (self-service reads via read_own; HR management via write;
|
||||
// admin = SuperUser). Two capabilities are SEPARATE because they are more than
|
||||
// plain write: hr.leave.approve gates deciding leave/sick requests (an approver
|
||||
// role, not necessarily HR-admin), hr.surveys.results gates viewing a survey's
|
||||
// aggregated results (distinct from participating).
|
||||
// NOTE: keep this comment free of double-quoted tokens. The roleDisplay test
|
||||
// regex-extracts every double-quoted string literal inside this array as a
|
||||
// permission name, so a quoted word in a comment becomes a phantom permission.
|
||||
"hr.leave.approve",
|
||||
"hr.surveys.results",
|
||||
// P14 Email (AK-P14a) — tenant-side sending-domain management. The module is
|
||||
// feature-gated (email-marketing); these two gate the sending-domain settings +
|
||||
// suppression view/manage actions (kept in DefaultPermissions, same list).
|
||||
"email.domain.view",
|
||||
"email.domain.manage",
|
||||
// P14 Email-Marketing (AK-P14b) — tenant-side campaigns/segments/reporting. The
|
||||
// module is feature-gated (email-marketing); `view` sees lists + reports,
|
||||
// `manage` creates/edits/sends campaigns + segments (kept in DefaultPermissions).
|
||||
"emailMarketing.view",
|
||||
"emailMarketing.manage",
|
||||
// P23 Postfach-Sync (VA-P23) — per-user Gmail/Microsoft mailbox mirror. The
|
||||
// module is feature-gated (email-inbox); `read_own` sees mails of the user's
|
||||
// OWN connected mailboxes, `read_all` sees every tenant mailbox, `write`
|
||||
// composes/sends over the user's own mailbox (M09 Block I, kept in
|
||||
// DefaultPermissions, same list).
|
||||
"email.read_own",
|
||||
"email.read_all",
|
||||
"email.write",
|
||||
// P5 Apps-Engine (R-P5) — integrations admin module. `read` sees the catalog +
|
||||
// connections; `connect`/`disconnect` manage a connection lifecycle;
|
||||
// `manual_sync` triggers a re-sync; `view_logs` opens sync history; `admin`
|
||||
// is the full integrations admin.
|
||||
"integrations.read",
|
||||
"integrations.connect",
|
||||
"integrations.disconnect",
|
||||
"integrations.manual_sync",
|
||||
"integrations.view_logs",
|
||||
"integrations.admin",
|
||||
// P16 Calendar-Sync (AK-P16a) — per-user Google calendar connections. The module
|
||||
// is feature-gated (calendar); `connect_own` lets a user connect/manage THEIR
|
||||
// OWN calendar (default for every tenant user, M25 Block I), `admin` gives
|
||||
// tenant-wide oversight + force-disconnect on offboarding (kept in DefaultPermissions).
|
||||
"calendar.connect_own",
|
||||
"calendar.admin",
|
||||
// P16 Booking (AK-P16b) — Calendly-style booking. The module is feature-gated
|
||||
// (booking). Cumulative bundle (M06 Block K): read_own (own appointments +
|
||||
// availability) < read_all < write (manage/cancel/reschedule) < admin (booking-page
|
||||
// CRUD + foreign availability + hard-delete). Owner-filtered server-side.
|
||||
"bookings.read_own",
|
||||
"bookings.read_all",
|
||||
"bookings.write",
|
||||
"bookings.admin",
|
||||
// P16 Forms (AK-P16c) — builder/publisher/admin bundle. basic sees owned
|
||||
// forms/submissions; builder edits owned forms; publisher can publish public
|
||||
// links; admin sees all forms and can re-run actions.
|
||||
"forms.basic",
|
||||
"forms.builder",
|
||||
"forms.publisher",
|
||||
"forms.admin",
|
||||
// P16 Signature (AK-P16d) — hardened SES default plus optional PandaDoc BYOK.
|
||||
// The module is feature-gated (signature). read/send are project owner scoped;
|
||||
// revoke/admin are tenant management capabilities.
|
||||
"signature.read",
|
||||
"signature.send",
|
||||
"signature.revoke",
|
||||
"signature.admin",
|
||||
// P11 Global Search (R-P11a). Search visibility remains entity-permission
|
||||
// aware; this capability only opens the search surface and admin tooling.
|
||||
"search.use",
|
||||
"search.admin",
|
||||
// P21 Privacy/GDPR (AK-P21). Self export reaches every tenant user; tenant
|
||||
// export, deletion, AVV acceptance and subprocessor visibility stay with
|
||||
// tenant administrators.
|
||||
"privacy.user_export.self",
|
||||
"privacy.tenant_export",
|
||||
"privacy.tenant_deletion",
|
||||
"privacy.avv.read",
|
||||
"privacy.avv.accept",
|
||||
"privacy.subprocessors.read",
|
||||
] as const;
|
||||
|
||||
export type DefaultPermissionSeed = {
|
||||
@@ -206,11 +336,6 @@ const explicitPermissionRoleAssignments: Partial<Record<(typeof defaultPermissio
|
||||
"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"],
|
||||
@@ -225,27 +350,32 @@ const explicitPermissionRoleAssignments: Partial<Record<(typeof defaultPermissio
|
||||
"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"],
|
||||
"dashboard.read": ["SuperUser", "Admin", "User"],
|
||||
"dashboard.customize": ["SuperUser", "Admin", "User"],
|
||||
"automation.read": ["SuperUser", "Admin"],
|
||||
"automation.manage": ["SuperUser", "Admin"],
|
||||
"automation.run": ["SuperUser", "Admin"],
|
||||
"automation.admin": ["SuperUser"],
|
||||
"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.onboarding.demoData.manage": ["SuperUser", "Admin"],
|
||||
"app.onboarding.checklist.update": ["SuperUser", "Admin", "User"],
|
||||
"app.settings.account.view": ["SuperUser", "Admin"],
|
||||
"app.settings.account.delete": ["SuperUser"],
|
||||
"app.settings.accounts.view": ["SuperUser", "Admin"],
|
||||
@@ -271,6 +401,94 @@ const explicitPermissionRoleAssignments: Partial<Record<(typeof defaultPermissio
|
||||
"tasks.write": ["SuperUser", "Admin", "User"],
|
||||
"tasks.delete": ["SuperUser", "Admin"],
|
||||
"tasks.admin": ["SuperUser"],
|
||||
// CRM — `crm.*` carries no `app.`/`admin.` prefix, so explicit grants are
|
||||
// mandatory. Regular users manage their own assigned contacts (read_own/write);
|
||||
// Admin/SuperUser see all and may delete; admin (custom-fields/tags/duplicates)
|
||||
// = SuperUser only.
|
||||
"crm.read_own": ["SuperUser", "Admin", "User"],
|
||||
"crm.read_all": ["SuperUser", "Admin"],
|
||||
"crm.write": ["SuperUser", "Admin", "User"],
|
||||
"crm.delete": ["SuperUser", "Admin"],
|
||||
"crm.admin": ["SuperUser"],
|
||||
// Leads — explicit grants because the prefix-default does not cover module
|
||||
// scopes without app/admin prefix.
|
||||
"leads.read_own": ["SuperUser", "Admin", "User"],
|
||||
"leads.read_all": ["SuperUser", "Admin"],
|
||||
"leads.write": ["SuperUser", "Admin", "User"],
|
||||
"leads.delete": ["SuperUser", "Admin"],
|
||||
"leads.admin": ["SuperUser"],
|
||||
// HR — `hr.*` carries no `app.`/`admin.` prefix, so explicit grants are
|
||||
// mandatory. Every employee sees their own profile/documents/directory and may
|
||||
// use a password safe they hold access to; Admin/SuperUser run the HR-admin
|
||||
// side (all employees, locations CRUD, document management, tenant-wide vault
|
||||
// management). admin = SuperUser only.
|
||||
"hr.read_own": ["SuperUser", "Admin", "User"],
|
||||
"hr.read_all": ["SuperUser", "Admin"],
|
||||
"hr.write": ["SuperUser", "Admin"],
|
||||
"hr.admin": ["SuperUser"],
|
||||
"hr.passwordsafe.use": ["SuperUser", "Admin", "User"],
|
||||
"hr.passwordsafe.admin": ["SuperUser", "Admin"],
|
||||
// HR workflows (AK-P17b) capabilities — approving requests and reading survey
|
||||
// results are management actions; granted to Admin/SuperUser by default.
|
||||
"hr.leave.approve": ["SuperUser", "Admin"],
|
||||
"hr.surveys.results": ["SuperUser", "Admin"],
|
||||
// Email sending-domain (AK-P14a) — viewing/managing the tenant sending domain +
|
||||
// suppression is a tenant-admin action (deliverability config).
|
||||
"email.domain.view": ["SuperUser", "Admin"],
|
||||
"email.domain.manage": ["SuperUser", "Admin"],
|
||||
// Email-Marketing (AK-P14b) — campaigns/segments/reporting are tenant-admin
|
||||
// actions (DSGVO-sensitive bulk send).
|
||||
"emailMarketing.view": ["SuperUser", "Admin"],
|
||||
"emailMarketing.manage": ["SuperUser", "Admin"],
|
||||
// Postfach-Sync (VA-P23) — reading/writing over your OWN connected mailbox is a
|
||||
// default tenant-user capability (M09 Block I); read_all (every tenant mailbox)
|
||||
// stays with tenant administrators.
|
||||
"email.read_own": ["SuperUser", "Admin", "User"],
|
||||
"email.read_all": ["SuperUser", "Admin"],
|
||||
"email.write": ["SuperUser", "Admin", "User"],
|
||||
// Integrations — `integrations.*` carries no `app.`/`admin.` prefix, so explicit
|
||||
// grants are mandatory. Connecting external systems is a tenant-admin action.
|
||||
"integrations.read": ["SuperUser", "Admin"],
|
||||
"integrations.connect": ["SuperUser", "Admin"],
|
||||
"integrations.disconnect": ["SuperUser", "Admin"],
|
||||
"integrations.manual_sync": ["SuperUser", "Admin"],
|
||||
"integrations.view_logs": ["SuperUser", "Admin"],
|
||||
"integrations.admin": ["SuperUser"],
|
||||
// Calendar — connecting your OWN calendar is a default tenant-user capability
|
||||
// (M25 Block I), so `connect_own` reaches the base `User` role; `admin` is the
|
||||
// tenant-wide oversight + force-disconnect capability.
|
||||
"calendar.connect_own": ["SuperUser", "Admin", "User"],
|
||||
"calendar.admin": ["SuperUser", "Admin"],
|
||||
// Booking — read_own (own appointments + own availability, M06 Block F) reaches
|
||||
// the base `User`; read_all/write/admin are tenant management capabilities.
|
||||
"bookings.read_own": ["SuperUser", "Admin", "User"],
|
||||
"bookings.read_all": ["SuperUser", "Admin"],
|
||||
"bookings.write": ["SuperUser", "Admin"],
|
||||
"bookings.admin": ["SuperUser", "Admin"],
|
||||
// Forms — every User can use owned forms; publishing and admin actions are
|
||||
// tenant management capabilities.
|
||||
"forms.basic": ["SuperUser", "Admin", "User"],
|
||||
"forms.builder": ["SuperUser", "Admin", "User"],
|
||||
"forms.publisher": ["SuperUser", "Admin"],
|
||||
"forms.admin": ["SuperUser", "Admin"],
|
||||
// Signature — all tenant users can read/send for their own readable projects;
|
||||
// revoke and admin stay with tenant administrators.
|
||||
"signature.read": ["SuperUser", "Admin", "User"],
|
||||
"signature.send": ["SuperUser", "Admin", "User"],
|
||||
"signature.revoke": ["SuperUser", "Admin"],
|
||||
"signature.admin": ["SuperUser", "Admin"],
|
||||
// Global search — every tenant user may search their permitted entities;
|
||||
// admin controls stay with tenant administrators.
|
||||
"search.use": ["SuperUser", "Admin", "User"],
|
||||
"search.admin": ["SuperUser", "Admin"],
|
||||
// Privacy/GDPR — self-export is a user right; all tenant-wide operations are
|
||||
// tenant-admin capabilities.
|
||||
"privacy.user_export.self": ["SuperUser", "Admin", "Billing Admin", "User"],
|
||||
"privacy.tenant_export": ["SuperUser", "Admin"],
|
||||
"privacy.tenant_deletion": ["SuperUser", "Admin"],
|
||||
"privacy.avv.read": ["SuperUser", "Admin"],
|
||||
"privacy.avv.accept": ["SuperUser", "Admin"],
|
||||
"privacy.subprocessors.read": ["SuperUser", "Admin"],
|
||||
};
|
||||
|
||||
export type SyncDefaultRolesAndPermissionsOptions = {
|
||||
@@ -367,7 +585,6 @@ export async function syncDefaultRolesAndPermissions({ client = getDbClient(), d
|
||||
type,
|
||||
order: index + 1,
|
||||
isDefault: true,
|
||||
entityId: null,
|
||||
})),
|
||||
skipDuplicates: true,
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import * as prismaBrowser from "./prisma-browser.js";
|
||||
|
||||
describe("@toolctrl/db browser Prisma boundary", () => {
|
||||
describe("@hivegrid/db browser Prisma boundary", () => {
|
||||
it("re-exports browser-safe Prisma symbols from the package-owned generated client", () => {
|
||||
expect(prismaBrowser.Prisma).toBeDefined();
|
||||
});
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
GDPR_EXPORT_URL_TTL_HOURS,
|
||||
GDPR_TENANT_DELETION_GRACE_DAYS,
|
||||
acceptAvv,
|
||||
cancelTenantDeletionRequest,
|
||||
createGdprExportJob,
|
||||
createTenantDeletionRequest,
|
||||
listDueTenantDeletionRequests,
|
||||
markGdprExportDownloaded,
|
||||
markGdprExportFailed,
|
||||
markGdprExportProcessing,
|
||||
markGdprExportReady,
|
||||
type PrivacyGdprClient,
|
||||
} from "./privacy-gdpr.server.js";
|
||||
|
||||
function createClient(overrides: {
|
||||
exportCount?: number;
|
||||
deletionCount?: number;
|
||||
updateCount?: number;
|
||||
} = {}): PrivacyGdprClient {
|
||||
return {
|
||||
gdprExportJob: {
|
||||
count: vi.fn().mockResolvedValue(overrides.exportCount ?? 0),
|
||||
create: vi.fn(async ({ data }) => ({
|
||||
id: "gdpr_export_1",
|
||||
createdAt: new Date("2026-07-02T09:00:00.000Z"),
|
||||
updatedAt: new Date("2026-07-02T09:00:00.000Z"),
|
||||
resultFileId: null,
|
||||
resultBucket: null,
|
||||
resultKey: null,
|
||||
resultSizeBytes: null,
|
||||
resultExpiresAt: null,
|
||||
downloadCount: 0,
|
||||
...data,
|
||||
})),
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
updateMany: vi.fn().mockResolvedValue({ count: overrides.updateCount ?? 1 }),
|
||||
},
|
||||
tenantDeletionRequest: {
|
||||
count: vi.fn().mockResolvedValue(overrides.deletionCount ?? 0),
|
||||
create: vi.fn(async ({ data }) => ({
|
||||
id: "tenant_delete_1",
|
||||
createdAt: new Date("2026-07-02T09:00:00.000Z"),
|
||||
updatedAt: new Date("2026-07-02T09:00:00.000Z"),
|
||||
cancelledAt: null,
|
||||
cancelledByUserId: null,
|
||||
hardDeleteStartedAt: null,
|
||||
hardDeleteEndedAt: null,
|
||||
errorMessage: null,
|
||||
...data,
|
||||
})),
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
updateMany: vi.fn().mockResolvedValue({ count: overrides.updateCount ?? 1 }),
|
||||
},
|
||||
avvAcceptance: {
|
||||
create: vi.fn(async ({ data }) => ({
|
||||
id: "avv_acceptance_1",
|
||||
createdAt: new Date("2026-07-02T09:00:00.000Z"),
|
||||
...data,
|
||||
})),
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
},
|
||||
subprocessor: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("GDPR export jobs", () => {
|
||||
it("creates user self exports with a 24h rate-limit query", async () => {
|
||||
const client = createClient();
|
||||
const now = new Date("2026-07-02T12:00:00.000Z");
|
||||
|
||||
await createGdprExportJob(
|
||||
{
|
||||
tenantId: "tenant_1",
|
||||
requestedByUserId: "user_1",
|
||||
targetUserId: "user_1",
|
||||
scope: "user_self",
|
||||
now,
|
||||
},
|
||||
client,
|
||||
);
|
||||
|
||||
expect(client.gdprExportJob.count).toHaveBeenCalledWith({
|
||||
where: {
|
||||
tenantId: "tenant_1",
|
||||
scope: "user_self",
|
||||
targetUserId: "user_1",
|
||||
createdAt: { gte: new Date("2026-07-01T12:00:00.000Z") },
|
||||
},
|
||||
});
|
||||
expect(client.gdprExportJob.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
tenantId: "tenant_1",
|
||||
requestedByUserId: "user_1",
|
||||
targetUserId: "user_1",
|
||||
scope: "user_self",
|
||||
status: "queued",
|
||||
progressPercent: 0,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects more than three user self exports per 24 hours", async () => {
|
||||
const client = createClient({ exportCount: 3 });
|
||||
|
||||
await expect(
|
||||
createGdprExportJob(
|
||||
{
|
||||
tenantId: "tenant_1",
|
||||
requestedByUserId: "user_1",
|
||||
scope: "user_self",
|
||||
},
|
||||
client,
|
||||
),
|
||||
).rejects.toThrow("GDPR user self export limit reached.");
|
||||
|
||||
expect(client.gdprExportJob.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("allows only one active tenant-full export", async () => {
|
||||
const client = createClient({ exportCount: 1 });
|
||||
|
||||
await expect(
|
||||
createGdprExportJob(
|
||||
{
|
||||
tenantId: "tenant_1",
|
||||
requestedByUserId: "admin_1",
|
||||
scope: "tenant_full",
|
||||
},
|
||||
client,
|
||||
),
|
||||
).rejects.toThrow("A tenant GDPR export is already active.");
|
||||
|
||||
expect(client.gdprExportJob.count).toHaveBeenCalledWith({
|
||||
where: {
|
||||
tenantId: "tenant_1",
|
||||
scope: "tenant_full",
|
||||
status: { in: ["queued", "processing"] },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("marks exports ready with 72h artifact expiry", async () => {
|
||||
const client = createClient();
|
||||
const now = new Date("2026-07-02T12:00:00.000Z");
|
||||
|
||||
await markGdprExportReady(
|
||||
{
|
||||
id: "gdpr_export_1",
|
||||
tenantId: "tenant_1",
|
||||
resultBucket: "exports",
|
||||
resultKey: "tenant_1/gdpr.zip",
|
||||
resultSizeBytes: 1234,
|
||||
now,
|
||||
},
|
||||
client,
|
||||
);
|
||||
|
||||
expect(client.gdprExportJob.updateMany).toHaveBeenCalledWith({
|
||||
where: { id: "gdpr_export_1", tenantId: "tenant_1" },
|
||||
data: {
|
||||
status: "ready",
|
||||
progressPercent: 100,
|
||||
resultFileId: null,
|
||||
resultBucket: "exports",
|
||||
resultKey: "tenant_1/gdpr.zip",
|
||||
resultSizeBytes: 1234,
|
||||
resultExpiresAt: new Date(now.getTime() + GDPR_EXPORT_URL_TTL_HOURS * 60 * 60 * 1_000),
|
||||
processingFinishedAt: now,
|
||||
errorMessage: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("uses tenant-scoped updateMany for lifecycle transitions", async () => {
|
||||
const client = createClient();
|
||||
|
||||
await markGdprExportProcessing({ id: "gdpr_export_1", tenantId: "tenant_1", now: new Date("2026-07-02T12:00:00.000Z") }, client);
|
||||
await markGdprExportFailed({ id: "gdpr_export_1", tenantId: "tenant_1", errorMessage: "token=secret-value" }, client);
|
||||
await markGdprExportDownloaded({ id: "gdpr_export_1", tenantId: "tenant_1", now: new Date("2026-07-02T13:00:00.000Z") }, client);
|
||||
|
||||
const calls = vi.mocked(client.gdprExportJob.updateMany).mock.calls;
|
||||
expect(calls[0]?.[0].where).toEqual({ id: "gdpr_export_1", tenantId: "tenant_1" });
|
||||
expect(calls[1]?.[0].data.errorMessage).toBe("token=[REDACTED]");
|
||||
expect(calls[2]?.[0]).toEqual({
|
||||
where: {
|
||||
id: "gdpr_export_1",
|
||||
tenantId: "tenant_1",
|
||||
status: "ready",
|
||||
resultExpiresAt: { gt: new Date("2026-07-02T13:00:00.000Z") },
|
||||
},
|
||||
data: {
|
||||
downloadCount: { increment: 1 },
|
||||
lastDownloadedAt: new Date("2026-07-02T13:00:00.000Z"),
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("tenant deletion and AVV", () => {
|
||||
it("creates tenant deletion requests with slug confirmation and 30-day grace", async () => {
|
||||
const client = createClient();
|
||||
const now = new Date("2026-07-02T12:00:00.000Z");
|
||||
|
||||
await createTenantDeletionRequest(
|
||||
{
|
||||
tenantId: "tenant_1",
|
||||
requestedByUserId: "admin_1",
|
||||
tenantSlug: "acme",
|
||||
slugConfirmPhrase: "acme",
|
||||
reason: "voluntary",
|
||||
now,
|
||||
},
|
||||
client,
|
||||
);
|
||||
|
||||
expect(client.tenantDeletionRequest.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
tenantId: "tenant_1",
|
||||
requestedByUserId: "admin_1",
|
||||
reason: "voluntary",
|
||||
reasonText: null,
|
||||
slugConfirmPhrase: "acme",
|
||||
status: "pending",
|
||||
gracePeriodEndsAt: new Date(now.getTime() + GDPR_TENANT_DELETION_GRACE_DAYS * 24 * 60 * 60 * 1_000),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects tenant deletion when the confirmation phrase differs from slug", async () => {
|
||||
const client = createClient();
|
||||
|
||||
await expect(
|
||||
createTenantDeletionRequest(
|
||||
{
|
||||
tenantId: "tenant_1",
|
||||
requestedByUserId: "admin_1",
|
||||
tenantSlug: "acme",
|
||||
slugConfirmPhrase: "wrong",
|
||||
reason: "voluntary",
|
||||
},
|
||||
client,
|
||||
),
|
||||
).rejects.toThrow("Tenant deletion confirmation phrase does not match the tenant slug.");
|
||||
|
||||
expect(client.tenantDeletionRequest.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("cancels only pending tenant deletion requests", async () => {
|
||||
const client = createClient();
|
||||
const now = new Date("2026-07-03T12:00:00.000Z");
|
||||
|
||||
await cancelTenantDeletionRequest({ id: "tenant_delete_1", tenantId: "tenant_1", cancelledByUserId: "admin_1", now }, client);
|
||||
|
||||
expect(client.tenantDeletionRequest.updateMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: "tenant_delete_1",
|
||||
tenantId: "tenant_1",
|
||||
status: "pending",
|
||||
},
|
||||
data: {
|
||||
status: "cancelled",
|
||||
cancelledAt: now,
|
||||
cancelledByUserId: "admin_1",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("lists due deletion requests for the hard-delete cron", async () => {
|
||||
const client = createClient();
|
||||
const now = new Date("2026-08-02T12:00:00.000Z");
|
||||
|
||||
await listDueTenantDeletionRequests({ now, take: 25 }, client);
|
||||
|
||||
expect(client.tenantDeletionRequest.findMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
status: "pending",
|
||||
gracePeriodEndsAt: { lte: now },
|
||||
},
|
||||
orderBy: [{ gracePeriodEndsAt: "asc" }, { id: "asc" }],
|
||||
take: 25,
|
||||
});
|
||||
});
|
||||
|
||||
it("records AVV acceptance history with request metadata", async () => {
|
||||
const client = createClient();
|
||||
|
||||
await acceptAvv(
|
||||
{
|
||||
tenantId: "tenant_1",
|
||||
acceptedByUserId: "admin_1",
|
||||
avvVersion: "2026-07-02",
|
||||
signerName: "Ada Lovelace",
|
||||
signerRole: "Owner",
|
||||
acceptedIp: "203.0.113.5",
|
||||
acceptedUserAgent: "Test browser",
|
||||
},
|
||||
client,
|
||||
);
|
||||
|
||||
expect(client.avvAcceptance.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
tenantId: "tenant_1",
|
||||
acceptedByUserId: "admin_1",
|
||||
acceptedIp: "203.0.113.5",
|
||||
acceptedUserAgent: "Test browser",
|
||||
avvVersion: "2026-07-02",
|
||||
pdfFileId: null,
|
||||
signerName: "Ada Lovelace",
|
||||
signerRole: "Owner",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,504 @@
|
||||
import { getDbClient, type DbClient } from "./client.server.js";
|
||||
|
||||
export const GDPR_EXPORT_URL_TTL_HOURS = 72;
|
||||
export const GDPR_USER_SELF_EXPORT_LIMIT_PER_24H = 3;
|
||||
export const GDPR_TENANT_DELETION_GRACE_DAYS = 30;
|
||||
|
||||
export type GdprExportScope = "user_self" | "tenant_full";
|
||||
export type GdprExportStatus = "queued" | "processing" | "ready" | "failed" | "expired";
|
||||
export type TenantDeletionRequestStatus = "pending" | "cancelled" | "executing" | "completed" | "failed";
|
||||
export type TenantDeletionReason = "voluntary" | "non_payment" | "suspended_violation" | "admin_initiated";
|
||||
|
||||
type GdprExportJobRecord = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
requestedByUserId: string;
|
||||
targetUserId: string | null;
|
||||
scope: GdprExportScope;
|
||||
status: GdprExportStatus;
|
||||
progressPercent: number;
|
||||
resultFileId: string | null;
|
||||
resultBucket: string | null;
|
||||
resultKey: string | null;
|
||||
resultSizeBytes: number | null;
|
||||
resultExpiresAt: Date | null;
|
||||
downloadCount: number;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
type TenantDeletionRequestRecord = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
requestedByUserId: string;
|
||||
reason: TenantDeletionReason;
|
||||
reasonText: string | null;
|
||||
slugConfirmPhrase: string;
|
||||
status: TenantDeletionRequestStatus;
|
||||
gracePeriodEndsAt: Date;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
type AvvAcceptanceRecord = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
acceptedByUserId: string;
|
||||
avvVersion: string;
|
||||
pdfFileId: string | null;
|
||||
signerName: string;
|
||||
signerRole: string | null;
|
||||
createdAt: Date;
|
||||
};
|
||||
|
||||
type SubprocessorRecord = {
|
||||
id: string;
|
||||
name: string;
|
||||
purposeText: string;
|
||||
country: string;
|
||||
isEuEea: boolean;
|
||||
dataCategories: string[];
|
||||
dpaUrl: string | null;
|
||||
activeSince: Date | null;
|
||||
archivedAt: Date | null;
|
||||
};
|
||||
|
||||
type GdprExportJobCreateData = {
|
||||
tenantId: string;
|
||||
requestedByUserId: string;
|
||||
targetUserId: string | null;
|
||||
scope: GdprExportScope;
|
||||
status: Extract<GdprExportStatus, "queued">;
|
||||
progressPercent: number;
|
||||
};
|
||||
|
||||
type GdprExportJobUpdateData = Partial<{
|
||||
status: GdprExportStatus;
|
||||
progressPercent: number;
|
||||
resultFileId: string | null;
|
||||
resultBucket: string | null;
|
||||
resultKey: string | null;
|
||||
resultSizeBytes: number | null;
|
||||
resultExpiresAt: Date | null;
|
||||
downloadCount: { increment: number } | number;
|
||||
lastDownloadedAt: Date | null;
|
||||
errorMessage: string | null;
|
||||
processingStartedAt: Date | null;
|
||||
processingFinishedAt: Date | null;
|
||||
}>;
|
||||
|
||||
type TenantDeletionRequestCreateData = {
|
||||
tenantId: string;
|
||||
requestedByUserId: string;
|
||||
reason: TenantDeletionReason;
|
||||
reasonText: string | null;
|
||||
slugConfirmPhrase: string;
|
||||
status: Extract<TenantDeletionRequestStatus, "pending">;
|
||||
gracePeriodEndsAt: Date;
|
||||
};
|
||||
|
||||
type TenantDeletionRequestUpdateData = Partial<{
|
||||
status: TenantDeletionRequestStatus;
|
||||
cancelledAt: Date | null;
|
||||
cancelledByUserId: string | null;
|
||||
hardDeleteStartedAt: Date | null;
|
||||
hardDeleteEndedAt: Date | null;
|
||||
errorMessage: string | null;
|
||||
}>;
|
||||
|
||||
type AvvAcceptanceCreateData = {
|
||||
tenantId: string;
|
||||
acceptedByUserId: string;
|
||||
acceptedIp: string | null;
|
||||
acceptedUserAgent: string | null;
|
||||
avvVersion: string;
|
||||
pdfFileId: string | null;
|
||||
signerName: string;
|
||||
signerRole: string | null;
|
||||
};
|
||||
|
||||
export type PrivacyGdprClient = {
|
||||
gdprExportJob: {
|
||||
count(args: { where: Record<string, unknown> }): Promise<number>;
|
||||
create(args: { data: GdprExportJobCreateData }): Promise<GdprExportJobRecord>;
|
||||
findMany(args: { where: Record<string, unknown>; orderBy: Record<string, string>; take?: number; skip?: number }): Promise<GdprExportJobRecord[]>;
|
||||
updateMany(args: { where: Record<string, unknown>; data: GdprExportJobUpdateData }): Promise<{ count?: number }>;
|
||||
};
|
||||
tenantDeletionRequest: {
|
||||
count(args: { where: Record<string, unknown> }): Promise<number>;
|
||||
create(args: { data: TenantDeletionRequestCreateData }): Promise<TenantDeletionRequestRecord>;
|
||||
findMany(args: {
|
||||
where: Record<string, unknown>;
|
||||
orderBy: Record<string, string> | Array<Record<string, string>>;
|
||||
take?: number;
|
||||
}): Promise<TenantDeletionRequestRecord[]>;
|
||||
updateMany(args: { where: Record<string, unknown>; data: TenantDeletionRequestUpdateData }): Promise<{ count?: number }>;
|
||||
};
|
||||
avvAcceptance: {
|
||||
create(args: { data: AvvAcceptanceCreateData }): Promise<AvvAcceptanceRecord>;
|
||||
findMany(args: { where: Record<string, unknown>; orderBy: Record<string, string> }): Promise<AvvAcceptanceRecord[]>;
|
||||
};
|
||||
subprocessor: {
|
||||
findMany(args: { where: Record<string, unknown>; orderBy: Record<string, string> }): Promise<SubprocessorRecord[]>;
|
||||
};
|
||||
};
|
||||
|
||||
export type CreateGdprExportJobInput = {
|
||||
tenantId: string;
|
||||
requestedByUserId: string;
|
||||
scope: GdprExportScope;
|
||||
targetUserId?: string | null;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
export type MarkGdprExportReadyInput = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
resultFileId?: string | null;
|
||||
resultBucket: string;
|
||||
resultKey: string;
|
||||
resultSizeBytes?: number | null;
|
||||
resultExpiresAt?: Date;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
export type MarkGdprExportProcessingInput = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
export type MarkGdprExportFailedInput = {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
errorMessage?: string | null;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
export type CreateTenantDeletionRequestInput = {
|
||||
tenantId: string;
|
||||
requestedByUserId: string;
|
||||
tenantSlug: string;
|
||||
slugConfirmPhrase: string;
|
||||
reason: TenantDeletionReason;
|
||||
reasonText?: string | null;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
export type AcceptAvvInput = {
|
||||
tenantId: string;
|
||||
acceptedByUserId: string;
|
||||
avvVersion: string;
|
||||
signerName: string;
|
||||
signerRole?: string | null;
|
||||
pdfFileId?: string | null;
|
||||
acceptedIp?: string | null;
|
||||
acceptedUserAgent?: string | null;
|
||||
};
|
||||
|
||||
function requireText(value: string, fieldName: string): string {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) {
|
||||
throw new Error(`${fieldName} is required.`);
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function hoursBefore(date: Date, hours: number): Date {
|
||||
return new Date(date.getTime() - hours * 60 * 60 * 1_000);
|
||||
}
|
||||
|
||||
function hoursAfter(date: Date, hours: number): Date {
|
||||
return new Date(date.getTime() + hours * 60 * 60 * 1_000);
|
||||
}
|
||||
|
||||
function daysAfter(date: Date, days: number): Date {
|
||||
return new Date(date.getTime() + days * 24 * 60 * 60 * 1_000);
|
||||
}
|
||||
|
||||
function clampProgress(value: number): number {
|
||||
if (!Number.isFinite(value)) {
|
||||
return 0;
|
||||
}
|
||||
return Math.max(0, Math.min(100, Math.floor(value)));
|
||||
}
|
||||
|
||||
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 clientOrDefault(client?: PrivacyGdprClient): PrivacyGdprClient {
|
||||
return client ?? (getDbClient() as DbClient & PrivacyGdprClient);
|
||||
}
|
||||
|
||||
async function updateOneTenantScoped(
|
||||
operation: Promise<{ count?: number }>,
|
||||
errorMessage: string,
|
||||
): Promise<void> {
|
||||
const result = await operation;
|
||||
if (typeof result.count === "number" && result.count !== 1) {
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
}
|
||||
|
||||
export async function createGdprExportJob(input: CreateGdprExportJobInput, client?: PrivacyGdprClient): Promise<GdprExportJobRecord> {
|
||||
const db = clientOrDefault(client);
|
||||
const tenantId = requireText(input.tenantId, "tenantId");
|
||||
const requestedByUserId = requireText(input.requestedByUserId, "requestedByUserId");
|
||||
const targetUserId = input.scope === "user_self" ? requireText(input.targetUserId ?? requestedByUserId, "targetUserId") : (input.targetUserId?.trim() || null);
|
||||
const now = input.now ?? new Date();
|
||||
|
||||
if (input.scope === "user_self") {
|
||||
const recentSelfExports = await db.gdprExportJob.count({
|
||||
where: {
|
||||
tenantId,
|
||||
scope: "user_self",
|
||||
targetUserId,
|
||||
createdAt: { gte: hoursBefore(now, 24) },
|
||||
},
|
||||
});
|
||||
if (recentSelfExports >= GDPR_USER_SELF_EXPORT_LIMIT_PER_24H) {
|
||||
throw new Error("GDPR user self export limit reached.");
|
||||
}
|
||||
} else {
|
||||
const activeTenantExports = await db.gdprExportJob.count({
|
||||
where: {
|
||||
tenantId,
|
||||
scope: "tenant_full",
|
||||
status: { in: ["queued", "processing"] },
|
||||
},
|
||||
});
|
||||
if (activeTenantExports > 0) {
|
||||
throw new Error("A tenant GDPR export is already active.");
|
||||
}
|
||||
}
|
||||
|
||||
return db.gdprExportJob.create({
|
||||
data: {
|
||||
tenantId,
|
||||
requestedByUserId,
|
||||
targetUserId,
|
||||
scope: input.scope,
|
||||
status: "queued",
|
||||
progressPercent: 0,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function listGdprExportJobs(
|
||||
input: { tenantId: string; requestedByUserId?: string | null; take?: number; skip?: number },
|
||||
client?: PrivacyGdprClient,
|
||||
): Promise<GdprExportJobRecord[]> {
|
||||
const tenantId = requireText(input.tenantId, "tenantId");
|
||||
return clientOrDefault(client).gdprExportJob.findMany({
|
||||
where: {
|
||||
tenantId,
|
||||
...(input.requestedByUserId ? { requestedByUserId: input.requestedByUserId } : {}),
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: input.take,
|
||||
skip: input.skip,
|
||||
});
|
||||
}
|
||||
|
||||
export async function markGdprExportProcessing(input: MarkGdprExportProcessingInput, client?: PrivacyGdprClient): Promise<void> {
|
||||
const now = input.now ?? new Date();
|
||||
await updateOneTenantScoped(
|
||||
clientOrDefault(client).gdprExportJob.updateMany({
|
||||
where: { id: requireText(input.id, "id"), tenantId: requireText(input.tenantId, "tenantId") },
|
||||
data: {
|
||||
status: "processing",
|
||||
progressPercent: 5,
|
||||
processingStartedAt: now,
|
||||
processingFinishedAt: null,
|
||||
errorMessage: null,
|
||||
},
|
||||
}),
|
||||
"GDPR export job tenant scope did not match exactly one job.",
|
||||
);
|
||||
}
|
||||
|
||||
export async function markGdprExportProgress(input: { id: string; tenantId: string; progressPercent: number }, client?: PrivacyGdprClient): Promise<void> {
|
||||
await updateOneTenantScoped(
|
||||
clientOrDefault(client).gdprExportJob.updateMany({
|
||||
where: { id: requireText(input.id, "id"), tenantId: requireText(input.tenantId, "tenantId") },
|
||||
data: { progressPercent: clampProgress(input.progressPercent) },
|
||||
}),
|
||||
"GDPR export job tenant scope did not match exactly one job.",
|
||||
);
|
||||
}
|
||||
|
||||
export async function markGdprExportReady(input: MarkGdprExportReadyInput, client?: PrivacyGdprClient): Promise<void> {
|
||||
const now = input.now ?? new Date();
|
||||
await updateOneTenantScoped(
|
||||
clientOrDefault(client).gdprExportJob.updateMany({
|
||||
where: { id: requireText(input.id, "id"), tenantId: requireText(input.tenantId, "tenantId") },
|
||||
data: {
|
||||
status: "ready",
|
||||
progressPercent: 100,
|
||||
resultFileId: input.resultFileId ?? null,
|
||||
resultBucket: requireText(input.resultBucket, "resultBucket"),
|
||||
resultKey: requireText(input.resultKey, "resultKey"),
|
||||
resultSizeBytes: input.resultSizeBytes ?? null,
|
||||
resultExpiresAt: input.resultExpiresAt ?? hoursAfter(now, GDPR_EXPORT_URL_TTL_HOURS),
|
||||
processingFinishedAt: now,
|
||||
errorMessage: null,
|
||||
},
|
||||
}),
|
||||
"GDPR export job tenant scope did not match exactly one job.",
|
||||
);
|
||||
}
|
||||
|
||||
export async function markGdprExportFailed(input: MarkGdprExportFailedInput, client?: PrivacyGdprClient): Promise<void> {
|
||||
await updateOneTenantScoped(
|
||||
clientOrDefault(client).gdprExportJob.updateMany({
|
||||
where: { id: requireText(input.id, "id"), tenantId: requireText(input.tenantId, "tenantId") },
|
||||
data: {
|
||||
status: "failed",
|
||||
errorMessage: redactDiagnosticText(input.errorMessage ?? "GDPR export failed.").slice(0, 2_000),
|
||||
processingFinishedAt: input.now ?? new Date(),
|
||||
},
|
||||
}),
|
||||
"GDPR export job tenant scope did not match exactly one job.",
|
||||
);
|
||||
}
|
||||
|
||||
export async function markGdprExportDownloaded(input: { id: string; tenantId: string; now?: Date }, client?: PrivacyGdprClient): Promise<void> {
|
||||
await updateOneTenantScoped(
|
||||
clientOrDefault(client).gdprExportJob.updateMany({
|
||||
where: {
|
||||
id: requireText(input.id, "id"),
|
||||
tenantId: requireText(input.tenantId, "tenantId"),
|
||||
status: "ready",
|
||||
resultExpiresAt: { gt: input.now ?? new Date() },
|
||||
},
|
||||
data: {
|
||||
downloadCount: { increment: 1 },
|
||||
lastDownloadedAt: input.now ?? new Date(),
|
||||
},
|
||||
}),
|
||||
"GDPR export job is not ready for download or has expired.",
|
||||
);
|
||||
}
|
||||
|
||||
export async function createTenantDeletionRequest(input: CreateTenantDeletionRequestInput, client?: PrivacyGdprClient): Promise<TenantDeletionRequestRecord> {
|
||||
const tenantId = requireText(input.tenantId, "tenantId");
|
||||
const requestedByUserId = requireText(input.requestedByUserId, "requestedByUserId");
|
||||
const tenantSlug = requireText(input.tenantSlug, "tenantSlug");
|
||||
const slugConfirmPhrase = requireText(input.slugConfirmPhrase, "slugConfirmPhrase");
|
||||
if (slugConfirmPhrase !== tenantSlug) {
|
||||
throw new Error("Tenant deletion confirmation phrase does not match the tenant slug.");
|
||||
}
|
||||
|
||||
const db = clientOrDefault(client);
|
||||
const activeRequests = await db.tenantDeletionRequest.count({
|
||||
where: { tenantId, status: { in: ["pending", "executing"] } },
|
||||
});
|
||||
if (activeRequests > 0) {
|
||||
throw new Error("A tenant deletion request is already active.");
|
||||
}
|
||||
|
||||
const now = input.now ?? new Date();
|
||||
return db.tenantDeletionRequest.create({
|
||||
data: {
|
||||
tenantId,
|
||||
requestedByUserId,
|
||||
reason: input.reason,
|
||||
reasonText: input.reasonText?.trim() || null,
|
||||
slugConfirmPhrase,
|
||||
status: "pending",
|
||||
gracePeriodEndsAt: daysAfter(now, GDPR_TENANT_DELETION_GRACE_DAYS),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function cancelTenantDeletionRequest(input: { id: string; tenantId: string; cancelledByUserId: string; now?: Date }, client?: PrivacyGdprClient): Promise<void> {
|
||||
await updateOneTenantScoped(
|
||||
clientOrDefault(client).tenantDeletionRequest.updateMany({
|
||||
where: {
|
||||
id: requireText(input.id, "id"),
|
||||
tenantId: requireText(input.tenantId, "tenantId"),
|
||||
status: "pending",
|
||||
},
|
||||
data: {
|
||||
status: "cancelled",
|
||||
cancelledAt: input.now ?? new Date(),
|
||||
cancelledByUserId: requireText(input.cancelledByUserId, "cancelledByUserId"),
|
||||
},
|
||||
}),
|
||||
"Tenant deletion request is not pending or does not belong to the tenant.",
|
||||
);
|
||||
}
|
||||
|
||||
export async function listDueTenantDeletionRequests(input: { now?: Date; take?: number }, client?: PrivacyGdprClient): Promise<TenantDeletionRequestRecord[]> {
|
||||
return clientOrDefault(client).tenantDeletionRequest.findMany({
|
||||
where: {
|
||||
status: "pending",
|
||||
gracePeriodEndsAt: { lte: input.now ?? new Date() },
|
||||
},
|
||||
orderBy: [{ gracePeriodEndsAt: "asc" }, { id: "asc" }],
|
||||
take: Math.max(1, Math.min(input.take ?? 50, 200)),
|
||||
});
|
||||
}
|
||||
|
||||
export async function markTenantDeletionExecuting(input: { id: string; tenantId: string; now?: Date }, client?: PrivacyGdprClient): Promise<void> {
|
||||
await updateOneTenantScoped(
|
||||
clientOrDefault(client).tenantDeletionRequest.updateMany({
|
||||
where: { id: requireText(input.id, "id"), tenantId: requireText(input.tenantId, "tenantId"), status: "pending" },
|
||||
data: { status: "executing", hardDeleteStartedAt: input.now ?? new Date(), errorMessage: null },
|
||||
}),
|
||||
"Tenant deletion request tenant scope did not match exactly one pending request.",
|
||||
);
|
||||
}
|
||||
|
||||
export async function markTenantDeletionCompleted(input: { id: string; tenantId: string; now?: Date }, client?: PrivacyGdprClient): Promise<void> {
|
||||
await updateOneTenantScoped(
|
||||
clientOrDefault(client).tenantDeletionRequest.updateMany({
|
||||
where: { id: requireText(input.id, "id"), tenantId: requireText(input.tenantId, "tenantId"), status: "executing" },
|
||||
data: { status: "completed", hardDeleteEndedAt: input.now ?? new Date(), errorMessage: null },
|
||||
}),
|
||||
"Tenant deletion request tenant scope did not match exactly one executing request.",
|
||||
);
|
||||
}
|
||||
|
||||
export async function markTenantDeletionFailed(input: { id: string; tenantId: string; errorMessage?: string | null }, client?: PrivacyGdprClient): Promise<void> {
|
||||
await updateOneTenantScoped(
|
||||
clientOrDefault(client).tenantDeletionRequest.updateMany({
|
||||
where: { id: requireText(input.id, "id"), tenantId: requireText(input.tenantId, "tenantId") },
|
||||
data: { status: "failed", errorMessage: redactDiagnosticText(input.errorMessage ?? "Tenant deletion failed.").slice(0, 2_000) },
|
||||
}),
|
||||
"Tenant deletion request tenant scope did not match exactly one request.",
|
||||
);
|
||||
}
|
||||
|
||||
export async function acceptAvv(input: AcceptAvvInput, client?: PrivacyGdprClient): Promise<AvvAcceptanceRecord> {
|
||||
return clientOrDefault(client).avvAcceptance.create({
|
||||
data: {
|
||||
tenantId: requireText(input.tenantId, "tenantId"),
|
||||
acceptedByUserId: requireText(input.acceptedByUserId, "acceptedByUserId"),
|
||||
acceptedIp: input.acceptedIp?.trim() || null,
|
||||
acceptedUserAgent: input.acceptedUserAgent?.trim() || null,
|
||||
avvVersion: requireText(input.avvVersion, "avvVersion"),
|
||||
pdfFileId: input.pdfFileId?.trim() || null,
|
||||
signerName: requireText(input.signerName, "signerName"),
|
||||
signerRole: input.signerRole?.trim() || null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function listAvvAcceptances(input: { tenantId: string }, client?: PrivacyGdprClient): Promise<AvvAcceptanceRecord[]> {
|
||||
return clientOrDefault(client).avvAcceptance.findMany({
|
||||
where: { tenantId: requireText(input.tenantId, "tenantId") },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
}
|
||||
|
||||
export async function listActiveSubprocessors(client?: PrivacyGdprClient): Promise<SubprocessorRecord[]> {
|
||||
return clientOrDefault(client).subprocessor.findMany({
|
||||
where: { archivedAt: null },
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { createHmac } from "node:crypto";
|
||||
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import {
|
||||
buildPublicWebhookIdempotencyKey,
|
||||
createPublicWebhookDeliveryHeaders,
|
||||
derivePublicApiSecretMetadata,
|
||||
derivePublicWebhookSigningSecret,
|
||||
hashJsonValue,
|
||||
planPublicWebhookRetry,
|
||||
verifyPublicApiSecret,
|
||||
verifyPublicWebhookHmacWithPresentedSecret,
|
||||
} from "./public-api.server.js";
|
||||
|
||||
describe("public-api.server", () => {
|
||||
test("stores only secret metadata and verifies presented webhook secrets", () => {
|
||||
const metadata = derivePublicApiSecretMetadata("hgwh_plain_secret", "test-hash-secret");
|
||||
|
||||
expect(metadata.hash).not.toContain("hgwh_plain_secret");
|
||||
expect(metadata.prefix).toBe("hgwh_plain");
|
||||
expect(metadata.lastFour).toBe("cret");
|
||||
expect(verifyPublicApiSecret("hgwh_plain_secret", metadata.hash, "test-hash-secret")).toBe(true);
|
||||
expect(verifyPublicApiSecret("wrong", metadata.hash, "test-hash-secret")).toBe(false);
|
||||
});
|
||||
|
||||
test("verifies incoming HMAC signatures from the once-visible webhook secret", () => {
|
||||
const secret = "hgwh_incoming_secret";
|
||||
const body = JSON.stringify({ email: "lead@example.test" });
|
||||
const timestamp = "1783055796";
|
||||
const signature = `sha256=${createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex")}`;
|
||||
const metadata = derivePublicApiSecretMetadata(secret, "test-hash-secret");
|
||||
|
||||
expect(
|
||||
verifyPublicWebhookHmacWithPresentedSecret({
|
||||
body,
|
||||
timestamp,
|
||||
signature,
|
||||
presentedSecret: secret,
|
||||
secretHash: metadata.hash,
|
||||
hashSecret: "test-hash-secret",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
verifyPublicWebhookHmacWithPresentedSecret({
|
||||
body,
|
||||
timestamp,
|
||||
signature: "sha256=bad",
|
||||
presentedSecret: secret,
|
||||
secretHash: metadata.hash,
|
||||
hashSecret: "test-hash-secret",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("creates deterministic outgoing HMAC headers and idempotency keys", () => {
|
||||
const payload = { b: 2, a: 1 };
|
||||
const signingSecret = derivePublicWebhookSigningSecret({ tenantId: "tenant_1", subscriptionId: "subscription_1" }, "test-hash-secret");
|
||||
const headers = createPublicWebhookDeliveryHeaders({
|
||||
eventType: "contact.created",
|
||||
deliveryId: "delivery_1",
|
||||
idempotencyKey: buildPublicWebhookIdempotencyKey({
|
||||
subscriptionId: "subscription_1",
|
||||
eventType: "contact.created",
|
||||
sourceEventId: "event_1",
|
||||
payloadHash: hashJsonValue(payload),
|
||||
}),
|
||||
payload,
|
||||
signingSecret,
|
||||
timestamp: new Date("2026-07-03T00:00:00.000Z"),
|
||||
});
|
||||
|
||||
expect(headers["X-HiveGrid-Event"]).toBe("contact.created");
|
||||
expect(headers["X-HiveGrid-Delivery"]).toBe("delivery_1");
|
||||
expect(headers["X-HiveGrid-Idempotency-Key"]).toBe("subscription_1:contact.created:event_1");
|
||||
expect(headers["X-HiveGrid-Signature"]).toMatch(/^sha256=[a-f0-9]{64}$/);
|
||||
});
|
||||
|
||||
test("plans exponential retry delays from the current attempt", () => {
|
||||
const now = new Date("2026-07-03T00:00:00.000Z");
|
||||
|
||||
expect(planPublicWebhookRetry({ attempt: 1, now, baseDelayMs: 1_000 }).toISOString()).toBe("2026-07-03T00:00:01.000Z");
|
||||
expect(planPublicWebhookRetry({ attempt: 4, now, baseDelayMs: 1_000 }).toISOString()).toBe("2026-07-03T00:00:08.000Z");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,643 @@
|
||||
import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
||||
|
||||
import { getDbClient } from "./client.server.js";
|
||||
import type {
|
||||
InboxLead,
|
||||
Prisma,
|
||||
PublicIncomingWebhookEndpoint,
|
||||
PublicWebhookAuthMode,
|
||||
PublicWebhookDeliveryLog,
|
||||
PublicWebhookDeliveryStatus,
|
||||
PublicWebhookIngestionLog,
|
||||
PublicWebhookSubscription,
|
||||
} from "./prisma-browser.js";
|
||||
|
||||
export const PUBLIC_API_SECRET_HASH_VERSION = 1;
|
||||
export const DEFAULT_PUBLIC_API_SECRET_HASH_SECRET = "public-api-secret-v1";
|
||||
export const PUBLIC_WEBHOOK_MAX_DELIVERY_ATTEMPTS = 5;
|
||||
export const PUBLIC_WEBHOOK_AUTO_DISABLE_FAILURES = 10;
|
||||
|
||||
export type PublicApiSecretMetadata = {
|
||||
hash: string;
|
||||
prefix: string;
|
||||
lastFour: string;
|
||||
};
|
||||
|
||||
export type PublicWebhookEndpointWithSecret = PublicIncomingWebhookEndpoint & {
|
||||
plaintextSecret: string | null;
|
||||
};
|
||||
|
||||
export type PublicWebhookSubscriptionWithSecret = PublicWebhookSubscription & {
|
||||
plaintextSecret: string;
|
||||
};
|
||||
|
||||
export type CreatePublicIncomingWebhookEndpointInput = {
|
||||
tenantId: string;
|
||||
slug: string;
|
||||
name: string;
|
||||
authMode: PublicWebhookAuthMode;
|
||||
apiKeyId?: string | null;
|
||||
payloadMapping?: Prisma.InputJsonValue;
|
||||
autoMatchRules?: Prisma.InputJsonValue;
|
||||
isDemoData?: boolean;
|
||||
};
|
||||
|
||||
export type CreatePublicWebhookSubscriptionInput = {
|
||||
tenantId: string;
|
||||
name: string;
|
||||
targetUrl: string;
|
||||
eventTypes: readonly string[];
|
||||
createdByUserId?: string | null;
|
||||
isDemoData?: boolean;
|
||||
};
|
||||
|
||||
export type PublicWebhookPayload = Prisma.InputJsonValue;
|
||||
|
||||
export type IngestPublicLeadWebhookInput = {
|
||||
tenantId: string;
|
||||
endpoint: Pick<PublicIncomingWebhookEndpoint, "id" | "slug" | "authMode" | "payloadMapping" | "autoMatchRules">;
|
||||
payload: PublicWebhookPayload;
|
||||
requestId?: string | null;
|
||||
sourceIp?: string | null;
|
||||
};
|
||||
|
||||
export type IngestPublicLeadWebhookResult = {
|
||||
lead: InboxLead;
|
||||
log: PublicWebhookIngestionLog;
|
||||
matchedKontaktId: string | null;
|
||||
automationExecutionIds: string[];
|
||||
};
|
||||
|
||||
export type EnqueuePublicWebhookEventInput = {
|
||||
tenantId: string;
|
||||
eventType: string;
|
||||
payload: PublicWebhookPayload;
|
||||
sourceEventId?: string | null;
|
||||
};
|
||||
|
||||
export type EnqueuePublicWebhookEventResult = {
|
||||
deliveries: PublicWebhookDeliveryLog[];
|
||||
};
|
||||
|
||||
export type DeliverPublicWebhookInput = {
|
||||
deliveryId: string;
|
||||
tenantId: string;
|
||||
payload: PublicWebhookPayload;
|
||||
fetcher?: typeof fetch;
|
||||
hashSecret?: string | null;
|
||||
};
|
||||
|
||||
export type PublicWebhookDeliveryHeaders = {
|
||||
"Content-Type": "application/json";
|
||||
"X-HiveGrid-Event": string;
|
||||
"X-HiveGrid-Delivery": string;
|
||||
"X-HiveGrid-Idempotency-Key": string;
|
||||
"X-HiveGrid-Timestamp": string;
|
||||
"X-HiveGrid-Signature": string;
|
||||
};
|
||||
|
||||
type PublicApiClient = ReturnType<typeof getDbClient>;
|
||||
|
||||
export function generatePublicApiSecret(): string {
|
||||
return `hgwh_${randomBytes(32).toString("base64url")}`;
|
||||
}
|
||||
|
||||
export function derivePublicWebhookSigningSecret(input: { tenantId: string; subscriptionId: string }, hashSecret?: string | null): string {
|
||||
const secret = normalizePublicApiSecretHashSecret(hashSecret);
|
||||
const digest = createHmac("sha256", secret).update(`${input.tenantId}:${input.subscriptionId}`).digest("base64url");
|
||||
return `hgwh_${digest}`;
|
||||
}
|
||||
|
||||
export function derivePublicApiSecretMetadata(secret: string, hashSecret?: string | null): PublicApiSecretMetadata {
|
||||
const normalizedSecret = normalizePublicApiSecretHashSecret(hashSecret);
|
||||
return {
|
||||
hash: createHmac("sha256", normalizedSecret).update(secret).digest("hex"),
|
||||
prefix: secret.slice(0, 10),
|
||||
lastFour: secret.slice(-4),
|
||||
};
|
||||
}
|
||||
|
||||
export function verifyPublicApiSecret(secret: string, expectedHash: string | null | undefined, hashSecret?: string | null): boolean {
|
||||
if (!expectedHash) {
|
||||
return false;
|
||||
}
|
||||
const actual = derivePublicApiSecretMetadata(secret, hashSecret).hash;
|
||||
return safeEqual(actual, expectedHash);
|
||||
}
|
||||
|
||||
export async function createPublicIncomingWebhookEndpoint(
|
||||
input: CreatePublicIncomingWebhookEndpointInput,
|
||||
client: PublicApiClient = getDbClient(),
|
||||
hashSecret?: string | null,
|
||||
): Promise<PublicWebhookEndpointWithSecret> {
|
||||
const plaintextSecret = input.authMode === "api_key" ? null : generatePublicApiSecret();
|
||||
const metadata = plaintextSecret ? derivePublicApiSecretMetadata(plaintextSecret, hashSecret) : null;
|
||||
const endpoint = await client.publicIncomingWebhookEndpoint.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
slug: input.slug,
|
||||
name: input.name,
|
||||
authMode: input.authMode,
|
||||
apiKeyId: input.apiKeyId ?? null,
|
||||
tokenHash: input.authMode === "url_token" ? metadata?.hash : null,
|
||||
tokenPrefix: input.authMode === "url_token" ? metadata?.prefix : null,
|
||||
tokenLastFour: input.authMode === "url_token" ? metadata?.lastFour : null,
|
||||
hmacSecretHash: input.authMode === "hmac" ? metadata?.hash : null,
|
||||
hmacSecretPrefix: input.authMode === "hmac" ? metadata?.prefix : null,
|
||||
hmacSecretLastFour: input.authMode === "hmac" ? metadata?.lastFour : null,
|
||||
payloadMapping: input.payloadMapping ?? {},
|
||||
autoMatchRules: input.autoMatchRules ?? {},
|
||||
isDemoData: input.isDemoData ?? false,
|
||||
},
|
||||
});
|
||||
|
||||
return { ...endpoint, plaintextSecret };
|
||||
}
|
||||
|
||||
export async function findPublicIncomingWebhookEndpoint(
|
||||
input: { tenantId: string; slug: string },
|
||||
client: PublicApiClient = getDbClient(),
|
||||
): Promise<PublicIncomingWebhookEndpoint | null> {
|
||||
return client.publicIncomingWebhookEndpoint.findFirst({
|
||||
where: {
|
||||
tenantId: input.tenantId,
|
||||
slug: input.slug,
|
||||
archivedAt: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createPublicWebhookIngestionLog(
|
||||
data: Prisma.PublicWebhookIngestionLogUncheckedCreateInput,
|
||||
client: PublicApiClient = getDbClient(),
|
||||
): Promise<PublicWebhookIngestionLog> {
|
||||
return client.publicWebhookIngestionLog.create({ data });
|
||||
}
|
||||
|
||||
export async function ingestPublicLeadWebhook(
|
||||
input: IngestPublicLeadWebhookInput,
|
||||
client: PublicApiClient = getDbClient(),
|
||||
): Promise<IngestPublicLeadWebhookResult> {
|
||||
const payloadHash = hashJsonValue(input.payload);
|
||||
const extracted = extractLeadFields(input.payload, input.endpoint.payloadMapping);
|
||||
return client.$transaction(async (tx) => {
|
||||
await tx.$executeRaw`SELECT set_config('app.tenant_id', ${input.tenantId}, true)`;
|
||||
const matchedKontaktId = await findMatchingKontaktId(tx, input.tenantId, extracted.email, extracted.telefon);
|
||||
const lead = await tx.inboxLead.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
quelle: "custom",
|
||||
quelleDetail: {
|
||||
source: "public_api_webhook",
|
||||
endpointId: input.endpoint.id,
|
||||
endpointSlug: input.endpoint.slug,
|
||||
requestId: input.requestId ?? null,
|
||||
},
|
||||
sourceOrigin: `public_api:${input.endpoint.slug}`,
|
||||
status: "new",
|
||||
vorname: extracted.vorname,
|
||||
nachname: extracted.nachname,
|
||||
email: extracted.email,
|
||||
telefon: extracted.telefon,
|
||||
message: extracted.message,
|
||||
rohdaten: input.payload,
|
||||
verknuepfterKontaktId: matchedKontaktId,
|
||||
},
|
||||
});
|
||||
const automationExecutionIds = await createWebhookAutomationExecutions(tx, {
|
||||
tenantId: input.tenantId,
|
||||
endpointId: input.endpoint.id,
|
||||
endpointSlug: input.endpoint.slug,
|
||||
leadId: lead.id,
|
||||
payload: input.payload,
|
||||
payloadHash,
|
||||
sourceEventId: input.requestId,
|
||||
});
|
||||
const log = await tx.publicWebhookIngestionLog.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
endpointId: input.endpoint.id,
|
||||
endpointSlug: input.endpoint.slug,
|
||||
authMode: input.endpoint.authMode,
|
||||
requestId: input.requestId ?? null,
|
||||
sourceIp: input.sourceIp ?? null,
|
||||
status: 201,
|
||||
result: "lead_created",
|
||||
payloadHash,
|
||||
payloadPreview: createPayloadPreview(input.payload),
|
||||
leadId: lead.id,
|
||||
matchedKontaktId,
|
||||
automationRunId: automationExecutionIds[0] ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
return { lead, log, matchedKontaktId, automationExecutionIds };
|
||||
});
|
||||
}
|
||||
|
||||
export async function createPublicWebhookSubscription(
|
||||
input: CreatePublicWebhookSubscriptionInput,
|
||||
client: PublicApiClient = getDbClient(),
|
||||
hashSecret?: string | null,
|
||||
): Promise<PublicWebhookSubscriptionWithSecret> {
|
||||
const id = randomUUID();
|
||||
const plaintextSecret = derivePublicWebhookSigningSecret({ tenantId: input.tenantId, subscriptionId: id }, hashSecret);
|
||||
const metadata = derivePublicApiSecretMetadata(plaintextSecret, hashSecret);
|
||||
const subscription = await client.publicWebhookSubscription.create({
|
||||
data: {
|
||||
id,
|
||||
tenantId: input.tenantId,
|
||||
name: input.name,
|
||||
targetUrl: input.targetUrl,
|
||||
eventTypes: [...new Set(input.eventTypes.filter(Boolean))],
|
||||
signingSecretHash: metadata.hash,
|
||||
signingSecretPrefix: metadata.prefix,
|
||||
signingSecretLastFour: metadata.lastFour,
|
||||
createdByUserId: input.createdByUserId ?? null,
|
||||
isDemoData: input.isDemoData ?? false,
|
||||
},
|
||||
});
|
||||
|
||||
return { ...subscription, plaintextSecret };
|
||||
}
|
||||
|
||||
export async function enqueuePublicWebhookEvent(
|
||||
input: EnqueuePublicWebhookEventInput,
|
||||
client: PublicApiClient = getDbClient(),
|
||||
): Promise<EnqueuePublicWebhookEventResult> {
|
||||
const payloadHash = hashJsonValue(input.payload);
|
||||
const subscriptions = await client.publicWebhookSubscription.findMany({
|
||||
where: {
|
||||
tenantId: input.tenantId,
|
||||
status: "active",
|
||||
archivedAt: null,
|
||||
},
|
||||
});
|
||||
const matching = subscriptions.filter((subscription) => subscriptionMatchesEvent(subscription.eventTypes, input.eventType));
|
||||
const deliveries = await Promise.all(
|
||||
matching.map((subscription) =>
|
||||
client.publicWebhookDeliveryLog.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
subscriptionId: subscription.id,
|
||||
eventType: input.eventType,
|
||||
targetUrl: subscription.targetUrl,
|
||||
status: "queued",
|
||||
idempotencyKey: buildPublicWebhookIdempotencyKey({
|
||||
subscriptionId: subscription.id,
|
||||
eventType: input.eventType,
|
||||
sourceEventId: input.sourceEventId,
|
||||
payloadHash,
|
||||
}),
|
||||
payloadHash,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
return { deliveries };
|
||||
}
|
||||
|
||||
export async function markPublicWebhookDeliveryResult(
|
||||
input: {
|
||||
deliveryId: string;
|
||||
tenantId: string;
|
||||
ok: boolean;
|
||||
httpStatus?: number | null;
|
||||
error?: string | null;
|
||||
responsePreview?: Prisma.InputJsonValue;
|
||||
now?: Date;
|
||||
},
|
||||
client: PublicApiClient = getDbClient(),
|
||||
): Promise<PublicWebhookDeliveryLog> {
|
||||
const now = input.now ?? new Date();
|
||||
return client.$transaction(async (tx) => {
|
||||
const delivery = await tx.publicWebhookDeliveryLog.findFirst({
|
||||
where: { id: input.deliveryId, tenantId: input.tenantId },
|
||||
include: { subscription: true },
|
||||
});
|
||||
if (!delivery) {
|
||||
throw new Error("Public webhook delivery not found");
|
||||
}
|
||||
|
||||
if (input.ok) {
|
||||
await tx.publicWebhookSubscription.update({
|
||||
where: { id: delivery.subscriptionId },
|
||||
data: { failureCount: 0, lastDeliveredAt: now, lastErrorAt: null },
|
||||
});
|
||||
return tx.publicWebhookDeliveryLog.update({
|
||||
where: { id: delivery.id },
|
||||
data: { status: "success", httpStatus: input.httpStatus ?? null, error: null, responsePreview: input.responsePreview ?? undefined, sentAt: now, nextAttemptAt: null },
|
||||
});
|
||||
}
|
||||
|
||||
const nextAttempt = delivery.attempt + 1;
|
||||
const nextFailureCount = delivery.subscription.failureCount + 1;
|
||||
const exhaustedDelivery = nextAttempt > delivery.maxAttempts;
|
||||
const shouldDisable = nextFailureCount >= PUBLIC_WEBHOOK_AUTO_DISABLE_FAILURES;
|
||||
const nextStatus: PublicWebhookDeliveryStatus = shouldDisable ? "disabled" : exhaustedDelivery ? "failed" : "retrying";
|
||||
const nextAttemptAt = nextStatus === "retrying" ? planPublicWebhookRetry({ attempt: delivery.attempt, now }) : null;
|
||||
await tx.publicWebhookSubscription.update({
|
||||
where: { id: delivery.subscriptionId },
|
||||
data: {
|
||||
failureCount: nextFailureCount,
|
||||
lastErrorAt: now,
|
||||
...(shouldDisable ? { status: "paused", autoDisabledAt: now, pausedAt: now } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
return tx.publicWebhookDeliveryLog.update({
|
||||
where: { id: delivery.id },
|
||||
data: {
|
||||
status: nextStatus,
|
||||
httpStatus: input.httpStatus ?? null,
|
||||
error: input.error ?? null,
|
||||
responsePreview: input.responsePreview ?? undefined,
|
||||
nextAttemptAt,
|
||||
attempt: exhaustedDelivery || shouldDisable ? delivery.attempt : nextAttempt,
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function deliverPublicWebhook(
|
||||
input: DeliverPublicWebhookInput,
|
||||
client: PublicApiClient = getDbClient(),
|
||||
): Promise<PublicWebhookDeliveryLog> {
|
||||
const delivery = await client.publicWebhookDeliveryLog.findFirst({
|
||||
where: { id: input.deliveryId, tenantId: input.tenantId },
|
||||
include: { subscription: true },
|
||||
});
|
||||
if (!delivery) {
|
||||
throw new Error("Public webhook delivery not found");
|
||||
}
|
||||
if (delivery.subscription.status !== "active" || delivery.status === "success" || delivery.status === "disabled") {
|
||||
return delivery;
|
||||
}
|
||||
|
||||
await client.publicWebhookDeliveryLog.update({
|
||||
where: { id: delivery.id },
|
||||
data: { status: "delivering" },
|
||||
});
|
||||
|
||||
const headers = createPublicWebhookDeliveryHeadersForSubscription({
|
||||
subscription: delivery.subscription,
|
||||
eventType: delivery.eventType,
|
||||
deliveryId: delivery.id,
|
||||
idempotencyKey: delivery.idempotencyKey,
|
||||
payload: input.payload,
|
||||
hashSecret: input.hashSecret,
|
||||
});
|
||||
|
||||
try {
|
||||
const response = await (input.fetcher ?? fetch)(delivery.targetUrl, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: stableStringify(input.payload),
|
||||
});
|
||||
const responsePreview = await readWebhookResponsePreview(response);
|
||||
return markPublicWebhookDeliveryResult(
|
||||
{
|
||||
deliveryId: delivery.id,
|
||||
tenantId: delivery.tenantId,
|
||||
ok: response.ok,
|
||||
httpStatus: response.status,
|
||||
error: response.ok ? null : `Webhook target returned HTTP ${response.status}.`,
|
||||
responsePreview,
|
||||
},
|
||||
client,
|
||||
);
|
||||
} catch (error) {
|
||||
return markPublicWebhookDeliveryResult(
|
||||
{
|
||||
deliveryId: delivery.id,
|
||||
tenantId: delivery.tenantId,
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.name : "WebhookDeliveryError",
|
||||
},
|
||||
client,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function createPublicWebhookDeliveryHeaders(input: {
|
||||
eventType: string;
|
||||
deliveryId: string;
|
||||
idempotencyKey: string;
|
||||
payload: PublicWebhookPayload;
|
||||
signingSecret: string;
|
||||
timestamp?: Date;
|
||||
}): PublicWebhookDeliveryHeaders {
|
||||
const timestamp = Math.floor((input.timestamp ?? new Date()).getTime() / 1000).toString();
|
||||
const body = stableStringify(input.payload);
|
||||
const signature = createHmac("sha256", input.signingSecret).update(`${timestamp}.${body}`).digest("hex");
|
||||
return {
|
||||
"Content-Type": "application/json",
|
||||
"X-HiveGrid-Event": input.eventType,
|
||||
"X-HiveGrid-Delivery": input.deliveryId,
|
||||
"X-HiveGrid-Idempotency-Key": input.idempotencyKey,
|
||||
"X-HiveGrid-Timestamp": timestamp,
|
||||
"X-HiveGrid-Signature": `sha256=${signature}`,
|
||||
};
|
||||
}
|
||||
|
||||
export function createPublicWebhookDeliveryHeadersForSubscription(input: {
|
||||
subscription: Pick<PublicWebhookSubscription, "id" | "tenantId">;
|
||||
eventType: string;
|
||||
deliveryId: string;
|
||||
idempotencyKey: string;
|
||||
payload: PublicWebhookPayload;
|
||||
hashSecret?: string | null;
|
||||
timestamp?: Date;
|
||||
}): PublicWebhookDeliveryHeaders {
|
||||
return createPublicWebhookDeliveryHeaders({
|
||||
eventType: input.eventType,
|
||||
deliveryId: input.deliveryId,
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
payload: input.payload,
|
||||
signingSecret: derivePublicWebhookSigningSecret(
|
||||
{ tenantId: input.subscription.tenantId, subscriptionId: input.subscription.id },
|
||||
input.hashSecret,
|
||||
),
|
||||
timestamp: input.timestamp,
|
||||
});
|
||||
}
|
||||
|
||||
export function verifyPublicWebhookHmacWithPresentedSecret(input: {
|
||||
body: string;
|
||||
timestamp: string | null;
|
||||
signature: string | null;
|
||||
presentedSecret: string | null;
|
||||
secretHash: string | null;
|
||||
hashSecret?: string | null;
|
||||
}): boolean {
|
||||
if (!input.timestamp || !input.signature || !input.presentedSecret || !verifyPublicApiSecret(input.presentedSecret, input.secretHash, input.hashSecret)) {
|
||||
return false;
|
||||
}
|
||||
const expected = `sha256=${createHmac("sha256", input.presentedSecret).update(`${input.timestamp}.${input.body}`).digest("hex")}`;
|
||||
return safeEqual(expected, input.signature);
|
||||
}
|
||||
|
||||
export function buildPublicWebhookIdempotencyKey(input: {
|
||||
subscriptionId: string;
|
||||
eventType: string;
|
||||
sourceEventId?: string | null;
|
||||
payloadHash: string;
|
||||
}): string {
|
||||
return [input.subscriptionId, input.eventType, input.sourceEventId || input.payloadHash].join(":");
|
||||
}
|
||||
|
||||
export function planPublicWebhookRetry(input: { attempt: number; now?: Date; baseDelayMs?: number }): Date {
|
||||
const baseDelayMs = input.baseDelayMs ?? 60_000;
|
||||
const delayMs = baseDelayMs * 2 ** Math.max(input.attempt - 1, 0);
|
||||
return new Date((input.now ?? new Date()).getTime() + delayMs);
|
||||
}
|
||||
|
||||
export function hashJsonValue(value: PublicWebhookPayload): string {
|
||||
return createHash("sha256").update(stableStringify(value)).digest("hex");
|
||||
}
|
||||
|
||||
function normalizePublicApiSecretHashSecret(secret: string | undefined | null): string {
|
||||
const normalized = secret?.trim();
|
||||
return normalized || DEFAULT_PUBLIC_API_SECRET_HASH_SECRET;
|
||||
}
|
||||
|
||||
function safeEqual(actual: string, expected: string): boolean {
|
||||
const actualBuffer = Buffer.from(actual);
|
||||
const expectedBuffer = Buffer.from(expected);
|
||||
return actualBuffer.length === expectedBuffer.length && timingSafeEqual(actualBuffer, expectedBuffer);
|
||||
}
|
||||
|
||||
function extractLeadFields(payload: PublicWebhookPayload, mapping: Prisma.JsonValue): { vorname: string | null; nachname: string | null; email: string | null; telefon: string | null; message: string | null } {
|
||||
const object = isRecord(payload) ? payload : {};
|
||||
const map = isRecord(mapping) ? mapping : {};
|
||||
return {
|
||||
vorname: readMappedString(object, map, "vorname", ["vorname", "firstName", "first_name", "contact.firstName"]),
|
||||
nachname: readMappedString(object, map, "nachname", ["nachname", "lastName", "last_name", "contact.lastName"]),
|
||||
email: normalizeEmail(readMappedString(object, map, "email", ["email", "contact.email", "from.email"])),
|
||||
telefon: readMappedString(object, map, "telefon", ["telefon", "phone", "telephone", "contact.phone"]),
|
||||
message: readMappedString(object, map, "message", ["message", "nachricht", "text", "body"]),
|
||||
};
|
||||
}
|
||||
|
||||
function readMappedString(object: Record<string, unknown>, mapping: Record<string, unknown>, key: string, fallbacks: readonly string[]): string | null {
|
||||
const mapped = typeof mapping[key] === "string" ? getPath(object, mapping[key]) : undefined;
|
||||
const value = mapped ?? fallbacks.map((path) => getPath(object, path)).find((item) => typeof item === "string" && item.trim());
|
||||
return typeof value === "string" && value.trim() ? value.trim().slice(0, 2_000) : null;
|
||||
}
|
||||
|
||||
function getPath(object: Record<string, unknown>, path: string): unknown {
|
||||
let current: unknown = object;
|
||||
for (const part of path.split(".")) {
|
||||
if (!isRecord(current)) {
|
||||
return undefined;
|
||||
}
|
||||
current = current[part];
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
async function findMatchingKontaktId(
|
||||
tx: Prisma.TransactionClient,
|
||||
tenantId: string,
|
||||
email: string | null,
|
||||
telefon: string | null,
|
||||
): Promise<string | null> {
|
||||
if (email) {
|
||||
const match = await tx.kontaktEmail.findFirst({
|
||||
where: { tenantId, email },
|
||||
select: { kontaktId: true },
|
||||
});
|
||||
if (match) return match.kontaktId;
|
||||
}
|
||||
if (telefon) {
|
||||
const match = await tx.kontaktTelefon.findFirst({
|
||||
where: { tenantId, telefon },
|
||||
select: { kontaktId: true },
|
||||
});
|
||||
if (match) return match.kontaktId;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function createWebhookAutomationExecutions(
|
||||
tx: Prisma.TransactionClient,
|
||||
input: { tenantId: string; endpointId: string; endpointSlug: string; leadId: string; payload: PublicWebhookPayload; payloadHash: string; sourceEventId?: string | null },
|
||||
): Promise<string[]> {
|
||||
const rules = await tx.automationRule.findMany({
|
||||
where: { tenantId: input.tenantId, triggerKey: "webhook.received", enabled: true, status: "active", archivedAt: null },
|
||||
select: { id: true, name: true },
|
||||
});
|
||||
const executions = await Promise.all(
|
||||
rules.map((rule) =>
|
||||
tx.automationExecution.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
ruleId: rule.id,
|
||||
triggerKey: "webhook.received",
|
||||
triggerPayload: {
|
||||
source: "external_event",
|
||||
endpointId: input.endpointId,
|
||||
endpointSlug: input.endpointSlug,
|
||||
leadId: input.leadId,
|
||||
payload: input.payload,
|
||||
},
|
||||
status: "queued",
|
||||
idempotencyKey: [input.tenantId, rule.id, "webhook.received", input.sourceEventId || input.payloadHash].join(":"),
|
||||
summaryText: `Webhook ${input.endpointSlug} queued automation ${rule.name}`,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
return executions.map((execution) => execution.id);
|
||||
}
|
||||
|
||||
function subscriptionMatchesEvent(eventTypes: Prisma.JsonValue, eventType: string): boolean {
|
||||
if (!Array.isArray(eventTypes)) {
|
||||
return false;
|
||||
}
|
||||
return eventTypes.includes("*") || eventTypes.includes(eventType);
|
||||
}
|
||||
|
||||
function createPayloadPreview(payload: PublicWebhookPayload): Prisma.InputJsonValue {
|
||||
if (!isRecord(payload)) {
|
||||
return payload;
|
||||
}
|
||||
const entries = Object.entries(payload).slice(0, 20).map(([key, value]) => [key, previewValue(value)]);
|
||||
return Object.fromEntries(entries);
|
||||
}
|
||||
|
||||
function previewValue(value: unknown): Prisma.InputJsonValue {
|
||||
if (typeof value === "string") return value.slice(0, 500);
|
||||
if (typeof value === "number" || typeof value === "boolean") return value;
|
||||
if (value === null) return "null";
|
||||
if (Array.isArray(value)) return value.slice(0, 10).map(previewValue);
|
||||
if (isRecord(value)) return Object.fromEntries(Object.entries(value).slice(0, 10).map(([key, item]) => [key, previewValue(item)]));
|
||||
return String(value);
|
||||
}
|
||||
|
||||
async function readWebhookResponsePreview(response: Response): Promise<Prisma.InputJsonValue> {
|
||||
const text = await response.text().catch(() => "");
|
||||
return {
|
||||
status: response.status,
|
||||
body: text.slice(0, 1_000),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeEmail(value: string | null): string | null {
|
||||
return value ? value.trim().toLowerCase() : null;
|
||||
}
|
||||
|
||||
function stableStringify(value: unknown): string {
|
||||
if (value === null || typeof value !== "object") {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return `[${value.map(stableStringify).join(",")}]`;
|
||||
}
|
||||
const entries = Object.entries(value as Record<string, unknown>).sort(([a], [b]) => a.localeCompare(b));
|
||||
return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`).join(",")}}`;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
-295
@@ -1,295 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,181 +0,0 @@
|
||||
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
@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { assertSafeSeedCredentials, runDbSeed, type DbSeedDiagnosticEvent } from "./seed.server.js";
|
||||
|
||||
describe("@toolctrl/db seed helpers", () => {
|
||||
describe("@hivegrid/db seed helpers", () => {
|
||||
it("rejects production seed runs with the default admin email before invoking the callback", async () => {
|
||||
const seed = vi.fn();
|
||||
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
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",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,225 +0,0 @@
|
||||
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,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
+20
-18
@@ -12,7 +12,6 @@ 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 = [
|
||||
@@ -29,10 +28,10 @@ const directBillingPrismaModels = [
|
||||
];
|
||||
|
||||
describe("subscription app boundary", () => {
|
||||
it.each(migratedWrappers)("keeps %s behind @toolctrl/db/subscriptions.server", (path) => {
|
||||
it.each(migratedWrappers)("keeps %s behind @hivegrid/db/subscriptions.server", (path) => {
|
||||
const source = readRepoFile(path);
|
||||
|
||||
expect(source).toContain("@toolctrl/db/subscriptions.server");
|
||||
expect(source).toContain("@hivegrid/db/subscriptions.server");
|
||||
expect(source).not.toContain("~/utils/db.server");
|
||||
expect(source).not.toContain("../../db.server");
|
||||
expect(source).not.toContain("../db.server");
|
||||
@@ -42,10 +41,10 @@ describe("subscription app boundary", () => {
|
||||
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("@hivegrid/db/subscriptions.server");
|
||||
expect(source).toContain("../../db.server");
|
||||
expect(source).toContain("clearCacheKey");
|
||||
expect(source).toContain("cancelStripeSubscription");
|
||||
expect(source).toContain("cancelTenantSubscription");
|
||||
expect(source).toContain("EventsService.create");
|
||||
|
||||
for (const model of directBillingPrismaModels) {
|
||||
@@ -53,20 +52,23 @@ describe("subscription app boundary", () => {
|
||||
}
|
||||
});
|
||||
|
||||
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",
|
||||
];
|
||||
it("keeps tenant subscription settings writes behind cache-clearing web wrappers", () => {
|
||||
const source = readRepoFile("apps/web/app/routes/app.$tenant/settings/subscription.tsx");
|
||||
const directPackageImport = source.match(/import\s+\{([^}]+)\}\s+from\s+["']@hivegrid\/db\/subscriptions\.server["']/s);
|
||||
const importedNames = directPackageImport?.[1] ?? "";
|
||||
|
||||
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");
|
||||
});
|
||||
|
||||
expect(importedNames).not.toMatch(/\bcreateTenantSubscription\b/);
|
||||
expect(importedNames).not.toMatch(/\bupdateTenantSubscriptionCustomerId\b/);
|
||||
expect(source).toContain("~/utils/db/tenantSubscriptions.db.server");
|
||||
}
|
||||
it("keeps the legacy subscribe route free of in-app checkout writes and plan UI", () => {
|
||||
const source = readRepoFile("apps/web/app/routes/subscribe.$tenant.tsx");
|
||||
|
||||
expect(source).not.toContain("@hivegrid/db/subscriptions.server");
|
||||
expect(source).not.toContain("~/utils/db/tenantSubscriptions.db.server");
|
||||
expect(source).not.toContain("createCheckoutSession");
|
||||
expect(source).not.toContain("createBillingCustomer");
|
||||
expect(source).not.toContain("PlansGrouped");
|
||||
});
|
||||
});
|
||||
+61
-47
@@ -17,36 +17,36 @@ import {
|
||||
deleteSubscriptionProduct,
|
||||
deleteSubscriptionUsageBasedPrice,
|
||||
deleteSubscriptionUsageBasedTier,
|
||||
findTenantSubscriptionProductByStripeSubscriptionId,
|
||||
findTenantSubscriptionProductByBillingProviderSubscriptionId,
|
||||
getEffectiveTenantEntitlementPlanId,
|
||||
getAllSubscriptionFeatures,
|
||||
getAllSubscriptionProducts,
|
||||
getAllSubscriptionProductsWithTenants,
|
||||
getSubscriptionPrice,
|
||||
getSubscriptionPriceByStripeId,
|
||||
getSubscriptionPriceByBillingProviderId,
|
||||
getSubscriptionPrices,
|
||||
getSubscriptionProduct,
|
||||
getSubscriptionProductByStripeId,
|
||||
getSubscriptionProductByBillingProviderId,
|
||||
getSubscriptionProductsInIds,
|
||||
getSubscriptionUsageBasedPriceByStripeId,
|
||||
getSubscriptionUsageBasedPriceByBillingProviderId,
|
||||
getTenantSubscription,
|
||||
getTenantSubscriptionProduct,
|
||||
getTenantSubscriptionProductById,
|
||||
getTenantSubscriptionProductByStripeSubscriptionId,
|
||||
getTenantSubscriptionProductByBillingProviderSubscriptionId,
|
||||
getTenantSubscriptions,
|
||||
getAllTenantSubscriptionProducts,
|
||||
getCheckoutSessionStatus,
|
||||
listTenantSubscriptionIds,
|
||||
updateCheckoutSessionStatus,
|
||||
updateSubscriptionPrice,
|
||||
updateSubscriptionPriceStripeId,
|
||||
updateSubscriptionPriceBillingProviderId,
|
||||
updateSubscriptionProduct,
|
||||
updateSubscriptionProductStripeId,
|
||||
updateSubscriptionProductBillingProviderId,
|
||||
updateTenantSubscriptionCustomerId,
|
||||
updateTenantSubscriptionProduct,
|
||||
updateTenantSubscriptionProductCustomEntitlementPlan,
|
||||
updateTenantSubscriptionProductFromStripe,
|
||||
type StripeTenantSubscriptionProductClient,
|
||||
updateTenantSubscriptionProductFromBillingProvider,
|
||||
type BillingProviderTenantSubscriptionProductClient,
|
||||
type SubscriptionCatalogClient,
|
||||
type TenantBillingClient,
|
||||
type TenantSubscriptionReaderClient,
|
||||
@@ -96,13 +96,13 @@ function createTenantSubscriptionClient(items: unknown[] = []): TenantSubscripti
|
||||
} as unknown as TenantSubscriptionReaderClient;
|
||||
}
|
||||
|
||||
function createStripeTenantSubscriptionProductClient(item: unknown = null): StripeTenantSubscriptionProductClient {
|
||||
function createBillingProviderTenantSubscriptionProductClient(item: unknown = null): BillingProviderTenantSubscriptionProductClient {
|
||||
return {
|
||||
tenantSubscriptionProduct: {
|
||||
findFirst: vi.fn().mockResolvedValue(item),
|
||||
update: vi.fn().mockResolvedValue({ tenantSubscription: { tenantId: "tenant_1" } }),
|
||||
},
|
||||
} as unknown as StripeTenantSubscriptionProductClient;
|
||||
} as unknown as BillingProviderTenantSubscriptionProductClient;
|
||||
}
|
||||
|
||||
function createTenantBillingClient(items: unknown[] = []): TenantBillingClient {
|
||||
@@ -111,7 +111,7 @@ function createTenantBillingClient(items: unknown[] = []): TenantBillingClient {
|
||||
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" }),
|
||||
update: vi.fn().mockResolvedValue(items[0] ?? { id: "tenant_sub_1", tenantId: "tenant_1", billingProviderCustomerId: "cus_1" }),
|
||||
},
|
||||
tenantSubscriptionProduct: {
|
||||
findMany: vi.fn().mockResolvedValue(items),
|
||||
@@ -213,19 +213,19 @@ describe("subscription product reads", () => {
|
||||
|
||||
await expect(getAllSubscriptionFeatures(client)).resolves.toEqual([]);
|
||||
expect(client.subscriptionFeature.findMany).toHaveBeenCalledWith({
|
||||
select: { name: true, order: true, title: true, type: true, value: true, accumulate: true },
|
||||
select: { name: true, code: 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" };
|
||||
it("fetches a product by billing provider id", async () => {
|
||||
const product = { id: "plan_a", billingProviderId: "prod_123" };
|
||||
const client = createSubscriptionProductClient([product]);
|
||||
|
||||
await expect(getSubscriptionProductByStripeId("prod_123", client)).resolves.toBe(product);
|
||||
await expect(getSubscriptionProductByBillingProviderId("prod_123", client)).resolves.toBe(product);
|
||||
expect(client.subscriptionProduct.findFirst).toHaveBeenCalledWith({
|
||||
where: { stripeId: "prod_123" },
|
||||
where: { billingProviderId: "prod_123" },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -248,14 +248,14 @@ describe("subscription catalog helpers", () => {
|
||||
|
||||
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();
|
||||
await expect(getSubscriptionPriceByBillingProviderId("price_provider_1", client)).resolves.toBeNull();
|
||||
await expect(getSubscriptionUsageBasedPriceByBillingProviderId("metered_provider_1", client)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it("creates catalog rows without coercing decimal-compatible values", async () => {
|
||||
const client = createSubscriptionProductClient([]);
|
||||
const productData = {
|
||||
stripeId: "prod_123",
|
||||
billingProviderId: "prod_123",
|
||||
order: 1,
|
||||
title: "Pro",
|
||||
model: 1,
|
||||
@@ -271,7 +271,7 @@ describe("subscription catalog helpers", () => {
|
||||
};
|
||||
const priceData = {
|
||||
subscriptionProductId: "plan_a",
|
||||
stripeId: "price_123",
|
||||
billingProviderId: "price_123",
|
||||
type: 1,
|
||||
billingPeriod: 1,
|
||||
price: "19.99",
|
||||
@@ -281,7 +281,7 @@ describe("subscription catalog helpers", () => {
|
||||
};
|
||||
const usagePriceData = {
|
||||
subscriptionProductId: "plan_a",
|
||||
stripeId: "metered_123",
|
||||
billingProviderId: "metered_123",
|
||||
currency: "usd",
|
||||
billingPeriod: 1,
|
||||
unit: "api_call",
|
||||
@@ -338,9 +338,9 @@ describe("subscription catalog helpers", () => {
|
||||
const client = createSubscriptionProductClient([]);
|
||||
|
||||
await updateSubscriptionProduct("plan_a", { title: "Business", public: false }, client);
|
||||
await updateSubscriptionProductStripeId("plan_a", { stripeId: "prod_new" }, client);
|
||||
await updateSubscriptionProductBillingProviderId("plan_a", { billingProviderId: "prod_new" }, client);
|
||||
await updateSubscriptionPrice("price_a", { price: "29.99", active: false }, client);
|
||||
await updateSubscriptionPriceStripeId("price_a", { stripeId: "price_new" }, client);
|
||||
await updateSubscriptionPriceBillingProviderId("price_a", { billingProviderId: "price_new" }, client);
|
||||
|
||||
expect(client.subscriptionProduct.update).toHaveBeenNthCalledWith(1, {
|
||||
where: { id: "plan_a" },
|
||||
@@ -348,7 +348,7 @@ describe("subscription catalog helpers", () => {
|
||||
});
|
||||
expect(client.subscriptionProduct.update).toHaveBeenNthCalledWith(2, {
|
||||
where: { id: "plan_a" },
|
||||
data: { stripeId: "prod_new" },
|
||||
data: { billingProviderId: "prod_new" },
|
||||
});
|
||||
expect(client.subscriptionPrice.update).toHaveBeenNthCalledWith(1, {
|
||||
where: { id: "price_a" },
|
||||
@@ -356,7 +356,7 @@ describe("subscription catalog helpers", () => {
|
||||
});
|
||||
expect(client.subscriptionPrice.update).toHaveBeenNthCalledWith(2, {
|
||||
where: { id: "price_a" },
|
||||
data: { stripeId: "price_new" },
|
||||
data: { billingProviderId: "price_new" },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -376,7 +376,7 @@ describe("subscription catalog helpers", () => {
|
||||
expect(client.subscriptionFeature.deleteMany).toHaveBeenCalledWith({ where: { subscriptionProductId: "plan_a" } });
|
||||
});
|
||||
|
||||
it("propagates mutation failures instead of hiding failed Stripe sync", async () => {
|
||||
it("propagates mutation failures instead of hiding failed billing provider sync", async () => {
|
||||
const client = createSubscriptionProductClient([]);
|
||||
const error = new Error("write failed");
|
||||
vi.mocked(client.subscriptionPrice.update).mockRejectedValueOnce(error);
|
||||
@@ -427,12 +427,12 @@ 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 createTenantSubscription({ tenantId: "tenant_1", billingProviderCustomerId: "cus_1" }, client);
|
||||
await updateTenantSubscriptionCustomerId("tenant_1", { billingProviderCustomerId: "cus_2" }, client);
|
||||
await expect(listTenantSubscriptionIds(client)).resolves.toEqual([{ tenantId: "tenant_1" }]);
|
||||
|
||||
expect(client.tenantSubscription.create).toHaveBeenCalledWith({
|
||||
data: { tenantId: "tenant_1", stripeCustomerId: "cus_1" },
|
||||
data: { tenantId: "tenant_1", billingProviderCustomerId: "cus_1" },
|
||||
include: {
|
||||
products: {
|
||||
include: {
|
||||
@@ -445,7 +445,7 @@ describe("tenant billing boundary", () => {
|
||||
});
|
||||
expect(client.tenantSubscription.update).toHaveBeenCalledWith({
|
||||
where: { tenantId: "tenant_1" },
|
||||
data: { stripeCustomerId: "cus_2" },
|
||||
data: { billingProviderCustomerId: "cus_2" },
|
||||
});
|
||||
expect(client.tenantSubscription.findMany).toHaveBeenCalledWith({ select: { tenantId: true } });
|
||||
});
|
||||
@@ -518,21 +518,21 @@ describe("tenant billing boundary", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("looks up tenant products by tenant/product, id, and Stripe subscription id", async () => {
|
||||
it("looks up tenant products by tenant/product, id, and Billing provider 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);
|
||||
await expect(getTenantSubscriptionProductByBillingProviderSubscriptionId("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" } }));
|
||||
expect(client.tenantSubscriptionProduct.findFirst).toHaveBeenNthCalledWith(3, expect.objectContaining({ where: { billingProviderSubscriptionId: "sub_1" } }));
|
||||
});
|
||||
|
||||
it("uses the billing product id when no custom entitlement override exists", () => {
|
||||
@@ -560,7 +560,7 @@ describe("tenant billing boundary", () => {
|
||||
{
|
||||
tenantSubscriptionId: "tenant_sub_1",
|
||||
subscriptionProductId: "plan_1",
|
||||
stripeSubscriptionId: "sub_1",
|
||||
billingProviderSubscriptionId: "sub_1",
|
||||
quantity: 2,
|
||||
fromCheckoutSessionId: "cs_1",
|
||||
prices: [{ subscriptionPriceId: "price_1" }, { subscriptionUsageBasedPriceId: "usage_price_1" }],
|
||||
@@ -580,7 +580,7 @@ describe("tenant billing boundary", () => {
|
||||
data: {
|
||||
tenantSubscriptionId: "tenant_sub_1",
|
||||
subscriptionProductId: "plan_1",
|
||||
stripeSubscriptionId: "sub_1",
|
||||
billingProviderSubscriptionId: "sub_1",
|
||||
quantity: 2,
|
||||
fromCheckoutSessionId: "cs_1",
|
||||
customEntitlementPlanId: undefined,
|
||||
@@ -645,21 +645,35 @@ describe("tenant billing boundary", () => {
|
||||
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 },
|
||||
data: expect.objectContaining({
|
||||
id: "cs_1",
|
||||
pending: true,
|
||||
email: "user@example.com",
|
||||
fromUrl: "/subscribe/acme",
|
||||
fromUserId: null,
|
||||
fromTenantId: null,
|
||||
provider: null,
|
||||
providerPaymentId: null,
|
||||
quantity: 1,
|
||||
status: "open",
|
||||
}),
|
||||
});
|
||||
expect(client.checkoutSessionStatus.update).toHaveBeenCalledWith({
|
||||
where: { id: "cs_1" },
|
||||
data: { pending: false, createdUserId: "user_1", createdTenantId: null },
|
||||
data: expect.objectContaining({ 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 = {
|
||||
tenantId: "tenant_1",
|
||||
tenantSubscriptionId: "tenant_subscription_1",
|
||||
tenantSubscriptionProductPriceId: "tenant_price_1",
|
||||
metricCode: "usage_metric",
|
||||
timestamp: 1_777_777,
|
||||
quantity: 1,
|
||||
stripeSubscriptionItemId: "si_1",
|
||||
billingProviderSubscriptionItemId: "si_1",
|
||||
};
|
||||
|
||||
await createTenantSubscriptionUsageRecord(usageData, client);
|
||||
@@ -671,14 +685,14 @@ describe("tenant billing boundary", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("stripe tenant subscription products", () => {
|
||||
it("fetches the tenant subscription product needed by Stripe webhooks", async () => {
|
||||
describe("billing provider tenant subscription products", () => {
|
||||
it("fetches the tenant subscription product needed by billing webhooks", async () => {
|
||||
const item = { id: "tenant_product_1" };
|
||||
const client = createStripeTenantSubscriptionProductClient(item);
|
||||
const client = createBillingProviderTenantSubscriptionProductClient(item);
|
||||
|
||||
await expect(findTenantSubscriptionProductByStripeSubscriptionId("sub_123", client)).resolves.toBe(item);
|
||||
await expect(findTenantSubscriptionProductByBillingProviderSubscriptionId("sub_123", client)).resolves.toBe(item);
|
||||
expect(client.tenantSubscriptionProduct.findFirst).toHaveBeenCalledWith({
|
||||
where: { stripeSubscriptionId: "sub_123" },
|
||||
where: { billingProviderSubscriptionId: "sub_123" },
|
||||
select: {
|
||||
id: true,
|
||||
endsAt: true,
|
||||
@@ -705,8 +719,8 @@ describe("stripe tenant subscription products", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("updates Stripe subscription dates and returns the owning tenant id", async () => {
|
||||
const client = createStripeTenantSubscriptionProductClient();
|
||||
it("updates Billing provider subscription dates and returns the owning tenant id", async () => {
|
||||
const client = createBillingProviderTenantSubscriptionProductClient();
|
||||
const data = {
|
||||
cancelledAt: new Date("2026-05-01T00:00:00.000Z"),
|
||||
currentPeriodStart: new Date("2026-05-01T00:00:00.000Z"),
|
||||
@@ -714,7 +728,7 @@ describe("stripe tenant subscription products", () => {
|
||||
endsAt: null,
|
||||
};
|
||||
|
||||
await expect(updateTenantSubscriptionProductFromStripe("tenant_product_1", data, client)).resolves.toEqual({ tenantId: "tenant_1" });
|
||||
await expect(updateTenantSubscriptionProductFromBillingProvider("tenant_product_1", data, client)).resolves.toEqual({ tenantId: "tenant_1" });
|
||||
expect(client.tenantSubscriptionProduct.update).toHaveBeenCalledWith({
|
||||
where: { id: "tenant_product_1" },
|
||||
data,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { getDbClient, type DbClient } from "./client.server.js";
|
||||
import type {
|
||||
Prisma,
|
||||
SubscriptionFeature,
|
||||
SubscriptionPrice,
|
||||
SubscriptionProduct,
|
||||
@@ -23,7 +24,7 @@ export type SubscriptionUsageBasedPriceWithProduct = SubscriptionUsageBasedPrice
|
||||
|
||||
export type SubscriptionProductCreateInput = Pick<
|
||||
SubscriptionProduct,
|
||||
| "stripeId"
|
||||
| "billingProviderId"
|
||||
| "order"
|
||||
| "title"
|
||||
| "model"
|
||||
@@ -36,12 +37,15 @@ export type SubscriptionProductCreateInput = Pick<
|
||||
| "billingAddressCollection"
|
||||
| "hasQuantity"
|
||||
| "canBuyAgain"
|
||||
>;
|
||||
> &
|
||||
Partial<Pick<SubscriptionProduct, "code" | "lagoPlanCode">>;
|
||||
|
||||
export type SubscriptionProductUpdateInput = Partial<
|
||||
Pick<
|
||||
SubscriptionProduct,
|
||||
| "stripeId"
|
||||
| "billingProviderId"
|
||||
| "code"
|
||||
| "lagoPlanCode"
|
||||
| "order"
|
||||
| "title"
|
||||
| "model"
|
||||
@@ -57,12 +61,13 @@ export type SubscriptionProductUpdateInput = Partial<
|
||||
>;
|
||||
|
||||
export type SubscriptionPriceCreateInput = Omit<
|
||||
Pick<SubscriptionPrice, "subscriptionProductId" | "stripeId" | "type" | "billingPeriod" | "price" | "currency" | "trialDays" | "active">,
|
||||
Pick<SubscriptionPrice, "subscriptionProductId" | "billingProviderId" | "type" | "billingPeriod" | "price" | "currency" | "trialDays" | "active">,
|
||||
"price"
|
||||
> & { price: SubscriptionPrice["price"] | number | string };
|
||||
> &
|
||||
Partial<Pick<SubscriptionPrice, "lagoFeeCode" | "molliePriceReference">> & { price: SubscriptionPrice["price"] | number | string };
|
||||
|
||||
export type SubscriptionPriceUpdateInput = Partial<
|
||||
Omit<Pick<SubscriptionPrice, "stripeId" | "type" | "billingPeriod" | "price" | "currency" | "trialDays" | "active">, "price"> & {
|
||||
Omit<Pick<SubscriptionPrice, "billingProviderId" | "lagoFeeCode" | "molliePriceReference" | "type" | "billingPeriod" | "price" | "currency" | "trialDays" | "active">, "price"> & {
|
||||
price: SubscriptionPrice["price"] | number | string;
|
||||
}
|
||||
>;
|
||||
@@ -70,7 +75,7 @@ export type SubscriptionPriceUpdateInput = Partial<
|
||||
export type SubscriptionUsageBasedPriceCreateInput = Pick<
|
||||
SubscriptionUsageBasedPrice,
|
||||
| "subscriptionProductId"
|
||||
| "stripeId"
|
||||
| "billingProviderId"
|
||||
| "currency"
|
||||
| "billingPeriod"
|
||||
| "unit"
|
||||
@@ -90,10 +95,12 @@ export type SubscriptionUsageBasedTierCreateInput = Omit<
|
||||
flatFeePrice?: SubscriptionUsageBasedTier["flatFeePrice"] | number | string | null;
|
||||
};
|
||||
|
||||
export type SubscriptionFeatureCreateInput = Omit<SubscriptionFeature, "id" | "subscriptionProductId" | "href" | "badge" | "accumulate"> & {
|
||||
export type SubscriptionFeatureCreateInput = Omit<SubscriptionFeature, "id" | "subscriptionProductId" | "href" | "badge" | "accumulate" | "code" | "quotaValue"> & {
|
||||
href?: string | null;
|
||||
badge?: string | null;
|
||||
accumulate?: boolean;
|
||||
code?: string | null;
|
||||
quotaValue?: Prisma.NullableJsonNullValueInput | Prisma.InputJsonValue;
|
||||
};
|
||||
|
||||
export type SubscriptionProductPriceWithDetails = Omit<SubscriptionPrice, "id"> & {
|
||||
@@ -112,6 +119,7 @@ export type SubscriptionProductWithDetails = Omit<SubscriptionProduct, "id"> & {
|
||||
|
||||
export type SubscriptionFeatureSummary = {
|
||||
name: string;
|
||||
code?: string | null;
|
||||
order: number;
|
||||
title: string;
|
||||
type: number;
|
||||
@@ -170,19 +178,22 @@ export type TenantSubscriptionProductPage = {
|
||||
};
|
||||
};
|
||||
|
||||
export type TenantSubscriptionCreateInput = Pick<TenantSubscription, "tenantId" | "stripeCustomerId">;
|
||||
export type TenantSubscriptionCreateInput = Pick<TenantSubscription, "tenantId"> &
|
||||
Partial<Pick<TenantSubscription, "billingProviderCustomerId" | "lagoCustomerId" | "mollieCustomerId" | "planCode" | "seatQuantity">>;
|
||||
|
||||
export type TenantSubscriptionCustomerIdUpdateInput = Pick<TenantSubscription, "stripeCustomerId">;
|
||||
export type TenantSubscriptionCustomerIdUpdateInput = Partial<
|
||||
Pick<TenantSubscription, "billingProviderCustomerId" | "lagoCustomerId" | "mollieCustomerId" | "planCode" | "seatQuantity" | "lastInvoiceExternalId" | "lastPaymentExternalId">
|
||||
>;
|
||||
|
||||
export type TenantSubscriptionProductCreateInput = Pick<
|
||||
TenantSubscriptionProduct,
|
||||
| "tenantSubscriptionId"
|
||||
| "subscriptionProductId"
|
||||
| "stripeSubscriptionId"
|
||||
| "billingProviderSubscriptionId"
|
||||
| "quantity"
|
||||
| "fromCheckoutSessionId"
|
||||
> &
|
||||
Partial<Pick<TenantSubscriptionProduct, "customEntitlementPlanId">> & {
|
||||
Partial<Pick<TenantSubscriptionProduct, "customEntitlementPlanId" | "lagoSubscriptionId" | "planCode" | "seatQuantity">> & {
|
||||
prices: {
|
||||
subscriptionPriceId?: string;
|
||||
subscriptionUsageBasedPriceId?: string;
|
||||
@@ -190,7 +201,10 @@ export type TenantSubscriptionProductCreateInput = Pick<
|
||||
};
|
||||
|
||||
export type TenantSubscriptionProductUpdateInput = Partial<
|
||||
Pick<TenantSubscriptionProduct, "quantity" | "cancelledAt" | "endsAt" | "currentPeriodStart" | "currentPeriodEnd" | "customEntitlementPlanId">
|
||||
Pick<
|
||||
TenantSubscriptionProduct,
|
||||
"quantity" | "seatQuantity" | "planCode" | "lagoSubscriptionId" | "cancelledAt" | "endsAt" | "currentPeriodStart" | "currentPeriodEnd" | "customEntitlementPlanId"
|
||||
>
|
||||
>;
|
||||
|
||||
export type TenantSubscriptionProductCustomEntitlementPlanUpdateInput = Pick<TenantSubscriptionProduct, "customEntitlementPlanId">;
|
||||
@@ -199,18 +213,48 @@ export type TenantSubscriptionProductCancelInput = Pick<TenantSubscriptionProduc
|
||||
|
||||
export type TenantSubscriptionUsageRecordCreateInput = Pick<
|
||||
TenantSubscriptionUsageRecord,
|
||||
"tenantSubscriptionProductPriceId" | "timestamp" | "quantity" | "stripeSubscriptionItemId"
|
||||
>;
|
||||
"tenantId" | "tenantSubscriptionId" | "tenantSubscriptionProductPriceId" | "metricCode" | "timestamp" | "quantity" | "billingProviderSubscriptionItemId"
|
||||
> &
|
||||
Partial<Pick<TenantSubscriptionUsageRecord, "idempotencyKey">>;
|
||||
|
||||
export type CheckoutSessionStatusCreateInput = Pick<CheckoutSessionStatus, "id" | "email" | "fromUrl"> &
|
||||
Partial<Pick<CheckoutSessionStatus, "fromUserId" | "fromTenantId">>;
|
||||
Partial<
|
||||
Pick<
|
||||
CheckoutSessionStatus,
|
||||
| "fromUserId"
|
||||
| "fromTenantId"
|
||||
| "provider"
|
||||
| "providerPaymentId"
|
||||
| "invoiceExternalId"
|
||||
| "subscriptionProductId"
|
||||
| "subscriptionPriceId"
|
||||
| "lagoSubscriptionId"
|
||||
| "planCode"
|
||||
| "quantity"
|
||||
| "amountCents"
|
||||
| "currency"
|
||||
| "checkoutUrl"
|
||||
| "status"
|
||||
>
|
||||
>;
|
||||
|
||||
export type CheckoutSessionStatusUpdateInput = Pick<CheckoutSessionStatus, "pending"> &
|
||||
Partial<Pick<CheckoutSessionStatus, "createdUserId" | "createdTenantId">>;
|
||||
Partial<
|
||||
Pick<
|
||||
CheckoutSessionStatus,
|
||||
| "createdUserId"
|
||||
| "createdTenantId"
|
||||
| "providerPaymentId"
|
||||
| "invoiceExternalId"
|
||||
| "lagoSubscriptionId"
|
||||
| "checkoutUrl"
|
||||
| "status"
|
||||
>
|
||||
>;
|
||||
|
||||
export type TenantIdResult = { tenantId: string };
|
||||
|
||||
export type StripeTenantSubscriptionProduct = Pick<TenantSubscriptionProduct, "id" | "endsAt" | "cancelledAt" | "customEntitlementPlanId"> & {
|
||||
export type BillingProviderTenantSubscriptionProduct = Pick<TenantSubscriptionProduct, "id" | "endsAt" | "cancelledAt" | "customEntitlementPlanId"> & {
|
||||
tenantSubscription: Pick<TenantSubscription, "tenantId"> & {
|
||||
tenant: {
|
||||
id: string;
|
||||
@@ -220,7 +264,7 @@ export type StripeTenantSubscriptionProduct = Pick<TenantSubscriptionProduct, "i
|
||||
subscriptionProduct: Pick<SubscriptionProduct, "id" | "title">;
|
||||
};
|
||||
|
||||
export type StripeTenantSubscriptionProductUpdate = {
|
||||
export type BillingProviderTenantSubscriptionProductUpdate = {
|
||||
cancelledAt?: Date | null;
|
||||
currentPeriodStart?: Date;
|
||||
currentPeriodEnd?: Date;
|
||||
@@ -274,7 +318,7 @@ const tenantSubscriptionDetailsInclude = {
|
||||
},
|
||||
} as const;
|
||||
|
||||
const stripeTenantSubscriptionProductSelect = {
|
||||
const billingProviderTenantSubscriptionProductSelect = {
|
||||
id: true,
|
||||
endsAt: true,
|
||||
cancelledAt: true,
|
||||
@@ -313,9 +357,9 @@ export type SubscriptionCatalogClient = {
|
||||
where: { id: string };
|
||||
include: typeof subscriptionProductDetailsInclude;
|
||||
}): Promise<SubscriptionProductWithDetails | null>;
|
||||
findFirst(args: { where: { stripeId: string } }): Promise<SubscriptionProduct | null>;
|
||||
findFirst(args: { where: { billingProviderId: string } }): Promise<SubscriptionProduct | null>;
|
||||
create(args: { data: SubscriptionProductCreateInput }): Promise<SubscriptionProduct>;
|
||||
update(args: { where: { id: string }; data: SubscriptionProductUpdateInput | { stripeId: string } }): Promise<SubscriptionProduct>;
|
||||
update(args: { where: { id: string }; data: SubscriptionProductUpdateInput | { billingProviderId: string } }): Promise<SubscriptionProduct>;
|
||||
delete(args: { where: { id: string } }): Promise<SubscriptionProduct>;
|
||||
};
|
||||
subscriptionPrice: {
|
||||
@@ -324,13 +368,13 @@ export type SubscriptionCatalogClient = {
|
||||
orderBy: [{ subscriptionProduct: { order: "asc" } }, { price: "asc" }];
|
||||
}): Promise<SubscriptionPriceWithProduct[]>;
|
||||
findUnique(args: { where: { id: string }; include: { subscriptionProduct: true } }): Promise<SubscriptionPriceWithProduct | null>;
|
||||
findFirst(args: { where: { stripeId: string }; include: { subscriptionProduct: true } }): Promise<SubscriptionPriceWithProduct | null>;
|
||||
findFirst(args: { where: { billingProviderId: string }; include: { subscriptionProduct: true } }): Promise<SubscriptionPriceWithProduct | null>;
|
||||
create(args: { data: SubscriptionPriceCreateInput }): Promise<SubscriptionPrice>;
|
||||
update(args: { where: { id: string }; data: SubscriptionPriceUpdateInput | { stripeId: string } }): Promise<SubscriptionPrice>;
|
||||
update(args: { where: { id: string }; data: SubscriptionPriceUpdateInput | { billingProviderId: string } }): Promise<SubscriptionPrice>;
|
||||
delete(args: { where: { id: string } }): Promise<SubscriptionPrice>;
|
||||
};
|
||||
subscriptionUsageBasedPrice: {
|
||||
findFirst(args: { where: { stripeId: string }; include: { subscriptionProduct: true } }): Promise<SubscriptionUsageBasedPriceWithProduct | null>;
|
||||
findFirst(args: { where: { billingProviderId: string }; include: { subscriptionProduct: true } }): Promise<SubscriptionUsageBasedPriceWithProduct | null>;
|
||||
create(args: { data: SubscriptionUsageBasedPriceCreateInput }): Promise<SubscriptionUsageBasedPrice>;
|
||||
delete(args: { where: { id: string } }): Promise<SubscriptionUsageBasedPrice>;
|
||||
};
|
||||
@@ -340,7 +384,7 @@ export type SubscriptionCatalogClient = {
|
||||
};
|
||||
subscriptionFeature: {
|
||||
findMany(args: {
|
||||
select: { name: true; order: true; title: true; type: true; value: true; accumulate: true };
|
||||
select: { name: true; code: true; order: true; title: true; type: true; value: true; accumulate: true };
|
||||
}): Promise<SubscriptionFeatureSummary[]>;
|
||||
create(args: { data: SubscriptionFeatureCreateInput & { subscriptionProductId: string } }): Promise<SubscriptionFeature>;
|
||||
deleteMany(args: { where: { subscriptionProductId: string } }): Promise<{ count: number }>;
|
||||
@@ -387,7 +431,7 @@ export type TenantBillingClient = TenantSubscriptionReaderClient & {
|
||||
}): Promise<TenantSubscriptionProductWithTenant[]>;
|
||||
count(args: { where: TenantSubscriptionProductWhereInput }): Promise<number>;
|
||||
findFirst(args: {
|
||||
where: { tenantSubscription: { tenantId: string }; subscriptionProductId: string } | { id: string; tenantSubscription: { tenantId: string } } | { stripeSubscriptionId: string };
|
||||
where: { tenantSubscription: { tenantId: string }; subscriptionProductId: string } | { id: string; tenantSubscription: { tenantId: string } } | { billingProviderSubscriptionId: string };
|
||||
include: typeof tenantSubscriptionProductWithTenantInclude;
|
||||
}): Promise<TenantSubscriptionProductWithTenant | null>;
|
||||
findUnique(args: { where: { id: string }; include: typeof tenantSubscriptionProductWithTenantInclude }): Promise<TenantSubscriptionProductWithTenant | null>;
|
||||
@@ -423,15 +467,15 @@ export type TenantBillingClient = TenantSubscriptionReaderClient & {
|
||||
};
|
||||
};
|
||||
|
||||
export type StripeTenantSubscriptionProductClient = {
|
||||
export type BillingProviderTenantSubscriptionProductClient = {
|
||||
tenantSubscriptionProduct: {
|
||||
findFirst(args: {
|
||||
where: { stripeSubscriptionId: string };
|
||||
select: typeof stripeTenantSubscriptionProductSelect;
|
||||
}): Promise<StripeTenantSubscriptionProduct | null>;
|
||||
where: { billingProviderSubscriptionId: string };
|
||||
select: typeof billingProviderTenantSubscriptionProductSelect;
|
||||
}): Promise<BillingProviderTenantSubscriptionProduct | null>;
|
||||
update(args: {
|
||||
where: { id: string };
|
||||
data: StripeTenantSubscriptionProductUpdate;
|
||||
data: BillingProviderTenantSubscriptionProductUpdate;
|
||||
select: { tenantSubscription: { select: { tenantId: true } } };
|
||||
}): Promise<{ tenantSubscription: { tenantId: string } }>;
|
||||
};
|
||||
@@ -503,7 +547,7 @@ export async function getAllSubscriptionFeatures(
|
||||
client: SubscriptionProductReaderClient = getDbClient(),
|
||||
): Promise<SubscriptionFeatureSummary[]> {
|
||||
return await client.subscriptionFeature.findMany({
|
||||
select: { name: true, order: true, title: true, type: true, value: true, accumulate: true },
|
||||
select: { name: true, code: true, order: true, title: true, type: true, value: true, accumulate: true },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -519,13 +563,13 @@ export async function getSubscriptionProduct(
|
||||
});
|
||||
}
|
||||
|
||||
export async function getSubscriptionProductByStripeId(
|
||||
stripeId: string,
|
||||
export async function getSubscriptionProductByBillingProviderId(
|
||||
billingProviderId: string,
|
||||
client: SubscriptionCatalogClient = getDbClient(),
|
||||
): Promise<SubscriptionProduct | null> {
|
||||
return await client.subscriptionProduct.findFirst({
|
||||
where: {
|
||||
stripeId,
|
||||
billingProviderId,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -570,13 +614,13 @@ export async function getSubscriptionPrice(
|
||||
});
|
||||
}
|
||||
|
||||
export async function getSubscriptionPriceByStripeId(
|
||||
stripeId: string,
|
||||
export async function getSubscriptionPriceByBillingProviderId(
|
||||
billingProviderId: string,
|
||||
client: SubscriptionCatalogClient = getDbClient(),
|
||||
): Promise<SubscriptionPriceWithProduct | null> {
|
||||
return await client.subscriptionPrice
|
||||
.findFirst({
|
||||
where: { stripeId },
|
||||
where: { billingProviderId },
|
||||
include: {
|
||||
subscriptionProduct: true,
|
||||
},
|
||||
@@ -586,13 +630,13 @@ export async function getSubscriptionPriceByStripeId(
|
||||
});
|
||||
}
|
||||
|
||||
export async function getSubscriptionUsageBasedPriceByStripeId(
|
||||
stripeId: string,
|
||||
export async function getSubscriptionUsageBasedPriceByBillingProviderId(
|
||||
billingProviderId: string,
|
||||
client: SubscriptionCatalogClient = getDbClient(),
|
||||
): Promise<SubscriptionUsageBasedPriceWithProduct | null> {
|
||||
return await client.subscriptionUsageBasedPrice
|
||||
.findFirst({
|
||||
where: { stripeId },
|
||||
where: { billingProviderId },
|
||||
include: {
|
||||
subscriptionProduct: true,
|
||||
},
|
||||
@@ -620,9 +664,9 @@ export async function updateSubscriptionProduct(
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateSubscriptionProductStripeId(
|
||||
export async function updateSubscriptionProductBillingProviderId(
|
||||
id: string,
|
||||
data: { stripeId: string },
|
||||
data: { billingProviderId: string },
|
||||
client: SubscriptionCatalogClient = getDbClient(),
|
||||
): Promise<SubscriptionProduct> {
|
||||
return await client.subscriptionProduct.update({
|
||||
@@ -631,9 +675,9 @@ export async function updateSubscriptionProductStripeId(
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateSubscriptionPriceStripeId(
|
||||
export async function updateSubscriptionPriceBillingProviderId(
|
||||
id: string,
|
||||
data: { stripeId: string },
|
||||
data: { billingProviderId: string },
|
||||
client: SubscriptionCatalogClient = getDbClient(),
|
||||
): Promise<SubscriptionPrice> {
|
||||
return await client.subscriptionPrice.update({
|
||||
@@ -877,12 +921,12 @@ export async function getTenantSubscriptionProductById(
|
||||
});
|
||||
}
|
||||
|
||||
export async function getTenantSubscriptionProductByStripeSubscriptionId(
|
||||
stripeSubscriptionId: string,
|
||||
export async function getTenantSubscriptionProductByBillingProviderSubscriptionId(
|
||||
billingProviderSubscriptionId: string,
|
||||
client: TenantBillingClient = getTenantBillingClient(),
|
||||
): Promise<TenantSubscriptionProductWithTenant | null> {
|
||||
return await client.tenantSubscriptionProduct.findFirst({
|
||||
where: { stripeSubscriptionId },
|
||||
where: { billingProviderSubscriptionId },
|
||||
include: tenantSubscriptionProductWithTenantInclude,
|
||||
});
|
||||
}
|
||||
@@ -895,7 +939,10 @@ export async function addTenantSubscriptionProduct(
|
||||
data: {
|
||||
tenantSubscriptionId: data.tenantSubscriptionId,
|
||||
subscriptionProductId: data.subscriptionProductId,
|
||||
stripeSubscriptionId: data.stripeSubscriptionId,
|
||||
billingProviderSubscriptionId: data.billingProviderSubscriptionId,
|
||||
lagoSubscriptionId: data.lagoSubscriptionId,
|
||||
planCode: data.planCode,
|
||||
seatQuantity: data.seatQuantity,
|
||||
quantity: data.quantity,
|
||||
fromCheckoutSessionId: data.fromCheckoutSessionId,
|
||||
customEntitlementPlanId: data.customEntitlementPlanId,
|
||||
@@ -994,6 +1041,18 @@ export async function createCheckoutSessionStatus(
|
||||
fromUrl: data.fromUrl,
|
||||
fromUserId: data.fromUserId ?? null,
|
||||
fromTenantId: data.fromTenantId ?? null,
|
||||
provider: data.provider ?? null,
|
||||
providerPaymentId: data.providerPaymentId ?? null,
|
||||
invoiceExternalId: data.invoiceExternalId ?? null,
|
||||
subscriptionProductId: data.subscriptionProductId ?? null,
|
||||
subscriptionPriceId: data.subscriptionPriceId ?? null,
|
||||
lagoSubscriptionId: data.lagoSubscriptionId ?? null,
|
||||
planCode: data.planCode ?? null,
|
||||
quantity: data.quantity ?? 1,
|
||||
amountCents: data.amountCents ?? null,
|
||||
currency: data.currency ?? null,
|
||||
checkoutUrl: data.checkoutUrl ?? null,
|
||||
status: data.status ?? "open",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1009,6 +1068,11 @@ export async function updateCheckoutSessionStatus(
|
||||
pending: data.pending,
|
||||
createdUserId: data.createdUserId ?? null,
|
||||
createdTenantId: data.createdTenantId ?? null,
|
||||
providerPaymentId: data.providerPaymentId ?? undefined,
|
||||
invoiceExternalId: data.invoiceExternalId ?? undefined,
|
||||
lagoSubscriptionId: data.lagoSubscriptionId ?? undefined,
|
||||
checkoutUrl: data.checkoutUrl ?? undefined,
|
||||
status: data.status ?? undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1020,22 +1084,22 @@ export async function createTenantSubscriptionUsageRecord(
|
||||
return await client.tenantSubscriptionUsageRecord.create({ data });
|
||||
}
|
||||
|
||||
export async function findTenantSubscriptionProductByStripeSubscriptionId(
|
||||
stripeSubscriptionId: string,
|
||||
client: StripeTenantSubscriptionProductClient = getDbClient() as unknown as StripeTenantSubscriptionProductClient,
|
||||
): Promise<StripeTenantSubscriptionProduct | null> {
|
||||
export async function findTenantSubscriptionProductByBillingProviderSubscriptionId(
|
||||
billingProviderSubscriptionId: string,
|
||||
client: BillingProviderTenantSubscriptionProductClient = getDbClient() as unknown as BillingProviderTenantSubscriptionProductClient,
|
||||
): Promise<BillingProviderTenantSubscriptionProduct | null> {
|
||||
return client.tenantSubscriptionProduct.findFirst({
|
||||
where: {
|
||||
stripeSubscriptionId,
|
||||
billingProviderSubscriptionId,
|
||||
},
|
||||
select: stripeTenantSubscriptionProductSelect,
|
||||
select: billingProviderTenantSubscriptionProductSelect,
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateTenantSubscriptionProductFromStripe(
|
||||
export async function updateTenantSubscriptionProductFromBillingProvider(
|
||||
id: string,
|
||||
data: StripeTenantSubscriptionProductUpdate,
|
||||
client: StripeTenantSubscriptionProductClient = getDbClient() as unknown as StripeTenantSubscriptionProductClient,
|
||||
data: BillingProviderTenantSubscriptionProductUpdate,
|
||||
client: BillingProviderTenantSubscriptionProductClient = getDbClient() as unknown as BillingProviderTenantSubscriptionProductClient,
|
||||
): Promise<{ tenantId: string }> {
|
||||
const item = await client.tenantSubscriptionProduct.update({
|
||||
where: { id },
|
||||
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { Prisma } from "../generated/prisma/client/client.js";
|
||||
import { createInboundSupportTicketFromEmail, type SupportTicketClient } from "./support-tickets.server.js";
|
||||
|
||||
const input = {
|
||||
messageId: "message_race",
|
||||
toEmail: "support-acme@example.test",
|
||||
fromEmail: "customer@example.test",
|
||||
subject: "Need help",
|
||||
message: "Something is broken.",
|
||||
};
|
||||
|
||||
function uniqueViolation(): Prisma.PrismaClientKnownRequestError {
|
||||
return new Prisma.PrismaClientKnownRequestError("Unique constraint failed", { code: "P2002", clientVersion: "7.8.0" });
|
||||
}
|
||||
|
||||
type FindUniqueResult = { id: string; tenantId: string | null } | null;
|
||||
|
||||
function createRaceClient(options: {
|
||||
findUniqueSequence: FindUniqueResult[];
|
||||
createError?: unknown;
|
||||
}): SupportTicketClient {
|
||||
const findUnique = vi.fn();
|
||||
for (const value of options.findUniqueSequence) {
|
||||
findUnique.mockResolvedValueOnce(value);
|
||||
}
|
||||
const create = options.createError
|
||||
? vi.fn().mockRejectedValue(options.createError)
|
||||
: vi.fn().mockResolvedValue({ id: "ticket_created", tenantId: "tenant_1" });
|
||||
|
||||
return {
|
||||
supportTicket: { findUnique, create },
|
||||
tenantInboundAddress: {
|
||||
findUnique: vi.fn().mockResolvedValue({ tenantId: "tenant_1" }),
|
||||
},
|
||||
} as unknown as SupportTicketClient;
|
||||
}
|
||||
|
||||
describe("createInboundSupportTicketFromEmail unique-constraint race", () => {
|
||||
it("resolves to duplicate when a concurrent insert wins the P2002 race", async () => {
|
||||
const client = createRaceClient({
|
||||
// 1st lookup (pre-insert): no existing ticket. 2nd lookup (post-conflict): the winner.
|
||||
findUniqueSequence: [null, { id: "ticket_winner", tenantId: "tenant_1" }],
|
||||
createError: uniqueViolation(),
|
||||
});
|
||||
|
||||
await expect(createInboundSupportTicketFromEmail(input, client)).resolves.toEqual({
|
||||
status: "duplicate",
|
||||
ticketId: "ticket_winner",
|
||||
tenantId: "tenant_1",
|
||||
});
|
||||
expect(client.supportTicket.findUnique).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("rethrows a P2002 error when the duplicate row cannot be re-read", async () => {
|
||||
const error = uniqueViolation();
|
||||
const client = createRaceClient({
|
||||
findUniqueSequence: [null, null],
|
||||
createError: error,
|
||||
});
|
||||
|
||||
await expect(createInboundSupportTicketFromEmail(input, client)).rejects.toBe(error);
|
||||
expect(client.supportTicket.findUnique).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("rethrows non-unique-constraint errors without a second lookup", async () => {
|
||||
const error = new Error("connection reset");
|
||||
const client = createRaceClient({
|
||||
findUniqueSequence: [null],
|
||||
createError: error,
|
||||
});
|
||||
|
||||
await expect(createInboundSupportTicketFromEmail(input, client)).rejects.toBe(error);
|
||||
// No recovery lookup happens for non-P2002 failures.
|
||||
expect(client.supportTicket.findUnique).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("truncates an oversized subject to 160 characters", async () => {
|
||||
const client = createRaceClient({ findUniqueSequence: [null] });
|
||||
const longSubject = "S".repeat(400);
|
||||
|
||||
await createInboundSupportTicketFromEmail({ ...input, subject: longSubject }, client);
|
||||
|
||||
const createArg = vi.mocked(client.supportTicket.create).mock.calls[0]?.[0] as { data: { subject: string } };
|
||||
expect(createArg.data.subject).toHaveLength(160);
|
||||
});
|
||||
|
||||
it("falls back to a default subject for blank input", async () => {
|
||||
const client = createRaceClient({ findUniqueSequence: [null] });
|
||||
|
||||
await createInboundSupportTicketFromEmail({ ...input, subject: " " }, client);
|
||||
|
||||
const createArg = vi.mocked(client.supportTicket.create).mock.calls[0]?.[0] as { data: { subject: string } };
|
||||
expect(createArg.data.subject).toBe("Support request");
|
||||
});
|
||||
});
|
||||
+53
-2
@@ -1,17 +1,19 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { createInboundSupportTicketFromEmail, type SupportTicketClient } from "./support-tickets.server.js";
|
||||
import { createInboundSupportTicketFromEmail, createWidgetSupportTicket, type SupportTicketClient } from "./support-tickets.server.js";
|
||||
|
||||
function createClient({
|
||||
existingTicket = null,
|
||||
inboundAddress = { tenantId: "tenant_1" },
|
||||
createdTicket = { id: "ticket_1", tenantId: inboundAddress?.tenantId ?? null, subject: "Need help" },
|
||||
}: {
|
||||
existingTicket?: { id: string; tenantId: string | null } | null;
|
||||
inboundAddress?: { tenantId: string } | null;
|
||||
createdTicket?: { id: string; tenantId: string | null; subject: string };
|
||||
} = {}): SupportTicketClient {
|
||||
return {
|
||||
supportTicket: {
|
||||
findUnique: vi.fn().mockResolvedValue(existingTicket),
|
||||
create: vi.fn().mockResolvedValue({ id: "ticket_1", tenantId: inboundAddress?.tenantId ?? null }),
|
||||
create: vi.fn().mockResolvedValue(createdTicket),
|
||||
},
|
||||
tenantInboundAddress: {
|
||||
findUnique: vi.fn().mockResolvedValue(inboundAddress),
|
||||
@@ -71,3 +73,52 @@ describe("createInboundSupportTicketFromEmail", () => {
|
||||
expect(client.supportTicket.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("createWidgetSupportTicket", () => {
|
||||
it("creates widget tickets in the support inbox with tenant and user scope", async () => {
|
||||
const client = createClient({ createdTicket: { id: "ticket_widget", tenantId: "tenant_1", subject: "Broken form" } });
|
||||
|
||||
await expect(
|
||||
createWidgetSupportTicket(
|
||||
{
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
subject: "Broken form",
|
||||
message: "The form does not submit.",
|
||||
fromUrl: "https://app.example.test/app/acme",
|
||||
},
|
||||
client,
|
||||
),
|
||||
).resolves.toEqual({ ticketId: "ticket_widget", tenantId: "tenant_1", subject: "Broken form" });
|
||||
|
||||
expect(client.supportTicket.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
source: "widget",
|
||||
subject: "Broken form",
|
||||
message: "The form does not submit.",
|
||||
fromUrl: "https://app.example.test/app/acme",
|
||||
},
|
||||
select: { id: true, tenantId: true, subject: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects empty widget ticket messages before persistence", async () => {
|
||||
const client = createClient();
|
||||
|
||||
await expect(
|
||||
createWidgetSupportTicket(
|
||||
{
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
message: " ",
|
||||
fromUrl: "/app/acme",
|
||||
},
|
||||
client,
|
||||
),
|
||||
).rejects.toThrow("Support ticket message is required.");
|
||||
|
||||
expect(client.supportTicket.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,14 @@ export type InboundSupportTicketInput = {
|
||||
message: string;
|
||||
};
|
||||
|
||||
export type WidgetSupportTicketInput = {
|
||||
tenantId: string | null;
|
||||
userId: string | null;
|
||||
subject?: string | null;
|
||||
message: string;
|
||||
fromUrl: string;
|
||||
};
|
||||
|
||||
export type InboundSupportTicketResult =
|
||||
| { status: "created"; ticketId: string; tenantId: string | null }
|
||||
| { status: "duplicate"; ticketId: string; tenantId: string | null }
|
||||
@@ -16,6 +24,29 @@ export type InboundSupportTicketResult =
|
||||
|
||||
export type SupportTicketClient = Pick<DbClient, "tenantInboundAddress" | "supportTicket">;
|
||||
|
||||
export async function createWidgetSupportTicket(
|
||||
input: WidgetSupportTicketInput,
|
||||
client: SupportTicketClient = getDbClient(),
|
||||
): Promise<{ ticketId: string; tenantId: string | null; subject: string }> {
|
||||
const message = input.message.trim();
|
||||
if (!message) {
|
||||
throw new Error("Support ticket message is required.");
|
||||
}
|
||||
const subject = truncate(input.subject?.trim() || message, 160) || "Support request";
|
||||
const ticket = await client.supportTicket.create({
|
||||
data: {
|
||||
tenantId: input.tenantId,
|
||||
userId: input.userId,
|
||||
source: "widget",
|
||||
subject,
|
||||
message,
|
||||
fromUrl: truncate(input.fromUrl.trim(), 2_000),
|
||||
},
|
||||
select: { id: true, tenantId: true, subject: true },
|
||||
});
|
||||
return { ticketId: ticket.id, tenantId: ticket.tenantId, subject: ticket.subject };
|
||||
}
|
||||
|
||||
export async function createInboundSupportTicketFromEmail(
|
||||
input: InboundSupportTicketInput,
|
||||
client: SupportTicketClient = getDbClient(),
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* `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`
|
||||
* metrics SDK. The web/api/worker apps wire their `@hivegrid/metrics`
|
||||
* `prismaQueryDurationSeconds` histogram (or, in the OTel-future, an OTel
|
||||
* Meter) by passing a recorder closure.
|
||||
*
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ import {
|
||||
type DbTransactionRunner,
|
||||
} from "./transactions.server.js";
|
||||
|
||||
describe("@toolctrl/db transaction helpers", () => {
|
||||
describe("@hivegrid/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 = {
|
||||
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
getCurrentSubscriptionPeriod,
|
||||
getTenantApiUsage,
|
||||
mergeApiSubscriptionFeatures,
|
||||
SUBSCRIPTION_FEATURE_LIMIT,
|
||||
} from "./usage.server.js";
|
||||
import type { TenantSubscriptionWithDetails } from "./subscriptions.server.js";
|
||||
import type { LegacyApiKeyLogWriterClient } from "./api-keys.server.js";
|
||||
|
||||
type ProductOverrides = {
|
||||
quantity?: number | null;
|
||||
currentPeriodStart?: Date | null;
|
||||
currentPeriodEnd?: Date | null;
|
||||
hasApiFeature?: boolean;
|
||||
featureType?: number;
|
||||
featureValue?: number;
|
||||
};
|
||||
|
||||
function buildSubscription(...products: ProductOverrides[]): TenantSubscriptionWithDetails {
|
||||
return {
|
||||
id: "subscription_1",
|
||||
tenantId: "tenant_1",
|
||||
products: products.map((p, index) => ({
|
||||
id: `tenant_product_${index}`,
|
||||
quantity: p.quantity ?? 1,
|
||||
currentPeriodStart: p.currentPeriodStart ?? null,
|
||||
currentPeriodEnd: p.currentPeriodEnd ?? null,
|
||||
subscriptionProduct: {
|
||||
features:
|
||||
p.hasApiFeature === false
|
||||
? [{ name: "storage", title: "Storage", type: SUBSCRIPTION_FEATURE_LIMIT.included, value: 5, accumulate: false }]
|
||||
: [
|
||||
{
|
||||
name: "api",
|
||||
title: "{0} API calls",
|
||||
type: p.featureType ?? SUBSCRIPTION_FEATURE_LIMIT.monthly,
|
||||
value: p.featureValue ?? 10,
|
||||
accumulate: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
})),
|
||||
} as unknown as TenantSubscriptionWithDetails;
|
||||
}
|
||||
|
||||
function createUsageClient(count: number): LegacyApiKeyLogWriterClient {
|
||||
return { apiKeyLog: { count: vi.fn().mockResolvedValue(count) } } as unknown as LegacyApiKeyLogWriterClient;
|
||||
}
|
||||
|
||||
describe("mergeApiSubscriptionFeatures", () => {
|
||||
it("returns undefined for an empty feature list", () => {
|
||||
expect(mergeApiSubscriptionFeatures([])).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps the highest limit type but only the first value when features are not accumulating", () => {
|
||||
const merged = mergeApiSubscriptionFeatures([
|
||||
{ title: "Plan", type: SUBSCRIPTION_FEATURE_LIMIT.included, value: 3, accumulate: false } as never,
|
||||
{ title: "Plan", type: SUBSCRIPTION_FEATURE_LIMIT.monthly, value: 9, accumulate: false } as never,
|
||||
]);
|
||||
|
||||
expect(merged).toMatchObject({ type: SUBSCRIPTION_FEATURE_LIMIT.monthly, value: 3 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("getTenantApiUsage", () => {
|
||||
it("returns undefined when there is no subscription at all", async () => {
|
||||
await expect(getTenantApiUsage("tenant_1", null)).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns undefined when no product carries an api feature", async () => {
|
||||
const client = createUsageClient(0);
|
||||
await expect(getTenantApiUsage("tenant_1", buildSubscription({ hasApiFeature: false }), client)).resolves.toBeUndefined();
|
||||
expect(client.apiKeyLog.count).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports unlimited plans without counting usage", async () => {
|
||||
const client = createUsageClient(0);
|
||||
|
||||
const usage = await getTenantApiUsage("tenant_1", buildSubscription({ featureType: SUBSCRIPTION_FEATURE_LIMIT.unlimited, featureValue: 0 }), client);
|
||||
|
||||
expect(usage).toMatchObject({ enabled: true, remaining: "unlimited" });
|
||||
expect(client.apiKeyLog.count).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("marks not-included plans disabled with the explanatory message", async () => {
|
||||
const client = createUsageClient(0);
|
||||
|
||||
const usage = await getTenantApiUsage("tenant_1", buildSubscription({ featureType: SUBSCRIPTION_FEATURE_LIMIT.notIncluded, featureValue: 0 }), client);
|
||||
|
||||
expect(usage).toMatchObject({ enabled: false, remaining: 0, message: "API usage is not included in this plan." });
|
||||
expect(client.apiKeyLog.count).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("leaves an included (non-metered) plan enabled without counting usage", async () => {
|
||||
const client = createUsageClient(0);
|
||||
|
||||
const usage = await getTenantApiUsage("tenant_1", buildSubscription({ featureType: SUBSCRIPTION_FEATURE_LIMIT.included, featureValue: 5 }), client);
|
||||
|
||||
expect(usage).toMatchObject({ enabled: true, remaining: 0 });
|
||||
expect(client.apiKeyLog.count).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("falls back to a single unit when product quantity is zero or missing", async () => {
|
||||
const client = createUsageClient(2);
|
||||
|
||||
const usage = await getTenantApiUsage(
|
||||
"tenant_1",
|
||||
buildSubscription({ quantity: 0, featureType: SUBSCRIPTION_FEATURE_LIMIT.monthly, featureValue: 10 }),
|
||||
client,
|
||||
);
|
||||
|
||||
// quantity 0 collapses to one feature instance, so the limit stays at the single feature value.
|
||||
expect(usage).toMatchObject({ value: 10, used: 2, remaining: 8 });
|
||||
});
|
||||
|
||||
it("uses the monthly message when a metered monthly plan is exhausted", async () => {
|
||||
const usage = await getTenantApiUsage(
|
||||
"tenant_1",
|
||||
buildSubscription({ featureType: SUBSCRIPTION_FEATURE_LIMIT.monthly, featureValue: 5 }),
|
||||
createUsageClient(5),
|
||||
);
|
||||
|
||||
expect(usage).toMatchObject({ enabled: false, remaining: 0, message: "You have reached the API usage limit this month (5/5)." });
|
||||
});
|
||||
|
||||
it("uses the max (lifetime) message when a capped plan is exhausted", async () => {
|
||||
const usage = await getTenantApiUsage(
|
||||
"tenant_1",
|
||||
buildSubscription({ featureType: SUBSCRIPTION_FEATURE_LIMIT.max, featureValue: 4 }),
|
||||
createUsageClient(4),
|
||||
);
|
||||
|
||||
expect(usage).toMatchObject({ enabled: false, message: "You have reached the API usage limit (4/4)." });
|
||||
});
|
||||
});
|
||||
|
||||
describe("getCurrentSubscriptionPeriod", () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("handles the December year-boundary branch", () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-12-15T12:00:00.000Z"));
|
||||
|
||||
const period = getCurrentSubscriptionPeriod(null);
|
||||
|
||||
expect(period.start.getFullYear()).toBe(2026);
|
||||
expect(period.start.getMonth()).toBe(11);
|
||||
// December clamps the period end to the last day of the year.
|
||||
expect(period.end.getFullYear()).toBe(2026);
|
||||
expect(period.end.getMonth()).toBe(11);
|
||||
expect(period.end.getDate()).toBe(31);
|
||||
});
|
||||
|
||||
it("prefers an explicit product billing period over the calendar month", () => {
|
||||
const start = new Date("2026-04-10T00:00:00.000Z");
|
||||
const end = new Date("2026-05-10T00:00:00.000Z");
|
||||
|
||||
const period = getCurrentSubscriptionPeriod(buildSubscription({ currentPeriodStart: start, currentPeriodEnd: end }));
|
||||
|
||||
expect(period).toEqual({ start, end });
|
||||
});
|
||||
|
||||
it("ignores products that lack a complete billing period", () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-06-15T12:00:00.000Z"));
|
||||
|
||||
const period = getCurrentSubscriptionPeriod(buildSubscription({ currentPeriodStart: null, currentPeriodEnd: null }));
|
||||
|
||||
// No override applied — falls back to the calendar month.
|
||||
expect(period.start.getMonth()).toBe(5);
|
||||
expect(period.end.getMonth()).toBe(5);
|
||||
});
|
||||
});
|
||||
@@ -19,7 +19,7 @@ function createSubscription(
|
||||
id: "subscription_1",
|
||||
tenantId: "tenant_1",
|
||||
active: true,
|
||||
stripeCustomerId: null,
|
||||
billingProviderCustomerId: null,
|
||||
createdAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
products: [
|
||||
@@ -32,7 +32,7 @@ function createSubscription(
|
||||
currentPeriodStart: new Date("2026-02-01T00:00:00.000Z"),
|
||||
currentPeriodEnd: new Date("2026-03-01T00:00:00.000Z"),
|
||||
endsAt: null,
|
||||
stripeSubscriptionId: null,
|
||||
billingProviderSubscriptionId: null,
|
||||
createdAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
subscriptionProduct: {
|
||||
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
findLegacyUserWithoutPasswordById,
|
||||
updateLegacyUserDefaultTenantId,
|
||||
type LegacyUserDefaultTenantWriterClient,
|
||||
type LegacyUserWithoutPasswordReaderClient,
|
||||
} from "./users.server.js";
|
||||
|
||||
describe("findLegacyUserWithoutPasswordById error handling", () => {
|
||||
it("returns null instead of propagating a read failure", async () => {
|
||||
const client = {
|
||||
user: {
|
||||
findUnique: vi.fn().mockRejectedValue(new Error("connection lost")),
|
||||
},
|
||||
} as unknown as LegacyUserWithoutPasswordReaderClient;
|
||||
|
||||
await expect(findLegacyUserWithoutPasswordById("user_1", client)).resolves.toBeNull();
|
||||
expect(client.user.findUnique).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateLegacyUserDefaultTenantId", () => {
|
||||
it("updates the default tenant for a valid user id", async () => {
|
||||
const update = vi.fn().mockResolvedValue({ id: "user_1", defaultTenantId: "tenant_2" });
|
||||
const client = { user: { update } } as unknown as LegacyUserDefaultTenantWriterClient;
|
||||
|
||||
const result = await updateLegacyUserDefaultTenantId({ defaultTenantId: "tenant_2" }, "user_1", client);
|
||||
|
||||
expect(result).toEqual({ id: "user_1", defaultTenantId: "tenant_2" });
|
||||
expect(update).toHaveBeenCalledWith({
|
||||
where: { id: "user_1" },
|
||||
data: { defaultTenantId: "tenant_2" },
|
||||
});
|
||||
});
|
||||
|
||||
it("short-circuits to null when the user id is empty", async () => {
|
||||
const update = vi.fn();
|
||||
const client = { user: { update } } as unknown as LegacyUserDefaultTenantWriterClient;
|
||||
|
||||
await expect(updateLegacyUserDefaultTenantId({ defaultTenantId: "tenant_2" }, "", client)).resolves.toBeNull();
|
||||
expect(update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user