// @vitest-environment node import { describe, expect, it, vi } from "vitest"; import type { Prisma, TenantUserInvitation } from "@hivegrid/db/prisma-browser"; import { hashWorkspaceInviteToken } from "@hivegrid/db/workspace-invites.server"; import { hashWorkspaceOwnerInvitationMailContent } from "@hivegrid/db/workspace-owner-invite-mail-contract.server"; import { hashOwnerInvitationIssuanceKey, issueReservedOwnerInvitationWithTx, type ReservedOwnerInvitationDraft } from "./ownerInvitationIssuance.server"; const TENANT_ID = "tenant_reserved"; const ISSUER_ID = "operator_1"; const TOKEN = "o".repeat(43); function draft(overrides: Partial = {}): ReservedOwnerInvitationDraft { return { issuanceKey: "reservation_1", email: "Owner@Heizkraft.example", firstName: "Mara", lastName: "König", fromUserId: ISSUER_ID, token: TOKEN, mail: { subject: "Einladung", html: `Einladung annehmen`, }, ...overrides, }; } function invitation(overrides: Partial = {}): TenantUserInvitation { const token = "s".repeat(43); return { id: "invite_existing", tenantId: TENANT_ID, email: "owner@heizkraft.example", firstName: "Mara", lastName: "König", type: 0, pending: true, status: "pending", tokenHash: hashWorkspaceInviteToken(token), tokenPrefix: token.slice(0, 12), expiresAt: new Date(Date.now() + 60_000), acceptedAt: null, revokedAt: null, createdUserId: null, fromUserId: ISSUER_ID, acceptedByUserId: null, revokedByUserId: null, ...overrides, }; } function mailOutbox(existing: TenantUserInvitation, overrides: Record = {}) { const storedToken = "s".repeat(43); const subject = "Einladung"; const html = `Einladung annehmen`; return { id: "outbox_existing", tenantId: TENANT_ID, eventType: "mail.transactional.send", payload: { tenantId: TENANT_ID, to: [existing.email], subject, html, priorityOverride: "critical", metadata: { source: "workspace-owner-invitation", alias: "user-invitation", invitationId: existing.id, invitationTokenHash: existing.tokenHash, issuanceKeyHash: hashOwnerInvitationIssuanceKey("reservation_1"), mailContentHash: hashWorkspaceOwnerInvitationMailContent({ recipient: existing.email, subject, html, rawToken: storedToken, invitationTokenHash: existing.tokenHash!, }), }, }, status: "PENDING", createdAt: new Date(), processedAt: null, retries: 0, lastError: null, scheduledAt: new Date(), dispatchKey: `mail:workspace-owner-invite:${existing.id}`, priority: 0, lockedUntil: null, ...overrides, }; } function buildTx( activeInvitations: TenantUserInvitation[] = [], existingOutbox: ReturnType | null = null, reservation = { active: false, deactivatedReason: "pending_owner", _count: { users: 0 } } ) { const createdOutboxes = new Map>(); const tx = { $executeRaw: vi.fn().mockResolvedValue(1), tenant: { findUnique: vi.fn().mockResolvedValue(reservation), }, tenantUserInvitation: { findMany: vi.fn().mockResolvedValue(activeInvitations), findFirst: vi.fn().mockResolvedValue(null), updateMany: vi.fn().mockResolvedValue({ count: 0 }), create: vi.fn().mockImplementation(({ data }: { data: Record }) => Promise.resolve({ id: "invite_created", acceptedAt: null, revokedAt: null, acceptedByUserId: null, revokedByUserId: null, ...data, }) ), }, outboxEvent: { findUnique: vi.fn().mockImplementation(({ where }: { where: { dispatchKey: string } }) => { if (existingOutbox?.dispatchKey === where.dispatchKey) return Promise.resolve(existingOutbox); return Promise.resolve(createdOutboxes.get(where.dispatchKey) ?? null); }), create: vi.fn().mockImplementation(({ data }: { data: Record }) => { const row = { id: "outbox_created", tenantId: data.tenantId as string, eventType: data.eventType as string, payload: data.payload as Prisma.JsonValue, status: "PENDING", createdAt: new Date(), processedAt: null, retries: 0, lastError: null, scheduledAt: new Date(), dispatchKey: data.dispatchKey as string, priority: 0, lockedUntil: null, } as ReturnType; createdOutboxes.set(row.dispatchKey, row); return Promise.resolve(row); }), }, }; return tx; } describe("reserved OWNER invitation issuance", () => { it("creates exactly one OWNER capability and keeps the raw token out of invite columns and metadata", async () => { const tx = buildTx(); const input = draft(); await expect(issueReservedOwnerInvitationWithTx(tx as never, { tenantId: TENANT_ID, ...input })).resolves.toEqual({ invitationId: "invite_created", replayed: false, }); expect(tx.$executeRaw).toHaveBeenCalledOnce(); expect(tx.tenantUserInvitation.create).toHaveBeenCalledOnce(); const inviteData = tx.tenantUserInvitation.create.mock.calls[0]?.[0].data as Record; expect(inviteData).toMatchObject({ tenantId: TENANT_ID, email: "owner@heizkraft.example", type: 0, pending: true, status: "pending", tokenHash: hashWorkspaceInviteToken(TOKEN), tokenPrefix: TOKEN.slice(0, 12), createdUserId: null, fromUserId: ISSUER_ID, }); expect(JSON.stringify(inviteData)).not.toContain(TOKEN); expect(tx.outboxEvent.create).toHaveBeenCalledOnce(); const outboxData = tx.outboxEvent.create.mock.calls[0]?.[0].data as { payload: Record; dispatchKey: string }; expect(outboxData.dispatchKey).toBe("mail:workspace-owner-invite:invite_created"); expect(outboxData.payload.html).toContain(TOKEN); const payloadWithoutHtml = { ...outboxData.payload, html: "[redacted]" }; expect(JSON.stringify(payloadWithoutHtml)).not.toContain(TOKEN); expect(payloadWithoutHtml.metadata).toMatchObject({ source: "workspace-owner-invitation", invitationId: "invite_created", invitationTokenHash: hashWorkspaceInviteToken(TOKEN), issuanceKeyHash: hashOwnerInvitationIssuanceKey("reservation_1"), mailContentHash: expect.stringMatching(/^[a-f0-9]{64}$/u), }); expect(JSON.stringify(payloadWithoutHtml.metadata)).not.toContain("reservation_1"); }); it("replays the exact stored invitation and outbox even when the caller prepared a fresh token", async () => { const existing = invitation(); const tx = buildTx([existing], mailOutbox(existing)); await expect(issueReservedOwnerInvitationWithTx(tx as never, { tenantId: TENANT_ID, ...draft() })).resolves.toEqual({ invitationId: existing.id, replayed: true, }); expect(hashWorkspaceInviteToken(TOKEN)).not.toBe(existing.tokenHash); expect(tx.tenantUserInvitation.create).not.toHaveBeenCalled(); expect(tx.outboxEvent.create).not.toHaveBeenCalled(); }); it("fails closed when an active OWNER invitation belongs to another issuance key", async () => { const existing = invitation(); const tx = buildTx([existing], mailOutbox(existing)); await expect( issueReservedOwnerInvitationWithTx(tx as never, { tenantId: TENANT_ID, ...draft({ issuanceKey: "reservation_2" }), }) ).rejects.toMatchObject({ code: "foundation.idempotency_conflict" }); expect(tx.tenantUserInvitation.create).not.toHaveBeenCalled(); expect(tx.outboxEvent.create).not.toHaveBeenCalled(); }); it("fails closed when a replay changes the OWNER identity", async () => { const existing = invitation(); const tx = buildTx([existing], mailOutbox(existing)); await expect( issueReservedOwnerInvitationWithTx(tx as never, { tenantId: TENANT_ID, ...draft({ email: "other-owner@heizkraft.example" }), }) ).rejects.toMatchObject({ code: "foundation.idempotency_conflict" }); expect(tx.tenantUserInvitation.create).not.toHaveBeenCalled(); expect(tx.outboxEvent.create).not.toHaveBeenCalled(); }); it("accepts an exact replay after a DONE mail outbox payload has been safely redacted", async () => { const existing = invitation(); const outbox = mailOutbox(existing, { status: "DONE", processedAt: new Date() }); const payload = outbox.payload as Record; delete payload.html; payload.metadata = { ...(payload.metadata as Record), secretBodyRedacted: true, }; const tx = buildTx([existing], outbox); await expect(issueReservedOwnerInvitationWithTx(tx as never, { tenantId: TENANT_ID, ...draft() })).resolves.toEqual({ invitationId: existing.id, replayed: true, }); expect(JSON.stringify(outbox.payload)).not.toContain("stored-token"); expect(tx.tenantUserInvitation.create).not.toHaveBeenCalled(); expect(tx.outboxEvent.create).not.toHaveBeenCalled(); }); it("rejects a redaction marker before the mail outbox reaches DONE", async () => { const existing = invitation(); const outbox = mailOutbox(existing); const payload = outbox.payload as Record; delete payload.html; payload.metadata = { ...(payload.metadata as Record), secretBodyRedacted: true, }; const tx = buildTx([existing], outbox); await expect(issueReservedOwnerInvitationWithTx(tx as never, { tenantId: TENANT_ID, ...draft() })).rejects.toMatchObject({ code: "foundation.idempotency_conflict", }); }); it("fails closed when the stored mail capability does not match the invitation hash", async () => { const existing = invitation(); const outbox = mailOutbox(existing); (outbox.payload.metadata as Record).invitationTokenHash = hashWorkspaceInviteToken("different-token"); const tx = buildTx([existing], outbox); await expect(issueReservedOwnerInvitationWithTx(tx as never, { tenantId: TENANT_ID, ...draft() })).rejects.toMatchObject({ code: "foundation.idempotency_conflict", }); expect(tx.tenantUserInvitation.create).not.toHaveBeenCalled(); expect(tx.outboxEvent.create).not.toHaveBeenCalled(); }); it("fails closed when a pre-redaction mail body or its retained content hash is damaged", async () => { const existing = invitation(); const damagedBody = mailOutbox(existing); (damagedBody.payload as Record).html = `${(damagedBody.payload as Record).html}

