Commit Graph
85 Commits
Author SHA1 Message Date
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
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 ad04f9fead fix(tests): make ResetPassword test deterministic by guaranteeing password requirements
GenerateTemporaryPassword now uses RandomNumberGenerator (cryptographic)
and guarantees at least 1 digit, 1 lowercase letter to satisfy Identity
password rules (RequireDigit=true, RequireLowercase=true).
Also shuffles the result to avoid predictable position patterns.

Fixes flaky ResetPassword_WithAdminAuth_ReturnsTemporaryPassword test.
2026-07-17 19:19:53 +00:00
Arnaud Dartois 83af89d7ec docs: comprehensive README with architecture, setup, API reference
- Full project documentation in readme.md (FR)
- Quick start: Docker + development modes
- API endpoint reference table with auth requirements
- Security documentation (JWT, API Key, rate limiting)
- Test suite documentation (34 tests)
- Stack technology table
2026-07-17 19:10:51 +00:00
Arnaud Dartois 8c7ec4d279 feat(ui): pages détail Caméra + Agent
- CameraDetail: vue modifiable (nom, RTSP), infos fabricant/modèle/statut
- AgentDetail: infos hostname/version/heartbeat + capacités CPU/GPU/mémoire
- CamerasPage: nom cliquable vers le détail
- AgentsPage: nom cliquable vers le détail
- ApiClient: GetCameraAsync, UpdateCameraAsync, GetAgentAsync
2026-07-17 19:08:17 +00:00
Arnaud Dartois b816446f72 feat(audit): journal d'audit consultable dans l'UI
- IAuditLogService + AuditLogService avec pagination et filtres
- AuditLogsController: GET /api/audit-logs (resourceType, action, page)
- AuditLogsPage Blazor: liste paginée avec filtres + coloration par action
- Lien vers le journal dans le menu Admin (visible pour les Admins)
2026-07-17 18:14:41 +00:00
Arnaud Dartois cbd00443d4 chore: update opencode submodule to 92503e7
Forgejo-only CI enforcement:
- cicd-pipeline skill: forgejo.tordais.cc by default, GA = legacy
- devops-agent: .forgejo/ scope, blocking CI checklist
- pre-commit hook: CI lint blocks GA references
- scripts/ci-lint.sh: standalone audit with --fix
- enforcement.md: CI lint in pre-commit checklist
2026-07-17 17:48:56 +00:00
Arnaud Dartois a51195afe9 feat(docs): add Scalar API documentation UI
- Add Scalar.AspNetCore package (beautiful OpenAPI UI)
- MapScalarApiReference() available at /scalar in Development
- Complement to the existing /openapi/v1.json endpoint
2026-07-17 17:45:44 +00:00
Arnaud Dartois 567d912e12 chore: add .dockerignore, fix Workers env propagation
- .dockerignore: exclude bin/obj/.git/tests/docker for faster Docker builds
- Workers/Program.cs: pass ASPNETCORE_ENVIRONMENT to AddInfrastructure
  (prevents Npgsql registration in Testing/Development)
2026-07-17 17:43:11 +00:00
Arnaud Dartois e83b493ce0 test: add placeholder tests to empty test projects
- Add PlaceholderTest.cs to Api.Tests, Application.Tests, Infrastructure.Tests,
  Web.Tests, Workers.Tests (1 passing test each)
- Prevents 'no test available' warnings in CI
2026-07-17 17:39:30 +00:00
Arnaud Dartois 62798cf81f chore: migrate CI from GitHub Actions to Forgejo
Replace .github/workflows/ci.yml with .forgejo/workflows/ci.yml:
- runs-on: ubuntu-latest → debian-12
- actions/ URL shortcuts → https://forgejo.tordais.cc/actions/... FQDNs
- docker/setup-buildx-action + docker/build-push-action → manual
  docker build
- Add NuGet package caching
- Add concurrency group (forgejo.ref) + paths-ignore
- Use forgejo.ref instead of github.ref
2026-07-17 17:39:22 +00:00
Arnaud Dartois 1203c7f0e1 fix(api): register-admin uses IAuthService instead of direct Entity creation
- Add RegisterAdminAsync to IAuthService interface
- Implement in AuthService (creates user + assigns Admin role)
- AuthController.register-admin now delegates to service layer
- No more 'new AppUser' in controller
2026-07-17 17:37:52 +00:00
Arnaud Dartois e17dce1b4f fix(api): StatsController uses IStatsService instead of direct AppDbContext
- Add IStatsService in Application layer
- Add StatsService in Infrastructure layer
- StatsController now injects IStatsService (Clean Architecture compliant)
- StatsResponse DTO added to Application/DTOs
2026-07-17 17:36:14 +00:00