diff --git a/.github/workflows/publish-repos.yml b/.github/workflows/publish-repos.yml new file mode 100644 index 00000000..76134b78 --- /dev/null +++ b/.github/workflows/publish-repos.yml @@ -0,0 +1,55 @@ +# Add a PUBLISHED release's .deb and .rpm to the apt and dnf repositories on +# the gh-pages branch (plan P11a step 3, D-26; GitHub Pages serves them). By +# hand only, after the release was tried and published: the release workflow +# never touches these repositories (plan P15 unit C1). Unsigned until the +# owner's release key signs the indexes (Q-4). +name: publish-repos + +on: + workflow_dispatch: + inputs: + tag: + description: "The published release's tag, e.g. v0.1.0" + required: true + +permissions: + contents: write + +jobs: + repos: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - name: Repository tools + run: sudo apt-get update && sudo apt-get install -y apt-utils createrepo-c + - name: The release's .deb and .rpm (it must be published, not a draft) + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ inputs.tag }} + run: | + draft=$(gh release view "$TAG" --json isDraft --jq .isDraft) + [ "$draft" = false ] || { echo "$TAG is a draft: publish the release first" >&2; exit 1; } + mkdir assets + gh release download "$TAG" --dir assets --pattern '*.deb' --pattern '*.rpm' + ls -l assets + - name: Add them to the apt and dnf repositories (gh-pages) + env: + TAG: ${{ inputs.tag }} + run: | + git fetch origin gh-pages || true + if git rev-parse --verify origin/gh-pages >/dev/null 2>&1; then + git worktree add repo origin/gh-pages + else + git worktree add --detach repo && git -C repo checkout --orphan gh-pages && git -C repo rm -rfq . || true + fi + mkdir -p repo/apt/pool repo/dnf + cp assets/*.deb repo/apt/pool/ + cp assets/*.rpm repo/dnf/ + deploy/packaging/repo-indexes.sh apt repo/apt + deploy/packaging/repo-indexes.sh dnf repo/dnf + cd repo || exit 1 + git config user.name "wanderbooks release" + git config user.email "release@wanderbooks.ai" + git add -A + git commit -m "wanderbooks $TAG" + git push origin HEAD:gh-pages diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0094a6b6..e807c738 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,29 +1,67 @@ -# Releases (plan P11a, D-24, D-26): on a version tag, build the Linux -# packages on the oldest system they claim (ubuntu-24.04, glibc 2.39; a -# program linked on a newer one does not start on an older one), attach -# them to the GitHub release, and add them to the apt and dnf repositories -# on the gh-pages branch (GitHub Pages serves them). Unsigned: step 5 of -# the unit (the release key, Q-4) signs the manifest and the indexes. The -# macOS job builds the .dmg UNSIGNED (no Developer ID, no notarization: -# step 5); the Windows job is unit P11c. The release holds no key today. -# To see the artifacts without a tag: Actions > release > Run workflow, -# pick the branch; each job uploads its files as a run artifact. +# The release (plan P15 unit C1; WB-pkg-7): packages for Linux, Windows and +# macOS, built from one version, tested on their own system, and attached with +# their SHA-256 sums to a DRAFT GitHub release. Nothing here publishes: the +# release stays a draft until the owner has tried the packages and presses +# Publish, and nothing here touches the apt or dnf repositories (that is +# publish-repos.yml, by hand, from a published release). +# +# Runs on a version tag (v0.1.0: the tag must equal the program's version) or +# by hand (Actions > release > Run workflow, on a branch: a draft for +# v is made, nothing is tagged). It never runs on an ordinary push: +# the tests below take hours (the same ones the portable workflows run). +# +# Unsigned by default. With the owner's secrets it signs; without them each +# signing step says so in the run's notices and the package is unsigned: +# Windows: WINDOWS_CERTIFICATE_PFX_BASE64, WINDOWS_CERTIFICATE_PASSWORD +# macOS: APPLE_CERTIFICATE_P12_BASE64, APPLE_CERTIFICATE_PASSWORD, +# APPLE_SIGNING_IDENTITY, and to notarize APPLE_ID, APPLE_TEAM_ID, +# APPLE_APP_SPECIFIC_PASSWORD +# (docs/install.md, "Signing", says how each is made.) name: release on: push: tags: ["v*"] workflow_dispatch: + inputs: + run_tests: + description: "Run each system's whole test suite before packaging (hours). Turn off only when this commit's tests already passed." + type: boolean + default: true permissions: - contents: write + contents: read + +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false + +env: + # Same disk discipline as check.yml: no incremental caches. + CARGO_INCREMENTAL: "0" jobs: + version: + name: The version (one source) + runs-on: ubuntu-24.04 + outputs: + version: ${{ steps.version.outputs.version }} + steps: + - uses: actions/checkout@v4 + - name: Read the version from crates/ledger-cli/Cargo.toml and check the tag against it + id: version + run: | + own=$(sh deploy/packaging/version.sh) + if [ "${GITHUB_REF_TYPE}" = tag ] && [ "${GITHUB_REF_NAME#v}" != "$own" ]; then + echo "the tag $GITHUB_REF_NAME is not the program's version $own (crates/ledger-cli/Cargo.toml)" >&2 + exit 1 + fi + echo "version=$own" >> "$GITHUB_OUTPUT" + linux: + name: Linux (AppImage, .deb, .rpm, pacman) + needs: version runs-on: ubuntu-24.04 - # Same disk discipline as check.yml: no incremental caches. - env: - CARGO_INCREMENTAL: "0" steps: - uses: actions/checkout@v4 - name: Room for the build (the image ships toolchains we never use) @@ -34,90 +72,257 @@ jobs: - uses: jdx/mise-action@v2 with: # Only what packaging needs, not the proof and fuzz tools. - install_args: "rust just cargo:cargo-packager cargo:cargo-generate-rpm" + install_args: "rust just cargo:cargo-packager cargo:cargo-generate-rpm cargo:cargo-about" - name: GUI build dependencies - run: sudo apt-get update && sudo apt-get install -y libxkbcommon-dev libgtk-3-dev apt-utils createrepo-c - - name: The tag is the program's version - id: version + run: sudo apt-get update && sudo apt-get install -y libxkbcommon-dev libgtk-3-dev + - name: THIRD-PARTY-NOTICES.txt is up to date with what the program links + run: scripts/notices.sh --check + - name: Tests (the workspace's whole suite on Linux) + if: ${{ github.event_name != 'workflow_dispatch' || inputs.run_tests }} + run: cargo test --workspace --no-fail-fast + - name: Build the release program and the four packages (on the oldest system they claim, glibc 2.39) + run: just package-linux ${{ needs.version.outputs.version }} + - name: Check each package holds the program, the entry, the icon and the licences run: | - own=$(sed -n 's/^version = "\(.*\)"/\1/p' crates/ledger-cli/Cargo.toml | head -n1) - tag="${GITHUB_REF_NAME#v}" - if [ "${GITHUB_REF_TYPE}" = tag ] && [ "$tag" != "$own" ]; then - echo "tag $GITHUB_REF_NAME is not version $own" >&2 - exit 1 - fi - echo "version=$own" >> "$GITHUB_OUTPUT" - - name: Build the packages - run: just package-linux ${{ steps.version.outputs.version }} - - name: Attach them to the release - if: github.ref_type == 'tag' - env: - GH_TOKEN: ${{ github.token }} - run: | - v=${{ steps.version.outputs.version }} - gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1 || gh release create "$GITHUB_REF_NAME" --title "$GITHUB_REF_NAME" --notes "wanderbooks $v" - gh release upload "$GITHUB_REF_NAME" --clobber target/packages/$v/*.AppImage target/packages/$v/*.deb target/packages/$v/*.rpm target/packages/$v/*.tar.gz - - name: Add them to the apt and dnf repositories (gh-pages) - if: github.ref_type == 'tag' - run: | - v=${{ steps.version.outputs.version }} - git fetch origin gh-pages || true - if git rev-parse --verify origin/gh-pages >/dev/null 2>&1; then - git worktree add repo origin/gh-pages + v=${{ needs.version.outputs.version }} + cd target/packages/$v || exit 1 + ls -l + for need in *.AppImage *.deb *.rpm *.tar.gz; do + test -s "$need" || { echo "no $need was built" >&2; exit 1; } + done + mkdir deb && (cd deb && ar x ../*.deb && tar -xf data.tar.* && ls -R . | head -50) + for f in usr/bin/wanderbooks usr/share/applications/wanderbooks.desktop \ + usr/share/icons/hicolor/512x512/apps/wanderbooks.png \ + usr/share/doc/wanderbooks/LICENSE-MIT usr/share/doc/wanderbooks/LICENSE-APACHE \ + usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt; do + test -e "deb/$f" || { echo "the .deb lacks $f" >&2; exit 1; } + done + rpm -qlp *.rpm > rpm.list 2>/dev/null || true + if [ -s rpm.list ]; then + for f in /usr/bin/wanderbooks /usr/share/applications/wanderbooks.desktop \ + /usr/share/doc/wanderbooks/LICENSE-MIT /usr/share/doc/wanderbooks/LICENSE-APACHE \ + /usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt; do + grep -qx "$f" rpm.list || { echo "the .rpm lacks $f" >&2; exit 1; } + done else - git worktree add --detach repo && git -C repo checkout --orphan gh-pages && git -C repo rm -rfq . || true + echo "::notice title=rpm not listed::rpm is not on this runner; the .rpm's files were not listed" fi - mkdir -p repo/apt/pool repo/dnf - cp target/packages/$v/*.deb repo/apt/pool/ - cp target/packages/$v/*.rpm repo/dnf/ - deploy/packaging/repo-indexes.sh apt repo/apt - deploy/packaging/repo-indexes.sh dnf repo/dnf - cd repo - git config user.name "wanderbooks release" - git config user.email "release@wanderbooks.ai" - git add -A - git commit -m "wanderbooks $v" - git push origin HEAD:gh-pages - - name: Keep them with the run (a dispatch has no release) + rm -rf deb rpm.list + - name: Keep the packages with the run uses: actions/upload-artifact@v4 with: name: linux-packages - path: target/packages/${{ steps.version.outputs.version }}/ + path: | + target/packages/${{ needs.version.outputs.version }}/*.AppImage + target/packages/${{ needs.version.outputs.version }}/*.deb + target/packages/${{ needs.version.outputs.version }}/*.rpm + target/packages/${{ needs.version.outputs.version }}/*.tar.gz + target/packages/${{ needs.version.outputs.version }}/PKGBUILD + if-no-files-found: error - macos: - # UNSIGNED: a .dmg that Gatekeeper refuses until step 5 signs and - # notarizes it. Apple silicon (macos-latest); an Intel build is not - # made yet. - runs-on: macos-latest + windows: + name: Windows (per-user installer) + needs: version + runs-on: windows-latest + defaults: + run: + shell: bash env: - CARGO_INCREMENTAL: "0" + WINDOWS_CERTIFICATE_PFX_BASE64: ${{ secrets.WINDOWS_CERTIFICATE_PFX_BASE64 }} + WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }} + CARGO_PROFILE_DEV_DEBUG: line-tables-only + CARGO_PROFILE_TEST_DEBUG: line-tables-only steps: - uses: actions/checkout@v4 - - uses: jdx/mise-action@v2 - with: - install_args: "rust just cargo:cargo-packager" - - name: The tag is the program's version - id: version + - name: Rust (the version mise.toml pins) + run: rustup toolchain install 1.99 --profile minimal && rustup default 1.99 + - name: Tests (the same ones the portable-windows workflow runs) + if: ${{ github.event_name != 'workflow_dispatch' || inputs.run_tests }} run: | - own=$(sed -n 's/^version = "\(.*\)"/\1/p' crates/ledger-cli/Cargo.toml | head -n1) - tag="${GITHUB_REF_NAME#v}" - if [ "${GITHUB_REF_TYPE}" = tag ] && [ "$tag" != "$own" ]; then - echo "tag $GITHUB_REF_NAME is not version $own" >&2 - exit 1 + cargo build --workspace --all-targets + cargo test --workspace --no-fail-fast + - name: Build the release program + run: cargo build --release -p ledger-cli + - name: Check the program is a Windows GUI program (no console window) and still prints in a terminal + shell: pwsh + run: | + $exe = "target\release\wanderbooks.exe" + $bytes = [IO.File]::ReadAllBytes($exe) + $pe = [BitConverter]::ToInt32($bytes, 0x3C) + $subsystem = [BitConverter]::ToUInt16($bytes, $pe + 24 + 68) + if ($subsystem -ne 2) { throw "wanderbooks.exe has Windows subsystem $subsystem, not 2 (GUI): the app would open a console window" } + Write-Host "subsystem $subsystem (GUI)" + $said = (& $exe --help 2>&1 | Out-String) + if ($said -notmatch "usage") { throw "wanderbooks.exe --help printed no usage through a pipe: $said" } + - name: Sign the program (only when the certificate secrets exist; says so when not) + shell: pwsh + run: deploy\packaging\windows\sign-windows.ps1 target\release\wanderbooks.exe + - name: NSIS (the installer's compiler; free) + shell: pwsh + run: | + if (-not (Get-Command makensis -ErrorAction SilentlyContinue) -and -not (Test-Path "${env:ProgramFiles(x86)}\NSIS\makensis.exe")) { + choco install nsis -y --no-progress + } + if (-not (Test-Path "${env:ProgramFiles(x86)}\NSIS\makensis.exe") -and -not (Get-Command makensis -ErrorAction SilentlyContinue)) { throw "NSIS did not install" } + - name: Build the installer + run: deploy/packaging/windows/build-windows.sh ${{ needs.version.outputs.version }} + - name: Sign the installer (only when the certificate secrets exist; says so when not) + shell: pwsh + run: deploy\packaging\windows\sign-windows.ps1 (Get-ChildItem target\packages\${{ needs.version.outputs.version }}\*-setup.exe) + - name: Install it silently, check what it put where, then uninstall it and check the books are still there + shell: pwsh + run: | + $v = "${{ needs.version.outputs.version }}" + $setup = (Get-ChildItem "target\packages\$v\Wanderbooks-$v-windows-x64-setup.exe").FullName + $dir = Join-Path $env:LOCALAPPDATA "Programs\Wanderbooks" + $data = Join-Path $env:LOCALAPPDATA "wanderbooks" + New-Item -ItemType Directory -Force $data | Out-Null + Set-Content (Join-Path $data "sentinel.txt") "the person's books" + $p = Start-Process $setup -ArgumentList "/S" -Wait -PassThru + if ($p.ExitCode -ne 0) { throw "the installer exited $($p.ExitCode)" } + foreach ($f in "wanderbooks.exe", "wanderbooks.ico", "LICENSE-MIT", "LICENSE-APACHE", "THIRD-PARTY-NOTICES.txt", "Uninstall Wanderbooks.exe") { + if (-not (Test-Path (Join-Path $dir $f))) { throw "the installer did not put $f in $dir" } + } + $lnk = Join-Path $env:APPDATA "Microsoft\Windows\Start Menu\Programs\Wanderbooks.lnk" + if (-not (Test-Path $lnk)) { throw "no Start Menu entry at $lnk" } + $shell = New-Object -ComObject WScript.Shell + $target = $shell.CreateShortcut($lnk).TargetPath + if ($target -ne (Join-Path $dir "wanderbooks.exe")) { throw "the Start Menu entry points at $target" } + $key = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\Wanderbooks" + $entry = Get-ItemProperty $key + if ($entry.DisplayName -ne "Wanderbooks" -or $entry.DisplayVersion -ne $v) { throw "the Settings > Apps entry is wrong: $($entry | Out-String)" } + # Installing a newer one over it keeps the same path (the bridge's). + $p = Start-Process $setup -ArgumentList "/S" -Wait -PassThru + if ($p.ExitCode -ne 0) { throw "installing over itself exited $($p.ExitCode)" } + if (-not (Test-Path (Join-Path $dir "wanderbooks.exe"))) { throw "the program is gone after installing over it" } + # Uninstall (in place, so this waits for it). + $p = Start-Process (Join-Path $dir "Uninstall Wanderbooks.exe") -ArgumentList "/S", "_?=$dir" -Wait -PassThru + if ($p.ExitCode -ne 0) { throw "the uninstaller exited $($p.ExitCode)" } + if (Test-Path (Join-Path $dir "wanderbooks.exe")) { throw "the uninstaller left the program" } + if (Test-Path $lnk) { throw "the uninstaller left the Start Menu entry" } + if (Test-Path $key) { throw "the uninstaller left its Settings > Apps entry" } + if (-not (Test-Path (Join-Path $data "sentinel.txt"))) { throw "THE UNINSTALLER REMOVED THE BOOKS' FOLDER" } + Write-Host "installed, installed over itself, uninstalled; the books' folder was left alone" + - name: Keep the installer with the run + uses: actions/upload-artifact@v4 + with: + name: windows-installer + path: target/packages/${{ needs.version.outputs.version }}/Wanderbooks-*-windows-x64-setup.exe + if-no-files-found: error + + macos: + name: macOS (universal .app in a .dmg) + needs: version + runs-on: macos-latest + env: + # A Unix socket path holds 104 bytes on macOS, and the runner's default + # temp folder is longer than the tests' homes can afford (the same + # reason as in portable-macos.yml). + TMPDIR: /tmp + CARGO_PROFILE_DEV_DEBUG: line-tables-only + CARGO_PROFILE_TEST_DEBUG: line-tables-only + APPLE_CERTIFICATE_P12_BASE64: ${{ secrets.APPLE_CERTIFICATE_P12_BASE64 }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }} + steps: + - uses: actions/checkout@v4 + - name: Rust (the version mise.toml pins), for both Macs + run: | + rustup toolchain install 1.99 --profile minimal && rustup default 1.99 + rustup target add aarch64-apple-darwin x86_64-apple-darwin + - name: Tests (the same ones the portable-macos workflow runs) + if: ${{ github.event_name != 'workflow_dispatch' || inputs.run_tests }} + run: | + cargo build --workspace --all-targets + cargo test --workspace --no-fail-fast + - name: Build the release program for Apple silicon + run: cargo build --release -p ledger-cli --target aarch64-apple-darwin + - name: Build the release program for Intel + run: cargo build --release -p ledger-cli --target x86_64-apple-darwin + - name: Put the Developer ID certificate in a temporary keychain (only when the secrets exist) + run: | + if [ -n "$APPLE_CERTIFICATE_P12_BASE64" ] && [ -n "$APPLE_CERTIFICATE_PASSWORD" ] && [ -n "$APPLE_SIGNING_IDENTITY" ]; then + deploy/packaging/macos/import-certificate.sh + else + echo "::notice title=macOS signing skipped::no APPLE_CERTIFICATE_P12_BASE64, APPLE_CERTIFICATE_PASSWORD and APPLE_SIGNING_IDENTITY secrets: the app is signed ad hoc and macOS Gatekeeper will refuse a download of it" fi - echo "version=$own" >> "$GITHUB_OUTPUT" - - name: Build the unsigned .dmg - run: just package-macos ${{ steps.version.outputs.version }} - - name: Attach it to the release - if: github.ref_type == 'tag' + - name: Build, sign, notarize (each only when its secrets exist) and staple the .dmg + env: + WB_SIGN_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }} + WB_NOTARY_APPLE_ID: ${{ secrets.APPLE_ID }} + WB_NOTARY_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + WB_NOTARY_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }} + run: deploy/packaging/macos/build-macos.sh ${{ needs.version.outputs.version }} + - name: Check the .dmg holds a universal, hardened, well-formed app (opened, not run) + run: | + v=${{ needs.version.outputs.version }} + dmg=$(ls target/packages/$v/Wanderbooks-$v-macos-universal.dmg) + mnt=$(mktemp -d /tmp/wbdmg.XXXXXX) + hdiutil attach "$dmg" -mountpoint "$mnt" -nobrowse -readonly + trap 'hdiutil detach "$mnt" -quiet || true' EXIT + app="$mnt/Wanderbooks.app" + test -d "$app" || { echo "no Wanderbooks.app in the .dmg" >&2; exit 1; } + test -L "$mnt/Applications" || { echo "no Applications shortcut in the .dmg" >&2; exit 1; } + lipo -archs "$app/Contents/MacOS/wanderbooks" + lipo -archs "$app/Contents/MacOS/wanderbooks" | grep -q arm64 + lipo -archs "$app/Contents/MacOS/wanderbooks" | grep -q x86_64 + plutil -lint "$app/Contents/Info.plist" + test "$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$app/Contents/Info.plist")" = ai.wanderbooks.app + test "$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$app/Contents/Info.plist")" = "$v" + test -f "$app/Contents/Resources/wanderbooks.icns" + for f in LICENSE-MIT LICENSE-APACHE THIRD-PARTY-NOTICES.txt; do test -f "$app/Contents/Resources/$f"; done + codesign --verify --deep --strict --verbose=2 "$app" + codesign -dv --verbose=4 "$app" 2>&1 | grep -E "flags=|Authority|Signature|TeamIdentifier" || true + - name: Keep the .dmg with the run + uses: actions/upload-artifact@v4 + with: + name: macos-dmg + path: target/packages/${{ needs.version.outputs.version }}/Wanderbooks-*-macos-universal.dmg + if-no-files-found: error + + draft-release: + name: A draft release with the packages and their SHA-256 sums + needs: [version, linux, windows, macos] + runs-on: ubuntu-24.04 + permissions: + contents: write + steps: + - uses: actions/checkout@v4 + - name: Fetch the three platforms' packages + uses: actions/download-artifact@v4 + with: + path: dist-parts + - name: Gather the files, the licences, the update note and the SHA-256 sums + run: | + v=${{ needs.version.outputs.version }} + mkdir dist + find dist-parts -type f -exec cp {} dist/ \; + cp LICENSE-MIT LICENSE-APACHE THIRD-PARTY-NOTICES.txt dist/ + # The note the app's daily look reads (crates/ledger-host/src/newer.rs): + # a version number and nothing else it uses. + printf '{"version":"%s"}\n' "$v" > dist/latest.json + (cd dist && sha256sum -- * > SHA256SUMS.txt && cat SHA256SUMS.txt) + ls -l dist + - name: Make or refresh the DRAFT release (a published release is never touched) env: GH_TOKEN: ${{ github.token }} run: | - v=${{ steps.version.outputs.version }} - gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1 || gh release create "$GITHUB_REF_NAME" --title "$GITHUB_REF_NAME" --notes "wanderbooks $v" - gh release upload "$GITHUB_REF_NAME" --clobber target/packages/$v/*.dmg - - name: Keep it with the run (a dispatch has no release) - uses: actions/upload-artifact@v4 - with: - name: macos-dmg-unsigned - path: target/packages/${{ steps.version.outputs.version }}/*.dmg + v=${{ needs.version.outputs.version }} + tag="v$v" + if gh release view "$tag" >/dev/null 2>&1; then + draft=$(gh release view "$tag" --json isDraft --jq .isDraft) + if [ "$draft" != true ]; then + echo "$tag is already published: this workflow never changes a published release" >&2 + exit 1 + fi + gh release upload "$tag" --clobber dist/* + else + gh release create "$tag" --draft --target "$GITHUB_SHA" \ + --title "Wanderbooks $v" \ + --notes "Wanderbooks $v. Unsigned builds warn on first run: see docs/install.md. Check the SHA-256 sums in SHA256SUMS.txt." \ + dist/* + fi + echo "A draft release $tag holds the packages. Try them, then publish it by hand." diff --git a/Cargo.lock b/Cargo.lock index 4508742f..7e52588d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4039,6 +4039,7 @@ dependencies = [ "time", "tokio", "tokio-rustls", + "windows-sys 0.61.2", "zeroize", "zip", ] @@ -4132,6 +4133,7 @@ dependencies = [ "tokio", "tokio-util", "zeroize", + "zip", ] [[package]] diff --git a/crates/ledger-cli/Cargo.toml b/crates/ledger-cli/Cargo.toml index a99d2b3c..a992303d 100644 --- a/crates/ledger-cli/Cargo.toml +++ b/crates/ledger-cli/Cargo.toml @@ -24,6 +24,11 @@ ledger-mcp = { path = "../ledger-mcp" } ledger-store = { path = "../ledger-store" } ledger-gui = { path = "../ledger-gui", optional = true } +# The parent's console for a command run in a terminal (console.rs): the +# raw bindings, already in the lockfile through ledger-store. +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Console"] } + [dev-dependencies] base64 = "0.22" chrono = "0.4" @@ -70,6 +75,8 @@ workspace = true # program: `just package-linux`. Paths are relative to the workspace root. [package.metadata.generate-rpm] name = "wanderbooks" +# Backups run the system's git (WB-pkg-4): dnf fetches it. +requires = { git = "*" } summary = "Double-entry bookkeeping your agent keeps and you can read" license = "MIT OR Apache-2.0" url = "https://wanderbooks.ai" @@ -77,5 +84,8 @@ assets = [ { source = "target/release/wanderbooks", dest = "/usr/bin/wanderbooks", mode = "0755" }, { source = "deploy/packaging/install-method-rpm", dest = "/usr/share/wanderbooks/install-method", mode = "0644" }, { source = "deploy/packaging/wanderbooks-static.desktop", dest = "/usr/share/applications/wanderbooks.desktop", mode = "0644" }, + { source = "deploy/packaging/icons/512x512.png", dest = "/usr/share/icons/hicolor/512x512/apps/wanderbooks.png", mode = "0644" }, + { source = "LICENSE-MIT", dest = "/usr/share/doc/wanderbooks/LICENSE-MIT", mode = "0644" }, + { source = "LICENSE-APACHE", dest = "/usr/share/doc/wanderbooks/LICENSE-APACHE", mode = "0644" }, { source = "THIRD-PARTY-NOTICES.txt", dest = "/usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt", mode = "0644" }, ] diff --git a/crates/ledger-cli/src/console.rs b/crates/ledger-cli/src/console.rs new file mode 100644 index 00000000..f7ee1d9d --- /dev/null +++ b/crates/ledger-cli/src/console.rs @@ -0,0 +1,85 @@ +//! The program's console on Windows (plan P15 unit C1, WB-pkg-2). +//! +//! The installed program is one executable that is the window, the books +//! server child and the assistants' bridge. Built for the Windows GUI +//! subsystem (`windows_subsystem = "windows"` in `main.rs`), a double-click +//! or a Start Menu entry opens no console window. The same file still has +//! to be a command line: a person who types `wanderbooks books list` in a +//! terminal needs the words printed there, and an assistant that starts +//! `wanderbooks mcp --book X` hands it pipes, which a GUI-subsystem +//! program receives as they are. +//! +//! ```text +//! GOAL: no console window when the program starts as an app; its words +//! reach the terminal that started it as a command; a pipe handed to +//! it is never replaced. +//! SOURCE: WB-pkg-2 (one executable); Microsoft's documentation of +//! AttachConsole(ATTACH_PARENT_PROCESS) and SetStdHandle. +//! INVARIANTS: +//! 1. A standard handle the parent gave (a pipe, a file) is left as it +//! is; only a missing one (null or invalid) is pointed at the +//! parent's console (CONIN$ for input, CONOUT$ for output and +//! errors). +//! 2. With no parent console (a Start Menu launch, an assistant that +//! gave pipes and has no console) nothing is attached and nothing is +//! opened: the program never makes a console window of its own. +//! SCENARIOS: +//! 1. IF an assistant starts `mcp` with three pipes: SHOULD speak over +//! them, unchanged. +//! 2. IF a terminal starts `books list`: SHOULD print into the terminal. +//! 3. IF the Start Menu starts it with no words: SHOULD open the window +//! and no console. +//! ``` +//! +//! Not run on Windows by the author (the unit was written on Linux); the +//! `release` workflow's Windows job builds it, and the first install is +//! the evidence for the scenarios. + +/// Point the missing standard handles at the parent's console, if there +/// is one (INVARIANTS 1 and 2). A no-op everywhere but Windows. +#[cfg(windows)] +pub fn attach_parent_console() { + use std::os::windows::io::IntoRawHandle; + use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + use windows_sys::Win32::System::Console::{ + ATTACH_PARENT_PROCESS, AttachConsole, GetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE, + STD_OUTPUT_HANDLE, SetStdHandle, + }; + + // SAFETY: plain Win32 calls with no pointers of ours; a failure is a + // value, and the handles opened below are given to the process, which + // keeps them open for its life. + unsafe { + let missing = |id| { + let handle = GetStdHandle(id); + handle.is_null() || handle == INVALID_HANDLE_VALUE + }; + let wanted = [ + (STD_INPUT_HANDLE, "CONIN$", true), + (STD_OUTPUT_HANDLE, "CONOUT$", false), + (STD_ERROR_HANDLE, "CONOUT$", false), + ]; + if !wanted.iter().any(|(id, _, _)| missing(*id)) { + return; + } + if AttachConsole(ATTACH_PARENT_PROCESS) == 0 { + return; + } + for (id, device, input) in wanted { + if !missing(id) { + continue; + } + let opened = std::fs::OpenOptions::new() + .read(input) + .write(!input) + .open(device); + if let Ok(file) = opened { + SetStdHandle(id, file.into_raw_handle()); + } + } + } +} + +/// Nothing to do where a program is a console program already. +#[cfg(not(windows))] +pub fn attach_parent_console() {} diff --git a/crates/ledger-cli/src/main.rs b/crates/ledger-cli/src/main.rs index 69e68251..3bc9c36b 100644 --- a/crates/ledger-cli/src/main.rs +++ b/crates/ledger-cli/src/main.rs @@ -9,6 +9,13 @@ //! From nothing to the first post: `wanderbooks setup`, `wanderbooks books //! create ID`, `wanderbooks connect claude --book ID` (then talk to the //! agent). +//! +//! On Windows the executable is built for the GUI subsystem, so starting +//! it from the Start Menu opens no console window; `console` gives a +//! command run in a terminal its words back (WB-pkg-2). +#![cfg_attr(all(windows, feature = "gui"), windows_subsystem = "windows")] + +mod console; use std::env; use std::io::Write; @@ -275,6 +282,18 @@ impl ledger_gui::owner::Owner for ViewerOwner { ) } + fn claude_desktop_extension( + &self, + book: &str, + company: &str, + ) -> Result { + let made = ledger_host::extension::claude_desktop_extension(&self.common, book, company)?; + Ok(ledger_gui::owner::ExtensionMade { + file: made.path.display().to_string(), + folder: made.folder.display().to_string(), + }) + } + fn new_books(&self, id: &str, currency: &str) -> Result { ledger_host::commands::new_books_and_home(&self.common, id, currency) } @@ -390,6 +409,15 @@ impl ledger_gui::owner::Owner for ViewerOwner { }) } + fn newer_version(&self) -> Option { + ledger_host::commands::newer_version(&self.common).map(|(version, page)| { + ledger_gui::owner::NewerVersion { + version, + page: page.to_string(), + } + }) + } + fn check_for_updates(&self) -> Result, String> { ledger_host::commands::check_for_updates(&self.common).map(|l| vec![l]) } @@ -683,8 +711,7 @@ fn is_bare_launch(words: &[String], stdin_is_terminal: bool) -> bool { } fn main() { - #[cfg(unix)] - ledger_host::update::set_program_version(env!("CARGO_PKG_VERSION")); + ledger_host::set_program_version(env!("CARGO_PKG_VERSION")); // A file's path may be any name the system takes: the file commands // get the words as given. Everything else is text. let given: Vec = env::args_os().skip(1).collect(); @@ -700,6 +727,11 @@ fn main() { eprintln!("error: an argument isn't UTF-8 text"); std::process::exit(2); }; + // A command run in a terminal prints there; the app (no words) opens + // no console at all (console.rs). + if !words.is_empty() { + console::attach_parent_console(); + } // A bare launch is the viewer. if is_bare_launch(&words, std::io::IsTerminal::is_terminal(&std::io::stdin())) { std::process::exit(run_gui(Vec::new())); diff --git a/crates/ledger-cli/tests/extension.rs b/crates/ledger-cli/tests/extension.rs new file mode 100644 index 00000000..1c0bda51 --- /dev/null +++ b/crates/ledger-cli/tests/extension.rs @@ -0,0 +1,144 @@ +//! The Claude desktop extension the Connect page writes (plan P15 unit C1, +//! WB-pkg-5): its package is Anthropic's MCP Bundle, and its manifest is +//! checked against Anthropic's published schema for manifest version 0.3 +//! (`tests/fixtures/mcpb/`, with where it came from). +//! +//! ```text +//! GOAL: a package the Claude desktop app can install, naming this +//! program's bridge for one company, with nothing secret in it. +//! SOURCE: WB-pkg-5; Anthropic's MCP Bundle manifest specification +//! (the manifest page and the version 0.3 JSON schema of its +//! mcpb repository on GitHub); the writer's own spec block in +//! the host crate. +//! INVARIANTS: +//! 1. The package is a zip whose root holds `manifest.json`; every file +//! the manifest names (`icon`, `server.entry_point`) is in the zip. +//! 2. The manifest validates against the 0.3 schema, which refuses any +//! field the specification does not define. +//! 3. The server is a `binary` whose command is the program's path and +//! whose arguments are `mcp --book `. +//! SCENARIOS: +//! 1. A package made for a company with an awkward name validates. +//! 2. Every required field of the schema is present. +//! ``` + +use serde_json::Value; +use std::io::Read; + +fn schema() -> jsonschema::Validator { + let text = include_str!("fixtures/mcpb/mcpb-manifest-v0.3.schema.json"); + jsonschema::validator_for(&serde_json::from_str::(text).unwrap()).unwrap() +} + +fn made(company: &str) -> (tempfile::TempDir, std::path::PathBuf) { + let dir = tempfile::tempdir().unwrap(); + let bridge: Vec = [ + "/Applications/Wanderbooks.app/Contents/MacOS/wanderbooks", + "mcp", + "--book", + "acme", + ] + .map(Into::into) + .to_vec(); + let made = ledger_host::extension::write_in(dir.path(), "acme", company, "0.1.0", &bridge) + .expect("the package is written"); + (dir, made.path) +} + +fn read(path: &std::path::Path) -> (Value, Vec) { + let mut zip = zip::ZipArchive::new(std::fs::File::open(path).unwrap()).unwrap(); + let names: Vec = (0..zip.len()) + .map(|i| zip.by_index(i).unwrap().name().unwrap().to_string()) + .collect(); + let mut text = String::new(); + zip.by_name("manifest.json") + .expect("manifest.json is at the root of the package") + .read_to_string(&mut text) + .unwrap(); + (serde_json::from_str(&text).unwrap(), names) +} + +#[test] +fn the_manifest_is_one_the_published_schema_accepts() { + for company in [ + "Wanderland Labs LLC", + "Quote \" and & \u{e9}\u{4e2d}", + &"long ".repeat(100), + "", + ] { + let (_dir, path) = made(company); + let (manifest, _) = read(&path); + let errors: Vec = schema() + .iter_errors(&manifest) + .map(|e| format!("{e} at {}", e.instance_path())) + .collect(); + assert!(errors.is_empty(), "{company:?}: {errors:?}\n{manifest:#}"); + // The check is not vacuous: a field the specification lacks, or a + // missing required one, is refused. + let mut extra = manifest.clone(); + extra["no_such_field"] = Value::Bool(true); + assert!(!schema().is_valid(&extra)); + let mut short = manifest.clone(); + short.as_object_mut().unwrap().remove("author"); + assert!(!schema().is_valid(&short)); + } +} + +#[test] +fn every_file_the_manifest_names_is_in_the_package() { + let (_dir, path) = made("Acme"); + let (manifest, names) = read(&path); + assert_eq!(manifest["manifest_version"], "0.3"); + for named in [ + manifest["icon"].as_str().unwrap(), + manifest["server"]["entry_point"].as_str().unwrap(), + ] { + assert!(names.iter().any(|n| n == named), "{named} in {names:?}"); + } + // The schema's required fields, by the schema's own list. + let schema: Value = + serde_json::from_str(include_str!("fixtures/mcpb/mcpb-manifest-v0.3.schema.json")).unwrap(); + for field in schema["required"].as_array().unwrap() { + assert!(manifest.get(field.as_str().unwrap()).is_some(), "{field}"); + } + for field in schema["properties"]["server"]["required"] + .as_array() + .unwrap() + { + assert!(manifest["server"].get(field.as_str().unwrap()).is_some()); + } +} + +#[test] +fn the_server_runs_this_programs_bridge_for_the_company() { + let (_dir, path) = made("Acme"); + let (manifest, _) = read(&path); + let server = &manifest["server"]; + assert_eq!(server["type"], "binary"); + assert_eq!( + server["mcp_config"]["command"], + "/Applications/Wanderbooks.app/Contents/MacOS/wanderbooks" + ); + assert_eq!( + server["mcp_config"]["args"], + serde_json::json!(["mcp", "--book", "acme"]) + ); + // The package carries no program (the one executable is the installed + // one) and no key. + let (_, names) = read(&path); + assert_eq!(names.len(), 3, "{names:?}"); + assert_eq!(manifest["name"], "wanderbooks-acme"); +} + +/// The 512 px icon is a PNG (the manifest's `icon` is "a png icon file"). +#[test] +fn the_icon_is_a_png() { + let (_dir, path) = made("Acme"); + let mut zip = zip::ZipArchive::new(std::fs::File::open(path).unwrap()).unwrap(); + let mut head = [0u8; 8]; + zip.by_name("icon.png") + .unwrap() + .read_exact(&mut head) + .unwrap(); + assert_eq!(&head, b"\x89PNG\r\n\x1a\n"); +} diff --git a/crates/ledger-cli/tests/fixtures/mcpb/SOURCE.txt b/crates/ledger-cli/tests/fixtures/mcpb/SOURCE.txt new file mode 100644 index 00000000..e87a8ce4 --- /dev/null +++ b/crates/ledger-cli/tests/fixtures/mcpb/SOURCE.txt @@ -0,0 +1,10 @@ +mcpb-manifest-v0.3.schema.json is Anthropic's published JSON Schema for the +manifest.json of an MCP Bundle (.mcpb, formerly the Desktop Extension .dxt), +manifest_version 0.3, copied verbatim on 2026-11-21 from +https://github.com/anthropics/mcpb (schemas/mcpb-manifest-v0.3.schema.json, +main branch). The specification's prose is MANIFEST.md in the same +repository; the install steps are Claude's help article "Getting started +with Local MCP servers on Claude Desktop" (support.claude.com). +The repository's licence: Apache-2.0 for new contributions, MIT for older +ones (its LICENSE file); both fit this project's MIT OR Apache-2.0. It is +a test fixture only and is not shipped. diff --git a/crates/ledger-cli/tests/fixtures/mcpb/mcpb-manifest-v0.3.schema.json b/crates/ledger-cli/tests/fixtures/mcpb/mcpb-manifest-v0.3.schema.json new file mode 100644 index 00000000..64471c54 --- /dev/null +++ b/crates/ledger-cli/tests/fixtures/mcpb/mcpb-manifest-v0.3.schema.json @@ -0,0 +1,376 @@ +{ + "type": "object", + "properties": { + "$schema": { + "type": "string" + }, + "dxt_version": { + "type": "string", + "const": "0.3", + "description": "@deprecated Use manifest_version instead" + }, + "manifest_version": { + "type": "string", + "const": "0.3" + }, + "name": { + "type": "string" + }, + "display_name": { + "type": "string" + }, + "version": { + "type": "string" + }, + "description": { + "type": "string" + }, + "long_description": { + "type": "string" + }, + "author": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "email": { + "type": "string", + "format": "email" + }, + "url": { + "type": "string", + "format": "uri" + } + }, + "required": [ + "name" + ], + "additionalProperties": false + }, + "repository": { + "type": "object", + "properties": { + "type": { + "type": "string" + }, + "url": { + "type": "string", + "format": "uri" + } + }, + "required": [ + "type", + "url" + ], + "additionalProperties": false + }, + "homepage": { + "type": "string", + "format": "uri" + }, + "documentation": { + "type": "string", + "format": "uri" + }, + "support": { + "type": "string", + "format": "uri" + }, + "icon": { + "type": "string" + }, + "icons": { + "type": "array", + "items": { + "type": "object", + "properties": { + "src": { + "type": "string" + }, + "size": { + "type": "string", + "pattern": "^\\d+x\\d+$" + }, + "theme": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "src", + "size" + ], + "additionalProperties": false + } + }, + "screenshots": { + "type": "array", + "items": { + "type": "string" + } + }, + "localization": { + "type": "object", + "properties": { + "resources": { + "type": "string", + "pattern": "\\$\\{locale\\}" + }, + "default_locale": { + "type": "string", + "pattern": "^[A-Za-z0-9]{2,8}(?:-[A-Za-z0-9]{1,8})*$" + } + }, + "required": [ + "resources", + "default_locale" + ], + "additionalProperties": false + }, + "server": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "python", + "node", + "binary" + ] + }, + "entry_point": { + "type": "string" + }, + "mcp_config": { + "type": "object", + "properties": { + "command": { + "type": "string" + }, + "args": { + "type": "array", + "items": { + "type": "string" + } + }, + "env": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "platform_overrides": { + "type": "object", + "additionalProperties": { + "type": "object", + "properties": { + "command": { + "$ref": "#/properties/server/properties/mcp_config/properties/command" + }, + "args": { + "$ref": "#/properties/server/properties/mcp_config/properties/args" + }, + "env": { + "$ref": "#/properties/server/properties/mcp_config/properties/env" + } + }, + "additionalProperties": false + } + } + }, + "required": [ + "command" + ], + "additionalProperties": false + } + }, + "required": [ + "type", + "entry_point", + "mcp_config" + ], + "additionalProperties": false + }, + "tools": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "description": { + "type": "string" + } + }, + "required": [ + "name" + ], + "additionalProperties": false + } + }, + "tools_generated": { + "type": "boolean" + }, + "prompts": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "arguments": { + "type": "array", + "items": { + "type": "string" + } + }, + "text": { + "type": "string" + } + }, + "required": [ + "name", + "text" + ], + "additionalProperties": false + } + }, + "prompts_generated": { + "type": "boolean" + }, + "keywords": { + "type": "array", + "items": { + "type": "string" + } + }, + "license": { + "type": "string" + }, + "privacy_policies": { + "type": "array", + "items": { + "type": "string", + "format": "uri" + } + }, + "compatibility": { + "type": "object", + "properties": { + "claude_desktop": { + "type": "string" + }, + "platforms": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "darwin", + "win32", + "linux" + ] + } + }, + "runtimes": { + "type": "object", + "properties": { + "python": { + "type": "string" + }, + "node": { + "type": "string" + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, + "user_config": { + "type": "object", + "additionalProperties": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "string", + "number", + "boolean", + "directory", + "file" + ] + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "required": { + "type": "boolean" + }, + "default": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ] + }, + "multiple": { + "type": "boolean" + }, + "sensitive": { + "type": "boolean" + }, + "min": { + "type": "number" + }, + "max": { + "type": "number" + } + }, + "required": [ + "type", + "title", + "description" + ], + "additionalProperties": false + } + }, + "_meta": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": {} + } + } + }, + "required": [ + "name", + "version", + "description", + "author", + "server" + ], + "additionalProperties": false, + "$schema": "http://json-schema.org/draft-07/schema#" +} \ No newline at end of file diff --git a/crates/ledger-cli/tests/packaging.rs b/crates/ledger-cli/tests/packaging.rs new file mode 100644 index 00000000..b54eaca4 --- /dev/null +++ b/crates/ledger-cli/tests/packaging.rs @@ -0,0 +1,709 @@ +//! The packages (plan P15 unit C1; WB-pkg-1 to WB-pkg-7): what can be checked +//! on Linux about the Windows installer, the macOS app, the Linux entries and +//! the one source of the version. For Windows and macOS the release workflow +//! is the real test (each packaging step fails loudly); these tests keep the +//! files it builds from true to the rules. +//! +//! ```text +//! GOAL: an installed Wanderbooks is one executable at a stable path, named +//! Wanderbooks everywhere a person sees it, with the licences beside +//! it; installing a newer one over it, or uninstalling it, never +//! touches the person's books. +//! SOURCE: WB-pkg-1 (installs like a normal program), WB-pkg-2 (one +//! executable, a stable bridge path), WB-pkg-6 (one version, one +//! name), WB-pkg-7 (the release carries the licences); D-77. +//! INVARIANTS: +//! 1. The version is written once (ledger-cli's Cargo.toml); the packaging +//! scripts read it through deploy/packaging/version.sh. +//! 2. The Windows installer is per user (no administrator), installs one +//! program, and its uninstaller names nothing but what the installer +//! put in its own folder: no recursive removal, no wildcard, no data +//! folder. +//! 3. The macOS bundle holds one program at Contents/MacOS/wanderbooks, an +//! Info.plist whose identifier, name, version and executable agree with +//! the scripts, and the licences. +//! 4. The Linux desktop entries launch plain `wanderbooks` (an AppImage's +//! launcher appends what it is given) with the icon, the name, and the +//! window's app id. +//! 5. Every package carries LICENSE-MIT, LICENSE-APACHE and +//! THIRD-PARTY-NOTICES.txt. +//! SCENARIOS: +//! 1. The bundle script run on Linux with a stand-in program makes a +//! bundle whose plist and files match the rules above. +//! ``` + +use std::path::{Path, PathBuf}; +use std::process::Command; + +fn root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../..") +} + +fn read(path: &str) -> String { + std::fs::read_to_string(root().join(path)).unwrap_or_else(|e| panic!("{path}: {e}")) +} + +/// The lines of `text` that are not comments (`;` for NSIS, `#` for shell +/// and TOML). +fn code(text: &str) -> Vec<&str> { + text.lines() + .map(str::trim) + .filter(|l| !l.is_empty() && !l.starts_with(';') && !l.starts_with('#')) + .collect() +} + +const LICENCE_FILES: [&str; 3] = ["LICENSE-MIT", "LICENSE-APACHE", "THIRD-PARTY-NOTICES.txt"]; + +// ---- the version, written once --------------------------------------------------- + +#[cfg(unix)] +#[test] +fn the_version_is_written_once_and_every_script_reads_it_from_there() { + let out = Command::new("sh") + .arg(root().join("deploy/packaging/version.sh")) + .output() + .unwrap(); + assert!(out.status.success(), "{out:?}"); + let said = String::from_utf8(out.stdout).unwrap(); + assert_eq!(said.trim(), env!("CARGO_PKG_VERSION")); + + // The Linux packager's own file carries a version the build script + // overwrites; it must not drift from the source. + let packager = read("deploy/packaging/packager.toml"); + let line = code(&packager) + .into_iter() + .find(|l| l.starts_with("version = ")) + .unwrap(); + assert_eq!(line, format!("version = \"{}\"", env!("CARGO_PKG_VERSION"))); + + // No packaging script or workflow assigns a literal version. + for file in [ + "deploy/packaging/windows/build-windows.sh", + "deploy/packaging/macos/build-macos.sh", + ".github/workflows/release.yml", + ] { + for line in code(&read(file)) { + let assigns = line.starts_with("version=") || line.starts_with("version:"); + let literal = line.split(['=', ':']).nth(1).is_some_and(|v| { + v.trim() + .trim_matches('"') + .chars() + .next() + .is_some_and(|c| c.is_ascii_digit()) + }); + assert!(!(assigns && literal), "{file}: a literal version: {line}"); + } + } + for file in [ + "deploy/packaging/windows/build-windows.sh", + "deploy/packaging/macos/build-macos.sh", + "deploy/packaging/build-linux.sh", + ] { + let text = read(file); + assert!( + text.contains("version.sh") || text.contains("ledger-cli/Cargo.toml"), + "{file} does not read the version from its one source" + ); + } +} + +#[cfg(unix)] +#[test] +fn a_version_that_is_not_three_numbers_is_refused() { + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(dir.path().join("deploy/packaging")).unwrap(); + std::fs::create_dir_all(dir.path().join("crates/ledger-cli")).unwrap(); + std::fs::copy( + root().join("deploy/packaging/version.sh"), + dir.path().join("deploy/packaging/version.sh"), + ) + .unwrap(); + for (toml, ok) in [ + ("version = \"0.2.0\"\n", true), + ("version = \"0.2.0-rc1\"\n", false), + ("version = \"two\"\n", false), + ("", false), + ] { + std::fs::write(dir.path().join("crates/ledger-cli/Cargo.toml"), toml).unwrap(); + let out = Command::new("sh") + .arg(dir.path().join("deploy/packaging/version.sh")) + .output() + .unwrap(); + assert_eq!(out.status.success(), ok, "{toml:?}: {out:?}"); + } +} + +// ---- Windows -------------------------------------------------------------------- + +#[test] +fn the_windows_installer_is_per_user_and_installs_one_program() { + let nsi = read("deploy/packaging/windows/wanderbooks.nsi"); + let lines = code(&nsi); + let has = |needle: &str| lines.iter().any(|l| l.contains(needle)); + // No administrator prompt; everything in the person's own profile. + assert!(has("RequestExecutionLevel user")); + assert!(has(r#"InstallDir "$LOCALAPPDATA\Programs\Wanderbooks""#)); + assert!( + !lines.iter().any(|l| l.contains("HKLM")), + "per-machine registry" + ); + assert!(!has("SetShellVarContext all"), "all users' Start Menu"); + // A Start Menu entry named Wanderbooks, with the icon. + assert!(has( + r#"CreateShortCut "$SMPROGRAMS\${NAME}.lnk" "$INSTDIR\wanderbooks.exe""# + )); + assert!(has(r#"!define NAME "Wanderbooks""#)); + assert!(has("wanderbooks.ico")); + // An uninstaller, listed in Settings > Apps, whose name is the product's. + assert!(has("WriteUninstaller")); + assert!(has(r#""DisplayName" "${NAME}""#)); + assert!(has("UninstallString")); + // One program: the only .exe installed besides the uninstaller. + let programs: Vec<&&str> = lines + .iter() + .filter(|l| l.starts_with("File ") && l.contains(".exe")) + .collect(); + assert_eq!(programs.len(), 1, "{programs:?}"); + assert!(programs[0].contains("/oname=wanderbooks.exe")); + // The licences travel with it. + for file in LICENCE_FILES { + assert!(has(&format!("/oname={file}")), "{file} is not installed"); + } +} + +/// WB-pkg-1: the uninstaller removes what the installer put in its own +/// folder and nothing else; the books are in the data folder, which it never +/// names. +#[test] +fn the_uninstaller_never_removes_the_books() { + let nsi = read("deploy/packaging/windows/wanderbooks.nsi"); + let lines = code(&nsi); + let start = lines + .iter() + .position(|l| l.starts_with(r#"Section "Uninstall""#)) + .expect("an uninstall section"); + let section = &lines[start..]; + let mut removals = 0; + for line in section { + let word = line.split_whitespace().next().unwrap_or(""); + if matches!(word, "Delete" | "RMDir" | "DeleteRegKey" | "DeleteRegValue") { + removals += 1; + assert!(!line.contains("/r"), "a recursive removal: {line}"); + assert!( + !line.contains('*') && !line.contains('?'), + "a wildcard: {line}" + ); + let ok = line.contains("$INSTDIR") + || line.contains("$SMPROGRAMS") + || line.contains("${UNINSTALL_KEY}") + || line.contains("${APP_KEY}"); + assert!( + ok, + "removes something that is not the program's own: {line}" + ); + } + } + assert!(removals >= 6, "the uninstaller removes the installed files"); + // The data folder, the roaming settings and the keys are named nowhere + // in the script's code (the comments say where the books are). + for line in &lines { + for data in [ + "$LOCALAPPDATA\\wanderbooks", + "$APPDATA", + "\\link", + "legacy", + "books\\", + ] { + assert!(!line.contains(data), "{data} named: {line}"); + } + } + // Only the registry keys of its own. + let keys: Vec<&&str> = lines + .iter() + .filter(|l| l.starts_with("!define") && l.contains("_KEY")) + .collect(); + assert_eq!(keys.len(), 2, "{keys:?}"); + assert!(keys[0].contains(r"Software\Microsoft\Windows\CurrentVersion\Uninstall\Wanderbooks")); + assert!(keys[1].contains(r"Software\Wanderbooks")); +} + +/// If NSIS is installed here, the script compiles with stand-in files +/// (the release workflow compiles it for real on Windows). +#[test] +fn the_installer_script_compiles_when_nsis_is_here() { + let Some(makensis) = std::env::var_os("PATH").and_then(|p| { + std::env::split_paths(&p) + .map(|d| d.join("makensis")) + .find(|f| f.is_file()) + }) else { + eprintln!( + "makensis is not installed here: the Windows job of the release workflow compiles the installer" + ); + return; + }; + let dir = tempfile::tempdir().unwrap(); + let p = dir.path(); + std::fs::write(p.join("wanderbooks.exe"), b"MZ").unwrap(); + for f in LICENCE_FILES { + std::fs::write(p.join(f), b"x").unwrap(); + } + std::fs::copy( + root().join("deploy/packaging/icons/wanderbooks.ico"), + p.join("wanderbooks.ico"), + ) + .unwrap(); + let out = Command::new(makensis) + .arg("-V2") + .arg(format!("-DVERSION={}", env!("CARGO_PKG_VERSION"))) + .arg(format!("-DPROGRAM={}", p.join("wanderbooks.exe").display())) + .arg(format!("-DICON={}", p.join("wanderbooks.ico").display())) + .arg(format!("-DLICENSES={}", p.display())) + .arg(format!("-DOUTFILE={}", p.join("setup.exe").display())) + .arg(root().join("deploy/packaging/windows/wanderbooks.nsi")) + .output() + .unwrap(); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stdout) + ); + assert!(p.join("setup.exe").metadata().unwrap().len() > 0); +} + +/// WB-pkg-2: on Windows the one executable is built for the GUI subsystem +/// (no console window for the app), and gives a terminal its words back. +#[test] +fn the_windows_program_opens_no_console_window_and_still_speaks_in_a_terminal() { + let main = read("crates/ledger-cli/src/main.rs"); + assert!( + main.contains( + r#"#![cfg_attr(all(windows, feature = "gui"), windows_subsystem = "windows")]"# + ) + ); + assert!(main.contains("console::attach_parent_console()")); + let console = read("crates/ledger-cli/src/console.rs"); + assert!(console.contains("AttachConsole(ATTACH_PARENT_PROCESS)")); + // The server child the app starts has no console window of its own. + assert!(read("crates/ledger-host/src/app_server.rs").contains("NO_WINDOW")); +} + +// ---- macOS ---------------------------------------------------------------------- + +/// The ``/value pairs of a plist's top-level dict, as text. Good enough +/// for the plain plists here (no nesting). +fn plist(text: &str) -> Vec<(String, String)> { + let mut pairs = Vec::new(); + let mut key: Option = None; + for line in text.lines().map(str::trim) { + if let Some(k) = line + .strip_prefix("") + .and_then(|l| l.strip_suffix("")) + { + assert!(key.is_none(), "a key with no value: {k}"); + key = Some(k.to_string()); + } else if let Some(k) = key.take_if(|_| line.starts_with('<') && !line.starts_with(" - - - LSMultipleInstancesProhibited - - NSSupportsAutomaticGraphicsSwitching - - - diff --git a/deploy/packaging/aur/PKGBUILD b/deploy/packaging/aur/PKGBUILD index 020b382c..77d469f9 100644 --- a/deploy/packaging/aur/PKGBUILD +++ b/deploy/packaging/aur/PKGBUILD @@ -9,7 +9,7 @@ pkgdesc="Double-entry bookkeeping your agent keeps and you can read" arch=('x86_64') url="https://wanderbooks.ai" license=('MIT' 'Apache-2.0') -depends=('gcc-libs' 'glibc') +depends=('gcc-libs' 'glibc' 'git') provides=('wanderbooks') conflicts=('wanderbooks') options=('!lto' '!strip') diff --git a/deploy/packaging/build-linux.sh b/deploy/packaging/build-linux.sh index ea84b556..88bad803 100755 --- a/deploy/packaging/build-linux.sh +++ b/deploy/packaging/build-linux.sh @@ -37,6 +37,7 @@ sed "s/^version = \".*\"/version = \"$version\"/ s#\"target/release\"#\"$PWD/$stage\"# s#\"deploy/packaging/#\"$PWD/deploy/packaging/# s#\"LICENSE-MIT\"#\"$PWD/LICENSE-MIT\"# + s#^\"LICENSE-APACHE\"#\"$PWD/LICENSE-APACHE\"# s#^\"THIRD-PARTY-NOTICES.txt\"#\"$PWD/THIRD-PARTY-NOTICES.txt\"#" \ deploy/packaging/packager.toml >"$config" # The AppImage tools are themselves AppImages; run them without FUSE. @@ -46,6 +47,9 @@ assets='assets = [ { source = "'$PWD/$stage'/wanderbooks", dest = "/usr/bin/wanderbooks", mode = "0755" }, { source = "deploy/packaging/install-method-rpm", dest = "/usr/share/wanderbooks/install-method", mode = "0644" }, { source = "deploy/packaging/wanderbooks-static.desktop", dest = "/usr/share/applications/wanderbooks.desktop", mode = "0644" }, + { source = "deploy/packaging/icons/512x512.png", dest = "/usr/share/icons/hicolor/512x512/apps/wanderbooks.png", mode = "0644" }, + { source = "LICENSE-MIT", dest = "/usr/share/doc/wanderbooks/LICENSE-MIT", mode = "0644" }, + { source = "LICENSE-APACHE", dest = "/usr/share/doc/wanderbooks/LICENSE-APACHE", mode = "0644" }, { source = "THIRD-PARTY-NOTICES.txt", dest = "/usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt", mode = "0644" }, ]' cargo generate-rpm -p crates/ledger-cli --set-metadata "version=\"$version\"" --set-metadata "$assets" -o "$out/" diff --git a/deploy/packaging/build-macos.sh b/deploy/packaging/build-macos.sh deleted file mode 100755 index f9e809f3..00000000 --- a/deploy/packaging/build-macos.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env bash -# The macOS bundle (P11a step 6), UNSIGNED, from the release program -# already built at target/release/wanderbooks (`cargo build --release -p -# ledger-cli`). Run on a Mac from the repository root: -# -# build-macos.sh [VERSION] -# -# Puts Wanderbooks_VERSION_.dmg into target/packages/VERSION/. It -# is not signed or notarized (step 5): Gatekeeper refuses it on a Mac -# that downloaded it, and the owner opens it with right-click > Open. -# Portable shell: macOS has BSD sed and no GNU mktemp options. -set -euo pipefail -own=$(sed -n 's/^version = "\(.*\)"/\1/p' crates/ledger-cli/Cargo.toml | head -n1) -version=${1:-$own} -out="target/packages/$version" -program=${WB_PROGRAM:-target/release/wanderbooks} -test -x "$program" || { echo "build the release program first: cargo build --release -p ledger-cli" >&2; exit 1; } -rm -rf "$out"; mkdir -p "$out" -stage="target/packages/.stage-$version" -rm -rf "$stage"; mkdir -p "$stage" -cp "$program" "$stage/wanderbooks" -config="$stage/packager.toml" -# cargo-packager reads paths relative to the config file, which is in the -# stage folder here, so they are made absolute. -sed -e "s/^version = \".*\"/version = \"$version\"/" \ - -e "s#^out-dir = .*#out-dir = \"$PWD/$out\"#" \ - -e "s#\"target/release\"#\"$PWD/$stage\"#" \ - -e "s#\"deploy/packaging/#\"$PWD/deploy/packaging/#" \ - -e "s#\"LICENSE-MIT\"#\"$PWD/LICENSE-MIT\"#" \ - deploy/packaging/packager-macos.toml >"$config" -cargo packager --config "$config" --formats dmg --release -rm -rf "$stage" -ls -l "$out" diff --git a/deploy/packaging/icons/wanderbooks.ico b/deploy/packaging/icons/wanderbooks.ico new file mode 100644 index 00000000..a2c72ed5 Binary files /dev/null and b/deploy/packaging/icons/wanderbooks.ico differ diff --git a/deploy/packaging/macos/Info.plist.in b/deploy/packaging/macos/Info.plist.in new file mode 100644 index 00000000..4f99388c --- /dev/null +++ b/deploy/packaging/macos/Info.plist.in @@ -0,0 +1,48 @@ + + + + + + CFBundleName + Wanderbooks + CFBundleDisplayName + Wanderbooks + CFBundleIdentifier + @BUNDLE_ID@ + CFBundleExecutable + wanderbooks + CFBundleIconFile + wanderbooks + CFBundlePackageType + APPL + CFBundleInfoDictionaryVersion + 6.0 + CFBundleShortVersionString + @VERSION@ + CFBundleVersion + @VERSION@ + LSMinimumSystemVersion + 11.0 + LSApplicationCategoryType + public.app-category.finance + NSHighResolutionCapable + + + LSMultipleInstancesProhibited + + + NSSupportsAutomaticGraphicsSwitching + + NSHumanReadableCopyright + MIT OR Apache-2.0 + + NSDocumentsFolderUsageDescription + Wanderbooks keeps a small folder in Documents for each company, where an assistant such as Claude Code works, and the extension file for the Claude app. + + diff --git a/deploy/packaging/macos/build-macos.sh b/deploy/packaging/macos/build-macos.sh new file mode 100755 index 00000000..fc7e7f0b --- /dev/null +++ b/deploy/packaging/macos/build-macos.sh @@ -0,0 +1,143 @@ +#!/usr/bin/env bash +# The macOS app and its .dmg (plan P15 unit C1; WB-pkg-1). Run on a Mac from +# the repository root (CI: the `macos` job of .github/workflows/release.yml): +# +# build-macos.sh [VERSION] +# +# Puts Wanderbooks-VERSION-macos-universal.dmg into target/packages/VERSION/. +# +# One UNIVERSAL program (Apple silicon and Intel in one file, `lipo`ed from +# the two release builds): one download for everyone. The program is +# WB_PROGRAM if set (any program file), else the lipo of +# target/aarch64-apple-darwin/release/wanderbooks and +# target/x86_64-apple-darwin/release/wanderbooks. +# +# Signing and notarization need the owner's Apple Developer identity and run +# only when it is given, in the environment (the release workflow sets these +# from secrets; nothing here is a secret and nothing prints one): +# WB_SIGN_IDENTITY the signing identity, e.g. +# "Developer ID Application: Name (TEAMID)", already in +# the keychain (import-certificate.sh does that in CI) +# WB_NOTARY_APPLE_ID, WB_NOTARY_TEAM_ID, WB_NOTARY_PASSWORD +# for `xcrun notarytool` (an app-specific password) +# Without WB_SIGN_IDENTITY the app is signed ad hoc ("-"): Apple silicon +# will not start an unsigned program at all, so it runs, but Gatekeeper +# still refuses a download of it (right-click > Open once, docs/install.md). +# Without the notarization variables the .dmg is signed but not notarized. +# +# WB_NO_ICNS=1 skips the icon (no `iconutil` off a Mac): the structure +# tests build the bundle that way on Linux; a release never does. +# WB_BUNDLE_ONLY=1 stops after the .app (the structure tests). +set -euo pipefail + +here=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd) +root=$(CDPATH='' cd -- "$here/../../.." && pwd) +cd "$root" +fail() { echo "build-macos: $*" >&2; exit 1; } +notice() { echo "::notice title=$1::$2"; echo "build-macos: $2"; } + +own=$(sh deploy/packaging/version.sh) +version=${1:-$own} +case "$version" in + [0-9]*.[0-9]*.[0-9]*) ;; + *) fail "'$version' is not an x.y.z version" ;; +esac +bundle_id=${WB_BUNDLE_ID:-ai.wanderbooks.app} +out="target/packages/$version" +stage="target/packages/.stage-macos-$version" +app="$stage/Wanderbooks.app" +dmg="Wanderbooks-$version-macos-universal.dmg" + +for f in LICENSE-MIT LICENSE-APACHE THIRD-PARTY-NOTICES.txt deploy/packaging/icons/512x512.png \ + deploy/packaging/macos/Info.plist.in deploy/packaging/macos/entitlements.plist; do + test -f "$f" || fail "$f is missing from the repository" +done + +# 1. The program: universal, or the one given. +rm -rf "${stage:?}" +mkdir -p "$stage" "$out" +program=${WB_PROGRAM:-} +if [ -z "$program" ]; then + arm=target/aarch64-apple-darwin/release/wanderbooks + intel=target/x86_64-apple-darwin/release/wanderbooks + test -f "$arm" || fail "$arm is missing: cargo build --release -p ledger-cli --target aarch64-apple-darwin" + test -f "$intel" || fail "$intel is missing: cargo build --release -p ledger-cli --target x86_64-apple-darwin" + lipo -create -output "$stage/wanderbooks-universal" "$arm" "$intel" + archs=$(lipo -archs "$stage/wanderbooks-universal") + case "$archs" in + *arm64*x86_64*|*x86_64*arm64*) ;; + *) fail "the universal program holds '$archs', not both arm64 and x86_64" ;; + esac + program="$stage/wanderbooks-universal" +fi +test -f "$program" || fail "the program is not at $program" + +# 2. The bundle. The program's path inside it, +# /Applications/Wanderbooks.app/Contents/MacOS/wanderbooks, is the one an +# assistant is registered with: it does not change when the app is +# replaced by a newer one dragged over it. +mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources" +cp "$program" "$app/Contents/MacOS/wanderbooks" +chmod 755 "$app/Contents/MacOS/wanderbooks" +sed -e "s/@VERSION@/$version/g" -e "s/@BUNDLE_ID@/$bundle_id/g" \ + deploy/packaging/macos/Info.plist.in > "$app/Contents/Info.plist" +printf 'APPL????' > "$app/Contents/PkgInfo" +cp LICENSE-MIT LICENSE-APACHE THIRD-PARTY-NOTICES.txt "$app/Contents/Resources/" +if [ "${WB_NO_ICNS:-}" = 1 ]; then + notice "no icon" "WB_NO_ICNS=1: the bundle has no icon (a test build, never a release)" +else + command -v iconutil >/dev/null || fail "iconutil is not here: build the icon on a Mac, or set WB_NO_ICNS=1 for a test bundle" + iconset="$stage/wanderbooks.iconset" + mkdir -p "$iconset" + src=deploy/packaging/icons/512x512.png + for size in 16 32 128 256 512; do + sips -z "$size" "$size" "$src" --out "$iconset/icon_${size}x${size}.png" >/dev/null + done + for size in 16 32 128 256; do + double=$((size * 2)) + sips -z "$double" "$double" "$src" --out "$iconset/icon_${size}x${size}@2x.png" >/dev/null + done + iconutil -c icns "$iconset" -o "$app/Contents/Resources/wanderbooks.icns" +fi +if [ "${WB_BUNDLE_ONLY:-}" = 1 ]; then + echo "build-macos: bundle at $app (WB_BUNDLE_ONLY=1)" + exit 0 +fi + +# 3. Sign: hardened runtime, the entitlements, a secure timestamp. +identity=${WB_SIGN_IDENTITY:-} +if [ -z "$identity" ]; then + notice "macOS signing skipped" "no WB_SIGN_IDENTITY: the app is signed ad hoc, so it runs here, but macOS Gatekeeper will refuse a download of it until it is signed with a Developer ID and notarized" + identity=- + timestamp=--timestamp=none +else + timestamp=--timestamp +fi +codesign --force --options runtime "$timestamp" \ + --entitlements deploy/packaging/macos/entitlements.plist \ + --sign "$identity" "$app" +codesign --verify --deep --strict --verbose=2 "$app" + +# 4. The .dmg: the app and a shortcut to Applications (drag to install). +mkdir -p "$stage/dmg" +cp -R "$app" "$stage/dmg/" +ln -s /Applications "$stage/dmg/Applications" +rm -f "${out:?}/${dmg:?}" +hdiutil create -volname "Wanderbooks" -srcfolder "$stage/dmg" -ov -format UDZO "$out/$dmg" +if [ "$identity" != "-" ]; then + codesign --force --timestamp --sign "$identity" "$out/$dmg" +fi + +# 5. Notarize and staple (the Developer ID signature and Apple's ticket). +if [ "$identity" != "-" ] && [ -n "${WB_NOTARY_APPLE_ID:-}" ] && [ -n "${WB_NOTARY_TEAM_ID:-}" ] && [ -n "${WB_NOTARY_PASSWORD:-}" ]; then + xcrun notarytool submit "$out/$dmg" \ + --apple-id "$WB_NOTARY_APPLE_ID" --team-id "$WB_NOTARY_TEAM_ID" \ + --password "$WB_NOTARY_PASSWORD" --wait + xcrun stapler staple "$out/$dmg" + xcrun stapler validate "$out/$dmg" + spctl --assess --type open --context context:primary-signature --verbose=2 "$out/$dmg" +else + notice "macOS notarization skipped" "no signing identity or no WB_NOTARY_APPLE_ID / WB_NOTARY_TEAM_ID / WB_NOTARY_PASSWORD: the .dmg is not notarized, and macOS will warn on the first open" +fi +rm -rf "${stage:?}" +ls -l "$out" diff --git a/deploy/packaging/macos/entitlements.plist b/deploy/packaging/macos/entitlements.plist new file mode 100644 index 00000000..30dd36ee --- /dev/null +++ b/deploy/packaging/macos/entitlements.plist @@ -0,0 +1,29 @@ + + + + + + diff --git a/deploy/packaging/macos/import-certificate.sh b/deploy/packaging/macos/import-certificate.sh new file mode 100755 index 00000000..25bcecf0 --- /dev/null +++ b/deploy/packaging/macos/import-certificate.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# Put the owner's Developer ID certificate into a temporary keychain on a CI +# macOS runner, so `codesign` can use it (plan P15 unit C1). Run by the +# release workflow only when the secrets exist. Takes the certificate (a .p12, +# base64) and its password from the environment, never the command line: +# APPLE_CERTIFICATE_P12_BASE64, APPLE_CERTIFICATE_PASSWORD +# Prints no secret. The keychain lives in RUNNER_TEMP and goes with the +# runner. +set -euo pipefail +: "${APPLE_CERTIFICATE_P12_BASE64:?the certificate secret is empty}" +: "${APPLE_CERTIFICATE_PASSWORD:?the certificate password secret is empty}" +: "${RUNNER_TEMP:?not on a GitHub runner}" +keychain="$RUNNER_TEMP/wanderbooks-signing.keychain-db" +password=$(uuidgen) +p12="$RUNNER_TEMP/wanderbooks-signing.p12" +printf '%s' "$APPLE_CERTIFICATE_P12_BASE64" | base64 --decode > "$p12" +security create-keychain -p "$password" "$keychain" +security set-keychain-settings -lut 21600 "$keychain" +security unlock-keychain -p "$password" "$keychain" +security import "$p12" -k "$keychain" -P "$APPLE_CERTIFICATE_PASSWORD" -T /usr/bin/codesign +security set-key-partition-list -S apple-tool:,apple: -s -k "$password" "$keychain" >/dev/null +security list-keychains -d user -s "$keychain" login.keychain +rm -f "$p12" +security find-identity -v -p codesigning "$keychain" diff --git a/deploy/packaging/packager-macos.toml b/deploy/packaging/packager-macos.toml deleted file mode 100644 index 64ef6c00..00000000 --- a/deploy/packaging/packager-macos.toml +++ /dev/null @@ -1,36 +0,0 @@ -# cargo-packager's description of the macOS bundle (P11a step 6; D-24, -# D-25): the .app and its .dmg, UNSIGNED. `deploy/packaging/build-macos.sh` -# runs it on a Mac (CI: the `macos` job of .github/workflows/release.yml). -# Developer ID signing and notarization are step 5 (the owner's Apple -# certificate, Q-4): they add `signing-identity` under [macos] and the -# certificate and notarization credentials as CI secrets. -# Paths are relative to this file's copy that build-macos.sh writes. -name = "wanderbooks" -product-name = "Wanderbooks" -version = "0.1.0" -identifier = "ai.wanderbooks.app" -description = "Double-entry bookkeeping your agent keeps and you can read." -homepage = "https://wanderbooks.ai" -authors = ["Stephen Waits"] -license-file = "LICENSE-MIT" -category = "Finance" -binaries-dir = "target/release" -out-dir = "target/packages" -# A png is made into the .icns (cargo-packager does it); the 512 px -# placeholder is the owner's to replace. -icons = ["deploy/packaging/icons/512x512.png"] -formats = ["dmg"] -binaries = [{ path = "wanderbooks", main = true }] - -[macos] -# The oldest macOS Rust's tier-1 aarch64-apple-darwin and x86-64 targets -# run on; eframe's wgpu/Metal path needs 10.15 at least. -minimum-system-version = "11.0" -# Keys merged into the generated Info.plist: one viewer at a time, and the -# discrete GPU is not woken for a ledger. -info-plist-path = "deploy/packaging/Info.plist" - -[dmg] -window-size = { width = 540, height = 380 } -app-position = { x = 140, y = 180 } -application-folder-position = { x = 400, y = 180 } diff --git a/deploy/packaging/packager.toml b/deploy/packaging/packager.toml index 0974f661..7a0b9791 100644 --- a/deploy/packaging/packager.toml +++ b/deploy/packaging/packager.toml @@ -24,17 +24,28 @@ section = "utils" # A deb marks itself package-managed: `wanderbooks update` refuses on it # and says to use apt (plan 3.9). desktop-template = "deploy/packaging/wanderbooks.desktop" -depends = ["libc6", "libgcc-s1"] +# git: the backups run the system's git (WB-pkg-4); the package manager +# fetches it, so a Linux person never sees the missing-git words. +depends = ["libc6", "libgcc-s1", "git"] [deb.files] "deploy/packaging/install-method-deb" = "usr/share/wanderbooks/install-method" # The notices the third-party licences ask to travel with the program # (`just notices`); `wanderbooks licenses` prints the same text. "THIRD-PARTY-NOTICES.txt" = "usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt" +"LICENSE-MIT" = "usr/share/doc/wanderbooks/LICENSE-MIT" +"LICENSE-APACHE" = "usr/share/doc/wanderbooks/LICENSE-APACHE" + +[appimage.files] +"THIRD-PARTY-NOTICES.txt" = "usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt" +"LICENSE-MIT" = "usr/share/doc/wanderbooks/LICENSE-MIT" +"LICENSE-APACHE" = "usr/share/doc/wanderbooks/LICENSE-APACHE" [pacman] -depends = ["gcc-libs", "glibc"] +depends = ["gcc-libs", "glibc", "git"] [pacman.files] "deploy/packaging/install-method-aur" = "usr/share/wanderbooks/install-method" "THIRD-PARTY-NOTICES.txt" = "usr/share/doc/wanderbooks/THIRD-PARTY-NOTICES.txt" +"LICENSE-MIT" = "usr/share/doc/wanderbooks/LICENSE-MIT" +"LICENSE-APACHE" = "usr/share/doc/wanderbooks/LICENSE-APACHE" diff --git a/deploy/packaging/version.sh b/deploy/packaging/version.sh new file mode 100755 index 00000000..99304cd3 --- /dev/null +++ b/deploy/packaging/version.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# The program's version: the one place it is written is `version = "..."` +# in crates/ledger-cli/Cargo.toml (plan P15 C1, WB-pkg-6). Every package, the +# release workflow and the installer take it from here; the program itself +# reports the same file's version through `CARGO_PKG_VERSION`. +# +# deploy/packaging/version.sh prints 0.1.0 +# +# A version that is not three plain numbers is refused: the Windows +# installer's file-version fields and the macOS bundle's both need them. +set -eu +here=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd) +version=$(sed -n 's/^version = "\(.*\)"/\1/p' "$here/../../crates/ledger-cli/Cargo.toml" | head -n1) +case "$version" in + [0-9]*.[0-9]*.[0-9]*) ;; + *) echo "version.sh: no x.y.z version in crates/ledger-cli/Cargo.toml (found: '$version')" >&2; exit 1 ;; +esac +case "$version" in + *[!0-9.]*) echo "version.sh: '$version' is not three plain numbers" >&2; exit 1 ;; +esac +printf '%s\n' "$version" diff --git a/deploy/packaging/wanderbooks-static.desktop b/deploy/packaging/wanderbooks-static.desktop index ffa4bbe2..c6a9391a 100644 --- a/deploy/packaging/wanderbooks-static.desktop +++ b/deploy/packaging/wanderbooks-static.desktop @@ -1,7 +1,9 @@ [Desktop Entry] -Categories=Office;Finance; +Type=Application +Name=Wanderbooks Comment=Double-entry bookkeeping your agent keeps and you can read. Exec=wanderbooks -Name=Wanderbooks +Icon=wanderbooks Terminal=false -Type=Application +Categories=Office;Finance; +StartupWMClass=wanderbooks diff --git a/deploy/packaging/wanderbooks.desktop b/deploy/packaging/wanderbooks.desktop index 574cd598..5e3f2a8a 100644 --- a/deploy/packaging/wanderbooks.desktop +++ b/deploy/packaging/wanderbooks.desktop @@ -8,3 +8,4 @@ Icon={{icon}} Name={{name}} Terminal=false Type=Application +StartupWMClass=wanderbooks diff --git a/deploy/packaging/windows/build-windows.sh b/deploy/packaging/windows/build-windows.sh new file mode 100755 index 00000000..68ea948f --- /dev/null +++ b/deploy/packaging/windows/build-windows.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# The Windows installer (plan P15 unit C1), from the release program already +# built at target/release/wanderbooks.exe (`cargo build --release -p +# ledger-cli`). Run from the repository root, in Git Bash on Windows (CI: +# the `windows` job of .github/workflows/release.yml) or anywhere makensis +# is: +# +# build-windows.sh [VERSION] +# +# Puts Wanderbooks-VERSION-windows-x64-setup.exe into target/packages/VERSION/. +# VERSION defaults to the program's own (deploy/packaging/version.sh). +# WB_PROGRAM names another program file; WB_MAKENSIS another makensis. +# +# Unsigned: signing is a separate, optional step (sign-windows.ps1) that +# runs when the release workflow has the certificate's secrets. +set -euo pipefail + +here=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd) +root=$(CDPATH='' cd -- "$here/../../.." && pwd) +cd "$root" +own=$(sh deploy/packaging/version.sh) +version=${1:-$own} +case "$version" in + [0-9]*.[0-9]*.[0-9]*) ;; + *) echo "build-windows: '$version' is not an x.y.z version" >&2; exit 1 ;; +esac +program=${WB_PROGRAM:-target/release/wanderbooks.exe} +out="target/packages/$version" +installer="Wanderbooks-$version-windows-x64-setup.exe" + +fail() { echo "build-windows: $*" >&2; exit 1; } +test -f "$program" || fail "the release program is not at $program: run cargo build --release -p ledger-cli first" +for f in LICENSE-MIT LICENSE-APACHE THIRD-PARTY-NOTICES.txt deploy/packaging/icons/wanderbooks.ico deploy/packaging/windows/wanderbooks.nsi; do + test -f "$f" || fail "$f is missing from the repository" +done + +makensis=${WB_MAKENSIS:-} +if [ -z "$makensis" ]; then + if command -v makensis >/dev/null 2>&1; then + makensis=makensis + elif [ -x "/c/Program Files (x86)/NSIS/makensis.exe" ]; then + makensis="/c/Program Files (x86)/NSIS/makensis.exe" + else + fail "makensis (NSIS) is not installed: choco install nsis, or apt install nsis" + fi +fi + +# NSIS is a Windows program; Git Bash must neither rewrite its options +# (-D...) nor hand it a Unix path, so paths are made native here. +export MSYS2_ARG_CONV_EXCL='*' +native() { if command -v cygpath >/dev/null 2>&1; then cygpath -w "$1"; else printf '%s\n' "$1"; fi; } + +rm -rf "${out:?}" +mkdir -p "$out" +"$makensis" -V2 \ + "-DVERSION=$version" \ + "-DPROGRAM=$(native "$program")" \ + "-DICON=$(native deploy/packaging/icons/wanderbooks.ico)" \ + "-DLICENSES=$(native "$root")" \ + "-DOUTFILE=$(native "$out/$installer")" \ + "$(native deploy/packaging/windows/wanderbooks.nsi)" +test -s "$out/$installer" || fail "makensis finished but $out/$installer is missing or empty" +ls -l "$out" diff --git a/deploy/packaging/windows/sign-windows.ps1 b/deploy/packaging/windows/sign-windows.ps1 new file mode 100644 index 00000000..6fce5ba0 --- /dev/null +++ b/deploy/packaging/windows/sign-windows.ps1 @@ -0,0 +1,36 @@ +# Sign Windows files with an Authenticode code-signing certificate (plan P15 +# unit C1). The release workflow runs this only when its secrets exist +# (WINDOWS_CERTIFICATE_PFX_BASE64 and WINDOWS_CERTIFICATE_PASSWORD); with none +# it prints a notice and the installer stays unsigned (SmartScreen warns). +# +# sign-windows.ps1 FILE [FILE...] +# +# The certificate is written to a temporary file for the signing and +# removed. Nothing here prints a secret. A failure is loud: a signature that +# was asked for and did not happen stops the release. +param([Parameter(Mandatory = $true, ValueFromRemainingArguments = $true)][string[]]$Files) +$ErrorActionPreference = 'Stop' + +if (-not $env:WINDOWS_CERTIFICATE_PFX_BASE64 -or -not $env:WINDOWS_CERTIFICATE_PASSWORD) { + Write-Host "::notice title=Windows signing skipped::no WINDOWS_CERTIFICATE_PFX_BASE64 / WINDOWS_CERTIFICATE_PASSWORD secret: the installer is unsigned and Windows SmartScreen will warn on the first run." + exit 0 +} + +$signtool = Get-ChildItem "${env:ProgramFiles(x86)}\Windows Kits\10\bin" -Recurse -Filter signtool.exe -ErrorAction SilentlyContinue | + Where-Object { $_.FullName -match '\\x64\\' } | + Sort-Object FullName -Descending | Select-Object -First 1 +if (-not $signtool) { throw "signtool.exe was not found in the Windows SDK on this runner" } + +$pfx = Join-Path $env:RUNNER_TEMP 'wanderbooks-codesign.pfx' +[IO.File]::WriteAllBytes($pfx, [Convert]::FromBase64String($env:WINDOWS_CERTIFICATE_PFX_BASE64)) +try { + foreach ($file in $Files) { + & $signtool.FullName sign /fd sha256 /f $pfx /p $env:WINDOWS_CERTIFICATE_PASSWORD /tr http://timestamp.digicert.com /td sha256 $file + if ($LASTEXITCODE -ne 0) { throw "signtool failed on $file" } + & $signtool.FullName verify /pa $file + if ($LASTEXITCODE -ne 0) { throw "the signature on $file does not verify" } + Write-Host "signed $file" + } +} finally { + Remove-Item $pfx -Force -ErrorAction SilentlyContinue +} diff --git a/deploy/packaging/windows/wanderbooks.nsi b/deploy/packaging/windows/wanderbooks.nsi new file mode 100644 index 00000000..9d332144 --- /dev/null +++ b/deploy/packaging/windows/wanderbooks.nsi @@ -0,0 +1,144 @@ +; The Wanderbooks installer for Windows (plan P15 unit C1; WB-pkg-1, WB-pkg-2, +; WB-pkg-7). Built by deploy/packaging/windows/build-windows.sh with NSIS +; (https://nsis.sourceforge.io, free software, zlib licence). +; +; makensis -DVERSION=0.1.0 -DPROGRAM=...\wanderbooks.exe -DICON=...\wanderbooks.ico ^ +; -DLICENSES= -DOUTFILE=...\Wanderbooks-0.1.0-windows-x64-setup.exe wanderbooks.nsi +; +; What it does, and the rules it keeps: +; * Per user: RequestExecutionLevel user, so double-clicking it shows no +; administrator prompt. Everything goes under the person's own profile +; and HKEY_CURRENT_USER. +; * One program file, wanderbooks.exe. It is the window, the books +; server's child and the assistants' bridge; an assistant is registered +; with this installed path, which an update keeps (the same folder, the +; same file name, replaced in place). +; * A Start Menu entry named Wanderbooks, with the icon, and an entry in +; Settings > Apps (the uninstaller). +; * The uninstaller removes the files this installer put in the install +; folder, the Start Menu entry and its two registry keys. It NEVER +; removes the person's books, keys, backups or settings: they live in +; the data folder (%LOCALAPPDATA%\wanderbooks), which this script +; names nowhere, and no command below deletes a folder's contents or +; uses a wildcard (a test, crates/ledger-cli/tests/packaging.rs, reads +; this file and fails if one appears). +; * It asks the person to quit Wanderbooks fully before it replaces or +; removes the program (a running program cannot be replaced). +; * Unsigned until the owner has a code-signing certificate: Windows +; SmartScreen says so on the first run (docs/install.md). + +Unicode true +SetCompressor /SOLID lzma +!include "MUI2.nsh" +!include "LogicLib.nsh" + +!ifndef VERSION + !error "pass -DVERSION=x.y.z (deploy/packaging/version.sh)" +!endif +!ifndef PROGRAM + !error "pass -DPROGRAM=" +!endif +!ifndef ICON + !error "pass -DICON=" +!endif +!ifndef LICENSES + !error "pass -DLICENSES=" +!endif +!ifndef OUTFILE + !error "pass -DOUTFILE=" +!endif + +!define NAME "Wanderbooks" +!define PUBLISHER "Wanderbooks" +!define UNINSTALL_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\Wanderbooks" +!define APP_KEY "Software\Wanderbooks" + +Name "${NAME}" +OutFile "${OUTFILE}" +RequestExecutionLevel user +InstallDir "$LOCALAPPDATA\Programs\Wanderbooks" +InstallDirRegKey HKCU "${APP_KEY}" "InstallDir" +BrandingText "${NAME} ${VERSION}" +ShowInstDetails nevershow +ShowUninstDetails nevershow + +VIProductVersion "${VERSION}.0" +VIAddVersionKey "ProductName" "${NAME}" +VIAddVersionKey "FileDescription" "${NAME} installer" +VIAddVersionKey "FileVersion" "${VERSION}" +VIAddVersionKey "ProductVersion" "${VERSION}" +VIAddVersionKey "LegalCopyright" "MIT OR Apache-2.0" + +!define MUI_ICON "${ICON}" +!define MUI_UNICON "${ICON}" +!define MUI_ABORTWARNING +!define MUI_FINISHPAGE_RUN "$INSTDIR\wanderbooks.exe" +!define MUI_FINISHPAGE_RUN_TEXT "Start ${NAME}" + +!insertmacro MUI_PAGE_INSTFILES +!insertmacro MUI_PAGE_FINISH +!insertmacro MUI_UNPAGE_CONFIRM +!insertmacro MUI_UNPAGE_INSTFILES +!insertmacro MUI_LANGUAGE "English" + +; A program that is running cannot be replaced or removed. Try to open the +; installed file for writing; if it is in use, ask the person to quit +; Wanderbooks (its window, which closes the books and the server) and retry. +!macro WaitUntilNotRunning + ${Do} + ClearErrors + ${If} ${FileExists} "$INSTDIR\wanderbooks.exe" + FileOpen $0 "$INSTDIR\wanderbooks.exe" a + ${IfNot} ${Errors} + FileClose $0 + ${Break} + ${EndIf} + MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "${NAME} is open. Quit it fully (close its window), then choose Retry." IDRETRY +2 + Abort "${NAME} is still open." + ${Else} + ${Break} + ${EndIf} + ${Loop} +!macroend + +Section "Install" + SetOutPath "$INSTDIR" + !insertmacro WaitUntilNotRunning + File "/oname=wanderbooks.exe" "${PROGRAM}" + File "/oname=wanderbooks.ico" "${ICON}" + File "/oname=LICENSE-MIT" "${LICENSES}\LICENSE-MIT" + File "/oname=LICENSE-APACHE" "${LICENSES}\LICENSE-APACHE" + File "/oname=THIRD-PARTY-NOTICES.txt" "${LICENSES}\THIRD-PARTY-NOTICES.txt" + WriteUninstaller "$INSTDIR\Uninstall Wanderbooks.exe" + + CreateShortCut "$SMPROGRAMS\${NAME}.lnk" "$INSTDIR\wanderbooks.exe" "" "$INSTDIR\wanderbooks.ico" 0 + + WriteRegStr HKCU "${APP_KEY}" "InstallDir" "$INSTDIR" + WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayName" "${NAME}" + WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayVersion" "${VERSION}" + WriteRegStr HKCU "${UNINSTALL_KEY}" "Publisher" "${PUBLISHER}" + WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayIcon" "$INSTDIR\wanderbooks.ico" + WriteRegStr HKCU "${UNINSTALL_KEY}" "InstallLocation" "$INSTDIR" + WriteRegStr HKCU "${UNINSTALL_KEY}" "URLInfoAbout" "https://wanderbooks.ai" + WriteRegStr HKCU "${UNINSTALL_KEY}" "UninstallString" '"$INSTDIR\Uninstall Wanderbooks.exe"' + WriteRegStr HKCU "${UNINSTALL_KEY}" "QuietUninstallString" '"$INSTDIR\Uninstall Wanderbooks.exe" /S' + WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoModify" 1 + WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoRepair" 1 +SectionEnd + +Section "Uninstall" + !insertmacro WaitUntilNotRunning + Delete "$INSTDIR\wanderbooks.exe" + Delete "$INSTDIR\wanderbooks.ico" + Delete "$INSTDIR\LICENSE-MIT" + Delete "$INSTDIR\LICENSE-APACHE" + Delete "$INSTDIR\THIRD-PARTY-NOTICES.txt" + Delete "$INSTDIR\Uninstall Wanderbooks.exe" + ; Only if empty: a folder the person put something in stays. + RMDir "$INSTDIR" + Delete "$SMPROGRAMS\${NAME}.lnk" + DeleteRegKey HKCU "${UNINSTALL_KEY}" + DeleteRegKey HKCU "${APP_KEY}" + ; The person's books, keys, backups and settings are not here: they are + ; in the data folder, which an uninstall leaves exactly as it is. +SectionEnd diff --git a/docs/install.md b/docs/install.md new file mode 100644 index 00000000..3fbf7944 --- /dev/null +++ b/docs/install.md @@ -0,0 +1,63 @@ +# Installing Wanderbooks + +For a person who wants to use it. Three short sections, one per system, then +what to do after. The release page has the files: +https://github.com/swaits/wanderbooks/releases/latest + +Wanderbooks keeps your books on your own computer. An assistant (Claude, +ChatGPT, Codex and others) can reach them **only while Wanderbooks is open**, +and only the companies you have open in its tabs. When you are finished, +close the window: that quits Wanderbooks fully and closes your books. + +## Windows + +1. Download `Wanderbooks-…-windows-x64-setup.exe` and double-click it. It asks + for no administrator password: it installs for you alone. +2. Until the installer is signed, Windows shows "Windows protected your PC". + Choose **More info**, then **Run anyway**. (Unsigned software always does + this the first time.) +3. Open **Wanderbooks** from the Start Menu. The first time, it makes your + books' folder and helps you connect your assistant. +4. To update, run the newer installer over the old one. To remove it, use + Settings, Apps, Wanderbooks. Neither touches your books. + +Where things are: the program is in `%LOCALAPPDATA%\Programs\Wanderbooks`; your +books, keys and backups are in `%LOCALAPPDATA%\wanderbooks`. +Backups need Git for Windows (https://git-scm.com/download/win, or `winget +install --id Git.Git -e`); without it Wanderbooks works and says so. + +## macOS + +1. Download `Wanderbooks-…-macos-universal.dmg` (one file for Apple silicon and + Intel), open it, and drag **Wanderbooks** onto **Applications**. +2. Open it from Applications, not from the disk image or your Downloads folder + (an assistant needs the program to stay in one place). Until the app is + notarized by Apple, the first time: right-click it, choose **Open**, then + **Open** again. +3. To update, quit Wanderbooks and drag the newer app over the old one. To + remove it, drag it to the Trash. Neither touches your books. + +Your books, keys and backups are in `~/Library/Application Support/wanderbooks`. +Backups need git: run `xcode-select --install` in Terminal (or `brew install +git`). + +## Linux + +Use the package for your system from the release page: the `.deb` (Debian, +Ubuntu), the `.rpm` (Fedora), the Arch package, or the AppImage (one file: mark +it executable, keep it where you put it, and run it). Open **Wanderbooks** from +the menu. To update, install the newer package, or replace the AppImage. Your +books are in `~/.local/share/wanderbooks` and are never touched by a package. +Backups need git (`sudo apt install git`, `sudo dnf install git`, +`sudo pacman -S git`). + +## After it is installed + +Open the **Assistants** page of a company. Pick the assistant you use: Claude +Code and Codex have a button; **Claude desktop app** has a button that makes one +extension file to open in Claude (Settings, Extensions, Advanced settings, +Install Extension); web assistants have an address and the steps. Wanderbooks +tells you in the window when a newer version is out. + +`wanderbooks serve` (a server with no window, for another computer) is for +people who run it themselves: see `deploy/README.md`. diff --git a/docs/packaging.md b/docs/packaging.md index 5d221ade..3cfb437c 100644 --- a/docs/packaging.md +++ b/docs/packaging.md @@ -16,8 +16,8 @@ not a tool, so there is nothing for a recipe to call. | `.rpm` | `cargo-generate-rpm` (table in `crates/ledger-cli/Cargo.toml`) | same paths, marker `rpm`; 36 MB | dnf repository (`repo-indexes.sh dnf`) | unsigned until step 5 (`--signing-key` takes the PGP key then) | | AUR `PKGBUILD` | `cargo packager` makes the tarball (`pacman` format) and a PKGBUILD for it; ours is `deploy/packaging/aur/PKGBUILD`, which repacks the release's tarball (package `wanderbooks-bin`) | same paths, marker `aur`; built with `makepkg` | pacman (the AUR keeps old PKGBUILDs) | n/a (pacman trusts the AUR's checksums) | | AppImage | `cargo packager` (`appimage`); 44 MB | one file the owner puts anywhere and runs; needs no admin password | `wanderbooks update` (`$APPIMAGE` is the file replaced) against the manifest; minisign | minisign by the release key (step 5) | -| `.dmg` | `cargo packager` (`dmg`), `deploy/packaging/build-macos.sh`; **built in CI, unsigned; the trial on a Mac is the owner's** | `Wanderbooks.app` dragged to Applications; no admin password (the trial will say) | `wanderbooks update` (it replaces the program inside the `.app`: see the note below) | **unsigned**; Developer ID and notarization are step 5 | -| NSIS `.exe` | `cargo packager` (`nsis`) | **not built**: native Windows is unit P11c (D-62) | `wanderbooks update` | the Windows identity (step 5) | +| `.dmg` | `deploy/packaging/macos/build-macos.sh` (P15 C1; it replaced the cargo-packager `dmg` config, unrun) | `Wanderbooks.app` dragged to Applications; one universal program at `Contents/MacOS/wanderbooks`; no admin password | the newer app dragged over the old (the program tells the person one exists) | hardened runtime; Developer ID and notarization when the owner's secrets are in the release workflow, else ad hoc | +| Windows `.exe` | `deploy/packaging/windows/build-windows.sh` with NSIS (P15 C1; not cargo-packager's `nsis`) | `%LOCALAPPDATA%\Programs\Wanderbooks\wanderbooks.exe`, Start Menu entry, Settings > Apps uninstaller; per user, no admin | the newer installer run over the old one (the program tells the person one exists) | Authenticode when the owner's certificate secrets are in the release workflow, else unsigned | `just package-linux` builds the first four (`deploy/packaging/build-linux.sh`, about a minute after the release build, itself 8 to 12 minutes on a @@ -130,7 +130,7 @@ package manager. Not tested: Ubuntu, openSUSE, a package-manager *downgrade* (the repositories keep every release by construction), and the `.rpm` and `.deb` under their real signatures (step 5). -## The macOS bundle (step 6, built in CI, unsigned) +## The macOS bundle (step 6; REPLACED by P15 unit C1, see "P15 unit C1" below) `deploy/packaging/packager-macos.toml` (cargo-packager: the `dmg` format, which makes the `.app` first; the icon is the 512 px PNG, made into an @@ -260,3 +260,90 @@ not a `cfg` gap. Today Unix-only, found by grep (2026-10-29): file with read, write and delete sharing, so a rename never meets an open handle of ours. - The `portable` job runs Windows as a gate (`experimental: false`), since the port landed (P11c). + + +## P15 unit C1: the installed app on the new shape (2026-11-21) + +Written on Linux. **Nothing here has been run on Windows or macOS**: the +`release` workflow's first run on GitHub is the evidence, and it is built to +fail loudly at each step. What Linux checked: `crates/ledger-cli/tests/packaging.rs` +reads the installer script, the plist, the entitlements, the desktop entries and +the workflow; builds the macOS bundle with a stand-in program; compiles the +installer with `makensis` when it is installed; and a real `.deb` and `.rpm` +were built with a stand-in program and their file lists read (program, desktop +entry, icon, licences). + +| | Windows | macOS | Linux | +|---|---|---|---| +| Package | NSIS installer, per user | `.app` in a `.dmg`, one universal program | `.deb`, `.rpm`, pacman tarball, AppImage (unchanged tools) | +| Program path (the bridge's) | `%LOCALAPPDATA%\Programs\Wanderbooks\wanderbooks.exe` | `/Applications/Wanderbooks.app/Contents/MacOS/wanderbooks` | `/usr/bin/wanderbooks`; the AppImage's own file | +| Books | `%LOCALAPPDATA%\wanderbooks` | `~/Library/Application Support/wanderbooks` | `~/.local/share/wanderbooks` (unchanged) | +| Removal leaves the books | the uninstaller names no data folder | dragging to Trash runs nothing | no package script runs | +| No console window | built for the GUI subsystem; attaches to a terminal for commands | n/a | n/a | +| Without git | says how to get Git for Windows | says `xcode-select --install`; the system's stub is not taken for git | says the package manager's command | + +**Why NSIS written by hand, not cargo-packager's.** The installer's rules +(per user, one program, an uninstaller that can never reach the books) are +short and exact; a script of our own states them in a file a test can read, and +needs only `makensis` (free, zlib-licensed, `choco install nsis`). cargo-packager's +NSIS template downloads helper plugins at build time and ships an uninstaller +option that removes application data. **Why the macOS bundle is assembled by a +script:** signing order (inside out, hardened runtime, then the disk image, then +notarization) and the entitlements are exact, and the secrets contract is ours. +cargo-packager stays for Linux. + +**Updating** is installing the newer package over the old one; the program says +when one exists (`ledger_host::newer`: a version number from `latest.json`, +once a day, a fixed download address) and never installs anything. The earlier +staged self-update (`update`, `update.lock`, the daily staged download) still +exists for an AppImage or a program put somewhere by hand and needs a release +key that does not exist yet; on the desktop the detached host it restarted +through is gone (P15 A5). A macOS `.app` is never updated one file at a time. + +**Signing.** Windows (secrets `WINDOWS_CERTIFICATE_PFX_BASE64`, +`WINDOWS_CERTIFICATE_PASSWORD`): `sign-windows.ps1` signs the program, then the +installer. macOS (`APPLE_CERTIFICATE_P12_BASE64`, `APPLE_CERTIFICATE_PASSWORD`, +`APPLE_SIGNING_IDENTITY`; to notarize `APPLE_ID`, `APPLE_TEAM_ID`, +`APPLE_APP_SPECIFIC_PASSWORD`): `import-certificate.sh` puts the certificate in +a temporary keychain, `build-macos.sh` signs with the hardened runtime, +notarizes and staples. With none, each step prints a notice and the package is +unsigned (macOS: ad hoc, so it runs, but Gatekeeper refuses a download). + +**The Claude desktop extension** (`ledger_host::extension`): an MCP Bundle +(`.mcpb`, the renamed `.dxt`; manifest version 0.3), one per company, made by the +Connect page's button; it runs the installed program as `mcp --book `. + +**Left out, on purpose:** an auto-installer; a Windows executable icon resource +(the shortcut and the uninstaller entry carry the icon, and the running window +sets its own from the 512 px PNG; Explorer shows the `.exe` with the default +icon); +`wanderbooks.cmd`/PATH setup so a terminal waits for a command on Windows (a +GUI-subsystem program returns the prompt at once); a macOS refusal for a program +run from a mounted disk image (a path under `/Volumes` may be a real install on +another disk); bundling git on Windows and macOS (the owner's decision, below); the signed `manifest.json` of the earlier self-update +(needs the release key, Q-4). + +### Bundling git (an owner decision, not made here) + +Backups run the system's git. **Linux:** the packages now depend on git, so the +package manager fetches it (nothing is bundled). **Windows and macOS:** the app +detects a missing git and says how to get it (WB-pkg-4); nothing is bundled. + +What bundling would mean. Git is GPL-2.0-only free software. Shipping an +unmodified git as a separate file that our program starts as its own process +(never linked) is what the GPL calls aggregation: our MIT OR Apache-2.0 code is +unaffected, and AGENTS.md's clean-room rule (never copy GnuCash's code) is not +touched, since nothing of git is copied into ours; `deny.toml` governs Rust +crates only and does not see it. It still requires, for each release that +carries git: git's GPL text and copyright notices beside it (Git for Windows' +MinGit adds the notices of the components it carries: OpenSSL/curl, the MSYS2 +runtime); the corresponding source of exactly that git, or a written offer for it +valid three years (GPLv2 section 3), most simply the git version's source +archive attached to the same release; no term of ours that forbids the +recipient what the GPL permits; and a note of any change if git were modified. +`THIRD-PARTY-NOTICES.txt` (cargo-about) covers Rust crates only, so it would +need an addition. On Windows the candidate is MinGit from Git for Windows +(about 40 MB, unpacked beside the program; `Git::find` would look there first); +on macOS Apple's command line tools' git is Apple's and cannot be bundled, so +it would be a build of our own (Homebrew's, or from source), universal, signed +inside the app, with the same obligations. diff --git a/docs/spec/claims/packaging.md b/docs/spec/claims/packaging.md new file mode 100644 index 00000000..d6fd5c05 --- /dev/null +++ b/docs/spec/claims/packaging.md @@ -0,0 +1,175 @@ +# Claims: packaging + +Wanderbooks' own product rules for how the program is installed, named, +updated and removed on Windows, macOS and Linux (plan P15 unit C1, +`plan/p15-app-and-relay.md`). No authority outside this product states them. +They are `WB-pkg-`. + +Rules: none from bookspec's list; these are product rules only. + +--- + +### Product rules + +**WB-pkg-1 It installs like a normal program, and taking it away never takes +the books.** A person downloads one file and opens it. On Windows that is an +installer that asks for no administrator password, installs under their own +profile, adds a Start Menu entry named Wanderbooks with the icon, and lists +an uninstaller in Settings. On macOS it is a disk image holding the app and a +shortcut to Applications to drag it onto. On Linux it is the package manager's +package, or one AppImage file. The Windows uninstaller removes exactly the +files the installer put in its own folder, the Start Menu entry and two +registry keys of its own: it uses no recursive removal and no wildcard and +names the data folder nowhere, and it asks the person to quit the app first +rather than fail on a program that is running. Moving the macOS app to the +Trash, or removing a Linux package, never runs a script. Each leaves the +person's books, keys, backups and settings where they are (WB-pkg-8). +*Enforced:* `deploy/packaging/windows/wanderbooks.nsi`, +`deploy/packaging/macos/build-macos.sh`, `deploy/packaging/packager.toml`. +*Checked:* `ledger-cli` `tests/packaging.rs` +(`the_windows_installer_is_per_user_and_installs_one_program`, +`the_uninstaller_never_removes_the_books`, +`no_package_runs_a_script_that_could_touch_the_books`, +`the_installer_script_compiles_when_nsis_is_here`, +`the_macos_bundle_has_one_program_and_a_plist_that_agrees_with_the_scripts`); +the release workflow's Windows job installs the installer, installs it over +itself and uninstalls it with a marker in the data folder that must survive. + +**WB-pkg-2 One executable is the window, the books server and the +assistants' bridge, and the path an assistant is given does not change.** The +installed program is one file, `wanderbooks`, started three ways: with +nothing to say, as the window; by the window with `server`, as its child; and +by an assistant with `mcp --book`, as the bridge. No second program is +installed. The path an assistant is registered with is the installed file's own: +`%LOCALAPPDATA%\Programs\Wanderbooks\wanderbooks.exe` on Windows, which the +installer replaces in place; `/Applications/Wanderbooks.app/Contents/MacOS/wanderbooks` +on macOS, which dragging a newer app over the old one replaces; `/usr/bin/wanderbooks` +for a Linux package, replaced by the package manager; and the AppImage's own +file, which the person keeps where they put it. On macOS a program running from +the temporary copy the system makes of a quarantined download still refuses to +register an assistant, in words, since that path goes away. On Windows the file +is built for the GUI subsystem, so starting it from the Start Menu opens no +console window; run from a terminal it attaches to that terminal so a +command's words appear there, and it never replaces a pipe an assistant gave +it. The two console programs the window starts (the assistant's own list and +the system's opener) are started without a console window. +*Enforced:* `ledger_host::start::translocation_refusal`, +`ledger_host::start::this_executable`, `crates/ledger-cli/src/console.rs` (the Windows +console), `ledger_host::app_server` (the server child). +*Checked:* `ledger-cli` `tests/one_executable.rs` +(`each_mode_names_itself_in_its_usage`), `tests/translocation.rs` +(`translocated_app_refuses_to_connect`), +`tests/packaging.rs` (`the_windows_program_opens_no_console_window_and_still_speaks_in_a_terminal`, +`the_macos_bundle_has_one_program_and_a_plist_that_agrees_with_the_scripts`); +the release workflow's Windows job checks the built file's subsystem is the GUI one +and that it still prints through a pipe. + +**WB-pkg-3 An update is the newer package installed over the old one, and the +app says when one exists.** The program installs nothing by itself. Once a day +at most, on a thread of its own, it reads one small public file a release +publishes and takes the version number from it and nothing else: where to get +the update is an address fixed in the program, never one the file names. A +higher version shows a notice in the window with a button to the download page, +and says the books, keys and connections stay as they are, because they live in +the data folder and the bridge's path is the same (WB-pkg-2). "Check for +updates" looks at once. The look sends no version, company or identifier and +a failed look is silent. A macOS app is never updated one file at a time +(that would break its signature): the program treats it as managed and says to +drag the newer app over the old one. Where the program may replace itself with +a release signed by our key (an AppImage, a program put somewhere by hand), the +earlier staged update still works; no release key exists yet, so today none does. +*Enforced:* `ledger_host::newer`, `ledger_host::update::install_kind`, +`ledger_host::commands::check_for_updates`, `ledger_gui::owner::NewerVersion`. +*Checked:* `ledger-host` unit tests in `newer.rs` +(`only_a_higher_plain_version_is_newer`, +`the_feed_gives_a_version_and_nothing_else`, +`a_look_is_noted_and_the_next_is_a_day_away`, +`a_failed_look_says_nothing_and_still_counts`, `the_note_is_private`) and +`update.rs` (`a_macos_app_is_never_updated_in_place`); `ledger-gui` +`tests/update_notice.rs` (`a_newer_version_is_told_with_where_to_get_it`). + +**WB-pkg-4 Without git, backups are off and the person is told how to get +it.** Backups run the system's git; the program carries none. With no git found, a +backup says so in plain words for the system it runs on (Git for Windows or winget; Apple's +command line tools or Homebrew; the package manager) and the books work as +ever; the next backup looks again, so installing git needs no restart. On a Mac +without the developer tools, the stub at the system's git path is not taken for a +git. Whether to ship a git with the app is the owner's decision, since git is +GPL-2.0-only free software and shipping it carries a source offer and notices. +*Enforced:* `ledger_store::backup::how_to_get_git`, +`ledger_store::backup::Git::find`. +*Checked:* `ledger-store` unit tests in `backup.rs` +(`a_missing_git_says_how_to_get_it`, +`the_mac_stub_is_not_a_git_until_the_developer_tools_are_there`); +`ledger-cli` `tests/packaging.rs` +(`the_linux_packages_depend_on_git_and_none_carries_one`). + +**WB-pkg-5 The Connect page can write a one-click Claude desktop extension +for a company.** The "Claude desktop app" row has one button. It makes the +company's assistant key if there is none and writes +`wanderbooks-.mcpb` in a folder named Extensions in Documents/Wanderbooks: an +MCP Bundle (Anthropic's extension format, a zip file with a manifest, manifest +version 0.3) whose server is a binary that runs this program's installed path +as `mcp --book ` (WB-pkg-2). The package carries no program, no key, no +passphrase and no path of the data root. The page then says in words where in Claude's +settings to pick the file (Settings, Extensions, Advanced settings, Install +Extension), to keep Wanderbooks open, and offers to show the file. A program +running from a translocated copy writes nothing and says to move it first. +*Enforced:* `ledger_host::extension::claude_desktop_extension`, +`ledger_host::extension::manifest`. +*Checked:* `ledger-cli` `tests/extension.rs` +(`the_manifest_is_one_the_published_schema_accepts`, +`every_file_the_manifest_names_is_in_the_package`, +`the_server_runs_this_programs_bridge_for_the_company`); `ledger-host` unit +tests in `extension.rs` +(`no_secret_and_no_data_root_is_in_the_package`); `ledger-gui` +`tests/assistants.rs` +(`the_claude_desktop_row_makes_the_extension_and_says_what_to_do_next`). + +**WB-pkg-6 One version, and the product is named Wanderbooks wherever a +person sees it.** The version is written once, in the program's own manifest +(`crates/ledger-cli/Cargo.toml`); every package script and the release workflow read it +through `deploy/packaging/version.sh`, which refuses anything that is not three +numbers, and the program reports it to the window, the update look and the +extension. The window's title, the Start Menu entry, the app bundle's name, +the uninstaller's entry and the installer are all "Wanderbooks". The +lower-case `wanderbooks` stays where it is an identifier a person does not +read: the program's file name, the window's app id, the data folder. +*Enforced:* `deploy/packaging/version.sh`, `ledger_host::program_version`. +*Checked:* `ledger-cli` `tests/packaging.rs` +(`the_version_is_written_once_and_every_script_reads_it_from_there`, +`a_version_that_is_not_three_numbers_is_refused`, +`the_desktop_entries_launch_plain_wanderbooks_with_the_icon_and_the_window_id`); +`ledger-gui` `tests/tabs.rs` (the window title tests). + +**WB-pkg-7 A release is a draft that carries the licences and the sums.** +The release workflow runs on a version tag or by hand and never on an +ordinary push. It builds all three packages, runs each system's tests on that +system, and attaches the packages, the licence files, the third-party +notices (every package also carries them), the update note and a file of +SHA-256 sums to a draft release. It never publishes a release, never changes +one already published, and never pushes the apt or dnf repositories (a +separate workflow, by hand, from a published release does). Signing runs only +when the owner's secrets are present and says so in the run's notices when not. +*Enforced:* `.github/workflows/release.yml`, +`.github/workflows/publish-repos.yml`. +*Checked:* `ledger-cli` `tests/packaging.rs` +(`the_release_workflow_makes_a_draft_of_all_three_packages_and_publishes_nothing`, +`only_a_person_runs_the_workflow_that_publishes_the_repositories`, +`every_package_carries_the_licences_and_the_icon`). + +**WB-pkg-8 The books live where each system keeps an app's own data, apart +from the program.** macOS: Library/Application Support/wanderbooks in the person's +home. Windows: the local application data folder, `wanderbooks` (never the +roaming one: the books are large, hold locks and belong to one machine). +Linux: the XDG data folder, `wanderbooks`, where the books have always been +(unchanged). The folder with the private keys and certificate for the web +address is owner-only on each system, as the data root is. No data folder is +inside any folder a program is installed to. +*Enforced:* `ledger_store::root::data_dir_for`, +`ledger_store::root::default_root`, `ledger_link::private::make_dir`. +*Checked:* `ledger-store` `tests/data_locations.rs` +(`each_system_keeps_its_data_where_it_keeps_an_apps_data`, +`no_data_folder_is_inside_an_install_folder`); `ledger-link` unit tests in +`private.rs` (`a_private_file_reads_back_and_is_mode_0600`, +`a_private_file_and_its_folder_are_owner_only_on_windows`). diff --git a/justfile b/justfile index 8db57ebf..e524faad 100644 --- a/justfile +++ b/justfile @@ -591,10 +591,23 @@ package-linux version="" formats="deb,appimage,pacman": cargo build --release -p ledger-cli deploy/packaging/build-linux.sh {{version}} {{formats}} -# Build the unsigned macOS .dmg (on a Mac; CI does it on a tag or dispatch) +# The macOS app and its universal .dmg (on a Mac; CI does it on a tag or +# dispatch). Signs and notarizes only with WB_SIGN_IDENTITY and WB_NOTARY_* +# in the environment (deploy/packaging/macos/build-macos.sh says which). +# Build the universal macOS .dmg package-macos version="": + rustup target add aarch64-apple-darwin x86_64-apple-darwin + cargo build --release -p ledger-cli --target aarch64-apple-darwin + cargo build --release -p ledger-cli --target x86_64-apple-darwin + deploy/packaging/macos/build-macos.sh {{version}} + +# The per-user Windows installer (in Git Bash on Windows, with NSIS: choco +# install nsis; CI does it on a tag or dispatch). Unsigned unless the +# release workflow signs it. +# Build the Windows installer +package-windows version="": cargo build --release -p ledger-cli - deploy/packaging/build-macos.sh {{version}} + deploy/packaging/windows/build-windows.sh {{version}} # A release folder on this machine signed with a throwaway key; then # `wanderbooks update --feed file://DIR/manifest.json --trusted-key DIR/release.pub` diff --git a/plan/STATUS.md b/plan/STATUS.md index d864f980..5e86bfdb 100644 --- a/plan/STATUS.md +++ b/plan/STATUS.md @@ -1,5 +1,34 @@ # STATUS — 2026-11-10: the evaluation batch: no money arithmetic outside the kernel in any crate, exact Decimal sums, four gates the build did not have +## 2026-11-21: P15 unit C1, the installed app (branch `t3/p15-c1-desktop-packages`) + +Written on Linux; **nothing of it has run on Windows or macOS**, and no +package has been installed anywhere. The `release` workflow's first run is the +evidence. What is there (`docs/packaging.md`, "P15 unit C1"; `docs/install.md`; +claims `WB-pkg-1` to `WB-pkg-8` in `docs/spec/claims/packaging.md`): + +- **Windows**: a per-user NSIS installer (no administrator prompt), one + program, a Start Menu entry named Wanderbooks, a Settings > Apps + uninstaller that cannot reach the books. The program is built for the GUI + subsystem, so no console window; a terminal still gets a command's words. +- **macOS**: a universal `.app` in a `.dmg` (hardened runtime, an empty + entitlements file with the reasons, a Documents-folder purpose string); + signing and notarization run only with the owner's Apple secrets. +- **Linux**: the tools are unchanged; the desktop entries carry the icon and + the window's app id, every package carries the licences, and the packages + depend on git. +- **The Claude desktop extension**: the Connect page's last row writes a + `.mcpb` (Anthropic's MCP Bundle, manifest 0.3) per company. +- **Update**: the window says when a newer version exists and where to get it + (a daily look at one small file; only a version number is read); the update + is the newer package installed over the old. +- **Release**: a draft only, tests on each system, SHA-256 sums, licences; + the apt/dnf publish moved to a by-hand workflow. +- **Owner's, open**: signing identities and their secrets; whether to bundle + git on Windows and macOS (a GPL-2.0 consequence, `docs/packaging.md`); + the first run of the release workflow on GitHub and the first install on a + clean Windows and macOS machine. + ## 2026-11-10: the evaluation batch (plan/2026-11-09_TRIAGE.md) A full evaluation of the project on 2026-11-09 found nothing wrong in the