Refresh HiveGrid Cloud reference snapshot

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

No files matched your search

@@ -0,0 +1,461 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getRlsExecutionContext, runWithRlsContext, runWithRlsTransaction } from "@hivegrid/db/rls-context.server";
const mocks = vi.hoisted(() => ({
db: {
onboarding: { findUnique: vi.fn() },
onboardingSession: { findFirst: vi.fn(), findUnique: vi.fn(), update: vi.fn() },
onboardingSessionStep: { findMany: vi.fn(), updateMany: vi.fn() },
user: { findUnique: vi.fn() },
tenantUser: { count: vi.fn() },
tenantUserInvitation: { count: vi.fn() },
kontakt: { count: vi.fn(), create: vi.fn() },
projekt: { count: vi.fn(), create: vi.fn() },
task: { create: vi.fn(), deleteMany: vi.fn() },
tenantSubscription: { findUnique: vi.fn() },
onboardingDemoProvisioning: { findFirst: vi.fn(), create: vi.fn(), update: vi.fn() },
$transaction: vi.fn(),
},
ensureDefaultSalesPipeline: vi.fn(),
}));
vi.mock("~/utils/db.server", () => ({ db: mocks.db }));
vi.mock("~/utils/integrations/projects/projectService.server", () => ({ ensureDefaultSalesPipeline: mocks.ensureDefaultSalesPipeline }));
import { getFirstStepsChecklist, updateFirstStepsChecklist } from "./akP20OnboardingService";
import { SHK_FIRST_STEPS, SHK_FIRST_STEPS_CHECKLIST_CODE, SHK_FIRST_STEPS_CHECKLIST_ID } from "~/domain/tenant-bootstrap/tenantBootstrap.constants";
function canonicalCatalog() {
return {
id: SHK_FIRST_STEPS_CHECKLIST_ID,
title: SHK_FIRST_STEPS_CHECKLIST_CODE,
type: "page",
realtime: false,
active: true,
canBeDismissed: true,
height: null,
steps: SHK_FIRST_STEPS.map((step) => ({ ...step })),
};
}
function sessionStep(index: number, id = `session_step_${index + 1}`) {
return {
id,
completedAt: null,
step: { ...SHK_FIRST_STEPS[index]! },
};
}
function legacyCatalogSteps() {
return SHK_FIRST_STEPS.map((step, index) => ({ ...step, id: `legacy_step_${index + 1}` }));
}
function legacySession(status = "active") {
return {
id: "legacy_session_1",
status,
onboarding: { steps: legacyCatalogSteps() },
};
}
const mutationSpies = [mocks.db.onboardingSession.update, mocks.db.onboardingSessionStep.updateMany, mocks.ensureDefaultSalesPipeline];
function expectNoChecklistWrites() {
for (const mutation of mutationSpies) {
expect(mutation).not.toHaveBeenCalled();
}
}
describe("getFirstStepsChecklist read path", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.db.onboarding.findUnique.mockResolvedValue(null);
mocks.db.onboardingSession.findFirst.mockResolvedValue(null);
mocks.db.onboardingSession.findUnique.mockResolvedValue(null);
mocks.db.onboardingSessionStep.findMany.mockResolvedValue([]);
mocks.db.user.findUnique.mockResolvedValue(null);
mocks.db.tenantUser.count.mockResolvedValue(1);
mocks.db.tenantUserInvitation.count.mockResolvedValue(0);
mocks.db.kontakt.count.mockResolvedValue(0);
mocks.db.projekt.count.mockResolvedValue(0);
mocks.db.tenantSubscription.findUnique.mockResolvedValue(null);
});
it("returns an empty checklist without provisioning when no definition exists", async () => {
const checklist = await getFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1" });
expect(checklist).toEqual({
id: "",
status: "active",
dismissed: false,
completedCount: 0,
totalCount: 0,
percentComplete: 0,
items: [],
});
expect(mocks.db.onboarding.findUnique).toHaveBeenCalledWith({
where: { id: SHK_FIRST_STEPS_CHECKLIST_ID },
select: {
id: true,
title: true,
type: true,
realtime: true,
active: true,
canBeDismissed: true,
height: true,
steps: { select: { id: true, order: true, block: true } },
},
});
expect(mocks.db.onboardingSession.findUnique).not.toHaveBeenCalled();
expect(mocks.db.onboardingSession.findFirst).toHaveBeenCalledWith({
where: {
userId: "user_1",
tenantId: "tenant_1",
onboardingId: { not: SHK_FIRST_STEPS_CHECKLIST_ID },
onboarding: { title: SHK_FIRST_STEPS_CHECKLIST_CODE },
},
select: {
id: true,
status: true,
onboarding: {
select: {
steps: { select: { id: true, order: true, block: true } },
},
},
},
orderBy: { createdAt: "asc" },
});
expectNoChecklistWrites();
});
it("derives auto-completion in memory without persisting session or step updates", async () => {
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
mocks.db.onboardingSession.findUnique.mockResolvedValue({ id: "session_1", status: "active" });
mocks.db.onboardingSessionStep.findMany.mockResolvedValue([sessionStep(0), sessionStep(1)]);
mocks.db.user.findUnique.mockResolvedValue({ firstName: "Ada", lastName: "Lovelace", email: "ada@example.test" });
mocks.db.kontakt.count.mockResolvedValue(1);
const checklist = await getFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1" });
expect(checklist).toMatchObject({ id: "session_1", status: "active", completedCount: 2, totalCount: 3, percentComplete: 67 });
expect(checklist.items).toEqual([
expect.objectContaining({ id: "session_step_1", block: "profile", completed: true }),
expect.objectContaining({ id: "shk-first-steps-team-detection-v1", block: "team", completed: false, canComplete: false }),
expect.objectContaining({ id: "session_step_2", block: "contacts", completed: true }),
]);
expect(mocks.db.onboardingSessionStep.findMany).toHaveBeenCalledWith({
where: {
onboardingSessionId: "session_1",
stepId: { in: SHK_FIRST_STEPS.map((step) => step.id) },
},
include: { step: true },
orderBy: { step: { order: "asc" } },
});
expect(mocks.db.tenantUserInvitation.count).toHaveBeenCalledWith({
where: {
tenantId: "tenant_1",
pending: true,
status: "pending",
revokedAt: null,
OR: [{ expiresAt: null }, { expiresAt: { gt: expect.any(Date) } }],
},
});
expect(mocks.db.onboardingSession.findFirst).not.toHaveBeenCalled();
expectNoChecklistWrites();
});
it("keeps an existing legacy checklist session readable without migrating it", async () => {
const legacySteps = legacyCatalogSteps();
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
mocks.db.onboardingSession.findUnique.mockResolvedValue(null);
mocks.db.onboardingSession.findFirst.mockResolvedValue(legacySession());
mocks.db.onboardingSessionStep.findMany.mockResolvedValue([
{ id: "legacy_session_step_1", completedAt: null, step: legacySteps[0] },
{ id: "legacy_session_step_2", completedAt: null, step: legacySteps[1] },
]);
mocks.db.user.findUnique.mockResolvedValue({ firstName: "Ada", lastName: "Lovelace", email: "ada@example.test" });
const checklist = await getFirstStepsChecklist({ tenantId: "legacy_tenant", userId: "user_1" });
expect(checklist).toMatchObject({ id: "legacy_session_1", completedCount: 1, totalCount: 3, percentComplete: 33 });
expect(checklist.items).toEqual([
expect.objectContaining({ id: "legacy_session_step_1", block: "profile", titleKey: "onboarding.firstSteps.profile" }),
expect.objectContaining({ id: "shk-first-steps-team-detection-v1", block: "team", titleKey: "onboarding.firstSteps.team" }),
expect.objectContaining({ id: "legacy_session_step_2", block: "contacts", titleKey: "onboarding.firstSteps.contacts" }),
]);
expect(mocks.db.onboardingSessionStep.findMany).toHaveBeenCalledWith({
where: {
onboardingSessionId: "legacy_session_1",
stepId: { in: legacySteps.map((step) => step.id) },
},
include: { step: true },
orderBy: { step: { order: "asc" } },
});
expectNoChecklistWrites();
});
it("binds every checklist read to the requested tenant and user", async () => {
const contexts: Array<ReturnType<typeof getRlsExecutionContext>> = [];
const observeContext = () => contexts.push(getRlsExecutionContext());
mocks.db.onboarding.findUnique.mockImplementation(async () => {
observeContext();
return canonicalCatalog();
});
mocks.db.onboardingSession.findUnique.mockImplementation(async () => {
observeContext();
return { id: "session_1", status: "active" };
});
mocks.db.onboardingSessionStep.findMany.mockImplementation(async () => {
observeContext();
return [sessionStep(0)];
});
mocks.db.user.findUnique.mockImplementation(async () => {
observeContext();
return { firstName: "Ada", lastName: "Lovelace", email: "ada@example.test" };
});
mocks.db.tenantUser.count.mockImplementation(async () => {
observeContext();
return 1;
});
mocks.db.tenantUserInvitation.count.mockImplementation(async () => {
observeContext();
return 0;
});
mocks.db.kontakt.count.mockImplementation(async () => {
observeContext();
return 0;
});
mocks.db.projekt.count.mockImplementation(async () => {
observeContext();
return 0;
});
mocks.db.tenantSubscription.findUnique.mockImplementation(async () => {
observeContext();
return null;
});
await getFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1" });
expect(contexts).toHaveLength(9);
for (const context of contexts) {
expect(context).toMatchObject({ tenantId: "tenant_1", userId: "user_1" });
}
});
it("updates only the existing session and never re-provisions tenant defaults", async () => {
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
mocks.db.onboardingSession.findUnique.mockResolvedValue({ id: "session_1" });
mocks.db.onboardingSession.update.mockResolvedValue({ id: "session_1", status: "dismissed" });
await updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1", action: "hide" });
expect(mocks.db.onboarding.findUnique).toHaveBeenCalledWith({
where: { id: SHK_FIRST_STEPS_CHECKLIST_ID },
select: {
id: true,
title: true,
type: true,
realtime: true,
active: true,
canBeDismissed: true,
height: true,
steps: { select: { id: true, order: true, block: true } },
},
});
expect(mocks.db.onboardingSession.update).toHaveBeenCalledWith({
where: { id: "session_1" },
data: { status: "dismissed", dismissedAt: expect.any(Date) },
});
expect(mocks.ensureDefaultSalesPipeline).not.toHaveBeenCalled();
});
it("reactivates a dismissed session on the show action", async () => {
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
mocks.db.onboardingSession.findUnique.mockResolvedValue({ id: "session_1" });
mocks.db.onboardingSession.update.mockResolvedValue({ id: "session_1", status: "active" });
await updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1", action: "show" });
expect(mocks.db.onboardingSession.update).toHaveBeenCalledWith({
where: { id: "session_1" },
data: { status: "active", dismissedAt: null },
});
});
it("updates an existing legacy session without replacing or provisioning it", async () => {
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
mocks.db.onboardingSession.findUnique.mockResolvedValue(null);
mocks.db.onboardingSession.findFirst.mockResolvedValue(legacySession());
mocks.db.onboardingSession.update.mockResolvedValue({ id: "legacy_session_1", status: "dismissed" });
await updateFirstStepsChecklist({ tenantId: "legacy_tenant", userId: "user_1", action: "hide" });
expect(mocks.db.onboardingSession.update).toHaveBeenCalledWith({
where: { id: "legacy_session_1" },
data: { status: "dismissed", dismissedAt: expect.any(Date) },
});
expect(mocks.ensureDefaultSalesPipeline).not.toHaveBeenCalled();
});
it("completes only a semantic checklist step from an existing legacy session", async () => {
const legacySteps = legacyCatalogSteps();
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
mocks.db.onboardingSession.findUnique.mockResolvedValue(null);
mocks.db.onboardingSession.findFirst.mockResolvedValue(legacySession());
mocks.db.onboardingSessionStep.updateMany.mockResolvedValue({ count: 1 });
await expect(
updateFirstStepsChecklist({
tenantId: "legacy_tenant",
userId: "user_1",
action: "complete",
sessionStepId: "legacy_session_step_1",
})
).resolves.toEqual({ count: 1 });
expect(mocks.db.onboardingSessionStep.updateMany).toHaveBeenCalledWith({
where: {
id: "legacy_session_step_1",
onboardingSessionId: "legacy_session_1",
stepId: { in: legacySteps.map((step) => step.id) },
},
data: { completedAt: expect.any(Date) },
});
});
it("does not use a malformed legacy catalog as a compatibility fallback", async () => {
mocks.db.onboarding.findUnique.mockResolvedValue(null);
mocks.db.onboardingSession.findFirst.mockResolvedValue({
...legacySession(),
onboarding: { steps: legacyCatalogSteps().slice(0, 3) },
});
await expect(updateFirstStepsChecklist({ tenantId: "legacy_tenant", userId: "user_1", action: "hide" })).rejects.toMatchObject({
code: "foundation.not_found",
});
expectNoChecklistWrites();
});
it("isolates checklist reads and writes from a previously bound tenant transaction", async () => {
const oldTransaction = {};
const contexts: Array<ReturnType<typeof getRlsExecutionContext>> = [];
const observeContext = () => contexts.push(getRlsExecutionContext());
mocks.db.onboarding.findUnique.mockImplementation(async () => {
observeContext();
return canonicalCatalog();
});
mocks.db.onboardingSession.findUnique.mockImplementation(async () => {
observeContext();
return { id: "session_1" };
});
mocks.db.onboardingSession.update.mockImplementation(async () => {
observeContext();
return { id: "session_1", status: "dismissed" };
});
await runWithRlsContext({ tenantId: "tenant_old", userId: "user_1" }, () =>
runWithRlsTransaction(oldTransaction, async () => {
await updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1", action: "hide" });
expect(getRlsExecutionContext()).toMatchObject({ tenantId: "tenant_old", userId: "user_1", transaction: oldTransaction });
})
);
expect(contexts).toHaveLength(3);
for (const context of contexts) {
expect(context).toMatchObject({ tenantId: "tenant_1", userId: "user_1" });
expect(context?.transaction).toBeUndefined();
}
});
it("fails closed before any query when a caller tries to replace the authenticated RLS user", async () => {
await runWithRlsContext({ tenantId: "tenant_1", userId: "authenticated_user" }, async () => {
await expect(getFirstStepsChecklist({ tenantId: "tenant_1", userId: "other_user" })).rejects.toMatchObject({
code: "foundation.not_found",
});
await expect(
updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "other_user", action: "hide" })
).rejects.toMatchObject({ code: "foundation.not_found" });
expect(getRlsExecutionContext()).toMatchObject({ tenantId: "tenant_1", userId: "authenticated_user" });
});
expect(mocks.db.onboarding.findUnique).not.toHaveBeenCalled();
expect(mocks.db.onboardingSession.findUnique).not.toHaveBeenCalled();
expect(mocks.db.onboardingSession.findFirst).not.toHaveBeenCalled();
expect(mocks.db.onboardingSessionStep.findMany).not.toHaveBeenCalled();
expectNoChecklistWrites();
});
it("fails closed instead of creating defaults for a tenant without a bootstrap session", async () => {
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
mocks.db.onboardingSession.findUnique.mockResolvedValue(null);
await expect(updateFirstStepsChecklist({ tenantId: "legacy_tenant", userId: "user_1", action: "hide" })).rejects.toMatchObject({
code: "foundation.not_found",
});
expectNoChecklistWrites();
});
it("fails closed for a catalog with generated or duplicated step identities", async () => {
mocks.db.onboarding.findUnique.mockResolvedValue({
...canonicalCatalog(),
steps: SHK_FIRST_STEPS.map((step, index) => (index === 0 ? { ...step, id: "generated-step" } : { ...step })),
});
await expect(updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1", action: "hide" })).rejects.toMatchObject({
code: "foundation.not_found",
});
expect(mocks.db.onboardingSession.findUnique).not.toHaveBeenCalled();
expectNoChecklistWrites();
});
it.each([
["type", "modal"],
["realtime", true],
["canBeDismissed", false],
["height", "md"],
] as const)("fails closed when the canonical catalog %s drifts", async (field, value) => {
mocks.db.onboarding.findUnique.mockResolvedValue({
...canonicalCatalog(),
[field]: value,
});
await expect(updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1", action: "hide" })).rejects.toMatchObject({
code: "foundation.not_found",
});
expect(mocks.db.onboardingSession.findUnique).not.toHaveBeenCalled();
expectNoChecklistWrites();
});
it("completes only a canonical step belonging to the selected SHK session", async () => {
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
mocks.db.onboardingSession.findUnique.mockResolvedValue({ id: "session_1" });
mocks.db.onboardingSessionStep.updateMany.mockResolvedValue({ count: 1 });
await expect(updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1", action: "complete", sessionStepId: "session_step_1" })).resolves.toEqual({
count: 1,
});
expect(mocks.db.onboardingSessionStep.updateMany).toHaveBeenCalledWith({
where: {
id: "session_step_1",
onboardingSessionId: "session_1",
stepId: { in: SHK_FIRST_STEPS.map((step) => step.id) },
},
data: { completedAt: expect.any(Date) },
});
});
it("returns not found when a submitted session step is outside the canonical SHK session", async () => {
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
mocks.db.onboardingSession.findUnique.mockResolvedValue({ id: "session_1" });
mocks.db.onboardingSessionStep.updateMany.mockResolvedValue({ count: 0 });
await expect(
updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1", action: "complete", sessionStepId: "foreign_step" })
).rejects.toMatchObject({ code: "foundation.not_found" });
});
});
@@ -1,129 +1,95 @@
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { getRlsExecutionContext, runWithIsolatedUserRlsContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import {
hasExactShkFirstSteps,
SHK_FIRST_STEPS,
SHK_FIRST_STEPS_CHECKLIST_CODE,
SHK_FIRST_STEPS_CHECKLIST_ID,
} from "~/domain/tenant-bootstrap/tenantBootstrap.constants";
import { db } from "~/utils/db.server";
import { seedShkRolesForTenant } from "../shkRoles.server";
import { seedShkFormTemplates, type FormTemplateTranslationFn } from "~/modules/forms/services/shkFormTemplates.server";
import { seedShkCustomFieldTemplate } from "~/utils/integrations/crm/customFieldService.server";
import { ensureDefaultAcceptanceFormTemplate, ensureDefaultProjectTemplate } from "~/utils/integrations/projects/auftragService.server";
import { ensureDefaultSalesPipeline } from "~/utils/integrations/projects/projectService.server";
const SHK_CHECKLIST_CODE = "shk-first-steps";
const SHK_DEMO_TEMPLATE_CODE = "shk-demo-v1";
const checklistSteps = [
{ order: 10, block: "profile", titleKey: "onboarding.firstSteps.profile", href: "settings/profile" },
{ order: 20, block: "contacts", titleKey: "onboarding.firstSteps.contacts", href: "contacts" },
{ order: 30, block: "projects", titleKey: "onboarding.firstSteps.projects", href: "projects" },
{ order: 40, block: "billing", titleKey: "onboarding.firstSteps.billing", href: "settings/subscription" },
{ ...SHK_FIRST_STEPS[0], titleKey: "onboarding.firstSteps.profile", href: "settings/profile" },
{ ...SHK_FIRST_STEPS[1], titleKey: "onboarding.firstSteps.contacts", href: "contacts" },
{ ...SHK_FIRST_STEPS[2], titleKey: "onboarding.firstSteps.projects", href: "projects" },
{ ...SHK_FIRST_STEPS[3], titleKey: "onboarding.firstSteps.billing", href: "settings/billing" },
] as const;
const TEAM_CHECKLIST_ITEM = {
id: "shk-first-steps-team-detection-v1",
block: "team",
titleKey: "onboarding.firstSteps.team",
href: "settings/team/members/new",
canComplete: false,
} as const;
type DemoEntityMap = Record<string, string[]>;
type FirstStepsBlock = (typeof checklistSteps)[number]["block"];
async function getOrCreateChecklistOnboarding() {
const existing = await db.onboarding.findFirst({ where: { title: SHK_CHECKLIST_CODE } });
if (existing) {
return existing;
}
return await db.onboarding.create({
data: {
title: SHK_CHECKLIST_CODE,
type: "page",
active: true,
canBeDismissed: true,
steps: {
create: checklistSteps.map((step) => ({
order: step.order,
block: step.block,
})),
},
},
});
}
export async function provisionShkTenantDefaults(input: { tenantId: string; userId: string; t?: FormTemplateTranslationFn }) {
await seedShkRolesForTenant(input.tenantId);
await Promise.all([
ensureDefaultSalesPipeline({ tenantId: input.tenantId, userId: input.userId }),
seedShkCustomFieldTemplate({ tenantId: input.tenantId }),
ensureDefaultAcceptanceFormTemplate({ tenantId: input.tenantId, userId: input.userId }),
ensureDefaultProjectTemplate({ tenantId: input.tenantId }),
input.t ? seedShkFormTemplates({ tenantId: input.tenantId, userId: input.userId, t: input.t }) : Promise.resolve({ upserted: 0 }),
]);
const onboarding = await getOrCreateChecklistOnboarding();
const session = await db.onboardingSession.upsert({
where: {
onboardingId_userId_tenantId: {
onboardingId: onboarding.id,
userId: input.userId,
tenantId: input.tenantId,
},
},
create: {
onboardingId: onboarding.id,
userId: input.userId,
tenantId: input.tenantId,
status: "active",
startedAt: new Date(),
},
update: {},
});
const steps = await db.onboardingStep.findMany({ where: { onboardingId: onboarding.id } });
const existingSessionSteps = await db.onboardingSessionStep.findMany({
where: { onboardingSessionId: session.id },
select: { stepId: true },
});
const existingStepIds = new Set(existingSessionSteps.map((step) => step.stepId));
await db.onboardingSessionStep.createMany({
data: steps
.filter((step) => !existingStepIds.has(step.id))
.map((step) => ({
onboardingSessionId: session.id,
stepId: step.id,
})),
skipDuplicates: true,
});
return session;
}
type FirstStepsBlock = (typeof checklistSteps)[number]["block"] | typeof TEAM_CHECKLIST_ITEM.block;
type FirstStepsCatalogStep = { id: string; order: number; block: string };
type ResolvedFirstStepsSession = {
id: string;
status: string;
stepIds: string[];
};
export async function getFirstStepsChecklist(input: { tenantId: string; userId: string }) {
const session = await provisionShkTenantDefaults(input);
return await withChecklistRlsContext(input, () => getFirstStepsChecklistInContext(input));
}
async function getFirstStepsChecklistInContext(input: { tenantId: string; userId: string }) {
const session = await findFirstStepsSession(input);
if (!session) {
return emptyFirstStepsChecklist();
}
const rows = await db.onboardingSessionStep.findMany({
where: { onboardingSessionId: session.id },
where: {
onboardingSessionId: session.id,
stepId: { in: session.stepIds },
},
include: { step: true },
orderBy: { step: { order: "asc" } },
});
const autoCompletedBlocks = await detectFirstStepsCompletion(input);
const now = new Date();
const autoCompletedRows = rows.filter((row) => !row.completedAt && autoCompletedBlocks.has(row.step.block as FirstStepsBlock));
if (autoCompletedRows.length > 0) {
await db.onboardingSessionStep.updateMany({
where: { id: { in: autoCompletedRows.map((row) => row.id) }, onboardingSessionId: session.id },
data: { completedAt: now },
});
if (rows.length === 0) {
return emptyFirstStepsChecklist();
}
const autoCompletedBlocks = await detectFirstStepsCompletion(input);
const dismissed = session.status === "dismissed";
const items = rows.map((row) => {
const config = checklistSteps.find((step) => step.block === row.step.block);
const items: Array<{
id: string;
block: string;
titleKey: string;
href: string;
completed: boolean;
hidden: boolean;
canComplete?: boolean;
}> = rows.flatMap((row) => {
const config = checklistSteps.find((step) => step.order === row.step.order && step.block === row.step.block);
if (!config) return [];
const completed = Boolean(row.completedAt) || autoCompletedBlocks.has(row.step.block as FirstStepsBlock);
return {
id: row.id,
block: row.step.block,
titleKey: config?.titleKey ?? "onboarding.firstSteps.item",
href: config?.href ?? "dashboard",
completed,
hidden: dismissed,
};
return [
{
id: row.id,
block: row.step.block,
titleKey: config.titleKey,
href: config.href,
completed,
hidden: dismissed,
},
];
});
if (items.length !== rows.length) return emptyFirstStepsChecklist();
items.splice(1, 0, {
...TEAM_CHECKLIST_ITEM,
completed: autoCompletedBlocks.has(TEAM_CHECKLIST_ITEM.block),
hidden: dismissed,
});
const completedCount = items.filter((item) => item.completed).length;
if (!dismissed && items.length > 0 && completedCount === items.length && session.status !== "completed") {
await db.onboardingSession.update({
where: { id: session.id },
data: { status: "completed", completedAt: now },
});
}
return {
id: session.id,
@@ -136,15 +102,39 @@ export async function getFirstStepsChecklist(input: { tenantId: string; userId:
};
}
function emptyFirstStepsChecklist() {
return {
id: "",
status: "active",
dismissed: false,
completedCount: 0,
totalCount: 0,
percentComplete: 0,
items: [],
};
}
async function detectFirstStepsCompletion(input: { tenantId: string; userId: string }): Promise<Set<FirstStepsBlock>> {
const [user, contactCount, projectCount, subscription] = await Promise.all([
const now = new Date();
const [user, memberCount, pendingInvitationCount, contactCount, projectCount, subscription] = await Promise.all([
db.user.findUnique({ where: { id: input.userId }, select: { firstName: true, lastName: true, email: true } }),
db.tenantUser.count({ where: { tenantId: input.tenantId } }),
db.tenantUserInvitation.count({
where: {
tenantId: input.tenantId,
pending: true,
status: "pending",
revokedAt: null,
OR: [{ expiresAt: null }, { expiresAt: { gt: now } }],
},
}),
db.kontakt.count({ where: { tenantId: input.tenantId, isDemoData: false } }),
db.projekt.count({ where: { tenantId: input.tenantId, isDemoData: false } }),
db.tenantSubscription.findUnique({ where: { tenantId: input.tenantId }, select: { status: true } }),
]);
const completed = new Set<FirstStepsBlock>();
if (user?.firstName && user.lastName && user.email) completed.add("profile");
if (memberCount > 1 || pendingInvitationCount > 0) completed.add("team");
if (contactCount > 0) completed.add("contacts");
if (projectCount > 0) completed.add("projects");
if (subscription?.status === "trial" || subscription?.status === "active") completed.add("billing");
@@ -155,28 +145,148 @@ export async function updateFirstStepsChecklist(input: {
tenantId: string;
userId: string;
sessionStepId?: string | null;
action: "complete" | "hide";
action: "complete" | "hide" | "show";
}) {
const session = await provisionShkTenantDefaults(input);
return await withChecklistRlsContext(input, () => updateFirstStepsChecklistInContext(input));
}
async function updateFirstStepsChecklistInContext(input: {
tenantId: string;
userId: string;
sessionStepId?: string | null;
action: "complete" | "hide" | "show";
}) {
const session = await findFirstStepsSession(input);
if (!session) {
throw new CatalogError(foundationErrors.notFound, { resource: "shk-first-steps-session" });
}
if (input.action === "hide") {
return await db.onboardingSession.update({
where: { id: session.id },
data: { status: "dismissed", dismissedAt: new Date() },
});
}
if (!input.sessionStepId) {
throw new Error("Missing checklist step id");
if (input.action === "show") {
return await db.onboardingSession.update({
where: { id: session.id },
data: { status: "active", dismissedAt: null },
});
}
return await db.onboardingSessionStep.updateMany({
if (!input.sessionStepId) {
throw new CatalogError(foundationErrors.notFound, { resource: "shk-first-steps-step" });
}
const result = await db.onboardingSessionStep.updateMany({
where: {
id: input.sessionStepId,
onboardingSession: {
tenantId: input.tenantId,
userId: input.userId,
},
onboardingSessionId: session.id,
stepId: { in: session.stepIds },
},
data: { completedAt: new Date() },
});
if (result.count !== 1) {
throw new CatalogError(foundationErrors.notFound, { resource: "shk-first-steps-step" });
}
return result;
}
async function findFirstStepsSession(input: { tenantId: string; userId: string }): Promise<ResolvedFirstStepsSession | null> {
const canonicalCatalog = await findCanonicalFirstStepsCatalog();
if (canonicalCatalog) {
const canonicalSession = await db.onboardingSession.findUnique({
where: {
onboardingId_userId_tenantId: {
onboardingId: canonicalCatalog.id,
userId: input.userId,
tenantId: input.tenantId,
},
},
});
if (canonicalSession) {
return {
id: canonicalSession.id,
status: canonicalSession.status,
stepIds: SHK_FIRST_STEPS.map((step) => step.id),
};
}
}
const legacySession = await db.onboardingSession.findFirst({
where: {
userId: input.userId,
tenantId: input.tenantId,
onboardingId: { not: SHK_FIRST_STEPS_CHECKLIST_ID },
onboarding: { title: SHK_FIRST_STEPS_CHECKLIST_CODE },
},
select: {
id: true,
status: true,
onboarding: {
select: {
steps: { select: { id: true, order: true, block: true } },
},
},
},
orderBy: { createdAt: "asc" },
});
if (!legacySession || !hasExactLegacyFirstSteps(legacySession.onboarding.steps)) {
return null;
}
return {
id: legacySession.id,
status: legacySession.status,
stepIds: legacySession.onboarding.steps.map((step) => step.id),
};
}
function hasExactLegacyFirstSteps(steps: ReadonlyArray<FirstStepsCatalogStep>): boolean {
return (
steps.length === checklistSteps.length &&
checklistSteps.every((expected) => steps.some((actual) => actual.order === expected.order && actual.block === expected.block))
);
}
async function findCanonicalFirstStepsCatalog() {
const onboarding = await db.onboarding.findUnique({
where: { id: SHK_FIRST_STEPS_CHECKLIST_ID },
select: {
id: true,
title: true,
type: true,
realtime: true,
active: true,
canBeDismissed: true,
height: true,
steps: { select: { id: true, order: true, block: true } },
},
});
if (
!onboarding ||
onboarding.title !== SHK_FIRST_STEPS_CHECKLIST_CODE ||
onboarding.type !== "page" ||
onboarding.realtime !== false ||
!onboarding.active ||
onboarding.canBeDismissed !== true ||
onboarding.height !== null ||
!hasExactShkFirstSteps(onboarding.steps)
) {
return null;
}
return onboarding;
}
function withChecklistRlsContext<T>(input: { tenantId: string; userId: string }, operation: () => T): T {
const current = getRlsExecutionContext();
if (current?.userId && current.userId !== input.userId) {
throw new CatalogError(foundationErrors.notFound, { resource: "shk-first-steps-session" });
}
const bindTarget = () => runWithRlsContext({ tenantId: input.tenantId, userId: input.userId }, operation);
if (current?.userId === input.userId && (current.transaction || (current.tenantId && current.tenantId !== input.tenantId))) {
return runWithIsolatedUserRlsContext(input.userId, bindTarget);
}
return bindTarget();
}
export async function getDemoDataStatus(tenantId: string) {
@@ -1,211 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
applyBillingDunningCycle,
billingStatusFromStripeSubscription,
createBillingDunningNotification,
evaluateBillingDunning,
processStripeBillingEvent,
} from "./billingDunningService";
vi.mock("~/utils/db.server", () => ({
db: {},
}));
const clearTenantSubscriptionCache = vi.fn();
const createNotificationDelivery = vi.fn();
vi.mock("./subscriptionService", () => ({
clearTenantSubscriptionCache: (...args: unknown[]) => clearTenantSubscriptionCache(...args),
}));
vi.mock("@hivegrid/db/notifications.server", () => ({
createNotificationDelivery: (...args: unknown[]) => createNotificationDelivery(...args),
}));
function createClient() {
return {
tenantSubscription: {
findUnique: vi.fn(),
findMany: vi.fn(),
update: vi.fn(),
},
tenantSubscriptionProduct: {
findFirst: vi.fn(),
update: vi.fn(),
},
stripeWebhookLog: {
findUnique: vi.fn(),
upsert: vi.fn(),
update: vi.fn(),
},
};
}
function stripeEvent(type: string, object: Record<string, unknown>) {
return {
id: `evt_${type.replaceAll(".", "_")}`,
type,
data: { object },
} as never;
}
describe("billingDunningService", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("evaluates the day 1/3/7 dunning schedule before freezing", () => {
const now = new Date("2026-07-10T00:00:00.000Z");
expect(evaluateBillingDunning({ status: "active", pastDueSince: now, dunningAttemptCount: 0 }, now)).toEqual({ kind: "noop" });
expect(evaluateBillingDunning({ status: "past_due", pastDueSince: "2026-07-09T00:00:00.000Z", dunningAttemptCount: 0 }, now)).toEqual({
kind: "send_dunning",
attempt: 1,
thresholdDays: 1,
});
expect(evaluateBillingDunning({ status: "past_due", pastDueSince: "2026-07-07T00:00:00.000Z", dunningAttemptCount: 1 }, now)).toEqual({
kind: "send_dunning",
attempt: 2,
thresholdDays: 3,
});
expect(evaluateBillingDunning({ status: "past_due", pastDueSince: "2026-07-03T00:00:00.000Z", dunningAttemptCount: 2 }, now)).toEqual({
kind: "send_dunning",
attempt: 3,
thresholdDays: 7,
});
expect(evaluateBillingDunning({ status: "past_due", pastDueSince: "2026-07-03T00:00:00.000Z", dunningAttemptCount: 3 }, now)).toEqual({
kind: "freeze",
thresholdDays: 7,
});
});
it("applies due dunning notices and freezes exhausted subscriptions", async () => {
const client = createClient();
const now = new Date("2026-07-10T00:00:00.000Z");
const sendDunningNotice = vi.fn();
client.tenantSubscription.findMany.mockResolvedValue([
{ tenantId: "tenant_notice", status: "past_due", pastDueSince: new Date("2026-07-09T00:00:00.000Z"), dunningAttemptCount: 0 },
{ tenantId: "tenant_freeze", status: "past_due", pastDueSince: new Date("2026-07-03T00:00:00.000Z"), dunningAttemptCount: 3 },
]);
const result = await applyBillingDunningCycle({ client, now, sendDunningNotice });
expect(result).toHaveLength(2);
expect(sendDunningNotice).toHaveBeenCalledWith({ tenantId: "tenant_notice", attempt: 1, thresholdDays: 1 });
expect(client.tenantSubscription.update).toHaveBeenCalledWith({
where: { tenantId: "tenant_notice" },
data: { dunningAttemptCount: { increment: 1 }, lastDunningSentAt: now },
});
expect(client.tenantSubscription.update).toHaveBeenCalledWith({
where: { tenantId: "tenant_freeze" },
data: { status: "frozen", frozenAt: now },
});
expect(clearTenantSubscriptionCache).toHaveBeenCalledWith("tenant_notice");
expect(clearTenantSubscriptionCache).toHaveBeenCalledWith("tenant_freeze");
});
it("maps Billing provider subscription statuses to tenant billing statuses", () => {
expect(billingStatusFromStripeSubscription("trialing")).toBe("trial");
expect(billingStatusFromStripeSubscription("active")).toBe("active");
expect(billingStatusFromStripeSubscription("past_due")).toBe("past_due");
expect(billingStatusFromStripeSubscription("unpaid")).toBe("past_due");
expect(billingStatusFromStripeSubscription("canceled")).toBe("cancelled");
});
it("creates dunning email notifications through the notification delivery boundary", async () => {
await createBillingDunningNotification({ tenantId: "tenant_1", attempt: 2, thresholdDays: 3 });
expect(createNotificationDelivery).toHaveBeenCalledWith({
tenantId: "tenant_1",
channel: "EMAIL",
category: "billing",
messageKey: "billing.notify.dunning.attempt2",
sourceKey: "billing-dunning:tenant_1:attempt:2",
payloadMetadata: {
attempt: 2,
thresholdDays: 3,
},
});
});
it("processes Stripe invoice failures idempotently", async () => {
const client = createClient();
const now = new Date("2026-07-10T00:00:00.000Z");
client.stripeWebhookLog.findUnique.mockResolvedValue(null);
client.tenantSubscriptionProduct.findFirst.mockResolvedValue({ tenantSubscription: { tenantId: "tenant_1" } });
client.tenantSubscription.findUnique.mockResolvedValue({ pastDueSince: null });
const result = await processStripeBillingEvent(stripeEvent("invoice.payment_failed", { subscription: "sub_1" }), { client, now });
expect(result).toEqual({ replayed: false, relatedTenantId: "tenant_1" });
expect(client.tenantSubscription.update).toHaveBeenCalledWith({
where: { tenantId: "tenant_1" },
data: { status: "past_due", pastDueSince: now, frozenAt: null },
});
expect(client.stripeWebhookLog.update).toHaveBeenCalledWith({
where: { stripeEventId: "evt_invoice_payment_failed" },
data: { processedAt: now, relatedTenantId: "tenant_1", error: null },
});
client.stripeWebhookLog.findUnique.mockResolvedValueOnce({ processedAt: now, relatedTenantId: "tenant_1" });
await expect(processStripeBillingEvent(stripeEvent("invoice.payment_failed", { subscription: "sub_1" }), { client, now })).resolves.toEqual({
replayed: true,
relatedTenantId: "tenant_1",
});
});
it("keeps the original past-due timestamp on repeated Stripe failures", async () => {
const client = createClient();
const now = new Date("2026-07-10T00:00:00.000Z");
const pastDueSince = new Date("2026-07-08T00:00:00.000Z");
client.stripeWebhookLog.findUnique.mockResolvedValue(null);
client.tenantSubscriptionProduct.findFirst.mockResolvedValue({ tenantSubscription: { tenantId: "tenant_1" } });
client.tenantSubscription.findUnique.mockResolvedValue({ pastDueSince });
await processStripeBillingEvent(stripeEvent("invoice.payment_failed", { subscription: "sub_1" }), { client, now });
expect(client.tenantSubscription.update).toHaveBeenCalledWith({
where: { tenantId: "tenant_1" },
data: { status: "past_due", pastDueSince, frozenAt: null },
});
});
it("syncs Billing provider subscription period fields and clears dunning state when active", async () => {
const client = createClient();
const now = new Date("2026-07-10T00:00:00.000Z");
client.stripeWebhookLog.findUnique.mockResolvedValue(null);
client.tenantSubscriptionProduct.findFirst.mockResolvedValue({ id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } });
await processStripeBillingEvent(
stripeEvent("customer.subscription.updated", {
id: "sub_1",
status: "active",
current_period_start: 1783296000,
current_period_end: 1785974400,
}),
{ client, now }
);
expect(client.tenantSubscriptionProduct.update).toHaveBeenCalledWith({
where: { id: "tenant_product_1" },
data: {
currentPeriodStart: new Date(1783296000 * 1000),
currentPeriodEnd: new Date(1785974400 * 1000),
endsAt: null,
cancelledAt: null,
},
});
expect(client.tenantSubscription.update).toHaveBeenCalledWith({
where: { tenantId: "tenant_1" },
data: {
status: "active",
pastDueSince: null,
frozenAt: null,
cancelledAt: null,
dunningAttemptCount: 0,
lastDunningSentAt: null,
},
});
});
});
@@ -1,247 +0,0 @@
import type Stripe from "stripe";
import { createNotificationDelivery } from "@hivegrid/db/notifications.server";
import { db } from "~/utils/db.server";
import { clearTenantSubscriptionCache } from "./subscriptionService";
export const BILLING_DUNNING_DAY_MARKS = [1, 3, 7] as const;
const DAY_MS = 24 * 60 * 60 * 1000;
const UNKNOWN_STRIPE_WEBHOOK_ERROR_CODE = "billing.stripeWebhook.unknownError";
export type BillingDunningDecision =
| { kind: "noop" }
| { kind: "send_dunning"; attempt: 1 | 2 | 3; thresholdDays: 1 | 3 | 7 }
| { kind: "freeze"; thresholdDays: 7 };
export type BillingDunningSubscription = {
status: string | null;
pastDueSince: Date | string | null;
dunningAttemptCount: number | null;
};
type BillingDunningDeps = {
now?: Date;
sendDunningNotice?: (input: { tenantId: string; attempt: 1 | 2 | 3; thresholdDays: 1 | 3 | 7 }) => Promise<void>;
client?: Pick<typeof db, "tenantSubscription" | "tenantSubscriptionProduct" | "stripeWebhookLog">;
};
type StripeSubscriptionLike = {
id: string;
status?: string | null;
current_period_start?: number | null;
current_period_end?: number | null;
cancel_at?: number | null;
canceled_at?: number | null;
};
function asDate(value: Date | string | null | undefined): Date | null {
if (!value) return null;
const date = value instanceof Date ? value : new Date(value);
return Number.isNaN(date.getTime()) ? null : date;
}
function fromUnix(value: number | null | undefined): Date | null {
return typeof value === "number" && Number.isFinite(value) ? new Date(value * 1000) : null;
}
function daysSince(from: Date, now: Date): number {
return Math.floor((now.getTime() - from.getTime()) / DAY_MS);
}
export function evaluateBillingDunning(input: BillingDunningSubscription, now: Date = new Date()): BillingDunningDecision {
if (input.status !== "past_due") return { kind: "noop" };
const pastDueSince = asDate(input.pastDueSince);
if (!pastDueSince) return { kind: "noop" };
const elapsedDays = daysSince(pastDueSince, now);
const attempts = Math.max(0, input.dunningAttemptCount ?? 0);
if (attempts >= BILLING_DUNNING_DAY_MARKS.length) {
return elapsedDays >= 7 ? { kind: "freeze", thresholdDays: 7 } : { kind: "noop" };
}
const thresholdDays = BILLING_DUNNING_DAY_MARKS[attempts];
if (elapsedDays < thresholdDays) return { kind: "noop" };
return { kind: "send_dunning", attempt: (attempts + 1) as 1 | 2 | 3, thresholdDays };
}
export function billingStatusFromStripeSubscription(status: string | null | undefined): "trial" | "active" | "past_due" | "cancelled" {
if (status === "trialing") return "trial";
if (status === "active") return "active";
if (status === "canceled") return "cancelled";
if (status === "past_due" || status === "unpaid" || status === "incomplete" || status === "incomplete_expired") return "past_due";
return "active";
}
export async function createBillingDunningNotification(input: { tenantId: string; attempt: 1 | 2 | 3; thresholdDays: 1 | 3 | 7 }): Promise<void> {
await createNotificationDelivery({
tenantId: input.tenantId,
channel: "EMAIL",
category: "billing",
messageKey: `billing.notify.dunning.attempt${input.attempt}`,
sourceKey: `billing-dunning:${input.tenantId}:attempt:${input.attempt}`,
payloadMetadata: {
attempt: input.attempt,
thresholdDays: input.thresholdDays,
},
});
}
export async function applyBillingDunningCycle(deps: BillingDunningDeps = {}) {
const client = deps.client ?? db;
const now = deps.now ?? new Date();
const sendDunningNotice = deps.sendDunningNotice ?? createBillingDunningNotification;
const subscriptions = await client.tenantSubscription.findMany({
where: { status: "past_due", pastDueSince: { not: null } },
select: { tenantId: true, status: true, pastDueSince: true, dunningAttemptCount: true },
});
const results: { tenantId: string; decision: BillingDunningDecision }[] = [];
for (const subscription of subscriptions) {
const decision = evaluateBillingDunning(subscription, now);
if (decision.kind === "send_dunning") {
await sendDunningNotice({ tenantId: subscription.tenantId, attempt: decision.attempt, thresholdDays: decision.thresholdDays });
await client.tenantSubscription.update({
where: { tenantId: subscription.tenantId },
data: { dunningAttemptCount: { increment: 1 }, lastDunningSentAt: now },
});
clearTenantSubscriptionCache(subscription.tenantId);
} else if (decision.kind === "freeze") {
await client.tenantSubscription.update({
where: { tenantId: subscription.tenantId },
data: { status: "frozen", frozenAt: now },
});
clearTenantSubscriptionCache(subscription.tenantId);
}
results.push({ tenantId: subscription.tenantId, decision });
}
return results;
}
async function setBillingStatusForTenant(
tenantId: string,
status: "trial" | "active" | "past_due" | "cancelled" | "frozen",
now: Date,
client: BillingDunningDeps["client"] = db,
) {
if (status === "past_due") {
const existingSubscription = await client.tenantSubscription.findUnique({
where: { tenantId },
select: { pastDueSince: true },
});
await client.tenantSubscription.update({
where: { tenantId },
data: {
status,
pastDueSince: existingSubscription?.pastDueSince ?? now,
frozenAt: null,
},
});
clearTenantSubscriptionCache(tenantId);
return;
}
await client.tenantSubscription.update({
where: { tenantId },
data: {
status,
pastDueSince: null,
frozenAt: null,
cancelledAt: status === "cancelled" ? now : null,
dunningAttemptCount: 0,
lastDunningSentAt: null,
},
});
clearTenantSubscriptionCache(tenantId);
}
function subscriptionIdFromInvoice(invoice: Record<string, unknown>): string | null {
const direct = invoice.subscription;
if (typeof direct === "string") return direct;
if (direct && typeof direct === "object" && "id" in direct && typeof direct.id === "string") return direct.id;
const parent = invoice.parent as { subscription_details?: { subscription?: unknown } } | null | undefined;
const parentSubscription = parent?.subscription_details?.subscription;
if (typeof parentSubscription === "string") return parentSubscription;
if (parentSubscription && typeof parentSubscription === "object" && "id" in parentSubscription && typeof parentSubscription.id === "string") {
return parentSubscription.id;
}
return null;
}
async function syncSubscriptionStatusFromStripeSubscription(
subscription: StripeSubscriptionLike,
now: Date,
client: BillingDunningDeps["client"] = db,
): Promise<string | null> {
const tenantProduct = await client.tenantSubscriptionProduct.findFirst({
where: { billingProviderSubscriptionId: subscription.id },
select: { id: true, tenantSubscription: { select: { tenantId: true } } },
});
if (!tenantProduct) return null;
await client.tenantSubscriptionProduct.update({
where: { id: tenantProduct.id },
data: {
currentPeriodStart: fromUnix(subscription.current_period_start),
currentPeriodEnd: fromUnix(subscription.current_period_end),
endsAt: fromUnix(subscription.cancel_at),
cancelledAt: fromUnix(subscription.canceled_at),
},
});
await setBillingStatusForTenant(tenantProduct.tenantSubscription.tenantId, billingStatusFromStripeSubscription(subscription.status), now, client);
return tenantProduct.tenantSubscription.tenantId;
}
async function markInvoiceSubscriptionStatus(
invoice: Record<string, unknown>,
status: "active" | "past_due",
now: Date,
client: BillingDunningDeps["client"] = db,
): Promise<string | null> {
const subscriptionId = subscriptionIdFromInvoice(invoice);
if (!subscriptionId) return null;
const tenantProduct = await client.tenantSubscriptionProduct.findFirst({
where: { billingProviderSubscriptionId: subscriptionId },
select: { tenantSubscription: { select: { tenantId: true } } },
});
if (!tenantProduct) return null;
await setBillingStatusForTenant(tenantProduct.tenantSubscription.tenantId, status, now, client);
return tenantProduct.tenantSubscription.tenantId;
}
export async function processStripeBillingEvent(event: Stripe.Event, deps: BillingDunningDeps = {}) {
const client = deps.client ?? db;
const now = deps.now ?? new Date();
const existing = await client.stripeWebhookLog.findUnique({ where: { stripeEventId: event.id } });
if (existing?.processedAt) {
return { replayed: true, relatedTenantId: existing.relatedTenantId ?? null };
}
await client.stripeWebhookLog.upsert({
where: { stripeEventId: event.id },
create: { stripeEventId: event.id, eventType: event.type },
update: { eventType: event.type, error: null },
});
try {
let relatedTenantId: string | null = null;
if (event.type === "customer.subscription.updated" || event.type === "customer.subscription.deleted") {
relatedTenantId = await syncSubscriptionStatusFromStripeSubscription(event.data.object as StripeSubscriptionLike, now, client);
} else if (event.type === "invoice.payment_failed") {
relatedTenantId = await markInvoiceSubscriptionStatus(event.data.object as unknown as Record<string, unknown>, "past_due", now, client);
} else if (event.type === "invoice.paid" || event.type === "invoice.payment_succeeded") {
relatedTenantId = await markInvoiceSubscriptionStatus(event.data.object as unknown as Record<string, unknown>, "active", now, client);
}
await client.stripeWebhookLog.update({
where: { stripeEventId: event.id },
data: { processedAt: now, relatedTenantId, error: null },
});
return { replayed: false, relatedTenantId };
} catch (error) {
await client.stripeWebhookLog.update({
where: { stripeEventId: event.id },
data: { error: error instanceof Error ? error.message : UNKNOWN_STRIPE_WEBHOOK_ERROR_CODE },
});
throw error;
}
}
@@ -4,6 +4,15 @@ const billingDomainMock = vi.hoisted(() => ({
resolveTenantBillingState: vi.fn(),
}));
const rlsMock = vi.hoisted(() => ({
getDbClient: vi.fn(() => ({ marker: "rls-client" })),
runWithRlsContext: vi.fn((_context: unknown, callback: () => unknown) => callback()),
}));
const storageMock = vi.hoisted(() => ({
resolveTenantStorageUsage: vi.fn(),
}));
const dbMock = vi.hoisted(() => ({
tenantSubscription: {
findUnique: vi.fn(),
@@ -23,6 +32,18 @@ vi.mock("@hivegrid/db/billing-domain.server", () => ({
resolveTenantBillingState: billingDomainMock.resolveTenantBillingState,
}));
vi.mock("@hivegrid/db/client.server", () => ({
getDbClient: rlsMock.getDbClient,
}));
vi.mock("@hivegrid/db/rls-context.server", () => ({
runWithRlsContext: rlsMock.runWithRlsContext,
}));
vi.mock("~/services/billing/storage-capacity.server", () => ({
resolveTenantStorageUsage: storageMock.resolveTenantStorageUsage,
}));
vi.mock("./subscriptionService", () => ({
clearTenantSubscriptionCache: vi.fn(),
}));
@@ -31,7 +52,6 @@ import {
assertBillingUsageWithinQuota,
BILLING_USAGE_METRICS,
BillingUsageQuotaExceededError,
buildBillingStatusBannerVm,
getBillingUsageSummary,
getTenantBillingReadOnlyState,
isTenantBillingReadOnly,
@@ -41,6 +61,7 @@ import {
describe("billingStatusService", () => {
beforeEach(() => {
vi.clearAllMocks();
storageMock.resolveTenantStorageUsage.mockResolvedValue({ available: false, reason: "subscription_missing" });
});
it("marks past-due, frozen and cancelled subscriptions as read-only", () => {
@@ -51,16 +72,6 @@ describe("billingStatusService", () => {
expect(isTenantBillingReadOnly("cancelled")).toBe(true);
});
it("builds localized billing status banner keys", () => {
expect(buildBillingStatusBannerVm({ status: "active", tenantSlug: "acme" })).toEqual({ visible: false });
expect(buildBillingStatusBannerVm({ status: "frozen", tenantSlug: "acme" })).toMatchObject({
visible: true,
severity: "danger",
messageKey: "billing:status.frozen",
actionHref: "/acme/settings/subscription",
});
});
it("reads tenant billing status for action write guards", async () => {
billingDomainMock.resolveTenantBillingState.mockResolvedValue({ status: "frozen", readOnly: true });
@@ -86,6 +97,41 @@ describe("billingStatusService", () => {
},
]),
});
expect(rlsMock.runWithRlsContext).toHaveBeenCalledWith({ tenantId: "tenant_1" }, expect.any(Function));
});
it("projects stored and reserved bytes against the canonical commercial storage capacity", async () => {
const capacityBytes = 350 * 1024 ** 3;
dbMock.tenantSubscription.findUnique.mockResolvedValue(subscriptionWithQuota(10));
dbMock.tenantSubscriptionUsageRecord.groupBy.mockResolvedValue([]);
storageMock.resolveTenantStorageUsage.mockResolvedValue({
available: true,
capacityBytes,
storedBytes: 50,
reservedBytes: 25,
remainingBytes: capacityBytes - 75,
});
const summary = await getBillingUsageSummary("tenant_1", new Date("2026-07-12T00:00:00.000Z"));
expect(summary.storageUnavailableReason).toBeNull();
expect(summary.metrics).toContainEqual({
metricCode: BILLING_USAGE_METRICS.storageBytes,
quantity: 75,
quota: capacityBytes,
remaining: capacityBytes - 75,
exceeded: false,
percentUsed: 0,
});
expect(storageMock.resolveTenantStorageUsage).toHaveBeenCalledWith({ marker: "rls-client" }, "tenant_1", new Date("2026-07-12T00:00:00.000Z"));
});
it("reports unavailable storage without presenting it as an unlimited allowance", async () => {
dbMock.tenantSubscription.findUnique.mockResolvedValue(null);
dbMock.tenantSubscriptionUsageRecord.groupBy.mockResolvedValue([]);
storageMock.resolveTenantStorageUsage.mockResolvedValue({ available: false, reason: "plan_unknown" });
await expect(getBillingUsageSummary("tenant_1")).resolves.toMatchObject({ storageUnavailableReason: "plan_unknown" });
});
it("throws a quota error before usage exceeds the current period limit", async () => {
@@ -95,6 +141,7 @@ describe("billingStatusService", () => {
await expect(assertBillingUsageWithinQuota({ tenantId: "tenant_1", metricCode: BILLING_USAGE_METRICS.automationRuns, quantity: 2 })).rejects.toBeInstanceOf(
BillingUsageQuotaExceededError
);
expect(storageMock.resolveTenantStorageUsage).not.toHaveBeenCalled();
});
it("records usage idempotently and does not double-count retries", async () => {
@@ -1,4 +1,8 @@
import { resolveTenantBillingState } from "@hivegrid/db/billing-domain.server";
import { getDbClient } from "@hivegrid/db/client.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { resolveTenantStorageUsage } from "~/services/billing/storage-capacity.server";
import type { TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
import { db } from "~/utils/db.server";
import { clearTenantSubscriptionCache } from "./subscriptionService";
@@ -15,15 +19,6 @@ const SUBSCRIPTION_FEATURE_LIMIT_MONTHLY = 2;
const SUBSCRIPTION_FEATURE_LIMIT_MAX = 3;
const SUBSCRIPTION_FEATURE_LIMIT_UNLIMITED = 4;
export type BillingStatusBannerVm =
| { visible: false }
| {
visible: true;
severity: "info" | "warning" | "danger";
messageKey: string;
actionHref: string;
};
export class BillingUsageQuotaExceededError extends Error {
readonly messageKey = "billing:usage.limitExceeded";
readonly metricCode: BillingUsageMetric;
@@ -53,28 +48,6 @@ export function isTenantBillingReadOnly(status: string | null | undefined): bool
return normalized === "past_due" || normalized === "frozen" || normalized === "cancelled";
}
export function buildBillingStatusBannerVm(input: {
status: string | null | undefined;
tenantSlug: string;
trialEndsAt?: Date | string | null;
}): BillingStatusBannerVm {
const status = normalizeBillingStatus(input.status);
const actionHref = `/${input.tenantSlug}/settings/subscription`;
if (status === "trial" && input.trialEndsAt) {
return { visible: true, severity: "info", messageKey: "billing:status.trial", actionHref };
}
if (status === "past_due") {
return { visible: true, severity: "warning", messageKey: "billing:status.pastDue", actionHref };
}
if (status === "frozen") {
return { visible: true, severity: "danger", messageKey: "billing:status.frozen", actionHref };
}
if (status === "cancelled") {
return { visible: true, severity: "warning", messageKey: "billing:status.cancelled", actionHref };
}
return { visible: false };
}
export async function getTenantBillingStatus(tenantId: string) {
return await db.tenantSubscription.findUnique({
where: { tenantId },
@@ -290,44 +263,71 @@ export async function recordBillingUsage(input: {
});
}
export async function getBillingUsageSummary(tenantId: string, now: Date = new Date()) {
const { periodStart, periodEnd } = getPeriodBounds(now);
const subscription = await loadTenantSubscriptionForUsage(tenantId);
const rows = await db.tenantSubscriptionUsageRecord.groupBy({
by: ["metricCode"],
where: {
tenantId,
timestamp: {
gte: Math.floor(periodStart.getTime() / 1000),
lt: Math.floor(periodEnd.getTime() / 1000),
},
},
_sum: { quantity: true },
export async function getBillingUsageSummary(
tenantId: string,
now: Date = new Date(),
options: { readonly includeCanonicalStorage?: boolean } = {},
) {
return runWithRlsContext({ tenantId }, async () => {
const { periodStart, periodEnd } = getPeriodBounds(now);
const [subscription, rows, storageUsage] = await Promise.all([
loadTenantSubscriptionForUsage(tenantId),
db.tenantSubscriptionUsageRecord.groupBy({
by: ["metricCode"],
where: {
tenantId,
timestamp: {
gte: Math.floor(periodStart.getTime() / 1000),
lt: Math.floor(periodEnd.getTime() / 1000),
},
},
_sum: { quantity: true },
}),
options.includeCanonicalStorage === false
? Promise.resolve(null)
: resolveTenantStorageUsage(getDbClient() as unknown as TenantRlsClient, tenantId, now),
]);
const quantities = new Map(rows.map((row) => [row.metricCode, row._sum.quantity ?? 0]));
const metricCodes = new Set<string>([...Object.values(BILLING_USAGE_METRICS), ...quantities.keys()]);
return {
periodStart,
periodEnd,
storageUnavailableReason: storageUsage === null || storageUsage.available ? null : storageUsage.reason,
metrics: [...metricCodes].map((metricCode) => {
if (metricCode === BILLING_USAGE_METRICS.storageBytes && storageUsage?.available) {
const quantity = storageUsage.storedBytes + storageUsage.reservedBytes;
const quota = storageUsage.capacityBytes;
return {
metricCode,
quantity,
quota,
remaining: storageUsage.remainingBytes,
exceeded: quantity >= quota,
percentUsed: Math.min(100, Math.round((quantity / quota) * 100)),
};
}
const quantity = quantities.get(metricCode) ?? 0;
const quota = Object.values(BILLING_USAGE_METRICS).includes(metricCode as BillingUsageMetric)
? resolveMetricQuota(subscription, metricCode as BillingUsageMetric)
: null;
return {
metricCode,
quantity,
quota,
remaining: quota === null ? null : Math.max(0, quota - quantity),
exceeded: quota !== null && quantity >= quota,
percentUsed: quota === null ? null : Math.min(100, Math.round((quantity / quota) * 100)),
};
}),
};
});
const quantities = new Map(rows.map((row) => [row.metricCode, row._sum.quantity ?? 0]));
const metricCodes = new Set<string>([...Object.values(BILLING_USAGE_METRICS), ...quantities.keys()]);
return {
periodStart,
periodEnd,
metrics: [...metricCodes].map((metricCode) => {
const quantity = quantities.get(metricCode) ?? 0;
const quota = Object.values(BILLING_USAGE_METRICS).includes(metricCode as BillingUsageMetric)
? resolveMetricQuota(subscription, metricCode as BillingUsageMetric)
: null;
return {
metricCode,
quantity,
quota,
remaining: quota === null ? null : Math.max(0, quota - quantity),
exceeded: quota !== null && quantity >= quota,
percentUsed: quota === null ? null : Math.min(100, Math.round((quantity / quota) * 100)),
};
}),
};
}
export async function assertBillingUsageWithinQuota(input: { tenantId: string; metricCode: BillingUsageMetric; quantity: number; at?: Date }) {
const summary = await getBillingUsageSummary(input.tenantId, input.at);
const summary = await getBillingUsageSummary(input.tenantId, input.at, {
includeCanonicalStorage: input.metricCode === BILLING_USAGE_METRICS.storageBytes,
});
const metric = summary.metrics.find((item) => item.metricCode === input.metricCode);
if (!metric?.quota) return;
if (metric.quantity + input.quantity > metric.quota) {
@@ -0,0 +1,36 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import { isDemoDataUiEnabled, isManagedNormalDataTenant } from "./demoDataUi.server";
describe("isDemoDataUiEnabled", () => {
it("is enabled outside production regardless of the staging flags", () => {
expect(isDemoDataUiEnabled({ NODE_ENV: "development" })).toBe(true);
expect(isDemoDataUiEnabled({ NODE_ENV: "test" })).toBe(true);
expect(isDemoDataUiEnabled({})).toBe(true);
});
it("is enabled on staging (NODE_ENV=production + both staging demo flags)", () => {
expect(isDemoDataUiEnabled({ NODE_ENV: "production", SEED_DEMO_DATA: "true", ALLOW_STAGING_DEMO_SEED: "true" })).toBe(true);
});
it("is disabled on production (no or partial staging demo flags)", () => {
expect(isDemoDataUiEnabled({ NODE_ENV: "production" })).toBe(false);
expect(isDemoDataUiEnabled({ NODE_ENV: "production", SEED_DEMO_DATA: "true" })).toBe(false);
expect(isDemoDataUiEnabled({ NODE_ENV: "production", ALLOW_STAGING_DEMO_SEED: "true" })).toBe(false);
expect(isDemoDataUiEnabled({ NODE_ENV: "production", SEED_DEMO_DATA: "false", ALLOW_STAGING_DEMO_SEED: "true" })).toBe(false);
});
it("is disabled for the managed normal-data tenant even on staging", () => {
const env = {
NODE_ENV: "production",
SEED_DEMO_DATA: "true",
ALLOW_STAGING_DEMO_SEED: "true",
SEED_DEMO_PRO_MANAGED: "true",
SEED_DEMO_PRO_EXPECTED_TENANT_ID: "tenant-normal-data",
};
expect(isManagedNormalDataTenant({ tenantId: "tenant-normal-data" }, env)).toBe(true);
expect(isManagedNormalDataTenant({ tenantSlug: "demo-pro-crm" }, env)).toBe(true);
expect(isDemoDataUiEnabled(env, { tenantId: "tenant-normal-data", tenantSlug: "demo-pro-crm" })).toBe(false);
expect(isDemoDataUiEnabled(env, { tenantId: "tenant-other", tenantSlug: "other" })).toBe(true);
});
});
@@ -0,0 +1,49 @@
// Demo data is a staging/dev-only affordance. Staging deploys set
// SEED_DEMO_DATA=true + ALLOW_STAGING_DEMO_SEED=true (see .gitea/workflows/
// deploy.yml); production resources must never set those flags (enforced by
// scripts/verify-gitea-deploy-workflow.mjs). When the demo UI is disabled the
// list loaders ignore the `demo=show` query param server-side and the list
// screens hide their "show demo data" checkbox entirely.
//
// Mirrors the guard pair used by SeedService.shouldSeedCrmDemoData and
// AuthService.isStagingDemoLoginAllowed: outside production the demo UI is
// always available (local dev provisions demo data via the settings page);
// in production it requires both staging flags.
import { loadWebConfig } from "@hivegrid/config";
type DemoDataUiEnvironment = {
NODE_ENV?: string;
SEED_DEMO_DATA?: string;
ALLOW_STAGING_DEMO_SEED?: string;
SEED_DEMO_PRO_MANAGED?: string;
SEED_DEMO_PRO_EXPECTED_TENANT_ID?: string;
};
type DemoDataTenantContext = {
tenantId?: string | null;
tenantSlug?: string | null;
};
const MANAGED_NORMAL_DATA_TENANT_SLUG = "demo-pro-crm";
export function isManagedNormalDataTenant(context: DemoDataTenantContext, env?: DemoDataUiEnvironment): boolean {
const demoEnv = env ?? (process.env as DemoDataUiEnvironment);
if (demoEnv.SEED_DEMO_PRO_MANAGED !== "true") return false;
const expectedTenantId = demoEnv.SEED_DEMO_PRO_EXPECTED_TENANT_ID?.trim();
if (expectedTenantId && context.tenantId === expectedTenantId) return true;
return context.tenantSlug === MANAGED_NORMAL_DATA_TENANT_SLUG;
}
export function isDemoDataUiEnabled(env?: DemoDataUiEnvironment, context?: DemoDataTenantContext): boolean {
const demoEnv = env ?? (process.env as DemoDataUiEnvironment);
if (context && isManagedNormalDataTenant(context, demoEnv)) return false;
// Injected env keeps tests hermetic; the runtime default resolves NODE_ENV
// through @hivegrid/config (runtime NODE_ENV boundary, enforced by
// apps/web/app/utils/runtime-node-env-boundary.test.ts).
const nodeEnv = env ? env.NODE_ENV : loadWebConfig().config.nodeEnv;
if (nodeEnv !== "production") {
return true;
}
return demoEnv.SEED_DEMO_DATA === "true" && demoEnv.ALLOW_STAGING_DEMO_SEED === "true";
}
@@ -59,7 +59,7 @@ function getTier(): TwoTierCache<EvaluateFlagResult> {
export function getFeatureFlagCache(): FlagEvalCache {
if (cacheSingleton) return cacheSingleton;
cacheSingleton = createFlagEvalCache(getTier());
cacheSingleton = createFlagEvalCache(getTier(), getSharedStore());
return cacheSingleton;
}
@@ -71,9 +71,8 @@ export function getFeatureFlagCache(): FlagEvalCache {
export async function subscribeFeatureFlagCache(): Promise<() => Promise<void>> {
if (subscribeDisposer) return subscribeDisposer;
const tier = getTier();
subscribeDisposer = await tier.subscribe(() => {
// Any invalidation drops everything — see cache.ts comment.
tier.flushLocal();
subscribeDisposer = await tier.subscribe((token) => {
getFeatureFlagCache().handleInvalidation(token);
});
log.info({ namespace: "feature-flags", channel: FEATURE_FLAGS_INVALIDATION_CHANNEL }, "feature-flag cache subscriber started");
return subscribeDisposer;
@@ -43,7 +43,7 @@ const createLoader = (): FlagLoader => async (key: string) => {
// OR-lookup so dependency-resolution (which calls back with an id)
// works against the same loader.
const row = await db.featureFlag.findFirst({
where: { OR: [{ name: key }, { id: key }] },
where: { archivedAt: null, OR: [{ name: key }, { id: key }] },
});
return toStored(row);
};
@@ -18,7 +18,7 @@
import { Params } from "react-router";
import type { EvaluateFlagResult } from "@hivegrid/feature-flags";
import { evaluateFlagForContext, evaluateFlagsForContext } from "./featureFlagEvaluator.server";
import { getAllFeatureFlags } from "~/modules/featureFlags/db/featureFlags.db.server";
import { getFeatureFlagEvaluationNames } from "~/modules/featureFlags/db/featureFlags.db.server";
import { getUserInfo } from "~/utils/session.server";
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
@@ -84,14 +84,11 @@ export async function isFeatureFlagEnabled(
* `enabled=true` boolean modulo v2 rule evaluation.
*/
export async function getCurrentEnabledFlagNames(input: RequestContextInput): Promise<string[]> {
const [tenantId, userInfo, flags] = await Promise.all([
const [tenantId, userInfo, names] = await Promise.all([
resolveTenantIdForFlags(input),
getUserInfo(input.request),
getAllFeatureFlags(),
getFeatureFlagEvaluationNames(),
]);
const names = flags
.map((f) => f.name ?? f.key ?? "")
.filter((n) => n.length > 0);
if (names.length === 0) return [];
const results = await evaluateFlagsForContext(names, {
flagName: "*",
@@ -0,0 +1,419 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
type Marker = {
requestHash: string;
responseStatus: number;
responseBody: unknown;
responseHeaders: Record<string, string> | null;
expiresAt: Date | null;
};
const mocks = vi.hoisted(() => ({
getTenant: vi.fn(),
getOrPersistTenantSubscription: vi.fn(),
getAllSubscriptionProducts: vi.fn(),
getAllSubscriptionProductsStrict: vi.fn(),
addTenantSubscriptionProduct: vi.fn(),
getUser: vi.fn(),
createEvent: vi.fn(),
createIdempotentTenantEvent: vi.fn(),
clearTenantSubscriptionCache: vi.fn(),
completeSelfServiceCheckout: vi.fn(),
loggerError: vi.fn(),
dbTransaction: vi.fn(),
executeRaw: vi.fn(),
upsertTenantSubscription: vi.fn(),
markers: new Map<string, Marker>(),
events: new Set<string>(),
subscriptionWrites: [] as unknown[],
transactionClients: [] as unknown[],
transactionOpen: false,
failCommitOnce: false,
failMarkerUpdateOnce: false,
}));
vi.mock("../../db/tenants.db.server", () => ({ getTenant: mocks.getTenant }));
vi.mock("../../db/tenantSubscriptions.db.server", () => ({ getOrPersistTenantSubscription: mocks.getOrPersistTenantSubscription }));
vi.mock("../../db/subscriptionProducts.db.server", () => ({
getAllSubscriptionProducts: mocks.getAllSubscriptionProducts,
getAllSubscriptionProductsStrict: mocks.getAllSubscriptionProductsStrict,
}));
vi.mock("../../db/subscriptions/tenantSubscriptionProducts.db.server", () => ({
addTenantSubscriptionProduct: mocks.addTenantSubscriptionProduct,
}));
vi.mock("../../db/users.db.server", () => ({ getUser: mocks.getUser }));
vi.mock("../../../modules/events/services/.server/EventsService", () => ({
default: {
create: mocks.createEvent,
createIdempotentTenantEvent: mocks.createIdempotentTenantEvent,
},
}));
vi.mock("~/application/pricing/currencies", () => ({
default: [{ value: "EUR", default: true }],
}));
vi.mock("~/utils/logger.server", () => ({
createScopedLogger: () => ({ info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: mocks.loggerError }),
}));
vi.mock("~/utils/db.server", () => ({ db: { $transaction: mocks.dbTransaction } }));
vi.mock("~/utils/db/appConfiguration.db.server", () => ({ getAppConfiguration: vi.fn() }));
vi.mock("./subscriptionService", () => ({
cancelTenantSubscription: vi.fn(),
clearAllSubscriptionsCache: vi.fn(),
clearTenantSubscriptionCache: mocks.clearTenantSubscriptionCache,
getActiveTenantSubscriptions: vi.fn(),
}));
vi.mock("~/services/billing/self-service-checkout.server", () => ({ completeSelfServiceCheckout: mocks.completeSelfServiceCheckout }));
vi.mock("../../api/.server/TenantTypesApi", () => ({ TenantTypesApi: { setTenantTypes: vi.fn() } }));
import { autosubscribeToTrialOrFreePlan } from "./pricingService";
const IDEMPOTENCY_KEY = "d7077797-054b-497a-b1ce-8e4f36257a96";
const IDEMPOTENCY_SCOPE = "tenant-bootstrap/workspace-trial-autosubscribe-v1";
function markerStorageKey({ partitionKey, scope, key }: { partitionKey: string; scope: string; key: string }): string {
return `${partitionKey}:${scope}:${key}`;
}
function expectedMarkerKey(): string {
return markerStorageKey({ partitionKey: "tenant:tenant_1", scope: IDEMPOTENCY_SCOPE, key: IDEMPOTENCY_KEY });
}
function idempotencyClient() {
return {
$executeRaw: mocks.executeRaw,
tenantSubscription: {
upsert: mocks.upsertTenantSubscription,
},
idempotencyKey: {
findUnique: vi.fn(
async ({ where }: { where: { idempotency_key_partition_scope_key: { partitionKey: string; scope: string; key: string } } }) =>
mocks.markers.get(markerStorageKey(where.idempotency_key_partition_scope_key)) ?? null
),
create: vi.fn(async ({ data }: { data: Marker & { partitionKey: string; scope: string; key: string } }) => {
const storageKey = markerStorageKey(data);
if (mocks.markers.has(storageKey)) throw Object.assign(new Error("duplicate marker"), { code: "P2002" });
const marker: Marker = {
requestHash: data.requestHash,
responseStatus: data.responseStatus,
responseBody: data.responseBody ?? null,
responseHeaders: data.responseHeaders ?? null,
expiresAt: data.expiresAt ?? null,
};
mocks.markers.set(storageKey, marker);
return marker;
}),
update: vi.fn(
async ({
where,
data,
}: {
where: { idempotency_key_partition_scope_key: { partitionKey: string; scope: string; key: string } };
data: Partial<Marker>;
}) => {
if (mocks.failMarkerUpdateOnce) {
mocks.failMarkerUpdateOnce = false;
throw new Error("marker update failed");
}
const storageKey = markerStorageKey(where.idempotency_key_partition_scope_key);
const existing = mocks.markers.get(storageKey);
if (!existing) throw new Error("marker missing");
const marker = { ...existing, ...data };
mocks.markers.set(storageKey, marker);
return marker;
}
),
deleteMany: vi.fn(async ({ where }: { where: { partitionKey: string; scope: string; key: string } }) => {
mocks.markers.delete(markerStorageKey(where));
return { count: 1 };
}),
},
};
}
function args(overrides: Record<string, unknown> = {}) {
return {
request: new Request("https://app.example.test/new-account"),
t: (key: string) => key,
tenantId: "tenant_1",
userId: "user_1",
throwOnFailure: true,
idempotencyKey: IDEMPOTENCY_KEY,
...overrides,
};
}
describe("autosubscribeToTrialOrFreePlan post-commit idempotency", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.markers.clear();
mocks.events.clear();
mocks.subscriptionWrites.length = 0;
mocks.transactionClients.length = 0;
mocks.transactionOpen = false;
mocks.failCommitOnce = false;
mocks.failMarkerUpdateOnce = false;
mocks.getTenant.mockResolvedValue({ id: "tenant_1", name: "Acme", slug: "acme" });
mocks.getOrPersistTenantSubscription.mockImplementation(async () => {
expect(mocks.transactionOpen).toBe(false);
return { id: "subscription_1" };
});
const catalog = [
{
id: "product_1",
title: "Pro",
prices: [
{
id: "price_1",
currency: "EUR",
price: 10,
trialDays: 14,
subscriptionProductId: "product_1",
subscriptionProduct: { title: "Pro" },
},
],
},
];
mocks.getAllSubscriptionProducts.mockResolvedValue(catalog);
mocks.getAllSubscriptionProductsStrict.mockResolvedValue(catalog);
mocks.getUser.mockResolvedValue({ id: "user_1", email: "owner@example.test" });
mocks.executeRaw.mockResolvedValue(1);
mocks.upsertTenantSubscription.mockImplementation(async () => {
expect(mocks.transactionOpen).toBe(true);
return { id: "subscription_1" };
});
mocks.addTenantSubscriptionProduct.mockImplementation(async (input, options) => {
expect(mocks.transactionOpen).toBe(true);
mocks.subscriptionWrites.push({ input, options });
return { id: "tenant_product_1" };
});
mocks.clearTenantSubscriptionCache.mockImplementation(() => {
expect(mocks.transactionOpen).toBe(false);
});
mocks.createIdempotentTenantEvent.mockImplementation(async ({ idempotencyKey }: { idempotencyKey: string }) => {
expect(mocks.transactionOpen).toBe(false);
mocks.events.add(idempotencyKey);
});
mocks.dbTransaction.mockImplementation(async (callback: (tx: ReturnType<typeof idempotencyClient>) => Promise<unknown>) => {
const markerSnapshot = new Map(mocks.markers);
const writeCount = mocks.subscriptionWrites.length;
const tx = idempotencyClient();
mocks.transactionClients.push(tx);
mocks.transactionOpen = true;
try {
const result = await callback(tx);
if (mocks.failCommitOnce) {
mocks.failCommitOnce = false;
throw new Error("transaction commit failed");
}
mocks.transactionOpen = false;
return result;
} catch (error) {
mocks.markers.clear();
for (const [key, marker] of markerSnapshot) mocks.markers.set(key, marker);
mocks.subscriptionWrites.splice(writeCount);
mocks.transactionOpen = false;
throw error;
}
});
});
it("commits the local trial marker before cache and event dispatch and never calls a billing gateway", async () => {
await expect(autosubscribeToTrialOrFreePlan(args() as never)).resolves.toBeUndefined();
expect(mocks.addTenantSubscriptionProduct).toHaveBeenCalledWith(
expect.objectContaining({
tenantSubscriptionId: "subscription_1",
subscriptionProductId: "product_1",
billingProviderSubscriptionId: null,
fromCheckoutSessionId: null,
}),
{
invalidateCache: false,
client: mocks.transactionClients[0],
}
);
expect(mocks.markers.get(expectedMarkerKey())?.responseStatus).toBe(201);
expect(mocks.clearTenantSubscriptionCache).toHaveBeenCalledWith("tenant_1");
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledWith(
expect.objectContaining({
event: "subscription.subscribed",
idempotencyKey: `tenant-bootstrap:tenant_1:${IDEMPOTENCY_KEY}:trial-subscribed`,
})
);
expect(mocks.executeRaw).toHaveBeenCalledOnce();
expect(mocks.upsertTenantSubscription).toHaveBeenCalledWith({
where: { tenantId: "tenant_1" },
create: { tenantId: "tenant_1", billingProviderCustomerId: "" },
update: {},
select: { id: true },
});
expect(mocks.getOrPersistTenantSubscription).not.toHaveBeenCalled();
expect(mocks.completeSelfServiceCheckout).not.toHaveBeenCalled();
});
it("replays without a duplicate subscription while safely retrying cache invalidation and the idempotent event", async () => {
await autosubscribeToTrialOrFreePlan(args() as never);
await autosubscribeToTrialOrFreePlan(args() as never);
expect(mocks.subscriptionWrites).toHaveLength(1);
expect(mocks.addTenantSubscriptionProduct).toHaveBeenCalledOnce();
expect(mocks.clearTenantSubscriptionCache).toHaveBeenCalledTimes(2);
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledTimes(2);
expect(mocks.createIdempotentTenantEvent.mock.calls.map(([input]) => input.idempotencyKey)).toEqual([
`tenant-bootstrap:tenant_1:${IDEMPOTENCY_KEY}:trial-subscribed`,
`tenant-bootstrap:tenant_1:${IDEMPOTENCY_KEY}:trial-subscribed`,
]);
expect(mocks.events.size).toBe(1);
});
it("serializes parallel retries to one subscription product and one event identity", async () => {
await Promise.all([autosubscribeToTrialOrFreePlan(args() as never), autosubscribeToTrialOrFreePlan(args() as never)]);
expect(mocks.addTenantSubscriptionProduct).toHaveBeenCalledOnce();
expect(mocks.subscriptionWrites).toHaveLength(1);
expect(mocks.events).toEqual(new Set([`tenant-bootstrap:tenant_1:${IDEMPOTENCY_KEY}:trial-subscribed`]));
expect(mocks.executeRaw).toHaveBeenCalledTimes(2);
});
it("fails closed when the strict bootstrap catalog read fails", async () => {
const error = new Error("subscription catalog unavailable");
mocks.getAllSubscriptionProductsStrict.mockRejectedValueOnce(error);
await expect(autosubscribeToTrialOrFreePlan(args() as never)).rejects.toBe(error);
expect(mocks.dbTransaction).toHaveBeenCalledOnce();
expect(mocks.getAllSubscriptionProducts).not.toHaveBeenCalled();
expect(mocks.addTenantSubscriptionProduct).not.toHaveBeenCalled();
expect(mocks.createIdempotentTenantEvent).not.toHaveBeenCalled();
expect(mocks.markers.size).toBe(0);
});
it("rolls back the local write when marker completion fails and retries cleanly", async () => {
mocks.failMarkerUpdateOnce = true;
await expect(autosubscribeToTrialOrFreePlan(args() as never)).rejects.toThrow("marker update failed");
expect(mocks.subscriptionWrites).toHaveLength(0);
expect(mocks.markers.has(expectedMarkerKey())).toBe(false);
expect(mocks.clearTenantSubscriptionCache).not.toHaveBeenCalled();
expect(mocks.createIdempotentTenantEvent).not.toHaveBeenCalled();
await expect(autosubscribeToTrialOrFreePlan(args() as never)).resolves.toBeUndefined();
expect(mocks.subscriptionWrites).toHaveLength(1);
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledOnce();
});
it("does not dispatch cache or event effects when the marker transaction commit fails", async () => {
mocks.failCommitOnce = true;
await expect(autosubscribeToTrialOrFreePlan(args() as never)).rejects.toThrow("transaction commit failed");
expect(mocks.subscriptionWrites).toHaveLength(0);
expect(mocks.markers.has(expectedMarkerKey())).toBe(false);
expect(mocks.clearTenantSubscriptionCache).not.toHaveBeenCalled();
expect(mocks.createIdempotentTenantEvent).not.toHaveBeenCalled();
await autosubscribeToTrialOrFreePlan(args() as never);
expect(mocks.subscriptionWrites).toHaveLength(1);
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledOnce();
});
it("keeps a committed local trial and retries only the idempotent event after event commit failure", async () => {
mocks.createIdempotentTenantEvent.mockRejectedValueOnce(new Error("event commit failed"));
await expect(autosubscribeToTrialOrFreePlan(args() as never)).rejects.toThrow("event commit failed");
expect(mocks.subscriptionWrites).toHaveLength(1);
expect(mocks.markers.get(expectedMarkerKey())?.responseStatus).toBe(201);
await autosubscribeToTrialOrFreePlan(args() as never);
expect(mocks.subscriptionWrites).toHaveLength(1);
expect(mocks.addTenantSubscriptionProduct).toHaveBeenCalledOnce();
expect(mocks.clearTenantSubscriptionCache).toHaveBeenCalledTimes(2);
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledTimes(2);
});
it("reuses the committed locale-invariant event payload when the catalog changes before a retry", async () => {
mocks.createIdempotentTenantEvent.mockRejectedValueOnce(new Error("event commit failed"));
await expect(autosubscribeToTrialOrFreePlan(args({ t: (key: string) => `de:${key}` }) as never)).rejects.toThrow("event commit failed");
mocks.getAllSubscriptionProductsStrict.mockResolvedValueOnce([
{
id: "product_2",
title: "Business",
prices: [
{
id: "price_2",
currency: "EUR",
price: 20,
trialDays: 7,
subscriptionProductId: "product_2",
subscriptionProduct: { title: "Business" },
},
],
},
]);
mocks.getTenant.mockResolvedValueOnce({ id: "tenant_1", name: "Renamed", slug: "renamed" });
mocks.getUser.mockResolvedValueOnce({ id: "user_1", email: "changed@example.test" });
await autosubscribeToTrialOrFreePlan(args({ t: (key: string) => `en:${key}` }) as never);
expect(mocks.subscriptionWrites).toHaveLength(1);
expect(mocks.getAllSubscriptionProductsStrict).toHaveBeenCalledOnce();
expect(mocks.getTenant).toHaveBeenCalledOnce();
expect(mocks.getUser).toHaveBeenCalledOnce();
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledTimes(2);
const eventPayloads = mocks.createIdempotentTenantEvent.mock.calls.map(([input]) => input.data);
expect(eventPayloads).toEqual([
{
user: { id: "user_1", email: "owner@example.test" },
tenant: { id: "tenant_1", name: "Acme", slug: "acme" },
subscription: { product: { id: "product_1", title: "Pro" } },
},
{
user: { id: "user_1", email: "owner@example.test" },
tenant: { id: "tenant_1", name: "Acme", slug: "acme" },
subscription: { product: { id: "product_1", title: "Pro" } },
},
]);
});
it("fails closed when a committed trial marker contains an invalid event projection", async () => {
await autosubscribeToTrialOrFreePlan(args() as never);
const marker = mocks.markers.get(expectedMarkerKey());
expect(marker).toBeDefined();
if (marker) {
marker.responseBody = {
state: "subscribed",
subscriptionProductId: "product_1",
subscriptionPriceId: "price_1",
eventData: { tenant: { id: "tenant_other" } },
};
}
await expect(autosubscribeToTrialOrFreePlan(args() as never)).rejects.toThrow("Workspace trial idempotency marker is invalid");
expect(mocks.subscriptionWrites).toHaveLength(1);
});
it("keeps legacy callers fail-soft while allowing workspace creation to fail closed", async () => {
mocks.addTenantSubscriptionProduct.mockRejectedValue(new Error("subscription write failed"));
await expect(autosubscribeToTrialOrFreePlan(args({ idempotencyKey: undefined, throwOnFailure: false }) as never)).resolves.toBeUndefined();
await expect(autosubscribeToTrialOrFreePlan(args({ idempotencyKey: undefined }) as never)).rejects.toThrow("subscription write failed");
expect(mocks.loggerError).toHaveBeenCalledTimes(2);
expect(JSON.stringify(mocks.loggerError.mock.calls)).not.toContain("subscription write failed");
expect(mocks.createEvent).not.toHaveBeenCalled();
expect(mocks.completeSelfServiceCheckout).not.toHaveBeenCalled();
});
it("does not complete a marker when RLS cannot see the committed tenant", async () => {
mocks.getTenant.mockResolvedValue(null);
await expect(autosubscribeToTrialOrFreePlan(args({ throwOnFailure: false }) as never)).resolves.toBeUndefined();
await expect(autosubscribeToTrialOrFreePlan(args() as never)).rejects.toThrow("Tenant unavailable for auto-subscribe");
expect(mocks.getOrPersistTenantSubscription).not.toHaveBeenCalled();
expect(mocks.markers.size).toBe(0);
});
});
@@ -8,23 +8,20 @@ import {
createSubscriptionFeature,
updateSubscriptionProductBillingProviderId,
updateSubscriptionPriceBillingProviderId,
deleteSubscriptionPrice,
deleteSubscriptionProduct,
updateSubscriptionProduct,
deleteSubscriptionFeatures,
deleteSubscriptionUsageBasedTier,
deleteSubscriptionUsageBasedPrice,
createSubscriptionUsageBasedPrice,
createSubscriptionUsageBasedTier,
getSubscriptionProduct,
getAllSubscriptionProducts,
getAllSubscriptionProductsStrict,
} from "../../db/subscriptionProducts.db.server";
import { CheckoutSessionStatus, SubscriptionPrice, SubscriptionUsageBasedPrice } from "@hivegrid/db/prisma-browser";
import { getOrPersistTenantSubscription } from "../../db/tenantSubscriptions.db.server";
import { getTenant } from "../../db/tenants.db.server";
import { SubscriptionUsageBasedPriceDto } from "~/application/dtos/subscriptions/SubscriptionUsageBasedPriceDto";
import { TFunction } from "i18next";
import { TenantTypesApi } from "../../api/.server/TenantTypesApi";
import { addTenantSubscriptionProduct } from "../../db/subscriptions/tenantSubscriptionProducts.db.server";
import EventsService from "../../../modules/events/services/.server/EventsService";
import { SubscriptionSubscribedDto } from "~/modules/events/dtos/SubscriptionSubscribedDto";
@@ -35,28 +32,85 @@ import currencies from "~/application/pricing/currencies";
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
import { createScopedLogger } from "~/utils/logger.server";
import { completeSelfServiceCheckout } from "~/services/billing/self-service-checkout.server";
import { db } from "~/utils/db.server";
import { withIdempotency, type IdempotencyClient } from "@hivegrid/foundation";
import type { TenantBillingClient } from "@hivegrid/db/subscriptions.server";
import { toSafeErrorLog } from "~/utils/safeErrorLog.server";
const pricingLogger = createScopedLogger("pricing");
const WORKSPACE_TRIAL_AUTOSUBSCRIBE_SCOPE = "tenant-bootstrap/workspace-trial-autosubscribe-v1";
function localBillingProviderId(prefix: string, seed: string) {
return `local_${prefix}_${seed.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 72)}`;
type WorkspaceTrialMarkerBody =
| {
state: "subscribed";
subscriptionProductId: string;
subscriptionPriceId: string | null;
eventData: SubscriptionSubscribedDto;
}
| {
state: "not-subscribed";
tenantId: string;
reason: "default-currency-unavailable" | "no-eligible-plan";
};
type WorkspaceTrialTransactionClient = IdempotencyClient & {
$executeRaw(query: TemplateStringsArray, ...values: unknown[]): Promise<unknown>;
tenantSubscription: {
upsert(args: {
where: { tenantId: string };
create: { tenantId: string; billingProviderCustomerId: string };
update: Record<string, never>;
select: { id: true };
}): Promise<{ id: string }>;
};
};
function readWorkspaceTrialMarkerBody(body: unknown): WorkspaceTrialMarkerBody {
if (!isRecord(body)) throw new Error("Workspace trial idempotency marker is invalid");
const candidate = body;
if (
candidate.state === "not-subscribed" &&
typeof candidate.tenantId === "string" &&
(candidate.reason === "default-currency-unavailable" || candidate.reason === "no-eligible-plan")
) {
return candidate as WorkspaceTrialMarkerBody;
}
const eventData = candidate.eventData;
const tenant = isRecord(eventData) ? eventData.tenant : null;
const subscription = isRecord(eventData) ? eventData.subscription : null;
const product = isRecord(subscription) ? subscription.product : null;
const user = isRecord(eventData) ? eventData.user : undefined;
if (
candidate.state !== "subscribed" ||
typeof candidate.subscriptionProductId !== "string" ||
!(typeof candidate.subscriptionPriceId === "string" || candidate.subscriptionPriceId === null) ||
!isRecord(eventData) ||
!isRecord(tenant) ||
typeof tenant.id !== "string" ||
typeof tenant.name !== "string" ||
typeof tenant.slug !== "string" ||
!isRecord(subscription) ||
!isRecord(product) ||
product.id !== candidate.subscriptionProductId ||
typeof product.title !== "string" ||
!(subscription.session === undefined || typeof subscription.session === "string") ||
!(user === null || (isRecord(user) && typeof user.id === "string" && typeof user.email === "string"))
) {
throw new Error("Workspace trial idempotency marker is invalid");
}
return candidate as WorkspaceTrialMarkerBody;
}
export async function createPlans(plans: SubscriptionProductDto[]) {
for (const plan of plans.sort((a, b) => a.order - b.order)) {
await createPlan(
plan,
plan.prices.map((price) => {
return {
billingPeriod: price.billingPeriod,
currency: price.currency,
price: Number(price.price),
};
}),
plan.features,
plan.usageBasedPrices
);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value && typeof value === "object" && !Array.isArray(value));
}
function localBillingProviderId(prefix: string, seed: string) {
return `local_${prefix}_${seed
.toLowerCase()
.replace(/[^a-z0-9]+/g, "_")
.replace(/^_+|_+$/g, "")
.slice(0, 72)}`;
}
export async function createPlan(
@@ -64,7 +118,7 @@ export async function createPlan(
prices: { billingPeriod: SubscriptionBillingPeriod; price: number; currency: string; trialDays?: number }[],
features: SubscriptionFeatureDto[],
usageBasedPrices?: SubscriptionUsageBasedPriceDto[],
t?: TFunction
_t?: TFunction
) {
const productBillingProviderId = plan.billingProviderId || localBillingProviderId("product", plan.title);
const product = await createSubscriptionProduct({
@@ -78,6 +132,7 @@ export async function createPlan(
groupDescription: plan.groupDescription ?? null,
active: plan.active,
public: plan.public,
kind: plan.kind ?? "recurring_add_on",
billingAddressCollection: plan.billingAddressCollection ?? "auto",
hasQuantity: plan.hasQuantity ?? false,
canBuyAgain: plan.canBuyAgain ?? false,
@@ -117,13 +172,13 @@ export async function createPlan(
usageBasedPrices.map(async (usageBasedPrice) => {
pricingLogger.info(
{ op: "createUsageBasedPrice", productId: product.id, billingPeriod: usageBasedPrice.billingPeriod, unit: usageBasedPrice.unit },
"Creating usage-based price",
"Creating usage-based price"
);
const createdPrice = await createSubscriptionUsageBasedPrice({
subscriptionProductId: product.id,
billingProviderId: localBillingProviderId(
"usage",
`${product.id}_${usageBasedPrice.billingPeriod}_${usageBasedPrice.currency}_${usageBasedPrice.unit}`,
`${product.id}_${usageBasedPrice.billingPeriod}_${usageBasedPrice.currency}_${usageBasedPrice.unit}`
),
billingPeriod: usageBasedPrice.billingPeriod,
currency: usageBasedPrice.currency,
@@ -202,42 +257,14 @@ export async function updatePlan(plan: SubscriptionProductDto, features: Subscri
}
export async function deletePlan(plan: SubscriptionProductDto) {
if (!plan.id) throw new Error("Subscription product id is required for deletion");
// Catalog children use ON DELETE CASCADE. One product delete is therefore a
// single atomic statement; a tenant-product FK rejects the whole statement
// without leaving partially deleted prices, tiers, or features behind.
await deleteSubscriptionProduct(plan.id);
await clearAllSubscriptionsCache();
pricingLogger.info({ op: "deletePlan.flatPrices", planId: plan.id, count: plan.prices?.length ?? 0 }, "Deleting flat-rate prices");
await Promise.all(
plan.prices
.map(async (price) => {
if (price.id) {
await deleteSubscriptionPrice(price.id);
}
return null;
})
);
pricingLogger.info(
{ op: "deletePlan.usageBasedPrices", planId: plan.id, count: plan.usageBasedPrices?.length ?? 0 },
"Deleting usage-based prices",
);
if (plan.usageBasedPrices) {
await Promise.all(
plan.usageBasedPrices?.map(async (price) => {
await Promise.all(
price.tiers.map(async (tier) => {
return deleteSubscriptionUsageBasedTier(tier.id);
})
);
await deleteSubscriptionUsageBasedPrice(price.id);
return null;
})
);
}
if (plan.id) {
await deleteSubscriptionProduct(plan.id);
}
pricingLogger.info({ op: "deletePlan", planId: plan.id }, "Deleted subscription product atomically");
}
export type CheckoutSessionResponse = {
@@ -273,8 +300,8 @@ export async function addTenantProductsFromCheckoutSession({
tenantId,
user,
checkoutSession,
createdUserId,
createdTenantId,
createdUserId: _createdUserId,
createdTenantId: _createdTenantId,
t,
}: {
request: Request;
@@ -309,7 +336,7 @@ export async function addTenantProductsFromCheckoutSession({
hasSubscribed,
recurringCount: recurringSubscriptions.length,
},
"Cancelling existing subscriptions before new subscribe",
"Cancelling existing subscriptions before new subscribe"
);
if (hasSubscribed && recurringSubscriptions.length > 0) {
await Promise.all(
@@ -321,7 +348,7 @@ export async function addTenantProductsFromCheckoutSession({
subscriptionId: recurringSubscription.id,
productId: recurringSubscription.subscriptionProductId,
},
"Cancelling tenant subscription",
"Cancelling tenant subscription"
);
return await cancelTenantSubscription(recurringSubscription.id, { tenantId, userId: user.id, t });
})
@@ -395,8 +422,6 @@ export async function addTenantProductsFromCheckoutSession({
},
} satisfies SubscriptionSubscribedDto,
});
await TenantTypesApi.setTenantTypes({ tenantId, subscriptionProduct });
}
})
);
@@ -405,52 +430,158 @@ export async function addTenantProductsFromCheckoutSession({
export async function autosubscribeToTrialOrFreePlan({
request,
t,
t: _t,
tenantId,
userId,
throwOnFailure = false,
idempotencyKey,
}: {
request: Request;
t: TFunction;
tenantId: string;
userId: string | null;
throwOnFailure?: boolean;
idempotencyKey?: string;
}) {
pricingLogger.info({ op: "autosubscribeToTrialOrFreePlan.start", tenantId }, "Starting auto-subscribe to trial/free plan");
const tenant = await getTenant(tenantId);
if (!tenant) {
pricingLogger.warn({ op: "autosubscribeToTrialOrFreePlan.start", tenantId }, "Tenant not found; skipping");
return;
}
const tenantSubscription = await getOrPersistTenantSubscription(tenant.id);
const defaultCurrency = currencies.find((f) => f.default)?.value;
if (!defaultCurrency) {
return;
}
const allProducts = await getAllSubscriptionProducts(true);
const productsFree: SubscriptionPriceDto[] = [];
const productsWithTrialDays: SubscriptionPriceDto[] = [];
try {
if (idempotencyKey) {
const markerBody = await db.$transaction(async (tx) => {
const client = tx as unknown as WorkspaceTrialTransactionClient;
const lockKey = `${WORKSPACE_TRIAL_AUTOSUBSCRIBE_SCOPE}:${tenantId}:${idempotencyKey}`;
await client.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, 0))`;
const result = await withIdempotency(
{
tenantId,
scope: WORKSPACE_TRIAL_AUTOSUBSCRIBE_SCOPE,
key: idempotencyKey,
fingerprint: {
version: 1,
tenantId,
userId,
},
},
client,
async () => {
const tenant = await getTenant(tenantId);
if (!tenant) {
throw new Error("Tenant unavailable for auto-subscribe");
}
const defaultCurrency = currencies.find((item) => item.default)?.value;
if (!defaultCurrency) {
return {
status: 204,
body: {
state: "not-subscribed",
tenantId,
reason: "default-currency-unavailable",
} satisfies WorkspaceTrialMarkerBody,
};
}
// Strict reads happen only for a new marker. A committed replay must
// remain dispatchable even if the mutable catalog changes later.
const allProducts = await getAllSubscriptionProductsStrict(true);
const candidate = allProducts
.flatMap((product) => product.prices.map((price) => ({ price, productTitle: product.title })))
.find(({ price }) => price.currency === defaultCurrency && (price.trialDays > 0 || price.price === undefined || Number(price.price) === 0));
pricingLogger.debug(
{ op: "autosubscribeToTrialOrFreePlan.products", tenantId, count: allProducts.length },
"Auto-subscribe candidate products loaded"
);
if (!candidate) {
return {
status: 204,
body: {
state: "not-subscribed",
tenantId,
reason: "no-eligible-plan",
} satisfies WorkspaceTrialMarkerBody,
};
}
const tenantSubscription = await client.tenantSubscription.upsert({
where: { tenantId },
create: { tenantId, billingProviderCustomerId: "" },
update: {},
select: { id: true },
});
const { price, productTitle } = candidate;
const user = userId ? await getUser(userId) : null;
const currentMarkerBody: WorkspaceTrialMarkerBody = {
state: "subscribed",
subscriptionProductId: price.subscriptionProductId,
subscriptionPriceId: price.id ?? null,
eventData: {
user: !user ? null : { id: user.id, email: user.email },
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug },
subscription: {
product: {
id: price.subscriptionProductId,
title: productTitle,
},
},
},
};
await addTenantSubscriptionProduct(
{
tenantSubscriptionId: tenantSubscription.id,
subscriptionProductId: price.subscriptionProductId,
quantity: 1,
billingProviderSubscriptionId: null,
fromCheckoutSessionId: null,
prices: [{ subscriptionPriceId: price.id }],
},
{
invalidateCache: false,
client: tx as unknown as TenantBillingClient,
}
);
return { status: 201, body: currentMarkerBody };
}
);
const stored = readWorkspaceTrialMarkerBody(result.body);
const storedTenantId = stored.state === "subscribed" ? stored.eventData.tenant.id : stored.tenantId;
if (storedTenantId !== tenantId) {
throw new Error("Workspace trial idempotency marker is invalid");
}
return stored;
});
pricingLogger.debug(
{ op: "autosubscribeToTrialOrFreePlan.products", tenantId, count: allProducts.length },
"Auto-subscribe candidate products loaded",
);
allProducts.forEach((product) => {
if (product.prices.length === 0) {
if (markerBody.state === "not-subscribed") {
pricingLogger.info({ op: "autosubscribeToTrialOrFreePlan.none", tenantId, reason: markerBody.reason }, "No auto-subscription product was selected");
return;
}
clearTenantSubscriptionCache(tenantId);
await EventsService.createIdempotentTenantEvent({
request,
event: "subscription.subscribed",
tenantId,
userId: markerBody.eventData.user?.id ?? null,
data: markerBody.eventData,
idempotencyKey: `tenant-bootstrap:${tenantId}:${idempotencyKey}:trial-subscribed`,
});
return;
}
const allPricesAreZero = product.prices.every((price) => price.currency === defaultCurrency && (price.price === undefined || Number(price.price) === 0));
if (allPricesAreZero) {
productsFree.push(product.prices[0]);
}
const firstPriceWithTrialDays = product.prices.find(
(price) => price.currency === defaultCurrency && (price.trialDays > 0 || price.price === undefined || Number(price.price) === 0)
);
if (firstPriceWithTrialDays) {
productsWithTrialDays.push(firstPriceWithTrialDays);
}
});
try {
const tenant = await getTenant(tenantId);
if (!tenant) {
throw new Error("Tenant unavailable for auto-subscribe");
}
const tenantSubscription = await getOrPersistTenantSubscription(tenant.id);
const defaultCurrency = currencies.find((item) => item.default)?.value;
if (!defaultCurrency) return;
const allProducts = throwOnFailure ? await getAllSubscriptionProductsStrict(true) : await getAllSubscriptionProducts(true);
const productsFree: SubscriptionPriceDto[] = [];
const productsWithTrialDays: SubscriptionPriceDto[] = [];
allProducts.forEach((product) => {
if (product.prices.length === 0) return;
const allPricesAreZero = product.prices.every((price) => price.currency === defaultCurrency && (price.price === undefined || Number(price.price) === 0));
if (allPricesAreZero) productsFree.push(product.prices[0]);
const firstPriceWithTrialDays = product.prices.find(
(price) => price.currency === defaultCurrency && (price.trialDays > 0 || price.price === undefined || Number(price.price) === 0)
);
if (firstPriceWithTrialDays) productsWithTrialDays.push(firstPriceWithTrialDays);
});
if (productsWithTrialDays.length > 0) {
pricingLogger.info(
{
@@ -459,23 +590,26 @@ export async function autosubscribeToTrialOrFreePlan({
productCount: productsWithTrialDays.length,
productIds: productsWithTrialDays.map((p) => p.subscriptionProductId),
},
"Autosubscribing tenant to trial/free plan",
"Autosubscribing tenant to trial/free plan"
);
const price = productsWithTrialDays[0];
await addTenantSubscriptionProduct({
const subscriptionProductInput = {
tenantSubscriptionId: tenantSubscription.id,
subscriptionProductId: price.subscriptionProductId,
quantity: 1,
billingProviderSubscriptionId: "",
// Workspace auto-trials are local entitlements only. Provider checkout
// and subscription creation remain exclusive to the explicit billing flow.
billingProviderSubscriptionId: null,
fromCheckoutSessionId: null,
prices: [
{
subscriptionPriceId: price.id,
},
],
});
};
await addTenantSubscriptionProduct(subscriptionProductInput);
const user = userId ? await getUser(userId) : null;
await EventsService.create({
const eventArgs = {
request,
event: "subscription.subscribed",
tenantId: tenant.id,
@@ -484,28 +618,26 @@ export async function autosubscribeToTrialOrFreePlan({
user: !user ? null : { id: user.id, email: user.email },
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug },
subscription: {
product: {
id: price.subscriptionProductId,
title: t(price.subscriptionProduct?.title ?? "") || price.subscriptionProduct?.title || "",
},
product: { id: price.subscriptionProductId, title: price.subscriptionProduct?.title ?? "" },
},
} satisfies SubscriptionSubscribedDto,
});
} as const;
await EventsService.create(eventArgs);
} else if (productsFree.length > 0) {
// TODO(pricing): implement free-plan auto-subscribe. Free plans are planned for
// HiveGrid, so this branch must mirror the trial path above (create the free
// subscription + emit "subscription.subscribed") instead of only logging.
pricingLogger.info(
{ op: "autosubscribeToTrialOrFreePlan.free", tenantId, count: productsFree.length },
"Free products available but auto-subscribe-free path not implemented yet",
"Free products available but auto-subscribe-free path not implemented yet"
);
} else {
pricingLogger.info(
{ op: "autosubscribeToTrialOrFreePlan.none", tenantId },
"No auto-subscription products/plans found",
);
pricingLogger.info({ op: "autosubscribeToTrialOrFreePlan.none", tenantId }, "No auto-subscription products/plans found");
}
} catch (e: any) {
pricingLogger.error({ err: e, op: "autosubscribeToTrialOrFreePlan", tenantId }, "Auto-subscribe failed");
pricingLogger.error({ ...toSafeErrorLog(e), op: "autosubscribeToTrialOrFreePlan", tenantId }, "Auto-subscribe failed");
if (throwOnFailure) {
throw e;
}
}
}
@@ -20,6 +20,7 @@ vi.mock("~/shared-store.server", async () => {
const store = createSharedStore({ namespace: "web-test", adapter });
return {
getSharedStore: () => store,
getCrossAppCacheStore: () => store,
__setSharedStoreFactoryForTests: vi.fn(),
__resetSharedStoreForTests: vi.fn(),
};
@@ -1,13 +1,13 @@
import { createTwoTierCache, type TwoTierCache } from "@hivegrid/shared-store";
import type { TenantSubscriptionWithDetails } from "@hivegrid/db/subscriptions.server";
import { getSharedStore } from "~/shared-store.server";
import { getCrossAppCacheStore } from "~/shared-store.server";
import { clearCacheKey, clearCacheKeyPrefix } from "~/utils/cache.server";
import { createScopedLogger } from "~/utils/logger.server";
/**
* Subscription cache (two-tier). L1 = in-process Map, L2 = SharedStore;
* cross-replica purges via pub/sub on channel
* `shared-store:web:ch:cache:subscription:invalidate`.
* `shared-store:cross-app-cache:ch:cache:subscription:invalidate`.
*
* Bootstrap (idempotent): call `subscribeSubscriptionCache()` once during
* web boot so this replica listens for invalidation messages emitted by
@@ -37,7 +37,7 @@ function ttlSecondsFromEnv(): number {
export function getSubscriptionCache(): TwoTierCache<TenantSubscriptionWithDetails | null> {
if (cacheSingleton) return cacheSingleton;
cacheSingleton = createTwoTierCache<TenantSubscriptionWithDetails | null>({
store: getSharedStore(),
store: getCrossAppCacheStore(),
namespace: "subscription",
ttlSeconds: ttlSecondsFromEnv(),
pubsubEnabled: pubsubEnabledFromEnv(),
@@ -0,0 +1,52 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
const mocks = vi.hoisted(() => ({
getTenantSubscription: vi.fn(),
getTenantSubscriptions: vi.fn(),
}));
vi.mock("../../db/tenantSubscriptions.db.server", () => ({
getTenantSubscription: mocks.getTenantSubscription,
getTenantSubscriptions: mocks.getTenantSubscriptions,
}));
import { getMrr } from "./subscriptionService";
describe("getMrr tenant RLS aggregation", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("loads every tenant subscription only inside its matching tenant context", async () => {
mocks.getTenantSubscription.mockImplementation(async (tenantId: string) => {
expect(getRlsExecutionContext()).toMatchObject({ userId: "operator_1", tenantId });
return {
id: `subscription_${tenantId}`,
tenantId,
products: [
{
endsAt: tenantId === "tenant_2" ? new Date("2020-01-01T00:00:00.000Z") : null,
prices: [
{
subscriptionPrice: {
billingPeriod: SubscriptionBillingPeriod.MONTHLY,
price: 199,
currency: "eur",
},
},
],
},
],
};
});
const result = await runWithRlsContext({ userId: "operator_1" }, () => getMrr("eur", ["tenant_1", "tenant_2"]));
expect(result).toEqual({ total: 199, count: 1 });
expect(mocks.getTenantSubscription).toHaveBeenCalledTimes(2);
expect(getRlsExecutionContext()).toBeNull();
});
});
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vitest";
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("../../db.server", () => ({ db: {} }));
vi.mock("../../db/entities/entities.db.server", () => ({ findSimpleEntityByName: vi.fn() }));
@@ -30,34 +30,130 @@ vi.mock("~/utils/db/subscriptions/tenantSubscriptionProducts.db.server", () => (
cancelTenantSubscriptionProduct: vi.fn(),
getTenantSubscriptionProductById: vi.fn(),
}));
vi.mock("~/services/billing/product-acquisition.server", () => {
class ProductAcquisitionError extends Error {
constructor(readonly code: string) {
super(code);
}
}
return {
ProductAcquisitionError,
cancelRecurringProductAcquisition: vi.fn(),
};
});
vi.mock("~/modules/events/services/.server/EventsService", () => ({ default: { create: vi.fn() } }));
vi.mock("~/utils/db/tenants.db.server", () => ({ getTenant: vi.fn() }));
vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn() }));
vi.mock("~/modules/emails/utils/EmailTemplates", () => ({ default: {} }));
vi.mock("~/utils/db/appConfiguration.db.server", () => ({ getAppConfiguration: vi.fn() }));
import {
cancelTenantSubscription,
clearAllSubscriptionsCache,
clearTenantSubscriptionCache,
} from "./subscriptionService";
import { getTenantSubscriptionProductById } from "~/utils/db/subscriptions/tenantSubscriptionProducts.db.server";
import { cancelTenantSubscription, clearAllSubscriptionsCache, clearTenantSubscriptionCache } from "./subscriptionService";
import { cancelTenantSubscriptionProduct, getTenantSubscriptionProductById } from "~/utils/db/subscriptions/tenantSubscriptionProducts.db.server";
import { getTenant } from "~/utils/db/tenants.db.server";
import { getUser } from "~/utils/db/users.db.server";
import { clearCacheKey } from "../../cache.server";
import { listTenantSubscriptionIds } from "@hivegrid/db/subscriptions.server";
import { cancelRecurringProductAcquisition, ProductAcquisitionError } from "~/services/billing/product-acquisition.server";
function subscriptionProduct(
overrides: {
kind?: "base_plan" | "recurring_add_on" | "one_time_setup" | "contract_override";
acquisition?: { productKind: "recurring_add_on"; status: string; lagoSubscriptionId: string | null } | null;
} = {}
): Awaited<ReturnType<typeof getTenantSubscriptionProductById>> {
return {
id: "tenant-sub-product-id",
subscriptionProductId: "product-id",
billingProviderSubscriptionId: null,
subscriptionProduct: { id: "product-id", title: "Product", kind: overrides.kind ?? "recurring_add_on" },
acquisition:
overrides.acquisition === undefined
? { productKind: "recurring_add_on", status: "active", lagoSubscriptionId: "lago_subscription_1" }
: overrides.acquisition,
} as Awaited<ReturnType<typeof getTenantSubscriptionProductById>>;
}
describe("cancelTenantSubscription", () => {
it("returns without logging when the product is not subscribed", async () => {
vi.mocked(getTenantSubscriptionProductById).mockResolvedValueOnce({
id: "tenant-sub-product-id",
billingProviderSubscriptionId: null,
} as Awaited<ReturnType<typeof getTenantSubscriptionProductById>>);
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
beforeEach(() => {
vi.mocked(getTenantSubscriptionProductById).mockReset();
vi.mocked(getUser).mockReset();
vi.mocked(getTenant).mockReset();
vi.mocked(cancelRecurringProductAcquisition).mockReset();
vi.mocked(cancelTenantSubscriptionProduct).mockReset();
vi.mocked(clearCacheKey).mockClear();
subscriptionCacheInvalidateMock.mockClear();
});
it.each(["base_plan", "one_time_setup"] as const)("never cancels a %s product", async (kind) => {
vi.mocked(getTenantSubscriptionProductById).mockResolvedValueOnce(subscriptionProduct({ kind, acquisition: null }));
await expect(cancelTenantSubscription("tenant-sub-product-id", { tenantId: "tenant-id", userId: "user-id" })).rejects.toMatchObject({
code: "PRODUCT_KIND_INVALID",
});
expect(cancelRecurringProductAcquisition).not.toHaveBeenCalled();
expect(cancelTenantSubscriptionProduct).not.toHaveBeenCalled();
expect(getUser).not.toHaveBeenCalled();
});
it("fails closed when a recurring add-on has no acquisition", async () => {
vi.mocked(getTenantSubscriptionProductById).mockResolvedValueOnce(subscriptionProduct({ acquisition: null }));
await expect(cancelTenantSubscription("tenant-sub-product-id", { tenantId: "tenant-id", userId: "user-id" })).rejects.toMatchObject({
code: "ACQUISITION_NOT_FOUND",
});
expect(cancelRecurringProductAcquisition).not.toHaveBeenCalled();
expect(cancelTenantSubscriptionProduct).not.toHaveBeenCalled();
});
it("fails closed when a recurring acquisition has no Lago subscription reference", async () => {
vi.mocked(getTenantSubscriptionProductById).mockResolvedValueOnce(
subscriptionProduct({ acquisition: { productKind: "recurring_add_on", status: "active", lagoSubscriptionId: null } })
);
await expect(cancelTenantSubscription("tenant-sub-product-id", { tenantId: "tenant-id", userId: "user-id" })).rejects.toMatchObject({
code: "IDEMPOTENCY_CONFLICT",
});
expect(cancelRecurringProductAcquisition).not.toHaveBeenCalled();
expect(cancelTenantSubscriptionProduct).not.toHaveBeenCalled();
});
it("delegates an acquisition-backed recurring add-on to the atomic provider cancellation path", async () => {
vi.mocked(getTenantSubscriptionProductById).mockResolvedValueOnce(subscriptionProduct());
vi.mocked(getUser).mockResolvedValueOnce({ id: "user-id", email: "owner@example.test" } as Awaited<ReturnType<typeof getUser>>);
vi.mocked(getTenant).mockResolvedValueOnce({ id: "tenant-id", name: "Tenant" } as Awaited<ReturnType<typeof getTenant>>);
vi.mocked(cancelRecurringProductAcquisition).mockResolvedValueOnce({} as Awaited<ReturnType<typeof cancelRecurringProductAcquisition>>);
await cancelTenantSubscription("tenant-sub-product-id", { tenantId: "tenant-id", userId: "user-id" });
expect(consoleLog).not.toHaveBeenCalled();
expect(cancelRecurringProductAcquisition).toHaveBeenCalledWith({
tenantId: "tenant-id",
actorUserId: "user-id",
tenantSubscriptionProductId: "tenant-sub-product-id",
eventData: {
user: { id: "user-id", email: "owner@example.test" },
tenant: { id: "tenant-id", name: "Tenant" },
subscription: { product: { id: "product-id", title: "Product" } },
},
});
expect(cancelTenantSubscriptionProduct).not.toHaveBeenCalled();
expect(clearCacheKey).toHaveBeenCalledWith("tenantSubscription:tenant-id");
});
consoleLog.mockRestore();
it("propagates an acquisition lookup failure without locally revoking the entitlement", async () => {
vi.mocked(getTenantSubscriptionProductById).mockResolvedValueOnce(subscriptionProduct());
vi.mocked(getUser).mockResolvedValueOnce({ id: "user-id", email: "owner@example.test" } as Awaited<ReturnType<typeof getUser>>);
vi.mocked(getTenant).mockResolvedValueOnce({ id: "tenant-id", name: "Tenant" } as Awaited<ReturnType<typeof getTenant>>);
vi.mocked(cancelRecurringProductAcquisition).mockRejectedValueOnce(new ProductAcquisitionError("ACQUISITION_NOT_FOUND"));
await expect(cancelTenantSubscription("tenant-sub-product-id", { tenantId: "tenant-id", userId: "user-id" })).rejects.toMatchObject({
code: "ACQUISITION_NOT_FOUND",
});
expect(cancelTenantSubscriptionProduct).not.toHaveBeenCalled();
expect(clearCacheKey).not.toHaveBeenCalledWith("tenantSubscription:tenant-id");
});
});
@@ -95,9 +191,7 @@ describe("subscription cache invalidation", () => {
it("clearAllSubscriptionsCache broadcasts a wildcard cross-replica invalidation", async () => {
subscriptionCacheInvalidateMock.mockClear();
vi.mocked(listTenantSubscriptionIds).mockResolvedValueOnce(
[] as Awaited<ReturnType<typeof listTenantSubscriptionIds>>,
);
vi.mocked(listTenantSubscriptionIds).mockResolvedValueOnce([] as Awaited<ReturnType<typeof listTenantSubscriptionIds>>);
await clearAllSubscriptionsCache();
@@ -14,25 +14,30 @@ import {
type TenantSubscriptionWithDetails,
} from "@hivegrid/db/subscriptions.server";
import { getTenantSubscription, getTenantSubscriptions } from "../../db/tenantSubscriptions.db.server";
import { sendEmail } from "~/modules/emails/services/EmailService";
import { apiKeyCreditableStatusCodes, apiKeyIgnoreEndpoints } from "../../helpers/ApiKeyHelper";
import { getBaseURL } from "../../url.server";
import { cachified, clearCacheKey } from "../../cache.server";
import { getSubscriptionCache } from "./subscriptionCache.server";
import DateUtils from "~/utils/shared/DateUtils";
import { TFunction } from "i18next";
import { cancelTenantSubscriptionProduct, getTenantSubscriptionProductById } from "~/utils/db/subscriptions/tenantSubscriptionProducts.db.server";
import { getTenantSubscriptionProductById } from "~/utils/db/subscriptions/tenantSubscriptionProducts.db.server";
import { SubscriptionCancelledDto } from "~/modules/events/dtos/SubscriptionCancelledDto";
import EventsService from "~/modules/events/services/.server/EventsService";
import { getTenant } from "~/utils/db/tenants.db.server";
import { getUser } from "~/utils/db/users.db.server";
import EmailTemplates from "~/modules/emails/utils/EmailTemplates";
import { getMailTranslatorFromRequest } from "~/locale/mail-translator.server";
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { cancelRecurringProductAcquisition, ProductAcquisitionError } from "~/services/billing/product-acquisition.server";
const ADMIN_MRR_TENANT_QUERY_BATCH_SIZE = 10;
function getActiveTenantSubscriptionProducts(subscription: TenantSubscriptionWithDetails | null): TenantSubscriptionWithDetails["products"] {
const now = Date.now();
return subscription?.products.filter((product) => !product.endsAt || new Date(product.endsAt).getTime() > now) ?? [];
return (
subscription?.products.filter(
(product) =>
!product.cancelledAt &&
(!product.currentPeriodStart || new Date(product.currentPeriodStart).getTime() <= now) &&
(!product.endsAt || new Date(product.endsAt).getTime() > now)
) ?? []
);
}
export async function getPlanFeaturesUsage(tenantId: string, tenantSubscription?: TenantSubscriptionWithDetails | null): Promise<PlanFeatureUsageDto[]> {
@@ -44,8 +49,15 @@ export async function getPlanFeaturesUsage(tenantId: string, tenantSubscription?
}
const myUsage: PlanFeatureUsageDto[] = [];
let allFeatures: SubscriptionFeatureDto[] = [];
const features: { name: string; code?: string | null; order: number; title: string; type: SubscriptionFeatureLimitType; value: number; accumulate: boolean }[] =
await getAllSubscriptionFeatures();
const features: {
name: string;
code?: string | null;
order: number;
title: string;
type: SubscriptionFeatureLimitType;
value: number;
accumulate: boolean;
}[] = await getAllSubscriptionFeatures();
features
.filter((f) => (f.code || f.name) && (f.code || f.name) !== DefaultFeatures.Credits)
.forEach((feature) => {
@@ -314,57 +326,62 @@ async function getSpentCredits(where: Prisma.CreditWhereInput): Promise<number>
// }
export async function getActiveTenantSubscriptions(tenantId: string) {
const mySubscription = await cachified({
key: `tenantSubscription:${tenantId}`,
ttl: 1000 * 60 * 60, // 1 hour
getFreshValue: () => getTenantSubscription(tenantId),
});
if (mySubscription) {
await Promise.all(
mySubscription.products.map(async (item) => {
if (item.billingProviderSubscriptionId) {
let currentPeriod =
item.currentPeriodStart && item.currentPeriodEnd
? {
start: DateUtils.getDateStartOfDay(item.currentPeriodStart),
end: DateUtils.getDateEndOfDay(item.currentPeriodEnd),
// This service is also called outside the app route middleware. Bind the
// tenant here so forced RLS never turns a valid subscription into a silent
// null result on staging/production while preserving an inherited user id.
return await runWithRlsContext({ tenantId }, async () => {
const mySubscription = await cachified({
key: `tenantSubscription:${tenantId}`,
ttl: 1000 * 60 * 60, // 1 hour
getFreshValue: () => getTenantSubscription(tenantId),
});
if (mySubscription) {
await Promise.all(
mySubscription.products.map(async (item) => {
if (item.billingProviderSubscriptionId) {
let currentPeriod =
item.currentPeriodStart && item.currentPeriodEnd
? {
start: DateUtils.getDateStartOfDay(item.currentPeriodStart),
end: DateUtils.getDateEndOfDay(item.currentPeriodEnd),
}
: undefined;
const today = new Date();
let todayIsInCurrentPeriod = false;
if (currentPeriod) {
todayIsInCurrentPeriod = today >= item.currentPeriodStart! && today <= item.currentPeriodEnd!;
}
if (currentPeriod && todayIsInCurrentPeriod) {
item.currentPeriodStart = currentPeriod.start;
item.currentPeriodEnd = currentPeriod.end;
} else {
const updatedItem = await updateTenantSubscriptionProduct(
{ id: item.id, tenantId: mySubscription.tenantId },
{
currentPeriodStart: item.currentPeriodStart,
currentPeriodEnd: item.currentPeriodEnd,
}
: undefined;
const today = new Date();
let todayIsInCurrentPeriod = false;
if (currentPeriod) {
todayIsInCurrentPeriod = today >= item.currentPeriodStart! && today <= item.currentPeriodEnd!;
);
// Cross-replica purge: billing-period sync mutates the
// subscription, so peer web replicas must drop their L1 too —
// a bare clearCacheKey would only purge this process.
clearTenantSubscriptionCache(updatedItem.tenantSubscription.tenantId);
}
}
if (currentPeriod && todayIsInCurrentPeriod) {
item.currentPeriodStart = currentPeriod.start;
item.currentPeriodEnd = currentPeriod.end;
} else {
const updatedItem = await updateTenantSubscriptionProduct({ id: item.id, tenantId: mySubscription.tenantId }, {
currentPeriodStart: item.currentPeriodStart,
currentPeriodEnd: item.currentPeriodEnd,
});
// Cross-replica purge: billing-period sync mutates the
// subscription, so peer web replicas must drop their L1 too —
// a bare clearCacheKey would only purge this process.
clearTenantSubscriptionCache(updatedItem.tenantSubscription.tenantId);
}
}
})
);
mySubscription.products = mySubscription.products.filter((f) => !f.endsAt || new Date(f.endsAt) > new Date());
mySubscription.products = mySubscription.products.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
}
return mySubscription;
})
);
mySubscription.products = getActiveTenantSubscriptionProducts(mySubscription);
}
return mySubscription;
});
}
export async function getActiveTenantsSubscriptions() {
const subscriptions = await getTenantSubscriptions();
return await Promise.all(
subscriptions.map(async (mySubscription) => {
await Promise.all(
mySubscription.products.map(async () => undefined)
);
mySubscription.products = mySubscription.products.filter((f) => !f.endsAt || new Date(f.endsAt) > new Date());
await Promise.all(mySubscription.products.map(async () => undefined));
mySubscription.products = getActiveTenantSubscriptionProducts(mySubscription);
return mySubscription;
})
);
@@ -401,23 +418,28 @@ export async function persistCheckoutSessionStatus({
id,
fromUrl,
fromUserId,
fromTenantId,
tenantId,
}: {
request: Request;
id: string;
fromUrl: string;
fromUserId?: string | null;
fromTenantId?: string | null;
tenantId: string;
}) {
void request;
void id;
void fromUrl;
void fromUserId;
void fromTenantId;
void tenantId;
}
export async function getMrr(currency: string) {
const activeSubscriptions = await getActiveTenantsSubscriptions();
export async function getMrr(currency: string, tenantIds: string[]) {
const activeSubscriptions = (await getTenantSubscriptionsInRlsBatches(tenantIds))
.filter((subscription): subscription is TenantSubscriptionWithDetails => subscription !== null)
.map((subscription) => ({
...subscription,
products: subscription.products.filter((product) => !product.endsAt || new Date(product.endsAt) > new Date()),
}));
let summary: { total: number; count: number } = {
total: 0,
count: 0,
@@ -433,6 +455,15 @@ export async function getMrr(currency: string) {
return summary;
}
async function getTenantSubscriptionsInRlsBatches(tenantIds: string[]): Promise<(TenantSubscriptionWithDetails | null)[]> {
const subscriptions: (TenantSubscriptionWithDetails | null)[] = [];
for (let index = 0; index < tenantIds.length; index += ADMIN_MRR_TENANT_QUERY_BATCH_SIZE) {
const batch = tenantIds.slice(index, index + ADMIN_MRR_TENANT_QUERY_BATCH_SIZE);
subscriptions.push(...(await Promise.all(batch.map((tenantId) => runWithRlsContext({ tenantId }, () => getTenantSubscription(tenantId))))));
}
return subscriptions;
}
function getPriceInCurrency(subscriptionPrice: SubscriptionPrice | null, currency: string) {
if (!subscriptionPrice) {
return 0;
@@ -500,9 +531,11 @@ export async function clearAllSubscriptionsCache() {
clearCacheKey(`tenantSubscription:${tenantSub.tenantId}`);
});
// Wildcard fan-out — peer replicas flush their L1 entirely.
await getSubscriptionCache().invalidate().catch(() => {
/* logged inside helper */
});
await getSubscriptionCache()
.invalidate()
.catch(() => {
/* logged inside helper */
});
}
export async function cancelTenantSubscription(
@@ -513,27 +546,36 @@ export async function cancelTenantSubscription(
if (!tenantSubscriptionProduct) {
throw new Error("Subscription product not found");
}
if (tenantSubscriptionProduct.subscriptionProduct.kind !== "recurring_add_on") {
throw new ProductAcquisitionError("PRODUCT_KIND_INVALID");
}
if (!tenantSubscriptionProduct.acquisition) {
throw new ProductAcquisitionError("ACQUISITION_NOT_FOUND");
}
if (tenantSubscriptionProduct.acquisition.productKind !== "recurring_add_on") {
throw new ProductAcquisitionError("PRODUCT_KIND_INVALID");
}
if (!tenantSubscriptionProduct.acquisition.lagoSubscriptionId?.trim()) {
throw new ProductAcquisitionError("IDEMPOTENCY_CONFLICT");
}
const user = userId ? await getUser(userId) : null;
const tenant = await getTenant(tenantId);
if (user && tenant) {
await EventsService.create({
event: "subscription.cancelled",
tenantId: tenant.id,
userId: user.id,
data: {
user: { id: user.id, email: user.email },
tenant: { id: tenant.id, name: tenant.name },
subscription: {
product: {
id: tenantSubscriptionProduct.subscriptionProductId,
title: t ? t(tenantSubscriptionProduct.subscriptionProduct.title) : tenantSubscriptionProduct.subscriptionProduct.title,
},
},
} satisfies SubscriptionCancelledDto,
});
}
await cancelTenantSubscriptionProduct(tenantSubscriptionProduct.id, tenantId, {
cancelledAt: new Date(),
endsAt: new Date(),
if (!user || !tenant) throw new Error("Subscription cancellation actor or tenant not found");
const eventData = {
user: { id: user.id, email: user.email },
tenant: { id: tenant.id, name: tenant.name },
subscription: {
product: {
id: tenantSubscriptionProduct.subscriptionProductId,
title: t ? t(tenantSubscriptionProduct.subscriptionProduct.title) : tenantSubscriptionProduct.subscriptionProduct.title,
},
},
} satisfies SubscriptionCancelledDto;
await cancelRecurringProductAcquisition({
tenantId,
actorUserId: user.id,
tenantSubscriptionProductId: tenantSubscriptionProduct.id,
eventData,
});
clearTenantSubscriptionCache(tenantId);
}
@@ -0,0 +1,23 @@
// AK-P21 — deletion_pending read-only state. While a tenant deletion request
// sits in its 30-day grace window (or is executing), the workspace is
// read-only. Enforced by the same central write guard as the AK-P20/BILL-05
// billing frozen mode (assertTenantWritableForRequest); the privacy area
// stays writable so admins can withdraw the request or pull an export.
import { getDbClient } from "@hivegrid/db/client.server";
export type TenantDeletionReadOnlyState = {
readOnly: boolean;
status: "none" | "pending" | "executing";
};
export async function getTenantDeletionReadOnlyState(tenantId: string): Promise<TenantDeletionReadOnlyState> {
const request = await getDbClient().tenantDeletionRequest.findFirst({
where: { tenantId, status: { in: ["pending", "executing"] } },
select: { status: true },
});
if (!request) {
return { readOnly: false, status: "none" };
}
return { readOnly: true, status: request.status === "executing" ? "executing" : "pending" };
}
@@ -1,18 +1,45 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getAdminActiveUserKpiCounts, getAdminTenantKpiCounts } from "@hivegrid/db/kpi.server";
import { StatChange } from "~/application/dtos/stats/StatChange";
import { getAdminDashboardStats } from "./adminDashboardService";
import { getDbClient } from "@hivegrid/db/client.server";
import { listAuditEvents } from "@hivegrid/db/audit-events-query.server";
import { getAdminDashboardOverview, getAdminDashboardStats } from "./adminDashboardService";
import { getMrr } from "./.server/subscriptionService";
import { adminGetAllTenantsIdsAndNames } from "../db/tenants.db.server";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { getPlatformOutboxCounts } from "@hivegrid/db/admin-dashboard.server";
vi.mock("@hivegrid/db/kpi.server", () => ({
getAdminActiveUserKpiCounts: vi.fn(),
getAdminTenantKpiCounts: vi.fn(),
}));
vi.mock("@hivegrid/db/client.server", () => ({
getDbClient: vi.fn(),
}));
vi.mock("@hivegrid/db/audit-events-query.server", () => ({
listAuditEvents: vi.fn(),
}));
vi.mock("@hivegrid/db/admin-dashboard.server", () => ({
getPlatformOutboxCounts: vi.fn(),
}));
vi.mock("./.server/subscriptionService", () => ({
getMrr: vi.fn(),
}));
vi.mock("../db/tenants.db.server", () => ({
adminGetAllTenantsIdsAndNames: vi.fn(),
}));
const adminTenants = ["tenant_1", "tenant_2", "tenant_3", "tenant_4", "tenant_5"].map((id) => ({
id,
name: id,
slug: id,
}));
const translations: Record<string, string> = {
"admin.kpi.accounts.name": "Translated accounts",
"admin.kpi.accounts.hint": "Translated total accounts",
@@ -30,6 +57,7 @@ function t(key: string) {
describe("getAdminDashboardStats", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(adminGetAllTenantsIdsAndNames).mockResolvedValue(adminTenants);
vi.mocked(getMrr).mockResolvedValue({ total: 1234.5, count: 7 });
});
@@ -45,7 +73,10 @@ describe("getAdminDashboardStats", () => {
expect(getAdminActiveUserKpiCounts).toHaveBeenCalledTimes(1);
expect(getAdminActiveUserKpiCounts).toHaveBeenCalledWith({ gte });
expect(getMrr).toHaveBeenCalledTimes(1);
expect(getMrr).toHaveBeenCalledWith("eur");
expect(getMrr).toHaveBeenCalledWith(
"eur",
adminTenants.map((tenant) => tenant.id)
);
expect(stats).toEqual([
{
name: "Translated accounts",
@@ -107,3 +138,107 @@ describe("getAdminDashboardStats", () => {
});
});
});
describe("getAdminDashboardOverview", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(adminGetAllTenantsIdsAndNames).mockResolvedValue(adminTenants);
vi.stubEnv("BULLMQ_REDIS_URL", "redis://localhost:6379/0");
vi.stubEnv("MEILI_URL", "http://localhost:7700");
vi.stubEnv("MEILI_API_KEY", "devkey");
vi.stubEnv("LAGO_API_URL", "http://lago.local");
vi.stubEnv("LAGO_API_KEY", "lago-key");
vi.stubEnv("MOLLIE_API_KEY", "mollie-key");
vi.stubEnv("MOLLIE_PROFILE_ID", "profile-id");
vi.stubEnv("SENTRY_ENVIRONMENT", "staging");
vi.stubEnv("SENTRY_RELEASE", "abc123");
vi.stubEnv("SENTRY_DSN", "https://example.invalid/1");
vi.mocked(listAuditEvents).mockResolvedValue({
rows: [
{
id: "audit-1",
createdAt: new Date("2026-07-01T10:00:00.000Z"),
summaryText: "Tenant aktualisiert",
action: "tenant.update",
actorEmail: "ops@example.test",
targetType: "Tenant",
sourceModule: "admin",
actorType: "user",
outcome: "success",
},
],
total: 1,
take: 5,
skip: 0,
} as never);
vi.mocked(getPlatformOutboxCounts).mockResolvedValue({ pendingOrProcessing: 5, failed: 6 });
});
it("builds billing, system, deploy, and audit overview signals", async () => {
vi.mocked(getDbClient).mockReturnValue(createDashboardClient({
failedWebhookCount: 4,
}) as never);
const overview = await runWithRlsContext({ userId: "operator_1" }, () => getAdminDashboardOverview());
expect(overview.billing).toMatchObject({
openIssueCount: 6,
pastDueCount: 2,
frozenCount: 1,
missingProviderCount: 3,
});
expect(overview.billing.signals).toEqual(
expect.arrayContaining([
expect.objectContaining({ id: "billing-issues", value: "6", tone: "warning", href: "/system/billing" }),
expect.objectContaining({ id: "billing-past-due", value: "2", tone: "danger", href: "/system/billing" }),
])
);
expect(overview.system.signals).toEqual(
expect.arrayContaining([
expect.objectContaining({ id: "redis", value: "OK", tone: "success" }),
expect.objectContaining({ id: "webhooks", value: "4", tone: "warning", href: "/system/webhooks" }),
expect.objectContaining({ id: "outbox", value: "5/6", tone: "danger", href: "/events" }),
])
);
expect(overview.deploy).toMatchObject({ environment: "staging", release: "abc123" });
expect(overview.recentEvents).toEqual([
expect.objectContaining({
id: "audit-1",
label: "Tenant aktualisiert",
detail: "ops@example.test · Tenant",
timestamp: "2026-07-01T10:00:00.000Z",
href: "/audit",
}),
]);
expect(listAuditEvents).toHaveBeenCalledWith({ take: 5, skip: 0 });
expect(getPlatformOutboxCounts).toHaveBeenCalledWith(undefined, {
allowMarkedLocalDatabaseFallback: false,
});
});
});
function createDashboardClient({
failedWebhookCount,
}: {
failedWebhookCount: number;
}) {
const subscriptions = new Map([
["tenant_1", { status: "past_due", pastDueSince: null, frozenAt: null, planCode: "pro", lagoCustomerId: null, mollieCustomerId: "m_1" }],
["tenant_2", { status: "trial", pastDueSince: new Date(), frozenAt: null, planCode: null, lagoCustomerId: "l_2", mollieCustomerId: "m_2" }],
["tenant_3", { status: "frozen", pastDueSince: null, frozenAt: new Date(), planCode: "pro", lagoCustomerId: "l_3", mollieCustomerId: null }],
["tenant_4", { status: "active", pastDueSince: null, frozenAt: null, planCode: "pro", lagoCustomerId: null, mollieCustomerId: "m_4" }],
["tenant_5", { status: "trial", pastDueSince: null, frozenAt: null, planCode: null, lagoCustomerId: "l_5", mollieCustomerId: "m_5" }],
]);
const tenantSubscriptionFindUnique = vi.fn(async ({ where }: { where: { tenantId: string } }) => {
expect(getRlsExecutionContext()).toMatchObject({ userId: "operator_1", tenantId: where.tenantId });
return subscriptions.get(where.tenantId) ?? null;
});
return {
tenantSubscription: {
findUnique: tenantSubscriptionFindUnique,
},
eventWebhookAttempt: {
count: vi.fn().mockResolvedValue(failedWebhookCount),
},
};
}
@@ -1,4 +1,8 @@
import { getAdminActiveUserKpiCounts, getAdminTenantKpiCounts } from "@hivegrid/db/kpi.server";
import { getDbClient } from "@hivegrid/db/client.server";
import { listAuditEvents } from "@hivegrid/db/audit-events-query.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { getPlatformOutboxCounts } from "@hivegrid/db/admin-dashboard.server";
import { Stat } from "~/application/dtos/stats/Stat";
import currencies from "~/application/pricing/currencies";
import { getStatChangeType } from "../app/DashboardUtils";
@@ -6,12 +10,54 @@ import NumberUtils from "../shared/NumberUtils";
import { getMrr } from "./.server/subscriptionService";
import { promiseHash } from "../promises/promiseHash";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import { adminGetAllTenantsIdsAndNames } from "../db/tenants.db.server";
const ADMIN_TENANT_QUERY_BATCH_SIZE = 10;
type AdminDashboardStatsOptions = {
t: (key: string) => string;
gte?: Date;
};
export type AdminDashboardSignalTone = "success" | "warning" | "danger" | "neutral";
export type AdminDashboardSignal = {
id: string;
labelKey: string;
detailKey: string;
value: string;
tone: AdminDashboardSignalTone;
href?: string;
};
export type AdminDashboardActivity = {
id: string;
label: string;
detail: string;
timestamp: string;
tone: AdminDashboardSignalTone;
href: string;
};
export type AdminDashboardOverview = {
billing: {
openIssueCount: number;
pastDueCount: number;
frozenCount: number;
missingProviderCount: number;
signals: AdminDashboardSignal[];
};
system: {
signals: AdminDashboardSignal[];
};
deploy: {
environment: string;
release: string;
signals: AdminDashboardSignal[];
};
recentEvents: AdminDashboardActivity[];
};
export async function getAdminDashboardStats({ t, gte }: AdminDashboardStatsOptions): Promise<Stat[]> {
const { tenantStat, mrrStat, activeUsersStat } = await promiseHash({
tenantStat: getTenantStat({ t, gte }),
@@ -21,6 +67,139 @@ export async function getAdminDashboardStats({ t, gte }: AdminDashboardStatsOpti
return [tenantStat, mrrStat, activeUsersStat];
}
export async function getAdminDashboardOverview(): Promise<AdminDashboardOverview> {
const db = getDbClient();
const tenants = await adminGetAllTenantsIdsAndNames();
const subscriptionRows = await mapTenantIdsInBatches(
tenants.map((tenant) => tenant.id),
(tenantId) =>
db.tenantSubscription.findUnique({
where: { tenantId },
select: {
status: true,
pastDueSince: true,
frozenAt: true,
planCode: true,
lagoCustomerId: true,
mollieCustomerId: true,
},
})
);
const subscriptions = subscriptionRows.filter((subscription) => subscription !== null);
const pastDueCount = subscriptions.filter((subscription) => subscription.status === "past_due" || subscription.pastDueSince !== null).length;
const frozenCount = subscriptions.filter((subscription) => subscription.status === "frozen" || subscription.frozenAt !== null).length;
const missingProviderCount = subscriptions.filter(
(subscription) =>
(subscription.planCode !== null || ["active", "past_due", "frozen"].includes(subscription.status)) &&
(subscription.lagoCustomerId === null || subscription.mollieCustomerId === null)
).length;
const { failedWebhookCount, outboxCounts, recentAudit } = await promiseHash({
failedWebhookCount: db.eventWebhookAttempt.count({ where: { success: false } }),
outboxCounts: getPlatformOutboxCounts(undefined, {
allowMarkedLocalDatabaseFallback: process.env.LOCAL_DEV_CREDENTIALS === "1",
}),
recentAudit: listAuditEvents({ take: 5, skip: 0 }),
});
const pendingOutboxCount = outboxCounts.pendingOrProcessing;
const failedOutboxCount = outboxCounts.failed;
const billingIssueCount = pastDueCount + frozenCount + missingProviderCount;
return {
billing: {
openIssueCount: billingIssueCount,
pastDueCount,
frozenCount,
missingProviderCount,
signals: [
signal({
id: "billing-issues",
labelKey: "admin.dashboard.billing.signals.issues.label",
detailKey: billingIssueCount > 0 ? "admin.dashboard.billing.signals.issues.detailOpen" : "admin.dashboard.billing.signals.issues.detailOk",
value: billingIssueCount.toString(),
tone: billingIssueCount > 0 ? "warning" : "success",
href: adminPath("system/billing", { mode: "host-aware" }),
}),
signal({
id: "billing-past-due",
labelKey: "admin.dashboard.billing.signals.pastDue.label",
detailKey: pastDueCount > 0 ? "admin.dashboard.billing.signals.pastDue.detailOpen" : "admin.dashboard.billing.signals.pastDue.detailOk",
value: pastDueCount.toString(),
tone: pastDueCount > 0 ? "danger" : "success",
href: adminPath("system/billing", { mode: "host-aware" }),
}),
signal({
id: "billing-providers",
labelKey: "admin.dashboard.billing.signals.providers.label",
detailKey: missingProviderCount > 0 ? "admin.dashboard.billing.signals.providers.detailOpen" : "admin.dashboard.billing.signals.providers.detailOk",
value: missingProviderCount.toString(),
tone: missingProviderCount > 0 ? "warning" : "success",
href: adminPath("system/billing", { mode: "host-aware" }),
}),
],
},
system: {
signals: [
envSignal("redis", "admin.dashboard.system.signals.redis", Boolean(process.env.BULLMQ_REDIS_URL || process.env.REDIS_URL)),
envSignal("meili", "admin.dashboard.system.signals.meili", Boolean(process.env.MEILI_URL && process.env.MEILI_API_KEY)),
envSignal("lago", "admin.dashboard.system.signals.lago", Boolean(process.env.LAGO_API_URL && process.env.LAGO_API_KEY)),
envSignal("mollie", "admin.dashboard.system.signals.mollie", Boolean(process.env.MOLLIE_API_KEY && process.env.MOLLIE_PROFILE_ID)),
signal({
id: "webhooks",
labelKey: "admin.dashboard.system.signals.webhooks.label",
detailKey: failedWebhookCount > 0 ? "admin.dashboard.system.signals.webhooks.detailOpen" : "admin.dashboard.system.signals.webhooks.detailOk",
value: failedWebhookCount.toString(),
tone: failedWebhookCount > 0 ? "warning" : "success",
href: adminPath("system/webhooks", { mode: "host-aware" }),
}),
signal({
id: "outbox",
labelKey: "admin.dashboard.system.signals.outbox.label",
detailKey: failedOutboxCount > 0 ? "admin.dashboard.system.signals.outbox.detailFailed" : "admin.dashboard.system.signals.outbox.detailOk",
value: `${pendingOutboxCount}/${failedOutboxCount}`,
tone: failedOutboxCount > 0 ? "danger" : pendingOutboxCount > 0 ? "neutral" : "success",
href: adminPath("events", { mode: "host-aware" }),
}),
],
},
deploy: {
environment: process.env.SENTRY_ENVIRONMENT ?? process.env.NODE_ENV ?? "development",
release: process.env.SENTRY_RELEASE ?? process.env.GIT_SHA ?? process.env.COMMIT_SHA ?? "local",
signals: [
envSignal("sentry", "admin.dashboard.deploy.signals.sentry", Boolean(process.env.SENTRY_DSN || process.env.VITE_SENTRY_DSN)),
signal({
id: "release",
labelKey: "admin.dashboard.deploy.signals.release.label",
detailKey: "admin.dashboard.deploy.signals.release.detail",
value: process.env.SENTRY_RELEASE ?? process.env.GIT_SHA?.slice(0, 8) ?? "local",
tone: "neutral",
}),
],
},
recentEvents: recentAudit.rows.map((event) => ({
id: event.id,
label: event.summaryText ?? event.action,
detail: [event.actorEmail, event.targetType].filter(Boolean).join(" · ") || event.sourceModule || event.actorType,
timestamp: event.createdAt.toISOString(),
tone: event.outcome === "success" ? "success" : "warning",
href: adminPath("audit", { mode: "host-aware" }),
})),
};
}
function signal(input: AdminDashboardSignal): AdminDashboardSignal {
return input;
}
function envSignal(id: string, baseKey: string, configured: boolean): AdminDashboardSignal {
return signal({
id,
labelKey: `${baseKey}.label`,
detailKey: configured ? `${baseKey}.detailOk` : `${baseKey}.detailMissing`,
value: configured ? "OK" : "!",
tone: configured ? "success" : "warning",
});
}
async function getTenantStat({ t, gte }: AdminDashboardStatsOptions) {
const { added, total } = await getAdminTenantKpiCounts({ gte });
const tenantStat: Stat = {
@@ -38,7 +217,11 @@ async function getTenantStat({ t, gte }: AdminDashboardStatsOptions) {
async function getMMRStat(t: AdminDashboardStatsOptions["t"]) {
const defaultCurrency = currencies.find((f) => f.default);
const currency = defaultCurrency ?? { value: "usd", symbol: "$" };
const mrr = await getMrr(currency.value);
const tenants = await adminGetAllTenantsIdsAndNames();
const mrr = await getMrr(
currency.value,
tenants.map((tenant) => tenant.id)
);
const tenantStat: Stat = {
name: t("admin.kpi.mrr.name"),
hint: t("admin.kpi.mrr.hint"),
@@ -48,6 +231,15 @@ async function getMMRStat(t: AdminDashboardStatsOptions["t"]) {
return tenantStat;
}
async function mapTenantIdsInBatches<T>(tenantIds: string[], operation: (tenantId: string) => Promise<T>): Promise<T[]> {
const results: T[] = [];
for (let index = 0; index < tenantIds.length; index += ADMIN_TENANT_QUERY_BATCH_SIZE) {
const batch = tenantIds.slice(index, index + ADMIN_TENANT_QUERY_BATCH_SIZE);
results.push(...(await Promise.all(batch.map((tenantId) => runWithRlsContext({ tenantId }, () => operation(tenantId))))));
}
return results;
}
async function getActiveUsersStat({ t, gte }: AdminDashboardStatsOptions) {
const { added, total } = await getAdminActiveUserKpiCounts({ gte });
const activeUsersStat: Stat = {
@@ -64,20 +64,6 @@ describe("adminSettingsValidation.server", () => {
expect(JSON.stringify(ignored)).not.toContain("G-ABC12345");
});
it("normalizes cookie settings and rejects malformed actions or booleans", () => {
const valid = parseAdminSettingsForm("cookies", createForm({ action: "update", enabled: "true" }));
expect(valid).toEqual({ ok: true, section: "cookies", data: { cookiesEnabled: true } });
const invalid = parseAdminSettingsForm("cookies", createForm({ action: "delete", enabled: "true" }));
expect(invalid).toEqual({ ok: false, status: 400, errors: { action: ["Invalid action."] } });
const tampered = parseAdminSettingsForm("cookies", createForm({ action: "update", enabled: "definitely" }));
expect(tampered).toEqual({ ok: false, status: 400, errors: { enabled: ["Boolean value is invalid."] } });
});
it("redacts scripts, tokens and query strings from audit details", () => {
const audit = redactSettingsAuditDetails("general", {
headScripts: sensitiveHeadScript,
@@ -1,6 +1,6 @@
import { Prisma } from "@hivegrid/db/prisma-browser";
export type AdminSettingsSection = "general" | "authentication" | "analytics" | "cookies";
export type AdminSettingsSection = "general" | "authentication" | "analytics";
export type AdminSettingsValidationErrors = Record<string, string[]>;
export type AdminSettingsValidationResult =
@@ -29,8 +29,6 @@ export function parseAdminSettingsForm(section: AdminSettingsSection, form: Form
return parseAuthenticationSettings(form, errors);
case "analytics":
return parseAnalyticsSettings(form, errors);
case "cookies":
return parseCookiesSettings(form, errors);
default:
addError(errors, "section", "Invalid settings section.");
return invalid(errors);
@@ -106,17 +104,6 @@ function parseAnalyticsSettings(form: FormData, errors: AdminSettingsValidationE
});
}
function parseCookiesSettings(form: FormData, errors: AdminSettingsValidationErrors): AdminSettingsValidationResult {
const enabled = getOptionalBoolean(form, "enabled", errors);
if (Object.keys(errors).length > 0) {
return invalid(errors);
}
return valid("cookies", {
cookiesEnabled: enabled,
});
}
function requireString(form: FormData, field: string, errors: AdminSettingsValidationErrors, maxLength = MAX_SHORT_TEXT_LENGTH) {
const value = optionalString(form, field, errors, maxLength);
if (!value) {
@@ -146,21 +133,6 @@ function getBoolean(form: FormData, field: string) {
return value === "on" || value === "true" || value === "1";
}
function getOptionalBoolean(form: FormData, field: string, errors: AdminSettingsValidationErrors) {
const value = form.get(field);
if (value === null) {
return false;
}
if (value === "on" || value === "true" || value === "1") {
return true;
}
if (value === "off" || value === "false" || value === "0") {
return false;
}
addError(errors, field, "Boolean value is invalid.");
return false;
}
function addError(errors: AdminSettingsValidationErrors, field: string, message: string) {
errors[field] = [...(errors[field] ?? []), message];
}
@@ -3,27 +3,29 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@hivegrid/db/accounts.server", () => ({
createUniqueLegacyTenantIpAddress: vi.fn(),
findLegacyTenantByIdOrSlug: vi.fn(),
getLegacyTenantMembershipsForUser: vi.fn(),
}));
vi.mock("@hivegrid/db/api-keys.server", () => ({
createLegacyApiKeyLog: vi.fn(),
findLegacyApiKeyByKey: vi.fn(),
findLegacyApiKeyByKeyWithRlsBootstrap: vi.fn(),
setLegacyApiKeyLogStatus: vi.fn(),
}));
vi.mock("@hivegrid/db/users.server", () => ({ findLegacyUserWithoutPasswordById: vi.fn() }));
vi.mock("./.server/subscriptionService", () => ({
getActiveTenantSubscriptions: vi.fn(),
getPlanFeatureUsage: vi.fn(),
}));
vi.mock("../server/IpUtils", () => ({ getClientIPAddress: vi.fn(() => "127.0.0.1") }));
vi.mock("jsonwebtoken", () => ({ default: { verify: vi.fn() } }));
vi.mock("../server/IpUtils", () => ({ getTrustedClientIpOrNull: vi.fn(() => "127.0.0.1") }));
vi.mock("~/modules/notifications/services/.server/NotificationService", () => ({
default: { sendToRoles: vi.fn() },
}));
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
vi.mock("./rateLimitService", () => ({ rateLimitByKey: vi.fn() }));
vi.mock("../cache.server", () => ({ cachified: vi.fn() }));
vi.mock("../app/CrossHostUrls", () => ({ absoluteAppPath: vi.fn(() => "https://app.example.com/acme/settings/api/keys") }));
vi.mock("../api/api-key-auth-cache.server", () => ({
loadCachedApiKeySnapshot: vi.fn(async (_key: string, getFreshValue: () => Promise<unknown>) => getFreshValue()),
}));
vi.mock("../db/tenant-cache.server", () => ({
loadTenantSecuritySnapshot: vi.fn(async (_key: string, getFreshValue: () => Promise<unknown>) => getFreshValue()),
}));
vi.mock("../app/CrossHostUrls", () => ({ absoluteAppPath: vi.fn(() => "https://app.example.com/acme/api/keys") }));
vi.mock("@hivegrid/config", () => ({
loadApiConfig: vi.fn(() => ({
ok: true,
@@ -38,9 +40,9 @@ vi.mock("@hivegrid/config", () => ({
}));
import { findLegacyTenantByIdOrSlug } from "@hivegrid/db/accounts.server";
import { createLegacyApiKeyLog, findLegacyApiKeyByKey, setLegacyApiKeyLogStatus } from "@hivegrid/db/api-keys.server";
import { createLegacyApiKeyLog, findLegacyApiKeyByKeyWithRlsBootstrap, setLegacyApiKeyLogStatus } from "@hivegrid/db/api-keys.server";
import { loadApiConfig } from "@hivegrid/config";
import { cachified } from "../cache.server";
import { loadCachedApiKeySnapshot } from "../api/api-key-auth-cache.server";
import { getTranslations } from "~/locale/i18next.server";
import { rateLimitByKey } from "./rateLimitService";
import { getApiKeyLookupCacheKey, serializeApiLogSearchParams } from "../api/apiKeySecurity.server";
@@ -50,7 +52,6 @@ describe("service API access token helpers", () => {
beforeEach(() => {
vi.mocked(findLegacyTenantByIdOrSlug).mockResolvedValue({ id: "tenant_1" } as never);
vi.mocked(createLegacyApiKeyLog).mockResolvedValue({ id: "log_1" } as never);
vi.mocked(cachified).mockImplementation((async (options: { getFreshValue: () => unknown }) => options.getFreshValue()) as never);
vi.mocked(getTranslations).mockResolvedValue({ t: (key: string) => key } as never);
});
@@ -70,12 +71,31 @@ describe("service API access token helpers", () => {
it("rejects missing or mismatched service tokens", () => {
expect(hasValidServiceAccessToken(new Request("https://example.com/v1/accounts"))).toBe(false);
expect(hasValidServiceAccessToken(new Request("https://example.com/v1/accounts", { headers: { Authorization: "Bearer wrong" } }))).toBe(false);
expect(hasValidServiceAccessToken(new Request("https://example.com/v1/accounts", { headers: { Authorization: "Bearer service-secret-extra" } }))).toBe(false);
expect(hasValidServiceAccessToken(new Request("https://example.com/v1/accounts", { headers: { Authorization: "Bearer service-secret-extra" } }))).toBe(
false
);
});
it("rejects legacy web JWT bearer credentials without attempting JWT verification", async () => {
const request = new Request("https://example.com/v1/accounts", {
headers: { Authorization: "Bearer eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiJ1c2VyXzEifQ.signature" },
});
await expect(validateApiKey(request, {})).rejects.toThrow("Bearer authentication is only supported for service access tokens");
});
it("accepts only the exact service token through Bearer auth", async () => {
const request = new Request("https://example.com/internal/api/workflows/run/workflow_1?tenantId=tenant_1", {
headers: { Authorization: "Bearer service-secret" },
});
await expect(validateApiKey(request, {})).resolves.toEqual({ tenant: { id: "tenant_1" } });
expect(findLegacyTenantByIdOrSlug).toHaveBeenCalledWith("tenant_1");
});
it("redacts sensitive API log query params before persistence", () => {
const request = new Request(
"https://example.com/v1/entities/contact/rows?entity=contact&id=row_1&page=2&token=raw-token&email=person@example.test&next=/dashboard&apiKey=secret_live_value"
"https://example.com/v1/contacts?entity=contact&id=row_1&page=2&token=raw-token&email=person@example.test&next=/dashboard&apiKey=secret_live_value"
);
expect(serializeApiLogSearchParams(request)).toBe(
@@ -90,20 +110,26 @@ describe("service API access token helpers", () => {
});
it("uses hashed cache keys for stored API-key lookups", async () => {
vi.mocked(findLegacyApiKeyByKey).mockResolvedValue(null);
vi.mocked(findLegacyApiKeyByKeyWithRlsBootstrap).mockResolvedValue(null);
await expect(validateApiKey(new Request("https://example.com/v1/widgets", { headers: { "X-Api-Key": "stored-key" } }), {})).rejects.toThrow(
"Invalid API Key"
);
expect(cachified).toHaveBeenCalledWith(expect.objectContaining({ key: getApiKeyLookupCacheKey("stored-key") }));
expect(cachified).not.toHaveBeenCalledWith(expect.objectContaining({ key: "apiKey:stored-key" }));
expect(loadCachedApiKeySnapshot).toHaveBeenCalledWith(getApiKeyLookupCacheKey("stored-key"), expect.any(Function));
expect(loadCachedApiKeySnapshot).not.toHaveBeenCalledWith("apiKey:stored-key", expect.any(Function));
});
it("resolves service-token tenant scope from query or headers", async () => {
const queryRequest = new Request("https://example.com/internal/api/workflows/run/workflow_1?tenantId=tenant_1", { headers: { "X-Api-Key": "service-secret" } });
const tenantHeaderRequest = new Request("https://example.com/internal/api/workflows/run/workflow_1", { headers: { "X-Api-Key": "service-secret", "X-Tenant-Id": "tenant_1" } });
const accountHeaderRequest = new Request("https://example.com/internal/api/workflows/run/workflow_1", { headers: { "X-Api-Key": "service-secret", "X-Account-Id": "tenant_1" } });
const queryRequest = new Request("https://example.com/internal/api/workflows/run/workflow_1?tenantId=tenant_1", {
headers: { "X-Api-Key": "service-secret" },
});
const tenantHeaderRequest = new Request("https://example.com/internal/api/workflows/run/workflow_1", {
headers: { "X-Api-Key": "service-secret", "X-Tenant-Id": "tenant_1" },
});
const accountHeaderRequest = new Request("https://example.com/internal/api/workflows/run/workflow_1", {
headers: { "X-Api-Key": "service-secret", "X-Account-Id": "tenant_1" },
});
await expect(validateApiKey(queryRequest, {})).resolves.toEqual({ tenant: { id: "tenant_1" } });
await expect(validateApiKey(tenantHeaderRequest, {})).resolves.toEqual({ tenant: { id: "tenant_1" } });
@@ -129,7 +155,7 @@ describe("service API access token helpers", () => {
await expect(validateApiKey(queryRequest, {})).rejects.toThrow("You cannot use tenantId, X-Tenant-Id, or X-Account-Id with a stored API key");
await expect(validateApiKey(tenantHeaderRequest, {})).rejects.toThrow("You cannot use tenantId, X-Tenant-Id, or X-Account-Id with a stored API key");
await expect(validateApiKey(accountHeaderRequest, {})).rejects.toThrow("You cannot use tenantId, X-Tenant-Id, or X-Account-Id with a stored API key");
expect(findLegacyApiKeyByKey).not.toHaveBeenCalled();
expect(findLegacyApiKeyByKeyWithRlsBootstrap).not.toHaveBeenCalled();
});
it("threads API-key hash secret and plaintext-fallback cutover into stored-key lookup", async () => {
@@ -142,18 +168,18 @@ describe("service API access token helpers", () => {
},
diagnostics: [],
} as never);
vi.mocked(findLegacyApiKeyByKey).mockResolvedValue(null);
vi.mocked(findLegacyApiKeyByKeyWithRlsBootstrap).mockResolvedValue(null);
const request = new Request("https://example.com/v1/widgets", { headers: { "X-Api-Key": "stored-key" } });
await expect(validateApiKey(request, {})).rejects.toThrow("Invalid API Key");
expect(findLegacyApiKeyByKey).toHaveBeenCalledWith("stored-key", undefined, "cutover-hash-secret", {
expect(findLegacyApiKeyByKeyWithRlsBootstrap).toHaveBeenCalledWith("stored-key", undefined, "cutover-hash-secret", {
allowPlaintextFallback: false,
});
});
it("updates stored API-key error logs with tenant scope", async () => {
vi.mocked(findLegacyApiKeyByKey).mockResolvedValue({
vi.mocked(findLegacyApiKeyByKeyWithRlsBootstrap).mockResolvedValue({
id: "api_key_1",
tenantId: "tenant_1",
active: true,
@@ -1,48 +1,36 @@
import { timingSafeEqual } from "node:crypto";
import {
createUniqueLegacyTenantIpAddress,
findLegacyTenantByIdOrSlug,
getLegacyTenantMembershipsForUser,
} from "@hivegrid/db/accounts.server";
import { createUniqueLegacyTenantIpAddress, findLegacyTenantByIdOrSlug } from "@hivegrid/db/accounts.server";
import {
createLegacyApiKeyLog,
findLegacyApiKeyByKey,
findLegacyApiKeyByKeyWithRlsBootstrap,
setLegacyApiKeyLogStatus as setApiKeyLogStatus,
type LegacyApiKeySimple,
} from "@hivegrid/db/api-keys.server";
import type { ApiKeyLog } from "@hivegrid/db/prisma-browser";
import { findLegacyUserWithoutPasswordById } from "@hivegrid/db/users.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { Params } from "react-router";
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
import { getActiveTenantSubscriptions, getPlanFeatureUsage } from "./.server/subscriptionService";
import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
import { getClientIPAddress } from "../server/IpUtils";
import jwt from "jsonwebtoken";
import { getTrustedClientIpOrNull } from "../server/IpUtils";
import NotificationService from "~/modules/notifications/services/.server/NotificationService";
import { getTranslations } from "~/locale/i18next.server";
import { rateLimitByKey } from "./rateLimitService";
import { cachified } from "../cache.server";
import { loadApiConfig, loadRequiredWebConfig } from "@hivegrid/config";
import { absoluteAppPath } from "../app/CrossHostUrls";
import { getApiKeyLookupCacheKey, serializeApiLogSearchParams } from "../api/apiKeySecurity.server";
import { loadCachedApiKeySnapshot } from "../api/api-key-auth-cache.server";
import { loadTenantSecuritySnapshot } from "../db/tenant-cache.server";
type ApiKeyLogScope = { id: string; tenantId: string };
async function setApiError(request: Request, params: Params, error: string, status: number, apiKeyLogScope?: ApiKeyLogScope) {
async function setApiError(_request: Request, _params: Params, error: string, status: number, apiKeyLogScope?: ApiKeyLogScope) {
if (apiKeyLogScope) {
await setApiKeyLogStatus(apiKeyLogScope, {
error,
status,
startTime: null,
});
} else {
await createApiKeyLog(request, {
apiKeyId: null,
tenantId: null,
endpoint: new URL(request.url).pathname,
error,
status,
});
}
throw Object.assign(new Error(error), {
status,
@@ -50,14 +38,6 @@ async function setApiError(request: Request, params: Params, error: string, stat
});
}
function getRequiredJwtSecret() {
const jwtSecret = loadRequiredWebConfig().jwtSecret;
if (!jwtSecret) {
throw new Error("JWT_SECRET is required for API authorization.");
}
return jwtSecret;
}
async function createApiKeyLog(
request: Request,
data: {
@@ -68,7 +48,7 @@ async function createApiKeyLog(
status?: number;
alias?: string;
tenantName?: string;
},
}
) {
return createLegacyApiKeyLog({
tenantId: data.tenantId,
@@ -78,22 +58,18 @@ async function createApiKeyLog(
status: data.status,
alias: data.alias,
tenantName: data.tenantName,
ip: getClientIPAddress(request) ?? "",
ip: getTrustedClientIpOrNull(request) ?? "",
method: request.method,
params: serializeApiLogSearchParams(request),
});
}
async function getApiKeyFromHeader(key: string) {
return cachified({
key: getApiKeyLookupCacheKey(key),
ttl: 1000 * 60 * 60,
getFreshValue: () => {
const { config } = loadApiConfig();
return findLegacyApiKeyByKey(key, undefined, config.jwtSecret, {
allowPlaintextFallback: config.apiKeys.allowLegacyPlaintextFallback,
});
},
return loadCachedApiKeySnapshot(getApiKeyLookupCacheKey(key), () => {
const { config } = loadApiConfig();
return findLegacyApiKeyByKeyWithRlsBootstrap(key, undefined, config.jwtSecret, {
allowPlaintextFallback: config.apiKeys.allowLegacyPlaintextFallback,
});
});
}
@@ -130,11 +106,7 @@ function getServiceTenantScopeFromRequest(request: Request) {
function getTenantScopeOverridesFromRequest(request: Request) {
const searchParams = new URL(request.url).searchParams;
return [
searchParams.get("tenantId"),
request.headers.get("X-Tenant-Id"),
request.headers.get("X-Account-Id"),
]
return [searchParams.get("tenantId"), request.headers.get("X-Tenant-Id"), request.headers.get("X-Account-Id")]
.map((value) => value?.trim() ?? "")
.filter((value) => value.length > 0);
}
@@ -155,51 +127,30 @@ export type ApiAccessValidation = {
};
export async function validateApiKey(request: Request, params: Params): Promise<ApiAccessValidation> {
const authorization = request.headers.get("Authorization");
if (authorization && authorization.startsWith("Bearer ")) {
const token = authorization.split(" ")[1];
let userId = "";
try {
const decoded: any = jwt.verify(token, getRequiredJwtSecret());
userId = decoded.userId;
} catch (e: any) {
throw Error("Invalid authorization token: " + e.message);
}
const user = await findLegacyUserWithoutPasswordById(userId);
if (!user) {
throw Error("Unauthorized");
}
let tenantId = request.headers.get("X-Account-Id") ?? request.headers.get("X-Tenant-Id");
if (!tenantId) {
if (!user.admin) {
throw Error("No X-Account-Id provided");
} else {
tenantId = null;
}
}
if (tenantId !== null) {
const userTenants = await getLegacyTenantMembershipsForUser(user.id);
if (!userTenants.find((t) => t.id === tenantId || t.slug === tenantId)) {
throw Error("Unauthorized");
}
}
const tenant = await findLegacyTenantByIdOrSlug(tenantId ?? "");
return {
userId,
tenant: tenantId === null ? null : tenant,
};
const authorization = request.headers.get("Authorization")?.trim() ?? "";
const hasBearerCredential = /^Bearer\s+/i.test(authorization);
if (hasBearerCredential && !hasValidServiceAccessToken(request)) {
// User/API JWTs belong to the dedicated API runtime. The web runtime only
// accepts its exact service credential as Bearer auth; stored tenant keys
// must use X-Api-Key so an HS256 token can never be mistaken for a session.
throw Error("Bearer authentication is only supported for service access tokens");
}
const apiKeyFromHeaders = request.headers.get("X-Api-Key") ?? "";
if (!apiKeyFromHeaders) {
if (!apiKeyFromHeaders && !hasBearerCredential) {
throw Error("No X-API-Key header or Authorization token provided");
}
const apiAccessToken = loadRequiredWebConfig().apiAccessToken;
if (apiAccessToken && apiKeyFromHeaders === apiAccessToken) {
if (hasValidServiceAccessToken(request)) {
const tenantId = getServiceTenantScopeFromRequest(request);
if (!tenantId) {
return { tenant: null };
}
const tenant = await findLegacyTenantByIdOrSlug(tenantId);
const tenant = await runWithRlsContext({ tenantId }, () =>
loadTenantSecuritySnapshot(tenantId, async () => {
const current = await findLegacyTenantByIdOrSlug(tenantId);
return current ? { id: current.id, name: current.name, slug: current.slug, deactivatedReason: current.deactivatedReason } : null;
})
);
if (!tenant) {
throw Error("Account not found: " + tenantId);
}
@@ -218,63 +169,73 @@ export async function validateTenantApiKey(request: Request, params: Params): Pr
if (!apiKey) {
throw await setApiError(request, params, "Invalid API Key", 401);
}
const tenantSubscription = await getActiveTenantSubscriptions(apiKey.tenantId);
const rateLimitResult = await rateLimitByKey({
apiKey: apiKey.id,
tenantId: apiKey.tenantId,
tenantSubscription,
});
const apiKeyLog = await createApiKeyLog(request, {
apiKeyId: apiKey.id,
tenantId: apiKey.tenantId,
endpoint: new URL(request.url).pathname,
});
if (rateLimitResult.error) {
throw await setApiError(request, params, "Rate limit exceeded: " + rateLimitResult.error, 429, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
}
createUniqueLegacyTenantIpAddress({
ip: getClientIPAddress(request) ?? "Unknown",
fromUrl: new URL(request.url).pathname,
tenantId: apiKey.tenantId,
apiKeyId: apiKey.id,
});
if (apiKey.tenant.deactivatedReason) {
throw await setApiError(request, params, "Account deactivated: " + apiKey.tenant.deactivatedReason, 403, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
}
if (!apiKey.active) {
throw await setApiError(request, params, "Inactive API Key", 400, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
}
if (apiKey.expires && apiKey?.expires < new Date()) {
throw await setApiError(request, params, "Expired API Key", 400, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
}
const usage = await getPlanFeatureUsage(apiKey.tenantId, DefaultFeatures.API, tenantSubscription);
if (usage && !usage.enabled) {
await NotificationService.sendToRoles({
channel: "admin-users",
tenantId: null,
notification: {
message: `${apiKey.tenant.name} (${apiKey.tenant.slug}) API error. ${t(usage.message)}`,
action: {
url: absoluteAppPath(loadRequiredWebConfig().routing, apiKey.tenant.slug, "settings/api/keys"),
},
},
return runWithRlsContext({ tenantId: apiKey.tenantId, userId: apiKey.createdByUserId }, async () => {
const tenant = await loadTenantSecuritySnapshot(apiKey.tenantId, async () => {
const current = await findLegacyTenantByIdOrSlug(apiKey.tenantId);
return current ? { id: current.id, name: current.name, slug: current.slug, deactivatedReason: current.deactivatedReason } : null;
});
throw await setApiError(request, params, t(usage.message), 402, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
}
return {
tenant: apiKey.tenant,
tenantApiKey: {
apiKey,
apiKeyLog,
usage,
},
};
if (!tenant) {
throw await setApiError(request, params, "Account not found", 401);
}
const tenantSubscription = await getActiveTenantSubscriptions(apiKey.tenantId);
const rateLimitResult = await rateLimitByKey({
apiKey: apiKey.id,
tenantId: apiKey.tenantId,
tenantSubscription,
});
const apiKeyLog = await createApiKeyLog(request, {
apiKeyId: apiKey.id,
tenantId: apiKey.tenantId,
endpoint: new URL(request.url).pathname,
});
if (rateLimitResult.error) {
throw await setApiError(request, params, "Rate limit exceeded: " + rateLimitResult.error, 429, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
}
createUniqueLegacyTenantIpAddress({
ip: getTrustedClientIpOrNull(request) ?? "Unknown",
fromUrl: new URL(request.url).pathname,
tenantId: apiKey.tenantId,
apiKeyId: apiKey.id,
});
if (tenant.deactivatedReason) {
throw await setApiError(request, params, "Account deactivated: " + tenant.deactivatedReason, 403, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
}
if (!apiKey.active) {
throw await setApiError(request, params, "Inactive API Key", 400, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
}
if (apiKey.expires && apiKey?.expires < new Date()) {
throw await setApiError(request, params, "Expired API Key", 400, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
}
const usage = await getPlanFeatureUsage(apiKey.tenantId, DefaultFeatures.API, tenantSubscription);
if (usage && !usage.enabled) {
await NotificationService.sendToRoles({
channel: "admin-users",
tenantId: null,
notification: {
message: `${tenant.name} (${tenant.slug}) API error. ${t(usage.message)}`,
action: {
url: absoluteAppPath(loadRequiredWebConfig().routing, tenant.slug, "api/keys"),
},
},
});
throw await setApiError(request, params, t(usage.message), 402, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
}
return {
userId: apiKey.createdByUserId,
tenant,
tenantApiKey: {
apiKey: { ...apiKey, tenant },
apiKeyLog,
usage,
},
};
});
}
export type WorkflowApiAccessValidation = {
@@ -296,7 +257,7 @@ export async function getWorkflowApiKeyFromRequest(request: Request, params: Par
export async function setWorkflowApiKeyLogStatus(
apiAccessValidation: WorkflowApiAccessValidation | undefined,
data: { error?: string; status: number; startTime: number },
data: { error?: string; status: number; startTime: number }
) {
if (!apiAccessValidation?.apiKeyLog) {
return;
@@ -305,5 +266,15 @@ export async function setWorkflowApiKeyLogStatus(
if (!tenantId) {
throw new Error(`API key log ${apiAccessValidation.apiKeyLog.id} cannot be updated without tenant scope`);
}
await setApiKeyLogStatus({ id: apiAccessValidation.apiKeyLog.id, tenantId }, data);
await runWithRlsContext({ tenantId, userId: apiAccessValidation.userId }, () =>
setApiKeyLogStatus({ id: apiAccessValidation.apiKeyLog!.id, tenantId }, data)
);
}
export function runWithWorkflowApiRlsContext<T>(apiAccessValidation: WorkflowApiAccessValidation, callback: () => T): T {
const tenantId = apiAccessValidation.tenant?.id;
if (!tenantId) {
throw new Error("Workflow API tenant context is required");
}
return runWithRlsContext({ tenantId, userId: apiAccessValidation.userId }, callback);
}
File diff suppressed because it is too large. Load diff
@@ -4,15 +4,21 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
findInBlacklist: vi.fn(),
getAppConfiguration: vi.fn(),
getTenantBySlug: vi.fn(),
getUserByEmail: vi.fn(),
register: vi.fn(),
createTenant: vi.fn(),
createTenantUser: vi.fn(),
getAllRoles: vi.fn(),
verifyLeadToken: vi.fn(),
validatePolicyPassword: vi.fn(),
createSignupTenant: vi.fn(),
isCaptchaConfigured: vi.fn(),
verifyCaptchaToken: vi.fn(),
recordExistingTenantLeadConversion: vi.fn(),
leadFindUnique: vi.fn(),
autosubscribeToTrialOrFreePlan: vi.fn(),
createIdempotentTenantEvent: vi.fn(),
resolveRegistrationSubscriptionPrice: vi.fn(),
}));
vi.mock("~/locale/i18next.server", () => ({
@@ -35,7 +41,22 @@ vi.mock("~/utils/app/UserValidationUtils", () => ({
}));
vi.mock("~/services/auth/password-policy.server", () => ({
validatePassword: vi.fn(async () => ({ valid: true, errors: [] })),
validatePassword: (...args: unknown[]) => mocks.validatePolicyPassword(...args),
}));
vi.mock("~/domain/tenant-bootstrap/tenantBootstrapService.server", () => ({
createSignupTenantWithShkDefaults: (...args: unknown[]) => mocks.createSignupTenant(...args),
deriveSignupTenantId: (_email: string, creationRequestKey: string) =>
creationRequestKey === "d7077797-054b-497a-b1ce-8e4f36257a96" ? "tenant_1" : "tenant_other_key",
isSignupCreationRequestKey: (value: string) => /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value),
}));
vi.mock("@hivegrid/captcha", () => ({
resolveCaptchaConfig: vi.fn(() => ({ provider: "mcaptcha", failOpen: false })),
isCaptchaConfigured: (...args: unknown[]) => mocks.isCaptchaConfigured(...args),
verifyCaptchaToken: (...args: unknown[]) => mocks.verifyCaptchaToken(...args),
getSecret: vi.fn(() => "secret"),
getSitekey: vi.fn(() => "sitekey"),
}));
vi.mock("~/utils/db/blacklist.db.server", () => ({
@@ -49,9 +70,9 @@ vi.mock("~/utils/db/users.db.server", () => ({
}));
vi.mock("~/utils/db/tenants.db.server", () => ({
TenantSlugCollisionError: class TenantSlugCollisionError extends Error {},
createTenant: (...args: unknown[]) => mocks.createTenant(...args),
createTenantUser: (...args: unknown[]) => mocks.createTenantUser(...args),
getTenantBySlug: (...args: unknown[]) => mocks.getTenantBySlug(...args),
}));
vi.mock("~/utils/db/permissions/roles.db.server", () => ({ getAllRoles: (...args: unknown[]) => mocks.getAllRoles(...args) }));
@@ -60,9 +81,18 @@ vi.mock("~/utils/db/registration.db.server", () => ({
getRegistrationByEmail: vi.fn(),
updateRegistration: vi.fn(),
}));
vi.mock("~/utils/db.server", () => ({ db: { lead: { findUnique: (...args: unknown[]) => mocks.leadFindUnique(...args) } } }));
vi.mock("@hivegrid/db/pretenant-security.server", () => ({
findLeadForSignedConversionCapability: (...args: unknown[]) => mocks.leadFindUnique(...args),
RegistrationCreateConflictError: class RegistrationCreateConflictError extends Error {},
}));
vi.mock("~/utils/url.server", () => ({ getAbsoluteUrl: vi.fn(() => "https://example.test") }));
vi.mock("~/modules/events/services/.server/EventsService", () => ({ default: { create: vi.fn() } }));
vi.mock("~/modules/events/services/.server/EventsService", () => ({
default: {
create: vi.fn(),
createIdempotentTenantEvent: (...args: unknown[]) => mocks.createIdempotentTenantEvent(...args),
},
}));
vi.mock("~/modules/events/utils/EventUtils", () => ({ default: { getDescription: vi.fn(() => "Account created") } }));
vi.mock("~/modules/emails/services/TransactionalEmailQueue.server", () => ({ queueTransactionalEmail: vi.fn() }));
vi.mock("~/modules/emails/utils/EmailTemplates", () => ({ default: { WELCOME_EMAIL: { parse: vi.fn(() => ({ subject: "Welcome", body: "Welcome" })) } } }));
vi.mock("~/locale/mail-translator.server", () => ({
@@ -70,20 +100,58 @@ vi.mock("~/locale/mail-translator.server", () => ({
getMailTranslatorFromRequest: vi.fn(),
}));
vi.mock("~/modules/ipAddress/services/IpAddressService.server", () => ({ default: { log: vi.fn() } }));
vi.mock("~/utils/api/.server/TenantTypesApi", () => ({ TenantTypesApi: { setTenantTypes: vi.fn() } }));
vi.mock("~/utils/leads/leadToken.server", () => ({ verifyLeadToken: (...args: unknown[]) => mocks.verifyLeadToken(...args) }));
vi.mock("~/utils/leads/convertLead.server", () => ({ recordExistingTenantLeadConversion: (...args: unknown[]) => mocks.recordExistingTenantLeadConversion(...args) }));
vi.mock("~/utils/leads/convertLead.server", () => ({
recordExistingTenantLeadConversion: (...args: unknown[]) => mocks.recordExistingTenantLeadConversion(...args),
}));
vi.mock("./.server/pricingService", () => ({
autosubscribeToTrialOrFreePlan: (...args: unknown[]) => mocks.autosubscribeToTrialOrFreePlan(...args),
}));
vi.mock("~/services/billing/registration-plan-selection.server", () => ({
resolveRegistrationSubscriptionPrice: (...args: unknown[]) => mocks.resolveRegistrationSubscriptionPrice(...args),
}));
vi.mock("@hivegrid/foundation", async () => {
const actual = await vi.importActual<typeof import("@hivegrid/foundation")>("@hivegrid/foundation");
return {
...actual,
withIdempotency: vi.fn(async (_input: unknown, _client: unknown, operation: () => Promise<unknown>) => ({
...(await operation()),
replayed: false,
})),
};
});
vi.mock("@hivegrid/db/outbox", () => ({ publishOutboxEvent: vi.fn(async () => ({})) }));
vi.mock("@hivegrid/queue", () => ({
buildWorkflowTriggerOutboxEvent: vi.fn(() => ({
tenantId: "tenant_1",
type: "workflow.trigger.event",
payload: {},
dispatchKey: "workflow-trigger:event_1",
})),
}));
vi.mock("~/utils/db.server", () => ({
db: {
$transaction: vi.fn(async (callback: (tx: unknown) => Promise<unknown>) => callback({ event: { create: vi.fn(async () => ({ id: "event_1" })) } })),
},
}));
import { TenantSlugCollisionError } from "~/utils/db/tenants.db.server";
import { validateRegistration } from "./authService";
const request = new Request("https://example.test/register");
const CREATION_REQUEST_KEY = "d7077797-054b-497a-b1ce-8e4f36257a96";
const OTHER_CREATION_REQUEST_KEY = "b79f4743-b5ee-48df-9287-10f24b2aedbf";
function appConfiguration(slug: { require: boolean; type: "tenant" | "user" } = { require: false, type: "tenant" }) {
function appConfiguration(
slug: { require: boolean; type: "tenant" | "username" } = { require: false, type: "tenant" },
requireEmailVerification = false,
requiredFields: { organization?: boolean; name?: boolean } = {}
) {
return {
auth: {
requireEmailVerification: false,
requireOrganization: false,
requireName: false,
requireEmailVerification,
requireOrganization: requiredFields.organization ?? false,
requireName: requiredFields.name ?? false,
slug,
},
};
@@ -95,7 +163,6 @@ describe("validateRegistration i18n errors", () => {
mocks.getAppConfiguration.mockResolvedValue(appConfiguration());
mocks.findInBlacklist.mockResolvedValue(null);
mocks.getUserByEmail.mockResolvedValue(null);
mocks.getTenantBySlug.mockResolvedValue(null);
mocks.createTenant.mockResolvedValue({ id: "tenant_1", name: "Ada", slug: "ada" });
mocks.register.mockResolvedValue({ id: "user_1", email: "ada@example.test", locale: "en" });
mocks.createTenantUser.mockResolvedValue({});
@@ -103,9 +170,350 @@ describe("validateRegistration i18n errors", () => {
mocks.verifyLeadToken.mockReturnValue(null);
mocks.recordExistingTenantLeadConversion.mockResolvedValue({});
mocks.leadFindUnique.mockResolvedValue(null);
mocks.validatePolicyPassword.mockResolvedValue({ valid: true, errors: [] });
mocks.createSignupTenant.mockResolvedValue({
tenant: { id: "tenant_1", name: "Ada", slug: "ada" },
user: { id: "user_1", email: "ada@example.test", locale: "en" },
replayed: false,
});
mocks.isCaptchaConfigured.mockReturnValue(false);
mocks.verifyCaptchaToken.mockResolvedValue(true);
mocks.autosubscribeToTrialOrFreePlan.mockResolvedValue(undefined);
mocks.createIdempotentTenantEvent.mockResolvedValue("account.created");
mocks.resolveRegistrationSubscriptionPrice.mockResolvedValue({
planId: "product_starter",
planCode: "starter",
titleKey: "Core",
descriptionKey: "Core plan",
priceId: "price_starter",
amountCents: 19_900,
currency: "EUR",
billingPeriod: 3,
});
delete process.env.LEAD_CONVERSION_ENABLED;
});
it("binds exact signup retries to one idempotent trial subscription and event key", async () => {
const appliedKeys = new Set<string>();
let subscriptionWrites = 0;
let logicalSubscriptionEvents = 0;
mocks.autosubscribeToTrialOrFreePlan.mockImplementation(async ({ idempotencyKey }: { idempotencyKey: string }) => {
if (!appliedKeys.has(idempotencyKey)) {
appliedKeys.add(idempotencyKey);
subscriptionWrites += 1;
logicalSubscriptionEvents += 1;
}
});
const input = {
request,
registrationData: {
email: "ada@example.test",
password: "Password123!",
creationRequestKey: CREATION_REQUEST_KEY,
},
checkEmailVerification: false,
addToTrialOrFreePlan: true,
};
await validateRegistration(input);
await validateRegistration(input);
expect(mocks.autosubscribeToTrialOrFreePlan).toHaveBeenCalledTimes(2);
expect(mocks.autosubscribeToTrialOrFreePlan).toHaveBeenNthCalledWith(
1,
expect.objectContaining({
tenantId: "tenant_1",
userId: "user_1",
idempotencyKey: CREATION_REQUEST_KEY,
throwOnFailure: true,
})
);
expect(subscriptionWrites).toBe(1);
expect(logicalSubscriptionEvents).toBe(1);
expect(appliedKeys).toEqual(new Set([CREATION_REQUEST_KEY]));
});
it("requires an exact canonical subscription price for public registration", async () => {
await expect(
validateRegistration({
request,
registrationData: {
email: "ada@example.test",
password: "Password123!",
creationRequestKey: CREATION_REQUEST_KEY,
},
addToTrialOrFreePlan: false,
requireSubscriptionSelection: true,
})
).rejects.toThrow("account.register.errors.priceNotSelected");
mocks.resolveRegistrationSubscriptionPrice.mockResolvedValueOnce(null);
await expect(
validateRegistration({
request,
registrationData: {
email: "ada@example.test",
password: "Password123!",
selectedSubscriptionPriceId: "forged_price",
creationRequestKey: CREATION_REQUEST_KEY,
},
addToTrialOrFreePlan: false,
requireSubscriptionSelection: true,
})
).rejects.toThrow("account.register.errors.priceNotInDatabase");
expect(mocks.createSignupTenant).not.toHaveBeenCalled();
});
it("requires a complete bounded registration team size and returns it unchanged", async () => {
const baseData = {
email: "ada@example.test",
selectedSubscriptionPriceId: "price_starter",
creationRequestKey: CREATION_REQUEST_KEY,
};
await expect(
validateRegistration({
request,
registrationData: baseData,
addToTrialOrFreePlan: false,
requireSubscriptionSelection: true,
})
).rejects.toThrow("auth:errors.invalidFormData");
await expect(
validateRegistration({
request,
registrationData: { ...baseData, selectedOfficeSeatQuantity: 0, selectedFieldSeatQuantity: 1 },
addToTrialOrFreePlan: false,
requireSubscriptionSelection: true,
})
).rejects.toThrow("auth:errors.invalidFormData");
await expect(
validateRegistration({
request,
registrationData: { ...baseData, selectedOfficeSeatQuantity: 5 },
addToTrialOrFreePlan: false,
requireSubscriptionSelection: true,
})
).rejects.toThrow("auth:errors.invalidFormData");
await expect(
validateRegistration({
request,
registrationData: { ...baseData, selectedFieldSeatQuantity: 0 },
addToTrialOrFreePlan: false,
requireSubscriptionSelection: true,
})
).rejects.toThrow("auth:errors.invalidFormData");
mocks.getAppConfiguration.mockResolvedValueOnce(appConfiguration({ require: false, type: "tenant" }, true));
await expect(
validateRegistration({
request,
registrationData: { ...baseData, selectedOfficeSeatQuantity: 5, selectedFieldSeatQuantity: 15 },
addToTrialOrFreePlan: false,
requireSubscriptionSelection: true,
})
).resolves.toMatchObject({
verificationRequired: true,
selectedOfficeSeatQuantity: 5,
selectedFieldSeatQuantity: 15,
});
});
it("binds the validated plan and team size to the direct signup bootstrap", async () => {
await validateRegistration({
request,
registrationData: {
email: "ada@example.test",
password: "Password123!",
selectedSubscriptionPriceId: "price_starter",
selectedOfficeSeatQuantity: 5,
selectedFieldSeatQuantity: 15,
creationRequestKey: CREATION_REQUEST_KEY,
},
addToTrialOrFreePlan: false,
requireSubscriptionSelection: true,
checkEmailVerification: false,
});
expect(mocks.createSignupTenant).toHaveBeenCalledWith(
expect.objectContaining({
creationRequestKey: CREATION_REQUEST_KEY,
billingPreference: {
selectedSubscriptionPriceId: "price_starter",
selectedOfficeSeatQuantity: 5,
selectedFieldSeatQuantity: 15,
},
})
);
});
it("propagates an atomic bootstrap failure and lets an exact signup retry commit the preference", async () => {
mocks.createSignupTenant
.mockRejectedValueOnce(new Error("preference transaction unavailable"))
.mockResolvedValueOnce({
tenant: { id: "tenant_1", name: "Ada", slug: "ada" },
user: { id: "user_1", email: "ada@example.test", locale: "en" },
replayed: false,
});
const input = {
request,
registrationData: {
email: "ada@example.test",
password: "Password123!",
selectedSubscriptionPriceId: "price_starter",
selectedOfficeSeatQuantity: 5,
selectedFieldSeatQuantity: 15,
creationRequestKey: CREATION_REQUEST_KEY,
},
addToTrialOrFreePlan: false,
requireSubscriptionSelection: true,
checkEmailVerification: false,
};
await expect(validateRegistration(input)).rejects.toThrow("preference transaction unavailable");
await expect(validateRegistration(input)).resolves.toMatchObject({ registered: { tenant: { id: "tenant_1" } } });
expect(mocks.createSignupTenant).toHaveBeenCalledTimes(2);
expect(mocks.createSignupTenant).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
billingPreference: {
selectedSubscriptionPriceId: "price_starter",
selectedOfficeSeatQuantity: 5,
selectedFieldSeatQuantity: 15,
},
})
);
});
it("propagates a required subscription failure so an exact retry can complete it once", async () => {
const logicalEntitlements = new Set<string>();
let logicalSubscriptionEvents = 0;
mocks.autosubscribeToTrialOrFreePlan
.mockRejectedValueOnce(new Error("subscription transaction unavailable"))
.mockImplementationOnce(async ({ idempotencyKey }: { idempotencyKey: string }) => {
if (!logicalEntitlements.has(idempotencyKey)) {
logicalEntitlements.add(idempotencyKey);
logicalSubscriptionEvents += 1;
}
});
const input = {
request,
registrationData: {
email: "ada@example.test",
password: "Password123!",
creationRequestKey: CREATION_REQUEST_KEY,
},
checkEmailVerification: false,
addToTrialOrFreePlan: true,
};
await expect(validateRegistration(input)).rejects.toThrow("subscription transaction unavailable");
await expect(validateRegistration(input)).resolves.toMatchObject({ registered: { tenant: { id: "tenant_1" } } });
expect(mocks.autosubscribeToTrialOrFreePlan).toHaveBeenCalledTimes(2);
expect(logicalEntitlements).toEqual(new Set([CREATION_REQUEST_KEY]));
expect(logicalSubscriptionEvents).toBe(1);
});
it("lets an exact slug retry reach deterministic bootstrap after the tenant commit", async () => {
mocks.getAppConfiguration.mockResolvedValue(appConfiguration({ require: true, type: "tenant" }));
const input = {
request,
registrationData: {
email: "ada@example.test",
password: "Password123!",
company: "Ada Labs",
slug: "ada-labs",
creationRequestKey: CREATION_REQUEST_KEY,
},
checkEmailVerification: false,
addToTrialOrFreePlan: false,
};
await validateRegistration(input);
await validateRegistration(input);
expect(mocks.createSignupTenant).toHaveBeenCalledTimes(2);
});
it("maps an authoritative committed-slug collision after the constraint race", async () => {
mocks.getAppConfiguration.mockResolvedValue(appConfiguration({ require: true, type: "tenant" }));
mocks.createSignupTenant.mockRejectedValueOnce(new TenantSlugCollisionError());
await expect(
validateRegistration({
request,
registrationData: {
email: "ada@example.test",
password: "Password123!",
company: "Ada Labs",
slug: "ada-labs",
creationRequestKey: OTHER_CREATION_REQUEST_KEY,
},
checkEmailVerification: false,
addToTrialOrFreePlan: false,
})
).rejects.toThrow("account.register.errors.slugTaken");
expect(mocks.createSignupTenant).toHaveBeenCalledOnce();
});
it("allows an exact lead conversion retry only for its deterministic committed tenant", async () => {
mocks.verifyLeadToken.mockReturnValue({ leadId: "lead_1", planId: "plan_pro" });
mocks.leadFindUnique
.mockResolvedValueOnce({ email: "ada@example.test", convertedToTenantId: null })
.mockResolvedValueOnce({ email: "ada@example.test", convertedToTenantId: "tenant_1" });
const logicalConversions = new Set<string>();
mocks.recordExistingTenantLeadConversion.mockImplementation(async ({ leadId, tenantId }: { leadId: string; tenantId: string }) => {
logicalConversions.add(`${leadId}:${tenantId}`);
return { alreadyConverted: logicalConversions.size === 1 };
});
const input = {
request,
registrationData: {
email: "ada@example.test",
password: "Password123!",
company: "Ada Labs",
leadId: "lead_1",
leadToken: "signed-lead-token",
leadPlanId: "plan_pro",
creationRequestKey: CREATION_REQUEST_KEY,
},
checkEmailVerification: false,
addToTrialOrFreePlan: false,
};
await validateRegistration(input);
await validateRegistration(input);
expect(mocks.createSignupTenant).toHaveBeenCalledTimes(2);
expect(mocks.recordExistingTenantLeadConversion).toHaveBeenCalledTimes(2);
expect(logicalConversions).toEqual(new Set(["lead_1:tenant_1"]));
});
it("rejects an already-converted lead when another request key derives another tenant", async () => {
mocks.verifyLeadToken.mockReturnValue({ leadId: "lead_1", planId: "plan_pro" });
mocks.leadFindUnique.mockResolvedValue({ email: "ada@example.test", convertedToTenantId: "tenant_1" });
await expect(
validateRegistration({
request,
registrationData: {
email: "ada@example.test",
password: "Password123!",
leadId: "lead_1",
leadToken: "signed-lead-token",
creationRequestKey: OTHER_CREATION_REQUEST_KEY,
},
checkEmailVerification: false,
addToTrialOrFreePlan: false,
})
).rejects.toThrow("account.register.errors.invalidLeadConversion");
expect(mocks.createSignupTenant).not.toHaveBeenCalled();
expect(mocks.recordExistingTenantLeadConversion).not.toHaveBeenCalled();
});
it.each([
["companyMaxLength", { company: "a".repeat(101) }],
["firstNameMaxLength", { firstName: "a".repeat(51) }],
@@ -114,22 +522,86 @@ describe("validateRegistration i18n errors", () => {
await expect(
validateRegistration({
request,
registrationData: { email: "ada@example.test", password: "Password123!", ...registrationData },
registrationData: { email: "ada@example.test", password: "Password123!", creationRequestKey: CREATION_REQUEST_KEY, ...registrationData },
addToTrialOrFreePlan: false,
})
).rejects.toThrow(`account.register.errors.${errorKey}`);
});
it.each([
["missing organization", { firstName: "Ada", lastName: "Lovelace" }, { organization: true }, "organizationRequired"],
["blank organization", { company: " ", firstName: "Ada", lastName: "Lovelace" }, { organization: true }, "organizationRequired"],
["missing first name", { company: "Ada Labs", lastName: "Lovelace" }, { name: true }, "nameRequired"],
["blank last name", { company: "Ada Labs", firstName: "Ada", lastName: " " }, { name: true }, "nameRequired"],
])("rejects %s before direct account bootstrap", async (_label, registrationData, requiredFields, errorKey) => {
mocks.getAppConfiguration.mockResolvedValueOnce(appConfiguration({ require: false, type: "tenant" }, false, requiredFields));
await expect(
validateRegistration({
request,
registrationData: {
email: "ada@example.test",
password: "Password123!",
creationRequestKey: CREATION_REQUEST_KEY,
...registrationData,
},
addToTrialOrFreePlan: false,
})
).rejects.toThrow(`account.register.errors.${errorKey}`);
expect(mocks.createSignupTenant).not.toHaveBeenCalled();
});
it("enforces required fields on the initial email-verification post", async () => {
mocks.getAppConfiguration.mockResolvedValueOnce(appConfiguration({ require: false, type: "tenant" }, true, { organization: true, name: true }));
await expect(
validateRegistration({
request,
registrationData: {
email: "ada@example.test",
firstName: "Ada",
lastName: "Lovelace",
creationRequestKey: CREATION_REQUEST_KEY,
},
addToTrialOrFreePlan: false,
})
).rejects.toThrow("account.register.errors.organizationRequired");
expect(mocks.createSignupTenant).not.toHaveBeenCalled();
});
it("accepts non-blank configured registration fields", async () => {
mocks.getAppConfiguration.mockResolvedValueOnce(appConfiguration({ require: false, type: "tenant" }, false, { organization: true, name: true }));
await expect(
validateRegistration({
request,
registrationData: {
email: "ada@example.test",
password: "Password123!",
company: "Ada Labs",
firstName: "Ada",
lastName: "Lovelace",
creationRequestKey: CREATION_REQUEST_KEY,
},
addToTrialOrFreePlan: false,
})
).resolves.toMatchObject({ verificationRequired: false, registered: { tenant: { id: "tenant_1" } } });
expect(mocks.createSignupTenant).toHaveBeenCalledTimes(1);
});
it.each([
["tenant", "slugRequired"],
["user", "usernameRequired"],
["username", "usernameRequired"],
] as const)("uses a translation key when the %s slug is required", async (slugType, errorKey) => {
mocks.getAppConfiguration.mockResolvedValueOnce(appConfiguration({ require: true, type: slugType }));
await expect(
validateRegistration({
request,
registrationData: { email: "ada@example.test", password: "Password123!" },
registrationData: { email: "ada@example.test", password: "Password123!", creationRequestKey: CREATION_REQUEST_KEY },
addToTrialOrFreePlan: false,
})
).rejects.toThrow(`account.register.errors.${errorKey}`);
@@ -137,15 +609,15 @@ describe("validateRegistration i18n errors", () => {
it.each([
["tenant", "slugTaken"],
["user", "usernameTaken"],
["username", "usernameTaken"],
] as const)("uses a translation key when the %s slug is already taken", async (slugType, errorKey) => {
mocks.getAppConfiguration.mockResolvedValueOnce(appConfiguration({ require: true, type: slugType }));
mocks.getTenantBySlug.mockResolvedValueOnce({ id: "tenant_1" });
mocks.getAppConfiguration.mockResolvedValue(appConfiguration({ require: true, type: slugType }));
mocks.createSignupTenant.mockRejectedValueOnce(new TenantSlugCollisionError());
await expect(
validateRegistration({
request,
registrationData: { email: "ada@example.test", password: "Password123!", slug: "ada" },
registrationData: { email: "ada@example.test", password: "Password123!", slug: "ada", creationRequestKey: CREATION_REQUEST_KEY },
addToTrialOrFreePlan: false,
})
).rejects.toThrow(`account.register.errors.${errorKey}`);
@@ -158,7 +630,7 @@ describe("validateRegistration i18n errors", () => {
await expect(
validateRegistration({
request,
registrationData: { email: "ada@example.test", password: "Password123!", slug },
registrationData: { email: "ada@example.test", password: "Password123!", slug, creationRequestKey: CREATION_REQUEST_KEY },
addToTrialOrFreePlan: false,
})
).rejects.toThrow(`account.register.errors.${errorKey}`);
@@ -184,7 +656,7 @@ describe("validateRegistration i18n errors", () => {
await expect(
validateRegistration({
request,
registrationData,
registrationData: { creationRequestKey: CREATION_REQUEST_KEY, ...registrationData },
addToTrialOrFreePlan: false,
})
).rejects.toThrow("account.register.errors.invalidLeadConversion");
@@ -204,6 +676,7 @@ describe("validateRegistration i18n errors", () => {
leadId: "lead_1",
leadToken: "signed",
leadPlanId: "plan_from_form",
creationRequestKey: CREATION_REQUEST_KEY,
},
addToTrialOrFreePlan: false,
})
@@ -212,8 +685,90 @@ describe("validateRegistration i18n errors", () => {
expect(mocks.recordExistingTenantLeadConversion).toHaveBeenCalledWith({
leadId: "lead_1",
tenantId: "tenant_1",
userId: "user_1",
expectedEmail: "ada@example.test",
planId: "plan_from_token",
conversionPath: "self-service",
});
});
it("requires a password when completing an email-verified registration", async () => {
mocks.getAppConfiguration.mockResolvedValueOnce(appConfiguration({ require: false, type: "tenant" }, true));
await expect(
validateRegistration({
request,
registrationData: { email: "ada@example.test", creationRequestKey: CREATION_REQUEST_KEY },
addToTrialOrFreePlan: false,
checkEmailVerification: false,
})
).rejects.toThrow("account.register.errors.passwordRequired");
expect(mocks.createSignupTenant).not.toHaveBeenCalled();
});
it.each([
["weak", "auth:errors.passwordTooShort"],
["compromised", "auth:errors.passwordCompromised"],
])("rejects a %s password before bootstrap on the verify path", async (_label, code) => {
mocks.getAppConfiguration.mockResolvedValueOnce(appConfiguration({ require: false, type: "tenant" }, true));
mocks.validatePolicyPassword.mockResolvedValueOnce({ valid: false, errors: [{ code, args: {} }] });
await expect(
validateRegistration({
request,
registrationData: {
email: "ada@example.test",
password: "bad-password",
creationRequestKey: CREATION_REQUEST_KEY,
},
addToTrialOrFreePlan: false,
checkEmailVerification: false,
})
).rejects.toThrow(code);
expect(mocks.createSignupTenant).not.toHaveBeenCalled();
});
it("keeps captcha mandatory on the initial registration post", async () => {
mocks.isCaptchaConfigured.mockReturnValueOnce(true);
mocks.verifyCaptchaToken.mockResolvedValueOnce(false);
await expect(
validateRegistration({
request,
registrationData: {
email: "ada@example.test",
password: "Password123!",
creationRequestKey: CREATION_REQUEST_KEY,
},
addToTrialOrFreePlan: false,
})
).rejects.toThrow("account.register.errors.captchaFailed");
expect(mocks.verifyCaptchaToken).toHaveBeenCalledTimes(1);
expect(mocks.createSignupTenant).not.toHaveBeenCalled();
});
it("does not require a second captcha after the outer verify flow validated token and bound key", async () => {
mocks.getAppConfiguration.mockResolvedValueOnce(appConfiguration({ require: false, type: "tenant" }, true));
mocks.isCaptchaConfigured.mockReturnValueOnce(true);
await expect(
validateRegistration({
request,
registrationData: {
email: "ada@example.test",
password: "Password123!",
creationRequestKey: CREATION_REQUEST_KEY,
},
addToTrialOrFreePlan: false,
checkEmailVerification: false,
captchaAlreadyVerified: true,
})
).resolves.toMatchObject({ verificationRequired: false, registered: { tenant: { id: "tenant_1" } } });
expect(mocks.verifyCaptchaToken).not.toHaveBeenCalled();
expect(mocks.createSignupTenant).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,49 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { createSharedStore, MemoryAdapter } from "@hivegrid/shared-store";
import { __resetRateLimitStoreForTests, __setRateLimitStoreForTests, rateLimitByKey } from "./rateLimitService";
const input = {
apiKey: "api-key-1",
tenantId: "tenant-1",
tenantSubscription: null,
limitByMinute: 2,
limitBySecond: 100,
};
describe("legacy API shared rate limit", () => {
beforeEach(() => {
__setRateLimitStoreForTests(createSharedStore({ namespace: "legacy-api-rate-test", adapter: new MemoryAdapter() }));
});
afterEach(() => {
__resetRateLimitStoreForTests();
});
it("enforces one counter shared by every caller instead of a process-local LRU", async () => {
await expect(rateLimitByKey(input)).resolves.toEqual({ success: true, error: null });
await expect(rateLimitByKey(input)).resolves.toEqual({ success: true, error: null });
await expect(rateLimitByKey(input)).resolves.toMatchObject({
success: false,
error: expect.stringContaining("2 request/min"),
});
});
it("atomically caps a parallel burst", async () => {
const results = await Promise.all(Array.from({ length: 20 }, () => rateLimitByKey({ ...input, apiKey: "parallel-key", limitByMinute: 5 })));
expect(results.filter((result) => result.success)).toHaveLength(5);
expect(results.filter((result) => !result.success)).toHaveLength(15);
});
it("fails closed when the shared counter is unavailable", async () => {
const adapter = new MemoryAdapter();
await adapter.close();
__setRateLimitStoreForTests(createSharedStore({ namespace: "legacy-api-rate-closed", adapter }));
await expect(rateLimitByKey(input)).resolves.toEqual({
success: false,
error: "Rate limit service temporarily unavailable",
});
});
});
@@ -1,14 +1,19 @@
import { getPlanFeatureUsage } from "./.server/subscriptionService";
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
import { SubscriptionFeatureLimitType } from "~/application/enums/subscriptions/SubscriptionFeatureLimitType";
import { cache } from "../cache.server";
import { TenantSubscriptionWithDetails } from "../db/tenantSubscriptions.db.server";
import { createFixedWindowRateLimiter, type SharedStore } from "@hivegrid/shared-store";
import { getSharedStore } from "~/shared-store.server";
const DEFAULT_RATE_LIMIT_PER_MINUTE = 60;
const DEFAULT_RATE_LIMIT_PER_SECOND = 5;
function getCacheKey(apiKey: string, period: string, timestamp: number): string {
return `rateLimit:${apiKey}:${period}:${timestamp}`;
let storeFactory: () => SharedStore = () => getSharedStore();
function featureLimit(feature: Awaited<ReturnType<typeof getPlanFeatureUsage>> | null, fallback: number): number {
if (!feature) return fallback;
if (feature.type === SubscriptionFeatureLimitType.UNLIMITED) return 0;
return feature.value;
}
export async function rateLimitByKey({
@@ -27,52 +32,62 @@ export async function rateLimitByKey({
success: boolean;
error: string | null;
}> {
const currentTimestamp = Math.floor(Date.now() / 1000);
const minuteTimestamp = Math.floor(currentTimestamp / 60);
const secondTimestamp = currentTimestamp;
const [minuteFeature, secondFeature] = await Promise.all([
limitByMinute === undefined ? getPlanFeatureUsage(tenantId, DefaultFeatures.RateLimitPerMinute, tenantSubscription) : Promise.resolve(null),
limitBySecond === undefined ? getPlanFeatureUsage(tenantId, DefaultFeatures.RateLimitPerSecond, tenantSubscription) : Promise.resolve(null),
]);
const minuteLimit = limitByMinute ?? featureLimit(minuteFeature, DEFAULT_RATE_LIMIT_PER_MINUTE);
const secondLimit = limitBySecond ?? featureLimit(secondFeature, DEFAULT_RATE_LIMIT_PER_SECOND);
const minuteKey = getCacheKey(apiKey, "minute", minuteTimestamp);
const secondKey = getCacheKey(apiKey, "second", secondTimestamp);
try {
const store = storeFactory();
const [minuteDecision, secondDecision] = await Promise.all([
minuteLimit === 0
? Promise.resolve(null)
: createFixedWindowRateLimiter({
store,
prefix: "legacy-api-minute",
windowSeconds: 60,
max: minuteLimit,
}).consume(apiKey),
secondLimit === 0
? Promise.resolve(null)
: createFixedWindowRateLimiter({
store,
prefix: "legacy-api-second",
windowSeconds: 1,
max: secondLimit,
}).consume(apiKey),
]);
let minuteCount = (cache.get(minuteKey)?.value as number) || 0;
let secondCount = (cache.get(secondKey)?.value as number) || 0;
if (limitByMinute === undefined) {
const feature = await getPlanFeatureUsage(tenantId, DefaultFeatures.RateLimitPerMinute, tenantSubscription);
if (!feature) {
limitByMinute = DEFAULT_RATE_LIMIT_PER_MINUTE;
} else if (feature.type === SubscriptionFeatureLimitType.UNLIMITED) {
limitByMinute = 0;
} else {
limitByMinute = feature.value;
if (minuteDecision && !minuteDecision.allowed) {
const retryAfterSeconds = Math.max(1, Math.ceil((minuteDecision.resetAt.getTime() - Date.now()) / 1000));
return {
success: false,
error: `You've exceeded the ${minuteLimit} request/min rate limit, try again in ${retryAfterSeconds} seconds`,
};
}
}
if (limitBySecond === undefined) {
const feature = await getPlanFeatureUsage(tenantId, DefaultFeatures.RateLimitPerSecond, tenantSubscription);
if (!feature) {
limitBySecond = DEFAULT_RATE_LIMIT_PER_SECOND;
} else if (feature.type === SubscriptionFeatureLimitType.UNLIMITED) {
limitBySecond = 0;
} else {
limitBySecond = feature.value;
if (secondDecision && !secondDecision.allowed) {
return {
success: false,
error: `You've exceeded the ${secondLimit} request/sec rate limit`,
};
}
} catch {
// A replica-local fallback would make the advertised limit bypassable by
// round-robin traffic. Authentication/usage enforcement therefore fails
// closed while the shared counter is unavailable.
return { success: false, error: "Rate limit service temporarily unavailable" };
}
minuteCount += 1;
secondCount += 1;
if (limitByMinute !== 0 && minuteCount > limitByMinute) {
let tryAgainIn = 60 - (currentTimestamp % 60);
return { success: false, error: `You've exceeded the ${limitByMinute} request/min rate limit, try again in ${tryAgainIn} seconds` };
}
if (limitBySecond !== 0 && secondCount > limitBySecond) {
return { success: false, error: `You've exceeded the ${limitBySecond} request/sec rate limit` };
}
cache.set(minuteKey, { value: minuteCount, metadata: { createdTime: Date.now() } }, { ttl: 60 * 1000 });
cache.set(secondKey, { value: secondCount, metadata: { createdTime: Date.now() } }, { ttl: 1000 });
return { success: true, error: null };
}
export function __setRateLimitStoreForTests(store: SharedStore): void {
storeFactory = () => store;
}
export function __resetRateLimitStoreForTests(): void {
storeFactory = () => getSharedStore();
}
@@ -72,6 +72,7 @@ describe("seedRolesAndPermissions diagnostics", () => {
adminGetAllTenantsMock.mockResolvedValue([
{
id: "tenant-1",
slug: "tenant-1",
users: [
{ userId: "admin-user-id" } as Awaited<ReturnType<typeof adminGetAllTenants>>[number]["users"][number],
{ userId: "app-user-id" } as Awaited<ReturnType<typeof adminGetAllTenants>>[number]["users"][number],
@@ -136,6 +137,33 @@ describe("seedRolesAndPermissions diagnostics", () => {
);
});
test("excludes managed tenants from boot-time app role assignments", async () => {
adminGetAllTenantsMock.mockResolvedValueOnce([
{
id: "tenant-1",
slug: "tenant-1",
users: [{ userId: "app-user-id" } as Awaited<ReturnType<typeof adminGetAllTenants>>[number]["users"][number]],
} as Awaited<ReturnType<typeof adminGetAllTenants>>[number],
{
id: "tenant-pro",
slug: "demo-pro-crm",
users: [{ userId: "managed-user-id" } as Awaited<ReturnType<typeof adminGetAllTenants>>[number]["users"][number]],
} as Awaited<ReturnType<typeof adminGetAllTenants>>[number],
]);
const diagnostics = vi.fn();
await seedRolesAndPermissions({
adminEmail: "admin@email.com",
diagnostics,
excludedTenantSlugs: ["demo-pro-crm"],
});
const assignments = createUserRoleAssignmentsMock.mock.calls[0]?.[0] ?? [];
expect(assignments).toEqual(expect.arrayContaining([{ userId: "app-user-id", roleId: appRoleRows[0]?.id, tenantId: "tenant-1" }]));
expect(assignments).not.toEqual(expect.arrayContaining([{ userId: "managed-user-id", roleId: appRoleRows[0]?.id, tenantId: "tenant-pro" }]));
expect(diagnostics).toHaveBeenLastCalledWith(expect.objectContaining({ phase: "success", tenantUserAssignmentCount: appRoleRows.length }));
});
test("emits failure diagnostics and rethrows the original seed error", async () => {
const diagnostics = vi.fn();
const originalError = new Error("seed failed without password token literals");
@@ -44,6 +44,7 @@ export type RolesAndPermissionsSeedDiagnostics = (event: RolesAndPermissionsSeed
export type SeedRolesAndPermissionsOptions = {
adminEmail?: string;
diagnostics?: RolesAndPermissionsSeedDiagnostics;
excludedTenantSlugs?: readonly string[];
};
function toSeedRolesAndPermissionsOptions(adminEmailOrOptions?: string | SeedRolesAndPermissionsOptions): SeedRolesAndPermissionsOptions {
@@ -61,7 +62,8 @@ async function emitRolesAndPermissionsSeedDiagnostic(
}
export async function seedRolesAndPermissions(adminEmailOrOptions?: string | SeedRolesAndPermissionsOptions): Promise<void> {
const { adminEmail, diagnostics } = toSeedRolesAndPermissionsOptions(adminEmailOrOptions);
const { adminEmail, diagnostics, excludedTenantSlugs = [] } = toSeedRolesAndPermissionsOptions(adminEmailOrOptions);
const excludedTenantSlugSet = new Set(excludedTenantSlugs);
const counts = {
adminRoleCount: defaultAdminRoles.length,
appRoleCount: defaultAppRoles.length,
@@ -93,7 +95,9 @@ export async function seedRolesAndPermissions(adminEmailOrOptions?: string | See
});
const tenants = await adminGetAllTenants();
tenants.forEach((tenant) => {
tenants
.filter((tenant) => !excludedTenantSlugSet.has(tenant.slug))
.forEach((tenant) => {
tenant.users.forEach((tenantUser) => {
appRoles.forEach((appRole) => {
counts.tenantUserAssignmentCount += 1;
@@ -1,90 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const dbMock = vi.hoisted(() => ({
permission: { findMany: vi.fn() },
role: { findFirst: vi.fn(), create: vi.fn() },
rolePermission: { findFirst: vi.fn(), create: vi.fn() },
}));
vi.mock("~/utils/db.server", () => ({ db: dbMock, dbRead: dbMock }));
const configMock = vi.hoisted(() => ({ nodeEnv: "test" }));
vi.mock("@hivegrid/config", () => ({ loadWebConfig: () => ({ config: { nodeEnv: configMock.nodeEnv } }) }));
import { SHK_ROLE_NAMES, SHK_ROLE_SEEDS, seedShkRolesForTenant, shouldSeedShkRoles } from "./shkRoles.server";
beforeEach(() => {
vi.clearAllMocks();
configMock.nodeEnv = "test";
});
describe("SHK role definitions", () => {
it("defines the six partner-named roles with Geschaeftsfuehrer as admin tier", () => {
expect(SHK_ROLE_NAMES).toEqual(["Geschäftsführer", "Projektleiter", "Verwaltung", "Vertriebler", "Kundensupporter", "Monteur"]);
expect(SHK_ROLE_SEEDS.find((role) => role.name === "Geschäftsführer")?.tier).toBe("admin");
});
it("gives every role at least dashboard access as the P2 baseline", () => {
for (const role of SHK_ROLE_SEEDS) {
expect(role.permissionKeys).toContain("app.dashboard.view");
}
});
});
describe("shouldSeedShkRoles (production seeds admin-only)", () => {
it("skips the SHK seeds on production by default (David's D-P2 decision)", () => {
configMock.nodeEnv = "production";
expect(shouldSeedShkRoles({})).toBe(false);
});
it("seeds on staging (SENTRY_ENVIRONMENT wins over NODE_ENV=production) and local dev", () => {
// Staging containers run NODE_ENV=production — the deploy-scoped env var decides.
configMock.nodeEnv = "production";
expect(shouldSeedShkRoles({ SENTRY_ENVIRONMENT: "staging" })).toBe(true);
configMock.nodeEnv = "development";
expect(shouldSeedShkRoles({})).toBe(true);
});
it("lets SEED_SHK_ROLES override in both directions", () => {
configMock.nodeEnv = "production";
expect(shouldSeedShkRoles({ SEED_SHK_ROLES: "true" })).toBe(true);
configMock.nodeEnv = "test";
expect(shouldSeedShkRoles({ SEED_SHK_ROLES: "false" })).toBe(false);
});
it("makes seedShkRolesForTenant a no-op on production", async () => {
configMock.nodeEnv = "production";
const result = await seedShkRolesForTenant("t1");
expect(result).toEqual({ createdRoles: 0 });
expect(dbMock.permission.findMany).not.toHaveBeenCalled();
expect(dbMock.role.create).not.toHaveBeenCalled();
});
});
describe("seedShkRolesForTenant", () => {
it("creates the missing roles as tenant-scoped app roles and links resolvable permissions", async () => {
dbMock.permission.findMany.mockResolvedValue([{ id: "perm_dash", name: "app.dashboard.view" }]);
dbMock.role.findFirst.mockResolvedValue(null);
dbMock.role.create.mockImplementation(async ({ data }: { data: { name: string } }) => ({ id: `role_${data.name}` }));
dbMock.rolePermission.findFirst.mockResolvedValue(null);
dbMock.rolePermission.create.mockResolvedValue({});
const result = await seedShkRolesForTenant("t1");
expect(result.createdRoles).toBe(6);
expect(dbMock.role.create).toHaveBeenCalledTimes(6);
expect(dbMock.role.create).toHaveBeenCalledWith(
expect.objectContaining({ data: expect.objectContaining({ tenantId: "t1", name: "Geschäftsführer", type: "app", assignToNewUsers: false }) })
);
// Nur die aufloesbare Permission (dashboard) wird verknuepft.
expect(dbMock.rolePermission.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ permissionId: "perm_dash" }) }));
});
it("is idempotent: existing roles are not recreated", async () => {
dbMock.permission.findMany.mockResolvedValue([]);
dbMock.role.findFirst.mockResolvedValue({ id: "existing" });
const result = await seedShkRolesForTenant("t1");
expect(result.createdRoles).toBe(0);
expect(dbMock.role.create).not.toHaveBeenCalled();
});
});
@@ -1,128 +0,0 @@
import { loadWebConfig } from "@hivegrid/config";
import { db } from "~/utils/db.server";
// R-P2b — SHK-Standard-Rollen (vom Partner genannt). PROVISORISCH/ANPASSBAR: datengetrieben, per
// Tenant als Template geseedet (upsert, idempotent). Die fachspezifischen Rechte (CRM/Leads/Projekte/
// Auftraege) haengen sich PRO PHASE an, sobald die Entitaeten existieren; bei P2 differenzieren nur die
// bereits vorhandenen App-/Settings-Rechte. Anpassbar ueber den Rollen-Editor (D-P2) oder durch Aendern
// dieser Definition + Re-Seed. Bulk-entfernbar ueber SHK_ROLE_NAMES (is_demo_data-Konvention, bis das
// Entity-Model TenantRole.is_template_origin angeglichen ist).
export type ShkRoleTier = "admin" | "elevated" | "standard";
export interface ShkRoleSeed {
readonly name: string;
// i18n-Key im Namespace-Format `settings:<key>` (Doppelpunkt!), gespeichert in Role.description;
// der Rollen-Editor löst ihn via t() auf (roleDisplayDescription). i18next adressiert ausgelagerte
// Namespaces mit ":" -- ein Punkt-Präfix landet im defaultNS und erschiene als nackter Key. Kein
// Klartext im Seed -> erfüllt die Hardcoded-String-Disziplin; Text liegt in settings.json.
readonly descriptionKey: string;
readonly tier: ShkRoleTier;
readonly permissionKeys: readonly string[];
}
const DASHBOARD = "app.dashboard.view";
export const SHK_ROLE_SEEDS: readonly ShkRoleSeed[] = [
{
name: "Geschäftsführer",
descriptionKey: "settings:shkRoles.geschaeftsfuehrer.description",
tier: "admin",
permissionKeys: [
DASHBOARD,
"app.settings.members.view",
"app.settings.members.create",
"app.settings.members.update",
"app.settings.members.delete",
"app.settings.roles.view",
"app.settings.roles.set",
"app.settings.groups.full",
"app.settings.account.view",
"app.settings.account.update",
"app.settings.subscription.view",
"app.settings.subscription.update",
"app.settings.subscription.invoices.view",
"app.settings.auditTrails.view",
],
},
{
name: "Projektleiter",
descriptionKey: "settings:shkRoles.projektleiter.description",
tier: "elevated",
permissionKeys: [DASHBOARD, "app.settings.members.view", "app.settings.groups.full", "app.settings.auditTrails.view"],
},
{
name: "Verwaltung",
descriptionKey: "settings:shkRoles.verwaltung.description",
tier: "elevated",
permissionKeys: [DASHBOARD, "app.settings.members.view", "app.settings.account.view", "app.settings.subscription.invoices.view"],
},
{
name: "Vertriebler",
descriptionKey: "settings:shkRoles.vertriebler.description",
tier: "standard",
permissionKeys: [DASHBOARD],
},
{
name: "Kundensupporter",
descriptionKey: "settings:shkRoles.kundensupporter.description",
tier: "standard",
permissionKeys: [DASHBOARD],
},
{
name: "Monteur",
descriptionKey: "settings:shkRoles.monteur.description",
tier: "standard",
permissionKeys: [DASHBOARD],
},
];
export const SHK_ROLE_NAMES: readonly string[] = SHK_ROLE_SEEDS.map((role) => role.name);
// Product decision 2026-07-07 (Akeshan, resolving the R-P2b seed-vs-design conflict): on PRODUCTION a
// fresh tenant starts with the admin system role only (David's validated D-P2 decision); the 6 SHK seed
// roles stay a staging/dev testing convenience. SEED_SHK_ROLES=true|false overrides either way in case
// the partner wants the seeds in production after all. Environment detection: NODE_ENV is "production"
// on staging containers too, so the deploy-scoped SENTRY_ENVIRONMENT (staging|production, estate
// standard §1) decides first and nodeEnv only covers local dev/test.
export function shouldSeedShkRoles(env: Record<string, string | undefined> = process.env): boolean {
if (env.SEED_SHK_ROLES === "true") return true;
if (env.SEED_SHK_ROLES === "false") return false;
const environment = env.SENTRY_ENVIRONMENT ?? loadWebConfig().config.nodeEnv;
return environment !== "production";
}
// Seedt die SHK-Rollen als App-Rollen eines Tenants (idempotent). Setzt fehlende Rollen + ihre
// vorhandenen Permission-Verknuepfungen auf; bestehende bleiben unberuehrt (anpassbar im Editor).
// Auf Produktion no-op (s. shouldSeedShkRoles) — dort startet ein Tenant nur mit der Admin-Systemrolle.
export async function seedShkRolesForTenant(tenantId: string): Promise<{ createdRoles: number }> {
if (!shouldSeedShkRoles()) {
return { createdRoles: 0 };
}
const wantedKeys = [...new Set(SHK_ROLE_SEEDS.flatMap((role) => role.permissionKeys))];
const permissions = await db.permission.findMany({ where: { name: { in: wantedKeys } }, select: { id: true, name: true } });
const permissionIdByName = new Map(permissions.map((permission) => [permission.name, permission.id]));
let createdRoles = 0;
for (const [index, seed] of SHK_ROLE_SEEDS.entries()) {
let role = await db.role.findFirst({ where: { tenantId, name: seed.name, type: "app" }, select: { id: true } });
if (!role) {
role = await db.role.create({
data: { tenantId, name: seed.name, description: seed.descriptionKey, type: "app", assignToNewUsers: false, isDefault: false, order: 100 + index },
select: { id: true },
});
createdRoles++;
}
for (const key of seed.permissionKeys) {
const permissionId = permissionIdByName.get(key);
if (!permissionId) {
continue;
}
const existing = await db.rolePermission.findFirst({ where: { roleId: role.id, permissionId } });
if (!existing) {
await db.rolePermission.create({ data: { roleId: role.id, permissionId } });
}
}
}
return { createdRoles };
}
@@ -0,0 +1,70 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import EventsService from "~/modules/events/services/.server/EventsService";
import { deleteTenant } from "../db/tenants.db.server";
import { getTenantSubscription } from "../db/tenantSubscriptions.db.server";
import { cancelTenantSubscription } from "./.server/subscriptionService";
import { deleteAndCancelTenant } from "./tenantService";
vi.mock("../db.server", () => ({ db: {} }));
vi.mock("../db/tenants.db.server", () => ({ deleteTenant: vi.fn() }));
vi.mock("../db/tenantSubscriptions.db.server", () => ({ getTenantSubscription: vi.fn() }));
vi.mock("./.server/subscriptionService", () => ({ cancelTenantSubscription: vi.fn() }));
vi.mock("~/modules/events/services/.server/EventsService", () => ({
default: { createTenantEventBeforeMutation: vi.fn(async (_args, mutation) => mutation()) },
}));
const eventData = {
tenant: { id: "tenant-1", name: "Acme" },
user: { id: "user-1", email: "user-1@example.test" },
};
describe("deleteAndCancelTenant", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getTenantSubscription).mockResolvedValue({ products: [] } as never);
vi.mocked(cancelTenantSubscription).mockResolvedValue(undefined as never);
vi.mocked(deleteTenant).mockResolvedValue({ id: "tenant-1", name: "Acme" } as never);
});
it("records the tenant event and deletion through one atomic event transaction", async () => {
await deleteAndCancelTenant({
tenantId: "tenant-1",
userId: "user-1",
request: new Request("https://app.example.test/acme/settings/account"),
eventData,
});
expect(EventsService.createTenantEventBeforeMutation).toHaveBeenCalledWith(
expect.objectContaining({
event: "account.deleted",
tenantId: "tenant-1",
userId: "user-1",
data: eventData,
}),
expect.any(Function)
);
expect(deleteTenant).toHaveBeenCalledWith("tenant-1");
});
it("does not record or delete when provider cancellation fails", async () => {
vi.mocked(getTenantSubscription).mockResolvedValue({ products: [{ id: "product-1" }] } as never);
vi.mocked(cancelTenantSubscription).mockRejectedValueOnce(new Error("provider cancellation failed"));
await expect(deleteAndCancelTenant({ tenantId: "tenant-1", userId: "user-1", eventData })).rejects.toThrow("provider cancellation failed");
expect(EventsService.createTenantEventBeforeMutation).not.toHaveBeenCalled();
expect(deleteTenant).not.toHaveBeenCalled();
});
it("re-checks ownership inside the deletion transaction", async () => {
const authorizeDeletion = vi.fn(async () => false);
await expect(deleteAndCancelTenant({ tenantId: "tenant-1", userId: "user-1", eventData, authorizeDeletion })).rejects.toThrow(
"ownership changed before commit"
);
expect(authorizeDeletion).toHaveBeenCalledTimes(1);
expect(deleteTenant).not.toHaveBeenCalled();
});
});
@@ -5,6 +5,8 @@ import { deleteTenant } from "../db/tenants.db.server";
import { getTenantSubscription } from "../db/tenantSubscriptions.db.server";
import { TFunction } from "i18next";
import { cancelTenantSubscription } from "./.server/subscriptionService";
import EventsService from "~/modules/events/services/.server/EventsService";
import type { AccountDeletedDto } from "~/modules/events/dtos/AccountDeletedDto";
export function normalizeTenantSlug(slug: string) {
return UrlUtils.slugify(slug).toLowerCase();
@@ -53,9 +55,37 @@ export function validateDesiredTenantSlug(input: string): TenantSlugValidation {
return { ok: true, slug };
}
export async function deleteAndCancelTenant({ tenantId, userId, t }: { tenantId: string; userId: string; t?: TFunction }) {
export async function deleteAndCancelTenant({
tenantId,
userId,
request,
eventData,
authorizeDeletion,
t,
}: {
tenantId: string;
userId: string;
request?: Request;
eventData: AccountDeletedDto;
authorizeDeletion?: () => Promise<boolean>;
t?: TFunction;
}) {
await cancelAllTenantPlans({ t, tenantId, userId });
return await deleteTenant(tenantId);
return EventsService.createTenantEventBeforeMutation(
{
request,
event: "account.deleted",
tenantId,
userId,
data: eventData,
},
async () => {
if (authorizeDeletion && !(await authorizeDeletion())) {
throw new Error("Tenant deletion ownership changed before commit");
}
return deleteTenant(tenantId);
}
);
}
export async function cancelAllTenantPlans({ tenantId, userId, t }: { tenantId: string; userId: string; t?: TFunction }) {
@@ -16,7 +16,6 @@ const tenantUserSearchInclude = {
firstName: true,
lastName: true,
active: true,
admin: { select: { userId: true } },
logs: {
where: { action: "Login" },
orderBy: { createdAt: "desc" },
@@ -0,0 +1,112 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
const transaction = vi.hoisted(() => ({
role: { findMany: vi.fn() },
userRole: { findMany: vi.fn(), deleteMany: vi.fn(), createMany: vi.fn() },
}));
const dbMock = vi.hoisted(() => ({
$transaction: vi.fn(async (callback: (client: typeof transaction) => Promise<unknown>) => callback(transaction)),
}));
const invalidatePermissionScopesMock = vi.hoisted(() => vi.fn());
const invalidateSnapshotMock = vi.hoisted(() => vi.fn());
vi.mock("../db.server", () => ({ db: dbMock }));
vi.mock("../db/users.db.server", () => ({ deleteUser: vi.fn() }));
vi.mock("../db/permissions/permission-cache.server", () => ({
invalidateUserPermissionCacheScopes: invalidatePermissionScopesMock,
}));
vi.mock("../db/user-snapshot-cache.server", () => ({ invalidateUserSnapshot: invalidateSnapshotMock }));
vi.mock("./tenantService", () => ({ deleteAndCancelTenant: vi.fn() }));
vi.mock("~/modules/events/services/.server/EventsService", () => ({ default: {} }));
import { setUserRoles } from "./userService";
const user = {
id: "user_1",
email: "member@example.test",
firstName: "Ada",
lastName: "Member",
avatar: null,
phone: null,
defaultTenantId: null,
createdAt: new Date("2026-07-14T08:00:00.000Z"),
locale: "de",
};
const adminRole = {
id: "role_admin",
tenantId: null,
type: "admin",
name: "SuperAdmin",
};
const appRole = {
id: "role_app",
tenantId: null,
type: "app",
name: "Office",
};
describe("tenant UserRole mutation boundary", () => {
beforeEach(() => {
vi.clearAllMocks();
transaction.userRole.findMany.mockResolvedValue([]);
transaction.userRole.deleteMany.mockResolvedValue({ count: 0 });
transaction.userRole.createMany.mockResolvedValue({ count: 1 });
});
it("rejects the retired UserRole-based admin path before writing", async () => {
transaction.role.findMany.mockResolvedValue([{ id: adminRole.id, tenantId: null, type: "admin" }]);
await expect(
runWithRlsContext({ userId: "operator_1" }, () =>
setUserRoles({
user,
roles: [{ role: adminRole as never, tenantId: null }],
type: "admin",
}),
),
).rejects.toThrow("Legacy UserRole-based admin assignment is disabled");
expect(transaction.userRole.findMany).not.toHaveBeenCalled();
expect(transaction.userRole.deleteMany).not.toHaveBeenCalled();
expect(transaction.userRole.createMany).not.toHaveBeenCalled();
expect(invalidatePermissionScopesMock).not.toHaveBeenCalled();
expect(invalidateSnapshotMock).not.toHaveBeenCalled();
});
it("rejects tenant roles outside the exact active tenant context", async () => {
transaction.role.findMany.mockResolvedValue([{ id: appRole.id, tenantId: null, type: "app" }]);
await expect(
runWithRlsContext({ userId: "operator_1" }, () =>
setUserRoles({
user,
roles: [{ role: appRole as never, tenantId: "tenant_1" }],
type: "app",
}),
),
).rejects.toThrow("matching active tenant context");
expect(transaction.userRole.deleteMany).not.toHaveBeenCalled();
});
it("replaces app roles and invalidates only the bound tenant scope", async () => {
transaction.role.findMany.mockResolvedValue([{ id: appRole.id, tenantId: null, type: "app" }]);
await runWithRlsContext({ userId: "operator_1", tenantId: "tenant_1" }, () =>
setUserRoles({
user,
roles: [{ role: appRole as never, tenantId: "tenant_1" }],
type: "app",
}),
);
expect(transaction.userRole.createMany).toHaveBeenCalledWith({
data: [{ userId: user.id, roleId: appRole.id, tenantId: "tenant_1" }],
});
expect(invalidatePermissionScopesMock).toHaveBeenCalledWith([{ userId: user.id, tenantId: "tenant_1" }]);
expect(invalidateSnapshotMock).toHaveBeenCalledWith(user.id);
});
});
@@ -1,53 +1,98 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import EventsService from "~/modules/events/services/.server/EventsService";
import { deleteUserWithItsTenants } from "./userService";
import { getMyTenants, getTenantWithUsers } from "../db/tenants.db.server";
import { deleteUser } from "../db/users.db.server";
import { deleteAndCancelTenant } from "./tenantService";
vi.mock("../db.server", () => ({ db: {} }));
const dbMock = vi.hoisted(() => ({
tenant: { findMany: vi.fn() },
tenantUser: { findMany: vi.fn() },
}));
vi.mock("../db.server", () => ({ db: dbMock }));
vi.mock("../cache.server", () => ({ clearCacheKey: vi.fn() }));
vi.mock("../db/permissions/userRoles.db.server", () => ({ createUserRoles: vi.fn(), deleteAllUserRoles: vi.fn() }));
vi.mock("../db/tenants.db.server", () => ({ getMyTenants: vi.fn(), getTenantWithUsers: vi.fn() }));
vi.mock("../db/tenants.db.server", () => ({}));
vi.mock("../db/users.db.server", () => ({ deleteUser: vi.fn() }));
vi.mock("./tenantService", () => ({ deleteAndCancelTenant: vi.fn() }));
vi.mock("~/modules/events/services/.server/EventsService", () => ({
default: { createUserEventBeforeMutation: vi.fn(async (_args, mutation) => mutation()) },
}));
const actorUserId = "user_1";
const targetUser = {
id: actorUserId,
email: "user-1@example.test",
firstName: "Ada",
lastName: "Lovelace",
};
const soloTenant = { id: "tenant_solo", name: "Solo" };
const sharedTenant = { id: "tenant_shared", name: "Shared" };
function deleteInAuthenticatedContext() {
return runWithRlsContext({ userId: actorUserId, tenantId: "tenant_active" }, () =>
deleteUserWithItsTenants({ actorUserId, targetUser, request: new Request("https://app.example.test/settings/profile") })
);
}
describe("deleteUserWithItsTenants", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getMyTenants).mockResolvedValue([soloTenant, sharedTenant] as never);
vi.mocked(getTenantWithUsers).mockImplementation(async (tenantId) => {
if (tenantId === soloTenant.id) {
return { users: [{ userId: "user_1" }] } as never;
}
return { users: [{ userId: "user_1" }, { userId: "user_2" }] } as never;
dbMock.tenant.findMany.mockImplementation(async () => {
expect(getRlsExecutionContext()).toEqual({ userId: actorUserId });
return [soloTenant, sharedTenant] as never;
});
vi.mocked(deleteAndCancelTenant).mockResolvedValue(soloTenant as never);
vi.mocked(deleteUser).mockResolvedValue({ id: "user_1" } as never);
dbMock.tenantUser.findMany.mockImplementation(async () => {
const tenantId = getRlsExecutionContext()?.tenantId;
return tenantId === soloTenant.id ? [{ userId: actorUserId }] : [{ userId: actorUserId }, { userId: "user_2" }];
});
vi.mocked(deleteAndCancelTenant).mockImplementation(async ({ tenantId, authorizeDeletion }) => {
expect(getRlsExecutionContext()).toEqual({ userId: actorUserId, tenantId });
expect(await authorizeDeletion?.()).toBe(true);
return tenantId === soloTenant.id ? (soloTenant as never) : (null as never);
});
vi.mocked(deleteUser).mockResolvedValue({ id: actorUserId } as never);
});
it("cancels and deletes only tenants where the deleted user is the sole tenant user", async () => {
const result = await deleteUserWithItsTenants("user_1");
it("re-proves each tenant boundary and deletes only a sole-owned tenant", async () => {
const result = await deleteInAuthenticatedContext();
expect(dbMock.tenantUser.findMany).toHaveBeenCalledTimes(3);
expect(deleteAndCancelTenant).toHaveBeenCalledTimes(1);
expect(deleteAndCancelTenant).toHaveBeenCalledWith({ tenantId: soloTenant.id, userId: "user_1" });
expect(deleteUser).toHaveBeenCalledWith("user_1");
expect(deleteAndCancelTenant).toHaveBeenCalledWith(expect.objectContaining({ tenantId: soloTenant.id, userId: actorUserId }));
expect(deleteUser).toHaveBeenCalledWith(actorUserId);
expect(result.deletedTenants).toEqual([soloTenant]);
expect(EventsService.createUserEventBeforeMutation).toHaveBeenCalledWith(
expect.objectContaining({ event: "user.profile.deleted", userId: actorUserId }),
expect.any(Function)
);
});
it("does not delete shared tenants when another tenant user remains", async () => {
await deleteUserWithItsTenants("user_1");
it("does not trust a listed tenant when the exact-context membership proof is missing", async () => {
dbMock.tenantUser.findMany.mockResolvedValue([]);
expect(deleteAndCancelTenant).not.toHaveBeenCalledWith({ tenantId: sharedTenant.id, userId: "user_1" });
await deleteInAuthenticatedContext();
expect(deleteAndCancelTenant).not.toHaveBeenCalled();
expect(deleteUser).toHaveBeenCalledWith(actorUserId);
});
it("does not delete the user if tenant cancellation fails", async () => {
vi.mocked(deleteAndCancelTenant).mockRejectedValueOnce(new Error("billing unavailable") as never);
await expect(deleteUserWithItsTenants("user_1")).rejects.toThrow("billing unavailable");
await expect(deleteInAuthenticatedContext()).rejects.toThrow("billing unavailable");
expect(deleteUser).not.toHaveBeenCalled();
expect(EventsService.createUserEventBeforeMutation).not.toHaveBeenCalled();
});
it("rejects a caller that tries to isolate a different authenticated actor", async () => {
await expect(
runWithRlsContext({ userId: "attacker", tenantId: "tenant_active" }, () => deleteUserWithItsTenants({ actorUserId, targetUser }))
).rejects.toThrow("matching authenticated user context");
expect(dbMock.tenant.findMany).not.toHaveBeenCalled();
expect(deleteUser).not.toHaveBeenCalled();
});
});
@@ -1,32 +1,89 @@
import { Tenant, Role } from "@hivegrid/db/prisma-browser";
import { getMyTenants, getTenantWithUsers } from "../db/tenants.db.server";
import { Prisma, Tenant, Role } from "@hivegrid/db/prisma-browser";
import { UserWithoutPassword, deleteUser } from "../db/users.db.server";
import { deleteAndCancelTenant } from "./tenantService";
import { db } from "../db.server";
import { createUserRoles, deleteAllUserRoles } from "../db/permissions/userRoles.db.server";
import { clearCacheKey } from "../cache.server";
import { invalidateUserSnapshot } from "../db/user-snapshot-cache.server";
import { getRlsExecutionContext, runWithIsolatedUserRlsContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import EventsService from "~/modules/events/services/.server/EventsService";
import type { AccountDeletedDto } from "~/modules/events/dtos/AccountDeletedDto";
import type { UserProfileDeletedDto } from "~/modules/events/dtos/UserProfileDeletedDto";
import { invalidateUserPermissionCacheScopes } from "../db/permissions/permission-cache.server";
export async function deleteUserWithItsTenants(id: string) {
const userTenants = await getMyTenants(id);
const deletedAccounts = await Promise.all(
userTenants.map(async (tenant) => {
const tenantUsers = await getTenantWithUsers(tenant.id);
if (tenantUsers?.users.length === 1 && tenantUsers.users[0].userId === id) {
return await deleteAndCancelTenant({
tenantId: tenant.id,
userId: id,
});
}
type DeleteUserTarget = Pick<UserWithoutPassword, "id" | "email" | "firstName" | "lastName">;
export async function deleteUserWithItsTenants({ actorUserId, targetUser, request }: { actorUserId: string; targetUser: DeleteUserTarget; request?: Request }) {
const userTenants = await runWithIsolatedUserRlsContext(actorUserId, () =>
db.tenant.findMany({
where: { users: { some: { userId: targetUser.id } } },
select: { id: true, name: true },
orderBy: { id: "asc" },
})
);
const deletedTenants: Tenant[] = [];
deletedAccounts.forEach((deletedAccount) => {
if (deletedAccount) {
deletedTenants.push(deletedAccount);
for (const tenant of userTenants) {
const deletedTenant = await runWithIsolatedUserRlsContext(actorUserId, () =>
runWithRlsContext({ tenantId: tenant.id }, async () => {
const memberships = await db.tenantUser.findMany({
where: { tenantId: tenant.id },
select: { userId: true },
});
if (memberships.length !== 1 || memberships[0]?.userId !== targetUser.id) {
return null;
}
const eventData = {
tenant: { id: tenant.id, name: tenant.name },
user: { id: targetUser.id, email: targetUser.email },
} satisfies AccountDeletedDto;
return deleteAndCancelTenant({
tenantId: tenant.id,
userId: actorUserId,
request,
eventData,
authorizeDeletion: async () => {
const currentMemberships = await db.tenantUser.findMany({
where: { tenantId: tenant.id },
select: { userId: true },
});
return currentMemberships.length === 1 && currentMemberships[0]?.userId === targetUser.id;
},
});
})
);
if (deletedTenant) {
deletedTenants.push(deletedTenant);
}
});
}
const deletedAccounts = deletedTenants.map(
(tenant) =>
({
tenant: { id: tenant.id, name: tenant.name },
user: { id: targetUser.id, email: targetUser.email },
}) satisfies AccountDeletedDto
);
const deletedUser = await runWithIsolatedUserRlsContext(actorUserId, () =>
EventsService.createUserEventBeforeMutation(
{
request,
event: "user.profile.deleted",
userId: actorUserId,
data: {
id: targetUser.id,
email: targetUser.email,
firstName: targetUser.firstName,
lastName: targetUser.lastName,
deletedAccounts,
} satisfies UserProfileDeletedDto,
},
() => deleteUser(targetUser.id)
)
);
return {
deletedUser: await deleteUser(id),
deletedUser,
deletedTenants,
};
}
@@ -34,30 +91,77 @@ export async function deleteUserWithItsTenants(id: string) {
export async function setUserRoles({
user,
roles,
isAdmin,
type,
}: {
user: UserWithoutPassword;
roles: { role: Role; tenantId: string | null }[];
isAdmin: boolean;
type: "admin" | "app";
}) {
if (user.admin && !isAdmin) {
await db.adminUser.delete({ where: { userId: user.id } });
} else if (!user.admin && isAdmin) {
await db.adminUser.create({ data: { userId: user.id } });
const cacheScopes = await db.$transaction((transaction) =>
replaceUserRolesInTransaction(transaction, {
userId: user.id,
roles,
type,
}),
);
await invalidateUserPermissionCacheScopes(cacheScopes);
await invalidateUserSnapshot(user.id);
return { count: roles.length };
}
async function replaceUserRolesInTransaction(
transaction: Prisma.TransactionClient,
{
userId,
roles,
type,
}: {
userId: string;
roles: { role: Role; tenantId: string | null }[];
type: "admin" | "app";
},
): Promise<{ userId: string; tenantId: string | null }[]> {
const roleIds = [...new Set(roles.map(({ role }) => role.id))];
if (roleIds.length !== roles.length) {
throw new Error("Duplicate role assignments are not allowed");
}
const persistedRoles = await transaction.role.findMany({
where: { id: { in: roleIds } },
select: { id: true, tenantId: true, type: true },
});
if (persistedRoles.length !== roleIds.length) {
throw new Error("One or more role assignments no longer exist");
}
await deleteAllUserRoles(user.id, type);
return await createUserRoles(
user.id,
roles.map(({ role, tenantId }) => ({
id: role.id,
tenantId,
}))
).then((item) => {
clearCacheKey(`user:${user.id}`);
clearCacheKey(`userRoles:${user.id}:${null}`);
return item;
const currentTenantId = getRlsExecutionContext()?.tenantId ?? null;
if (type === "admin") {
throw new Error("Legacy UserRole-based admin assignment is disabled; use AdminUserRole");
}
const persistedById = new Map(persistedRoles.map((role) => [role.id, role]));
for (const assignment of roles) {
const persisted = persistedById.get(assignment.role.id);
if (!persisted || persisted.type !== type) {
throw new Error("Role assignment type does not match the requested scope");
}
if (!currentTenantId || assignment.tenantId !== currentTenantId || (persisted.tenantId !== null && persisted.tenantId !== currentTenantId)) {
throw new Error("Tenant role assignments require the matching active tenant context");
}
}
const previousAssignments = await transaction.userRole.findMany({
where: { userId, role: { type } },
select: { tenantId: true },
});
await transaction.userRole.deleteMany({
where: { userId, role: { type } },
});
if (roles.length > 0) {
await transaction.userRole.createMany({
data: roles.map(({ role, tenantId }) => ({ userId, roleId: role.id, tenantId })),
});
}
return [...new Set([...previousAssignments.map(({ tenantId }) => tenantId), ...roles.map(({ tenantId }) => tenantId)])].map((tenantId) => ({
userId,
tenantId,
}));
}