From 02f7fcdf734bf37396112bdfa634f27d0d424fbf Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 24 Nov 2026 20:00:44 -0500 Subject: [PATCH] packaging(linux): support co-installable nightly packages (#2350) Linux nightly packaging by @dylanmtaylor, with the per-app Nightly flavor commits stacked on his branch. Co-authored-by: Dylan M. Taylor --- .github/actionlint.yaml | 12 + .github/nightly-linux-signing-key.asc | 16 + .github/nightly-signing-policy.json | 112 ++++ .github/workflows/actions.lock | 5 + .github/workflows/nightly-macos.yml | 84 +++ .github/workflows/nightly-sign.yml | 42 ++ .github/workflows/nightly.yml | 34 ++ .github/workflows/packaging-lint.yml | 21 +- .gitignore | 6 + ATTRIBUTION.md | 2 + Cargo.lock | 2 + README.md | 23 + apps/deckcraft-cli/src/main.rs | 10 + apps/deckcraft-cli/tests/it/cli.rs | 19 + apps/deckcraft/Cargo.toml | 5 + apps/deckcraft/build.rs | 46 +- apps/deckcraft/src/app_dirs.rs | 189 ++++++ apps/deckcraft/src/build_channel.rs | 54 ++ apps/deckcraft/src/build_flavor.rs | 72 +++ apps/deckcraft/src/launch_profile.rs | 221 +++++++ apps/deckcraft/src/main.rs | 245 ++++++-- apps/deckcraft/src/nightly_session.rs | 277 +++++++++ apps/deckcraft/src/process_identity.rs | 70 +++ apps/deckcraft/src/profile_root.rs | 622 ++++++++++++++++++++ assets/app-icon/deckcraft-nightly-1024.png | Bin 0 -> 22205 bytes assets/app-icon/deckcraft-nightly.icns | Bin 0 -> 50041 bytes assets/app-icon/deckcraft-nightly.ico | Bin 0 -> 113870 bytes assets/app-icon/deckcraft-nightly.png | Bin 0 -> 3208 bytes assets/app-icon/nightly-provenance.json | 61 ++ crates/ui-egui/build.rs | 30 + crates/ui-egui/src/app.rs | 2 +- crates/ui-egui/src/app/commands.rs | 3 +- crates/ui-egui/src/dialogs/about.rs | 4 +- crates/ui-egui/src/dialogs/updates_ui.rs | 62 +- crates/ui-egui/src/flavor.rs | 36 ++ crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/os_window.rs | 80 +++ crates/ui-egui/src/services.rs | 3 + docs/nightly-release-preparation.md | 88 +++ packaging/linux/flatpak-bundle.sh | 70 ++- packaging/linux/nfpm.yaml | 13 +- packaging/linux/nightly-arch-tar-test.sh | 68 +++ packaging/linux/nightly-arch-tar.sh | 19 + packaging/linux/nightly-launch-test.sh | 105 ++++ packaging/linux/nightly-launch.sh | 63 ++ packaging/linux/nightly.sh | 33 ++ packaging/linux/package.sh | 150 ++++- packaging/macos/nightly-lib.sh | 110 ++++ packaging/macos/nightly-sign.sh | 143 +++++ packaging/macos/nightly-verify.sh | 74 +++ packaging/macos/nightly.sh | 51 ++ packaging/macos/nightly_plist.py | 69 +++ packaging/macos/nightly_plist_tests.py | 202 +++++++ packaging/macos/nightly_sign_tests.py | 425 +++++++++++++ packaging/nightly-archive.py | 134 +++++ packaging/nightly-common.sh | 95 +++ packaging/nightly-release-tests.py | 356 +++++++++++ packaging/nightly-tests.py | 36 ++ packaging/nightly_paths.py | 139 +++++ packaging/windows/nightly-package-tests.ps1 | 95 +++ packaging/windows/nightly-signing-tests.ps1 | 90 +++ packaging/windows/nightly.ps1 | 134 +++++ packaging/windows/package.ps1 | 21 +- packaging/windows/sign.ps1 | 41 +- sonar-project.properties | 11 + 65 files changed, 5222 insertions(+), 85 deletions(-) create mode 100644 .github/actionlint.yaml create mode 100644 .github/nightly-linux-signing-key.asc create mode 100644 .github/nightly-signing-policy.json create mode 100644 .github/workflows/nightly-macos.yml create mode 100644 .github/workflows/nightly-sign.yml create mode 100644 .github/workflows/nightly.yml create mode 100644 apps/deckcraft/src/app_dirs.rs create mode 100644 apps/deckcraft/src/build_channel.rs create mode 100644 apps/deckcraft/src/build_flavor.rs create mode 100644 apps/deckcraft/src/launch_profile.rs create mode 100644 apps/deckcraft/src/nightly_session.rs create mode 100644 apps/deckcraft/src/process_identity.rs create mode 100644 apps/deckcraft/src/profile_root.rs create mode 100644 assets/app-icon/deckcraft-nightly-1024.png create mode 100644 assets/app-icon/deckcraft-nightly.icns create mode 100644 assets/app-icon/deckcraft-nightly.ico create mode 100644 assets/app-icon/deckcraft-nightly.png create mode 100644 assets/app-icon/nightly-provenance.json create mode 100644 crates/ui-egui/src/flavor.rs create mode 100644 crates/ui-egui/src/os_window.rs create mode 100644 docs/nightly-release-preparation.md create mode 100755 packaging/linux/nightly-arch-tar-test.sh create mode 100755 packaging/linux/nightly-arch-tar.sh create mode 100755 packaging/linux/nightly-launch-test.sh create mode 100755 packaging/linux/nightly-launch.sh create mode 100755 packaging/linux/nightly.sh create mode 100755 packaging/macos/nightly-lib.sh create mode 100755 packaging/macos/nightly-sign.sh create mode 100755 packaging/macos/nightly-verify.sh create mode 100755 packaging/macos/nightly.sh create mode 100755 packaging/macos/nightly_plist.py create mode 100755 packaging/macos/nightly_plist_tests.py create mode 100755 packaging/macos/nightly_sign_tests.py create mode 100644 packaging/nightly-archive.py create mode 100644 packaging/nightly-common.sh create mode 100755 packaging/nightly-release-tests.py create mode 100755 packaging/nightly-tests.py create mode 100644 packaging/nightly_paths.py create mode 100644 packaging/windows/nightly-package-tests.ps1 create mode 100644 packaging/windows/nightly-signing-tests.ps1 create mode 100644 packaging/windows/nightly.ps1 diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml new file mode 100644 index 000000000..11ce0bebd --- /dev/null +++ b/.github/actionlint.yaml @@ -0,0 +1,12 @@ +# Custom runner labels actionlint can't know about. +self-hosted-runner: + labels: + - macos-release # org larger runner (M2 Pro), used by release.yml + +# actionlint 1.7.12 predates GitHub's queue key, which the signer caller may use when it needs +# serialization. Only this exact false positive is suppressed; Packaging lint's independent +# source-contract job enforces the values. +paths: + .github/workflows/nightly-sign.yml: + ignore: + - '^unexpected key "queue" for "concurrency" section\. expected one of "cancel-in-progress", "group"$' diff --git a/.github/nightly-linux-signing-key.asc b/.github/nightly-linux-signing-key.asc new file mode 100644 index 000000000..a1c1f31e8 --- /dev/null +++ b/.github/nightly-linux-signing-key.asc @@ -0,0 +1,16 @@ +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C +bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA +OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL +AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf +PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz +BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56 +er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT +oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ +AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo +9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo +SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A +ga/qCA== +=3wGQ +-----END PGP PUBLIC KEY BLOCK----- diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json new file mode 100644 index 000000000..93c84e100 --- /dev/null +++ b/.github/nightly-signing-policy.json @@ -0,0 +1,112 @@ +{ + "schema": "craft-nightly-release-policy/v3", + "repository": "storytold/deckcraft", + "repository_id": 1408294296, + "producer_workflow_id": null, + "producer_workflow_path": ".github/workflows/nightly.yml", + "producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea", + "signer_workflow_path": ".github/workflows/nightly-sign.yml", + "signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea", + "release_branch": "release", + "manual_actors": [ + "bflatastic", + "dylanmtaylor", + "echelon", + "FredApps", + "skylartaylor" + ], + "max_age_seconds": 86400, + "candidate_policy": { + "schema": "craft-nightly-candidate-policy/v3", + "epoch": "deckcraft-nightly-20261124-initial", + "repository": "storytold/deckcraft", + "branch": "main", + "required_workflows": [ + { + "workflow_id": 377160704, + "workflow_path": ".github/workflows/ci.yml", + "jobs": [ + { + "name": "font-pin", + "app_id": 15368, + "applicability": "required" + }, + { + "name": "gate / gate (ubuntu-24.04)", + "app_id": 15368, + "applicability": "required" + } + ] + } + ], + "sonar": { + "organization": "storytold", + "project": "storytold_deckcraft", + "app_id": 12526, + "check_name": "SonarCloud Code Analysis", + "details_url": "https://sonarcloud.io/dashboard?id=storytold_deckcraft&branch=main", + "issue_types": [ + "VULNERABILITY" + ], + "accepted_conditions": [ + { + "metric": "new_security_rating", + "comparator": "GT", + "error_threshold": "1", + "maximum": "5" + } + ], + "required_conditions": [ + { + "metric": "new_reliability_rating", + "comparator": "GT", + "error_threshold": "1" + }, + { + "metric": "new_maintainability_rating", + "comparator": "GT", + "error_threshold": "1" + }, + { + "metric": "new_coverage", + "comparator": "LT", + "error_threshold": "80" + }, + { + "metric": "new_duplicated_lines_density", + "comparator": "GT", + "error_threshold": "3" + }, + { + "metric": "new_security_hotspots_reviewed", + "comparator": "LT", + "error_threshold": "100" + } + ], + "debt": [] + } + }, + "max_artifact_bytes": 2147483648, + "automatic_signer_actors": [], + "platforms": { + "windows-x86_64": { + "unsigned_artifact_name": "nightly-unsigned-windows-x86_64", + "trust": { + "publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US" + } + }, + "linux-x86_64": { + "unsigned_artifact_name": "nightly-unsigned-linux-x86_64", + "trust": { + "fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED" + } + }, + "macos-aarch64": { + "unsigned_artifact_name": "nightly-unsigned-macos-aarch64", + "trust": { + "apple_team_id": "DJ6XS33FX8" + } + } + } +} diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index 5e478baa9..208d35e10 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -11,6 +11,11 @@ workflows: '.github/workflows/lockfile.yml': - 'actions/checkout@v7.0.1' - 'step-security/harden-runner@v2.22.4' + '.github/workflows/nightly-sign.yml': [] + '.github/workflows/nightly.yml': [] + '.github/workflows/nightly-macos.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/harden-runner@v2.22.4' '.github/workflows/nix.yml': [] '.github/workflows/packaging-lint.yml': - 'actions/checkout@v7.0.1' diff --git a/.github/workflows/nightly-macos.yml b/.github/workflows/nightly-macos.yml new file mode 100644 index 000000000..54529b83d --- /dev/null +++ b/.github/workflows/nightly-macos.yml @@ -0,0 +1,84 @@ +# Builds the unsigned Apple-silicon DeckCraft Nightly (packaging/macos/nightly.sh) on a hosted +# macOS runner and checks the archive as the Launcher unpacks it, ending with the bundle's version +# query (packaging/macos/nightly-verify.sh --expect unsigned). No secrets and no environment: the +# real Nightly is signed and notarized by the shared release-ref signer (craft-common-actions), +# which calls packaging/macos/nightly-sign.sh. +name: Nightly macOS build + +on: + # macOS runners are shared with release builds: pull requests run this only with the `full-ci` + # label, never by changed paths. `labeled` so adding the label starts a run. + pull_request: + types: [opened, synchronize, reopened, labeled] + workflow_dispatch: + +permissions: + contents: read + +# A newer push to a labelled PR cancels its older run. Any event that will not build (no `full-ci` +# label, or another label added) gets a group of its own, so it never cancels a real build. +concurrency: + group: nightly-macos-${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'full-ci') && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + build: + name: Nightly .app (aarch64, unsigned) + if: >- + github.event_name == 'workflow_dispatch' || + (contains(github.event.pull_request.labels.*.name, 'full-ci') && + (github.event.action != 'labeled' || github.event.label.name == 'full-ci')) + runs-on: macos-15 + timeout-minutes: 90 + env: + CARGO_TERM_COLOR: always + CARGO_INCREMENTAL: 0 + RUST_BACKTRACE: 1 + steps: + - name: Harden runner + uses: step-security/harden-runner@v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + # The release's pin (release.yml craft-fonts-ref), so the bundle's notices match a shipped build. + - name: Check out craft-fonts + uses: actions/checkout@v7.0.1 + with: + repository: storytold/craft-fonts + ref: 37827adc41fd165f9a9234ac40f94dbad353aa69 + path: craft-fonts + - name: Check out craft-i18n + uses: actions/checkout@v7.0.1 + with: + repository: storytold/craft-i18n + path: craft-i18n + # The hosted image ships rustup: install the current stable plus the macOS target, with no new + # action pin for one job. Cargo enforces [workspace.package] rust-version. + - name: Install the Rust toolchain + run: rustup toolchain install stable --profile minimal --target aarch64-apple-darwin + + # A version of the prepared Nightly form for this commit; the real one comes from the feed's + # identity job. Only nightly.sh's input checks read it. + - name: Prepare a Nightly identity for this commit + run: | + set -euo pipefail + base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')" + sha="$(git rev-parse HEAD)" + date="$(date -u +%Y-%m-%d)" + { + echo "DECKCRAFT_BUILD_SHA=$sha" + echo "DECKCRAFT_BUILD_DATE=$date" + echo "DECKCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}" + } >>"$GITHUB_ENV" + - name: Build the unsigned Nightly bundle + env: + DECKCRAFT_BUILD_CHANNEL: nightly-v1 + CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets + DIST: ${{ runner.temp }}/nightly-dist + CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts + CRAFT_FONTS_REQUIRED: "1" + run: bash packaging/macos/nightly.sh --arch aarch64 + - name: Check the archive and the bundle's version + run: bash packaging/macos/nightly-verify.sh --expect unsigned --input "$RUNNER_TEMP/nightly-dist/deckcraft-$DECKCRAFT_VERSION-macos-aarch64-nightly.zip" diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml new file mode 100644 index 000000000..a6e384c94 --- /dev/null +++ b/.github/workflows/nightly-sign.yml @@ -0,0 +1,42 @@ +name: DeckCraft release-ref nightly signer + +# Enabled for supervised manual dispatch on release. Main/release contents must match. +# A reusable callee does not change context; this must be a real top-level release dispatch. +on: + workflow_dispatch: + inputs: + producer_run_id: + description: Exact untrusted producer Actions run ID + required: true + type: string + producer_run_attempt: + description: Exact untrusted producer Actions run attempt + required: true + type: string + +permissions: {} + +concurrency: + group: deckcraft-nightly-release + cancel-in-progress: false + +jobs: + release: + # Actual context guards: official repository, manual dispatch, real release branch. + if: >- + github.repository == 'storytold/deckcraft' && + github.event_name == 'workflow_dispatch' && + github.ref == 'refs/heads/release' && github.ref_type == 'branch' + permissions: + contents: write + actions: read + checks: read + attestations: write + id-token: write + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea + with: + tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea + producer_run_id: ${{ inputs.producer_run_id }} + producer_run_attempt: ${{ inputs.producer_run_attempt }} + # No secrets: inherit or raw platform values in this caller. Only the isolated native + # callee job may bind the existing release environment and export keys in its signing step. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml new file mode 100644 index 000000000..a3cbdebe9 --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,34 @@ +name: DeckCraft unsigned nightly + +# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet. +# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it). +on: + workflow_dispatch: + +permissions: + contents: read + +jobs: + unsigned: + # Actual context guards only; no inherited/platform secrets. + if: >- + github.repository == 'storytold/deckcraft' && + github.ref == 'refs/heads/main' && github.ref_type == 'branch' && + (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') + # Maximum for the reusable workflow. Its compiler narrows to contents/actions read; + # no OIDC, attestation write, release environment or platform secrets in compilation. + permissions: + contents: read + actions: read + attestations: write + id-token: write + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea + with: + tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea + app-name: deckcraft + manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' + craft-fonts-ref: 37827adc41fd165f9a9234ac40f94dbad353aa69 + # One producer run builds every listed platform for one all-or-nothing release. The pin is the + # craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the + # Linux/macOS signer (#342). + platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]' diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index fb9e3d4f7..306c88caa 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -5,9 +5,9 @@ name: Packaging lint on: push: branches: [main, release] - paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"] + paths: [".github/workflows/**", ".github/actionlint.yaml", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"] pull_request: - paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"] + paths: [".github/workflows/**", ".github/actionlint.yaml", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"] workflow_dispatch: permissions: @@ -49,3 +49,20 @@ jobs: - name: Build and check non-executable installer fixtures shell: pwsh run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests') + + nightly-source-contract: + name: Nightly source contracts (no build or signing) + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + steps: + - name: Harden runner + uses: step-security/harden-runner@v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - name: Enforce nightly serialization and synthetic packaging contracts + run: python3 packaging/nightly-tests.py diff --git a/.gitignore b/.gitignore index 07d2ffd67..61dd538a6 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,9 @@ packaging/env.sh /packaging/linux/flatpak/cargo-sources.json /build-flatpak/ /.flatpak-builder/ + +# Checked out inside the workspace by the shared nightly workflows (craft-common-actions). +/.nightly-tools +/.nightly-input +/craft-i18n +__pycache__/ diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index c64f9e5b7..638e22eae 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -23,6 +23,8 @@ artwork. The ribbon and menu icons stay original drawings. | `packaging/macos/dmg/background.svg` | @XusBadia | DeckCraft macOS DMG window background, original work for this repository (2026-10-08), derived from the DeckCraft app icon `assets/app-icon/deckcraft-1024.png` (referenced via ``, not copied); text is outlined Inter / JetBrains Mono glyph paths | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | Finder window of the macOS DMG; `packaging/macos/dmg/generate.py` renders it to `background.tiff` | | `packaging/macos/dmg/background.tiff` | @XusBadia | Rendered from `packaging/macos/dmg/background.svg` by `packaging/macos/dmg/generate.py` | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 1x + 2x HiDPI TIFF for the macOS DMG window; includes the app icon (see its row) and LittleCMS's built-in sRGB profile ("No copyright, use freely") | | `assets/app-icon/deckcraft.icns`, `assets/app-icon/deckcraft.ico` | DeckCraft contributors | generated from the PNGs above by `packaging/icons.sh` (sips/iconutil, `cargo xtask ico`) | MIT OR Apache-2.0 | macOS and Windows app icons | +| `assets/app-icon/deckcraft-nightly*` (`deckcraft-nightly.png`, `deckcraft-nightly-1024.png`, `deckcraft-nightly.ico`, `deckcraft-nightly.icns`) | @skylartaylor | derivative of `assets/app-icon/deckcraft-1024.png` and `assets/app-icon/icon-source.deckcraft`, recoloured in code (background `#f26b1d` → `#a6420c`; foreground, padding and accent bars unchanged; native-size frames area-averaged from the 1024 master); recorded in `assets/app-icon/nightly-provenance.json` | MIT OR Apache-2.0 | DeckCraft Nightly app icon: window/desktop icon, macOS `CFBundleIconFile`, Windows resources and `.ico` | +| `assets/app-icon/nightly-provenance.json` | @skylartaylor | written alongside the nightly icons above; names their inputs, the recolour method and every output SHA-256 | MIT OR Apache-2.0 | Provenance of the DeckCraft Nightly icons | | `assets/app-icon/hicolor/scalable/apps/ai.storyteller.deckcraft.svg` | DeckCraft contributors | the shapes of `assets/app-icon/icon-source.deckcraft` written out as SVG (same coordinates, colours and corner radii) | MIT OR Apache-2.0 | Scalable app icon for Linux desktops (hicolor theme) | | `assets/app-icon/icon-source.deckcraft` | DeckCraft contributors | made with `deckcraft-cli run` (see git history) | MIT OR Apache-2.0 | Source of the placeholder icon | | `docs/images/editor.png`, `docs/images/shape-format.png`, `docs/images/format-pane.png`, `docs/images/slide-sorter.png`, `docs/images/dark-mode.png`, `docs/images/sample-deck.png` | DeckCraft contributors | Screenshots of DeckCraft and slides rendered by `deckcraft-cli` from the built-in sample deck (original content; Inter font, OFL-1.1) | MIT OR Apache-2.0 | README screenshots | diff --git a/Cargo.lock b/Cargo.lock index a1e9615e0..dd197290f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1284,8 +1284,10 @@ dependencies = [ "log", "rfd", "serde_json", + "thiserror 2.0.21", "winit", "winresource", + "winsafe", ] [[package]] diff --git a/README.md b/README.md index 32d9b0e56..1265e5924 100644 --- a/README.md +++ b/README.md @@ -173,6 +173,29 @@ See [ROADMAP.md](ROADMAP.md) for the stage, numbers by dimension and what's next [docs/gaps.md](docs/gaps.md) for every known shortfall and [docs/parity-checklist.md](docs/parity-checklist.md) for the feature-by-feature checklist. +## Nightly builds (not released yet) + +DeckCraft has a separate **DeckCraft Nightly** channel for Launcher-managed nightly builds beside +the stable app: its own application ID, package identity, data folder, taskbar entry and window +class, so it never reads or writes stable DeckCraft's settings, recovery autosaves, logs, user +dictionary or single window state. The Nightly app is started only by ArtCraft Launcher +(`--launch-profile nightly-v1 --profile-root -- `); the profile root is validated and +fenced against every stable data and install folder, so a Nightly window cannot fall back to +stable state. Nightly is managed by the Launcher and does not self-update. + +On Linux, every Nightly format starts through the same launcher +(`packaging/linux/nightly-launch.sh`): the `.tar.gz` and AppImage, the deb/rpm package, the Flatpak +and the Arch handoff all pass `--launch-profile nightly-v1 --profile-root -- ` to the +GUI, so an unpacked or distro-installed copy is isolated without the Launcher. + +The channel's packaging lives in `packaging/nightly-common.sh`, `packaging/{linux,macos,windows}/nightly*` +and `.github/workflows/nightly*.yml`. The producer and signer workflows are registered and can be +dispatched by the reviewed release managers only; there is no schedule or automatic dispatch yet. +Read [`docs/nightly-release-preparation.md`](docs/nightly-release-preparation.md) before the first +supervised run. The channel is compiled with `DECKCRAFT_BUILD_CHANNEL=nightly-v1`, which also +selects the deeper-background icons recorded in +[`assets/app-icon/nightly-provenance.json`](assets/app-icon/nightly-provenance.json). + ## Downloads **Download DeckCraft** from GitHub: the [latest release](https://github.com/storytold/deckcraft/releases/latest) has every build listed below, and [all releases](https://github.com/storytold/deckcraft/releases) has earlier versions and their notes. `` in the file names is the version number, and `SHA256SUMS.txt` lists a checksum for every file. diff --git a/apps/deckcraft-cli/src/main.rs b/apps/deckcraft-cli/src/main.rs index 420f4f1a5..961a3ec37 100644 --- a/apps/deckcraft-cli/src/main.rs +++ b/apps/deckcraft-cli/src/main.rs @@ -41,6 +41,16 @@ fn stdout_line(args: std::fmt::Arguments<'_>) -> std::io::Result<()> { fn main() -> ExitCode { let args: Vec = std::env::args().skip(1).collect(); + // nightly-v1 is a desktop-only launcher protocol. Never let GUI profile arguments fall through + // to stable CLI/MCP directory discovery. + if args + .iter() + .take_while(|arg| arg.as_str() != "--") + .any(|arg| arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=")) + { + eprintln!("nightly-v1 is supported only by the DeckCraft desktop launcher protocol"); + return ExitCode::from(2); + } let rest = args.get(1..).unwrap_or(&[]); let asks_help = rest.iter().any(|a| a == "--help" || a == "-h"); if let Some(page) = args.first().filter(|_| asks_help).and_then(|n| help::page(n)) { diff --git a/apps/deckcraft-cli/tests/it/cli.rs b/apps/deckcraft-cli/tests/it/cli.rs index fd9c27ed7..fafc663c4 100644 --- a/apps/deckcraft-cli/tests/it/cli.rs +++ b/apps/deckcraft-cli/tests/it/cli.rs @@ -287,3 +287,22 @@ fn commands_lists_one_line_per_command() { assert_eq!(stdout(&cli(&["commands", "slide.next"])), "slide.next — Next Slide\n"); assert_eq!(stdout(&cli(&["commands", "shape.presets"])), "shape.presets — Shape Gallery → [{name, label, category}]\n"); } + +/// The desktop-only Nightly launcher protocol never falls through to the CLI's stable directory +/// discovery: every spelling leaves with exit 2 and says so. +#[test] +fn the_desktop_launcher_protocol_is_refused() { + for args in [ + &["--launch-profile", "nightly-v1", "--profile-root", "/nightly-data/profiles/deckcraft", "--", "deck.pptx"][..], + &["--launch-profile", "nightly-v1", "info"][..], + &["--profile-root=/nightly-data/profiles/deckcraft", "info"][..], + ] { + let o = cli(args); + assert_eq!(o.status.code(), Some(2), "{args:?}"); + let err = String::from_utf8_lossy(&o.stderr); + assert!(err.contains("desktop launcher protocol"), "{args:?}: {err}"); + } + // Everything after the delimiter is a file name, so the flags there are not the protocol. + let o = cli(&["--", "--launch-profile"]); + assert_eq!(o.status.code(), Some(1), "`--` is an unknown subcommand, not a profile"); +} diff --git a/apps/deckcraft/Cargo.toml b/apps/deckcraft/Cargo.toml index 5b4afbb83..f4afdaf33 100644 --- a/apps/deckcraft/Cargo.toml +++ b/apps/deckcraft/Cargo.toml @@ -21,6 +21,7 @@ egui = { workspace = true } serde_json = { workspace = true } log = { workspace = true } chrono = { workspace = true } +thiserror = { workspace = true } [build-dependencies] # Icon + VERSIONINFO for deckcraft.exe; build.rs only uses it when the target is Windows. @@ -33,6 +34,10 @@ arboard = { workspace = true, features = ["image-data"] } image = { workspace = true } cpal = "0.16" +[target.'cfg(windows)'.dependencies] +# An explicit AppUserModelID for DeckCraft Nightly, so its taskbar group and toasts are not stable's. +winsafe = { version = "0.0.29", features = ["user", "shell"] } + [target.'cfg(target_os = "macos")'.dependencies] # Finder double-click, Open With, Dock drops and `open -a DeckCraft deck.pptx` arrive as a # kAEOpenDocuments Apple event, which winit 0.30 doesn't handle. This audited crate (also used by diff --git a/apps/deckcraft/build.rs b/apps/deckcraft/build.rs index 5bb30d583..368fb06c2 100644 --- a/apps/deckcraft/build.rs +++ b/apps/deckcraft/build.rs @@ -4,22 +4,62 @@ //! On every other target this does nothing. A missing resource compiler is a warning, so a //! cross-compile from macOS or Linux still links, unless `DECKCRAFT_REQUIRE_WINRES=1` turns it //! into an error (for release builds). +//! +//! `DECKCRAFT_BUILD_CHANNEL=nightly-v1` selects the Nightly flavor: `cfg(deckcraft_nightly_v1)`, +//! the deeper nightly icon, `ProductName "DeckCraft Nightly"` and the exact prepared +//! `DECKCRAFT_VERSION` as ProductVersion (the Launcher checks ProductVersion, not FileVersion). + +#[path = "src/build_channel.rs"] +mod build_channel; fn main() { println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-env-changed=DECKCRAFT_BUILD_CHANNEL"); + println!("cargo:rustc-check-cfg=cfg(deckcraft_nightly_v1)"); + let nightly = match std::env::var("DECKCRAFT_BUILD_CHANNEL").as_deref() { + Ok("nightly-v1") => { + println!("cargo:rustc-cfg=deckcraft_nightly_v1"); + true + } + // An empty value (an unset CI input) means the default stable build. + Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false, + _ => { + eprintln!("unsupported DECKCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)"); + std::process::exit(1); + } + }; println!("cargo:rerun-if-changed=../../assets/app-icon/deckcraft.ico"); + println!("cargo:rerun-if-changed=../../assets/app-icon/deckcraft-nightly.ico"); println!("cargo:rerun-if-env-changed=DECKCRAFT_REQUIRE_WINRES"); + println!("cargo:rerun-if-env-changed=DECKCRAFT_VERSION"); + let built_version = if nightly { + match std::env::var("DECKCRAFT_VERSION") { + Ok(version) if build_channel::is_nightly_version(&version) => version, + _ => { + eprintln!("nightly-v1 requires an explicit DECKCRAFT_VERSION feed identity"); + std::process::exit(1); + } + } + } else { + std::env::var("CARGO_PKG_VERSION").unwrap_or_default() + }; + println!("cargo:rustc-env=DECKCRAFT_BUILT_VERSION={built_version}"); + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return; } let mut res = winresource::WindowsResource::new(); - res.set_icon("../../assets/app-icon/deckcraft.ico") - .set("ProductName", "DeckCraft") - .set("FileDescription", "DeckCraft presentations") + res.set_icon(build_channel::windows_icon_path(nightly)) + .set("ProductName", if nightly { "DeckCraft Nightly" } else { "DeckCraft" }) + .set("FileDescription", if nightly { "DeckCraft Nightly presentations" } else { "DeckCraft presentations" }) .set("CompanyName", "Learning Machines LLC") .set("LegalCopyright", "Copyright (c) the DeckCraft authors. MIT OR Apache-2.0.") .set("OriginalFilename", "deckcraft.exe") .set("InternalName", "deckcraft"); + if nightly { + // The Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion. + res.set("ProductVersion", &built_version); + } if let Err(e) = res.compile() { if std::env::var_os("DECKCRAFT_REQUIRE_WINRES").is_some() { eprintln!("embedding Windows resources failed: {e}"); diff --git a/apps/deckcraft/src/app_dirs.rs b/apps/deckcraft/src/app_dirs.rs new file mode 100644 index 000000000..caa250c0e --- /dev/null +++ b/apps/deckcraft/src/app_dirs.rs @@ -0,0 +1,189 @@ +//! Where the desktop app keeps its per-user data: `ui.json`, `prefs.json`, `logs/`, the crash +//! recovery folder and the user dictionary all live under the directory [`config_dir`] returns. +//! +//! In order: +//! 1. A selected Nightly profile root ([`crate::launch_profile`]): everything lives under it, and +//! nothing is read from or written to a stable folder. +//! 2. The platform convention: macOS `~/Library/Application Support/DeckCraft`, Windows +//! `%APPDATA%\DeckCraft`, Linux `$XDG_CONFIG_HOME/deckcraft` or `~/.config/deckcraft`. +//! +//! DeckCraft has no portable mode and no `DECKCRAFT_CONFIG_DIR` override, so the stable resolution +//! is exactly the one `main.rs` used before the Nightly channel; the fence module +//! ([`crate::profile_root`]) still refuses a `DeckCraftData` folder or a `portable.txt` beside a +//! DeckCraft executable, which a hand-made portable copy could carry. + +use std::ffi::OsString; +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; + +/// The portable data folder name a hand-made portable copy could use. No DeckCraft package +/// writes it, but the fence refuses a profile inside one (see [`crate::profile_root`]). +pub const PORTABLE_DATA_DIR: &str = "DeckCraftData"; + +/// The marker file of a portable copy, beside its executable. +pub const PORTABLE_MARKERS: [&str; 1] = ["portable.txt"]; + +/// The portable marker in `dir`, when it is a regular file. +pub fn portable_marker(dir: &Path) -> Option { + PORTABLE_MARKERS.iter().map(|name| dir.join(name)).find(|path| path.is_file()) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + /// The profile root chosen by the Launcher (`--launch-profile nightly-v1`). + Override, + /// The platform convention (stable). + Platform, +} + +#[derive(Clone, Debug)] +pub struct DataDir { + pub dir: Option, + pub mode: Mode, +} + +/// The data directory for this process, resolved once. +pub fn current() -> &'static DataDir { + static DIR: OnceLock = OnceLock::new(); + DIR.get_or_init(|| match crate::launch_profile::current().root() { + Some(root) => DataDir { dir: Some(root.to_path_buf()), mode: Mode::Override }, + None => DataDir { dir: platform_dir(|key| std::env::var_os(key)), mode: Mode::Platform }, + }) +} + +/// The per-user settings directory (see the module docs). +pub fn config_dir() -> Option { + current().dir.clone() +} + +/// The platform's settings directory. Read from the environment every call, so tests can vary it. +pub fn platform_dir(env: impl Fn(&str) -> Option) -> Option { + if cfg!(target_os = "macos") { + env("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/DeckCraft")) + } else if cfg!(windows) { + env("APPDATA").map(|a| PathBuf::from(a).join("DeckCraft")) + } else { + env("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| env("HOME").map(|h| PathBuf::from(h).join(".config"))).map(|c| c.join("deckcraft")) + } +} + +/// The crash-recovery folder: inside the profile for Nightly, the platform's own folder for stable +/// (`deckcraft_engine::recovery::default_dir`, which keeps autosaves out of the synced config). +fn recovery_dir_for(current: &DataDir) -> Option { + match current { + DataDir { dir: Some(root), mode: Mode::Override } => Some(root.join("Recovery")), + _ => deckcraft_engine::recovery::default_dir(), + } +} + +/// [`recovery_dir_for`] for this process. +pub fn recovery_dir() -> Option { + recovery_dir_for(current()) +} + +/// The user dictionary (`user.dic`, the words "Add to dictionary" keeps): inside the profile for +/// Nightly, the platform's dictionary folder for stable. +fn user_dictionary_for(current: &DataDir) -> Option { + match current { + DataDir { dir: Some(root), mode: Mode::Override } => Some(root.join("Dictionaries").join("user.dic")), + _ => None, + } +} + +/// [`user_dictionary_for`] for this process. +pub fn user_dictionary() -> Option { + user_dictionary_for(current()) +} + +/// The app's exclusive write probe: a new file created in `dir` and removed again. It never falls +/// back to another directory, so the Nightly validator can refuse a root it cannot write. +pub fn ensure_writable(dir: &Path) -> std::io::Result<()> { + // A probe left behind by an interrupted launch must not make a writable profile look + // unwritable, so each attempt uses a fresh name and a collision tries the next one. + // `create_new` still guarantees a create rather than a truncation. + for attempt in 0..8u32 { + let probe = dir.join(format!(".deckcraft-write-probe-{}-{attempt}", std::process::id())); + match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) { + Ok(file) => { + drop(file); + return std::fs::remove_file(probe); + } + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error), + } + } + Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "no free write-probe name in the profile")) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeMap; + + fn env(pairs: &[(&str, &str)]) -> BTreeMap { + pairs.iter().map(|(k, v)| ((*k).into(), (*v).into())).collect() + } + + #[test] + fn platform_dirs_follow_the_platform_convention() { + let home = if cfg!(windows) { r"C:\Users\me" } else { "/home/me" }; + let env = env(&[("HOME", home), ("APPDATA", r"C:\Users\me\AppData\Roaming"), ("XDG_CONFIG_HOME", "/xdg/config")]); + let dir = platform_dir(|k| env.get(k).cloned()).expect("a platform directory"); + if cfg!(target_os = "macos") { + assert_eq!(dir, PathBuf::from(home).join("Library/Application Support/DeckCraft")); + } else if cfg!(windows) { + assert_eq!(dir, PathBuf::from(r"C:\Users\me\AppData\Roaming").join("DeckCraft")); + } else { + assert_eq!(dir, PathBuf::from("/xdg/config").join("deckcraft")); + } + } + + /// Recovery and the dictionary follow the profile; stable keeps the engine's own folders and + /// writes no per-profile dictionary. + #[test] + fn the_nightly_profile_owns_recovery_and_the_dictionary() { + let root = PathBuf::from("/nightly-data/profiles/deckcraft"); + let profile = DataDir { dir: Some(root.clone()), mode: Mode::Override }; + assert_eq!(recovery_dir_for(&profile), Some(root.join("Recovery"))); + assert_eq!(user_dictionary_for(&profile), Some(root.join("Dictionaries").join("user.dic"))); + let stable = DataDir { dir: None, mode: Mode::Platform }; + assert_eq!(user_dictionary_for(&stable), None); + assert_eq!(recovery_dir_for(&stable), deckcraft_engine::recovery::default_dir()); + } + + /// The process resolves its data directory once; every caller must get that same decision. + #[test] + fn the_data_directory_is_resolved_once() { + let resolved = current(); + assert!(std::ptr::eq(resolved, current())); + assert_eq!(resolved.dir, config_dir()); + } + + #[test] + fn permanent_probe_does_not_replace_an_existing_entry() { + let dir = std::env::temp_dir().join(format!("deckcraft-writable-{}-{}", std::process::id(), line!())); + std::fs::create_dir_all(&dir).unwrap(); + let probe = |attempt: u32| dir.join(format!(".deckcraft-write-probe-{}-{attempt}", std::process::id())); + // An entry already at the probe's name must never be truncated: the probe takes the next + // free name, and it removes only the file it created. + std::fs::write(probe(0), b"someone else's file").unwrap(); + ensure_writable(&dir).unwrap(); + assert_eq!(std::fs::read(probe(0)).unwrap(), b"someone else's file"); + assert!(!probe(1).exists()); + // Every name taken is an error, not a truncation of any of them. + for attempt in 0..8 { + std::fs::write(probe(attempt), b"someone else's file").unwrap(); + } + assert!(ensure_writable(&dir).is_err(), "no free probe name is reported, not truncated"); + for attempt in 0..8 { + assert_eq!(std::fs::read(probe(attempt)).unwrap(), b"someone else's file", "{attempt}"); + } + for attempt in 0..8 { + std::fs::remove_file(probe(attempt)).unwrap(); + } + // A folder whose stale probes were cleared is writable, and the probe leaves nothing behind. + ensure_writable(&dir).unwrap(); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/apps/deckcraft/src/build_channel.rs b/apps/deckcraft/src/build_channel.rs new file mode 100644 index 000000000..8faa6c300 --- /dev/null +++ b/apps/deckcraft/src/build_channel.rs @@ -0,0 +1,54 @@ +//! The build-time nightly identity shared by the build script and its pure regression tests. +pub fn is_nightly_version(version: &str) -> bool { + let Some((base, suffix)) = version.split_once("-nightly.") else { return false }; + let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()); + let base: Vec<_> = base.split('.').collect(); + let parts: Vec<_> = suffix.split('.').collect(); + base.len() == 3 + && base.iter().all(|s| digits(s)) + && parts.len() == 4 + && parts[0].len() == 8 + && digits(parts[0]) + && digits(parts[1]) + && digits(parts[2]) + && parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))) +} +pub fn windows_icon_path(nightly: bool) -> &'static str { + if nightly { "../../assets/app-icon/deckcraft-nightly.ico" } else { "../../assets/app-icon/deckcraft.ico" } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() { + assert_eq!(windows_icon_path(false), "../../assets/app-icon/deckcraft.ico"); + assert_eq!(windows_icon_path(true), "../../assets/app-icon/deckcraft-nightly.ico"); + } + + #[test] + fn explicit_feed_identity_is_required_for_a_nightly_build() { + assert!(is_nightly_version("0.19.0-nightly.20261124.17.1.gabcdef012345")); + for invalid in [ + "", + "0.19.0", + "0.19.0-nightly", + "0.19.0-nightly.20261124", + "0.19.0-nightly.20261124.17.1.gABCDEF012345", + "0.19.0-nightly.20261124.17.1.gabcdef012345\n", + ] { + assert!(!is_nightly_version(invalid), "{invalid:?}"); + } + } + + #[test] + fn version_cannot_inject_a_path_or_an_extra_build_directive() { + for invalid in [ + "../0.19.0-nightly.20261124.1.1.gabcdef012345", + "0.19.0-nightly.20261124.1.1.gabcdef012345/other", + "0.19.0-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other", + ] { + assert!(!is_nightly_version(invalid)); + } + } +} diff --git a/apps/deckcraft/src/build_flavor.rs b/apps/deckcraft/src/build_flavor.rs new file mode 100644 index 000000000..fb05b758c --- /dev/null +++ b/apps/deckcraft/src/build_flavor.rs @@ -0,0 +1,72 @@ +//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build. +use crate::launch_profile::Profile; +use std::ffi::OsString; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BuildFlavor { + Stable, + NightlyV1, +} + +pub const COMPILED: BuildFlavor = if cfg!(deckcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable }; + +pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> { + match (flavor, profile.is_nightly()) { + (BuildFlavor::NightlyV1, false) => Err("Open DeckCraft Nightly from ArtCraft Launcher".into()), + (BuildFlavor::Stable, true) => Err("This is a stable DeckCraft build; nightly-v1 requires the nightly build".into()), + _ => Ok(()), + } +} + +pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool { + desktop_session && flavor == BuildFlavor::NightlyV1 +} + +pub fn version_query(args: &[OsString]) -> bool { + matches!(args, [arg] if arg == "--version" || arg == "-V") +} + +pub fn version(flavor: BuildFlavor, stable: &str) -> String { + match flavor { + BuildFlavor::Stable => stable.to_owned(), + BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn only_a_nightly_desktop_refusal_requests_a_native_dialog() { + assert!(needs_native_error(BuildFlavor::NightlyV1, true)); + assert!(!needs_native_error(BuildFlavor::NightlyV1, false)); + assert!(!needs_native_error(BuildFlavor::Stable, true)); + assert!(!needs_native_error(BuildFlavor::Stable, false)); + } + + #[test] + fn nightly_build_without_a_profile_is_refused_before_startup() { + let started = std::cell::Cell::new(false); + let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true)); + assert!(result.unwrap_err().contains("ArtCraft Launcher")); + assert!(!started.get()); + } + + #[test] + fn stable_and_nightly_flavors_accept_only_their_own_profile() { + let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root")); + assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok()); + assert!(require_profile(BuildFlavor::Stable, &nightly).is_err()); + assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok()); + } + + #[test] + fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() { + assert_eq!(version(BuildFlavor::Stable, "0.19.0"), "0.19.0"); + assert_eq!(version(BuildFlavor::NightlyV1, "0.19.0"), "0.19.0 (nightly-v1)"); + assert!(version_query(&["--version".into()])); + assert!(version_query(&["-V".into()])); + assert!(!version_query(&["--".into(), "--version".into()])); + assert!(!version_query(&[])); + } +} diff --git a/apps/deckcraft/src/launch_profile.rs b/apps/deckcraft/src/launch_profile.rs new file mode 100644 index 000000000..fd95c757a --- /dev/null +++ b/apps/deckcraft/src/launch_profile.rs @@ -0,0 +1,221 @@ +//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state. +//! Stable launches retain their original arguments and directory policy. No environment mutation. + +use std::ffi::OsString; +use std::path::{Component, Path, PathBuf}; +use std::sync::OnceLock; + +pub const VERSION: &str = "nightly-v1"; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Profile { + Stable, + NightlyV1(PathBuf), +} + +impl Profile { + pub fn is_nightly(&self) -> bool { + matches!(self, Self::NightlyV1(_)) + } + + pub fn root(&self) -> Option<&Path> { + match self { + Self::Stable => None, + Self::NightlyV1(root) => Some(root), + } + } +} + +#[derive(Debug, PartialEq, Eq)] +pub struct Launch { + pub profile: Profile, + pub args: Vec, +} + +static PROFILE: OnceLock = OnceLock::new(); + +pub fn current() -> &'static Profile { + PROFILE.get().unwrap_or(&Profile::Stable) +} + +pub fn install(profile: Profile) -> Result<(), String> { + PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into()) +} + +/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is +/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here. +pub fn parse(args: Vec) -> Result { + let mut selector = None; + let mut root = None; + let mut other = Vec::new(); + let mut files = Vec::new(); + let mut iter = args.iter(); + let mut delimiter = false; + while let Some(arg) = iter.next() { + if arg == "--" { + delimiter = true; + files.extend(iter.cloned()); + break; + } + if arg == "--launch-profile" || arg == "--profile-root" { + let slot = if arg == "--launch-profile" { &mut selector } else { &mut root }; + if slot.is_some() { + return Err("the profile selector and root must each occur exactly once".into()); + } + let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?; + if value.to_string_lossy().starts_with("--") { + return Err("the profile selector/root needs a value".into()); + } + *slot = Some(value.clone()); + } else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") { + return Err("the nightly protocol requires separate literal selector/root argument tokens".into()); + } else { + other.push(arg.clone()); + } + } + match (selector, root) { + (None, None) => Ok(Launch { profile: Profile::Stable, args }), + (Some(version), Some(root)) if version == VERSION => { + if !delimiter || !other.is_empty() { + return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into()); + } + let root = PathBuf::from(root); + if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) { + return Err("the nightly profile root must be absolute and contain no parent traversal".into()); + } + Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() }) + } + (Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()), + _ => Err("--launch-profile and --profile-root must be supplied together".into()), + } +} + +/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`), +/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never +/// validated or touched, and `-- --version` stays a file name. +pub fn version_query(args: &[OsString]) -> bool { + let Some((last, pair)) = args.split_last() else { return false }; + if last != "--version" && last != "-V" { + return false; + } + let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect(); + matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1) +} + +/// Validation finishes before the caller's first startup effect. Stable never calls the nightly +/// root validator, so its old config resolution stays unchanged. +pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result) -> Result { + if let Profile::NightlyV1(root) = &launch.profile { + launch.profile = Profile::NightlyV1(validate(root)?); + } + Ok(launch) +} + +/// Resolve the selected private root before the caller's first startup effect. +pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option, exe: Option<&Path>) -> Result { + crate::profile_root::validate(root, env, exe, crate::app_dirs::ensure_writable) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + fn args(values: &[&str]) -> Vec { + values.iter().map(OsString::from).collect() + } + fn absolute() -> &'static str { + if cfg!(windows) { r"C:\NightlyData\profiles\deckcraft" } else { "/nightly-data/profiles/deckcraft" } + } + fn nightly() -> Vec { + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) + } + + /// The process installs one profile; later answers are read-only and a second install fails. + #[test] + fn the_process_installs_its_profile_once() { + assert_eq!(current(), &Profile::Stable, "an unselected process is a stable launch"); + assert!(install(Profile::Stable).is_ok()); + assert_eq!(current(), &Profile::Stable); + assert!(install(Profile::Stable).is_err()); + } + + #[test] + fn stable_arguments_and_directory_policy_are_unchanged() { + for argv in [args(&[]), args(&["--sample", "a.pptx"]), args(&["--", "--launch-profile", "file.pptx"])] { + let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap(); + assert_eq!(launch, Launch { profile: Profile::Stable, args: argv }); + } + } + + #[test] + fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() { + let mut argv = nightly(); + argv.extend(args(&["--profile-root", "talk with spaces.pptx"])); + let launch = parse(argv).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); + assert_eq!(launch.args, args(&["--", "--profile-root", "talk with spaces.pptx"])); + } + + #[test] + fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() { + for argv in [ + args(&["--launch-profile", VERSION]), + args(&["--profile-root", absolute()]), + args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", "", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--control", "4242", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute()]), + args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]), + ] { + assert!(parse(argv).is_err()); + } + } + + #[test] + fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() { + let pair = &["--launch-profile", VERSION, "--profile-root", absolute()]; + let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION]; + for flag in ["--version", "-V"] { + for form in [pair, reversed] { + let mut argv = args(form); + argv.push(flag.into()); + assert!(version_query(&argv), "{argv:?}"); + } + } + for argv in [ + args(&["--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--control", "1", "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]), + args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]), + args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]), + args(&["--launch-profile", VERSION, "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]), + ] { + assert!(!version_query(&argv), "{argv:?}"); + } + // Outside the query the strict protocol still refuses the version flag. + assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err()); + } + + #[test] + fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() { + let reached = Cell::new(false); + let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true)); + assert!(result.is_err()); + assert!(!reached.get()); + } + + #[test] + fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() { + let checked = PathBuf::from(absolute()).join("checked"); + let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap(); + assert_eq!(launch.profile.root(), Some(checked.as_path())); + assert!(launch.profile.is_nightly()); + } +} diff --git a/apps/deckcraft/src/main.rs b/apps/deckcraft/src/main.rs index b40f2bdce..554b1ea87 100644 --- a/apps/deckcraft/src/main.rs +++ b/apps/deckcraft/src/main.rs @@ -14,17 +14,25 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] +mod app_dirs; #[cfg(target_os = "macos")] mod apple_events; mod audio; +#[cfg(test)] +mod build_channel; +mod build_flavor; mod control_server; #[cfg(all(unix, not(target_os = "macos")))] mod display; #[cfg(any(target_os = "windows", test))] mod graphics; +mod launch_profile; mod logging; +mod nightly_session; #[cfg(not(target_arch = "wasm32"))] mod pasteboard; +mod process_identity; +mod profile_root; use deckcraft_engine::Session; use deckcraft_ui_egui::{Services, SlideApp}; @@ -50,6 +58,10 @@ impl eframe::App for App { self.0.ui(ui); } fn on_exit(&mut self) { + // The one exit path macOS has: run the hook exactly once (the Nightly session record). + if let Some(hook) = self.0.services.at_exit.take() { + hook(); + } save_prefs(&self.0); // The window is closing for good: a ready update's helper starts now and installs it once // the process has exited. @@ -69,25 +81,11 @@ impl eframe::App for App { } } -/// The per-user settings directory: `ui.json`, `prefs.json` and `logs/` live here. -fn config_dir() -> Option { - if cfg!(target_os = "macos") { - std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join("Library/Application Support/DeckCraft")) - } else if cfg!(windows) { - std::env::var_os("APPDATA").map(|a| std::path::PathBuf::from(a).join("DeckCraft")) - } else { - std::env::var_os("XDG_CONFIG_HOME") - .map(std::path::PathBuf::from) - .or_else(|| std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".config"))) - .map(|c| c.join("deckcraft")) - } -} - fn load_prefs(app: &mut SlideApp) { if std::env::var_os("DECKCRAFT_NO_PREFS").is_some() { return; } - let Some(dir) = config_dir() else { return }; + let Some(dir) = app_dirs::config_dir() else { return }; let (ui, prefs) = deckcraft_ui_egui::settings::load(&dir); if let Some(ui) = ui { app.ui = ui; @@ -101,7 +99,7 @@ fn save_prefs(app: &SlideApp) { if std::env::var_os("DECKCRAFT_NO_PREFS").is_some() { return; } - if let Some(dir) = config_dir() { + if let Some(dir) = app_dirs::config_dir() { deckcraft_ui_egui::settings::save(&dir, &app.ui, &app.session.prefs); } } @@ -155,8 +153,6 @@ fn display_count(window: &winit::window::Window) -> Option { (n > 0).then_some(n) } -const APP_ID: &str = "ai.storyteller.deckcraft"; - const USAGE: &str = "\ Usage: deckcraft [--control PORT] [--sample] [--show] [FILE...] @@ -183,6 +179,11 @@ fn startup(mut control_port: Option, args: impl IntoIterator let mut args = args.into_iter(); while let Some(a) = args.next() { match a.as_str() { + // The Nightly Launcher form: everything after the delimiter is a file. + "--" => { + files.extend(args.by_ref()); + break; + } "--control" => control_port = args.next().and_then(|p| p.parse().ok()), "--sample" => sample = true, "--show" => show = true, @@ -197,40 +198,134 @@ fn startup(mut control_port: Option, args: impl IntoIterator } fn app_icon() -> Option { + // The window icon follows the compiled channel, so a Nightly window is not the stable icon. + #[cfg(deckcraft_nightly_v1)] + let png: &[u8] = include_bytes!("../../../assets/app-icon/deckcraft-nightly.png"); + #[cfg(not(deckcraft_nightly_v1))] let png: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.deckcraft.png"); eframe::icon_data::from_png_bytes(png).map_err(|e| log::warn!("app icon: {e}")).ok() } +/// Select the immutable launch profile before any startup service or side effect. +fn prepare_launch() -> Option> { + // The trusted Launcher protocol is decided before logger/crash/update/font/prefs access. + let argv: Vec<_> = std::env::args_os().skip(1).collect(); + // Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root + // --version`: answered before root validation, process identity, IPC or any window. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) + { + use std::io::Write as _; + let _ = writeln!(std::io::stdout(), "DeckCraft {}", build_flavor::version(build_flavor::COMPILED, deckcraft_ui_egui::flavor::version())); + return None; + } + let early = launch_profile::parse(argv) + .and_then(|launch| { + build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; + initialize_nightly_process_identity().map_err(|error| error.to_string())?; + Ok(launch) + }) + .and_then(|launch| { + launch_profile::prepare(launch, |root| { + launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref()) + }) + }) + .unwrap_or_else(|error| { + report_launch_profile_error(&error); + std::process::exit(2) + }); + let identity = if early.profile.is_nightly() { + deckcraft_ui_egui::os_window::LaunchIdentity::NightlyV1 + } else { + deckcraft_ui_egui::os_window::LaunchIdentity::Stable + }; + if let Err(error) = launch_profile::install(early.profile).and_then(|()| deckcraft_ui_egui::os_window::select_identity(identity)) { + report_launch_profile_error(&error); + std::process::exit(2); + } + + Some(early.args) +} + +fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> { + process_identity::initialize( + build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, + deckcraft_ui_egui::os_window::id_for(deckcraft_ui_egui::os_window::LaunchIdentity::NightlyV1), + ) +} + +fn report_launch_profile_error(error: &str) { + eprintln!("DeckCraft launch profile: {error}"); + let desktop_session = cfg!(windows) + || cfg!(target_os = "macos") + || (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty()))); + if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) { + if let Err(error) = initialize_nightly_process_identity() { + eprintln!("DeckCraft launch profile: {error}"); + return; + } + #[cfg(any(windows, target_os = "linux", target_os = "macos"))] + let _ = rfd::MessageDialog::new() + .set_title("DeckCraft Nightly") + .set_description(error) + .set_level(rfd::MessageLevel::Error) + .set_buttons(rfd::MessageButtons::Ok) + .show(); + } +} + /// Install logging, parse startup arguments and environment, launch the native app, and /// propagate an eframe startup failure. fn main() -> eframe::Result { + let Some(arguments) = prepare_launch() else { return Ok(()) }; + let nightly = launch_profile::current().is_nightly(); + // Nightly session health: the record names this window's owner and survives an abnormal end. + let (watch, session_unavailable) = nightly_session::Session::begin_with_health( + launch_profile::current().root(), + deckcraft_ui_egui::flavor::version(), + option_env!("DECKCRAFT_BUILD_SHA"), + ) + .unwrap_or_else(|error| { + eprintln!("DeckCraft Nightly session state: {error}"); + (None, false) + }); + let previous_unclean = watch.as_ref().is_some_and(nightly_session::Session::previous_unclean); + let session: nightly_session::Shared = std::sync::Arc::new(std::sync::Mutex::new(watch)); + let notice_shown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let exit_session = session.clone(); + let exit_notice = notice_shown.clone(); // First, so every start-up record (and the engine's panic hook, installed with the first // Session) is captured; see `logging`. let logger = logging::install(); - if let Some(done) = craft_update::self_update::finish(&deckcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { + // Nightly is managed by ArtCraft Launcher: no stable self-update helper runs in it. + if !nightly + && let Some(done) = craft_update::self_update::finish(&deckcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) + { if let Err(e) = done { eprintln!("DeckCraft update helper failed: {e}"); std::process::exit(1); } return Ok(()); } - let (control_port, files, sample, show) = - match startup(std::env::var("DECKCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok()), std::env::args().skip(1)) { - Startup::Help => { - print!("{USAGE}"); - return Ok(()); - } - Startup::Version => { - println!("deckcraft {}", env!("CARGO_PKG_VERSION")); - return Ok(()); - } - Startup::Run { control_port, files, sample, show } => (control_port, files, sample, show), - }; - log::info!("DeckCraft {} ({} {})", env!("CARGO_PKG_VERSION"), std::env::consts::OS, std::env::consts::ARCH); + let (control_port, files, sample, show) = match startup( + if nightly { None } else { std::env::var("DECKCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok()) }, + arguments.into_iter().map(|a| a.to_string_lossy().into_owned()), + ) { + Startup::Help => { + print!("{USAGE}"); + return Ok(()); + } + Startup::Version => { + println!("deckcraft {}", env!("CARGO_PKG_VERSION")); + return Ok(()); + } + Startup::Run { control_port, files, sample, show } => (control_port, files, sample, show), + }; + log::info!("DeckCraft {} ({} {})", deckcraft_ui_egui::flavor::version(), std::env::consts::OS, std::env::consts::ARCH); + // The log file lives under the settings directory; opened after the arguments, so `--help` and // `--version` leave no file behind. Records logged until now are written to it first. if let Some(logger) = logger { - match config_dir().map(|d| logger.attach_dir(&d.join(logging::LOG_DIR))) { + match app_dirs::config_dir().map(|d| logger.attach_dir(&d.join(logging::LOG_DIR))) { Some(Ok(path)) => log::info!("log file {}", path.display()), Some(Err(e)) => log::warn!("no log file: {e}"), None => { @@ -241,7 +336,7 @@ fn main() -> eframe::Result { } let mut options = eframe::NativeOptions { viewport: egui::ViewportBuilder::default() - .with_title("DeckCraft") + .with_title(deckcraft_ui_egui::os_window::name_for(deckcraft_ui_egui::os_window::identity())) .with_inner_size([1440.0, 900.0]) .with_min_inner_size([900.0, 560.0]) .with_drag_and_drop(true) @@ -250,7 +345,7 @@ fn main() -> eframe::Result { .with_title_shown(false), ..Default::default() }; - options.viewport = options.viewport.with_app_id(APP_ID); + options.viewport = options.viewport.with_app_id(deckcraft_ui_egui::os_window::app_id()); if let Some(icon) = app_icon() { options.viewport = options.viewport.with_icon(icon); } @@ -286,28 +381,46 @@ fn main() -> eframe::Result { let apple_events = apple_events::AppleEvents::install(); #[cfg(target_os = "macos")] let apple_events = &apple_events; - eframe::run_native( - "DeckCraft", + let creator_notice = notice_shown.clone(); + let mut services = services(native_wayland); + // The Nightly session record is finished exactly once, on the clean exit path macOS has. + services.at_exit = Some(Box::new(move || { + nightly_session::finish_once(&exit_session, exit_notice.load(std::sync::atomic::Ordering::Relaxed)); + })); + let result = eframe::run_native( + deckcraft_ui_egui::os_window::name_for(deckcraft_ui_egui::os_window::identity()), options, Box::new(move |cc| { deckcraft_ui_egui::install_ime_pass_hooks(&cc.egui_ctx); - let mut app = SlideApp::new(Session::new(), services(native_wayland)); + let mut app = SlideApp::new(Session::new(), services); // Presenter View asks winit how many displays there are when a show starts. #[cfg(all(unix, not(target_os = "macos")))] if let Some(window) = cc.winit_window().cloned() { app.services.displays = Some(Box::new(move || display_count(&window))); } load_prefs(&mut app); - app.enable_update_checks(); + if !nightly { + // Nightly is managed by ArtCraft Launcher: no self-update prompt or stable feed. + app.enable_update_checks(); + } // AutoRecover: reopen what a previous run left unsaved, then keep it current. if std::env::var_os("DECKCRAFT_NO_RECOVERY").is_none() { - app.session.recovery_dir = deckcraft_engine::recovery::default_dir(); + app.session.recovery_dir = app_dirs::recovery_dir(); if let Ok(v) = app.session.execute("file.recovery.open", &serde_json::json!({})) && let Some(n) = v.get("opened").and_then(|o| o.as_array()).map(Vec::len).filter(|n| *n > 0) { app.set_status(format!("Recovered {n} unsaved presentation{} from the last session", if n == 1 { "" } else { "s" })); } } + if let Some(dictionary) = app_dirs::user_dictionary() { + deckcraft_engine::spell::set_user_dictionary_path(dictionary); + } + if session_unavailable { + app.set_status("Another DeckCraft Nightly window owns this profile: its session health is unavailable here."); + } else if previous_unclean { + app.set_status("DeckCraft Nightly closed unexpectedly last time."); + creator_notice.store(true, std::sync::atomic::Ordering::Relaxed); + } app.integrated_titlebar = cfg!(target_os = "macos"); if let Some(port) = control_port { let rx = control_server::start(port, cc.egui_ctx.clone()); @@ -329,7 +442,10 @@ fn main() -> eframe::Result { apple_events.connect(&cc.egui_ctx), ))) }), - ) + ); + // The exit hook normally finished it already; this covers a start that never created a window. + nightly_session::finish_once(&session, notice_shown.load(std::sync::atomic::Ordering::Relaxed)); + result } #[cfg(test)] @@ -399,6 +515,53 @@ mod tests { } } + /// The delimiter is the Nightly Launcher's file list, never a file name of its own. + #[test] + fn the_delimiter_ends_the_flags_and_leaves_only_files() { + let launch = startup(None, ["--", "--control", "deck.pptx"].map(str::to_string)); + assert!(matches!(launch, Startup::Run { control_port: None, .. })); + if let Startup::Run { files, .. } = launch { + assert_eq!(files, ["--control".to_string(), "deck.pptx".to_string()]); + } + } + + /// The desktop crate's build script and the UI crate's read the same channel switch. + #[test] + fn both_crates_agree_on_the_compiled_channel() { + assert_eq!(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, deckcraft_ui_egui::flavor::is_nightly()); + assert_eq!(deckcraft_ui_egui::os_window::name_for(deckcraft_ui_egui::os_window::LaunchIdentity::NightlyV1), "DeckCraft Nightly"); + } + + /// The exit hook (the Nightly session record) runs once, on the one exit path macOS has. + /// The check runs in a child with `DECKCRAFT_NO_PREFS=1`: `on_exit` saves the preferences + /// otherwise, and this test never loads the ones already on the machine. Not on macOS + /// itself: there `on_exit` ends the process, which is the behaviour the test above checks. + #[cfg(not(target_os = "macos"))] + #[test] + fn leaving_runs_the_exit_hook_once() { + if std::env::var_os("DECKCRAFT_TEST_EXIT_HOOK").is_some() { + let runs = std::rc::Rc::new(std::cell::Cell::new(0)); + let counted = runs.clone(); + let services = Services { at_exit: Some(Box::new(move || counted.set(counted.get() + 1))), ..Default::default() }; + let mut app = App(SlideApp::new(Session::new(), services)); + eframe::App::on_exit(&mut app); + assert_eq!(runs.get(), 1); + eframe::App::on_exit(&mut app); + assert_eq!(runs.get(), 1, "a second exit must not run the hook again"); + println!("exit hook ran once"); + return; + } + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "tests::leaving_runs_the_exit_hook_once", "--nocapture"]) + .env("DECKCRAFT_TEST_EXIT_HOOK", "1") + .env("DECKCRAFT_NO_PREFS", "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!(out.status.success(), "{stdout}"); + assert!(stdout.contains("exit hook ran once"), "the child didn't run the test: {stdout}"); + } + #[test] fn finder_process_serial_number_is_not_a_file() { let launch = startup(None, ["-psn_0_1234567".to_string(), "talk.pptx".to_string()]); diff --git a/apps/deckcraft/src/nightly_session.rs b/apps/deckcraft/src/nightly_session.rs new file mode 100644 index 000000000..6f1b80b93 --- /dev/null +++ b/apps/deckcraft/src/nightly_session.rs @@ -0,0 +1,277 @@ +//! App-private Nightly session health, not telemetry or a Launcher protocol. +//! A live owner holds a separate persistent lease; secondary launches never rewrite its record. +//! Dropping the guard does not clear the marker. Only the app's controlled return path does. + +use std::fs::{File, OpenOptions}; +use std::io::{self, Read, Write}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, PoisonError}; + +const RECORD: &str = "nightly-session.json"; +const LEASE: &str = "nightly-session.lock"; +const MAX_METADATA_BYTES: usize = 256; + +pub struct Session { + _lease: File, + path: PathBuf, + own_record: Vec, + previous_unclean: bool, +} + +fn regular_or_missing(path: &Path) -> io::Result { + match std::fs::symlink_metadata(path) { + Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true), + Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error), + } +} + +/// Write `bytes` to `path` through a new file in the same directory, then rename it into place. +/// The rename replaces a symlink rather than following it, so a raced alias never reaches another +/// file; the created file is mode 0600 and is synced before the rename. +fn atomic_write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> { + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT: AtomicU64 = AtomicU64::new(0); + let directory = path.parent().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "the session record has no directory"))?; + let name = path.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "the session record has no file name"))?; + let temporary = directory.join(format!(".{}.{}.{}.tmp", name.to_string_lossy(), std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt as _; + options.mode(0o600); + } + let mut file = options.open(&temporary)?; + let written = file.write_all(bytes).and_then(|()| file.sync_all()); + drop(file); + if let Err(error) = written { + let _ = std::fs::remove_file(&temporary); + return Err(error); + } + match std::fs::rename(&temporary, path) { + Ok(()) => Ok(()), + Err(error) => { + let _ = std::fs::remove_file(&temporary); + Err(error) + } + } +} + +/// The owner's session, shared by the app's exit hook (macOS) and the code after the event loop. +/// On macOS every quit ends the process inside AppKit's terminate, after eframe's `on_exit` and +/// before `eframe::run_native` could return, so the exit hook finishes it there; the return path +/// still runs for a start that created no window. +pub type Shared = Arc>>; + +/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing. +pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) { + let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take(); + if let Some(watch) = watch + && let Err(error) = watch.finish(unclean_notice_shown) + { + log::warn!("Nightly session state was left intact: {error}"); + } +} + +impl Session { + /// The warning belongs to this window: a busy secondary has no health-record coverage, + /// while Stable and a lease-owning Nightly window preserve their existing result. + pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option, bool)> { + let watch = Self::begin(root, version, commit)?; + let unavailable = root.is_some() && watch.is_none(); + Ok((watch, unavailable)) + } + + /// `None` is stable or another owner of this profile. Neither case touches the record. + /// The supplied root must already be the validated private Nightly profile. + pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result> { + let Some(root) = root else { return Ok(None) }; + if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large")); + } + let lease_path = root.join(LEASE); + regular_or_missing(&lease_path)?; + let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?; + match lease.try_lock() { + Ok(()) => {} + Err(std::fs::TryLockError::WouldBlock) => return Ok(None), + Err(std::fs::TryLockError::Error(error)) => return Err(error), + } + let path = root.join(RECORD); + let previous_unclean = regular_or_missing(&path)?; + let own_record = serde_json::to_vec(&serde_json::json!({ + "schema_version": 1, + "channel": "nightly-v1", + "version": version, + "commit": commit.filter(|value| !value.is_empty()), + }))?; + atomic_write_no_follow(&path, &own_record)?; + Ok(Some(Self { _lease: lease, path, own_record, previous_unclean })) + } + + pub fn previous_unclean(&self) -> bool { + self.previous_unclean + } + + /// Controlled return. If an earlier session's interruption was detected but no window showed + /// it yet (a renderer failure before the app callback), the record is left for the next owner + /// to report; otherwise this is [`Self::complete`]. + pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> { + if self.previous_unclean && !unclean_notice_shown { + return Ok(()); + } + self.complete() + } + + /// Controlled event-loop completion includes a handled startup error, not only exit 0. + /// An unwind, abort, forced exit or killed process never calls this method. + pub fn complete(self) -> io::Result<()> { + if !regular_or_missing(&self.path)? { + return Ok(()); + } + let mut current = Vec::new(); + File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?; + if current != self.own_record { + return Err(io::Error::other("Nightly session state changed; leaving it intact")); + } + std::fs::remove_file(&self.path) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + + struct Fixture(PathBuf); + impl Fixture { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + loop { + let path = + std::env::temp_dir().join(format!("deckcraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + match std::fs::create_dir(&path) { + Ok(()) => return Self(path), + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("cannot create owned fixture: {error}"), + } + } + } + } + impl Drop for Fixture { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).unwrap(); + } + } + + #[test] + fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() { + let fixture = Fixture::new(); + let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap(); + assert!(stable.is_none() && !warning); + let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap(); + assert!(!warning); + let first = first.unwrap(); + let record = std::fs::read(fixture.0.join(RECORD)).unwrap(); + let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap(); + assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage"); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record); + first.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() { + let fixture = Fixture::new(); + let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap(); + assert!(!first.previous_unclean()); + let own = std::fs::read(fixture.0.join(RECORD)).unwrap(); + assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none()); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record"); + first.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + let unfinished = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap(); + assert!(!unfinished.previous_unclean()); + drop(unfinished); // Unwind/abnormal-path ownership release, not a controlled completion. + let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap(); + assert!(next.previous_unclean()); + next.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn an_interruption_no_window_showed_survives_a_handled_startup_failure() { + let fixture = Fixture::new(); + drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap()); + // Renderer initialization failed before the app callback: no notice was shown. + let failed = Session::begin(Some(&fixture.0), "gpu-failed", None).unwrap().unwrap(); + assert!(failed.previous_unclean()); + failed.finish(false).unwrap(); + // The next start still sees the interruption and shows it. + let retry = Session::begin(Some(&fixture.0), "next", None).unwrap().unwrap(); + assert!(retry.previous_unclean()); + retry.finish(true).unwrap(); + assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record"); + // Without an earlier interruption, a handled failure still clears normally. + let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap(); + assert!(!clean.previous_unclean()); + clean.finish(false).unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn the_exit_hook_and_the_return_path_finish_the_session_once() { + let fixture = Fixture::new(); + let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap())); + // The exit hook (macOS quit: the only path that runs there). + finish_once(&shared, false); + assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit"); + // Elsewhere the return path runs too, by then possibly after a successor took the profile. + let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap(); + assert!(!successor.previous_unclean()); + let record = std::fs::read(fixture.0.join(RECORD)).unwrap(); + finish_once(&shared, false); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record"); + successor.complete().unwrap(); + } + + #[test] + fn cleanup_never_removes_an_unknown_changed_record() { + let fixture = Fixture::new(); + let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap(); + std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap(); + assert!(watch.complete().is_err()); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else"); + } + + #[test] + fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() { + let fixture = Fixture::new(); + assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err()); + assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0); + assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects"); + let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap(); + let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap(); + let fields = data.as_object().unwrap().keys().map(String::as_str).collect::>(); + assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect()); + assert!(data["commit"].is_null(), "missing provenance must not be invented"); + watch.complete().unwrap(); + } + + #[test] + #[cfg(unix)] + fn reserved_state_aliases_do_not_modify_external_files() { + let fixture = Fixture::new(); + let external = fixture.0.join("stable-document"); + std::fs::write(&external, b"stable bytes").unwrap(); + for name in [LEASE, RECORD] { + let alias = fixture.0.join(name); + std::os::unix::fs::symlink(&external, &alias).unwrap(); + assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err()); + assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes"); + std::fs::remove_file(alias).unwrap(); + } + } +} diff --git a/apps/deckcraft/src/process_identity.rs b/apps/deckcraft/src/process_identity.rs new file mode 100644 index 000000000..9d2e1c179 --- /dev/null +++ b/apps/deckcraft/src/process_identity.rs @@ -0,0 +1,70 @@ +//! Set the immutable nightly Windows identity before any native window or COM service. +//! Stable deliberately leaves its implicit shortcut/path identity unchanged. + +use std::sync::OnceLock; + +#[derive(Clone, Debug, thiserror::Error)] +pub enum IdentityError { + #[error("{0}")] + Configuration(String), +} + +pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> { + configure(nightly && cfg!(windows), app_id, |id| { + static RESULT: OnceLock> = OnceLock::new(); + RESULT + .get_or_init(|| { + #[cfg(windows)] + { + winsafe::SetCurrentProcessExplicitAppUserModelID(id) + .map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?; + let actual = winsafe::GetCurrentProcessExplicitAppUserModelID() + .map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?; + if actual != id { + return Err("the native Windows identity did not match the selected nightly channel".into()); + } + Ok(()) + } + #[cfg(not(windows))] + { + let _ = id; + Ok(()) + } + }) + .clone() + }) + .map_err(IdentityError::Configuration) +} + +fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> { + if explicit_nightly { set(app_id) } else { Ok(()) } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn stable_does_not_call_the_explicit_identity_api() { + configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap(); + } + + #[test] + fn nightly_applies_the_supplied_identity_once() { + let calls = std::cell::Cell::new(0); + configure(true, "nightly-id", |id| { + assert_eq!(id, "nightly-id"); + calls.set(calls.get() + 1); + Ok(()) + }) + .unwrap(); + assert_eq!(calls.get(), 1); + } + + #[test] + fn native_identity_failure_is_returned_instead_of_starting_a_window() { + let started = std::cell::Cell::new(false); + let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true)); + assert_eq!(result.unwrap_err(), "native identity refused"); + assert!(!started.get()); + } +} diff --git a/apps/deckcraft/src/profile_root.rs b/apps/deckcraft/src/profile_root.rs new file mode 100644 index 000000000..a7e9b3bfc --- /dev/null +++ b/apps/deckcraft/src/profile_root.rs @@ -0,0 +1,622 @@ +//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. + +use std::ffi::OsString; + +use crate::app_dirs::{PORTABLE_DATA_DIR, portable_marker}; +use std::path::{Component, Path, PathBuf}; + +/// The DeckCraft Nightly Flatpak app id (`packaging/linux/flatpak-bundle.sh`), the one Flatpak +/// instance a Nightly profile may inherit. +pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.deckcraft.nightly"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Platform { + Windows, + Linux, + Mac, +} + +impl Platform { + fn current() -> Result { + match std::env::consts::OS { + "windows" => Ok(Self::Windows), + "linux" => Ok(Self::Linux), + "macos" => Ok(Self::Mac), + _ => Err("nightly-v1 is not defined for this operating system".into()), + } + } + + fn ignores_case(self) -> bool { + self != Self::Linux + } +} + +fn absolute(path: PathBuf, label: &str) -> Result { + if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) { + return Err(format!("{label} must be absolute and contain no parent traversal")); + } + Ok(path) +} + +fn required_base(env: &impl Fn(&str) -> Option, key: &str) -> Result { + let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?; + absolute(PathBuf::from(value), key) +} + +fn xdg_base(env: &impl Fn(&str) -> Option, key: &str, fallback: &str) -> Result { + match env(key).filter(|v| !v.is_empty()) { + Some(value) => absolute(PathBuf::from(value), key), + None => Ok(required_base(env, "HOME")?.join(fallback)), + } +} + +/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor +/// is not a missing directory that may be replaced or followed later. +fn canonical_future(path: &Path) -> Result { + let mut parent = path; + let mut missing = Vec::new(); + loop { + match std::fs::symlink_metadata(parent) { + Ok(_) => break, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string()); + parent = parent.parent().ok_or("the profile root has no existing ancestor")?; + } + Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")), + } + } + let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?; + for part in missing.into_iter().rev() { + resolved.push(part); + } + Ok(resolved) +} + +fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool { + let parts = |p: &Path| { + p.components() + .map(|c| { + let value = c.as_os_str().to_string_lossy().into_owned(); + if platform.ignores_case() { value.to_lowercase() } else { value } + }) + .collect::>() + }; + let (a, b) = (parts(a), parts(b)); + a.starts_with(&b) || b.starts_with(&a) +} + +fn installation_boundary(platform: Platform, exe: &Path) -> Result { + let parent = exe.parent().ok_or("cannot establish the installation boundary")?; + if platform == Platform::Mac { + // A profile in Resources is still inside the versioned install, not beside MacOS. + if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) { + return Ok(bundle.to_path_buf()); + } + } + Ok(parent.to_path_buf()) +} + +fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, exe: &Path) -> Result, String> { + let mut roots = match platform { + Platform::Windows => { + let mut roots = ["APPDATA", "LOCALAPPDATA"] + .into_iter() + .map(|key| required_base(env, key).map(|p| p.join("DeckCraft"))) + .collect::, _>>()?; + // The MSI's default per-user and per-machine folders (install-policy.wxi). A custom + // install folder is not known here; the executable's own folder is fenced below. + roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("DeckCraft")); + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + if let Some(base) = env(key).filter(|v| !v.is_empty()) { + roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("DeckCraft")); + } + } + roots + } + Platform::Linux => { + let mut roots = + [("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")] + .into_iter() + .map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("deckcraft"))) + .collect::, _>>()?; + roots.extend(["/usr/bin/deckcraft", "/usr/local/bin/deckcraft", "/opt/deckcraft"].map(PathBuf::from)); + // The stable Flatpak keeps its data in its own per-app folder. + roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.deckcraft")); + roots + } + Platform::Mac => { + let home = required_base(env, "HOME")?; + let library = home.join("Library"); + vec![ + library.join("Application Support/DeckCraft"), + library.join("Caches/DeckCraft"), + library.join("Caches/ai.storyteller.deckcraft"), + library.join("Preferences/DeckCraft"), + library.join("Preferences/ai.storyteller.deckcraft.plist"), + library.join("Saved Application State/ai.storyteller.deckcraft.savedState"), + home.join("Applications/DeckCraft.app"), + PathBuf::from("/Applications/DeckCraft.app"), + ] + } + }; + roots.push(installation_boundary(platform, exe)?); + roots.into_iter().map(|p| canonical_future(&p)).collect() +} + +fn private_subdirectory(root: &Path, name: impl AsRef, label: &str) -> Result { + let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?; + let child = canonical_future(&chosen.join(name))?; + if child == chosen || !child.starts_with(&chosen) { + return Err(format!("the nightly {label} must stay inside its selected profile")); + } + Ok(child) +} + +/// Every existing entry directly in the profile (Dictionaries, logs, settings and so on) must +/// resolve inside it, so a link there cannot point Nightly's writes at another app's data. +fn entries_stay_inside(root: &Path) -> Result<(), String> { + let entries = match std::fs::read_dir(root) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")), + }; + for entry in entries { + let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; + private_subdirectory(root, entry.file_name(), "profile entry")?; + } + // The one nested file Nightly writes itself: a link at Dictionaries/user.dic would append + // "add to dictionary" words to the stable app's file instead of this profile's. + private_subdirectory(root, std::path::Path::new("Dictionaries").join("user.dic"), "user dictionary")?; + Ok(()) +} + +/// Recognise a portable data namespace in both the supplied and resolved path. DeckCraft ships no +/// portable package, so this only refuses a hand-made copy; it is not an inventory of arbitrary +/// custom Stable overrides or a Launcher ownership proof. +fn is_portable_layout(path: &Path, platform: Platform) -> bool { + // Above the chosen folder itself, a marker only counts beside a DeckCraft executable, so an + // unrelated portable.txt higher up (in a user folder or at a drive root) does not refuse it. + path.ancestors().enumerate().any(|(depth, ancestor)| { + portable_marker(ancestor).is_some() && (depth == 0 || ["deckcraft.exe", "deckcraft"].iter().any(|exe| ancestor.join(exe).is_file())) + }) || path.components().any(|component| match component { + Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR), + Component::Normal(name) => name == PORTABLE_DATA_DIR, + _ => false, + }) +} + +/// The writable hook is the app's existing exclusive probe. Keeping it injected lets filesystem +/// boundary tests exercise the real policy without starting the app or changing global state. +pub fn validate( + root: &Path, + env: impl Fn(&str) -> Option, + exe: Option<&Path>, + writable: impl FnOnce(&Path) -> std::io::Result<()>, +) -> Result { + validate_for(Platform::current()?, root, env, exe, writable) +} + +fn validate_for( + platform: Platform, + root: &Path, + env: impl Fn(&str) -> Option, + exe: Option<&Path>, + writable: impl FnOnce(&Path) -> std::io::Result<()>, +) -> Result { + absolute(root.to_path_buf(), "the nightly profile root")?; + if let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty()) { + // The native tar and app-bundle rows are not Flatpak packages: inheriting a Flatpak + // runtime could point another profile at the stable app's data. DeckCraft Nightly's own + // Flatpak (packaging/linux/flatpak-bundle.sh) is the one allowed instance, matched by its + // exact id; the stable id and any other app are refused. + if platform == Platform::Windows || id != NIGHTLY_FLATPAK_ID { + return Err("nightly-v1 accepts only the DeckCraft Nightly Flatpak instance; launch through the native Launcher".into()); + } + } + let chosen = canonical_future(root)?; + if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) { + return Err("the nightly root must not use a portable DeckCraft copy or its DeckCraftData settings folder".into()); + } + let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?; + let forbidden = forbidden_roots(platform, &env, &exe)?; + if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) { + return Err("the nightly root must not overlap stable data or an installation".into()); + } + entries_stay_inside(&chosen)?; + // Recovery can read, adopt, overwrite and sweep entries. Never let its alias leave this + // private profile, including toward a Stable portable directory not in our known roots. + private_subdirectory(&chosen, "Recovery", "recovery folder")?; + private_subdirectory(&chosen, "Dictionaries", "dictionary folder")?; + let mut create = std::fs::DirBuilder::new(); + create.recursive(true); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt as _; + create.mode(0o700); + } + create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?; + let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?; + if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) { + return Err("the nightly profile changed while it was being validated".into()); + } + private_subdirectory(&confirmed, "Recovery", "recovery folder")?; + private_subdirectory(&confirmed, "Dictionaries", "dictionary folder")?; + entries_stay_inside(&confirmed)?; + writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?; + Ok(confirmed) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeMap; + use std::sync::atomic::{AtomicU64, Ordering}; + + struct Fixture { + root: PathBuf, + env: BTreeMap, + exe: PathBuf, + } + + impl Fixture { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let root = loop { + let candidate = + std::env::temp_dir().join(format!("deckcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + match std::fs::create_dir(&candidate) { + Ok(()) => break std::fs::canonicalize(candidate).unwrap(), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("cannot create owned fixture: {error}"), + } + }; + let home = root.join("home"); + let exe = root.join("install/deckcraft"); + std::fs::create_dir_all(&home).unwrap(); + std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); + std::fs::write(&exe, b"fixture executable, never run").unwrap(); + let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))] + .into_iter() + .map(|(key, value)| (key.into(), value.into_os_string())) + .collect(); + Self { root, env, exe } + } + + fn get(&self, key: &str) -> Option { + self.env.get(key).cloned() + } + + fn check(&self, platform: Platform, root: &Path) -> Result { + validate_for( + platform, + root, + |key| self.get(key), + Some(&self.exe), + |dir| { + let probe = dir.join("exclusive-test-probe"); + let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?; + drop(file); + std::fs::remove_file(probe) + }, + ) + } + + fn home(&self) -> PathBuf { + PathBuf::from(self.get("HOME").unwrap()) + } + } + + impl Drop for Fixture { + fn drop(&mut self) { + // Only the directory successfully created by this fixture is owned for removal. + std::fs::remove_dir_all(&self.root).unwrap(); + } + } + + #[test] + fn portable_settings_from_another_install_are_refused_before_any_probe() { + let fixture = Fixture::new(); + let stable_install = fixture.root.join("stable portable install"); + let stable_data = stable_install.join(PORTABLE_DATA_DIR); + std::fs::create_dir_all(&stable_data).unwrap(); + std::fs::write(stable_install.join("portable.txt"), b"owned portable fixture").unwrap(); + std::fs::write(stable_data.join("settings.json"), b"stable settings must not change").unwrap(); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + for candidate in [&stable_data, &stable_data.join("nested nightly")] { + let probed = std::cell::Cell::new(false); + let result = validate_for( + platform, + candidate, + |key| fixture.get(key), + Some(&fixture.exe), + |_| { + probed.set(true); + Ok(()) + }, + ); + assert!(result.is_err(), "a different portable install is not a private Nightly profile"); + assert!(!probed.get(), "reject portable data before a writable probe"); + assert!(!stable_data.join("nested nightly").exists()); + assert_eq!(std::fs::read(stable_data.join("settings.json")).unwrap(), b"stable settings must not change"); + } + } + let private = fixture.root.join("DeckCraftData-backup-name/nightly"); + assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component"); + } + + #[cfg(unix)] + #[test] + fn recovery_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() { + let fixture = Fixture::new(); + let stable = fixture.home().join(".local/share/deckcraft/recovery"); + std::fs::create_dir_all(&stable).unwrap(); + std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap(); + for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() { + let private = fixture.root.join(format!("nightly-{index}")); + std::fs::create_dir(&private).unwrap(); + std::os::unix::fs::symlink(&target, private.join("Recovery")).unwrap(); + let probed = std::cell::Cell::new(false); + let result = validate_for( + Platform::Linux, + &private, + |key| fixture.get(key), + Some(&fixture.exe), + |_| { + probed.set(true); + Ok(()) + }, + ); + assert!(result.is_err(), "Recovery must not escape the private profile or follow a dangling alias"); + assert!(!probed.get()); + } + let private = fixture.root.join("nightly-self"); + std::fs::create_dir(&private).unwrap(); + std::os::unix::fs::symlink(&private, private.join("Recovery")).unwrap(); + assert!(fixture.check(Platform::Linux, &private).is_err(), "Recovery cannot treat all profile settings as recovery entries"); + assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes"); + } + + #[cfg(unix)] + #[test] + fn recovery_alias_to_a_private_subfolder_keeps_the_profile_usable() { + let fixture = Fixture::new(); + let private = fixture.root.join("nightly-private"); + let recovery = private.join("private-recovery"); + std::fs::create_dir_all(&recovery).unwrap(); + std::os::unix::fs::symlink(&recovery, private.join("Recovery")).unwrap(); + assert!(fixture.check(Platform::Linux, &private).is_ok()); + assert_eq!(std::fs::canonicalize(private.join("Recovery")).unwrap(), recovery); + } + + /// The public entry point reads the host platform and refuses a relative root before probing. + #[cfg(target_os = "linux")] + #[test] + fn the_public_validator_uses_the_host_platform_and_creates_only_the_profile() { + let fixture = Fixture::new(); + let root = fixture.home().join("nightly/profiles/deckcraft"); + let created = validate(&root, |key| fixture.get(key), Some(&fixture.exe), crate::app_dirs::ensure_writable) + .expect("a private profile under HOME is valid on Linux"); + assert_eq!(created, root); + assert!(created.is_dir()); + let probed = std::cell::Cell::new(false); + let refused = validate( + Path::new("relative/profile"), + |key| fixture.get(key), + Some(&fixture.exe), + |_| { + probed.set(true); + Ok(()) + }, + ); + assert!(refused.is_err()); + assert!(!probed.get(), "a relative root is refused before the write probe"); + } + + #[test] + fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() { + let fixture = Fixture::new(); + let root = fixture.home().join("nightly/profiles/deckcraft"); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + assert!(overlaps(&root, &root.join("Recovery"), platform)); + assert!(overlaps(&root.join("Recovery"), &root, platform)); + assert!(!overlaps(&root, &root.with_file_name("deckcraft-other"), platform)); + } + } + + #[test] + fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() { + let mut fixture = Fixture::new(); + for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] { + fixture.env.insert(key.into(), fixture.root.join(key).into_os_string()); + } + for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] { + let stable = PathBuf::from(fixture.get(key).unwrap()).join("deckcraft"); + std::fs::create_dir_all(&stable).unwrap(); + std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap(); + for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] { + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap")); + } + assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes"); + } + let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap()); + let nightly = data.join("ArtCraftLauncher/nightly/profiles/deckcraft"); + assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly); + assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0); + } + + #[test] + fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() { + let mut fixture = Fixture::new(); + fixture.exe = fixture.root.join("install/DeckCraft Nightly.app/Contents/MacOS/DeckCraft"); + std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap(); + std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap(); + let library = fixture.home().join("Library"); + for suffix in [ + "Application Support/DeckCraft", + "Caches/DeckCraft", + "Caches/ai.storyteller.deckcraft", + "Preferences/DeckCraft", + "Saved Application State/ai.storyteller.deckcraft.savedState", + ] { + let stable = library.join(suffix); + assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap")); + assert!(!stable.exists()); + } + let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile"); + assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap")); + assert!(!inside_resources.exists()); + let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/deckcraft"); + assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid); + } + + #[test] + fn windows_roaming_local_and_install_fences_remain_active() { + let fixture = Fixture::new(); + for key in ["APPDATA", "LOCALAPPDATA"] { + let stable = PathBuf::from(fixture.get(key).unwrap()).join("DeckCraft"); + assert!(fixture.check(Platform::Windows, &stable.join("nightly")).unwrap_err().contains("overlap")); + assert!(!stable.exists()); + } + assert!(fixture.check(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_err()); + assert!(fixture.check(Platform::Windows, &fixture.root.join("Launcher/profiles/deckcraft")).is_ok()); + } + + #[test] + fn windows_default_msi_install_folders_are_fenced() { + let mut fixture = Fixture::new(); + let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()); + let per_user = local.join("Programs").join("ArtCraft").join("DeckCraft"); + assert!(fixture.check(Platform::Windows, &per_user.join("nightly")).unwrap_err().contains("overlap")); + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + let base = fixture.root.join(format!("machine {key}")); + fixture.env.insert(key.into(), base.clone().into_os_string()); + let machine = base.join("ArtCraft").join("DeckCraft"); + assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap")); + assert!(!machine.exists()); + } + let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("deckcraft"); + assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not DeckCraft's install"); + } + + #[test] + fn folders_under_a_stable_portable_copy_are_refused_before_any_probe() { + let fixture = Fixture::new(); + let portable = fixture.root.join("D/DC"); + std::fs::create_dir_all(&portable).unwrap(); + std::fs::write(portable.join("portable.txt"), b"stable portable copy").unwrap(); + std::fs::write(portable.join("deckcraft.exe"), b"stable portable executable, never run").unwrap(); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + for candidate in [portable.join("nightly"), portable.join("deeper/nightly")] { + let probed = std::cell::Cell::new(false); + let result = validate_for( + platform, + &candidate, + |key| fixture.get(key), + Some(&fixture.exe), + |_| { + probed.set(true); + Ok(()) + }, + ); + assert!(result.unwrap_err().contains("portable")); + assert!(!probed.get()); + assert!(!candidate.exists()); + } + } + // A portable.txt that no DeckCraft executable sits beside is someone else's file. + let unrelated = fixture.root.join("user folder"); + std::fs::create_dir_all(&unrelated).unwrap(); + std::fs::write(unrelated.join("portable.txt"), b"another app's marker").unwrap(); + assert!(fixture.check(Platform::Windows, &unrelated.join("Launcher/nightly/deckcraft")).is_ok()); + } + + #[test] + fn linux_fences_the_stable_flatpak_data_folder() { + let fixture = Fixture::new(); + let flatpak = fixture.home().join(".var/app/ai.storyteller.deckcraft"); + for candidate in [flatpak.clone(), flatpak.join("data/nightly")] { + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap")); + } + assert!(!flatpak.exists()); + assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok()); + } + + #[cfg(unix)] + #[test] + fn any_profile_entry_alias_must_stay_inside_the_profile() { + let fixture = Fixture::new(); + let stable = fixture.home().join(".config/deckcraft/logs"); + std::fs::create_dir_all(&stable).unwrap(); + std::fs::write(stable.join("stable-log"), b"stable log bytes").unwrap(); + for name in ["Dictionaries", "logs", "ui.json"] { + let private = fixture.root.join(format!("nightly-{name}")); + std::fs::create_dir(&private).unwrap(); + std::os::unix::fs::symlink(&stable, private.join(name)).unwrap(); + let probed = std::cell::Cell::new(false); + let result = validate_for( + Platform::Linux, + &private, + |key| fixture.get(key), + Some(&fixture.exe), + |_| { + probed.set(true); + Ok(()) + }, + ); + assert!(result.is_err(), "{name} must not lead outside the profile"); + assert!(!probed.get()); + } + let private = fixture.root.join("nightly-inside"); + std::fs::create_dir_all(private.join("real-dictionaries")).unwrap(); + std::fs::write(private.join("ui.json"), b"{}").unwrap(); + std::os::unix::fs::symlink(private.join("real-dictionaries"), private.join("Dictionaries")).unwrap(); + assert!(fixture.check(Platform::Linux, &private).is_ok(), "regular files and links that stay inside are fine"); + assert_eq!(std::fs::read(stable.join("stable-log")).unwrap(), b"stable log bytes"); + } + + #[test] + fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() { + let mut fixture = Fixture::new(); + let candidate = fixture.home().join("nightly/profiles/deckcraft"); + fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into()); + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute")); + fixture.env.remove("XDG_CACHE_HOME"); + // The stable Flatpak instance, or any other app's, is not a Nightly launch. + fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.deckcraft".into()); + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak")); + fixture.env.insert("FLATPAK_ID".into(), "org.example.other".into()); + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak")); + // DeckCraft Nightly's own Flatpak is the one allowed instance. + fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into()); + assert!(fixture.check(Platform::Linux, &candidate).is_ok()); + fixture.env.remove("FLATPAK_ID"); + fixture.env.remove("HOME"); + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME")); + } + + #[test] + fn non_directory_and_failed_write_probe_never_fall_back_to_stable() { + let fixture = Fixture::new(); + let file = fixture.home().join("not-a-directory"); + std::fs::write(&file, b"regular file").unwrap(); + assert!(fixture.check(Platform::Linux, &file.join("nightly")).is_err()); + let candidate = fixture.home().join("nightly/profiles/deckcraft"); + let result = validate_for( + Platform::Linux, + &candidate, + |key| fixture.get(key), + Some(&fixture.exe), + |_| Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "read-only")), + ); + assert!(result.unwrap_err().contains("not writable")); + assert!(!candidate.join("Recovery").exists(), "a failed probe leaves no stable fallback behind"); + } + + #[test] + fn relative_roots_and_parent_traversal_are_refused() { + let fixture = Fixture::new(); + for candidate in [PathBuf::from("relative/nightly"), fixture.home().join("nightly/../escape")] { + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute")); + } + } +} diff --git a/assets/app-icon/deckcraft-nightly-1024.png b/assets/app-icon/deckcraft-nightly-1024.png new file mode 100644 index 0000000000000000000000000000000000000000..f6ab7e29471c2d7e427713cac83801806cfcc3dd GIT binary patch literal 22205 zcmeIa2UJtr)<3%GB27gNh=7G+r5r$z0KqOw@u){YszyNtK?Fi4(PN`~KGfqmZ21dsQA|9ju~kMX@R-XLzX*P3h2->hrxWUT}oF+L!& zbj?x-f^Cj_0iX0UhHanCQb7Li~p_n0Xcv(GK=JG+h1 z7js_(=|`SeDt~-a@f+?)p9g%r8{A(nJLtLm@rSe}c~&MTH4J-!K_8*t_LJ~<)tfS3K#N%q?|9QlH-+vzc|vwKu7>0I-wru^>2 zS^6v2Zi*985*w^qD)Ikc{!1IA9gWx?(}-@USHotctD@n0>?mH>CHZb*BHAP4li3}( zua;?dxkq0u|2KHDzRT%7%;=xS<4l-?vhQGqc)tB8o}>y_TT@_0mnA>+kOoA#Ynj9HEjG^zsLll;sD zzw;2KNO{;Yxo4U8P>psY*RR;kB+#$pE;8F^!_V?T-%soz9(t86+^;k(Do(7dF^(AA zk=fBO2K@iAkAUy%@e!UFr^Us^k+c${Eb^aaq?g-lN~*s2QXhg=y>LHQACO@GT{>`D z^v>Y!Oz{$@mFRGz4-#0z^NM(vCVWP^%L!&XZagQquEb&xKF0+?o)ISsHsew;gN8ky z_MnfyI^4J^M77k7>M>zjX?Ww+6Y8O;?tw~1Y0yrHtaS4V)v@VWWZCmo=%}hXz_wd- z);wpnYP8Hm)=`5p;H+R%uA4~GXOsu2L;7EtD~YBw+svR61|Ezd@G>jk(}az+=~KZ7W~1gY40PbG_ihXg{Uq~Sg{D= zhCa4NWJ;BWo;$XqG&rM!2NW5pIN|nTV1WVT{Tntt{t2LJ1 zFep0`H(Ab8H5NBrMbEXafgp)As%U@sw6P>HRisG*ThLoWYIo+JU8C5g*<&#qS6*TL z0uZHo@E5K{+tFe(UB48DsM-a0eU4BtS?j35)CEyjE3^`V_{s=2r2~@ahepj3SZ(z` z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sm<=LtgzQpv@xi~^z}D3==k-SzDlx|8!%B`Q!Srut-}Rv!Q#FOM^P@j zr1det)2VS@c*?i!yiTMIpq%XUUZ20Q=r&z}F>0jz6r{>8W zZh~OD(S@RDyL1I)o5WwKHQz+p>#`$IEj;3Hx$}jqd2_8slUn*wbkp2(OpnVB-uLK9 zW9?I-cIH~d6g9*6v#TlUJ&xk`YZY}3!cSzaYw+kPaB^sW z@AM>JgE9JLtlFyQI?iLH zW?BbNT9=uu87R{hPLn?0tclU$!3j`VLGv51rx9!#c2UPiM ALI3~& literal 0 HcmV?d00001 diff --git a/assets/app-icon/deckcraft-nightly.icns b/assets/app-icon/deckcraft-nightly.icns new file mode 100644 index 0000000000000000000000000000000000000000..6a37040c3ea446d27a28a7ac19563e7253124e42 GIT binary patch literal 50041 zcmeFa2Ut_j(m1>cNRg^2y;;FR6Oj^u*cB15f^-2vdJzIhNw6azDx!3-P*e~Qkxqir zyYwCe1cA_z8gjl3`YZ2!?|uLG|9$s)z6KAFJ-airvoo`^vuEd=SerXs2jGjRwYk%N z08mc;I$9?<)(fr&0C1c-dGs9o`AGn9VP5K_!SwqbIS;&C=_9JKFhx_o34t)s^(AQI}2u>Z-I{N;w=}jna1pv@2|3u#6 z5KMek-q&y3n1%8#`$OLRcBbJx!JD|V7^XIh(@@38u445#OTX%;TP-{{apPa!jL()W zr$~A~Ltef3E=%S5vZ3A-Im%r1_{ib)?WnQx^*aq_sCCW#i?Odxi?Huwv)CE2t>dwX z)4IzIdPY;o>@HQr>dfe?^-SUG_VLu9bRUTjo^%*R3Dbyp&wFqAEq2}*$KptMJ5CRe zWh&C~cH_&*PiOX=bR*$!a%Q`IXAC>T&a_UU`h$GgJhiS?b5Z?8;!h-xFRQ{GoLv|x zM8vG(Z%*A4;VCl9Rp~%-ay&^MG)l!sH`2ZHwlsX@vvuZ=wqea08XBCKXK@PWTT!FB zGKX1lcAR>jt_|Y19l3>kd*O$~cI6#4VkYdpv&i{$Ax)WJ>SeCo zDG)8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0WGYa(><_jCuId z0^2%74GjJ?a^|JzlG_+dhXNDZZGY4G*sU#oQAwcl0h3QUy>g75^J>Y5u-7HGGnPAg z+}&N9-w+h%)BeDZl76tQM> z(=@j#iwC~`6zk~%W?uQs({70eyLN5xa(W9dcW@cx)x&NIw z(-G{KDf@my@PFIL7qnjQcEQgly&XqZT1(a+&*N`7Z;pT3u9YVyh9oktEo#`A|8^ui zpuzjE#SRuf@pJL28$OK=zIb^3tb8#p7L7j6-um|8cdOWrKesTu9{cU>2mmui1`b@BY8MI-z}rsk_tv-SFjh9_rD z>hw?E__!aFEh?-m?>cD78@G+Au1)XLVZLA*#D| zw}{$@{yY2P_646URbi0)dlC5{*$D>8qs|_3e>d5=SW~}(cRk~Wp9yo{c)xv2HT$xU zI=#vN@%r&WqlcZn9@ci#x~O_hudUt_zSd89=nfA-(_r literal 0 HcmV?d00001 diff --git a/assets/app-icon/deckcraft-nightly.png b/assets/app-icon/deckcraft-nightly.png new file mode 100644 index 0000000000000000000000000000000000000000..10dabf61858f57aa20e0834e6f6c28a799f97710 GIT binary patch literal 3208 zcmd5;cT|(f7N3L&3DOn>q!$&GB1%<23B4BqVUc141Vp8|23J4=DlHx%b?e`Q1Ce@5bBNm~wN9 zasmLj&CQJL0f0dw3?SK|!7ZfN2LLWxb0dAnTVLi!$awcDiFeCajgYq&PZjGQ%ovmV z9AJ{AfVBU$Axep#uj^jvittZQ?W&KKz)ngp6lO;qPsk23?J-6@^_aF0HV{(d`k~rP zyYp$ComkHZ*QefZ*{7okq1RM5a>DX%EY9u^OwOQ4kvDZ0!#=F)emkA}(B9(M^GE;P zIkpk7Aqz|SqdI3#eR8*PvnrK~iBD|FZNbt!JhjeY3Wtn^D z(&t!VG|D@$d6-cI6>1-~FWhghmfR^G*jQ{@GxD#ki64gFJ0?>du323c%QTDVS!_%Z z^>@ddcwTDS_I-_+Ss#fl&k5ZzF*`A3)aHC>_4Y26u1Ck+%jF!@zm3K&H1cwA&Wx;ebgF4e#5NCWQo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7!8h-AYh)IaF)|G+CNu1*+Wr#;KX;lXk-I#9l|5$w!?!6{Lij{gJAKo6_PAh(3 zf<#mqI>>;oWLGmT?khwUVU=@yl?< zDo2Vtych@39f2yl-_hDzGqy=h5Kf=|9iS^atYh>6^PH0;JG%wl+laghu4?q8$fi+#;E$McuNC&=!r~apHoX7jVIM8L!LU zJ^f&voCEAeA_N=CE^6FQ!K$-VzP8j7=G6LrmQp5?n=4S>+D-IPK07Gtb;CF;YVK4T~2%Ipt&wFN7 zoG_)UEHf9$i(rQu%rcZIS$wFBBc$Gl?Zwag*}>5-2jiQDOA31MBcJmj-@!Ew=bsC^ zeqza0_L-m`s!K#4fsc{}WG6Y?c;=>Yq6P5dZSGyg=PD>RP8Y@;0kzTHHhpOxYt?&l zrv@^={?|(=a6P}?u>mAp{YF#5SWfVRY9HtirJUxmoxm;!yt~tE+%={*9u{id%1=Q7 zmlbJ-U(pAPzz}ys0Z=`8yJ!KDE%xNkhY>+XgPpychiA|xUi=X&cE0>+)aht;c>r%u z*q>|OcY(O!eY<&BG#4PH_Xn6hnX{_y$VIFwzC*2AgDvWq zp_M5~XZznb^bpLI_!#|f;R;j3)2_Lij*QB5@e}#>$8UbIH$K;riHnT~eGljrMo;|D zr`2;`ya}SJUTIeihrg8K%?MM7po{Uy21y4PN&QjVU;*VXkX%hCe$QoYv9cFuO8go) ze}$RE&Gop3tq>U%QOGDrstq75f?0%;5d2PMdy&TKwqV)8+G_`orf>KVf3J8P#z8?N zwARCO=D+Nss211sU|rOm?S_$_;iW>^mvzF;O4lX?UC2IaNjWblULQ@KWqje*6&r0< z*_!#iaU{m8kaUCNgtF0NvSwXapyfMu+W4Vmglv+Gp=kAhtl{%Fr`rX3Q@?)}yD{oDv>WiZOGd4lg4hChtND5 z+AtY|W|U*Xk|UOLoa { + println!("cargo::rustc-cfg=deckcraft_nightly_v1"); + true + } + Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false, + _ => { + println!("cargo::error=unsupported DECKCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)"); + std::process::exit(1); + } + }; + let version = if nightly { + match std::env::var("DECKCRAFT_VERSION") { + Ok(version) if version.contains("-nightly.") => version, + _ => { + println!("cargo::error=nightly-v1 requires an explicit DECKCRAFT_VERSION feed identity"); + std::process::exit(1); + } + } + } else { + std::env::var("CARGO_PKG_VERSION").unwrap_or_default() + }; + println!("cargo::rustc-env=DECKCRAFT_BUILT_VERSION={version}"); + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../contributors"); let json = read(&dir.join("contributors.json"), "the About window shows no contributors", |t| { serde_json::from_str::(t).map_err(|e| e.to_string()) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index fb5e7e3dd..6fa915a29 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -140,7 +140,7 @@ impl SlideApp { /// Start the helper of an update that is ready, so that it installs once the process has /// exited. The desktop shell calls it in `on_exit`, which ends the process on macOS before the - /// app is dropped. Later calls do nothing. + /// app is dropped. Later calls do nothing, and a Nightly launch never starts a stable update. #[cfg(not(target_arch = "wasm32"))] pub fn start_pending_update(&mut self) { updates_ui::start_pending_update(self); diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 75eba4b22..e5c43af1a 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -227,8 +227,9 @@ impl SlideApp { } "app.about" => self.dialog = Some(dialogs::Dialog::new("about")), "app.checkUpdates" => { + // Nightly is updated by ArtCraft Launcher; its stable updater must stay idle. #[cfg(not(target_arch = "wasm32"))] - updates_ui::request_check(self); + updates_ui::request_check(self)?; #[cfg(target_arch = "wasm32")] return Err("updates are handled by the browser: reload the page".into()); } diff --git a/crates/ui-egui/src/dialogs/about.rs b/crates/ui-egui/src/dialogs/about.rs index 059543b61..79fa0c7b8 100644 --- a/crates/ui-egui/src/dialogs/about.rs +++ b/crates/ui-egui/src/dialogs/about.rs @@ -20,7 +20,7 @@ pub fn about(_app: &mut SlideApp, ui: &mut Ui) { ui.vertical_centered(|ui| { let (r, _) = ui.allocate_exact_size(vec2(64.0, 64.0), Sense::hover()); paint_logo(ui.painter(), r); - ui.label(egui::RichText::new("DeckCraft").font(theme::bold(22.0))); + ui.label(egui::RichText::new(crate::flavor::app_name()).font(theme::bold(22.0))); ui.label(egui::RichText::new(version_line()).color(t.text_dim)); ui.add_space(6.0); ui.label("Presentations and slide shows, rebuilt from scratch in pure Rust."); @@ -38,7 +38,7 @@ pub fn about(_app: &mut SlideApp, ui: &mut Ui) { /// from `[workspace.package] version` (the single source of truth, `cargo xtask version`); the /// release workflow sets `DECKCRAFT_BUILD_SHA` / `DECKCRAFT_BUILD_DATE` at build time. pub fn version_line() -> String { - let mut s = format!("Version {}", env!("CARGO_PKG_VERSION")); + let mut s = format!("Version {}", crate::flavor::version()); let sha = option_env!("DECKCRAFT_BUILD_SHA").map(|s| s.get(..9).unwrap_or(s)).filter(|s| !s.is_empty()); let date = option_env!("DECKCRAFT_BUILD_DATE").filter(|s| !s.is_empty()); match (sha, date) { diff --git a/crates/ui-egui/src/dialogs/updates_ui.rs b/crates/ui-egui/src/dialogs/updates_ui.rs index 3c62a254d..41bebcc9c 100644 --- a/crates/ui-egui/src/dialogs/updates_ui.rs +++ b/crates/ui-egui/src/dialogs/updates_ui.rs @@ -8,16 +8,28 @@ use crate::SlideApp; const VERSION: &str = env!("CARGO_PKG_VERSION"); +/// What Help > Check for Updates… answers in Nightly, which ArtCraft Launcher updates. +pub(crate) const NIGHTLY_UPDATES: &str = "DeckCraft Nightly is updated by ArtCraft Launcher"; + pub(crate) struct Runtime { updater: Updater, /// The desktop host turns the check at start on; tests and the web build leave it off. enabled: bool, check_requested: bool, + /// The stable self-updater (its feed, cache and records under Stable's folders) is a stable + /// service only. The launch identity is read once, when the UI state is built, so every entry + /// point below agrees and no test can reselect the process-wide identity. + stable_services: bool, } impl Default for Runtime { fn default() -> Self { - Self { updater: Updater::new(&crate::UPDATE_APP, VERSION), enabled: false, check_requested: false } + Self { + updater: Updater::new(&crate::UPDATE_APP, VERSION), + enabled: false, + check_requested: false, + stable_services: crate::os_window::stable_services_allowed(), + } } } @@ -25,21 +37,31 @@ pub(crate) fn enable(app: &mut SlideApp) { app.updates_rt.enabled = true; } -/// Help > Check for Updates…: runs a check and reports the outcome either way. -pub(crate) fn request_check(app: &mut SlideApp) { +/// Help > Check for Updates…: runs a check and reports the outcome either way. Nightly has no +/// update check of its own (the Launcher owns the install) and never touches Stable's updater. +pub(crate) fn request_check(app: &mut SlideApp) -> Result<(), String> { + if !app.updates_rt.stable_services { + return Err(NIGHTLY_UPDATES.into()); + } if !matches!(app.updates_rt.updater.status(), Status::Checking) { app.updates_rt.check_requested = true; } + Ok(()) } /// Starts the helper of an update that is ready, so that it installs once the process has exited. -/// Later calls do nothing. +/// Later calls do nothing; Nightly has no ready stable update to start. pub(crate) fn start_pending_update(app: &mut SlideApp) { - app.updates_rt.updater.start_pending_update(); + if app.updates_rt.stable_services { + app.updates_rt.updater.start_pending_update(); + } } pub(crate) fn tick(app: &mut SlideApp, ctx: &egui::Context) { let rt = &mut app.updates_rt; + if !rt.stable_services { + return; + } if std::mem::take(&mut rt.check_requested) { rt.updater.check_now(ctx); } else if rt.enabled { @@ -49,6 +71,9 @@ pub(crate) fn tick(app: &mut SlideApp, ctx: &egui::Context) { } pub(crate) fn show(app: &mut SlideApp, ctx: &egui::Context) { + if !app.updates_rt.stable_services { + return; + } // An installation starts, and a ready update asks the app to close, only while nothing is unsaved. let clean = !app.session.documents().iter().any(|d| d.is_dirty()); match app.updates_rt.updater.show_if(ctx, clean) { @@ -103,6 +128,33 @@ mod tests { app } + /// Nightly is updated by ArtCraft Launcher: the stable feed, its cache and its records (all + /// under Stable's folders) stay untouched, and Help > Check for Updates… says so. + #[test] + fn a_nightly_launch_never_starts_the_stable_updater() { + let mut app = SlideApp::new(deckcraft_engine::Session::new(), crate::Services::default()); + assert!(app.updates_rt.stable_services, "the test binary is a stable launch"); + app.updates_rt.stable_services = false; + assert_eq!(request_check(&mut app), Err(NIGHTLY_UPDATES.to_string())); + assert!(!app.updates_rt.check_requested, "a refused check must not be queued"); + start_pending_update(&mut app); + let ctx = egui::Context::default(); + ctx.run_ui(egui::RawInput::default(), |ui| { + tick(&mut app, ui.ctx()); + show(&mut app, ui.ctx()); + }) + .textures_delta + .clear(); + assert_eq!(app.updates_rt.updater.status(), &Status::Idle, "Nightly never drives the updater"); + } + + /// The identity is sampled when the UI state is built, so the answer cannot drift later. + #[test] + fn the_updater_reads_the_launch_identity_once() { + assert_eq!(Runtime::default().stable_services, crate::os_window::stable_services_allowed()); + assert_eq!(crate::os_window::identity(), crate::os_window::LaunchIdentity::Stable); + } + fn records_dir(name: &str) -> std::path::PathBuf { let dir = std::env::temp_dir().join(format!("deckcraft-updates-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); diff --git a/crates/ui-egui/src/flavor.rs b/crates/ui-egui/src/flavor.rs new file mode 100644 index 000000000..60d6900f9 --- /dev/null +++ b/crates/ui-egui/src/flavor.rs @@ -0,0 +1,36 @@ +//! The compiled channel, shared by the About dialog and the window name. The build script sets +//! `cfg(deckcraft_nightly_v1)` and `DECKCRAFT_BUILT_VERSION` from `DECKCRAFT_BUILD_CHANNEL`, the +//! same switch the app crate's build script reads, so both crates agree in one build. + +/// The display name: the same string the Launcher and the macOS bundle use. +pub const fn app_name() -> &'static str { + if is_nightly() { "DeckCraft Nightly" } else { "DeckCraft" } +} + +pub const fn is_nightly() -> bool { + cfg!(deckcraft_nightly_v1) +} + +/// The version the binary was built as: the workspace version for stable, the prepared Nightly +/// feed identity for Nightly (never the bare Cargo version). +pub const fn version() -> &'static str { + env!("DECKCRAFT_BUILT_VERSION") +} + +#[cfg(test)] +mod tests { + #[test] + fn nightly_and_stable_names_match_the_build_channel() { + assert_eq!(super::is_nightly(), cfg!(deckcraft_nightly_v1)); + assert_eq!(super::app_name(), if cfg!(deckcraft_nightly_v1) { "DeckCraft Nightly" } else { "DeckCraft" }); + assert!(super::version().starts_with(env!("CARGO_PKG_VERSION").split('-').next().unwrap_or_default())); + } + + #[test] + fn a_nightly_build_never_reports_the_bare_workspace_version() { + if cfg!(deckcraft_nightly_v1) { + assert_ne!(super::version(), env!("CARGO_PKG_VERSION")); + assert!(super::version().contains("-nightly.")); + } + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 48253bb01..3654fa153 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -22,10 +22,12 @@ pub mod control; pub mod dialogs; pub mod doc_window; pub mod eyedropper; +pub mod flavor; pub mod icons; pub mod media; pub mod menus; pub mod opening; +pub mod os_window; pub mod presenter; pub mod ribbon; pub mod settings; diff --git a/crates/ui-egui/src/os_window.rs b/crates/ui-egui/src/os_window.rs new file mode 100644 index 000000000..540ad7052 --- /dev/null +++ b/crates/ui-egui/src/os_window.rs @@ -0,0 +1,80 @@ +//! The app id every DeckCraft OS window carries, so docks show the DeckCraft icon on them and +//! Wayland compositors' window rules can match them. + +/// Matches the `.desktop` file and hicolor icon name, so Wayland docks pick up the icon. +pub const APP_ID: &str = "ai.storyteller.deckcraft"; + +/// Immutable startup identity. The desktop selects it before any UI service is created. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LaunchIdentity { + Stable, + NightlyV1, +} + +static IDENTITY: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + +pub fn select_identity(identity: LaunchIdentity) -> Result<(), String> { + let value = match identity { + LaunchIdentity::Stable => 1, + LaunchIdentity::NightlyV1 => 2, + }; + IDENTITY + .compare_exchange(0, value, std::sync::atomic::Ordering::AcqRel, std::sync::atomic::Ordering::Acquire) + .map(|_| ()) + .map_err(|_| "the window launch identity was already selected".into()) +} + +pub fn identity() -> LaunchIdentity { + if IDENTITY.load(std::sync::atomic::Ordering::Acquire) == 2 { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable } +} + +pub const fn id_for(identity: LaunchIdentity) -> &'static str { + match identity { + LaunchIdentity::Stable => APP_ID, + LaunchIdentity::NightlyV1 => "ai.storyteller.deckcraft.nightly-v1", + } +} + +pub fn app_id() -> &'static str { + id_for(identity()) +} + +pub const fn name_for(identity: LaunchIdentity) -> &'static str { + match identity { + LaunchIdentity::Stable => "DeckCraft", + LaunchIdentity::NightlyV1 => "DeckCraft Nightly", + } +} + +pub const fn stable_services_for(identity: LaunchIdentity) -> bool { + matches!(identity, LaunchIdentity::Stable) +} + +pub fn stable_services_allowed() -> bool { + stable_services_for(identity()) +} + +/// A builder for an extra OS window, carrying the selected app id. +pub fn builder() -> egui::ViewportBuilder { + egui::ViewportBuilder::default().with_app_id(app_id()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn extra_windows_carry_the_app_id() { + assert_eq!(builder().app_id.as_deref(), Some(APP_ID)); + } + + #[test] + fn nightly_identity_is_distinct_and_never_enables_stable_services() { + assert_eq!(id_for(LaunchIdentity::Stable), APP_ID); + assert_ne!(id_for(LaunchIdentity::NightlyV1), APP_ID); + assert_eq!(id_for(LaunchIdentity::NightlyV1), "ai.storyteller.deckcraft.nightly-v1"); + assert_eq!(name_for(LaunchIdentity::NightlyV1), "DeckCraft Nightly"); + assert!(stable_services_for(LaunchIdentity::Stable)); + assert!(!stable_services_for(LaunchIdentity::NightlyV1)); + } +} diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 0ca335a84..fd45ea17c 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -73,4 +73,7 @@ pub struct Services { pub audio_out: Option>, /// How many displays are connected, when the host can tell: Presenter View needs a second. pub displays: Option Option>>, + /// Work that must finish on a clean quit. `eframe::App::on_exit` takes and runs it once: on + /// macOS ⌘Q ends the process inside AppKit's terminate, so nothing after `run_native` runs. + pub at_exit: Option>, } diff --git a/docs/nightly-release-preparation.md b/docs/nightly-release-preparation.md new file mode 100644 index 000000000..77bed2669 --- /dev/null +++ b/docs/nightly-release-preparation.md @@ -0,0 +1,88 @@ +# Windows, Linux and macOS release-ref nightly: supervised manual go-live + +**Enabled for supervised manual runs, not yet qualified.** The producer (`nightly.yml`, main) and the +signer (`nightly-sign.yml`, release) keep only their exact context guards and run when one of the reviewed +manual actors dispatches them. There is no schedule and no automatic dispatch transport yet. The installed +policy [`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the real v3 +policy. Once `nightly.yml` lands on `main`, populate `producer_workflow_id` with its registration ID: + +```bash +gh api repos/storytold/deckcraft/actions/workflows/nightly.yml --jq .id +``` + +The callers pass no platform secrets. The unsigned reusable caller's maximum OIDC/attestation +permissions are for its isolated attester; its compiler narrows to contents and Actions read +only, with no OIDC, attestation write, release environment or platform signing secrets. +Shared tooling is pinned to `605d58766e8f536564da8fc81d3676ac86816dea`, the craft-common-actions +main commit that merged [#339](https://github.com/storytold/craft-common-actions/pull/339) (bounded +lineage compares and an issue reread at the end of candidate admission) on top of +[#342](https://github.com/storytold/craft-common-actions/pull/342) (policy v3, the `platforms` input +and the Linux and macOS legs). Both callers name it in `uses` and `tooling-revision`. A pin is reviewed +source availability, not provider, queue, native signing or crypto qualification. +Existing stable workflows are unchanged. + +**The shared-workflow port is a prerequisite.** At this pin both reusable workflows admit only +PhotoCraft: `nightly-unsigned.yml` requires `inputs.app-name == 'photocraft'` and +`github.repository == 'storytold/photocraft'` on its build jobs, and `nightly-release.yml` requires the +same repository in `validate` and every signing job (its concurrency group is +`craft-release-ref-signer-photocraft`). A DeckCraft dispatch therefore builds and signs nothing until +`storytold/craft-common-actions` admits `storytold/deckcraft`. No dispatch can produce a release before +that port, and both callers' `uses`, `tooling-revision` and the policy pins must move to the same +reviewed revision together. + +**First runs.** The first runs are manual dispatches in this order: `nightly.yml` on main (only a +listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `release` with that +producer run ID and attempt, by a listed manual actor. + +**Manual actors.** `bflatastic`, `dylanmtaylor`, `echelon`, `FredApps` and `skylartaylor`, in the +producer's `manual-actors` and the policy's `manual_actors`. The list mirrors the release-managers +team (id 19837241), leaving out `echelon-robot`; update it by PR in both places when the team changes. + +**Admission timing.** The candidate check reads the newest CI run on the candidate commit and +main's latest finished Sonar analysis, so pick a quiet `main`, wait for its CI and SonarCloud analysis +to finish green, then dispatch the producer and, once it succeeds, the signer, before another `main` +push lands a newer analysis. + +**Platform rows.** The producer caller lists +`platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'` on its single job: one producer +run builds every listed platform for one all-or-nothing release (one failed or skipped platform stops +that night's release), and the release-ref signer admits platforms only from the protected policy, so +there is no separate Linux or macOS caller job and the signer caller has no platform input. + +## Installed policy values and their sources + +Read on 2026-11-24; re-read anything that may have moved before the policy is promoted to `release`. + +| Field | Value | Source | +|---|---|---| +| `repository_id` | `1408294296` | `gh api repos/storytold/deckcraft --jq .id` | +| `producer_workflow_id` | `null` (populate after `nightly.yml` reaches `main`) | `gh api repos/storytold/deckcraft/actions/workflows/nightly.yml --jq .id` | +| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `605d5876…` (craft-common-actions #339) | The callers' pin | +| `manual_actors` / `automatic_signer_actors` | the five release managers / `[]` | release-managers team (id 19837241) members who can push; equals the producer caller's `manual-actors` | +| `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist | +| `platforms` | three rows | Storytold stable signing identities (`windows-x86_64`, `linux-x86_64`, `macos-aarch64`) | +| `candidate_policy.required_workflows` | CI (`ci.yml`, workflow `377160704`), 2 jobs | Workflow list API; jobs that succeeded on recent `main` push runs | +| `candidate_policy.sonar` | `storytold` / `storytold_deckcraft`, app `12526` | `sonar-project.properties`; the SonarCloud check on `main` commits | +| Sonar conditions | `new_security_rating` accepted (max 5); the other five required | Standard Storytold SonarCloud quality gate | +| Sonar `issue_types` / `debt` | `VULNERABILITY` / `[]` | Update before promotion if any unresolved `main` vulnerabilities exist | + +## Ownership and interface + +- `.github/workflows/nightly.yml`: default-main registration of the unsigned producer, named + `DeckCraft unsigned nightly`, enabled for manual dispatch by `manual-actors`; no signing secrets + may be passed or inherited. +- `.github/workflows/nightly-sign.yml`: top-level release registration, enabled for manual dispatch, + and identical on `main` and `release` after reviewed promotion. It rejects wrong repository/event/actual + branch, including same-name tags. Its constant whole-run concurrency is distinct from stable, + cancellation is off and `queue: max` must be hosted-qualified. The caller itself passes no + credentials; only the shared callee's sign jobs bind the `release` environment. +- Shared reusable entrypoints are `nightly-unsigned.yml` and `nightly-release.yml` in + `storytold/craft-common-actions`. Both must resolve to a **real reviewed public immutable + commit**; the defining workflow SHA and tooling input must match. + +## Local regression checks + +`python3 packaging/nightly-release-tests.py` verifies the installed v3 policy, exact context guards +on `nightly.yml` and `nightly-sign.yml`, manual actor alignment, platform list and trust anchors, +shared tooling pin alignment, no-cache/no-platform-secret boundaries, and root concurrency +serialization (`deckcraft-nightly-release`, `queue: max`, `cancel-in-progress: false`). diff --git a/packaging/linux/flatpak-bundle.sh b/packaging/linux/flatpak-bundle.sh index e56692adf..73b6daeee 100755 --- a/packaging/linux/flatpak-bundle.sh +++ b/packaging/linux/flatpak-bundle.sh @@ -17,6 +17,12 @@ set -euo pipefail . "$(dirname "${BASH_SOURCE[0]}")/../common.sh" HERE="$ROOT/packaging/linux" APP_ID=ai.storyteller.deckcraft +FLATPAK_ID="$APP_ID" +# The remote indexes both app IDs on the stable ref branch; IDs isolate installations. +FLATPAK_BRANCH=stable +if [[ "${DECKCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then + FLATPAK_ID="$APP_ID.nightly" +fi FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo TEST=1 @@ -51,30 +57,78 @@ WORK="$CARGO_TARGET_DIR/flatpak-bundle" rm -rf "$WORK" mkdir -p "$WORK/stage" tar -xzf "$TARBALL" -C "$WORK/stage" --strip-components=1 -[[ -x "$WORK/stage/bin/deckcraft" ]] || { echo "error: $TARBALL has no bin/deckcraft" >&2; exit 1; } -cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$APP_ID.yml" +if [[ "$FLATPAK_ID" != "$APP_ID" ]]; then + # The nightly tarball already carries its launcher and a GUI named for it, so the bundle + # installs both rather than generating a sixth wrapper. + [[ -x "$WORK/stage/bin/deckcraft-bin" && -x "$WORK/stage/bin/deckcraft-nightly" ]] \ + || { echo "error: the nightly $TARBALL has no bin/deckcraft-bin and bin/deckcraft-nightly" >&2; exit 1; } + NIGHTLY_ICON="$ROOT/assets/app-icon/deckcraft-nightly.png" + [[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" + # Two ids meet here on purpose. The bundle id is the Flatpak app id (`$APP_ID.nightly`), so the + # exported desktop entry, its basename and the icon carry it. The window keeps the flavor id + # (`$APP_ID.nightly-v1`) that every other Linux format's desktop entry is renamed to, so + # StartupWMClass names the window id: that is what ties this launcher to the running window. + sed -e "s|^Icon=$APP_ID$|Icon=$FLATPAK_ID|" \ + -e "s|^Name=DeckCraft$|Name=DeckCraft Nightly|" \ + -e "s#^Exec=deckcraft\\([[:space:]]\\|$\\)#Exec=deckcraft-nightly\\1#" \ + -e "s|^TryExec=deckcraft$|TryExec=deckcraft-nightly|" \ + -e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.deckcraft.nightly-v1|' \ + -e '/^MimeType=/d' \ + "$WORK/stage/share/applications/$APP_ID.desktop" >"$WORK/stage/share/applications/$FLATPAK_ID.desktop" + rm -f "$WORK/stage/share/applications/$APP_ID.desktop" + sed -e "s|$APP_ID|$FLATPAK_ID|g" \ + -e "s|DeckCraft|DeckCraft Nightly|g" \ + -e "s|$APP_ID.desktop|$FLATPAK_ID.desktop|g" \ + -e "s|$APP_ID|$FLATPAK_ID|g" \ + -e '//d' \ + "$WORK/stage/share/metainfo/$APP_ID.metainfo.xml" >"$WORK/stage/share/metainfo/$FLATPAK_ID.metainfo.xml" + rm -f "$WORK/stage/share/metainfo/$APP_ID.metainfo.xml" + mv "$WORK/stage/share/mime/packages/$APP_ID.xml" "$WORK/stage/share/mime/packages/$FLATPAK_ID.xml" + rm -rf "$WORK/stage/share/icons/hicolor" + install -Dm644 "$NIGHTLY_ICON" \ + "$WORK/stage/share/icons/hicolor/256x256/apps/$FLATPAK_ID.png" + # Flatpak starts `command`, and the desktop entry's Exec names the same launcher; the GUI sits + # beside it in /app/bin, where the launcher looks first. + sed -e "s|ai\.storyteller\.deckcraft|$FLATPAK_ID|g" \ + -e 's|^command: deckcraft$|command: deckcraft-nightly|' \ + -e 's|^ - install -Dm755 bin/deckcraft /app/bin/deckcraft$| - install -Dm755 bin/deckcraft-bin /app/bin/deckcraft-bin\n - install -Dm755 bin/deckcraft-nightly /app/bin/deckcraft-nightly|' \ + -e 's|deckcraft|deckcraft-nightly|' \ + "$HERE/flatpak/$APP_ID.bundle.yml" >"$WORK/$FLATPAK_ID.yml" + # A template change must fail here, not as a bundle whose menu entry cannot find a program. + for expected in 'command: deckcraft-nightly' \ + ' - install -Dm755 bin/deckcraft-bin /app/bin/deckcraft-bin' \ + ' - install -Dm755 bin/deckcraft-nightly /app/bin/deckcraft-nightly'; do + grep -qxF "$expected" "$WORK/$FLATPAK_ID.yml" || { + echo "error: the nightly Flatpak manifest lost \"$expected\"" >&2 + exit 1 + } + done +else + [[ -x "$WORK/stage/bin/deckcraft" ]] || { echo "error: $TARBALL has no bin/deckcraft" >&2; exit 1; } + cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$FLATPAK_ID.yml" +fi flatpak remote-add --user --if-not-exists flathub "$FLATHUB" # --disable-rofiles-fuse: no FUSE in containers and CI runners. flatpak-builder --user --install-deps-from=flathub --disable-rofiles-fuse --force-clean \ - --default-branch=stable --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$APP_ID.yml" + --default-branch="$FLATPAK_BRANCH" --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$FLATPAK_ID.yml" OUT="$DIST/$BASENAME.flatpak" # --runtime-repo lets `flatpak install` fetch the freedesktop runtime from Flathub if missing. -flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$APP_ID" stable +flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$FLATPAK_ID" "$FLATPAK_BRANCH" echo "wrote $OUT" if [[ "$OCI" = 1 ]]; then OUT_OCI="$DIST/$BASENAME-oci" rm -rf "$OUT_OCI" - flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$APP_ID" stable + flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$FLATPAK_ID" "$FLATPAK_BRANCH" echo "wrote OCI layout to $OUT_OCI" fi if [[ "$TEST" = 1 ]]; then flatpak install --user -y --noninteractive --reinstall "$OUT" - flatpak info --user "$APP_ID" - flatpak run --command=deckcraft-cli "$APP_ID" --version - flatpak run --command=sh "$APP_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/256x256/apps' + flatpak info --user "$FLATPAK_ID" + flatpak run --command=deckcraft-cli "$FLATPAK_ID" --version + flatpak run --command=sh "$FLATPAK_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/*/apps' fi echo "==> done" ls -lh "$OUT" diff --git a/packaging/linux/nfpm.yaml b/packaging/linux/nfpm.yaml index 0d41fc7ec..15986f5b0 100644 --- a/packaging/linux/nfpm.yaml +++ b/packaging/linux/nfpm.yaml @@ -3,7 +3,7 @@ # exports VERSION and NFPM_ARCH. # # nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/ -name: deckcraft +name: ${NFPM_NAME} arch: ${NFPM_ARCH} platform: linux version: ${VERSION} @@ -58,12 +58,15 @@ overrides: - xdg-desktop-portal contents: - - src: ${STAGE}/usr/bin/deckcraft - dst: /usr/bin/deckcraft + - src: ${STAGE}/usr/bin/${NFPM_BIN} + dst: /usr/bin/${NFPM_BIN} file_info: { mode: 0755 } - - src: ${STAGE}/usr/bin/deckcraft-cli - dst: /usr/bin/deckcraft-cli + - src: ${STAGE}/usr/bin/${NFPM_CLI} + dst: /usr/bin/${NFPM_CLI} file_info: { mode: 0755 } + - src: ${STAGE}/usr/lib/ + dst: /usr/lib/ + type: tree - src: ${STAGE}/usr/share/ dst: /usr/share/ type: tree diff --git a/packaging/linux/nightly-arch-tar-test.sh b/packaging/linux/nightly-arch-tar-test.sh new file mode 100755 index 000000000..f229be1cf --- /dev/null +++ b/packaging/linux/nightly-arch-tar-test.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +# Validate the staged Arch launcher without building or opening DeckCraft. +set -euo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +stage="$work/source" +dst="$work/dist" +base=deckcraft-0.0.1-nightly.1-linux-x86_64 +mkdir -p "$stage/bin" "$dst" "$work/extract" + +# A local argv recorder stands in for the compiled binaries. It never opens a UI. +cat >"$stage/bin/deckcraft" <<'RECORDER' +#!/bin/sh +printf '<%s>\n' "$@" +RECORDER +chmod 755 "$stage/bin/deckcraft" +cp "$stage/bin/deckcraft" "$stage/bin/deckcraft-cli" + +bash "$HERE/nightly-arch-tar.sh" "$stage" "$work/stage" "$dst" "$base" +tar -xzf "$dst/$base.tar.gz" -C "$work/extract" +bin="$work/extract/$base/bin" +# Simulate the existing Arch bin-tree copy and public launcher rename. +mkdir -p "$work/installed" +cp -R "$bin" "$work/installed/bin" +bin="$work/installed/bin" +mv "$bin/deckcraft" "$bin/deckcraft-nightly" +mv "$bin/deckcraft-cli" "$bin/deckcraft-nightly-cli" + +[[ ! -e "$stage/bin/.deckcraft-nightly" ]] +cmp "$stage/bin/deckcraft" "$bin/.deckcraft-nightly/deckcraft-bin" +cmp "$stage/bin/deckcraft-cli" "$bin/deckcraft-nightly-cli" +export HOME="$work/home" +mkdir -p "$HOME" +export XDG_CONFIG_HOME="$HOME/.config" XDG_DATA_HOME="$HOME/.local/share" +expect() { + expected="$1" + shift + actual=$(PATH="$bin:$PATH" deckcraft-nightly "$@") + if [[ "$actual" != "$expected" ]]; then + printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2 + exit 1 + fi +} +profile="$XDG_DATA_HOME/deckcraft-nightly/launcher/profiles/deckcraft" +nightly_argv() { + printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$profile" -- +} +expect "$(nightly_argv)" +expect "$(nightly_argv; printf '<%s>\n' 'deck with spaces.pptx' '--other-name.deckcraft')" \ + 'deck with spaces.pptx' '--other-name.deckcraft' +# A caller-written `--` is the launcher's own separator: it is never passed on as a file name. +expect "$(nightly_argv; printf '<%s>\n' 'deck.pptx')" -- deck.pptx +# A bare version query stays a version query, not a file name, and creates no profile. +expect '<--version>' --version +expect '<-V>' -V +# The Launcher's own protocol is passed through untouched, never wrapped a second time. +expect "$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$work/launcher" -- 'deck.pptx')" \ + --launch-profile nightly-v1 --profile-root "$work/launcher" -- 'deck.pptx' +test ! -e "$profile" +# A profile needs a data folder: the launcher refuses instead of writing into /. +status=0 +env -u XDG_DATA_HOME -u HOME PATH="$bin:$PATH" deckcraft-nightly deck.pptx >/dev/null 2>&1 || status=$? +[[ "$status" -eq 2 ]] || { printf 'expected exit 2 without XDG_DATA_HOME/HOME, got %s\n' "$status" >&2; exit 1; } +test ! -e "$work/home/.local/share/deckcraft-nightly" + +echo "PASS: Arch Nightly handoff stages the hidden GUI, the shared launcher and the launch arguments" diff --git a/packaging/linux/nightly-arch-tar.sh b/packaging/linux/nightly-arch-tar.sh new file mode 100755 index 000000000..1fd33084a --- /dev/null +++ b/packaging/linux/nightly-arch-tar.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Stage the DeckCraft Nightly-only handoff for the Arch packager. +set -euo pipefail + +here="$(cd "$(dirname "$0")" && pwd)" +source_tree="$1" +work="$2" +destination="$3" +basename="$4" +stage="$work/$basename" + +mkdir -p "$work" +cp -R "$source_tree" "$stage" +mkdir "$stage/bin/.deckcraft-nightly" +mv "$stage/bin/deckcraft" "$stage/bin/.deckcraft-nightly/deckcraft-bin" +cp "$here/nightly-launch.sh" "$stage/bin/deckcraft" +chmod 755 "$stage/bin/deckcraft" +tar -C "$work" -czf "$destination/$basename.tar.gz" "$basename" +echo "wrote $destination/$basename.tar.gz" diff --git a/packaging/linux/nightly-launch-test.sh b/packaging/linux/nightly-launch-test.sh new file mode 100755 index 000000000..1be5d3ff5 --- /dev/null +++ b/packaging/linux/nightly-launch-test.sh @@ -0,0 +1,105 @@ +#!/usr/bin/env bash +# Validate the nightly launcher in every Linux placement without building or opening DeckCraft: +# the flat nightly tar (`deckcraft` + `deckcraft-bin`), the AppImage (`AppRun` + `usr/bin/deckcraft`), +# the distro tree (`bin/deckcraft-nightly` + `bin/deckcraft-bin`) and the /usr/bin rule that reaches +# the fixed /usr/lib copy. A recorder binary stands in for the GUI and prints its argv. +set -euo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +launcher="$HERE/nightly-launch.sh" +export HOME="$work/home" +mkdir -p "$HOME" +export XDG_CONFIG_HOME="$HOME/.config" XDG_DATA_HOME="$HOME/.local/share" +profile="$XDG_DATA_HOME/deckcraft-nightly/launcher/profiles/deckcraft" + +recorder() { + mkdir -p "$(dirname "$1")" + cat >"$1" <<'RECORDER' +#!/bin/sh +printf '<%s>\n' "$@" +RECORDER + chmod 755 "$1" +} + +expect() { + binary="$1" + expected="$2" + shift 2 + actual=$("$binary" "$@") + if [[ "$actual" != "$expected" ]]; then + printf '%s\nexpected:\n%s\nactual:\n%s\n' "$binary" "$expected" "$actual" >&2 + exit 1 + fi +} +nightly_argv() { + printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$profile" -- +} + +# ---- the flat nightly tar: `deckcraft` launcher, `deckcraft-bin` GUI ---- +flat="$work/flat" +recorder "$flat/deckcraft-bin" +cp "$launcher" "$flat/deckcraft" +chmod 755 "$flat/deckcraft" +expect "$flat/deckcraft" "$(nightly_argv)" +expect "$flat/deckcraft" "$(nightly_argv; printf '<%s>\n' 'deck with spaces.pptx' '--other-name.pptx')" \ + 'deck with spaces.pptx' '--other-name.pptx' +expect "$flat/deckcraft" "$(nightly_argv; printf '<%s>\n' 'deck.pptx')" -- deck.pptx +expect "$flat/deckcraft" '<--version>' --version +expect "$flat/deckcraft" '<-V>' -V +expect "$flat/deckcraft" '<--help>' --help +expect "$flat/deckcraft" "$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$work/launcher" -- 'deck.pptx')" \ + --launch-profile nightly-v1 --profile-root "$work/launcher" -- 'deck.pptx' +test ! -e "$profile" + +# ---- the AppImage: AppRun at the mount root, the GUI and the entry's copy in usr/bin ---- +appdir="$work/DeckCraft.AppDir" +recorder "$appdir/usr/bin/deckcraft-bin" +cp "$launcher" "$appdir/AppRun" +chmod 755 "$appdir/AppRun" +expect "$appdir/AppRun" "$(nightly_argv; printf '<%s>\n' book.pptx)" book.pptx +cp "$launcher" "$appdir/usr/bin/deckcraft-nightly" +chmod 755 "$appdir/usr/bin/deckcraft-nightly" +expect "$appdir/usr/bin/deckcraft-nightly" "$(nightly_argv; printf '<%s>\n' book.pptx)" book.pptx +test ! -e "$profile" + +# ---- the distro tree tarball: bin/deckcraft-nightly beside bin/deckcraft-bin ---- +tree="$work/tree/bin" +recorder "$tree/deckcraft-bin" +cp "$launcher" "$tree/deckcraft-nightly" +chmod 755 "$tree/deckcraft-nightly" +actual=$(PATH="$tree:$PATH" deckcraft-nightly book.pptx) +[[ "$actual" == "$(nightly_argv; printf '<%s>\n' book.pptx)" ]] || { printf 'a PATH invocation printed:\n%s\n' "$actual" >&2; exit 1; } +test ! -e "$profile" + +# ---- a missing GUI fails closed, and so does a tree with no data folder ---- +empty="$work/empty" +mkdir -p "$empty" +cp "$launcher" "$empty/deckcraft" +chmod 755 "$empty/deckcraft" +status=0 +"$empty/deckcraft" book.pptx >/dev/null 2>&1 || status=$? +[[ "$status" -eq 2 ]] || { printf 'a launcher with no GUI must exit 2, got %s\n' "$status" >&2; exit 1; } +recorder "$work/nodata/deckcraft-bin" +cp "$launcher" "$work/nodata/deckcraft" +chmod 755 "$work/nodata/deckcraft" +status=0 +env -u XDG_DATA_HOME -u HOME "$work/nodata/deckcraft" book.pptx >/dev/null 2>&1 || status=$? +[[ "$status" -eq 2 ]] || { printf 'a launcher with no data folder must exit 2, got %s\n' "$status" >&2; exit 1; } +# A query is not a launch: it answers without a data folder instead of becoming that error. +actual=$(env -u XDG_DATA_HOME -u HOME "$work/nodata/deckcraft" --version) \ + || { printf 'a no-data-folder --version must still answer\n' >&2; exit 1; } +[[ "$actual" == '<--version>' ]] || { printf 'a no-data-folder --version printed:\n%s\n' "$actual" >&2; exit 1; } + +# ---- the /usr/bin rule: the fixed /usr/lib copy is named, and no parent path is ever used ---- +# The launcher's text is searched literally, so `$here` must not expand here. +# shellcheck disable=SC2016 +grep -Fq '[ "$here" = /usr/bin ]' "$launcher" +grep -Fq '/usr/lib/deckcraft-nightly/deckcraft' "$launcher" +if grep -q '\.\.' "$launcher"; then + echo "the launcher must not reach outside its own folder or the fixed /usr/lib path" >&2 + exit 1 +fi + +echo "PASS: nightly launcher starts the GUI with the profile in every layout and refuses the rest" diff --git a/packaging/linux/nightly-launch.sh b/packaging/linux/nightly-launch.sh new file mode 100755 index 000000000..52b03904f --- /dev/null +++ b/packaging/linux/nightly-launch.sh @@ -0,0 +1,63 @@ +#!/bin/sh +# The DeckCraft Nightly launcher every Linux format ships: the plain nightly tar's `deckcraft`, the +# distro tree's `bin/deckcraft-nightly`, the AppImage's `AppRun`, the Arch handoff's `bin/deckcraft` +# and the Flatpak's `/app/bin/deckcraft-nightly`. A nightly build refuses to start without +# `--launch-profile nightly-v1 --profile-root `, and the profile is its only data root, so +# this is what keeps a Nightly run out of the stable app's settings, prefs, logs and recovery. +set -eu + +# Resolve this script's own folder from `$0`. A shell that finds it through PATH passes a bare +# name, so ask the shell where that is instead of using the working directory. +case "$0" in + */*) self="$0" ;; + *) self="$(command -v "$0" || printf '%s' "$0")" ;; +esac +case "$self" in + /*) ;; + *) self="$PWD/$self" ;; +esac +here="$(CDPATH='' cd "$(dirname "$self")" && pwd -P)" +self="$here/$(basename "$self")" + +# The GUI each placement keeps inside its own tree, never from a parent folder: `deckcraft-bin` +# beside the launcher (the flat nightly tar, the distro tree, the Flatpak sandbox), the same name +# in an AppImage's `usr/bin`, and the hidden copy the Arch handoff keeps. A candidate that is this +# same file is never started, so a launcher cannot recurse into itself. +real= +for candidate in "$here/deckcraft-bin" "$here/usr/bin/deckcraft-bin" "$here/.deckcraft-nightly/deckcraft-bin"; do + if [ -f "$candidate" ] && [ -x "$candidate" ] && [ ! "$candidate" -ef "$self" ]; then + real="$candidate" + break + fi +done +# A distro package keeps the GUI in /usr/lib. Reach that fixed path only from /usr/bin, so a +# writable parent folder can never plant a program for this launcher to run. +if [ -z "$real" ] && [ "$here" = /usr/bin ] && [ -f /usr/lib/deckcraft-nightly/deckcraft ] && [ -x /usr/lib/deckcraft-nightly/deckcraft ]; then + real=/usr/lib/deckcraft-nightly/deckcraft +fi +if [ -z "$real" ]; then + echo "deckcraft-nightly: no DeckCraft binary beside $self" >&2 + exit 2 +fi + +# A bare version/help query and the Launcher's own protocol pass straight through: they are not +# file names, need no data folder, and a profile the caller already supplied is never wrapped +# twice. This runs before the data-folder check, so `deckcraft-nightly --version` still answers +# where HOME and XDG_DATA_HOME are both unset. +case "${1-}" in + --launch-profile | --profile-root | --version | -V | --help | -h) exec "$real" "$@" ;; +esac + +if [ -z "${XDG_DATA_HOME:-}" ] && [ -z "${HOME:-}" ]; then + echo "deckcraft-nightly: XDG_DATA_HOME and HOME are both unset, so there is no Nightly data folder" >&2 + exit 2 +fi +# The same root as every other format's launcher: beside the fenced stable `deckcraft` folder, +# never inside it. +profile="${XDG_DATA_HOME:-$HOME/.local/share}/deckcraft-nightly/launcher/profiles/deckcraft" +# A caller-written `--` is the separator this launcher adds below. Drop it, so it can never reach +# the app as a file name. +if [ "${1-}" = "--" ]; then + shift +fi +exec "$real" --launch-profile nightly-v1 --profile-root "$profile" -- "$@" diff --git a/packaging/linux/nightly.sh b/packaging/linux/nightly.sh new file mode 100755 index 000000000..baea54508 --- /dev/null +++ b/packaging/linux/nightly.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# App-owned GUI-only nightly tar: no FUSE/AppImage, CLI, association or install hooks. +set -euo pipefail +ARCH= +while [[ $# -gt 0 ]]; do + case "$1" in + --arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;; + -h|--help) echo 'Usage: nightly.sh --arch x86_64'; exit 0 ;; + *) echo "unsupported nightly argument: $1" >&2; exit 2 ;; + esac +done +[[ "$ARCH" == x86_64 && "$(uname -s)" == Linux ]] || { echo 'only native Linux x86_64 nightly packaging is supported' >&2; exit 2; } +# shellcheck source=../nightly-common.sh +. "$(dirname "${BASH_SOURCE[0]}")/../nightly-common.sh" +nightly_init linux "$ARCH" x86_64-unknown-linux-gnu +OUTPUT="$DIST/deckcraft-$VERSION-linux-x86_64-nightly.tar.gz" +[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || nightly_die 'refusing to replace an existing nightly archive' +nightly_build_gui +STAGE="$NIGHTLY_WORK/stage" +mkdir -p "$STAGE" +# The kit's flat tar layout: `deckcraft` is the launcher people run and `deckcraft-bin` the GUI it +# starts with this channel's own launch profile, so an unpacked copy never writes stable's data. +cp "$NIGHTLY_GUI" "$STAGE/deckcraft-bin" +chmod 755 "$STAGE/deckcraft-bin" +cp "$ROOT/packaging/linux/nightly-launch.sh" "$STAGE/deckcraft" +chmod 755 "$STAGE/deckcraft" +ICON_SRC="$ROOT/assets/app-icon/deckcraft-nightly.png" +[[ -f "$ICON_SRC" ]] || ICON_SRC="$ROOT/assets/app-icon/deckcraft-1024.png" +cp "$ICON_SRC" "$STAGE/deckcraft-nightly.png" +nightly_copy_notices "$STAGE" +# The private mktemp cwd is the helper authority root, not a CLI path parent. +(cd "$NIGHTLY_WORK" && python3 "$ROOT/packaging/nightly-archive.py" linux stage archive.tar.gz) +nightly_publish_archive "$NIGHTLY_WORK/archive.tar.gz" "$OUTPUT" diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index de0470391..85f18c497 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -7,7 +7,7 @@ # $DIST/deckcraft--linux-.rpm Fedora, openSUSE, RHEL, ... # $DIST/deckcraft--linux-.tar.gz plain FHS-style tree (bin/, share/) # -# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"] +# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"] [--arch-tar-dir DIRECTORY] # # Needs: cargo; nfpm for deb/rpm (https://nfpm.goreleaser.com); appimagetool for the AppImage # (downloaded into $CARGO_TARGET_DIR if missing). Build on an old distro (CI: Ubuntu 22.04, @@ -27,10 +27,16 @@ verify_sha256() { SKIP_BUILD=0 FORMATS="appimage deb rpm tar" +ARCH_TAR_DIR= while [[ $# -gt 0 ]]; do case "$1" in --skip-build) SKIP_BUILD=1; shift ;; --formats) FORMATS="$2"; shift 2 ;; + --arch-tar-dir) + [[ -n "${2:-}" ]] || { echo "error: --arch-tar-dir needs a directory" >&2; exit 2; } + ARCH_TAR_DIR="$2" + shift 2 + ;; -h | --help) sed -n '2,17p' "$0"; exit 0 ;; *) echo "unknown argument: $1" >&2; exit 2 ;; esac @@ -44,9 +50,20 @@ case "$ARCH" in *) echo "unsupported architecture $ARCH" >&2; exit 2 ;; esac export DECKCRAFT_MAINTAINER="${DECKCRAFT_MAINTAINER:-DeckCraft maintainers }" +IS_NIGHTLY=0 +if [[ "${DECKCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then + IS_NIGHTLY=1 + export DECKCRAFT_BUILD_CHANNEL=nightly-v1 + export DECKCRAFT_OVERRIDE_VERSION="$VERSION" +fi BASENAME="deckcraft-$VERSION-linux-$ARCH" -echo "==> DeckCraft $VERSION for Linux $ARCH ($FORMATS)" +if [[ -n "$ARCH_TAR_DIR" && "$IS_NIGHTLY" != 1 ]]; then + echo "error: --arch-tar-dir is only for Nightly builds" >&2 + exit 2 +fi + +echo "==> DeckCraft $VERSION for Linux $ARCH ($FORMATS, channel=${DECKCRAFT_BUILD_CHANNEL:-stable})" if [[ "$SKIP_BUILD" = 0 ]]; then if [[ -n "${CROSS_TARGET:-}" ]]; then @@ -65,6 +82,11 @@ install -Dm755 "$BIN/deckcraft" "$STAGE/usr/bin/deckcraft" install -Dm755 "$BIN/deckcraft-cli" "$STAGE/usr/bin/deckcraft-cli" "${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/deckcraft" "$STAGE/usr/bin/deckcraft-cli" 2>/dev/null || true install -Dm644 "$HERE/$APP_ID.desktop" "$STAGE/usr/share/applications/$APP_ID.desktop" +if [[ "$IS_NIGHTLY" = 1 ]]; then + sed -e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.deckcraft.nightly-v1|' \ + "$STAGE/usr/share/applications/$APP_ID.desktop" >"$STAGE/usr/share/applications/$APP_ID.desktop.tmp" + mv "$STAGE/usr/share/applications/$APP_ID.desktop.tmp" "$STAGE/usr/share/applications/$APP_ID.desktop" +fi install -Dm644 "$HERE/$APP_ID.mime.xml" "$STAGE/usr/share/mime/packages/$APP_ID.xml" mkdir -p "$STAGE/usr/share/metainfo" sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$DECKCRAFT_BUILD_DATE/g" \ @@ -90,17 +112,88 @@ has() { if has tar; then mkdir -p "$WORK/tar" cp -R "$STAGE/usr" "$WORK/tar/$BASENAME" + if [[ "$IS_NIGHTLY" = 1 ]]; then + # An unpacked nightly tree is isolated too: bin/deckcraft-nightly starts the GUI (here + # bin/deckcraft-bin), because the binary alone refuses to run without a launch profile. + install -Dm755 "$WORK/tar/$BASENAME/bin/deckcraft" "$WORK/tar/$BASENAME/bin/deckcraft-bin" + rm -f "$WORK/tar/$BASENAME/bin/deckcraft" + install -Dm755 "$HERE/nightly-launch.sh" "$WORK/tar/$BASENAME/bin/deckcraft-nightly" + TAR_DESK="$WORK/tar/$BASENAME/share/applications/$APP_ID.desktop" + sed -e "s#^Exec=deckcraft\([[:space:]]\|$\)#Exec=deckcraft-nightly\1#" \ + -e "s|^TryExec=deckcraft$|TryExec=deckcraft-nightly|" \ + -e "s|^Name=DeckCraft$|Name=DeckCraft Nightly|" \ + -e '/^MimeType=/d' \ + "$TAR_DESK" >"$TAR_DESK.tmp" + mv "$TAR_DESK.tmp" "$TAR_DESK" + fi tar -C "$WORK/tar" -czf "$DIST/$BASENAME.tar.gz" "$BASENAME" echo "wrote $DIST/$BASENAME.tar.gz" fi +# The Arch handoff keeps the same basename as the plain tarball in a separate directory. It is +# built from the staged tree, not from the nightly tar beside it (whose bin/deckcraft is already +# the launcher and whose bin/deckcraft-bin is the GUI). +if [[ -n "$ARCH_TAR_DIR" ]]; then + mkdir -p "$ARCH_TAR_DIR" + if [[ "$(cd "$ARCH_TAR_DIR" && pwd -P)" == "$(cd "$DIST" && pwd -P)" ]]; then + echo "error: the Arch tar directory must differ from the release directory" >&2 + exit 2 + fi + bash "$HERE/nightly-arch-tar.sh" "$STAGE/usr" "$WORK/arch-tar" "$ARCH_TAR_DIR" "$BASENAME" +fi + # ---- .deb / .rpm -------------------------------------------------------------------------------- if has deb || has rpm; then command -v nfpm >/dev/null || { echo "error: nfpm not found (https://nfpm.goreleaser.com/install/)" >&2; exit 1; } export VERSION export NFPM_ARCH="$DEB_ARCH" + NFPM_STAGE="$STAGE" + export NFPM_NAME="deckcraft" + export NFPM_BIN="deckcraft" + export NFPM_CLI="deckcraft-cli" + if [[ "$IS_NIGHTLY" = 1 ]]; then + NIGHTLY_DESK_ID="$APP_ID.nightly-v1" + NIGHTLY_ICON="$ROOT/assets/app-icon/deckcraft-nightly.png" + [[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" + export NFPM_NAME="deckcraft-nightly" + export NFPM_BIN="deckcraft-nightly" + export NFPM_CLI="deckcraft-nightly-cli" + NFPM_STAGE="$WORK/nfpm-root" + rm -rf "$NFPM_STAGE" + cp -R "$STAGE" "$NFPM_STAGE" + # The GUI keeps its name under /usr/lib; /usr/bin/deckcraft-nightly is the launcher, whose + # /usr/bin gate is what reaches that fixed path (the same file as the tar and AppImage use). + install -Dm755 "$NFPM_STAGE/usr/bin/deckcraft" "$NFPM_STAGE/usr/lib/deckcraft-nightly/deckcraft" + install -Dm755 "$HERE/nightly-launch.sh" "$NFPM_STAGE/usr/bin/$NFPM_BIN" + rm -f "$NFPM_STAGE/usr/bin/deckcraft" + mv "$NFPM_STAGE/usr/bin/deckcraft-cli" "$NFPM_STAGE/usr/bin/$NFPM_CLI" + mv "$NFPM_STAGE/usr/share/doc/deckcraft" "$NFPM_STAGE/usr/share/doc/$NFPM_NAME" + sed -e "s#^Exec=deckcraft\([[:space:]]\|$\)#Exec=$NFPM_BIN\1#" \ + -e "s|^TryExec=deckcraft$|TryExec=$NFPM_BIN|" \ + -e "s|^Icon=$APP_ID$|Icon=$NIGHTLY_DESK_ID|" \ + -e "s|^Name=DeckCraft$|Name=DeckCraft Nightly|" \ + -e '/^MimeType=/d' \ + "$NFPM_STAGE/usr/share/applications/$APP_ID.desktop" >"$NFPM_STAGE/usr/share/applications/$NIGHTLY_DESK_ID.desktop" + rm -f "$NFPM_STAGE/usr/share/applications/$APP_ID.desktop" + sed -e "s|$APP_ID|$NIGHTLY_DESK_ID|g" \ + -e "s|DeckCraft|DeckCraft Nightly|g" \ + -e "s|$APP_ID.desktop|$NIGHTLY_DESK_ID.desktop|g" \ + -e "s|$APP_ID|$NIGHTLY_DESK_ID|g" \ + -e "s|deckcraft|$NFPM_BIN|g" \ + -e '//d' \ + "$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" >"$NFPM_STAGE/usr/share/metainfo/$NIGHTLY_DESK_ID.metainfo.xml" + rm -f "$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" + rm -rf "$NFPM_STAGE/usr/share/mime" + rm -rf "$NFPM_STAGE/usr/share/icons/hicolor" + install -Dm644 "$NIGHTLY_ICON" \ + "$NFPM_STAGE/usr/share/icons/hicolor/256x256/apps/$NIGHTLY_DESK_ID.png" + fi # nfpm expands env vars in fields like `version` and `arch`, but not in `contents[].src`. - sed "s|\${STAGE}|$STAGE|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" + DROP_LIB_TREE= + # shellcheck disable=SC2016 + [[ -d "$NFPM_STAGE/usr/lib" ]] || DROP_LIB_TREE='\|^ - src: \${STAGE}/usr/lib/|,+2d;' + # shellcheck disable=SC2016 + sed "${DROP_LIB_TREE}s|\${STAGE}|$NFPM_STAGE|g;s|\${NFPM_BIN}|$NFPM_BIN|g;s|\${NFPM_CLI}|$NFPM_CLI|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" for fmt in deb rpm; do if has "$fmt"; then (cd "$ROOT" && nfpm package -f "$WORK/nfpm.yaml" -p "$fmt" -t "$DIST/$BASENAME.$fmt"); fi done @@ -127,10 +220,40 @@ if has appimage; then fi APPDIR="$WORK/DeckCraft.AppDir" cp -R "$STAGE" "$APPDIR" - ln -s usr/bin/deckcraft "$APPDIR/AppRun" - cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop" - cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png" - ln -s "$APP_ID.png" "$APPDIR/.DirIcon" + if [[ "$IS_NIGHTLY" = 1 ]]; then + # Not a symlink: the nightly AppImage starts the app with its launch profile, so an AppImage + # run is isolated like the distro package even without the ArtCraft Launcher. The GUI takes + # the name the launcher looks for, and the entry names the launcher for integrations that + # read it. + install -Dm755 "$APPDIR/usr/bin/deckcraft" "$APPDIR/usr/bin/deckcraft-bin" + rm -f "$APPDIR/usr/bin/deckcraft" + install -Dm755 "$HERE/nightly-launch.sh" "$APPDIR/AppRun" + install -Dm755 "$HERE/nightly-launch.sh" "$APPDIR/usr/bin/deckcraft-nightly" + else + ln -s usr/bin/deckcraft "$APPDIR/AppRun" + fi + if [[ "$IS_NIGHTLY" = 1 ]]; then + APPIMAGE_ID="$APP_ID.nightly-v1" + NIGHTLY_ICON="$ROOT/assets/app-icon/deckcraft-nightly.png" + [[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" + sed -e "s#^Exec=deckcraft\([[:space:]]\|$\)#Exec=deckcraft-nightly\1#" \ + -e "s|^TryExec=deckcraft$|TryExec=deckcraft-nightly|" \ + -e "s|^Icon=$APP_ID$|Icon=$APPIMAGE_ID|" \ + -e "s|^Name=DeckCraft$|Name=DeckCraft Nightly|" \ + -e '/^MimeType=/d' \ + "$APPDIR/usr/share/applications/$APP_ID.desktop" >"$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop" + rm -f "$APPDIR/usr/share/applications/$APP_ID.desktop" + cp "$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop" "$APPDIR/$APPIMAGE_ID.desktop" + rm -rf "$APPDIR/usr/share/icons/hicolor" + install -Dm644 "$NIGHTLY_ICON" \ + "$APPDIR/usr/share/icons/hicolor/256x256/apps/$APPIMAGE_ID.png" + cp "$NIGHTLY_ICON" "$APPDIR/$APPIMAGE_ID.png" + ln -s "$APPIMAGE_ID.png" "$APPDIR/.DirIcon" + else + cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop" + cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png" + ln -s "$APP_ID.png" "$APPDIR/.DirIcon" + fi TOOL="${APPIMAGETOOL:-$(command -v appimagetool || true)}" if [[ -z "$TOOL" ]]; then @@ -171,11 +294,20 @@ if has appimage; then # each AppImage on GitHub Releases. `latest` is the newest published release that is not a # pre-release. A fork's builds point at its own releases through GITHUB_REPOSITORY. REPO="${GITHUB_REPOSITORY:-storytold/deckcraft}" - UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|deckcraft-*-linux-$ARCH.AppImage.zsync" + UPDATE_ARGS=() + if [[ "$IS_NIGHTLY" = 0 ]]; then + UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|deckcraft-*-linux-$ARCH.AppImage.zsync" + UPDATE_ARGS=(-u "$UPDATE_INFO") + else + # Nightly releases are GitHub pre-releases (`latest` only selects stable releases), so point + # zsync update metadata at `latest-pre` using the same asset naming pattern as `BASENAME`. + UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest-pre|deckcraft-*-linux-$ARCH.AppImage.zsync" + UPDATE_ARGS=(-u "$UPDATE_INFO") + fi # Extract-and-run: works without FUSE (containers, CI). The output embeds the static runtime, # so users don't need libfuse2 either. With zsyncmake on the host (CI installs the zsync # package) appimagetool also writes the .zsync, into its working directory, hence the cd. - (cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream --runtime-file "$RUNTIME" -u "$UPDATE_INFO" "$APPDIR" "$OUT") + (cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream --runtime-file "$RUNTIME" "${UPDATE_ARGS[@]}" "$APPDIR" "$OUT") echo "wrote $OUT" if [[ -s "$OUT.zsync" ]]; then echo "wrote $OUT.zsync" diff --git a/packaging/macos/nightly-lib.sh b/packaging/macos/nightly-lib.sh new file mode 100755 index 000000000..6eda07778 --- /dev/null +++ b/packaging/macos/nightly-lib.sh @@ -0,0 +1,110 @@ +# shellcheck shell=bash +# Shared checks for the Apple-silicon Nightly scripts (nightly.sh, nightly-sign.sh, nightly-verify.sh). +# Stable packaging (package.sh, verify.sh) does not source this file. The text checks take tool output +# as arguments, so packaging/macos/nightly_sign_tests.py runs them without macOS. + +MAC_NIGHTLY_APP='DeckCraft Nightly.app' +MAC_NIGHTLY_ID='ai.storyteller.deckcraft.nightly' +# The release environment's names, as stable release.yml passes them (packaging/macos/import-cert.sh). +MAC_NIGHTLY_SECRETS=(APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID) + +mac_nightly_die() { printf 'error: %s\n' "$*" >&2; exit 2; } + +# The exact prepared version from the feed asset name, or failure. +mac_nightly_version_from_asset() { + local name="$1" version + [[ "$name" =~ ^deckcraft-(.+)-macos-aarch64-nightly\.zip$ ]] || return 1 + version="${BASH_REMATCH[1]}" + [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || return 1 + printf '%s\n' "$version" +} + +# Every signing and notarization value is set, and the team is one Apple team ID. No ad-hoc fallback. +mac_nightly_require_secrets() { + local name + for name in "${MAC_NIGHTLY_SECRETS[@]}"; do + [[ -n "${!name:-}" ]] || mac_nightly_die "$name is not set: Nightly signing and notarization are required, with no ad-hoc fallback" + done + [[ "$APPLE_TEAM_ID" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'APPLE_TEAM_ID is not an Apple team ID' + if [[ -n "${NIGHTLY_APPLE_TEAM_ID:-}" && "$NIGHTLY_APPLE_TEAM_ID" != "$APPLE_TEAM_ID" ]]; then + mac_nightly_die 'the signing team differs from the reviewed Nightly team (NIGHTLY_APPLE_TEAM_ID)' + fi +} + +# One line of `security find-identity -v -p codesigning`: the identity is a Developer ID Application of the team. +mac_nightly_identity_is_team() { + local line="$1" identity="$2" team="$3" + [[ "$line" == *" $identity "* && "$line" == *'"Developer ID Application: '*" ($team)\""* ]] +} + +# `codesign -d --verbose=2` of the signed bundle: the Nightly identifier, a Developer ID Application of the +# team, a secure timestamp and the hardened runtime (the checks of verify.sh, made strict). +mac_nightly_check_signature() { + local details="$1" team="$2" ok=0 + grep -Fqx "Identifier=$MAC_NIGHTLY_ID" <<<"$details" || { echo "error: the bundle is not signed as $MAC_NIGHTLY_ID" >&2; ok=1; } + grep -q '^Authority=Developer ID Application:' <<<"$details" || { echo 'error: not signed with a Developer ID Application identity' >&2; ok=1; } + grep -qx "TeamIdentifier=$team" <<<"$details" || { echo 'error: signed by a different team' >&2; ok=1; } + grep -q '^Timestamp=' <<<"$details" || { echo 'error: the signature has no secure timestamp' >&2; ok=1; } + grep -Eq '^CodeDirectory .*flags=0x[0-9a-f]+\([^)]*runtime' <<<"$details" || { echo 'error: not signed with the hardened runtime' >&2; ok=1; } + return "$ok" +} + +# `spctl --assess --type execute -vv`: Gatekeeper accepts the bundle as notarized. +mac_nightly_check_assessment() { + grep -q 'accepted' <<<"$1" && grep -qx 'source=Notarized Developer ID' <<<"$1" +} + +# Before anything is unpacked: every ZIP entry is a regular file or directory inside the one Nightly +# bundle, with no absolute path, `..`, backslash or empty component, and no link or special file. +mac_nightly_check_zip_entries() { + python3 -I - "$1" "$MAC_NIGHTLY_APP" <<'PY' || mac_nightly_die 'the archive has an entry outside the bundle, a link or a special file' +import stat, sys, zipfile +archive, app = sys.argv[1:] +with zipfile.ZipFile(archive) as z: + for info in z.infolist(): + name = info.filename + parts = name.rstrip("/").split("/") + mode = info.external_attr >> 16 + if (name.startswith("/") or "\\" in name or "\0" in name or parts[0] != app + or any(part in ("", ".", "..") for part in parts) + or stat.S_IFMT(mode) not in (0, stat.S_IFREG, stat.S_IFDIR)): + sys.exit(f"refused entry: {name!r}") +PY +} + +# An unpacked payload directory holds exactly the GUI-only Nightly bundle: one thin arm64 DeckCraft +# executable, the Nightly identity and the exact version (no numeric fallback), no CLI, no links or special +# files, no document or URL types. +mac_nightly_check_bundle() { + local payload="$1" version="$2" app entries plist key value + app="$payload/$MAC_NIGHTLY_APP" + entries="$(ls -A "$payload")" + [[ "$entries" == "$MAC_NIGHTLY_APP" && -d "$app" && ! -L "$app" ]] || mac_nightly_die "the archive must hold exactly $MAC_NIGHTLY_APP" + [[ -z "$(find "$payload" ! -type f ! -type d -print -quit)" ]] || mac_nightly_die 'the bundle contains links or special files' + [[ "$(ls -A "$app/Contents/MacOS")" == DeckCraft ]] || mac_nightly_die 'Contents/MacOS must hold only the DeckCraft GUI (no CLI)' + [[ -f "$app/Contents/MacOS/DeckCraft" && -x "$app/Contents/MacOS/DeckCraft" ]] || mac_nightly_die 'missing executable GUI' + [[ "$(lipo -archs "$app/Contents/MacOS/DeckCraft")" == arm64 ]] || mac_nightly_die 'the GUI must be thin arm64' + plist="$app/Contents/Info.plist" + for key in CFBundleIdentifier CFBundleExecutable DeckCraftVersion; do + value="$(plutil -extract "$key" raw -o - "$plist")" || mac_nightly_die "Info.plist has no $key" + case "$key" in + CFBundleIdentifier) [[ "$value" == "$MAC_NIGHTLY_ID" ]] ;; + CFBundleExecutable) [[ "$value" == DeckCraft ]] ;; + DeckCraftVersion) [[ "$value" == "$version" ]] ;; + esac || mac_nightly_die "Info.plist $key is not the prepared Nightly identity" + done + for key in CFBundleDocumentTypes CFBundleURLTypes UTExportedTypeDeclarations UTImportedTypeDeclarations; do + if plutil -extract "$key" xml1 -o - "$plist" >/dev/null 2>&1; then mac_nightly_die "Nightly declares $key"; fi + done +} + +# `stapler validate` asks Apple's CloudKit service, which sometimes drops the connection (error 68) +# though the ticket is there (verify.sh). +mac_nightly_validate_staple() { + local target="$1" attempt + for attempt in 1 2 3 4 5; do + xcrun stapler validate "$target" && return 0 + [[ "$attempt" = 5 ]] || sleep $((attempt * 20)) + done + return 1 +} diff --git a/packaging/macos/nightly-sign.sh b/packaging/macos/nightly-sign.sh new file mode 100755 index 000000000..2c84eb73a --- /dev/null +++ b/packaging/macos/nightly-sign.sh @@ -0,0 +1,143 @@ +#!/usr/bin/env bash +# Trusted signing step for the Apple-silicon Nightly, the stable release's macOS signing route +# (import-cert.sh, then package.sh's codesign, notarytool and stapler steps): +# +# nightly-sign.sh --arch aarch64 --input /abs/deckcraft--macos-aarch64-nightly.zip \ +# --output /abs//deckcraft--macos-aarch64-nightly.zip +# +# Input: the unsigned archive nightly.sh made. Output: the same bundle signed with the Developer ID and +# hardened runtime, notarized, with the ticket stapled into the bundle, zipped without extended +# attributes. Writes only that file, never replacing one; the temporary keychain and work directory +# are removed on every exit. +# +# Env (all required, no ad-hoc or unnotarized fallback): APPLE_CERTIFICATE, APPLE_CERTIFICATE_PASSWORD, +# KEYCHAIN_PASSWORD, APPLE_ID, APPLE_PASSWORD, APPLE_TEAM_ID; optional NIGHTLY_APPLE_TEAM_ID (must +# equal APPLE_TEAM_ID) and RUNNER_TEMP (work directory base). +# +# Never compiles, and never runs anything from the payload: the version query runs on the signed +# bundle in a job without secrets (nightly-verify.sh). +set -euo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=nightly-lib.sh +. "$HERE/nightly-lib.sh" +# shellcheck source=../nightly-common.sh +. "$HERE/../nightly-common.sh" + +ARCH='' INPUT='' OUTPUT='' +while [[ $# -gt 0 ]]; do + case "$1" in + --arch | --input | --output) + [[ $# -ge 2 ]] || mac_nightly_die "missing $1 value" + case "$1" in --arch) ARCH="$2" ;; --input) INPUT="$2" ;; --output) OUTPUT="$2" ;; esac + shift 2 ;; + -h | --help) sed -n '2,18p' "$0"; exit 0 ;; + *) mac_nightly_die "unsupported argument: $1" ;; + esac +done +[[ "$ARCH" == aarch64 ]] || mac_nightly_die 'only --arch aarch64 is supported' +[[ "$INPUT" == /* && "$OUTPUT" == /* ]] || mac_nightly_die '--input and --output must be absolute paths' +NAME="$(basename -- "$INPUT")" +VERSION="$(mac_nightly_version_from_asset "$NAME")" || mac_nightly_die 'the input is not a prepared Nightly archive name' +[[ "$(basename -- "$OUTPUT")" == "$NAME" ]] || mac_nightly_die 'the output must keep the archive name' +[[ -f "$INPUT" && ! -L "$INPUT" ]] || mac_nightly_die 'the input must be a regular file' +[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || mac_nightly_die 'refusing to replace an existing output' +[[ -d "$(dirname -- "$OUTPUT")" && ! -L "$(dirname -- "$OUTPUT")" ]] || mac_nightly_die 'the output directory must exist' +mac_nightly_require_secrets +[[ "$(uname -s)" == Darwin ]] || mac_nightly_die 'signing needs macOS (codesign, notarytool, stapler)' + +BASE="${RUNNER_TEMP:-${TMPDIR:-/tmp}}" +WORK="$(mktemp -d "${BASE%/}/deckcraft-nightly-sign.XXXXXX")" +# import-cert.sh creates the keychain under RUNNER_TEMP, in a private subdirectory of its own; the +# path is taken from its output below and must stay inside this run's WORK. +KEYCHAIN="" +cleanup() { + if [[ -n "$KEYCHAIN" && -e "$KEYCHAIN" ]]; then security delete-keychain "$KEYCHAIN" >/dev/null 2>&1 || rm -f -- "$KEYCHAIN"; fi + rm -rf -- "$WORK" +} +trap cleanup EXIT + +# ---- identity: import-cert.sh, into this run's private directory ------------------------------ +# An empty GITHUB_ENV makes it print the identity instead of exporting it to later steps. +imported="$(GITHUB_ENV='' RUNNER_TEMP="$WORK" DIST="$WORK/dist" bash "$HERE/import-cert.sh")" +IDENTITY="$(sed -n 's/^MACOS_SIGN_IDENTITY=//p' <<<"$imported")" +KEYCHAIN="$(sed -n 's/^MACOS_KEYCHAIN=//p' <<<"$imported")" +[[ "$IDENTITY" =~ ^[0-9A-F]{40}$ && "$KEYCHAIN" == "$WORK"/* && -f "$KEYCHAIN" && ! -L "$KEYCHAIN" ]] \ + || mac_nightly_die 'import-cert.sh did not import a signing identity into the work directory' +mac_nightly_identity_is_team "$(security find-identity -v -p codesigning "$KEYCHAIN" | grep -F " $IDENTITY " || true)" "$IDENTITY" "$APPLE_TEAM_ID" \ + || mac_nightly_die "the imported identity is not a Developer ID Application of team $APPLE_TEAM_ID" +echo "==> DeckCraft Nightly $VERSION for macOS (aarch64), identity: $IDENTITY" + +# ---- the unsigned bundle --------------------------------------------------------------------------- +mac_nightly_check_zip_entries "$INPUT" +ditto -x -k --norsrc --noextattr "$INPUT" "$WORK/payload" +mac_nightly_check_bundle "$WORK/payload" "$VERSION" +APP="$WORK/payload/$MAC_NIGHTLY_APP" + +# ---- package.sh's signing and notarization, with a required Developer ID --------------------------- +sign() { + codesign --force --sign "$IDENTITY" --keychain "$KEYCHAIN" --timestamp "$@" +} + +notarize() { + local file="$1" out id status + echo "==> notarizing $(basename "$file") (this can take a few minutes)" + out="$(xcrun notarytool submit "$file" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" \ + --team-id "$APPLE_TEAM_ID" --wait --timeout 1h --output-format json)" || true + echo "$out" + id="$(printf '%s' "$out" | plutil -extract id raw -o - - 2>/dev/null || true)" + status="$(printf '%s' "$out" | plutil -extract status raw -o - - 2>/dev/null || true)" + if [[ "$status" != "Accepted" ]]; then + if [[ -n "$id" ]]; then + # Capped: the shared signer bounds a step's output at 256 KiB. + xcrun notarytool log "$id" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" --team-id "$APPLE_TEAM_ID" | head -c 131072 || true + fi + echo "error: notarization of $(basename "$file") failed (status: ${status:-unknown})" >&2 + exit 1 + fi +} + +# Stapling and validating both look the ticket up in Apple's CloudKit service, which can drop the +# connection right after notarization (error 68), so retry the pair (package.sh). +staple() { + local file="$1" attempt + for attempt in 1 2 3 4 5; do + if xcrun stapler staple "$file" && xcrun stapler validate "$file"; then + return + fi + if [[ "$attempt" = 5 ]]; then + echo "error: stapling $(basename "$file") failed after $attempt attempts" >&2 + exit 1 + fi + echo "stapling $(basename "$file") failed (attempt $attempt); retrying in $((attempt * 20))s" >&2 + sleep $((attempt * 20)) + done +} + +# Inside-out: the executable, then the bundle (no --deep on the final signature). +sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/MacOS/DeckCraft" +sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP" +codesign --verify --strict --deep --verbose=2 "$APP" +ditto -c -k --keepParent "$APP" "$WORK/notarize.zip" +notarize "$WORK/notarize.zip" +# The ticket goes into the bundle (Contents/CodeResources): the Launcher's extract restores no xattrs. +staple "$APP" + +# ---- the final archive, checked as the Launcher unpacks it ----------------------------------------- +ditto -c -k --norsrc --noextattr --noacl --keepParent "$APP" "$WORK/final.zip" +ditto -x -k --norsrc --noextattr "$WORK/final.zip" "$WORK/check" +mac_nightly_check_bundle "$WORK/check" "$VERSION" +CHECK="$WORK/check/$MAC_NIGHTLY_APP" +codesign --verify --strict --deep --verbose=2 "$CHECK" +mac_nightly_check_signature "$(codesign -d --verbose=2 "$CHECK" 2>&1)" "$APPLE_TEAM_ID" \ + || mac_nightly_die 'the signed bundle is not the required Developer ID signature' +mac_nightly_validate_staple "$CHECK" || mac_nightly_die 'no notarization ticket is stapled into the bundle' +# spctl's lookup can lag a few seconds behind notarytool's "Accepted" (verify.sh). +for attempt in 1 2 3 4 5; do + assessment="$(spctl --assess --type execute -vv "$CHECK" 2>&1)" || true + mac_nightly_check_assessment "$assessment" && break + [[ "$attempt" = 5 ]] || sleep 10 +done +printf '%s\n' "$assessment" +mac_nightly_check_assessment "$assessment" || mac_nightly_die 'Gatekeeper does not accept the bundle as notarized' + +nightly_publish_archive "$WORK/final.zip" "$OUTPUT" diff --git a/packaging/macos/nightly-verify.sh b/packaging/macos/nightly-verify.sh new file mode 100755 index 000000000..d1c50aca0 --- /dev/null +++ b/packaging/macos/nightly-verify.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +# Check an Apple-silicon Nightly archive as the Launcher unpacks it, then ask the GUI its version. +# For a job without signing material (it refuses to run with any), after nightly-sign.sh: +# +# nightly-verify.sh --input /abs/deckcraft--macos-aarch64-nightly.zip --expect signed [--team ID] +# nightly-verify.sh --input /abs/deckcraft--macos-aarch64-nightly.zip --expect unsigned +# +# Both: the archive holds only the GUI-only Nightly bundle with the exact DeckCraftVersion, unpacked +# without extended attributes. `signed` (the feed artifact): Developer ID of the team (--team, else +# NIGHTLY_APPLE_TEAM_ID), hardened runtime, secure timestamp, stapled ticket, Gatekeeper accepts it as +# notarized. `unsigned` (nightly.sh's compile output, e.g. pull-request CI) checks no signature. +# Last, the bundle's GUI answers its version query with an empty environment, both plainly and in the +# Launcher's form `--launch-profile nightly-v1 --profile-root --version` (the shared producer +# smoke): each must exit 0 within 15 seconds, print exactly `DeckCraft (nightly-v1)` and +# write nothing to standard error. +set -euo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=nightly-lib.sh +. "$HERE/nightly-lib.sh" + +INPUT='' EXPECT='' TEAM="${NIGHTLY_APPLE_TEAM_ID:-}" +while [[ $# -gt 0 ]]; do + case "$1" in + --input | --expect | --team) + [[ $# -ge 2 ]] || mac_nightly_die "missing $1 value" + case "$1" in --input) INPUT="$2" ;; --expect) EXPECT="$2" ;; --team) TEAM="$2" ;; esac + shift 2 ;; + -h | --help) sed -n '2,15p' "$0"; exit 0 ;; + *) mac_nightly_die "unsupported argument: $1" ;; + esac +done +for name in "${MAC_NIGHTLY_SECRETS[@]}" MACOS_SIGN_IDENTITY MACOS_KEYCHAIN; do + [[ -z "${!name:-}" ]] || mac_nightly_die "refusing to run the payload with signing material in the environment ($name)" +done +[[ "$EXPECT" == signed || "$EXPECT" == unsigned ]] || mac_nightly_die '--expect must be signed or unsigned' +[[ "$EXPECT" == unsigned || "$TEAM" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'a signed check needs the Apple team ID (--team or NIGHTLY_APPLE_TEAM_ID)' +[[ "$INPUT" == /* && -f "$INPUT" && ! -L "$INPUT" ]] || mac_nightly_die '--input must be an absolute regular file' +VERSION="$(mac_nightly_version_from_asset "$(basename -- "$INPUT")")" || mac_nightly_die 'the input is not a prepared Nightly archive name' +[[ "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] || mac_nightly_die 'needs an Apple silicon Mac' + +WORK="$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/deckcraft-nightly-verify.XXXXXX")" +trap 'rm -rf -- "$WORK"' EXIT +mac_nightly_check_zip_entries "$INPUT" +ditto -x -k --norsrc --noextattr "$INPUT" "$WORK/payload" +mac_nightly_check_bundle "$WORK/payload" "$VERSION" +APP="$WORK/payload/$MAC_NIGHTLY_APP" + +if [[ "$EXPECT" == signed ]]; then + codesign --verify --strict --deep --verbose=2 "$APP" + mac_nightly_check_signature "$(codesign -d --verbose=2 "$APP" 2>&1)" "$TEAM" \ + || mac_nightly_die 'the bundle is not the required Developer ID signature' + mac_nightly_validate_staple "$APP" || mac_nightly_die 'no notarization ticket is stapled into the bundle' + for attempt in 1 2 3 4 5; do + assessment="$(spctl --assess --type execute -vv "$APP" 2>&1)" || true + mac_nightly_check_assessment "$assessment" && break + [[ "$attempt" = 5 ]] || sleep 10 + done + printf '%s\n' "$assessment" + mac_nightly_check_assessment "$assessment" || mac_nightly_die 'Gatekeeper does not accept the bundle as notarized' +fi + +# macOS has no timeout(1): perl's alarm survives its exec and ends a query that hangs (a dialog, say). +query() { + local out + out="$(env -i HOME="$WORK/home" TMPDIR="$WORK/tmp/" PATH=/usr/bin:/bin \ + /usr/bin/perl -e 'alarm 15; exec @ARGV or die' "$APP/Contents/MacOS/DeckCraft" "$@" 2>"$WORK/stderr")" \ + || mac_nightly_die "the version query ($*) failed or did not finish within 15 s" + [[ ! -s "$WORK/stderr" ]] || mac_nightly_die "the version query ($*) wrote to standard error: $(head -c 2000 "$WORK/stderr")" + [[ "$out" == "DeckCraft $VERSION (nightly-v1)" ]] || mac_nightly_die "the version query ($*) reports '$out', not DeckCraft $VERSION (nightly-v1)" +} +mkdir -m 700 "$WORK/home" "$WORK/tmp" "$WORK/profile" +query --version +query --launch-profile nightly-v1 --profile-root "$WORK/profile" --version +echo "==> verified ($EXPECT): DeckCraft $VERSION (nightly-v1), plain and in the Launcher's profile form" diff --git a/packaging/macos/nightly.sh b/packaging/macos/nightly.sh new file mode 100755 index 000000000..b3a20f291 --- /dev/null +++ b/packaging/macos/nightly.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# App-owned GUI-only Nightly for Apple silicon, compile step only (no signing material): +# +# $DIST/deckcraft--macos-aarch64-nightly.zip DeckCraft Nightly.app, unsigned +# +# Usage: packaging/macos/nightly.sh --arch aarch64 +# +# Required env (nightly-common.sh): DECKCRAFT_BUILD_CHANNEL=nightly-v1, DECKCRAFT_VERSION, +# DECKCRAFT_BUILD_SHA, DECKCRAFT_BUILD_DATE, absolute CARGO_TARGET_DIR and DIST; CRAFT_FONTS_DIR optional. +# +# Not publishable by itself: the trusted step (nightly-sign.sh) signs, notarizes and staples it. No CLI, +# DMG, document or URL types, and no stable package.sh. The bundle is not run here; the version query +# runs on the signed bundle (nightly-verify.sh). +set -euo pipefail +ARCH= +while [[ $# -gt 0 ]]; do + case "$1" in + --arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;; + -h|--help) sed -n '2,13p' "$0"; exit 0 ;; + *) echo "unsupported nightly argument: $1" >&2; exit 2 ;; + esac +done +[[ "$ARCH" == aarch64 && "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] || { echo 'only native macOS aarch64 nightly packaging is supported' >&2; exit 2; } +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +. "$HERE/../nightly-common.sh" +. "$HERE/nightly-lib.sh" +nightly_refuse_signing_env +nightly_init macos "$ARCH" aarch64-apple-darwin +# Keep in sync with LSMinimumSystemVersion in Info.plist.in (as package.sh). +export MACOSX_DEPLOYMENT_TARGET=11.0 +OUTPUT="$DIST/deckcraft-$VERSION-macos-aarch64-nightly.zip" +[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || nightly_die 'refusing to replace an existing nightly archive' +nightly_compile_gui + +APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP" +mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" +cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/DeckCraft" +chmod 755 "$APP/Contents/MacOS/DeckCraft" +cp "$ROOT/assets/app-icon/deckcraft-nightly.icns" "$APP/Contents/Resources/deckcraft-nightly.icns" +nightly_copy_notices "$APP/Contents/Resources" +# The private mktemp cwd is the helper authority root: stage the template inside it. +cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in" +(cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \ + --output "stage/$MAC_NIGHTLY_APP/Contents/Info.plist" --version "$VERSION" --source-commit "$DECKCRAFT_BUILD_SHA") +plutil -lint "$APP/Contents/Info.plist" +printf 'APPL????' >"$APP/Contents/PkgInfo" +mac_nightly_check_bundle "$NIGHTLY_WORK/stage" "$VERSION" + +# No resource forks, extended attributes or ACLs: the Launcher restores none, so nothing may depend on them. +ditto -c -k --norsrc --noextattr --noacl --keepParent "$APP" "$NIGHTLY_WORK/archive.zip" +nightly_publish_archive "$NIGHTLY_WORK/archive.zip" "$OUTPUT" diff --git a/packaging/macos/nightly_plist.py b/packaging/macos/nightly_plist.py new file mode 100755 index 000000000..52740965a --- /dev/null +++ b/packaging/macos/nightly_plist.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Nightly metadata: run from a private owned build cwd with a staged template. + +All file arguments must stay beneath that cwd; this is not native/signing acceptance. +""" +import argparse +import datetime +import os +from pathlib import Path +import plistlib +import re +import sys + +# The shared helper location is fixed by this script, not by CLI file arguments. +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +from nightly_paths import OwnedBuildRoot + +MAX_TEMPLATE_BYTES = 256 * 1024 + +IDENTIFIER = "ai.storyteller.deckcraft.nightly" +ASSOCIATIONS = ("CFBundleDocumentTypes", "CFBundleURLTypes", "UTExportedTypeDeclarations", "UTImportedTypeDeclarations") +VERSION = re.compile(r"([0-9]+\.[0-9]+\.[0-9]+)-nightly\.([0-9]{8})\.[0-9]+\.[0-9]+\.g([0-9a-f]{12})\Z") + + +def render(template: bytes, version: str, commit: str) -> bytes: + match = VERSION.fullmatch(version) + if not match or not re.fullmatch(r"[0-9a-f]{40}", commit) or match[3] != commit[:12]: + raise ValueError("exact prepared Nightly version and matching source commit are required") + datetime.datetime.strptime(match[2], "%Y%m%d") + data = plistlib.loads(template) + if not isinstance(data, dict) or data.get("CFBundlePackageType") != "APPL": + raise ValueError("expected the app-owned application plist template") + for key in ASSOCIATIONS: + data.pop(key, None) + data.update( + CFBundleDisplayName="DeckCraft Nightly", + CFBundleName="DeckCraft Nightly", + CFBundleIdentifier=IDENTIFIER, + CFBundleExecutable="DeckCraft", + CFBundleIconFile="deckcraft-nightly", + CFBundleShortVersionString=match[1], + CFBundleVersion=match[1], + DeckCraftVersion=version, + DeckCraftBuildCommit=commit, + ) + return plistlib.dumps(data, fmt=plistlib.FMT_XML, sort_keys=False) + + +def write_plist(template: Path, destination: Path, version: str, commit: str) -> None: + with OwnedBuildRoot() as root: + content = render(root.read_bytes(template, MAX_TEMPLATE_BYTES), version, commit) + with root.create(destination) as stream: + stream.write(content) + stream.flush() + os.fsync(stream.fileno()) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--template", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--version", required=True) + parser.add_argument("--source-commit", required=True) + args = parser.parse_args() + write_plist(args.template, args.output, args.version, args.source_commit) + + +if __name__ == "__main__": + main() diff --git a/packaging/macos/nightly_plist_tests.py b/packaging/macos/nightly_plist_tests.py new file mode 100755 index 000000000..5cdbe494d --- /dev/null +++ b/packaging/macos/nightly_plist_tests.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python3 +"""Generated metadata/sentinel fixtures; no native binary, signature, archive or network.""" +import importlib.util +import os +from pathlib import Path +import plistlib +import runpy +import sys +from unittest import mock +import tempfile +import unittest + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("photo_nightly_plist", HERE / "nightly_plist.py") +POLICY = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(POLICY) +COMMIT = "a" * 40 +VERSION = "0.23.1-nightly.20261121.12345.1.g" + COMMIT[:12] + + +class NightlyMetadata(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name).resolve() + previous = Path.cwd() + os.chdir(self.root) + self.addCleanup(os.chdir, previous) + self.template = self.root / "Info.plist.in" + self.original = (HERE / "Info.plist.in").read_bytes() + self.template.write_bytes(self.original) + self.output = self.root / "Info.plist" + + def test_nightly_transform_removes_associations_without_changing_stable_or_platform_metadata(self): + stable = plistlib.loads(self.original) + stable["CFBundleURLTypes"] = [{"CFBundleURLSchemes": ["generated-test-scheme"]}] + prepared = plistlib.dumps(stable) + self.template.write_bytes(prepared) + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + rendered = plistlib.loads(self.output.read_bytes()) + for key in POLICY.ASSOCIATIONS: + self.assertNotIn(key, rendered) + self.assertNotEqual(rendered["CFBundleIdentifier"], stable["CFBundleIdentifier"]) + self.assertEqual(rendered["CFBundleIdentifier"], "ai.storyteller.deckcraft.nightly") + self.assertEqual(rendered["CFBundleExecutable"], "DeckCraft") + self.assertEqual(rendered["DeckCraftVersion"], VERSION) + self.assertEqual(rendered["DeckCraftBuildCommit"], COMMIT) + self.assertTrue(VERSION.startswith(rendered["CFBundleVersion"] + "-nightly.")) + for key in ("LSMinimumSystemVersion", "LSApplicationCategoryType", "NSHighResolutionCapable", "NSHumanReadableCopyright", "CFBundlePackageType"): + self.assertEqual(rendered[key], stable[key]) + self.assertEqual(self.template.read_bytes(), prepared) + self.assertEqual((HERE / "Info.plist.in").read_bytes(), self.original) + + def test_bad_identity_or_template_refuses_before_creating_output(self): + for version, commit in (("0.23.1", COMMIT), (VERSION, "b" * 40), (VERSION, "not-a-commit"), (VERSION.replace("20261121", "20261399"), COMMIT)): + with self.subTest(version=version, commit=commit): + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, version, commit) + self.assertFalse(self.output.exists()) + self.assertEqual(self.template.read_bytes(), self.original) + self.template.write_bytes(plistlib.dumps({"CFBundlePackageType": "generated-not-an-app"})) + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + + def test_cli_writes_the_requested_identity_without_replacing_the_template(self): + helper = HERE / "nightly_plist.py" + argv = [str(helper), "--template", str(self.template), "--output", str(self.output), "--version", VERSION, "--source-commit", COMMIT] + with mock.patch.object(sys, "argv", argv): + runpy.run_path(str(helper), run_name="__main__") + result = plistlib.loads(self.output.read_bytes()) + self.assertEqual(result["DeckCraftVersion"], VERSION) + self.assertEqual(result["DeckCraftBuildCommit"], COMMIT) + self.assertEqual(self.template.read_bytes(), self.original) + + def test_template_alias_or_nonfile_refuses_before_output(self): + alias = self.root / "template-alias" + alias.symlink_to(self.template) + for template in (alias, self.root, self.root / "missing-template"): + with self.subTest(template=template), self.assertRaises(ValueError): + POLICY.write_plist(template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + self.assertEqual(self.template.read_bytes(), self.original) + + def test_failed_write_cleans_owned_output_but_preserves_a_replacement(self): + sentinel = b"generated replacement artifact" + for disposition in ("owned", "missing", "replacement"): + with self.subTest(disposition=disposition): + if self.output.exists(): + self.output.unlink() + + def fail_sync(_descriptor): + # macOS/Linux allow unlink of an open file: exercise the real + # cleanup ownership check, not a mocked inode comparison. + if disposition != "owned": + self.output.unlink() + if disposition == "replacement": + self.output.write_bytes(sentinel) + raise OSError("generated fsync failure") + + with mock.patch.object(POLICY.os, "fsync", side_effect=fail_sync), self.assertRaises(OSError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + if disposition == "replacement": + self.assertEqual(self.output.read_bytes(), sentinel) + else: + self.assertFalse(self.output.exists()) + self.assertEqual(self.template.read_bytes(), self.original) + + def test_exclusive_output_preserves_existing_bytes_and_symlink_targets(self): + sentinel = b"generated owned sentinel, not an existing app or user file" + self.output.write_bytes(sentinel) + with self.assertRaises(FileExistsError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertEqual(self.output.read_bytes(), sentinel) + self.output.unlink() + external = self.root / "sentinel" + external.write_bytes(sentinel) + self.output.symlink_to(external) + with self.assertRaisesRegex(ValueError, "symlinks or aliases"): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertEqual(external.read_bytes(), sentinel) + self.assertTrue(self.output.is_symlink()) + + + def test_template_outside_build_root_refuses_before_output(self): + with tempfile.TemporaryDirectory() as external: + template = Path(external) / "Info.plist.in" + template.write_bytes(self.original) + with self.assertRaises(ValueError): + POLICY.write_plist(template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + self.assertEqual(template.read_bytes(), self.original) + + def test_output_outside_build_root_refuses_before_write(self): + with tempfile.TemporaryDirectory() as external: + output = Path(external) / "Info.plist" + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, output, VERSION, COMMIT) + self.assertFalse(output.exists()) + + def test_parent_traversal_refuses_even_to_an_owned_sibling(self): + with tempfile.TemporaryDirectory(dir=self.root.parent) as external: + output = Path("..") / Path(external).name / "Info.plist" + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, output, VERSION, COMMIT) + self.assertFalse((Path(external) / "Info.plist").exists()) + + def test_symlinked_output_parent_refuses(self): + with tempfile.TemporaryDirectory() as external: + alias = self.root / "alias" + alias.symlink_to(external, target_is_directory=True) + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, alias / "Info.plist", VERSION, COMMIT) + self.assertFalse((Path(external) / "Info.plist").exists()) + + def test_template_read_is_bounded_before_output(self): + self.template.write_bytes(plistlib.dumps({"CFBundlePackageType": "APPL", "fixture": "x" * 300000})) + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + + def test_nonprivate_build_root_refuses(self): + self.root.chmod(0o755) + try: + with self.assertRaises(ValueError): + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + self.assertFalse(self.output.exists()) + finally: + self.root.chmod(0o700) + + + def test_output_keeps_normal_new_file_permissions_inside_private_root(self): + previous = os.umask(0o022) + try: + reference = self.root / "reference" + reference.write_bytes(b"generated ordinary output") + POLICY.write_plist(self.template, self.output, VERSION, COMMIT) + finally: + os.umask(previous) + self.assertEqual(self.output.stat().st_mode & 0o777, reference.stat().st_mode & 0o777) + + def test_open_parent_anchor_prevents_a_later_alias_redirect(self): + parent = self.root / "stage" + parent.mkdir() + retained = self.root / "retained-stage" + destination = parent / "Info.plist" + original = POLICY.OwnedBuildRoot._parent + with tempfile.TemporaryDirectory() as external: + def swap_after_parent_open(root, path): + descriptor, name = original(root, path) + if Path(path) == destination: + parent.rename(retained) + parent.symlink_to(external, target_is_directory=True) + return descriptor, name + with mock.patch.object(POLICY.OwnedBuildRoot, "_parent", swap_after_parent_open): + POLICY.write_plist(self.template, destination, VERSION, COMMIT) + self.assertFalse((Path(external) / "Info.plist").exists()) + self.assertEqual(plistlib.loads((retained / "Info.plist").read_bytes())["DeckCraftVersion"], VERSION) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/macos/nightly_sign_tests.py b/packaging/macos/nightly_sign_tests.py new file mode 100755 index 000000000..f0cb5cb7e --- /dev/null +++ b/packaging/macos/nightly_sign_tests.py @@ -0,0 +1,425 @@ +#!/usr/bin/env python3 +"""The macOS Nightly signing and verification scripts, run on any POSIX host against generated +fixtures and stand-in Apple tools (codesign, notarytool, stapler, spctl, security, ditto, plutil, +lipo) that log their arguments. This proves the scripts' order, refusals and cleanup; it is not a +real signature, notarization or Mac run.""" +import base64 +import importlib.util +import json +import os +from pathlib import Path +import plistlib +import shutil +import stat +import subprocess +import sys +import tempfile +import textwrap +import time +import unittest +import zipfile + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("photo_mac_nightly_plist", HERE / "nightly_plist.py") +PLIST = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(PLIST) +COMMIT = "b" * 40 +VERSION = "0.23.1-nightly.20261123.4567.1.g" + COMMIT[:12] +ASSET = f"deckcraft-{VERSION}-macos-aarch64-nightly.zip" +APP = "DeckCraft Nightly.app" +TEAM = "ABCDE12345" +IDENTITY = "0123456789ABCDEF0123456789ABCDEF01234567" +SECRETS = { + "APPLE_CERTIFICATE": base64.b64encode(b"generated fixture, not a certificate").decode(), + "APPLE_CERTIFICATE_PASSWORD": "generated-fixture", + "KEYCHAIN_PASSWORD": "generated-fixture", + "APPLE_ID": "fixture@example.invalid", + "APPLE_PASSWORD": "generated-fixture", + "APPLE_TEAM_ID": TEAM, +} + +# One stand-in for every Apple tool, dispatched on its own name. Each logs its argv as a JSON line. +SHIM = r""" +import json, os, plistlib, sys, zipfile +from pathlib import Path +name = Path(sys.argv[0]).name +args = sys.argv[1:] +with open(os.environ["SHIM_LOG"], "a") as log: + log.write(json.dumps([name] + args) + "\n") +team = os.environ.get("SHIM_TEAM", "") +if name == "uname": + print({"-s": "Darwin", "-m": "arm64"}.get(args[0], "Darwin")) +elif name == "lipo": + print("arm64") +elif name == "ditto": + paths = [a for a in args if not a.startswith("-")] + src, dst = paths + if "-x" in args: + with zipfile.ZipFile(src) as z: + for info in z.infolist(): + target = Path(dst) / info.filename + if info.is_dir(): + target.mkdir(parents=True, exist_ok=True) + continue + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(z.read(info)) + mode = (info.external_attr >> 16) & 0o777 + if mode: + target.chmod(mode) + else: + root = Path(src) + with zipfile.ZipFile(dst, "x") as z: + for path in sorted([root] + list(root.rglob("*"))): + arc = (Path(root.name) / path.relative_to(root)).as_posix() + if path.is_dir(): + z.writestr(zipfile.ZipInfo(arc + "/"), b"") + else: + info = zipfile.ZipInfo(arc) + info.external_attr = (path.stat().st_mode & 0xFFFF) << 16 + z.writestr(info, path.read_bytes()) +elif name == "plutil": + if args[0] == "-lint": + sys.exit(0) + key, fmt, source = args[1], args[2], args[-1] + data = sys.stdin.read() if source == "-" else Path(source).read_bytes() + value = json.loads(data) if source == "-" else plistlib.loads(data) + if key not in value: + sys.exit(1) + print(value[key] if fmt == "raw" else "") +elif name == "security": + verb = args[0] + if verb == "create-keychain": + Path(args[-1]).write_bytes(b"keychain") + elif verb == "find-identity": + print(' 1) %s "Developer ID Application: Generated Fixture (%s)"' % (os.environ["SHIM_IDENTITY"], team)) + print(" 1 valid identities found") + elif verb == "delete-keychain": + Path(args[-1]).unlink() +elif name == "codesign": + target = Path(args[-1]) + if "--sign" in args and target.suffix == ".app": + (target / "Contents/_CodeSignature").mkdir(exist_ok=True) + (target / "Contents/_CodeSignature/CodeResources").write_bytes(b"sealed") + if "-d" in args: + sys.stderr.write("Executable=%s\nIdentifier=ai.storyteller.deckcraft.nightly\n" + "CodeDirectory v=20500 size=1 flags=0x10000(runtime) hashes=1+7 location=embedded\n" + "Authority=Developer ID Application: Generated Fixture (%s)\n" + "Timestamp=23 Nov 2026 at 17:00:00\nTeamIdentifier=%s\n" % (target, team, team)) +elif name == "xcrun": + if args[:2] == ["notarytool", "submit"]: + print(json.dumps({"id": "generated-id", "status": os.environ.get("SHIM_NOTARY", "Accepted")})) + elif args[:2] == ["stapler", "staple"]: + (Path(args[2]) / "Contents/CodeResources").write_bytes(b"ticket") + elif args[:2] == ["stapler", "validate"]: + sys.exit(0 if (Path(args[2]) / "Contents/CodeResources").is_file() else 1) +elif name == "spctl": + sys.stderr.write("%s: accepted\nsource=Notarized Developer ID\n" % args[-1]) +elif name == "cargo": + sys.exit(1) +# sleep: the retry waits pass at once. +""" + +TOOLS = ("uname", "lipo", "ditto", "plutil", "security", "codesign", "xcrun", "spctl", "cargo", "sleep") + + +class Fixture: + def __init__(self, test): + self.directory = tempfile.TemporaryDirectory() + test.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name).resolve() + self.bin = self.root / "bin" + self.bin.mkdir() + shim = self.bin / "shim.py" + shim.write_text(SHIM) + for tool in TOOLS: + path = self.bin / tool + path.write_text(f"#!{sys.executable}\nimport sys\nsys.argv[0] = {str(path)!r}\nexec(compile(open({str(shim)!r}).read(), 'shim', 'exec'), {{'__name__': '__main__'}})\n") + path.chmod(0o755) + self.log = self.root / "tools.log" + self.ran = self.root / "payload-ran" + self.temp = self.root / "runner-temp" + self.temp.mkdir() + self.dist = self.root / "unsigned" + self.dist.mkdir() + self.signed = self.root / "signed" + self.signed.mkdir() + self.input = self.dist / ASSET + self.output = self.signed / ASSET + # Every script runs from a directory with modules a Python helper must not import (-I). + self.cwd = self.root / "cwd" + self.cwd.mkdir() + self.hijacked = self.root / "hijacked" + for module in ("shutil", "zipfile", "stat"): + (self.cwd / f"{module}.py").write_text(f"open({str(self.hijacked)!r}, 'a').write({module!r})\n") + + def add_entry(self, info, data=b""): + """Append one raw entry to the input archive.""" + with zipfile.ZipFile(self.input, "a") as z: + z.writestr(info, data) + + def bundle(self, version=VERSION, extra=None, gui=None): + """The archive nightly.sh makes: the real template through the real plist helper.""" + stage = self.root / "stage" + shutil.rmtree(stage, ignore_errors=True) + app = stage / APP + (app / "Contents/MacOS").mkdir(parents=True) + (app / "Contents/Resources").mkdir() + exe = app / "Contents/MacOS/DeckCraft" + exe.write_text(gui or f"#!/bin/sh\ntouch {self.ran}\necho 'DeckCraft {version} (nightly-v1)'\n") + exe.chmod(0o755) + (app / "Contents/Resources/deckcraft-nightly.icns").write_bytes(b"generated icon") + rendered = PLIST.render((HERE / "Info.plist.in").read_bytes(), version, COMMIT) + (app / "Contents/Info.plist").write_bytes(rendered) + for relative, data in (extra or {}).items(): + (app / relative).write_bytes(data) + (app / relative).chmod(0o755) + if self.input.exists(): + self.input.unlink() + with zipfile.ZipFile(self.input, "x") as z: + for path in sorted([app] + list(app.rglob("*"))): + arc = (Path(APP) / path.relative_to(app)).as_posix() + info = zipfile.ZipInfo(arc + ("/" if path.is_dir() else "")) + info.external_attr = (path.stat().st_mode & 0xFFFF) << 16 + z.writestr(info, b"" if path.is_dir() else path.read_bytes()) + return self.input + + def env(self, **changes): + env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.root), "SHIM_LOG": str(self.log), + "SHIM_TEAM": TEAM, "SHIM_IDENTITY": IDENTITY, "RUNNER_TEMP": str(self.temp), **SECRETS} + env.update(changes) + return {key: value for key, value in env.items() if value is not None} + + def run(self, script, *args, **env): + if self.log.exists(): + self.log.unlink() + return subprocess.run(["bash", str(HERE / script), *map(str, args)], env=self.env(**env), cwd=self.cwd, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120) + + def sign(self, **env): + return self.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.input, "--output", self.output, **env) + + def calls(self): + if not self.log.exists(): + return [] + return [json.loads(line) for line in self.log.read_text().splitlines()] + + +def lib(function, *args): + """Run one nightly-lib.sh function; returns (exit status, stdout).""" + script = f'. {str(HERE / "nightly-lib.sh")!r}; {function} "$@"' + result = subprocess.run(["bash", "-c", script, "lib", *args], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) + return result.returncode, result.stdout.strip() + + +DETAILS = (f"Identifier=ai.storyteller.deckcraft.nightly\nCodeDirectory v=20500 size=1 flags=0x10000(runtime) hashes=1\n" + f"Authority=Developer ID Application: Generated Fixture ({TEAM})\nAuthority=Developer ID Certification Authority\n" + f"Timestamp=23 Nov 2026\nTeamIdentifier={TEAM}\n") + + +class Checks(unittest.TestCase): + def test_the_version_comes_only_from_a_prepared_nightly_asset_name(self): + self.assertEqual(lib("mac_nightly_version_from_asset", ASSET), (0, VERSION)) + for name in (f"deckcraft-0.23.1-macos-aarch64.zip", f"deckcraft-{VERSION}-macos-universal-nightly.zip", + f"deckcraft-{VERSION}-linux-x86_64-nightly.tar.gz", ASSET.replace(".g", ".x"), "../" + ASSET): + with self.subTest(name=name): + self.assertNotEqual(lib("mac_nightly_version_from_asset", name)[0], 0) + + def test_signature_needs_every_part_of_the_developer_id_signature(self): + self.assertEqual(lib("mac_nightly_check_signature", DETAILS, TEAM)[0], 0) + for broken in (DETAILS.replace("flags=0x10000(runtime)", "flags=0x0(none)"), + DETAILS.replace("Timestamp=23 Nov 2026\n", "Signed Time=23 Nov 2026\n"), + "Identifier=deckcraft-1234\nSignature=adhoc\nTeamIdentifier=not set\n", + DETAILS.replace("ai.storyteller.deckcraft.nightly", "ai.storyteller.deckcraft"), + DETAILS.replace("ai.storyteller.deckcraft.nightly", "aiXstorytellerXdeckcraftXnightly")): + with self.subTest(broken=broken): + self.assertNotEqual(lib("mac_nightly_check_signature", broken, TEAM)[0], 0) + self.assertNotEqual(lib("mac_nightly_check_signature", DETAILS, "ZZZZZ99999")[0], 0, "another team") + + def test_gatekeeper_must_accept_the_bundle_as_notarized(self): + self.assertEqual(lib("mac_nightly_check_assessment", "x.app: accepted\nsource=Notarized Developer ID\n")[0], 0) + for text in ("x.app: accepted\nsource=Developer ID\n", "x.app: rejected\nsource=Unnotarized Developer ID\n"): + with self.subTest(text=text): + self.assertNotEqual(lib("mac_nightly_check_assessment", text)[0], 0) + + def test_the_imported_identity_must_be_a_developer_id_of_the_team(self): + line = f' 1) {IDENTITY} "Developer ID Application: Generated Fixture ({TEAM})"' + self.assertEqual(lib("mac_nightly_identity_is_team", line, IDENTITY, TEAM)[0], 0) + self.assertNotEqual(lib("mac_nightly_identity_is_team", line, IDENTITY, "ZZZZZ99999")[0], 0) + self.assertNotEqual(lib("mac_nightly_identity_is_team", line.replace("Developer ID Application", "Apple Development"), IDENTITY, TEAM)[0], 0) + + +class Sign(unittest.TestCase): + def setUp(self): + self.f = Fixture(self) + self.f.bundle() + self.unsigned = self.f.input.read_bytes() + + def assert_refused_untouched(self, result, signed=False): + self.assertNotEqual(result.returncode, 0, result.stdout) + self.assertFalse(self.f.output.exists()) + self.assertEqual(self.f.input.read_bytes(), self.unsigned) + self.assertFalse(self.f.ran.exists(), "the payload must never run in the signing step") + names = [call[0] for call in self.f.calls()] + self.assertNotIn("cargo", names) + if not signed: + self.assertNotIn("codesign", names) + self.assertNotIn("xcrun", names) + self.assertEqual(list(self.f.temp.iterdir()), [], "the work directory and keychain are removed") + + def test_signs_notarizes_and_staples_without_running_the_payload(self): + result = self.f.sign() + self.assertEqual(result.returncode, 0, result.stdout) + self.assertFalse(self.f.hijacked.exists(), "helpers run isolated (python3 -I) beside the secrets") + calls = self.f.calls() + names = [call[0] for call in calls] + self.assertNotIn("cargo", names) + self.assertFalse(self.f.ran.exists(), "the payload must never run in the signing step") + self.assertEqual(self.f.input.read_bytes(), self.unsigned) + signs = [call for call in calls if call[0] == "codesign" and "--sign" in call] + self.assertEqual([Path(call[-1]).name for call in signs], ["DeckCraft", APP], "inside-out: executable, then bundle") + for call in signs: + for flag in ("--force", "--timestamp", "runtime", str(HERE / "entitlements.plist"), IDENTITY): + self.assertIn(flag, call) + order = [" ".join(call[:3]) for call in calls] + submit = order.index("xcrun notarytool submit") + staple = order.index("xcrun stapler staple") + self.assertLess(max(i for i, call in enumerate(calls) if call[0] == "codesign" and "--sign" in call), submit) + self.assertLess(submit, staple) + final = [i for i, call in enumerate(calls) if call[0] == "ditto" and "-c" in call][-1] + self.assertLess(staple, final, "the final archive carries the stapled ticket") + self.assertIn("--noextattr", calls[final]) + self.assertIn(["security", "delete-keychain"], [call[:2] for call in calls]) + self.assertEqual(list(self.f.temp.iterdir()), [], "the work directory and keychain are removed") + with zipfile.ZipFile(self.f.output) as z: + names = set(z.namelist()) + self.assertIn(f"{APP}/Contents/CodeResources", names, "stapled ticket inside the bundle") + self.assertIn(f"{APP}/Contents/_CodeSignature/CodeResources", names) + self.assertTrue(all(name.startswith(APP) for name in names)) + mode = z.getinfo(f"{APP}/Contents/MacOS/DeckCraft").external_attr >> 16 + self.assertTrue(mode & stat.S_IXUSR) + + def test_every_signing_and_notarization_secret_is_required(self): + for name in SECRETS: + with self.subTest(missing=name): + self.assert_refused_untouched(self.f.sign(**{name: None})) + self.assertEqual(self.f.calls(), [], "no tool runs before the configuration is complete") + self.assert_refused_untouched(self.f.sign(NIGHTLY_APPLE_TEAM_ID="ZZZZZ99999")) + self.assert_refused_untouched(self.f.sign(APPLE_TEAM_ID="not-a-team")) + + def test_refuses_another_team_s_identity(self): + self.assert_refused_untouched(self.f.sign(SHIM_TEAM="ZZZZZ99999")) + + def test_never_replaces_an_output_or_renames_the_asset(self): + self.f.output.write_bytes(b"generated existing artifact") + result = self.f.sign() + self.assertNotEqual(result.returncode, 0) + self.assertEqual(self.f.output.read_bytes(), b"generated existing artifact") + self.f.output.unlink() + renamed = self.f.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.f.input, "--output", self.f.signed / "other.zip") + self.assertNotEqual(renamed.returncode, 0) + relative = self.f.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.f.input.name, "--output", self.f.output) + self.assertNotEqual(relative.returncode, 0) + self.assertEqual(list(self.f.signed.iterdir()), []) + + def test_refuses_a_payload_that_is_not_the_exact_gui_only_nightly(self): + cases = { + "cli": dict(extra={"Contents/MacOS/deckcraft-cli": b"generated cli"}), + "version": dict(version=VERSION.replace("4567", "4568")), + } + for label, change in cases.items(): + with self.subTest(label=label): + self.f.bundle(**change) + self.unsigned = self.f.input.read_bytes() + self.assert_refused_untouched(self.f.sign()) + + def test_refuses_links_traversal_and_foreign_entries_before_unpacking(self): + link = zipfile.ZipInfo(f"{APP}/Contents/Resources/link") + link.external_attr = (stat.S_IFLNK | 0o777) << 16 + fifo = zipfile.ZipInfo(f"{APP}/Contents/Resources/fifo") + fifo.external_attr = (stat.S_IFIFO | 0o644) << 16 + for label, info in (("link", link), ("special", fifo), ("traversal", zipfile.ZipInfo(f"{APP}/../outside")), + ("absolute", zipfile.ZipInfo("/tmp/outside")), ("foreign root", zipfile.ZipInfo("Other.app/x"))): + with self.subTest(label=label): + self.f.bundle() + self.f.add_entry(info, b"/etc/passwd") + self.unsigned = self.f.input.read_bytes() + result = self.f.sign() + self.assert_refused_untouched(result) + self.assertNotIn("ditto", [call[0] for call in self.f.calls()], "refused before unpacking") + + def test_a_rejected_notarization_publishes_nothing_and_removes_the_keychain(self): + result = self.f.sign(SHIM_NOTARY="Invalid") + self.assert_refused_untouched(result, signed=True) + self.assertIn(["xcrun", "notarytool", "log"], [call[:3] for call in self.f.calls()]) + self.assertNotIn(["xcrun", "stapler", "staple"], [call[:3] for call in self.f.calls()]) + + +class Verify(unittest.TestCase): + def setUp(self): + self.f = Fixture(self) + + def verify(self, *args, **env): + return self.f.run("nightly-verify.sh", "--input", self.f.input, *args, **{name: None for name in SECRETS}, **env) + + def test_asks_the_gui_its_version_with_an_empty_environment(self): + self.f.bundle(gui=f"#!/bin/sh\n[ -z \"$INHERITED\" ] || exit 9\necho 'DeckCraft {VERSION} (nightly-v1)'\n") + result = self.verify("--expect", "unsigned", INHERITED="generated") + self.assertEqual(result.returncode, 0, result.stdout) + self.f.bundle(gui="#!/bin/sh\necho 'DeckCraft 0.23.1 (stable)'\n") + self.assertNotEqual(self.verify("--expect", "unsigned").returncode, 0) + + def test_the_launcher_profile_form_must_answer_promptly_and_cleanly(self): + answer = f"echo 'DeckCraft {VERSION} (nightly-v1)'" + # The shared producer smoke's exact form, with a fresh profile directory. + exact = ('#!/bin/sh\nif [ "$1" = --launch-profile ]; then\n' + ' [ "$#" = 5 ] && [ "$2" = nightly-v1 ] && [ "$3" = --profile-root ] && [ -d "$4" ] && [ "$5" = --version ] || exit 7\n' + f'fi\n{answer}\n') + self.f.bundle(gui=exact) + result = self.verify("--expect", "unsigned") + self.assertEqual(result.returncode, 0, result.stdout) + hangs = f'#!/bin/sh\n[ "$1" != --launch-profile ] || exec /bin/sleep 60\n{answer}\n' + self.f.bundle(gui=hangs) + started = time.monotonic() + result = self.verify("--expect", "unsigned") + self.assertNotEqual(result.returncode, 0) + self.assertIn("within 15 s", result.stdout) + self.assertLess(time.monotonic() - started, 45, "a hanging query is ended, not waited for") + noisy = f'#!/bin/sh\n[ "$1" != --launch-profile ] || echo refusal >&2\n{answer}\n' + self.f.bundle(gui=noisy) + result = self.verify("--expect", "unsigned") + self.assertNotEqual(result.returncode, 0) + self.assertIn("standard error", result.stdout) + + def test_a_signed_check_needs_the_signature_ticket_and_team(self): + self.f.bundle() + self.assertNotEqual(self.verify("--expect", "signed").returncode, 0, "no team to check against") + self.assertNotEqual(self.verify("--expect", "signed", "--team", TEAM).returncode, 0, "no stapled ticket") + self.f.bundle(extra={"Contents/CodeResources": b"ticket"}) + self.assertEqual(self.verify("--expect", "signed", "--team", TEAM).returncode, 0) + self.assertNotEqual(self.verify("--expect", "signed", "--team", TEAM, SHIM_TEAM="ZZZZZ99999").returncode, 0) + + def test_refuses_to_run_the_payload_beside_signing_material(self): + self.f.bundle() + for name in ("APPLE_PASSWORD", "APPLE_CERTIFICATE", "MACOS_KEYCHAIN"): + with self.subTest(name=name): + result = self.f.run("nightly-verify.sh", "--input", self.f.input, "--expect", "unsigned", + **{**{key: None for key in SECRETS}, name: "generated"}) + self.assertNotEqual(result.returncode, 0) + self.assertFalse(self.f.ran.exists()) + self.assertEqual(self.f.calls(), []) + + +class Build(unittest.TestCase): + def test_compilation_refuses_signing_material_before_building(self): + f = Fixture(self) + for name in ("APPLE_CERTIFICATE", "APPLE_PASSWORD", "MACOS_SIGN_IDENTITY", "WINDOWS_CERTIFICATE", "AZURE_CLIENT_SECRET", "LINUX_SIGNING_KEY"): + with self.subTest(name=name): + result = f.run("nightly.sh", "--arch", "aarch64", **{**{key: None for key in SECRETS}, name: "generated"}, + DECKCRAFT_BUILD_CHANNEL="nightly-v1", DECKCRAFT_VERSION=VERSION) + self.assertNotEqual(result.returncode, 0) + self.assertIn(name, result.stdout) + self.assertNotIn("cargo", [call[0] for call in f.calls()]) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/nightly-archive.py b/packaging/nightly-archive.py new file mode 100644 index 000000000..4d84b9acc --- /dev/null +++ b/packaging/nightly-archive.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""Flat Linux archive policy, invoked from its private owned build cwd. + +The stage and archive must both remain under that independently chosen root. +No native build, platform signing, or malicious-same-UID sandbox is implied. +""" +import grp +import gzip +import os +import pathlib +import pwd +import re +import stat +import sys +import tarfile + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) +from nightly_paths import OwnedBuildRoot + +APP_DOCS = {"README.md", "LICENSE", "LICENSE-MIT", "LICENSE-APACHE", "COPYRIGHT", "NOTICE", "ATTRIBUTION.md"} +MAX_MEMBER_BYTES = 512 * 1024 * 1024 +MAX_TOTAL_BYTES = 1024 * 1024 * 1024 +MAX_MEMBERS = 128 + + +def notice(name): + return name in APP_DOCS or re.fullmatch(r"OFL-[A-Za-z0-9_.-]+\.txt", name) is not None + + +def checked_entries(root, stage): + entries = sorted(root.children(stage, MAX_MEMBERS), key=lambda item: item.name) + folded = set() + total = 0 + for entry in entries: + name = entry.name + # `deckcraft` is the launcher and `deckcraft-bin` the GUI it starts (nightly.sh); the icon + # and the notices are the rest of the flat archive. + if name not in {"deckcraft", "deckcraft-bin", "deckcraft-nightly.png"} and not notice(name): + raise ValueError(f"unexpected nightly member: {name}") + if len(name.encode("utf-8")) > 100: + raise ValueError(f"nightly member must be a short regular file: {name}") + with root.reader(entry, MAX_MEMBER_BYTES) as stream: + total += os.fstat(stream.fileno()).st_size + if total > MAX_TOTAL_BYTES: + raise ValueError("nightly stage exceeds its read bound") + if name.casefold() in folded: + raise ValueError(f"case-colliding nightly member: {name}") + folded.add(name.casefold()) + required = {"deckcraft", "deckcraft-bin", "deckcraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md"} + if not required.issubset({item.name for item in entries}): + raise ValueError("required GUI/icon/notices missing") + return entries + + +def member_info(stage_root, name, incoming): + """Header for one stage file, built from the file this run opened rather than from the archive. + + Members are flat names that resolve directly inside the stage they came from. + """ + if os.path.isabs(name) or os.path.basename(name) != name or name in ("", ".", ".."): + raise ValueError(f"nightly member name must be a flat file name: {name}") + destination = os.path.realpath(os.path.join(stage_root, name)) + if not destination.startswith(stage_root + os.sep) or os.path.dirname(destination) != stage_root: + raise ValueError(f"nightly member resolves outside its stage: {name}") + status = os.fstat(incoming.fileno()) + if not stat.S_ISREG(status.st_mode): + raise ValueError(f"nightly member must be a regular file: {name}") + # The same fields TarFile.gettarinfo records for a regular file. + # The header keeps the validated stage name, not the resolved one: a stage symlink must + # never rename a member or leave a required name out of the archive. + info = tarfile.TarInfo(name) + info.type = tarfile.REGTYPE + info.mode = stat.S_IMODE(status.st_mode) + info.uid, info.gid = status.st_uid, status.st_gid + info.size = status.st_size + info.mtime = status.st_mtime + try: + info.uname = pwd.getpwuid(status.st_uid).pw_name + except KeyError: + pass + try: + info.gname = grp.getgrgid(status.st_gid).gr_name + except KeyError: + pass + return info + + +def verify_headers(root, output): + # Bounded ordinary headers, not a transparent PAX/GNU-normalizing reader. + total = 0 + count = 0 + with root.reader(output, MAX_TOTAL_BYTES) as incoming, gzip.GzipFile(fileobj=incoming) as stream: + while True: + header = stream.read(512) + if header == b"\0" * 512: + break + if len(header) != 512 or header[156:157] not in {b"0", b"\0"}: + raise ValueError("non-ordinary TAR record was emitted") + size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8) + count += 1 + total += size + if count > MAX_MEMBERS or size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES: + raise ValueError("archive exceeds its bounded member budget") + remaining = ((size + 511) // 512) * 512 + while remaining: + chunk = stream.read(min(remaining, 1024 * 1024)) + if not chunk: + raise ValueError("truncated TAR member") + remaining -= len(chunk) + + +def linux_archive(stage, output): + with OwnedBuildRoot() as root: + entries = checked_entries(root, stage) + stage_root = os.path.realpath(os.path.join(root.directory, stage)) + total = 0 + with root.create(output) as outgoing: + with tarfile.open(fileobj=outgoing, mode="w:gz", format=tarfile.USTAR_FORMAT) as archive: + for entry in entries: + with root.reader(entry, MAX_MEMBER_BYTES) as incoming: + info = member_info(stage_root, entry.name, incoming) + total += info.size + if info.size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES: + raise ValueError("nightly stage grew beyond its read bound") + archive.addfile(info, incoming) + outgoing.flush() + os.fsync(outgoing.fileno()) + verify_headers(root, output) + + +if __name__ == "__main__": + if len(sys.argv) != 4 or sys.argv[1] != "linux": + raise SystemExit("usage: nightly-archive.py linux STAGE OUTPUT (from owned private build cwd)") + linux_archive(pathlib.Path(sys.argv[2]), pathlib.Path(sys.argv[3])) diff --git a/packaging/nightly-common.sh b/packaging/nightly-common.sh new file mode 100644 index 000000000..1e5518947 --- /dev/null +++ b/packaging/nightly-common.sh @@ -0,0 +1,95 @@ +# shellcheck shell=bash +# Shared setup for app-owned native nightly archives; stable packaging does not source this file. + +nightly_die() { printf 'error: %s\n' "$*" >&2; exit 2; } + +nightly_init() { + local os="$1" arch="$2" target="$3" date_digits + [[ "${DECKCRAFT_BUILD_CHANNEL:-}" == nightly-v1 ]] || nightly_die 'DECKCRAFT_BUILD_CHANNEL must be nightly-v1' + [[ "${DECKCRAFT_VERSION:-}" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || nightly_die 'an exact prepared nightly version is required' + [[ "${DECKCRAFT_BUILD_SHA:-}" =~ ^[0-9a-f]{40}$ ]] || nightly_die 'an exact source commit is required' + [[ "${DECKCRAFT_VERSION##*.g}" == "${DECKCRAFT_BUILD_SHA:0:12}" ]] || nightly_die 'version/source commit mismatch' + [[ "${DECKCRAFT_BUILD_DATE:-}" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || nightly_die 'the original run-created UTC date is required' + date_digits="${DECKCRAFT_VERSION#*-nightly.}" + date_digits="${date_digits%%.*}" + [[ "${DECKCRAFT_BUILD_DATE//-/}" == "$date_digits" ]] || nightly_die 'version/original-run date mismatch' + [[ "${CARGO_TARGET_DIR:-}" == /* && "$CARGO_TARGET_DIR" != / ]] || nightly_die 'an absolute owned CARGO_TARGET_DIR base is required' + [[ "${DIST:-}" == /* && "$DIST" != / ]] || nightly_die 'an absolute DIST output directory is required' + [[ "/$CARGO_TARGET_DIR/" != *'/../'* && "/$DIST/" != *'/../'* ]] || nightly_die 'output paths must not contain parent traversal' + ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$DECKCRAFT_BUILD_SHA" ]] || nightly_die 'prepared source is not the checked-out commit' + [[ -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'nightly packaging requires the frozen clean source' + if [[ -n "${CRAFT_FONTS_DIR:-}" && ! -d "$CRAFT_FONTS_DIR/fonts" ]]; then + nightly_die 'declared CRAFT_FONTS_DIR has no fonts directory' + fi + # common.sh retains the established notice copier. Required values above prohibit its stable fallbacks. + # shellcheck source=common.sh + . "$ROOT/packaging/common.sh" + export CARGO_TARGET_DIR="$CARGO_TARGET_DIR/nightly-v1/$os-$arch" + NIGHTLY_RUST_TARGET="$target" + mkdir -p "$CARGO_TARGET_DIR" + NIGHTLY_WORK="$(mktemp -d "$CARGO_TARGET_DIR/nightly-package.XXXXXX")" + trap 'rm -rf -- "$NIGHTLY_WORK"' EXIT +} + +# Compile only: macOS runs the version query after signing. +nightly_compile_gui() { + # The guard sits here as well as in the entrypoints: no caller may compile with signing material. + nightly_refuse_signing_env + (cd "$ROOT" && cargo build --release --locked -p deckcraft --target "$NIGHTLY_RUST_TARGET") + NIGHTLY_GUI="$CARGO_TARGET_DIR/$NIGHTLY_RUST_TARGET/release/deckcraft" + [[ -f "$NIGHTLY_GUI" && ! -L "$NIGHTLY_GUI" ]] || nightly_die 'the owned GUI build did not produce a regular executable' + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$DECKCRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the build' +} + +nightly_build_gui() { + nightly_compile_gui + local actual + actual="$("$NIGHTLY_GUI" --version)" || nightly_die 'side-effect-free nightly version verification failed' + # The desktop's version query answers `DeckCraft (nightly-v1)`; the exact line, not a + # prefix, so a stable or mismatched build cannot pass. + [[ "$actual" == "DeckCraft $VERSION (nightly-v1)" ]] || nightly_die 'the built version/flavor is not the prepared identity' + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$DECKCRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the version query' +} + +# Signing material never reaches compilation (the Windows -CheckBuildEnvironment rule). +nightly_refuse_signing_env() { + local name + # The signing names release.yml passes, for every platform, and import-cert.sh's outputs. + for name in APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID \ + MACOS_SIGN_IDENTITY MACOS_KEYCHAIN WINDOWS_CERTIFICATE WINDOWS_CERTIFICATE_PASSWORD AZURE_TENANT_ID AZURE_CLIENT_ID \ + AZURE_CLIENT_SECRET AZURE_SIGNING_ENDPOINT AZURE_SIGNING_ACCOUNT AZURE_CERT_PROFILE LINUX_SIGNING_KEY; do + [[ -z "${!name:-}" ]] || nightly_die "compilation must not receive signing configuration ($name); sign in the separate trusted step" + done +} + +nightly_copy_notices() { + local destination="$1" required + for required in README.md LICENSE-MIT LICENSE-APACHE NOTICE ATTRIBUTION.md; do + [[ -f "$ROOT/$required" && ! -L "$ROOT/$required" ]] || nightly_die "missing regular app notice: $required" + done + copy_docs "$destination" + cp "$ROOT/ATTRIBUTION.md" "$destination/" +} + +nightly_publish_archive() { + # Exclusive creation: never replace an existing artifact, even if another writer raced the preflight. + python3 -I - "$1" "$2" <<'PY' +import os, shutil, sys +source, destination = sys.argv[1:] +created = False +try: + # Open the input first: a missing source must not leave an empty final artifact. + with open(source, 'rb') as incoming: + with open(destination, 'xb') as output: + created = True + shutil.copyfileobj(incoming, output, length=1024 * 1024) + output.flush() + os.fsync(output.fileno()) +except BaseException: + if created: + os.unlink(destination) + raise +PY + printf 'Nightly artifact: %s\n' "$2" +} diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py new file mode 100755 index 000000000..fe60b6cbb --- /dev/null +++ b/packaging/nightly-release-tests.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Local regression checks for DeckCraft nightly workflow and policy contracts.""" +import copy +import json +from pathlib import Path +import re +import unittest + +ROOT = Path(__file__).resolve().parents[1] +INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json" + +NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64") +# Each platform's one trust field in policy v3, and the public stable identity it must name. +NIGHTLY_TRUST = { + "windows-x86_64": ("publisher_subject", + "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"), + "linux-x86_64": ("fingerprint", "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"), + "macos-aarch64": ("apple_team_id", "DJ6XS33FX8"), +} + +# Mirrors the storytold release-managers team (id 19837241) minus echelon-robot. +# Update by PR, in the caller and the policy, when the team changes. +RELEASE_MANAGERS = ["bflatastic", "dylanmtaylor", "echelon", "FredApps", "skylartaylor"] + + +def assert_nightly_serialization(source): + """Fail closed unless this app's plain root concurrency block retains its contract.""" + lines = source.splitlines() + roots = [index for index, line in enumerate(lines) if line.startswith("concurrency:")] + if len(roots) != 1 or lines[roots[0]] != "concurrency:": + raise ValueError("one plain root concurrency block is required") + values = {} + for line in lines[roots[0] + 1:]: + if not line.strip() or line.lstrip().startswith("#"): + continue + if not line[0].isspace(): + break + row = re.fullmatch(r" (group|cancel-in-progress): ([^#]+?)(?: +#.*)?", line) + if row is None or row[1] in values: + raise ValueError("malformed or duplicate nightly concurrency entry") + values[row[1]] = row[2].rstrip() + if values != {"group": "deckcraft-nightly-release", "cancel-in-progress": "false"}: + raise ValueError("nightly serialization must use its stable group and no cancellation") + + +def job_conditions(jobs): + """Each job-level `if:` as (block indicator or None, the whole expression YAML would read).""" + lines = jobs.splitlines() + found = [] + for index, line in enumerate(lines): + head = re.fullmatch(r" if:(?: (.*))?", line) + if head is None: + continue + value = (head[1] or "").strip() + continuation = [] + for follow in lines[index + 1:]: + if follow.strip() and len(follow) - len(follow.lstrip(" ")) <= 4: + break + continuation.append(follow.strip()) + indicator = value if re.fullmatch(r"[>|][+-]?", value) else None + parts = continuation if indicator else [value] + continuation + found.append((indicator, " ".join(part for part in parts if part))) + return found + + +def producer_platforms(source): + """Read the one producer job's literal platform list; a narrow source guard, not YAML.""" + rows = re.findall(r"(?m)^ platforms: (.*)$", source) + if len(rows) != 1: + raise ValueError("exactly one producer platform list is required") + literal = re.fullmatch(r"'(\[[^']*\])'", rows[0]) + if literal is None: + raise ValueError("the platform list must be one single-quoted literal") + platforms = json.loads(literal[1]) + if not isinstance(platforms, list) or json.dumps(platforms, separators=(",", ":")) != literal[1]: + raise ValueError("the platform list must be compact JSON") + if len(set(platforms)) != len(platforms) or not set(platforms) <= set(NIGHTLY_PLATFORMS): + raise ValueError("platforms must be distinct known nightly targets") + if "windows-x86_64" not in platforms: + raise ValueError("the Windows row stays in the producer") + return platforms + + +def reviewed_manual_actors(caller_source, policy): + """The one reviewed manual-actor list, identical in the producer caller and the policy.""" + rows = re.findall(r"(?m)^ manual-actors: '(\[[^']*\])'$", caller_source) + if len(rows) != 1: + raise ValueError("exactly one literal manual-actors list is required") + caller = json.loads(rows[0]) + if caller != policy["manual_actors"]: + raise ValueError("caller and policy must grant the same actors in the same order") + if caller != RELEASE_MANAGERS: + raise ValueError("manual actors must be exactly the reviewed release managers") + if caller != sorted(caller, key=str.lower) or len({login.lower() for login in caller}) != len(caller): + raise ValueError("manual actors must be distinct and sorted case-insensitively") + if set(caller) & {login for login in policy["automatic_signer_actors"]}: + raise ValueError("manual and automatic actors overlap") + return caller + + +def caller_pin(name): + return re.findall(r"(?m)^ tooling-revision: ([0-9a-f]{40})$", (ROOT / ".github/workflows" / name).read_text())[0] + + +class TrustedSourcePreparation(unittest.TestCase): + def test_one_producer_and_one_signer_job_carry_every_platform(self): + for name, job in (("nightly.yml", "unsigned"), ("nightly-sign.yml", "release")): + jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1] + with self.subTest(workflow=name): + self.assertEqual(re.findall(r"(?m)^ ([^\s#][^:]*):", jobs), [job], + "a platform is a list entry, not a separately activatable job") + signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + self.assertNotRegex(signer, r"(?m)^\s*platforms?:", "the release policy, not the caller, admits platforms") + + def test_malformed_or_narrowed_platform_lists_are_rejected(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + current = "platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"macos-aarch64\"]'" + self.assertIn(current, source) + for new in ("platforms: '[\"linux-x86_64\"]'", + "platforms: '[\"linux-x86_64\",\"macos-aarch64\"]'", + "platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"linux-x86_64\"]'", + "platforms: '[\"windows-x86_64\",\"macos-x86_64\"]'", + "platforms: '[\"windows-x86_64\",\"linux-arm64\"]'", + "platforms: '[\"windows-x86_64\", \"linux-x86_64\"]'", + "platforms: [\"windows-x86_64\",\"linux-x86_64\"]", + "platforms: ${{ vars.NIGHTLY_PLATFORMS }}", + "platforms: '{\"windows-x86_64\":1}'", + current + "\n " + current): + with self.subTest(change=new), self.assertRaises(ValueError): + producer_platforms(source.replace(current, new)) + with self.assertRaises(ValueError): + producer_platforms(source.replace(" " + current + "\n", "")) + + def test_continuation_lines_of_any_scalar_form_reach_the_guard_checks(self): + for name in ("nightly.yml", "nightly-sign.yml"): + source = (ROOT / ".github/workflows" / name).read_text() + expected = NightlyEnabledCallers.GUARDS[name] + guard = re.search(r"(?m)^ if: >-\n(?: [^\n]*\n)+", source)[0] + for replacement in (guard + " || true\n", " if: " + expected + "\n || true\n"): + jobs = source.replace(guard, replacement).split("\njobs:\n", 1)[1] + with self.subTest(workflow=name, replacement=replacement[-30:]): + (indicator, expression), = job_conditions(jobs) + self.assertFalse(indicator == ">-" and " ".join(expression.split()) == expected) + + def test_no_nightly_schedule_is_registered(self): + for name, event in (("nightly.yml", "workflow_dispatch"), + ("nightly-sign.yml", "workflow_dispatch")): + source = (ROOT / ".github/workflows" / name).read_text() + events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0] + triggers = [line for line in events.splitlines() if line.startswith(" ") + and not line.startswith(" ") and line.strip() and not line.lstrip().startswith("#")] + with self.subTest(workflow=name): + self.assertEqual(triggers, [f" {event}:"], "schedule/activation needs explicit review") + + def test_signer_serialization_contract_is_enforced(self): + assert_nightly_serialization((ROOT / ".github/workflows/nightly-sign.yml").read_text()) + + def test_the_producer_declares_no_serialization_of_its_own(self): + # Only the signer serializes, because one protected release at a time is what the policy + # needs. The producer is a manual, stateless dispatch, so a concurrency block there would + # be a second, unreviewed gate; this keeps one from slipping in unnoticed. + source = (ROOT / ".github/workflows/nightly.yml").read_text() + executable = "\n".join(line for line in source.splitlines() if not line.lstrip().startswith("#")) + self.assertNotRegex(executable, r"(?m)^\s*concurrency:") + self.assertNotIn("cancel-in-progress", executable) + + def test_weakened_or_malformed_serialization_is_rejected(self): + source = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + for old, new in ( + ("cancel-in-progress: false", "cancel-in-progress: false\n queue: max"), + ("cancel-in-progress: false", "cancel-in-progress: true"), + ("cancel-in-progress: false", "cancel-in-progress: ${{ github.event_name == 'push' }}"), + ("cancel-in-progress: false\n", ""), + ("group: deckcraft-nightly-release", "group: ${{ github.run_id }}"), + ("group: deckcraft-nightly-release", "group: release-${{ github.ref }}"), + ("concurrency:\n", "concurrency: ${{ github.run_id }}\n"), + ("concurrency:\n", " concurrency:\n"), + ): + with self.subTest(change=new), self.assertRaises(ValueError): + assert_nightly_serialization(source.replace(old, new)) + + def test_no_cache_actions_or_cache_setup_options_in_app_trusted_closure(self): + for name in ("nightly.yml", "nightly-sign.yml"): + source = (ROOT / ".github/workflows" / name).read_text() + executable = "\n".join(line for line in source.splitlines() + if not line.lstrip().startswith("#")) + with self.subTest(workflow=name): + self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache") + self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:") + self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):") + self.assertNotIn("secrets.", executable) + + def test_both_callers_use_one_shared_pin_in_uses_and_tooling_revision(self): + pins = set() + for name, callee in (("nightly.yml", "nightly-unsigned.yml"), ("nightly-sign.yml", "nightly-release.yml")): + source = (ROOT / ".github/workflows" / name).read_text() + uses = re.findall(r"(?m)^ uses: storytold/craft-common-actions/\.github/workflows/" + + re.escape(callee) + r"@(\S+)$", source) + tooling = re.findall(r"(?m)^ tooling-revision: (\S+)$", source) + with self.subTest(workflow=name): + self.assertEqual(len(uses), 1) + self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match") + pins.update(uses) + self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit") + self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder") + + +class NightlyEnabledCallers(unittest.TestCase): + """Producer and signer run only in their exact context, for the reviewed manual actor.""" + + GUARDS = { + "nightly.yml": "github.repository == 'storytold/deckcraft' && github.ref == 'refs/heads/main' && " + "github.ref_type == 'branch' && (github.event_name == 'schedule' || " + "github.event_name == 'workflow_dispatch')", + "nightly-sign.yml": "github.repository == 'storytold/deckcraft' && github.event_name == 'workflow_dispatch' && " + "github.ref == 'refs/heads/release' && github.ref_type == 'branch'", + } + + def test_enabled_jobs_keep_exact_context_guards(self): + for name, expected in self.GUARDS.items(): + jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1] + guards = job_conditions(jobs) + with self.subTest(workflow=name): + self.assertEqual(len(guards), 1) + indicator, expression = guards[0] + self.assertEqual(indicator, ">-") + self.assertEqual(" ".join(expression.split()), expected, "guards may only change with review") + + def test_manual_actors_are_the_release_managers_in_caller_and_policy(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + policy = json.loads(INSTALLED_POLICY.read_text()) + self.assertEqual(reviewed_manual_actors(source, policy), RELEASE_MANAGERS) + self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule") + + def test_an_actor_outside_the_release_managers_is_refused(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + policy = json.loads(INSTALLED_POLICY.read_text()) + caller = json.dumps(RELEASE_MANAGERS, separators=(",", ":")) + widened = sorted(RELEASE_MANAGERS + ["echelon-robot"], key=str.lower) + for change in ("caller", "policy", "both", "order", "case"): + mutated_source, mutated_policy = source, copy.deepcopy(policy) + if change in ("caller", "both"): + mutated_source = source.replace(caller, json.dumps(widened, separators=(",", ":"))) + if change in ("policy", "both"): + mutated_policy["manual_actors"] = widened + if change == "order": + mutated_policy["manual_actors"] = list(reversed(RELEASE_MANAGERS)) + if change == "case": + mutated_policy["manual_actors"] = [login.lower() for login in RELEASE_MANAGERS] + with self.subTest(change=change), self.assertRaises(ValueError): + reviewed_manual_actors(mutated_source, mutated_policy) + + +class NightlyInstalledPolicy(unittest.TestCase): + """The installed v3 policy matches the callers, the repository and its documented sources.""" + + def setUp(self): + self.assertFalse(INSTALLED_POLICY.is_symlink()) + self.policy = json.loads(INSTALLED_POLICY.read_text()) + + def test_exact_v3_fields_and_repository_identity(self): + expected = {"schema", "repository", "repository_id", "producer_workflow_id", + "producer_workflow_path", "producer_tooling_revision", "producer_workflow_ref", + "signer_workflow_path", "signer_tooling_revision", "release_branch", "manual_actors", + "automatic_signer_actors", "max_age_seconds", "candidate_policy", + "max_artifact_bytes", "platforms"} + self.assertEqual(set(self.policy), expected) + self.assertEqual(self.policy["schema"], "craft-nightly-release-policy/v3") + self.assertEqual(self.policy["repository"], "storytold/deckcraft") + self.assertEqual(self.policy["release_branch"], "release") + self.assertIs(type(self.policy["repository_id"]), int) + self.assertGreater(self.policy["repository_id"], 0) + # producer_workflow_id is null until nightly.yml is registered on main; once set, it must be a positive int. + if self.policy["producer_workflow_id"] is not None: + self.assertIs(type(self.policy["producer_workflow_id"]), int) + self.assertGreater(self.policy["producer_workflow_id"], 0) + self.assertNotEqual(self.policy["producer_workflow_id"], + self.policy["candidate_policy"]["required_workflows"][0]["workflow_id"], + "the producer is not its own quality workflow") + + def test_paths_and_tooling_match_the_callers(self): + pin = caller_pin("nightly.yml") + self.assertEqual(caller_pin("nightly-sign.yml"), pin) + self.assertEqual(self.policy["producer_workflow_path"], ".github/workflows/nightly.yml") + self.assertEqual(self.policy["signer_workflow_path"], ".github/workflows/nightly-sign.yml") + self.assertEqual(self.policy["producer_tooling_revision"], pin) + self.assertEqual(self.policy["signer_tooling_revision"], pin) + self.assertEqual(self.policy["producer_workflow_ref"], + "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@" + pin) + + def test_platforms_and_trust_anchors(self): + built = producer_platforms((ROOT / ".github/workflows/nightly.yml").read_text()) + self.assertEqual(built, list(NIGHTLY_PLATFORMS)) + self.assertEqual(set(self.policy["platforms"]), set(built)) + for platform, (field, value) in NIGHTLY_TRUST.items(): + row = self.policy["platforms"][platform] + with self.subTest(platform=platform): + self.assertEqual(set(row), {"unsigned_artifact_name", "trust"}) + self.assertEqual(row["unsigned_artifact_name"], f"nightly-unsigned-{platform}") + self.assertEqual(row["trust"], {field: value}) + + def test_bounds(self): + self.assertIs(type(self.policy["max_age_seconds"]), int) + self.assertTrue(0 < self.policy["max_age_seconds"] <= 604800) + self.assertIs(type(self.policy["max_artifact_bytes"]), int) + self.assertTrue(0 < self.policy["max_artifact_bytes"] <= 16 * 1024 ** 3) + + def test_candidate_workflows_run_on_every_main_push(self): + candidate = self.policy["candidate_policy"] + self.assertEqual(set(candidate), {"schema", "epoch", "repository", "branch", "required_workflows", "sonar"}) + self.assertEqual(candidate["schema"], "craft-nightly-candidate-policy/v3") + self.assertEqual((candidate["repository"], candidate["branch"]), ("storytold/deckcraft", "main")) + self.assertTrue(isinstance(candidate["epoch"], str) and 0 < len(candidate["epoch"]) <= 128) + rows = candidate["required_workflows"] + self.assertTrue(rows) + for row in rows: + with self.subTest(workflow=row["workflow_path"]): + self.assertEqual(set(row), {"workflow_id", "workflow_path", "jobs"}) + self.assertIs(type(row["workflow_id"]), int) + self.assertNotEqual(row["workflow_path"], self.policy["producer_workflow_path"]) + source = (ROOT / row["workflow_path"]).read_text() + push = re.search(r"(?m)^ push:\n((?: .*\n)+)", source) + self.assertIsNotNone(push, "a required workflow must run on main pushes") + self.assertIn(" branches: [main]\n", push[1]) + self.assertNotRegex(push[1], r"paths", "a path filter would leave candidates without a run") + names = [job["name"] for job in row["jobs"]] + self.assertEqual(len(names), len(set(names))) + for job in row["jobs"]: + self.assertEqual(set(job), {"name", "app_id", "applicability"}) + self.assertEqual((job["app_id"], job["applicability"]), (15368, "required")) + + def test_sonar_identity_and_reviewed_scope(self): + sonar = self.policy["candidate_policy"]["sonar"] + properties = dict(line.split("=", 1) for line in (ROOT / "sonar-project.properties").read_text().splitlines() + if line and not line.startswith("#")) + self.assertEqual(sonar["organization"], properties["sonar.organization"]) + self.assertEqual(sonar["project"], properties["sonar.projectKey"]) + self.assertEqual((sonar["app_id"], sonar["check_name"]), (12526, "SonarCloud Code Analysis")) + self.assertEqual(sonar["details_url"], "https://sonarcloud.io/dashboard?id=" + sonar["project"] + "&branch=main") + accepted = {"bugs": "BUG", "vulnerabilities": "VULNERABILITY", "code_smells": "CODE_SMELL", + "security_rating": "VULNERABILITY", "new_security_rating": "VULNERABILITY"} + self.assertEqual({accepted[c["metric"]] for c in sonar["accepted_conditions"]}, set(sonar["issue_types"])) + metrics = [c["metric"] for c in sonar["accepted_conditions"] + sonar["required_conditions"]] + self.assertEqual(len(metrics), len(set(metrics))) + keys = [item["key"] for item in sonar["debt"]] + self.assertEqual(len(keys), len(set(keys))) + for item in sonar["debt"]: + with self.subTest(issue=item["key"]): + self.assertEqual(set(item), {"key", "rule", "component", "type", "severity", "hash"}) + self.assertTrue(item["component"].startswith(sonar["project"] + ":")) + self.assertIn(item["type"], sonar["issue_types"]) + self.assertRegex(item["hash"], r"^[0-9a-f]{32}$") + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/packaging/nightly-tests.py b/packaging/nightly-tests.py new file mode 100755 index 000000000..4d83735e8 --- /dev/null +++ b/packaging/nightly-tests.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +"""Run the existing synthetic packaging suites together; no app build or signing.""" +import importlib.util +from pathlib import Path +import subprocess +import unittest + +HERE = Path(__file__).resolve().parent + + +class LinuxLauncherContractTests(unittest.TestCase): + """The launchers' argv contract, proven by a recorder binary instead of a build.""" + + def test_every_linux_launcher_passes_the_profile(self): + for script in ("linux/nightly-launch-test.sh", "linux/nightly-arch-tar-test.sh"): + result = subprocess.run(["bash", str(HERE / script)], capture_output=True, text=True, timeout=120) + self.assertEqual(result.returncode, 0, f"{script}\n{result.stdout}\n{result.stderr}") + + +def main() -> int: + suite = unittest.TestSuite() + for name, relative in ( + ("deck_plist_suite", "macos/nightly_plist_tests.py"), + ("deck_release_dispatch_suite", "nightly-release-tests.py"), + ("deck_mac_sign_suite", "macos/nightly_sign_tests.py"), + ): + spec = importlib.util.spec_from_file_location(name, HERE / relative) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(module)) + suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(LinuxLauncherContractTests)) + return 0 if unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful() else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packaging/nightly_paths.py b/packaging/nightly_paths.py new file mode 100644 index 000000000..792198589 --- /dev/null +++ b/packaging/nightly_paths.py @@ -0,0 +1,139 @@ +"""POSIX packaging I/O rooted at a caller-owned private working directory. + +The build launcher chooses cwd independently of file arguments (Linux uses its +mktemp directory). This is not a sandbox against root or a malicious same-UID +caller, and inode-check/unlink cleanup is not an atomic replacement-race primitive. +""" +import contextlib +import os +from pathlib import Path +import stat + + +def _component(name): + # A descriptor-relative open must name exactly one entry in its directory. + if not name or name in (".", "..") or os.path.basename(name) != name: + raise ValueError("build path components must be single names") + return os.path.basename(name) + + +class OwnedBuildRoot: + def __enter__(self): + self.directory = Path.cwd() + self.fd = os.open(".", os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + info = os.fstat(self.fd) + if info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) & 0o077: + os.close(self.fd) + raise ValueError("packaging cwd must be an owned private build directory") + return self + + def __exit__(self, *_error): + os.close(self.fd) + + def _relative(self, path): + path = Path(path) + try: + relative = path.relative_to(self.directory) if path.is_absolute() else path + except ValueError as error: + raise ValueError("path is outside the owned build directory") from error + if not relative.parts or ".." in relative.parts: + raise ValueError("empty or parent-traversing build path") + # Check an independently selected root, never the supplied filename's parent. + try: + parent = (self.directory / relative).parent.resolve(strict=True) + except OSError as error: + raise ValueError("build path parent must exist") from error + if not parent.is_relative_to(self.directory): + raise ValueError("resolved path escapes the owned build directory") + return relative + + def _checked_parts(self, path): + relative = self._relative(path) + root = os.path.realpath(self.directory) + lexical = os.path.join(root, *relative.parts) + target = os.path.realpath(lexical) + if target == root or os.path.commonpath([root, target]) != root: + raise ValueError("resolved path escapes the owned build directory") + if target != lexical: + raise ValueError("build path must not pass through symlinks or aliases") + return [_component(part) for part in os.path.relpath(target, root).split(os.sep)] + + def _parent(self, path): + parts = self._checked_parts(path) + current = os.dup(self.fd) + try: + for part in parts[:-1]: + next_fd = os.open(_component(part), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=current) + os.close(current) + current = next_fd + return current, parts[-1] + except OSError as error: + os.close(current) + raise ValueError("build path parents must be non-symlink directories") from error + + @contextlib.contextmanager + def reader(self, path, limit): + parent, name = self._parent(path) + try: + try: + descriptor = os.open(_component(name), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent) + except OSError as error: + raise ValueError("build input must be a regular file without aliases") from error + finally: + os.close(parent) + info = os.fstat(descriptor) + if not stat.S_ISREG(info.st_mode) or info.st_size > limit: + os.close(descriptor) + raise ValueError("build input must be a regular file within its read bound") + with os.fdopen(descriptor, "rb") as stream: + yield stream + + def read_bytes(self, path, limit): + with self.reader(path, limit) as stream: + data = stream.read(limit + 1) + if len(data) > limit: + raise ValueError("build input grew beyond its read bound") + return data + + def children(self, path, limit): + relative = self._relative(path) + parent, name = self._parent(path) + try: + try: + descriptor = os.open(_component(name), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent) + except OSError as error: + raise ValueError("build stage must be a non-symlink directory") from error + finally: + os.close(parent) + try: + entries = [] + with os.scandir(descriptor) as iterator: + for entry in iterator: + if len(entries) >= limit: + raise ValueError("too many build stage members") + entries.append(self.directory / relative / entry.name) + return entries + finally: + os.close(descriptor) + + @contextlib.contextmanager + def create(self, path): + parent, name = self._parent(path) + name = _component(name) + try: + descriptor = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o666, dir_fd=parent) + info = os.fstat(descriptor) + identity = (info.st_dev, info.st_ino) + try: + with os.fdopen(descriptor, "wb") as stream: + yield stream + except BaseException: + try: + current = os.stat(name, dir_fd=parent, follow_symlinks=False) + if (current.st_dev, current.st_ino) == identity: + os.unlink(_component(name), dir_fd=parent) + except FileNotFoundError: + pass + raise + finally: + os.close(parent) diff --git a/packaging/windows/nightly-package-tests.ps1 b/packaging/windows/nightly-package-tests.ps1 new file mode 100644 index 000000000..833aa6a87 --- /dev/null +++ b/packaging/windows/nightly-package-tests.ps1 @@ -0,0 +1,95 @@ +param([Parameter(Mandatory=$true)][string] $FixtureRoot) +. (Join-Path $PSScriptRoot 'nightly.ps1') -FunctionsOnly +function Assert([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } } +$spec = Get-NightlyArchiveSpec '0.23.1-nightly.20261120.17.1.gabcdef012345' 'x64' +Assert ($spec.Archive -eq 'deckcraft-0.23.1-nightly.20261120.17.1.gabcdef012345-windows-x86_64-nightly.zip') 'wrong nightly artifact name' +Assert ($spec.Executables.Count -eq 1 -and $spec.Executables[0] -eq 'deckcraft.exe') 'nightly must not ship the unqualified CLI' +Assert ($spec.AppId -eq 'ai.storyteller.deckcraft.nightly-v1') 'nightly identity is not distinct' +foreach ($arch in @('x86', 'arm64')) { + $refused = $false + try { Get-NightlyArchiveSpec '0.23.1' $arch | Out-Null } catch { $refused = $true } + Assert $refused 'unsupported target was accepted' +} +foreach ($bad in @('', '0.23.1', '../other', '0.23.1/elsewhere')) { + $refused = $false + try { Get-NightlyArchiveSpec $bad 'x64' | Out-Null } catch { $refused = $true } + Assert $refused 'unsafe artifact version was accepted' +} +Assert-NightlyFlavor 'DeckCraft Nightly' 'DeckCraft 0.23.1-nightly.20261120.17.1.gabcdef012345 (nightly-v1)' '0.23.1-nightly.20261120.17.1.gabcdef012345' +foreach ($pair in @(@('DeckCraft', 'DeckCraft 0.23.1 (nightly-v1)'), @('DeckCraft Nightly', 'DeckCraft 0.23.1'))) { + $refused = $false + try { Assert-NightlyFlavor $pair[0] $pair[1] '0.23.1-nightly.20261120.17.1.gabcdef012345' } catch { $refused = $true } + Assert $refused 'stable or mismatched build flavor was accepted' +} +$sha = 'abcdef0123456789abcdef0123456789abcdef01' +$good = '0.23.1-nightly.20261120.17.1.gabcdef012345' +Assert-NightlySource $good $sha '2026-11-20' $sha '' +$cases = @( + @('missing commit', $good, '', '2026-11-20', $sha, ''), + @('short commit', $good, 'abcdef012345', '2026-11-20', $sha, ''), + @('uppercase commit', $good, $sha.ToUpper(), '2026-11-20', $sha.ToUpper(), ''), + @('version names another commit', '0.23.1-nightly.20261120.17.1.g000000000000', $sha, '2026-11-20', $sha, ''), + @('missing date', $good, $sha, '', $sha, ''), + @('date differs from version', $good, $sha, '2026-11-21', $sha, ''), + @('other commit checked out', $good, $sha, '2026-11-20', ('0' * 40), ''), + @('dirty tree', $good, $sha, '2026-11-20', $sha, ' M apps/deckcraft/src/main.rs') +) +foreach ($case in $cases) { + $refused = $false + try { Assert-NightlySource $case[1] $case[2] $case[3] $case[4] $case[5] } catch { $refused = $true } + Assert $refused "source identity accepted: $($case[0])" +} +Write-Output 'nightly packaging spec, target/version refusal, source identity and flavor-binding tests passed' + +# Exercise the SAME production notice copier with the real repository layout, then inspect a ZIP. +if (-not $FixtureRoot -or -not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'supply an owned absolute -FixtureRoot for the notices/ZIP regression' } +$testRoot = Join-Path $FixtureRoot ("nightly-notices-" + [Guid]::NewGuid().ToString('N')) +try { + $repo = Join-Path $testRoot 'app' + $fontRepo = Join-Path $testRoot 'craft-fonts' + $family = Join-Path $fontRepo 'fonts\ExampleFamily' + $stage = Join-Path $testRoot 'stage' + New-Item -ItemType Directory -Force -Path $repo, $family, $stage | Out-Null + $rootNames = @('README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') + foreach ($name in $rootNames) { Set-Content -LiteralPath (Join-Path $repo $name) -Value "root-notice-$name" } + Set-Content -LiteralPath (Join-Path $family 'OFL.txt') -Value 'font-notice-example' + Copy-NightlyNotices $repo $fontRepo $stage + foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { + Assert (Test-Path -LiteralPath (Join-Path $stage $name)) "missing staged notice $name" + } + $zip = Join-Path $testRoot 'notices.zip' + Compress-Archive -Path (Join-Path $stage '*') -DestinationPath $zip + $archive = [IO.Compression.ZipFile]::OpenRead($zip) + try { + $names = @($archive.Entries | ForEach-Object { $_.FullName }) + foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { Assert ($name -in $names) "missing archived notice $name" } + foreach ($forbidden in @('portable.txt', 'deckcraft-cli.exe')) { Assert ($forbidden -notin $names) "unexpected payload $forbidden" } + $entry = $archive.GetEntry('OFL-ExampleFamily.txt') + $reader = [IO.StreamReader]::new($entry.Open()) + try { Assert ($reader.ReadToEnd().Contains('font-notice-example')) 'wrong font license bytes in ZIP' } finally { $reader.Dispose() } + } finally { $archive.Dispose() } +} finally { + if (Test-Path -LiteralPath $testRoot) { Remove-Item -LiteralPath $testRoot -Recurse -Force } +} +Write-Output 'nightly mock-repository root and font notices are present in stage and ZIP' + +# The source state comes from git itself: the checked-out commit, then a dirty tree. +$gitRoot = Join-Path $FixtureRoot ("nightly-source-" + [Guid]::NewGuid().ToString('N')) +try { + New-Item -ItemType Directory -Force -Path $gitRoot | Out-Null + git -C $gitRoot init -q; git -C $gitRoot -c user.name=fixture -c user.email=fixture@invalid commit -q --allow-empty -m fixture + if ($LASTEXITCODE -ne 0) { throw 'cannot create the git fixture' } + $head = (git -C $gitRoot rev-parse HEAD).Trim() + $state = Get-NightlySourceState $gitRoot + Assert ($state.Head -ceq $head -and -not $state.Status) 'clean checkout not reported as clean at HEAD' + $version = '0.23.1-nightly.20261120.17.1.g' + $head.Substring(0, 12) + Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status + Set-Content -LiteralPath (Join-Path $gitRoot 'untracked.txt') -Value 'dirty' + $state = Get-NightlySourceState $gitRoot + $refused = $false + try { Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status } catch { $refused = $true } + Assert $refused 'a dirty checkout was accepted' +} finally { + if (Test-Path -LiteralPath $gitRoot) { Remove-Item -LiteralPath $gitRoot -Recurse -Force } +} +Write-Output 'nightly source state is read from git and a dirty checkout is refused' diff --git a/packaging/windows/nightly-signing-tests.ps1 b/packaging/windows/nightly-signing-tests.ps1 new file mode 100644 index 000000000..a2c13e7b1 --- /dev/null +++ b/packaging/windows/nightly-signing-tests.ps1 @@ -0,0 +1,90 @@ +param( + [Parameter(Mandatory=$true)][string] $FixtureRoot, + [string] $PackagingRoot = $PSScriptRoot, + [switch] $PhaseGuardOnly +) +$ErrorActionPreference = 'Stop' +. (Join-Path $PackagingRoot 'nightly.ps1') -FunctionsOnly +$sign = Join-Path $PackagingRoot 'sign.ps1' +$names = @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_TENANT_ID','AZURE_CLIENT_ID','AZURE_CLIENT_SECRET','AZURE_SIGNING_ENDPOINT','AZURE_SIGNING_ACCOUNT','AZURE_CERT_PROFILE') +function Clear-SigningFixtures { foreach ($name in $names) { [Environment]::SetEnvironmentVariable($name, $null) } } +function Assert-Policy([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } } +function Invoke-Refusal([scriptblock] $Operation, [string] $Message) { + $errorText = '' + try { & $Operation | Out-Null } catch { $errorText = $_.Exception.Message } + Assert-Policy ($errorText.Contains($Message)) "expected refusal: $Message; got: $errorText" +} +function global:cargo { $global:SigningFixtureCargoCalls++; throw 'FIXTURE_COMPILER_BOUNDARY' } +function global:Invoke-WebRequest { throw 'fixture must not perform signing downloads' } +$global:SigningFixtureCargoCalls = 0 +if (-not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'use an owned absolute FixtureRoot' } +$root = Join-Path $FixtureRoot ('signing-policy-' + [Guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $root | Out-Null +# The fixture mocks Cargo, but nightly.ps1 checks the same source identity a packaging run does: +# the version names this checkout's commit and the run's UTC date, and the tree is clean. Deriving +# them here keeps the fixture reaching the mocked compiler instead of failing in source validation. +$sha = "$(git -C $PSScriptRoot rev-parse HEAD)".Trim() +$runDate = (Get-Date).ToUniversalTime().ToString('yyyyMMdd') +$version = "0.23.1-nightly.$runDate.12345.1.g$($sha.Substring(0, 12))" +$env:DECKCRAFT_VERSION = $version +$env:DECKCRAFT_BUILD_SHA = $sha +$env:DECKCRAFT_BUILD_DATE = "$($runDate.Substring(0, 4))-$($runDate.Substring(4, 2))-$($runDate.Substring(6, 2))" +function Invoke-Build([switch] $BuildOnly) { + $arguments = @{Arch='x64';Version=$version;Target='x86_64-pc-windows-msvc';TargetDir=$root;Dist=(Join-Path $root 'dist')} + if ($BuildOnly) { $arguments.BuildOnly = $true } + & (Join-Path $PackagingRoot 'nightly.ps1') @arguments +} +try { + Clear-SigningFixtures + Invoke-Refusal { Invoke-Build } 'requires -BuildOnly' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'default mode invoked Cargo' + Write-Output 'PASS: explicit-build-phase-required' + if ($PhaseGuardOnly) { return } + + foreach ($name in @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_CLIENT_SECRET')) { + Clear-SigningFixtures + [Environment]::SetEnvironmentVariable($name, 'generated-fixture-not-a-secret') + Invoke-Refusal { Invoke-Build -BuildOnly } 'Compilation must not receive signing credentials' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'key-bearing compilation reached Cargo' + } + Write-Output 'PASS: credentials-rejected-before-compilation' + + Clear-SigningFixtures + Invoke-Refusal { Invoke-Build -BuildOnly } 'FIXTURE_COMPILER_BOUNDARY' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 1) 'clean compilation did not reach the mocked compiler boundary' + Assert-Policy (-not (Test-Path (Join-Path $root 'dist'))) 'mocked compilation produced an artifact' + Write-Output 'PASS: secret-free-build-reaches-only-mocked-boundary' + + Clear-SigningFixtures + Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required' + $env:AZURE_CLIENT_SECRET = 'generated-partial-fixture' + Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required' + Write-Output 'PASS: required-signer-refuses-missing-and-partial-configuration' + + Clear-SigningFixtures + $env:WINDOWS_CERTIFICATE = 'generated-presence-fixture-not-a-certificate' + & $sign -Required -CheckOnly + Clear-SigningFixtures + foreach ($name in $names | Where-Object { $_.StartsWith('AZURE_') }) { [Environment]::SetEnvironmentVariable($name, 'generated-presence-fixture') } + & $sign -Required -CheckOnly + Clear-SigningFixtures + Write-Output 'PASS: supported-configuration-presence-without-signing' + + # Load the policy function without signing. These objects are not crypto evidence. + . $sign -CheckOnly + foreach ($value in @($null, [pscustomobject]@{Status='NotSigned';SignerCertificate='fixture'}, [pscustomobject]@{Status='HashMismatch';SignerCertificate='fixture'}, [pscustomobject]@{Status='Valid';SignerCertificate=$null})) { + Invoke-Refusal { Assert-AuthenticodeSignature $value } 'valid Authenticode signature' + } + Assert-AuthenticodeSignature ([pscustomobject]@{Status='Valid';SignerCertificate='generated-public-certificate-placeholder'}) + Write-Output 'PASS: required-signature-policy-rejects-invalid-or-missing-signer' + + $file = Join-Path $root 'owned-sentinel.exe' + [IO.File]::WriteAllText($file, 'generated sentinel, not a real executable') + $before = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash + & $sign -Files $file + Assert-Policy ((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash -ceq $before) 'optional stable policy changed unsigned bytes' + Write-Output 'PASS: stable-optional-policy-preserves-owned-bytes' +} finally { + Clear-SigningFixtures + Remove-Item -LiteralPath $root -Recurse -Force +} diff --git a/packaging/windows/nightly.ps1 b/packaging/windows/nightly.ps1 new file mode 100644 index 000000000..fc0de1380 --- /dev/null +++ b/packaging/windows/nightly.ps1 @@ -0,0 +1,134 @@ +<# First nightly target only: Windows x86_64 GUI ZIP. No MSI, CLI, portable marker or association registration. #> +param( + [string] $Arch = 'x64', + [string] $Version, + [string] $Target, + [string] $TargetDir, + [string] $Dist, + [switch] $SkipBuild, + [switch] $BuildOnly, + [switch] $FunctionsOnly +) +$ErrorActionPreference = 'Stop' + +function Get-NightlyArchiveSpec([string] $Version, [string] $Arch) { + if ($Arch -ne 'x64') { throw 'nightly-v1 supports only Windows x86_64' } + if (-not $Version -or $Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' } + return @{ + Archive = "deckcraft-$Version-windows-x86_64-nightly.zip" + UnsignedArchive = "deckcraft-$Version-windows-x86_64-nightly.unsigned.zip" + Executables = @('deckcraft.exe') + Channel = 'nightly-v1' + AppId = 'ai.storyteller.deckcraft.nightly-v1' + } +} + +# The same source identity the Linux helper enforces (nightly-common.sh): the version names the +# commit being built, the date is the original run's, and the tree is clean. +function Assert-NightlySource([string] $Version, [string] $Sha, [string] $BuildDate, [string] $Head, [string] $Status) { + if ($Sha -cnotmatch '^[0-9a-f]{40}\z') { throw 'an exact source commit is required (DECKCRAFT_BUILD_SHA)' } + if ($Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' } + if ($Version.Substring($Version.Length - 12) -cne $Sha.Substring(0, 12)) { throw 'version/source commit mismatch' } + if ($BuildDate -cnotmatch '^\d{4}-\d{2}-\d{2}\z') { throw 'the original run-created UTC date is required (DECKCRAFT_BUILD_DATE)' } + $versionDate = ($Version -split '-nightly\.', 2)[1].Substring(0, 8) + if ($BuildDate.Replace('-', '') -cne $versionDate) { throw 'version/original-run date mismatch' } + if ($Head -cne $Sha) { throw 'prepared source is not the checked-out commit' } + if ($Status) { throw 'nightly packaging requires the frozen clean source' } +} + +function Get-NightlySourceState([string] $RepositoryRoot) { + $head = git -C $RepositoryRoot rev-parse HEAD + if ($LASTEXITCODE -ne 0) { throw 'cannot read the checked-out commit' } + $status = git -C $RepositoryRoot status --porcelain + if ($LASTEXITCODE -ne 0) { throw 'cannot read the source tree status' } + return @{ Head = "$head".Trim(); Status = ($status | Out-String).Trim() } +} + +function Assert-NightlyFlavor([string] $ProductName, [string] $VersionOutput, [string] $ExpectedVersion) { + if ($ProductName -ne 'DeckCraft Nightly' -or $VersionOutput -cne "DeckCraft $ExpectedVersion (nightly-v1)") { + throw 'the executable is not the compiled nightly-v1 flavor' + } +} + + +function Copy-NightlyNotices([string] $RepositoryRoot, [string] $FontRepository, [string] $Destination) { + foreach ($name in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') { + $source = Join-Path $RepositoryRoot $name + if (Test-Path -LiteralPath $source) { Copy-Item -LiteralPath $source -Destination $Destination } + } + if ($FontRepository) { + $fonts = Join-Path $FontRepository 'fonts' + if (-not (Test-Path -LiteralPath $fonts -PathType Container)) { throw 'CRAFT_FONTS_DIR has no fonts directory for the bundled notices' } + foreach ($family in Get-ChildItem -LiteralPath $fonts -Directory) { + $license = Join-Path $family.FullName 'OFL.txt' + if (Test-Path -LiteralPath $license) { Copy-Item -LiteralPath $license -Destination (Join-Path $Destination "OFL-$($family.Name).txt") } + } + } +} + +if ($FunctionsOnly) { return } +if (-not $env:DECKCRAFT_VERSION -or $Version -cne $env:DECKCRAFT_VERSION) { throw 'nightly-v1 requires explicit DECKCRAFT_VERSION, not the Cargo version fallback' } +$Spec = Get-NightlyArchiveSpec $Version $Arch +if ($SkipBuild) { throw 'nightly-v1 forbids -SkipBuild; the executable flavor must be built in this operation' } +if ($Target -ne 'x86_64-pc-windows-msvc') { throw 'nightly-v1 target must be x86_64-pc-windows-msvc' } +if (-not $BuildOnly) { throw 'Nightly compilation requires -BuildOnly; final archives are produced in the separate trusted signing job' } +# No key values may enter compilation. This produces an internal intermediate, not a feed artifact. +& (Join-Path $PSScriptRoot 'sign.ps1') -CheckBuildEnvironment +$Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path +$Source = Get-NightlySourceState $Root +Assert-NightlySource $Version $env:DECKCRAFT_BUILD_SHA $env:DECKCRAFT_BUILD_DATE $Source.Head $Source.Status +$oldChannel = $env:DECKCRAFT_BUILD_CHANNEL +try { + # DECKCRAFT_VERSION is the prepared identity the build script embeds; there is no separate + # version-override variable (DeckCraft's format layer uses the Cargo version). + $env:DECKCRAFT_BUILD_CHANNEL = 'nightly-v1' + $env:DECKCRAFT_REQUIRE_WINRES = '1' + $env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS = '-C target-feature=+crt-static' + # The same directory the packaging steps below read from, so a custom -TargetDir cannot leave + # Cargo writing somewhere else and the steps reading a stale executable. + cargo build --release --locked -p deckcraft --target $Target --target-dir $TargetDir + if ($LASTEXITCODE -ne 0) { throw "nightly cargo build failed: $LASTEXITCODE" } +} finally { + $env:DECKCRAFT_BUILD_CHANNEL = $oldChannel +} +$Source = Get-NightlySourceState $Root +try { Assert-NightlySource $Version $env:DECKCRAFT_BUILD_SHA $env:DECKCRAFT_BUILD_DATE $Source.Head $Source.Status } +catch { throw "source changed during the build: $_" } +$Exe = Join-Path $TargetDir "$Target\release\deckcraft.exe" +$pe = [System.IO.File]::ReadAllBytes($Exe) +if ($pe.Length -lt 64) { throw 'truncated nightly PE executable' } +$offset = [BitConverter]::ToInt32($pe, 0x3C) +if ($offset -lt 0 -or $offset -gt $pe.Length - 0x5E) { throw 'invalid nightly PE header offset' } +if ([BitConverter]::ToUInt16($pe, $offset + 4) -ne 0x8664 -or [BitConverter]::ToUInt16($pe, $offset + 0x5C) -ne 2) { + throw 'nightly executable must be x86_64 Windows GUI' +} +$VersionInfo = (Get-Item -LiteralPath $Exe).VersionInfo +$ProductName = $VersionInfo.ProductName +if ($VersionInfo.ProductVersion -cne $Version) { throw 'nightly PE ProductVersion differs from the feed identity' } +# Check the embedded build flavor before invoking even the side-effect-free version query. +if ($ProductName -ne 'DeckCraft Nightly') { throw 'nightly executable is missing the embedded build flavor' } +$VersionOutput = (& $Exe --version | Out-String).Trim() +if ($LASTEXITCODE -ne 0) { throw 'nightly --version query failed' } +Assert-NightlyFlavor $ProductName $VersionOutput $Version +$Stage = Join-Path $TargetDir 'windows-package\nightly-v1-x86_64' +if (Test-Path -LiteralPath $Stage) { Remove-Item -LiteralPath $Stage -Recurse -Force } +New-Item -ItemType Directory -Force -Path $Stage | Out-Null +Copy-Item -LiteralPath $Exe -Destination (Join-Path $Stage 'deckcraft.exe') +# Signing happens only in the separate trusted step, using sign.ps1 -Required. +# The intermediate's filename cannot satisfy the feed-ready archive contract. +Copy-NightlyNotices $Root $env:CRAFT_FONTS_DIR $Stage +if ((Get-ChildItem -LiteralPath $Stage -Filter '*.exe').Count -ne 1 -or (Test-Path (Join-Path $Stage 'portable.txt'))) { + throw 'nightly stage contains an unexpected executable or portable fallback marker' +} +New-Item -ItemType Directory -Force -Path $Dist | Out-Null +$Zip = Join-Path $Dist $Spec.UnsignedArchive +if (Test-Path -LiteralPath $Zip) { throw 'Nightly output already exists; refusing to replace prepared artifact bytes' } +Compress-Archive -Path (Join-Path $Stage '*') -DestinationPath $Zip +$Archive = [System.IO.Compression.ZipFile]::OpenRead($Zip) +try { + $Names = @($Archive.Entries | ForEach-Object { $_.FullName }) + if ('deckcraft.exe' -notin $Names -or 'deckcraft-cli.exe' -in $Names -or 'portable.txt' -in $Names) { + throw 'nightly ZIP payload violates the GUI-only profile contract' + } +} finally { $Archive.Dispose() } +Write-Output "Nightly build intermediate (not publishable): $Zip ($VersionOutput)" diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index b2a5825bb..8e8198e03 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -21,9 +21,12 @@ #> param( [ValidateSet('x64', 'x86', 'arm64')] [string] $Arch = 'x64', - [switch] $SkipBuild + [switch] $SkipBuild, + [switch] $Nightly, + [switch] $BuildOnly ) $ErrorActionPreference = 'Stop' +if ($BuildOnly -and -not $Nightly) { throw '-BuildOnly is only for secret-free nightly compilation' } $Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path function Invoke-Native([string] $What, [scriptblock] $Block) { @@ -50,12 +53,21 @@ $Dist = if ($env:DIST) { $env:DIST } else { Join-Path $Root 'dist\release' } $TargetDir = if ($env:CARGO_TARGET_DIR) { $env:CARGO_TARGET_DIR } else { Join-Path $Root 'target' } New-Item -ItemType Directory -Force -Path $Dist | Out-Null -if (-not $env:DECKCRAFT_BUILD_SHA) { $env:DECKCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } -if (-not $env:DECKCRAFT_BUILD_DATE) { $env:DECKCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } +# Nightly requires the prepared commit and original run date explicitly; nightly.ps1 checks both. +if (-not $Nightly) { + if (-not $env:DECKCRAFT_BUILD_SHA) { $env:DECKCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } + if (-not $env:DECKCRAFT_BUILD_DATE) { $env:DECKCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } +} Write-Output "DeckCraft $Version for Windows $Arch ($Target)" +if ($Nightly) { + & (Join-Path $PSScriptRoot 'nightly.ps1') -Arch $Arch -Version $Version -Target $Target -TargetDir $TargetDir -Dist $Dist -SkipBuild:$SkipBuild -BuildOnly:$BuildOnly + return +} + if (-not $SkipBuild) { + $env:DECKCRAFT_BUILD_CHANNEL = 'stable' # Static CRT: no VC++ redistributable needed. Scoped to the target so host build scripts and # proc-macros are unaffected. $flagVar = 'CARGO_TARGET_' + ($Target.ToUpper() -replace '-', '_') + '_RUSTFLAGS' @@ -83,6 +95,9 @@ foreach ($check in @(@('deckcraft.exe', 2), @('deckcraft-cli.exe', 3))) { if ($h.Subsystem -ne $check[1]) { throw "$($check[0]) has PE subsystem $($h.Subsystem), expected $($check[1])" } Write-Output "ok $($check[0]): $Arch, PE subsystem $($h.Subsystem)" } +if ((Get-Item -LiteralPath (Join-Path $Bin 'deckcraft.exe')).VersionInfo.ProductName -eq 'DeckCraft Nightly') { + throw 'a nightly executable cannot be packaged as stable' +} # The Start menu shortcut is not advertised and names no MSI icon, so it shows the icon embedded in # deckcraft.exe (#1114). -SkipBuild takes whatever binary is already there, which may come from a diff --git a/packaging/windows/sign.ps1 b/packaging/windows/sign.ps1 index c70a54d16..b969bb024 100644 --- a/packaging/windows/sign.ps1 +++ b/packaging/windows/sign.ps1 @@ -9,7 +9,9 @@ AZURE_SIGNING_ENDPOINT (e.g. https://eus.codesigning.azure.net), AZURE_SIGNING_ACCOUNT, AZURE_CERT_PROFILE With neither, it prints a warning and leaves the files unsigned (exit code 0), so test builds - still produce installers. + still produce installers. Nightly callers require signing with -Required and can + check signing configuration with -Required -CheckOnly. Compilation uses the + separate -CheckBuildEnvironment mode, without importing signing keys. This is the one place to adapt when the signing setup changes (an HSM/cloud key, a different timestamp server, ...). Optional overrides: WINDOWS_TIMESTAMP_URL, SIGNTOOL (path to signtool.exe). @@ -18,8 +20,11 @@ pwsh packaging/windows/sign.ps1 dist/deckcraft.exe dist/Deckcraft.msi #> param( - [Parameter(Mandatory = $true, ValueFromRemainingArguments = $true)] - [string[]] $Files + [Parameter(Position = 0, ValueFromRemainingArguments = $true)] + [string[]] $Files, + [switch] $Required, + [switch] $CheckOnly, + [switch] $CheckBuildEnvironment ) $ErrorActionPreference = 'Stop' @@ -27,6 +32,12 @@ function Write-Warn([string] $Message) { if ($env:GITHUB_ACTIONS) { Write-Output "::warning::$Message" } else { Write-Warning $Message } } +function Assert-AuthenticodeSignature($Signature) { + if (-not $Signature -or [string]$Signature.Status -cne 'Valid' -or -not $Signature.SignerCertificate) { + throw 'Required signing must produce a valid Authenticode signature and signer certificate' + } +} + function Find-SignTool { if ($env:SIGNTOOL) { return $env:SIGNTOOL } $onPath = Get-Command signtool.exe -ErrorAction SilentlyContinue @@ -44,11 +55,28 @@ function Invoke-SignTool([string[]] $Arguments) { if ($LASTEXITCODE -ne 0) { throw "signtool $($Arguments[0]) failed with exit code $LASTEXITCODE" } } -$Files = $Files | ForEach-Object { (Resolve-Path $_).Path } -$haveCert = [bool]$env:WINDOWS_CERTIFICATE $azureVars = 'AZURE_TENANT_ID', 'AZURE_CLIENT_ID', 'AZURE_CLIENT_SECRET', 'AZURE_SIGNING_ENDPOINT', 'AZURE_SIGNING_ACCOUNT', 'AZURE_CERT_PROFILE' +if ($CheckBuildEnvironment) { + if ($Required -or $CheckOnly -or $Files) { throw '-CheckBuildEnvironment is separate from signing' } + $names = @('WINDOWS_CERTIFICATE', 'WINDOWS_CERTIFICATE_PASSWORD') + $azureVars + if ($names | Where-Object { [Environment]::GetEnvironmentVariable($_) }) { + throw 'Compilation must not receive signing credentials; use a separate trusted signing step' + } + return +} +$haveCert = [bool]$env:WINDOWS_CERTIFICATE $haveAzure = -not ($azureVars | Where-Object { -not [Environment]::GetEnvironmentVariable($_) }) +if ($Required -and -not $haveCert -and -not $haveAzure) { + throw 'Nightly signing is required: configure WINDOWS_CERTIFICATE or the complete existing Azure signing configuration' +} +if ($CheckOnly) { + if ($Files) { throw '-CheckOnly does not sign files' } + return +} +if (-not $Files) { throw 'At least one file is required for signing' } +$Files = $Files | ForEach-Object { (Resolve-Path $_).Path } + if (-not $haveCert -and -not $haveAzure) { Write-Warn "Windows signing secrets not set (WINDOWS_CERTIFICATE or AZURE_*): leaving unsigned: $($Files -join ', ')" exit 0 @@ -96,6 +124,9 @@ try { Invoke-SignTool ($common + @('/tr', $ts, '/dlib', $dlib.FullName, '/dmdf', $metadata) + $Files) } Invoke-SignTool (@('verify', '/pa', '/v') + $Files) + if ($Required) { + foreach ($file in $Files) { Assert-AuthenticodeSignature (Get-AuthenticodeSignature -LiteralPath $file) } + } } finally { Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue diff --git a/sonar-project.properties b/sonar-project.properties index 16a5e3800..038abcd00 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -9,3 +9,14 @@ sonar.organization=storytold sonar.issue.ignore.multicriteria=gha-lockfile sonar.issue.ignore.multicriteria.gha-lockfile.ruleKey=githubactions:S7637 sonar.issue.ignore.multicriteria.gha-lockfile.resourceKey=.github/workflows/** +# Coverage counts only code a test run executes. These are process entrypoints and build scripts: +# `cargo llvm-cov` starts the test binaries, never `main`, and cargo runs each build script in its +# own process, so their lines can never be covered however much the modules they call are (the +# wordcraft learning). Keep the logic they call in measured modules. +sonar.coverage.exclusions=packaging/**,apps/deckcraft/src/main.rs,apps/deckcraft/build.rs,crates/ui-egui/build.rs +# Setting test roots disables the CLI default; keep all production sources analyzed. +sonar.sources=. +# These exact fixture runners are tests, not production code. Do not exclude helpers. +sonar.tests=packaging +sonar.test.inclusions=packaging/nightly-tests.py,packaging/macos/nightly_plist_tests.py,packaging/macos/nightly_sign_tests.py,packaging/windows/nightly-package-tests.ps1,packaging/windows/nightly-signing-tests.ps1,packaging/nightly-release-tests.py +sonar.python.coverage.reportPaths=python-coverage.xml