diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2af69606..1584fa84 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -337,10 +337,24 @@ jobs: # Both Mac architectures from one Apple Silicon runner. Only the native one # can be smoke tested; the Intel build is checked to be the right kind of file. + # + # With signing set up (see "macOS: signing and notarization" in + # packaging/README.md), the programs, the app and the dmgs are signed with + # the Developer ID certificate under the hardened runtime, and the dmgs and + # the CLI are notarized; the dmgs get the ticket stapled. Without it, the + # signing steps are skipped and the app is signed ad hoc, as before. macos: name: macos runs-on: macos-15 - timeout-minutes: 30 + # Room for four notarization requests, which usually take minutes. + timeout-minutes: 240 + env: + # Tags are signed only when the variable SIGN_MACOS is true, dry runs + # only when SIGN_DRY_RUNS is, and either only when every secret is set. + MACOS_SIGNING: ${{ ((startsWith(github.ref, 'refs/tags/') && vars.SIGN_MACOS == 'true') || (!startsWith(github.ref, 'refs/tags/') && vars.SIGN_DRY_RUNS == 'true')) && secrets.MACOS_CERT_P12 != '' && secrets.MACOS_CERT_PASSWORD != '' && secrets.APPLE_API_KEY_P8 != '' && secrets.APPLE_API_KEY_ID != '' && secrets.APPLE_API_ISSUER_ID != '' && vars.APPLE_TEAM_ID != '' }} + # A tag with SIGN_MACOS on must not quietly ship unsigned because a + # secret is missing. + MACOS_SIGNING_REQUIRED: ${{ startsWith(github.ref, 'refs/tags/') && vars.SIGN_MACOS == 'true' }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -352,6 +366,63 @@ jobs: cargo build --release --locked -p hatchzip -p hatchzip-gui --features rar --target x86_64-apple-darwin file target/x86_64-apple-darwin/release/hatchzip | grep -q x86_64 file target/x86_64-apple-darwin/release/hatchzip-gui | grep -q x86_64 + - name: signing + run: | + if [ "$MACOS_SIGNING" = true ]; then + echo "signing with the Developer ID certificate and notarizing" + elif [ "$MACOS_SIGNING_REQUIRED" = true ]; then + echo "::error::SIGN_MACOS is true, but a macOS signing secret or APPLE_TEAM_ID is missing" + exit 1 + else + echo "signing ad hoc, Developer ID signing is not set up for this run" + fi + + # A keychain of its own, with a random password nobody sees, alone in + # the search list so codesign finds the certificate. Deleted at the end. + - name: import the Developer ID certificate + if: env.MACOS_SIGNING == 'true' + env: + MACOS_CERT_P12: ${{ secrets.MACOS_CERT_P12 }} + MACOS_CERT_PASSWORD: ${{ secrets.MACOS_CERT_PASSWORD }} + APPLE_TEAM_ID: ${{ vars.APPLE_TEAM_ID }} + run: | + keychain="$RUNNER_TEMP/hatchzip-signing.keychain-db" + p12="$RUNNER_TEMP/hatchzip-signing.p12" + password=$(openssl rand -hex 32) + echo "::add-mask::$password" + (umask 077 && printf '%s' "$MACOS_CERT_P12" | base64 --decode > "$p12") + security create-keychain -p "$password" "$keychain" + echo "MACOS_KEYCHAIN=$keychain" >> "$GITHUB_ENV" + security set-keychain-settings -lut 21600 "$keychain" + security unlock-keychain -p "$password" "$keychain" + security import "$p12" -k "$keychain" -f pkcs12 -P "$MACOS_CERT_PASSWORD" -T /usr/bin/codesign + rm -f "$p12" + security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$password" "$keychain" > /dev/null + security list-keychains -d user -s "$keychain" + security default-keychain -d user -s "$keychain" + # The identity by its SHA-1, so two certificates with one name + # can't be mixed up, and only one of this team's. + found=$(security find-identity -v -p codesigning "$keychain" | grep -F '"Developer ID Application: ' | grep -F "($APPLE_TEAM_ID)\"" || true) + if [ "$(printf '%s\n' "$found" | grep -c .)" != 1 ]; then + echo "::error::expected one Developer ID Application identity of team $APPLE_TEAM_ID in MACOS_CERT_P12" + security find-identity -v -p codesigning "$keychain" + exit 1 + fi + echo "signing as $(printf '%s' "$found" | sed 's/^[^"]*//')" + echo "MACOS_SIGN_IDENTITY=$(printf '%s' "$found" | awk '{print $2}')" >> "$GITHUB_ENV" + # Before the tests and the packaging, so both run the signed programs + # and the tarballs and their checksums hold them. build-dmg.sh signs + # its copies inside the app again, as part of the bundle. + - name: sign the programs + if: env.MACOS_SIGNING == 'true' + run: | + for arch in aarch64 x86_64; do + for bin in hatchzip hatchzip-gui; do + codesign --force --timestamp --options runtime --sign "$MACOS_SIGN_IDENTITY" "target/$arch-apple-darwin/release/$bin" + codesign --verify --strict --verbose=2 "target/$arch-apple-darwin/release/$bin" + done + done + - name: smoke test run: python3 .github/scripts/smoke.py target/aarch64-apple-darwin/release/hatchzip - name: no networking @@ -371,12 +442,119 @@ jobs: (cd dist && shasum -a 256 "$name.tar.gz" > "$name.tar.gz.sha256") done # HatchZip.app in a dmg per architecture, with the CLI from the folder - # the tarball was made from inside it. + # the tarball was made from inside it. Signed with MACOS_SIGN_IDENTITY + # when the import step set it, ad hoc otherwise. dmgbuild lays out the + # window; it is pinned with its dependencies, hashes included, in a + # venv of its own. - name: dmg run: | + python3 -m venv "$RUNNER_TEMP/dmgbuild" + "$RUNNER_TEMP/dmgbuild/bin/pip" install --quiet --no-deps --require-hashes -r packaging/macos/requirements-dmg.txt + export DMGBUILD="$RUNNER_TEMP/dmgbuild/bin/dmgbuild" for arch in aarch64 x86_64; do sh packaging/macos/build-dmg.sh "$arch" "target/$arch-apple-darwin/release/hatchzip-gui" "dist/hatchzip-$arch-macos" done + + # The dmg is the outermost container, so it's what is notarized: the + # ticket covers the app and the CLI inside it, and is stapled to the + # dmg. The CLI in the tarballs is notarized as a zip of the binary, + # since Apple doesn't take tar.gz; a bare binary can't hold a stapled + # ticket, so Gatekeeper looks that one up online. Stapling changes the + # dmg, so this comes before the tests and the checksums. + - name: notarize + if: env.MACOS_SIGNING == 'true' + env: + APPLE_API_KEY_P8: ${{ secrets.APPLE_API_KEY_P8 }} + APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }} + APPLE_API_ISSUER_ID: ${{ secrets.APPLE_API_ISSUER_ID }} + run: | + key="$RUNNER_TEMP/hatchzip-notary.p8" + trap 'rm -f "$key"' EXIT + (umask 077 && printf '%s\n' "$APPLE_API_KEY_P8" > "$key") + chmod 600 "$key" + auth=(--key "$key" --key-id "$APPLE_API_KEY_ID" --issuer "$APPLE_API_ISSUER_ID") + notarize() { + local out id status + echo "notarizing $(basename "$1")" + out=$(xcrun notarytool submit "$1" "${auth[@]}" --wait --timeout 150m --output-format json) || true + echo "$out" + id=$(jq -r '.id // empty' <<< "$out" 2> /dev/null) || id="" + status=$(jq -r '.status // empty' <<< "$out" 2> /dev/null) || status="" + if [ "$status" != Accepted ]; then + echo "::error::notarization of $(basename "$1") ended with status '${status:-none}'" + if [ -n "$id" ]; then + xcrun notarytool log "$id" "${auth[@]}" || true + fi + exit 1 + fi + } + # Three submissions at once: both CLI binaries in one zip, and each + # dmg. Apple's queue, not the upload, is what takes the time; a new + # team's first submissions can wait an hour or more. + cli="$RUNNER_TEMP/hatchzip-cli" + mkdir -p "$cli" + for arch in aarch64 x86_64; do + cp "dist/hatchzip-$arch-macos/hatchzip" "$cli/hatchzip-$arch" + done + zip="$RUNNER_TEMP/hatchzip-macos-cli.zip" + ditto -c -k --keepParent "$cli" "$zip" + pids=() + for file in "$zip" dist/HatchZip-aarch64.dmg dist/HatchZip-x86_64.dmg; do + ( notarize "$file" ) & + pids+=($!) + done + failed=0 + for pid in "${pids[@]}"; do + wait "$pid" || failed=1 + done + rm -rf "$zip" "$cli" + [ "$failed" = 0 ] || exit 1 + for arch in aarch64 x86_64; do + xcrun stapler staple "dist/HatchZip-$arch.dmg" + done + # What Gatekeeper sees: the Developer ID and hardened runtime on the + # CLI, the stapled ticket on the dmg, and the app inside it notarized. + - name: check the signatures + if: env.MACOS_SIGNING == 'true' + run: | + # Gatekeeper may be turned off on the runner, which spctl reports + # as an override instead of the source; the ticket is then checked + # by stapler alone. + gatekeeper() { + spctl "$@" 2>&1 | tee "$RUNNER_TEMP/spctl.txt" + if grep -q 'override=security disabled' "$RUNNER_TEMP/spctl.txt"; then + echo "::warning::Gatekeeper is turned off on this runner, so spctl can't check ${*: -1}" + else + grep -q 'source=Notarized Developer ID' "$RUNNER_TEMP/spctl.txt" + fi + } + mnt=$(mktemp -d) + for arch in aarch64 x86_64; do + cli="dist/hatchzip-$arch-macos/hatchzip" + dmg="dist/HatchZip-$arch.dmg" + codesign --verify --strict --verbose=2 "$cli" + info=$(codesign -dvv "$cli" 2>&1) + grep -q '^Authority=Developer ID Application: ' <<< "$info" + grep -q 'flags=0x10000(runtime)' <<< "$info" + + xcrun stapler validate "$dmg" + gatekeeper -a -t open --context context:primary-signature -vv "$dmg" + + hdiutil attach "$dmg" -nobrowse -readonly -mountpoint "$mnt" -quiet + app="$mnt/HatchZip.app" + # Gatekeeper on the app as the dmg has it, hidden extension and + # all; the strict check on a copy without the Finder info that + # flag lives in, which --strict refuses (see test-dmg.sh). + gatekeeper --assess --type execute -vv "$app" + copy="$RUNNER_TEMP/check-$arch/HatchZip.app" + mkdir -p "$(dirname "$copy")" + ditto "$app" "$copy" + xattr -d com.apple.FinderInfo "$copy" + codesign --verify --strict --deep --verbose=2 "$copy" + rm -rf "$(dirname "$copy")" + hdiutil detach "$mnt" -quiet + done + - name: open the dmg and run the app run: sh packaging/macos/test-dmg.sh dist/HatchZip-aarch64.dmg - name: checksum the dmgs @@ -392,6 +570,11 @@ jobs: dist/*.tar.gz* dist/HatchZip-*.dmg* if-no-files-found: error + - name: delete the signing keychain + if: always() && env.MACOS_KEYCHAIN != '' + run: | + security delete-keychain "$MACOS_KEYCHAIN" || true + rm -f "$RUNNER_TEMP/hatchzip-signing.p12" "$RUNNER_TEMP/hatchzip-notary.p8" # .deb, .rpm and AppImage of the desktop app, x86_64 only for now. A job of # its own because the app can't be a static musl build like the CLI: it diff --git a/packaging/README.md b/packaging/README.md index fad9b1e1..719fb86a 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -10,7 +10,7 @@ runs, so any step can be repeated by hand. | `HatchZip-x64-setup.exe` | App, CLI (`hatchzip.exe` and `hz.exe`) | [Inno Setup 6](https://jrsoftware.org/isinfo.php) | Windows | | `HatchZip-x64.msi` | The same as the setup | [WiX Toolset 5](https://wixtoolset.org) | Windows | | `HatchZip-x64-portable.zip` | The setup's files, nothing to install; the app adds the right-click menu from Settings | `7z` | Windows | -| `HatchZip-aarch64.dmg`, `HatchZip-x86_64.dmg` | `HatchZip.app`, with the CLI and man page inside | `hdiutil`, `codesign` | macOS | +| `HatchZip-aarch64.dmg`, `HatchZip-x86_64.dmg` | `HatchZip.app`, with the CLI and man page inside | `hdiutil`, `codesign`, [dmgbuild](https://dmgbuild.readthedocs.io) | macOS | | `hatchzip_amd64.deb`, `hatchzip-x86_64.rpm` | App, CLI, `hz` link, man pages, completions, menu entry, icons | [nfpm](https://nfpm.goreleaser.com) | Ubuntu 22.04 | | `HatchZip-x86_64.AppImage` | App | [linuxdeploy](https://github.com/linuxdeploy/linuxdeploy), [appimagetool](https://github.com/AppImage/appimagetool) | Ubuntu 22.04 | @@ -254,7 +254,9 @@ rather than a service the workflow calls afterwards. ```sh cargo build --release --locked --bin hatchzip-gui --target aarch64-apple-darwin -sh packaging/macos/build-dmg.sh aarch64 \ +python3 -m venv .venv +.venv/bin/pip install --no-deps --require-hashes -r packaging/macos/requirements-dmg.txt +DMGBUILD=.venv/bin/dmgbuild sh packaging/macos/build-dmg.sh aarch64 \ target/aarch64-apple-darwin/release/hatchzip-gui dist/hatchzip-aarch64-macos sh packaging/macos/test-dmg.sh dist/HatchZip-aarch64.dmg ``` @@ -264,6 +266,15 @@ architecture. `macos/Info.plist` declares zip, 7z and tar as documents HatchZip can open, so it shows up in Finder's "Open With" without replacing Archive Utility as the default. +The dmg opens as a fixed window with the app on the left, Applications on +the right and an arrow between them. [dmgbuild](https://dmgbuild.readthedocs.io) +writes that layout into the dmg's `.DS_Store` itself, without Finder or a +logged in session; `macos/dmg-settings.py` holds its settings. The window's +size and the icons' places are in `macos/dmg-background/layout.json`, which +`macos/dmg-background/make.py` also draws the background from; the 1x, 2x +and combined TIFF images it writes are committed, so the build doesn't need +Pillow. + The app is signed ad hoc, not with a Developer ID, and not notarized, so macOS asks before the first launch: @@ -282,6 +293,115 @@ sudo ln -sf /Applications/HatchZip.app/Contents/MacOS/hatchzip /usr/local/bin/hz sudo ln -sf /Applications/HatchZip.app/Contents/Resources/man/man1/hatchzip.1 /usr/local/share/man/man1/hatchzip.1 ``` +## macOS: signing and notarization + +The release workflow can sign the macOS downloads with a Developer ID +Application certificate and have Apple notarize them: + +1. `hatchzip` and `hatchzip-gui` of both architectures are signed right + after the build, with a secure timestamp and the hardened runtime + (`codesign --timestamp --options runtime`), so the smoke tests, the + tarballs and their checksums all use the signed programs. +2. `build-dmg.sh` signs the two programs inside `HatchZip.app`, then the + bundle, inside out and without `--deep`, then builds the dmg and signs + it too. The app needs no entitlements: it draws with OpenGL or the + software renderer, has no JIT, loads no unsigned libraries and sends no + Apple Events. +3. Each dmg is notarized (`xcrun notarytool submit --wait`) and the ticket + is stapled to it. The ticket covers the app and the CLI inside, and the + dmg is the outermost container, so the app itself is not stapled + separately; once copied out of the dmg, Gatekeeper finds its ticket + online. +4. The CLI in each tarball is notarized as a zip of the binary, since + notarization doesn't take a tar.gz. A bare binary can't hold a stapled + ticket, so Gatekeeper looks it up online. +5. The job checks the result: a Developer ID signature with the hardened + runtime on the CLI, `stapler validate` and `spctl` on the dmg, and + `codesign --verify --deep --strict` and `spctl` on the app inside it. + Notarization that ends in any status but Accepted fails the job, with + Apple's log printed. + +Stapling changes the dmg, so its checksum is taken afterwards, and the +publish job's build provenance covers the final files. + +Signing runs only when every secret below is set. Builds of a tag are +signed only when the repository variable `SIGN_MACOS` is `true`; with it on +and a secret missing, the job fails instead of publishing an unsigned app. +Dry runs are signed when `SIGN_DRY_RUNS` is `true`, the same variable the +Windows job reads. Otherwise the app is signed ad hoc and nothing is +notarized, as before. + +| Kind | Name | Value | +|---|---|---| +| Secret | `MACOS_CERT_P12` | The Developer ID Application certificate and its private key, as a base64 `.p12` | +| Secret | `MACOS_CERT_PASSWORD` | The `.p12` export password | +| Secret | `APPLE_API_KEY_P8` | The App Store Connect API key, the contents of `AuthKey_.p8` | +| Secret | `APPLE_API_KEY_ID` | The API key's Key ID | +| Secret | `APPLE_API_ISSUER_ID` | The API key's Issuer ID | +| Variable | `APPLE_TEAM_ID` | The 10-character Team ID, shown in the certificate's name and under Membership details on developer.apple.com | + +The certificate is imported into a keychain the job creates with a random +password and deletes when it ends, whether it passed or not. The `.p12` and +`.p8` are written to the runner's temporary folder, readable only by the +job's user, and removed after use. The identity is picked by the Team ID, +so a certificate of another team fails the job. + +To set it up, on a Mac signed in to the Apple Developer account: + +1. **The Developer ID Application certificate.** In Xcode, Settings > + Accounts, select the team, Manage Certificates, then + > Developer ID + Application. Only the Account Holder can create one. (Or, without + Xcode: create a certificate signing request in Keychain Access, + Certificate Assistant > Request a Certificate From a Certificate + Authority, saved to disk, upload it at developer.apple.com > + Certificates, Identifiers & Profiles > Certificates > + > Developer ID + Application, choose the G2 Sub-CA, and open the downloaded `.cer`.) Then + in Keychain Access, under My Certificates, select "Developer ID + Application: ()" with its private key, File > Export + Items, save it as `cert.p12` with a strong password. +2. **The App Store Connect API key.** In App Store Connect, Users and + Access > Integrations > App Store Connect API > Team Keys, generate a key + with the Developer role. Download `AuthKey_.p8`: it can be + downloaded only once. Note the Key ID next to it and the Issuer ID above + the list. +3. **The secrets and variables**, read from the files so nothing is pasted + into a terminal's history, from the folder holding the files: + + ```sh + base64 -i cert.p12 | gh secret set MACOS_CERT_P12 --repo xevrion/hatchzip + gh secret set MACOS_CERT_PASSWORD --repo xevrion/hatchzip # prompts for it + gh secret set APPLE_API_KEY_P8 --repo xevrion/hatchzip < AuthKey_XXXXXXXXXX.p8 + gh secret set APPLE_API_KEY_ID --repo xevrion/hatchzip # prompts: the Key ID + gh secret set APPLE_API_ISSUER_ID --repo xevrion/hatchzip # prompts: the Issuer ID + gh variable set APPLE_TEAM_ID --repo xevrion/hatchzip --body XXXXXXXXXX + ``` + + Then delete `cert.p12` and keep the `.p8` somewhere safe, or revoke the + key and make a new one when it's needed again. +4. **A dry run.** Turn on signed dry runs, run the release workflow on a + branch, and check the macos job: the import step prints the identity, + each notarization ends "Accepted", and "check the signatures" passes. + Download the `macos` artifact and open a dmg on a Mac: it opens without + a warning. + + ```sh + gh variable set SIGN_DRY_RUNS --repo xevrion/hatchzip --body true + gh workflow run release --repo xevrion/hatchzip --ref + ``` + + `SIGN_DRY_RUNS` also signs the Windows dry runs when SignPath or Azure is + set up, which may wait for a person to approve the request; set it back + to `false` afterwards if that's not wanted. Once the dry run passes, sign + the releases: + + ```sh + gh variable set SIGN_MACOS --repo xevrion/hatchzip --body true + ``` + +A Developer ID certificate is valid for five years. Apps signed with it +keep working after it expires, since the signature is timestamped; new +releases need a new certificate in `MACOS_CERT_P12`. + ## Package managers The manifests for the AUR, winget, Homebrew, Scoop, Chocolatey, Flathub and diff --git a/packaging/macos/build-dmg.sh b/packaging/macos/build-dmg.sh index 8fec10b2..8056aeb1 100644 --- a/packaging/macos/build-dmg.sh +++ b/packaging/macos/build-dmg.sh @@ -1,7 +1,8 @@ #!/bin/sh # Builds dist/HatchZip-.dmg: HatchZip.app next to a link to -# /Applications, to drag it onto. Runs on a Mac (hdiutil, codesign), from -# the repository root: +# /Applications, to drag it onto, in a window laid out for that. Runs on a +# Mac (hdiutil, codesign, and dmgbuild from requirements-dmg.txt, or the +# one DMGBUILD names), from the repository root: # # sh packaging/macos/build-dmg.sh aarch64 \ # target/aarch64-apple-darwin/release/hatchzip-gui \ @@ -11,9 +12,13 @@ # man page go inside the app too, so the one download has everything; the # app's README section in packaging/README.md shows how to put them on PATH. # -# Not signed with a Developer ID or notarized yet. The app is signed ad hoc, -# which Apple Silicon requires to run anything at all; Gatekeeper still asks -# the user to confirm the first launch. +# By default the app is signed ad hoc, which Apple Silicon requires to run +# anything at all; Gatekeeper still asks the user to confirm the first +# launch. With MACOS_SIGN_IDENTITY set to a Developer ID Application +# identity in the keychain search list (its name or SHA-1), the programs and +# the bundle are signed with it under the hardened runtime, and so is the +# dmg. Notarizing the dmg is left to the caller; see "macOS: signing and +# notarization" in packaging/README.md. set -eu arch="$1" @@ -42,11 +47,28 @@ sed "s/@VERSION@/$version/g" packaging/macos/Info.plist > "$app/Contents/Info.pl printf 'APPL????' > "$app/Contents/PkgInfo" plutil -lint "$app/Contents/Info.plist" -# Inside out: the helper first, then the bundle, whose signature covers it. -codesign --force --sign - "$app/Contents/MacOS/hatchzip" -codesign --force --sign - "$app" +# Inside out: the programs first, then the bundle, whose signature covers +# them. No --deep: it signs nested code with the bundle's options, which is +# not what each piece needs. No entitlements either: the app draws with +# OpenGL and has no JIT, unsigned libraries or Apple Events to send, so the +# hardened runtime's defaults fit it. +identity="${MACOS_SIGN_IDENTITY:-}" +if [ -n "$identity" ]; then + for bin in hatchzip hatchzip-gui; do + codesign --force --timestamp --options runtime --sign "$identity" "$app/Contents/MacOS/$bin" + done + codesign --force --timestamp --options runtime --sign "$identity" "$app" +else + codesign --force --sign - "$app/Contents/MacOS/hatchzip" + codesign --force --sign - "$app" +fi codesign --verify --strict --verbose=2 "$app" -ln -s /Applications "$stage/Applications" +# dmgbuild adds the Applications link, the background and the volume icon, +# and writes the window layout itself; dmg-settings.py has the details. mkdir -p dist -hdiutil create -volname HatchZip -srcfolder "$stage" -fs HFS+ -format UDZO -ov "dist/HatchZip-$arch.dmg" +"${DMGBUILD:-dmgbuild}" -s packaging/macos/dmg-settings.py -D app="$app" HatchZip "dist/HatchZip-$arch.dmg" +if [ -n "$identity" ]; then + codesign --force --timestamp --sign "$identity" "dist/HatchZip-$arch.dmg" + codesign --verify --strict --verbose=2 "dist/HatchZip-$arch.dmg" +fi diff --git a/packaging/macos/dmg-background/background.png b/packaging/macos/dmg-background/background.png new file mode 100644 index 00000000..d9a9bf39 Binary files /dev/null and b/packaging/macos/dmg-background/background.png differ diff --git a/packaging/macos/dmg-background/background.tiff b/packaging/macos/dmg-background/background.tiff new file mode 100644 index 00000000..e133a383 Binary files /dev/null and b/packaging/macos/dmg-background/background.tiff differ diff --git a/packaging/macos/dmg-background/background@2x.png b/packaging/macos/dmg-background/background@2x.png new file mode 100644 index 00000000..d448d559 Binary files /dev/null and b/packaging/macos/dmg-background/background@2x.png differ diff --git a/packaging/macos/dmg-background/layout.json b/packaging/macos/dmg-background/layout.json new file mode 100644 index 00000000..fb463812 --- /dev/null +++ b/packaging/macos/dmg-background/layout.json @@ -0,0 +1,11 @@ +{ + "width": 660, + "height": 400, + "image_height": 784, + "icon_size": 128, + "text_size": 13, + "icon_y": 190, + "hidden_y": 656, + "app_x": 170, + "applications_x": 490 +} diff --git a/packaging/macos/dmg-background/make.py b/packaging/macos/dmg-background/make.py new file mode 100644 index 00000000..6151366b --- /dev/null +++ b/packaging/macos/dmg-background/make.py @@ -0,0 +1,173 @@ +"""Draws the background of the dmg window, at 1x and 2x. + +The images are committed, so the release build doesn't need Pillow. Run +this again only to change them, on a Mac (for tiffutil), with Inter 4.1 +Regular, which is under the SIL Open Font License +(https://github.com/rsms/inter/releases/tag/v4.1): + + uv run -q --no-project --python 3.12 --with pillow \ + python packaging/macos/dmg-background/make.py path/to/Inter-Regular.ttf + +The window's size and the icons' places come from layout.json, which +packaging/macos/dmg-settings.py reads too, so the arrow stays between the +icons. Change them there and run this again. +""" + +import json +import math +import pathlib +import random +import subprocess +import sys + +from PIL import Image, ImageDraw, ImageFont + +OUT = pathlib.Path(__file__).resolve().parent +LAYOUT = json.loads((OUT / "layout.json").read_text()) +WIDTH, HEIGHT = LAYOUT["width"], LAYOUT["height"] +IMAGE_HEIGHT = LAYOUT["image_height"] +ICON_Y = LAYOUT["icon_y"] +APP_X, APPLICATIONS_X = LAYOUT["app_x"], LAYOUT["applications_x"] +ICON_SIZE = LAYOUT["icon_size"] + +TOP = (0xF5, 0xF5, 0xF7) +BOTTOM = (0xEC, 0xEC, 0xEE) +ARROW = (0xF0, 0xB4, 0x00) +TEXT = (0x6E, 0x6E, 0x6E) +MESSAGE = "Drag HatchZip to Applications to install" + +# Drawn this many times larger than the output and scaled down, which +# antialiases the arrow and the text alike. +SUPERSAMPLE = 4 + + +def wobble(seed: int): + """A smooth, small, repeatable unevenness over t in [0, 1]: a few slow + sine waves with phases from a fixed seed, so every run draws the same.""" + rng = random.Random(seed) + waves = [(f, rng.uniform(0, 2 * math.pi), a) for f, a in ((1.3, 0.6), (2.9, 0.3), (5.1, 0.12))] + return lambda t: sum(a * math.sin(2 * math.pi * f * t + p) for f, p, a in waves) + + +def bezier(p0, p1, p2, p3, t): + u = 1 - t + return tuple(u**3 * a + 3 * u * u * t * b + 3 * u * t * t * c + t**3 * d for a, b, c, d in zip(p0, p1, p2, p3)) + + +def smoothstep(e0, e1, x): + x = min(max((x - e0) / (e1 - e0), 0.0), 1.0) + return x * x * (3 - 2 * x) + + +def background(scale: int, font_path: str) -> Image.Image: + k = scale * SUPERSAMPLE + w, h = WIDTH * k, IMAGE_HEIGHT * k + + # A faint vertical gradient over the window, one row at a time, then + # its last colour down to the bottom of the image. + image = Image.new("RGB", (w, h), BOTTOM) + draw = ImageDraw.Draw(image) + for y in range(HEIGHT * k): + t = y / (HEIGHT * k - 1) + draw.line( + [(0, y), (w, y)], + fill=tuple(round(a + (b - a) * t) for a, b in zip(TOP, BOTTOM)), + ) + + def marker(points, widths): + # A marker stroke: a disc stamped every fraction of a pixel along + # the path, so the width can change smoothly along it. + for (x, y), width in zip(points, widths): + r = width * k / 2 + draw.ellipse([x * k - r, y * k - r, x * k + r, y * k + r], fill=ARROW) + + def path(p0, p1, p2, p3, length, seed, sway): + # Samples close enough at this scale that the discs overlap well. + n = max(int(length * k * 2), 2) + noise = wobble(seed) + points = [] + for i in range(n + 1): + t = i / n + x, y = bezier(p0, p1, p2, p3, t) + # The unevenness of a hand, across the stroke, gone at the ends. + dx, dy = bezier(p0, p1, p2, p3, min(t + 1e-3, 1)) + ux, uy = bezier(p0, p1, p2, p3, max(t - 1e-3, 0)) + nx, ny = uy - dy, dx - ux + norm = math.hypot(nx, ny) or 1 + off = sway * noise(t) * math.sin(math.pi * t) + points.append((x + off * nx / norm, y + off * ny / norm)) + return points + + # A designer's sketch of an arrow: one soft arc from the app towards + # Applications, rising a little in the middle, in a marker stroke that + # thickens from a thin tail, with a head of two quick strokes that + # don't quite meet. Centred between the icons and on their centres. + middle = (APP_X + APPLICATIONS_X) / 2 + half = (APPLICATIONS_X - APP_X - ICON_SIZE) / 2 * 0.58 + rise = 12 + start = (middle - half, ICON_Y + rise * 0.4) + tip = (middle + half, ICON_Y + rise * 0.15) + c1 = (middle - half * 0.45, ICON_Y - rise * 1.1) + c2 = (middle + half * 0.4, ICON_Y - rise * 1.0) + length = 2 * half * 1.05 + + shaft = path(start, c1, c2, tip, length, seed=11, sway=0.7) + thickness = wobble(23) + n = len(shaft) - 1 + + def shaft_width(t): + # Thin at the tail, full through the middle, easing off towards + # the tip so the head's strokes don't pool there. + body = 3.8 + 1.4 * smoothstep(0.0, 0.5, t) + 0.5 * thickness(t) + return body * (0.4 + 0.6 * smoothstep(0.0, 0.2, t)) * (1 - 0.3 * smoothstep(0.8, 1.0, t)) + + # The shaft stops just short of where the head meets. + stop = int(n * 0.975) + marker(shaft[:stop], [shaft_width(i / n) for i in range(stop)]) + + # The head: two short strokes flicked back from near the tip, each + # starting a little off it so they don't meet exactly, the upper one + # longer. Their angle follows the shaft's last direction, half way to + # level, as a hand would draw them. + ex, ey = shaft[-1] + px, py = shaft[-int(n * 0.05)] + heading = 0.5 * math.atan2(ey - py, ex - px) + for spread, size, (ox, oy), bow, seed in ( + (math.radians(-47), 25, (1.2, -0.6), 1.4, 31), + (math.radians(43), 21, (-0.9, 1.3), -1.1, 37), + ): + a = math.pi + heading + spread + origin = (ex + ox, ey + oy) + far = (origin[0] + size * math.cos(a), origin[1] + size * math.sin(a)) + # A slight bow, as a flick of the wrist makes. + bx, by = bow * -math.sin(a), bow * math.cos(a) + mid1 = (origin[0] + (far[0] - origin[0]) / 3 + bx, origin[1] + (far[1] - origin[1]) / 3 + by) + mid2 = (origin[0] + 2 * (far[0] - origin[0]) / 3 + bx, origin[1] + 2 * (far[1] - origin[1]) / 3 + by) + stroke = path(origin, mid1, mid2, far, size, seed=seed, sway=0.15) + m = len(stroke) - 1 + # Light where the pen lands, heavier, then lifting off. + marker(stroke, [(3.0 + 1.8 * smoothstep(0.0, 0.25, i / m)) - 2.0 * smoothstep(0.4, 1.0, i / m) for i in range(m + 1)]) + + # One line of help, well below Finder's icon labels, in the size they use. + font = ImageFont.truetype(font_path, LAYOUT["text_size"] * k) + draw.text((WIDTH / 2 * k, 336 * k), MESSAGE, font=font, fill=TEXT, anchor="mm") + + return image.resize((WIDTH * scale, IMAGE_HEIGHT * scale), Image.Resampling.LANCZOS) + + +def main() -> None: + font_path = sys.argv[1] + one = OUT / "background.png" + two = OUT / "background@2x.png" + for scale, path in ((1, one), (2, two)): + # 72 and 144 dpi, so both read as the same size in points. + background(scale, font_path).save(path, dpi=(72 * scale, 72 * scale), optimize=True) + # One TIFF with both, from which Finder picks by the screen's scale. + subprocess.run( + ["tiffutil", "-cathidpicheck", str(one), str(two), "-out", str(OUT / "background.tiff")], + check=True, + ) + + +if __name__ == "__main__": + main() diff --git a/packaging/macos/dmg-settings.py b/packaging/macos/dmg-settings.py new file mode 100644 index 00000000..18ab08cf --- /dev/null +++ b/packaging/macos/dmg-settings.py @@ -0,0 +1,71 @@ +# dmgbuild settings for HatchZip-.dmg, read by build-dmg.sh: +# +# dmgbuild -s packaging/macos/dmg-settings.py -D app=path/to/HatchZip.app \ +# HatchZip dist/HatchZip-aarch64.dmg +# +# dmgbuild writes the window's .DS_Store itself, so this needs no Finder, +# AppleScript or logged in session. The window's size and the icons' places +# come from dmg-background/layout.json, which dmg-background/make.py draws +# the background from. Paths are from the repository root, where +# build-dmg.sh runs. +# +# dmgbuild runs this file with `defines` set to the -D values. +# ruff: noqa: F821 + +import json +import subprocess + +with open("packaging/macos/dmg-background/layout.json") as f: + layout = json.load(f) + +app = defines["app"] + +format = "UDZO" +filesystem = "HFS+" + +files = [app] +symlinks = {"Applications": "/Applications"} +hide_extensions = ["HatchZip.app"] + +# The volume's icon in Finder and on the desktop. +icon = "assets/icon/hatchzip.icns" +# The 1x and 2x images in one TIFF. +background = "packaging/macos/dmg-background/background.tiff" + +# Finder counts the title bar in the window's height, so this is the +# layout's height plus the 28 point title bar of macOS 11 to 15; macOS 26's +# is 32 points, and leaves 396 to see. The image is taller than either, and +# than the window scrolled down to the hidden files, so it always reaches +# the bottom edge; Finder doesn't scroll to show the rest of a background. +window_rect = ((200, 120), (layout["width"], layout["height"] + 28)) +default_view = "icon-view" +show_toolbar = False +show_status_bar = False +show_tab_view = False +show_pathbar = False +show_sidebar = False +include_list_view_settings = False + +arrange_by = None +label_pos = "bottom" +icon_size = layout["icon_size"] +text_size = layout["text_size"] + +# Icon centres. The background and volume icon files are hidden, and also +# kept below the window, for those who have Finder show hidden files; they +# see a scrollbar, but nothing over the layout. Below and in line with the +# visible icons, since Finder scrolls the window sideways to fit an icon +# past its right edge. +hidden = [".background.tiff", ".VolumeIcon.icns"] +icon_locations = { + "HatchZip.app": (layout["app_x"], layout["icon_y"]), + "Applications": (layout["applications_x"], layout["icon_y"]), + hidden[0]: (layout["app_x"], layout["hidden_y"]), + hidden[1]: (layout["applications_x"], layout["hidden_y"]), +} + + +def create_hook(mount_point, options): + # Dot names hide them from Finder, chflags from everything else that + # lists a folder the way Finder does. + subprocess.run(["chflags", "hidden"] + [f"{mount_point}/{name}" for name in hidden], check=True) diff --git a/packaging/macos/requirements-dmg.txt b/packaging/macos/requirements-dmg.txt new file mode 100644 index 00000000..849956d1 --- /dev/null +++ b/packaging/macos/requirements-dmg.txt @@ -0,0 +1,10 @@ +# dmgbuild, which build-dmg.sh lays the dmg out with, and its dependencies, +# pinned with their hashes: +# +# python3 -m venv .venv && .venv/bin/pip install --require-hashes -r packaging/macos/requirements-dmg.txt +dmgbuild==1.6.7 \ + --hash=sha256:37ee5771c377beb3203d9164aae8046ffed8531c06edf9227f5788b3c599b1bf +ds-store==1.3.3 \ + --hash=sha256:b92a371efbf1b4ccce2a04d1ed13fceacc4736c81ba09cf5aefb74c088160a35 +mac-alias==2.2.3 \ + --hash=sha256:7362b521d2132ef92f606a37abfed5fcd849ceb2f28b6f9743e014b02af92f0d diff --git a/packaging/macos/test-dmg.sh b/packaging/macos/test-dmg.sh index ee2cc78d..6ddd3c41 100644 --- a/packaging/macos/test-dmg.sh +++ b/packaging/macos/test-dmg.sh @@ -1,7 +1,8 @@ #!/bin/sh # Opens a dmg the way a user does, copies the app out of it, and checks the # copy: signature, Info.plist, icon, and that both programs start. Only the -# dmg for this Mac's own architecture can be run. +# dmg for this Mac's own architecture can be run. Checks the dmg's layout +# too. # # sh packaging/macos/test-dmg.sh dist/HatchZip-aarch64.dmg set -eu @@ -18,10 +19,26 @@ trap cleanup EXIT hdiutil verify "$dmg" hdiutil attach "$dmg" -nobrowse -readonly -mountpoint "$mnt" -quiet [ -L "$mnt/Applications" ] || { echo "no Applications link in the dmg" >&2; exit 1; } +# The window dmg-settings.py lays out: only the app and the link to see, +# the background and volume icon there but hidden, the app's extension +# hidden, and the volume named HatchZip. +[ "$(ls "$mnt" | tr '\n' ' ')" = "Applications HatchZip.app " ] || { echo "unexpected files in the dmg: $(ls "$mnt")" >&2; exit 1; } +for f in .DS_Store .background.tiff .VolumeIcon.icns; do + [ -s "$mnt/$f" ] || { echo "no $f in the dmg" >&2; exit 1; } +done +for f in .background.tiff .VolumeIcon.icns; do + ls -lO "$mnt/$f" | grep -q ' hidden ' || { echo "$f isn't hidden in the dmg" >&2; exit 1; } +done +[ "$(GetFileInfo -aE "$mnt/HatchZip.app")" = 1 ] || { echo "HatchZip.app shows its extension in the dmg" >&2; exit 1; } +[ "$(diskutil info "$mnt" | sed -n 's/^ *Volume Name: *//p')" = HatchZip ] || { echo "the dmg's volume isn't named HatchZip" >&2; exit 1; } # ditto keeps the bundle exactly as it is, signature included. ditto "$mnt/HatchZip.app" "$dest/HatchZip.app" app="$dest/HatchZip.app" +# The hidden extension is a flag in the bundle's Finder info, outside the +# signature, which strict verification refuses as detritus. Gatekeeper +# doesn't mind it, so the strict check runs on everything else. +xattr -d com.apple.FinderInfo "$app" codesign --verify --strict --verbose=2 "$app" plutil -lint "$app/Contents/Info.plist" [ "$(defaults read "$app/Contents/Info" CFBundleExecutable)" = hatchzip-gui ]