Commit Graph
116 Commits
Author SHA1 Message Date
Arnaud Dartois c5728fa810 feat(events): add SignalR real-time event broadcasting to web UI 2026-07-19 15:24:52 +00:00
Arnaud Dartois 0d2f0574c9 feat(ui): add snapshot gallery with lightbox and search filter 2026-07-19 15:19:33 +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 2d65f273c6 feat(ui): enrich dashboard with event data, camera status, and agent workload 2026-07-19 13:30:03 +00:00
Arnaud Dartois add9ebf462 feat(ui): add events page and event timeline on camera detail 2026-07-19 13:21:25 +00:00
Arnaud Dartois 8ac8baf20a feat(storage): add S3 snapshot service and comprehensive tests for phases 2-3
Adds S3-compatible snapshot storage (Alarik) with AWS Signature V4,
upload, thumbnail, and delete operations. Backfills Phase 2 & 3 with
27 new tests covering camera assignment strategies, event CRUD with
filtering, snapshot attachment, and API contract validation.

- SnapshotService with S3 REST API via HttpClient + SigV4 signing
- 10 unit tests for CameraAssignmentService (assign, release, failover, history)
- 9 unit tests for CameraEventService (create, query, filter, delete, snapshot)
- 8 integration tests for AssignmentsController + EventsController
- SnapshotService registration with 5-min timeout HTTP client
2026-07-19 13:14:05 +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 2152fca3c6 feat(discovery): implement camera detection and dedup pipeline
Manual camera configuration does not scale beyond a few devices.
Automated discovery is needed to support deployments with 50+
cameras across heterogeneous protocols (ONVIF, mDNS, HTTP, ARP).

Phase 1 introduces 5 network probe services, a stream tester, an
orchestrating discovery service with IP+MAC deduplication, 11 REST
endpoints, a pre-verification endpoint, 57 tests, and DI registration.
2026-07-19 12:00:16 +00:00
Arnaud Dartois 31f2056d48 feat(agents): add global agents page, reusable components, KPIs, admin-only security 2026-07-19 07:25:27 +00:00
Arnaud Dartois 9113191547 feat(ui): modernize all pages — auto-refresh, skeleton loading, tooltips, filters 2026-07-19 07:12:40 +00:00
Arnaud Dartois 2ff355e567 feat(auth): add default groups, claims-based authorization and update spec 2026-07-19 07:04:25 +00:00
Arnaud Dartois 57b51f403c feat(web): add profile, roles, groups and claims pages 2026-07-19 06:49:17 +00:00
Arnaud Dartois e73c4b357b chore: update opencode submodule to 4bc9d1d — fix broken agent launch (frontmatter + double definitions) 2026-07-19 06:35:01 +00:00
Arnaud Dartois 3056452b9e fix(web): repair design on users page, settings page and audit logs 2026-07-19 06:34:32 +00:00
Arnaud Dartois ca693a2ed0 fix(web): repair home page design — invalid CSS, dead code, missing form wrappers 2026-07-19 06:28:13 +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 8c6b2610a0 fix(web): register HeimdallAuthStateProvider concrete type in DI
The service was registered only as AuthenticationStateProvider (base class),
but Login.razor, Register.razor, and MainLayout.razor inject the concrete
@inject HeimdallAuthStateProvider. Blazor's DI could not resolve it,
causing InvalidOperationException on page render.

Fix: register the concrete type first, then make the base class
registration resolve to the same instance via GetRequiredService.
2026-07-18 21:08:08 +00:00
Arnaud Dartois 39f08e39ed fix(web): add cookie authentication to fix IAuthenticationService missing error 2026-07-18 20:59:38 +00:00
Arnaud Dartois f5c4bcd5f0 feat(deploy): add heimdall-web Blazor UI service to Docker Compose
The Dockerfile.central already compiled Heimdall.Web but it was never
deployed as a service. Add heimdall-web service using the same image
with entrypoint overridden to dotnet web/Heimdall.Web.dll.

- Expose port 5001 for the Blazor Server UI
- API_BASE_URL points to heimdall-central:8080 for server-side HTTP calls
- Healthcheck on root / returns 200 once the Blazor circuit is ready
2026-07-18 20:44:38 +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 ee66cf5971 chore: update opencode submodule to 09da68e — fully automatic auto-learning/auto-healing pipeline 2026-07-18 20:15:41 +00:00
Arnaud Dartois abf8162824 fix(db): fix index filter casing in all migration snapshots
Fix the filtered index column name casing in ALL .Designer.cs files
and AppDbContextModelSnapshot.cs:
  - "status" → "Status" (Agent.LastHeartbeat index)
  - "is_deleted" → "IsDeleted" (Site.IsDeleted index)

These must match the actual column names (PascalCase) since
PostgreSQL quoted identifiers are case-sensitive.

Also fix the InitialCreate migration .cs file directly.
All 10 references across 5 snapshot files corrected.
2026-07-18 20:11:19 +00:00
Arnaud Dartois 3978f64f93 fix(workers): use IDbContextFactory for HeartbeatMonitorJob thread safety
Pattern #4 from cross-project learning analysis: HeartbeatMonitorJob
injected AppDbContext directly (not thread-safe). Changed to
IDbContextFactory<AppDbContext> + registered factory in DI.

