跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

提交记录

修复 Windows 原生自检取证目录和源码收集环境并增加安全只读签名诊断

作者
Lee-xeo
时间
2026/11/09 19:23
提交
fb4d227
上一个
a7fb3dc
这个版本的全部文件
修改.github/workflows/windows-build.yml+16 −3看文件
@@ -60,7 +60,19 @@ jobs:
6060 mingw-w64-ucrt-x86_64-ninja
6161 mingw-w64-ucrt-x86_64-python
6262 mingw-w64-ucrt-x86_64-pkgconf
63删除: - uses: actions/cache@v4
63新增: - uses: actions/cache/restore@v4
64新增: id: qemu_cache
65新增: with:
66新增: path: _output/windows-deps
67新增: key: cage-windows-deps-${{ hashFiles('packaging/windows/dependencies.json', 'patches/qemu/**', 'scripts/build-qemu-windows.*') }}
68新增: restore-keys: cage-windows-deps-
69新增: - name: Build and verify QEMU runtime before application acceptance
70新增: env:
71新增: CAGE_MSYS2_ROOT: ${{ steps.msys2.outputs.msys2-location }}
72新增: run: ./scripts/build-qemu-windows.ps1
73新增: - name: Preserve only the completed verified runtime cache
74新增: if: steps.qemu_cache.outputs.cache-hit != 'true'
75新增: uses: actions/cache/save@v4
6476 with:
6577 path: _output/windows-deps
6678 key: cage-windows-deps-${{ hashFiles('packaging/windows/dependencies.json', 'patches/qemu/**', 'scripts/build-qemu-windows.*') }}
@@ -132,7 +144,8 @@ jobs:
132144 id: qemu_cache
133145 with:
134146 path: _output/windows-deps
135删除: key: cage-windows-deps-${{ hashFiles('packaging/windows/dependencies.json', 'patches/qemu/**', 'scripts/build-qemu-windows.*', 'scripts/bundle-qemu-sources.sh') }}
147新增: restore-keys: cage-windows-deps-
148新增: key: cage-windows-deps-${{ hashFiles('packaging/windows/dependencies.json', 'patches/qemu/**', 'scripts/build-qemu-windows.*') }}
136149 - name: Build and verify QEMU runtime and package identity
137150 id: qemu_build
138151 env:
@@ -148,7 +161,7 @@ jobs:
148161 uses: actions/cache/save@v4
149162 with:
150163 path: _output/windows-deps
151删除: key: cage-windows-deps-${{ hashFiles('packaging/windows/dependencies.json', 'patches/qemu/**', 'scripts/build-qemu-windows.*', 'scripts/bundle-qemu-sources.sh') }}
164新增: key: cage-windows-deps-${{ hashFiles('packaging/windows/dependencies.json', 'patches/qemu/**', 'scripts/build-qemu-windows.*') }}
152165 - uses: actions/cache/restore@v4
153166 id: qemu_sources
154167 with:
修改.github/workflows/windows-signing-check.yml+9 −2看文件
@@ -1,6 +1,12 @@
11name: Verify Windows cloud signing without a release
22on:
33 workflow_dispatch:
4新增: inputs:
5新增: mode:
6新增: description: Sign a disposable probe, or only read credential information without signing
7新增: type: choice
8新增: options: [sign, credential-info]
9新增: default: sign
410permissions:
511 contents: read
612concurrency:
@@ -24,7 +30,7 @@ jobs:
2430 with:
2531 distribution: temurin
2632 java-version: '21'
27删除: - name: Sign one disposable executable and verify Windows trust
33新增: - name: Run the selected signing verification or read-only diagnosis
2834 shell: pwsh
2935 env:
3036 CAGE_WINDOWS_SIGNING_PROVIDER: ${{ vars.CAGE_WINDOWS_SIGNING_PROVIDER }}
@@ -33,7 +39,8 @@ jobs:
3339 CAGE_ESIGNER_CREDENTIAL_ID: ${{ secrets.CAGE_ESIGNER_CREDENTIAL_ID }}
3440 CAGE_ESIGNER_CERTIFICATE_SERIAL: ${{ vars.CAGE_ESIGNER_CERTIFICATE_SERIAL }}
3541 CAGE_ESIGNER_TOTP_SECRET: ${{ secrets.CAGE_ESIGNER_TOTP_SECRET }}
36删除: run: ./scripts/check-windows-signing.ps1
42新增: CAGE_SIGNING_CHECK_MODE: ${{ inputs.mode }}
43新增: run: ./scripts/check-windows-signing.ps1 -Mode $env:CAGE_SIGNING_CHECK_MODE
3744 - name: Preserve verification facts only
3845 if: always()
3946 uses: actions/upload-artifact@v4
修改desktop/linux/test-smoke.mjs+17 −2看文件
@@ -133,9 +133,24 @@ try {
133133 console.error(error.message);
134134} finally {
135135 try {
136删除: const stopped = parseBackend(await execute(backend, ['prepare-update', '--json']));
136新增: const cleanupRun = await execute(backend, ['prepare-update', '--json']);
137新增: if (cleanupRun.code !== 0) {
138新增: // prepare-update returns only status/message. Never log desktop's
139新增: // entry JSON or arbitrary stdout, which can contain a session URL.
140新增: let message = '';
141新增: try {
142新增: const response = JSON.parse(cleanupRun.stdout);
143新增: if (typeof response.message === 'string') message = response.message.slice(0, 500);
144新增: } catch { /* Keep malformed or non-JSON output private. */ }
145新增: console.error(`Cleanup prepare-update failed (exit ${cleanupRun.code}, signal ${cleanupRun.signal || 'none'}): ${message}`);
146新增: }
147新增: const stopped = parseBackend(cleanupRun);
137148 clean = stopped.status === 'prepared';
138删除: } catch { /* Preserve the fixture until a remaining controller can be stopped. */ }
149新增: if (!clean) console.error(`Cleanup prepare-update returned ${stopped.status || 'unknown status'}.`);
150新增: } catch (error) {
151新增: console.error(`Cleanup could not confirm controller exit: ${error.message}`);
152新增: // Preserve the fixture until a remaining controller can be stopped.
153新增: }
139154 if (clean) await rm(root, { recursive: true, force: true });
140155 else { console.error(`Cleanup incomplete; isolated profile retained at ${root}`); result = 1; }
141156}
修改scripts/build-qemu-windows.ps1+1 −1看文件
@@ -14,7 +14,7 @@ $DependencyCache = [IO.Path]::GetFullPath($DependencyCache)
1414$OutputDirectory = [IO.Path]::GetFullPath($OutputDirectory)
1515$dependencies = Get-Content (Join-Path $repository 'packaging/windows/dependencies.json') -Raw | ConvertFrom-Json
1616$patchDirectory = Join-Path $repository 'patches/qemu'
17删除:$inputs = @((Join-Path $PSScriptRoot 'build-qemu-windows.sh'), (Join-Path $PSScriptRoot 'bundle-qemu-sources.sh'), $PSCommandPath) + @(Get-ChildItem $patchDirectory -Filter '*.patch' | Sort-Object Name | ForEach-Object FullName)
17新增:$inputs = @((Join-Path $PSScriptRoot 'build-qemu-windows.sh'), $PSCommandPath) + @(Get-ChildItem $patchDirectory -Filter '*.patch' | Sort-Object Name | ForEach-Object FullName)
1818$fingerprintText = $dependencies.qemuSource.hash + $dependencies.qemuKeycodemap.hash + (($inputs | ForEach-Object { (Get-FileHash $_ -Algorithm SHA256).Hash }) -join '')
1919$fingerprint = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($fingerprintText)))
2020$manifestPath = Join-Path $OutputDirectory 'cage-build.json'
修改scripts/bundle-qemu-sources.sh+5 −3看文件
@@ -4,7 +4,9 @@ set -euo pipefail
44repository=$(cygpath -u "$1")
55runtime=$(cygpath -u "$2")
66archive=$(cygpath -u "$3")
7删除:commit=$(node -p "JSON.parse(require('fs').readFileSync(process.argv[1])).qemuSource.commit" "$repository/packaging/windows/dependencies.json")
7新增:node_command=${CAGE_NODE:-node}
8新增:if [[ -n ${CAGE_NODE:-} ]]; then node_command=$(cygpath -u "$CAGE_NODE"); fi
9新增:commit=$("$node_command" -p "JSON.parse(require('fs').readFileSync(process.argv[1])).qemuSource.commit" "$repository/packaging/windows/dependencies.json")
810[[ $commit =~ ^[a-f0-9]{40}$ && -s "$runtime/build-source-packages.txt" ]] || { echo 'QEMU source/package identity is missing.' >&2; exit 1; }
911stage=$(mktemp -d)
1012trap 'rm -rf "$stage"' EXIT
@@ -30,8 +32,8 @@ if grep -Eq '^[-+U]' "$stage/source/firmware-revisions.txt"; then echo 'Firmware
3032cp "$runtime/build-source-packages.txt" "$runtime/build-packages.txt" "$runtime/cage-build.json" "$stage/source/cage/"
3133cp "$repository/scripts/build-qemu-windows.sh" "$repository/scripts/build-qemu-windows.ps1" "$repository/scripts/bundle-qemu-sources.sh" "$stage/source/cage/"
3234cp -R "$repository/patches/qemu" "$stage/source/cage/patches"
33删除:keymap_url=$(node -p "JSON.parse(require('fs').readFileSync(process.argv[1])).qemuKeycodemap.url" "$repository/packaging/windows/dependencies.json")
34删除:keymap_hash=$(node -p "JSON.parse(require('fs').readFileSync(process.argv[1])).qemuKeycodemap.hash" "$repository/packaging/windows/dependencies.json")
35新增:keymap_url=$("$node_command" -p "JSON.parse(require('fs').readFileSync(process.argv[1])).qemuKeycodemap.url" "$repository/packaging/windows/dependencies.json")
36新增:keymap_hash=$("$node_command" -p "JSON.parse(require('fs').readFileSync(process.argv[1])).qemuKeycodemap.hash" "$repository/packaging/windows/dependencies.json")
3537curl --fail --location --retry 3 -o "$stage/source/keycodemapdb.tar.gz" "$keymap_url"
3638printf '%s %s\n' "$keymap_hash" "$stage/source/keycodemapdb.tar.gz" | sha256sum -c -
3739while read -r base version; do
修改scripts/bundle-qemu-sources.test.mjs+2 −1看文件
@@ -18,13 +18,14 @@ test('source collector includes pinned firmware and authenticated package source
1818 await writeFile(join(repository,'patches/qemu/fixture.patch'),'fixture patch');
1919 const command=async(name,body)=>{const path=join(bin,name);await writeFile(path,'#!/bin/bash\nset -e\n'+body+'\n');await chmod(path,0o755)};
2020 await command('cygpath','printf "%s\\n" "$2"');
21新增: await command('node','echo "The collector must use the explicit CAGE_NODE path" >&2; exit 99');
2122 await command('git',`if [[ "$*" == *' init '* ]];then mkdir -p "\${@: -1}/.git";fi
2223 if [[ "$*" == *rev-parse* ]];then printf '${sha}\\n';fi
2324 if [[ "$*" == *'submodule update'* ]];then for ((i=1;i<=$#;i++));do if [[ "\${!i}" == -C ]];then j=$((i+1));q="\${!j}";fi;done;mkdir -p "$q/roms/seabios";echo 'firmware code' > "$q/roms/seabios/code.c";echo 'gitdir: private' > "$q/roms/seabios/.git";fi
2425 if [[ "$*" == *'submodule status'* ]];then printf ' ${sha} roms/seabios\\n';fi`);
2526 await command('curl',`while [[ $# -gt 0 ]];do if [[ "$1" == -o ]];then shift;destination=$1;fi;shift;done;printf '${content.replaceAll('\n','\\n')}' > "$destination"`);
2627 await command('pacman-key','printf "%s\\n" "$*" >> "$SOURCE_TEST_VERIFICATIONS"');
27删除: execFileSync('bash',[collector,repository,runtime,artifact],{env:{...process.env,PATH:bin+':'+process.env.PATH,SOURCE_TEST_VERIFICATIONS:join(root,'verified')},stdio:'pipe'});
28新增: execFileSync('bash',[collector,repository,runtime,artifact],{env:{...process.env,PATH:bin+':'+process.env.PATH,CAGE_NODE:process.execPath,SOURCE_TEST_VERIFICATIONS:join(root,'verified')},stdio:'pipe'});
2829 const listing=execFileSync('tar',['-tzf',artifact],{encoding:'utf8'});
2930 for(const path of ['source/firmware-revisions.txt','source/qemu/roms/seabios/code.c','source/packages/mingw-w64-fixture-1.2.3-1.src.tar.zst','source/cage/patches/fixture.patch','source/SHA256SUMS'])assert.ok(listing.includes(path),path);
3031 assert.ok(!listing.includes('/.git'));
修改scripts/check-windows-signing.ps1+9 −3看文件
@@ -1,14 +1,20 @@
11#requires -Version 7.0
2删除:# One real signature on a disposable PE file. No package, version or release writes.
2新增:# Explicit signing or read-only credential verification. No package, version or release writes.
33[CmdletBinding()]
4删除:param()
4新增:param([ValidateSet('sign', 'credential-info')][string]$Mode = 'sign')
55. (Join-Path $PSScriptRoot 'windows-common.ps1')
66if (-not $IsWindows) { throw 'This verification requires Windows trust APIs.' }
77if ($env:GITHUB_ACTIONS -ne 'true' -or $env:GITHUB_EVENT_NAME -ne 'workflow_dispatch' -or
8删除: $env:GITHUB_REPOSITORY -ne 'Lee-xeo/Claude-Cage' -or $env:GITHUB_REF -ne 'refs/heads/main') {
8新增: $env:GITHUB_REPOSITORY -ne 'Lee-xeo/Claude-Cage' -or
9新增: $env:GITHUB_REF -ne 'refs/heads/main') {
910 throw 'Run the explicit main-branch signing verification workflow.'
1011}
1112if ($env:CAGE_WINDOWS_SIGNING_PROVIDER -ne 'esigner') { throw 'Select esigner for this verification.' }
13新增:if ($Mode -eq 'credential-info') {
14新增: try { Invoke-BuildTool 'node' @((Join-Path $PSScriptRoot 'esigner.mjs'), 'diagnose') }
15新增: finally { Remove-Item Env:CAGE_ESIGNER_PASSWORD, Env:CAGE_ESIGNER_TOTP_SECRET -ErrorAction SilentlyContinue }
16新增: return
17新增:}
1218foreach ($name in @('CAGE_ESIGNER_USERNAME', 'CAGE_ESIGNER_PASSWORD', 'CAGE_ESIGNER_CREDENTIAL_ID', 'CAGE_ESIGNER_CERTIFICATE_SERIAL', 'CAGE_ESIGNER_TOTP_SECRET')) {
1319 if (-not [Environment]::GetEnvironmentVariable($name)) { throw "Missing cage-release setting: $name" }
1420}
修改scripts/ci-windows-build.ps1+1 −0看文件
@@ -49,6 +49,7 @@ try {
4949 $env:PATH = (Join-Path $env:RUNNER_TEMP 'nsis-3.13') + [IO.Path]::PathSeparator + $env:PATH
5050 Invoke-BuildTool 'node' @('scripts/check-version.mjs')
5151 Invoke-BuildTool 'node' @('--test', 'internal/cage/browser-clipboard.test.mjs', 'scripts/windows-native-bridge.test.mjs')
52新增: Invoke-BuildTool (Get-BuildCommand @('pwsh.exe', 'pwsh')) @('-NoProfile', '-NonInteractive', '-File', 'scripts/windows-workbench-smoke.test.ps1')
5253 $windowsPowerShell = Join-Path ([Environment]::SystemDirectory) 'WindowsPowerShell/v1.0/powershell.exe'
5354 & (Join-Path $PSScriptRoot 'test-windows-installation-files.ps1') -HelperShell $windowsPowerShell
5455 if ($Release) {
修改scripts/esigner.mjs+18 −5看文件
@@ -185,18 +185,29 @@ export async function invokeSigning({ invoke, outputPath, pause = ms => new Prom
185185 }
186186}
187187
188新增:// Diagnostic output is an allowlist. Never return vendor JSON, identities,
189新增:// certificate data, tokens or free-form error messages to CI logs.
190新增:export function credentialDiagnostic(error) {
191新增: if (!error) return { operation: 'credential_info', success: true, stage: 'csc-credential-info', exitCode: 0, error: '' };
192新增: const match = /^CodeSignTool failed \(exit ([0-9]{1,3})\)/.exec(error.message);
193新增: const exitCode = match && Number(match[1]) <= 255 ? Number(match[1]) : null;
194新增: const code = /"error"\s*:\s*"([a-z_]+)"/.exec(error.message)?.[1];
195新增: const allowed = ['server_error', 'invalid_grant', 'invalid_client', 'access_denied', 'unauthorized', 'invalid_request'];
196新增: return { operation: 'credential_info', success: false, stage: exitCode === 1 ? 'oauth-token' : exitCode === 2 ? 'csc-credential-info' : 'client', exitCode, error: allowed.includes(code) ? code : 'unclassified' };
197新增:}
198新增:
188199async function main(argv) {
189200 const [command, input, flag, destination] = argv;
190201 if (command === 'install' && argv.length === 1) { console.log(`Verified CodeSignTool ${pin.version}: ${await installTool()}`); return; }
191删除: if (!['info', 'sign'].includes(command) || (command === 'info' && argv.length !== 1) ||
202新增: if (!['info', 'diagnose', 'sign'].includes(command) || (['info', 'diagnose'].includes(command) && argv.length !== 1) ||
192203 (command === 'sign' && (argv.length !== 4 || flag !== '--output-dir'))) {
193删除: throw new Error('Usage: node scripts/esigner.mjs install | info | sign INPUT.exe --output-dir DIRECTORY');
204新增: throw new Error('Usage: node scripts/esigner.mjs install | info | diagnose | sign INPUT.exe --output-dir DIRECTORY');
194205 }
195206 if (command === 'sign') await assertWindowsExecutable(resolve(input));
196207 const directory = await installTool();
197208 const auth = await credentials();
198209 if (command === 'sign' && !auth.totp && !process.stdin.isTTY) throw new Error('Non-interactive signing requires CAGE_ESIGNER_TOTP_SECRET.');
199删除: const args = [command === 'info' ? 'credential_info' : 'sign', `-username=${auth.username}`, `-password=${auth.password}`, `-credential_id=${auth.credential}`];
210新增: const args = [command === 'sign' ? 'sign' : 'credential_info', `-username=${auth.username}`, `-password=${auth.password}`, `-credential_id=${auth.credential}`];
200211 let staged, output, vendor;
201212 try {
202213 if (command === 'sign') {
@@ -219,13 +230,15 @@ async function main(argv) {
219230 if (!bytes.length || hash(bytes) === hash(await readFile(resolve(input)))) throw new Error('CodeSignTool did not produce a changed signed file.');
220231 await copyFile(signed, output, (await import('node:fs')).constants.COPYFILE_EXCL);
221232 console.log(`Signed copy: ${output}\nWindows trust and publisher verification are still required.`);
222删除: } else console.log(result.trim());
233新增: } else if (command === 'diagnose') console.log(JSON.stringify(credentialDiagnostic()));
234新增: else console.log(result.trim());
223235 } finally { if (staged) await rm(staged, { recursive: true, force: true }); }
224236}
225237
226238if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
227239 main(process.argv.slice(2)).catch(error => {
228删除: console.error(redact(error.message, secretNames.map(name => process.env[name])));
240新增: if (process.argv[2] === 'diagnose') console.error(JSON.stringify(credentialDiagnostic(error)));
241新增: else console.error(redact(error.message, secretNames.map(name => process.env[name])));
229242 process.exitCode = 1;
230243 });
231244}
修改scripts/esigner.test.mjs+14 −1看文件
@@ -5,13 +5,26 @@ import { join } from 'node:path';
55import { tmpdir } from 'node:os';
66import { fileURLToPath } from 'node:url';
77import { test } from 'node:test';
8删除:import { assertWindowsExecutable, invokeJava, invokeSigning, javaArgument, prepareVendorInput, redact, verifyTool } from './esigner.mjs';
8新增:import { assertWindowsExecutable, credentialDiagnostic, invokeJava, invokeSigning, javaArgument, prepareVendorInput, redact, verifyTool } from './esigner.mjs';
99
1010test('Java arguments reject line injection and redact overlapping secrets', () => {
1111 for (const value of ['line\nbreak', 'line\rbreak', 'a\0b']) assert.throws(() => javaArgument(value));
1212 assert.equal(redact('secret-long and secret', ['secret', 'secret-long']), '[redacted] and [redacted]');
1313});
1414
15新增:test('read-only credential diagnosis emits only fixed stage, exit and error classifications', () => {
16新增: assert.deepEqual(credentialDiagnostic(), { operation: 'credential_info', success: true, stage: 'csc-credential-info', exitCode: 0, error: '' });
17新增: for (const [code, stage] of [[1, 'oauth-token'], [2, 'csc-credential-info'], [3, 'client']]) {
18新增: const result = credentialDiagnostic(new Error(`CodeSignTool failed (exit ${code}). Error: {"error":"server_error","token":"private-token","username":"private-user","credential_id":"private-id"}`));
19新增: assert.deepEqual(result, { operation: 'credential_info', success: false, stage, exitCode: code, error: 'server_error' });
20新增: assert.ok(!JSON.stringify(result).includes('private'));
21新增: }
22新增: const unknown = credentialDiagnostic(new Error('private-user private-id private-token {"error":"private_password"}'));
23新增: assert.equal(unknown.error, 'unclassified');
24新增: assert.equal(unknown.exitCode, null);
25新增: assert.ok(!JSON.stringify(unknown).includes('private'));
26新增:});
27新增:
1528test('signing retries only declared server errors without output and remains bounded', async t => {
1629 const root = await mkdtemp(join(tmpdir(), 'cage-sign-retry-'));
1730 t.after(() => rm(root, { recursive: true, force: true }));
修改scripts/prepare-qemu-release.ps1+3 −2看文件
@@ -24,12 +24,13 @@ if ((Test-Path -LiteralPath $record) -and (Test-Path -LiteralPath $archive)) {
2424 return
2525}
2626New-Item -ItemType Directory -Path $directory -Force | Out-Null
27删除:$savedMsystem, $savedChere = $env:MSYSTEM, $env:CHERE_INVOKING
27新增:$savedMsystem, $savedChere, $savedNode = $env:MSYSTEM, $env:CHERE_INVOKING, $env:CAGE_NODE
2828try {
2929 $env:MSYSTEM = 'UCRT64'; $env:CHERE_INVOKING = '1'
30新增: $env:CAGE_NODE = Get-BuildCommand @('node.exe', 'node')
3031 Invoke-BuildTool (Join-Path $MsysDirectory 'usr/bin/bash.exe') @('-l',
3132 (Join-Path $PSScriptRoot 'bundle-qemu-sources.sh'), $repository, $runtime, $archive)
32删除:} finally { $env:MSYSTEM = $savedMsystem; $env:CHERE_INVOKING = $savedChere }
33新增:} finally { $env:MSYSTEM = $savedMsystem; $env:CHERE_INVOKING = $savedChere; $env:CAGE_NODE = $savedNode }
3334$identity = @{ schema = 1; fingerprint = $runtimeIdentity.fingerprint; collectorHash = $collectorHash; sha256 = (Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash }
3435$identity | ConvertTo-Json | Set-Content -LiteralPath "$record.partial" -Encoding utf8
3536Move-Item -LiteralPath "$record.partial" -Destination $record -Force
修改scripts/windows-common.ps1+44 −7看文件
@@ -9,10 +9,52 @@ function Invoke-BuildTool {
99 if ($LASTEXITCODE -ne 0) { throw "$Tool failed with exit code $LASTEXITCODE" }
1010}
1111
12新增:function Get-WindowsWorkbenchTestBase {
13新增: if ($env:RUNNER_TEMP) { return [IO.Path]::GetFullPath($env:RUNNER_TEMP) }
14新增: return [IO.Path]::GetTempPath()
15新增:}
16新增:
17新增:function ConvertTo-SmokeSafeText {
18新增: param($Value)
19新增: if ($Value -isnot [string]) { return '' }
20新增: $text = [regex]::Replace($Value, 'https?://[^\s"''<>]+', {
21新增: param($match)
22新增: try { return ([Uri]$match.Value).GetLeftPart([UriPartial]::Path) }
23新增: catch { return '[URL omitted]' }
24新增: })
25新增: $text = $text -replace '[?#][^\s"''<>)]*', '[redacted]'
26新增: return $text.Substring(0, [Math]::Min(768, $text.Length))
27新增:}
28新增:
29新增:function Assert-WindowsWorkbenchReport {
30新增: param([int]$ExitCode, [string]$Report)
31新增: if (-not (Test-Path -LiteralPath $Report -PathType Leaf)) { throw "Cage workbench acceptance failed ($ExitCode). No smoke report: $Report" }
32新增: if ((Get-Item -LiteralPath $Report).Length -gt 65536) { throw 'Cage smoke report exceeds the bounded diagnostic size.' }
33新增: $result = Get-Content -LiteralPath $Report -Raw | ConvertFrom-Json -AsHashtable
34新增: $safe = @{ phase = ConvertTo-SmokeSafeText $result['phase']; nativeStatus = ConvertTo-SmokeSafeText $result['nativeStatus']; jsErrors = @() }
35新增: if ($result['page'] -is [System.Collections.IDictionary] -and $result['page']['errors']) {
36新增: $safe.jsErrors = @($result['page']['errors'] | Select-Object -First 8 | ForEach-Object {
37新增: if ($_ -isnot [System.Collections.IDictionary]) { return }
38新增: @{
39新增: type = ConvertTo-SmokeSafeText $_['type']
40新增: source = if ($_['source'] -is [string] -and $_['source'].StartsWith('/')) { ConvertTo-SmokeSafeText $_['source'] } else { '' }
41新增: message = ConvertTo-SmokeSafeText $_['message']
42新增: stack = @($_['stack'] | Select-Object -First 6 | ForEach-Object { ConvertTo-SmokeSafeText $_ })
43新增: }
44新增: })
45新增: }
46新增: # Log only these already-bounded fields, even when the process failed. Do
47新增: # not print launch entries, page URLs, account data or the raw report.
48新增: Write-Host ('Cage smoke diagnostic: ' + ($safe | ConvertTo-Json -Depth 6 -Compress))
49新增: if ($ExitCode -ne 0 -or $result['success'] -ne $true -or $result['nativeBridgeReady'] -ne $true) {
50新增: throw "Cage workbench/bridge acceptance failed ($ExitCode), phase $($safe.phase): $($safe.nativeStatus). Diagnostics: $Report"
51新增: }
52新增:}
53新增:
1254function Assert-WindowsWorkbench {
1355 param([Parameter(Mandatory)][string]$AppDirectory)
1456 if (-not $IsWindows) { throw 'Workbench acceptance requires Windows.' }
15删除: $testRoot = Join-Path ([IO.Path]::GetTempPath()) ('cage-build-ui-' + [guid]::NewGuid().ToString('N'))
57新增: $testRoot = Join-Path (Get-WindowsWorkbenchTestBase) ('cage-build-ui-' + [guid]::NewGuid().ToString('N'))
1658 New-Item -ItemType Directory -Path $testRoot -Force | Out-Null
1759 $report = Join-Path $testRoot 'smoke.json'
1860 $start = [Diagnostics.ProcessStartInfo]::new((Join-Path $AppDirectory 'Cage.exe'))
@@ -25,12 +67,7 @@ function Assert-WindowsWorkbench {
2567 $passed = $false
2668 try {
2769 if (-not $window.WaitForExit(180000)) { throw "Cage workbench acceptance timed out. Diagnostics retained at $testRoot" }
28删除: if ($window.ExitCode -ne 0 -or -not (Test-Path -LiteralPath $report)) { throw "Cage workbench acceptance failed. Diagnostics retained at $testRoot" }
29删除: $result = Get-Content -LiteralPath $report -Raw | ConvertFrom-Json
30删除: if ($result.success -ne $true -or $result.nativeBridgeReady -ne $true) {
31删除: $detail = if ($result.PSObject.Properties.Name -contains 'nativeStatus') { $result.nativeStatus } else { 'No native status was recorded.' }
32删除: throw "Cage workbench/bridge acceptance failed: $detail Diagnostics retained at $testRoot"
33删除: }
70新增: Assert-WindowsWorkbenchReport -ExitCode $window.ExitCode -Report $report
3471 $passed = $true
3572 } finally {
3673 if (-not $window.HasExited) { $window.Kill($true); $window.WaitForExit() }
新增scripts/windows-workbench-smoke.test.ps1+55 −0看文件
@@ -0,0 +1,55 @@
1新增:# Cross-platform regression for the real smoke-report and CI artifact contract.
2新增:. (Join-Path $PSScriptRoot 'windows-common.ps1')
3新增:$directory = Join-Path ([IO.Path]::GetTempPath()) ('cage-smoke-contract-' + [guid]::NewGuid().ToString('N'))
4新增:New-Item -ItemType Directory -Path $directory | Out-Null
5新增:$savedRunnerTemp = $env:RUNNER_TEMP
6新增:function Assert-SmokeContract([bool]$Condition, [string]$Message) { if (-not $Condition) { throw $Message } }
7新增:try {
8新增: $env:RUNNER_TEMP = Join-Path $directory 'runner-temp'
9新增: Assert-SmokeContract ((Get-WindowsWorkbenchTestBase) -eq [IO.Path]::GetFullPath($env:RUNNER_TEMP)) 'CI report directory ignores RUNNER_TEMP.'
10新增: Remove-Item Env:RUNNER_TEMP -ErrorAction SilentlyContinue
11新增: Assert-SmokeContract ((Get-WindowsWorkbenchTestBase) -eq [IO.Path]::GetTempPath()) 'Local report directory lost its OS temp fallback.'
12新增: $report = Join-Path $directory 'smoke.json'
13新增: $fixture = Join-Path $directory 'fixture.json'
14新增: $childScript = Join-Path $directory 'child.ps1'
15新增: [IO.File]::WriteAllText($childScript, '[IO.File]::Copy($args[0],$args[1],$true); exit 17')
16新增: @{
17新增: success = $false; nativeBridgeReady = $false; phase = 'loading_workbench'
18新增: nativeStatus = 'failed http://localhost:1234/?token=private-token#private-fragment'
19新增: entryJSON = 'private-entry'; pageURL = 'http://localhost:1234/#private-launch'
20新增: page = @{ text = 'private-page-body'; errors = @(
21新增: @{ type = 'module-load'; source = '/missing.js?session=private-query#private-fragment' },
22新增: @{ type = 'error'; source = '/main.js'; message = 'syntax error'; stack = @('at http://localhost:1234/main.js?session=private-query#private-fragment') }
23新增: ) }
24新增: } | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $fixture
25新增: $start = [Diagnostics.ProcessStartInfo]::new((Get-Process -Id $PID).Path)
26新增: $start.UseShellExecute = $false
27新增: foreach ($argument in @('-NoProfile','-NonInteractive','-File',$childScript,$fixture,$report)) { $start.ArgumentList.Add($argument) }
28新增: $child = [Diagnostics.Process]::Start($start)
29新增: try {
30新增: $child.WaitForExit()
31新增: Assert-SmokeContract ($child.ExitCode -eq 17) 'Failure fixture did not exit unsuccessfully.'
32新增: $failed = $false
33新增: $captured = & {
34新增: try { Assert-WindowsWorkbenchReport -ExitCode $child.ExitCode -Report $report }
35新增: catch { $script:observedFailure = $_.Exception.Message; Write-Output ('Rejected smoke: ' + $_.Exception.Message) }
36新增: } 6>&1
37新增: $text = ($captured | ForEach-Object { $_.ToString() }) -join "`n"
38新增: Assert-SmokeContract ($observedFailure -like '*loading_workbench*') 'Failure report was not parsed before rejecting its process exit.'
39新增: foreach ($expected in @('loading_workbench', 'module-load', '/missing.js', 'syntax error')) {
40新增: Assert-SmokeContract ($text.Contains($expected)) "Missing safe smoke evidence: $expected"
41新增: }
42新增: foreach ($private in @('private-token','private-fragment','private-query','private-entry','private-launch','private-page-body')) {
43新增: Assert-SmokeContract (-not $text.Contains($private)) "Private smoke field leaked: $private"
44新增: }
45新增: } finally { $child.Dispose() }
46新增: [IO.File]::WriteAllText($report, '{"success":true,"nativeBridgeReady":true}')
47新增: Assert-WindowsWorkbenchReport -ExitCode 0 -Report $report
48新增: $rejected = $false
49新增: try { Assert-WindowsWorkbenchReport -ExitCode 17 -Report $report } catch { $rejected = $true }
50新增: Assert-SmokeContract $rejected 'Nonzero child exit was accepted because its report said success.'
51新增: Write-Output 'PASS: RUNNER_TEMP/local selection, real failed child with existing diagnostic, safe evidence logging, and success/exit contract.'
52新增:} finally {
53新增: $env:RUNNER_TEMP = $savedRunnerTemp
54新增: Remove-Item -LiteralPath $directory -Recurse
55新增:}