0, 'path' => '/', 'secure' => $secure, 'httponly' => true, 'samesite' => 'Strict', ]); session_start(); } function h(string $value): string { return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); } function admin_csrf_token(): string { admin_start_session(); if (empty($_SESSION['csrf'])) { $_SESSION['csrf'] = bin2hex(random_bytes(32)); } return $_SESSION['csrf']; } function admin_csrf_valid(?string $token): bool { admin_start_session(); return is_string($token) && isset($_SESSION['csrf']) && hash_equals($_SESSION['csrf'], $token); } function admin_normalize_screen_name(string $name): string { $name = trim($name); $name = preg_replace('/\s+/', ' ', $name) ?? $name; return strtolower($name); } function admin_is_allowed(string $screenName): bool { $normalized = admin_normalize_screen_name($screenName); $allowed = admin_cfg('admin_users', []); foreach ($allowed as $entry) { if (admin_normalize_screen_name((string) $entry) === $normalized) { return true; } } return false; } function admin_mgmt_base(): string { $host = (string) admin_cfg('mgmt_api_host', '127.0.0.1'); $port = (int) admin_cfg('mgmt_api_port', 8080); $host = trim($host); if ($host === '') { $host = '127.0.0.1'; } if ($port < 1 || $port > 65535) { $port = 8080; } return 'http://' . $host . ':' . $port; } function admin_api(string $method, string $path, ?array $body = null, array $query = []): array { $base = admin_mgmt_base(); $url = $base . $path; if ($query !== []) { $url .= '?' . http_build_query($query); } $ch = curl_init($url); $headers = ['Accept: application/json']; $payload = null; if ($body !== null) { $payload = json_encode($body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); $headers[] = 'Content-Type: application/json'; } curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => strtoupper($method), CURLOPT_HTTPHEADER => $headers, CURLOPT_TIMEOUT => 15, CURLOPT_CONNECTTIMEOUT => 5, ]); if ($payload !== null) { curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); } $raw = curl_exec($ch); $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE); $err = curl_error($ch); curl_close($ch); if ($raw === false) { return ['ok' => false, 'status' => 0, 'error' => $err ?: 'Request failed', 'data' => null, 'raw' => '']; } $decoded = json_decode($raw, true); $ok = $status >= 200 && $status < 300; return [ 'ok' => $ok, 'status' => $status, 'error' => $ok ? null : (is_array($decoded) && isset($decoded['message']) ? (string) $decoded['message'] : ($raw !== '' ? $raw : 'HTTP ' . $status)), 'data' => $decoded, 'raw' => $raw, ]; } function admin_send_im(string $to, string $text, bool $storeOffline = true): array { $from = trim((string) admin_cfg('system_screen_name', '')); if ($from === '') { return ['ok' => false, 'status' => 0, 'error' => 'System screen name is not configured', 'data' => null, 'raw' => '']; } return admin_api('POST', '/instant-message', [ 'from' => $from, 'to' => $to, 'text' => $text, 'storeOffline' => $storeOffline, ]); } function admin_random_code(int $length = 8): string { $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; $max = strlen($alphabet) - 1; $out = ''; for ($i = 0; $i < $length; $i++) { $out .= $alphabet[random_int(0, $max)]; } return $out; } function admin_login_attempts_key(): string { return 'login_attempts'; } function admin_login_throttled(): bool { admin_start_session(); $window = (int) admin_cfg('login_attempt_window_seconds', 900); $max = (int) admin_cfg('max_login_attempts', 8); $now = time(); $attempts = $_SESSION[admin_login_attempts_key()] ?? []; if (!is_array($attempts)) { $attempts = []; } $attempts = array_values(array_filter($attempts, fn($ts) => is_int($ts) && $ts >= ($now - $window))); $_SESSION[admin_login_attempts_key()] = $attempts; return count($attempts) >= $max; } function admin_record_login_failure(): void { admin_start_session(); $now = time(); $attempts = $_SESSION[admin_login_attempts_key()] ?? []; if (!is_array($attempts)) { $attempts = []; } $attempts[] = $now; $_SESSION[admin_login_attempts_key()] = $attempts; } function admin_clear_login_failures(): void { admin_start_session(); unset($_SESSION[admin_login_attempts_key()]); } function admin_set_pending_login(string $screenName, string $code, string $delivery = 'oscar'): void { admin_start_session(); $ttl = (int) admin_cfg('login_code_ttl_seconds', 600); $_SESSION['pending_login'] = [ 'screen_name' => $screenName, 'normalized' => admin_normalize_screen_name($screenName), 'code_hash' => password_hash($code, PASSWORD_DEFAULT), 'expires_at' => time() + max(60, $ttl), 'delivery' => $delivery === 'gotify' ? 'gotify' : 'oscar', ]; } function admin_pending_login(): ?array { admin_start_session(); $pending = $_SESSION['pending_login'] ?? null; if (!is_array($pending)) { return null; } if (($pending['expires_at'] ?? 0) < time()) { unset($_SESSION['pending_login']); return null; } return $pending; } function admin_clear_pending_login(): void { admin_start_session(); unset($_SESSION['pending_login']); } function admin_login_user(string $screenName): void { admin_start_session(); session_regenerate_id(true); $_SESSION['admin_user'] = [ 'screen_name' => $screenName, 'normalized' => admin_normalize_screen_name($screenName), 'logged_in_at' => time(), ]; admin_clear_pending_login(); admin_clear_login_failures(); } function admin_current_user(): ?array { admin_start_session(); $user = $_SESSION['admin_user'] ?? null; if (!is_array($user) || empty($user['screen_name'])) { return null; } return $user; } function admin_require_login(): array { $user = admin_current_user(); if ($user === null) { header('Location: login.php'); exit; } return $user; } function admin_logout(): void { admin_start_session(); $_SESSION = []; if (ini_get('session.use_cookies')) { $params = session_get_cookie_params(); setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']); } session_destroy(); } function admin_flash(string $type, string $message): void { admin_start_session(); $_SESSION['flash'][] = ['type' => $type, 'message' => $message]; } function admin_flashes(): array { admin_start_session(); $flashes = $_SESSION['flash'] ?? []; unset($_SESSION['flash']); return is_array($flashes) ? $flashes : []; } function admin_json(array $payload, int $status = 200): never { http_response_code($status); header('Content-Type: application/json; charset=utf-8'); echo json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); exit; } function admin_redirect(string $url): never { header('Location: ' . $url); exit; } function admin_page(string $title, string $active, callable $body, array $opts = []): void { $user = admin_current_user(); $flashes = admin_flashes(); $site = (string) admin_cfg('site_name', 'Oscar Admin'); $shared = (string) admin_cfg('shared_style_path', 'assets/style.css'); $sharedHref = file_exists(__DIR__ . '/' . ltrim($shared, '/')) ? $shared : $shared; $indexable = !empty($opts['indexable']); $desc = trim((string) ($opts['description'] ?? ($indexable ? 'Oscar Admin is a standalone web admin dashboard for Open OSCAR Server. Manage users, sessions, rooms, BART, buddy lists, and more.' : ''))); $canonical = trim((string) ($opts['canonical'] ?? '')); $repoUrl = trim((string) ($opts['repo_url'] ?? 'https://git.claytonia.net/Clarth/oscar-admin')); if (!headers_sent()) { header('X-Frame-Options: DENY'); header('X-Content-Type-Options: nosniff'); header('Referrer-Policy: no-referrer'); header('Permissions-Policy: camera=(), microphone=(), geolocation=()'); header('X-Robots-Tag: ' . ($indexable ? 'index, follow' : 'noindex, nofollow')); header("Content-Security-Policy: default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self'; form-action 'self'"); } ?>