Other patterns verified already in place:
- CancellationToken on all async methods ✅ (100% controller adoption)
- N+1 per-entity loops ✅ (all services use bulk-loading)
- AsNoTracking ✅ (explicit on read-only queries)
- Global QueryTrackingBehavior.NoTracking deferred: safe for
  new projects but requires write-path audit on existing codebase
2026-07-18 20:05:22 +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 f43297bf08 chore: update opencode submodule to d1cf062 — codify 4 cross-project patterns into base config 2026-07-18 19:59:58 +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 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 8f095f1d5d chore: update opencode submodule to cb6fbae — auto-learning/healing/evolution (3 phases) 2026-07-18 19:38:30 +00:00
Arnaud Dartois cb1e4d61b8 fix(db): migrate DB inline before seeding to prevent startup crash
Replace the background MigrationHostedService with inline
db.Database.MigrateAsync() before Identity role seeding. The
IHostedService started after app.Run(), but seeding ran synchronously
before app.Run() — causing 42P01 when RoleManager queried the roles
table that didn't exist yet.

- Add await db.Database.MigrateAsync() with 120s timeout before seeding
- Add structured logging (ILogger) and error handling around migration
- Remove MigrationHostedService.cs (dead code — inline migration makes
  it permanently no-op)
- Remove unused using Heimdall.Infrastructure.Services
- Unify using style (using var instead of using block)
2026-07-18 19:28:16 +00:00
Arnaud Dartois cca6ab6f46 feat(mvp): agent settings UI + migration orchestrator
Agent settings UI:
- Add settings section to AgentDetail page showing per-agent overrides
- Add/edit/delete agent settings with confirmation dialogs
- Add settings API methods + DTOs to HeimdallApiClient
- Real-time SignalR notification shown in UI feedback

Migration orchestrator:
- Replace inline db.Database.Migrate() with MigrationHostedService
- Runs migrations in background at startup (non-blocking)
- 60-second timeout with critical logging on failure
- Preserves Testing environment exclusion
- Clear migration progress logging
2026-07-18 19:07:01 +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 3fc42be4b2 test(agent): add unit tests for AgentState, AgentHealthCheck, AgentRegistrationService
13 tests covering:
- AgentState file persistence (save, load, corrupt file, empty ID, clear)
- AgentHealthCheck (healthy, degraded, unhealthy states)
- AgentRegistrationService (successful registration, retry on failure,
  all retries exhausted, reuse existing identity, offline heartbeat on stop)
2026-07-18 14:16:13 +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 cb500e0354 fix(deps): override transitive AngleSharp 1.4.0 with 1.5.2 to fix NU1902 vulnerability
bunit 2.8.4-preview transitively pulls AngleSharp 1.4.0 which has a
known moderate severity vulnerability (GHSA-pgww-w46g-26qg). Adding
a direct PackageReference to AngleSharp 1.5.2 overrides the transitive
version and resolves the CI build failure.
2026-07-18 11:41:33 +00:00
Arnaud Dartois 5b656286e5 refactor: replace MinIO with Alarik S3-compatible storage
Alarik is a drop-in S3-compatible replacement requiring no application
code changes. All S3 APIs (upload, download, list, delete, multipart)
are fully supported.
2026-07-18 11:40:03 +00:00
Arnaud Dartois 2f32906f68 feat: add Docker Hub production docker-compose and docs 2026-07-18 11:30:55 +00:00
Arnaud Dartois e85c5fff3f chore(ci): add Docker Hub publish steps to pipeline 2026-07-18 11:27:43 +00:00
Arnaud Dartois 8b0350bc2c perf(db): add AsNoTracking to read-only queries across services
Adds .AsNoTracking() to all read-only list/pagination queries in
SiteService, AgentService, CameraService, AuditLogService, and
UserService. Prevents EF Core change tracker overhead when only
displaying data.

UserService.ListAsync and UserSites query benefit most (materialize
AppUser/UserSite entities). AuditLogService, SiteService, CameraService,
AgentService paginated lists are read-only so AsNoTracking is safe.
2026-07-17 20:58:10 +00:00
Arnaud Dartois 076bc58e93 fix(security): implement IDataProtector-based credential encryption for CameraCredentials
- Add ICredentialProtector/DataProtectorCredentialProtector using ASP.NET Core Data Protection
- Register AddDataProtection + ICredentialProtector in Infrastructure DI
- Update CameraCredentials XML comments to reference real protector
- Add SetCredentialsAsync to CameraService with encryption
- Update ICameraService interface
2026-07-17 20:07:03 +00:00
Arnaud Dartois 12a1ff2737 fix(ui): implement token generation in SitesPage.CopyToken
Replaces the no-op CopyToken method with actual API call.
Adds a dialog showing the generated token with expiry warning.
2026-07-17 20:04:52 +00:00
Arnaud Dartois 369b685fef fix(domain): make AuditLog.User setter private for consistency
All other properties on AuditLog use private set.
2026-07-17 20:03:51 +00:00