oscar-admin/lib.php
Oscar Admin Contributors 77342f4629 Initial public release of Oscar Admin
Standalone Open OSCAR Server admin dashboard with login, user/session/room management, BART, buddy list, Gotify addon, audit log, and API console. Includes AI disclosure and open-source project docs.
2026-12-03 18:26:44 -05:00

433 lines
12 KiB
PHP

<?php
declare(strict_types=1);
/**
* Oscar Admin shared helpers.
*
* This is the core include for the standalone admin panel.
* Responsibilities:
* - config loading (config.php, fallback config.example.php)
* - session/CSRF/auth helpers
* - OSCAR Management API client (admin_api/admin_send_im)
* - login throttle + pending-login state
* - page shell rendering (admin_page)
* - audit log helpers
*
* Keep this file dependency-light; optional integrations (Gotify) live in
* separate lib_gotify.php and are loaded conditionally.
*/
function admin_config(): array
{
static $config = null;
if ($config === null) {
$configPath = __DIR__ . '/config.php';
$examplePath = __DIR__ . '/config.example.php';
if (file_exists($configPath)) {
$config = require $configPath;
} elseif (file_exists($examplePath)) {
$config = require $examplePath;
} else {
throw new RuntimeException('Missing admin config.php (or config.example.php).');
}
}
return $config;
}
function admin_cfg(string $key, mixed $default = null): mixed
{
$config = admin_config();
return array_key_exists($key, $config) ? $config[$key] : $default;
}
function admin_start_session(): void
{
if (session_status() === PHP_SESSION_ACTIVE) {
return;
}
$secure = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
session_name((string) admin_cfg('session_name', 'oscar_admin'));
session_set_cookie_params([
'lifetime' => 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): 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;
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex,nofollow">
<title><?= h($title) ?> - <?= h($site) ?></title>
<link rel="stylesheet" href="<?= h($sharedHref) ?>">
<link rel="stylesheet" href="admin.css">
</head>
<body class="admin-body">
<div class="bg-orb orb-a"></div>
<div class="bg-orb orb-b"></div>
<div class="bg-grid"></div>
<header class="admin-topbar">
<div class="admin-brand">
<div class="brand-mark" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3l7 3v5c0 5-3 7.5-7 10-4-2.5-7-5-7-10V6l7-3z"/><path d="M9 12l2 2 4-4"/></svg>
</div>
<div>
<div class="brand-title"><?= h($site) ?></div>
<div class="brand-sub">Open OSCAR control room</div>
</div>
</div>
<?php if ($user): ?>
<nav class="admin-nav" aria-label="Admin">
<a class="<?= $active === 'dashboard' ? 'active' : '' ?>" href="index.php">Dashboard</a>
<?php
$gotifyLib = __DIR__ . '/lib_gotify.php';
if (file_exists($gotifyLib) && !function_exists('admin_gotify_feature_enabled')) {
require_once $gotifyLib;
}
$menuFile = __DIR__ . '/user-menu.php';
if (file_exists($menuFile)) {
include $menuFile;
} else {
?>
<span class="nav-user" title="Signed in"><?= h((string) $user['screen_name']) ?></span>
<form method="post" action="logout.php" class="inline-form">
<input type="hidden" name="csrf" value="<?= h(admin_csrf_token()) ?>">
<button type="submit" class="btn btn-ghost btn-small">Logout</button>
</form>
<?php
}
?>
</nav>
<?php endif; ?>
</header>
<main class="admin-main">
<?php foreach ($flashes as $flash): ?>
<div class="flash flash-<?= h((string) ($flash['type'] ?? 'info')) ?>" role="status">
<?= h((string) ($flash['message'] ?? '')) ?>
</div>
<?php endforeach; ?>
<?php $body(); ?>
</main>
<script>
window.ADMIN_CSRF = <?= json_encode(admin_csrf_token(), JSON_UNESCAPED_SLASHES) ?>;
</script>
<script src="admin.js"></script>
</body>
</html>
<?php
}
/**
* Append a local audit entry (gitignored audit.log).
* Sensitive keys are scrubbed by callers where needed.
*/
function admin_audit(string $action, array $details = []): void
{
$file = __DIR__ . '/audit.log';
$user = admin_current_user();
$entry = [
'ts' => date('c'),
'user' => $user['screen_name'] ?? 'unknown',
'ip' => $_SERVER['REMOTE_ADDR'] ?? '',
'action' => $action,
'details' => $details,
];
@file_put_contents($file, json_encode($entry, JSON_UNESCAPED_SLASHES) . "\n", FILE_APPEND | LOCK_EX);
}
function admin_audit_read(int $limit = 200): array
{
$file = __DIR__ . '/audit.log';
if (!file_exists($file)) return [];
$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if (!$lines) return [];
$lines = array_slice($lines, -$limit);
$out = [];
foreach ($lines as $line) {
$decoded = json_decode($line, true);
if (is_array($decoded)) $out[] = $decoded;
}
return array_reverse($out);
}