> **Documentation associée :** > - `docs/ui-pages.md` — Description détaillée de toutes les pages UI (Blazor) > - `docs/mobile-app.md` — Application Android (Avalonia UI) — consultation uniquement > - `docs/auth-roles.md` — Authentification, rôles, permissions, visibilité UI > - `docs/notifications.md` — Email SMTP, Gotify, templates Markdown i18n > - `docs/hangfire-usage.md` — Tous les jobs Hangfire (Central + Agent) > - `docs/signalr-usage.md` — Tous les hubs SignalR (events, streaming, monitoring) > - `docs/implementation.md` — Plan d'implémentation complet par phases ````markdown # Heimdall ## Intelligent Local AI Video Surveillance Platform **Version:** 1.0 **Target Framework:** .NET 10+ **Architecture:** Clean Architecture / CQRS / Multi-site / Local AI --- # 1. Vision ## Overview Heimdall is a modern self-hosted intelligent video surveillance platform designed around: - Local AI processing - Multi-site architecture - ONVIF camera discovery - RTSP video management - Face recognition - License plate recognition - Local LLM analysis - Enterprise security model - Full configuration through Web UI Heimdall does not depend on cloud services. All business configuration is stored in PostgreSQL and managed through the application interface. --- # 2. Main Objectives ## Functional Objectives - Manage multiple sites - Automatically discover ONVIF cameras - Support Imou cameras at minimum - Record and manage video streams - Detect people, vehicles and objects - Recognize known persons - Detect and read license plates - Associate vehicles with persons - Generate AI summaries using Ollama - Provide secure API access - Provide complete administration through Blazor UI --- ## Technical Objectives - 100% Docker deployment - .NET 10+ - PostgreSQL as unique source of configuration - No business configuration files - Local-first architecture - GPU acceleration when available - Enterprise logging and monitoring --- # 3. Naming ## Heimdall Inspired by Norse mythology. Heimdall is the guardian watching the Bifröst bridge. Mission: > Protect and monitor your infrastructure. --- # 4. Global Architecture ```text Heimdall Central (ASP.NET Core + Blazor) | ┌───────────┼──────────────┐ │ Signaling │ HTTPS API │ │ (SignalR) │ (REST) │ └─────┬─────┴──────┬────────┘ │ │ │ ┌─────────┴──────────┐ │ │ PostgreSQL │ │ │ + STUN/TURN │ │ │ (coturn - Docker) │ │ └────────────────────┘ │ ┌────────────┴────────────┐ │ WebRTC P2P Signaling │ │ (SDP + ICE via SignalR)│ └────────────┬────────────┘ │ ┌─────┴──────┐ │ │ ┌──────────┴──────┐ ┌──┴────────────────┐ │ Heimdall Agent │ │ Heimdall Agent │ │ (Site A) │ │ (Site B) │ │ │ │ │ │ SIPSorcery │ │ SIPSorcery │ │ WebRTC Peer │ │ WebRTC Peer │ │ FFmpeg → H264 │ │ FFmpeg → H264 │ └──┬───────────────┘ └───┬────────────────┘ │ │ │ Flux WebRTC P2P │ Flux WebRTC P2P │ ◄══════════════════► │ ◄══════════════► │ (SRTP/SCTP direct) │ (SRTP/SCTP) └──────────────────────┘ │ ┌────────┴────────┐ │ STUN/TURN │ │ (si double NAT)│ └─────────────────┘ ```` --- # 5. Solution Structure ```text Heimdall.sln src/ ├── Heimdall.Domain ├── Heimdall.Application ├── Heimdall.Infrastructure ├── Heimdall.Api ├── Heimdall.Web ├── Heimdall.Agent ├── Heimdall.Workers ├── Heimdall.Contracts └── Heimdall.Shared ``` --- # 6. Technology Stack ## Backend * .NET 10+ * C# * ASP.NET Core * Blazor Web App * Clean Architecture * CQRS * MediatR * FluentValidation * Entity Framework Core * Hangfire * Serilog * OpenTelemetry ready * Sentry SDK compatible with GlitchTip * **SignalR** — WebRTC signaling (SDP + ICE exchange) * **SIPSorcery** — WebRTC peer (ICE, STUN, TURN, DTLS, SRTP) * **SIPSorceryMedia.FFmpeg** — Codec H264 via FFmpeg * **coturn** — TURN relay (optionnel, double NAT) --- ## Frontend * Blazor Web App * Interactive Server Rendering * MudBlazor * Material Design principles --- ## Database PostgreSQL ORM: * Entity Framework Core Database configuration: * IEntityTypeConfiguration * Specification Pattern No generic repository pattern. --- # 7. Coding Rules All code must follow Microsoft .NET recommendations. ## Language Source code: * English only Comments: * English only XML documentation: * English only --- ## C# Rules Enabled: * Nullable Reference Types * Implicit Usings * File Scoped Namespace Rules: * Async everywhere * No blocking calls * Strong typing * No magic strings * No duplicated business logic --- # 8. Domain Model Design ## Enum First Approach Heimdall maximizes strongly typed enums. Business states must never be represented by strings. --- ## Examples ### Camera Status ```csharp public enum CameraStatus { Unknown, Online, Offline, Disabled, Error } ``` --- ### Event Type ```csharp public enum EventType { MotionDetected, PersonDetected, VehicleDetected, UnknownPerson, FaceRecognized, LicensePlateDetected } ``` --- ### Storage Provider ```csharp public enum StorageProvider { Local, S3 } ``` --- ### Theme Mode ```csharp public enum ThemeMode { Light, Dark, Auto } ``` --- # 9. Authentication and Security ## Authentication Microsoft Identity. No Azure AD dependency. --- ## Authorization Based on: * Roles * Permissions * Policies Examples: ``` Camera.Read Camera.Write Person.Read Person.Write Recording.Delete Administration.Manage ``` --- # 10. API Security External integrations use API Keys. Features: * Generate API key from UI * Define permissions * Expiration date * Revocation * Audit history Storage: * Hash only * Never store clear text keys --- # 11. Multi Site Management ## Site Entity ``` Site ├── Id (Guid, PK) ├── Name (string, required) ├── Description (string) ├── Address (string) ├── Timezone (string) ├── Enabled (bool) │ ├── Registration (pour déploiement Agent) │ ├── Token (string, hash SHA256) │ ├── TokenPlain (string, affiché 1 fois à la création) │ ├── TokenExpiresAt (DateTime?) │ └── Agents (List) ``` --- Each object belongs to a site: * Cameras * Events * Recordings * Persons * Vehicles * Agents --- ## Agent Registration Flow ```text ┌─────────┐ ┌──────────┐ ┌──────────┐ │ Admin │ │ Heimdall │ │ Agent │ │ (Blazor) │ │ Central │ │ (Docker) │ └────┬─────┘ └────┬─────┘ └────┬─────┘ │ │ │ │ 1. Crée Site │ │ │─────────────────►│ │ │ │ 2. Génère token │ │ │ (UUID v4) │ │ 3. Token + │ │ │ commande │ │ │◄─────────────────│ │ │ docker │ │ │ préremplie │ │ │ │ │ │ 4. docker run -e │ │ │ SITE_TOKEN=.. │ │ │────────────────────────────────────►│ │ │ │ │ │ 5. POST /api/agents/register │ │◄─────────────────│ │ │ { token, │ │ │ hostname, │ │ │ version } │ │ │ │ │ │ 6. Valide token │ │ │ Associe site │ │ │ AgentId = UUID│ │ 7. Agent OK │ │ │◄─────────────────│ │ │ │ 8. Heartbeat │ │ │ toutes les 30s│ │ │◄─────────────────│ ``` Le token est **mono-usage** : une fois l'Agent enregistré, le token est consommé. Pour ajouter un autre Agent, l'admin génère un nouveau token depuis l'UI. ### API Endpoints — Registration | Méthode | Route | Auth | Description | |---|---|---|---| | `POST` | `/api/sites/{id}/tokens` | Admin | Génère un nouveau token d'enregistrement | | `GET` | `/api/sites/{id}/tokens` | Admin | Liste les tokens actifs | | `DELETE` | `/api/sites/{id}/tokens/{tokenId}` | Admin | Révoque un token | | `POST` | `/api/agents/register` | Token | Enregistre un Agent (public, sans auth préalable) | | `GET` | `/api/agents/{id}/heartbeat` | API Key | Heartbeat Agent | | `GET` | `/api/sites/{id}/agents` | Admin | Liste les Agents du site | ### Token Security * Token = `UUID v4` (128 bits, 36 chars) * Stocké en base : `SHA256(token)` * Affiche en clair **1 seule fois** à la création * Durée de vie : configurable (défaut 24h) * Révocable depuis l'UI * Une fois l'Agent enregistré → automatiquement expiré --- # 12. Heimdall Agent Optional Docker component. Purpose: * Manage remote sites * Communicate with local cameras * Process local streams * Reduce WAN traffic * **Stream live video via WebRTC P2P** vers le navigateur Communication: * HTTPS (REST API + SignalR WebSocket) * Secure authentication (API key) * **SignalR — signaling WebRTC** (SDP + ICE candidates) * **WebRTC P2P** — flux vidéo direct (SRTP/SCTP) avec le navigateur ## Live Video Streaming — WebRTC P2P Le Heimdall Agent utilise **SIPSorcery** pour diffuser le flux vidéo en direct vers le navigateur via WebRTC, sans passer par le serveur central. ### Pipeline ```text Caméra RTSP │ ▼ FFmpeg (demux RTSP → decode → encode H264) │ ┌─────────────────┐ ▼ │ │ RTP stream (H264 encodé) │ SIPSorcery │ │ │ WebRTC Peer │ ▼ │ │ FFmpegListener (capture les frames) ──→ │ addTrack(H264) │ │ createOffer() │ │ ICE/STUN/TURN │ └────────┬────────┘ │ WebRTC P2P (SRTP/H264) │ ▼ Navigateur (Blazor)