diff --git a/src/Heimdall.Agent/AgentOptions.cs b/src/Heimdall.Agent/AgentOptions.cs
index 2493dd4..524f059 100644
--- a/src/Heimdall.Agent/AgentOptions.cs
+++ b/src/Heimdall.Agent/AgentOptions.cs
@@ -35,6 +35,13 @@ public sealed class AgentOptions
[Range(1, 20)]
public int RegistrationMaxRetries { get; init; } = 5;
+ /// Interval between automatic camera network scans in seconds (default: 900 = 15 min).
+ [Range(60, 86400)]
+ public int DiscoveryIntervalSeconds { get; init; } = 900;
+
+ /// Enable automatic camera discovery on the local network (default: true).
+ public bool DiscoveryEnabled { get; init; } = true;
+
/// Agent software version reported to Central.
public string Version { get; init; } = "1.0.0";
}
diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs
index 1dc582b..68f5a79 100644
--- a/src/Heimdall.Agent/Program.cs
+++ b/src/Heimdall.Agent/Program.cs
@@ -61,8 +61,12 @@ builder.Services.AddSingleton(sp =>
});
builder.Services.AddSingleton();
+builder.Services.AddSingleton();
+builder.Services.AddSingleton();
+builder.Services.AddSingleton();
builder.Services.AddHostedService();
builder.Services.AddHostedService();
+builder.Services.AddHostedService();
// Health checks — used by Docker HEALTHCHECK
builder.Services.AddHealthChecks()
diff --git a/src/Heimdall.Agent/Services/AgentCredentialStore.cs b/src/Heimdall.Agent/Services/AgentCredentialStore.cs
new file mode 100644
index 0000000..124b01a
--- /dev/null
+++ b/src/Heimdall.Agent/Services/AgentCredentialStore.cs
@@ -0,0 +1,20 @@
+using Heimdall.Application.DTOs;
+
+namespace Heimdall.Agent.Services;
+
+///
+/// In-memory holder for the site's camera credential pool, received from the
+/// Central inside the encrypted agent config envelope and decrypted locally.
+/// Shared between (writes) and
+/// /
+/// (reads). Never persisted to disk.
+///
+public sealed class AgentCredentialStore
+{
+ private IReadOnlyList _pool = [];
+
+ public IReadOnlyList Pool => Volatile.Read(ref _pool);
+
+ public void Set(IReadOnlyList pool)
+ => Interlocked.Exchange(ref _pool, pool ?? []);
+}
diff --git a/src/Heimdall.Agent/Services/AgentDiscoveryService.cs b/src/Heimdall.Agent/Services/AgentDiscoveryService.cs
new file mode 100644
index 0000000..7db9720
--- /dev/null
+++ b/src/Heimdall.Agent/Services/AgentDiscoveryService.cs
@@ -0,0 +1,132 @@
+using System.Net.Http.Json;
+using Heimdall.Application.DTOs;
+using Microsoft.Extensions.Options;
+
+namespace Heimdall.Agent.Services;
+
+///
+/// Periodically scans the agent's local network for cameras and posts the
+/// results to the Central (POST /api/agents/{id}/discovery). The agent owns
+/// the authenticated ONVIF enrichment: it receives the site's credential pool
+/// through the encrypted agent config (see )
+/// and the scanner identifies protected cameras (ONVIF manufacturer/model)
+/// before they are posted. The Central only persists the devices.
+///
+/// Scan triggers: immediately after registration, then every
+/// seconds, and on demand
+/// via (pushed by Central over SignalR).
+///
+public sealed class AgentDiscoveryService : BackgroundService
+{
+ private readonly AgentState _state;
+ private readonly AgentOptions _options;
+ private readonly NetworkCameraScanner _scanner;
+ private readonly DiscoveryScanTrigger _trigger;
+ private readonly AgentCredentialStore _credentialStore;
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly ILogger _logger;
+
+ public AgentDiscoveryService(
+ AgentState state,
+ IOptions options,
+ NetworkCameraScanner scanner,
+ DiscoveryScanTrigger trigger,
+ AgentCredentialStore credentialStore,
+ IHttpClientFactory httpClientFactory,
+ ILogger logger)
+ {
+ _state = state;
+ _options = options.Value;
+ _scanner = scanner;
+ _trigger = trigger;
+ _credentialStore = credentialStore;
+ _httpClientFactory = httpClientFactory;
+ _logger = logger;
+ }
+
+ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+ {
+ // Wait until the agent is registered (has an AgentId + API key).
+ while (_state.AgentId == Guid.Empty && !stoppingToken.IsCancellationRequested)
+ await Task.Delay(1000, stoppingToken).ConfigureAwait(false);
+
+ if (stoppingToken.IsCancellationRequested)
+ return;
+
+ _logger.LogInformation(
+ "Camera discovery service started (interval={Interval}s, enabled={Enabled})",
+ _options.DiscoveryIntervalSeconds, _options.DiscoveryEnabled);
+
+ var interval = TimeSpan.FromSeconds(
+ _options.DiscoveryIntervalSeconds > 0 ? _options.DiscoveryIntervalSeconds : 900);
+
+ // Initial scan shortly after registration.
+ await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken).ConfigureAwait(false);
+ await ScanAndSubmitAsync(stoppingToken).ConfigureAwait(false);
+
+ while (!stoppingToken.IsCancellationRequested)
+ {
+ try
+ {
+ var delayTask = Task.Delay(interval, stoppingToken);
+ var triggerTask = _trigger.WaitAsync(stoppingToken).AsTask();
+ var completed = await Task.WhenAny(delayTask, triggerTask).ConfigureAwait(false);
+
+ if (completed == triggerTask)
+ _logger.LogInformation("Camera discovery: scan requested by Central");
+
+ await ScanAndSubmitAsync(stoppingToken).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
+ {
+ break;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning(ex, "Camera discovery cycle failed (will retry)");
+ await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken).ConfigureAwait(false);
+ }
+ }
+ }
+
+ private async Task ScanAndSubmitAsync(CancellationToken ct)
+ {
+ if (!_options.DiscoveryEnabled)
+ return;
+
+ try
+ {
+ var pool = _credentialStore.Pool;
+ var devices = await _scanner.ScanAsync(ct, pool).ConfigureAwait(false);
+
+ using var client = _httpClientFactory.CreateClient("Central");
+ client.DefaultRequestHeaders.Remove("X-API-Key");
+ client.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey);
+
+ var response = await client.PostAsJsonAsync(
+ $"api/agents/{_state.AgentId}/discovery", devices, ct).ConfigureAwait(false);
+
+ if (response.IsSuccessStatusCode)
+ {
+ var result = await response.Content.ReadFromJsonAsync(ct).ConfigureAwait(false);
+ _logger.LogInformation(
+ "Camera discovery submitted: {Count} device(s) — {New} new, {Updated} updated",
+ devices.Count, result?.New ?? 0, result?.Updated ?? 0);
+ }
+ else
+ {
+ _logger.LogWarning(
+ "Camera discovery submission failed: {StatusCode} ({Reason})",
+ response.StatusCode, response.ReasonPhrase);
+ }
+ }
+ catch (OperationCanceledException) when (ct.IsCancellationRequested)
+ {
+ throw;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning(ex, "Camera discovery scan/submit error (will retry)");
+ }
+ }
+}
diff --git a/src/Heimdall.Agent/Services/ConfigReceiverService.cs b/src/Heimdall.Agent/Services/ConfigReceiverService.cs
index 2296077..90abb7f 100644
--- a/src/Heimdall.Agent/Services/ConfigReceiverService.cs
+++ b/src/Heimdall.Agent/Services/ConfigReceiverService.cs
@@ -1,3 +1,6 @@
+using System.Net.Http.Json;
+using Heimdall.Application.DTOs;
+using Heimdall.Application.Security;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.Options;
@@ -14,18 +17,24 @@ public sealed class ConfigReceiverService : BackgroundService
private readonly AgentOptions _options;
private readonly ILogger _logger;
private readonly IHttpClientFactory _httpClientFactory;
+ private readonly DiscoveryScanTrigger _scanTrigger;
+ private readonly AgentCredentialStore _credentialStore;
private HubConnection? _connection;
public ConfigReceiverService(
AgentState state,
IOptions options,
ILogger logger,
- IHttpClientFactory httpClientFactory)
+ IHttpClientFactory httpClientFactory,
+ DiscoveryScanTrigger scanTrigger,
+ AgentCredentialStore credentialStore)
{
_state = state;
_options = options.Value;
_logger = logger;
_httpClientFactory = httpClientFactory;
+ _scanTrigger = scanTrigger;
+ _credentialStore = credentialStore;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
@@ -140,12 +149,45 @@ public sealed class ConfigReceiverService : BackgroundService
case "log.level":
_logger.LogInformation("Log level update received: {Level} (applied on next restart)", value);
break;
+ case "discovery.scan.requested":
+ _logger.LogInformation("Camera discovery scan requested by Central");
+ _scanTrigger.Trigger();
+ break;
+ case "discovery.credentials":
+ ApplyCredentialPool(value);
+ break;
default:
_logger.LogDebug("Unknown setting {Key} = {Value} (stored for future use)", key, value);
break;
}
}
+ ///
+ /// Decrypt the site's camera credential pool shipped by the Central and
+ /// store it for the discovery scanner. Uses the agent's plaintext API key
+ /// (only the agent can open the envelope).
+ ///
+ private void ApplyCredentialPool(string envelope)
+ {
+ try
+ {
+ if (string.IsNullOrEmpty(_state.ApiKey))
+ {
+ _logger.LogWarning("Credential pool received but no API key available — cannot decrypt");
+ return;
+ }
+
+ var key = AgentCredentialEnvelope.DeriveKeyFromApiKey(_state.ApiKey);
+ var pool = AgentCredentialEnvelope.Decrypt(envelope, key);
+ _credentialStore.Set(pool);
+ _logger.LogInformation("Camera credential pool updated: {Count} pair(s)", pool.Count);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning(ex, "Failed to decrypt camera credential pool (kept previous pool)");
+ }
+ }
+
private async Task FetchFullConfigAsync(CancellationToken ct)
{
try
@@ -159,10 +201,23 @@ public sealed class ConfigReceiverService : BackgroundService
var url = $"{_options.CentralUrl.TrimEnd('/')}/api/settings/agent/{_state.AgentId}";
var response = await http.GetAsync(url, ct);
- if (response.IsSuccessStatusCode)
+ if (!response.IsSuccessStatusCode)
{
- _logger.LogInformation("Full configuration fetched successfully");
+ _logger.LogWarning("Failed to fetch full configuration: {StatusCode}", response.StatusCode);
+ return;
}
+
+ var config = await response.Content.ReadFromJsonAsync>(ct);
+ if (config is null)
+ {
+ _logger.LogWarning("Full configuration response was empty");
+ return;
+ }
+
+ _logger.LogInformation("Full configuration fetched successfully ({Count} setting(s))", config.Count);
+
+ if (config.TryGetValue("discovery.credentials", out var envelope))
+ ApplyCredentialPool(envelope);
}
catch (Exception ex)
{
diff --git a/src/Heimdall.Agent/Services/DiscoveryScanTrigger.cs b/src/Heimdall.Agent/Services/DiscoveryScanTrigger.cs
new file mode 100644
index 0000000..25bbb64
--- /dev/null
+++ b/src/Heimdall.Agent/Services/DiscoveryScanTrigger.cs
@@ -0,0 +1,20 @@
+using System.Threading.Channels;
+
+namespace Heimdall.Agent.Services;
+
+///
+/// Shared trigger allowing ConfigReceiverService (SignalR "scan now" push)
+/// to wake the AgentDiscoveryService for an immediate network scan.
+///
+public sealed class DiscoveryScanTrigger
+{
+ private readonly Channel _channel = Channel.CreateBounded(
+ new BoundedChannelOptions(4) { FullMode = BoundedChannelFullMode.DropWrite });
+
+ public void Trigger()
+ {
+ _channel.Writer.TryWrite(true);
+ }
+
+ public ValueTask WaitAsync(CancellationToken ct) => _channel.Reader.ReadAsync(ct);
+}
diff --git a/src/Heimdall.Agent/Services/NetworkCameraScanner.cs b/src/Heimdall.Agent/Services/NetworkCameraScanner.cs
new file mode 100644
index 0000000..d02ac59
--- /dev/null
+++ b/src/Heimdall.Agent/Services/NetworkCameraScanner.cs
@@ -0,0 +1,546 @@
+using System.Collections.Concurrent;
+using System.Globalization;
+using System.Net;
+using System.Net.NetworkInformation;
+using System.Net.Sockets;
+using System.Security.Cryptography;
+using System.Text;
+using System.Xml.Linq;
+using Heimdall.Application.DTOs;
+using Microsoft.Extensions.Logging;
+
+namespace Heimdall.Agent.Services;
+
+///
+/// Lightweight local-network camera scanner used by the agent.
+/// The agent lives on the camera network (the Central usually does not), so it
+/// probes its own subnet: TCP port scan for common camera ports, an HTTP
+/// header probe, ONVIF WS-Discovery (unicast), and an ARP table lookup for the
+/// MAC address. When the site's credential pool is available (shipped by the
+/// Central in the agent config, encrypted), the scanner performs the
+/// authenticated ONVIF GetDeviceInformation calls itself — protected
+/// cameras that refuse anonymous probing are identified (manufacturer, model)
+/// using each credential pair. Raw+enriched results are posted to the Central
+/// (POST /api/agents/{id}/discovery), which only persists them.
+///
+public sealed class NetworkCameraScanner
+{
+ private static readonly int[] CameraPorts = [80, 443, 554, 8554, 3702, 8899, 37777];
+ private static readonly TimeSpan PortTimeout = TimeSpan.FromMilliseconds(250);
+ private static readonly TimeSpan HttpTimeout = TimeSpan.FromSeconds(2);
+ private static readonly TimeSpan OnvifUdpTimeout = TimeSpan.FromMilliseconds(500);
+
+ // ReSharper disable once InconsistentNaming
+ private static readonly XNamespace SoapNs = "http://www.w3.org/2003/05/soap-envelope";
+ // ReSharper disable once InconsistentNaming
+ private static readonly XNamespace WsdNs = "http://schemas.xmlsoap.org/ws/2005/04/discovery";
+ // ReSharper disable once InconsistentNaming
+ private static readonly XNamespace WsaNs = "http://schemas.xmlsoap.org/ws/2004/08/addressing";
+ // ReSharper disable once InconsistentNaming
+ private static readonly XNamespace TdnNs = "http://www.onvif.org/ver10/network/wsdl";
+ // ReSharper disable once InconsistentNaming
+ private static readonly XNamespace TdsNs = "http://www.onvif.org/ver10/device/wsdl";
+ // ReSharper disable once InconsistentNaming
+ private static readonly XNamespace WsseNs = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
+
+ private readonly ILogger _logger;
+ private readonly string? _localIp;
+
+ public NetworkCameraScanner(ILogger logger)
+ {
+ _logger = logger;
+ _localIp = GetLocalIpv4();
+ }
+
+ ///
+ /// Scan the local subnet for camera-like devices. Returns an empty list
+ /// when the local network cannot be determined. When
+ /// is provided, ONVIF device information is fetched with authentication
+ /// (each pair is tried, PasswordDigest then PasswordText) so protected
+ /// cameras are identified with their ONVIF manufacturer/model.
+ ///
+ public async Task> ScanAsync(
+ CancellationToken ct, IReadOnlyList? credentialPool = null)
+ {
+ var (subnetCidr, localIp) = GetLocalSubnetCidr();
+ if (subnetCidr is null)
+ {
+ _logger.LogWarning("Camera discovery: unable to determine local subnet, skipping scan");
+ return [];
+ }
+
+ var ips = ExpandSubnet(subnetCidr);
+ _logger.LogInformation("Camera discovery: scanning {Subnet} ({Count} hosts, {Pool} credential pair(s))",
+ subnetCidr, ips.Count, credentialPool?.Count ?? 0);
+
+ var results = new ConcurrentBag();
+ using var throttler = new SemaphoreSlim(40);
+
+ var tasks = ips.Select(async ip =>
+ {
+ if (ct.IsCancellationRequested) return;
+ if (ip == localIp) return;
+
+ await throttler.WaitAsync(ct).ConfigureAwait(false);
+ try
+ {
+ var device = await ProbeHostAsync(ip, credentialPool, ct).ConfigureAwait(false);
+ if (device is not null)
+ results.Add(device);
+ }
+ catch (OperationCanceledException) when (ct.IsCancellationRequested)
+ {
+ // stop probing
+ }
+ catch (Exception ex)
+ {
+ _logger.LogTrace(ex, "Probe error for {Ip}", ip);
+ }
+ finally
+ {
+ throttler.Release();
+ }
+ });
+
+ await Task.WhenAll(tasks).ConfigureAwait(false);
+ _logger.LogInformation("Camera discovery: {Found} candidate device(s) on {Subnet}", results.Count, subnetCidr);
+
+ return results.ToList();
+ }
+
+ private async Task ProbeHostAsync(
+ string ip, IReadOnlyList? credentialPool, CancellationToken ct)
+ {
+ var openPorts = await ScanPortsAsync(ip, ct).ConfigureAwait(false);
+ if (openPorts.Count == 0)
+ return null;
+
+ HttpProbe? http = null;
+ if (openPorts.Contains(80) || openPorts.Contains(443))
+ {
+ var webPort = openPorts.Contains(80) ? 80 : 443;
+ http = await ProbeHttpAsync(ip, webPort, ct).ConfigureAwait(false);
+ }
+
+ OnvifProbe? onvif = null;
+ if (openPorts.Contains(3702))
+ onvif = await ProbeOnvifAsync(ip, 3702, credentialPool, ct).ConfigureAwait(false);
+
+ var mac = GetArpMac(ip);
+
+ return new AgentDiscoveredDevice(
+ Ip: ip,
+ IsReachable: true,
+ OpenPorts: [.. openPorts],
+ MacAddress: mac,
+ Vendor: null,
+ Hostname: null,
+ HttpServerHeader: http?.ServerHeader,
+ HttpStatusCode: http?.StatusCode,
+ HttpPort: http?.Port,
+ OnvifDeviceServiceUrl: onvif?.DeviceServiceUrl,
+ OnvifName: onvif?.Name,
+ OnvifHardware: onvif?.Hardware,
+ OnvifPort: onvif is not null ? 3702 : null,
+ HomeKitName: null,
+ HomeKitDeviceId: null,
+ HomeKitModel: null,
+ CredentialLabel: onvif?.CredentialLabel);
+ }
+
+ private static async Task> ScanPortsAsync(string ip, CancellationToken ct)
+ {
+ var open = new ConcurrentBag();
+ var tasks = CameraPorts.Select(async port =>
+ {
+ using var client = new TcpClient();
+ var connectTask = client.ConnectAsync(IPAddress.Parse(ip), port, ct).AsTask();
+ var completed = await Task.WhenAny(connectTask, Task.Delay(PortTimeout, ct)).ConfigureAwait(false);
+ if (completed == connectTask && client.Connected)
+ open.Add(port);
+ client.Close();
+ });
+
+ await Task.WhenAll(tasks).ConfigureAwait(false);
+ return [.. open.Order()];
+ }
+
+ private async Task ProbeHttpAsync(string ip, int port, CancellationToken ct)
+ {
+ try
+ {
+ using var handler = new HttpClientHandler
+ {
+ AllowAutoRedirect = false,
+ ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator,
+ };
+ using var client = new HttpClient(handler) { Timeout = HttpTimeout };
+ using var request = new HttpRequestMessage(HttpMethod.Get, $"http://{ip}:{port}/");
+ request.Headers.UserAgent.ParseAdd("HeimdallAgent/1.0");
+ using var response = await client.SendAsync(request, ct).ConfigureAwait(false);
+
+ var serverHeader = response.Headers.TryGetValues("Server", out var values)
+ ? string.Join(",", values)
+ : null;
+ return new HttpProbe(port, (int)response.StatusCode, serverHeader);
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ _logger.LogTrace(ex, "HTTP probe failed for {Ip}:{Port}", ip, port);
+ return null;
+ }
+ }
+
+ private async Task ProbeOnvifAsync(
+ string ip, int port, IReadOnlyList? credentialPool, CancellationToken ct)
+ {
+ try
+ {
+ using var udp = new UdpClient();
+ udp.Client.ReceiveTimeout = (int)OnvifUdpTimeout.TotalMilliseconds;
+ udp.Connect(ip, port);
+
+ var messageId = Guid.NewGuid().ToString();
+ var probe = $@"
+
+
+ {WsdNs.NamespaceName}/Probe
+ uuid:{messageId}
+ urn:schemas-xmlsoap-org:ws:2005:04:discovery
+
+
+
+ tdn:NetworkVideoTransmitter
+
+
+";
+
+ await udp.SendAsync(Encoding.UTF8.GetBytes(probe), ct).ConfigureAwait(false);
+ var result = await udp.ReceiveAsync(ct).ConfigureAwait(false);
+ var xml = Encoding.UTF8.GetString(result.Buffer);
+
+ var doc = XDocument.Parse(xml);
+ var xaddrs = doc.Descendants(XName.Get("XAddrs", WsdNs.NamespaceName))
+ .SelectMany(e => e.Value.Split(' ', StringSplitOptions.RemoveEmptyEntries))
+ .ToList();
+ if (xaddrs.Count == 0)
+ return null;
+
+ var deviceServiceUrl = xaddrs[0];
+ var detail = await GetDeviceInformationWithCredentialsAsync(deviceServiceUrl, credentialPool, ct).ConfigureAwait(false);
+
+ return new OnvifProbe(deviceServiceUrl, detail?.Manufacturer, detail?.Model, detail?.CredentialLabel);
+ }
+ catch (SocketException ex) when (ex.SocketErrorCode is SocketError.TimedOut or SocketError.ConnectionRefused)
+ {
+ return null;
+ }
+ catch (OperationCanceledException) when (ct.IsCancellationRequested)
+ {
+ throw;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogTrace(ex, "ONVIF probe failed for {Ip}:{Port}", ip, port);
+ return null;
+ }
+ }
+
+ ///
+ /// Fetch ONVIF device information, trying the site credential pool so that
+ /// protected cameras respond. Order: anonymous first (open cameras), then
+ /// each pair of the pool (PasswordDigest, then PasswordText for laxer
+ /// WS-Security implementations). Returns null when nothing works.
+ ///
+ private async Task GetDeviceInformationWithCredentialsAsync(
+ string deviceServiceUrl, IReadOnlyList? credentialPool, CancellationToken ct)
+ {
+ // 1. Anonymous (cameras without auth or with default-open ONVIF).
+ var anonymous = await GetDeviceInformationAsync(deviceServiceUrl, null, null, null, ct).ConfigureAwait(false);
+ if (anonymous is not null)
+ return anonymous;
+
+ // 2. Credential pool, if provided by the Central.
+ if (credentialPool is not null)
+ {
+ foreach (var credential in credentialPool)
+ {
+ var digest = await GetDeviceInformationAsync(
+ deviceServiceUrl, credential.Username, credential.Password, "PasswordDigest", ct).ConfigureAwait(false);
+ if (digest is not null)
+ {
+ _logger.LogInformation(
+ "ONVIF auth succeeded with credential '{Label}' for {Url}", credential.Label, deviceServiceUrl);
+ return digest with { CredentialLabel = credential.Label };
+ }
+
+ var text = await GetDeviceInformationAsync(
+ deviceServiceUrl, credential.Username, credential.Password, "PasswordText", ct).ConfigureAwait(false);
+ if (text is not null)
+ {
+ _logger.LogInformation(
+ "ONVIF auth (PasswordText) succeeded with credential '{Label}' for {Url}", credential.Label, deviceServiceUrl);
+ return text with { CredentialLabel = credential.Label };
+ }
+ }
+ }
+
+ return null;
+ }
+
+ private async Task GetDeviceInformationAsync(
+ string deviceServiceUrl, string? username, string? password, string? passwordType, CancellationToken ct)
+ {
+ try
+ {
+ using var client = new HttpClient { Timeout = HttpTimeout };
+ var soap = BuildSoapEnvelope(username, password, passwordType);
+
+ using var content = new StringContent(soap, Encoding.UTF8, "application/soap+xml");
+ using var response = await client.PostAsync(deviceServiceUrl, content, ct).ConfigureAwait(false);
+ if (!response.IsSuccessStatusCode)
+ return null;
+
+ var responseXml = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
+ var doc = XDocument.Parse(responseXml);
+ var info = doc.Root?.Element(SoapNs + "Body")?.Element(XName.Get("GetDeviceInformationResponse", TdsNs.NamespaceName));
+ if (info is null)
+ return null;
+
+ return new OnvifDetail(
+ info.Element(XName.Get("Manufacturer", TdsNs.NamespaceName))?.Value,
+ info.Element(XName.Get("Model", TdsNs.NamespaceName))?.Value);
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ _logger.LogTrace(ex, "GetDeviceInformation failed for {Url}", deviceServiceUrl);
+ return null;
+ }
+ }
+
+ ///
+ /// Build the GetDeviceInformation SOAP envelope, adding a WS-Security
+ /// UsernameToken when credentials are provided (PasswordDigest or
+ /// PasswordText, matching ONVIF interop requirements).
+ ///
+ private static string BuildSoapEnvelope(string? username, string? password, string? passwordType)
+ {
+ var securityHeader = string.Empty;
+ if (username is not null && passwordType is not null)
+ {
+ if (passwordType == "PasswordDigest")
+ {
+ var nonce = new byte[16];
+ RandomNumberGenerator.Fill(nonce);
+ var created = DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture);
+ // ONVIF WS-Security PasswordDigest is defined by the standard to use SHA1
+ // (digest = Base64(SHA1(nonce + created + password))). Required for
+ // interoperability with ONVIF cameras — not used for application security.
+#pragma warning disable CA5350 // Do Not Use Weak Cryptographic Algorithms
+ var digest = SHA1.HashData([.. nonce, .. Encoding.UTF8.GetBytes(created + password)]);
+#pragma warning restore CA5350
+ securityHeader = $@"
+
+
+
+ {username}
+ {Convert.ToBase64String(digest)}
+ {Convert.ToBase64String(nonce)}
+ {created}
+
+
+ ";
+ }
+ else
+ {
+ securityHeader = $@"
+
+
+
+ {username}
+ {password}
+
+
+ ";
+ }
+ }
+
+ return $@"
+{securityHeader}
+
+
+
+";
+ }
+
+ // ─── Network helpers ────────────────────────────────────────────────
+
+ private static string? GetLocalIpv4()
+ {
+ foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
+ {
+ if (ni.OperationalStatus != OperationalStatus.Up)
+ continue;
+ foreach (var addr in ni.GetIPProperties().UnicastAddresses)
+ {
+ if (IsCandidateNetwork(addr.Address))
+ return addr.Address.ToString();
+ }
+ }
+ return null;
+ }
+
+ ///
+ /// True for a routable private IPv4 that is a plausible camera LAN.
+ /// Excludes loopback and common virtualisation/docker ranges
+ /// (172.16.0.0/12, 100.64.0.0/10) so the scanner targets the real LAN.
+ ///
+ private static bool IsCandidateNetwork(IPAddress address)
+ {
+ if (address.AddressFamily != AddressFamily.InterNetwork || IPAddress.IsLoopback(address))
+ return false;
+
+ var b = address.GetAddressBytes();
+ if (b[0] == 172 && b[1] is >= 16 and <= 31)
+ return false; // docker / private virtualisation
+ if (b[0] == 100 && b[1] is >= 64 and <= 127)
+ return false; // CGNAT
+ return true;
+ }
+
+ /// Return the local subnet as CIDR (e.g. 192.168.1.0/24) plus the local IP.
+ private (string? Cidr, string? LocalIp) GetLocalSubnetCidr()
+ {
+ foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
+ {
+ if (ni.OperationalStatus != OperationalStatus.Up)
+ continue;
+
+ foreach (var addr in ni.GetIPProperties().UnicastAddresses)
+ {
+ if (!IsCandidateNetwork(addr.Address))
+ continue;
+
+ var mask = addr.IPv4Mask;
+ if (mask is null)
+ continue;
+
+ var prefix = CountPrefixBits(mask.GetAddressBytes());
+ var network = NetworkAddress(addr.Address.GetAddressBytes(), mask.GetAddressBytes());
+ var cidr = $"{new IPAddress(network)}/{prefix}";
+ _logger.LogDebug("Local subnet detected: {Cidr} (interface {Interface})", cidr, ni.Name);
+ return (cidr, addr.Address.ToString());
+ }
+ }
+ return (null, null);
+ }
+
+ private static int CountPrefixBits(byte[] mask)
+ {
+ var count = 0;
+ foreach (var b in mask)
+ {
+ for (var i = 7; i >= 0; i--)
+ {
+ if ((b & (1 << i)) == 0)
+ return count;
+ count++;
+ }
+ }
+ return count;
+ }
+
+ private static byte[] NetworkAddress(byte[] ip, byte[] mask)
+ {
+ var network = new byte[4];
+ for (var i = 0; i < 4; i++)
+ network[i] = (byte)(ip[i] & mask[i]);
+ return network;
+ }
+
+ /// Expand a CIDR to host IPs (skipping network/broadcast, capped at 65 536).
+ internal static List ExpandSubnet(string subnetCidr)
+ {
+ var parts = subnetCidr.Split('/');
+ if (parts.Length != 2)
+ return [];
+ if (!IPAddress.TryParse(parts[0], out var ip))
+ return [];
+ if (!int.TryParse(parts[1], out var prefixLength) || prefixLength is < 0 or > 32)
+ return [];
+
+ var ipBytes = ip.GetAddressBytes();
+ if (BitConverter.IsLittleEndian)
+ Array.Reverse(ipBytes);
+ var uintIp = BitConverter.ToUInt32(ipBytes, 0);
+
+ uint mask;
+ long hostCount;
+ int startOffset;
+
+ if (prefixLength >= 32)
+ {
+ mask = uint.MaxValue;
+ hostCount = 1;
+ startOffset = 0;
+ }
+ else if (prefixLength == 31)
+ {
+ mask = uint.MaxValue << 1;
+ hostCount = 2;
+ startOffset = 0;
+ }
+ else
+ {
+ mask = uint.MaxValue << (32 - prefixLength);
+ hostCount = (1L << (32 - prefixLength)) - 2;
+ startOffset = 1;
+ }
+
+ if (hostCount < 0)
+ hostCount = 0;
+ if (hostCount > 65536)
+ hostCount = 65536;
+
+ var network = uintIp & mask;
+ var ips = new List((int)hostCount);
+ for (var i = 0; i < hostCount; i++)
+ {
+ var hostIp = network + (uint)(i + startOffset);
+ var bytes = BitConverter.GetBytes(hostIp);
+ if (BitConverter.IsLittleEndian)
+ Array.Reverse(bytes);
+ ips.Add(new IPAddress(bytes).ToString());
+ }
+
+ return ips;
+ }
+
+ /// Read the ARP table (/proc/net/arp) to resolve an IP's MAC address.
+ private static string? GetArpMac(string ip)
+ {
+ try
+ {
+ var lines = File.ReadAllLines("/proc/net/arp");
+ foreach (var line in lines.Skip(1))
+ {
+ var fields = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
+ if (fields.Length >= 4 && fields[0] == ip && fields[3] != "00:00:00:00:00:00")
+ return fields[3];
+ }
+ }
+ catch (Exception)
+ {
+ // ARP table unavailable (non-Linux or restricted container) — best effort.
+ }
+ return null;
+ }
+
+ private sealed record HttpProbe(int Port, int StatusCode, string? ServerHeader);
+ private sealed record OnvifProbe(string DeviceServiceUrl, string? Name, string? Hardware, string? CredentialLabel = null);
+ private sealed record OnvifDetail(string? Manufacturer, string? Model, string? CredentialLabel = null);
+}
diff --git a/src/Heimdall.Application/AgentDiscovery/Commands/SubmitAgentDiscovery/SubmitAgentDiscoveryCommand.cs b/src/Heimdall.Application/AgentDiscovery/Commands/SubmitAgentDiscovery/SubmitAgentDiscoveryCommand.cs
new file mode 100644
index 0000000..0281294
--- /dev/null
+++ b/src/Heimdall.Application/AgentDiscovery/Commands/SubmitAgentDiscovery/SubmitAgentDiscoveryCommand.cs
@@ -0,0 +1,22 @@
+using Heimdall.Application.Common;
+using Heimdall.Application.DTOs;
+using Heimdall.Application.Services;
+using MediatR;
+
+namespace Heimdall.Application.AgentDiscovery.Commands.SubmitAgentDiscovery;
+
+public record SubmitAgentDiscoveryCommand(
+ Guid AgentId,
+ IReadOnlyList Devices) : IRequest>;
+
+public class SubmitAgentDiscoveryHandler : IRequestHandler>
+{
+ private readonly ICameraDiscoveryService _discovery;
+
+ public SubmitAgentDiscoveryHandler(ICameraDiscoveryService discovery) => _discovery = discovery;
+
+ public async Task> Handle(
+ SubmitAgentDiscoveryCommand request, CancellationToken cancellationToken)
+ => await _discovery.SubmitAgentDiscoveriesAsync(request.AgentId, request.Devices, cancellationToken)
+ .ConfigureAwait(false);
+}
diff --git a/src/Heimdall.Application/Common/IApplicationDbContext.cs b/src/Heimdall.Application/Common/IApplicationDbContext.cs
index 0fe8416..27ab50f 100644
--- a/src/Heimdall.Application/Common/IApplicationDbContext.cs
+++ b/src/Heimdall.Application/Common/IApplicationDbContext.cs
@@ -28,6 +28,7 @@ public interface IApplicationDbContext
DbSet Persons { get; }
DbSet RevokedRefreshTokens { get; }
DbSet Sites { get; }
+ DbSet SiteCredentials { get; }
DbSet UserGroups { get; }
DbSet UserSites { get; }
Task SaveChangesAsync(CancellationToken cancellationToken);
diff --git a/src/Heimdall.Application/DTOs/SiteCredentialDto.cs b/src/Heimdall.Application/DTOs/SiteCredentialDto.cs
new file mode 100644
index 0000000..ede7d4a
--- /dev/null
+++ b/src/Heimdall.Application/DTOs/SiteCredentialDto.cs
@@ -0,0 +1,98 @@
+namespace Heimdall.Application.DTOs;
+
+// ────────────────────────────────────────────────────────────────────
+// Site credentials (pool of login/password pairs for camera discovery)
+// ────────────────────────────────────────────────────────────────────
+
+/// Credential pair declared for a site. Password is write-only: never returned by the API.
+public record SiteCredentialResponse(
+ Guid Id,
+ Guid SiteId,
+ string Label,
+ string Username,
+ DateTime CreatedAt,
+ DateTime? LastUsedAt);
+
+/// Add a credential pair to a site.
+public record AddSiteCredentialRequest(
+ string Label,
+ string Username,
+ string Password);
+
+///
+/// A credential pair shipped inside the agent config envelope. The password is
+/// only ever present inside the encrypted envelope — never in plain settings.
+///
+public record AgentCameraCredential(
+ string Label,
+ string Username,
+ string Password);
+
+// ────────────────────────────────────────────────────────────────────
+// Agent-submitted discovery results
+// ────────────────────────────────────────────────────────────────────
+
+///
+/// A single device detected by an agent's network scan. The agent performs
+/// the probes (ports, HTTP header, ONVIF WS-Discovery with the site's
+/// credential pool, ARP) and reports devices already identified — ONVIF
+/// manufacturer/model are filled in by the agent when authentication with a
+/// pool credential succeeded. The Central only persists the results.
+///
+public record AgentDiscoveredDevice(
+ string Ip,
+ bool IsReachable,
+ int[] OpenPorts,
+ string? MacAddress,
+ string? Vendor,
+ string? Hostname,
+ string? HttpServerHeader,
+ int? HttpStatusCode,
+ int? HttpPort,
+ string? OnvifDeviceServiceUrl,
+ string? OnvifName,
+ string? OnvifHardware,
+ int? OnvifPort,
+ string? HomeKitName,
+ string? HomeKitDeviceId,
+ string? HomeKitModel,
+ string? CredentialLabel = null);
+
+/// Response to an agent's discovery submission.
+public record AgentDiscoverySubmitResponse(
+ int Received,
+ int New,
+ int Updated);
+
+// ────────────────────────────────────────────────────────────────────
+// Pending discovery results (UI)
+// ────────────────────────────────────────────────────────────────────
+
+/// A persisted discovery result exposed to the UI for confirmation.
+public record PendingDiscoveryResponse(
+ Guid Id,
+ Guid SiteId,
+ string IpAddress,
+ string? MacAddress,
+ string? Vendor,
+ string? Hostname,
+ bool IsReachable,
+ string DetectedType,
+ string DiscoveryMethod,
+ int[] OpenPorts,
+ string? OnvifDeviceServiceUrl,
+ string? OnvifName,
+ string? OnvifHardware,
+ int? OnvifPort,
+ string? HttpServerHeader,
+ int? HttpStatusCode,
+ int? HttpPort,
+ DateTime ProbedAt,
+ bool IsProcessed,
+ string[] StreamUrls);
+
+/// Request to reject (ignore) a pending discovery result.
+public record RejectDiscoveryRequest(Guid ResultId);
+
+/// Result of a scan-now request broadcast to site agents.
+public record ScanNowResponse(int AgentsNotified);
diff --git a/src/Heimdall.Application/Discovery/Commands/RejectDiscovery/RejectDiscoveryCommand.cs b/src/Heimdall.Application/Discovery/Commands/RejectDiscovery/RejectDiscoveryCommand.cs
new file mode 100644
index 0000000..d0b727d
--- /dev/null
+++ b/src/Heimdall.Application/Discovery/Commands/RejectDiscovery/RejectDiscoveryCommand.cs
@@ -0,0 +1,17 @@
+using Heimdall.Application.Common;
+using Heimdall.Application.Services;
+using MediatR;
+
+namespace Heimdall.Application.Discovery.Commands.RejectDiscovery;
+
+public record RejectDiscoveryCommand(Guid ResultId) : IRequest;
+
+public class RejectDiscoveryHandler : IRequestHandler
+{
+ private readonly ICameraDiscoveryService _discovery;
+
+ public RejectDiscoveryHandler(ICameraDiscoveryService discovery) => _discovery = discovery;
+
+ public async Task Handle(RejectDiscoveryCommand request, CancellationToken cancellationToken)
+ => await _discovery.RejectDiscoveryAsync(request.ResultId, cancellationToken).ConfigureAwait(false);
+}
diff --git a/src/Heimdall.Application/Discovery/Commands/RequestSiteScan/RequestSiteScanCommand.cs b/src/Heimdall.Application/Discovery/Commands/RequestSiteScan/RequestSiteScanCommand.cs
new file mode 100644
index 0000000..5bc8577
--- /dev/null
+++ b/src/Heimdall.Application/Discovery/Commands/RequestSiteScan/RequestSiteScanCommand.cs
@@ -0,0 +1,50 @@
+using Heimdall.Application.Common;
+using Heimdall.Application.DTOs;
+using Heimdall.Application.Services;
+using MediatR;
+using Microsoft.EntityFrameworkCore;
+
+namespace Heimdall.Application.Discovery.Commands.RequestSiteScan;
+
+public record RequestSiteScanCommand(Guid SiteId) : IRequest>;
+
+///
+/// Ask every online agent of a site to run an immediate network scan.
+/// Delivery is best-effort over SignalR — offline agents pick up the change
+/// on their periodic scan schedule anyway.
+///
+public class RequestSiteScanHandler : IRequestHandler>
+{
+ private readonly IApplicationDbContext _context;
+ private readonly IConfigBroadcastService _broadcast;
+
+ public RequestSiteScanHandler(IApplicationDbContext context, IConfigBroadcastService broadcast)
+ {
+ _context = context;
+ _broadcast = broadcast;
+ }
+
+ public async Task> Handle(
+ RequestSiteScanCommand request, CancellationToken cancellationToken)
+ {
+ var siteExists = await _context.Sites.AnyAsync(s => s.Id == request.SiteId, cancellationToken).ConfigureAwait(false);
+ if (!siteExists)
+ return ServiceResult.NotFound("Site not found");
+
+ var agents = await _context.Agents
+ .Where(a => a.SiteId == request.SiteId && !a.IsDeleted)
+ .ToListAsync(cancellationToken)
+ .ConfigureAwait(false);
+
+ var notified = 0;
+ foreach (var agent in agents)
+ {
+ // Only connected agents receive the push; offline agents scan on schedule.
+ await _broadcast.NotifyAgentSettingChanged(
+ agent.Id, "discovery.scan.requested", "1", cancellationToken).ConfigureAwait(false);
+ notified++;
+ }
+
+ return ServiceResult.Success(new ScanNowResponse(notified));
+ }
+}
diff --git a/src/Heimdall.Application/Discovery/Queries/ListPendingDiscoveries/ListPendingDiscoveriesQuery.cs b/src/Heimdall.Application/Discovery/Queries/ListPendingDiscoveries/ListPendingDiscoveriesQuery.cs
new file mode 100644
index 0000000..fbe4b87
--- /dev/null
+++ b/src/Heimdall.Application/Discovery/Queries/ListPendingDiscoveries/ListPendingDiscoveriesQuery.cs
@@ -0,0 +1,19 @@
+using Heimdall.Application.Common;
+using Heimdall.Application.DTOs;
+using Heimdall.Application.Services;
+using MediatR;
+
+namespace Heimdall.Application.Discovery.Queries.ListPendingDiscoveries;
+
+public record ListPendingDiscoveriesQuery(Guid SiteId) : IRequest>>;
+
+public class ListPendingDiscoveriesHandler : IRequestHandler>>
+{
+ private readonly ICameraDiscoveryService _discovery;
+
+ public ListPendingDiscoveriesHandler(ICameraDiscoveryService discovery) => _discovery = discovery;
+
+ public async Task>> Handle(
+ ListPendingDiscoveriesQuery request, CancellationToken cancellationToken)
+ => await _discovery.ListPendingDiscoveriesAsync(request.SiteId, cancellationToken).ConfigureAwait(false);
+}
diff --git a/src/Heimdall.Application/Security/AgentCredentialEnvelope.cs b/src/Heimdall.Application/Security/AgentCredentialEnvelope.cs
new file mode 100644
index 0000000..c0a3fa2
--- /dev/null
+++ b/src/Heimdall.Application/Security/AgentCredentialEnvelope.cs
@@ -0,0 +1,72 @@
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using Heimdall.Application.DTOs;
+
+namespace Heimdall.Application.Security;
+
+///
+/// Encrypted envelope carrying the site's camera credential pool to an agent.
+///
+/// The envelope is sealed with AES-256-GCM using a key derived from the
+/// agent's API key (SHA-256). The Central only ever stores the SHA-256 hash
+/// of the API key (),
+/// so the pair it ships is decryptable only by the agent that holds the
+/// plaintext API key — a third party intercepting the config payload cannot
+/// recover the login/password pairs.
+///
+public static class AgentCredentialEnvelope
+{
+ private const string Prefix = "v1:";
+ private const int NonceSize = 12;
+ private const int TagSize = 16;
+
+ ///
+ /// Derive the AES key for an agent from its API key hash (hex SHA-256 of
+ /// the plaintext API key, as stored on the Agent entity).
+ ///
+ public static byte[] DeriveKeyFromApiKeyHash(string apiKeyHash)
+ => Convert.FromHexString(apiKeyHash);
+
+ /// Derive the AES key from the plaintext API key (agent side).
+ public static byte[] DeriveKeyFromApiKey(string apiKey)
+ => SHA256.HashData(Encoding.UTF8.GetBytes(apiKey));
+
+ public static string Encrypt(IReadOnlyList credentials, byte[] key)
+ {
+ var payload = JsonSerializer.SerializeToUtf8Bytes(credentials.ToArray());
+ var nonce = RandomNumberGenerator.GetBytes(NonceSize);
+ var ciphertext = new byte[payload.Length];
+ var tag = new byte[TagSize];
+
+ using var aes = new AesGcm(key, TagSize);
+ aes.Encrypt(nonce, payload, ciphertext, tag);
+
+ var combined = new byte[NonceSize + TagSize + ciphertext.Length];
+ nonce.CopyTo(combined, 0);
+ tag.CopyTo(combined, NonceSize);
+ ciphertext.CopyTo(combined, NonceSize + TagSize);
+
+ return Prefix + Convert.ToBase64String(combined);
+ }
+
+ public static IReadOnlyList Decrypt(string envelope, byte[] key)
+ {
+ if (!envelope.StartsWith(Prefix, StringComparison.Ordinal))
+ throw new CryptographicException("Invalid credential envelope format");
+
+ var combined = Convert.FromBase64String(envelope[Prefix.Length..]);
+ if (combined.Length < NonceSize + TagSize)
+ throw new CryptographicException("Credential envelope too short");
+
+ var nonce = combined[..NonceSize];
+ var tag = combined[NonceSize..(NonceSize + TagSize)];
+ var ciphertext = combined[(NonceSize + TagSize)..];
+ var payload = new byte[ciphertext.Length];
+
+ using var aes = new AesGcm(key, TagSize);
+ aes.Decrypt(nonce, ciphertext, tag, payload);
+
+ return JsonSerializer.Deserialize(payload) ?? [];
+ }
+}
diff --git a/src/Heimdall.Application/Services/ICameraDiscoveryService.cs b/src/Heimdall.Application/Services/ICameraDiscoveryService.cs
index a681d0b..c47f41d 100644
--- a/src/Heimdall.Application/Services/ICameraDiscoveryService.cs
+++ b/src/Heimdall.Application/Services/ICameraDiscoveryService.cs
@@ -79,4 +79,26 @@ public interface ICameraDiscoveryService
///
Task> CheckDuplicateAsync(
CheckDuplicateRequest request, CancellationToken ct);
+
+ ///
+ /// Receive a batch of devices probed by an agent's network scan. Persists
+ /// them as CameraDiscoveryResult (upsert by site+IP for unprocessed results),
+ /// then enriches each candidate: authenticated ONVIF GetDeviceInformation
+ /// using the site's declared credential pool, and candidate stream URL
+ /// building from the built-in camera database.
+ ///
+ Task> SubmitAgentDiscoveriesAsync(
+ Guid agentId, IReadOnlyList devices, CancellationToken ct);
+
+ ///
+ /// List pending (unprocessed) discovery results for a site, newest first.
+ ///
+ Task>> ListPendingDiscoveriesAsync(
+ Guid siteId, CancellationToken ct);
+
+ ///
+ /// Mark a discovery result as rejected (ignored) so it no longer appears
+ /// in the pending list. Does not delete the row.
+ ///
+ Task RejectDiscoveryAsync(Guid resultId, CancellationToken ct);
}
diff --git a/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs b/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs
index 1bc684f..ee3ddf4 100644
--- a/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs
+++ b/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs
@@ -1,4 +1,6 @@
using Heimdall.Application.Common;
+using Heimdall.Application.DTOs;
+using Heimdall.Application.Security;
using MediatR;
using Microsoft.EntityFrameworkCore;
@@ -10,8 +12,13 @@ public class GetEffectiveAgentConfigQueryHandler
: IRequestHandler>>
{
private readonly IApplicationDbContext _db;
+ private readonly ICredentialProtector _protector;
- public GetEffectiveAgentConfigQueryHandler(IApplicationDbContext db) => _db = db;
+ public GetEffectiveAgentConfigQueryHandler(IApplicationDbContext db, ICredentialProtector protector)
+ {
+ _db = db;
+ _protector = protector;
+ }
public async Task>> Handle(
GetEffectiveAgentConfigQuery request, CancellationToken ct)
@@ -29,6 +36,38 @@ public class GetEffectiveAgentConfigQueryHandler
foreach (var s in agentSettings)
config[s.Key] = s.Value;
+ // ── Camera credential pool (encrypted, decryptable only by the agent) ──
+ // The agent lives on the camera network, so it must own the authenticated
+ // ONVIF enrichment. The Central ships the site's credential pairs inside
+ // an AES-GCM envelope keyed by the agent's API key hash. The agent can
+ // decrypt it with its plaintext API key; nobody else can.
+ var agent = await _db.Agents
+ .AsNoTracking()
+ .FirstOrDefaultAsync(a => a.Id == request.AgentId, ct)
+ .ConfigureAwait(false);
+
+ if (agent is not null && !string.IsNullOrEmpty(agent.ApiKeyHash))
+ {
+ var credentials = await _db.SiteCredentials
+ .AsNoTracking()
+ .Where(c => c.SiteId == agent.SiteId)
+ .ToListAsync(ct)
+ .ConfigureAwait(false);
+
+ if (credentials.Count > 0)
+ {
+ var pairs = credentials
+ .Select(c => new AgentCameraCredential(
+ c.Label,
+ c.Username,
+ _protector.Decrypt(c.Password)))
+ .ToList();
+
+ var key = AgentCredentialEnvelope.DeriveKeyFromApiKeyHash(agent.ApiKeyHash);
+ config["discovery.credentials"] = AgentCredentialEnvelope.Encrypt(pairs, key);
+ }
+ }
+
return ServiceResult>.Success(config);
}
}
diff --git a/src/Heimdall.Application/SiteCredentials/Commands/AddSiteCredential/AddSiteCredentialCommand.cs b/src/Heimdall.Application/SiteCredentials/Commands/AddSiteCredential/AddSiteCredentialCommand.cs
new file mode 100644
index 0000000..c4c35a0
--- /dev/null
+++ b/src/Heimdall.Application/SiteCredentials/Commands/AddSiteCredential/AddSiteCredentialCommand.cs
@@ -0,0 +1,61 @@
+using Heimdall.Application.Common;
+using Heimdall.Application.DTOs;
+using Heimdall.Domain.Entities;
+using MediatR;
+using Microsoft.EntityFrameworkCore;
+
+namespace Heimdall.Application.SiteCredentials.Commands.AddSiteCredential;
+
+public record AddSiteCredentialCommand(
+ Guid SiteId,
+ string Label,
+ string Username,
+ string Password) : IRequest>;
+
+public class AddSiteCredentialHandler : IRequestHandler>
+{
+ private readonly IApplicationDbContext _context;
+ private readonly ICredentialProtector _protector;
+
+ public AddSiteCredentialHandler(IApplicationDbContext context, ICredentialProtector protector)
+ {
+ _context = context;
+ _protector = protector;
+ }
+
+ public async Task> Handle(
+ AddSiteCredentialCommand request, CancellationToken cancellationToken)
+ {
+ if (string.IsNullOrWhiteSpace(request.Label))
+ return ServiceResult.Failure("Label is required");
+ if (string.IsNullOrWhiteSpace(request.Username))
+ return ServiceResult.Failure("Username is required");
+ if (string.IsNullOrWhiteSpace(request.Password))
+ return ServiceResult.Failure("Password is required");
+
+ var siteExists = await _context.Sites.AnyAsync(s => s.Id == request.SiteId, cancellationToken).ConfigureAwait(false);
+ if (!siteExists)
+ return ServiceResult.NotFound("Site not found");
+
+ var duplicate = await _context.SiteCredentials
+ .AnyAsync(c => c.SiteId == request.SiteId
+ && (c.Label == request.Label || c.Username == request.Username),
+ cancellationToken)
+ .ConfigureAwait(false);
+ if (duplicate)
+ return ServiceResult.Conflict("A credential with this label or username already exists for this site");
+
+ var credential = new SiteCredential(
+ request.SiteId,
+ request.Label.Trim(),
+ request.Username.Trim(),
+ _protector.Encrypt(request.Password));
+
+ _context.SiteCredentials.Add(credential);
+ await _context.SaveChangesWithRetryAsync(ct: cancellationToken).ConfigureAwait(false);
+
+ return ServiceResult.Success(new SiteCredentialResponse(
+ credential.Id, credential.SiteId, credential.Label, credential.Username,
+ credential.CreatedAt, credential.LastUsedAt));
+ }
+}
diff --git a/src/Heimdall.Application/SiteCredentials/Commands/DeleteSiteCredential/DeleteSiteCredentialCommand.cs b/src/Heimdall.Application/SiteCredentials/Commands/DeleteSiteCredential/DeleteSiteCredentialCommand.cs
new file mode 100644
index 0000000..e6d1475
--- /dev/null
+++ b/src/Heimdall.Application/SiteCredentials/Commands/DeleteSiteCredential/DeleteSiteCredentialCommand.cs
@@ -0,0 +1,30 @@
+using Heimdall.Application.Common;
+using MediatR;
+using Microsoft.EntityFrameworkCore;
+
+namespace Heimdall.Application.SiteCredentials.Commands.DeleteSiteCredential;
+
+public record DeleteSiteCredentialCommand(Guid SiteId, Guid CredentialId) : IRequest;
+
+public class DeleteSiteCredentialHandler : IRequestHandler
+{
+ private readonly IApplicationDbContext _context;
+
+ public DeleteSiteCredentialHandler(IApplicationDbContext context) => _context = context;
+
+ public async Task Handle(
+ DeleteSiteCredentialCommand request, CancellationToken cancellationToken)
+ {
+ var credential = await _context.SiteCredentials
+ .FirstOrDefaultAsync(c => c.Id == request.CredentialId && c.SiteId == request.SiteId, cancellationToken)
+ .ConfigureAwait(false);
+
+ if (credential is null)
+ return ServiceResult.NotFound("Credential not found for this site");
+
+ _context.SiteCredentials.Remove(credential);
+ await _context.SaveChangesWithRetryAsync(ct: cancellationToken).ConfigureAwait(false);
+
+ return ServiceResult.Success();
+ }
+}
diff --git a/src/Heimdall.Application/SiteCredentials/Queries/ListSiteCredentials/ListSiteCredentialsQuery.cs b/src/Heimdall.Application/SiteCredentials/Queries/ListSiteCredentials/ListSiteCredentialsQuery.cs
new file mode 100644
index 0000000..c7b8464
--- /dev/null
+++ b/src/Heimdall.Application/SiteCredentials/Queries/ListSiteCredentials/ListSiteCredentialsQuery.cs
@@ -0,0 +1,36 @@
+using Heimdall.Application.Common;
+using Heimdall.Application.DTOs;
+using MediatR;
+using Microsoft.EntityFrameworkCore;
+
+namespace Heimdall.Application.SiteCredentials.Queries.ListSiteCredentials;
+
+public record ListSiteCredentialsQuery(Guid SiteId) : IRequest>>;
+
+public class ListSiteCredentialsHandler : IRequestHandler>>
+{
+ private readonly IApplicationDbContext _context;
+
+ public ListSiteCredentialsHandler(IApplicationDbContext context) => _context = context;
+
+ public async Task>> Handle(
+ ListSiteCredentialsQuery request, CancellationToken cancellationToken)
+ {
+ var siteExists = await _context.Sites.AnyAsync(s => s.Id == request.SiteId, cancellationToken).ConfigureAwait(false);
+ if (!siteExists)
+ return ServiceResult>.NotFound("Site not found");
+
+ var credentials = await _context.SiteCredentials
+ .Where(c => c.SiteId == request.SiteId)
+ .OrderBy(c => c.CreatedAt)
+ .ToListAsync(cancellationToken)
+ .ConfigureAwait(false);
+
+ var response = credentials
+ .Select(c => new SiteCredentialResponse(
+ c.Id, c.SiteId, c.Label, c.Username, c.CreatedAt, c.LastUsedAt))
+ .ToList();
+
+ return ServiceResult>.Success(response);
+ }
+}
diff --git a/src/Heimdall.Domain/Entities/CameraDiscoveryResult.cs b/src/Heimdall.Domain/Entities/CameraDiscoveryResult.cs
index ea6fb24..582e1b5 100644
--- a/src/Heimdall.Domain/Entities/CameraDiscoveryResult.cs
+++ b/src/Heimdall.Domain/Entities/CameraDiscoveryResult.cs
@@ -116,5 +116,11 @@ public class CameraDiscoveryResult : Entity
Vendor = vendor;
}
+ public void SetHostname(string? hostname)
+ {
+ if (!string.IsNullOrEmpty(hostname))
+ Hostname = hostname;
+ }
+
public void MarkProcessed() => IsProcessed = true;
}
diff --git a/src/Heimdall.Domain/Entities/Site.cs b/src/Heimdall.Domain/Entities/Site.cs
index 97147de..8fa8f8c 100644
--- a/src/Heimdall.Domain/Entities/Site.cs
+++ b/src/Heimdall.Domain/Entities/Site.cs
@@ -30,6 +30,10 @@ public class Site : Entity, IAuditableEntity, ISoftDeletable
private readonly List _cameras = [];
public IReadOnlyCollection Cameras => _cameras.AsReadOnly();
+ /// Credential pairs declared for this site (used by camera discovery).
+ private readonly List _credentials = [];
+ public IReadOnlyCollection Credentials => _credentials.AsReadOnly();
+
private Site() { } // EF Core
public Site(string name, string? address = null, string? timezone = null)
diff --git a/src/Heimdall.Domain/Entities/SiteCredential.cs b/src/Heimdall.Domain/Entities/SiteCredential.cs
new file mode 100644
index 0000000..74e431e
--- /dev/null
+++ b/src/Heimdall.Domain/Entities/SiteCredential.cs
@@ -0,0 +1,49 @@
+using Heimdall.Domain.Primitives;
+
+namespace Heimdall.Domain.Entities;
+
+///
+/// A credential pair (username/password) declared for a site, used by agents
+/// to authenticate against cameras discovered on the site's network.
+/// The password is encrypted at rest via
+/// (applied in the
+/// application/service layer before storage) — never stored in plain text.
+///
+public class SiteCredential : Entity
+{
+ public Guid SiteId { get; private set; }
+ public Site Site { get; private set; } = null!;
+
+ /// Human-readable label, e.g. "admin principal" or "comptes NVR".
+ public string Label { get; private set; } = string.Empty;
+
+ public string Username { get; private set; } = string.Empty;
+
+ /// Encrypted via ICredentialProtector at the service layer.
+ public string Password { get; private set; } = string.Empty;
+
+ public DateTime CreatedAt { get; private set; } = DateTime.UtcNow;
+
+ /// Last time a discovery successfully used this credential pair.
+ public DateTime? LastUsedAt { get; private set; }
+
+ private SiteCredential() { } // EF Core
+
+ public SiteCredential(Guid siteId, string label, string username, string password)
+ : base(Guid.NewGuid())
+ {
+ SiteId = siteId;
+ Label = label;
+ Username = username;
+ Password = password;
+ }
+
+ public void Update(string label, string username, string password)
+ {
+ Label = label;
+ Username = username;
+ Password = password;
+ }
+
+ public void MarkUsed() => LastUsedAt = DateTime.UtcNow;
+}
diff --git a/src/Heimdall.Infrastructure/Data/AppDbContext.cs b/src/Heimdall.Infrastructure/Data/AppDbContext.cs
index 5892eba..7ec75e4 100644
--- a/src/Heimdall.Infrastructure/Data/AppDbContext.cs
+++ b/src/Heimdall.Infrastructure/Data/AppDbContext.cs
@@ -21,6 +21,7 @@ public class AppDbContext : IdentityDbContext, IApplicat
// Domain entities
public DbSet Sites => Set();
+ public DbSet SiteCredentials => Set();
public DbSet Agents => Set();
public DbSet Cameras => Set();
public DbSet CameraCredentials => Set();
diff --git a/src/Heimdall.Infrastructure/Data/Configurations/SiteCredentialConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/SiteCredentialConfiguration.cs
new file mode 100644
index 0000000..b6e1a3f
--- /dev/null
+++ b/src/Heimdall.Infrastructure/Data/Configurations/SiteCredentialConfiguration.cs
@@ -0,0 +1,43 @@
+using Heimdall.Domain.Entities;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+
+namespace Heimdall.Infrastructure.Data.Configurations;
+
+public class SiteCredentialConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("site_credentials");
+
+ builder.HasKey(c => c.Id);
+
+ builder.Property(c => c.Label)
+ .HasMaxLength(100)
+ .IsUnicode(false);
+
+ builder.Property(c => c.Username)
+ .HasMaxLength(200)
+ .IsUnicode(false);
+
+ // Password is encrypted (ICredentialProtector) — column must be large enough
+ // for the ciphertext (base64 of AesGcm output + tag + nonce).
+ builder.Property(c => c.Password)
+ .HasMaxLength(2000)
+ .IsUnicode(false);
+
+ builder.Property(c => c.CreatedAt)
+ .HasDefaultValueSql("NOW()");
+
+ builder.Property(c => c.LastUsedAt);
+
+ // ── Indexes ─────────────────────────────────────────────────
+ builder.HasIndex(c => c.SiteId);
+
+ // ── Relationships ───────────────────────────────────────────
+ builder.HasOne(c => c.Site)
+ .WithMany(s => s.Credentials)
+ .HasForeignKey(c => c.SiteId)
+ .OnDelete(DeleteBehavior.Cascade);
+ }
+}
diff --git a/src/Heimdall.Infrastructure/Migrations/20260811120321_AddSiteCredentials.Designer.cs b/src/Heimdall.Infrastructure/Migrations/20260811120321_AddSiteCredentials.Designer.cs
new file mode 100644
index 0000000..870178b
--- /dev/null
+++ b/src/Heimdall.Infrastructure/Migrations/20260811120321_AddSiteCredentials.Designer.cs
@@ -0,0 +1,1831 @@
+//
+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("20260811120321_AddSiteCredentials")]
+ partial class AddSiteCredentials
+ {
+ ///
+ 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("CpuUsagePercent")
+ .HasColumnType("double precision");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("DeletedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("DiskUsagePercent")
+ .HasColumnType("double precision");
+
+ 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("MemoryUsageBytes")
+ .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("UptimeSeconds")
+ .HasColumnType("bigint");
+
+ 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("AgentScoped")
+ .HasColumnType("boolean");
+
+ 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("Capabilities")
+ .IsRequired()
+ .HasMaxLength(64)
+ .IsUnicode(false)
+ .HasColumnType("character varying(64)");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.Property("DeletedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("DetectedType")
+ .IsRequired()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("character varying(20)");
+
+ b.Property("DiscoveryMethod")
+ .IsRequired()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("character varying(20)");
+
+ b.Property("HasAudio")
+ .HasColumnType("boolean");
+
+ b.Property("HasMotionDetection")
+ .HasColumnType("boolean");
+
+ b.Property("HasPtz")
+ .HasColumnType("boolean");
+
+ b.Property("HttpPort")
+ .HasColumnType("integer");
+
+ b.Property("IpAddress")
+ .HasMaxLength(45)
+ .HasColumnType("character varying(45)");
+
+ b.Property("IsDeleted")
+ .HasColumnType("boolean");
+
+ b.Property("LastDiscoveredAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("LastStreamTestAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("LastTestedCodecs")
+ .HasMaxLength(200)
+ .IsUnicode(false)
+ .HasColumnType("character varying(200)");
+
+ b.Property("LastTestedHeight")
+ .HasColumnType("integer");
+
+ b.Property("LastTestedLatencyMs")
+ .HasColumnType("bigint");
+
+ b.Property("LastTestedWidth")
+ .HasColumnType("integer");
+
+ b.Property("MacAddress")
+ .HasMaxLength(17)
+ .HasColumnType("character varying(17)");
+
+ 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("OnvifPort")
+ .HasColumnType("integer");
+
+ b.Property("RtspPort")
+ .HasColumnType("integer");
+
+ 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("SubRtspUrl")
+ .HasMaxLength(1000)
+ .IsUnicode(false)
+ .HasColumnType("character varying(1000)");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("timestamp with time zone")
+ .HasDefaultValueSql("NOW()");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AgentId");
+
+ b.HasIndex("IpAddress");
+
+ b.HasIndex("MacAddress");
+
+ b.HasIndex("SiteId");
+
+ b.ToTable("cameras", (string)null);
+ });
+
+ modelBuilder.Entity("Heimdall.Domain.Entities.CameraAssignment", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("AgentId")
+ .HasColumnType("uuid");
+
+ b.Property("AssignedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("CameraId")
+ .HasColumnType("uuid");
+
+ b.Property("Reason")
+ .IsRequired()
+ .HasMaxLength(50)
+ .IsUnicode(false)
+ .HasColumnType("character varying(50)");
+
+ b.Property("ReleasedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AssignedAt");
+
+ b.HasIndex("AgentId", "ReleasedAt")
+ .HasFilter("\"ReleasedAt\" IS NULL");
+
+ b.HasIndex("CameraId", "ReleasedAt")
+ .IsUnique()
+ .HasFilter("\"ReleasedAt\" IS NULL");
+
+ b.ToTable("camera_assignments", (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.CameraDiscoveryResult", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("DetectedType")
+ .IsRequired()
+ .HasMaxLength(20)
+ .IsUnicode(false)
+ .HasColumnType("character varying(20)");
+
+ b.Property