feat(agent): add Pangolin-style native installs and updates
Heimdall Gitea / Detect CI scope (pull_request) Successful in 5s
Heimdall Gitea / Build and tests (pull_request) Failing after 2m11s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 3s
Heimdall Gitea / Detect CI scope (pull_request) Successful in 5s
Heimdall Gitea / Build and tests (pull_request) Failing after 2m11s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Failing after 3s
This commit is contained in:
1 parent
13b6ee7979
commit
8d35518d1a
34 files changed
+4202
-136
No files matched your search
@@ -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.
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 <<EOF | sudo tee /etc/systemd/system/$SERVICE_NAME.service >/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
|
||||
@@ -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'
|
||||
|
||||
@@ -107,9 +107,18 @@ public sealed class AgentOptions
|
||||
/// <summary>Locally provisioned publisher public key; Central cannot change this setting.</summary>
|
||||
public string? UpdatePublicKeyPath { get; init; }
|
||||
|
||||
/// <summary>Publisher public key provisioned by the trusted installation flow.</summary>
|
||||
public string? UpdatePublicKeyPem { get; init; }
|
||||
|
||||
/// <summary>Locally installed agent release root containing current and releases.</summary>
|
||||
public string? UpdateInstallRoot { get; init; }
|
||||
|
||||
/// <summary>Windows helper that replaces the running release after process shutdown and rolls back on failed health checks.</summary>
|
||||
public string? UpdateSupervisorPath { get; init; }
|
||||
|
||||
/// <summary>Optional Windows Service name; empty means a foreground console installation.</summary>
|
||||
public string? UpdateWindowsServiceName { get; init; }
|
||||
|
||||
private static string? ReadSystemdCredential(string name)
|
||||
{
|
||||
var directory = Environment.GetEnvironmentVariable("CREDENTIALS_DIRECTORY");
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.13" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="10.0.13" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="10.0.13" />
|
||||
<PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.22.0" />
|
||||
<PackageReference Include="OpenTelemetry" Version="1.17.0" />
|
||||
<PackageReference Include="OpenTelemetry.Exporter.Prometheus.AspNetCore" Version="1.17.0-beta.1" />
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
/// </summary>
|
||||
public sealed class AgentUpdateService : BackgroundService
|
||||
{
|
||||
private static readonly TimeSpan ReleaseStabilizationPeriod = TimeSpan.FromHours(24);
|
||||
private readonly AgentState _state;
|
||||
private readonly IOptions<AgentOptions> _options;
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
@@ -30,7 +32,7 @@ public sealed class AgentUpdateService : BackgroundService
|
||||
public void SetCapturing(bool capturing) => _isCapturing = capturing;
|
||||
|
||||
/// <summary>Runs an update check immediately when requested by Central.</summary>
|
||||
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<string>
|
||||
{
|
||||
"-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<LatestReleaseResponse?> 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<string, AssetDto> Assets { get; set; } = [];
|
||||
[JsonPropertyName("signedManifest")]
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -11,7 +11,6 @@ namespace Heimdall.Agent.Services;
|
||||
/// </summary>
|
||||
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<AgentOptions> options, AgentState state, ContainerInfoProvider containerInfo, IHttpClientFactory httpClientFactory, ILogger<DockerUpdateService> 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;
|
||||
}
|
||||
|
||||
/// <summary>Runs a Docker image update check immediately when requested by Central.</summary>
|
||||
@@ -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; }
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -11,7 +11,7 @@ public record SiteResponse(
|
||||
string Timezone,
|
||||
string? NtfyTopic,
|
||||
bool Enabled,
|
||||
bool AutoUpdateEnabled,
|
||||
bool? AutoUpdateEnabled,
|
||||
DateTime CreatedAt);
|
||||
|
||||
public record SiteWithTokenResponse(
|
||||
|
||||
+21
-6
@@ -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
|
||||
|
||||
@@ -12,8 +12,8 @@ public class Site : Entity<Guid>, IAuditableEntity, ISoftDeletable
|
||||
/// <summary>Topic ntfy dédié pour les notifications de ce site (null → topic personnel utilisateur).</summary>
|
||||
public string? NtfyTopic { get; private set; }
|
||||
|
||||
/// <summary>Enable automatic agent updates from the central server.</summary>
|
||||
public bool AutoUpdateEnabled { get; private set; }
|
||||
/// <summary>Site-level automatic update override; null inherits the global Agent setting.</summary>
|
||||
public bool? AutoUpdateEnabled { get; private set; }
|
||||
|
||||
/// <summary>Hashed registration token (SHA256) for agent enrollment.</summary>
|
||||
public string? RegistrationTokenHash { get; private set; }
|
||||
@@ -57,8 +57,7 @@ public class Site : Entity<Guid>, 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<Guid>, 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()
|
||||
{
|
||||
|
||||
@@ -25,6 +25,9 @@ public class SiteConfiguration : IEntityTypeConfiguration<Site>
|
||||
.HasDefaultValue("UTC")
|
||||
.IsUnicode(false);
|
||||
|
||||
builder.Property(s => s.AutoUpdateEnabled)
|
||||
.IsRequired(false);
|
||||
|
||||
builder.Property(s => s.RegistrationTokenHash)
|
||||
.HasMaxLength(128)
|
||||
.IsUnicode(false);
|
||||
|
||||
+2832
File diff suppressed because it is too large.
Load diff
@@ -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<bool>(
|
||||
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<bool>(
|
||||
name: "AutoUpdateEnabled",
|
||||
table: "sites",
|
||||
type: "boolean",
|
||||
nullable: false,
|
||||
defaultValue: false,
|
||||
oldClrType: typeof(bool),
|
||||
oldType: "boolean",
|
||||
oldNullable: true);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
// <auto-generated />
|
||||
// <auto-generated />
|
||||
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<bool>("AutoUpdateEnabled")
|
||||
b.Property<bool?>("AutoUpdateEnabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
|
||||
@@ -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
|
||||
{
|
||||
|
||||
@@ -157,9 +157,13 @@ else
|
||||
HelperText="@Text["SitesPage_TimezoneHelper"]" />
|
||||
<MudTextField @bind-Value="_editNtfyTopic" Label="@Text["SitesPage_NtfyLabel"]" Variant="Variant.Outlined" Class="mb-4"
|
||||
HelperText="@Text["SitesPage_NtfyHelper"]" />
|
||||
<MudSwitch T="bool" @bind-Value="_editAutoUpdate" Color="Color.Primary" Class="mb-4"
|
||||
Label="@Text["SitesPage_AutoUpdate"]"
|
||||
HelperText="@Text["SitesPage_AutoUpdateHelper"]" />
|
||||
<MudSelect T="bool?" Value="_editAutoUpdate" ValueChanged="OnAutoUpdateOverrideChanged"
|
||||
Label="@Text["SitesPage_AutoUpdate"]" Variant="Variant.Outlined" Class="mb-4"
|
||||
HelperText="@Text["SitesPage_AutoUpdateHelper"]">
|
||||
<MudSelectItem T="bool?" Value="@((bool?)null)">@Text["SitesPage_AutoUpdateInherit"]</MudSelectItem>
|
||||
<MudSelectItem T="bool?" Value="@((bool?)true)">@Text["SitesPage_AutoUpdateEnabled"]</MudSelectItem>
|
||||
<MudSelectItem T="bool?" Value="@((bool?)false)">@Text["SitesPage_AutoUpdateDisabled"]</MudSelectItem>
|
||||
</MudSelect>
|
||||
@if (!string.IsNullOrEmpty(_editError))
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Class="mb-4">@_editError</MudAlert>
|
||||
@@ -279,7 +283,7 @@ else
|
||||
private string? _editAddress;
|
||||
private string? _editTimezone;
|
||||
private string? _editNtfyTopic;
|
||||
private bool _editAutoUpdate;
|
||||
private bool? _editAutoUpdate;
|
||||
private string _editError = "";
|
||||
|
||||
/// <summary>URL publique du serveur Heimdall (utilisée dans le compose généré).</summary>
|
||||
@@ -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))
|
||||
|
||||
@@ -51,6 +51,20 @@
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-3">
|
||||
<i class="fas fa-arrows-rotate mr-1" style="color: var(--mud-palette-primary);"></i> @Text["AgentDefaultsSection_Updates"]
|
||||
</MudText>
|
||||
<MudGrid>
|
||||
<MudItem xs="12">
|
||||
<MudSwitch T="bool"
|
||||
Value="@(GetValue("autoupdateenabled")?.Equals("true", StringComparison.OrdinalIgnoreCase) == true)"
|
||||
ValueChanged="OnAutoUpdateChanged"
|
||||
Color="Color.Primary"
|
||||
Label="@Text["AgentDefaultsSection_AutoUpdate"]"
|
||||
HelperText="@Text["AgentDefaultsSection_AutoUpdateHelp"]" />
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-3">
|
||||
<i class="fas fa-bug mr-1" style="color: var(--mud-palette-primary);"></i> @Text["AgentDefaultsSection_Diagnostics"]
|
||||
</MudText>
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
@@ -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"]
|
||||
</MudText>
|
||||
|
||||
<MudTabs Class="mb-4" Elevation="0" Rounded="true">
|
||||
<MudTabPanel Text="@Text["SiteInstallPanel_DockerCompose"]" Icon="@Icons.Material.Filled.IntegrationInstructions">
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-2">@((MarkupString)string.Format(Text["SiteInstallPanel_ComposeInstructions"], "<code>docker-compose.yml</code>", "<code>docker compose up -d</code>"))</MudText>
|
||||
<MudAlert Severity="Severity.Info" Class="mb-3">
|
||||
@((MarkupString)string.Format(Text["SiteInstallPanel_ReleaseKeyInstructions"], "<code>agent-release-public.pem</code>", "<code>chmod 644</code>"))
|
||||
</MudAlert>
|
||||
@if (_agentImageReference is null)
|
||||
{
|
||||
<MudAlert Severity="Severity.Warning">@Text["SiteInstallPanel_ImageUnavailable"]</MudAlert>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudPaper Class="pa-3" Style="border-radius: 8px; background: #0d1117; overflow-x: auto;">
|
||||
<pre class="mb-0" style="color:#c9d1d9;font-size:0.85rem;"><code>@ComposeYaml</code></pre>
|
||||
</MudPaper>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" Class="mt-3"
|
||||
OnClick="@(() => CopyCode(ComposeYaml))" StartIcon="@Icons.Material.Filled.ContentCopy">
|
||||
@Text["SiteInstallPanel_CopyCompose"]
|
||||
</MudButton>
|
||||
}
|
||||
</MudTabPanel>
|
||||
<MudTabPanel Text="@Text["SiteInstallPanel_ShellScript"]" Icon="@Icons.Material.Filled.Terminal">
|
||||
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-2">
|
||||
@Text["SiteInstallPanel_ShellInstructions"]
|
||||
</MudText>
|
||||
<MudPaper Class="pa-3" Style="border-radius: 8px; background: #0d1117; overflow-x: auto;">
|
||||
<pre class="mb-0" style="color:#c9d1d9;font-size:0.85rem;"><code>@ShellCommand</code></pre>
|
||||
</MudPaper>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" Class="mt-3"
|
||||
OnClick="@(() => CopyCode(ShellCommand))" StartIcon="@Icons.Material.Filled.ContentCopy">
|
||||
@Text["SiteInstallPanel_CopyCommand"]
|
||||
</MudButton>
|
||||
</MudTabPanel>
|
||||
</MudTabs>
|
||||
<MudText Typo="Typo.subtitle1" Class="mb-2">@Text["SiteInstallPanel_OperatingSystem"]</MudText>
|
||||
<MudGrid Class="mb-3">
|
||||
@foreach (var os in OperatingSystems)
|
||||
{
|
||||
<MudItem xs="12" sm="4" @key="os.Id">
|
||||
<MudButton FullWidth="true" Variant="@(_operatingSystem == os.Id ? Variant.Filled : Variant.Outlined)"
|
||||
Color="@(_operatingSystem == os.Id ? Color.Primary : Color.Default)"
|
||||
OnClick="@(() => SelectOperatingSystem(os.Id))">@os.Icon @Text[os.Label]</MudButton>
|
||||
</MudItem>
|
||||
}
|
||||
</MudGrid>
|
||||
|
||||
<MudText Typo="Typo.subtitle1" Class="mb-2">@Text["SiteInstallPanel_Method"]</MudText>
|
||||
<MudGrid Class="mb-4">
|
||||
@foreach (var method in AvailableMethods)
|
||||
{
|
||||
var selectedMethod = method.Id;
|
||||
<MudItem xs="12" sm="6" @key="method.Id">
|
||||
<MudButton FullWidth="true" Variant="@(_method == method.Id ? Variant.Filled : Variant.Outlined)"
|
||||
Color="@(_method == method.Id ? Color.Primary : Color.Default)"
|
||||
OnClick="@(() => _method = selectedMethod)">@Text[method.Label]</MudButton>
|
||||
</MudItem>
|
||||
}
|
||||
</MudGrid>
|
||||
|
||||
@if (_method == "docker-compose" && CanGenerateDocker)
|
||||
{
|
||||
<MudText Typo="Typo.subtitle1" Class="mb-2">@Text["SiteInstallPanel_Configuration"]</MudText>
|
||||
<MudAlert Severity="Severity.Info" Class="mb-3">@Text["SiteInstallPanel_DockerUpdateNote"]</MudAlert>
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-2">@Text["SiteInstallPanel_Install"]</MudText>
|
||||
<MudPaper Class="pa-3" Style="border-radius:8px;background:#0d1117;overflow-x:auto;">
|
||||
<pre class="mb-0" style="color:#c9d1d9;font-size:.85rem;"><code>@ComposeYaml</code></pre>
|
||||
</MudPaper>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" Class="mt-3"
|
||||
OnClick="@(() => CopyCode(ComposeYaml))" StartIcon="@Icons.Material.Filled.ContentCopy">
|
||||
@Text["SiteInstallPanel_CopyCompose"]
|
||||
</MudButton>
|
||||
}
|
||||
else if (_method == "docker-compose" && !CanGenerateDocker)
|
||||
{
|
||||
<MudAlert Severity="Severity.Warning">@Text["SiteInstallPanel_ImageUnavailable"]</MudAlert>
|
||||
}
|
||||
|
||||
<MudText Typo="Typo.subtitle1" Class="mb-2 mt-4">@Text["SiteInstallPanel_Commands"]</MudText>
|
||||
@foreach (var command in Commands)
|
||||
{
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-2 mt-3">@Text[command.Label]</MudText>
|
||||
<MudPaper Class="pa-3" Style="border-radius:8px;background:#0d1117;overflow-x:auto;">
|
||||
<pre class="mb-0" style="color:#c9d1d9;font-size:.85rem;"><code>@command.Value</code></pre>
|
||||
</MudPaper>
|
||||
<MudButton Variant="Variant.Text" Color="Color.Primary" Class="mt-2"
|
||||
OnClick="@(() => CopyCode(command.Value))" StartIcon="@Icons.Material.Filled.ContentCopy">
|
||||
@Text["SiteInstallPanel_CopyCommand"]
|
||||
</MudButton>
|
||||
}
|
||||
|
||||
@if (_method == "windows-run")
|
||||
{
|
||||
<MudAlert Severity="Severity.Info" Class="mt-3">@Text["SiteInstallPanel_WindowsConsoleNote"]</MudAlert>
|
||||
}
|
||||
else if (_method == "windows-service")
|
||||
{
|
||||
<MudAlert Severity="Severity.Info" Class="mt-3">@Text["SiteInstallPanel_WindowsServiceAdminNote"]</MudAlert>
|
||||
}
|
||||
|
||||
@code {
|
||||
/// <summary>Nom du site cible.</summary>
|
||||
[Parameter, EditorRequired] public string SiteName { get; set; } = "";
|
||||
|
||||
/// <summary>Token d'enregistrement du site (affiché dans le compose).</summary>
|
||||
[Parameter, EditorRequired] public string SiteToken { get; set; } = "";
|
||||
|
||||
/// <summary>URL publique du serveur Heimdall (ex: https://heimdall.tordais.cc).</summary>
|
||||
[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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/// <summary>Get cascade info (agent/camera counts) before deleting a site.</summary>
|
||||
|
||||
@@ -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<string, PlatformAsset> 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; }
|
||||
}
|
||||
|
||||
@@ -14,6 +14,17 @@
|
||||
<InternalsVisibleTo Include="Heimdall.IntegrationTests" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Include="../../install/install-agent.sh" Link="wwwroot/install/install-agent.sh"
|
||||
CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
|
||||
<Content Include="../../install/agent-supervisor.py" Link="wwwroot/install/agent-supervisor.py"
|
||||
CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
|
||||
<Content Include="../../install/install-agent.ps1" Link="wwwroot/install/install-agent.ps1"
|
||||
CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
|
||||
<Content Include="../../install/agent-update-supervisor.ps1" Link="wwwroot/install/agent-update-supervisor.ps1"
|
||||
CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Heimdall.Application\Heimdall.Application.csproj" />
|
||||
<ProjectReference Include="..\Heimdall.Contracts\Heimdall.Contracts.csproj" />
|
||||
|
||||
@@ -93,6 +93,12 @@ public class ConfigBroadcastService : IConfigBroadcastService
|
||||
_logger.LogDebug("Broadcasting global setting change: {Key}", key);
|
||||
var access = services.GetRequiredService<ResourceAccess>();
|
||||
var subscriptions = services.GetRequiredService<LiveSubscriptions>();
|
||||
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<IApplicationDbContext>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Requests an immediate update check from connected, authorized agents.</summary>
|
||||
|
||||
@@ -1723,7 +1723,16 @@
|
||||
<value>Automatic agent updates</value>
|
||||
</data>
|
||||
<data name="SitesPage_AutoUpdateHelper" xml:space="preserve">
|
||||
<value>Allow agents at this site to update automatically from the central server.</value>
|
||||
<value>Choose whether this site inherits the global setting or overrides it.</value>
|
||||
</data>
|
||||
<data name="SitesPage_AutoUpdateInherit" xml:space="preserve">
|
||||
<value>Inherit global setting</value>
|
||||
</data>
|
||||
<data name="SitesPage_AutoUpdateEnabled" xml:space="preserve">
|
||||
<value>Enabled</value>
|
||||
</data>
|
||||
<data name="SitesPage_AutoUpdateDisabled" xml:space="preserve">
|
||||
<value>Disabled</value>
|
||||
</data>
|
||||
<data name="SitesPage_CameraCount" xml:space="preserve">
|
||||
<value>camera(s)</value>
|
||||
@@ -2625,6 +2634,15 @@
|
||||
<data name="AgentDefaultsSection_Global" xml:space="preserve">
|
||||
<value>Global</value>
|
||||
</data>
|
||||
<data name="AgentDefaultsSection_Updates" xml:space="preserve">
|
||||
<value>Updates</value>
|
||||
</data>
|
||||
<data name="AgentDefaultsSection_AutoUpdate" xml:space="preserve">
|
||||
<value>Automatic updates for native agents</value>
|
||||
</data>
|
||||
<data name="AgentDefaultsSection_AutoUpdateHelp" xml:space="preserve">
|
||||
<value>Enable automatic updates for native agents by default. Sites can override this. New releases wait 24 hours before automatic installation.</value>
|
||||
</data>
|
||||
<data name="AgentDefaultsSection_Heartbeat" xml:space="preserve">
|
||||
<value>Heartbeat</value>
|
||||
</data>
|
||||
@@ -3984,4 +4002,58 @@
|
||||
<data name="AdminAllAgents_Title" xml:space="preserve">
|
||||
<value>Agents</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_OperatingSystem" xml:space="preserve">
|
||||
<value>Operating system</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Linux" xml:space="preserve">
|
||||
<value>Linux</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Windows" xml:space="preserve">
|
||||
<value>Windows</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Docker" xml:space="preserve">
|
||||
<value>Docker</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Method" xml:space="preserve">
|
||||
<value>Method</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_SystemdService" xml:space="preserve">
|
||||
<value>Systemd service</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_PowerShellRun" xml:space="preserve">
|
||||
<value>PowerShell — user process</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_WindowsService" xml:space="preserve">
|
||||
<value>Windows Service</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Configuration" xml:space="preserve">
|
||||
<value>Configuration</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Commands" xml:space="preserve">
|
||||
<value>Commands</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Install" xml:space="preserve">
|
||||
<value>Install</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_InstallAndRun" xml:space="preserve">
|
||||
<value>Install and run</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Run" xml:space="preserve">
|
||||
<value>Run</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Check" xml:space="preserve">
|
||||
<value>Check</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_DockerUpdateNote" xml:space="preserve">
|
||||
<value>Update containers through Docker or Kubernetes. Heimdall pins each image to its signed digest.</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_WindowsConsoleNote" xml:space="preserve">
|
||||
<value>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.</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_WindowsServiceAdminNote" xml:space="preserve">
|
||||
<value>This installs a Windows Service and requires administrator rights. The service starts automatically with Windows.</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_DockerRun" xml:space="preserve">
|
||||
<value>Docker Run</value>
|
||||
</data>
|
||||
</root>
|
||||
@@ -1723,7 +1723,16 @@
|
||||
<value>Mises à jour automatiques des agents</value>
|
||||
</data>
|
||||
<data name="SitesPage_AutoUpdateHelper" xml:space="preserve">
|
||||
<value>Autoriser les agents de ce site à se mettre à jour automatiquement depuis le serveur central.</value>
|
||||
<value>Choisir si ce site hérite du réglage global ou le remplace.</value>
|
||||
</data>
|
||||
<data name="SitesPage_AutoUpdateInherit" xml:space="preserve">
|
||||
<value>Hériter du réglage global</value>
|
||||
</data>
|
||||
<data name="SitesPage_AutoUpdateEnabled" xml:space="preserve">
|
||||
<value>Activées</value>
|
||||
</data>
|
||||
<data name="SitesPage_AutoUpdateDisabled" xml:space="preserve">
|
||||
<value>Désactivées</value>
|
||||
</data>
|
||||
<data name="SitesPage_CameraCount" xml:space="preserve">
|
||||
<value>caméra(s)</value>
|
||||
@@ -2625,6 +2634,15 @@
|
||||
<data name="AgentDefaultsSection_Global" xml:space="preserve">
|
||||
<value>Globaux</value>
|
||||
</data>
|
||||
<data name="AgentDefaultsSection_Updates" xml:space="preserve">
|
||||
<value>Mises à jour</value>
|
||||
</data>
|
||||
<data name="AgentDefaultsSection_AutoUpdate" xml:space="preserve">
|
||||
<value>Mises à jour automatiques des agents natifs</value>
|
||||
</data>
|
||||
<data name="AgentDefaultsSection_AutoUpdateHelp" xml:space="preserve">
|
||||
<value>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.</value>
|
||||
</data>
|
||||
<data name="AgentDefaultsSection_Heartbeat" xml:space="preserve">
|
||||
<value>Heartbeat</value>
|
||||
</data>
|
||||
@@ -3984,4 +4002,58 @@
|
||||
<data name="AdminAllAgents_Title" xml:space="preserve">
|
||||
<value>Agents</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_OperatingSystem" xml:space="preserve">
|
||||
<value>Système d’exploitation</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Linux" xml:space="preserve">
|
||||
<value>Linux</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Windows" xml:space="preserve">
|
||||
<value>Windows</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Docker" xml:space="preserve">
|
||||
<value>Docker</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Method" xml:space="preserve">
|
||||
<value>Méthode</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_SystemdService" xml:space="preserve">
|
||||
<value>Service systemd</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_PowerShellRun" xml:space="preserve">
|
||||
<value>PowerShell — exécution utilisateur</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_WindowsService" xml:space="preserve">
|
||||
<value>Service Windows</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Configuration" xml:space="preserve">
|
||||
<value>Configuration</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Commands" xml:space="preserve">
|
||||
<value>Commandes</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Install" xml:space="preserve">
|
||||
<value>Installer</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_InstallAndRun" xml:space="preserve">
|
||||
<value>Installer et lancer</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Run" xml:space="preserve">
|
||||
<value>Lancer</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Check" xml:space="preserve">
|
||||
<value>Vérifier</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_DockerUpdateNote" xml:space="preserve">
|
||||
<value>Les mises à jour des conteneurs passent par Docker ou Kubernetes. Heimdall épingle chaque image sur son digest signé.</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_WindowsConsoleNote" xml:space="preserve">
|
||||
<value>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.</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_WindowsServiceAdminNote" xml:space="preserve">
|
||||
<value>Ce mode installe un service Windows et demande des droits administrateur. Le service démarre automatiquement avec Windows.</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_DockerRun" xml:space="preserve">
|
||||
<value>Docker Run</value>
|
||||
</data>
|
||||
</root>
|
||||
@@ -1720,10 +1720,19 @@
|
||||
<value>agent(s)</value>
|
||||
</data>
|
||||
<data name="SitesPage_AutoUpdate" xml:space="preserve">
|
||||
<value>Mises à jour automatiques des agents</value>
|
||||
<value>Automatic agent updates</value>
|
||||
</data>
|
||||
<data name="SitesPage_AutoUpdateHelper" xml:space="preserve">
|
||||
<value>Autoriser les agents de ce site à se mettre à jour automatiquement depuis le serveur central.</value>
|
||||
<value>Choose whether this site inherits the global setting or overrides it.</value>
|
||||
</data>
|
||||
<data name="SitesPage_AutoUpdateInherit" xml:space="preserve">
|
||||
<value>Inherit global setting</value>
|
||||
</data>
|
||||
<data name="SitesPage_AutoUpdateEnabled" xml:space="preserve">
|
||||
<value>Enabled</value>
|
||||
</data>
|
||||
<data name="SitesPage_AutoUpdateDisabled" xml:space="preserve">
|
||||
<value>Disabled</value>
|
||||
</data>
|
||||
<data name="SitesPage_CameraCount" xml:space="preserve">
|
||||
<value>caméra(s)</value>
|
||||
@@ -2625,6 +2634,15 @@
|
||||
<data name="AgentDefaultsSection_Global" xml:space="preserve">
|
||||
<value>Globaux</value>
|
||||
</data>
|
||||
<data name="AgentDefaultsSection_Updates" xml:space="preserve">
|
||||
<value>Updates</value>
|
||||
</data>
|
||||
<data name="AgentDefaultsSection_AutoUpdate" xml:space="preserve">
|
||||
<value>Automatic updates for native agents</value>
|
||||
</data>
|
||||
<data name="AgentDefaultsSection_AutoUpdateHelp" xml:space="preserve">
|
||||
<value>Enable automatic updates for native agents by default. Sites can override this. New releases wait 24 hours before automatic installation.</value>
|
||||
</data>
|
||||
<data name="AgentDefaultsSection_Heartbeat" xml:space="preserve">
|
||||
<value>Heartbeat</value>
|
||||
</data>
|
||||
@@ -3984,4 +4002,58 @@
|
||||
<data name="AdminAllAgents_Title" xml:space="preserve">
|
||||
<value>Agents</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_OperatingSystem" xml:space="preserve">
|
||||
<value>Operating system</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Linux" xml:space="preserve">
|
||||
<value>Linux</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Windows" xml:space="preserve">
|
||||
<value>Windows</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Docker" xml:space="preserve">
|
||||
<value>Docker</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Method" xml:space="preserve">
|
||||
<value>Method</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_SystemdService" xml:space="preserve">
|
||||
<value>Systemd service</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_PowerShellRun" xml:space="preserve">
|
||||
<value>PowerShell — user process</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_WindowsService" xml:space="preserve">
|
||||
<value>Windows Service</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Configuration" xml:space="preserve">
|
||||
<value>Configuration</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Commands" xml:space="preserve">
|
||||
<value>Commands</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Install" xml:space="preserve">
|
||||
<value>Install</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_InstallAndRun" xml:space="preserve">
|
||||
<value>Install and run</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Run" xml:space="preserve">
|
||||
<value>Run</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_Check" xml:space="preserve">
|
||||
<value>Check</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_DockerUpdateNote" xml:space="preserve">
|
||||
<value>Update containers through Docker or Kubernetes. Heimdall pins each image to its signed digest.</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_WindowsConsoleNote" xml:space="preserve">
|
||||
<value>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.</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_WindowsServiceAdminNote" xml:space="preserve">
|
||||
<value>This installs a Windows Service and requires administrator rights. The service starts automatically with Windows.</value>
|
||||
</data>
|
||||
<data name="SiteInstallPanel_DockerRun" xml:space="preserve">
|
||||
<value>Docker Run</value>
|
||||
</data>
|
||||
</root>
|
||||
@@ -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(
|
||||
|
||||
@@ -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<string, PlatformAssetInfo> 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<string, PlatformAssetInfo> 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);
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
Reference in new issue
Block a user