Compare commits

..
Author SHA1 Message Date
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
6 changed files with 523 additions and 549 deletions

No files matched your search

+78 -319
View File
@@ -1,361 +1,120 @@
# Dune Awakening Dashboard # 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 ## Quick Start
### Windows ### **Windows**
1. Double-click `launcher.bat` (or run `.\launcher.ps1` in PowerShell) 1. Run `launcher.bat` or `.\launcher.ps1`
2. Select option **2** to run Setup on first use 2. Select **[2] Run Setup** on first launch
3. Select option **1** to Start Dashboard 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`. > The launcher automatically finds your Dune Awakening SSH key and politely ignores PowerShell’s opinions about execution policies.
>
> **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. ### **Linux / macOS**
```bash
chmod +x start.sh
./start.sh
```
---
## Features ## 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%. - **Interactive Maps** with calibrated coordinates
- **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. - **Player Management** (vitals, inventory, vehicles, buildings, guilds, reputation)
- **Chat Logs**: Parsed from text-router pod logs with channel filtering and auto-refresh. - **Chat Logs** with channel filtering and auto-refresh
- **Director Controls**: Live battlegroup stats, world state management, and server transfer controls. - **Director Tools** (battlegroups, world state, transfers)
- **File Browser**: Secure SSH-based file browser for server configuration and logs. - **SSH File Browser** + **in-browser shell**
- **Shell Access**: Interactive VM and Kubernetes pod shells directly in the browser. - **Admin Tools** (ban/kick, history, read‑only SQL viewer)
- **Admin Tools**: Ban management, IP detection, kick/unban functionality, player history, item/currency/vitals editing, and raw SQL query interface. - **Firewall Hardening** via iptables
- **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. - **Auto‑Update** with safe file replacement
- **Vehicles & Buildings**: Track owned vehicles, modules, and player structures. - **HTTPS + Remote Access** (self‑signed or Let’s Encrypt)
- **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. - **Cross‑Platform Launchers**
- **Remote Access**: Built-in support for HTTPS and binding to `0.0.0.0` for secure remote management. - **Organized Logging** with automatic cleanup and redaction
- **Let's Encrypt**: Optionally set up publicly trusted SSL certs during setup with automatic renewal via certbot. - **Debug Mode** with full request/SSH/K8s tracing
- **Settings Migration**: Automatically adds new configuration options to `settings.yaml` when updating, so you never miss a feature. - **14 Dune house themes** (Atreides, Harkonnen, Fremen etc.)
- **Cross-Platform**: Works on Windows (`.bat`/`.ps1`) and Linux/macOS (`.sh`). - And yes, it’s all probably more than you’ll ever need — but it *felt right at the time*.
- **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`.
## 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
- **[9] Repair Game Database** — Fix dashboard schema ownership so game updates won't break servers
- **[10] Clean up Old Dashboard Schema** — Drop the old `dashboard` schema from the game database (after migration)
- **[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 ## Project Structure
``` ```
DuneDashboard/ DuneDashboard/
├── backend/ # New Flask backend (API + services) ├── backend/ # Flask API + services
│ ├── app/ ├── frontend/ # React + Vite + Tailwind SPA
│ │ ├── routes/ # HTTP route handlers (API, auth, health, server, files, director, chat) ├── app/ # Legacy Flask/Jinja2 dashboard
│ │ ├── services/ # Business logic (DB, SSH, K8s, BGD, RMQ, player, economy, guild, world, etc.) ├── launcher.ps1 # Windows launcher
│ │ ├── models/ # Pydantic v2 models ├── start.sh # Linux/macOS launcher
│ │ ├── websocket/ # Socket.IO shell handler └── settings.yaml # Generated config (gitignored)
│ │ ├── 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
``` ```
> **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. > The legacy dashboard still works. Like an old Fremen still wandering the desert — reliable, but we don’t talk about it much.
## Architecture ---
### Frontend ## Requirements
- **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
### Backend - Python 3.8+
- **Flask 3** with Blueprint-based routing - Node.js 18+
- **Pydantic v2** for request/response validation - OpenSSH client
- **psycopg3** with connection pooling for PostgreSQL - `kubectl` access to your Dune Awakening cluster
- **Flask-SocketIO** for the interactive shell - SSH access to the game server VM
- **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 Notes ## Security
- Never commit `settings.yaml` to version control. - `settings.yaml` is never committed
- SSH keys are copied to `%TEMP%` with restricted permissions during startup. - SSH keys stored with restricted permissions
- All database queries use parameterized statements to prevent SQL injection. - All DB queries parameterized
- Dashboard authentication is required by default. - Raw SQL endpoint is **read‑only SELECT**
- Raw SQL query endpoint (`/api/query`) is **read-only SELECT** — INSERT/UPDATE/DELETE/DROP/CREATE/ALTER/GRANT/TRUNCATE are blocked. - All mutations audited
- All mutations are audited to PostgreSQL. - CSP, HSTS, X‑Frame‑Options enforced in production
- CSP, HSTS, X-Frame-Options, and other security headers are enforced in production mode.
## Logging > “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.
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 ## Development
### Frontend Development ### Frontend
```bash ```bash
cd frontend cd frontend
npm install npm install
npm run dev # Vite dev server with API proxy to localhost:5050 npm run dev
npm run build # Production build to frontend/dist/
``` ```
### Backend Development ### Backend
```bash ```bash
cd backend cd backend
pip install -r requirements.txt pip install -r requirements.txt
python run.py # Or: flask --app run:app run python run.py
``` ```
### Themes ---
The dashboard supports 14 Dune house themes. Switch via the theme picker in the top-right nav bar: ## Branching Strategy
Classic Dune, House Atreides, House Harkonnen, Fremen, Bene Gesserit, Spacing Guild, Emperor, House Corrino, Mentat, Sardaukar, Bene Tleilax, House Ordos, Ix, CHOAM.
- **main** — stable-ish beta
- **nightly** — latest features
- **experimental** — where chaos becomes innovation
> “This seemed like a great idea at 3am.” — every experimental commit ever
---
## 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.
+5 -4
View File
@@ -44,6 +44,7 @@ def create_app(settings_path=None):
static_url_path='/static' static_url_path='/static'
) )
app.config['SECRET_KEY'] = settings['dashboard']['secret_key'] 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_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax' app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
app.config['PERMANENT_SESSION_LIFETIME'] = 28800 # 8 hours app.config['PERMANENT_SESSION_LIFETIME'] = 28800 # 8 hours
@@ -289,11 +290,11 @@ def create_app(settings_path=None):
cors_origins = "*" if settings['dashboard']['host'] == '0.0.0.0' else [] cors_origins = "*" if settings['dashboard']['host'] == '0.0.0.0' else []
socketio = SocketIO(app, cors_allowed_origins=cors_origins, async_mode='threading') 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( limiter = Limiter(
app=app, app=app,
key_func=get_remote_address, key_func=get_remote_address,
default_limits=["200 per day", "50 per hour"], default_limits=[], # rate limits applied per-route only (login has 10/min)
storage_uri="memory://", storage_uri="memory://",
) )
app.limiter = limiter app.limiter = limiter
@@ -305,8 +306,8 @@ def create_app(settings_path=None):
register_api_routes(app, services, settings) register_api_routes(app, services, settings)
register_websocket_handlers(socketio, settings) register_websocket_handlers(socketio, settings)
# Start update checker # Start update checker (disabled — being reworked)
updater_svc.start_checker() # updater_svc.start_checker()
@app.teardown_appcontext @app.teardown_appcontext
def cleanup_db(exc): def cleanup_db(exc):
+124 -38
View File
@@ -57,7 +57,7 @@ def register_api_routes(app, services, settings):
# Server actions # Server actions
@app.route('/server/action', methods=['POST']) @app.route('/server/action', methods=['POST'])
@auth_req @auth_req
@limiter.limit("500 per hour")
def server_action(): def server_action():
deployment = request.form.get('deployment', '') deployment = request.form.get('deployment', '')
action = request.form.get('action', '') action = request.form.get('action', '')
@@ -114,7 +114,7 @@ def register_api_routes(app, services, settings):
@app.route('/server/battlegroup/action', methods=['POST']) @app.route('/server/battlegroup/action', methods=['POST'])
@auth_req @auth_req
@limiter.limit("500 per hour")
def battlegroup_action(): def battlegroup_action():
action = request.form.get('action', '') action = request.form.get('action', '')
if action not in ('start', 'stop', 'restart'): 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']) @app.route('/server/battlegroup/update', methods=['POST'])
@auth_req @auth_req
@limiter.limit("1000 per hour")
def battlegroup_update(): def battlegroup_update():
bg_script = settings['kubernetes']['battlegroup_script'] bg_script = settings['kubernetes']['battlegroup_script']
out, err, rc = ssh.run(f'{bg_script} update', timeout=600) 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']) @app.route('/server/firewall/block', methods=['POST'])
@auth_req @auth_req
@limiter.limit("500 per hour")
def firewall_block(): def firewall_block():
port = request.form.get('port', type=int) port = request.form.get('port', type=int)
bgd_port = _get_bgd_nodeport() bgd_port = _get_bgd_nodeport()
@@ -239,7 +239,7 @@ def register_api_routes(app, services, settings):
@app.route('/server/firewall/unblock', methods=['POST']) @app.route('/server/firewall/unblock', methods=['POST'])
@auth_req @auth_req
@limiter.limit("500 per hour")
def firewall_unblock(): def firewall_unblock():
port = request.form.get('port', type=int) port = request.form.get('port', type=int)
bgd_port = _get_bgd_nodeport() bgd_port = _get_bgd_nodeport()
@@ -345,7 +345,7 @@ def register_api_routes(app, services, settings):
# Ban management # Ban management
@app.route('/api/ban_player', methods=['POST']) @app.route('/api/ban_player', methods=['POST'])
@auth_req @auth_req
@limiter.limit("1000 per hour")
def api_ban_player(): def api_ban_player():
try: try:
player_id = request.form.get('player_id', type=int) 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']) @app.route('/api/unban_player', methods=['POST'])
@auth_req @auth_req
@limiter.limit("1000 per hour")
def api_unban_player(): def api_unban_player():
try: try:
player_id = request.form.get('player_id', type=int) 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']) @app.route('/api/kick_player', methods=['POST'])
@auth_req @auth_req
@limiter.limit("500 per hour")
def api_kick_player(): def api_kick_player():
try: try:
player_id = request.form.get('player_id', type=int) player_id = request.form.get('player_id', type=int)
@@ -449,7 +449,7 @@ def register_api_routes(app, services, settings):
# Vitals editing # Vitals editing
@app.route('/api/edit_vitals', methods=['POST']) @app.route('/api/edit_vitals', methods=['POST'])
@auth_req @auth_req
@limiter.limit("500 per hour")
def api_edit_vitals(): def api_edit_vitals():
try: try:
pawn_id = request.form.get('pawn_id', type=int) pawn_id = request.form.get('pawn_id', type=int)
@@ -800,35 +800,66 @@ def register_api_routes(app, services, settings):
FILEBROWSER_BASE_PATH = '/srv' FILEBROWSER_BASE_PATH = '/srv'
def _validate_fb_path(path): def _validate_fb_path(path):
"""Validate filebrowser path is within allowed directory.""" """Validate filebrowser path — allow any path, block traversal."""
import posixpath
path_str = str(path or "").lstrip("/") path_str = str(path or "").lstrip("/")
if '..' in path_str or '\x00' in path_str: if '..' in path_str or '\x00' in path_str:
return False return False
normalized = posixpath.normpath("/" + path_str) return True
return normalized == FILEBROWSER_BASE_PATH or normalized.startswith(FILEBROWSER_BASE_PATH + "/")
def _get_fb_pod(): 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') pod = k8s.find_pod_by_pattern('fb-deploy')
return pod return pod
def _fb_exec(command, timeout=10): def _list_pods():
"""Execute kubectl exec in the FileBrowser pod with correct namespace placement.""" """List all running pods available for file browsing, plus VM host."""
pod = _get_fb_pod() 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: 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}' full_cmd = f'sudo kubectl exec {pod} -n {k8s.namespace} -- {command}'
return k8s.ssh.run(full_cmd, timeout=timeout) 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']) @app.route('/api/files/list', methods=['POST'])
@auth_req @auth_req
def api_files_list(): def api_files_list():
path = request.form.get('path', '/srv') path = request.form.get('path', '/srv')
pod_name = _get_pod_from_request()
if not _validate_fb_path(path): if not _validate_fb_path(path):
return jsonify({'success': False, 'error': 'Invalid path: access denied'}) return jsonify({'success': False, 'error': 'Invalid path: access denied'})
safe_path = quote_remote(path) 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: if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to list directory'}) return jsonify({'success': False, 'error': err or 'Failed to list directory'})
@@ -855,35 +886,90 @@ def register_api_routes(app, services, settings):
@auth_req @auth_req
def api_files_view(): def api_files_view():
path = request.args.get('path', '') path = request.args.get('path', '')
pod_name = _get_pod_from_request()
if not path: if not path:
return jsonify({'success': False, 'error': 'Missing path'}) return jsonify({'success': False, 'error': 'Missing path'})
if not _validate_fb_path(path): if not _validate_fb_path(path):
return jsonify({'success': False, 'error': 'Invalid path: access denied'}) return jsonify({'success': False, 'error': 'Invalid path: access denied'})
safe_path = quote_remote(path) 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: if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to read file'}) return jsonify({'success': False, 'error': err or 'Failed to read file'})
return jsonify({'success': True, 'content': out, 'path': path}) return jsonify({'success': True, 'content': out, 'path': path})
@app.route('/api/files/save', methods=['POST']) @app.route('/api/files/save', methods=['POST'])
@auth_req @auth_req
@limiter.limit("50 per hour")
def api_files_save(): def api_files_save():
path = request.form.get('path', '') path = request.form.get('path', '')
content = request.form.get('content', '') content = request.form.get('content', '')
pod_name = _get_pod_from_request()
if not path: if not path:
return jsonify({'success': False, 'error': 'Missing path'}) return jsonify({'success': False, 'error': 'Missing path'})
if not _validate_fb_path(path): if not _validate_fb_path(path):
return jsonify({'success': False, 'error': 'Invalid path: access denied'}) return jsonify({'success': False, 'error': 'Invalid path: access denied'})
import base64 import base64
content_b64 = base64.b64encode(content.encode()).decode() content_b64 = base64.b64encode(content.encode()).decode()
safe_path = quote_remote(path) out, err, rc = _fb_write_file(content_b64, path, pod_name)
save_script = quote_remote(f"base64 -d > {safe_path}")
out, err, rc = _fb_exec(f"sh -c {save_script}", timeout=15)
if rc != 0: if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to save file'}) return jsonify({'success': False, 'error': err or 'Failed to save file'})
return jsonify({'success': True}) 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_svc = services.get('director')
director_port = settings.get('director', {}).get('port', 32479) director_port = settings.get('director', {}).get('port', 32479)
@@ -1255,7 +1341,7 @@ def register_api_routes(app, services, settings):
# ── Admin Experimental: Broadcast ───────────────────────────────── # ── Admin Experimental: Broadcast ─────────────────────────────────
@app.route('/api/admin-experimental/broadcast', methods=['POST']) @app.route('/api/admin-experimental/broadcast', methods=['POST'])
@auth_req @auth_req
@limiter.limit("100 per hour")
def admin_broadcast(): def admin_broadcast():
data = request.get_json() or {} data = request.get_json() or {}
title = (data.get('title') or '').strip() title = (data.get('title') or '').strip()
@@ -1272,7 +1358,7 @@ def register_api_routes(app, services, settings):
# ── Admin Experimental: Query Database ──────────────────────────── # ── Admin Experimental: Query Database ────────────────────────────
@app.route('/api/admin-experimental/query', methods=['POST']) @app.route('/api/admin-experimental/query', methods=['POST'])
@auth_req @auth_req
@limiter.limit("300 per hour")
def admin_query(): def admin_query():
data = request.get_json() or {} data = request.get_json() or {}
sql = (data.get('sql') or '').strip() sql = (data.get('sql') or '').strip()
@@ -1311,7 +1397,7 @@ def register_api_routes(app, services, settings):
# ── Admin Experimental: Adjust Currency ─────────────────────────── # ── Admin Experimental: Adjust Currency ───────────────────────────
@app.route('/api/admin-experimental/adjust-currency', methods=['POST']) @app.route('/api/admin-experimental/adjust-currency', methods=['POST'])
@auth_req @auth_req
@limiter.limit("200 per hour")
def admin_adjust_currency(): def admin_adjust_currency():
data = request.get_json() or {} data = request.get_json() or {}
pid = data.get('player_controller_id') pid = data.get('player_controller_id')
@@ -1325,7 +1411,7 @@ def register_api_routes(app, services, settings):
# ── Admin Experimental: Change Faction ──────────────────────────── # ── Admin Experimental: Change Faction ────────────────────────────
@app.route('/api/admin-experimental/change-faction', methods=['POST']) @app.route('/api/admin-experimental/change-faction', methods=['POST'])
@auth_req @auth_req
@limiter.limit("100 per hour")
def admin_change_faction(): def admin_change_faction():
data = request.get_json() or {} data = request.get_json() or {}
pid = data.get('player_id') pid = data.get('player_id')
@@ -1365,7 +1451,7 @@ def register_api_routes(app, services, settings):
# ── Admin Experimental: Teleport Player ─────────────────────────── # ── Admin Experimental: Teleport Player ───────────────────────────
@app.route('/api/admin-experimental/teleport', methods=['POST']) @app.route('/api/admin-experimental/teleport', methods=['POST'])
@auth_req @auth_req
@limiter.limit("100 per hour")
def admin_teleport(): def admin_teleport():
data = request.get_json() or {} data = request.get_json() or {}
fls_id = data.get('fls_id') fls_id = data.get('fls_id')
@@ -1449,7 +1535,7 @@ def register_api_routes(app, services, settings):
@app.route('/api/admin-experimental/disband-guild', methods=['POST']) @app.route('/api/admin-experimental/disband-guild', methods=['POST'])
@auth_req @auth_req
@limiter.limit("50 per hour")
def admin_disband_guild(): def admin_disband_guild():
data = request.get_json() or {} data = request.get_json() or {}
guild_id = data.get('guild_id') guild_id = data.get('guild_id')
@@ -1463,7 +1549,7 @@ def register_api_routes(app, services, settings):
@app.route('/api/admin-experimental/remove-guild-member', methods=['POST']) @app.route('/api/admin-experimental/remove-guild-member', methods=['POST'])
@auth_req @auth_req
@limiter.limit("100 per hour")
def admin_remove_guild_member(): def admin_remove_guild_member():
data = request.get_json() or {} data = request.get_json() or {}
guild_id = data.get('guild_id') guild_id = data.get('guild_id')
@@ -1496,7 +1582,7 @@ def register_api_routes(app, services, settings):
@app.route('/api/admin-experimental/flag-cheater', methods=['POST']) @app.route('/api/admin-experimental/flag-cheater', methods=['POST'])
@auth_req @auth_req
@limiter.limit("50 per hour")
def admin_flag_cheater(): def admin_flag_cheater():
data = request.get_json() or {} data = request.get_json() or {}
account_id = data.get('account_id') account_id = data.get('account_id')
@@ -1555,7 +1641,7 @@ def register_api_routes(app, services, settings):
@app.route('/api/admin-experimental/delete-character', methods=['POST']) @app.route('/api/admin-experimental/delete-character', methods=['POST'])
@auth_req @auth_req
@limiter.limit("20 per hour")
def admin_delete_character(): def admin_delete_character():
data = request.get_json() or {} data = request.get_json() or {}
actor_id = data.get('actor_id') actor_id = data.get('actor_id')
@@ -1569,7 +1655,7 @@ def register_api_routes(app, services, settings):
@app.route('/api/admin-experimental/delete-account', methods=['POST']) @app.route('/api/admin-experimental/delete-account', methods=['POST'])
@auth_req @auth_req
@limiter.limit("10 per hour")
def admin_delete_account(): def admin_delete_account():
data = request.get_json() or {} data = request.get_json() or {}
user_id = data.get('user_id') user_id = data.get('user_id')
@@ -1686,7 +1772,7 @@ def register_api_routes(app, services, settings):
# ── Admin Experimental: Spice Fields ────────────────────────────── # ── Admin Experimental: Spice Fields ──────────────────────────────
@app.route('/api/admin-experimental/spice', methods=['POST']) @app.route('/api/admin-experimental/spice', methods=['POST'])
@auth_req @auth_req
@limiter.limit("30 per hour")
def admin_spice(): def admin_spice():
data = request.get_json() or {} data = request.get_json() or {}
try: try:
@@ -1701,7 +1787,7 @@ def register_api_routes(app, services, settings):
# ── Admin Experimental: Server Tools ────────────────────────────── # ── Admin Experimental: Server Tools ──────────────────────────────
@app.route('/api/admin-experimental/server-tools', methods=['POST']) @app.route('/api/admin-experimental/server-tools', methods=['POST'])
@auth_req @auth_req
@limiter.limit("30 per hour")
def admin_server_tools(): def admin_server_tools():
data = request.get_json() or {} data = request.get_json() or {}
try: try:
@@ -1867,7 +1953,7 @@ def register_api_routes(app, services, settings):
@app.route('/api/admin-experimental/functions/<name>/execute', methods=['POST']) @app.route('/api/admin-experimental/functions/<name>/execute', methods=['POST'])
@auth_req @auth_req
@limiter.limit("200 per hour")
def admin_execute_function(name): def admin_execute_function(name):
data = request.get_json() or {} data = request.get_json() or {}
params = data.get('params', []) params = data.get('params', [])
@@ -1883,7 +1969,7 @@ def register_api_routes(app, services, settings):
# ── Admin Experimental: SQL Execute (admin functions) ───────────── # ── Admin Experimental: SQL Execute (admin functions) ─────────────
@app.route('/api/admin-experimental/execute', methods=['POST']) @app.route('/api/admin-experimental/execute', methods=['POST'])
@auth_req @auth_req
@limiter.limit("200 per hour")
def admin_execute(): def admin_execute():
data = request.get_json() or {} data = request.get_json() or {}
sql = (data.get('sql') or '').strip() sql = (data.get('sql') or '').strip()
-59
View File
@@ -10,13 +10,6 @@
{% block head_extra %}{% endblock %} {% block head_extra %}{% endblock %}
</head> </head>
<body> <body>
<div id="update-banner" class="update-banner" style="display:none;">
<span>🔄 Update available for Dune Dashboard</span>
<div class="update-actions">
<button onclick="applyUpdate()" class="update-btn primary">Update Now</button>
<button onclick="dismissUpdate()" class="update-btn">Later</button>
</div>
</div>
<nav> <nav>
<div class="brand">DUNE DASHBOARD</div> <div class="brand">DUNE DASHBOARD</div>
{% for href, label in nav_pages %} {% for href, label in nav_pages %}
@@ -104,7 +97,6 @@
<span class="conn-dot {% if conn_ok %}online{% else %}offline{% endif %}"></span> <span class="conn-dot {% if conn_ok %}online{% else %}offline{% endif %}"></span>
{{ 'Connected' if conn_ok else 'Disconnected' }} {{ 'Connected' if conn_ok else 'Disconnected' }}
</span> </span>
<button id="check-update-btn" onclick="manualCheckUpdate()" style="font-size:12px;color:var(--nav-text);background:none;border:none;cursor:pointer;padding:4px 8px;" title="Check for updates">🔄 Check Updates</button>
{% if current_user and current_user.is_authenticated %} {% if current_user and current_user.is_authenticated %}
<a href="/logout" style="font-size:12px;color:var(--nav-text);">Logout</a> <a href="/logout" style="font-size:12px;color:var(--nav-text);">Logout</a>
{% endif %} {% endif %}
@@ -115,13 +107,6 @@
<footer class="site-footer"> <footer class="site-footer">
<span>This is a fan-made project and is not affiliated with, endorsed by, or connected to Funcom, Legendary Entertainment, or any official Dune rights holders. All game assets, trademarks, and intellectual property belong to their respective owners.</span> <span>This is a fan-made project and is not affiliated with, endorsed by, or connected to Funcom, Legendary Entertainment, or any official Dune rights holders. All game assets, trademarks, and intellectual property belong to their respective owners.</span>
</footer> </footer>
<div id="update-progress" class="update-progress" style="display:none;">
<div class="update-progress-inner">
<h3>Updating Dashboard...</h3>
<p id="update-status-text">Checking for updates...</p>
<div class="update-spinner"></div>
</div>
</div>
<script> <script>
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content'); const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
@@ -131,40 +116,6 @@
return fetch(url, options); return fetch(url, options);
} }
let updateDismissed = false;
async function checkForUpdate() {
if (updateDismissed) return;
try {
const resp = await fetch('/api/update/status');
const data = await resp.json();
if (data.available) {
document.getElementById('update-banner').style.display = 'flex';
}
} catch (e) {}
}
async function manualCheckUpdate() {
const progress = document.getElementById('update-progress');
const statusText = document.getElementById('update-status-text');
progress.style.display = 'flex';
statusText.textContent = 'The update system is being reworked for better reliability. Please check back soon.';
setTimeout(() => { progress.style.display = 'none'; }, 4000);
}
function dismissUpdate() {
updateDismissed = true;
document.getElementById('update-banner').style.display = 'none';
}
async function applyUpdate() {
const banner = document.getElementById('update-banner');
const progress = document.getElementById('update-progress');
const statusText = document.getElementById('update-status-text');
banner.style.display = 'none';
progress.style.display = 'flex';
statusText.textContent = 'The auto-update system is being reworked to be more reliable and robust. Manual updates from the launcher still work.';
setTimeout(() => { progress.style.display = 'none'; }, 5000);
}
setInterval(checkForUpdate, 60000);
checkForUpdate();
// Theme System // Theme System
function setTheme(themeName) { function setTheme(themeName) {
document.documentElement.setAttribute('data-theme', themeName); document.documentElement.setAttribute('data-theme', themeName);
@@ -188,16 +139,6 @@
</script> </script>
{% block scripts %}{% endblock %} {% block scripts %}{% endblock %}
<style> <style>
.update-banner { background: var(--hover); border-bottom: 2px solid var(--accent); padding: 10px 20px; display: flex; justify-content: space-between; align-items: center; font-size: 13px; color: var(--text); }
.update-actions { display: flex; gap: 8px; }
.update-btn { padding: 4px 12px; border: 1px solid var(--border); border-radius: 4px; background: var(--bg-card); color: var(--text); cursor: pointer; font-size: 12px; }
.update-btn.primary { background: var(--accent); color: #fff; border-color: var(--accent); }
.update-progress { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); display: flex; align-items: center; justify-content: center; z-index: 9999; }
.update-progress-inner { background: var(--bg-card); padding: 30px 40px; border-radius: 8px; text-align: center; color: var(--text); max-width: 400px; }
.update-progress-inner h3 { margin: 0 0 10px; }
.update-progress-inner p { margin: 0 0 15px; color: var(--text-muted); font-size: 13px; }
.update-spinner { width: 30px; height: 30px; border: 3px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin 1s linear infinite; margin: 0 auto; }
@keyframes spin { to { transform: rotate(360deg); } }
.site-footer { text-align: center; padding: 16px 20px; font-size: 11px; color: var(--text-muted); border-top: 1px solid var(--border); margin-top: 24px; } .site-footer { text-align: center; padding: 16px 20px; font-size: 11px; color: var(--text-muted); border-top: 1px solid var(--border); margin-top: 24px; }
</style> </style>
</body> </body>
+49
View File
@@ -14,7 +14,9 @@
<span id="view-mode-badge" class="badge">View Mode</span> <span id="view-mode-badge" class="badge">View Mode</span>
</div> </div>
<div class="view-actions"> <div class="view-actions">
<button id="dl-btn" class="view-btn" onclick="downloadFile()">Download</button>
<button id="edit-btn" class="view-btn" onclick="toggleEdit()">Edit</button> <button id="edit-btn" class="view-btn" onclick="toggleEdit()">Edit</button>
<button id="delete-btn" class="view-btn danger" onclick="deleteViewFile()">Delete</button>
<button id="save-btn" class="view-btn primary" style="display:none;" onclick="saveFile()">Save</button> <button id="save-btn" class="view-btn primary" style="display:none;" onclick="saveFile()">Save</button>
<button id="cancel-btn" class="view-btn" style="display:none;" onclick="cancelEdit()">Cancel</button> <button id="cancel-btn" class="view-btn" style="display:none;" onclick="cancelEdit()">Cancel</button>
</div> </div>
@@ -106,6 +108,53 @@ function cancelEdit() {
badge.classList.remove('edit'); badge.classList.remove('edit');
} }
async function deleteViewFile() {
const name = filePath.split('/').pop();
if (!confirm(`Delete "${name}"? This cannot be undone.`)) return;
try {
const form = new FormData();
form.append('path', filePath);
const resp = await csrfFetch('/api/files/delete', { method: 'POST', body: form });
const data = await resp.json();
if (data.success) {
window.close();
} else {
document.getElementById('view-error').textContent = 'Delete failed: ' + (data.error || 'Unknown');
document.getElementById('view-error').style.display = 'block';
}
} catch (e) {
document.getElementById('view-error').textContent = 'Delete failed: ' + e.message;
document.getElementById('view-error').style.display = 'block';
}
}
async function downloadFile() {
try {
const form = new FormData();
form.append('path', filePath);
const resp = await csrfFetch('/api/files/download', { method: 'POST', body: form });
const data = await resp.json();
if (!data.success) {
document.getElementById('view-error').textContent = 'Error: ' + (data.error || 'Download failed');
document.getElementById('view-error').style.display = 'block';
return;
}
const byteChars = atob(data.content);
const bytes = new Uint8Array(byteChars.length);
for (let i = 0; i < byteChars.length; i++) bytes[i] = byteChars.charCodeAt(i);
const blob = new Blob([bytes]);
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url; a.download = data.filename;
document.body.appendChild(a); a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} catch (e) {
document.getElementById('view-error').textContent = 'Request failed: ' + e.message;
document.getElementById('view-error').style.display = 'block';
}
}
async function saveFile() { async function saveFile() {
const saveBtn = document.getElementById('save-btn'); const saveBtn = document.getElementById('save-btn');
const success = document.getElementById('view-success'); const success = document.getElementById('view-success');
+267 -129
View File
@@ -3,49 +3,79 @@
{% block content %} {% block content %}
<div class="page-header"> <div class="page-header">
<h1>File Browser</h1> <h1>File Manager</h1>
<p>Browse server files via SSH</p> <p>Browse, edit, upload, and download server files</p>
</div> </div>
<div class="card"> <div class="fm-layout">
<div class="card-body"> <div class="fm-panel">
<div class="fb-toolbar"> <div class="fm-toolbar">
<div class="fb-breadcrumb" id="fb-breadcrumb"></div> <select id="fm-pod-select" onchange="selectPod()" style="padding:6px 8px;background:var(--bg-card);color:var(--text);border:1px solid var(--border);border-radius:4px;font-size:12px;max-width:180px;">
<div class="fb-actions"> <option value="">Loading...</option>
<button id="fb-refresh-btn" class="fb-btn">Refresh</button> </select>
</div> <span style="flex:1;"></span>
<input type="file" id="fm-upload-input" style="display:none;" onchange="uploadFile()">
<button class="fm-btn" onclick="document.getElementById('fm-upload-input').click()">&#8682; Upload</button>
<button class="fm-btn" onclick="loadFiles(currentPath)">&#8635; Refresh</button>
</div> </div>
<div id="fb-error" class="error-banner danger" style="display:none;"></div> <div class="fm-breadcrumb" id="fm-breadcrumb"></div>
<div id="fb-file-list" class="fb-file-list"></div> <div id="fm-error" class="error-banner danger" style="display:none;"></div>
<div id="fm-file-list" class="fm-file-list"></div>
</div>
<div class="fm-viewer" id="fm-viewer">
<div id="fm-viewer-empty" class="fm-viewer-empty">Select a file to view or edit</div>
<div id="fm-viewer-toolbar" class="fm-viewer-toolbar" style="display:none;">
<span id="fm-viewer-name" style="font-size:13px;color:var(--text);"></span>
<span style="flex:1;"></span>
<button class="fm-btn" onclick="toggleEdit()" id="fm-edit-btn">&#9998; Edit</button>
<button class="fm-btn" onclick="saveFile()" id="fm-save-btn" style="display:none;">&#128190; Save</button>
<button class="fm-btn" onclick="cancelEdit()" id="fm-cancel-btn" style="display:none;">Cancel</button>
<button class="fm-btn" onclick="downloadCurrent()">&#128229; Download</button>
<button class="fm-btn danger" onclick="deleteCurrent()">&#128465; Delete</button>
</div>
<pre id="fm-viewer-content" class="fm-viewer-content" style="display:none;"></pre>
<textarea id="fm-editor-content" class="fm-editor-content" style="display:none;" spellcheck="false"></textarea>
<div id="fm-viewer-status" class="error-banner success" style="display:none;"></div>
</div> </div>
</div> </div>
<style> <style>
.fb-toolbar { display: flex; justify-content: space-between; align-items: center; padding: 12px; background: var(--bg-hover); border-radius: 6px; margin-bottom: 12px; } .fm-layout { display: grid; grid-template-columns: 340px 1fr; gap: 16px; min-height: calc(100vh - 200px); }
.fb-breadcrumb { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; } .fm-panel { min-height: 0; display: flex; flex-direction: column; }
.fb-breadcrumb span { cursor: pointer; color: var(--primary); font-family: monospace; font-size: 13px; } .fm-toolbar { display: flex; gap: 8px; margin-bottom: 10px; }
.fb-breadcrumb span:hover { text-decoration: underline; } .fm-btn { padding: 6px 12px; background: var(--bg-card); color: var(--text); border: 1px solid var(--border); border-radius: 4px; cursor: pointer; font-size: 12px; white-space: nowrap; }
.fb-breadcrumb .sep { color: var(--text-muted); cursor: default; font-size: 11px; } .fm-btn:hover { background: var(--bg-hover); }
.fb-breadcrumb .sep:hover { text-decoration: none; } .fm-btn.danger { color: var(--danger); border-color: var(--danger); }
.fb-breadcrumb .current { color: var(--text); cursor: default; } .fm-breadcrumb { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; font-size: 12px; margin-bottom: 8px; min-height: 20px; }
.fb-breadcrumb .current:hover { text-decoration: none; } .fm-breadcrumb span { cursor: pointer; color: var(--primary); font-family: monospace; }
.fb-actions { display: flex; gap: 8px; } .fm-breadcrumb span:hover { text-decoration: underline; }
.fb-btn { padding: 6px 14px; background: var(--bg-card); color: var(--text); border: 1px solid var(--border); border-radius: 4px; cursor: pointer; font-size: 13px; } .fm-breadcrumb .sep { color: var(--text-muted); cursor: default; }
.fb-btn:hover { background: var(--bg-hover); } .fm-breadcrumb .sep:hover { text-decoration: none; }
.fb-file-list { } .fm-breadcrumb .current { color: var(--text); cursor: default; }
.fb-item { display: flex; align-items: center; padding: 8px 12px; border-bottom: 1px solid var(--border); cursor: pointer; } .fm-breadcrumb .current:hover { text-decoration: none; }
.fb-item:hover { background: var(--bg-hover); } .fm-file-list { flex: 1; overflow-y: auto; border: 1px solid var(--border); border-radius: 6px; }
.fb-item:last-child { border-bottom: none; } .fm-item { display: flex; align-items: center; padding: 6px 10px; border-bottom: 1px solid var(--border); cursor: pointer; font-size: 12px; }
.fb-icon { width: 24px; text-align: center; margin-right: 8px; font-size: 16px; } .fm-item:hover { background: var(--bg-hover); }
.fb-icon.dir { color: var(--accent); } .fm-item.selected { background: var(--bg-hover); border-left: 3px solid var(--primary); }
.fb-name { flex: 1; font-size: 13px; } .fm-item:last-child { border-bottom: none; }
.fb-name.dir { color: var(--accent); font-weight: 500; cursor: pointer; } .fm-icon { width: 20px; text-align: center; margin-right: 6px; font-size: 14px; flex-shrink: 0; }
.fb-name.file { cursor: pointer; } .fm-icon.dir { color: var(--accent); }
.fb-name:hover { text-decoration: underline; } .fm-fname { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.fb-size { color: var(--text-muted); font-size: 12px; margin-right: 12px; min-width: 70px; text-align: right; } .fm-fname.dir { color: var(--accent); font-weight: 500; }
.fb-date { color: var(--text-muted); font-size: 12px; margin-right: 12px; min-width: 130px; } .fm-fsize { color: var(--text-muted); font-size: 11px; margin-left: 8px; flex-shrink: 0; }
.fb-perms { color: var(--text-muted); font-size: 11px; font-family: monospace; margin-right: 12px; min-width: 80px; } .fm-delete-btn { padding: 2px 6px; background: none; border: none; color: var(--danger); cursor: pointer; font-size: 13px; flex-shrink: 0; }
.fb-empty { padding: 20px; text-align: center; color: var(--text-muted); } .fm-delete-btn:hover { background: var(--bg-hover); border-radius: 3px; }
.fm-empty { padding: 20px; text-align: center; color: var(--text-muted); font-size: 12px; }
.fm-viewer { display: flex; flex-direction: column; border: 1px solid var(--border); border-radius: 6px; min-height: 0; }
.fm-viewer-toolbar { display: flex; align-items: center; gap: 6px; padding: 8px 12px; border-bottom: 1px solid var(--border); background: var(--bg-hover); border-radius: 6px 6px 0 0; }
.fm-viewer-empty { flex: 1; display: flex; align-items: center; justify-content: center; color: var(--text-muted); font-size: 14px; }
.fm-viewer-content { flex: 1; margin: 0; padding: 12px; overflow: auto; font-family: 'Consolas','Courier New',monospace; font-size: 12px; line-height: 1.5; white-space: pre-wrap; word-break: break-all; background: var(--bg); color: var(--text); border: none; border-radius: 0 0 6px 6px; }
.fm-editor-content { flex: 1; padding: 12px; background: var(--bg); color: var(--text); border: none; font-family: 'Consolas','Courier New',monospace; font-size: 12px; line-height: 1.5; resize: none; outline: none; border-radius: 0 0 6px 6px; }
@media (max-width: 768px) {
.fm-layout { grid-template-columns: 1fr; grid-template-rows: auto 1fr; }
.fm-viewer { min-height: 300px; }
}
</style> </style>
{% endblock %} {% endblock %}
@@ -53,118 +83,226 @@
{% block scripts %} {% block scripts %}
<script> <script>
let currentPath = '/srv'; let currentPath = '/srv';
let currentFile = null;
let currentPod = '';
let originalContent = '';
function formatSize(sizeStr) { async function loadPods() {
if (!sizeStr || sizeStr === '-') return ''; const sel = document.getElementById('fm-pod-select');
const bytes = parseInt(sizeStr); try {
if (isNaN(bytes)) return sizeStr; const r = await csrfFetch('/api/files/pods');
const units = ['B', 'KB', 'MB', 'GB', 'TB']; const d = await r.json();
let i = 0; sel.innerHTML = '';
let size = bytes; if (d.success && d.pods) {
while (size >= 1024 && i < units.length - 1) { size /= 1024; i++; } d.pods.forEach(p => { const o = document.createElement('option'); o.value = p; o.textContent = p; sel.appendChild(o); });
return size.toFixed(i === 0 ? 0 : 1) + ' ' + units[i]; }
// Default to fb-deploy pod if available
const fbOpt = Array.from(sel.options).find(o => o.value.includes('fb-deploy'));
if (fbOpt) { fbOpt.selected = true; currentPod = fbOpt.value; }
else if (sel.options.length) { sel.options[0].selected = true; currentPod = sel.options[0].value; }
} catch(e) { sel.innerHTML = '<option>Error loading pods</option>'; }
}
function selectPod() {
currentPod = document.getElementById('fm-pod-select').value;
currentFile = null;
hideViewer();
loadFiles(currentPath);
}
function buildForm(path) {
const f = new FormData();
f.append('path', path);
if (currentPod) f.append('pod', currentPod);
return f;
}
function formatSize(s) {
if (!s || s === '-') return '';
const b = parseInt(s); if (isNaN(b)) return s;
const u = ['B','KB','MB','GB','TB']; let i = 0, sz = b;
while (sz >= 1024 && i < u.length-1) { sz /= 1024; i++; }
return sz.toFixed(i===0?0:1) + ' ' + u[i];
} }
function renderBreadcrumb(path) { function renderBreadcrumb(path) {
const parts = path.split('/').filter(Boolean); const p = path.split('/').filter(Boolean);
let html = '<span onclick="loadFiles(\'/\')">&#128193; /</span>'; let h = '<span onclick="loadFiles(\'/\')">&#128193; /</span>';
let buildPath = ''; let b = '';
for (let i = 0; i < parts.length; i++) { for (let i=0;i<p.length;i++) {
buildPath += '/' + parts[i]; b += '/'+p[i];
const isLast = i === parts.length - 1; h += i===p.length-1
if (isLast) { ? '<span class="sep">/</span><span class="current">'+p[i]+'</span>'
html += `<span class="sep">/</span><span class="current">${parts[i]}</span>`; : '<span class="sep">/</span><span onclick="loadFiles(\''+b.replace(/'/g,"\\'")+'\')">'+p[i]+'</span>';
} else {
html += `<span class="sep">/</span><span onclick="loadFiles('${buildPath.replace(/'/g, "\\'")}')">${parts[i]}</span>`;
}
} }
return html; return h;
} }
function selectFile(path) { currentFile = path; }
async function loadFiles(path) { async function loadFiles(path) {
currentPath = path; currentPath = path; currentFile = null;
const list = document.getElementById('fb-file-list'); document.getElementById('fm-error').style.display = 'none';
const error = document.getElementById('fb-error'); document.getElementById('fm-breadcrumb').innerHTML = renderBreadcrumb(path);
const breadcrumb = document.getElementById('fb-breadcrumb'); const list = document.getElementById('fm-file-list');
error.style.display = 'none'; list.innerHTML = '<div class="fm-empty">Loading...</div>';
list.innerHTML = '<div class="fb-empty">Loading...</div>';
breadcrumb.innerHTML = renderBreadcrumb(path);
try { try {
const form = new FormData(); const f = buildForm(path);
form.append('path', path); const r = await csrfFetch('/api/files/list',{method:'POST',body:f});
const resp = await csrfFetch('/api/files/list', { method: 'POST', body: form }); const d = await r.json();
const data = await resp.json(); if (!d.success) { list.innerHTML = ''; showErr(d.error); return; }
if (!data.success) { const files = (d.files||[]).sort((a,b)=>a.is_dir!==b.is_dir?a.is_dir?-1:1:a.name.localeCompare(b.name));
list.innerHTML = ''; if (!files.length) { list.innerHTML = '<div class="fm-empty">Empty directory</div>'; return; }
error.textContent = 'Error: ' + (data.error || 'Failed to list directory'); let h = '';
error.style.display = 'block'; for (const x of files) {
return; const fp = (path==='/'?'':path)+'/'+x.name;
} const sp = fp.replace(/\\/g,'\\\\').replace(/'/g,"\\'");
const files = data.files || []; const sn = x.name.replace(/\\/g,'\\\\').replace(/'/g,"\\'");
if (files.length === 0) { const icon = x.is_dir ? '&#128193;' : getIcon(x.name);
list.innerHTML = '<div class="fb-empty">Empty directory</div>'; const action = x.is_dir ? `loadFiles('${sp}')` : `openFile('${sp}','${sn}')`;
return; h += `<div class="fm-item" onclick="${action}">
} <span class="fm-icon ${x.is_dir?'dir':''}">${icon}</span>
const sorted = files.sort((a, b) => { <span class="fm-fname ${x.is_dir?'dir':''}">${x.name}</span>
if (a.is_dir !== b.is_dir) return a.is_dir ? -1 : 1; <span class="fm-fsize">${formatSize(x.size)}</span>
return a.name.localeCompare(b.name); <button class="fm-delete-btn" onclick="event.stopPropagation();deleteFile('${sp}','${sn}')" title="Delete">&#128465;</button>
});
let html = '';
for (const f of sorted) {
const icon = f.is_dir ? '&#128193;' : getFileIcon(f.name);
const iconClass = f.is_dir ? 'dir' : '';
const nameClass = f.is_dir ? 'dir' : 'file';
const fullPath = (path === '/' ? '' : path) + '/' + f.name;
const safePath = fullPath.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
const safeName = f.name.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
const clickAction = f.is_dir
? `loadFiles('${safePath}')`
: `viewFile('${safePath}', '${safeName}')`;
html += `<div class="fb-item" onclick="${clickAction}">
<span class="fb-icon ${iconClass}">${icon}</span>
<span class="fb-name ${nameClass}">${f.name}</span>
<span class="fb-perms">${f.perms || ''}</span>
<span class="fb-size">${formatSize(f.size)}</span>
<span class="fb-date">${f.date || ''}</span>
</div>`; </div>`;
} }
list.innerHTML = html; list.innerHTML = h;
} catch (e) { } catch(e) { list.innerHTML = ''; showErr(e.message); }
list.innerHTML = '';
error.textContent = 'Request failed: ' + e.message;
error.style.display = 'block';
}
} }
function getFileIcon(name) { function getIcon(name) {
const icons = {log:'&#128221;',txt:'&#128196;',ini:'&#9881;',cfg:'&#9881;',json:'&#123364;',xml:'&#128196;',yaml:'&#128196;',yml:'&#128196;',sh:'&#9881;',ps1:'&#9881;',bat:'&#9881;',cmd:'&#9881;',zip:'&#128230;',gz:'&#128230;',tar:'&#128230;',sql:'&#128451;',db:'&#128451;',png:'&#127748;',jpg:'&#127748;',jpeg:'&#127748;',gif:'&#127748;',svg:'&#127748;',pdf:'&#128214;',md:'&#128214;',html:'&#127760;',css:'&#127912;',js:'&#128220;',py:'&#128220;'};
return icons[name.split('.').pop().toLowerCase()] || '&#128196;';
}
const textExts = ['log','txt','ini','cfg','json','xml','yaml','yml','sh','ps1','bat','cmd','md','html','css','js','py','conf','env'];
function openFile(path, name) {
currentFile = path;
const ext = name.split('.').pop().toLowerCase(); const ext = name.split('.').pop().toLowerCase();
const icons = { if (!textExts.includes(ext)) { downloadFile(path); return; }
log: '&#128221;', txt: '&#128196;', ini: '&#9881;', cfg: '&#9881;',
json: '&#123364;', xml: '&#128196;', yaml: '&#128196;', yml: '&#128196;', document.getElementById('fm-viewer-empty').style.display = 'none';
sh: '&#9881;', ps1: '&#9881;', bat: '&#9881;', cmd: '&#9881;', document.getElementById('fm-viewer-status').style.display = 'none';
zip: '&#128230;', gz: '&#128230;', tar: '&#128230;', document.getElementById('fm-viewer-content').style.display = 'block';
sql: '&#128451;', db: '&#128451;', sqlite: '&#128451;', document.getElementById('fm-editor-content').style.display = 'none';
png: '&#127748;', jpg: '&#127748;', jpeg: '&#127748;', gif: '&#127748;', svg: '&#127748;', document.getElementById('fm-edit-btn').style.display = 'inline-block';
pdf: '&#128214;', document.getElementById('fm-save-btn').style.display = 'none';
md: '&#128214;', html: '&#127760;', css: '&#127912;', js: '&#128220;', document.getElementById('fm-cancel-btn').style.display = 'none';
py: '&#128220;', document.getElementById('fm-viewer-toolbar').style.display = 'flex';
}; document.getElementById('fm-viewer-name').textContent = name;
return icons[ext] || '&#128196;';
const content = document.getElementById('fm-viewer-content');
content.textContent = 'Loading...';
fetch('/api/files/view?path=' + encodeURIComponent(path) + '&pod=' + encodeURIComponent(currentPod))
.then(r=>r.json()).then(d=>{
if(!d.success){content.textContent='Error: '+(d.error||'Load failed');return;}
originalContent = d.content;
content.textContent = d.content;
}).catch(e=>{content.textContent='Error: '+e.message;});
// Highlight selected file
document.querySelectorAll('.fm-item').forEach(el=>el.classList.remove('selected'));
} }
function viewFile(path, name) { function toggleEdit() {
const ext = name.split('.').pop().toLowerCase(); document.getElementById('fm-viewer-content').style.display = 'none';
const textExts = ['log', 'txt', 'ini', 'cfg', 'json', 'xml', 'yaml', 'yml', 'sh', 'ps1', 'bat', 'cmd', 'md', 'html', 'css', 'js', 'py', 'conf', 'env']; document.getElementById('fm-editor-content').style.display = 'block';
if (textExts.includes(ext)) { document.getElementById('fm-editor-content').value = originalContent;
window.open(`/files/view?path=${encodeURIComponent(path)}`, '_blank'); document.getElementById('fm-editor-content').focus();
} else { document.getElementById('fm-edit-btn').style.display = 'none';
alert('File preview is only available for text files. Download via SSH to view this file.'); document.getElementById('fm-save-btn').style.display = 'inline-block';
} document.getElementById('fm-cancel-btn').style.display = 'inline-block';
} }
document.getElementById('fb-refresh-btn')?.addEventListener('click', () => loadFiles(currentPath)); function cancelEdit() {
document.getElementById('fm-editor-content').style.display = 'none';
document.getElementById('fm-viewer-content').style.display = 'block';
document.getElementById('fm-edit-btn').style.display = 'inline-block';
document.getElementById('fm-save-btn').style.display = 'none';
document.getElementById('fm-cancel-btn').style.display = 'none';
}
async function saveFile() {
if (!currentFile) return;
const content = document.getElementById('fm-editor-content').value;
const btn = document.getElementById('fm-save-btn');
btn.textContent = 'Saving...'; btn.disabled = true;
try {
const f = buildForm(currentFile); f.append('content', content);
const r = await csrfFetch('/api/files/save',{method:'POST',body:f});
const d = await r.json();
if(!d.success){showErr(d.error);return;}
originalContent = content;
document.getElementById('fm-viewer-content').textContent = content;
cancelEdit();
document.getElementById('fm-viewer-status').textContent = 'Saved'; document.getElementById('fm-viewer-status').style.display='block';
setTimeout(()=>document.getElementById('fm-viewer-status').style.display='none',2000);
} catch(e) { showErr(e.message); }
btn.textContent = '💾 Save'; btn.disabled = false;
}
function downloadCurrent() {
if (!currentFile) return;
downloadFile(currentFile);
}
async function deleteCurrent() {
if (!currentFile) return;
const name = currentFile.split('/').pop();
if (!confirm('Delete "'+name+'"? This cannot be undone.')) return;
try {
const f = buildForm(currentFile);
const r = await csrfFetch('/api/files/delete',{method:'POST',body:f});
const d = await r.json();
if(d.success){currentFile=null;document.getElementById('fm-viewer-toolbar').style.display='none';document.getElementById('fm-viewer-content').style.display='none';document.getElementById('fm-viewer-empty').style.display='flex';loadFiles(currentPath);}
else showErr(d.error||'Delete failed');
} catch(e) { showErr(e.message); }
}
async function uploadFile() {
const input = document.getElementById('fm-upload-input');
const file = input.files[0]; if(!file)return;
const f = buildForm(currentPath); f.append('file',file);
try {
const r = await csrfFetch('/api/files/upload',{method:'POST',body:f});
const d = await r.json();
if(d.success){input.value='';loadFiles(currentPath);}
else showErr('Upload: '+(d.error||'Unknown'));
} catch(e) { showErr(e.message); }
}
async function downloadFile(path) {
try {
const f = buildForm(path);
const r = await csrfFetch('/api/files/download',{method:'POST',body:f});
const d = await r.json();
if(!d.success){alert('Download failed: '+(d.error||'Unknown'));return;}
const chars=atob(d.content); const bytes=new Uint8Array(chars.length);
for(let i=0;i<chars.length;i++)bytes[i]=chars.charCodeAt(i);
const blob=new Blob([bytes]),url=URL.createObjectURL(blob);
const a=document.createElement('a');a.href=url;a.download=d.filename;
document.body.appendChild(a);a.click();document.body.removeChild(a);URL.revokeObjectURL(url);
} catch(e) { alert('Download failed: '+e.message); }
}
async function deleteFile(path,name) {
if(!confirm('Delete "'+name+'"? This cannot be undone.'))return;
try {
const f = buildForm(path);
const r = await csrfFetch('/api/files/delete',{method:'POST',body:f});
const d = await r.json();
if(d.success){ if(currentFile===path){currentFile=null;document.getElementById('fm-viewer-toolbar').style.display='none';document.getElementById('fm-viewer-content').style.display='none';document.getElementById('fm-viewer-empty').style.display='flex';} loadFiles(currentPath); }
else showErr(d.error||'Delete failed');
} catch(e) { showErr(e.message); }
}
function showErr(msg) { const e=document.getElementById('fm-error');e.textContent='Error: '+msg;e.style.display='block'; }
function hideErr() { document.getElementById('fm-error').style.display='none'; }
function hideViewer() { document.getElementById('fm-viewer-toolbar').style.display='none'; document.getElementById('fm-viewer-content').style.display='none'; document.getElementById('fm-editor-content').style.display='none'; document.getElementById('fm-viewer-empty').style.display='flex'; }
loadPods();
loadFiles('/srv'); loadFiles('/srv');
</script> </script>
{% endblock %} {% endblock %}