1191 lines
51 KiB
TypeScript
1191 lines
51 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { action, headers, loader } from "./invitation.$id";
|
|
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
|
import { queueTransactionalEmail } from "~/modules/emails/services/TransactionalEmailQueue.server";
|
|
import { sendEmail } from "~/modules/emails/services/EmailService";
|
|
import EmailTemplates from "~/modules/emails/utils/EmailTemplates";
|
|
import { emitUserCreatedHook, getUser, getUserByEmail, register } from "~/utils/db/users.db.server";
|
|
import { createTenantUser, getInvitationTenantIdentity, getTenantUserByIds } from "~/utils/db/tenants.db.server";
|
|
import { getAllRoles } from "~/utils/db/permissions/roles.db.server";
|
|
import { createUserSession, getUserInfo, setLoggedUser, validateCSRFToken } from "~/utils/session.server";
|
|
import EventsService from "~/modules/events/services/.server/EventsService";
|
|
import {
|
|
acceptWorkspaceInvite,
|
|
getWorkspaceInviteByToken,
|
|
hashWorkspaceInviteToken,
|
|
type WorkspaceInviteClient,
|
|
WorkspaceInviteError,
|
|
} from "@hivegrid/db/workspace-invites.server";
|
|
import { getDbClient } from "@hivegrid/db/client.server";
|
|
import { loadRequiredWebConfig } from "@hivegrid/config";
|
|
import { beginAlternativeLoginMfa } from "~/services/auth/alternative-login-mfa.server";
|
|
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
|
|
import { claimReservedTenantWithShkDefaults } from "~/domain/tenant-bootstrap/tenantBootstrapService.server";
|
|
import { hashPassword } from "~/utils/auth/passwordHasher.server";
|
|
import { checkAuthRateLimit } from "~/services/auth/auth-rate-limit.server";
|
|
|
|
vi.mock("~/utils/db/appConfiguration.db.server", () => ({
|
|
getAppConfiguration: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/lib/metrics/ssr", () => ({
|
|
withMetrics: (_name: string, handler: unknown) => handler,
|
|
}));
|
|
|
|
vi.mock("@hivegrid/config", () => ({
|
|
loadRequiredWebConfig: vi.fn(() => ({
|
|
routing: {
|
|
adminAppHost: "admin.example.test",
|
|
apiHost: "api.example.test",
|
|
appBaseDomain: "example.test",
|
|
protocol: "https",
|
|
webAppHost: "app.example.test",
|
|
},
|
|
})),
|
|
}));
|
|
|
|
vi.mock("~/services/auth/password-policy.server", () => ({
|
|
validatePassword: vi.fn(async () => ({ valid: true, errors: [] })),
|
|
loadPasswordPolicy: vi.fn(() => ({
|
|
minLength: 1,
|
|
requireUpper: false,
|
|
requireLower: false,
|
|
requireDigit: false,
|
|
requireSpecial: false,
|
|
hibpCheck: false,
|
|
hibpMaxOccurrences: 0,
|
|
})),
|
|
MIN_PASSWORD_LENGTH: 12,
|
|
}));
|
|
|
|
vi.mock("~/utils/auth/passwordHasher.server", () => ({
|
|
hashPassword: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/services/auth/invitation-password.server", () => ({
|
|
createInvitationMagicLinkPassword: vi.fn(() => "generated-magic-link-password"),
|
|
}));
|
|
|
|
vi.mock("~/services/auth/auth-rate-limit.server", () => ({
|
|
checkAuthRateLimit: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/modules/emails/services/TransactionalEmailQueue.server", () => ({
|
|
queueTransactionalEmail: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/modules/emails/services/EmailService", () => ({
|
|
sendEmail: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/modules/emails/utils/EmailTemplates", () => ({
|
|
default: {
|
|
WELCOME_EMAIL: {
|
|
parse: vi.fn(({ data }) => ({
|
|
subject: "Welcome to Example",
|
|
body: `<p>Welcome ${data.name} at ${data.action_url}</p>`,
|
|
})),
|
|
},
|
|
},
|
|
}));
|
|
|
|
vi.mock("~/utils/url.server", () => ({
|
|
getAbsoluteUrl: vi.fn((_request: Request, path: string) => `https://example.com${path}`),
|
|
}));
|
|
|
|
vi.mock("~/utils/logger.server", () => ({
|
|
createScopedLogger: vi.fn(() => ({ debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() })),
|
|
}));
|
|
|
|
vi.mock("~/utils/safeErrorLog.server", () => ({
|
|
toSafeErrorLog: vi.fn(() => ({ err: { name: "Error" } })),
|
|
}));
|
|
|
|
vi.mock("~/locale/i18next.server", () => ({
|
|
enabledLocales: ["de", "en"],
|
|
getTranslations: vi.fn(async () => ({ t: (key: string) => key })),
|
|
remixI18Next: {
|
|
getFixedT: vi.fn(async () => (key: string) => key),
|
|
getLocale: vi.fn(async () => "en"),
|
|
},
|
|
}));
|
|
|
|
vi.mock("~/components/brand/Logo", () => ({ default: () => null }));
|
|
vi.mock("~/components/ui/buttons/LoadingButton", () => ({ default: () => null }));
|
|
vi.mock("~/components/ui/modals/ErrorModal", () => ({ default: () => null }));
|
|
vi.mock("~/components/ui/banners/SuccessBanner", () => ({ default: () => null }));
|
|
vi.mock("~/components/ui/button", () => ({ Button: ({ children }: { children: React.ReactNode }) => <>{children}</> }));
|
|
|
|
vi.mock("~/utils/db/users.db.server", () => ({
|
|
emitUserCreatedHook: vi.fn(),
|
|
getUser: vi.fn(),
|
|
getUserByEmail: vi.fn(),
|
|
register: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("@hivegrid/db/client.server", () => ({
|
|
getDbClient: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("@hivegrid/db/workspace-invites.server", async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import("@hivegrid/db/workspace-invites.server")>();
|
|
return {
|
|
...actual,
|
|
acceptWorkspaceInvite: vi.fn(actual.acceptWorkspaceInvite),
|
|
getWorkspaceInviteByToken: vi.fn(),
|
|
};
|
|
});
|
|
|
|
vi.mock("~/utils/db/tenants.db.server", () => ({
|
|
createTenantUser: vi.fn(),
|
|
getInvitationTenantIdentity: vi.fn(),
|
|
getTenantUserByIds: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/domain/tenant-bootstrap/tenantBootstrapService.server", () => ({
|
|
claimReservedTenantWithShkDefaults: vi.fn(),
|
|
TENANT_PENDING_OWNER_REASON: "pending_owner",
|
|
}));
|
|
|
|
vi.mock("~/utils/db/permissions/roles.db.server", () => ({
|
|
getAllRoles: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/utils/session.server", () => ({
|
|
createUserSession: vi.fn(),
|
|
getUserInfo: vi.fn(),
|
|
setLoggedUser: vi.fn(),
|
|
validateCSRFToken: vi.fn(),
|
|
}));
|
|
vi.mock("~/services/auth/alternative-login-mfa.server", () => ({
|
|
beginAlternativeLoginMfa: vi.fn(),
|
|
LOGIN_MFA_CHALLENGE_PATH: "/login-mfa",
|
|
}));
|
|
|
|
vi.mock("~/modules/events/services/.server/EventsService", () => ({
|
|
default: {
|
|
create: vi.fn(),
|
|
createIdempotentTenantEvent: vi.fn(),
|
|
},
|
|
}));
|
|
|
|
const appConfiguration = { app: { name: "Example" } } as Awaited<ReturnType<typeof getAppConfiguration>>;
|
|
const invitation = {
|
|
id: "invitation_1",
|
|
email: "invitee@example.com",
|
|
firstName: "Ada",
|
|
lastName: "Lovelace",
|
|
tenantId: "tenant_1",
|
|
type: 2,
|
|
fromUserId: "from_user_1",
|
|
tenant: { id: "tenant_1", name: "Example Co", slug: "example-co" },
|
|
};
|
|
const workspaceInvite = {
|
|
id: invitation.id,
|
|
email: invitation.email,
|
|
firstName: invitation.firstName,
|
|
lastName: invitation.lastName,
|
|
tenantId: invitation.tenantId,
|
|
type: invitation.type,
|
|
fromUserId: invitation.fromUserId,
|
|
pending: true,
|
|
status: "pending",
|
|
tokenPrefix: "invite-token".slice(0, 12),
|
|
createdUserId: null,
|
|
acceptedByUserId: null,
|
|
revokedByUserId: null,
|
|
expiresAt: new Date("2030-01-01T00:00:00.000Z"),
|
|
acceptedAt: null,
|
|
revokedAt: null,
|
|
} as Awaited<ReturnType<typeof getWorkspaceInviteByToken>>;
|
|
const role = { id: "role_1", assignToNewUsers: true, isDefault: true } as Awaited<ReturnType<typeof getAllRoles>>[number];
|
|
const tenantScopedRole = { id: "role_tenant", assignToNewUsers: true, isDefault: false } as Awaited<ReturnType<typeof getAllRoles>>[number];
|
|
|
|
const getAppConfigurationMock = vi.mocked(getAppConfiguration);
|
|
const queueTransactionalEmailMock = vi.mocked(queueTransactionalEmail);
|
|
const sendEmailMock = vi.mocked(sendEmail);
|
|
const welcomeParseMock = vi.mocked(EmailTemplates.WELCOME_EMAIL.parse);
|
|
const getUserMock = vi.mocked(getUser);
|
|
const getUserByEmailMock = vi.mocked(getUserByEmail);
|
|
const registerMock = vi.mocked(register);
|
|
const emitUserCreatedHookMock = vi.mocked(emitUserCreatedHook);
|
|
const acceptWorkspaceInviteMock = vi.mocked(acceptWorkspaceInvite);
|
|
const getWorkspaceInviteByTokenMock = vi.mocked(getWorkspaceInviteByToken);
|
|
const getDbClientMock = vi.mocked(getDbClient);
|
|
const createTenantUserMock = vi.mocked(createTenantUser);
|
|
const getInvitationTenantIdentityMock = vi.mocked(getInvitationTenantIdentity);
|
|
const getTenantUserByIdsMock = vi.mocked(getTenantUserByIds);
|
|
const getAllRolesMock = vi.mocked(getAllRoles);
|
|
const createUserSessionMock = vi.mocked(createUserSession);
|
|
const getUserInfoMock = vi.mocked(getUserInfo);
|
|
const setLoggedUserMock = vi.mocked(setLoggedUser);
|
|
const validateCSRFTokenMock = vi.mocked(validateCSRFToken);
|
|
const eventsCreateMock = vi.mocked(EventsService.create);
|
|
const loadRequiredWebConfigMock = vi.mocked(loadRequiredWebConfig);
|
|
const beginAlternativeLoginMfaMock = vi.mocked(beginAlternativeLoginMfa);
|
|
const claimReservedTenantWithShkDefaultsMock = vi.mocked(claimReservedTenantWithShkDefaults);
|
|
const eventsCreateIdempotentMock = vi.mocked(EventsService.createIdempotentTenantEvent);
|
|
const hashPasswordMock = vi.mocked(hashPassword);
|
|
const checkAuthRateLimitMock = vi.mocked(checkAuthRateLimit);
|
|
let eventRlsContexts: Array<ReturnType<typeof getRlsExecutionContext>> = [];
|
|
let transactionInvite = {
|
|
...workspaceInvite!,
|
|
tokenHash: hashWorkspaceInviteToken("invite-token"),
|
|
};
|
|
let transactionMembership: { tenantId: string; userId: string; status: number } | null = null;
|
|
let registeredUserIds = new Set<string>();
|
|
let transactionTail: Promise<void> = Promise.resolve();
|
|
const transactionClient = {
|
|
tenantUserInvitation: {
|
|
findFirst: vi.fn(async () => ({ ...transactionInvite })),
|
|
findMany: vi.fn(async () => [{ ...transactionInvite }]),
|
|
create: vi.fn(),
|
|
update: vi.fn(),
|
|
updateMany: vi.fn(async ({ where, data }: { where: Record<string, unknown>; data: Record<string, unknown> }) => {
|
|
if (
|
|
transactionInvite.pending !== true ||
|
|
transactionInvite.status !== "pending" ||
|
|
where.createdUserId !== transactionInvite.createdUserId ||
|
|
where.tokenHash !== transactionInvite.tokenHash
|
|
) {
|
|
return { count: 0 };
|
|
}
|
|
transactionInvite = { ...transactionInvite, ...data };
|
|
return { count: 1 };
|
|
}),
|
|
},
|
|
} as unknown as WorkspaceInviteClient;
|
|
|
|
async function runFakeTransaction<T>(callback: (transaction: WorkspaceInviteClient) => Promise<T>): Promise<T> {
|
|
const previous = transactionTail;
|
|
let release!: () => void;
|
|
transactionTail = new Promise<void>((resolve) => {
|
|
release = resolve;
|
|
});
|
|
await previous;
|
|
const inviteBefore = { ...transactionInvite };
|
|
const membershipBefore = transactionMembership ? { ...transactionMembership } : null;
|
|
const registeredUsersBefore = new Set(registeredUserIds);
|
|
try {
|
|
return await callback(transactionClient);
|
|
} catch (error) {
|
|
transactionInvite = inviteBefore;
|
|
transactionMembership = membershipBefore;
|
|
registeredUserIds = registeredUsersBefore;
|
|
throw error;
|
|
} finally {
|
|
release();
|
|
}
|
|
}
|
|
|
|
async function postInvitation(intent = "set-password") {
|
|
const form = new FormData();
|
|
form.set("intent", intent);
|
|
form.set("password", "password");
|
|
form.set("password-confirm", "password");
|
|
form.set("csrf", "csrf-token");
|
|
|
|
return action({
|
|
request: new Request("https://example.com/invitation/invite-token", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
body: new URLSearchParams(form as unknown as Record<string, string>),
|
|
}),
|
|
params: { id: "invite-token" },
|
|
context: {},
|
|
} as unknown as Parameters<typeof action>[0]);
|
|
}
|
|
|
|
async function readJson(response: unknown) {
|
|
expect(response).toBeInstanceOf(Response);
|
|
return (response as Response).json();
|
|
}
|
|
|
|
function configureOwnerInvitation({
|
|
status = "pending",
|
|
acceptedByUserId = null,
|
|
createdUserId = null,
|
|
active = false,
|
|
deactivatedReason = "pending_owner",
|
|
}: {
|
|
status?: "pending" | "accepted" | "expired" | "revoked";
|
|
acceptedByUserId?: string | null;
|
|
createdUserId?: string | null;
|
|
active?: boolean;
|
|
deactivatedReason?: string | null;
|
|
} = {}) {
|
|
getWorkspaceInviteByTokenMock.mockResolvedValue({
|
|
...workspaceInvite!,
|
|
type: 0,
|
|
status,
|
|
pending: status === "pending",
|
|
acceptedByUserId,
|
|
createdUserId,
|
|
acceptedAt: status === "accepted" ? new Date("2026-07-15T11:05:00.000Z") : null,
|
|
} as Awaited<ReturnType<typeof getWorkspaceInviteByToken>>);
|
|
getInvitationTenantIdentityMock.mockImplementation(async () => {
|
|
expect(getRlsExecutionContext()).toMatchObject({ tenantId: "tenant_1" });
|
|
return { id: "tenant_1", name: "Example Co", slug: "example-co", active, deactivatedReason };
|
|
});
|
|
}
|
|
|
|
function configureAuthenticatedExistingUser(userId = "existing_user_1") {
|
|
const existingUser = {
|
|
id: userId,
|
|
email: "invitee@example.com",
|
|
firstName: "Ada",
|
|
lastName: "Lovelace",
|
|
locale: "en",
|
|
defaultTenantId: null,
|
|
createdAt: new Date("2026-07-01T10:00:00.000Z"),
|
|
} as Awaited<ReturnType<typeof getUserByEmail>>;
|
|
getUserByEmailMock.mockResolvedValue(existingUser);
|
|
getUserMock.mockImplementation(async (requestedUserId) =>
|
|
requestedUserId === userId
|
|
? (existingUser as Awaited<ReturnType<typeof getUser>>)
|
|
: ({ id: "from_user_1", email: "owner@example.com" } as Awaited<ReturnType<typeof getUser>>)
|
|
);
|
|
getUserInfoMock.mockResolvedValue({ userId, lng: "en", lightOrDarkMode: "light" } as Awaited<ReturnType<typeof getUserInfo>>);
|
|
return existingUser;
|
|
}
|
|
|
|
describe("invitation action transactional welcome email", () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
transactionInvite = { ...workspaceInvite!, tokenHash: hashWorkspaceInviteToken("invite-token") };
|
|
transactionMembership = null;
|
|
registeredUserIds = new Set<string>();
|
|
transactionTail = Promise.resolve();
|
|
getAppConfigurationMock.mockResolvedValue(appConfiguration);
|
|
queueTransactionalEmailMock.mockResolvedValue({ enqueued: true, jobId: "job_1" });
|
|
getWorkspaceInviteByTokenMock.mockResolvedValue(workspaceInvite);
|
|
getDbClientMock.mockReturnValue({
|
|
$transaction: vi.fn((callback: (transaction: WorkspaceInviteClient) => Promise<unknown>) => runFakeTransaction(callback)),
|
|
} as unknown as ReturnType<typeof getDbClient>);
|
|
getTenantUserByIdsMock.mockImplementation(async (_tenantId, userId) =>
|
|
transactionMembership?.userId === userId ? (transactionMembership as Awaited<ReturnType<typeof getTenantUserByIds>>) : null
|
|
);
|
|
getUserMock.mockResolvedValue({ id: "from_user_1", email: "owner@example.com" } as Awaited<ReturnType<typeof getUser>>);
|
|
getUserByEmailMock.mockResolvedValue(null);
|
|
registerMock.mockImplementation(async (input) => {
|
|
const createdAt = new Date("2026-07-15T11:00:00.000Z");
|
|
const createdUser = {
|
|
id: "user_1",
|
|
email: "invitee@example.com",
|
|
passwordHash: "hash",
|
|
firstName: "Ada",
|
|
lastName: "Lovelace",
|
|
avatar: "",
|
|
phone: "",
|
|
active: true,
|
|
defaultTenantId: null,
|
|
locale: "en",
|
|
createdAt,
|
|
};
|
|
return runFakeTransaction(async (transaction) => {
|
|
registeredUserIds.add(createdUser.id);
|
|
await input.transactionalMutation?.(transaction as never, createdUser as never);
|
|
return { id: createdUser.id, email: createdUser.email, locale: createdUser.locale, defaultTenantId: null, createdAt };
|
|
});
|
|
});
|
|
hashPasswordMock.mockResolvedValue("$argon2id$prepared-owner-password");
|
|
checkAuthRateLimitMock.mockResolvedValue({ allowed: true });
|
|
claimReservedTenantWithShkDefaultsMock.mockImplementation(
|
|
async (input) =>
|
|
({
|
|
tenant: {
|
|
id: "tenant_1",
|
|
name: "Example Co",
|
|
slug: "example-co",
|
|
active: true,
|
|
deactivatedReason: null,
|
|
},
|
|
user: {
|
|
id: input.userId,
|
|
email: "invitee@example.com",
|
|
firstName: "Ada",
|
|
lastName: "Lovelace",
|
|
locale: "en",
|
|
createdAt: new Date("2026-07-15T11:00:00.000Z"),
|
|
defaultTenantId: "tenant_1",
|
|
},
|
|
replayed: false,
|
|
}) as Awaited<ReturnType<typeof claimReservedTenantWithShkDefaults>>
|
|
);
|
|
getAllRolesMock.mockResolvedValue([role] as Awaited<ReturnType<typeof getAllRoles>>);
|
|
createTenantUserMock.mockImplementation(async ({ tenantId, userId }) => {
|
|
transactionMembership = { tenantId, userId, status: 1 };
|
|
return { id: "tenant_user_1" } as Awaited<ReturnType<typeof createTenantUser>>;
|
|
});
|
|
eventRlsContexts = [];
|
|
eventsCreateMock.mockImplementation(async () => {
|
|
eventRlsContexts.push(getRlsExecutionContext());
|
|
return {} as Awaited<ReturnType<typeof EventsService.create>>;
|
|
});
|
|
eventsCreateIdempotentMock.mockImplementation(async () => {
|
|
eventRlsContexts.push(getRlsExecutionContext());
|
|
return {} as Awaited<ReturnType<typeof EventsService.createIdempotentTenantEvent>>;
|
|
});
|
|
getUserInfoMock.mockResolvedValue({ lng: "en", lightOrDarkMode: "light" } as Awaited<ReturnType<typeof getUserInfo>>);
|
|
setLoggedUserMock.mockImplementation(
|
|
async (user) =>
|
|
({
|
|
userId: user.id,
|
|
defaultTenantId: "tenant_1",
|
|
defaultTenant: { id: "tenant_1", name: "Example Co", slug: "example-co", active: true, deactivatedReason: null },
|
|
}) as Awaited<ReturnType<typeof setLoggedUser>>
|
|
);
|
|
getInvitationTenantIdentityMock.mockImplementation(async () => {
|
|
expect(getRlsExecutionContext()).toMatchObject({ tenantId: "tenant_1" });
|
|
return { id: "tenant_1", name: "Example Co", slug: "example-co", active: true, deactivatedReason: null };
|
|
});
|
|
createUserSessionMock.mockResolvedValue(
|
|
new Response(null, { status: 302, headers: { Location: "/example-co/dashboard" } }) as Awaited<ReturnType<typeof createUserSession>>
|
|
);
|
|
beginAlternativeLoginMfaMock.mockResolvedValue({ required: false });
|
|
loadRequiredWebConfigMock.mockReturnValue({
|
|
routing: {
|
|
adminAppHost: "admin.example.test",
|
|
apiHost: "api.example.test",
|
|
appBaseDomain: "example.test",
|
|
protocol: "https",
|
|
webAppHost: "app.example.test",
|
|
},
|
|
} as ReturnType<typeof loadRequiredWebConfig>);
|
|
});
|
|
|
|
it("precomputes the accepted-invitation sign-in path in the loader", async () => {
|
|
getUserByEmailMock.mockResolvedValueOnce({
|
|
id: "existing_user_1",
|
|
email: "invitee@example.com",
|
|
passwordHash: "must-never-reach-hydration",
|
|
totpSecretEncrypted: "must-never-reach-hydration",
|
|
} as Awaited<ReturnType<typeof getUserByEmail>>);
|
|
const response = await loader({
|
|
request: new Request("https://example.com/invitation/invite-token"),
|
|
params: { id: "invite-token" },
|
|
context: {},
|
|
} as unknown as Parameters<typeof loader>[0]);
|
|
|
|
expect(response).toMatchObject({
|
|
appRootPath: "https://app.example.test/",
|
|
existingUser: { id: "existing_user_1" },
|
|
invitation: expect.objectContaining({
|
|
email: "invitee@example.com",
|
|
tenant: { name: "Example Co" },
|
|
}),
|
|
});
|
|
expect(JSON.stringify(response)).not.toContain("passwordHash");
|
|
expect(JSON.stringify(response)).not.toContain("totpSecretEncrypted");
|
|
expect(JSON.stringify(response)).not.toContain("themeConfig");
|
|
expect(getInvitationTenantIdentityMock).toHaveBeenCalledWith("tenant_1");
|
|
expect(checkAuthRateLimitMock).toHaveBeenCalledWith({
|
|
request: expect.any(Request),
|
|
action: "invitation-view",
|
|
identifier: "invite-token",
|
|
limit: 30,
|
|
identifierLimit: 120,
|
|
clientLimit: 300,
|
|
windowMs: 15 * 60 * 1000,
|
|
});
|
|
expect(headers()).toEqual({ "Cache-Control": "no-store", "Referrer-Policy": "no-referrer" });
|
|
});
|
|
|
|
it("fails closed before the loader lookup when the invitation throttle denies or its store is unavailable", async () => {
|
|
checkAuthRateLimitMock.mockResolvedValueOnce({ allowed: false, retryAfterSeconds: 47 });
|
|
|
|
const response = await loader({
|
|
request: new Request("https://example.com/invitation/invite-token"),
|
|
params: { id: "invite-token" },
|
|
context: {},
|
|
} as unknown as Parameters<typeof loader>[0]);
|
|
|
|
expect(response).toBeInstanceOf(Response);
|
|
expect((response as Response).status).toBe(429);
|
|
expect((response as Response).headers.get("Retry-After")).toBe("47");
|
|
expect((response as Response).headers.get("Cache-Control")).toBe("no-store");
|
|
await expect((response as Response).json()).resolves.toMatchObject({ invitation: null, existingUser: null });
|
|
expect(getWorkspaceInviteByTokenMock).not.toHaveBeenCalled();
|
|
expect(getInvitationTenantIdentityMock).not.toHaveBeenCalled();
|
|
expect(getUserByEmailMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("fails closed before CSRF and invitation lookup when the action throttle denies", async () => {
|
|
checkAuthRateLimitMock.mockResolvedValueOnce({ allowed: false, retryAfterSeconds: 61 });
|
|
|
|
const response = await postInvitation();
|
|
|
|
expect(response).toBeInstanceOf(Response);
|
|
expect((response as Response).status).toBe(429);
|
|
expect((response as Response).headers.get("Retry-After")).toBe("61");
|
|
await expect((response as Response).json()).resolves.toEqual({ error: "auth:invitation.errors.invalid" });
|
|
expect(checkAuthRateLimitMock).toHaveBeenCalledWith({
|
|
request: expect.any(Request),
|
|
action: "invitation-accept",
|
|
identifier: "invite-token",
|
|
limit: 10,
|
|
identifierLimit: 30,
|
|
clientLimit: 100,
|
|
windowMs: 15 * 60 * 1000,
|
|
});
|
|
expect(validateCSRFTokenMock).not.toHaveBeenCalled();
|
|
expect(getWorkspaceInviteByTokenMock).not.toHaveBeenCalled();
|
|
expect(registerMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("renders an accepted owner invitation as replayable only for the same authenticated owner", async () => {
|
|
configureOwnerInvitation({
|
|
status: "accepted",
|
|
acceptedByUserId: "existing_user_1",
|
|
active: true,
|
|
deactivatedReason: null,
|
|
});
|
|
configureAuthenticatedExistingUser();
|
|
|
|
const response = await loader({
|
|
request: new Request("https://example.com/invitation/invite-token"),
|
|
params: { id: "invite-token" },
|
|
context: {},
|
|
} as unknown as Parameters<typeof loader>[0]);
|
|
|
|
expect(response).toMatchObject({
|
|
invitation: expect.objectContaining({ pending: true }),
|
|
existingUser: { id: "existing_user_1" },
|
|
});
|
|
expect(getUserByEmailMock).not.toHaveBeenCalled();
|
|
|
|
getUserInfoMock.mockResolvedValueOnce({ userId: "different_user", lng: "en", lightOrDarkMode: "light" } as Awaited<ReturnType<typeof getUserInfo>>);
|
|
getUserByEmailMock.mockResolvedValueOnce(null);
|
|
const deniedReplay = await loader({
|
|
request: new Request("https://example.com/invitation/invite-token"),
|
|
params: { id: "invite-token" },
|
|
context: {},
|
|
} as unknown as Parameters<typeof loader>[0]);
|
|
|
|
expect(deniedReplay).toMatchObject({ invitation: null, existingUser: null });
|
|
expect(JSON.stringify(deniedReplay)).not.toContain("invitee@example.com");
|
|
expect(JSON.stringify(deniedReplay)).not.toContain("Example Co");
|
|
|
|
getWorkspaceInviteByTokenMock.mockResolvedValueOnce({
|
|
...workspaceInvite!,
|
|
pending: false,
|
|
status: "accepted",
|
|
acceptedAt: new Date("2026-07-15T11:05:00.000Z"),
|
|
acceptedByUserId: "member_1",
|
|
} as Awaited<ReturnType<typeof getWorkspaceInviteByToken>>);
|
|
const acceptedMember = await loader({
|
|
request: new Request("https://example.com/invitation/invite-token"),
|
|
params: { id: "invite-token" },
|
|
context: {},
|
|
} as unknown as Parameters<typeof loader>[0]);
|
|
|
|
expect(acceptedMember).toMatchObject({ invitation: null, existingUser: null });
|
|
expect(JSON.stringify(acceptedMember)).not.toContain("invitee@example.com");
|
|
expect(JSON.stringify(acceptedMember)).not.toContain("Example Co");
|
|
});
|
|
|
|
it("enqueues welcome email only after persisting a new invited user", async () => {
|
|
const response = await postInvitation();
|
|
|
|
expect(response).toBeInstanceOf(Response);
|
|
expect(validateCSRFTokenMock).toHaveBeenCalledOnce();
|
|
const [csrfRequest, csrfOptions] = validateCSRFTokenMock.mock.calls[0]!;
|
|
expect(csrfRequest.method).toBe("POST");
|
|
expect(csrfOptions?.formData?.get("csrf")).toBe("csrf-token");
|
|
expect((response as Response).status).toBe(302);
|
|
expect(registerMock).toHaveBeenCalledWith({
|
|
email: "invitee@example.com",
|
|
password: "password",
|
|
firstName: "Ada",
|
|
lastName: "Lovelace",
|
|
locale: "en",
|
|
request: expect.any(Request),
|
|
transactionalMutation: expect.any(Function),
|
|
});
|
|
expect(createTenantUserMock).toHaveBeenCalledWith({ tenantId: "tenant_1", userId: "user_1", type: 2 }, [role]);
|
|
expect(welcomeParseMock).toHaveBeenCalledWith({
|
|
appConfiguration,
|
|
data: {
|
|
action_url: "https://example.com/login",
|
|
name: "Ada",
|
|
},
|
|
t: expect.any(Function),
|
|
locale: "en",
|
|
});
|
|
expect(queueTransactionalEmailMock).toHaveBeenCalledWith({
|
|
to: "invitee@example.com",
|
|
alias: "welcome",
|
|
tenantId: "tenant_1",
|
|
userId: "user_1",
|
|
idempotencyKey: "invitation:invitation_1:welcome",
|
|
subject: "Welcome to Example",
|
|
body: "<p>Welcome Ada at https://example.com/login</p>",
|
|
data: {
|
|
action_url: "https://example.com/login",
|
|
name: "Ada",
|
|
},
|
|
});
|
|
expect(acceptWorkspaceInviteMock).toHaveBeenCalledWith(
|
|
{
|
|
tenantId: "tenant_1",
|
|
inviteId: "invitation_1",
|
|
token: "invite-token",
|
|
acceptedByUserId: "user_1",
|
|
createdUserId: "user_1",
|
|
bindCreatedUserId: true,
|
|
},
|
|
transactionClient
|
|
);
|
|
expect(queueTransactionalEmailMock.mock.invocationCallOrder[0]).toBeGreaterThan(acceptWorkspaceInviteMock.mock.invocationCallOrder[0]);
|
|
expect(queueTransactionalEmailMock.mock.invocationCallOrder[0]).toBeGreaterThan(createTenantUserMock.mock.invocationCallOrder[0]);
|
|
expect(queueTransactionalEmailMock.mock.invocationCallOrder[0]).toBeGreaterThan(eventsCreateIdempotentMock.mock.invocationCallOrder[0]);
|
|
expect(eventsCreateIdempotentMock).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
idempotencyKey: "invitation:invitation_1:accepted",
|
|
data: expect.objectContaining({ newUser: true, invitation: { id: "invitation_1" } }),
|
|
})
|
|
);
|
|
expect(eventRlsContexts).toEqual([expect.objectContaining({ tenantId: "tenant_1", userId: "user_1" })]);
|
|
expect(createUserSessionMock).toHaveBeenCalledWith(expect.objectContaining({ userId: "user_1", lng: "en" }), "/example-co/dashboard", {
|
|
request: expect.any(Request),
|
|
rotate: true,
|
|
});
|
|
expect(transactionInvite).toMatchObject({ pending: false, status: "accepted", acceptedByUserId: "user_1", createdUserId: "user_1" });
|
|
expect(transactionMembership).toEqual({ tenantId: "tenant_1", userId: "user_1", status: 1 });
|
|
expect(registeredUserIds).toEqual(new Set(["user_1"]));
|
|
expect(sendEmailMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rolls user, invite, and membership back together when membership creation fails, then remains retryable", async () => {
|
|
createTenantUserMock.mockRejectedValueOnce(new Error("membership unavailable"));
|
|
|
|
await expect(postInvitation()).rejects.toThrow("membership unavailable");
|
|
|
|
expect(transactionInvite).toMatchObject({ pending: true, status: "pending", acceptedByUserId: null, createdUserId: null });
|
|
expect(transactionMembership).toBeNull();
|
|
expect(registeredUserIds).toEqual(new Set());
|
|
expect(eventsCreateIdempotentMock).not.toHaveBeenCalled();
|
|
expect(queueTransactionalEmailMock).not.toHaveBeenCalled();
|
|
|
|
const retry = await postInvitation();
|
|
|
|
expect(retry).toBeInstanceOf(Response);
|
|
expect((retry as Response).status).toBe(302);
|
|
expect(transactionInvite).toMatchObject({ pending: false, status: "accepted", acceptedByUserId: "user_1", createdUserId: "user_1" });
|
|
expect(transactionMembership).toEqual({ tenantId: "tenant_1", userId: "user_1", status: 1 });
|
|
expect(registeredUserIds).toEqual(new Set(["user_1"]));
|
|
expect(eventsCreateIdempotentMock).toHaveBeenCalledTimes(1);
|
|
expect(queueTransactionalEmailMock).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("commits exactly one complete membership when the same fresh invite is accepted concurrently", async () => {
|
|
const results = await Promise.all([postInvitation(), postInvitation()]);
|
|
const statuses = results.map((result) => (result as Response).status).sort((left, right) => left - right);
|
|
|
|
expect(statuses).toEqual([302, 400]);
|
|
expect(transactionInvite).toMatchObject({ pending: false, status: "accepted", acceptedByUserId: "user_1", createdUserId: "user_1" });
|
|
expect(transactionMembership).toEqual({ tenantId: "tenant_1", userId: "user_1", status: 1 });
|
|
expect(registeredUserIds).toEqual(new Set(["user_1"]));
|
|
expect(eventsCreateIdempotentMock).toHaveBeenCalledTimes(1);
|
|
expect(queueTransactionalEmailMock).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("generates a server-only throwaway password for magic-link invitations", async () => {
|
|
const response = await postInvitation("magic-link");
|
|
|
|
expect(response).toBeInstanceOf(Response);
|
|
expect((response as Response).status).toBe(302);
|
|
expect(registerMock).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
email: "invitee@example.com",
|
|
password: "generated-magic-link-password",
|
|
})
|
|
);
|
|
});
|
|
|
|
it("does not issue a full invitation session when TOTP is enabled", async () => {
|
|
beginAlternativeLoginMfaMock.mockResolvedValue({
|
|
required: true,
|
|
setCookie: "hivegrid_session=pending; HttpOnly",
|
|
});
|
|
|
|
const response = await postInvitation();
|
|
|
|
expect(response).toBeInstanceOf(Response);
|
|
expect((response as Response).status).toBe(302);
|
|
expect((response as Response).headers.get("Location")).toBe("/login-mfa");
|
|
expect((response as Response).headers.get("Set-Cookie")).toContain("hivegrid_session=pending");
|
|
expect(beginAlternativeLoginMfaMock).toHaveBeenCalledWith({
|
|
request: expect.any(Request),
|
|
userId: "user_1",
|
|
redirectTo: "/example-co/dashboard",
|
|
primaryMethod: "invitation",
|
|
});
|
|
expect(setLoggedUserMock).not.toHaveBeenCalled();
|
|
expect(createUserSessionMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("does not grant tenant-specific app roles from other tenants to invited users", async () => {
|
|
getAllRolesMock.mockResolvedValue([role, tenantScopedRole] as Awaited<ReturnType<typeof getAllRoles>>);
|
|
|
|
const response = await postInvitation();
|
|
|
|
expect(response).toBeInstanceOf(Response);
|
|
expect(createTenantUserMock).toHaveBeenCalledWith({ tenantId: "tenant_1", userId: "user_1", type: 2 }, [role]);
|
|
});
|
|
|
|
it("accepts existing-user invitations without enqueueing a welcome email", async () => {
|
|
const existingUser = { id: "existing_user_1", email: "invitee@example.com", firstName: "Ada", lastName: "Lovelace" } as Awaited<
|
|
ReturnType<typeof getUserByEmail>
|
|
>;
|
|
getUserByEmailMock.mockResolvedValue(existingUser);
|
|
getUserMock.mockImplementation(async (userId) =>
|
|
userId === "existing_user_1" ? (existingUser as Awaited<ReturnType<typeof getUser>>) : ({ id: "from_user_1", email: "owner@example.com" } as never)
|
|
);
|
|
getUserInfoMock.mockResolvedValue({ userId: "existing_user_1", lng: "en", lightOrDarkMode: "light" } as Awaited<ReturnType<typeof getUserInfo>>);
|
|
|
|
const response = await postInvitation();
|
|
|
|
expect(response).toEqual({ invitationAccepted: true });
|
|
expect(registerMock).not.toHaveBeenCalled();
|
|
expect(acceptWorkspaceInviteMock).toHaveBeenCalledWith(
|
|
{
|
|
tenantId: "tenant_1",
|
|
inviteId: "invitation_1",
|
|
token: "invite-token",
|
|
acceptedByUserId: "existing_user_1",
|
|
},
|
|
transactionClient
|
|
);
|
|
expect(createTenantUserMock).toHaveBeenCalledWith({ tenantId: "tenant_1", userId: "existing_user_1", type: 2 }, [role]);
|
|
expect(eventRlsContexts).toEqual([expect.objectContaining({ tenantId: "tenant_1", userId: "existing_user_1" })]);
|
|
expect(queueTransactionalEmailMock).not.toHaveBeenCalled();
|
|
expect(sendEmailMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("fails closed before accepting when the invited existing user already has an inactive membership", async () => {
|
|
configureAuthenticatedExistingUser();
|
|
transactionMembership = { tenantId: "tenant_1", userId: "existing_user_1", status: 0 };
|
|
|
|
const response = await postInvitation();
|
|
|
|
expect(response).toBeInstanceOf(Response);
|
|
expect((response as Response).status).toBe(400);
|
|
await expect(readJson(response)).resolves.toEqual({ error: "auth:invitation.errors.invalid" });
|
|
expect(transactionInvite).toMatchObject({ pending: true, status: "pending", acceptedByUserId: null });
|
|
expect(createTenantUserMock).not.toHaveBeenCalled();
|
|
expect(eventsCreateIdempotentMock).not.toHaveBeenCalled();
|
|
expect(queueTransactionalEmailMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("claims an inactive pending-owner reservation for a newly registered owner before every external side effect", async () => {
|
|
configureOwnerInvitation();
|
|
|
|
const response = await postInvitation();
|
|
|
|
expect(response).toBeInstanceOf(Response);
|
|
expect((response as Response).status).toBe(302);
|
|
expect(getWorkspaceInviteByTokenMock.mock.invocationCallOrder[0]).toBeLessThan(getInvitationTenantIdentityMock.mock.invocationCallOrder[0]);
|
|
expect(getInvitationTenantIdentityMock).toHaveBeenCalledWith("tenant_1", {
|
|
allowedInactiveReason: "pending_owner",
|
|
});
|
|
expect(registerMock).not.toHaveBeenCalled();
|
|
expect(hashPasswordMock).toHaveBeenCalledWith("password");
|
|
const claimInput = claimReservedTenantWithShkDefaultsMock.mock.calls[0]?.[0];
|
|
expect(claimInput).toEqual({
|
|
tenantId: "tenant_1",
|
|
userId: expect.stringMatching(/^[a-f0-9-]{36}$/u),
|
|
t: expect.any(Function),
|
|
createUser: {
|
|
id: expect.stringMatching(/^[a-f0-9-]{36}$/u),
|
|
email: "invitee@example.com",
|
|
passwordHash: "$argon2id$prepared-owner-password",
|
|
firstName: "Ada",
|
|
lastName: "Lovelace",
|
|
locale: "en",
|
|
},
|
|
claim: {
|
|
kind: "workspace-invite",
|
|
inviteId: "invitation_1",
|
|
token: "invite-token",
|
|
createdUserId: expect.stringMatching(/^[a-f0-9-]{36}$/u),
|
|
},
|
|
});
|
|
expect(claimInput?.createUser?.id).toBe(claimInput?.userId);
|
|
expect(claimInput?.claim.createdUserId).toBe(claimInput?.userId);
|
|
expect(acceptWorkspaceInviteMock).not.toHaveBeenCalled();
|
|
expect(createTenantUserMock).not.toHaveBeenCalled();
|
|
expect(getUserMock).not.toHaveBeenCalled();
|
|
expect(emitUserCreatedHookMock).toHaveBeenCalledWith(expect.objectContaining({ id: claimInput?.userId, defaultTenantId: "tenant_1" }));
|
|
expect(eventsCreateMock).not.toHaveBeenCalled();
|
|
expect(eventsCreateIdempotentMock).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
idempotencyKey: "invitation:invitation_1:accepted",
|
|
data: expect.objectContaining({ newUser: true, fromUser: null }),
|
|
})
|
|
);
|
|
expect(queueTransactionalEmailMock).toHaveBeenCalledWith(
|
|
expect.objectContaining({ idempotencyKey: "invitation:invitation_1:welcome", userId: claimInput?.userId })
|
|
);
|
|
expect(setLoggedUserMock).toHaveBeenCalledWith(expect.objectContaining({ id: claimInput?.userId, defaultTenantId: "tenant_1" }));
|
|
expect(createUserSessionMock).toHaveBeenCalledWith(expect.objectContaining({ userId: claimInput?.userId }), "/example-co/dashboard", {
|
|
request: expect.any(Request),
|
|
rotate: true,
|
|
});
|
|
const claimOrder = claimReservedTenantWithShkDefaultsMock.mock.invocationCallOrder[0]!;
|
|
expect(emitUserCreatedHookMock.mock.invocationCallOrder[0]).toBeGreaterThan(claimOrder);
|
|
expect(eventsCreateIdempotentMock.mock.invocationCallOrder[0]).toBeGreaterThan(claimOrder);
|
|
expect(queueTransactionalEmailMock.mock.invocationCallOrder[0]).toBeGreaterThan(claimOrder);
|
|
expect(createUserSessionMock.mock.invocationCallOrder[0]).toBeGreaterThan(claimOrder);
|
|
});
|
|
|
|
it("keeps magic-link owner creation inside the same atomic claim transaction", async () => {
|
|
configureOwnerInvitation();
|
|
|
|
const response = await postInvitation("magic-link");
|
|
|
|
expect(response).toBeInstanceOf(Response);
|
|
expect((response as Response).status).toBe(302);
|
|
expect(registerMock).not.toHaveBeenCalled();
|
|
expect(hashPasswordMock).toHaveBeenCalledWith("generated-magic-link-password");
|
|
expect(claimReservedTenantWithShkDefaultsMock).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
createUser: expect.objectContaining({ passwordHash: "$argon2id$prepared-owner-password" }),
|
|
claim: expect.objectContaining({ createdUserId: expect.any(String) }),
|
|
})
|
|
);
|
|
});
|
|
|
|
it("claims an inactive pending-owner reservation for an authenticated existing owner without creating membership twice", async () => {
|
|
configureOwnerInvitation();
|
|
configureAuthenticatedExistingUser();
|
|
|
|
const response = await postInvitation();
|
|
|
|
expect(response).toBeInstanceOf(Response);
|
|
expect((response as Response).status).toBe(302);
|
|
expect(registerMock).not.toHaveBeenCalled();
|
|
expect(claimReservedTenantWithShkDefaultsMock).toHaveBeenCalledWith({
|
|
tenantId: "tenant_1",
|
|
userId: "existing_user_1",
|
|
t: expect.any(Function),
|
|
claim: { kind: "workspace-invite", inviteId: "invitation_1", token: "invite-token" },
|
|
});
|
|
expect(acceptWorkspaceInviteMock).not.toHaveBeenCalled();
|
|
expect(createTenantUserMock).not.toHaveBeenCalled();
|
|
expect(getUserMock).not.toHaveBeenCalledWith("from_user_1");
|
|
expect(emitUserCreatedHookMock).not.toHaveBeenCalled();
|
|
expect(queueTransactionalEmailMock).not.toHaveBeenCalled();
|
|
expect(eventsCreateIdempotentMock).toHaveBeenCalledTimes(1);
|
|
expect(setLoggedUserMock).toHaveBeenCalledWith(expect.objectContaining({ id: "existing_user_1", defaultTenantId: "tenant_1" }));
|
|
expect(createUserSessionMock).toHaveBeenCalledWith(expect.objectContaining({ userId: "existing_user_1" }), "/example-co/dashboard", {
|
|
request: expect.any(Request),
|
|
rotate: true,
|
|
});
|
|
expect(createUserSessionMock.mock.calls[0]?.[0]).not.toHaveProperty("defaultTenantId");
|
|
});
|
|
|
|
it("fails closed without side effects when the atomic new-owner claim loses the invite race", async () => {
|
|
configureOwnerInvitation();
|
|
claimReservedTenantWithShkDefaultsMock.mockRejectedValueOnce(new WorkspaceInviteError("invite_not_found"));
|
|
|
|
const response = await postInvitation();
|
|
|
|
expect((response as Response).status).toBe(400);
|
|
expect(await readJson(response)).toEqual({ error: "auth:invitation.errors.invalid" });
|
|
expect(registerMock).not.toHaveBeenCalled();
|
|
expect(claimReservedTenantWithShkDefaultsMock).toHaveBeenCalledOnce();
|
|
expect(emitUserCreatedHookMock).not.toHaveBeenCalled();
|
|
expect(eventsCreateIdempotentMock).not.toHaveBeenCalled();
|
|
expect(queueTransactionalEmailMock).not.toHaveBeenCalled();
|
|
expect(createUserSessionMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("does not rotate an owner session unless membership resolution selects the claimed tenant", async () => {
|
|
configureOwnerInvitation();
|
|
configureAuthenticatedExistingUser();
|
|
setLoggedUserMock.mockResolvedValueOnce({
|
|
userId: "existing_user_1",
|
|
defaultTenantId: "another_tenant",
|
|
defaultTenant: { id: "another_tenant", name: "Other", slug: "other", active: true, deactivatedReason: null },
|
|
} as Awaited<ReturnType<typeof setLoggedUser>>);
|
|
|
|
const response = await postInvitation();
|
|
|
|
expect((response as Response).status).toBe(400);
|
|
expect(await readJson(response)).toEqual({ error: "auth:invitation.errors.invalid" });
|
|
expect(setLoggedUserMock).toHaveBeenCalledWith(expect.objectContaining({ defaultTenantId: "tenant_1" }));
|
|
expect(createUserSessionMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("keeps a pending owner invitation on an active tenant on the normal membership path", async () => {
|
|
configureOwnerInvitation({ active: true, deactivatedReason: null });
|
|
configureAuthenticatedExistingUser();
|
|
|
|
await expect(postInvitation()).resolves.toEqual({ invitationAccepted: true });
|
|
|
|
expect(claimReservedTenantWithShkDefaultsMock).not.toHaveBeenCalled();
|
|
expect(acceptWorkspaceInviteMock).toHaveBeenCalledWith(
|
|
{
|
|
tenantId: "tenant_1",
|
|
inviteId: "invitation_1",
|
|
token: "invite-token",
|
|
acceptedByUserId: "existing_user_1",
|
|
},
|
|
transactionClient
|
|
);
|
|
expect(createTenantUserMock).toHaveBeenCalledTimes(1);
|
|
expect(eventsCreateMock).not.toHaveBeenCalled();
|
|
expect(eventsCreateIdempotentMock).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("does not resolve an inactive tenant for a normal member invitation", async () => {
|
|
getInvitationTenantIdentityMock.mockResolvedValueOnce(null);
|
|
|
|
const response = await postInvitation();
|
|
|
|
expect((response as Response).status).toBe(400);
|
|
expect(getInvitationTenantIdentityMock).toHaveBeenCalledWith("tenant_1");
|
|
expect(claimReservedTenantWithShkDefaultsMock).not.toHaveBeenCalled();
|
|
expect(registerMock).not.toHaveBeenCalled();
|
|
expect(acceptWorkspaceInviteMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("replays an accepted owner claim only for the same authenticated existing owner", async () => {
|
|
configureOwnerInvitation({
|
|
status: "accepted",
|
|
acceptedByUserId: "existing_user_1",
|
|
active: true,
|
|
deactivatedReason: null,
|
|
});
|
|
configureAuthenticatedExistingUser();
|
|
claimReservedTenantWithShkDefaultsMock.mockResolvedValueOnce({
|
|
tenant: { id: "tenant_1", active: true },
|
|
user: { id: "existing_user_1" },
|
|
replayed: true,
|
|
} as Awaited<ReturnType<typeof claimReservedTenantWithShkDefaults>>);
|
|
|
|
const response = await postInvitation();
|
|
|
|
expect(response).toBeInstanceOf(Response);
|
|
expect((response as Response).status).toBe(302);
|
|
|
|
expect(claimReservedTenantWithShkDefaultsMock).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
userId: "existing_user_1",
|
|
claim: { kind: "workspace-invite", inviteId: "invitation_1", token: "invite-token" },
|
|
})
|
|
);
|
|
expect(acceptWorkspaceInviteMock).not.toHaveBeenCalled();
|
|
expect(createTenantUserMock).not.toHaveBeenCalled();
|
|
expect(eventsCreateIdempotentMock).toHaveBeenCalledWith(expect.objectContaining({ idempotencyKey: "invitation:invitation_1:accepted" }));
|
|
});
|
|
|
|
it("replays the created-user owner claim with the exact durable marker and idempotent side effects", async () => {
|
|
configureOwnerInvitation({
|
|
status: "accepted",
|
|
acceptedByUserId: "existing_user_1",
|
|
createdUserId: "existing_user_1",
|
|
active: true,
|
|
deactivatedReason: null,
|
|
});
|
|
configureAuthenticatedExistingUser();
|
|
claimReservedTenantWithShkDefaultsMock.mockResolvedValueOnce({
|
|
tenant: { id: "tenant_1", active: true },
|
|
user: { id: "existing_user_1" },
|
|
replayed: true,
|
|
} as Awaited<ReturnType<typeof claimReservedTenantWithShkDefaults>>);
|
|
|
|
const response = await postInvitation();
|
|
|
|
expect(response).toBeInstanceOf(Response);
|
|
expect((response as Response).status).toBe(302);
|
|
|
|
expect(claimReservedTenantWithShkDefaultsMock).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
userId: "existing_user_1",
|
|
claim: {
|
|
kind: "workspace-invite",
|
|
inviteId: "invitation_1",
|
|
token: "invite-token",
|
|
createdUserId: "existing_user_1",
|
|
},
|
|
})
|
|
);
|
|
expect(emitUserCreatedHookMock).toHaveBeenCalledWith(expect.objectContaining({ id: "existing_user_1", defaultTenantId: "tenant_1" }));
|
|
expect(eventsCreateIdempotentMock).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ newUser: true }) }));
|
|
expect(queueTransactionalEmailMock).toHaveBeenCalledWith(expect.objectContaining({ idempotencyKey: "invitation:invitation_1:welcome" }));
|
|
});
|
|
|
|
it("still rotates the owner session when post-commit hook, event, and welcome dispatch all fail", async () => {
|
|
configureOwnerInvitation({
|
|
status: "accepted",
|
|
acceptedByUserId: "existing_user_1",
|
|
createdUserId: "existing_user_1",
|
|
active: true,
|
|
deactivatedReason: null,
|
|
});
|
|
configureAuthenticatedExistingUser();
|
|
claimReservedTenantWithShkDefaultsMock.mockResolvedValueOnce({
|
|
tenant: { id: "tenant_1", active: true },
|
|
user: { id: "existing_user_1" },
|
|
replayed: true,
|
|
} as Awaited<ReturnType<typeof claimReservedTenantWithShkDefaults>>);
|
|
emitUserCreatedHookMock.mockRejectedValueOnce(new Error("hook unavailable"));
|
|
eventsCreateIdempotentMock.mockRejectedValueOnce(new Error("event unavailable"));
|
|
queueTransactionalEmailMock.mockRejectedValueOnce(new Error("queue unavailable"));
|
|
|
|
const response = await postInvitation();
|
|
|
|
expect(response).toBeInstanceOf(Response);
|
|
expect((response as Response).status).toBe(302);
|
|
expect((response as Response).headers.get("Location")).toBe("/example-co/dashboard");
|
|
expect(emitUserCreatedHookMock).toHaveBeenCalledOnce();
|
|
expect(eventsCreateIdempotentMock).toHaveBeenCalledOnce();
|
|
expect(queueTransactionalEmailMock).toHaveBeenCalledOnce();
|
|
expect(setLoggedUserMock).toHaveBeenCalledWith(expect.objectContaining({ defaultTenantId: "tenant_1" }));
|
|
expect(createUserSessionMock).toHaveBeenCalledWith(expect.objectContaining({ userId: "existing_user_1" }), "/example-co/dashboard", {
|
|
request: expect.any(Request),
|
|
rotate: true,
|
|
});
|
|
});
|
|
|
|
it("fails closed for an accepted owner token when acceptedBy does not match the authenticated user", async () => {
|
|
configureOwnerInvitation({
|
|
status: "accepted",
|
|
acceptedByUserId: "different_user",
|
|
active: true,
|
|
deactivatedReason: null,
|
|
});
|
|
configureAuthenticatedExistingUser();
|
|
|
|
const response = await postInvitation();
|
|
|
|
expect((response as Response).status).toBe(400);
|
|
expect(claimReservedTenantWithShkDefaultsMock).not.toHaveBeenCalled();
|
|
expect(acceptWorkspaceInviteMock).not.toHaveBeenCalled();
|
|
expect(eventsCreateIdempotentMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("retries a rolled-back atomic new-owner claim without a session or stranded user", async () => {
|
|
configureOwnerInvitation();
|
|
claimReservedTenantWithShkDefaultsMock.mockRejectedValueOnce(new WorkspaceInviteError("invite_not_found"));
|
|
|
|
const failed = await postInvitation();
|
|
|
|
expect((failed as Response).status).toBe(400);
|
|
expect(registerMock).not.toHaveBeenCalled();
|
|
expect(claimReservedTenantWithShkDefaultsMock).toHaveBeenCalledTimes(1);
|
|
expect(emitUserCreatedHookMock).not.toHaveBeenCalled();
|
|
expect(eventsCreateIdempotentMock).not.toHaveBeenCalled();
|
|
expect(queueTransactionalEmailMock).not.toHaveBeenCalled();
|
|
expect(createUserSessionMock).not.toHaveBeenCalled();
|
|
|
|
const retried = await postInvitation();
|
|
|
|
expect(retried).toBeInstanceOf(Response);
|
|
expect((retried as Response).status).toBe(302);
|
|
|
|
expect(registerMock).not.toHaveBeenCalled();
|
|
expect(claimReservedTenantWithShkDefaultsMock).toHaveBeenCalledTimes(2);
|
|
const firstAttempt = claimReservedTenantWithShkDefaultsMock.mock.calls[0]?.[0];
|
|
const secondAttempt = claimReservedTenantWithShkDefaultsMock.mock.calls[1]?.[0];
|
|
expect(firstAttempt?.createUser?.id).toBe(firstAttempt?.userId);
|
|
expect(secondAttempt?.createUser?.id).toBe(secondAttempt?.userId);
|
|
expect(secondAttempt?.userId).not.toBe(firstAttempt?.userId);
|
|
expect(getUserInfoMock).toHaveBeenLastCalledWith(expect.any(Request));
|
|
expect(acceptWorkspaceInviteMock).not.toHaveBeenCalled();
|
|
expect(createTenantUserMock).not.toHaveBeenCalled();
|
|
expect(eventsCreateIdempotentMock).toHaveBeenCalledTimes(1);
|
|
expect(emitUserCreatedHookMock).toHaveBeenCalledTimes(1);
|
|
expect(queueTransactionalEmailMock).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("rejects an authenticated user whose identity does not match the invited email", async () => {
|
|
getUserInfoMock.mockResolvedValue({ userId: "attacker_1", lng: "en", lightOrDarkMode: "light" } as Awaited<ReturnType<typeof getUserInfo>>);
|
|
getUserMock.mockResolvedValueOnce({ id: "attacker_1", email: "attacker@example.com" } as Awaited<ReturnType<typeof getUser>>);
|
|
|
|
const response = await postInvitation();
|
|
|
|
expect((response as Response).status).toBe(400);
|
|
await expect(readJson(response)).resolves.toEqual({ error: "auth:invitation.errors.signInAsInvitedUser" });
|
|
expect(registerMock).not.toHaveBeenCalled();
|
|
expect(acceptWorkspaceInviteMock).not.toHaveBeenCalled();
|
|
expect(eventsCreateMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("keeps expired owner and accepted member invitations finalized and side-effect free", async () => {
|
|
configureOwnerInvitation({ status: "expired", active: false, deactivatedReason: "pending_owner" });
|
|
|
|
const expiredOwner = await postInvitation();
|
|
|
|
expect((expiredOwner as Response).status).toBe(400);
|
|
await expect(readJson(expiredOwner)).resolves.toEqual({ error: "auth:invitation.errors.expired" });
|
|
expect(registerMock).not.toHaveBeenCalled();
|
|
expect(claimReservedTenantWithShkDefaultsMock).not.toHaveBeenCalled();
|
|
|
|
vi.clearAllMocks();
|
|
getWorkspaceInviteByTokenMock.mockResolvedValue({
|
|
...workspaceInvite!,
|
|
pending: false,
|
|
status: "accepted",
|
|
acceptedByUserId: "existing_user_1",
|
|
} as Awaited<ReturnType<typeof getWorkspaceInviteByToken>>);
|
|
getInvitationTenantIdentityMock.mockResolvedValue({
|
|
id: "tenant_1",
|
|
name: "Example Co",
|
|
slug: "example-co",
|
|
active: true,
|
|
deactivatedReason: null,
|
|
});
|
|
getUserInfoMock.mockResolvedValue({ userId: "existing_user_1", lng: "en" } as Awaited<ReturnType<typeof getUserInfo>>);
|
|
|
|
const acceptedMember = await postInvitation();
|
|
|
|
expect((acceptedMember as Response).status).toBe(400);
|
|
expect(getUserMock).not.toHaveBeenCalled();
|
|
expect(claimReservedTenantWithShkDefaultsMock).not.toHaveBeenCalled();
|
|
expect(acceptWorkspaceInviteMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("returns 400 for invalid invitations without enqueueing", async () => {
|
|
getWorkspaceInviteByTokenMock.mockResolvedValue(null);
|
|
|
|
const response = await postInvitation();
|
|
|
|
expect((response as Response).status).toBe(400);
|
|
await expect(readJson(response)).resolves.toEqual({ error: "auth:invitation.errors.invalid" });
|
|
expect(getInvitationTenantIdentityMock).not.toHaveBeenCalled();
|
|
expect(registerMock).not.toHaveBeenCalled();
|
|
expect(claimReservedTenantWithShkDefaultsMock).not.toHaveBeenCalled();
|
|
expect(acceptWorkspaceInviteMock).not.toHaveBeenCalled();
|
|
expect(createTenantUserMock).not.toHaveBeenCalled();
|
|
expect(queueTransactionalEmailMock).not.toHaveBeenCalled();
|
|
expect(sendEmailMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("fails closed when the verified invite cannot read its tenant-safe projection", async () => {
|
|
getInvitationTenantIdentityMock.mockResolvedValueOnce(null);
|
|
|
|
const response = await postInvitation();
|
|
|
|
expect((response as Response).status).toBe(400);
|
|
await expect(readJson(response)).resolves.toEqual({ error: "auth:invitation.errors.invalid" });
|
|
expect(registerMock).not.toHaveBeenCalled();
|
|
expect(claimReservedTenantWithShkDefaultsMock).not.toHaveBeenCalled();
|
|
expect(acceptWorkspaceInviteMock).not.toHaveBeenCalled();
|
|
expect(eventsCreateMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects a forged invitation POST before reading or mutating invitation state", async () => {
|
|
validateCSRFTokenMock.mockRejectedValueOnce(new Error("CSRF tokens do not match"));
|
|
|
|
await expect(postInvitation()).rejects.toThrow("CSRF tokens do not match");
|
|
|
|
expect(getWorkspaceInviteByTokenMock).not.toHaveBeenCalled();
|
|
expect(registerMock).not.toHaveBeenCalled();
|
|
expect(claimReservedTenantWithShkDefaultsMock).not.toHaveBeenCalled();
|
|
expect(acceptWorkspaceInviteMock).not.toHaveBeenCalled();
|
|
});
|
|
});
|