diff --git a/docs/agent-release-signing.md b/docs/agent-release-signing.md index f5905ce..eb205ba 100644 --- a/docs/agent-release-signing.md +++ b/docs/agent-release-signing.md @@ -1,6 +1,6 @@ # Signatures des mises à jour Agent -Les mises à jour natives et Docker sont acceptées uniquement si le manifeste de release est signé par la clé de publication. Central transmet le manifeste et sa signature, mais ne fournit jamais la clé de confiance aux Agents. Chaque Agent lit sa clé publique depuis un fichier local monté ou installé par l’exploitant. +Les mises à jour natives et Docker sont acceptées uniquement si le manifeste de release est signé par la clé de publication. La release publie aussi la clé publique ECDSA P-256. Pour le premier déploiement, l’installateur la récupère via Central sur HTTPS; l’Agent la conserve ensuite localement (Linux) ou dans la configuration générée par l’IHM (Docker/Windows). Central ne peut donc pas remplacer silencieusement la clé déjà épinglée par un Agent existant. ## Préparer les clés @@ -12,15 +12,17 @@ openssl pkey -in agent-release-private.pem -pubout -out agent-release-public.pem base64 -w0 agent-release-private.pem ``` -La dernière sortie est la valeur du secret Gitea Actions `RELEASE_SIGNING_KEY_B64`. Ne pas ajouter la clé privée au dépôt ni aux images. Distribuer `agent-release-public.pem` par un canal d’administration indépendant de Central. La publication d’une release échoue si le secret de signature manque. +La dernière sortie est la valeur du secret Gitea Actions `RELEASE_SIGNING_KEY_B64`. Ne pas ajouter la clé privée au dépôt ni aux images. Le job de publication dérive la clé publique depuis ce secret et l’attache à chaque release. La publication d’une release échoue si le secret de signature manque. Configurer également la variable Gitea Actions `RELEASE_SERVER_URL` avec l’origine HTTPS de la forge attendue (par exemple `https://sources.tordais.cc`, sans chemin). La publication compare cette valeur à `BUILD_SERVER_URL`, fourni par Gitea, avant toute publication. Les images serveur et Agent sont publiées sur Docker Hub sous `eltruncho/heimdall` et `eltruncho/heimdall-agent`; configurer les secrets Actions `DOCKERHUB_USERNAME` et `DOCKERHUB_TOKEN`. Central transmet à l’Agent le dépôt et le digest signés dans la release. La publication génère `agent-update-manifest.json`, qui lie la version, les SHA-256 des archives Agent et le dépôt ainsi que le digest immuable de l’image Docker. Elle publie aussi `agent-update-manifest.sig`, signature ECDSA/SHA-256 du fichier JSON. La clé publique permet de vérifier ces valeurs avant tout remplacement d’agent. Une modification de l’URL de la forge ou du registre reste possible sans changer cette clé. +Les mises à jour automatiques natives sont désactivées par défaut dans les réglages globaux Agent; chaque site peut hériter de ce réglage ou le remplacer. L’Agent vérifie les releases toutes les 12 heures et attend que `publishedAt` ait au moins 24 heures avant d’appliquer une mise à jour automatique. Une demande manuelle d’administrateur peut déclencher la mise à jour immédiatement. Les installations Docker/Kubernetes ne font pas de polling d’image local : elles suivent le mécanisme de l’orchestrateur et le digest fourni par l’IHM. + ## Installer un Agent natif -Installer les dépendances `.NET 10`, `jq`, `openssl` et `python3`, puis exécuter le script d’installation avec sa copie locale de la clé publique : +Central affiche une commande Bash qui télécharge et exécute l’installateur pour le site, sans copier les scripts ni la clé sur l’hôte. L’installateur vérifie le manifeste et l’archive avant installation. Le runtime .NET 10, `jq`, `openssl` et `python3` doivent être présents. Le paramètre local de clé reste disponible pour les installations isolées : ```sh sudo bash install/install-agent.sh \ @@ -29,12 +31,12 @@ sudo bash install/install-agent.sh \ --update-public-key /chemin/local/agent-release-public.pem ``` -Le script lit le manifeste signé via Central, vérifie la signature et l’archive, puis installe la release sous `/opt/heimdall/agent/releases/`. Le service utilise le lien `current`; lors d’une mise à jour, le superviseur accorde jusqu’à 180 secondes au démarrage, exige ensuite 60 secondes de réponse continue de `/api/version` pour la version attendue et rétablit la release précédente si cette validation échoue. Garder ensemble `install-agent.sh` et `agent-supervisor.py` lors d’une installation depuis une copie des scripts. +L’installateur Linux est servi par Central avec son superviseur. Il installe la release sous `/opt/heimdall/agent/releases/`; le service systemd utilise le lien `current`. Après téléchargement vérifié, le superviseur accorde jusqu’à 180 secondes au démarrage, exige ensuite 60 secondes de réponse continue de `/api/version` pour la version attendue et rétablit la release précédente si cette validation échoue. -Pour un Agent Docker, déposer la clé reçue par un canal de confiance indépendant de Central dans `agent-release-public.pem`, à côté du Compose généré par l’IHM. Celui-ci la monte en lecture seule sur `/run/secrets/agent-release-public.pem` et configure `Agent__UpdatePublicKeyPath`; le fichier doit être lisible par l’UID 1654 (par exemple `chmod 644`). Le démarrage échoue explicitement si le fichier est absent. L’Agent refuse la mise à jour si le chemin ou la signature manque, si le digest d’image diffère du manifeste signé, ou si le registre ne fournit pas l’image au digest annoncé. +Pour un Agent Docker, le Compose généré par l’IHM contient le dépôt, le digest et la clé publique issus des métadonnées de release vérifiées par Central. Aucun fichier de clé n’est à créer manuellement. L’Agent refuse la mise à jour si la signature manque, si le digest d’image diffère du manifeste signé, ou si le registre ne fournit pas l’image au digest annoncé. ## Rotation -Une rotation de clé exige de déployer d’abord la nouvelle clé publique sur chaque Agent par le canal d’administration local. Publier ensuite les releases avec la nouvelle clé privée. Les Agents non mis à jour refusent ces releases; aucun remplacement automatique de la clé via Central n’est autorisé. Conserver une procédure de retour arrière et la dernière release vérifiée pendant la transition. +Une rotation de clé exige de déployer d’abord la nouvelle clé publique sur chaque Agent par une mise à jour locale de confiance, puis de publier les releases avec la nouvelle clé privée. Les Agents déjà installés refusent les releases signées uniquement par la nouvelle clé tant qu’elle n’a pas été ajoutée localement. Conserver une procédure de retour arrière et la dernière release vérifiée pendant la transition. -La CI distante doit encore démontrer une release signée complète sur un runner capable de joindre la forge et le registre. Les plateformes autres que l’installation Linux gérée restent à valider sur leurs environnements cibles. +La CI distante doit encore démontrer une release signée complète sur un runner capable de joindre la forge et le registre. L’installation native Windows et son rollback doivent être validés sur Windows réel; Linux natif reste à valider sur un hôte Linux. Les installations Docker restent confiées au cycle d’image généré par l’IHM. diff --git a/install/agent-update-supervisor.ps1 b/install/agent-update-supervisor.ps1 new file mode 100644 index 0000000..bb714dc --- /dev/null +++ b/install/agent-update-supervisor.ps1 @@ -0,0 +1,237 @@ +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)][ValidateRange(1, 2147483647)][int] $AgentPid, + [Parameter(Mandatory = $true)][string] $InstallRoot, + [Parameter(Mandatory = $true)][string] $ArchivePath, + [Parameter(Mandatory = $true)][string] $Version, + [Parameter(Mandatory = $true)][ValidatePattern('^[A-Fa-f0-9]{64}$')][string] $ExpectedSha256, + [Parameter(Mandatory = $true)][string] $DotnetPath, + [string] $ServiceName, + [string] $HealthUrl = 'http://127.0.0.1:8081/api/version' +) + +$ErrorActionPreference = 'Stop' +$ProgressPreference = 'SilentlyContinue' +$StartupTimeout = [TimeSpan]::FromSeconds(180) +$StablePeriod = [TimeSpan]::FromSeconds(60) + +function Get-Sha256([string] $Path) { + return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant() +} + +function Assert-SafeArchive([string] $Path) { + if ((Get-Item -LiteralPath $Path).Length -gt 2GB) { throw 'Update archive exceeds 2 GiB.' } + $entries = & tar.exe -tzf $Path + if ($LASTEXITCODE -ne 0 -or $entries.Count -gt 20000) { throw 'Update archive cannot be inspected or has too many entries.' } + foreach ($entry in $entries) { + $name = ([string]$entry).Replace('\', '/') + if ([string]::IsNullOrWhiteSpace($name) -or $name.StartsWith('/') -or + $name -match '^[A-Za-z]:' -or ($name -split '/') -contains '..') { + throw 'Update archive contains an unsafe path.' + } + } +} + +function Start-Agent([string] $Directory, [string] $RuntimePath) { + $assembly = Join-Path $Directory 'Heimdall.Agent.dll' + if (-not (Test-Path -LiteralPath $assembly -PathType Leaf)) { throw 'Release directory has no Agent assembly.' } + $quotedAssembly = '"' + $assembly.Replace('"', '\"') + '"' + return Start-Process -FilePath $RuntimePath -ArgumentList $quotedAssembly -WorkingDirectory $Directory -WindowStyle Hidden -PassThru +} + +function Stop-AgentProcess($Process) { + if ($null -ne $Process -and -not $Process.HasExited) { + Stop-Process -Id $Process.Id -Force -ErrorAction SilentlyContinue + try { $Process.WaitForExit(10000) } catch { } + } +} + +function Wait-ForHealthyVersion($Process, [string] $ExpectedVersion) { + $deadline = [DateTime]::UtcNow + $StartupTimeout + $healthySince = $null + while ([DateTime]::UtcNow -lt $deadline) { + if ($Process.HasExited) { return $false } + try { + $health = Invoke-RestMethod -Method Get -Uri $HealthUrl -TimeoutSec 3 + $actual = ([string]$health.version).Split('+')[0].TrimStart('v', 'V') + $wanted = $ExpectedVersion.Split('+')[0].TrimStart('v', 'V') + if ($actual -eq $wanted) { + if ($null -eq $healthySince) { $healthySince = [DateTime]::UtcNow } + if ([DateTime]::UtcNow - $healthySince -ge $StablePeriod) { return $true } + } + else { $healthySince = $null } + } + catch { $healthySince = $null } + Start-Sleep -Seconds 2 + } + return $false +} + +function Wait-ForHealthyService([string] $Name, [string] $ExpectedVersion) { + $deadline = [DateTime]::UtcNow + $StartupTimeout + $healthySince = $null + while ([DateTime]::UtcNow -lt $deadline) { + $service = Get-Service -Name $Name -ErrorAction SilentlyContinue + if ($null -eq $service -or $service.Status.ToString() -ne 'Running') { + $healthySince = $null + Start-Sleep -Seconds 2 + continue + } + try { + $health = Invoke-RestMethod -Method Get -Uri $HealthUrl -TimeoutSec 3 + $actual = ([string]$health.version).Split('+')[0].TrimStart('v', 'V') + $wanted = if ($ExpectedVersion) { $ExpectedVersion.Split('+')[0].TrimStart('v', 'V') } else { $null } + if (-not $wanted -or $actual -eq $wanted) { + if ($null -eq $healthySince) { $healthySince = [DateTime]::UtcNow } + if ([DateTime]::UtcNow - $healthySince -ge $StablePeriod) { return $true } + } + else { $healthySince = $null } + } + catch { $healthySince = $null } + Start-Sleep -Seconds 2 + } + return $false +} + +$root = [IO.Path]::GetFullPath($InstallRoot).TrimEnd('\') +$releases = Join-Path $root 'releases' +$current = Join-Path $root 'current' +$sourceArchive = [IO.Path]::GetFullPath($ArchivePath) +$versionLeaf = $Version.TrimStart('v', 'V') +if ($versionLeaf -notmatch '^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$') { throw 'Invalid update version.' } +if (-not (Test-Path -LiteralPath $current -PathType Container)) { throw 'Managed current Agent directory is missing.' } +if ((Get-Item -LiteralPath $current -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { + throw 'The current Agent directory cannot be a reparse point.' +} +if ([IO.Path]::IsPathRooted($DotnetPath) -and -not (Test-Path -LiteralPath $DotnetPath -PathType Leaf)) { + throw 'The configured .NET host was not found.' +} +New-Item -ItemType Directory -Path $releases -Force | Out-Null +if (-not (Test-Path -LiteralPath $sourceArchive -PathType Leaf)) { throw 'Update archive is missing.' } +$archive = Join-Path $releases ('.update-' + [Guid]::NewGuid().ToString('N') + '.tar.gz') +Copy-Item -LiteralPath $sourceArchive -Destination $archive +if ((Get-Sha256 $archive) -ine $ExpectedSha256) { + Remove-Item -LiteralPath $archive -Force + throw 'Update archive SHA-256 verification failed.' +} +try { Assert-SafeArchive $archive } +catch { + Remove-Item -LiteralPath $archive -Force -ErrorAction SilentlyContinue + throw +} + +# Wait until the old Agent has completely left its working directory before replacing files. +try { + $old = Get-Process -Id $AgentPid -ErrorAction Stop + $old.WaitForExit(180000) | Out-Null + if (-not $old.HasExited) { throw 'Previous Agent process did not stop within 180 seconds.' } +} +catch [Microsoft.PowerShell.Commands.ProcessCommandException] { + # The process may have exited between the helper launch and this lookup. +} +catch { + Remove-Item -LiteralPath $archive -Force -ErrorAction SilentlyContinue + throw +} + +if ($ServiceName) { + $serviceDeadline = [DateTime]::UtcNow.AddSeconds(30) + do { + $service = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue + if ($null -eq $service -or $service.Status.ToString() -eq 'Stopped') { break } + Start-Sleep -Seconds 1 + } while ([DateTime]::UtcNow -lt $serviceDeadline) + if ($service -and $service.Status.ToString() -ne 'Stopped') { + Remove-Item -LiteralPath $archive -Force -ErrorAction SilentlyContinue + throw "Windows Service '$ServiceName' did not stop after its Agent process exited." + } +} + +$stage = Join-Path $releases ('.staging-' + [Guid]::NewGuid().ToString('N')) +$previous = Join-Path $releases ('.previous-' + [Guid]::NewGuid().ToString('N')) +$failed = Join-Path $releases ('.failed-' + [Guid]::NewGuid().ToString('N')) +$versionRoot = Join-Path $releases $versionLeaf +New-Item -ItemType Directory -Path $stage | Out-Null +$newProcess = $null +$swapped = $false + +try { + & tar.exe -xzf $archive -C $stage + if ($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath (Join-Path $stage 'Heimdall.Agent.dll') -PathType Leaf)) { + throw 'Update archive extraction failed.' + } + if (Test-Path -LiteralPath $versionRoot) { throw "Release $versionLeaf is already present." } + Move-Item -LiteralPath $stage -Destination $versionRoot + + # Directory moves stay on the same volume. Keep the old tree until the new process passes its startup probe. + Move-Item -LiteralPath $current -Destination $previous + try { + Copy-Item -LiteralPath $versionRoot -Destination $current -Recurse + $swapped = $true + } + catch { + if (Test-Path -LiteralPath $current -PathType Container) { + Remove-Item -LiteralPath $current -Recurse -Force -ErrorAction SilentlyContinue + } + Move-Item -LiteralPath $previous -Destination $current + throw + } + + if ($ServiceName) { + Start-Service -Name $ServiceName + if (-not (Wait-ForHealthyService $ServiceName $Version)) { + throw 'Updated Windows Service failed its startup and 60-second stability checks.' + } + } + else { + $newProcess = Start-Agent $current $DotnetPath + if (-not (Wait-ForHealthyVersion $newProcess $Version)) { + throw 'Updated Agent failed its startup and 60-second stability checks.' + } + } + + Remove-Item -LiteralPath $previous -Recurse -Force + Write-Output "Agent update to $Version passed startup verification." + if (-not $ServiceName) { + # Keep this supervisor alive with the launched console Agent. + $newProcess.WaitForExit() + } +} +catch { + $failure = $_ + if ($ServiceName) { Stop-Service -Name $ServiceName -Force -ErrorAction SilentlyContinue } + else { Stop-AgentProcess $newProcess } + if ($swapped -and (Test-Path -LiteralPath $current -PathType Container)) { + Move-Item -LiteralPath $current -Destination $failed + } + if (Test-Path -LiteralPath $previous -PathType Container) { + Move-Item -LiteralPath $previous -Destination $current + try { + if ($ServiceName) { + Start-Service -Name $ServiceName + if (-not (Wait-ForHealthyService $ServiceName $null)) { throw 'Restored service did not pass its health check.' } + } + else { + $rollbackProcess = Start-Agent $current $DotnetPath + $rollbackProcess.WaitForExit() + } + Write-Warning 'The previous Agent release was restored and restarted.' + } + catch { Write-Error "Rollback restart failed: $($_.Exception.Message)" } + } + if (Test-Path -LiteralPath $versionRoot -PathType Container) { + Remove-Item -LiteralPath $versionRoot -Recurse -Force -ErrorAction SilentlyContinue + } + throw $failure +} +finally { + if (Test-Path -LiteralPath $stage -PathType Container) { + Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue + } + if (Test-Path -LiteralPath $failed -PathType Container) { + Remove-Item -LiteralPath $failed -Recurse -Force -ErrorAction SilentlyContinue + } + if (Test-Path -LiteralPath $archive -PathType Leaf) { + Remove-Item -LiteralPath $archive -Force -ErrorAction SilentlyContinue + } +} diff --git a/install/install-agent.ps1 b/install/install-agent.ps1 new file mode 100644 index 0000000..ba6a287 --- /dev/null +++ b/install/install-agent.ps1 @@ -0,0 +1,306 @@ +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)][string] $CentralUrl, + [Parameter(Mandatory = $true)][string] $SiteToken, + [Parameter(Mandatory = $true)][string] $AgentName, + [string] $InstallDirectory = (Join-Path $env:LOCALAPPDATA 'Heimdall\Agent'), + [switch] $InstallAsService, + [switch] $InstallOnly, + [string] $ServiceName = 'HeimdallAgent', + [switch] $SkipRuntimeInstall +) + +$ErrorActionPreference = 'Stop' +$ProgressPreference = 'SilentlyContinue' + +function Get-Sha256([string] $Path) { + return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant() +} + +function Assert-HttpsUrl([string] $Value, [string] $Description) { + $uri = [Uri]::new($Value) + if ($uri.Scheme -ne 'https' -or $uri.UserInfo -or $uri.Fragment) { + throw "$Description must be an HTTPS URL without credentials or fragment." + } + return $uri +} + +function Convert-DerSignatureToP1363([byte[]] $Signature) { + if ($Signature.Length -lt 8 -or $Signature[0] -ne 0x30) { throw 'Invalid ECDSA signature encoding.' } + $offset = 2 + if ($Signature[$offset] -ne 0x02) { throw 'Invalid ECDSA signature encoding.' } + $rLength = [int]$Signature[$offset + 1] + $offset += 2 + if ($rLength -lt 1 -or $offset + $rLength + 2 -gt $Signature.Length) { throw 'Invalid ECDSA signature encoding.' } + [byte[]]$r = $Signature[$offset..($offset + $rLength - 1)] + $offset += $rLength + if ($Signature[$offset] -ne 0x02) { throw 'Invalid ECDSA signature encoding.' } + $sLength = [int]$Signature[$offset + 1] + $offset += 2 + if ($sLength -lt 1 -or $offset + $sLength -ne $Signature.Length) { throw 'Invalid ECDSA signature encoding.' } + [byte[]]$s = $Signature[$offset..($offset + $sLength - 1)] + while ($r.Length -gt 1 -and $r[0] -eq 0) { $r = $r[1..($r.Length - 1)] } + while ($s.Length -gt 1 -and $s[0] -eq 0) { $s = $s[1..($s.Length - 1)] } + if ($r.Length -gt 32 -or $s.Length -gt 32) { throw 'ECDSA signature is not P-256.' } + $fixed = New-Object byte[] 64 + [Array]::Copy($r, 0, $fixed, 32 - $r.Length, $r.Length) + [Array]::Copy($s, 0, $fixed, 64 - $s.Length, $s.Length) + return ,$fixed +} + +function Test-EcdsaP256Signature([byte[]] $Data, [byte[]] $Signature, [string] $PublicKeyPem) { + # Windows PowerShell 5 uses .NET Framework, which lacks ImportFromPem. Parse the + # fixed P-256 SubjectPublicKeyInfo emitted by OpenSSL and import a CNG public blob. + $body = ($PublicKeyPem -replace '-----BEGIN PUBLIC KEY-----|-----END PUBLIC KEY-----|\s', '') + $spki = [Convert]::FromBase64String($body) + $prefix = [byte[]](0x30,0x59,0x30,0x13,0x06,0x07,0x2a,0x86,0x48,0xce,0x3d,0x02,0x01, + 0x06,0x08,0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x07,0x03,0x42,0x00,0x04) + if ($spki.Length -ne 91) { throw 'The release public key is not a valid ECDSA P-256 public key.' } + for ($i = 0; $i -lt $prefix.Length; $i++) { + if ($spki[$i] -ne $prefix[$i]) { throw 'The release public key is not ECDSA P-256.' } + } + + $blob = New-Object byte[] 72 + [BitConverter]::GetBytes([UInt32]0x31534345).CopyTo($blob, 0) # BCRYPT_ECDSA_PUBLIC_P256_MAGIC (ECS1) + [BitConverter]::GetBytes([UInt32]32).CopyTo($blob, 4) + [Array]::Copy($spki, 27, $blob, 8, 64) + $key = [Security.Cryptography.CngKey]::Import($blob, [Security.Cryptography.CngKeyBlobFormat]::EccPublicBlob) + $ecdsa = New-Object -TypeName Security.Cryptography.ECDsaCng -ArgumentList $key + try { + $fixedSignature = Convert-DerSignatureToP1363 $Signature + return $ecdsa.VerifyData($Data, $fixedSignature, [Security.Cryptography.HashAlgorithmName]::SHA256) + } + finally { + $ecdsa.Dispose() + $key.Dispose() + } +} + +$central = Assert-HttpsUrl $CentralUrl 'Central URL' +$CentralUrl = $central.AbsoluteUri.TrimEnd('/') +if ([string]::IsNullOrWhiteSpace($SiteToken)) { throw 'SiteToken is required.' } +if ([string]::IsNullOrWhiteSpace($AgentName)) { throw 'AgentName is required.' } +if ($InstallAsService) { + $principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) + if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { + throw 'Windows Service installation requires an elevated PowerShell session (Run as Administrator).' + } + if ($ServiceName -notmatch '^[A-Za-z0-9_.-]{1,80}$') { throw 'ServiceName contains unsupported characters.' } + if (-not $PSBoundParameters.ContainsKey('InstallDirectory')) { + $slug = ($AgentName.ToLowerInvariant() -replace '[^a-z0-9]+', '-').Trim('-') + if (-not $slug) { $slug = 'site' } + $InstallDirectory = Join-Path $env:ProgramData "Heimdall\Agent-$slug" + } +} +if (-not [Environment]::Is64BitOperatingSystem -or $env:PROCESSOR_ARCHITECTURE -notin @('AMD64', 'ARM64')) { + throw 'This native installer currently supports 64-bit Windows only.' +} + +$platform = 'win-x64' +$tempRoot = Join-Path ([IO.Path]::GetTempPath()) ('heimdall-agent-' + [Guid]::NewGuid().ToString('N')) +$releaseRoot = [IO.Path]::GetFullPath($InstallDirectory) +$releasesRoot = Join-Path $releaseRoot 'releases' +$releasePath = Join-Path $releaseRoot 'current' +if (Test-Path -LiteralPath $releasePath) { + throw 'A Heimdall Agent is already installed here. Use its automatic updater or choose another InstallDirectory.' +} +if ($InstallAsService -and (Get-Service -Name $ServiceName -ErrorAction SilentlyContinue)) { + throw "Windows Service '$ServiceName' already exists. Choose another ServiceName or uninstall the existing service first." +} +New-Item -ItemType Directory -Path $tempRoot -Force | Out-Null +New-Item -ItemType Directory -Path $releaseRoot -Force | Out-Null +New-Item -ItemType Directory -Path $releasesRoot -Force | Out-Null +$stage = $null +$versionRoot = $null + +try { + $release = Invoke-RestMethod -Method Get -Uri "$CentralUrl/api/updates/latest" -TimeoutSec 30 + if (-not $release.updatePublicKeyPem) { throw 'Central did not provide the signed release public key.' } + if (-not $release.signedManifest -or -not $release.manifestSignature) { throw 'The release has no signed manifest.' } + + $manifestBytes = [Convert]::FromBase64String([string]$release.signedManifest) + $signatureBytes = [Convert]::FromBase64String([string]$release.manifestSignature) + $manifestJson = [Text.Encoding]::UTF8.GetString($manifestBytes) + $manifest = $manifestJson | ConvertFrom-Json + if ([string]$manifest.version -ne [string]$release.version) { throw 'Release version differs from its signed manifest.' } + + if (-not (Test-EcdsaP256Signature $manifestBytes $signatureBytes ([string]$release.updatePublicKeyPem))) { + throw 'Release signature verification failed.' + } + + $assetPlatform = if ($manifest.assets.PSObject.Properties.Name -contains $platform) { $platform } + elseif ($manifest.assets.PSObject.Properties.Name -contains 'portable') { 'portable' } + else { throw "The signed release has no archive for $platform or portable .NET." } + $expectedHash = [string]$manifest.assets.$assetPlatform + if ($expectedHash -notmatch '^[A-Fa-f0-9]{64}$') { throw 'The signed archive digest is invalid.' } + $asset = $release.assets.$assetPlatform + if (-not $asset -or -not $asset.url -or -not $asset.sha256) { throw 'Central did not provide the signed Agent archive.' } + $assetUri = Assert-HttpsUrl ([string]$asset.url) 'Agent archive URL' + if ([string]$asset.sha256 -ine $expectedHash) { throw 'Release archive digest differs from the signed manifest.' } + + $archivePath = Join-Path $tempRoot 'agent.tar.gz' + Invoke-WebRequest -UseBasicParsing -Uri $assetUri.AbsoluteUri -OutFile $archivePath -TimeoutSec 600 + if ((Get-Sha256 $archivePath) -ine $expectedHash) { throw 'Downloaded Agent archive SHA-256 does not match the signed manifest.' } + + $supervisorPath = Join-Path $releaseRoot 'agent-update-supervisor.ps1' + $supervisorTemp = Join-Path $tempRoot 'agent-update-supervisor.ps1' + Invoke-WebRequest -UseBasicParsing -Uri "$CentralUrl/install/agent-update-supervisor.ps1" -OutFile $supervisorTemp -TimeoutSec 30 + if (-not (Test-Path -LiteralPath $supervisorTemp -PathType Leaf)) { throw 'Windows update supervisor download failed.' } + + $dotnet = Get-Command dotnet -ErrorAction SilentlyContinue + $runtimeInfo = if ($dotnet) { & dotnet --list-runtimes } else { @() } + $runtimeRoot = Join-Path $releaseRoot 'runtime' + if (-not ($runtimeInfo -match 'Microsoft.AspNetCore.App 10\.')) { + if ($SkipRuntimeInstall) { throw '.NET 10 ASP.NET Core Runtime is required but not installed.' } + $bootstrap = Join-Path $tempRoot 'dotnet-install.ps1' + Invoke-WebRequest -UseBasicParsing -Uri 'https://dot.net/v1/dotnet-install.ps1' -OutFile $bootstrap -TimeoutSec 30 + Unblock-File -LiteralPath $bootstrap + & $bootstrap -Runtime aspnetcore -Channel '10.0' -InstallDir $runtimeRoot + if ($LASTEXITCODE -ne 0) { throw '.NET 10 ASP.NET Core Runtime installation failed.' } + $env:PATH = "$runtimeRoot;$env:PATH" + $env:DOTNET_ROOT = $runtimeRoot + } + $dotnetInfo = & dotnet --list-runtimes + if (-not ($dotnetInfo -match 'Microsoft.AspNetCore.App 10\.')) { + throw 'The Agent requires the .NET 10 ASP.NET Core Runtime. Install it and run this installer again.' + } + + if (-not (Get-Command ffmpeg -ErrorAction SilentlyContinue)) { + $winget = Get-Command winget -ErrorAction SilentlyContinue + if (-not $winget) { throw 'FFmpeg is required for camera capture. Install FFmpeg and add it to PATH, then run this command again.' } + $answer = Read-Host 'FFmpeg is required for camera capture. Install it now with WinGet? [Y/n]' + if ($answer -and $answer -notmatch '^(y|yes)$') { throw 'FFmpeg installation was declined.' } + if ($InstallAsService) { + & winget install --exact --id Gyan.FFmpeg --scope machine --accept-package-agreements --accept-source-agreements + } + else { + & winget install --exact --id Gyan.FFmpeg --accept-package-agreements --accept-source-agreements + } + if ($LASTEXITCODE -ne 0) { throw 'WinGet could not install FFmpeg.' } + $env:PATH = [Environment]::GetEnvironmentVariable('Path', 'Machine') + ';' + + [Environment]::GetEnvironmentVariable('Path', 'User') + if (-not (Get-Command ffmpeg -ErrorAction SilentlyContinue)) { + throw 'FFmpeg was installed but is not available in this PowerShell session. Open a new terminal and run the install command again.' + } + } + + $listing = & tar.exe -tzf $archivePath + if ($LASTEXITCODE -ne 0 -or $listing.Count -gt 20000 -or (Get-Item $archivePath).Length -gt 2GB) { + throw 'Cannot inspect the Agent archive or it exceeds extraction limits.' + } + foreach ($entry in $listing) { + $normalized = $entry.Replace('\', '/') + if ($normalized.StartsWith('/') -or $normalized -match '^[A-Za-z]:' -or + ($normalized -split '/') -contains '..') { + throw 'Agent archive contains an unsafe path.' + } + } + $verboseListing = & tar.exe -tvzf $archivePath + if ($LASTEXITCODE -ne 0 -or @($verboseListing | Where-Object { $_ -match '^[lh][rwx-]{9}\s' }).Count -gt 0) { + throw 'Agent archive contains a link or unsupported entry.' + } + $stage = Join-Path $releasesRoot ('.staging-' + [Guid]::NewGuid().ToString('N')) + New-Item -ItemType Directory -Path $stage | Out-Null + & tar.exe -xzf $archivePath -C $stage + if ($LASTEXITCODE -ne 0 -or -not (Test-Path (Join-Path $stage 'Heimdall.Agent.dll'))) { + Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue + throw 'Agent archive extraction failed or did not contain Heimdall.Agent.dll.' + } + + $versionLeaf = ([string]$release.version).TrimStart('v', 'V') + if ($versionLeaf -notmatch '^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$') { throw 'Invalid signed release version.' } + $versionRoot = Join-Path $releasesRoot $versionLeaf + if (Test-Path -LiteralPath $versionRoot) { throw "Release $versionLeaf is already installed." } + Move-Item -LiteralPath $stage -Destination $versionRoot + Copy-Item -LiteralPath $versionRoot -Destination $releasePath -Recurse + + Move-Item -LiteralPath $supervisorTemp -Destination $supervisorPath -Force + + $stateDirectory = Join-Path $releaseRoot 'state' + New-Item -ItemType Directory -Path $stateDirectory -Force | Out-Null + $env:ASPNETCORE_URLS = 'http://127.0.0.1:8081' + if ($InstallAsService) { + $publicKeyPath = Join-Path $releaseRoot 'update-public-key.pem' + Set-Content -LiteralPath $publicKeyPath -Value ([string]$release.updatePublicKeyPem) -Encoding Ascii + $binaryPath = '"{0}" "{1}"' -f (Get-Command dotnet).Source, (Join-Path $releasePath 'Heimdall.Agent.dll') + New-Service -Name $ServiceName -DisplayName "Heimdall Agent ($AgentName)" -Description "Heimdall camera agent for site $AgentName" ` + -BinaryPathName $binaryPath -StartupType Automatic | Out-Null + + $serviceKey = "HKLM:\SYSTEM\CurrentControlSet\Services\$ServiceName" + $environment = @( + "ASPNETCORE_URLS=http://127.0.0.1:8081", + 'ASPNETCORE_ENVIRONMENT=Production', + "Agent__CentralUrl=$CentralUrl", + "Agent__SiteToken=$SiteToken", + "Agent__AgentName=$AgentName", + "Agent__StateDirectory=$stateDirectory", + "Agent__UpdateInstallRoot=$releaseRoot", + "Agent__UpdatePublicKeyPath=$publicKeyPath", + "Agent__UpdateSupervisorPath=$supervisorPath", + "Agent__UpdateWindowsServiceName=$ServiceName" + ) + New-ItemProperty -LiteralPath $serviceKey -Name Environment -PropertyType MultiString -Value $environment -Force | Out-Null + + # Environment contains the enrollment token. Restrict registry access and files to SYSTEM and administrators. + $registryAcl = New-Object Security.AccessControl.RegistrySecurity + $registryAcl.SetAccessRuleProtection($true, $false) + $registryAcl.SetOwner([Security.Principal.NTAccount]::new('BUILTIN\Administrators')) + $registryAcl.AddAccessRule([Security.AccessControl.RegistryAccessRule]::new('NT AUTHORITY\SYSTEM', 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')) + $registryAcl.AddAccessRule([Security.AccessControl.RegistryAccessRule]::new('BUILTIN\Administrators', 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')) + Set-Acl -LiteralPath $serviceKey -AclObject $registryAcl + + $rootAcl = New-Object Security.AccessControl.DirectorySecurity + $rootAcl.SetAccessRuleProtection($true, $false) + $rootAcl.SetOwner([Security.Principal.NTAccount]::new('BUILTIN\Administrators')) + $rootAcl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new('NT AUTHORITY\SYSTEM', 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')) + $rootAcl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new('BUILTIN\Administrators', 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')) + Set-Acl -LiteralPath $releaseRoot -AclObject $rootAcl + + if ($InstallOnly) { + Write-Host "Installed Windows Service '$ServiceName'. Start it with: Start-Service -Name '$ServiceName'" + return + } + Start-Service -Name $ServiceName + $deadline = [DateTime]::UtcNow.AddSeconds(180) + do { + try { + $health = Invoke-RestMethod -Method Get -Uri 'http://127.0.0.1:8081/api/version' -TimeoutSec 3 + if (([string]$health.version).Split('+')[0].TrimStart('v', 'V') -eq ([string]$release.version).TrimStart('v', 'V')) { + Write-Host "Windows Service '$ServiceName' started Heimdall Agent $($release.version)." + return + } + } + catch { } + Start-Sleep -Seconds 2 + } while ([DateTime]::UtcNow -lt $deadline) + Stop-Service -Name $ServiceName -Force -ErrorAction SilentlyContinue + throw "Windows Service '$ServiceName' failed its startup health check." + } + + if ($InstallOnly) { + Write-Host "Installed Heimdall Agent $($release.version) under '$releaseRoot'. Start it from PowerShell with the command shown by Central." + return + } + + $env:Agent__CentralUrl = $CentralUrl + $env:Agent__SiteToken = $SiteToken + $env:Agent__AgentName = $AgentName + $env:Agent__StateDirectory = $stateDirectory + $env:Agent__UpdatePublicKeyPem = [string]$release.updatePublicKeyPem + $env:Agent__UpdateInstallRoot = $releaseRoot + $env:Agent__UpdateSupervisorPath = $supervisorPath + Write-Host "Starting Heimdall Agent $($release.version) for site '$AgentName'. Press Ctrl+C to stop." + Push-Location $releasePath + try { & dotnet (Join-Path $releasePath 'Heimdall.Agent.dll') } + finally { Pop-Location } +} +finally { + if ($stage -and (Test-Path -LiteralPath $stage -PathType Container)) { + Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue + } + if ($versionRoot -and -not (Test-Path -LiteralPath $releasePath) -and + (Test-Path -LiteralPath $versionRoot -PathType Container)) { + Remove-Item -LiteralPath $versionRoot -Recurse -Force -ErrorAction SilentlyContinue + } + Remove-Item -LiteralPath $tempRoot -Recurse -Force -ErrorAction SilentlyContinue +} diff --git a/install/install-agent.sh b/install/install-agent.sh index 92e477b..a93fab7 100755 --- a/install/install-agent.sh +++ b/install/install-agent.sh @@ -1,13 +1,12 @@ #!/usr/bin/env bash # install-agent.sh — Heimdall Agent installer for Linux set -euo pipefail -CENTRAL_URL="" SITE_TOKEN="" AGENT_NAME="" STATE_DIR="/var/lib/heimdall" UPDATE_PUBLIC_KEY="" ALLOW_INSECURE_HTTP=false +CENTRAL_URL="" SITE_TOKEN="" AGENT_NAME="" STATE_DIR="/var/lib/heimdall" UPDATE_PUBLIC_KEY="" ALLOW_INSECURE_HTTP=false RUN_MODE=false INSTALL_ONLY=false INSTALL_ROOT="/opt/heimdall/agent" SERVICE_NAME="heimdall-agent" SERVICE_USER="heimdall" -while [[ $# -gt 0 ]]; do case "$1" in --central-url) CENTRAL_URL="$2"; shift 2;; --site-token) SITE_TOKEN="$2"; shift 2;; --update-public-key) UPDATE_PUBLIC_KEY="$2"; shift 2;; --agent-name) AGENT_NAME="$2"; shift 2;; --state-dir) STATE_DIR="$2"; shift 2;; --allow-insecure-http) ALLOW_INSECURE_HTTP=true; shift;; -h|--help) echo "Usage: $0 --central-url URL --site-token TOKEN --update-public-key LOCAL_PEM [--agent-name NAME] [--state-dir PATH] [--allow-insecure-http]"; exit 0;; *) echo "Unknown: $1" >&2; exit 1;; esac; done -[[ -z "$CENTRAL_URL" || -z "$SITE_TOKEN" || -z "$UPDATE_PUBLIC_KEY" ]] && { echo "Error: --central-url, --site-token and --update-public-key required" >&2; exit 1; } -[[ -f "$UPDATE_PUBLIC_KEY" ]] || { echo 'Publisher public key file is missing' >&2; exit 1; } -command -v jq >/dev/null && command -v openssl >/dev/null && command -v python3 >/dev/null && command -v dotnet >/dev/null || { echo 'jq, openssl, python3 and the .NET 10 runtime are required' >&2; exit 1; } -DOTNET_BIN=$(command -v dotnet) +while [[ $# -gt 0 ]]; do case "$1" in --central-url) CENTRAL_URL="$2"; shift 2;; --site-token) SITE_TOKEN="$2"; shift 2;; --update-public-key) UPDATE_PUBLIC_KEY="$2"; shift 2;; --agent-name) AGENT_NAME="$2"; shift 2;; --state-dir) STATE_DIR="$2"; shift 2;; --allow-insecure-http) ALLOW_INSECURE_HTTP=true; shift;; --run) RUN_MODE=true; shift;; --install-only) INSTALL_ONLY=true; shift;; -h|--help) echo "Usage: $0 --central-url URL --site-token TOKEN [--agent-name NAME] [--run | --install-only] [--update-public-key LOCAL_PEM] [--state-dir PATH] [--allow-insecure-http]"; exit 0;; *) echo "Unknown: $1" >&2; exit 1;; esac; done +[[ -z "$CENTRAL_URL" || -z "$SITE_TOKEN" ]] && { echo "Error: --central-url and --site-token are required" >&2; exit 1; } +[[ "$RUN_MODE" == true && "$INSTALL_ONLY" == true ]] && { echo '--run and --install-only cannot be combined' >&2; exit 1; } +if [[ -n "$UPDATE_PUBLIC_KEY" && ! -f "$UPDATE_PUBLIC_KEY" ]]; then echo 'Publisher public key file is missing' >&2; exit 1; fi CENTRAL_URL="${CENTRAL_URL%/}" if [[ "$CENTRAL_URL" != https://* && ! ( "$ALLOW_INSECURE_HTTP" == true && "$CENTRAL_URL" == http://* ) ]]; then echo "Error: --central-url must use HTTPS (or explicitly opt in with --allow-insecure-http on an isolated network)" >&2 @@ -16,7 +15,44 @@ fi ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) PLATFORM="linux-x64";; aarch64|arm64) PLATFORM="linux-arm64";; armv7l|armhf) PLATFORM="linux-arm";; *) echo "Unsupported: $ARCH" >&2; exit 1;; esac echo "Installing Heimdall Agent for $PLATFORM..." TMP_DIR=$(mktemp -d); trap 'rm -rf "$TMP_DIR"' EXIT +missing=() +for tool in curl jq openssl python3; do command -v "$tool" >/dev/null || missing+=("$tool"); done +if ((${#missing[@]})); then + if command -v apt-get >/dev/null; then + apt-get update -qq + DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "${missing[@]}" + elif command -v dnf >/dev/null; then + dnf install -y "${missing[@]}" + elif command -v apk >/dev/null; then + apk add --no-cache "${missing[@]}" + else + echo "Install these prerequisites and rerun: ${missing[*]}" >&2 + exit 1 + fi +fi +if command -v dotnet >/dev/null; then + DOTNET_BIN=$(command -v dotnet) +else + DOTNET_BIN="/opt/heimdall/dotnet/dotnet" + curl -fsSL --proto '=https' --proto-redir '=https' https://dot.net/v1/dotnet-install.sh -o "$TMP_DIR/dotnet-install.sh" + install -d -m 755 /opt/heimdall/dotnet + bash "$TMP_DIR/dotnet-install.sh" --channel 10.0 --runtime aspnetcore --install-dir /opt/heimdall/dotnet +fi +"$DOTNET_BIN" --list-runtimes | grep -q '^Microsoft.AspNetCore.App 10\.' || { + echo 'A compatible ASP.NET Core 10 runtime is required' >&2; exit 1; +} curl -fsS "$CENTRAL_URL/api/updates/latest" -o "$TMP_DIR/release.json" || { echo "Failed to fetch release" >&2; exit 1; } +if [[ -z "$UPDATE_PUBLIC_KEY" ]]; then + jq -er '.updatePublicKeyPem | select(type == "string" and length > 0 and length <= 4096)' "$TMP_DIR/release.json" > "$TMP_DIR/update-public-key.pem" || { + echo 'Central release metadata has no valid publisher public key' >&2; exit 1; + } + UPDATE_PUBLIC_KEY="$TMP_DIR/update-public-key.pem" +fi +openssl pkey -pubin -in "$UPDATE_PUBLIC_KEY" -noout >/dev/null || { echo 'Invalid publisher public key' >&2; exit 1; } +openssl pkey -pubin -in "$UPDATE_PUBLIC_KEY" -text -noout 2>/dev/null | grep -q 'ASN1 OID: prime256v1' || { + echo 'Publisher public key must use ECDSA P-256' >&2 + exit 1 +} jq -r '.signedManifest // empty' "$TMP_DIR/release.json" | base64 -d > "$TMP_DIR/manifest.json" || { echo 'Invalid signed manifest encoding' >&2; exit 1; } jq -r '.manifestSignature // empty' "$TMP_DIR/release.json" | base64 -d > "$TMP_DIR/manifest.sig" || { echo 'Invalid release signature encoding' >&2; exit 1; } openssl dgst -sha256 -verify "$UPDATE_PUBLIC_KEY" -signature "$TMP_DIR/manifest.sig" "$TMP_DIR/manifest.json" >/dev/null || { echo 'Release signature verification failed' >&2; exit 1; } @@ -63,16 +99,45 @@ sudo ln -sfn "$INSTALL_ROOT/releases/$VERSION" "$INSTALL_ROOT/current" sudo install -d -o root -g root -m 755 /etc/heimdall sudo install -o root -g root -m 644 "$UPDATE_PUBLIC_KEY" /etc/heimdall/update-public-key.pem sudo install -d -o root -g root -m 755 /usr/local/libexec -sudo install -o root -g root -m 755 "$(dirname "$0")/agent-supervisor.py" /usr/local/libexec/heimdall-agent-supervisor.py +SUPERVISOR_SOURCE="$(dirname "$0")/agent-supervisor.py" +if [[ ! -f "$SUPERVISOR_SOURCE" ]]; then + SUPERVISOR_SOURCE="$TMP_DIR/agent-supervisor.py" + curl -fsS "$CENTRAL_URL/install/agent-supervisor.py" -o "$SUPERVISOR_SOURCE" || { + echo 'Failed to download the Heimdall Agent supervisor from Central' >&2; exit 1; + } +fi +sudo install -o root -g root -m 755 "$SUPERVISOR_SOURCE" /usr/local/libexec/heimdall-agent-supervisor.py sudo install -d -o root -g root -m 700 /etc/heimdall/credentials printf '%s' "$SITE_TOKEN" | sudo tee /etc/heimdall/credentials/site-token >/dev/null sudo chmod 600 /etc/heimdall/credentials/site-token +sudo install -d -o "$SERVICE_USER" -g "$SERVICE_USER" -m 700 "$STATE_DIR/credentials" +printf '%s' "$SITE_TOKEN" | sudo tee "$STATE_DIR/credentials/site-token" >/dev/null +sudo chown "$SERVICE_USER:$SERVICE_USER" "$STATE_DIR/credentials/site-token" +sudo chmod 600 "$STATE_DIR/credentials/site-token" AGENT_NAME_CREDENTIAL="" if [[ -n "$AGENT_NAME" ]]; then printf '%s' "$AGENT_NAME" | sudo tee /etc/heimdall/credentials/agent-name >/dev/null sudo chmod 600 /etc/heimdall/credentials/agent-name + printf '%s' "$AGENT_NAME" | sudo tee "$STATE_DIR/credentials/agent-name" >/dev/null + sudo chown "$SERVICE_USER:$SERVICE_USER" "$STATE_DIR/credentials/agent-name" + sudo chmod 600 "$STATE_DIR/credentials/agent-name" AGENT_NAME_CREDENTIAL="LoadCredential=agent-name:/etc/heimdall/credentials/agent-name" fi +if [[ "$RUN_MODE" == true ]]; then + echo "Starting Heimdall Agent $VERSION in foreground; press Ctrl+C to stop." + sudo -u "$SERVICE_USER" env \ + CREDENTIALS_DIRECTORY="$STATE_DIR/credentials" \ + ASPNETCORE_URLS=http://127.0.0.1:8081 \ + HEIMDALL_DOTNET="$DOTNET_BIN" \ + ASPNETCORE_ENVIRONMENT=Production \ + Agent__CentralUrl="$CENTRAL_URL" \ + Agent__AllowInsecureHttp="$ALLOW_INSECURE_HTTP" \ + Agent__StateDirectory="$STATE_DIR" \ + Agent__UpdateInstallRoot="$INSTALL_ROOT" \ + Agent__UpdatePublicKeyPath=/etc/heimdall/update-public-key.pem \ + /usr/bin/python3 /usr/local/libexec/heimdall-agent-supervisor.py + exit $? +fi cat </dev/null [Unit] Description=Heimdall Agent @@ -97,5 +162,10 @@ $AGENT_NAME_CREDENTIAL [Install] WantedBy=multi-user.target EOF -sudo systemctl daemon-reload && sudo systemctl enable "$SERVICE_NAME" && sudo systemctl start "$SERVICE_NAME" -echo "Done! Version: $VERSION, Service: $SERVICE_NAME" +sudo systemctl daemon-reload && sudo systemctl enable "$SERVICE_NAME" +if [[ "$INSTALL_ONLY" == true ]]; then + echo "Installed version $VERSION and enabled $SERVICE_NAME. Start it with: sudo systemctl start $SERVICE_NAME" +else + sudo systemctl start "$SERVICE_NAME" + echo "Done! Version: $VERSION, Service: $SERVICE_NAME" +fi diff --git a/scripts/ci/publish.sh b/scripts/ci/publish.sh index d85e320..cc6b13a 100644 --- a/scripts/ci/publish.sh +++ b/scripts/ci/publish.sh @@ -31,6 +31,8 @@ openssl ec -in "$signing_key" -noout -text 2>/dev/null | grep -q 'ASN1 OID: prim echo 'Release signing key must use ECDSA P-256' >&2 exit 1 } +openssl pkey -in "$signing_key" -pubout -out artifacts/packages/agent-release-public.pem +(cd artifacts/packages && sha256sum agent-release-public.pem >> SHA256SUMS) tag=${BUILD_REF#refs/tags/} [[ "$BUILD_REF" == refs/tags/v* ]] || exit 1 python3 - "$sha" "$tag" <<'PY' diff --git a/src/Heimdall.Agent/AgentOptions.cs b/src/Heimdall.Agent/AgentOptions.cs index 901bef3..ae2b740 100644 --- a/src/Heimdall.Agent/AgentOptions.cs +++ b/src/Heimdall.Agent/AgentOptions.cs @@ -107,9 +107,18 @@ public sealed class AgentOptions /// Locally provisioned publisher public key; Central cannot change this setting. public string? UpdatePublicKeyPath { get; init; } + /// Publisher public key provisioned by the trusted installation flow. + public string? UpdatePublicKeyPem { get; init; } + /// Locally installed agent release root containing current and releases. public string? UpdateInstallRoot { get; init; } + /// Windows helper that replaces the running release after process shutdown and rolls back on failed health checks. + public string? UpdateSupervisorPath { get; init; } + + /// Optional Windows Service name; empty means a foreground console installation. + public string? UpdateWindowsServiceName { get; init; } + private static string? ReadSystemdCredential(string name) { var directory = Environment.GetEnvironmentVariable("CREDENTIALS_DIRECTORY"); diff --git a/src/Heimdall.Agent/Heimdall.Agent.csproj b/src/Heimdall.Agent/Heimdall.Agent.csproj index 1fdf67d..f647dc2 100644 --- a/src/Heimdall.Agent/Heimdall.Agent.csproj +++ b/src/Heimdall.Agent/Heimdall.Agent.csproj @@ -24,6 +24,7 @@ + diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index 003a38c..2c6d929 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -15,6 +15,8 @@ using Microsoft.Extensions.Options; using OpenTelemetry.Metrics; var builder = WebApplication.CreateSlimBuilder(args); +if (OperatingSystem.IsWindows()) + builder.Host.UseWindowsService(); // ── Sentry (GlitchTip) — DSN from config pipeline with legacy env var fallback ── // Primary: Sentry:Dsn from appsettings.json or env var Sentry__Dsn diff --git a/src/Heimdall.Agent/Services/AgentUpdateService.cs b/src/Heimdall.Agent/Services/AgentUpdateService.cs index 44e86cf..55906e9 100644 --- a/src/Heimdall.Agent/Services/AgentUpdateService.cs +++ b/src/Heimdall.Agent/Services/AgentUpdateService.cs @@ -1,4 +1,5 @@ using System.Net.Http.Json; +using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text.Json; @@ -14,6 +15,7 @@ namespace Heimdall.Agent.Services; /// public sealed class AgentUpdateService : BackgroundService { + private static readonly TimeSpan ReleaseStabilizationPeriod = TimeSpan.FromHours(24); private readonly AgentState _state; private readonly IOptions _options; private readonly IHttpClientFactory _httpClientFactory; @@ -30,7 +32,7 @@ public sealed class AgentUpdateService : BackgroundService public void SetCapturing(bool capturing) => _isCapturing = capturing; /// Runs an update check immediately when requested by Central. - public Task RequestUpdateAsync(CancellationToken ct = default) => CheckAndApplyUpdateAsync(ct); + public Task RequestUpdateAsync(CancellationToken ct = default) => CheckAndApplyUpdateAsync(ct, force: true); protected override async Task ExecuteAsync(CancellationToken stoppingToken) { @@ -56,12 +58,12 @@ public sealed class AgentUpdateService : BackgroundService } } - private async Task CheckAndApplyUpdateAsync(CancellationToken ct) + private async Task CheckAndApplyUpdateAsync(CancellationToken ct, bool force = false) { await _updateLock.WaitAsync(ct); try { - await CheckAndApplyUpdateCoreAsync(ct); + await CheckAndApplyUpdateCoreAsync(ct, force); } finally { @@ -69,14 +71,14 @@ public sealed class AgentUpdateService : BackgroundService } } - private async Task CheckAndApplyUpdateCoreAsync(CancellationToken ct) + private async Task CheckAndApplyUpdateCoreAsync(CancellationToken ct, bool force) { if (_isCapturing) { _logger.LogDebug("Capture active, deferring update"); return; } _logger.LogInformation("Checking for updates..."); var release = await FetchLatestReleaseAsync(ct); if (release is null) return; var signed = ReleaseSignatureVerifier.Verify(release.SignedManifest, release.ManifestSignature, - _options.Value.UpdatePublicKeyPath); + _options.Value.UpdatePublicKeyPath, _options.Value.UpdatePublicKeyPem); if (!string.Equals(signed.Version, release.Version, StringComparison.Ordinal)) throw new InvalidOperationException("Release version differs from the signed manifest"); var currentVersion = _options.Value.Version; @@ -84,6 +86,14 @@ public sealed class AgentUpdateService : BackgroundService _logger.LogInformation("Current: v{Current}, Remote: v{Remote}", currentVersion, remoteVersion); if (!IsNewerVersion(remoteVersion, currentVersion)) { _logger.LogInformation("Up to date (v{Version})", currentVersion); return; } + if (!force && (release.PublishedAt is null || + DateTimeOffset.UtcNow - release.PublishedAt.Value < ReleaseStabilizationPeriod)) + { + _logger.LogInformation( + "Deferring automatic update to v{Version}; release must be available for at least {Delay}", + remoteVersion, ReleaseStabilizationPeriod); + return; + } _logger.LogInformation("New version available: v{Remote}", remoteVersion); var platformKey = GetPlatformKey(); if (platformKey is null || @@ -95,13 +105,20 @@ public sealed class AgentUpdateService : BackgroundService !string.Equals(signedSha256, asset.Sha256, StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("Agent archive digest differs from the signed manifest"); var installRoot = _options.Value.UpdateInstallRoot; - if (!OperatingSystem.IsLinux() || string.IsNullOrWhiteSpace(installRoot)) - throw new InvalidOperationException("Native update requires a managed Linux installation root"); + if ((!OperatingSystem.IsLinux() && !OperatingSystem.IsWindows()) || string.IsNullOrWhiteSpace(installRoot)) + throw new InvalidOperationException("Native update requires a managed Linux or Windows installation root"); var tempPath = Path.Combine(Path.GetTempPath(), "heimdall-update-" + Guid.NewGuid().ToString("N") + ".tar.gz"); try { await DownloadAndVerifyAsync(asset.Url, signedSha256, tempPath, ct); - await NativeAgentPackageInstaller.ActivateAsync(tempPath, installRoot, signed.Version, ct); + if (OperatingSystem.IsLinux()) + { + await NativeAgentPackageInstaller.ActivateAsync(tempPath, installRoot, signed.Version, ct); + } + else + { + StartWindowsUpdateSupervisor(tempPath, signed.Version, signedSha256, installRoot); + } _logger.LogInformation("Updated from v{Old} to v{New}. Restarting...", currentVersion, remoteVersion); Environment.Exit(0); } @@ -110,6 +127,48 @@ public sealed class AgentUpdateService : BackgroundService finally { try { File.Delete(tempPath); } catch { } } } + private void StartWindowsUpdateSupervisor(string archivePath, string version, string sha256, string installRoot) + { + var supervisorPath = _options.Value.UpdateSupervisorPath; + if (string.IsNullOrWhiteSpace(supervisorPath) || !Path.IsPathFullyQualified(supervisorPath) || + !File.Exists(supervisorPath)) + throw new InvalidOperationException("The managed Windows update supervisor is missing"); + + var start = new ProcessStartInfo("powershell.exe") + { + UseShellExecute = false, + CreateNoWindow = true, + WorkingDirectory = installRoot, + }; + var arguments = new List + { + "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", supervisorPath, + "-AgentPid", Environment.ProcessId.ToString(System.Globalization.CultureInfo.InvariantCulture), + "-InstallRoot", installRoot, + "-ArchivePath", archivePath, + "-Version", version, + "-ExpectedSha256", sha256, + "-DotnetPath", Environment.ProcessPath is { } processPath && Path.GetFileNameWithoutExtension(processPath).Equals("dotnet", StringComparison.OrdinalIgnoreCase) + ? processPath + : "dotnet", + }; + var serviceName = _options.Value.UpdateWindowsServiceName; + if (!string.IsNullOrWhiteSpace(serviceName)) + { + if (serviceName.Length > 80 || serviceName.Any(c => !char.IsAsciiLetterOrDigit(c) && c is not '_' and not '-' and not '.')) + throw new InvalidOperationException("The configured Windows Agent service name is invalid"); + arguments.Add("-ServiceName"); + arguments.Add(serviceName); + } + foreach (var argument in arguments) + start.ArgumentList.Add(argument); + + using var process = Process.Start(start); + if (process is null) + throw new InvalidOperationException("Could not start the Windows Agent update supervisor"); + _logger.LogInformation("Windows update supervisor started for v{Version}", version); + } + private async Task FetchLatestReleaseAsync(CancellationToken ct) { try @@ -187,6 +246,10 @@ public sealed class AgentUpdateService : BackgroundService { [JsonPropertyName("version")] public string Version { get; set; } = string.Empty; + [JsonPropertyName("publishedAt")] + public DateTimeOffset? PublishedAt { get; set; } + [JsonPropertyName("updatePublicKeyPem")] + public string? UpdatePublicKeyPem { get; set; } [JsonPropertyName("assets")] public Dictionary Assets { get; set; } = []; [JsonPropertyName("signedManifest")] diff --git a/src/Heimdall.Agent/Services/ConfigReceiverService.cs b/src/Heimdall.Agent/Services/ConfigReceiverService.cs index 9f80ced..48afd72 100644 --- a/src/Heimdall.Agent/Services/ConfigReceiverService.cs +++ b/src/Heimdall.Agent/Services/ConfigReceiverService.cs @@ -269,7 +269,7 @@ public sealed class ConfigReceiverService : BackgroundService case "discovery.credentials": ApplyCredentialPool(value); break; - case "autoUpdateEnabled": + case "autoupdateenabled": if (bool.TryParse(value, out var autoUpdate)) { _options.AutoUpdateEnabled = autoUpdate; diff --git a/src/Heimdall.Agent/Services/DockerUpdateService.cs b/src/Heimdall.Agent/Services/DockerUpdateService.cs index d345553..be4da84 100644 --- a/src/Heimdall.Agent/Services/DockerUpdateService.cs +++ b/src/Heimdall.Agent/Services/DockerUpdateService.cs @@ -11,7 +11,6 @@ namespace Heimdall.Agent.Services; /// public sealed class DockerUpdateService : BackgroundService { - private static readonly TimeSpan CheckInterval = TimeSpan.FromHours(12); private readonly AgentOptions _options; private readonly AgentState _state; private readonly ContainerInfoProvider _containerInfo; @@ -21,18 +20,13 @@ public sealed class DockerUpdateService : BackgroundService public DockerUpdateService(IOptions options, AgentState state, ContainerInfoProvider containerInfo, IHttpClientFactory httpClientFactory, ILogger logger) { _options = options.Value; _state = state; _containerInfo = containerInfo; _httpClientFactory = httpClientFactory; _logger = logger; } - protected override async Task ExecuteAsync(CancellationToken stoppingToken) + protected override Task ExecuteAsync(CancellationToken stoppingToken) { var info = _containerInfo.Collect(); - if (!info.IsContainer) { _logger.LogDebug("Docker update: not in container, skipping"); return; } - _logger.LogInformation("Docker update service started (container {Id})", info.ContainerId); - using var timer = new PeriodicTimer(CheckInterval); - while (await timer.WaitForNextTickAsync(stoppingToken).ConfigureAwait(false)) - { - try { await CheckAndUpdateAsync(info, stoppingToken).ConfigureAwait(false); } - catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } - catch (Exception ex) { _logger.LogWarning(ex, "Docker update check failed"); } - } + _logger.LogInformation(info.IsContainer + ? "Automatic container updates are managed by Docker or Kubernetes; local image polling is disabled" + : "Docker update service is inactive outside a container"); + return Task.CompletedTask; } /// Runs a Docker image update check immediately when requested by Central. @@ -55,7 +49,7 @@ public sealed class DockerUpdateService : BackgroundService var release = await FetchLatestReleaseAsync(ct).ConfigureAwait(false); if (release is null) { _logger.LogWarning("Could not fetch latest release from Central"); return; } var signed = ReleaseSignatureVerifier.Verify(release.SignedManifest, release.ManifestSignature, - _options.UpdatePublicKeyPath); + _options.UpdatePublicKeyPath, _options.UpdatePublicKeyPem); if (!string.Equals(signed.Version, release.Version, StringComparison.Ordinal) || !string.Equals(signed.ContainerImage, release.ContainerImage, StringComparison.Ordinal) || !string.Equals(signed.ContainerImageDigest, release.ContainerImageDigest, StringComparison.OrdinalIgnoreCase)) @@ -256,6 +250,7 @@ public sealed class DockerUpdateService : BackgroundService private sealed class LatestUpdateResponse { [JsonPropertyName("version")] public string Version { get; init; } = string.Empty; + [JsonPropertyName("updatePublicKeyPem")] public string? UpdatePublicKeyPem { get; init; } [JsonPropertyName("containerImage")] public string? ContainerImage { get; init; } [JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; init; } [JsonPropertyName("signedManifest")] public string? SignedManifest { get; init; } diff --git a/src/Heimdall.Agent/Services/ReleaseSignatureVerifier.cs b/src/Heimdall.Agent/Services/ReleaseSignatureVerifier.cs index 907295f..04d1cf7 100644 --- a/src/Heimdall.Agent/Services/ReleaseSignatureVerifier.cs +++ b/src/Heimdall.Agent/Services/ReleaseSignatureVerifier.cs @@ -9,10 +9,12 @@ internal static class ReleaseSignatureVerifier { private static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = true }; - internal static SignedAgentRelease Verify(string? manifestBase64, string? signatureBase64, string? publicKeyPath) + internal static SignedAgentRelease Verify(string? manifestBase64, string? signatureBase64, + string? publicKeyPath, string? publicKeyPem = null) { - if (string.IsNullOrWhiteSpace(publicKeyPath) || !Path.IsPathFullyQualified(publicKeyPath)) - throw new InvalidOperationException("A local release public key path is required for updates"); + if (string.IsNullOrWhiteSpace(publicKeyPem) && + (string.IsNullOrWhiteSpace(publicKeyPath) || !Path.IsPathFullyQualified(publicKeyPath))) + throw new InvalidOperationException("A release public key is required for updates"); if (string.IsNullOrWhiteSpace(manifestBase64) || string.IsNullOrWhiteSpace(signatureBase64)) throw new InvalidOperationException("Release signature is missing"); @@ -31,7 +33,9 @@ internal static class ReleaseSignatureVerifier throw new InvalidOperationException("Release signature payload has invalid size"); using var verifier = ECDsa.Create(); - verifier.ImportFromPem(File.ReadAllText(publicKeyPath)); + verifier.ImportFromPem(string.IsNullOrWhiteSpace(publicKeyPem) + ? File.ReadAllText(publicKeyPath!) + : publicKeyPem); if (verifier.KeySize != 256 || !verifier.VerifyData(manifest, signature, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence)) throw new InvalidOperationException("Release signature is invalid"); diff --git a/src/Heimdall.Agent/packages.lock.json b/src/Heimdall.Agent/packages.lock.json index 1f96845..4044c80 100644 --- a/src/Heimdall.Agent/packages.lock.json +++ b/src/Heimdall.Agent/packages.lock.json @@ -33,6 +33,15 @@ "SQLitePCLRaw.core": "2.1.13" } }, + "Microsoft.Extensions.Hosting.WindowsServices": { + "type": "Direct", + "requested": "[10.0.13, )", + "resolved": "10.0.13", + "contentHash": "sk3VNcYEmgwYGPF4ze/112jpaeDKSsKGhmEZ8IlhOR8F6JT+1DYaZUb14jobVXiKhuXWIKcYXV7mkSPeA4dc3g==", + "dependencies": { + "System.ServiceProcess.ServiceController": "10.0.13" + } + }, "Microsoft.ML.OnnxRuntime": { "type": "Direct", "requested": "[1.22.0, )", @@ -299,6 +308,11 @@ "resolved": "9.0.0", "contentHash": "hyJB4UlpAi19Xr9AXzu2NuagKC4lPfHObNMEAA0HmqFz2rX7wKgzeYzO/jM/eBHDhnUGFFEjk5cOoJaxqg5J4A==" }, + "System.ServiceProcess.ServiceController": { + "type": "Transitive", + "resolved": "10.0.13", + "contentHash": "0Zh/U/1+hy1MCxx1BTikJi4L5o1Ys6VhB8PKlTNOB4/n2d6ua2+TuoD6T7xN9RV0uiOGod575pQrUSTXg+aYGQ==" + }, "heimdall.application": { "type": "Project", "dependencies": { diff --git a/src/Heimdall.Application/DTOs/SiteDto.cs b/src/Heimdall.Application/DTOs/SiteDto.cs index 89e2e5d..a706ba6 100644 --- a/src/Heimdall.Application/DTOs/SiteDto.cs +++ b/src/Heimdall.Application/DTOs/SiteDto.cs @@ -11,7 +11,7 @@ public record SiteResponse( string Timezone, string? NtfyTopic, bool Enabled, - bool AutoUpdateEnabled, + bool? AutoUpdateEnabled, DateTime CreatedAt); public record SiteWithTokenResponse( diff --git a/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs b/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs index 283f4d9..db7e3fb 100644 --- a/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs +++ b/src/Heimdall.Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs @@ -39,19 +39,34 @@ public class GetEffectiveAgentConfigQueryHandler .Where(s => s.AgentId == request.AgentId && _db.AppSettings.Any(a => a.Key == s.Key && a.AgentScoped)) .ToListAsync(ct); - foreach (var s in agentSettings) + foreach (var s in agentSettings.Where(s => !string.Equals(s.Key, "autoupdateenabled", StringComparison.OrdinalIgnoreCase))) config[s.Key] = s.Value; + var agent = await _db.Agents + .AsNoTracking() + .FirstOrDefaultAsync(a => a.Id == request.AgentId, ct) + .ConfigureAwait(false); + + if (agent is not null) + { + var siteAutoUpdate = await _db.Sites + .AsNoTracking() + .Where(s => s.Id == agent.SiteId) + .Select(s => s.AutoUpdateEnabled) + .FirstOrDefaultAsync(ct) + .ConfigureAwait(false); + + if (siteAutoUpdate.HasValue) + config["autoupdateenabled"] = siteAutoUpdate.Value ? "true" : "false"; + else if (!config.ContainsKey("autoupdateenabled")) + config["autoupdateenabled"] = "false"; + } + // ── 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 diff --git a/src/Heimdall.Domain/Entities/Site.cs b/src/Heimdall.Domain/Entities/Site.cs index f0edef6..fc8bb74 100644 --- a/src/Heimdall.Domain/Entities/Site.cs +++ b/src/Heimdall.Domain/Entities/Site.cs @@ -12,8 +12,8 @@ public class Site : Entity, IAuditableEntity, ISoftDeletable /// Topic ntfy dédié pour les notifications de ce site (null → topic personnel utilisateur). public string? NtfyTopic { get; private set; } - /// Enable automatic agent updates from the central server. - public bool AutoUpdateEnabled { get; private set; } + /// Site-level automatic update override; null inherits the global Agent setting. + public bool? AutoUpdateEnabled { get; private set; } /// Hashed registration token (SHA256) for agent enrollment. public string? RegistrationTokenHash { get; private set; } @@ -57,8 +57,7 @@ public class Site : Entity, IAuditableEntity, ISoftDeletable Address = address; Timezone = timezone ?? Timezone; NtfyTopic = ntfyTopic; - if (autoUpdate.HasValue) - AutoUpdateEnabled = autoUpdate.Value; + AutoUpdateEnabled = autoUpdate; } public void GenerateRegistrationToken(string tokenHash, DateTime expiresAt) @@ -75,7 +74,7 @@ public class Site : Entity, IAuditableEntity, ISoftDeletable public void SetEnabled(bool enabled) => Enabled = enabled; - public void SetAutoUpdate(bool enabled) => AutoUpdateEnabled = enabled; + public void SetAutoUpdate(bool? enabled) => AutoUpdateEnabled = enabled; public void SoftDelete() { diff --git a/src/Heimdall.Infrastructure/Data/Configurations/SiteConfiguration.cs b/src/Heimdall.Infrastructure/Data/Configurations/SiteConfiguration.cs index 20a438c..6e63bb9 100644 --- a/src/Heimdall.Infrastructure/Data/Configurations/SiteConfiguration.cs +++ b/src/Heimdall.Infrastructure/Data/Configurations/SiteConfiguration.cs @@ -25,6 +25,9 @@ public class SiteConfiguration : IEntityTypeConfiguration .HasDefaultValue("UTC") .IsUnicode(false); + builder.Property(s => s.AutoUpdateEnabled) + .IsRequired(false); + builder.Property(s => s.RegistrationTokenHash) .HasMaxLength(128) .IsUnicode(false); diff --git a/src/Heimdall.Infrastructure/Migrations/20261026130000_AgentAutoUpdateOverride.Designer.cs b/src/Heimdall.Infrastructure/Migrations/20261026130000_AgentAutoUpdateOverride.Designer.cs new file mode 100644 index 0000000..9f4b34a --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261026130000_AgentAutoUpdateOverride.Designer.cs @@ -0,0 +1,2832 @@ +// +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("20261026130000_AgentAutoUpdateOverride")] + partial class AgentAutoUpdateOverride : Migration + { + 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("Arch") + .HasColumnType("text"); + + b.Property("ContainerCpuLimit") + .HasColumnType("bigint"); + + b.Property("ContainerId") + .HasColumnType("text"); + + b.Property("ContainerImage") + .HasColumnType("text"); + + b.Property("ContainerMemoryLimitBytes") + .HasColumnType("bigint"); + + b.Property("CpuArchitecture") + .HasColumnType("text"); + + b.Property("CpuCacheBytes") + .HasColumnType("bigint"); + + b.Property("CpuCores") + .HasColumnType("integer"); + + b.Property("CpuFlags") + .HasColumnType("text"); + + b.Property("CpuFrequencyMhz") + .HasColumnType("double precision"); + + b.Property("CpuModel") + .HasColumnType("text"); + + b.Property("CpuUsagePercent") + .HasColumnType("double precision"); + + b.Property("CpuVendor") + .HasColumnType("text"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DiskInventoryJson") + .HasColumnType("text"); + + b.Property("DiskUsagePercent") + .HasColumnType("double precision"); + + b.Property("GpuInventoryJson") + .HasColumnType("text"); + + b.Property("GpuLoadPercent") + .HasColumnType("double precision"); + + b.Property("GpuName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + 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("KernelVersion") + .HasColumnType("text"); + + b.Property("LastAppliedCameraConfigAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastAppliedCameraConfigVersion") + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("LastHeartbeat") + .HasColumnType("timestamp with time zone"); + + b.Property("LogicalCores") + .HasColumnType("integer"); + + b.Property("MemAvailableBytes") + .HasColumnType("bigint"); + + b.Property("MemTotalBytes") + .HasColumnType("bigint"); + + b.Property("MemoryMb") + .HasColumnType("bigint"); + + b.Property("MemoryUsageBytes") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("NetworkInterfacesJson") + .HasColumnType("text"); + + b.Property("OsName") + .HasColumnType("text"); + + b.Property("PhysicalCores") + .HasColumnType("integer"); + + 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("SwapFreeBytes") + .HasColumnType("bigint"); + + b.Property("SwapTotalBytes") + .HasColumnType("bigint"); + + b.Property("TemperatureJson") + .HasColumnType("text"); + + b.Property("ThreadsPerCore") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UptimeMachineSeconds") + .HasColumnType("bigint"); + + b.Property("UptimeSeconds") + .HasColumnType("bigint"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("VramMb") + .HasColumnType("bigint"); + + b.Property("VramUsageBytes") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("LastHeartbeat") + .HasFilter("\"Status\" = 'Online'"); + + b.HasIndex("SiteId"); + + b.ToTable("agents", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentLogEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("Exception") + .HasMaxLength(4000) + .HasColumnType("character varying(4000)"); + + b.Property("Level") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("Source") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("TimestampUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("AgentId", "TimestampUtc"); + + b.ToTable("agent_log_entries", (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.AnalysisJob", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AssignedAgentId") + .HasColumnType("uuid"); + + b.Property("AttemptId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CompletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DispatchedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ErrorMessage") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("JobType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("MaxExecutionTime") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(3000000000L); + + b.Property("MaxRetries") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(3); + + b.Property("ParametersJson") + .HasColumnType("jsonb"); + + b.Property("Priority") + .HasColumnType("integer"); + + b.Property("RequiredCpuCores") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("RequiredMemoryMb") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(0L); + + b.Property("RequiresGpu") + .HasColumnType("boolean"); + + b.Property("ResultJson") + .HasColumnType("jsonb"); + + b.Property("RetryCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("StartedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("character varying(30)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("CameraId") + .HasDatabaseName("ix_analysis_jobs_camera"); + + b.HasIndex("AssignedAgentId", "Status") + .HasDatabaseName("ix_analysis_jobs_agent_workload") + .HasFilter("\"AssignedAgentId\" IS NOT NULL"); + + b.HasIndex("Status", "DispatchedAt") + .HasDatabaseName("ix_analysis_jobs_timeout"); + + b.HasIndex("Status", "Priority", "CreatedAt") + .HasDatabaseName("ix_analysis_jobs_pending"); + + b.ToTable("analysis_jobs", (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("StoragePolicyId") + .HasColumnType("uuid"); + + 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.HasIndex("StoragePolicyId"); + + 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("ExecutionProfileJson") + .HasColumnType("text"); + + 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("DiscoveryMethod") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("HomeKitDeviceId") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("HomeKitCategory") + .HasColumnType("integer"); + + b.Property("HomeKitIsPaired") + .HasColumnType("boolean"); + + b.Property("HomeKitPort") + .HasColumnType("integer"); + + b.Property("HomeKitModel") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HomeKitName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("Hostname") + .HasMaxLength(255) + .IsUnicode(false) + .HasColumnType("character varying(255)"); + + b.Property("HttpPort") + .HasColumnType("integer"); + + b.Property("HttpServerHeader") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("HttpStatusCode") + .HasColumnType("integer"); + + b.Property("IpAddress") + .IsRequired() + .HasMaxLength(45) + .IsUnicode(false) + .HasColumnType("character varying(45)"); + + b.Property("IsHomeKitCamera") + .HasColumnType("boolean"); + + b.Property("IsProcessed") + .HasColumnType("boolean"); + + b.Property("IsReachable") + .HasColumnType("boolean"); + + b.Property("MacAddress") + .HasMaxLength(17) + .IsUnicode(false) + .HasColumnType("character varying(17)"); + + b.Property("OnvifDeviceServiceUrl") + .HasMaxLength(500) + .IsUnicode(false) + .HasColumnType("character varying(500)"); + + b.Property("OnvifHardware") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifName") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("OnvifPort") + .HasColumnType("integer"); + + b.PrimitiveCollection("OpenPorts") + .IsRequired() + .IsUnicode(false) + .HasColumnType("integer[]"); + + b.Property("ProbedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Vendor") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.HasKey("Id"); + + b.HasIndex("IpAddress"); + + b.HasIndex("IsProcessed"); + + b.HasIndex("SiteId"); + + b.ToTable("camera_discovery_results", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("OccurredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("Confidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DetectionHash") + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("IsSuppressed") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("Label") + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.Property("MetadataJson") + .HasColumnType("jsonb"); + + b.Property("ParentEventId") + .HasColumnType("uuid"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("RecordingId") + .HasColumnType("uuid"); + + b.Property("SnapshotThumbUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotObjectKey") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotThumbObjectKey") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotStorageProvider") + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("SnapshotStorageRoot") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotStorageEndpoint") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("SnapshotStorageBucket") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("SnapshotUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("TrackId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Type") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("VehicleId") + .HasColumnType("uuid"); + + b.HasKey("Id", "OccurredAt"); + + b.HasIndex("DetectionHash"); + + b.HasIndex("MetadataJson"); + + NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("MetadataJson"), "gin"); + NpgsqlIndexBuilderExtensions.HasOperators(b.HasIndex("MetadataJson"), new[] { "jsonb_path_ops" }); + + b.HasIndex("OccurredAt"); + + b.HasIndex("ParentEventId"); + + b.HasIndex("PersonId", "OccurredAt"); + + b.HasIndex("RecordingId"); + + b.HasIndex("TrackId"); + + b.HasIndex("VehicleId"); + + b.HasIndex("CameraId", "OccurredAt") + .IsDescending(false, true); + + b.HasIndex("CameraId", "Type"); + + b.ToTable("camera_events", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.PrimitiveCollection("Codecs") + .IsRequired() + .IsUnicode(false) + .HasColumnType("text[]"); + + b.Property("DiscoveryResultId") + .HasColumnType("uuid"); + + b.Property("Height") + .HasColumnType("integer"); + + b.Property("IsAlive") + .HasColumnType("boolean"); + + b.Property("IsMainStream") + .HasColumnType("boolean"); + + b.Property("LatencyMs") + .HasColumnType("bigint"); + + b.Property("Protocol") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Url") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("Width") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DiscoveryResultId"); + + b.HasIndex("IsAlive"); + + b.HasIndex("IsMainStream"); + + b.ToTable("discovered_streams", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("IsDeleted") + .HasFilter("\"IsDeleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("groups", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.GroupCameraAccess", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("CameraId"); + + b.HasIndex("GroupId", "CameraId") + .IsUnique(); + + b.ToTable("group_camera_accesses", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Embedding") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("SourceEventId") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("ThumbnailUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("PersonId"); + + b.ToTable("known_faces", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LicensePlate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Confidence") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("PlateText") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("VehicleId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("PersonId"); + + b.HasIndex("PlateText"); + + NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("PlateText"), "gin"); + NpgsqlIndexBuilderExtensions.HasOperators(b.HasIndex("PlateText"), new[] { "gin_trgm_ops" }); + + b.HasIndex("VehicleId"); + + b.ToTable("license_plates", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LoginChallenge", b => + { + b.Property("Id") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Verifying") + .HasColumnType("boolean"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("Consumed") + .HasColumnType("boolean"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SecurityStamp") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("UserId"); + + b.ToTable("login_challenges", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ManualSnapshotRequest", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("AgentId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("FailureReason") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("CameraId", "CreatedAt"); + + b.HasIndex("ExpiresAt"); + + b.ToTable("manual_snapshot_requests", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Notification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsRead") + .HasColumnType("boolean"); + + b.Property("Link") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("ReadAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("SnapshotUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "IsRead"); + + b.ToTable("notifications", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.NotificationDelivery", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DeliveredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastErrorType") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("LeaseExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("NextAttemptAt") + .HasColumnType("timestamp with time zone"); + + b.Property("NotificationId") + .HasColumnType("uuid"); + + b.Property("Priority") + .HasColumnType("integer"); + + b.Property("Recipient") + .IsRequired() + .HasMaxLength(320) + .HasColumnType("character varying(320)"); + + b.Property("ServiceUrl") + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("Status", "NextAttemptAt", "LeaseExpiresAt") + .HasDatabaseName("ix_notification_deliveries_dispatch"); + + b.HasIndex("NotificationId", "Channel") + .IsUnique() + .HasDatabaseName("ux_notification_deliveries_notification_channel"); + + b.ToTable("notification_deliveries", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.NotificationTemplate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("BodyMarkdown") + .IsRequired() + .HasColumnType("text"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("EventType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("IsDefault") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("Subject") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("EventType", "Channel", "Language") + .IsUnique(); + + b.ToTable("notification_templates", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Person", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Category") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("IsWatchlisted") + .HasColumnType("boolean"); + + b.Property("Notes") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("PhotoUrl") + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Category"); + + b.HasIndex("DisplayName"); + + b.HasIndex("IsWatchlisted"); + + b.ToTable("persons", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Recording", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DurationSeconds") + .ValueGeneratedOnAdd() + .HasColumnType("double precision") + .HasDefaultValue(0.0); + + b.Property("SizeBytes") + .HasColumnType("bigint"); + + b.Property("StorageBucket") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("StorageEndpoint") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("StoragePath") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("StorageRoot") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("StorageLocationCaptured") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("StoragePolicyId") + .HasColumnType("uuid"); + + b.Property("StorageProvider") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Timestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("StoragePath") + .IsUnique(); + + b.HasIndex("StoragePolicyId"); + + b.HasIndex("CameraId", "Timestamp"); + + b.ToTable("recordings", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.RevokedRefreshToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("RevokedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("character varying(128)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ExpiresAt"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("revoked_refresh_tokens", (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("AutoUpdateEnabled") + .HasColumnType("boolean"); + + 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("NtfyTopic") + .HasColumnType("text"); + + 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("\"IsDeleted\" = false"); + + b.HasIndex("Name"); + + b.ToTable("sites", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.SiteCredential", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Password") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(200) + .IsUnicode(false) + .HasColumnType("character varying(200)"); + + b.HasKey("Id"); + + b.HasIndex("SiteId"); + + b.ToTable("site_credentials", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.StoragePolicy", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("RetentionDays") + .HasColumnType("integer"); + + b.Property("StorageProvider") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.ToTable("storage_policies", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.StorageDestination", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("FirstSeenAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("LocalRoot") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("S3Bucket") + .IsRequired() + .HasMaxLength(256) + .IsUnicode(false) + .HasColumnType("character varying(256)"); + + b.Property("S3Endpoint") + .IsRequired() + .HasMaxLength(2000) + .IsUnicode(false) + .HasColumnType("character varying(2000)"); + + b.HasKey("Id"); + + b.HasIndex("Provider") + .HasDatabaseName("ix_storage_destinations_provider"); + + b.ToTable("storage_destinations", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCamera", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "CameraId"); + + b.HasIndex("CameraId"); + + b.HasIndex("UserId"); + + b.ToTable("user_cameras", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("SiteId") + .HasColumnType("uuid"); + + b.Property("CameraId") + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("UserId", "SiteId", "CameraId"); + + b.HasIndex("CameraId"); + + b.HasIndex("SiteId"); + + b.ToTable("UserCameraAccesses", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "GroupId"); + + b.HasIndex("GroupId"); + + b.ToTable("user_groups", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserNotificationConfig", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("DailyDigest") + .HasColumnType("boolean"); + + b.Property("EmailAddress") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("EmailEnabled") + .HasColumnType("boolean"); + + b.Property("Language") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasDefaultValue("fr"); + + b.Property("NtfyEnabled") + .HasColumnType("boolean"); + + b.Property("NtfyTopic") + .HasColumnType("text"); + + b.Property("NtfyUrl") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("SubscribedEventsJson") + .HasColumnType("jsonb") + .HasColumnName("subscribed_events"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("WeeklyDigest") + .HasColumnType("boolean"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("user_notification_configs", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserRecoveryCode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CodeHash") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("UsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("UserId", "CodeHash") + .IsUnique(); + + b.ToTable("user_recovery_codes", (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("Heimdall.Domain.Entities.Vehicle", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Color") + .HasMaxLength(50) + .IsUnicode(false) + .HasColumnType("character varying(50)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.Property("LicensePlate") + .HasMaxLength(20) + .IsUnicode(false) + .HasColumnType("character varying(20)"); + + b.Property("Make") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("Model") + .HasMaxLength(100) + .IsUnicode(false) + .HasColumnType("character varying(100)"); + + b.Property("PersonId") + .HasColumnType("uuid"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("LicensePlate"); + + b.HasIndex("PersonId"); + + b.ToTable("vehicles", (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("UserId") + .HasColumnType("uuid"); + + b.Property("RoleId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("user_roles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("user_tokens", (string)null); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.NotificationDelivery", b => + { + b.HasOne("Heimdall.Domain.Entities.Notification", null) + .WithMany() + .HasForeignKey("NotificationId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Agents") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentLogEntry", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AgentSetting", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Agent"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AnalysisJob", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "AssignedAgent") + .WithMany() + .HasForeignKey("AssignedAgentId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AssignedAgent"); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.ApiKey", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AuditLog", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany("Cameras") + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Cameras") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.StoragePolicy", "StoragePolicy") + .WithMany() + .HasForeignKey("StoragePolicyId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Agent"); + + b.Navigation("Site"); + + b.Navigation("StoragePolicy"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraAssignment", b => + { + b.HasOne("Heimdall.Domain.Entities.Agent", "Agent") + .WithMany() + .HasForeignKey("AgentId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Agent"); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraCredentials", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("Credentials") + .HasForeignKey("Heimdall.Domain.Entities.CameraCredentials", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDetectionProfile", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithOne("DetectionProfile") + .HasForeignKey("Heimdall.Domain.Entities.CameraDetectionProfile", "CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraEvent", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.DiscoveredStreamUrl", b => + { + b.HasOne("Heimdall.Domain.Entities.CameraDiscoveryResult", "DiscoveryResult") + .WithMany("DiscoveredStreams") + .HasForeignKey("DiscoveryResultId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DiscoveryResult"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.GroupCameraAccess", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany("GroupCameraAccesses") + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.Group", "Group") + .WithMany("GroupCameraAccesses") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + + b.Navigation("Group"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.KnownFace", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany("Faces") + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Person"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LicensePlate", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany() + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Heimdall.Domain.Entities.Vehicle", "Vehicle") + .WithMany() + .HasForeignKey("VehicleId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Person"); + + b.Navigation("Vehicle"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.LoginChallenge", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Recording", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.StoragePolicy", "StoragePolicy") + .WithMany() + .HasForeignKey("StoragePolicyId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Camera"); + + b.Navigation("StoragePolicy"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.SiteCredential", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany("Credentials") + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCamera", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserCameraAccess", b => + { + b.HasOne("Heimdall.Domain.Entities.Camera", "Camera") + .WithMany() + .HasForeignKey("CameraId") + .OnDelete(DeleteBehavior.Cascade); + + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Camera"); + + b.Navigation("Site"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserGroup", b => + { + b.HasOne("Heimdall.Domain.Entities.Group", "Group") + .WithMany("UserGroups") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany("UserGroups") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Group"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.UserSite", b => + { + b.HasOne("Heimdall.Domain.Entities.Site", "Site") + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", "User") + .WithMany("UserSites") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Site"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Vehicle", b => + { + b.HasOne("Heimdall.Domain.Entities.Person", "Person") + .WithMany() + .HasForeignKey("PersonId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Person"); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Heimdall.Domain.Entities.AppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Heimdall.Domain.Entities.AppRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Heimdall.Domain.Entities.AppUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Agent", b => + { + b.Navigation("Cameras"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.AppUser", b => + { + b.Navigation("UserGroups"); + + b.Navigation("UserSites"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Camera", b => + { + b.Navigation("Credentials"); + + b.Navigation("DetectionProfile"); + + b.Navigation("GroupCameraAccesses"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.CameraDiscoveryResult", b => + { + b.Navigation("DiscoveredStreams"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Group", b => + { + b.Navigation("GroupCameraAccesses"); + + b.Navigation("UserGroups"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Person", b => + { + b.Navigation("Faces"); + }); + + modelBuilder.Entity("Heimdall.Domain.Entities.Site", b => + { + b.Navigation("Agents"); + + b.Navigation("Cameras"); + + b.Navigation("Credentials"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/20261026130000_AgentAutoUpdateOverride.cs b/src/Heimdall.Infrastructure/Migrations/20261026130000_AgentAutoUpdateOverride.cs new file mode 100644 index 0000000..450d4a9 --- /dev/null +++ b/src/Heimdall.Infrastructure/Migrations/20261026130000_AgentAutoUpdateOverride.cs @@ -0,0 +1,38 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Heimdall.Infrastructure.Migrations; + +public partial class AgentAutoUpdateOverride : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "AutoUpdateEnabled", + table: "sites", + type: "boolean", + nullable: true, + oldClrType: typeof(bool), + oldType: "boolean", + oldDefaultValue: false); + + // Preserve every existing site choice. NULL is reserved for sites created + // after this migration or explicitly changed to inherit in the UI. + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.Sql("UPDATE sites SET \"AutoUpdateEnabled\" = FALSE WHERE \"AutoUpdateEnabled\" IS NULL"); + + migrationBuilder.AlterColumn( + name: "AutoUpdateEnabled", + table: "sites", + type: "boolean", + nullable: false, + defaultValue: false, + oldClrType: typeof(bool), + oldType: "boolean", + oldNullable: true); + } +} diff --git a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index e3381d3..c02663a 100644 --- a/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/src/Heimdall.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -1,4 +1,4 @@ -// +// using System; using Heimdall.Infrastructure.Data; using Microsoft.EntityFrameworkCore; @@ -1933,7 +1933,7 @@ namespace Heimdall.Infrastructure.Migrations .HasMaxLength(500) .HasColumnType("character varying(500)"); - b.Property("AutoUpdateEnabled") + b.Property("AutoUpdateEnabled") .HasColumnType("boolean"); b.Property("CreatedAt") diff --git a/src/Heimdall.Web/Components/Pages/AgentDetail.razor b/src/Heimdall.Web/Components/Pages/AgentDetail.razor index ec12d79..9e731af 100644 --- a/src/Heimdall.Web/Components/Pages/AgentDetail.razor +++ b/src/Heimdall.Web/Components/Pages/AgentDetail.razor @@ -941,10 +941,13 @@ else { _globalSettings = (await Api.GetSettingsAsync()) .Where(s => s.AgentScoped) + .Where(s => !string.Equals(s.Key, "autoupdateenabled", StringComparison.OrdinalIgnoreCase)) .OrderBy(s => s.Category) .ThenBy(s => s.Key) .ToList(); - _settings = await Api.GetAgentSettingsAsync(Id); + _settings = (await Api.GetAgentSettingsAsync(Id)) + .Where(s => !string.Equals(s.Key, "autoupdateenabled", StringComparison.OrdinalIgnoreCase)) + .ToList(); } catch { diff --git a/src/Heimdall.Web/Components/Pages/SitesPage.razor b/src/Heimdall.Web/Components/Pages/SitesPage.razor index dc77647..a407c0c 100644 --- a/src/Heimdall.Web/Components/Pages/SitesPage.razor +++ b/src/Heimdall.Web/Components/Pages/SitesPage.razor @@ -157,9 +157,13 @@ else HelperText="@Text["SitesPage_TimezoneHelper"]" /> - + + @Text["SitesPage_AutoUpdateInherit"] + @Text["SitesPage_AutoUpdateEnabled"] + @Text["SitesPage_AutoUpdateDisabled"] + @if (!string.IsNullOrEmpty(_editError)) { @_editError @@ -279,7 +283,7 @@ else private string? _editAddress; private string? _editTimezone; private string? _editNtfyTopic; - private bool _editAutoUpdate; + private bool? _editAutoUpdate; private string _editError = ""; /// URL publique du serveur Heimdall (utilisée dans le compose généré). @@ -452,6 +456,12 @@ else finally { _editing = false; } } + private Task OnAutoUpdateOverrideChanged(bool? value) + { + _editAutoUpdate = value; + return Task.CompletedTask; + } + private async Task DeleteSite(Guid id, string name) { if (await Api.DeleteSiteAsync(id)) diff --git a/src/Heimdall.Web/Components/Settings/AgentDefaultsSection.razor b/src/Heimdall.Web/Components/Settings/AgentDefaultsSection.razor index 0d8b696..6f29443 100644 --- a/src/Heimdall.Web/Components/Settings/AgentDefaultsSection.razor +++ b/src/Heimdall.Web/Components/Settings/AgentDefaultsSection.razor @@ -51,6 +51,20 @@ + + @Text["AgentDefaultsSection_Updates"] + + + + + + + @Text["AgentDefaultsSection_Diagnostics"] @@ -88,6 +102,7 @@ private Task OnRetentionChanged(int? v) => SaveValueAsync("log.retentiondays", v?.ToString() ?? ""); private Task OnHeartbeatChanged(int? v) => SaveValueAsync("heartbeat.interval.seconds", v?.ToString() ?? ""); private Task OnSentryEnabledChanged(bool v) => SaveValueAsync("sentry.enabled", v ? "true" : "false"); + private Task OnAutoUpdateChanged(bool v) => SaveValueAsync("autoupdateenabled", v ? "true" : "false"); private async Task SaveValueAsync(string key, string? value) { diff --git a/src/Heimdall.Web/Components/SiteInstallPanel.razor b/src/Heimdall.Web/Components/SiteInstallPanel.razor index ef9b88e..0f595df 100644 --- a/src/Heimdall.Web/Components/SiteInstallPanel.razor +++ b/src/Heimdall.Web/Components/SiteInstallPanel.razor @@ -1,6 +1,4 @@ -@* SiteInstallPanel.razor — génère les instructions d'installation d'un agent - Heimdall sur un site, façon Pangolin (choix de la méthode + code à copier). - Modes : Docker Compose (recommandé) ou script shell. *@ +@* Pangolin-style installer command generator for a single Heimdall site. *@ @using MudBlazor @inject Heimdall.Web.Services.UiText Text @@ -12,67 +10,166 @@ @Text["SiteInstallPanel_Description"] - - - @((MarkupString)string.Format(Text["SiteInstallPanel_ComposeInstructions"], "docker-compose.yml", "docker compose up -d")) - - @((MarkupString)string.Format(Text["SiteInstallPanel_ReleaseKeyInstructions"], "agent-release-public.pem", "chmod 644")) - - @if (_agentImageReference is null) - { - @Text["SiteInstallPanel_ImageUnavailable"] - } - else - { - -
@ComposeYaml
-
- - @Text["SiteInstallPanel_CopyCompose"] - - } -
- - - @Text["SiteInstallPanel_ShellInstructions"] - - -
@ShellCommand
-
- - @Text["SiteInstallPanel_CopyCommand"] - -
-
+@Text["SiteInstallPanel_OperatingSystem"] + + @foreach (var os in OperatingSystems) + { + + @os.Icon @Text[os.Label] + + } + + +@Text["SiteInstallPanel_Method"] + + @foreach (var method in AvailableMethods) + { + var selectedMethod = method.Id; + + @Text[method.Label] + + } + + +@if (_method == "docker-compose" && CanGenerateDocker) +{ + @Text["SiteInstallPanel_Configuration"] + @Text["SiteInstallPanel_DockerUpdateNote"] + @Text["SiteInstallPanel_Install"] + +
@ComposeYaml
+
+ + @Text["SiteInstallPanel_CopyCompose"] + +} +else if (_method == "docker-compose" && !CanGenerateDocker) +{ + @Text["SiteInstallPanel_ImageUnavailable"] +} + +@Text["SiteInstallPanel_Commands"] +@foreach (var command in Commands) +{ + @Text[command.Label] + +
@command.Value
+
+ + @Text["SiteInstallPanel_CopyCommand"] + +} + +@if (_method == "windows-run") +{ + @Text["SiteInstallPanel_WindowsConsoleNote"] +} +else if (_method == "windows-service") +{ + @Text["SiteInstallPanel_WindowsServiceAdminNote"] +} @code { - /// Nom du site cible. [Parameter, EditorRequired] public string SiteName { get; set; } = ""; - - /// Token d'enregistrement du site (affiché dans le compose). [Parameter, EditorRequired] public string SiteToken { get; set; } = ""; - - /// URL publique du serveur Heimdall (ex: https://heimdall.tordais.cc). [Parameter, EditorRequired] public string CentralUrl { get; set; } = ""; [Inject] private ISnackbar Snackbar { get; set; } = default!; [Inject] private HeimdallApiClient Api { get; set; } = default!; + [Inject] private IJSRuntime JsRuntime { get; set; } = default!; + private static readonly (string Id, string Label, string Icon)[] OperatingSystems = + [ + ("linux", "SiteInstallPanel_Linux", "🐧"), + ("windows", "SiteInstallPanel_Windows", "⊞"), + ("docker", "SiteInstallPanel_Docker", "🐳") + ]; + + private string _operatingSystem = "linux"; + private string _method = "linux-systemd"; private string? _agentImageReference; + private string? _updatePublicKeyPem; + + private bool CanGenerateDocker => !string.IsNullOrWhiteSpace(_agentImageReference) && + !string.IsNullOrWhiteSpace(_updatePublicKeyPem); + + private IReadOnlyList<(string Id, string Label)> AvailableMethods => _operatingSystem switch + { + "linux" => [("linux-run", "SiteInstallPanel_Run"), ("linux-systemd", "SiteInstallPanel_SystemdService")], + "windows" => [("windows-run", "SiteInstallPanel_PowerShellRun"), ("windows-service", "SiteInstallPanel_WindowsService")], + _ => [("docker-compose", "SiteInstallPanel_DockerCompose"), ("docker-run", "SiteInstallPanel_DockerRun")] + }; + + private IReadOnlyList<(string Label, string Value)> Commands + { + get + { + if (_method == "linux-systemd") + return + [ + ("SiteInstallPanel_Install", LinuxInstallCommand(service: true)), + ("SiteInstallPanel_Run", "sudo systemctl start heimdall-agent"), + ("SiteInstallPanel_Check", "sudo systemctl status heimdall-agent --no-pager && curl -fsS http://127.0.0.1:8081/api/version") + ]; + if (_method == "linux-run") + return + [ + ("SiteInstallPanel_InstallAndRun", LinuxInstallCommand(service: false)), + ("SiteInstallPanel_Check", "curl -fsS http://127.0.0.1:8081/api/version") + ]; + if (_method == "windows-run") + return + [ + ("SiteInstallPanel_Install", WindowsInstallCommand(service: false, installOnly: true)), + ("SiteInstallPanel_Run", WindowsConsoleRunCommand), + ("SiteInstallPanel_Check", "Invoke-RestMethod http://127.0.0.1:8081/api/version") + ]; + if (_method == "windows-service") + { + var serviceName = WindowsServiceName; + return + [ + ("SiteInstallPanel_Install", WindowsInstallCommand(service: true, installOnly: true)), + ("SiteInstallPanel_Run", $"Start-Service -Name {PowerShellQuote(serviceName)}"), + ("SiteInstallPanel_Check", $"Get-Service -Name {PowerShellQuote(serviceName)}; Invoke-RestMethod http://127.0.0.1:8081/api/version") + ]; + } + if (_method == "docker-compose") + return + [ + ("SiteInstallPanel_Run", "docker compose up -d"), + ("SiteInstallPanel_Check", $"docker compose ps heimdall-agent-{Slugify(SiteName)} && docker compose logs --tail 50 heimdall-agent-{Slugify(SiteName)}") + ]; + if (_method == "docker-run") + return + [ + ("SiteInstallPanel_Install", DockerRunInstallCommand), + ("SiteInstallPanel_Run", DockerRunCommand), + ("SiteInstallPanel_Check", $"docker inspect --format '{{{{.State.Status}}}}' heimdall-agent-{Slugify(SiteName)} && docker logs --tail 50 heimdall-agent-{Slugify(SiteName)}") + ]; + return []; + } + } protected override async Task OnInitializedAsync() { try { var release = await Api.GetLatestUpdateAsync(); - if (!string.IsNullOrWhiteSpace(release?.ContainerImage) && !string.IsNullOrWhiteSpace(release.ContainerImageDigest)) + if (!string.IsNullOrWhiteSpace(release?.ContainerImage) && + !string.IsNullOrWhiteSpace(release.ContainerImageDigest)) _agentImageReference = $"{release.ContainerImage}@{release.ContainerImageDigest}"; + _updatePublicKeyPem = release?.UpdatePublicKeyPem; } catch { - // The compose stays hidden until Central provides a verified image manifest. + // Native installers fetch signed release metadata directly; Docker needs a verified image reference and key. } } @@ -81,6 +178,7 @@ get { var safeName = Slugify(SiteName); + var pem = EscapeYamlString(_updatePublicKeyPem ?? ""); return $$""" services: heimdall-agent: @@ -88,23 +186,16 @@ container_name: heimdall-agent-{{safeName}} restart: unless-stopped user: "1654:1654" - # Required for camera LAN discovery and RTSP access. network_mode: host environment: - Agent__CentralUrl: {{CentralUrl}} - Agent__SiteToken: {{SiteToken}} - Agent__AgentName: {{SiteName}} + Agent__CentralUrl: {{YamlScalar(CentralUrl)}} + Agent__SiteToken: {{YamlScalar(SiteToken)}} + Agent__AgentName: {{YamlScalar(SiteName)}} Agent__HeartbeatIntervalSeconds: "30" Agent__StateDirectory: /var/lib/heimdall - Agent__UpdatePublicKeyPath: /run/secrets/agent-release-public.pem + Agent__UpdatePublicKeyPem: "{{pem}}" volumes: - - agent_state:/var/lib/heimdall - - type: bind - source: ./agent-release-public.pem - target: /run/secrets/agent-release-public.pem - read_only: true - bind: - create_host_path: false + - agent_state_{{safeName}}:/var/lib/heimdall depends_on: agent-state-init: condition: service_completed_successfully @@ -120,17 +211,99 @@ user: "0:0" entrypoint: ["chown", "-R", "1654:1654", "/state"] volumes: - - agent_state:/state + - agent_state_{{safeName}}:/state restart: "no" volumes: - agent_state: + agent_state_{{safeName}}: """; } } - private string ShellCommand - => $"curl -sSL {ShellQuote(CentralUrl.TrimEnd('/') + "/install-agent.sh")} -o install-agent.sh && bash install-agent.sh --central-url {ShellQuote(CentralUrl)} --site-token {ShellQuote(SiteToken)} --agent-name {ShellQuote(SiteName)}"; + private string DockerRunInstallCommand + { + get + { + var volume = "heimdall-agent-state-" + Slugify(SiteName); + return $"docker pull {_agentImageReference} && docker volume create {volume} && " + + $"docker run --rm --user 0:0 --entrypoint chown -v {volume}:/state {_agentImageReference} -R 1654:1654 /state"; + } + } + + private string DockerRunCommand + { + get + { + var name = "heimdall-agent-" + Slugify(SiteName); + var volume = "heimdall-agent-state-" + Slugify(SiteName); + return $"docker run -d --name {name} --restart unless-stopped --network host --user 1654:1654 " + + $"-e Agent__CentralUrl={ShellQuote(CentralUrl)} -e Agent__SiteToken={ShellQuote(SiteToken)} " + + $"-e Agent__AgentName={ShellQuote(SiteName)} -e Agent__StateDirectory=/var/lib/heimdall " + + $"-e Agent__UpdatePublicKeyPem={ShellQuote(_updatePublicKeyPem ?? "")} " + + $"-v {volume}:/var/lib/heimdall {_agentImageReference}"; + } + } + + private string LinuxInstallCommand(bool service) + { + var baseUrl = CentralUrl.TrimEnd('/'); + var scriptUrl = ShellQuote(baseUrl + "/install/install-agent.sh"); + var supervisorUrl = ShellQuote(baseUrl + "/install/agent-supervisor.py"); + var args = $"--central-url {ShellQuote(CentralUrl)} --site-token {ShellQuote(SiteToken)} --agent-name {ShellQuote(SiteName)}"; + args += service ? " --install-only" : " --run"; + return "tmp=$(mktemp -d) && " + + $"curl -fsSL {scriptUrl} -o \"$tmp/install-agent.sh\" && " + + $"curl -fsSL {supervisorUrl} -o \"$tmp/agent-supervisor.py\" && " + + $"sudo bash \"$tmp/install-agent.sh\" {args}; rc=$?; rm -rf \"$tmp\"; exit $rc"; + } + + private string WindowsServiceName => "HeimdallAgent-" + Slugify(SiteName)[..Math.Min(60, Slugify(SiteName).Length)]; + + private string WindowsConsoleRunCommand + { + get + { + var root = "$env:LOCALAPPDATA + '\\Heimdall\\Agent'"; + return $"$root = {root}; $env:PATH = (Join-Path $root 'runtime') + ';' + $env:PATH; " + + $"$env:ASPNETCORE_URLS = 'http://127.0.0.1:8081'; " + + $"$env:Agent__CentralUrl = {PowerShellQuote(CentralUrl)}; " + + $"$env:Agent__SiteToken = {PowerShellQuote(SiteToken)}; " + + $"$env:Agent__AgentName = {PowerShellQuote(SiteName)}; " + + "$env:Agent__StateDirectory = Join-Path $root 'state'; " + + $"$env:Agent__UpdatePublicKeyPem = {PowerShellQuote(_updatePublicKeyPem ?? "")}; " + + "$env:Agent__UpdateInstallRoot = $root; " + + "$env:Agent__UpdateSupervisorPath = Join-Path $root 'agent-update-supervisor.ps1'; " + + "$current = Join-Path $root 'current'; " + + "Start-Process -FilePath 'dotnet' -ArgumentList 'Heimdall.Agent.dll' -WorkingDirectory $current " + + "-RedirectStandardOutput (Join-Path $root 'agent.log') -RedirectStandardError (Join-Path $root 'agent-error.log') " + + "-WindowStyle Hidden -PassThru"; + } + } + + private string WindowsInstallCommand(bool service, bool installOnly) + { + var scriptUrl = PowerShellQuote(CentralUrl.TrimEnd('/') + "/install/install-agent.ps1"); + var args = $"-CentralUrl {PowerShellQuote(CentralUrl)} -SiteToken {PowerShellQuote(SiteToken)} " + + $"-AgentName {PowerShellQuote(SiteName)}"; + if (service) + args += $" -InstallAsService -ServiceName {PowerShellQuote(WindowsServiceName)}"; + if (installOnly) + args += " -InstallOnly"; + return "$script = Join-Path $env:TEMP 'heimdall-install-agent.ps1'; " + + $"Invoke-WebRequest -UseBasicParsing -Uri {scriptUrl} -OutFile $script; Unblock-File $script; " + + $"try {{ & $script {args} }} finally {{ Remove-Item $script -Force -ErrorAction SilentlyContinue }}"; + } + + private void SelectOperatingSystem(string value) + { + _operatingSystem = value; + _method = value switch + { + "linux" => "linux-systemd", + "windows" => "windows-run", + _ => "docker-compose" + }; + } private async Task CopyCode(string code) { @@ -138,16 +311,30 @@ Snackbar.Add(Text["SiteInstallPanel_Copied"], Severity.Success); } - [Inject] private IJSRuntime JsRuntime { get; set; } = default!; - private static string Slugify(string value) { var sb = new System.Text.StringBuilder(); foreach (var ch in value.ToLowerInvariant()) - sb.Append(char.IsLetterOrDigit(ch) ? ch : '-'); - return sb.ToString().Trim('-'); + sb.Append(char.IsAsciiLetterOrDigit(ch) ? ch : '-'); + var slug = sb.ToString().Trim('-'); + return string.IsNullOrWhiteSpace(slug) ? "site" : slug; } - private static string ShellQuote(string value) - => $"'{value.Replace("'", "'\\''", StringComparison.Ordinal)}'"; + private static string ShellQuote(string value) => + "'" + value.Replace("'", "'\\''", StringComparison.Ordinal) + "'"; + + private static string PowerShellQuote(string value) => + "'" + value.Replace("'", "''", StringComparison.Ordinal) + "'"; + + private static string YamlScalar(string value) => + "\"" + value.Replace("\\", "\\\\", StringComparison.Ordinal) + .Replace("\"", "\\\"", StringComparison.Ordinal) + .Replace("\r", "", StringComparison.Ordinal) + .Replace("\n", "\\n", StringComparison.Ordinal) + "\""; + + private static string EscapeYamlString(string value) => + value.Replace("\\", "\\\\", StringComparison.Ordinal) + .Replace("\"", "\\\"", StringComparison.Ordinal) + .Replace("\r", "", StringComparison.Ordinal) + .Replace("\n", "\\n", StringComparison.Ordinal); } diff --git a/src/Heimdall.Web/Controllers/SitesController.cs b/src/Heimdall.Web/Controllers/SitesController.cs index 6a6413b..f9fc219 100644 --- a/src/Heimdall.Web/Controllers/SitesController.cs +++ b/src/Heimdall.Web/Controllers/SitesController.cs @@ -116,9 +116,11 @@ public class SitesController : ControllerBase var command = new UpdateSiteCommand(id, request.Name, request.Address, request.Timezone, request.NtfyTopic, request.AutoUpdateEnabled, actorId); var result = await _mediator.Send(command, ct); - return result.IsSuccess - ? Ok(result.Data) - : StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + if (!result.IsSuccess) + return StatusCode(result.StatusCode ?? 400, new { error = result.Error }); + + await _broadcast.NotifyAllAgentsReload(ct); + return Ok(result.Data); } /// Get cascade info (agent/camera counts) before deleting a site. diff --git a/src/Heimdall.Web/Controllers/UpdatesController.cs b/src/Heimdall.Web/Controllers/UpdatesController.cs index e07c80c..f4d07d6 100644 --- a/src/Heimdall.Web/Controllers/UpdatesController.cs +++ b/src/Heimdall.Web/Controllers/UpdatesController.cs @@ -131,6 +131,21 @@ public class UpdatesController : ControllerBase assets[platform] = new PlatformAsset { Url = asset.BrowserDownloadUrl, Sha256 = ExtractSha256(asset.Digest), Size = asset.Size }; } var result = new LatestReleaseResponse { Version = release.TagName, ReleaseNotes = release.Body, PublishedAt = release.PublishedAt, Assets = assets }; + var publicKeyBytes = await FetchBoundedReleaseAssetAsync(release.Assets, + "agent-release-public.pem", client, 4096, ct); + if (publicKeyBytes is not null) + { + try + { + var publicKeyPem = System.Text.Encoding.UTF8.GetString(publicKeyBytes); + using var verifier = ECDsa.Create(); + verifier.ImportFromPem(publicKeyPem); + if (verifier.KeySize == 256) + result.UpdatePublicKeyPem = publicKeyPem; + } + catch (CryptographicException) { } + catch (ArgumentException) { } + } var image = await FetchAgentImageManifestAsync(release.Assets, client, ct); result.ContainerImage = image?.Image; result.ContainerImageDigest = image?.Digest; @@ -269,6 +284,7 @@ public class UpdatesController : ControllerBase [JsonPropertyName("assets")] public Dictionary Assets { get; set; } = []; [JsonPropertyName("containerImage")] public string? ContainerImage { get; set; } [JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; set; } + [JsonPropertyName("updatePublicKeyPem")] public string? UpdatePublicKeyPem { get; set; } [JsonPropertyName("signedManifest")] public string? SignedManifest { get; set; } [JsonPropertyName("manifestSignature")] public string? ManifestSignature { get; set; } } diff --git a/src/Heimdall.Web/Heimdall.Web.csproj b/src/Heimdall.Web/Heimdall.Web.csproj index df6b60c..feb0bc7 100644 --- a/src/Heimdall.Web/Heimdall.Web.csproj +++ b/src/Heimdall.Web/Heimdall.Web.csproj @@ -14,6 +14,17 @@
+ + + + + + + diff --git a/src/Heimdall.Web/Hubs/ConfigHub.cs b/src/Heimdall.Web/Hubs/ConfigHub.cs index caae48b..5145836 100644 --- a/src/Heimdall.Web/Hubs/ConfigHub.cs +++ b/src/Heimdall.Web/Hubs/ConfigHub.cs @@ -93,6 +93,12 @@ public class ConfigBroadcastService : IConfigBroadcastService _logger.LogDebug("Broadcasting global setting change: {Key}", key); var access = services.GetRequiredService(); var subscriptions = services.GetRequiredService(); + if (string.Equals(key, "autoupdateenabled", StringComparison.OrdinalIgnoreCase)) + { + await _hubContext.Clients.Clients(await subscriptions.AuthorizedAsync("config", "all", access, + r => Task.FromResult(r.Kind == RequesterKind.Agent), ct)).SendAsync("ConfigReload", ct); + return; + } await _hubContext.Clients.Clients(await subscriptions.AuthorizedAsync("config", "all", access, r => Task.FromResult(r.Kind == RequesterKind.Agent), ct)).SendAsync("SettingChanged", key, value, ct); } @@ -116,7 +122,14 @@ public class ConfigBroadcastService : IConfigBroadcastService var db = services.GetRequiredService(); if (!await db.AppSettings.AnyAsync(s => s.Key == key && s.AgentScoped, ct)) return; _logger.LogDebug("Broadcasting agent setting change: Agent={AgentId}, {Key}", agentId, key); - await _hubContext.Clients.Clients(await subscriptions.AuthorizedAsync("config", $"agent_{agentId}", access, r => access.AgentAsync(r, agentId, ct), ct)).SendAsync("SettingChanged", key, value, ct); + var recipients = await subscriptions.AuthorizedAsync("config", $"agent_{agentId}", access, + r => access.AgentAsync(r, agentId, ct), ct); + if (string.Equals(key, "autoupdateenabled", StringComparison.OrdinalIgnoreCase)) + { + await _hubContext.Clients.Clients(recipients).SendAsync("ConfigReload", ct); + return; + } + await _hubContext.Clients.Clients(recipients).SendAsync("SettingChanged", key, value, ct); } /// Requests an immediate update check from connected, authorized agents. diff --git a/src/Heimdall.Web/Localization/SharedResources.en.resx b/src/Heimdall.Web/Localization/SharedResources.en.resx index 7a83e5f..b709165 100644 --- a/src/Heimdall.Web/Localization/SharedResources.en.resx +++ b/src/Heimdall.Web/Localization/SharedResources.en.resx @@ -1723,7 +1723,16 @@ Automatic agent updates - Allow agents at this site to update automatically from the central server. + Choose whether this site inherits the global setting or overrides it. + + + Inherit global setting + + + Enabled + + + Disabled camera(s) @@ -2625,6 +2634,15 @@ Global + + Updates + + + Automatic updates for native agents + + + Enable automatic updates for native agents by default. Sites can override this. New releases wait 24 hours before automatic installation. + Heartbeat @@ -3984,4 +4002,58 @@ Agents + + Operating system + + + Linux + + + Windows + + + Docker + + + Method + + + Systemd service + + + PowerShell — user process + + + Windows Service + + + Configuration + + + Commands + + + Install + + + Install and run + + + Run + + + Check + + + Update containers through Docker or Kubernetes. Heimdall pins each image to its signed digest. + + + The Agent starts in the background so you can check it from this PowerShell session. Choose Windows Service to restart it after logoff or reboot. + + + This installs a Windows Service and requires administrator rights. The service starts automatically with Windows. + + + Docker Run + diff --git a/src/Heimdall.Web/Localization/SharedResources.fr.resx b/src/Heimdall.Web/Localization/SharedResources.fr.resx index 7f89d58..c8cb42a 100644 --- a/src/Heimdall.Web/Localization/SharedResources.fr.resx +++ b/src/Heimdall.Web/Localization/SharedResources.fr.resx @@ -1723,7 +1723,16 @@ Mises à jour automatiques des agents - Autoriser les agents de ce site à se mettre à jour automatiquement depuis le serveur central. + Choisir si ce site hérite du réglage global ou le remplace. + + + Hériter du réglage global + + + Activées + + + Désactivées caméra(s) @@ -2625,6 +2634,15 @@ Globaux + + Mises à jour + + + Mises à jour automatiques des agents natifs + + + Activer par défaut les mises à jour automatiques des agents natifs. Chaque site peut remplacer ce réglage. Une nouvelle version attend 24 heures avant son installation automatique. + Heartbeat @@ -3984,4 +4002,58 @@ Agents + + Système d’exploitation + + + Linux + + + Windows + + + Docker + + + Méthode + + + Service systemd + + + PowerShell — exécution utilisateur + + + Service Windows + + + Configuration + + + Commandes + + + Installer + + + Installer et lancer + + + Lancer + + + Vérifier + + + Les mises à jour des conteneurs passent par Docker ou Kubernetes. Heimdall épingle chaque image sur son digest signé. + + + L’Agent démarre en arrière-plan pour permettre la vérification depuis cette console. Le mode Service Windows le relance après fermeture de session ou redémarrage. + + + Ce mode installe un service Windows et demande des droits administrateur. Le service démarre automatiquement avec Windows. + + + Docker Run + diff --git a/src/Heimdall.Web/Localization/SharedResources.resx b/src/Heimdall.Web/Localization/SharedResources.resx index 7f89d58..0006516 100644 --- a/src/Heimdall.Web/Localization/SharedResources.resx +++ b/src/Heimdall.Web/Localization/SharedResources.resx @@ -1720,10 +1720,19 @@ agent(s) - Mises à jour automatiques des agents + Automatic agent updates - Autoriser les agents de ce site à se mettre à jour automatiquement depuis le serveur central. + Choose whether this site inherits the global setting or overrides it. + + + Inherit global setting + + + Enabled + + + Disabled caméra(s) @@ -2625,6 +2634,15 @@ Globaux + + Updates + + + Automatic updates for native agents + + + Enable automatic updates for native agents by default. Sites can override this. New releases wait 24 hours before automatic installation. + Heartbeat @@ -3984,4 +4002,58 @@ Agents + + Operating system + + + Linux + + + Windows + + + Docker + + + Method + + + Systemd service + + + PowerShell — user process + + + Windows Service + + + Configuration + + + Commands + + + Install + + + Install and run + + + Run + + + Check + + + Update containers through Docker or Kubernetes. Heimdall pins each image to its signed digest. + + + The Agent starts in the background so you can check it from this PowerShell session. Choose Windows Service to restart it after logoff or reboot. + + + This installs a Windows Service and requires administrator rights. The service starts automatically with Windows. + + + Docker Run + diff --git a/src/Heimdall.Web/Services/AuthState.cs b/src/Heimdall.Web/Services/AuthState.cs index e75e0b1..2b92bd3 100644 --- a/src/Heimdall.Web/Services/AuthState.cs +++ b/src/Heimdall.Web/Services/AuthState.cs @@ -101,7 +101,7 @@ public record SiteItem( [property: JsonPropertyName("timezone")] string Timezone, [property: JsonPropertyName("ntfyTopic")] string? NtfyTopic, [property: JsonPropertyName("enabled")] bool Enabled, - [property: JsonPropertyName("autoUpdateEnabled")] bool AutoUpdateEnabled, + [property: JsonPropertyName("autoUpdateEnabled")] bool? AutoUpdateEnabled, [property: JsonPropertyName("createdAt")] DateTime CreatedAt); public record SiteWithTokenResult( diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index 1b96cae..f958d6b 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -1404,7 +1404,7 @@ public record CreateApiKeyResult( [property: JsonPropertyName("siteId")] Guid? SiteId, [property: JsonPropertyName("expiresAt")] DateTime? ExpiresAt); -public class LatestReleaseInfo { [JsonPropertyName("version")] public string Version { get; set; } = ""; [JsonPropertyName("releaseNotes")] public string? ReleaseNotes { get; set; } [JsonPropertyName("publishedAt")] public DateTime? PublishedAt { get; set; } [JsonPropertyName("assets")] public Dictionary Assets { get; set; } = []; [JsonPropertyName("containerImage")] public string? ContainerImage { get; set; } [JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; set; } } +public class LatestReleaseInfo { [JsonPropertyName("version")] public string Version { get; set; } = ""; [JsonPropertyName("releaseNotes")] public string? ReleaseNotes { get; set; } [JsonPropertyName("publishedAt")] public DateTime? PublishedAt { get; set; } [JsonPropertyName("assets")] public Dictionary Assets { get; set; } = []; [JsonPropertyName("containerImage")] public string? ContainerImage { get; set; } [JsonPropertyName("containerImageDigest")] public string? ContainerImageDigest { get; set; } [JsonPropertyName("updatePublicKeyPem")] public string? UpdatePublicKeyPem { get; set; } } public class PlatformAssetInfo { [JsonPropertyName("url")] public string Url { get; set; } = ""; [JsonPropertyName("sha256")] public string? Sha256 { get; set; } [JsonPropertyName("size")] public long Size { get; set; } } public record SiteCascadeInfo([property: JsonPropertyName("agentCount")] int AgentCount, [property: JsonPropertyName("cameraCount")] int CameraCount); diff --git a/todo.md b/todo.md index 71ea222..c7b6e91 100644 --- a/todo.md +++ b/todo.md @@ -27,6 +27,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PIPE-10 / FEAT-05** La PR #74 fait remonter les erreurs ntfy; la PR #76 ajoute une outbox SQL atomique avec état, leases, reprise périodique et unicité par notification/canal. Sa CI (run #242) a validé les tests et scans d’images. La PR #110 ajoute des tests PostgreSQL du succès, du backoff après erreur, de la reprise de lease expirée, de l’ignorance des livraisons différées ou déjà prises et du routage Hangfire par canal. Le run PR #332 a passé les 155 tests d’intégration et les 35 E2E sans test ignoré, les builds/scans des deux images et `CI policy`; la publication Docker Hub a été ignorée comme prévu. Restent les essais SMTP/ntfy réels. La livraison reste au moins une fois : une panne après acceptation fournisseur mais avant l’acquittement SQL peut produire un doublon; aucune garantie exactement une fois n’est possible avec ces interfaces. - [ ] **OPS-02** Les PR #62, #63 et #106 protègent les références de caméras supprimées logiquement, enregistrent l'inventaire des destinations avant upload et font parcourir ces destinations par le nettoyage final. Le run PR #317 a passé les 284 tests Infrastructure, dont les scénarios de changement de destination (snapshot référencé conservé, puis orphelin supprimé) et de S3 historique inaccessible (références conservées). Restent les objets recording tant que FEAT-02 n'a pas de producteur, les lignes historiques sans provenance (ne pas deviner), et la validation du changement de provider sur stockage déployé. - [ ] **OPS-05 / AGENT-06** Les Compose sont simplifiés en un noyau Central + PostgreSQL, un Compose Agent de développement local et des Compose facultatifs séparés par logiciel. En production, le Compose Agent est fourni par l’IHM pour le site sélectionné; le Compose statique de production a été supprimé. La PR #114 retire du Compose les réglages métier (SMTP, ntfy, Ollama, stockage, source des releases et URL API) pour les gérer par l’IHM avec portée globale, en laissant les destinations de notification à leur portée site/utilisateur. La PR #117 ajoute l’installateur interactif Linux Central + PostgreSQL et fixe les images à Docker Hub; sa CI PR #394 a passé tests et scans des deux images ainsi que `CI policy`, puis a été fusionnée sur `main` (`d1f3f1a`). Restent l’installation des clés de signature CI et la validation réelle de la génération IHM, digest/signature Agent, mise à jour native/Docker, arrêt propre et rollback. +- [ ] **Installateurs Agent / mises à jour façon Pangolin** L’IHM doit proposer les OS et méthodes réellement supportés et générer des commandes Bash/PowerShell qui téléchargent puis exécutent l’installateur depuis Central, sans copier les scripts sur les hôtes. Les installations natives Linux/Windows doivent vérifier l’archive signée et le digest, fonctionner comme service quand cette méthode est offerte, puis appliquer les mises à jour avec validation de démarrage et rollback. Le réglage de mise à jour doit être global, avec surcharge nullable par site; les agents natifs attendent 24 h après publication avant une mise à jour automatique, tandis que les conteneurs restent gérés par leur orchestrateur. La migration conserve les choix existants des sites (activés ou désactivés) ; les nouveaux sites et les sites explicitement configurés en héritage suivent le défaut global. À valider en CI, puis sur des hôtes Linux et Windows réels. - [ ] **AGENT-08** Valider reconnexion, remplacement atomique de configuration caméra et ACK persisté sur Agent déployé. - [ ] **AGENT-09** La PR #101 aligne `heimdall.ai.pipeline.level` sur les transitions réelles (inférence lente, moteur indisponible, saturation CPU et récupération), sans ratio cumulatif périmé. La PR #102 ajoute `heimdall.ai.inference.queue.depth` et `heimdall.ai.inference.queue.rejected` pour rendre visibles le backlog ONNX et les frames rejetées quand la file est pleine. Restent à mesurer les seuils de capture et la santé d'enregistrement sous panne caméra/modèle/disque, puis valider ces alertes sur matériel représentatif. - [ ] **AGENT-10** Tester charge, redémarrages rapides et arrêt FFmpeg/ONNX sous contrainte sur matériel représentatif.