param( [ValidateSet('clean', 'prepare', 'app', 'win', 'package')] [string]$Stage = 'package' ) $ErrorActionPreference = 'Stop' $root = Split-Path -Parent $MyInvocation.MyCommand.Path $tempRootName = [string]([char]0x4E34) + [char]0x65F6 $tempPackagingDir = Join-Path (Join-Path $root $tempRootName) 'packaging' $versioningDir = Join-Path $root 'versioning' $releaseStoreDir = Join-Path $versioningDir 'releases' $releaseFeedPath = Join-Path $versioningDir 'update-feed.json' $timestamp = Get-Date -Format 'yyyyMMdd-HHmmss' $logPath = Join-Path $tempPackagingDir ("build-$timestamp.log") function Ensure-Dir([string]$PathValue) { if (-not (Test-Path $PathValue)) { New-Item -ItemType Directory -Path $PathValue -Force | Out-Null } } function Write-Log([string]$Message) { Ensure-Dir $tempPackagingDir $line = "[{0}] {1}" -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $Message $line | Tee-Object -FilePath $logPath -Append } function Invoke-Step([string]$Name, [scriptblock]$Action) { Write-Log "START $Name" & $Action Write-Log "DONE $Name" } function Invoke-Npm([string[]]$Args) { & npm.cmd @Args if ($LASTEXITCODE -ne 0) { throw "npm $($Args -join ' ') failed with exit code $LASTEXITCODE" } } function Invoke-Builder([string[]]$Args) { $builderPath = Join-Path $root 'node_modules\.bin\electron-builder.cmd' if (-not (Test-Path $builderPath)) { throw 'electron-builder.cmd not found, run npm install first' } & $builderPath @Args if ($LASTEXITCODE -ne 0) { throw "electron-builder $($Args -join ' ') failed with exit code $LASTEXITCODE" } } function Get-PackageVersion { $manifest = Get-Content (Join-Path $root 'package.json') -Raw | ConvertFrom-Json $version = [string]$manifest.version if ([string]::IsNullOrWhiteSpace($version)) { throw 'package.json version is empty' } return $version } function Get-InstallerFileName([string]$Version) { return "printServer-$Version-setup.exe" } function Assert-VersionArtifactNotExists { if ($env:PRINTSERVER_SKIP_VERSION_CHECK -eq '1') { Write-Log 'VERSION CHECK skipped by PRINTSERVER_SKIP_VERSION_CHECK=1' return } $version = Get-PackageVersion $installerFile = Get-InstallerFileName -Version $version $distInstallerPath = Join-Path (Join-Path $root 'dist') $installerFile $archivedInstallerPath = Join-Path (Join-Path $releaseStoreDir $version) $installerFile if (Test-Path $distInstallerPath) { throw "version $version already has installer in dist: $distInstallerPath ; bump package.json version before packaging" } if (Test-Path $archivedInstallerPath) { throw "version $version already archived: $archivedInstallerPath ; bump package.json version before packaging" } if (Test-Path $releaseFeedPath) { try { $feed = Get-Content $releaseFeedPath -Raw | ConvertFrom-Json if ($feed -and $feed.releases) { foreach ($release in $feed.releases) { if ([string]$release.version -eq $version) { throw "version $version already exists in release feed: $releaseFeedPath ; bump package.json version before packaging" } } } } catch { throw "release feed validation failed: $($_.Exception.Message)" } } Write-Log "VERSION CHECK passed for $version" } function Get-SignOptions { $enabled = ($env:PRINTSERVER_SIGN_ENABLE -eq '1') $timestampEnv = $env:SIGN_TIMESTAMP_URL $timestampUrl = 'http://timestamp.digicert.com' if (-not [string]::IsNullOrWhiteSpace($timestampEnv)) { if ($timestampEnv -match '^(none|off|disable)$') { $timestampUrl = '' } else { $timestampUrl = $timestampEnv } } return [PSCustomObject]@{ Enabled = $enabled SignToolPath = if ([string]::IsNullOrWhiteSpace($env:SIGNTOOL_PATH)) { 'signtool.exe' } else { $env:SIGNTOOL_PATH } CertFile = $env:SIGN_CERT_FILE CertPassword = $env:SIGN_CERT_PASSWORD CertThumbprint = $env:SIGN_CERT_THUMBPRINT TimestampUrl = $timestampUrl } } function Write-ArtifactHash([string]$ArtifactPath) { if (-not (Test-Path $ArtifactPath)) { return } $hash = (Get-FileHash -Path $ArtifactPath -Algorithm SHA256).Hash Write-Log ("HASH " + $ArtifactPath + " SHA256=" + $hash) } function Invoke-SignFile([string]$TargetPath, [string]$Label) { if (-not (Test-Path $TargetPath)) { Write-Log ("SIGN SKIP " + $Label + " missing: " + $TargetPath) return } $signOptions = Get-SignOptions if (-not $signOptions.Enabled) { Write-Log ("SIGN SKIP " + $Label + " disabled (set PRINTSERVER_SIGN_ENABLE=1 to enable)") Write-ArtifactHash $TargetPath return } $signtoolArgs = @('sign', '/fd', 'SHA256') if (-not [string]::IsNullOrWhiteSpace($signOptions.TimestampUrl)) { $signtoolArgs += @('/td', 'SHA256', '/tr', $signOptions.TimestampUrl) } if (-not [string]::IsNullOrWhiteSpace($signOptions.CertFile)) { $signtoolArgs += @('/f', $signOptions.CertFile) if (-not [string]::IsNullOrWhiteSpace($signOptions.CertPassword)) { $signtoolArgs += @('/p', $signOptions.CertPassword) } } elseif (-not [string]::IsNullOrWhiteSpace($signOptions.CertThumbprint)) { $signtoolArgs += @('/sha1', $signOptions.CertThumbprint) } else { throw 'signing enabled but no certificate provided (SIGN_CERT_FILE or SIGN_CERT_THUMBPRINT)' } $signtoolArgs += @($TargetPath) $signtoolReady = $false if ($signOptions.SignToolPath -eq 'signtool.exe') { $signtoolReady = [bool](Get-Command 'signtool.exe' -ErrorAction SilentlyContinue) } else { $signtoolReady = Test-Path $signOptions.SignToolPath } if ($signtoolReady) { & $signOptions.SignToolPath @signtoolArgs if ($LASTEXITCODE -ne 0) { throw "signing failed for $Label with exit code $LASTEXITCODE" } } else { $cert = $null if (-not [string]::IsNullOrWhiteSpace($signOptions.CertFile)) { $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($signOptions.CertFile, $signOptions.CertPassword) } elseif (-not [string]::IsNullOrWhiteSpace($signOptions.CertThumbprint)) { $cert = Get-ChildItem -Path (Join-Path 'Cert:\CurrentUser\My' $signOptions.CertThumbprint) -ErrorAction SilentlyContinue } if (-not $cert) { throw "signing failed for $Label because certificate is unavailable" } if (-not [string]::IsNullOrWhiteSpace($signOptions.TimestampUrl)) { $result = Set-AuthenticodeSignature -FilePath $TargetPath -Certificate $cert -TimestampServer $signOptions.TimestampUrl -HashAlgorithm SHA256 } else { $result = Set-AuthenticodeSignature -FilePath $TargetPath -Certificate $cert -HashAlgorithm SHA256 } $acceptedStatuses = @('Valid', 'UnknownError') if ($acceptedStatuses -notcontains [string]$result.Status) { throw "signing failed for $Label with status $($result.Status)" } Write-Log ("SIGN FALLBACK Set-AuthenticodeSignature used for " + $Label + " status=" + $result.Status) } Write-Log ("SIGN OK " + $Label + " => " + $TargetPath) Write-ArtifactHash $TargetPath } function Sign-AppArtifacts { $appExePath = Join-Path $root 'dist\win-unpacked\printServer.exe' $serviceWrapperPath = Join-Path $root 'dist\win-unpacked\resources\daemon\printserver.exe' Invoke-SignFile -TargetPath $appExePath -Label 'app executable' Invoke-SignFile -TargetPath $serviceWrapperPath -Label 'service wrapper' } function Sign-InstallerArtifacts { $installer = Get-ChildItem -Path (Join-Path $root 'dist') -Filter 'printServer-*-setup.exe' -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending | Select-Object -First 1 if ($installer) { Invoke-SignFile -TargetPath $installer.FullName -Label 'nsis installer' return } Write-Log 'SIGN SKIP nsis installer missing in dist/' } function Update-ReleaseFeed { $version = Get-PackageVersion $installerFile = Get-InstallerFileName -Version $version $installerPath = Join-Path (Join-Path $root 'dist') $installerFile if (-not (Test-Path $installerPath)) { throw "installer missing for release feed: $installerPath" } $releaseDir = Join-Path $releaseStoreDir $version Ensure-Dir $releaseDir $archivedInstallerPath = Join-Path $releaseDir $installerFile Copy-Item -Path $installerPath -Destination $archivedInstallerPath -Force $blockmapFile = "$installerFile.blockmap" $blockmapPath = Join-Path (Join-Path $root 'dist') $blockmapFile $archivedBlockmapPath = Join-Path $releaseDir $blockmapFile if (Test-Path $blockmapPath) { Copy-Item -Path $blockmapPath -Destination $archivedBlockmapPath -Force } $releaseHash = (Get-FileHash -Path $archivedInstallerPath -Algorithm SHA256).Hash $releaseSize = (Get-Item $archivedInstallerPath).Length $builtAtUtc = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') $releaseEntry = [PSCustomObject]@{ version = $version installer = "releases/$version/$installerFile" blockmap = if (Test-Path $archivedBlockmapPath) { "releases/$version/$blockmapFile" } else { $null } sha256 = $releaseHash size = $releaseSize builtAtUtc = $builtAtUtc } $existingEntries = @() if (Test-Path $releaseFeedPath) { try { $existingFeed = Get-Content $releaseFeedPath -Raw | ConvertFrom-Json if ($existingFeed -and $existingFeed.releases) { foreach ($item in $existingFeed.releases) { if ([string]$item.version -ne $version) { $existingEntries += [PSCustomObject]@{ version = [string]$item.version installer = [string]$item.installer blockmap = if ($null -eq $item.blockmap) { $null } else { [string]$item.blockmap } sha256 = [string]$item.sha256 size = [int64]$item.size builtAtUtc = [string]$item.builtAtUtc } } } } } catch { throw "release feed parse failed: $($_.Exception.Message)" } } $allEntries = @($releaseEntry) + $existingEntries $allEntries = $allEntries | Sort-Object builtAtUtc -Descending $feed = [PSCustomObject]@{ app = 'printserver' channel = 'stable' latest = $version generatedAtUtc = $builtAtUtc releases = $allEntries } Ensure-Dir $versioningDir $feed | ConvertTo-Json -Depth 6 | Set-Content -Path $releaseFeedPath -Encoding UTF8 Write-Log "RELEASE ARCHIVE $archivedInstallerPath" if (Test-Path $archivedBlockmapPath) { Write-Log "RELEASE ARCHIVE $archivedBlockmapPath" } Write-Log "RELEASE FEED $releaseFeedPath latest=$version sha256=$releaseHash" } function Ensure-AppExecutable() { $appOutDir = Join-Path $root 'dist\win-unpacked' $targetExe = Join-Path $appOutDir 'printServer.exe' $fallbackSource = Join-Path $root 'node_modules\electron\dist\electron.exe' $runtimeMarker = Join-Path $appOutDir 'resources.pak' if (Test-Path $targetExe) { return $true } if ((Test-Path $appOutDir) -and (Test-Path $runtimeMarker) -and (Test-Path $fallbackSource)) { Copy-Item -Path $fallbackSource -Destination $targetExe -Force Write-Log 'FALLBACK app executable copied from node_modules/electron/dist/electron.exe' return $true } return $false } function Ensure-PackagedResources() { $appOutDir = Join-Path $root 'dist\win-unpacked' $resourcesDir = Join-Path $appOutDir 'resources' Ensure-Dir $resourcesDir $configTemplateSource = Join-Path $root 'config.packaged.json' $configTargetPath = Join-Path $resourcesDir 'config.json' if (Test-Path $configTemplateSource) { Copy-Item -Path $configTemplateSource -Destination $configTargetPath -Force } foreach ($fileName in @('printer.ps1')) { $sourcePath = Join-Path $root $fileName $targetPath = Join-Path $resourcesDir $fileName if (Test-Path $sourcePath) { Copy-Item -Path $sourcePath -Destination $targetPath -Force } } $iconSourcePath = Join-Path $root 'electron\assets\printserver.ico' $iconTargetPath = Join-Path $resourcesDir 'printserver.ico' if (Test-Path $iconSourcePath) { Copy-Item -Path $iconSourcePath -Destination $iconTargetPath -Force } foreach ($dirName in @('daemon', 'frpc')) { $sourcePath = Join-Path $root $dirName $targetPath = Join-Path $resourcesDir $dirName if (Test-Path $sourcePath) { if (Test-Path $targetPath) { Remove-Item -Path $targetPath -Recurse -Force } Copy-Item -Path $sourcePath -Destination $targetPath -Recurse -Force } } } function Clean-Stage { foreach ($target in @('dist', 'release')) { $fullPath = Join-Path $root $target if (Test-Path $fullPath) { Remove-Item -Path $fullPath -Recurse -Force } } if (Test-Path $tempPackagingDir) { Remove-Item -Path $tempPackagingDir -Recurse -Force } } function Prepare-Stage { Ensure-Dir $tempPackagingDir $requiredItems = @( 'index.js', 'config.packaged.json', 'printer.ps1', 'views\index.html', 'electron\main.cjs' ) $missing = @() foreach ($item in $requiredItems) { $target = Join-Path $root $item if (-not (Test-Path $target)) { $missing += $item } } if ($missing.Count -gt 0) { throw "missing required packaging inputs: $($missing -join ', ')" } $manifest = [PSCustomObject]@{ version = (Get-Content (Join-Path $root 'package.json') -Raw | ConvertFrom-Json).version checkedAt = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss') requiredItems = $requiredItems } $manifest | ConvertTo-Json -Depth 4 | Set-Content -Path (Join-Path $tempPackagingDir 'preflight-check.json') -Encoding UTF8 } function App-Stage { $builderFailed = $false try { Invoke-Builder @('--dir', '--win') } catch { $builderFailed = $true Write-Log ("WARN app stage failed before completion: " + $_.Exception.Message) } if ($builderFailed -and (Ensure-AppExecutable)) { Ensure-PackagedResources Sign-AppArtifacts Write-Log 'APP stage fallback completed with unpacked executable workaround' return } if ($builderFailed) { throw 'app stage failed and no usable unpacked executable was produced' } Ensure-PackagedResources Sign-AppArtifacts Write-Log 'APP stage resources synchronized' } function Win-Stage { App-Stage try { & node (Join-Path $root 'electron\build-installer.mjs') if ($LASTEXITCODE -ne 0) { throw "installer build failed with exit code $LASTEXITCODE" } Write-Log 'NSIS installer build completed' Sign-InstallerArtifacts Update-ReleaseFeed } catch { Write-Log ("ERROR NSIS installer unavailable: " + $_.Exception.Message) throw 'NSIS installer build failed; offline IExpress fallback has been disabled by policy' } } switch ($Stage) { 'clean' { Invoke-Step 'clean' { Clean-Stage } } 'prepare' { Invoke-Step 'prepare' { Prepare-Stage } } 'app' { Invoke-Step 'prepare' { Prepare-Stage } Invoke-Step 'app' { App-Stage } } 'win' { Invoke-Step 'version-check' { Assert-VersionArtifactNotExists } Invoke-Step 'prepare' { Prepare-Stage } Invoke-Step 'win' { Win-Stage } } 'package' { Invoke-Step 'version-check' { Assert-VersionArtifactNotExists } Invoke-Step 'clean' { Clean-Stage } Invoke-Step 'prepare' { Prepare-Stage } Invoke-Step 'win' { Win-Stage } } }