Commit Graph
18 Commits
Author SHA1 Message Date
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 f800103239 feat: remplacer Gotify par ntfy — push notifications multi-utilisateur avec isolation par topic
- Nouveau NtfyService: topic isolé par user (heimdall_{userId})
- Configuration globale Ntfy:BaseUrl + Ntfy:Token (plus de token par user)
- Renommage UserNotificationConfig: Gotify* → Ntfy*
- Migration des colonnes DB: gotify_enabled/url/token → ntfy_enabled/url
- Ajout service ntfy dans docker-compose (binwiederhier/ntfy)
- Mise à jour .env.example avec NTFY__BASE_URL et NTFY__TOKEN
- Suppression GotifyService et IGotifyService
2026-07-27 04:56:16 +00:00
Arnaud Dartois f9be0f1e0d feat: implémenter SignalR hubs (Monitoring, Notifications, Admin) + système de notifications complet
SignalR Hubs:
- MonitoringHub (/hubs/monitoring) — statuts agents/caméras/stockage/GPU jobs
- NotificationsHub (/hubs/notifications) — notifications in-app badge temps réel
- AdminHub (/hubs/admin) — broadcast changements config (Admin only)

Notification System:
- Nouvelles entités: Notification, NotificationTemplate, UserNotificationConfig
- CQRS/MediatR: 6 handlers (list, unread, mark-read, mark-all, config get/update)
- Infrastructure: NotificationService orchestrator + EmailService + GotifyService
- Rate limiter IMemoryCache (20 events/min/camera/type)
- Hangfire jobs: SendNotification, DailyDigest, WeeklyDigest
- NotificationsController API (6 endpoints)
- Blazor UI: NotificationsPage + NotificationBadge
- Migration AddNotifications (3 nouvelles tables)
- 644 nouveaux tests (Domain: 131, Application: 321, Infra: 151, Integration: 120, +autres)
2026-07-26 20:45:35 +00:00
Arnaud Dartois 7be5d42e85 fix(identity): DB refresh tokens, auto-refresh handler, 2FA endpoints, JWT fix
- DB-backed RevokedRefreshToken entity + migration (remplace ConcurrentDictionary\n  en memoire, fonctionne en multi-instance et survive aux redemarrages)\n- TokenRefreshHandler: auto-refresh des JWT 401 via DelegatingHandler\n  (avec SemaphoreSlim pour eviter les refresh storms)\n- Fix: GenerateRefreshToken genere maintenant un JWT valide au lieu de\n  bytes aleatoires (ValidateRefreshToken attendait un JWT - flux casse)\n- Fix: Login.razor gere Requires2fa correctement (affiche champ code 2FA)\n- Ajout: endpoints POST /api/auth/2fa/enable et /2fa/disable\n- Ajout: Disable2faAsync dans IAuthService\n- Fix: GenerateTemporaryPassword garantit les 4 categories de charactere\n  (uppercase, lowercase, digit, non-alphanumeric)\n- Fix: TestFactory ajoute Jwt:RefreshKey manquant\n\nBuild: 0 errors, 0 warnings\nTests: 226/226 passed
2026-07-21 08:57:53 +00:00
Arnaud Dartois e74995f088 fix(db): add value comparer for KnownFace.Embedding float array
Adds ValueComparer<float[]> with element-by-element comparison and
snapshot copy. Prevents EF Core warning 10620 about collection types
with value converters but no value comparer.
2026-07-20 14:03:40 +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 129a6148f5 feat(persons): add person manager with known face registry and CRUD API 2026-07-19 15:28:38 +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 159da2ca26 feat(assign): implement camera-to-agent assignment with failover and strategy support
Multi-agent sites need automatic camera distribution, failover when
an agent goes offline, and rebalancing when new agents join.

Adds CameraAssignment entity with audit trail, 4 assignment strategies
(RoundRobin, GpuPriority, LeastCameras, Failover), a Hangfire failover
job that checks for stale heartbeats every 60s, a discovery coordinator
for leader election, 6 REST endpoints, EF migration, and DI registration.
2026-07-19 12:20:07 +00:00
Arnaud Dartois 57b51f403c feat(web): add profile, roles, groups and claims pages 2026-07-19 06:49:17 +00:00
Arnaud Dartois 7e66bb4fbb feat(discovery): add camera detection pipeline inspired by Strix
Add complete camera discovery and stream testing specification,
Domain entities, enums, DTOs, Application interfaces, and EF Core
configurations for automated ONVIF/mDNS/HTTP/ARP camera detection.

