diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..238ea76 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,2 @@ +# Every change is reviewed by the maintainer. +* @poli0981 diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..43e6fb3 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,59 @@ +name: Bug report +description: Something does not work as expected. +labels: [bug] +body: + - type: textarea + id: what + attributes: + label: What happened? + description: What did you do, what did you expect, and what happened instead? + validations: + required: true + - type: textarea + id: steps + attributes: + label: Steps to reproduce + placeholder: | + 1. Open Generate Hash + 2. Drop a folder with ... + 3. ... + validations: + required: true + - type: input + id: version + attributes: + label: Hash Tool version + description: Shown on the About page. + placeholder: "1.2.0" + validations: + required: true + - type: dropdown + id: os + attributes: + label: Operating system + options: + - Windows 11 + - Windows 10 + - macOS (Apple silicon) + - macOS (Intel) + - Linux + validations: + required: true + - type: dropdown + id: install + attributes: + label: How did you install it? + options: + - Installer (Setup) + - Portable + - Linux AppImage + - Command-line tool (hashtool) + - Built from source + - type: textarea + id: logs + attributes: + label: Logs + description: > + Settings > Configuration > Open Data Folder, then the "log" folder. User folders are already masked in the log, + but please check before posting. + render: text diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..912644c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,8 @@ +blank_issues_enabled: false +contact_links: + - name: Report a security vulnerability + url: https://github.com/poli0981/HashTool/security/advisories/new + about: Please report security issues privately, not as public issues. + - name: Questions and ideas + url: https://github.com/poli0981/HashTool/discussions + about: Ask questions or discuss ideas before opening a feature request. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..bffd7e0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,20 @@ +name: Feature request +description: Suggest an improvement or a new feature. +labels: [enhancement] +body: + - type: textarea + id: problem + attributes: + label: What problem would this solve? + validations: + required: true + - type: textarea + id: idea + attributes: + label: What would you like to happen? + validations: + required: true + - type: textarea + id: alternatives + attributes: + label: Alternatives you have considered diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..deada83 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,14 @@ +## What and why + + + +## How it was tested + + + +## Checklist + +- [ ] `dotnet build HashTool.slnx -warnaserror` and `dotnet test --solution HashTool.slnx` pass +- [ ] `dotnet format HashTool.slnx --verify-no-changes` passes +- [ ] New or changed UI text is added to every language (`python -I eng/loc.py check` passes) +- [ ] User-visible changes are listed under `[Unreleased]` in CHANGELOG.md diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..3e872b1 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,38 @@ +version: 2 + +updates: + - package-ecosystem: nuget + directory: / + schedule: + interval: weekly + day: monday + open-pull-requests-limit: 10 + # The upgrade gate deliberately pins the Velopack library that Hash Tool 1.1.x shipped. + exclude-paths: + - "tests/Compat/**" + groups: + avalonia: + patterns: ["Avalonia*", "Material.Icons*"] + microsoft: + patterns: ["Microsoft.Extensions.*", "System.*"] + tests: + patterns: ["xunit*", "Microsoft.Testing.*", "BenchmarkDotNet*"] + ignore: + # xunit.v3 4.x breaks Avalonia.Headless.XUnit (AvaloniaUI/Avalonia#22072). + - dependency-name: "xunit.v3*" + update-types: ["version-update:semver-major"] + + - package-ecosystem: dotnet-sdk + directory: / + schedule: + interval: weekly + day: monday + + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + day: monday + groups: + actions: + patterns: ["*"] diff --git a/.github/workflows/announce-release.yml b/.github/workflows/announce-release.yml index 392e871..9df8569 100644 --- a/.github/workflows/announce-release.yml +++ b/.github/workflows/announce-release.yml @@ -1,5 +1,7 @@ name: Announce Release to Discord +# Releases published by the Release workflow are announced from there (events created with GITHUB_TOKEN do not start +# other workflows). This covers releases published by hand and re-announcements. on: release: types: [published] @@ -10,14 +12,15 @@ on: required: true type: string -# Reusable announce-release.yml only needs `contents: read` to fetch -# release metadata via the gh CLI. -permissions: - contents: read +permissions: {} jobs: announce: - uses: poli0981/.github/.github/workflows/announce-release.yml@main + permissions: + contents: read + uses: poli0981/.github/.github/workflows/announce-release.yml@c3e118a01d40e95b36b2c3466dc206638c11eb5a with: tag_override: ${{ inputs.tag || '' }} - secrets: inherit \ No newline at end of file + secrets: + DISCORD_RELEASES_WEBHOOK: ${{ secrets.DISCORD_RELEASES_WEBHOOK }} + DISCORD_REPO_WEBHOOK: ${{ secrets.DISCORD_REPO_WEBHOOK }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6ed7f12..b965b7e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,6 +16,7 @@ env: DOTNET_NOLOGO: true DOTNET_CLI_TELEMETRY_OPTOUT: true DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true + AVALONIA_TELEMETRY_OPTOUT: 1 jobs: build-test: @@ -46,8 +47,9 @@ jobs: - name: Restore run: dotnet restore HashTool.slnx + # Warnings fail the build, including NuGet audit (NU1901-NU1904) for vulnerable packages. - name: Build - run: dotnet build HashTool.slnx -c Release --no-restore + run: dotnet build HashTool.slnx -c Release --no-restore -warnaserror - name: Test run: > @@ -55,6 +57,17 @@ jobs: --results-directory TestResults --coverage --coverage-output-format cobertura + - name: Coverage gate (HashTool.Core >= 80%) + if: runner.os == 'Linux' + run: python3 -I eng/coverage-gate.py TestResults HashTool.Core 80 + + # Starts the real app headless: every page, every language, hashing and verifying a file. + - name: Smoke test + shell: bash + env: + HASHTOOL_DATA_DIR: ${{ runner.temp }}/smoke-data + run: dotnet src/HashTool.App/bin/Release/net10.0/CheckHash.dll --smoke-test --smoke-out TestResults/smoke.json + - name: Upload test results if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 @@ -84,3 +97,23 @@ jobs: - name: Check formatting run: dotnet format HashTool.slnx --no-restore --verify-no-changes --verbosity minimal + + - name: Check translations + run: python3 -I eng/loc.py check + + # Single required status check for branch protection. + ci-ok: + name: ci-ok + if: always() + needs: [build-test, format] + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: {} + steps: + - name: All CI jobs passed + env: + BUILD_TEST: ${{ needs.build-test.result }} + FORMAT: ${{ needs.format.result }} + run: | + echo "build-test: $BUILD_TEST, format: $FORMAT" + test "$BUILD_TEST" = success && test "$FORMAT" = success diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml new file mode 100644 index 0000000..6c248fd --- /dev/null +++ b/.github/workflows/dependency-review.yml @@ -0,0 +1,24 @@ +name: Dependency Review + +on: + pull_request: + +permissions: {} + +jobs: + dependency-review: + name: dependency-review + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + # Licenses are checked by the Security workflow (nuget-license reads the exact NuGet metadata). + - uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0 + with: + fail-on-severity: moderate + license-check: false diff --git a/.github/workflows/dependency-submission.yml b/.github/workflows/dependency-submission.yml new file mode 100644 index 0000000..dfbd6d4 --- /dev/null +++ b/.github/workflows/dependency-submission.yml @@ -0,0 +1,34 @@ +name: Dependency Submission + +# Submits the resolved NuGet graph, including transitive packages, so Dependabot alerts cover packages that are only +# pulled in indirectly (central package management hides versions from GitHub's static parser). +on: + push: + branches: [main] + workflow_dispatch: + +permissions: {} + +jobs: + submit: + name: submit + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: 10.0.4xx + + - name: Restore + run: dotnet restore HashTool.slnx + + - uses: advanced-security/component-detection-dependency-submission-action@a02aeda7a175ad4dd38a13c4d3ff2df9da8f2cf0 # v0.2.0 + with: + detectorsCategories: NuGet + directoryExclusionList: "**/tests/Compat/**" diff --git a/.github/workflows/notify-ci-failure.yml b/.github/workflows/notify-ci-failure.yml index d9fe9cd..fc1ea11 100644 --- a/.github/workflows/notify-ci-failure.yml +++ b/.github/workflows/notify-ci-failure.yml @@ -2,16 +2,21 @@ name: Notify CI Failures on: workflow_run: - workflows: ["*"] + workflows: [CI, Security, Scorecard] types: [completed] -# REQUIRED: declare permissions matching the reusable workflow's needs. -# Reusable needs `actions: read` to inspect workflow_run details. -permissions: - contents: read - actions: read +permissions: {} jobs: notify: - uses: poli0981/.github/.github/workflows/notify-ci-failure.yml@main - secrets: inherit \ No newline at end of file + # Failures on this repository's own pushes and schedules only; fork pull requests cannot trigger a message. + if: > + github.event.workflow_run.conclusion == 'failure' && + github.event.workflow_run.head_repository.full_name == github.repository && + contains(fromJSON('["push", "schedule", "workflow_dispatch"]'), github.event.workflow_run.event) + permissions: + contents: read + actions: read + uses: poli0981/.github/.github/workflows/notify-ci-failure.yml@c3e118a01d40e95b36b2c3466dc206638c11eb5a + secrets: + DISCORD_CI_WEBHOOK: ${{ secrets.DISCORD_CI_WEBHOOK }} diff --git a/.github/workflows/notify-release-pipeline.yml b/.github/workflows/notify-release-pipeline.yml index 148a576..4d2f35c 100644 --- a/.github/workflows/notify-release-pipeline.yml +++ b/.github/workflows/notify-release-pipeline.yml @@ -2,14 +2,18 @@ name: Notify Release Pipeline on: workflow_run: - workflows: ["*"] + workflows: [Release] types: [completed] -permissions: - contents: read - actions: read +permissions: {} jobs: notify: - uses: poli0981/.github/.github/workflows/notify-release-pipeline.yml@main - secrets: inherit \ No newline at end of file + # Only real releases (started by hand), never pull request dry runs. + if: github.event.workflow_run.event == 'workflow_dispatch' + permissions: + contents: read + actions: read + uses: poli0981/.github/.github/workflows/notify-release-pipeline.yml@c3e118a01d40e95b36b2c3466dc206638c11eb5a + secrets: + DISCORD_RELEASE_PIPELINE_WEBHOOK: ${{ secrets.DISCORD_RELEASE_PIPELINE_WEBHOOK }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..f32d799 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,456 @@ +name: Release + +# Builds, packages and tests every platform; publishes only when started by hand with publish=true. +# Pull requests that touch the release machinery get a full dry run (nothing is published). +on: + workflow_dispatch: + inputs: + version: + description: "Version without a leading v, e.g. 1.2.0 (must match Directory.Build.props to publish)" + required: true + type: string + publish: + description: "Publish the GitHub release (unchecked = dry run)" + required: true + type: boolean + default: false + pull_request: + paths: + - .github/workflows/release.yml + - build/** + - eng/assert-release.py + - eng/release-notes.py + - tests/Compat/** + +permissions: {} + +concurrency: + group: release-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + DOTNET_NOLOGO: true + DOTNET_CLI_TELEMETRY_OPTOUT: true + AVALONIA_TELEMETRY_OPTOUT: 1 + PACK_ID: HashTool + # The release 1.x clients update from in the upgrade gate. + LEGACY_VERSION: 1.1.3 + +jobs: + prepare: + name: prepare + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + outputs: + version: ${{ steps.version.outputs.version }} + publish: ${{ steps.version.outputs.publish }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Resolve version + id: version + env: + EVENT: ${{ github.event_name }} + INPUT_VERSION: ${{ inputs.version }} + INPUT_PUBLISH: ${{ inputs.publish }} + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + project=$(sed -n 's:.*\(.*\).*:\1:p' Directory.Build.props) + if [ "$EVENT" = workflow_dispatch ]; then + version="$INPUT_VERSION" + publish="$INPUT_PUBLISH" + else + # Pull request dry run: a pre-release above the last release, so the upgrade gate still applies. + version="$project-ci.$GITHUB_RUN_NUMBER" + publish=false + fi + if ! [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]]; then + echo "::error::'$version' is not a valid version (expected 1.2.3 or 1.2.3-suffix, no leading v)" + exit 1 + fi + if [ "$publish" = true ]; then + if [ "$version" != "$project" ]; then + echo "::error::Version $version does not match Directory.Build.props ($project)" + exit 1 + fi + if [ "$GITHUB_REF" != refs/heads/main ]; then + echo "::error::Releases are published from main only (got $GITHUB_REF)" + exit 1 + fi + if gh release view "$version" --repo "$GITHUB_REPOSITORY" > /dev/null 2>&1; then + echo "::error::Release $version already exists" + exit 1 + fi + fi + { + echo "version=$version" + echo "publish=$publish" + echo "notes=$project" + } >> "$GITHUB_OUTPUT" + echo "Version $version (publish: $publish)" + + - name: Release notes + env: + NOTES_VERSION: ${{ steps.version.outputs.notes }} + PUBLISH: ${{ steps.version.outputs.publish }} + run: | + set -euo pipefail + flags=() + if [ "$PUBLISH" = true ]; then flags+=(--require-date); fi + python3 -I eng/release-notes.py "$NOTES_VERSION" "${flags[@]}" > release-notes.md + cat release-notes.md + + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: notes + path: release-notes.md + retention-days: 7 + + app: + name: app (${{ matrix.channel }}) + needs: prepare + strategy: + fail-fast: false + matrix: + include: + - { os: windows-2025, rid: win-x64, channel: win, exe: CheckHash.exe } + - { os: macos-15, rid: osx-arm64, channel: osx, exe: CheckHash } + - { os: macos-15-intel, rid: osx-x64, channel: osx-x64, exe: CheckHash } + - { os: ubuntu-24.04, rid: linux-x64, channel: linux, exe: CheckHash } + runs-on: ${{ matrix.os }} + timeout-minutes: 45 + permissions: + contents: read + env: + VERSION: ${{ needs.prepare.outputs.version }} + RID: ${{ matrix.rid }} + CHANNEL: ${{ matrix.channel }} + MAIN_EXE: ${{ matrix.exe }} + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: 10.0.4xx + + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: notes + + - name: Install tools + run: | + dotnet tool restore + if [ "$RUNNER_OS" = Linux ]; then sudo apt-get update -q && sudo apt-get install -y -q squashfs-tools; fi + + # Same shape as every 1.x release: self-contained single file, CheckHash(.exe) as the main executable. + - name: Publish + run: > + dotnet publish src/HashTool.App/HashTool.App.csproj -c Release -r "$RID" --self-contained + -p:PublishSingleFile=true -p:Version="$VERSION" -o "publish/$RID" + + - name: Smoke test + env: + HASHTOOL_DATA_DIR: ${{ runner.temp }}/smoke + run: '"publish/$RID/$MAIN_EXE" --smoke-test --expect-version "$VERSION"' + + - name: Pack (Windows) + if: runner.os == 'Windows' + run: > + dotnet vpk pack -u "$PACK_ID" -v "$VERSION" -p "publish/$RID" -e "$MAIN_EXE" -c "$CHANNEL" -r "$RID" + --icon src/HashTool.App/Assets/icon/favicon.ico --delta None --releaseNotes release-notes.md -o Releases + + # The custom Info.plist keeps the 1.x bundle identity and adds "Open With" document types. + - name: Pack (macOS) + if: runner.os == 'macOS' + run: | + sed "s/@VERSION@/$VERSION/g" build/macos/Info.plist > "$RUNNER_TEMP/Info.plist" + plutil -lint "$RUNNER_TEMP/Info.plist" + dotnet vpk pack -u "$PACK_ID" -v "$VERSION" -p "publish/$RID" -e "$MAIN_EXE" -c "$CHANNEL" -r "$RID" \ + --packTitle "Hash Tool" --bundleId com.HashTool.HashTool --plist "$RUNNER_TEMP/Info.plist" \ + --icon src/HashTool.App/Assets/icon/icons.icns --delta None --releaseNotes release-notes.md -o Releases + + - name: Pack (Linux) + if: runner.os == 'Linux' + run: > + dotnet vpk pack -u "$PACK_ID" -v "$VERSION" -p "publish/$RID" -e "$MAIN_EXE" -c "$CHANNEL" -r "$RID" + --packTitle "Hash Tool" --icon build/linux/hashtool.png --categories Utility + --delta None --releaseNotes release-notes.md -o Releases + + - name: Check packages + run: | + bundle_id=() + if [ "$RUNNER_OS" = macOS ]; then bundle_id=(com.HashTool.HashTool); fi + python3 -I eng/assert-release.py Releases "$CHANNEL" "$VERSION" "$MAIN_EXE" "${bundle_id[@]}" + + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: release-${{ matrix.channel }} + path: Releases/* + if-no-files-found: error + retention-days: 7 + + # Updates a real Hash Tool 1.1.3 with its own Velopack 0.0.1298 library and updater, then starts the result. + upgrade-gate: + name: upgrade-gate (${{ matrix.channel }}) + needs: [prepare, app] + strategy: + fail-fast: false + matrix: + include: + - { os: windows-2025, channel: win } + - { os: macos-15, channel: osx } + runs-on: ${{ matrix.os }} + timeout-minutes: 30 + permissions: + contents: read + env: + VERSION: ${{ needs.prepare.outputs.version }} + CHANNEL: ${{ matrix.channel }} + GH_TOKEN: ${{ github.token }} + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: 10.0.4xx + + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: release-${{ matrix.channel }} + path: Releases + + - name: Install Hash Tool ${{ env.LEGACY_VERSION }} (portable) + run: | + set -euo pipefail + gh release download "$LEGACY_VERSION" --repo "$GITHUB_REPOSITORY" -p "HashTool-$CHANNEL-Portable.zip" -D "$RUNNER_TEMP" + mkdir -p "$RUNNER_TEMP/legacy" + if [ "$RUNNER_OS" = macOS ]; then + ditto -x -k "$RUNNER_TEMP/HashTool-$CHANNEL-Portable.zip" "$RUNNER_TEMP/legacy" + root="$RUNNER_TEMP/legacy/Hash Tool.app" + app="$root/Contents/MacOS" + update="$app/UpdateMac" + exe="$app/CheckHash" + else + unzip -q "$RUNNER_TEMP/HashTool-$CHANNEL-Portable.zip" -d "$RUNNER_TEMP/legacy" + root="$RUNNER_TEMP/legacy" + app="$root/current" + update="$root/Update.exe" + exe="$app/CheckHash.exe" + fi + ls -la "$app" + test -x "$update" -o -f "$update" + { + echo "LEGACY_ROOT=$root" + echo "LEGACY_APP=$app" + echo "LEGACY_UPDATE=$update" + echo "LEGACY_EXE=$exe" + } >> "$GITHUB_ENV" + + - name: Find and download the update with Velopack 0.0.1298 + run: | + set -euo pipefail + package=$(dotnet run --project tests/Compat/LegacyClient -c Release -- \ + "$PWD/Releases" "$CHANNEL" "$LEGACY_VERSION" "$VERSION" "$LEGACY_ROOT" "$LEGACY_APP" "$LEGACY_UPDATE" "$RUNNER_TEMP/packages") + echo "UPDATE_PACKAGE=$package" >> "$GITHUB_ENV" + + - name: Apply with the ${{ env.LEGACY_VERSION }} updater + run: | + "$LEGACY_UPDATE" --silent --verbose --log "$RUNNER_TEMP/update.log" apply --package "$UPDATE_PACKAGE" --norestart + # The updater may finish its work in a child process; wait for the new version to appear. + for _ in $(seq 1 60); do + if grep -q "applied successfully" "$RUNNER_TEMP/update.log" 2> /dev/null; then break; fi + sleep 2 + done + tail -n 40 "$RUNNER_TEMP/update.log" + + - name: Start the updated app + env: + HASHTOOL_DATA_DIR: ${{ runner.temp }}/smoke + run: '"$LEGACY_EXE" --smoke-test --expect-version "$VERSION"' + + - name: Upload updater log + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: upgrade-gate-log-${{ matrix.channel }} + path: ${{ runner.temp }}/update.log + if-no-files-found: ignore + retention-days: 7 + + cli: + name: cli (${{ matrix.rid }}) + needs: prepare + strategy: + fail-fast: false + matrix: + include: + - { os: windows-2025, rid: win-x64, exe: hashtool.exe } + - { os: macos-15, rid: osx-arm64, exe: hashtool } + - { os: macos-15-intel, rid: osx-x64, exe: hashtool } + # Built on the oldest supported Ubuntu so the native binary runs on older glibc. + - { os: ubuntu-22.04, rid: linux-x64, exe: hashtool } + runs-on: ${{ matrix.os }} + timeout-minutes: 30 + permissions: + contents: read + env: + VERSION: ${{ needs.prepare.outputs.version }} + RID: ${{ matrix.rid }} + EXE: ${{ matrix.exe }} + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: 10.0.4xx + + - name: Install native toolchain (Linux) + if: runner.os == 'Linux' + run: sudo apt-get update -q && sudo apt-get install -y -q clang zlib1g-dev + + - name: Publish (NativeAOT) + run: | + set -euo pipefail + name="hashtool-$VERSION-$RID" + dotnet publish src/HashTool.Cli/HashTool.Cli.csproj -c Release -r "$RID" -p:Version="$VERSION" -o "cli/$name" + rm -rf "cli/$name"/*.pdb "cli/$name"/*.dbg "cli/$name"/*.dSYM + cp LICENSE "cli/$name/" + ls -la "cli/$name" + echo "CLI_NAME=$name" >> "$GITHUB_ENV" + + - name: Test the binary + run: | + set -euo pipefail + bin="cli/$CLI_NAME/$EXE" + test "$("$bin" --version)" = "$VERSION" + printf '123456789' > "$RUNNER_TEMP/check.txt" + "$bin" hash -a crc32 "$RUNNER_TEMP/check.txt" | grep -q '^cbf43926 ' + "$bin" check "$RUNNER_TEMP/check.txt" -e 15e2b0d3c33891ebb0f1ef609ec419420c20e320ce94c65fbc8c3312448eb225 + + - name: Archive + run: | + set -euo pipefail + mkdir -p dist + if [ "$RUNNER_OS" = Windows ]; then + pwsh -NoProfile -Command "Compress-Archive -Path 'cli/$CLI_NAME' -DestinationPath 'dist/$CLI_NAME.zip'" + else + tar -czf "dist/$CLI_NAME.tar.gz" -C cli "$CLI_NAME" + fi + ls -la dist + + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: cli-${{ matrix.rid }} + path: dist/* + if-no-files-found: error + retention-days: 7 + + publish: + name: publish + needs: [prepare, app, upgrade-gate, cli] + if: needs.prepare.outputs.publish == 'true' + runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + contents: write + id-token: write + attestations: write + env: + VERSION: ${{ needs.prepare.outputs.version }} + GH_TOKEN: ${{ github.token }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: 10.0.4xx + + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: "{release,cli}-*" + path: dist + merge-multiple: true + + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: notes + + - name: SBOM and checksums + run: | + set -euo pipefail + dotnet tool restore + dotnet CycloneDX src/HashTool.App/HashTool.App.csproj -rs -F Json -o dist -fn "hashtool-app-$VERSION.cdx.json" -sn "Hash Tool" -sv "$VERSION" + dotnet CycloneDX src/HashTool.Cli/HashTool.Cli.csproj -rs -F Json -o dist -fn "hashtool-cli-$VERSION.cdx.json" -sn "Hash Tool CLI" -sv "$VERSION" + (cd dist && sha256sum -- * > SHA256SUMS) + cat dist/SHA256SUMS + + - name: Check the asset list + run: | + set -euo pipefail + cd dist + for f in \ + "HashTool-$VERSION-full.nupkg" HashTool-win-Setup.exe HashTool-win-Portable.zip releases.win.json assets.win.json RELEASES \ + "HashTool-$VERSION-osx-full.nupkg" HashTool-osx-Setup.pkg HashTool-osx-Portable.zip releases.osx.json assets.osx.json \ + "HashTool-$VERSION-osx-x64-full.nupkg" releases.osx-x64.json assets.osx-x64.json \ + "HashTool-$VERSION-linux-full.nupkg" releases.linux.json assets.linux.json \ + "hashtool-$VERSION-win-x64.zip" "hashtool-$VERSION-linux-x64.tar.gz" \ + "hashtool-$VERSION-osx-arm64.tar.gz" "hashtool-$VERSION-osx-x64.tar.gz" SHA256SUMS; do + test -f "$f" || { echo "::error::Missing release asset $f"; exit 1; } + done + ls -la + + - uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 + with: + subject-path: dist/* + + # Draft first, verify every upload, then publish: users never see a half-uploaded release. + - name: Create release + run: | + set -euo pipefail + gh release create "$VERSION" --repo "$GITHUB_REPOSITORY" --draft --target "$GITHUB_SHA" \ + --title "Hash Tool $VERSION" --notes-file release-notes.md + gh release upload "$VERSION" --repo "$GITHUB_REPOSITORY" dist/* + expected=$(cd dist && ls -1 | sort) + actual=$(gh release view "$VERSION" --repo "$GITHUB_REPOSITORY" --json assets --jq '.assets[].name' | sort) + if [ "$expected" != "$actual" ]; then + echo "::error::Uploaded assets differ from the build output" + diff <(echo "$expected") <(echo "$actual") || true + exit 1 + fi + gh release edit "$VERSION" --repo "$GITHUB_REPOSITORY" --draft=false --latest + echo "Published https://github.com/$GITHUB_REPOSITORY/releases/tag/$VERSION" + + # A release published with GITHUB_TOKEN does not trigger other workflows, so announce it from here. + announce: + name: announce + needs: [prepare, publish] + permissions: + contents: read + uses: poli0981/.github/.github/workflows/announce-release.yml@c3e118a01d40e95b36b2c3466dc206638c11eb5a + with: + tag_override: ${{ needs.prepare.outputs.version }} + secrets: + DISCORD_RELEASES_WEBHOOK: ${{ secrets.DISCORD_RELEASES_WEBHOOK }} + DISCORD_REPO_WEBHOOK: ${{ secrets.DISCORD_REPO_WEBHOOK }} diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml new file mode 100644 index 0000000..f95ad03 --- /dev/null +++ b/.github/workflows/scorecard.yml @@ -0,0 +1,36 @@ +name: Scorecard + +on: + push: + branches: [main] + schedule: + - cron: "41 5 * * 2" + branch_protection_rule: + workflow_dispatch: + +permissions: {} + +jobs: + analysis: + name: analysis + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + actions: read + security-events: write + id-token: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: ossf/scorecard-action@fa7117db83c52d787ae5a89f350999701505d78e # v2.5.0 + with: + results_file: results.sarif + results_format: sarif + publish_results: true + + - uses: github/codeql-action/upload-sarif@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3 + with: + sarif_file: results.sarif diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml new file mode 100644 index 0000000..c03c41d --- /dev/null +++ b/.github/workflows/security.yml @@ -0,0 +1,119 @@ +name: Security + +on: + push: + branches: [main] + pull_request: + schedule: + - cron: "23 4 * * 1" + workflow_dispatch: + +permissions: {} + +concurrency: + group: security-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +env: + DOTNET_NOLOGO: true + DOTNET_CLI_TELEMETRY_OPTOUT: true + AVALONIA_TELEMETRY_OPTOUT: 1 + +jobs: + # `dotnet package list --vulnerable` always exits 0, so the JSON report is checked explicitly. + vulnerable-packages: + name: vulnerable-packages + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: 10.0.4xx + + - name: Restore + run: dotnet restore HashTool.slnx + + - name: List vulnerable packages + run: | + dotnet package list --project HashTool.slnx --vulnerable --include-transitive --format json > vulnerable.json + jq -r '.projects[]? | .path as $p | .frameworks[]? | (.topLevelPackages[]?, .transitivePackages[]?) + | select((.vulnerabilities // []) | length > 0) + | "\($p): \(.id) \(.resolvedVersion) - \([.vulnerabilities[].severity] | join(", ")) \([.vulnerabilities[].advisoryurl] | join(" "))"' vulnerable.json \ + | sort -u | tee vulnerable.txt + if [ -s vulnerable.txt ]; then + echo "::error::Vulnerable NuGet packages found (see above)." + exit 1 + fi + echo "No known vulnerable packages." + + # Only shipped projects are checked; test and benchmark tools are not redistributed. + licenses: + name: licenses + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: 10.0.4xx + + - name: Restore + run: | + dotnet tool restore + dotnet restore HashTool.slnx + + - name: Check licenses + run: > + dotnet nuget-license -ji eng/license-inputs.json -t + -a eng/allowed-licenses.json -o Markdown + + secrets: + name: secrets + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + + - uses: gitleaks/gitleaks-action@e0c47f4f8be36e29cdc102c57e68cb5cbf0e8d1e # v3.0.0 + env: + GITHUB_TOKEN: ${{ github.token }} + GITLEAKS_ENABLE_COMMENTS: false + GITLEAKS_ENABLE_UPLOAD_ARTIFACT: false + + workflows: + name: workflows + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + # Built from source through the Go module proxy, which verifies it against the checksum database. + - name: actionlint + run: go run github.com/rhysd/actionlint/cmd/actionlint@v1.7.12 -color + + - name: zizmor + uses: zizmorcore/zizmor-action@cc914d7f3750a2d13d75c7f184a1060aa0e9d482 # v0.6.4 + with: + version: 1.30.1 + config: .github/zizmor.yml + advanced-security: false diff --git a/.github/zizmor.yml b/.github/zizmor.yml new file mode 100644 index 0000000..eac5e16 --- /dev/null +++ b/.github/zizmor.yml @@ -0,0 +1,7 @@ +rules: + dangerous-triggers: + ignore: + # workflow_run is the only way to report other workflows' results. These jobs check out no code from the + # triggering run, only call the maintainer's pinned notifier, and are limited to this repository's own runs. + - notify-ci-failure.yml + - notify-release-pipeline.yml diff --git a/eng/allowed-licenses.json b/eng/allowed-licenses.json new file mode 100644 index 0000000..a6e9325 --- /dev/null +++ b/eng/allowed-licenses.json @@ -0,0 +1,10 @@ +[ + "MIT", + "Apache-2.0", + "BSD-2-Clause", + "BSD-3-Clause", + "OFL-1.1", + "MS-PL", + "Zlib", + "ISC" +] diff --git a/eng/assert-release.py b/eng/assert-release.py new file mode 100644 index 0000000..72c0264 --- /dev/null +++ b/eng/assert-release.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +"""Checks the files `vpk pack` produced for one channel before anything is published. + + python -I eng/assert-release.py [] + +Verifies that the feed (releases..json) lists exactly the new full package with the right size and SHA-256, +that every file in assets..json exists, and that the package carries the identity 1.x clients expect: +pack id HashTool, the channel, the main executable and, on macOS, the original bundle identifier. +""" + +import hashlib +import json +import plistlib +import re +import sys +import zipfile +from pathlib import Path + +PACK_ID = "HashTool" + + +def fail(message: str) -> None: + print(f"::error::{message}") + sys.exit(1) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(1 << 20), b""): + digest.update(block) + return digest.hexdigest().upper() + + +def manifest_value(text: str, element: str) -> str | None: + match = re.search(rf"<{element}>(.*?)", text, re.S) + return match.group(1).strip() if match else None + + +def main(releases: Path, channel: str, version: str, main_exe: str, bundle_id: str | None) -> None: + feed_path = releases / f"releases.{channel}.json" + if not feed_path.exists(): + fail(f"{feed_path.name} is missing") + feed = json.loads(feed_path.read_text(encoding="utf-8-sig")) + full = [a for a in feed.get("Assets", []) if a.get("Type") == "Full"] + if len(full) != 1 or full[0].get("Version") != version or full[0].get("PackageId") != PACK_ID: + fail(f"{feed_path.name} should list one {PACK_ID} {version} full package, found {full}") + package = releases / full[0]["FileName"] + if not package.exists(): + fail(f"{package.name} is missing") + if package.stat().st_size != full[0]["Size"] or sha256(package) != full[0]["SHA256"].upper(): + fail(f"{package.name} does not match the size/SHA-256 in {feed_path.name}") + + assets_path = releases / f"assets.{channel}.json" + if not assets_path.exists(): + fail(f"{assets_path.name} is missing") + assets = json.loads(assets_path.read_text(encoding="utf-8-sig")) + for asset in assets: + if not (releases / asset["RelativeFileName"]).exists(): + fail(f"{asset['RelativeFileName']} (listed in {assets_path.name}) is missing") + kinds = {asset["Type"] for asset in assets} + if "Full" not in kinds or not kinds & {"Installer", "Portable"}: + fail(f"{assets_path.name} should contain the full package and an installer or portable build, found {sorted(kinds)}") + + with zipfile.ZipFile(package) as archive: + names = archive.namelist() + versions = [n for n in names if n.endswith("sq.version")] + if len(versions) != 1: + fail(f"{package.name} should contain one sq.version, found {versions}") + manifest = archive.read(versions[0]).decode("utf-8-sig") + expected = {"id": PACK_ID, "version": version, "channel": channel, "mainExe": main_exe} + for element, value in expected.items(): + if manifest_value(manifest, element) != value: + fail(f"sq.version has {element}={manifest_value(manifest, element)!r}, expected {value!r}") + if not any(n.endswith("/" + main_exe) for n in names): + fail(f"{package.name} does not contain {main_exe}") + + if bundle_id is not None: + plists = [n for n in names if n.endswith("Contents/Info.plist")] + if len(plists) != 1: + fail(f"{package.name} should contain one Info.plist, found {plists}") + info = plistlib.loads(archive.read(plists[0])) + for key, value in {"CFBundleIdentifier": bundle_id, "CFBundleExecutable": main_exe, + "CFBundleName": "Hash Tool", "CFBundleVersion": version}.items(): + if info.get(key) != value: + fail(f"Info.plist has {key}={info.get(key)!r}, expected {value!r}") + + print(f"{channel}: {package.name} ({package.stat().st_size:,} bytes) and {len(assets)} assets look right") + for path in sorted(releases.iterdir()): + print(f" {path.name}") + + +if __name__ == "__main__": + if len(sys.argv) not in (5, 6): + print(__doc__) + sys.exit(2) + main(Path(sys.argv[1]), sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5] if len(sys.argv) == 6 else None) diff --git a/eng/coverage-gate.py b/eng/coverage-gate.py new file mode 100644 index 0000000..5976135 --- /dev/null +++ b/eng/coverage-gate.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +"""Fails when a package's line coverage in Cobertura reports is below a threshold. + + python -I eng/coverage-gate.py + +Every *.cobertura.xml under is read; the package's best line rate counts (each test project reports the +assemblies it loaded, so HashTool.Core shows up in several reports with different coverage). +""" + +import sys +import xml.etree.ElementTree as ElementTree +from pathlib import Path + + +def main(results: str, package: str, minimum: float) -> int: + rates = [] + for report in Path(results).rglob("*.cobertura.xml"): + for element in ElementTree.parse(report).getroot().iter("package"): + if element.get("name") == package: + rates.append(float(element.get("line-rate", "0")) * 100) + if not rates: + print(f"::error::No coverage data for {package} under {results}") + return 1 + best = max(rates) + print(f"{package}: {best:.1f}% line coverage (minimum {minimum:.0f}%)") + if best < minimum: + print(f"::error::{package} line coverage {best:.1f}% is below {minimum:.0f}%") + return 1 + return 0 + + +if __name__ == "__main__": + if len(sys.argv) != 4: + print(__doc__) + sys.exit(2) + sys.exit(main(sys.argv[1], sys.argv[2], float(sys.argv[3]))) diff --git a/eng/license-inputs.json b/eng/license-inputs.json new file mode 100644 index 0000000..63f20dd --- /dev/null +++ b/eng/license-inputs.json @@ -0,0 +1,4 @@ +[ + "src/HashTool.App/HashTool.App.csproj", + "src/HashTool.Cli/HashTool.Cli.csproj" +] diff --git a/eng/release-notes.py b/eng/release-notes.py new file mode 100644 index 0000000..67514c0 --- /dev/null +++ b/eng/release-notes.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +"""Extracts the notes of one version from CHANGELOG.md (Keep a Changelog format). + + python -I eng/release-notes.py 1.2.0 [--changelog CHANGELOG.md] [--require-date] > notes.md + +Prints the body of the "## []" section and fails when it is missing or empty, so nothing ships without notes. +--require-date additionally insists on a dated heading ("## [1.2.0] - 2026-10-15"), which a real release needs. +""" + +import argparse +import re +import sys +from pathlib import Path + +MAX_LENGTH = 20_000 + + +def find_section(changelog: str, version: str) -> tuple[str, str] | None: + heading = re.compile(rf"^## \[{re.escape(version)}\][^\n]*$", re.MULTILINE) + match = heading.search(changelog) + if match is None: + return None + following = re.compile(r"^## \[", re.MULTILINE).search(changelog, match.end()) + body = changelog[match.end():following.start() if following else len(changelog)] + # Link reference definitions ([1.2.0]: https://...) belong to the whole file. + body = re.sub(r"^\[[^\]]+\]:\s*\S+\s*$", "", body, flags=re.MULTILINE) + # A horizontal rule separating versions is not part of the notes. + body = re.sub(r"\n-{3,}\s*$", "", body.strip()) + return match.group(0), body.strip() + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("version") + parser.add_argument("--changelog", default="CHANGELOG.md") + parser.add_argument("--require-date", action="store_true") + args = parser.parse_args() + + section = find_section(Path(args.changelog).read_text(encoding="utf-8"), args.version) + if section is None or not section[1]: + print(f"::error::CHANGELOG has no notes for {args.version}", file=sys.stderr) + return 1 + heading, notes = section + if args.require_date and not re.search(r"- \d{4}-\d{2}-\d{2}\s*$", heading): + print(f"::error::The CHANGELOG heading '{heading}' has no release date", file=sys.stderr) + return 1 + if len(notes) > MAX_LENGTH: + print(f"::error::Release notes for {args.version} are {len(notes)} characters (limit {MAX_LENGTH})", file=sys.stderr) + return 1 + sys.stdout.reconfigure(encoding="utf-8") + print(notes) + return 0 + + +if __name__ == "__main__": + sys.exit(main())