From 5a0eac5132083109e159fde874302f801e278947 Mon Sep 17 00:00:00 2001 From: Socrates Date: Wed, 2 Dec 2026 16:15:40 +0800 Subject: [PATCH 1/2] chore(release): add release preparation/verification scripts, RC pre-release support, and changelog notes --- .gitattributes | 1 + .github/workflows/ci.yml | 4 + .github/workflows/release.yml | 98 +++++---- AGENTS.md | 1 + CONTRIBUTING.md | 54 ++++- scripts/prepare-release.mjs | 113 ++++++++++ scripts/release-utils.mjs | 377 +++++++++++++++++++++++++++++++++ scripts/verify-release.mjs | 87 ++++++++ tests/test-release-scripts.mjs | 158 ++++++++++++++ 9 files changed, 849 insertions(+), 44 deletions(-) create mode 100644 scripts/prepare-release.mjs create mode 100644 scripts/release-utils.mjs create mode 100644 scripts/verify-release.mjs create mode 100644 tests/test-release-scripts.mjs diff --git a/.gitattributes b/.gitattributes index 8d40e38..6f47b79 100644 --- a/.gitattributes +++ b/.gitattributes @@ -29,6 +29,7 @@ web/dist/** text eol=lf /.github export-ignore /CONTRIBUTING.md export-ignore /TODO.md export-ignore +/scripts export-ignore /tests export-ignore /web/.gitignore export-ignore /web/e2e export-ignore diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b7c333d..84ac4ce 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,6 +38,10 @@ jobs: echo 'web/dist is not synchronized with web/src. Run npm run build in web/ and commit the result.' >&2 exit 1 fi + - name: Verify release metadata and release scripts + run: | + node scripts/verify-release.mjs + node --test tests/test-release-scripts.mjs browser-e2e: name: Browser session E2E diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index fa275ca..740f4a2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -15,18 +15,13 @@ jobs: timeout-minutes: 10 steps: - uses: actions/checkout@v7 - - name: Verify release version + - uses: actions/setup-node@v7 + with: + node-version: 22 + - name: Verify release metadata and changelog run: | - version="$(tr -d '[:space:]' < VERSION)" - pkg_version="$(node -p "require('./web/package.json').version")" - if [[ "${GITHUB_REF_NAME}" != "v${version}" ]]; then - echo "Tag ${GITHUB_REF_NAME} does not match VERSION ${version}." >&2 - exit 1 - fi - if [[ "${pkg_version}" != "${version}" ]]; then - echo "web/package.json version ${pkg_version} does not match VERSION ${version}." >&2 - exit 1 - fi + node scripts/verify-release.mjs --tag "${GITHUB_REF_NAME}" + node --test tests/test-release-scripts.mjs - name: Check POSIX and Bash shell syntax run: | for file in linux/runtime/*.sh; do @@ -47,22 +42,14 @@ jobs: timeout-minutes: 15 steps: - uses: actions/checkout@v7 - - name: Verify release version - shell: pwsh - run: | - $version = (Get-Content -Raw -LiteralPath VERSION).Trim() - $packageVersion = (Get-Content -Raw -LiteralPath web/package.json | ConvertFrom-Json).version - if ($env:GITHUB_REF_NAME -ne "v$version") { - throw "Tag $env:GITHUB_REF_NAME does not match VERSION $version." - } - if ($packageVersion -ne $version) { - throw "web/package.json version $packageVersion does not match VERSION $version." - } - uses: actions/setup-node@v7 with: node-version: 22 cache: npm cache-dependency-path: web/package-lock.json + - name: Verify release metadata and changelog + shell: pwsh + run: node scripts/verify-release.mjs --tag "$env:GITHUB_REF_NAME" - name: Install frontend dependencies working-directory: web run: npm ci @@ -100,14 +87,18 @@ jobs: - uses: actions/checkout@v7 with: fetch-depth: 0 + - uses: actions/setup-node@v7 + with: + node-version: 22 + - name: Resolve release metadata and changelog notes + run: | + node scripts/verify-release.mjs \ + --tag "${GITHUB_REF_NAME}" \ + --write-notes "${RUNNER_TEMP}/release-notes.md" \ + --github-env "${GITHUB_ENV}" - name: Create and verify release archive run: | - version="$(tr -d '[:space:]' < VERSION)" - if [[ "${GITHUB_REF_NAME}" != "v${version}" ]]; then - echo "Tag ${GITHUB_REF_NAME} does not match VERSION ${version}." >&2 - exit 1 - fi - prefix="clash-ssh-proxy-bootstrap-${version}" + prefix="clash-ssh-proxy-bootstrap-${RELEASE_VERSION}" archive="${prefix}.zip" git archive --format=zip --prefix="${prefix}/" --output="${archive}" HEAD entries="$(unzip -Z1 "${archive}")" @@ -124,23 +115,50 @@ jobs: exit 1 fi done - if grep -Eq "^${prefix}/(tests|\.github|web/src|web/e2e|web/package-lock\.json)(/|$)" <<< "${entries}"; then + if grep -Eq "^${prefix}/(tests|scripts|\.github|web/src|web/e2e|web/package-lock\.json)(/|$)" <<< "${entries}"; then echo "Release archive contains excluded development files:" >&2 - grep -E "^${prefix}/(tests|\.github|web/src|web/e2e|web/package-lock\.json)(/|$)" <<< "${entries}" >&2 + grep -E "^${prefix}/(tests|scripts|\.github|web/src|web/e2e|web/package-lock\.json)(/|$)" <<< "${entries}" exit 1 fi sha256sum "${archive}" > "${archive}.sha256" - { - echo "RELEASE_VERSION=${version}" - echo "RELEASE_ARCHIVE=${archive}" - } >> "${GITHUB_ENV}" + sha256sum -c "${archive}.sha256" + echo "RELEASE_ARCHIVE=${archive}" >> "${GITHUB_ENV}" - name: Publish GitHub release env: GH_TOKEN: ${{ github.token }} run: | - gh release create "${GITHUB_REF_NAME}" \ - "${RELEASE_ARCHIVE}" \ - "${RELEASE_ARCHIVE}.sha256" \ - --verify-tag \ - --generate-notes \ - --title "Clash SSH Proxy Manager ${RELEASE_VERSION}" + args=( + "${GITHUB_REF_NAME}" + "${RELEASE_ARCHIVE}" + "${RELEASE_ARCHIVE}.sha256" + --verify-tag + --notes-file "${RUNNER_TEMP}/release-notes.md" + --title "${RELEASE_TITLE}" + ) + if [[ "${IS_PRERELEASE}" == "true" ]]; then + args+=(--prerelease) + fi + gh release create "${args[@]}" + - name: Verify published GitHub release assets + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release view "${GITHUB_REF_NAME}" --json tagName,isPrerelease,assets | node -e " + const fs = require('node:fs'); + const data = JSON.parse(fs.readFileSync(0, 'utf8')); + const expectedTag = process.env.GITHUB_REF_NAME; + const expectedPre = process.env.IS_PRERELEASE === 'true'; + const expectedZip = process.env.RELEASE_ARCHIVE; + const expectedSha = expectedZip + '.sha256'; + if (data.tagName !== expectedTag) { + throw new Error('Unexpected tagName: ' + data.tagName); + } + if (Boolean(data.isPrerelease) !== expectedPre) { + throw new Error('Unexpected isPrerelease: ' + data.isPrerelease); + } + const names = new Set((data.assets || []).map((a) => a.name)); + if (!names.has(expectedZip) || !names.has(expectedSha)) { + throw new Error('Missing expected release assets: ' + Array.from(names).join(', ')); + } + console.log('Verified published GitHub Release ' + data.tagName + ' (prerelease=' + data.isPrerelease + ').'); + " diff --git a/AGENTS.md b/AGENTS.md index ebab475..bdc8d59 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -46,3 +46,4 @@ $prep = .\proxy-manager.ps1 prepare-ssh -Name edge-prod -RemoteHost 203.0.113.10 - Maintain compatibility with both **Windows PowerShell 5.1** and **PowerShell 7**. - Keep `web/dist` synchronized with `web/src` (`cd web && npm run check`). - Never commit private RFC 1918 IPv4 addresses, personal usernames, or key material (enforced by `tests/test-privacy.sh`). Use RFC 5737 documentation IPs (`203.0.113.10`, `198.51.100.8`, `192.0.2.17`). +- **Release discipline**: Never bypass branch protection on `main` or push a `v*` release tag before all 5 required CI checks (including Windows PowerShell 5.1, PowerShell 7, and Edge E2E) pass on a PR. Use `node scripts/prepare-release.mjs ` on a `release/v` branch, fill in `CHANGELOG.md`, verify with `node scripts/verify-release.mjs --tag v`, optionally validate on Windows via a `v-rc.1` pre-release tag, merge the PR to `main`, and only then tag `v` on `main`. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3868566..c53ae8d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -54,7 +54,53 @@ keys, `authorized_keys`, or copied production logs. ## Releases -A `v` tag must match both `VERSION` and `web/package.json`. The release -workflow repeats all platform checks, verifies `web/dist`, and publishes a Git -archive with a SHA-256 checksum. Code signing is intentionally outside this -repository until a trusted signing identity is configured. +Never push release commits or `v*` tags directly to `main` before the required +CI checks pass. Follow this standard release workflow: + +1. **Merge all feature PRs into `main` first** and confirm all 5 required CI + checks (`React build and tests`, `Browser session E2E`, `Windows PowerShell 5.1`, + `PowerShell 7`, and `Linux scripts and privacy`) are green. +2. **Create a release branch from `main`** and run the release preparation script: + + ```bash + git checkout main && git pull + git checkout -b release/v1.6.0 + node scripts/prepare-release.mjs 1.6.0 + ``` + + This updates `VERSION`, `web/package.json`, `web/package-lock.json`, + `README.md`, `README.zh-CN.md`, `docs/WINDOWS-UI.en-US.md`, + `docs/WINDOWS-UI.zh-CN.md`, inserts a stub in `CHANGELOG.md`, and rebuilds + `web/dist` via `npm run check`. +3. **Fill in `CHANGELOG.md`** under `## 1.6.0 - YYYY-MM-DD` (replacing the + placeholder line) and validate all release metadata: + + ```bash + node scripts/verify-release.mjs --tag v1.6.0 + ``` + +4. **Open a pull request** from `release/v1.6.0` to `main` and wait for all 5 + required CI checks to pass. +5. **Optional Windows RC smoke test (recommended for OS / task-scheduler / + self-update changes)**: push a pre-release tag `v1.6.0-rc.1` on the green + release branch commit. `.github/workflows/release.yml` automatically marks + `-rc.N` tags as GitHub **Pre-releases** (ignored by stable in-app update + checks) and attaches `clash-ssh-proxy-bootstrap-1.6.0-rc.1.zip` + `.sha256` + for real Windows verification (including upgrading from the previous stable + release and testing sign-out/sign-in behavior). +6. **Merge the release PR into `main`**, then create and push the stable tag on + the merged `main` commit: + + ```bash + git checkout main && git pull + git tag -a v1.6.0 -m "Release v1.6.0" + git push origin v1.6.0 + ``` + +7. **Verify the published release**: `.github/workflows/release.yml` re-runs + Linux and Windows validation, verifies `web/dist` and `CHANGELOG.md`, builds + a clean Git archive (excluding `tests/`, `scripts/`, `.github/`, and frontend + sources), generates and checks `.sha256`, extracts release notes directly from + `CHANGELOG.md`, publishes the GitHub Release, and verifies the uploaded assets. + Code signing is intentionally outside this repository until a trusted signing + identity is configured. diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjs new file mode 100644 index 0000000..a4b3682 --- /dev/null +++ b/scripts/prepare-release.mjs @@ -0,0 +1,113 @@ +#!/usr/bin/env node +import { execFileSync } from 'node:child_process' +import { dirname, join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import { SEMVER_RE, updateReleaseFiles, verifyReleaseMetadata } from './release-utils.mjs' + +const scriptDir = dirname(fileURLToPath(import.meta.url)) +const repoRoot = resolve(scriptDir, '..') + +function parseArgs(argv) { + const parsed = { + version: '', + date: new Date().toISOString().slice(0, 10), + skipBuild: false, + allowDirty: false, + allowMain: false, + } + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i] + if (arg === '--date') { + parsed.date = argv[++i] ?? '' + } else if (arg === '--skip-build') { + parsed.skipBuild = true + } else if (arg === '--allow-dirty') { + parsed.allowDirty = true + } else if (arg === '--allow-main') { + parsed.allowMain = true + } else if (arg === '--help' || arg === '-h') { + console.log( + [ + 'Usage: node scripts/prepare-release.mjs [--date YYYY-MM-DD] [--skip-build] [--allow-dirty] [--allow-main]', + '', + 'Prepares a release branch by updating VERSION, web/package*.json, README*.md,', + 'docs/WINDOWS-UI*.md, CHANGELOG.md, and rebuilding web/dist via npm run check.', + ].join('\n'), + ) + process.exit(0) + } else if (!arg.startsWith('-') && !parsed.version) { + parsed.version = arg + } else { + throw new Error(`Unknown or duplicate argument: ${arg}`) + } + } + return parsed +} + +function runGit(args) { + return execFileSync('git', args, { cwd: repoRoot, encoding: 'utf8' }).trim() +} + +try { + const args = parseArgs(process.argv.slice(2)) + if (!SEMVER_RE.test(args.version)) { + throw new Error( + `Invalid or missing version '${args.version}'. Usage: node scripts/prepare-release.mjs `, + ) + } + + const branch = runGit(['rev-parse', '--abbrev-ref', 'HEAD']) + if (!args.allowMain && branch === 'main') { + throw new Error( + `Refusing to prepare a release directly on 'main'. Create a release branch first:\n git checkout -b release/v${args.version}`, + ) + } + + const status = runGit(['status', '--porcelain']) + if (!args.allowDirty && status.length > 0) { + throw new Error( + 'Working tree has uncommitted changes. Commit or stash them first (or pass --allow-dirty).', + ) + } + + const { updatedFiles, changelogCreated } = updateReleaseFiles(repoRoot, args.version, { + date: args.date, + }) + console.log(`Updated ${updatedFiles.length} file(s) for v${args.version}:`) + for (const file of updatedFiles) { + console.log(` - ${file}`) + } + + if (!args.skipBuild) { + console.log('\nRunning frontend lint, unit tests, and production build (cd web && npm run check)...') + const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm' + execFileSync(npmCmd, ['run', 'check'], { + cwd: join(repoRoot, 'web'), + stdio: 'inherit', + }) + } + + const verification = verifyReleaseMetadata(repoRoot, { tag: `v${args.version}` }) + console.log('\nNext steps:') + if (changelogCreated) { + console.log(` 1. Fill in the release highlights under '## ${args.version} - ${args.date}' in CHANGELOG.md.`) + console.log(` 2. Run: node scripts/verify-release.mjs --tag v${args.version}`) + } else if (!verification.ok) { + console.log(' 1. Fix remaining release metadata warnings:') + for (const err of verification.errors) { + console.log(` - ${err}`) + } + } else { + console.log(` 1. Release metadata verified for v${args.version}.`) + } + console.log(` - Commit and push branch '${branch}', then open a PR to 'main' and wait for 5/5 CI checks.`) + console.log( + ` - Optional Windows RC smoke test: tag 'v${args.version}-rc.1' on the green release branch to publish a GitHub Pre-release.`, + ) + console.log( + ` - After merging the PR to 'main', tag 'v${args.version}' on 'main' to publish the official GitHub Release.`, + ) +} catch (error) { + console.error(error instanceof Error ? error.message : String(error)) + process.exit(1) +} diff --git a/scripts/release-utils.mjs b/scripts/release-utils.mjs new file mode 100644 index 0000000..acedb71 --- /dev/null +++ b/scripts/release-utils.mjs @@ -0,0 +1,377 @@ +import { readFileSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' + +export const REPO_SLUG = 'Scrates1/clash-ssh-proxy-bootstrap' +export const SEMVER_RE = /^\d+\.\d+\.\d+$/ +export const RELEASE_TAG_RE = /^v(\d+\.\d+\.\d+)(?:-rc\.([1-9]\d*))?$/ +export const CHANGELOG_PLACEHOLDER_MARKER = 'TODO: Summarize user-facing changes before merging this release PR.' + +const VERSION_PLACEHOLDER_PATTERNS = [ + /\bTODO\b/i, + /\bTBD\b/i, + /Fill in release notes/i, +] + +function normalizeNewlines(text) { + return String(text).replace(/\r\n/g, '\n') +} + +export function parseReleaseTag(tag) { + const trimmed = String(tag ?? '').trim() + const match = RELEASE_TAG_RE.exec(trimmed) + if (!match) { + throw new Error( + `Invalid release tag '${trimmed}'. Expected 'vX.Y.Z' (stable) or 'vX.Y.Z-rc.N' (pre-release, N >= 1).`, + ) + } + const baseVersion = match[1] + const rcNumber = match[2] ? Number.parseInt(match[2], 10) : null + const isPrerelease = rcNumber !== null + const releaseVersion = isPrerelease ? `${baseVersion}-rc.${rcNumber}` : baseVersion + const title = isPrerelease + ? `Clash SSH Proxy Manager ${releaseVersion} (Pre-release)` + : `Clash SSH Proxy Manager ${releaseVersion}` + + return { + tag: trimmed, + baseVersion, + rcNumber, + isPrerelease, + releaseVersion, + title, + } +} + +export function extractChangelogSection(changelogText, baseVersion) { + const normalized = normalizeNewlines(changelogText) + const lines = normalized.split('\n') + const headingRe = new RegExp( + `^##\\s+${baseVersion.replace(/\./g, '\\.')}\\s+-\\s+(\\d{4}-\\d{2}-\\d{2})\\s*$`, + ) + + let startIndex = -1 + let heading = '' + let date = '' + for (let i = 0; i < lines.length; i += 1) { + const match = headingRe.exec(lines[i]) + if (match) { + startIndex = i + heading = lines[i].trim() + date = match[1] + break + } + } + + if (startIndex === -1) { + return null + } + + let endIndex = lines.length + for (let i = startIndex + 1; i < lines.length; i += 1) { + if (/^##\s+/.test(lines[i])) { + endIndex = i + break + } + } + + const body = lines + .slice(startIndex + 1, endIndex) + .join('\n') + .trim() + + return { heading, date, body } +} + +export function validateChangelogBody(body) { + const errors = [] + const trimmed = String(body ?? '').trim() + if (!trimmed) { + errors.push('CHANGELOG.md section for this version is empty.') + return errors + } + if (!/^\s*[-*]\s+\S+/m.test(trimmed)) { + errors.push('CHANGELOG.md section must contain at least one bullet point describing changes.') + } + for (const pattern of VERSION_PLACEHOLDER_PATTERNS) { + if (pattern.test(trimmed)) { + errors.push(`CHANGELOG.md section still contains placeholder text matching ${pattern}.`) + break + } + } + return errors +} + +export function formatGitHubReleaseNotes({ + baseVersion, + releaseVersion, + isPrerelease, + changelogBody, + repoSlug = REPO_SLUG, +}) { + const parts = [] + if (isPrerelease) { + parts.push( + `> [!WARNING]`, + `> This is a **pre-release candidate** (\`v${releaseVersion}\`) for validation and Windows smoke testing before \`v${baseVersion}\`. Stable in-app auto-update checks ignore pre-releases.`, + '', + ) + } + + parts.push(`## What's Changed in ${releaseVersion}`, '', changelogBody.trim(), '') + parts.push( + '## Verification', + '', + `- Verify the downloaded archive against \`clash-ssh-proxy-bootstrap-${releaseVersion}.zip.sha256\`.`, + `- Full release history: [CHANGELOG.md](https://github.com/${repoSlug}/blob/v${releaseVersion}/CHANGELOG.md).`, + '', + ) + + return parts.join('\n') +} + +function readUtf8(repoRoot, relativePath) { + return readFileSync(join(repoRoot, relativePath), 'utf8') +} + +export function verifyReleaseMetadata(repoRoot, options = {}) { + const errors = [] + const expectedTag = options.tag ? String(options.tag).trim() : '' + + let releaseInfo = null + if (expectedTag) { + try { + releaseInfo = parseReleaseTag(expectedTag) + } catch (error) { + errors.push(error instanceof Error ? error.message : String(error)) + } + } + + const version = readUtf8(repoRoot, 'VERSION').trim() + if (!SEMVER_RE.test(version)) { + errors.push(`VERSION must match X.Y.Z, found '${version}'.`) + } + + if (releaseInfo && releaseInfo.baseVersion !== version) { + errors.push( + `Tag '${releaseInfo.tag}' targets base version '${releaseInfo.baseVersion}', but VERSION is '${version}'.`, + ) + } + + const pkg = JSON.parse(readUtf8(repoRoot, 'web/package.json')) + if (pkg.version !== version) { + errors.push(`web/package.json version '${pkg.version}' does not match VERSION '${version}'.`) + } + + const lock = JSON.parse(readUtf8(repoRoot, 'web/package-lock.json')) + if (lock.version !== version) { + errors.push(`web/package-lock.json version '${lock.version}' does not match VERSION '${version}'.`) + } + const rootPkgVersion = lock.packages && lock.packages[''] ? lock.packages[''].version : undefined + if (rootPkgVersion !== version) { + errors.push( + `web/package-lock.json packages[""].version '${rootPkgVersion}' does not match VERSION '${version}'.`, + ) + } + + const expectedZipUrl = `https://github.com/${REPO_SLUG}/releases/download/v${version}/clash-ssh-proxy-bootstrap-${version}.zip` + for (const readmePath of ['README.md', 'README.zh-CN.md']) { + const content = readUtf8(repoRoot, readmePath) + const downloadUrls = content.match( + /https:\/\/github\.com\/Scrates1\/clash-ssh-proxy-bootstrap\/releases\/download\/v[^\s")]+/g, + ) ?? [] + if (downloadUrls.length < 2) { + errors.push(`${readmePath} must contain at least 2 release ZIP download links (found ${downloadUrls.length}).`) + } + for (const url of downloadUrls) { + if (url !== expectedZipUrl) { + errors.push(`${readmePath} contains out-of-sync download URL '${url}' (expected '${expectedZipUrl}').`) + } + } + } + + const enGuide = readUtf8(repoRoot, 'docs/WINDOWS-UI.en-US.md') + if (!enGuide.includes(`Current stable version: ${version}.`)) { + errors.push(`docs/WINDOWS-UI.en-US.md does not declare 'Current stable version: ${version}.'`) + } + + const zhGuide = readUtf8(repoRoot, 'docs/WINDOWS-UI.zh-CN.md') + if (!zhGuide.includes(`当前稳定版本:${version}。`)) { + errors.push(`docs/WINDOWS-UI.zh-CN.md does not declare '当前稳定版本:${version}。'`) + } + + const changelogText = readUtf8(repoRoot, 'CHANGELOG.md') + const changelog = SEMVER_RE.test(version) ? extractChangelogSection(changelogText, version) : null + if (!changelog) { + errors.push(`CHANGELOG.md is missing a '## ${version} - YYYY-MM-DD' section.`) + } else { + for (const err of validateChangelogBody(changelog.body)) { + errors.push(err) + } + } + + const effectiveReleaseInfo = + releaseInfo ?? + (SEMVER_RE.test(version) + ? parseReleaseTag(`v${version}`) + : null) + + return { + ok: errors.length === 0, + errors, + version, + releaseInfo: effectiveReleaseInfo, + changelog, + } +} + +function replaceExactly(text, regex, replacement, label, expectedCount) { + const globalFlags = regex.flags.includes('g') ? regex.flags : `${regex.flags}g` + const countRegex = new RegExp(regex.source, globalFlags) + const matches = Array.from(text.matchAll(countRegex)) + if (matches.length !== expectedCount) { + throw new Error(`Expected ${expectedCount} match(es) for ${label}, found ${matches.length}.`) + } + return text.replace(regex, replacement) +} + +export function updateReleaseFiles(repoRoot, targetVersion, options = {}) { + if (!SEMVER_RE.test(targetVersion)) { + throw new Error(`Target version '${targetVersion}' must match X.Y.Z.`) + } + + const date = options.date ?? new Date().toISOString().slice(0, 10) + if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) { + throw new Error(`Release date '${date}' must match YYYY-MM-DD.`) + } + + const updatedFiles = [] + + // 1. VERSION + writeFileSync(join(repoRoot, 'VERSION'), `${targetVersion}\n`, 'utf8') + updatedFiles.push('VERSION') + + // 2. web/package.json + const pkgPath = join(repoRoot, 'web/package.json') + const pkgRaw = readFileSync(pkgPath, 'utf8') + const pkgUpdated = replaceExactly( + pkgRaw, + /("name":\s*"clash-ssh-proxy-manager-ui",\s*\r?\n\s*"private":\s*true,\s*\r?\n\s*"version":\s*")\d+\.\d+\.\d+(")/, + `$1${targetVersion}$2`, + 'web/package.json version', + 1, + ) + writeFileSync(pkgPath, pkgUpdated, 'utf8') + updatedFiles.push('web/package.json') + + // 3. web/package-lock.json (top-level + packages[""]) + const lockPath = join(repoRoot, 'web/package-lock.json') + const lockRaw = readFileSync(lockPath, 'utf8') + const lockUpdated = replaceExactly( + lockRaw, + /("name":\s*"clash-ssh-proxy-manager-ui",\s*\r?\n\s*"version":\s*")\d+\.\d+\.\d+(")/g, + `$1${targetVersion}$2`, + 'web/package-lock.json root versions', + 2, + ) + writeFileSync(lockPath, lockUpdated, 'utf8') + updatedFiles.push('web/package-lock.json') + + // 4. README.md + const readmeEnPath = join(repoRoot, 'README.md') + let readmeEn = readFileSync(readmeEnPath, 'utf8') + readmeEn = replaceExactly( + readmeEn, + /https:\/\/github\.com\/Scrates1\/clash-ssh-proxy-bootstrap\/releases\/download\/v\d+\.\d+\.\d+\/clash-ssh-proxy-bootstrap-\d+\.\d+\.\d+\.zip/g, + `https://github.com/${REPO_SLUG}/releases/download/v${targetVersion}/clash-ssh-proxy-bootstrap-${targetVersion}.zip`, + 'README.md download URLs', + 2, + ) + readmeEn = replaceExactly( + readmeEn, + /Download v\d+\.\d+\.\d+ ZIP/, + `Download v${targetVersion} ZIP`, + 'README.md button label', + 1, + ) + readmeEn = replaceExactly( + readmeEn, + /\[clash-ssh-proxy-bootstrap-\d+\.\d+\.\d+\.zip\]/, + `[clash-ssh-proxy-bootstrap-${targetVersion}.zip]`, + 'README.md link text', + 1, + ) + writeFileSync(readmeEnPath, readmeEn, 'utf8') + updatedFiles.push('README.md') + + // 5. README.zh-CN.md + const readmeZhPath = join(repoRoot, 'README.zh-CN.md') + let readmeZh = readFileSync(readmeZhPath, 'utf8') + readmeZh = replaceExactly( + readmeZh, + /https:\/\/github\.com\/Scrates1\/clash-ssh-proxy-bootstrap\/releases\/download\/v\d+\.\d+\.\d+\/clash-ssh-proxy-bootstrap-\d+\.\d+\.\d+\.zip/g, + `https://github.com/${REPO_SLUG}/releases/download/v${targetVersion}/clash-ssh-proxy-bootstrap-${targetVersion}.zip`, + 'README.zh-CN.md download URLs', + 2, + ) + readmeZh = replaceExactly( + readmeZh, + /下载 v\d+\.\d+\.\d+ ZIP/, + `下载 v${targetVersion} ZIP`, + 'README.zh-CN.md button label', + 1, + ) + readmeZh = replaceExactly( + readmeZh, + /\[clash-ssh-proxy-bootstrap-\d+\.\d+\.\d+\.zip\]/, + `[clash-ssh-proxy-bootstrap-${targetVersion}.zip]`, + 'README.zh-CN.md link text', + 1, + ) + writeFileSync(readmeZhPath, readmeZh, 'utf8') + updatedFiles.push('README.zh-CN.md') + + // 6. docs/WINDOWS-UI.en-US.md + const uiEnPath = join(repoRoot, 'docs/WINDOWS-UI.en-US.md') + const uiEn = replaceExactly( + readFileSync(uiEnPath, 'utf8'), + /Current stable version: \d+\.\d+\.\d+\./, + `Current stable version: ${targetVersion}.`, + 'docs/WINDOWS-UI.en-US.md version', + 1, + ) + writeFileSync(uiEnPath, uiEn, 'utf8') + updatedFiles.push('docs/WINDOWS-UI.en-US.md') + + // 7. docs/WINDOWS-UI.zh-CN.md + const uiZhPath = join(repoRoot, 'docs/WINDOWS-UI.zh-CN.md') + const uiZh = replaceExactly( + readFileSync(uiZhPath, 'utf8'), + /当前稳定版本:\d+\.\d+\.\d+。/, + `当前稳定版本:${targetVersion}。`, + 'docs/WINDOWS-UI.zh-CN.md version', + 1, + ) + writeFileSync(uiZhPath, uiZh, 'utf8') + updatedFiles.push('docs/WINDOWS-UI.zh-CN.md') + + // 8. CHANGELOG.md (insert stub if section for targetVersion does not yet exist) + const changelogPath = join(repoRoot, 'CHANGELOG.md') + const changelogRaw = readFileSync(changelogPath, 'utf8') + let changelogCreated = false + if (!extractChangelogSection(changelogRaw, targetVersion)) { + const eol = changelogRaw.includes('\r\n') ? '\r\n' : '\n' + const stub = `## Unreleased${eol}${eol}## ${targetVersion} - ${date}${eol}${eol}- ${CHANGELOG_PLACEHOLDER_MARKER}` + const updatedChangelog = replaceExactly( + changelogRaw, + /^## Unreleased$/m, + stub, + 'CHANGELOG.md Unreleased heading', + 1, + ) + writeFileSync(changelogPath, updatedChangelog, 'utf8') + updatedFiles.push('CHANGELOG.md') + changelogCreated = true + } + + return { updatedFiles, changelogCreated } +} diff --git a/scripts/verify-release.mjs b/scripts/verify-release.mjs new file mode 100644 index 0000000..29fccf6 --- /dev/null +++ b/scripts/verify-release.mjs @@ -0,0 +1,87 @@ +#!/usr/bin/env node +import { appendFileSync, writeFileSync } from 'node:fs' +import { dirname, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import { formatGitHubReleaseNotes, verifyReleaseMetadata } from './release-utils.mjs' + +const scriptDir = dirname(fileURLToPath(import.meta.url)) +const repoRoot = resolve(scriptDir, '..') + +function parseArgs(argv) { + const parsed = { + tag: '', + writeNotes: '', + githubEnv: '', + json: false, + } + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i] + if (arg === '--tag') { + parsed.tag = argv[++i] ?? '' + } else if (arg === '--write-notes') { + parsed.writeNotes = argv[++i] ?? '' + } else if (arg === '--github-env') { + parsed.githubEnv = argv[++i] ?? '' + } else if (arg === '--json') { + parsed.json = true + } else if (arg === '--help' || arg === '-h') { + console.log( + 'Usage: node scripts/verify-release.mjs [--tag vX.Y.Z|vX.Y.Z-rc.N] [--write-notes FILE] [--github-env FILE] [--json]', + ) + process.exit(0) + } else { + throw new Error(`Unknown argument: ${arg}`) + } + } + return parsed +} + +try { + const args = parseArgs(process.argv.slice(2)) + const result = verifyReleaseMetadata(repoRoot, { tag: args.tag || undefined }) + + if (!result.ok) { + if (args.json) { + console.error(JSON.stringify(result, null, 2)) + } else { + console.error('Release metadata verification failed:') + for (const err of result.errors) { + console.error(` - ${err}`) + } + } + process.exit(1) + } + + if (args.writeNotes) { + const notes = formatGitHubReleaseNotes({ + baseVersion: result.releaseInfo.baseVersion, + releaseVersion: result.releaseInfo.releaseVersion, + isPrerelease: result.releaseInfo.isPrerelease, + changelogBody: result.changelog.body, + }) + writeFileSync(args.writeNotes, notes, 'utf8') + } + + if (args.githubEnv) { + const envLines = [ + `BASE_VERSION=${result.releaseInfo.baseVersion}`, + `RELEASE_VERSION=${result.releaseInfo.releaseVersion}`, + `IS_PRERELEASE=${result.releaseInfo.isPrerelease ? 'true' : 'false'}`, + `RELEASE_TITLE=${result.releaseInfo.title}`, + '', + ] + appendFileSync(args.githubEnv, envLines.join('\n'), 'utf8') + } + + if (args.json) { + console.log(JSON.stringify(result, null, 2)) + } else { + const modeLabel = result.releaseInfo.isPrerelease ? 'pre-release' : 'stable' + console.log( + `Release metadata verified: ${result.releaseInfo.tag} (${modeLabel}, base VERSION ${result.version}).`, + ) + } +} catch (error) { + console.error(error instanceof Error ? error.message : String(error)) + process.exit(1) +} diff --git a/tests/test-release-scripts.mjs b/tests/test-release-scripts.mjs new file mode 100644 index 0000000..b7f62f9 --- /dev/null +++ b/tests/test-release-scripts.mjs @@ -0,0 +1,158 @@ +import assert from 'node:assert/strict' +import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join, resolve } from 'node:path' +import test from 'node:test' +import { fileURLToPath } from 'node:url' +import { + CHANGELOG_PLACEHOLDER_MARKER, + extractChangelogSection, + formatGitHubReleaseNotes, + parseReleaseTag, + updateReleaseFiles, + validateChangelogBody, + verifyReleaseMetadata, +} from '../scripts/release-utils.mjs' + +const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..') + +function createTempRepoFixture() { + const tempRoot = mkdtempSync(join(tmpdir(), 'clash-proxy-release-test-')) + const files = [ + 'VERSION', + 'CHANGELOG.md', + 'README.md', + 'README.zh-CN.md', + 'docs/WINDOWS-UI.en-US.md', + 'docs/WINDOWS-UI.zh-CN.md', + 'web/package.json', + 'web/package-lock.json', + ] + for (const rel of files) { + const dest = join(tempRoot, rel) + mkdirSync(dirname(dest), { recursive: true }) + copyFileSync(join(repoRoot, rel), dest) + } + return tempRoot +} + +test('parseReleaseTag accepts stable and rc tags and rejects invalid tags', () => { + const stable = parseReleaseTag('v1.5.0') + assert.equal(stable.baseVersion, '1.5.0') + assert.equal(stable.releaseVersion, '1.5.0') + assert.equal(stable.isPrerelease, false) + assert.equal(stable.title, 'Clash SSH Proxy Manager 1.5.0') + + const rc = parseReleaseTag('v1.6.0-rc.2') + assert.equal(rc.baseVersion, '1.6.0') + assert.equal(rc.releaseVersion, '1.6.0-rc.2') + assert.equal(rc.rcNumber, 2) + assert.equal(rc.isPrerelease, true) + assert.equal(rc.title, 'Clash SSH Proxy Manager 1.6.0-rc.2 (Pre-release)') + + for (const badTag of ['', '1.5.0', 'v1.5', 'v1.5.0-rc.0', 'v1.5.0-beta.1', 'v1.5.0-rc']) { + assert.throws(() => parseReleaseTag(badTag), /Invalid release tag/) + } +}) + +test('extractChangelogSection and validateChangelogBody enforce non-empty bullet entries without placeholders', () => { + const sample = [ + '# Changelog', + '', + '## Unreleased', + '', + '## 2.0.0 - 2026-12-05', + '', + '- Add feature A.', + '- Fix bug B.', + '', + '## 1.5.0 - 2026-12-02', + '', + '- Earlier entry.', + ].join('\n') + + const section = extractChangelogSection(sample, '2.0.0') + assert.ok(section) + assert.equal(section.date, '2026-12-05') + assert.match(section.body, /Add feature A/) + assert.doesNotMatch(section.body, /Earlier entry/) + assert.deepEqual(validateChangelogBody(section.body), []) + + assert.equal(extractChangelogSection(sample, '9.9.9'), null) + assert.ok(validateChangelogBody('').length > 0) + assert.ok(validateChangelogBody('Plain paragraph with no bullet').length > 0) + assert.ok(validateChangelogBody(`- ${CHANGELOG_PLACEHOLDER_MARKER}`).length > 0) +}) + +test('formatGitHubReleaseNotes includes prerelease banner only for rc releases', () => { + const stableNotes = formatGitHubReleaseNotes({ + baseVersion: '1.6.0', + releaseVersion: '1.6.0', + isPrerelease: false, + changelogBody: '- Ship awesome feature.', + }) + assert.doesNotMatch(stableNotes, /pre-release candidate/i) + assert.match(stableNotes, /clash-ssh-proxy-bootstrap-1\.6\.0\.zip\.sha256/) + assert.match(stableNotes, /Ship awesome feature/) + + const rcNotes = formatGitHubReleaseNotes({ + baseVersion: '1.6.0', + releaseVersion: '1.6.0-rc.1', + isPrerelease: true, + changelogBody: '- Ship awesome feature.', + }) + assert.match(rcNotes, /pre-release candidate/i) + assert.match(rcNotes, /clash-ssh-proxy-bootstrap-1\.6\.0-rc\.1\.zip\.sha256/) +}) + +test('verifyReleaseMetadata passes on current repository state and enforces tag match', () => { + const currentVersion = readFileSync(join(repoRoot, 'VERSION'), 'utf8').trim() + const baseCheck = verifyReleaseMetadata(repoRoot) + assert.equal(baseCheck.ok, true, `Unexpected errors: ${baseCheck.errors.join('; ')}`) + assert.equal(baseCheck.version, currentVersion) + + const stableTagCheck = verifyReleaseMetadata(repoRoot, { tag: `v${currentVersion}` }) + assert.equal(stableTagCheck.ok, true, `Unexpected errors: ${stableTagCheck.errors.join('; ')}`) + assert.equal(stableTagCheck.releaseInfo.isPrerelease, false) + + const rcTagCheck = verifyReleaseMetadata(repoRoot, { tag: `v${currentVersion}-rc.1` }) + assert.equal(rcTagCheck.ok, true, `Unexpected errors: ${rcTagCheck.errors.join('; ')}`) + assert.equal(rcTagCheck.releaseInfo.isPrerelease, true) + + const mismatchCheck = verifyReleaseMetadata(repoRoot, { tag: 'v99.0.0' }) + assert.equal(mismatchCheck.ok, false) + assert.ok(mismatchCheck.errors.some((e) => e.includes('targets base version'))) +}) + +test('updateReleaseFiles bumps all version files, blocks placeholder changelog, and passes once notes are filled', () => { + const tempRoot = createTempRepoFixture() + try { + const { updatedFiles, changelogCreated } = updateReleaseFiles(tempRoot, '2.0.0', { + date: '2026-12-10', + }) + assert.equal(changelogCreated, true) + assert.equal(updatedFiles.length, 8) + + // Placeholder CHANGELOG must be rejected before release + const withPlaceholder = verifyReleaseMetadata(tempRoot, { tag: 'v2.0.0' }) + assert.equal(withPlaceholder.ok, false) + assert.ok(withPlaceholder.errors.some((e) => e.includes('placeholder'))) + + // Replace placeholder with real release highlights + const changelogPath = join(tempRoot, 'CHANGELOG.md') + const filled = readFileSync(changelogPath, 'utf8').replace( + CHANGELOG_PLACEHOLDER_MARKER, + 'Add hardened release workflow with RC pre-release and changelog extraction.', + ) + writeFileSync(changelogPath, filled, 'utf8') + + const verifiedStable = verifyReleaseMetadata(tempRoot, { tag: 'v2.0.0' }) + assert.equal(verifiedStable.ok, true, `Unexpected errors: ${verifiedStable.errors.join('; ')}`) + + const verifiedRc = verifyReleaseMetadata(tempRoot, { tag: 'v2.0.0-rc.1' }) + assert.equal(verifiedRc.ok, true, `Unexpected errors: ${verifiedRc.errors.join('; ')}`) + assert.equal(verifiedRc.releaseInfo.isPrerelease, true) + } finally { + rmSync(tempRoot, { recursive: true, force: true }) + } +}) From 0108d1b792bc0b5ec06aee63e6c56f9140e04011 Mon Sep 17 00:00:00 2001 From: Socrates Date: Wed, 2 Dec 2026 16:55:38 +0800 Subject: [PATCH 2/2] fix(tests): clone mock COM task definitions in Test-Hardening and add enterprise CI security hardening --- .PSScriptAnalyzerSettings.psd1 | 24 +++++++++++++ .gitattributes | 1 + .github/CODEOWNERS | 2 ++ .github/workflows/ci.yml | 36 ++++++++++++++++---- .github/workflows/release.yml | 43 ++++++++++++++++++----- tests/Test-Hardening.ps1 | 62 ++++++++++++++++++++++++++++++++-- 6 files changed, 150 insertions(+), 18 deletions(-) create mode 100644 .PSScriptAnalyzerSettings.psd1 create mode 100644 .github/CODEOWNERS diff --git a/.PSScriptAnalyzerSettings.psd1 b/.PSScriptAnalyzerSettings.psd1 new file mode 100644 index 0000000..b3ff27e --- /dev/null +++ b/.PSScriptAnalyzerSettings.psd1 @@ -0,0 +1,24 @@ +@{ + Severity = @('Error', 'Warning') + IncludeRules = @( + 'PSAvoidUsingInvokeExpression', + 'PSAvoidUsingPlainTextForPassword', + 'PSAvoidUsingConvertToSecureStringWithPlainText', + 'PSAvoidUsingUsernameAndPasswordParams', + 'PSAvoidUsingAllowUnencryptedAuthentication', + 'PSAvoidUsingBrokenHashAlgorithms', + 'PSAvoidUsingComputerNameHardcoded', + 'PSAvoidUsingCmdletAliases', + 'PSAvoidUsingWMICmdlet', + 'PSPossibleIncorrectComparisonWithNull', + 'PSPossibleIncorrectUsageOfAssignmentOperator', + 'PSPossibleIncorrectUsageOfRedirectionOperator', + 'PSUseDeclaredVarsMoreThanAssignments', + 'PSAvoidUsingDoubleQuotesForConstantString', + 'PSAvoidDefaultValueSwitchParameter', + 'PSReservedCmdletChar', + 'PSReservedParams', + 'PSMissingModuleManifestField', + 'PSAvoidUsingDeprecatedManifestFields' + ) +} diff --git a/.gitattributes b/.gitattributes index 6f47b79..a94a5b5 100644 --- a/.gitattributes +++ b/.gitattributes @@ -27,6 +27,7 @@ web/dist/** text eol=lf /.gitattributes export-ignore /.gitignore export-ignore /.github export-ignore +/.PSScriptAnalyzerSettings.psd1 export-ignore /CONTRIBUTING.md export-ignore /TODO.md export-ignore /scripts export-ignore diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..6b4daba --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,2 @@ +# Default repository owner for pull request review and security governance. +* @Scrates1 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 84ac4ce..cb610e8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,8 +19,8 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 10 steps: - - uses: actions/checkout@v7 - - uses: actions/setup-node@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0 with: node-version: 22 cache: npm @@ -28,6 +28,9 @@ jobs: - name: Install frontend dependencies working-directory: web run: npm ci + - name: Audit production frontend dependencies + working-directory: web + run: npm audit --omit=dev --audit-level=high - name: Test and build frontend working-directory: web run: npm run check @@ -48,8 +51,8 @@ jobs: runs-on: windows-latest timeout-minutes: 10 steps: - - uses: actions/checkout@v7 - - uses: actions/setup-node@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0 with: node-version: 22 cache: npm @@ -66,7 +69,7 @@ jobs: runs-on: windows-latest timeout-minutes: 10 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Run manager tests shell: powershell run: .\tests\Test-Manager.ps1 @@ -76,7 +79,26 @@ jobs: runs-on: windows-latest timeout-minutes: 10 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Run PSScriptAnalyzer security checks + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + if (-not (Get-Module -ListAvailable -Name PSScriptAnalyzer)) { + Install-Module -Name PSScriptAnalyzer -Scope CurrentUser -Force -ErrorAction Stop + } + Import-Module PSScriptAnalyzer -ErrorAction Stop + $files = @('proxy-manager.ps1', 'proxy-manager-react-host.ps1') + @( + Get-ChildItem -Path src -Recurse -Filter '*.ps1' | ForEach-Object { $_.FullName } + ) + $findings = @(foreach ($file in $files) { + Invoke-ScriptAnalyzer -Path $file -Settings .PSScriptAnalyzerSettings.psd1 + }) + if ($findings.Count -gt 0) { + $findings | Format-Table ScriptName, Line, Severity, RuleName, Message -AutoSize + throw "PSScriptAnalyzer detected $($findings.Count) security/correctness finding(s)." + } + Write-Host "PSScriptAnalyzer passed across $($files.Count) PowerShell files." - name: Run manager tests shell: pwsh run: .\tests\Test-Manager.ps1 @@ -86,7 +108,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 10 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Check POSIX and Bash shell syntax run: | for file in linux/runtime/*.sh; do diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 740f4a2..179158d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -14,8 +14,8 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 10 steps: - - uses: actions/checkout@v7 - - uses: actions/setup-node@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0 with: node-version: 22 - name: Verify release metadata and changelog @@ -41,8 +41,8 @@ jobs: runs-on: windows-latest timeout-minutes: 15 steps: - - uses: actions/checkout@v7 - - uses: actions/setup-node@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0 with: node-version: 22 cache: npm @@ -53,6 +53,9 @@ jobs: - name: Install frontend dependencies working-directory: web run: npm ci + - name: Audit production frontend dependencies + working-directory: web + run: npm audit --omit=dev --audit-level=high - name: Test and build frontend working-directory: web run: npm run check @@ -67,6 +70,24 @@ jobs: $changes | Write-Host throw 'web/dist is not synchronized with web/src.' } + - name: Run PSScriptAnalyzer security checks + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + if (-not (Get-Module -ListAvailable -Name PSScriptAnalyzer)) { + Install-Module -Name PSScriptAnalyzer -Scope CurrentUser -Force -ErrorAction Stop + } + Import-Module PSScriptAnalyzer -ErrorAction Stop + $files = @('proxy-manager.ps1', 'proxy-manager-react-host.ps1') + @( + Get-ChildItem -Path src -Recurse -Filter '*.ps1' | ForEach-Object { $_.FullName } + ) + $findings = @(foreach ($file in $files) { + Invoke-ScriptAnalyzer -Path $file -Settings .PSScriptAnalyzerSettings.psd1 + }) + if ($findings.Count -gt 0) { + $findings | Format-Table ScriptName, Line, Severity, RuleName, Message -AutoSize + throw "PSScriptAnalyzer detected $($findings.Count) security/correctness finding(s)." + } - name: Run Windows PowerShell 5.1 manager tests shell: powershell run: .\tests\Test-Manager.ps1 @@ -83,11 +104,13 @@ jobs: timeout-minutes: 10 permissions: contents: write + id-token: write + attestations: write steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - - uses: actions/setup-node@v7 + - uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0 with: node-version: 22 - name: Resolve release metadata and changelog notes @@ -115,14 +138,18 @@ jobs: exit 1 fi done - if grep -Eq "^${prefix}/(tests|scripts|\.github|web/src|web/e2e|web/package-lock\.json)(/|$)" <<< "${entries}"; then + if grep -Eq "^${prefix}/(tests|scripts|\.github|\.PSScriptAnalyzerSettings\.psd1|web/src|web/e2e|web/package-lock\.json)(/|$)" <<< "${entries}"; then echo "Release archive contains excluded development files:" >&2 - grep -E "^${prefix}/(tests|scripts|\.github|web/src|web/e2e|web/package-lock\.json)(/|$)" <<< "${entries}" + grep -E "^${prefix}/(tests|scripts|\.github|\.PSScriptAnalyzerSettings\.psd1|web/src|web/e2e|web/package-lock\.json)(/|$)" <<< "${entries}" exit 1 fi sha256sum "${archive}" > "${archive}.sha256" sha256sum -c "${archive}.sha256" echo "RELEASE_ARCHIVE=${archive}" >> "${GITHUB_ENV}" + - name: Generate build provenance attestation + uses: actions/attest-build-provenance@96278af6caaf10aea03fd8d33a09a777ca52d62f # v3.2.0 + with: + subject-path: ${{ env.RELEASE_ARCHIVE }} - name: Publish GitHub release env: GH_TOKEN: ${{ github.token }} diff --git a/tests/Test-Hardening.ps1 b/tests/Test-Hardening.ps1 index 1a1f6bb..2c2df09 100644 --- a/tests/Test-Hardening.ps1 +++ b/tests/Test-Hardening.ps1 @@ -2022,10 +2022,64 @@ Set-StrictMode -Version Latest TaskDis = (New-MockComTask -Description 'Managed by clash-ssh-proxy-bootstrap; target=dis-t; destination=u2@203.0.113.11' -TaskEnabled $false -TaskState 1 -LogonEnabled $true) TaskUnown = (New-MockComTask -Description 'Some third-party task' -TaskEnabled $true -TaskState 3 -LogonEnabled $true -ComHandlerAction) } + function Copy-MockComTask { + param($SourceTask) + $clonedActions = New-Object 'System.Collections.Generic.List[object]' + for ($actIdx = 0; $actIdx -lt $SourceTask.Definition.Actions.Items.Count; $actIdx++) { + $act = $SourceTask.Definition.Actions.Items[$actIdx] + $actCopy = [pscustomobject]@{} + foreach ($prop in $act.PSObject.Properties) { + Add-Member -InputObject $actCopy -NotePropertyName $prop.Name -NotePropertyValue $prop.Value -Force + } + [void]$clonedActions.Add($actCopy) + } + $actionsObj = [pscustomobject]@{ Items = $clonedActions } + Add-Member -InputObject $actionsObj -MemberType ScriptProperty -Name Count -Value { return $this.Items.Count } + Add-Member -InputObject $actionsObj -MemberType ScriptMethod -Name Item -Value { param($i) return $this.Items[$i - 1] } + + $clonedTriggers = New-Object 'System.Collections.Generic.List[object]' + for ($trigIdx = 0; $trigIdx -lt $SourceTask.Definition.Triggers.Items.Count; $trigIdx++) { + $trig = $SourceTask.Definition.Triggers.Items[$trigIdx] + [void]$clonedTriggers.Add([pscustomobject]@{ + Type = [int]$trig.Type + Enabled = [bool]$trig.Enabled + Delay = [string]$trig.Delay + UserId = [string]$trig.UserId + }) + } + $triggersObj = [pscustomobject]@{ Items = $clonedTriggers } + Add-Member -InputObject $triggersObj -MemberType ScriptProperty -Name Count -Value { return $this.Items.Count } + Add-Member -InputObject $triggersObj -MemberType ScriptMethod -Name Item -Value { param($i) return $this.Items[$i - 1] } + Add-Member -InputObject $triggersObj -MemberType ScriptMethod -Name Create -Value { + param([int]$TriggerType) + $created = [pscustomobject]@{ Type = $TriggerType; Enabled = $true; Delay = ''; UserId = '' } + [void]$this.Items.Add($created) + return $created + } + Add-Member -InputObject $triggersObj -MemberType ScriptMethod -Name Remove -Value { + param([int]$Index) + $this.Items.RemoveAt($Index - 1) + } + $defObj = [pscustomobject]@{ + RegistrationInfo = [pscustomobject]@{ Description = [string]$SourceTask.Definition.RegistrationInfo.Description } + Actions = $actionsObj + Triggers = $triggersObj + Settings = [pscustomobject]@{ Enabled = [bool]$SourceTask.Definition.Settings.Enabled } + Principal = [pscustomobject]@{ + LogonType = [int]$SourceTask.Definition.Principal.LogonType + UserId = [string]$SourceTask.Definition.Principal.UserId + } + } + return [pscustomobject]@{ + Enabled = [bool]$SourceTask.Enabled + State = [int]$SourceTask.State + Definition = $defObj + } + } $script:FailTaskRegisterOn = '' Set-Item Function:Get-RegisteredTaskFast -Value { param([string]$TaskName) - if ($script:MockTasks.ContainsKey($TaskName)) { return $script:MockTasks[$TaskName] } + if ($script:MockTasks.ContainsKey($TaskName)) { return (Copy-MockComTask $script:MockTasks[$TaskName]) } return $null } Set-Item Function:Register-UpdatedTaskDefinitionFast -Value { @@ -2033,8 +2087,9 @@ Set-StrictMode -Version Latest if ($script:FailTaskRegisterOn -eq $TaskName) { throw "Injected trigger update failure on $TaskName" } + $Definition.Settings.Enabled = $TaskEnabled $script:MockTasks[$TaskName].Enabled = $TaskEnabled - $script:MockTasks[$TaskName].Definition.Settings.Enabled = $TaskEnabled + $script:MockTasks[$TaskName].Definition = $Definition } $offRes = (Set-ManagerAutoStart -ConfigPath $multiConfigPath -AutoStart 'off') | ConvertFrom-Json @@ -2061,7 +2116,8 @@ Set-StrictMode -Version Latest $afterFailCfg = Read-ManagerConfig -Path $multiConfigPath if (-not $rollbackTriggered -or (Get-ManagerAutoStartSetting $afterFailCfg) -ne $false -or - $script:MockTasks['TaskRun'].Definition.Triggers.Items[0].Enabled -ne $false) { + $script:MockTasks['TaskRun'].Definition.Triggers.Items[0].Enabled -ne $false -or + $script:MockTasks['TaskDis'].Definition.Triggers.Items[0].Enabled -ne $false) { throw 'Set-ManagerAutoStart did not roll back modified task triggers and preserve config on failure' }