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
+416
-86
@@ -1,9 +1,21 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import UserValidationUtils from "~/utils/app/UserValidationUtils";
|
||||
import { createLogLogin } from "~/utils/db/logs.db.server";
|
||||
import { getUserByEmail, getUser, getUserTotpStatus, getActiveTotpSecretEncrypted, consumeUserMfaRecoveryCode } from "~/utils/db/users.db.server";
|
||||
import { setLoggedUser, createUserSession, getUserInfo, getUserSession, validateCSRFToken, commitPendingMfaLoginCookie } from "~/utils/session.server";
|
||||
import { startServerSession } from "~/services/auth/sessionLifecycle.server";
|
||||
import {
|
||||
setLoggedUser,
|
||||
createUserSession,
|
||||
getUserInfo,
|
||||
getUserSession,
|
||||
validateCSRFToken,
|
||||
commitPendingMfaLoginCookie,
|
||||
isPendingMfaLoginFresh,
|
||||
isPendingMfaPrimaryMethod,
|
||||
PENDING_MFA_PRIMARY_METHOD_KEY,
|
||||
} from "~/utils/session.server";
|
||||
import { updateUserPassword } from "~/utils/db/users.db.server";
|
||||
import { verifyTotpCode } from "~/services/auth/totp.server";
|
||||
import {
|
||||
@@ -14,10 +26,16 @@ import {
|
||||
} from "~/utils/auth/mfa/challenge-rate-limit.server";
|
||||
import { isTrustedDevice, rememberDeviceForUser } from "~/utils/auth/mfa/trusted-device.server";
|
||||
import { verifyPassword } from "~/utils/auth/passwordHasher.server";
|
||||
import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { getRegistrationFormData, validateRegistration, createRegistrationForm } from "~/utils/services/authService";
|
||||
import { getRegistrationByToken, updateRegistration } from "~/utils/db/registration.db.server";
|
||||
import {
|
||||
createRegistrationForm,
|
||||
getRegistrationFormData,
|
||||
isSignupCreationRequestKey,
|
||||
RegistrationValidationError,
|
||||
resolvePendingRegistrationResendRecovery,
|
||||
validateRegistration,
|
||||
} from "~/utils/services/authService";
|
||||
import { getRegistrationVerificationStateByToken, updateRegistration } from "~/utils/db/registration.db.server";
|
||||
import { Params, redirect } from "react-router";
|
||||
import IpAddressServiceServer from "~/modules/ipAddress/services/IpAddressService.server";
|
||||
import { isCanonicalAdminHostRoute } from "~/utils/app/HostRouting.server";
|
||||
@@ -29,10 +47,28 @@ import { clearFailedLogins, getFailedLoginCount, loginRequiresCaptcha, recordFai
|
||||
import { getSecret, getSitekey, isCaptchaConfigured, resolveCaptchaConfig, verifyCaptchaToken } from "@hivegrid/captcha";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
import { validatePassword as validatePolicyPassword } from "~/services/auth/password-policy.server";
|
||||
import {
|
||||
AdminFallbackLoginRejected,
|
||||
assertAdminFallbackLoginAllowedForIdentity,
|
||||
isCompletedAdminFallbackLoginResponse,
|
||||
} from "~/services/auth/admin-fallback.server";
|
||||
import { writeAdminSsoAuditEvent } from "~/modules/admin-sso/audit.server";
|
||||
import { deriveVerificationCreationRequestKey } from "~/domain/tenant-bootstrap/signupCreationRequestKey.server";
|
||||
import {
|
||||
clearRegistrationResendRecovery,
|
||||
commitRegistrationResendRecovery,
|
||||
readRegistrationResendRecovery,
|
||||
} from "~/services/auth/registration-resend-recovery.server";
|
||||
|
||||
const authLogger = createScopedLogger("auth");
|
||||
|
||||
const DUMMY_PASSWORD_HASH = "$2a$10$7EqJtq98hPqEX7fNZaFWoOhi8VfIf6z9SjG8/aYx8vvjE5LiE3D0C";
|
||||
const DUMMY_PASSWORD_HASH = "$argon2id$v=19$m=19456,t=2,p=1$CGZ841jS/Rerhh41+cREiw$piaCzFMbzHjq946K2t0iN7iMI/389iUpLNm2HROGO4Y";
|
||||
const REGISTRATION_VERIFY_RATE_LIMIT = 5;
|
||||
const REGISTRATION_VERIFY_RATE_LIMIT_WINDOW_MS = 15 * 60 * 1000;
|
||||
|
||||
function registrationVerifyRateLimitIdentifier(token: string): string {
|
||||
return createHash("sha256").update("registration-verify:v1\0").update(token).digest("hex");
|
||||
}
|
||||
|
||||
// D1 — tenant-faehige Verify-Route, an die das Login nach Passwort-OK fuer den zweiten Faktor
|
||||
// weiterleitet (siehe routeModules/auth/login-mfa).
|
||||
@@ -56,38 +92,48 @@ function translateIpAddressError(t: (key: string) => string, error: string): str
|
||||
if (error === "unauthorized") {
|
||||
return t("admin.accounts.ipAddresses.errors.unauthorized");
|
||||
}
|
||||
return error;
|
||||
return t("shared.unexpectedError");
|
||||
}
|
||||
|
||||
// The demo-login gate is a RUNTIME switch, not a seeding switch. It used to ride
|
||||
// on SEED_DEMO_DATA / ALLOW_STAGING_DEMO_SEED / SEED_DEMO_PRO_MANAGED, but the
|
||||
// RLS deploy contract forbids every SEED_*-prefixed key on a runtime resource
|
||||
// (`assert-runtime-db-env` rejects them, and seeding is not approved under forced
|
||||
// RLS). Carrying the gate on those names made the staging demo accounts
|
||||
// unreachable the moment the contract was enforced. It now has its own name, so
|
||||
// enabling demo logins never implies enabling a seed path.
|
||||
//
|
||||
// SENTRY_ENVIRONMENT is still required to be `staging`: the flag alone must not be
|
||||
// able to unlock a demo account in production, even if someone sets it there.
|
||||
type DemoLoginEnvironment = {
|
||||
ALLOW_STAGING_DEMO_SEED?: string;
|
||||
SEED_DEMO_DATA?: string;
|
||||
SENTRY_ENVIRONMENT?: string;
|
||||
STAGING_DEMO_LOGIN_ENABLED?: string;
|
||||
};
|
||||
|
||||
export function isStagingDemoLoginAllowed(env?: DemoLoginEnvironment) {
|
||||
const demoLoginEnv = env ?? (process.env as DemoLoginEnvironment);
|
||||
return demoLoginEnv.SEED_DEMO_DATA === "true" && demoLoginEnv.ALLOW_STAGING_DEMO_SEED === "true";
|
||||
return demoLoginEnv.SENTRY_ENVIRONMENT?.trim() === "staging" && demoLoginEnv.STAGING_DEMO_LOGIN_ENABLED?.trim() === "true";
|
||||
}
|
||||
|
||||
export function isProductionTestAccountBlocked(email: string, env?: DemoLoginEnvironment) {
|
||||
const runtimeEnv = env ?? (process.env as DemoLoginEnvironment);
|
||||
if (blockedProductionSeedAccountEmails.has(email)) {
|
||||
return true;
|
||||
}
|
||||
if (guardedStagingDemoAccountEmails.has(email)) {
|
||||
return !isStagingDemoLoginAllowed(env);
|
||||
if (guardedStagingDemoAccountEmails.has(email) || email.endsWith("@mitarbeiter.example.test")) {
|
||||
return !isStagingDemoLoginAllowed(runtimeEnv);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
async function getHome({ isAdmin, tenantId, request }: { isAdmin: boolean; tenantId: string; request: Request }) {
|
||||
async function getHome({ isAdmin, tenantSlug, request }: { isAdmin: boolean; tenantSlug?: string | null; request: Request }) {
|
||||
let appHome = "";
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
if (isAdmin) {
|
||||
appHome = absoluteAdminPath(loadRequiredWebConfig().routing, "dashboard");
|
||||
} else if (appConfiguration.app.features.tenantHome === "/:tenant/") {
|
||||
const tenant = await getTenant(tenantId);
|
||||
if (tenant) {
|
||||
appHome = absoluteAppPath(loadRequiredWebConfig().routing, tenant.slug, "dashboard");
|
||||
if (tenantSlug) {
|
||||
appHome = absoluteAppPath(loadRequiredWebConfig().routing, tenantSlug, "dashboard");
|
||||
} else {
|
||||
appHome = absoluteAppRootPath(loadRequiredWebConfig().routing);
|
||||
}
|
||||
@@ -97,6 +143,22 @@ async function getHome({ isAdmin, tenantId, request }: { isAdmin: boolean; tenan
|
||||
return appHome;
|
||||
}
|
||||
|
||||
function getRegistrationBillingDestination(
|
||||
tenantSlug: string,
|
||||
selectedSubscriptionPriceId: string,
|
||||
selectedOfficeSeatQuantity?: number,
|
||||
selectedFieldSeatQuantity?: number
|
||||
): string {
|
||||
const destination = new URL(absoluteAppPath(loadRequiredWebConfig().routing, tenantSlug, "settings/billing"));
|
||||
destination.searchParams.set("subscription_required", "1");
|
||||
destination.searchParams.set("selected_price", selectedSubscriptionPriceId);
|
||||
if (selectedOfficeSeatQuantity !== undefined && selectedFieldSeatQuantity !== undefined) {
|
||||
destination.searchParams.set("office_seats", String(selectedOfficeSeatQuantity));
|
||||
destination.searchParams.set("field_seats", String(selectedFieldSeatQuantity));
|
||||
}
|
||||
return destination.toString();
|
||||
}
|
||||
|
||||
function isSafeRelativeRedirect(redirectTo: string) {
|
||||
return redirectTo.startsWith("/") && !redirectTo.startsWith("//") && !redirectTo.includes("\\");
|
||||
}
|
||||
@@ -125,11 +187,13 @@ export async function getSafeLoginRedirect({
|
||||
redirectTo,
|
||||
isAdmin,
|
||||
defaultTenantId,
|
||||
defaultTenantSlug,
|
||||
fallback,
|
||||
}: {
|
||||
redirectTo: string;
|
||||
isAdmin: boolean;
|
||||
defaultTenantId: string;
|
||||
defaultTenantSlug?: string | null;
|
||||
fallback: string;
|
||||
}) {
|
||||
if (!redirectTo || !isSafeRelativeRedirect(redirectTo)) {
|
||||
@@ -149,8 +213,7 @@ export async function getSafeLoginRedirect({
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const defaultTenant = defaultTenantId ? await getTenant(defaultTenantId) : null;
|
||||
const tenantSlug = defaultTenant?.slug;
|
||||
const tenantSlug = defaultTenantSlug ?? undefined;
|
||||
const targetsDefaultTenantId = Boolean(defaultTenantId && (redirectTo === `/${defaultTenantId}` || redirectTo.startsWith(`/${defaultTenantId}/`)));
|
||||
if (targetsDefaultTenantId) {
|
||||
return fallback;
|
||||
@@ -191,14 +254,16 @@ async function loginFromRequest(request: Request, form: FormData) {
|
||||
throw new Error(t("auth:errors.invalidFormData"));
|
||||
}
|
||||
|
||||
const fields = { email, password };
|
||||
// Never return the submitted password in action data. React Router hydrates
|
||||
// error responses into the document, so only non-secret fields may be echoed.
|
||||
const fields = { email };
|
||||
const fieldErrors = {
|
||||
email: !UserValidationUtils.validateEmail(email) ? t("auth:errors.invalidEmail") : undefined,
|
||||
password: !UserValidationUtils.validatePassword(password) ? t("auth:errors.invalidPassword") : undefined,
|
||||
};
|
||||
if (Object.values(fieldErrors).some(Boolean)) return Response.json({ fieldErrors, fields }, { status: 400 });
|
||||
|
||||
const rateLimit = checkAuthRateLimit({
|
||||
const rateLimit = await checkAuthRateLimit({
|
||||
request,
|
||||
action: "login",
|
||||
identifier: email,
|
||||
@@ -212,7 +277,7 @@ async function loginFromRequest(request: Request, form: FormData) {
|
||||
// Brute-force soft gate: after repeated failures per IP+email, require the
|
||||
// configured self-hosted captcha before checking the password.
|
||||
const captchaConfig = resolveCaptchaConfig(process.env);
|
||||
if (isCaptchaConfigured(captchaConfig) && loginRequiresCaptcha(getFailedLoginCount({ request, identifier: email }))) {
|
||||
if (isCaptchaConfigured(captchaConfig) && loginRequiresCaptcha(await getFailedLoginCount({ request, identifier: email }))) {
|
||||
const captchaOk = await verifyCaptchaToken({
|
||||
token: form.get("cap-token")?.toString() ?? form.get("mcaptcha__token")?.toString() ?? form.get("captchaToken")?.toString(),
|
||||
sitekey: getSitekey(captchaConfig, "login"),
|
||||
@@ -238,7 +303,7 @@ async function loginFromRequest(request: Request, form: FormData) {
|
||||
}
|
||||
|
||||
if (isProductionTestAccountBlocked(email)) {
|
||||
return Response.json({ fields: { email, password }, error: t("auth:errors.productionTestAccountBlocked") }, { status: 400 });
|
||||
return Response.json({ fields, error: t("auth:errors.productionTestAccountBlocked") }, { status: 400 });
|
||||
}
|
||||
}
|
||||
// Phase 01 / #20 — Magic-link-only accounts have `passwordHash = null`
|
||||
@@ -252,11 +317,38 @@ async function loginFromRequest(request: Request, form: FormData) {
|
||||
// false for a null-hash row, so no session is ever issued. The magic-link
|
||||
// hint is surfaced generically on the /forgot-password flow, not here.
|
||||
const { valid: isCorrectPassword, rehashedHash } = await verifyPassword(password, user?.passwordHash ?? DUMMY_PASSWORD_HASH);
|
||||
if (!user || user.passwordHash === null || !isCorrectPassword) {
|
||||
recordFailedLogin({ request, identifier: email });
|
||||
// Keep disabled identities on the same generic credentials path so they
|
||||
// cannot be enumerated and never receive an immediately unusable session.
|
||||
if (!user || user.passwordHash === null || !isCorrectPassword || user.active === false) {
|
||||
await recordFailedLogin({ request, identifier: email });
|
||||
return Response.json({ fields, error: t("api.errors.invalidPassword") }, { status: 400 });
|
||||
}
|
||||
|
||||
// Admin identities may only use a password as the explicitly enabled,
|
||||
// allowlisted emergency fallback. This identity-based check also prevents
|
||||
// an AdminUser from bypassing the admin-host policy through an app-host
|
||||
// login; the resulting app cookie remains host-isolated from admin.
|
||||
const isAdminFallbackLogin = Boolean(user.admin);
|
||||
if (isAdminFallbackLogin) {
|
||||
try {
|
||||
assertAdminFallbackLoginAllowedForIdentity(user);
|
||||
} catch (error) {
|
||||
if (!(error instanceof AdminFallbackLoginRejected)) {
|
||||
throw error;
|
||||
}
|
||||
await recordFailedLogin({ request, identifier: email });
|
||||
await writeAdminSsoAuditEvent({
|
||||
action: "admin.login.fallback.failure",
|
||||
actorAdminUserId: user.admin?.userId,
|
||||
request,
|
||||
meta: { reason: error.reason, email, method: "password" },
|
||||
});
|
||||
// Preserve the same public response as invalid credentials so resolving
|
||||
// an AdminUser never becomes an account-enumeration oracle.
|
||||
return Response.json({ fields, error: t("api.errors.invalidPassword") }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
if (rehashedHash) {
|
||||
// Drain a legacy bcrypt user to argon2 transparently on successful login.
|
||||
// Best-effort: never block the login on a rehash-persist failure.
|
||||
@@ -275,7 +367,7 @@ async function loginFromRequest(request: Request, form: FormData) {
|
||||
}
|
||||
|
||||
// Erfolgreicher Login: Brute-Force-Failure-Counter zuruecksetzen (Captcha-Gate faellt wieder weg).
|
||||
clearFailedLogins({ request, identifier: email });
|
||||
await clearFailedLogins({ request, identifier: email });
|
||||
|
||||
// D1 (Produktentscheidung 18.06.) — 2FA-Login-Gate: TOTP-Nutzer erhalten mit Passwort allein
|
||||
// KEINE Session. Stattdessen wird ein signierter Pending-MFA-Zustand ins Cookie geschrieben
|
||||
@@ -283,26 +375,24 @@ async function loginFromRequest(request: Request, form: FormData) {
|
||||
// vertrauenswuerdig markiertes Geraet (Trust-Device-Cookie) ueberspringt den zweiten Faktor.
|
||||
const totpStatus = await getUserTotpStatus(user.id);
|
||||
if (totpStatus?.enabled && !(await isTrustedDevice(request, user.id))) {
|
||||
const setCookie = await commitPendingMfaLoginCookie(request, { userId: user.id, redirectTo });
|
||||
const setCookie = await commitPendingMfaLoginCookie(request, { userId: user.id, redirectTo, primaryMethod: "password" });
|
||||
authLogger.info({ op: "login.mfaRequired", userId: user.id }, "Password accepted; awaiting second factor before issuing a session.");
|
||||
return Response.json(
|
||||
{ requiresMfa: true, redirectTo, mfaVerifyPath: LOGIN_MFA_VERIFY_PATH },
|
||||
{ status: 200, headers: { "Set-Cookie": setCookie } }
|
||||
);
|
||||
return Response.json({ requiresMfa: true, redirectTo, mfaVerifyPath: LOGIN_MFA_VERIFY_PATH }, { status: 200, headers: { "Set-Cookie": setCookie } });
|
||||
}
|
||||
|
||||
await createLogLogin(request, user);
|
||||
const userSession = await setLoggedUser(user);
|
||||
// const tenant = await getTenant(userSession.defaultTenantId);
|
||||
const { defaultTenant, ...userSessionData } = userSession;
|
||||
const appHome = await getHome({
|
||||
isAdmin: !!user.admin,
|
||||
tenantId: userSession.defaultTenantId,
|
||||
tenantSlug: defaultTenant?.slug,
|
||||
request,
|
||||
});
|
||||
const safeRedirectTo = await getSafeLoginRedirect({
|
||||
redirectTo,
|
||||
isAdmin: !!user.admin,
|
||||
defaultTenantId: userSession.defaultTenantId,
|
||||
defaultTenantId: userSessionData.defaultTenantId,
|
||||
defaultTenantSlug: defaultTenant?.slug,
|
||||
fallback: appHome,
|
||||
});
|
||||
// Phase 01 / #27 — soft-check the submitted password against the current
|
||||
@@ -333,19 +423,32 @@ async function loginFromRequest(request: Request, form: FormData) {
|
||||
"Password policy soft-check raised; falling back to policyOutdated=false."
|
||||
);
|
||||
}
|
||||
// R-P2a S4b — serverseitige Session-Zeile additiv anlegen (best-effort; ein Store-Fehler darf
|
||||
// den Login nicht blockieren) und ihren Token ins Cookie geben.
|
||||
const sessionToken = await startServerSession({ request, userId: user.id }).catch(() => null);
|
||||
return createUserSession(
|
||||
const response = await createUserSession(
|
||||
{
|
||||
...userInfo,
|
||||
...userSession,
|
||||
...userSessionData,
|
||||
lng: user.locale ?? userInfo.lng,
|
||||
passwordPolicyOutdated: passwordPolicyOutdated || undefined,
|
||||
sessionToken: sessionToken ?? undefined,
|
||||
},
|
||||
safeRedirectTo
|
||||
safeRedirectTo,
|
||||
isAdminFallbackLogin
|
||||
? {
|
||||
request,
|
||||
rotate: true,
|
||||
adminAuthenticationMethods: ["local-development", "mfa"],
|
||||
adminMfaAssuredAt: new Date(),
|
||||
}
|
||||
: { request, rotate: true }
|
||||
);
|
||||
if (isAdminFallbackLogin && isCompletedAdminFallbackLoginResponse(response)) {
|
||||
await writeAdminSsoAuditEvent({
|
||||
action: "admin.login.fallback.success",
|
||||
actorAdminUserId: user.admin?.userId,
|
||||
request,
|
||||
meta: { email, severity: "warn", method: "password" },
|
||||
});
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -364,7 +467,10 @@ async function verifyMfaLoginFromRequest(request: Request, form: FormData) {
|
||||
const { t } = await getTranslations(request);
|
||||
const session = await getUserSession(request);
|
||||
const pendingMfaUserId = session.get("pendingMfaUserId");
|
||||
if (typeof pendingMfaUserId !== "string" || pendingMfaUserId.length === 0) {
|
||||
const pendingMfaStartedAt = session.get("pendingMfaStartedAt");
|
||||
const rawPendingMfaPrimaryMethod = session.get(PENDING_MFA_PRIMARY_METHOD_KEY);
|
||||
const pendingMfaPrimaryMethod = isPendingMfaPrimaryMethod(rawPendingMfaPrimaryMethod) ? rawPendingMfaPrimaryMethod : undefined;
|
||||
if (typeof pendingMfaUserId !== "string" || pendingMfaUserId.length === 0 || !isPendingMfaLoginFresh(pendingMfaStartedAt)) {
|
||||
// Kein laufender 2FA-Login (Cookie fehlt/abgelaufen) -> sauber zurueck zur Anmeldung.
|
||||
throw redirect("/login");
|
||||
}
|
||||
@@ -381,7 +487,10 @@ async function verifyMfaLoginFromRequest(request: Request, form: FormData) {
|
||||
const rateLimitKey = mfaChallengeRateLimitKey(request, user.id);
|
||||
const rateLimit = await checkMfaChallengeRateLimit(rateLimitKey);
|
||||
if (!rateLimit.allowed) {
|
||||
return Response.json({ error: t("account.loginMfa.errors.tooManyAttempts") }, { status: 429, headers: { "Retry-After": String(rateLimit.retryAfterSeconds) } });
|
||||
return Response.json(
|
||||
{ error: t("account.loginMfa.errors.tooManyAttempts") },
|
||||
{ status: 429, headers: { "Retry-After": String(rateLimit.retryAfterSeconds) } }
|
||||
);
|
||||
}
|
||||
|
||||
let verified = false;
|
||||
@@ -410,28 +519,70 @@ async function verifyMfaLoginFromRequest(request: Request, form: FormData) {
|
||||
|
||||
await resetMfaChallengeRateLimit(rateLimitKey);
|
||||
|
||||
// The pending cookie is signed and records which primary factor established
|
||||
// the challenge. Authentik is the only AdminUser path that may finish
|
||||
// without the emergency fallback policy; every other path is re-checked at
|
||||
// the last possible point so disabling/removing the allowlist during the MFA
|
||||
// challenge prevents a real admin session from being issued.
|
||||
const isAdminFallbackMfa = Boolean(user.admin && pendingMfaPrimaryMethod !== "admin-sso");
|
||||
if (isAdminFallbackMfa) {
|
||||
try {
|
||||
assertAdminFallbackLoginAllowedForIdentity(user);
|
||||
} catch (error) {
|
||||
if (!(error instanceof AdminFallbackLoginRejected)) {
|
||||
throw error;
|
||||
}
|
||||
await writeAdminSsoAuditEvent({
|
||||
action: "admin.login.fallback.failure",
|
||||
actorAdminUserId: user.admin?.userId,
|
||||
request,
|
||||
meta: {
|
||||
reason: error.reason,
|
||||
email: user.email,
|
||||
method: pendingMfaPrimaryMethod ?? "unknown",
|
||||
stage: "mfa-complete",
|
||||
},
|
||||
});
|
||||
throw redirect("/login?error=fallback_disabled");
|
||||
}
|
||||
}
|
||||
|
||||
// Ab hier identisch zum normalen Login-Abschluss in loginFromRequest.
|
||||
const userInfo = await getUserInfo(request);
|
||||
await createLogLogin(request, user);
|
||||
const userSession = await setLoggedUser(user);
|
||||
const appHome = await getHome({ isAdmin: !!user.admin, tenantId: userSession.defaultTenantId, request });
|
||||
const { defaultTenant, ...userSessionData } = userSession;
|
||||
const appHome = await getHome({ isAdmin: !!user.admin, tenantSlug: defaultTenant?.slug, request });
|
||||
const rawRedirectTo = session.get("pendingMfaRedirectTo");
|
||||
const safeRedirectTo = await getSafeLoginRedirect({
|
||||
redirectTo: typeof rawRedirectTo === "string" ? rawRedirectTo : "",
|
||||
isAdmin: !!user.admin,
|
||||
defaultTenantId: userSession.defaultTenantId,
|
||||
defaultTenantId: userSessionData.defaultTenantId,
|
||||
defaultTenantSlug: defaultTenant?.slug,
|
||||
fallback: appHome,
|
||||
});
|
||||
const sessionToken = await startServerSession({ request, userId: user.id }).catch(() => null);
|
||||
const response = await createUserSession(
|
||||
{
|
||||
...userInfo,
|
||||
...userSession,
|
||||
...userSessionData,
|
||||
lng: user.locale ?? userInfo.lng,
|
||||
sessionToken: sessionToken ?? undefined,
|
||||
},
|
||||
safeRedirectTo
|
||||
safeRedirectTo,
|
||||
{ request, rotate: true }
|
||||
);
|
||||
if (isAdminFallbackMfa && isCompletedAdminFallbackLoginResponse(response)) {
|
||||
await writeAdminSsoAuditEvent({
|
||||
action: "admin.login.fallback.success",
|
||||
actorAdminUserId: user.admin?.userId,
|
||||
request,
|
||||
meta: {
|
||||
email: user.email,
|
||||
severity: "warn",
|
||||
method: pendingMfaPrimaryMethod ?? "unknown",
|
||||
mfa: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Trust-Device: dieses Geraet kuenftig ohne zweiten Faktor zulassen. Legt eine widerrufbare
|
||||
// TrustedDevice-Zeile an und gibt den Token als zusaetzliches Set-Cookie aus.
|
||||
@@ -444,84 +595,263 @@ async function verifyMfaLoginFromRequest(request: Request, form: FormData) {
|
||||
async function registerFromRequest(request: Request) {
|
||||
const { t } = await getTranslations(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
let creationRequestKey: string | undefined;
|
||||
let verificationFlowAttempted = false;
|
||||
let verificationEmail: string | undefined;
|
||||
let shouldResetCaptcha = false;
|
||||
try {
|
||||
await validateCSRFToken(request);
|
||||
const registrationData = await getRegistrationFormData(request);
|
||||
const result = await validateRegistration({ request, registrationData, addToTrialOrFreePlan: true });
|
||||
shouldResetCaptcha = registrationData.intent !== "resendVerification";
|
||||
if (registrationData.creationRequestKey && isSignupCreationRequestKey(registrationData.creationRequestKey)) {
|
||||
creationRequestKey = registrationData.creationRequestKey;
|
||||
}
|
||||
const isResendVerification = registrationData.intent === "resendVerification";
|
||||
let resendRecovery: { registrationId: string; catchUpOnly: boolean } | undefined;
|
||||
if (isResendVerification && registrationData.email) {
|
||||
const signedRecovery = await readRegistrationResendRecovery(request);
|
||||
if (signedRecovery?.email === registrationData.email.trim().toLowerCase()) {
|
||||
const resolvedRecovery = await resolvePendingRegistrationResendRecovery(signedRecovery);
|
||||
if (resolvedRecovery) {
|
||||
registrationData.creationRequestKey = resolvedRecovery.creationRequestKey;
|
||||
creationRequestKey = resolvedRecovery.creationRequestKey;
|
||||
resendRecovery = {
|
||||
registrationId: resolvedRecovery.registrationId,
|
||||
catchUpOnly: resolvedRecovery.catchUpOnly,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!isResendVerification && (!registrationData.acceptTerms || !registrationData.acceptPrivacy)) {
|
||||
throw new RegistrationValidationError("account.register.errors.acceptTermsAndPrivacy");
|
||||
}
|
||||
const result = await validateRegistration({
|
||||
request,
|
||||
registrationData,
|
||||
addToTrialOrFreePlan: false,
|
||||
requireSubscriptionSelection: true,
|
||||
...(isResendVerification ? { captchaAlreadyVerified: true } : {}),
|
||||
});
|
||||
if (result.verificationRequired) {
|
||||
await createRegistrationForm({ ...registrationData, email: result.email, ipAddress: result.ipAddress, recreateToken: false, request });
|
||||
return Response.json({ verificationEmailSent: true });
|
||||
verificationFlowAttempted = true;
|
||||
verificationEmail = result.email;
|
||||
if (!creationRequestKey) {
|
||||
throw new RegistrationValidationError("auth:errors.invalidFormData");
|
||||
}
|
||||
const createdRegistration = await createRegistrationForm({
|
||||
...registrationData,
|
||||
email: result.email,
|
||||
ipAddress: result.ipAddress,
|
||||
resendOnly: isResendVerification,
|
||||
request,
|
||||
creationRequestKey,
|
||||
selectedSubscriptionPriceId: result.selectedSubscriptionPriceId,
|
||||
selectedOfficeSeatQuantity: result.selectedOfficeSeatQuantity,
|
||||
selectedFieldSeatQuantity: result.selectedFieldSeatQuantity,
|
||||
...(resendRecovery ? { resendRecovery } : {}),
|
||||
});
|
||||
creationRequestKey = createdRegistration.creationRequestKey;
|
||||
return await registrationVerificationResponse(verificationEmail, creationRequestKey);
|
||||
} else if (result.registered) {
|
||||
const userSession = await setLoggedUser(result.registered.user);
|
||||
const home = await getHome({
|
||||
isAdmin: false,
|
||||
tenantId: userSession.defaultTenantId,
|
||||
request,
|
||||
});
|
||||
const sessionToken = await startServerSession({ request, userId: result.registered.user.id }).catch(() => null);
|
||||
return createUserSession(
|
||||
const { defaultTenant, ...userSessionData } = userSession;
|
||||
const tenantSlug = defaultTenant?.slug ?? result.registered.tenant.slug;
|
||||
const home = result.selectedSubscriptionPriceId
|
||||
? getRegistrationBillingDestination(tenantSlug, result.selectedSubscriptionPriceId, result.selectedOfficeSeatQuantity, result.selectedFieldSeatQuantity)
|
||||
: await getHome({
|
||||
isAdmin: false,
|
||||
tenantSlug,
|
||||
request,
|
||||
});
|
||||
const response = await createUserSession(
|
||||
{
|
||||
...userInfo,
|
||||
...userSession,
|
||||
...userSessionData,
|
||||
lng: result.registered.user.locale ?? userInfo.lng,
|
||||
sessionToken: sessionToken ?? undefined,
|
||||
},
|
||||
home
|
||||
home,
|
||||
{ request, rotate: true }
|
||||
);
|
||||
return await clearRegistrationRecoveryOnSessionResponse(response);
|
||||
}
|
||||
return Response.json({ error: t("shared.unknownError") }, { status: 400 });
|
||||
} catch (e: any) {
|
||||
return Response.json(
|
||||
{
|
||||
error: t("shared.unknownError"),
|
||||
...(creationRequestKey ? { creationRequestKey } : {}),
|
||||
...(shouldResetCaptcha ? { captchaResetKey: randomUUID() } : {}),
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
} catch (e: unknown) {
|
||||
// Intentionally do NOT log e.message verbatim — auth flow errors may
|
||||
// contain user-provided email/registration tokens. Log only the error
|
||||
// class and a short tag so we can still investigate via Sentry.
|
||||
authLogger.warn(
|
||||
{
|
||||
err: { name: e?.name ?? "Error", message: typeof e?.message === "string" ? "[redacted]" : "[unknown]" },
|
||||
err: { name: e instanceof Error ? e.name : "Error", message: e instanceof Error ? "[redacted]" : "[unknown]" },
|
||||
op: "verifyAndRegister",
|
||||
},
|
||||
"Auth verify-and-register failed"
|
||||
);
|
||||
return Response.json({ error: t(e.message) }, { status: 400 });
|
||||
if (verificationFlowAttempted && isHiddenRegistrationExistenceConflict(e) && creationRequestKey) {
|
||||
authLogger.info(
|
||||
{
|
||||
op: "registration.existence_hidden",
|
||||
reason: e instanceof RegistrationValidationError ? "registered" : "pending-conflict",
|
||||
},
|
||||
"Registration existence response normalized"
|
||||
);
|
||||
if (verificationEmail) {
|
||||
return await registrationVerificationResponse(verificationEmail, creationRequestKey);
|
||||
}
|
||||
}
|
||||
const publicError =
|
||||
e instanceof RegistrationValidationError ? t(e.i18nKey, e.i18nArgs ?? {}) : e instanceof CatalogError ? t(e.i18nKey) : t("shared.unknownError");
|
||||
return Response.json(
|
||||
{
|
||||
error: publicError,
|
||||
...(creationRequestKey ? { creationRequestKey } : {}),
|
||||
// CAP proofs are single-use. Any later validation failure after a
|
||||
// successful verification has consumed the proof as well, so every
|
||||
// failed initial registration must mount a fresh challenge for retry.
|
||||
...(shouldResetCaptcha ? { captchaResetKey: randomUUID() } : {}),
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function registrationVerificationResponse(email: string, creationRequestKey: string): Promise<Response> {
|
||||
return Response.json(
|
||||
{ verificationEmailSent: true, creationRequestKey },
|
||||
{
|
||||
headers: {
|
||||
"Cache-Control": "no-store",
|
||||
"Set-Cookie": await commitRegistrationResendRecovery({ email, creationRequestKey }),
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
async function clearRegistrationRecoveryOnSessionResponse(response: Response): Promise<Response> {
|
||||
response.headers.append("Set-Cookie", await clearRegistrationResendRecovery());
|
||||
return response;
|
||||
}
|
||||
|
||||
function isHiddenRegistrationExistenceConflict(error: unknown): boolean {
|
||||
return (
|
||||
(error instanceof RegistrationValidationError && error.i18nKey === "api.errors.userAlreadyRegistered") ||
|
||||
(error instanceof CatalogError && error.code === "foundation.idempotency_conflict")
|
||||
);
|
||||
}
|
||||
|
||||
async function verifyFromRequest({ request, params }: { request: Request; params: Params }) {
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const verificationToken = params.id ?? "";
|
||||
const rateLimit = await checkAuthRateLimit({
|
||||
request,
|
||||
action: "registration-verify",
|
||||
identifier: registrationVerifyRateLimitIdentifier(verificationToken),
|
||||
limit: REGISTRATION_VERIFY_RATE_LIMIT,
|
||||
windowMs: REGISTRATION_VERIFY_RATE_LIMIT_WINDOW_MS,
|
||||
});
|
||||
if (!rateLimit.allowed) {
|
||||
return Response.json(
|
||||
{ error: t("api.errors.tooManyRequests") },
|
||||
{
|
||||
status: 429,
|
||||
headers: {
|
||||
"Cache-Control": "no-store",
|
||||
"Retry-After": String(rateLimit.retryAfterSeconds),
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
const userInfo = await getUserInfo(request);
|
||||
|
||||
const registration = await getRegistrationByToken(params.id ?? "");
|
||||
if (!registration || registration.createdTenantId) {
|
||||
return Response.json({ error: t("api.errors.userAlreadyRegistered") }, { status: 400 });
|
||||
const verificationState = await getRegistrationVerificationStateByToken(verificationToken);
|
||||
if (verificationState.status !== "pending") {
|
||||
const errorKey =
|
||||
verificationState.status === "expired"
|
||||
? "account.verify.expiredLink"
|
||||
: verificationState.status === "used"
|
||||
? "account.verify.usedLink"
|
||||
: "account.verify.invalidLink";
|
||||
return Response.json({ error: t(errorKey) }, { status: 400 });
|
||||
}
|
||||
const registration = verificationState.registration;
|
||||
|
||||
let creationRequestKey: string | undefined;
|
||||
try {
|
||||
const registrationData = await getRegistrationFormData(request);
|
||||
registrationData.leadId = registration.leadConversionLeadId ?? undefined;
|
||||
registrationData.leadToken = registration.leadConversionToken ?? undefined;
|
||||
registrationData.leadPlanId = registration.leadConversionPlanId ?? undefined;
|
||||
const result = await validateRegistration({ request, registrationData, checkEmailVerification: false, addToTrialOrFreePlan: true });
|
||||
if (!result.registered) {
|
||||
return Response.json({ error: t("shared.unknownError") }, { status: 400 });
|
||||
const submittedData = await getRegistrationFormData(request);
|
||||
const expectedCreationRequestKey = deriveVerificationCreationRequestKey(registration.id);
|
||||
if (
|
||||
!submittedData.creationRequestKey ||
|
||||
!isSignupCreationRequestKey(submittedData.creationRequestKey) ||
|
||||
submittedData.creationRequestKey !== expectedCreationRequestKey
|
||||
) {
|
||||
throw new Error("Invalid verification creation request key");
|
||||
}
|
||||
await updateRegistration(registration.id, { createdTenantId: result.registered.tenant.id });
|
||||
const userSession = await setLoggedUser(result.registered.user);
|
||||
const appHome = await getHome({
|
||||
isAdmin: false,
|
||||
tenantId: userSession.defaultTenantId,
|
||||
creationRequestKey = expectedCreationRequestKey;
|
||||
// The URL token selects the persisted registration. Only the password and
|
||||
// captcha proof may come from the browser; identity and lead fields are
|
||||
// immutable here so hidden-form tampering cannot change the new account.
|
||||
const registrationData = {
|
||||
email: registration.email,
|
||||
password: submittedData.password,
|
||||
company: registration.company ?? undefined,
|
||||
firstName: registration.firstName,
|
||||
lastName: registration.lastName,
|
||||
slug: registration.slug ?? undefined,
|
||||
leadId: registration.leadConversionLeadId ?? undefined,
|
||||
leadToken: registration.leadConversionToken ?? undefined,
|
||||
leadPlanId: registration.leadConversionPlanId ?? undefined,
|
||||
selectedSubscriptionPriceId: registration.selectedSubscriptionPriceId ?? undefined,
|
||||
selectedOfficeSeatQuantity: registration.selectedOfficeSeatQuantity ?? undefined,
|
||||
selectedFieldSeatQuantity: registration.selectedFieldSeatQuantity ?? undefined,
|
||||
creationRequestKey,
|
||||
captchaToken: submittedData.captchaToken,
|
||||
};
|
||||
const result = await validateRegistration({
|
||||
request,
|
||||
registrationData,
|
||||
checkEmailVerification: false,
|
||||
captchaAlreadyVerified: true,
|
||||
addToTrialOrFreePlan: false,
|
||||
requireSubscriptionSelection: true,
|
||||
requireRegistrationSeatQuantities: registration.selectedOfficeSeatQuantity !== null && registration.selectedFieldSeatQuantity !== null,
|
||||
});
|
||||
const sessionToken = await startServerSession({ request, userId: result.registered.user.id }).catch(() => null);
|
||||
return createUserSession(
|
||||
if (!result.registered) {
|
||||
return Response.json({ error: t("shared.unknownError"), ...(creationRequestKey ? { creationRequestKey } : {}) }, { status: 400 });
|
||||
}
|
||||
// The compare-and-set below is the intentional replay boundary. Before it
|
||||
// commits, response-loss may safely retry the same key/payload. Afterwards
|
||||
// the token stays consumed; the committed password account recovers via
|
||||
// normal login instead of turning this verification URL into a login link.
|
||||
await updateRegistration(registration.id, { expectedToken: verificationToken }, { createdTenantId: result.registered.tenant.id });
|
||||
const userSession = await setLoggedUser(result.registered.user);
|
||||
const { defaultTenant, ...userSessionData } = userSession;
|
||||
const tenantSlug = defaultTenant?.slug ?? result.registered.tenant.slug;
|
||||
const appHome = result.selectedSubscriptionPriceId
|
||||
? getRegistrationBillingDestination(tenantSlug, result.selectedSubscriptionPriceId, result.selectedOfficeSeatQuantity, result.selectedFieldSeatQuantity)
|
||||
: await getHome({
|
||||
isAdmin: false,
|
||||
tenantSlug,
|
||||
request,
|
||||
});
|
||||
const response = await createUserSession(
|
||||
{
|
||||
...userInfo,
|
||||
...userSession,
|
||||
...userSessionData,
|
||||
lng: result.registered.user.locale ?? userInfo.lng,
|
||||
sessionToken: sessionToken ?? undefined,
|
||||
},
|
||||
appHome
|
||||
appHome,
|
||||
{ request, rotate: true }
|
||||
);
|
||||
return await clearRegistrationRecoveryOnSessionResponse(response);
|
||||
} catch {
|
||||
return Response.json({ error: t("shared.unknownError") }, { status: 400 });
|
||||
return Response.json({ error: t("shared.unknownError"), ...(creationRequestKey ? { creationRequestKey } : {}) }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user