diff --git a/.github/workflows/ci-windows.yml b/.github/workflows/ci-windows.yml index c3ea5c58fc..1ef6862c46 100644 --- a/.github/workflows/ci-windows.yml +++ b/.github/workflows/ci-windows.yml @@ -116,12 +116,21 @@ jobs: - name: Parse Windows runner supervision scripts shell: pwsh run: | - foreach ($path in @('apps/desktop/scripts/windows-runner-task.ps1', 'apps/desktop/scripts/run-windows-runner-task.ps1', 'apps/desktop/scripts/start-windows-packaging-runner.ps1', 'apps/desktop/scripts/windows-runner-network.ps1', 'apps/desktop/scripts/run-windows-runner-network-process.ps1', 'apps/desktop/tests/windows-runner-task.ps1', 'apps/desktop/tests/windows-runner-launcher.ps1', 'apps/desktop/tests/windows-runner-network.ps1', 'apps/desktop/tests/windows-runner-network-process.ps1')) { + foreach ($path in @('apps/desktop/scripts/windows-runner-task.ps1', 'apps/desktop/scripts/windows-runner-scheduler.ps1', 'apps/desktop/tests/windows-runner-boot.ps1', 'apps/desktop/tests/windows-runner-processes.ps1', 'apps/desktop/tests/windows-runner-recovery.ps1', 'apps/desktop/scripts/run-windows-runner-task.ps1', 'apps/desktop/scripts/start-windows-packaging-runner.ps1', 'apps/desktop/scripts/windows-runner-network.ps1', 'apps/desktop/scripts/run-windows-runner-network-process.ps1', 'apps/desktop/tests/windows-runner-task.ps1', 'apps/desktop/tests/windows-runner-launcher.ps1', 'apps/desktop/tests/windows-runner-network.ps1', 'apps/desktop/tests/windows-runner-network-process.ps1')) { $tokens = $null $parseErrors = $null $null = [Management.Automation.Language.Parser]::ParseFile((Join-Path $env:GITHUB_WORKSPACE $path), [ref]$tokens, [ref]$parseErrors) if ($parseErrors.Count) { throw ($parseErrors -join "`n") } } + - name: Verify Windows unattended runner definitions and recovery + shell: pwsh + run: | + ./apps/desktop/tests/windows-runner-boot.ps1 + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + ./apps/desktop/tests/windows-runner-recovery.ps1 + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + ./apps/desktop/tests/windows-runner-processes.ps1 + exit $LASTEXITCODE - name: Verify windowless Windows runner launcher shell: pwsh run: ./apps/desktop/tests/windows-runner-launcher.ps1 diff --git a/.github/workflows/windows-package.yml b/.github/workflows/windows-package.yml index 405ee6bd29..c54f013a59 100644 --- a/.github/workflows/windows-package.yml +++ b/.github/workflows/windows-package.yml @@ -105,10 +105,11 @@ jobs: ref: ${{ github.workflow_sha }} sparse-checkout: apps/desktop/scripts - name: Stage workflow helpers + id: helpers run: | $helpers = Join-Path $env:RUNNER_TEMP "packaging-helpers-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" New-Item -ItemType Directory -Path $helpers -ErrorAction Stop | Out-Null - foreach ($name in @('windows-packaging-priority.ps1')) { + foreach ($name in @('windows-packaging-priority.ps1', 'windows-packaging-summary.mjs')) { Copy-Item -LiteralPath (Join-Path 'apps/desktop/scripts' $name) -Destination $helpers -ErrorAction Stop } "PACKAGE_CI_HELPERS=$helpers" >> $env:GITHUB_ENV @@ -176,6 +177,14 @@ jobs: env: PACKAGE_BUILD_VERSION: ${{ inputs.build_version }} run: node apps/desktop/scripts/prepare-windows-ci.mjs + - name: Summarize packaging parameters + if: always() && steps.helpers.outcome == 'success' + env: + PACKAGE_INPUT_VERSION_MODE: ${{ inputs.version_mode }} + PACKAGE_BUILD_VERSION: ${{ inputs.build_version }} + PACKAGE_SOURCE_SHA: ${{ steps.checkout.outputs.commit }} + PACKAGE_VERSION: ${{ steps.settings.outputs.version }} + run: node "$env:PACKAGE_CI_HELPERS/windows-packaging-summary.mjs" - name: Check packaging configuration and toolchain env: PACKAGE_VERSION: ${{ steps.settings.outputs.version }} diff --git a/apps/desktop/publishing/ci/README.i18n.yaml b/apps/desktop/publishing/ci/README.i18n.yaml index 7d9a3d1d4a..0e8c926ed0 100644 --- a/apps/desktop/publishing/ci/README.i18n.yaml +++ b/apps/desktop/publishing/ci/README.i18n.yaml @@ -15,8 +15,8 @@ en: 37d76f8473b967b7 zh: d211cc54af96672d /desktop-ci-publication/setup-sequence: - en: 2be541ef35a092a4 - zh: 77d87c00deb45758 + en: 4a7458326bb10b10 + zh: e48c2345ebd54aac /desktop-ci-publication/runner-labels-and-queue-diagnosis: en: d2195ee7581b74ec zh: 0b9847afe9a2a373 @@ -24,8 +24,8 @@ en: 0f43f2e193e95043 zh: 1c1efb062c06f7b8 /desktop-ci-publication/package-and-publish: - en: 6325c71df74a9915 - zh: edaa8a4502ed80a1 + en: 2b75de75308c7729 + zh: 1b09a6edd8c7e9b0 /desktop-ci-publication/rollout-and-website-publication: en: b6c39cec0946d5f4 zh: 3a6014ffbbec81f1 diff --git a/apps/desktop/publishing/ci/README.md b/apps/desktop/publishing/ci/README.md index 4b65c1eec2..f182d27b4a 100644 --- a/apps/desktop/publishing/ci/README.md +++ b/apps/desktop/publishing/ci/README.md @@ -28,7 +28,7 @@ Use this sequence when onboarding a dedicated machine. The deployment operator o 1. Prepare a runner-owned checkout and an external configuration directory. Follow [Windows machine setup and signing](../../windows-signing/README.md#machine-setup) or [macOS runner and signing setup](../../packaging/README.md#macos-actions) for tools, templates and platform credentials. 2. Register the runner using GitHub **Settings → Actions → Runners**, or the organization's runner administration page. Record its exact registered name, grant this repository access to its runner group, and assign the [required labels](#runner-labels). Keep the default labels during registration. -3. Install and start the platform supervisor described in the platform guide. Windows Task Scheduler and the macOS LaunchAgent require the configured user's login; they do not provide unattended startup before login. Confirm both GitHub connectivity and `Listening for Jobs`, then check the runner is online in GitHub. +3. Install and start the platform supervisor described in the platform guide. Windows supports optional Boot tasks for startup before login; its default Interactive task and the macOS LaunchAgent require the configured user's desktop login. Confirm both GitHub connectivity and `Listening for Jobs`, then check the runner is online in GitHub. 4. Complete [machine publication configuration](#machine-setup), the repository's `DESKTOP_PUBLISH_RUNNERS` variable, and the two deployment Environments. The repository administrator owns routing and reviewers; the COS administrator owns bucket configuration and object read/write permissions; production also needs the configured GitHub App. 5. Run a signed Windows or notarized macOS **test** package using [Package and publish](#package-and-publish). Confirm the packaging job used the intended registered runner and retained its files. Dispatch publication from `master` with that run ID and attempt; confirm `prepare` actually starts on the same machine and produces the approval summary. 6. Inspect the summary's environment, version, channel and URLs before approving the test upload. Verify the publication record, public installer download and update feed. Test acceptance does not establish production permissions: provision and approve production separately. Keep the run/attempt and acceptance results for recovery. @@ -69,6 +69,8 @@ Environment approval gates this workflow, not arbitrary code running under the s ## Package and publish +The Windows packaging run shows a Chinese parameter summary with the requested source, environment, channel, version mode, signing mode, compression, test release ID and cache namespace, plus the workflow identity, checked-out commit, resolved version and runner. Once workflow helpers are staged, earlier failures still produce the summary with unavailable results labeled explicitly. The summary reads no machine configuration; a blank test release ID is shown as machine-default selection, not its resolved value. It does not establish build, signature or publication success. + The publication form accepts an optional `staging_percentage` integer from 0 to 100. It applies to the retained package’s channel (nightly or stable), appears in the approval summary, and is included in the published YAML and audit record without modifying retained artifacts. Leave it blank for the packaged default (normally full rollout). Completed publications cannot change this percentage through a retry; same-version feed conflicts remain errors. For publication to either test or production, choose Windows `signing=signed` or leave macOS **Skip notarization** unchecked. Unsigned and unnotarized packages are only for internal debugging; they cannot publish or provide automatic updates. Before installing dependencies, the hosted routing job rejects debugging artifacts identified by the selected run and attempt. An archive-only rerun retains the original build attempt in artifact names, so this early check can miss it; local manifest qualification still rejects debugging builds before publication. Missing artifact metadata does not establish eligibility: the original machine still validates its retained manifest and signatures. A debugging-package rejection requires a new signed/notarized package and its run ID / attempt; retrying publication cannot qualify the existing bytes. diff --git a/apps/desktop/publishing/ci/README.zh.md b/apps/desktop/publishing/ci/README.zh.md index 097eeb4298..529238486e 100644 --- a/apps/desktop/publishing/ci/README.zh.md +++ b/apps/desktop/publishing/ci/README.zh.md @@ -28,7 +28,7 @@ description: "在专用 macOS 和 Windows runner 上发布留存的 Desktop 安 1. 准备 runner 专用 checkout 和仓库外的配置目录。按 [Windows 机器与签名配置](../../windows-signing/README.zh.md#machine-setup)或 [macOS runner 与签名配置](../../packaging/README.zh.md#macos-actions)准备工具、模板和平台凭据。 2. 通过 GitHub **Settings → Actions → Runners** 或组织的 runner 管理页面注册 runner。记录准确的注册名称,允许本仓库访问其 runner group,并分配[必需标签](#runner-labels)。注册时保留默认标签。 -3. 按平台指南安装并启动守护任务。Windows 计划任务和 macOS LaunchAgent 都要求配置的用户登录,不能在登录前无人值守启动。确认已连接 GitHub 且出现 `Listening for Jobs`,再检查 GitHub 中 runner 在线。 +3. 按平台指南安装并启动守护任务。Windows 可选 Boot 任务支持登录前启动;默认 Interactive 任务和 macOS LaunchAgent 仍要求配置的用户登录桌面。确认已连接 GitHub 且出现 `Listening for Jobs`,再检查 GitHub 中 runner 在线。 4. 完成[本机发布配置](#machine-setup)、仓库变量 `DESKTOP_PUBLISH_RUNNERS` 和两个部署 Environment。仓库管理员负责路由与审批人;COS 管理员负责桶配置及对象读写权限;production 还需要配置 GitHub App。 5. 按[打包与发布](#package-and-publish)完成一次 Windows 已签名或 macOS 已公证的 **test** 打包。确认打包 job 使用预期的注册 runner 并留存文件。从 `master` 发起发布,填写该 run ID 和 attempt;确认 `prepare` 确实在同一台机器上启动并生成审批摘要。 6. 审核摘要中的环境、版本、频道和 URL 后,再批准测试上传。验证发布记录、公开安装包下载和升级 feed。test 验收不能证明 production 权限可用:production 需独立配置与审批。保留 run/attempt 和验收结果,供故障恢复使用。 @@ -69,6 +69,8 @@ Environment 审批限制此工作流,不限制同一机器账户运行的任 ## 打包与发布 +Windows 打包运行会展示中文参数摘要,列出请求的源码、环境、通道、版本模式、签名方式、压缩等级、测试 release ID 和缓存命名空间,以及工作流标识、检出提交、解析版本和 runner。工作流辅助脚本暂存成功后,即使前序步骤失败仍会生成摘要,并明确标记尚未取得的结果。摘要不读取机器配置;测试 release ID 留空时仅显示选择了机器默认值,不展示其解析值。摘要不代表构建、签名或发布成功。 + 发布表单支持可选的 `staging_percentage`,取值为 0 到 100 的整数。该值作用于保留包所属的 nightly 或 stable 渠道,显示在审批摘要中,并写入发布的 YAML 和审计记录,不修改保留产物。留空沿用包内默认值(通常为全量)。已完成的发布不能通过重试修改比例;同版本清单内容冲突仍会报错。 发布到 test 或 production 都必须在 Windows 选择 `signing=signed`,或在 macOS 不勾选**跳过公证**。无签名、无公证的包仅限内部调试,不能发布或用于自动更新。托管路由 job 会在安装依赖前,依据所选 run 和 attempt 对应的 artifact 名称拒绝已标明的调试包。仅重跑归档时,artifact 名称保留原构建 attempt,早期检查可能未识别该包;本地清单资格校验仍会在发布前拒绝调试包。缺少 artifact 元数据不代表允许发布:原机器仍会验证留存清单和签名。遇到调试包拒绝提示时,需重新完成签名或公证,再使用新包的 run ID / attempt 发布;重跑发布不能使现有产物获得发布资格。 diff --git a/apps/desktop/scripts/desktop-toolchain-preflight.ts b/apps/desktop/scripts/desktop-toolchain-preflight.ts index ff855cfd09..da0f06a8ec 100644 --- a/apps/desktop/scripts/desktop-toolchain-preflight.ts +++ b/apps/desktop/scripts/desktop-toolchain-preflight.ts @@ -14,6 +14,8 @@ import { tmpdir } from 'node:os' import { basename, dirname, join } from 'node:path' import { promisify } from 'node:util' +import { scrubWindowsSigningEnvironment } from './windows-sign.mjs' + const run = promisify(execFile) /** One tool the packaging run requires, and what went wrong with it. */ @@ -45,6 +47,14 @@ async function probeTar(): Promise { async function probeWindowsInstallerToolchain(environment: NodeJS.ProcessEnv): Promise { const failures: DesktopToolchainProbeFailure[] = [] + try { + await run('pwsh', ['-NoProfile', '-NonInteractive', '-Command', + '$ErrorActionPreference="Stop"; if ($PSVersionTable.PSVersion.Major -lt 7) { throw "PowerShell 7 or newer is required" }; Import-Module "$PSHOME/Modules/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1" -ErrorAction Stop; Get-Command Get-AuthenticodeSignature -ErrorAction Stop | Out-Null'], + { env: scrubWindowsSigningEnvironment(environment), windowsHide: true, timeout: 20_000 }) + } + catch (error) { + failures.push({ tool: 'pwsh', detail: `PowerShell 7 with Authenticode support must be available on PATH: ${error instanceof Error ? error.message : String(error)}` }) + } const programFiles = environment['ProgramFiles(x86)'] const vswhere = programFiles === undefined ? undefined diff --git a/apps/desktop/scripts/run-windows-runner-task.ps1 b/apps/desktop/scripts/run-windows-runner-task.ps1 index 56371e970c..51b8890b97 100644 --- a/apps/desktop/scripts/run-windows-runner-task.ps1 +++ b/apps/desktop/scripts/run-windows-runner-task.ps1 @@ -4,17 +4,17 @@ $runnerRoot = [IO.Path]::GetFullPath((Split-Path -Parent $PSScriptRoot)).TrimEnd $digest = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($runnerRoot.ToUpperInvariant()))) $taskName = 'DSH-Packaging-' + $digest.Substring(0,16) $log = Join-Path $PSScriptRoot ('run-' + [DateTime]::UtcNow.ToString('yyyyMMddTHHmmssfffZ') + '-' + $PID + '.log') +$attemptReserved = $false try { $config = Get-Content -LiteralPath (Join-Path $PSScriptRoot 'config.json') -Raw | ConvertFrom-Json $attemptFile = Join-Path $PSScriptRoot 'attempts.txt' $attempts = [int](Get-Content -LiteralPath $attemptFile -Raw) if ($attempts -lt 0 -or $config.RestartCount -lt 1 -or $config.RestartCount -gt 999) { throw 'Invalid restart budget; reinstall the task.' } if ($attempts -gt $config.RestartCount) { - $null = Disable-ScheduledTask -TaskName $config.TaskName -TaskPath '\' - Set-Content -LiteralPath $log -Value 'Restart budget exhausted. Task disabled; inspect runner logs, fix the cause and run start.' - exit 1 + throw 'Restart budget exhausted; inspect runner logs, fix the cause and run start.' } Set-Content -LiteralPath $attemptFile -Value ($attempts + 1) + $attemptReserved = $true $startup = Join-Path $PSScriptRoot 'start.ps1' if ($config.NetworkRoot) { if (-not (Test-Path -LiteralPath (Join-Path $config.ConfigRoot 'runner-network.json') -PathType Leaf)) { throw 'Owned network supervision requires runner-network.json.' } @@ -27,10 +27,25 @@ try { # An unexpected exit is a task failure even when run.cmd hides the listener's nonzero status; the log retains its code. exit 1 } catch { - # A missing or unwritable counter cannot bound retries; the task name must not depend on readable configuration. - $null = Disable-ScheduledTask -TaskName $taskName -TaskPath '\' - $message = 'Runner task failed: ' + $_.Exception.Message + $failure = $_.Exception.Message + $disposition = 'Scheduled recovery remains bounded by the persisted attempt budget.' + # Stop triggers when the budget is exhausted or an attempt could not be persisted. + if (-not $attemptReserved) { + try { + $scheduler = New-Object -ComObject 'Schedule.Service' + $scheduler.Connect() + $scheduler.GetFolder('\').GetTask($taskName).Enabled = $false + $disposition = 'Task disabled; inspect configuration and attempt storage before starting.' + } catch { + # A limited task account may lack permission to change its scheduler registration. + $disposition = 'Task disable failed; an administrator must disable its triggers. No runner was launched.' + } + } + $message = 'Runner task failed: ' + $failure + ' ' + $disposition [Console]::Error.WriteLine($message) - Add-Content -LiteralPath $log -Value $message + try { Add-Content -LiteralPath $log -Value $message } catch { + # The launcher captures stderr independently when the runner log is unavailable. + [Console]::Error.WriteLine('Runner log unavailable: ' + $_.Exception.Message) + } exit 1 } diff --git a/apps/desktop/scripts/windows-packaging-summary.d.mts b/apps/desktop/scripts/windows-packaging-summary.d.mts new file mode 100644 index 0000000000..d369273144 --- /dev/null +++ b/apps/desktop/scripts/windows-packaging-summary.d.mts @@ -0,0 +1,7 @@ +/** Windows packaging parameter summary without machine configuration access. */ +/** + * Summarize allowlisted workflow inputs and resolved build identity. + * @param environment Workflow inputs and GitHub run identity. + * @returns Markdown tables without a build or signature success claim. + */ +export function windowsPackagingSummary(environment: NodeJS.ProcessEnv): string diff --git a/apps/desktop/scripts/windows-packaging-summary.mjs b/apps/desktop/scripts/windows-packaging-summary.mjs new file mode 100644 index 0000000000..c5f9d2aac4 --- /dev/null +++ b/apps/desktop/scripts/windows-packaging-summary.mjs @@ -0,0 +1,45 @@ +/** Render Windows packaging inputs and resolved build identity without loading machine configuration. */ +import { appendFile } from 'node:fs/promises' +import { realpathSync } from 'node:fs' +import { fileURLToPath } from 'node:url' + +function text(value) { + return value.replace(/[&<>"'|`\r\n\\*_\[\]()!~:]/gu, character => `&#${character.charCodeAt(0)};`) +} + +/** + * Summarize allowlisted workflow inputs separately from resolved checkout and version values. + * @param {NodeJS.ProcessEnv} environment Workflow inputs and GitHub run identity. + * @returns {string} Markdown parameter tables; no signature or publication success claim. + */ +export function windowsPackagingSummary(environment) { + const row = (label, value, fallback = '未提供') => `| ${label} | ${value ? `${text(value)}` : fallback} |` + return [ + '## Windows 打包参数', '', + '以下记录输入参数与已解析结果,不代表构建、签名或发布成功;执行结果以各步骤状态为准。', '', + '### 输入参数', '', '| 项目 | 选择值 |', '| --- | --- |', + row('源码 ref', environment.PACKAGE_SOURCE_REF), + row('环境', environment.DSH_PACKAGING_PRESET), + row('升级通道', environment.DSH_DESKTOP_UPDATE_CHANNEL), + row('版本模式', environment.PACKAGE_INPUT_VERSION_MODE), + row('手动版本号', environment.PACKAGE_BUILD_VERSION, '未填写'), + row('签名方式(请求)', environment.PACKAGE_SIGNING), + row('安装器压缩等级', environment.PACKAGE_WINDOWS_COMPRESSION_LEVEL), + row('测试 release ID(输入)', environment.PACKAGE_TEST_RELEASE_ID, '使用机器默认值(本摘要不读取)'), + row('缓存命名空间', environment.PACKAGE_CACHE_NAMESPACE, '共享缓存'), '', + '### 执行信息', '', '| 项目 | 已知值 |', '| --- | --- |', + row('平台', 'win-x64'), + row('工作流 ref', environment.GITHUB_WORKFLOW_REF), + row('工作流 SHA', environment.GITHUB_WORKFLOW_SHA), + row('检出源码 SHA', environment.PACKAGE_SOURCE_SHA, '尚未取得'), + row('解析后的版本号', environment.PACKAGE_VERSION, '尚未解析成功'), + row('Runner', environment.RUNNER_NAME), + row('运行 ID', environment.GITHUB_RUN_ID), + row('尝试次数', environment.GITHUB_RUN_ATTEMPT), '', + ].join('\n') +} + +if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) { + if (!process.env.GITHUB_STEP_SUMMARY) throw new Error('Windows packaging summary requires GITHUB_STEP_SUMMARY') + await appendFile(process.env.GITHUB_STEP_SUMMARY, windowsPackagingSummary(process.env)) +} diff --git a/apps/desktop/scripts/windows-runner-network.ps1 b/apps/desktop/scripts/windows-runner-network.ps1 index 9ab2491901..7112e200fd 100644 --- a/apps/desktop/scripts/windows-runner-network.ps1 +++ b/apps/desktop/scripts/windows-runner-network.ps1 @@ -48,7 +48,7 @@ function Wait-RunnerNetwork($Config) { $info.Environment['DSH_NETWORK_PROBE_TIMEOUT'] = [string]($Config.timeoutSeconds * 1000) $info.ArgumentList.Add('--input-type=module') $info.ArgumentList.Add('-e') - $info.ArgumentList.Add('try { const r = await fetch(process.env.DSH_NETWORK_PROBE_URL, { method: "HEAD", redirect: "error", signal: AbortSignal.timeout(Number(process.env.DSH_NETWORK_PROBE_TIMEOUT)) }); await r.body?.cancel(); process.exit(r.ok ? 0 : 1); } catch { process.exit(1); }') + $info.ArgumentList.Add('try { const r = await fetch(process.env.DSH_NETWORK_PROBE_URL, { method: "HEAD", redirect: "error", signal: AbortSignal.timeout(Number(process.env.DSH_NETWORK_PROBE_TIMEOUT)) }); await r.body?.cancel(); process.exitCode = r.ok ? 0 : 1; } catch { process.exitCode = 1; }') for ($attempt = 1; $attempt -le $Config.attempts; $attempt++) { $ready = $true if ($Config.serviceName) { diff --git a/apps/desktop/scripts/windows-runner-processes.cs b/apps/desktop/scripts/windows-runner-processes.cs new file mode 100644 index 0000000000..171f17798a --- /dev/null +++ b/apps/desktop/scripts/windows-runner-processes.cs @@ -0,0 +1,50 @@ +// Toolhelp snapshots expose parent IDs without the WMI namespace permissions required by CIM. +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; + +public static class DshRunnerProcesses +{ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct Entry + { + public uint Size, Usage, ProcessId; + public UIntPtr DefaultHeapId; + public uint ModuleId, Threads, ParentProcessId; + public int Priority; + public uint Flags; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string Name; + } + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern IntPtr CreateToolhelp32Snapshot(uint flags, uint processId); + [DllImport("kernel32.dll", EntryPoint = "Process32FirstW", SetLastError = true)] + private static extern bool First(IntPtr snapshot, ref Entry entry); + [DllImport("kernel32.dll", EntryPoint = "Process32NextW", SetLastError = true)] + private static extern bool Next(IntPtr snapshot, ref Entry entry); + [DllImport("kernel32.dll")] + private static extern bool CloseHandle(IntPtr handle); + + // These parent IDs select handles to await; taskkill retains termination authority over the live tree. + public static Dictionary ReadParents() + { + IntPtr snapshot = CreateToolhelp32Snapshot(2, 0); + if (snapshot == new IntPtr(-1)) throw new Win32Exception(Marshal.GetLastWin32Error()); + try + { + var result = new Dictionary(); + var entry = new Entry { Size = (uint)Marshal.SizeOf(typeof(Entry)) }; + bool found = First(snapshot, ref entry); + while (found) + { + result.Add((int)entry.ProcessId, (int)entry.ParentProcessId); + found = Next(snapshot, ref entry); + } + int error = Marshal.GetLastWin32Error(); + if (error != 18) throw new Win32Exception(error); + return result; + } + finally { CloseHandle(snapshot); } + } +} diff --git a/apps/desktop/scripts/windows-runner-scheduler.ps1 b/apps/desktop/scripts/windows-runner-scheduler.ps1 new file mode 100644 index 0000000000..4514ffba60 --- /dev/null +++ b/apps/desktop/scripts/windows-runner-scheduler.ps1 @@ -0,0 +1,72 @@ +# Build an unregistered runner task. Credentials are supplied only to the scheduler at installation. +function New-WindowsRunnerTaskDefinition($Scheduler, [string]$Sid, [string]$RunnerRoot, [string]$PowerShell, [int]$RestartMinutes, [ValidateSet('Interactive','Boot')][string]$StartupMode = 'Interactive') { + $definition = $Scheduler.NewTask(0) + $definition.RegistrationInfo.Description = "DSH packaging runner: $RunnerRoot; owner: $Sid" + $definition.Principal.UserId = $Sid + $definition.Principal.LogonType = if ($StartupMode -eq 'Boot') { 1 } else { 3 } # Password or InteractiveToken. + $definition.Principal.RunLevel = 0 # TASK_RUNLEVEL_LUA: the job does not inherit installer elevation. + $definition.Settings.Priority = 4 + $definition.Settings.Enabled = $false + $definition.Settings.MultipleInstances = 2 # TASK_INSTANCES_IGNORE_NEW + $definition.Settings.ExecutionTimeLimit = 'PT0S' + $definition.Settings.DisallowStartIfOnBatteries = $false + $definition.Settings.StopIfGoingOnBatteries = $false + if ($StartupMode -eq 'Boot') { + $null = $definition.Triggers.Create(8) # TASK_TRIGGER_BOOT + } else { + $logon = $definition.Triggers.Create(9) # TASK_TRIGGER_LOGON + $logon.UserId = $Sid + } + $recovery = $definition.Triggers.Create(1) # TASK_TRIGGER_TIME + $recovery.StartBoundary = (Get-Date).AddMinutes($RestartMinutes).ToString('yyyy-MM-ddTHH:mm:ss') + $recovery.Repetition.Interval = "PT${RestartMinutes}M" + $execution = $definition.Actions.Create(0) # TASK_ACTION_EXEC + $execution.Path = Join-Path $RunnerRoot 'dsh-task/launcher.exe' + $execution.Arguments = '"' + $PowerShell + '"' + $execution.WorkingDirectory = $RunnerRoot + return $definition +} + +# Prompt locally and submit once; credential-bearing COM failures must not reach diagnostics. +function Register-WindowsRunnerBootTask($Scheduler, [string]$TaskName, $Definition, [string]$Sid, [string]$RunAs) { + $credential = Get-Credential -UserName $RunAs -Message 'Windows account password for unattended runner startup (not the signing Token PIN)' + if (-not $credential -or $credential.UserName -ne $RunAs -or $credential.Password.Length -eq 0) { + throw 'Credential entry cancelled or account changed; no task was registered.' + } + try { + # COM avoids putting a plaintext password in command arguments or cmdlet parameter logging. + $null = $Scheduler.GetFolder('\').RegisterTaskDefinition($TaskName, $Definition, 2, $RunAs, $credential.GetNetworkCredential().Password, 1, "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;$Sid)") + } catch { + # Registration may have committed before an error reached this caller. + $code = '0x{0:X8}' -f $_.Exception.GetBaseException().HResult + throw "Boot task registration failed ($code); registration outcome is unconfirmed. Inspect Task Scheduler, batch-logon policy and account credentials locally before retrying." + } finally { + $credential = $null + } +} + +# Validate machine-owned preparation data before credentials or scheduler registration. +function Assert-WindowsRunnerBootConfiguration($Config, [string]$Sid, [string]$RunnerRoot, [string]$TaskName) { + if ($Config.StartupMode -ne 'Boot' -or $Config.AccountSid -ne $Sid -or $Config.RunnerRoot -ne $RunnerRoot -or $Config.TaskName -ne $TaskName) { + throw 'Prepared Boot configuration does not match RunAs and RunnerRoot; prepare again as the runner account.' + } + if (($Config.RestartMinutes -isnot [int] -and $Config.RestartMinutes -isnot [long]) -or $Config.RestartMinutes -lt 1 -or $Config.RestartMinutes -gt 1440 -or $Config.PowerShell -isnot [string] -or $Config.PowerShell -notmatch '^[A-Za-z]:[\\/]' -or -not (Test-Path -LiteralPath $Config.PowerShell -PathType Leaf) -or -not (Test-Path -LiteralPath (Join-Path $RunnerRoot 'dsh-task/launcher.exe') -PathType Leaf)) { + throw 'Prepared Boot startup files or restart interval are invalid; prepare again as the runner account.' + } +} + +# Missing tasks are distinct from denied or unavailable scheduler access. +function Get-WindowsRunnerTask($Scheduler, [string]$TaskName) { + try { return $Scheduler.GetFolder('\').GetTask($TaskName) } catch { + if ($_.Exception.GetBaseException().HResult -eq -2147024894) { return $null } + throw + } +} + +# Unreadable process locations must reject maintenance just like missing locations. +function Get-WindowsRunnerProcessPath($Process) { + try { return $Process.Path } catch { + # Access-denied and exited-process errors cannot establish an unrelated location. + return $null + } +} diff --git a/apps/desktop/scripts/windows-runner-task.ps1 b/apps/desktop/scripts/windows-runner-task.ps1 index e940eef988..3bb086b9e8 100644 --- a/apps/desktop/scripts/windows-runner-task.ps1 +++ b/apps/desktop/scripts/windows-runner-task.ps1 @@ -1,18 +1,21 @@ -# Manage a registered packaging runner in the current user's interactive Windows session. +# Prepare startup files and manage runner tasks; Boot registration requires an administrator. [CmdletBinding()] param( - [Parameter(Mandatory=$true)][ValidateSet('install','start','stop','status','uninstall')][string]$Action, + [Parameter(Mandatory=$true)][ValidateSet('install','register-boot','start','stop','status','uninstall')][string]$Action, [Parameter(Mandatory=$true)][string]$RunnerRoot, [string]$ConfigRoot, [string]$NetworkRoot, + [ValidateSet('Interactive','Boot')][string]$StartupMode = 'Interactive', + [string]$RunAs, [ValidateRange(1,1440)][int]$RestartMinutes = 1, [ValidateRange(1,999)][int]$RestartCount = 10 ) $ErrorActionPreference = 'Stop' if (-not $IsWindows) { throw 'This command requires PowerShell 7 on Windows.' } -if ($Action -ne 'install' -and @('ConfigRoot','NetworkRoot','RestartMinutes','RestartCount').Where({ $PSBoundParameters.ContainsKey($_) }).Count) { - throw 'ConfigRoot, NetworkRoot, RestartMinutes and RestartCount apply only to install; reinstall to change them.' +if ($Action -ne 'install' -and @('ConfigRoot','NetworkRoot','StartupMode','RestartMinutes','RestartCount').Where({ $PSBoundParameters.ContainsKey($_) }).Count) { + throw 'Configuration and retry options apply only to install; reinstall to change them.' } +if ($Action -ne 'register-boot' -and $PSBoundParameters.ContainsKey('RunAs')) { throw 'RunAs applies only to register-boot.' } if ($RunnerRoot -notmatch '^[A-Za-z]:[\\/]') { throw 'RunnerRoot must be an absolute local directory.' } $RunnerRoot = [IO.Path]::GetFullPath($RunnerRoot).TrimEnd('\','/') if (-not (Test-Path -LiteralPath (Join-Path $RunnerRoot '.runner') -PathType Leaf)) { throw 'Register the runner before managing its task.' } @@ -23,11 +26,46 @@ $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value $digest = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($RunnerRoot.ToUpperInvariant()))) $taskName = 'DSH-Packaging-' + $digest.Substring(0,16) $serviceDir = Join-Path $RunnerRoot 'dsh-task' -$task = Get-ScheduledTask -TaskPath '\' | Where-Object TaskName -eq $taskName -if ($task -and $task.Description -ne "DSH packaging runner: $RunnerRoot; owner: $sid") { throw 'Task ownership differs; inspect it in Task Scheduler.' } +if ($Action -eq 'register-boot') { + if (-not $RunAs) { throw 'Boot registration requires -RunAs with the prepared runner account.' } + $identity = [Security.Principal.WindowsIdentity]::GetCurrent() + if (-not ([Security.Principal.WindowsPrincipal]::new($identity)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { + throw 'Boot registration requires an elevated PowerShell; the runner account remains limited.' + } + $sid = ([Security.Principal.NTAccount]::new($RunAs)).Translate([Security.Principal.SecurityIdentifier]).Value + if ($sid -in @('S-1-5-18','S-1-5-19','S-1-5-20') -or $sid.EndsWith('-500')) { throw 'Use a dedicated runner account, not a built-in service or Administrator account.' } +} +. (Join-Path $PSScriptRoot 'windows-runner-scheduler.ps1') +$scheduler = New-Object -ComObject 'Schedule.Service' +$scheduler.Connect() +$task = Get-WindowsRunnerTask $scheduler $taskName +if ($task -and $task.Definition.RegistrationInfo.Description -ne "DSH packaging runner: $RunnerRoot; owner: $sid") { throw 'Task ownership differs; inspect it in Task Scheduler.' } + +if ($Action -in @('install','register-boot')) { + if ($task) { throw 'Task already installed; stop and uninstall before reinstalling.' } + # Pause dispatch before migration; never overwrite a live startup snapshot. + foreach ($process in @(Get-Process | Where-Object { $_.ProcessName -in @('Runner.Listener','Runner.Worker') })) { + $path = Get-WindowsRunnerProcessPath $process + if (-not $path -or $path.StartsWith($RunnerRoot + '\', [StringComparison]::OrdinalIgnoreCase)) { + throw 'A runner process is active or its location is unreadable. Pause dispatch and stop its supervisor before installing.' + } + } + if (Test-Path -LiteralPath (Join-Path $RunnerRoot '.service')) { throw 'A native runner service is configured; inspect and remove it before task migration.' } + if ((Test-Path -LiteralPath $serviceDir) -and ((Get-Item -LiteralPath $serviceDir).Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'Task directory cannot be a link.' } +} +if ($Action -eq 'register-boot') { + # This elevated path only registers a limited task; it never executes runner-owned files. + $configFile = Join-Path $serviceDir 'config.json' + if ((Get-Item -LiteralPath $configFile).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Task configuration cannot be a link.' } + $config = Get-Content -LiteralPath $configFile -Raw | ConvertFrom-Json + Assert-WindowsRunnerBootConfiguration $config $sid $RunnerRoot $taskName + $definition = New-WindowsRunnerTaskDefinition $scheduler $sid $RunnerRoot $config.PowerShell $config.RestartMinutes 'Boot' + Register-WindowsRunnerBootTask $scheduler $taskName $definition $sid $RunAs + Write-Output "Registered disabled Boot task $taskName. Run start as the runner account. Logs: $serviceDir" + exit 0 +} if ($Action -eq 'install') { - if ($task) { throw 'Task already installed; stop and uninstall before reinstalling.' } if (-not $ConfigRoot -or $ConfigRoot -notmatch '^[A-Za-z]:[\\/]') { throw 'Install requires an absolute ConfigRoot.' } $ConfigRoot = [IO.Path]::GetFullPath($ConfigRoot) $pwsh = Join-Path $PSHOME 'pwsh.exe' @@ -56,46 +94,47 @@ if ($Action -eq 'install') { foreach ($helper in @('windows-runner-network.ps1','run-windows-runner-network-process.ps1')) { Copy-Item -LiteralPath (Join-Path $PSScriptRoot $helper) -Destination (Join-Path $serviceDir $helper) } - @{ RunnerRoot = $RunnerRoot; ConfigRoot = $ConfigRoot; NetworkRoot = $NetworkRoot; TaskName = $taskName; RestartCount = $RestartCount } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $serviceDir 'config.json') -Encoding utf8 + @{ RunnerRoot = $RunnerRoot; ConfigRoot = $ConfigRoot; NetworkRoot = $NetworkRoot; TaskName = $taskName; RestartCount = $RestartCount; StartupMode = $StartupMode; AccountSid = $sid; PowerShell = $pwsh; RestartMinutes = $RestartMinutes } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $serviceDir 'config.json') -Encoding utf8 Set-Content -LiteralPath (Join-Path $serviceDir 'attempts.txt') -Value '0' - $execution = New-ScheduledTaskAction -Execute $launcher -Argument ('"' + $pwsh + '"') -WorkingDirectory $RunnerRoot - $principal = New-ScheduledTaskPrincipal -UserId $sid -LogonType Interactive -RunLevel Limited - $trigger = @( - (New-ScheduledTaskTrigger -AtLogOn -User $sid), - (New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes($RestartMinutes) -RepetitionInterval (New-TimeSpan -Minutes $RestartMinutes)) - ) - $settings = New-ScheduledTaskSettingsSet -Priority 4 -MultipleInstances IgnoreNew -ExecutionTimeLimit ([TimeSpan]::Zero) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries - $settings.Enabled = $false - $null = Register-ScheduledTask -TaskName $taskName -TaskPath '\' -Action $execution -Principal $principal -Trigger $trigger -Settings $settings -Description "DSH packaging runner: $RunnerRoot; owner: $sid" + if ($StartupMode -eq 'Boot') { + Write-Output "Prepared Boot startup for account $sid. An administrator must run register-boot with RunnerRoot and RunAs; no task was registered." + exit 0 + } + $definition = New-WindowsRunnerTaskDefinition $scheduler $sid $RunnerRoot $pwsh $RestartMinutes 'Interactive' + $null = $scheduler.GetFolder('\').RegisterTaskDefinition($taskName, $definition, 2, $sid, $null, 3, $null) Write-Output "Installed disabled task $taskName. Run start while logged in; reboot requires desktop login. Logs: $serviceDir" exit 0 } if (-not $task) { throw 'Task is not installed for this runner directory.' } switch ($Action) { 'status' { - $info = Get-ScheduledTaskInfo -InputObject $task + $bootTrigger = $false + for ($index = 1; $index -le $task.Definition.Triggers.Count; $index++) { + if ($task.Definition.Triggers.Item($index).Type -eq 8) { $bootTrigger = $true } + } $launches = [int](Get-Content -LiteralPath (Join-Path $serviceDir 'attempts.txt') -Raw) $config = Get-Content -LiteralPath (Join-Path $serviceDir 'config.json') -Raw | ConvertFrom-Json - [pscustomobject]@{ TaskName = $taskName; State = $task.State; LastRunTime = $info.LastRunTime; LastTaskResult = $info.LastTaskResult; Launches = $launches; RemainingLaunches = [Math]::Max(0, 1 + $config.RestartCount - $launches); Logs = $serviceDir } + [pscustomobject]@{ TaskName = $taskName; State = @('Unknown','Disabled','Queued','Ready','Running')[[int]$task.State]; Account = $task.Definition.Principal.UserId; LogonType = @('None','Password','S4U','Interactive','Group','ServiceAccount','InteractiveOrPassword')[[int]$task.Definition.Principal.LogonType]; BootTrigger = $bootTrigger; LastRunTime = $task.LastRunTime; LastTaskResult = $task.LastTaskResult; Launches = $launches; RemainingLaunches = [Math]::Max(0, 1 + $config.RestartCount - $launches); Logs = $serviceDir } } 'start' { - if ($task.State -eq 'Running') { Write-Output "$taskName is already running."; break } + if ($task.State -eq 4) { Write-Output "$taskName is already running."; break } Set-Content -LiteralPath (Join-Path $serviceDir 'attempts.txt') -Value '0' - $null = Enable-ScheduledTask -InputObject $task - Start-ScheduledTask -InputObject $task + $task.Enabled = $true + $null = $task.Run($null) Write-Output "Start requested for $taskName. Verify Connected to GitHub and Listening for Jobs in $serviceDir." } 'stop' { # Operators pause workflow dispatch first; this local check cannot reserve an idle GitHub runner. - $workers = Get-CimInstance Win32_Process -Filter "Name = 'Runner.Worker.exe'" + $workers = Get-Process | Where-Object ProcessName -eq 'Runner.Worker' foreach ($worker in $workers) { - if (-not $worker.ExecutablePath -or $worker.ExecutablePath.StartsWith($RunnerRoot + '\', [StringComparison]::OrdinalIgnoreCase)) { + $path = Get-WindowsRunnerProcessPath $worker + if (-not $path -or $path.StartsWith($RunnerRoot + '\', [StringComparison]::OrdinalIgnoreCase)) { throw 'A runner job is active or its location is unreadable. Wait for completion before stopping.' } } - $null = Disable-ScheduledTask -InputObject $task - $task = Get-ScheduledTask -TaskName $taskName -TaskPath '\' - if ($task.State -eq 'Running') { + $task.Enabled = $false + $task = Get-WindowsRunnerTask $scheduler $taskName + if ($task.State -eq 4) { $recordFile = Join-Path $serviceDir 'process.json' if (-not (Test-Path -LiteralPath $recordFile)) { throw 'Running task process identity is unavailable. Automatic starts are disabled; inspect the task before stopping it.' } $record = Get-Content -LiteralPath $recordFile -Raw | ConvertFrom-Json @@ -104,13 +143,14 @@ switch ($Action) { throw 'Running task process identity is unavailable. Automatic starts are disabled; inspect the task before stopping it.' } # Parent IDs can be reused; this snapshot supplies wait handles, not termination authority. - $processes = @(Get-CimInstance Win32_Process) + if (-not ('DshRunnerProcesses' -as [type])) { Add-Type -Path (Join-Path $PSScriptRoot 'windows-runner-processes.cs') } + $processes = [DshRunnerProcesses]::ReadParents() $ownedIds = [Collections.Generic.HashSet[int]]::new() $null = $ownedIds.Add($owner.Id) do { $added = $false - foreach ($process in $processes) { - if ($ownedIds.Contains([int]$process.ParentProcessId) -and $ownedIds.Add([int]$process.ProcessId)) { $added = $true } + foreach ($process in $processes.GetEnumerator()) { + if ($ownedIds.Contains([int]$process.Value) -and $ownedIds.Add([int]$process.Key)) { $added = $true } } } while ($added) $owned = @(foreach ($ownedId in $ownedIds) { Get-Process -Id $ownedId -ErrorAction SilentlyContinue }) @@ -120,19 +160,19 @@ switch ($Action) { if (-not $process.WaitForExit(30000)) { throw 'Runner task child remains alive; inspect it before restarting.' } } } - Stop-ScheduledTask -InputObject $task + $task.Stop(0) $deadline = [DateTime]::UtcNow.AddSeconds(30) do { - $state = (Get-ScheduledTask -TaskName $taskName -TaskPath '\').State - if ($state -ne 'Running') { break } + $state = (Get-WindowsRunnerTask $scheduler $taskName).State + if ($state -ne 4) { break } Start-Sleep -Milliseconds 200 } while ([DateTime]::UtcNow -lt $deadline) - if ($state -eq 'Running') { throw 'Task remains running; inspect its processes before further maintenance.' } + if ($state -eq 4) { throw 'Task remains running; inspect its processes before further maintenance.' } Write-Output "Stopped and disabled $taskName. Run start to enable automatic starts again." } 'uninstall' { - if ($task.State -ne 'Disabled') { throw 'Stop the task before uninstalling.' } - Unregister-ScheduledTask -InputObject $task -Confirm:$false + if ($task.State -ne 1) { throw 'Stop the task before uninstalling.' } + $scheduler.GetFolder('\').DeleteTask($taskName, 0) Write-Output "Uninstalled $taskName. Registration, configuration and logs remain in $RunnerRoot." } } diff --git a/apps/desktop/scripts/windows-runtime-signature.mjs b/apps/desktop/scripts/windows-runtime-signature.mjs index 9f79547b34..c85a23fbda 100644 --- a/apps/desktop/scripts/windows-runtime-signature.mjs +++ b/apps/desktop/scripts/windows-runtime-signature.mjs @@ -9,13 +9,12 @@ import { inspectSignaturesBatched } from './windows-signature-batch.mjs' import { packagingStep } from './packaging-step.mjs' /** - * Read Windows trust, timestamp and signer identity using the engine's bundled modules, without accessing the private key. + * Read Windows trust, timestamp and signer identity using PowerShell 7's bundled modules, without accessing the private key. * @param {string} path File to inspect. * @returns {Promise<{status: string, timestamped: boolean, thumbprint: string | null}>} Authenticode verification result. */ export async function inspectWindowsRuntimeSignature(path) { - // Node can inherit PowerShell 7's module search path while launching Windows PowerShell 5. - const { stdout, stderr } = await promisify(execFile)('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', + const { stdout, stderr } = await promisify(execFile)('pwsh', ['-NoProfile', '-NonInteractive', '-Command', '$ErrorActionPreference="Stop"; [Console]::OutputEncoding=[System.Text.UTF8Encoding]::new(); Import-Module "$PSHOME/Modules/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1" -ErrorAction Stop; Import-Module "$PSHOME/Modules/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1" -ErrorAction Stop; $s=Get-AuthenticodeSignature -LiteralPath $env:DSH_RUNTIME_VERIFY_FILE; [pscustomobject]@{status=[string]$s.Status;timestamped=($null -ne $s.TimeStamperCertificate);thumbprint=$s.SignerCertificate.Thumbprint}|ConvertTo-Json -Compress'], { env: { ...scrubWindowsSigningEnvironment(process.env), DSH_RUNTIME_VERIFY_FILE: path }, encoding: 'utf8', windowsHide: true, timeout: 60_000, maxBuffer: 64 * 1024, diff --git a/apps/desktop/scripts/windows-signature-batch.mjs b/apps/desktop/scripts/windows-signature-batch.mjs index cbc37b9d30..4b54428c45 100644 --- a/apps/desktop/scripts/windows-signature-batch.mjs +++ b/apps/desktop/scripts/windows-signature-batch.mjs @@ -1,4 +1,4 @@ -/** Bounded public-key verification batches; every output row must match its requested file. */ +/** Bounded PowerShell 7 public-key verification batches; every output row must match its requested file. */ import { execFile } from 'node:child_process' import { promisify } from 'node:util' import { scrubWindowsSigningEnvironment } from './windows-sign.mjs' @@ -27,7 +27,7 @@ export function parseSignatureRows(stdout, stderr, files) { } async function inspectBatch(files) { - const pending = promisify(execFile)('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', command], { + const pending = promisify(execFile)('pwsh', ['-NoProfile', '-NonInteractive', '-Command', command], { env: scrubWindowsSigningEnvironment(process.env), encoding: 'utf8', windowsHide: true, timeout: 60_000, maxBuffer: 64 * 1024 * files.length, }) diff --git a/apps/desktop/tests/desktop-build-commit.spec.ts b/apps/desktop/tests/desktop-build-commit.spec.ts index 57016a5e7e..ab3c252e67 100644 --- a/apps/desktop/tests/desktop-build-commit.spec.ts +++ b/apps/desktop/tests/desktop-build-commit.spec.ts @@ -73,6 +73,18 @@ describe('desktop toolchain preflight', () => { expect(failures.find(failure => failure.tool === 'vswhere')?.detail).toContain('ProgramFiles(x86)') }) + it('reports missing PowerShell before Windows packaging', async () => { + const empty = await mkdtemp(join(tmpdir(), 'dsh-no-pwsh-')) + directories.push(empty) + const failures = await probeDesktopToolchain('win32', { PATH: empty }) + expect(failures.find(failure => failure.tool === 'pwsh')?.detail).toContain('PowerShell 7') + }) + + it.skipIf(process.platform !== 'win32')('accepts the Windows Authenticode toolchain', async () => { + const failures = await probeDesktopToolchain('win32', process.env) + expect(failures.filter(failure => failure.tool === 'pwsh')).toEqual([]) + }) + it('writes nothing into the working directory while probing', async () => { const directory = await mkdtemp(join(tmpdir(), 'dsh-probe-cwd-')) directories.push(directory) diff --git a/apps/desktop/tests/windows-packaging-summary.spec.ts b/apps/desktop/tests/windows-packaging-summary.spec.ts new file mode 100644 index 0000000000..328cb85d16 --- /dev/null +++ b/apps/desktop/tests/windows-packaging-summary.spec.ts @@ -0,0 +1,58 @@ +/** Workflow summaries distinguish requested options from completed build evidence. */ +import { execFile } from 'node:child_process' +import { copyFile, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { promisify } from 'node:util' +import { expect, it } from 'vitest' +import { windowsPackagingSummary } from '../scripts/windows-packaging-summary.mjs' + +it('separates workflow identity, requested source, and resolved build version', () => { + const summary = windowsPackagingSummary({ + PACKAGE_SOURCE_REF: 'feature/windows', PACKAGE_SOURCE_SHA: 'source-sha', + GITHUB_WORKFLOW_REF: 'repo/.github/workflows/windows-package.yml@refs/heads/master', + GITHUB_WORKFLOW_SHA: 'workflow-sha', PACKAGE_INPUT_VERSION_MODE: 'default', + PACKAGE_VERSION: '0.2.2-rc.1.20261110.1.1', PACKAGE_SIGNING: 'signed', + DSH_PACKAGING_PRESET: 'test', DSH_DESKTOP_UPDATE_CHANNEL: 'nightly', + }) + expect(summary).toContain('| 源码 ref | feature/windows |') + expect(summary).toContain('| 检出源码 SHA | source-sha |') + expect(summary).toContain('| 工作流 SHA | workflow-sha |') + expect(summary).toContain('| 版本模式 | default |') + expect(summary).toContain('| 解析后的版本号 | 0.2.2-rc.1.20261110.1.1 |') + expect(summary).toContain('不代表构建、签名或发布成功') +}) + +it('retains unresolved and machine-default labels after an earlier failure', () => { + const summary = windowsPackagingSummary({ PACKAGE_SOURCE_REF: 'bad-source' }) + expect(summary).toContain('| 检出源码 SHA | 尚未取得 |') + expect(summary).toContain('| 解析后的版本号 | 尚未解析成功 |') + expect(summary).toContain('使用机器默认值(本摘要不读取)') + expect(summary).toContain('| 缓存命名空间 | 共享缓存 |') +}) + +it('escapes input markup and excludes unrelated environment and private configuration', () => { + const summary = windowsPackagingSummary({ + PACKAGE_SOURCE_REF: '