diff --git a/src/Heimdall.Agent/Heimdall.Agent.csproj b/src/Heimdall.Agent/Heimdall.Agent.csproj
index ca85395..41a7c46 100644
--- a/src/Heimdall.Agent/Heimdall.Agent.csproj
+++ b/src/Heimdall.Agent/Heimdall.Agent.csproj
@@ -12,4 +12,8 @@
+
+
+
+
diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs
index 6c58ad9..8c7510a 100644
--- a/src/Heimdall.Agent/Program.cs
+++ b/src/Heimdall.Agent/Program.cs
@@ -40,6 +40,7 @@ builder.Services.AddSingleton(sp =>
builder.Services.AddSingleton();
builder.Services.AddHostedService();
+builder.Services.AddHostedService();
// Health checks — used by Docker HEALTHCHECK
builder.Services.AddHealthChecks()
diff --git a/src/Heimdall.Agent/Services/ConfigReceiverService.cs b/src/Heimdall.Agent/Services/ConfigReceiverService.cs
new file mode 100644
index 0000000..f8d27de
--- /dev/null
+++ b/src/Heimdall.Agent/Services/ConfigReceiverService.cs
@@ -0,0 +1,181 @@
+using Microsoft.AspNetCore.SignalR.Client;
+using Microsoft.Extensions.Options;
+
+namespace Heimdall.Agent.Services;
+
+///
+/// Connects to the Central SignalR ConfigHub to receive real-time configuration updates.
+/// When a setting changes, applies it locally and logs the change.
+/// Service will auto-reconnect on connection loss.
+///
+public sealed class ConfigReceiverService : BackgroundService
+{
+ private readonly AgentState _state;
+ private readonly AgentOptions _options;
+ private readonly ILogger _logger;
+ private HubConnection? _connection;
+
+ public ConfigReceiverService(
+ AgentState state,
+ IOptions options,
+ ILogger logger)
+ {
+ _state = state;
+ _options = options.Value;
+ _logger = logger;
+ }
+
+ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+ {
+ // Wait until the agent is registered (has an AgentId)
+ while (_state.AgentId == Guid.Empty && !stoppingToken.IsCancellationRequested)
+ {
+ await Task.Delay(1000, stoppingToken);
+ }
+
+ if (stoppingToken.IsCancellationRequested) return;
+
+ var hubUrl = $"{_options.CentralUrl.TrimEnd('/')}/hubs/config";
+
+ _connection = new HubConnectionBuilder()
+ .WithUrl(hubUrl, options =>
+ {
+ options.AccessTokenProvider = () => Task.FromResult(_state.ApiKey);
+ })
+ .WithAutomaticReconnect(new RetryDelayed(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(30)))
+ .Build();
+
+ // Listen for setting changes
+ _connection.On("SettingChanged", (key, value) =>
+ {
+ _logger.LogInformation("Config update received: {Key} = {Value}", key, value);
+ ApplySetting(key, value);
+ });
+
+ // Listen for full reload signal
+ _connection.On("ConfigReload", () =>
+ {
+ _logger.LogInformation("Full config reload requested, fetching from API...");
+ _ = FetchFullConfigAsync(CancellationToken.None);
+ });
+
+ // Reconnection events
+ _connection.Reconnecting += _ =>
+ {
+ _logger.LogWarning("Config hub connection lost, reconnecting...");
+ return Task.CompletedTask;
+ };
+
+ _connection.Reconnected += async _ =>
+ {
+ _logger.LogInformation("Config hub reconnected, rejoining agent group...");
+ try
+ {
+ await _connection.InvokeAsync("JoinAgentGroup", _state.AgentId.ToString(), stoppingToken);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning(ex, "Failed to rejoin agent group after reconnect");
+ }
+ };
+
+ // Retry loop for initial connection (auto-reconnect handles the rest)
+ while (!stoppingToken.IsCancellationRequested)
+ {
+ try
+ {
+ await _connection.StartAsync(stoppingToken);
+ _logger.LogInformation("Connected to config hub at {HubUrl}", hubUrl);
+
+ // Join our personal config channel
+ await _connection.InvokeAsync("JoinAgentGroup", _state.AgentId.ToString(), stoppingToken);
+
+ // Fetch initial full config
+ await FetchFullConfigAsync(stoppingToken);
+
+ // Keep service alive until cancellation — auto-reconnect handles reconnection
+ await Task.Delay(Timeout.Infinite, stoppingToken);
+ }
+ catch (OperationCanceledException)
+ {
+ break;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning(ex, "Config hub connection failed, retrying in 15s...");
+ await Task.Delay(TimeSpan.FromSeconds(15), stoppingToken);
+ }
+ }
+ }
+
+ public override async Task StopAsync(CancellationToken cancellationToken)
+ {
+ if (_connection is not null)
+ {
+ try { await _connection.DisposeAsync(); }
+ catch { /* best effort */ }
+ }
+ await base.StopAsync(cancellationToken);
+ }
+
+ private void ApplySetting(string key, string value)
+ {
+ // Apply known settings locally
+ switch (key)
+ {
+ case "heartbeat.interval.seconds":
+ if (int.TryParse(value, out var interval) && interval >= 5)
+ {
+ // The heartbeat interval will be read from options on next heartbeat
+ _logger.LogInformation("Heartbeat interval updated to {Interval}s (applied on next restart)", interval);
+ }
+ break;
+ case "log.level":
+ _logger.LogInformation("Log level update received: {Level} (applied on next restart)", value);
+ break;
+ default:
+ _logger.LogDebug("Unknown setting {Key} = {Value} (stored for future use)", key, value);
+ break;
+ }
+ }
+
+ private async Task FetchFullConfigAsync(CancellationToken ct)
+ {
+ try
+ {
+ using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
+ http.DefaultRequestHeaders.Add("Authorization", $"Bearer {_state.ApiKey}");
+
+ var url = $"{_options.CentralUrl.TrimEnd('/')}/api/settings/agent/{_state.AgentId}";
+ var response = await http.GetAsync(url, ct);
+
+ if (response.IsSuccessStatusCode)
+ {
+ _logger.LogInformation("Full configuration fetched successfully");
+ }
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning(ex, "Failed to fetch full configuration");
+ }
+ }
+}
+
+///
+/// Retry policy for SignalR reconnection with specific delays.
+///
+internal sealed class RetryDelayed : IRetryPolicy
+{
+ private readonly TimeSpan[] _delays;
+
+ public RetryDelayed(params TimeSpan[] delays) => _delays = delays;
+
+ public TimeSpan? NextRetryDelay(RetryContext context)
+ {
+ if (context.PreviousRetryCount < _delays.Length)
+ return _delays[context.PreviousRetryCount];
+
+ // After exhausting specified delays, retry every 60 seconds
+ return TimeSpan.FromSeconds(60);
+ }
+}
diff --git a/src/Heimdall.Api/Controllers/AgentsController.cs b/src/Heimdall.Api/Controllers/AgentsController.cs
index 4a792e3..1d16104 100644
--- a/src/Heimdall.Api/Controllers/AgentsController.cs
+++ b/src/Heimdall.Api/Controllers/AgentsController.cs
@@ -3,11 +3,13 @@ using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/agents")]
+[EnableRateLimiting("Api")]
public class AgentsController : ControllerBase
{
private readonly IAgentService _agentService;
@@ -17,6 +19,8 @@ public class AgentsController : ControllerBase
/// Register an agent using a site registration token.
[AllowAnonymous]
[HttpPost("register")]
+ [ProducesResponseType(typeof(RegisterAgentResponse), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task Register(
[FromBody] RegisterAgentRequest request, CancellationToken ct)
{
@@ -33,6 +37,8 @@ public class AgentsController : ControllerBase
/// Send heartbeat from agent (API Key auth).
[Authorize(AuthenticationSchemes = "ApiKey")]
[HttpPost("{id:guid}/heartbeat")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task Heartbeat(
Guid id, [FromBody] AgentHeartbeatRequest request, CancellationToken ct)
{
@@ -45,6 +51,8 @@ public class AgentsController : ControllerBase
/// Get agent details (JWT auth).
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
[HttpGet("{id:guid}")]
+ [ProducesResponseType(typeof(AgentResponse), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task GetById(Guid id, CancellationToken ct)
{
var result = await _agentService.GetByIdAsync(id, ct);
@@ -56,10 +64,14 @@ public class AgentsController : ControllerBase
/// List agents for a site.
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
[HttpGet("by-site/{siteId:guid}")]
+ [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task ListBySite(
Guid siteId, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
{
var result = await _agentService.ListBySiteAsync(siteId, page, pageSize, ct);
+ if (!result.IsSuccess)
+ return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
}
diff --git a/src/Heimdall.Api/Controllers/AuditLogsController.cs b/src/Heimdall.Api/Controllers/AuditLogsController.cs
index 609c240..7b9659f 100644
--- a/src/Heimdall.Api/Controllers/AuditLogsController.cs
+++ b/src/Heimdall.Api/Controllers/AuditLogsController.cs
@@ -3,19 +3,24 @@ using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/audit-logs")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
+[EnableRateLimiting("Api")]
public class AuditLogsController : ControllerBase
{
private readonly IAuditLogService _auditLogService;
public AuditLogsController(IAuditLogService auditLogService) => _auditLogService = auditLogService;
+ /// List audit log entries with optional filtering.
[HttpGet]
+ [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task List(
[FromQuery] string? resourceType,
[FromQuery] string? action,
@@ -24,6 +29,8 @@ public class AuditLogsController : ControllerBase
CancellationToken ct = default)
{
var result = await _auditLogService.ListAsync(resourceType, action, page, pageSize, ct);
+ if (!result.IsSuccess)
+ return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
}
diff --git a/src/Heimdall.Api/Controllers/AuthController.cs b/src/Heimdall.Api/Controllers/AuthController.cs
index 1fcb323..9a418a9 100644
--- a/src/Heimdall.Api/Controllers/AuthController.cs
+++ b/src/Heimdall.Api/Controllers/AuthController.cs
@@ -3,11 +3,13 @@ using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/auth")]
+[EnableRateLimiting("Auth")]
public class AuthController : ControllerBase
{
private readonly IAuthService _authService;
@@ -19,8 +21,11 @@ public class AuthController : ControllerBase
_env = env;
}
+ /// Register a new user.
[AllowAnonymous]
[HttpPost("register")]
+ [ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task Register([FromBody] RegisterRequest request, CancellationToken ct)
{
var result = await _authService.RegisterAsync(request, ct);
@@ -29,8 +34,11 @@ public class AuthController : ControllerBase
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
+ /// Authenticate a user.
[AllowAnonymous]
[HttpPost("login")]
+ [ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task Login([FromBody] LoginRequest request, CancellationToken ct)
{
var result = await _authService.LoginAsync(request, ct);
@@ -39,8 +47,11 @@ public class AuthController : ControllerBase
: StatusCode(result.StatusCode ?? 401, new { error = result.Error });
}
+ /// Verify a 2FA code.
[AllowAnonymous]
[HttpPost("2fa/verify")]
+ [ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task Verify2fa([FromBody] Verify2faRequest request, CancellationToken ct)
{
var result = await _authService.Verify2faAsync(request, ct);
@@ -49,8 +60,11 @@ public class AuthController : ControllerBase
: StatusCode(result.StatusCode ?? 401, new { error = result.Error });
}
+ /// Refresh an authentication token.
[AllowAnonymous]
[HttpPost("refresh")]
+ [ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task Refresh([FromBody] RefreshTokenRequest request, CancellationToken ct)
{
var result = await _authService.RefreshTokenAsync(request.RefreshToken, ct);
@@ -62,6 +76,9 @@ public class AuthController : ControllerBase
/// Test/Dev-only: register a user with Admin role (bypasses chicken-and-egg).
[AllowAnonymous]
[HttpPost("register-admin")]
+ [ProducesResponseType(typeof(AuthResponse), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task RegisterAdmin([FromBody] RegisterRequest request, CancellationToken ct)
{
if (!_env.IsEnvironment("Testing") && !_env.IsDevelopment())
diff --git a/src/Heimdall.Api/Controllers/CamerasController.cs b/src/Heimdall.Api/Controllers/CamerasController.cs
index 3f55b62..2111a8e 100644
--- a/src/Heimdall.Api/Controllers/CamerasController.cs
+++ b/src/Heimdall.Api/Controllers/CamerasController.cs
@@ -3,19 +3,24 @@ using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/cameras")]
+[EnableRateLimiting("Api")]
public class CamerasController : ControllerBase
{
private readonly ICameraService _cameraService;
public CamerasController(ICameraService cameraService) => _cameraService = cameraService;
+ /// Create a new camera.
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
[HttpPost]
+ [ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task Create([FromBody] CreateCameraRequest request, CancellationToken ct)
{
var result = await _cameraService.CreateAsync(request, ct);
@@ -24,8 +29,11 @@ public class CamerasController : ControllerBase
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
+ /// Get a camera by ID.
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet("{id:guid}")]
+ [ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task GetById(Guid id, CancellationToken ct)
{
var result = await _cameraService.GetByIdAsync(id, ct);
@@ -34,17 +42,26 @@ public class CamerasController : ControllerBase
: NotFound(new { error = result.Error });
}
+ /// List cameras by site.
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraRead)]
[HttpGet("by-site/{siteId:guid}")]
+ [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task ListBySite(
Guid siteId, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
{
var result = await _cameraService.ListBySiteAsync(siteId, page, pageSize, ct);
+ if (!result.IsSuccess)
+ return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
+ /// Update a camera.
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
[HttpPut("{id:guid}")]
+ [ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task Update(Guid id, [FromBody] UpdateCameraRequest request, CancellationToken ct)
{
var result = await _cameraService.UpdateAsync(id, request, ct);
@@ -53,8 +70,12 @@ public class CamerasController : ControllerBase
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
+ /// Delete a camera.
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
[HttpDelete("{id:guid}")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task Delete(Guid id, CancellationToken ct)
{
var result = await _cameraService.DeleteAsync(id, ct);
diff --git a/src/Heimdall.Api/Controllers/HealthController.cs b/src/Heimdall.Api/Controllers/HealthController.cs
index 70bf578..5479fca 100644
--- a/src/Heimdall.Api/Controllers/HealthController.cs
+++ b/src/Heimdall.Api/Controllers/HealthController.cs
@@ -1,34 +1,34 @@
-using Heimdall.Infrastructure.Data;
-using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace Heimdall.Api.Controllers;
[ApiController]
-[AllowAnonymous]
public class HealthController : ControllerBase
{
+ ///
+ /// Liveness probe — always returns OK if the process is running.
+ ///
[HttpGet("/healthz")]
- public IActionResult Health()
- {
- return Ok(new { status = "healthy", timestamp = DateTime.UtcNow });
- }
+ [ProducesResponseType(typeof(void), StatusCodes.Status200OK)]
+ public IActionResult Health() => Ok(new { status = "healthy", timestamp = DateTime.UtcNow });
+ ///
+ /// Readiness probe — checks if the database is reachable.
+ /// Uses ASP.NET Core health checks infrastructure.
+ ///
[HttpGet("/readyz")]
- public async Task Readiness([FromServices] AppDbContext db)
+ [ProducesResponseType(typeof(void), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status503ServiceUnavailable)]
+ public async Task Readiness(
+ [FromServices] HealthCheckService healthCheckService,
+ CancellationToken ct)
{
- try
- {
- var canConnect = await db.Database.CanConnectAsync();
- if (!canConnect)
- return StatusCode(503, new { status = "unhealthy", database = "disconnected" });
+ var report = await healthCheckService.CheckHealthAsync(
+ _ => true, ct);
- return Ok(new { status = "ready", database = "connected" });
- }
- catch (Exception ex)
- {
- return StatusCode(503, new { status = "unhealthy", database = ex.Message });
- }
+ return report.Status == HealthStatus.Healthy
+ ? Ok(new { status = "healthy", timestamp = DateTime.UtcNow })
+ : StatusCode(503, new { status = "unhealthy", errors = report.Entries });
}
}
diff --git a/src/Heimdall.Api/Controllers/SettingsController.cs b/src/Heimdall.Api/Controllers/SettingsController.cs
new file mode 100644
index 0000000..2320d1a
--- /dev/null
+++ b/src/Heimdall.Api/Controllers/SettingsController.cs
@@ -0,0 +1,196 @@
+using Heimdall.Application.Common;
+using Heimdall.Application.DTOs;
+using Heimdall.Application.Services;
+using Heimdall.Api.Hubs;
+using Heimdall.Infrastructure.Security;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.RateLimiting;
+
+namespace Heimdall.Api.Controllers;
+
+[ApiController]
+[Route("api/settings")]
+[Authorize]
+[EnableRateLimiting("Api")]
+public class SettingsController : ControllerBase
+{
+ private readonly ISettingService _settingService;
+ private readonly IConfigBroadcastService _broadcast;
+ private readonly ILogger _logger;
+
+ public SettingsController(
+ ISettingService settingService,
+ IConfigBroadcastService broadcast,
+ ILogger logger)
+ {
+ _settingService = settingService;
+ _broadcast = broadcast;
+ _logger = logger;
+ }
+
+ /// List all global settings (Admin only).
+ [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
+ [HttpGet]
+ [ProducesResponseType(typeof(List), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
+ public async Task ListAll(CancellationToken ct)
+ {
+ var result = await _settingService.GetAllSettingsAsync(ct);
+ if (!result.IsSuccess)
+ return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
+ return Ok(result.Data);
+ }
+
+ /// Get a global setting by key (Admin only).
+ [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
+ [HttpGet("{key}")]
+ [ProducesResponseType(typeof(AppSettingDto), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
+ public async Task GetByKey(string key, CancellationToken ct)
+ {
+ var result = await _settingService.GetSettingByKeyAsync(key, ct);
+ return result.IsSuccess
+ ? Ok(result.Data)
+ : NotFound(new { error = result.Error });
+ }
+
+ /// Create a new global setting (Admin only).
+ [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
+ [HttpPost]
+ [ProducesResponseType(typeof(AppSettingDto), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
+ public async Task Create(
+ [FromBody] CreateAppSettingRequest request, CancellationToken ct)
+ {
+ var result = await _settingService.CreateSettingAsync(request, ct);
+ if (!result.IsSuccess)
+ return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
+
+ await _broadcast.NotifyGlobalSettingChanged(result.Data!.Key, result.Data.Value, ct);
+ _logger.LogInformation("Created global setting {Key} = {Value}", result.Data.Key, result.Data.Value);
+ return Ok(result.Data);
+ }
+
+ /// Update a global setting (Admin only). Broadcasts the change to all agents.
+ [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
+ [HttpPut("{key}")]
+ [ProducesResponseType(typeof(AppSettingDto), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
+ public async Task Update(
+ string key, [FromBody] UpdateAppSettingRequest request, CancellationToken ct)
+ {
+ var result = await _settingService.UpdateSettingAsync(key, request, ct);
+ if (!result.IsSuccess)
+ return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
+
+ await _broadcast.NotifyGlobalSettingChanged(result.Data!.Key, result.Data.Value, ct);
+ _logger.LogInformation("Updated global setting {Key} = {Value}", result.Data.Key, result.Data.Value);
+ return Ok(result.Data);
+ }
+
+ /// Delete a global setting (Admin only). Broadcasts the change to all agents.
+ [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
+ [HttpDelete("{key}")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
+ public async Task Delete(string key, CancellationToken ct)
+ {
+ var result = await _settingService.DeleteSettingAsync(key, ct);
+ if (!result.IsSuccess)
+ return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
+
+ await _broadcast.NotifyAllAgentsReload(ct);
+ _logger.LogInformation("Deleted global setting {Key}", key);
+ return NoContent();
+ }
+
+ ///
+ /// Get the effective configuration for an agent: global defaults merged with
+ /// per-agent overrides (Agent or Admin only).
+ ///
+ [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
+ [HttpGet("agent/{agentId:guid}")]
+ [ProducesResponseType(typeof(Dictionary), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
+ public async Task GetEffectiveConfig(Guid agentId, CancellationToken ct)
+ {
+ var result = await _settingService.GetEffectiveAgentConfigAsync(agentId, ct);
+ return result.IsSuccess
+ ? Ok(result.Data)
+ : NotFound(new { error = result.Error });
+ }
+
+ /// List all setting overrides for a specific agent (Admin only).
+ [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
+ [HttpGet("agent/{agentId:guid}/overrides")]
+ [ProducesResponseType(typeof(List), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
+ public async Task ListAgentOverrides(Guid agentId, CancellationToken ct)
+ {
+ var result = await _settingService.GetAgentSettingsAsync(agentId, ct);
+ return result.IsSuccess
+ ? Ok(result.Data)
+ : NotFound(new { error = result.Error });
+ }
+
+ ///
+ /// Set (create or update) a per-agent setting override (Admin only).
+ /// Broadcasts the change to the affected agent in real-time.
+ ///
+ [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
+ [HttpPut("agent/{agentId:guid}/overrides")]
+ [ProducesResponseType(typeof(AgentSettingDto), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
+ public async Task SetAgentOverride(
+ Guid agentId, [FromBody] SetAgentSettingRequest request, CancellationToken ct)
+ {
+ var result = await _settingService.SetAgentSettingAsync(agentId, request, ct);
+ if (!result.IsSuccess)
+ return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
+
+ await _broadcast.NotifyAgentSettingChanged(agentId, result.Data!.Key, result.Data.Value, ct);
+ _logger.LogInformation("Set agent override Agent={AgentId}, {Key} = {Value}",
+ agentId, result.Data.Key, result.Data.Value);
+ return Ok(result.Data);
+ }
+
+ ///
+ /// Remove a per-agent setting override (Admin only).
+ /// Broadcasts a reload notification to the affected agent.
+ ///
+ [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
+ [HttpDelete("agent/{agentId:guid}/overrides/{key}")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
+ public async Task RemoveAgentOverride(Guid agentId, string key, CancellationToken ct)
+ {
+ var result = await _settingService.RemoveAgentSettingAsync(agentId, key, ct);
+ if (!result.IsSuccess)
+ return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
+
+ await _broadcast.NotifyAgentSettingChanged(agentId, key, string.Empty, ct);
+ _logger.LogInformation("Removed agent override Agent={AgentId}, {Key}", agentId, key);
+ return NoContent();
+ }
+
+ ///
+ /// Broadcast a "ConfigReload" signal to all connected agents so they
+ /// re-fetch their full configuration (Admin only).
+ ///
+ [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminManage)]
+ [HttpPost("reload")]
+ [ProducesResponseType(StatusCodes.Status202Accepted)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
+ public async Task ReloadAllAgents(CancellationToken ct)
+ {
+ await _broadcast.NotifyAllAgentsReload(ct);
+ _logger.LogInformation("Broadcast ConfigReload to all agents");
+ return Accepted(new { message = "Config reload broadcast to all connected agents" });
+ }
+}
diff --git a/src/Heimdall.Api/Controllers/SitesController.cs b/src/Heimdall.Api/Controllers/SitesController.cs
index 42d6a1a..86cc237 100644
--- a/src/Heimdall.Api/Controllers/SitesController.cs
+++ b/src/Heimdall.Api/Controllers/SitesController.cs
@@ -4,11 +4,13 @@ using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/sites")]
+[EnableRateLimiting("Api")]
public class SitesController : ControllerBase
{
private readonly ISiteService _siteService;
@@ -18,10 +20,16 @@ public class SitesController : ControllerBase
/// Create a new site (Admin only).
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)]
[HttpPost]
+ [ProducesResponseType(typeof(SiteWithTokenResponse), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task Create(
[FromBody] CreateSiteRequest request, CancellationToken ct)
{
- var userId = Guid.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
+ var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
+ if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId))
+ return Unauthorized(new { error = "Invalid user identity" });
+
var result = await _siteService.CreateAsync(request, userId, ct);
return result.IsSuccess
? Ok(result.Data)
@@ -31,16 +39,22 @@ public class SitesController : ControllerBase
/// List all sites.
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
[HttpGet]
+ [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task List(
[FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
{
var result = await _siteService.ListAsync(page, pageSize, ct);
+ if (!result.IsSuccess)
+ return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
/// Get a site by ID.
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
[HttpGet("{id:guid}")]
+ [ProducesResponseType(typeof(SiteResponse), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task GetById(Guid id, CancellationToken ct)
{
var result = await _siteService.GetByIdAsync(id, ct);
@@ -52,6 +66,9 @@ public class SitesController : ControllerBase
/// Update a site (Admin only).
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)]
[HttpPut("{id:guid}")]
+ [ProducesResponseType(typeof(SiteResponse), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task Update(
Guid id, [FromBody] UpdateSiteRequest request, CancellationToken ct)
{
@@ -64,6 +81,9 @@ public class SitesController : ControllerBase
/// Delete a site (Admin only).
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteDelete)]
[HttpDelete("{id:guid}")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task Delete(Guid id, CancellationToken ct)
{
var result = await _siteService.DeleteAsync(id, ct);
@@ -75,6 +95,9 @@ public class SitesController : ControllerBase
/// Generate a new agent registration token (Admin only).
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)]
[HttpPost("{id:guid}/tokens")]
+ [ProducesResponseType(typeof(RegistrationTokenResponse), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task GenerateToken(Guid id, CancellationToken ct)
{
var result = await _siteService.GenerateTokenAsync(id, ct);
diff --git a/src/Heimdall.Api/Controllers/StatsController.cs b/src/Heimdall.Api/Controllers/StatsController.cs
index e77d654..c4d93b8 100644
--- a/src/Heimdall.Api/Controllers/StatsController.cs
+++ b/src/Heimdall.Api/Controllers/StatsController.cs
@@ -3,22 +3,29 @@ using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/stats")]
+[EnableRateLimiting("Api")]
public class StatsController : ControllerBase
{
private readonly IStatsService _statsService;
public StatsController(IStatsService statsService) => _statsService = statsService;
+ /// Get system-wide statistics.
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
[HttpGet]
+ [ProducesResponseType(typeof(StatsResponse), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task GetStats(CancellationToken ct)
{
var result = await _statsService.GetStatsAsync(ct);
+ if (!result.IsSuccess)
+ return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(new { data = result.Data, timestamp = DateTime.UtcNow });
}
}
diff --git a/src/Heimdall.Api/Controllers/UsersController.cs b/src/Heimdall.Api/Controllers/UsersController.cs
index 4fb42fb..f832ae2 100644
--- a/src/Heimdall.Api/Controllers/UsersController.cs
+++ b/src/Heimdall.Api/Controllers/UsersController.cs
@@ -3,27 +3,37 @@ using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.RateLimiting;
namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/users")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.AdminUsers)]
+[EnableRateLimiting("Api")]
public class UsersController : ControllerBase
{
private readonly IUserService _userService;
public UsersController(IUserService userService) => _userService = userService;
+ /// List all users (Admin only).
[HttpGet]
+ [ProducesResponseType(typeof(PagedResult), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task List(
[FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
{
var result = await _userService.ListAsync(page, pageSize, ct);
+ if (!result.IsSuccess)
+ return StatusCode(result.StatusCode ?? 400, new { error = result.Error });
return Ok(result.Data);
}
+ /// Get a user by ID.
[HttpGet("{id:guid}")]
+ [ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task GetById(Guid id, CancellationToken ct)
{
var result = await _userService.GetByIdAsync(id, ct);
@@ -32,7 +42,10 @@ public class UsersController : ControllerBase
: NotFound(new { error = result.Error });
}
+ /// Create a new user (Admin only).
[HttpPost]
+ [ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task Create([FromBody] CreateUserRequest request, CancellationToken ct)
{
var result = await _userService.CreateAsync(request, ct);
@@ -41,7 +54,11 @@ public class UsersController : ControllerBase
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
+ /// Update a user (Admin only).
[HttpPut("{id:guid}")]
+ [ProducesResponseType(typeof(UserResponse), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task Update(
Guid id, [FromBody] UpdateUserRequest request, CancellationToken ct)
{
@@ -51,7 +68,10 @@ public class UsersController : ControllerBase
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
+ /// Assign roles to a user (Admin only).
[HttpPut("{id:guid}/roles")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task AssignRoles(
Guid id, [FromBody] AssignRolesRequest request, CancellationToken ct)
{
@@ -61,7 +81,10 @@ public class UsersController : ControllerBase
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
+ /// Assign sites to a user (Admin only).
[HttpPut("{id:guid}/sites")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task AssignSites(
Guid id, [FromBody] AssignSitesRequest request, CancellationToken ct)
{
@@ -71,7 +94,10 @@ public class UsersController : ControllerBase
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
+ /// Reset a user's password (Admin only).
[HttpPost("{id:guid}/reset-password")]
+ [ProducesResponseType(typeof(ResetPasswordResponse), StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task ResetPassword(Guid id, CancellationToken ct)
{
var result = await _userService.ResetPasswordAsync(id, ct);
@@ -80,7 +106,10 @@ public class UsersController : ControllerBase
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
+ /// Lock a user account (Admin only).
[HttpPost("{id:guid}/lock")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task Lock(Guid id, CancellationToken ct)
{
var result = await _userService.LockAsync(id, ct);
@@ -89,7 +118,10 @@ public class UsersController : ControllerBase
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
+ /// Unlock a user account (Admin only).
[HttpPost("{id:guid}/unlock")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ [ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task Unlock(Guid id, CancellationToken ct)
{
var result = await _userService.UnlockAsync(id, ct);
diff --git a/src/Heimdall.Api/Hubs/ConfigHub.cs b/src/Heimdall.Api/Hubs/ConfigHub.cs
new file mode 100644
index 0000000..fb6a398
--- /dev/null
+++ b/src/Heimdall.Api/Hubs/ConfigHub.cs
@@ -0,0 +1,96 @@
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.SignalR;
+using Heimdall.Application.Services;
+
+namespace Heimdall.Api.Hubs;
+
+///
+/// SignalR hub for real-time configuration push to agents.
+/// Agents connect and receive config updates instantly when settings change.
+///
+[Authorize(AuthenticationSchemes = "ApiKey")]
+public class ConfigHub : Hub
+{
+ private readonly ILogger _logger;
+
+ public ConfigHub(ILogger logger)
+ {
+ _logger = logger;
+ }
+
+ ///
+ /// Agents call this on connect to join their personal config channel.
+ /// The agentId comes from the authenticated API key's associated agent.
+ ///
+ public async Task JoinAgentGroup(string agentId)
+ {
+ if (!Guid.TryParse(agentId, out var _))
+ {
+ await Clients.Caller.SendAsync("Error", "Invalid agentId format");
+ return;
+ }
+
+ await Groups.AddToGroupAsync(Context.ConnectionId, $"agent_{agentId}");
+ _logger.LogInformation("Agent {AgentId} joined config group", agentId);
+ }
+
+ public override async Task OnDisconnectedAsync(Exception? exception)
+ {
+ _logger.LogInformation("Agent disconnected from config hub: {ConnectionId}", Context.ConnectionId);
+ await base.OnDisconnectedAsync(exception);
+ }
+}
+
+///
+/// Service that broadcasts config changes to connected agents via SignalR.
+/// Called by the SettingService after any setting change.
+///
+public interface IConfigBroadcastService
+{
+ /// Notify all connected agents that a global setting changed.
+ Task NotifyGlobalSettingChanged(string key, string value, CancellationToken ct = default);
+
+ /// Notify a specific agent that one of its overrides changed.
+ Task NotifyAgentSettingChanged(Guid agentId, string key, string value, CancellationToken ct = default);
+
+ /// Notify all agents to reload their full configuration.
+ Task NotifyAllAgentsReload(CancellationToken ct = default);
+}
+
+///
+/// Broadcasts config changes to connected agents via SignalR.
+/// Injected as a scoped service; the HubContext is a singleton so broadcasting
+/// works safely across all connected clients.
+///
+public class ConfigBroadcastService : IConfigBroadcastService
+{
+ private readonly IHubContext _hubContext;
+ private readonly ILogger _logger;
+
+ public ConfigBroadcastService(IHubContext hubContext, ILogger logger)
+ {
+ _hubContext = hubContext;
+ _logger = logger;
+ }
+
+ ///
+ public async Task NotifyGlobalSettingChanged(string key, string value, CancellationToken ct = default)
+ {
+ _logger.LogDebug("Broadcasting global setting change: {Key} = {Value}", key, value);
+ await _hubContext.Clients.All.SendAsync("SettingChanged", key, value, ct);
+ }
+
+ ///
+ public async Task NotifyAgentSettingChanged(Guid agentId, string key, string value, CancellationToken ct = default)
+ {
+ _logger.LogDebug("Broadcasting agent setting change: Agent={AgentId}, {Key} = {Value}", agentId, key, value);
+ await _hubContext.Clients.Group($"agent_{agentId}").SendAsync("SettingChanged", key, value, ct);
+ }
+
+ ///
+ public async Task NotifyAllAgentsReload(CancellationToken ct = default)
+ {
+ _logger.LogInformation("Broadcasting full config reload to all agents");
+ await _hubContext.Clients.All.SendAsync("ConfigReload", ct);
+ }
+}
diff --git a/src/Heimdall.Api/Program.cs b/src/Heimdall.Api/Program.cs
index 5c05faf..33f8165 100644
--- a/src/Heimdall.Api/Program.cs
+++ b/src/Heimdall.Api/Program.cs
@@ -4,6 +4,7 @@ using Scalar.AspNetCore;
using Heimdall.Api.Filters;
using Heimdall.Application;
using Heimdall.Infrastructure;
+using Heimdall.Api.Hubs;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Security;
using Microsoft.AspNetCore.Authentication.JwtBearer;
@@ -46,6 +47,9 @@ else
builder.Services.AddControllers();
}
+builder.Services.AddSignalR();
+builder.Services.AddScoped();
+
builder.Services.AddOpenApi();
// ── Application layer ─────────────────────────────────────────────
@@ -191,5 +195,6 @@ app.UseRateLimiter();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
+app.MapHub("/hubs/config");
app.Run();
diff --git a/src/Heimdall.Application/DTOs/SettingDto.cs b/src/Heimdall.Application/DTOs/SettingDto.cs
new file mode 100644
index 0000000..da06692
--- /dev/null
+++ b/src/Heimdall.Application/DTOs/SettingDto.cs
@@ -0,0 +1,59 @@
+using System.Text.Json.Serialization;
+
+namespace Heimdall.Application.DTOs;
+
+///
+/// A global application setting visible to all agents unless overridden.
+///
+public sealed record AppSettingDto(
+ [property: JsonPropertyName("id")] Guid Id,
+ [property: JsonPropertyName("key")] string Key,
+ [property: JsonPropertyName("value")] string Value,
+ [property: JsonPropertyName("description")] string? Description,
+ [property: JsonPropertyName("category")] string Category,
+ [property: JsonPropertyName("valueType")] string ValueType,
+ [property: JsonPropertyName("allowedValues")] string? AllowedValues,
+ [property: JsonPropertyName("updatedAt")] DateTime UpdatedAt
+);
+
+///
+/// Per-agent setting override.
+///
+public sealed record AgentSettingDto(
+ [property: JsonPropertyName("id")] Guid Id,
+ [property: JsonPropertyName("agentId")] Guid AgentId,
+ [property: JsonPropertyName("key")] string Key,
+ [property: JsonPropertyName("value")] string Value,
+ [property: JsonPropertyName("updatedAt")] DateTime UpdatedAt
+);
+
+///
+/// Request to create a new global setting.
+///
+public sealed record CreateAppSettingRequest(
+ [property: JsonPropertyName("key")] string Key,
+ [property: JsonPropertyName("value")] string Value,
+ [property: JsonPropertyName("category")] string Category = "General",
+ [property: JsonPropertyName("description")] string? Description = null,
+ [property: JsonPropertyName("valueType")] string ValueType = "string",
+ [property: JsonPropertyName("allowedValues")] string? AllowedValues = null
+);
+
+///
+/// Request to update an existing global setting value.
+///
+public sealed record UpdateAppSettingRequest(
+ [property: JsonPropertyName("value")] string Value,
+ [property: JsonPropertyName("description")] string? Description = null,
+ [property: JsonPropertyName("category")] string? Category = null,
+ [property: JsonPropertyName("valueType")] string? ValueType = null,
+ [property: JsonPropertyName("allowedValues")] string? AllowedValues = null
+);
+
+///
+/// Request to set a per-agent setting override.
+///
+public sealed record SetAgentSettingRequest(
+ [property: JsonPropertyName("key")] string Key,
+ [property: JsonPropertyName("value")] string Value
+);
diff --git a/src/Heimdall.Application/Services/ISettingService.cs b/src/Heimdall.Application/Services/ISettingService.cs
new file mode 100644
index 0000000..6f8e623
--- /dev/null
+++ b/src/Heimdall.Application/Services/ISettingService.cs
@@ -0,0 +1,29 @@
+using Heimdall.Application.Common;
+using Heimdall.Application.DTOs;
+
+namespace Heimdall.Application.Services;
+
+///
+/// Manages global settings and per-agent setting overrides.
+/// All changes are broadcast to connected agents via SignalR in real-time.
+///
+public interface ISettingService
+{
+ // Global settings
+ Task>> GetAllSettingsAsync(CancellationToken ct = default);
+ Task> GetSettingByKeyAsync(string key, CancellationToken ct = default);
+ Task> CreateSettingAsync(CreateAppSettingRequest request, CancellationToken ct = default);
+ Task> UpdateSettingAsync(string key, UpdateAppSettingRequest request, CancellationToken ct = default);
+ Task DeleteSettingAsync(string key, CancellationToken ct = default);
+
+ // Agent-specific overrides
+ Task>> GetAgentSettingsAsync(Guid agentId, CancellationToken ct = default);
+ Task> SetAgentSettingAsync(Guid agentId, SetAgentSettingRequest request, CancellationToken ct = default);
+ Task RemoveAgentSettingAsync(Guid agentId, string key, CancellationToken ct = default);
+
+ ///
+ /// Returns the effective configuration for an agent: global defaults merged with
+ /// per-agent overrides. Used by agents to fetch their full config on connect.
+ ///
+ Task>> GetEffectiveAgentConfigAsync(Guid agentId, CancellationToken ct = default);
+}
diff --git a/src/Heimdall.Application/Validators/CreateAppSettingValidator.cs b/src/Heimdall.Application/Validators/CreateAppSettingValidator.cs
new file mode 100644
index 0000000..d774b88
--- /dev/null
+++ b/src/Heimdall.Application/Validators/CreateAppSettingValidator.cs
@@ -0,0 +1,40 @@
+using FluentValidation;
+using Heimdall.Application.DTOs;
+
+namespace Heimdall.Application.Validators;
+
+public class CreateAppSettingValidator : AbstractValidator
+{
+ public CreateAppSettingValidator()
+ {
+ RuleFor(x => x.Key).NotEmpty().MaximumLength(200)
+ .Matches(@"^[a-z0-9][a-z0-9._-]*[a-z0-9]$")
+ .WithMessage("Key must start and end with a lowercase alphanumeric character, and contain only lowercase letters, digits, dots, hyphens, or underscores");
+ RuleFor(x => x.Value).NotNull();
+ RuleFor(x => x.Category).NotEmpty().MaximumLength(100);
+ RuleFor(x => x.ValueType).Must(t => t is "string" or "int" or "bool" or "double" or "select")
+ .WithMessage("ValueType must be one of: string, int, bool, double, select");
+ }
+}
+
+public class UpdateAppSettingValidator : AbstractValidator
+{
+ public UpdateAppSettingValidator()
+ {
+ RuleFor(x => x.Value).NotEmpty();
+ When(x => x.Category is not null, () =>
+ RuleFor(x => x.Category!).MaximumLength(100));
+ When(x => x.ValueType is not null, () =>
+ RuleFor(x => x.ValueType!).Must(t => t is "string" or "int" or "bool" or "double" or "select")
+ .WithMessage("ValueType must be one of: string, int, bool, double, select"));
+ }
+}
+
+public class SetAgentSettingValidator : AbstractValidator
+{
+ public SetAgentSettingValidator()
+ {
+ RuleFor(x => x.Key).NotEmpty().MaximumLength(200);
+ RuleFor(x => x.Value).NotNull();
+ }
+}
diff --git a/src/Heimdall.Application/Validators/CreateCameraValidator.cs b/src/Heimdall.Application/Validators/CreateCameraValidator.cs
new file mode 100644
index 0000000..dd84502
--- /dev/null
+++ b/src/Heimdall.Application/Validators/CreateCameraValidator.cs
@@ -0,0 +1,15 @@
+using FluentValidation;
+using Heimdall.Application.DTOs;
+
+namespace Heimdall.Application.Validators;
+
+public class CreateCameraValidator : AbstractValidator
+{
+ public CreateCameraValidator()
+ {
+ RuleFor(x => x.Name).NotEmpty().MaximumLength(200);
+ RuleFor(x => x.RtspUrl).NotEmpty().Must(uri => Uri.TryCreate(uri, UriKind.Absolute, out _))
+ .WithMessage("RTSP URL must be a valid absolute URI");
+ RuleFor(x => x.SiteId).NotEmpty();
+ }
+}
diff --git a/src/Heimdall.Application/Validators/CreateSiteValidator.cs b/src/Heimdall.Application/Validators/CreateSiteValidator.cs
index bd93cd6..345bfee 100644
--- a/src/Heimdall.Application/Validators/CreateSiteValidator.cs
+++ b/src/Heimdall.Application/Validators/CreateSiteValidator.cs
@@ -77,7 +77,7 @@ public class RegisterRequestValidator : AbstractValidator
RuleFor(x => x.Password)
.NotEmpty()
- .MinimumLength(8)
+ .MinimumLength(12)
.MaximumLength(200);
RuleFor(x => x.DisplayName)
diff --git a/src/Heimdall.Application/Validators/CreateUserValidator.cs b/src/Heimdall.Application/Validators/CreateUserValidator.cs
new file mode 100644
index 0000000..5784088
--- /dev/null
+++ b/src/Heimdall.Application/Validators/CreateUserValidator.cs
@@ -0,0 +1,19 @@
+using FluentValidation;
+using Heimdall.Application.DTOs;
+
+namespace Heimdall.Application.Validators;
+
+public class CreateUserValidator : AbstractValidator
+{
+ public CreateUserValidator()
+ {
+ RuleFor(x => x.Email).NotEmpty().EmailAddress().MaximumLength(256);
+ RuleFor(x => x.DisplayName).NotEmpty().MaximumLength(100);
+ RuleFor(x => x.Password).NotEmpty().MinimumLength(12)
+ .WithMessage("Password must be at least 12 characters");
+ When(x => x.Roles is not null, () =>
+ RuleFor(x => x.Roles!)
+ .Must(roles => roles.All(r => r is "Admin" or "Supervisor" or "Viewer"))
+ .WithMessage("Roles must be Admin, Supervisor, or Viewer"));
+ }
+}
diff --git a/src/Heimdall.Application/Validators/UpdateCameraValidator.cs b/src/Heimdall.Application/Validators/UpdateCameraValidator.cs
new file mode 100644
index 0000000..21a4506
--- /dev/null
+++ b/src/Heimdall.Application/Validators/UpdateCameraValidator.cs
@@ -0,0 +1,14 @@
+using FluentValidation;
+using Heimdall.Application.DTOs;
+
+namespace Heimdall.Application.Validators;
+
+public class UpdateCameraValidator : AbstractValidator
+{
+ public UpdateCameraValidator()
+ {
+ RuleFor(x => x.Name).NotEmpty().MaximumLength(200);
+ RuleFor(x => x.RtspUrl).NotEmpty().Must(uri => Uri.TryCreate(uri, UriKind.Absolute, out _))
+ .WithMessage("RTSP URL must be a valid absolute URI");
+ }
+}
diff --git a/src/Heimdall.Application/Validators/UpdateSiteValidator.cs b/src/Heimdall.Application/Validators/UpdateSiteValidator.cs
new file mode 100644
index 0000000..d6093fc
--- /dev/null
+++ b/src/Heimdall.Application/Validators/UpdateSiteValidator.cs
@@ -0,0 +1,17 @@
+using FluentValidation;
+using Heimdall.Application.DTOs;
+
+namespace Heimdall.Application.Validators;
+
+public class UpdateSiteValidator : AbstractValidator
+{
+ public UpdateSiteValidator()
+ {
+ When(x => x.Name is not null, () =>
+ RuleFor(x => x.Name!).MaximumLength(200));
+ When(x => x.Address is not null, () =>
+ RuleFor(x => x.Address!).MaximumLength(500));
+ When(x => x.Timezone is not null, () =>
+ RuleFor(x => x.Timezone!).MaximumLength(100));
+ }
+}
diff --git a/src/Heimdall.Application/Validators/UpdateUserValidator.cs b/src/Heimdall.Application/Validators/UpdateUserValidator.cs
new file mode 100644
index 0000000..08e4432
--- /dev/null
+++ b/src/Heimdall.Application/Validators/UpdateUserValidator.cs
@@ -0,0 +1,16 @@
+using FluentValidation;
+using Heimdall.Application.DTOs;
+
+namespace Heimdall.Application.Validators;
+
+public class UpdateUserValidator : AbstractValidator
+{
+ public UpdateUserValidator()
+ {
+ When(x => x.DisplayName is not null, () =>
+ RuleFor(x => x.DisplayName!).MaximumLength(100));
+ When(x => x.Theme is not null, () =>
+ RuleFor(x => x.Theme!).Must(t => t is "light" or "dark")
+ .WithMessage("Theme must be 'light' or 'dark'"));
+ }
+}
diff --git a/src/Heimdall.Domain/Entities/AppSetting.cs b/src/Heimdall.Domain/Entities/AppSetting.cs
new file mode 100644
index 0000000..cc96b69
--- /dev/null
+++ b/src/Heimdall.Domain/Entities/AppSetting.cs
@@ -0,0 +1,97 @@
+namespace Heimdall.Domain.Entities;
+
+///
+/// Global application setting (key-value). Stored in DB and pushed to all agents
+/// in real-time via SignalR. Overridable per-agent via AgentSetting.
+///
+public class AppSetting
+{
+ public Guid Id { get; private set; } = Guid.NewGuid();
+
+ /// Unique setting key (e.g. "heartbeat.interval.seconds", "log.level", "ai.detection.enabled").
+ public string Key { get; private set; } = string.Empty;
+
+ /// Setting value as a JSON-serializable string.
+ public string Value { get; private set; } = string.Empty;
+
+ /// Human-readable description of what this setting controls.
+ public string? Description { get; private set; }
+
+ /// Category for UI grouping (e.g. "Heartbeat", "Logging", "AI", "Recording").
+ public string Category { get; private set; } = "General";
+
+ /// Value type hint for UI rendering ("string", "int", "bool", "double", "select").
+ public string ValueType { get; private set; } = "string";
+
+ /// For select types, comma-separated allowed values.
+ public string? AllowedValues { get; private set; }
+
+ public DateTime CreatedAt { get; private set; } = DateTime.UtcNow;
+ public DateTime UpdatedAt { get; private set; } = DateTime.UtcNow;
+
+ private AppSetting() { } // EF Core
+
+ public AppSetting(string key, string value, string category = "General", string? description = null)
+ {
+ Key = !string.IsNullOrWhiteSpace(key) ? key.Trim().ToLowerInvariant()
+ : throw new ArgumentException("Key is required", nameof(key));
+ Value = value ?? string.Empty;
+ Category = category;
+ Description = description;
+ }
+
+ public void UpdateValue(string value)
+ {
+ Value = value ?? string.Empty;
+ UpdatedAt = DateTime.UtcNow;
+ }
+
+ public void UpdateMetadata(string? description, string? category, string? valueType, string? allowedValues)
+ {
+ if (description is not null) Description = description;
+ if (category is not null) Category = category;
+ if (valueType is not null) ValueType = valueType;
+ if (allowedValues is not null) AllowedValues = allowedValues;
+ UpdatedAt = DateTime.UtcNow;
+ }
+}
+
+///
+/// Per-agent setting override. Takes precedence over AppSetting for a specific agent.
+/// When created/updated, a SignalR notification is sent to the affected agent.
+///
+public class AgentSetting
+{
+ public Guid Id { get; private set; } = Guid.NewGuid();
+
+ /// Foreign key to the Agent this setting applies to.
+ public Guid AgentId { get; private set; }
+
+ /// Setting key (same namespace as AppSetting keys).
+ public string Key { get; private set; } = string.Empty;
+
+ /// Override value for this specific agent.
+ public string Value { get; private set; } = string.Empty;
+
+ public DateTime CreatedAt { get; private set; } = DateTime.UtcNow;
+ public DateTime UpdatedAt { get; private set; } = DateTime.UtcNow;
+
+ // Navigation
+ public Agent Agent { get; private set; } = null!;
+
+ private AgentSetting() { } // EF Core
+
+ public AgentSetting(Guid agentId, string key, string value)
+ {
+ AgentId = agentId;
+ Key = !string.IsNullOrWhiteSpace(key) ? key.Trim().ToLowerInvariant()
+ : throw new ArgumentException("Key is required", nameof(key));
+ Value = value ?? string.Empty;
+ }
+
+ public void UpdateValue(string value)
+ {
+ Value = value ?? string.Empty;
+ UpdatedAt = DateTime.UtcNow;
+ }
+}
diff --git a/src/Heimdall.Infrastructure/Data/AppDbContext.cs b/src/Heimdall.Infrastructure/Data/AppDbContext.cs
index c2fc787..340c195 100644
--- a/src/Heimdall.Infrastructure/Data/AppDbContext.cs
+++ b/src/Heimdall.Infrastructure/Data/AppDbContext.cs
@@ -19,6 +19,8 @@ public class AppDbContext : IdentityDbContext
public DbSet UserSites => Set();
public DbSet ApiKeys => Set();
public DbSet AuditLogs => Set();
+ public DbSet AppSettings => Set();
+ public DbSet AgentSettings => Set();
protected override void OnModelCreating(ModelBuilder builder)
{
diff --git a/src/Heimdall.Infrastructure/Data/Configurations/AppSettingConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/AppSettingConfiguration.cs
new file mode 100644
index 0000000..96c3c75
--- /dev/null
+++ b/src/Heimdall.Infrastructure/Data/Configurations/AppSettingConfiguration.cs
@@ -0,0 +1,43 @@
+using Heimdall.Domain.Entities;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+
+namespace Heimdall.Infrastructure.Data.Configurations;
+
+public class AppSettingConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("app_settings");
+ builder.HasKey(x => x.Id);
+ builder.HasIndex(x => x.Key).IsUnique();
+ builder.Property(x => x.Key).IsRequired().HasMaxLength(200).HasColumnName("key");
+ builder.Property(x => x.Value).IsRequired().HasColumnName("value");
+ builder.Property(x => x.Description).HasMaxLength(500).HasColumnName("description");
+ builder.Property(x => x.Category).IsRequired().HasMaxLength(100).HasColumnName("category");
+ builder.Property(x => x.ValueType).IsRequired().HasMaxLength(50).HasColumnName("value_type");
+ builder.Property(x => x.AllowedValues).HasMaxLength(2000).HasColumnName("allowed_values");
+ builder.Property(x => x.CreatedAt).HasColumnName("created_at");
+ builder.Property(x => x.UpdatedAt).HasColumnName("updated_at");
+ }
+}
+
+public class AgentSettingConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("agent_settings");
+ builder.HasKey(x => x.Id);
+ builder.HasIndex(x => new { x.AgentId, x.Key }).IsUnique();
+ builder.Property(x => x.AgentId).IsRequired().HasColumnName("agent_id");
+ builder.Property(x => x.Key).IsRequired().HasMaxLength(200).HasColumnName("key");
+ builder.Property(x => x.Value).IsRequired().HasColumnName("value");
+ builder.Property(x => x.CreatedAt).HasColumnName("created_at");
+ builder.Property(x => x.UpdatedAt).HasColumnName("updated_at");
+
+ builder.HasOne(x => x.Agent)
+ .WithMany()
+ .HasForeignKey(x => x.AgentId)
+ .OnDelete(DeleteBehavior.Cascade);
+ }
+}
diff --git a/src/Heimdall.Infrastructure/DependencyInjection.cs b/src/Heimdall.Infrastructure/DependencyInjection.cs
index ab4f905..7ac2eba 100644
--- a/src/Heimdall.Infrastructure/DependencyInjection.cs
+++ b/src/Heimdall.Infrastructure/DependencyInjection.cs
@@ -68,6 +68,7 @@ public static class DependencyInjection
services.AddScoped();
services.AddScoped();
services.AddScoped();
+ services.AddScoped();
return services;
}
diff --git a/src/Heimdall.Infrastructure/Migrations/20260718143003_AddAppSettings.Designer.cs b/src/Heimdall.Infrastructure/Migrations/20260718143003_AddAppSettings.Designer.cs
new file mode 100644
index 0000000..933c15e
--- /dev/null
+++ b/src/Heimdall.Infrastructure/Migrations/20260718143003_AddAppSettings.Designer.cs
@@ -0,0 +1,985 @@
+//
+using System;
+using Heimdall.Infrastructure.Data;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
+
+#nullable disable
+
+namespace Heimdall.Infrastructure.Migrations
+{
+ [DbContext(typeof(AppDbContext))]
+ [Migration("20260718143003_AddAppSettings")]
+ partial class AddAppSettings
+ {
+ ///
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasAnnotation("ProductVersion", "10.0.8")
+ .HasAnnotation("Relational:MaxIdentifierLength", 63);
+
+ NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("ApiKeyHash")
+ .HasMaxLength(128)
+ .IsUnicode(false)
+ .HasColumnType("character varying(128)");
+
+ b.Property("ApiKeyPrefix")
+ .HasMaxLength(8)
+ .IsUnicode(false)
+ .HasColumnType("character varying(8)");
+
+ b.Property("CpuCores")
+ .HasColumnType("integer");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("DeletedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("GpuType")
+ .IsRequired()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("character varying(20)");
+
+ b.Property("HasGpu")
+ .HasColumnType("boolean");
+
+ b.Property("Hostname")
+ .IsRequired()
+ .HasMaxLength(255)
+ .IsUnicode(false)
+ .HasColumnType("character varying(255)");
+
+ b.Property("IsDeleted")
+ .HasColumnType("boolean");
+
+ b.Property("LastHeartbeat")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("MemoryMb")
+ .HasColumnType("bigint");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(200)
+ .IsUnicode(false)
+ .HasColumnType("character varying(200)");
+
+ b.Property("PublicIp")
+ .HasMaxLength(45)
+ .IsUnicode(false)
+ .HasColumnType("character varying(45)");
+
+ b.Property("SiteId")
+ .HasColumnType("uuid");
+
+ b.Property("Status")
+ .IsRequired()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("character varying(20)");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("Version")
+ .IsRequired()
+ .HasMaxLength(50)
+ .IsUnicode(false)
+ .HasColumnType("character varying(50)");
+
+ b.HasKey("Id");
+
+ b.HasIndex("LastHeartbeat")
+ .HasFilter("\"status\" = 'Online'");
+
+ b.HasIndex("SiteId");
+
+ b.ToTable("agents", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("AgentId")
+ .HasColumnType("uuid")
+ .HasColumnName("agent_id");
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("created_at");
+
+ b.Property("Key")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("character varying(200)")
+ .HasColumnName("key");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("updated_at");
+
+ b.Property("Value")
+ .IsRequired()
+ .HasColumnType("text")
+ .HasColumnName("value");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AgentId", "Key")
+ .IsUnique();
+
+ b.ToTable("agent_settings", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("CreatedByUserId")
+ .HasColumnType("uuid");
+
+ b.Property("Enabled")
+ .HasColumnType("boolean");
+
+ b.Property("ExpiresAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("KeyHash")
+ .IsRequired()
+ .HasMaxLength(128)
+ .IsUnicode(false)
+ .HasColumnType("character varying(128)");
+
+ b.Property("KeyPrefix")
+ .IsRequired()
+ .HasMaxLength(8)
+ .IsUnicode(false)
+ .HasColumnType("character varying(8)");
+
+ b.Property("LastUsedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("SiteId")
+ .HasColumnType("uuid");
+
+ b.HasKey("Id");
+
+ b.HasIndex("KeyHash");
+
+ b.HasIndex("KeyPrefix");
+
+ b.HasIndex("SiteId");
+
+ b.ToTable("api_keys", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.AppRole", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("ConcurrencyStamp")
+ .IsConcurrencyToken()
+ .HasColumnType("text");
+
+ b.Property("Name")
+ .HasMaxLength(256)
+ .HasColumnType("character varying(256)");
+
+ b.Property("NormalizedName")
+ .HasMaxLength(256)
+ .HasColumnType("character varying(256)");
+
+ b.HasKey("Id");
+
+ b.HasIndex("NormalizedName")
+ .IsUnique()
+ .HasDatabaseName("RoleNameIndex");
+
+ b.ToTable("roles", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.AppSetting", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("AllowedValues")
+ .HasMaxLength(2000)
+ .HasColumnType("character varying(2000)")
+ .HasColumnName("allowed_values");
+
+ b.Property("Category")
+ .IsRequired()
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)")
+ .HasColumnName("category");
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("created_at");
+
+ b.Property("Description")
+ .HasMaxLength(500)
+ .HasColumnType("character varying(500)")
+ .HasColumnName("description");
+
+ b.Property("Key")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("character varying(200)")
+ .HasColumnName("key");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("timestamp with time zone")
+ .HasColumnName("updated_at");
+
+ b.Property("Value")
+ .IsRequired()
+ .HasColumnType("text")
+ .HasColumnName("value");
+
+ b.Property("ValueType")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)")
+ .HasColumnName("value_type");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Key")
+ .IsUnique();
+
+ b.ToTable("app_settings", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("AccessFailedCount")
+ .HasColumnType("integer");
+
+ b.Property("ConcurrencyStamp")
+ .IsConcurrencyToken()
+ .HasColumnType("text");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("DisplayName")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("character varying(200)");
+
+ b.Property("Email")
+ .HasMaxLength(256)
+ .HasColumnType("character varying(256)");
+
+ b.Property("EmailConfirmed")
+ .HasColumnType("boolean");
+
+ b.Property("Language")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(10)
+ .IsUnicode(false)
+ .HasColumnType("character varying(10)")
+ .HasDefaultValue("fr");
+
+ b.Property("LockoutEnabled")
+ .HasColumnType("boolean");
+
+ b.Property("LockoutEnd")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("MustChangePassword")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("boolean")
+ .HasDefaultValue(false);
+
+ b.Property("NormalizedEmail")
+ .HasMaxLength(256)
+ .HasColumnType("character varying(256)");
+
+ b.Property("NormalizedUserName")
+ .HasMaxLength(256)
+ .HasColumnType("character varying(256)");
+
+ b.Property("PasswordHash")
+ .HasColumnType("text");
+
+ b.Property("PhoneNumber")
+ .HasColumnType("text");
+
+ b.Property("PhoneNumberConfirmed")
+ .HasColumnType("boolean");
+
+ b.Property("SecurityStamp")
+ .HasColumnType("text");
+
+ b.Property("Theme")
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("character varying(20)")
+ .HasDefaultValue("Auto");
+
+ b.Property("TwoFactorEnabled")
+ .HasColumnType("boolean");
+
+ b.Property("UserName")
+ .HasMaxLength(256)
+ .HasColumnType("character varying(256)");
+
+ b.HasKey("Id");
+
+ b.HasIndex("NormalizedEmail")
+ .HasDatabaseName("EmailIndex");
+
+ b.HasIndex("NormalizedUserName")
+ .IsUnique()
+ .HasDatabaseName("UserNameIndex");
+
+ b.ToTable("users", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("Action")
+ .IsRequired()
+ .HasMaxLength(100)
+ .IsUnicode(false)
+ .HasColumnType("character varying(100)");
+
+ b.Property("IpAddress")
+ .HasMaxLength(45)
+ .IsUnicode(false)
+ .HasColumnType("character varying(45)");
+
+ b.Property("NewValue")
+ .HasColumnType("text");
+
+ b.Property("OldValue")
+ .HasColumnType("text");
+
+ b.Property("ResourceId")
+ .HasMaxLength(100)
+ .IsUnicode(false)
+ .HasColumnType("character varying(100)");
+
+ b.Property("ResourceType")
+ .IsRequired()
+ .HasMaxLength(100)
+ .IsUnicode(false)
+ .HasColumnType("character varying(100)");
+
+ b.Property("Timestamp")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("UserId")
+ .HasColumnType("uuid");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Timestamp")
+ .IsDescending();
+
+ b.HasIndex("UserId");
+
+ b.HasIndex("ResourceType", "ResourceId", "Timestamp")
+ .IsDescending(false, false, true);
+
+ b.ToTable("audit_logs", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("AgentId")
+ .HasColumnType("uuid");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("DeletedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("HasAudio")
+ .HasColumnType("boolean");
+
+ b.Property("HasMotionDetection")
+ .HasColumnType("boolean");
+
+ b.Property("HasPtz")
+ .HasColumnType("boolean");
+
+ b.Property("IsDeleted")
+ .HasColumnType("boolean");
+
+ b.Property("Manufacturer")
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)");
+
+ b.Property("Model")
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(200)
+ .IsUnicode(false)
+ .HasColumnType("character varying(200)");
+
+ b.Property("RtspUrl")
+ .HasMaxLength(1000)
+ .IsUnicode(false)
+ .HasColumnType("character varying(1000)");
+
+ b.Property("SiteId")
+ .HasColumnType("uuid");
+
+ b.Property("Status")
+ .IsRequired()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("character varying(20)");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AgentId");
+
+ b.HasIndex("SiteId");
+
+ b.ToTable("cameras", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b =>
+ {
+ b.Property("CameraId")
+ .HasColumnType("uuid");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("OnvifPassword")
+ .IsRequired()
+ .HasMaxLength(500)
+ .IsUnicode(false)
+ .HasColumnType("character varying(500)");
+
+ b.Property("OnvifUsername")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(100)
+ .IsUnicode(false)
+ .HasColumnType("character varying(100)")
+ .HasDefaultValue("admin");
+
+ b.Property("RtspPassword")
+ .IsRequired()
+ .HasMaxLength(500)
+ .IsUnicode(false)
+ .HasColumnType("character varying(500)");
+
+ b.Property("RtspUsername")
+ .IsRequired()
+ .HasMaxLength(100)
+ .IsUnicode(false)
+ .HasColumnType("character varying(100)");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.HasKey("CameraId");
+
+ b.ToTable("camera_credentials", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b =>
+ {
+ b.Property("CameraId")
+ .HasColumnType("uuid");
+
+ b.Property("ActiveIntervalMs")
+ .HasColumnType("integer");
+
+ b.Property("AnimalCooldownSec")
+ .HasColumnType("integer");
+
+ b.Property("DetectAnimal")
+ .HasColumnType("boolean");
+
+ b.Property("DetectMotion")
+ .HasColumnType("boolean");
+
+ b.Property("DetectPackage")
+ .HasColumnType("boolean");
+
+ b.Property("DetectPerson")
+ .HasColumnType("boolean");
+
+ b.Property("DetectVehicle")
+ .HasColumnType("boolean");
+
+ b.Property("FaceRecognition")
+ .HasColumnType("boolean");
+
+ b.Property("IdleIntervalMs")
+ .HasColumnType("integer");
+
+ b.Property("IoUThreshold")
+ .HasColumnType("double precision");
+
+ b.Property("LicensePlateRecognition")
+ .HasColumnType("boolean");
+
+ b.Property("MaxEventsPerMinute")
+ .HasColumnType("integer");
+
+ b.Property("MinConfidence")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("double precision")
+ .HasDefaultValue(0.40000000000000002);
+
+ b.Property("MotionIntervalMs")
+ .HasColumnType("integer");
+
+ b.Property("MotionThreshold")
+ .HasColumnType("double precision");
+
+ b.Property("PersonCooldownSec")
+ .HasColumnType("integer");
+
+ b.Property("RequireMotionForAI")
+ .HasColumnType("boolean");
+
+ b.Property("VehicleCooldownSec")
+ .HasColumnType("integer");
+
+ b.Property("YoloModel")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(50)
+ .IsUnicode(false)
+ .HasColumnType("character varying(50)")
+ .HasDefaultValue("yolov8n");
+
+ b.HasKey("CameraId");
+
+ b.ToTable("camera_detection_profiles", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.Site", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("Address")
+ .HasMaxLength(500)
+ .HasColumnType("character varying(500)");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("DeletedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("Enabled")
+ .HasColumnType("boolean");
+
+ b.Property("IsDeleted")
+ .HasColumnType("boolean");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("character varying(200)");
+
+ b.Property("RegistrationTokenHash")
+ .HasMaxLength(128)
+ .IsUnicode(false)
+ .HasColumnType("character varying(128)");
+
+ b.Property("Timezone")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(100)
+ .IsUnicode(false)
+ .HasColumnType("character varying(100)")
+ .HasDefaultValue("UTC");
+
+ b.Property("TokenExpiresAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.HasKey("Id");
+
+ b.HasIndex("IsDeleted")
+ .HasFilter("\"is_deleted\" = false");
+
+ b.HasIndex("Name");
+
+ b.ToTable("sites", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b =>
+ {
+ b.Property("UserId")
+ .HasColumnType("uuid");
+
+ b.Property("SiteId")
+ .HasColumnType("uuid");
+
+ b.HasKey("UserId", "SiteId");
+
+ b.HasIndex("SiteId");
+
+ b.ToTable("user_sites", (string)null);
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id"));
+
+ b.Property("ClaimType")
+ .HasColumnType("text");
+
+ b.Property("ClaimValue")
+ .HasColumnType("text");
+
+ b.Property("RoleId")
+ .HasColumnType("uuid");
+
+ b.HasKey("Id");
+
+ b.HasIndex("RoleId");
+
+ b.ToTable("role_claims", (string)null);
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id"));
+
+ b.Property("ClaimType")
+ .HasColumnType("text");
+
+ b.Property("ClaimValue")
+ .HasColumnType("text");
+
+ b.Property("UserId")
+ .HasColumnType("uuid");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("user_claims", (string)null);
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b =>
+ {
+ b.Property("LoginProvider")
+ .HasColumnType("text");
+
+ b.Property("ProviderKey")
+ .HasColumnType("text");
+
+ b.Property("ProviderDisplayName")
+ .HasColumnType("text");
+
+ b.Property("UserId")
+ .HasColumnType("uuid");
+
+ b.HasKey("LoginProvider", "ProviderKey");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("user_logins", (string)null);
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b =>
+ {
+ b.Property