oscar-admin/login.php
Oscar Admin Contributors a67ca468ef Add SEO metadata and git repo link to admin pages
Makes login page indexable with description/OG/canonical options, keeps authenticated dashboard noindex, and adds a footer link to the source repository.
2026-12-03 18:49:13 -05:00

304 lines
16 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
declare(strict_types=1);
/**
* Admin login page.
*
* Flow:
* 1) User enters OSCAR screen name + solves math anti-spam challenge.
* 2) Server sends one-time code via OSCAR IM, or via Gotify if that screen
* name has a personal Gotify config (Gotify addon is optional).
* 3) User verifies code and gets an admin session.
*
* Security/anti-enumeration:
* - Same UI flow for allowed and non-allowed screen names.
* - Non-allowed names get a random funny denial IM/notification, but the page
* still shows the normal "code sent" / verify flow with a fake pending code.
* - Session-based throttling limits brute force/spam.
*/
require_once __DIR__ . '/lib.php';
$gotifyLib = __DIR__ . '/lib_gotify.php';
if (file_exists($gotifyLib)) {
require_once $gotifyLib;
}
admin_start_session();
if (admin_current_user() !== null) {
admin_redirect('index.php');
}
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("Content-Security-Policy: default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self'; form-action 'self'");
}
function admin_login_math_new(): array
{
$a = random_int(2, 15);
$b = random_int(1, 12);
$ops = ['+', '-', '×'];
$op = $ops[array_rand($ops)];
if ($op === '-') {
if ($b > $a) { [$a, $b] = [$b, $a]; }
$answer = $a - $b;
} elseif ($op === '×') {
$a = random_int(2, 9);
$b = random_int(2, 9);
$answer = $a * $b;
} else {
$answer = $a + $b;
}
$_SESSION['login_math'] = [
'q' => "What is {$a} {$op} {$b}?",
'a' => (string) $answer,
't' => time(),
];
return $_SESSION['login_math'];
}
function admin_login_math_get(): array
{
$m = $_SESSION['login_math'] ?? null;
if (!is_array($m) || empty($m['q']) || !isset($m['a'])) {
return admin_login_math_new();
}
// Refresh stale challenges.
if (time() - (int) ($m['t'] ?? 0) > 900) {
return admin_login_math_new();
}
return $m;
}
function admin_login_math_check(?string $answer): bool
{
$m = admin_login_math_get();
$ok = is_string($answer) && trim($answer) !== '' && hash_equals((string) $m['a'], trim($answer));
// One attempt per challenge.
admin_login_math_new();
return $ok;
}
$error = '';
$notice = '';
$pending = admin_pending_login();
$stage = $pending ? 'verify' : 'request';
$math = admin_login_math_get();
$gotifyEnabled = function_exists('admin_gotify_enabled') && admin_gotify_enabled();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!admin_csrf_valid($_POST['csrf'] ?? null)) {
$error = 'Security check failed. Please try again.';
} elseif (admin_login_throttled()) {
$error = 'Too many login attempts. Take a breather and try again later.';
} else {
$action = (string) ($_POST['action'] ?? '');
if ($action === 'request_code') {
$screenName = trim((string) ($_POST['screen_name'] ?? ''));
$mathAnswer = (string) ($_POST['math_answer'] ?? '');
$delivery = 'oscar';
if ($gotifyEnabled && function_exists('admin_gotify_resolve')) {
$gcfg = admin_gotify_resolve($screenName);
if ($gcfg) {
$delivery = 'gotify';
}
}
if (!admin_login_math_check($mathAnswer)) {
admin_record_login_failure();
$error = 'Math check failed. Try again (robots are notoriously bad at this).';
$math = admin_login_math_get();
} elseif ($screenName === '' || strlen($screenName) > 64) {
$error = 'Enter your OSCAR screen name.';
$math = admin_login_math_get();
} elseif (!admin_is_allowed($screenName)) {
admin_record_login_failure();
$funny = [
"Nice try, {$screenName}. This admin panel is members-only, and the velvet rope just laughed at you.",
"Access denied. The admin hamsters held an emergency meeting and voted you 'not it'.",
"Whoa there, keyboard cowboy. You're not on the admin list. The server has filed your request under 'bold, but no'.",
"Nope. You're not an admin. Please return your imaginary badge at the nearest imaginary desk.",
"The OSCAR server checked the VIP list twice. You are on neither list. It also asked me to tell you to get lost, politely-ish.",
"Error 403: You lack the ancient admin runes. The control room door remains unimpressed.",
"Sorry {$screenName}, this dashboard runs on admin juice, and your cup is empty.",
"The admin council consulted the sacred spreadsheet. Your name was not there. It was a short meeting.",
"You have reached the admin panel. Unfortunately, the admin panel has not reached you back.",
"Bold move. Wrong permissions. The server admires the confidence, but not enough to let you in.",
"Access denied. I asked the mainframe, and it said 'lol no' with surprising professionalism.",
"This area is for admins only. You are currently in the 'very enthusiastic spectator' category.",
"The bouncer checked your name, checked it again, then checked the vibes. All three said no.",
"You must be this admin to ride this dashboard. You are currently several admins short.",
"The keys to the control room are guarded by a dragon. The dragon says you may not pass.",
];
$msg = $funny[array_rand($funny)];
// Best effort: notify via selected channel. Failure is intentionally silent to avoid leaking details.
if ($delivery === 'gotify' && function_exists('admin_gotify_send_for_user')) {
$gcfg = admin_gotify_resolve($screenName);
if ($gcfg) {
admin_gotify_send_for_user($screenName, 'Oscar Admin login denied', $msg);
}
// If no gotify config, silently skip send but keep same UI.
} else {
admin_send_im($screenName, $msg, true);
}
// Behave identically to a successful send to avoid account enumeration.
$fakeCode = admin_random_code((int) admin_cfg('login_code_length', 8));
admin_set_pending_login($screenName, $fakeCode, $delivery);
$pending = admin_pending_login();
$stage = 'verify';
$notice = $delivery === 'gotify'
? 'Login code sent via Gotify. Check your Gotify notifications.'
: 'Login code sent to ' . $screenName . ' on OSCAR. Check your IMs.';
} else {
$code = admin_random_code((int) admin_cfg('login_code_length', 8));
$text = "Oscar Admin login code for {$screenName}: {$code}\nThis code expires in " . (int) admin_cfg('login_code_ttl_seconds', 600) . " seconds. If you didn't request it, ignore this message.";
$send = ['ok' => false, 'error' => 'Delivery failed'];
if ($delivery === 'gotify' && function_exists('admin_gotify_send_for_user')) {
$gcfg = function_exists('admin_gotify_resolve') ? admin_gotify_resolve($screenName) : null;
if ($gcfg) {
$send = admin_gotify_send_for_user($screenName, 'Oscar Admin login code', $text);
} else {
// No personal/global gotify config - fake success UI to avoid enumeration, but no code is sent.
// Legit admins must configure Gotify in dashboard first.
$send = ['ok' => true, 'status' => 0, 'error' => null, 'data' => null, 'raw' => ''];
}
} else {
$send = admin_send_im($screenName, $text, true);
}
if (!$send['ok']) {
admin_record_login_failure();
$error = $delivery === 'gotify'
? 'Could not send a login code via Gotify right now. Check Gotify settings.'
: 'Could not send a login code via OSCAR right now. Check the system account and management API config.';
$math = admin_login_math_get();
} else {
admin_set_pending_login($screenName, $code, $delivery);
$pending = admin_pending_login();
$stage = 'verify';
$notice = $delivery === 'gotify'
? 'Login code sent via Gotify. Check your Gotify notifications.'
: 'Login code sent to ' . $screenName . ' on OSCAR. Check your IMs.';
}
}
} elseif ($action === 'verify_code') {
$pending = admin_pending_login();
$code = trim((string) ($_POST['code'] ?? ''));
if (!$pending) {
$error = 'Your login code expired. Request a new one.';
$stage = 'request';
} elseif ($code === '') {
$error = 'Enter the login code you received on OSCAR.';
$stage = 'verify';
} elseif (!password_verify($code, (string) $pending['code_hash'])) {
admin_record_login_failure();
$error = 'That code is not right. The OSCAR gods remain unimpressed.';
$stage = 'verify';
// After several failures, clear pending.
$attempts = $_SESSION['login_attempts'] ?? [];
if (is_array($attempts) && count($attempts) >= (int) admin_cfg('max_login_attempts', 8)) {
admin_clear_pending_login();
$stage = 'request';
}
} else {
$name = (string) $pending['screen_name'];
if (!admin_is_allowed($name)) {
// Treat as invalid to avoid account/enumeration leaks.
admin_record_login_failure();
$error = 'That code is not right. The OSCAR gods remain unimpressed.';
$stage = 'verify';
$attempts = $_SESSION['login_attempts'] ?? [];
if (is_array($attempts) && count($attempts) >= (int) admin_cfg('max_login_attempts', 8)) {
admin_clear_pending_login();
$stage = 'request';
}
} else {
admin_login_user($name);
admin_flash('success', 'Welcome back, ' . $name . '. The control room is yours.');
admin_redirect('index.php');
}
}
} elseif ($action === 'reset') {
admin_clear_pending_login();
$pending = null;
$stage = 'request';
$notice = 'Login reset. Start fresh.';
} else {
$error = 'Unknown action.';
}
}
}
admin_page('Login', 'login', function () use ($error, $notice, $pending, $stage, $math, $gotifyEnabled): void {
?>
<section class="auth-wrap">
<div class="auth-card card reveal">
<div class="auth-head">
<div class="eyebrow">Secure sign-in</div>
<h1>Admin access</h1>
<p class="muted">Sign in with your OSCAR screen name. We'll send a one-time code through <?= !empty($gotifyEnabled) ? 'OSCAR or Gotify' : 'the OSCAR server' ?>.</p>
</div>
<?php if ($error): ?>
<div class="flash flash-error" role="alert"><?= h($error) ?></div>
<?php endif; ?>
<?php if ($notice): ?>
<div class="flash flash-success" role="status"><?= h($notice) ?></div>
<?php endif; ?>
<?php if ($stage === 'verify' && $pending): ?>
<div class="pending-box">
<div class="pending-label">Code sent via <?= h(((string)($pending['delivery'] ?? 'oscar')) === 'gotify' ? 'Gotify' : 'OSCAR IM') ?></div>
<div class="pending-name"><?= h((string) $pending['screen_name']) ?></div>
<div class="pending-expiry muted">Expires in <?= h((string) max(0, (int) $pending['expires_at'] - time())) ?>s</div>
</div>
<form method="post" class="stack-form">
<input type="hidden" name="csrf" value="<?= h(admin_csrf_token()) ?>">
<input type="hidden" name="action" value="verify_code">
<label class="field">
<span>Login code</span>
<input type="text" name="code" autocomplete="one-time-code" inputmode="text" maxlength="32" required placeholder="Enter login code">
</label>
<button type="submit" class="btn btn-primary btn-block">Verify &amp; enter</button>
</form>
<form method="post" class="reset-row">
<input type="hidden" name="csrf" value="<?= h(admin_csrf_token()) ?>">
<input type="hidden" name="action" value="reset">
<button type="submit" class="btn btn-ghost btn-small">Use a different screen name</button>
</form>
<?php else: ?>
<form method="post" class="stack-form">
<input type="hidden" name="csrf" value="<?= h(admin_csrf_token()) ?>">
<input type="hidden" name="action" value="request_code">
<label class="field">
<span>OSCAR screen name</span>
<input type="text" name="screen_name" autocomplete="username" maxlength="64" required placeholder="your screen name">
</label>
<label class="field">
<span>Anti-spam check: <?= h((string) ($math['q'] ?? 'What is 1 + 1?')) ?></span>
<input type="text" name="math_answer" inputmode="numeric" autocomplete="off" required placeholder="Answer">
</label>
<button type="submit" class="btn btn-primary btn-block">Send login code</button>
</form>
<?php endif; ?>
</div>
<div class="auth-side reveal delay-1">
<div class="side-card">
<h2>How it works</h2>
<ol class="step-list">
<li><span class="step-num">1</span><div><strong>Enter your screen name</strong><p class="muted">The one configured as an admin.</p></div></li>
<li><span class="step-num">2</span><div><strong>Get your code</strong><p class="muted"><?= !empty($gotifyEnabled) ? 'Receive it via OSCAR IM or Gotify.' : 'The system account sends your one-time code via OSCAR IM.' ?></p></div></li>
<li><span class="step-num">3</span><div><strong>Verify and manage</strong><p class="muted">Access the full admin dashboard.</p></div></li>
</ol>
</div>
</div>
</section>
<?php
}, [
'indexable' => true,
'description' => 'Oscar Admin is a standalone open-source web dashboard for managing Open OSCAR Server: users, sessions, chat rooms, BART assets, buddy lists, and more.',
'repo_url' => 'https://git.claytonia.net/Clarth/oscar-admin',
]);