# Heimdall — Master Specification Technique > **Version :** 2.0 | **Date :** 2026-07-16 > **Stack :** .NET 10+ / Blazor MudBlazor / PostgreSQL / ONNX Runtime (agents) / SIPSorcery / WebRTC > **Status :** SPECIFICATION FINALE — synthèse de 5600+ lignes de docs, revue par 5 agents experts > > **Documents sources fusionnés :** `specs.md`, `implementation.md`, `notifications.md`, `signalr-usage.md`, > `auth-roles.md`, `pwa.md`, `hangfire-usage.md`, `ui-pages.md` > > **Correctifs intégrés :** 5 agents (council, security, db, ai, perf) ont analysé la spec originale > et identifié **36 issues critiques** résolues dans ce document. --- ## Préambule — Décisions Architecturales ### D1 — Accès mobile via la PWA du serveur Le client natif est retiré. L’application Blazor devient la cible mobile installable ; la première version conserve Interactive Server avec une page hors connexion et Web Push. La consultation métier hors ligne nécessitera une couche cliente autonome. Voir [l’audit PWA](pwa.md). ### D2 — Topologie : API + Web fusionnés (1 conteneur) | Choix | Raison | |---|---| | **Api + Web = même conteneur** | Blazor Server + API en appel direct = latence < 2ms | | Conteneurs séparés rejeté | Double-hop (SignalR → Web → API → DB) ajoute 50-100ms par interaction | **Exception** : En scaling horizontal, on peut séparer les conteneurs avec un Redis backplane. ### D3 — TURN/Coturn obligatoire (pas optionnel) | Choix | Raison | |---|---| | **Coturn REQUIS** | CGNAT (4G/5G), pare-feu entreprises, Starlink — toute installation derrière NAT | | Optionnel rejeté | WebRTC échoue silencieusement sans TURN → support impossible | ### D4 — Agents : Installation Docker uniquement | Choix | Raison | |---|---| | **Docker uniquement** | FFmpeg, SIPSorcery, YOLOv8 (ONNX Runtime) ont des dépendances natives complexes | | Installation manuelle rejetée | Gestion des versions, dépendances système, mise à jour = cauchemar sans conteneurisation | **Conséquence** : L'Agent est distribué exclusivement via `heimdall/agent:latest` (Docker Hub / registry privée). Pas de binaire standalone, pas de .deb, pas d'installation manuelle. La mise à jour se fait par `docker pull` + redémarrage. ### D6 — SFU (MediaMTX) différé à v2 | Choix | Raison | |---|---| | **P2P uniquement en v1** (1 viewer/caméra max) | Complexité de transition P2P→SFU sous-estimée | | SFU repoussé à v2 | Renégociation SDP pendant flux actif = perte d'images, protocole non spécifié | ### D7 — CQRS avec MediatR in-process (pas de message broker) | Choix | Raison | |---|---| | **MediatR in-process + CQRS** | Architecture monolithe — aucun besoin de broker externe | | RabbitMQ/Kafka rejeté | Overkill pour un monolithe Clean Architecture | | SignalR + Hangfire couvrent les besoins asynchrones | Events temps réel → SignalR, Jobs différés → Hangfire | **Impact** : L'Application layer est organisée par domaine (Sites/, Cameras/, etc.) avec séparation Commandes/Requêtes. Les Handlers MediatR remplacent les services. Les pipelines MediatR (ValidationBehavior, LoggingBehavior) remplacent les filtres MVC. **Architecture CQRS** : ``` Contrôleur → IMediator.Send(Command/Query) → [ValidationBehavior] → [LoggingBehavior] → Handler → IApplicationDbContext ↓ (si événement) INotification → SignalR broadcast ``` --- ## PARTIE 1 : Architecture Globale ### 1.1 Vision Heimdall est une plateforme de vidéosurveillance IA locale, auto-hébergée, multi-site. 100% locale — aucun cloud, aucune dépendance externe obligatoire. ### 1.2 Principes Fondateurs | Principe | Application | |---|---| | **Privacy First** | IA ONNX Runtime en local sur les agents, 0 envoi de données au cloud | | **Multi-site** | 1 serveur Central + N Agents distants (sites physiques séparés) | | **Clean Architecture / CQRS** | Domain → Application → Infrastructure → Api/Web | | **Temps réel** | SignalR (5 hubs), WebRTC P2P < 500ms (LAN) | | **IA locale** | YOLOv8 nano ONNX (Agent CPU) + GPU NVIDIA/AMD/Intel sur agents équipés, mutualisable inter-sites via broker | ### 1.3 Architecture Logique ``` ┌────────────────────────────────────────────────────────────────────────┐ │ HEIMDALL CENTRAL (1 container) │ │ │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌────────────┐ │ │ │ Api REST + │ │ Web Blazor │ │ Workers │ │ Broker IA │ │ │ │ SignalR Hubs │ │ MudBlazor │ │ Hangfire │ │ .AI Server │ │ │ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │ Ollama │ │ │ │ │ │ └────────────┘ │ │ └──────────────────┴─────────────────┘ │ │ │ PostgreSQL / Hangfire (schema séparé) │ │ │ RustFS / S3 │ └──────────────────────────────┼────────────────────────────────────────┘ │ HTTPS REST + SignalR (events + signaling) │ ┌─────────┴──────────┐ │ │ ┌────────┴───────┐ ┌────────┴───────┐ │ Agent A │ │ Agent B │ │ (site distant) │ │ (site distant) │ │ │ │ │ │ SIPSorcery │ │ SIPSorcery │ │ WebRTC Peer │ │ WebRTC Peer │ │ FFmpeg │ │ FFmpeg │ │ YOLOv8 nano │ │ YOLOv8 nano │ │ Hangfire InMem │ │ Hangfire InMem │ └────────┬───────┘ └────────┬───────┘ │ │ P2P WebRTC (SRTP/H264) │ ◄════════════════════════════════►│ Navigateur ``` ### 1.4 Conteneurs Docker ```yaml services: heimdall-central: # Api + Web + Workers fusionnés (1 conteneur) heimdall-agent: # SIPSorcery + FFmpeg + YOLOv8 + Hangfire InMemory postgresql: # Base de données (app + hangfire) rustfs: # Stockage S3 (enregistrements) # L'IA lourde (détection, visages, LPR) tourne sur les agents GPU (ONNX Runtime) — pas de service central ollama: # LLM local (résumés quotidiens) coturn: # TURN relay (OBLIGATOIRE, pas optionnel) redis: # Cache + SignalR backplane (optionnel, scaling) ``` --- ## PARTIE 2 : Domain Model — Entités Complètes ### 2.1 Définitions ``` Site Agent Camera ├── Id (Guid) PK ├── Id (Guid) PK ├── Id (Guid) PK ├── Name ├── SiteId (FK) ├── SiteId (FK) ├── Address ├── Name ├── AgentId (FK) ← NOUVEAU ├── Timezone ├── Hostname ├── Name ├── Enabled ├── Version ├── Manufacturer ├── Registration ├── Status ├── Model │ TokenHash (string) │ (Online/Offline/Err) ├── RtspUrl │ TokenExpiresAt ├── LastHeartbeat ├── Status ├── IsDeleted ├── PublicIp ├── Capabilities │ (soft delete) ├── Capabilities │ (Ptz, Audio, Motion) ├── CreatedAt │ HasGpu, CpuCores ├── Credentials (1:1) ├── UpdatedAt ├── ApiKeyHash ├── DetectionProfileId ├── DeletedAt ├── ApiKeyPrefix ├── StoragePolicyId (FK) ├── IsDeleted ├── IsDeleted ├── CreatedAt ├── CreatedAt ├── UpdatedAt ├── UpdatedAt └── DeletedAt └── DeletedAt CameraCredentials CameraDetectionProfile StoragePolicy ├── CameraId (PK, FK) ├── CameraId (PK, FK) ├── Id (Guid) PK ├── OnvifUsername ├── DetectPerson ├── Name ├── OnvifPassword ├── DetectVehicle ├── RetentionDays │ (chiffré) ├── DetectAnimal ├── StorageProvider ├── RtspUsername ├── DetectPackage │ (S3, Local) ├── RtspPassword ├── DetectMotion ├── CreatedAt │ (chiffré) ├── FaceRecognition └── UpdatedAt ├── UpdatedAt ├── LicensePlateRecog └── CreatedAt ├── SnapshotIntervalMs ├── MotionThreshold ├── MinConfidence ← NOUVEAU ├── RequireMotionForAI ← NOUVEAU (DÉFAUT: true) ├── DedupCooldownSec ← NOUVEAU ├── MaxEventsPerMinute ← NOUVEAU └── YoloModel Person Vehicle Event ├── Id (Guid) PK ├── Id (Guid) PK ├── Id (Guid) PK ├── Name ├── LicensePlate ├── SiteId (FK) ├── Photo ├── PersonId (FK) ├── CameraId (FK) ├── IsUnknown ├── Make ├── Type (enum) ├── FaceSamples ├── Model ├── Timestamp ├── FaceEmbeddingHash ├── Color ├── CreatedAt │ (string) ← NOUVEAU ├── CreatedAt ├── TrackId (Guid?) ← NOUVEAU ├── Notes └── UpdatedAt ├── DetectionHash ← NOUVEAU ├── IsDeleted │ (string, dedup key) ├── CreatedAt ├── IsSuppressed ← NOUVEAU └── UpdatedAt ├── PersonId (FK) ← NOUVEAU ├── VehicleId (FK) ← NOUVEAU Recording LicensePlate ├── RecordingId (FK?) ← NOUVEAU ├── Id (Guid) PK ├── Id (Guid) PK ├── ParentEventId (FK) ← NOUVEAU ├── CameraId (FK) ├── PlateText ├── SnapshotPath ├── Timestamp ├── VehicleId (FK) └── Metadata (jsonb) ├── Duration ├── PersonId (FK?) ├── StoragePath ├── Confidence ├── SizeBytes ├── CreatedAt ├── StorageProvider └── UpdatedAt ├── StoragePolicyId (FK) ├── CreatedAt UserSite UserNotificationConfig └── UpdatedAt ├── UserId (FK) ├── UserId (PK, FK) ├── SiteId (FK) ├── EmailEnabled ApiKey └── (PK composite) ├── GotifyEnabled ├── Id (Guid) PK ├── EmailAddress ├── KeyHash (HMACSHA256) NotificationTemplate ├── SubscribedEvents ├── KeyPrefix (8 chars) ├── Id (Guid) PK (List, jsonb) ├── SiteId (FK?) ├── EventType (enum) ├── Language ├── CreatedByUserId (FK) ├── Language ├── DailyDigest ├── CreatedAt ├── Channel ├── WeeklyDigest ├── ExpiresAt? ├── Subject ├── PersonCooldownSec ← NOUVEAU ├── Enabled ├── BodyMarkdown ├── VehicleCooldownSec ← NOUVEAU ├── LastUsedAt └── IsDefault └── UnknownPersonCooldownSec ← NOUVEAU └── IsDeleted AuditLog (NOUVEAU) User ├── Id (Guid) PK ├── Id (Guid) PK ├── UserId (FK) ├── DisplayName ├── Action ├── Theme ├── ResourceType ├── Language ├── ResourceId ├── TwoFactorEnabled ├── OldValue? ├── CreatedAt ├── NewValue? └── (IdentityUser) ├── IpAddress ├── Timestamp └── (append-only, immuable) ``` ### 2.2 Relations et Cardinalités | Relation | Type | Contrainte | |---|---|---| | Site → Agent | 1:N | Un Agent appartient à un Site | | Site → Camera | 1:N | Une caméra appartient à un Site | | Agent → Camera | 1:N | Une caméra est gérée par un Agent (nouveau) | | Camera → CameraCredentials | 1:1 | Identifiants chiffrés, stockage séparé | | Camera → DetectionProfile | 1:1 | Profil de détection intégré ou table séparée | | Camera → StoragePolicy | N:1 | Plusieurs caméras partagent une politique | | Camera → Recording | 1:N | Enregistrements vidéo | | Camera → Event | 1:N | Événements de détection | | Event → Person | N:1 | Une personne peut avoir N événements | | Event → Vehicle | N:1 | Un véhicule peut avoir N événements | | Event → Event (Parent) | N:1 | Hiérarchie d'événements (regroupement track) | | Event → Recording | N:1 | Lien événement → enregistrement pour playback | ### 2.3 Index PostgreSQL Essentiels ```sql -- Partitionnement obligatoire dès le jour 1 CREATE TABLE events ( id UUID, site_id UUID, camera_id UUID, type TEXT, timestamp TIMESTAMPTZ NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), metadata JSONB, ... ) PARTITION BY RANGE (timestamp); -- Créer les partitions mensuelles (via Hangfire ou pg_cron) CREATE TABLE events_2026_07 PARTITION OF events FOR VALUES FROM ('2026-07-01') TO ('2026-08-01'); -- Index composites critiques CREATE INDEX idx_events_camera_time ON events (camera_id, timestamp DESC); CREATE INDEX idx_events_site_time ON events (site_id, timestamp DESC); CREATE INDEX idx_events_type_time ON events (type, timestamp DESC); CREATE INDEX idx_events_track_id ON events (track_id); CREATE INDEX idx_events_detection_hash ON events (detection_hash); CREATE INDEX idx_events_parent_id ON events (parent_event_id); -- Index GIN pour jsonb (seulement si requêtes Metadata) CREATE INDEX idx_events_metadata ON events USING GIN (metadata jsonb_path_ops); -- Autres index CREATE INDEX idx_recordings_cleanup ON recordings (camera_id, timestamp); CREATE INDEX idx_recordings_storage_path ON recordings (storage_path); CREATE INDEX idx_agents_heartbeat ON agents (site_id, last_heartbeat) WHERE status = 'Online'; CREATE INDEX idx_persons_unknown ON persons (is_unknown, created_at); CREATE INDEX idx_license_plate ON license_plates USING GIN (plate_text gin_trgm_ops); -- pour recherche floue ``` --- ## PARTIE 3 : AI Pipeline et Dédoublonnage ### 3.1 Problème : Objets Stationnaires **Sans dédoublonnage** : une personne immobile 10 minutes génère : - 3000 snapshots (200ms × 600s) - 3000 inférences YOLOv8 nano - 3000 analyses IA (ONNX local ou via broker) - 3000 événements en base - 3000 notifications (email + gotify + in-app) **Solution** : Architecture de dédoublonnage à 4 niveaux. ### 3.2 Architecture de Dédoublonnage ``` ┌─────────────────────────────────────────────────────────────────────────┐ │ HEIMDALL DEDUPLICATION LAYER │ ├─────────────────────────────────────────────────────────────────────────┤ │ │ │ NIVEAU 0 — Motion Gate (Agent, pré-YOLO) │ │ ├── Pixel diff > MotionThreshold ? → continue vers YOLO │ │ └── Pas de mouvement depuis 1s ? → SKIP YOLO, pas de snapshot envoyé │ │ │ │ NIVEAU 1 — Spatial Dedup (Agent, post-YOLO) │ │ ├── IoU(bbox_courante, bbox_précédente) > 0.6 ? → MÊME objet │ │ │ → Incrémente DetectionCount, ne crée PAS d'événement │ │ ├── IoU > 0.6 mais > DedupCooldownSec écoulé ? → NOUVEL événement │ │ └── IoU ≤ 0.6 → NOUVEL objet → envoyer au Central │ │ │ │ NIVEAU 2 — Temporal Cooldown (Central, post-analyse) │ │ ├── Cache IMemoryCache par (cameraId, trackId, objectType) │ │ ├── Si clé existe encore → événement SUPPRIMÉ (IsSuppressed=true) │ │ └── Si clé expirée → événement CRÉÉ, clé reset avec nouveau cooldown │ │ │ │ NIVEAU 3 — Embedding Dedup (Central, visages) │ │ ├── Cache LRU d'embeddings faciaux (float[512], 10K entries) │ │ ├── Distance L2 < 0.6 ? → MÊME personne → supprimé │ │ ├── Personne connue trouvée → update last_seen, événement supprimé │ │ └── Personne inconnue → ajout cache avec TTL (5min défaut) │ │ │ │ NIVEAU 4 — Suppression Hiérarchique (Central, post-événement) │ │ ├── FaceRecognized émis → ne PAS émettre PersonDetected │ │ ├── LicensePlateDetected émis → ne PAS émettre VehicleDetected │ │ └── MotionDetected seul → événement SILENCIEUX (pas de notification) │ └─────────────────────────────────────────────────────────────────────────┘ ``` ### 3.3 Flux de Détection Complet ``` Agent : snapshot JPEG toutes les 200ms (adaptatif) │ ▼ [NIVEAU 0] Motion Gate (pixel diff) │ ├── Pas de mouvement → retour, pas de YOLO (économie 90%+ CPU) │ └── Mouvement détecté → YOLOv8 nano (Agent CPU) │ ▼ Objet trouvé ? (confidence > MinConfidence) │ ┌────┴────┐ │ │ NON OUI → [NIVEAU 1] Spatial Dedup │ ├── Même track (IoU > 0.6) + cooldown actif ? │ │ → IGNORER (pas d'envoi au Central) │ └── Nouvel objet OU cooldown expiré │ → ENVOYER snapshot au Central │ Retour attente │ ▼ Central reçoit snapshot │ ▼ [NIVEAU 3] Analyse IA (ONNX/broker) ├── Object Detection (YOLOv8, ~40ms GPU) ├── Face Recognition (si personne, ~40ms) └── ALPR (si véhicule + LPR, ~200ms) │ ┌──────────┴──────────┐ │ │ [NIVEAU 2] Cooldown [NIVEAU 3] Embedding Cache Central Cache LRU Visages │ │ └──────────┬──────────┘ ▼ [NIVEAU 4] Suppression Hiérarchique │ ▼ Création Événement + Notification (si non supprimé) ``` ### 3.4 Cooldowns par Défaut (CameraDetectionProfile) ```csharp public class CameraDetectionProfile { // -- Types d'objets à détecter -- public bool DetectPerson { get; set; } = true; public bool DetectVehicle { get; set; } = true; public bool DetectAnimal { get; set; } = false; public bool DetectPackage { get; set; } = false; public bool DetectMotion { get; set; } = true; // -- IA lourde (Central GPU) -- public bool FaceRecognition { get; set; } = true; public bool LicensePlateRecognition { get; set; } = true; // -- Paramètres de snapshot -- public int IdleIntervalMs { get; set; } = 1000; // Pas de mouvement public int MotionIntervalMs { get; set; } = 500; // Mouvement détecté public int ActiveIntervalMs { get; set; } = 200; // Objet détecté public double MotionThreshold { get; set; } = 0.3; // Pixel diff // -- Paramètres YOLO -- public string YoloModel { get; set; } = "yolov8n"; public double MinConfidence { get; set; } = 0.4; // ← NOUVEAU // -- Dédoublonnage (NOUVEAU) -- public bool RequireMotionForAI { get; set; } = true; // Motion gate public double IoUThreshold { get; set; } = 0.6; // Spatial dedup public int PersonCooldownSec { get; set; } = 30; // Cooldown entre events public int VehicleCooldownSec { get; set; } = 60; public int AnimalCooldownSec { get; set; } = 120; public int UnknownPersonCooldownSec { get; set; } = 300; // 5 min public int MaxEventsPerMinute { get; set; } = 20; // Rate limit } ``` ### 3.5 Pipeline Degradation (Circuit Breaker IA) | Niveau | État | Action | |---|---|---| | 0 | Normal | Pipeline complet : Agent YOLO → analyse IA (locale ou broker) | | 1 | Exécutant IA lent (>1s) | Agent only (YOLOv8 nano, confidence baissée à 0.3) | | 2 | Exécutant IA down / broker injoignable | Agent only + détection de mouvement seulement | | 3 | Agent CPU >80% | Snapshots réduits de moitié, alert admin | | 4 | Queue overflow | Drop oldest snapshots, alert admin | ### 3.6 Gestion des Erreurs IA (exécutant / broker) | Erreur | Comportement | Récupération | |---|---|---| | Timeout (5s) | Retry 1x après 100ms, puis degrade level 1 | Health check toutes les 30s | | HTTP 503 | Degrade level 2 immédiat | Health check toutes les 10s | | Prédiction vide | Log, aucun événement | Normal | | Module désactivé | Skip cet appel, log | Normal (module peut être réactivé via API) | --- ## PARTIE 4 : Authentification, Rôles et Sécurité ### 4.1 Architecture Auth ``` ┌──────────────────────────────────────────────────────────────────┐ │ AUTHENTIFICATION │ ├──────────────────────────────────────────────────────────────────┤ │ │ │ HUMAINS (email + password + 2FA TOTP) │ │ ├── Admin : tous les sites, toutes les permissions │ │ ├── Superviseur : sites assignés, lecture + écriture limitée │ │ └── Viewer : sites assignés, lecture seule │ │ │ │ AGENTS (API Key HMACSHA256 + salt) │ │ ├── Clé générée par l'Admin via API │ │ ├── Liée à un Site (scope automatique) │ │ └── Rotation possible, révocation immédiate │ │ │ │ JWT Claims : │ │ ├── sub (userId) │ │ ├── role (Admin|Superviseur|Viewer) │ │ ├── permission[] (liste plate des permissions) │ │ └── ⚠️ Plus de site IDs dans le JWT (sécurité) │ │ │ │ Site-Scope : lookup serveur à chaque requête │ │ (Middleware SiteScope) — pas de site IDs dans le token │ └──────────────────────────────────────────────────────────────────┘ ``` ### 4.2 Permissions (Policies) | Permission | Admin | Superviseur | Viewer | |---|---|---|---| | `Site.Read` | ✅ | ✅ | ✅ | | `Site.Write` | ✅ | ❌ | ❌ | | `Site.Delete` | ✅ | ❌ | ❌ | | `Camera.Read` | ✅ | ✅ | ✅ | | `Camera.Write` | ✅ | ✅ (ses sites) | ❌ | | `Camera.Live` | ✅ | ✅ | ✅ | | `Camera.Record` | ✅ | ✅ | ❌ | | `Camera.Snapshot` | ✅ | ✅ | ❌ | | `Event.Read` | ✅ | ✅ | ✅ | | `Person.Read` | ✅ | ✅ | ✅ | | `Person.Write` | ✅ | ✅ | ❌ | | `Admin.Manage` | ✅ | ❌ | ❌ | | `Admin.Users` | ✅ | ❌ | ❌ | | `Admin.ApiKeys` | ✅ | ❌ | ❌ | | `Admin.Jobs` | ✅ | ❌ | ❌ | ### 4.3 Mesures de Sécurité Implémentées | Mesure | Détail | Priorité | |---|---|---| | Rate limiting | `AspNetCoreRateLimit` sur auth (5 tentatives/15min) | P0 | | 2FA TOTP | Récupération : 10 codes de secours à l'enrôlement | P0 | | CORS | Domaines connus uniquement (pas `AllowAnyOrigin`) | P0 | | API Keys HMACSHA256 | Avec salt par clé, préfixe 8 chars pour identification | P0 | | IDataProtector | Purposes isolées par type : `CameraCredentials`, `NotificationCredentials`, `SmtpConfig` | P0 | | Key ring partagé | Volume Docker monté : `/root/.aspnet/DataProtection-Keys` | P0 | | Audit logging | Table `AuditLog` append-only (login, admin actions, permissions) | P0 | | HTTPS partout | Y compris AMQP TLS vers le broker (certificat CA auto) | P1 | | Docker secrets | `/run/secrets/` en production, env vars en dev | P1 | | Secrets dans logs | Sanitized : `password`, `token`, `secret`, `snapshotUrl` masqués dans Serilog et Sentry | P1 | | Mot de passe | Min 8 car, 1 maj, 1 chiffre. Check HaveIBeenPwned | P2 | ### 4.4 StreamingHub — Sécurité renforcée ```csharp [Authorize(Policy = AppPermissions.CameraLive)] // ← PERMISSION explicite public class StreamingHub : Hub { public async Task RequestStream(Guid cameraId) { // 1. Vérifier que l'utilisateur a accès au site de la caméra var camera = await _db.Cameras .Where(c => c.Id == cameraId) .Select(c => new { c.SiteId }) .FirstOrDefaultAsync(); if (camera == null) throw new HubException("Camera not found"); if (!Context.User.IsInRole(AppRoles.Admin)) { var userId = Context.User.GetUserId(); var hasAccess = await _db.UserSites .AnyAsync(us => us.UserId == userId && us.SiteId == camera.SiteId); if (!hasAccess) throw new HubException("Access denied to this camera"); } // 2. Ajouter aux groupes await Groups.AddToGroupAsync(Context.ConnectionId, $"viewer-{cameraId}"); await Clients.Group($"camera-{cameraId}") .SendAsync("ViewerConnected", Context.ConnectionId); } } ``` ### 4.5 Enregistrement Agent — Flux Complet ``` Admin crée Site │ ▼ POST /api/sites → génère token + API Key (PREMIÈRE ET UNIQUE FOIS) │ ├── RegistrationToken (plain, affiché 1 fois) ├── ApiKey (plain, affiché 1 fois — NOUVEAU) ├── TokenHash (SHA256) en DB ├── ApiKeyHash (HMACSHA256) en DB └── docker run command avec les deux clés Admin donne le token + API Key à l'Agent (hors bande) │ ▼ Agent démarre avec HEIMDALL_SITE_TOKEN + HEIMDALL_API_KEY │ ▼ POST /api/agents/register { token, hostname, version, apiKey } │ ├── Token valide ? → Agent enregistré, statut Online ├── ApiKey associée au site pour les appels suivants └── Retour : { agentId, iceServers } │ ▼ Agent lance heartbeat (30s) avec API Key Agent lance CameraHealthCheck (30s) avec API Key Agent se connecte à SignalR avec API Key ``` --- ## PARTIE 5 : SignalR — 5 Hubs Détaillés ### 5.1 Hubs | Hub | Route | Auth | Clients | Usage | |---|---|---|---|---| | **EventsHub** | `/hubs/events` | JWT + API Key | Browser + Agent | Événements détection en temps réel | | **StreamingHub** | `/hubs/streaming` | JWT + API Key (+ Camera.Live) | Browser + Agent | Signaling WebRTC (SDP + ICE) | | **MonitoringHub** | `/hubs/monitoring` | JWT | Browser | Status agents, caméras, stockage | | **NotificationsHub** | `/hubs/notifications` | JWT | Browser | Notifications in-app avec badge | | **AdminHub** | `/hubs/admin` | JWT (Admin only) | Browser (Admin) | Broadcast changements config | ### 5.2 Groupes SignalR ```csharp // Standardisé sur tous les hubs : "all-sites" // Admin : voit tout (Events, Monitoring) "site-{siteId}" // User : voit ses sites (Events, Monitoring) "camera-{cameraId}" // Agent source pour le streaming "viewer-{cameraId}" // Browser viewer du flux "notif-{userId}" // Notifications par utilisateur "admin-broadcast" // Broadcast admin (Config changée) ``` ### 5.3 Événements par Hub **EventsHub** | Event | Payload | Destinataires | |---|---|---| | `EventCreated` | `EventDto` | Groupe `site-{siteId}` | | `PersonDetected` | `PersonEventDto` | Groupe `site-{siteId}` | | `UnknownPerson` | `UnknownPersonDto` | `site-{siteId}` + `all-sites` | | `VehicleDetected` | `VehicleEventDto` | Groupe `site-{siteId}` | | `LicensePlateRead` | `PlateEventDto` | Groupe `site-{siteId}` | | `MotionDetected` | `MotionDto` | Groupe `site-{siteId}` (silencieux) | **MonitoringHub** | Event | Payload | Destinataires | |---|---|---| | `AgentStatusChanged` | `AgentStatusDto` | Groupe `monitoring-site-{siteId}` | | `CameraStatusChanged` | `CameraStatusDto` | Groupe `monitoring-site-{siteId}` | | `StorageUsageUpdated` | `StorageDto` | `admin-broadcast` | | `GpuUsageUpdated` | `GpuDto` | `admin-broadcast` | | `JobStatusChanged` | `JobDto` | `admin-broadcast` | **NotificationsHub** | Event | Payload | Destinataires | |---|---|---| | `NewNotification` | `NotificationDto` | `notif-{userId}` | | `UnreadCount` | `int` | `notif-{userId}` | **AdminHub** | Event | Payload | Destinataires | |---|---|---| | `ConfigChanged` | `ConfigChangeDto` | `admin-broadcast` | | `CameraAdded` | `CameraDto` | `admin-broadcast` + `site-{siteId}` | | `CameraRemoved` | `Guid` | `admin-broadcast` + `site-{siteId}` | | `UserRoleChanged` | `UserRoleDto` | `admin-broadcast` | ### 5.4 Scaling (Backplane Redis) ```csharp // Program.cs — quand multi-instance Central builder.Services.AddSignalR() .AddStackExchangeRedis(config => { config.ConnectionFactory = async _ => { var connection = await ConnectionMultiplexer.ConnectAsync( builder.Configuration.GetConnectionString("Redis")); return connection; }; }); ``` --- ## PARTIE 6 : WebRTC et Pipeline Vidéo ### 6.1 Stack | Composant | Technologie | Version | |---|---|---| | WebRTC | SIPSorcery | 10.0.12+ | | Capture | FFmpeg (via SIPSorceryMedia.FFmpeg) | 6+ | | Streaming | WebRTC P2P (SRTP/H264, pas de decode→re-encode) | — | | TURN | Coturn | 4.6+ | | SFU | MediaMTX (v2 uniquement) | 1.0+ | ### 6.2 Pipeline Basse Latence (< 500ms LAN) ``` Caméra RTSP (H264) │ ├── FFmpeg (mode PASSTHROUGH, pas de decode→re-encode) │ │ ffmpeg -rtsp_transport tcp -buffer_size 0 -max_delay 0 │ │ -i rtsp://... -g 1 -tune zerolatency │ │ -preset ultrafast -c:v copy ← PASSTHROUGH ! │ │ -f rawvideo pipe:1 │ └── Latence : ~100ms (1 frame buffer) │ ▼ SIPSorcery WebRTC PeerConnection ├── Codec : H264 (pas de transcode) ├── DTLS-SRTP : chiffrement natif └── ICE : STUN + TURN (coturn obligatoire) │ ▼ SignalR Signaling (/hubs/streaming) ├── SDP Offer → Browser ├── SDP Answer ← Browser └── ICE Candidates ↔ bidirectionnel │ ▼ Navigateur