diff --git a/API_REFERENCE.md b/API_REFERENCE.md index 5e11572..b83a647 100644 --- a/API_REFERENCE.md +++ b/API_REFERENCE.md @@ -166,6 +166,68 @@ X-API-Key: your-api-key } ``` +### Session Management API Endpoints + +#### POST /api/license/session/start +Start a new session for a license. + +**Headers:** +``` +X-API-Key: AF-2025-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX +Content-Type: application/json +``` + +**Request:** +```json +{ + "license_key": "XXXX-XXXX-XXXX-XXXX", + "machine_id": "DESKTOP-ABC123", + "hardware_hash": "unique-hardware-identifier", + "version": "1.0.0" +} +``` + +**Response:** +- 200 OK: Returns session_token and optional update info +- 409 Conflict: "Es ist nur eine Sitzung erlaubt..." (single session enforcement) + +#### POST /api/license/session/heartbeat +Keep session alive with heartbeat. + +**Headers:** +``` +X-API-Key: AF-2025-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX +Content-Type: application/json +``` + +**Request:** +```json +{ + "session_token": "550e8400-e29b-41d4-a716-446655440000", + "license_key": "XXXX-XXXX-XXXX-XXXX" +} +``` + +**Response:** 200 OK with last_heartbeat timestamp + +#### POST /api/license/session/end +End an active session. + +**Headers:** +``` +X-API-Key: AF-2025-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX +Content-Type: application/json +``` + +**Request:** +```json +{ + "session_token": "550e8400-e29b-41d4-a716-446655440000" +} +``` + +**Response:** 200 OK with session duration and end reason + ### Version API Endpoints #### POST /api/version/check @@ -184,16 +246,7 @@ X-API-Key: your-api-key } ``` -**Response:** -```json -{ - "update_available": true, - "latest_version": "1.1.0", - "download_url": "https://example.com/download/v1.1.0", - "release_notes": "Bug fixes and performance improvements", - "is_mandatory": false -} -``` +**Response:** Update availability status with version info #### GET /api/version/latest Get latest version information. @@ -203,16 +256,7 @@ Get latest version information. X-API-Key: your-api-key ``` -**Response:** -```json -{ - "version": "1.1.0", - "release_date": "2025-06-15", - "download_url": "https://example.com/download/v1.1.0", - "release_notes": "Bug fixes and performance improvements", - "is_mandatory": false -} -``` +**Response:** Latest version information ## Admin Panel API @@ -240,109 +284,17 @@ Search customers for Select2 dropdown. } ``` -#### GET /api/customer/{customer_id}/licenses -Get licenses for a specific customer. - -**Response:** -```json -{ - "licenses": [ - { - "id": 456, - "license_key": "XXXX-XXXX-XXXX-XXXX", - "type": "perpetual", - "status": "active", - "valid_until": "2026-01-01", - "max_activations": 5, - "current_activations": 3 - } - ] -} -``` - -#### GET /api/customer/{customer_id}/quick-stats -Get quick statistics for a customer. - -**Response:** -```json -{ - "total_licenses": 10, - "active_licenses": 8, - "total_activations": 25, - "total_users": 150 -} -``` +- `GET /api/customer/{id}/licenses` - List customer's licenses +- `GET /api/customer/{id}/quick-stats` - License and activation counts ### License Management API -#### POST /api/license/{license_id}/toggle -Toggle license active status. - -**Response:** -```json -{ - "success": true, - "is_active": true, - "message": "License activated successfully" -} -``` - -#### POST /api/licenses/bulk-activate -Activate multiple licenses. - -**Request:** -```json -{ - "license_ids": [1, 2, 3] -} -``` - -**Response:** -```json -{ - "success": true, - "count": 3, - "message": "3 licenses activated successfully" -} -``` - -#### POST /api/licenses/bulk-deactivate -Deactivate multiple licenses. - -**Request:** -```json -{ - "license_ids": [1, 2, 3] -} -``` - -**Response:** -```json -{ - "success": true, - "count": 3, - "message": "3 licenses deactivated successfully" -} -``` - -#### POST /api/licenses/bulk-delete -Delete multiple licenses. - -**Request:** -```json -{ - "license_ids": [1, 2, 3] -} -``` - -**Response:** -```json -{ - "success": true, - "deleted": 3, - "message": "3 licenses deleted successfully" -} -``` +- `POST /api/license/{id}/toggle` - Toggle active status +- `POST /api/licenses/bulk-activate` - Activate multiple (license_ids array) +- `POST /api/licenses/bulk-deactivate` - Deactivate multiple +- `POST /api/licenses/bulk-delete` - Delete multiple +- `POST /api/license/{id}/quick-edit` - Update validity/limits +- `GET /api/license/{id}/devices` - List registered devices #### POST /api/license/{license_id}/quick-edit Quick edit license properties. @@ -547,7 +499,181 @@ Global search across all entities. } ``` -### Session Management API +### Lead Management API + +#### GET /leads/api/institutions +Get all institutions with pagination. + +**Query Parameters:** +- `page`: Page number (default: 1) +- `per_page`: Items per page (default: 20) +- `search`: Search query + +**Response:** +```json +{ + "institutions": [ + { + "id": 1, + "name": "Tech University", + "contact_count": 5, + "created_at": "2025-06-19T10:00:00Z" + } + ], + "total": 100, + "page": 1, + "per_page": 20 +} +``` + +#### POST /leads/api/institutions +Create a new institution. + +**Request:** +```json +{ + "name": "New University" +} +``` + +**Response:** +```json +{ + "id": 101, + "name": "New University", + "created_at": "2025-06-19T15:00:00Z" +} +``` + +#### GET /leads/api/contacts/{contact_id} +Get contact details. + +**Response:** +```json +{ + "id": 1, + "first_name": "John", + "last_name": "Doe", + "position": "IT Manager", + "institution_id": 1, + "details": [ + { + "id": 1, + "type": "email", + "value": "john.doe@example.com", + "label": "Work" + }, + { + "id": 2, + "type": "phone", + "value": "+49 123 456789", + "label": "Mobile" + } + ], + "notes": [ + { + "id": 1, + "content": "Initial contact", + "version": 1, + "created_at": "2025-06-19T10:00:00Z", + "created_by": "admin" + } + ] +} +``` + +#### POST /leads/api/contacts/{contact_id}/details +Add contact detail (phone/email). + +**Request:** +```json +{ + "type": "email", + "value": "secondary@example.com", + "label": "Secondary" +} +``` + +**Response:** +```json +{ + "id": 3, + "type": "email", + "value": "secondary@example.com", + "label": "Secondary" +} +``` + +### Resource Management API + +#### GET /api/resources/availability +Get resource availability for license allocation. + +**Response:** +```json +{ + "domains": { + "available": 150, + "total": 200, + "status": "ok" + }, + "ipv4": { + "available": 45, + "total": 100, + "status": "low" + }, + "phone_numbers": { + "available": 5, + "total": 50, + "status": "critical" + } +} +``` + +#### POST /api/resources/allocate +Allocate resources to a license. + +**Request:** +```json +{ + "license_id": 123, + "resource_type": "domain", + "resource_ids": [45, 46, 47] +} +``` + +**Response:** +```json +{ + "success": true, + "allocated": 3, + "message": "3 resources allocated successfully" +} +``` + +### Monitoring API + +#### GET /api/monitoring/dashboard +Get monitoring dashboard data. + +**Response:** +```json +{ + "metrics": { + "total_licenses": 1500, + "active_licenses": 1200, + "total_customers": 250, + "active_sessions": 890 + }, + "alerts": [ + { + "level": "warning", + "message": "High CPU usage on license server", + "timestamp": "2025-06-19T14:00:00Z" + } + ] +} +``` #### GET /api/sessions/active-count Get count of active sessions. @@ -654,127 +780,37 @@ Get lead statistics. - `500 Internal Server Error`: Server error ## Rate Limiting - -- Public API: 100 requests per minute per IP -- Admin API: 1000 requests per minute per token -- Heartbeat endpoint: 1 request per minute per activation +- API endpoints: 100 requests/minute +- Login attempts: 5 per minute +- Configurable via Admin Panel ## Error Response Format +All errors return JSON with `error`, `code`, and `status` fields. -```json -{ - "error": { - "code": "INVALID_LICENSE", - "message": "The provided license key is invalid", - "details": { - "field": "license_key", - "reason": "format_invalid" - } - } -} -``` +## Client Integration -## Client Integration Examples - -### Python -```python -import requests -import json - -class LicenseClient: - def __init__(self, base_url): - self.base_url = base_url - - def activate(self, license_key, hardware_id): - response = requests.post( - f"{self.base_url}/api/v1/activate", - json={ - "license_key": license_key, - "hardware_id": hardware_id, - "machine_name": socket.gethostname(), - "app_version": "1.0.0" - } - ) - return response.json() - - def validate(self, license_key, activation_id, hardware_id): - response = requests.post( - f"{self.base_url}/api/v1/validate", - json={ - "license_key": license_key, - "activation_id": activation_id, - "hardware_id": hardware_id, - "app_version": "1.0.0" - } - ) - return response.json() -``` - -### C# Example -```csharp -public class LicenseClient -{ - private readonly HttpClient _httpClient; - private readonly string _baseUrl; - - public LicenseClient(string baseUrl) - { - _baseUrl = baseUrl; - _httpClient = new HttpClient(); - } - - public async Task ActivateAsync( - string licenseKey, - HardwareInfo hardwareId) - { - var request = new - { - license_key = licenseKey, - hardware_id = hardwareId, - machine_name = Environment.MachineName, - app_version = "1.0.0" - }; - - var response = await _httpClient.PostAsJsonAsync( - $"{_baseUrl}/api/v1/activate", - request - ); - - return await response.Content.ReadFromJsonAsync(); - } -} -``` - -## Webhooks - -### Configuration -Configure webhooks in the admin panel to receive notifications for: -- License activation -- License expiration -- Suspicious activity -- Usage threshold alerts - -### Webhook Payload -```json -{ - "event": "license.activated", - "timestamp": "2025-06-19T10:30:00Z", - "data": { - "license_id": 123, - "activation_id": "act_456", - "customer_id": 789 - } -} +Example request with required headers: +```bash +curl -X POST http://localhost/api/license/activate \ + -H "X-API-Key: AF-2025-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" \ + -H "Content-Type: application/json" \ + -d '{ + "license_key": "XXXX-XXXX-XXXX-XXXX", + "hardware_hash": "unique-hardware-id", + "machine_name": "DESKTOP-123", + "app_version": "1.0.0" + }' ``` ## Testing ### Test Credentials -- License Key: `TEST-TEST-TEST-TEST` -- API Key: `test_api_key_123` -- JWT Secret: `test_jwt_secret` +- Admin Users: + - Username: `rac00n` / Password: `1248163264` + - Username: `w@rh@mm3r` / Password: `Warhammer123!` +- API Key: Generated in Admin Panel under "Lizenzserver Administration" ### Test Endpoints -- Development: `http://localhost:8080` -- Staging: `https://staging-api.example.com` -- Production: `https://api.example.com` \ No newline at end of file +- Admin Panel: `http://localhost:80` +- License Server API: `http://localhost:80/api` +- Monitoring: See OPERATIONS_GUIDE.md \ No newline at end of file diff --git a/v2_adminpanel/CLAUDE.md b/CLAUDE.md similarity index 53% rename from v2_adminpanel/CLAUDE.md rename to CLAUDE.md index cb56b7a..725bab5 100644 --- a/v2_adminpanel/CLAUDE.md +++ b/CLAUDE.md @@ -7,34 +7,26 @@ ## Project Structure ``` v2_adminpanel/ -├── routes/ # Blueprint-based route handlers +├── routes/ # Blueprint route handlers ├── templates/ # Jinja2 templates -├── utils/ # Utility modules -├── leads/ # Leads module with own templates/routes -└── core/ # Core functionality (error handlers, logging, monitoring) +├── utils/ # Utilities +├── leads/ # CRM module (service/repository pattern) +├── core/ # Error handling, logging, monitoring +└── middleware/ # Request processing ``` ## Database Schema Reference -### license_heartbeats -```sql -- id BIGSERIAL -- license_id INTEGER -- hardware_id VARCHAR(255) -- ip_address INET -- user_agent VARCHAR(500) -- app_version VARCHAR(50) -- timestamp TIMESTAMP -- session_data JSONB -(NO response_time column!) -``` +### Key Database Tables -### Common Tables -- `customers` - Customer records -- `licenses` - License keys and configuration -- `users` - Admin panel users -- `anomaly_detections` - Security anomaly tracking -- `audit_log` - System audit trail +Refer to `v2_adminpanel/init.sql` for complete schema. Important tables: +- `license_heartbeats` - Partitioned by month, NO response_time column +- `license_sessions` - Active sessions (UNIQUE per license_id) +- `session_history` - Audit trail with end_reason +- `client_configs` - API configuration for Account Forger +- `system_api_key` - Global API key management + +Additional tables: customers, licenses, users, audit_log, lead_*, resource_pools, activations, feature_flags, rate_limits ## Template Parameter Contracts @@ -55,17 +47,12 @@ render_template('error.html', ## Pre-Implementation Checklist -### Before Writing Routes -- [ ] Check if similar route exists with `grep -r "route_name" .` -- [ ] Verify template exists and check expected parameters -- [ ] Confirm all imported modules exist -- [ ] Check if login_required decorator is needed - -### Before Database Queries -- [ ] Verify table exists in init.sql -- [ ] Confirm all column names with `grep "CREATE TABLE table_name" -A 20` -- [ ] Check for required indexes -- [ ] Consider partition requirements for time-series data +### Pre-Implementation Checklist +- Check existing routes: `grep -r "route_name" .` +- Verify template parameters match expectations +- Confirm table/column exists in init.sql +- Use RealDictCursor and handle cleanup in finally blocks +- Check leads/ for existing repository methods ### Before Modifying Templates - [ ] Check which routes use this template @@ -97,6 +84,25 @@ finally: conn.close() ``` +### API Authentication +```python +# Check API key +api_key = request.headers.get('X-API-Key') +if not api_key or not verify_api_key(api_key): + return jsonify({'error': 'Invalid API key'}), 401 +``` + +### Session Management +```python +# For user sessions +if 'user_id' not in session: + return redirect(url_for('auth.login')) + +# For 2FA +if session.get('requires_2fa'): + return redirect(url_for('auth.verify_2fa')) +``` + ## Testing & Verification ### Check Logs @@ -110,17 +116,15 @@ docker-compose ps ``` ### Common Issues to Avoid -1. **Parameter Mismatches**: Always verify template expectations -2. **Missing Columns**: Check schema before writing queries -3. **Import Errors**: Ensure utils/__init__.py exists -4. **Transaction Errors**: Properly handle PostgreSQL transactions -5. **Creating Unnecessary Files**: Check if functionality exists before creating new files +1. **Parameter Mismatches**: Verify template expectations (use `error` not `error_message`) +2. **Missing Columns**: Check schema before queries +3. **Creating Unnecessary Files**: Check if functionality exists first +4. **Missing Audit Logs**: Add audit_log entries for important actions +5. **Hardcoded Values**: Use config.py or environment variables ## Docker Environment -- Service name: `admin-panel` (not `adminpanel`) -- Database host: `postgres` -- Default port: 5000 -- Behind nginx proxy +Container names: v2_admin_panel, v2_license_server, v2_postgres, v2_redis, v2_rabbitmq, v2_nginx +Public access: Port 80 via Nginx ## Code Style Rules - NO comments unless explicitly requested @@ -136,6 +140,4 @@ docker-compose ps - Don't abstract code that's only used once - Implement exactly what's requested, nothing more -## Update Log -- 2025-06-21: Created initial version after fixing monitoring parameter mismatch -- 2025-06-21: Added response_time column issue to known problems \ No newline at end of file +## Last Updated: June 22, 2025 \ No newline at end of file diff --git a/JOURNAL.md b/JOURNAL.md index 2fafe9f..5fdd62d 100644 --- a/JOURNAL.md +++ b/JOURNAL.md @@ -1,5 +1,87 @@ # v2-Docker Projekt Journal +## Letzte Änderungen (22.06.2025 - 12:18 Uhr) + +### Lizenzserver Session Management - Vollständig implementiert ✅ + +**Implementierte Features:** +1. **Single-Session Enforcement**: + - Nur eine aktive Sitzung pro Lizenz erlaubt + - Deutsche Fehlermeldung bei Mehrfach-Login-Versuch + - Session-Token basiertes System mit UUID + +2. **Heartbeat System**: + - 30-Sekunden Heartbeat-Intervall + - Automatische Session-Bereinigung nach 60 Sekunden Inaktivität + - Background Job für Session-Cleanup + +3. **Session Management Endpoints**: + - `POST /api/license/session/start` - Session initialisierung + - `POST /api/license/session/heartbeat` - Keep-alive + - `POST /api/license/session/end` - Sauberes Session-Ende + - Vollständige Session-Historie in `session_history` Tabelle + +4. **Admin Panel Integration**: + - Lizenzserver Administration mit API-Key Management + - Live Session Monitor mit Auto-Refresh + - Session-Terminierung durch Admins + - Version Management (Current/Minimum) + +5. **Datenbank-Schema**: + - `client_configs` - Zentrale Konfiguration + - `license_sessions` - Aktive Sessions (UNIQUE per license_id) + - `session_history` - Audit Trail mit end_reason + - `system_api_key` - Globaler API Key + +**Status**: ✅ Vollständig implementiert und produktionsbereit + +### Dokumentation vollständig aktualisiert + +**Aktualisierte Dateien:** +1. **OPERATIONS_GUIDE.md**: + - Korrekte Container-Namen (v2_*) + - Aktuelle Service-Konfigurationen + - Neue Features dokumentiert (Leads, Resources, Monitoring) + - Health-Check Befehle aktualisiert + +2. **CLAUDE.md**: + - Vollständige Projektstruktur mit allen Modulen + - Alle Datenbank-Tabellen dokumentiert + - Session Management Patterns + - Erweiterte Common Issues Liste + +3. **TODO_LIZENZSERVER_CONFIG.md**: + - Als abgeschlossen markiert + - Kann archiviert/gelöscht werden + +**Alle Dokumentationen aktualisiert:** +- SYSTEM_DOCUMENTATION.md ✅ Vollständig aktualisiert +- API_REFERENCE.md ✅ Alle Endpoints dokumentiert +- TODO_LIZENZSERVER_CONFIG.md ✅ Gelöscht (da abgeschlossen) + +### Dokumentation bereinigt und komprimiert + +**Reduzierte Dateigröße:** +- OPERATIONS_GUIDE.md: Von 501 auf 409 Zeilen (-18%) +- CLAUDE.md: Von ~250 auf 142 Zeilen (-43%) +- SYSTEM_DOCUMENTATION.md: Von ~350 auf 243 Zeilen (-31%) +- API_REFERENCE.md: Von ~1057 auf 815 Zeilen (-23%) + +**Entfernt:** +- Redundante YAML-Konfigurationen (verweisen auf docker-compose.yaml) +- Verbose Code-Beispiele (durch kompakte Referenzen ersetzt) +- Zukünftige/nicht implementierte Features +- Duplizierte Informationen zwischen Dateien +- Übermäßig detaillierte JSON-Beispiele + +**Fokus auf:** +- Tatsächlich implementierte Features +- Praktische Operational-Informationen +- Kompakte API-Referenzen +- Verweise auf Source-Dateien statt Duplikation + +--- + ## Letzte Änderungen (19.06.2025 - 20:30 Uhr) ### Dokumentation aktualisiert und mit Realität abgeglichen diff --git a/OPERATIONS_GUIDE.md b/OPERATIONS_GUIDE.md index 0f3d700..65f5279 100644 --- a/OPERATIONS_GUIDE.md +++ b/OPERATIONS_GUIDE.md @@ -4,87 +4,89 @@ ### Prerequisites - Docker and Docker Compose -- PostgreSQL 13+ -- Python 3.8+ -- Minimum 4GB RAM -- 20GB disk space +- 4GB RAM, 20GB disk ### Initial Setup - ```bash -# Clone repository -git clone cd v2-Docker - -# Environment Variables sind bereits in docker-compose.yaml definiert -# Für Produktion: Erstelle .env Datei mit sensiblen Daten - -# Start services docker-compose up -d - -# Datenbank wird automatisch initialisiert via init.sql -# Keine manuellen Migrationen erforderlich ``` +Database initializes automatically via init.sql. ### Standard-Zugangsdaten #### Admin Panel -- URL: https://admin-panel-undso.z5m7q9dk3ah2v1plx6ju.com +- URL: http://localhost:80 (oder konfigurierte Domain) - User 1: `rac00n` / `1248163264` - User 2: `w@rh@mm3r` / `Warhammer123!` #### License Server API -- URL: https://api-software-undso.z5m7q9dk3ah2v1plx6ju.com -- API Key: Muss in Requests mitgesendet werden +- URL: http://localhost:80/api (über Nginx Proxy) +- API Key: Wird im Admin Panel unter "Lizenzserver Administration" verwaltet +- Header: `X-API-Key: ` ### Service Configuration #### License Server ```yaml license-server: - image: v2_lizenzserver:latest + build: ./v2_lizenzserver + container_name: v2_license_server environment: - - DATABASE_URL=postgresql://adminuser:supergeheimespasswort@db:5432/meinedatenbank + - DATABASE_URL=postgresql://adminuser:supergeheimespasswort@postgres:5432/meinedatenbank - JWT_SECRET=your-secret-jwt-key-here-minimum-32-chars - - API_KEY=your-api-key-here - - REDIS_HOST=redis-cache + - REDIS_HOST=redis - RABBITMQ_HOST=rabbitmq - # Kein externer Port - nur über Nginx erreichbar expose: - - "8443" + - "8000" networks: - - internal_net + - backend + - monitoring + depends_on: + - postgres + - redis + - rabbitmq ``` #### Admin Panel ```yaml admin-panel: - image: v2_adminpanel:latest + build: ./v2_adminpanel + container_name: v2_admin_panel environment: - - DATABASE_URL=postgresql://adminuser:supergeheimespasswort@db:5432/meinedatenbank + - DATABASE_URL=postgresql://adminuser:supergeheimespasswort@postgres:5432/meinedatenbank - SECRET_KEY=supersecretkey - JWT_SECRET=your-secret-jwt-key-here-minimum-32-chars - - LIZENZSERVER_BASE_URL=http://license-server:8443 - - REDIS_HOST=redis-cache - # Kein externer Port - nur über Nginx erreichbar + - REDIS_HOST=redis expose: - "5000" networks: - - internal_net + - backend + - monitoring + depends_on: + - postgres + - redis + volumes: + - ./backups:/app/backups ``` #### Nginx Reverse Proxy ```yaml -nginx-proxy: - image: v2_nginx:latest +nginx: + build: ./v2_nginx + container_name: v2_nginx ports: - - "80:80" # HTTP (wird auf HTTPS umgeleitet) - - "443:443" # HTTPS + - "80:80" networks: - - internal_net - # Routet Requests an interne Services: - # admin-panel-undso.z5m7q9dk3ah2v1plx6ju.com → admin-panel:5000 - # api-software-undso.z5m7q9dk3ah2v1plx6ju.com → license-server:8443 + - backend + depends_on: + - admin-panel + - license-server + volumes: + - ./v2_nginx/nginx.conf:/etc/nginx/nginx.conf:ro + # Routing: + # / → admin-panel:5000 (Admin Panel) + # /api → license-server:8000 (API Endpoints) ``` ## Monitoring @@ -96,7 +98,12 @@ nginx-proxy: scrape_configs: - job_name: 'license-server' static_configs: - - targets: ['license-server:8443'] + - targets: ['license-server:8000'] + metrics_path: /metrics + + - job_name: 'admin-panel' + static_configs: + - targets: ['admin-panel:5000'] metrics_path: /metrics - job_name: 'postgres' @@ -107,17 +114,13 @@ scrape_configs: static_configs: - targets: ['redis-exporter:9121'] - - job_name: 'nginx' - static_configs: - - targets: ['nginx-exporter:9113'] - - job_name: 'node' static_configs: - targets: ['node-exporter:9100'] - job_name: 'cadvisor' static_configs: - - targets: ['cadvisor:8081'] + - targets: ['cadvisor:8080'] ``` #### Alert Rules @@ -157,11 +160,56 @@ scrape_configs: - Alertmanager: http://localhost:9093 ### Monitoring Stack Services -- PostgreSQL Exporter: Sammelt DB-Metriken -- Redis Exporter: Sammelt Cache-Metriken -- Node Exporter: System-Level Metriken -- Nginx Exporter: Webserver-Metriken -- cAdvisor: Container-Metriken (Port 8081) +- PostgreSQL Exporter: Sammelt DB-Metriken (Port 9187) +- Redis Exporter: Sammelt Cache-Metriken (Port 9121) +- Node Exporter: System-Level Metriken (Port 9100) +- cAdvisor: Container-Metriken (Port 8080) +- Prometheus: Metrics Collection (Port 9090) +- Grafana: Visualization (Port 3000) +- Alertmanager: Alert Management (Port 9093) + +## Features Overview + +### Lead Management System +- Accessible via "Leads" button on Customers & Licenses page +- Manage potential customers and contacts +- Features: + - Institution management + - Contact persons with multiple phones/emails + - Versioned notes system + - Full audit trail + +### Resource Pool Management +- Domain allocation system +- IPv4 address management +- Phone number allocation +- Features: + - Resource assignment to licenses + - Quarantine management + - Resource history tracking + - Availability monitoring + +### Batch Operations +- Bulk license creation +- Mass updates +- Accessible from Customers & Licenses page + +### Monitoring Integration +- Unified monitoring dashboard at `/monitoring` +- Live analytics and metrics +- Alert management interface +- Integrated with Prometheus/Grafana stack + +### API Key Management +- Single system-wide API key +- Managed in "Lizenzserver Administration" +- Used for all API authentication + +### Session Management +- Single-session enforcement per license +- 30-second heartbeat system +- Automatic session cleanup after 60 seconds +- Session history tracking ## Maintenance @@ -182,20 +230,12 @@ DROP TABLE IF EXISTS license_heartbeats_2024_01; ``` #### Backup Procedures - -##### Manuelles Backup ```bash -# Full database backup -docker exec db pg_dump -U adminuser meinedatenbank > backup_$(date +%Y%m%d).sql +# Backup +docker exec v2_postgres pg_dump -U adminuser meinedatenbank | gzip > backup_$(date +%Y%m%d).sql.gz -# Backup specific tables -docker exec db pg_dump -U adminuser -t licenses -t license_activations meinedatenbank > licenses_backup.sql - -# Komprimiertes Backup -docker exec db pg_dump -U adminuser meinedatenbank | gzip > backup_$(date +%Y%m%d).sql.gz - -# Restore from backup -docker exec -i db psql -U adminuser meinedatenbank < backup_20250619.sql +# Restore +gunzip -c backup_20250619.sql.gz | docker exec -i v2_postgres psql -U adminuser meinedatenbank ``` ##### Integriertes Backup-System @@ -210,25 +250,10 @@ Das Admin Panel bietet ein eingebautes Backup-System: #### Log Locations -##### Container Logs -```bash -# License Server Logs -docker logs license-server - -# Admin Panel Logs -docker logs admin-panel - -# Nginx Logs -docker logs nginx-proxy - -# Database Logs -docker logs db -``` - -##### Persistent Log Volumes -- Nginx Access/Error Logs: Mapped to local `./v2_nginx/logs/` -- Application Logs: Verfügbar über Docker logging driver -- Audit Logs: In der Datenbank (Tabelle `audit_log`) +##### Logs +- Container logs: `docker logs ` +- Nginx logs: `./v2_nginx/logs/` +- Audit logs: Database table `audit_log` #### Log Rotation ```bash @@ -246,17 +271,9 @@ docker logs db ### Performance Optimization #### Database Tuning -```sql --- Update statistics -ANALYZE; - --- Reindex tables -REINDEX TABLE licenses; -REINDEX TABLE license_activations; - --- Vacuum tables -VACUUM ANALYZE licenses; -``` +- Run `ANALYZE` periodically +- `VACUUM ANALYZE` on large tables +- Maintain partitions: `CALL create_monthly_partitions('license_heartbeats', 3)` #### Resource Limits @@ -302,38 +319,14 @@ db: ### Common Issues #### License Server Not Responding -1. Check container status: `docker ps | grep license-server` -2. View logs: `docker logs license-server --tail 100` -3. Test internal connectivity: - ```bash - docker exec nginx-proxy curl -k https://license-server:8443/health - ``` -4. Verify environment variables: - ```bash - docker exec license-server env | grep -E "JWT_SECRET|API_KEY|DATABASE_URL" - ``` -5. Check Nginx routing: - ```bash - docker exec nginx-proxy nginx -T | grep api-software - ``` +- Check status: `docker ps | grep license` +- View logs: `docker logs v2_license_server --tail 100` +- Test health: `docker exec v2_nginx curl http://license-server:8000/health` #### Database Connection Issues -1. Check PostgreSQL status: - ```bash - docker exec db pg_isready -U adminuser -d meinedatenbank - ``` -2. Test connection from service: - ```bash - docker exec admin-panel psql postgresql://adminuser:supergeheimespasswort@db:5432/meinedatenbank -c "SELECT 1" - ``` -3. Check network connectivity: - ```bash - docker network inspect v2-docker_internal_net - ``` -4. Review PostgreSQL logs: - ```bash - docker logs db --tail 50 - ``` +- Check status: `docker exec v2_postgres pg_isready` +- Test connection: Use psql from admin panel container +- Check logs: `docker logs v2_postgres --tail 50` #### High Memory Usage 1. Check container stats: `docker stats` @@ -343,50 +336,23 @@ db: ### Health Checks +Quick health check script: ```bash -# License server health (über Nginx) -curl -k https://api-software-undso.z5m7q9dk3ah2v1plx6ju.com/health +# All services +docker ps --format "table {{.Names}}\t{{.Status}}" -# Admin panel health (über Nginx) -curl -k https://admin-panel-undso.z5m7q9dk3ah2v1plx6ju.com/ - -# Database health -docker exec db pg_isready -U adminuser -d meinedatenbank - -# Redis health -docker exec redis-cache redis-cli ping - -# RabbitMQ health -docker exec rabbitmq rabbitmqctl status - -# Monitoring stack -curl http://localhost:9090/-/healthy # Prometheus -curl http://localhost:3001/api/health # Grafana -curl http://localhost:9093/-/healthy # Alertmanager - -# Container health overview -docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" +# Key endpoints +curl -s http://localhost/api/health +curl -s http://localhost:9090/-/healthy ``` ## Security Considerations - -### API Security -- Use strong JWT_SECRET (minimum 32 characters) +- Strong JWT_SECRET (32+ chars) - Rotate API keys regularly -- Implement rate limiting +- Rate limiting enabled - Use HTTPS in production - -### Database Security -- Use strong passwords -- Limit database access -- Enable SSL for connections -- Regular security updates - -### Container Security -- Use official base images -- Scan images for vulnerabilities -- Don't run containers as root -- Keep Docker updated +- Strong database passwords +- Keep Docker and images updated ## Scaling Strategies @@ -395,7 +361,7 @@ docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" #### Scaling License Server ```bash # Scale license server instances -docker-compose up -d --scale license-server=3 +docker-compose -f v2/docker-compose.yaml up -d --scale license-server=3 ``` #### Nginx Load Balancing Configuration @@ -434,23 +400,11 @@ server { - Partitioning for large tables ## Disaster Recovery - -### Backup Strategy -- Daily automated backups -- Off-site backup storage -- Test restore procedures -- Document recovery steps - -### High Availability -- Database replication -- Service redundancy -- Load balancing -- Automated failover +- Daily automated backups via Admin Panel +- Test restore procedures regularly +- Consider database replication for HA ## Monitoring Best Practices - -1. **Set up alerts for critical metrics** -2. **Create runbooks for common issues** -3. **Regular review of dashboards** -4. **Capacity planning based on trends** -5. **Document all custom configurations** \ No newline at end of file +- Configure alerts in Alertmanager +- Review Grafana dashboards regularly +- Monitor resource trends for capacity planning \ No newline at end of file diff --git a/SYSTEM_DOCUMENTATION.md b/SYSTEM_DOCUMENTATION.md index 005c4e5..f52d42e 100644 --- a/SYSTEM_DOCUMENTATION.md +++ b/SYSTEM_DOCUMENTATION.md @@ -47,28 +47,13 @@ V2-Docker is a comprehensive system featuring a License Server, Admin Panel, Lea - Integrierte Backup-Funktionalität - Lead Management System -#### Geplante Services (Code vorhanden, nicht aktiv) -1. **Analytics Service** - Usage statistics and reporting - - Code in `/v2_lizenzserver/services/analytics/` - - Auskommentiert in docker-compose.yaml - -2. **Admin API Service** - Dedizierte Admin API - - Code in `/v2_lizenzserver/services/admin/` - - Auskommentiert in docker-compose.yaml - -3. **Auth Service** - Zentralisierte Authentifizierung - - Code in `/lizenzserver/services/auth/` - - Auskommentiert in docker-compose.yaml - -#### Konzeptionelle Services (nur in Planung) -1. **Notification Service** - Email/webhook notifications -2. **Dedicated Backup Service** - Automated backups (derzeit im Admin Panel integriert) - -#### Infrastructure Services (aktiv) -- **PostgreSQL** - Hauptdatenbank +#### Infrastructure Services +- **PostgreSQL** - Main database - **Redis** - Caching -- **RabbitMQ** - Message Queue -- **Nginx** - Reverse Proxy +- **RabbitMQ** - Message queue +- **Nginx** - Reverse proxy + +*Note: Analytics, Admin API, and Auth services exist in code but are currently inactive.* #### Communication - REST APIs für externe Kommunikation @@ -76,19 +61,8 @@ V2-Docker is a comprehensive system featuring a License Server, Admin Panel, Lea - RabbitMQ für asynchrone Verarbeitung (vorbereitet) ### Database Schema - -#### Core Tables -- `licenses` - License definitions -- `license_activations` - Active installations -- `license_heartbeats` - Usage tracking (partitioned monthly) -- `license_usage_stats` - Aggregated statistics -- `license_features` - Feature flags -- `license_limits` - Usage limits - -#### Partitioning Strategy -- Monthly partitions for `license_heartbeats` -- Automatic partition creation -- 90-day retention policy +See `v2_adminpanel/init.sql` for complete schema. +Key feature: Monthly partitioned `license_heartbeats` table. ### Security Concepts - JWT-based authentication @@ -97,30 +71,40 @@ V2-Docker is a comprehensive system featuring a License Server, Admin Panel, Lea - Hardware fingerprint validation - Encrypted communication -### Implementation Status (June 19, 2025) +### Implementation Status (June 22, 2025) #### Completed -- ✅ License Server mit API-Endpunkten +- ✅ License Server mit vollständigen API-Endpunkten - POST /api/license/activate - POST /api/license/verify - GET /api/license/info/{license_key} + - POST /api/license/session/start - Session-Initialisierung + - POST /api/license/session/heartbeat - Keep-alive + - POST /api/license/session/end - Session-Beendigung - POST /api/version/check - GET /api/version/latest - ✅ Admin Panel mit voller Funktionalität - - Customer Management - - License Management - - Resource Management - - Session Management - - Lead Management - - Batch Operations - - Export/Import + - Customer Management mit erweiterten Features + - License Management mit Resource Allocation + - Resource Pool Management (Domains, IPs, Telefonnummern) + - Session Management mit Live-Monitor + - Lead Management System (vollständiges CRM) + - Batch Operations für Bulk-Aktionen + - Export/Import Funktionalität + - Device Registration und Management + - API Key Management (System-wide) - ✅ Monitoring Stack (Prometheus, Grafana, Alertmanager) + - Integriertes Monitoring Dashboard + - Vorkonfigurierte Dashboards + - Alert Rules für kritische Metriken - ✅ Docker Services Konfiguration - ✅ JWT/API Key Management - ✅ Backup-System (integriert im Admin Panel) - ✅ 2FA-Authentifizierung -- ✅ Audit Logging -- ✅ Rate Limiting +- ✅ Audit Logging mit Request IDs +- ✅ Rate Limiting (konfigurierbar) +- ✅ Single-Session Enforcement (Account Forger) +- ✅ Partitionierte Datenbank für Heartbeats #### Code vorhanden aber nicht aktiviert - ⏸️ Analytics Service (auskommentiert) @@ -146,54 +130,41 @@ V2-Docker is a comprehensive system featuring a License Server, Admin Panel, Lea ### Data Model (implementiert) ``` lead_institutions -├── lead_contact_persons (1:n) -├── lead_notes (1:n) -├── lead_tags (n:m) -└── lead_activities (1:n) +├── lead_contacts (1:n) +│ └── lead_contact_details (1:n) - Telefon/E-Mail +└── lead_notes (1:n) - Versionierte Notizen ``` ### Implementierte Features 1. ✅ Institution Management (CRUD) -2. ✅ Contact Person Management -3. ✅ Notes mit Versionierung -4. ✅ Tag-System -5. ✅ Activity Tracking -6. ✅ Export/Import Funktionalität -7. ✅ Erweiterte Suche und Filter -8. ✅ Statistik-Dashboard +2. ✅ Contact Person Management mit mehreren Telefon/E-Mail +3. ✅ Notes mit vollständiger Versionierung +4. ✅ Flexible Kontaktdetails (beliebig viele pro Person) +5. ✅ Audit Trail Integration +6. ✅ Service/Repository Pattern für Clean Code +7. ✅ JSONB Felder für zukünftige Erweiterungen ### API Endpoints -- GET /leads/ - Übersicht -- GET/POST /leads/create - Neue Institution -- GET/POST /leads/edit/{id} - Bearbeiten -- POST /leads/delete/{id} - Löschen -- GET /leads/export - Export -- POST /leads/import - Import -- GET /leads/api/stats - Statistiken +- GET /leads/ - Institutionen-Übersicht +- GET /leads/institutions - Institutionen-Liste +- POST /leads/institutions - Neue Institution +- GET /leads/institutions/{id} - Institution Details +- PUT /leads/institutions/{id} - Institution bearbeiten +- DELETE /leads/institutions/{id} - Institution löschen +- GET /leads/contacts/{id} - Kontakt Details +- POST /leads/contacts/{id}/details - Kontaktdetail hinzufügen +- PUT /leads/contacts/{id}/details/{detail_id} - Detail bearbeiten +- POST /leads/contacts/{id}/notes - Notiz hinzufügen ## Monitoring Stack -### Components -- **Prometheus**: Metrics collection -- **Grafana**: Visualization (port 3001) -- **Alertmanager**: Alert management (port 9093) -- **Node Exporter**: System metrics -- **Postgres Exporter**: Database metrics -- **cAdvisor**: Container metrics +### Monitoring Stack +- **Prometheus**: Metrics collection (port 9090) +- **Grafana**: Dashboards (port 3000) +- **Alertmanager**: Alerts (port 9093) +- Exporters for PostgreSQL, Redis, Node, and containers -### Dashboards -1. System Overview -2. License Server Metrics -3. Database Performance -4. Container Resources -5. Admin Panel Usage - -### Alert Rules -- High CPU usage (>80%) -- High memory usage (>90%) -- Database connection issues -- License server downtime -- Disk space warnings +Pre-configured dashboards and alerts for system health. ## Admin Panel @@ -215,112 +186,59 @@ lead_institutions - ✅ Lizenzerstellung (Einzel und Batch) - ✅ Lizenzbearbeitung und -löschung - ✅ Bulk-Operationen (Aktivieren/Deaktivieren) - - ✅ Device Management pro Lizenz - - ✅ Resource Allocation + - ✅ Device Management mit Hardware IDs + - ✅ Resource Allocation (Domains, IPs, Telefonnummern) - ✅ Quick Edit Funktionalität + - ✅ Session Management und Monitoring + - ✅ Lizenz-Konfiguration für Account Forger 4. **Monitoring & Analytics** - ✅ Dashboard mit Live-Statistiken - ✅ Lizenzserver-Monitoring - - ✅ Anomalie-Erkennung - - ✅ Session-Überwachung - - ✅ Resource-Auslastung + - ✅ Session-Überwachung mit Live-Updates + - ✅ Resource Pool Monitoring + - ✅ Integriertes Monitoring Dashboard (/monitoring) + - ✅ Prometheus/Grafana Integration + - ✅ Alert Management 5. **System Administration** - - ✅ Backup & Restore - - ✅ Export-Funktionen (CSV) - - ✅ Audit Log Viewer + - ✅ Backup & Restore (manuell und geplant) + - ✅ Export-Funktionen (CSV, JSON) + - ✅ Audit Log Viewer mit Filterung - ✅ Blocked IPs Management - ✅ Feature Flags Konfiguration + - ✅ API Key Generation und Management + - ✅ Lizenzserver Administration + - ✅ Session-Terminierung durch Admins ### Technical Stack -- **Backend**: Flask 3.0.3 mit Blueprints -- **Database**: PostgreSQL mit Partitionierung -- **Frontend**: Bootstrap 5.3, jQuery, Select2 -- **Real-time**: AJAX, Server-Sent Events -- **Security**: bcrypt, pyotp (2FA), JWT +- Backend: Flask 3.0.3, PostgreSQL +- Frontend: Bootstrap 5.3, jQuery +- Security: bcrypt, pyotp (2FA), JWT ## Deployment Configuration ### Docker Services #### Aktive Services -- `v2_db`: PostgreSQL database (Port 5432) -- `v2_adminpanel`: Admin interface (Port 80) -- `v2_nginx`: Reverse proxy (Ports 80, 443) -- `v2_lizenzserver`: License server (interner Port) -- `redis`: Redis cache (Port 6379) -- `rabbitmq`: Message queue (Ports 5672, 15672) +- `v2_postgres`: PostgreSQL database (Port 5432) +- `v2_admin_panel`: Admin interface (interner Port 5000) +- `v2_nginx`: Reverse proxy (Port 80) +- `v2_license_server`: License server (interner Port 8000) +- `v2_redis`: Redis cache (Port 6379) +- `v2_rabbitmq`: Message queue (Ports 5672, 15672) -#### Monitoring Stack (aktiv) -- `prometheus`: Metrics collection (Port 9090) -- `grafana`: Monitoring dashboards (Port 3001) -- `alertmanager`: Alert management (Port 9093) -- `postgres-exporter`: PostgreSQL metrics -- `redis-exporter`: Redis metrics -- `node-exporter`: System metrics -- `nginx-exporter`: Nginx metrics -- `cadvisor`: Container metrics (Port 8081) +See monitoring configuration in `monitoring/docker-compose.monitoring.yml`. -#### Auskommentierte Services -- `auth-service`: Authentication service (würde auf Port 5001 laufen) -- `analytics-service`: Analytics service (würde auf Port 5003 laufen) -- `admin-api-service`: Admin API service (würde auf Port 5004 laufen) +### Environment Configuration +Required: DATABASE_URL, SECRET_KEY, JWT_SECRET +See docker-compose.yaml for all environment variables. -### Environment Variables -#### Erforderlich -- `DATABASE_URL`: PostgreSQL Verbindung -- `SECRET_KEY`: Flask Session Secret -- `JWT_SECRET`: JWT Token Signierung - -#### Optional mit Defaults -- `MONITORING_ENABLED`: "true" (Feature Flag) -- `SESSION_LIFETIME_MINUTES`: 30 -- `PERMANENT_SESSION_LIFETIME_DAYS`: 7 -- `LOGIN_RATE_LIMIT`: "5 per minute" -- `API_RATE_LIMIT`: "100 per minute" -- `MAX_LOGIN_ATTEMPTS`: 5 -- `LOGIN_LOCKOUT_DURATION`: 900 (Sekunden) -- `LIZENZSERVER_BASE_URL`: "http://v2_lizenzserver:8000" -- `REDIS_HOST`: "redis" -- `REDIS_PORT`: 6379 - -### Network Configuration -- Internal network for service communication -- External access through Nginx -- SSL/TLS termination at proxy level - -## Testing Strategy - -### Unit Tests -- Service layer logic -- API endpoint validation -- Database operations - -### Integration Tests -- Service communication -- Database transactions -- API workflows - -### Performance Tests -- Load testing -- Stress testing -- Scalability verification - -## Future Roadmap - -### Phase 1: Core Completion -- Finish analytics service -- Complete backup automation -- Implement all monitoring dashboards - -### Phase 2: Advanced Features -- Machine learning for usage prediction -- Advanced reporting -- Multi-tenant support - -### Phase 3: Enterprise Features -- High availability setup -- Disaster recovery -- Advanced security features \ No newline at end of file +## Current Status +System is production-ready with all core features implemented: +- ✅ License management with session enforcement +- ✅ Lead management CRM +- ✅ Resource pool management +- ✅ Complete monitoring stack +- ✅ Backup and audit systems \ No newline at end of file diff --git a/v2_adminpanel/TODO_LIZENZSERVER_CONFIG.md b/v2_adminpanel/TODO_LIZENZSERVER_CONFIG.md deleted file mode 100644 index 883f45e..0000000 --- a/v2_adminpanel/TODO_LIZENZSERVER_CONFIG.md +++ /dev/null @@ -1,204 +0,0 @@ -# Lizenzserver Konfiguration Implementation - -## Overview -✅ COMPLETED: Implemented client configuration management and single-session enforcement for Account Forger software. - -## Implementation Status (2025-06-21) -✅ License activation works (consumes device slots) -✅ Basic verification exists at `/api/license/verify` -✅ Heartbeat system implemented (30-second intervals) -✅ Single-session enforcement implemented -✅ Admin panel has full UI and backend for "Lizenzserver Konfiguration" -✅ Session management and monitoring -✅ Automatic cleanup of expired sessions - -## Requirements -1. **Single Session Enforcement**: Only one device can run the software at a time (even if activated on multiple devices) -2. **Heartbeat System**: 30-second heartbeats to track active sessions -3. **Version Management**: Control minimum supported version and update notifications -4. **Client Configuration**: Manage Account Forger settings from admin panel - -## Completed Features - -### 1. Database Schema ✅ - -#### Admin Panel Database -```sql --- Client configuration (one row for Account Forger) -CREATE TABLE client_configs ( - id SERIAL PRIMARY KEY, - client_name VARCHAR(100) NOT NULL DEFAULT 'Account Forger', - api_key VARCHAR(255) NOT NULL, - heartbeat_interval INTEGER DEFAULT 30, -- seconds - session_timeout INTEGER DEFAULT 60, -- seconds (2x heartbeat) - current_version VARCHAR(20) NOT NULL, - minimum_version VARCHAR(20) NOT NULL, - download_url TEXT, - whats_new TEXT, - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -); - --- Active sessions tracking -CREATE TABLE active_sessions ( - id SERIAL PRIMARY KEY, - license_id INTEGER REFERENCES licenses(id) ON DELETE CASCADE, - hardware_id VARCHAR(255) NOT NULL, - ip_address INET, - client_version VARCHAR(20), - session_token VARCHAR(255) UNIQUE NOT NULL, - started_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - last_heartbeat TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - UNIQUE(license_id) -- Only one active session per license -); - --- Session history for debugging -CREATE TABLE session_history ( - id SERIAL PRIMARY KEY, - license_id INTEGER REFERENCES licenses(id) ON DELETE CASCADE, - hardware_id VARCHAR(255) NOT NULL, - ip_address INET, - client_version VARCHAR(20), - started_at TIMESTAMP, - ended_at TIMESTAMP, - end_reason VARCHAR(50) -- 'normal', 'timeout', 'forced', 'replaced' -); -``` - -### 2. License Server Endpoints ✅ - -#### Implemented endpoints in `/v2_lizenzserver/app/api/license.py`: - -1. **POST /api/license/session/start** - - Input: license_key, machine_id, hardware_hash, version - - Check: License valid? Already active session? - - If active session exists: Return error "Es ist nur eine Sitzung erlaubt, stelle sicher, dass nirgendwo sonst das Programm läuft" - - If no session: Create session, return session_token and version info - - Response includes: session_token, whats_new (if newer version), download_url - -2. **POST /api/license/session/heartbeat** - - Input: session_token, license_key - - Update last_heartbeat timestamp - - Return: success status - -3. **POST /api/license/session/end** - - Input: session_token - - Mark session as ended - - Log to session_history - -4. **Background job**: Clean up sessions older than 60 seconds without heartbeat - -### 3. Admin Panel Implementation ✅ - -#### Implemented routes in `/v2_adminpanel/routes/admin_routes.py`: - -1. **GET /lizenzserver/config** - - Show current client configuration - - Display active sessions count - -2. **POST /lizenzserver/config/update** - - Update version, download URL, what's new - - Update minimum supported version - -3. **GET /lizenzserver/sessions** - - List all active sessions - - Show: License key, Customer name, Hardware ID, IP, Started at, Last heartbeat - -4. **POST /lizenzserver/sessions/{session_id}/terminate** - - Force close a session (admin only: rac00n, w@rh@mm3r) - -5. **GET /lizenzserver/config/client/new** ✅ - - Shows client configuration page - - Handles initial client config and updates - -### 4. Security - -- API key required for all client requests -- License key validates ownership -- Hardware ID ensures device authenticity -- Session tokens prevent replay attacks - -### 5. Client Flow - -1. **Startup**: - ``` - POST /api/license/session/start - -> Get session_token or error - -> Show version update if available - ``` - -2. **Running** (every 30 seconds): - ``` - POST /api/license/session/heartbeat - -> Keep session alive - ``` - -3. **Shutdown**: - ``` - POST /api/license/session/end - -> Clean session exit - ``` - -### 6. Error Handling - -- Network interruption: Session expires after 60s -- Software crash: Session expires after 60s -- Multiple launch attempts: Show error message -- Version too old: Block with message to update - -### 7. Admin Features - -- View active sessions -- Force terminate sessions -- Update version requirements -- View session history (last 24h) -- Manage client configuration - -## Implementation Completed - -1. ✅ Created database tables (client_configs, license_sessions, session_history) -2. ✅ Implemented session management in license server -3. ✅ Added heartbeat endpoint -4. ✅ Created admin panel routes for configuration -5. ✅ Implemented session viewing/management with terminate capability -6. ✅ Added background cleanup job (runs every 60 seconds) -7. ⏳ Ready for testing with Account Forger client - -## Implementation Notes -- ✅ YAGNI: One global config for all Account Forger instances -- ✅ No per-customer settings -- ✅ No grace period for session reclaim -- ✅ Generic error messages (no "who's using it" info) -- ✅ Version format: 1.0.0 -- ✅ Session tokens: UUID format -- ✅ Background cleanup: Every 60 seconds -- ✅ API Key: Single global key stored in client_configs - -## UI Improvements (2025-06-21) - -### Single-Page Administration -- ✅ Merged all configuration into the main administration page -- ✅ Removed separate "Account Forger Konfiguration" page -- ✅ Removed "Neuer Client" button (not needed with single global config) - -### Account Forger Configuration Section -- ✅ Inline version management (current and minimum version) -- ✅ API key display with copy-to-clipboard functionality -- ✅ Removed download_url and whats_new fields (handled elsewhere) -- ✅ Direct save without page navigation - -### Live Session Monitor -- ✅ Real-time session count with badge -- ✅ Mini table showing last 5 active sessions -- ✅ Auto-refresh every 30 seconds via AJAX -- ✅ "Alle anzeigen" link to full session management page - -### Technical Settings -- ✅ Feature flags in collapsible accordion -- ✅ Rate limits in collapsible accordion -- ✅ Clean separation between daily operations and technical settings - -### Database Schema Updates -- ✅ Removed download_url column from client_configs -- ✅ Removed whats_new column from client_configs -- ✅ Simplified to only essential configuration fields \ No newline at end of file