Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
@@ -1,13 +1,13 @@
|
||||
import UserValidationUtils from "~/utils/app/UserValidationUtils";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { useActionData, useLoaderData } from "react-router";
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect } from "react-router";
|
||||
import { withMetrics } from "~/lib/metrics/ssr";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getUser, getUserByEmail, register } from "~/utils/db/users.db.server";
|
||||
import { emitUserCreatedHook, getUser, getUserByEmail, register } from "~/utils/db/users.db.server";
|
||||
import { queueTransactionalEmail } from "~/modules/emails/services/TransactionalEmailQueue.server";
|
||||
import { createTenantUser, getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { createUserSession, getUserInfo, setLoggedUser } from "~/utils/session.server";
|
||||
import type { Tenant, User } from "@hivegrid/db/prisma-browser";
|
||||
import { createTenantUser, getInvitationTenantIdentity, getTenantUserByIds } from "~/utils/db/tenants.db.server";
|
||||
import { createUserSession, getUserInfo, setLoggedUser, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getAllRoles } from "~/utils/db/permissions/roles.db.server";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
import { getAbsoluteUrl } from "~/utils/url.server";
|
||||
@@ -20,43 +20,160 @@ import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { absoluteAppRootPath } from "~/utils/app/CrossHostUrls";
|
||||
import { acceptWorkspaceInvite, getWorkspaceInviteByToken, WorkspaceInviteDto, WorkspaceInviteError } from "@hivegrid/db/workspace-invites.server";
|
||||
import {
|
||||
acceptWorkspaceInvite,
|
||||
getWorkspaceInviteByToken,
|
||||
type WorkspaceInviteClient,
|
||||
WorkspaceInviteDto,
|
||||
WorkspaceInviteError,
|
||||
} from "@hivegrid/db/workspace-invites.server";
|
||||
import { getDbClient } from "@hivegrid/db/client.server";
|
||||
import { beginAlternativeLoginMfa, LOGIN_MFA_CHALLENGE_PATH } from "~/services/auth/alternative-login-mfa.server";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
import { toSafeErrorLog } from "~/utils/safeErrorLog.server";
|
||||
import { hashPassword } from "~/utils/auth/passwordHasher.server";
|
||||
import { TENANT_PENDING_OWNER_REASON } from "~/domain/tenant-bootstrap/tenantBootstrap.constants";
|
||||
import { claimReservedTenantWithShkDefaults } from "~/domain/tenant-bootstrap/tenantBootstrapService.server";
|
||||
import { checkAuthRateLimit } from "~/services/auth/auth-rate-limit.server";
|
||||
|
||||
const invitationLogger = createScopedLogger("invitation");
|
||||
const INVITATION_RATE_WINDOW_MS = 15 * 60 * 1000;
|
||||
const INVITATION_VIEW_RATE_LIMIT = 30;
|
||||
const INVITATION_VIEW_IDENTIFIER_LIMIT = 120;
|
||||
const INVITATION_VIEW_CLIENT_LIMIT = 300;
|
||||
const INVITATION_ACCEPT_RATE_LIMIT = 10;
|
||||
const INVITATION_ACCEPT_IDENTIFIER_LIMIT = 30;
|
||||
const INVITATION_ACCEPT_CLIENT_LIMIT = 100;
|
||||
const MAX_INVITATION_THROTTLE_TOKEN_LENGTH = 256;
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
invitation: (WorkspaceInviteDto & { tenant: Tenant }) | null;
|
||||
existingUser: User | null;
|
||||
invitation: (Pick<WorkspaceInviteDto, "email" | "firstName" | "pending"> & { tenant: { name: string } }) | null;
|
||||
existingUser: { id: string } | null;
|
||||
appRootPath: string;
|
||||
};
|
||||
|
||||
type ResolvedInvitation = WorkspaceInviteDto & {
|
||||
tenant: { id: string; name: string; slug: string; active: boolean; deactivatedReason: string | null };
|
||||
};
|
||||
|
||||
async function getResolvedInvitation(token: string): Promise<ResolvedInvitation | null> {
|
||||
const invite = await getWorkspaceInviteByToken({ token });
|
||||
if (!invite) return null;
|
||||
|
||||
return runWithRlsContext({ tenantId: invite.tenantId }, async () => {
|
||||
const tenant =
|
||||
invite.type === TenantUserType.OWNER
|
||||
? await getInvitationTenantIdentity(invite.tenantId, { allowedInactiveReason: TENANT_PENDING_OWNER_REASON })
|
||||
: await getInvitationTenantIdentity(invite.tenantId);
|
||||
return tenant ? { ...invite, tenant } : null;
|
||||
});
|
||||
}
|
||||
|
||||
export const loader = withMetrics("invitation", async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
const appRootPath = absoluteAppRootPath(loadRequiredWebConfig().routing);
|
||||
const invite = await getWorkspaceInviteByToken({ token: params.id ?? "" });
|
||||
const tenant = invite?.tenantId ? await getTenant(invite.tenantId) : null;
|
||||
const invitation = invite && tenant ? { ...invite, tenant } : null;
|
||||
const existingUser = await getUserByEmail(invitation?.email);
|
||||
const invitationToken = params.id ?? "";
|
||||
const rateLimit = await checkInvitationRateLimit({ request, token: invitationToken, action: "invitation-view" });
|
||||
if (!rateLimit.allowed) {
|
||||
return Response.json(
|
||||
{
|
||||
title: `${t("account.invitation.title")} | ${process.env.APP_NAME}`,
|
||||
invitation: null,
|
||||
existingUser: null,
|
||||
appRootPath,
|
||||
} satisfies LoaderData,
|
||||
{ status: 429, headers: invitationRateLimitHeaders(rateLimit.retryAfterSeconds) }
|
||||
);
|
||||
}
|
||||
|
||||
if (!isBoundedInvitationToken(invitationToken)) {
|
||||
return {
|
||||
title: `${t("account.invitation.title")} | ${process.env.APP_NAME}`,
|
||||
invitation: null,
|
||||
existingUser: null,
|
||||
appRootPath,
|
||||
} satisfies LoaderData;
|
||||
}
|
||||
|
||||
const candidateInvitation = await getResolvedInvitation(invitationToken);
|
||||
const replayUserInfo = candidateInvitation && isAcceptedOwnerClaimCandidate(candidateInvitation) ? await getUserInfo(request) : null;
|
||||
const replayableOwnerClaim = Boolean(candidateInvitation && isAcceptedOwnerClaimReplay(candidateInvitation, replayUserInfo?.userId));
|
||||
const resolvedInvitation =
|
||||
candidateInvitation && ((candidateInvitation.status === "pending" && candidateInvitation.pending) || replayableOwnerClaim) ? candidateInvitation : null;
|
||||
const invitation = resolvedInvitation
|
||||
? {
|
||||
email: resolvedInvitation.email,
|
||||
firstName: resolvedInvitation.firstName,
|
||||
pending: resolvedInvitation.pending || replayableOwnerClaim,
|
||||
tenant: { name: resolvedInvitation.tenant.name },
|
||||
}
|
||||
: null;
|
||||
const existingUserRecord =
|
||||
resolvedInvitation && !replayableOwnerClaim
|
||||
? await runWithRlsContext({ tenantId: resolvedInvitation.tenantId }, () => getUserByEmail(resolvedInvitation.email))
|
||||
: null;
|
||||
const data: LoaderData = {
|
||||
title: `${t("account.invitation.title")} | ${process.env.APP_NAME}`,
|
||||
invitation,
|
||||
existingUser,
|
||||
existingUser: replayableOwnerClaim && replayUserInfo?.userId ? { id: replayUserInfo.userId } : existingUserRecord ? { id: existingUserRecord.id } : null,
|
||||
appRootPath,
|
||||
};
|
||||
return data;
|
||||
});
|
||||
|
||||
export function headers() {
|
||||
return {
|
||||
"Cache-Control": "no-store",
|
||||
"Referrer-Policy": "no-referrer",
|
||||
};
|
||||
}
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
error?: string;
|
||||
invitationAccepted?: boolean;
|
||||
};
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
function invitationRateLimitHeaders(retryAfterSeconds: number) {
|
||||
return {
|
||||
"Cache-Control": "no-store",
|
||||
"Referrer-Policy": "no-referrer",
|
||||
"Retry-After": String(retryAfterSeconds),
|
||||
};
|
||||
}
|
||||
|
||||
function isBoundedInvitationToken(token: string): boolean {
|
||||
return token.length > 0 && token.length <= MAX_INVITATION_THROTTLE_TOKEN_LENGTH;
|
||||
}
|
||||
|
||||
async function checkInvitationRateLimit(input: { request: Request; token: string; action: "invitation-view" | "invitation-accept" }) {
|
||||
const isView = input.action === "invitation-view";
|
||||
return checkAuthRateLimit({
|
||||
request: input.request,
|
||||
action: input.action,
|
||||
identifier: isBoundedInvitationToken(input.token) ? input.token : null,
|
||||
limit: isView ? INVITATION_VIEW_RATE_LIMIT : INVITATION_ACCEPT_RATE_LIMIT,
|
||||
identifierLimit: isView ? INVITATION_VIEW_IDENTIFIER_LIMIT : INVITATION_ACCEPT_IDENTIFIER_LIMIT,
|
||||
clientLimit: isView ? INVITATION_VIEW_CLIENT_LIMIT : INVITATION_ACCEPT_CLIENT_LIMIT,
|
||||
windowMs: INVITATION_RATE_WINDOW_MS,
|
||||
});
|
||||
}
|
||||
|
||||
function workspaceInviteErrorResponse(error: unknown, t: (key: string) => string) {
|
||||
if (error instanceof WorkspaceInviteError) {
|
||||
return badRequest({
|
||||
error: error.code === "invite_expired" ? t("auth:invitation.errors.expired") : t("auth:invitation.errors.invalid"),
|
||||
});
|
||||
}
|
||||
if (error instanceof CatalogError) {
|
||||
return badRequest({ error: t("auth:invitation.errors.invalid") });
|
||||
}
|
||||
if (typeof error === "object" && error !== null && "code" in error && error.code === "P2002") {
|
||||
return badRequest({ error: t("auth:invitation.errors.invalid") });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
export function invitationCreatedUserDashboardPath(tenant: { slug?: string | null } | null) {
|
||||
@@ -67,158 +184,430 @@ function getDefaultInvitationRoles(roles: Awaited<ReturnType<typeof getAllRoles>
|
||||
return roles.filter((role) => role.assignToNewUsers && role.isDefault);
|
||||
}
|
||||
|
||||
function isPendingOwnerReservation(invitation: ResolvedInvitation): boolean {
|
||||
return (
|
||||
invitation.pending &&
|
||||
invitation.type === TenantUserType.OWNER &&
|
||||
!invitation.tenant.active &&
|
||||
invitation.tenant.deactivatedReason === TENANT_PENDING_OWNER_REASON
|
||||
);
|
||||
}
|
||||
|
||||
function isAcceptedOwnerClaimReplay(invitation: ResolvedInvitation, userId?: string): boolean {
|
||||
return Boolean(userId) && invitation.type === TenantUserType.OWNER && invitation.status === "accepted" && invitation.acceptedByUserId === userId;
|
||||
}
|
||||
|
||||
function isAcceptedOwnerClaimCandidate(invitation: ResolvedInvitation): boolean {
|
||||
return invitation.type === TenantUserType.OWNER && invitation.status === "accepted" && Boolean(invitation.acceptedByUserId);
|
||||
}
|
||||
|
||||
type InvitationAcceptanceResult = {
|
||||
claimedReservedOwner: boolean;
|
||||
createdByInvitation: boolean;
|
||||
replayed: boolean;
|
||||
};
|
||||
|
||||
async function acceptInvitationForUser(
|
||||
{
|
||||
invitation,
|
||||
token,
|
||||
userId,
|
||||
createdUserId,
|
||||
bindCreatedUserId = false,
|
||||
t,
|
||||
}: {
|
||||
invitation: ResolvedInvitation;
|
||||
token: string;
|
||||
userId: string;
|
||||
createdUserId?: string;
|
||||
bindCreatedUserId?: boolean;
|
||||
t: (key: string) => string;
|
||||
},
|
||||
transaction?: WorkspaceInviteClient
|
||||
): Promise<InvitationAcceptanceResult> {
|
||||
const acceptedReplay = isAcceptedOwnerClaimReplay(invitation, userId);
|
||||
if (isPendingOwnerReservation(invitation) || acceptedReplay) {
|
||||
const invitationCreatedUserId = createdUserId ?? (invitation.createdUserId === userId ? userId : undefined);
|
||||
const result = await claimReservedTenantWithShkDefaults({
|
||||
tenantId: invitation.tenantId,
|
||||
userId,
|
||||
t,
|
||||
claim: {
|
||||
kind: "workspace-invite",
|
||||
inviteId: invitation.id,
|
||||
token,
|
||||
...(invitationCreatedUserId ? { createdUserId: invitationCreatedUserId } : {}),
|
||||
},
|
||||
});
|
||||
return {
|
||||
claimedReservedOwner: true,
|
||||
createdByInvitation: invitationCreatedUserId === userId,
|
||||
replayed: result.replayed,
|
||||
};
|
||||
}
|
||||
|
||||
if (!invitation.pending) {
|
||||
throw new WorkspaceInviteError("invite_already_finalized");
|
||||
}
|
||||
const acceptAndCreateMembership = async (tx: WorkspaceInviteClient) => {
|
||||
const existingMembership = await getTenantUserByIds(invitation.tenantId, userId);
|
||||
if (existingMembership) {
|
||||
throw new WorkspaceInviteError("invite_not_found");
|
||||
}
|
||||
await acceptWorkspaceInvite(
|
||||
{
|
||||
tenantId: invitation.tenantId,
|
||||
inviteId: invitation.id,
|
||||
token,
|
||||
acceptedByUserId: userId,
|
||||
...(createdUserId ? { createdUserId } : {}),
|
||||
...(bindCreatedUserId ? { bindCreatedUserId: true } : {}),
|
||||
},
|
||||
tx
|
||||
);
|
||||
const roles = await getAllRoles("app");
|
||||
await createTenantUser(
|
||||
{
|
||||
tenantId: invitation.tenantId,
|
||||
userId,
|
||||
type: invitation.type,
|
||||
},
|
||||
getDefaultInvitationRoles(roles)
|
||||
);
|
||||
return { claimedReservedOwner: false, createdByInvitation: Boolean(createdUserId), replayed: false } satisfies InvitationAcceptanceResult;
|
||||
};
|
||||
return transaction
|
||||
? acceptAndCreateMembership(transaction)
|
||||
: getDbClient().$transaction((tx) => acceptAndCreateMembership(tx as unknown as WorkspaceInviteClient));
|
||||
}
|
||||
|
||||
async function queueInvitationWelcomeEmail({
|
||||
request,
|
||||
invitation,
|
||||
user,
|
||||
locale,
|
||||
idempotencyKey,
|
||||
}: {
|
||||
request: Request;
|
||||
invitation: ResolvedInvitation;
|
||||
user: { id: string; locale?: string | null };
|
||||
locale: string;
|
||||
idempotencyKey?: string;
|
||||
}): Promise<void> {
|
||||
const welcomeTemplateData = {
|
||||
action_url: getAbsoluteUrl(request, "/login"),
|
||||
name: invitation.firstName,
|
||||
};
|
||||
const welcomeMailTranslator = await getMailTranslator(user.locale ?? locale);
|
||||
await queueTransactionalEmail({
|
||||
to: invitation.email,
|
||||
alias: "welcome",
|
||||
tenantId: invitation.tenantId,
|
||||
userId: user.id,
|
||||
...(idempotencyKey ? { idempotencyKey } : {}),
|
||||
...EmailTemplates.WELCOME_EMAIL.parse({
|
||||
appConfiguration: await getAppConfiguration({ request }),
|
||||
data: welcomeTemplateData,
|
||||
t: welcomeMailTranslator.t,
|
||||
locale: welcomeMailTranslator.locale,
|
||||
}),
|
||||
data: welcomeTemplateData,
|
||||
});
|
||||
}
|
||||
|
||||
async function runInvitationPostCommitStep(input: { operation: string; tenantId: string; userId: string }, step: () => Promise<void>): Promise<void> {
|
||||
try {
|
||||
await step();
|
||||
} catch (error) {
|
||||
invitationLogger.error(
|
||||
{ ...toSafeErrorLog(error), op: input.operation, tenantId: input.tenantId, userId: input.userId },
|
||||
"Invitation acceptance committed, but a post-commit step failed."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const invitationToken = params.id ?? "";
|
||||
const rateLimit = await checkInvitationRateLimit({ request, token: invitationToken, action: "invitation-accept" });
|
||||
if (!rateLimit.allowed) {
|
||||
return Response.json({ error: t("auth:invitation.errors.invalid") }, { status: 429, headers: invitationRateLimitHeaders(rateLimit.retryAfterSeconds) });
|
||||
}
|
||||
if (!isBoundedInvitationToken(invitationToken)) {
|
||||
return badRequest({ error: t("auth:invitation.errors.invalid") });
|
||||
}
|
||||
|
||||
const form = await request.formData();
|
||||
await validateCSRFToken(request, { formData: form });
|
||||
const userInfo = await getUserInfo(request);
|
||||
const intent = form.get("intent")?.toString() ?? "set-password";
|
||||
const useMagicLink = intent === "magic-link";
|
||||
const password = form.get("password")?.toString() ?? "";
|
||||
const passwordConfirm = form.get("password-confirm")?.toString() ?? "";
|
||||
|
||||
const invite = await getWorkspaceInviteByToken({ token: params.id ?? "" });
|
||||
const tenant = invite?.tenantId ? await getTenant(invite.tenantId) : null;
|
||||
const invitation = invite && tenant ? { ...invite, tenant } : null;
|
||||
if (!invitation?.pending) {
|
||||
const invitation = await getResolvedInvitation(invitationToken);
|
||||
if (!invitation) {
|
||||
return badRequest({
|
||||
error: t("auth:invitation.errors.invalid"),
|
||||
});
|
||||
}
|
||||
const fromUser = invitation.fromUserId ? await getUser(invitation.fromUserId) : null;
|
||||
|
||||
let existingUser = await getUserByEmail(invitation.email);
|
||||
if (!existingUser) {
|
||||
// Register user. Two paths:
|
||||
// - intent="magic-link": accept invitation without password — generate
|
||||
// a strong random throwaway hash; the user signs in later via the
|
||||
// forgot-password → magic-link flow (#19). Mirrors the spirit of the
|
||||
// detail-MD's "magic-link invitation" feature without needing to
|
||||
// overlay the magic-link-token infrastructure (which requires a User
|
||||
// row to exist for its FK, which is exactly what's missing here).
|
||||
// - intent="set-password" (default): traditional confirm+validate path.
|
||||
let effectivePassword = password;
|
||||
if (useMagicLink) {
|
||||
// 32 bytes of crypto-random → 256 bits → far beyond any policy floor;
|
||||
// the user never sees it and it's not stored anywhere outside the hash.
|
||||
const { createInvitationMagicLinkPassword } = await import("~/services/auth/invitation-password.server");
|
||||
effectivePassword = createInvitationMagicLinkPassword();
|
||||
} else {
|
||||
const passwordError = await UserValidationUtils.validatePasswords({ t, password, passwordConfirm, email: invitation.email });
|
||||
if (passwordError) {
|
||||
return badRequest({ error: passwordError });
|
||||
}
|
||||
}
|
||||
|
||||
const user = await register({
|
||||
email: invitation.email,
|
||||
password: effectivePassword,
|
||||
firstName: invitation.firstName,
|
||||
lastName: invitation.lastName,
|
||||
locale: userInfo.lng,
|
||||
request,
|
||||
});
|
||||
if (!user) {
|
||||
return badRequest({ error: t("auth:invitation.errors.createUserFailed") });
|
||||
}
|
||||
try {
|
||||
await acceptWorkspaceInvite({ tenantId: invitation.tenantId, inviteId: invitation.id, token: params.id ?? "", acceptedByUserId: user.id });
|
||||
} catch (error) {
|
||||
return workspaceInviteErrorResponse(error, t);
|
||||
}
|
||||
const roles = await getAllRoles("app");
|
||||
await createTenantUser(
|
||||
{
|
||||
tenantId: invitation.tenantId,
|
||||
userId: user.id,
|
||||
type: invitation.type,
|
||||
},
|
||||
getDefaultInvitationRoles(roles)
|
||||
);
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "member.invitation.accepted",
|
||||
tenantId: invitation.tenant.id,
|
||||
userId: user.id,
|
||||
data: {
|
||||
newUser: true,
|
||||
tenant: { id: invitation.tenantId, name: invitation.tenant.name, slug: invitation.tenant.slug },
|
||||
user: { id: user.id, email: user.email, firstName: invitation.firstName, lastName: invitation.lastName, type: TenantUserType[invitation.type] },
|
||||
fromUser: !fromUser ? null : { id: fromUser.id, email: fromUser.email },
|
||||
invitation: { id: invitation.id },
|
||||
} satisfies MemberInvitationAcceptedDto,
|
||||
});
|
||||
|
||||
const welcomeTemplateData = {
|
||||
action_url: getAbsoluteUrl(request, "/login"),
|
||||
name: invitation.firstName,
|
||||
};
|
||||
const welcomeMailTranslator = await getMailTranslator(user.locale ?? userInfo.lng);
|
||||
await queueTransactionalEmail({
|
||||
to: invitation.email,
|
||||
alias: "welcome",
|
||||
tenantId: invitation.tenantId,
|
||||
userId: user.id,
|
||||
...EmailTemplates.WELCOME_EMAIL.parse({
|
||||
appConfiguration: await getAppConfiguration({ request }),
|
||||
data: welcomeTemplateData,
|
||||
t: welcomeMailTranslator.t,
|
||||
locale: welcomeMailTranslator.locale,
|
||||
}),
|
||||
data: welcomeTemplateData,
|
||||
});
|
||||
|
||||
const userSession = await setLoggedUser(user);
|
||||
const tenant = await getTenant(userSession.defaultTenantId);
|
||||
return createUserSession(
|
||||
{
|
||||
...userInfo,
|
||||
...userSession,
|
||||
userId: user.id,
|
||||
lng: user.locale ?? userInfo.lng,
|
||||
},
|
||||
invitationCreatedUserDashboardPath(tenant)
|
||||
);
|
||||
} else {
|
||||
// Existing user
|
||||
if (userInfo.userId !== existingUser.id) {
|
||||
if (invitation.status === "expired") {
|
||||
return badRequest({ error: t("auth:invitation.errors.expired") });
|
||||
}
|
||||
if (isAcceptedOwnerClaimCandidate(invitation) && !isAcceptedOwnerClaimReplay(invitation, userInfo.userId)) {
|
||||
return badRequest({ error: t("auth:invitation.errors.invalid") });
|
||||
}
|
||||
if (!invitation.pending && !isAcceptedOwnerClaimCandidate(invitation)) {
|
||||
return badRequest({ error: t("auth:invitation.errors.invalid") });
|
||||
}
|
||||
return runWithRlsContext({ tenantId: invitation.tenantId }, async () => {
|
||||
const authenticatedUser = userInfo.userId ? await getUser(userInfo.userId) : null;
|
||||
if (userInfo.userId && (!authenticatedUser || authenticatedUser.email.toLowerCase() !== invitation.email.toLowerCase())) {
|
||||
return badRequest({ error: t("auth:invitation.errors.signInAsInvitedUser") });
|
||||
}
|
||||
let existingUser: Awaited<ReturnType<typeof getUserByEmail>> | typeof authenticatedUser;
|
||||
try {
|
||||
await acceptWorkspaceInvite({ tenantId: invitation.tenantId, inviteId: invitation.id, token: params.id ?? "", acceptedByUserId: existingUser.id });
|
||||
} catch (error) {
|
||||
return workspaceInviteErrorResponse(error, t);
|
||||
existingUser = authenticatedUser ?? (await getUserByEmail(invitation.email));
|
||||
} catch {
|
||||
return badRequest({ error: t("auth:invitation.errors.invalid") });
|
||||
}
|
||||
const roles = await getAllRoles("app");
|
||||
await createTenantUser(
|
||||
{
|
||||
tenantId: invitation.tenantId,
|
||||
userId: existingUser.id,
|
||||
type: invitation.type,
|
||||
},
|
||||
getDefaultInvitationRoles(roles)
|
||||
);
|
||||
await EventsService.create({
|
||||
request,
|
||||
event: "member.invitation.accepted",
|
||||
tenantId: invitation.tenant.id,
|
||||
userId: existingUser.id,
|
||||
data: {
|
||||
newUser: false,
|
||||
tenant: { id: invitation.tenantId, name: invitation.tenant.name, slug: invitation.tenant.slug },
|
||||
fromUser: !fromUser ? null : { id: fromUser.id, email: fromUser.email },
|
||||
user: {
|
||||
id: existingUser.id,
|
||||
email: existingUser.email,
|
||||
firstName: existingUser.firstName,
|
||||
lastName: existingUser.lastName,
|
||||
type: TenantUserType[invitation.type],
|
||||
},
|
||||
invitation: { id: invitation.id },
|
||||
} satisfies MemberInvitationAcceptedDto,
|
||||
});
|
||||
const isReservedOwnerFlow = isPendingOwnerReservation(invitation) || isAcceptedOwnerClaimCandidate(invitation);
|
||||
const fromUser = !isReservedOwnerFlow && invitation.fromUserId ? await getUser(invitation.fromUserId) : null;
|
||||
if (!existingUser) {
|
||||
if (!invitation.pending) {
|
||||
return badRequest({ error: t("auth:invitation.errors.invalid") });
|
||||
}
|
||||
// Register user. Two paths:
|
||||
// - intent="magic-link": accept invitation without password — generate
|
||||
// a strong random throwaway hash; the user signs in later via the
|
||||
// forgot-password → magic-link flow (#19). Mirrors the spirit of the
|
||||
// detail-MD's "magic-link invitation" feature without needing to
|
||||
// overlay the magic-link-token infrastructure (which requires a User
|
||||
// row to exist for its FK, which is exactly what's missing here).
|
||||
// - intent="set-password" (default): traditional confirm+validate path.
|
||||
let effectivePassword = password;
|
||||
if (useMagicLink) {
|
||||
// 32 bytes of crypto-random → 256 bits → far beyond any policy floor;
|
||||
// the user never sees it and it's not stored anywhere outside the hash.
|
||||
const { createInvitationMagicLinkPassword } = await import("~/services/auth/invitation-password.server");
|
||||
effectivePassword = createInvitationMagicLinkPassword();
|
||||
} else {
|
||||
const passwordError = await UserValidationUtils.validatePasswords({ t, password, passwordConfirm, email: invitation.email });
|
||||
if (passwordError) {
|
||||
return badRequest({ error: passwordError });
|
||||
}
|
||||
}
|
||||
|
||||
return { invitationAccepted: true };
|
||||
}
|
||||
let user: Awaited<ReturnType<typeof register>>;
|
||||
let committedAcceptance: InvitationAcceptanceResult | null = null;
|
||||
if (isPendingOwnerReservation(invitation)) {
|
||||
const userId = randomUUID();
|
||||
const passwordHash = await hashPassword(effectivePassword);
|
||||
try {
|
||||
const claimResult = await runWithRlsContext({ userId }, () =>
|
||||
claimReservedTenantWithShkDefaults({
|
||||
tenantId: invitation.tenantId,
|
||||
userId,
|
||||
t,
|
||||
createUser: {
|
||||
id: userId,
|
||||
email: invitation.email.trim().toLowerCase(),
|
||||
passwordHash,
|
||||
firstName: invitation.firstName,
|
||||
lastName: invitation.lastName,
|
||||
locale: userInfo.lng,
|
||||
},
|
||||
claim: {
|
||||
kind: "workspace-invite",
|
||||
inviteId: invitation.id,
|
||||
token: invitationToken,
|
||||
createdUserId: userId,
|
||||
},
|
||||
})
|
||||
);
|
||||
user = {
|
||||
id: claimResult.user.id,
|
||||
email: claimResult.user.email,
|
||||
defaultTenantId: invitation.tenantId,
|
||||
locale: claimResult.user.locale ?? undefined,
|
||||
createdAt: claimResult.user.createdAt,
|
||||
};
|
||||
committedAcceptance = { claimedReservedOwner: true, createdByInvitation: true, replayed: claimResult.replayed };
|
||||
} catch (error) {
|
||||
return workspaceInviteErrorResponse(error, t);
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
user = await register({
|
||||
email: invitation.email,
|
||||
password: effectivePassword,
|
||||
firstName: invitation.firstName,
|
||||
lastName: invitation.lastName,
|
||||
locale: userInfo.lng,
|
||||
request,
|
||||
transactionalMutation: async (transaction, createdUser) => {
|
||||
committedAcceptance = await acceptInvitationForUser(
|
||||
{
|
||||
invitation,
|
||||
token: invitationToken,
|
||||
userId: createdUser.id,
|
||||
createdUserId: createdUser.id,
|
||||
bindCreatedUserId: true,
|
||||
t,
|
||||
},
|
||||
transaction as unknown as WorkspaceInviteClient
|
||||
);
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return workspaceInviteErrorResponse(error, t);
|
||||
}
|
||||
}
|
||||
if (!user) {
|
||||
return badRequest({ error: t("auth:invitation.errors.createUserFailed") });
|
||||
}
|
||||
return runWithRlsContext({ userId: user.id }, async () => {
|
||||
const acceptance = committedAcceptance;
|
||||
if (!acceptance) {
|
||||
return badRequest({ error: t("auth:invitation.errors.createUserFailed") });
|
||||
}
|
||||
if (acceptance.createdByInvitation && acceptance.claimedReservedOwner) {
|
||||
await runInvitationPostCommitStep({ operation: "owner-claim.user-hook", tenantId: invitation.tenantId, userId: user.id }, () =>
|
||||
emitUserCreatedHook({ ...user, locale: user.locale ?? null, defaultTenantId: invitation.tenantId })
|
||||
);
|
||||
}
|
||||
const eventInput = {
|
||||
request,
|
||||
event: "member.invitation.accepted" as const,
|
||||
tenantId: invitation.tenant.id,
|
||||
userId: user.id,
|
||||
data: {
|
||||
newUser: acceptance.createdByInvitation,
|
||||
tenant: { id: invitation.tenantId, name: invitation.tenant.name, slug: invitation.tenant.slug },
|
||||
fromUser: acceptance.claimedReservedOwner || !fromUser ? null : { id: fromUser.id, email: fromUser.email },
|
||||
user: { id: user.id, email: user.email, firstName: invitation.firstName, lastName: invitation.lastName, type: TenantUserType[invitation.type] },
|
||||
invitation: { id: invitation.id },
|
||||
} satisfies MemberInvitationAcceptedDto,
|
||||
};
|
||||
await runInvitationPostCommitStep({ operation: "invitation.accepted-event", tenantId: invitation.tenantId, userId: user.id }, () =>
|
||||
EventsService.createIdempotentTenantEvent({
|
||||
...eventInput,
|
||||
idempotencyKey: `invitation:${invitation.id}:accepted`,
|
||||
}).then(() => undefined)
|
||||
);
|
||||
|
||||
const queueWelcome = () =>
|
||||
queueInvitationWelcomeEmail({
|
||||
request,
|
||||
invitation,
|
||||
user,
|
||||
locale: userInfo.lng,
|
||||
idempotencyKey: `invitation:${invitation.id}:welcome`,
|
||||
});
|
||||
await runInvitationPostCommitStep({ operation: "invitation.welcome-email", tenantId: invitation.tenantId, userId: user.id }, queueWelcome);
|
||||
|
||||
const dashboardPath = invitationCreatedUserDashboardPath(invitation.tenant);
|
||||
const mfa = await beginAlternativeLoginMfa({ request, userId: user.id, redirectTo: dashboardPath, primaryMethod: "invitation" });
|
||||
if (mfa.required) {
|
||||
return redirect(LOGIN_MFA_CHALLENGE_PATH, { headers: { "Set-Cookie": mfa.setCookie } });
|
||||
}
|
||||
const userSession = await setLoggedUser(user);
|
||||
if (userSession.userId !== user.id || userSession.defaultTenantId !== invitation.tenantId) {
|
||||
return badRequest({ error: t("auth:invitation.errors.invalid") });
|
||||
}
|
||||
return createUserSession(
|
||||
{
|
||||
...userInfo,
|
||||
userId: user.id,
|
||||
lng: user.locale ?? userInfo.lng,
|
||||
},
|
||||
dashboardPath,
|
||||
{ request, rotate: true }
|
||||
);
|
||||
});
|
||||
} else {
|
||||
// Existing user
|
||||
if (userInfo.userId !== existingUser.id) {
|
||||
return badRequest({ error: t("auth:invitation.errors.signInAsInvitedUser") });
|
||||
}
|
||||
if (!invitation.pending && !isAcceptedOwnerClaimReplay(invitation, existingUser.id)) {
|
||||
return badRequest({ error: t("auth:invitation.errors.invalid") });
|
||||
}
|
||||
return runWithRlsContext({ userId: existingUser.id }, async () => {
|
||||
let acceptance: InvitationAcceptanceResult;
|
||||
try {
|
||||
acceptance = await acceptInvitationForUser({
|
||||
invitation,
|
||||
token: invitationToken,
|
||||
userId: existingUser.id,
|
||||
t,
|
||||
});
|
||||
} catch (error) {
|
||||
return workspaceInviteErrorResponse(error, t);
|
||||
}
|
||||
if (acceptance.createdByInvitation && acceptance.claimedReservedOwner) {
|
||||
await runInvitationPostCommitStep({ operation: "owner-claim.user-hook", tenantId: invitation.tenantId, userId: existingUser.id }, () =>
|
||||
emitUserCreatedHook({ ...existingUser, defaultTenantId: invitation.tenantId })
|
||||
);
|
||||
}
|
||||
const eventInput = {
|
||||
request,
|
||||
event: "member.invitation.accepted" as const,
|
||||
tenantId: invitation.tenant.id,
|
||||
userId: existingUser.id,
|
||||
data: {
|
||||
newUser: acceptance.createdByInvitation,
|
||||
tenant: { id: invitation.tenantId, name: invitation.tenant.name, slug: invitation.tenant.slug },
|
||||
fromUser: acceptance.claimedReservedOwner || !fromUser ? null : { id: fromUser.id, email: fromUser.email },
|
||||
user: {
|
||||
id: existingUser.id,
|
||||
email: existingUser.email,
|
||||
firstName: acceptance.claimedReservedOwner ? invitation.firstName : existingUser.firstName,
|
||||
lastName: acceptance.claimedReservedOwner ? invitation.lastName : existingUser.lastName,
|
||||
type: TenantUserType[invitation.type],
|
||||
},
|
||||
invitation: { id: invitation.id },
|
||||
} satisfies MemberInvitationAcceptedDto,
|
||||
};
|
||||
await runInvitationPostCommitStep({ operation: "invitation.accepted-event", tenantId: invitation.tenantId, userId: existingUser.id }, () =>
|
||||
EventsService.createIdempotentTenantEvent({
|
||||
...eventInput,
|
||||
idempotencyKey: `invitation:${invitation.id}:accepted`,
|
||||
}).then(() => undefined)
|
||||
);
|
||||
|
||||
if (acceptance.createdByInvitation && acceptance.claimedReservedOwner) {
|
||||
await runInvitationPostCommitStep({ operation: "owner-claim.welcome-email", tenantId: invitation.tenantId, userId: existingUser.id }, () =>
|
||||
queueInvitationWelcomeEmail({
|
||||
request,
|
||||
invitation,
|
||||
user: existingUser,
|
||||
locale: userInfo.lng,
|
||||
idempotencyKey: `invitation:${invitation.id}:welcome`,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
if (acceptance.claimedReservedOwner) {
|
||||
const dashboardPath = invitationCreatedUserDashboardPath(invitation.tenant);
|
||||
const userSession = await setLoggedUser({ ...existingUser, defaultTenantId: invitation.tenantId });
|
||||
if (userSession.userId !== existingUser.id || userSession.defaultTenantId !== invitation.tenantId) {
|
||||
return badRequest({ error: t("auth:invitation.errors.invalid") });
|
||||
}
|
||||
return createUserSession(
|
||||
{
|
||||
...userInfo,
|
||||
userId: existingUser.id,
|
||||
lng: existingUser.locale ?? userInfo.lng,
|
||||
},
|
||||
dashboardPath,
|
||||
{ request, rotate: true }
|
||||
);
|
||||
}
|
||||
|
||||
return { invitationAccepted: true };
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
Reference in new issue
Block a user