- 4 new enums: CameraDiscoveryMethod, DetectedCameraType,
  StreamProtocol, CameraCapability (flags)
- Camera entity extended with 15+ discovery/test fields
- New entities: CameraDiscoveryResult, DiscoveredStreamUrl
- DTOs: ProbeRequest/Response, StreamTestRequest/Session, etc.
- Interface: ICameraDiscoveryService (8 methods)
- EF Core configurations for all new tables + columns
- Full spec doc: docs/specifications/detection-camera.md (16 sections)
- 145 tests pass, 0 warnings

Inspiré de Strix (github.com/eduard256/Strix) — moteur de
découverte de flux IP supportant 3600+ marques, 100K+ patterns.
2026-07-18 21:15:05 +00:00
Arnaud Dartois 0f22a60fbc fix(db): correct Site index filter column casing ("is_deleted" → "IsDeleted")
The filtered index IX_sites_IsDeleted uses a WHERE clause
referencing "is_deleted" (lowercase underscore) but the column
is "IsDeleted" (PascalCase). PostgreSQL quoted identifiers are
case-sensitive, causing Npgsql.PostgresException on migration.

Fixes remaining HEIMDALL issues on GlitchTip.
2026-07-18 20:01:31 +00:00
Arnaud Dartois ba9678f192 fix(db): correct Agent index filter column casing ("status" → "Status")
The filtered index IX_agents_LastHeartbeat uses a WHERE clause
referencing "status" (lowercase) but the column is "Status"
(PascalCase). PostgreSQL quoted identifiers are case-sensitive,
causing Npgsql.PostgresException 42703 on migration.

Fixes HEIMDALL-2 on GlitchTip.
2026-07-18 19:59:07 +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 b04d8a72c2 perf(db): add IsUnicode(false) on ASCII-only code/identifier columns
Added IsUnicode(false) to hostname, version, status, IP, hash,
prefix, key, URL, timezone, theme, language, YOLO model name,
and enum-based string columns. These columns only contain ASCII
data — disabling Unicode improves PostgreSQL index efficiency
and reduces storage.

Excluded natural text columns (Address, DisplayName, Site.Name)
that may contain Unicode characters like accented letters.
2026-07-17 19:31:11 +00:00
Arnaud Dartois ec45fa3c87 fix(perf): eliminate N+1 in AuditLogService by adding User navigation property
Added AppUser navigation property to AuditLog entity with EF Core
configuration (FK -> UserId, SetNull on delete). Replaced the sub-query
in AuditLogService ListAsync with a direct navigation property access,
enabling EF Core to generate a single LEFT JOIN instead of N sub-queries.

Migration: AddAuditLogUserRelation
2026-07-17 19:24:07 +00:00
Arnaud Dartois 7a71a09102 fix(api): replace lockout with MustChangePassword flag in ResetPasswordAsync
Setting LockoutEnd to UtcNow locked the user out instead of forcing
a password change. Added MustChangePassword boolean to AppUser entity
with EF Core migration. ResetPasswordAsync now sets this flag instead
of locking the account.
2026-07-17 19:21:12 +00:00
Arnaud Dartois b217c932e8 feat(mvp): implement MVP multi-site platform
Complete MVP implementation (Étape 1) covering:
- Domain: primitives (Entity<TId>, ValueObject), 10 entities, 6 enums
- EF Core: AppDbContext + Identity, 8 EntityTypeConfigurations, audit/soft-delete interceptors, initial migration
- Application: service interfaces, DTOs, FluentValidation, ServiceResult pattern
- Security: Identity + JWT + API Key multi-auth, role-based permissions, constant-time key validation
- API: Auth/Sites/Agents controllers with explicit auth scheme policies
- Workers: Hangfire PostgreSQL setup with schema isolation, HeartbeatMonitorJob
- Agent: registration service + 30s heartbeat loop
- Docker: multi-stage Dockerfiles for central + agent, docker-compose.yml
- CI/CD: GitHub Actions pipeline with build+test and Docker build
- Tests: 13 domain tests (Site, Agent, Camera entities)

Architecture decisions per deliberation council:
- API Key via AuthenticationHandler<T> (not middleware)
- Explicit [Authorize(AuthenticationSchemes)] on all endpoints
- Event/Recording/Person/Vehicle deferred from initial migration
- Hangfire compatible with .NET 10 (v1.8.17)
2026-07-16 20:53:56 +00:00