fix(desktop): verify long Windows paths with PowerShell 7

This commit is contained in:
winewill committed 2026-11-10 14:43:34 +08:00
1 parent 0116485ca3
commit d28a0ed804
9 files changed
+44 -13

No files matched your search

@@ -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<string | undefined> {
async function probeWindowsInstallerToolchain(environment: NodeJS.ProcessEnv): Promise<DesktopToolchainProbeFailure[]> {
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
@@ -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,
@@ -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,
})
@@ -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)
+1 -1
View File
@@ -74,7 +74,7 @@ describe('Windows token signing', () => {
} else {
expect(options.env.DSH_DESKTOP_WINDOWS_TOKEN_PIN).toBeUndefined()
expect(options.env.DSH_DESKTOP_WINDOWS_KEY_CONTAINER).toBeUndefined()
if (command === 'powershell.exe') {
if (command === 'pwsh') {
const timestamped = readFileSync(options.env.DSH_RUNTIME_VERIFY_FILE!, 'utf8').endsWith(':timestamp')
if (!timestamped) expect(existsSync(join(stateDirectory, 'attempt.json'))).toBe(true)
callback(null, JSON.stringify({ status: mode === 'invalid-primary' ? 'NotTrusted' : 'Valid', timestamped, thumbprint: 'A'.repeat(40) }), '')
@@ -1,7 +1,7 @@
/** Parser fault checks; real-file equivalence is measured separately. */
import { it as test } from 'vitest'
import assert from 'node:assert/strict'
import { copyFile, mkdtemp, rm } from 'node:fs/promises'
import { copyFile, mkdir, mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { parseSignatureRows, inspectSignaturesBatched } from '../scripts/windows-signature-batch.mjs'
@@ -33,12 +33,18 @@ test('empty input launches no verifier and returns no rows', async () => {
assert.deepEqual(await inspectSignaturesBatched([]), [])
})
test.skipIf(process.platform !== 'win32')('Unicode paths retain the same Windows trust result as individual inspection', async (t) => {
test.skipIf(process.platform !== 'win32')('long Unicode paths retain the same Windows trust result as short paths', async (t) => {
const root = await mkdtemp(join(tmpdir(), 'signature-batch-'))
t.onTestFinished(() => rm(root, { recursive: true, force: true }))
const path = join(root, "验证 ' 文件.exe")
await copyFile(join(process.env.SystemRoot!, 'System32', 'cmd.exe'), path)
const expected = await inspectWindowsRuntimeSignature(path)
const shortPath = join(root, 'short.exe')
const directory = join(root, 'nested-'.repeat(15), 'nested-'.repeat(15))
await mkdir(directory, { recursive: true })
const path = join(directory, "验证 ' 文件.exe")
assert.ok(path.length > 260)
await copyFile(join(process.env.SystemRoot!, 'System32', 'cmd.exe'), shortPath)
await copyFile(shortPath, path)
const expected = await inspectWindowsRuntimeSignature(shortPath)
assert.deepEqual(await inspectWindowsRuntimeSignature(path), expected)
assert.equal(expected.status, 'Valid')
assert.deepEqual(await inspectSignaturesBatched([path]), [expected])
await signWindowsCode(root, {
@@ -30,8 +30,8 @@
en: 31ffd631dd215fc6
zh: ebfe8a3a64ed6e02
/windows-signing-and-runner-operations/signing-configuration:
en: 4b5548818375eb9a
zh: 8c975adbb1dca9c8
en: b38f6fbfcfd73f7a
zh: f3afb7053af7480b
/windows-signing-and-runner-operations/signing-and-timestamp-completion:
en: a8d23c931cafc236
zh: 28fd4860549cdc7b
+2
View File
@@ -77,6 +77,8 @@ For a new machine, keep the runner disabled while preparing and testing network
## Signing configuration
Windows packaging requires PowerShell 7 (`pwsh`) on `PATH`. The toolchain check verifies Authenticode support before building; runtime signature checks use this engine to handle paths longer than 260 characters.
The [machine preset configuration](../packaging/README.md#configuration-and-local-builds) selects public settings and the signing file. Without a preset, use the target dotenv file.
Fill in `.env.windows` with `DSH_DESKTOP_WINDOWS_CER_FILE` (public EV leaf certificate), `DSH_DESKTOP_WINDOWS_SIGNTOOL` (SafeNet-compatible SignTool), `DSH_DESKTOP_WINDOWS_KEY_CONTAINER` (matching private-key container), and `DSH_DESKTOP_WINDOWS_TOKEN_PIN` (Token Password). The private key stays on the USB token; keep the certificate and local credential file out of Git.
@@ -77,6 +77,8 @@ Windows CI 使用隔离的本地 fixture 运行 `pwsh -NoProfile -File apps/desk
## 签名配置
Windows 打包要求 `PATH` 中提供 PowerShell 7(`pwsh`)。工具链检查在构建前验证 Authenticode 支持;运行时签名检查使用此引擎处理超过 260 个字符的路径。
通过[机器 preset 配置](../packaging/README.zh.md#configuration-and-local-builds)选择公开设置与签名文件;不选择 preset 时使用目标 dotenv 文件。
在 `.env.windows` 中填写 `DSH_DESKTOP_WINDOWS_CER_FILE`(公开 EV 叶证书)、`DSH_DESKTOP_WINDOWS_SIGNTOOL`(SafeNet 兼容的 SignTool)、`DSH_DESKTOP_WINDOWS_KEY_CONTAINER`(匹配的私钥容器)和 `DSH_DESKTOP_WINDOWS_TOKEN_PIN`(Token Password)。私钥仍保留在 USB Token;不要把证书或本地凭据文件提交到 Git。