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,354 @@
// @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> = {}): ReservedOwnerInvitationDraft {
return {
issuanceKey: "reservation_1",
email: "Owner@Heizkraft.example",
firstName: "Mara",
lastName: "König",
fromUserId: ISSUER_ID,
token: TOKEN,
mail: {
subject: "Einladung",
html: `<a href="https://app.example.test/invitation/${TOKEN}">Einladung annehmen</a>`,
},
...overrides,
};
}
function invitation(overrides: Partial<TenantUserInvitation> = {}): 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<string, unknown> = {}) {
const storedToken = "s".repeat(43);
const subject = "Einladung";
const html = `<a href="https://app.example.test/invitation/${storedToken}">Einladung annehmen</a>`;
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<typeof mailOutbox> | null = null,
reservation = { active: false, deactivatedReason: "pending_owner", _count: { users: 0 } }
) {
const createdOutboxes = new Map<string, ReturnType<typeof mailOutbox>>();
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<string, unknown> }) =>
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<string, unknown> }) => {
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<typeof mailOutbox>;
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<string, unknown>;
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<string, unknown>; 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<string, unknown>;
delete payload.html;
payload.metadata = {
...(payload.metadata as Record<string, unknown>),
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<string, unknown>;
delete payload.html;
payload.metadata = {
...(payload.metadata as Record<string, unknown>),
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<string, unknown>).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<string, unknown>).html = `${(damagedBody.payload as Record<string, unknown>).html}<p>corrupted</p>`;
const damagedHash = mailOutbox(existing);
((damagedHash.payload as Record<string, unknown>).metadata as Record<string, unknown>).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<string, unknown>).bcc = ["attacker@example.test"];
const postRedaction = mailOutbox(existing, { status: "DONE", processedAt: new Date() });
const postPayload = postRedaction.payload as Record<string, unknown>;
delete postPayload.html;
postPayload.headers = [{ name: "x-unexpected", value: "1" }];
postPayload.metadata = { ...(postPayload.metadata as Record<string, unknown>), 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();
});
});
@@ -0,0 +1,287 @@
import { createHash } from "node:crypto";
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
import type { Prisma, TenantUserInvitation } from "@hivegrid/db/prisma-browser";
import {
createWorkspaceInvite,
generateWorkspaceInviteToken,
hashWorkspaceInviteToken,
WORKSPACE_INVITE_STATUS_PENDING,
type WorkspaceInviteClient,
} from "@hivegrid/db/workspace-invites.server";
import {
hashWorkspaceOwnerInvitationMailContent,
hasValidRedactedWorkspaceOwnerInvitationMailContent,
hasValidWorkspaceOwnerInvitationMailContent,
normalizeWorkspaceOwnerInvitationMailText,
normalizeWorkspaceOwnerInvitationRecipient,
readWorkspaceOwnerInvitationMailMetadata,
WORKSPACE_OWNER_INVITATION_SECRET_REDACTED_MARKER,
workspaceOwnerInvitationHashesEqual,
} from "@hivegrid/db/workspace-owner-invite-mail-contract.server";
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
import EmailTemplates from "~/modules/emails/utils/EmailTemplates";
import { getMailTranslator } from "~/locale/mail-translator.server";
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
import { getAbsoluteUrl } from "~/utils/url.server";
import { TENANT_PENDING_OWNER_REASON } from "./tenantBootstrap.constants";
const OWNER_INVITATION_SCOPE = "tenant-owner-invitation";
export type ReservedOwnerInvitationDraft = {
issuanceKey: string;
email: string;
firstName: string;
lastName: string;
fromUserId: string | null;
token: string;
mail: {
subject: string;
html: string;
};
};
export type ReservedOwnerInvitationIssuer = {
id: string | null;
firstName: string;
locale: string | null;
};
export async function prepareReservedOwnerInvitation(input: {
request: Request;
issuanceKey: string;
tenantName: string;
email: string;
firstName?: string | null;
lastName?: string | null;
issuer: ReservedOwnerInvitationIssuer;
}): Promise<ReservedOwnerInvitationDraft> {
const token = generateWorkspaceInviteToken();
const firstName = input.firstName?.trim() ?? "";
const lastName = input.lastName?.trim() ?? "";
const email = normalizeEmail(input.email);
const [mailTranslator, appConfiguration] = await Promise.all([getMailTranslator(input.issuer.locale), getAppConfiguration({ request: input.request })]);
const rendered = EmailTemplates.USER_INVITATION_EMAIL.parse({
appConfiguration,
data: {
name: firstName,
invite_sender_name: input.issuer.firstName,
invite_sender_organization: input.tenantName,
action_url: getAbsoluteUrl(input.request, `/invitation/${token}`),
},
t: mailTranslator.t,
locale: mailTranslator.locale,
});
return {
issuanceKey: input.issuanceKey,
email,
firstName,
lastName,
fromUserId: input.issuer.id,
token,
mail: { subject: rendered.subject, html: rendered.body },
};
}
/**
* Creates the single active OWNER invitation and its mail outbox row in the
* caller's reservation transaction. The raw token is persisted only as its
* invite hash and inside the dedicated mail payload.
*/
export async function issueReservedOwnerInvitationWithTx(
tx: Prisma.TransactionClient,
input: ReservedOwnerInvitationDraft & { tenantId: string }
): Promise<{ invitationId: string; replayed: boolean }> {
assertIssuanceInput(input);
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${`tenant-owner-invitation:${input.tenantId}`}, 0))`;
const reservation = await tx.tenant.findUnique({
where: { id: input.tenantId },
select: {
active: true,
deactivatedReason: true,
_count: { select: { users: true } },
},
});
if (!reservation || reservation.active || reservation.deactivatedReason !== TENANT_PENDING_OWNER_REASON || reservation._count.users !== 0) {
throw issuanceConflict(input.issuanceKey);
}
const now = new Date();
const activeInvitations = await tx.tenantUserInvitation.findMany({
where: {
tenantId: input.tenantId,
type: TenantUserType.OWNER,
status: WORKSPACE_INVITE_STATUS_PENDING,
pending: true,
acceptedAt: null,
revokedAt: null,
OR: [{ expiresAt: null }, { expiresAt: { gt: now } }],
},
orderBy: { id: "asc" },
take: 2,
});
if (activeInvitations.length > 1) throw issuanceConflict(input.issuanceKey);
const existing = activeInvitations[0];
if (existing) {
assertExactInvitation(existing, input);
const dispatchKey = ownerInvitationDispatchKey(existing.id);
const outbox = await tx.outboxEvent.findUnique({ where: { dispatchKey } });
if (!outbox || !existing.tokenHash || !isExactReservedOwnerInvitationMailReplay(outbox, input, existing.id, existing.tokenHash)) {
throw issuanceConflict(input.issuanceKey);
}
return { invitationId: existing.id, replayed: true };
}
const invitation = await createWorkspaceInvite(
{
tenantId: input.tenantId,
email: normalizeEmail(input.email),
firstName: input.firstName.trim(),
lastName: input.lastName.trim(),
type: TenantUserType.OWNER,
fromUserId: input.fromUserId,
token: input.token,
now,
},
tx as unknown as WorkspaceInviteClient
);
const invitationTokenHash = hashWorkspaceInviteToken(input.token);
const mailContentHash = hashWorkspaceOwnerInvitationMailContent({
recipient: input.email,
subject: input.mail.subject,
html: input.mail.html,
rawToken: input.token,
invitationTokenHash,
});
const outbox = await publishOutboxEvent(tx as OutboxPublisherTransaction, {
tenantId: input.tenantId,
type: "mail.transactional.send",
dispatchKey: ownerInvitationDispatchKey(invitation.id),
payload: {
tenantId: input.tenantId,
to: [normalizeEmail(input.email)],
subject: input.mail.subject,
html: input.mail.html,
priorityOverride: "critical",
metadata: {
source: "workspace-owner-invitation",
alias: "user-invitation",
invitationId: invitation.id,
invitationTokenHash,
issuanceKeyHash: hashOwnerInvitationIssuanceKey(input.issuanceKey),
mailContentHash,
},
},
});
if (!isExactReservedOwnerInvitationMailReplay(outbox, input, invitation.id, invitationTokenHash)) {
throw issuanceConflict(input.issuanceKey);
}
return { invitationId: invitation.id, replayed: false };
}
function assertIssuanceInput(input: ReservedOwnerInvitationDraft & { tenantId: string }): void {
const email = normalizeEmail(input.email);
if (
!input.tenantId.trim() ||
!input.issuanceKey.trim() ||
!email.includes("@") ||
!/^[A-Za-z0-9_-]{32,512}$/u.test(input.token) ||
!input.mail.subject.trim() ||
!input.mail.html.includes(input.token)
) {
throw issuanceConflict(input.issuanceKey);
}
}
function assertExactInvitation(invitation: TenantUserInvitation, input: ReservedOwnerInvitationDraft & { tenantId: string }): void {
if (
invitation.tenantId !== input.tenantId ||
invitation.email !== normalizeEmail(input.email) ||
invitation.firstName !== input.firstName.trim() ||
invitation.lastName !== input.lastName.trim() ||
invitation.type !== TenantUserType.OWNER ||
invitation.status !== WORKSPACE_INVITE_STATUS_PENDING ||
!invitation.pending ||
!invitation.tokenHash ||
!/^[a-f0-9]{64}$/u.test(invitation.tokenHash) ||
invitation.createdUserId !== null ||
invitation.fromUserId !== input.fromUserId ||
invitation.acceptedAt !== null ||
invitation.revokedAt !== null
) {
throw issuanceConflict(input.issuanceKey);
}
}
export function isExactReservedOwnerInvitationMailReplay(
outbox: { tenantId: string | null; eventType: string; payload: Prisma.JsonValue; status: string },
input: ReservedOwnerInvitationDraft & { tenantId: string },
invitationId: string,
invitationTokenHash: string
): boolean {
const payload = asRecord(outbox.payload);
const metadata = asRecord(payload?.metadata);
const contractMetadata = readWorkspaceOwnerInvitationMailMetadata(payload);
let expectedMailContentHash: string;
try {
expectedMailContentHash = hashWorkspaceOwnerInvitationMailContent({
recipient: input.email,
subject: input.mail.subject,
html: input.mail.html,
rawToken: input.token,
invitationTokenHash,
});
} catch {
return false;
}
const hasDeliveryBody = metadata?.[WORKSPACE_OWNER_INVITATION_SECRET_REDACTED_MARKER] !== true && hasValidWorkspaceOwnerInvitationMailContent(payload);
const hasRedactedDoneBody =
outbox.status === "DONE" &&
metadata?.[WORKSPACE_OWNER_INVITATION_SECRET_REDACTED_MARKER] === true &&
hasValidRedactedWorkspaceOwnerInvitationMailContent(payload);
return (
outbox.tenantId === input.tenantId &&
outbox.eventType === "mail.transactional.send" &&
payload?.tenantId === input.tenantId &&
Array.isArray(payload.to) &&
payload.to.length === 1 &&
typeof payload.to[0] === "string" &&
normalizeWorkspaceOwnerInvitationRecipient(payload.to[0]) === normalizeWorkspaceOwnerInvitationRecipient(input.email) &&
typeof payload.subject === "string" &&
normalizeWorkspaceOwnerInvitationMailText(payload.subject) === normalizeWorkspaceOwnerInvitationMailText(input.mail.subject) &&
(hasDeliveryBody || hasRedactedDoneBody) &&
metadata?.source === "workspace-owner-invitation" &&
metadata.alias === "user-invitation" &&
metadata.invitationId === invitationId &&
contractMetadata !== null &&
contractMetadata.invitationId === invitationId &&
workspaceOwnerInvitationHashesEqual(contractMetadata.issuanceKeyHash, hashOwnerInvitationIssuanceKey(input.issuanceKey)) &&
workspaceOwnerInvitationHashesEqual(contractMetadata.invitationTokenHash, invitationTokenHash) &&
workspaceOwnerInvitationHashesEqual(contractMetadata.mailContentHash, expectedMailContentHash)
);
}
export function hashOwnerInvitationIssuanceKey(issuanceKey: string): string {
return createHash("sha256").update(`workspace-owner-invitation:v1:${issuanceKey.trim()}`, "utf8").digest("hex");
}
function asRecord(value: unknown): Record<string, unknown> | null {
return value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : null;
}
function normalizeEmail(value: string): string {
return value.trim().toLowerCase();
}
function ownerInvitationDispatchKey(invitationId: string): string {
return `mail:workspace-owner-invite:${invitationId}`;
}
function issuanceConflict(key: string): CatalogError {
return new CatalogError(foundationErrors.idempotencyConflict, { scope: OWNER_INVITATION_SCOPE, key });
}
@@ -0,0 +1,487 @@
// @vitest-environment node
import { createHash } from "node:crypto";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { Prisma, TenantUserInvitation } from "@hivegrid/db/prisma-browser";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { hashWorkspaceOwnerInvitationMailContent } from "@hivegrid/db/workspace-owner-invite-mail-contract.server";
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
const dbMock = vi.hoisted(() => ({ $transaction: vi.fn() }));
const issuanceMock = vi.hoisted(() => ({ issueReservedOwnerInvitationWithTx: vi.fn() }));
vi.mock("~/utils/db.server", () => ({ db: dbMock }));
vi.mock("./ownerInvitationIssuance.server", async (importOriginal) => {
const original = await importOriginal<typeof import("./ownerInvitationIssuance.server")>();
return { ...original, issueReservedOwnerInvitationWithTx: issuanceMock.issueReservedOwnerInvitationWithTx };
});
import { hashOwnerInvitationIssuanceKey, type ReservedOwnerInvitationDraft } from "./ownerInvitationIssuance.server";
import { getReservedOwnerInvitationReissueTarget, reissueReservedOwnerInvitation } from "./ownerInvitationReissue.server";
const TENANT_ID = "tenant_reserved";
const OPERATOR_ID = "operator_1";
const SOURCE_ID = "invite_001";
const ISSUANCE_KEY = "93923898-e834-41e9-9e2c-0c03080e91df";
const TOKEN = "r".repeat(43);
type TestOutbox = {
tenantId: string;
eventType: string;
payload: Prisma.JsonValue;
status: string;
};
function ownerInvitation(overrides: Partial<TenantUserInvitation> = {}): TenantUserInvitation {
const token = "s".repeat(43);
return {
id: SOURCE_ID,
tenantId: TENANT_ID,
email: "owner@heizkraft.example",
firstName: "Mara",
lastName: "König",
type: TenantUserType.OWNER,
pending: true,
status: "pending",
tokenHash: createHash("sha256").update(token).digest("hex"),
tokenPrefix: token.slice(0, 12),
expiresAt: new Date("2099-01-01T00:00:00.000Z"),
acceptedAt: null,
revokedAt: null,
createdUserId: null,
fromUserId: "operator_initial",
acceptedByUserId: null,
revokedByUserId: null,
...overrides,
};
}
function draft(overrides: Partial<ReservedOwnerInvitationDraft> = {}): ReservedOwnerInvitationDraft {
return {
issuanceKey: ISSUANCE_KEY,
email: "owner@heizkraft.example",
firstName: "Mara",
lastName: "König",
fromUserId: OPERATOR_ID,
token: TOKEN,
mail: {
subject: "Einladung",
html: `<a href="https://app.example.test/invitation/${TOKEN}">Einladung annehmen</a>`,
},
...overrides,
};
}
function ownerOutbox(
invitation: TenantUserInvitation,
issuanceKey: string,
mail: { rawToken: string; subject: string; html: string } = {
rawToken: "s".repeat(43),
subject: "Einladung",
html: `<a href="https://app.example.test/invitation/${"s".repeat(43)}">Einladung annehmen</a>`,
}
): TestOutbox {
return {
tenantId: TENANT_ID,
eventType: "mail.transactional.send",
status: "PENDING",
payload: {
tenantId: TENANT_ID,
to: [invitation.email],
subject: mail.subject,
html: mail.html,
metadata: {
source: "workspace-owner-invitation",
alias: "user-invitation",
invitationId: invitation.id,
invitationTokenHash: invitation.tokenHash,
issuanceKeyHash: hashOwnerInvitationIssuanceKey(issuanceKey),
mailContentHash: hashWorkspaceOwnerInvitationMailContent({
recipient: invitation.email,
subject: mail.subject,
html: mail.html,
rawToken: mail.rawToken,
invitationTokenHash: invitation.tokenHash!,
}),
},
},
};
}
function buildHarness(
options: {
tenant?: { id: string; name: string; active: boolean; deactivatedReason: string | null; _count: { users: number } } | null;
invitations?: TenantUserInvitation[];
outboxes?: Map<string, TestOutbox>;
} = {}
) {
const tenant =
options.tenant === undefined
? { id: TENANT_ID, name: "Heizkraft GmbH", active: false, deactivatedReason: "pending_owner", _count: { users: 0 } }
: options.tenant;
const invitations = options.invitations ?? [ownerInvitation()];
const outboxes = options.outboxes ?? new Map<string, TestOutbox>();
const tx = {
$executeRaw: vi.fn().mockResolvedValue(1),
tenant: {
findUnique: vi.fn().mockImplementation(async () => {
expect(getRlsExecutionContext()).toMatchObject({ tenantId: TENANT_ID, userId: OPERATOR_ID });
return tenant;
}),
},
tenantUserInvitation: {
findMany: vi.fn().mockImplementation(async () => [...invitations].sort((left, right) => right.id.localeCompare(left.id))),
updateMany: vi.fn().mockImplementation(async ({ where, data }: { where: Record<string, unknown>; data: Record<string, unknown> }) => {
const invitation = invitations.find((candidate) => candidate.id === where.id);
if (
!invitation ||
invitation.tenantId !== where.tenantId ||
invitation.status !== "pending" ||
!invitation.pending ||
invitation.acceptedAt !== null ||
invitation.revokedAt !== null ||
invitation.createdUserId !== null
) {
return { count: 0 };
}
Object.assign(invitation, data);
return { count: 1 };
}),
},
outboxEvent: {
findUnique: vi.fn().mockImplementation(async ({ where }: { where: { dispatchKey: string } }) => outboxes.get(where.dispatchKey) ?? null),
},
};
return { tx, tenant, invitations, outboxes };
}
function installTransactionHarness(tx: ReturnType<typeof buildHarness>["tx"]): void {
let tail = Promise.resolve();
dbMock.$transaction.mockImplementation((callback: (transaction: typeof tx) => Promise<unknown>) => {
const result = tail.then(() => callback(tx));
tail = result.then(
() => undefined,
() => undefined
);
return result;
});
}
function runAsOperator<T>(callback: () => T): T {
return runWithRlsContext({ userId: OPERATOR_ID }, callback);
}
describe("reserved OWNER invitation reissue", () => {
beforeEach(() => {
vi.clearAllMocks();
issuanceMock.issueReservedOwnerInvitationWithTx.mockResolvedValue({ invitationId: "invite_002", replayed: false });
});
it("resolves one case-normalized identity while isolating an unrelated tenant context", async () => {
const harness = buildHarness({ invitations: [ownerInvitation({ email: " Owner@Heizkraft.Example " })] });
installTransactionHarness(harness.tx);
const target = await runWithRlsContext({ userId: OPERATOR_ID, tenantId: "tenant_previous" }, async () => {
const result = await getReservedOwnerInvitationReissueTarget({ tenantId: TENANT_ID, operatorUserId: OPERATOR_ID });
expect(getRlsExecutionContext()).toMatchObject({ userId: OPERATOR_ID, tenantId: "tenant_previous" });
return result;
});
expect(target).toEqual({
invitationId: SOURCE_ID,
tenantName: "Heizkraft GmbH",
email: "owner@heizkraft.example",
firstName: "Mara",
lastName: "König",
});
expect(harness.tx.tenantUserInvitation.findMany).toHaveBeenCalledWith(
expect.objectContaining({ where: { tenantId: TENANT_ID, type: TenantUserType.OWNER }, take: 3 })
);
});
it("requires the current RLS user to be the exact operator", async () => {
const harness = buildHarness();
installTransactionHarness(harness.tx);
await expect(getReservedOwnerInvitationReissueTarget({ tenantId: TENANT_ID, operatorUserId: OPERATOR_ID })).rejects.toMatchObject({
code: "foundation.not_found",
});
await expect(
runWithRlsContext({ userId: "operator_other" }, () =>
reissueReservedOwnerInvitation({
tenantId: TENANT_ID,
operatorUserId: OPERATOR_ID,
sourceInvitationId: SOURCE_ID,
ownerInvitation: draft(),
})
)
).rejects.toMatchObject({ code: "foundation.not_found" });
expect(dbMock.$transaction).not.toHaveBeenCalled();
});
it.each([
["active", { id: TENANT_ID, name: "Heizkraft GmbH", active: true, deactivatedReason: null, _count: { users: 0 } }],
["wrong reason", { id: TENANT_ID, name: "Heizkraft GmbH", active: false, deactivatedReason: "billing", _count: { users: 0 } }],
["membership exists", { id: TENANT_ID, name: "Heizkraft GmbH", active: false, deactivatedReason: "pending_owner", _count: { users: 1 } }],
])("refuses an ownerless reservation whose tenant is %s", async (_label, tenant) => {
const harness = buildHarness({ tenant });
installTransactionHarness(harness.tx);
await expect(
runAsOperator(() =>
reissueReservedOwnerInvitation({
tenantId: TENANT_ID,
operatorUserId: OPERATOR_ID,
sourceInvitationId: SOURCE_ID,
ownerInvitation: draft(),
})
)
).rejects.toMatchObject({ code: "foundation.not_found" });
expect(harness.tx.tenantUserInvitation.updateMany).not.toHaveBeenCalled();
expect(issuanceMock.issueReservedOwnerInvitationWithTx).not.toHaveBeenCalled();
});
it("fails closed for ambiguous identities or a capability already bound to a user", async () => {
const ambiguous = buildHarness({
invitations: [ownerInvitation({ id: "invite_002", email: "other@heizkraft.example" }), ownerInvitation()],
});
installTransactionHarness(ambiguous.tx);
await expect(runAsOperator(() => getReservedOwnerInvitationReissueTarget({ tenantId: TENANT_ID, operatorUserId: OPERATOR_ID }))).rejects.toMatchObject({
code: "foundation.not_found",
});
const bound = buildHarness({ invitations: [ownerInvitation({ createdUserId: "owner_user" })] });
installTransactionHarness(bound.tx);
await expect(runAsOperator(() => getReservedOwnerInvitationReissueTarget({ tenantId: TENANT_ID, operatorUserId: OPERATOR_ID }))).rejects.toMatchObject({
code: "foundation.not_found",
});
});
it("locks the reservation, conditionally revokes an active source, and then issues the replacement", async () => {
const harness = buildHarness();
installTransactionHarness(harness.tx);
await expect(
runAsOperator(() =>
reissueReservedOwnerInvitation({
tenantId: TENANT_ID,
operatorUserId: OPERATOR_ID,
sourceInvitationId: SOURCE_ID,
ownerInvitation: draft(),
})
)
).resolves.toEqual({ invitationId: "invite_002", replayed: false });
expect(harness.tx.$executeRaw).toHaveBeenCalledOnce();
expect(String(harness.tx.$executeRaw.mock.calls[0]?.[0])).toContain("pg_advisory_xact_lock");
expect(harness.tx.tenantUserInvitation.updateMany).toHaveBeenCalledWith({
where: expect.objectContaining({
id: SOURCE_ID,
tenantId: TENANT_ID,
type: TenantUserType.OWNER,
pending: true,
status: "pending",
createdUserId: null,
acceptedAt: null,
revokedAt: null,
}),
data: expect.objectContaining({ pending: false, status: "revoked", revokedByUserId: OPERATOR_ID }),
});
expect(issuanceMock.issueReservedOwnerInvitationWithTx).toHaveBeenCalledWith(harness.tx, {
tenantId: TENANT_ID,
...draft(),
});
expect(harness.tx.tenantUserInvitation.updateMany.mock.invocationCallOrder[0]).toBeLessThan(
issuanceMock.issueReservedOwnerInvitationWithTx.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY
);
});
it("rotates an expired source and does not depend on it still being active", async () => {
const harness = buildHarness({ invitations: [ownerInvitation({ expiresAt: new Date("2000-01-01T00:00:00.000Z") })] });
installTransactionHarness(harness.tx);
await expect(
runAsOperator(() =>
reissueReservedOwnerInvitation({
tenantId: TENANT_ID,
operatorUserId: OPERATOR_ID,
sourceInvitationId: SOURCE_ID,
ownerInvitation: draft(),
})
)
).resolves.toEqual({ invitationId: "invite_002", replayed: false });
expect(harness.tx.tenantUserInvitation.updateMany).toHaveBeenCalledOnce();
expect(issuanceMock.issueReservedOwnerInvitationWithTx).toHaveBeenCalledOnce();
});
it("rotates a delivery-failed source only through a fresh OWNER capability", async () => {
const harness = buildHarness({
invitations: [
ownerInvitation({
pending: false,
status: "delivery_failed",
revokedAt: new Date("2026-07-15T10:00:00.000Z"),
revokedByUserId: null,
}),
],
});
installTransactionHarness(harness.tx);
await expect(
runAsOperator(() =>
reissueReservedOwnerInvitation({
tenantId: TENANT_ID,
operatorUserId: OPERATOR_ID,
sourceInvitationId: SOURCE_ID,
ownerInvitation: draft(),
})
)
).resolves.toEqual({ invitationId: "invite_002", replayed: false });
expect(harness.tx.tenantUserInvitation.updateMany).not.toHaveBeenCalled();
expect(issuanceMock.issueReservedOwnerInvitationWithTx).toHaveBeenCalledOnce();
});
it("accepts a stale source only when the active replacement proves the same issuance key", async () => {
const oldSource = ownerInvitation({
pending: false,
status: "revoked",
revokedAt: new Date("2026-07-15T10:00:00.000Z"),
revokedByUserId: OPERATOR_ID,
});
const replacement = ownerInvitation({ id: "invite_002", fromUserId: OPERATOR_ID });
const outboxes = new Map([["mail:workspace-owner-invite:invite_002", ownerOutbox(replacement, ISSUANCE_KEY)]]);
const harness = buildHarness({ invitations: [replacement, oldSource], outboxes });
installTransactionHarness(harness.tx);
await expect(
runAsOperator(() =>
reissueReservedOwnerInvitation({
tenantId: TENANT_ID,
operatorUserId: OPERATOR_ID,
sourceInvitationId: SOURCE_ID,
ownerInvitation: draft(),
})
)
).resolves.toEqual({ invitationId: replacement.id, replayed: true });
expect(harness.tx.tenantUserInvitation.updateMany).not.toHaveBeenCalled();
expect(issuanceMock.issueReservedOwnerInvitationWithTx).not.toHaveBeenCalled();
});
it("replays an HTTP response-loss retry with a freshly rendered token without rotating the active replacement", async () => {
const oldSource = ownerInvitation({
pending: false,
status: "revoked",
revokedAt: new Date("2026-07-15T10:00:00.000Z"),
revokedByUserId: OPERATOR_ID,
});
const replacement = ownerInvitation({ id: "invite_002", fromUserId: OPERATOR_ID });
const outboxes = new Map([["mail:workspace-owner-invite:invite_002", ownerOutbox(replacement, ISSUANCE_KEY)]]);
const harness = buildHarness({ invitations: [replacement, oldSource], outboxes });
installTransactionHarness(harness.tx);
const freshlyRenderedDraft = draft({
token: "fresh-response-loss-token".padEnd(43, "x"),
mail: {
subject: "Einladung",
html: `<a href="https://app.example.test/invitation/${"fresh-response-loss-token".padEnd(43, "x")}">Einladung annehmen</a>`,
},
});
await expect(
runAsOperator(() =>
reissueReservedOwnerInvitation({
tenantId: TENANT_ID,
operatorUserId: OPERATOR_ID,
sourceInvitationId: replacement.id,
ownerInvitation: freshlyRenderedDraft,
})
)
).resolves.toEqual({ invitationId: replacement.id, replayed: true });
expect(harness.tx.tenantUserInvitation.updateMany).not.toHaveBeenCalled();
expect(issuanceMock.issueReservedOwnerInvitationWithTx).not.toHaveBeenCalled();
});
it("fails closed when a stale source races with a different issuance key", async () => {
const oldSource = ownerInvitation({
pending: false,
status: "revoked",
revokedAt: new Date("2026-07-15T10:00:00.000Z"),
revokedByUserId: OPERATOR_ID,
});
const replacement = ownerInvitation({ id: "invite_002", fromUserId: OPERATOR_ID });
const outboxes = new Map([["mail:workspace-owner-invite:invite_002", ownerOutbox(replacement, "different-key")]]);
const harness = buildHarness({ invitations: [replacement, oldSource], outboxes });
installTransactionHarness(harness.tx);
await expect(
runAsOperator(() =>
reissueReservedOwnerInvitation({
tenantId: TENANT_ID,
operatorUserId: OPERATOR_ID,
sourceInvitationId: SOURCE_ID,
ownerInvitation: draft(),
})
)
).rejects.toMatchObject({ code: "foundation.idempotency_conflict" });
expect(harness.tx.tenantUserInvitation.updateMany).not.toHaveBeenCalled();
expect(issuanceMock.issueReservedOwnerInvitationWithTx).not.toHaveBeenCalled();
});
it("serializes concurrent same-key rotations and replays the one replacement", async () => {
const harness = buildHarness();
installTransactionHarness(harness.tx);
issuanceMock.issueReservedOwnerInvitationWithTx.mockImplementation(async (_tx, input) => {
const existing = harness.invitations.find((invitation) => invitation.id === "invite_002");
if (existing) {
return { invitationId: existing.id, replayed: true };
}
const replacement = ownerInvitation({
id: "invite_002",
email: input.email,
firstName: input.firstName,
lastName: input.lastName,
fromUserId: input.fromUserId,
tokenHash: createHash("sha256").update(input.token).digest("hex"),
tokenPrefix: input.token.slice(0, 12),
});
harness.invitations.push(replacement);
harness.outboxes.set(
"mail:workspace-owner-invite:invite_002",
ownerOutbox(replacement, input.issuanceKey, {
rawToken: input.token,
subject: input.mail.subject,
html: input.mail.html,
})
);
return { invitationId: replacement.id, replayed: false };
});
const request = () =>
runAsOperator(() =>
reissueReservedOwnerInvitation({
tenantId: TENANT_ID,
operatorUserId: OPERATOR_ID,
sourceInvitationId: SOURCE_ID,
ownerInvitation: draft(),
})
);
const results = await Promise.all([request(), request()]);
expect(results).toEqual(
expect.arrayContaining([
{ invitationId: "invite_002", replayed: false },
{ invitationId: "invite_002", replayed: true },
])
);
expect(harness.tx.tenantUserInvitation.updateMany).toHaveBeenCalledOnce();
expect(issuanceMock.issueReservedOwnerInvitationWithTx).toHaveBeenCalledOnce();
});
});
@@ -0,0 +1,339 @@
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import type { Prisma, TenantUserInvitation } from "@hivegrid/db/prisma-browser";
import { getRlsExecutionContext, runWithIsolatedUserRlsContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import {
WORKSPACE_INVITE_STATUS_ACCEPTED,
WORKSPACE_INVITE_STATUS_DELIVERY_FAILED,
WORKSPACE_INVITE_STATUS_EXPIRED,
WORKSPACE_INVITE_STATUS_PENDING,
WORKSPACE_INVITE_STATUS_REVOKED,
} from "@hivegrid/db/workspace-invites.server";
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
import { db } from "~/utils/db.server";
import { TENANT_PENDING_OWNER_REASON } from "./tenantBootstrap.constants";
import {
isExactReservedOwnerInvitationMailReplay,
issueReservedOwnerInvitationWithTx,
type ReservedOwnerInvitationDraft,
} from "./ownerInvitationIssuance.server";
const OWNER_INVITATION_REISSUE_SCOPE = "tenant-owner-invitation-reissue";
type OwnerIdentity = {
email: string;
firstName: string;
lastName: string;
};
export type ReservedOwnerInvitationReissueTarget = OwnerIdentity & {
invitationId: string;
tenantName: string;
};
export type ReservedOwnerInvitationReissueInput = {
tenantId: string;
operatorUserId: string;
sourceInvitationId: string;
ownerInvitation: ReservedOwnerInvitationDraft;
};
/**
* Resolves the only safe OWNER identity that may be rotated. Mail rendering is
* deliberately performed by the caller after this transaction has completed.
*/
export async function getReservedOwnerInvitationReissueTarget(input: {
tenantId: string;
operatorUserId: string;
}): Promise<ReservedOwnerInvitationReissueTarget> {
assertAuthenticatedOperator(input.operatorUserId);
assertIdentifier(input.tenantId);
return runInReservationTenantContext(input.tenantId, input.operatorUserId, () =>
db.$transaction(async (tx) => {
const { tenant, invitations } = await loadReservationState(tx, input.tenantId);
assertOwnerlessReservation(tenant);
const invitationSet = assertUnambiguousOwnerInvitationSet(invitations, input.tenantId, new Date());
return {
invitationId: invitationSet.latest.id,
tenantName: tenant.name,
...invitationSet.identity,
};
})
);
}
/**
* Atomically terminalizes the expected OWNER capability and issues its
* replacement. The stable issuance key makes a parallel or response-loss
* retry replay the already-created replacement instead of rotating it again.
*/
export async function reissueReservedOwnerInvitation(input: ReservedOwnerInvitationReissueInput): Promise<{ invitationId: string; replayed: boolean }> {
assertAuthenticatedOperator(input.operatorUserId);
assertIdentifier(input.tenantId);
assertIdentifier(input.sourceInvitationId);
if (input.ownerInvitation.fromUserId !== input.operatorUserId) {
throw reissueNotFound();
}
const requestedIdentity = normalizeOwnerIdentity(input.ownerInvitation);
if (!isValidOwnerIdentity(requestedIdentity) || !input.ownerInvitation.issuanceKey.trim()) {
throw reissueConflict(input.ownerInvitation.issuanceKey);
}
return runInReservationTenantContext(input.tenantId, input.operatorUserId, () =>
db.$transaction(async (tx) => {
await acquireOwnerInvitationLock(tx, input.tenantId);
const now = new Date();
const { tenant, invitations } = await loadReservationState(tx, input.tenantId);
assertOwnerlessReservation(tenant);
const invitationSet = assertUnambiguousOwnerInvitationSet(invitations, input.tenantId, now);
if (!ownerIdentitiesEqual(invitationSet.identity, requestedIdentity)) {
throw reissueConflict(input.ownerInvitation.issuanceKey);
}
const source = invitations.find((invitation) => invitation.id === input.sourceInvitationId);
if (!source || !isEligibleOwnerInvitation(source, input.tenantId, invitationSet.identity, now)) {
throw reissueConflict(input.ownerInvitation.issuanceKey);
}
const activeInvitations = invitations.filter((invitation) => isActiveOwnerInvitation(invitation, now));
if (activeInvitations.length > 1) {
throw reissueConflict(input.ownerInvitation.issuanceKey);
}
const activeInvitation = activeInvitations[0];
if (
activeInvitation?.fromUserId === input.operatorUserId &&
(await hasMatchingInvitationReplay(tx, activeInvitation, input.ownerInvitation))
) {
// A response-loss retry renders a fresh raw token before entering this
// transaction. The mail contract normalizes that token against the
// already persisted invitation hash, so the same logical issuance key
// replays the committed capability without another rotation.
return { invitationId: activeInvitation.id, replayed: true };
}
if (invitationSet.latest.id !== source.id || (activeInvitation && activeInvitation.id !== source.id)) {
throw reissueConflict(input.ownerInvitation.issuanceKey);
}
if (isPendingInvitation(source)) {
const transition = await tx.tenantUserInvitation.updateMany({
where: {
id: source.id,
tenantId: input.tenantId,
type: TenantUserType.OWNER,
email: source.email,
firstName: source.firstName,
lastName: source.lastName,
pending: true,
status: WORKSPACE_INVITE_STATUS_PENDING,
createdUserId: null,
acceptedAt: null,
revokedAt: null,
acceptedByUserId: null,
revokedByUserId: null,
},
data: {
pending: false,
status: WORKSPACE_INVITE_STATUS_REVOKED,
revokedAt: now,
revokedByUserId: input.operatorUserId,
},
});
if (transition.count !== 1) {
throw reissueConflict(input.ownerInvitation.issuanceKey);
}
}
return issueReservedOwnerInvitationWithTx(tx, { tenantId: input.tenantId, ...input.ownerInvitation });
})
);
}
type ReservationState = {
tenant: {
id: string;
name: string;
active: boolean;
deactivatedReason: string | null;
_count: { users: number };
} | null;
invitations: TenantUserInvitation[];
};
async function loadReservationState(tx: Prisma.TransactionClient, tenantId: string): Promise<ReservationState> {
const tenant = await tx.tenant.findUnique({
where: { id: tenantId },
select: {
id: true,
name: true,
active: true,
deactivatedReason: true,
_count: { select: { users: true } },
},
});
const invitations = await tx.tenantUserInvitation.findMany({
where: { tenantId, type: TenantUserType.OWNER },
orderBy: { id: "desc" },
// The UI submits the latest capability; an exact response-loss replay can
// reference only its immediate predecessor. Older history is never a valid
// rotation source and must not make request latency grow without bound.
take: 3,
});
return { tenant, invitations };
}
function assertOwnerlessReservation(tenant: ReservationState["tenant"]): asserts tenant is NonNullable<ReservationState["tenant"]> {
if (!tenant || tenant.active || tenant.deactivatedReason !== TENANT_PENDING_OWNER_REASON || tenant._count.users !== 0) {
throw reissueNotFound();
}
}
function assertUnambiguousOwnerInvitationSet(
invitations: TenantUserInvitation[],
tenantId: string,
now: Date
): { latest: TenantUserInvitation; identity: OwnerIdentity } {
const latest = invitations[0];
if (!latest) {
throw reissueNotFound();
}
const identity = normalizeOwnerIdentity(latest);
if (!isValidOwnerIdentity(identity)) {
throw reissueNotFound();
}
for (const invitation of invitations) {
if (!isEligibleOwnerInvitation(invitation, tenantId, identity, now)) {
throw reissueNotFound();
}
}
const activeInvitations = invitations.filter((invitation) => isActiveOwnerInvitation(invitation, now));
if (activeInvitations.length > 1 || (activeInvitations[0] && activeInvitations[0].id !== latest.id)) {
throw reissueNotFound();
}
return { latest, identity };
}
function isEligibleOwnerInvitation(invitation: TenantUserInvitation, tenantId: string, identity: OwnerIdentity, now: Date): boolean {
if (
invitation.tenantId !== tenantId ||
invitation.type !== TenantUserType.OWNER ||
invitation.status === WORKSPACE_INVITE_STATUS_ACCEPTED ||
invitation.createdUserId !== null ||
invitation.acceptedAt !== null ||
invitation.acceptedByUserId !== null ||
!ownerIdentitiesEqual(normalizeOwnerIdentity(invitation), identity) ||
!invitation.tokenHash ||
!/^[a-f0-9]{64}$/u.test(invitation.tokenHash)
) {
return false;
}
if (isPendingInvitation(invitation)) {
return invitation.revokedAt === null && invitation.revokedByUserId === null;
}
if (invitation.status === WORKSPACE_INVITE_STATUS_REVOKED) {
return !invitation.pending && invitation.revokedAt !== null && invitation.revokedByUserId !== null;
}
if (invitation.status === WORKSPACE_INVITE_STATUS_DELIVERY_FAILED) {
return !invitation.pending && invitation.revokedAt !== null && invitation.revokedByUserId === null;
}
if (invitation.status === WORKSPACE_INVITE_STATUS_EXPIRED) {
return (
!invitation.pending &&
invitation.revokedAt === null &&
invitation.revokedByUserId === null &&
invitation.expiresAt !== null &&
invitation.expiresAt <= now
);
}
return false;
}
function isPendingInvitation(invitation: TenantUserInvitation): boolean {
return invitation.status === WORKSPACE_INVITE_STATUS_PENDING && invitation.pending;
}
function isActiveOwnerInvitation(invitation: TenantUserInvitation, now: Date): boolean {
return isPendingInvitation(invitation) && invitation.revokedAt === null && (invitation.expiresAt === null || invitation.expiresAt > now);
}
async function hasMatchingInvitationReplay(
tx: Prisma.TransactionClient,
invitation: TenantUserInvitation,
ownerInvitation: ReservedOwnerInvitationDraft
): Promise<boolean> {
const outbox = await tx.outboxEvent.findUnique({
where: { dispatchKey: ownerInvitationDispatchKey(invitation.id) },
select: { tenantId: true, eventType: true, payload: true, status: true },
});
if (!outbox || !invitation.tokenHash) {
return false;
}
return isExactReservedOwnerInvitationMailReplay(outbox, { tenantId: invitation.tenantId, ...ownerInvitation }, invitation.id, invitation.tokenHash);
}
function acquireOwnerInvitationLock(tx: Prisma.TransactionClient, tenantId: string): Promise<unknown> {
return tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${`tenant-owner-invitation:${tenantId}`}, 0))`;
}
function runInReservationTenantContext<T>(tenantId: string, operatorUserId: string, callback: () => T): T {
const current = getRlsExecutionContext();
if (!current || current.userId !== operatorUserId) {
throw reissueNotFound();
}
const run = () => runWithRlsContext({ tenantId, userId: operatorUserId }, callback);
if (current.tenantId !== undefined || current.transaction !== undefined || current.publicKnowledgeBaseId !== undefined) {
return runWithIsolatedUserRlsContext(operatorUserId, run);
}
return run();
}
function normalizeOwnerIdentity(input: Pick<TenantUserInvitation, "email" | "firstName" | "lastName"> | ReservedOwnerInvitationDraft): OwnerIdentity {
return {
email: input.email.trim().toLowerCase(),
firstName: input.firstName.trim(),
lastName: input.lastName.trim(),
};
}
function isValidOwnerIdentity(identity: OwnerIdentity): boolean {
return /^[^@\s]+@[^@\s]+\.[^@\s]+$/u.test(identity.email) && Boolean(identity.firstName && identity.lastName);
}
function ownerIdentitiesEqual(left: OwnerIdentity, right: OwnerIdentity): boolean {
return left.email === right.email && left.firstName === right.firstName && left.lastName === right.lastName;
}
function ownerInvitationDispatchKey(invitationId: string): string {
return `mail:workspace-owner-invite:${invitationId}`;
}
function assertAuthenticatedOperator(operatorUserId: string): void {
if (!operatorUserId.trim() || getRlsExecutionContext()?.userId !== operatorUserId) {
throw reissueNotFound();
}
}
function assertIdentifier(value: string): void {
if (!value.trim() || value !== value.trim() || value.length > 191 || value.includes("\u0000")) {
throw reissueNotFound();
}
}
function reissueNotFound(): CatalogError {
return new CatalogError(foundationErrors.notFound, { resource: OWNER_INVITATION_REISSUE_SCOPE });
}
function reissueConflict(key: string): CatalogError {
return new CatalogError(foundationErrors.idempotencyConflict, { scope: OWNER_INVITATION_REISSUE_SCOPE, key });
}
@@ -0,0 +1,111 @@
import { describe, expect, it } from "vitest";
import { defaultPermissionSeeds } from "@hivegrid/db/permissions-seed.server";
import { shkTemplateRoleSeeds } from "@hivegrid/db/shk-template-roles-seed.server";
import { digestShkV2TenantBootstrapConfig, SHK_V2_TENANT_BOOTSTRAP_CONFIG, shkV2TenantBootstrapConfigSchema } from "./shk-v2.config";
describe("SHK v2 tenant bootstrap config", () => {
it("is schema-valid, versioned and references the single global Admin owner role", () => {
expect(shkV2TenantBootstrapConfigSchema.safeParse(SHK_V2_TENANT_BOOTSTRAP_CONFIG).success).toBe(true);
expect(SHK_V2_TENANT_BOOTSTRAP_CONFIG.templateKey).toBe("shk-v2");
expect(SHK_V2_TENANT_BOOTSTRAP_CONFIG.ownerRole).toEqual({ name: "Admin", type: "app", ownership: "global" });
});
it("defines exactly the five decided editable tenant roles from conservative registered permissions", () => {
expect(SHK_V2_TENANT_BOOTSTRAP_CONFIG.tenantRoles.map((role) => role.name)).toEqual([
"Vertrieb",
"Marketing",
"Innendienst",
"Buchhaltung/Verwaltung",
"Monteur",
]);
const validPermissionKeys = new Set<string>(defaultPermissionSeeds);
for (const role of SHK_V2_TENANT_BOOTSTRAP_CONFIG.tenantRoles) {
expect(role.isTemplateOrigin).toBe(true);
expect(
role.permissionKeys.every((key) => validPermissionKeys.has(key)),
`${role.name} references an unknown permission`
).toBe(true);
expect(
role.permissionKeys.some((key) => key.startsWith("admin.")),
`${role.name} references an operator permission`
).toBe(false);
expect(new Set(role.permissionKeys).size).toBe(role.permissionKeys.length);
}
});
it("derives Vertrieb, Marketing, Innendienst and Monteur from the existing validated role baselines", () => {
const existing = new Map(shkTemplateRoleSeeds.map((role) => [role.name, role.permissionKeys]));
const configured = new Map(SHK_V2_TENANT_BOOTSTRAP_CONFIG.tenantRoles.map((role) => [role.name, role.permissionKeys]));
expect(configured.get("Vertrieb")).toEqual(existing.get("Vertriebler"));
expect(configured.get("Marketing")).toEqual(existing.get("Marketing"));
expect(configured.get("Monteur")).toEqual(existing.get("Monteur"));
expect(configured.get("Innendienst")).toEqual(existing.get("Büro/Backoffice")?.filter((key) => key !== "app.settings.subscription.view"));
expect(configured.get("Innendienst")?.some((key) => key.includes("subscription") || key.includes("invoice"))).toBe(false);
});
it("keeps Buchhaltung/Verwaltung read-only and limited to existing administration and subscription views", () => {
const accounting = SHK_V2_TENANT_BOOTSTRAP_CONFIG.tenantRoles.find((role) => role.name === "Buchhaltung/Verwaltung");
expect(accounting?.permissionKeys).toEqual([
"app.settings.members.view",
"app.settings.account.view",
"app.settings.subscription.view",
"app.settings.subscription.invoices.view",
"dashboard.read",
]);
expect(accounting?.permissionKeys.some((key) => /(?:create|update|delete|write|manage|admin|set)$/.test(key))).toBe(false);
});
it("defines three sales pipelines with the validated stage and lost-reason baselines", () => {
expect(SHK_V2_TENANT_BOOTSTRAP_CONFIG.salesPipelines.map(({ name, isDefault }) => ({ name, isDefault }))).toEqual([
{ name: "Vertrieb Wärmepumpe", isDefault: true },
{ name: "Vertrieb Photovoltaik", isDefault: false },
{ name: "Vertrieb Badezimmer", isDefault: false },
]);
const expectedStages = [
{ name: "Neu", stageKind: "offen", winProbability: 10, color: "#64748b", position: 10 },
{ name: "Qualifiziert", stageKind: "offen", winProbability: 30, color: "#0ea5e9", position: 20 },
{ name: "Angebot", stageKind: "offen", winProbability: 60, color: "#f59e0b", position: 30 },
{ name: "Gewonnen", stageKind: "gewonnen", winProbability: 100, color: "#16a34a", position: 40 },
{ name: "Verloren", stageKind: "verloren", winProbability: 0, color: "#dc2626", position: 50 },
];
for (const pipeline of SHK_V2_TENANT_BOOTSTRAP_CONFIG.salesPipelines) {
expect(pipeline.stages).toEqual(expectedStages);
}
expect(SHK_V2_TENANT_BOOTSTRAP_CONFIG.salesLostReasons).toEqual(["Preis", "Zeitpunkt", "Kein Bedarf", "Wettbewerber", "Nicht erreichbar"]);
});
it("keeps all three automation placeholders unpublished and non-executable behind explicit gates", () => {
expect(SHK_V2_TENANT_BOOTSTRAP_CONFIG.automationPlaceholders.map((placeholder) => placeholder.templateKey)).toEqual([
"shk.order-thank-you.v1",
"shk.kwp-project-routing.v1",
"shk.follow-up-reminder.v1",
]);
for (const placeholder of SHK_V2_TENANT_BOOTSTRAP_CONFIG.automationPlaceholders) {
expect(placeholder.isPublished).toBe(false);
expect(placeholder.isExecutable).toBe(false);
expect(placeholder.nodes).toEqual([]);
expect(placeholder.activationGates.length).toBeGreaterThan(0);
}
});
it("produces a canonical SHA-256 digest independent of object key insertion order", () => {
const digest = digestShkV2TenantBootstrapConfig();
expect(digest).toBe("6f37bd4b1f71174dcc677e6111161aa558d5d5a08fc9fb4e2a19136d4afdcdf9");
const reordered = {
automationPlaceholders: SHK_V2_TENANT_BOOTSTRAP_CONFIG.automationPlaceholders,
salesLostReasons: SHK_V2_TENANT_BOOTSTRAP_CONFIG.salesLostReasons,
salesPipelines: SHK_V2_TENANT_BOOTSTRAP_CONFIG.salesPipelines,
tenantRoles: SHK_V2_TENANT_BOOTSTRAP_CONFIG.tenantRoles,
ownerRole: SHK_V2_TENANT_BOOTSTRAP_CONFIG.ownerRole,
schemaVersion: SHK_V2_TENANT_BOOTSTRAP_CONFIG.schemaVersion,
templateKey: SHK_V2_TENANT_BOOTSTRAP_CONFIG.templateKey,
};
expect(digestShkV2TenantBootstrapConfig(reordered)).toBe(digest);
});
});
@@ -0,0 +1,366 @@
import { createHash } from "node:crypto";
import { z } from "zod";
import { DEFAULT_SALES_LOST_REASONS, DEFAULT_SALES_PIPELINE_STAGES } from "~/utils/integrations/projects/salesPipelineDefaults";
const CONFIG_VALIDATION_MESSAGE = {
permissionKeysUnique: "Permission keys must be unique",
pipelineStageNamesUnique: "Pipeline stage names must be unique",
pipelineWonStageRequired: "A pipeline needs exactly one won stage",
pipelineLostStageRequired: "A pipeline needs exactly one lost stage",
pipelineOpenStageRequired: "A pipeline needs at least one open stage",
activationGatesUnique: "Activation gates must be unique",
tenantRoleNamesUnique: "Tenant role names must be unique",
salesPipelineNamesUnique: "Pipeline names must be unique",
defaultSalesPipelineInvalid: "Vertrieb Wärmepumpe must be the only default pipeline",
lostReasonsUnique: "Lost reasons must be unique",
automationTemplateKeysUnique: "Automation template keys must be unique",
} as const;
const permissionKeySchema = z
.string()
.trim()
.min(1)
.refine((key) => !key.startsWith("admin."), "Tenant roles cannot reference operator permissions");
const tenantRoleSchema = z
.object({
name: z.enum(["Vertrieb", "Marketing", "Innendienst", "Buchhaltung/Verwaltung", "Monteur"]),
descriptionKey: z.string().regex(/^tenantBootstrap\.roles\.[a-z][A-Za-z]*\.description$/),
type: z.literal("app"),
assignToNewUsers: z.literal(false),
isDefault: z.literal(false),
order: z.number().int().min(100),
seatCategory: z.enum(["office", "field"]),
isTemplateOrigin: z.literal(true),
permissionKeys: z.array(permissionKeySchema).min(1),
})
.strict()
.superRefine((role, context) => {
if (new Set(role.permissionKeys).size !== role.permissionKeys.length) {
context.addIssue({ code: z.ZodIssueCode.custom, path: ["permissionKeys"], message: CONFIG_VALIDATION_MESSAGE.permissionKeysUnique });
}
});
const pipelineStageSchema = z
.object({
name: z.enum(["Neu", "Qualifiziert", "Angebot", "Gewonnen", "Verloren"]),
stageKind: z.enum(["offen", "gewonnen", "verloren"]),
winProbability: z.number().int().min(0).max(100),
color: z.string().regex(/^#[0-9a-f]{6}$/i),
position: z.number().int().positive(),
})
.strict();
const salesPipelineSchema = z
.object({
name: z.enum(["Vertrieb Wärmepumpe", "Vertrieb Photovoltaik", "Vertrieb Badezimmer"]),
typHint: z.literal("sales"),
position: z.number().int().positive(),
isDefault: z.boolean(),
isDemoData: z.literal(false),
stages: z.array(pipelineStageSchema).length(5),
})
.strict()
.superRefine((pipeline, context) => {
if (new Set(pipeline.stages.map((stage) => stage.name)).size !== pipeline.stages.length) {
context.addIssue({ code: z.ZodIssueCode.custom, path: ["stages"], message: CONFIG_VALIDATION_MESSAGE.pipelineStageNamesUnique });
}
if (pipeline.stages.filter((stage) => stage.stageKind === "gewonnen").length !== 1) {
context.addIssue({ code: z.ZodIssueCode.custom, path: ["stages"], message: CONFIG_VALIDATION_MESSAGE.pipelineWonStageRequired });
}
if (pipeline.stages.filter((stage) => stage.stageKind === "verloren").length !== 1) {
context.addIssue({ code: z.ZodIssueCode.custom, path: ["stages"], message: CONFIG_VALIDATION_MESSAGE.pipelineLostStageRequired });
}
if (!pipeline.stages.some((stage) => stage.stageKind === "offen")) {
context.addIssue({ code: z.ZodIssueCode.custom, path: ["stages"], message: CONFIG_VALIDATION_MESSAGE.pipelineOpenStageRequired });
}
});
const automationPlaceholderSchema = z
.object({
templateKey: z.enum(["shk.order-thank-you.v1", "shk.kwp-project-routing.v1", "shk.follow-up-reminder.v1"]),
category: z.literal("shk"),
isPublished: z.literal(false),
isExecutable: z.literal(false),
nodes: z.array(z.never()).length(0),
activationGates: z.array(z.string().regex(/^[a-z][a-z0-9.-]+$/)).min(1),
})
.strict()
.superRefine((placeholder, context) => {
if (new Set(placeholder.activationGates).size !== placeholder.activationGates.length) {
context.addIssue({ code: z.ZodIssueCode.custom, path: ["activationGates"], message: CONFIG_VALIDATION_MESSAGE.activationGatesUnique });
}
});
export const shkV2TenantBootstrapConfigSchema = z
.object({
templateKey: z.literal("shk-v2"),
schemaVersion: z.literal(1),
ownerRole: z
.object({
name: z.literal("Admin"),
type: z.literal("app"),
ownership: z.literal("global"),
})
.strict(),
tenantRoles: z.array(tenantRoleSchema).length(5),
salesPipelines: z.array(salesPipelineSchema).length(3),
salesLostReasons: z.array(z.string().trim().min(1)).length(5),
automationPlaceholders: z.array(automationPlaceholderSchema).length(3),
})
.strict()
.superRefine((config, context) => {
if (new Set(config.tenantRoles.map((role) => role.name)).size !== config.tenantRoles.length) {
context.addIssue({ code: z.ZodIssueCode.custom, path: ["tenantRoles"], message: CONFIG_VALIDATION_MESSAGE.tenantRoleNamesUnique });
}
if (new Set(config.salesPipelines.map((pipeline) => pipeline.name)).size !== config.salesPipelines.length) {
context.addIssue({ code: z.ZodIssueCode.custom, path: ["salesPipelines"], message: CONFIG_VALIDATION_MESSAGE.salesPipelineNamesUnique });
}
const defaultPipelines = config.salesPipelines.filter((pipeline) => pipeline.isDefault);
if (defaultPipelines.length !== 1 || defaultPipelines[0]?.name !== "Vertrieb Wärmepumpe") {
context.addIssue({
code: z.ZodIssueCode.custom,
path: ["salesPipelines"],
message: CONFIG_VALIDATION_MESSAGE.defaultSalesPipelineInvalid,
});
}
if (new Set(config.salesLostReasons).size !== config.salesLostReasons.length) {
context.addIssue({ code: z.ZodIssueCode.custom, path: ["salesLostReasons"], message: CONFIG_VALIDATION_MESSAGE.lostReasonsUnique });
}
if (new Set(config.automationPlaceholders.map((template) => template.templateKey)).size !== config.automationPlaceholders.length) {
context.addIssue({
code: z.ZodIssueCode.custom,
path: ["automationPlaceholders"],
message: CONFIG_VALIDATION_MESSAGE.automationTemplateKeysUnique,
});
}
});
export type ShkV2TenantBootstrapConfig = z.infer<typeof shkV2TenantBootstrapConfigSchema>;
export type ShkV2TenantRole = ShkV2TenantBootstrapConfig["tenantRoles"][number];
export type ShkV2SalesPipeline = ShkV2TenantBootstrapConfig["salesPipelines"][number];
export type ShkV2PipelineStage = ShkV2SalesPipeline["stages"][number];
export type ShkV2AutomationPlaceholder = ShkV2TenantBootstrapConfig["automationPlaceholders"][number];
const rawShkV2TenantBootstrapConfig = {
templateKey: "shk-v2",
schemaVersion: 1,
ownerRole: {
name: "Admin",
type: "app",
ownership: "global",
},
tenantRoles: [
{
name: "Vertrieb",
descriptionKey: "tenantBootstrap.roles.sales.description",
type: "app",
assignToNewUsers: false,
isDefault: false,
order: 100,
seatCategory: "office",
isTemplateOrigin: true,
permissionKeys: [
"crm.read_own",
"crm.read_all",
"crm.write",
"leads.read_own",
"leads.write",
"projects.read_own",
"projects.read_all",
"projects.write",
"projects.change_stage",
"bookings.read_own",
"bookings.write",
"calendar.connect_own",
"chat.read_own_channels",
"chat.write",
"chat.create_dm",
"dashboard.read",
],
},
{
name: "Marketing",
descriptionKey: "tenantBootstrap.roles.marketing.description",
type: "app",
assignToNewUsers: false,
isDefault: false,
order: 101,
seatCategory: "office",
isTemplateOrigin: true,
permissionKeys: [
"crm.read_own",
"crm.read_all",
"emailMarketing.manage",
"forms.basic",
"forms.builder",
"forms.publisher",
"leads.read_own",
"leads.write",
"bookings.read_own",
"chat.read_own_channels",
"chat.write",
"chat.create_dm",
"dashboard.read",
],
},
{
name: "Innendienst",
descriptionKey: "tenantBootstrap.roles.insideSales.description",
type: "app",
assignToNewUsers: false,
isDefault: false,
order: 102,
seatCategory: "office",
isTemplateOrigin: true,
permissionKeys: [
"crm.read_own",
"crm.read_all",
"projects.read_own",
"projects.read_all",
"projects.write",
"files.read_own",
"files.write",
"hr.read_own",
"hr.read_all",
"hr.write",
"hr.admin",
"bookings.read_own",
"bookings.write",
"bookings.admin",
"email.read_own",
"email.read_all",
"tasks.read_own",
"tasks.write",
"chat.read_own_channels",
"chat.write",
"chat.create_dm",
"chat.create_channel",
"dashboard.read",
],
},
{
name: "Buchhaltung/Verwaltung",
descriptionKey: "tenantBootstrap.roles.accounting.description",
type: "app",
assignToNewUsers: false,
isDefault: false,
order: 103,
seatCategory: "office",
isTemplateOrigin: true,
permissionKeys: [
"app.settings.members.view",
"app.settings.account.view",
"app.settings.subscription.view",
"app.settings.subscription.invoices.view",
"dashboard.read",
],
},
{
name: "Monteur",
descriptionKey: "tenantBootstrap.roles.technician.description",
type: "app",
assignToNewUsers: false,
isDefault: false,
order: 104,
seatCategory: "field",
isTemplateOrigin: true,
permissionKeys: [
"projects.read_own",
"projects.read_own_member",
"tasks.read_own",
"tasks.write",
"acceptance.write",
"forms.basic",
"files.read_own",
"files.write",
"hr.read_own",
"search.use",
"chat.read_own_channels",
"chat.write",
"chat.create_dm",
"dashboard.read",
],
},
],
salesPipelines: [
{
name: "Vertrieb Wärmepumpe",
typHint: "sales",
position: 10,
isDefault: true,
isDemoData: false,
stages: DEFAULT_SALES_PIPELINE_STAGES,
},
{
name: "Vertrieb Photovoltaik",
typHint: "sales",
position: 20,
isDefault: false,
isDemoData: false,
stages: DEFAULT_SALES_PIPELINE_STAGES,
},
{
name: "Vertrieb Badezimmer",
typHint: "sales",
position: 30,
isDefault: false,
isDemoData: false,
stages: DEFAULT_SALES_PIPELINE_STAGES,
},
],
salesLostReasons: DEFAULT_SALES_LOST_REASONS,
automationPlaceholders: [
{
templateKey: "shk.order-thank-you.v1",
category: "shk",
isPublished: false,
isExecutable: false,
nodes: [],
activationGates: ["mail-content.approved", "mail-sender.approved", "mail-recipient.approved"],
},
{
templateKey: "shk.kwp-project-routing.v1",
category: "shk",
isPublished: false,
isExecutable: false,
nodes: [],
activationGates: ["kwp-target-pipeline.approved"],
},
{
templateKey: "shk.follow-up-reminder.v1",
category: "shk",
isPublished: false,
isExecutable: false,
nodes: [],
activationGates: ["follow-up-timing.approved", "trigger-stage.approved"],
},
],
} as const;
export const SHK_V2_TENANT_BOOTSTRAP_CONFIG: ShkV2TenantBootstrapConfig = shkV2TenantBootstrapConfigSchema.parse(rawShkV2TenantBootstrapConfig);
function canonicalStringify(value: unknown): string {
if (value === null || typeof value !== "object") {
const serialized = JSON.stringify(value);
if (serialized === undefined) {
throw new TypeError("Bootstrap config contains a non-JSON value");
}
return serialized;
}
if (Array.isArray(value)) {
return `[${value.map(canonicalStringify).join(",")}]`;
}
const entries = Object.entries(value as Record<string, unknown>).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));
return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalStringify(entry)}`).join(",")}}`;
}
export function digestShkV2TenantBootstrapConfig(config: ShkV2TenantBootstrapConfig = SHK_V2_TENANT_BOOTSTRAP_CONFIG): string {
const validated = shkV2TenantBootstrapConfigSchema.parse(config);
return createHash("sha256").update(canonicalStringify(validated), "utf8").digest("hex");
}
/** Validated once at module load so interactive bootstrap transactions do no schema or hashing work. */
export const SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST = digestShkV2TenantBootstrapConfig(SHK_V2_TENANT_BOOTSTRAP_CONFIG);
@@ -0,0 +1,22 @@
import { describe, expect, it } from "vitest";
import { deriveResendCreationRequestKey, deriveVerificationCreationRequestKey, isSignupCreationRequestKey } from "./signupCreationRequestKey.server";
describe("signup creation request keys", () => {
it("keeps the verification bootstrap identity stable across token rotations", () => {
const registrationId = "registration_1";
const previousToken = "a".repeat(40);
const nextToken = "b".repeat(40);
const beforeResend = deriveVerificationCreationRequestKey(registrationId);
const resend = deriveResendCreationRequestKey(registrationId, previousToken);
const afterResend = deriveVerificationCreationRequestKey(registrationId);
expect(isSignupCreationRequestKey(beforeResend)).toBe(true);
expect(isSignupCreationRequestKey(resend)).toBe(true);
expect(afterResend).toBe(beforeResend);
expect(resend).toBe(deriveResendCreationRequestKey(registrationId, previousToken));
expect(resend).not.toBe(beforeResend);
expect(resend).not.toBe(deriveResendCreationRequestKey(registrationId, nextToken));
expect(deriveVerificationCreationRequestKey("registration_2")).not.toBe(beforeResend);
});
});
@@ -0,0 +1,32 @@
import { createHash } from "node:crypto";
const SIGNUP_CREATION_REQUEST_KEY_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
export function isSignupCreationRequestKey(value: string): boolean {
return SIGNUP_CREATION_REQUEST_KEY_PATTERN.test(value);
}
/**
* Binds tenant creation to the immutable persisted registration identity.
* Resends rotate the verification token, but they must never rotate the
* bootstrap identity: an already-committed bootstrap must remain replayable
* after a concurrent resend wins the token-consumption CAS.
*/
export function deriveVerificationCreationRequestKey(registrationId: string): string {
return deriveBoundCreationRequestKey("signup-verification-creation-request:v2", registrationId);
}
/** Stable next key for resend response-loss recovery and double-click races. */
export function deriveResendCreationRequestKey(registrationId: string, previousVerificationToken: string): string {
return deriveBoundCreationRequestKey("signup-verification-resend-request:v1", registrationId, previousVerificationToken);
}
function deriveBoundCreationRequestKey(domain: string, ...parts: string[]): string {
const digest = createHash("sha256").update(domain);
for (const part of parts) digest.update("\0").update(part.trim());
const bytes = digest.digest().subarray(0, 16);
bytes[6] = (bytes[6]! & 0x0f) | 0x40;
bytes[8] = (bytes[8]! & 0x3f) | 0x80;
const hex = Buffer.from(bytes).toString("hex");
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
@@ -0,0 +1,30 @@
import { describe, expect, it } from "vitest";
import { deriveSignupVerificationToken } from "./signupVerificationToken.server";
const CREATION_REQUEST_KEY = "d7077797-054b-497a-b1ce-8e4f36257a96";
const OTHER_CREATION_REQUEST_KEY = "b79f4743-b5ee-48df-9287-10f24b2aedbf";
describe("deriveSignupVerificationToken", () => {
it("derives a stable opaque capability from normalized email, key and server secret", () => {
const token = deriveSignupVerificationToken(" Ada@Example.com ", CREATION_REQUEST_KEY, "secret-a");
expect(token).toMatch(/^[a-f0-9]{40}$/u);
expect(deriveSignupVerificationToken("ada@example.com", CREATION_REQUEST_KEY, "secret-a")).toBe(token);
expect(token).not.toContain("ada@example.com");
expect(token).not.toContain(CREATION_REQUEST_KEY);
});
it("changes when any bound input changes", () => {
const token = deriveSignupVerificationToken("ada@example.com", CREATION_REQUEST_KEY, "secret-a");
expect(deriveSignupVerificationToken("grace@example.com", CREATION_REQUEST_KEY, "secret-a")).not.toBe(token);
expect(deriveSignupVerificationToken("ada@example.com", OTHER_CREATION_REQUEST_KEY, "secret-a")).not.toBe(token);
expect(deriveSignupVerificationToken("ada@example.com", CREATION_REQUEST_KEY, "secret-b")).not.toBe(token);
});
it("fails closed without a secret or a valid UUIDv4 request key", () => {
expect(() => deriveSignupVerificationToken("ada@example.com", CREATION_REQUEST_KEY, "")).toThrow("Signup verification token configuration is invalid");
expect(() => deriveSignupVerificationToken("ada@example.com", "not-a-uuid", "secret-a")).toThrow("Signup verification token configuration is invalid");
});
});
@@ -0,0 +1,21 @@
import { createHmac } from "node:crypto";
import { isSignupCreationRequestKey } from "./signupCreationRequestKey.server";
/**
* Produces a stable, server-secret verification capability for an exact
* registration retry. The browser UUID alone cannot be used to derive it.
*/
export function deriveSignupVerificationToken(email: string, creationRequestKey: string, secret = process.env.CRYPTO_SECRET): string {
if (!secret || !isSignupCreationRequestKey(creationRequestKey)) {
throw new Error("Signup verification token configuration is invalid");
}
return createHmac("sha256", secret)
.update("signup-email-verification:v1")
.update("\0")
.update(email.trim().toLowerCase())
.update("\0")
.update(creationRequestKey)
.digest("hex")
.slice(0, 40);
}
@@ -0,0 +1,19 @@
import { describe, expect, it } from "vitest";
import { hasExactShkFirstSteps, SHK_FIRST_STEPS } from "./tenantBootstrap.constants";
describe("SHK first-steps catalog identity", () => {
it("accepts only the exact canonical id, order, and block tuples", () => {
expect(hasExactShkFirstSteps(SHK_FIRST_STEPS)).toBe(true);
for (const change of [{ id: "generated-step" }, { order: 999 }, { block: "unexpected" }]) {
expect(hasExactShkFirstSteps(SHK_FIRST_STEPS.map((step, index) => (index === 0 ? { ...step, ...change } : { ...step })))).toBe(false);
}
});
it("rejects missing, duplicated, and additional steps", () => {
expect(hasExactShkFirstSteps(SHK_FIRST_STEPS.slice(1))).toBe(false);
expect(hasExactShkFirstSteps([SHK_FIRST_STEPS[0], SHK_FIRST_STEPS[0], SHK_FIRST_STEPS[2], SHK_FIRST_STEPS[3]])).toBe(false);
expect(hasExactShkFirstSteps([...SHK_FIRST_STEPS, { id: "extra", order: 50, block: "extra" }])).toBe(false);
});
});
@@ -0,0 +1,30 @@
/** Lifecycle reason used until a workspace reservation has a bootstrapped owner. */
export const TENANT_PENDING_OWNER_REASON = "pending_owner" as const;
/** Stable global catalog identity used by every SHK v2 tenant bootstrap. */
export const SHK_FIRST_STEPS_CHECKLIST_ID = "shk-first-steps-v1" as const;
export const SHK_FIRST_STEPS_CHECKLIST_CODE = "shk-first-steps" as const;
/**
* Stable step identities keep bootstrap retries and existing session references
* independent from generated database ids.
*/
export const SHK_FIRST_STEPS = [
{ id: "shk-first-steps-profile-v1", order: 10, block: "profile" },
{ id: "shk-first-steps-contacts-v1", order: 20, block: "contacts" },
{ id: "shk-first-steps-projects-v1", order: 30, block: "projects" },
{ id: "shk-first-steps-billing-v1", order: 40, block: "billing" },
] as const;
type ChecklistStepIdentity = {
id: string;
order: number;
block: string;
};
export function hasExactShkFirstSteps(steps: ReadonlyArray<ChecklistStepIdentity>): boolean {
return (
steps.length === SHK_FIRST_STEPS.length &&
SHK_FIRST_STEPS.every((expected) => steps.some((actual) => actual.id === expected.id && actual.order === expected.order && actual.block === expected.block))
);
}
@@ -0,0 +1,955 @@
// @vitest-environment node
import pg from "pg";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { disconnectDbClients } from "@hivegrid/db/client.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { hashWorkspaceInviteToken } from "@hivegrid/db/workspace-invites.server";
import { closeSharedStores } from "~/shared-store.server";
import { hashPassword } from "~/utils/auth/passwordHasher.server";
import { db } from "~/utils/db.server";
import { TenantSlugCollisionError } from "~/utils/db/tenants.db.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 } from "./tenantBootstrap.constants";
import {
claimReservedTenantWithShkDefaults,
createSignupTenantWithShkDefaults,
reserveTenantWithoutOwner,
SHK_V2_BOOTSTRAP_SCOPE,
type TenantBootstrapResult,
} from "./tenantBootstrapService.server";
const ADMIN_URL = process.env.RLS_TEST_DATABASE_URL;
const APP_DATABASE_URL = process.env.DATABASE_URL;
const APP_ROLE = "hivegrid_app";
const SUCCESS_EMAIL = "rls-product-bootstrap-live@example.test";
const SUCCESS_SLUG = "rls-product-bootstrap-live";
const ROLLBACK_EMAIL = "rls-product-bootstrap-rollback@example.test";
const ROLLBACK_SLUG = "rls-product-bootstrap-rollback";
const SUCCESS_CREATION_REQUEST_KEY = "484ac2c0-0e91-4fb8-92ac-b0056cdb822c";
const COLLISION_EMAIL = "rls-product-bootstrap-collision@example.test";
const COLLISION_CREATION_REQUEST_KEY = "48dd961f-f270-41f5-b99e-f256a860e031";
const ROLLBACK_CREATION_REQUEST_KEY = "d9291bd7-e1fc-46af-8f6c-92901934af48";
const FOREIGN_USER_ID = "rls_product_bootstrap_foreign_user";
const FOREIGN_TENANT_ID = "rls_product_bootstrap_foreign_tenant";
const FOREIGN_MEMBERSHIP_ID = "rls_product_bootstrap_foreign_membership";
const RESERVATION_REQUEST_KEY = "72b24df6-d97c-4bed-b349-278107253b36";
const RESERVATION_SLUG = "rls-product-ownerless-reservation";
const RESERVATION_OWNER_ID = "rls_product_reservation_owner";
const RESERVATION_OWNER_EMAIL = "rls-product-reservation-owner@example.test";
const RESERVATION_OWNER_INVITE_TOKEN = "rls-product-reservation-owner-token-7w0UbHBUwhI";
const CLAIM_ROLLBACK_REQUEST_KEY = "a9f5e8bc-c418-4ba0-bb80-0393dd64c27d";
const CLAIM_ROLLBACK_SLUG = "rls-product-ownerless-claim-rollback";
const CLAIM_ROLLBACK_USER_ID = "rls_product_claim_rollback_owner";
const CLAIM_ROLLBACK_EMAIL = "rls-product-claim-rollback@example.test";
const CLAIM_ROLLBACK_TOKEN = "rls-product-claim-rollback-token-6xDPsbBfJ9p";
const CLAIM_RACE_REQUEST_KEY = "8281ae1e-fab4-4282-8cde-57b09286b729";
const CLAIM_RACE_SLUG = "rls-product-ownerless-claim-race";
const CLAIM_RACE_USER_IDS = ["rls_product_claim_race_owner_a", "rls_product_claim_race_owner_b"] as const;
const CLAIM_RACE_EMAIL = "rls-product-claim-race@example.test";
const CLAIM_RACE_TOKEN = "rls-product-claim-race-token-2drxMzUCD8T";
const TEST_ADMIN_ROLE_ID = "rls_product_bootstrap_global_admin";
const TRACE_TABLE = "rls_product_bootstrap_write_trace";
const TRACE_FUNCTION = "rls_product_bootstrap_trace_write";
const isRestrictedAppDatabase = (() => {
if (!ADMIN_URL || !APP_DATABASE_URL) return false;
try {
return new URL(APP_DATABASE_URL).username === APP_ROLE;
} catch {
return false;
}
})();
const describeIfLiveDatabase = isRestrictedAppDatabase ? describe : describe.skip;
const translate = (key: string) => `Live: ${key}`;
let admin: pg.Client;
let successfulBootstrap: TenantBootstrapResult | undefined;
let reservedTenantId: string | undefined;
let reservedOwnerInviteId: string | undefined;
let claimRollbackTenantId: string | undefined;
let claimRaceTenantId: string | undefined;
let insertedAdminRole = false;
let insertedChecklist = false;
let originalChecklistActive = true;
const insertedPermissionIds: string[] = [];
describeIfLiveDatabase("SHK v2 product signup under FORCE RLS", () => {
beforeAll(async () => {
admin = new pg.Client({ connectionString: ADMIN_URL });
await admin.connect();
await dropTraceInfrastructure();
await cleanupStaleProductFixtures();
await provisionGlobalPrerequisites();
await createTraceInfrastructure();
await provisionForeignTenant();
});
afterAll(async () => {
try {
if (successfulBootstrap) {
await cleanupTenantRows(successfulBootstrap.tenant.id, successfulBootstrap.user.id);
}
if (reservedTenantId) {
await cleanupTenantRows(reservedTenantId, RESERVATION_OWNER_ID);
}
if (claimRollbackTenantId) {
await cleanupTenantRows(claimRollbackTenantId, CLAIM_ROLLBACK_USER_ID);
}
if (claimRaceTenantId) {
await cleanupTenantRows(claimRaceTenantId, CLAIM_RACE_USER_IDS[0]);
await admin?.query('DELETE FROM "User" WHERE id = ANY($1::text[])', [CLAIM_RACE_USER_IDS]);
}
await cleanupTenantRows(FOREIGN_TENANT_ID, FOREIGN_USER_ID);
await admin?.query('DELETE FROM "User" WHERE email IN ($1, $2, $3)', [SUCCESS_EMAIL, ROLLBACK_EMAIL, COLLISION_EMAIL]);
await admin?.query('DELETE FROM "Tenant" WHERE slug LIKE $1 OR slug LIKE $2', [`${SUCCESS_SLUG}%`, `${ROLLBACK_SLUG}%`]);
if (insertedChecklist) {
await admin?.query('DELETE FROM "Onboarding" WHERE id = $1', [SHK_FIRST_STEPS_CHECKLIST_ID]);
} else {
await admin?.query('UPDATE "Onboarding" SET active = $2 WHERE id = $1', [SHK_FIRST_STEPS_CHECKLIST_ID, originalChecklistActive]);
}
if (insertedAdminRole) {
await admin?.query('DELETE FROM "Role" WHERE id = $1', [TEST_ADMIN_ROLE_ID]);
}
if (insertedPermissionIds.length > 0) {
await admin?.query('DELETE FROM "Permission" WHERE id = ANY($1::text[])', [insertedPermissionIds]);
}
await dropTraceInfrastructure();
} finally {
await disconnectDbClients();
await closeSharedStores();
await admin?.end();
}
});
it("creates the complete baseline atomically through the product signup service", async () => {
const runtimeIdentity = await db.$queryRawUnsafe<Array<{ current_user: string }>>("SELECT current_user");
expect(runtimeIdentity).toEqual([{ current_user: APP_ROLE }]);
successfulBootstrap = await createSignupTenantWithShkDefaults({
email: SUCCESS_EMAIL,
password: "Live-RLS-password-42!",
firstName: "Mara",
lastName: "König",
company: "RLS Product Bootstrap Live",
slug: SUCCESS_SLUG,
locale: "de",
creationRequestKey: SUCCESS_CREATION_REQUEST_KEY,
t: translate,
});
expect(successfulBootstrap.replayed).toBe(false);
expect(successfulBootstrap.tenant).toMatchObject({ active: true, deactivatedReason: null, slug: SUCCESS_SLUG });
const snapshot = await readBootstrapSnapshot(successfulBootstrap.tenant.id, successfulBootstrap.user.id);
expect(snapshot.tenant).toEqual({ id: successfulBootstrap.tenant.id, active: true, deactivatedReason: null });
expect(snapshot.user).toEqual({ id: successfulBootstrap.user.id, active: true, defaultTenantId: successfulBootstrap.tenant.id });
expect(snapshot.memberships).toEqual([
{
tenantId: successfulBootstrap.tenant.id,
userId: successfulBootstrap.user.id,
type: 0,
joined: 0,
status: 2,
},
]);
expect(snapshot.assignments).toEqual([
{
tenantId: successfulBootstrap.tenant.id,
userId: successfulBootstrap.user.id,
role: { tenantId: null, name: "Admin", type: "app" },
},
]);
expect(snapshot.roles).toHaveLength(5);
expect(snapshot.roles.map((role) => role.name)).toEqual(SHK_V2_TENANT_BOOTSTRAP_CONFIG.tenantRoles.map((role) => role.name));
expect(snapshot.roles.every((role) => role.type === "app" && role.isTemplateOrigin && !role.assignToNewUsers && !role.isDefault)).toBe(true);
expect(snapshot.pipelines).toHaveLength(3);
expect(snapshot.pipelines.map((pipeline) => pipeline.name)).toEqual(SHK_V2_TENANT_BOOTSTRAP_CONFIG.salesPipelines.map((pipeline) => pipeline.name));
expect(snapshot.pipelines.flatMap((pipeline) => pipeline.stages)).toHaveLength(15);
expect(snapshot.pipelines.filter((pipeline) => pipeline.isDefault).map((pipeline) => pipeline.name)).toEqual(["Vertrieb Wärmepumpe"]);
for (const pipeline of snapshot.pipelines) {
expect(pipeline.stages.map((stage) => stage.name)).toEqual(["Neu", "Qualifiziert", "Angebot", "Gewonnen", "Verloren"]);
}
expect(snapshot.forms).toEqual([
{ name: "SHK Abnahmeprotokoll", slug: "shk-abnahmeprotokoll", subtype: "acceptance_form", status: "draft", isDemoData: false },
{ name: "SHK Angebotsanfrage", slug: "shk-angebotsanfrage", subtype: "standard", status: "draft", isDemoData: false },
]);
expect(snapshot.acceptanceTemplates).toEqual([{ name: "SHK Standard-Abnahme", isDefault: true, isDemoData: false }]);
expect(snapshot.projectTemplates).toEqual([{ name: "SHK Standard-Projekt", isDemoData: false }]);
expect(snapshot.checklistSessions).toHaveLength(1);
expect(snapshot.checklistSessions[0]).toMatchObject({ status: "active", onboarding: { id: SHK_FIRST_STEPS_CHECKLIST_ID } });
expect(snapshot.checklistSessions[0]?.sessionSteps.map(({ step }) => step)).toEqual(SHK_FIRST_STEPS.map((step) => ({ ...step })));
expect(snapshot.automations).toHaveLength(3);
expect(snapshot.automations.map((automation) => automation.name)).toEqual(
SHK_V2_TENANT_BOOTSTRAP_CONFIG.automationPlaceholders.map((automation) => automation.templateKey).sort()
);
for (const automation of snapshot.automations) {
expect(automation.isPublished).toBe(false);
expect(automation.flowData).toMatchObject({ isExecutable: false, nodes: [] });
}
expect(snapshot.markers).toHaveLength(1);
expect(snapshot.markers[0]).toMatchObject({
scope: SHK_V2_BOOTSTRAP_SCOPE,
key: SHK_V2_TENANT_BOOTSTRAP_CONFIG.templateKey,
requestHash: SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST,
responseStatus: 201,
responseBody: { state: "completed", templateKey: "shk-v2", schemaVersion: 1 },
});
const trace = await admin.query<{ event: string }>(`SELECT event FROM public.${TRACE_TABLE} WHERE tenant_id = $1 ORDER BY seq`, [
successfulBootstrap.tenant.id,
]);
expect(trace.rows.at(-2)?.event).toBe("marker.complete");
expect(trace.rows.at(-1)?.event).toBe("tenant.activate");
const foreignSnapshot = await readForeignSnapshot(successfulBootstrap.tenant.id, successfulBootstrap.user.id);
expect(foreignSnapshot).toEqual({
tenants: [],
users: [],
memberships: [],
assignments: [],
roles: [],
pipelines: [],
stages: [],
forms: [],
acceptanceTemplates: [],
projectTemplates: [],
checklistSessions: [],
automations: [],
markers: [],
});
});
it("rejects a globally occupied explicit slug that pre-auth RLS cannot enumerate", async () => {
expect(successfulBootstrap).toBeDefined();
await expect(
createSignupTenantWithShkDefaults({
email: COLLISION_EMAIL,
password: "Live-RLS-password-44!",
firstName: "Rita",
lastName: "Collision",
company: "RLS Product Bootstrap Collision",
slug: SUCCESS_SLUG,
locale: "de",
creationRequestKey: COLLISION_CREATION_REQUEST_KEY,
t: translate,
})
).rejects.toBeInstanceOf(TenantSlugCollisionError);
const userRows = await admin.query<{ id: string }>('SELECT id FROM "User" WHERE email = $1', [COLLISION_EMAIL]);
const tenantRows = await admin.query<{ id: string }>('SELECT id FROM "Tenant" WHERE name = $1', ["RLS Product Bootstrap Collision"]);
expect(userRows.rows).toEqual([]);
expect(tenantRows.rows).toEqual([]);
});
it("creates and exactly replays an ownerless reservation under restricted RLS", async () => {
const input = {
name: "RLS Product Ownerless Reservation",
slug: RESERVATION_SLUG,
operatorUserId: FOREIGN_USER_ID,
reservationRequestKey: RESERVATION_REQUEST_KEY,
ownerInvitation: {
issuanceKey: RESERVATION_REQUEST_KEY,
email: RESERVATION_OWNER_EMAIL,
firstName: "Olivia",
lastName: "Owner",
fromUserId: FOREIGN_USER_ID,
token: RESERVATION_OWNER_INVITE_TOKEN,
mail: {
subject: "RLS product reservation owner invitation",
html: `<a href="https://app.example.test/invitation/${RESERVATION_OWNER_INVITE_TOKEN}">Accept invitation</a>`,
},
},
};
const first = await runWithRlsContext({ tenantId: FOREIGN_TENANT_ID, userId: FOREIGN_USER_ID }, () => reserveTenantWithoutOwner(input));
reservedTenantId = first.id;
const replay = await runWithRlsContext({ tenantId: FOREIGN_TENANT_ID, userId: FOREIGN_USER_ID }, () => reserveTenantWithoutOwner(input));
expect(replay).toMatchObject({
id: first.id,
name: input.name,
slug: input.slug,
active: false,
deactivatedReason: "pending_owner",
});
const persisted = await admin.query<{
active: boolean;
deactivatedReason: string | null;
requestHash: string;
responseStatus: number;
responseBody: { state?: string } | null;
}>(
`SELECT tenant.active,
tenant."deactivatedReason",
marker."requestHash",
marker."responseStatus",
marker."responseBody"
FROM "Tenant" AS tenant
JOIN "IdempotencyKey" AS marker ON marker."tenantId" = tenant.id
WHERE tenant.id = $1 AND marker.scope = 'tenant-reservation' AND marker.key = $2`,
[first.id, RESERVATION_REQUEST_KEY]
);
expect(persisted.rows).toEqual([
expect.objectContaining({
active: false,
deactivatedReason: "pending_owner",
requestHash: expect.stringMatching(/^[a-f0-9]{64}$/),
responseStatus: 201,
responseBody: expect.objectContaining({ state: "reserved" }),
}),
]);
const invitation = await admin.query<{
id: string;
tokenHash: string | null;
status: string;
outboxCount: string;
}>(
`SELECT invitation.id,
invitation."tokenHash",
invitation.status,
count(outbox.id)::text AS "outboxCount"
FROM "TenantUserInvitation" AS invitation
LEFT JOIN "OutboxEvent" AS outbox
ON outbox."dispatchKey" = 'mail:workspace-owner-invite:' || invitation.id
WHERE invitation."tenantId" = $1 AND invitation.type = 0
GROUP BY invitation.id, invitation."tokenHash", invitation.status`,
[first.id]
);
expect(invitation.rows).toEqual([
expect.objectContaining({
tokenHash: hashWorkspaceInviteToken(RESERVATION_OWNER_INVITE_TOKEN),
status: "pending",
outboxCount: "1",
}),
]);
reservedOwnerInviteId = invitation.rows[0]?.id;
await expect(
runWithRlsContext({ tenantId: FOREIGN_TENANT_ID, userId: FOREIGN_USER_ID }, () => reserveTenantWithoutOwner({ ...input, name: "Changed Reservation" }))
).rejects.toMatchObject({ code: "foundation.idempotency_conflict" });
});
it("claims the ownerless reservation atomically through a verified OWNER invite under restricted RLS", async () => {
expect(reservedTenantId).toBeDefined();
expect(reservedOwnerInviteId).toBeDefined();
const tenantId = reservedTenantId!;
const claimInput = {
tenantId,
userId: RESERVATION_OWNER_ID,
t: translate,
createUser: {
id: RESERVATION_OWNER_ID,
email: RESERVATION_OWNER_EMAIL,
passwordHash: await hashPassword("Live-RLS-owner-password-45!"),
firstName: "Olivia",
lastName: "Owner",
locale: "de",
},
claim: {
kind: "workspace-invite" as const,
inviteId: reservedOwnerInviteId!,
token: RESERVATION_OWNER_INVITE_TOKEN,
createdUserId: RESERVATION_OWNER_ID,
},
};
const claimed = await runWithRlsContext({ userId: RESERVATION_OWNER_ID }, () => claimReservedTenantWithShkDefaults(claimInput));
expect(claimed).toMatchObject({
replayed: false,
tenant: { id: tenantId, active: true, deactivatedReason: null },
user: { id: RESERVATION_OWNER_ID, email: RESERVATION_OWNER_EMAIL, defaultTenantId: tenantId },
});
const replay = await runWithRlsContext({ userId: RESERVATION_OWNER_ID }, () =>
claimReservedTenantWithShkDefaults({
tenantId,
userId: RESERVATION_OWNER_ID,
t: translate,
claim: {
kind: "workspace-invite",
inviteId: reservedOwnerInviteId!,
token: RESERVATION_OWNER_INVITE_TOKEN,
createdUserId: RESERVATION_OWNER_ID,
},
})
);
expect(replay).toMatchObject({ replayed: true, tenant: { id: tenantId, active: true }, user: { id: RESERVATION_OWNER_ID } });
const snapshot = await readBootstrapSnapshot(tenantId, RESERVATION_OWNER_ID);
expect(snapshot.memberships).toEqual([
{
tenantId,
userId: RESERVATION_OWNER_ID,
type: 0,
joined: 0,
status: 2,
},
]);
expect(snapshot.assignments).toEqual([
{
tenantId,
userId: RESERVATION_OWNER_ID,
role: { tenantId: null, name: "Admin", type: "app" },
},
]);
expect(snapshot.roles).toHaveLength(5);
expect(snapshot.pipelines).toHaveLength(3);
expect(snapshot.markers).toHaveLength(1);
const invitation = await admin.query<{
status: string;
pending: boolean;
acceptedByUserId: string | null;
}>('SELECT status, pending, "acceptedByUserId" FROM "TenantUserInvitation" WHERE id = $1', [reservedOwnerInviteId]);
expect(invitation.rows).toEqual([{ status: "accepted", pending: false, acceptedByUserId: RESERVATION_OWNER_ID }]);
});
it("rolls back a newly created owner, invite binding, and defaults when the late claim bootstrap fails", async () => {
const fixture = await reserveOwnerlessFixture({
requestKey: CLAIM_ROLLBACK_REQUEST_KEY,
slug: CLAIM_ROLLBACK_SLUG,
email: CLAIM_ROLLBACK_EMAIL,
token: CLAIM_ROLLBACK_TOKEN,
});
claimRollbackTenantId = fixture.tenantId;
const rollbackPasswordHash = await hashPassword("Live-RLS-rollback-owner-46!");
await admin.query('UPDATE "Onboarding" SET active = false WHERE id = $1', [SHK_FIRST_STEPS_CHECKLIST_ID]);
try {
await expect(
runWithRlsContext({ userId: CLAIM_ROLLBACK_USER_ID }, () =>
claimReservedTenantWithShkDefaults({
tenantId: fixture.tenantId,
userId: CLAIM_ROLLBACK_USER_ID,
t: translate,
createUser: {
id: CLAIM_ROLLBACK_USER_ID,
email: CLAIM_ROLLBACK_EMAIL,
passwordHash: rollbackPasswordHash,
firstName: "Romy",
lastName: "Rollback",
locale: "de",
},
claim: {
kind: "workspace-invite",
inviteId: fixture.inviteId,
token: CLAIM_ROLLBACK_TOKEN,
createdUserId: CLAIM_ROLLBACK_USER_ID,
},
})
)
).rejects.toThrow();
} finally {
await admin.query('UPDATE "Onboarding" SET active = true WHERE id = $1', [SHK_FIRST_STEPS_CHECKLIST_ID]);
}
const state = await admin.query<{
active: boolean;
deactivatedReason: string | null;
status: string;
pending: boolean;
createdUserId: string | null;
users: string;
memberships: string;
markers: string;
}>(
`SELECT tenant.active,
tenant."deactivatedReason",
invitation.status,
invitation.pending,
invitation."createdUserId",
(SELECT count(*)::text FROM "User" WHERE id = $2) AS users,
(SELECT count(*)::text FROM "TenantUser" WHERE "tenantId" = tenant.id) AS memberships,
(SELECT count(*)::text FROM "IdempotencyKey" WHERE "tenantId" = tenant.id AND scope = $3) AS markers
FROM "Tenant" AS tenant
JOIN "TenantUserInvitation" AS invitation ON invitation."tenantId" = tenant.id
WHERE tenant.id = $1 AND invitation.id = $4`,
[fixture.tenantId, CLAIM_ROLLBACK_USER_ID, SHK_V2_BOOTSTRAP_SCOPE, fixture.inviteId]
);
expect(state.rows).toEqual([
{
active: false,
deactivatedReason: "pending_owner",
status: "pending",
pending: true,
createdUserId: null,
users: "0",
memberships: "0",
markers: "0",
},
]);
});
it("allows exactly one newly created owner when parallel claims race under restricted RLS", async () => {
const fixture = await reserveOwnerlessFixture({
requestKey: CLAIM_RACE_REQUEST_KEY,
slug: CLAIM_RACE_SLUG,
email: CLAIM_RACE_EMAIL,
token: CLAIM_RACE_TOKEN,
});
claimRaceTenantId = fixture.tenantId;
const passwordHash = await hashPassword("Live-RLS-race-owner-47!");
const attempts = await Promise.allSettled(
CLAIM_RACE_USER_IDS.map((userId) =>
runWithRlsContext({ userId }, () =>
claimReservedTenantWithShkDefaults({
tenantId: fixture.tenantId,
userId,
t: translate,
createUser: {
id: userId,
email: CLAIM_RACE_EMAIL,
passwordHash,
firstName: "Raya",
lastName: "Race",
locale: "de",
},
claim: {
kind: "workspace-invite",
inviteId: fixture.inviteId,
token: CLAIM_RACE_TOKEN,
createdUserId: userId,
},
})
)
)
);
const fulfilled = attempts.filter((attempt): attempt is PromiseFulfilledResult<TenantBootstrapResult> => attempt.status === "fulfilled");
const rejected = attempts.filter((attempt): attempt is PromiseRejectedResult => attempt.status === "rejected");
expect(fulfilled).toHaveLength(1);
expect(rejected).toHaveLength(1);
const winnerId = fulfilled[0]?.value.user.id;
expect(CLAIM_RACE_USER_IDS).toContain(winnerId);
const state = await admin.query<{
active: boolean;
status: string;
acceptedByUserId: string | null;
userIds: string[];
membershipUserIds: string[];
}>(
`SELECT tenant.active,
invitation.status,
invitation."acceptedByUserId",
ARRAY(SELECT id FROM "User" WHERE id = ANY($2::text[]) ORDER BY id) AS "userIds",
ARRAY(SELECT "userId" FROM "TenantUser" WHERE "tenantId" = tenant.id ORDER BY "userId") AS "membershipUserIds"
FROM "Tenant" AS tenant
JOIN "TenantUserInvitation" AS invitation ON invitation."tenantId" = tenant.id
WHERE tenant.id = $1 AND invitation.id = $3`,
[fixture.tenantId, CLAIM_RACE_USER_IDS, fixture.inviteId]
);
expect(state.rows).toEqual([
{
active: true,
status: "accepted",
acceptedByUserId: winnerId,
userIds: [winnerId],
membershipUserIds: [winnerId],
},
]);
});
it("rolls back the late bootstrap failure without leaving a tenant or user", async () => {
const traceCountBefore = await admin.query<{ count: string }>(`SELECT count(*)::text AS count FROM public.${TRACE_TABLE}`);
await admin.query('UPDATE "Onboarding" SET active = false WHERE id = $1', [SHK_FIRST_STEPS_CHECKLIST_ID]);
try {
await expect(
createSignupTenantWithShkDefaults({
email: ROLLBACK_EMAIL,
password: "Live-RLS-password-43!",
firstName: "Nina",
lastName: "Rollback",
company: "RLS Product Bootstrap Rollback",
slug: ROLLBACK_SLUG,
locale: "de",
creationRequestKey: ROLLBACK_CREATION_REQUEST_KEY,
t: translate,
})
).rejects.toThrow();
} finally {
await admin.query('UPDATE "Onboarding" SET active = true WHERE id = $1', [SHK_FIRST_STEPS_CHECKLIST_ID]);
}
const tenantRows = await admin.query<{ id: string }>('SELECT id FROM "Tenant" WHERE slug LIKE $1', [`${ROLLBACK_SLUG}%`]);
const userRows = await admin.query<{ id: string }>('SELECT id FROM "User" WHERE email = $1', [ROLLBACK_EMAIL]);
const traceCountAfter = await admin.query<{ count: string }>(`SELECT count(*)::text AS count FROM public.${TRACE_TABLE}`);
expect(tenantRows.rows).toEqual([]);
expect(userRows.rows).toEqual([]);
expect(traceCountAfter.rows[0]?.count).toBe(traceCountBefore.rows[0]?.count);
});
});
async function reserveOwnerlessFixture(input: {
requestKey: string;
slug: string;
email: string;
token: string;
}): Promise<{ tenantId: string; inviteId: string }> {
const tenant = await runWithRlsContext({ tenantId: FOREIGN_TENANT_ID, userId: FOREIGN_USER_ID }, () =>
reserveTenantWithoutOwner({
name: `RLS Ownerless ${input.slug}`,
slug: input.slug,
operatorUserId: FOREIGN_USER_ID,
reservationRequestKey: input.requestKey,
ownerInvitation: {
issuanceKey: input.requestKey,
email: input.email,
firstName: input.slug === CLAIM_ROLLBACK_SLUG ? "Romy" : "Raya",
lastName: input.slug === CLAIM_ROLLBACK_SLUG ? "Rollback" : "Race",
fromUserId: FOREIGN_USER_ID,
token: input.token,
mail: {
subject: "RLS product owner invitation",
html: `<a href="https://app.example.test/invitation/${input.token}">Accept invitation</a>`,
},
},
})
);
const invitation = await admin.query<{ id: string }>(
`SELECT id FROM "TenantUserInvitation" WHERE "tenantId" = $1 AND type = 0 AND status = 'pending' ORDER BY id`,
[tenant.id]
);
const inviteId = invitation.rows[0]?.id;
if (!inviteId || invitation.rows.length !== 1) {
throw new Error("Expected exactly one pending owner invitation fixture");
}
return { tenantId: tenant.id, inviteId };
}
async function readBootstrapSnapshot(tenantId: string, userId: string) {
return runWithRlsContext({ tenantId, userId }, () =>
db.$transaction(async (tx) => ({
tenant: await tx.tenant.findUnique({ where: { id: tenantId }, select: { id: true, active: true, deactivatedReason: true } }),
user: await tx.user.findUnique({ where: { id: userId }, select: { id: true, active: true, defaultTenantId: true } }),
memberships: await tx.tenantUser.findMany({
where: { tenantId, userId },
select: { tenantId: true, userId: true, type: true, joined: true, status: true },
}),
assignments: await tx.userRole.findMany({
where: { tenantId, userId },
select: { tenantId: true, userId: true, role: { select: { tenantId: true, name: true, type: true } } },
}),
roles: await tx.role.findMany({
where: { tenantId },
orderBy: { order: "asc" },
select: { name: true, type: true, assignToNewUsers: true, isDefault: true, isTemplateOrigin: true },
}),
pipelines: await tx.pipeline.findMany({
where: { tenantId },
orderBy: { position: "asc" },
select: {
name: true,
isDefault: true,
stages: { orderBy: { position: "asc" }, select: { name: true, stageKind: true, winProbability: true } },
},
}),
forms: await tx.form.findMany({
where: { tenantId },
orderBy: { name: "asc" },
select: { name: true, slug: true, subtype: true, status: true, isDemoData: true },
}),
acceptanceTemplates: await tx.acceptanceFormTemplate.findMany({
where: { tenantId },
orderBy: { name: "asc" },
select: { name: true, isDefault: true, isDemoData: true },
}),
projectTemplates: await tx.projectTemplate.findMany({
where: { tenantId },
orderBy: { name: "asc" },
select: { name: true, isDemoData: true },
}),
checklistSessions: await tx.onboardingSession.findMany({
where: { tenantId, userId },
select: {
status: true,
onboarding: { select: { id: true } },
sessionSteps: {
orderBy: { step: { order: "asc" } },
select: { step: { select: { id: true, order: true, block: true } } },
},
},
}),
automations: await tx.automationTemplate.findMany({
where: { tenantId },
orderBy: { name: "asc" },
select: { name: true, isPublished: true, flowData: true },
}),
markers: await tx.idempotencyKey.findMany({
where: { tenantId, scope: SHK_V2_BOOTSTRAP_SCOPE, key: SHK_V2_TENANT_BOOTSTRAP_CONFIG.templateKey },
select: { scope: true, key: true, requestHash: true, responseStatus: true, responseBody: true },
}),
}))
);
}
async function readForeignSnapshot(targetTenantId: string, targetUserId: string) {
return runWithRlsContext({ tenantId: FOREIGN_TENANT_ID, userId: FOREIGN_USER_ID }, () =>
db.$transaction(async (tx) => ({
tenants: await tx.tenant.findMany({ where: { id: targetTenantId }, select: { id: true } }),
users: await tx.user.findMany({ where: { id: targetUserId }, select: { id: true } }),
memberships: await tx.tenantUser.findMany({ where: { tenantId: targetTenantId }, select: { id: true } }),
assignments: await tx.userRole.findMany({ where: { tenantId: targetTenantId }, select: { id: true } }),
roles: await tx.role.findMany({ where: { tenantId: targetTenantId }, select: { id: true } }),
pipelines: await tx.pipeline.findMany({ where: { tenantId: targetTenantId }, select: { id: true } }),
stages: await tx.pipelineStage.findMany({ where: { tenantId: targetTenantId }, select: { id: true } }),
forms: await tx.form.findMany({ where: { tenantId: targetTenantId }, select: { id: true } }),
acceptanceTemplates: await tx.acceptanceFormTemplate.findMany({ where: { tenantId: targetTenantId }, select: { id: true } }),
projectTemplates: await tx.projectTemplate.findMany({ where: { tenantId: targetTenantId }, select: { id: true } }),
checklistSessions: await tx.onboardingSession.findMany({ where: { tenantId: targetTenantId }, select: { id: true } }),
automations: await tx.automationTemplate.findMany({ where: { tenantId: targetTenantId }, select: { id: true } }),
markers: await tx.idempotencyKey.findMany({ where: { tenantId: targetTenantId }, select: { id: true } }),
}))
);
}
async function provisionGlobalPrerequisites(): Promise<void> {
const adminRoles = await admin.query<{ id: string }>('SELECT id FROM "Role" WHERE "tenantId" IS NULL AND name = $1 AND type = $2 ORDER BY id', [
"Admin",
"app",
]);
if (adminRoles.rows.length === 0) {
await admin.query(
`INSERT INTO "Role" (id, "updatedAt", "tenantId", name, description, type, "assignToNewUsers", "isDefault", "order")
VALUES ($1, now(), NULL, 'Admin', 'RLS product bootstrap global Admin app role', 'app', false, false, 1)`,
[TEST_ADMIN_ROLE_ID]
);
insertedAdminRole = true;
} else if (adminRoles.rows.length !== 1) {
throw new Error(`Expected exactly one global Admin app role, found ${adminRoles.rows.length}`);
}
const permissionKeys = [...new Set(SHK_V2_TENANT_BOOTSTRAP_CONFIG.tenantRoles.flatMap((role) => role.permissionKeys))];
for (const [index, name] of permissionKeys.entries()) {
const id = `rls_product_bootstrap_permission_${String(index).padStart(3, "0")}`;
const inserted = await admin.query<{ id: string }>(
`INSERT INTO "Permission" (id, "updatedAt", name, description, type, "isDefault", "order")
VALUES ($1, now(), $2, 'RLS product bootstrap permission fixture', 'app', false, $3)
ON CONFLICT (name) DO NOTHING
RETURNING id`,
[id, name, 20_000 + index]
);
if (inserted.rows[0]?.id === id) insertedPermissionIds.push(id);
}
const checklist = await admin.query<{ title: string; active: boolean }>('SELECT title, active FROM "Onboarding" WHERE id = $1', [
SHK_FIRST_STEPS_CHECKLIST_ID,
]);
if (checklist.rows.length === 0) {
await admin.query(
`INSERT INTO "Onboarding" (id, "updatedAt", title, type, realtime, active, "canBeDismissed")
VALUES ($1, now(), $2, 'page', false, true, true)`,
[SHK_FIRST_STEPS_CHECKLIST_ID, SHK_FIRST_STEPS_CHECKLIST_CODE]
);
for (const step of SHK_FIRST_STEPS) {
await admin.query('INSERT INTO "OnboardingStep" (id, "onboardingId", "order", block) VALUES ($1, $2, $3, $4)', [
step.id,
SHK_FIRST_STEPS_CHECKLIST_ID,
step.order,
step.block,
]);
}
insertedChecklist = true;
} else {
if (checklist.rows.length !== 1 || checklist.rows[0]?.title !== SHK_FIRST_STEPS_CHECKLIST_CODE) {
throw new Error("The canonical SHK first-steps checklist has an incompatible identity");
}
originalChecklistActive = checklist.rows[0].active;
const steps = await admin.query<{ id: string; order: number; block: string }>(
'SELECT id, "order", block FROM "OnboardingStep" WHERE "onboardingId" = $1 ORDER BY "order"',
[SHK_FIRST_STEPS_CHECKLIST_ID]
);
expect(steps.rows).toEqual(SHK_FIRST_STEPS.map((step) => ({ ...step })));
await admin.query('UPDATE "Onboarding" SET active = true WHERE id = $1', [SHK_FIRST_STEPS_CHECKLIST_ID]);
}
}
async function provisionForeignTenant(): Promise<void> {
await admin.query(
`INSERT INTO "User" (id, "updatedAt", email, "firstName", "lastName", active, "defaultTenantId")
VALUES ($1, now(), 'rls-product-bootstrap-foreign@example.test', 'RLS', 'Foreign', true, $2)`,
[FOREIGN_USER_ID, FOREIGN_TENANT_ID]
);
await admin.query(
`INSERT INTO "Tenant" (id, "updatedAt", slug, name, active)
VALUES ($1, now(), 'rls-product-bootstrap-foreign', 'RLS Product Bootstrap Foreign', true)`,
[FOREIGN_TENANT_ID]
);
await admin.query(
`INSERT INTO "TenantUser" (id, "tenantId", "userId", type, joined, status)
VALUES ($1, $2, $3, 2, 0, 2)`,
[FOREIGN_MEMBERSHIP_ID, FOREIGN_TENANT_ID, FOREIGN_USER_ID]
);
}
async function cleanupStaleProductFixtures(): Promise<void> {
const staleReservations = await admin.query<{ id: string }>('SELECT id FROM "Tenant" WHERE slug = ANY($1::text[])', [
[RESERVATION_SLUG, CLAIM_ROLLBACK_SLUG, CLAIM_RACE_SLUG],
]);
for (const tenant of staleReservations.rows) {
await cleanupTenantRows(tenant.id, RESERVATION_OWNER_ID);
}
const staleTenants = await admin.query<{ id: string; user_id: string | null }>(
`SELECT tenant.id, owner.id AS user_id
FROM "Tenant" AS tenant
LEFT JOIN "User" AS owner ON owner."defaultTenantId" = tenant.id
WHERE tenant.slug LIKE $1 OR tenant.slug LIKE $2 OR tenant.id = $3`,
[`${SUCCESS_SLUG}%`, `${ROLLBACK_SLUG}%`, FOREIGN_TENANT_ID]
);
for (const tenant of staleTenants.rows) {
await cleanupTenantRows(tenant.id, tenant.user_id ?? FOREIGN_USER_ID);
}
await admin.query('DELETE FROM "User" WHERE email IN ($1, $2, $3) OR id = $4', [
SUCCESS_EMAIL,
ROLLBACK_EMAIL,
"rls-product-bootstrap-foreign@example.test",
FOREIGN_USER_ID,
]);
await admin.query('DELETE FROM "User" WHERE id = ANY($1::text[]) OR email = ANY($2::text[])', [
[RESERVATION_OWNER_ID, CLAIM_ROLLBACK_USER_ID, ...CLAIM_RACE_USER_IDS],
[RESERVATION_OWNER_EMAIL, CLAIM_ROLLBACK_EMAIL, CLAIM_RACE_EMAIL],
]);
await admin.query('DELETE FROM "Role" WHERE id = $1', [TEST_ADMIN_ROLE_ID]);
await admin.query('DELETE FROM "Permission" WHERE id LIKE $1', ["rls_product_bootstrap_permission_%"]);
}
async function cleanupTenantRows(tenantId: string, userId: string): Promise<void> {
await admin.query('DELETE FROM "OnboardingSessionStep" WHERE "onboardingSessionId" IN (SELECT id FROM "OnboardingSession" WHERE "tenantId" = $1)', [
tenantId,
]);
await admin.query('DELETE FROM "OnboardingSession" WHERE "tenantId" = $1', [tenantId]);
await admin.query('DELETE FROM "RolePermission" WHERE "roleId" IN (SELECT id FROM "Role" WHERE "tenantId" = $1)', [tenantId]);
await admin.query('DELETE FROM "UserRole" WHERE "tenantId" = $1 OR "userId" = $2', [tenantId, userId]);
await admin.query('DELETE FROM "PipelineStage" WHERE "tenantId" = $1', [tenantId]);
await admin.query('DELETE FROM "Pipeline" WHERE "tenantId" = $1', [tenantId]);
await admin.query('DELETE FROM "LostReason" WHERE "tenantId" = $1', [tenantId]);
await admin.query('DELETE FROM "AutomationTemplate" WHERE "tenantId" = $1', [tenantId]);
await admin.query('DELETE FROM "AcceptanceFormTemplate" WHERE "tenantId" = $1', [tenantId]);
await admin.query('DELETE FROM "ProjectTemplate" WHERE "tenantId" = $1', [tenantId]);
await admin.query('DELETE FROM "CustomFieldDefinition" WHERE "tenantId" = $1', [tenantId]);
await admin.query('DELETE FROM "Form" WHERE "tenantId" = $1', [tenantId]);
await admin.query('DELETE FROM "OutboxEvent" WHERE "tenantId" = $1', [tenantId]);
await admin.query('DELETE FROM "IdempotencyKey" WHERE "tenantId" = $1', [tenantId]);
await admin.query('DELETE FROM "TenantUser" WHERE "tenantId" = $1', [tenantId]);
await admin.query('DELETE FROM "Role" WHERE "tenantId" = $1', [tenantId]);
await admin.query('DELETE FROM "TenantInboundAddress" WHERE "tenantId" = $1', [tenantId]);
await admin.query('DELETE FROM "Tenant" WHERE id = $1', [tenantId]);
await admin.query('DELETE FROM "User" WHERE id = $1', [userId]);
}
async function createTraceInfrastructure(): Promise<void> {
await admin.query(`
CREATE TABLE public.${TRACE_TABLE} (
seq bigserial PRIMARY KEY,
tenant_id text NOT NULL,
event text NOT NULL
);
CREATE FUNCTION public.${TRACE_FUNCTION}()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = pg_catalog, public
AS $$
DECLARE
target_tenant_id text;
event_name text;
BEGIN
IF TG_TABLE_NAME = 'Tenant' THEN
target_tenant_id := NEW.id;
ELSIF TG_TABLE_NAME = 'User' THEN
target_tenant_id := NEW."defaultTenantId";
ELSIF TG_TABLE_NAME = 'OnboardingSessionStep' THEN
SELECT session."tenantId" INTO target_tenant_id
FROM public."OnboardingSession" AS session
WHERE session.id = NEW."onboardingSessionId";
ELSE
target_tenant_id := to_jsonb(NEW)->>'tenantId';
END IF;
IF target_tenant_id IS NULL OR NOT EXISTS (
SELECT 1 FROM public."Tenant" AS tenant
WHERE tenant.id = target_tenant_id
AND tenant.slug LIKE 'rls-product-bootstrap-%'
) THEN
RETURN NEW;
END IF;
event_name := TG_ARGV[0] || '.' || lower(TG_OP);
IF TG_TABLE_NAME = 'Tenant' AND TG_OP = 'UPDATE' THEN
IF NEW.active AND NOT OLD.active THEN
event_name := 'tenant.activate';
END IF;
ELSIF TG_TABLE_NAME = 'IdempotencyKey' AND TG_OP = 'UPDATE' THEN
IF NEW."responseStatus" = 201 THEN
event_name := 'marker.complete';
END IF;
END IF;
INSERT INTO public.${TRACE_TABLE} (tenant_id, event)
VALUES (target_tenant_id, event_name);
RETURN NEW;
END;
$$;
REVOKE ALL ON TABLE public.${TRACE_TABLE} FROM PUBLIC;
REVOKE ALL ON FUNCTION public.${TRACE_FUNCTION}() FROM PUBLIC;
`);
const tracedTables = [
["Tenant", "tenant"],
["User", "user"],
["TenantUser", "membership"],
["UserRole", "assignment"],
["Role", "role"],
["Pipeline", "pipeline"],
["PipelineStage", "stage"],
["LostReason", "lost-reason"],
["Form", "form"],
["AcceptanceFormTemplate", "acceptance"],
["ProjectTemplate", "project-template"],
["OnboardingSession", "checklist-session"],
["OnboardingSessionStep", "checklist-step"],
["AutomationTemplate", "automation"],
["IdempotencyKey", "marker"],
] as const;
for (const [table, event] of tracedTables) {
await admin.query(
`CREATE TRIGGER rls_product_bootstrap_trace
AFTER INSERT OR UPDATE ON public."${table}"
FOR EACH ROW EXECUTE FUNCTION public.${TRACE_FUNCTION}('${event}')`
);
}
}
async function dropTraceInfrastructure(): Promise<void> {
if (!admin) return;
const tracedTables = [
"Tenant",
"User",
"TenantUser",
"UserRole",
"Role",
"Pipeline",
"PipelineStage",
"LostReason",
"Form",
"AcceptanceFormTemplate",
"ProjectTemplate",
"OnboardingSession",
"OnboardingSessionStep",
"AutomationTemplate",
"IdempotencyKey",
];
for (const table of tracedTables) {
await admin.query(`DROP TRIGGER IF EXISTS rls_product_bootstrap_trace ON public."${table}"`);
}
await admin.query(`DROP FUNCTION IF EXISTS public.${TRACE_FUNCTION}()`);
await admin.query(`DROP TABLE IF EXISTS public.${TRACE_TABLE}`);
}
@@ -0,0 +1,98 @@
import type { TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
import { describe, expect, it, vi } from "vitest";
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 } from "./tenantBootstrap.constants";
import { bootstrapShkV2TenantWithTx } from "./tenantBootstrapService.server";
import { prepareShkFormTemplates } from "~/modules/forms/services/shkFormTemplates.server";
const MAX_BOOTSTRAP_TRANSACTION_QUERIES = 26;
describe("tenant bootstrap transaction performance contract", () => {
it("executes the real helper graph within the sequential query budget", async () => {
const calls: string[] = [];
const query = <T>(name: string, result: T) =>
vi.fn(async () => {
calls.push(name);
return result;
});
const permissions = [...new Set(SHK_V2_TENANT_BOOTSTRAP_CONFIG.tenantRoles.flatMap((role) => role.permissionKeys))].map((name, index) => ({
id: `permission_${index}`,
name,
}));
const roles = 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 tx = {
idempotencyKey: {
upsert: vi.fn(async ({ create }: { create: Record<string, unknown> }) => {
calls.push("marker.acquire");
return create;
}),
update: query("marker.complete", {}),
},
role: {
findMany: query("role.admin", [{ id: "role_admin" }]),
createManyAndReturn: query("roles.create", roles),
},
tenantUser: { upsert: query("owner.create", {}) },
user: { update: query("user.defaultTenant", {}) },
userRole: {
deleteMany: query("userRoles.prune", { count: 0 }),
createMany: query("userRoles.admin", { count: 1 }),
},
tenant: {
update: vi.fn(async ({ data }: { data: { active?: boolean } }) => {
calls.push("tenant.activate");
return { id: "tenant_1", active: Boolean(data.active), deactivatedReason: data.active ? null : "pending_owner" };
}),
},
permission: { findMany: query("permissions.read", permissions) },
rolePermission: { createMany: query("rolePermissions.create", { count: permissions.length }) },
pipeline: { createManyAndReturn: query("pipelines.create", pipelines) },
pipelineStage: { createMany: query("pipelineStages.create", { count: 15 }) },
lostReason: { createMany: query("lostReasons.create", { count: 5 }) },
acceptanceFormTemplate: { upsert: query("acceptanceTemplate.upsert", { id: "acceptance_1" }) },
projectTemplate: { upsert: query("projectTemplate.upsert", { id: "project_template_1" }) },
form: { upsert: query("form.upsert", { id: "form_1" }) },
onboarding: {
findUnique: query("onboarding.read", {
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 })),
}),
},
onboardingSession: { upsert: query("onboardingSession.upsert", { id: "session_1" }) },
onboardingSessionStep: { createMany: query("onboardingSteps.create", { count: 4 }) },
automationTemplate: { createMany: query("automationPlaceholders.create", { count: 3 }) },
portal: { upsert: query("portal.scaffold", { id: "portal_1" }) },
};
await expect(
bootstrapShkV2TenantWithTx(tx as unknown as TenantRlsClient, {
tenantId: "tenant_1",
tenantName: "Heizkraft GmbH",
tenantSlug: "heizkraft",
userId: "user_1",
attemptId: "attempt_1",
t: (key) => key,
configDigest: SHK_V2_TENANT_BOOTSTRAP_CONFIG_DIGEST,
preparedFormTemplates: prepareShkFormTemplates((key) => key),
})
).resolves.toMatchObject({ replayed: false, tenant: { id: "tenant_1", active: true } });
expect(calls.length).toBeLessThanOrEqual(MAX_BOOTSTRAP_TRANSACTION_QUERIES);
expect(calls.at(-2)).toBe("marker.complete");
expect(calls.at(-1)).toBe("tenant.activate");
});
});