Commit Graph
63 Commits
Author SHA1 Message Date
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
Arnaud Dartois c6450ad50d feat(api): dedicated /api/stats endpoint
- StatsController: aggregates sites, cameras, agents counts in one DB query
- Dashboard: now uses stats endpoint (2 API calls instead of N*2+1)
- ApiClient: GetStatsAsync + StatsResult DTO
2026-07-17 17:22:33 +00:00
Arnaud Dartois 1fd3f8f003 feat(dashboard): real stats with parallel API calls
- Dashboard now shows: total sites, total cameras, online agents, active sites
- Stats loaded in parallel with Task.WhenAll for performance
- Falls back gracefully if cameras/agents endpoints return no data
2026-07-17 15:10:14 +00:00
Arnaud Dartois 3be0993fb5 feat(ui): multi-role selection with checkboxes
- Users: replace single MudSelect role picker with MudCheckBox multi-select
- Users: users can now have multiple roles (Admin + Supervisor, etc.)
- Users: edit dialog validates at least one role is selected
- Build: suppress MudBlazor analyzer MUD0002 (false positive on Checked bind)
2026-07-17 13:26:15 +00:00
Arnaud Dartois cb855f83b8 feat(ui): login redirect + configurable API URL
- Login: redirect to original page after auth via returnUrl query param
- RedirectToLogin: encodes current URL as ?returnUrl=/path
- API URL: configurable via appsettings.json ApiBaseUrl or API_BASE_URL env
- NotFound page: preserved from template
2026-07-17 13:22:02 +00:00
Arnaud Dartois da123ec544 fix(tests): InMemory DB isolation + refactor test helpers
- Fix: InMemory database name now unique per test factory instance
  (was using process-wide env var, now per-host config via UseSetting)
- Refactor: all integration tests use shared TestHelpers.CreateAdminClientAsync
- New: register-admin endpoint (test/dev only) creates Admin users directly
- New: TestHelpers.cs with extension method for admin client creation
- Cleanup: removed bootstrap template files, old Counter/Weather pages
- Cleanup: simplified app.css with MudBlazor-only styles
- Seed: demo admin + demo site created in Development mode
2026-07-17 13:15:25 +00:00
Arnaud Dartois 129bcfa9d7 feat(ui): Blazor auth redirect + CascadingAuthenticationState
- Routes: wrap with CascadingAuthenticationState + AuthorizeRouteView
- RedirectToLogin: component that redirects unauthenticated users to /login
- HeimdallAuthStateProvider: NotifyLogin/NotifyLogout methods
- Login/Register/MainLayout: use AuthStateProvider.NotifyLogin/Logout
  instead of direct AuthState mutation (triggers Blazor auth cascade)
- _Imports: add Microsoft.AspNetCore.Components.Authorization
2026-07-17 07:05:07 +00:00
Arnaud Dartois d4a86b8c7f feat(mvp): docker-compose snippet in UI, agent flow tests
- Site detail: generate registration token with copy/paste docker-compose snippet
- Docker snippet: pre-filled with token + agent hostname, ready to copy
- Agents integration tests: register with valid token, heartbeat with API key,
  invalid token rejection (3 new tests)
- TokenResult DTO for API client
- IJSRuntime clipboard copy for docker-compose snippet
2026-07-17 07:00:58 +00:00
Arnaud Dartois 2ea82504d7 feat(mvp): rate limiting, agents page, site detail navigation
- Rate limiting: Microsoft.AspNetCore.RateLimiting AddFixedWindowLimiter
  (Auth: 10 req/min, Api: 200 req/min, returns 429 when exceeded)
- Agents Blazor: new page listing agents per site with status/heartbeat
- Site detail: camera and agent navigation cards
- ApiClient: GetAgentsBySiteAsync, AgentItem DTO
- Removed custom middleware (replaced by proper built-in rate limiter)
2026-07-17 06:57:00 +00:00
Arnaud Dartois dfc888db94 feat(mvp): agent auth, cameras UI, rate limiting attempt
- Agent: fix heartbeat auth — set API Key header after registration
- Cameras Blazor: full page with create/delete/list by site
- ApiClient: cameras CRUD endpoints + CameraItem DTO
- Rate limiting: attempted but deferred (System.Threading.RateLimiting package issue)
- Security: refresh token rotation now enforced server-side
2026-07-17 06:30:09 +00:00
Arnaud Dartois 6d5ec0c201 feat(mvp): cameras API, Docker production, tests, security, Makefile
- Cameras API: CRUD with service/controller/DTOs + Blazor page
- Docker: production-grade compose with healthchecks, .env, Makefile, networks
- Healthchecks: /healthz (liveness) and /readyz (readiness) endpoints
- Testing: 13 integration tests (Auth, Sites, Users, Cameras controllers)
  - Users: create, list, lock, reset-password
  - Cameras: create with site, list by site
