Compare commits

...
13 Commits
Author SHA1 Message Date
Reditus 1d1d2ab2ee fix: use ON CONFLICT DO NOTHING in migration; replace launcher.ps1 with tested version (SID fix, StrictHostKeyChecking=no, BatchMode=yes, ConnectTimeout) 2026-06-01 07:51:16 +01:00
Reditus 32517999f3 fix: wrap Set-Acl in try/catch to avoid SeSecurityPrivilege error on SSH key rotate 2026-06-01 05:47:04 +01:00
Reditus 5d19f772e5 docs: update README to reflect removal of backend/frontend and launcher-driven workflow 2026-06-01 05:40:45 +01:00
Reditus 9ea0829789 feat: add SSH key rotation menu option [10] 2026-06-01 05:36:41 +01:00
Reditus 5ecf9f2417 chore: remove new dashboard (backend/ + frontend/) from repo and launcher 2026-05-30 04:49:40 +01:00
Reditus 18e85592b7 Merge Experimental into nightly for v0.5.0 sync 2026-05-30 01:42:18 +01:00
Reditus c7a0260569 Revise README
Updated the README
2026-05-30 01:35:39 +01:00
Reditus 17232053ee Revise README
Updated README
2026-05-30 01:34:23 +01:00
Reditus 593345fb1f fix: file manager overhaul, update removal, template auto-reload
File manager: inline split-pane layout, multi-pod selector, full filesystem access, upload permissions fix, download/delete buttons. Factory: TEMPLATES_AUTO_RELOAD to pick up template changes. Base: removed update banner, check button, polling, progress overlay, and all update JS/CSS.
2026-05-29 17:47:59 +01:00
Reditus 79818f6d5d fix: remove rate limits from API routes, keep login-only
Global default_limits set to [] and all per-route @limiter.limit decorators removed from api.py. Login page retains 10/min.
2026-05-29 16:34:50 +01:00
Reditus f4ee1b85cf feat: themes dual-variant, Leaflet maps, RMQ explorer, security hardening
Themes: 28 variants (14 light + 14 dark) with grid-based switcher
Maps: Leaflet.js smooth zoom/pan, marker clustering, search, owner labels
Experimental: RMQ queue/exchange explorer, publish, message inspector, safety gate
Security: timing-safe login, rate limiter, token env-var, session timeout, Erlang injection fix
Fixes: logout, auto-login removed, table-header theme, default dark theme, ConfigMap name
2026-05-29 16:03:13 +01:00
Reditus 4a94bf68ce fix: director ConfigMap name, CSRF, ServerSetScale replicas + error handling
- Fix ConfigMap name derivation (strip funcom-seabass- prefix from namespace)
- Fix CSRF token missing on all 6 director POST handlers (fetch -> csrfFetch)
- Add ServerSetScale replicas management to director map cards
- Merge webOverrideCfg into cfg so UI shows active runtime overrides
- Auto-refresh after Apply and reset button state on all handlers
- Surface JSON error bodies in error banner instead of silent fail
- Fix SSL SAN handling for IP vs DNS common name
- Fix Let's Encrypt certbot paths to use project-root certbot/ dir
- Fix deploys_ok to reflect actual K8s availability
- Add active server deployment matching with restart buttons
2026-05-29 11:55:57 +01:00
Reditus 0f173dc107 feat: separate dashboard database + launcher repair/cleanup options
- Move dashboard tables (bans, player_ips, audit_log, chat_history,
  settings, player_actions) to a dedicated 'dashboard' database to
  prevent pg_dump conflicts during game updates
- Add DashboardDatabaseService (legacy + backend) with auto-migration
  from old dashboard schema on first startup
- Add launcher option 9: Repair Game Database (fixes schema ownership)
- Add launcher option 10: Clean up Old Dashboard Schema (drops old schema)
- Update PlayerService to fetch IPs from dashboard DB separately
- Update all routes and services to use dash_db for dashboard tables
- Add dashboard_database_name config option to settings.yaml.example
- Update README with new menu options
2026-05-27 01:02:39 +01:00
101 changed files with 2677 additions and 13262 deletions

No files matched your search

