Heimdall Gitea / Detect CI scope (push) Successful in 5s
Heimdall Gitea / Build and tests (push) Successful in 20m50s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 6m39s
Heimdall Gitea / Build and scan agent image (push) Successful in 9m12s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m21s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 20m14s
Heimdall Gitea / CI policy (push) Successful in 3s
Refs #293 Co-authored-by: Arnaud Dartois <admin@tordais.cc>
308 lines
17 KiB
PowerShell
308 lines
17 KiB
PowerShell
[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",
|
|
"MODEL_PATH=$(Join-Path $releasePath 'models\yolov8n.onnx')",
|
|
"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
|
|
}
|