- Environment: .env.example, docker-compose.override.yml for dev
- Infrastructure: ICameraService registered in DI
2026-07-17 06:18:56 +00:00
Arnaud Dartois 38816aec8a feat(mvp): complete Blazor UI + User Management + integration tests 2026-07-16 21:19:16 +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
Arnaud Dartois ad78346ac4 chore: update opencode submodule to 7463a8a
- feat(rules): add mandatory user confirmation gate for deliberation and commit
2026-07-16 20:18:51 +00:00
Arnaud Dartois 1bd6de1d48 docs: detail fonctionnel des etapes 2 a 7 avec scenarios concrets
Chaque phase des Etapes 2 a 7 a maintenant des scenarios de test detailles, des exemples requetes/reponses HTTP, et des sections 'Fonctionnel a la fin de cette phase' comme pour l'Etape 1. Ajout de schemas JSON pour chaque endpoint, scenarios utilisateur complets (detection avec dedup, live video, notifications, retention, mobile).
2026-07-16 20:14:06 +00:00
Arnaud Dartois 150275a47a docs: detail chaque phase de l'etape 1 avec scenarios fonctionnels concrets
Chaque phase de l'Étape 1 (MVP Multi-Site) a désormais une section '✅ Fonctionnel à la fin de cette phase' qui décrit EXACTEMENT ce qui marche, avec des exemples de requêtes/réponses HTTP et le scénario de bout en bout.
2026-07-16 20:07:40 +00:00
Arnaud Dartois eb59ffd4f6 refactor: split implementation in 2 stages — MVP multi-site then business features
Étape 1 (Phases 1-12) : Foundation + API multi-site (Sites, Agents, Auth) + Agent Docker avec heartbeat. Pas de caméra, pas d'IA, pas de vidéo. L'objectif est d'avoir N sites avec N agents enregistrés, heartbeats, status Online, le tout via API.

Étape 2 (Phases 13-25) : on ajoute le métier par-dessus — caméras, vidéo, IA, notifications, UI, mobile.
2026-07-16 20:05:19 +00:00
Arnaud Dartois 098a05aceb fix: move mobile app to last phase (Phase 23)
L'application Kotlin est réalisée en dernier, après le Production Hardening.
2026-07-16 20:01:52 +00:00
Arnaud Dartois 9fff2ec917 fix: mobile stack Kotlin (not Avalonia), agents Docker-only
Corrections après feedback utilisateur : stack mobile = Kotlin + Jetpack Compose (Android natif, WebRTC natif), Agents installés exclusivement via Docker (pas de binaire standalone).
2026-07-16 20:00:48 +00:00
Arnaud Dartois 5c8df8127b docs: master specification v2.0 consolidating 9 fragmented docs
Complete specification rewrite after deep review by 5 expert agents (council, security, db, ai, perf). Fixes 36 critical issues including: stationary object dedup (4-level), motion gate, Avalonia mobile stack, API+Web fusion, HMACSHA256 auth, partitioned Events table, Hangfire queue isolation.
2026-07-16 19:59:21 +00:00
Arnaud Dartois 6138795771 feat: switch mobile app from Avalonia UI to Kotlin + Jetpack Compose
- Complete rewrite of mobile-app.md: Kotlin 2.1+, Jetpack Compose 1.7+
- Clean Architecture: data/domain/presentation layers
- Ktor 3.0 HTTP client (replaces Kiota, Kotlin-native)
- WebRTC natif Android (SurfaceViewRenderer + PeerConnection)
- SignalR client Java Microsoft (compatible Kotlin)
- Hilt DI, Room cache, DataStore preferences, Coil images
- Firebase Cloud Messaging push notifications
- MVVM with StateFlow + collectAsStateWithLifecycle
- Compose Navigation (NavHost, sealed Screen routes)
- Tests: JUnit 5 + MockK + Turbine (Flow) + Compose UI Test
- CI/CD Gradle with lint + detekt + unit tests + APK signing
- GitHub Actions workflow dedicated to mobile
- Update implementation.md Phase 21 with new stack
- Update README.md references
2026-07-16 19:52:01 +00:00
Arnaud Dartois 32240da193 docs: add CodeProject.AI reference doc with full API, modules, perf
- Create docs/codeproject-ai.md with:
  - All 17 modules listed (Object Detection YOLOv5/v8, ALPR, Face, Scene...)
  - API endpoints with request/response examples
  - Pipeline flow diagram Heimdall → CodeProject.AI
  - Per-camera DetectionProfile filtering before API calls
  - Docker config with GPU passthrough and env vars
  - Performance benchmarks (GPU vs CPU vs RPi4)
  - Custom detection models (ipcam-general, ipcam-animal...)
  - Mesh multi-instance architecture
- Update implementation.md Phase 12 with CodeProject.AI deep link
- Add CodeProject.AI to README.md navigation
2026-07-16 19:43:34 +00:00
Arnaud Dartois 5073592cdb feat: per-camera detection profiles (person/vehicle/face/LPR per camera)
- Add CameraDetectionProfile model with per-camera toggles
  (DetectPerson, DetectVehicle, FaceRecognition, LicensePlateRecognition...)
- Add default profiles: Indoor, Outdoor, Stairwell, Parking
- Agent only runs YOLO classes matching enabled detection types
- Central skips face rec/LPR when disabled per camera
- Add detection-profile endpoints to Camera API
- UI: per-camera checkbox grid + profile presets
- Add ONVIF camera credentials (per-camera + per-site defaults)
- Add SharpOnvifClient + OnvifDiscovery NuGet references
- Add Imou camera protocol details: RTSP URLs, known issues,
  firmware blocking, activation procedure
2026-07-16 19:40:50 +00:00