corrupted

`; const damagedHash = mailOutbox(existing); ((damagedHash.payload as Record).metadata as Record).mailContentHash = "c".repeat(64); await expect(issueReservedOwnerInvitationWithTx(buildTx([existing], damagedBody) as never, { tenantId: TENANT_ID, ...draft() })).rejects.toMatchObject({ code: "foundation.idempotency_conflict", }); await expect(issueReservedOwnerInvitationWithTx(buildTx([existing], damagedHash) as never, { tenantId: TENANT_ID, ...draft() })).rejects.toMatchObject({ code: "foundation.idempotency_conflict", }); }); it("fails closed on delivery-affecting extras before and after redaction", async () => { const existing = invitation(); const preRedaction = mailOutbox(existing); (preRedaction.payload as Record).bcc = ["attacker@example.test"]; const postRedaction = mailOutbox(existing, { status: "DONE", processedAt: new Date() }); const postPayload = postRedaction.payload as Record; delete postPayload.html; postPayload.headers = [{ name: "x-unexpected", value: "1" }]; postPayload.metadata = { ...(postPayload.metadata as Record), secretBodyRedacted: true }; await expect(issueReservedOwnerInvitationWithTx(buildTx([existing], preRedaction) as never, { tenantId: TENANT_ID, ...draft() })).rejects.toMatchObject({ code: "foundation.idempotency_conflict", }); await expect(issueReservedOwnerInvitationWithTx(buildTx([existing], postRedaction) as never, { tenantId: TENANT_ID, ...draft() })).rejects.toMatchObject({ code: "foundation.idempotency_conflict", }); }); it("rejects multiple active OWNER capabilities before writing", async () => { const tx = buildTx([invitation(), invitation({ id: "invite_second" })]); await expect(issueReservedOwnerInvitationWithTx(tx as never, { tenantId: TENANT_ID, ...draft() })).rejects.toMatchObject({ code: "foundation.idempotency_conflict", }); expect(tx.tenantUserInvitation.create).not.toHaveBeenCalled(); expect(tx.outboxEvent.create).not.toHaveBeenCalled(); }); it("refuses issuance once the reservation is active or already has a member", async () => { const activeTx = buildTx([], null, { active: true, deactivatedReason: null, _count: { users: 0 } }); const memberTx = buildTx([], null, { active: false, deactivatedReason: "pending_owner", _count: { users: 1 } }); await expect(issueReservedOwnerInvitationWithTx(activeTx as never, { tenantId: TENANT_ID, ...draft() })).rejects.toMatchObject({ code: "foundation.idempotency_conflict", }); await expect(issueReservedOwnerInvitationWithTx(memberTx as never, { tenantId: TENANT_ID, ...draft() })).rejects.toMatchObject({ code: "foundation.idempotency_conflict", }); expect(activeTx.tenantUserInvitation.create).not.toHaveBeenCalled(); expect(memberTx.tenantUserInvitation.create).not.toHaveBeenCalled(); }); it("propagates outbox failure so the surrounding reservation transaction can roll back", async () => { const tx = buildTx(); tx.outboxEvent.create.mockRejectedValueOnce(new Error("outbox unavailable")); await expect(issueReservedOwnerInvitationWithTx(tx as never, { tenantId: TENANT_ID, ...draft() })).rejects.toThrow("outbox unavailable"); expect(tx.tenantUserInvitation.create).toHaveBeenCalledOnce(); }); });