Compare commits

...
Author SHA1 Message Date
binaricat 50fbd51186 test(qa): capture actual Mac window using native Electron API 2026-11-22 03:08:11 +00:00
binaricat a94401170c test(qa): await real macOS renderer before native inspection 2026-11-22 03:05:06 +00:00
binaricat 197c00a2f0 test(qa): preserve normal macOS home for native launch control 2026-11-22 03:02:33 +00:00
binaricat 191b604d16 test(qa): bound native macOS automation teardown and preserve reviewed diagnostics 2026-11-22 02:55:36 +00:00
binaricat c81adf2c9c test(qa): verify official macOS native install launch and loopback SSH 2026-11-22 02:47:52 +00:00
binaricat dfb3e2a3a1 test(qa): package exact active-pointer fix and verify real Windows restart 2026-11-22 01:28:37 +00:00
binaricat 73473986a0 test(qa): require a positive GUI pointer seed without gating history durability 2026-11-22 01:10:36 +00:00
binaricat 506c1c1a1e test(qa): retain strict pointer failure and finish independent durability checks 2026-11-22 01:06:30 +00:00
binaricat eba0959bd3 test(qa): assert migrated records before normal chat navigation 2026-11-22 01:03:36 +00:00
binaricat e22743ac7d test(qa): scope host visibility and retain native PNG metadata 2026-11-22 01:00:23 +00:00
binaricat 82f778d7ef test(qa): serialize native readiness function without nested quoting 2026-11-22 00:57:32 +00:00
binaricat ba031d5658 test(qa): wait for real renderer and use portable executable directory 2026-11-22 00:55:03 +00:00
binaricat 32ade8984d test(qa): select the actual host editor save control 2026-11-22 00:51:52 +00:00
binaricat 20ae299359 test(qa): wait for native Chromium and isolate portable migration 2026-11-22 00:50:14 +00:00
binaricat afef08c28d test(qa): isolate Windows process preflight from installer diagnostics 2026-11-22 00:47:49 +00:00
binaricat f646178c27 test(qa): diagnose normal NSIS install and retain Windows evidence 2026-11-22 00:43:40 +00:00
binaricat d1b3038ec1 test(qa): verify installed Windows AI history migration 2026-11-22 00:39:25 +00:00
binaricat 2f7c55e014 test(qa): audit SFTP ranges and committed bytes and record real pause footage 2026-11-21 12:55:08 +00:00
binaricat d370f25858 test(qa): record sustained pause quiescence and allow source verification time 2026-11-21 12:48:41 +00:00
binaricat 44c616e262 fix(qa): observe automatic reconnect and preserve evidence before cleanup 2026-11-21 12:44:58 +00:00
binaricat 6dec3ecab6 test(qa): verify native terminal output and compare pinned official candidates 2026-11-21 12:41:27 +00:00
binaricat e5cc0127e7 test(qa): isolate SSH input and real SFTP pause-resume scenarios 2026-11-21 12:35:20 +00:00
binaricat 4fc1850299 test(qa): share explicit candidate pins and wait for production window readiness 2026-11-21 12:29:22 +00:00
binaricat 3c9dc8e5ce fix(qa): align runtime window lookup with native input lookup 2026-11-21 12:27:27 +00:00
binaricat f6ea7661d4 fix(qa): select the production native window by exact URL prefix 2026-11-21 12:27:10 +00:00
binaricat d86626fb52 fix(qa): assert the official production app protocol 2026-11-21 12:25:28 +00:00
binaricat 997dfa9e4f fix(qa): pass Xvfb authorization and expose reviewed launcher stderr 2026-11-21 12:23:45 +00:00
binaricat 6bcd9a3cea fix(qa): use a literal isolated job directory 2026-11-21 12:21:37 +00:00
binaricat 3650e23966 test(qa): probe official Linux candidate in isolated Draft PR 2026-11-21 12:20:11 +00:00
26 changed files with 2605 additions and 0 deletions

No files matched your search

