import type { AuthenticationConfigProvider, AuthMode } from "./types.js"; import type { LocalUserRegistry } from "./local-registry.js"; import { OidcIssuerMismatchError, OidcJwksUnavailableError, type OidcProtocol } from "./oidc-client.js"; import { createPosixAuthStorageBridge, createWindowsAuthStorageBridge, type WindowsAuthStorageBridge, } from "./windows-auth-storage.js"; import { isUsableAuthenticationSecret, type AuthenticationSecretReference } from "./secret-policy.js"; import type { AuthDiagnostic, AuthDiagnosticCode, AuthDiagnostics, GroupCatalog } from "./group-catalog.js"; export type { AuthDiagnostic, AuthDiagnosticCode, AuthDiagnostics } from "./group-catalog.js"; const LIVE_DIAGNOSTIC_TIMEOUT_MS = 30_000; export interface AuthDiagnoser { inspect(options: { live: boolean; interactive?: boolean; signal?: AbortSignal; /** Device-code presentation is transient operator output, never persisted diagnostic state. */ presentDeviceCode?: (uri: string, code: string) => void; }): Promise; } export interface AuthDiagnoserDependencies { authMode: AuthMode; authStateRoot: string; /** Platform integrations may inject an equivalent side-effect-free owner/ACL validator. */ sessionRootValidator?: (root: string) => void | Promise; windowsStorageBridge?: Pick; posixStorageBridge?: Pick; authentication?: AuthenticationConfigProvider; secrets?: ReadonlyMap; localUserRegistry?: LocalUserRegistry; oidcProtocol?: OidcProtocol; groupCatalog?: GroupCatalog; } function check(code: AuthDiagnosticCode, message: string, field?: string): AuthDiagnostic { return { level: "error", code, message, ...(field === undefined ? {} : { field }) }; } function ordered(checks: readonly AuthDiagnostic[]): readonly AuthDiagnostic[] { const unique = new Map(); for (const item of checks) unique.set(`${item.code}\u0000${item.field ?? ""}`, item); return [...unique.values()].sort((left, right) => { const leftKey = `${left.code}\u0000${left.field ?? ""}`; const rightKey = `${right.code}\u0000${right.field ?? ""}`; return leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : 0; }); } function stableCompare(left: string, right: string): number { return left < right ? -1 : left > right ? 1 : 0; } function abortReason(signal: AbortSignal): unknown { return signal.reason ?? new DOMException("The operation was aborted", "AbortError"); } function awaitWithAbort(operation: Promise, signal: AbortSignal): Promise { return new Promise((resolve, reject) => { let settled = false; const abort = () => { if (settled) return; settled = true; signal.removeEventListener("abort", abort); reject(abortReason(signal)); }; if (signal.aborted) abort(); else signal.addEventListener("abort", abort, { once: true }); operation.then( (value) => { if (settled) return; settled = true; signal.removeEventListener("abort", abort); resolve(value); }, (error: unknown) => { if (settled) return; settled = true; signal.removeEventListener("abort", abort); reject(error); }, ); }); } function startBeforeAbort(signal: AbortSignal, operation: () => Promise): Promise { return Promise.resolve().then(() => { if (signal.aborted) throw abortReason(signal); return operation(); }); } async function localRegistryIsUsable(deps: AuthDiagnoserDependencies): Promise { try { if (!deps.localUserRegistry) { return check("local_user_registry_invalid", "The local user registry is unavailable."); } if (!await deps.localUserRegistry.hasEnabledAdmin()) { return check("local_admin_missing", "No enabled local administrator is configured."); } return undefined; } catch { return check("local_user_registry_invalid", "The local user registry is invalid."); } } export function createAuthDiagnoser(deps: AuthDiagnoserDependencies): AuthDiagnoser { const validateSessionRoot = deps.sessionRootValidator ?? (process.platform === "win32" ? (root: string) => (deps.windowsStorageBridge ?? createWindowsAuthStorageBridge()).validateRoot(root) : (root: string) => (deps.posixStorageBridge ?? createPosixAuthStorageBridge()).validateRoot(root)); return { async inspect(options): Promise { const checks: AuthDiagnostic[] = []; const signal = options.signal ?? new AbortController().signal; try { await validateSessionRoot(deps.authStateRoot); } catch { checks.push(check("auth_session_store_invalid", "The authentication session store is invalid.")); } if (deps.authMode === "none" || deps.authMode === "mock") { const result = ordered(checks); return result.length === 0 ? { ready: true, mode: deps.authMode, checks: [{ level: "info", code: "auth_ready", message: "Authentication is ready." }] } : { ready: false, mode: deps.authMode, checks: result }; } if (deps.authMode === "upstream") { const result = ordered(checks); return result.length === 0 ? { ready: true, mode: "upstream", checks: [{ level: "info", code: "auth_ready", message: "Authentication is ready." }], } : { ready: false, mode: "upstream", checks: result }; } let loaded; try { if (!deps.authentication) throw new Error("missing authentication configuration"); loaded = deps.authentication.current(); } catch { checks.push(check(deps.authentication ? "auth_config_invalid" : "auth_config_incomplete", "Authentication configuration is unavailable.")); return { ready: false, mode: deps.authMode, checks: ordered(checks) }; } if (loaded.value.mode !== deps.authMode) { checks.push(check("auth_config_invalid", "Authentication mode does not match its configuration.")); return { ready: false, mode: deps.authMode, checks: ordered(checks) }; } if (loaded.value.mode === "local") { const local = await localRegistryIsUsable(deps); if (local) checks.push(local); const result = ordered(checks); return result.length === 0 ? { ready: true, mode: "local", checks: [{ level: "info", code: "auth_ready", message: "Authentication is ready." }] } : { ready: false, mode: "local", checks: result }; } const requiredSecrets: readonly AuthenticationSecretReference[] = ["THT_OIDC_CLIENT_SECRET", "THT_AUTHENTIK_API_TOKEN"]; if (requiredSecrets.some((name) => !isUsableAuthenticationSecret(name, deps.secrets?.get(name)))) { checks.push(check("oidc_secret_missing", "A required OIDC or group catalog secret is unavailable.")); } if (!options.live || checks.length > 0) { const result = ordered(checks); return result.length === 0 ? { ready: true, mode: "oidc", checks: [{ level: "info", code: "auth_ready", message: "Authentication is ready." }] } : { ready: false, mode: "oidc", checks: result }; } const mappedGroupNames = Object.keys(loaded.value.authorization.groupRoles).sort(stableCompare); const deadline = new AbortController(); const deadlineTimer = setTimeout(() => deadline.abort(), LIVE_DIAGNOSTIC_TIMEOUT_MS); deadlineTimer.unref(); const liveSignal = AbortSignal.any([signal, deadline.signal]); try { if (!deps.oidcProtocol) { checks.push(check("oidc_discovery_unreachable", "The OIDC provider is unavailable.")); } else { try { await awaitWithAbort(startBeforeAbort(liveSignal, () => deps.oidcProtocol!.diagnose(liveSignal)), liveSignal); } catch (error) { checks.push(check( error instanceof OidcIssuerMismatchError ? "oidc_issuer_mismatch" : error instanceof OidcJwksUnavailableError ? "oidc_jwks_unreachable" : "oidc_discovery_unreachable", "The OIDC provider could not be validated.", )); } } if (!liveSignal.aborted) { if (!deps.groupCatalog) { checks.push(check("oidc_group_catalog_unreachable", "The configured group catalog cannot be certified.")); } else { try { checks.push(...await awaitWithAbort(startBeforeAbort(liveSignal, () => deps.groupCatalog!.verifyConfiguredGroups( mappedGroupNames, liveSignal, )), liveSignal)); } catch { checks.push(check("oidc_group_catalog_unreachable", "The configured group catalog is unavailable.")); } } } } finally { clearTimeout(deadlineTimer); } const result = ordered(checks); return result.length === 0 ? { ready: true, mode: "oidc", checks: [{ level: "info", code: "auth_ready", message: "Authentication is ready." }] } : { ready: false, mode: "oidc", checks: result }; }, }; }