diff --git a/TASKS.md b/TASKS.md index 20a04e4..77edd8d 100644 --- a/TASKS.md +++ b/TASKS.md @@ -154,6 +154,6 @@ open until it is run on disposable machines with the required account setups. - [x] Document portable package identity, pinning, storage and recovery semantics. - [x] Validate and resolve portable package declarations alongside WinGet (17 Linux Pester tests pass). -- [ ] Implement portable ZIP planning, verified staging, launchers and recovery with focused tests. +- [x] Implement portable ZIP planning, verified staging, launchers and recovery with Linux Pester tests; keep Windows acceptance below open. - [ ] Add the verified PDF Presenter release to the desktop profile and document updates. - [ ] Validate portable installation, Start menu launch and running-app handling on disposable Windows x64. diff --git a/src/Core.psm1 b/src/Core.psm1 index 5903d46..7933690 100644 --- a/src/Core.psm1 +++ b/src/Core.psm1 @@ -13,8 +13,9 @@ function Get-OperationPlan { $effective = Resolve-MachineManifest -RepositoryRoot $RepositoryRoot -Machine $Machine $packagePlan = @() if (-not $ConfigsOnly) { - $inventory = Get-WingetInventory - $packagePlan = @(Get-PackagePlan -Packages $effective.packages -Inventory $inventory) + $wingetPackages = @($effective.packages | Where-Object { -not $_.PSObject.Properties['provider'] -or $_.provider -eq 'winget' }) + $inventory = if ($wingetPackages.Count) { Get-WingetInventory } else { @{} } + $packagePlan = @(Get-PackagePlan -Packages $effective.packages -Inventory $inventory -DataRoot $Paths.Root) } $configPlan = @(Get-ConfigPlan -Configs $effective.configs -RepositoryRoot $RepositoryRoot -State $state -Settings $settings) [pscustomobject]@{ effective = $effective; packages = $packagePlan; configs = $configPlan; state = $state; settings = $settings } @@ -77,7 +78,7 @@ function Invoke-ApplyPlan { } foreach ($packageResult in $packageResults) { [void](Add-RunResult -Run $run -Kind package -Name $packageResult.name -Status $packageResult.status -Message $packageResult.message) - if ($packageResult.status -eq 'Failed') { [void]$failedPackages.Add($packageResult.name) } + if ($packageResult.status -in @('Failed', 'Conflict')) { [void]$failedPackages.Add($packageResult.name) } if ($packageResult.PSObject.Properties['rebootRequired'] -and $packageResult.rebootRequired) { $rebootRequired = $true } } diff --git a/src/Elevation.psm1 b/src/Elevation.psm1 index ca2ddc6..3abf88d 100644 --- a/src/Elevation.psm1 +++ b/src/Elevation.psm1 @@ -20,6 +20,9 @@ function Protect-ElevationFile { function Invoke-ElevatedPackageBatch { param([Parameter(Mandatory)]$Operations, [Parameter(Mandatory)][string]$RepositoryRoot, [Parameter(Mandatory)]$Paths, [string]$LogPath) if (@($Operations).Count -eq 0) { return @() } + foreach ($operation in $Operations) { + if ($operation.package.PSObject.Properties['provider'] -and $operation.package.provider -ne 'winget') { throw 'Only WinGet packages may use the elevated worker.' } + } if (Test-IsAdministrator) { return Invoke-PackagePlan -Plan $Operations -LogPath $LogPath } $requestId = [guid]::NewGuid().ToString('N') diff --git a/src/Manifest.psm1 b/src/Manifest.psm1 index cd06836..b3581c0 100644 --- a/src/Manifest.psm1 +++ b/src/Manifest.psm1 @@ -48,6 +48,7 @@ function Get-OptionalProperty { function Assert-PortableDeclaration { param($Item, [string]$Source) if ($Source -cnotmatch '^[a-z0-9][a-z0-9-]{0,63}$' -or $Item.id -cnotmatch '^[a-z0-9][a-z0-9-]{0,63}$') { throw 'Portable source and id must be lowercase slugs.' } + if ($Source -match '^(con|prn|aux|nul|com[1-9]|lpt[1-9])$' -or $Item.id -match '^(con|prn|aux|nul|com[1-9]|lpt[1-9])$') { throw 'Portable identity cannot use reserved Windows device names.' } if ((Get-OptionalProperty $Item 'scope' 'user') -ne 'user') { throw 'Portable packages require user scope.' } if (-not (Get-OptionalProperty $Item 'enabled' $true)) { return } foreach ($field in @('version', 'url', 'sha256', 'executable', 'update')) { diff --git a/src/Packages.psm1 b/src/Packages.psm1 index 2c9f59f..5ee3a41 100644 --- a/src/Packages.psm1 +++ b/src/Packages.psm1 @@ -1,4 +1,5 @@ Set-StrictMode -Version Latest +Import-Module (Join-Path $PSScriptRoot 'PortablePackages.psm1') -Force $script:WingetNoApplicationsFound = [Convert]::ToUInt32('8A150014', 16) $script:WingetNoApplicableUpgrade = [Convert]::ToUInt32('8A15002B', 16) @@ -55,9 +56,13 @@ function Get-WingetInventory { } function Get-PackagePlan { - param([Parameter(Mandatory)]$Packages, [Parameter(Mandatory)]$Inventory) + param([Parameter(Mandatory)]$Packages, [Parameter(Mandatory)]$Inventory, [string]$DataRoot) $plan = [System.Collections.Generic.List[object]]::new() foreach ($package in @($Packages)) { + if ($package.PSObject.Properties['provider'] -and $package.provider -eq 'portable') { + $plan.Add((Get-PortablePackagePlan -Package $package -DataRoot $DataRoot)) + continue + } $key = "$($package.source)/$($package.id)".ToLowerInvariant() $installed = if ($Inventory.Contains($key)) { $Inventory[$key] } else { $null } $versionProperty = $package.PSObject.Properties['version'] @@ -88,6 +93,9 @@ function Get-PackagePlan { function Invoke-PackageOperation { param([Parameter(Mandatory)]$Operation, [string]$LogPath) + if ($Operation.package.PSObject.Properties['provider'] -and $Operation.package.provider -eq 'portable') { + return Invoke-PortablePackageOperation -Operation $Operation + } if ($Operation.action -in @('None', 'Warning')) { return [pscustomobject]@{ name = $Operation.name; status = $Operation.action; exitCode = 0; rebootRequired = $false; message = $Operation.reason } } diff --git a/src/PortablePackages.psm1 b/src/PortablePackages.psm1 new file mode 100644 index 0000000..4a6839a --- /dev/null +++ b/src/PortablePackages.psm1 @@ -0,0 +1,200 @@ +Set-StrictMode -Version Latest + +function Assert-PortableRelativePath { + param([string]$Path) + if (-not $Path -or $Path -match '[\\:<>"|?*\x00-\x1f]' -or $Path.StartsWith('/')) { throw "Unsafe portable path '$Path'." } + foreach ($part in $Path.TrimEnd('/') -split '/') { + if ($part -in @('', '.', '..') -or $part -match '[. ]$|^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)') { throw "Unsafe portable path '$Path'." } + } +} + +function Assert-PortableNoLinks { + param([string]$Path) + $cursor = [IO.Path]::GetFullPath($Path) + while ($cursor) { + if (Test-Path -LiteralPath $cursor) { + if ((Get-Item -LiteralPath $cursor -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Portable path is a link: '$cursor'. Remove the link before retrying." } + } + $cursor = Split-Path -Parent $cursor + } +} + +function Get-PortableProgramsPath { + [Environment]::GetFolderPath('Programs') +} + +function Get-PortablePaths { + param($Package, [string]$DataRoot) + if (-not $DataRoot) { throw 'Portable packages require a data root.' } + foreach ($value in @($Package.source, $Package.id)) { + if ($value -cnotmatch '^[a-z0-9][a-z0-9-]{0,63}$' -or $value -match '^(con|prn|aux|nul|com[1-9]|lpt[1-9])$') { throw 'Unsafe portable package identity.' } + } + $root = Join-Path $DataRoot "apps/$($Package.source)/$($Package.id)" + Assert-PortableNoLinks $root + $programs = Get-PortableProgramsPath + [pscustomobject]@{ + Root = $root + Receipt = Join-Path $root 'current.json' + Launcher = Join-Path $root 'launch.ps1' + Shortcut = $(if ($programs) { Join-Path $programs "Config Central/$($Package.source)/$($Package.id).lnk" } else { $null }) + } +} + +function Get-PortableLauncherContent { + Get-Content -LiteralPath (Join-Path $PSScriptRoot 'portable-launcher.ps1') -Raw +} + +function Get-PortablePackagePlan { + param($Package, [string]$DataRoot) + $ErrorActionPreference = 'Stop' + $action = 'Install'; $reason = 'Portable package is absent' + $paths = Get-PortablePaths $Package $DataRoot + try { + if (Test-Path -LiteralPath $paths.Receipt) { + Assert-PortableNoLinks $paths.Receipt + $receipt = Get-Content -LiteralPath $paths.Receipt -Raw | ConvertFrom-Json -AsHashtable + if ($receipt.schemaVersion -ne 1 -or $receipt.directory -notmatch '^versions/[0-9.]+-[a-f0-9]{32}$') { throw 'Invalid portable receipt; inspect current.json before retrying.' } + Assert-PortableRelativePath $receipt.executable + $missing = $false + if ($receipt.files.Count -eq 0 -or -not $receipt.files.Contains($receipt.executable)) { throw 'Incomplete portable receipt.' } + foreach ($relative in $receipt.files.Keys) { + Assert-PortableRelativePath $relative + $path = Join-Path $paths.Root "$($receipt.directory)/$relative" + Assert-PortableNoLinks $path + if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { $missing = $true; continue } + if ((Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash -ne $receipt.files[$relative]) { throw "Locally modified portable file '$path'; inspect it before retrying." } + } + if (Test-Path -LiteralPath $paths.Launcher) { + Assert-PortableNoLinks $paths.Launcher + if ([IO.File]::ReadAllText($paths.Launcher) -cne (Get-PortableLauncherContent)) { throw "Locally modified launcher '$($paths.Launcher)'; inspect it before retrying." } + } + else { $missing = $true } + if ($paths.Shortcut -and -not (Test-Path -LiteralPath $paths.Shortcut)) { $missing = $true } + if ($receipt.version -eq $Package.version -and $receipt.sha256 -ne $Package.sha256) { throw 'Archive checksum changed without a version change; publish a new version before retrying.' } + if ($missing) { + if ($receipt.version -ne $Package.version -and ($Package.update -eq 'install-only' -or [version]$receipt.version -gt [version]$Package.version)) { throw 'Installed files are missing; pin the installed version to repair it without changing update policy.' } + $reason = 'Repair missing portable installation files or launcher' + } + elseif ($Package.update -eq 'install-only') { $action = 'None'; $reason = "Installed ($($receipt.version)); install-only policy" } + elseif ([version]$receipt.version -gt [version]$Package.version) { $action = 'Warning'; $reason = "Installed $($receipt.version) is newer than requested $($Package.version)" } + elseif ($receipt.version -eq $Package.version -and $receipt.executable -eq $Package.executable) { $action = 'None'; $reason = "Pinned version $($Package.version) is installed and verified" } + else { $reason = "Move $($receipt.version) to pinned $($Package.version)" } + } + elseif (Test-Path -LiteralPath $paths.Launcher) { + Assert-PortableNoLinks $paths.Launcher + if ([IO.File]::ReadAllText($paths.Launcher) -cne (Get-PortableLauncherContent)) { throw 'Unrecognized portable launcher; inspect it before retrying.' } + } + } + catch { $action = 'Conflict'; $reason = $_.Exception.Message } + [pscustomobject]@{ kind = 'package'; name = $Package.id; action = $action; reason = $reason; package = $Package; dataRoot = $DataRoot } +} + +function Expand-PortableArchive { + param([string]$Archive, [string]$Destination) + $zip = [IO.Compression.ZipFile]::OpenRead($Archive) + try { + $names = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase) + $size = 0L + foreach ($entry in $zip.Entries) { + Assert-PortableRelativePath $entry.FullName + if (-not $names.Add($entry.FullName.TrimEnd('/'))) { throw 'ZIP contains colliding paths.' } + $unixType = ($entry.ExternalAttributes -shr 16) -band 0xF000 + if ($unixType -notin @(0, 0x8000, 0x4000) -or ($entry.ExternalAttributes -band 0x400)) { throw 'ZIP contains links or special files.' } + $size += $entry.Length + if ($size -gt 2GB) { throw 'Portable ZIP exceeds the 2 GiB expanded size limit.' } + } + [IO.Compression.ZipFileExtensions]::ExtractToDirectory($zip, $Destination) + } + finally { $zip.Dispose() } +} + +function Assert-PortablePlatform { + if (-not $IsWindows -or [Runtime.InteropServices.RuntimeInformation]::OSArchitecture -ne 'X64') { throw 'Portable packages currently require Windows x64.' } +} + +function Assert-PortableStopped { + param([string]$Root) + $prefix = [IO.Path]::GetFullPath($Root) + [IO.Path]::DirectorySeparatorChar + foreach ($process in Get-Process) { + if ($process.Path -and $process.Path.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) { throw "Close '$($process.ProcessName)' before updating this portable package." } + } +} + +function Set-PortableShortcut { + param($Paths) + if (-not $Paths.Shortcut) { throw 'The desktop user Start menu directory is unavailable.' } + Assert-PortableNoLinks $Paths.Shortcut + [void][IO.Directory]::CreateDirectory((Split-Path -Parent $Paths.Shortcut)) + $temporary = "$($Paths.Shortcut).$([guid]::NewGuid().ToString('N')).lnk" + try { + $shell = New-Object -ComObject WScript.Shell + $shortcut = $shell.CreateShortcut($temporary) + $shortcut.TargetPath = Join-Path $PSHOME 'pwsh.exe' + $shortcut.Arguments = '-NoLogo -NoProfile -ExecutionPolicy Bypass -File "' + $Paths.Launcher + '"' + $shortcut.WorkingDirectory = $Paths.Root + $shortcut.Save() + [IO.File]::Move($temporary, $Paths.Shortcut, $true) + } + finally { if (Test-Path -LiteralPath $temporary) { Remove-Item -LiteralPath $temporary -Force } } +} + +function Invoke-PortablePackageOperation { + param($Operation) + $ErrorActionPreference = 'Stop' + $ProgressPreference = 'SilentlyContinue' + $staging = $null + try { + Assert-PortablePlatform + # Refresh under the controller's apply lock rather than trusting an earlier plan. + $plan = Get-PortablePackagePlan $Operation.package $Operation.dataRoot + if ($plan.action -eq 'Conflict') { + return [pscustomobject]@{ name = $plan.name; status = 'Conflict'; rebootRequired = $false; exitCode = 1; message = $plan.reason } + } + if ($plan.action -in @('None', 'Warning')) { + return [pscustomobject]@{ name = $plan.name; status = $plan.action; rebootRequired = $false; exitCode = 0; message = $plan.reason } + } + $package = $plan.package + $paths = Get-PortablePaths $package $Operation.dataRoot + Assert-PortableStopped $paths.Root + [void][IO.Directory]::CreateDirectory($paths.Root) + $staging = Join-Path $paths.Root ('.stage-' + [guid]::NewGuid().ToString('N')) + [void][IO.Directory]::CreateDirectory($staging) + $archive = Join-Path $staging 'download.zip' + Invoke-WebRequest -Uri $package.url -OutFile $archive -MaximumRedirection 5 -ErrorAction Stop + if ((Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash -ne $package.sha256) { throw 'Downloaded archive SHA-256 does not match the manifest. Check the release and checksum before retrying.' } + $expanded = Join-Path $staging 'content' + Expand-PortableArchive $archive $expanded + $executable = Join-Path $expanded $package.executable + if (-not (Test-Path -LiteralPath $executable -PathType Leaf)) { throw "Archive does not contain '$($package.executable)'." } + $files = [ordered]@{} + foreach ($file in Get-ChildItem -LiteralPath $expanded -File -Recurse) { + $relative = [IO.Path]::GetRelativePath($expanded, $file.FullName).Replace('\', '/') + $files[$relative] = (Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash + } + $directory = "versions/$($package.version)-$([guid]::NewGuid().ToString('N'))" + $destination = Join-Path $paths.Root $directory + Assert-PortableNoLinks $destination + [void][IO.Directory]::CreateDirectory((Split-Path -Parent $destination)) + [IO.Directory]::Move($expanded, $destination) + # Launcher content is constant across versions. Leave existing launchers intact. + if (-not (Test-Path -LiteralPath $paths.Launcher)) { + [IO.File]::WriteAllText((Join-Path $staging 'launch.ps1'), (Get-PortableLauncherContent)) + [IO.File]::Move((Join-Path $staging 'launch.ps1'), $paths.Launcher) + } + Set-PortableShortcut $paths + Assert-PortableStopped $paths.Root + $receipt = [ordered]@{ schemaVersion = 1; version = $package.version; sha256 = $package.sha256; directory = $directory; executable = $package.executable; files = $files } + $temporary = Join-Path $staging 'current.json' + $receipt | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $temporary -Encoding utf8NoBOM + [IO.File]::Move($temporary, $paths.Receipt, $true) + [pscustomobject]@{ name = $plan.name; status = 'Succeeded'; rebootRequired = $false; exitCode = 0; message = "Installed portable version $($package.version); previous versions retained" } + } + catch { + [pscustomobject]@{ name = $Operation.name; status = 'Failed'; rebootRequired = $false; exitCode = 1; message = $_.Exception.Message } + } + finally { + if ($staging -and (Test-Path -LiteralPath $staging)) { Remove-Item -LiteralPath $staging -Recurse -Force -ErrorAction SilentlyContinue } + } +} + +Export-ModuleMember -Function Get-PortablePackagePlan, Invoke-PortablePackageOperation diff --git a/src/elevated-worker.ps1 b/src/elevated-worker.ps1 index 05efacd..ab0dd06 100644 --- a/src/elevated-worker.ps1 +++ b/src/elevated-worker.ps1 @@ -26,6 +26,7 @@ try { if ($request.schemaVersion -ne 1) { throw 'Unsupported elevation request version.' } if ($request.requestType -eq 'packages') { foreach ($operation in @($request.operations)) { + if ($operation.package.PSObject.Properties['provider'] -and $operation.package.provider -ne 'winget') { throw 'Only WinGet packages may use the elevated worker.' } if ($operation.kind -ne 'package' -or $operation.action -notin @('Install', 'Upgrade', 'None', 'Warning')) { throw 'Elevation request contains an unsupported operation.' } if ($operation.package.id -notmatch '^[A-Za-z0-9._+-]+$' -or $operation.package.source -notmatch '^[A-Za-z0-9._+-]+$') { throw 'Elevation request contains an unsafe package identifier.' } if ($operation.package.PSObject.Properties['scope'] -and $operation.package.scope -ne 'machine') { throw 'Elevated operations must use machine scope.' } diff --git a/src/portable-launcher.ps1 b/src/portable-launcher.ps1 new file mode 100644 index 0000000..9362fff --- /dev/null +++ b/src/portable-launcher.ps1 @@ -0,0 +1,37 @@ +function Write-ConfigCentralMessage { + param([string]$Message, [ValidateSet('Info', 'Success', 'Warning', 'Error')][string]$Level = 'Info') + $color = switch ($Level) { + 'Success' { 'Green' } + 'Warning' { 'Yellow' } + 'Error' { 'Red' } + default { 'Cyan' } + } + $redirected = if ($Level -eq 'Error') { [Console]::IsErrorRedirected } else { [Console]::IsOutputRedirected } + $useColor = -not $redirected -and $null -eq [Environment]::GetEnvironmentVariable('NO_COLOR') + if ($Level -eq 'Error') { + $previous = $null + try { + if ($useColor) { $previous = [Console]::ForegroundColor; [Console]::ForegroundColor = $color } + [Console]::Error.WriteLine($Message) + } + finally { if ($null -ne $previous) { [Console]::ForegroundColor = $previous } } + } + elseif ($useColor) { Write-Host $Message -ForegroundColor $color } + else { Write-Host $Message } +} + +$ErrorActionPreference = 'Stop' +try { + $receipt = Get-Content -LiteralPath (Join-Path $PSScriptRoot 'current.json') -Raw | ConvertFrom-Json + $root = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot $receipt.directory)) + $executable = [IO.Path]::GetFullPath((Join-Path $root $receipt.executable)) + if (-not $root.StartsWith(($PSScriptRoot + [IO.Path]::DirectorySeparatorChar), [StringComparison]::OrdinalIgnoreCase) -or + -not $executable.StartsWith(($root + [IO.Path]::DirectorySeparatorChar), [StringComparison]::OrdinalIgnoreCase)) { throw 'Invalid portable receipt paths.' } + Push-Location (Split-Path -Parent $executable) + try { & $executable @args; $applicationExitCode = $LASTEXITCODE } finally { Pop-Location } + exit $applicationExitCode +} +catch { + Write-ConfigCentralMessage -Level Error -Message "Cannot launch portable application: $($_.Exception.Message) Run cc apply to inspect or repair the installation." + exit 1 +} diff --git a/tests/Core.Tests.ps1 b/tests/Core.Tests.ps1 index 7b126dd..8169f01 100644 --- a/tests/Core.Tests.ps1 +++ b/tests/Core.Tests.ps1 @@ -78,3 +78,41 @@ Describe 'Result status colors' { } } } + +Describe 'Portable workflow integration' { + It 'plans portable-only machines without WinGet and performs no writes' { + InModuleScope Core -Parameters @{ Working = $TestDrive } { + Mock Read-JsonState { @{ configs = @{} } } + Mock Resolve-MachineManifest { [pscustomobject]@{ packages = @( + [pscustomobject]@{ id = 'presenter'; source = 'gitea'; provider = 'portable'; version = '1.0'; update = 'pinned'; sha256 = ('a' * 64); executable = 'app.exe' } + ); configs = @() } } + Mock Get-WingetInventory { throw 'WinGet must not run' } + Mock Get-ConfigPlan { @() } + $paths = Get-ConfigCentralPaths -DataRoot "$Working/portable-plan" + $plan = Get-OperationPlan -Machine test -RepositoryRoot $Working -Paths $paths + $plan.packages[0].action | Should -Be 'Install' + Test-Path $paths.Root | Should -BeFalse + Should -Invoke Get-WingetInventory -Times 0 + } + } + It 'continues independent packages and skips configs after a portable failure' { + InModuleScope Core -Parameters @{ Working = $TestDrive } { + Mock Invoke-PackageOperation { + if ($Operation.name -eq 'presenter') { return [pscustomobject]@{ name = 'presenter'; status = 'Failed'; message = 'Checksum mismatch'; rebootRequired = $false } } + [pscustomobject]@{ name = 'other'; status = 'Succeeded'; message = 'Installed'; rebootRequired = $false } + } + Mock Invoke-ConfigOperation { throw 'Dependent config must not run' } + $paths = Get-ConfigCentralPaths -DataRoot "$Working/portable-failure" + $plan = [pscustomobject]@{ state = @{ configs = @{} }; packages = @( + [pscustomobject]@{ name = 'presenter'; package = [pscustomobject]@{ provider = 'portable'; scope = 'user' } }, + [pscustomobject]@{ name = 'other'; package = [pscustomobject]@{ provider = 'winget'; scope = 'user' } } + ); configs = @([pscustomobject]@{ name = 'dependent'; requiresPackage = 'presenter' }) } + $result = Invoke-ApplyPlan -Plan $plan -Machine test -RepositoryRoot $Working -Paths $paths -Revision abc + $result.exitCode | Should -Be 5 + $result.operations.status | Should -Be @('Failed', 'Succeeded', 'Skipped') + $json = $result | ConvertTo-Json -Depth 16 | ConvertFrom-Json + $json.operations[0].message | Should -Be 'Checksum mismatch' + (Read-JsonState $paths.State @{}).lastRun.revision | Should -Be 'abc' + } + } +} diff --git a/tests/Elevation.Tests.ps1 b/tests/Elevation.Tests.ps1 index 50dccab..788e529 100644 --- a/tests/Elevation.Tests.ps1 +++ b/tests/Elevation.Tests.ps1 @@ -60,3 +60,16 @@ Describe 'Elevation request file protection' -Skip:(-not $IsWindows) { } } } + +Describe 'Portable elevation boundary' { + It 'rejects portable requests before launching or using the administrator fast path' { + InModuleScope Elevation -Parameters @{ Working = $TestDrive } { + Mock Test-IsAdministrator { $true } + Mock Start-Process { throw 'Must not launch' } + $operation = [pscustomobject]@{ package = [pscustomobject]@{ provider = 'portable'; scope = 'machine' } } + { Invoke-ElevatedPackageBatch -Operations @($operation) -RepositoryRoot $Working -Paths ([pscustomobject]@{ Root = $Working }) } | Should -Throw '*Only WinGet*' + Should -Invoke Test-IsAdministrator -Times 0 + Should -Invoke Start-Process -Times 0 + } + } +} diff --git a/tests/Output.Tests.ps1 b/tests/Output.Tests.ps1 index 1319601..089e14e 100644 --- a/tests/Output.Tests.ps1 +++ b/tests/Output.Tests.ps1 @@ -1,5 +1,5 @@ BeforeAll { - $script:entrypoints = @('install.ps1', 'bootstrap.ps1', 'update-configs.ps1', 'cc.ps1', 'tools/TemporarySsh.ps1', 'tools/Export-MpcHcSettings.ps1') + $script:entrypoints = @('install.ps1', 'bootstrap.ps1', 'update-configs.ps1', 'cc.ps1', 'tools/TemporarySsh.ps1', 'tools/Export-MpcHcSettings.ps1', 'src/portable-launcher.ps1') $script:formatters = foreach ($entry in $entrypoints) { $tokens = $null; $errors = $null $ast = [System.Management.Automation.Language.Parser]::ParseFile("$PSScriptRoot/../$entry", [ref]$tokens, [ref]$errors) diff --git a/tests/PortablePackages.Tests.ps1 b/tests/PortablePackages.Tests.ps1 new file mode 100644 index 0000000..34849b2 --- /dev/null +++ b/tests/PortablePackages.Tests.ps1 @@ -0,0 +1,166 @@ +Import-Module "$PSScriptRoot/../src/PortablePackages.psm1" -Force +Describe 'Portable package lifecycle' { + InModuleScope PortablePackages { + BeforeEach { + $root = Join-Path $TestDrive ([guid]::NewGuid().ToString('N') + ' espace é') + $bundle = Join-Path $TestDrive ([guid]::NewGuid().ToString('N')) + [void][IO.Directory]::CreateDirectory("$bundle/bundle") + [IO.File]::WriteAllText("$bundle/bundle/app.exe", 'test executable') + [IO.File]::WriteAllText("$bundle/bundle/library.dll", 'test dependency') + $script:fixtureZip = "$bundle.zip" + [IO.Compression.ZipFile]::CreateFromDirectory($bundle, $script:fixtureZip) + $package = [pscustomobject]@{ id = 'presenter'; provider = 'portable'; source = 'gitea'; version = '1.2.3'; update = 'pinned'; url = 'https://example.org/app.zip'; sha256 = (Get-FileHash $script:fixtureZip).Hash; executable = 'bundle/app.exe' } + Mock Get-PortableProgramsPath { Join-Path $root 'test-programs' } + Mock Assert-PortablePlatform {} + Mock Assert-PortableStopped {} + Mock Set-PortableShortcut { + [void][IO.Directory]::CreateDirectory((Split-Path -Parent $Paths.Shortcut)) + [IO.File]::WriteAllText($Paths.Shortcut, 'mock shortcut') + } + Mock Invoke-WebRequest { Copy-Item -LiteralPath $script:fixtureZip -Destination $OutFile } + } + It 'plans without writes or downloads, installs, and verifies an unchanged rerun' { + $plan = Get-PortablePackagePlan $package $root + $plan.action | Should -Be 'Install' + Test-Path $root | Should -BeFalse + Should -Invoke Invoke-WebRequest -Times 0 + (Invoke-PortablePackageOperation $plan).status | Should -Be 'Succeeded' + $again = Get-PortablePackagePlan $package $root + $again.action | Should -Be 'None' + (Invoke-PortablePackageOperation $again).status | Should -Be 'None' + Should -Invoke Invoke-WebRequest -Times 1 + } + It 'retains the previous version and unmanaged settings on update' { + $paths = Get-PortablePaths $package $root + (Invoke-PortablePackageOperation (Get-PortablePackagePlan $package $root)).status | Should -Be 'Succeeded' + $old = Get-Content $paths.Receipt -Raw | ConvertFrom-Json + $settings = Join-Path $paths.Root "$($old.directory)/settings.json" + 'user settings' | Set-Content $settings + $package.version = '2.0' + (Invoke-PortablePackageOperation (Get-PortablePackagePlan $package $root)).status | Should -Be 'Succeeded' + Test-Path (Join-Path $paths.Root "$($old.directory)/bundle/app.exe") | Should -BeTrue + Get-Content $settings | Should -Be 'user settings' + (Get-Content $paths.Receipt -Raw | ConvertFrom-Json).version | Should -Be '2.0' + } + It 'repairs missing files but refuses modified files' { + $paths = Get-PortablePaths $package $root + [void](Invoke-PortablePackageOperation (Get-PortablePackagePlan $package $root)) + $receipt = Get-Content $paths.Receipt -Raw | ConvertFrom-Json + Remove-Item (Join-Path $paths.Root "$($receipt.directory)/bundle/library.dll") + (Get-PortablePackagePlan $package $root).action | Should -Be 'Install' + (Invoke-PortablePackageOperation (Get-PortablePackagePlan $package $root)).status | Should -Be 'Succeeded' + $receipt = Get-Content $paths.Receipt -Raw | ConvertFrom-Json + 'local edit' | Set-Content (Join-Path $paths.Root "$($receipt.directory)/bundle/app.exe") + (Get-PortablePackagePlan $package $root).action | Should -Be 'Conflict' + (Invoke-PortablePackageOperation (Get-PortablePackagePlan $package $root)).status | Should -Be 'Conflict' + } + It 'keeps the active receipt on checksum or shortcut failure and recovers on retry' { + $paths = Get-PortablePaths $package $root + [void](Invoke-PortablePackageOperation (Get-PortablePackagePlan $package $root)) + $before = Get-Content $paths.Receipt -Raw + $package.version = '2.0' + $hash = $package.sha256 + $package.sha256 = '0' * 64 + $result = Invoke-PortablePackageOperation (Get-PortablePackagePlan $package $root) + $result.status | Should -Be 'Failed' + $result.message | Should -Match 'SHA-256' + Get-Content $paths.Receipt -Raw | Should -Be $before + $package.sha256 = $hash + Mock Set-PortableShortcut { throw 'Shortcut failure' } + (Invoke-PortablePackageOperation (Get-PortablePackagePlan $package $root)).status | Should -Be 'Failed' + Get-Content $paths.Receipt -Raw | Should -Be $before + Mock Set-PortableShortcut { + [void][IO.Directory]::CreateDirectory((Split-Path -Parent $Paths.Shortcut)) + [IO.File]::WriteAllText($Paths.Shortcut, 'mock shortcut') + } + (Invoke-PortablePackageOperation (Get-PortablePackagePlan $package $root)).status | Should -Be 'Succeeded' + } + It 'recovers a first install interrupted after launcher creation' { + Mock Set-PortableShortcut { throw 'Shortcut failure' } + (Invoke-PortablePackageOperation (Get-PortablePackagePlan $package $root)).status | Should -Be 'Failed' + Mock Set-PortableShortcut { + [void][IO.Directory]::CreateDirectory((Split-Path -Parent $Paths.Shortcut)) + [IO.File]::WriteAllText($Paths.Shortcut, 'mock shortcut') + } + (Invoke-PortablePackageOperation (Get-PortablePackagePlan $package $root)).status | Should -Be 'Succeeded' + } + It 'blocks a running application before downloading' { + Mock Assert-PortableStopped { throw 'Close presenter before updating' } + $result = Invoke-PortablePackageOperation (Get-PortablePackagePlan $package $root) + $result.status | Should -Be 'Failed' + $result.message | Should -Match 'Close presenter' + Should -Invoke Invoke-WebRequest -Times 0 + } + It 'honors install-only and newer-version policies and rejects a republished hash' { + [void](Invoke-PortablePackageOperation (Get-PortablePackagePlan $package $root)) + $package.update = 'install-only'; $package.version = '2.0' + (Get-PortablePackagePlan $package $root).action | Should -Be 'None' + $package.update = 'pinned'; $package.version = '1.0' + (Get-PortablePackagePlan $package $root).action | Should -Be 'Warning' + $package.version = '1.2.3'; $package.sha256 = '0' * 64 + (Get-PortablePackagePlan $package $root).action | Should -Be 'Conflict' + } + It 'rejects a missing executable and returns a structured failure without activating it' { + $package.executable = 'absent.exe' + $result = Invoke-PortablePackageOperation (Get-PortablePackagePlan $package $root) + $result.status | Should -Be 'Failed' + $result.message | Should -Match 'does not contain' + Test-Path (Get-PortablePaths $package $root).Receipt | Should -BeFalse + { $result | ConvertTo-Json | ConvertFrom-Json } | Should -Not -Throw + } + It 'rejects unsafe archive entries before extraction' -ForEach @( + @{ Name = '../escape.exe'; Attributes = 0 } + @{ Name = 'C:/escape.exe'; Attributes = 0 } + @{ Name = 'safe/../../escape.exe'; Attributes = 0 } + @{ Name = 'app.exe:stream'; Attributes = 0 } + @{ Name = 'con/file.exe'; Attributes = 0 } + @{ Name = 'link'; Attributes = -1577123840 } + ) { + $bad = "$bundle-bad.zip" + $zip = [IO.Compression.ZipFile]::Open($bad, 'Create') + $entry = $zip.CreateEntry($Name) + $entry.ExternalAttributes = $Attributes + $zip.Dispose() + { Expand-PortableArchive $bad "$bundle-expanded" } | Should -Throw + Test-Path "$bundle-expanded" | Should -BeFalse + } + It 'rejects archive paths that collide on Windows' { + $bad = "$bundle-bad.zip" + $zip = [IO.Compression.ZipFile]::Open($bad, 'Create') + [void]$zip.CreateEntry('App.exe') + [void]$zip.CreateEntry('app.exe') + $zip.Dispose() + { Expand-PortableArchive $bad "$bundle-expanded" } | Should -Throw '*colliding*' + } + It 'rejects linked installation directories' -Skip:$IsWindows { + [void][IO.Directory]::CreateDirectory("$root/apps") + [void](New-Item -ItemType SymbolicLink -Path "$root/apps/gitea" -Target $bundle) + { Get-PortablePackagePlan $package $root } | Should -Throw '*link*' + } + } +} + +Describe 'Portable launcher presentation' { + It 'reports missing receipts concisely with a failing process exit code' { + $launcher = Join-Path $TestDrive 'launch.ps1' + Copy-Item "$PSScriptRoot/../src/portable-launcher.ps1" $launcher + $output = & (Join-Path $PSHOME $(if ($IsWindows) { 'pwsh.exe' } else { 'pwsh' })) -NoProfile -File $launcher 2>&1 + $LASTEXITCODE | Should -Be 1 + ($output | Out-String) | Should -Match 'Cannot launch portable application:.*Run cc apply' + ($output | Out-String) | Should -Not -Match 'CategoryInfo|FullyQualifiedErrorId|\x1b' + } +} + +Describe 'Portable launcher process status' { + It 'preserves the application exit code and literal arguments' -Skip:$IsWindows { + $root = Join-Path $TestDrive 'launcher status' + [void][IO.Directory]::CreateDirectory("$root/versions/1.0") + Copy-Item "$PSScriptRoot/../src/portable-launcher.ps1" "$root/launch.ps1" + [IO.File]::WriteAllText("$root/versions/1.0/app.exe", "#!/bin/sh`nprintf '%s' `"`$1`"`nexit 7`n") + & chmod +x "$root/versions/1.0/app.exe" + @{ directory = 'versions/1.0'; executable = 'app.exe' } | ConvertTo-Json | Set-Content "$root/current.json" + $output = & (Join-Path $PSHOME 'pwsh') -NoProfile -File "$root/launch.ps1" 'document with spaces.pdf' + $LASTEXITCODE | Should -Be 7 + $output | Should -Be 'document with spaces.pdf' + } +}