+90
View File
@@ -0,0 +1,90 @@
name: QA official Linux candidate (incremental probe)
on:
pull_request:
branches: [main]
types: [opened, synchronize, reopened]
paths:
- .github/workflows/qa-official-linux.yml
- scripts/qa-official-linux/**
permissions:
contents: read
actions: read
concurrency:
group: qa-official-linux-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
official-package-probe:
if: >-
github.repository == 'binaricat/Netcatty' &&
github.event.pull_request.head.repo.full_name == 'binaricat/Netcatty' &&
github.event.pull_request.head.ref == 'qa/official-linux-a23868e' &&
github.event.pull_request.draft == true
strategy:
fail-fast: false
matrix:
include:
- candidate: a23868e
config: candidate.json
- candidate: 9d4e90b
config: candidate-9d4e90b.json
runs-on: ubuntu-22.04
timeout-minutes: 12
env:
QA_ROOT: /tmp/netcatty-official-qa-${{ matrix.candidate }}
QA_CANDIDATE: ${{ matrix.config }}
steps:
- name: Checkout QA harness without persisted credentials
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
ref: ${{ github.event.pull_request.head.sha }}
persist-credentials: false
- name: Node for QA harness only
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: '24.11.1'
- name: Stock desktop runtime dependencies
run: |
sudo apt-get update -qq
sudo apt-get install -y --no-install-recommends xvfb ffmpeg libgtk-3-0 libnss3 libasound2 libgbm1 libatk-bridge2.0-0 libxss1 libsecret-1-0
- name: Install isolated QA dependencies without lifecycle scripts
run: npm ci --prefix scripts/qa-official-linux --ignore-scripts --no-audit --no-fund
- name: Verify official run, artifact ZIP and deb; extract without installer scripts
id: provenance
env:
GH_TOKEN: ${{ github.token }}
run: node scripts/qa-official-linux/provenance.cjs
- name: Persistence through real official Electron restart
id: persistence
if: success()
run: xvfb-run -a -s '-screen 0 1440x1000x24 -nolisten tcp' node scripts/qa-official-linux/desktop.cjs persistence
- name: Real SSH disconnect and original-tab reconnect
id: ssh
if: always() && steps.provenance.outcome == 'success'
run: xvfb-run -a -s '-screen 0 1440x1000x24 -nolisten tcp' node scripts/qa-official-linux/desktop.cjs ssh
- name: Independent real SFTP pause, stable bytes, resume and SHA-256
id: sftp
if: always() && steps.provenance.outcome == 'success'
run: xvfb-run -a -s '-screen 0 1440x1000x24 -nolisten tcp' node scripts/qa-official-linux/desktop.cjs sftp
- name: Independent clipboard UI check (never gates reconnect)
if: always() && steps.provenance.outcome == 'success'
run: xvfb-run -a -s '-screen 0 1440x1000x24 -nolisten tcp' node scripts/qa-official-linux/desktop.cjs clipboard
- name: Independent new host filter compatibility and boundary checks
if: always() && steps.provenance.outcome == 'success' && matrix.candidate == '9d4e90b'
run: xvfb-run -a -s '-screen 0 1440x1000x24 -nolisten tcp' node scripts/qa-official-linux/desktop.cjs host-filter
- name: Record explicit scope
if: always()
run: |
echo 'Candidate ${{ matrix.candidate }}; exact official SHA/run/artifact/digests are recorded in provenance.json' >> "$GITHUB_STEP_SUMMARY"
echo 'Read independent persistence, ssh and sftp assertions.json reports and real screenshots; a failure in one scenario does not skip the others. Stock sandbox launch failures are failures, never feature passes. This is extracted-package execution, not system-install acceptance.' >> "$GITHUB_STEP_SUMMARY"
- name: Upload reviewed QA evidence (3 days)
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: official-linux-${{ matrix.candidate }}-qa-${{ github.run_id }}
path: /tmp/netcatty-official-qa-${{ matrix.candidate }}/evidence/
retention-days: 3
if-no-files-found: warn
+74
View File
@@ -0,0 +1,74 @@
name: QA official macOS native launch and SSH
on:
pull_request:
branches: [main]
types: [opened, synchronize, reopened]
paths:
- .github/workflows/qa-official-macos.yml
- scripts/qa-official-macos/**
permissions:
contents: read
actions: read
concurrency:
group: qa-official-macos-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
official-macos-smoke:
if: >-
github.repository == 'binaricat/Netcatty' &&
github.event.pull_request.head.repo.full_name == 'binaricat/Netcatty' &&
github.event.pull_request.head.ref == 'qa/official-linux-a23868e' &&
github.event.pull_request.draft == true
strategy:
fail-fast: false
matrix:
include:
- runner: macos-26
arch: arm64
- runner: macos-15-intel
arch: x64
runs-on: ${{ matrix.runner }}
timeout-minutes: 15
env:
QA_ROOT: '${{ github.workspace }}/.qa-macos-${{ matrix.arch }}'
QA_ARCH: ${{ matrix.arch }}
QA_RUNNER: ${{ matrix.runner }}
QA_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
steps:
- name: Checkout exact authorized QA head without persisted credentials
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
ref: ${{ github.event.pull_request.head.sha }}
persist-credentials: false
- name: Native Node for isolated QA harness
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: '24.11.1'
architecture: ${{ matrix.arch }}
- name: Install only QA dependencies without lifecycle scripts or browsers
run: npm ci --prefix scripts/qa-official-macos --ignore-scripts --no-audit --no-fund
- name: Verify exact successful official push artifact and archive digest
env:
GH_TOKEN: ${{ github.token }}
run: node scripts/qa-official-macos/provenance.cjs
- name: Verify DMG, copy read-only mounted app, require Developer ID and notarized Gatekeeper acceptance
run: node scripts/qa-official-macos/verify-install.cjs
- name: Actual native first launch and real GUI SSH roundtrip
run: node scripts/qa-official-macos/desktop.cjs
- name: Record exact scope
if: always()
run: |
echo 'Read provenance.json, verification.json and assertions.json individually. DMG integrity is separate from the inner APP signature/ticket/Gatekeeper result. OS blockers are failures, never bypassed.' >> "$GITHUB_STEP_SUMMARY"
echo 'Exact official 9d4e90b candidate only, standard hosted native architecture, fresh synthetic profile, loopback SSH/DevTools. No Finder-quarantine, LAN, updater, personal-device or final merged revision coverage.' >> "$GITHUB_STEP_SUMMARY"
- name: Retain per-architecture reviewed logs, assertions and actual native PNGs (3 days)
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: qa-macos-${{ matrix.arch }}-9d4e90b-${{ github.run_id }}
path: '${{ env.QA_ROOT }}/evidence/'
retention-days: 3
if-no-files-found: warn
+165
View File
@@ -0,0 +1,165 @@
name: QA official Windows install and AI history
on:
pull_request:
branches: [main]
types: [opened, synchronize, reopened]
paths:
- .github/workflows/qa-official-windows.yml
- scripts/qa-official-windows/**
permissions:
contents: read
actions: read
concurrency:
group: qa-official-windows-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
installed-windows-history:
if: >-
github.repository == 'binaricat/Netcatty' &&
github.event.pull_request.head.repo.full_name == 'binaricat/Netcatty' &&
github.event.pull_request.head.ref == 'qa/official-linux-a23868e' &&
github.event.pull_request.draft == true
runs-on: windows-2022
strategy:
fail-fast: false
matrix:
mode: [nsis, portable]
timeout-minutes: 18
env:
QA_ROOT: '${{ github.workspace }}\.qa-win-runtime'
QA_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
QA_MODE: ${{ matrix.mode }}
steps:
- name: Checkout only the authorized QA head without saved credentials
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
ref: ${{ github.event.pull_request.head.sha }}
persist-credentials: false
- name: Node for QA harness
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: '24.11.1'
- name: Install only QA dependencies without lifecycle scripts or browsers
run: npm ci --prefix scripts/qa-official-windows --ignore-scripts --no-audit --no-fund
- name: Verify released installer and exact official Windows artifact
env:
GH_TOKEN: ${{ github.token }}
run: node scripts/qa-official-windows/provenance.cjs
- name: Real installed GUI baseline, replacement, migration and restart
run: node scripts/qa-official-windows/desktop.cjs
- name: Record acceptance scope
if: always()
shell: pwsh
run: |
'Read assertions.json for individual outcomes, provenance.json for hashes, and actual native renderer PNGs. A failed launcher or harness is not a migration pass. The candidate has a 0.0.0-sha version; this is not released automatic-updater acceptance.' >> $env:GITHUB_STEP_SUMMARY
'Standard ephemeral windows-2022 runner, normal per-user official NSIS, synthetic data, same isolated profile and app origin, deterministic loopback model only; no security changes. Linux evidence remains in its earlier independent workflow.' >> $env:GITHUB_STEP_SUMMARY
- name: Upload reviewed assertions, installer logs and native renderer PNGs (3 days)
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: qa-windows-${{ matrix.mode }}-9d4e90b-${{ github.event.pull_request.head.sha }}
path: '${{ env.QA_ROOT }}\evidence\'
retention-days: 3
if-no-files-found: warn
fixed-windows-package:
name: Build exact 4516d3a Windows QA NSIS (unsigned, never publish)
if: >-
github.repository == 'binaricat/Netcatty' &&
github.event.pull_request.head.repo.full_name == 'binaricat/Netcatty' &&
github.event.pull_request.head.ref == 'qa/official-linux-a23868e' &&
github.event.pull_request.draft == true
runs-on: windows-2022
timeout-minutes: 35
env:
QA_FIX_SOURCE: '${{ github.workspace }}\fixed-source'
QA_BUILD_OUTPUT: '${{ github.workspace }}\qa-fixed-package'
QA_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
outputs:
installer_sha: ${{ steps.build.outputs.installer_sha }}
artifact_id: ${{ steps.package.outputs.artifact-id }}
artifact_digest: ${{ steps.package.outputs.artifact-digest }}
steps:
- name: Checkout authorized QA harness without saved credentials
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
ref: ${{ github.event.pull_request.head.sha }}
persist-credentials: false
- name: Separate exact trusted same-repository fix checkout
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
repository: binaricat/Netcatty
ref: 4516d3aed7cb54862dabd53abb56a7f90fba3212
path: fixed-source
persist-credentials: false
- name: Node 22 for repository Windows packaging conventions
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: '22.21.1'
- name: Build real NSIS with stock MSVC and existing pack:win-x64
id: build
run: node scripts/qa-official-windows/build-fixed.cjs
- name: Retain exact QA installer, build provenance and reviewed logs (3 days)
id: package
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: qa-fixed-windows-4516d3a-${{ github.run_id }}
path: '${{ env.QA_BUILD_OUTPUT }}\'
retention-days: 3
if-no-files-found: warn
fixed-installed-windows-history:
name: Test real installed exact 4516d3a fix and positive pointer restart
needs: fixed-windows-package
if: >-
github.repository == 'binaricat/Netcatty' &&
github.event.pull_request.head.repo.full_name == 'binaricat/Netcatty' &&
github.event.pull_request.head.ref == 'qa/official-linux-a23868e' &&
github.event.pull_request.draft == true
runs-on: windows-2022
timeout-minutes: 15
env:
QA_ROOT: '${{ github.workspace }}\.qa-fixed-win-runtime'
QA_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
QA_MODE: nsis
QA_CANDIDATE: fixed-candidate.json
QA_FIXED_ARTIFACT: '${{ github.workspace }}\qa-fixed-input'
QA_EXPECTED_INSTALLER_SHA: ${{ needs.fixed-windows-package.outputs.installer_sha }}
QA_BUILD_ARTIFACT_ID: ${{ needs.fixed-windows-package.outputs.artifact_id }}
QA_BUILD_ARTIFACT_DIGEST: ${{ needs.fixed-windows-package.outputs.artifact_digest }}
steps:
- name: Checkout same QA harness without persisted credentials
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
ref: ${{ github.event.pull_request.head.sha }}
persist-credentials: false
- name: Node for actual native application harness
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: '24.11.1'
- name: Retrieve only this run's exact SHA QA package
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
name: qa-fixed-windows-4516d3a-${{ github.run_id }}
path: '${{ env.QA_FIXED_ARTIFACT }}'
- name: Install QA dependencies without scripts or browsers
run: npm ci --prefix scripts/qa-official-windows --ignore-scripts --no-audit --no-fund
- name: Verify same-run package SHA and official v1.1.90 baseline
env:
GH_TOKEN: ${{ github.token }}
run: node scripts/qa-official-windows/provenance-fixed.cjs
- name: Real normal NSIS replacement, UI history, appended reply and strict restart
run: node scripts/qa-official-windows/desktop.cjs
- name: Retain exact fix assertions and actual native PNGs (3 days)
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: qa-fixed-nsis-history-4516d3a-${{ github.event.pull_request.head.sha }}
path: '${{ env.QA_ROOT }}\evidence\'
retention-days: 3
if-no-files-found: warn
+76
View File
@@ -0,0 +1,76 @@
# Official Linux package QA
Temporary same-repository **Draft** PR only. Do not merge or publish this branch.
The workflow uses standard GitHub-hosted Ubuntu 22.04, read-only contents/actions
permissions, pinned official actions and checkout without persisted credentials.
No release workflow is dispatched.
Candidate metadata is explicit JSON. `candidate.json` pins a23868e, official run
44901156879 / artifact 14706239224. `candidate-9d4e90b.json` pins the independently
verified 9d4e90b run 44903060405 / artifact 14707251480. No floating latest or older
fallback is used. Each report records its full candidate SHA; never mix results.
The downloader checks repository/run/job/artifact metadata, archive SHA-256, deb
SHA-256 from the official build log, and amd64 architecture before extraction.
The official deb is extracted as the non-root runner. Installer scripts are
never executed because those scripts change SUID/AppArmor. This is extracted
package execution, not system-install acceptance. The application archive is
never patched. No --no-sandbox, sysctl, AppArmor, SUID or system security changes
are used. A normal launch failure is a failure with actual reviewed stderr.
The stock renderer preference is sandbox:false; the report states this honestly
and does not certify full renderer sandboxing.
Only the downloader receives the GitHub token. Electron gets an explicit
environment allowlist with fresh scenario-specific HOME/XDG/temp/profile paths.
Xvfb's temporary XAUTHORITY is passed through for the isolated display. No model
credentials, business data or production account is used. SSH/SFTP and DevTools
listen only on loopback. SSH credentials and host keys are generated per run.
Independent scenarios prevent one functional assertion from skipping another:
- `persistence`: real packaged launch, synthetic saved host visible in the vault,
graceful full process quit, restart with the same profile, same data visible.
- `ssh`: actual encrypted SSH2 loopback transport through the production UI.
Explicitly focus xterm's real input element, use native renderer input events,
assert server receive and real terminal echo, destroy the server connection,
reconnect the original tab, assert a second shell and stable tab ID. Accept the stock automatic reconnect
path or the visible manual reconnect path, recording which occurred. Receive
hex, focus and echo diagnostics distinguish harness input failures from an
established product regression.
- `sftp`: establish a separate real SSH connection and SFTP subsystem, then invoke
the production preload transfer API into the actual packaged native runtime.
This covers real transport/control behavior, not a certification of UI button
gestures. Capture transfer-center screenshots; pause mid-file; drain pending
reads and asynchronous checkpoint fingerprint work; retain every settling
sample; require at least 2.5 s of sustained actual server bytes and current
native-progress stability;
assert both are unchanged; resume and assert both grow; finish and compare
file length and SHA-256 to a deterministic 32 MiB payload. Record every READ
receive/reply with subsystem, unique handle, path, offset and logical range.
Separate the isolated payload handle from shared source-fingerprint reads;
permit only already-started payload ranges to drain after pause, forbid new
payload range starts before resume, and reject completion before resume.
Sample the production committed checkpoint, verify its actual local prefix
bytes against the source, and check the full staging-content hash remains
unchanged. Logical file length / preallocation is not counted as progress. No component fixture,
injected transfer implementation, or checkout-sourced bridge substitutes for
the official package's transfer code.
- `clipboard`: independently test real terminal Select All / Copy after proving
the command reached the server and the production terminal buffer. This
independent step cannot gate SSH reconnect or SFTP.
- `host-filter` (9d4e90b only): seed synthetic vault hosts and call the actual
packaged public/vault/hosts/list dispatcher and renderer bridge. Independently
check no-filter compatibility, empty/non-string filters, multiword keyword
matching, group path boundaries, case sensitivity and combined filters.
Evidence lives under scenario directories: `assertions.json`, reviewed
`electron-output.log`, `sftp-protocol.json` for the SFTP request/reply audit,
optional actual-display `sftp-pause-resume.mp4`, and real application screenshots named for each scene.
`provenance.json` at the artifact root identifies the official package. Raw
profiles and payloads are never uploaded. Save tested assertions and reviewed
evidence before cleanup; cleanup uses ssh2 end(), while only the intentional
transport-loss scene destroys the test server socket. Logs and assertion diagnostics are
checked for the ephemeral password, private keys, GitHub credentials and bearer
headers before logs/screenshots are published; matches withhold those files and
fail. Artifacts expire after three days. Read each assertion report: environment
and harness failures never count as feature passes.
@@ -0,0 +1,11 @@
{
"repository": "binaricat/Netcatty",
"repositoryId": 1111357457,
"sha": "9d4e90b3aa8fe0a52d1a58e8ea8e61bdd3865e28",
"run": 44903060405,
"artifact": 14707251480,
"name": "netcatty-linux-x64",
"zipSha256": "26c11c14501f58616600dc648a61dc36c256c558b86cc8fcff62bd0f38a9ade7",
"deb": "Netcatty-0.0.0-sha-9d4e90b-linux-amd64.deb",
"debSha256": "45781c366dcf9715eb681293e58e2ed47eba3cc9872a52cd2e1b8f3cf3de6ae0"
}
+11
View File
@@ -0,0 +1,11 @@
{
"repository": "binaricat/Netcatty",
"repositoryId": 1111357457,
"sha": "a23868ee88603d0182c5370fca851cb9d05d7f8f",
"run": 44901156879,
"artifact": 14706239224,
"name": "netcatty-linux-x64",
"zipSha256": "c6a3a18fd44592f6c8207aa5bbf82e6a034e7c15bf54e1633296f3ab0e0fb15c",
"deb": "Netcatty-0.0.0-sha-a23868e-linux-amd64.deb",
"debSha256": "d06498511d6298a3e0a46c3bed6626843ba3d9bed987b1d9a20c41874bc98929"
}
+607
View File
@@ -0,0 +1,607 @@
// Adapted from terminal-broadcast-ssh.live.cjs: packaged app, real SSH, native input.
const assert = require('node:assert/strict');
const crypto = require('node:crypto');
const fs = require('node:fs');
const net = require('node:net');
const path = require('node:path');
const { spawn } = require('node:child_process');
const { Server } = require('ssh2');
const loginPassword = crypto.randomBytes(24).toString('hex');
const root = path.resolve(process.env.QA_ROOT);
const scenario = process.argv[2] || 'persistence';
assert(['persistence', 'ssh', 'sftp', 'host-filter', 'clipboard'].includes(scenario));
const pinned = require(path.resolve(__dirname, process.env.QA_CANDIDATE || 'candidate.json'));
const evidence = path.join(root, 'evidence', scenario);
const executable = path.join(root, 'package/opt/Netcatty/netcatty');
const report = { candidate: pinned.sha, scenario, launcher: 'not_run', persistence: 'not_run', sshReconnect: 'not_run', sftpPauseResume: 'not_run', install: 'not_covered: extracted official deb; postinst never executed', sandbox: 'stock application configuration; no disabling switches or security changes' };
const logs = [];
const screenshots = new Map();
let videoChild;
const videoPath = path.join(root, 'sftp-pause-resume.mp4');
let child, cdp, mainCdp, fixture;
const profile = path.join(root, `profile-${scenario}`);
let watchdog;
const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const deadline = (ms) => Date.now() + ms;
function waitForExit(child, ms) {
if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);
return new Promise((resolve) => {
const onExit = () => { clearTimeout(timer); resolve(true); };
const timer = setTimeout(() => { child.off('exit', onExit); resolve(false); }, ms);
child.once('exit', onExit);
});
}
async function until(label, check, ms = 15000) {
const end = deadline(ms);
let last;
while (Date.now() < end) {
try {
const value = await check();
if (value) return value;
} catch (error) { last = error; }
await pause(100);
}
throw new Error(`Timed out waiting for ${label}${last ? `: ${last.message}` : ''}`);
}
async function freePort() {
const server = net.createServer();
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const port = server.address().port;
await new Promise((resolve) => server.close(resolve));
return port;
}
class Devtools {
constructor(url) {
this.ws = new WebSocket(url);
this.nextId = 0;
this.pending = new Map();
this.ws.addEventListener('message', (event) => {
const message = JSON.parse(event.data);
const item = this.pending.get(message.id);
if (!item) return;
this.pending.delete(message.id);
if (message.error) item.reject(new Error(message.error.message));
else item.resolve(message.result);
});
}
async connect() {
await new Promise((resolve, reject) => {
this.ws.addEventListener('open', resolve, { once: true });
this.ws.addEventListener('error', reject, { once: true });
});
}
send(method, params = {}, timeoutMs = 10000) {
const id = ++this.nextId;
return new Promise((resolve, reject) => {
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`CDP timeout: ${method}`)); }, timeoutMs);
this.pending.set(id, { resolve: value => { clearTimeout(timer); resolve(value); }, reject: error => { clearTimeout(timer); reject(error); } });
this.ws.send(JSON.stringify({ id, method, params }));
});
}
async eval(expression, timeoutMs = 10000) {
const result = await this.send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, timeoutMs);
if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
return result.result.value;
}
close() { this.ws.close(); }
}
async function clickPoint(cdp, { x, y }, button = 'left') {
await cdp.send('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button, clickCount: 1 });
await cdp.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button, clickCount: 1 });
}
async function clickElement(cdp, selector, index = 0, button = 'left') {
const point = await cdp.eval(`(() => {const items=[...document.querySelectorAll(${JSON.stringify(selector)})].filter(e=>{const r=e.getBoundingClientRect();return r.width>0&&r.height>0&&r.x>=0&&r.y>=0});const e=items[${index}];if(!e)throw new Error('Missing visible element: '+${JSON.stringify(selector)});const r=e.getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2}})()`);
await clickPoint(cdp, point, button);
}
async function clickText(cdp, label, selector = 'button') {
const point = await cdp.eval(`(() => {const e=[...document.querySelectorAll(${JSON.stringify(selector)})].find(x=>x.textContent.trim()===${JSON.stringify(label)}&&x.getBoundingClientRect().x>=0);if(!e)throw new Error('Missing button: '+${JSON.stringify(label)});const r=e.getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2}})()`);
await clickPoint(cdp, point);
}
async function insertText(mainCdp, value) {
await mainCdp.eval(`process.mainModule.require('electron').BrowserWindow.getAllWindows().find(w => w.webContents.getURL().startsWith('app://netcatty/index.html')).webContents.insertText(${JSON.stringify(value)})`);
}
async function key(mainCdp, code, type = 'keyDown') {
await mainCdp.eval(`process.mainModule.require('electron').BrowserWindow.getAllWindows().find(w => w.webContents.getURL().startsWith('app://netcatty/index.html')).webContents.sendInputEvent({type:${JSON.stringify(type)},keyCode:${JSON.stringify(code)}})`);
}
async function typeLine(mainCdp, value) {
for (const letter of value) await key(mainCdp, letter, 'char');
await key(mainCdp, 'Enter');
await key(mainCdp, 'Enter', 'keyUp');
}
async function terminalLine(cdp, mainCdp, value) {
await mainCdp.eval(`process.mainModule.require('electron').BrowserWindow.getAllWindows().find(w => w.webContents.getURL().startsWith('app://netcatty/index.html')).focus()`);
await until('connected terminal without overlay', () => cdp.eval(`!![...document.querySelectorAll('.xterm-helper-textarea')].find(e => e.closest('.xterm')?.getBoundingClientRect().width > 0) && !document.querySelector('[data-terminal-disconnected-dialog="true"]')`));
const focus = await cdp.eval(`(() => { const e = [...document.querySelectorAll('.xterm-helper-textarea')].find(e => e.closest('.xterm')?.getBoundingClientRect().width > 0); e.focus(); return {focused: document.activeElement === e, tag: document.activeElement.tagName, className: document.activeElement.className}; })()`);
assert.equal(focus.focused, true, 'Harness must focus actual xterm input');
report.inputFocus = focus;
await pause(350);
await cdp.send('Input.insertText', {text: value});
await cdp.send('Input.dispatchKeyEvent', {type: 'keyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13, text: '\r', unmodifiedText: '\r'});
await cdp.send('Input.dispatchKeyEvent', {type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13});
}
function startSshFixture() {
const { privateKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
privateKeyEncoding: { type: 'pkcs1', format: 'pem' },
publicKeyEncoding: { type: 'spki', format: 'pem' },
});
const sessions = [];
const clients = new Set();
const payload = Buffer.alloc(32 * 1024 * 1024);
for (let i = 0; i < payload.length; i++) payload[i] = i % 251;
const sftpStats = { reads: 0, bytesSent: 0, activeReads: 0 };
let nextReadAt = 0;
const protocol = {channels: [], opens: [], reads: [], closes: []};
let nextChannel = 0, nextHandle = 0, nextRead = 0;
const server = new Server({ hostKeys: [privateKey] }, (client) => {
clients.add(client);
client.on('error', () => {});
client.on('close', () => clients.delete(client));
const session = { receivedHex: '', sent: [], commands: [], prompts: 0, answers: [], pending: false, ready: false };
sessions.push(session);
client.on('close', () => { session.closedAt = Date.now(); });
client.on('authentication', (ctx) => {
if (ctx.method === 'password' && ctx.password === loginPassword) ctx.accept();
else ctx.reject(['password']);
});
client.on('ready', () => {
client.on('session', (accept) => {
const channel = accept();
channel.on('pty', (acceptPty) => acceptPty && acceptPty());
channel.on('sftp', acceptSftp => {
const remote = acceptSftp();
const channelId = ++nextChannel;
protocol.channels.push({id: channelId, openedAt: Date.now()});
const handles = new Map();
remote.on('error', () => {});
const attrs = { size: payload.length, mode: 0o100644, uid: 1, gid: 1, atime: 1700000000, mtime: 1700000000 };
remote.on('REALPATH', id => remote.name(id, [{ filename: '/', longname: '/', attrs: {...attrs, mode: 0o40755} }]));
for (const operation of ['STAT', 'LSTAT', 'FSTAT']) remote.on(operation, id => remote.attrs(id, attrs));
remote.on('OPEN', (id, filePath, flags) => {
const handle = `qa-handle-${++nextHandle}`;
const info = {handle, channelId, path: String(filePath), flags, openedAt: Date.now()};
handles.set(handle, info); protocol.opens.push(info);
remote.handle(id, Buffer.from(handle));
});
remote.on('CLOSE', (id, handleBytes) => {
const handle = handleBytes.toString();
const info = handles.get(handle); if (info) info.closedAt = Date.now();
protocol.closes.push({handle, channelId, at: Date.now()});
remote.status(id, 0);
});
remote.on('READ', (id, handleBytes, position, length) => {
const handle = handleBytes.toString();
const request = {sequence: ++nextRead, channelId, handle, path: handles.get(handle)?.path, offset: position, length, logicalRangeStart: Math.floor(position / 32768) * 32768, receivedAt: Date.now()};
protocol.reads.push(request);
sftpStats.reads++; sftpStats.activeReads++;
const due = Math.max(Date.now(), nextReadAt); nextReadAt = due + 20;
setTimeout(() => {
sftpStats.activeReads--;
if (remote.destroyed) { request.droppedAt = Date.now(); return; }
request.repliedAt = Date.now();
if (position >= payload.length) { request.replyBytes = 0; remote.status(id, 1); }
else { const bytes = payload.subarray(position, Math.min(payload.length, position + length)); request.replyBytes = bytes.length; remote.data(id, bytes); sftpStats.bytesSent += bytes.length; }
}, due - Date.now());
});
});
channel.on('shell', (acceptShell) => {
const stream = acceptShell();
session.ready = true; session.readyAt = Date.now();
stream.on('error', () => {});
let line = '';
stream.write('fixture$ ');
stream.on('data', (buffer) => {
session.receivedHex = (session.receivedHex + buffer.toString('hex')).slice(-8192);
for (const char of buffer.toString('utf8')) {
if (char === '\r' || char === '\n') {
if (!line && char === '\n') continue;
const submitted = line;
line = '';
if (session.pending) {
session.answers.push(submitted);
session.pending = false;
stream.write('\r\naccepted\r\nfixture$ ');
} else if (submitted === 'ask') {
session.commands.push(submitted);
session.prompts += 1;
session.pending = true;
stream.write('\r\nPassword:');
} else if (submitted) {
session.commands.push(submitted);
session.sent.push(`ran: ${submitted}`);
stream.write(`\r\nran: ${submitted}\r\nfixture$ `);
}
} else if (char === '\x7f') line = line.slice(0, -1);
else line += char;
}
});
});
});
});
});
return { server, sessions, clients, sftpStats, payload, protocol };
}
async function launch() {
const debugPort = await freePort();
const inspectPort = await freePort();
// Build an allowlist environment. No GitHub/Actions tokens, provider credentials,
// development server, NODE_OPTIONS, preload overrides or no-sandbox escape hatch.
const env = { PATH: process.env.PATH, DISPLAY: process.env.DISPLAY, XAUTHORITY: process.env.XAUTHORITY, LANG: 'en_US.UTF-8',
HOME: path.join(root, scenario, 'home'), XDG_CONFIG_HOME: path.join(root, scenario, 'config'),
XDG_CACHE_HOME: path.join(root, scenario, 'cache'), XDG_DATA_HOME: path.join(root, scenario, 'data'),
XDG_RUNTIME_DIR: path.join(root, scenario, 'runtime'), TMPDIR: path.join(root, scenario, 'tmp') };
for (const key of ['HOME', 'XDG_CONFIG_HOME', 'XDG_CACHE_HOME', 'XDG_DATA_HOME', 'XDG_RUNTIME_DIR', 'TMPDIR']) fs.mkdirSync(env[key], { recursive: true, mode: 0o700 });
child = spawn(executable, [`--user-data-dir=${profile}`, '--remote-debugging-address=127.0.0.1', `--remote-debugging-port=${debugPort}`, `--inspect=127.0.0.1:${inspectPort}`], { cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'] });
child.on('error', error => logs.push(`launcher: ${error.message}\n`));
for (const stream of [child.stdout, child.stderr]) stream.on('data', bytes => {
logs.push(bytes.toString());
if (logs.reduce((n, item) => n + item.length, 0) > 2_000_000) child.kill('SIGTERM');
});
const target = await until('official packaged renderer (stock sandbox required)', async () => {
assert.equal(child.exitCode, null, `Official Electron exited ${child.exitCode}; inspect stderr`);
const targets = await (await fetch(`http://127.0.0.1:${debugPort}/json/list`)).json();
return targets.find(item => item.type === 'page' && /index\.html/.test(item.url));
}, 30000);
const rendererUrl = new URL(target.url);
assert.equal(rendererUrl.protocol, 'app:', 'Official production renderer protocol');
assert.equal(rendererUrl.host, 'netcatty');
assert.equal(rendererUrl.pathname, '/index.html');
cdp = new Devtools(target.webSocketDebuggerUrl);
await cdp.connect();
await cdp.send('Page.bringToFront');
const inspector = await until('official Electron main inspector', async () => (await (await fetch(`http://127.0.0.1:${inspectPort}/json/list`)).json())[0]);
mainCdp = new Devtools(inspector.webSocketDebuggerUrl);
await mainCdp.connect();
report.rendererTarget = { id: target.id, url: target.url };
await until('production renderer DOM loaded', () => cdp.eval(`Boolean(document.querySelector('input[placeholder^="Find a host"]'))`));
report.nativeWindows = await mainCdp.eval(`process.mainModule.require('electron').BrowserWindow.getAllWindows().map(w => ({id: w.id, url: w.webContents.getURL()}))`);
await until('native production window URL committed', () => mainCdp.eval(`process.mainModule.require('electron').BrowserWindow.getAllWindows().some(w => w.webContents.getURL().startsWith('app://netcatty/index.html'))`));
const runtime = await mainCdp.eval(`(() => { const { app, BrowserWindow } = process.mainModule.require('electron'); const win = BrowserWindow.getAllWindows().find(w => w.webContents.getURL().startsWith('app://netcatty/index.html')); win.focus(); return { packaged: app.isPackaged, appPath: app.getAppPath(), profile: app.getPath('userData'), argv: process.argv, uid: process.getuid(), electron: process.versions.electron, rendererPreferences: { sandbox: win.webContents.getLastWebPreferences().sandbox, contextIsolation: win.webContents.getLastWebPreferences().contextIsolation, nodeIntegration: win.webContents.getLastWebPreferences().nodeIntegration } }; })()`);
assert.equal(runtime.packaged, true);
assert(runtime.appPath.endsWith('/resources/app.asar'));
assert.equal(runtime.profile, profile);
assert.notEqual(runtime.uid, 0);
assert(!runtime.argv.some(arg => /no-sandbox|disable.*sandbox/.test(arg)));
assert.equal(runtime.rendererPreferences.contextIsolation, true);
assert.equal(runtime.rendererPreferences.nodeIntegration, false);
// Report the stock app's sandbox:false renderer preference honestly. Do not
// rewrite its preferences or call this a full renderer-sandbox verification.
report.runtime = runtime;
report.launcher = 'pass';
await until('real vault UI', () => cdp.eval(`Boolean(document.querySelector('input[placeholder^="Find a host"]'))`));
}
async function capture(name) {
const result = await cdp.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false });
const bytes = Buffer.from(result.data, 'base64');
assert(bytes.length > 10000, 'Screenshot must contain a real application window');
screenshots.set(name, bytes);
}
async function assertEcho(expected) {
const sessionId = await cdp.eval(`document.querySelector('[data-tab-type="session"]').getAttribute('data-tab-id')`);
const params = {sessionId, scopedSessionIds: [sessionId], range: 'tail', maxLines: 80};
await until('server echo in production xterm reader', async () => {
const result = await mainCdp.eval(`process.mainModule.require(process.mainModule.require('electron').app.getAppPath() + '/electron/bridges/mcpServerBridge.cjs').dispatchBuiltinRpc('netcatty/readContext', ${JSON.stringify(params)})`);
report.terminalRead = result;
return result.ok === true && result.content.includes(expected);
}, 10000);
}
function disconnectFixtureClients(transportLoss = false) {
for (const client of fixture?.clients || []) {
// ssh2 Server.Connection exposes end(), not Client.destroy(). A socket
// destruction here is an actual transport loss, not a renderer status edit.
if (transportLoss) client._sock?.destroy();
else client.end();
}
}
async function quit() {
if (mainCdp) await mainCdp.eval(`process.mainModule.require('electron').app.quit()`).catch(() => {});
if (child && !await waitForExit(child, 5000)) {
child.kill('SIGTERM');
if (!await waitForExit(child, 3000)) { child.kill('SIGKILL'); await waitForExit(child, 2000); }
}
cdp?.close(); mainCdp?.close(); cdp = mainCdp = undefined;
}
function observeLocalStage(stagePath, checkpointBytes) {
const stats = fs.statSync(stagePath);
const actual = fs.readFileSync(stagePath);
const prefix = actual.subarray(0, checkpointBytes);
const committedPrefixSha256 = crypto.createHash('sha256').update(prefix).digest('hex');
const expectedPrefix = crypto.createHash('sha256').update(fixture.payload.subarray(0, checkpointBytes)).digest('hex');
return {logicalSize: stats.size, allocatedBytes: stats.blocks * 512, committedBytesRead: prefix.length, committedPrefixSha256, committedPrefixMatchesPayload: prefix.length === checkpointBytes && committedPrefixSha256 === expectedPrefix, fullStageSha256: crypto.createHash('sha256').update(actual).digest('hex')};
}
function startPauseRecording() {
report.recording = {path: 'sftp-pause-resume.mp4', startedAt: Date.now(), source: 'actual isolated Xvfb display; 5 fps; no generated frames'};
videoChild = spawn('/usr/bin/ffmpeg', ['-hide_banner', '-loglevel', 'error', '-y', '-f', 'x11grab', '-video_size', '1440x1000', '-framerate', '5', '-i', process.env.DISPLAY, '-c:v', 'libx264', '-preset', 'ultrafast', '-crf', '30', '-t', '120', videoPath], {env: {PATH: process.env.PATH, DISPLAY: process.env.DISPLAY, XAUTHORITY: process.env.XAUTHORITY}, stdio: ['ignore', 'ignore', 'pipe']});
videoChild.on('error', error => { report.recording.error = error.message; });
videoChild.stderr.on('data', bytes => logs.push('Recording: ' + bytes.toString()));
}
async function stopPauseRecording() {
if (!videoChild) return;
if (videoChild.exitCode === null && videoChild.signalCode === null) { videoChild.kill('SIGINT'); if (!await waitForExit(videoChild, 3000)) videoChild.kill('SIGKILL'); }
report.recording.endedAt = Date.now();
report.recording.exitCode = videoChild.exitCode;
videoChild = undefined;
}
async function verifySftp() {
report.sftpPauseResume = 'incomplete';
const sessionId = await cdp.eval(`document.querySelector('[data-tab-type="session"]').getAttribute('data-tab-id')`);
report.stage = 'SFTP open on existing production SSH session';
const sftpId = await cdp.eval(`window.netcatty.openSftpForSession(${JSON.stringify(sessionId)}, {reuseExactSessionOnly: true})`);
assert(sftpId, 'Real packaged app must open SFTP on the SSH transport');
const transferId = `qa-${crypto.randomUUID()}`;
const targetPath = path.join(root, `download-${scenario}.bin`);
const expectedSha256 = crypto.createHash('sha256').update(fixture.payload).digest('hex');
const stagePath = await mainCdp.eval(`process.mainModule.require(process.mainModule.require('electron').app.getAppPath() + '/electron/bridges/tempDirBridge.cjs').getTransferTempFilePath(${JSON.stringify(transferId)}, ${JSON.stringify(path.basename(targetPath))})`);
report.sftpStagePath = stagePath;
const options = { transferId, sourcePath: '/qa-payload.bin', targetPath, sourceType: 'sftp', targetType: 'local', sourceSftpId: sftpId, totalBytes: fixture.payload.length, resumable: true };
await cdp.eval(`(() => { window.__qaTransfer = {events: [], done: false}; window.netcatty.onGlobalSftpTransferEvent(e => { if (e.transferId === ${JSON.stringify(transferId)}) window.__qaTransfer.events.push({...e, qaObservedAt: Date.now()}); }); window.netcatty.startStreamTransfer(${JSON.stringify(options)}).then(result => { window.__qaTransfer.result = result; window.__qaTransfer.done = true; }, error => { window.__qaTransfer.error = String(error); window.__qaTransfer.done = true; }); return true; })()`);
const progress = () => cdp.eval(`window.__qaTransfer.events.filter(e => typeof e.transferred === 'number').at(-1)?.transferred || 0`);
report.stage = 'SFTP bytes and native progress';
await until('real SFTP bytes and native progress', async () => fixture.sftpStats.bytesSent > 262144 && await progress() > 131072, 30000);
await clickElement(cdp, 'button[aria-label="File Transfers"]');
await pause(200);
await capture('03-sftp-transferring.png');
const sharedChannel = fixture.protocol.channels[0].id;
const isolated = fixture.protocol.opens.filter(open => open.channelId !== sharedChannel && !open.closedAt && open.path === '/qa-payload.bin');
assert.equal(isolated.length, 1, 'Harness must identify one active isolated download handle');
const transferHandle = isolated[0].handle;
report.sftpHandleClassification = {sharedVerificationChannel: sharedChannel, isolatedDownload: {...isolated[0]}, basis: 'official concurrent-isolated download uses an isolated subsystem; fingerprint ranges use the shared browse subsystem; inspect sftp-protocol.json for every OPEN/READ/CLOSE'};
report.stage = 'SFTP pause';
const paused = await cdp.eval(`window.netcatty.pauseTransfer(${JSON.stringify(transferId)})`);
const pauseAcknowledgedAt = Date.now();
assert.equal(paused.success, true, paused.reason);
await until('native paused lifecycle event', () => cdp.eval(`window.__qaTransfer.events.some(e => e.type === 'paused')`));
report.sftpControl = {transferId, pauseAcknowledgedAt, paused};
const allowedRanges = new Set(fixture.protocol.reads.filter(read => read.handle === transferHandle && read.receivedAt <= pauseAcknowledgedAt).map(read => read.logicalRangeStart));
report.sftpControl.alreadyStartedDownloadRanges = [...allowedRanges].sort((a,b) => a-b);
report.sftpControl.inFlightDownloadReadsAtAcknowledgement = fixture.protocol.reads.filter(read => read.handle === transferHandle && read.receivedAt <= pauseAcknowledgedAt && (!read.repliedAt || read.repliedAt > pauseAcknowledgedAt)).map(read => read.sequence);
report.sftpPauseDrain = {startedAt: Date.now(), initial: {...fixture.sftpStats}, samples: []};
// A transient zero in-flight count is not quiescence: the production runtime
// may start checkpoint fingerprint reads asynchronously after acknowledging
// pause. Keep the complete settling timeline and require sustained stability.
let stable = [];
await until('sustained actual SFTP bytes and native progress stop', async () => {
const native = await cdp.eval(`({done: window.__qaTransfer.done, completed: window.__qaTransfer.events.some(e => e.type === 'completed'), checkpoint: window.__qaTransfer.events.filter(e => typeof e.checkpointBytes === 'number').at(-1)?.checkpointBytes})`);
assert.equal(native.done, false, 'Transfer resolved before explicit resume');
assert.equal(native.completed, false, 'Transfer completed before explicit resume');
const checkpointBytes = native.checkpoint ?? paused.checkpointBytes ?? 0;
const sample = {at: Date.now(), serverBytes: fixture.sftpStats.bytesSent, activeReads: fixture.sftpStats.activeReads, progressBytes: await progress(), checkpointBytes, done: native.done, local: observeLocalStage(stagePath, checkpointBytes)};
report.sftpPauseDrain.samples.push(sample);
const previous = stable.at(-1);
if (previous && (previous.serverBytes !== sample.serverBytes || previous.progressBytes !== sample.progressBytes || previous.checkpointBytes !== sample.checkpointBytes || previous.local.fullStageSha256 !== sample.local.fullStageSha256 || sample.activeReads !== 0)) stable = [];
stable.push(sample);
if (stable.length < 6) { await pause(500); return false; }
return sample.activeReads === 0 && sample.at - stable[0].at >= 2500;
}, 60000);
const samples = stable;
report.sftpPauseDrain.endedAt = Date.now();
report.sftpPauseDrain.final = {...fixture.sftpStats};
report.sftpPauseSamples = samples;
assert(samples[0].progressBytes > 0 && samples[0].progressBytes < fixture.payload.length, 'Pause must happen mid-transfer');
assert(samples.every(s => s.serverBytes === samples[0].serverBytes), 'Actual SFTP server bytes changed in stable pause window');
assert(samples.every(s => s.progressBytes === samples[0].progressBytes), 'Native progress changed in stable pause window');
const unexpectedRangeStarts = fixture.protocol.reads.filter(read => read.handle === transferHandle && read.receivedAt > pauseAcknowledgedAt && !allowedRanges.has(read.logicalRangeStart));
report.sftpRangePauseAssertions = {transferHandle, logicalChunkBytes: 32768, noNewLogicalDownloadRangeStarts: unexpectedRangeStarts.length === 0, unexpectedRangeStarts, noCompleteBeforeResume: true};
assert.equal(unexpectedRangeStarts.length, 0, 'New logical download ranges started after pause acknowledgement');
assert(samples.every(sample => sample.local.committedPrefixMatchesPayload), 'Committed checkpoint bytes do not match source payload');
assert(samples.every(sample => sample.local.fullStageSha256 === samples[0].local.fullStageSha256), 'Local file contents changed during stable pause');
assert(samples.every(sample => sample.checkpointBytes === samples[0].checkpointBytes), 'Committed checkpoint changed during stable pause');
await capture('04-sftp-paused.png');
startPauseRecording();
await pause(2000);
report.stage = 'SFTP resume';
const finalPausedNative = await cdp.eval(`({done: window.__qaTransfer.done, completed: window.__qaTransfer.events.some(e => e.type === 'completed')})`);
assert.equal(finalPausedNative.done, false, 'Transfer resolved before resume request');
assert.equal(finalPausedNative.completed, false, 'Transfer completed before resume request');
report.sftpControl.resumeRequestedAt = Date.now();
const lateNewRanges = fixture.protocol.reads.filter(read => read.handle === transferHandle && read.receivedAt > pauseAcknowledgedAt && read.receivedAt < report.sftpControl.resumeRequestedAt && !allowedRanges.has(read.logicalRangeStart));
const newIsolatedHandles = fixture.protocol.opens.filter(open => open.channelId !== sharedChannel && open.handle !== transferHandle && open.openedAt > pauseAcknowledgedAt && open.openedAt < report.sftpControl.resumeRequestedAt);
report.sftpRangePauseAssertions.unexpectedRangeStarts = lateNewRanges;
report.sftpRangePauseAssertions.unclassifiedNewIsolatedHandles = newIsolatedHandles;
assert.equal(lateNewRanges.length, 0, 'New logical download range started before explicit resume');
assert.equal(newIsolatedHandles.length, 0, 'Unclassified isolated file handle opened while paused');
const resumed = await cdp.eval(`window.netcatty.resumeTransfer(${JSON.stringify(transferId)})`, 60000);
report.sftpControl.resumed = resumed;
assert.equal(resumed.success, true, resumed.reason);
await until('server and progress resume', async () => fixture.sftpStats.bytesSent > samples[0].serverBytes && await progress() > samples[0].progressBytes, 15000);
await capture('05-sftp-resumed.png');
await pause(1500);
await stopPauseRecording();
await until('native transfer completes', () => cdp.eval(`window.__qaTransfer.done`), 90000);
const result = await cdp.eval(`window.__qaTransfer.result`);
assert(result && !result.error && !result.cancelled, JSON.stringify(result));
const actualSha256 = crypto.createHash('sha256').update(fs.readFileSync(targetPath)).digest('hex');
assert.equal(fs.statSync(targetPath).size, fixture.payload.length);
assert.equal(actualSha256, expectedSha256);
report.sftpPauseResume = 'pass';
report.sftp = { invocation: 'production preload API -> packaged native transfer runtime, actual loopback SSH2 SFTP; no substituted bridge', transferId, bytes: fixture.payload.length, paused, resumed, pauseSamples: samples, finalServer: fixture.sftpStats, expectedSha256, actualSha256, events: await cdp.eval(`window.__qaTransfer.events`) };
await capture('06-sftp-completed.png');
}
async function verifyHostFilters() {
report.hostFilters = {status: 'incomplete', cases: []};
const hosts = [
{id: 'web', label: 'QA WEB', hostname: '127.0.0.1', username: 'deploy', group: 'prod/web', tags: ['Nginx'], os: 'linux'},
{id: 'db', label: 'QA DB', hostname: '127.0.0.2', username: 'root', group: 'prod/db', tags: ['postgres'], os: 'linux'},
{id: 'old', label: 'QA OLD', hostname: '127.0.0.3', username: 'root', group: 'production-old', tags: [], os: 'linux'},
{id: 'prod-root', label: 'QA PROD ROOT', hostname: '127.0.0.4', username: 'ops', group: 'prod', tags: [], os: 'linux'},
{id: 'ungrouped', label: 'QA UNGROUPED', hostname: '127.0.0.5', username: 'ops', tags: [], os: 'linux'},
];
await cdp.eval(`localStorage.setItem('netcatty_hosts_v1', ${JSON.stringify(JSON.stringify(hosts))})`);
await cdp.send('Page.reload');
await until('synthetic filter host vault loaded', () => cdp.eval(`document.body.innerText.includes('QA UNGROUPED')`));
await capture('02-host-filter-vault.png');
const all = hosts.map(h => h.id).sort();
const cases = [
[{}, all],
[{query: ' ', group: ''}, all],
[{query: 123, group: null}, all],
[{query: 'WEB nginx'}, ['web']],
[{query: 'root DB'}, ['db']],
[{query: 'production'}, []],
[{group: 'prod'}, ['db', 'prod-root', 'web']],
[{group: 'prod/web'}, ['web']],
[{group: ' prod/ '}, ['db', 'prod-root', 'web']],
[{group: 'PROD'}, []],
[{group: 'prod', query: 'postgres'}, ['db']],
];
for (const [params, expected] of cases) {
const result = await mainCdp.eval(`process.mainModule.require(process.mainModule.require('electron').app.getAppPath() + '/electron/bridges/mcpServerBridge.cjs').dispatchBuiltinRpc('public/vault/hosts/list', ${JSON.stringify(params)})`);
assert.equal(result.ok, true, JSON.stringify(result));
const ids = result.hosts.map(h => h.id).sort();
report.hostFilters.cases.push({params, ids, expected});
assert.deepEqual(ids, expected);
assert(result.hosts.every(h => !('password' in h) && !('privateKey' in h)));
}
report.hostFilters.status = 'pass';
report.hostFilters.path = 'real packaged public/vault/hosts/list dispatcher -> production renderer vault bridge';
await capture('03-host-filter-cases-completed.png');
}
function saveEvidence(print) {
if (fixture && scenario === 'sftp') {
const pauseAt = report.sftpControl?.pauseAcknowledgedAt;
const resumeAt = report.sftpControl?.resumeRequestedAt || Infinity;
report.sftpProtocolSummary = fixture.protocol.opens.map(open => {
const reads = fixture.protocol.reads.filter(read => read.handle === open.handle);
return {...open, role: open.handle === report.sftpHandleClassification?.isolatedDownload?.handle ? 'isolated payload download' : open.channelId === report.sftpHandleClassification?.sharedVerificationChannel ? 'shared browse / source verification' : 'unclassified', readCount: reads.length, repliedBytes: reads.reduce((n, read) => n + (read.replyBytes || 0), 0), readsReceivedWhilePaused: reads.filter(read => read.receivedAt > pauseAt && read.receivedAt < resumeAt).length, repliesWhilePaused: reads.filter(read => read.repliedAt > pauseAt && read.repliedAt < resumeAt).length};
});
}
const output = logs.join('');
const publicText = output + JSON.stringify(report) + (fixture ? JSON.stringify(fixture.protocol) : '');
const sensitive = publicText.includes(loginPassword) || /-----BEGIN [A-Z ]*PRIVATE KEY-----|(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]+)|Authorization:\s*Bearer\s+\S+/i.test(publicText);
report.stderrReview = sensitive ? 'blocked: sensitive output; logs and screenshots withheld' : 'pass: ephemeral password, private key, GitHub credential and bearer-token checks';
if (sensitive) {
process.exitCode = 1; delete report.failure; delete report.sshDiagnostics;
for (const name of ['electron-output.log', 'sftp-protocol.json', 'sftp-pause-resume.mp4', ...screenshots.keys()]) fs.rmSync(path.join(evidence, name), {force: true});
} else {
fs.writeFileSync(path.join(evidence, 'electron-output.log'), output);
if (fixture && scenario === 'sftp') fs.writeFileSync(path.join(evidence, 'sftp-protocol.json'), JSON.stringify(fixture.protocol, null, 2));
if (fs.existsSync(videoPath) && fs.statSync(videoPath).size > 1000) fs.copyFileSync(videoPath, path.join(evidence, 'sftp-pause-resume.mp4'));
for (const [name, bytes] of screenshots) fs.writeFileSync(path.join(evidence, name), bytes);
if (print) console.log('Reviewed official Electron stdout/stderr:\n' + output);
}
report.coverage = 'Independent scenario: only this report and candidate SHA count; other scenario reports must be evaluated separately';
fs.writeFileSync(path.join(evidence, 'assertions.json'), JSON.stringify(report, null, 2));
if (print) console.log(JSON.stringify(report, null, 2));
}
async function verifyClipboard() {
report.clipboard = {status: 'incomplete'};
await terminalLine(cdp, mainCdp, 'QA_CLIPBOARD_ONLY');
await until('clipboard scenario server receive', () => fixture.sessions.some(s => s.commands.includes('QA_CLIPBOARD_ONLY')));
await assertEcho('ran: QA_CLIPBOARD_ONLY');
async function menu(label) {
await clickElement(cdp, '.xterm', 0, 'right');
const point = await until(`terminal menu ${label}`, () => cdp.eval(`(() => { const e = [...document.querySelectorAll('[role="menuitem"]')].find(e => e.textContent.trim().startsWith(${JSON.stringify(label)})); if (!e) return null; const r=e.getBoundingClientRect(); return {x:r.x+r.width/2,y:r.y+r.height/2}; })()`));
await clickPoint(cdp, point);
await pause(200);
}
await menu('Select All'); await menu('Copy');
await until('clipboard receives real terminal echo', async () => {
const actual = await mainCdp.eval(`process.mainModule.require('electron').clipboard.readText()`);
report.clipboard.observed = actual;
return actual.includes('ran: QA_CLIPBOARD_ONLY');
}, 5000);
report.clipboard.status = 'pass';
await capture('03-independent-clipboard.png');
}
async function run() {
assert.notEqual(process.getuid(), 0, 'QA must run as a non-root user');
assert(fs.existsSync(executable), `Official executable missing: ${executable}`);
fs.mkdirSync(evidence, { recursive: true });
assert(!fs.existsSync(profile), 'QA profile must start clean');
watchdog = setTimeout(() => { fs.writeFileSync(path.join(evidence, 'watchdog.json'), JSON.stringify({candidate: pinned.sha, scenario, failure: 'Scenario exceeded 180 seconds', stage: report.stage || 'desktop'})); child?.kill('SIGKILL'); process.exit(1); }, 180000);
try {
await launch();
await capture('01-official-launch.png');
if (scenario === 'persistence') {
const seed = { id: 'qa-persisted-host', label: 'QA persisted loopback host', hostname: '127.0.0.1', username: 'fixture', port: 22222, protocol: 'ssh', tags: ['qa-only'], os: 'linux' };
// Seed synthetic pre-existing data through real Chromium storage. The
// acceptance check is a full process restart and visible real vault data.
await cdp.eval(`localStorage.setItem('netcatty_hosts_v1', ${JSON.stringify(JSON.stringify([seed]))})`);
await cdp.send('Page.reload');
await until('seeded host visible before quit', () => cdp.eval(`document.body.innerText.includes('QA persisted loopback host')`));
await capture('02-seeded-data.png');
await quit();
await launch();
await until('same profile data visible after restart', () => cdp.eval(`document.body.innerText.includes('QA persisted loopback host')`));
assert.equal(await cdp.eval(`JSON.parse(localStorage.getItem('netcatty_hosts_v1'))[0].id`), seed.id);
report.persistence = 'pass: synthetic saved host visible before and after graceful quit/relaunch of same isolated profile';
await capture('03-persisted-after-restart.png');
return;
}
if (scenario === 'host-filter') { await verifyHostFilters(); return; }
fixture = startSshFixture();
await new Promise((resolve, reject) => { fixture.server.once('error', reject); fixture.server.listen(0, '127.0.0.1', resolve); });
const sshPort = fixture.server.address().port;
await clickElement(cdp, 'input[placeholder^="Find a host"]');
await insertText(mainCdp, `ssh -p ${sshPort} fixture@127.0.0.1`);
await clickText(cdp, 'Connect');
await until('protocol wizard', () => cdp.eval(`document.body.innerText.includes('Choose protocol')`));
await clickText(cdp, 'Continue');
await until('username wizard', () => cdp.eval(`Boolean(document.querySelector('input[placeholder="root"]'))`));
await clickText(cdp, 'Continue');
await until('password wizard', () => cdp.eval(`Boolean(document.querySelector('input[placeholder="Enter password"]'))`));
await clickElement(cdp, 'input[placeholder="Enter password"]');
await insertText(mainCdp, loginPassword);
await clickText(cdp, 'Continue');
await until('real host-key confirmation', () => cdp.eval(`document.body.innerText.includes('Confirm this host key')`));
await clickText(cdp, 'Add and continue');
await until('first real SSH shell', () => fixture.sessions.filter(s => s.ready).length === 1);
await pause(700);
await capture('02-connected-shell.png');
if (scenario === 'sftp') { await verifySftp(); return; }
if (scenario === 'clipboard') { await verifyClipboard(); return; }
report.sshReconnect = 'incomplete';
await terminalLine(cdp, mainCdp, 'QA_BEFORE_DISCONNECT');
await until('first server received command', () => fixture.sessions.some(s => s.commands.includes('QA_BEFORE_DISCONNECT')));
await assertEcho('ran: QA_BEFORE_DISCONNECT');
const originalTabs = await cdp.eval(`[...document.querySelectorAll('[data-tab-type="session"]')].map(e => e.getAttribute('data-tab-id'))`);
assert.equal(originalTabs.length, 1);
assert(originalTabs[0], 'Stable original tab ID required');
disconnectFixtureClients(true);
await capture('03-real-ssh-transport-lost.png');
await until('transport closed and reconnect path observable', async () => fixture.sessions[0].closedAt && (fixture.sessions.filter(s => s.ready).length >= 2 || await cdp.eval(`Boolean(document.querySelector('[data-terminal-disconnected-dialog="true"]'))`)));
if (fixture.sessions.filter(s => s.ready).length < 2) {
report.reconnectMode = 'UI Enter';
await capture('04-real-ssh-disconnected.png');
await key(mainCdp, 'Enter'); await key(mainCdp, 'Enter', 'keyUp');
} else report.reconnectMode = 'production automatic reconnect after real transport loss';
await until('second real SSH shell', () => fixture.sessions.filter(s => s.ready).length === 2, 20000);
await pause(700);
await terminalLine(cdp, mainCdp, 'QA_AFTER_RECONNECT');
await until('second server received command', () => fixture.sessions.filter(s => s.ready)[1].commands.includes('QA_AFTER_RECONNECT'));
await assertEcho('ran: QA_AFTER_RECONNECT');
assert.deepEqual(await cdp.eval(`[...document.querySelectorAll('[data-tab-type="session"]')].map(e => e.getAttribute('data-tab-id'))`), originalTabs);
report.sshReconnect = 'pass';
report.ssh = { transport: 'SSH2 over loopback TCP; server destroys its socket, production app reconnects original tab', shellConnections: fixture.sessions.filter(s => s.ready).length, originalTabs, commands: fixture.sessions.filter(s => s.ready).map(s => s.commands.filter(command => command.startsWith('QA_'))), connections: fixture.sessions.filter(s => s.ready).map(({readyAt, closedAt}) => ({readyAt, closedAt})) };
await capture('05-real-ssh-reconnected.png');
} catch (error) {
report.failure = error.message;
report.failureCategory = 'Unresolved assertion; use focus and server receive diagnostics before assigning a product regression';
if (fixture) report.sftpServerAtFailure = {...fixture.sftpStats};
if (scenario === 'sftp' && cdp) report.sftpNativeAtFailure = await cdp.eval(`window.__qaTransfer`).catch(() => null);
if (fixture) report.sshDiagnostics = fixture.sessions.map(({ready, receivedHex, commands, sent}) => ({ready, receivedHex, commands, sent}));
if (report.launcher === 'not_run') report.launcher = 'fail';
await capture('failure-real-application.png').catch(() => {});
process.exitCode = 1;
} finally {
// Persist tested assertions and reviewed evidence before teardown. Cleanup
// must not erase a functional result or mask the original failure.
await stopPauseRecording();
saveEvidence(false);
try {
await quit();
if (fixture) {
disconnectFixtureClients();
await Promise.race([new Promise(resolve => fixture.server.close(resolve)), pause(5000)]);
}
fs.rmSync(profile, { recursive: true, force: true, maxRetries: 5, retryDelay: 300 });
} catch (error) { report.cleanupWarning = error.code || error.message; }
clearTimeout(watchdog);
saveEvidence(true);
}
}
run().catch(error => { console.error(error.message); process.exitCode = 1; });
+92
View File
@@ -0,0 +1,92 @@
{
"name": "netcatty-official-linux-qa",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "netcatty-official-linux-qa",
"version": "1.0.0",
"dependencies": {
"ssh2": "1.17.0"
}
},
"node_modules/asn1": {
"version": "0.2.6",
"resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz",
"integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==",
"license": "MIT",
"dependencies": {
"safer-buffer": "~2.1.0"
}
},
"node_modules/bcrypt-pbkdf": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz",
"integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==",
"license": "BSD-3-Clause",
"dependencies": {
"tweetnacl": "^0.14.3"
}
},
"node_modules/buildcheck": {
"version": "0.0.7",
"resolved": "https://registry.npmjs.org/buildcheck/-/buildcheck-0.0.7.tgz",
"integrity": "sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA==",
"optional": true,
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/cpu-features": {
"version": "0.0.10",
"resolved": "https://registry.npmjs.org/cpu-features/-/cpu-features-0.0.10.tgz",
"integrity": "sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA==",
"hasInstallScript": true,
"optional": true,
"dependencies": {
"buildcheck": "~0.0.6",
"nan": "^2.19.0"
},
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/nan": {
"version": "2.30.0",
"resolved": "https://registry.npmjs.org/nan/-/nan-2.30.0.tgz",
"integrity": "sha512-P5mokDkSvCGBz6mZDD/2l+w9QoICRXdCyZ9ONGmTePr40oihJg3Kpn0YU3twKd6PJnwSlLBWNQeOT6yWEV2c4A==",
"license": "MIT",
"optional": true
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/ssh2": {
"version": "1.17.0",
"resolved": "https://registry.npmjs.org/ssh2/-/ssh2-1.17.0.tgz",
"integrity": "sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ==",
"hasInstallScript": true,
"dependencies": {
"asn1": "^0.2.6",
"bcrypt-pbkdf": "^1.0.2"
},
"engines": {
"node": ">=10.16.0"
},
"optionalDependencies": {
"cpu-features": "~0.0.10",
"nan": "^2.23.0"
}
},
"node_modules/tweetnacl": {
"version": "0.14.5",
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz",
"integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==",
"license": "Unlicense"
}
}
}
+7
View File
@@ -0,0 +1,7 @@
{
"name": "netcatty-official-linux-qa",
"private": true,
"version": "1.0.0",
"description": "QA harness dependencies only; never bundled in Netcatty",
"dependencies": { "ssh2": "1.17.0" }
}
+62
View File
@@ -0,0 +1,62 @@
// The GitHub token exists only in this downloader process, never in Electron.
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const { Readable } = require('node:stream');
const { pipeline } = require('node:stream/promises');
const { execFileSync } = require('node:child_process');
const pinned = require(path.resolve(__dirname, process.env.QA_CANDIDATE || 'candidate.json'));
async function main() {
assert(process.env.GH_TOKEN, 'Downloader needs actions:read token');
const root = path.resolve(process.env.QA_ROOT);
fs.mkdirSync(path.join(root, 'evidence'), { recursive: true });
const base = `https://api.github.com/repos/${pinned.repository}`;
const headers = { Authorization: `Bearer ${process.env.GH_TOKEN}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' };
async function api(route) {
const response = await fetch(base + route, { headers });
assert(response.ok, `GitHub metadata HTTP ${response.status}`);
return response.json();
}
const run = await api(`/actions/runs/${pinned.run}`);
assert.equal(run.head_sha, pinned.sha);
assert.equal(run.repository.id, pinned.repositoryId);
assert.equal(run.head_repository.id, pinned.repositoryId);
assert.equal(run.head_branch, 'main');
assert.equal(run.event, 'push');
assert.equal(run.path, '.github/workflows/build.yml');
const jobs = await api(`/actions/runs/${pinned.run}/jobs?per_page=100`);
const job = jobs.jobs.find(item => item.name === 'build-linux-x64');
assert.equal(job?.conclusion, 'success', 'Official Linux job must succeed');
const artifact = await api(`/actions/artifacts/${pinned.artifact}`);
assert.equal(artifact.name, pinned.name);
assert.equal(artifact.expired, false);
assert.equal(artifact.workflow_run.id, pinned.run);
assert.equal(artifact.workflow_run.head_sha, pinned.sha);
assert.equal(artifact.workflow_run.head_repository_id, pinned.repositoryId);
assert.equal(artifact.digest, `sha256:${pinned.zipSha256}`);
const response = await fetch(`${base}/actions/artifacts/${pinned.artifact}/zip`, { headers, redirect: 'manual' });
assert.equal(response.status, 302);
const location = new URL(response.headers.get('location'));
assert.equal(location.protocol, 'https:');
// Deliberately omit authorization from the redirected blob request.
const archive = await fetch(location);
assert(archive.ok, `Artifact download HTTP ${archive.status}`);
const zip = path.join(root, 'official.zip');
await pipeline(Readable.fromWeb(archive.body), fs.createWriteStream(zip));
async function digest(file) {
const hash = crypto.createHash('sha256');
for await (const bytes of fs.createReadStream(file)) hash.update(bytes);
return hash.digest('hex');
}
assert.equal(await digest(zip), pinned.zipSha256);
// Extract just the named deb, without trusting archive paths or executing postinst.
execFileSync('python3', ['-c', 'import sys,zipfile; z=zipfile.ZipFile(sys.argv[1]); n=sys.argv[2]; assert z.namelist().count(n)==1; open(sys.argv[3],"wb").write(z.read(n))', zip, pinned.deb, path.join(root, pinned.deb)]);
const deb = path.join(root, pinned.deb);
assert.equal(await digest(deb), pinned.debSha256);
assert.equal(execFileSync('dpkg-deb', ['-f', deb, 'Architecture'], { encoding: 'utf8' }).trim(), 'amd64');
execFileSync('dpkg-deb', ['-x', deb, path.join(root, 'package')]);
fs.writeFileSync(path.join(root, 'evidence/provenance.json'), JSON.stringify({ ...pinned, officialLinuxJob: job.id, officialRunStatus: run.status, mode: 'rootless deb extraction; installer scripts not executed', verifiedAt: new Date().toISOString() }, null, 2));
console.log(`Verified official ${pinned.sha}, run ${pinned.run}, artifact ${pinned.artifact}, deb SHA-256 ${pinned.debSha256}`);
}
main().catch(error => { console.error(error.message); process.exitCode = 1; });
+47
View File
@@ -0,0 +1,47 @@
# Official macOS candidate smoke (QA-only Draft #4299)
Independent standard macos-26 Apple Silicon and macos-15-intel jobs pin official
main 9d4e90b / successful push run 44903060405 / artifact 14706977005. Only the
metadata/downloader step receives the built-in Actions read token. It verifies
repository IDs, head, branch/event/workflow, successful macOS job, exact artifact
ID/name/size/expiry and archive SHA-256, then extracts only the matching DMG.
Stock hdiutil verifies DMG integrity and mounts it read-only. ditto copies the
original Netcatty.app into a temporary runner-owned Applications directory,
preserving bundle metadata. The copied app must have the native Mach-O slice,
strict valid Developer ID signature, hardened runtime, a valid stapled APP
notarization ticket, and accepted Notarized Developer ID Gatekeeper assessment.
Outer DMG signature/stapler results are recorded separately and are never
presented as APP notarization. No OS/security/xattr/quarantine/privacy settings
are modified; an assessment preventing launch stops the GUI step.
The unmodified installed app executable launches its real native GUI with a
fresh synthetic profile and an allowlisted process environment retaining the
ephemeral VM's standard HOME/TMPDIR for ordinary macOS services. Actual app
version/path/origin/profile/architecture and stock web preferences are recorded.
Renderer automation and screenshots use loopback CDP/native capture, without
accessibility or screen-recording permission grants. No browser/UI fixture or
checkout-sourced application code replaces the official package.
A generated-credential ssh2 server listens only on 127.0.0.1. Normal Netcatty
Quick Connect GUI accepts that test host key in the isolated profile and opens a
real encrypted PTY/shell. Native xterm input sends a unique harmless printf
token. Both the server receipt/acknowledgement event and the production live
terminal reader must observe the explicit server acknowledgement. Screenshots
capture the actual startup, connection and terminal output. No LAN, external
SSH account, model, business data or public listener is used.
Evidence retained for three days: provenance.json, verification.json (including
exact OS command outputs and package identities), assertions.json,
application-output.log, and arch-prefixed native PNGs: 00-native-launch,
01-first-launch, 02-real-ssh-connected, 03-real-ssh-roundtrip, or failure-native-
application when possible. Assertions and reviewed images are saved before
cleanup; credentials/private keys/tokens in output withhold logs/images and fail.
Raw profiles and generated private keys are never uploaded.
This covers copy installation and first native executable GUI launch after APP
Gatekeeper assessment, not Finder quarantine ingestion, physical user devices,
LAN/privacy approval, automatic updating or a final merged revision. The stock
renderer sandbox:false preference is recorded honestly, never changed. Final
official revision replay requires a separately supplied merge SHA and artifact
IDs; the pinned candidate is not silently replaced.
+17
View File
@@ -0,0 +1,17 @@
{
"repository": "binaricat/Netcatty",
"repositoryId": 1111357457,
"sha": "9d4e90b3aa8fe0a52d1a58e8ea8e61bdd3865e28",
"run": 44903060405,
"buildJob": 136843406473,
"artifact": 14706977005,
"name": "netcatty-macos",
"archiveBytes": 594675248,
"zipSha256": "9c2484a19db5fc74d201bbe8dbdd11101a6a36360a99743a4fe2d90a48369ef1",
"version": "0.0.0-sha-9d4e90b",
"bundleId": "com.netcatty.app",
"dmgs": {
"arm64": "Netcatty-0.0.0-sha-9d4e90b-mac-arm64.dmg",
"x64": "Netcatty-0.0.0-sha-9d4e90b-mac-x64.dmg"
}
}
+245
View File
@@ -0,0 +1,245 @@
// Real, verified installed app GUI + real loopback SSH2; no component fixtures.
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const net = require('node:net');
const vm = require('node:vm');
const { spawn, execFileSync } = require('node:child_process');
const { chromium } = require('playwright-core');
const { Server } = require('ssh2');
const pinned = require('./candidate.json');
const arch = process.env.QA_ARCH, root = path.resolve(process.env.QA_ROOT);
const evidence = path.join(root, 'evidence'), profile = path.join(root, 'profile');
const executable = path.join(root, 'Applications/Netcatty.app/Contents/MacOS/Netcatty');
const loginPassword = crypto.randomBytes(24).toString('hex');
const token = `QA_MAC_${arch}_${crypto.randomUUID().replaceAll('-', '')}`;
const commandText = `printf ${token}`;
const acknowledgement = `QA_MAC_ACK:${token}`;
const report = { candidate: pinned.sha, arch, qaHead: process.env.QA_HEAD_SHA, runner: process.env.QA_RUNNER, firstLaunch: 'not_run', ssh: 'not_run', screenshots: [], fixtureEvents: [], scope: 'First real native GUI launch of the copied official signed/notarized APP, then actual SSH2 loopback shell roundtrip. Not Finder quarantine, LAN, updater, personal-device or final-merged-revision coverage.', security: 'Stock Electron and OS protections. No sandbox/Gatekeeper/quarantine/SIP or privacy-permission changes.' };
const logs = [], images = new Map(), clients = new Set();
let app, browser, page, inspector, server, watchdog, finishing;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
function stage(name) { report.stage = name; console.log(`QA_MAC_STAGE ${name}`); }
async function until(label, check, timeout = 20000) {
const end = Date.now() + timeout; let last;
while (Date.now() < end) {
try { const value = await check(); if (value) return value; } catch (error) { if (error instanceof SyntaxError) throw error; last = error; }
await sleep(150);
}
throw new Error(`Timed out: ${label}${last ? `: ${last.message}` : ''}`);
}
async function freePort() { const s = net.createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; }
function environment() {
const env = {};
for (const key of ['PATH', 'HOME', 'TMPDIR', 'USER', 'LOGNAME', 'SHELL', '__CF_USER_TEXT_ENCODING', 'XPC_FLAGS', 'XPC_SERVICE_NAME', 'COMMAND_MODE']) if (process.env[key]) env[key] = process.env[key];
Object.assign(env, { LANG: 'en_US.UTF-8', LC_ALL: 'en_US.UTF-8' });
// Preserve the ephemeral VM's normal OS home/bootstrap and temporary paths.
// Only app userData is isolated; never substitute/disable the OS keychain.
report.environment = { home: env.HOME, tmpdir: env.TMPDIR, isolatedAppProfile: profile, inheritedKeys: Object.keys(env) };
return env;
}
class Inspector {
constructor(url) {
this.ws = new WebSocket(url); this.next = 0; this.pending = new Map();
this.ws.addEventListener('message', event => { const m = JSON.parse(event.data), item = this.pending.get(m.id); if (!item) return; this.pending.delete(m.id); m.error ? item.reject(new Error(m.error.message)) : item.resolve(m.result); });
}
async connect() { await new Promise((resolve, reject) => { this.ws.addEventListener('open', resolve, { once: true }); this.ws.addEventListener('error', reject, { once: true }); }); }
async eval(expression) {
if (typeof expression === 'function') expression = `(${expression.toString()})()`;
new vm.Script(expression);
const id = ++this.next;
const result = await new Promise((resolve, reject) => {
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error('Native inspector timeout')); }, 12000);
this.pending.set(id, { resolve: v => { clearTimeout(timer); resolve(v); }, reject: e => { clearTimeout(timer); reject(e); } });
this.ws.send(JSON.stringify({ id, method: 'Runtime.evaluate', params: { expression, returnByValue: true, awaitPromise: true } }));
});
if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
return result.result.value;
}
close() { this.ws.close(); }
}
function keepImage(name, bytes) {
assert(bytes.length > 10000, 'Capture must contain an actual rendered application');
assert.equal(bytes.subarray(1, 4).toString(), 'PNG');
images.set(name, bytes);
report.screenshots.push({ name, bytes: bytes.length, width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20), sha256: crypto.createHash('sha256').update(bytes).digest('hex'), source: 'Actual installed native renderer capture' });
}
async function capture(name) {
if (inspector) {
const encoded = await inspector.eval(async () => {
const e = process.mainModule.require('electron');
const w = e.BrowserWindow.getAllWindows().find(w => w.webContents.getURL().startsWith('app://netcatty/index.html'));
return w ? (await w.webContents.capturePage()).toPNG().toString('base64') : null;
});
if (encoded) keepImage(`${arch}-${name}.png`, Buffer.from(encoded, 'base64'));
} else if (page && !page.isClosed()) keepImage(`${arch}-${name}.png`, await page.screenshot({ timeout: 10000 }));
}
function event(kind, detail = {}) { report.fixtureEvents.push({ at: new Date().toISOString(), kind, ...detail }); }
async function startSsh() {
const { privateKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048, privateKeyEncoding: { type: 'pkcs1', format: 'pem' }, publicKeyEncoding: { type: 'spki', format: 'pem' } });
server = new Server({ hostKeys: [privateKey] }, client => {
clients.add(client); const connection = report.fixtureEvents.filter(e => e.kind === 'tcp').length + 1;
event('tcp', { connection, remoteAddress: client._sock?.remoteAddress });
client.on('error', error => event('transport_error', { connection, message: error.message }));
client.on('close', () => { clients.delete(client); event('closed', { connection }); });
client.on('authentication', ctx => { if (ctx.method === 'password' && ctx.username === 'fixture' && ctx.password === loginPassword) { event('authentication_accepted', { connection, method: ctx.method }); ctx.accept(); } else ctx.reject(['password']); });
client.on('ready', () => {
event('ready', { connection });
client.on('session', accept => {
const session = accept();
session.on('pty', acceptPty => { event('pty', { connection }); acceptPty?.(); });
session.on('window-change', acceptChange => acceptChange?.());
session.on('shell', acceptShell => {
const stream = acceptShell(); let line = '';
event('shell', { connection }); stream.write('Synthetic Netcatty QA loopback SSH\r\nfixture$ ');
stream.on('data', data => {
for (const char of data.toString()) {
if (char === '\r' || char === '\n') {
const submitted = line; line = '';
if (!submitted) continue;
event('command_received', { connection, command: submitted });
if (submitted === commandText) { stream.write(`\r\n${acknowledgement}\r\nfixture$ `); event('acknowledgement_sent', { connection, text: acknowledgement }); }
} else if (char === '\x7f') line = line.slice(0, -1);
else line += char;
}
});
});
});
});
});
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
report.service = { implementation: 'ssh2 real encrypted loopback server with a controlled synthetic shell', address: server.address(), command: commandText, acknowledgement, generatedCredential: 'ephemeral random password, never logged or uploaded' };
assert.equal(server.address().address, '127.0.0.1');
return server.address().port;
}
async function launch() {
stage('launch verified installed app executable');
const debugPort = await freePort(), inspectPort = await freePort();
app = spawn(executable, [`--user-data-dir=${profile}`, '--remote-debugging-address=127.0.0.1', `--remote-debugging-port=${debugPort}`, `--inspect=127.0.0.1:${inspectPort}`], { cwd: path.dirname(executable), env: environment(), stdio: ['ignore', 'pipe', 'pipe'] });
app.on('error', error => logs.push(error.stack));
for (const name of ['stdout', 'stderr']) app[name].on('data', b => logs.push(`[${name}] ${b}`));
const target = await until('stock signed app native debugger', async () => {
assert.equal(app.exitCode, null, 'Actual app exited; read real stderr');
return (await (await fetch(`http://127.0.0.1:${inspectPort}/json/list`, { signal: AbortSignal.timeout(1000) })).json())[0];
}, 45000);
stage('await actual renderer CDP target before native identity inspection');
await until('official app renderer target', async () => {
const targets = await (await fetch(`http://127.0.0.1:${debugPort}/json/list`, { signal: AbortSignal.timeout(1000) })).json();
report.rendererTargets = targets.map(t => ({ type: t.type, url: t.url, title: t.title }));
return targets.some(t => t.type === 'page' && t.url.startsWith('app://netcatty/index.html'));
}, 45000);
browser = await chromium.connectOverCDP(`http://127.0.0.1:${debugPort}`, { timeout: 30000 }); browser.contexts()[0].setDefaultTimeout(12000);
page = await until('actual installed app page', () => browser.contexts()[0].pages().find(p => p.url().startsWith('app://netcatty/index.html') && !p.url().includes('settings')));
await page.getByPlaceholder(/^Find a host/).waitFor({ timeout: 45000 });
inspector = new Inspector(target.webSocketDebuggerUrl); await inspector.connect();
report.nativeInspectorPreflight = await inspector.eval('({pid:process.pid, platform:process.platform, arch:process.arch})');
stage('actual renderer ready; inspect native app identity');
report.native = await inspector.eval(() => {
const e = process.mainModule.require('electron'), w = e.BrowserWindow.getAllWindows().find(w => w.webContents.getURL().startsWith('app://netcatty/index.html'));
w.setSize(1440, 1000); w.show(); w.focus();
return { pid: process.pid, platform: process.platform, arch: process.arch, uid: process.getuid(), version: e.app.getVersion(), packaged: e.app.isPackaged, appPath: e.app.getAppPath(), executable: process.execPath, profile: e.app.getPath('userData'), origin: w.webContents.getURL(), electron: process.versions.electron, argv: process.argv, preferences: w.webContents.getLastWebPreferences(), noSandbox: e.app.commandLine.hasSwitch('no-sandbox'), disableSetuidSandbox: e.app.commandLine.hasSwitch('disable-setuid-sandbox') };
});
const n = report.native;
assert.equal(n.arch, arch); assert.equal(n.platform, 'darwin'); assert.notEqual(n.uid, 0); assert.equal(n.version, pinned.version); assert.equal(n.packaged, true);
assert.equal(n.executable, executable); assert.equal(n.profile, profile); assert(n.appPath.endsWith('/Netcatty.app/Contents/Resources/app.asar'));
assert.equal(n.noSandbox, false); assert.equal(n.disableSetuidSandbox, false); assert.equal(n.preferences.contextIsolation, true); assert.equal(n.preferences.nodeIntegration, false); assert.equal(n.preferences.webSecurity, true);
report.sandboxScope = `Unmodified stock renderer sandbox:${n.preferences.sandbox}; this is not full renderer-sandbox certification`;
await until('native window resize applied', () => inspector.eval(() => {
const w = process.mainModule.require('electron').BrowserWindow.getAllWindows().find(w => w.webContents.getURL().startsWith('app://netcatty/index.html'));
return w.isVisible() && w.getBounds().width === 1440;
}));
await sleep(300);
await capture('00-native-launch');
stage('native GUI identity and initial capture verified');
for (const port of [debugPort, inspectPort]) {
const output = execFileSync('/usr/sbin/lsof', ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN'], { encoding: 'utf8', timeout: 10000 });
assert(!/\*:|0\.0\.0\.0:|\[::\]:/.test(output), 'Debugger must not listen publicly'); assert(/127\.0\.0\.1:|\[::1\]:/.test(output));
(report.debuggerListeners ||= []).push({ port, output });
}
report.firstLaunch = 'passed: actual installed official native GUI, fresh synthetic profile, stock protections';
await capture('01-first-launch');
stage('first GUI launch passed');
}
async function ssh(port) {
stage('normal GUI quick-connect to owned loopback SSH');
report.ssh = 'incomplete';
await page.getByPlaceholder(/^Find a host/).fill(`ssh -p ${port} fixture@127.0.0.1`);
await page.getByRole('button', { name: 'Connect', exact: true }).click();
await page.getByText('Choose protocol', { exact: false }).first().waitFor();
await page.getByRole('button', { name: 'Continue', exact: true }).click();
await page.getByPlaceholder('root', { exact: true }).fill('fixture');
await page.getByRole('button', { name: 'Continue', exact: true }).click();
await page.getByPlaceholder('Enter password', { exact: true }).fill(loginPassword);
await page.getByRole('button', { name: 'Continue', exact: true }).click();
await page.getByText('Confirm this host key', { exact: false }).first().waitFor();
await page.getByRole('button', { name: 'Add and continue', exact: true }).click();
await until('actual authenticated SSH shell', () => report.fixtureEvents.some(e => e.kind === 'shell'));
stage('real authenticated SSH shell accepted by fixture');
await until('actual xterm input mounted', () => page.evaluate(() => [...document.querySelectorAll('.xterm-helper-textarea')].some(e => e.closest('.xterm')?.getBoundingClientRect().width > 0)));
await capture('02-real-ssh-connected');
report.inputFocus = await page.evaluate(() => { const e = [...document.querySelectorAll('.xterm-helper-textarea')].find(e => e.closest('.xterm')?.getBoundingClientRect().width > 0); e.focus(); return { focused: document.activeElement === e, tag: document.activeElement.tagName }; });
assert.equal(report.inputFocus.focused, true);
await page.keyboard.insertText(commandText); await page.keyboard.press('Enter');
await until('server received unique harmless command', () => report.fixtureEvents.some(e => e.kind === 'command_received' && e.command === commandText));
assert(report.fixtureEvents.some(e => e.kind === 'acknowledgement_sent' && e.text === acknowledgement));
const tabId = await page.locator('[data-tab-type="session"]').first().getAttribute('data-tab-id'); assert(tabId);
const params = { sessionId: tabId, scopedSessionIds: [tabId], range: 'tail', maxLines: 80 };
await until('server acknowledgement in actual production terminal reader', async () => {
const result = await inspector.eval(`process.mainModule.require(process.mainModule.require('electron').app.getAppPath() + '/electron/bridges/mcpServerBridge.cjs').dispatchBuiltinRpc('netcatty/readContext', ${JSON.stringify(params)})`);
report.terminalRead = result;
return result.ok === true && result.content.includes(acknowledgement);
});
report.ssh = 'passed: encrypted SSH authentication + PTY/shell, server unique-command receipt, explicit server acknowledgement in production live terminal buffer';
report.tabId = tabId; await sleep(150); await capture('03-real-ssh-roundtrip');
stage('real SSH roundtrip passed');
}
async function quit() {
if (inspector) {
try { if (app?.exitCode === null && app?.signalCode === null) await inspector.eval("setImmediate(() => process.mainModule.require('electron').app.quit()); true"); }
finally { inspector.close(); inspector = null; }
}
if (!app || app.exitCode !== null || app.signalCode !== null) return;
const exited = await new Promise(resolve => { const timer = setTimeout(() => resolve(false), 10000); app.once('exit', () => { clearTimeout(timer); resolve(true); }); });
if (!exited && app.exitCode === null && app.signalCode === null) {
report.cleanupWarning = 'Normal quit exceeded 10 seconds; terminate only the owned ephemeral QA app'; app.kill('SIGTERM'); await sleep(1500);
if (app.exitCode === null && app.signalCode === null) app.kill('SIGKILL');
}
}
function save() {
const output = logs.join('');
const publicText = output + JSON.stringify(report);
const sensitive = publicText.includes(loginPassword) || /-----BEGIN [A-Z ]*PRIVATE KEY-----|(?:gh[opsur]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,})|Authorization:\s*Bearer\s+\S+/i.test(publicText);
report.stderrReview = sensitive ? 'blocked: sensitive data; logs and images withheld' : 'passed: ephemeral password, private key, GitHub credential and bearer-header checks';
if (sensitive) { process.exitCode = 1; report.error = 'Sensitive-data review failed'; }
else { fs.writeFileSync(path.join(evidence, 'application-output.log'), output); for (const [name, bytes] of images) fs.writeFileSync(path.join(evidence, name), bytes); }
fs.writeFileSync(path.join(evidence, 'assertions.json'), JSON.stringify(report, null, 2));
}
async function finish() {
if (finishing) return finishing;
finishing = (async () => {
clearTimeout(watchdog);
if (report.error) { try { await capture('failure-native-application'); } catch {} if (page) try { report.failureVisibleUI = await page.locator('body').innerText({ timeout: 3000 }); } catch {} }
save(); // Preserve actual assertions before cleanup.
for (const client of clients) client.end();
if (server) { server.close(); await sleep(200); }
try { await quit(); } catch (error) { report.cleanupWarning = error.message; app?.kill('SIGTERM'); }
for (const client of clients) client._sock?.destroy(); // Owned fixture teardown only, after SSH assertions.
if (browser) await Promise.race([browser.close().catch(() => {}), sleep(2000)]);
report.applicationExit = app && { pid: app.pid, code: app.exitCode, signal: app.signalCode };
save();
if (report.stderrReview.startsWith('passed')) console.log('Reviewed actual application output:\n' + logs.join(''));
await new Promise(resolve => process.stdout.write(JSON.stringify(report, null, 2) + '\n', resolve));
})();
return finishing;
}
async function main() {
assert.equal(process.platform, 'darwin'); assert.equal(process.arch, arch); assert.notEqual(process.getuid(), 0); assert(!process.env.GH_TOKEN && !process.env.GITHUB_TOKEN);
assert.equal(JSON.parse(fs.readFileSync(path.join(evidence, 'verification.json'))).status, 'passed', 'No launch around a failed OS assessment');
assert(!fs.existsSync(profile), 'First launch must use a fresh QA profile'); fs.mkdirSync(evidence, { recursive: true });
watchdog = setTimeout(() => { report.error = 'Native scenario exceeded 240 seconds'; process.exitCode = 1; finish().finally(() => process.exit(1)); }, 240000);
const port = await startSsh(); await launch(); await ssh(port);
}
main().catch(error => { report.error = error.stack; process.exitCode = 1; }).then(async () => {
await finish(); process.exit(process.exitCode || 0); // Do not let stale automation transports keep a finished QA step alive.
}).catch(error => { console.error(error.stack); process.exit(1); });
+105
View File
@@ -0,0 +1,105 @@
{
"name": "netcatty-official-macos-qa",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "netcatty-official-macos-qa",
"version": "1.0.0",
"dependencies": {
"playwright-core": "1.56.1",
"ssh2": "1.17.0"
}
},
"node_modules/asn1": {
"version": "0.2.6",
"resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz",
"integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==",
"license": "MIT",
"dependencies": {
"safer-buffer": "~2.1.0"
}
},
"node_modules/bcrypt-pbkdf": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz",
"integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==",
"license": "BSD-3-Clause",
"dependencies": {
"tweetnacl": "^0.14.3"
}
},
"node_modules/buildcheck": {
"version": "0.0.7",
"resolved": "https://registry.npmjs.org/buildcheck/-/buildcheck-0.0.7.tgz",
"integrity": "sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA==",
"optional": true,
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/cpu-features": {
"version": "0.0.10",
"resolved": "https://registry.npmjs.org/cpu-features/-/cpu-features-0.0.10.tgz",
"integrity": "sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA==",
"hasInstallScript": true,
"optional": true,
"dependencies": {
"buildcheck": "~0.0.6",
"nan": "^2.19.0"
},
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/nan": {
"version": "2.30.0",
"resolved": "https://registry.npmjs.org/nan/-/nan-2.30.0.tgz",
"integrity": "sha512-P5mokDkSvCGBz6mZDD/2l+w9QoICRXdCyZ9ONGmTePr40oihJg3Kpn0YU3twKd6PJnwSlLBWNQeOT6yWEV2c4A==",
"license": "MIT",
"optional": true
},
"node_modules/playwright-core": {
"version": "1.56.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.56.1.tgz",
"integrity": "sha512-hutraynyn31F+Bifme+Ps9Vq59hKuUCz7H1kDOcBs+2oGguKkWTU50bBWrtz34OUWmIwpBTWDxaRPXrIXkgvmQ==",
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/ssh2": {
"version": "1.17.0",
"resolved": "https://registry.npmjs.org/ssh2/-/ssh2-1.17.0.tgz",
"integrity": "sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ==",
"hasInstallScript": true,
"dependencies": {
"asn1": "^0.2.6",
"bcrypt-pbkdf": "^1.0.2"
},
"engines": {
"node": ">=10.16.0"
},
"optionalDependencies": {
"cpu-features": "~0.0.10",
"nan": "^2.23.0"
}
},
"node_modules/tweetnacl": {
"version": "0.14.5",
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz",
"integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==",
"license": "Unlicense"
}
}
}
+10
View File
@@ -0,0 +1,10 @@
{
"name": "netcatty-official-macos-qa",
"version": "1.0.0",
"private": true,
"description": "QA-only official macOS native launch and loopback SSH",
"dependencies": {
"playwright-core": "1.56.1",
"ssh2": "1.17.0"
}
}
+42
View File
@@ -0,0 +1,42 @@
// Only this metadata/download step receives the built-in Actions read token.
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const { Readable } = require('node:stream');
const { pipeline } = require('node:stream/promises');
const { execFileSync } = require('node:child_process');
const pinned = require('./candidate.json');
const root = path.resolve(process.env.QA_ROOT);
const arch = process.env.QA_ARCH;
async function digest(file) { const h = crypto.createHash('sha256'); for await (const b of fs.createReadStream(file)) h.update(b); return h.digest('hex'); }
async function main() {
assert.equal(process.platform, 'darwin'); assert(pinned.dmgs[arch]); assert(process.env.GH_TOKEN);
fs.mkdirSync(path.join(root, 'evidence'), { recursive: true });
const base = `https://api.github.com/repos/${pinned.repository}`;
const headers = { Authorization: `Bearer ${process.env.GH_TOKEN}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' };
async function api(route) { const r = await fetch(base + route, { headers, signal: AbortSignal.timeout(30000) }); assert(r.ok, `Metadata HTTP ${r.status}`); return r.json(); }
const run = await api(`/actions/runs/${pinned.run}`);
assert.equal(run.head_sha, pinned.sha); assert.equal(run.repository.id, pinned.repositoryId); assert.equal(run.head_repository.id, pinned.repositoryId);
assert.equal(run.event, 'push'); assert.equal(run.head_branch, 'main'); assert.equal(run.path, '.github/workflows/build.yml'); assert.equal(run.conclusion, 'success');
const jobs = await api(`/actions/runs/${pinned.run}/jobs?per_page=100`);
const job = jobs.jobs.find(j => j.id === pinned.buildJob);
assert.equal(job?.name, 'build-macos'); assert.equal(job.conclusion, 'success');
const artifact = await api(`/actions/artifacts/${pinned.artifact}`);
assert.equal(artifact.name, pinned.name); assert.equal(artifact.expired, false); assert(Date.parse(artifact.expires_at) > Date.now());
assert.equal(artifact.size_in_bytes, pinned.archiveBytes); assert.equal(artifact.digest, `sha256:${pinned.zipSha256}`);
assert.equal(artifact.workflow_run.id, pinned.run); assert.equal(artifact.workflow_run.head_sha, pinned.sha); assert.equal(artifact.workflow_run.head_repository_id, pinned.repositoryId);
const redirect = await fetch(`${base}/actions/artifacts/${pinned.artifact}/zip`, { headers, redirect: 'manual', signal: AbortSignal.timeout(30000) });
assert.equal(redirect.status, 302); const location = new URL(redirect.headers.get('location')); assert.equal(location.protocol, 'https:');
const response = await fetch(location, { signal: AbortSignal.timeout(180000) }); // No token forwarded to blob storage.
assert(response.ok, `Artifact HTTP ${response.status}`);
const archive = path.join(root, 'official.zip'); await pipeline(Readable.fromWeb(response.body), fs.createWriteStream(archive));
assert.equal(fs.statSync(archive).size, pinned.archiveBytes); assert.equal(await digest(archive), pinned.zipSha256);
const dmg = path.join(root, pinned.dmgs[arch]);
const script = 'import sys,zipfile,shutil,json; z=zipfile.ZipFile(sys.argv[1]); n=sys.argv[2]; assert z.namelist().count(n)==1; print(json.dumps(z.namelist())); src=z.open(n); dst=open(sys.argv[3],"wb"); shutil.copyfileobj(src,dst); dst.close(); src.close()';
const entries = JSON.parse(execFileSync('python3', ['-c', script, archive, pinned.dmgs[arch], dmg], { encoding: 'utf8', env: { ...process.env, GH_TOKEN: '' }, timeout: 60000, maxBuffer: 2e6 }));
const report = { ...pinned, arch, qaHead: process.env.QA_HEAD_SHA, officialArtifactExpiresAt: artifact.expires_at, verifiedAt: new Date().toISOString(), archiveEntries: entries, selectedDmg: pinned.dmgs[arch], dmgSha256: await digest(dmg), dmgBytes: fs.statSync(dmg).size, scope: 'Exact official candidate only; not final merged revision or release updater acceptance' };
fs.writeFileSync(path.join(root, 'evidence/provenance.json'), JSON.stringify(report, null, 2));
console.log(JSON.stringify(report, null, 2));
}
main().catch(error => { console.error(error.stack); process.exitCode = 1; });
@@ -0,0 +1,66 @@
// Read-only OS assessments and normal copy installation. No OS settings change.
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
const pinned = require('./candidate.json');
const root = path.resolve(process.env.QA_ROOT), arch = process.env.QA_ARCH;
const evidence = path.join(root, 'evidence');
const app = path.join(root, 'Applications/Netcatty.app');
const mount = path.join(root, 'mount');
const report = { candidate: pinned.sha, arch, qaHead: process.env.QA_HEAD_SHA, commands: [], dmgIntegrity: 'not_run', installedApp: 'not_run', developerId: 'not_run', appNotarizationTicket: 'not_run', gatekeeperApp: 'not_run', scope: 'Runner-owned Applications copy from read-only mounted official DMG. DMG integrity differs from app Developer ID/notarization; no Finder-quarantine or personal-device claim.' };
let mounted = false;
function command(label, executable, args, required = true, timeout = 60000) {
const r = spawnSync(executable, args, { encoding: 'utf8', timeout, maxBuffer: 5e6 });
const item = { label, executable, args, exitCode: r.status, signal: r.signal, stdout: r.stdout || '', stderr: r.stderr || '', error: r.error?.message };
report.commands.push(item);
if (required) assert.equal(r.status, 0, `${label}: ${item.stderr || item.stdout || item.error}`);
return item;
}
function main() {
assert.equal(process.platform, 'darwin'); assert.equal(process.arch, arch); assert.notEqual(process.getuid(), 0);
assert(!process.env.GH_TOKEN && !process.env.GITHUB_TOKEN);
fs.mkdirSync(evidence, { recursive: true });
report.uname = command('runner uname', '/usr/bin/uname', ['-m']).stdout.trim();
assert.equal(report.uname, arch === 'arm64' ? 'arm64' : 'x86_64');
report.os = command('runner OS', '/usr/bin/sw_vers', []).stdout;
report.uid = process.getuid(); report.runnerLabel = process.env.QA_RUNNER; report.nodeArch = process.arch;
const dmg = path.join(root, pinned.dmgs[arch]);
command('DMG integrity verification', '/usr/bin/hdiutil', ['verify', dmg]); report.dmgIntegrity = 'passed';
// Informational only: unsigned outer DMG != unsigned/not-notarized inner app.
report.outerDmgSignature = command('outer DMG signature display (not an app assessment)', '/usr/bin/codesign', ['-d', '--verbose=4', dmg], false);
report.outerDmgStapler = command('outer DMG staple validation (reported separately)', '/usr/bin/xcrun', ['stapler', 'validate', dmg], false);
fs.mkdirSync(mount, { recursive: true });
command('mount official DMG read-only', '/usr/bin/hdiutil', ['attach', '-readonly', '-nobrowse', '-noautoopen', '-mountpoint', mount, dmg]); mounted = true;
assert(fs.existsSync(path.join(mount, 'Netcatty.app')));
fs.mkdirSync(path.dirname(app), { recursive: true }); assert(!fs.existsSync(app));
command('copy original app preserving bundle metadata', '/usr/bin/ditto', [path.join(mount, 'Netcatty.app'), app]); report.installedApp = 'passed: normal runner-owned Applications copy; original bundle unchanged';
command('unmount read-only image', '/usr/bin/hdiutil', ['detach', mount]); mounted = false;
report.bundleIdentifier = command('bundle identifier', '/usr/libexec/PlistBuddy', ['-c', 'Print :CFBundleIdentifier', path.join(app, 'Contents/Info.plist')]).stdout.trim();
assert.equal(report.bundleIdentifier, pinned.bundleId);
report.bundleVersion = command('bundle version', '/usr/libexec/PlistBuddy', ['-c', 'Print :CFBundleShortVersionString', path.join(app, 'Contents/Info.plist')]).stdout.trim();
const executableName = command('bundle executable', '/usr/libexec/PlistBuddy', ['-c', 'Print :CFBundleExecutable', path.join(app, 'Contents/Info.plist')]).stdout.trim();
assert.equal(executableName, 'Netcatty');
report.executable = path.join(app, 'Contents/MacOS', executableName);
report.executableArchitectures = command('Mach-O architecture', '/usr/bin/lipo', ['-archs', report.executable]).stdout.trim().split(/\s+/);
assert(report.executableArchitectures.includes(report.uname), 'Official executable must contain native runner architecture');
command('strict deep code signature verification', '/usr/bin/codesign', ['--verify', '--deep', '--strict', '--verbose=4', app]);
const signature = command('Developer ID signature identifiers', '/usr/bin/codesign', ['-d', '--verbose=4', app]);
const description = signature.stdout + signature.stderr;
assert(description.includes(`Identifier=${pinned.bundleId}`)); assert(/Authority=Developer ID Application:/.test(description)); assert(/TeamIdentifier=[A-Z0-9]+/.test(description)); assert(/flags=.*runtime/.test(description));
report.teamIdentifier = description.match(/TeamIdentifier=([A-Z0-9]+)/)[1];
report.authorities = [...description.matchAll(/^Authority=(.+)$/gm)].map(m => m[1]);
command('designated requirements', '/usr/bin/codesign', ['-d', '-r-', app]); report.developerId = 'passed: valid strict Developer ID application signature with hardened runtime';
command('notarization ticket on installed APP', '/usr/bin/xcrun', ['stapler', 'validate', app]); report.appNotarizationTicket = 'passed';
const status = command('stock Gatekeeper status (read only)', '/usr/sbin/spctl', ['--status']);
assert(/assessments enabled/i.test(status.stdout + status.stderr), 'Runner must have stock Gatekeeper assessments enabled; never enable/disable to obtain a pass');
const gatekeeper = command('Gatekeeper assessment of installed APP', '/usr/sbin/spctl', ['--assess', '--type', 'execute', '--verbose=4', app], true, 90000);
assert(/Notarized Developer ID/.test(gatekeeper.stdout + gatekeeper.stderr)); report.gatekeeperApp = 'passed: accepted, Notarized Developer ID';
report.installedAppXattrs = command('observe app xattrs without modification', '/usr/bin/xattr', ['-l', app], false);
report.installPath = app; report.status = 'passed';
}
try { main(); } catch (error) { report.status = 'failed'; report.blocker = error.stack; process.exitCode = 1; }
finally {
if (mounted) command('detach after failed assessment', '/usr/bin/hdiutil', ['detach', mount], false);
fs.mkdirSync(evidence, { recursive: true }); fs.writeFileSync(path.join(evidence, 'verification.json'), JSON.stringify(report, null, 2)); console.log(JSON.stringify(report, null, 2));
}
+76
View File
@@ -0,0 +1,76 @@
# Installed Windows package acceptance (QA only)
This harness belongs only to same-repository Draft PR #4299 on
`qa/official-linux-a23868e`. Its independent standard `windows-2022` workflow
does not modify the product, release packages, main, or the earlier Linux job.
`candidate.json` pins the public v1.1.90 NSIS asset and the exact official
9d4e90b Windows Actions artifact. The downloader verifies repository, main push,
build job, artifact metadata and archive SHA-256 before extracting the one named
NSIS installer. The Actions read token exists only in this downloader step.
An independent `portable` matrix job verifies the public v1.1.90 Windows ZIP
SHA-256 `df057f03d122fb541168868d2d203c3723b8b731a663dbdaa5bc38390a742b88`
and extracts the exact candidate Windows ZIP entry from the same verified
official artifact. It runs the identical actual-GUI migration assertions on an
explicit disposable profile, even if NSIS fails. ZIP extraction does not certify
installation, overinstallation, NSIS portable launchers or automatic updates.
The two modes use fresh independent VMs and separately named evidence artifacts.
The separate exact-fix jobs pin same-repository PR #4302 commit
`4516d3aed7cb54862dabd53abb56a7f90fba3212`, based on frozen main 9d4e90b.
If no exact standard package exists, a separate checkout on standard
windows-2022 runs the existing Node 22/MSVC/npm ci/pack:win-x64 conventions.
Only the normal non-release version metadata is set. Application source is not
patched while packaging. The build child receives a Windows environment
allowlist with no Actions credentials; signing/distribution credentials are not
supplied and publishing is disabled. The resulting NSIS is explicitly
CI QA-built, unsigned and unreleased. Its exact SHA-256, source SHA and QA run
are verified in a separate fresh desktop job before normal installation.
The fix acceptance uses the same real released v1.1.90 GUI baseline and native
NSIS/history harness. A positive candidate-created Beta pointer in IndexedDB is
a mandatory precondition before normal quit. That exact pointer must survive
complete restart before panel interaction, alongside both original chats,
saved host and new reply. Panel display intent remains memory-only: manual
history opening after restart is not claimed as automatic conversation reopen.
The old official 9d4e90b control and its original retained failure are separate.
The installed real v1.1.90 GUI configures a deterministic loopback-only OpenAI
provider, saves one synthetic loopback host, and creates two distinct chats with
two complete user/assistant turns each. Beta remains active. No localStorage,
IndexedDB or React state writes seed the fixture. The same custom profile and
`app://netcatty` origin are reused by the installed official candidate. Read-only
storage observations compare original session IDs, full messages and scope,
the exact active pointer, saved host and the IndexedDB migration marker. The
candidate sends another normal GUI message, quits normally and restarts to
verify the appended turn and original chats persist.
Both candidate snapshots must have IndexedDB `meta.activeSessionMap` directly;
legacy localStorage is not accepted as a substitute for migration evidence.
The stock panel's draft/chat display intent is memory-only. Record and capture
the initial candidate/restarted view before any navigation. If it opens the
Recent/draft view, verify the original IndexedDB active pointer first, then
select the existing chat through normal history UI. Do not call that selection
automatic restoration of the previously visible conversation.
Both installers use normal silent per-user NSIS arguments. The candidate version
`0.0.0-sha-9d4e90b` is below 1.1.90, so this is **not** released automatic updater
acceptance. A blocked replacement is recorded separately. A normal uninstall
and fresh candidate installation may then test migration using the preserved
explicit QA profile, without altering packages or bypassing version checks.
The application receives an allowlist of Windows runtime environment variables,
isolated synthetic home directories, and no GitHub token. There are no sandbox
disabling flags or system security changes. The stock application's own web
preferences are recorded rather than claiming stronger isolation than it uses.
Evidence is retained for three days. `provenance.json` has exact hashes;
`assertions.json` records individual outcomes, installer exits, actual running
executable/version/profile/origin, and loopback calls. Storage snapshots contain
only synthetic chats/host. PNGs (`01-baseline-alpha`, `02-baseline-beta-active`,
`03-candidate-beta-active`, `04-candidate-alpha`, `05-candidate-appended`,
`06-candidate-restarted`, or `failure-*`) capture the actual installed native
renderer via CDP, not the Windows OS desktop or a physical computer. Logs are
checked for credential patterns before PNGs and app output enter the upload
directory. Launch, installer, harness and product failures remain failures.
@@ -0,0 +1,77 @@
// Trusted exact-SHA source build only. No Actions credentials reach npm/build.
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const { spawn, execFileSync } = require('node:child_process');
const pinned = require('./fixed-candidate.json');
const source = path.resolve(process.env.QA_FIX_SOURCE);
const output = path.resolve(process.env.QA_BUILD_OUTPUT);
const report = { ...pinned, origin: 'CI QA-built from exact trusted same-repository fix; unsigned, unreleased, no automatic updater certification', run: process.env.GITHUB_RUN_ID, qaHead: process.env.QA_HEAD_SHA, node: process.version, platform: process.platform, arch: process.arch, steps: [] };
const logs = [];
function environment() {
const allowed = ['PATH', 'SystemRoot', 'SystemDrive', 'WINDIR', 'ComSpec', 'PATHEXT', 'ProgramFiles', 'ProgramFiles(x86)', 'ProgramW6432', 'CommonProgramFiles', 'CommonProgramFiles(x86)', 'CommonProgramW6432', 'ProgramData', 'ALLUSERSPROFILE', 'PUBLIC', 'OS', 'PROCESSOR_ARCHITECTURE', 'NUMBER_OF_PROCESSORS', 'USERNAME', 'USERDOMAIN', 'USERDNSDOMAIN', 'COMPUTERNAME', 'SESSIONNAME', 'PSModulePath', 'PSHOME', 'USERPROFILE', 'HOME', 'APPDATA', 'LOCALAPPDATA', 'HOMEDRIVE', 'HOMEPATH', 'TEMP', 'TMP'];
const env = {};
for (const key of allowed) if (process.env[key]) env[key] = process.env[key];
return { ...env, CI: 'true', BUNDLE_MOSH: 'false', BUNDLE_ET: 'false', ELECTRON_BUILDER_PUBLISH: 'never', CSC_IDENTITY_AUTO_DISCOVERY: 'false', NPM_CONFIG_FETCH_RETRIES: '4', NPM_CONFIG_FETCH_RETRY_FACTOR: '2', NPM_CONFIG_FETCH_RETRY_MINTIMEOUT: '1000', NPM_CONFIG_FETCH_RETRY_MAXTIMEOUT: '10000' };
}
const safe = environment();
function git(...args) { return execFileSync('git', args, { cwd: source, env: safe, encoding: 'utf8', timeout: 30000 }).trim(); }
async function digest(file) { const hash = crypto.createHash('sha256'); for await (const part of fs.createReadStream(file)) hash.update(part); return hash.digest('hex'); }
async function main() {
assert.equal(process.platform, 'win32'); assert.equal(process.arch, 'x64');
fs.mkdirSync(output, { recursive: true });
assert.equal(git('rev-parse', 'HEAD'), pinned.sha);
assert.equal(git('config', '--get', 'remote.origin.url').replace(/\.git$/, ''), `https://github.com/${pinned.repository}`);
assert.equal(git('status', '--porcelain'), '', 'Exact source checkout must begin clean');
const originalSourceHash = await digest(path.join(source, 'application/state/useAIState.ts'));
const vswhere = path.join(process.env['ProgramFiles(x86)'], 'Microsoft Visual Studio/Installer/vswhere.exe');
const installation = execFileSync(vswhere, ['-latest', '-products', '*', '-requires', 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64', '-property', 'installationPath'], { env: safe, encoding: 'utf8', timeout: 30000 }).trim();
assert(installation, 'Stock Windows hosted MSVC installation required');
const vsScript = path.join(installation, 'Common7/Tools/Launch-VsDevShell.ps1');
assert(fs.existsSync(vsScript));
const script = `$ErrorActionPreference = 'Stop'
& $env:QA_VS_SCRIPT -Arch amd64 -HostArch amd64 -SkipAutomaticLocation
if (-not $?) { throw 'MSVC developer shell failed' }
Set-Location -LiteralPath $env:QA_FIX_SOURCE
Write-Output 'QA_BUILD_STEP npm ci'
& npm.cmd ci
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
Write-Output 'QA_BUILD_STEP repository non-release version metadata'
& npm.cmd pkg set "version=$env:QA_FIX_VERSION"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
Write-Output 'QA_BUILD_STEP npm run pack:win-x64 -- publish never'
& npm.cmd run pack:win-x64
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
Write-Output 'QA_BUILD_STEP packaged SSH cipher verification'
& node scripts/test-packaged-ssh-ciphers.cjs
exit $LASTEXITCODE`;
const child = spawn('pwsh.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { cwd: source, env: { ...safe, QA_FIX_SOURCE: source, QA_FIX_VERSION: pinned.version, QA_VS_SCRIPT: vsScript }, windowsHide: false, stdio: ['ignore', 'pipe', 'pipe'] });
child.on('error', error => logs.push(error.stack));
for (const stream of [child.stdout, child.stderr]) stream.on('data', part => { const text = String(part); logs.push(text); process.stdout.write(text); });
const code = await new Promise(resolve => child.once('close', resolve));
report.buildExit = code;
assert.equal(code, 0, 'Repository Windows packaging failed');
assert.equal(await digest(path.join(source, 'application/state/useAIState.ts')), originalSourceHash, 'Do not modify application source to package it');
assert.equal(git('rev-parse', 'HEAD'), pinned.sha);
const installer = path.join(source, 'release', pinned.installer);
assert(fs.existsSync(installer), 'Exact NSIS installer must be produced');
report.installerSha256 = await digest(installer);
report.installerBytes = fs.statSync(installer).size;
report.sourceFileSha256 = originalSourceHash;
report.versionMetadata = JSON.parse(fs.readFileSync(path.join(source, 'package.json'))).version;
assert.equal(report.versionMetadata, pinned.version);
fs.copyFileSync(installer, path.join(output, pinned.installer));
fs.appendFileSync(process.env.GITHUB_OUTPUT, `installer_sha=${report.installerSha256}\n`);
report.status = 'passed';
}
main().catch(error => { report.status = 'failed'; report.error = error.stack; process.exitCode = 1; }).finally(() => {
fs.mkdirSync(output, { recursive: true });
const log = logs.join('');
const sensitive = /(?:gh[opsu]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}|-----BEGIN (?:RSA |OPENSSH )?PRIVATE KEY-----|Authorization:\s*Bearer\s+\S+)/i.test(log);
report.logReview = sensitive ? 'blocked' : 'passed: no credentials supplied to build process; output pattern scan passed';
if (!sensitive) fs.writeFileSync(path.join(output, 'build.log'), log);
else { process.exitCode = 1; fs.rmSync(path.join(output, pinned.installer), { force: true }); }
fs.writeFileSync(path.join(output, 'build-provenance.json'), JSON.stringify(report, null, 2));
console.log(JSON.stringify(report, null, 2));
});
@@ -0,0 +1,26 @@
{
"repository": "binaricat/Netcatty",
"repositoryId": 1111357457,
"sha": "9d4e90b3aa8fe0a52d1a58e8ea8e61bdd3865e28",
"run": 44903060405,
"artifact": 14707595613,
"name": "netcatty-windows",
"zipSha256": "3a197f7b2510e34547168b066a470e70c454610500639670e356a8a24da1e502",
"installer": "Netcatty-0.0.0-sha-9d4e90b-win-x64.exe",
"version": "0.0.0-sha-9d4e90b",
"portableZip": "Netcatty-0.0.0-sha-9d4e90b-win-x64.zip",
"portableBaseline": {
"tag": "v1.1.90",
"asset": 677167676,
"installer": "Netcatty-1.1.90-win-x64.zip",
"sha256": "df057f03d122fb541168868d2d203c3723b8b731a663dbdaa5bc38390a742b88",
"url": "https://github.com/binaricat/Netcatty/releases/download/v1.1.90/Netcatty-1.1.90-win-x64.zip"
},
"baseline": {
"tag": "v1.1.90",
"asset": 677167660,
"installer": "Netcatty-1.1.90-win-x64.exe",
"sha256": "cf6a028a0286264fd1e315025b1f78e8c96c468d6a22d5058b64319410debdc9",
"url": "https://github.com/binaricat/Netcatty/releases/download/v1.1.90/Netcatty-1.1.90-win-x64.exe"
}
}
+510
View File
@@ -0,0 +1,510 @@
// Operates the installed, unmodified Electron application through its real GUI.
// Storage and native debugger calls below observe state; all test data is seeded
// through normal controls and a deterministic model bound only to loopback.
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const http = require('node:http');
const net = require('node:net');
const vm = require('node:vm');
const crypto = require('node:crypto');
const { spawn, execFileSync } = require('node:child_process');
const { chromium } = require('playwright-core');
const pinned = require(path.resolve(__dirname, process.env.QA_CANDIDATE || 'candidate.json'));
const portable = process.env.QA_MODE === 'portable';
const root = path.resolve(process.env.QA_ROOT);
const evidence = path.join(root, 'evidence');
const staging = path.join(root, 'unreviewed');
const home = path.join(root, 'user');
const profile = path.join(root, 'profile');
const installDir = path.join(root, 'app');
let executable = path.join(installDir, 'Netcatty.exe');
const hostLabel = 'QA Windows Loopback';
const report = {
candidate: pinned.sha, qaHead: process.env.QA_HEAD_SHA, mode: portable ? 'portable ZIP' : 'NSIS installed',
testPackageOrigin: pinned.qaBuilt ? 'Exact trusted fix SHA, CI QA-built NSIS; unsigned/unreleased, not released automatic updater acceptance' : 'Pinned official package',
baselineInstall: 'not_run', baselineGuiSeed: 'not_run', installerReplacement: 'not_run',
candidateInstall: 'not_run', aiHistoryMigration: 'not_run', restartPersistence: 'not_run',
scope: portable ? 'Independent official Windows ZIP extraction and real native Electron GUI migration; no installation, replacement or updater coverage. CDP PNGs are actual renderer captures. Synthetic data only.' : 'Real per-user NSIS and installed native Electron renderer on ephemeral windows-2022; CDP PNGs are actual renderer captures, not OS desktop captures. Synthetic data only.',
updater: 'not_covered: CI candidate 0.0.0-sha version is not a released automatic updater test',
security: 'Stock application sandbox settings; no disabling flags, privilege or system security changes',
events: [], installers: [], launches: [],
};
const logs = [];
const replies = new Map([
['QA_ALPHA_USER_ONE', 'QA_ALPHA_REPLY_ONE'], ['QA_ALPHA_USER_TWO', 'QA_ALPHA_REPLY_TWO'],
['QA_BETA_USER_ONE', 'QA_BETA_REPLY_ONE'], ['QA_BETA_USER_TWO', 'QA_BETA_REPLY_TWO'],
['QA_BETA_AFTER_UPGRADE', 'QA_BETA_REPLY_AFTER_UPGRADE'],
]);
let app, browser, page, inspector, fixture, watchdog;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
function event(label, detail) { report.events.push({ at: new Date().toISOString(), label, detail }); console.log(label); }
async function until(label, check, timeout = 20000) {
const deadline = Date.now() + timeout;
let last;
while (Date.now() < deadline) {
try { const result = await check(); if (result) return result; } catch (error) { if (error instanceof SyntaxError) throw error; last = error; }
await sleep(200);
}
throw new Error(`Timed out: ${label}${last ? `: ${last.message}` : ''}`);
}
function childExit(child, timeout) {
if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);
return new Promise(resolve => {
const finish = () => { clearTimeout(timer); resolve(true); };
const timer = setTimeout(() => { child.off('exit', finish); resolve(false); }, timeout);
child.once('exit', finish);
});
}
async function freePort() {
const server = net.createServer();
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const port = server.address().port;
await new Promise(resolve => server.close(resolve));
return port;
}
function isolatedEnvironment(installer = false) {
const allowed = ['PATH', 'SystemRoot', 'SystemDrive', 'WINDIR', 'ComSpec', 'PATHEXT', 'ProgramFiles', 'ProgramFiles(x86)', 'ProgramData', 'ALLUSERSPROFILE', 'PUBLIC', 'OS', 'PROCESSOR_ARCHITECTURE', 'NUMBER_OF_PROCESSORS', 'USERNAME', 'USERDOMAIN', 'USERDNSDOMAIN', 'COMPUTERNAME', 'SESSIONNAME', 'PSModulePath', 'PSHOME'];
const env = {};
for (const key of allowed) if (process.env[key]) env[key] = process.env[key];
Object.assign(env, { USERPROFILE: home, HOME: home, APPDATA: path.join(home, 'AppData', 'Roaming'), LOCALAPPDATA: path.join(home, 'AppData', 'Local'), TEMP: path.join(root, 'temp'), TMP: path.join(root, 'temp') });
for (const dir of [home, env.APPDATA, env.LOCALAPPDATA, env.TEMP]) fs.mkdirSync(dir, { recursive: true });
// NSIS uses the real ephemeral Windows user's shell folders. Its explicit
// installation directory remains QA-owned; only the application gets the
// synthetic home/profile. Do not change Windows account or registry paths.
if (installer) for (const key of ['USERPROFILE', 'HOME', 'APPDATA', 'LOCALAPPDATA', 'HOMEDRIVE', 'HOMEPATH']) if (process.env[key]) env[key] = process.env[key];
return env;
}
function osCommand(script, timeout = 20000, extra = {}) {
return execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { env: { ...isolatedEnvironment(true), ...extra }, encoding: 'utf8', timeout });
}
function installerDiagnostic(label, pid) {
const result = { executableExists: fs.existsSync(executable), installFiles: fs.existsSync(installDir) ? fs.readdirSync(installDir) : [] };
try {
result.process = osCommand(`Get-CimInstance Win32_Process -Filter "ProcessId=$env:QA_NSIS_PID" | Select-Object Name,ProcessId,ParentProcessId,ExecutablePath,CommandLine | ConvertTo-Json; Get-Process | Where-Object {$_.ProcessName -like '*Netcatty*'} | Select-Object ProcessName,Id,MainWindowTitle,Responding,SessionId | ConvertTo-Json`, 10000, { QA_NSIS_PID: String(pid) });
} catch (error) { result.processError = error.message; }
try {
result.desktop = osCommand(`Add-Type -AssemblyName System.Windows.Forms; Add-Type -AssemblyName System.Drawing
$b = [Windows.Forms.Screen]::PrimaryScreen.Bounds
$bitmap = [Drawing.Bitmap]::new($b.Width,$b.Height); $g = [Drawing.Graphics]::FromImage($bitmap)
$g.CopyFromScreen($b.Location,[Drawing.Point]::Empty,$b.Size)
$bitmap.Save($env:QA_NATIVE_PNG,[Drawing.Imaging.ImageFormat]::Png); $g.Dispose(); $bitmap.Dispose(); 'Actual OS desktop captured'`, 10000, { QA_NATIVE_PNG: path.join(staging, `installer-${label.replace(/[^a-z0-9]/gi, '-')}.png`) });
} catch (error) { result.desktopError = error.message; }
try {
const source = `using System; using System.Text; using System.Runtime.InteropServices;
public class QaWindows { public delegate bool Callback(IntPtr h, IntPtr p);
[DllImport("user32.dll")] public static extern bool EnumWindows(Callback cb, IntPtr p);
[DllImport("user32.dll")] public static extern bool EnumChildWindows(IntPtr h, Callback cb, IntPtr p);
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern int GetWindowText(IntPtr h, StringBuilder b, int n);
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid); }`;
const script = `Add-Type -TypeDefinition $env:QA_NATIVE_SOURCE
$items = [Collections.Generic.List[object]]::new()
[QaWindows]::EnumWindows({param($h,$p)
[uint32]$owner = 0; [void][QaWindows]::GetWindowThreadProcessId($h,[ref]$owner)
$proc = Get-Process -Id $owner -ErrorAction SilentlyContinue
if ($proc.ProcessName -like '*Netcatty*') {
$text = [Text.StringBuilder]::new(4096); [void][QaWindows]::GetWindowText($h,$text,4096)
$items.Add(@{process=$proc.ProcessName;pid=$owner;text=$text.ToString()})
[QaWindows]::EnumChildWindows($h,{param($child,$unused)
$body = [Text.StringBuilder]::new(4096); [void][QaWindows]::GetWindowText($child,$body,4096)
if ($body.Length) {$items.Add(@{childText=$body.ToString()})}; return $true
},[IntPtr]::Zero) | Out-Null
}; return $true
},[IntPtr]::Zero) | Out-Null
$items | ConvertTo-Json -Depth 5`;
result.windows = osCommand(script, 10000, { QA_NATIVE_SOURCE: source });
} catch (error) { result.windowError = error.message; }
return result;
}
class Inspector {
constructor(url) {
this.ws = new WebSocket(url); this.id = 0; this.pending = new Map();
this.ws.addEventListener('message', event => {
const message = JSON.parse(event.data);
const item = this.pending.get(message.id);
if (!item) return;
this.pending.delete(message.id);
if (message.error) item.reject(new Error(message.error.message)); else item.resolve(message.result);
});
}
async connect() {
await new Promise((resolve, reject) => { this.ws.addEventListener('open', resolve, { once: true }); this.ws.addEventListener('error', reject, { once: true }); });
}
async eval(expression) {
if (typeof expression === 'function') expression = `(${expression.toString()})()`;
new vm.Script(expression); // Validate generated debugger code before sending.
const id = ++this.id;
const result = await new Promise((resolve, reject) => {
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error('Native inspector timeout')); }, 12000);
this.pending.set(id, { resolve: v => { clearTimeout(timer); resolve(v); }, reject: e => { clearTimeout(timer); reject(e); } });
this.ws.send(JSON.stringify({ id, method: 'Runtime.evaluate', params: { expression, returnByValue: true, awaitPromise: true } }));
});
if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
return result.result.value;
}
close() { this.ws.close(); }
}
async function install(installer, label, uninstall = false) {
assert(!app || app.exitCode !== null, 'Close app before official installer');
const args = uninstall ? ['/S', '/currentuser'] : ['/S', '/currentuser', `/D=${installDir}`];
const started = Date.now();
const child = spawn(installer, args, { env: isolatedEnvironment(true), windowsHide: false, stdio: 'ignore' });
let output = '';
let spawnError;
child.on('error', error => { spawnError = error; });
const completed = await childExit(child, 90000);
const diagnostic = !completed ? installerDiagnostic(label, child.pid) : undefined;
if (!completed) child.kill();
const result = { label, installer: path.basename(installer), arguments: args, exitCode: child.exitCode, completed, durationMs: Date.now() - started, output, error: spawnError?.message, diagnostic };
report.installers.push(result); event(`installer ${label}`, result);
return completed && child.exitCode === 0 && !spawnError;
}
async function startModel() {
const calls = [];
const server = http.createServer(async (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'content-type,authorization,x-api-key');
if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
if (req.url === '/v1/models') { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ object: 'list', data: [{ id: 'qa-history-fixture', object: 'model', owned_by: 'synthetic-loopback' }] })); return; }
if (req.url !== '/v1/chat/completions' || req.method !== 'POST') { res.writeHead(404); res.end(); return; }
let raw = '';
for await (const part of req) { raw += part; if (raw.length > 4e6) { res.writeHead(413); res.end(); return; } }
const body = JSON.parse(raw);
const last = body.messages?.filter(m => m.role === 'user').at(-1)?.content;
const content = typeof last === 'string' ? last : (last || []).filter(p => p.type === 'text').map(p => p.text).join('\n');
const matched = [...replies.keys()].find(text => content?.includes(text));
calls.push({ at: new Date().toISOString(), prompt: matched || 'UNEXPECTED_SYNTHETIC_REQUEST', model: body.model, stream: body.stream });
const reply = replies.get(matched) || 'QA_UNEXPECTED_PROMPT';
if (!body.stream) {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ id: 'qa', object: 'chat.completion', choices: [{ index: 0, message: { role: 'assistant', content: reply }, finish_reason: 'stop' }] })); return;
}
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
const chunk = (delta, finish_reason = null) => `data: ${JSON.stringify({ id: 'qa', object: 'chat.completion.chunk', created: 1700000000, model: 'qa-history-fixture', choices: [{ index: 0, delta, finish_reason }] })}\n\n`;
res.write(chunk({ role: 'assistant', content: reply }));
await sleep(100);
res.write(chunk({}, 'stop')); res.end('data: [DONE]\n\n');
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
return { server, calls, port: server.address().port };
}
async function screenshot(name, target = page) {
if (target && !target.isClosed()) {
const png = await target.screenshot({ path: path.join(staging, `${name}.png`), timeout: 10000 });
(report.screenshots ||= []).push({ name: `${name}.png`, bytes: png.length, width: png.readUInt32BE(16), height: png.readUInt32BE(20), sha256: crypto.createHash('sha256').update(png).digest('hex'), scope: 'Actual native application renderer' });
}
}
async function launch(label, expectedVersion) {
assert(fs.existsSync(executable), 'Official installer must create Netcatty.exe');
const port = await freePort(), inspectPort = await freePort();
app = spawn(executable, [`--user-data-dir=${profile}`, '--remote-debugging-address=127.0.0.1', `--remote-debugging-port=${port}`, `--inspect=127.0.0.1:${inspectPort}`], {
cwd: path.dirname(executable), env: isolatedEnvironment(), windowsHide: false, stdio: ['ignore', 'pipe', 'pipe'],
});
app.on('error', error => logs.push(`${label}: ${error.message}`));
for (const name of ['stdout', 'stderr']) app[name].on('data', part => logs.push(`[${label} ${name}] ${part}`));
const info = await until(`${label} native debugger`, async () => {
assert.equal(app.exitCode, null, 'Installed app exited before debugger');
const response = await fetch(`http://127.0.0.1:${inspectPort}/json/list`, { signal: AbortSignal.timeout(1000) });
return (await response.json())[0];
}, 45000);
inspector = new Inspector(info.webSocketDebuggerUrl); await inspector.connect();
await until(`${label} Chromium debugger ready`, async () => {
assert.equal(app.exitCode, null, 'Real app exited before Chromium debugger');
const response = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1000) });
return (await response.json()).webSocketDebuggerUrl;
}, 45000);
await until(`${label} actual native renderer ready`, () => inspector.eval(async () => {
const e = process.mainModule.require('electron');
const w = e.BrowserWindow.getAllWindows().find(w => w.webContents.getURL().startsWith('app://netcatty/index.html') && !w.webContents.getURL().includes('settings'));
return !!w && !w.webContents.isLoadingMainFrame() && await w.webContents.executeJavaScript("!!document.querySelector('[data-section=\"top-tabs-toolbar-actions\"]')");
}), 45000);
const native = await inspector.eval(`(() => {
const e = process.mainModule.require('electron');
const w = e.BrowserWindow.getAllWindows().find(w => w.webContents.getURL().startsWith('app://netcatty/index.html') && !w.webContents.getURL().includes('settings'));
w.setSize(1440, 1000); w.show(); w.focus();
return { version:e.app.getVersion(), packaged:e.app.isPackaged, appPath:e.app.getAppPath(), profile:e.app.getPath('userData'), executable:process.execPath,
origin:w.webContents.getURL(), argv:process.argv, preferences:w.webContents.getLastWebPreferences(),
noSandbox:e.app.commandLine.hasSwitch('no-sandbox'), disableSetuidSandbox:e.app.commandLine.hasSwitch('disable-setuid-sandbox') };
})()`);
report.launches.push({ label, ...native });
assert.equal(native.version, expectedVersion);
assert.equal(native.packaged, true);
assert.equal(path.resolve(native.profile).toLowerCase(), profile.toLowerCase());
assert.equal(path.resolve(native.executable).toLowerCase(), executable.toLowerCase());
assert(native.appPath.toLowerCase().startsWith(path.dirname(executable).toLowerCase()));
assert.equal(native.noSandbox, false); assert.equal(native.disableSetuidSandbox, false);
event(`launched ${label}`, { version: native.version, origin: native.origin });
const nativePng = await inspector.eval(`(async () => {
const e = process.mainModule.require('electron');
const w = e.BrowserWindow.getAllWindows().find(w => w.webContents.getURL().startsWith('app://netcatty/index.html') && !w.webContents.getURL().includes('settings'));
return (await w.webContents.capturePage()).toPNG().toString('base64');
})()`);
fs.writeFileSync(path.join(staging, `native-launch-${label}.png`), Buffer.from(nativePng, 'base64'));
browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`, { timeout: 30000 });
browser.contexts()[0].setDefaultTimeout(12000);
page = await until(`${label} actual app page`, () => browser.contexts()[0].pages().find(p => p.url().startsWith('app://netcatty/index.html') && !p.url().includes('settings')));
await page.locator('[data-section="top-tabs-toolbar-actions"]').waitFor({ timeout: 15000 });
await screenshot(`launch-${label}`);
return native.version;
}
async function quit() {
if (!app) return;
if (inspector) {
try { await inspector.eval("setImmediate(() => process.mainModule.require('electron').app.quit()); true"); } catch {}
inspector.close(); inspector = null;
}
// Node inspector must disconnect before Electron can exit normally.
assert(await childExit(app, 20000), 'App did not complete normal quit; do not call persistence passed');
browser = null; page = null;
}
async function snapshot() {
return page.evaluate(async () => {
const read = key => { const value = localStorage.getItem(key); return value ? JSON.parse(value) : null; };
const result = { origin: location.origin, legacy: read('netcatty_ai_sessions_v1'), activeMap: read('netcatty_ai_active_session_map_v1'), hosts: read('netcatty_hosts_v1'), databases: await indexedDB.databases(), liveTabs: [...document.querySelectorAll('[data-tab-type="session"]')].map(e => ({ id: e.getAttribute('data-tab-id'), text: e.textContent })) };
if (result.databases.some(db => db.name === 'netcatty_ai_sessions')) {
result.idb = await new Promise((resolve, reject) => {
const request = indexedDB.open('netcatty_ai_sessions');
request.onerror = () => reject(request.error);
request.onsuccess = () => {
const db = request.result, tx = db.transaction(['sessions', 'meta'], 'readonly');
const sessions = tx.objectStore('sessions').getAll(), meta = tx.objectStore('meta').getAll();
tx.oncomplete = () => { db.close(); resolve({ sessions: sessions.result, meta: meta.result }); };
tx.onerror = () => { db.close(); reject(tx.error); };
};
});
}
return result;
});
}
function sessionWith(snapshot, marker) {
return (snapshot.idb?.sessions || snapshot.legacy || []).find(s => s.messages.some(m => m.role === 'user' && m.content.includes(marker)));
}
function messages(session) { return session.messages.filter(m => m.role === 'user' || m.role === 'assistant').map(m => ({ id: m.id, role: m.role, content: m.content, timestamp: m.timestamp })); }
async function configureProvider() {
await page.locator('[data-section="top-tabs-toolbar-actions"] button:has(svg.lucide-settings)').click();
const settings = await until('native settings window', () => browser.contexts()[0].pages().find(p => p.url().includes('settings')));
await settings.getByRole('tab', { name: 'AI', exact: true }).click();
await settings.getByRole('tab', { name: 'Providers', exact: true }).click();
await settings.getByRole('button', { name: 'Add Provider', exact: true }).click();
await settings.getByRole('button', { name: 'Custom', exact: true }).click();
await settings.getByPlaceholder('e.g. My Provider').fill('QA Loopback');
await settings.getByPlaceholder('Enter API key').fill('qa-local-only');
await settings.getByPlaceholder('https://', { exact: true }).fill(`http://127.0.0.1:${fixture.port}/v1`);
await settings.getByPlaceholder(/Search or type model ID|e\.g\. gpt-4o/).fill('qa-history-fixture');
const chat = settings.getByRole('button', { name: 'Chat Completions', exact: true });
if (await chat.count()) await chat.click();
await settings.getByRole('button', { name: 'Save', exact: true }).click();
const enable = settings.getByRole('switch', { checked: false }).first();
await enable.click();
await until('provider enabled', () => settings.getByRole('switch', { checked: true }).count());
// Close via normal native-window control; settings is a real separate window.
await settings.getByRole('button', { name: 'Close', exact: true }).click();
await page.bringToFront(); event('Configured normal loopback OpenAI provider');
}
async function saveHost() {
await page.getByRole('button', { name: 'New Host', exact: true }).click();
await page.getByPlaceholder('Label (e.g., Production Server)', { exact: true }).fill(hostLabel);
await page.getByPlaceholder('IP or Hostname', { exact: true }).fill('127.0.0.1');
await page.getByPlaceholder('Username', { exact: true }).fill('synthetic-qa');
await page.locator('button[aria-label="Save"]').click();
await until('GUI saved loopback host', async () => (await snapshot()).hosts?.some(h => h.label === hostLabel && (h.hostname === '127.0.0.1' || h.address === '127.0.0.1')));
await page.getByText(hostLabel, { exact: true }).filter({ visible: true }).first().waitFor();
event('Synthetic host saved through actual GUI');
}
async function aiPanel(restore = false) {
if (!restore) {
await page.keyboard.press('Control+t');
await page.locator('.xterm-helper-textarea').first().waitFor({ state: 'attached' });
}
let panel = page.locator('[data-section="ai-chat-panel"]:visible');
if (!(await panel.count())) await page.locator('[data-section="top-tabs-toolbar-actions"] button:has(svg.lucide-sparkles)').click();
await panel.waitFor({ state: 'visible' });
return panel;
}
async function send(panel, prompt) {
const input = panel.locator('textarea:visible').first();
await input.fill(prompt); await input.press('Enter');
await panel.getByText(replies.get(prompt), { exact: true }).waitFor({ timeout: 45000 });
await until(`stored full reply ${prompt}`, async () => sessionWith(await snapshot(), prompt)?.messages.some(m => m.role === 'assistant' && m.content === replies.get(prompt)), 20000);
event('Normal AI turn completed', { prompt, reply: replies.get(prompt) });
}
async function chooseChat(panel, marker) {
await panel.locator('button:has(svg.lucide-history)').click();
await panel.getByText(marker, { exact: true }).first().click();
await panel.getByText(replies.get(marker), { exact: true }).waitFor();
}
async function assertChats(baseline, current, afterAppend = false, pointerSource = baseline) {
const a = sessionWith(current, 'QA_ALPHA_USER_ONE'), b = sessionWith(current, 'QA_BETA_USER_ONE');
assert(a && b, 'Both distinct chats must exist'); assert.notEqual(a.id, b.id);
const oldA = sessionWith(baseline, 'QA_ALPHA_USER_ONE'), oldB = sessionWith(baseline, 'QA_BETA_USER_ONE');
assert.equal(a.id, oldA.id); assert.equal(b.id, oldB.id);
assert.deepEqual(messages(a), messages(oldA), 'Alpha complete turns and identities preserved');
assert.deepEqual(messages(b).slice(0, 4), messages(oldB), 'Beta original full turns and identities preserved');
assert.equal(messages(b).length, afterAppend ? 6 : 4);
if (afterAppend) assert.deepEqual(messages(b).slice(-2).map(m => [m.role, m.content]), [['user', 'QA_BETA_AFTER_UPGRADE'], ['assistant', 'QA_BETA_REPLY_AFTER_UPGRADE']]);
assert(current.hosts.some(h => h.id === baseline.hosts.find(h => h.label === hostLabel).id && h.label === hostLabel));
assert(current.idb, 'Candidate must use the real AI IndexedDB');
assert(current.idb.meta.some(m => m.key === 'migrationCompleted' && m.value?.migrationCompleted === true));
const active = current.idb.meta.find(m => m.key === 'activeSessionMap')?.value;
assert(active && typeof active === 'object', 'IndexedDB meta.activeSessionMap must exist directly; no legacy fallback');
const originalPointerMap = pointerSource.idb ? pointerSource.idb.meta.find(m => m.key === 'activeSessionMap')?.value : pointerSource.activeMap;
const activeKey = Object.keys(originalPointerMap || {}).find(key => originalPointerMap[key] === oldB.id);
assert.equal(current.origin, baseline.origin, 'Actual app origin must stay identical');
assert.deepEqual(a.scope, oldA.scope); assert.deepEqual(b.scope, oldB.scope);
const pointer = { phase: afterAppend ? 'restarted' : 'migrated', expectedKey: activeKey, expectedBeta: oldB.id, originalScope: oldB.scope, baselineMap: originalPointerMap, actualIdbMap: active, actualLegacyMap: current.activeMap, baselineLiveTabs: baseline.liveTabs, liveTabs: current.liveTabs };
(report.activePointerChecks ||= []).push(pointer);
if (!activeKey) {
pointer.status = 'untested: no positive pointer persisted by the source GUI';
(report.coverageGaps ||= []).push({ phase: pointer.phase, assertion: 'active pointer preservation', reason: pointer.status });
} else try {
assert.equal(active[activeKey], oldB.id, 'Exact original scope-to-session active pointer preserved');
pointer.status = 'passed';
} catch (error) {
pointer.status = 'failed'; pointer.failure = error.message;
(report.validationFailures ||= []).push({ phase: pointer.phase, assertion: 'original active Beta pointer in IndexedDB', message: error.message });
process.exitCode = 1;
}
return { alpha: a.id, beta: b.id, activeMap: active, activePointer: pointer.status, originalRecordsAndScope: 'passed', savedHost: 'passed', alphaMessages: messages(a).length, betaMessages: messages(b).length };
}
async function main() {
assert.equal(process.platform, 'win32');
assert(!process.env.GH_TOKEN && !process.env.GITHUB_TOKEN, 'Application/test step must not receive GitHub token');
fs.mkdirSync(evidence, { recursive: true }); fs.mkdirSync(staging, { recursive: true });
assert(!fs.existsSync(profile), 'Only a fresh QA profile may be seeded');
report.processPreflight = osCommand("'QA_WINDOWS_PROCESS_PREFLIGHT'; [Environment]::UserName; [Environment]::OSVersion.VersionString", 10000);
event('Windows process preflight passed');
watchdog = setTimeout(() => { report.error = 'Harness global timeout'; finish().finally(() => process.exit(1)); }, 11 * 60 * 1000);
fixture = await startModel();
if (portable) {
executable = path.join(root, 'baseline-portable', 'Netcatty.exe');
report.baselineInstall = 'not_covered: official ZIP extraction';
report.installerReplacement = 'not_covered: separate portable migration job';
report.candidateInstall = 'not_covered: official ZIP extraction';
} else {
assert(await install(path.join(root, pinned.baseline.installer), 'baseline v1.1.90'), 'Baseline NSIS failed'); report.baselineInstall = 'passed';
}
await launch('baseline', '1.1.90');
await configureProvider(); await saveHost();
let panel = await aiPanel();
await send(panel, 'QA_ALPHA_USER_ONE'); await send(panel, 'QA_ALPHA_USER_TWO');
await screenshot('01-baseline-alpha');
await panel.locator('button:has(svg.lucide-plus)').first().click();
await send(panel, 'QA_BETA_USER_ONE'); await send(panel, 'QA_BETA_USER_TWO');
await screenshot('02-baseline-beta-active');
// Explicit normal history selection gives the released GUI a bounded chance
// to persist Beta before asking the candidate to migrate a positive pointer.
await chooseChat(panel, 'QA_ALPHA_USER_ONE');
await chooseChat(panel, 'QA_BETA_USER_ONE');
let baseline;
try {
baseline = await until('released GUI positive active Beta pointer', async () => {
const value = await snapshot(), beta = sessionWith(value, 'QA_BETA_USER_ONE');
return beta && value.activeMap?.[`terminal:${beta.scope.targetId}`] === beta.id && value;
}, 4000);
report.baselinePointerSeed = { status: 'passed', map: baseline.activeMap };
} catch {
baseline = await snapshot();
report.baselinePointerSeed = { status: 'untested: released GUI did not persist a positive Beta pointer after History Alpha then Beta', map: baseline.activeMap, beta: sessionWith(baseline, 'QA_BETA_USER_ONE')?.id, scope: sessionWith(baseline, 'QA_BETA_USER_ONE')?.scope, liveTabs: baseline.liveTabs };
}
assert(!baseline.idb, 'Released baseline must exercise legacy-to-IDB migration');
assert.equal(messages(sessionWith(baseline, 'QA_ALPHA_USER_ONE')).length, 4);
assert.equal(messages(sessionWith(baseline, 'QA_BETA_USER_ONE')).length, 4);
fs.writeFileSync(path.join(evidence, 'baseline-storage.json'), JSON.stringify(baseline, null, 2));
report.baselineGuiSeed = 'passed'; await quit();
if (portable) executable = path.join(root, 'candidate-portable', 'Netcatty.exe');
else {
const replaced = await install(path.join(root, pinned.installer), 'candidate replacement');
if (!replaced) {
report.installerReplacement = 'blocked_or_failed: see installer exit/output; CI version is older than 1.1.90';
// Normal uninstall/reinstall is separately labelled. Never patch the package
// or bypass an official installer version check; keep the custom profile.
const uninstall = path.join(installDir, 'Uninstall Netcatty.exe');
assert(fs.existsSync(uninstall), 'Normal uninstaller unavailable');
assert(await install(uninstall, 'baseline normal uninstall (preserve explicit QA profile)', true));
assert(await install(path.join(root, pinned.installer), 'candidate fresh install preserving QA profile'), 'Candidate fresh NSIS failed');
report.candidateInstall = 'passed: fresh install after normal baseline uninstall; migration uses original profile';
} else { report.installerReplacement = 'passed: normal per-user NSIS replacement'; report.candidateInstall = 'passed'; }
}
await launch('candidate-after-install', pinned.version);
const beforePanel = await until('candidate migration marker before panel navigation', async () => {
const value = await snapshot();
return value.idb?.meta.some(m => m.key === 'migrationCompleted' && m.value?.migrationCompleted === true) && value;
});
fs.writeFileSync(path.join(evidence, 'candidate-before-panel-storage.json'), JSON.stringify(beforePanel, null, 2));
report.candidateBeforePanel = { activeMap: beforePanel.activeMap, idbMeta: beforePanel.idb?.meta, liveTabs: beforePanel.liveTabs };
panel = await aiPanel(true);
const migrated = await until('IDB migration completed', async () => {
const value = await snapshot();
return value.idb?.meta.some(m => m.key === 'migrationCompleted' && m.value?.migrationCompleted === true) && value;
});
fs.writeFileSync(path.join(evidence, 'candidate-migrated-storage.json'), JSON.stringify(migrated, null, 2));
report.migratedChats = await assertChats(baseline, beforePanel);
report.afterOpeningPanelActiveMap = migrated.idb?.meta.find(m => m.key === 'activeSessionMap')?.value;
report.candidateInitialView = { automaticallyOpenedBeta: await panel.getByText('QA_BETA_REPLY_TWO', { exact: true }).isVisible(), visibleText: await panel.innerText(), policy: 'Stock panelViewByScope is memory-only; exact persisted active pointer checked before any chat selection' };
await screenshot('candidate-initial-view-before-history-selection');
if (!report.candidateInitialView.automaticallyOpenedBeta) await chooseChat(panel, 'QA_BETA_USER_ONE');
await panel.getByText('QA_BETA_REPLY_TWO', { exact: true }).waitFor();
await screenshot('03-candidate-beta-active');
await chooseChat(panel, 'QA_ALPHA_USER_ONE'); await screenshot('04-candidate-alpha');
await chooseChat(panel, 'QA_BETA_USER_ONE');
report.aiHistoryMigration = `original records/full turns/scope/host PASSED; active pointer ${report.migratedChats.activePointer}`;
await send(panel, 'QA_BETA_AFTER_UPGRADE'); await screenshot('05-candidate-appended');
const beforeRestart = pinned.requirePositiveCandidatePointer ? await until('patched candidate persists a positive Beta pointer before quit', async () => {
const value = await snapshot(), beta = sessionWith(value, 'QA_BETA_USER_ONE');
const map = value.idb?.meta.find(m => m.key === 'activeSessionMap')?.value;
return beta && map?.[`${beta.scope.type}:${beta.scope.targetId ?? ''}`] === beta.id && value;
}, 5000) : await snapshot();
fs.writeFileSync(path.join(evidence, 'candidate-before-quit-storage.json'), JSON.stringify(beforeRestart, null, 2));
report.beforeRestartPointer = { idbMap: beforeRestart.idb?.meta.find(m => m.key === 'activeSessionMap')?.value, legacyMap: beforeRestart.activeMap };
await quit(); await launch('candidate-restarted', pinned.version);
const restartBeforePanel = await snapshot();
fs.writeFileSync(path.join(evidence, 'restarted-before-panel-storage.json'), JSON.stringify(restartBeforePanel, null, 2));
report.restartBeforePanel = { activeMap: restartBeforePanel.activeMap, idbMeta: restartBeforePanel.idb?.meta, liveTabs: restartBeforePanel.liveTabs };
panel = await aiPanel(true);
const restarted = await snapshot();
fs.writeFileSync(path.join(evidence, 'candidate-restarted-storage.json'), JSON.stringify(restarted, null, 2));
report.restartedChats = await assertChats(baseline, restartBeforePanel, true, beforeRestart);
report.afterRestartOpeningPanelActiveMap = restarted.idb?.meta.find(m => m.key === 'activeSessionMap')?.value;
report.restartInitialView = { automaticallyOpenedBeta: await panel.getByText('QA_BETA_REPLY_AFTER_UPGRADE', { exact: true }).isVisible(), visibleText: await panel.innerText(), policy: 'Report automatic view restoration separately from unchanged IndexedDB active pointer and complete persisted turns' };
await screenshot('restarted-initial-view-before-history-selection');
if (!report.restartInitialView.automaticallyOpenedBeta) await chooseChat(panel, 'QA_BETA_USER_ONE');
await panel.getByText('QA_BETA_REPLY_AFTER_UPGRADE', { exact: true }).waitFor();
await screenshot('06-candidate-restarted');
report.restartPersistence = `original and appended turns/scope/host PASSED; active pointer ${report.restartedChats.activePointer}`;
report.targetedCandidateRestartRegression = report.restartedChats.activePointer === 'passed' ? 'passed: positive candidate-created IDB Beta pointer and full new/original contents survived complete restart' : 'failed or untested: read activePointerChecks';
report.overall = report.validationFailures?.length ? 'failed: read individual validation failures' : report.coverageGaps?.length ? 'partial: independent data assertions passed; positive legacy pointer not available' : 'passed';
await quit(); event('Windows installed real GUI acceptance completed');
}
let finishing;
async function finish() {
if (finishing) return finishing;
finishing = (async () => {
clearTimeout(watchdog);
if ((report.error || report.validationFailures?.length) && browser) {
for (const [index, target] of browser.contexts()[0].pages().entries()) {
try { await screenshot(`failure-${index}`, target); } catch {}
try {
const text = await target.locator('body').innerText({ timeout: 3000 });
fs.writeFileSync(path.join(evidence, `failure-${index}-visible-ui.txt`), text);
(report.failureVisibleUI ||= []).push({ page: index, text: text.slice(-14000) });
} catch {}
}
}
if (report.error && app && !browser) report.nativeFailureDiagnostic = installerDiagnostic('application-launch-failure', app.pid);
try { await quit(); } catch (error) { report.cleanupError = error.message; app?.kill(); }
if (fixture) { fixture.server.closeAllConnections(); fixture.server.close(); report.modelCalls = fixture.calls; }
const stderr = logs.join('\n');
// Only synthetic app data and no tokens/credentials may leave this runner.
const secretPattern = /(?:gh[opsu]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}|-----BEGIN (?:RSA |OPENSSH )?PRIVATE KEY-----|Bearer\s+(?!qa-local-only)[A-Za-z0-9_.-]{20,})/i;
report.evidenceReview = secretPattern.test(stderr) ? 'failed: raw app logs and PNGs withheld' : 'passed: app logs checked for credential patterns; only known synthetic GUI data';
if (!secretPattern.test(stderr)) {
fs.writeFileSync(path.join(evidence, 'app-output.log'), stderr);
console.log('Reviewed actual application output:\n' + stderr);
for (const file of fs.readdirSync(staging)) fs.copyFileSync(path.join(staging, file), path.join(evidence, file));
} else { report.error ||= 'Evidence sensitive-data review failed'; process.exitCode = 1; }
fs.writeFileSync(path.join(evidence, 'assertions.json'), JSON.stringify(report, null, 2));
console.log(JSON.stringify(report, null, 2));
})();
return finishing;
}
main().catch(error => { report.error = error.stack; process.exitCode = 1; }).finally(finish);
@@ -0,0 +1,18 @@
{
"repository": "binaricat/Netcatty",
"repositoryId": 1111357457,
"sha": "4516d3aed7cb54862dabd53abb56a7f90fba3212",
"base": "9d4e90b3aa8fe0a52d1a58e8ea8e61bdd3865e28",
"sourcePr": 4302,
"qaBuilt": true,
"requirePositiveCandidatePointer": true,
"version": "0.0.0-sha-4516d3a",
"installer": "Netcatty-0.0.0-sha-4516d3a-win-x64.exe",
"baseline": {
"tag": "v1.1.90",
"asset": 677167660,
"installer": "Netcatty-1.1.90-win-x64.exe",
"sha256": "cf6a028a0286264fd1e315025b1f78e8c96c468d6a22d5058b64319410debdc9",
"url": "https://github.com/binaricat/Netcatty/releases/download/v1.1.90/Netcatty-1.1.90-win-x64.exe"
}
}
+27
View File
@@ -0,0 +1,27 @@
{
"name": "netcatty-official-windows-qa",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "netcatty-official-windows-qa",
"version": "1.0.0",
"dependencies": {
"playwright-core": "1.56.1"
}
},
"node_modules/playwright-core": {
"version": "1.56.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.56.1.tgz",
"integrity": "sha512-hutraynyn31F+Bifme+Ps9Vq59hKuUCz7H1kDOcBs+2oGguKkWTU50bBWrtz34OUWmIwpBTWDxaRPXrIXkgvmQ==",
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=18"
}
}
}
}
+7
View File
@@ -0,0 +1,7 @@
{
"name": "netcatty-official-windows-qa",
"private": true,
"version": "1.0.0",
"description": "QA-only native installed Windows application acceptance",
"dependencies": { "playwright-core": "1.56.1" }
}
@@ -0,0 +1,33 @@
// Token is scoped to public release metadata/download in this step only.
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const { Readable } = require('node:stream');
const { pipeline } = require('node:stream/promises');
const pinned = require('./fixed-candidate.json');
const root = path.resolve(process.env.QA_ROOT);
const artifact = path.resolve(process.env.QA_FIXED_ARTIFACT);
async function digest(file) { const hash = crypto.createHash('sha256'); for await (const part of fs.createReadStream(file)) hash.update(part); return hash.digest('hex'); }
async function main() {
fs.mkdirSync(path.join(root, 'evidence'), { recursive: true });
const build = JSON.parse(fs.readFileSync(path.join(artifact, 'build-provenance.json')));
assert.equal(build.repository, pinned.repository); assert.equal(build.sha, pinned.sha);
assert.equal(build.status, 'passed'); assert.equal(build.logReview.startsWith('passed'), true);
assert.equal(build.run, process.env.GITHUB_RUN_ID); assert.equal(build.qaHead, process.env.QA_HEAD_SHA);
assert.equal(build.versionMetadata, pinned.version);
assert.equal(build.installerSha256, process.env.QA_EXPECTED_INSTALLER_SHA);
assert.equal(await digest(path.join(artifact, pinned.installer)), process.env.QA_EXPECTED_INSTALLER_SHA);
fs.copyFileSync(path.join(artifact, pinned.installer), path.join(root, pinned.installer));
const response = await fetch(`https://api.github.com/repos/${pinned.repository}/releases/tags/${pinned.baseline.tag}`, { headers: { Authorization: `Bearer ${process.env.GH_TOKEN}`, Accept: 'application/vnd.github+json' }, signal: AbortSignal.timeout(30000) });
assert(response.ok);
const release = await response.json(), asset = release.assets.find(a => a.id === pinned.baseline.asset);
assert.equal(asset?.name, pinned.baseline.installer); assert.equal(asset.digest, `sha256:${pinned.baseline.sha256}`); assert.equal(asset.browser_download_url, pinned.baseline.url);
const baseline = await fetch(pinned.baseline.url, { signal: AbortSignal.timeout(120000) });
assert(baseline.ok);
await pipeline(Readable.fromWeb(baseline.body), fs.createWriteStream(path.join(root, pinned.baseline.installer)));
assert.equal(await digest(path.join(root, pinned.baseline.installer)), pinned.baseline.sha256);
fs.writeFileSync(path.join(root, 'evidence/provenance.json'), JSON.stringify({ ...pinned, build, buildArtifactId: process.env.QA_BUILD_ARTIFACT_ID, buildArtifactDigest: process.env.QA_BUILD_ARTIFACT_DIGEST, baselineVerifiedSha256: pinned.baseline.sha256, testPackageOrigin: 'Exact trusted patch SHA, CI QA-built NSIS; unsigned/unreleased, not official release/updater acceptance' }, null, 2));
console.log(JSON.stringify({ fixedSha: pinned.sha, installerSha256: build.installerSha256, baselineSha256: pinned.baseline.sha256, buildArtifact: process.env.QA_BUILD_ARTIFACT_ID }, null, 2));
}
main().catch(error => { console.error(error.stack); process.exitCode = 1; });
+104
View File
@@ -0,0 +1,104 @@
// Only this downloader receives the standard Actions read token.
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const { Readable } = require('node:stream');
const { pipeline } = require('node:stream/promises');
const { execFileSync } = require('node:child_process');
const pinned = require('./candidate.json');
const portable = process.env.QA_MODE === 'portable';
const baseline = portable ? pinned.portableBaseline : pinned.baseline;
const entry = portable ? pinned.portableZip : pinned.installer;
const root = path.resolve(process.env.QA_ROOT);
const evidence = path.join(root, 'evidence');
const digest = async file => {
const hash = crypto.createHash('sha256');
for await (const part of fs.createReadStream(file)) hash.update(part);
return hash.digest('hex');
};
async function download(response, file) {
assert(response.ok, `Download HTTP ${response.status}`);
await pipeline(Readable.fromWeb(response.body), fs.createWriteStream(file));
}
async function main() {
assert.equal(process.platform, 'win32');
assert(process.env.GH_TOKEN);
fs.mkdirSync(evidence, { recursive: true });
const base = `https://api.github.com/repos/${pinned.repository}`;
const headers = { Authorization: `Bearer ${process.env.GH_TOKEN}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' };
async function api(route) {
const response = await fetch(base + route, { headers, signal: AbortSignal.timeout(30000) });
assert(response.ok, `GitHub metadata HTTP ${response.status}`);
return response.json();
}
const run = await api(`/actions/runs/${pinned.run}`);
assert.equal(run.head_sha, pinned.sha);
assert.equal(run.repository.id, pinned.repositoryId);
assert.equal(run.head_repository.id, pinned.repositoryId);
assert.equal(run.head_branch, 'main');
assert.equal(run.event, 'push');
assert.equal(run.path, '.github/workflows/build.yml');
const jobs = await api(`/actions/runs/${pinned.run}/jobs?per_page=100`);
const job = jobs.jobs.find(item => item.name === 'build-windows');
assert.equal(job?.conclusion, 'success');
const artifact = await api(`/actions/artifacts/${pinned.artifact}`);
assert.equal(artifact.name, pinned.name);
assert.equal(artifact.expired, false);
assert.equal(artifact.workflow_run.id, pinned.run);
assert.equal(artifact.workflow_run.head_sha, pinned.sha);
assert.equal(artifact.workflow_run.head_repository_id, pinned.repositoryId);
assert.equal(artifact.digest, `sha256:${pinned.zipSha256}`);
const release = await api(`/releases/tags/${baseline.tag}`);
const asset = release.assets.find(item => item.id === baseline.asset);
assert.equal(asset?.name, baseline.installer);
assert.equal(asset.digest, `sha256:${baseline.sha256}`);
assert.equal(asset.browser_download_url, baseline.url);
await download(await fetch(baseline.url, { signal: AbortSignal.timeout(120000) }), path.join(root, baseline.installer));
assert.equal(await digest(path.join(root, baseline.installer)), baseline.sha256);
const response = await fetch(`${base}/actions/artifacts/${pinned.artifact}/zip`, { headers, redirect: 'manual', signal: AbortSignal.timeout(30000) });
assert.equal(response.status, 302);
const location = new URL(response.headers.get('location'));
assert.equal(location.protocol, 'https:');
// Never forward the token to the signed artifact blob or to installers/apps.
const zip = path.join(root, 'official.zip');
await download(await fetch(location, { signal: AbortSignal.timeout(180000) }), zip);
assert.equal(await digest(zip), pinned.zipSha256);
const extract = `Add-Type -AssemblyName System.IO.Compression.FileSystem
$z = [IO.Compression.ZipFile]::OpenRead($env:QA_ZIP)
try {
$entries = @($z.Entries | Where-Object { $_.FullName -eq $env:QA_INSTALLER })
if ($entries.Count -ne 1) { throw 'Expected exactly one pinned NSIS entry' }
[IO.Compression.ZipFileExtensions]::ExtractToFile($entries[0], $env:QA_OUTPUT, $false)
} finally { $z.Dispose() }`;
execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', extract], {
env: { ...process.env, GH_TOKEN: '', QA_ZIP: zip, QA_INSTALLER: entry, QA_OUTPUT: path.join(root, entry) }, timeout: 30000,
});
if (portable) {
const unpack = `Add-Type -AssemblyName System.IO.Compression.FileSystem
$destination = [IO.Path]::GetFullPath($env:QA_DEST) + [IO.Path]::DirectorySeparatorChar
$z = [IO.Compression.ZipFile]::OpenRead($env:QA_ARCHIVE)
try { foreach ($e in $z.Entries) {
$target = [IO.Path]::GetFullPath([IO.Path]::Combine($destination,$e.FullName))
if (-not $target.StartsWith($destination,[StringComparison]::OrdinalIgnoreCase)) { throw 'ZIP path outside isolated root' }
if ($e.Name -eq '') { [void][IO.Directory]::CreateDirectory($target) }
else { [void][IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($target)); [IO.Compression.ZipFileExtensions]::ExtractToFile($e,$target,$false) }
}} finally { $z.Dispose() }`;
for (const [archive, dest] of [[baseline.installer, 'baseline-portable'], [entry, 'candidate-portable']]) {
execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', unpack], { env: { ...process.env, GH_TOKEN: '', QA_ARCHIVE: path.join(root, archive), QA_DEST: path.join(root, dest) }, timeout: 60000 });
assert(fs.existsSync(path.join(root, dest, 'Netcatty.exe')));
}
}
const provenance = {
...pinned, mode: process.env.QA_MODE || 'nsis', testedBaseline: baseline,
officialWindowsJob: job.id, verifiedAt: new Date().toISOString(),
candidateEntry: entry, candidateEntrySha256: await digest(path.join(root, entry)),
candidateEntryDigestSource: 'Computed from exact entry in verified official artifact ZIP',
baselineMode: portable ? 'Public released Windows ZIP, extraction only' : 'Public released NSIS installer',
candidateMode: portable ? 'Official CI Windows ZIP, extraction only; no installer/updater coverage' : 'Official CI NSIS installer; prerelease version, not released updater acceptance',
};
fs.writeFileSync(path.join(evidence, 'provenance.json'), JSON.stringify(provenance, null, 2));
console.log(JSON.stringify(provenance, null, 2));
console.log(`Verified ${pinned.baseline.tag} and official ${pinned.sha}, artifact ${pinned.artifact}`);
}
main().catch(error => { console.error(error.message); process.exitCode = 1; });