Commit Graph
97 Commits
Author SHA1 Message Date
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
Arnaud Dartois fb8f49a2f6 refactor(domain): remove redundant Camera.Update call in CreateAsync
Camera constructor now accepts Manufacturer and Model directly,
so the redundant Update() call in CameraService is no longer needed.
2026-07-17 20:03:23 +00:00
Arnaud Dartois 8a6a0a9d04 chore(api): remove dead IApiKeyService interface
No implementation exists and no controller injects it.
The DTOs (ApiKeyResponse, CreateApiKeyResponse) are kept
as they may be reused by a future endpoint.
2026-07-17 20:02:33 +00:00
Arnaud Dartois 23ead64795 docs: update implementation.md with current MVP status
- Mark ✅/⏳ for all 23 phases based on actual implementation
- Add stats: 83 files, 34 tests, 13 pages, 30+ endpoints
- Clearly separate done vs v2/v3 (hardware-dependent)
- Document stack choices (no MediatR at MVP)
2026-07-17 19:45:40 +00:00
Arnaud Dartois 0c0437a2cf fix(perf): eliminate N+1 in UserService.ListAsync with bulk role/site loading
ListAsync called UserManager.GetRolesAsync() per user (N queries
for N users). Now loads all roles and user-site assignments in two
bulk queries, grouped by userId in memory for O(1) lookup.
2026-07-17 19:32:13 +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 c36978d5a1 fix(domain): encapsulate CameraCredentials with private setters and SetCredentials method
All sensitive fields (OnvifPassword, RtspPassword, etc.) had public
setters allowing uncontrolled modification. Encapsulated via private
setters with a dedicated SetCredentials() method that updates all
values atomically and sets UpdatedAt.
2026-07-17 19:30:05 +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
Arnaud Dartois 8c550bc715 fix(auth): invalidate refresh token on LogoutAsync
Added SHA256 blacklist of revoked refresh tokens (in-memory
ConcurrentDictionary). RefreshTokenAsync now checks the blacklist
before validating the token. LogoutAsync hashes and stores the
revoked token. Added audit log entry for logout.

For multi-instance deployments, replace with DB-backed store.
2026-07-17 19:28:55 +00:00
Arnaud Dartois 21642bc4d6 fix(api): align IStatsService with ServiceResult pattern and fix activeSites bug
IStatsService was the only service returning raw Task<T> instead of
ServiceResult<T>. Also fixed 'activeSites = totalSites' copy-paste
bug — now counts sites where Enabled == true.
2026-07-17 19:28:02 +00:00
Arnaud Dartois 88d7cd79f8 fix(seed): update dev admin password to meet Identity RequiredLength=12
The seed password 'Admin123!' (9 chars) was silently rejected by
UserManager.CreateAsync because Identity Password.RequiredLength=12.
Updated to 'Admin123!Pass' (13 chars) and synchronized in readme.md
and Api.http.
2026-07-17 19:27:16 +00:00
Arnaud Dartois 1e05069a66 docs: replace stale weatherforecast in Api.http with real endpoints 2026-07-17 19:26:38 +00:00
Arnaud Dartois 20e2a235ad chore: remove stale NavMenu.razor template boilerplate
NavMenu.razor contained Counter/Weather links from the default Blazor
template and was never used (MainLayout.razor has its own navigation).
Removed the associated scoped CSS file to fix BLAZOR102 build error.
2026-07-17 19:26:27 +00:00
Arnaud Dartois 6094206cbc fix(api): return typed StatsResponse DTO instead of anonymous object
StatsController was constructing an anonymous response object that
differed from the StatsResponse DTO shape. Now wraps the actual DTO
in a standard envelope { data, timestamp } consistent with the rest
of the API.
2026-07-17 19:25:52 +00:00
Arnaud Dartois e5e88ff83f chore: remove dead Heimdall.Contracts project
Project had zero source files, no project references, and no consumers.
It only added build overhead and Docker cache layer noise.
2026-07-17 19:25:32 +00:00
Arnaud Dartois 5d86d2b7b7 fix(data): consolidate SaveChangesAsync calls in SiteService and AgentService
Both CreateAsync and RegisterAsync called SaveChangesAsync twice —
once for the main operation and once for the audit log. This creates
a risk of partial persistence if the second call fails.
Moved audit log addition before a single SaveChangesAsync call.
2026-07-17 19:24:56 +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 015711e156 fix(build): keep UseAppHost=false global for Alpine compatibility
Reverts per-project scoping from previous commit — Alpine build env
needs this globally because even Debug mode tries to create a native
host. The 4 Docker-published projects also inherit it from the global
Directory.Build.props.

Proper long-term fix: build CI on non-Alpine image, or set
UseAppHost=false only in Dockerfile publish args via /p flag.
2026-07-17 19:24:00 +00:00
Arnaud Dartois 3060f38979 fix(build): scope UseAppHost=false to Docker-published projects in Release only
The Alpine workaround was applied globally via Directory.Build.props,
preventing native host generation even for local dev builds. Moved to
only the 4 Docker-published projects (Api, Web, Workers, Agent) with
Condition='==Release'. Dev builds still get native
executables.
2026-07-17 19:22:05 +00:00
Arnaud Dartois ca394a9eaa fix(security): remove API key query string authentication vector
Query string (?apiKey=...) leaks credentials in server logs, referrer
headers, and browser history. Only Authorization header and X-API-Key
header are now accepted for API key authentication.
2026-07-17 19:21:25 +00:00