<?php

declare(strict_types=1);

/**
 * webauthn_bootstrap.php — Wires up the WebAuthn (passkey) subsystem,
 * consistent with how functions.php exposes a shared $db instance
 * elsewhere in this codebase.
 *
 * Relying Party ID: derived from the CURRENT request's Host header at
 * construction time, NOT hardcoded, because every panel installation is
 * self-hosted on a different customer domain (see includes/functions.php's
 * HTTPS-enforcement redirect for the same $_SERVER['HTTP_HOST']-based
 * pattern already used elsewhere in this codebase). WebAuthn credentials
 * are bound to the domain they were registered on; if a customer changes
 * domains, existing passkeys stop working and must be re-registered —
 * this is a WebAuthn platform limitation, not something this bootstrap
 * can work around.
 *
 * Included from includes/functions.php. Safe to include multiple times
 * (guarded).
 */

if (isset($webAuthn)) {
    return;
}

require_once __DIR__ . '/vendor/lbuchs-webauthn/src/WebAuthn.php';

use lbuchs\WebAuthn\WebAuthn;

$webAuthnRpId = (string) ($_SERVER['HTTP_HOST'] ?? 'localhost');
// Strip a port if present (e.g. "localhost:8888") — RP ID must be a bare
// domain, no scheme/port, per the WebAuthn spec.
if (str_contains($webAuthnRpId, ':')) {
    $webAuthnRpId = (string) strtok($webAuthnRpId, ':');
}

$webAuthnRpName = (string) ($config_ini['titles']['panel_name'] ?? 'IPTV Panel');

// 'none' attestation only: this is a self-service admin login for a
// single-operator panel, not a scenario requiring hardware-authenticity
// proof — the operator IS the trust root here, same as the existing
// password. Also keeps the registration ceremony fast and avoids
// bundling root CA certificate bundles for the other attestation formats.
$webAuthn = new WebAuthn($webAuthnRpName, $webAuthnRpId, ['none']);
