<?php  declare(strict_types=1); require_once __DIR__ . '/../system/init.php'; App::apiHeaders(); App::requirePost(); $body = App::jsonBody(); if (!$body) { App::err('Invalid JSON', 400); } $route = $body['route'] ?? $_POST['route'] ?? ''; if (empty($route) && isset($body['action'])) { $legacyAction = $body['action']; $legacyMap = [ 'telemetry' => 'telemetry.legacy_telemetry', 'watchdog' => 'telemetry.watchdog', 'login' => 'auth.login', 'get_wallets' => 'crypto.get_wallets', 'track_order' => 'order.track', ]; if (isset($legacyMap[$legacyAction])) { $route = $legacyMap[$legacyAction]; $body['route'] = $route; } } $parts = explode('.', $route, 2); $group = $parts[0] ?? ''; $action = $parts[1] ?? ''; $map = [ 'auth' => __DIR__ . '/handlers/auth.handler.php', 'account' => __DIR__ . '/handlers/account.handler.php', 'checkout' => __DIR__ . '/handlers/checkout.handler.php', 'order' => __DIR__ . '/handlers/order.handler.php', 'product' => __DIR__ . '/handlers/product.handler.php', 'review' => __DIR__ . '/handlers/review.handler.php', 'support' => __DIR__ . '/handlers/support.handler.php', 'trust' => __DIR__ . '/handlers/trust.handler.php', 'telemetry'=> __DIR__ . '/handlers/telemetry.handler.php', 'security' => __DIR__ . '/handlers/security.handler.php', 'page' => __DIR__ . '/handlers/page.handler.php', 'crypto' => __DIR__ . '/handlers/checkout.handler.php', 'callback' => __DIR__ . '/handlers/callback.handler.php', 'render' => __DIR__ . '/handlers/render.handler.php', ]; if (!isset($map[$group]) || !file_exists($map[$group])) { App::err('Unknown route: ' . $route, 404); } $csrfExempt = ['telemetry', 'callback', 'security']; if (!in_array($group, $csrfExempt, true)) { $csrfToken = $body['csrf'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? ''; if (!Auth::validateCsrf($csrfToken)) { try { DB::run( "INSERT INTO events (event_type, ip_address, details, created_at) VALUES ('csrf_violation', :ip, :details, NOW())", [':ip' => $_SERVER['REMOTE_ADDR'] ?? '', ':details' => json_encode(['route' => $route, 'ua' => substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 300)])] ); } catch (\Throwable $e) { error_log('[CSRF] Log failed: ' . $e->getMessage()); } App::err('Security token expired. Please refresh the page.', 403); } } require_once $map[$group]; $handler = $group . 'Handler'; if (!function_exists($handler)) { App::err('Handler not found: ' . $handler, 500); } $handler($action, $body); App::err('Unknown action: ' . $action, 404); 