464 lines
28 KiB
PowerShell
464 lines
28 KiB
PowerShell
Set-StrictMode -Version Latest
|
|
|
|
$script:LegacyPortableLauncherHashes = @(
|
|
'644e2a37e75a4297bceba8da2605f5edffd12ad8adfde1bb244b3baa7fdd1f91'
|
|
)
|
|
|
|
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'
|
|
AssociationIcon = Join-Path $root 'file-association.ico'
|
|
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 Test-PortableLegacyLauncher {
|
|
param([Parameter(Mandatory)][string]$Path)
|
|
(Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant() -in $script:LegacyPortableLauncherHashes
|
|
}
|
|
|
|
function Get-PortableAssociationIconSource {
|
|
param($Package)
|
|
if (-not $Package.PSObject.Properties['fileAssociationIcon']) { return $null }
|
|
$repositoryRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..'))
|
|
$source = [IO.Path]::GetFullPath((Join-Path $repositoryRoot ([string]$Package.fileAssociationIcon)))
|
|
if (-not $source.StartsWith(($repositoryRoot.TrimEnd([IO.Path]::DirectorySeparatorChar) + [IO.Path]::DirectorySeparatorChar), [StringComparison]::OrdinalIgnoreCase) -or
|
|
-not (Test-Path -LiteralPath $source -PathType Leaf)) { throw "Portable file association icon is missing or outside the repository: '$($Package.fileAssociationIcon)'." }
|
|
return $source
|
|
}
|
|
|
|
function Get-PortableAssociationSpec {
|
|
param($Package, [Parameter(Mandatory)][string]$Executable, [string]$Icon)
|
|
if (-not $Package.PSObject.Properties['fileAssociations']) { return @() }
|
|
if ([string]::IsNullOrWhiteSpace($Icon)) { $Icon = $Executable }
|
|
$registeredName = "ConfigCentral.$($Package.source).$($Package.id)"
|
|
$capabilitiesPath = "Software\ConfigCentral\Applications\$($Package.source)\$($Package.id)\Capabilities"
|
|
foreach ($extension in @($Package.fileAssociations)) {
|
|
$suffix = $extension.TrimStart('.').ToLowerInvariant()
|
|
[pscustomobject]@{
|
|
extension = $extension.ToLowerInvariant()
|
|
registeredName = $registeredName
|
|
capabilitiesPath = $capabilitiesPath
|
|
progId = "$registeredName.$suffix"
|
|
displayName = [string]$Package.displayName
|
|
description = "$($Package.displayName) $($suffix.ToUpperInvariant()) document"
|
|
executable = [IO.Path]::GetFullPath($Executable)
|
|
icon = [IO.Path]::GetFullPath($Icon)
|
|
}
|
|
}
|
|
}
|
|
|
|
function Get-PortableRegistryValue {
|
|
param([Parameter(Mandatory)][string]$Path, [Parameter(Mandatory)][AllowEmptyString()][string]$Name)
|
|
$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($Path, $false)
|
|
if ($null -eq $key) { return $null }
|
|
try { return $key.GetValue($Name, $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) }
|
|
finally { $key.Dispose() }
|
|
}
|
|
|
|
function Set-PortableRegistryValue {
|
|
param([Parameter(Mandatory)][string]$Path, [Parameter(Mandatory)][AllowEmptyString()][string]$Name, [Parameter(Mandatory)][AllowEmptyString()][string]$Value)
|
|
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($Path, $true)
|
|
if ($null -eq $key) { throw "Cannot create per-user registration key 'HKCU:\$Path'." }
|
|
try { $key.SetValue($Name, $Value, [Microsoft.Win32.RegistryValueKind]::String) }
|
|
finally { $key.Dispose() }
|
|
}
|
|
|
|
function Test-PortableFileAssociations {
|
|
param($Package, [Parameter(Mandatory)][string]$Executable, [string]$Icon)
|
|
$specs = @(Get-PortableAssociationSpec -Package $Package -Executable $Executable -Icon $Icon)
|
|
if (-not $specs.Count) { return $true }
|
|
if (-not $IsWindows) { return $false }
|
|
foreach ($spec in $specs) {
|
|
$command = '"' + $spec.executable + '" "%1"'
|
|
if ((Get-PortableRegistryValue 'Software\RegisteredApplications' $spec.registeredName) -ne $spec.capabilitiesPath -or
|
|
(Get-PortableRegistryValue $spec.capabilitiesPath 'ApplicationName') -ne $spec.displayName -or
|
|
(Get-PortableRegistryValue "$($spec.capabilitiesPath)\FileAssociations" $spec.extension) -ne $spec.progId -or
|
|
(Get-PortableRegistryValue "Software\Classes\$($spec.progId)" '') -ne $spec.description -or
|
|
(Get-PortableRegistryValue "Software\Classes\$($spec.progId)\DefaultIcon" '') -ne "$($spec.icon),0" -or
|
|
(Get-PortableRegistryValue "Software\Classes\$($spec.progId)\shell\open\command" '') -ne $command -or
|
|
$null -eq (Get-PortableRegistryValue "Software\Classes\$($spec.extension)\OpenWithProgids" $spec.progId)) { return $false }
|
|
}
|
|
return $true
|
|
}
|
|
|
|
function Set-PortableFileAssociations {
|
|
param($Package, [Parameter(Mandatory)][string]$Executable, [string]$Icon)
|
|
foreach ($spec in @(Get-PortableAssociationSpec -Package $Package -Executable $Executable -Icon $Icon)) {
|
|
Set-PortableRegistryValue 'Software\RegisteredApplications' $spec.registeredName $spec.capabilitiesPath
|
|
Set-PortableRegistryValue $spec.capabilitiesPath 'ApplicationName' $spec.displayName
|
|
Set-PortableRegistryValue $spec.capabilitiesPath 'ApplicationDescription' "Open supported documents with $($spec.displayName)."
|
|
Set-PortableRegistryValue "$($spec.capabilitiesPath)\FileAssociations" $spec.extension $spec.progId
|
|
Set-PortableRegistryValue "Software\Classes\$($spec.progId)" '' $spec.description
|
|
Set-PortableRegistryValue "Software\Classes\$($spec.progId)\DefaultIcon" '' "$($spec.icon),0"
|
|
Set-PortableRegistryValue "Software\Classes\$($spec.progId)\shell\open\command" '' ('"' + $spec.executable + '" "%1"')
|
|
Set-PortableRegistryValue "Software\Classes\$($spec.extension)\OpenWithProgids" $spec.progId ''
|
|
}
|
|
}
|
|
|
|
function Get-PortablePreviousVersionPaths {
|
|
param($Paths, [Parameter(Mandatory)][string]$CurrentDirectory)
|
|
$versionsRoot = Join-Path $Paths.Root 'versions'
|
|
if (-not (Test-Path -LiteralPath $versionsRoot -PathType Container)) { return @() }
|
|
Assert-PortableNoLinks $versionsRoot
|
|
$current = [IO.Path]::GetFullPath((Join-Path $Paths.Root $CurrentDirectory))
|
|
foreach ($directory in Get-ChildItem -LiteralPath $versionsRoot -Directory) {
|
|
if ($directory.Name -notmatch '^[0-9.]+-[a-f0-9]{32}$') { continue }
|
|
Assert-PortableNoLinks $directory.FullName
|
|
if (-not [string]::Equals([IO.Path]::GetFullPath($directory.FullName), $current, [StringComparison]::OrdinalIgnoreCase)) {
|
|
$directory.FullName
|
|
}
|
|
}
|
|
}
|
|
|
|
function Remove-PortablePreviousVersions {
|
|
param($Paths, [Parameter(Mandatory)][string]$CurrentDirectory)
|
|
$previous = @(Get-PortablePreviousVersionPaths -Paths $Paths -CurrentDirectory $CurrentDirectory)
|
|
foreach ($path in $previous) { Remove-Item -LiteralPath $path -Recurse -Force -ErrorAction Stop }
|
|
return $previous.Count
|
|
}
|
|
|
|
function Invoke-PortableReleaseRequest {
|
|
param([Parameter(Mandatory)][string]$Uri, [Parameter(Mandatory)][ValidateSet('Json', 'Text')][string]$Kind)
|
|
try { $response = Invoke-WebRequest -Uri $Uri -MaximumRedirection 5 -ErrorAction Stop }
|
|
catch { throw "Portable release request failed for '$Uri': $($_.Exception.Message)" }
|
|
if ($null -eq $response -or $null -eq $response.PSObject.Properties['Content']) { throw "Portable release request returned no content for '$Uri'." }
|
|
$content = [string]$response.Content
|
|
$limit = if ($Kind -eq 'Json') { 4MB } else { 1MB }
|
|
if ([Text.Encoding]::UTF8.GetByteCount($content) -gt $limit) { throw "Portable release $($Kind.ToLowerInvariant()) response is too large." }
|
|
if ($Kind -eq 'Text') { return $content }
|
|
try { return $content | ConvertFrom-Json -Depth 32 }
|
|
catch { throw "Portable release API returned invalid JSON: $($_.Exception.Message)" }
|
|
}
|
|
|
|
function Assert-PortableReleaseUrl {
|
|
param([Parameter(Mandatory)][string]$Url, [Parameter(Mandatory)][uri]$ApiUri, [Parameter(Mandatory)][string]$Description)
|
|
$uri = $null
|
|
if (-not [uri]::TryCreate($Url, [UriKind]::Absolute, [ref]$uri) -or
|
|
$uri.Scheme -ne 'https' -or $uri.UserInfo -or $uri.Fragment -or
|
|
-not [string]::Equals($uri.Authority, $ApiUri.Authority, [StringComparison]::OrdinalIgnoreCase)) {
|
|
throw "$Description URL must use HTTPS on the release API host."
|
|
}
|
|
return $uri
|
|
}
|
|
|
|
function Resolve-PortablePackageRelease {
|
|
param([Parameter(Mandatory)]$Package)
|
|
if (-not $Package.PSObject.Properties['releaseApi']) { return $Package }
|
|
|
|
$apiUri = [uri]$Package.releaseApi
|
|
$response = Invoke-PortableReleaseRequest -Uri $Package.releaseApi -Kind Json
|
|
$candidates = [System.Collections.Generic.List[object]]::new()
|
|
foreach ($release in @($response)) {
|
|
if ($release.draft) { continue }
|
|
if ($Package.releaseChannel -eq 'stable' -and $release.prerelease) { continue }
|
|
$match = [regex]::Match([string]$release.tag_name, '^v?(\d+\.\d+(?:\.\d+){0,2})$')
|
|
if (-not $match.Success) { continue }
|
|
$version = $null
|
|
if (-not [version]::TryParse($match.Groups[1].Value, [ref]$version)) { continue }
|
|
if ($version -lt [version]$Package.version) { continue }
|
|
$candidates.Add([pscustomobject]@{ release = $release; version = $version; versionText = $match.Groups[1].Value })
|
|
}
|
|
if ($candidates.Count -eq 0) { throw "No eligible $($Package.releaseChannel) release at or above $($Package.version) was found for '$($Package.id)'." }
|
|
$ordered = @($candidates | Sort-Object version -Descending)
|
|
if ($ordered.Count -gt 1 -and $ordered[0].version -eq $ordered[1].version) { throw "Release API returned duplicate version '$($ordered[0].versionText)' for '$($Package.id)'." }
|
|
$selected = $ordered[0]
|
|
$assetName = $Package.assetTemplate.Replace('{version}', $selected.versionText)
|
|
$checksumName = if ($Package.PSObject.Properties['checksumAsset']) { [string]$Package.checksumAsset } else { 'SHA256SUMS' }
|
|
$assets = @($selected.release.assets)
|
|
$archiveAssets = @($assets | Where-Object { [string]::Equals([string]$_.name, $assetName, [StringComparison]::Ordinal) })
|
|
$checksumAssets = @($assets | Where-Object { [string]::Equals([string]$_.name, $checksumName, [StringComparison]::Ordinal) })
|
|
if ($archiveAssets.Count -ne 1) { throw "Release '$($selected.release.tag_name)' must contain exactly one '$assetName' asset." }
|
|
if ($checksumAssets.Count -ne 1) { throw "Release '$($selected.release.tag_name)' must contain exactly one '$checksumName' asset." }
|
|
|
|
$archiveUri = Assert-PortableReleaseUrl -Url ([string]$archiveAssets[0].browser_download_url) -ApiUri $apiUri -Description 'Portable archive'
|
|
$checksumUri = Assert-PortableReleaseUrl -Url ([string]$checksumAssets[0].browser_download_url) -ApiUri $apiUri -Description 'Portable checksum'
|
|
if ($archiveUri.AbsolutePath -notlike '*.zip') { throw 'Portable release archive URL must identify a ZIP file.' }
|
|
$checksumText = Invoke-PortableReleaseRequest -Uri $checksumUri.AbsoluteUri -Kind Text
|
|
$matches = [System.Collections.Generic.List[string]]::new()
|
|
foreach ($line in $checksumText -split '\r?\n') {
|
|
$checksumMatch = [regex]::Match($line, '^([a-fA-F0-9]{64})\s+\*?(.+)$')
|
|
if ($checksumMatch.Success -and [string]::Equals($checksumMatch.Groups[2].Value, $assetName, [StringComparison]::Ordinal)) {
|
|
$matches.Add($checksumMatch.Groups[1].Value.ToLowerInvariant())
|
|
}
|
|
}
|
|
if ($matches.Count -ne 1) { throw "Checksum asset must contain exactly one SHA-256 entry for '$assetName'." }
|
|
if ($selected.versionText -eq $Package.version -and $matches[0] -ne $Package.sha256.ToLowerInvariant()) {
|
|
throw "Published checksum for pinned version $($Package.version) differs from the manifest; review the release before updating."
|
|
}
|
|
|
|
$resolved = [ordered]@{}
|
|
foreach ($property in $Package.PSObject.Properties) { $resolved[$property.Name] = $property.Value }
|
|
$resolved.version = $selected.versionText
|
|
$resolved.url = $archiveUri.AbsoluteUri
|
|
$resolved.sha256 = $matches[0]
|
|
$resolved.executable = $Package.executableTemplate.Replace('{version}', $selected.versionText)
|
|
return [pscustomobject]$resolved
|
|
}
|
|
|
|
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)) {
|
|
if (Test-PortableLegacyLauncher -Path $paths.Launcher) { $missing = $true }
|
|
else { throw "Locally modified launcher '$($paths.Launcher)'; inspect it before retrying." }
|
|
}
|
|
}
|
|
else { $missing = $true }
|
|
$activeExecutable = Join-Path $paths.Root "$($receipt.directory)/$($receipt.executable)"
|
|
if ($paths.Shortcut -and -not (Test-PortableShortcut -Path $paths.Shortcut -Executable $activeExecutable)) { $missing = $true }
|
|
$associationIcon = $activeExecutable
|
|
if ($Package.PSObject.Properties['fileAssociationIcon']) {
|
|
$associationIconSource = Get-PortableAssociationIconSource -Package $Package
|
|
if (-not (Test-Path -LiteralPath $paths.AssociationIcon -PathType Leaf) -or
|
|
(Get-FileHash -LiteralPath $paths.AssociationIcon -Algorithm SHA256).Hash -ne (Get-FileHash -LiteralPath $associationIconSource -Algorithm SHA256).Hash) { $missing = $true }
|
|
$associationIcon = $paths.AssociationIcon
|
|
}
|
|
if (-not (Test-PortableFileAssociations -Package $Package -Executable $activeExecutable -Icon $associationIcon)) { $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, launcher, shortcut, or file associations'
|
|
}
|
|
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)" }
|
|
$previousVersions = @(Get-PortablePreviousVersionPaths -Paths $paths -CurrentDirectory $receipt.directory)
|
|
if ($action -eq 'None' -and $previousVersions.Count) {
|
|
$action = 'Cleanup'; $reason = 'Remove previous portable versions'
|
|
}
|
|
}
|
|
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 New-PortableShortcutShell {
|
|
New-Object -ComObject WScript.Shell
|
|
}
|
|
|
|
function Get-PortableShortcutDetails {
|
|
param([Parameter(Mandatory)][string]$Path)
|
|
$shell = New-PortableShortcutShell
|
|
$shortcut = $shell.CreateShortcut($Path)
|
|
[pscustomobject]@{
|
|
TargetPath = [string]$shortcut.TargetPath
|
|
Arguments = [string]$shortcut.Arguments
|
|
WorkingDirectory = [string]$shortcut.WorkingDirectory
|
|
IconLocation = [string]$shortcut.IconLocation
|
|
}
|
|
}
|
|
|
|
function Test-PortableShortcut {
|
|
param([Parameter(Mandatory)][string]$Path, [Parameter(Mandatory)][string]$Executable)
|
|
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return $false }
|
|
try {
|
|
Assert-PortableNoLinks $Path
|
|
$details = Get-PortableShortcutDetails -Path $Path
|
|
$target = [IO.Path]::GetFullPath($details.TargetPath)
|
|
$expected = [IO.Path]::GetFullPath($Executable)
|
|
return [string]::Equals($target, $expected, [StringComparison]::OrdinalIgnoreCase) -and
|
|
[string]::IsNullOrWhiteSpace($details.Arguments)
|
|
}
|
|
catch { return $false }
|
|
}
|
|
|
|
function Set-PortableShortcut {
|
|
param($Paths, [Parameter(Mandatory)][string]$Executable)
|
|
if (-not $Paths.Shortcut) { throw 'The desktop user Start menu directory is unavailable.' }
|
|
if (-not (Test-Path -LiteralPath $Executable -PathType Leaf)) { throw "Portable shortcut target is missing: '$Executable'." }
|
|
Assert-PortableNoLinks $Paths.Shortcut
|
|
[void][IO.Directory]::CreateDirectory((Split-Path -Parent $Paths.Shortcut))
|
|
$temporary = "$($Paths.Shortcut).$([guid]::NewGuid().ToString('N')).lnk"
|
|
try {
|
|
$shell = New-PortableShortcutShell
|
|
$shortcut = $shell.CreateShortcut($temporary)
|
|
$shortcut.TargetPath = $Executable
|
|
$shortcut.Arguments = ''
|
|
$shortcut.WorkingDirectory = Split-Path -Parent $Executable
|
|
$shortcut.IconLocation = "$Executable,0"
|
|
$shortcut.Description = 'Managed by Config Central'
|
|
$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 -eq 'Cleanup') {
|
|
$paths = Get-PortablePaths $plan.package $Operation.dataRoot
|
|
Assert-PortableStopped $paths.Root
|
|
$receipt = Get-Content -LiteralPath $paths.Receipt -Raw | ConvertFrom-Json -AsHashtable
|
|
try {
|
|
$removed = Remove-PortablePreviousVersions -Paths $paths -CurrentDirectory $receipt.directory
|
|
return [pscustomobject]@{ name = $plan.name; status = 'Succeeded'; rebootRequired = $false; exitCode = 0; message = "Removed $removed previous portable version(s)" }
|
|
}
|
|
catch {
|
|
return [pscustomobject]@{ name = $plan.name; status = 'Warning'; rebootRequired = $false; exitCode = 0; message = "Could not remove previous portable versions: $($_.Exception.Message). Rerun cc update-software to retry." }
|
|
}
|
|
}
|
|
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)
|
|
# Planning rejects unknown launcher edits; current and known legacy copies can be replaced safely.
|
|
[IO.File]::WriteAllText((Join-Path $staging 'launch.ps1'), (Get-PortableLauncherContent))
|
|
[IO.File]::Move((Join-Path $staging 'launch.ps1'), $paths.Launcher, $true)
|
|
$installedExecutable = Join-Path $destination $package.executable
|
|
Set-PortableShortcut -Paths $paths -Executable $installedExecutable
|
|
$associationIcon = $installedExecutable
|
|
if ($package.PSObject.Properties['fileAssociationIcon']) {
|
|
$associationIconSource = Get-PortableAssociationIconSource -Package $package
|
|
Copy-Item -LiteralPath $associationIconSource -Destination (Join-Path $staging 'file-association.ico')
|
|
[IO.File]::Move((Join-Path $staging 'file-association.ico'), $paths.AssociationIcon, $true)
|
|
$associationIcon = $paths.AssociationIcon
|
|
}
|
|
Set-PortableFileAssociations -Package $package -Executable $installedExecutable -Icon $associationIcon
|
|
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)
|
|
try { $removed = Remove-PortablePreviousVersions -Paths $paths -CurrentDirectory $directory }
|
|
catch {
|
|
return [pscustomobject]@{ name = $plan.name; status = 'Warning'; rebootRequired = $false; exitCode = 0; message = "Installed portable version $($package.version), but could not remove previous versions: $($_.Exception.Message). Rerun cc update-software to retry." }
|
|
}
|
|
$associationMessage = if ($package.PSObject.Properties['fileAssociations']) { "; registered for $(@($package.fileAssociations) -join ', ') (choose it once in Windows Default Apps)" } else { '' }
|
|
$cleanupMessage = if ($removed) { "; removed $removed previous version(s)" } else { '' }
|
|
[pscustomobject]@{ name = $plan.name; status = 'Succeeded'; rebootRequired = $false; exitCode = 0; message = "Installed portable version $($package.version)$cleanupMessage$associationMessage" }
|
|
}
|
|
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, Resolve-PortablePackageRelease, Invoke-PortablePackageOperation
|