Commit Graph
55 Commits
Author SHA1 Message Date
Arnaud Dartois e14e4cde78 feat(discovery): base caméras Strix — DB SQLite embarquée 100k+ patterns (Fixes #64)
- cameras.db récupérée depuis l'image Docker eduard256/strix (MIT © 2025 eduard256,
  /app/cameras.db) : 3 688 marques, 17 313 streams, 73 238 modèles, 4 186 presets, 2 406 OUIs
- SqliteCameraDatabase (Microsoft.Data.Sqlite pur managé, Alpine-safe) :
  Search (presets+brands+models, multi-mots), BuildStreams (ids b:/m:/p:,
  placeholders [CHANNEL]/[USERNAME]/[PASSWORD]..., portFilter), LookupOui
- Copiée en Content CopyToOutputDirectory → dispo Central + Agent + tests
- Central : SearchDatabase/BuildStreamUrls/ResolveOuiVendor préfèrent la DB
  (fallback catalogue statique + templates)
- Agent : BuildCandidateUrls utilise les patterns réels de la marque (DB) sinon templates
- Tests : 10 (search marque/modèle/preset, build URLs, portFilter, OUI)
2026-08-12 08:45:18 +02:00
Arnaud Dartois 6df44cb9e0 chore: auto-commit 2026-08-11 22:57 [Heimdall] src/Heimdall.Agent/Services/NetworkCameraScanner.cs, src/Heimdall.Application/DTOs/SiteCredentialDto.cs, src/Heimdall.Application/Services/ICameraDiscoveryService.cs, src/Heimdall.Infrastructure/Services/Discovery/CameraDiscoveryService.cs, src/Heimdall.Infrastructure/Services/Discovery/StreamTesterService.cs… 2026-08-11 22:57:42 +02:00
Arnaud Dartois ac1871e8d9 feat(agent): test de flux multi-protocoles — RTMP, Bubble/Uniview, HomeKit (Fixes #67)
- RTMP : handshake minimal C0/C1 (0x03 + 1536 octets) — serveur qui répond C0 = vivant
- Bubble (Uniview) : TCP + requête HTTP tramée (préambule binaire 8 octets, go2rtc pkg/bubble) + vérif HTTP/1.1 200
- HomeKit : TCP + GET /accessories — toute réponse HTTP (200/401/470) prouve un service HAP vivant
- StreamTesterService central : dvrip/bubble/homekit acceptés (TCP reachable)
- Timeouts explicites Task.WhenAny partout (jamais de hang, cf. 491a253)
- Tests : 4 (serveurs TCP factices RTMP/HTTP)
2026-08-11 22:25:59 +02:00
Arnaud Dartois c0768b3804 feat(agent): test de flux DVRIP — handshake login Sofia MD5 (Fixes #66)
- IsDvripUrlAliveAsync : connexion TCP + login DVRIP-Web (paquet 20 octets,
  cmd=1000), hash Sofia (md5 + mapping 62 chars) transposé de go2rtc pkg/dvrip
- Ret=100/515 = caméra DVRIP vivante (login prouve identifiants + canal)
- Timeouts explicites Task.WhenAny (jamais de hang, cf. 491a253)
- p:dvrrip ajouté aux candidates quand 34567/34568/37777 ouvert
- ProtocolFromUrl : dvrip:// → StreamProtocol.Dvrip (déjà fait #68)
- Tests : 4 (SofiaHash vecteur go2rtc, layout paquet, payload login, ctor)
2026-08-11 22:22:31 +02:00
Arnaud Dartois e5b035745d feat(agent): découverte mDNS/HomeKit — probe multicast _hap._tcp (Fixes #62)
- HomeKitMdnsProbe : paquet DNS PTR brut sur 224.0.0.251:5353, écoute 2 s
  avec timeout explicite Task.WhenAny (jamais de hang, cf. 491a253)
- Parseur DNS complet : PTR/SRV/TXT/A avec pointeurs de compression, TXT
  (ci/id/md/sf), dédup par IP, mapping IP via SRV target
- Filtre catégories 17 (camera) et 18 (doorbell) — Strix pkg/probe/mdns.go
- Intégré au scan broadcast de NetworkCameraScanner ; devices HomeKit avec
  HomeKitName/HomeKitDeviceId/HomeKitModel remplis → classés HomeKit côté central
- Les devices HomeKit ne génèrent plus de fausses URLs RTSP (flux HAP)
- Tests : 4 (parseur PTR/SRV/TXT/A, filtrage catégories, dédup, no-hang)
2026-08-11 22:16:19 +02:00
Arnaud Dartois f713abc7ca feat(discovery): reverse DNS pour le hostname des devices détectés (Fixes #63)
- ResolveHostnameAsync : PTR via Dns.GetHostEntryAsync avec timeout 500 ms,
  échec silencieux (le scan n'est jamais bloqué par un DNS lent)
- Fallback uniquement : le hostname ONVIF/DVRIP/mDNS existant est conservé
2026-08-11 22:06:10 +02:00
Arnaud Dartois 84c3e3682f feat(discovery): ports de scan élargis + portFilter par protocole (Fixes #68)
- Agent : 22 ports probés (ajout 8080/5544/10554/1935/81/88/8090/8001/8081/7070/7447/51826)
- CameraStreamTemplates : port par défaut par schéma (rtsp=554, rtmp=1935, http=80,
  dvrip=34567, bubble=80), filtre de compatibilité protocole → les URLs ne portent
  plus de ports incohérents (ex. RTSP sur :80) ; plus de forçage de ports[0]
- Nouveaux templates : p:rtmp, b:uniview (bubble), b:reolink, dvrip:// dans p:dvrrip/b:dahua
- ProtocolFromUrl : Dvrip/Bubble/HomeKit reconnus côté central
- Tests : 9 tests unitaires CameraStreamTemplates
2026-08-11 22:04:10 +02:00
Arnaud Dartois 33a08f5ea0 fix(agent): async UDP receive hangs — explicit timeout via Task.WhenAny
Refs #54 #55 #56

Socket.ReceiveTimeout only applies to synchronous Receive() — the async
ReceiveAsync(ct) on the ONVIF multicast, DVRIP broadcast and unicast
ONVIF probe waited forever when no camera replied, so a scan never
completed (no response → hang). Enforce the listen window explicitly
with Task.WhenAny(receiveTask, Task.Delay(...)):

- WS-Discovery multicast: 5s listen window
- DVRIP broadcast: 2s listen window
- unicast ONVIF probe: OnvifUdpTimeout (500ms)

Also fixed ValueTask→Task (.AsTask()) for the WhenAny overload.
2026-08-11 21:36:48 +02:00
Arnaud Dartois 9e64b03f31 feat(agent): auto main stream via ONVIF GetProfiles/GetStreamUri
Fixes #56

The agent asks the camera for its REAL stream URLs instead of guessing
from templates: GetProfiles (media service) then GetStreamUri per profile
(RTP-Unicast/RTSP), trying the site credential pool (anonymous → digest →
text). The returned URLs get the probed IP injected (buggy 0.0.0.0 or
different host) and the credentials embedded, so the Central gets a
directly usable main stream.

- Generalized BuildSoapEnvelope/PostSoapAsync for device + media services
- OnvifProbe carries StreamUrls; ProbeHostAsync and the WS-Discovery
  multicast enrichment both fill them
- BuildFinalDeviceAsync prioritizes real GetStreamUri URLs over templates
  and keeps them even if the stream test fails (camera proven by ONVIF)
- Refactored TestUrlsAsync shared by both paths
2026-08-11 21:18:26 +02:00
Arnaud Dartois c38d69a1e5 feat(agent): pipeline capture vidéo — FFmpeg par caméra, snapshots adaptatifs, frames → analyseur (Fixes #1)
- CameraStreamService enregistré dans le DI + hosted SnapshotPipelineService
  qui synchronise les captures avec les caméras assignées (Central = source de
  vérité via clés camera.<id>.* dans la config agent ; fallback local Agent:Cameras)
- Découpage du flux MJPEG en frames JPEG (JpegFrameSplitter, marqueurs SOI/EOI)
- Intervalle adaptatif (spec Phase 15) : scène vide 1000ms / mouvement 500ms /
  objet détecté 200ms, doublé si CPU > 80% ; état de scène piloté par les
  résultats de l'analyseur + proxy de mouvement (FrameMotionDetector, pixel diff
  réel en Phase 16)
- Channel borné 100 snapshots (DropOldest) — backpressure + compteur de drops
  et log rate-limité (alerte admin via remontée des logs agent)
- Frames réellement transmises à FrameAnalyzerService (compteur AnalyzedFrameCount)
- Central : GET /api/settings/agent/{id} embarque les caméras assignées
  (name/rtsp/sub_rtsp/enabled) ; ConfigReceiverService les applique à chaud
- Tests : JpegFrameSplitter, intervalle adaptatif, tracker de scène, motion
  detector, CameraConfigStore, pipeline (snapshot → analyseur), handler config
2026-08-11 21:16:28 +02:00
Arnaud Dartois ea773b17a1 feat(agent): Dahua/Imou DVRIP broadcast discovery
Fixes #55

Sends the DVRIP probe (ff00000000000000000000000000fa0500000000) 3x over
UDP broadcast on port 34569 and parses the NetWork.NetCommon JSON replies
(HostIP, HostName, MAC, HttpPort, Ret). Finds Dahua/Imou cameras even
when RTSP/ONVIF are disabled, with MAC/vendor from the reply itself.

- Filter Ret != 100 error replies, require HostIP+HostName
- Devices are created with OpenPorts [37777] (DVRIP) so they pass the
  camera-evidence filter and get classified Standard by the Central
- Transposed from go2rtc internal/dvrip
2026-08-11 21:13:32 +02:00
Arnaud Dartois 1bc4c73f23 feat(agent): ONVIF WS-Discovery multicast camera discovery
Fixes #54

The agent now sends one UDP multicast probe (239.255.255.250:3702) per
scan and collects ONVIF replies for ~5s, instead of relying solely on the
per-IP TCP port sweep. This finds every ONVIF camera on the LAN — even
those with TCP 3702 closed — in one request, with name/hardware from the
WS-Discovery scopes (and the buggy 0.0.0.0 XAddrs fix).

- ScanAsync runs the broadcast probes in parallel with the TCP sweep and
  merges results (dedupe by IP)
- Factorized BuildFinalDeviceAsync (evidence filter + live stream test)
  shared by the TCP sweep and the multicast merge
- Transposed from go2rtc pkg/onvif DiscoveryStreamingDevices
2026-08-11 21:11:45 +02:00
Arnaud Dartois ddfa22bee6 fix(agent): camera discovery — host-network compose, parasite filtering, auto stream detection
- Compose (dev+prod): agent on host network (bridge 172.x was skipped by the
  scanner), listen on 8081 (ntfy owns 8080), CentralUrl via host/domain,
  healthcheck adapted, no Docker DNS
- Scanner: skip the LAN gateway (NAT router, never a camera); wider camera
  ports (+34567/34568 Imou SDK, +8000 Hikvision SDK); 750 ms port timeout;
  keep only devices with real camera evidence; RTSP OPTIONS + MJPEG
  content-type probes prove live streams from the agent (it is on the LAN)
- Central: drop Unknown devices (nginx/gunicorn/gateway) on submit; classify
  37777 DVRIP as Standard camera (not NVR), 8899 alone as NVR; persist
  agent-tested stream URLs flagged IsAlive; shared CameraStreamTemplates
  with the agent so both build identical candidate URLs
- UI: discoveries popup auto-selects the agent-verified main stream — no
  manual stream choice
2026-08-11 20:47:27 +02:00
Arnaud Dartois 0136bf33ec feat(logs): remontée des logs agents vers le central — buffer, API, UI (Fixes #50 #51 #52)
- Agent : LogBufferService (ring buffer borné, drop-oldest), AgentLoggingProvider
  (capture ILogger non-bloquante), LogSanitizer (masque password/token/secret/bearer),
  LogUploadService (batch POST /api/agents/{id}/logs, retry, drop si 400)
- Central : entité AgentLogEntry + migration AddAgentLogEntries (index AgentId+TimestampUtc),
  SubmitAgentLogsCommand (batch <= 200, entrées invalides ignorées),
  GetAgentLogsQuery (pagination, filtres niveau/période/recherche),
  endpoints POST + GET /api/agents/{id}/logs
- UI : onglet Logs dans AgentDetail (filtres, pagination, auto-refresh toggle)
- Logs agent enrichis : heartbeat succès (Debug), résolution IP (Debug)
- Tests : LogBufferServiceTests (6), AgentDetailLogsTests (4), handlers AgentLogs (8)
2026-08-11 18:51:52 +02:00
Arnaud Dartois ab705e72fa fix(agent): settings distants appliqués à chaud — log.level live + full reload complet (Fixes #20)
- log.level appliqué immédiatement via RuntimeLogLevel (règle globale en tête
  du LoggerFilterOptions partagé + RefreshFilters réflexif sur le LoggerFactory,
  API publique AddFilter retirée en .NET 10) — effet observable sur les loggers
  déjà créés, sans redémarrage
- FetchFullConfigAsync applique désormais TOUTES les clés du full config via le
  même pipeline que SettingChanged (heartbeat, log.level, credentials, …) au
  lieu de ne traiter que discovery.credentials
- Settings connus non dynamiques (ai.detection.*, detection.*, model.*,
  ffmpeg.*, yolo.*, camera.*) loggés explicitement « requires restart »
- Tests : effet observable sur loggers existants, abaissement de niveau,
  full reload complet (heartbeat + log.level + credential pool)
2026-08-11 17:34:22 +02:00
Arnaud Dartoisandnonobis f8f2b08d29 feat(agent): enrichissement ONVIF authentifié côté agent — pool chiffré via config (#49)
## What

L'enrichissement ONVIF authentifié est déplacé côté **agent**. Le pool de credentials du site (login/mdp) est exposé à l'agent via `GET /api/settings/agent/{id}` sous forme d'enveloppe AES-256-GCM (`AgentCredentialEnvelope`, clé dérivée du SHA-256 de l'API key) — déchiffrable uniquement côté agent. `NetworkCameraScanner` tente `GetDeviceInformation` avec chaque couple du pool (PasswordDigest puis PasswordText) et remonte des devices **déjà identifiés** (fabricant/modèle ONVIF + `CredentialLabel`). Le central persiste et marque le credential utilisé (`LastUsedAt`) — plus aucun appel réseau ONVIF côté central.

## Why

Le central n'est généralement **pas** sur le réseau des caméras : les appels ONVIF authentifiés qu'il faisait après réception des devices bruts échouaient. L'agent, lui, est sur le sous-réseau des caméras — c'est lui qui doit porter l'auth. Enrichissement et identification se font au moment du scan, avant la remontée.

## How

- `AgentCredentialEnvelope` (Application/Security) : AES-256-GCM, clé = SHA-256 de l'API key ; central chiffre (via l'`ApiKeyHash` stocké), agent déchiffre (via sa clé en clair).
- `GetEffectiveAgentConfigQuery` : ajoute `discovery.credentials` (pool chiffré) au dict de config.
- `SettingsController.GetEffectiveConfig` : accepte l'API key agent (vérification par site) en plus du JWT admin — corrige au passage un 403 latent sur cet endpoint.
- `NetworkCameraScanner` : probe ONVIF authentifié avec le pool (anonyme d'abord, puis chaque couple).
- `AgentCredentialStore` (mémoire, jamais sur disque) : reçoit le pool déchiffré par `ConfigReceiverService`, lu par `AgentDiscoveryService`.
- `CameraDiscoveryService` : suppression de l'enrichissement réseau ; persistance + `MarkUsed` via `CredentialLabel` ; vendor déduit du fabricant ONVIF remonté.
- `SitesController` : broadcast `ConfigReload` après add/delete credential pour que les agents re-fetch leur pool.
- Multi-agents : inchangé — upsert par (site, IP) et anti-doublon IP/MAC à la confirmation évitent les caméras en double même si un agent est éteint.

## Testing

- `dotnet build Heimdall.slnx` : 0 erreur / 0 warning.
- Application 346 verts, Agent 108 verts, Infrastructure 143 verts (hors Testcontainers).
- Web.Tests 213 verts — nouveaux bUnit : DiscoveriesPage (5) + SiteDetail credentials (4).

## Breaking Changes

Aucun changement de schéma (pas de migration). Comportement API : `GET /api/settings/agent/{id}` accepte désormais l'API key agent (accès élargi au cas d'usage prévu).

Related to #48

Co-authored-by: nonobis <nonobis@tordais.cc>
Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/49
2026-08-11 16:15:41 +02:00
Arnaud Dartois 3ff20ddf98 fix(agent): settings distants réellement appliqués (heartbeat live)
ConfigReceiverService.ApplySetting ne faisait que logger. Le setting
heartbeat.interval.seconds est désormais appliqué à chaud : écrit dans
AgentState.HeartbeatIntervalSeconds (snapshot thread-safe) et relu par
AgentRegistrationService à chaque cycle — plus besoin de redémarrer
l'agent pour changer l'intervalle. Validation 5-300s, valeurs invalides
ignorées sans muter l'état.

Tests : +2 (application live vérifiée, invalides ne mutent pas l'état).
2026-08-10 11:02:37 +02:00
Arnaud Dartois 1e3322cd1a fix(agent): heartbeat X-API-Key complet + métriques temps réel + hub config
- ApiKeyAuthenticationHandler accepte l'API key via query string access_token
  sur les chemins /hubs (WebSocket SignalR ne peut pas poser de header custom)
  → le ConfigReceiverService de l'agent peut se connecter au ConfigHub
- ConfigReceiverService.FetchFullConfigAsync : X-API-Key au lieu de Bearer
- Métriques heartbeat : CpuUsagePercent/MemoryUsageBytes/DiskUsagePercent/
  UptimeSeconds + IsOffline désormais transportées jusqu'à l'entité Agent
  (migration AddAgentLiveMetrics) ; IsOffline marque l'agent Offline
  immédiatement au lieu d'attendre le timeout 90s du HeartbeatMonitorJob
- docker-compose.local.yml : override aussi l'image agent (heimdall-agent:local)

Tests : +2 unit AgentRegistrationService (X-API-Key), +2 HeartbeatHandler
(métriques, offline), +3 intégration SignalR (ConfigHub query string) — verts.
2026-08-10 10:26:31 +02:00
Arnaud Dartois 4516761a3a fix(agent): authentifie le heartbeat via X-API-Key au lieu de Bearer
Le central (ApiKeyAuthenticationHandler) ne lit que le header X-API-Key.
L'agent posait Authorization: Bearer <apiKey> sur le client 'Central'
→ tout heartbeat et le heartbeat final de StopAsync renvoyait 401.
Corrige les deux chemins (identité existante + post-registration) et
verrouille le comportement avec deux tests (nouvelle identité, identité
réutilisée).
2026-08-10 10:09:27 +02:00
Arnaud Dartois 450e019617 feat(infra): intégration Sentry/GlitchTip complète
- Upgrade Sentry.AspNetCore v6.7.0 → v6.8.0
- Ajout Sentry base package à Infrastructure (pour SentryErrorReporter)
- Configuration SDK enrichie dans Web et Agent:
  - AutoSessionTracking=false (GlitchTip ne supporte pas)
  - EnableLogs=true (logs structurés)
  - CaptureBlockingCalls=true (détection .Result/.Wait())
  - CaptureFailedRequests=true (capture 4xx/5xx HttpClient)
  - IncludeActivityData=true (DiagnosticSource)
  - SetBeforeSend pour nettoyage PII (password, token, secret)
  - SetBeforeBreadcrumb pour filtrage breadcrumbs
  - SampleRate, AttachStacktrace, MaxBreadcrumbs configurés
  - Release depuis la config, Environment auto
  - StackTraceMode.Enhanced
  - double.Parse avec CultureInfo.InvariantCulture
  - UseSentry avec type explicite SentryAspNetCoreOptions
- Abstraction IErrorReporter dans Application (0 dép. Sentry)
- Implémentation SentryErrorReporter dans Infrastructure
- Enregistrement DI dans Infrastructure
- DSN de développement dans appsettings.Development.json
- .env.example avec Sentry__Dsn et Sentry__TracesSampleRate
2026-07-28 14:52:52 +00:00
Arnaud Dartois edc739dffe fix(sentry): use config pipeline for DSN, add MaxRequestBodySize and ProfilesSampleRate
- Heimdall.Web/Program.cs: use Sentry:Dsn from IConfiguration as primary
  source with legacy SENTRY_DSN env var as fallback (no hardcoded DSN)
- Heimdall.Agent/Program.cs: same pattern applied
- Both: add MaxRequestBodySize=Small and ProfilesSampleRate=0.05
  (previously missing); lower TracesSampleRate to 0.05
- appsettings.json: add Sentry:Dsn entry for discoverability

Resolves codify signal: hardcoded-sdk-credentials (C1)
2026-07-28 10:14:34 +00:00
Arnaud Dartois 87eb0982a7 refactor: replace URI string concatenation with EndsWith check
Replace new Uri(url.TrimEnd('/') + "/") pattern with explicit
EndsWith('/') check to avoid string concatenation inside URI
construction. Applies to 3 locations:
- Program.cs (Heimdall.Web) - HttpClient base address
- TokenRefreshHandler.cs - raw HttpClient for token refresh
- Program.cs (Heimdall.Agent) - Central service client
2026-07-27 18:43:25 +00:00
Arnaud Dartois fc5108a4fa fix(agent): add ffmpegPath parameter to CameraStreamService for deterministic testability 2026-07-24 06:38:15 +00:00
Arnaud Dartois 0745903fef test: add remaining handler tests for Users, Groups, Persons, Assignments, Discovery; more Agent + E2E tests 2026-07-23 19:19:05 +00:00
Arnaud Dartois 7678b4703a chore: add InternalsVisibleTo for Agent tests 2026-07-23 17:00:22 +00:00
Arnaud Dartois 262adc07cf test(agent): add service tests for CameraStream, ConfigReceiver, FrameAnalyzer, SystemMetrics, DTOs 2026-07-23 15:37:20 +00:00
Arnaud Dartois a33a436c26 chore: apply auto-fixes and code improvements
- AuthService: fix public registration logic revert
- JwtService: add ILogger dependency
- SoftDeleteInterceptor removed (merged)
- XML doc comments on all services
- Error boundary + error page in Blazor
- Optimize StatsService queries
- ApiClient error handling improvements
2026-07-20 09:50:43 +00:00
Arnaud Dartois 153be535d4 fix(multiple): auth, workers, EF Core, MudTheme fixes
- Auth: AssignmentsController auth bug, ReleaseCamera result, logout endpoint
- Security: open redirect fix
- Workers: AgentState thread-safety, CameraStreamService async, HttpClientFactory
- EF Core: AddCameraDiscoveryFields migration, DI interceptors, retry helper
- UI: MudTheme palette config, aria-labels on icon buttons
2026-07-19 19:58:45 +00:00
Arnaud Dartois 32025eae67 fix(infra): persist Data Protection keys to filesystem for Docker
- Add PersistKeysToFileSystem to /var/lib/heimdall/dp-keys so camera
  credential decryption survives container restarts
- Remove hardcoded connection string fallback, throw instead
- Add Microsoft.AspNetCore.DataProtection.Extensions dependency
2026-07-19 19:33:10 +00:00
Arnaud Dartois 363b43f779 fix: prevent orphaned TaskCompletionSource in frame queue
Changed BoundedChannelFullMode from DropOldest to DropWrite.
With DropOldest, the oldest queued job is silently removed when the
channel is full, but its TaskCompletionSource is never completed —
causing the caller to hang indefinitely.

DropWrite rejects new writes when full, returning TryWrite=false,
which triggers the existing graceful fallback (tcs.TrySetResult(null)).
2026-07-19 15:54:46 +00:00
Arnaud Dartois d9f5224e21 fix: resolve review findings — SignalR JWT, enum serialization, TCS leak, thread safety 2026-07-19 15:54:13 +00:00
Arnaud Dartois 70176124cb refactor(css): merge duplicate dark mode media blocks into one
- Single @media (prefers-color-scheme: dark) block containing both
  auth-specific rules and general (body, blazor-error-ui) rules
- Removes duplicate @media query, simplifies maintenance
2026-07-19 15:49:46 +00:00
Arnaud Dartois d5776496e7 fix: suppress NU1510 for transitive System.Threading.Channels 2026-07-19 15:32:47 +00:00
Arnaud Dartois 255c3f6260 fix: resolve CA1822 and CA1859 in FrameAnalyzerService 2026-07-19 15:30:51 +00:00
Arnaud Dartois 488996a760 fix: add missing System.Threading.Channels import in FrameAnalyzerService 2026-07-19 15:30:08 +00:00
Arnaud Dartois 76b261378c fix: resolve review findings — thread safety, N+1, DTO layering, sentry, S3 retry 2026-07-19 13:43:48 +00:00
Arnaud Dartois 358443ff1a feat(events): implement camera event pipeline with AI detection storage
Adds the foundation for AI-powered detection events storage, query,
and snapshot management. Agents can POST detection events (motion,
person, vehicle, face, etc.) with confidence scores and metadata;
users can query, filter, and view event history.

- CameraEvent entity with EF Core configuration + migration
- ICameraEventService / CameraEventService with paged query + filters
- EventsController: 5 REST endpoints (create, get, query, attach snapshot, delete)
- Agent-side CameraStreamService: FFmpeg-based RTSP frame capture (foundation)
- Supports both ApiKey (agent) and JWT (user) authentication
2026-07-19 12:55:05 +00:00
Arnaud Dartois fdfd506977 fix: resolve GlitchTip anomalies — DB retry, query filters, Sentry DSN, Workers tracking
- 🔴 Fix startup crash when DB is temporarily unavailable: add 5x retry
  with exponential backoff to Database.MigrateAsync() in API and Workers
- 🔴 Fix EF Core 'required navigation with query filter' warnings:
  add matching soft-delete query filters to AgentSetting, CameraCredentials,
  CameraDetectionProfile, UserSite
- 🔴 Add Sentry error tracking to Workers (Hangfire background jobs)
- 🟡 Make Sentry/GlitchTip DSN configurable via SENTRY_DSN env var
  (applies to API, Web, Agent, Workers)
- 🟡 Suppress EF Core RedundantIndexRemoved informational messages

Closes GlitchTip #538
2026-07-18 20:31:37 +00:00
Arnaud Dartois cc52214404 feat: add Sentry (GlitchTip) client to Api, Agent, Web
Add Sentry.AspNetCore v6.7.0 with hardcoded DSN constant
(not overridable by env) pointing to GlitchTip instance at
https://glitchtip.tordais.cc/6.

Same DSN configured across all three entry-point projects:
- Heimdall.Api
- Heimdall.Agent
- Heimdall.Web
2026-07-18 19:41:57 +00:00
Arnaud Dartois c2837af089 feat(mvp): complete MVP hardening — API, Web, config system, SignalR, tests 2026-07-18 18:58:20 +00:00
Arnaud Dartois f937117f5a chore(agent): remove placeholder Worker.cs
Worker.cs was a template artifact that only logged 'running' every
second. It was never registered in DI. AgentRegistrationService
handles all background work.
2026-07-18 14:12:03 +00:00
Arnaud Dartois 1c08e0394d refactor(agent): use Options pattern with validation instead of raw env vars
Introduce AgentOptions class with DataAnnotations validation bound
from configuration (env vars with Agent__ prefix). Replace all
Environment.GetEnvironmentVariable() calls with typed IOptions<T>
injection. Config errors are caught at startup via ValidateOnStart().
2026-07-18 14:11:47 +00:00
Arnaud Dartois 58f46fe3dd feat(agent): add health check endpoint and Docker HEALTHCHECK
Migrate from Microsoft.NET.Sdk.Worker to Microsoft.NET.Sdk.Web to
enable HTTP health checks. Add /healthz endpoint via
AgentHealthCheck (reports healthy when registered with Central).
Configure Docker HEALTHCHECK with 30s interval and 15s start period.
2026-07-18 14:09:32 +00:00
Arnaud Dartois eafbab5e7a chore(agent): remove unused Heimdall.Infrastructure dependency
Heimdall.Agent does not use EF Core, Identity, or any Infrastructure
services. Removing the reference eliminates unnecessary transitive
dependencies (Npgsql, Hangfire, EF Core) and speeds up builds.
Add explicit Microsoft.Extensions.Http package (was transitively
provided by Infrastructure).
2026-07-18 14:07:41 +00:00
Arnaud Dartois f03ed91695 feat(agent): add system metrics (CPU, memory, disk, uptime) to heartbeat
Introduce SystemMetricsProvider that reads /proc on Linux (with
safe fallbacks on other platforms) and includes CPU usage, memory
usage, disk usage, and uptime in every heartbeat payload. Allows
Central to monitor agent health proactively.
2026-07-18 14:06:09 +00:00
Arnaud Dartois 4b6e4ce27a feat(agent): persist agent identity to disk so it survives restarts
Replace the mutable AgentState POCO with a file-persisted version.
On startup, load existing identity from /var/lib/heimdall/agent-state.json
and skip re-registration. On first registration, save identity to disk.
Prevents orphaned agents in Central after agent restarts.
2026-07-18 14:05:07 +00:00
Arnaud Dartois df74a61744 feat(agent): add graceful shutdown with final offline heartbeat
Override StopAsync to send a final heartbeat with IsOffline=true
before the agent stops. This allows Central to distinguish between
intentional shutdown and unexpected disconnection.
2026-07-18 14:03:49 +00:00
Arnaud Dartois 7d30d93939 feat(agent): add retry with exponential backoff on registration failure
Wrap agent registration in 5-attempt retry loop with exponential
backoff (2^attempt seconds). Prevents crash-loop when Central is
temporarily unavailable on startup. OperationCanceledException
bubbles up immediately for clean shutdown.
2026-07-18 14:03:14 +00:00
Arnaud Dartois da1a278b14 perf(agent): replace new HttpClient() with IHttpClientFactory for IP resolution
Use IHttpClientFactory instead of manual new HttpClient() in
ResolvePublicIpAsync to prevent socket exhaustion in long-running
agent service. Register a named 'IpResolver' client for this purpose.
2026-07-18 14:02:40 +00:00
Arnaud Dartois 0473f8ff5b fix(agent): implement GetPublicIp via api.ipify.org with async resolution
Replaced the always-null GetPublicIp stub with a proper async
implementation. IP is resolved once at registration time (not per
heartbeat) and stored in AgentState for reuse. Uses 5s timeout
and graceful failure (null if unreachable).
2026-07-17 19:29:40 +00:00