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,14 +1,17 @@
import { createHash, randomBytes } from "node:crypto";
import { createCookie } from "react-router";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { loadRequiredWebConfig, resolveHostOnlyCookiePolicy } from "@hivegrid/config";
import { db } from "~/utils/db.server";
import { buildSessionDeviceContext } from "~/services/auth/sessionLifecycle.server";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { resolveTrustedDeviceRlsIdentity } from "@hivegrid/db/rls-resolvers.server";
// The trust-device marker survives logout, stays revocable via TrustedDevice,
// and stores only the SHA-256 hash of the opaque cookie token in the database.
export const TRUSTED_DEVICE_COOKIE_NAME = "hivegrid_trusted_device";
export const TRUSTED_DEVICE_MAX_AGE_SECONDS = 60 * 60 * 24 * 30; // 30 Tage
export const TRUSTED_DEVICE_COOKIE_NAME = "__Host-hivegrid_trusted_device";
export const LOCAL_TRUSTED_DEVICE_COOKIE_NAME = "hivegrid_trusted_device";
export const TRUSTED_DEVICE_MAX_AGE_SECONDS = 60 * 60 * 24 * 30; // 30 days
const TRUSTED_DEVICE_TOKEN_BYTES = 32;
const TOUCH_THROTTLE_MS = 5 * 60 * 1000; // throttle lastUsedAt updates to every 5 minutes
@@ -21,12 +24,19 @@ function getTrustedDeviceCookie() {
return cachedCookie;
}
const webConfig = loadRequiredWebConfig();
cachedCookie = createCookie(TRUSTED_DEVICE_COOKIE_NAME, {
httpOnly: true,
sameSite: "lax",
path: "/",
secure: webConfig.nodeEnv === "production",
const policy = resolveHostOnlyCookiePolicy({
nodeEnv: webConfig.nodeEnv,
routing: webConfig.routing,
secureName: TRUSTED_DEVICE_COOKIE_NAME,
localName: LOCAL_TRUSTED_DEVICE_COOKIE_NAME,
maxAge: TRUSTED_DEVICE_MAX_AGE_SECONDS,
});
cachedCookie = createCookie(policy.name, {
httpOnly: policy.httpOnly,
sameSite: policy.sameSite,
path: policy.path,
secure: policy.secure,
maxAge: policy.maxAge,
secrets: webConfig.sessionSecret ? [webConfig.sessionSecret] : [],
});
return cachedCookie;
@@ -54,10 +64,14 @@ async function readRawTokenFromCookie(request: Request): Promise<string | null>
}
/**
* Markiert das aktuelle Geraet fuer `userId` als vertrauenswuerdig: legt die Tabellen-Zeile mit
* (pseudonymisiertem) Geraete-Kontext an und gibt den Set-Cookie-String mit dem rohen Token zurueck.
* Marks the current device as trusted for `userId`, persists only the
* pseudonymized device context, and returns the raw token in a Set-Cookie value.
*/
export async function rememberDeviceForUser({ request, userId, now = new Date() }: { request: Request; userId: string; now?: Date }): Promise<string> {
return withUserRlsContext(userId, () => rememberDeviceForUserScoped({ request, userId, now }));
}
async function rememberDeviceForUserScoped({ request, userId, now }: { request: Request; userId: string; now: Date }): Promise<string> {
const rawToken = generateTrustedDeviceToken();
const context = await buildSessionDeviceContext(request);
await db.trustedDevice.create({
@@ -74,11 +88,14 @@ export async function rememberDeviceForUser({ request, userId, now = new Date()
}
/**
* Prueft, ob der Request ein vertrauenswuerdiges Geraet fuer `userId` traegt: Cookie-Token -> Hash ->
* aktive Tabellen-Zeile mit passender userId. Best-effort: jeder Fehler gilt als "nicht vertraut".
* Schreibt lastUsedAt gedrosselt fort.
* Resolves the cookie token to an active row owned by `userId`. This is
* best-effort and fail-closed; `lastUsedAt` writes are throttled.
*/
export async function isTrustedDevice(request: Request, userId: string, now: Date = new Date()): Promise<boolean> {
return withUserRlsContext(userId, () => isTrustedDeviceScoped(request, userId, now));
}
async function isTrustedDeviceScoped(request: Request, userId: string, now: Date): Promise<boolean> {
try {
const rawToken = await readRawTokenFromCookie(request);
if (!rawToken) {
@@ -97,50 +114,69 @@ export async function isTrustedDevice(request: Request, userId: string, now: Dat
}
}
/** Aktive vertrauenswuerdige Geraete eines Nutzers (Geraete-Liste in Settings > Sicherheit). */
/** Lists active trusted devices for the security settings screen. */
export async function listTrustedDevices(userId: string): Promise<TrustedDeviceRow[]> {
return db.trustedDevice.findMany({
where: { userId, revokedAt: null, expiresAt: { gt: new Date() } },
orderBy: { lastUsedAt: "desc" },
});
return withUserRlsContext(userId, () =>
db.trustedDevice.findMany({
where: { userId, revokedAt: null, expiresAt: { gt: new Date() } },
orderBy: { lastUsedAt: "desc" },
}),
);
}
/** Widerruft genau ein eigenes vertrauenswuerdiges Geraet (Eigentuemerschaft ueber userId gesichert). */
/** Revokes one trusted device after enforcing user ownership in the query. */
export async function revokeTrustedDevice({ userId, deviceId }: { userId: string; deviceId: string }): Promise<boolean> {
const result = await db.trustedDevice.updateMany({
where: { id: deviceId, userId, revokedAt: null },
data: { revokedAt: new Date() },
return withUserRlsContext(userId, async () => {
const result = await db.trustedDevice.updateMany({
where: { id: deviceId, userId, revokedAt: null },
data: { revokedAt: new Date() },
});
return result.count > 0;
});
return result.count > 0;
}
/** "Alle Geraete vergessen": widerruft alle aktiven Trust-Marker des Nutzers. */
/** Revokes every active trusted-device marker owned by the user. */
export async function revokeAllTrustedDevices(userId: string): Promise<number> {
const result = await db.trustedDevice.updateMany({
where: { userId, revokedAt: null },
data: { revokedAt: new Date() },
return withUserRlsContext(userId, async () => {
const result = await db.trustedDevice.updateMany({
where: { userId, revokedAt: null },
data: { revokedAt: new Date() },
});
return result.count;
});
return result.count;
}
/**
* Vergisst das aktuelle Geraet: widerruft die zum Cookie gehoerende Zeile (falls vorhanden) und gibt
* den Set-Cookie-String zurueck, der den Trust-Marker im Browser loescht.
*/
/** Revokes the current marker, if present, and clears its browser cookie. */
export async function forgetCurrentTrustedDevice(request: Request): Promise<string> {
const rawToken = await readRawTokenFromCookie(request);
if (rawToken) {
await db.trustedDevice.updateMany({ where: { tokenHash: hashTrustedDeviceToken(rawToken), revokedAt: null }, data: { revokedAt: new Date() } }).catch(() => undefined);
const tokenHash = hashTrustedDeviceToken(rawToken);
const identity = await resolveTrustedDeviceRlsIdentity(tokenHash).catch(() => null);
if (identity) {
await runWithRlsContext({ userId: identity.userId }, () =>
db.trustedDevice.updateMany({
where: { id: identity.resourceId, tokenHash, userId: identity.userId, revokedAt: null },
data: { revokedAt: new Date() },
}),
).catch(() => undefined);
}
}
return clearTrustedDeviceCookie();
}
/** Set-Cookie-String, der den Trust-Marker im Browser loescht (ohne DB-Zugriff). */
/** Returns a Set-Cookie value that clears the marker without a database read. */
export async function clearTrustedDeviceCookie(): Promise<string> {
return getTrustedDeviceCookie().serialize("", { maxAge: 0, expires: new Date(0) });
}
/** Test-Naht: erzwingt eine Neuauflage des Cookies (z.B. nach geaenderter Config im Test). */
/** Test seam for rebuilding the cookie after configuration changes. */
export function __resetTrustedDeviceCookieForTests() {
cachedCookie = null;
}
function withUserRlsContext<T>(userId: string, operation: () => T): T {
if (getRlsExecutionContext()?.userId) {
return operation();
}
return runWithRlsContext({ userId }, operation);
}