commit 77342f4629ca64e89a9edd33363f709497880733 Author: Oscar Admin Contributors Date: Thu Dec 3 18:26:44 2026 -0500 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. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..72de612 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +# Runtime / secrets - never commit +/config.php +/audit.log +/gotify-users.php +/gotify-users.json + +# OS/editor noise +.DS_Store +Thumbs.db +.idea/ +.vscode/ +*.swp +*.swo diff --git a/AI_DISCLOSURE.md b/AI_DISCLOSURE.md new file mode 100644 index 0000000..77d39af --- /dev/null +++ b/AI_DISCLOSURE.md @@ -0,0 +1,7 @@ +# AI Disclosure + +Parts of this project were created and maintained with assistance from AI coding tools. + +AI-assisted contributions may include code, refactors, documentation, and configuration. All AI-assisted output is intended to be reviewed, tested, and maintained by human contributors before release. + +If you find an issue, security concern, or incorrect behavior, please open an issue or report it through the process described in [SECURITY.md](SECURITY.md). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..85f72b3 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,48 @@ +# Contributing + +Thanks for your interest in improving Oscar Admin. + +## Before you start + +- Keep changes focused and easy to review. +- Do not commit secrets or runtime data (`config.php`, `audit.log`, `gotify-users.php`). +- Preserve the project's security model: private Management API, CSRF on writes, anti-enumeration login behavior, and optional Gotify. + +## Development + +### Requirements + +- PHP 8.1+ (8.2+ recommended) +- PHP cURL extension +- Access to an Open OSCAR Server Management API (private/local) + +### Local setup + +```bash +cp config.example.php config.php +php -S 127.0.0.1:8081 +``` + +Then open `http://127.0.0.1:8081/login.php`. + +### Code style + +- PHP: clear, small functions; strict types where already used; escape output with `h()` in templates. +- JS: vanilla JS, defensive DOM checks, no build step. +- CSS: keep admin styles in `admin.css`; `assets/style.css` is the bundled base stylesheet. + +## Pull requests + +- Describe the problem and the user-facing impact. +- Include manual test steps. +- For security-sensitive changes, note threat/abuse considerations. +- If AI tools were used, make sure the change is reviewed and understood before submitting. + +## Reporting bugs + +Please include: + +- What you expected vs. what happened +- Steps to reproduce +- PHP version and deployment context (nginx/apache/php-fpm/built-in) +- Relevant logs/screenshots (redact secrets, tokens, and private IPs as needed) diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..91e2699 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Oscar Admin contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100755 index 0000000..b4812a2 --- /dev/null +++ b/README.md @@ -0,0 +1,156 @@ +# Oscar Admin + +A standalone, web-based admin dashboard for [Open OSCAR Server](https://github.com/oscar-server/oscar-server) (AIM/ICQ OSCAR protocol). + +Oscar Admin provides a clean UI for day-to-day server administration: users, sessions, chat rooms, messaging, directory, BART assets, buddy lists (feedbag), audit logs, and a raw Management API console. + +> **Status:** Active. The admin panel is intended to be deployed alongside Open OSCAR Server, but this repository is standalone and does not require changes to the server source. + +## Features + +- **Secure login** - OSCAR screen name + math anti-spam challenge + one-time code sent via OSCAR IM. +- **Anti-enumeration** - Allowed and non-allowed screen names get the same login flow/UI. +- **Optional Gotify delivery** - Per-user Gotify URL/token settings; login codes can be sent through Gotify when configured. 100% optional. +- **Overview** - Version, online sessions, users, and room counts. +- **User management** - List/search, create/delete, details, suspend/unsuspend, bot flag, password reset, buddy icon, active sessions. +- **Session management** - List active sessions, inspect details, kick sessions. +- **Chat rooms** - List public/private rooms, create/delete public rooms. +- **Messaging** - Send IM/popup through the system account (feature availability depends on server version). +- **Directory** - Category/keyword CRUD and AIM directory entries. +- **BART / Buddy Art** - Type catalog, browse assets, upload/hash/preview/delete, feedbag BART item set/remove, and a built-in info guide. +- **Buddy List / Feedbag** - User-friendly group/buddy management and linked accounts. +- **Audit log** - Local log of admin actions. +- **API Console** - Raw Management API requests for advanced/debug use. + +## Requirements + +- **PHP 8.1+** with `curl` and `session` extensions enabled. +- A web server capable of running PHP (nginx + PHP-FPM, Apache, Caddy+php-fpm, etc.). +- An **Open OSCAR Server** instance with the **Management API** enabled. +- A system OSCAR account on that server (used to send login codes/messages). + +## Quick Start + +1. **Clone the repo** + + ```bash + git clone https://github.com//oscar-admin.git + cd oscar-admin + ``` + +2. **Create config** + + ```bash + cp config.example.php config.php + ``` + +3. **Edit `config.php`** + + - Add allowed admin screen names to `admin_users`. + - Set `system_screen_name` and `system_password` (an existing OSCAR account). + - Set `mgmt_api_host` / `mgmt_api_port` to your private Management API endpoint. + - Optionally enable Gotify (`gotify_enabled => true`). + +4. **Serve with PHP** + + For local testing: + + ```bash + php -S 127.0.0.1:8081 + ``` + + Open `http://127.0.0.1:8081/login.php`. + + For production, use nginx/Apache + PHP-FPM behind HTTPS. + +## Configuration + +See [`config.example.php`](config.example.php) for all options. Key settings: + +| Setting | Purpose | +|---|---| +| `admin_users` | OSCAR screen names allowed to sign in | +| `system_screen_name` / `system_password` | OSCAR account used to send login codes/messages | +| `mgmt_api_host` / `mgmt_api_port` | Private Open OSCAR Management API endpoint | +| `gotify_enabled` | Enables optional Gotify addon | +| `gotify_url` / `gotify_token` | Optional global Gotify fallback (per-user settings preferred) | +| `shared_style_path` | Base CSS path (defaults to bundled `assets/style.css`) | + +## Gotify (Optional) + +Gotify support is a 100% optional addon (`lib_gotify.php`). The panel works without it. + +1. Set `gotify_enabled => true` in `config.php`. +2. Sign in to the admin dashboard. +3. Open the top-right user menu and save your Gotify URL/token. +4. Use **Test** to verify delivery. + +If a Gotify URL/token is saved for a user, login codes are sent through Gotify for that user. Clear settings to disable Gotify delivery for that account. + +Per-user Gotify settings are stored in `gotify-users.php` (gitignored). It is a PHP file to reduce accidental direct exposure. + +## Deployment / Hardening + +### Keep the Management API private + +The OSCAR Management API is powerful. Bind it to `127.0.0.1` or a trusted private network and **do not expose it publicly**. + +### Protect sensitive files + +Do not serve or commit: + +- `config.php` - secrets and config +- `audit.log` - admin action log +- `gotify-users.php` - per-user Gotify tokens/URLs + +Example nginx rules (adjust paths to your install): + +```nginx +location /admin/ { + # ... php handling ... + + location ~* /admin/(config\.php|config\.example\.php|lib\.php|lib_gotify\.php|user-menu\.php|gotify-users\.php|gotify-users\.json|audit\.log|README\.md|\.gitignore)$ { + deny all; + return 404; + } +} +``` + +Also serve the admin panel over HTTPS and consider an IP allowlist/VPN/auth proxy. + +## Project Structure + +```text +. +├── action.php # Authenticated JSON action endpoint (dashboard -> Management API) +├── admin.css # Admin-specific styles +├── admin.js # Dashboard client behavior +├── assets/ +│ └── style.css # Bundled base stylesheet +├── bart-info.php # BART/Buddy Art help page +├── config.example.php # Configuration template +├── index.php # Dashboard UI +├── lib.php # Shared helpers: config/session/auth/API/audit/page shell +├── lib_gotify.php # Optional Gotify addon +├── login.php # Login flow (math challenge + OSCAR/Gotify OTP) +├── logout.php # CSRF-protected logout +└── user-menu.php # User menu / per-user Gotify settings +``` + +Runtime files (gitignored): `config.php`, `audit.log`, `gotify-users.php`. + +## Security + +See [SECURITY.md](SECURITY.md) for vulnerability reporting and deployment guidance. + +## AI Disclosure + +Parts of this project were created and maintained with assistance from AI coding tools. See [AI_DISCLOSURE.md](AI_DISCLOSURE.md). + +## Contributing + +Contributions are welcome. Please read [CONTRIBUTING.md](CONTRIBUTING.md) before opening a PR. + +## License + +[MIT](LICENSE) diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..b8a60e1 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,26 @@ +# Security Policy + +## Supported versions + +The latest version on the default branch is the supported version. + +## Reporting a vulnerability + +Please **do not** open a public issue for a suspected security vulnerability. + +Instead, report it privately to the maintainers with: + +- A description of the issue and impact +- Steps to reproduce or proof of concept +- Affected files/endpoints/configuration +- Any suggested mitigation + +If you need a private contact channel, use the repository owner's preferred security contact method listed on their GitHub/Git profile. + +## Security notes for deployers + +- Keep `config.php`, `audit.log`, and `gotify-users.php` outside public access and out of git. +- **Never expose the OSCAR Management API publicly.** Bind it to localhost or a trusted private network. +- Serve the admin panel behind HTTPS. +- Restrict access at the web server where appropriate (VPN/IP allowlist/auth proxy). +- Review web server rules to deny direct access to sensitive files. diff --git a/action.php b/action.php new file mode 100644 index 0000000..904fef1 --- /dev/null +++ b/action.php @@ -0,0 +1,400 @@ + false, 'error' => 'Invalid CSRF token.'], 403); + } + $scrubbed = $input; + foreach (['password', 'csrf', 'body'] as $k) { if (isset($scrubbed[$k])) $scrubbed[$k] = '[redacted]'; } + admin_audit($action ?: 'unknown', $scrubbed); +} + +function admin_need(string $value, string $field): string +{ + $value = trim($value); + if ($value === '') { + admin_json(['ok' => false, 'error' => "Missing field: {$field}"], 400); + } + return $value; +} + +switch ($action) { + case 'overview': + $version = admin_api('GET', '/version'); + $sessions = admin_api('GET', '/session'); + $users = admin_api('GET', '/user'); + $publicRooms = admin_api('GET', '/chat/room/public'); + $privateRooms = admin_api('GET', '/chat/room/private'); + admin_json([ + 'ok' => true, + 'version' => $version, + 'sessions' => $sessions, + 'users' => $users, + 'public_rooms' => $publicRooms, + 'private_rooms' => $privateRooms, + ]); + + case 'users.list': + admin_json(admin_api('GET', '/user')); + + case 'users.create': + $screenName = admin_need((string) ($input['screen_name'] ?? ''), 'screen_name'); + $password = admin_need((string) ($input['password'] ?? ''), 'password'); + admin_json(admin_api('POST', '/user', ['screen_name' => $screenName, 'password' => $password])); + + case 'users.delete': + $screenName = admin_need((string) ($input['screen_name'] ?? ''), 'screen_name'); + admin_json(admin_api('DELETE', '/user', ['screen_name' => $screenName])); + + case 'users.get': + $screenName = admin_need((string) ($input['screen_name'] ?? ''), 'screen_name'); + admin_json(admin_api('GET', '/user/' . rawurlencode($screenName) . '/account')); + + case 'users.patch': + $screenName = admin_need((string) ($input['screen_name'] ?? ''), 'screen_name'); + $body = []; + if (array_key_exists('suspended_status', $input)) { + $status = $input['suspended_status']; + if ($status === '' || $status === null) { + $body['suspended_status'] = null; + } else { + $body['suspended_status'] = (string) $status; + } + } + if (array_key_exists('is_bot', $input)) { + $val = $input['is_bot']; + if ($val === '' || $val === null) { + $body['is_bot'] = null; + } else { + $body['is_bot'] = filter_var($val, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); + if ($body['is_bot'] === null && $val !== 'false' && $val !== '0') { + $body['is_bot'] = (bool) $val; + } + } + } + if ($body === []) { + admin_json(['ok' => false, 'error' => 'No fields to update.'], 400); + } + admin_json(admin_api('PATCH', '/user/' . rawurlencode($screenName) . '/account', $body)); + + case 'users.set_password': + $screenName = admin_need((string) ($input['screen_name'] ?? ''), 'screen_name'); + $password = admin_need((string) ($input['password'] ?? ''), 'password'); + admin_json(admin_api('PUT', '/user/password', ['screen_name' => $screenName, 'password' => $password])); + + case 'sessions.list': + admin_json(admin_api('GET', '/session')); + + case 'sessions.get': + $screenName = admin_need((string) ($input['screen_name'] ?? ''), 'screen_name'); + admin_json(admin_api('GET', '/session/' . rawurlencode($screenName))); + + case 'sessions.kick': + $screenName = admin_need((string) ($input['screen_name'] ?? ''), 'screen_name'); + admin_json(admin_api('DELETE', '/session/' . rawurlencode($screenName))); + + case 'rooms.public.list': + admin_json(admin_api('GET', '/chat/room/public')); + + case 'rooms.private.list': + admin_json(admin_api('GET', '/chat/room/private')); + + case 'rooms.public.create': + $name = admin_need((string) ($input['name'] ?? ''), 'name'); + admin_json(admin_api('POST', '/chat/room/public', ['name' => $name])); + + case 'rooms.public.delete': + $names = $input['names'] ?? []; + if (is_string($names)) { + $names = array_filter(array_map('trim', preg_split('/[\r\n,]+/', $names))); + } + if (!is_array($names) || $names === []) { + admin_json(['ok' => false, 'error' => 'Missing field: names'], 400); + } + $names = array_values(array_filter(array_map(fn($n) => trim((string) $n), $names), fn($n) => $n !== '')); + admin_json(admin_api('DELETE', '/chat/room/public', ['names' => $names])); + + case 'im.send': + $from = admin_need((string) ($input['from'] ?? ''), 'from'); + $to = admin_need((string) ($input['to'] ?? ''), 'to'); + $text = admin_need((string) ($input['text'] ?? ''), 'text'); + $storeOffline = filter_var($input['store_offline'] ?? false, FILTER_VALIDATE_BOOLEAN); + admin_json(admin_api('POST', '/instant-message', [ + 'from' => $from, + 'to' => $to, + 'text' => $text, + 'storeOffline' => $storeOffline, + ])); + + case 'popup.send': + $message = admin_need((string) ($input['message'] ?? ''), 'message'); + $body = ['message' => $message]; + $broadcast = filter_var($input['broadcast'] ?? false, FILTER_VALIDATE_BOOLEAN); + if ($broadcast) { + $body['broadcast'] = true; + } else { + $recipients = $input['recipients'] ?? []; + if (is_string($recipients)) { + $recipients = array_filter(array_map('trim', preg_split('/[\r\n,]+/', $recipients))); + } + $recipients = is_array($recipients) ? array_values(array_filter(array_map(fn($r) => trim((string) $r), $recipients), fn($r) => $r !== '')) : []; + if ($recipients === []) { + admin_json(['ok' => false, 'error' => 'Provide recipients or enable broadcast.'], 400); + } + $body['recipients'] = $recipients; + } + if (isset($input['url']) && trim((string) $input['url']) !== '') $body['url'] = trim((string) $input['url']); + if (isset($input['width']) && $input['width'] !== '') $body['width'] = max(0, min(65535, (int) $input['width'])); + if (isset($input['height']) && $input['height'] !== '') $body['height'] = max(0, min(65535, (int) $input['height'])); + admin_json(admin_api('POST', '/popup', $body)); + + case 'directory.categories.list': + admin_json(admin_api('GET', '/directory/category')); + + case 'directory.categories.create': + $name = admin_need((string) ($input['name'] ?? ''), 'name'); + admin_json(admin_api('POST', '/directory/category', ['name' => $name])); + + case 'directory.categories.delete': + $id = (int) ($input['id'] ?? 0); + if ($id <= 0) admin_json(['ok' => false, 'error' => 'Missing field: id'], 400); + admin_json(admin_api('DELETE', '/directory/category/' . $id)); + + case 'directory.keywords.list': + $id = (int) ($input['category_id'] ?? $input['id'] ?? 0); + if ($id <= 0) admin_json(['ok' => false, 'error' => 'Missing field: category_id'], 400); + admin_json(admin_api('GET', '/directory/category/' . $id . '/keyword')); + + case 'directory.keywords.create': + $categoryId = (int) ($input['category_id'] ?? 0); + $name = admin_need((string) ($input['name'] ?? ''), 'name'); + if ($categoryId <= 0) admin_json(['ok' => false, 'error' => 'Missing field: category_id'], 400); + admin_json(admin_api('POST', '/directory/keyword', ['category_id' => $categoryId, 'name' => $name])); + + case 'directory.keywords.delete': + $id = (int) ($input['id'] ?? 0); + if ($id <= 0) admin_json(['ok' => false, 'error' => 'Missing field: id'], 400); + admin_json(admin_api('DELETE', '/directory/keyword/' . $id)); + + case 'directory.aim.list': + admin_json(admin_api('GET', '/directory/aim')); + + case 'users.icon.get': + $screenName = admin_need((string) ($input['screen_name'] ?? ''), 'screen_name'); + $r = admin_api('GET', '/user/' . rawurlencode($screenName) . '/icon'); + if ($r['ok']) { + admin_json(['ok' => true, 'status' => $r['status'], 'data' => ['base64' => base64_encode($r['raw']), 'content_type' => 'image/*']]); + } + admin_json($r); + + case 'bart.list': + $type = $input['type'] ?? null; + if ($type === null || $type === '') admin_json(['ok' => false, 'error' => 'Missing field: type'], 400); + admin_json(admin_api('GET', '/bart', null, ['type' => (int) $type])); + + case 'bart.get': + $hash = admin_need((string) ($input['hash'] ?? ''), 'hash'); + $r = admin_api('GET', '/bart/' . rawurlencode($hash)); + if ($r['ok']) { + admin_json(['ok' => true, 'status' => $r['status'], 'data' => ['base64' => base64_encode($r['raw'])]]); + } + admin_json($r); + + case 'bart.upload': + // BART upload needs raw binary body; admin_api() JSON-encodes bodies, so use curl directly. + $hash = admin_need((string) ($input['hash'] ?? ''), 'hash'); + $type = $input['type'] ?? null; + if ($type === null || $type === '') admin_json(['ok' => false, 'error' => 'Missing field: type'], 400); + $b64 = admin_need((string) ($input['data_base64'] ?? ''), 'data_base64'); + $bin = base64_decode($b64, true); + if ($bin === false) admin_json(['ok' => false, 'error' => 'Invalid base64 data.'], 400); + $url = admin_mgmt_base() . '/bart/' . rawurlencode($hash) . '?type=' . urlencode((string) (int) $type); + $ch = curl_init($url); + curl_setopt_array($ch, [ + CURLOPT_RETURNTRANSFER => true, + CURLOPT_CUSTOMREQUEST => 'POST', + CURLOPT_HTTPHEADER => ['Content-Type: application/octet-stream', 'Accept: application/json'], + CURLOPT_POSTFIELDS => $bin, + CURLOPT_TIMEOUT => 20, + CURLOPT_CONNECTTIMEOUT => 5, + ]); + $raw = curl_exec($ch); + $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE); + $err = curl_error($ch); + curl_close($ch); + if ($raw === false) admin_json(['ok' => false, 'status' => 0, 'error' => $err ?: 'Request failed']); + $decoded = json_decode($raw, true); + $ok = $status >= 200 && $status < 300; + admin_json(['ok' => $ok, 'status' => $status, 'error' => $ok ? null : ($decoded['message'] ?? $raw), 'data' => $decoded, 'raw' => $raw]); + + case 'bart.delete': + $hash = admin_need((string) ($input['hash'] ?? ''), 'hash'); + admin_json(admin_api('DELETE', '/bart/' . rawurlencode($hash))); + + case 'feedbag.bart.set': + $screenName = admin_need((string) ($input['screen_name'] ?? ''), 'screen_name'); + $hash = admin_need((string) ($input['hash'] ?? ''), 'hash'); + $type = $input['type'] ?? null; + if ($type === null || $type === '') admin_json(['ok' => false, 'error' => 'Missing field: type'], 400); + admin_json(admin_api('PUT', '/feedbag/' . rawurlencode($screenName) . '/bart', ['hash' => $hash, 'type' => (int) $type])); + + case 'feedbag.bart.delete': + $screenName = admin_need((string) ($input['screen_name'] ?? ''), 'screen_name'); + $type = $input['type'] ?? null; + if ($type === null || $type === '') admin_json(['ok' => false, 'error' => 'Missing field: type'], 400); + admin_json(admin_api('DELETE', '/feedbag/' . rawurlencode($screenName) . '/bart', null, ['type' => (int) $type])); + + case 'feedbag.groups.list': + $screenName = admin_need((string) ($input['screen_name'] ?? ''), 'screen_name'); + admin_json(admin_api('GET', '/feedbag/' . rawurlencode($screenName) . '/group')); + + case 'feedbag.groups.create': + $screenName = admin_need((string) ($input['screen_name'] ?? ''), 'screen_name'); + $groupName = admin_need((string) ($input['group_name'] ?? ''), 'group_name'); + admin_json(admin_api('PUT', '/feedbag/' . rawurlencode($screenName) . '/group/' . rawurlencode($groupName))); + + case 'feedbag.buddy.add': + $screenName = admin_need((string) ($input['screen_name'] ?? ''), 'screen_name'); + $groupId = (int) ($input['group_id'] ?? 0); + $buddy = admin_need((string) ($input['buddy_screen_name'] ?? ''), 'buddy_screen_name'); + if ($groupId <= 0) admin_json(['ok' => false, 'error' => 'Missing field: group_id'], 400); + admin_json(admin_api('PUT', '/feedbag/' . rawurlencode($screenName) . '/group/' . $groupId . '/buddy/' . rawurlencode($buddy))); + + case 'feedbag.buddy.delete': + $screenName = admin_need((string) ($input['screen_name'] ?? ''), 'screen_name'); + $groupId = (int) ($input['group_id'] ?? 0); + $buddy = admin_need((string) ($input['buddy_screen_name'] ?? ''), 'buddy_screen_name'); + if ($groupId <= 0) admin_json(['ok' => false, 'error' => 'Missing field: group_id'], 400); + admin_json(admin_api('DELETE', '/feedbag/' . rawurlencode($screenName) . '/group/' . $groupId . '/buddy/' . rawurlencode($buddy))); + + case 'linked.list': + $screenName = admin_need((string) ($input['screen_name'] ?? ''), 'screen_name'); + admin_json(admin_api('GET', '/user/' . rawurlencode($screenName) . '/linked-account')); + + case 'linked.add': + $screenName = admin_need((string) ($input['screen_name'] ?? ''), 'screen_name'); + $linked = admin_need((string) ($input['linked_screen_name'] ?? ''), 'linked_screen_name'); + admin_json(admin_api('POST', '/user/' . rawurlencode($screenName) . '/linked-account', ['linked_screen_name' => $linked])); + + case 'linked.delete': + $screenName = admin_need((string) ($input['screen_name'] ?? ''), 'screen_name'); + $linked = admin_need((string) ($input['linked_screen_name'] ?? ''), 'linked_screen_name'); + admin_json(admin_api('DELETE', '/user/' . rawurlencode($screenName) . '/linked-account/' . rawurlencode($linked))); + + case 'audit.list': + $limit = max(1, min(1000, (int) ($input['limit'] ?? 200))); + admin_json(['ok' => true, 'data' => admin_audit_read($limit)]); + + case 'gotify.self.get': + if (!function_exists('admin_gotify_feature_enabled') || !admin_gotify_feature_enabled()) { + admin_json(['ok' => false, 'error' => 'Gotify is not enabled.'], 400); + } + $user = admin_current_user(); + $sn = (string) ($user['screen_name'] ?? ''); + $cfg = admin_gotify_user_get($sn); + admin_json(['ok' => true, 'data' => [ + 'enabled' => true, + 'configured' => $cfg !== null, + 'url' => $cfg['url'] ?? '', + 'token_set' => $cfg !== null && ($cfg['token'] ?? '') !== '', + 'priority' => $cfg['priority'] ?? (int) admin_cfg('gotify_priority', 5), + 'updated_at' => $cfg['updated_at'] ?? '', + ]]); + + case 'gotify.self.save': + if (!function_exists('admin_gotify_feature_enabled') || !admin_gotify_feature_enabled()) { + admin_json(['ok' => false, 'error' => 'Gotify is not enabled.'], 400); + } + $user = admin_current_user(); + $sn = (string) ($user['screen_name'] ?? ''); + $url = trim((string) ($input['url'] ?? '')); + $token = trim((string) ($input['token'] ?? '')); + $priority = isset($input['priority']) ? (int) $input['priority'] : null; + if ($url !== '' && $token === '') { + $existing = admin_gotify_user_get($sn); + if ($existing && !empty($existing['token'])) { + $token = (string) $existing['token']; + } + } + $result = admin_gotify_user_save($sn, $url, $token, $priority); + if (!($result['ok'] ?? false)) { + admin_json(['ok' => false, 'error' => $result['error'] ?? 'Failed to save.'], 400); + } + $cfg = admin_gotify_user_get($sn); + admin_json(['ok' => true, 'data' => [ + 'configured' => $cfg !== null, + 'url' => $cfg['url'] ?? '', + 'token_set' => $cfg !== null && ($cfg['token'] ?? '') !== '', + 'priority' => $cfg['priority'] ?? (int) admin_cfg('gotify_priority', 5), + 'updated_at' => $cfg['updated_at'] ?? '', + 'cleared' => $result['cleared'] ?? false, + ]]); + + case 'gotify.self.test': + if (!function_exists('admin_gotify_feature_enabled') || !admin_gotify_feature_enabled()) { + admin_json(['ok' => false, 'error' => 'Gotify is not enabled.'], 400); + } + $user = admin_current_user(); + $sn = (string) ($user['screen_name'] ?? ''); + $cfg = function_exists('admin_gotify_user_get') ? admin_gotify_user_get($sn) : null; + if (!$cfg) { + admin_json(['ok' => false, 'error' => 'No Gotify configuration saved for your account. Save URL and token first.'], 400); + } + $send = admin_gotify_send_for_user($sn, 'Oscar Admin test', "This is a test notification for {$sn} from Oscar Admin.", $cfg['priority'] ?? null); + if (!($send['ok'] ?? false)) { + admin_json(['ok' => false, 'error' => $send['error'] ?? 'Gotify test failed.'], 400); + } + admin_json(['ok' => true, 'data' => ['sent' => true]]); + + case 'api.raw': + $reqMethod = strtoupper(admin_need((string) ($input['method'] ?? 'GET'), 'method')); + $path = admin_need((string) ($input['path'] ?? ''), 'path'); + if (!str_starts_with($path, '/')) { + $path = '/' . $path; + } + if (!in_array($reqMethod, ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'], true)) { + admin_json(['ok' => false, 'error' => 'Unsupported method.'], 400); + } + $body = null; + if (isset($input['body']) && trim((string) $input['body']) !== '') { + $decoded = json_decode((string) $input['body'], true); + if ($decoded === null && json_last_error() !== JSON_ERROR_NONE) { + admin_json(['ok' => false, 'error' => 'Body must be valid JSON.'], 400); + } + $body = $decoded; + } + admin_json(admin_api($reqMethod, $path, is_array($body) ? $body : null)); + + default: + admin_json(['ok' => false, 'error' => 'Unknown action.'], 400); +} diff --git a/admin.css b/admin.css new file mode 100644 index 0000000..a61b07a --- /dev/null +++ b/admin.css @@ -0,0 +1,421 @@ +/* + * Oscar Admin - standalone styles. + * + * Loaded alongside the bundled shared base stylesheet (assets/style.css, + * configurable via shared_style_path) by admin_page(). Keep this file + * self-contained for admin-specific layout/components. + * + * Sections: tokens/base, layout/nav, components, forms/buttons, tables, + * detail/BART/feedbag helpers, auth, toasts, animations, responsive. + */ +:root { + --bg: #0b1020; + --bg-soft: #121a2f; + --panel: rgba(18, 26, 47, 0.72); + --panel-solid: #141d35; + --panel-2: #1b2742; + --text: #e8eefc; + --muted: #93a4c4; + --accent: #6ea8ff; + --accent-2: #8b7bff; + --ok: #4fd18b; + --warn: #ffcc66; + --danger: #ff6b6b; + --line: rgba(148, 163, 184, 0.16); + --line-strong: rgba(148, 163, 184, 0.28); + --shadow: 0 20px 60px rgba(0, 0, 0, 0.35); + --radius: 16px; + --radius-sm: 10px; + --font: Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Arial, sans-serif; + --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + color-scheme: dark; +} + +* { box-sizing: border-box; } +html, body { margin: 0; padding: 0; min-height: 100%; } +body.admin-body { + font-family: var(--font); + color: var(--text); + background: + radial-gradient(1200px 600px at 10% -10%, rgba(110,168,255,.18), transparent 60%), + radial-gradient(900px 500px at 100% 0%, rgba(139,123,255,.14), transparent 55%), + linear-gradient(180deg, #090e1a 0%, #0b1020 100%); + overflow-x: hidden; +} +a { color: var(--accent); } +code { font-family: var(--mono); font-size: .92em; background: rgba(255,255,255,.06); padding: .15em .4em; border-radius: 4px; } + +.bg-orb { position: fixed; border-radius: 50%; filter: blur(60px); pointer-events: none; z-index: 0; opacity: .55; } +.orb-a { width: 420px; height: 420px; top: -120px; left: -80px; background: rgba(110,168,255,.22); animation: float 14s ease-in-out infinite, hueDrift 20s ease-in-out infinite; } +.orb-b { width: 360px; height: 360px; top: 20%; right: -100px; background: rgba(139,123,255,.18); animation: float 18s ease-in-out infinite reverse, hueDrift 24s ease-in-out infinite reverse; } +.bg-grid { + position: fixed; inset: 0; pointer-events: none; z-index: 0; + background-image: linear-gradient(rgba(255,255,255,.02) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,.02) 1px, transparent 1px); + background-size: 32px 32px; + mask-image: radial-gradient(ellipse 70% 60% at 50% 20%, black, transparent); + animation: gridPan 30s linear infinite; +} +.bg-grid::after { + content: ''; position: absolute; inset: 0; + background: linear-gradient(120deg, transparent 30%, rgba(110,168,255,.04) 50%, transparent 70%); + background-size: 200% 200%; + animation: shimmerBg 12s ease-in-out infinite; +} + +.admin-topbar { + position: sticky; top: 0; z-index: 50; + display: flex; align-items: center; justify-content: space-between; gap: 1rem; + padding: .65rem 1.25rem; + background: rgba(11, 16, 32, 0.72); + backdrop-filter: blur(16px); + border-bottom: 1px solid var(--line); +} +.admin-brand { display: flex; align-items: center; gap: .85rem; } +.brand-mark { + width: 42px; height: 42px; display: grid; place-items: center; border-radius: 12px; + background: linear-gradient(135deg, rgba(110,168,255,.25), rgba(139,123,255,.2)); + border: 1px solid rgba(110,168,255,.3); + color: var(--accent); + box-shadow: 0 0 0 4px rgba(110,168,255,.06); +} +.brand-mark svg { width: 22px; height: 22px; } +.brand-title { font-weight: 700; font-size: 1.05rem; letter-spacing: -.01em; } +.brand-sub { font-size: .78rem; color: var(--muted); } +.admin-nav { display: flex; align-items: center; gap: .75rem; } +.admin-nav a { color: var(--muted); text-decoration: none; padding: .5rem .75rem; border-radius: 8px; font-size: .9rem; } +.admin-nav a:hover, .admin-nav a.active { color: var(--text); background: rgba(255,255,255,.05); } +.nav-user { color: var(--muted); font-size: .85rem; padding: .35rem .65rem; border: 1px solid var(--line); border-radius: 999px; background: rgba(255,255,255,.03); max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.user-menu { position: relative; } +.user-menu-trigger { display: inline-flex; align-items: center; gap: .35rem; cursor: pointer; font: inherit; color: var(--muted); font-size: .85rem; padding: .35rem .65rem; border: 1px solid var(--line); border-radius: 999px; background: rgba(255,255,255,.03); max-width: 220px; } +.user-menu-trigger:hover { color: var(--text); border-color: var(--line-strong); background: rgba(255,255,255,.05); } +.user-menu-trigger span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.user-menu-dropdown { position: absolute; top: calc(100% + .5rem); right: 0; width: min(340px, calc(100vw - 2rem)); background: linear-gradient(180deg, rgba(24,35,61,.98), rgba(16,24,43,.98)); border: 1px solid var(--line-strong); border-radius: 14px; box-shadow: 0 20px 50px rgba(0,0,0,.45); padding: .75rem; z-index: 200; } +.user-menu-dropdown[hidden] { display: none !important; } +.user-menu-head { padding: .25rem .25rem .6rem; border-bottom: 1px solid var(--line); margin-bottom: .6rem; } +.user-menu-name { font-weight: 650; font-size: .95rem; } +.user-menu-section { padding: .25rem 0; } +.user-menu-section + .user-menu-section { border-top: 1px solid var(--line); margin-top: .6rem; padding-top: .75rem; } +.user-menu-section-title { font-size: .72rem; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); font-weight: 700; margin-bottom: .5rem; display: flex; align-items: center; gap: .25rem; } +.user-menu-actions .btn-block { width: 100%; } +.inline-form { margin: 0; } + +.admin-main { position: relative; z-index: 1; width: min(1400px, calc(100% - 2rem)); margin: 0 auto; padding: 1rem 0 2rem; } + +/* Buttons */ +.btn { + appearance: none; border: 1px solid var(--line-strong); background: rgba(255,255,255,.04); color: var(--text); + padding: .65rem 1rem; border-radius: 10px; font: inherit; font-size: .9rem; font-weight: 550; cursor: pointer; + display: inline-flex; align-items: center; justify-content: center; gap: .5rem; text-decoration: none; + transition: transform .15s ease, background .2s ease, border-color .2s ease, box-shadow .2s ease; +} +.btn:hover { background: rgba(255,255,255,.08); border-color: rgba(148,163,184,.4); transform: translateY(-1px); } +.btn:active { transform: translateY(0); } +.btn:disabled { opacity: .55; cursor: not-allowed; transform: none; } +.btn svg { width: 16px; height: 16px; } +.btn-primary { + position: relative; overflow: hidden; + background: linear-gradient(135deg, rgba(110,168,255,.95), rgba(139,123,255,.95)); + border-color: transparent; color: #08101f; font-weight: 650; + box-shadow: 0 8px 24px rgba(110,168,255,.25); +} +.btn-primary::after { + content: ''; position: absolute; top: 0; left: 0; width: 40%; height: 100%; + background: linear-gradient(90deg, transparent, rgba(255,255,255,.35), transparent); + transform: translateX(-120%) skewX(-15deg); +} +.btn-primary:hover { filter: brightness(1.06); box-shadow: 0 10px 30px rgba(110,168,255,.32); } +.btn-primary:hover::after { animation: sheen .7s ease; } +.btn-danger { background: rgba(255,107,107,.12); border-color: rgba(255,107,107,.35); color: #ffb3b3; } +.btn-danger:hover { background: rgba(255,107,107,.18); } +.btn-ghost { background: transparent; } +.btn-small { padding: .4rem .7rem; font-size: .82rem; border-radius: 8px; } +.btn-block { width: 100%; } + +/* Hero */ +.hero { + display: flex; align-items: flex-end; justify-content: space-between; gap: 1rem; margin: .5rem 0 1rem; +} +.eyebrow { font-size: .72rem; font-weight: 700; letter-spacing: .12em; text-transform: uppercase; color: var(--accent); margin-bottom: .2rem; } +.hero h1 { margin: 0; font-size: clamp(1.6rem, 3vw, 2.2rem); line-height: 1.1; letter-spacing: -.03em; } +.hero p { margin: .35rem 0 0; max-width: 60ch; font-size: .92rem; } +.hero-actions { display: flex; align-items: center; gap: .75rem; flex-wrap: wrap; } +.muted { color: var(--muted); } + +.status-chip { + display: inline-flex; align-items: center; gap: .5rem; padding: .5rem .8rem; border-radius: 999px; + background: rgba(255,255,255,.04); border: 1px solid var(--line); font-size: .82rem; color: var(--muted); +} +.status-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--warn); box-shadow: 0 0 0 4px rgba(255,204,102,.12); } +.status-chip.ok .status-dot { background: var(--ok); box-shadow: 0 0 0 4px rgba(79,209,139,.12); } +.status-chip.bad .status-dot { background: var(--danger); box-shadow: 0 0 0 4px rgba(255,107,107,.12); } + +/* Stats */ +.stats-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: .75rem; margin-bottom: 1rem; } +.stat-card { + display: flex; gap: .75rem; align-items: flex-start; padding: .85rem 1rem; + background: var(--panel); border: 1px solid var(--line); border-radius: 12px; + backdrop-filter: blur(10px); box-shadow: var(--shadow); + transition: transform .2s ease, border-color .2s ease; +} +.stat-card:hover { transform: translateY(-3px); border-color: rgba(110,168,255,.25); box-shadow: 0 20px 60px rgba(0,0,0,.35), 0 0 24px rgba(110,168,255,.08); } +.stat-icon { + width: 38px; height: 38px; border-radius: 10px; display: grid; place-items: center; + background: linear-gradient(135deg, rgba(110,168,255,.16), rgba(139,123,255,.12)); color: var(--accent); + flex-shrink: 0; +} +.stat-icon svg { width: 20px; height: 20px; } +.stat-label { font-size: .72rem; color: var(--muted); text-transform: uppercase; letter-spacing: .06em; } +.stat-value { font-size: 1.45rem; font-weight: 700; line-height: 1.2; margin: .1rem 0; letter-spacing: -.02em; } +.stat-sub { font-size: .75rem; } + +/* Panels / tabs */ +.panel { + background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); + backdrop-filter: blur(10px); box-shadow: var(--shadow); overflow: hidden; +} +.tab-bar { display: flex; gap: .2rem; padding: .5rem .75rem; border-bottom: 1px solid var(--line); overflow-x: auto; background: rgba(0,0,0,.08); } +.tab { + appearance: none; background: transparent; border: 0; color: var(--muted); font: inherit; font-size: .85rem; font-weight: 550; + padding: .5rem .75rem; border-radius: 8px; cursor: pointer; white-space: nowrap; transition: all .2s ease; position: relative; +} +.tab:hover { color: var(--text); background: rgba(255,255,255,.04); } +.tab.active { color: var(--text); background: rgba(110,168,255,.12); } +.tab.active::after { + content: ''; position: absolute; left: 1rem; right: 1rem; bottom: .35rem; height: 2px; border-radius: 2px; + background: linear-gradient(90deg, var(--accent), var(--accent-2)); +} +.tab-panels { padding: .85rem 1rem; } +.tab-panel { display: none; } +.tab-panel.active { display: block; animation: fadeIn .25s ease; } + +.panel-head { display: flex; align-items: flex-start; justify-content: space-between; gap: .75rem; margin-bottom: .75rem; } +.panel-head h2, .panel-head h3 { margin: 0; font-size: 1.05rem; letter-spacing: -.01em; } +.panel-head p { margin: .15rem 0 0; font-size: .84rem; } +.subhead { font-size: .88rem; margin: 0 0 .5rem; color: var(--muted); font-weight: 600; } + +/* Cards/forms */ +.card.subcard { + background: rgba(255,255,255,.02); border: 1px solid var(--line); border-radius: 10px; padding: .75rem; +} +.subcard h3 { margin: 0 0 .6rem; font-size: .92rem; } +.split-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: .75rem; margin-bottom: .75rem; } +.room-columns { display: grid; grid-template-columns: repeat(2, 1fr); gap: .75rem; } +.stack-form { display: flex; flex-direction: column; gap: .65rem; } +.stack-form.compact { gap: .5rem; } +.field { display: flex; flex-direction: column; gap: .25rem; } +.field span, .field label { font-size: .82rem; color: var(--muted); font-weight: 550; } +.field input, .field textarea, .field select, .input { + width: 100%; padding: .5rem .65rem; border-radius: 8px; border: 1px solid var(--line-strong); + background: rgba(0,0,0,.18); color: var(--text); font: inherit; font-size: .88rem; + transition: border-color .2s ease, box-shadow .2s ease; +} +.field input:focus, .field textarea:focus, .field select:focus, .input:focus { + outline: none; border-color: rgba(110,168,255,.55); box-shadow: 0 0 0 4px rgba(110,168,255,.12); +} +.field textarea { resize: vertical; min-height: 70px; } +.field-row { display: grid; grid-template-columns: 1fr 1fr; gap: .75rem; } +.check { display: flex; gap: .55rem; align-items: flex-start; font-size: .88rem; color: var(--muted); } +.check input { margin-top: .2rem; accent-color: var(--accent); } +.table-tools { margin-bottom: .5rem; } +.table-tools .input { max-width: 320px; } +.users-toolbar { display: flex; gap: .5rem; align-items: center; flex-wrap: wrap; } +.users-toolbar .input { max-width: 240px; } +.bulk-actions { display: flex; gap: .4rem; align-items: center; flex-wrap: wrap; margin-left: auto; } +.bulk-actions .input { width: auto; max-width: 160px; } +.auto-refresh-toggle { font-size: .82rem; color: var(--muted); margin: 0; white-space: nowrap; } +.inline-controls { display: flex; gap: .5rem; align-items: center; } +.inline-controls .input { width: 140px; } + +/* Code block */ +.code-block { + margin: 0; padding: 1rem; border-radius: 10px; border: 1px solid var(--line); + background: rgba(0,0,0,.25); color: #cfe0ff; font-family: var(--mono); font-size: .82rem; + line-height: 1.6; overflow: auto; max-height: 420px; white-space: pre-wrap; word-break: break-word; +} + +/* Tooltips */ +.tip { + display: inline-flex; align-items: center; justify-content: center; + width: 16px; height: 16px; margin-left: .35rem; border-radius: 50%; + background: rgba(110,168,255,.14); border: 1px solid rgba(110,168,255,.28); + color: var(--accent); font-size: .65rem; font-weight: 700; line-height: 1; + cursor: help; vertical-align: middle; position: relative; flex-shrink: 0; +} +.tip:hover, .tip:focus { background: rgba(110,168,255,.22); outline: none; } +.tip::after { + content: attr(data-tip); position: absolute; left: 50%; bottom: calc(100% + 8px); + transform: translateX(calc(-50% + var(--tip-shift, 0px))) translateY(4px); width: max-content; max-width: 260px; + padding: .5rem .65rem; border-radius: 8px; background: #18233d; color: var(--text); + border: 1px solid var(--line-strong); box-shadow: 0 10px 30px rgba(0,0,0,.35); + font-size: .74rem; font-weight: 500; line-height: 1.45; text-transform: none; letter-spacing: normal; + white-space: normal; opacity: 0; pointer-events: none; transition: opacity .15s ease, transform .15s ease; z-index: 500; +} +.tip::before { + content: ''; position: absolute; left: 50%; bottom: calc(100% + 3px); + transform: translateX(calc(-50% + var(--tip-shift, 0px))) translateY(4px); border: 5px solid transparent; border-top-color: #18233d; + opacity: 0; pointer-events: none; transition: opacity .15s ease, transform .15s ease; z-index: 501; +} +.tip:hover::after, .tip:focus::after, .tip:hover::before, .tip:focus::before { opacity: 1; transform: translateX(calc(-50% + var(--tip-shift, 0px))) translateY(0); } +.label-row { display: inline-flex; align-items: center; gap: .25rem; } + +/* BART layout */ +.bart-layout { display: grid; grid-template-columns: minmax(280px, 360px) minmax(0, 1fr); gap: .75rem; align-items: start; } +.bart-rail { position: sticky; top: .75rem; max-height: calc(100vh - 1.5rem); overflow: hidden; display: flex; flex-direction: column; } +.bart-rail .bart-type-catalog { flex: 1; min-height: 0; max-height: none; overflow: auto; } +.bart-main { display: grid; gap: .75rem; min-width: 0; } +@media (max-width: 1100px) { + .bart-layout { grid-template-columns: 1fr; } + .bart-rail { position: static; max-height: none; } +} + +/* BART catalog */ +.bart-type-catalog { display: grid; gap: .75rem; max-height: 60vh; overflow: auto; padding-right: .15rem; } +.bart-group-title { font-size: .7rem; text-transform: uppercase; letter-spacing: .07em; color: var(--muted); font-weight: 700; margin-bottom: .35rem; } +.bart-group-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(170px, 1fr)); gap: .45rem; } +.bart-type-card { text-align: left; padding: .6rem .7rem; border-radius: 10px; border: 1px solid var(--line); background: rgba(255,255,255,.02); color: var(--text); cursor: pointer; transition: all .18s ease; } +.bart-type-card:hover { border-color: rgba(110,168,255,.3); background: rgba(110,168,255,.05); transform: translateY(-1px); } +.bart-type-card.selected { border-color: rgba(110,168,255,.55); background: rgba(110,168,255,.1); box-shadow: inset 0 0 0 1px rgba(110,168,255,.2); } +.bart-type-top { display: flex; align-items: center; justify-content: space-between; margin-bottom: .2rem; } +.bart-type-icon { font-size: 1rem; line-height: 1; } +.bart-type-id { font-size: .68rem; color: var(--accent); font-weight: 700; font-family: var(--mono); } +.bart-type-name { font-size: .83rem; font-weight: 650; margin: .05rem 0; } +.bart-type-desc { font-size: .71rem; color: var(--muted); line-height: 1.35; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } +.bart-type-info { padding: .55rem .7rem; border-radius: 9px; background: rgba(110,168,255,.06); border: 1px solid rgba(110,168,255,.12); font-size: .8rem; } +.bart-type-info:empty { display: none; } +.bart-selected-type { display: flex; gap: .6rem; align-items: flex-start; } +.bart-selected-icon { font-size: 1.3rem; line-height: 1; margin-top: .05rem; } +.bart-browse-status { font-size: .78rem; color: var(--muted); min-height: 1.2em; margin-top: .35rem; } +.bart-browse-status:empty { display: none; } +.bart-upload-purpose { margin-bottom: .65rem; } +.bart-purpose { padding: .7rem .85rem; border-radius: 10px; background: linear-gradient(135deg, rgba(110,168,255,.12), rgba(92,214,166,.06)); border: 1px solid rgba(110,168,255,.2); } +.bart-purpose-label { font-size: .67rem; text-transform: uppercase; letter-spacing: .07em; color: var(--accent); font-weight: 700; margin-bottom: .15rem; } +.bart-purpose-name { font-size: .95rem; font-weight: 650; display: flex; align-items: center; gap: .35rem; flex-wrap: wrap; } +.bart-purpose-icon { font-size: 1.1rem; } + +/* Detail view */ +.detail-view { + padding: 0; border-radius: 0; border: 0; + background: transparent; color: var(--text); font-size: .84rem; line-height: 1.5; + overflow: visible; max-height: none; +} +.kv-grid { display: grid; gap: .35rem; } +.kv-row { display: grid; grid-template-columns: minmax(140px, 220px) 1fr; gap: .5rem; padding: .35rem .5rem; border-radius: 8px; background: rgba(255,255,255,.02); border: 1px solid rgba(148,163,184,.08); } +.kv-k { color: var(--muted); font-size: .75rem; text-transform: uppercase; letter-spacing: .04em; font-weight: 650; align-self: start; padding-top: .1rem; word-break: break-word; } +.kv-v { min-width: 0; word-break: break-word; } +.kv-v .mono { font-size: .82rem; } +.detail-section { margin-top: .6rem; } +.detail-section-title { font-size: .72rem; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); font-weight: 700; margin-bottom: .35rem; } +.detail-list { display: grid; gap: .4rem; } +.detail-card { padding: .55rem .65rem; border-radius: 8px; border: 1px solid rgba(148,163,184,.1); background: rgba(255,255,255,.02); } +.detail-empty { color: var(--muted); font-style: italic; } +.bool-yes { color: #8fe0b5; } +.bool-no { color: var(--muted); } +.audit-details .kv-grid { gap: .2rem; } +.audit-details .kv-row { grid-template-columns: 120px 1fr; padding: .2rem .35rem; font-size: .78rem; } +.audit-details .detail-list { gap: .25rem; } + +.detail-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: .6rem; margin-bottom: .75rem; } +.detail-stat { padding: .7rem .8rem; border-radius: 10px; background: rgba(255,255,255,.03); border: 1px solid var(--line); } +.detail-stat-label { font-size: .68rem; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); font-weight: 700; } +.detail-stat-value { font-size: 1.1rem; font-weight: 700; margin-top: .15rem; letter-spacing: -.01em; } +.detail-stat-sub { font-size: .75rem; color: var(--muted); margin-top: .1rem; } +.detail-info-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: .5rem; margin-bottom: .75rem; } +.detail-info-item { padding: .55rem .7rem; border-radius: 9px; background: rgba(255,255,255,.02); border: 1px solid rgba(148,163,184,.08); } +.detail-info-label { font-size: .67rem; text-transform: uppercase; letter-spacing: .05em; color: var(--muted); font-weight: 700; margin-bottom: .15rem; } +.detail-info-value { font-size: .88rem; word-break: break-word; } +.instance-list { display: grid; gap: .6rem; } +.instance-card { padding: .75rem; border-radius: 10px; border: 1px solid var(--line); background: rgba(255,255,255,.02); } +.instance-head { display: flex; align-items: center; justify-content: space-between; gap: .5rem; margin-bottom: .5rem; } +.instance-title { font-weight: 650; font-size: .88rem; } +.tag-row { display: flex; gap: .35rem; flex-wrap: wrap; } + +/* Tables */ +.table-wrap { overflow: auto; border: 1px solid var(--line); border-radius: 12px; background: rgba(0,0,0,.12); } +.data-table { width: 100%; border-collapse: collapse; font-size: .88rem; } +.data-table th, .data-table td { padding: .45rem .65rem; text-align: left; border-bottom: 1px solid rgba(148,163,184,.1); vertical-align: middle; } +.data-table th { font-size: .7rem; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); font-weight: 650; background: rgba(255,255,255,.02); position: sticky; top: 0; } +.data-table tbody tr { transition: background .15s ease; } +.data-table tbody tr:hover { background: rgba(110,168,255,.04); } +.data-table tbody tr:last-child td { border-bottom: 0; } +.empty-cell { text-align: center; color: var(--muted); padding: 2rem 1rem !important; } +.actions-cell { white-space: nowrap; display: flex; gap: .4rem; flex-wrap: wrap; } +.pill { display: inline-flex; align-items: center; padding: .2rem .55rem; border-radius: 999px; font-size: .72rem; font-weight: 650; border: 1px solid transparent; } +.pill-ok { color: #8fe0b5; background: rgba(79,209,139,.12); border-color: rgba(79,209,139,.2); } +.pill-warn { color: #ffe0a3; background: rgba(255,204,102,.12); border-color: rgba(255,204,102,.2); } +.pill-bad { color: #ffb3b3; background: rgba(255,107,107,.12); border-color: rgba(255,107,107,.2); } +.pill-muted { color: var(--muted); background: rgba(148,163,184,.1); border-color: rgba(148,163,184,.15); } +.mono { font-family: var(--mono); font-size: .85em; } + +/* Auth */ +.auth-wrap { display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; align-items: stretch; min-height: calc(100vh - 180px); padding: 1.5rem 0; } +.auth-card, .side-card { background: var(--panel); border: 1px solid var(--line); border-radius: 20px; padding: 2rem; backdrop-filter: blur(12px); box-shadow: var(--shadow); } +.auth-card { animation: borderGlow 6s ease-in-out infinite; } +.auth-head h1 { margin: 0; font-size: 2rem; letter-spacing: -.02em; } +.auth-head p { margin: .5rem 0 1.5rem; } +.auth-foot { margin-top: 1.5rem; padding-top: 1rem; border-top: 1px solid var(--line); font-size: .85rem; display: flex; align-items: center; gap: .5rem; } +.auth-foot .dot { width: 6px; height: 6px; border-radius: 50%; background: var(--accent); } +.pulse-dot { animation: pulseRing 2s ease-out infinite; } +.pending-box { padding: 1rem; border-radius: 12px; background: rgba(110,168,255,.08); border: 1px solid rgba(110,168,255,.18); margin-bottom: 1rem; } +.pending-label { font-size: .75rem; color: var(--muted); text-transform: uppercase; letter-spacing: .06em; } +.pending-name { font-size: 1.25rem; font-weight: 700; margin: .2rem 0; } +.pending-expiry { font-size: .82rem; } +.reset-row { margin-top: .75rem; } +.side-card { display: flex; flex-direction: column; justify-content: center; background: linear-gradient(160deg, rgba(110,168,255,.08), rgba(20,29,53,.6)); } +.side-card h2 { margin: 0 0 1.25rem; font-size: 1.3rem; } +.step-list { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 1.25rem; } +.step-list li { display: flex; gap: 1rem; align-items: flex-start; } +.step-num { width: 32px; height: 32px; border-radius: 50%; display: grid; place-items: center; background: rgba(110,168,255,.15); color: var(--accent); font-weight: 700; font-size: .85rem; flex-shrink: 0; } +.step-list strong { display: block; margin-bottom: .15rem; } +.step-list p { margin: 0; font-size: .9rem; } + +/* Flashes/toasts */ +.flash { padding: .8rem 1rem; border-radius: 10px; margin-bottom: 1rem; font-size: .9rem; border: 1px solid transparent; } +.flash-error { background: rgba(255,107,107,.1); border-color: rgba(255,107,107,.25); color: #ffbdbd; } +.flash-success { background: rgba(79,209,139,.1); border-color: rgba(79,209,139,.25); color: #b7efd0; } +.flash-info { background: rgba(110,168,255,.1); border-color: rgba(110,168,255,.25); color: #c7dcff; } + +#toast-container { position: fixed; right: 1rem; bottom: 1rem; display: flex; flex-direction: column; gap: .6rem; z-index: 200; width: min(360px, calc(100vw - 2rem)); } +.toast { + padding: .85rem 1rem; border-radius: 12px; background: #18233d; border: 1px solid var(--line-strong); color: var(--text); + box-shadow: 0 10px 30px rgba(0,0,0,.35); font-size: .88rem; animation: toastIn .3s ease; +} +.toast.success { border-color: rgba(79,209,139,.35); } +.toast.error { border-color: rgba(255,107,107,.35); } +.toast.out { animation: toastOut .25s ease forwards; } + +/* Animations */ +.reveal { animation: riseIn .5s ease both; } +.delay-1 { animation-delay: .08s; } +.delay-2 { animation-delay: .16s; } +@keyframes riseIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } } +@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } +@keyframes float { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-16px); } } +@keyframes toastIn { from { opacity: 0; transform: translateY(12px) scale(.96); } to { opacity: 1; transform: translateY(0) scale(1); } } +@keyframes toastOut { from { opacity: 1; transform: translateY(0); } to { opacity: 0; transform: translateY(10px); } } +@keyframes hueDrift { 0%,100% { filter: blur(60px) hue-rotate(0deg); } 50% { filter: blur(60px) hue-rotate(25deg); } } +@keyframes gridPan { from { background-position: 0 0, 0 0; } to { background-position: 32px 32px, 32px 32px; } } +@keyframes shimmerBg { 0%,100% { background-position: 0% 50%; opacity: .4; } 50% { background-position: 100% 50%; opacity: 1; } } +@keyframes pulseRing { 0% { box-shadow: 0 0 0 0 rgba(110,168,255,.45); } 70% { box-shadow: 0 0 0 8px rgba(110,168,255,0); } 100% { box-shadow: 0 0 0 0 rgba(110,168,255,0); } } +@keyframes borderGlow { 0%,100% { border-color: rgba(110,168,255,.18); box-shadow: 0 20px 60px rgba(0,0,0,.35), 0 0 0 1px rgba(110,168,255,.05); } 50% { border-color: rgba(139,123,255,.3); box-shadow: 0 20px 60px rgba(0,0,0,.35), 0 0 30px rgba(110,168,255,.08); } } +@keyframes sheen { from { transform: translateX(-120%) skewX(-15deg); } to { transform: translateX(220%) skewX(-15deg); } } + +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important; scroll-behavior: auto !important; } +} + +/* Responsive */ +@media (max-width: 1100px) { + .stats-grid { grid-template-columns: repeat(2, 1fr); } +} +@media (max-width: 900px) { + .auth-wrap, .split-grid, .room-columns { grid-template-columns: 1fr; } + .hero { flex-direction: column; align-items: stretch; } +} +@media (max-width: 700px) { + .admin-topbar { flex-direction: column; align-items: stretch; } + .admin-nav { justify-content: space-between; flex-wrap: wrap; } + .stats-grid { grid-template-columns: 1fr; } + .admin-main { width: min(100% - 1rem, 1400px); } + .tab-panels { padding: 1rem; } + .data-table th, .data-table td { padding: .6rem; } +} diff --git a/admin.js b/admin.js new file mode 100644 index 0000000..0968234 --- /dev/null +++ b/admin.js @@ -0,0 +1,1024 @@ +/** + * Oscar Admin dashboard JS. + * + * Single-file client for index.php dashboard: + * - api(action, payload, method): POST/GET to action.php + * - toast/animateValue helpers + * - Detail renderers for sessions/users/generic JSON + * - Overview/users/sessions/rooms/directory renderers + * - BART catalog/browse/upload helpers + * - Buddy list (feedbag) helpers + * - Audit + API console + auto-refresh wiring + * + * The script is defensive: most handlers check for element presence so it can be + * safely loaded on pages that share admin_page() layout. + */ +(() => { + const CSRF = window.ADMIN_CSRF || ''; + const $ = (s, r = document) => r.querySelector(s); + const $$ = (s, r = document) => Array.from(r.querySelectorAll(s)); + + function esc(str) { + return String(str ?? '') + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); + } + + function toast(msg, type = 'info', ms = 3200) { + const box = $('#toast-container'); + if (!box) return; + const el = document.createElement('div'); + el.className = `toast ${type}`; + el.textContent = msg; + box.appendChild(el); + setTimeout(() => { + el.classList.add('out'); + el.addEventListener('animationend', () => el.remove(), { once: true }); + }, ms); + } + + function animateValue(el, to) { + if (!el) return; + const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches; + const target = Number(to); + if (!Number.isFinite(target) || reduce) { el.textContent = String(to); return; } + const from = Number(el.textContent.replace(/[^0-9.-]/g, '')) || 0; + const start = performance.now(); + const dur = 500; + const step = (now) => { + const p = Math.min(1, (now - start) / dur); + const ease = 1 - Math.pow(1 - p, 3); + el.textContent = String(Math.round(from + (target - from) * ease)); + if (p < 1) requestAnimationFrame(step); + }; + requestAnimationFrame(step); + } + + function fmtVal(v) { + if (v === null || v === undefined || v === '') return '—'; + if (typeof v === 'boolean') return v ? 'true' : 'false'; + if (typeof v === 'number') return `${esc(v)}`; + if (typeof v === 'string') return esc(v); + if (Array.isArray(v)) { + if (!v.length) return 'empty'; + if (v.every(x => ['string','number','boolean'].includes(typeof x) || x === null)) { + return v.map(x => `${esc(String(x))}`).join(' '); + } + return `
${v.map(x => `
${renderDetailHtml(x)}
`).join('')}
`; + } + if (typeof v === 'object') return renderDetailHtml(v); + return esc(String(v)); + } + + function renderDetailHtml(data) { + if (data === null || data === undefined) return '—'; + if (['string','number','boolean'].includes(typeof data)) return fmtVal(data); + if (Array.isArray(data)) return fmtVal(data); + if (typeof data === 'object') { + const entries = Object.entries(data); + if (!entries.length) return 'empty'; + return `
${entries.map(([k,v]) => `
${esc(k.replace(/_/g,' '))}
${fmtVal(v)}
`).join('')}
`; + } + return esc(String(data)); + } + + function setDetail(id, data) { + const el = typeof id === 'string' ? document.getElementById(id) : id; + if (!el) return; + if (typeof data === 'string') { el.textContent = data; return; } + el.innerHTML = renderDetailHtml(data); + } + + function boolPill(v, trueLabel='Yes', falseLabel='No') { + return v ? `${esc(trueLabel)}` : `${esc(falseLabel)}`; + } + + function renderSessionDetailHtml(data) { + const s = (data && Array.isArray(data.sessions) && data.sessions[0]) ? data.sessions[0] : data; + if (!s || typeof s !== 'object') return renderDetailHtml(data); + const instances = Array.isArray(s.instances) ? s.instances : []; + const away = !!(s.is_away || s.away_message); + return ` +
+
Online
${esc(fmtSeconds(s.online_seconds))}
+
Idle
${esc(fmtSeconds(s.idle_seconds))}
+
Instances
${esc(s.instance_count ?? instances.length)}
+
Status
${away ? 'Away' : 'Active'}
+
+
+
Screen name
${esc(s.screen_name || s.id || '—')}
+
Account type
${s.is_icq ? 'ICQ' : 'AIM'}
+
Invisible
${boolPill(!!s.is_invisible)}
+
Away message
${s.away_message ? esc(s.away_message) : 'None'}
+
+
+
Instances
+
${instances.length ? instances.map(inst => ` +
+
+
Instance #${esc(inst.num ?? '?')}
+
${inst.is_away ? 'Away' : 'Active'}${inst.is_invisible ? 'Invisible' : ''}
+
+
+
Client
${esc(inst.client_id || '—')}
+
Remote address
${esc(inst.remote_addr || '—')}${inst.remote_port ? ':' + esc(inst.remote_port) : ''}
+
Idle
${esc(fmtSeconds(inst.idle_seconds))}
+
Away message
${inst.away_message ? esc(inst.away_message) : 'None'}
+
+
`).join('') : '
No instance data.
'} +
+
`; + } + + function renderUserDetailHtml(data) { + if (!data || typeof data !== 'object') return renderDetailHtml(data); + return ` +
+
Type
${data.is_icq ? 'ICQ' : 'AIM'}
+
Status
${data.suspended_status ? `${esc(data.suspended_status)}` : 'Active'}
+
Bot
${boolPill(!!data.is_bot)}
+
Confirmed
${boolPill(!!data.confirmed)}
+
+
+
Screen name
${esc(data.screen_name || '—')}
+
ID
${esc(data.id || '—')}
+
Email
${data.email_address ? esc(data.email_address) : 'None'}
+
Profile
${data.profile ? esc(String(data.profile)).slice(0,120) : 'None'}
+
`; + } + + async function api(action, data = {}, method = 'POST') { + const opts = { method, headers: {} }; + if (method === 'GET') { + const url = new URL('action.php', window.location.href); + url.searchParams.set('action', action); + for (const [k, v] of Object.entries(data)) { + if (v !== undefined && v !== null) url.searchParams.set(k, v); + } + const res = await fetch(url.toString(), { credentials: 'same-origin' }); + return res.json(); + } + opts.headers['Content-Type'] = 'application/json'; + opts.body = JSON.stringify({ action, csrf: CSRF, ...data }); + opts.credentials = 'same-origin'; + const res = await fetch('action.php', opts); + return res.json(); + } + + function fmtSeconds(s) { + s = Number(s || 0); + if (s < 60) return `${s}s`; + if (s < 3600) return `${Math.floor(s / 60)}m ${s % 60}s`; + const h = Math.floor(s / 3600); + const m = Math.floor((s % 3600) / 60); + return `${h}h ${m}m`; + } + + function setStatus(ok, text) { + const chip = $('#api-status-chip'); + if (!chip) return; + chip.classList.toggle('ok', !!ok); + chip.classList.toggle('bad', ok === false); + chip.querySelector('.status-text').textContent = text; + } + + // Tabs + $$('.tab').forEach(tab => { + tab.addEventListener('click', () => { + $$('.tab').forEach(t => t.classList.remove('active')); + $$('.tab-panel').forEach(p => p.classList.remove('active')); + tab.classList.add('active'); + const panel = $(`.tab-panel[data-panel="${tab.dataset.tab}"]`); + if (panel) panel.classList.add('active'); + }); + }); + + // Overview + let usersCache = []; + + async function loadOverview() { + setStatus(null, 'Checking...'); + try { + const data = await api('overview', {}, 'GET'); + if (!data.ok) throw new Error(data.error || 'Overview failed'); + renderOverview(data); + setStatus(true, 'API connected'); + } catch (e) { + console.error(e); + setStatus(false, 'API error'); + toast('Failed to load overview: ' + (e.message || e), 'error'); + } + } + + function renderOverview(data) { + const v = data.version || {}; + const vData = v.data || {}; + $('#stat-version').textContent = v.ok ? (vData.version || 'OK') : '—'; + $('#stat-version-sub').textContent = v.ok ? [vData.commit ? String(vData.commit).slice(0, 8) : null, vData.date ? String(vData.date).slice(0, 10) : null].filter(Boolean).join(' · ') || 'Version' : (v.error || 'Unavailable'); + + const sess = data.sessions || {}; + const sessData = sess.data || {}; + const sessList = Array.isArray(sessData.sessions) ? sessData.sessions : (Array.isArray(sessData) ? sessData : []); + if (sess.ok) animateValue($('#stat-sessions'), sessData.count ?? sessList.length); + else $('#stat-sessions').textContent = '—'; + $('#stat-sessions-sub').textContent = sess.ok ? 'Active now' : (sess.error || 'Unavailable'); + renderSessions(sessList); + + const users = data.users || {}; + usersCache = users.ok && Array.isArray(users.data) ? users.data : []; + if (users.ok) animateValue($('#stat-users'), usersCache.length); + else $('#stat-users').textContent = '—'; + $('#stat-users-sub').textContent = users.ok ? 'Registered accounts' : (users.error || 'Unavailable'); + renderUsers(usersCache); + + const pub = data.public_rooms || {}; + const priv = data.private_rooms || {}; + const pubList = pub.ok && Array.isArray(pub.data) ? pub.data : []; + const privList = priv.ok && Array.isArray(priv.data) ? priv.data : []; + if (pub.ok || priv.ok) animateValue($('#stat-rooms'), pubList.length + privList.length); + else $('#stat-rooms').textContent = '—'; + $('#stat-rooms-sub').textContent = (pub.ok || priv.ok) ? `${pubList.length} public / ${privList.length} private` : 'Unavailable'; + renderRooms(pubList, privList); + } + + function renderSessions(list) { + const tbody = $('#sessions-tbody'); + if (!tbody) return; + if (!list.length) { + tbody.innerHTML = 'No active sessions.'; + return; + } + tbody.innerHTML = list.map(s => { + const instances = Array.isArray(s.instances) ? s.instances : []; + const first = instances[0] || {}; + const away = s.is_away || first.is_away || s.away_message || first.away_message; + const client = first.client_id || s.client_id || '—'; + const addr = first.remote_addr ? `${first.remote_addr}${first.remote_port ? ':' + first.remote_port : ''}` : '—'; + const sn = esc(s.screen_name || ''); + return ` + ${sn || esc(s.id || '—')}${s.is_icq ? ' ICQ' : ''} + ${esc(fmtSeconds(s.online_seconds))} + ${esc(fmtSeconds(s.idle_seconds ?? first.idle_seconds))} + ${away ? 'Away' : 'Here'} + ${esc(addr)} + ${esc(client)} + + + + + `; + }).join(''); + $$('[data-session-detail]', tbody).forEach(btn => btn.addEventListener('click', () => viewSession(btn.dataset.sessionDetail))); + $$('[data-kick]', tbody).forEach(btn => btn.addEventListener('click', () => kickSession(btn.dataset.kick))); + } + + function renderUsers(list) { + const tbody = $('#users-tbody'); + if (!tbody) return; + const filter = ($('#users-filter')?.value || '').toLowerCase().trim(); + const filtered = filter ? list.filter(u => String(u.screen_name || '').toLowerCase().includes(filter)) : list; + if (!filtered.length) { + tbody.innerHTML = 'No users found.'; + return; + } + tbody.innerHTML = filtered.map(u => { + const status = u.suspended_status ? `${esc(u.suspended_status)}` : 'active'; + const bot = u.is_bot ? 'bot' : 'no'; + const sn = esc(u.screen_name || ''); + return ` + + ${sn} + ${u.is_icq ? 'ICQ' : 'AIM'} + ${status} + ${bot} + + + + + + + `; + }).join(''); + $$('[data-view-user]', tbody).forEach(btn => btn.addEventListener('click', () => viewUser(btn.dataset.viewUser))); + $$('[data-suspend]', tbody).forEach(btn => btn.addEventListener('click', () => patchUser(btn.dataset.suspend, { suspended_status: 'suspended' }))); + $$('[data-unsuspend]', tbody).forEach(btn => btn.addEventListener('click', () => patchUser(btn.dataset.unsuspend, { suspended_status: '' }))); + $$('[data-delete-user]', tbody).forEach(btn => btn.addEventListener('click', () => deleteUser(btn.dataset.deleteUser))); + } + + function renderRooms(pub, priv) { + const pubBody = $('#public-rooms-tbody'); + const privBody = $('#private-rooms-tbody'); + if (pubBody) { + pubBody.innerHTML = pub.length ? pub.map(r => ` + ${esc(r.name || '')} + ${esc(r.create_time || '—')} + ${Array.isArray(r.participants) ? r.participants.length : 0} + `).join('') : 'No public rooms.'; + } + if (privBody) { + privBody.innerHTML = priv.length ? priv.map(r => ` + ${esc(r.name || '')} + ${esc(r.create_time || '—')} + ${esc(r.creator_id || '—')} + ${Array.isArray(r.participants) ? r.participants.length : 0} + `).join('') : 'No private rooms.'; + } + } + + // Actions + async function kickSession(screenName) { + if (!screenName) return; + if (!confirm(`Kick ${screenName}? This will disconnect their active session(s).`)) return; + const r = await api('sessions.kick', { screen_name: screenName }); + if (r.ok) { toast(`Kicked ${screenName}`, 'success'); loadOverview(); } + else toast(r.error || 'Kick failed', 'error'); + } + + async function patchUser(screenName, body) { + if (!screenName) return; + const r = await api('users.patch', { screen_name: screenName, ...body }); + if (r.ok) { toast(`Updated ${screenName}`, 'success'); loadOverview(); } + else toast(r.error || 'Update failed', 'error'); + } + + async function deleteUser(screenName) { + if (!screenName) return; + if (!confirm(`Delete user ${screenName}? This cannot be undone.`)) return; + const r = await api('users.delete', { screen_name: screenName }); + if (r.ok) { toast(`Deleted ${screenName}`, 'success'); loadOverview(); } + else toast(r.error || 'Delete failed', 'error'); + } + + async function viewUser(screenName) { + if (!screenName) return; + const card = $('#user-detail-card'); + $('#user-detail-name').textContent = screenName; + card.style.display = 'block'; + setDetail('user-detail-json', 'Loading...'); + $('#user-detail-icon-wrap').innerHTML = ''; + $('#user-detail-sessions-json').style.display = 'none'; + const r = await api('users.get', { screen_name: screenName }, 'GET'); + if (r.ok) { + $('#user-detail-json').innerHTML = renderUserDetailHtml(r.data); + $('#user-detail-status').value = r.data?.suspended_status || ''; + $('#user-detail-bot').checked = !!r.data?.is_bot; + } else { + setDetail('user-detail-json', r.error || 'Failed to load user.'); + } + } + + async function viewSession(screenName) { + if (!screenName) return; + const card = $('#session-detail-card'); + $('#session-detail-name').textContent = screenName; + card.style.display = 'block'; + setDetail('session-detail-json', 'Loading...'); + const r = await api('sessions.get', { screen_name: screenName }, 'GET'); + const el = $('#session-detail-json'); + if (r.ok) el.innerHTML = renderSessionDetailHtml(r.data); + else setDetail(el, r.error || 'Failed to load session.'); + } + + function selectedUsers() { + return $$('.user-select:checked').map(c => c.value).filter(Boolean); + } + + // Forms + function bindForm(id, handler) { + const form = document.getElementById(id); + if (!form) return; + form.addEventListener('submit', async (e) => { + e.preventDefault(); + const btn = form.querySelector('button[type="submit"]'); + const old = btn?.textContent; + if (btn) { btn.disabled = true; btn.textContent = 'Working...'; } + try { await handler(new FormData(form), form); } + catch (err) { console.error(err); toast(err.message || 'Request failed', 'error'); } + finally { if (btn) { btn.disabled = false; btn.textContent = old; } } + }); + } + + bindForm('create-user-form', async (fd, form) => { + const r = await api('users.create', { screen_name: fd.get('screen_name'), password: fd.get('password') }); + if (r.ok) { toast('User created', 'success'); form.reset(); loadOverview(); } + else toast(r.error || 'Create failed', 'error'); + }); + + bindForm('set-password-form', async (fd, form) => { + const r = await api('users.set_password', { screen_name: fd.get('screen_name'), password: fd.get('password') }); + if (r.ok) { toast('Password updated', 'success'); form.reset(); } + else toast(r.error || 'Password update failed', 'error'); + }); + + bindForm('create-room-form', async (fd, form) => { + const r = await api('rooms.public.create', { name: fd.get('name') }); + if (r.ok) { toast('Room created', 'success'); form.reset(); loadOverview(); } + else toast(r.error || 'Create room failed', 'error'); + }); + + bindForm('delete-room-form', async (fd, form) => { + const names = String(fd.get('names') || '').split(/[\n,]+/).map(s => s.trim()).filter(Boolean); + if (!names.length) return toast('Enter at least one room name', 'error'); + if (!confirm(`Delete ${names.length} room(s)?`)) return; + const r = await api('rooms.public.delete', { names }); + if (r.ok) { toast('Rooms deleted', 'success'); form.reset(); loadOverview(); } + else toast(r.error || 'Delete rooms failed', 'error'); + }); + + bindForm('send-im-form', async (fd, form) => { + const r = await api('im.send', { + from: fd.get('from'), to: fd.get('to'), text: fd.get('text'), + store_offline: fd.get('store_offline') ? true : false + }); + if (r.ok) { toast('Instant message sent', 'success'); form.querySelector('[name="text"]').value = ''; } + else toast(r.error || 'Send failed', 'error'); + }); + + bindForm('send-popup-form', async (fd, form) => { + const recipients = String(fd.get('recipients') || '').split(/[\n,]+/).map(s => s.trim()).filter(Boolean); + const r = await api('popup.send', { + recipients, broadcast: fd.get('broadcast') ? true : false, + message: fd.get('message'), url: fd.get('url'), width: fd.get('width'), height: fd.get('height') + }); + if (r.ok) { toast('Popup sent', 'success'); } + else toast(r.error || 'Popup failed', 'error'); + }); + + bindForm('create-category-form', async (fd, form) => { + const r = await api('directory.categories.create', { name: fd.get('name') }); + if (r.ok) { toast('Category created', 'success'); form.reset(); loadDirectory(); } + else toast(r.error || 'Create category failed', 'error'); + }); + + bindForm('create-keyword-form', async (fd, form) => { + const r = await api('directory.keywords.create', { category_id: fd.get('category_id'), name: fd.get('name') }); + if (r.ok) { toast('Keyword added', 'success'); form.reset(); const cat = $('#keyword-category-id').value; if (cat) loadKeywords(cat); } + else toast(r.error || 'Add keyword failed', 'error'); + }); + + bindForm('api-console-form', async (fd) => { + const r = await api('api.raw', { + method: fd.get('method'), + path: fd.get('path'), + body: fd.get('body') + }); + const out = $('#api-console-output'); + if (out) out.textContent = JSON.stringify(r, null, 2); + if (r.ok) toast('API request completed', 'success'); + else toast(r.error || 'API request failed', 'error'); + }); + $('#clear-api-response')?.addEventListener('click', () => { + const out = $('#api-console-output'); + if (out) out.textContent = 'No request sent yet.'; + }); + + // Directory + async function loadDirectory() { + const tbody = $('#categories-tbody'); + if (!tbody) return; + tbody.innerHTML = 'Loading...'; + const r = await api('directory.categories.list', {}, 'GET'); + const list = r.ok && Array.isArray(r.data) ? r.data : []; + if (!r.ok) { tbody.innerHTML = `${esc(r.error || 'Failed to load')}`; return; } + if (!list.length) { tbody.innerHTML = 'No categories.'; return; } + tbody.innerHTML = list.map(c => ` + ${esc(c.id)} + ${esc(c.name)} + + + + + `).join(''); + $$('[data-load-kw]', tbody).forEach(b => b.addEventListener('click', () => { $('#keyword-category-id').value = b.dataset.loadKw; loadKeywords(b.dataset.loadKw); })); + $$('[data-del-cat]', tbody).forEach(b => b.addEventListener('click', async () => { + if (!confirm(`Delete category ${b.dataset.delCat}?`)) return; + const dr = await api('directory.categories.delete', { id: Number(b.dataset.delCat) }); + if (dr.ok) { toast('Category deleted', 'success'); loadDirectory(); } else toast(dr.error || 'Delete failed', 'error'); + })); + } + + async function loadKeywords(categoryId) { + const tbody = $('#keywords-tbody'); + if (!tbody) return; + tbody.innerHTML = 'Loading...'; + const r = await api('directory.keywords.list', { category_id: Number(categoryId) }, 'GET'); + const list = r.ok && Array.isArray(r.data) ? r.data : []; + if (!r.ok) { tbody.innerHTML = `${esc(r.error || 'Failed to load')}`; return; } + if (!list.length) { tbody.innerHTML = 'No keywords.'; return; } + tbody.innerHTML = list.map(k => ` + ${esc(k.id)}${esc(k.name)} + + `).join(''); + $$('[data-del-kw]', tbody).forEach(b => b.addEventListener('click', async () => { + if (!confirm(`Delete keyword ${b.dataset.delKw}?`)) return; + const dr = await api('directory.keywords.delete', { id: Number(b.dataset.delKw) }); + if (dr.ok) { toast('Keyword deleted', 'success'); loadKeywords(categoryId); } else toast(dr.error || 'Delete failed', 'error'); + })); + } + + $('#load-keywords-btn')?.addEventListener('click', () => { + const id = $('#keyword-category-id')?.value; + if (id) loadKeywords(id); + }); + + // User detail controls + $('#close-user-detail')?.addEventListener('click', () => $('#user-detail-card').style.display = 'none'); + $('#close-session-detail')?.addEventListener('click', () => $('#session-detail-card').style.display = 'none'); + $('#user-detail-save')?.addEventListener('click', async () => { + const sn = $('#user-detail-name').textContent; + if (!sn) return; + const r = await api('users.patch', { screen_name: sn, suspended_status: $('#user-detail-status').value, is_bot: $('#user-detail-bot').checked }); + if (r.ok) { toast('User updated', 'success'); viewUser(sn); loadOverview(); } else toast(r.error || 'Update failed', 'error'); + }); + $('#user-detail-icon')?.addEventListener('click', async () => { + const sn = $('#user-detail-name').textContent; + if (!sn) return; + const r = await api('users.icon.get', { screen_name: sn }, 'GET'); + const wrap = $('#user-detail-icon-wrap'); + if (r.ok && r.data?.base64) { + wrap.innerHTML = `icon`; + } else { + wrap.innerHTML = `
${esc(r.error || 'No icon')}
`; + } + }); + $('#user-detail-sessions')?.addEventListener('click', async () => { + const sn = $('#user-detail-name').textContent; + if (!sn) return; + const r = await api('sessions.get', { screen_name: sn }, 'GET'); + const el = $('#user-detail-sessions-json'); + el.style.display = 'block'; + if (r.ok) el.innerHTML = renderSessionDetailHtml(r.data); + else setDetail(el, r.error || 'Failed'); + }); + + // Bulk actions + $('#users-select-all')?.addEventListener('change', (e) => { + $$('.user-select').forEach(c => c.checked = e.target.checked); + }); + $('#bulk-apply-status')?.addEventListener('click', async () => { + const users = selectedUsers(); + if (!users.length) return toast('Select users first', 'error'); + const status = $('#bulk-suspend-status').value; + if (!confirm(`Apply status "${status || 'active'}" to ${users.length} user(s)?`)) return; + for (const sn of users) await api('users.patch', { screen_name: sn, suspended_status: status }); + toast('Bulk status update complete', 'success'); loadOverview(); + }); + $('#bulk-delete-users')?.addEventListener('click', async () => { + const users = selectedUsers(); + if (!users.length) return toast('Select users first', 'error'); + if (!confirm(`Delete ${users.length} user(s)? This cannot be undone.`)) return; + for (const sn of users) await api('users.delete', { screen_name: sn }); + toast('Bulk delete complete', 'success'); loadOverview(); + }); + + // BART + const BART_TYPES = [ + {id:0,name:'Buddy icon (small)',desc:'Small buddy icon shown in buddy lists. GIF/JPEG/BMP/PNG, <= 32x32, <= 2KB.',group:'Icons',icon:'🖼️'}, + {id:1,name:'Buddy icon',desc:'Standard buddy icon. GIF/JPEG/BMP/PNG, <= 64x64, <= 7KB.',group:'Icons',icon:'🖼️'}, + {id:12,name:'Buddy icon (big)',desc:'Large buddy icon. GIF/JPEG/BMP/PNG, <= 1024x1024, <= 64KB.',group:'Icons',icon:'🖼️'}, + {id:2,name:'Status string',desc:'Status text in StringTLV format (DATA flag always set).',group:'Status',icon:'💬'}, + {id:13,name:'Status string time',desc:'Time when the status string was set.',group:'Status',icon:'🕒'}, + {id:3,name:'Arrive sound',desc:'Sound played when a buddy comes online. WAV/MP3/MID, <= 10KB.',group:'Sounds',icon:'🔔'}, + {id:96,name:'Depart sound',desc:'Sound played when a buddy goes offline. WAV/MP3/MID, <= 10KB.',group:'Sounds',icon:'🔕'}, + {id:131,name:'IM sound',desc:'Sound played for instant messages. WAV/MP3, <= 10KB.',group:'Sounds',icon:'🎵'}, + {id:4,name:'Rich text',desc:'Rich text formatting codes (DATA flag always set).',group:'Text & UI',icon:'✍️'}, + {id:129,name:'IM chrome',desc:'IM window wallpaper/background. GIF/JPG/BMP.',group:'Text & UI',icon:'🎨'}, + {id:136,name:'IM chrome XML',desc:'IM chrome XML definition.',group:'Text & UI',icon:'📄'}, + {id:137,name:'IM chrome immersive',desc:'Immersive Expressions for IM chrome.',group:'Text & UI',icon:'✨'}, + {id:5,name:'SuperBuddy icon',desc:'SuperBuddy icon XML.',group:'Other',icon:'⭐'}, + {id:6,name:'Radio station',desc:'Radio station opaque struct (DATA flag always set).',group:'Other',icon:'📻'}, + {id:15,name:'Current AV track',desc:'Current audio/video track XML.',group:'Other',icon:'🎬'}, + {id:1024,name:'Emoticon set',desc:'Set of default emoticons.',group:'Other',icon:'😊'}, + {id:1026,name:'Encryption cert chain',desc:'Certificate chain for encryption certs.',group:'Security',icon:'🔒'}, + {id:1027,name:'Signing cert chain',desc:'Certificate chain for signing certs.',group:'Security',icon:'✒️'}, + {id:1028,name:'Gateway cert',desc:'Certificate for enterprise gateway.',group:'Security',icon:'🛡️'}, + ]; + const bartTypeById = new Map(BART_TYPES.map(t => [Number(t.id), t])); + let bartAssetsCache = []; + let bartLoadSeq = 0; + + function bartTypeLabel(id) { + const t = bartTypeById.get(Number(id)); + return t ? `${t.name} (${t.id})` : `Type ${id}`; + } + function renderBartTypeInfo(targetId, typeId) { + const el = document.getElementById(targetId); + if (!el) return; + const t = bartTypeById.get(Number(typeId)); + if (!t) { el.innerHTML = `Unknown/custom type ID ${esc(typeId)}. You can still use it if the server supports it.`; return; } + el.innerHTML = `
${t.icon || '📦'}
${esc(t.name)} type #${esc(t.id)} ${esc(t.group)}
${esc(t.desc)}
`; + } + function renderBartUploadPurpose(typeId) { + const el = document.getElementById('bart-upload-purpose'); + if (!el) return; + const t = bartTypeById.get(Number(typeId)); + if (!t) { + el.innerHTML = `
Uploading for
Custom type #${esc(typeId)}
Unknown type - make sure the server expects this type ID.
`; + return; + } + el.innerHTML = `
You're uploading
${t.icon || '📦'}${esc(t.name)} type #${esc(t.id)}
${esc(t.desc)}
`; + } + function selectBartType(id) { + id = Number(id); + const listType = $('#bart-list-type'); + const upType = $('#bart-upload-type'); + if (listType) listType.value = id; + if (upType) upType.value = id; + renderBartTypeInfo('bart-selected-type-info', id); + renderBartTypeInfo('bart-upload-type-info', id); + renderBartUploadPurpose(id); + $$('.bart-type-card').forEach(c => c.classList.toggle('selected', Number(c.dataset.typeId) === id)); + } + function renderBartCatalog() { + const wrap = $('#bart-type-catalog'); + if (!wrap) return; + const q = ($('#bart-type-filter')?.value || '').toLowerCase().trim(); + const types = BART_TYPES.filter(t => !q || `${t.id} ${t.name} ${t.desc} ${t.group}`.toLowerCase().includes(q)); + const groups = []; + for (const t of types) { + let g = groups.find(x => x.name === t.group); + if (!g) { g = {name: t.group, items: []}; groups.push(g); } + g.items.push(t); + } + const sel = Number($('#bart-list-type')?.value); + wrap.innerHTML = groups.map(g => ` +
+
${esc(g.name)}
+
+ ${g.items.map(t => ` + `).join('')} +
+
`).join('') || '
No matching types.
'; + $$('.bart-type-card', wrap).forEach(btn => btn.addEventListener('click', () => selectBartType(btn.dataset.typeId))); + } + + function renderBartAssets() { + const tbody = $('#bart-list-tbody'); + if (!tbody) return; + const q = ($('#bart-asset-filter')?.value || '').toLowerCase().trim(); + const list = bartAssetsCache.filter(a => { + if (!q) return true; + const t = bartTypeById.get(Number(a.type)); + return String(a.hash || '').toLowerCase().includes(q) || String(a.type).includes(q) || (t && t.name.toLowerCase().includes(q)); + }); + const count = $('#bart-asset-count'); + if (count) count.textContent = bartAssetsCache.length ? `${list.length} of ${bartAssetsCache.length} assets` : ''; + if (!list.length) { tbody.innerHTML = `${bartAssetsCache.length ? 'No assets match your search.' : 'No assets found.'}`; return; } + tbody.innerHTML = list.map(a => { + const t = bartTypeById.get(Number(a.type)); + return ` + ${esc(a.hash)} + #${esc(a.type)} ${esc(t ? t.name : 'Unknown type')} + + + + + `; + }).join(''); + $$('[data-bart-get]', tbody).forEach(b => b.addEventListener('click', async () => { + const gr = await api('bart.get', { hash: b.dataset.bartGet }, 'GET'); + const prev = $('#bart-preview'); + if (gr.ok && gr.data?.base64) prev.innerHTML = `
${esc(b.dataset.bartGet)}
`; + else prev.innerHTML = `
${esc(gr.error || 'Could not preview (may be binary/non-image).')}
`; + })); + $$('[data-bart-use]', tbody).forEach(b => b.addEventListener('click', () => { + $('#bart-get-hash').value = b.dataset.bartUse; + $('#bart-upload-hash').value = b.dataset.bartUse; + if (b.dataset.bartType) { selectBartType(b.dataset.bartType); } + toast('Hash copied to forms', 'success', 1500); + })); + } + + async function loadAllBartAssets() { + const seq = ++bartLoadSeq; + const btns = [$('#bart-browse-all'), $('#bart-browse-all-secondary')].filter(Boolean); + const status = $('#bart-browse-status'); + btns.forEach(b => { b.disabled = true; b.textContent = 'Loading...'; }); + const all = []; + let done = 0; + for (const t of BART_TYPES) { + if (seq !== bartLoadSeq) return; + if (status) status.textContent = `Loading ${done + 1}/${BART_TYPES.length}: ${t.name} (#${t.id})...`; + const r = await api('bart.list', { type: t.id }, 'GET'); + if (r.ok && Array.isArray(r.data)) all.push(...r.data.map(a => ({...a, type: a.type ?? t.id}))); + done++; + } + if (seq !== bartLoadSeq) return; + bartAssetsCache = all; + renderBartAssets(); + if (status) status.textContent = `Loaded ${all.length} assets across ${BART_TYPES.length} known types.`; + btns.forEach(b => { b.disabled = false; b.textContent = b.id === 'bart-browse-all' ? 'Load all assets' : 'Load all types'; }); + toast(`Loaded ${all.length} assets across known types`, 'success'); + } + + bindForm('bart-list-form', async (fd) => { + const type = fd.get('type'); + renderBartTypeInfo('bart-selected-type-info', type); + selectBartType(type); + const status = $('#bart-browse-status'); + if (status) status.textContent = `Loading type #${type}...`; + const r = await api('bart.list', { type }, 'GET'); + bartAssetsCache = r.ok && Array.isArray(r.data) ? r.data.map(a => ({...a, type: a.type ?? Number(type)})) : []; + if (status) status.textContent = r.ok ? `Loaded ${bartAssetsCache.length} asset(s) for ${bartTypeLabel(type)}.` : ''; + if (!r.ok) { $('#bart-list-tbody').innerHTML = `${esc(r.error || 'Failed')}`; return; } + renderBartAssets(); + }); + + $('#bart-browse-all')?.addEventListener('click', loadAllBartAssets); + $('#bart-browse-all-secondary')?.addEventListener('click', loadAllBartAssets); + $('#bart-type-filter')?.addEventListener('input', renderBartCatalog); + $('#bart-asset-filter')?.addEventListener('input', renderBartAssets); + $('#bart-list-type')?.addEventListener('change', (e) => { selectBartType(e.target.value); }); + $('#bart-upload-type')?.addEventListener('change', (e) => { selectBartType(e.target.value); }); + + function md5Hex(buffer) { + // Compact MD5 for file hashing (BART asset hashes are MD5 hex). + function cmn(q,a,b,x,s,t){a=(a+q+x+t)|0;return(((a<>> (32-s)))+b)|0;} + function ff(a,b,c,d,x,s,t){return cmn((b&c)|((~b)&d),a,b,x,s,t);} + function gg(a,b,c,d,x,s,t){return cmn((b&d)|(c&(~d)),a,b,x,s,t);} + function hh(a,b,c,d,x,s,t){return cmn(b^c^d,a,b,x,s,t);} + function ii(a,b,c,d,x,s,t){return cmn(c^(b|(~d)),a,b,x,s,t);} + function md5blk(bytes){ + const n=((bytes.length+8)>>6)+1; const M=new Array(n*16).fill(0); + for(let i=0;i>2]|=bytes[i]<<((i%4)*8); + M[bytes.length>>2]|=0x80<<((bytes.length%4)*8); + const bitLen=bytes.length*8; M[n*16-2]=bitLen&0xffffffff; M[n*16-1]=Math.floor(bitLen/0x100000000); + return M; + } + const x=md5blk(new Uint8Array(buffer)); + let a=1732584193,b=-271733879,c=-1732584194,d=271733878; + for(let i=0;i>(j*8+4))&0x0f]+s[(n>>(j*8))&0x0f];return o;} + return hex(a)+hex(b)+hex(c)+hex(d); + } + + async function bartHashSelectedFile(quiet=false) { + const file = $('#bart-upload-file')?.files?.[0]; + if (!file) { if (!quiet) toast('Choose a file first', 'error'); return; } + const buf = await file.arrayBuffer(); + $('#bart-upload-hash').value = md5Hex(buf); + if (!quiet) toast('MD5 hash generated from file', 'success', 1500); + } + $('#bart-hash-file')?.addEventListener('click', () => bartHashSelectedFile(false)); + $('#bart-upload-file')?.addEventListener('change', () => bartHashSelectedFile(true)); + bindForm('bart-upload-form', async (fd, form) => { + const file = form.querySelector('input[type="file"]').files[0]; + if (!file) return toast('Choose a file', 'error'); + const b64 = await new Promise((resolve, reject) => { const r = new FileReader(); r.onload = () => resolve(String(r.result).split(',')[1] || ''); r.onerror = reject; r.readAsDataURL(file); }); + const r = await api('bart.upload', { hash: fd.get('hash'), type: fd.get('type'), data_base64: b64 }); + if (r.ok) { toast('BART asset uploaded', 'success'); renderBartTypeInfo('bart-upload-type-info', fd.get('type')); } + else toast(r.error || 'Upload failed', 'error'); + }); + bindForm('bart-get-form', async (fd) => { + const r = await api('bart.get', { hash: fd.get('hash') }, 'GET'); + const prev = $('#bart-preview'); + if (r.ok && r.data?.base64) prev.innerHTML = `
${esc(fd.get('hash'))}
`; + else prev.innerHTML = `
${esc(r.error || 'Not found')}
`; + }); + $('#bart-delete-btn')?.addEventListener('click', async () => { + const hash = $('#bart-get-hash').value.trim(); + if (!hash) return toast('Enter hash', 'error'); + if (!confirm(`Delete BART asset ${hash}?`)) return; + const r = await api('bart.delete', { hash }); + if (r.ok) { toast('BART asset deleted', 'success'); $('#bart-preview').innerHTML = ''; } + else toast(r.error || 'Delete failed', 'error'); + }); + + // Feedbag / Buddy List + let feedbagCurrentUser = ''; + let feedbagGroupsCache = []; + + function feedbagUser() { + return feedbagCurrentUser || ($('#feedbag-screen-name')?.value || '').trim(); + } + + function renderFeedbagGroups(groups) { + feedbagGroupsCache = Array.isArray(groups) ? groups : []; + const view = $('#feedbag-groups-view'); + const select = $('#feedbag-group-select'); + const raw = $('#feedbag-json'); + if (raw) raw.innerHTML = feedbagGroupsCache.length ? renderDetailHtml(feedbagGroupsCache) : '
No data.
'; + + if (select) { + if (!feedbagGroupsCache.length) { + select.innerHTML = ''; + } else { + select.innerHTML = '' + feedbagGroupsCache.map(g => + `` + ).join(''); + } + } + + if (!view) return; + if (!feedbagGroupsCache.length) { + view.innerHTML = '
No groups found for this user. Add a group to get started.
'; + return; + } + view.innerHTML = feedbagGroupsCache.map(g => { + const buddies = Array.isArray(g.buddies) ? g.buddies : []; + return `
+
+
${esc(g.group_name || 'Group')}
+ Group ID ${esc(g.group_id)} +
+
+ ${buddies.length ? buddies.map(b => `${esc(b.name || b)}`).join('') : 'No buddies in this group'} +
+
`; + }).join(''); + } + + async function loadFeedbag(screenName) { + const sn = (screenName || feedbagUser()).trim(); + if (!sn) { toast('Enter a screen name', 'error'); return; } + feedbagCurrentUser = sn; + $('#feedbag-current-user').textContent = `Loaded: ${sn}`; + const r = await api('feedbag.groups.list', { screen_name: sn }, 'GET'); + if (r.ok) { + renderFeedbagGroups(Array.isArray(r.data) ? r.data : []); + } else { + renderFeedbagGroups([]); + $('#feedbag-groups-view').innerHTML = `
${esc(r.error || 'Failed to load buddy list')}
`; + setDetail('feedbag-json', r.error || 'Failed'); + toast(r.error || 'Failed to load buddy list', 'error'); + } + } + + bindForm('feedbag-load-form', async (fd) => { + await loadFeedbag(fd.get('screen_name')); + }); + + bindForm('feedbag-add-group-form', async (fd, form) => { + const sn = feedbagUser(); + if (!sn) return toast('Load a user first', 'error'); + const r = await api('feedbag.groups.create', { screen_name: sn, group_name: fd.get('group_name') }); + if (r.ok) { toast('Group added', 'success'); form.reset(); loadFeedbag(sn); } + else toast(r.error || 'Failed', 'error'); + }); + + bindForm('feedbag-buddy-form', async (fd) => { + const sn = feedbagUser(); + if (!sn) return toast('Load a user first', 'error'); + const groupId = fd.get('group_id'); + if (!groupId) return toast('Select a group', 'error'); + const r = await api('feedbag.buddy.add', { screen_name: sn, group_id: groupId, buddy_screen_name: fd.get('buddy_screen_name') }); + if (r.ok) { toast('Buddy added', 'success'); $('#feedbag-buddy-name').value = ''; loadFeedbag(sn); } + else toast(r.error || 'Failed', 'error'); + }); + + $('#feedbag-remove-buddy-btn')?.addEventListener('click', async () => { + const sn = feedbagUser(); + if (!sn) return toast('Load a user first', 'error'); + const groupId = $('#feedbag-group-select')?.value; + const buddy = $('#feedbag-buddy-name')?.value?.trim(); + if (!groupId) return toast('Select a group', 'error'); + if (!buddy) return toast('Enter buddy screen name', 'error'); + if (!confirm(`Remove ${buddy} from this group?`)) return; + const r = await api('feedbag.buddy.delete', { screen_name: sn, group_id: groupId, buddy_screen_name: buddy }); + if (r.ok) { toast('Buddy removed', 'success'); $('#feedbag-buddy-name').value = ''; loadFeedbag(sn); } + else toast(r.error || 'Failed', 'error'); + }); + + bindForm('feedbag-bart-set-form', async (fd) => { + const sn = feedbagUser(); + if (!sn) return toast('Load a user first', 'error'); + const hash = (fd.get('hash') || '').trim(); + const type = fd.get('type'); + if (!hash) return toast('Enter asset hash', 'error'); + if (type === '' || type === null) return toast('Enter type ID', 'error'); + const r = await api('feedbag.bart.set', { screen_name: sn, hash, type }); + if (r.ok) toast('Buddy icon/item set', 'success'); else toast(r.error || 'Failed', 'error'); + }); + + $('#feedbag-bart-delete-btn')?.addEventListener('click', async () => { + const sn = feedbagUser(); + if (!sn) return toast('Load a user first', 'error'); + const type = $('#feedbag-bart-set-form [name="type"]')?.value; + if (type === '' || type === null) return toast('Enter type ID', 'error'); + if (!confirm('Remove this BART item from the user\'s buddy list?')) return; + const r = await api('feedbag.bart.delete', { screen_name: sn, type }); + if (r.ok) toast('BART item removed', 'success'); else toast(r.error || 'Failed', 'error'); + }); + + // Linked accounts + bindForm('linked-load-form', async (fd) => { + const sn = feedbagUser(); + if (!sn) return toast('Load a user first', 'error'); + const r = await api('linked.list', { screen_name: sn }, 'GET'); + if (r.ok) { + const list = Array.isArray(r.data?.linked_accounts) ? r.data.linked_accounts : (Array.isArray(r.data) ? r.data : []); + $('#linked-json').innerHTML = list.length ? `
${list.map(n => `${esc(n)}`).join('')}
` : '
No linked accounts.
'; + } else setDetail('linked-json', r.error || 'Failed'); + }); + bindForm('linked-add-form', async (fd) => { + const sn = feedbagUser(); + if (!sn) return toast('Load a user first', 'error'); + const r = await api('linked.add', { screen_name: sn, linked_screen_name: fd.get('linked_screen_name') }); + if (r.ok) { toast('Account linked', 'success'); $('#linked-screen-name').value = ''; } else toast(r.error || 'Failed', 'error'); + }); + $('#linked-remove-btn')?.addEventListener('click', async () => { + const sn = feedbagUser(); + if (!sn) return toast('Load a user first', 'error'); + const linked = $('#linked-screen-name')?.value?.trim(); + if (!linked) return toast('Enter linked screen name', 'error'); + if (!confirm(`Unlink ${linked}?`)) return; + const r = await api('linked.delete', { screen_name: sn, linked_screen_name: linked }); + if (r.ok) { toast('Account unlinked', 'success'); $('#linked-screen-name').value = ''; } else toast(r.error || 'Failed', 'error'); + }); + + // Audit + async function loadAudit() { + const r = await api('audit.list', { limit: 200 }, 'GET'); + const tbody = $('#audit-tbody'); + const list = r.ok && Array.isArray(r.data) ? r.data : []; + if (!r.ok) { tbody.innerHTML = `${esc(r.error || 'Failed')}`; return; } + if (!list.length) { tbody.innerHTML = 'No audit entries.'; return; } + tbody.innerHTML = list.map(e => `${esc(e.ts || '')}${esc(e.user || '')}${esc(e.action || '')}${renderDetailHtml(e.details || {})}`).join(''); + } + $('#refresh-audit')?.addEventListener('click', loadAudit); + + // AIM directory + async function loadAimDirectory() { + const tbody = $('#aim-directory-tbody'); + if (!tbody) return; + tbody.innerHTML = 'Loading...'; + const r = await api('directory.aim.list', {}, 'GET'); + const list = r.ok && Array.isArray(r.data) ? r.data : []; + if (!r.ok) { tbody.innerHTML = `${esc(r.error || 'Failed')}`; return; } + if (!list.length) { tbody.innerHTML = 'No entries.'; return; } + tbody.innerHTML = list.map(e => { + const name = [e.first_name, e.middle_name, e.last_name, e.nickname].filter(Boolean).join(' '); + const loc = [e.city, e.state, e.country].filter(Boolean).join(', '); + const kw = Array.isArray(e.keywords) ? e.keywords.join(', ') : ''; + return `${esc(e.screen_name || '')}${esc(name)}${esc(loc)}${esc(kw)}`; + }).join(''); + } + $('#load-aim-directory')?.addEventListener('click', loadAimDirectory); + + // Auto-refresh + let autoRefreshTimer = null; + $('#auto-refresh-toggle')?.addEventListener('change', (e) => { + if (autoRefreshTimer) { clearInterval(autoRefreshTimer); autoRefreshTimer = null; } + if (e.target.checked) autoRefreshTimer = setInterval(() => { loadOverview(); }, 15000); + }); + + // Refresh handlers + $('#refresh-all')?.addEventListener('click', () => { loadOverview(); loadDirectory(); loadAudit(); }); + $$('[data-refresh]').forEach(btn => btn.addEventListener('click', () => { + const t = btn.dataset.refresh; + if (t === 'sessions' || t === 'users' || t === 'rooms') loadOverview(); + if (t === 'directory') loadDirectory(); + })); + + $('#users-filter')?.addEventListener('input', () => renderUsers(usersCache)); + + // Tooltip edge correction + document.addEventListener('mouseover', (e) => { + const tip = e.target.closest('.tip'); + if (!tip) return; + tip.style.setProperty('--tip-shift', '0px'); + const r = tip.getBoundingClientRect(); + const pad = 12, w = 260; + let shift = 0; + const left = r.left + r.width/2 - w/2; + const right = r.left + r.width/2 + w/2; + if (left < pad) shift = pad - left; + if (right > window.innerWidth - pad) shift = (window.innerWidth - pad) - right; + tip.style.setProperty('--tip-shift', shift + 'px'); + }); + + // Initial load + renderBartCatalog(); + selectBartType(1); + if ($('#sessions-tbody')) { + loadOverview(); + loadDirectory(); + loadAudit(); + } +})(); diff --git a/assets/style.css b/assets/style.css new file mode 100644 index 0000000..9aadb31 --- /dev/null +++ b/assets/style.css @@ -0,0 +1,689 @@ +/* Bundled base stylesheet for Oscar Admin. Self-contained: no external fonts, scripts, or CDNs. */ + +:root { + --bg: #161821; + --bg-soft: #1d2030; + --panel: #20243a; + --panel-2: #262b44; + --text: #e8eaf3; + --muted: #98a0b8; + --accent: #5aa9ff; + --accent-2: #8f7dff; + --ok: #6fd69b; + --warn: #f2c66d; + --danger: #f06f6f; + --line: #353b57; + --shadow: 0 10px 30px rgba(0, 0, 0, .25); + --radius: 12px; + --radius-sm: 8px; + --max: 1040px; + --font: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + color-scheme: dark; +} + +html[data-theme="light"] { + --bg: #f4f6fb; + --bg-soft: #ffffff; + --panel: #ffffff; + --panel-2: #eef2fb; + --text: #1b1f33; + --muted: #5d6680; + --accent: #1f6fd1; + --accent-2: #6a54e8; + --ok: #1e8f58; + --warn: #9a6a00; + --danger: #c23b3b; + --line: #d6dbea; + --shadow: 0 10px 30px rgba(20, 30, 60, .08); + color-scheme: light; +} + +* { box-sizing: border-box; } +[hidden] { display: none !important; } +html { background: var(--bg); } +body { + margin: 0; + min-height: 100vh; + display: flex; + flex-direction: column; + background: + radial-gradient(1200px 500px at 85% -10%, rgba(90, 169, 255, .10), transparent 60%), + radial-gradient(900px 400px at -10% 10%, rgba(143, 125, 255, .09), transparent 60%), + var(--bg); + background-attachment: fixed; + color: var(--text); + font: 16px/1.6 var(--font); + -webkit-font-smoothing: antialiased; +} + +a { color: var(--accent); text-decoration: none; } +a:hover { text-decoration: underline; } +:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; border-radius: 4px; } +code, pre { + font-family: var(--mono); + background: var(--panel-2); + border: 1px solid var(--line); + border-radius: 6px; +} +code { padding: 1px 6px; font-size: .9em; overflow-wrap: anywhere; } + +.skip-link { + position: absolute; + left: 12px; + top: -60px; + padding: 8px 12px; + background: var(--accent); + color: #fff; + border-radius: var(--radius-sm); + z-index: 200; +} +.skip-link:focus { top: 12px; } + +/* ---------- Header and navigation ---------- */ +.site-header { + position: sticky; + top: 0; + z-index: 100; + display: flex; + align-items: center; + gap: 14px; + width: 100%; + padding: 14px max(16px, calc((100% - var(--max)) / 2)); + background: color-mix(in srgb, var(--bg) 85%, transparent); + backdrop-filter: blur(10px); + border-bottom: 1px solid var(--line); +} + +.brand { + display: inline-flex; + align-items: center; + gap: 10px; + font-weight: 700; + font-size: 1.05rem; + color: var(--text); + white-space: nowrap; +} +.brand:hover { text-decoration: none; } +.brand-logo { + display: block; + width: 32px; + height: 32px; + flex: none; + border-radius: 9px; +} + +.site-nav { + display: flex; + flex: 1; + flex-wrap: wrap; + gap: 2px; + justify-content: flex-end; +} +.site-nav a { + position: relative; + padding: 7px 11px; + border-radius: var(--radius-sm); + color: var(--muted); + font-size: .92rem; + transition: color .2s ease, background .2s ease; +} +.site-nav a:hover { color: var(--text); background: var(--panel); text-decoration: none; } +.site-nav a[aria-current="page"] { color: var(--text); background: var(--panel-2); } +.site-nav a[aria-current="page"]::after { + content: ""; + position: absolute; + left: 11px; + right: 11px; + bottom: 2px; + height: 2px; + border-radius: 2px; + background: var(--accent); +} + +.nav-toggle { display: none; } +.logout-form { margin: 0; } +.logout-form .button { min-height: 34px; padding: 6px 10px; font-size: .92rem; } + +/* ---------- Layout ---------- */ +main { + flex: 1; + width: min(100% - 32px, var(--max)); + margin: 0 auto; + padding: 28px 0 48px; + animation: rise .4s ease-out both; + outline: none; +} + +h1 { font-size: clamp(1.6rem, 2.5vw, 2.1rem); line-height: 1.2; margin: .2em 0 .45em; } +h2 { font-size: 1.2rem; margin: 0 0 .5em; } +p { margin: 0 0 .8em; } +ul, ol { margin: 0 0 .8em; padding-left: 1.3em; } +.lead { font-size: 1.1rem; color: var(--muted); max-width: 60ch; } +.muted { color: var(--muted); } +.small { font-size: .84rem; } +.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; } + +.card { + background: var(--panel); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 20px 22px; + margin: 0 0 18px; + box-shadow: var(--shadow); + transition: border-color .2s ease, transform .2s ease; +} +.card:hover { border-color: color-mix(in srgb, var(--accent) 45%, var(--line)); } +.card > :last-child { margin-bottom: 0; } + +.grid-2 { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 18px; +} + +.account-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 18px; + align-items: start; +} +.account-grid > .card { margin: 0; } +.account-grid .form { max-width: none; } +.account-grid .actions + .form { + margin-top: 18px; + padding-top: 18px; + border-top: 1px solid var(--line); +} + +.actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 10px; + margin-top: 16px; +} +.actions form { margin: 0; } + +.hero { + padding: 26px 0 10px; + animation: rise .5s ease-out both; +} +.eyebrow { + margin: 0 0 6px; + color: var(--accent); + font-size: .8rem; + font-weight: 700; + letter-spacing: .12em; + text-transform: uppercase; +} +.hero h1 { font-size: clamp(2rem, 4vw, 2.8rem); margin-bottom: .35em; } + +/* ---------- Buttons ---------- */ +.button { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + min-height: 40px; + padding: 9px 16px; + border: 1px solid var(--accent); + border-radius: var(--radius-sm); + background: transparent; + color: var(--accent); + font: inherit; + font-size: .92rem; + font-weight: 600; + text-decoration: none; + cursor: pointer; + transition: background .2s ease, color .2s ease, transform .15s ease, box-shadow .2s ease; +} +.button:hover { text-decoration: none; background: color-mix(in srgb, var(--accent) 14%, transparent); } +.button:active { transform: translateY(1px); } +.button-primary { + background: linear-gradient(135deg, var(--accent), var(--accent-2)); + border-color: transparent; + color: #fff; + box-shadow: 0 6px 18px color-mix(in srgb, var(--accent) 35%, transparent); +} +.button-primary:hover { background: linear-gradient(135deg, var(--accent), var(--accent-2)); color: #fff; filter: brightness(1.08); } +.button-ghost { border-color: var(--line); color: var(--text); } +.button-small { min-height: 28px; padding: 4px 10px; font-size: .78rem; } +.button[aria-expanded="true"] { border-color: var(--accent); } + +/* ---------- Stats ---------- */ +.stats { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); + gap: 12px; + margin: 18px 0; +} +.stat-tile { + display: flex; + flex-direction: column; + gap: 4px; + padding: 16px 18px; + background: var(--panel); + border: 1px solid var(--line); + border-radius: var(--radius); + box-shadow: var(--shadow); + animation: rise .5s ease-out both; +} +.stat-tile:nth-child(2) { animation-delay: .04s; } +.stat-tile:nth-child(3) { animation-delay: .08s; } +.stat-tile:nth-child(4) { animation-delay: .12s; } +.stat-tile:nth-child(5) { animation-delay: .16s; } +.stat-label { color: var(--muted); font-size: .8rem; text-transform: uppercase; letter-spacing: .08em; } +.stat-value { font-size: 1.6rem; font-weight: 700; font-variant-numeric: tabular-nums; } +.stat-note { font-size: .8rem; } + +/* ---------- Home ---------- */ +.home-lower { + display: grid; + grid-template-columns: minmax(0, 1.65fr) minmax(250px, 1fr); + gap: 18px; + align-items: start; +} +.home-lower > .card { margin: 0; } + +.card-head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 12px; + flex-wrap: wrap; + margin-bottom: 10px; +} +.card-head h2 { margin: 0; } +.card-head > a { font-size: .88rem; white-space: nowrap; } + +.howto-list { + list-style: none; + padding: 0; + margin: 0; + display: grid; + counter-reset: howto; +} +.howto-list li { + counter-increment: howto; + display: grid; + grid-template-columns: 26px minmax(0, 1fr); + gap: 12px; + padding: 11px 0; + border-bottom: 1px dashed var(--line); +} +.howto-list li:first-child { padding-top: 0; } +.howto-list li:last-child { padding-bottom: 0; border-bottom: 0; } +.howto-num { + width: 26px; + height: 26px; + display: grid; + place-items: center; + border-radius: 50%; + background: var(--panel-2); + border: 1px solid var(--line); + color: var(--accent); + font-size: .78rem; + font-weight: 700; +} +.howto-num::before { content: counter(howto); } +.howto-list strong { display: block; font-size: .95rem; margin: 1px 0 2px; } +.howto-list p { margin: 0; font-size: .9rem; color: var(--muted); } + +.copy-inline { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 58px; + min-height: 22px; + margin-left: 6px; + padding: 0 8px; + border: 1px solid var(--line); + border-radius: 999px; + background: transparent; + color: var(--muted); + font: inherit; + font-size: .72rem; + font-weight: 600; + line-height: 1; + vertical-align: baseline; + cursor: pointer; + transition: color .15s ease, border-color .15s ease; +} +.copy-inline:hover { color: var(--text); border-color: var(--accent); } + +/* ---------- Pills and status ---------- */ +.pill { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 2px 10px; + border: 1px solid var(--line); + border-radius: 999px; + font-size: .8rem; + color: var(--muted); + white-space: nowrap; +} +.pill.is-ok { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 60%, transparent); } +.pill.is-down { color: var(--danger); border-color: color-mix(in srgb, var(--danger) 60%, transparent); } +.pill.is-warn { color: var(--warn); border-color: color-mix(in srgb, var(--warn) 60%, transparent); } +.dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: currentColor; +} +.pill.is-ok .dot { animation: pulse 2.4s ease-out infinite; } + +/* ---------- Lists, key-value and steps ---------- */ +.kv { + display: grid; + grid-template-columns: max-content 1fr; + gap: 10px 18px; + align-items: center; + margin: 0 0 12px; +} +.kv dt { color: var(--muted); font-size: .9rem; } +.kv dd { margin: 0; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; min-width: 0; } + +.link-list { list-style: none; padding: 0; margin: 0; } +.link-list li { padding: 6px 0; border-bottom: 1px dashed var(--line); } +.link-list li:last-child { border-bottom: 0; } + +.steps { list-style: none; padding: 0; counter-reset: step; } +.steps li { + counter-increment: step; + position: relative; + padding: 12px 12px 12px 52px; + border-bottom: 1px solid var(--line); +} +.steps li:last-child { border-bottom: 0; } +.steps li::before { + content: counter(step); + position: absolute; + left: 12px; + top: 12px; + width: 28px; + height: 28px; + display: grid; + place-items: center; + border-radius: 50%; + background: var(--panel-2); + border: 1px solid var(--line); + font-weight: 700; + font-size: .85rem; +} +.steps li > * { display: block; } + +details { + border-top: 1px solid var(--line); + padding: 10px 0; +} +details:first-of-type { border-top: 0; } +summary { + cursor: pointer; + font-weight: 600; + list-style: none; + display: flex; + justify-content: space-between; + align-items: center; +} +summary::-webkit-details-marker { display: none; } +summary::after { content: "+"; color: var(--muted); font-size: 1.1rem; transition: transform .2s ease; } +details[open] > summary::after { content: "−"; } +details > :not(summary) { margin-top: 8px; } + +/* ---------- Tables ---------- */ +.table-wrap { overflow-x: auto; padding: 0; } +.table-wrap table { margin: 0; } +table { width: 100%; border-collapse: collapse; } +th, td { text-align: left; padding: 10px 12px; border-bottom: 1px solid var(--line); vertical-align: top; } +th { color: var(--muted); font-size: .78rem; font-weight: 600; text-transform: uppercase; letter-spacing: .06em; background: var(--bg-soft); } +tbody tr { transition: background .15s ease; } +tbody tr:hover { background: var(--panel-2); } +tbody tr:last-child td { border-bottom: 0; } + +.pager { + display: flex; + align-items: center; + justify-content: center; + gap: 12px; + margin: 16px 0; +} + +/* ---------- Filters ---------- */ +.filters { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)) auto; + gap: 12px; + align-items: end; +} +.filter-actions { display: flex; gap: 8px; } + +/* ---------- Forms ---------- */ +.form { display: grid; gap: 16px; max-width: 520px; } +label { display: grid; gap: 6px; font-weight: 500; font-size: .95rem; } +input[type="text"], +input[type="email"], +input[type="password"], +select { + width: 100%; + min-height: 42px; + padding: 9px 12px; + background: var(--bg); + color: var(--text); + border: 1px solid var(--line); + border-radius: var(--radius-sm); + font: inherit; + transition: border-color .2s ease, box-shadow .2s ease; +} +input:focus, select:focus { + outline: none; + border-color: var(--accent); + box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 25%, transparent); +} +input[aria-invalid="true"] { border-color: var(--danger); } +.input-with-button { display: flex; gap: 8px; } +.input-with-button input { flex: 1; } +.hint { color: var(--muted); font-size: .82rem; font-weight: 400; } +.field-error { color: var(--danger); font-size: .85rem; font-weight: 500; } +.field-error[hidden] { display: none; } +.strength { font-size: .82rem; color: var(--muted); min-height: 1.2em; } +.strength.is-weak { color: var(--danger); } +.strength.is-fair { color: var(--warn); } +.strength.is-strong { color: var(--ok); } + +/* ---------- Account pages ---------- */ +.auth-grid { + display: grid; + grid-template-columns: minmax(0, 1.7fr) minmax(260px, 1fr); + gap: 20px; + align-items: start; +} +.auth-main, +.auth-side { margin: 0; } +.auth-main > h1 { margin-top: 0; } +.auth-form { max-width: none; } +.form-section { display: grid; gap: 14px; } +.form-section + .form-section { + padding-top: 18px; + border-top: 1px solid var(--line); +} +.form-section-title { + margin: 0; + font-size: .74rem; + font-weight: 700; + letter-spacing: .1em; + text-transform: uppercase; + color: var(--muted); +} +.auth-submit { width: 100%; min-height: 46px; } +.auth-consent { margin: 0; text-align: center; } +.auth-side h2 { font-size: .95rem; } +.auth-side h2:not(:first-child) { margin-top: 18px; } +.auth-side .check-list { margin-bottom: 14px; } + +.check-list { + list-style: none; + padding: 0; + margin: 0 0 12px; + display: grid; + gap: 9px; +} +.check-list li { + position: relative; + padding-left: 22px; + font-size: .9rem; + line-height: 1.45; +} +.check-list li::before { + content: "✓"; + position: absolute; + left: 0; + top: 0; + color: var(--accent); + font-weight: 700; +} + +/* ---------- Notices, empty states ---------- */ +.notice { + padding: 12px 14px; + border-radius: var(--radius-sm); + border: 1px solid var(--line); + background: var(--panel); + margin: 0 0 16px; + animation: rise .3s ease-out both; +} +.notice.is-ok { border-color: color-mix(in srgb, var(--ok) 60%, transparent); color: var(--ok); } +.notice.is-error { border-color: color-mix(in srgb, var(--danger) 60%, transparent); color: var(--danger); } +.empty { text-align: center; color: var(--muted); padding: 28px 18px; } + +/* ---------- Long-form pages (privacy, terms) ---------- */ +.prose { max-width: 78ch; } +.prose h2 { margin: 22px 0 8px; font-size: 1.15rem; } +.prose h2:first-child { margin-top: 0; } +.prose p { margin: 0 0 12px; line-height: 1.65; } +.prose ul { margin: 0 0 14px; padding-left: 22px; } +.prose li { margin: 5px 0; line-height: 1.6; } +.prose p:last-child, .prose ul:last-child { margin-bottom: 0; } +.prose h2[id] { scroll-margin-top: 84px; } + +/* ---------- Room and client grids ---------- */ +.room-grid, +.client-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); + gap: 16px; +} +.room-card, +.client-card { display: flex; flex-direction: column; gap: 4px; } +.room-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + margin-bottom: 4px; +} +.room-head h2 { margin: 0; font-size: 1.05rem; word-break: break-word; } + +/* ---------- Other servers ---------- */ +.server-list { display: grid; gap: 14px; } +.server-row { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + grid-template-areas: + "head action" + "desc action"; + align-items: center; + gap: 4px 24px; + margin: 0; + padding: 20px 22px; +} +.server-row-head { + grid-area: head; + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 10px; +} +.server-row-head h2 { margin: 0; font-size: 1.15rem; } +.server-row-desc { + grid-area: desc; + margin: 0; + color: var(--muted); + max-width: 74ch; +} +.server-row > .button { grid-area: action; white-space: nowrap; } + +/* ---------- Footer ---------- */ +.site-footer { + width: min(100% - 32px, var(--max)); + margin: 0 auto; + padding: 22px 0 30px; + border-top: 1px solid var(--line); + color: var(--muted); + font-size: .88rem; + display: grid; + gap: 6px; +} +.footer-links { display: flex; gap: 14px; flex-wrap: wrap; } + +/* ---------- Motion ---------- */ +@keyframes rise { + from { opacity: 0; transform: translateY(6px); } + to { opacity: 1; transform: none; } +} +@keyframes pulse { + 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--ok) 60%, transparent); } + 70% { box-shadow: 0 0 0 7px transparent; } + 100% { box-shadow: 0 0 0 0 transparent; } +} + +/* ---------- Responsive ---------- */ +@media (max-width: 820px) { + .grid-2 { grid-template-columns: 1fr; } + .account-grid { grid-template-columns: 1fr; } + .auth-grid { grid-template-columns: 1fr; } + .home-lower { grid-template-columns: 1fr; } + .filters { grid-template-columns: 1fr 1fr; } + .filter-actions { grid-column: 1 / -1; } +} +@media (max-width: 720px) { + .site-header { flex-wrap: wrap; } + .nav-toggle { display: inline-flex; margin-left: auto; } + .site-nav { + display: none; + width: 100%; + flex-direction: column; + gap: 4px; + padding: 8px 0 4px; + } + .site-nav.is-open { display: flex; } + .site-nav a { padding: 10px 12px; } + .theme-toggle { order: 3; } + .stats { grid-template-columns: repeat(2, minmax(0, 1fr)); } +} +@media (max-width: 640px) { + .server-row { + grid-template-columns: 1fr; + grid-template-areas: + "head" + "desc" + "action"; + gap: 10px; + justify-items: start; + } +} +@media (max-width: 520px) { + .filters { grid-template-columns: 1fr; } + .kv { grid-template-columns: 1fr; gap: 4px; } + .kv dd { margin-bottom: 10px; } +} + +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { + animation: none !important; + transition: none !important; + scroll-behavior: auto !important; + } +} diff --git a/bart-info.php b/bart-info.php new file mode 100644 index 0000000..92ab61a --- /dev/null +++ b/bart-info.php @@ -0,0 +1,199 @@ + + + +
+
+
+
+
Open OSCAR Server
+

BART / Buddy ART Guide

+

What BART assets are, how type IDs and hashes work, and how to manage them on the server and in OSCAR clients.

+
+ +
+
+ +
+
+ Accuracy note: This is a practical guide. Type IDs/names/descriptions reflect common OSCAR BART documentation and the catalog used by this admin UI. Management API endpoint details are based on Open OSCAR Server api.yml. NINA wiki was offline during this update, so protocol details were not re-verified live. Verify implementation-specific behavior against the sources below. +
+
+ +
+

What is BART?

+

BART stands for Buddy ART. It's the OSCAR asset system used for buddy icons, sounds, emoticon sets, IM chrome, status strings, and other client art.

+
+
+

Identified by type + hash

+

Each asset has a type ID (what it is) and a hash (usually MD5 hex of the file content). Together they identify the asset.

+
+
+

Stored on the server

+

The OSCAR server stores BART assets. Clients upload/download through the BART foodgroup (0x0010), and admins can manage them through the Management API.

+
+
+

Used by clients

+

Clients reference BART assets for buddy icons, arrival/depart sounds, IM chrome, emoticons, and other features. Support varies by client version.

+
+
+
+ +
+

Common BART type IDs

+

Type IDs tell the server and client what the asset is for. These are the known types shown in the admin catalog.

+
+ + + + + + + + + + + + + + + + + + + + + + + +
IDNameGroupWhat it's for / notes
0Buddy icon (small)IconsSmall buddy icon. GIF/JPEG/BMP/PNG, <= 32x32, <= 2KB.
1Buddy iconIconsStandard buddy icon. GIF/JPEG/BMP/PNG, <= 64x64, <= 7KB.
12Buddy icon (big)IconsLarge buddy icon. GIF/JPEG/BMP/PNG, <= 1024x1024, <= 64KB.
2Status stringStatusStatus text in StringTLV format (DATA flag always set).
13Status string timeStatusTime when the status string was set.
3Arrive soundSoundsSound played when a buddy comes online. WAV/MP3/MID, <= 10KB.
96Depart soundSoundsSound played when a buddy goes offline. WAV/MP3/MID, <= 10KB.
131IM soundSoundsInstant message sound. WAV/MP3, <= 10KB.
4Rich textText & UIRich text formatting codes (DATA flag always set).
129IM chromeText & UIIM window wallpaper/background. GIF/JPG/BMP.
136IM chrome XMLText & UIIM chrome XML definition.
137IM chrome immersiveText & UIImmersive Expressions for IM chrome.
5SuperBuddy iconOtherSuperBuddy icon XML.
6Radio stationOtherRadio station opaque struct (DATA flag always set).
15Current AV trackOtherCurrent audio/video track XML.
1024Emoticon setOtherSet of default emoticons.
1026Encryption cert chainSecurityCertificate chain for encryption certs.
1027Signing cert chainSecurityCertificate chain for signing certs.
1028Gateway certSecurityCertificate for enterprise gateway.
+
+
+ +
+

How to use BART in the admin panel

+

The BART tab talks to the Open OSCAR Management API. Pick a type, browse existing assets, or upload a new one.

+
+
+
+

1Pick a type

+

Select a type card in the left catalog. The selected type is used for browsing and uploading, and the upload banner explains what that type is for.

+
+
+

2Browse assets

+
    +
  • List this type - fetch assets for the selected type ID.
  • +
  • Load all assets - scan known types and merge results so you can search by hash, type ID, or type name.
  • +
  • Preview/Use - preview an asset or copy its hash/type into forms.
  • +
+
+
+

3Upload or delete

+
    +
  • Upload - choose a file, auto-generate MD5 hash, then upload to POST /bart/{hash}?type=....
  • +
  • Delete - remove an asset by hash via DELETE /bart/{hash}.
  • +
+
+
+
+
+

On the server

+
    +
  • Assets are stored by hash/type in the server's BART store.
  • +
  • Management API endpoints: GET /bart?type=, GET /bart/{hash}, POST /bart/{hash}?type=, DELETE /bart/{hash}.
  • +
  • Feedbag entries can reference BART items (e.g. buddy icons). The admin Feedbag tab can set/remove a user's feedbag BART item.
  • +
+
+
+

In OSCAR clients

+
    +
  • Clients use the BART foodgroup (0x0010) to upload/download art assets.
  • +
  • Buddy icons are typically uploaded, hashed, and referenced in presence/feedbag data so other clients can fetch them.
  • +
  • Feature support varies by client and server version. A 404/unsupported response may mean the running server build doesn't expose that endpoint.
  • +
+
+
+
+
+ +
+

Sources & references

+

Use these for authoritative or implementation-specific details.

+ +
+
+ [ + // 'admin', + // 'clay', + ], + + // --- System OSCAR account used to send login codes / messages --- + // Create this account on the OSCAR server first. + 'system_screen_name' => 'SystemAdmin', + 'system_password' => 'CHANGE_ME', + + // --- OSCAR Management API ("dev API") --- + // The management API listens on API_LISTENER in the OSCAR server settings. + // Keep this on localhost/private network; do not expose it publicly. + 'mgmt_api_host' => '127.0.0.1', + 'mgmt_api_port' => 8080, + + // Optional: separate dev API endpoint if your setup uses one. + // Leave empty to use mgmt_api_host/mgmt_api_port. + 'dev_api_host' => '', + 'dev_api_port' => 0, + + // --- Admin UI --- + 'site_name' => 'Oscar Server Admin', + 'session_name' => 'oscar_admin', + 'login_code_ttl_seconds' => 600, + 'login_code_length' => 8, + 'max_login_attempts' => 8, + 'login_attempt_window_seconds' => 900, + + // --- Optional Gotify addon (lib_gotify.php) --- + // 100% optional. The admin panel works without this addon. + // Enable the feature here; each admin user sets their own Gotify URL/token + // from the dashboard user menu (stored in gotify-users.php, gitignored). + 'gotify_enabled' => false, + 'gotify_priority' => 5, // default priority for notifications (0-10) + + // Optional global fallback (used only if a user has no personal Gotify config). + // Prefer per-user settings in the dashboard. + 'gotify_url' => '', + 'gotify_token' => '', + + // Base path to shared web CSS. Defaults to bundled assets/style.css. + // Relative to this admin directory, or absolute. + 'shared_style_path' => 'assets/style.css', +]; diff --git a/index.php b/index.php new file mode 100644 index 0000000..4803659 --- /dev/null +++ b/index.php @@ -0,0 +1,508 @@ + +
+
+
Open OSCAR Server
+

Control Room

+

Signed in as . Manage users, sessions, rooms, and messages from one place.

+
+
+ + +
Checking...
+
+
+ +
+
+
+
Server
—
Version
+
+
+
+
Online sessions
—
Active now
+
+
+
+
Users
—
Registered accounts
+
+
+
+
Chat rooms
—
Public / private
+
+
+ +
+
+ + + + + + + + + +
+ +
+
+
+
+

Active Sessions ?

+

Who's online right now. Kick a session if needed.

+
+ +
+
+ + + +
Screen nameOnlineIdleAwayInstanceClient
Loading...
+
+ +
+ +
+
+
+

Users ?

+

Create, inspect, suspend, or delete accounts.

+
+ +
+
+
+

Create user

+
+ + + +
+
+
+

Set password

+
+ + + +
+
+
+
+ +
+ + + +
+
+
+ + + +
Screen nameTypeStatusBotActions
Loading...
+
+ +
+ +
+
+
+

Chat Rooms ?

+

Public and private chat rooms on the server.

+
+ +
+
+
+

Create public room

+
+ + +
+
+
+

Delete public rooms

+
+ + +
+
+
+
+
+

Public rooms

+
NameCreatedParticipants
Loading...
+
+
+

Private rooms

+
NameCreatedCreatorParticipants
Loading...
+
+
+
+ +
+
+
+

Messaging ?

+

Send instant messages or popup broadcasts through the management API.

+
+
+
+
+

Send instant message

+
+ + + + + +
+
+
+

Send popup

+

Not supported on OSCAR Server 0.25.0; expected in the next release after v0.25.0 (added in main, PR #222).

+
+ + + + +
+ + +
+ +
+
+
+
+ +
+
+
+

Directory ?

+

Manage AIM directory keyword categories and keywords.

+
+ +
+
+
+

Create category

+
+ + +
+

Add keyword

+
+ + + +
+
+
+

Categories

+
+ + + +
IDName
Loading...
+
+
+
+
+

Keywords

+
+ + + +
IDName
Select a category.
+
+
+
+

AIM Directory Entries

+
Screen nameNameLocationKeywords
Not loaded.
+
+
+ +
+
+
+

BART Assets ?

+

Pick an asset type on the left, then browse or upload on the right.

+
+
+ BART info + +
+
+ +
+
+
+
+

Asset types ?

+

Select what kind of asset you're working with.

+
+
+ +
+
+ +
+
+
+
+

Browse assets

+

List assets for the selected type, or load everything.

+
+
+
+
+ + + +
+
+
+
+ + +
+
+
Asset hashType
Select a type and click "List this type", or click "Load all types".
+
+ +
+
+
+

Upload asset

+

Upload a file for the selected asset type.

+
+
+
+
+ +
+ + + +
+ +
+

Preview / delete by hash

+
+ +
+ + +
+
+
+
+
+
+
+ +
+
+
+

Buddy List ?

+

Manage a user's buddy groups, buddies, linked accounts, and advanced icon settings.

+
+
+ +
+
+
+

1. Choose a user

+

Load a user's buddy list to view and manage it.

+
+
+
+
+
+ + +
+
+
+ +
+
+
+
+

2. Buddy groups & buddies

+

Groups organize a user's buddies. Add a group, then add buddies to it.

+
+
+ +
+
Load a user to see their buddy list.
+
+ +
+

Add a group

+
+ + +
+ +
+ Show raw data +
—
+
+
+ +
+
+
+

3. Manage buddies

+

Add or remove buddies in the selected user's groups.

+
+
+ +
+ + +
+ + +
+
+ +
+

Linked accounts ?

+

Connect alternate screen names to the loaded user.

+
+
+ +
+
+
—
+
+ +
+ + +
+
+ +
+ Advanced: Buddy icon / BART item +

Advanced OSCAR setting: assign a BART asset (like a buddy icon) to the user's feedbag. Most admins won't need this.

+
+ + +
+ + +
+
+
+
+
+
+ +
+
+

Audit Log ?

Recent admin actions from this panel.

+ +
+
+ + + +
TimeUserActionDetails
Loading...
+
+
+ +
+
+
+

API Console

+

Send raw requests to the configured Management API. Full power, full responsibility.

+
+
+
+
+
+ + +
+ + +
+
+
+

Response

+
No request sent yet.
+
+
+
+
+ +
+ 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; + ?> + + + + + + + <?= h($title) ?> - <?= h($site) ?> + + + + +
+
+
+
+
+ +
+
+
Open OSCAR control room
+
+
+ + + +
+
+ +
+ +
+ + +
+ + + + + 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); +} diff --git a/lib_gotify.php b/lib_gotify.php new file mode 100644 index 0000000..07097cf --- /dev/null +++ b/lib_gotify.php @@ -0,0 +1,195 @@ + $url, + 'token' => $token, + 'priority' => max(0, min(10, (int) ($row['priority'] ?? admin_cfg('gotify_priority', 5)))), + 'updated_at' => (string) ($row['updated_at'] ?? ''), + ]; +} + +function admin_gotify_user_save(string $screenName, string $url, string $token, ?int $priority = null): array +{ + if (!function_exists('admin_normalize_screen_name')) { + return ['ok' => false, 'error' => 'Missing admin helpers.']; + } + $key = admin_normalize_screen_name($screenName); + if ($key === '') return ['ok' => false, 'error' => 'Invalid screen name.']; + $url = rtrim(trim($url), '/'); + $token = trim($token); + $priority = $priority ?? (int) admin_cfg('gotify_priority', 5); + $priority = max(0, min(10, $priority)); + + $all = admin_gotify_users_load(); + if ($url === '' || $token === '') { + unset($all[$key]); + $saved = admin_gotify_users_save_all($all); + return $saved ? ['ok' => true, 'cleared' => true] : ['ok' => false, 'error' => 'Failed to save Gotify settings.']; + } + + // Basic validation + if (!preg_match('#^https?://#i', $url)) { + return ['ok' => false, 'error' => 'Gotify URL must start with http:// or https://']; + } + + $all[$key] = [ + 'screen_name' => $screenName, + 'url' => $url, + 'token' => $token, + 'priority' => $priority, + 'updated_at' => date('c'), + ]; + $saved = admin_gotify_users_save_all($all); + return $saved ? ['ok' => true, 'cleared' => false] : ['ok' => false, 'error' => 'Failed to save Gotify settings.']; +} + +function admin_gotify_resolve(string $screenName): ?array +{ + $user = admin_gotify_user_get($screenName); + if ($user) return $user; + // Optional global fallback + $url = rtrim(trim((string) admin_cfg('gotify_url', '')), '/'); + $token = trim((string) admin_cfg('gotify_token', '')); + if ($url !== '' && $token !== '') { + return [ + 'url' => $url, + 'token' => $token, + 'priority' => max(0, min(10, (int) admin_cfg('gotify_priority', 5))), + 'updated_at' => '', + 'fallback' => true, + ]; + } + return null; +} + +function admin_gotify_enabled(): bool +{ + // Back-compat alias: feature toggle (not "is configured for a specific user"). + return admin_gotify_feature_enabled(); +} + +function admin_gotify_send(string $title, string $message, ?int $priority = null, ?string $url = null, ?string $token = null): array +{ + if (!admin_gotify_feature_enabled()) { + return ['ok' => false, 'status' => 0, 'error' => 'Gotify is not enabled', 'data' => null, 'raw' => '']; + } + + $url = rtrim(trim((string) ($url ?? admin_cfg('gotify_url', ''))), '/'); + $token = trim((string) ($token ?? admin_cfg('gotify_token', ''))); + if ($url === '' || $token === '') { + return ['ok' => false, 'status' => 0, 'error' => 'Gotify is not configured', 'data' => null, 'raw' => '']; + } + + $priority = $priority ?? (int) admin_cfg('gotify_priority', 5); + $priority = max(0, min(10, $priority)); + + $endpoint = $url . '/message?token=' . rawurlencode($token); + $payload = json_encode([ + 'title' => $title, + 'message' => $message, + 'priority' => $priority, + ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + + $ch = curl_init($endpoint); + curl_setopt_array($ch, [ + CURLOPT_RETURNTRANSFER => true, + CURLOPT_POST => true, + CURLOPT_HTTPHEADER => ['Content-Type: application/json; charset=utf-8', 'Accept: application/json'], + CURLOPT_POSTFIELDS => $payload, + CURLOPT_TIMEOUT => 10, + CURLOPT_CONNECTTIMEOUT => 5, + ]); + + $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 ?: 'Gotify 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['errorDescription']) ? (string) $decoded['errorDescription'] : ($raw !== '' ? $raw : 'HTTP ' . $status)), + 'data' => $decoded, + 'raw' => $raw, + ]; +} + +function admin_gotify_send_for_user(string $screenName, string $title, string $message, ?int $priority = null): array +{ + $cfg = admin_gotify_resolve($screenName); + if (!$cfg) { + return ['ok' => false, 'status' => 0, 'error' => 'No Gotify configuration for this user', 'data' => null, 'raw' => '']; + } + return admin_gotify_send($title, $message, $priority ?? $cfg['priority'], $cfg['url'], $cfg['token']); +} diff --git a/login.php b/login.php new file mode 100644 index 0000000..6c52967 --- /dev/null +++ b/login.php @@ -0,0 +1,292 @@ + $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 { + ?> +
+
+
+
Secure sign-in
+

Admin access

+

Sign in with your OSCAR screen name. We'll send a one-time code through .

+
+ + + + + +
+ + + +
+
Code sent via
+
+
Expires in s
+
+
+ + + + +
+
+ + + +
+ +
+ + + + + +
+ + + +
+
+
+

How it works

+
    +
  1. 1
    Enter your screen name

    The one configured as an admin.

  2. +
  3. 2
    Get your code

  4. +
  5. 3
    Verify and manage

    Access the full admin dashboard.

  6. +
+
+
+
+ + +
+ + +
+ +
+ + +
+