<?php
// =============================================================================
// POST /api/guard/bootstrap — hidden DEX PanelBootstrap path (dormant in
// IBO Ultra but supported here so future builds work without code changes).
//
// Request body (application/x-www-form-urlencoded):
//   pkg, c (cert hex), b (bootstrap build_id), t (ts), n (nonce hex),
//   s = HMAC-SHA256(bootstrap_auth_key, t.n.b).hex()
//
// Response (JSON):
//   { "payload": "<hex>" }
//
// Where payload = bin2hex(iv(16) || AES-256-CBC(K, iv).encrypt(pad(json)))
//       K       = HMAC-SHA256(bootstrap_auth_key, nonce).digest()   (32 B)
//       json    = {"u": "<panel_base_url>"}
//
// The client decrypts payload and uses "u" as the panel base URL (overrides
// the encrypted Guard.ns() constant if non-null).
// =============================================================================

require_once __DIR__ . '/../../includes/client_common.php';

require_method('POST');

// Accept both form-encoded (the production path) and JSON (for testers).
$pkg = $_POST['pkg'] ?? '';
$c   = $_POST['c']   ?? '';
$b   = $_POST['b']   ?? '';
$t   = $_POST['t']   ?? '';
$n   = $_POST['n']   ?? '';
$s   = $_POST['s']   ?? '';
if ($pkg === '' && $c === '') {
    $body = json_request_body();
    $pkg = $body['pkg'] ?? '';  $c = $body['c'] ?? '';  $b = $body['b'] ?? '';
    $t   = $body['t']   ?? '';  $n = $body['n'] ?? '';  $s = $body['s'] ?? '';
}

$cfg = db_config();
$boot_key_hex = (string)($cfg['bootstrap_auth_key_hex'] ?? '');
$boot_bid     = (string)($cfg['bootstrap_build_id']     ?? '');
$panel_url    = (string)($cfg['panel_base_url']         ?? '');

if ($boot_key_hex === '' || strlen($boot_key_hex) !== 32) {
    // The dormant hidden-DEX bootstrap path isn't enabled in this build.
    // Return a clean 404 instead of leaking config-state via a 500.
    json_error('not found', 404);
}
if ($panel_url === '') {
    // Auto-derive: same host + path the request came in on, minus /api/guard/bootstrap
    $scheme   = (!empty($_SERVER['HTTPS']) ? 'https' : 'http');
    $host     = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $base     = rtrim(dirname(dirname(dirname($_SERVER['SCRIPT_NAME']))), '/');
    $panel_url = $scheme . '://' . $host . $base;
}

$boot_key_raw = @hex2bin($boot_key_hex);
if ($boot_key_raw === false) {
    panel_log_write([
        'level'   => 'error',
        'message' => 'bootstrap_auth_key_hex is malformed (not valid hex)',
        'context' => ['len' => strlen($boot_key_hex)],
    ]);
    json_error('not found', 404);
}

$valid = bootstrap_verify_signature($boot_key_raw, (string)$t, (string)$n, (string)$b, (string)$s) ? 1 : 0;
// Same soft-validate policy as /api/guard/key — log but don't reject.

try {
    $payload_hex = bootstrap_encrypt_payload($boot_key_raw, (string)$n, ['u' => $panel_url]);
} catch (Throwable $e) {
    panel_log_exception($e, ['endpoint' => 'guard/bootstrap', 'pkg' => $pkg]);
    json_error('not found', 404);
}

db_exec(
    'INSERT INTO bootstrap_log (req_pkg, req_cert, req_ts, req_nonce, req_s, req_s_valid,
                                resp_payload_hex, ip_address)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
    [$pkg, $c, (int)$t, $n, $s, $valid, $payload_hex, client_ip()]
);
client_log_prune_table('bootstrap_log');

json_response(['payload' => $payload_hex]);
