Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/utils/services/authService.transactional-email.test.ts
T

1367 lines
56 KiB
TypeScript

import { beforeEach, describe, expect, it, vi } from "vitest";
import { createRegistrationForm, createUserAndTenant, getRegistrationFormData, resolvePendingRegistrationResendRecovery } from "./authService";
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
import {
createRegistration,
getRegistrationByEmail,
getRegistrationByToken,
getRegistrationVerificationStateByToken,
RegistrationVerificationRotationConflictError,
rotateRegistrationVerification,
} from "~/utils/db/registration.db.server";
import { createSignupTenantWithShkDefaults } from "~/domain/tenant-bootstrap/tenantBootstrapService.server";
import { queueTransactionalEmail } from "~/modules/emails/services/TransactionalEmailQueue.server";
import EmailTemplates from "~/modules/emails/utils/EmailTemplates";
import { sendEmail } from "~/modules/emails/services/EmailService";
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
import { RegistrationCreateConflictError } from "@hivegrid/db/pretenant-security.server";
import { deriveResendCreationRequestKey, deriveVerificationCreationRequestKey } from "~/domain/tenant-bootstrap/signupCreationRequestKey.server";
import { deriveSignupVerificationToken } from "~/domain/tenant-bootstrap/signupVerificationToken.server";
import { TenantSlugCollisionError } from "~/utils/db/tenants.db.server";
const dbMocks = vi.hoisted(() => ({ transaction: vi.fn() }));
const eventServiceMocks = vi.hoisted(() => ({ createIdempotentTenantEvent: vi.fn() }));
vi.mock("~/utils/db/appConfiguration.db.server", () => ({
getAppConfiguration: vi.fn(),
}));
vi.mock("~/utils/db/registration.db.server", () => ({
createRegistration: vi.fn(),
getRegistrationByEmail: vi.fn(),
getRegistrationByToken: vi.fn(),
getRegistrationVerificationStateByToken: vi.fn(),
RegistrationVerificationRotationConflictError: class RegistrationVerificationRotationConflictError extends Error {},
rotateRegistrationVerification: vi.fn(),
updateRegistration: vi.fn(),
}));
vi.mock("~/utils/db/tenants.db.server", () => ({
getTenantBySlug: vi.fn(),
TenantSlugCollisionError: class TenantSlugCollisionError extends Error {},
}));
vi.mock("~/utils/db/users.db.server", () => ({
getUserByEmail: vi.fn(),
}));
vi.mock("~/domain/tenant-bootstrap/tenantBootstrapService.server", () => ({
createSignupTenantWithShkDefaults: vi.fn(),
isSignupCreationRequestKey: vi.fn((value: string) => /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)),
}));
vi.mock("~/domain/tenant-bootstrap/signupVerificationToken.server", () => ({
deriveSignupVerificationToken: vi.fn((_email: string, creationRequestKey: string) =>
creationRequestKey === "d7077797-054b-497a-b1ce-8e4f36257a96" ? "registration-token" : "different-registration-token"
),
}));
vi.mock("~/modules/emails/services/TransactionalEmailQueue.server", () => ({
queueTransactionalEmail: vi.fn(),
}));
vi.mock("~/modules/emails/services/EmailService", () => ({
sendEmail: vi.fn(),
}));
vi.mock("~/utils/url.server", () => ({
getAbsoluteUrl: vi.fn((_request: Request, path: string) => `https://example.com${path}`),
}));
vi.mock("~/utils/session.server", () => ({
getUserInfo: vi.fn(async () => ({ lng: "en" })),
}));
vi.mock("./.server/pricingService", () => ({
autosubscribeToTrialOrFreePlan: vi.fn(),
}));
vi.mock("~/services/billing/registration-plan-selection.server", () => ({
resolveRegistrationSubscriptionPrice: vi.fn(),
}));
vi.mock("~/modules/emails/utils/EmailTemplates", () => ({
default: {
VERIFICATION_EMAIL: {
parse: vi.fn(({ data }) => ({
subject: "Verify your email",
body: `<p>Verify at ${data.action_url} for ${data.name}</p>`,
})),
},
WELCOME_EMAIL: {
parse: vi.fn(({ data }) => ({
subject: "Welcome",
body: `<p>Welcome at ${data.action_url} for ${data.name}</p>`,
text: `Welcome at ${data.action_url} for ${data.name}`,
})),
},
},
}));
vi.mock("~/modules/events/utils/EventUtils", () => ({
default: {
getDescription: vi.fn(() => "Account created: Ada Co"),
},
}));
vi.mock("~/modules/events/services/.server/EventsService", () => ({
default: {
createIdempotentTenantEvent: eventServiceMocks.createIdempotentTenantEvent,
},
}));
vi.mock("~/modules/ipAddress/services/IpAddressService.server", () => ({
default: {
log: vi.fn(async () => undefined),
},
}));
vi.mock("~/utils/db.server", () => ({
db: { $transaction: dbMocks.transaction },
}));
vi.mock("~/locale/i18next.server", () => ({
getTranslations: vi.fn(async () => ({ t: (key: string) => key })),
remixI18Next: {
getFixedT: vi.fn(async () => (key: string) => key),
getLocale: vi.fn(async () => "de"),
},
}));
vi.mock("~/locale/mail-translator.server", () => ({
getMailTranslator: vi.fn(async () => ({ t: (key: string) => key, locale: "de" })),
getMailTranslatorFromRequest: vi.fn(async () => ({ t: (key: string) => key, locale: "de" })),
resolveMailLocale: vi.fn((locale: string | null | undefined) => locale ?? "de"),
}));
const getAppConfigurationMock = vi.mocked(getAppConfiguration);
const getRegistrationByEmailMock = vi.mocked(getRegistrationByEmail);
const getRegistrationByTokenMock = vi.mocked(getRegistrationByToken);
const getRegistrationVerificationStateByTokenMock = vi.mocked(getRegistrationVerificationStateByToken);
const rotateRegistrationVerificationMock = vi.mocked(rotateRegistrationVerification);
const deriveSignupVerificationTokenMock = vi.mocked(deriveSignupVerificationToken);
const createRegistrationMock = vi.mocked(createRegistration);
const queueTransactionalEmailMock = vi.mocked(queueTransactionalEmail);
const verificationParseMock = vi.mocked(EmailTemplates.VERIFICATION_EMAIL.parse);
const welcomeParseMock = vi.mocked(EmailTemplates.WELCOME_EMAIL.parse);
const createSignupTenantWithShkDefaultsMock = vi.mocked(createSignupTenantWithShkDefaults);
const sendEmailMock = vi.mocked(sendEmail);
const request = new Request("https://example.com/register");
const CREATION_REQUEST_KEY = "d7077797-054b-497a-b1ce-8e4f36257a96";
const BOUND_VERIFICATION_KEY = deriveVerificationCreationRequestKey("registration_1");
const RESEND_CREATION_REQUEST_KEY = deriveResendCreationRequestKey("registration_1", "registration-token");
const SECOND_RESEND_CREATION_REQUEST_KEY = deriveResendCreationRequestKey("registration_1", "different-registration-token");
const VERIFICATION_URL = `https://example.com/verify/registration-token?creationRequestKey=${BOUND_VERIFICATION_KEY}`;
const CREATED_AT = new Date("2026-07-15T00:00:00.000Z");
function pendingRegistration(overrides: Record<string, unknown> = {}) {
return {
id: "registration_1",
createdAt: CREATED_AT,
email: "ada@example.com",
firstName: "Ada",
lastName: "",
slug: null,
token: "registration-token",
ipAddress: "127.0.0.1",
company: "Ada Co",
selectedSubscriptionPriceId: null,
selectedOfficeSeatQuantity: null,
selectedFieldSeatQuantity: null,
leadConversionLeadId: null,
leadConversionToken: null,
leadConversionPlanId: null,
createdTenantId: null,
...overrides,
} as Awaited<ReturnType<typeof getRegistrationByToken>>;
}
type MarkerRow = {
requestHash: string;
responseStatus: number;
responseBody: unknown;
responseHeaders: Record<string, string> | null;
};
type OutboxRow = {
id: string;
tenantId: string | null;
eventType: string;
payload: Record<string, unknown>;
dispatchKey: string | null;
};
type EventRow = { id: string; name: string; tenantId: string; userId: string; data: string; description: string };
const postCommitState = {
markers: new Map<string, MarkerRow>(),
outbox: [] as OutboxRow[],
events: [] as EventRow[],
failNextOutboxCreate: false,
transactionContexts: [] as Array<ReturnType<typeof getRlsExecutionContext>>,
accountEventKeys: new Set<string>(),
logicalAdminNotifications: 0,
};
function markerStorageKey(where: { idempotency_key_partition_scope_key: { partitionKey: string; scope: string; key: string } }): string {
const key = where.idempotency_key_partition_scope_key;
return `${key.partitionKey}:${key.scope}:${key.key}`;
}
function buildPostCommitTx() {
return {
idempotencyKey: {
findUnique: vi.fn(async ({ where }: { where: Parameters<typeof markerStorageKey>[0] }) => postCommitState.markers.get(markerStorageKey(where)) ?? null),
create: vi.fn(async ({ data }: { data: MarkerRow & { partitionKey: string; scope: string; key: string } }) => {
const storageKey = `tenant:${data.partitionKey.replace(/^tenant:/, "")}:${data.scope}:${data.key}`;
postCommitState.markers.set(storageKey, {
requestHash: data.requestHash,
responseStatus: data.responseStatus,
responseBody: data.responseBody,
responseHeaders: data.responseHeaders,
});
return {};
}),
update: vi.fn(async ({ where, data }: { where: Parameters<typeof markerStorageKey>[0]; data: Partial<MarkerRow> }) => {
const storageKey = markerStorageKey(where);
const existing = postCommitState.markers.get(storageKey);
if (!existing) throw new Error("missing idempotency marker");
postCommitState.markers.set(storageKey, { ...existing, ...data });
return {};
}),
deleteMany: vi.fn(async ({ where }: { where: { partitionKey: string; scope: string; key: string } }) => {
postCommitState.markers.delete(`${where.partitionKey}:${where.scope}:${where.key}`);
return { count: 1 };
}),
},
outboxEvent: {
create: vi.fn(
async ({ data }: { data: { tenantId?: string | null; eventType: string; payload: Record<string, unknown>; dispatchKey?: string | null } }) => {
if (postCommitState.failNextOutboxCreate) {
postCommitState.failNextOutboxCreate = false;
throw new Error("outbox temporarily unavailable");
}
const row: OutboxRow = {
id: `outbox_${postCommitState.outbox.length + 1}`,
tenantId: data.tenantId ?? null,
eventType: data.eventType,
payload: data.payload,
dispatchKey: data.dispatchKey ?? null,
};
postCommitState.outbox.push(row);
return row;
}
),
findUnique: vi.fn(async ({ where }: { where: { dispatchKey: string } }) => {
return postCommitState.outbox.find((row) => row.dispatchKey === where.dispatchKey) ?? null;
}),
},
event: {
create: vi.fn(async ({ data }: { data: Omit<EventRow, "id"> }) => {
const row = { id: `event_${postCommitState.events.length + 1}`, ...data };
postCommitState.events.push(row);
return row;
}),
},
};
}
function resetPostCommitState(): void {
postCommitState.markers.clear();
postCommitState.outbox.length = 0;
postCommitState.events.length = 0;
postCommitState.failNextOutboxCreate = false;
postCommitState.transactionContexts.length = 0;
postCommitState.accountEventKeys.clear();
postCommitState.logicalAdminNotifications = 0;
}
const appConfiguration = {
app: { name: "Example" },
email: { fromName: "Support", supportEmail: "support@example.com" },
} as Awaited<ReturnType<typeof getAppConfiguration>>;
describe("auth service transactional registration emails", () => {
beforeEach(() => {
vi.clearAllMocks();
resetPostCommitState();
getAppConfigurationMock.mockResolvedValue(appConfiguration);
getRegistrationVerificationStateByTokenMock.mockResolvedValue({ status: "invalid" });
rotateRegistrationVerificationMock.mockResolvedValue(true);
queueTransactionalEmailMock.mockResolvedValue({ enqueued: true, jobId: "job_1" });
eventServiceMocks.createIdempotentTenantEvent.mockImplementation(async ({ idempotencyKey }: { idempotencyKey: string }) => {
if (!postCommitState.accountEventKeys.has(idempotencyKey)) {
postCommitState.accountEventKeys.add(idempotencyKey);
postCommitState.logicalAdminNotifications += 1;
}
return "account.created";
});
dbMocks.transaction.mockImplementation(async (callback: (tx: ReturnType<typeof buildPostCommitTx>) => Promise<unknown>) => {
const markerSnapshot = new Map(postCommitState.markers);
const outboxSnapshot = [...postCommitState.outbox];
const eventSnapshot = [...postCommitState.events];
postCommitState.transactionContexts.push(getRlsExecutionContext());
try {
return await callback(buildPostCommitTx());
} catch (error) {
postCommitState.markers.clear();
markerSnapshot.forEach((value, key) => postCommitState.markers.set(key, value));
postCommitState.outbox.splice(0, postCommitState.outbox.length, ...outboxSnapshot);
postCommitState.events.splice(0, postCommitState.events.length, ...eventSnapshot);
throw error;
}
});
});
it("requeues an exact pending registration without mutating its token or payload", async () => {
getRegistrationByEmailMock.mockResolvedValue({ id: "registration_1", createdTenantId: null } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
getRegistrationByTokenMock.mockResolvedValue(pendingRegistration());
await createRegistrationForm({
request,
email: "ada@example.com",
ipAddress: "127.0.0.1",
firstName: "Ada",
company: "Ada Co",
creationRequestKey: CREATION_REQUEST_KEY,
});
expect(getRegistrationByTokenMock).toHaveBeenCalledWith("registration-token");
expect(verificationParseMock).toHaveBeenCalledWith(
expect.objectContaining({
appConfiguration,
data: {
action_url: VERIFICATION_URL,
name: "Ada",
},
t: expect.any(Function),
locale: expect.any(String),
})
);
expect(queueTransactionalEmailMock).toHaveBeenCalledWith({
to: "ada@example.com",
alias: "email-verification",
subject: "Verify your email",
body: `<p>Verify at ${VERIFICATION_URL} for Ada</p>`,
data: {
action_url: VERIFICATION_URL,
name: "Ada",
},
priorityOverride: "critical",
idempotencyKey: expect.stringMatching(/^registration-verification:registration_1:[a-f0-9]{32}$/),
});
expect(queueTransactionalEmailMock.mock.invocationCallOrder[0]).toBeGreaterThan(getRegistrationByTokenMock.mock.invocationCallOrder[0]);
expect(sendEmailMock).not.toHaveBeenCalled();
});
it("requeues only when persisted lead conversion context matches exactly", async () => {
getRegistrationByEmailMock.mockResolvedValue({ id: "registration_1", createdTenantId: null } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
getRegistrationByTokenMock.mockResolvedValue(
pendingRegistration({
email: "lead@example.com",
lastName: "Lovelace",
leadConversionLeadId: "lead_2",
leadConversionToken: "signed-token-2",
leadConversionPlanId: "plan_scale",
})
);
await createRegistrationForm({
request,
email: "lead@example.com",
ipAddress: "127.0.0.1",
firstName: "Ada",
lastName: "Lovelace",
company: "Ada Co",
leadId: "lead_2",
leadToken: "signed-token-2",
leadPlanId: "plan_scale",
creationRequestKey: CREATION_REQUEST_KEY,
});
expect(getRegistrationByTokenMock).toHaveBeenCalledWith("registration-token");
expect(queueTransactionalEmailMock).toHaveBeenCalledWith(
expect.objectContaining({
to: "lead@example.com",
alias: "email-verification",
priorityOverride: "critical",
})
);
expect(queueTransactionalEmailMock.mock.invocationCallOrder[0]).toBeGreaterThan(getRegistrationByTokenMock.mock.invocationCallOrder[0]);
expect(sendEmailMock).not.toHaveBeenCalled();
});
it("fails closed for another creation key without mutating or mailing a pending registration", async () => {
getRegistrationByEmailMock.mockResolvedValue({ id: "registration_1", createdTenantId: null } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
getRegistrationByTokenMock.mockResolvedValue(null);
createRegistrationMock.mockRejectedValueOnce(new RegistrationCreateConflictError());
await expect(
createRegistrationForm({
request,
email: "ada@example.com",
ipAddress: "127.0.0.1",
firstName: "Ada",
company: "Ada Co",
creationRequestKey: "b79f4743-b5ee-48df-9287-10f24b2aedbf",
})
).rejects.toMatchObject({ code: "foundation.idempotency_conflict" });
expect(createRegistrationMock).toHaveBeenCalledOnce();
expect(queueTransactionalEmailMock).not.toHaveBeenCalled();
});
it.each([
["first name", { firstName: "Mallory" }],
["last name", { lastName: "Lovelace" }],
["company", { company: "Other Co" }],
["slug", { slug: "other-co" }],
["lead id", { leadId: "lead_1" }],
["lead token", { leadToken: "lead-token" }],
["lead plan", { leadPlanId: "plan_pro" }],
["subscription price", { selectedSubscriptionPriceId: "price_pro" }],
["IP address", { ipAddress: "127.0.0.2" }],
])("fails closed when an exact pending retry changes %s", async (_label, override) => {
getRegistrationByEmailMock.mockResolvedValue({ id: "registration_1", createdTenantId: null } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
getRegistrationByTokenMock.mockResolvedValue(pendingRegistration());
await expect(
createRegistrationForm({
request,
email: "ada@example.com",
ipAddress: "127.0.0.1",
firstName: "Ada",
company: "Ada Co",
creationRequestKey: CREATION_REQUEST_KEY,
...override,
})
).rejects.toMatchObject({ code: "foundation.idempotency_conflict" });
expect(queueTransactionalEmailMock).not.toHaveBeenCalled();
});
it("creates new registration records and enqueues verification email", async () => {
getRegistrationByEmailMock.mockResolvedValue(null);
createRegistrationMock.mockResolvedValue({ id: "registration_1" } as Awaited<ReturnType<typeof createRegistration>>);
await createRegistrationForm({
request,
email: "ada@example.com",
ipAddress: "127.0.0.1",
firstName: "Ada",
lastName: "Lovelace",
company: "Ada Co",
slug: "ada-co",
selectedSubscriptionPriceId: "price_starter",
selectedOfficeSeatQuantity: 4,
selectedFieldSeatQuantity: 8,
creationRequestKey: CREATION_REQUEST_KEY,
});
expect(createRegistrationMock).toHaveBeenCalledWith({
email: "ada@example.com",
firstName: "Ada",
lastName: "Lovelace",
company: "Ada Co",
token: "registration-token",
selectedSubscriptionPriceId: "price_starter",
selectedOfficeSeatQuantity: 4,
selectedFieldSeatQuantity: 8,
leadConversionLeadId: null,
leadConversionToken: null,
leadConversionPlanId: null,
ipAddress: "127.0.0.1",
slug: "ada-co",
});
expect(queueTransactionalEmailMock).toHaveBeenCalledWith({
to: "ada@example.com",
alias: "email-verification",
subject: "Verify your email",
body: `<p>Verify at ${VERIFICATION_URL} for Ada</p>`,
data: {
action_url: VERIFICATION_URL,
name: "Ada",
},
priorityOverride: "critical",
idempotencyKey: expect.stringMatching(/^registration-verification:registration_1:[a-f0-9]{32}$/),
});
expect(queueTransactionalEmailMock.mock.invocationCallOrder[0]).toBeGreaterThan(createRegistrationMock.mock.invocationCallOrder[0]);
expect(sendEmailMock).not.toHaveBeenCalled();
});
it("keeps the original registration key and logical mail job across an exact response-loss retry", async () => {
getRegistrationByEmailMock
.mockResolvedValueOnce(null)
.mockResolvedValueOnce({ id: "registration_1", createdTenantId: null } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
createRegistrationMock.mockResolvedValueOnce({ id: "registration_1" } as Awaited<ReturnType<typeof createRegistration>>);
getRegistrationByTokenMock.mockResolvedValueOnce(pendingRegistration());
const input = {
request,
email: "ada@example.com",
ipAddress: "127.0.0.1",
firstName: "Ada",
company: "Ada Co",
creationRequestKey: CREATION_REQUEST_KEY,
};
const initial = await createRegistrationForm(input);
const resend = await createRegistrationForm(input);
expect(initial).toEqual({ creationRequestKey: CREATION_REQUEST_KEY });
expect(resend).toEqual({ creationRequestKey: CREATION_REQUEST_KEY });
expect(initial.creationRequestKey).not.toBe(BOUND_VERIFICATION_KEY);
expect(createRegistrationMock).toHaveBeenCalledOnce();
expect(getRegistrationByTokenMock).toHaveBeenCalledWith("registration-token");
expect(queueTransactionalEmailMock).toHaveBeenCalledTimes(2);
expect(queueTransactionalEmailMock.mock.calls[0]?.[0]).toEqual(queueTransactionalEmailMock.mock.calls[1]?.[0]);
expect(queueTransactionalEmailMock.mock.calls[0]?.[0]).toMatchObject({
data: { action_url: VERIFICATION_URL, name: "Ada" },
idempotencyKey: expect.stringMatching(/^registration-verification:registration_1:[a-f0-9]{32}$/u),
});
});
it("rotates a fresh manual resend so a retained mail job cannot suppress delivery", async () => {
getRegistrationByEmailMock
.mockResolvedValueOnce(null)
.mockResolvedValueOnce({ id: "registration_1", createdTenantId: null } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
createRegistrationMock.mockResolvedValueOnce({ id: "registration_1" } as Awaited<ReturnType<typeof createRegistration>>);
getRegistrationByTokenMock
.mockResolvedValueOnce(pendingRegistration())
.mockResolvedValueOnce(pendingRegistration({ token: "different-registration-token" }));
const input = {
request,
email: "ada@example.com",
ipAddress: "127.0.0.1",
firstName: "Ada",
company: "Ada Co",
creationRequestKey: CREATION_REQUEST_KEY,
};
const initial = await createRegistrationForm(input);
const resend = await createRegistrationForm({ ...input, resendOnly: true });
expect(initial).toEqual({ creationRequestKey: CREATION_REQUEST_KEY });
expect(resend).toEqual({ creationRequestKey: RESEND_CREATION_REQUEST_KEY });
expect(rotateRegistrationVerificationMock).toHaveBeenCalledWith("registration_1", "registration-token", "different-registration-token");
expect(queueTransactionalEmailMock).toHaveBeenCalledTimes(2);
const [initialMail, resendMail] = queueTransactionalEmailMock.mock.calls.map(([mail]) => mail);
expect(initialMail?.idempotencyKey).not.toBe(resendMail?.idempotencyKey);
expect(initialMail?.data.action_url).toContain("/verify/registration-token?");
expect(resendMail?.data.action_url).toContain("/verify/different-registration-token?");
});
it("resolves only the exact signed pending Registration and follows one committed resend after response loss", async () => {
getRegistrationByEmailMock.mockResolvedValue({ id: "registration_1", createdTenantId: null } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
getRegistrationVerificationStateByTokenMock.mockImplementation(async (token) => {
if (token === "registration-token") return { status: "invalid" };
return { status: "pending", registration: pendingRegistration({ token: "different-registration-token" }) };
});
await expect(resolvePendingRegistrationResendRecovery({ email: " Ada@Example.COM ", creationRequestKey: CREATION_REQUEST_KEY })).resolves.toEqual({
email: "ada@example.com",
creationRequestKey: RESEND_CREATION_REQUEST_KEY,
registrationId: "registration_1",
catchUpOnly: true,
selectedSubscriptionPriceId: null,
selectedOfficeSeatQuantity: null,
selectedFieldSeatQuantity: null,
});
getRegistrationVerificationStateByTokenMock.mockResolvedValueOnce({
status: "pending",
registration: pendingRegistration({ email: "mallory@example.com" }),
});
await expect(resolvePendingRegistrationResendRecovery({ email: "ada@example.com", creationRequestKey: CREATION_REQUEST_KEY })).resolves.toBeNull();
getRegistrationByEmailMock.mockResolvedValueOnce({ id: "registration_1", createdTenantId: "tenant_1" } as Awaited<
ReturnType<typeof getRegistrationByEmail>
>);
await expect(resolvePendingRegistrationResendRecovery({ email: "ada@example.com", creationRequestKey: CREATION_REQUEST_KEY })).resolves.toBeNull();
});
it("uses persisted identity fields and preserves one logical mail across concurrent recovery CAS attempts", async () => {
getRegistrationByEmailMock.mockResolvedValue({ id: "registration_1", createdTenantId: null } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
getRegistrationVerificationStateByTokenMock.mockImplementation(async (token) => ({
status: "pending",
registration: pendingRegistration({ token }),
}));
rotateRegistrationVerificationMock.mockResolvedValueOnce(true).mockRejectedValueOnce(new RegistrationVerificationRotationConflictError());
const input = {
request,
email: "ada@example.com",
ipAddress: "203.0.113.99",
firstName: "Mallory",
lastName: "Tampered",
company: "Attacker Ltd",
creationRequestKey: CREATION_REQUEST_KEY,
resendOnly: true,
resendRecovery: { registrationId: "registration_1", catchUpOnly: false },
};
await expect(Promise.all([createRegistrationForm(input), createRegistrationForm(input)])).resolves.toEqual([
{ creationRequestKey: RESEND_CREATION_REQUEST_KEY },
{ creationRequestKey: RESEND_CREATION_REQUEST_KEY },
]);
expect(rotateRegistrationVerificationMock).toHaveBeenCalledTimes(2);
expect(queueTransactionalEmailMock).toHaveBeenCalledTimes(2);
expect(new Set(queueTransactionalEmailMock.mock.calls.map(([mail]) => mail.idempotencyKey)).size).toBe(1);
expect(queueTransactionalEmailMock).toHaveBeenCalledWith(
expect.objectContaining({
to: "ada@example.com",
data: expect.objectContaining({ name: "Ada" }),
})
);
expect(JSON.stringify(queueTransactionalEmailMock.mock.calls)).not.toContain("Mallory");
expect(JSON.stringify(queueTransactionalEmailMock.mock.calls)).not.toContain("Attacker Ltd");
});
it("requeues the committed token once before rotating again so a lost cookie response can catch up", async () => {
getRegistrationByEmailMock.mockResolvedValue({ id: "registration_1", createdTenantId: null } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
getRegistrationVerificationStateByTokenMock.mockResolvedValue({
status: "pending",
registration: pendingRegistration({ token: "different-registration-token" }),
});
await expect(
createRegistrationForm({
request,
email: "ada@example.com",
ipAddress: "203.0.113.99",
creationRequestKey: RESEND_CREATION_REQUEST_KEY,
resendOnly: true,
resendRecovery: { registrationId: "registration_1", catchUpOnly: true },
})
).resolves.toEqual({ creationRequestKey: RESEND_CREATION_REQUEST_KEY });
expect(rotateRegistrationVerificationMock).not.toHaveBeenCalled();
expect(queueTransactionalEmailMock).toHaveBeenCalledOnce();
expect(queueTransactionalEmailMock).toHaveBeenCalledWith(
expect.objectContaining({ to: "ada@example.com", data: expect.objectContaining({ name: "Ada" }) })
);
});
it("rotates an expired catch-up token and renews its verification window instead of mailing a dead link", async () => {
getRegistrationByEmailMock.mockResolvedValue({ id: "registration_1", createdTenantId: null } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
deriveSignupVerificationTokenMock
.mockReturnValueOnce("unused-outer-registration-token")
.mockReturnValueOnce("different-registration-token")
.mockReturnValueOnce("third-registration-token");
getRegistrationVerificationStateByTokenMock
.mockResolvedValueOnce({
status: "expired",
registration: pendingRegistration({ token: "different-registration-token", createdAt: new Date("2026-07-01T00:00:00.000Z") }),
})
.mockResolvedValueOnce({
status: "pending",
registration: pendingRegistration({ token: "third-registration-token", createdAt: new Date("2026-08-03T12:00:00.000Z") }),
});
await expect(
createRegistrationForm({
request,
email: "ada@example.com",
ipAddress: "203.0.113.99",
creationRequestKey: RESEND_CREATION_REQUEST_KEY,
resendOnly: true,
resendRecovery: { registrationId: "registration_1", catchUpOnly: true },
})
).resolves.toEqual({ creationRequestKey: SECOND_RESEND_CREATION_REQUEST_KEY });
expect(rotateRegistrationVerificationMock).toHaveBeenCalledWith(
"registration_1",
"different-registration-token",
"third-registration-token"
);
expect(queueTransactionalEmailMock).toHaveBeenCalledOnce();
expect(queueTransactionalEmailMock).toHaveBeenCalledWith(
expect.objectContaining({
to: "ada@example.com",
data: { action_url: expect.stringContaining("/verify/third-registration-token?creationRequestKey="), name: "Ada" },
})
);
expect(JSON.stringify(queueTransactionalEmailMock.mock.calls)).not.toContain("/verify/different-registration-token?");
});
it("coalesces a resend during the server-side cooldown without queueing another email", async () => {
getRegistrationByEmailMock.mockResolvedValue({ id: "registration_1", createdTenantId: null } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
getRegistrationByTokenMock.mockResolvedValue(
pendingRegistration({
createdAt: new Date(Date.now() - 30_000),
})
);
const result = await createRegistrationForm({
request,
email: "ada@example.com",
ipAddress: "127.0.0.1",
firstName: "Ada",
company: "Ada Co",
creationRequestKey: CREATION_REQUEST_KEY,
resendOnly: true,
});
expect(result).toEqual({ creationRequestKey: CREATION_REQUEST_KEY });
expect(rotateRegistrationVerificationMock).not.toHaveBeenCalled();
expect(queueTransactionalEmailMock).not.toHaveBeenCalled();
});
it("recovers the same resend key and mail job after response loss during a double click", async () => {
getRegistrationByEmailMock.mockResolvedValue({ id: "registration_1", createdTenantId: null } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
getRegistrationByTokenMock.mockImplementation(async (token) =>
token === "registration-token" ? pendingRegistration() : pendingRegistration({ token: "different-registration-token" })
);
rotateRegistrationVerificationMock
.mockRejectedValueOnce(new Error("rotation response lost after commit"))
.mockRejectedValueOnce(new RegistrationVerificationRotationConflictError());
const input = {
request,
email: "ada@example.com",
ipAddress: "127.0.0.1",
firstName: "Ada",
company: "Ada Co",
creationRequestKey: CREATION_REQUEST_KEY,
resendOnly: true,
};
await expect(Promise.all([createRegistrationForm(input), createRegistrationForm(input)])).resolves.toEqual([
{ creationRequestKey: RESEND_CREATION_REQUEST_KEY },
{ creationRequestKey: RESEND_CREATION_REQUEST_KEY },
]);
expect(rotateRegistrationVerificationMock).toHaveBeenCalledTimes(2);
expect(queueTransactionalEmailMock).toHaveBeenCalledTimes(2);
expect(new Set(queueTransactionalEmailMock.mock.calls.map(([mail]) => mail.idempotencyKey)).size).toBe(1);
expect(new Set(queueTransactionalEmailMock.mock.calls.map(([mail]) => mail.data.action_url)).size).toBe(1);
});
it("recovers an exact retry after the browser keeps the old key but the rotation already committed", async () => {
getRegistrationByEmailMock.mockResolvedValue({ id: "registration_1", createdTenantId: null } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
let oldTokenReads = 0;
getRegistrationByTokenMock.mockImplementation(async (token) => {
if (token !== "registration-token") return pendingRegistration({ token: "different-registration-token" });
oldTokenReads += 1;
return oldTokenReads === 1 ? pendingRegistration() : null;
});
getRegistrationVerificationStateByTokenMock.mockResolvedValue({ status: "invalid" });
rotateRegistrationVerificationMock
.mockRejectedValueOnce(new Error("rotation response lost after commit"))
.mockRejectedValueOnce(new RegistrationVerificationRotationConflictError());
const input = {
request,
email: "ada@example.com",
ipAddress: "127.0.0.1",
firstName: "Ada",
company: "Ada Co",
creationRequestKey: CREATION_REQUEST_KEY,
resendOnly: true,
};
const lostResponse = await createRegistrationForm(input);
const retry = await createRegistrationForm(input);
expect(lostResponse).toEqual({ creationRequestKey: RESEND_CREATION_REQUEST_KEY });
expect(retry).toEqual(lostResponse);
expect(getRegistrationVerificationStateByTokenMock).toHaveBeenCalledWith("registration-token");
expect(new Set(queueTransactionalEmailMock.mock.calls.map(([mail]) => mail.idempotencyKey)).size).toBe(1);
});
it("rotates an expired exact resend to a new server-generated key and invalidates the old token", async () => {
getRegistrationByEmailMock.mockResolvedValue({ id: "registration_1", createdTenantId: null } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
getRegistrationByTokenMock.mockResolvedValueOnce(null).mockResolvedValueOnce(pendingRegistration({ token: "different-registration-token" }));
getRegistrationVerificationStateByTokenMock.mockResolvedValueOnce({
status: "expired",
registration: pendingRegistration(),
});
const result = await createRegistrationForm({
request,
email: "ada@example.com",
ipAddress: "127.0.0.1",
firstName: "Ada",
company: "Ada Co",
creationRequestKey: CREATION_REQUEST_KEY,
resendOnly: true,
});
expect(result).toEqual({ creationRequestKey: RESEND_CREATION_REQUEST_KEY });
expect(getRegistrationVerificationStateByTokenMock).toHaveBeenCalledWith("registration-token");
expect(rotateRegistrationVerificationMock).toHaveBeenCalledWith("registration_1", "registration-token", "different-registration-token");
expect(createRegistrationMock).not.toHaveBeenCalled();
expect(queueTransactionalEmailMock).toHaveBeenCalledWith(
expect.objectContaining({
data: { action_url: expect.stringContaining("/verify/different-registration-token?creationRequestKey="), name: "Ada" },
idempotencyKey: expect.stringMatching(/^registration-verification:registration_1:[a-f0-9]{32}$/u),
})
);
expect(JSON.stringify(queueTransactionalEmailMock.mock.calls)).not.toContain("/verify/registration-token?");
});
it("returns a clear expiry error instead of silently reactivating an old token", async () => {
getRegistrationByEmailMock.mockResolvedValue({ id: "registration_1", createdTenantId: null } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
getRegistrationByTokenMock.mockResolvedValueOnce(null);
getRegistrationVerificationStateByTokenMock.mockResolvedValueOnce({
status: "expired",
registration: pendingRegistration(),
});
await expect(
createRegistrationForm({
request,
email: "ada@example.com",
ipAddress: "127.0.0.1",
firstName: "Ada",
company: "Ada Co",
creationRequestKey: CREATION_REQUEST_KEY,
})
).rejects.toMatchObject({ i18nKey: "account.register.errors.registrationExpired" });
expect(rotateRegistrationVerificationMock).not.toHaveBeenCalled();
expect(createRegistrationMock).not.toHaveBeenCalled();
expect(queueTransactionalEmailMock).not.toHaveBeenCalled();
});
it("rotates an expired pending row after a full reload supplies a fresh key", async () => {
const freshCreationRequestKey = "b79f4743-b5ee-48df-9287-10f24b2aedbf";
getRegistrationByEmailMock.mockResolvedValue({ id: "registration_1", createdTenantId: null } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
getRegistrationByTokenMock.mockResolvedValueOnce(null);
createRegistrationMock.mockResolvedValueOnce(
pendingRegistration({ token: "different-registration-token", createdAt: new Date("2026-07-16T08:00:00.000Z") }) as Awaited<
ReturnType<typeof createRegistration>
>
);
await expect(
createRegistrationForm({
request,
email: "ada@example.com",
ipAddress: "127.0.0.1",
firstName: "Ada",
company: "Ada Co",
creationRequestKey: freshCreationRequestKey,
})
).resolves.toEqual({ creationRequestKey: freshCreationRequestKey });
expect(createRegistrationMock).toHaveBeenCalledWith(expect.objectContaining({ token: "different-registration-token" }));
expect(queueTransactionalEmailMock).toHaveBeenCalledOnce();
});
it("recovers one logical mail job when exact expired replacements race", async () => {
const freshCreationRequestKey = "b79f4743-b5ee-48df-9287-10f24b2aedbf";
getRegistrationByEmailMock.mockResolvedValue({ id: "registration_1", createdTenantId: null } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
getRegistrationByTokenMock
.mockResolvedValueOnce(null)
.mockResolvedValueOnce(null)
.mockResolvedValueOnce(pendingRegistration({ token: "different-registration-token" }));
let replaced = false;
createRegistrationMock.mockImplementation(async () => {
if (replaced) throw new RegistrationCreateConflictError();
replaced = true;
return pendingRegistration({ token: "different-registration-token" }) as Awaited<ReturnType<typeof createRegistration>>;
});
const input = {
request,
email: "ada@example.com",
ipAddress: "127.0.0.1",
firstName: "Ada",
company: "Ada Co",
creationRequestKey: freshCreationRequestKey,
};
await expect(Promise.all([createRegistrationForm(input), createRegistrationForm(input)])).resolves.toEqual([
{ creationRequestKey: freshCreationRequestKey },
{ creationRequestKey: freshCreationRequestKey },
]);
expect(createRegistrationMock).toHaveBeenCalledTimes(2);
expect(queueTransactionalEmailMock).toHaveBeenCalledTimes(2);
expect(new Set(queueTransactionalEmailMock.mock.calls.map(([mail]) => mail.idempotencyKey)).size).toBe(1);
});
it.each([
["Prisma unique constraint", { code: "P2002" }],
["raw Postgres unique constraint", { code: "P2010", meta: { code: "23505" } }],
])("recovers an exact parallel insert race after %s and emits only one logical mail job key", async (_label, uniqueError) => {
getRegistrationByEmailMock.mockResolvedValue(null);
let inserted = false;
createRegistrationMock.mockImplementation(async () => {
if (inserted) throw uniqueError;
inserted = true;
return { id: "registration_1" } as Awaited<ReturnType<typeof createRegistration>>;
});
getRegistrationByTokenMock.mockResolvedValue(pendingRegistration());
const input = {
request,
email: "ada@example.com",
ipAddress: "127.0.0.1",
firstName: "Ada",
company: "Ada Co",
creationRequestKey: CREATION_REQUEST_KEY,
};
await expect(Promise.all([createRegistrationForm(input), createRegistrationForm(input)])).resolves.toEqual([
{ creationRequestKey: CREATION_REQUEST_KEY },
{ creationRequestKey: CREATION_REQUEST_KEY },
]);
expect(createRegistrationMock).toHaveBeenCalledTimes(2);
expect(getRegistrationByTokenMock).toHaveBeenCalledWith("registration-token");
expect(queueTransactionalEmailMock).toHaveBeenCalledTimes(2);
const jobKeys = queueTransactionalEmailMock.mock.calls.map((call) => call[0].idempotencyKey);
expect(new Set(jobKeys)).toEqual(new Set([jobKeys[0]]));
});
it("does not misclassify other raw-query failures as an insert replay", async () => {
const rawQueryFailure = { code: "P2010", meta: { code: "40001" } };
getRegistrationByEmailMock.mockResolvedValue(null);
createRegistrationMock.mockRejectedValueOnce(rawQueryFailure);
await expect(
createRegistrationForm({
request,
email: "ada@example.com",
ipAddress: "127.0.0.1",
firstName: "Ada",
company: "Ada Co",
creationRequestKey: CREATION_REQUEST_KEY,
})
).rejects.toBe(rawQueryFailure);
expect(getRegistrationByTokenMock).not.toHaveBeenCalled();
expect(queueTransactionalEmailMock).not.toHaveBeenCalled();
});
it("recovers an exact registration retry after the first verification enqueue fails", async () => {
getRegistrationByEmailMock
.mockResolvedValueOnce(null)
.mockResolvedValueOnce({ id: "registration_1", createdTenantId: null } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
createRegistrationMock.mockResolvedValueOnce({ id: "registration_1" } as Awaited<ReturnType<typeof createRegistration>>);
getRegistrationByTokenMock.mockResolvedValueOnce(pendingRegistration());
queueTransactionalEmailMock.mockRejectedValueOnce(new Error("queue unavailable"));
const input = {
request,
email: "ada@example.com",
ipAddress: "127.0.0.1",
firstName: "Ada",
company: "Ada Co",
creationRequestKey: CREATION_REQUEST_KEY,
};
await expect(createRegistrationForm(input)).rejects.toThrow("queue unavailable");
await expect(createRegistrationForm(input)).resolves.toEqual({ creationRequestKey: CREATION_REQUEST_KEY });
expect(createRegistrationMock).toHaveBeenCalledTimes(1);
expect(getRegistrationByTokenMock).toHaveBeenCalledWith("registration-token");
expect(queueTransactionalEmailMock).toHaveBeenCalledTimes(2);
expect(queueTransactionalEmailMock.mock.calls[0]?.[0]).toEqual(queueTransactionalEmailMock.mock.calls[1]?.[0]);
});
it("recovers when registration commit succeeds but its response is lost before mail enqueue", async () => {
getRegistrationByEmailMock
.mockResolvedValueOnce(null)
.mockResolvedValueOnce({ id: "registration_1", createdTenantId: null } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
createRegistrationMock.mockRejectedValueOnce(new Error("registration commit response lost"));
getRegistrationByTokenMock.mockResolvedValueOnce(pendingRegistration());
const input = {
request,
email: "ada@example.com",
ipAddress: "127.0.0.1",
firstName: "Ada",
company: "Ada Co",
creationRequestKey: CREATION_REQUEST_KEY,
};
await expect(createRegistrationForm(input)).rejects.toThrow("registration commit response lost");
expect(queueTransactionalEmailMock).not.toHaveBeenCalled();
await expect(createRegistrationForm(input)).resolves.toEqual({ creationRequestKey: CREATION_REQUEST_KEY });
expect(getRegistrationByTokenMock).toHaveBeenCalledWith("registration-token");
expect(queueTransactionalEmailMock).toHaveBeenCalledTimes(1);
});
it("persists signed lead conversion context for email verification registrations", async () => {
getRegistrationByEmailMock.mockResolvedValue(null);
createRegistrationMock.mockResolvedValue({ id: "registration_1" } as Awaited<ReturnType<typeof createRegistration>>);
await createRegistrationForm({
request,
email: "lead@example.com",
ipAddress: "127.0.0.1",
firstName: "Ada",
company: "Ada Co",
leadId: "lead_1",
leadToken: "signed-token",
leadPlanId: "plan_pro",
selectedOfficeSeatQuantity: 5,
selectedFieldSeatQuantity: 15,
creationRequestKey: CREATION_REQUEST_KEY,
});
expect(createRegistrationMock).toHaveBeenCalledWith(
expect.objectContaining({
email: "lead@example.com",
leadConversionLeadId: "lead_1",
leadConversionToken: "signed-token",
leadConversionPlanId: "plan_pro",
})
);
});
it("parses signed lead conversion fields from registration posts", async () => {
const form = new URLSearchParams({
email: "Lead@Example.com ",
password: "Password123!",
company: "Ada Co",
leadId: "lead_1",
leadToken: "signed-token",
leadPlanId: "plan_pro",
selectedOfficeSeatQuantity: "5",
selectedFieldSeatQuantity: "15",
creationRequestKey: CREATION_REQUEST_KEY,
acceptTerms: "true",
acceptPrivacy: "true",
});
await expect(
getRegistrationFormData(
new Request("https://example.com/register", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: form,
})
)
).resolves.toMatchObject({
email: "lead@example.com",
company: "Ada Co",
leadId: "lead_1",
leadToken: "signed-token",
leadPlanId: "plan_pro",
selectedOfficeSeatQuantity: 5,
selectedFieldSeatQuantity: 15,
creationRequestKey: CREATION_REQUEST_KEY,
acceptTerms: true,
acceptPrivacy: true,
});
});
it("keeps incomplete registration seat pairs incomplete for fail-closed validation", async () => {
const form = new URLSearchParams({
email: "ada@example.com",
selectedOfficeSeatQuantity: "5",
creationRequestKey: CREATION_REQUEST_KEY,
});
const parsed = await getRegistrationFormData(
new Request("https://example.com/register", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: form,
})
);
expect(parsed).toMatchObject({ selectedOfficeSeatQuantity: 5 });
expect(parsed).not.toHaveProperty("selectedFieldSeatQuantity");
});
it("does not normalize non-decimal registration seat syntax into valid quantities", async () => {
const form = new URLSearchParams({
email: "ada@example.com",
selectedOfficeSeatQuantity: "1e3",
selectedFieldSeatQuantity: "1.5",
creationRequestKey: CREATION_REQUEST_KEY,
});
const parsed = await getRegistrationFormData(
new Request("https://example.com/register", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: form,
})
);
expect(parsed.selectedOfficeSeatQuantity).toBeNaN();
expect(parsed.selectedFieldSeatQuantity).toBeNaN();
});
it("maps an authoritative explicit-slug collision to the registration field error", async () => {
createSignupTenantWithShkDefaultsMock.mockRejectedValueOnce(new TenantSlugCollisionError());
await expect(
createUserAndTenant({
request,
email: "ada@example.com",
password: "password",
company: "Ada Co",
firstName: "Ada",
lastName: "Lovelace",
slug: "ada-co",
creationRequestKey: CREATION_REQUEST_KEY,
})
).rejects.toMatchObject({ i18nKey: "account.register.errors.slugTaken" });
expect(dbMocks.transaction).not.toHaveBeenCalled();
expect(queueTransactionalEmailMock).not.toHaveBeenCalled();
});
it("stores welcome mail and canonical account event as independently replay-safe effects", async () => {
const tenant = { id: "tenant_1", name: "Ada Co", slug: "ada-co" };
const user = {
id: "user_1",
email: "ada@example.com",
firstName: "Ada",
lastName: "Lovelace",
locale: "en",
createdAt: new Date("2026-07-15T08:00:00.000Z"),
defaultTenantId: "tenant_1",
};
createSignupTenantWithShkDefaultsMock.mockResolvedValue({ tenant, user, replayed: false } as never);
const result = await createUserAndTenant({
request,
email: "ada@example.com",
password: "password",
company: "Ada Co",
firstName: "Ada",
lastName: "Lovelace",
locale: "en",
slug: "ada-co",
creationRequestKey: CREATION_REQUEST_KEY,
});
await createUserAndTenant({
request,
email: "ada@example.com",
password: "password",
company: "Ada Co",
firstName: "Ada",
lastName: "Lovelace",
locale: "en",
slug: "ada-co",
creationRequestKey: CREATION_REQUEST_KEY,
});
expect(result).toEqual({ user, tenant });
expect(createSignupTenantWithShkDefaultsMock).toHaveBeenNthCalledWith(1, {
email: "ada@example.com",
password: "password",
firstName: "Ada",
lastName: "Lovelace",
company: "Ada Co",
avatarURL: undefined,
locale: "en",
slug: "ada-co",
creationRequestKey: CREATION_REQUEST_KEY,
t: expect.any(Function),
});
expect(postCommitState.transactionContexts).toEqual([
expect.objectContaining({ tenantId: "tenant_1", userId: "user_1" }),
expect.objectContaining({ tenantId: "tenant_1", userId: "user_1" }),
]);
expect(postCommitState.markers).toHaveLength(1);
expect([...postCommitState.markers.values()][0]).toMatchObject({
responseStatus: 201,
responseBody: { state: "completed" },
});
expect(postCommitState.events).toEqual([]);
expect(postCommitState.outbox).toEqual([
expect.objectContaining({
eventType: "mail.transactional.send",
dispatchKey: `mail:signup-welcome:tenant_1:${CREATION_REQUEST_KEY}`,
payload: expect.objectContaining({
tenantId: "tenant_1",
to: ["ada@example.com"],
subject: "Welcome",
text: "Welcome at https://example.com/login for Ada",
html: "<p>Welcome at https://example.com/login for Ada</p>",
}),
}),
]);
expect(eventServiceMocks.createIdempotentTenantEvent).toHaveBeenCalledTimes(2);
expect(eventServiceMocks.createIdempotentTenantEvent).toHaveBeenNthCalledWith(1, {
event: "account.created",
tenantId: "tenant_1",
userId: "user_1",
data: {
tenant: { id: "tenant_1", name: "Ada Co", slug: "ada-co" },
user: { id: "user_1", email: "ada@example.com" },
},
idempotencyKey: `signup-account-created:tenant_1:${CREATION_REQUEST_KEY}`,
});
expect(postCommitState.accountEventKeys).toEqual(new Set([`signup-account-created:tenant_1:${CREATION_REQUEST_KEY}`]));
expect(postCommitState.logicalAdminNotifications).toBe(1);
expect(queueTransactionalEmailMock).not.toHaveBeenCalled();
expect(welcomeParseMock).toHaveBeenCalledWith(
expect.objectContaining({
appConfiguration,
data: {
action_url: "https://example.com/login",
name: "Ada",
},
t: expect.any(Function),
locale: expect.any(String),
})
);
expect(sendEmailMock).not.toHaveBeenCalled();
});
it("scopes a reused browser request key to each committed tenant account event", async () => {
const first = {
tenant: { id: "tenant_1", name: "Ada Co", slug: "ada-co" },
user: { id: "user_1", email: "ada@example.com", firstName: "Ada", lastName: "Lovelace", locale: "en" },
};
const second = {
tenant: { id: "tenant_2", name: "Grace Co", slug: "grace-co" },
user: { id: "user_2", email: "grace@example.com", firstName: "Grace", lastName: "Hopper", locale: "en" },
};
createSignupTenantWithShkDefaultsMock
.mockResolvedValueOnce({ ...first, replayed: false } as never)
.mockResolvedValueOnce({ ...second, replayed: false } as never);
await createUserAndTenant({
request,
email: first.user.email,
password: "password",
company: first.tenant.name,
firstName: first.user.firstName,
lastName: first.user.lastName,
creationRequestKey: CREATION_REQUEST_KEY,
});
await createUserAndTenant({
request,
email: second.user.email,
password: "password",
company: second.tenant.name,
firstName: second.user.firstName,
lastName: second.user.lastName,
creationRequestKey: CREATION_REQUEST_KEY,
});
expect(eventServiceMocks.createIdempotentTenantEvent.mock.calls.map(([input]) => input.idempotencyKey)).toEqual([
`signup-account-created:tenant_1:${CREATION_REQUEST_KEY}`,
`signup-account-created:tenant_2:${CREATION_REQUEST_KEY}`,
]);
expect(postCommitState.accountEventKeys.size).toBe(2);
expect(postCommitState.logicalAdminNotifications).toBe(2);
});
it("rolls back an unavailable outbox transaction and writes each durable effect exactly once on retry", async () => {
const tenant = { id: "tenant_1", name: "Ada Co", slug: "ada-co" };
const user = {
id: "user_1",
email: "ada@example.com",
firstName: "Ada",
lastName: "Lovelace",
locale: "en",
createdAt: new Date("2026-07-15T08:00:00.000Z"),
defaultTenantId: "tenant_1",
};
createSignupTenantWithShkDefaultsMock.mockResolvedValue({ tenant, user, replayed: false } as never);
postCommitState.failNextOutboxCreate = true;
await expect(
createUserAndTenant({
request,
email: user.email,
password: "password",
company: tenant.name,
firstName: user.firstName,
lastName: user.lastName,
creationRequestKey: CREATION_REQUEST_KEY,
})
).rejects.toThrow("outbox temporarily unavailable");
expect(postCommitState.markers).toHaveLength(0);
expect(postCommitState.events).toHaveLength(0);
expect(postCommitState.outbox).toHaveLength(0);
expect(eventServiceMocks.createIdempotentTenantEvent).not.toHaveBeenCalled();
await expect(
createUserAndTenant({
request,
email: user.email,
password: "password",
company: tenant.name,
firstName: user.firstName,
lastName: user.lastName,
creationRequestKey: CREATION_REQUEST_KEY,
})
).resolves.toEqual({ user, tenant });
expect(postCommitState.markers).toHaveLength(1);
expect(postCommitState.events).toHaveLength(0);
expect(postCommitState.outbox).toHaveLength(1);
expect(eventServiceMocks.createIdempotentTenantEvent).toHaveBeenCalledOnce();
expect(postCommitState.logicalAdminNotifications).toBe(1);
expect(queueTransactionalEmailMock).not.toHaveBeenCalled();
});
it("replays the canonical account event after welcome mail already committed", async () => {
const tenant = { id: "tenant_1", name: "Ada Co", slug: "ada-co" };
const user = {
id: "user_1",
email: "ada@example.com",
firstName: "Ada",
lastName: "Lovelace",
locale: "en",
createdAt: new Date("2026-07-15T08:00:00.000Z"),
defaultTenantId: "tenant_1",
};
createSignupTenantWithShkDefaultsMock.mockResolvedValue({ tenant, user, replayed: false } as never);
eventServiceMocks.createIdempotentTenantEvent.mockRejectedValueOnce(new Error("event transaction unavailable"));
const input = {
request,
email: user.email,
password: "password",
company: tenant.name,
firstName: user.firstName,
lastName: user.lastName,
creationRequestKey: CREATION_REQUEST_KEY,
};
await expect(createUserAndTenant(input)).rejects.toThrow("event transaction unavailable");
expect(postCommitState.markers).toHaveLength(1);
expect(postCommitState.outbox).toHaveLength(1);
expect(postCommitState.logicalAdminNotifications).toBe(0);
await expect(createUserAndTenant(input)).resolves.toEqual({ user, tenant });
expect(postCommitState.markers).toHaveLength(1);
expect(postCommitState.outbox).toHaveLength(1);
expect(eventServiceMocks.createIdempotentTenantEvent).toHaveBeenCalledTimes(2);
expect(postCommitState.logicalAdminNotifications).toBe(1);
});
it("does not create a session-side mail or event transaction when exact password replay verification fails", async () => {
createSignupTenantWithShkDefaultsMock.mockRejectedValueOnce(new Error("signup replay conflict"));
await expect(
createUserAndTenant({
request,
email: "ada@example.com",
password: "wrong password",
company: "Ada Co",
firstName: "Ada",
lastName: "Lovelace",
creationRequestKey: CREATION_REQUEST_KEY,
})
).rejects.toThrow("signup replay conflict");
expect(dbMocks.transaction).not.toHaveBeenCalled();
expect(postCommitState.markers).toHaveLength(0);
expect(postCommitState.events).toHaveLength(0);
expect(postCommitState.outbox).toHaveLength(0);
expect(eventServiceMocks.createIdempotentTenantEvent).not.toHaveBeenCalled();
expect(queueTransactionalEmailMock).not.toHaveBeenCalled();
});
it("throws for already-created registrations without enqueueing", async () => {
getRegistrationByEmailMock.mockResolvedValue({ id: "registration_1", createdTenantId: "tenant_1" } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
await expect(
createRegistrationForm({
request,
email: "ada@example.com",
ipAddress: "127.0.0.1",
creationRequestKey: CREATION_REQUEST_KEY,
})
).rejects.toThrow("api.errors.userAlreadyRegistered");
expect(getRegistrationByTokenMock).not.toHaveBeenCalled();
expect(createRegistrationMock).not.toHaveBeenCalled();
expect(queueTransactionalEmailMock).not.toHaveBeenCalled();
expect(sendEmailMock).not.toHaveBeenCalled();
});
});