import { getAppUrl, readEnv } from '../../app-config'; import { AppSettings } from '../../db/entities/AppSettings.entity'; import type { AppSettingsRepository } from '../../db/repositories/AppSettings.repository'; import { InjectRepository } from '@mikro-orm/nestjs'; import { Injectable, Logger } from '@nestjs/common'; function hostOf(url: string): string | null { try { return new URL(url).hostname || null; } catch { return null; } } /** WebAuthn RP IDs must be registrable domains — never bare IP literals. */ function isIpHost(host: string): boolean { if (/^\d{1,3}(\.\d{1,3}){3}$/.test(host)) return true; // IPv4 if (host.includes(':')) return true; // IPv6 (hostname keeps the colons) return false; } /** * An http(s) origin reduced to the scheme, host and port the browser reports * (`new URL(o).origin`), so a configured path, trailing slash or uppercase host * still matches. @simplewebauthn/server refuses such an expected origin * outright, where older releases only failed to match it. Any other scheme (an * app package origin) is kept as written. Null when the value does not parse. */ function normalizeOrigin(origin: string): string | null { let url: URL; try { url = new URL(origin); } catch { return null; } return url.protocol === 'http:' || url.protocol === 'https:' ? url.origin : origin; } /** * The scope rule WebAuthn itself applies when the browser runs a ceremony: the * origin's host must equal the RP ID or be a subdomain of it, over https * (plain http only for localhost loopback dev). Used to judge whether an * origin could ever complete a ceremony against a given RP ID — never to * derive the RP ID from anything request-controlled. */ export function originWithinRpScope(origin: string, rpID: string): boolean { let url: URL; try { url = new URL(origin); } catch { return false; } const host = url.hostname; const loopback = host === 'localhost' || host === '127.0.0.1'; if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) return false; return host === rpID || host.endsWith(`.${rpID}`); } export interface WebauthnConfig { rpID: string; rpName: string; /** Exact allowed origins (scheme + host + port). One in prod; localhost dev adds the Vite/API ports. */ origins: string[]; /** * True when `origins` came from operator config (env / admin setting) — such * a list is honored verbatim. False when derived from APP_URL, where the * scheme/port may not match the real browsing origin (TLS-terminating proxy) * and the verifier may widen within the RP ID's scope. */ explicitOrigins: boolean; } /** * Resolves the WebAuthn Relying Party ID + allowed origins for this deployment. * * SECURITY: the RP ID and the allowed origins are derived ONLY from server-side * configuration — the `webauthn_rp_id` / `webauthn_origins` admin settings (or * the matching env vars), falling back to APP_URL. They are NEVER taken from the * request `Host` / `X-Forwarded-Host` header: a forged forwarded host would * otherwise let an attacker bind credentials to a domain they control, or brick * every enrolled user. This mirrors how OIDC derives its redirect URI from * APP_URL (oidc.controller.ts) rather than from request input. * * Nothing is cached: `readEnv()` and the app-settings row are read on every * resolve so an operator flipping the RP ID at runtime takes effect on the next * ceremony instead of after a restart. */ @Injectable() export class WebauthnConfigService { private readonly logger = new Logger(WebauthnConfigService.name); constructor(@InjectRepository(AppSettings) private readonly appSettings: AppSettingsRepository) {} /** Normalizes every origin, dropping (and naming) the ones that do not parse. */ private normalizeOrigins(origins: string[]): string[] { const normalized: string[] = []; const unparseable: string[] = []; for (const origin of origins) { const value = normalizeOrigin(origin); if (value === null) unparseable.push(origin); else normalized.push(value); } if (unparseable.length > 0) { this.logger.warn(`Ignoring passkey origins that are not valid URLs: ${unparseable.join(', ')}`); } return Array.from(new Set(normalized)); } /** `SELECT value FROM app_settings WHERE key = ?` (WC1), through `AppSettingsRepository.getValue` (Plan 3a). */ private async setting(key: string): Promise { const raw = (await this.appSettings.getValue(key)) ?? undefined; const trimmed = raw?.trim(); return trimmed ? trimmed : null; } /** * Returns null when no usable RP ID can be resolved (bare IP host, or nothing * configured) — the feature then reports itself as "not configured" and stays * disabled so nobody can enrol a credential bound to the wrong origin. */ async resolve(): Promise { // 1. Explicit operator config always wins. Host names compare without case, // and the verifier refuses an RP ID that is not in its lower-case form. const explicitRpId = (readEnv().webauthn.rpId || (await this.setting('webauthn_rp_id')))?.trim().toLowerCase() || null; const configuredOrigins = (readEnv().webauthn.origins || (await this.setting('webauthn_origins')) || '') .split(',') // The lookbehind matches only the first slash of the trailing run. Without it the // engine retries from every slash, which is quadratic on a slash-heavy value. .map((o) => o.trim().replace(/(? 0; const appUrl = getAppUrl(); const appHost = hostOf(appUrl); // 2. Derive the RP ID from APP_URL when not explicitly set. let rpID = explicitRpId; if (!rpID && appHost && !isIpHost(appHost)) { rpID = appHost; // a real domain, or "localhost" } if (!rpID) return null; // bare IP / unresolved → WebAuthn cannot be used here // 3. Resolve the allowed origins. Explicit list wins (operator's // responsibility); a list whose every entry failed to parse stays explicit // and leaves the feature unconfigured rather than falling back to APP_URL. // Otherwise derive a SINGLE origin from APP_URL; we never silently union // dev localhost origins into a production allow-list. let origins = explicitOrigins; if (!hasExplicitOrigins) { if (appHost) origins = this.normalizeOrigins([appUrl.replace(/(? { return (await this.resolve()) !== null; } }