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,11 +1,17 @@
|
||||
import { createCookieSessionStorage, redirect, Session } from "react-router";
|
||||
import { loadRequiredWebConfig, resolveSessionCookiePolicy } from "@hivegrid/config";
|
||||
import { getMyTenants, getTenant } from "./db/tenants.db.server";
|
||||
import { loadRequiredWebConfig, resolveWebSessionCookiePolicy, type WebSessionCookieSurface } from "@hivegrid/config";
|
||||
import { getTenantSessionIdentityForUser, type TenantSessionIdentity } from "./db/tenants.db.server";
|
||||
import { randomBytes, timingSafeEqual } from "crypto";
|
||||
import { getUser } from "./db/users.db.server";
|
||||
import { getActiveSessionByToken } from "~/services/auth/sessionStore.server";
|
||||
import { endServerSession } from "~/services/auth/sessionLifecycle.server";
|
||||
import { endServerSession, startServerSession } from "~/services/auth/sessionLifecycle.server";
|
||||
import type { ActiveUserSessionRow } from "~/services/auth/sessionStore.server";
|
||||
import { getActiveAdminSessionByToken, type ActiveAdminSession } from "@hivegrid/db/admin-sessions.server";
|
||||
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { createScopedLogger } from "./logger.server";
|
||||
import { getHostRoutingContext, getRequestRoutingHost } from "./app/HostRouting.server";
|
||||
import { safeSessionRedirectTarget } from "./app/SessionRedirectSafety.server";
|
||||
import { defaultLocale, normalizeLocaleCandidate } from "@hivegrid/i18n";
|
||||
|
||||
const sessionLogger = createScopedLogger("session");
|
||||
|
||||
@@ -13,6 +19,7 @@ const sessionLogger = createScopedLogger("session");
|
||||
// `validateImpersonationSessionState` reports `stale_started_at` past this
|
||||
// window so the impersonated tenant session can no longer act.
|
||||
export const IMPERSONATION_SESSION_TTL_MS = 30 * 60 * 1000;
|
||||
export const PENDING_MFA_LOGIN_TTL_MS = 10 * 60 * 1000;
|
||||
|
||||
export type ImpersonationSessionValidationReason =
|
||||
| "not_impersonating"
|
||||
@@ -44,6 +51,8 @@ export type UserSession = {
|
||||
ignoreUrls: string[];
|
||||
};
|
||||
impersonatingFromUserId?: string;
|
||||
impersonatingFromAdminUserId?: string;
|
||||
impersonatingFromAdminEmail?: string;
|
||||
impersonatingStartedAt?: string;
|
||||
theme?: string;
|
||||
/**
|
||||
@@ -52,11 +61,7 @@ export type UserSession = {
|
||||
* dashboard soft-banner. Never gates the login itself.
|
||||
*/
|
||||
passwordPolicyOutdated?: boolean;
|
||||
/**
|
||||
* R-P2a S4b — opaker Token der serverseitigen Session (UserSession-Zeile). Additiv: das Cookie
|
||||
* bleibt primaerer Auth-Mechanismus; ist der Token gesetzt, honoriert requireUserId Revoke/
|
||||
* "ueberall abmelden". Alte Cookies ohne Token bleiben unberuehrt.
|
||||
*/
|
||||
/** Every authenticated cookie must reference an active UserSession row. */
|
||||
sessionToken?: string;
|
||||
/**
|
||||
* D1 (2FA-Login-Gate) — Zwischenzustand zwischen Passwort-OK und TOTP-Verifikation. Traegt das
|
||||
@@ -67,42 +72,67 @@ export type UserSession = {
|
||||
*/
|
||||
pendingMfaUserId?: string;
|
||||
pendingMfaRedirectTo?: string;
|
||||
pendingMfaStartedAt?: string;
|
||||
pendingMfaPrimaryMethod?: PendingMfaPrimaryMethod;
|
||||
};
|
||||
|
||||
export const PENDING_MFA_USER_ID_KEY = "pendingMfaUserId";
|
||||
export const PENDING_MFA_REDIRECT_KEY = "pendingMfaRedirectTo";
|
||||
export const PENDING_MFA_STARTED_AT_KEY = "pendingMfaStartedAt";
|
||||
export const PENDING_MFA_PRIMARY_METHOD_KEY = "pendingMfaPrimaryMethod";
|
||||
export type PendingMfaPrimaryMethod = "admin-sso" | "password" | "magic-link" | "password-reset" | "invitation";
|
||||
|
||||
export function isPendingMfaPrimaryMethod(value: unknown): value is PendingMfaPrimaryMethod {
|
||||
return value === "admin-sso" || value === "password" || value === "magic-link" || value === "password-reset" || value === "invitation";
|
||||
}
|
||||
|
||||
export function isPendingMfaLoginFresh(value: unknown, nowMs = Date.now()): value is string {
|
||||
if (typeof value !== "string") return false;
|
||||
const startedAtMs = Date.parse(value);
|
||||
return Number.isFinite(startedAtMs) && startedAtMs <= nowMs && nowMs - startedAtMs < PENDING_MFA_LOGIN_TTL_MS;
|
||||
}
|
||||
|
||||
export type SetLoggedUserResult = {
|
||||
userId: string;
|
||||
defaultTenantId: string;
|
||||
/**
|
||||
* The tenant resolved during setLoggedUser, if any. Returned so callers can
|
||||
* avoid a second `getTenant(userSession.defaultTenantId)` round-trip
|
||||
* immediately after sign-in / impersonation.
|
||||
* reuse the membership-proven safe projection immediately after sign-in or
|
||||
* impersonation without a second cache-backed tenant lookup.
|
||||
*/
|
||||
defaultTenant: Awaited<ReturnType<typeof getTenant>> | null;
|
||||
defaultTenant: TenantSessionIdentity | null;
|
||||
};
|
||||
|
||||
export async function setLoggedUser(user: { id: string; email: string; defaultTenantId: string | null }): Promise<SetLoggedUserResult> {
|
||||
if (user.defaultTenantId) {
|
||||
const tenant = await getTenant(user.defaultTenantId);
|
||||
if (tenant) {
|
||||
return {
|
||||
userId: user.id,
|
||||
defaultTenantId: tenant.id,
|
||||
defaultTenant: tenant,
|
||||
};
|
||||
export function setLoggedUser(user: { id: string; email: string; defaultTenantId: string | null }): Promise<SetLoggedUserResult> {
|
||||
const resolveTenant = async (): Promise<SetLoggedUserResult> => {
|
||||
if (user.defaultTenantId) {
|
||||
const tenant = await getTenantSessionIdentityForUser({ userId: user.id, tenant: user.defaultTenantId });
|
||||
if (tenant) {
|
||||
return {
|
||||
userId: user.id,
|
||||
defaultTenantId: tenant.id,
|
||||
defaultTenant: tenant,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const userTenants = await getMyTenants(user.id);
|
||||
const fallback = userTenants[0] ?? null;
|
||||
const fallback = await getTenantSessionIdentityForUser({ userId: user.id });
|
||||
|
||||
return {
|
||||
userId: user.id,
|
||||
defaultTenantId: fallback?.id ?? "",
|
||||
defaultTenant: null,
|
||||
return {
|
||||
userId: user.id,
|
||||
defaultTenantId: fallback?.id ?? "",
|
||||
defaultTenant: fallback,
|
||||
};
|
||||
};
|
||||
|
||||
// Login and magic-link callbacks run before the request middleware has an
|
||||
// authenticated identity. Bind the just-authenticated user so Tenant and
|
||||
// TenantUser policies can resolve the initial workspace. An existing
|
||||
// context (for example an operator impersonation flow) remains authoritative.
|
||||
if (getRlsExecutionContext()?.userId) {
|
||||
return resolveTenant();
|
||||
}
|
||||
return runWithRlsContext({ userId: user.id }, resolveTenant);
|
||||
}
|
||||
|
||||
export function createImpersonationStartedAt(now: Date = new Date()) {
|
||||
@@ -145,57 +175,228 @@ export function validateImpersonationSessionState(
|
||||
return { valid: true, reason: "valid", actorUserId, startedAt };
|
||||
}
|
||||
|
||||
const webConfig = loadRequiredWebConfig();
|
||||
|
||||
export const storage = createCookieSessionStorage({
|
||||
cookie: {
|
||||
...resolveSessionCookiePolicy({
|
||||
nodeEnv: webConfig.nodeEnv,
|
||||
routing: webConfig.routing,
|
||||
name: "hivegrid_session",
|
||||
maxAge: 60 * 60 * 24 * 30,
|
||||
}),
|
||||
secrets: webConfig.sessionSecret ? [webConfig.sessionSecret] : [],
|
||||
export function validateAdminImpersonationSessionState(
|
||||
state: {
|
||||
impersonatingFromAdminUserId?: unknown;
|
||||
impersonatingFromAdminEmail?: unknown;
|
||||
impersonatingStartedAt?: unknown;
|
||||
userId?: unknown;
|
||||
},
|
||||
});
|
||||
now = new Date()
|
||||
): boolean {
|
||||
const actorId = state.impersonatingFromAdminUserId;
|
||||
const actorEmail = state.impersonatingFromAdminEmail;
|
||||
const targetId = state.userId;
|
||||
const startedAt = state.impersonatingStartedAt;
|
||||
if (![actorId, actorEmail, targetId, startedAt].every((value) => typeof value === "string" && value.length > 0)) return false;
|
||||
const issuedAt = Date.parse(startedAt as string);
|
||||
return Number.isFinite(issuedAt) && issuedAt <= now.getTime() && now.getTime() - issuedAt <= IMPERSONATION_SESSION_TTL_MS;
|
||||
}
|
||||
|
||||
function resolveEffectiveSessionUserId({
|
||||
userId,
|
||||
impersonatingFromUserId,
|
||||
impersonatingStartedAt,
|
||||
validation,
|
||||
}: {
|
||||
userId: unknown;
|
||||
impersonatingFromUserId: unknown;
|
||||
impersonatingStartedAt: unknown;
|
||||
validation: ImpersonationSessionValidation;
|
||||
}): string | null {
|
||||
const hasImpersonationMarker = typeof impersonatingFromUserId === "string" || typeof impersonatingStartedAt === "string";
|
||||
if (validation.valid || !hasImpersonationMarker) {
|
||||
return typeof userId === "string" && userId.length > 0 ? userId : null;
|
||||
}
|
||||
|
||||
// A malformed or expired impersonation cookie must never degrade into an
|
||||
// ordinary session for the target user. The signed actor id is the only
|
||||
// safe identity to restore; if it is unavailable, fail closed.
|
||||
return typeof impersonatingFromUserId === "string" && impersonatingFromUserId.length > 0 ? impersonatingFromUserId : null;
|
||||
}
|
||||
|
||||
type ActiveServerSession = ActiveUserSessionRow | NonNullable<ActiveAdminSession>;
|
||||
|
||||
type ServerSessionValidation =
|
||||
| { valid: true; session: ActiveServerSession }
|
||||
| { valid: false; reason: "missing-token" | "inactive-token" | "owner-mismatch" | "store-error" };
|
||||
|
||||
const requestServerSessionValidation = new WeakMap<Request, { key: string; promise: Promise<ServerSessionValidation> }>();
|
||||
|
||||
async function validateServerSessionForRequest(request: Request, rawToken: unknown, expectedOwnerUserId: string): Promise<ServerSessionValidation> {
|
||||
if (typeof rawToken !== "string" || rawToken.length === 0) {
|
||||
return { valid: false, reason: "missing-token" };
|
||||
}
|
||||
|
||||
const key = `${expectedOwnerUserId}\u0000${rawToken}`;
|
||||
const cached = requestServerSessionValidation.get(request);
|
||||
if (cached?.key === key) {
|
||||
return cached.promise;
|
||||
}
|
||||
|
||||
const promise = (async (): Promise<ServerSessionValidation> => {
|
||||
let activeSession: ActiveServerSession | null;
|
||||
try {
|
||||
activeSession =
|
||||
surfaceForRequest(request) === "admin" ? await getActiveAdminSessionByToken(rawToken) : await getActiveSessionByToken(rawToken);
|
||||
} catch (error) {
|
||||
sessionLogger.warn(
|
||||
{ op: "session.validation.failed", err: { name: error instanceof Error ? error.name : "Error" } },
|
||||
"Server-session validation failed closed."
|
||||
);
|
||||
return { valid: false, reason: "store-error" };
|
||||
}
|
||||
if (!activeSession) {
|
||||
return { valid: false, reason: "inactive-token" };
|
||||
}
|
||||
const ownerId = "adminUserId" in activeSession ? activeSession.adminUserId : activeSession.userId;
|
||||
if (ownerId !== expectedOwnerUserId) {
|
||||
return { valid: false, reason: "owner-mismatch" };
|
||||
}
|
||||
return { valid: true, session: activeSession };
|
||||
})();
|
||||
requestServerSessionValidation.set(request, { key, promise });
|
||||
return promise;
|
||||
}
|
||||
|
||||
const webConfig = loadRequiredWebConfig();
|
||||
const SESSION_MAX_AGE_SECONDS = 60 * 60 * 24 * 30;
|
||||
|
||||
function createSurfaceSessionStorage(surface: WebSessionCookieSurface) {
|
||||
return createCookieSessionStorage({
|
||||
cookie: {
|
||||
...resolveWebSessionCookiePolicy({
|
||||
nodeEnv: webConfig.nodeEnv,
|
||||
routing: webConfig.routing,
|
||||
surface,
|
||||
maxAge: SESSION_MAX_AGE_SECONDS,
|
||||
}),
|
||||
secrets: webConfig.sessionSecret ? [webConfig.sessionSecret] : [],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const appSessionStorage = createSurfaceSessionStorage("app");
|
||||
const adminSessionStorage = createSurfaceSessionStorage("admin");
|
||||
const sessionSurface = new WeakMap<object, WebSessionCookieSurface>();
|
||||
|
||||
function storageForSurface(surface: WebSessionCookieSurface) {
|
||||
return surface === "admin" ? adminSessionStorage : appSessionStorage;
|
||||
}
|
||||
|
||||
function surfaceForRequest(request: Request): WebSessionCookieSurface {
|
||||
const url = new URL(request.url);
|
||||
const host = getRequestRoutingHost(request, url, webConfig.routing);
|
||||
return getHostRoutingContext(host, webConfig.routing) === "admin" ? "admin" : "app";
|
||||
}
|
||||
|
||||
function rememberSessionSurface<T extends Session>(session: T, surface: WebSessionCookieSurface): T {
|
||||
sessionSurface.set(session, surface);
|
||||
return session;
|
||||
}
|
||||
|
||||
async function getSurfaceSession(surface: WebSessionCookieSurface, cookieHeader?: string | null) {
|
||||
return rememberSessionSurface(await storageForSurface(surface).getSession(cookieHeader), surface);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compatibility facade for existing call sites. New request-bound reads must
|
||||
* use `getUserSession(request)` so the app/admin cookie namespace is selected
|
||||
* from the canonical host. Sessions returned by that helper retain their
|
||||
* surface for subsequent commit/destroy calls.
|
||||
*/
|
||||
export const storage = {
|
||||
getSession(cookieHeader?: string | null) {
|
||||
return getSurfaceSession("app", cookieHeader);
|
||||
},
|
||||
commitSession(session: Session, options?: Parameters<typeof appSessionStorage.commitSession>[1]) {
|
||||
return storageForSurface(sessionSurface.get(session) ?? "app").commitSession(session, options);
|
||||
},
|
||||
destroySession(session: Session, options?: Parameters<typeof appSessionStorage.destroySession>[1]) {
|
||||
return storageForSurface(sessionSurface.get(session) ?? "app").destroySession(session, options);
|
||||
},
|
||||
};
|
||||
|
||||
export function getUserSession(request: Request) {
|
||||
return storage.getSession(request.headers.get("Cookie"));
|
||||
return getSurfaceSession(surfaceForRequest(request), request.headers.get("Cookie"));
|
||||
}
|
||||
|
||||
export async function getUserInfo(request: Request): Promise<UserSession> {
|
||||
const session = await getUserSession(request);
|
||||
const userId = session.get("userId") ?? null;
|
||||
const storedUserId = session.get("userId") ?? null;
|
||||
const lightOrDarkMode = session.get("lightOrDarkMode") ?? "";
|
||||
const lng = ["de", "en"].includes(session.get("lng") ?? "") ? session.get("lng") : "de";
|
||||
const candidateLocale = normalizeLocaleCandidate(session.get("lng"));
|
||||
const lng = candidateLocale && webConfig.i18n.enabledLocales.includes(candidateLocale) ? candidateLocale : defaultLocale;
|
||||
const csrf = session.get("csrf");
|
||||
const metrics = session.get("metrics") ?? { enabled: false, logToConsole: false, saveToDatabase: false, ignoreUrls: [] };
|
||||
const cookies = session.get("cookies") ?? [];
|
||||
const impersonatingFromUserId = session.get("impersonatingFromUserId");
|
||||
const impersonatingFromAdminUserId = session.get("impersonatingFromAdminUserId");
|
||||
const impersonatingFromAdminEmail = session.get("impersonatingFromAdminEmail");
|
||||
const impersonatingStartedAt = session.get("impersonatingStartedAt");
|
||||
const impersonationValidation = validateImpersonationSessionState({ impersonatingFromUserId, impersonatingStartedAt, userId });
|
||||
const impersonationValidation = validateImpersonationSessionState({
|
||||
impersonatingFromUserId,
|
||||
impersonatingStartedAt,
|
||||
userId: storedUserId,
|
||||
});
|
||||
const legacyUserId = resolveEffectiveSessionUserId({
|
||||
userId: storedUserId,
|
||||
impersonatingFromUserId,
|
||||
impersonatingStartedAt,
|
||||
validation: impersonationValidation,
|
||||
});
|
||||
const hasAdminImpersonationMarker =
|
||||
typeof impersonatingFromAdminUserId === "string" ||
|
||||
typeof impersonatingFromAdminEmail === "string";
|
||||
const adminImpersonationValid = validateAdminImpersonationSessionState({
|
||||
impersonatingFromAdminUserId,
|
||||
impersonatingFromAdminEmail,
|
||||
impersonatingStartedAt,
|
||||
userId: storedUserId,
|
||||
});
|
||||
const userId = hasAdminImpersonationMarker ? (adminImpersonationValid ? storedUserId : null) : legacyUserId;
|
||||
const theme = session.get("theme");
|
||||
const passwordPolicyOutdated = session.get("passwordPolicyOutdated") === true;
|
||||
const sessionToken = session.get("sessionToken");
|
||||
const expectedSessionOwnerUserId = impersonationValidation.valid ? impersonationValidation.actorUserId : userId;
|
||||
const serverSessionValidation = expectedSessionOwnerUserId ? await validateServerSessionForRequest(request, sessionToken, expectedSessionOwnerUserId) : null;
|
||||
const authenticated = Boolean(userId && serverSessionValidation?.valid);
|
||||
const pendingMfaUserId = session.get(PENDING_MFA_USER_ID_KEY);
|
||||
const pendingMfaRedirectTo = session.get(PENDING_MFA_REDIRECT_KEY);
|
||||
const pendingMfaStartedAt = session.get(PENDING_MFA_STARTED_AT_KEY);
|
||||
const pendingMfaPrimaryMethod = session.get(PENDING_MFA_PRIMARY_METHOD_KEY);
|
||||
const pendingMfaFresh = isPendingMfaLoginFresh(pendingMfaStartedAt);
|
||||
return {
|
||||
userId,
|
||||
userId: (authenticated ? userId : null) as UserSession["userId"],
|
||||
lightOrDarkMode,
|
||||
lng,
|
||||
csrf,
|
||||
metrics,
|
||||
cookies,
|
||||
impersonatingFromUserId: impersonationValidation.valid ? impersonatingFromUserId : undefined,
|
||||
impersonatingStartedAt: impersonationValidation.valid ? impersonatingStartedAt : undefined,
|
||||
impersonatingFromUserId: authenticated && impersonationValidation.valid ? impersonatingFromUserId : undefined,
|
||||
impersonatingFromAdminUserId: authenticated && adminImpersonationValid ? impersonatingFromAdminUserId : undefined,
|
||||
impersonatingFromAdminEmail: authenticated && adminImpersonationValid ? impersonatingFromAdminEmail : undefined,
|
||||
impersonatingStartedAt: authenticated && (impersonationValidation.valid || adminImpersonationValid) ? impersonatingStartedAt : undefined,
|
||||
theme,
|
||||
passwordPolicyOutdated: passwordPolicyOutdated || undefined,
|
||||
sessionToken: typeof sessionToken === "string" ? sessionToken : undefined,
|
||||
pendingMfaUserId: typeof pendingMfaUserId === "string" ? pendingMfaUserId : undefined,
|
||||
pendingMfaRedirectTo: typeof pendingMfaRedirectTo === "string" ? pendingMfaRedirectTo : undefined,
|
||||
sessionToken: authenticated && typeof sessionToken === "string" ? sessionToken : undefined,
|
||||
pendingMfaUserId: pendingMfaFresh && typeof pendingMfaUserId === "string" ? pendingMfaUserId : undefined,
|
||||
pendingMfaRedirectTo: pendingMfaFresh && typeof pendingMfaRedirectTo === "string" ? pendingMfaRedirectTo : undefined,
|
||||
pendingMfaStartedAt: pendingMfaFresh ? pendingMfaStartedAt : undefined,
|
||||
pendingMfaPrimaryMethod: pendingMfaFresh && isPendingMfaPrimaryMethod(pendingMfaPrimaryMethod) ? pendingMfaPrimaryMethod : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getValidatedServerSession(request: Request, userInfo?: UserSession): Promise<ActiveServerSession | null> {
|
||||
const info = userInfo ?? (await getUserInfo(request));
|
||||
if (!info.userId || !info.sessionToken) {
|
||||
return null;
|
||||
}
|
||||
const expectedOwnerUserId = info.impersonatingFromUserId ?? info.userId;
|
||||
const validation = await validateServerSessionForRequest(request, info.sessionToken, expectedOwnerUserId);
|
||||
return validation.valid ? validation.session : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* D1 (2FA-Login-Gate) — schreibt den Pending-MFA-Zustand in das SIGNIERTE Session-Cookie und gibt
|
||||
* den Set-Cookie-String zurueck. Bewusst KEINE Session: `userId`/`sessionToken` werden entfernt,
|
||||
@@ -203,11 +404,16 @@ export async function getUserInfo(request: Request): Promise<UserSession> {
|
||||
* weiterverwendet, damit der bereits ausgehandelte `csrf`-Token erhalten bleibt und die Verify-Route
|
||||
* die CSRF-Pruefung besteht.
|
||||
*/
|
||||
export async function commitPendingMfaLoginCookie(request: Request, { userId, redirectTo }: { userId: string; redirectTo?: string }) {
|
||||
export async function commitPendingMfaLoginCookie(
|
||||
request: Request,
|
||||
{ userId, redirectTo, primaryMethod }: { userId: string; redirectTo?: string; primaryMethod: PendingMfaPrimaryMethod }
|
||||
) {
|
||||
const session = await getUserSession(request);
|
||||
session.unset("userId");
|
||||
session.unset("sessionToken");
|
||||
session.set(PENDING_MFA_USER_ID_KEY, userId);
|
||||
session.set(PENDING_MFA_STARTED_AT_KEY, new Date().toISOString());
|
||||
session.set(PENDING_MFA_PRIMARY_METHOD_KEY, primaryMethod);
|
||||
if (typeof redirectTo === "string" && redirectTo.length > 0) {
|
||||
session.set(PENDING_MFA_REDIRECT_KEY, redirectTo);
|
||||
} else {
|
||||
@@ -218,38 +424,16 @@ export async function commitPendingMfaLoginCookie(request: Request, { userId, re
|
||||
|
||||
export async function requireUserId(request: Request, redirectTo: string = new URL(request.url).pathname) {
|
||||
const session = await getUserSession(request);
|
||||
const userId = session.get("userId");
|
||||
if (!userId || typeof userId !== "string") {
|
||||
const storedUserId = session.get("userId");
|
||||
const hadAuthenticatedCookie = typeof storedUserId === "string" && storedUserId.length > 0;
|
||||
const userInfo = await getUserInfo(request);
|
||||
if (!userInfo.userId) {
|
||||
const searchParams = new URLSearchParams([["redirectTo", redirectTo]]);
|
||||
throw redirect(`/login?${searchParams}`);
|
||||
}
|
||||
await assertServerSessionNotRevoked(session, redirectTo);
|
||||
return userId;
|
||||
}
|
||||
|
||||
// R-P2a S4b — additive Revoke-Durchsetzung: traegt das Cookie einen serverseitigen Session-Token,
|
||||
// wird die UserSession-Zeile geprueft; ist sie revoked/abgelaufen, gilt der Nutzer als abgemeldet
|
||||
// (Cookie zerstoeren + zur Login-Seite). Fail-open: ein Store-Fehler meldet NICHT ab (ein DB-Blip
|
||||
// soll keinen Massen-Logout ausloesen). Alte Cookies ohne Token bleiben unberuehrt.
|
||||
async function assertServerSessionNotRevoked(session: Session, redirectTo: string) {
|
||||
const sessionToken = session.get("sessionToken");
|
||||
if (typeof sessionToken !== "string" || sessionToken.length === 0) {
|
||||
return;
|
||||
}
|
||||
let active = true;
|
||||
try {
|
||||
active = (await getActiveSessionByToken(sessionToken)) !== null;
|
||||
} catch (error) {
|
||||
sessionLogger.warn(
|
||||
{ op: "session.revokeCheck.failed", err: { name: error instanceof Error ? error.name : "Error" } },
|
||||
"Server-session revoke check raised; failing open (treating session as valid)."
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!active) {
|
||||
const searchParams = new URLSearchParams([["redirectTo", redirectTo]]);
|
||||
throw redirect(`/login?${searchParams}`, { headers: { "Set-Cookie": await storage.destroySession(session) } });
|
||||
throw redirect(`/login?${searchParams}`, {
|
||||
headers: hadAuthenticatedCookie ? { "Set-Cookie": await storage.destroySession(session) } : undefined,
|
||||
});
|
||||
}
|
||||
return userInfo.userId;
|
||||
}
|
||||
|
||||
export async function requireUser({ request }: { request: Request }) {
|
||||
@@ -267,7 +451,7 @@ export async function logout(request: Request) {
|
||||
// Geraet auch in der Geraeteliste verschwindet und der Token nicht weiterlebt.
|
||||
const sessionToken = session.get("sessionToken");
|
||||
if (typeof sessionToken === "string" && sessionToken.length > 0) {
|
||||
await endServerSession(sessionToken).catch((error: unknown) => {
|
||||
await endServerSession(sessionToken, request).catch((error: unknown) => {
|
||||
sessionLogger.warn(
|
||||
{ op: "session.logout.revokeFailed", err: { name: error instanceof Error ? error.name : "Error" } },
|
||||
"Logout could not revoke the server session row; cookie is destroyed regardless."
|
||||
@@ -281,26 +465,92 @@ export async function logout(request: Request) {
|
||||
});
|
||||
}
|
||||
|
||||
export async function createUserSession(userSession: UserSession, redirectTo: string = "") {
|
||||
const session = await storage.getSession();
|
||||
session.set("userId", userSession.userId);
|
||||
export type CreateUserSessionOptions = {
|
||||
request: Request;
|
||||
rotate?: boolean;
|
||||
adminAuthenticationMethods?: readonly string[];
|
||||
adminMfaAssuredAt?: Date;
|
||||
};
|
||||
|
||||
export async function createUserSession(userSession: UserSession, redirectTo: string, options: CreateUserSessionOptions) {
|
||||
const safeRedirectTo = safeSessionRedirectTarget(redirectTo, webConfig.routing);
|
||||
const session = await getSurfaceSession(surfaceForRequest(options.request));
|
||||
const impersonationValidation = validateImpersonationSessionState(userSession);
|
||||
const hasAdminImpersonationMarker =
|
||||
typeof userSession.impersonatingFromAdminUserId === "string" ||
|
||||
typeof userSession.impersonatingFromAdminEmail === "string";
|
||||
const adminImpersonationValid = validateAdminImpersonationSessionState(userSession);
|
||||
const effectiveUserId = resolveEffectiveSessionUserId({
|
||||
userId: userSession.userId,
|
||||
impersonatingFromUserId: userSession.impersonatingFromUserId,
|
||||
impersonatingStartedAt: userSession.impersonatingStartedAt,
|
||||
validation: impersonationValidation,
|
||||
});
|
||||
const finalEffectiveUserId = hasAdminImpersonationMarker ? (adminImpersonationValid ? userSession.userId : null) : effectiveUserId;
|
||||
if (finalEffectiveUserId) {
|
||||
session.set("userId", finalEffectiveUserId);
|
||||
} else {
|
||||
session.unset("userId");
|
||||
}
|
||||
const expectedSessionOwnerUserId = impersonationValidation.valid ? impersonationValidation.actorUserId : finalEffectiveUserId;
|
||||
let sessionToken: string | undefined;
|
||||
if (expectedSessionOwnerUserId) {
|
||||
if (options.rotate) {
|
||||
if (typeof userSession.sessionToken === "string" && userSession.sessionToken.length > 0) {
|
||||
await endServerSession(userSession.sessionToken, options.request);
|
||||
}
|
||||
sessionToken = await startServerSession({
|
||||
request: options.request,
|
||||
userId: expectedSessionOwnerUserId,
|
||||
...(options.adminAuthenticationMethods && options.adminMfaAssuredAt
|
||||
? {
|
||||
adminAuthenticationMethods: options.adminAuthenticationMethods,
|
||||
adminMfaAssuredAt: options.adminMfaAssuredAt,
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
} else if (typeof userSession.sessionToken === "string" && userSession.sessionToken.length > 0) {
|
||||
const validation = await validateServerSessionForRequest(options.request, userSession.sessionToken, expectedSessionOwnerUserId);
|
||||
if (!validation.valid) {
|
||||
throw new Error(`Cannot issue authenticated cookie from invalid server session: ${validation.reason}`);
|
||||
}
|
||||
sessionToken = userSession.sessionToken;
|
||||
} else {
|
||||
sessionToken = await startServerSession({
|
||||
request: options.request,
|
||||
userId: expectedSessionOwnerUserId,
|
||||
...(options.adminAuthenticationMethods && options.adminMfaAssuredAt
|
||||
? {
|
||||
adminAuthenticationMethods: options.adminAuthenticationMethods,
|
||||
adminMfaAssuredAt: options.adminMfaAssuredAt,
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
session.set("lightOrDarkMode", userSession.lightOrDarkMode);
|
||||
session.set("lng", userSession.lng);
|
||||
session.set("csrf", userSession.csrf);
|
||||
session.set("metrics", userSession.metrics);
|
||||
session.set("cookies", userSession.cookies);
|
||||
const impersonationValidation = validateImpersonationSessionState(userSession);
|
||||
session.set("impersonatingFromUserId", impersonationValidation.valid ? userSession.impersonatingFromUserId : undefined);
|
||||
session.set("impersonatingStartedAt", impersonationValidation.valid ? userSession.impersonatingStartedAt : undefined);
|
||||
session.set("impersonatingFromAdminUserId", adminImpersonationValid ? userSession.impersonatingFromAdminUserId : undefined);
|
||||
session.set("impersonatingFromAdminEmail", adminImpersonationValid ? userSession.impersonatingFromAdminEmail : undefined);
|
||||
session.set(
|
||||
"impersonatingStartedAt",
|
||||
impersonationValidation.valid || adminImpersonationValid ? userSession.impersonatingStartedAt : undefined
|
||||
);
|
||||
session.set("theme", userSession.theme);
|
||||
session.set("passwordPolicyOutdated", userSession.passwordPolicyOutdated === true ? true : undefined);
|
||||
session.set("sessionToken", userSession.sessionToken);
|
||||
session.set("sessionToken", sessionToken);
|
||||
// D1 — ein vollwertiger Login loescht den Pending-MFA-Zustand. createUserSession baut zwar ein
|
||||
// frisches Cookie (ohne diese Keys), das explizite Loeschen dokumentiert die Invariante und
|
||||
// schuetzt, falls hier kuenftig eine bestehende Session weiterverwendet wuerde.
|
||||
session.unset(PENDING_MFA_USER_ID_KEY);
|
||||
session.unset(PENDING_MFA_REDIRECT_KEY);
|
||||
return redirect(redirectTo, {
|
||||
session.unset(PENDING_MFA_STARTED_AT_KEY);
|
||||
session.unset(PENDING_MFA_PRIMARY_METHOD_KEY);
|
||||
return redirect(safeRedirectTo, {
|
||||
headers: {
|
||||
"Set-Cookie": await storage.commitSession(session),
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user