Add safe configuration capture command

This commit is contained in:
Dandaedre 2026-10-17 10:09:32 +02:00
parent 3d6cb0317b
commit 493838a4a8
5 changed files with 124 additions and 6 deletions

View File

@ -107,6 +107,7 @@ open until it is run on disposable machines with the required account setups.
## Requested desktop configuration
- [x] Show each managed config's repository source and resolved computer path.
- [x] Capture live configs under Documents for review and upload without exporting Nextcloud credentials.
- [x] Add the requested WinGet packages: XnView MP, Zoom, Nextcloud Desktop,
Notepad++, HandBrake, GIMP, Krita, LibreOffice, Waterfox, and Shotcut.
- [x] Add a safe registry-value adapter for MPC-HC settings.

5
cc.ps1
View File

@ -1,8 +1,9 @@
[CmdletBinding()]
param(
[Parameter(Position = 0)][ValidateSet('doctor', 'plan', 'apply', 'sync', 'status', 'configs', 'restore', 'schedule', 'unschedule', 'menu')][string]$Command = 'menu',
[Parameter(Position = 0)][ValidateSet('doctor', 'plan', 'apply', 'sync', 'status', 'configs', 'capture', 'restore', 'schedule', 'unschedule', 'menu')][string]$Command = 'menu',
[string]$Machine,
[string]$Config,
[string]$OutputPath,
[switch]$ConfigsOnly,
[switch]$ForceConfigs,
[switch]$Json,
@ -33,7 +34,7 @@ try {
Show-ConfigCentralMenu -Machine $Machine -DataRoot $DataRoot -RepositoryRoot $RepositoryRoot
exit 0
}
$result = Invoke-ConfigCentral -Command $Command -Machine $Machine -Config $Config -ConfigsOnly:$ConfigsOnly -ForceConfigs:$ForceConfigs -Paths $paths -RepositoryRoot $RepositoryRoot -FromSnapshot:$FromSnapshot -Revision $Revision
$result = Invoke-ConfigCentral -Command $Command -Machine $Machine -Config $Config -ConfigsOnly:$ConfigsOnly -ForceConfigs:$ForceConfigs -OutputPath $OutputPath -Paths $paths -RepositoryRoot $RepositoryRoot -FromSnapshot:$FromSnapshot -Revision $Revision
if ($Json) { $result | ConvertTo-Json -Depth 32 }
else { Write-ConfigCentralResult $result }
exit ([int]$result.exitCode)

View File

@ -112,6 +112,88 @@ function Get-ConfigLocations {
return @($locations)
}
function Export-ConfigCapture {
param(
[Parameter(Mandatory)]$Configs,
[Parameter(Mandatory)][string]$RepositoryRoot,
[Parameter(Mandatory)]$Settings,
[Parameter(Mandatory)][string]$Machine,
[string]$Name,
[string]$OutputPath
)
if ([string]::IsNullOrWhiteSpace($OutputPath)) {
$documents = [Environment]::GetFolderPath([Environment+SpecialFolder]::MyDocuments)
if ([string]::IsNullOrWhiteSpace($documents)) {
$pathMap = Get-UserPathMap -Settings $Settings
if (-not $pathMap.Contains('USERPROFILE')) { throw 'The Documents directory could not be resolved.' }
$documents = Join-Path $pathMap.USERPROFILE 'Documents'
}
$captureName = "$Machine-$([DateTimeOffset]::Now.ToString('yyyyMMdd-HHmmss'))"
$OutputPath = Join-Path (Join-Path $documents 'ConfigCentral\captures') $captureName
}
$captureRoot = [IO.Path]::GetFullPath($OutputPath)
if (Test-Path -LiteralPath $captureRoot) { throw "Capture destination already exists: '$captureRoot'." }
[void](New-Item -ItemType Directory -Path $captureRoot -Force)
$selectedConfigs = @($Configs)
if (-not [string]::IsNullOrWhiteSpace($Name)) {
$selectedConfigs = @($selectedConfigs | Where-Object name -eq $Name)
if ($selectedConfigs.Count -eq 0) { throw "Unknown config '$Name'." }
}
$locations = @(Get-ConfigLocations -Configs $selectedConfigs -RepositoryRoot $RepositoryRoot -Settings $Settings)
$operations = [Collections.Generic.List[object]]::new()
foreach ($config in $selectedConfigs) {
$location = $locations | Where-Object name -eq $config.name | Select-Object -First 1
if (-not $location.targetExists) {
$operations.Add([pscustomobject]@{ kind = 'config'; name = $config.name; status = 'Missing'; message = "Computer source is absent: $($location.target)" })
continue
}
if ($config.name -eq 'nextcloud-settings') {
$operations.Add([pscustomobject]@{ kind = 'config'; name = $config.name; status = 'Excluded'; message = 'Complete Nextcloud config may contain credentials and was not captured.' })
continue
}
if ($config.mode -eq 'copy') {
$relative = ([string]$config.source).Replace('/', [IO.Path]::DirectorySeparatorChar)
$destination = Join-Path $captureRoot $relative
$status = 'Captured'
}
elseif ($config.mode -eq 'registry' -and $config.name -eq 'mpc-hc-settings') {
$destination = Join-Path $captureRoot 'review\mpc-hc-settings\settings.json'
[void](New-Item -ItemType Directory -Path (Split-Path -Parent $destination) -Force)
& (Join-Path $RepositoryRoot 'tools\Export-MpcHcSettings.ps1') -OutputPath $destination
$operations.Add([pscustomobject]@{ kind = 'config'; name = $config.name; status = 'Review'; message = $destination })
continue
}
else {
$fileName = if ($config.mode -eq 'hosts-block') { 'hosts' } else { [IO.Path]::GetFileName($location.target) }
$destination = Join-Path $captureRoot "review\$($config.name)\$fileName"
$status = 'Review'
}
[void](New-Item -ItemType Directory -Path (Split-Path -Parent $destination) -Force)
Copy-Item -LiteralPath $location.target -Destination $destination
$operations.Add([pscustomobject]@{ kind = 'config'; name = $config.name; status = $status; message = $destination })
}
$readme = @(
'Config Central configuration capture',
'',
'Files below configs/ retain their repository-relative paths.',
'Files below review/ are raw exports and must be curated before committing.',
'The complete Nextcloud configuration is never captured because it may contain credentials.'
) -join [Environment]::NewLine
[IO.File]::WriteAllText((Join-Path $captureRoot 'README.txt'), $readme + [Environment]::NewLine, [Text.UTF8Encoding]::new($false))
$manifest = [ordered]@{
schemaVersion = 1
machine = $Machine
capturedAt = [DateTimeOffset]::Now.ToString('o')
repositoryRevision = Get-RepositoryRevision -RepositoryRoot $RepositoryRoot
operations = @($operations)
}
[IO.File]::WriteAllText((Join-Path $captureRoot 'capture.json'), ($manifest | ConvertTo-Json -Depth 8), [Text.UTF8Encoding]::new($false))
return [pscustomobject]@{ path = $captureRoot; operations = @($operations) }
}
function Backup-ConfigTarget {
param($Operation, $Paths)
if (-not (Test-Path -LiteralPath $Operation.target -PathType Leaf)) { return $null }
@ -193,4 +275,4 @@ function Restore-ConfigBackup {
[pscustomobject]@{ name = $Name; status = 'Restored'; message = "Restored $($backup.FullName)" }
}
Export-ModuleMember -Function Get-UserPathMap, Resolve-ConfigTarget, Resolve-ConfigSource, Get-FileHashValue, Get-ConfigPlan, Get-ConfigLocations, Invoke-ConfigOperation, Restore-ConfigBackup
Export-ModuleMember -Function Get-UserPathMap, Resolve-ConfigTarget, Resolve-ConfigSource, Get-FileHashValue, Get-ConfigPlan, Get-ConfigLocations, Export-ConfigCapture, Invoke-ConfigOperation, Restore-ConfigBackup

View File

@ -128,7 +128,7 @@ function Invoke-SnapshotApply {
function Invoke-ConfigCentral {
param(
[string]$Command, [string]$Machine, [string]$Config, [switch]$ConfigsOnly,
[switch]$ForceConfigs, $Paths, [string]$RepositoryRoot, [switch]$FromSnapshot,
[switch]$ForceConfigs, [string]$OutputPath, $Paths, [string]$RepositoryRoot, [switch]$FromSnapshot,
[string]$Revision
)
if ($Command -eq 'doctor') { return Invoke-Doctor -Machine $Machine -RepositoryRoot $RepositoryRoot -Paths $Paths }
@ -139,6 +139,15 @@ function Invoke-ConfigCentral {
$result.operations = @(Get-ConfigLocations -Configs $effective.configs -RepositoryRoot $RepositoryRoot -Settings $settings -Name $Config)
return [pscustomobject]$result
}
if ($Command -eq 'capture') {
$settings = Read-JsonState -Path $Paths.Settings -Default ([ordered]@{})
$effective = Resolve-MachineManifest -RepositoryRoot $RepositoryRoot -Machine $Machine
$capture = Export-ConfigCapture -Configs $effective.configs -RepositoryRoot $RepositoryRoot -Settings $settings -Machine $Machine -Name $Config -OutputPath $OutputPath
$result = New-BaseResult 'capture'
$result.operations = @($capture.operations)
$result | Add-Member -NotePropertyName capturePath -NotePropertyValue $capture.path
return [pscustomobject]$result
}
if ($Command -eq 'restore') {
if ([string]::IsNullOrWhiteSpace($Config)) { throw 'restore requires -Config NAME.' }
$state = Read-JsonState -Path $Paths.State -Default ([ordered]@{})
@ -190,9 +199,9 @@ function Write-ConfigCentralResult {
function Show-ConfigCentralMenu {
param([string]$Machine, [string]$DataRoot, [string]$RepositoryRoot)
Write-Host 'Config Central'
Write-Host '1. Plan 2. Sync 3. Status 4. Doctor 5. Schedule 6. Config paths Q. Quit'
Write-Host '1. Plan 2. Sync 3. Status 4. Doctor 5. Schedule 6. Config paths 7. Capture configs Q. Quit'
$choice = Read-Host 'Select'
$command = switch ($choice.ToUpperInvariant()) { '1' { 'plan' } '2' { 'sync' } '3' { 'status' } '4' { 'doctor' } '5' { 'schedule' } '6' { 'configs' } 'Q' { return } default { throw "Unknown menu choice '$choice'." } }
$command = switch ($choice.ToUpperInvariant()) { '1' { 'plan' } '2' { 'sync' } '3' { 'status' } '4' { 'doctor' } '5' { 'schedule' } '6' { 'configs' } '7' { 'capture' } 'Q' { return } default { throw "Unknown menu choice '$choice'." } }
$arguments = @($command, '-RepositoryRoot', $RepositoryRoot)
if ($Machine) { $arguments += @('-Machine', $Machine) }
if ($DataRoot) { $arguments += @('-DataRoot', $DataRoot) }

View File

@ -1,5 +1,6 @@
BeforeAll {
Import-Module "$PSScriptRoot/../src/State.psm1" -Force
Import-Module "$PSScriptRoot/../src/Repository.psm1" -Force
Import-Module "$PSScriptRoot/../src/Configs.psm1" -Force
}
@ -71,6 +72,30 @@ Describe 'Configuration deployment' {
{ Get-ConfigLocations -Configs $configs -RepositoryRoot $repo -Settings $settings -Name missing } | Should -Throw "*Unknown config 'missing'*"
}
It 'captures safe files for upload and excludes the complete Nextcloud config' {
Mock Get-RepositoryRevision { 'abc123' } -ModuleName Configs
$xnviewTarget = Join-Path $caseRoot 'user/xnview.ini'
$nextcloudTarget = Join-Path $caseRoot 'user/nextcloud.cfg'
New-Item -ItemType Directory (Split-Path -Parent $xnviewTarget) -Force | Out-Null
'computer value' | Set-Content $destination -NoNewline
'portable=true' | Set-Content $xnviewTarget -NoNewline
'token=never-export-this' | Set-Content $nextcloudTarget -NoNewline
'; overlay' | Set-Content "$repo/configs/xnview.ini"
'; safe keys only' | Set-Content "$repo/configs/nextcloud.ini"
$captureConfigs = @(
$configs[0],
[pscustomobject]@{ name = 'xnviewmp-settings'; source = 'configs/xnview.ini'; target = $xnviewTarget; mode = 'ini-overlay' },
[pscustomobject]@{ name = 'nextcloud-settings'; source = 'configs/nextcloud.ini'; target = $nextcloudTarget; mode = 'ini-overlay' }
)
$output = Join-Path $caseRoot 'capture'
$capture = Export-ConfigCapture -Configs $captureConfigs -RepositoryRoot $repo -Settings $settings -Machine test -OutputPath $output
(Get-Content "$output/configs/config.txt" -Raw) | Should -Be 'computer value'
(Get-Content "$output/review/xnviewmp-settings/xnview.ini" -Raw) | Should -Be 'portable=true'
Get-ChildItem $output -Recurse -File | Where-Object Name -eq 'nextcloud.cfg' | Should -BeNullOrEmpty
($capture.operations | Where-Object name -eq 'nextcloud-settings').status | Should -Be 'Excluded'
(Get-Content "$output/capture.json" -Raw | ConvertFrom-Json).repositoryRevision | Should -Be 'abc123'
}
It 'refuses unsafe automatic restoration of registry and hosts backups' {
$registryState = @{ configs = @{ 'mpc-hc-settings' = @{ mode = 'registry'; target = 'HKCU:\Software\MPC-HC\MPC-HC' } } }
{ Restore-ConfigBackup -Name mpc-hc-settings -Paths $paths -State $registryState } | Should -Throw '*not supported for registry*'