Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -1,7 +1,9 @@
import { createHash, randomBytes } from "node:crypto";
import { cachified, clearCacheKey } from "~/utils/cache.server";
import { clearCacheKey } from "~/utils/cache.server";
import { db } from "~/utils/db.server";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { resolveUserSessionRlsIdentity } from "@hivegrid/db/rls-resolvers.server";
// R-P2a S4 — serverseitige Sessions. Postgres ist Source-of-Truth (Tabelle UserSession),
// davor ein kurzlebiger Cache (LRU heute, Redis-swappable per cache.server, AD-4). Das
@@ -9,10 +11,25 @@ import { db } from "~/utils/db.server";
const SESSION_TOKEN_BYTES = 32;
const DEFAULT_SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 Tage, deckt das Cookie-Max-Age
const SESSION_CACHE_TTL_MS = 60 * 1000; // kurzer Cache vor dem Postgres-SoT
const TOUCH_THROTTLE_MS = 5 * 60 * 1000; // lastSeenAt hoechstens alle 5min fortschreiben
export type UserSessionRow = Awaited<ReturnType<typeof db.userSession.create>>;
export type ActiveUserSessionOwner = {
id: string;
email: string;
firstName: string;
lastName: string;
avatar: string | null;
phone: string | null;
defaultTenantId: string | null;
createdAt: Date;
locale: string | null;
lightOrDarkMode: string | null;
active: boolean;
pendingDeletion: boolean;
pseudonymized: boolean;
};
export type ActiveUserSessionRow = UserSessionRow & { user: ActiveUserSessionOwner };
type Identified = { userId: string; sessionId: string };
@@ -47,13 +64,18 @@ export type CreateSessionInput = {
};
export async function createUserSession(input: CreateSessionInput): Promise<{ session: UserSessionRow; rawToken: string }> {
return withUserRlsContext(input.userId, () => createUserSessionScoped(input));
}
async function createUserSessionScoped(input: CreateSessionInput): Promise<{ session: UserSessionRow; rawToken: string }> {
const rawToken = input.rawToken ?? generateSessionToken();
const now = Date.now();
const expiresAt = input.expiresAt ?? new Date(now + DEFAULT_SESSION_TTL_MS);
const session = await db.userSession.create({
data: {
userId: input.userId,
tokenHash: hashSessionToken(rawToken),
expiresAt: input.expiresAt ?? new Date(now + DEFAULT_SESSION_TTL_MS),
expiresAt,
ipHash: input.ipHash ?? null,
userAgent: input.userAgent ?? null,
deviceLabel: input.deviceLabel ?? null,
@@ -65,22 +87,52 @@ export async function createUserSession(input: CreateSessionInput): Promise<{ se
return { session, rawToken };
}
// Liefert die aktive Session zum Cookie-Token oder null (revoked/abgelaufen/unbekannt). Der
// Cache wird bei Revoke gezielt invalidiert; die Ablauf-Pruefung laeuft zusaetzlich live gegen now.
export async function getActiveSessionByToken(rawToken: string | undefined | null): Promise<UserSessionRow | null> {
// Authorization reads always hit the source of truth. Positive cross-request
// caching would leave revoked sessions usable until the cache TTL elapsed.
export async function getActiveSessionByToken(rawToken: string | undefined | null): Promise<ActiveUserSessionRow | null> {
if (!rawToken) {
return null;
}
const tokenHash = hashSessionToken(rawToken);
const session = await cachified<UserSessionRow | null>({
key: sessionCacheKey(tokenHash),
ttl: SESSION_CACHE_TTL_MS,
getFreshValue: async () => db.userSession.findUnique({ where: { tokenHash } }),
});
if (!isActive(session)) {
const identity = await resolveUserSessionRlsIdentity(tokenHash);
if (!identity) {
return null;
}
return session;
return runWithRlsContext({ userId: identity.userId }, () => getActiveSessionByTokenScoped(tokenHash, identity.resourceId));
}
async function getActiveSessionByTokenScoped(tokenHash: string, expectedSessionId: string): Promise<ActiveUserSessionRow | null> {
const session = await db.userSession.findUnique({
where: { tokenHash },
include: {
user: {
select: {
id: true,
email: true,
firstName: true,
lastName: true,
avatar: true,
phone: true,
defaultTenantId: true,
createdAt: true,
locale: true,
lightOrDarkMode: true,
active: true,
pendingDeletion: true,
pseudonymized: true,
},
},
},
});
if (!session || session.id !== expectedSessionId || !isActive(session)) {
return null;
}
// Existing sessions must stop authorizing immediately when the account is
// disabled, enters deletion, or has already been pseudonymized.
if (!session.user.active || session.user.pendingDeletion || session.user.pseudonymized) {
return null;
}
return session as ActiveUserSessionRow;
}
// Schreibt lastSeenAt fort, aber gedrosselt (hoechstens alle TOUCH_THROTTLE_MS), um den
@@ -95,15 +147,21 @@ export async function touchSession(session: Pick<UserSessionRow, "id" | "lastSee
}
export async function listActiveUserSessions(userId: string): Promise<UserSessionRow[]> {
return db.userSession.findMany({
where: { userId, revokedAt: null, expiresAt: { gt: new Date() } },
orderBy: { lastSeenAt: "desc" },
});
return withUserRlsContext(userId, () =>
db.userSession.findMany({
where: { userId, revokedAt: null, expiresAt: { gt: new Date() } },
orderBy: { lastSeenAt: "desc" },
}),
);
}
// Revoke einzeln (Geraete-Liste). Verifiziert die Eigentuemerschaft ueber userId, damit ein
// Nutzer nur eigene Sessions beenden kann, und invalidiert den Cache.
export async function revokeUserSession({ userId, sessionId }: Identified): Promise<boolean> {
return withUserRlsContext(userId, () => revokeUserSessionScoped({ userId, sessionId }));
}
async function revokeUserSessionScoped({ userId, sessionId }: Identified): Promise<boolean> {
const session = await db.userSession.findFirst({ where: { id: sessionId, userId }, select: { id: true, tokenHash: true, revokedAt: true } });
if (!session || session.revokedAt !== null) {
return false;
@@ -115,6 +173,10 @@ export async function revokeUserSession({ userId, sessionId }: Identified): Prom
// "Ueberall abmelden": alle aktiven Sessions des Nutzers ausser der aktuellen beenden.
export async function revokeAllUserSessionsExcept({ userId, sessionId }: Identified): Promise<number> {
return withUserRlsContext(userId, () => revokeAllUserSessionsExceptScoped({ userId, sessionId }));
}
async function revokeAllUserSessionsExceptScoped({ userId, sessionId }: Identified): Promise<number> {
const sessions = await db.userSession.findMany({
where: { userId, revokedAt: null, id: { not: sessionId } },
select: { id: true, tokenHash: true },
@@ -133,14 +195,46 @@ export async function revokeAllUserSessionsExcept({ userId, sessionId }: Identif
return sessions.length;
}
// Used when an external identity loses an allowed group. Revoking every
// server-side row makes the decision visible to all web replicas immediately.
export async function revokeAllUserSessionsForUser(userId: string): Promise<number> {
return withUserRlsContext(userId, () => revokeAllUserSessionsForUserScoped(userId));
}
async function revokeAllUserSessionsForUserScoped(userId: string): Promise<number> {
const sessions = await db.userSession.findMany({
where: { userId, revokedAt: null, expiresAt: { gt: new Date() } },
select: { tokenHash: true },
});
if (sessions.length === 0) {
return 0;
}
const result = await db.userSession.updateMany({
where: { userId, revokedAt: null, expiresAt: { gt: new Date() } },
data: { revokedAt: new Date() },
});
for (const session of sessions) {
clearCacheKey(sessionCacheKey(session.tokenHash));
}
return result.count;
}
// Revoke ueber den Cookie-Token (Logout): beendet genau die aktuelle Session.
export async function revokeSessionByToken(rawToken: string | undefined | null): Promise<boolean> {
if (!rawToken) {
return false;
}
const tokenHash = hashSessionToken(rawToken);
const identity = await resolveUserSessionRlsIdentity(tokenHash);
if (!identity) {
return false;
}
return runWithRlsContext({ userId: identity.userId }, () => revokeSessionByTokenScoped(tokenHash, identity.resourceId));
}
async function revokeSessionByTokenScoped(tokenHash: string, expectedSessionId: string): Promise<boolean> {
const session = await db.userSession.findUnique({ where: { tokenHash }, select: { id: true, revokedAt: true } });
if (!session || session.revokedAt !== null) {
if (!session || session.id !== expectedSessionId || session.revokedAt !== null) {
return false;
}
await db.userSession.update({ where: { id: session.id }, data: { revokedAt: new Date() } });
@@ -150,9 +244,18 @@ export async function revokeSessionByToken(rawToken: string | undefined | null):
// Trust-Device (S5/2FA): markiert eine eigene Session als vertrauenswuerdig.
export async function markSessionTrusted({ userId, sessionId }: Identified): Promise<boolean> {
const result = await db.userSession.updateMany({
where: { id: sessionId, userId, revokedAt: null },
data: { trustedAt: new Date() },
return withUserRlsContext(userId, async () => {
const result = await db.userSession.updateMany({
where: { id: sessionId, userId, revokedAt: null },
data: { trustedAt: new Date() },
});
return result.count > 0;
});
return result.count > 0;
}
function withUserRlsContext<T>(userId: string, operation: () => T): T {
if (getRlsExecutionContext()?.userId) {
return operation();
}
return runWithRlsContext({ userId }, operation);
}