import { createHash } from "node:crypto"; import type { Tenant, User } from "@hivegrid/db/prisma-browser"; import { CatalogError, foundationErrors } from "@hivegrid/foundation"; import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { TenantUserType } from "~/application/enums/tenants/TenantUserType"; import type { TenantRlsClient } from "~/utils/db/.server/tenantRls.server"; import { SHK_V2_TENANT_BOOTSTRAP_CONFIG, SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST } from "./shk-v2.config"; import { SHK_FIRST_STEPS, SHK_FIRST_STEPS_CHECKLIST_CODE, SHK_FIRST_STEPS_CHECKLIST_ID, TENANT_PENDING_OWNER_REASON, } from "./tenantBootstrap.constants"; const dependencyMocks = vi.hoisted(() => ({ hashPassword: vi.fn(), verifyPassword: vi.fn(), createTenant: vi.fn(), emitTenantCreatedHook: vi.fn(), dbTransaction: vi.fn(), dbUserFindUnique: vi.fn(), invalidateUserSnapshot: vi.fn(), publishTenantInvalidation: vi.fn(), emitUserCreatedHook: vi.fn(), seedForms: vi.fn(), prepareForms: vi.fn(), seedCustomFields: vi.fn(), seedAcceptance: vi.fn(), seedProject: vi.fn(), getWorkspaceInviteByToken: vi.fn(), acceptWorkspaceInvite: vi.fn(), hashWorkspaceInviteToken: vi.fn(() => "a".repeat(64)), resolveUserEmailRlsIdentity: vi.fn(), findRegistrationBillingPreferenceCapability: vi.fn(), issueReservedOwnerInvitationWithTx: vi.fn(), })); vi.mock("~/utils/auth/passwordHasher.server", () => ({ hashPassword: dependencyMocks.hashPassword, verifyPassword: dependencyMocks.verifyPassword, })); vi.mock("~/utils/db/tenants.db.server", () => ({ createTenant: dependencyMocks.createTenant, emitTenantCreatedHook: dependencyMocks.emitTenantCreatedHook, })); vi.mock("~/utils/db.server", () => ({ db: { $transaction: dependencyMocks.dbTransaction, user: { findUnique: dependencyMocks.dbUserFindUnique }, }, })); vi.mock("~/utils/db/user-snapshot-cache.server", () => ({ invalidateUserSnapshot: dependencyMocks.invalidateUserSnapshot })); vi.mock("~/utils/db/tenant-cache.server", () => ({ publishTenantInvalidation: dependencyMocks.publishTenantInvalidation })); vi.mock("~/utils/db/users.db.server", () => ({ emitUserCreatedHook: dependencyMocks.emitUserCreatedHook })); vi.mock("~/modules/forms/services/shkFormTemplates.server", () => ({ prepareShkFormTemplates: dependencyMocks.prepareForms, seedShkFormTemplatesWithTx: dependencyMocks.seedForms, })); vi.mock("~/utils/integrations/crm/customFieldService.server", () => ({ seedShkCustomFieldTemplateWithTx: dependencyMocks.seedCustomFields, })); vi.mock("~/utils/integrations/projects/auftragService.server", () => ({ ensureDefaultAcceptanceFormTemplateWithTx: dependencyMocks.seedAcceptance, ensureDefaultProjectTemplateWithTx: dependencyMocks.seedProject, })); vi.mock("@hivegrid/db/workspace-invites.server", () => ({ getWorkspaceInviteByToken: dependencyMocks.getWorkspaceInviteByToken, acceptWorkspaceInvite: dependencyMocks.acceptWorkspaceInvite, hashWorkspaceInviteToken: dependencyMocks.hashWorkspaceInviteToken, WorkspaceInviteError: class WorkspaceInviteError extends Error {}, })); vi.mock("@hivegrid/db/rls-resolvers.server", () => ({ resolveUserEmailRlsIdentity: dependencyMocks.resolveUserEmailRlsIdentity, })); vi.mock("@hivegrid/db/pretenant-security.server", () => ({ findRegistrationBillingPreferenceCapability: dependencyMocks.findRegistrationBillingPreferenceCapability, })); vi.mock("./ownerInvitationIssuance.server", () => ({ issueReservedOwnerInvitationWithTx: dependencyMocks.issueReservedOwnerInvitationWithTx, })); import { bootstrapShkV2TenantWithTx, claimReservedTenantWithShkDefaults, createOwnedTenantWithShkDefaults, createSignupTenantWithShkDefaults, deriveSignupTenantId, deriveSignupUserId, deriveTenantCreationId, deriveTenantReservationId, isExactOwnedTenantCreationReplay, reserveTenantWithoutOwner, SHK_V2_BOOTSTRAP_SCOPE, } from "./tenantBootstrapService.server"; const FIXED_NOW = new Date("2026-07-15T10:00:00.000Z"); const CREATION_REQUEST_KEY = "d7077797-054b-497a-b1ce-8e4f36257a96"; const OWNER_INVITATION_DRAFT = { issuanceKey: "41adac34-7b0d-47f0-9bb5-74dd67104dcb", email: "owner@heizkraft.example", firstName: "Mara", lastName: "König", fromUserId: "operator_1", token: "o".repeat(43), mail: { subject: "Einladung", html: `https://app.example.test/invitation/${"o".repeat(43)}` }, }; const translate = (key: string) => `translated:${key}`; const preparedFormTemplates = []; function tenantRow(overrides: Partial = {}): Tenant { return { id: "tenant_1", createdAt: FIXED_NOW, updatedAt: FIXED_NOW, slug: "heizkraft", name: "Heizkraft GmbH", icon: null, logo: null, subscriptionId: null, active: false, deactivatedReason: TENANT_PENDING_OWNER_REASON, theme: null, themeConfig: null, anrede: "du", ...overrides, }; } function userRow(overrides: Partial = {}): User { return { id: "user_1", createdAt: FIXED_NOW, updatedAt: FIXED_NOW, email: "owner@heizkraft.example", passwordHash: "hash", firstName: "Mara", lastName: "König", avatar: "", phone: "", defaultTenantId: "tenant_1", verifyToken: null, verifyTokenCreatedAt: null, locale: "de", lightOrDarkMode: null, totpSecretEncrypted: null, totpPendingSecretEncrypted: null, totpEnabledAt: null, totpPendingCreatedAt: null, mfaRecoveryCodeHashes: null, mfaRecoveryCodesGeneratedAt: null, mfaRecoveryCodeLastUsedAt: null, active: false, pendingDeletion: false, scheduledDeletionAt: null, deletionRequestedAt: null, pseudonymized: false, pseudonymizedAt: null, deletionRequestId: null, ...overrides, }; } type FakeTx = ReturnType; function buildFakeTx(markerOverrides: Record = {}, storedMarker: Record | null = null) { const calls: string[] = []; const record = (name: string, value: T) => { calls.push(name); return Promise.resolve(value); }; const permissionKeys = [...new Set(SHK_V2_TENANT_BOOTSTRAP_CONFIG.tenantRoles.flatMap((role) => role.permissionKeys))]; const tenantRoles = SHK_V2_TENANT_BOOTSTRAP_CONFIG.tenantRoles.map((role, index) => ({ id: `role_${index}`, name: role.name })); const pipelines = SHK_V2_TENANT_BOOTSTRAP_CONFIG.salesPipelines.map((pipeline, index) => ({ id: `pipeline_${index}`, name: pipeline.name })); const onboardingSteps = SHK_FIRST_STEPS.map((step) => ({ ...step })); const tx = { calls, $queryRaw: vi.fn(() => record("user.lock", [userRow({ active: true })])), idempotencyKey: { upsert: vi.fn((args: { create: Record }) => record("marker.acquire", { ...args.create, ...markerOverrides })), findUnique: vi.fn(() => record("marker.find", storedMarker)), update: vi.fn(() => record("marker.complete", {})), }, role: { findMany: vi.fn(() => record("role.admin.find", [{ id: "role_admin" }])), createManyAndReturn: vi.fn(() => record("role.tenant.createManyAndReturn", tenantRoles)), }, tenantUser: { upsert: vi.fn(() => record("membership.upsert", {})), findFirst: vi.fn(() => record("membership.findOwner", { id: "membership_1" })), findMany: vi.fn(() => record("membership.findExisting", [])), }, tenantUserInvitation: { updateMany: vi.fn(() => record("invitation.bindCreatedUser", { count: 1 })), }, user: { create: vi.fn(() => record("user.create", userRow())), update: vi.fn((args: { data: { active?: boolean; defaultTenantId?: string } }) => record( args.data.active ? "user.activate" : "user.defaultTenant", userRow({ active: args.data.active ?? true, defaultTenantId: args.data.defaultTenantId ?? "tenant_1" }) ) ), findUnique: vi.fn(() => record("user.find", userRow())), findMany: vi.fn(() => record("user.findMatches", [userRow()])), }, userRole: { deleteMany: vi.fn(() => record("userRole.prune", { count: 0 })), createMany: vi.fn(() => record("userRole.admin", { count: 1 })), }, tenantType: { findMany: vi.fn(() => record("tenantType.findMany", [])) }, permission: { findMany: vi.fn(() => record( "permission.findMany", permissionKeys.map((name, index) => ({ id: `permission_${index}`, name })) ) ), }, rolePermission: { createMany: vi.fn(() => record("rolePermission.createMany", { count: permissionKeys.length })) }, pipeline: { createManyAndReturn: vi.fn(() => record("pipeline.createManyAndReturn", pipelines)), }, pipelineStage: { createMany: vi.fn(() => record("pipelineStage.createMany", { count: 15 })) }, lostReason: { createMany: vi.fn(() => record("lostReason.createMany", { count: 5 })) }, onboarding: { findUnique: vi.fn(() => record("onboarding.find", { id: SHK_FIRST_STEPS_CHECKLIST_ID, title: SHK_FIRST_STEPS_CHECKLIST_CODE, type: "page", realtime: false, active: true, canBeDismissed: true, height: null, steps: onboardingSteps, }) ), }, onboardingSession: { upsert: vi.fn(() => record("onboardingSession.upsert", { id: "session_1" })) }, onboardingSessionStep: { createMany: vi.fn(() => record("onboardingSessionStep.createMany", { count: 4 })) }, automationTemplate: { createMany: vi.fn(() => record("automationTemplate.createMany", { count: 3 })) }, portal: { upsert: vi.fn(() => record("portal.scaffold", { id: "portal_1" })) }, tenantProductConfiguration: { upsert: vi.fn((args: { create: Record }) => record("billingPreference.upsert", args.create)), findUnique: vi.fn(() => record("billingPreference.find", { signupSubscriptionPriceId: "price_swarm_monthly", signupOfficeSeatQuantity: 5, signupFieldSeatQuantity: 15, }) ), }, tenant: { findUnique: vi.fn(() => record("tenant.find", tenantRow())), findUniqueOrThrow: vi.fn(() => record("tenant.findFinal", tenantRow({ active: true, deactivatedReason: null }))), update: vi.fn((args: { data: { active?: boolean } }) => record(args.data.active ? "tenant.activate" : "tenant.update", tenantRow({ active: Boolean(args.data.active), deactivatedReason: null })) ), }, }; return tx; } function asTenantTx(fake: FakeTx): TenantRlsClient { return fake as unknown as TenantRlsClient; } beforeEach(() => { vi.clearAllMocks(); dependencyMocks.hashPassword.mockResolvedValue("prepared_hash"); dependencyMocks.verifyPassword.mockResolvedValue({ valid: true }); dependencyMocks.dbUserFindUnique.mockResolvedValue({ passwordHash: "hash" }); dependencyMocks.emitUserCreatedHook.mockResolvedValue(undefined); dependencyMocks.emitTenantCreatedHook.mockResolvedValue(undefined); dependencyMocks.invalidateUserSnapshot.mockResolvedValue(undefined); dependencyMocks.publishTenantInvalidation.mockResolvedValue(undefined); dependencyMocks.seedForms.mockImplementation((_tx: unknown, _input: unknown) => Promise.resolve({ upserted: 2 })); dependencyMocks.prepareForms.mockReturnValue(preparedFormTemplates); dependencyMocks.seedCustomFields.mockImplementation((_tx: unknown, _input: unknown) => Promise.resolve({ created: 0 })); dependencyMocks.seedAcceptance.mockImplementation((_tx: unknown, _tenantId: string) => Promise.resolve({ id: "acceptance_1" })); dependencyMocks.seedProject.mockImplementation((_tx: unknown, _tenantId: string) => Promise.resolve({ id: "project_template_1" })); dependencyMocks.getWorkspaceInviteByToken.mockResolvedValue({ id: "invite_1", tenantId: "tenant_1", email: "owner@heizkraft.example", firstName: "Mara", lastName: "König", type: TenantUserType.OWNER, status: "pending", createdUserId: null, acceptedByUserId: null, }); dependencyMocks.acceptWorkspaceInvite.mockResolvedValue({ id: "invite_1", tenantId: "tenant_1", email: "owner@heizkraft.example", type: TenantUserType.OWNER, status: "accepted", acceptedByUserId: "user_1", }); dependencyMocks.resolveUserEmailRlsIdentity.mockImplementation(async (_email: string, client?: unknown) => client ? { resourceId: "user_1", userId: "user_1" } : null ); dependencyMocks.findRegistrationBillingPreferenceCapability.mockResolvedValue(null); dependencyMocks.issueReservedOwnerInvitationWithTx.mockResolvedValue({ invitationId: "invite_owner", replayed: false }); }); describe("bootstrapShkV2TenantWithTx", () => { it("batches the configured defaults and activates the tenant as the final write", async () => { const fake = buildFakeTx(); await expect( bootstrapShkV2TenantWithTx(asTenantTx(fake), { tenantId: "tenant_1", tenantName: "Heizkraft GmbH", tenantSlug: "heizkraft", userId: "user_1", attemptId: "attempt_1", t: translate, now: FIXED_NOW, configDigest: SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST, preparedFormTemplates, }) ).resolves.toEqual({ replayed: false, tenant: tenantRow({ active: true, deactivatedReason: null }) }); expect(fake.role.createManyAndReturn).toHaveBeenCalledWith(expect.objectContaining({ skipDuplicates: true })); expect(fake.role.createManyAndReturn.mock.calls[0]?.[0].data).toHaveLength(5); expect(fake.userRole.createMany).toHaveBeenCalledWith({ data: [{ tenantId: "tenant_1", userId: "user_1", roleId: "role_admin" }], skipDuplicates: true, }); expect(fake.pipeline.createManyAndReturn.mock.calls[0]?.[0].data).toHaveLength(3); expect(fake.pipelineStage.createMany.mock.calls[0]?.[0].data).toHaveLength(15); expect(fake.lostReason.createMany.mock.calls[0]?.[0].data).toHaveLength(5); expect(fake.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(fake.onboardingSessionStep.createMany).toHaveBeenCalledWith({ data: SHK_FIRST_STEPS.map((step) => ({ onboardingSessionId: "session_1", stepId: step.id })), skipDuplicates: true, }); expect(fake.automationTemplate.createMany).toHaveBeenCalledWith( expect.objectContaining({ data: expect.arrayContaining([ expect.objectContaining({ name: "shk.order-thank-you.v1", isPublished: false, flowData: expect.objectContaining({ nodes: [] }) }), expect.objectContaining({ name: "shk.kwp-project-routing.v1", isPublished: false, flowData: expect.objectContaining({ nodes: [] }) }), expect.objectContaining({ name: "shk.follow-up-reminder.v1", isPublished: false, flowData: expect.objectContaining({ nodes: [] }) }), ]), }) ); expect(fake.portal.upsert).toHaveBeenCalledWith({ where: { tenantId: "tenant_1" }, create: { tenantId: "tenant_1", createdByUserId: "user_1", subdomain: "heizkraft", title: "Heizkraft GmbH", isPublished: false, metadata: { provisioningSource: "tenant_bootstrap_v1" }, }, update: {}, select: { id: true }, }); expect(fake.calls.indexOf("portal.scaffold")).toBeLessThan(fake.calls.indexOf("marker.complete")); expect(fake.calls.at(-2)).toBe("marker.complete"); expect(fake.calls.at(-1)).toBe("tenant.activate"); expect(fake.calls.length).toBeLessThanOrEqual(26); }); it("returns a completed marker without mutating an existing tenant", async () => { const fake = buildFakeTx({ responseStatus: 201, responseBody: { state: "completed", completedAt: FIXED_NOW.toISOString() } }); await expect( bootstrapShkV2TenantWithTx(asTenantTx(fake), { tenantId: "tenant_1", tenantName: "Heizkraft GmbH", tenantSlug: "heizkraft", userId: "user_1", attemptId: "attempt_2", t: translate, configDigest: SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST, preparedFormTemplates, }) ).resolves.toEqual({ replayed: true }); expect(fake.calls).toEqual(["marker.acquire"]); expect(fake.tenant.update).not.toHaveBeenCalled(); }); it("fails closed when a completed tenant has another config digest", async () => { const fake = buildFakeTx({ requestHash: "different", responseStatus: 201 }); await expect( bootstrapShkV2TenantWithTx(asTenantTx(fake), { tenantId: "tenant_1", tenantName: "Heizkraft GmbH", tenantSlug: "heizkraft", userId: "user_1", attemptId: "attempt_1", t: translate, configDigest: SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST, preparedFormTemplates, }) ).rejects.toMatchObject({ code: foundationErrors.idempotencyConflict.code }); expect(fake.tenant.update).not.toHaveBeenCalled(); }); it("never completes the marker or activates when a default fails", async () => { const fake = buildFakeTx(); dependencyMocks.seedForms.mockRejectedValueOnce(new Error("form-default-failed")); await expect( bootstrapShkV2TenantWithTx(asTenantTx(fake), { tenantId: "tenant_1", tenantName: "Heizkraft GmbH", tenantSlug: "heizkraft", userId: "user_1", attemptId: "attempt_1", t: translate, configDigest: SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST, preparedFormTemplates, }) ).rejects.toThrow("form-default-failed"); expect(fake.idempotencyKey.update).not.toHaveBeenCalled(); expect(fake.tenant.update).not.toHaveBeenCalled(); }); it("never completes the marker or activates when the portal scaffold cannot be created", async () => { const fake = buildFakeTx(); fake.portal.upsert.mockRejectedValueOnce(new Error("portal-subdomain-conflict")); await expect( bootstrapShkV2TenantWithTx(asTenantTx(fake), { tenantId: "tenant_1", tenantName: "Heizkraft GmbH", tenantSlug: "heizkraft", userId: "user_1", attemptId: "attempt_1", t: translate, configDigest: SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST, preparedFormTemplates, }) ).rejects.toThrow("portal-subdomain-conflict"); expect(fake.idempotencyKey.update).not.toHaveBeenCalled(); expect(fake.tenant.update).not.toHaveBeenCalled(); }); it("never completes the marker or activates when the signup billing preference cannot be persisted", async () => { const fake = buildFakeTx(); fake.tenantProductConfiguration.upsert.mockRejectedValueOnce(new Error("preference-write-failed")); await expect( bootstrapShkV2TenantWithTx(asTenantTx(fake), { tenantId: "tenant_1", tenantName: "Heizkraft GmbH", tenantSlug: "heizkraft", userId: "user_1", attemptId: "attempt_1", t: translate, configDigest: SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST, preparedFormTemplates, billingPreference: { selectedSubscriptionPriceId: "price_swarm_monthly", selectedOfficeSeatQuantity: 5, selectedFieldSeatQuantity: 15, }, }) ).rejects.toThrow("preference-write-failed"); expect(fake.idempotencyKey.update).not.toHaveBeenCalled(); expect(fake.tenant.update).not.toHaveBeenCalled(); }); it("fails closed when the global checklist does not have the exact canonical step identities", async () => { const fake = buildFakeTx(); fake.onboarding.findUnique.mockResolvedValueOnce({ 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, index) => (index === 0 ? { ...step, id: "generated-duplicate-step" } : { ...step })), }); await expect( bootstrapShkV2TenantWithTx(asTenantTx(fake), { tenantId: "tenant_1", tenantName: "Heizkraft GmbH", tenantSlug: "heizkraft", userId: "user_1", attemptId: "attempt_1", t: translate, configDigest: SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST, preparedFormTemplates, }) ).rejects.toMatchObject({ code: foundationErrors.notFound.code }); expect(fake.onboardingSession.upsert).not.toHaveBeenCalled(); expect(fake.idempotencyKey.update).not.toHaveBeenCalled(); expect(fake.tenant.update).not.toHaveBeenCalled(); }); it.each([ ["type", "modal"], ["realtime", true], ["canBeDismissed", false], ["height", "md"], ] as const)("fails closed when the global checklist %s drifts", async (field, value) => { const fake = buildFakeTx(); fake.onboarding.findUnique.mockResolvedValueOnce({ 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 })), [field]: value, }); await expect( bootstrapShkV2TenantWithTx(asTenantTx(fake), { tenantId: "tenant_1", tenantName: "Heizkraft GmbH", tenantSlug: "heizkraft", userId: "user_1", attemptId: "attempt_1", t: translate, configDigest: SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST, preparedFormTemplates, }) ).rejects.toMatchObject({ code: foundationErrors.notFound.code }); expect(fake.onboardingSession.upsert).not.toHaveBeenCalled(); expect(fake.idempotencyKey.update).not.toHaveBeenCalled(); expect(fake.tenant.update).not.toHaveBeenCalled(); }); it("uses the permanent tenant-scoped marker contract", async () => { const fake = buildFakeTx(); await bootstrapShkV2TenantWithTx(asTenantTx(fake), { tenantId: "tenant_1", tenantName: "Heizkraft GmbH", tenantSlug: "heizkraft", userId: "user_1", attemptId: "attempt_1", t: translate, configDigest: SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST, preparedFormTemplates, }); expect(fake.idempotencyKey.upsert).toHaveBeenCalledWith( expect.objectContaining({ where: { idempotency_key_partition_scope_key: { partitionKey: "tenant:tenant_1", scope: SHK_V2_BOOTSTRAP_SCOPE, key: "shk-v2", }, }, create: expect.objectContaining({ tenantId: "tenant_1", requestHash: expect.stringMatching(/^[a-f0-9]{64}$/), }), }) ); }); }); describe("tenant bootstrap entry functions", () => { it("derives a domain-separated tenant id and replays the same completed creation request", async () => { const owner = userRow({ defaultTenantId: null }); const firstTx = buildFakeTx(); let firstTenantId = ""; dependencyMocks.createTenant.mockImplementationOnce(async (input: { tenantId: string; setup: (tenant: Tenant, tx: TenantRlsClient) => Promise }) => { firstTenantId = input.tenantId; await input.setup(tenantRow({ id: input.tenantId }), asTenantTx(firstTx)); return tenantRow({ id: input.tenantId, active: true, deactivatedReason: null }); }); const first = await runWithRlsContext({ userId: owner.id }, () => createOwnedTenantWithShkDefaults({ user: owner, name: "Heizkraft GmbH", slug: "heizkraft", creationRequestKey: CREATION_REQUEST_KEY, t: translate, }) ); expect(firstTenantId).toBe(deriveTenantCreationId(owner.id, CREATION_REQUEST_KEY)); expect(firstTenantId).not.toBe(CREATION_REQUEST_KEY); expect(firstTenantId).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); expect(first.replayed).toBe(false); expect(dependencyMocks.createTenant).toHaveBeenNthCalledWith(1, expect.objectContaining({ emitCreatedHook: false })); const completedBody = firstTx.idempotencyKey.update.mock.calls[0]?.[0].data.responseBody; expect(firstTx.idempotencyKey.upsert.mock.calls[0]?.[0].create).toMatchObject({ requestHash: SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST, responseBody: { creationRequest: { key: CREATION_REQUEST_KEY, payloadHash: expect.stringMatching(/^[a-f0-9]{64}$/), tenantName: "Heizkraft GmbH", tenantSlug: "heizkraft", }, }, }); const storedMarker = { requestHash: SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST, responseStatus: 201, responseBody: completedBody, }; const replayTx = buildFakeTx({ responseStatus: 201, responseBody: completedBody }, storedMarker); dependencyMocks.createTenant.mockImplementationOnce( async (input: { tenantId: string; validateExistingReplay: (tenant: Tenant, tx: TenantRlsClient) => Promise; setup: (tenant: Tenant, tx: TenantRlsClient) => Promise; }) => { const existing = tenantRow({ id: input.tenantId, active: true, deactivatedReason: null }); await input.validateExistingReplay(existing, asTenantTx(replayTx)); await input.setup(existing, asTenantTx(replayTx)); return existing; } ); const replay = await runWithRlsContext({ userId: owner.id }, () => createOwnedTenantWithShkDefaults({ user: owner, name: "Heizkraft GmbH", slug: "heizkraft", creationRequestKey: CREATION_REQUEST_KEY, t: translate, }) ); expect(replay).toMatchObject({ tenant: { id: firstTenantId }, replayed: true }); expect(replayTx.calls).toEqual(["membership.findOwner", "marker.find", "marker.acquire"]); expect(dependencyMocks.publishTenantInvalidation).toHaveBeenCalledTimes(2); expect(dependencyMocks.emitTenantCreatedHook).toHaveBeenCalledTimes(2); expect(dependencyMocks.emitTenantCreatedHook).toHaveBeenLastCalledWith(expect.objectContaining({ id: firstTenantId }), owner.id); }); it("fails closed for a changed creation payload or another authenticated user", async () => { const owner = userRow({ defaultTenantId: null }); const firstTx = buildFakeTx(); dependencyMocks.createTenant.mockImplementationOnce(async (input: { tenantId: string; setup: (tenant: Tenant, tx: TenantRlsClient) => Promise }) => { await input.setup(tenantRow({ id: input.tenantId }), asTenantTx(firstTx)); return tenantRow({ id: input.tenantId, active: true, deactivatedReason: null }); }); await runWithRlsContext({ userId: owner.id }, () => createOwnedTenantWithShkDefaults({ user: owner, name: "Heizkraft GmbH", slug: "heizkraft", creationRequestKey: CREATION_REQUEST_KEY, t: translate, }) ); const completedBody = firstTx.idempotencyKey.update.mock.calls[0]?.[0].data.responseBody; const replayTx = buildFakeTx({}, { requestHash: SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST, responseStatus: 201, responseBody: completedBody }); dependencyMocks.createTenant.mockImplementationOnce( async (input: { tenantId: string; validateExistingReplay: (tenant: Tenant, tx: TenantRlsClient) => Promise }) => { await input.validateExistingReplay(tenantRow({ id: input.tenantId, active: true, deactivatedReason: null }), asTenantTx(replayTx)); return tenantRow({ id: input.tenantId, active: true, deactivatedReason: null }); } ); await expect( runWithRlsContext({ userId: owner.id }, () => createOwnedTenantWithShkDefaults({ user: owner, name: "Changed GmbH", slug: "heizkraft", creationRequestKey: CREATION_REQUEST_KEY, t: translate, }) ) ).rejects.toMatchObject({ code: foundationErrors.idempotencyConflict.code }); dependencyMocks.createTenant.mockClear(); await expect( runWithRlsContext({ userId: "user_foreign" }, () => createOwnedTenantWithShkDefaults({ user: owner, name: "Heizkraft GmbH", creationRequestKey: CREATION_REQUEST_KEY, t: translate, }) ) ).rejects.toMatchObject({ code: foundationErrors.notFound.code }); expect(dependencyMocks.createTenant).not.toHaveBeenCalled(); }); it("classifies only a completed marker with the exact owner payload as a replay", async () => { const tenantId = deriveTenantCreationId("user_1", CREATION_REQUEST_KEY); const payloadHash = createHash("sha256") .update( JSON.stringify({ contract: "tenant-creation-request/v1", userId: "user_1", key: CREATION_REQUEST_KEY, name: "Heizkraft GmbH", slug: "heizkraft", }) ) .digest("hex"); const marker = { requestHash: SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST, responseStatus: 201, responseBody: { state: "completed", templateKey: SHK_V2_TENANT_BOOTSTRAP_CONFIG.templateKey, schemaVersion: SHK_V2_TENANT_BOOTSTRAP_CONFIG.schemaVersion, completedAt: FIXED_NOW.toISOString(), creationRequest: { key: CREATION_REQUEST_KEY, payloadHash, tenantName: "Heizkraft GmbH", tenantSlug: "heizkraft", }, }, }; const fake = buildFakeTx({}, marker); fake.tenant.findUnique.mockResolvedValue(tenantRow({ id: tenantId, active: true, deactivatedReason: null })); dependencyMocks.dbTransaction.mockImplementation(async (callback: (tx: TenantRlsClient) => Promise) => callback(asTenantTx(fake))); await expect( runWithRlsContext({ userId: "user_1" }, () => isExactOwnedTenantCreationReplay({ userId: "user_1", name: "Heizkraft GmbH", slug: "heizkraft", creationRequestKey: CREATION_REQUEST_KEY, }) ) ).resolves.toBe(true); await expect( runWithRlsContext({ userId: "user_1" }, () => isExactOwnedTenantCreationReplay({ userId: "user_1", name: "Changed GmbH", slug: "heizkraft", creationRequestKey: CREATION_REQUEST_KEY, }) ) ).resolves.toBe(false); dependencyMocks.dbTransaction.mockClear(); await expect( runWithRlsContext({ userId: "user_foreign" }, () => isExactOwnedTenantCreationReplay({ userId: "user_1", name: "Heizkraft GmbH", slug: "heizkraft", creationRequestKey: CREATION_REQUEST_KEY, }) ) ).resolves.toBe(false); expect(dependencyMocks.dbTransaction).not.toHaveBeenCalled(); }); it("replays an exact signup creation request with deterministic identities and no password material in its marker", async () => { const email = " OWNER@Heizkraft.Example "; const normalizedEmail = "owner@heizkraft.example"; const password = "correct horse battery staple"; const expectedUserId = deriveSignupUserId(normalizedEmail, CREATION_REQUEST_KEY); const expectedTenantId = deriveSignupTenantId(normalizedEmail, CREATION_REQUEST_KEY); const createdUser = userRow({ id: expectedUserId, email: normalizedEmail, defaultTenantId: expectedTenantId, active: true, }); const firstTx = buildFakeTx(); firstTx.user.create.mockImplementationOnce((args: { data: Record }) => Promise.resolve(userRow({ ...(args.data as Partial), createdAt: FIXED_NOW, updatedAt: FIXED_NOW })) ); firstTx.tenant.update.mockResolvedValueOnce(tenantRow({ id: expectedTenantId, active: true, deactivatedReason: null })); dependencyMocks.createTenant.mockImplementationOnce( async (input: { tenantId: string; setup: (tenant: Tenant, tx: TenantRlsClient) => Promise }) => { expect(input.tenantId).toBe(expectedTenantId); const pendingTenant = tenantRow({ id: input.tenantId }); return (await input.setup(pendingTenant, asTenantTx(firstTx))) ?? pendingTenant; } ); const first = await createSignupTenantWithShkDefaults({ email, password, firstName: "Mara", lastName: "König", company: "Heizkraft GmbH", locale: "de", slug: "heizkraft", creationRequestKey: CREATION_REQUEST_KEY, billingPreference: { selectedSubscriptionPriceId: "price_swarm_monthly", selectedOfficeSeatQuantity: 5, selectedFieldSeatQuantity: 15, }, t: translate, }); expect(first).toMatchObject({ tenant: { id: expectedTenantId, active: true }, user: { id: expectedUserId, email: normalizedEmail, defaultTenantId: expectedTenantId }, replayed: false, }); expect(firstTx.user.create).toHaveBeenCalledWith({ data: expect.objectContaining({ id: expectedUserId, email: normalizedEmail, passwordHash: "prepared_hash", defaultTenantId: expectedTenantId, }), }); const completedBody = firstTx.idempotencyKey.update.mock.calls[0]?.[0].data.responseBody; expect(completedBody).toMatchObject({ state: "completed", creationRequest: { key: CREATION_REQUEST_KEY, payloadHash: expect.stringMatching(/^[a-f0-9]{64}$/), tenantName: "Heizkraft GmbH", tenantSlug: "heizkraft", signup: { normalizedEmail, userId: expectedUserId }, }, }); expect(JSON.stringify(completedBody)).not.toContain(password); expect(JSON.stringify(completedBody)).not.toContain("prepared_hash"); expect(firstTx.tenantProductConfiguration.upsert).toHaveBeenCalledWith({ where: { tenantId: expectedTenantId }, create: { tenantId: expectedTenantId, signupSubscriptionPriceId: "price_swarm_monthly", signupOfficeSeatQuantity: 5, signupFieldSeatQuantity: 15, }, update: { signupSubscriptionPriceId: "price_swarm_monthly", signupOfficeSeatQuantity: 5, signupFieldSeatQuantity: 15, }, }); expect(firstTx.calls.indexOf("billingPreference.upsert")).toBeLessThan(firstTx.calls.indexOf("marker.complete")); expect(dependencyMocks.resolveUserEmailRlsIdentity).toHaveBeenCalledWith(normalizedEmail); expect(dependencyMocks.hashPassword).toHaveBeenCalledTimes(1); expect(dependencyMocks.verifyPassword).not.toHaveBeenCalled(); const replayTx = buildFakeTx( {}, { requestHash: SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST, responseStatus: 201, responseBody: completedBody, } ); replayTx.$queryRaw.mockResolvedValue([createdUser]); dependencyMocks.resolveUserEmailRlsIdentity.mockResolvedValueOnce({ resourceId: expectedUserId, userId: expectedUserId }); dependencyMocks.hashPassword.mockClear(); dependencyMocks.verifyPassword.mockClear(); const replayOrder: string[] = []; dependencyMocks.dbUserFindUnique.mockImplementationOnce(async (args: { where: { id: string }; select: { passwordHash: boolean } }) => { replayOrder.push("password.read"); expect(args).toEqual({ where: { id: expectedUserId }, select: { passwordHash: true } }); expect(getRlsExecutionContext()).toMatchObject({ userId: expectedUserId }); expect(getRlsExecutionContext()?.tenantId).toBeUndefined(); expect(getRlsExecutionContext()?.transaction).toBeUndefined(); return { passwordHash: "hash" }; }); dependencyMocks.verifyPassword.mockImplementationOnce(async () => { replayOrder.push("password.verify"); expect(getRlsExecutionContext()).toMatchObject({ userId: expectedUserId }); expect(getRlsExecutionContext()?.transaction).toBeUndefined(); return { valid: true }; }); dependencyMocks.createTenant.mockImplementationOnce( async (input: { tenantId: string; validateExistingReplay: (tenant: Tenant, tx: TenantRlsClient) => Promise; setup: (tenant: Tenant, tx: TenantRlsClient) => Promise; }) => { replayOrder.push("transaction.start"); const existingTenant = tenantRow({ id: input.tenantId, active: true, deactivatedReason: null }); await input.validateExistingReplay(existingTenant, asTenantTx(replayTx)); const result = (await input.setup(existingTenant, asTenantTx(replayTx))) ?? existingTenant; replayOrder.push("transaction.commit"); return result; } ); const replay = await createSignupTenantWithShkDefaults({ email, password, firstName: "Mara", lastName: "König", company: "Heizkraft GmbH", locale: "de", slug: "heizkraft", creationRequestKey: CREATION_REQUEST_KEY, billingPreference: { selectedSubscriptionPriceId: "price_swarm_monthly", selectedOfficeSeatQuantity: 5, selectedFieldSeatQuantity: 15, }, t: translate, }); expect(replay).toMatchObject({ tenant: { id: expectedTenantId }, user: { id: expectedUserId, email: normalizedEmail }, replayed: true, }); expect(replayTx.user.create).not.toHaveBeenCalled(); expect(replayTx.idempotencyKey.upsert).not.toHaveBeenCalled(); expect(replayTx.tenantProductConfiguration.findUnique).toHaveBeenCalledWith({ where: { tenantId: expectedTenantId }, select: { signupSubscriptionPriceId: true, signupOfficeSeatQuantity: true, signupFieldSeatQuantity: true, }, }); expect(replayTx.$queryRaw).toHaveBeenCalledOnce(); expect(dependencyMocks.hashPassword).not.toHaveBeenCalled(); expect(replayOrder).toEqual(["password.read", "password.verify", "transaction.start", "transaction.commit"]); expect(dependencyMocks.verifyPassword).toHaveBeenCalledTimes(1); expect(dependencyMocks.verifyPassword).toHaveBeenCalledWith(password, "hash"); expect(dependencyMocks.findRegistrationBillingPreferenceCapability).not.toHaveBeenCalled(); dependencyMocks.resolveUserEmailRlsIdentity.mockResolvedValueOnce({ resourceId: expectedUserId, userId: expectedUserId }); dependencyMocks.createTenant.mockClear(); dependencyMocks.hashPassword.mockClear(); dependencyMocks.verifyPassword.mockClear(); dependencyMocks.verifyPassword.mockResolvedValueOnce({ valid: false }); await expect( createSignupTenantWithShkDefaults({ email, password: "wrong password", firstName: "Mara", lastName: "König", company: "Heizkraft GmbH", locale: "de", slug: "heizkraft", creationRequestKey: CREATION_REQUEST_KEY, t: translate, }) ).rejects.toMatchObject({ code: foundationErrors.idempotencyConflict.code }); expect(dependencyMocks.hashPassword).not.toHaveBeenCalled(); expect(dependencyMocks.verifyPassword).toHaveBeenCalledTimes(1); expect(dependencyMocks.createTenant).not.toHaveBeenCalled(); }); it("replays a completed v1 signup after the v2 deploy only when its registration-bound billing preference matches", async () => { const normalizedEmail = "owner@heizkraft.example"; const password = "correct horse battery staple"; const expectedUserId = deriveSignupUserId(normalizedEmail, CREATION_REQUEST_KEY); const expectedTenantId = deriveSignupTenantId(normalizedEmail, CREATION_REQUEST_KEY); const billingPreference = { selectedSubscriptionPriceId: "price_swarm_monthly", selectedOfficeSeatQuantity: 5, selectedFieldSeatQuantity: 15, } as const; const payloadHash = createHash("sha256") .update( JSON.stringify({ contract: "signup-creation-request/v1", key: CREATION_REQUEST_KEY, normalizedEmail, company: "Heizkraft GmbH", firstName: "Mara", lastName: "König", avatarURL: null, locale: "de", slug: "heizkraft", }) ) .digest("hex"); const replayTx = buildFakeTx( {}, { requestHash: SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST, responseStatus: 201, responseBody: { state: "completed", templateKey: SHK_V2_TENANT_BOOTSTRAP_CONFIG.templateKey, schemaVersion: SHK_V2_TENANT_BOOTSTRAP_CONFIG.schemaVersion, completedAt: FIXED_NOW.toISOString(), creationRequest: { key: CREATION_REQUEST_KEY, payloadHash, tenantName: "Heizkraft GmbH", tenantSlug: "heizkraft", signup: { normalizedEmail, userId: expectedUserId }, }, }, } ); replayTx.$queryRaw.mockResolvedValueOnce([ userRow({ id: expectedUserId, email: normalizedEmail, defaultTenantId: expectedTenantId, active: true }), ]); replayTx.tenantProductConfiguration.findUnique.mockResolvedValueOnce(null); dependencyMocks.findRegistrationBillingPreferenceCapability.mockResolvedValueOnce(billingPreference); dependencyMocks.resolveUserEmailRlsIdentity.mockResolvedValueOnce({ resourceId: expectedUserId, userId: expectedUserId }); dependencyMocks.createTenant.mockImplementationOnce( async (input: { tenantId: string; validateExistingReplay: (tenant: Tenant, tx: TenantRlsClient) => Promise }) => { const existingTenant = tenantRow({ id: input.tenantId, active: true, deactivatedReason: null }); await input.validateExistingReplay(existingTenant, asTenantTx(replayTx)); return existingTenant; } ); await expect( createSignupTenantWithShkDefaults({ email: normalizedEmail, password, firstName: "Mara", lastName: "König", company: "Heizkraft GmbH", locale: "de", slug: "heizkraft", creationRequestKey: CREATION_REQUEST_KEY, billingPreference, t: translate, }) ).resolves.toMatchObject({ tenant: { id: expectedTenantId }, user: { id: expectedUserId }, replayed: true }); expect(dependencyMocks.findRegistrationBillingPreferenceCapability).toHaveBeenCalledWith( expectedTenantId, expectedUserId, replayTx ); expect(replayTx.idempotencyKey.update).not.toHaveBeenCalled(); expect(replayTx.tenantProductConfiguration.upsert).not.toHaveBeenCalled(); }); it("fails closed when a completed v1 signup receives different v2 billing preferences", async () => { const normalizedEmail = "owner@heizkraft.example"; const expectedUserId = deriveSignupUserId(normalizedEmail, CREATION_REQUEST_KEY); const expectedTenantId = deriveSignupTenantId(normalizedEmail, CREATION_REQUEST_KEY); const payloadHash = createHash("sha256") .update( JSON.stringify({ contract: "signup-creation-request/v1", key: CREATION_REQUEST_KEY, normalizedEmail, company: "Heizkraft GmbH", firstName: "Mara", lastName: "König", avatarURL: null, locale: "de", slug: "heizkraft", }) ) .digest("hex"); const replayTx = buildFakeTx( {}, { requestHash: SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST, responseStatus: 201, responseBody: { state: "completed", templateKey: SHK_V2_TENANT_BOOTSTRAP_CONFIG.templateKey, schemaVersion: SHK_V2_TENANT_BOOTSTRAP_CONFIG.schemaVersion, completedAt: FIXED_NOW.toISOString(), creationRequest: { key: CREATION_REQUEST_KEY, payloadHash, tenantName: "Heizkraft GmbH", tenantSlug: "heizkraft", signup: { normalizedEmail, userId: expectedUserId }, }, }, } ); replayTx.$queryRaw.mockResolvedValueOnce([ userRow({ id: expectedUserId, email: normalizedEmail, defaultTenantId: expectedTenantId, active: true }), ]); replayTx.tenantProductConfiguration.findUnique.mockResolvedValueOnce(null); dependencyMocks.findRegistrationBillingPreferenceCapability.mockResolvedValueOnce({ selectedSubscriptionPriceId: "price_swarm_monthly", selectedOfficeSeatQuantity: 5, selectedFieldSeatQuantity: 15, }); dependencyMocks.resolveUserEmailRlsIdentity.mockResolvedValueOnce({ resourceId: expectedUserId, userId: expectedUserId }); dependencyMocks.createTenant.mockImplementationOnce( async (input: { tenantId: string; validateExistingReplay: (tenant: Tenant, tx: TenantRlsClient) => Promise }) => { const existingTenant = tenantRow({ id: input.tenantId, active: true, deactivatedReason: null }); await input.validateExistingReplay(existingTenant, asTenantTx(replayTx)); return existingTenant; } ); await expect( createSignupTenantWithShkDefaults({ email: normalizedEmail, password: "correct horse battery staple", firstName: "Mara", lastName: "König", company: "Heizkraft GmbH", locale: "de", slug: "heizkraft", creationRequestKey: CREATION_REQUEST_KEY, billingPreference: { selectedSubscriptionPriceId: "price_colony_monthly", selectedOfficeSeatQuantity: 10, selectedFieldSeatQuantity: 30, }, t: translate, }) ).rejects.toMatchObject({ code: foundationErrors.idempotencyConflict.code }); expect(dependencyMocks.findRegistrationBillingPreferenceCapability).toHaveBeenCalledOnce(); expect(replayTx.idempotencyKey.update).not.toHaveBeenCalled(); expect(replayTx.tenantProductConfiguration.upsert).not.toHaveBeenCalled(); }); it("fails closed when the password hash changes after verification but before the replay row lock", async () => { const normalizedEmail = "owner@heizkraft.example"; const password = "correct horse battery staple"; const expectedUserId = deriveSignupUserId(normalizedEmail, CREATION_REQUEST_KEY); const expectedTenantId = deriveSignupTenantId(normalizedEmail, CREATION_REQUEST_KEY); const input = { email: normalizedEmail, password, firstName: "Mara", lastName: "König", company: "Heizkraft GmbH", locale: "de", slug: "heizkraft", creationRequestKey: CREATION_REQUEST_KEY, t: translate, } as const; const payloadHash = createHash("sha256") .update( JSON.stringify({ contract: "signup-creation-request/v2", key: CREATION_REQUEST_KEY, normalizedEmail, company: input.company, firstName: input.firstName, lastName: input.lastName, avatarURL: null, locale: input.locale, slug: input.slug, billingPreference: null, }) ) .digest("hex"); const replayTx = buildFakeTx( {}, { requestHash: SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST, responseStatus: 201, responseBody: { state: "completed", templateKey: SHK_V2_TENANT_BOOTSTRAP_CONFIG.templateKey, schemaVersion: SHK_V2_TENANT_BOOTSTRAP_CONFIG.schemaVersion, completedAt: FIXED_NOW.toISOString(), creationRequest: { key: CREATION_REQUEST_KEY, payloadHash, tenantName: input.company, tenantSlug: input.slug, signup: { normalizedEmail, userId: expectedUserId }, }, }, } ); replayTx.$queryRaw.mockResolvedValueOnce([ userRow({ id: expectedUserId, email: normalizedEmail, passwordHash: "rotated_hash", defaultTenantId: expectedTenantId, active: true, }), ]); dependencyMocks.resolveUserEmailRlsIdentity.mockResolvedValueOnce({ resourceId: expectedUserId, userId: expectedUserId }); const order: string[] = []; dependencyMocks.dbUserFindUnique.mockImplementationOnce(async () => { order.push("password.read"); return { passwordHash: "verified_hash" }; }); dependencyMocks.verifyPassword.mockImplementationOnce(async () => { order.push("password.verify"); return { valid: true }; }); dependencyMocks.createTenant.mockImplementationOnce( async (createInput: { tenantId: string; validateExistingReplay: (tenant: Tenant, tx: TenantRlsClient) => Promise }) => { order.push("transaction.start"); await createInput.validateExistingReplay(tenantRow({ id: createInput.tenantId, active: true, deactivatedReason: null }), asTenantTx(replayTx)); order.push("transaction.commit"); return tenantRow({ id: createInput.tenantId, active: true, deactivatedReason: null }); } ); await expect(createSignupTenantWithShkDefaults(input)).rejects.toMatchObject({ code: foundationErrors.idempotencyConflict.code, }); expect(order).toEqual(["password.read", "password.verify", "transaction.start"]); expect(dependencyMocks.verifyPassword).toHaveBeenCalledWith(password, "verified_hash"); expect(replayTx.$queryRaw).toHaveBeenCalledOnce(); expect(replayTx.tenantUser.findFirst).toHaveBeenCalledOnce(); expect(replayTx.idempotencyKey.findUnique).toHaveBeenCalledOnce(); }); it("fails closed when a signup replay changes its bound payload or creation key", async () => { const normalizedEmail = "owner@heizkraft.example"; const expectedUserId = deriveSignupUserId(normalizedEmail, CREATION_REQUEST_KEY); const expectedTenantId = deriveSignupTenantId(normalizedEmail, CREATION_REQUEST_KEY); const markerBody = { state: "completed", templateKey: SHK_V2_TENANT_BOOTSTRAP_CONFIG.templateKey, schemaVersion: SHK_V2_TENANT_BOOTSTRAP_CONFIG.schemaVersion, completedAt: FIXED_NOW.toISOString(), creationRequest: { key: CREATION_REQUEST_KEY, payloadHash: "intentionally-not-the-changed-payload-hash", tenantName: "Heizkraft GmbH", tenantSlug: "heizkraft", signup: { normalizedEmail, userId: expectedUserId }, }, }; const replayTx = buildFakeTx( {}, { requestHash: SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST, responseStatus: 201, responseBody: markerBody, } ); replayTx.$queryRaw.mockResolvedValueOnce([userRow({ id: expectedUserId, email: normalizedEmail, defaultTenantId: expectedTenantId, active: true })]); dependencyMocks.resolveUserEmailRlsIdentity.mockResolvedValueOnce({ resourceId: expectedUserId, userId: expectedUserId }); dependencyMocks.createTenant.mockImplementationOnce( async (input: { tenantId: string; validateExistingReplay: (tenant: Tenant, tx: TenantRlsClient) => Promise }) => { await input.validateExistingReplay(tenantRow({ id: input.tenantId, active: true, deactivatedReason: null }), asTenantTx(replayTx)); return tenantRow({ id: input.tenantId, active: true, deactivatedReason: null }); } ); await expect( createSignupTenantWithShkDefaults({ email: normalizedEmail, password: "password", firstName: "Changed", lastName: "König", company: "Heizkraft GmbH", locale: "de", slug: "heizkraft", creationRequestKey: CREATION_REQUEST_KEY, t: translate, }) ).rejects.toMatchObject({ code: foundationErrors.idempotencyConflict.code }); expect(dependencyMocks.hashPassword).not.toHaveBeenCalled(); expect(dependencyMocks.verifyPassword).toHaveBeenCalledTimes(1); expect(dependencyMocks.verifyPassword).toHaveBeenCalledWith("password", "hash"); const anotherKey = "b79f4743-b5ee-48df-9287-10f24b2aedbf"; expect(deriveSignupTenantId(normalizedEmail, anotherKey)).not.toBe(expectedTenantId); expect(deriveSignupUserId(normalizedEmail, anotherKey)).not.toBe(expectedUserId); dependencyMocks.resolveUserEmailRlsIdentity.mockResolvedValueOnce({ resourceId: expectedUserId, userId: expectedUserId }); dependencyMocks.createTenant.mockClear(); dependencyMocks.hashPassword.mockClear(); dependencyMocks.verifyPassword.mockClear(); await expect( createSignupTenantWithShkDefaults({ email: normalizedEmail, password: "password", firstName: "Mara", lastName: "König", company: "Heizkraft GmbH", creationRequestKey: anotherKey, t: translate, }) ).rejects.toMatchObject({ code: foundationErrors.idempotencyConflict.code }); expect(dependencyMocks.createTenant).not.toHaveBeenCalled(); expect(dependencyMocks.hashPassword).not.toHaveBeenCalled(); expect(dependencyMocks.verifyPassword).not.toHaveBeenCalled(); }); it("never creates a user without a fresh hash when only the expected identity exists", async () => { const normalizedEmail = "owner@heizkraft.example"; const expectedUserId = deriveSignupUserId(normalizedEmail, CREATION_REQUEST_KEY); const fake = buildFakeTx(); dependencyMocks.resolveUserEmailRlsIdentity.mockResolvedValueOnce({ resourceId: expectedUserId, userId: expectedUserId }); dependencyMocks.createTenant.mockImplementationOnce(async (input: { setup: (tenant: Tenant, tx: TenantRlsClient) => Promise }) => { await input.setup(tenantRow({ id: deriveSignupTenantId(normalizedEmail, CREATION_REQUEST_KEY) }), asTenantTx(fake)); return tenantRow(); }); await expect( createSignupTenantWithShkDefaults({ email: normalizedEmail, password: "correct horse battery staple", firstName: "Mara", lastName: "König", company: "Heizkraft GmbH", creationRequestKey: CREATION_REQUEST_KEY, t: translate, }) ).rejects.toMatchObject({ code: foundationErrors.idempotencyConflict.code }); expect(dependencyMocks.hashPassword).not.toHaveBeenCalled(); expect(dependencyMocks.verifyPassword).toHaveBeenCalledTimes(1); expect(dependencyMocks.verifyPassword).toHaveBeenCalledWith("correct horse battery staple", "hash"); expect(fake.user.create).not.toHaveBeenCalled(); }); it("fails closed when a new-signup identity race reaches a unique constraint", async () => { dependencyMocks.resolveUserEmailRlsIdentity.mockResolvedValueOnce(null); dependencyMocks.createTenant.mockRejectedValueOnce({ code: "P2002" }); await expect( createSignupTenantWithShkDefaults({ email: "owner@heizkraft.example", password: "correct horse battery staple", firstName: "Mara", lastName: "König", company: "Heizkraft GmbH", creationRequestKey: CREATION_REQUEST_KEY, t: translate, }) ).rejects.toMatchObject({ code: foundationErrors.idempotencyConflict.code }); expect(dependencyMocks.hashPassword).toHaveBeenCalledTimes(1); expect(dependencyMocks.verifyPassword).not.toHaveBeenCalled(); }); it("hashes before the transaction and emits the user hook only after commit", async () => { const order: string[] = []; const fake = buildFakeTx(); dependencyMocks.prepareForms.mockImplementation(() => { order.push("forms.prepare"); return preparedFormTemplates; }); dependencyMocks.hashPassword.mockImplementation(async () => { order.push("hash"); return "prepared_hash"; }); dependencyMocks.createTenant.mockImplementation(async (input: { setup: (tenant: Tenant, tx: TenantRlsClient) => Promise }) => { order.push("transaction.start"); await input.setup(tenantRow(), asTenantTx(fake)); order.push("transaction.commit"); return tenantRow({ active: true, deactivatedReason: null }); }); dependencyMocks.emitUserCreatedHook.mockImplementation(async () => { order.push("user.hook"); }); dependencyMocks.emitTenantCreatedHook.mockImplementation(async () => { order.push("tenant.hook"); }); dependencyMocks.invalidateUserSnapshot.mockImplementation(async () => { order.push("user-cache.invalidate"); }); dependencyMocks.publishTenantInvalidation.mockImplementation(async () => { order.push("tenant-cache.invalidate"); }); const result = await createSignupTenantWithShkDefaults({ email: "owner@heizkraft.example", password: "correct horse battery staple", firstName: "Mara", lastName: "König", company: "Heizkraft GmbH", locale: "de", creationRequestKey: CREATION_REQUEST_KEY, t: translate, }); expect(order).toEqual([ "forms.prepare", "hash", "transaction.start", "transaction.commit", "tenant-cache.invalidate", "user-cache.invalidate", "tenant.hook", "user.hook", ]); expect(result.tenant.active).toBe(true); expect(dependencyMocks.createTenant).toHaveBeenCalledWith( expect.objectContaining({ active: false, deactivatedReason: TENANT_PENDING_OWNER_REASON, rlsUserId: expect.any(String), emitCreatedHook: false }) ); expect(fake.user.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ active: true }) })); }); it("creates and exactly replays an ownerless reservation without defaults or hooks", async () => { const reservationRequestKey = "41adac34-7b0d-47f0-9bb5-74dd67104dcb"; const tenantId = deriveTenantReservationId("operator_1", reservationRequestKey); const firstTx = buildFakeTx(); dependencyMocks.createTenant.mockImplementationOnce( async (input: { tenantId: string; setup: (tenant: Tenant, tx: TenantRlsClient) => Promise }) => { expect(input.tenantId).toBe(tenantId); const reserved = tenantRow({ id: tenantId }); return input.setup(reserved, asTenantTx(firstTx)); } ); const first = await runWithRlsContext({ userId: "operator_1" }, () => reserveTenantWithoutOwner({ name: "Heizkraft GmbH", operatorUserId: "operator_1", reservationRequestKey, ownerInvitation: OWNER_INVITATION_DRAFT, }) ); expect(first.id).toBe(tenantId); expect(dependencyMocks.createTenant).toHaveBeenNthCalledWith( 1, expect.objectContaining({ tenantId, name: "Heizkraft GmbH", slug: undefined, active: false, deactivatedReason: TENANT_PENDING_OWNER_REASON, rlsUserId: "operator_1", emitCreatedHook: false, setup: expect.any(Function), validateExistingReplay: expect.any(Function), }) ); const firstMarker = firstTx.idempotencyKey.upsert.mock.calls[0]?.[0].create; expect(firstMarker).toMatchObject({ tenantId, partitionKey: `tenant:${tenantId}`, scope: "tenant-reservation", key: reservationRequestKey, requestHash: expect.stringMatching(/^[a-f0-9]{64}$/), responseStatus: 201, responseBody: { state: "reserved", tenantName: "Heizkraft GmbH", tenantSlug: "heizkraft" }, }); expect(dependencyMocks.issueReservedOwnerInvitationWithTx).toHaveBeenCalledWith(firstTx, { tenantId, ...OWNER_INVITATION_DRAFT, }); const replayTx = buildFakeTx({}, firstMarker); dependencyMocks.createTenant.mockImplementationOnce( async (input: { validateExistingReplay: (tenant: Tenant, tx: TenantRlsClient) => Promise; setup: (tenant: Tenant, tx: TenantRlsClient) => Promise; }) => { const reserved = tenantRow({ id: tenantId }); await input.validateExistingReplay(reserved, asTenantTx(replayTx)); return input.setup(reserved, asTenantTx(replayTx)); } ); await expect( runWithRlsContext({ userId: "operator_1" }, () => reserveTenantWithoutOwner({ name: "Heizkraft GmbH", operatorUserId: "operator_1", reservationRequestKey, ownerInvitation: OWNER_INVITATION_DRAFT, }) ) ).resolves.toMatchObject({ id: tenantId, active: false, deactivatedReason: TENANT_PENDING_OWNER_REASON }); const claimedTenant = tenantRow({ id: tenantId, active: true, deactivatedReason: null }); const claimedReplayTx = buildFakeTx({}, firstMarker); const issuanceCallsBeforeClaimedReplay = dependencyMocks.issueReservedOwnerInvitationWithTx.mock.calls.length; dependencyMocks.createTenant.mockImplementationOnce( async (input: { validateExistingReplay: (tenant: Tenant, tx: TenantRlsClient) => Promise; setup: (tenant: Tenant, tx: TenantRlsClient) => Promise; }) => { await input.validateExistingReplay(claimedTenant, asTenantTx(claimedReplayTx)); return input.setup(claimedTenant, asTenantTx(claimedReplayTx)); } ); await expect( runWithRlsContext({ userId: "operator_1" }, () => reserveTenantWithoutOwner({ name: "Heizkraft GmbH", operatorUserId: "operator_1", reservationRequestKey, ownerInvitation: OWNER_INVITATION_DRAFT, }) ) ).resolves.toMatchObject({ id: tenantId, active: true, deactivatedReason: null }); expect(dependencyMocks.issueReservedOwnerInvitationWithTx).toHaveBeenCalledTimes(issuanceCallsBeforeClaimedReplay); dependencyMocks.createTenant.mockImplementationOnce(async (input: { validateExistingReplay: (tenant: Tenant, tx: TenantRlsClient) => Promise }) => { const reserved = tenantRow({ id: tenantId }); await input.validateExistingReplay(reserved, asTenantTx(replayTx)); return reserved; }); await expect( runWithRlsContext({ userId: "operator_1" }, () => reserveTenantWithoutOwner({ name: "Changed GmbH", operatorUserId: "operator_1", reservationRequestKey, ownerInvitation: OWNER_INVITATION_DRAFT, }) ) ).rejects.toMatchObject({ code: foundationErrors.idempotencyConflict.code }); dependencyMocks.createTenant.mockClear(); await expect( runWithRlsContext({ userId: "operator_foreign" }, () => reserveTenantWithoutOwner({ name: "Heizkraft GmbH", operatorUserId: "operator_1", reservationRequestKey, ownerInvitation: OWNER_INVITATION_DRAFT, }) ) ).rejects.toMatchObject({ code: foundationErrors.notFound.code }); expect(dependencyMocks.createTenant).not.toHaveBeenCalled(); expect(dependencyMocks.seedForms).not.toHaveBeenCalled(); }); it("rejects an owner invitation capability bound to a different reservation key", async () => { await expect( runWithRlsContext({ userId: "operator_1" }, () => reserveTenantWithoutOwner({ name: "Heizkraft GmbH", operatorUserId: "operator_1", reservationRequestKey: OWNER_INVITATION_DRAFT.issuanceKey, ownerInvitation: { ...OWNER_INVITATION_DRAFT, issuanceKey: "54a4218a-e068-43e5-9bf2-87b704191ce0" }, }) ) ).rejects.toMatchObject({ code: foundationErrors.notFound.code }); expect(dependencyMocks.createTenant).not.toHaveBeenCalled(); expect(dependencyMocks.issueReservedOwnerInvitationWithTx).not.toHaveBeenCalled(); }); it("continues post-commit work when tenant cache invalidation fails", async () => { const fake = buildFakeTx(); dependencyMocks.createTenant.mockImplementation(async (input: { setup: (tenant: Tenant, tx: TenantRlsClient) => Promise }) => { await input.setup(tenantRow(), asTenantTx(fake)); return tenantRow({ active: true, deactivatedReason: null }); }); dependencyMocks.publishTenantInvalidation.mockRejectedValueOnce(new Error("redis unavailable")); await expect( createSignupTenantWithShkDefaults({ email: "owner@heizkraft.example", password: "correct horse battery staple", firstName: "Mara", lastName: "König", company: "Heizkraft GmbH", creationRequestKey: CREATION_REQUEST_KEY, t: translate, }) ).resolves.toMatchObject({ tenant: { active: true }, user: { id: "user_1" } }); expect(dependencyMocks.publishTenantInvalidation).toHaveBeenCalledWith("tenant_1", "heizkraft"); expect(dependencyMocks.invalidateUserSnapshot).toHaveBeenCalledTimes(1); expect(dependencyMocks.emitTenantCreatedHook).toHaveBeenCalledTimes(1); expect(dependencyMocks.emitUserCreatedHook).toHaveBeenCalledTimes(1); }); it("claims a reservation under tenant and owner RLS and emits the tenant hook after commit", async () => { const fake = buildFakeTx(); const order: string[] = []; dependencyMocks.getWorkspaceInviteByToken.mockImplementationOnce(async () => { order.push("claim.authorize"); return { id: "invite_1", tenantId: "tenant_1", email: " OWNER@HEIZKRAFT.EXAMPLE ", type: TenantUserType.OWNER, status: "pending", acceptedByUserId: null, }; }); dependencyMocks.dbTransaction.mockImplementation(async (callback: (tx: TenantRlsClient) => Promise) => { expect(getRlsExecutionContext()).toMatchObject({ tenantId: "tenant_1", userId: "user_1" }); order.push("transaction.start"); const result = await callback(asTenantTx(fake)); order.push("transaction.commit"); return result; }); dependencyMocks.emitTenantCreatedHook.mockImplementation(async () => { order.push("tenant.hook"); }); dependencyMocks.invalidateUserSnapshot.mockImplementation(async () => { order.push("cache.invalidate"); }); dependencyMocks.publishTenantInvalidation.mockImplementation(async () => { order.push("tenant-cache.invalidate"); }); const result = await runWithRlsContext({ userId: "user_1" }, () => claimReservedTenantWithShkDefaults({ tenantId: "tenant_1", userId: "user_1", t: translate, claim: { kind: "workspace-invite", inviteId: "invite_1", token: "valid-token" }, }) ); expect(result).toMatchObject({ tenant: { id: "tenant_1", active: true }, user: { id: "user_1" }, replayed: false }); expect(order).toEqual(["transaction.start", "claim.authorize", "transaction.commit", "tenant-cache.invalidate", "cache.invalidate", "tenant.hook"]); expect(dependencyMocks.acceptWorkspaceInvite).toHaveBeenCalledWith( { tenantId: "tenant_1", inviteId: "invite_1", token: "valid-token", acceptedByUserId: "user_1" }, expect.anything() ); expect(dependencyMocks.emitTenantCreatedHook).toHaveBeenCalledWith(expect.objectContaining({ id: "tenant_1", active: true }), "user_1"); }); it("creates the new owner, binds and accepts the invite, and bootstraps the tenant in one transaction", async () => { const fake = buildFakeTx(); fake.user.create.mockImplementationOnce(async (args: { data: Partial }) => { fake.calls.push("user.create"); return userRow(args.data); }); dependencyMocks.resolveUserEmailRlsIdentity.mockResolvedValueOnce(null); dependencyMocks.acceptWorkspaceInvite.mockImplementationOnce(async () => { fake.calls.push("invitation.accept"); return { id: "invite_1", tenantId: "tenant_1", email: "owner@heizkraft.example", type: TenantUserType.OWNER, status: "accepted", acceptedByUserId: "user_1", createdUserId: "user_1", }; }); dependencyMocks.dbTransaction.mockImplementation(async (callback: (tx: TenantRlsClient) => Promise) => callback(asTenantTx(fake))); const result = await runWithRlsContext({ userId: "user_1" }, () => claimReservedTenantWithShkDefaults({ tenantId: "tenant_1", userId: "user_1", t: translate, createUser: { id: "user_1", email: "owner@heizkraft.example", passwordHash: "$argon2id$prepared-password-hash", firstName: "Mara", lastName: "König", locale: "de", }, claim: { kind: "workspace-invite", inviteId: "invite_1", token: "valid-token", createdUserId: "user_1", }, }) ); expect(result).toMatchObject({ tenant: { id: "tenant_1", active: true }, user: { id: "user_1", active: true, defaultTenantId: "tenant_1" }, replayed: false, }); expect(fake.user.create).toHaveBeenCalledWith({ data: { id: "user_1", email: "owner@heizkraft.example", passwordHash: "$argon2id$prepared-password-hash", firstName: "Mara", lastName: "König", avatar: "", phone: "", active: true, locale: "de", defaultTenantId: null, }, }); expect(fake.tenantUserInvitation.updateMany).toHaveBeenCalledWith({ where: { id: "invite_1", tenantId: "tenant_1", email: "owner@heizkraft.example", type: TenantUserType.OWNER, pending: true, status: "pending", tokenHash: expect.stringMatching(/^[a-f0-9]{64}$/u), createdUserId: null, acceptedAt: null, revokedAt: null, OR: [{ expiresAt: null }, { expiresAt: { gt: expect.any(Date) } }], }, data: { createdUserId: "user_1" }, }); expect(dependencyMocks.acceptWorkspaceInvite).toHaveBeenCalledWith( { tenantId: "tenant_1", inviteId: "invite_1", token: "valid-token", acceptedByUserId: "user_1", createdUserId: "user_1", }, expect.anything() ); expect(fake.calls.indexOf("user.create")).toBeLessThan(fake.calls.indexOf("invitation.bindCreatedUser")); expect(fake.calls.indexOf("invitation.bindCreatedUser")).toBeLessThan(fake.calls.indexOf("invitation.accept")); expect(fake.calls.indexOf("invitation.accept")).toBeLessThan(fake.calls.indexOf("tenant.activate")); expect(fake.user.update).toHaveBeenCalledWith({ where: { id: "user_1" }, data: { defaultTenantId: "tenant_1" } }); expect(dependencyMocks.emitUserCreatedHook).not.toHaveBeenCalled(); }); it("records the accepting user only when the owner claim created that account", async () => { const fake = buildFakeTx(); dependencyMocks.getWorkspaceInviteByToken.mockResolvedValueOnce({ id: "invite_1", tenantId: "tenant_1", email: "owner@heizkraft.example", type: TenantUserType.OWNER, status: "pending", createdUserId: "user_1", acceptedByUserId: null, }); dependencyMocks.dbTransaction.mockImplementation(async (callback: (tx: TenantRlsClient) => Promise) => callback(asTenantTx(fake))); await runWithRlsContext({ userId: "user_1" }, () => claimReservedTenantWithShkDefaults({ tenantId: "tenant_1", userId: "user_1", t: translate, claim: { kind: "workspace-invite", inviteId: "invite_1", token: "valid-token", createdUserId: "user_1", }, }) ); expect(dependencyMocks.acceptWorkspaceInvite).toHaveBeenCalledWith( { tenantId: "tenant_1", inviteId: "invite_1", token: "valid-token", acceptedByUserId: "user_1", createdUserId: "user_1", }, expect.anything() ); }); it("rejects a created-user claim unless registration already bound the exact durable invite marker", async () => { const fake = buildFakeTx(); dependencyMocks.dbTransaction.mockImplementation(async (callback: (tx: TenantRlsClient) => Promise) => callback(asTenantTx(fake))); await expect( runWithRlsContext({ userId: "user_1" }, () => claimReservedTenantWithShkDefaults({ tenantId: "tenant_1", userId: "user_1", t: translate, claim: { kind: "workspace-invite", inviteId: "invite_1", token: "valid-token", createdUserId: "user_1", }, }) ) ).rejects.toMatchObject({ code: foundationErrors.notFound.code }); expect(dependencyMocks.acceptWorkspaceInvite).not.toHaveBeenCalled(); expect(fake.tenant.findUnique).not.toHaveBeenCalled(); expect(fake.tenantUser.upsert).not.toHaveBeenCalled(); }); it("rejects a reservation claim without a matching authenticated user context", async () => { await expect( claimReservedTenantWithShkDefaults({ tenantId: "tenant_1", userId: "user_1", t: translate, claim: { kind: "workspace-invite", inviteId: "invite_1", token: "valid-token" }, }) ).rejects.toMatchObject({ code: foundationErrors.notFound.code }); expect(dependencyMocks.dbTransaction).not.toHaveBeenCalled(); }); it("does not inspect or mutate a reservation when the claim capability is rejected", async () => { const fake = buildFakeTx(); dependencyMocks.getWorkspaceInviteByToken.mockResolvedValueOnce(null); dependencyMocks.dbTransaction.mockImplementation(async (callback: (tx: TenantRlsClient) => Promise) => callback(asTenantTx(fake))); await expect( runWithRlsContext({ userId: "user_1" }, () => claimReservedTenantWithShkDefaults({ tenantId: "tenant_1", userId: "user_1", t: translate, claim: { kind: "workspace-invite", inviteId: "invite_1", token: "invalid-token" }, }) ) ).rejects.toMatchObject({ code: foundationErrors.notFound.code }); expect(fake.user.findMany).not.toHaveBeenCalled(); expect(fake.tenant.findUnique).not.toHaveBeenCalled(); expect(fake.idempotencyKey.upsert).not.toHaveBeenCalled(); }); it("rejects a member invitation before owner provisioning", async () => { const fake = buildFakeTx(); dependencyMocks.getWorkspaceInviteByToken.mockResolvedValueOnce({ id: "invite_1", tenantId: "tenant_1", email: "owner@heizkraft.example", type: TenantUserType.MEMBER, status: "pending", acceptedByUserId: null, }); dependencyMocks.dbTransaction.mockImplementation(async (callback: (tx: TenantRlsClient) => Promise) => callback(asTenantTx(fake))); await expect( runWithRlsContext({ userId: "user_1" }, () => claimReservedTenantWithShkDefaults({ tenantId: "tenant_1", userId: "user_1", t: translate, claim: { kind: "workspace-invite", inviteId: "invite_1", token: "valid-token" }, }) ) ).rejects.toMatchObject({ code: foundationErrors.notFound.code }); expect(fake.user.findMany).not.toHaveBeenCalled(); expect(dependencyMocks.acceptWorkspaceInvite).not.toHaveBeenCalled(); expect(fake.tenantUser.upsert).not.toHaveBeenCalled(); expect(fake.userRole.createMany).not.toHaveBeenCalled(); }); it("rejects an invitation for another email before owner provisioning", async () => { const fake = buildFakeTx(); dependencyMocks.getWorkspaceInviteByToken.mockResolvedValueOnce({ id: "invite_1", tenantId: "tenant_1", email: "other@heizkraft.example", type: TenantUserType.OWNER, status: "pending", acceptedByUserId: null, }); dependencyMocks.dbTransaction.mockImplementation(async (callback: (tx: TenantRlsClient) => Promise) => callback(asTenantTx(fake))); await expect( runWithRlsContext({ userId: "user_1" }, () => claimReservedTenantWithShkDefaults({ tenantId: "tenant_1", userId: "user_1", t: translate, claim: { kind: "workspace-invite", inviteId: "invite_1", token: "valid-token" }, }) ) ).rejects.toMatchObject({ code: foundationErrors.notFound.code }); expect(fake.user.findMany).toHaveBeenCalledWith({ where: { email: { equals: "other@heizkraft.example", mode: "insensitive" } }, select: { id: true }, orderBy: { id: "asc" }, take: 2, }); expect(dependencyMocks.acceptWorkspaceInvite).not.toHaveBeenCalled(); expect(fake.tenantUser.upsert).not.toHaveBeenCalled(); expect(fake.userRole.createMany).not.toHaveBeenCalled(); }); it("rejects a case-insensitive email identity when more than one user row matches", async () => { const fake = buildFakeTx(); fake.user.findMany.mockResolvedValueOnce([{ id: "user_1" }, { id: "case_variant_user" }]); dependencyMocks.dbTransaction.mockImplementation(async (callback: (tx: TenantRlsClient) => Promise) => callback(asTenantTx(fake))); await expect( runWithRlsContext({ userId: "user_1" }, () => claimReservedTenantWithShkDefaults({ tenantId: "tenant_1", userId: "user_1", t: translate, claim: { kind: "workspace-invite", inviteId: "invite_1", token: "valid-token" }, }) ) ).rejects.toMatchObject({ code: foundationErrors.notFound.code }); expect(dependencyMocks.resolveUserEmailRlsIdentity).toHaveBeenCalledWith("owner@heizkraft.example", expect.anything()); expect(fake.$queryRaw).not.toHaveBeenCalled(); expect(dependencyMocks.acceptWorkspaceInvite).not.toHaveBeenCalled(); expect(fake.tenant.findUnique).not.toHaveBeenCalled(); }); it("replays an already accepted invitation for the same existing owner without a created-user marker", async () => { const fake = buildFakeTx({ responseStatus: 201, responseBody: { state: "completed", completedAt: FIXED_NOW.toISOString() } }); dependencyMocks.getWorkspaceInviteByToken.mockResolvedValueOnce({ id: "invite_1", tenantId: "tenant_1", email: "owner@heizkraft.example", type: TenantUserType.OWNER, status: "accepted", createdUserId: null, acceptedByUserId: "user_1", }); dependencyMocks.dbTransaction.mockImplementation(async (callback: (tx: TenantRlsClient) => Promise) => callback(asTenantTx(fake))); await expect( runWithRlsContext({ userId: "user_1" }, () => claimReservedTenantWithShkDefaults({ tenantId: "tenant_1", userId: "user_1", t: translate, claim: { kind: "workspace-invite", inviteId: "invite_1", token: "valid-token" }, }) ) ).resolves.toMatchObject({ replayed: true, tenant: { id: "tenant_1" }, user: { id: "user_1" } }); expect(dependencyMocks.acceptWorkspaceInvite).not.toHaveBeenCalled(); expect(fake.user.findMany).toHaveBeenCalledWith({ where: { email: { equals: "owner@heizkraft.example", mode: "insensitive" } }, select: { id: true }, orderBy: { id: "asc" }, take: 2, }); expect(dependencyMocks.publishTenantInvalidation).toHaveBeenCalledWith("tenant_1", "heizkraft"); expect(dependencyMocks.emitTenantCreatedHook).toHaveBeenCalledWith(expect.objectContaining({ id: "tenant_1" }), "user_1"); }); it("replays an already accepted invitation for the same newly created owner with the matching marker", async () => { const fake = buildFakeTx({ responseStatus: 201, responseBody: { state: "completed", completedAt: FIXED_NOW.toISOString() } }); dependencyMocks.getWorkspaceInviteByToken.mockResolvedValueOnce({ id: "invite_1", tenantId: "tenant_1", email: "owner@heizkraft.example", type: TenantUserType.OWNER, status: "accepted", createdUserId: "user_1", acceptedByUserId: "user_1", }); dependencyMocks.dbTransaction.mockImplementation(async (callback: (tx: TenantRlsClient) => Promise) => callback(asTenantTx(fake))); await expect( runWithRlsContext({ userId: "user_1" }, () => claimReservedTenantWithShkDefaults({ tenantId: "tenant_1", userId: "user_1", t: translate, claim: { kind: "workspace-invite", inviteId: "invite_1", token: "valid-token", createdUserId: "user_1", }, }) ) ).resolves.toMatchObject({ replayed: true, user: { id: "user_1" } }); expect(dependencyMocks.acceptWorkspaceInvite).not.toHaveBeenCalled(); expect(fake.user.update).not.toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ active: true }) })); }); it("rejects an accepted owner replay after the user was administratively deactivated", async () => { const fake = buildFakeTx({ responseStatus: 201, responseBody: { state: "completed", completedAt: FIXED_NOW.toISOString() } }); fake.$queryRaw.mockResolvedValueOnce([userRow({ active: false })]); dependencyMocks.getWorkspaceInviteByToken.mockResolvedValueOnce({ id: "invite_1", tenantId: "tenant_1", email: "owner@heizkraft.example", type: TenantUserType.OWNER, status: "accepted", createdUserId: "user_1", acceptedByUserId: "user_1", }); dependencyMocks.dbTransaction.mockImplementation(async (callback: (tx: TenantRlsClient) => Promise) => callback(asTenantTx(fake))); await expect( runWithRlsContext({ userId: "user_1" }, () => claimReservedTenantWithShkDefaults({ tenantId: "tenant_1", userId: "user_1", t: translate, claim: { kind: "workspace-invite", inviteId: "invite_1", token: "valid-token", createdUserId: "user_1", }, }) ) ).rejects.toMatchObject({ code: foundationErrors.notFound.code }); expect(fake.user.update).not.toHaveBeenCalled(); expect(dependencyMocks.acceptWorkspaceInvite).not.toHaveBeenCalled(); expect(fake.tenant.findUnique).not.toHaveBeenCalled(); }); it("rejects an accepted invitation replay when its created-user marker is omitted", async () => { const fake = buildFakeTx({ responseStatus: 201, responseBody: { state: "completed", completedAt: FIXED_NOW.toISOString() } }); dependencyMocks.getWorkspaceInviteByToken.mockResolvedValueOnce({ id: "invite_1", tenantId: "tenant_1", email: "owner@heizkraft.example", type: TenantUserType.OWNER, status: "accepted", createdUserId: "user_1", acceptedByUserId: "user_1", }); dependencyMocks.dbTransaction.mockImplementation(async (callback: (tx: TenantRlsClient) => Promise) => callback(asTenantTx(fake))); await expect( runWithRlsContext({ userId: "user_1" }, () => claimReservedTenantWithShkDefaults({ tenantId: "tenant_1", userId: "user_1", t: translate, claim: { kind: "workspace-invite", inviteId: "invite_1", token: "valid-token" }, }) ) ).rejects.toMatchObject({ code: foundationErrors.notFound.code }); expect(fake.tenant.findUnique).not.toHaveBeenCalled(); expect(fake.tenantUser.upsert).not.toHaveBeenCalled(); }); it("rejects an accepted invitation replay for a different authenticated owner", async () => { const fake = buildFakeTx({ responseStatus: 201, responseBody: { state: "completed", completedAt: FIXED_NOW.toISOString() } }); dependencyMocks.getWorkspaceInviteByToken.mockResolvedValueOnce({ id: "invite_1", tenantId: "tenant_1", email: "owner@heizkraft.example", type: TenantUserType.OWNER, status: "accepted", createdUserId: null, acceptedByUserId: "user_2", }); dependencyMocks.dbTransaction.mockImplementation(async (callback: (tx: TenantRlsClient) => Promise) => callback(asTenantTx(fake))); await expect( runWithRlsContext({ userId: "user_1" }, () => claimReservedTenantWithShkDefaults({ tenantId: "tenant_1", userId: "user_1", t: translate, claim: { kind: "workspace-invite", inviteId: "invite_1", token: "valid-token" }, }) ) ).rejects.toMatchObject({ code: foundationErrors.notFound.code }); expect(dependencyMocks.acceptWorkspaceInvite).not.toHaveBeenCalled(); expect(fake.tenant.findUnique).not.toHaveBeenCalled(); }); it("rejects an accepted invitation replay when its email no longer matches the owner", async () => { const fake = buildFakeTx({ responseStatus: 201, responseBody: { state: "completed", completedAt: FIXED_NOW.toISOString() } }); dependencyMocks.getWorkspaceInviteByToken.mockResolvedValueOnce({ id: "invite_1", tenantId: "tenant_1", email: "other@heizkraft.example", type: TenantUserType.OWNER, status: "accepted", acceptedByUserId: "user_1", }); dependencyMocks.dbTransaction.mockImplementation(async (callback: (tx: TenantRlsClient) => Promise) => callback(asTenantTx(fake))); await expect( runWithRlsContext({ userId: "user_1" }, () => claimReservedTenantWithShkDefaults({ tenantId: "tenant_1", userId: "user_1", t: translate, claim: { kind: "workspace-invite", inviteId: "invite_1", token: "valid-token" }, }) ) ).rejects.toMatchObject({ code: foundationErrors.notFound.code }); expect(dependencyMocks.acceptWorkspaceInvite).not.toHaveBeenCalled(); expect(fake.tenantUser.upsert).not.toHaveBeenCalled(); expect(fake.userRole.createMany).not.toHaveBeenCalled(); }); it("rejects a claim when the reservation already has another member", async () => { const fake = buildFakeTx(); fake.tenantUser.findMany.mockResolvedValueOnce([{ userId: "user_other", type: 0, status: 2 }]); dependencyMocks.dbTransaction.mockImplementation(async (callback: (tx: TenantRlsClient) => Promise) => callback(asTenantTx(fake))); await expect( runWithRlsContext({ userId: "user_1" }, () => claimReservedTenantWithShkDefaults({ tenantId: "tenant_1", userId: "user_1", t: translate, claim: { kind: "workspace-invite", inviteId: "invite_1", token: "valid-token" }, }) ) ).rejects.toMatchObject({ code: foundationErrors.notFound.code }); expect(fake.idempotencyKey.upsert).not.toHaveBeenCalled(); expect(fake.tenant.update).not.toHaveBeenCalled(); }); });