Author SHA1 Message Date
root 83c98ff0b8 Merge main into update/v0.5.0-audit-auth-router (resolved conflicts with ZIP version) 2026-06-26 20:44:40 +02:00
root f2fdf95897 v0.5.0: Add RBAC auth, LLM router, audit logging, output sanitization
- New: auth.py – Role-based access (operator/approver/viewer)
- New: llm_router.py – Configurable primary/fallback provider chain
- New: audit_log.py + audit_query.py – DSGVO-compliant audit trail
- New: sanitize_output() – masks secrets in bot responses
- Updated: bot.py – Integrated auth guards, router, audit logging
- Updated: ollama_client.py – Router-compatible interface
- Updated: CLOWNFISCHSERVER.md – Documentation updated
- Updated: README.md – Documentation updated
2026-06-26 20:41:35 +02:00
13 changed files with 3711 additions and 2300 deletions
+467 -467
View File
@@ -1,467 +1,467 @@
# 🐠 Clownfischserver – Projekt-Kontext # 🐠 Clownfischserver – Projekt-Kontext
> Diese Datei ist der zentrale Wissensspeicher für das Clownfischserver-Projekt. > Diese Datei ist der zentrale Wissensspeicher für das Clownfischserver-Projekt.
> Lade sie in jede KI/Chat-Session um sofort produktiv zu sein. > Lade sie in jede KI/Chat-Session um sofort produktiv zu sein.
> Letzte Aktualisierung: v0.5.0 (30.05.2026) > Letzte Aktualisierung: v0.5.0 (30.05.2026)
> **⚠️ Bewusst entfernt (nicht wieder einbauen!):** Ein „Vault/MCP-Context"-System > **⚠️ Bewusst entfernt (nicht wieder einbauen!):** Ein „Vault/MCP-Context"-System
> (`_get_vault_context`, `MCP_VAULT_URL`, `MCP_API_KEY`) wurde in v0.5.0 komplett > (`_get_vault_context`, `MCP_VAULT_URL`, `MCP_API_KEY`) wurde in v0.5.0 komplett
> entfernt. Es war toter Code, nutzte `verify=False` und schickte Chat-Nachrichten an > entfernt. Es war toter Code, nutzte `verify=False` und schickte Chat-Nachrichten an
> externe Endpoints – ein klarer DSGVO-Verstoß und Widerspruch zum „local-first"-Prinzip. > externe Endpoints – ein klarer DSGVO-Verstoß und Widerspruch zum „local-first"-Prinzip.
> Token-Optimierung über Obsidian gehört NICHT in den Bot. > Token-Optimierung über Obsidian gehört NICHT in den Bot.
--- ---
## Was ist der Clownfischserver? ## Was ist der Clownfischserver?
Ein Open-Source, Telegram-gesteuerter Linux-Server-Manager. Der Admin schreibt dem Bot über Telegram – der Bot versteht, generiert Befehle, erstellt Scripts, verwaltet den Server. Komplett lokal mit Ollama, optional Cloud-Fallback über OpenRouter. Ein Open-Source, Telegram-gesteuerter Linux-Server-Manager. Der Admin schreibt dem Bot über Telegram – der Bot versteht, generiert Befehle, erstellt Scripts, verwaltet den Server. Komplett lokal mit Ollama, optional Cloud-Fallback über OpenRouter.
**Repo:** https://github.com/mehlzoerwer-claude/clownfischserver **Repo:** https://github.com/mehlzoerwer-claude/clownfischserver
**Lizenz:** GPL-3.0 **Lizenz:** GPL-3.0
**Entwickler:** Mehlzoerwer-Claude (Thorsten Matthes) **Entwickler:** Mehlzoerwer-Claude (Thorsten Matthes)
**KI-Assistent:** Claude (Anthropic) – Pair-Programming Partner **KI-Assistent:** Claude (Anthropic) – Pair-Programming Partner
--- ---
## Architektur ## Architektur
``` ```
┌─────────────────────┐ ┌─────────────────────┐
│ Telegram Bot │ │ Telegram Bot │
│ (bot.py) │ │ (bot.py) │
└──────┬──────┬────────┘ └──────┬──────┬────────┘
│ │ │ │
┌─────────────────┤ ├─────────────────┐ ┌─────────────────┤ ├─────────────────┐
▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼
┌────────────────┐ ┌────────────┐ ┌──────────────────┐ ┌────────────────┐ ┌────────────┐ ┌──────────────────┐
│ ollama_client │ │ shell.py │ │ aider_wrapper │ │ ollama_client │ │ shell.py │ │ aider_wrapper │
│ (Dual-Model) │ │ (run_shell)│ │ (Code-Agent) │ │ (Dual-Model) │ │ (run_shell)│ │ (Code-Agent) │
└───────┬────┬────┘ └────────────┘ └──────────────────┘ └───────┬────┬────┘ └────────────┘ └──────────────────┘
│ │ │ │
┌────────┘ └────────┐ ┌────────┘ └────────┐
▼ ▼ ▼ ▼
┌──────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────┐ ┌──────────────┐ ┌──────────────┐
│ Chat-Model│ │ Coder-Model │ │ OpenRouter │ │ Chat-Model│ │ Coder-Model │ │ OpenRouter │
│ (gemma3) │ │(qwen2.5-coder)│ │ (Fallback) │ │ (gemma3) │ │(qwen2.5-coder)│ │ (Fallback) │
└──────────┘ └──────────────┘ └──────────────┘ └──────────┘ └──────────────┘ └──────────────┘
``` ```
**Prinzip:** Freitext = Chat. `/shell` = KI generiert Befehl → Admin bestätigt mit `/ja`. `/code` = Aider erstellt Dateien. `/run` = direkte Shell. **Prinzip:** Freitext = Chat. `/shell` = KI generiert Befehl → Admin bestätigt mit `/ja`. `/code` = Aider erstellt Dateien. `/run` = direkte Shell.
--- ---
## Dateistruktur (19 Dateien, ~3250 Zeilen) ## Dateistruktur (19 Dateien, ~3250 Zeilen)
``` ```
clownfischserver/ clownfischserver/
├── bot/ ├── bot/
│ ├── bot.py # Hauptbot: alle Commands, Auth, Self-Update, Update-Dialog │ ├── bot.py # Hauptbot: alle Commands, Auth, Self-Update, Update-Dialog
│ ├── ollama_client.py # Dual-Model, OpenRouter Fallback, NUM_CTX, Shell-Prompt │ ├── ollama_client.py # Dual-Model, OpenRouter Fallback, NUM_CTX, Shell-Prompt
│ ├── openrouter_client.py # OpenRouter Free Models Client (openrouter/free) │ ├── openrouter_client.py # OpenRouter Free Models Client (openrouter/free)
│ ├── shell.py # run_shell (shlex.quote), execute_command │ ├── shell.py # run_shell (shlex.quote), execute_command
│ ├── aider_wrapper.py # Aider mit --edit-format diff, 600s Timeout │ ├── aider_wrapper.py # Aider mit --edit-format diff, 600s Timeout
│ ├── snapshot.py # tar.gz Snapshots, Workspace, Paketliste, sudo rsync │ ├── snapshot.py # tar.gz Snapshots, Workspace, Paketliste, sudo rsync
│ ├── boot_notify.py # Telegram-Nachricht 120s nach Boot │ ├── boot_notify.py # Telegram-Nachricht 120s nach Boot
│ ├── knock_notify.py # Port-Knocking SSH-Benachrichtigungen │ ├── knock_notify.py # Port-Knocking SSH-Benachrichtigungen
│ └── requirements.txt # python-telegram-bot, requests, python-dotenv │ └── requirements.txt # python-telegram-bot, requests, python-dotenv
├── config/ ├── config/
│ ├── .env.example # Vorlage mit allen Variablen │ ├── .env.example # Vorlage mit allen Variablen
│ └── knockd.conf # Port-Knocking Sequenz (7000→8000→9000) │ └── knockd.conf # Port-Knocking Sequenz (7000→8000→9000)
├── systemd/ ├── systemd/
│ ├── clownfisch.service # Bot-Service (User=clownfish, wird gepatcht) │ ├── clownfisch.service # Bot-Service (User=clownfish, wird gepatcht)
│ └── clownfisch-boot.service # Boot-Notification (oneshot, 120s delay) │ └── clownfisch-boot.service # Boot-Notification (oneshot, 120s delay)
├── install.sh # 8-Schritt Installer mit Modell/CTX-Auswahl ├── install.sh # 8-Schritt Installer mit Modell/CTX-Auswahl
├── README.md # Vollständige Dokumentation ├── README.md # Vollständige Dokumentation
├── LICENSE # GPL-3.0 ├── LICENSE # GPL-3.0
├── .gitignore ├── .gitignore
├── CONTRIBUTING.md ├── CONTRIBUTING.md
└── GITHUB_PROFILE.md └── GITHUB_PROFILE.md
``` ```
--- ---
## Wichtige Konventionen ## Wichtige Konventionen
### Naming ### Naming
- **Service:** `clownfisch.service` (Deutsch, mit "ch") - **Service:** `clownfisch.service` (Deutsch, mit "ch")
- **Linux-User:** Beliebig (z.B. `clownfisch`, `clownfish`, `admin`) – wird aus `MGMT_USER` in `.env` gelesen - **Linux-User:** Beliebig (z.B. `clownfisch`, `clownfish`, `admin`) – wird aus `MGMT_USER` in `.env` gelesen
- **Branding:** Immer "Clownfisch" (Deutsch) - **Branding:** Immer "Clownfisch" (Deutsch)
- **ZIP-Benennung:** `v0.5.0-clownfischserver.zip` - **ZIP-Benennung:** `v0.5.0-clownfischserver.zip`
### Code-Stil ### Code-Stil
- Python 3, keine Type Hints in Funktionssignaturen (außer Optional) - Python 3, keine Type Hints in Funktionssignaturen (außer Optional)
- Logging über `logging` Modul - Logging über `logging` Modul
- Async für alle Telegram-Handler - Async für alle Telegram-Handler
- `safe_reply()` für alle Telegram-Nachrichten (Markdown-Fallback) - `safe_reply()` für alle Telegram-Nachrichten (Markdown-Fallback)
- Fehler werden dem User angezeigt, nie verschluckt - Fehler werden dem User angezeigt, nie verschluckt
### Sicherheits-Regeln ### Sicherheits-Regeln
- Configs (`sshd_config`, `knockd.conf`) NIE überschreiben – nur gezielte Zeilen ändern - Configs (`sshd_config`, `knockd.conf`) NIE überschreiben – nur gezielte Zeilen ändern
- `.env` Permissions: 0600 - `.env` Permissions: 0600
- SSH Host-Keys, `/etc/shadow` NIE in Snapshots - SSH Host-Keys, `/etc/shadow` NIE in Snapshots
- `.env` seit v0.4.12 aus Snapshots excludiert - `.env` seit v0.4.12 aus Snapshots excludiert
- Self-Update: systemd-Services werden mit `MGMT_USER` aus `.env` gepatcht (Regex: `User=\S+`) - Self-Update: systemd-Services werden mit `MGMT_USER` aus `.env` gepatcht (Regex: `User=\S+`)
--- ---
## .env Variablen ## .env Variablen
``` ```
TELEGRAM_BOT_TOKEN=... # Bot-Token von @BotFather TELEGRAM_BOT_TOKEN=... # Bot-Token von @BotFather
TELEGRAM_CHAT_ID=... # Autorisierte Chat-ID (Single-User) TELEGRAM_CHAT_ID=... # Autorisierte Chat-ID (Single-User)
OLLAMA_BASE_URL=http://localhost:11434 OLLAMA_BASE_URL=http://localhost:11434
OLLAMA_MODEL=qwen2.5-coder:7b # Coder-Modell für /shell und /code OLLAMA_MODEL=qwen2.5-coder:7b # Coder-Modell für /shell und /code
OLLAMA_MODEL_FAST=gemma3:4b # Chat-Modell für Freitext OLLAMA_MODEL_FAST=gemma3:4b # Chat-Modell für Freitext
OLLAMA_NUM_CTX=16384 # Context-Window (4096-32768) OLLAMA_NUM_CTX=16384 # Context-Window (4096-32768)
OPENROUTER_API_KEY=sk-or-v1-... # Optional: kostenloser Cloud-Fallback OPENROUTER_API_KEY=sk-or-v1-... # Optional: kostenloser Cloud-Fallback
SNAPSHOT_DIR=/opt/clownfisch-snapshots SNAPSHOT_DIR=/opt/clownfisch-snapshots
SNAPSHOT_METHOD=tar SNAPSHOT_METHOD=tar
INSTALL_DIR=/opt/clownfischserver INSTALL_DIR=/opt/clownfischserver
MGMT_USER=clownfisch # Linux-User (beliebig wählbar) MGMT_USER=clownfisch # Linux-User (beliebig wählbar)
AIDER_WORKDIR=/opt/clownfisch-workspace AIDER_WORKDIR=/opt/clownfisch-workspace
``` ```
--- ---
## Bot-Befehle ## Bot-Befehle
| Befehl | Funktion | | Befehl | Funktion |
|--------|----------| |--------|----------|
| Freitext | Chat mit KI (gemma3 lokal, OpenRouter Fallback) | | Freitext | Chat mit KI (gemma3 lokal, OpenRouter Fallback) |
| `/shell <beschreibung>` | KI generiert Shell-Befehl, non-interaktiv | | `/shell <beschreibung>` | KI generiert Shell-Befehl, non-interaktiv |
| `/ja` | Letzten `/shell` Befehl ausführen (mit Snapshot davor) | | `/ja` | Letzten `/shell` Befehl ausführen (mit Snapshot davor) |
| `/code <aufgabe>` | Aider erstellt Dateien (Smart Prompt: Dateiname wird ergänzt) | | `/code <aufgabe>` | Aider erstellt Dateien (Smart Prompt: Dateiname wird ergänzt) |
| `/run <befehl>` | Direkte Shell, kein KI, kein Bestätigen | | `/run <befehl>` | Direkte Shell, kein KI, kein Bestätigen |
| `/status` | CPU, RAM, Disk, Top-Prozesse | | `/status` | CPU, RAM, Disk, Top-Prozesse |
| `/ssh open [ip]` | SSH via ufw öffnen | | `/ssh open [ip]` | SSH via ufw öffnen |
| `/ssh close [ip]` | SSH via ufw schließen | | `/ssh close [ip]` | SSH via ufw schließen |
| `/snapshot [label]` | Manuell Snapshot erstellen | | `/snapshot [label]` | Manuell Snapshot erstellen |
| `/snapshot keep/delete <n>` | Snapshot markieren/löschen | | `/snapshot keep/delete <n>` | Snapshot markieren/löschen |
| `/snapshots` | Alle Snapshots anzeigen | | `/snapshots` | Alle Snapshots anzeigen |
| `/rollback <name>` | Zu Snapshot zurückkehren (sudo rsync --delete) | | `/rollback <name>` | Zu Snapshot zurückkehren (sudo rsync --delete) |
| `/start` / `/help` | Bot-Info und Befehlsübersicht | | `/start` / `/help` | Bot-Info und Befehlsübersicht |
| ZIP senden | Self-Update mit optionalem OpenRouter-Setup-Dialog | | ZIP senden | Self-Update mit optionalem OpenRouter-Setup-Dialog |
--- ---
## Dual-Model Strategie ## Dual-Model Strategie
| Rolle | Modell | RAM | Aufgabe | | Rolle | Modell | RAM | Aufgabe |
|-------|--------|-----|---------| |-------|--------|-----|---------|
| Coder | qwen2.5-coder:7b | ~4.7GB | `/shell`, `/code`, Befehlsgenerierung | | Coder | qwen2.5-coder:7b | ~4.7GB | `/shell`, `/code`, Befehlsgenerierung |
| Chat | gemma3:4b | ~3.3GB | Freitext, Erklärungen, Übersetzungen | | Chat | gemma3:4b | ~3.3GB | Freitext, Erklärungen, Übersetzungen |
| Fallback | openrouter/free | 0 (Cloud) | Wenn Ollama nicht verfügbar | | Fallback | openrouter/free | 0 (Cloud) | Wenn Ollama nicht verfügbar |
**Shell-Prompt:** Few-Shot mit non-interaktiven Regeln (kein nano/vim/crontab -e, sudo wenn nötig). **Shell-Prompt:** Few-Shot mit non-interaktiven Regeln (kein nano/vim/crontab -e, sudo wenn nötig).
**Chat-Prompt:** Deutsch als Standard, antwortet in Sprache des Nutzers. **Chat-Prompt:** Deutsch als Standard, antwortet in Sprache des Nutzers.
**Explain-Prompt:** Erklärt Befehlsergebnisse auf Deutsch. **Explain-Prompt:** Erklärt Befehlsergebnisse auf Deutsch.
--- ---
## Snapshot-System ## Snapshot-System
**Gesichert:** `/etc`, `/opt/clownfischserver`, `/home`, `/opt/clownfisch-workspace` **Gesichert:** `/etc`, `/opt/clownfischserver`, `/home`, `/opt/clownfisch-workspace`
**Excludiert:** SSH Host-Keys, shadow, `.env`, `__pycache__`, `node_modules` **Excludiert:** SSH Host-Keys, shadow, `.env`, `__pycache__`, `node_modules`
**Paketliste:** `dpkg --get-selections` pro Snapshot als `.packages.txt` **Paketliste:** `dpkg --get-selections` pro Snapshot als `.packages.txt`
**Rollback:** `sudo rsync -av --delete` pro Verzeichnis **Rollback:** `sudo rsync -av --delete` pro Verzeichnis
**Auto-Cleanup:** Max 20 Snapshots, `keep`-markierte bleiben immer **Auto-Cleanup:** Max 20 Snapshots, `keep`-markierte bleiben immer
--- ---
## OpenRouter Integration ## OpenRouter Integration
- **Client:** `openrouter_client.py` mit `openrouter/free` Auto-Router - **Client:** `openrouter_client.py` mit `openrouter/free` Auto-Router
- **Fallback-Trigger:** Ollama Timeout ODER "nicht erreichbar" - **Fallback-Trigger:** Ollama Timeout ODER "nicht erreichbar"
- **Betrifft:** Chat + `/shell` (nicht `/code` – Aider braucht Ollama direkt) - **Betrifft:** Chat + `/shell` (nicht `/code` – Aider braucht Ollama direkt)
- **Setup:** Beim Self-Update fragt Bot "OpenRouter aktivieren?" → Key eingeben → `.env` - **Setup:** Beim Self-Update fragt Bot "OpenRouter aktivieren?" → Key eingeben → `.env`
- **Kosten:** Free Tier: 50 Requests/Tag, 20/Minute, keine Kreditkarte - **Kosten:** Free Tier: 50 Requests/Tag, 20/Minute, keine Kreditkarte
--- ---
## Bekannte Bugs / Einschränkungen ## Bekannte Bugs / Einschränkungen
- `/code` hat keinen OpenRouter-Fallback (Aider spricht nur Ollama) - `/code` hat keinen OpenRouter-Fallback (Aider spricht nur Ollama)
- Kleine Modelle (< 8B) halluzinieren bei Erklärungen - Kleine Modelle (< 8B) halluzinieren bei Erklärungen
- Aider `diff`-Format überfordert kleine Modelle manchmal → Datei wird nicht erstellt - Aider `diff`-Format überfordert kleine Modelle manchmal → Datei wird nicht erstellt
- Shell-Prompt vergisst manchmal `sudo` bei Root-Operationen - Shell-Prompt vergisst manchmal `sudo` bei Root-Operationen
--- ---
## Server-Umgebung ## Server-Umgebung
- **Hoster:** netcup VPS - **Hoster:** netcup VPS
- **OS:** Ubuntu 24.04 LTS - **OS:** Ubuntu 24.04 LTS
- **RAM:** 16GB - **RAM:** 16GB
- **Disk:** 300GB - **Disk:** 300GB
- **IP:** 92.60.38.175 - **IP:** 92.60.38.175
- **Ollama:** qwen2.5-coder:7b + gemma3:4b (oder gemma4:e2b) - **Ollama:** qwen2.5-coder:7b + gemma3:4b (oder gemma4:e2b)
- **Docker:** installiert - **Docker:** installiert
- **SSH:** Port-Knocking via knockd (7000→8000→9000) - **SSH:** Port-Knocking via knockd (7000→8000→9000)
--- ---
## Roadmap ## Roadmap
### v0.5.0 – Sicherheit + Features ### v0.5.0 – Sicherheit + Features
**Security (DSGVO-Pflicht):** **Security (DSGVO-Pflicht):**
- Sensitive Dateien über Telegram blockieren (`.env`, shadow, Keys) - Sensitive Dateien über Telegram blockieren (`.env`, shadow, Keys)
- Output-Sanitizer: API Keys/Tokens in JEDER Bot-Antwort maskieren - Output-Sanitizer: API Keys/Tokens in JEDER Bot-Antwort maskieren
- Log-Sanitizer: Keine Secrets im Audit-Log - Log-Sanitizer: Keine Secrets im Audit-Log
- Audit-Log: Jeder Befehl mit Timestamp (DSGVO Art. 5/32) - Audit-Log: Jeder Befehl mit Timestamp (DSGVO Art. 5/32)
- SHA256-Hash bei Self-Update + Admin-Bestätigung - SHA256-Hash bei Self-Update + Admin-Bestätigung
- `.env` Permissions-Check beim Bot-Start - `.env` Permissions-Check beim Bot-Start
- `bot.log`, `.aider.chat.history.md`, `bash_history` aus Snapshots excluden - `bot.log`, `.aider.chat.history.md`, `bash_history` aus Snapshots excluden
- Rate-Limiting: Max 30 Befehle/Minute - Rate-Limiting: Max 30 Befehle/Minute
- Session-Timeout: Nach 30 Min Inaktivität → 2FA erneut - Session-Timeout: Nach 30 Min Inaktivität → 2FA erneut
- 2FA bei kritischen Aktionen (TOTP/Mail/zweiter Bot) - 2FA bei kritischen Aktionen (TOTP/Mail/zweiter Bot)
- Persönlicher Code-Offset (SECURITY_OFFSET in .env) - Persönlicher Code-Offset (SECURITY_OFFSET in .env)
**Features:** **Features:**
- Snapshot-Scheduling + Export via Telegram - Snapshot-Scheduling + Export via Telegram
- Verschlüsselte Snapshots (SNAPSHOT_PASSWORD) - Verschlüsselte Snapshots (SNAPSHOT_PASSWORD)
- `/logs`, `/docker` - `/logs`, `/docker`
- Port-Knocking Sequenz wählbar - Port-Knocking Sequenz wählbar
- Open Interpreter als Aider-Alternative evaluieren - Open Interpreter als Aider-Alternative evaluieren
**Quick-Win Security:** **Quick-Win Security:**
- Panik-Wort: Admin-definiertes Wort → Bot löscht .env, sperrt alles - Panik-Wort: Admin-definiertes Wort → Bot löscht .env, sperrt alles
- Honeypot-Befehle: Fake-Commands die Eindringlinge verraten - Honeypot-Befehle: Fake-Commands die Eindringlinge verraten
- Selbstzerstörende Nachrichten: Bot löscht eigene Outputs nach X Minuten - Selbstzerstörende Nachrichten: Bot löscht eigene Outputs nach X Minuten
- Rollback-Bombe: 3x falscher 2FA → auto-Rollback + SSH sperren + Alert - Rollback-Bombe: 3x falscher 2FA → auto-Rollback + SSH sperren + Alert
- Dead Man's Switch: Kein Lebenszeichen in 24h → Bot sperrt sich selbst - Dead Man's Switch: Kein Lebenszeichen in 24h → Bot sperrt sich selbst
### v0.6.0 – Multi-Server + Gedächtnis ### v0.6.0 – Multi-Server + Gedächtnis
- Ein Bot steuert mehrere Server - Ein Bot steuert mehrere Server
- Audit-Log / Server-Gedächtnis (server_log.txt) - Audit-Log / Server-Gedächtnis (server_log.txt)
- Chat kann vergangene Aktionen abfragen - Chat kann vergangene Aktionen abfragen
### v0.7.0 – DSGVO-bewusster Backup-Manager ### v0.7.0 – DSGVO-bewusster Backup-Manager
- Verschlüsselte Snapshots (SNAPSHOT_PASSWORD in .env) - Verschlüsselte Snapshots (SNAPSHOT_PASSWORD in .env)
### v0.8.0 – Erweiterte Cloud-API ### v0.8.0 – Erweiterte Cloud-API
- Premium-Modelle auf OpenRouter - Premium-Modelle auf OpenRouter
- Anthropic/OpenAI direkt - Anthropic/OpenAI direkt
- Kosten-Tracking - Kosten-Tracking
### v0.9.0 – Multi-Interface + Advanced Security ### v0.9.0 – Multi-Interface + Advanced Security
**Alternative Interfaces (E2E-verschlüsselt):** **Alternative Interfaces (E2E-verschlüsselt):**
- Matrix/Element Connector (matrix-nio, self-hosted, E2E) - Matrix/Element Connector (matrix-nio, self-hosted, E2E)
- Signal Connector (signal-cli, E2E) - Signal Connector (signal-cli, E2E)
- Web-UI (HTTPS, self-hosted, Let's Encrypt) - Web-UI (HTTPS, self-hosted, Let's Encrypt)
- SSH-CLI (interaktive Shell-Session, kein Messenger nötig) - SSH-CLI (interaktive Shell-Session, kein Messenger nötig)
- E-Mail mit GPG-Verschlüsselung - E-Mail mit GPG-Verschlüsselung
**Advanced Security Features (evaluieren bei v0.8.x Abschluss):** **Advanced Security Features (evaluieren bei v0.8.x Abschluss):**
- Fake-Modus: Falscher 2FA-Code → Bot tut so als ob, führt nichts aus, stiller Alarm - Fake-Modus: Falscher 2FA-Code → Bot tut so als ob, führt nichts aus, stiller Alarm
- Distress-Code: Umgekehrter Offset = "Ich werde gezwungen" → Fake-Modus - Distress-Code: Umgekehrter Offset = "Ich werde gezwungen" → Fake-Modus
- Geo-Fencing: Bot antwortet nur aus erlaubten Ländern/IP-Bereichen - Geo-Fencing: Bot antwortet nur aus erlaubten Ländern/IP-Bereichen
- Buddy-System: Kritische Befehle brauchen Bestätigung von zweitem Admin - Buddy-System: Kritische Befehle brauchen Bestätigung von zweitem Admin
- Canary Token: Unsichtbare Marker-Dateien, Alert bei Zugriff - Canary Token: Unsichtbare Marker-Dateien, Alert bei Zugriff
- Verschlüsselter Rückkanal: Bot-Antworten verschlüsselt über Telegram - Verschlüsselter Rückkanal: Bot-Antworten verschlüsselt über Telegram
- Hardware-Token: USB-Stick als physischer Schlüssel - Hardware-Token: USB-Stick als physischer Schlüssel
**Architektur-Ziel:** **Architektur-Ziel:**
``` ```
[Telegram] ─┐ [Telegram] ─┐
[Matrix] ─┤ [Matrix] ─┤
[Web-UI] ─┼─→ [bot_core.py] → [Ollama/OpenRouter] [Web-UI] ─┼─→ [bot_core.py] → [Ollama/OpenRouter]
[SSH-CLI] ─┤ [SSH-CLI] ─┤
[E-Mail] ─┘ [E-Mail] ─┘
``` ```
Ein Bot, viele Eingänge. Admin wählt was er will. Ein Bot, viele Eingänge. Admin wählt was er will.
### v1.0.0 – Disaster Recovery ### v1.0.0 – Disaster Recovery
### v2.0.0 – Cross-Distribution Server Migration ### v2.0.0 – Cross-Distribution Server Migration
--- ---
## Getestete Modelle ## Getestete Modelle
| Modell | Größe | Rolle | Ergebnis | | Modell | Größe | Rolle | Ergebnis |
|--------|-------|-------|----------| |--------|-------|-------|----------|
| qwen2.5-coder:7b | 4.7GB | Coder | ✅ Beste Wahl für Code | | qwen2.5-coder:7b | 4.7GB | Coder | ✅ Beste Wahl für Code |
| qwen2.5-coder:3b | 1.9GB | Coder | ✅ Funktioniert, schwächer | | qwen2.5-coder:3b | 1.9GB | Coder | ✅ Funktioniert, schwächer |
| gemma3:4b | 3.3GB | Chat | ✅ Gutes Deutsch, schnell | | gemma3:4b | 3.3GB | Chat | ✅ Gutes Deutsch, schnell |
| gemma4:e2b | 7.2GB | Beide | ⚠️ Zu groß für Dual-Setup | | gemma4:e2b | 7.2GB | Beide | ⚠️ Zu groß für Dual-Setup |
| rnj-1:8b | 5.1GB | Coder | ❓ Test ausstehend | | rnj-1:8b | 5.1GB | Coder | ❓ Test ausstehend |
| qwen3.5:4b | – | Coder | ❌ Thinking, zu langsam auf CPU | | qwen3.5:4b | – | Coder | ❌ Thinking, zu langsam auf CPU |
| openrouter/free | Cloud | Fallback | ✅ Nemotron-H, stark | | openrouter/free | Cloud | Fallback | ✅ Nemotron-H, stark |
--- ---
## Wichtige Design-Entscheidungen ## Wichtige Design-Entscheidungen
1. **Local-first:** Cloud ist Opt-in Werkzeug, nicht Abhängigkeit 1. **Local-first:** Cloud ist Opt-in Werkzeug, nicht Abhängigkeit
2. **Kein Classifier:** Freitext = Chat. Befehle explizit per `/shell`, `/run`, `/code` 2. **Kein Classifier:** Freitext = Chat. Befehle explizit per `/shell`, `/run`, `/code`
3. **Bestätigungs-Flow:** `/shell` generiert → Admin prüft → `/ja` führt aus 3. **Bestätigungs-Flow:** `/shell` generiert → Admin prüft → `/ja` führt aus
4. **Beliebiger Username:** MGMT_USER wird überall per Regex eingesetzt 4. **Beliebiger Username:** MGMT_USER wird überall per Regex eingesetzt
5. **Smart `/code` Prompt:** Bot ergänzt Dateiname wenn User keinen nennt 5. **Smart `/code` Prompt:** Bot ergänzt Dateiname wenn User keinen nennt
6. **Snapshot vor destruktiven Aktionen:** Automatisch bei apt install, rm, chmod etc. 6. **Snapshot vor destruktiven Aktionen:** Automatisch bei apt install, rm, chmod etc.
7. **DSGVO by design:** Lokal, keine Daten an Cloud, Snapshots ohne Secrets 7. **DSGVO by design:** Lokal, keine Daten an Cloud, Snapshots ohne Secrets
--- ---
## Security-Analyse (v0.4.13) ## Security-Analyse (v0.4.13)
### Was wir haben ✅ ### Was wir haben ✅
- Chat-ID Auth (Single-User) - Chat-ID Auth (Single-User)
- `.env` mit 0600 Permissions - `.env` mit 0600 Permissions
- SSH Host-Keys + shadow excluded aus Snapshots - SSH Host-Keys + shadow excluded aus Snapshots
- `.env` excluded aus Snapshots (seit v0.4.12) - `.env` excluded aus Snapshots (seit v0.4.12)
- Port-Knocking statt offenes SSH - Port-Knocking statt offenes SSH
- Lokal-first, Cloud opt-in - Lokal-first, Cloud opt-in
- Safe-Reply Markdown-Fallback (kein Crash bei Sonderzeichen) - Safe-Reply Markdown-Fallback (kein Crash bei Sonderzeichen)
### Bekannte Schwachstellen ❌ ### Bekannte Schwachstellen ❌
**Telegram als Angriffsfläche:** **Telegram als Angriffsfläche:**
- Bot-Token im Klartext in `.env` – wer den Server hackt hat den Bot - Bot-Token im Klartext in `.env` – wer den Server hackt hat den Bot
- Telegram Chat-History enthält alle Befehle + Outputs – nicht löschbar vom Bot - Telegram Chat-History enthält alle Befehle + Outputs – nicht löschbar vom Bot
- Telegram API ist NICHT E2E-verschlüsselt – Telegram Inc. kann mitlesen - Telegram API ist NICHT E2E-verschlüsselt – Telegram Inc. kann mitlesen
- Jemand der das Handy entsperrt hat vollen Zugriff - Jemand der das Handy entsperrt hat vollen Zugriff
- `.env` Inhalte können per `/run cat .env` über Telegram geleakt werden - `.env` Inhalte können per `/run cat .env` über Telegram geleakt werden
**Bot-Sicherheit:** **Bot-Sicherheit:**
- Kein Rate-Limiting – Brute-Force auf Befehle möglich - Kein Rate-Limiting – Brute-Force auf Befehle möglich
- Kein Session-Timeout – Bot antwortet 24/7 ohne erneute Auth - Kein Session-Timeout – Bot antwortet 24/7 ohne erneute Auth
- `bot.log` enthält möglicherweise sensible Daten (unverschlüsselt) - `bot.log` enthält möglicherweise sensible Daten (unverschlüsselt)
- `.aider.chat.history.md` loggt alle Code-Prompts im Klartext - `.aider.chat.history.md` loggt alle Code-Prompts im Klartext
- Ollama API auf localhost:11434 hat keine Auth – jeder lokale Prozess kann anfragen - Ollama API auf localhost:11434 hat keine Auth – jeder lokale Prozess kann anfragen
**Snapshots:** **Snapshots:**
- Snapshots enthalten `/home` – SSH Keys, bash_history, private Dateien - Snapshots enthalten `/home` – SSH Keys, bash_history, private Dateien
- Snapshot-Verzeichnis nicht verschlüsselt - Snapshot-Verzeichnis nicht verschlüsselt
- Kein Integrity-Check ob Snapshots manipuliert wurden - Kein Integrity-Check ob Snapshots manipuliert wurden
**Netzwerk:** **Netzwerk:**
- knockd Sequenz steht im Klartext in `knockd.conf` - knockd Sequenz steht im Klartext in `knockd.conf`
- ufw Regeln können über `/run` beliebig geändert werden - ufw Regeln können über `/run` beliebig geändert werden
**Server:** **Server:**
- NOPASSWD sudo – kompromittierter Bot = Root - NOPASSWD sudo – kompromittierter Bot = Root
- `install.sh` lädt Pakete aus dem Internet ohne Signatur-Check - `install.sh` lädt Pakete aus dem Internet ohne Signatur-Check
- Docker Socket zugänglich → Container-Escape möglich - Docker Socket zugänglich → Container-Escape möglich
### Security-Maßnahmen geplant ### Security-Maßnahmen geplant
**v0.5.0 (realistisch umsetzbar):** **v0.5.0 (realistisch umsetzbar):**
1. `.env`/Secrets über Telegram blockieren (Blacklist für sensitive Pfade) 1. `.env`/Secrets über Telegram blockieren (Blacklist für sensitive Pfade)
2. Output-Sanitizer: API Keys/Tokens in JEDER Bot-Antwort maskieren 2. Output-Sanitizer: API Keys/Tokens in JEDER Bot-Antwort maskieren
3. Log-Sanitizer: Keine Secrets im Audit-Log 3. Log-Sanitizer: Keine Secrets im Audit-Log
4. `bot.log` + `.aider.chat.history.md` + `bash_history` aus Snapshots excluden 4. `bot.log` + `.aider.chat.history.md` + `bash_history` aus Snapshots excluden
5. Rate-Limiting: Max 30 Befehle/Minute 5. Rate-Limiting: Max 30 Befehle/Minute
6. Session-Timeout: Nach 30 Min Inaktivität → 2FA erneut nötig 6. Session-Timeout: Nach 30 Min Inaktivität → 2FA erneut nötig
7. 2FA bei kritischen Aktionen (TOTP/Mail/zweiter Bot) 7. 2FA bei kritischen Aktionen (TOTP/Mail/zweiter Bot)
8. Persönlicher Code-Offset (SECURITY_OFFSET in .env) 8. Persönlicher Code-Offset (SECURITY_OFFSET in .env)
9. SHA256-Hash bei Self-Update → Admin bestätigt 9. SHA256-Hash bei Self-Update → Admin bestätigt
10. `.env` Permissions-Check beim Bot-Start (warnen wenn nicht 0600) 10. `.env` Permissions-Check beim Bot-Start (warnen wenn nicht 0600)
11. Audit-Log mit Timestamp für jeden Befehl (DSGVO Art. 5/32) 11. Audit-Log mit Timestamp für jeden Befehl (DSGVO Art. 5/32)
**v0.6.0+ (langfristig):** **v0.6.0+ (langfristig):**
12. Bot-Token Rotation 12. Bot-Token Rotation
13. Verschlüsselte Snapshots (SNAPSHOT_PASSWORD) 13. Verschlüsselte Snapshots (SNAPSHOT_PASSWORD)
14. Integrity-Hashes für Snapshots (Manipulation erkennen) 14. Integrity-Hashes für Snapshots (Manipulation erkennen)
15. Ollama API Auth 15. Ollama API Auth
16. Audit-Log mit Tamper-Protection (Signierung) 16. Audit-Log mit Tamper-Protection (Signierung)
### DSGVO-Regel für Telegram ### DSGVO-Regel für Telegram
`.env` wird NUR angelegt/geändert über SSH. Niemals über Telegram lesbar. `.env` wird NUR angelegt/geändert über SSH. Niemals über Telegram lesbar.
Der Bot BLOCKIERT Befehle die sensitive Dateien über Telegram ausgeben würden. Der Bot BLOCKIERT Befehle die sensitive Dateien über Telegram ausgeben würden.
--- ---
## ZIP bauen – exakte Vorgehensweise ## ZIP bauen – exakte Vorgehensweise
### Voraussetzungen ### Voraussetzungen
- Alle 20 Dateien müssen im Ordner `clownfischserver/` liegen - Alle 20 Dateien müssen im Ordner `clownfischserver/` liegen
- Python-Dateien müssen syntax-geprüft sein - Python-Dateien müssen syntax-geprüft sein
- install.sh muss bash-syntax-geprüft sein - install.sh muss bash-syntax-geprüft sein
### Schritt 1: Syntax-Check (IMMER vor dem ZIP) ### Schritt 1: Syntax-Check (IMMER vor dem ZIP)
```bash ```bash
cd clownfischserver cd clownfischserver
python3 -m py_compile bot/bot.py python3 -m py_compile bot/bot.py
python3 -m py_compile bot/ollama_client.py python3 -m py_compile bot/ollama_client.py
python3 -m py_compile bot/openrouter_client.py python3 -m py_compile bot/openrouter_client.py
python3 -m py_compile bot/shell.py python3 -m py_compile bot/shell.py
python3 -m py_compile bot/snapshot.py python3 -m py_compile bot/snapshot.py
python3 -m py_compile bot/aider_wrapper.py python3 -m py_compile bot/aider_wrapper.py
python3 -m py_compile bot/boot_notify.py python3 -m py_compile bot/boot_notify.py
python3 -m py_compile bot/knock_notify.py python3 -m py_compile bot/knock_notify.py
bash -n install.sh bash -n install.sh
``` ```
### Schritt 2: ZIP erstellen ### Schritt 2: ZIP erstellen
```bash ```bash
cd .. # Eine Ebene über clownfischserver/ cd .. # Eine Ebene über clownfischserver/
zip -r v0.5.0-clownfischserver.zip clownfischserver/ -x "*__pycache__*" "*.pyc" zip -r v0.5.0-clownfischserver.zip clownfischserver/ -x "*__pycache__*" "*.pyc"
``` ```
**WICHTIG:** **WICHTIG:**
- ZIP-Name: `v<version>-clownfischserver-opus.zip` - ZIP-Name: `v<version>-clownfischserver-opus.zip`
- Root-Ordner im ZIP muss `clownfischserver/` heißen (nicht `build/` oder anderer Name) - Root-Ordner im ZIP muss `clownfischserver/` heißen (nicht `build/` oder anderer Name)
- Keine `__pycache__` oder `.pyc` Dateien - Keine `__pycache__` oder `.pyc` Dateien
- Keine `.git/` Ordner - Keine `.git/` Ordner
- Keine `.env` mit echten Credentials - Keine `.env` mit echten Credentials
### Schritt 3: Verifizieren ### Schritt 3: Verifizieren
```bash ```bash
unzip -l v0.5.0-clownfischserver.zip | head -30 unzip -l v0.5.0-clownfischserver.zip | head -30
# Muss zeigen: clownfischserver/bot/bot.py etc. (20 Dateien) # Muss zeigen: clownfischserver/bot/bot.py etc. (20 Dateien)
``` ```
### Schritt 4: Einspielen ### Schritt 4: Einspielen
**Per Telegram:** ZIP an den ClownfischServer Bot senden → Self-Update Dialog **Per Telegram:** ZIP an den ClownfischServer Bot senden → Self-Update Dialog
**Per Server:** `bash install.sh` im entpackten Ordner **Per Server:** `bash install.sh` im entpackten Ordner
### Schritt 5: GitHub Push ### Schritt 5: GitHub Push
```bash ```bash
cd clownfischserver cd clownfischserver
rm -rf .git rm -rf .git
git init git init
git remote add origin https://github.com/mehlzoerwer-claude/clownfischserver.git git remote add origin https://github.com/mehlzoerwer-claude/clownfischserver.git
git add -A git add -A
git commit -m "v0.4.13 – Beschreibung der Änderungen" git commit -m "v0.4.13 – Beschreibung der Änderungen"
git branch -M main git branch -M main
git push -u origin main --force git push -u origin main --force
``` ```
### Dateiliste (20 Dateien, vollständig) ### Dateiliste (20 Dateien, vollständig)
``` ```
clownfischserver/ clownfischserver/
├── .gitignore ├── .gitignore
├── CLOWNFISCHSERVER.md ← diese Datei ├── CLOWNFISCHSERVER.md ← diese Datei
├── CONTRIBUTING.md ├── CONTRIBUTING.md
├── GITHUB_PROFILE.md ├── GITHUB_PROFILE.md
├── LICENSE ├── LICENSE
├── README.md ├── README.md
├── install.sh ├── install.sh
├── bot/ ├── bot/
│ ├── aider_wrapper.py │ ├── aider_wrapper.py
│ ├── boot_notify.py │ ├── boot_notify.py
│ ├── bot.py │ ├── bot.py
│ ├── knock_notify.py │ ├── knock_notify.py
│ ├── ollama_client.py │ ├── ollama_client.py
│ ├── openrouter_client.py │ ├── openrouter_client.py
│ ├── requirements.txt │ ├── requirements.txt
│ ├── shell.py │ ├── shell.py
│ └── snapshot.py │ └── snapshot.py
├── config/ ├── config/
│ ├── .env.example │ ├── .env.example
│ └── knockd.conf │ └── knockd.conf
└── systemd/ └── systemd/
├── clownfisch-boot.service ├── clownfisch-boot.service
└── clownfisch.service └── clownfisch.service
``` ```
### Versions-Bump Checkliste ### Versions-Bump Checkliste
Bei neuer Version diese Stellen aktualisieren: Bei neuer Version diese Stellen aktualisieren:
1. `install.sh` – Banner + Log-Meldung (3x `v0.4.13`) 1. `install.sh` – Banner + Log-Meldung (3x `v0.4.13`)
2. `bot/bot.py` – `cmd_start` Begrüßung + `main()` Log-Meldung 2. `bot/bot.py` – `cmd_start` Begrüßung + `main()` Log-Meldung
3. `README.md` – Badge `Version-0.4.13` + Roadmap "Fertig (v0.1 – v0.4.13)" 3. `README.md` – Badge `Version-0.4.13` + Roadmap "Fertig (v0.1 – v0.4.13)"
4. `CLOWNFISCHSERVER.md` – Header + Dateiliste 4. `CLOWNFISCHSERVER.md` – Header + Dateiliste
5. ZIP-Dateiname 5. ZIP-Dateiname
--- ---
> *"Angefangen als einfacher Telegram-Bot – gewachsen zu einer Vision."* 🐠 > *"Angefangen als einfacher Telegram-Bot – gewachsen zu einer Vision."* 🐠
+53 -53
View File
@@ -1,53 +1,53 @@
# Contributing to Clownfischserver 🐠 # Contributing to Clownfischserver 🐠
Danke dass du mitmachen willst! Hier sind die Regeln: Danke dass du mitmachen willst! Hier sind die Regeln:
## Grundprinzipien ## Grundprinzipien
- **Open Source bleibt Open Source** – GPL-3.0, keine Ausnahmen - **Open Source bleibt Open Source** – GPL-3.0, keine Ausnahmen
- **Lokal first** – keine Cloud-Dependencies, keine externen APIs - **Lokal first** – keine Cloud-Dependencies, keine externen APIs
- **Einfach bleiben** – ein Nutzer, ein Bot, ein Server - **Einfach bleiben** – ein Nutzer, ein Bot, ein Server
- **Sicherheit** – Safety-Check vor jeder Aktion - **Sicherheit** – Safety-Check vor jeder Aktion
## Pull Requests ## Pull Requests
1. Fork das Repo 1. Fork das Repo
2. Branch erstellen: `git checkout -b feature/dein-feature` 2. Branch erstellen: `git checkout -b feature/dein-feature`
3. Änderungen committen 3. Änderungen committen
4. PR öffnen mit Beschreibung was und warum 4. PR öffnen mit Beschreibung was und warum
## Code Style ## Code Style
- Python: PEP8, async/await - Python: PEP8, async/await
- Bash: shellcheck-kompatibel - Bash: shellcheck-kompatibel
- Kommentare auf Deutsch oder Englisch - Kommentare auf Deutsch oder Englisch
- Header in jeder Datei (siehe bestehende Dateien) - Header in jeder Datei (siehe bestehende Dateien)
## Code-Hygiene (wichtig!) ## Code-Hygiene (wichtig!)
- **Kein toter Code** – keine Funktionen/Module die definiert aber nie aufgerufen werden - **Kein toter Code** – keine Funktionen/Module die definiert aber nie aufgerufen werden
- **Keine versteckten Cloud-Calls** – jeder externe Request muss klar ersichtlich und opt-in sein - **Keine versteckten Cloud-Calls** – jeder externe Request muss klar ersichtlich und opt-in sein
- **Niemals `verify=False`** bei HTTPS-Requests - **Niemals `verify=False`** bei HTTPS-Requests
- **Keine User-Eingaben an Dritte** ohne explizites Opt-in (DSGVO by design) - **Keine User-Eingaben an Dritte** ohne explizites Opt-in (DSGVO by design)
- **Klare Conditions** – verschachtelte Ternaries (`A if B else C` innerhalb von `and`-Ketten) vermeiden - **Klare Conditions** – verschachtelte Ternaries (`A if B else C` innerhalb von `and`-Ketten) vermeiden
- Selbst-Review vor jedem Release: macht jede Zeile noch das was sie soll? - Selbst-Review vor jedem Release: macht jede Zeile noch das was sie soll?
## Issues ## Issues
- Bug? → Issue mit Log-Output - Bug? → Issue mit Log-Output
- Feature-Idee? → Issue mit Use-Case Beschreibung - Feature-Idee? → Issue mit Use-Case Beschreibung
- Frage? → Issue oder Discussions - Frage? → Issue oder Discussions
## Was wir suchen ## Was wir suchen
- Distro-Support (getestete Fedora/Arch Fixes) - Distro-Support (getestete Fedora/Arch Fixes)
- Neue Bot-Commands - Neue Bot-Commands
- Bessere Safety-Prompts - Bessere Safety-Prompts
- Dokumentation - Dokumentation
- Tests - Tests
## Was wir NICHT wollen ## Was wir NICHT wollen
- Cloud-Dependencies - Cloud-Dependencies
- Closed-Source Komponenten - Closed-Source Komponenten
- Komplexität die Einsteiger abschreckt - Komplexität die Einsteiger abschreckt
+149
View File
@@ -0,0 +1,149 @@
# DSGVO-Konformität – Clownfischserver v0.5.0
> Dieser Stand bezieht sich auf v0.5.0. Frühere Versionen erfüllen nicht den vollen
> Funktionsumfang. v0.6.0 erweitert um Transport-Verschlüsselung und Backup-Konzept.
Clownfischserver ist als **Gateway für lokal gehostete LLMs in Unternehmens­umgebungen**
positioniert. Datenschutz ist kein Add-on, sondern strukturelle Voraussetzung.
Verantwortlich für die DSGVO-konforme Konfiguration im konkreten Einsatz bleibt
**der Betreiber**. Dieses Dokument beschreibt, welche technischen Maßnahmen die
Software dafür bereitstellt.
---
## Art. 5 DSGVO – Grundsätze der Verarbeitung
### Art. 5 (1) (a) – Rechtmäßigkeit, Verarbeitung nach Treu und Glauben, Transparenz
Jeder privilegierte Vorgang wird im Audit-Trail (`audit.jsonl`) protokolliert:
- Wer hat was wann ausgeführt? (`/shell`, `/code`, `/run`, `/ja`, `/ssh`, `/snapshot`, `/rollback`)
- Welches LLM-Modell hat eine Antwort generiert? (Audit-Event `llm.route`)
- Welche Zugriffe wurden abgelehnt? (`result: denied`)
Operatoren können den Trail jederzeit via `/logs` einsehen
(`bot/audit_query.py`, `cmd_logs` in `bot/bot.py`).
### Art. 5 (1) (b) – Zweckbindung
`/shell` und `/code` benötigen eine explizite Bestätigung durch einen Approver
(`/ja`). Dieser Approval-Flow ist nicht umgehbar: jeder Befehl wird *vor* der
Ausführung als Vorschlag im Chat dargestellt, der ausführende Approver
hinterlässt seinerseits einen Audit-Eintrag (`shell.approval`).
### Art. 5 (1) (c) – Datenminimierung
- Audit-Einträge enthalten **nur die numerische Telegram User-ID** – keine
Klarnamen, keine Telegram-Usernames, keine E-Mail-Adressen.
- Befehlstexte werden auf `AUDIT_MAX_DETAIL_LEN` Zeichen (Default 2000) gekürzt.
Konfigurierbar via `.env`.
- Es findet **keine Telemetrie nach außen** statt. Sämtliche LLM-Calls können
konfigurationsabhängig vollständig on-prem gehalten werden
(`LLM_PRIMARY_PROVIDER=ollama`, `LLM_FALLBACK_PROVIDER=none`).
### Art. 5 (1) (d) – Richtigkeit
Audit-Einträge enthalten Eingaben (`description`, `command`) **und** Ergebnis
(`returncode`, ggf. `stderr`). Falschmeldungen lassen sich gegen den realen
Server­zustand verifizieren.
### Art. 5 (1) (e) – Speicherbegrenzung
`audit_log.prune_old_logs()` läuft beim Bot-Start und entfernt Einträge,
die älter als `AUDIT_RETENTION_DAYS` (Default 90 Tage) sind.
- `AUDIT_RETENTION_DAYS=0` deaktiviert das Pruning bewusst (z. B. für
forensische Anforderungen mit längerer Aufbewahrungspflicht).
- Das Pruning nutzt einen atomic-rename, sodass auch ein Crash während des
Bereinigungslaufs keine Audit-Lücken erzeugt.
### Art. 5 (1) (f) – Integrität und Vertraulichkeit
- Audit-Datei wird nach jedem Append auf `0600` gesetzt (nur Eigentümer
lesbar/schreibbar). Auf Windows-Filesystemen ohne POSIX-Permissions wird
der Schreibvorgang nicht blockiert, sondern lediglich geloggt – Produktion
läuft per `install.sh` auf Linux.
- Sämtliche LLM-Kommunikation kann ausschließlich lokal stattfinden
(Ollama via `127.0.0.1:11434`). OpenRouter-Fallback ist **opt-in**.
---
## Art. 32 DSGVO – Sicherheit der Verarbeitung
### Art. 32 (1) (a) – Pseudonymisierung
Audit-Einträge speichern numerische User-IDs, keine Namen oder Handles.
Die Zuordnung User-ID → Person verbleibt beim Betreiber, außerhalb der Software.
### Art. 32 (1) (a) – Verschlüsselung
- **In v0.5.0 nicht enthalten**: Die Audit-Datei liegt unverschlüsselt im
Filesystem. Schutz erfolgt ausschließlich über Dateisystem-Permissions
(`0600`, `MGMT_USER`).
- **Plan für v0.6.0**: HTTPS-only Webhook-Endpoint (Telegram-Bot ist
derzeit Long-Polling), at-rest-Encryption der Audit-Datei.
### Art. 32 (1) (b) – Vertraulichkeit, Integrität, Verfügbarkeit
- **Rollenbasierter Zugriff** (`bot/auth.py`):
- `operator` – darf Befehle vorschlagen, ausführen, Code generieren,
SSH-Firewall steuern, Snapshots verwalten, Rollback fahren.
- `approver` – darf vorgeschlagene Befehle bestätigen (`/ja`).
- `viewer` – darf Status und Snapshots einsehen, im Chat lesen.
- Inheritance: operator ⊃ approver ⊃ viewer.
- Jeder Endpunkt im Bot prüft die Rolle explizit; ein nicht autorisierter
Zugriff wird abgelehnt **und** als `result: denied` im Audit protokolliert.
- Verfügbarkeit: Bot läuft als `systemd`-Service (`clownfisch`); Boot-Notify-
Service informiert beim Neustart.
### Art. 32 (1) (c) – Wiederherstellbarkeit
`bot/snapshot.py` erstellt automatisch Snapshots vor potenziell zerstörerischen
Operationen (`/code`, ZIP-Upload, schreibende `/shell`-Befehle). `/rollback`
stellt einen Snapshot wieder her – ebenfalls per Operator-Rolle abgesichert.
### Art. 32 (1) (d) – Verfahren zur Überprüfung
Tests unter `tests/`:
- `test_auth.py` – Rollenmodell + Backwards-Compat
- `test_audit_log.py` – Schreibverhalten, Pruning, Datenminimierung
- `test_audit_query.py` – Filterlogik, Format
- `test_llm_router.py` – Routing-Verhalten, Audit-Hooks
`tests/_smoke.py`, `tests/_smoke_router.py`, `tests/_smoke_query.py` sind
standalone-Skripte für Einsatz ohne pytest.
---
## Was Clownfischserver **nicht** automatisch erledigt
Diese Punkte verbleiben beim Betreiber:
- **Auftragsverarbeitungs-Vertrag** mit OpenRouter (falls Fallback aktiviert).
OpenRouter-Server stehen außerhalb der EU – aktiviere den Fallback nicht
für Daten mit Personenbezug.
- **Verzeichnis von Verarbeitungstätigkeiten** (Art. 30 DSGVO).
- **Datenschutz-Folgenabschätzung** bei großvolumiger Personendaten­verarbeitung
durch das gehostete LLM.
- **Backup-Strategie** für die Audit-Datei (in v0.6.0 geplant).
- **Schulung der Operatoren** im Umgang mit dem `/shell`-Approval-Flow.
---
## Kurz: Welche `.env`-Variablen sind DSGVO-relevant?
| Variable | Effekt |
|---|---|
| `CLOWNFISCH_OPERATORS` / `_APPROVERS` / `_VIEWERS` | Rollenzuweisung, Art. 32 (1) (b) |
| `AUDIT_LOG_PATH` | Pfad zur Audit-Datei (sollte auf verschlüsseltem Volume liegen) |
| `AUDIT_RETENTION_DAYS` | Speicherbegrenzung, Art. 5 (1) (e) |
| `AUDIT_MAX_DETAIL_LEN` | Datenminimierung, Art. 5 (1) (c) |
| `LLM_PRIMARY_PROVIDER=ollama` | On-prem-LLM, keine Cloud-Übertragung |
| `LLM_FALLBACK_PROVIDER=none` | Cloud-Fallback explizit deaktivieren |
| `OPENROUTER_API_KEY` | nur setzen wenn AV-Vertrag mit OpenRouter besteht |
---
**Stand:** Juni 2026 · v0.5.0 · Mehlzoerwer-Claude
+508 -436
View File
@@ -1,436 +1,508 @@
# 🐠 Clownfischserver # 🐠 Clownfischserver
> *Wie der Clownfisch in seiner Anemone lebt – geschützt, autonom, und beißt überraschend hart.* > *Wie der Clownfisch in seiner Anemone lebt – geschützt, autonom, und beißt überraschend hart.*
Ein selbst-hostbarer, KI-gestützter Server-Manager der ausschließlich über Telegram kommuniziert. Kein Dashboard, kein Web-UI, keine Cloud. Nur du und dein Server – über eine Chat-Nachricht. Ein selbst-hostbarer, KI-gestützter Server-Manager der ausschließlich über Telegram kommuniziert. Kein Dashboard, kein Web-UI, keine Cloud. Nur du und dein Server – über eine Chat-Nachricht.
![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg) ![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)
![Platform: Linux](https://img.shields.io/badge/Platform-Linux-red.svg) ![Platform: Linux](https://img.shields.io/badge/Platform-Linux-red.svg)
![Version](https://img.shields.io/badge/Version-0.5.0-green.svg) ![Version](https://img.shields.io/badge/Version-0.5.0-green.svg)
![Status](https://img.shields.io/badge/Status-Active%20Development-yellow.svg) ![Status](https://img.shields.io/badge/Status-Active%20Development-yellow.svg)
--- ---
## 🐟 Warum "Clownfisch"? ## 🐟 Warum "Clownfisch"?
Der Clownfisch lebt in seiner Anemone – einem der wenigen Orte im Ozean die für andere Fische tödlich sind. Er verlässt sie kaum, schützt sie aktiv, und fühlt sich darin vollkommen sicher. Der Clownfisch lebt in seiner Anemone – einem der wenigen Orte im Ozean die für andere Fische tödlich sind. Er verlässt sie kaum, schützt sie aktiv, und fühlt sich darin vollkommen sicher.
Genauso lebt der Clownfischserver **in seinem Server** (seiner Anemone): Genauso lebt der Clownfischserver **in seinem Server** (seiner Anemone):
- Er schirmt alles ab was nicht sein muss - Er schirmt alles ab was nicht sein muss
- SSH bleibt standardmäßig zu – nur wer das richtige Klopfmuster kennt kommt rein - SSH bleibt standardmäßig zu – nur wer das richtige Klopfmuster kennt kommt rein
- Die KI entscheidet was sicher ist und was nicht - Die KI entscheidet was sicher ist und was nicht
- Und wie der echte Clownfisch: **beißt er überraschend hart wenn nötig** 🐠 - Und wie der echte Clownfisch: **beißt er überraschend hart wenn nötig** 🐠
--- ---
## Was ist das? ## Was ist das?
Clownfischserver verwandelt einen Linux-Server in einen vollautonomen, Telegram-gesteuerten Assistenten. Du schreibst ihm in natürlicher Sprache – er versteht, generiert Befehle, erstellt Scripts, und verwaltet deinen Server. Clownfischserver verwandelt einen Linux-Server in einen vollautonomen, Telegram-gesteuerten Assistenten. Du schreibst ihm in natürlicher Sprache – er versteht, generiert Befehle, erstellt Scripts, und verwaltet deinen Server.
Das Ziel: **Server-Administration so einfach wie eine Chat-Nachricht.** Heute ein Server, morgen eine ganze Farm. Das Ziel: **Server-Administration so einfach wie eine Chat-Nachricht.** Heute ein Server, morgen eine ganze Farm.
**Kein SCP. Kein Dashboard. Kein Cloud-Zwang. Nur Telegram.** **Kein SCP. Kein Dashboard. Kein Cloud-Zwang. Nur Telegram.**
--- ---
## Features ## Features
- 🤖 **Telegram Bot** als primäres Interface – von überall, auch vom Handy - 🤖 **Telegram Bot** als primäres Interface – von überall, auch vom Handy
- 🧠 **Dual-Model KI** – Code-Modell (qwen2.5-coder) für Befehle + Chat-Modell (gemma3) für Konversation - 🧠 **Dual-Model KI** – Code-Modell (qwen2.5-coder) für Befehle + Chat-Modell (gemma3) für Konversation
- 🔧 **`/shell` + `/ja`** – KI generiert Shell-Befehle, du bestätigst vor der Ausführung - 🔧 **`/shell` + `/ja`** – KI generiert Shell-Befehle, du bestätigst vor der Ausführung
- 🛠️ **`/code` + Aider** – autonome Code- und Script-Generierung direkt auf dem Server - 🛠️ **`/code` + Aider** – autonome Code- und Script-Generierung direkt auf dem Server
- 💬 **Natürlicher Chat** – Fragen stellen, Erklärungen bekommen, übersetzen lassen - 💬 **Natürlicher Chat** – Fragen stellen, Erklärungen bekommen, übersetzen lassen
- 📸 **Automatische Snapshots** vor destruktiven Aktionen (tar.gz mit Keep/Unkeep + Paketliste) - 📸 **Automatische Snapshots** vor destruktiven Aktionen (tar.gz mit Keep/Unkeep + Paketliste)
- 🔐 **Port-Knocking SSH** als sicherer Backup-Zugang (knockd) mit Telegram-Benachrichtigung - 🔐 **Port-Knocking SSH** als sicherer Backup-Zugang (knockd) mit Telegram-Benachrichtigung
- 🔔 **Benachrichtigungen** – SSH-Zugang, Server-Boot, Knock-Versuche via Telegram - 🔔 **Benachrichtigungen** – SSH-Zugang, Server-Boot, Knock-Versuche via Telegram
- 📦 **Self-Update via Telegram** – ZIP an den Bot schicken, fertig (inkl. systemd-Services) - 📦 **Self-Update via Telegram** – ZIP an den Bot schicken, fertig (inkl. systemd-Services)
- ☁️ **OpenRouter Fallback** – kostenlose Cloud-Modelle als Backup wenn Ollama nicht verfügbar - ☁️ **OpenRouter Fallback** – kostenlose Cloud-Modelle als Backup wenn Ollama nicht verfügbar
- 👤 **Eigener User** – beliebiger Name, passwordless sudo, wird überall korrekt eingesetzt - 👥 **Team-Rollen** *(v0.5.0)* – `operator` / `approver` / `viewer` mit Inheritance, env-gesteuert
- 🌍 **Mehrsprachig** – antwortet in der Sprache in der du schreibst - 📜 **Audit-Trail** *(v0.5.0)* – jeder privilegierte Vorgang in `audit.jsonl`, abfragbar via `/logs`, Retention konfigurierbar
- 🐧 **Multi-Distro** – Debian, Ubuntu, Fedora, Arch (Installer) - 🔀 **LLM-Router** *(v0.5.0)* – Primary/Fallback-Chain via `LLM_PRIMARY_PROVIDER` etc.; pro Provider eigenes Kontextfenster
- 🔒 **DSGVO by design** – lokal ist Standard, Cloud ist Opt-in - 👤 **Eigener User** – beliebiger Name, passwordless sudo, wird überall korrekt eingesetzt
- 🌍 **Mehrsprachig** – antwortet in der Sprache in der du schreibst
--- - 🐧 **Multi-Distro** – Debian, Ubuntu, Fedora, Arch (Installer)
- 🔒 **DSGVO by design** – lokal ist Standard, Cloud ist Opt-in (siehe [DSGVO.md](DSGVO.md))
## Schnellstart
---
```bash
# Frisches Ubuntu/Debian – als root: ## For Enterprise Teams (v0.5.0)
wget https://github.com/mehlzoerwer-claude/clownfischserver/archive/refs/heads/main.zip
unzip main.zip && cd clownfischserver-main Clownfischserver v0.5.0 ist als **Gateway für Teams mit lokal gehosteten
bash install.sh LLMs** positioniert. Wenn ihr Claude Opus, Qwen 32B oder Gemma 4 auf eigener
``` Hardware betreibt, gibt euch v0.5.0:
Der Installer führt dich durch alles – Schritt für Schritt, mit Erklärungen. ### Rollenbasierte Zugriffskontrolle
--- Drei Rollen mit Inheritance (`operator` ⊃ `approver` ⊃ `viewer`):
## Installation ```dotenv
# .env
### Was du brauchst CLOWNFISCH_OPERATORS=12345,67890 # dürfen /shell /code /run /ssh /ja /snapshot /rollback
CLOWNFISCH_APPROVERS=11111 # dürfen /ja (Bestätigungen)
- Frischer Ubuntu 22/24 oder Debian 12/13 VPS (min. 8GB RAM empfohlen, 20GB Disk) CLOWNFISCH_VIEWERS=22222,33333 # dürfen /status /snapshots /help + Chat
- Root SSH-Zugang für die Installation ```
- Ein Telegram-Account (5 Minuten für Bot-Setup)
Wer keine Rolle hat, wird abgelehnt – inklusive Audit-Eintrag mit
### RAM-Empfehlung `result: denied`. Backwards-kompatibel: ohne Rollen-Vars wird die alte
`TELEGRAM_CHAT_ID` automatisch zu `operator`.
| RAM | Coder-Modell | Chat-Modell | Gesamt ca. |
|-----|-------------|-------------|------------| ### Audit-Trail nach DSGVO Art. 5 + 32
| 8-12 GB | qwen2.5-coder:3b | gemma3:1b | ~3 GB |
| 16+ GB | qwen2.5-coder:7b | gemma3:4b | ~8 GB | Jeder Vorgang wird in `audit.jsonl` als JSONL-Eintrag protokolliert:
### Der Installer ```jsonl
{"ts":"2026-06-04T14:21:03+00:00","user_id":"12345","action":"shell.execute","result":"ok","role":"operator","details":{"command":"systemctl restart nginx","returncode":0}}
``` {"ts":"2026-06-04T14:21:07+00:00","action":"llm.route","result":"hit","details":{"tier":"primary","provider":"ollama","model":"qwen2.5-coder:7b","method":"chat"}}
[1/8] Systemcheck → RAM, Disk, Distro-Erkennung ```
[2/8] Pakete → alles Nötige mit Spinner
[3/8] User einrichten → eigener User oder vorhandenen nutzen Operatoren fragen den Trail direkt aus Telegram ab:
[4/8] SSH + Firewall → Port-Knocking, ufw, SSH bleibt offen
[5/8] Ollama → Dual-Model KI-Setup (Coder + Chat) ```text
[6/8] Python + Aider → Bot-Umgebung + Code-Agent /logs # letzte 20 Einträge
[7/8] Telegram → geführtes Bot-Setup mit BotFather /logs user 12345 days 7 # User-Aktivität, letzte 7 Tage
[8/8] Service starten → systemd + Boot-Notification /logs prefix shell. result error
``` /logs action llm.route limit 50
```
### Update (wenn bereits installiert)
Retention via `AUDIT_RETENTION_DAYS` (Default 90 Tage, beim Bot-Start automatisch).
```bash
bash install.sh ### Konfigurierbares LLM-Routing
# → erkennt laufenden Service
# → [1] Update [2] Neuinstallation [3] Abbrechen Primary/Fallback-Chain via Env – kein Auto-Selection, keine Halluzinationen:
```
```dotenv
Oder noch einfacher: **ZIP direkt an den Bot schicken** – Self-Update! # Primary: lokal, sensitive Daten bleiben on-prem
LLM_PRIMARY_PROVIDER=ollama
--- LLM_PRIMARY_MODEL=qwen2.5-coder:7b
LLM_PRIMARY_NUM_CTX=65536 # z. B. Gemma 4 27B braucht 64K+
## Nutzung
# Fallback nur für non-sensitive Tasks
### Bot-Befehle LLM_FALLBACK_PROVIDER=openrouter
LLM_FALLBACK_MODEL=deepseek/deepseek-r1:free
| Befehl | Beschreibung |
|--------|-------------| # Fallback komplett deaktivieren:
| `/shell <beschreibung>` | KI generiert Shell-Befehl aus natürlicher Sprache | # LLM_FALLBACK_PROVIDER=none
| `/ja` | Letzten vorgeschlagenen Befehl ausführen | ```
| `/code <aufgabe>` | Aider erstellt/bearbeitet Code und Scripts |
| `/run <befehl>` | Direkte Shell – kein Ollama, kein Bestätigen | Routable Errors (Timeout, Connection-Refused) lösen Fallback aus; harte
| `/status` | CPU, RAM, Disk, Top-Prozesse | Fehler (JSON-Parse, Bad API Key) propagieren – ohne stille Modellwechsel.
| `/snapshots` | Alle Snapshots anzeigen |
| `/snapshot [label]` | Manuell Snapshot erstellen | ### Vollständige Compliance-Dokumentation
| `/snapshot keep <n>` | Snapshot als wichtig markieren |
| `/snapshot delete <n>` | Snapshot löschen | Siehe **[DSGVO.md](DSGVO.md)** – aufgeschlüsselt nach Art. 5 + 32 mit
| `/rollback <n>` | Zu einem Snapshot zurückkehren | Referenzen auf den konkreten Code.
| `/ssh open [ip]` | SSH via ufw öffnen (für alle oder eine IP) |
| `/ssh close [ip]` | SSH wieder sperren | ---
| `/start` / `/help` | Bot-Info und Befehlsübersicht |
## Schnellstart
### Freitext-Chat
```bash
Einfach schreiben – ohne Befehl. Der Bot antwortet als Chat-Partner: # Frisches Ubuntu/Debian – als root:
wget https://github.com/mehlzoerwer-claude/clownfischserver/archive/refs/heads/main.zip
``` unzip main.zip && cd clownfischserver-main
"Was ist ein Reverse Proxy?" bash install.sh
"Übersetze das ins Englische: ..." ```
"Erkläre mir den Unterschied zwischen apt und snap"
"Welche Services laufen gerade auf meinem Server?" Der Installer führt dich durch alles – Schritt für Schritt, mit Erklärungen.
```
---
### Workflow: `/shell` + `/ja`
## Installation
```
Du: /shell zeig mir die größten Dateien auf dem Server ### Was du brauchst
Bot: 🔧 Vorgeschlagener Befehl:
du -ah / | sort -rh | head -20 - Frischer Ubuntu 22/24 oder Debian 12/13 VPS (min. 8GB RAM empfohlen, 20GB Disk)
→ Mit /ja ausführen oder einfach ignorieren. - Root SSH-Zugang für die Installation
Du: /ja - Ein Telegram-Account (5 Minuten für Bot-Setup)
Bot: ✅ Ergebnis: ...
``` ### RAM-Empfehlung
### Workflow: `/code` | RAM | Coder-Modell | Chat-Modell | Gesamt ca. |
|-----|-------------|-------------|------------|
``` | 8-12 GB | qwen2.5-coder:3b | gemma3:1b | ~3 GB |
Du: /code erstelle ein bash script das alte Logs älter als 30 Tage löscht | 16+ GB | qwen2.5-coder:7b | gemma3:4b | ~8 GB |
Bot: 🛠️ Aider Ergebnis:
✅ Aider Task abgeschlossen ### Der Installer
Applied edit to cleanup-logs.sh
``` ```
[1/8] Systemcheck → RAM, Disk, Distro-Erkennung
### Self-Update [2/8] Pakete → alles Nötige mit Spinner
[3/8] User einrichten → eigener User oder vorhandenen nutzen
ZIP-Datei direkt an den Bot schicken → Bot erstellt Snapshot → installiert Update → startet neu. [4/8] SSH + Firewall → Port-Knocking, ufw, SSH bleibt offen
[5/8] Ollama → Dual-Model KI-Setup (Coder + Chat)
--- [6/8] Python + Aider → Bot-Umgebung + Code-Agent
[7/8] Telegram → geführtes Bot-Setup mit BotFather
## Architektur [8/8] Service starten → systemd + Boot-Notification
```
```
┌─────────────────────┐ ### Update (wenn bereits installiert)
│ Telegram Bot │
│ (bot.py) │ ```bash
└──────┬──────┬────────┘ bash install.sh
│ │ # → erkennt laufenden Service
┌─────────────────┤ ├─────────────────┐ # → [1] Update [2] Neuinstallation [3] Abbrechen
▼ ▼ ▼ ▼ ```
┌────────────────┐ ┌────────────┐ ┌──────────────────┐
│ ollama_client │ │ shell.py │ │ aider_wrapper │ Oder noch einfacher: **ZIP direkt an den Bot schicken** – Self-Update!
│ (Dual-Model) │ │ (run_shell)│ │ (Code-Agent) │
└───────┬────┬────┘ └────────────┘ └──────────────────┘ ---
│ │
┌────────┘ └────────┐ ## Nutzung
▼ ▼
┌──────────┐ ┌──────────────┐ ### Bot-Befehle
│ Chat-Model│ │ Coder-Model │
│ (gemma3) │ │(qwen2.5-coder)│ | Befehl | Beschreibung |
└──────────┘ └──────────────┘ |--------|-------------|
| `/shell <beschreibung>` | KI generiert Shell-Befehl aus natürlicher Sprache |
Weitere Module: | `/ja` | Letzten vorgeschlagenen Befehl ausführen |
snapshot.py – Backup-System (tar.gz, keep/unkeep, auto-cleanup) | `/code <aufgabe>` | Aider erstellt/bearbeitet Code und Scripts |
knock_notify.py – SSH Port-Knocking Alerts | `/run <befehl>` | Direkte Shell – kein Ollama, kein Bestätigen |
boot_notify.py – Server-Neustart Benachrichtigung | `/status` | CPU, RAM, Disk, Top-Prozesse |
``` | `/snapshots` | Alle Snapshots anzeigen |
| `/snapshot [label]` | Manuell Snapshot erstellen |
--- | `/snapshot keep <n>` | Snapshot als wichtig markieren |
| `/snapshot delete <n>` | Snapshot löschen |
## Sicherheit | `/rollback <n>` | Zu einem Snapshot zurückkehren |
| `/ssh open [ip]` | SSH via ufw öffnen (für alle oder eine IP) |
### Port-Knocking | `/ssh close [ip]` | SSH wieder sperren |
| `/start` / `/help` | Bot-Info und Befehlsübersicht |
SSH ist standardmäßig durch ufw blockiert. Zugang via Klopf-Sequenz:
### Freitext-Chat
```bash
# Oeffnen: 7000 -> 8000 -> 9000 Einfach schreiben – ohne Befehl. Der Bot antwortet als Chat-Partner:
knock SERVER_IP 7000 8000 9000
```
# Schliessen: 9000 -> 8000 -> 7000 "Was ist ein Reverse Proxy?"
knock SERVER_IP 9000 8000 7000 "Übersetze das ins Englische: ..."
``` "Erkläre mir den Unterschied zwischen apt und snap"
"Welche Services laufen gerade auf meinem Server?"
Bei jedem Knock kommt eine Telegram-Benachrichtigung mit IP und Zeitstempel. ```
### KI-gestützte Befehlsgenerierung ### Workflow: `/shell` + `/ja`
``` ```
/shell installiere nginx Du: /shell zeig mir die größten Dateien auf dem Server
→ KI generiert: apt install -y nginx Bot: 🔧 Vorgeschlagener Befehl:
→ Gefährlich? Nein → Vorschlag anzeigen du -ah / | sort -rh | head -20
→ /ja zum Ausführen, oder ignorieren → Mit /ja ausführen oder einfach ignorieren.
Du: /ja
/shell lösche alles in /etc Bot: ✅ Ergebnis: ...
→ KI generiert: rm -rf /etc/* ```
→ Gefährlich? JA → Verweigert mit Erklärung
``` ### Workflow: `/code`
Kein Befehl wird ohne Bestätigung ausgeführt. Gefährliche Befehle werden immer verweigert. ```
Du: /code erstelle ein bash script das alte Logs älter als 30 Tage löscht
### Snapshot-System Bot: 🛠️ Aider Ergebnis:
✅ Aider Task abgeschlossen
Vor destruktiven Aktionen automatischer Snapshot (tar.gz). Wichtige Snapshots können mit `/snapshot keep` markiert werden und werden nie automatisch gelöscht. Applied edit to cleanup-logs.sh
```
### Boot-Notification
### Self-Update
Nach jedem Server-Neustart bekommst du eine Telegram-Nachricht mit Status aller Dienste (Clownfisch, Ollama, ufw, SSH, Cron) – nach 2 Minuten, wenn alles hochgefahren ist.
ZIP-Datei direkt an den Bot schicken → Bot erstellt Snapshot → installiert Update → startet neu.
---
---
## Roadmap
## Architektur
### Fertig (v0.1 – v0.5.0)
```
- [x] Basis-Installer mit geführtem Setup (8 Schritte) ┌─────────────────────┐
- [x] Telegram Bot mit Auth Guard (Single-User) │ Telegram Bot │
- [x] Dual-Model KI: Coder (qwen2.5-coder) + Chat (gemma3/gemma4) │ (bot.py) │
- [x] `/shell` + `/ja` – Befehlsgenerierung mit Bestätigung (non-interaktive Befehle) └──────┬──────┬────────┘
- [x] `/code` – Aider Code-Agent für autonome Script-Erstellung (Smart Prompt) │ │
- [x] `/run` – Direkte Shell ohne KI ┌─────────────────┤ ├─────────────────┐
- [x] `/status` – Systemübersicht (CPU, RAM, Disk, Prozesse) ▼ ▼ ▼ ▼
- [x] `/ssh open/close` – ufw-basierter SSH-Zugang ┌────────────────┐ ┌────────────┐ ┌──────────────────┐
- [x] Freitext-Chat mit History (letzte 10 Exchanges) │ ollama_client │ │ shell.py │ │ aider_wrapper │
- [x] Snapshot-System (tar.gz, keep/unkeep, auto-cleanup max 20, Paketliste) │ (Dual-Model) │ │ (run_shell)│ │ (Code-Agent) │
- [x] `/snapshot`, `/snapshots`, `/rollback` (inkl. Workspace) └───────┬────┬────┘ └────────────┘ └──────────────────┘
- [x] Port-Knocking SSH (knockd) mit Telegram-Benachrichtigung │ │
- [x] Boot-Notification nach Server-Neustart (Dienste-Status) ┌────────┘ └────────┐
- [x] Self-Update via Telegram ZIP (inkl. systemd-Services + User-Patch) ▼ ▼
- [x] Update-Modus im Installer (mit MGMT_USER aus .env) ┌──────────┐ ┌──────────────┐
- [x] Multi-Distro Installer (apt/dnf/pacman) │ Chat-Model│ │ Coder-Model │
- [x] Ollama Warmup im Hintergrund (Bot sofort bereit) │ (gemma3) │ │(qwen2.5-coder)│
- [x] **OpenRouter Free Fallback** – kostenlose Cloud-Modelle wenn Ollama nicht verfügbar └──────────┘ └──────────────┘
- [x] Interaktiver Update-Dialog (OpenRouter Key Eingabe via Telegram)
- [x] `OLLAMA_NUM_CTX` konfigurierbar (4K–32K, RAM-basierte Empfehlung im Installer) Weitere Module:
- [x] Safe Telegram Output (Markdown-Fallback bei Parse-Fehlern) snapshot.py – Backup-System (tar.gz, keep/unkeep, auto-cleanup)
- [x] Lange Antworten werden in Teile gesplittet (kein Abschneiden) knock_notify.py – SSH Port-Knocking Alerts
- [x] Mehrsprachig (antwortet in der Sprache des Nutzers) boot_notify.py – Server-Neustart Benachrichtigung
- [x] MGMT_USER Regex-Patch (beliebiger Username funktioniert überall) ```
- [x] Security-Analyse dokumentiert (Schwachstellen + Maßnahmen in CLOWNFISCHSERVER.md)
- [x] DSGVO-Regel: `.env` nur per SSH, nie über Telegram lesbar ---
- [x] Projekt-Kontext-Datei (CLOWNFISCHSERVER.md) für KI-gestütztes Pair-Programming
## Sicherheit
### v0.5.0 – Cleanup & Stabilität (aktuelles Release)
### Port-Knocking
**Bugfixes & Aufräumarbeiten (dieser Release):**
- [x] Totes Vault/MCP-Context-System komplett entfernt (war nie verdrahtet, `verify=False`-Lücke) SSH ist standardmäßig durch ufw blockiert. Zugang via Klopf-Sequenz:
- [x] Privacy-Fix: Chat-Nachrichten gingen via Vault-Suche an externe Endpoints → entfernt
- [x] `/code` Filepath-Logik: fragiler Ternary-Ausdruck sauber umgeschrieben (kein Crash bei leerem Task) ```bash
- [x] Aider-Model-Default vereinheitlicht (zieht sich `OLLAMA_MODEL` aus der Umgebung) # Oeffnen: 7000 -> 8000 -> 9000
- [x] Irreführende „Token-Optimization"-Logs (Anthropic-Kosten/Obsidian) aus dem Start-Log entfernt knock SERVER_IP 7000 8000 9000
**Sicherheit & DSGVO (geplant):** # Schliessen: 9000 -> 8000 -> 7000
- [ ] Sensitive Dateien über Telegram blockieren (`.env`, `shadow`, Keys) knock SERVER_IP 9000 8000 7000
- [ ] Output-Sanitizer: API Keys/Tokens in jeder Bot-Antwort maskieren ```
- [ ] Log-Sanitizer: Keine Secrets im Audit-Log
- [ ] Audit-Log: Jeder Befehl mit Timestamp (DSGVO Art. 5/32) Bei jedem Knock kommt eine Telegram-Benachrichtigung mit IP und Zeitstempel.
- [ ] Self-Update Hardening: SHA256-Hash anzeigen, Admin bestätigt
- [ ] `.env` Permissions-Check beim Bot-Start ### KI-gestützte Befehlsgenerierung
- [ ] `bot.log`, `.aider.chat.history.md`, `bash_history` aus Snapshots excluden
- [ ] Rate-Limiting: Max 30 Befehle/Minute ```
- [ ] Session-Timeout: Nach 30 Min Inaktivität → 2FA erneut nötig /shell installiere nginx
- [ ] 2FA bei kritischen Aktionen (TOTP/Mail/zweiter Bot) → KI generiert: apt install -y nginx
- [ ] Persönlicher Code-Offset (SECURITY_OFFSET in `.env`) → Gefährlich? Nein → Vorschlag anzeigen
→ /ja zum Ausführen, oder ignorieren
**Features:**
- [ ] Snapshot-Scheduling (`/snapshot schedule daily 03:00`) /shell lösche alles in /etc
- [ ] Snapshot-Export als ZIP via Telegram (`/snapshot export <n>`) → KI generiert: rm -rf /etc/*
- [ ] `/logs` – Systemlogs direkt im Bot → Gefährlich? JA → Verweigert mit Erklärung
- [ ] `/docker` – Docker Container Management ```
- [ ] Port-Knocking Sequenz im Installer wählbar
- [ ] Verschlüsselte Snapshots (SNAPSHOT_PASSWORD) Kein Befehl wird ohne Bestätigung ausgeführt. Gefährliche Befehle werden immer verweigert.
- [ ] Open Interpreter als Aider-Alternative evaluieren
### Snapshot-System
**Quick-Win Security:**
- [ ] Panik-Wort: Admin-definiertes Wort → Bot löscht .env, sperrt alles Vor destruktiven Aktionen automatischer Snapshot (tar.gz). Wichtige Snapshots können mit `/snapshot keep` markiert werden und werden nie automatisch gelöscht.
- [ ] Honeypot-Befehle: Fake-Commands die Eindringlinge verraten
- [ ] Selbstzerstörende Nachrichten: Bot löscht eigene Outputs nach X Minuten ### Boot-Notification
- [ ] Rollback-Bombe: 3x falscher 2FA → auto-Rollback + SSH sperren
- [ ] Dead Man's Switch: Kein Lebenszeichen in 24h → Bot sperrt sich Nach jedem Server-Neustart bekommst du eine Telegram-Nachricht mit Status aller Dienste (Clownfisch, Ollama, ufw, SSH, Cron) – nach 2 Minuten, wenn alles hochgefahren ist.
### v0.6.0 – Multi-Server ---
- [ ] Ein Bot steuert mehrere Server ## Roadmap
- [ ] Zentrale Snapshot-Verwaltung
- [ ] Serverpark-Übersicht und -Steuerung ### Fertig (v0.1 – v0.5.0)
- [ ] Mehrere Nutzer mit unterschiedlichen Rechten
- [x] Basis-Installer mit geführtem Setup (8 Schritte)
### v0.7.0 – DSGVO-bewusster Backup-Manager - [x] Telegram Bot mit Auth Guard (Single-User)
- [x] Dual-Model KI: Coder (qwen2.5-coder) + Chat (gemma3/gemma4)
- [ ] `/backup configs` → immer erlaubt - [x] `/shell` + `/ja` – Befehlsgenerierung mit Bestätigung (non-interaktive Befehle)
- [ ] `/backup app` → eigene Anwendungsdaten - [x] `/code` – Aider Code-Agent für autonome Script-Erstellung (Smart Prompt)
- [ ] `/backup db` → Warnung + Bestätigung bei personenbezogenen Daten - [x] `/run` – Direkte Shell ohne KI
- [ ] Lokale KI bewertet ob Daten DSGVO-relevant sein könnten - [x] `/status` – Systemübersicht (CPU, RAM, Disk, Prozesse)
- [x] `/ssh open/close` – ufw-basierter SSH-Zugang
### v0.8.0 – Erweiterte Cloud-API Integration - [x] Freitext-Chat mit History (letzte 10 Exchanges)
- [x] Snapshot-System (tar.gz, keep/unkeep, auto-cleanup max 20, Paketliste)
- [ ] Wahl zwischen Free- und Premium-Modellen auf OpenRouter - [x] `/snapshot`, `/snapshots`, `/rollback` (inkl. Workspace)
- [ ] Direkte Anthropic/OpenAI API-Anbindung (neben OpenRouter) - [x] Port-Knocking SSH (knockd) mit Telegram-Benachrichtigung
- [ ] Admin steuert pro Befehlstyp: lokal oder Cloud - [x] Boot-Notification nach Server-Neustart (Dienste-Status)
- [ ] Kosten-Tracking für Cloud-API-Nutzung - [x] Self-Update via Telegram ZIP (inkl. systemd-Services + User-Patch)
- [x] Update-Modus im Installer (mit MGMT_USER aus .env)
### v0.9.0 – Multi-Interface + Advanced Security - [x] Multi-Distro Installer (apt/dnf/pacman)
- [x] Ollama Warmup im Hintergrund (Bot sofort bereit)
- [ ] Matrix/Element Connector (E2E-verschlüsselt, self-hosted) - [x] **OpenRouter Free Fallback** – kostenlose Cloud-Modelle wenn Ollama nicht verfügbar
- [ ] Web-UI mit HTTPS (self-hosted, Let's Encrypt) - [x] Interaktiver Update-Dialog (OpenRouter Key Eingabe via Telegram)
- [ ] SSH-CLI als direktes Interface - [x] `OLLAMA_NUM_CTX` konfigurierbar (4K–32K, RAM-basierte Empfehlung im Installer)
- [ ] Fake-Modus + Distress-Code (falscher 2FA → stiller Alarm) - [x] Safe Telegram Output (Markdown-Fallback bei Parse-Fehlern)
- [ ] Geo-Fencing (nur erlaubte Länder/IP-Bereiche) - [x] Lange Antworten werden in Teile gesplittet (kein Abschneiden)
- [ ] Buddy-System (zwei Admins für kritische Befehle) - [x] Mehrsprachig (antwortet in der Sprache des Nutzers)
- [ ] Verschlüsselter Rückkanal über Telegram - [x] MGMT_USER Regex-Patch (beliebiger Username funktioniert überall)
- [x] Security-Analyse dokumentiert (Schwachstellen + Maßnahmen in CLOWNFISCHSERVER.md)
--- - [x] DSGVO-Regel: `.env` nur per SSH, nie über Telegram lesbar
- [x] Projekt-Kontext-Datei (CLOWNFISCHSERVER.md) für KI-gestütztes Pair-Programming
## Langzeit-Vision 🚀
### v0.5.0 – Cleanup & Stabilität (aktuelles Release)
### v1.0.0 – Intelligent Disaster Recovery
**Bugfixes & Aufräumarbeiten (dieser Release):**
Server komplett aus Snapshot wiederherstellen – auch auf anderer Hardware oder in einer anderen Umgebung. Die KI analysiert den Snapshot und rekonstruiert die Umgebung. - [x] Totes Vault/MCP-Context-System komplett entfernt (war nie verdrahtet, `verify=False`-Lücke)
- [x] Privacy-Fix: Chat-Nachrichten gingen via Vault-Suche an externe Endpoints → entfernt
*"Stelle Server 3 auf Stand von gestern 02:00 Uhr wieder her."* - [x] `/code` Filepath-Logik: fragiler Ternary-Ausdruck sauber umgeschrieben (kein Crash bei leerem Task)
- [x] Aider-Model-Default vereinheitlicht (zieht sich `OLLAMA_MODEL` aus der Umgebung)
Ziel: Open Source Alternative zu teuren Enterprise DR-Lösungen. - [x] Irreführende „Token-Optimization"-Logs (Anthropic-Kosten/Obsidian) aus dem Start-Log entfernt
### v2.0.0 – Cross-Distribution Server Migration **Sicherheit & DSGVO (geplant):**
- [ ] Sensitive Dateien über Telegram blockieren (`.env`, `shadow`, Keys)
Die eigentliche Revolution: **Ein Snapshot, jedes Zielsystem.** - [ ] Output-Sanitizer: API Keys/Tokens in jeder Bot-Antwort maskieren
- [ ] Log-Sanitizer: Keine Secrets im Audit-Log
Der Clownfischserver versteht nicht nur Dateien, sondern die *Logik* eines Servers: - [ ] Audit-Log: Jeder Befehl mit Timestamp (DSGVO Art. 5/32)
- Welche Pakete sind installiert und wofür? - [ ] Self-Update Hardening: SHA256-Hash anzeigen, Admin bestätigt
- Welche Services laufen und wie sind sie konfiguriert? - [ ] `.env` Permissions-Check beim Bot-Start
- Welche Abhängigkeiten bestehen zwischen Komponenten? - [ ] `bot.log`, `.aider.chat.history.md`, `bash_history` aus Snapshots excluden
- [ ] Rate-Limiting: Max 30 Befehle/Minute
Diese Logik ist distro-unabhängig. Ein Debian-Server mit nginx + PostgreSQL + Docker hat die gleiche *Absicht* wie ein Arch-Server mit denselben Diensten – nur andere Paketnamen, Pfade und Init-Systeme. - [ ] Session-Timeout: Nach 30 Min Inaktivität → 2FA erneut nötig
- [ ] 2FA bei kritischen Aktionen (TOTP/Mail/zweiter Bot)
**Ziel-Plattformen:** - [ ] Persönlicher Code-Offset (SECURITY_OFFSET in `.env`)
- Debian / Ubuntu (heute)
- Arch Linux **Features:**
- Red Hat / Fedora / CentOS - [ ] Snapshot-Scheduling (`/snapshot schedule daily 03:00`)
- openSUSE - [ ] Snapshot-Export als ZIP via Telegram (`/snapshot export <n>`)
- FreeBSD - [ ] `/logs` – Systemlogs direkt im Bot
- Weitere UNIX-Systeme - [ ] `/docker` – Docker Container Management
- [ ] Port-Knocking Sequenz im Installer wählbar
**Wie es funktioniert:** - [ ] Verschlüsselte Snapshots (SNAPSHOT_PASSWORD)
1. KI analysiert Snapshot und erstellt ein distro-neutrales "Server-Profil" - [ ] Open Interpreter als Aider-Alternative evaluieren
2. Profil beschreibt: Dienste, Konfigurationen, Daten, Netzwerk, Nutzer
3. Auf dem Zielsystem: KI übersetzt das Profil in native Befehle **Quick-Win Security:**
4. `apt install nginx` → `pacman -S nginx` → `pkg install nginx` - [ ] Panik-Wort: Admin-definiertes Wort → Bot löscht .env, sperrt alles
5. Konfigurationen werden angepasst (Pfade, Syntax, Permissions) - [ ] Honeypot-Befehle: Fake-Commands die Eindringlinge verraten
- [ ] Selbstzerstörende Nachrichten: Bot löscht eigene Outputs nach X Minuten
*"Migriere meinen Debian-Webserver auf Arch Linux."* - [ ] Rollback-Bombe: 3x falscher 2FA → auto-Rollback + SSH sperren
- [ ] Dead Man's Switch: Kein Lebenszeichen in 24h → Bot sperrt sich
### Weltklasse Integration 🌍
### v0.6.0 – Multi-Server
Clownfischserver als Infrastruktur-Layer für die Weltklasse App – natürliche Sprachsteuerung des gesamten Server-Ökosystems. GDPR-konform, vollständig lokal, kein Cloud-Zwang.
- [ ] Ein Bot steuert mehrere Server
--- - [ ] Zentrale Snapshot-Verwaltung
- [ ] Serverpark-Übersicht und -Steuerung
> *"Angefangen als einfacher Telegram-Bot – gewachsen zu einer Vision."* 🐠 - [ ] Mehrere Nutzer mit unterschiedlichen Rechten
--- ### v0.7.0 – DSGVO-bewusster Backup-Manager
## Prinzipien 🛡️ - [ ] `/backup configs` → immer erlaubt
- [ ] `/backup app` → eigene Anwendungsdaten
``` - [ ] `/backup db` → Warnung + Bestätigung bei personenbezogenen Daten
1. Local AI first – Lokal ist Standard. Cloud ist Opt-in. - [ ] Lokale KI bewertet ob Daten DSGVO-relevant sein könnten
2. Open Source always – GPL-3.0, keine Ausnahmen
3. DSGVO by design – Datenschutz ist kein Feature, es ist Pflicht ### v0.8.0 – Erweiterte Cloud-API Integration
4. Security first – SSH zu, KI prüft, Snapshots sichern
5. Einfachheit – ein Mensch, ein Bot, ein Server - [ ] Wahl zwischen Free- und Premium-Modellen auf OpenRouter
6. Distro-agnostisch – Linux ist Linux. Die KI kennt den Unterschied. - [ ] Direkte Anthropic/OpenAI API-Anbindung (neben OpenRouter)
``` - [ ] Admin steuert pro Befehlstyp: lokal oder Cloud
- [ ] Kosten-Tracking für Cloud-API-Nutzung
### Zur Cloud-Frage
### v0.9.0 – Multi-Interface + Advanced Security
Clownfischserver ist und bleibt local-first. Aber wir sind keine Puristen: wenn ein Admin einen OpenRouter-API-Key hat und ihn für komplexe Aufgaben nutzen will, soll er das können. Die Entscheidung liegt beim Admin, nicht beim Tool.
- [ ] Matrix/Element Connector (E2E-verschlüsselt, self-hosted)
Was wir **nicht** tun: - [ ] Web-UI mit HTTPS (self-hosted, Let's Encrypt)
- Cloud als Voraussetzung - [ ] SSH-CLI als direktes Interface
- Daten automatisch an externe APIs senden - [ ] Fake-Modus + Distress-Code (falscher 2FA → stiller Alarm)
- Features hinter Cloud-APIs verstecken - [ ] Geo-Fencing (nur erlaubte Länder/IP-Bereiche)
- [ ] Buddy-System (zwei Admins für kritische Befehle)
Was wir **ermöglichen** (seit v0.4.12/v0.4.13): - [ ] Verschlüsselter Rückkanal über Telegram
- Optionaler OpenRouter API-Key in `.env` (kostenlos, keine Kreditkarte)
- Automatischer Fallback: Ollama Timeout → OpenRouter übernimmt ---
- Wenn Cloud ausfällt, funktioniert alles weiterhin lokal
- Setup direkt im Bot: ZIP schicken → Bot fragt nach Key → fertig ## Langzeit-Vision 🚀
> *Als Admin entscheidest du – nicht das Tool.* ### v1.0.0 – Intelligent Disaster Recovery
--- Server komplett aus Snapshot wiederherstellen – auch auf anderer Hardware oder in einer anderen Umgebung. Die KI analysiert den Snapshot und rekonstruiert die Umgebung.
## Entwicklung *"Stelle Server 3 auf Stand von gestern 02:00 Uhr wieder her."*
**Entwickler:** [Mehlzoerwer-Claude](https://github.com/mehlzoerwer-claude) Ziel: Open Source Alternative zu teuren Enterprise DR-Lösungen.
**KI-Assistent:** Dieses Projekt wurde mit [Claude](https://claude.ai) (Anthropic) als Pair-Programming Partner entwickelt. Claude ist der einzige nicht-Open-Source Teil dieser Zusammenarbeit. 😄 ### v2.0.0 – Cross-Distribution Server Migration
**Philosophie:** Open Source ohne Wenn und Aber. Wer's nutzt, muss es offen lassen (GPL-3.0). Die eigentliche Revolution: **Ein Snapshot, jedes Zielsystem.**
--- Der Clownfischserver versteht nicht nur Dateien, sondern die *Logik* eines Servers:
- Welche Pakete sind installiert und wofür?
## Lizenz - Welche Services laufen und wie sind sie konfiguriert?
- Welche Abhängigkeiten bestehen zwischen Komponenten?
GPL-3.0 - Keep it open. Always.
Diese Logik ist distro-unabhängig. Ein Debian-Server mit nginx + PostgreSQL + Docker hat die gleiche *Absicht* wie ein Arch-Server mit denselben Diensten – nur andere Paketnamen, Pfade und Init-Systeme.
Copyright (C) 2025-2026 Mehlzoerwer-Claude
**Ziel-Plattformen:**
--- - Debian / Ubuntu (heute)
- Arch Linux
*Danke an alle die Ollama, Aider, python-telegram-bot, knockd und ufw gebaut haben.* - Red Hat / Fedora / CentOS
*Und an den echten Clownfisch – für die Inspiration.* 🐠 - openSUSE
- FreeBSD
- Weitere UNIX-Systeme
**Wie es funktioniert:**
1. KI analysiert Snapshot und erstellt ein distro-neutrales "Server-Profil"
2. Profil beschreibt: Dienste, Konfigurationen, Daten, Netzwerk, Nutzer
3. Auf dem Zielsystem: KI übersetzt das Profil in native Befehle
4. `apt install nginx` → `pacman -S nginx` → `pkg install nginx`
5. Konfigurationen werden angepasst (Pfade, Syntax, Permissions)
*"Migriere meinen Debian-Webserver auf Arch Linux."*
### Weltklasse Integration 🌍
Clownfischserver als Infrastruktur-Layer für die Weltklasse App – natürliche Sprachsteuerung des gesamten Server-Ökosystems. GDPR-konform, vollständig lokal, kein Cloud-Zwang.
---
> *"Angefangen als einfacher Telegram-Bot – gewachsen zu einer Vision."* 🐠
---
## Prinzipien 🛡️
```
1. Local AI first – Lokal ist Standard. Cloud ist Opt-in.
2. Open Source always – GPL-3.0, keine Ausnahmen
3. DSGVO by design – Datenschutz ist kein Feature, es ist Pflicht
4. Security first – SSH zu, KI prüft, Snapshots sichern
5. Einfachheit – ein Mensch, ein Bot, ein Server
6. Distro-agnostisch – Linux ist Linux. Die KI kennt den Unterschied.
```
### Zur Cloud-Frage
Clownfischserver ist und bleibt local-first. Aber wir sind keine Puristen: wenn ein Admin einen OpenRouter-API-Key hat und ihn für komplexe Aufgaben nutzen will, soll er das können. Die Entscheidung liegt beim Admin, nicht beim Tool.
Was wir **nicht** tun:
- Cloud als Voraussetzung
- Daten automatisch an externe APIs senden
- Features hinter Cloud-APIs verstecken
Was wir **ermöglichen** (seit v0.4.12/v0.4.13):
- Optionaler OpenRouter API-Key in `.env` (kostenlos, keine Kreditkarte)
- Automatischer Fallback: Ollama Timeout → OpenRouter übernimmt
- Wenn Cloud ausfällt, funktioniert alles weiterhin lokal
- Setup direkt im Bot: ZIP schicken → Bot fragt nach Key → fertig
> *Als Admin entscheidest du – nicht das Tool.*
---
## Entwicklung
**Entwickler:** [Mehlzoerwer-Claude](https://github.com/mehlzoerwer-claude)
**KI-Assistent:** Dieses Projekt wurde mit [Claude](https://claude.ai) (Anthropic) als Pair-Programming Partner entwickelt. Claude ist der einzige nicht-Open-Source Teil dieser Zusammenarbeit. 😄
**Philosophie:** Open Source ohne Wenn und Aber. Wer's nutzt, muss es offen lassen (GPL-3.0).
---
## Lizenz
GPL-3.0 - Keep it open. Always.
Copyright (C) 2025-2026 Mehlzoerwer-Claude
---
*Danke an alle die Ollama, Aider, python-telegram-bot, knockd und ufw gebaut haben.*
*Und an den echten Clownfisch – für die Inspiration.* 🐠
+128 -128
View File
@@ -1,128 +1,128 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
""" """
🐠 Clownfischserver 🐠 Clownfischserver
Author: Mehlzoerwer-Claude (https://github.com/mehlzoerwer-claude) Author: Mehlzoerwer-Claude (https://github.com/mehlzoerwer-claude)
License: GPL-3.0 – Keep it open. Always. License: GPL-3.0 – Keep it open. Always.
Repo: https://github.com/mehlzoerwer-claude/clownfischserver Repo: https://github.com/mehlzoerwer-claude/clownfischserver
""" """
import asyncio import asyncio
import logging import logging
import os import os
import tempfile import tempfile
from pathlib import Path from pathlib import Path
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
INSTALL_DIR = os.getenv("INSTALL_DIR", "/opt/clownfischserver") INSTALL_DIR = os.getenv("INSTALL_DIR", "/opt/clownfischserver")
AIDER_WORKDIR = os.getenv("AIDER_WORKDIR", "/opt/clownfisch-workspace") AIDER_WORKDIR = os.getenv("AIDER_WORKDIR", "/opt/clownfisch-workspace")
OLLAMA_BASE_URL = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434") OLLAMA_BASE_URL = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")
OLLAMA_MODEL = os.getenv("OLLAMA_MODEL", "qwen2.5-coder:7b") OLLAMA_MODEL = os.getenv("OLLAMA_MODEL", "qwen2.5-coder:7b")
TIMEOUT = 600 # 10 minutes for aider tasks on CPU TIMEOUT = 600 # 10 minutes for aider tasks on CPU
class AiderWrapper: class AiderWrapper:
def __init__(self): def __init__(self):
self.workdir = Path(AIDER_WORKDIR) self.workdir = Path(AIDER_WORKDIR)
self.workdir.mkdir(parents=True, exist_ok=True) self.workdir.mkdir(parents=True, exist_ok=True)
self.venv_python = Path(INSTALL_DIR) / "aider-venv" / "bin" / "python3" self.venv_python = Path(INSTALL_DIR) / "aider-venv" / "bin" / "python3"
self.venv_aider = Path(INSTALL_DIR) / "aider-venv" / "bin" / "aider" self.venv_aider = Path(INSTALL_DIR) / "aider-venv" / "bin" / "aider"
logger.info(f"AiderWrapper init: workdir={self.workdir}") logger.info(f"AiderWrapper init: workdir={self.workdir}")
async def run(self, task: str, target_file: str = None) -> str: async def run(self, task: str, target_file: str = None) -> str:
""" """
Run aider in script mode for a coding task. Run aider in script mode for a coding task.
Returns the output/result as string. Returns the output/result as string.
""" """
logger.info(f"Aider task: {task[:100]}") logger.info(f"Aider task: {task[:100]}")
# Determine working directory and files # Determine working directory and files
workdir = self.workdir workdir = self.workdir
# Build aider command # Build aider command
cmd = self._build_aider_command(task, target_file) cmd = self._build_aider_command(task, target_file)
try: try:
process = await asyncio.create_subprocess_exec( process = await asyncio.create_subprocess_exec(
*cmd, *cmd,
stdout=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
cwd=str(workdir), cwd=str(workdir),
env={ env={
**os.environ, **os.environ,
"OLLAMA_API_BASE": OLLAMA_BASE_URL, "OLLAMA_API_BASE": OLLAMA_BASE_URL,
"HOME": f"/home/{os.getenv('MGMT_USER', 'clownfish')}", "HOME": f"/home/{os.getenv('MGMT_USER', 'clownfish')}",
} }
) )
try: try:
stdout, stderr = await asyncio.wait_for( stdout, stderr = await asyncio.wait_for(
process.communicate(), process.communicate(),
timeout=TIMEOUT timeout=TIMEOUT
) )
except asyncio.TimeoutError: except asyncio.TimeoutError:
process.kill() process.kill()
return f"⏱️ Aider Timeout nach {TIMEOUT}s. Task zu komplex oder Modell überlastet." return f"⏱️ Aider Timeout nach {TIMEOUT}s. Task zu komplex oder Modell überlastet."
stdout_str = stdout.decode("utf-8", errors="replace").strip() stdout_str = stdout.decode("utf-8", errors="replace").strip()
stderr_str = stderr.decode("utf-8", errors="replace").strip() stderr_str = stderr.decode("utf-8", errors="replace").strip()
# Build response # Build response
result_parts = [] result_parts = []
if stdout_str: if stdout_str:
result_parts.append(stdout_str) result_parts.append(stdout_str)
if stderr_str and process.returncode != 0: if stderr_str and process.returncode != 0:
result_parts.append(f"[STDERR]\n{stderr_str}") result_parts.append(f"[STDERR]\n{stderr_str}")
if process.returncode == 0: if process.returncode == 0:
result_parts.insert(0, f"✅ Aider Task abgeschlossen\nArbeitsverzeichnis: {workdir}\n") result_parts.insert(0, f"✅ Aider Task abgeschlossen\nArbeitsverzeichnis: {workdir}\n")
else: else:
result_parts.insert(0, f"⚠️ Aider beendet mit Code {process.returncode}\n") result_parts.insert(0, f"⚠️ Aider beendet mit Code {process.returncode}\n")
return "\n".join(result_parts) or "✓ Task abgeschlossen (keine Ausgabe)" return "\n".join(result_parts) or "✓ Task abgeschlossen (keine Ausgabe)"
except FileNotFoundError: except FileNotFoundError:
return ( return (
"❌ Aider nicht gefunden. Bitte prüfen:\n" "❌ Aider nicht gefunden. Bitte prüfen:\n"
f" ls {self.venv_aider}\n" f" ls {self.venv_aider}\n"
" Ggf. neu installieren mit: pip install aider-chat" " Ggf. neu installieren mit: pip install aider-chat"
) )
except Exception as e: except Exception as e:
logger.error(f"Aider execution error: {e}", exc_info=True) logger.error(f"Aider execution error: {e}", exc_info=True)
return f"❌ Aider Fehler: {e}" return f"❌ Aider Fehler: {e}"
def _build_aider_command(self, task: str, target_file: str = None) -> list: def _build_aider_command(self, task: str, target_file: str = None) -> list:
"""Build the aider command with appropriate flags""" """Build the aider command with appropriate flags"""
cmd = [ cmd = [
str(self.venv_aider), str(self.venv_aider),
"--model", f"ollama/{OLLAMA_MODEL}", "--model", f"ollama/{OLLAMA_MODEL}",
"--no-git", # Don't require git "--no-git", # Don't require git
"--yes", # Auto-confirm all changes "--yes", # Auto-confirm all changes
"--no-pretty", # Plain output for telegram "--no-pretty", # Plain output for telegram
"--no-show-model-warnings", # Skip env var warnings "--no-show-model-warnings", # Skip env var warnings
"--no-analytics", # No analytics prompts "--no-analytics", # No analytics prompts
"--edit-format", "diff", # Better format for small models "--edit-format", "diff", # Better format for small models
"--message", task, # The task as a message "--message", task, # The task as a message
] ]
if target_file: if target_file:
cmd.append(target_file) cmd.append(target_file)
return cmd return cmd
async def list_workspace_files(self) -> str: async def list_workspace_files(self) -> str:
"""List files in the aider workspace""" """List files in the aider workspace"""
try: try:
files = list(self.workdir.rglob("*")) files = list(self.workdir.rglob("*"))
if not files: if not files:
return f"📁 Workspace {self.workdir} ist leer." return f"📁 Workspace {self.workdir} ist leer."
file_list = "\n".join([ file_list = "\n".join([
f" {'📁' if f.is_dir() else '📄'} {f.relative_to(self.workdir)}" f" {'📁' if f.is_dir() else '📄'} {f.relative_to(self.workdir)}"
for f in sorted(files)[:50] for f in sorted(files)[:50]
]) ])
return f"📁 Workspace: {self.workdir}\n\n{file_list}" return f"📁 Workspace: {self.workdir}\n\n{file_list}"
except Exception as e: except Exception as e:
return f"❌ Fehler beim Lesen des Workspace: {e}" return f"❌ Fehler beim Lesen des Workspace: {e}"
+205
View File
@@ -0,0 +1,205 @@
#!/usr/bin/env python3
"""
🐠 Clownfischserver – Audit Trail (DSGVO Art. 5 + 32)
Author: Mehlzoerwer-Claude (https://github.com/mehlzoerwer-claude)
License: GPL-3.0
Writes JSON-line entries for every privileged action.
Pseudonymized: stores only numeric Telegram user_ids, never usernames.
Compliance:
- Art. 5(1)(a) lawfulness/transparency: every action is recorded.
- Art. 5(1)(c) data minimization: numeric IDs only, command/result trimmed.
- Art. 5(1)(e) storage limitation: prune_old_logs() drops entries older
than AUDIT_RETENTION_DAYS (default 90).
- Art. 32 integrity: append-only file, 0600 permissions.
"""
from __future__ import annotations
import json
import logging
import os
import threading
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
logger = logging.getLogger(__name__)
# How much of a command/result we keep – longer payloads are truncated
# to honour data minimization. Configurable via env.
_MAX_DETAIL_LEN = int(os.getenv("AUDIT_MAX_DETAIL_LEN", "2000"))
# Lock for append writes – multiple coroutines may log concurrently.
_write_lock = threading.Lock()
def _default_audit_path() -> str:
install_dir = os.getenv("INSTALL_DIR", "/opt/clownfischserver")
return os.getenv("AUDIT_LOG_PATH", os.path.join(install_dir, "audit.jsonl"))
def _retention_days() -> int:
try:
return max(0, int(os.getenv("AUDIT_RETENTION_DAYS", "90")))
except ValueError:
return 90
def _trim(value: Any) -> Any:
if isinstance(value, str) and len(value) > _MAX_DETAIL_LEN:
return value[:_MAX_DETAIL_LEN] + f"... (truncated, {len(value)} chars total)"
return value
def _now_iso() -> str:
return datetime.now(timezone.utc).isoformat(timespec="seconds")
def log_action(
user_id: str | int | None,
action: str,
*,
role: str | None = None,
result: str = "ok",
details: dict[str, Any] | None = None,
path: str | None = None,
) -> None:
"""Append a single audit record. Never raises – audit failure must not
break the bot."""
entry: dict[str, Any] = {
"ts": _now_iso(),
"user_id": str(user_id) if user_id is not None else None,
"action": action,
"result": result,
}
if role:
entry["role"] = role
if details:
entry["details"] = {k: _trim(v) for k, v in details.items()}
target = path or _default_audit_path()
try:
Path(target).parent.mkdir(parents=True, exist_ok=True)
line = json.dumps(entry, ensure_ascii=False) + "\n"
with _write_lock:
with open(target, "a", encoding="utf-8") as fh:
fh.write(line)
try:
os.chmod(target, 0o600)
except OSError:
# chmod can fail on non-POSIX FS (e.g. tests on Windows) –
# the JSONL content is still written.
pass
except Exception as e:
logger.error(f"Audit log write failed: {e}")
def log_shell(user_id, command: str, *, role: str | None = None,
status: str = "executed", returncode: int | None = None,
stderr: str | None = None, path: str | None = None) -> None:
details: dict[str, Any] = {"command": command}
if returncode is not None:
details["returncode"] = returncode
if stderr:
details["stderr"] = stderr
log_action(user_id, "shell.execute", role=role, result=status,
details=details, path=path)
def log_shell_proposed(user_id, description: str, command: str,
role: str | None = None, dangerous: bool = False,
path: str | None = None) -> None:
log_action(
user_id,
"shell.proposed",
role=role,
result="dangerous" if dangerous else "ok",
details={"description": description, "command": command},
path=path,
)
def log_code(user_id, task: str, *, role: str | None = None,
status: str = "ok", path: str | None = None) -> None:
log_action(user_id, "code.run", role=role, result=status,
details={"task": task}, path=path)
def log_approval(user_id, command: str, *, role: str | None = None,
approved: bool = True, path: str | None = None) -> None:
log_action(
user_id,
"shell.approval",
role=role,
result="approved" if approved else "rejected",
details={"command": command},
path=path,
)
def log_denied(user_id, action: str, *, role: str | None = None,
reason: str = "insufficient_role",
path: str | None = None) -> None:
log_action(user_id, action, role=role, result="denied",
details={"reason": reason}, path=path)
def prune_old_logs(path: str | None = None,
retention_days: int | None = None) -> int:
"""Rewrite the audit file, dropping entries older than retention_days.
Returns the number of dropped lines. retention_days=0 disables pruning.
Uses an atomic temp-file + rename so a crash mid-prune cannot corrupt
the audit trail.
"""
target = path or _default_audit_path()
days = retention_days if retention_days is not None else _retention_days()
if days <= 0 or not os.path.exists(target):
return 0
cutoff = time.time() - days * 86400
tmp_path = target + ".prune.tmp"
dropped = 0
kept = 0
try:
with _write_lock:
with open(target, "r", encoding="utf-8") as src, \
open(tmp_path, "w", encoding="utf-8") as dst:
for line in src:
raw = line.strip()
if not raw:
continue
try:
record = json.loads(raw)
ts = record.get("ts", "")
# ISO 8601 – parse with fromisoformat (UTC suffix safe)
dt = datetime.fromisoformat(ts.replace("Z", "+00:00"))
if dt.timestamp() < cutoff:
dropped += 1
continue
except (ValueError, KeyError):
# Malformed line: keep it rather than silently dropping
# forensic evidence.
pass
dst.write(line if line.endswith("\n") else line + "\n")
kept += 1
os.replace(tmp_path, target)
try:
os.chmod(target, 0o600)
except OSError:
pass
logger.info(f"Audit prune: kept={kept} dropped={dropped} retention={days}d")
except Exception as e:
logger.error(f"Audit prune failed: {e}")
if os.path.exists(tmp_path):
try:
os.remove(tmp_path)
except OSError:
pass
return 0
return dropped
+189
View File
@@ -0,0 +1,189 @@
#!/usr/bin/env python3
"""
🐠 Clownfischserver – Audit Trail Query (Phase 2b)
Author: Mehlzoerwer-Claude (https://github.com/mehlzoerwer-claude)
License: GPL-3.0
Read-side companion to audit_log.py. Filters/sorts JSONL audit records for
the `/logs` admin command.
The query layer is intentionally separate from the writer so that:
- Tests can exercise filtering without touching real audit data.
- The writer stays append-only and minimal.
- Future query backends (SQLite, OpenSearch) can swap in without touching
the writer.
"""
from __future__ import annotations
import json
import logging
import os
from datetime import datetime, timezone, timedelta
from typing import Any, Iterable
logger = logging.getLogger(__name__)
def _default_audit_path() -> str:
install_dir = os.getenv("INSTALL_DIR", "/opt/clownfischserver")
return os.getenv("AUDIT_LOG_PATH", os.path.join(install_dir, "audit.jsonl"))
def _parse_ts(record: dict) -> datetime | None:
"""Best-effort parse of the record's ts field. Returns None on
malformed timestamps (caller decides how to handle)."""
ts = record.get("ts")
if not isinstance(ts, str):
return None
try:
return datetime.fromisoformat(ts.replace("Z", "+00:00"))
except ValueError:
return None
def read_all(path: str | None = None) -> list[dict]:
"""Load every audit record from the JSONL file. Malformed lines are
skipped with a debug log (the writer keeps them for forensic purposes,
but the query layer prefers a clean result set)."""
target = path or _default_audit_path()
if not os.path.exists(target):
return []
out: list[dict] = []
try:
with open(target, "r", encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if not line:
continue
try:
out.append(json.loads(line))
except json.JSONDecodeError:
logger.debug(f"audit_query: skipping malformed line")
continue
except OSError as e:
logger.error(f"audit_query: cannot read {target}: {e}")
return []
return out
def filter_records(
records: Iterable[dict],
*,
user_id: str | int | None = None,
action: str | None = None,
action_prefix: str | None = None,
result: str | None = None,
since: datetime | None = None,
until: datetime | None = None,
) -> list[dict]:
"""Apply filters and return matching records, newest first.
Filters are AND-combined. None values are ignored. action/result match
exactly; action_prefix matches if the record's action starts with it.
"""
target_user = str(user_id) if user_id is not None else None
matched: list[dict] = []
for rec in records:
if target_user is not None and rec.get("user_id") != target_user:
continue
if action is not None and rec.get("action") != action:
continue
if action_prefix is not None:
rec_action = rec.get("action", "")
if not isinstance(rec_action, str) or not rec_action.startswith(action_prefix):
continue
if result is not None and rec.get("result") != result:
continue
if since is not None or until is not None:
dt = _parse_ts(rec)
if dt is None:
# Malformed ts – exclude when caller asked for a date window.
continue
if since is not None and dt < since:
continue
if until is not None and dt > until:
continue
matched.append(rec)
# Newest first – stable sort by ts (records without ts go to the bottom).
matched.sort(key=lambda r: r.get("ts", ""), reverse=True)
return matched
def query(
*,
user_id: str | int | None = None,
action: str | None = None,
action_prefix: str | None = None,
result: str | None = None,
days: int | None = None,
limit: int = 20,
path: str | None = None,
) -> list[dict]:
"""Convenience wrapper: read + filter in one call.
`days` is a shortcut for `since = now - days`. limit clamps the
returned record count (use limit=0 for no limit)."""
since = None
if days is not None and days > 0:
since = datetime.now(timezone.utc) - timedelta(days=days)
records = read_all(path=path)
matched = filter_records(
records,
user_id=user_id,
action=action,
action_prefix=action_prefix,
result=result,
since=since,
)
if limit and limit > 0:
matched = matched[:limit]
return matched
def format_record(rec: dict) -> str:
"""Render one audit record as a single compact line for Telegram."""
ts = rec.get("ts", "?")
# Trim ts down to HH:MM:SS or YYYY-MM-DD HH:MM:SS for readability.
if isinstance(ts, str) and len(ts) >= 19:
ts_short = ts[:19].replace("T", " ")
else:
ts_short = str(ts)
uid = rec.get("user_id") or "—"
action = rec.get("action", "?")
result = rec.get("result", "?")
role = rec.get("role")
role_part = f" [{role}]" if role else ""
details = rec.get("details") or {}
detail_str = ""
if isinstance(details, dict):
# Pick the single most-informative key per common action.
for key in ("command", "task", "reason", "snapshot", "method", "tier"):
if key in details:
val = str(details[key])
if len(val) > 80:
val = val[:77] + "..."
detail_str = f" {val}"
break
return f"{ts_short} {uid}{role_part} {action}={result}{detail_str}"
def summarize(records: list[dict]) -> dict[str, Any]:
"""Aggregate counts useful for the /logs header."""
by_action: dict[str, int] = {}
by_user: dict[str, int] = {}
by_result: dict[str, int] = {}
for r in records:
act = r.get("action", "?")
by_action[act] = by_action.get(act, 0) + 1
uid = r.get("user_id") or "—"
by_user[uid] = by_user.get(uid, 0) + 1
res = r.get("result", "?")
by_result[res] = by_result.get(res, 0) + 1
return {"total": len(records), "by_action": by_action,
"by_user": by_user, "by_result": by_result}
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""
🐠 Clownfischserver – Role-Based Access Control
Author: Mehlzoerwer-Claude (https://github.com/mehlzoerwer-claude)
License: GPL-3.0
Implements DSGVO Art. 32 access control:
- operator: full execution rights (/shell, /code, /run, /ja, /ssh, /snapshot)
- approver: can approve pending operations (/ja)
- viewer: read-only access (/status, /snapshots, /help)
Backwards compatible: if no role env vars are set but TELEGRAM_CHAT_ID
is configured, that user is auto-granted the operator role.
"""
from __future__ import annotations
import logging
import os
logger = logging.getLogger(__name__)
ROLE_OPERATOR = "operator"
ROLE_APPROVER = "approver"
ROLE_VIEWER = "viewer"
VALID_ROLES = (ROLE_OPERATOR, ROLE_APPROVER, ROLE_VIEWER)
# Operators implicitly hold approver + viewer rights.
# Approvers implicitly hold viewer rights.
_ROLE_INHERITANCE: dict[str, tuple[str, ...]] = {
ROLE_OPERATOR: (ROLE_OPERATOR, ROLE_APPROVER, ROLE_VIEWER),
ROLE_APPROVER: (ROLE_APPROVER, ROLE_VIEWER),
ROLE_VIEWER: (ROLE_VIEWER,),
}
def _parse_id_list(raw: str | None) -> set[str]:
if not raw:
return set()
return {part.strip() for part in raw.split(",") if part.strip()}
def _load_role_map() -> dict[str, str]:
"""Read role config from env vars.
Returns {user_id_str: highest_role}. If a user appears in multiple
role lists, the strongest role wins (operator > approver > viewer).
"""
operators = _parse_id_list(os.getenv("CLOWNFISCH_OPERATORS"))
approvers = _parse_id_list(os.getenv("CLOWNFISCH_APPROVERS"))
viewers = _parse_id_list(os.getenv("CLOWNFISCH_VIEWERS"))
role_map: dict[str, str] = {}
for uid in viewers:
role_map[uid] = ROLE_VIEWER
for uid in approvers:
role_map[uid] = ROLE_APPROVER
for uid in operators:
role_map[uid] = ROLE_OPERATOR
# Backwards compatibility: legacy TELEGRAM_CHAT_ID becomes operator
# when no explicit role lists are defined.
if not role_map:
legacy = os.getenv("TELEGRAM_CHAT_ID", "").strip()
if legacy:
role_map[legacy] = ROLE_OPERATOR
logger.info(
"Auth: no role lists configured – granting operator to legacy "
"TELEGRAM_CHAT_ID for backwards compatibility."
)
return role_map
def get_role(user_id: str | int | None) -> str | None:
"""Return the role of a user, or None if unauthorized."""
if user_id is None:
return None
return _load_role_map().get(str(user_id))
def has_role(user_id: str | int | None, *required: str) -> bool:
"""Check if the user satisfies ANY of the required roles.
Inheritance applies: an operator passes a check for approver/viewer.
"""
role = get_role(user_id)
if role is None:
return False
granted = _ROLE_INHERITANCE.get(role, (role,))
return any(r in granted for r in required)
def is_authorized(user_id: str | int | None) -> bool:
"""True if the user has any role at all."""
return get_role(user_id) is not None
def list_users_with_role(role: str) -> list[str]:
"""Return all user_ids that hold (or inherit) the given role."""
if role not in VALID_ROLES:
return []
return [uid for uid, r in _load_role_map().items()
if role in _ROLE_INHERITANCE.get(r, (r,))]
def describe_roles() -> dict[str, list[str]]:
"""Snapshot of current role assignments – useful for /status or audits."""
role_map = _load_role_map()
result: dict[str, list[str]] = {r: [] for r in VALID_ROLES}
for uid, role in role_map.items():
result[role].append(uid)
return result
+1081 -771
View File
File diff suppressed because it is too large Load Diff
+322
View File
@@ -0,0 +1,322 @@
#!/usr/bin/env python3
"""
🐠 Clownfischserver – LLM Provider Router (Phase 3)
Author: Mehlzoerwer-Claude (https://github.com/mehlzoerwer-claude)
License: GPL-3.0
Replaces the previously hard-wired Ollama+OpenRouter fallback logic with a
config-driven primary/fallback chain.
Env vars:
LLM_PRIMARY_PROVIDER = "ollama" | "openrouter" (default: ollama)
LLM_PRIMARY_MODEL = model id for the primary provider
LLM_PRIMARY_MODEL_FAST = optional faster model for chat replies (ollama only)
LLM_PRIMARY_NUM_CTX = context window override (ollama)
LLM_FALLBACK_PROVIDER = "openrouter" | "ollama" | "" ("" disables fallback)
LLM_FALLBACK_MODEL = model id for fallback provider
TRACK_LLM_COSTS = "true"|"false" – currently informational only
Backwards compatibility:
- If LLM_*_PROVIDER vars are absent we still default to Ollama primary and,
when OPENROUTER_API_KEY exists, OpenRouter as fallback. Existing
OLLAMA_MODEL / OLLAMA_MODEL_FAST / OLLAMA_NUM_CTX / OPENROUTER_API_KEY
env vars are honoured.
Routing policy (intentionally explicit, not "self-improving"):
- Primary is tried first. Only routable errors (network, timeout, provider
unavailable) trigger fallback. Hard errors (invalid JSON, malformed prompt,
bad API key) propagate so callers see them.
- Every routing decision is written to the audit trail as `llm.route` so
admins can see which model produced which output (DSGVO Art. 5(1)(a)
transparency).
"""
from __future__ import annotations
import logging
import os
from typing import Any, Awaitable, Callable, Optional
from ollama_client import OllamaClient
from openrouter_client import OpenRouterClient
try: # audit is optional – router must work even if audit module is missing
import audit_log
except ImportError: # pragma: no cover
audit_log = None # type: ignore
logger = logging.getLogger(__name__)
PROVIDER_OLLAMA = "ollama"
PROVIDER_OPENROUTER = "openrouter"
# Error substrings that should trigger a fallback rather than propagate.
# Kept narrow on purpose – we don't want to mask programmer errors.
_ROUTABLE_ERROR_FRAGMENTS = (
"Timeout",
"nicht erreichbar",
"ConnectionError",
"Connection refused",
"API Key nicht konfiguriert",
)
def _is_routable_error(exc: BaseException) -> bool:
msg = str(exc)
return any(frag in msg for frag in _ROUTABLE_ERROR_FRAGMENTS)
class LLMProvider:
"""Thin interface every provider satisfies."""
name: str = "base"
model: str = ""
def is_available(self) -> bool:
raise NotImplementedError
async def chat(self, message: str, history: list | None = None) -> str:
raise NotImplementedError
async def generate_shell_command(self, description: str) -> dict:
raise NotImplementedError
async def explain_output(self, command: str, output: str,
error: str = "") -> str:
raise NotImplementedError
class OllamaProvider(LLMProvider):
name = PROVIDER_OLLAMA
def __init__(self, model: Optional[str] = None,
model_fast: Optional[str] = None,
num_ctx: Optional[int] = None,
base_url: Optional[str] = None):
# Pass openrouter_client=None so the underlying client does NOT
# perform its own fallback – the router owns that decision now.
self.client = OllamaClient(
openrouter_client=None,
model=model,
model_fast=model_fast,
num_ctx=num_ctx,
base_url=base_url,
)
self.model = self.client.model
def is_available(self) -> bool:
# Connection health is checked at call time; we always advertise
# ourselves as available so the router will attempt and trigger
# fallback on actual failure.
return True
async def chat(self, message, history=None):
return await self.client.chat(message, history)
async def generate_shell_command(self, description):
return await self.client.generate_shell_command(description)
async def explain_output(self, command, output, error=""):
return await self.client.explain_output(command, output, error)
class OpenRouterProvider(LLMProvider):
name = PROVIDER_OPENROUTER
def __init__(self, model: Optional[str] = None):
self.client = OpenRouterClient()
# OpenRouterClient reads OPENROUTER_API_KEY at import time. We
# only override the model id, leaving the API key handling alone.
self.model = model or "openrouter/free"
if model:
# Patch the FREE_MODELS dict so chat/coder both use the
# configured model. Limited blast radius – it only affects
# this OpenRouterClient instance, not the module constant.
self._patch_model(model)
def _patch_model(self, model: str) -> None:
# The underlying OpenRouterClient hard-codes FREE_MODELS["coder"]/
# ["chat"] at call sites. Wrap _chat_sync so every call resolves
# to the user-pinned model regardless of what callers pass in.
pinned = model
original_chat_sync = self.client._chat_sync
def wrapper(messages, system=None, model=None):
return original_chat_sync(messages, system=system, model=pinned)
self.client._chat_sync = wrapper # type: ignore[assignment]
def is_available(self) -> bool:
return self.client.is_available()
async def chat(self, message, history=None):
return await self.client.chat(message, history)
async def generate_shell_command(self, description):
return await self.client.generate_shell_command(description)
async def explain_output(self, command, output, error=""):
return await self.client.explain_output(command, output, error)
def _build_provider(kind: str) -> Optional[LLMProvider]:
"""Build the provider for kind ∈ {"primary", "fallback"}.
Returns None if the configuration disables this tier (e.g. fallback
requested but no key available).
"""
explicit = os.getenv(f"LLM_{kind.upper()}_PROVIDER", "").strip().lower()
if kind == "primary":
provider_name = explicit or PROVIDER_OLLAMA
else:
# Fallback default: openrouter only if API key is configured.
if explicit:
provider_name = explicit
elif os.getenv("OPENROUTER_API_KEY"):
provider_name = PROVIDER_OPENROUTER
else:
return None
if provider_name in ("", "none", "off", "disabled"):
return None
model = os.getenv(f"LLM_{kind.upper()}_MODEL", "").strip() or None
if provider_name == PROVIDER_OLLAMA:
model_fast = os.getenv(f"LLM_{kind.upper()}_MODEL_FAST", "").strip() or None
num_ctx_raw = os.getenv(f"LLM_{kind.upper()}_NUM_CTX", "").strip()
num_ctx = int(num_ctx_raw) if num_ctx_raw.isdigit() else None
return OllamaProvider(model=model, model_fast=model_fast,
num_ctx=num_ctx)
if provider_name == PROVIDER_OPENROUTER:
provider = OpenRouterProvider(model=model)
# Skip the tier if OpenRouter is configured but key is missing.
if not provider.is_available():
logger.warning(
f"LLM router: {kind} provider 'openrouter' has no API key – disabled"
)
return None
return provider
logger.error(f"LLM router: unknown {kind} provider '{provider_name}'")
return None
_BUILD_FROM_ENV = object() # sentinel: distinguish "not passed" from "None"
class LLMRouter:
"""Drop-in replacement for the old OllamaClient surface.
Exposes the same async methods (`chat`, `generate_shell_command`,
`explain_output`) plus a small status surface (`primary`, `fallback`,
`describe()`).
Pass `primary=None` / `fallback=None` to explicitly disable a tier;
omit the kwarg entirely to build the tier from environment.
"""
def __init__(self, primary=_BUILD_FROM_ENV, fallback=_BUILD_FROM_ENV):
self.primary = _build_provider("primary") if primary is _BUILD_FROM_ENV else primary
self.fallback = _build_provider("fallback") if fallback is _BUILD_FROM_ENV else fallback
if self.primary is None and self.fallback is None:
logger.error("LLMRouter: neither primary nor fallback configured!")
# ---- public describe ------------------------------------------------
def describe(self) -> dict:
def _info(p: LLMProvider | None) -> dict | None:
if p is None:
return None
return {"provider": p.name, "model": p.model,
"available": p.is_available()}
return {"primary": _info(self.primary), "fallback": _info(self.fallback)}
# ---- dispatcher -----------------------------------------------------
async def _dispatch(self, method_name: str, *args, **kwargs) -> Any:
attempts: list[tuple[str, LLMProvider]] = []
if self.primary is not None:
attempts.append(("primary", self.primary))
if self.fallback is not None:
attempts.append(("fallback", self.fallback))
if not attempts:
raise RuntimeError(
"Kein LLM-Provider konfiguriert (LLM_PRIMARY_PROVIDER fehlt)"
)
last_error: Optional[BaseException] = None
for tier, provider in attempts:
if not provider.is_available():
self._audit("skip", tier, provider, method_name,
reason="provider_unavailable")
continue
try:
result = await getattr(provider, method_name)(*args, **kwargs)
self._audit("hit", tier, provider, method_name)
return result
except Exception as e:
last_error = e
routable = _is_routable_error(e)
self._audit("error", tier, provider, method_name,
reason=str(e)[:200],
routable=routable)
if not routable:
# Hard error – don't mask it with a fallback.
raise
# Otherwise loop to next tier.
continue
# All tiers exhausted.
raise RuntimeError(
f"Alle LLM-Provider fehlgeschlagen für {method_name}: {last_error}"
)
def _audit(self, status: str, tier: str, provider: LLMProvider,
method: str, **extra) -> None:
if audit_log is None:
return
try:
details = {"tier": tier, "provider": provider.name,
"model": provider.model, "method": method}
details.update(extra)
audit_log.log_action(None, "llm.route", result=status,
details=details)
except Exception as e: # pragma: no cover – audit must never fail
logger.debug(f"audit emit failed: {e}")
# ---- public surface -------------------------------------------------
async def chat(self, message: str, history: list | None = None) -> str:
return await self._dispatch("chat", message, history)
async def generate_shell_command(self, description: str) -> dict:
return await self._dispatch("generate_shell_command", description)
async def explain_output(self, command: str, output: str,
error: str = "") -> str:
return await self._dispatch("explain_output", command, output, error)
# ---- convenience for the warmup path in bot.py ----------------------
@property
def ollama_models(self) -> list[str]:
"""Return distinct Ollama model ids configured across tiers –
used by the warmup thread in bot.py."""
models: list[str] = []
for p in (self.primary, self.fallback):
if isinstance(p, OllamaProvider):
if p.client.model and p.client.model not in models:
models.append(p.client.model)
if (p.client.model_fast
and p.client.model_fast not in models):
models.append(p.client.model_fast)
return models
@property
def ollama_base_url(self) -> str:
for p in (self.primary, self.fallback):
if isinstance(p, OllamaProvider):
return p.client.base_url
return os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")
def has_fallback(self) -> bool:
return self.fallback is not None and self.fallback.is_available()
+238 -234
View File
@@ -1,234 +1,238 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
""" """
🐠 Clownfischserver 🐠 Clownfischserver
Author: Mehlzoerwer-Claude (https://github.com/mehlzoerwer-claude) Author: Mehlzoerwer-Claude (https://github.com/mehlzoerwer-claude)
License: GPL-3.0 – Keep it open. Always. License: GPL-3.0 – Keep it open. Always.
Repo: https://github.com/mehlzoerwer-claude/clownfischserver Repo: https://github.com/mehlzoerwer-claude/clownfischserver
""" """
import json import json
import logging import logging
import os import os
import re import re
import asyncio import asyncio
import requests import requests
from typing import Optional from typing import Optional
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
OLLAMA_BASE_URL = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434") OLLAMA_BASE_URL = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")
OLLAMA_MODEL = os.getenv("OLLAMA_MODEL", "qwen2.5-coder:7b") OLLAMA_MODEL = os.getenv("OLLAMA_MODEL", "qwen2.5-coder:7b")
OLLAMA_MODEL_FAST = os.getenv("OLLAMA_MODEL_FAST", "") OLLAMA_MODEL_FAST = os.getenv("OLLAMA_MODEL_FAST", "")
OLLAMA_NUM_CTX = int(os.getenv("OLLAMA_NUM_CTX", "4096")) OLLAMA_NUM_CTX = int(os.getenv("OLLAMA_NUM_CTX", "4096"))
SHELL_PROMPT_TEMPLATE = """You are a Linux bash command generator for an Ubuntu 24.04 server. SHELL_PROMPT_TEMPLATE = """You are a Linux bash command generator for an Ubuntu 24.04 server.
Convert the user request into a single non-interactive bash command. Convert the user request into a single non-interactive bash command.
Respond with ONLY a JSON object. Respond with ONLY a JSON object.
CRITICAL RULES: CRITICAL RULES:
- Commands run WITHOUT a terminal. No interactive commands like nano, vim, crontab -e, less, top. - Commands run WITHOUT a terminal. No interactive commands like nano, vim, crontab -e, less, top.
- Use non-interactive alternatives: echo/tee for files, /etc/cron.d/ for cron jobs, sed for edits. - Use non-interactive alternatives: echo/tee for files, /etc/cron.d/ for cron jobs, sed for edits.
- Use sudo when root permissions are needed. - Use sudo when root permissions are needed.
- Chain commands with && if needed. - Chain commands with && if needed.
Example request: "show free ram" Example request: "show free ram"
Example response: {{"dangerous":false,"reason":"","command":"free -h"}} Example response: {{"dangerous":false,"reason":"","command":"free -h"}}
Example request: "installiere nginx" Example request: "installiere nginx"
Example response: {{"dangerous":false,"reason":"","command":"sudo apt install -y nginx"}} Example response: {{"dangerous":false,"reason":"","command":"sudo apt install -y nginx"}}
Example request: "erstelle einen cronjob der alle 5 minuten ein script ausfuehrt" Example request: "erstelle einen cronjob der alle 5 minuten ein script ausfuehrt"
Example response: {{"dangerous":false,"reason":"","command":"echo '*/5 * * * * root /path/to/script.sh' | sudo tee /etc/cron.d/myjob"}} Example response: {{"dangerous":false,"reason":"","command":"echo '*/5 * * * * root /path/to/script.sh' | sudo tee /etc/cron.d/myjob"}}
Example request: "schreibe hello world in eine datei" Example request: "schreibe hello world in eine datei"
Example response: {{"dangerous":false,"reason":"","command":"echo 'hello world' | sudo tee /tmp/hello.txt"}} Example response: {{"dangerous":false,"reason":"","command":"echo 'hello world' | sudo tee /tmp/hello.txt"}}
Example request: "starte nginx neu" Example request: "starte nginx neu"
Example response: {{"dangerous":false,"reason":"","command":"sudo systemctl restart nginx"}} Example response: {{"dangerous":false,"reason":"","command":"sudo systemctl restart nginx"}}
Example request: "lösche alles in /etc" Example request: "lösche alles in /etc"
Example response: {{"dangerous":true,"reason":"Würde Systemkonfiguration zerstören","command":"rm -rf /etc/*"}} Example response: {{"dangerous":true,"reason":"Würde Systemkonfiguration zerstören","command":"rm -rf /etc/*"}}
Now generate JSON for this request: "{description}" Now generate JSON for this request: "{description}"
IMPORTANT: Respond with ONLY the JSON object. No other text. No markdown.""" IMPORTANT: Respond with ONLY the JSON object. No other text. No markdown."""
CHAT_SYSTEM_PROMPT = """Du bist der Clownfischserver KI-Assistent. Du hilfst beim Verwalten eines Linux-Servers. CHAT_SYSTEM_PROMPT = """Du bist der Clownfischserver KI-Assistent. Du hilfst beim Verwalten eines Linux-Servers.
Antworte kurz und technisch. Antworte IMMER in der Sprache in der der Nutzer schreibt. Antworte kurz und technisch. Antworte IMMER in der Sprache in der der Nutzer schreibt.
Wenn du ein Befehlsergebnis erklärst, sei präzise und verständlich.""" Wenn du ein Befehlsergebnis erklärst, sei präzise und verständlich."""
def _extract_json(raw: str) -> dict: def _extract_json(raw: str) -> dict:
"""Extract JSON from Ollama response, handling markdown wrappers and stray text.""" """Extract JSON from Ollama response, handling markdown wrappers and stray text."""
text = raw.strip() text = raw.strip()
text = re.sub(r"^```(?:json)?\s*", "", text) text = re.sub(r"^```(?:json)?\s*", "", text)
text = re.sub(r"\s*```$", "", text) text = re.sub(r"\s*```$", "", text)
text = text.strip() text = text.strip()
try: try:
return json.loads(text) return json.loads(text)
except json.JSONDecodeError: except json.JSONDecodeError:
pass pass
match = re.search(r"\{[^{}]*\}", text, re.DOTALL) match = re.search(r"\{[^{}]*\}", text, re.DOTALL)
if match: if match:
try: try:
return json.loads(match.group()) return json.loads(match.group())
except json.JSONDecodeError: except json.JSONDecodeError:
pass pass
raise json.JSONDecodeError("No valid JSON found", text, 0) raise json.JSONDecodeError("No valid JSON found", text, 0)
class OllamaClient: class OllamaClient:
def __init__(self, openrouter_client=None): def __init__(self, openrouter_client=None, model: Optional[str] = None,
self.base_url = OLLAMA_BASE_URL model_fast: Optional[str] = None,
self.model = OLLAMA_MODEL num_ctx: Optional[int] = None,
self.model_fast = OLLAMA_MODEL_FAST or OLLAMA_MODEL base_url: Optional[str] = None):
self.openrouter = openrouter_client self.base_url = base_url or OLLAMA_BASE_URL
self.model = model or OLLAMA_MODEL
def _chat_sync(self, messages: list, system: Optional[str] = None, think: Optional[bool] = None, use_fast: bool = False) -> str: self.model_fast = model_fast or OLLAMA_MODEL_FAST or self.model
"""Synchronous Ollama API call""" self.num_ctx = num_ctx if num_ctx is not None else OLLAMA_NUM_CTX
model = self.model_fast if use_fast else self.model self.openrouter = openrouter_client
payload = {
"model": model, def _chat_sync(self, messages: list, system: Optional[str] = None, think: Optional[bool] = None, use_fast: bool = False) -> str:
"messages": messages, """Synchronous Ollama API call"""
"stream": False, model = self.model_fast if use_fast else self.model
"keep_alive": -1, payload = {
"options": {"num_ctx": OLLAMA_NUM_CTX}, "model": model,
} "messages": messages,
if system: "stream": False,
payload["system"] = system "keep_alive": -1,
if think is not None: "options": {"num_ctx": self.num_ctx},
payload["think"] = think }
if system:
try: payload["system"] = system
response = requests.post( if think is not None:
f"{self.base_url}/api/chat", payload["think"] = think
json=payload,
timeout=180, try:
) response = requests.post(
response.raise_for_status() f"{self.base_url}/api/chat",
data = response.json() json=payload,
return data.get("message", {}).get("content", "") timeout=180,
except requests.exceptions.ConnectionError: )
raise RuntimeError("Ollama nicht erreichbar – läuft der Service? (systemctl status ollama)") response.raise_for_status()
except requests.exceptions.Timeout: data = response.json()
raise RuntimeError("Ollama Timeout – Modell lädt möglicherweise noch.") return data.get("message", {}).get("content", "")
except Exception as e: except requests.exceptions.ConnectionError:
raise RuntimeError(f"Ollama Fehler: {e}") raise RuntimeError("Ollama nicht erreichbar – läuft der Service? (systemctl status ollama)")
except requests.exceptions.Timeout:
async def generate_shell_command(self, description: str) -> dict: raise RuntimeError("Ollama Timeout – Modell lädt möglicherweise noch.")
"""Generate a shell command from natural language description. except Exception as e:
Tries Ollama first, falls back to OpenRouter on timeout.""" raise RuntimeError(f"Ollama Fehler: {e}")
loop = asyncio.get_running_loop()
raw = "" async def generate_shell_command(self, description: str) -> dict:
"""Generate a shell command from natural language description.
# 1. Try local Ollama Tries Ollama first, falls back to OpenRouter on timeout."""
try: loop = asyncio.get_running_loop()
prompt = SHELL_PROMPT_TEMPLATE.format(description=description) raw = ""
raw = await loop.run_in_executor(
None, # 1. Try local Ollama
lambda: self._chat_sync( try:
messages=[{"role": "user", "content": prompt}], prompt = SHELL_PROMPT_TEMPLATE.format(description=description)
think=False, raw = await loop.run_in_executor(
use_fast=False, None,
), lambda: self._chat_sync(
) messages=[{"role": "user", "content": prompt}],
result = _extract_json(raw) think=False,
use_fast=False,
if "command" not in result or not result["command"].strip(): ),
logger.warning(f"Shell generate: no command in result: {result}") )
return {"dangerous": False, "reason": "", "command": ""} result = _extract_json(raw)
if "dangerous" not in result:
result["dangerous"] = False if "command" not in result or not result["command"].strip():
logger.warning(f"Shell generate: no command in result: {result}")
logger.info(f"Shell generate (Ollama): {result}") return {"dangerous": False, "reason": "", "command": ""}
return result if "dangerous" not in result:
result["dangerous"] = False
except json.JSONDecodeError as e:
logger.warning(f"Shell generate JSON error: {e}, raw: {raw[:500]}") logger.info(f"Shell generate (Ollama): {result}")
return {"dangerous": False, "reason": "", "command": ""} return result
except RuntimeError as e:
if "Timeout" not in str(e) and "nicht erreichbar" not in str(e): except json.JSONDecodeError as e:
raise logger.warning(f"Shell generate JSON error: {e}, raw: {raw[:500]}")
logger.warning("Ollama nicht verfügbar für /shell – trying OpenRouter fallback") return {"dangerous": False, "reason": "", "command": ""}
except RuntimeError as e:
# 2. Fallback to OpenRouter if "Timeout" not in str(e) and "nicht erreichbar" not in str(e):
if self.openrouter and self.openrouter.is_available(): raise
try: logger.warning("Ollama nicht verfügbar für /shell – trying OpenRouter fallback")
logger.info("Using OpenRouter fallback for /shell...")
result = await self.openrouter.generate_shell_command(description) # 2. Fallback to OpenRouter
logger.info(f"Shell generate (OpenRouter): {result}") if self.openrouter and self.openrouter.is_available():
return result try:
except Exception as e: logger.info("Using OpenRouter fallback for /shell...")
logger.error(f"OpenRouter fallback failed: {e}") result = await self.openrouter.generate_shell_command(description)
logger.info(f"Shell generate (OpenRouter): {result}")
return { return result
"dangerous": False, "reason": "", except Exception as e:
"command": "", logger.error(f"OpenRouter fallback failed: {e}")
"_error": "Ollama Timeout und kein OpenRouter Fallback verfügbar.",
} return {
"dangerous": False, "reason": "",
async def explain_output(self, command: str, output: str, error: str = "") -> str: "command": "",
"""Ask Ollama to explain/summarize command output""" "_error": "Ollama Timeout und kein OpenRouter Fallback verfügbar.",
loop = asyncio.get_running_loop() }
content = f"Command: {command}\nOutput:\n{output}" async def explain_output(self, command: str, output: str, error: str = "") -> str:
if error: """Ask Ollama to explain/summarize command output"""
content += f"\nErrors:\n{error}" loop = asyncio.get_running_loop()
content += "\n\nErkläre kurz was passiert ist und ob es Probleme gibt. Antworte in der gleichen Sprache wie der Nutzer."
content = f"Command: {command}\nOutput:\n{output}"
try: if error:
return await loop.run_in_executor( content += f"\nErrors:\n{error}"
None, content += "\n\nErkläre kurz was passiert ist und ob es Probleme gibt. Antworte in der gleichen Sprache wie der Nutzer."
lambda: self._chat_sync(
messages=[{"role": "user", "content": content}], try:
system=CHAT_SYSTEM_PROMPT, return await loop.run_in_executor(
think=False, None,
use_fast=True, lambda: self._chat_sync(
), messages=[{"role": "user", "content": content}],
) system=CHAT_SYSTEM_PROMPT,
except Exception as e: think=False,
logger.error(f"explain_output failed: {e}") use_fast=True,
# Try OpenRouter fallback ),
if self.openrouter and self.openrouter.is_available(): )
try: except Exception as e:
return await self.openrouter.explain_output(command, output, error) logger.error(f"explain_output failed: {e}")
except Exception: # Try OpenRouter fallback
pass if self.openrouter and self.openrouter.is_available():
return "" try:
return await self.openrouter.explain_output(command, output, error)
async def chat(self, message: str, history: list = None) -> str: except Exception:
"""General chat with context. Tries Ollama, falls back to OpenRouter.""" pass
loop = asyncio.get_running_loop() return ""
messages = list(history) if history else []
messages.append({"role": "user", "content": message}) async def chat(self, message: str, history: list = None) -> str:
"""General chat with context. Tries Ollama, falls back to OpenRouter."""
# 1. Try local Ollama loop = asyncio.get_running_loop()
try: messages = list(history) if history else []
return await loop.run_in_executor( messages.append({"role": "user", "content": message})
None,
lambda: self._chat_sync( # 1. Try local Ollama
messages=messages, try:
system=CHAT_SYSTEM_PROMPT, return await loop.run_in_executor(
use_fast=True, None,
), lambda: self._chat_sync(
) messages=messages,
except RuntimeError as e: system=CHAT_SYSTEM_PROMPT,
if "Timeout" not in str(e) and "nicht erreichbar" not in str(e): use_fast=True,
return f"Fehler: {e}" ),
logger.warning("Ollama chat nicht verfügbar – trying OpenRouter") )
except RuntimeError as e:
# 2. Fallback to OpenRouter if "Timeout" not in str(e) and "nicht erreichbar" not in str(e):
if self.openrouter and self.openrouter.is_available(): return f"Fehler: {e}"
try: logger.warning("Ollama chat nicht verfügbar – trying OpenRouter")
logger.info("Using OpenRouter for chat...")
return await self.openrouter.chat(message, history) # 2. Fallback to OpenRouter
except Exception as e: if self.openrouter and self.openrouter.is_available():
return f"Ollama und OpenRouter nicht verfügbar: {e}" try:
logger.info("Using OpenRouter for chat...")
return ( return await self.openrouter.chat(message, history)
"Ollama nicht verfügbar und kein OpenRouter Fallback konfiguriert.\n" except Exception as e:
"Versuche es später oder konfiguriere OpenRouter in .env" return f"Ollama und OpenRouter nicht verfügbar: {e}"
)
return (
"Ollama nicht verfügbar und kein OpenRouter Fallback konfiguriert.\n"
"Versuche es später oder konfiguriere OpenRouter in .env"
)
+183 -181
View File
@@ -1,181 +1,183 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
""" """
🐠 Clownfischserver – OpenRouter Free Models Fallback 🐠 Clownfischserver – OpenRouter Free Models Fallback
Author: Mehlzoerwer-Claude (https://github.com/mehlzoerwer-claude) Author: Mehlzoerwer-Claude (https://github.com/mehlzoerwer-claude)
License: GPL-3.0 – Keep it open. Always. License: GPL-3.0 – Keep it open. Always.
Repo: https://github.com/mehlzoerwer-claude/clownfischserver Repo: https://github.com/mehlzoerwer-claude/clownfischserver
""" """
import json import json
import logging import logging
import os import os
import re import re
import asyncio import asyncio
import requests import requests
from typing import Optional from typing import Optional
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "") OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "")
OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1" OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"
# Free models on OpenRouter (no credit card needed) # Free models on OpenRouter (no credit card needed)
# openrouter/free auto-selects the best available free model # openrouter/free auto-selects the best available free model
FREE_MODELS = { FREE_MODELS = {
"coder": "openrouter/free", "coder": "openrouter/free",
"chat": "openrouter/free", "chat": "openrouter/free",
} }
def _extract_json(raw: str) -> dict: def _extract_json(raw: str) -> dict:
"""Extract JSON from response.""" """Extract JSON from response."""
text = raw.strip() text = raw.strip()
text = re.sub(r"^```(?:json)?\s*", "", text) text = re.sub(r"^```(?:json)?\s*", "", text)
text = re.sub(r"\s*```$", "", text) text = re.sub(r"\s*```$", "", text)
text = text.strip() text = text.strip()
try: try:
return json.loads(text) return json.loads(text)
except json.JSONDecodeError: except json.JSONDecodeError:
pass pass
match = re.search(r"\{[^{}]*\}", text, re.DOTALL) match = re.search(r"\{[^{}]*\}", text, re.DOTALL)
if match: if match:
try: try:
return json.loads(match.group()) return json.loads(match.group())
except json.JSONDecodeError: except json.JSONDecodeError:
pass pass
raise json.JSONDecodeError("No valid JSON found", text, 0) raise json.JSONDecodeError("No valid JSON found", text, 0)
class OpenRouterClient: class OpenRouterClient:
"""OpenRouter Free Models Client – fallback when Ollama times out.""" """OpenRouter Free Models Client – fallback when Ollama times out."""
def __init__(self): def __init__(self):
self.api_key = OPENROUTER_API_KEY # Read at construction time, not import time, so env changes between
self.base_url = OPENROUTER_BASE_URL # boot and config reloads (or test monkeypatching) take effect.
if self.api_key: self.api_key = os.getenv("OPENROUTER_API_KEY", "") or OPENROUTER_API_KEY
logger.info("OpenRouter Fallback konfiguriert") self.base_url = OPENROUTER_BASE_URL
else: if self.api_key:
logger.info("OpenRouter nicht konfiguriert – Fallback deaktiviert") logger.info("OpenRouter Fallback konfiguriert")
else:
def is_available(self) -> bool: logger.info("OpenRouter nicht konfiguriert – Fallback deaktiviert")
return bool(self.api_key)
def is_available(self) -> bool:
def _chat_sync(self, messages: list, system: Optional[str] = None, model: str = None) -> str: return bool(self.api_key)
"""Synchronous OpenRouter API call."""
if not self.api_key: def _chat_sync(self, messages: list, system: Optional[str] = None, model: str = None) -> str:
raise RuntimeError("OpenRouter API Key nicht konfiguriert") """Synchronous OpenRouter API call."""
if not self.api_key:
model = model or FREE_MODELS["chat"] raise RuntimeError("OpenRouter API Key nicht konfiguriert")
api_messages = [] model = model or FREE_MODELS["chat"]
if system:
api_messages.append({"role": "system", "content": system}) api_messages = []
api_messages.extend(messages) if system:
api_messages.append({"role": "system", "content": system})
try: api_messages.extend(messages)
response = requests.post(
f"{self.base_url}/chat/completions", try:
headers={ response = requests.post(
"Authorization": f"Bearer {self.api_key}", f"{self.base_url}/chat/completions",
"Content-Type": "application/json", headers={
}, "Authorization": f"Bearer {self.api_key}",
json={ "Content-Type": "application/json",
"model": model, },
"messages": api_messages, json={
"temperature": 0.7, "model": model,
}, "messages": api_messages,
timeout=60, "temperature": 0.7,
) },
response.raise_for_status() timeout=60,
data = response.json() )
return data.get("choices", [{}])[0].get("message", {}).get("content", "") response.raise_for_status()
except requests.exceptions.ConnectionError: data = response.json()
raise RuntimeError("OpenRouter nicht erreichbar") return data.get("choices", [{}])[0].get("message", {}).get("content", "")
except requests.exceptions.Timeout: except requests.exceptions.ConnectionError:
raise RuntimeError("OpenRouter Timeout") raise RuntimeError("OpenRouter nicht erreichbar")
except Exception as e: except requests.exceptions.Timeout:
raise RuntimeError(f"OpenRouter Fehler: {e}") raise RuntimeError("OpenRouter Timeout")
except Exception as e:
async def generate_shell_command(self, description: str) -> dict: raise RuntimeError(f"OpenRouter Fehler: {e}")
"""Generate shell command via OpenRouter."""
loop = asyncio.get_running_loop() async def generate_shell_command(self, description: str) -> dict:
"""Generate shell command via OpenRouter."""
system = "Server: Ubuntu 24.04, Clownfischserver setup." loop = asyncio.get_running_loop()
prompt = ( system = "Server: Ubuntu 24.04, Clownfischserver setup."
"You are a Linux bash command generator for Ubuntu 24.04.\n"
"Convert the request into a single non-interactive bash command.\n" prompt = (
"Respond ONLY with JSON: {\"dangerous\": bool, \"reason\": string, \"command\": string}\n" "You are a Linux bash command generator for Ubuntu 24.04.\n"
"No interactive commands (nano, vim, crontab -e). Use sudo when needed.\n\n" "Convert the request into a single non-interactive bash command.\n"
f"Request: {description}\n\nJSON only:" "Respond ONLY with JSON: {\"dangerous\": bool, \"reason\": string, \"command\": string}\n"
) "No interactive commands (nano, vim, crontab -e). Use sudo when needed.\n\n"
f"Request: {description}\n\nJSON only:"
try: )
raw = await loop.run_in_executor(
None, try:
lambda: self._chat_sync( raw = await loop.run_in_executor(
messages=[{"role": "user", "content": prompt}], None,
system=system, lambda: self._chat_sync(
model=FREE_MODELS["coder"], messages=[{"role": "user", "content": prompt}],
), system=system,
) model=FREE_MODELS["coder"],
result = _extract_json(raw) ),
if "command" not in result: )
result["command"] = "" result = _extract_json(raw)
if "dangerous" not in result: if "command" not in result:
result["dangerous"] = False result["command"] = ""
logger.info(f"OpenRouter shell: {result}") if "dangerous" not in result:
return result result["dangerous"] = False
except json.JSONDecodeError as e: logger.info(f"OpenRouter shell: {result}")
logger.warning(f"OpenRouter JSON error: {e}") return result
return {"dangerous": False, "reason": "", "command": ""} except json.JSONDecodeError as e:
except Exception as e: logger.warning(f"OpenRouter JSON error: {e}")
logger.error(f"OpenRouter shell failed: {e}") return {"dangerous": False, "reason": "", "command": ""}
raise except Exception as e:
logger.error(f"OpenRouter shell failed: {e}")
async def chat(self, message: str, history: list = None) -> str: raise
"""General chat via OpenRouter."""
loop = asyncio.get_running_loop() async def chat(self, message: str, history: list = None) -> str:
messages = list(history) if history else [] """General chat via OpenRouter."""
messages.append({"role": "user", "content": message}) loop = asyncio.get_running_loop()
messages = list(history) if history else []
system = ( messages.append({"role": "user", "content": message})
"Du bist der Clownfischserver KI-Assistent. Du hilfst beim Verwalten eines Linux-Servers.\n"
"Antworte kurz und technisch. Antworte IMMER in der Sprache in der der Nutzer schreibt." system = (
) "Du bist der Clownfischserver KI-Assistent. Du hilfst beim Verwalten eines Linux-Servers.\n"
"Antworte kurz und technisch. Antworte IMMER in der Sprache in der der Nutzer schreibt."
try: )
return await loop.run_in_executor(
None, try:
lambda: self._chat_sync( return await loop.run_in_executor(
messages=messages, None,
system=system, lambda: self._chat_sync(
model=FREE_MODELS["chat"], messages=messages,
), system=system,
) model=FREE_MODELS["chat"],
except Exception as e: ),
return f"OpenRouter Fehler: {e}" )
except Exception as e:
async def explain_output(self, command: str, output: str, error: str = "") -> str: return f"OpenRouter Fehler: {e}"
"""Explain command output via OpenRouter."""
loop = asyncio.get_running_loop() async def explain_output(self, command: str, output: str, error: str = "") -> str:
"""Explain command output via OpenRouter."""
content = f"Command: {command}\nOutput:\n{output}" loop = asyncio.get_running_loop()
if error:
content += f"\nErrors:\n{error}" content = f"Command: {command}\nOutput:\n{output}"
content += "\n\nErkläre kurz was passiert ist und ob es Probleme gibt. Antworte in der gleichen Sprache wie der Nutzer." if error:
content += f"\nErrors:\n{error}"
try: content += "\n\nErkläre kurz was passiert ist und ob es Probleme gibt. Antworte in der gleichen Sprache wie der Nutzer."
return await loop.run_in_executor(
None, try:
lambda: self._chat_sync( return await loop.run_in_executor(
messages=[{"role": "user", "content": content}], None,
model=FREE_MODELS["chat"], lambda: self._chat_sync(
), messages=[{"role": "user", "content": content}],
) model=FREE_MODELS["chat"],
except Exception as e: ),
logger.error(f"OpenRouter explain failed: {e}") )
return "" except Exception as e:
logger.error(f"OpenRouter explain failed: {e}")
return ""
+73 -30
View File
@@ -1,30 +1,73 @@
# 🐠 Clownfischserver – Konfiguration # 🐠 Clownfischserver – Konfiguration
# Diese Datei wird automatisch durch install.sh erstellt. # Diese Datei wird automatisch durch install.sh erstellt.
# Niemals diese Datei committen oder teilen! # Niemals diese Datei committen oder teilen!
# Telegram # Telegram
TELEGRAM_BOT_TOKEN=123456789:ABCdefGHIjklMNOpqrSTUvwxYZ TELEGRAM_BOT_TOKEN=123456789:ABCdefGHIjklMNOpqrSTUvwxYZ
TELEGRAM_CHAT_ID=987654321 # Legacy single-user mode: dieser Nutzer bekommt automatisch die operator-Rolle,
# wenn keine CLOWNFISCH_* Rollen-Variablen gesetzt sind (v0.4-Kompatibilität).
# Ollama TELEGRAM_CHAT_ID=987654321
OLLAMA_BASE_URL=http://localhost:11434
OLLAMA_MODEL=qwen2.5-coder:7b # === Team-Rollen (v0.5.0) ===========================================
OLLAMA_MODEL_FAST=gemma3:4b # Kommagetrennte Telegram User-IDs (nicht Chat-IDs!).
OLLAMA_NUM_CTX=16384 # Operator = darf /shell /code /run /ja /ssh /snapshot /rollback ausführen
# Approver = darf /ja (Bestätigungen) ausführen
# OpenRouter (optional – kostenloser Fallback bei Ollama-Timeout) # Viewer = darf /start /help /status /snapshots /chat lesen
# API Key von openrouter.ai (kostenlos, keine Kreditkarte) # Inheritance: operator > approver > viewer (höhere Rolle erbt niedrigere Rechte).
# OPENROUTER_API_KEY=sk-or-v1-... # CLOWNFISCH_OPERATORS=12345,67890
# CLOWNFISCH_APPROVERS=11111
# Snapshots # CLOWNFISCH_VIEWERS=22222,33333
SNAPSHOT_DIR=/opt/clownfisch-snapshots
SNAPSHOT_METHOD=tar # === Audit-Trail (DSGVO Art. 5, 32) =================================
# Pfad zur JSON-Lines-Audit-Datei. Default: $INSTALL_DIR/audit.jsonl
# HomeIP Auto-Update (optional – myfritz.net Dynamic DNS) # AUDIT_LOG_PATH=/opt/clownfischserver/audit.jsonl
# Domain für automatische Firewall-Regel-Updates bei IP-Wechsel # Aufbewahrungsdauer in Tagen (Art. 5(1)(e) – Storage Limitation).
# CLOWNFISCHSERVER_HOME_IP_DOMAIN=vorname.myfritz.net # Beim Bot-Start werden ältere Einträge automatisch entfernt. 0 = nie löschen.
AUDIT_RETENTION_DAYS=90
# Paths # Maximale Länge eines Audit-Detailfeldes (Datenminimierung).
INSTALL_DIR=/opt/clownfischserver AUDIT_MAX_DETAIL_LEN=2000
MGMT_USER=clownfish
AIDER_WORKDIR=/opt/clownfisch-workspace # Ollama
OLLAMA_BASE_URL=http://localhost:11434
OLLAMA_MODEL=qwen2.5-coder:7b
OLLAMA_MODEL_FAST=gemma3:4b
OLLAMA_NUM_CTX=16384
# OpenRouter (optional – kostenloser Fallback bei Ollama-Timeout)
# API Key von openrouter.ai (kostenlos, keine Kreditkarte)
# OPENROUTER_API_KEY=sk-or-v1-...
# === LLM Routing (v0.5.0, Phase 3) ==================================
# Konfiguriert welches Modell als Primary und welches als Fallback genutzt wird.
# Wenn nicht gesetzt: defaultet auf Ollama primary, OpenRouter fallback (sofern
# OPENROUTER_API_KEY gesetzt ist). Damit bleibt das v0.4-Verhalten erhalten.
#
# Primary (für sensible Daten – läuft lokal, keine Cloud)
# LLM_PRIMARY_PROVIDER=ollama
# LLM_PRIMARY_MODEL=qwen2.5-coder:7b
# LLM_PRIMARY_MODEL_FAST=gemma3:4b
# Gemma 4 27B benötigt mindestens 64K Token Kontext – sonst halluziniert das Modell.
# Override pro Provider (überschreibt OLLAMA_NUM_CTX).
# LLM_PRIMARY_NUM_CTX=65536
#
# Fallback (nur falls Primary nicht erreichbar / Timeout)
# LLM_FALLBACK_PROVIDER=openrouter
# LLM_FALLBACK_MODEL=deepseek/deepseek-r1:free
# Wert "none" oder leer = Fallback explizit deaktivieren
# LLM_FALLBACK_PROVIDER=none
#
# Optional: Kostentracking für Admins (informativ, keine Limit-Erzwingung).
# TRACK_LLM_COSTS=true
# Snapshots
SNAPSHOT_DIR=/opt/clownfisch-snapshots
SNAPSHOT_METHOD=tar
# HomeIP Auto-Update (optional – myfritz.net Dynamic DNS)
# Domain für automatische Firewall-Regel-Updates bei IP-Wechsel
# CLOWNFISCHSERVER_HOME_IP_DOMAIN=vorname.myfritz.net
# Paths
INSTALL_DIR=/opt/clownfischserver
MGMT_USER=clownfish
AIDER_WORKDIR=/opt/clownfisch-workspace