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

@@ -2,7 +2,7 @@
* Phase 09 Task #82 — PKCE / state / nonce challenge persistence.
*
* Stores the tuple { state, nonce, codeVerifier, createdAt } in an
* HMAC-signed HttpOnly cookie scoped to /auth/admin. The cookie is
* HMAC-signed HttpOnly cookie scoped to the dedicated admin host. The cookie is
* single-use: `consumeAdminSsoChallenge()` returns the payload and emits a
* `Set-Cookie` header that clears it.
*
@@ -17,12 +17,13 @@
* server-side (cookie Max-Age is best-effort; clients lie).
*/
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { loadRequiredWebConfig, resolveHostOnlyCookiePolicy } from "@hivegrid/config";
import { generators } from "openid-client";
export const ADMIN_SSO_CHALLENGE_COOKIE = "hivegrid_admin_sso_challenge";
export const ADMIN_SSO_CHALLENGE_COOKIE = "__Host-hivegrid_admin_sso_challenge";
export const LOCAL_ADMIN_SSO_CHALLENGE_COOKIE = "hivegrid_admin_sso_challenge";
export const ADMIN_SSO_CHALLENGE_TTL_MS = 10 * 60 * 1000;
const COOKIE_PATH = "/auth/admin";
const ADMIN_SSO_CHALLENGE_CLOCK_SKEW_MS = 60 * 1000;
const PAYLOAD_VERSION = "v1";
export type AdminSsoChallengePayload = {
@@ -58,6 +59,19 @@ function getSigningSecret(override?: string): string {
return secret;
}
function getCookiePolicy() {
const webConfig = loadRequiredWebConfig();
// `__Host-` requires Path=/. The dedicated admin hostname is the narrowest
// safe scope that preserves the browser-enforced no-Domain guarantee.
return resolveHostOnlyCookiePolicy({
nodeEnv: webConfig.nodeEnv,
routing: webConfig.routing,
secureName: ADMIN_SSO_CHALLENGE_COOKIE,
localName: LOCAL_ADMIN_SSO_CHALLENGE_COOKIE,
maxAge: Math.ceil(ADMIN_SSO_CHALLENGE_TTL_MS / 1000),
});
}
function base64UrlEncode(buf: Buffer | string): string {
const b = typeof buf === "string" ? Buffer.from(buf, "utf8") : buf;
return b.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
@@ -105,15 +119,9 @@ export function serializeAdminSsoChallengeCookie(payload: AdminSsoChallengePaylo
const body = base64UrlEncode(JSON.stringify({ v: PAYLOAD_VERSION, p: payload }));
const sig = sign(body, secret);
const value = `${body}.${sig}`;
const maxAgeSeconds = Math.ceil(ADMIN_SSO_CHALLENGE_TTL_MS / 1000);
const attributes = [
`${ADMIN_SSO_CHALLENGE_COOKIE}=${value}`,
`Path=${COOKIE_PATH}`,
"HttpOnly",
"SameSite=Lax",
`Max-Age=${maxAgeSeconds}`,
];
if (process.env.NODE_ENV !== "test") {
const policy = getCookiePolicy();
const attributes = [`${policy.name}=${value}`, `Path=${policy.path}`, "HttpOnly", "SameSite=Lax", `Max-Age=${policy.maxAge}`];
if (policy.secure) {
attributes.push("Secure");
}
return attributes.join("; ");
@@ -123,14 +131,9 @@ export function serializeAdminSsoChallengeCookie(payload: AdminSsoChallengePaylo
* Returns a `Set-Cookie` header that clears the challenge cookie.
*/
export function clearAdminSsoChallengeCookie(): string {
const attributes = [
`${ADMIN_SSO_CHALLENGE_COOKIE}=`,
`Path=${COOKIE_PATH}`,
"HttpOnly",
"SameSite=Lax",
"Max-Age=0",
];
if (process.env.NODE_ENV !== "test") {
const policy = getCookiePolicy();
const attributes = [`${policy.name}=`, `Path=${policy.path}`, "HttpOnly", "SameSite=Lax", "Max-Age=0"];
if (policy.secure) {
attributes.push("Secure");
}
return attributes.join("; ");
@@ -153,11 +156,14 @@ function readCookieValue(request: Request, name: string): string | null {
* Always returns a `clearCookie` header that the caller must include on
* the redirect response so the cookie cannot be replayed.
*/
export function consumeAdminSsoChallenge(
request: Request,
options: { now?: () => number; secret?: string } = {}
): ConsumeResult {
const value = readCookieValue(request, ADMIN_SSO_CHALLENGE_COOKIE);
export function consumeAdminSsoChallenge(request: Request, options: { now?: () => number; secret?: string } = {}): ConsumeResult {
let cookieName: string;
try {
cookieName = getCookiePolicy().name;
} catch {
return { ok: false, reason: "malformed" };
}
const value = readCookieValue(request, cookieName);
if (!value) return { ok: false, reason: "missing" };
const dot = value.lastIndexOf(".");
if (dot <= 0) return { ok: false, reason: "malformed" };
@@ -172,18 +178,48 @@ export function consumeAdminSsoChallenge(
if (!verifySignature(body, sig, secret)) {
return { ok: false, reason: "bad-signature" };
}
let decoded: { v: string; p: AdminSsoChallengePayload };
let decoded: { v?: unknown; p?: unknown };
try {
decoded = JSON.parse(base64UrlDecode(body).toString("utf8"));
decoded = JSON.parse(base64UrlDecode(body).toString("utf8")) as { v?: unknown; p?: unknown };
} catch {
return { ok: false, reason: "malformed" };
}
if (decoded.v !== PAYLOAD_VERSION || !decoded.p) {
if (decoded.v !== PAYLOAD_VERSION || !isAdminSsoChallengePayload(decoded.p)) {
return { ok: false, reason: "malformed" };
}
const now = options.now ? options.now() : Date.now();
if (typeof decoded.p.createdAt !== "number" || now - decoded.p.createdAt > ADMIN_SSO_CHALLENGE_TTL_MS) {
if (decoded.p.createdAt > now + ADMIN_SSO_CHALLENGE_CLOCK_SKEW_MS) {
return { ok: false, reason: "malformed" };
}
if (now - decoded.p.createdAt > ADMIN_SSO_CHALLENGE_TTL_MS) {
return { ok: false, reason: "expired" };
}
return { ok: true, payload: decoded.p, clearCookie: clearAdminSsoChallengeCookie() };
}
function isAdminSsoChallengePayload(value: unknown): value is AdminSsoChallengePayload {
if (!value || typeof value !== "object") {
return false;
}
const payload = value as Partial<Record<keyof AdminSsoChallengePayload, unknown>>;
if (
typeof payload.state !== "string" ||
!/^[0-9a-f]{64}$/.test(payload.state) ||
typeof payload.nonce !== "string" ||
!/^[0-9a-f]{64}$/.test(payload.nonce) ||
typeof payload.codeVerifier !== "string" ||
!/^[A-Za-z0-9._~-]{43,128}$/.test(payload.codeVerifier) ||
typeof payload.codeChallenge !== "string" ||
!/^[A-Za-z0-9_-]{43}$/.test(payload.codeChallenge) ||
typeof payload.createdAt !== "number" ||
!Number.isFinite(payload.createdAt) ||
(payload.returnTo !== undefined && typeof payload.returnTo !== "string")
) {
return false;
}
try {
return generators.codeChallenge(payload.codeVerifier) === payload.codeChallenge;
} catch {
return false;
}
}