+7
View File
@@ -14,6 +14,10 @@ frontend/.pnpm-store/
frontend/.vite/
frontend/dist/
# New dashboard (removed - legacy only)
backend/
frontend/
# Virtual environments
venv/
env/
@@ -38,6 +42,9 @@ internal-scripts/ssh/sshKey
# SSL Certificates
ssl/
# Let's Encrypt certbot runtime data
certbot/
# Temporary settings scripts (generated by launcher)
read_settings*.py
hash_pw*.py
+65 -324
View File
@@ -1,359 +1,100 @@
# Dune Awakening Dashboard
A comprehensive web-based management dashboard for Dune: Awakening private servers. Provides real-time monitoring, player management, chat logging, file browsing, and server administration tools.
A modern, full‑featured management dashboard for **Dune: Awakening** private servers. Provides real‑time monitoring, player tools, chat logs, file browsing, admin utilities, and secure remote access.
## Branching Strategy
> “A comprehensive web-based management dashboard for Dune: Awakening private servers.”
This repo follows a git-flow inspired strategy. Here's the breakdown:
- **main** - Current beta release. It's stable enough to use, but things still break occasionally. I'm working toward a proper stable release, but we're not there yet. Don't use main as a reference for "production-ready" code - it's more "production-adjacent."
- **nightly** - The cutting edge. Updated automatically from main with the latest changes. Might have shiny new features, might have shiny new bugs. Generally works but don't be surprised if something catches fire.
- **experimental** - Where ideas go to become features or crash spectacularly. This is where new features are tested, questionable UI decisions are made, and code is written that might make future-me weep. Expect bugs. Expect weirdness. Expect things to break in creative new ways.
> "This seemed like a great idea at 3am" - every experimental commit ever
**Workflow:** Features → experimental → testing → nightly → main (eventually)
If you're testing this project, grab builds from nightly for the latest features, or main for something more stable. Experimental is where I break things on purpose to see what sticks.
---
## Quick Start
### Windows
1. Double-click `launcher.bat` (or run `.\launcher.ps1` in PowerShell)
2. Select option **2** to run Setup on first use
3. Select option **1** to Start Dashboard
### **Windows**
1. Run `launcher.bat` or `.\launcher.ps1`
2. Select **[2] Run Setup** on first launch
3. Select **[1] Start Dashboard** to open the UI
> **Tip**: The launcher automatically finds your SSH key from the Dune Awakening server installation at `%LOCALAPPDATA%\DuneAwakeningServer\sshKey`.
>
> **Note**: If PowerShell blocks running scripts due to execution policy (`launcher.ps1` won't run), use `launcher.bat` instead — it bypasses the restriction automatically. You can also run `powershell.exe -ExecutionPolicy Bypass -File .\launcher.ps1` directly from Command Prompt.
> The launcher automatically finds your Dune Awakening SSH key and politely ignores PowerShell’s opinions about execution policies.
### **Linux / macOS**
```bash
chmod +x start.sh
./start.sh
```
---
## Features
- **Map Features**: Interactive maps with real-world coordinate calibration for Hagga Basin and The Deep Desert. Default view centers on Hagga Basin at 15% zoom. Zoom range: 15%–100%.
- **Player Management**: View, search, and filter players. Track online status, factions, guilds, and locations. Rich detail view with vitals, currency, inventory, vehicles, buildings, landclaims, specialization, keystones, and faction reputation.
- **Chat Logs**: Parsed from text-router pod logs with channel filtering and auto-refresh.
- **Director Controls**: Live battlegroup stats, world state management, and server transfer controls.
- **File Browser**: Secure SSH-based file browser for server configuration and logs.
- **Shell Access**: Interactive VM and Kubernetes pod shells directly in the browser.
- **Admin Tools**: Ban management, IP detection, kick/unban functionality, player history, item/currency/vitals editing, and raw SQL query interface.
- **Firewall Security**: Block unauthenticated game server ports (File Browser, Director) from external internet access. Applied via iptables on the game server VM across INPUT, FORWARD, and mangle PREROUTING chains to cover both host services and Kubernetes NodePort traffic. Configurable per-port during setup or from the Server page.
- **Vehicles & Buildings**: Track owned vehicles, modules, and player structures.
- **Auto-Update**: Background checker polls GitHub for new commits. Safe file replacement preserves your settings, logs, and SSH keys. One-click update from the dashboard.
- **Remote Access**: Built-in support for HTTPS and binding to `0.0.0.0` for secure remote management.
- **Let's Encrypt**: Optionally set up publicly trusted SSL certs during setup with automatic renewal via certbot.
- **Settings Migration**: Automatically adds new configuration options to `settings.yaml` when updating, so you never miss a feature.
- **Cross-Platform**: Works on Windows (`.bat`/`.ps1`) and Linux/macOS (`.sh`).
- **Organized Logging**: Launcher logs are automatically categorized by type (SSH, K8s, database, etc.) with sensitive data redacted. Old logs are cleaned up after 30 days, oversized files are truncated at 10 MB.
- **Debug Mode**: Enable verbose debug logging via launcher (option 6) or the Server page UI. Logs detailed information about all HTTP requests/responses, SSH commands, database queries, Kubernetes operations, and service health checks. All sensitive data (passwords, tokens, keys) is automatically sanitized before writing to log files. Debug logs are written to `logs/debug.log`.
- **Player Management** (vitals, inventory, vehicles, buildings, guilds, reputation)
- **Chat Logs** with channel filtering and auto-refresh
- **Director Tools** (battlegroups, world state, transfers)
- **SSH File Browser** + **in-browser shell**
- **Firewall Hardening** via iptables
- **Auto‑Update** with safe file replacement
- **HTTPS + Remote Access** (self‑signed or Let’s Encrypt)
- **Cross‑Platform Launchers**
- **Organized Logging** with automatic cleanup and redaction
- **Debug Mode** with full SSH/K8s tracing
- **SSH Key Rotation** — scan all key locations and sync the newest key
## License
This project is **Source Available** under the [Dune Dashboard Source License (DDSL)](LICENSE).
- Source code is available for inspection and security auditing.
- **No redistribution** (modified or unmodified).
- **No claiming of credit** or authorship.
- Personal, non-commercial use only.
## Requirements
- Python 3.8+
- Node.js 18+ (for frontend development/build)
- OpenSSH client
- `kubectl` access to the Dune: Awakening Kubernetes cluster
- SSH access to the game server VM
## Setup
### Windows
1. **Run the Launcher**
```powershell
.\launcher.ps1
```
2. **Choose an option from the menu:**
- **[1] Start Dashboard** — Launch the dashboard web interface
- **[2] Run Setup** — Configure the dashboard for the first time (or reconfigure)
- **[3] Run Diagnostics** — Check your system for common issues
- **[4] Install CA Certificate** — Install the local CA into Windows Trusted Root store (removes browser SSL warnings)
- **[5] Clean & Reinstall CA Certificate** — Remove old CA certificates and install a fresh one
- **[6] Start Dashboard (Debug Mode)** — Launch with full debug logging enabled
- **[7] Start New Dashboard (React + ChakraUI)** — Launch the modern React dashboard with auto-installed dependencies
- **[8] Reset to Factory Defaults** — Wipe all data (settings, logs, certs, cache, node_modules) and return to a clean state
- **[Q] Quit** — Exit the launcher
3. **First-time Setup** (option 2)
The setup script will:
- Install Python dependencies
- Find your SSH key (automatically detects the Dune Awakening server key)
- Auto-detect your VM IP from Hyper-V or SSH history
- Generate SSL certificates (local CA or Let's Encrypt)
- Configure firewall rules and security hardening
During setup you'll be prompted for:
- **VM External IP** — the IP you SSH into (e.g., `<YOUR_VM_IP>`)
- **Host External IP** — the public IP for SSL certificate SANs (e.g., `<YOUR_HOST_IP>`)
- **Let's Encrypt** — optionally set up a publicly trusted SSL cert with auto-renewal via certbot
- **Firewall rules** — only prompted if no `DuneDashboard` rule exists yet
> **Note**: Setup will retry SSH up to 12 times (60 seconds) to accommodate fresh VM boot times. If SSH isn't ready yet, you can still continue and enter your Kubernetes namespace manually.
4. **Start Dashboard** (option 1)
The launcher will:
- Establish an SSH tunnel to your game server
- Set up database and Director port-forwards via kubectl
- Scale up the BGD deployment if needed
- Launch the dashboard web interface
### Linux / macOS
1. **Start Dashboard**
```bash
chmod +x start.sh
./start.sh
```
The launcher will prompt you to run setup if `settings.yaml` is missing.
## Configuration
All settings are stored in `settings.yaml`. The setup script generates this automatically. Key settings include:
- `server.host`: Game server VM IP
- `server.ssh_key`: Path to your SSH private key
- `kubernetes.namespace`: Auto-detected K8s namespace
- `database.port`: Local port for database tunnel
- `auth.username` / `auth.password_hash`: Dashboard login credentials (password_hash is Argon2 hash, generated by setup)
### Remote Access
During setup, answer **y** to "Enable remote access?" to:
- Bind to `0.0.0.0` (accessible from other machines)
- Auto-generate SSL certificates for HTTPS
- Enable secure remote connections via `https://YOUR_IP:5050`
**Firewall rules** are created automatically during setup. On subsequent starts, `start.ps1`/`start.sh` will only prompt if the `DuneDashboard` rule is missing.
You can also manually edit `settings.yaml` later:
```yaml
dashboard:
host: 0.0.0.0
ssl_cert: ssl/cert.pem
ssl_key: ssl/key.pem
```
### Let's Encrypt (Publicly Trusted Certs)
During setup, answer **y** when asked to enable Let's Encrypt. The setup script will:
1. Install `certbot` (tries `winget`, `pip`, and `python -m` fallbacks on Windows)
2. Run `certbot certonly --standalone` to validate your domain
3. Configure auto-renewal via Windows Scheduled Task or Linux cron
4. Point the dashboard to the Let's Encrypt cert paths
> **Note**: Port 80 must be free during certbot validation. The dashboard's HTTP redirect server will release port 80 temporarily for this.
### Local CA Utilities (Windows)
Available from the launcher menu (`.\launcher.ps1`):
- **Option 4: Install CA Certificate** — Installs the local CA (`ssl/ca.pem`) into Windows Trusted Root store. Run as Administrator. Removes browser warnings.
- **Option 5: Clean & Reinstall CA Certificate** — Removes all old Dune Dashboard CA certificates from Windows Trusted Root store and installs a fresh one. Use if you have duplicate or expired CA certificates.
### SSL Configuration
The dashboard supports both self-signed and CA-signed certificates.
**Local CA (auto-generated during setup):**
- A local Certificate Authority (`ssl/ca.pem`) is created during setup
- Server certificates are signed by this CA
- Server certs include SAN for the server IP + `127.0.0.1` + `localhost`
- Valid for 365 days
**Remove browser warnings (Windows):**
1. Run `.\launcher.ps1` and select option **4** (Install CA Certificate)
2. Restart your browser
3. Access `https://localhost:5050` — no more warnings
**Remove browser warnings (Linux):**
```bash
sudo cp ssl/ca.pem /usr/local/share/ca-certificates/dune-dashboard-ca.crt
sudo update-ca-certificates
```
**Let's Encrypt or custom CA:**
```yaml
dashboard:
host: 0.0.0.0
ssl_cert: /etc/letsencrypt/live/yourdomain.com/fullchain.pem
ssl_key: /etc/letsencrypt/live/yourdomain.com/privkey.pem
```
When SSL is enabled:
- Session cookies are marked `Secure` (sent only over HTTPS)
- HTTP-to-HTTPS redirect runs on port+1 (e.g., `http://localhost:5051` → `https://localhost:5050`)
- Certificate expiry is checked at startup (warning if < 30 days)
**Regenerate certificates:**
Delete `ssl/cert.pem`, `ssl/key.pem`, and `ssl/ca*.pem`, then re-run setup.
### Auto-Renewal
SSL certificates are automatically regenerated when they approach expiry:
- A background thread checks the certificate every 24 hours (configurable)
- If the certificate expires within 30 days (configurable), a new one is generated
- The server does **not** need to restart — Flask-SocketIO picks up the new cert on the next connection
- Configure thresholds in `settings.yaml` under the `ssl:` section
---
## Project Structure
```
DuneDashboard/
├── backend/ # New Flask backend (API + services)
│ ├── app/
│ │ ├── routes/ # HTTP route handlers (API, auth, health, server, files, director, chat)
│ │ ├── services/ # Business logic (DB, SSH, K8s, BGD, RMQ, player, economy, guild, world, etc.)
│ │ ├── models/ # Pydantic v2 models
│ │ ├── websocket/ # Socket.IO shell handler
│ │ ├── config.py # Settings loader
│ │ └── factory.py # App factory (services, blueprints, security)
│ ├── run.py # Entry point
│ └── requirements.txt # Python dependencies
│
├── frontend/ # New React SPA (Vite + TypeScript + Tailwind)
│ ├── src/
│ │ ├── components/ # Pages (overview, players, guilds, vehicles, buildings, map, accounts, server, admin, chat, shell, files, director, settings)
│ │ ├── api/ # Axios client
│ │ ├── stores/ # React Context (app state, auth, theme)
│ │ ├── hooks/ # Custom hooks (realtime, debounce)
│ │ └── styles/ # Tailwind + 14 Dune themes
│ ├── index.html
│ ├── package.json
│ ├── vite.config.ts
│ └── tsconfig.json
│
├── app/ # Legacy Flask/Jinja2 dashboard (untouched, still functional)
│ ├── routes/
│ ├── services/
│ ├── utils/
│ └── websocket/
├── templates/ # Legacy Jinja2 HTML templates
├── static/ # Legacy CSS and frontend assets
├── scripts/ # Pre-flight utilities (db_check.py)
├── launcher.ps1 # Unified launcher (setup, start, diagnostics, CA tools)
├── start.sh # Linux/macOS entry point
├── settings.yaml # Configuration (gitignored)
└── settings.yaml.example # Reference configuration
├── app/ # Flask/Jinja2 dashboard
├── launcher.ps1 # Windows launcher
├── start.sh # Linux/macOS launcher
└── settings.yaml # Generated config (gitignored)
```
> **Note**: The legacy `app/`, `templates/`, and `static/` directories remain untouched and functional. The new system lives in `backend/` and `frontend/`. Both can coexist during migration.
---
## Architecture
## Requirements
### Frontend
- **React 18** with TypeScript
- **Vite** for fast builds and HMR
- **Tailwind CSS** for styling with 14 Dune house themes
- **SWR** for server state caching and revalidation
- **Axios** for HTTP requests with 401 redirect handling
- **Socket.IO Client** for the remote terminal
- **xterm.js** for the in-browser shell
- Python 3.8+
- OpenSSH client
- `kubectl` access to your Dune Awakening cluster
- SSH access to the game server VM
### Backend
- **Flask 3** with Blueprint-based routing
- **Pydantic v2** for request/response validation
- **psycopg3** with connection pooling for PostgreSQL
- **Flask-SocketIO** for the interactive shell
- **Flask-Login** for session-based authentication (Argon2 password hashing)
- **Flask-Limiter** for rate limiting
- **SSE (Server-Sent Events)** for real-time updates (battlegroup, chat, metrics)
---
### Services
- `DatabaseService` — psycopg3 pool, stored procedure executor, audit table DDL
- `SSHService` — paramiko SSH client for tunneling and remote commands
- `K8sService` — kubectl-over-SSH for pod/deployment management
- `BgDirectorService` — HTTP client for the Battlegroup Director API
- `RmqAdminService` — RabbitMQ Management HTTP API client
- `RmqGameService` — RabbitMQ Game HTTP API client (broadcasts, chat intercept)
- `RealtimeService` — SSE broadcaster with background polling loops
- `PlayerService` / `EconomyService` / `GuildService` / `WorldService` / `ProgressionService` / `CharacterService` — DB-function-only domain services
- `AuditService` — persistent PostgreSQL audit logging
- `ChatService` — chat history + pod log catch-up
## Security
## Security Notes
- `settings.yaml` is never committed
- SSH keys stored with restricted permissions
- All DB queries parameterized
- Raw SQL endpoint is **read‑only SELECT**
- All mutations audited
- CSP, HSTS, X‑Frame‑Options enforced in production
- Never commit `settings.yaml` to version control.
- SSH keys are copied to `%TEMP%` with restricted permissions during startup.
- All database queries use parameterized statements to prevent SQL injection.
- Dashboard authentication is required by default.
- Raw SQL query endpoint (`/api/query`) is **read-only SELECT** — INSERT/UPDATE/DELETE/DROP/CREATE/ALTER/GRANT/TRUNCATE are blocked.
- All mutations are audited to PostgreSQL.
- CSP, HSTS, X-Frame-Options, and other security headers are enforced in production mode.
> “Raw SQL query endpoint is read‑only SELECT — INSERT/UPDATE/DELETE… are blocked.”
> Because letting users run `DROP TABLE` from a web UI is how horror stories begin.
## Logging
The launcher automatically organizes and sanitizes logs to protect sensitive information.
### Log Categories
```
logs/
├── launcher/
│ ├── general/ # General launcher events
│ ├── ssh/ # SSH tunnel and connection logs
│ ├── k8s/ # Kubernetes operations
│ ├── database/ # Database port-forward and connections
│ ├── dashboard/ # Dashboard startup and runtime
│ ├── setup/ # Setup wizard logs
│ └── diagnostics/ # Diagnostic tool output
├── app.log # Python application log (rotating, 10 MB max, 5 backups)
└── audit.log # Security audit log (rotating, 10 MB max, 5 backups)
```
### Sensitive Data Redaction
All launcher log files are automatically sanitized before writing. The following are redacted:
- IP addresses → `<IP_REDACTED>`
- JWT tokens → `<JWT_REDACTED>`
- Base64 secrets → `<BASE64_REDACTED>`
- SSH key paths → `<SSH_KEY_PATH_REDACTED>`
- K8s namespaces → `<NAMESPACE_REDACTED>`
- Host IDs → `<HOST_ID_REDACTED>`
- Passwords/tokens → `<REDACTED>`
- Funcom IDs → `<FUNCOM_ID_REDACTED>`
Console output is **not** sanitized so you can see full details during operation.
### Automatic Cleanup
- Log files older than **30 days** are deleted
- Files exceeding **10 MB** are truncated (keeps last 5000 lines)
- Empty category directories are removed
- Cleanup runs automatically on every launcher start
---
## Development
### Frontend Development
Run `launcher.bat` or `.\launcher.ps1` — the launcher handles dependencies, SSH key configuration, and server setup automatically.
```bash
cd frontend
npm install
npm run dev # Vite dev server with API proxy to localhost:5050
npm run build # Production build to frontend/dist/
```
---
### Backend Development
## Branching Strategy
```bash
cd backend
pip install -r requirements.txt
python run.py # Or: flask --app run:app run
```
- **main** — stable-ish beta
- **nightly** — latest features
- **experimental** — where chaos becomes innovation
### Themes
> “This seemed like a great idea at 3am.” — every experimental commit ever
The dashboard supports 14 Dune house themes. Switch via the theme picker in the top-right nav bar:
Classic Dune, House Atreides, House Harkonnen, Fremen, Bene Gesserit, Spacing Guild, Emperor, House Corrino, Mentat, Sardaukar, Bene Tleilax, House Ordos, Ix, CHOAM.
---
## License
Source Available under the **Dune Dashboard Source License (DDSL)**
- No redistribution
- No claiming authorship
- Personal, non-commercial use only
- Basically: look, learn, enjoy — just don’t repost it as “Dune Dashboard Pro Deluxe Edition”.
Themes are implemented via CSS custom properties (`var(--primary)`, `var(--bg)`, etc.) and switched by setting `data-theme` on the `<html>` element.
+1
View File
@@ -39,6 +39,7 @@ DEFAULTS = {
'max_connections': 10,
'owner': 'dune',
'dashboard_schema': 'dashboard',
'dashboard_database_name': 'dashboard',
},
'kubernetes': {
'namespace': '',
+37 -23
View File
@@ -15,7 +15,7 @@ from flask_limiter.util import get_remote_address
from app.config import load_settings
from app.utils.debug_logging import create_debug_log_handler, sanitize_for_log, log_request_details, log_response_details
from app.services.database import DatabaseService
from app.services.database import DatabaseService, DashboardDatabaseService
from app.services.ssh import SSHService
from app.services.k8s import K8sService
from app.services.player import PlayerService
@@ -24,6 +24,7 @@ from app.services.chat import ChatService
from app.services.admin import AdminService
from app.services.updater import UpdateService
from app.services.director import DirectorService
from app.services.rmq import RmqService
from app.utils.cache import MultiCache
from app.routes.main import register_routes
from app.routes.api import register_api_routes
@@ -43,8 +44,10 @@ def create_app(settings_path=None):
static_url_path='/static'
)
app.config['SECRET_KEY'] = settings['dashboard']['secret_key']
app.config['TEMPLATES_AUTO_RELOAD'] = True # Pick up template changes without restart
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
app.config['PERMANENT_SESSION_LIFETIME'] = 28800 # 8 hours
app.config['WTF_CSRF_ENABLED'] = True
app.config['WTF_CSRF_TIME_LIMIT'] = None
@@ -58,7 +61,6 @@ def create_app(settings_path=None):
and settings['dashboard']['ssl_key'] != 'null'
)
# Set SESSION_COOKIE_SECURE conditional on SSL being enabled
app.config['SESSION_COOKIE_SECURE'] = ssl_enabled
# Add security headers manually (replaces deprecated Flask-Talisman)
@@ -188,19 +190,32 @@ def create_app(settings_path=None):
'database': settings['database']['name'],
}
dash_db_config = {
'host': db_host,
'port': settings['database']['port'],
'user': settings['database']['user'],
'password': settings['database']['password'],
'database': settings['database'].get('dashboard_database_name', 'dashboard'),
}
db_service = DatabaseService(
db_config,
min_conn=settings['database']['min_connections'],
max_conn=settings['database']['max_connections'],
dashboard_schema=settings['database'].get('dashboard_schema', 'dashboard')
)
logging.debug(f"DatabaseService initialized: host={db_config['host']}, port={db_config['port']}, user={db_config['user']}")
db_service.ensure_tables()
logging.debug("Database tables ensured")
dash_db_service = DashboardDatabaseService(
dash_db_config,
min_conn=settings['database']['min_connections'],
max_conn=settings['database']['max_connections'],
owner=settings['database'].get('owner', 'dune'),
)
dash_db_service.ensure_tables(game_db=db_service)
# Create performance indexes if they don't exist
try:
admin_svc_for_indexes = AdminService(db_service, None)
admin_svc_for_indexes = AdminService(db_service, None, dash_db=dash_db_service)
success, created, error = admin_svc_for_indexes.create_indexes()
if success and created:
logging.info(f"Created {len(created)} database indexes")
@@ -223,11 +238,11 @@ def create_app(settings_path=None):
static_cache = MultiCache(ttl_seconds=settings['cache']['static_data_ttl'])
player_svc = PlayerService(db_service)
player_svc = PlayerService(db_service, dash_db=dash_db_service)
vehicle_svc = VehicleService(db_service)
chat_svc = ChatService(db_service, k8s_service, ssh_service, static_cache)
chat_svc = ChatService(dash_db_service, k8s_service, ssh_service, static_cache)
logging.debug("ChatService initialized")
admin_svc = AdminService(db_service, ssh_service)
admin_svc = AdminService(db_service, ssh_service, dash_db=dash_db_service)
logging.debug("AdminService initialized")
updater_svc = UpdateService(base_dir)
logging.debug("UpdateService initialized")
@@ -239,9 +254,17 @@ def create_app(settings_path=None):
namespace=settings['kubernetes']['namespace'],
)
logging.debug(f"DirectorService initialized: port={settings.get('director', {}).get('port', 32479)}")
rmq_svc = RmqService(
admin_port=settings.get('rabbitmq', {}).get('admin_port', 30325),
game_port=settings.get('rabbitmq', {}).get('game_port', 32716),
username=settings.get('rabbitmq', {}).get('username', 'dashboard_admin'),
password=settings.get('rabbitmq', {}).get('password', ''),
)
logging.debug(f"RmqService initialized: admin=localhost:{settings.get('rabbitmq', {}).get('admin_port', 30325)} game=localhost:{settings.get('rabbitmq', {}).get('game_port', 32716)}")
services = {
'db': db_service,
'dash_db': dash_db_service,
'ssh': ssh_service,
'k8s': k8s_service,
'player': player_svc,
@@ -251,6 +274,7 @@ def create_app(settings_path=None):
'static_cache': static_cache,
'updater': updater_svc,
'director': director_svc,
'rmq': rmq_svc,
}
logging.debug(f"All services registered: {list(services.keys())}")
@@ -266,11 +290,11 @@ def create_app(settings_path=None):
cors_origins = "*" if settings['dashboard']['host'] == '0.0.0.0' else []
socketio = SocketIO(app, cors_allowed_origins=cors_origins, async_mode='threading')
# Initialize rate limiter (disabled)
# Initialize rate limiter (enabled, per-route limits only)
limiter = Limiter(
app=app,
key_func=get_remote_address,
default_limits=[],
default_limits=[], # rate limits applied per-route only (login has 10/min)
storage_uri="memory://",
)
app.limiter = limiter
@@ -278,22 +302,12 @@ def create_app(settings_path=None):
if settings['auth']['enabled']:
init_auth(app, settings, limiter, audit_svc)
# Auto-login for SPA frontend — bypasses login page
from flask_login import login_user
from app.routes.auth import AdminUser
@app.before_request
def auto_login_dev():
if not current_user.is_authenticated:
cfg_user = str(settings.get("auth", {}).get("username", "dune"))
login_user(AdminUser(cfg_user))
register_routes(app, services, settings)
register_api_routes(app, services, settings)
register_websocket_handlers(socketio, settings)
# Start update checker
updater_svc.start_checker()
# Start update checker (disabled — being reworked)
# updater_svc.start_checker()
@app.teardown_appcontext
def cleanup_db(exc):
+273 -39
View File
@@ -57,7 +57,7 @@ def register_api_routes(app, services, settings):
# Server actions
@app.route('/server/action', methods=['POST'])
@auth_req
@limiter.limit("500 per hour")
def server_action():
deployment = request.form.get('deployment', '')
action = request.form.get('action', '')
@@ -114,7 +114,7 @@ def register_api_routes(app, services, settings):
@app.route('/server/battlegroup/action', methods=['POST'])
@auth_req
@limiter.limit("500 per hour")
def battlegroup_action():
action = request.form.get('action', '')
if action not in ('start', 'stop', 'restart'):
@@ -125,7 +125,7 @@ def register_api_routes(app, services, settings):
@app.route('/server/battlegroup/update', methods=['POST'])
@auth_req
@limiter.limit("1000 per hour")
def battlegroup_update():
bg_script = settings['kubernetes']['battlegroup_script']
out, err, rc = ssh.run(f'{bg_script} update', timeout=600)
@@ -195,7 +195,7 @@ def register_api_routes(app, services, settings):
@app.route('/server/firewall/block', methods=['POST'])
@auth_req
@limiter.limit("500 per hour")
def firewall_block():
port = request.form.get('port', type=int)
bgd_port = _get_bgd_nodeport()
@@ -239,7 +239,7 @@ def register_api_routes(app, services, settings):
@app.route('/server/firewall/unblock', methods=['POST'])
@auth_req
@limiter.limit("500 per hour")
def firewall_unblock():
port = request.form.get('port', type=int)
bgd_port = _get_bgd_nodeport()
@@ -345,7 +345,7 @@ def register_api_routes(app, services, settings):
# Ban management
@app.route('/api/ban_player', methods=['POST'])
@auth_req
@limiter.limit("1000 per hour")
def api_ban_player():
try:
player_id = request.form.get('player_id', type=int)
@@ -408,7 +408,7 @@ def register_api_routes(app, services, settings):
@app.route('/api/unban_player', methods=['POST'])
@auth_req
@limiter.limit("1000 per hour")
def api_unban_player():
try:
player_id = request.form.get('player_id', type=int)
@@ -434,7 +434,7 @@ def register_api_routes(app, services, settings):
@app.route('/api/kick_player', methods=['POST'])
@auth_req
@limiter.limit("500 per hour")
def api_kick_player():
try:
player_id = request.form.get('player_id', type=int)
@@ -449,7 +449,7 @@ def register_api_routes(app, services, settings):
# Vitals editing
@app.route('/api/edit_vitals', methods=['POST'])
@auth_req
@limiter.limit("500 per hour")
def api_edit_vitals():
try:
pawn_id = request.form.get('pawn_id', type=int)
@@ -800,35 +800,66 @@ def register_api_routes(app, services, settings):
FILEBROWSER_BASE_PATH = '/srv'
def _validate_fb_path(path):
"""Validate filebrowser path is within allowed directory."""
import posixpath
"""Validate filebrowser path — allow any path, block traversal."""
path_str = str(path or "").lstrip("/")
if '..' in path_str or '\x00' in path_str:
return False
normalized = posixpath.normpath("/" + path_str)
return normalized == FILEBROWSER_BASE_PATH or normalized.startswith(FILEBROWSER_BASE_PATH + "/")
return True
def _get_fb_pod():
"""Get the FileBrowser pod name dynamically."""
"""Get the default FileBrowser pod name dynamically."""
pod = k8s.find_pod_by_pattern('fb-deploy')
return pod
def _fb_exec(command, timeout=10):
"""Execute kubectl exec in the FileBrowser pod with correct namespace placement."""
pod = _get_fb_pod()
def _list_pods():
"""List all running pods available for file browsing, plus VM host."""
available = ['__VM__ (Host OS)']
pods = k8s.get_pods()
for p in pods:
if p.endswith('-sts-0') or '-deploy-' in p:
available.append(p)
return available
def _fb_exec(command, pod_name=None, timeout=10):
"""Execute a command on the VM host or in a K8s pod."""
if pod_name == '__VM__' or (pod_name and pod_name.startswith('__VM__')):
return k8s.ssh.run(command, timeout=timeout)
pod = pod_name or _get_fb_pod()
if not pod:
return '', 'FileBrowser pod not found', 1
return '', 'No pod specified or found', 1
full_cmd = f'sudo kubectl exec {pod} -n {k8s.namespace} -- {command}'
return k8s.ssh.run(full_cmd, timeout=timeout)
def _fb_write_file(content_b64, path, pod_name=None, timeout=30):
"""Write a file to the pod filesystem."""
import base64
cmd = f"echo '{content_b64}' | base64 -d > '{path}'"
return _fb_exec(f"sh -c {quote_remote(cmd)}", pod_name, timeout)
def _get_pod_from_request():
pod = request.form.get('pod', '') or request.args.get('pod', '') or request.get_json(silent=True)
if isinstance(pod, dict):
pod = pod.get('pod', '')
return pod or None
@app.route('/api/files/pods')
@auth_req
def api_files_pods():
try:
pods = _list_pods()
return jsonify({'success': True, 'pods': pods})
except Exception as e:
return jsonify({'success': False, 'error': str(e)})
@app.route('/api/files/list', methods=['POST'])
@auth_req
def api_files_list():
path = request.form.get('path', '/srv')
pod_name = _get_pod_from_request()
if not _validate_fb_path(path):
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
safe_path = quote_remote(path)
out, err, rc = _fb_exec(f'ls -la {safe_path}', timeout=10)
out, err, rc = _fb_exec(f'ls -la {safe_path}', pod_name, timeout=10)
if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to list directory'})
@@ -855,35 +886,90 @@ def register_api_routes(app, services, settings):
@auth_req
def api_files_view():
path = request.args.get('path', '')
pod_name = _get_pod_from_request()
if not path:
return jsonify({'success': False, 'error': 'Missing path'})
if not _validate_fb_path(path):
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
safe_path = quote_remote(path)
out, err, rc = _fb_exec(f'head -c 100000 {safe_path}', timeout=10)
out, err, rc = _fb_exec(f'head -c 100000 {safe_path}', pod_name, timeout=10)
if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to read file'})
return jsonify({'success': True, 'content': out, 'path': path})
@app.route('/api/files/save', methods=['POST'])
@auth_req
@limiter.limit("50 per hour")
def api_files_save():
path = request.form.get('path', '')
content = request.form.get('content', '')
pod_name = _get_pod_from_request()
if not path:
return jsonify({'success': False, 'error': 'Missing path'})
if not _validate_fb_path(path):
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
import base64
content_b64 = base64.b64encode(content.encode()).decode()
safe_path = quote_remote(path)
save_script = quote_remote(f"base64 -d > {safe_path}")
out, err, rc = _fb_exec(f"sh -c {save_script}", timeout=15)
out, err, rc = _fb_write_file(content_b64, path, pod_name)
if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to save file'})
return jsonify({'success': True})
@app.route('/api/files/download', methods=['POST'])
@auth_req
def api_files_download():
path = request.form.get('path', '')
pod_name = _get_pod_from_request()
if not path:
return jsonify({'success': False, 'error': 'Missing path'})
if not _validate_fb_path(path):
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
import base64
safe_path = quote_remote(path)
out, err, rc = _fb_exec(f'base64 {safe_path}', pod_name, timeout=30)
if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to read file'})
filename = path.rsplit('/', 1)[-1] if '/' in path else path
return jsonify({'success': True, 'content': out.strip(), 'filename': filename})
@app.route('/api/files/upload', methods=['POST'])
@auth_req
def api_files_upload():
target_path = request.form.get('path', '/srv')
uploaded = request.files.get('file')
pod_name = _get_pod_from_request()
if not uploaded:
return jsonify({'success': False, 'error': 'No file provided'})
if not _validate_fb_path(target_path):
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
import base64
filename = uploaded.filename.rsplit('/', 1)[-1].rsplit('\\', 1)[-1] if uploaded.filename else 'uploaded_file'
dest = target_path.rstrip('/') + '/' + filename
if not _validate_fb_path(dest):
return jsonify({'success': False, 'error': 'Invalid destination path'})
content = uploaded.read()
content_b64 = base64.b64encode(content).decode()
out, err, rc = _fb_write_file(content_b64, dest, pod_name)
if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to upload file'})
return jsonify({'success': True, 'filename': filename})
@app.route('/api/files/delete', methods=['POST'])
@auth_req
def api_files_delete():
path = request.form.get('path', '')
pod_name = _get_pod_from_request()
if not path:
return jsonify({'success': False, 'error': 'Missing path'})
if not _validate_fb_path(path):
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
safe_path = quote_remote(path)
out, err, rc = _fb_exec(f'rm -rf {safe_path}', pod_name, timeout=10)
if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to delete'})
return jsonify({'success': True})
director_svc = services.get('director')
director_port = settings.get('director', {}).get('port', 32479)
@@ -922,7 +1008,8 @@ def register_api_routes(app, services, settings):
if map_name:
kv = director_svc.extract_server_config_kv(config)
if kv:
director_svc.update_ini_section(map_name, kv)
if not director_svc.update_ini_section(map_name, kv):
logger.warning("ConfigMap update failed for map %s (director API call succeeded)", map_name)
return result, 200, {'Content-Type': 'application/json'}
except Exception as e:
@@ -992,6 +1079,41 @@ def register_api_routes(app, services, settings):
return jsonify({'success': False, 'error': 'Director unavailable. The BGD service is not responding.'}), 503
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/director/server_set_scale/<map_name>')
@auth_req
def director_server_set_scale_get(map_name):
try:
if not director_svc:
return jsonify({'success': False, 'error': 'Director service not available'}), 503
scale = director_svc.get_server_set_scale(map_name)
if scale is None:
return jsonify({'replicas': 0, 'partitions': []})
spec = scale.get('spec', {})
return jsonify({
'replicas': spec.get('replicas', 0),
'partitions': [p for p in spec.get('partitions', []) if p is not None],
})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/director/server_set_scale/<map_name>', methods=['POST'])
@auth_req
def director_server_set_scale_patch(map_name):
try:
if not director_svc:
return jsonify({'success': False, 'error': 'Director service not available'}), 503
config = request.get_json()
replicas = int(config.get('replicas', 1))
partitions_raw = config.get('partitions', [])
partitions = [int(p) for p in partitions_raw if p is not None]
if replicas > len(partitions):
return jsonify({'success': False, 'error': 'replicas cannot exceed partition count'}), 400
if not director_svc.patch_server_set_scale(map_name, replicas, partitions):
return jsonify({'success': False, 'error': 'Failed to patch ServerSetScale'}), 500
return jsonify({'success': True})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
# Update management
@app.route('/api/update/status')
@auth_req
@@ -1219,7 +1341,7 @@ def register_api_routes(app, services, settings):
# ── Admin Experimental: Broadcast ─────────────────────────────────
@app.route('/api/admin-experimental/broadcast', methods=['POST'])
@auth_req
@limiter.limit("100 per hour")
def admin_broadcast():
data = request.get_json() or {}
title = (data.get('title') or '').strip()
@@ -1236,7 +1358,7 @@ def register_api_routes(app, services, settings):
# ── Admin Experimental: Query Database ────────────────────────────
@app.route('/api/admin-experimental/query', methods=['POST'])
@auth_req
@limiter.limit("300 per hour")
def admin_query():
data = request.get_json() or {}
sql = (data.get('sql') or '').strip()
@@ -1275,7 +1397,7 @@ def register_api_routes(app, services, settings):
# ── Admin Experimental: Adjust Currency ───────────────────────────
@app.route('/api/admin-experimental/adjust-currency', methods=['POST'])
@auth_req
@limiter.limit("200 per hour")
def admin_adjust_currency():
data = request.get_json() or {}
pid = data.get('player_controller_id')
@@ -1289,7 +1411,7 @@ def register_api_routes(app, services, settings):
# ── Admin Experimental: Change Faction ────────────────────────────
@app.route('/api/admin-experimental/change-faction', methods=['POST'])
@auth_req
@limiter.limit("100 per hour")
def admin_change_faction():
data = request.get_json() or {}
pid = data.get('player_id')
@@ -1329,7 +1451,7 @@ def register_api_routes(app, services, settings):
# ── Admin Experimental: Teleport Player ───────────────────────────
@app.route('/api/admin-experimental/teleport', methods=['POST'])
@auth_req
@limiter.limit("100 per hour")
def admin_teleport():
data = request.get_json() or {}
fls_id = data.get('fls_id')
@@ -1413,7 +1535,7 @@ def register_api_routes(app, services, settings):
@app.route('/api/admin-experimental/disband-guild', methods=['POST'])
@auth_req
@limiter.limit("50 per hour")
def admin_disband_guild():
data = request.get_json() or {}
guild_id = data.get('guild_id')
@@ -1427,7 +1549,7 @@ def register_api_routes(app, services, settings):
@app.route('/api/admin-experimental/remove-guild-member', methods=['POST'])
@auth_req
@limiter.limit("100 per hour")
def admin_remove_guild_member():
data = request.get_json() or {}
guild_id = data.get('guild_id')
@@ -1460,7 +1582,7 @@ def register_api_routes(app, services, settings):
@app.route('/api/admin-experimental/flag-cheater', methods=['POST'])
@auth_req
@limiter.limit("50 per hour")
def admin_flag_cheater():
data = request.get_json() or {}
account_id = data.get('account_id')
@@ -1519,7 +1641,7 @@ def register_api_routes(app, services, settings):
@app.route('/api/admin-experimental/delete-character', methods=['POST'])
@auth_req
@limiter.limit("20 per hour")
def admin_delete_character():
data = request.get_json() or {}
actor_id = data.get('actor_id')
@@ -1533,7 +1655,7 @@ def register_api_routes(app, services, settings):
@app.route('/api/admin-experimental/delete-account', methods=['POST'])
@auth_req
@limiter.limit("10 per hour")
def admin_delete_account():
data = request.get_json() or {}
user_id = data.get('user_id')
@@ -1650,7 +1772,7 @@ def register_api_routes(app, services, settings):
# ── Admin Experimental: Spice Fields ──────────────────────────────
@app.route('/api/admin-experimental/spice', methods=['POST'])
@auth_req
@limiter.limit("30 per hour")
def admin_spice():
data = request.get_json() or {}
try:
@@ -1665,7 +1787,7 @@ def register_api_routes(app, services, settings):
# ── Admin Experimental: Server Tools ──────────────────────────────
@app.route('/api/admin-experimental/server-tools', methods=['POST'])
@auth_req
@limiter.limit("30 per hour")
def admin_server_tools():
data = request.get_json() or {}
try:
@@ -1696,6 +1818,118 @@ def register_api_routes(app, services, settings):
except Exception as e:
return jsonify({'success': False, 'error': str(e)})
# ── Admin Experimental: RMQ Explorer ─────────────────────────────
@app.route('/api/admin-experimental/rmq/overview')
@auth_req
def admin_rmq_overview():
try:
rmq = services.get('rmq')
if not rmq:
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
data = rmq.combined_overview()
return jsonify({'success': True, 'data': data})
except Exception as e:
return jsonify({'success': False, 'error': str(e)})
@app.route('/api/admin-experimental/rmq/queues')
@auth_req
def admin_rmq_queues():
try:
rmq = services.get('rmq')
if not rmq:
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
data = rmq.combined_queues()
return jsonify({'success': True, 'data': data})
except Exception as e:
return jsonify({'success': False, 'error': str(e)})
@app.route('/api/admin-experimental/rmq/exchanges')
@auth_req
def admin_rmq_exchanges():
try:
rmq = services.get('rmq')
if not rmq:
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
data = rmq.combined_exchanges()
return jsonify({'success': True, 'data': data})
except Exception as e:
return jsonify({'success': False, 'error': str(e)})
@app.route('/api/admin-experimental/rmq/bindings')
@auth_req
def admin_rmq_bindings():
try:
rmq = services.get('rmq')
if not rmq:
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
data = rmq.bindings()
return jsonify({'success': True, 'data': data})
except Exception as e:
return jsonify({'success': False, 'error': str(e)})
@app.route('/api/admin-experimental/rmq/consumers')
@auth_req
def admin_rmq_consumers():
try:
rmq = services.get('rmq')
if not rmq:
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
data = rmq.consumers()
return jsonify({'success': True, 'data': data})
except Exception as e:
return jsonify({'success': False, 'error': str(e)})
@app.route('/api/admin-experimental/rmq/peek', methods=['POST'])
@auth_req
def admin_rmq_peek():
try:
rmq = services.get('rmq')
if not rmq:
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
cfg = request.get_json() or {}
queue_name = cfg.get('queue', '')
count = int(cfg.get('count', 5))
if not queue_name:
return jsonify({'success': False, 'error': 'queue name required'}), 400
data = rmq.peek_messages(queue_name, count=count)
return jsonify({'success': True, 'data': data})
except Exception as e:
return jsonify({'success': False, 'error': str(e)})
@app.route('/api/admin-experimental/rmq/publish', methods=['POST'])
@auth_req
def admin_rmq_publish():
try:
rmq = services.get('rmq')
if not rmq:
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
cfg = request.get_json() or {}
exchange = cfg.get('exchange', '')
routing_key = cfg.get('routing_key', '')
message = cfg.get('message', '')
side = cfg.get('side', 'admin')
if not exchange:
return jsonify({'success': False, 'error': 'exchange name required'}), 400
if side == 'game':
result = rmq.game_publish(exchange, routing_key, message)
else:
result = rmq.publish(exchange, routing_key, message)
return jsonify({'success': True, 'data': result})
except Exception as e:
return jsonify({'success': False, 'error': str(e)})
@app.route('/api/admin-experimental/rmq/health')
@auth_req
def admin_rmq_health():
try:
rmq = services.get('rmq')
if not rmq:
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
data = rmq.health()
return jsonify({'success': True, 'data': data})
except Exception as e:
return jsonify({'success': False, 'error': str(e)})
# ── Admin Experimental: Function Explorer ─────────────────────────
@app.route('/api/admin-experimental/functions', methods=['GET'])
@auth_req
@@ -1719,7 +1953,7 @@ def register_api_routes(app, services, settings):
@app.route('/api/admin-experimental/functions/<name>/execute', methods=['POST'])
@auth_req
@limiter.limit("200 per hour")
def admin_execute_function(name):
data = request.get_json() or {}
params = data.get('params', [])
@@ -1735,7 +1969,7 @@ def register_api_routes(app, services, settings):
# ── Admin Experimental: SQL Execute (admin functions) ─────────────
@app.route('/api/admin-experimental/execute', methods=['POST'])
@auth_req
@limiter.limit("200 per hour")
def admin_execute():
data = request.get_json() or {}
sql = (data.get('sql') or '').strip()
+44 -30
View File
@@ -2,7 +2,7 @@
import time
import threading
from flask import render_template, request, redirect, url_for, flash
from flask import render_template, request, redirect, url_for, flash, session, make_response
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
@@ -14,6 +14,15 @@ login_manager.login_message = 'Please log in.'
# In-memory failed login tracker: {ip: {"count": int, "first_attempt": float}}
_failed_attempts = {}
_failed_lock = threading.Lock()
# Reusable Argon2 verifier (created once, not per-request)
try:
from argon2 import PasswordHasher, exceptions as argon2_exceptions
_password_hasher = PasswordHasher(time_cost=3, memory_cost=65536)
except ImportError:
_password_hasher = None
argon2_exceptions = None
_failed_lock = threading.Lock()
_MAX_FAILED_ATTEMPTS = 5
_BLOCK_DURATION = 900 # 15 minutes
@@ -82,39 +91,41 @@ def init_auth(app, settings, limiter=None, audit_svc=None):
u = request.form.get('username', '')
p = request.form.get('password', '')
auth = settings.get('auth', {})
cfg_u = str(auth.get('username', ''))
password_hash = auth.get('password_hash')
if u != cfg_u:
if audit_svc:
audit_svc.log('login_failed', {'username': u, 'reason': 'invalid_username'}, user='unknown', severity='warning')
if not password_hash:
flash('Authentication not configured. Please run setup.')
return render_template('login.html')
try:
# Always run Argon2 verify regardless of username (prevents timing enumeration)
from argon2 import exceptions
_DUMMY = '$argon2id$v=19$m=65536,t=3,p=4$AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
hash_to_verify = password_hash if u == cfg_u else _DUMMY
verified = _password_hasher.verify(hash_to_verify, p)
if verified and u == cfg_u:
_clear_failed_attempts(client_ip)
login_user(AdminUser(u))
if audit_svc:
audit_svc.log('login_success', {'username': u}, user=u, severity='info')
return redirect(url_for('overview'))
else:
# Dummy always fails; wrong password also fails here
_record_failed_attempt(client_ip)
if u == cfg_u and audit_svc:
audit_svc.log('login_failed', {'username': u, 'reason': 'invalid_password'}, user=u, severity='warning')
elif audit_svc:
audit_svc.log('login_failed', {'username': u, 'reason': 'invalid_credentials'}, user='unknown', severity='warning')
flash('Invalid username or password')
return render_template('login.html')
except exceptions.VerifyMismatchError:
_record_failed_attempt(client_ip)
flash('Invalid username or password')
return render_template('login.html')
if password_hash:
try:
from argon2 import PasswordHasher, exceptions
ph = PasswordHasher(time_cost=3, memory_cost=65536)
if ph.verify(password_hash, p):
_clear_failed_attempts(client_ip)
login_user(AdminUser(u))
if audit_svc:
audit_svc.log('login_success', {'username': u}, user=u, severity='info')
return redirect(url_for('overview'))
else:
if audit_svc:
audit_svc.log('login_failed', {'username': u, 'reason': 'invalid_password'}, user=u, severity='warning')
except exceptions.VerifyMismatchError:
if audit_svc:
audit_svc.log('login_failed', {'username': u, 'reason': 'invalid_password'}, user=u, severity='warning')
pass
except Exception:
flash('Authentication error. Please try again.')
return render_template('login.html')
else:
flash('Authentication not configured. Please run setup.')
except Exception as e:
flash('Authentication error. Please try again.')
return render_template('login.html')
_record_failed_attempt(client_ip)
@@ -123,10 +134,13 @@ def init_auth(app, settings, limiter=None, audit_svc=None):
return render_template('login.html')
@app.route('/logout')
@login_required
def logout():
user = current_user.id if current_user.is_authenticated else 'unknown'
logout_user()
session.clear()
if audit_svc:
audit_svc.log('logout', {}, user=user, severity='info')
return redirect(url_for('login'))
resp = make_response(redirect(url_for('login')))
resp.delete_cookie('session')
resp.delete_cookie('remember_token')
return resp
+77 -18
View File
@@ -6,6 +6,7 @@ from flask import Blueprint, render_template, request, jsonify
from flask_login import login_required, current_user
from app.utils.constants import NAV_PAGES, GUILD_ROLES
from app.utils.debug_logging import sanitize_for_log
from app.services.player import LIKE_PC
logger = logging.getLogger(__name__)
@@ -326,20 +327,32 @@ def register_routes(app, services, settings):
try:
buildings_list = db.query("""
SELECT a.id, a.class, a.map, a.transform::text as transform_text,
COALESCE(NULLIF(ps.character_name, ''), NULLIF(ea.platform_name, ''), 'ID:' || b.owner_id::text) as owner_name,
COALESCE(NULLIF(owner.character_name, ''), 'Base ' || b.id::text) as owner_name,
(SELECT COUNT(*)::int FROM dune.building_instances bi WHERE bi.building_id = b.id) as instance_count,
a.properties->>'m_bIsPowered' as is_powered,
a.properties->>'m_PowerLevel' as power_level,
a.properties->'PowerComponent'->>'m_PowerGridID' as power_grid_id
FROM dune.buildings b
JOIN dune.actors a ON b.id = a.id
LEFT JOIN dune.player_state ps ON b.owner_id = ps.player_pawn_id
LEFT JOIN dune.encrypted_accounts ea ON ea.id = (
SELECT ps2.account_id FROM dune.player_state ps2 WHERE ps2.player_pawn_id = b.owner_id LIMIT 1
)
LEFT JOIN LATERAL (
SELECT DISTINCT afe_totem.actor_id as totem_actor_id
FROM dune.building_instances bi
JOIN dune.actor_fgl_entities afe_totem ON afe_totem.entity_id = bi.owner_entity_id
WHERE bi.building_id = b.id
LIMIT 1
) totem ON true
LEFT JOIN LATERAL (
SELECT ps.character_name
FROM dune.actors pawn
JOIN dune.player_state ps ON pawn.id = ps.player_pawn_id
WHERE pawn.id BETWEEN totem.totem_actor_id - 6 AND totem.totem_actor_id - 1
AND pawn.class LIKE %s
ORDER BY totem.totem_actor_id - pawn.id
LIMIT 1
) owner ON true
ORDER BY owner_name
LIMIT 200
""") or []
""", [LIKE_PC]) or []
return render_template('buildings.html', buildings=buildings_list)
except Exception as e:
logger.exception("Error in buildings route")
@@ -426,7 +439,7 @@ def register_routes(app, services, settings):
def server_status():
logger.debug(f"Page access: /server by user={current_user.id}")
try:
active_servers = db.query("""
active_servers_raw = db.query("""
SELECT server_id, map
FROM dune.world_partition
WHERE server_id IS NOT NULL
@@ -448,6 +461,34 @@ def register_routes(app, services, settings):
deployments = k8s.get_deployments()
node_metrics = k8s.get_node_metrics()
active_servers = []
for s in active_servers_raw:
sid = (s.get('server_id') or '').lower().replace('_', '-')
s['deployment'] = ''
mp = (s.get('map') or '').lower().replace('_', '-')
for d in deployments:
short = d.replace('deployment.apps/', '')
if sid and sid in short.lower():
s['deployment'] = d
break
if mp and mp in short.lower():
s['deployment'] = d
break
if not s['deployment']:
mid = '-sg-' + sid
for d in deployments:
short = d.replace('deployment.apps/', '')
if mid in short.lower():
s['deployment'] = d
break
if not s['deployment'] and mp:
for d in deployments:
short = d.replace('deployment.apps/', '')
if mp in short.lower() and 'pod' in short.lower():
s['deployment'] = d
break
active_servers.append(s)
for p in partitions:
sid = (p.get('server_id') or '').lower().replace('_', '-')
p['deployment'] = ''
@@ -482,7 +523,7 @@ def register_routes(app, services, settings):
online_players=online_players, partitions=partitions,
overmap_count=overmap_count.get('c') if overmap_count else 0,
online_count=online_count.get('c') if online_count else 0,
deployments=deployments, deploys_ok=True, ssh_error='',
deployments=deployments, deploys_ok=len(deployments) > 0, ssh_error='',
node_metrics=node_metrics)
except Exception as e:
logger.exception("Error in server_status route")
@@ -524,7 +565,7 @@ def register_routes(app, services, settings):
name: cfg for name, cfg in map_config.items()
if isinstance(cfg, dict) and cfg.get('image') and cfg.get('bounds')
}
default_map = map_config.get('default_map', 'DeepDesert')
default_map = map_config.get('default_map', 'HaggaBasin')
return map_config, configured_maps, default_map
@@ -535,6 +576,7 @@ def register_routes(app, services, settings):
map_options = []
for key, cfg in configured_maps.items():
image_size = cfg.get('image_size', {})
bounds = cfg.get('bounds', {})
map_options.append({
'key': key,
'label': cfg.get('label') or key,
@@ -542,6 +584,7 @@ def register_routes(app, services, settings):
'width': image_size.get('width', 1000),
'height': image_size.get('height', 1000),
'default_zoom': cfg.get('default_zoom', 0.5),
'bounds': bounds,
'counts': {
'players': sum(1 for p in player_locations if p.get('map') == key and p.get('in_bounds')),
'vehicles': sum(1 for v in vehicle_locations if v.get('map') == key and v.get('in_bounds')),
@@ -569,27 +612,43 @@ def register_routes(app, services, settings):
# Get vehicles with coordinates for configured map assets
vehicles = db.query("""
SELECT v.id, a.map, a.transform, a.class
SELECT DISTINCT ON (v.id)
v.id, a.map, a.transform, a.class,
COALESCE(NULLIF(ps.character_name, ''), 'Vehicle ' || v.id::text) as owner_name
FROM dune.vehicles v
JOIN dune.actors a ON v.id = a.id
LEFT JOIN dune.permission_actor_rank par ON par.permission_actor_id = v.id
LEFT JOIN dune.player_state ps ON par.player_id = ps.player_controller_id
WHERE a.transform IS NOT NULL AND a.map = ANY(%s)
ORDER BY a.map, a.class
ORDER BY v.id, par.rank ASC
""", [selected_map_keys]) or []
# Get bases/buildings with coordinates for configured map assets
buildings = db.query("""
SELECT b.id, a.map, a.transform, a.class,
COALESCE(NULLIF(ps.character_name, ''), NULLIF(ea.platform_name, ''), 'Base ' || b.id::text) as owner_name
COALESCE(NULLIF(owner.character_name, ''), 'Base ' || b.id::text) as owner_name
FROM dune.buildings b
JOIN dune.actors a ON b.id = a.id
LEFT JOIN dune.player_state ps ON b.owner_id = ps.player_pawn_id
LEFT JOIN dune.encrypted_accounts ea ON ea.id = (
SELECT ps2.account_id FROM dune.player_state ps2 WHERE ps2.player_pawn_id = b.owner_id LIMIT 1
)
LEFT JOIN LATERAL (
SELECT DISTINCT afe_totem.actor_id as totem_actor_id
FROM dune.building_instances bi
JOIN dune.actor_fgl_entities afe_totem ON afe_totem.entity_id = bi.owner_entity_id
WHERE bi.building_id = b.id
LIMIT 1
) totem ON true
LEFT JOIN LATERAL (
SELECT ps.character_name
FROM dune.actors pawn
JOIN dune.player_state ps ON pawn.id = ps.player_pawn_id
WHERE pawn.id BETWEEN totem.totem_actor_id - 6 AND totem.totem_actor_id - 1
AND pawn.class LIKE %s
ORDER BY totem.totem_actor_id - pawn.id
LIMIT 1
) owner ON true
WHERE a.transform IS NOT NULL AND a.map = ANY(%s)
ORDER BY a.map
LIMIT 500
""", [selected_map_keys]) or []
""", [LIKE_PC, selected_map_keys]) or []
# Parse coordinates from transform field
def parse_transform(t):
@@ -631,7 +690,7 @@ def register_routes(app, services, settings):
if coords:
vehicle_locations.append({
'id': v['id'],
'name': v.get('name', 'Unknown'),
'name': v.get('owner_name') or v.get('class', '').split('/')[-1] if v.get('class') else f'Vehicle {v["id"]}',
'map': v['map'],
'class': v.get('class', '').split('/')[-1] if v.get('class') else '',
'x': coords['x'],
+76 -86
View File
@@ -26,9 +26,10 @@ def _validate_ip(ip):
class AdminService:
_iptables_lock = threading.Lock()
def __init__(self, db_service, ssh_service):
def __init__(self, db_service, ssh_service, dash_db=None):
self.db = db_service
self.ssh = ssh_service
self.dash_db = dash_db or db_service
def ban_player(self, player_id, duration=0, reason='', note=''):
try:
@@ -44,17 +45,11 @@ class AdminService:
account_id = player_row.get('account_id') if player_row else None
player_name = player_row.get('character_name', 'Unknown') if player_row else 'Unknown'
conn = self.db.get_connection()
if not conn:
return False, "Database connection failed"
cur = None
try:
cur = conn.cursor()
if account_id:
if duration_int == 0:
cur.execute("""
INSERT INTO dashboard.bans (player_id, account_id, reason, note, duration, banned_at, expires_at, active)
self.dash_db.execute("""
INSERT INTO bans (player_id, account_id, reason, note, duration, banned_at, expires_at, active)
VALUES (%s, %s, %s, %s, %s, NOW(), NULL, TRUE)
ON CONFLICT (player_id) DO UPDATE SET
account_id = EXCLUDED.account_id, reason = EXCLUDED.reason,
@@ -62,8 +57,8 @@ class AdminService:
banned_at = NOW(), expires_at = NULL, active = TRUE
""", [player_id, account_id, reason, note, duration_int])
else:
cur.execute("""
INSERT INTO dashboard.bans (player_id, account_id, reason, note, duration, banned_at, expires_at, active)
self.dash_db.execute("""
INSERT INTO bans (player_id, account_id, reason, note, duration, banned_at, expires_at, active)
VALUES (%s, %s, %s, %s, %s, NOW(), NOW() + INTERVAL '1 minute' * %s, TRUE)
ON CONFLICT (player_id) DO UPDATE SET
account_id = EXCLUDED.account_id, reason = EXCLUDED.reason,
@@ -72,8 +67,8 @@ class AdminService:
""", [player_id, account_id, reason, note, duration_int, duration_int, duration_int])
else:
if duration_int == 0:
cur.execute("""
INSERT INTO dashboard.bans (player_id, reason, note, duration, banned_at, expires_at, active)
self.dash_db.execute("""
INSERT INTO bans (player_id, reason, note, duration, banned_at, expires_at, active)
VALUES (%s, %s, %s, %s, NOW(), NULL, TRUE)
ON CONFLICT (player_id) DO UPDATE SET
reason = EXCLUDED.reason, note = EXCLUDED.note,
@@ -81,8 +76,8 @@ class AdminService:
expires_at = NULL, active = TRUE
""", [player_id, reason, note, duration_int])
else:
cur.execute("""
INSERT INTO dashboard.bans (player_id, reason, note, duration, banned_at, expires_at, active)
self.dash_db.execute("""
INSERT INTO bans (player_id, reason, note, duration, banned_at, expires_at, active)
VALUES (%s, %s, %s, %s, NOW(), NOW() + INTERVAL '1 minute' * %s, TRUE)
ON CONFLICT (player_id) DO UPDATE SET
reason = EXCLUDED.reason, note = EXCLUDED.note,
@@ -90,47 +85,47 @@ class AdminService:
expires_at = NOW() + INTERVAL '1 minute' * %s, active = TRUE
""", [player_id, reason, note, duration_int, duration_int, duration_int])
conn.commit()
audit_logger.info(f"BAN: player_id={player_id} player_name={player_name} duration={duration_int}min reason={reason}")
return True, f"Player {player_name} banned for {duration_int} minutes"
except Exception as e:
logger.error(f"Failed to ban player {player_id}: {e}")
if conn:
conn.rollback()
return False, str(e)
finally:
if cur:
cur.close()
self.db.return_connection(conn)
def unban_player(self, player_id):
conn = self.db.get_connection()
if not conn:
return False, "Database connection failed"
cur = None
try:
cur = conn.cursor()
cur.execute("DELETE FROM dashboard.bans WHERE player_id = %s", [player_id])
conn.commit()
# Delete from dashboard bans
self.dash_db.execute("DELETE FROM bans WHERE player_id = %s", [player_id])
cur.execute("SELECT ps.account_id FROM dune.player_state ps WHERE ps.player_controller_id = %s", [player_id])
account_row = cur.fetchone()
account_id = account_row[0] if account_row and isinstance(account_row, (tuple, list)) else (account_row.get('account_id') if account_row else None)
# Look up account info from game database
account_row = self.db.query(
"SELECT ps.account_id FROM dune.player_state ps WHERE ps.player_controller_id = %s",
[player_id], one=True
)
account_id = account_row.get('account_id') if account_row else None
ips_to_unblock = []
if account_id:
all_ips = self.db.query("""
SELECT ip_address FROM dashboard.player_ips
WHERE player_id IN (SELECT player_controller_id FROM dune.player_state WHERE account_id = %s)
""", [account_id]) or []
ips_to_unblock = [r.get('ip_address') for r in all_ips if r.get('ip_address')]
game_account_players = self.db.query(
"SELECT player_controller_id FROM dune.player_state WHERE account_id = %s",
[account_id]
) or []
account_player_ids = [r['player_controller_id'] for r in game_account_players]
if account_player_ids:
placeholders = ','.join(['%s'] * len(account_player_ids))
ips_rows = self.dash_db.query(
f"SELECT ip_address FROM player_ips WHERE player_id IN ({placeholders})",
account_player_ids
) or []
ips_to_unblock = [r.get('ip_address') for r in ips_rows if r.get('ip_address')]
else:
ip_row = self.db.query("SELECT ip_address FROM dashboard.player_ips WHERE player_id = %s", [player_id], one=True)
ip_row = self.dash_db.query("SELECT ip_address FROM player_ips WHERE player_id = %s", [player_id], one=True)
if ip_row and ip_row.get('ip_address'):
ips_to_unblock.append(ip_row.get('ip_address'))
cur.execute("INSERT INTO dashboard.player_actions (player_id, action_type, reason, duration_minutes) VALUES (%s, 'unban', 'Manual unban', 0)", [player_id])
conn.commit()
self.dash_db.execute(
"INSERT INTO player_actions (player_id, action_type, reason, duration_minutes) VALUES (%s, 'unban', 'Manual unban', 0)",
[player_id]
)
with self._iptables_lock:
for ip in ips_to_unblock:
@@ -144,13 +139,7 @@ class AdminService:
return True, f"Player unbanned. Cleared {len(ips_to_unblock)} IP block(s)."
except Exception as e:
logger.error(f"Failed to unban player {player_id}: {e}")
if conn:
conn.rollback()
return False, str(e)
finally:
if cur:
cur.close()
self.db.return_connection(conn)
def kick_player(self, player_id):
player = self.db.query("""
@@ -163,7 +152,7 @@ class AdminService:
return False, "Player not found"
player_name = player.get('character_name', 'Unknown')
ip_row = self.db.query("SELECT ip_address FROM dashboard.player_ips WHERE player_id = %s", [player_id], one=True)
ip_row = self.dash_db.query("SELECT ip_address FROM player_ips WHERE player_id = %s", [player_id], one=True)
player_ip = ip_row.get('ip_address') if ip_row else None
if not player_ip:
@@ -184,7 +173,7 @@ class AdminService:
thread = threading.Thread(target=temporary_block, args=(player_ip,), daemon=True)
thread.start()
self.db.execute("INSERT INTO dashboard.player_actions (player_id, action_type, reason, duration_minutes, ip_address) VALUES (%s, 'kick', 'Temporary kick', 1, %s)", [player_id, player_ip])
self.dash_db.execute("INSERT INTO player_actions (player_id, action_type, reason, duration_minutes, ip_address) VALUES (%s, 'kick', 'Temporary kick', 1, %s)", [player_id, player_ip])
audit_logger.info(f"KICK: player_id={player_id} player_name={player_name} ip={player_ip}")
return True, f"Player {player_name} kicked (IP {player_ip} blocked for 60 seconds)"
@@ -262,14 +251,8 @@ class AdminService:
if not game_pods:
return False, "No game server pods found"
conn = self.db.get_connection()
if not conn:
return False, "Database connection failed"
cur = None
updated = 0
try:
cur = conn.cursor()
for pod_name, map_name in game_pods:
cmd = f'sudo kubectl exec -n {namespace} {pod_name} -- find /home/dune -name "*.log" -path "*/Logs/*" 2>/dev/null | head -5'
out_logs, err_logs, rc_logs = self.ssh.run(cmd)
@@ -302,26 +285,25 @@ class AdminService:
if ip_to_player:
for ip, name in ip_to_player.items():
cur.execute("""
player_row = self.db.query("""
SELECT ps.player_controller_id, ps.account_id
FROM dune.player_state ps
JOIN dune.accounts a ON ps.account_id = a.id
WHERE a.funcom_id = %s OR ps.character_name = %s
LIMIT 1
""", [name, name])
row = cur.fetchone()
if row:
pid = row[0] if isinstance(row, (tuple, list)) else row.get('funcom_id')
account_id = row[1] if isinstance(row, (tuple, list)) else row.get('account_id')
cur.execute("""
INSERT INTO dashboard.player_ips (player_id, ip_address, updated_at)
""", [name, name], one=True)
if player_row:
pid = player_row.get('player_controller_id')
account_id = player_row.get('account_id')
self.dash_db.execute("""
INSERT INTO player_ips (player_id, ip_address, updated_at)
VALUES (%s, %s, NOW())
ON CONFLICT (player_id) DO UPDATE SET ip_address = EXCLUDED.ip_address, updated_at = NOW()
""", [pid, ip])
updated += 1
ban_check = self.db.query("""
SELECT player_id FROM dashboard.bans
ban_check = self.dash_db.query("""
SELECT player_id FROM bans
WHERE (player_id = %s OR account_id = %s) AND (active = TRUE OR active IS NULL)
LIMIT 1
""", [pid, account_id], one=True)
@@ -334,21 +316,14 @@ class AdminService:
else:
logger.warning(f"Skipping invalid IP for ban block: {ip}")
conn.commit()
return True, f"Updated {updated} player IPs from game logs"
except Exception as e:
logger.error(f"Failed to detect player IPs: {e}")
if conn:
conn.rollback()
return False, str(e)
finally:
if cur:
cur.close()
self.db.return_connection(conn)
def set_player_ip(self, player_id, ip_address):
return self.db.execute("""
INSERT INTO dashboard.player_ips (player_id, ip_address, updated_at)
return self.dash_db.execute("""
INSERT INTO player_ips (player_id, ip_address, updated_at)
VALUES (%s, %s, NOW())
ON CONFLICT (player_id) DO UPDATE SET ip_address = EXCLUDED.ip_address, updated_at = NOW()
""", [player_id, ip_address])
@@ -363,21 +338,31 @@ class AdminService:
return True, f"Unblocked {ip}"
def get_bans(self, limit=50):
return self.db.query("""
SELECT b.id, b.player_id, b.reason, b.active, b.banned_at, b.expires_at, ps.character_name
FROM dashboard.bans b
LEFT JOIN dune.player_state ps ON b.player_id = ps.player_controller_id
ORDER BY b.banned_at DESC
bans = self.dash_db.query("""
SELECT id, player_id, reason, active, banned_at, expires_at
FROM bans
ORDER BY banned_at DESC
LIMIT %s
""", [limit]) or []
for ban in bans:
pid = ban.get('player_id')
if pid:
player = self.db.query(
"SELECT character_name FROM dune.player_state WHERE player_controller_id = %s",
[pid], one=True
)
ban['character_name'] = player.get('character_name', '') if player else ''
else:
ban['character_name'] = ''
return bans
def get_player_ban(self, player_id):
return self.db.query("SELECT reason, note, duration, banned_at, expires_at FROM dashboard.bans WHERE player_id = %s", [player_id], one=True)
return self.dash_db.query("SELECT reason, note, duration, banned_at, expires_at FROM bans WHERE player_id = %s", [player_id], one=True)
def get_player_history(self, player_id, limit=20):
return self.db.query("""
return self.dash_db.query("""
SELECT action_type, reason, note, duration_minutes, created_at, ip_address
FROM dashboard.player_actions
FROM player_actions
WHERE player_id = %s
ORDER BY created_at DESC
LIMIT %s
@@ -813,17 +798,22 @@ class AdminService:
try:
import base64
import json as _json
title_json = _json.dumps(title)[1:-1]
message_json = _json.dumps(message)[1:-1]
import os
token = os.environ.get('DUNE_BROADCAST_TOKEN',
getattr(self, '_broadcast_token', None) or 'Nu6VmPWUMvdPMeB7qErr')
title_b64 = base64.b64encode(title.encode('utf-8')).decode()
message_b64 = base64.b64encode(message.encode('utf-8')).decode()
erl = (
f'Title = unicode:characters_to_binary(<<"{title_json}">>, utf8), '
f'Body = unicode:characters_to_binary(<<"{message_json}">>, utf8), '
f'Title = base64:decode(<<"{title_b64}">>), '
f'Body = base64:decode(<<"{message_b64}">>), '
f'Duration = {duration}, '
f'Token = <<"{token}">>, '
'EntryEn = #{<<"Key">> => <<"en">>, <<"Title">> => Title, <<"Body">> => Body}, '
'EntryEnUs = #{<<"Key">> => <<"en-US">>, <<"Title">> => Title, <<"Body">> => Body}, '
'Inner = iolist_to_binary(rabbit_json:encode(#{<<"ServerCommand">> => <<"ServiceBroadcast">>, <<"BroadcastType">> => <<"Generic">>, <<"BroadcastPayload">> => #{<<"BroadcastDuration">> => Duration, <<"LocalizedText">> => [EntryEn, EntryEnUs]}})), '
'Outer = iolist_to_binary(rabbit_json:encode(#{<<"Version">> => 2, <<"AuthToken">> => <<"Nu6VmPWUMvdPMeB7qErr">>, <<"MessageContent">> => Inner})), '
'Outer = iolist_to_binary(rabbit_json:encode(#{<<"Version">> => 2, <<"AuthToken">> => Token, <<"MessageContent">> => Inner})), '
'XName = rabbit_misc:r(<<"/">>, exchange, <<"heartbeats">>), '
'X = rabbit_exchange:lookup_or_die(XName), '
'MsgId = list_to_binary("manual-service-broadcast-" ++ integer_to_list(erlang:system_time(millisecond))), '
+6 -6
View File
@@ -9,7 +9,7 @@ logger = logging.getLogger(__name__)
class ChatService:
def __init__(self, db_service, k8s_service, ssh_service, cache):
self.db = db_service
self.db = db_service # DashboardDatabaseService
self.k8s = k8s_service
self.ssh = ssh_service
self.cache = cache
@@ -20,7 +20,7 @@ class ChatService:
return True
try:
self.db.execute("""
CREATE TABLE IF NOT EXISTS dashboard.chat_history (
CREATE TABLE IF NOT EXISTS chat_history (
id SERIAL PRIMARY KEY,
timestamp TIMESTAMP DEFAULT NOW(),
channel VARCHAR(50),
@@ -33,7 +33,7 @@ class ChatService:
is_admin BOOLEAN DEFAULT FALSE
)
""")
self.db.execute("CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON dashboard.chat_history (timestamp DESC)")
self.db.execute("CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON chat_history (timestamp DESC)")
self.ensured_table = True
logger.info("Chat history table ready")
return True
@@ -46,7 +46,7 @@ class ChatService:
loc_y = location.get('Y', 0) if location else 0
loc_z = location.get('Z', 0) if location else 0
return self.db.execute("""
INSERT INTO dashboard.chat_history (channel, sender, message, target, location_x, location_y, location_z, is_admin)
INSERT INTO chat_history (channel, sender, message, target, location_x, location_y, location_z, is_admin)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
""", [channel, sender, message, target, loc_x, loc_y, loc_z, is_admin])
@@ -61,7 +61,7 @@ class ChatService:
cur = conn.cursor()
for msg in messages:
cur.execute("""
INSERT INTO dashboard.chat_history (channel, sender, message, target, location_x, location_y, location_z, is_admin)
INSERT INTO chat_history (channel, sender, message, target, location_x, location_y, location_z, is_admin)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
""", [
msg['channel'], msg['sender'], msg['message'],
@@ -87,7 +87,7 @@ class ChatService:
return self.db.query("""
SELECT id, timestamp, channel, sender, message, target,
location_x, location_y, location_z, is_admin
FROM dashboard.chat_history
FROM chat_history
ORDER BY timestamp DESC
LIMIT %s
""", [limit])
+248 -12
View File
@@ -10,11 +10,10 @@ logger = logging.getLogger(__name__)
class DatabaseService:
def __init__(self, db_config, min_conn=2, max_conn=10, dashboard_schema='dashboard'):
def __init__(self, db_config, min_conn=2, max_conn=10):
self.db_config = db_config
self.min_conn = min_conn
self.max_conn = max_conn
self.dashboard_schema = dashboard_schema
self.pool = None
def init_pool(self):
@@ -138,23 +137,186 @@ class DatabaseService:
return False
def ensure_tables(self):
"""No-op: dashboard tables now live in a separate database."""
pass
class DashboardDatabaseService:
"""Service for the dedicated dashboard database (player_ips, bans, audit_log, etc.)."""
def __init__(self, db_config, min_conn=2, max_conn=10, owner='dune'):
self.db_config = db_config
self.min_conn = min_conn
self.max_conn = max_conn
self.owner = owner
self.pool = None
self._migrated = False
def init_pool(self):
if self.pool is not None:
return self.pool
for attempt in range(10):
try:
self.pool = psycopg2.pool.ThreadedConnectionPool(
minconn=self.min_conn,
maxconn=self.max_conn,
**self.db_config
)
logger.info("Dashboard database pool initialized")
return self.pool
except psycopg2.OperationalError as e:
if 'does not exist' in str(e) and attempt == 0:
logger.info("Dashboard database does not exist, creating...")
self._ensure_database()
continue
if attempt < 9:
logger.warning(f"Dashboard DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
time.sleep(2)
else:
logger.error(f"Failed to initialize dashboard pool after 10 attempts: {e}")
self.pool = None
except Exception as e:
if attempt < 9:
logger.warning(f"Dashboard DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
time.sleep(2)
else:
logger.error(f"Failed to initialize dashboard pool after 10 attempts: {e}")
self.pool = None
return self.pool
def _ensure_database(self):
try:
admin_config = dict(self.db_config)
admin_config['database'] = 'postgres'
conn = psycopg2.connect(**admin_config)
conn.autocommit = True
cur = conn.cursor()
cur.execute("SELECT 1 FROM pg_database WHERE datname = %s", [self.db_config['database']])
if not cur.fetchone():
cur.execute(f"CREATE DATABASE {self.db_config['database']} OWNER {self.db_config['user']}")
logger.info("Created dashboard database '%s'", self.db_config['database'])
cur.close()
conn.close()
except Exception as e:
logger.error("Failed to create dashboard database: %s", e)
raise
def _migrate_old_schema(self, game_db):
if self._migrated:
return
tables = ['settings', 'bans', 'player_ips', 'player_actions', 'audit_log', 'chat_history']
migrated = False
for table in tables:
try:
rows = game_db.query(f"SELECT count(*) as cnt FROM dashboard.{table}", one=True)
if rows and rows.get('cnt', 0) > 0:
logger.info("Migrating %d rows from dashboard.%s", rows['cnt'], table)
old_rows = game_db.query(f"SELECT * FROM dashboard.{table}")
if old_rows:
cols = list(old_rows[0].keys())
placeholders = ','.join(['%s'] * len(cols))
col_names = ','.join(cols)
for row in old_rows:
vals = [row[c] for c in cols]
self.execute(
f"INSERT INTO {table} ({col_names}) VALUES ({placeholders}) ON CONFLICT DO NOTHING",
vals,
)
migrated = True
logger.info("Migrated dashboard.%s -> %s (%d rows)", table, table, rows['cnt'])
except Exception as e:
logger.debug("No data to migrate from dashboard.%s: %s", table, e)
if migrated:
logger.info("Data migration from old dashboard schema complete")
self._migrated = True
def get_connection(self):
try:
pool = self.init_pool()
if pool:
return pool.getconn()
return psycopg2.connect(**self.db_config)
except Exception as e:
logger.error("Failed to get dashboard connection: %s", e)
return None
def return_connection(self, conn):
if conn and self.pool and hasattr(conn, 'poll'):
try:
self.pool.putconn(conn)
except Exception:
try:
conn.close()
except Exception:
pass
def close_all(self):
if self.pool:
try:
self.pool.closeall()
except Exception as e:
logger.error("Error closing dashboard pool: %s", e)
self.pool = None
def query(self, sql, params=None, one=False):
conn = self.get_connection()
if not conn:
return {} if one else []
cur = None
try:
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute(sql, params)
rows = cur.fetchall()
if one and rows:
return rows[0]
if one:
return {}
return rows
except Exception as e:
logger.error("Dashboard query error: %s", e)
raise
finally:
if cur:
cur.close()
self.return_connection(conn)
def execute(self, sql, params=None, commit=True):
conn = self.get_connection()
if not conn:
return False
cur = None
try:
cur = conn.cursor()
cur.execute(sql, params)
if commit:
conn.commit()
return True
except Exception as e:
logger.error("Dashboard execute error: %s", e)
if conn:
conn.rollback()
return False
finally:
if cur:
cur.close()
self.return_connection(conn)
def ensure_tables(self, game_db=None):
conn = self.get_connection()
if not conn:
return
cur = None
schema = self.dashboard_schema
try:
cur = conn.cursor()
cur.execute(f"CREATE SCHEMA IF NOT EXISTS {schema}")
cur.execute(f"""
CREATE TABLE IF NOT EXISTS {schema}.player_ips (
cur.execute("""
CREATE TABLE IF NOT EXISTS player_ips (
player_id BIGINT PRIMARY KEY,
ip_address INET NOT NULL,
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
)
""")
cur.execute(f"""
CREATE TABLE IF NOT EXISTS {schema}.bans (
cur.execute("""
CREATE TABLE IF NOT EXISTS bans (
id SERIAL PRIMARY KEY,
player_id BIGINT UNIQUE,
account_id BIGINT,
@@ -166,8 +328,8 @@ class DatabaseService:
active BOOLEAN DEFAULT TRUE
)
""")
cur.execute(f"""
CREATE TABLE IF NOT EXISTS {schema}.player_actions (
cur.execute("""
CREATE TABLE IF NOT EXISTS player_actions (
id SERIAL PRIMARY KEY,
player_id BIGINT NOT NULL,
action_type VARCHAR(50) NOT NULL,
@@ -178,13 +340,87 @@ class DatabaseService:
created_at TIMESTAMP NOT NULL DEFAULT NOW()
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS audit_log (
id BIGSERIAL PRIMARY KEY,
action_type VARCHAR(50) NOT NULL,
user_name VARCHAR(100) NOT NULL,
target_player_id BIGINT,
details JSONB DEFAULT '{}',
source_ip INET,
severity VARCHAR(20) DEFAULT 'info',
created_at TIMESTAMP NOT NULL DEFAULT NOW()
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS chat_history (
id SERIAL PRIMARY KEY,
timestamp TIMESTAMP DEFAULT NOW(),
channel VARCHAR(50),
sender VARCHAR(255),
message TEXT,
target VARCHAR(255),
location_x FLOAT,
location_y FLOAT,
location_z FLOAT,
is_admin BOOLEAN DEFAULT FALSE
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS settings (
key VARCHAR(255) PRIMARY KEY,
value TEXT DEFAULT '',
updated_at TIMESTAMP DEFAULT NOW()
)
""")
owner = self.owner
cur.execute(f"""
DO $$DECLARE r RECORD;
BEGIN
FOR r IN SELECT tablename FROM pg_tables WHERE schemaname = 'public'
LOOP
EXECUTE 'ALTER TABLE public.' || quote_ident(r.tablename) || ' OWNER TO {owner}';
END LOOP;
END$$;
""")
cur.execute(f"""
DO $$DECLARE r RECORD;
BEGIN
FOR r IN SELECT sequencename FROM pg_sequences WHERE schemaname = 'public'
LOOP
EXECUTE 'ALTER SEQUENCE public.' || quote_ident(r.sequencename) || ' OWNER TO {owner}';
END LOOP;
END$$;
""")
cur.execute(f"ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO {owner}")
cur.execute(f"ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO {owner}")
conn.commit()
logger.info(f"Dashboard tables ensured in schema '{schema}' (player_ips, bans, player_actions)")
logger.info("Legacy dashboard tables ensured, owner=%s", owner)
except Exception as e:
logger.warning(f"Failed to ensure dashboard tables: {e}")
logger.warning("Failed to ensure legacy dashboard tables: %s", e)
if conn:
conn.rollback()
finally:
if cur:
cur.close()
self.return_connection(conn)
if game_db is not None:
self._migrate_old_schema(game_db)
def check_health(self):
try:
conn = self.get_connection()
if not conn:
return False
cur = conn.cursor()
cur.execute('SELECT 1')
cur.fetchone()
cur.close()
self.return_connection(conn)
return True
except Exception as e:
logger.warning("Dashboard health check FAILED: %s", e)
return False
+42 -2
View File
@@ -27,7 +27,13 @@ class DirectorService:
self.k8s = k8s_service
self.ssh = ssh_service
self.namespace = namespace
self.cm_name = f"{namespace}-bgd-conf-cm"
resource_prefix = namespace
for prefix in ['funcom-seabass-']:
if resource_prefix.startswith(prefix):
resource_prefix = resource_prefix[len(prefix):]
break
self.resource_prefix = resource_prefix
self.cm_name = f"{resource_prefix}-bgd-conf-cm"
def _request(self, path: str, method: str = 'GET', data: Any = None,
timeout: int = 15, raw_data: bool = False) -> str:
@@ -141,8 +147,9 @@ class DirectorService:
Returns:
True if the update succeeded, False otherwise.
"""
cm_out, _, cm_rc = self.k8s.run(f'get configmap {self.cm_name} -o json')
cm_out, cm_err, cm_rc = self.k8s.run(f'get configmap {self.cm_name} -o json')
if cm_rc != 0 or not cm_out:
logger.warning("update_ini_section: could not get ConfigMap %s: %s", self.cm_name, cm_err)
return False
cm = json.loads(cm_out)
@@ -165,6 +172,39 @@ class DirectorService:
cfg.write(buf)
return self.patch_configmap(buf.getvalue())
# ── ServerSetScale management ────────────────────────────────────
def _map_to_scale_name(self, map_name: str) -> str:
safe = map_name.lower().replace('_', '-')
return f"{self.resource_prefix}-{safe}"
def get_server_set_scale(self, map_name: str) -> Optional[Dict]:
name = self._map_to_scale_name(map_name)
cm_out, cm_err, cm_rc = self.k8s.run(
f'get serversetscale {name} -o json')
if cm_rc != 0 or not cm_out:
return None
return json.loads(cm_out)
def patch_server_set_scale(self, map_name: str, replicas: int,
partitions: list) -> bool:
name = self._map_to_scale_name(map_name)
patch = json.dumps({
'spec': {
'partitions': partitions,
'replicas': replicas,
}
})
patch_b64 = base64.b64encode(patch.encode()).decode()
cmd = (f'echo {patch_b64} | base64 -d | '
f'sudo kubectl patch serversetscale {name} -n {self.namespace} '
f'--type merge --patch-file /dev/stdin')
out, err, rc = self.ssh.run(cmd, timeout=15)
if rc != 0:
logger.warning("ServerSetScale patch failed for %s: %s", map_name, err)
return False
return True
# ── Helper: extract config values for INI update ─────────────────
@staticmethod
+36 -6
View File
@@ -41,8 +41,9 @@ def _build_player_filters(search='', faction_id='', guild_id='', map_filter='',
class PlayerService:
def __init__(self, db_service):
def __init__(self, db_service, dash_db=None):
self.db = db_service
self.dash_db = dash_db
def is_online(self, player_controller_id):
result = self.db.query(
@@ -131,8 +132,7 @@ class PlayerService:
ea.id as account_id, ea.user as account_email,
acc.funcom_id,
ps.player_controller_id,
f.name as faction_name, g.guild_name,
pi.ip_address
f.name as faction_name, g.guild_name
FROM dune.actors a
JOIN dune.encrypted_accounts ea ON a.owner_account_id = ea.id
LEFT JOIN dune.accounts acc ON ea.id = acc.id
@@ -141,7 +141,6 @@ class PlayerService:
LEFT JOIN dune.factions f ON pf.faction_id = f.id
LEFT JOIN dune.guild_members gm ON ps.player_controller_id = gm.player_id
LEFT JOIN dune.guilds g ON gm.guild_id = g.guild_id
LEFT JOIN dashboard.player_ips pi ON ps.player_controller_id = pi.player_id
WHERE {where_clause}
ORDER BY player_name
LIMIT %s OFFSET %s
@@ -151,6 +150,22 @@ class PlayerService:
return []
player_ids = [p.get('player_controller_id') for p in players if p.get('player_controller_id')]
# Fetch IPs from the dashboard database separately and merge
ip_map = {}
if self.dash_db and player_ids:
placeholders = ','.join(['%s'] * len(player_ids))
ip_rows = self.dash_db.query(
f"SELECT player_id, ip_address FROM player_ips WHERE player_id IN ({placeholders})",
player_ids
) or []
ip_map = {r['player_id']: r['ip_address'] for r in ip_rows if r.get('player_id')}
for p in players:
pid = p.get('player_controller_id')
if pid and pid in ip_map:
p['ip_address'] = ip_map[pid]
else:
p['ip_address'] = None
actor_ids = [p.get('id') for p in players if p.get('id')]
vehicle_counts = {}
@@ -254,9 +269,24 @@ class PlayerService:
(SELECT COUNT(*)::int FROM dune.building_instances bi WHERE bi.building_id = b.id) as instance_count
FROM dune.buildings b
JOIN dune.actors a ON b.id = a.id
WHERE b.owner_id = %s
JOIN LATERAL (
SELECT DISTINCT afe_totem.actor_id as totem_actor_id
FROM dune.building_instances bi
JOIN dune.actor_fgl_entities afe_totem ON afe_totem.entity_id = bi.owner_entity_id
WHERE bi.building_id = b.id
LIMIT 1
) totem ON true
JOIN LATERAL (
SELECT pawn.id as pawn_id
FROM dune.actors pawn
WHERE pawn.id BETWEEN totem.totem_actor_id - 6 AND totem.totem_actor_id - 1
AND pawn.class LIKE %s
ORDER BY totem.totem_actor_id - pawn.id
LIMIT 1
) owner ON true
WHERE owner.pawn_id = %s
ORDER BY a.map
""", [player_id]) or []
""", [LIKE_PC, player_id]) or []
except Exception:
return []
+210
View File
@@ -0,0 +1,210 @@
"""RMQ service - RabbitMQ Management HTTP API client."""
import json
import logging
import base64
import urllib.request
import urllib.error
from typing import Any, Dict, List, Optional
logger = logging.getLogger(__name__)
class RmqService:
"""RabbitMQ Management HTTP API client.
Communicates with RMQ Admin (port 30325) and RMQ Game (port 32716)
HTTP API endpoints via SSH tunnel (localhost).
"""
def __init__(self, admin_port: int = 30325, game_port: int = 32716,
username: str = 'dashboard_admin', password: str = ''):
self.admin_port = admin_port
self.game_port = game_port
self.username = username
self.password = password
self._auth = base64.b64encode(
f"{username}:{password}".encode()).decode()
logger.info("RmqService initialized: admin=localhost:%s game=localhost:%s",
admin_port, game_port)
def _request(self, port: int, path: str, method: str = 'GET',
body: Any = None, timeout: int = 15) -> Optional[Any]:
"""Execute an HTTP request against an RMQ API.
Args:
port: Tunnel port (30325 for admin, 32716 for game).
path: API path (e.g., '/api/overview').
method: HTTP method.
body: Optional JSON-serializable request body.
timeout: Request timeout in seconds.
Returns:
Parsed JSON response, or None on failure.
"""
url = f"http://127.0.0.1:{port}{path}"
headers = {
'Authorization': f'Basic {self._auth}',
}
if body is not None:
headers['Content-Type'] = 'application/json'
data = json.dumps(body).encode()
else:
data = None
req = urllib.request.Request(url, data=data, headers=headers)
if method != 'GET' and method != 'POST':
req.method = method
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
raw = resp.read().decode()
return json.loads(raw) if raw.strip() else {}
except urllib.error.HTTPError as e:
logger.warning("RMQ HTTP %s %s -> %s: %s", method, url, e.code,
e.read().decode()[:200] if e.fp else '')
return None
except Exception as e:
logger.warning("RMQ request error %s %s: %s", method, url, e)
return None
@staticmethod
def _encode_vhost(vhost: str = '/') -> str:
return vhost.replace('/', '%2F')
# ── Admin API (port 30325) ───────────────────────────────────────
def overview(self) -> Optional[Dict]:
"""Cluster overview: node info, message stats, queue totals."""
return self._request(self.admin_port, '/api/overview')
def nodes(self) -> Optional[List]:
"""List nodes with memory and disk info."""
return self._request(self.admin_port, '/api/nodes')
def exchanges(self) -> Optional[List]:
"""List all exchanges with message stats."""
return self._request(self.admin_port, '/api/exchanges')
def queues(self) -> Optional[List]:
"""List all queues with consumer counts and message depths."""
return self._request(self.admin_port, '/api/queues')
def bindings(self) -> Optional[List]:
"""List all bindings (source -> destination mappings)."""
return self._request(self.admin_port, '/api/bindings')
def consumers(self) -> Optional[List]:
"""List active consumers."""
return self._request(self.admin_port, '/api/consumers')
def connections(self) -> Optional[List]:
"""List active AMQP connections."""
return self._request(self.admin_port, '/api/connections')
def channels(self) -> Optional[List]:
"""List active channels."""
return self._request(self.admin_port, '/api/channels')
def health(self) -> Optional[Dict]:
"""Cluster health and alarm status."""
return self._request(self.admin_port,
'/api/health/checks/alarms')
def peek_messages(self, queue_name: str, vhost: str = '/',
count: int = 5) -> Optional[List]:
"""Peek at messages in a queue without consuming them."""
vh = self._encode_vhost(vhost)
body = {
'count': count,
'ackmode': 'ack_requeue_true',
'encoding': 'auto',
}
return self._request(self.admin_port,
f'/api/queues/{vh}/{queue_name}/get',
method='POST', body=body)
def publish(self, exchange: str, routing_key: str, message: Any,
vhost: str = '/') -> Optional[Dict]:
"""Publish a message to an exchange.
NOTE: RMQ HTTP API sets user_id to the authenticated username,
which the game server may reject. For ServerCommands on the
game RPC exchange, use the Erlang eval approach instead.
"""
vh = self._encode_vhost(vhost)
body = {
'properties': {},
'routing_key': routing_key,
'payload': json.dumps(message) if not isinstance(message, str)
else message,
'payload_encoding': 'string',
}
return self._request(self.admin_port,
f'/api/exchanges/{vh}/{exchange}/publish',
method='POST', body=body)
def get_queue_bindings(self, queue_name: str,
vhost: str = '/') -> Optional[List]:
vh = self._encode_vhost(vhost)
return self._request(self.admin_port,
f'/api/queues/{vh}/{queue_name}/bindings')
def get_exchange_bindings(self, exchange: str,
vhost: str = '/') -> Optional[List]:
vh = self._encode_vhost(vhost)
return self._request(self.admin_port,
f'/api/exchanges/{vh}/{exchange}/bindings/source')
# ── Game API (port 32716) ────────────────────────────────────────
def game_overview(self) -> Optional[Dict]:
"""Game RMQ cluster overview."""
return self._request(self.game_port, '/api/overview')
def game_queues(self) -> Optional[List]:
"""Game RMQ queues."""
return self._request(self.game_port, '/api/queues')
def game_exchanges(self) -> Optional[List]:
"""Game RMQ exchanges."""
return self._request(self.game_port, '/api/exchanges')
def game_publish(self, exchange: str, routing_key: str,
message: Any, vhost: str = '/') -> Optional[Dict]:
"""Publish a message to the game RMQ."""
vh = self._encode_vhost(vhost)
body = {
'properties': {},
'routing_key': routing_key,
'payload': json.dumps(message) if not isinstance(message, str)
else message,
'payload_encoding': 'string',
}
return self._request(self.game_port,
f'/api/exchanges/{vh}/{exchange}/publish',
method='POST', body=body)
# ── Combined / convenience ───────────────────────────────────────
def combined_overview(self) -> Dict[str, Any]:
"""Get overview from both RMQ instances."""
return {
'admin': self.overview(),
'game': self.game_overview(),
}
def combined_queues(self) -> Dict[str, Any]:
"""Get queues from both RMQ instances."""
return {
'admin': self.queues(),
'game': self.game_queues(),
}
def combined_exchanges(self) -> Dict[str, Any]:
"""Get exchanges from both RMQ instances."""
return {
'admin': self.exchanges(),
'game': self.game_exchanges(),
}
+1 -1
View File
@@ -81,5 +81,5 @@ NAV_PAGES = [
('/guilds', 'Guilds'),
('/buildings', 'Buildings'),
('/map', 'Map'),
('/admin-experimental', 'Admin Experimental'),
('/admin-experimental', 'Experimental'),
]
+6 -1
View File
@@ -108,7 +108,12 @@ def generate_cert(cert_path, key_path, ca_cert_path=None, ca_key_path=None,
])
# Build SAN entries
san_entries = [x509.DNSName(common_name)]
san_entries = []
# Add common_name as the appropriate SAN type
try:
san_entries.append(x509.IPAddress(ipaddress.ip_address(common_name)))
except ValueError:
san_entries.append(x509.DNSName(common_name))
if san_ips:
for ip in san_ips:
try:
-1
View File
@@ -1 +0,0 @@
# Backend package init.
-286
View File
@@ -1,286 +0,0 @@
"""Settings loader — reads settings.yaml with env var overrides."""
import os
import socket
import yaml
import logging
import copy
import secrets
logger = logging.getLogger(__name__)
DEFAULTS = {
"server": {
"host": "127.0.0.1",
"user": "dune",
"ssh_key": None,
"local_ip": None,
},
"dashboard": {
"host": "127.0.0.1",
"port": 5050,
"debug": False,
"secret_key": None,
"ssl_cert": None,
"ssl_key": None,
"ssl_domain": None,
"ssl_email": None,
"http_redirect": False,
"http_redirect_port": 80,
},
"database": {
"host": "127.0.0.1",
"port": 15433,
"user": "postgres",
"password": None,
"name": "dune",
"schema": "dune",
"min_connections": 2,
"max_connections": 10,
"owner": "dune",
"dashboard_schema": "dashboard",
},
"kubernetes": {
"namespace": "",
"battlegroup_script": "/home/dune/.dune/bin/battlegroup",
},
"director": {
"port": 32479,
"host": "127.0.0.1",
},
"rmq": {
"admin_host": "127.0.0.1",
"admin_port": 32686,
"game_host": "127.0.0.1",
"game_port": 32021,
"username": "admin",
"password": None,
"vhost": "%2f",
},
"filebrowser": {
"port": 18888,
},
"firewall": {
"block_filebrowser": True,
"block_director": True,
},
"cache": {
"chat_pod_ttl": 60,
"chat_messages_ttl": 10,
"static_data_ttl": 300,
"bgd_ttl": 10,
"rmq_ttl": 15,
},
"auth": {
"enabled": True,
"username": None,
"password_hash": None,
"shell_enabled": True,
},
"logging": {
"level": "INFO",
"file": "logs/dashboard.log",
"debug_file": "logs/debug.log",
"debug_enabled": False,
"max_bytes": 10485760,
"backup_count": 5,
},
"ssl": {
"check_interval_hours": 24,
"renewal_days_before_expiry": 30,
},
"maps": {
"default_map": "HaggaBasin",
"DeepDesert": {
"image": "maps/Deep_Desert.webp",
"label": "The Deep Desert",
"bounds": {
"min_x": -1268624.82,
"max_x": 1163312.83,
"min_y": -1266548.17,
"max_y": 1162416.13,
},
"flip_y": False,
"image_size": {"width": 8000, "height": 8000},
"default_zoom": 0.15,
},
"HaggaBasin": {
"image": "maps/HaggaBasin_8k.webp",
"label": "Hagga Basin",
"bounds": {
"min_x": -456752.21,
"max_x": 354547.46,
"min_y": -450630.14,
"max_y": 353821.95,
},
"flip_y": False,
"image_size": {"width": 8000, "height": 8000},
"default_zoom": 0.15,
},
},
}
def deep_merge(base, override):
"""Deep merge override dict into base dict."""
result = base.copy()
for key, value in override.items():
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
result[key] = deep_merge(result[key], value)
else:
result[key] = value
return result
def _detect_local_ip():
"""Detect local IP address for VM connectivity."""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(1)
s.connect(("8.8.8.8", 80))
local_ip = s.getsockname()[0]
s.close()
if local_ip:
logger.debug(f"Detected local IP: {local_ip}")
return local_ip
except Exception as e:
logger.debug(f"Could not detect local IP: {e}")
return "127.0.0.1"
def _validate_server_host(settings):
"""Validate and fix server.host if invalid or placeholder."""
server = settings.setdefault("server", {})
host = server.get("host", "")
local_ip = server.get("local_ip")
if local_ip:
local_ip_str = str(local_ip).strip()
if local_ip_str and local_ip_str not in ("", "null", "None", "YOUR_SERVER_IP", "YOUR_VM_IP"):
if local_ip_str.count(".") == 3 and all(part.isdigit() and 0 <= int(part) <= 255 for part in local_ip_str.split(".")):
server["host"] = local_ip_str
logger.info(f"Using server.local_ip override: {server['host']}")
return settings
host_str = str(host).strip() if host else ""
invalid_hosts = ("", "YOUR_SERVER_IP", "YOUR_VM_IP", "null", "None")
if host_str in invalid_hosts or not host_str:
detected_ip = _detect_local_ip()
server["host"] = detected_ip
logger.warning(f"Invalid server.host detected, using auto-detected IP: {detected_ip}")
logger.warning("To fix: Edit settings.yaml and set server.host to your VM's IP address")
return settings
def _find_missing_keys(defaults, current, path=""):
"""Find keys present in defaults but missing in current."""
missing = []
for key, val in defaults.items():
new_path = f"{path}.{key}" if path else key
if key not in current:
missing.append(new_path)
elif isinstance(val, dict) and isinstance(current.get(key), dict):
missing.extend(_find_missing_keys(val, current[key], new_path))
return missing
def load_settings(settings_path=None):
"""Load settings from YAML file with defaults and env var overrides."""
if settings_path is None:
settings_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "settings.yaml")
settings = copy.deepcopy(DEFAULTS)
if os.path.exists(settings_path):
try:
with open(settings_path, "r") as f:
file_settings = yaml.safe_load(f) or {}
settings = deep_merge(settings, file_settings)
logger.info(f"Settings loaded from {settings_path}")
except Exception as e:
logger.error(f"Failed to load settings from {settings_path}: {e}")
logger.warning("Using default settings")
else:
logger.warning(f"Settings file not found at {settings_path}, using defaults")
env_overrides = {}
if os.environ.get("DUNE_SERVER_HOST"):
env_overrides.setdefault("server", {})["host"] = os.environ["DUNE_SERVER_HOST"]
if os.environ.get("DUNE_SERVER_USER"):
env_overrides.setdefault("server", {})["user"] = os.environ["DUNE_SERVER_USER"]
if os.environ.get("DUNE_DB_PASSWORD"):
env_overrides.setdefault("database", {})["password"] = os.environ["DUNE_DB_PASSWORD"]
if os.environ.get("DUNE_K8S_NAMESPACE"):
env_overrides.setdefault("kubernetes", {})["namespace"] = os.environ["DUNE_K8S_NAMESPACE"]
if os.environ.get("DUNE_AUTH_PASSWORD"):
env_overrides.setdefault("auth", {})["password"] = os.environ["DUNE_AUTH_PASSWORD"]
if os.environ.get("DUNE_DASHBOARD_PORT"):
env_overrides.setdefault("dashboard", {})["port"] = int(os.environ["DUNE_DASHBOARD_PORT"])
if os.environ.get("DUNE_RMQ_PASSWORD"):
env_overrides.setdefault("rmq", {})["password"] = os.environ["DUNE_RMQ_PASSWORD"]
if env_overrides:
settings = deep_merge(settings, env_overrides)
logger.info("Environment variable overrides applied")
if not settings["dashboard"].get("secret_key"):
settings["dashboard"]["secret_key"] = secrets.token_hex(32)
logger.info("Generated secure SECRET_KEY")
auth = settings.get("auth", {})
password_migrated = False
if auth.get("password") and not auth.get("password_hash"):
try:
from argon2 import PasswordHasher
ph = PasswordHasher(time_cost=3, memory_cost=65536)
settings["auth"]["password_hash"] = ph.hash(str(auth["password"]))
del settings["auth"]["password"]
password_migrated = True
logger.info("Migrated plaintext password to Argon2 hash")
except ImportError:
logger.error("argon2-cffi not installed. Password hashing unavailable.")
settings["auth"]["password_hash"] = None
if password_migrated:
settings["dashboard"]["secret_key"] = secrets.token_hex(32)
logger.warning("Rotated secret_key to invalidate sessions after password migration")
settings = _validate_server_host(settings)
return settings
_settings_cache = None
def get_settings():
"""Get current settings (cached for performance)."""
global _settings_cache
if _settings_cache is None:
_settings_cache = load_settings()
return _settings_cache
def save_settings(settings):
"""Save settings to YAML file."""
global _settings_cache
settings_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "settings.yaml")
try:
with open(settings_path, "w") as f:
yaml.safe_dump(settings, f, default_flow_style=False, sort_keys=False)
_settings_cache = settings
logger.info(f"Settings saved to {settings_path}")
return True
except Exception as e:
logger.error(f"Failed to save settings to {settings_path}: {e}")
return False
def reload_settings():
"""Force reload settings from file."""
global _settings_cache
_settings_cache = load_settings()
return _settings_cache
-313
View File
@@ -1,313 +0,0 @@
# Application factory — creates and configures the Flask app.
import os
import sys
import logging
import logging.handlers
from datetime import datetime
from flask import Flask, jsonify, request, g, send_from_directory
from flask_cors import CORS
from flask_login import current_user
from flask_socketio import SocketIO
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from app.config import load_settings
from app.routes.auth import auth_bp, init_auth
from app.routes.health import health_bp
from app.routes.api import api_bp
from app.routes.director import director_bp
from app.routes.server import server_bp
from app.routes.files import files_bp
from app.routes.debug import debug_bp
from app.routes.chat import chat_bp
from app.websocket.shell import register_websocket_handlers
from app.services.database import DatabaseService
from app.services.ssh import SSHService
from app.services.k8s import K8sService
from app.services.bg_director import BgDirectorService
from app.services.rmq_admin import RmqAdminService
from app.services.rmq_game import RmqGameService
from app.services.realtime import RealtimeService
from app.services.player import PlayerService
from app.services.economy import EconomyService
from app.services.guild import GuildService
from app.services.world import WorldService
from app.services.progression import ProgressionService
from app.services.character import CharacterService
from app.services.audit import AuditService
from app.services.chat import ChatService
_services = None
def get_services():
global _services
return _services
def create_app(settings_path=None):
global _services
settings = load_settings(settings_path)
base_dir = os.path.dirname(os.path.dirname(__file__))
app = Flask(
__name__,
template_folder=os.path.join(base_dir, "frontend", "dist"),
static_folder=os.path.join(base_dir, "frontend", "dist", "assets"),
static_url_path="/assets",
)
app.config["SECRET_KEY"] = settings["dashboard"]["secret_key"]
app.config["SESSION_COOKIE_HTTPONLY"] = True
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
app.config["WTF_CSRF_ENABLED"] = True
app.config["WTF_CSRF_TIME_LIMIT"] = None
CORS(app, resources={r"/api/*": {"origins": "*"}})
ssl_enabled = bool(
settings["dashboard"].get("ssl_cert")
and settings["dashboard"].get("ssl_key")
and settings["dashboard"]["ssl_cert"] != "null"
and settings["dashboard"]["ssl_key"] != "null"
)
app.config["SESSION_COOKIE_SECURE"] = ssl_enabled
if not settings["dashboard"]["debug"]:
@app.after_request
def add_security_headers(response):
if ssl_enabled:
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
response.headers["X-Frame-Options"] = "SAMEORIGIN"
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-XSS-Protection"] = "1; mode=block"
response.headers["Content-Security-Policy"] = (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline'; "
"style-src 'self' 'unsafe-inline'; "
"img-src 'self' data:; "
"connect-src 'self' ws: wss:; "
"frame-ancestors 'self'; "
"base-uri 'self'; "
"form-action 'self'"
)
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
return response
# Error handlers
@app.errorhandler(Exception)
def handle_exception(e):
logging.exception("Unhandled exception: %s", e)
from app.models import ApiResponse, ErrorDetail
if settings["dashboard"].get("debug", False):
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="InternalError", message=str(e)),
).model_dump()), 500
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="InternalError", message="An internal error occurred"),
).model_dump()), 500
@app.errorhandler(404)
def handle_not_found(e):
from app.models import ApiResponse, ErrorDetail
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="NotFound", message="Resource not found"),
).model_dump()), 404
@app.errorhandler(405)
def handle_method_not_allowed(e):
from app.models import ApiResponse, ErrorDetail
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="MethodNotAllowed", message="Method not allowed"),
).model_dump()), 405
# Request logging
@app.before_request
def before_request_logging():
import time as _time
g._request_start_time = _time.time()
@app.after_request
def after_request_logging(response):
import time as _time
duration = _time.time() - g.get("_request_start_time", _time.time())
user = current_user.id if current_user.is_authenticated else "anonymous"
if request.path.startswith("/api") or request.path.startswith("/server"):
logging.info("%s %s %d %.3fs user=%s", request.method, request.path, response.status_code, duration, user)
response.headers["X-Response-Time"] = f"{duration:.3f}s"
return response
_setup_logging(settings)
# ── Services ─────────────────────────────────────────────────
db_config = {
"host": settings["database"]["host"],
"port": settings["database"]["port"],
"user": settings["database"]["user"],
"password": settings["database"]["password"],
"database": settings["database"]["name"],
}
db_service = DatabaseService(
db_config,
min_conn=settings["database"]["min_connections"],
max_conn=settings["database"]["max_connections"],
dashboard_schema=settings["database"].get("dashboard_schema", "dashboard"),
)
db_service.ensure_tables()
ssh_service = SSHService(
host=settings["server"]["host"],
user=settings["server"]["user"],
ssh_key=settings["server"].get("ssh_key"),
)
k8s_service = K8sService(
ssh_service=ssh_service,
namespace=settings["kubernetes"]["namespace"],
)
bg_director = BgDirectorService(
host=settings["director"].get("host", "127.0.0.1"),
node_port=settings["director"].get("port", 32479),
)
rmq_admin = RmqAdminService(
host=settings["rmq"]["admin_host"],
port=settings["rmq"]["admin_port"],
username=settings["rmq"]["username"],
password=settings["rmq"]["password"],
)
rmq_game = RmqGameService(
host=settings["rmq"]["game_host"],
port=settings["rmq"]["game_port"],
username=settings["rmq"]["username"],
password=settings["rmq"]["password"],
)
player_svc = PlayerService(db_service)
economy_svc = EconomyService(db_service)
guild_svc = GuildService(db_service)
world_svc = WorldService(db_service)
progression_svc = ProgressionService(db_service)
character_svc = CharacterService(db_service)
audit_svc = AuditService(db_service)
chat_svc = ChatService(db_service, k8s_service, ssh_service)
realtime_svc = RealtimeService(bg_director, rmq_admin, chat_svc)
realtime_svc.start()
_services = {
"db": db_service,
"ssh": ssh_service,
"k8s": k8s_service,
"bg_director": bg_director,
"rmq_admin": rmq_admin,
"rmq_game": rmq_game,
"realtime": realtime_svc,
"player": player_svc,
"economy": economy_svc,
"guild": guild_svc,
"world": world_svc,
"progression": progression_svc,
"character": character_svc,
"audit": audit_svc,
"chat": chat_svc,
}
app.dune_settings = settings
app.dune_services = _services
# ── Blueprints ───────────────────────────────────────────────
init_auth(app, settings)
# Auto-login for development — bypasses authentication on all endpoints
from flask_login import login_user
from app.routes.auth import AdminUser
@app.before_request
def auto_login_dev():
if not current_user.is_authenticated:
cfg_user = str(settings.get("auth", {}).get("username", "admin"))
login_user(AdminUser(cfg_user))
app.register_blueprint(auth_bp, url_prefix="/api/auth")
app.register_blueprint(health_bp, url_prefix="/api")
app.register_blueprint(api_bp, url_prefix="/api")
app.register_blueprint(director_bp, url_prefix="/api/director")
app.register_blueprint(server_bp, url_prefix="/api/server")
app.register_blueprint(files_bp, url_prefix="/api/files")
app.register_blueprint(chat_bp, url_prefix="/api/chat")
app.register_blueprint(debug_bp, url_prefix="/api/debug")
# ── SocketIO ─────────────────────────────────────────────────
socketio = SocketIO(app, cors_allowed_origins="*", async_mode="threading")
register_websocket_handlers(socketio, settings)
app.socketio = socketio
# ── Rate Limiter ─────────────────────────────────────────────
limiter = Limiter(
app=app,
key_func=get_remote_address,
default_limits=[],
storage_uri="memory://",
)
app.limiter = limiter
# ── Catch-all for React SPA ─────────────────────────────────
@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
def serve_react(path):
if path.startswith("api/") or path.startswith("server/") or path.startswith("static/") or path.startswith("assets/"):
from app.models import ApiResponse, ErrorDetail
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="NotFound", message="Resource not found"),
).model_dump()), 404
return send_from_directory(os.path.join(base_dir, "frontend", "dist"), "index.html")
# ── Auto-detect namespace if empty ───────────────────────────
if settings["kubernetes"]["namespace"] == "":
try:
k8s_service.auto_detect_namespace()
if k8s_service.namespace:
settings["kubernetes"]["namespace"] = k8s_service.namespace
except Exception as e:
logging.warning("Could not auto-detect K8s namespace: %s", e)
return app
def _setup_logging(settings):
log_level = getattr(logging, settings["logging"]["level"].upper(), logging.INFO)
log_file = settings["logging"]["file"]
os.makedirs(os.path.dirname(log_file), exist_ok=True)
handler = logging.handlers.RotatingFileHandler(
log_file,
maxBytes=settings["logging"]["max_bytes"],
backupCount=settings["logging"]["backup_count"],
)
handler.setFormatter(logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
))
handler.setLevel(log_level)
console = logging.StreamHandler(sys.stdout)
console.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
console.setLevel(log_level)
root = logging.getLogger()
root.setLevel(log_level)
root.addHandler(handler)
root.addHandler(console)
-232
View File
@@ -1,232 +0,0 @@
# Pydantic models for the Dune Admin Dashboard API.
from pydantic import BaseModel, Field
from typing import Any, List, Optional
class ErrorDetail(BaseModel):
code: str
message: str
details: Optional[Any] = None
class ApiResponse(BaseModel):
success: bool
data: Optional[Any] = None
error: Optional[ErrorDetail] = None
# ── Player Models ───────────────────────────────────────────────
class Vitals(BaseModel):
current_health: Optional[float] = None
max_health: Optional[float] = None
current_hydration: Optional[float] = None
dehydration_penalty: Optional[float] = None
current_spice: Optional[float] = None
spice_addiction_level: Optional[float] = None
spice_tolerance: Optional[float] = None
class CurrencyBalance(BaseModel):
currency_id: int
currency_label: str
balance: float = 0.0
class Item(BaseModel):
id: Optional[int] = None
template_id: str = ""
stack_size: int = 1
quality_level: int = 0
is_new: bool = False
position_index: int = 0
stats: Optional[Any] = None
durability: Optional[float] = None
max_durability: Optional[float] = None
ammo: Optional[int] = None
class Inventory(BaseModel):
inventory_id: int
actor_id: Optional[int] = None
inventory_type: int = 0
inventory_type_label: str = ""
max_item_count: Optional[int] = None
max_item_volume: Optional[float] = None
items: List[Item] = []
class VehicleSummary(BaseModel):
id: Optional[int] = None
class_name: str = ""
display_name: str = ""
map: Optional[str] = None
class BuildingSummary(BaseModel):
id: Optional[int] = None
class_name: str = ""
map: Optional[str] = None
owner_name: str = ""
instance_count: int = 0
is_powered: bool = False
power_level: Optional[Any] = None
class Landclaim(BaseModel):
id: Optional[int] = None
class_name: str = ""
map: Optional[str] = None
class SpecializationTrack(BaseModel):
track_type: str = ""
xp_amount: int = 0
level: int = 0
class Keystone(BaseModel):
id: int
name: str = ""
class FactionReputation(BaseModel):
faction_id: Optional[int] = None
faction_name: str = ""
reputation_amount: int = 0
class LandsraadInfo(BaseModel):
daily_reward_charges: Optional[int] = None
last_viewed_term_id: Optional[int] = None
daily_reward_last_processed: Optional[Any] = None
class PlayerSummary(BaseModel):
player_controller_id: Optional[int] = None
character_name: str = "Unknown"
account_email: Optional[str] = None
funcom_id: Optional[str] = None
faction_name: Optional[str] = None
faction_id: Optional[int] = None
map: Optional[str] = None
online_status: str = "Unknown"
life_state: Optional[str] = None
last_login_time: Optional[str] = None
last_avatar_activity: Optional[str] = None
class PlayerDetail(BaseModel):
id: Optional[int] = None
account_id: int
player_controller_id: Optional[int] = None
player_pawn_id: Optional[int] = None
character_name: str = "Unknown"
account_email: Optional[str] = None
funcom_id: Optional[str] = None
faction_name: Optional[str] = None
faction_id: Optional[int] = None
map: Optional[str] = None
online_status: str = "Unknown"
life_state: Optional[str] = None
last_login_time: Optional[str] = None
last_avatar_activity: Optional[str] = None
vitals: Optional[Vitals] = None
currency: List[CurrencyBalance] = []
inventories: List[Inventory] = []
vehicles: List[VehicleSummary] = []
buildings: List[BuildingSummary] = []
landclaims: List[Landclaim] = []
specialization: List[SpecializationTrack] = []
keystones: List[Keystone] = []
faction_reputation: List[FactionReputation] = []
landsraad: Optional[LandsraadInfo] = None
tags: List[str] = []
is_online: bool = False
# ── Guild Models ────────────────────────────────────────────────
class GuildMember(BaseModel):
player_id: int
role_id: int = 50
role_name: str = "Member"
player_name: str = "Unknown"
online_status: str = "Unknown"
class GuildSummary(BaseModel):
guild_id: int
guild_name: str = ""
guild_description: Optional[str] = None
faction_name: Optional[str] = None
member_count: int = 0
online_count: int = 0
class GuildDetail(BaseModel):
guild_id: int
guild_name: str = ""
guild_description: Optional[str] = None
faction_name: Optional[str] = None
faction_id: Optional[int] = None
members: List[GuildMember] = []
# ── World Models ───────────────────────────────────────────────
class PartitionInfo(BaseModel):
partition_id: int
name: str = ""
map: Optional[str] = None
player_count: int = 0
status: str = "unknown"
# ── RMQ Models ────────────────────────────────────────────────
class RmqQueueInfo(BaseModel):
name: str
messages: int = 0
consumers: int = 0
state: str = ""
class RmqOverview(BaseModel):
queues: List[RmqQueueInfo] = []
total_messages: int = 0
total_consumers: int = 0
# ── BGD Models ────────────────────────────────────────────────
class BattlegroupState(BaseModel):
battlegroup_id: Optional[int] = None
name: Optional[str] = None
status: Optional[str] = None
player_count: Optional[int] = None
servers: Optional[List[Any]] = None
# ── Request Models ─────────────────────────────────────────────
class BroadcastRequest(BaseModel):
message: str = Field(..., min_length=1, max_length=500)
server: Optional[str] = None
partition: Optional[str] = None
class TeleportRequest(BaseModel):
player_id: int
destination: str = Field(..., min_length=1)
class FunctionExecuteRequest(BaseModel):
schema_name: Optional[str] = Field(default=None, alias="schema")
function: str = Field(..., min_length=1)
args: dict = {}
class RawQueryRequest(BaseModel):
query: str = Field(..., min_length=1)
-1
View File
@@ -1 +0,0 @@
# Routes package init.
-971
View File
@@ -1,971 +0,0 @@
# Main API routes — players, guilds, economy, world, progression, character, admin.
import logging
from flask import Blueprint, request, jsonify
from flask_login import login_required, current_user
from pydantic import ValidationError
from app.models import (
ApiResponse, ErrorDetail, PlayerDetail, BroadcastRequest,
TeleportRequest, FunctionExecuteRequest, RawQueryRequest,
)
api_bp = Blueprint("api", __name__)
logger = logging.getLogger(__name__)
def _audit(action: str, details: dict | None = None, target_player_id: int | None = None, severity: str = "info"):
from app.factory import get_services
services = get_services()
audit = services.get("audit")
if audit:
audit.log(
action=action,
user=current_user.id if current_user.is_authenticated else "anonymous",
details=details,
target_player_id=target_player_id,
severity=severity,
source_ip=request.remote_addr,
)
@api_bp.errorhandler(ValidationError)
def handle_validation_error(e):
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message=str(e)),
).model_dump()), 400
# ── Player Endpoints ──────────────────────────────────────────────
@api_bp.route("/players", methods=["GET"])
@login_required
def list_players():
term = request.args.get("q", "")
limit = int(request.args.get("limit", 50))
from app.factory import get_services
svc = get_services()["player"]
results = svc.search(term, limit=limit)
return jsonify(ApiResponse(success=True, data=results).model_dump())
@api_bp.route("/players/search", methods=["POST"])
@login_required
def search_players():
data = request.get_json() or {}
term = data.get("term", "")
from app.factory import get_services
svc = get_services()["player"]
results = svc.search(term)
return jsonify(ApiResponse(success=True, data=results).model_dump())
@api_bp.route("/players/<int:account_id>", methods=["GET"])
@login_required
def get_player(account_id):
from app.factory import get_services
svc = get_services()["player"]
detail = svc.get_detail(account_id)
if not detail:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="NotFound", message="Player not found"),
).model_dump()), 404
return jsonify(ApiResponse(success=True, data=detail).model_dump())
@api_bp.route("/players/<int:account_id>/inventory", methods=["GET"])
@login_required
def get_player_inventory(account_id):
from app.factory import get_services
svc = get_services()["economy"]
inventories = svc.get_inventory(account_id)
return jsonify(ApiResponse(success=True, data=inventories).model_dump())
@api_bp.route("/players/<int:account_id>/currency", methods=["GET"])
@login_required
def get_player_currency(account_id):
from app.factory import get_services
player_svc = get_services()["player"]
detail = player_svc.get_detail(account_id)
pid = detail.get("player_controller_id") if detail else None
if not pid:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="NotFound", message="Player controller not found"),
).model_dump()), 404
econ = get_services()["economy"]
currency = econ.get_currency(pid)
return jsonify(ApiResponse(success=True, data=currency).model_dump())
@api_bp.route("/players/<int:account_id>/vitals", methods=["GET"])
@login_required
def get_player_vitals(account_id):
from app.factory import get_services
player_svc = get_services()["player"]
detail = player_svc.get_detail(account_id)
pawn_id = detail.get("player_pawn_id") if detail else None
if not pawn_id:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="NotFound", message="Player pawn not found"),
).model_dump()), 404
econ = get_services()["economy"]
vitals = econ.get_vitals(pawn_id)
return jsonify(ApiResponse(success=True, data=vitals).model_dump())
# ── Economy Mutations ────────────────────────────────────────────
@api_bp.route("/items/add", methods=["POST"])
@login_required
def add_item():
data = request.get_json() or {}
inventory_id = data.get("inventory_id")
template_id = data.get("template_id")
stack_size = data.get("stack_size", 1)
quality_level = data.get("quality_level", 0)
if not inventory_id or not template_id:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing inventory_id or template_id"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["economy"]
item_id = svc.add_item(inventory_id, template_id, stack_size, quality_level)
_audit("item_add", {"inventory_id": inventory_id, "template_id": template_id, "item_id": item_id})
return jsonify(ApiResponse(success=True, data={"item_id": item_id}).model_dump())
@api_bp.route("/items/<int:item_id>", methods=["DELETE"])
@login_required
def delete_item(item_id):
from app.factory import get_services
svc = get_services()["economy"]
svc.delete_item(item_id)
_audit("item_delete", {"item_id": item_id})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/items/<int:item_id>", methods=["PATCH"])
@login_required
def edit_item(item_id):
data = request.get_json() or {}
field = data.get("field")
value = data.get("value")
if not field or value is None:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing field or value"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["economy"]
svc.edit_item_field(item_id, field, value)
_audit("item_edit", {"item_id": item_id, "field": field, "value": value})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/currency/adjust", methods=["POST"])
@login_required
def adjust_currency():
data = request.get_json() or {}
controller_id = data.get("controller_id")
currency_id = data.get("currency_id")
delta = data.get("delta")
if controller_id is None or currency_id is None or delta is None:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing required parameters"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["economy"]
new_balance = svc.adjust_currency(controller_id, currency_id, delta)
_audit("currency_adjust", {"controller_id": controller_id, "currency_id": currency_id, "delta": delta, "new_balance": new_balance}, target_player_id=controller_id)
return jsonify(ApiResponse(success=True, data={"new_balance": new_balance}).model_dump())
@api_bp.route("/currency/set", methods=["POST"])
@login_required
def set_currency():
data = request.get_json() or {}
controller_id = data.get("controller_id")
currency_id = data.get("currency_id")
balance = data.get("balance")
if controller_id is None or currency_id is None or balance is None:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing required parameters"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["economy"]
svc.set_currency(controller_id, currency_id, balance)
_audit("currency_set", {"controller_id": controller_id, "currency_id": currency_id, "balance": balance}, target_player_id=controller_id)
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/vitals/set", methods=["POST"])
@login_required
def set_vitals():
data = request.get_json() or {}
pawn_id = data.get("pawn_id")
health = data.get("health")
max_health = data.get("max_health")
hydration = data.get("hydration")
spice = data.get("spice")
if pawn_id is None or hydration is None or spice is None:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing required parameters"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["economy"]
svc.set_vitals(pawn_id, health, max_health, hydration, spice)
_audit("vitals_edit", {"pawn_id": pawn_id, "health": health, "max_health": max_health, "hydration": hydration, "spice": spice})
return jsonify(ApiResponse(success=True).model_dump())
# ── Guild Endpoints ──────────────────────────────────────────────
@api_bp.route("/guilds", methods=["GET"])
@login_required
def list_guilds():
term = request.args.get("q", "")
limit = int(request.args.get("limit", 50))
from app.factory import get_services
svc = get_services()["guild"]
guilds = svc.list_all()
if term:
guilds = [g for g in guilds if term.lower() in g.guild_name.lower()]
return jsonify(ApiResponse(success=True, data=guilds[:limit]).model_dump())
@api_bp.route("/guilds/<int:guild_id>", methods=["GET"])
@login_required
def get_guild(guild_id):
from app.factory import get_services
svc = get_services()["guild"]
guild = svc.get_detail(guild_id)
if not guild:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="NotFound", message="Guild not found"),
).model_dump()), 404
return jsonify(ApiResponse(success=True, data=guild).model_dump())
@api_bp.route("/guilds/<int:guild_id>", methods=["DELETE"])
@login_required
def disband_guild(guild_id):
from app.factory import get_services
svc = get_services()["guild"]
svc.disband(guild_id)
_audit("guild_disband", {"guild_id": guild_id})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/guilds/<int:guild_id>/members/<int:player_id>", methods=["DELETE"])
@login_required
def remove_guild_member(guild_id, player_id):
from app.factory import get_services
svc = get_services()["guild"]
svc.remove_member(guild_id, player_id)
_audit("guild_kick", {"guild_id": guild_id, "player_id": player_id})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/guilds/<int:guild_id>/members/<int:player_id>/role", methods=["PUT"])
@login_required
def set_guild_role(guild_id, player_id):
data = request.get_json() or {}
role_id = data.get("role_id")
action = data.get("action", "promote")
if role_id is None:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing role_id"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["guild"]
if action == "promote":
svc.promote(guild_id, player_id, role_id)
else:
svc.demote(guild_id, player_id, role_id)
_audit(f"guild_{action}", {"guild_id": guild_id, "player_id": player_id, "role_id": role_id})
return jsonify(ApiResponse(success=True).model_dump())
# ── World Endpoints ──────────────────────────────────────────────
@api_bp.route("/partitions", methods=["GET"])
@login_required
def list_partitions():
map_name = request.args.get("map", "")
from app.factory import get_services
svc = get_services()["world"]
partitions = svc.get_partitions(map_name)
return jsonify(ApiResponse(success=True, data=partitions).model_dump())
@api_bp.route("/teleport", methods=["POST"])
@login_required
def teleport():
data = request.get_json() or {}
try:
req = TeleportRequest(**data)
except ValidationError as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message=str(e)),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["world"]
svc.teleport(req.fls_id, req.partition_id, req.x, req.y, req.z)
_audit("player_teleport", {"fls_id": req.fls_id, "partition_id": req.partition_id, "coords": [req.x, req.y, req.z]})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/spice/reset", methods=["POST"])
@login_required
def reset_spice():
data = request.get_json() or {}
map_name = data.get("map_name")
dimension_index = data.get("dimension_index", 0)
if not map_name:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing map_name"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["world"]
svc.reset_spice(map_name, dimension_index)
_audit("spice_reset", {"map": map_name, "dimension": dimension_index})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/spice/spawn", methods=["POST"])
@login_required
def force_spice_spawn():
data = request.get_json() or {}
server_id = data.get("server_id")
spicefield_type_id = data.get("spicefield_type_id")
if not server_id or spicefield_type_id is None:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing required parameters"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["world"]
svc.force_spice_spawn(server_id, spicefield_type_id)
_audit("spice_spawn", {"server_id": server_id, "spicefield_type_id": spicefield_type_id})
return jsonify(ApiResponse(success=True).model_dump())
# ── Progression Endpoints ────────────────────────────────────────
@api_bp.route("/progression/journey", methods=["POST"])
@login_required
def journey_action():
data = request.get_json() or {}
player_id = data.get("player_id")
node_ids = data.get("node_ids", [])
action = data.get("action", "complete")
if not player_id or not node_ids:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing player_id or node_ids"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["progression"]
if action == "complete":
svc.complete_nodes(player_id, node_ids)
elif action == "reveal":
svc.reveal_nodes(player_id, node_ids)
elif action == "reset":
svc.reset_nodes(player_id, node_ids)
else:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Invalid action"),
).model_dump()), 400
_audit(f"journey_{action}", {"player_id": player_id, "node_ids": node_ids})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/progression/specialization", methods=["POST"])
@login_required
def set_specialization():
data = request.get_json() or {}
player_id = data.get("player_id")
track_type = data.get("track_type")
xp = data.get("xp")
level = data.get("level")
if player_id is None or not track_type or xp is None:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing required parameters"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["progression"]
svc.set_specialization(player_id, track_type, xp, level or 0)
_audit("specialization_set", {"player_id": player_id, "track": track_type, "xp": xp, "level": level})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/progression/specialization/reset", methods=["POST"])
@login_required
def reset_specializations():
data = request.get_json() or {}
player_id = data.get("player_id")
if player_id is None:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing player_id"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["progression"]
svc.reset_specializations(player_id)
_audit("specialization_reset", {"player_id": player_id})
return jsonify(ApiResponse(success=True).model_dump())
# ── Character Management Endpoints ──────────────────────────────
@api_bp.route("/characters/<int:account_id>/name", methods=["PUT"])
@login_required
def rename_character(account_id):
data = request.get_json() or {}
name = data.get("name", "").strip()
if not name:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing name"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["character"]
svc.rename(account_id, name)
_audit("character_rename", {"account_id": account_id, "new_name": name})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/characters/<int:actor_id>", methods=["DELETE"])
@login_required
def delete_character(actor_id):
from app.factory import get_services
svc = get_services()["character"]
svc.delete_character(actor_id)
_audit("character_delete", {"actor_id": actor_id})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/accounts/<user_id>", methods=["DELETE"])
@login_required
def delete_account(user_id):
data = request.get_json() or {}
reason = data.get("reason", "admin")
from app.factory import get_services
svc = get_services()["character"]
svc.delete_account(user_id, reason)
_audit("account_delete", {"user_id": user_id, "reason": reason})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/accounts/<user_id>/demo", methods=["PUT"])
@login_required
def set_demo_state(user_id):
data = request.get_json() or {}
state = data.get("demo")
if state is None:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing demo"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["character"]
svc.set_demo(user_id, state)
_audit("demo_set", {"user_id": user_id, "state": state})
return jsonify(ApiResponse(success=True).model_dump())
# ── Vehicles ────────────────────────────────────────────────────
@api_bp.route("/vehicles", methods=["GET"])
@login_required
def list_vehicles():
from app.factory import get_services
db = get_services()["db"]
term = request.args.get("q", "")
limit = int(request.args.get("limit", 100))
rows = db.execute_readonly(
"""SELECT a.id, a.class, a.map
FROM dune.actors a
JOIN dune.vehicle_instances vi ON a.id = vi.actor_id
WHERE a.class ILIKE %s
ORDER BY a.id DESC LIMIT %s""",
[f"%{term}%", limit],
)
vehicles = [{
"id": r["id"],
"class_name": r["class"],
"display_name": (r["class"] or "").split("/")[-1].replace("_C", "").replace("BP_", "").replace("_", " "),
"map": r["map"],
"owner_name": "Unknown",
} for r in rows]
return jsonify(ApiResponse(success=True, data=vehicles).model_dump())
@api_bp.route("/vehicles/<int:vehicle_id>/<action>", methods=["POST"])
@login_required
def vehicle_action(vehicle_id, action):
from app.factory import get_services
db = get_services()["db"]
if action == "repair":
db.call_procedure("repair_vehicle", [vehicle_id])
_audit("vehicle_repair", {"vehicle_id": vehicle_id})
elif action == "destroy":
db.call_procedure("destroy_vehicle", [vehicle_id])
_audit("vehicle_destroy", {"vehicle_id": vehicle_id})
else:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message=f"Unknown action: {action}"),
).model_dump()), 400
return jsonify(ApiResponse(success=True).model_dump())
# ── Buildings ───────────────────────────────────────────────────
@api_bp.route("/buildings", methods=["GET"])
@login_required
def list_buildings():
from app.factory import get_services
db = get_services()["db"]
term = request.args.get("q", "")
limit = int(request.args.get("limit", 100))
rows = db.execute_readonly(
"""SELECT a.id, a.class, a.map, a.properties->>'m_bIsPowered' as is_powered,
a.properties->>'m_PowerLevel' as power_level
FROM dune.actors a
JOIN dune.buildings b ON a.id = b.id
WHERE a.class ILIKE %s
ORDER BY a.id DESC LIMIT %s""",
[f"%{term}%", limit],
)
buildings = [{
"id": r["id"],
"class_name": r["class"],
"map": r["map"],
"owner_name": "Unknown",
"is_powered": r.get("is_powered") == "True",
"power_level": r.get("power_level"),
"instance_count": 1,
} for r in rows]
return jsonify(ApiResponse(success=True, data=buildings).model_dump())
# ── Accounts ────────────────────────────────────────────────────
@api_bp.route("/accounts", methods=["GET"])
@login_required
def list_accounts():
from app.factory import get_services
db = get_services()["db"]
term = request.args.get("q", "")
limit = int(request.args.get("limit", 100))
rows = db.execute_readonly(
"""SELECT a.id, COALESCE(a.email, '') as email, a.funcom_id,
(SELECT COUNT(*) FROM dune.player_state ps WHERE ps.account_id = a.id) as character_count,
COALESCE(a.is_demo, false) as is_demo, COALESCE(a.is_cheater, false) as is_cheater,
NULL as last_login
FROM dune.accounts a
WHERE a.email ILIKE %s OR a.funcom_id ILIKE %s
LIMIT %s""",
[f"%{term}%", f"%{term}%", limit],
)
accounts = [{
"id": r["id"],
"email": r.get("email") or "",
"funcom_id": r["funcom_id"],
"character_count": r["character_count"],
"is_demo": r["is_demo"],
"is_cheater": r["is_cheater"],
"last_login": r["last_login"].isoformat() if r["last_login"] else None,
} for r in rows]
return jsonify(ApiResponse(success=True, data=accounts).model_dump())
@api_bp.route("/players/<int:account_id>/cheater", methods=["POST"])
@login_required
def flag_cheater(account_id):
data = request.get_json() or {}
cheat_type = data.get("cheat_type")
if not cheat_type:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing cheat_type"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["character"]
svc.flag_cheater(account_id, cheat_type)
_audit("cheater_flag", {"account_id": account_id, "cheat_type": cheat_type})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/players/<int:account_id>/tags", methods=["GET"])
@login_required
def get_player_tags(account_id):
from app.factory import get_services
svc = get_services()["character"]
tags = svc.get_tags(account_id)
return jsonify(ApiResponse(success=True, data={"tags": tags}).model_dump())
@api_bp.route("/players/<int:account_id>/tags", methods=["PUT"])
@login_required
def update_player_tags(account_id):
data = request.get_json() or {}
add = data.get("add", [])
remove = data.get("remove", [])
from app.factory import get_services
svc = get_services()["character"]
svc.update_tags(account_id, add, remove)
_audit("tags_update", {"account_id": account_id, "add": add, "remove": remove})
return jsonify(ApiResponse(success=True).model_dump())
# ── Broadcast ───────────────────────────────────────────────────
@api_bp.route("/broadcast", methods=["POST"])
@login_required
def send_broadcast():
data = request.get_json() or {}
try:
req = BroadcastRequest(**data)
except ValidationError as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message=str(e)),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["rmq_game"]
success = svc.send_broadcast(req.message, server=req.server, partition=req.partition)
if success:
_audit("broadcast_sent", {"message": req.message, "server": req.server, "partition": req.partition})
return jsonify(ApiResponse(success=True).model_dump())
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="BroadcastFailed", message="Failed to send broadcast via RMQ"),
).model_dump()), 502
# ── Vendor / Economy ────────────────────────────────────────────
@api_bp.route("/vendors/clean", methods=["POST"])
@login_required
def clean_vendor_stock():
data = request.get_json() or {}
player_id = data.get("player_id")
if not player_id:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing player_id"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["economy"]
svc.clean_vendor_stock(player_id)
_audit("vendor_clean", {"player_id": player_id})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/tax/invoices", methods=["POST"])
@login_required
def get_tax_invoices():
data = request.get_json() or {}
player_id = data.get("player_id")
if not player_id:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing player_id"),
).model_dump()), 400
from app.factory import get_services
svc = get_services()["economy"]
invoices = svc.get_tax_invoices(player_id)
return jsonify(ApiResponse(success=True, data=invoices).model_dump())
# ── Function Explorer ────────────────────────────────────────────
@api_bp.route("/functions", methods=["GET"])
@login_required
def list_functions():
from app.factory import get_services
db = get_services()["db"]
rows = db.execute_readonly(
"""SELECT p.proname as name,
pg_get_function_identity_arguments(p.oid) as args,
l.lanname as language,
p.prokind as kind
FROM pg_proc p
JOIN pg_namespace n ON n.oid = p.pronamespace
JOIN pg_language l ON l.oid = p.prolang
WHERE n.nspname = 'dune' AND p.prokind = 'f'
ORDER BY p.proname"""
)
return jsonify(ApiResponse(success=True, data=rows).model_dump())
@api_bp.route("/functions/<name>", methods=["GET"])
@login_required
def get_function_detail(name):
from app.factory import get_services
db = get_services()["db"]
rows = db.execute_readonly(
"""SELECT pg_get_functiondef(p.oid) as definition,
p.proname as name,
pg_get_function_identity_arguments(p.oid) as args
FROM pg_proc p
JOIN pg_namespace n ON n.oid = p.pronamespace
WHERE n.nspname = 'dune' AND p.proname = %s AND p.prokind = 'f'""",
[name],
)
if not rows:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="NotFound", message="Function not found"),
).model_dump()), 404
return jsonify(ApiResponse(success=True, data=rows[0]).model_dump())
@api_bp.route("/functions/execute", methods=["POST"])
@login_required
def execute_function_v2():
data = request.get_json() or {}
schema = data.get("schema")
func_name = data.get("function", "")
args = data.get("args", {})
if not func_name:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing function name"),
).model_dump()), 400
from app.factory import get_services
db = get_services()["db"]
try:
full_name = f"{schema}.{func_name}" if schema else func_name
if isinstance(args, dict):
params = list(args.values())
elif isinstance(args, list):
params = args
else:
params = [args]
result = db.call_function(full_name, params)
_audit("function_execute", {"function": full_name, "params": params})
return jsonify(ApiResponse(success=True, data=result).model_dump())
except Exception as e:
logger.exception("Function execution failed")
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ExecutionError", message=str(e)),
).model_dump()), 500
@api_bp.route("/functions/<name>/execute", methods=["POST"])
@login_required
def execute_function(name):
data = request.get_json() or {}
params = data.get("params", [])
from app.factory import get_services
db = get_services()["db"]
try:
result = db.call_function(name, params)
_audit("function_execute", {"function": name, "params": params})
return jsonify(ApiResponse(success=True, data=result).model_dump())
except Exception as e:
logger.exception("Function execution failed")
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ExecutionError", message=str(e)),
).model_dump()), 500
# ── Raw Query (SELECT only) ──────────────────────────────────────
@api_bp.route("/query", methods=["POST"])
@login_required
def raw_query():
data = request.get_json() or {}
sql = (data.get("query") or data.get("sql", "")).strip()
if not sql:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Missing SQL"),
).model_dump()), 400
upper = sql.upper()
if any(kw in upper for kw in ("INSERT", "UPDATE", "DELETE", "DROP", "CREATE", "ALTER", "GRANT", "TRUNCATE")):
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="Forbidden", message="Only SELECT queries are allowed"),
).model_dump()), 403
from app.factory import get_services
db = get_services()["db"]
try:
result = db.execute_readonly(sql)
_audit("raw_query", {"sql": sql[:200]})
return jsonify(ApiResponse(success=True, data=result).model_dump())
except Exception as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="QueryError", message=str(e)),
).model_dump()), 500
# ── Audit Logs ──────────────────────────────────────────────────
@api_bp.route("/audit/logs", methods=["GET"])
@login_required
def get_audit_logs():
action = request.args.get("action")
user = request.args.get("user")
limit = int(request.args.get("limit", 100))
offset = int(request.args.get("offset", 0))
from app.factory import get_services
svc = get_services()["audit"]
logs = svc.get_logs(action=action, user=user, limit=limit, offset=offset)
return jsonify(ApiResponse(success=True, data=logs).model_dump())
@api_bp.route("/stats", methods=["GET"])
@login_required
def get_stats():
from app.factory import get_services
db = get_services()["db"]
try:
stats = db.execute_readonly("""
SELECT
(SELECT COUNT(*) FROM dune.player_state) AS total_players,
(SELECT COUNT(*) FROM dune.player_state WHERE online_status::text = 'Online') AS online_players,
(SELECT COUNT(*) FROM dune.guilds) AS guild_count,
(SELECT 0) AS active_guilds,
(SELECT COUNT(*) FROM dune.accounts) AS server_count,
(SELECT 0) AS partition_count,
(SELECT 0) AS total_worth,
(SELECT 0) AS total_flavor_text
""")
return jsonify(ApiResponse(success=True, data=stats[0] if stats else {}).model_dump())
except Exception as e:
logger.exception("Failed to get stats")
return jsonify(ApiResponse(success=False, error=ErrorDetail(code="StatsError", message=str(e))).model_dump()), 500
@api_bp.route("/audit/stats", methods=["GET"])
@login_required
def get_audit_stats():
from app.factory import get_services
svc = get_services()["audit"]
stats = svc.get_stats()
return jsonify(ApiResponse(success=True, data=stats).model_dump())
# ── Settings ────────────────────────────────────────────────────
@api_bp.route("/settings", methods=["GET"])
@login_required
def get_settings():
from app.factory import get_services
settings = get_services()["db"].execute_readonly(
"SELECT key, value, updated_at FROM dashboard.settings ORDER BY key"
)
return jsonify(ApiResponse(success=True, data={r["key"]: r["value"] for r in settings}).model_dump())
@api_bp.route("/settings", methods=["POST"])
@login_required
def update_settings():
data = request.get_json() or {}
if not isinstance(data, dict):
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="ValidationError", message="Expected JSON object"),
).model_dump()), 400
from app.factory import get_services
db = get_services()["db"]
for key, value in data.items():
db.execute_mutation(
"""INSERT INTO dashboard.settings (key, value, updated_at)
VALUES (%s, %s, NOW())
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()""",
[key, str(value)],
)
_audit("settings_update", {"keys": list(data.keys())})
return jsonify(ApiResponse(success=True).model_dump())
# ── Moderation (Ban / Kick) ────────────────────────────────────
@api_bp.route("/players/<int:player_id>/ban", methods=["POST"])
@login_required
def ban_player(player_id):
data = request.get_json() or {}
reason = data.get("reason", "admin")
duration = data.get("duration_hours", 0)
from app.factory import get_services
db = get_services()["db"]
db.execute_mutation(
"""INSERT INTO dashboard.bans (player_id, reason, duration, banned_at, expires_at, active)
VALUES (%s, %s, %s, NOW(), CASE WHEN %s > 0 THEN NOW() + INTERVAL '%s hours' ELSE NULL END, TRUE)
ON CONFLICT (player_id) DO UPDATE SET reason = EXCLUDED.reason, duration = EXCLUDED.duration, banned_at = NOW(), expires_at = EXCLUDED.expires_at, active = TRUE""",
[player_id, reason, duration, duration, duration],
)
_audit("player_ban", {"player_id": player_id, "reason": reason, "duration": duration})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/players/<int:player_id>/unban", methods=["POST"])
@login_required
def unban_player(player_id):
from app.factory import get_services
db = get_services()["db"]
db.execute_mutation(
"UPDATE dashboard.bans SET active = FALSE WHERE player_id = %s",
[player_id],
)
_audit("player_unban", {"player_id": player_id})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/players/<int:player_id>/ban", methods=["GET"])
@login_required
def get_player_ban(player_id):
from app.factory import get_services
db = get_services()["db"]
rows = db.execute_readonly(
"SELECT * FROM dashboard.bans WHERE player_id = %s AND active = TRUE",
[player_id],
)
return jsonify(ApiResponse(success=True, data=rows[0] if rows else None).model_dump())
@api_bp.route("/players/<int:player_id>/kick", methods=["POST"])
@login_required
def kick_player(player_id):
data = request.get_json() or {}
reason = data.get("reason", "admin")
_audit("player_kick", {"player_id": player_id, "reason": reason})
return jsonify(ApiResponse(success=True).model_dump())
@api_bp.route("/players/<int:player_id>/history", methods=["GET"])
@login_required
def get_player_history(player_id):
from app.factory import get_services
db = get_services()["db"]
logs = db.execute_readonly(
"""SELECT * FROM dashboard.audit_log
WHERE target_player_id = %s OR (details->>'player_id')::bigint = %s
ORDER BY created_at DESC LIMIT 100""",
[player_id, player_id],
)
return jsonify(ApiResponse(success=True, data=logs).model_dump())
-131
View File
@@ -1,131 +0,0 @@
# Authentication routes — login, logout.
import time
import threading
from functools import wraps
from flask import Blueprint, request, jsonify, session
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user
from app.models import ApiResponse, ErrorDetail
auth_bp = Blueprint("auth", __name__)
login_manager = LoginManager()
_failed_attempts = {}
_failed_lock = threading.Lock()
_MAX_FAILED_ATTEMPTS = 5
_BLOCK_DURATION = 900
class AdminUser(UserMixin):
def __init__(self, username):
self.id = username
def _is_ip_blocked(ip):
with _failed_lock:
record = _failed_attempts.get(ip)
if record and record["count"] >= _MAX_FAILED_ATTEMPTS:
elapsed = time.time() - record["first_attempt"]
if elapsed < _BLOCK_DURATION:
return True
del _failed_attempts[ip]
return False
def _record_failed_attempt(ip):
with _failed_lock:
now = time.time()
record = _failed_attempts.get(ip)
if record:
record["count"] += 1
else:
_failed_attempts[ip] = {"count": 1, "first_attempt": now}
return _failed_attempts[ip]["count"] >= _MAX_FAILED_ATTEMPTS
def _clear_failed_attempts(ip):
with _failed_lock:
_failed_attempts.pop(ip, None)
def init_auth(app, settings):
login_manager.init_app(app)
login_manager.login_view = "auth.login"
login_manager.login_message = "Please log in."
@login_manager.user_loader
def load_user(user_id):
auth = settings.get("auth", {})
if str(auth.get("username")) == str(user_id):
return AdminUser(user_id)
return None
def get_audit_user():
return current_user.id if current_user.is_authenticated else "anonymous"
@auth_bp.route("/login", methods=["POST"])
def login():
data = request.get_json() or {}
username = data.get("username", "").strip()
password = data.get("password", "")
client_ip = request.remote_addr or "unknown"
if _is_ip_blocked(client_ip):
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="IpBlocked", message="Too many failed attempts. Try again later."),
).model_dump()), 429
auth = request.app.dune_settings.get("auth", {})
cfg_u = str(auth.get("username", ""))
password_hash = auth.get("password_hash")
if username != cfg_u:
_record_failed_attempt(client_ip)
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="InvalidCredentials", message="Invalid username or password"),
).model_dump()), 401
if password_hash:
try:
from argon2 import PasswordHasher, exceptions
ph = PasswordHasher(time_cost=3, memory_cost=65536)
ph.verify(password_hash, password)
_clear_failed_attempts(client_ip)
login_user(AdminUser(username))
return jsonify(ApiResponse(success=True, data={"user": username}).model_dump())
except exceptions.VerifyMismatchError:
_record_failed_attempt(client_ip)
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="InvalidCredentials", message="Invalid username or password"),
).model_dump()), 401
except Exception:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="AuthError", message="Authentication error"),
).model_dump()), 500
else:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="NotConfigured", message="Authentication not configured"),
).model_dump()), 403
@auth_bp.route("/logout", methods=["POST"])
@login_required
def logout():
logout_user()
return jsonify(ApiResponse(success=True).model_dump())
@auth_bp.route("/me", methods=["GET"])
def me():
if current_user.is_authenticated:
return jsonify(ApiResponse(success=True, data={"user": current_user.id}).model_dump())
return jsonify(ApiResponse(success=False, error=ErrorDetail(code="Unauthorized", message="Not authenticated")).model_dump()), 401
-24
View File
@@ -1,24 +0,0 @@
# Chat routes.
import logging
from flask import Blueprint, jsonify, request
from flask_login import login_required
from app.models import ApiResponse, ErrorDetail
chat_bp = Blueprint("chat", __name__)
logger = logging.getLogger(__name__)
@chat_bp.route("/history", methods=["GET"])
@login_required
def chat_history():
channel = request.args.get("channel", "")
limit = int(request.args.get("limit", 100))
from app.factory import get_services
svc = get_services()["chat"]
rows = svc.get_history(limit=limit)
if channel:
rows = [r for r in rows if r.get("channel", "").lower() == channel.lower()]
return jsonify(ApiResponse(success=True, data=rows).model_dump())
-43
View File
@@ -1,43 +0,0 @@
# Debug routes — restricted to admin.
import logging
from flask import Blueprint, jsonify
from flask_login import login_required
from app.models import ApiResponse, ErrorDetail
debug_bp = Blueprint("debug", __name__)
logger = logging.getLogger(__name__)
def _get_services():
from app.factory import get_services
return get_services()
@debug_bp.route("/tables", methods=["GET"])
@login_required
def list_tables():
db = _get_services()["db"]
rows = db.execute_readonly(
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'dune' ORDER BY table_name"
)
return jsonify(ApiResponse(success=True, data={"tables": [r["table_name"] for r in rows]}).model_dump())
@debug_bp.route("/vehicle/<int:vehicle_id>", methods=["GET"])
@login_required
def debug_vehicle(vehicle_id):
db = _get_services()["db"]
vehicle = db.execute_readonly(
"""SELECT a.id, a.class, a.properties
FROM dune.actors a JOIN dune.vehicles v ON a.id = v.id WHERE a.id = %s""",
[vehicle_id],
)
if not vehicle:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="NotFound", message="Vehicle not found"),
).model_dump()), 404
return jsonify(ApiResponse(success=True, data=vehicle[0]).model_dump())
-147
View File
@@ -1,147 +0,0 @@
# BGD Director proxy routes.
import logging
from flask import Blueprint, jsonify, request
from flask_login import login_required
from app.models import ApiResponse, ErrorDetail
director_bp = Blueprint("director", __name__)
logger = logging.getLogger(__name__)
def _get_service():
from app.factory import get_services
return get_services()["bg_director"]
@director_bp.route("/battlegroup", methods=["GET"])
@login_required
def director_battlegroup():
try:
svc = _get_service()
data = svc.get_battlegroup()
return jsonify(ApiResponse(success=True, data=data.model_dump()).model_dump())
except Exception as e:
logger.error("Director battlegroup error: %s", e)
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="DirectorUnavailable", message=str(e), hint="Check BGD pod logs"),
).model_dump()), 503
@director_bp.route("/config", methods=["POST"])
@login_required
def director_update_config():
data = request.get_json() or {}
try:
svc = _get_service()
result = svc.update_server_config(data)
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
except Exception as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
).model_dump()), 503
@director_bp.route("/config/clear", methods=["POST"])
@login_required
def director_clear_config():
map_name = request.get_data(as_text=True).strip()
try:
svc = _get_service()
result = svc.clear_map_config(map_name)
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
except Exception as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
).model_dump()), 503
@director_bp.route("/transfer", methods=["GET"])
@login_required
def director_transfer_get():
try:
svc = _get_service()
data = svc.get_transfer_rules()
return jsonify(ApiResponse(success=True, data=data).model_dump())
except Exception as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
).model_dump()), 503
@director_bp.route("/transfer", methods=["POST"])
@login_required
def director_transfer_update():
data = request.get_json() or {}
try:
svc = _get_service()
result = svc.update_transfer_settings(data)
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
except Exception as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
).model_dump()), 503
@director_bp.route("/transfer/clear", methods=["POST"])
@login_required
def director_transfer_clear():
try:
svc = _get_service()
result = svc.clear_transfer_overrides()
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
except Exception as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
).model_dump()), 503
@director_bp.route("/fls", methods=["GET"])
@login_required
def director_fls_get():
try:
svc = _get_service()
data = svc.get_fls_settings()
return jsonify(ApiResponse(success=True, data=data).model_dump())
except Exception as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
).model_dump()), 503
@director_bp.route("/fls", methods=["POST"])
@login_required
def director_fls_update():
data = request.get_json() or {}
try:
svc = _get_service()
result = svc.update_fls_settings(data)
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
except Exception as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
).model_dump()), 503
@director_bp.route("/fls/clear", methods=["POST"])
@login_required
def director_fls_clear():
try:
svc = _get_service()
result = svc.clear_fls_overrides()
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
except Exception as e:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
).model_dump()), 503
-120
View File
@@ -1,120 +0,0 @@
# File browser routes.
import base64
import logging
import posixpath
from flask import Blueprint, jsonify, request
from flask_login import login_required
from app.models import ApiResponse, ErrorDetail
files_bp = Blueprint("files", __name__)
logger = logging.getLogger(__name__)
FILEBROWSER_BASE_PATH = "/srv"
def _validate_fb_path(path: str) -> bool:
path_str = str(path or "").lstrip("/")
if ".." in path_str or "\x00" in path_str:
return False
normalized = posixpath.normpath("/" + path_str)
return normalized == FILEBROWSER_BASE_PATH or normalized.startswith(FILEBROWSER_BASE_PATH + "/")
def _get_services():
from app.factory import get_services
return get_services()
def _fb_exec(command: str, timeout: int = 10):
services = _get_services()
k8s = services["k8s"]
pod = k8s.get_filebrowser_pod()
if not pod:
return "", "FileBrowser pod not found", 1
full_cmd = f"sudo kubectl exec {pod} -n {k8s.namespace} -- {command}"
return k8s.ssh.run(full_cmd, timeout=timeout)
@files_bp.route("/list", methods=["POST"])
@login_required
def files_list():
data = request.get_json() or {}
path = data.get("path", "/srv")
if not _validate_fb_path(path):
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="AccessDenied", message="Invalid path"),
).model_dump()), 403
import shlex
safe_path = shlex.quote(path)
out, err, rc = _fb_exec(f"ls -la {safe_path}", timeout=10)
if rc != 0:
return jsonify(ApiResponse(
success=False,
error=ErrorDetail(code="CommandError", message=err or "Failed to list directory"),