diff --git a/.github/nightly-linux-signing-key.asc b/.github/nightly-linux-signing-key.asc new file mode 100644 index 0000000000..a1c1f31e8d --- /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 0000000000..e53f913ffd --- /dev/null +++ b/.github/nightly-signing-policy.json @@ -0,0 +1,107 @@ +{ + "schema": "craft-nightly-release-policy/v3", + "repository": "storytold/lightcraft", + "repository_id": 1398185212, + "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": "lightcraft-nightly-20261124", + "repository": "storytold/lightcraft", + "branch": "main", + "required_workflows": [ + { + "workflow_id": 380135819, + "workflow_path": ".github/workflows/ci.yml", + "jobs": [ + { + "name": "gate / gate (ubuntu-24.04)", + "app_id": 15368, + "applicability": "required" + } + ] + } + ], + "sonar": { + "organization": "storytold", + "project": "storytold_lightcraft", + "app_id": 12526, + "check_name": "SonarCloud Code Analysis", + "details_url": "https://sonarcloud.io/dashboard?id=storytold_lightcraft&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/nightly-dispatch.yml b/.github/workflows/nightly-dispatch.yml new file mode 100644 index 0000000000..5707eee2d3 --- /dev/null +++ b/.github/workflows/nightly-dispatch.yml @@ -0,0 +1,72 @@ +name: Dispatch release-ref nightly + +# Transport only, never authorization. No checkout, payload parsing or release environment. +on: + workflow_run: + workflows: [LightCraft unsigned nightly] + types: [completed] + branches: [main] + +permissions: {} + +jobs: + dispatch: + # SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification. + if: >- + false && github.repository == 'storytold/lightcraft' && + github.event_name == 'workflow_run' + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + actions: write + steps: + - name: Dispatch only the exact completed producer run and attempt + shell: python + env: + GH_TOKEN: ${{ github.token }} + run: | + import json + import os + import urllib.request + + def require(value, message): + if not value: + raise RuntimeError(message) + + # These filters reduce noise; the protected release validator repeats admission + # against authenticated API metadata and required attestation/quality evidence. + require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/lightcraft', 'wrong repository') + require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event') + with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream: + event = json.load(stream) + require(event.get('action') == 'completed', 'producer is not complete') + require(event.get('repository', {}).get('full_name') == 'storytold/lightcraft', 'wrong event repository') + producer = event.get('workflow_run', {}) + require(producer.get('head_repository', {}).get('full_name') == 'storytold/lightcraft', 'foreign producer') + require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path') + require(producer.get('head_branch') == 'main', 'wrong producer branch') + require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed') + # First scheduled attempt only; reviewed manual/re-run authority belongs to release policy. + require(producer.get('event') == 'schedule', 'not an automatic scheduled producer') + run_id, attempt = producer.get('id'), producer.get('run_attempt') + require(type(run_id) is int and run_id > 0, 'invalid producer run id') + require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt') + body = json.dumps({'ref': 'release', 'inputs': { + 'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt) + }}).encode('utf-8') + request = urllib.request.Request( + 'https://api.github.com/repos/storytold/lightcraft/actions/workflows/nightly-sign.yml/dispatches', + data=body, method='POST', headers={ + 'Authorization': 'Bearer ' + os.environ['GH_TOKEN'], + 'Accept': 'application/vnd.github+json', + 'Content-Type': 'application/json', + 'X-GitHub-Api-Version': '2022-11-28', + 'User-Agent': 'lightcraft-nightly-dispatch' + }) + class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + raise RuntimeError('dispatch redirects are forbidden') + # One bounded request, no retry: duplicate transport is not publication authority. + with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response: + require(response.status == 204, 'dispatch was not accepted') + print('Dispatched producer run/attempt to the release-ref validator; not a signing result.') diff --git a/.github/workflows/nightly-macos.yml b/.github/workflows/nightly-macos.yml new file mode 100644 index 0000000000..ee6ce724bb --- /dev/null +++ b/.github/workflows/nightly-macos.yml @@ -0,0 +1,91 @@ +name: Nightly macOS build + +# Builds the unsigned Apple-silicon LightCraft 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. +on: + # macOS runners are shared with release builds: pull requests run this only with the `full-ci` + # label (as ci.yml's Windows legs), never by changed paths. `labeled` so adding it 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@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # 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: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939 + with: + ref: cc9269cd8d8258785dac603fba3122e5d2556795 + - uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939 + - id: rust + uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939 + with: + targets: aarch64-apple-darwin + - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + with: + toolchain: ${{ steps.rust.outputs.toolchain }} + targets: ${{ steps.rust.outputs.targets }} + components: ${{ steps.rust.outputs.components }} + # 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 "LIGHTCRAFT_BUILD_SHA=$sha" + echo "LIGHTCRAFT_BUILD_DATE=$date" + echo "LIGHTCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}" + } >>"$GITHUB_ENV" + - name: Build the unsigned Nightly bundle + env: + LIGHTCRAFT_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/lightcraft-$LIGHTCRAFT_VERSION-macos-aarch64-nightly.zip" + # Keeps the verified unsigned zip briefly for keyless signer tests and hand testing. Unsigned only. + - name: Keep the unsigned archive + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: lightcraft-nightly-macos-aarch64-unsigned + path: ${{ runner.temp }}/nightly-dist/lightcraft-${{ env.LIGHTCRAFT_VERSION }}-macos-aarch64-nightly.zip + if-no-files-found: error + retention-days: 7 + compression-level: 0 diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml new file mode 100644 index 0000000000..3620f21f60 --- /dev/null +++ b/.github/workflows/nightly-sign.yml @@ -0,0 +1,42 @@ +name: LightCraft 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: lightcraft-nightly-release + cancel-in-progress: false + +jobs: + release: + # Actual context guards: official repository, manual dispatch, real release branch. + if: >- + github.repository == 'storytold/lightcraft' && + 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 0000000000..8a089d190e --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,34 @@ +name: LightCraft 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/lightcraft' && + 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: lightcraft + manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' + craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + # 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 4350481874..cbe4281c07 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/**", "packaging/**", "assets/app-icon/**", "docs/nightly-signing-policy.example.json", ".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/**", "packaging/**", "assets/app-icon/**", "docs/nightly-signing-policy.example.json", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"] workflow_dispatch: permissions: @@ -71,3 +71,40 @@ 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 + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Enforce nightly caller and synthetic packaging contracts + run: python3 packaging/nightly-tests.py + - name: Nightly Linux launchers and the Arch handoff (recorded argv) + run: | + bash packaging/linux/nightly-launcher-test.sh + bash packaging/linux/nightly-arch-tar-test.sh + + nightly-windows-synthetic: + name: Nightly Windows packaging contracts (no app build) + runs-on: windows-latest + timeout-minutes: 10 + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Nightly package and signing contracts + shell: pwsh + run: | + ./packaging/windows/nightly-package-tests.ps1 -FixtureRoot $env:RUNNER_TEMP + ./packaging/windows/nightly-signing-tests.ps1 -FixtureRoot $env:RUNNER_TEMP diff --git a/.gitignore b/.gitignore index c88ace5fa4..0c84f4178f 100644 --- a/.gitignore +++ b/.gitignore @@ -17,3 +17,8 @@ plan/ # Python tools import their public operator family. __pycache__/ + +# Checked out inside the workspace by the shared nightly workflows (craft-common-actions). +/.nightly-tools +/.nightly-input +/craft-i18n diff --git a/Cargo.lock b/Cargo.lock index d6ddaca554..9528b69836 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3944,8 +3944,10 @@ dependencies = [ "raw-window-handle", "rfd", "serde_json", + "thiserror 2.0.21", "winit", "winresource", + "winsafe", "zbus", ] diff --git a/apps/lightcraft-cli/src/main.rs b/apps/lightcraft-cli/src/main.rs index d384229558..eeeafaa7f1 100644 --- a/apps/lightcraft-cli/src/main.rs +++ b/apps/lightcraft-cli/src/main.rs @@ -147,7 +147,27 @@ fn library_error(dir: &str, e: lightcraft_engine::EngineError) -> String { } } +/// The desktop GUI's Launcher protocol is not a headless option: a CLI invoked with it (a shell +/// completing `lightcraft` to `lightcraft-cli`, say) must say so rather than import the profile path +/// as a folder. Checked before the arguments are otherwise read. +fn launch_profile_refusal(args: impl Iterator) -> Option { + for arg in args { + // (`--` ends the options: a file after it may be named like one of these.) + if arg == "--" { + break; + } + if arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=") { + return Some(format!("lightcraft-cli: `{arg}` belongs to the LightCraft desktop app, not the headless CLI")); + } + } + None +} + fn main() -> ExitCode { + if let Some(refusal) = launch_profile_refusal(std::env::args_os().skip(1).map(|a| a.to_string_lossy().into_owned())) { + eprintln!("{refusal}"); + return ExitCode::from(2); + } // `--features dhat-heap`: count allocations; the profile is written when `_heap` drops // (LIGHTCRAFT_DHAT_FILE, default dhat-heap.json). #[cfg(feature = "dhat-heap")] @@ -1137,6 +1157,28 @@ mod raw_files_tests { } } +#[cfg(test)] +mod launch_profile_tests { + use super::launch_profile_refusal; + + fn refusal(args: &[&str]) -> Option { + launch_profile_refusal(args.iter().map(|a| (*a).to_string())) + } + + #[test] + fn the_desktop_launch_protocol_is_refused_before_it_can_be_read_as_a_folder() { + for args in [ + vec!["--launch-profile", "nightly-v1", "--profile-root", "/p", "--"], + vec!["run", "--profile-root=/p"], + vec!["--launch-profile=nightly-v1"], + ] { + assert!(refusal(&args).is_some(), "{args:?}"); + } + assert!(refusal(&["run", "--library", "a", "--", "/p"]).is_none(), "a file named like an option after -- is a file"); + assert!(refusal(&["run", "--demo"]).is_none()); + } +} + #[cfg(test)] mod tests { /// `render` and `merge` read the lens database the desktop app downloaded, as the desktop does (the same raw diff --git a/apps/lightcraft/Cargo.toml b/apps/lightcraft/Cargo.toml index 18024a32f6..93c7fcde68 100644 --- a/apps/lightcraft/Cargo.toml +++ b/apps/lightcraft/Cargo.toml @@ -29,6 +29,7 @@ eframe = { workspace = true, features = ["default_fonts", "clipboard", "wgpu", " egui = { workspace = true } serde_json = { workspace = true } chrono = { workspace = true } +thiserror = { workspace = true } # probing the window's renderer before it opens (`window_gpu`) pollster = { workspace = true } log = { workspace = true } @@ -58,6 +59,8 @@ lightcraft-testkit = { workspace = true } [target.'cfg(windows)'.dependencies] craft-update = { workspace = true } +# the explicit Nightly AppUserModelID, before any window exists (`process_identity`) +winsafe = { version = "0.0.29", features = ["shell"] } # the colour profile of the monitor showing the window (`win_screen_profile`) lightcraft-wincolor = { workspace = true } raw-window-handle = "0.6" diff --git a/apps/lightcraft/build.rs b/apps/lightcraft/build.rs index 4947091d64..4e93816eb7 100644 --- a/apps/lightcraft/build.rs +++ b/apps/lightcraft/build.rs @@ -3,22 +3,71 @@ //! //! 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 `LIGHTCRAFT_REQUIRE_WINRES=1` turns it -//! into an error (for release builds). +//! into an error (for release and Nightly builds). + +#[path = "src/build_channel.rs"] +mod build_channel; fn main() { println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-env-changed=LIGHTCRAFT_BUILD_CHANNEL"); + println!("cargo:rustc-check-cfg=cfg(lightcraft_nightly_v1)"); + // Only the Nightly producer sets this; anything else is a build error, never a silent fallback. + let nightly = match std::env::var("LIGHTCRAFT_BUILD_CHANNEL").as_deref() { + Ok("nightly-v1") => { + println!("cargo:rustc-cfg=lightcraft_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 LIGHTCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)"); + std::process::exit(1); + } + }; println!("cargo:rerun-if-changed=../../assets/app-icon/lightcraft.ico"); + println!("cargo:rerun-if-changed=../../assets/app-icon/lightcraft-nightly.ico"); println!("cargo:rerun-if-env-changed=LIGHTCRAFT_REQUIRE_WINRES"); + println!("cargo:rerun-if-env-changed=LIGHTCRAFT_VERSION"); + println!("cargo:rerun-if-env-changed=LIGHTCRAFT_OVERRIDE_VERSION"); + let built_version = if nightly { + // The feed identity: LIGHTCRAFT_VERSION, or the packaging scripts' LIGHTCRAFT_OVERRIDE_VERSION. + match std::env::var("LIGHTCRAFT_VERSION").or_else(|_| std::env::var("LIGHTCRAFT_OVERRIDE_VERSION")) { + Ok(version) if build_channel::is_nightly_version(&version) => version, + _ => { + eprintln!("nightly-v1 requires an explicit LIGHTCRAFT_VERSION feed identity"); + std::process::exit(1); + } + } + } else { + std::env::var("CARGO_PKG_VERSION").unwrap_or_default() + }; + println!("cargo:rustc-env=LIGHTCRAFT_BUILT_VERSION={built_version}"); + println!("cargo:rerun-if-env-changed=LIGHTCRAFT_BUILD_SHA"); + let built_commit = std::env::var("LIGHTCRAFT_BUILD_SHA").unwrap_or_default(); + if nightly && !(built_commit.len() == 40 && built_commit.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))) { + eprintln!("nightly-v1 requires the exact LIGHTCRAFT_BUILD_SHA source commit"); + std::process::exit(1); + } + println!("cargo:rustc-env=LIGHTCRAFT_BUILD_COMMIT={built_commit}"); + 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/lightcraft.ico") - .set("ProductName", "LightCraft") - .set("FileDescription", "LightCraft photo library and raw developer") + res.set_icon(build_channel::windows_icon_path(nightly)) + .set("ProductName", if nightly { "LightCraft Nightly" } else { "LightCraft" }) + .set( + "FileDescription", + if nightly { "LightCraft Nightly photo library and raw developer" } else { "LightCraft photo library and raw developer" }, + ) .set("LegalCopyright", "Copyright (c) the LightCraft authors. MIT OR Apache-2.0.") .set("OriginalFilename", "lightcraft.exe") .set("InternalName", "lightcraft"); + 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("LIGHTCRAFT_REQUIRE_WINRES").is_some() { panic!("embedding Windows resources failed: {e}"); diff --git a/apps/lightcraft/src/build_channel.rs b/apps/lightcraft/src/build_channel.rs new file mode 100644 index 0000000000..1f17594cfe --- /dev/null +++ b/apps/lightcraft/src/build_channel.rs @@ -0,0 +1,55 @@ +//! 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/lightcraft-nightly.ico" } else { "../../assets/app-icon/lightcraft.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/lightcraft.ico"); + assert_eq!(windows_icon_path(true), "../../assets/app-icon/lightcraft-nightly.ico"); + } + + #[test] + fn explicit_feed_identity_is_required_for_a_nightly_build() { + assert!(is_nightly_version("0.21.0-nightly.20261124.17.1.gabcdef012345")); + for invalid in [ + "", + "0.21.0", + "0.21.0-nightly", + "0.21.0-nightly.20261124", + "0.21.0-nightly.20261124.17.1.gABCDEF012345", + "0.21.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.21.0-nightly.20261124.1.1.gabcdef012345", + "0.21.0-nightly.20261124.1.1.gabcdef012345/other", + "0.21.0-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other", + ] { + assert!(!is_nightly_version(invalid)); + } + } +} diff --git a/apps/lightcraft/src/build_flavor.rs b/apps/lightcraft/src/build_flavor.rs new file mode 100644 index 0000000000..4b9779edb2 --- /dev/null +++ b/apps/lightcraft/src/build_flavor.rs @@ -0,0 +1,87 @@ +//! 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!(lightcraft_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 LightCraft Nightly from ArtCraft Launcher".into()), + (BuildFlavor::Stable, true) => Err("This is a stable LightCraft 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") +} + +/// The help query only, in the same exact form: the CLI help is the same for both channels, so the +/// launch-profile requirement must not pre-empt it. +pub fn help_query(args: &[OsString]) -> bool { + matches!(args, [arg] if arg == "--help" || arg == "-h") +} + +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 the_help_query_is_only_the_bare_flag() { + assert!(help_query(&["--help".into()])); + assert!(help_query(&["-h".into()])); + assert!(!help_query(&[])); + assert!(!help_query(&["--help".into(), "--library".into()])); + assert!(!help_query(&["--".into(), "--help".into()])); + } + + #[test] + fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() { + assert_eq!(version(BuildFlavor::Stable, "0.21.0"), "0.21.0"); + assert_eq!(version(BuildFlavor::NightlyV1, "0.21.0"), "0.21.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/lightcraft/src/launch.rs b/apps/lightcraft/src/launch.rs index 13edce0fd5..2a4d86c237 100644 --- a/apps/lightcraft/src/launch.rs +++ b/apps/lightcraft/src/launch.rs @@ -105,9 +105,18 @@ pub(crate) fn control_port_from(what: &str, value: Option) -> Option Option, temp: std::path::PathBuf) -> std::path::PathBuf { +/// An isolated profile keeps the emergency crash log with its other app data: the Nightly profile's +/// settings folder, else `LIGHTCRAFT_CONFIG_DIR`, else (no override, or an empty one) the historical +/// system-temp location. The profile wins because Nightly refuses `LIGHTCRAFT_CONFIG_DIR`, and a +/// shared temp file would put a Nightly crash in Stable's log. +pub(crate) fn panic_log_path_with( + env: impl Fn(&str) -> Option, + temp: std::path::PathBuf, + profile: Option, +) -> std::path::PathBuf { + if let Some(root) = profile.filter(|root| !root.as_os_str().is_empty()) { + return root.join("Settings").join("lightcraft-panics.log"); + } env("LIGHTCRAFT_CONFIG_DIR").filter(|value| !value.is_empty()).map(std::path::PathBuf::from).unwrap_or(temp).join("lightcraft-panics.log") } @@ -163,8 +172,22 @@ mod config_path_tests { #[test] fn config_override_keeps_panic_log_in_isolated_profile() { let temp = std::path::PathBuf::from("temp"); - assert_eq!(panic_log_path_with(|_| Some("isolated".into()), temp.clone()), std::path::PathBuf::from("isolated/lightcraft-panics.log")); - assert_eq!(panic_log_path_with(|_| None, temp.clone()), temp.join("lightcraft-panics.log")); - assert_eq!(panic_log_path_with(|_| Some("".into()), temp.clone()), temp.join("lightcraft-panics.log")); + assert_eq!(panic_log_path_with(|_| Some("isolated".into()), temp.clone(), None), std::path::PathBuf::from("isolated/lightcraft-panics.log")); + assert_eq!(panic_log_path_with(|_| None, temp.clone(), None), temp.join("lightcraft-panics.log")); + assert_eq!(panic_log_path_with(|_| Some("".into()), temp.clone(), None), temp.join("lightcraft-panics.log")); + } + + /// Nightly's crash log lives in its own profile's settings folder, never in Stable's temp file, + /// and an inherited LIGHTCRAFT_CONFIG_DIR cannot move it out again. + #[test] + fn nightly_profile_owns_the_panic_log() { + let temp = std::path::PathBuf::from("temp"); + let profile = std::path::PathBuf::from("/launcher/profiles/lightcraft"); + assert_eq!( + panic_log_path_with(|_| Some("stable settings".into()), temp.clone(), Some(profile.clone())), + profile.join("Settings/lightcraft-panics.log") + ); + assert_eq!(panic_log_path_with(|_| None, temp.clone(), Some(profile.clone())), profile.join("Settings/lightcraft-panics.log")); + assert_eq!(panic_log_path_with(|_| None, temp.clone(), Some("".into())), temp.join("lightcraft-panics.log")); } } diff --git a/apps/lightcraft/src/launch_profile.rs b/apps/lightcraft/src/launch_profile.rs new file mode 100644 index 0000000000..49340cc3fa --- /dev/null +++ b/apps/lightcraft/src/launch_profile.rs @@ -0,0 +1,212 @@ +//! 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 portable/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, lightcraft_engine::config::ensure_writable) +} + +#[cfg(test)] +mod tests { + use super::*; + fn args(values: &[&str]) -> Vec { + values.iter().map(OsString::from).collect() + } + fn absolute() -> &'static str { + if cfg!(windows) { r"C:\NightlyData\profiles\lightcraft" } else { "/nightly-data/profiles/lightcraft" } + } + fn nightly() -> Vec { + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) + } + + #[test] + fn stable_arguments_and_directory_policy_are_unchanged() { + for argv in [args(&[]), args(&["--library", "a.lclib"]), args(&["--", "--launch-profile", "file.jpg"])] { + 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", "image with spaces.dng"])); + let launch = parse(argv).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); + assert_eq!(launch.args, args(&["--", "--profile-root", "image with spaces.dng"])); + } + + #[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(), "--new-instance", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute()]), + ] { + assert!(parse(argv).is_err()); + } + // A stable-only flag cannot ride along with the nightly selector; a file after `--` can. + assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "file.jpg"])).is_ok()); + } + + #[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(), "--new-instance", "--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 = std::cell::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/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index 97479ad68a..2c3b4cac2f 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -26,6 +26,9 @@ mod alloc_release; mod appearance; +#[cfg(test)] +mod build_channel; +mod build_flavor; #[cfg(target_os = "linux")] mod colord; mod control_server; @@ -50,8 +53,12 @@ use lightcraft_ui_egui::{LightcraftApp, Services, UiState}; mod gpu_crash; mod launch; +mod launch_profile; +mod nightly_session; mod platform; mod prefs; +mod process_identity; +mod profile_root; mod session; use gpu_crash::{gpu_crash_check, gpu_lost_check_at, gpu_lost_marker_path, gpu_lost_reason, record_gpu_lost, window_files}; @@ -70,8 +77,11 @@ use prefs::{PrefsWriter, as_remembered, load_prefs, prefs_path}; use prefs::{load_prefs_at, write_atomic}; use session::{open_session, services}; -/// Reverse-DNS app id: Wayland app id, `.desktop` file and hicolor icon name. -const APP_ID: &str = "ai.storyteller.lightcraft"; +/// Reverse-DNS app id of the selected channel: Wayland app id, `.desktop` file and icon name +/// (see [`lightcraft_ui_egui::channel`]). Stable keeps `ai.storyteller.lightcraft` byte for byte. +fn app_id() -> &'static str { + lightcraft_ui_egui::channel::app_id() +} /// The window, taskbar and Dock icon (assets/app-icon/, regenerated by packaging/icons.sh). macOS /// gets the version with Apple's transparent margin so it sits right among the other Dock icons. @@ -83,7 +93,30 @@ fn app_icon() -> egui::IconData { eframe::icon_data::from_png_bytes(png).unwrap_or_default() } -struct App(LightcraftApp, PrefsWriter, Option, #[cfg(target_os = "macos")] Option); +struct App(LightcraftApp, PrefsWriter, Option, NightlyExit, #[cfg(target_os = "macos")] Option); + +/// What the exit path must finish: the Nightly session record (if this window owns it) and whether +/// the window ever showed its owner the interruption notice. +struct NightlyExit { + session: nightly_session::Shared, + notice_shown: std::sync::Arc, +} + +impl NightlyExit { + /// A window with no Nightly session to finish: Stable, a `--memory` session, and the tests that + /// build an `App` without one. + #[cfg(test)] + fn none() -> Self { + Self { + session: std::sync::Arc::new(std::sync::Mutex::new(None)), + notice_shown: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + } + } + + fn finish(&self) { + nightly_session::finish_once(&self.session, self.notice_shown.load(std::sync::atomic::Ordering::Relaxed)); + } +} /// Draws renders that stayed on the GPU: registers their textures with the window's egui-wgpu /// renderer (the GPU renderer runs on the window's device, see [`adopt_window_device`]). @@ -153,7 +186,7 @@ impl eframe::App for App { } fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { #[cfg(target_os = "macos")] - if let Some(m) = self.3.as_mut() + if let Some(m) = self.4.as_mut() && m.update(&mut self.0, ctx) && lightcraft_ui_egui::panels::notices::may_close(&mut self.0) { @@ -205,6 +238,9 @@ impl eframe::App for App { // starts here. Elsewhere dropping the app starts it. #[cfg(target_os = "macos")] self.0.start_pending_update(); + // Everything is saved and background work has stopped: a controlled quit is a clean exit. + // (On macOS this must come before the `exit(0)` below, which never returns.) + self.3.finish(); // macOS (#1331): end the process here, before eframe tears the window down, as Quit from // the menu bar already does (PR #444). AccessKit's macOS adapter subclasses the window's // content view and restores its class on teardown; AppKit's Touch Bar support observes @@ -222,45 +258,192 @@ impl eframe::App for App { /// a second; anything slower gives way to quitting. const EXIT_WAIT: std::time::Duration = std::time::Duration::from_secs(2); +/// The nightly Windows taskbar/Start identity, before any window or COM service exists. +fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> { + process_identity::initialize( + build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, + lightcraft_ui_egui::channel::id_for(lightcraft_ui_egui::channel::LaunchIdentity::NightlyV1), + ) +} + +/// A launcher script has no terminal: say why it refused, in a native dialog on a desktop session. +fn report_launch_profile_error(error: &str) { + eprintln!("LightCraft 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!("LightCraft launch profile: {error}"); + return; + } + let _ = rfd::MessageDialog::new() + .set_title(lightcraft_ui_egui::channel::name_for(lightcraft_ui_egui::channel::LaunchIdentity::NightlyV1)) + .set_description(error) + .set_level(rfd::MessageLevel::Error) + .set_buttons(rfd::MessageButtons::Ok) + .show(); + } +} + +/// Select the immutable launch profile and its data root before any startup service or side effect. +/// Returns the arguments the app itself parses (`None`: a version or help query answered; we are done). +fn prepare_launch() -> Option> { + let nightly_build = build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1; + // The trusted Launcher protocol is decided before logger/crash/update/prefs access, so a + // headless query never creates a folder, a log file, a window or a dialog. + let argv: Vec<_> = std::env::args_os().skip(1).collect(); + if nightly_build && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) { + use std::io::Write as _; + let _ = writeln!(std::io::stdout(), "LightCraft {}", build_flavor::version(build_flavor::COMPILED, env!("LIGHTCRAFT_BUILT_VERSION"))); + return None; + } + // The AppImage's AppRun and the FHS launchers hand `--help` / `-h` through without a profile, so + // the help query is answered here: the profile requirement would refuse it before main prints it. + // The help text is the same for both channels, and no profile, log file or dialog is created. + if build_flavor::help_query(&argv) { + print!("{HELP}"); + 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 nightly = early.profile.is_nightly(); + let identity = if nightly { lightcraft_ui_egui::channel::LaunchIdentity::NightlyV1 } else { lightcraft_ui_egui::channel::LaunchIdentity::Stable }; + let finish = launch_profile::install(early.profile) + .and_then(|()| lightcraft_ui_egui::channel::select_identity(identity)) + // The feed version and commit are what About and System Info report for this build. + .and_then(|()| { + // The source commit is Nightly's (Stable's packagers export a SHA too, and About must not + // call a release a nightly build). + lightcraft_ui_egui::channel::select_version( + env!("LIGHTCRAFT_BUILT_VERSION").to_owned(), + nightly.then(|| env!("LIGHTCRAFT_BUILD_COMMIT").to_owned()), + ) + }); + // The settings folder, models, logs and the default library must all answer from the profile. + let finish = finish.and_then(|()| match launch_profile::current().root() { + Some(root) => lightcraft_engine::config::set_profile_root(root.to_path_buf()), + None => Ok(()), + }); + if let Err(error) = finish { + report_launch_profile_error(&error); + std::process::exit(2); + } + Some(early.args) +} + +/// What the app's own arguments ask for, once the launch profile's tokens are gone. +#[derive(Debug, Default, PartialEq)] +struct AppOptions { + files: Vec, + /// The raw `--control` value; Stable only (Nightly consumes and ignores it). + control: Option, + library: Option, + seed_demo: bool, + in_memory: bool, +} + +/// The app's own arguments: start with these options, or answer one of the two queries. +#[derive(Debug, PartialEq)] +enum AppCommand { + Start(AppOptions), + Version, + Help, +} + +/// Parse the app's own arguments. Pure (no printing, no exit, no environment) so the loop — and the +/// launch profile's `--` hand-off — is testable. Nightly's arguments arrive as `-- files…`, so the +/// first `--` ends the options and every later word is a file, even one spelled like an option. +fn app_command(args: &[String], nightly: bool) -> Result { + let mut options = AppOptions { seed_demo: true, ..AppOptions::default() }; + let mut args = args.iter(); + while let Some(argument) = args.next() { + match argument.as_str() { + "--control" => { + let value = args.next().cloned().unwrap_or_default(); + if !nightly { + options.control = Some(value); + } + } + "--library" => options.library = args.next().map(std::path::PathBuf::from), + "--no-demo" => options.seed_demo = false, + "--memory" | "--demo" => options.in_memory = true, + "--" => { + options.files.extend(args.by_ref().cloned()); + break; + } + "--version" => return Ok(AppCommand::Version), + "-h" | "--help" => return Ok(AppCommand::Help), + option if option.starts_with("--") => return Err(format!("unknown option `{option}`")), + _ => options.files.push(argument.clone()), + } + } + Ok(AppCommand::Start(options)) +} + fn main() -> eframe::Result { + let Some(arguments) = prepare_launch() else { return Ok(()) }; // Windows: the update helper is a copy of this program started with `--finish-update`. #[cfg(windows)] - if let Some(result) = craft_update::self_update::finish(&lightcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { + if !launch_profile::current().is_nightly() + && let Some(result) = craft_update::self_update::finish(&lightcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) + { std::process::exit(i32::from(result.is_err())); } // First, so every start-up record is kept for the log file (`logging`). let logger = logging::install(); - lightcraft_engine::guard::install_hook(panic_log_path_with(|name| std::env::var_os(name), std::env::temp_dir())); + // The crash log follows the profile: Nightly keeps it in /Settings, never in the shared + // system-temp file Stable writes. + lightcraft_engine::guard::install_hook(panic_log_path_with( + |name| std::env::var_os(name), + std::env::temp_dir(), + lightcraft_engine::config::profile_root().map(std::path::Path::to_path_buf), + )); if let Some(logger) = logger { logging::record_panics(logger); } alloc_release::install(); - let mut control_port = control_port_from("LIGHTCRAFT_CONTROL_PORT", std::env::var("LIGHTCRAFT_CONTROL_PORT").ok().filter(|v| !v.is_empty())); - let mut files = Vec::new(); - let mut seed_demo = true; - let mut in_memory = false; - let mut library_dir: Option = None; - let mut args = std::env::args().skip(1); - while let Some(a) = args.next() { - match a.as_str() { - "--control" => control_port = control_port_from("--control", Some(args.next().unwrap_or_default())), - "--library" => library_dir = args.next().map(std::path::PathBuf::from), - "--no-demo" => seed_demo = false, - "--memory" | "--demo" => in_memory = true, - "--version" => { - println!("lightcraft {}", env!("CARGO_PKG_VERSION")); - return Ok(()); - } - "-h" | "--help" => { - print!("{HELP}"); - return Ok(()); - } - o if o.starts_with("--") => { - eprintln!("lightcraft: unknown option `{o}`\n\n{HELP}"); - std::process::exit(2); - } - _ => files.push(a), + let nightly = launch_profile::current().is_nightly(); + // Nightly has no control server: an inherited port variable or flag must not open a socket the + // Launcher did not agree to (the options are still accepted and ignored, so the CLI help stays true). + let mut control_port = if nightly { + None + } else { + control_port_from("LIGHTCRAFT_CONTROL_PORT", std::env::var("LIGHTCRAFT_CONTROL_PORT").ok().filter(|v| !v.is_empty())) + }; + // The selected profile's arguments (Stable's are the same ones the process was started with). + let args = arguments.into_iter().map(|a| a.to_string_lossy().into_owned()).collect::>(); + let (files, control, library_dir, seed_demo, in_memory) = match app_command(&args, nightly) { + Ok(AppCommand::Start(options)) => (options.files, options.control, options.library, options.seed_demo, options.in_memory), + Ok(AppCommand::Version) => { + println!("lightcraft {}", env!("CARGO_PKG_VERSION")); + return Ok(()); } + Ok(AppCommand::Help) => { + print!("{HELP}"); + return Ok(()); + } + Err(problem) => { + eprintln!("lightcraft: {problem}\n\n{HELP}"); + std::process::exit(2); + } + }; + // Nightly has no control server: the option and its port are still consumed, and ignored. + if !nightly && let Some(value) = control { + control_port = control_port_from("--control", Some(value)); } // The log file: opened after the arguments, so `--version`, `--help` and a usage error leave // no file behind. Records logged until now are written to it first. @@ -317,11 +500,29 @@ fn main() -> eframe::Result { // the window came up: a failure after this is LightCraft stopping, not a start that failed let came_up = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let came_up_app = came_up.clone(); + // Nightly session health: after the profile is validated and before the window loop, so an + // interruption is recorded from the first frame. Stable and a --memory session write nothing. + let (nightly_session, session_broken) = match nightly_session::Session::begin_with_health( + launch_profile::current().root().filter(|_| !in_memory), + env!("LIGHTCRAFT_BUILT_VERSION"), + Some(env!("LIGHTCRAFT_BUILD_COMMIT")), + ) { + Ok(state) => state, + Err(error) => { + log::warn!("Nightly session health is unavailable: {error}"); + (None, true) + } + }; + let previous_nightly_unclean = nightly_session.as_ref().is_some_and(nightly_session::Session::previous_unclean); + let notice_shown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let session_state: nightly_session::Shared = std::sync::Arc::new(std::sync::Mutex::new(nightly_session)); + let session_state_in_callback = session_state.clone(); + let notice_shown_in_callback = notice_shown.clone(); // how the window was when the app was last used (checked: the settings file is a file) let opens_as = prefs.as_ref().and_then(|ui| ui.window).and_then(lightcraft_ui_egui::window_place::WindowPlace::checked); let options = eframe::NativeOptions { renderer, - viewport: as_remembered(egui::ViewportBuilder::default().with_title("LightCraft"), opens_as) + viewport: as_remembered(egui::ViewportBuilder::default().with_title(lightcraft_ui_egui::channel::name()), opens_as) .with_min_inner_size(lightcraft_ui_egui::window_place::MIN_SIZE) .with_drag_and_drop(true) .with_transparent(window_gpu::composes_window(compose_window, window_renderer)) @@ -330,7 +531,7 @@ fn main() -> eframe::Result { .with_title_shown(false) .with_icon(app_icon()) // Wayland matches the window to packaging/linux/ai.storyteller.lightcraft.desktop by this id - .with_app_id(APP_ID), + .with_app_id(app_id()), wgpu_options, ..Default::default() }; @@ -350,7 +551,7 @@ fn main() -> eframe::Result { } let started = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { eframe::run_native( - "LightCraft", + lightcraft_ui_egui::channel::name(), options, Box::new(move |cc| { // the window's renderer is up (eframe calls this after creating it) @@ -364,7 +565,10 @@ fn main() -> eframe::Result { // HDR display: SDR unless the surface, platform and display all allow HDR hdr_display::report(cc.wgpu_render_state.as_ref().map(|r| r.target_format)); let mut app = LightcraftApp::new(session, services(cc, app_log_file.as_deref())); - app.set_startup_update_check(true); + // Nightly is updated by the Launcher, never by the app's own release feed. + if !nightly { + app.set_startup_update_check(true); + } if let Some(ui) = prefs { app.ui = ui; } @@ -380,6 +584,18 @@ fn main() -> eframe::Result { app.notices.extend(window_notice); app.gpu_notice = true; app.disk_space_notice = true; + if session_broken { + app.notices.push( + "LightCraft Nightly could not record this session's exit, so an unexpected close will not be reported next time.".to_string(), + ); + } + if previous_nightly_unclean { + app.notices.push( + "LightCraft Nightly closed unexpectedly last time. The library kept its recovery records, so reopen it to see what was saved." + .to_string(), + ); + notice_shown_in_callback.store(true, std::sync::atomic::Ordering::Relaxed); + } // an empty library opens where Import is offered (a grid, with the sidebar); before // the snapshot below, so this alone isn't written to the settings file if problem.is_none() && files.is_empty() { @@ -444,6 +660,7 @@ fn main() -> eframe::Result { app, writer, window_textures, + NightlyExit { session: session_state_in_callback, notice_shown: notice_shown_in_callback }, #[cfg(target_os = "macos")] menu, ))) @@ -473,19 +690,24 @@ fn main() -> eframe::Result { }; stopped_while_running(&stopped_text(&what, lost.as_deref()), log_file.as_deref()); } + nightly_session::finish_once(&session_state, notice_shown.load(std::sync::atomic::Ordering::Relaxed)); return stopped; } // a panic that still escaped the renderer's start (the probe and error handler should // prevent it): an error like any other failed start let started = started.unwrap_or_else(|_| Err(eframe::Error::AppCreation("the window's renderer panicked while starting".into()))); if let Err(e) = &started { - // the renderer never came up: start again, which tries the next one in the chain - if window_gpu::relaunch_after_failure(&win_files) { + // the renderer never came up: start again, which tries the next one in the chain. The + // Nightly record is finished first (a clean hand-off), so the new process owns its own + // session instead of joining this one's doomed record as a secondary. + let finish = || nightly_session::finish_once(&session_state, notice_shown.load(std::sync::atomic::Ordering::Relaxed)); + if window_gpu::relaunch_after_failure(&win_files, finish) { log::error!("LightCraft could not open its window with {}: {e}; trying the next renderer", window_renderer.name()); return Ok(()); } startup_failed(&e.to_string(), log_file.as_deref()); } + nightly_session::finish_once(&session_state, notice_shown.load(std::sync::atomic::Ordering::Relaxed)); started } diff --git a/apps/lightcraft/src/nightly_session.rs b/apps/lightcraft/src/nightly_session.rs new file mode 100644 index 0000000000..12437b0fed --- /dev/null +++ b/apps/lightcraft/src/nightly_session.rs @@ -0,0 +1,269 @@ +//! 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 a file that must not exist yet without following a link planted at its name: stage a +/// fresh file in the same folder, flush it, then rename it over the name (a rename replaces the +/// link itself, never its target). +fn write_no_follow(path: &Path, data: &[u8]) -> io::Result<()> { + let folder = path.parent().ok_or_else(|| io::Error::other("the session record has no folder"))?; + let name = path.file_name().ok_or_else(|| io::Error::other("the session record has no name"))?; + let mut staging = folder.join(name); + staging.set_file_name(format!(".{}.{}.tmp", name.to_string_lossy(), std::process::id())); + let mut staged = OpenOptions::new().write(true).create_new(true).open(&staging)?; + let result = staged.write_all(data).and_then(|()| staged.sync_all()); + drop(staged); + if let Err(error) = result { + let _ = std::fs::remove_file(&staging); + return Err(error); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + std::fs::set_permissions(&staging, std::fs::Permissions::from_mode(0o600))?; + } + if let Err(error) = std::fs::rename(&staging, path) { + let _ = std::fs::remove_file(&staging); + return Err(error); + } + if let Ok(folder) = File::open(folder) { + let _ = folder.sync_all(); + } + Ok(()) +} + +/// The owner's session, shared by the app's exit path and the code after the event loop. +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()), + }))?; + 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, including a renderer hand-off), 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. + /// Clear before releasing the lease so a successor cannot miss record ownership. + /// 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!("lc-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); // 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 renderer hand-off (a new process) still sees the interruption and shows it. + let retry = Session::begin(Some(&fixture.0), "retry", 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"); + 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_path_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())); + finish_once(&shared, false); + assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit path is a clean exit"); + 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/lightcraft/src/process_identity.rs b/apps/lightcraft/src/process_identity.rs new file mode 100644 index 0000000000..9d2e1c1799 --- /dev/null +++ b/apps/lightcraft/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/lightcraft/src/profile_root.rs b/apps/lightcraft/src/profile_root.rs new file mode 100644 index 0000000000..50076284b7 --- /dev/null +++ b/apps/lightcraft/src/profile_root.rs @@ -0,0 +1,646 @@ +//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. + +use std::ffi::OsString; + +use lightcraft_engine::config::{PORTABLE_DATA_DIR, PORTABLE_MARKERS}; +use std::path::{Component, Path, PathBuf}; + +/// The Nightly Flatpak's application id (packaging/linux/flatpak-bundle.sh). It is its own sandbox, +/// so the nightly GUI inside it may select a profile; any other Flatpak instance is a native package +/// inheriting a foreign runtime, which is refused. +const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.lightcraft.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("LightCraft"))) + .collect::, _>>()?; + // The MSI's default per-machine folder (lightcraft.wxs); a per-user install goes under + // Programs, and a custom folder is not known here — the executable's own folder is + // fenced below. + roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("LightCraft")); + 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("LightCraft")); + } + } + 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("lightcraft"))) + .collect::, _>>()?; + roots.extend(["/usr/bin/lightcraft", "/usr/local/bin/lightcraft", "/opt/lightcraft"].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.lightcraft")); + roots + } + Platform::Mac => { + let home = required_base(env, "HOME")?; + let library = home.join("Library"); + vec![ + library.join("Application Support/LightCraft"), + library.join("Caches/LightCraft"), + library.join("Caches/ai.storyteller.lightcraft"), + library.join("Preferences/LightCraft"), + library.join("Preferences/ai.storyteller.lightcraft.plist"), + library.join("Saved Application State/ai.storyteller.lightcraft.savedState"), + home.join("Applications/LightCraft.app"), + PathBuf::from("/Applications/LightCraft.app"), + ] + } + }; + // Stable's default library (`lightcraft_engine::library::default_dir`): its catalog, lock, + // presets and thumbnails. A Nightly profile inside it would write its own Library, Settings and + // session files into the folder Stable opens. A host with no home variable has no such library. + let home_key = if platform == Platform::Windows { "USERPROFILE" } else { "HOME" }; + if let Some(home) = env(home_key).filter(|value| !value.is_empty()) { + roots.push(absolute(PathBuf::from(home), home_key)?.join("Pictures").join("LightCraft Library")); + } + roots.push(installation_boundary(platform, exe)?); + roots.into_iter().map(|p| canonical_future(&p)).collect() +} + +/// The nightly library a fresh Nightly opens: `/Library`. Resolving it never creates it. +pub fn library_directory(root: &Path) -> Result { + private_subdirectory(root, "Library", "default library") +} + +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 (Library, 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")?; + } + Ok(()) +} + +/// Recognise the shared portable data namespace in both the supplied and resolved path. +/// This is not an inventory of arbitrary custom Stable overrides or a Launcher ownership proof. +fn is_portable_layout(path: &Path, platform: Platform) -> bool { + path.ancestors().enumerate().any(|(depth, ancestor)| { + portable_marker(ancestor) && (depth == 0 || ["lightcraft.exe", "lightcraft"].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, + }) +} + +fn portable_marker(dir: &Path) -> bool { + PORTABLE_MARKERS.iter().any(|marker| dir.join(marker).is_file()) +} + +/// 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 env("LIGHTCRAFT_CONFIG_DIR").is_some_and(|v| !v.is_empty()) { + return Err("nightly-v1 cannot be combined with LIGHTCRAFT_CONFIG_DIR".into()); + } + if env("LIGHTCRAFT_LIBRARY").is_some_and(|v| !v.is_empty()) { + // An inherited library variable could point Nightly's catalog at Stable's library. + return Err("nightly-v1 cannot inherit LIGHTCRAFT_LIBRARY; open a library with File ▸ Open Library".into()); + } + if platform != Platform::Windows + && let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty()) + && id != NIGHTLY_FLATPAK_ID + { + // A native tar/app-bundle launch must not inherit a Flatpak runtime (its socket namespace + // and its data folder could point another profile at the stable app's state). The Nightly + // Flatpak itself is its own sandbox and profiles inside it; it is the only id allowed here. + return Err("nightly-v1 native packages cannot inherit a 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 LightCraft installation or its LightCraftData 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()); + } + // `library_directory` refuses an entry alias that would redirect the default library elsewhere. + library_directory(&chosen)?; + entries_stay_inside(&chosen)?; + 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()); + } + library_directory(&confirmed)?; + 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!("lightcraft-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/lightcraft"); + 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) { + 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("ui.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("ui.json")).unwrap(), b"stable settings must not change"); + } + } + let private = fixture.root.join("LightCraftData-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 library_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() { + let fixture = Fixture::new(); + let stable = fixture.home().join("Pictures/LightCraft Library"); + std::fs::create_dir_all(&stable).unwrap(); + std::fs::write(stable.join("catalog.snap"), b"stable catalog bytes").unwrap(); + for (index, target) in [stable.clone(), fixture.root.join("missing library 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("Library")).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(), "Library 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("Library")).unwrap(); + assert!(fixture.check(Platform::Linux, &private).is_err(), "Library cannot treat the whole profile as the library"); + assert_eq!(std::fs::read(stable.join("catalog.snap")).unwrap(), b"stable catalog bytes"); + assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1); + } + + #[cfg(unix)] + #[test] + fn library_alias_to_a_private_subfolder_keeps_the_profile_usable() { + let fixture = Fixture::new(); + let private = fixture.root.join("nightly-private"); + let library = private.join("my-library"); + std::fs::create_dir_all(&library).unwrap(); + std::os::unix::fs::symlink(&library, private.join("Library")).unwrap(); + assert!(fixture.check(Platform::Linux, &private).is_ok()); + assert_eq!(std::fs::canonicalize(private.join("Library")).unwrap(), library); + } + + #[test] + fn default_library_is_private_lazy_and_preserves_stable_pictures() { + let fixture = Fixture::new(); + let stable = fixture.home().join("Pictures/LightCraft Library"); + std::fs::create_dir_all(&stable).unwrap(); + std::fs::write(stable.join("catalog.log"), b"stable document bytes").unwrap(); + let private = fixture.check(Platform::Linux, &fixture.home().join("nightly-profile")).unwrap(); + let library = library_directory(&private).unwrap(); + assert!(library.starts_with(&private) && library != private); + assert!(!library.exists(), "resolving the default library must not create it before use"); + std::fs::create_dir_all(&library).unwrap(); + std::fs::write(library.join("catalog.log"), b"nightly bytes").unwrap(); + assert_eq!(std::fs::read(stable.join("catalog.log")).unwrap(), b"stable document bytes"); + assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1); + assert_eq!(std::fs::read(library.join("catalog.log")).unwrap(), b"nightly bytes"); + } + + #[test] + fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() { + let fixture = Fixture::new(); + let root = fixture.home().join("nightly/profiles/lightcraft"); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + assert!(overlaps(&root, &root.join("Library"), platform)); + assert!(overlaps(&root.join("Library"), &root, platform)); + assert!(!overlaps(&root, &root.with_file_name("lightcraft-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("lightcraft"); + 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/lightcraft"); + 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/LightCraft Nightly.app/Contents/MacOS/LightCraft"); + 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/LightCraft", + "Caches/LightCraft", + "Caches/ai.storyteller.lightcraft", + "Preferences/LightCraft", + "Saved Application State/ai.storyteller.lightcraft.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/lightcraft"); + assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid); + } + + /// Stable's default library holds the user's photos and its catalog: a profile inside it would + /// write Nightly's Library and Settings there. Windows resolves the home folder as USERPROFILE. + #[test] + fn stable_default_library_folder_is_fenced_on_every_os() { + let mut fixture = Fixture::new(); + let linux_library = fixture.home().join("Pictures/LightCraft Library"); + assert!(fixture.check(Platform::Linux, &linux_library.join("nightly")).unwrap_err().contains("overlap")); + assert!(fixture.check(Platform::Mac, &linux_library.join("nightly")).unwrap_err().contains("overlap")); + assert!(!linux_library.exists(), "the fence is decided before anything is created"); + fixture.env.insert("USERPROFILE".into(), fixture.root.join("users/skylar").into_os_string()); + let windows_library = fixture.root.join("users/skylar/Pictures/LightCraft Library"); + assert!(fixture.check(Platform::Windows, &windows_library.join("nightly")).unwrap_err().contains("overlap")); + assert!(fixture.check(Platform::Windows, &windows_library).is_err(), "the library folder itself is Stable's too"); + // A merely similar folder next door stays available. + assert!(fixture.check(Platform::Linux, &fixture.home().join("Pictures/ArtCraftLauncher/nightly")).is_ok()); + } + + #[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("LightCraft"); + 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/lightcraft")).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("LightCraft"); + 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("LightCraft"); + 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("lightcraft"); + assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not LightCraft'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/LC"); + std::fs::create_dir_all(&portable).unwrap(); + std::fs::write(portable.join("portable.txt"), b"stable portable copy").unwrap(); + std::fs::write(portable.join("lightcraft.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 marker that no LightCraft 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/lightcraft")).is_ok()); + } + + #[test] + fn linux_fences_the_stable_flatpak_data_folder() { + let fixture = Fixture::new(); + let flatpak = fixture.home().join(".var/app/ai.storyteller.lightcraft"); + 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/lightcraft/logs"); + std::fs::create_dir_all(&stable).unwrap(); + std::fs::write(stable.join("stable.log"), b"stable log bytes").unwrap(); + for name in ["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-logs")).unwrap(); + std::fs::write(private.join("ui.json"), b"{}").unwrap(); + std::os::unix::fs::symlink(private.join("real-logs"), private.join("logs")).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/lightcraft"); + 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"); + fixture.env.insert("LIGHTCRAFT_CONFIG_DIR".into(), fixture.home().join("custom-stable").into_os_string()); + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("LIGHTCRAFT_CONFIG_DIR")); + fixture.env.remove("LIGHTCRAFT_CONFIG_DIR"); + fixture.env.insert("LIGHTCRAFT_LIBRARY".into(), fixture.home().join("Pictures/LightCraft Library").into_os_string()); + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("LIGHTCRAFT_LIBRARY")); + fixture.env.remove("LIGHTCRAFT_LIBRARY"); + fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.lightcraft".into()); + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak")); + // The Nightly Flatpak is its own sandbox: its id may select a profile inside it. + fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into()); + assert!(fixture.check(Platform::Linux, &fixture.home().join("nightly-flatpak/profile")).is_ok()); + fixture.env.remove("FLATPAK_ID"); + fixture.env.remove("HOME"); + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME")); + assert!(!candidate.exists()); + } + + #[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"stable file").unwrap(); + assert!(fixture.check(Platform::Linux, &file).is_err()); + assert_eq!(std::fs::read(&file).unwrap(), b"stable file"); + let private = fixture.home().join("nightly/profiles/lightcraft"); + assert!(fixture.check(Platform::Linux, &private).is_ok(), "the profile itself is created when it can be"); + let unwritable = fixture.home().join("nightly/profiles/lightcraft-two"); + let result = validate_for( + Platform::Linux, + &unwritable, + |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")); + } +} diff --git a/apps/lightcraft/src/tests.rs b/apps/lightcraft/src/tests.rs index e358ee15fe..6ac872f319 100644 --- a/apps/lightcraft/src/tests.rs +++ b/apps/lightcraft/src/tests.rs @@ -6,6 +6,7 @@ fn desktop_clear_color_stays_opaque_with_a_modal_open() { LightcraftApp::new(Session::new(), Services::default()), PrefsWriter::default(), None, + NightlyExit::none(), #[cfg(target_os = "macos")] None, ); @@ -16,6 +17,34 @@ fn desktop_clear_color_stays_opaque_with_a_modal_open() { } } +/// The launch profile hands the files over after `--` (launch_profile::parse): a file named like +/// an option stays a file, and nothing after `--` is read as an option again. +#[test] +fn the_launch_profile_hands_files_over_after_a_double_dash() { + let args = ["--", "--version", "--library", "--control", "-h", "photo with spaces.dng"].map(String::from); + assert_eq!( + app_command(&args, true).unwrap(), + AppCommand::Start(AppOptions { + files: ["--version", "--library", "--control", "-h", "photo with spaces.dng"].map(String::from).to_vec(), + seed_demo: true, + ..AppOptions::default() + }) + ); + // Stable and Nightly share the parser: Nightly consumes and ignores --control with its port. + assert_eq!( + app_command(&["--control".to_string(), "7000".to_string()], true).unwrap(), + AppCommand::Start(AppOptions { seed_demo: true, ..AppOptions::default() }) + ); + assert_eq!( + app_command(&["--control".to_string(), "7000".to_string()], false).unwrap(), + AppCommand::Start(AppOptions { control: Some("7000".into()), seed_demo: true, ..AppOptions::default() }) + ); + // The queries stay queries, and an unknown option stays a usage error. + assert_eq!(app_command(&["--version".to_string()], true).unwrap(), AppCommand::Version); + assert_eq!(app_command(&["-h".to_string()], true).unwrap(), AppCommand::Help); + assert!(app_command(&["--bogus".to_string()], true).unwrap_err().contains("unknown option `--bogus`")); +} + fn dir(tag: &str) -> std::path::PathBuf { let d = std::env::temp_dir().join(format!("lc-app-prefs-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); @@ -604,6 +633,7 @@ fn on_exit_ends_the_process_on_macos() { app, PrefsWriter::default(), None, + NightlyExit::none(), #[cfg(target_os = "macos")] None, ); @@ -637,6 +667,7 @@ fn on_exit_removes_the_lock_owner_note() { LightcraftApp::new(session, Services::default()), PrefsWriter::default(), None, + NightlyExit::none(), #[cfg(target_os = "macos")] None, ); diff --git a/apps/lightcraft/src/window_gpu.rs b/apps/lightcraft/src/window_gpu.rs index 9c588a6f61..9b905aa862 100644 --- a/apps/lightcraft/src/window_gpu.rs +++ b/apps/lightcraft/src/window_gpu.rs @@ -253,8 +253,10 @@ pub fn check_pipeline(device: &wgpu::Device, build: impl FnOnce(&wgpu::Device)) /// The start failed (error or panic) before the window's renderer came up: start the app again, /// which then tries the next renderer. `false`: not relaunched (it came up, nothing written to -/// disk, or the retries are used up). -pub fn relaunch_after_failure(files: &Files) -> bool { +/// disk, or the retries are used up). `before_spawn` runs once the decision to retry is made and +/// before the new process exists, so a resource the new process must own (the Nightly session +/// lease) is released first. +pub fn relaunch_after_failure(files: &Files, before_spawn: impl FnOnce()) -> bool { if !files.armed() { return false; } @@ -263,6 +265,7 @@ pub fn relaunch_after_failure(files: &Files) -> bool { return false; } let Ok(exe) = std::env::current_exe() else { return false }; + before_spawn(); log::warn!("window: the renderer failed to start; starting again with the next one"); std::process::Command::new(exe) .args(std::env::args_os().skip(1)) @@ -318,7 +321,7 @@ mod tests { // nothing written without a settings folder let none = Files::new(None); none.arm(dx); - assert!(!none.armed() && !relaunch_after_failure(&none)); + assert!(!none.armed() && !relaunch_after_failure(&none, || {})); let _ = std::fs::remove_dir_all(&d); } diff --git a/assets/app-icon/README.md b/assets/app-icon/README.md index ff6aafd659..7fec4a3b20 100644 --- a/assets/app-icon/README.md +++ b/assets/app-icon/README.md @@ -46,3 +46,16 @@ and the `.desktop` file into `applications/`. Edit `lightcraft.svg` (or `lightcraft-small.svg`), then run `packaging/icons.sh` (needs `resvg`; `iconutil` on macOS for the `.icns`; the `.ico` is packed by `cargo xtask ico`). Every output is committed. + +## Nightly channel + +The Nightly derivatives keep the foreground artwork, alpha and Mac padding unchanged: only the +amber field moves to the deeper Nightly amber. There is no letter, crescent or badge; the app, the +window title and the Launcher name the channel in text. + +`lightcraft-nightly.png` and its nine-frame ICO use the existing full-bleed 256 px render. The +separate `lightcraft-nightly-1024.png` and eleven-slot ICNS use the actual padded Mac master, never +an upscale. The palette recipe, the input/output hashes and the container sizes are recorded in +[`nightly-provenance.json`](nightly-provenance.json); `packaging/nightly-icons.py` derives them +(no `resvg` or `iconutil` needed) and `packaging/nightly-icons-tests.py` re-derives the committed +bytes. Stable source files are not recoloured. diff --git a/assets/app-icon/lightcraft-nightly-1024.png b/assets/app-icon/lightcraft-nightly-1024.png new file mode 100644 index 0000000000..a987ecc667 Binary files /dev/null and b/assets/app-icon/lightcraft-nightly-1024.png differ diff --git a/assets/app-icon/lightcraft-nightly.icns b/assets/app-icon/lightcraft-nightly.icns new file mode 100644 index 0000000000..b404477f0a Binary files /dev/null and b/assets/app-icon/lightcraft-nightly.icns differ diff --git a/assets/app-icon/lightcraft-nightly.ico b/assets/app-icon/lightcraft-nightly.ico new file mode 100644 index 0000000000..a2e2029ec2 Binary files /dev/null and b/assets/app-icon/lightcraft-nightly.ico differ diff --git a/assets/app-icon/lightcraft-nightly.png b/assets/app-icon/lightcraft-nightly.png new file mode 100644 index 0000000000..69127a2215 Binary files /dev/null and b/assets/app-icon/lightcraft-nightly.png differ diff --git a/assets/app-icon/nightly-provenance.json b/assets/app-icon/nightly-provenance.json new file mode 100644 index 0000000000..01f8c3dd9e --- /dev/null +++ b/assets/app-icon/nightly-provenance.json @@ -0,0 +1,71 @@ +{ + "title": "LightCraft Nightly deep-background icons", + "author": "@skylartaylor", + "license": "MIT OR Apache-2.0", + "inputs": [ + { + "path": "assets/app-icon/hicolor/256x256/apps/ai.storyteller.lightcraft.png", + "sha256": "57e58898ea1a1012ebafe1472e2438db2f02886a0e022c6abf88bcb71b690fc3", + "purpose": "Windows/Linux full-bleed 256 px master" + }, + { + "path": "assets/app-icon/lightcraft-macos-512.png", + "sha256": "650dfc3a821e70e47d806e9eb4a4065de46bb518d78052708b4ed9722307151e", + "purpose": "padded macOS 512 px master; the 16/32/64 px icns slots are downsampled from it, never upscaled" + }, + { + "path": "assets/app-icon/lightcraft.ico", + "sha256": "ef198753b4eca2e252553890a345cba48884998d6515fc36a67fb441c583999b", + "purpose": "the nine committed full-bleed frames" + }, + { + "path": "assets/app-icon/lightcraft.icns", + "sha256": "73b594f33963d14ba8533cd9e5bf96fd8d37a1ac2a2cf78e81ba180235692f3b", + "purpose": "the committed padded macOS frames" + } + ], + "method": { + "kind": "original code-generated derivative of the project-owned icon", + "original_palette": { + "ink": "#0b0b0c", + "paper": "#efe9dc", + "background": "#f2a516" + }, + "nightly_background": "#9a6610", + "transform": "Project every pixel onto the nearest two-colour segment of the drawing's exact palette (ink/paper, ink/background, paper/background), then move only the background share from the stable amber to the Nightly amber. Ink, paper, alpha and the macOS padding are unchanged; frames are packed at their own size and never upscaled. A frame downsampled from the padded master weights each channel by its pixel's alpha, so the transparent margin cannot darken the edge it borders. No crescent, letter or badge.", + "why_two_colours": "Solving ink, paper and background weights at once is numerically unstable for this palette: ink and paper are nearly collinear with the neutral axis, so a half-unit of rounding moves the ink/paper split by more than one. A real edge pixel is a blend of exactly two of the three colours.", + "generator": "packaging/nightly-icons.py", + "generator_sha256": "dff74f2a243d205c1babb8ebfa2d528bb8696b13839215f5f824447b09bf89f8" + }, + "outputs": { + "assets/app-icon/lightcraft-nightly.png": "b92530460f2fc49cb768fd8b12be957b5d1cbaf2f82e89b335bc64193283d4c3", + "assets/app-icon/lightcraft-nightly.ico": "69a0c3f003dbf74d7ecb29252c1fbae4ca594a2744ee67cdbb2f3a8c85db0304", + "assets/app-icon/lightcraft-nightly-1024.png": "caa27ef797c22e6a2a95928341a717c6c5784acd5c09ce5547cefcf482617ddb", + "assets/app-icon/lightcraft-nightly.icns": "e738bbb001f347459c7ef1994c2c38f42570992238ad4bcf6d041ec7335a3767" + }, + "ico_frame_sizes": [ + 16, + 20, + 24, + 32, + 40, + 48, + 64, + 128, + 256 + ], + "icns_png_slots": { + "icp4": 16, + "icp5": 32, + "ic11": 32, + "icp6": 64, + "ic12": 64, + "ic07": 128, + "ic08": 256, + "ic13": 256, + "ic09": 512, + "ic14": 512, + "ic10": 1024 + }, + "validation": "packaging/nightly-icons-tests.py re-derives the committed bytes (--check) and pins that only the field share changes, that alpha and the padded margin are preserved, that a transparent block never darkens its visible colour, and that every container frame has its own size. The 16/32/64 px padded slots were regenerated with the alpha-weighted filter: only their anti-aliased edge colour moved (52/100/197 pixels, no alpha change); the other frames are byte-identical. Native Explorer/Finder qualification remains unrun." +} diff --git a/crates/engine/src/config.rs b/crates/engine/src/config.rs index f7b762a6b3..8519f89bf0 100644 --- a/crates/engine/src/config.rs +++ b/crates/engine/src/config.rs @@ -44,7 +44,38 @@ pub fn config_dir() -> Option { } else { Platform::Other }; - config_dir_with(platform, |name| std::env::var_os(name), portable_dir) + config_dir_from(profile_root(), platform, |name| std::env::var_os(name), portable_dir) +} + +/// The Nightly desktop's private root, selected once before any host service reads a folder. +/// `None` for Stable, which keeps every rule below unchanged. +static PROFILE_ROOT: OnceLock = OnceLock::new(); + +/// Select the private Nightly root. The caller has validated it (it is inside no Stable folder); +/// this refuses only a second selection or a relative path. +pub fn set_profile_root(root: PathBuf) -> Result<(), String> { + if !root.is_absolute() { + return Err("the Nightly profile root must be absolute".into()); + } + PROFILE_ROOT.set(root).map_err(|_| "the Nightly profile root was already selected".to_string()) +} + +pub fn profile_root() -> Option<&'static Path> { + PROFILE_ROOT.get().map(PathBuf::as_path) +} + +/// [`config_dir`] with the selected profile made explicit, so the rules are testable without a +/// process-wide selection: a Nightly profile keeps its settings in `/Settings`. +fn config_dir_from( + profile: Option<&Path>, + platform: Platform, + env: impl Fn(&str) -> Option, + portable: impl FnOnce() -> Option, +) -> Option { + match profile { + Some(root) => Some(root.join("Settings")), + None => config_dir_with(platform, env, portable), + } } /// `portable` is asked only without an override, so an isolated run never probes beside the executable. @@ -99,7 +130,8 @@ fn portable_dir_in(exe_dir: &Path) -> Result, String> { } /// Create `dir` and prove a file can be written in it (a folder can exist yet be read-only). -fn ensure_writable(dir: &Path) -> std::io::Result<()> { +/// The Nightly root validator uses this same exclusive probe rather than a second rule. +pub fn ensure_writable(dir: &Path) -> std::io::Result<()> { std::fs::create_dir_all(dir)?; let probe = dir.join(format!(".write-test-{}", std::process::id())); std::fs::write(&probe, b"")?; @@ -261,6 +293,22 @@ mod config_tests { } } + /// A selected Nightly profile keeps settings (ui.json, logs, models, lensfun, geonames) inside + /// it, and none of the Stable environment or portable rules are consulted. + #[test] + fn a_nightly_profile_owns_the_settings_folder() { + let root = PathBuf::from("nightly/profile"); + for platform in [Platform::Mac, Platform::Windows, Platform::Other] { + let actual = + config_dir_from(Some(root.as_path()), platform, |_| panic!("a Nightly profile must not read Stable variables"), no_portable_probe); + assert_eq!(actual, Some(root.join("Settings"))); + } + assert_eq!( + config_dir_from(None, Platform::Windows, |name| (name == "APPDATA").then(|| OsString::from("/roaming")), || None), + Some(PathBuf::from("/roaming/LightCraft")) + ); + } + #[test] fn config_unset_override_keeps_platform_defaults() { let vars = [("HOME", "/user"), ("APPDATA", "/roaming"), ("XDG_CONFIG_HOME", "/xdg")]; diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index 261ef52eec..e0b7c496c4 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -81,6 +81,11 @@ pub fn library_state(dir: &Path) -> std::io::Result { /// The default library location: `$LIGHTCRAFT_LIBRARY` if set, else `~/Pictures/LightCraft Library` /// (`%USERPROFILE%\Pictures\LightCraft Library` on Windows). pub fn default_dir() -> Option { + // A Nightly profile opens its own library: an inherited LIGHTCRAFT_LIBRARY could otherwise point + // Nightly's catalog at Stable's library (the launch-profile validator refuses that variable too). + if let Some(root) = crate::config::profile_root() { + return Some(root.join("Library")); + } if let Some(p) = std::env::var_os("LIGHTCRAFT_LIBRARY").filter(|p| !p.is_empty()) { return Some(PathBuf::from(p)); } diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 66e377a913..f219af0c17 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -344,12 +344,9 @@ impl LightcraftApp { ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.window_title())); } - /// "LightCraft — " (just "LightCraft" for a library that isn't saved). + /// "LightCraft — " (just the channel's name for a library that isn't saved). pub fn window_title(&self) -> String { - match panels::settings::open_library_name(self) { - Some(name) => format!("LightCraft — {name}"), - None => "LightCraft".to_string(), - } + crate::channel::window_title(panels::settings::open_library_name(self).as_deref()) } /// The browser page's title: "[ •] — LightCraft" for the active photo (• while @@ -359,7 +356,7 @@ impl LightcraftApp { pub fn page_title(&self, unsaved: bool) -> String { let dot = if unsaved { " •" } else { "" }; match self.session.active().and_then(|id| self.session.catalog.photo(id)) { - Some(p) => format!("{}{dot} — LightCraft", p.file_name), + Some(p) => format!("{}{dot} — {}", p.file_name, crate::channel::name()), None => format!("{}{dot}", self.window_title()), } } diff --git a/crates/ui-egui/src/channel.rs b/crates/ui-egui/src/channel.rs new file mode 100644 index 0000000000..d82426d525 --- /dev/null +++ b/crates/ui-egui/src/channel.rs @@ -0,0 +1,133 @@ +//! The app id every LightCraft OS window carries and the channel name it shows. +//! +//! The identity is selected once, before any UI service is created. Stable keeps the original id, +//! name and version line; Nightly uses its own window/Wayland id and its own name, so a dock, an +//! Alt-Tab list or a window rule can tell the two apart, and About never claims to be Stable. +//! The package/bundle identity (`ai.storyteller.lightcraft.nightly`) is a different string: it names +//! the installed artifact, not a window. + +/// Matches the `.desktop` file and hicolor icon name, so Wayland docks pick up the icon. +pub const APP_ID: &str = "ai.storyteller.lightcraft"; +/// The window/Wayland id and (on Windows) the AppUserModelID of the Nightly channel. +pub const NIGHTLY_APP_ID: &str = "ai.storyteller.lightcraft.nightly-v1"; +pub const APP_NAME: &str = "LightCraft"; +pub const NIGHTLY_APP_NAME: &str = "LightCraft Nightly"; + +/// Immutable startup identity. The desktop selects it before any UI/runtime 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); +static VERSION: std::sync::OnceLock = std::sync::OnceLock::new(); +static COMMIT: std::sync::OnceLock = std::sync::OnceLock::new(); + +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 fn is_nightly() -> bool { + identity() == LaunchIdentity::NightlyV1 +} + +pub const fn id_for(identity: LaunchIdentity) -> &'static str { + match identity { + LaunchIdentity::Stable => APP_ID, + LaunchIdentity::NightlyV1 => NIGHTLY_APP_ID, + } +} + +pub fn app_id() -> &'static str { + id_for(identity()) +} + +pub const fn name_for(identity: LaunchIdentity) -> &'static str { + match identity { + LaunchIdentity::Stable => APP_NAME, + LaunchIdentity::NightlyV1 => NIGHTLY_APP_NAME, + } +} + +/// The channel's name for OS surfaces (title bar, task switcher, menus). +pub fn name() -> &'static str { + name_for(identity()) +} + +/// The version the app was built as: the Nightly feed version (set by the desktop host) or the +/// Cargo package version of a stable build. +pub fn version() -> &'static str { + VERSION.get().map_or(env!("CARGO_PKG_VERSION"), String::as_str) +} + +/// The source commit, when the host knows it (Nightly builds only). +pub fn commit() -> Option<&'static str> { + COMMIT.get().map(String::as_str) +} + +pub fn select_version(version: String, commit: Option) -> Result<(), String> { + VERSION.set(version).map_err(|_| "the channel version was already selected".to_string())?; + if let Some(commit) = commit.filter(|c| !c.is_empty()) { + let _ = COMMIT.set(commit); + } + Ok(()) +} + +/// The version line About and the window show: `0.21.0` or `0.21.0 (nightly-v1)`. +pub fn display_version() -> String { + match identity() { + LaunchIdentity::Stable => version().to_owned(), + LaunchIdentity::NightlyV1 => format!("{} (nightly-v1)", version()), + } +} + +/// The title-bar caption: the channel name, then the open collection when one is named. +pub fn window_title(collection: Option<&str>) -> String { + match collection.filter(|name| !name.is_empty()) { + Some(name) => format!("{} \u{2014} {}", name_owned(), name), + None => name_owned(), + } +} + +fn name_owned() -> String { + name().to_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_two_channels_never_share_a_window_identity_or_a_name() { + assert_eq!(id_for(LaunchIdentity::Stable), APP_ID); + assert_eq!(id_for(LaunchIdentity::NightlyV1), NIGHTLY_APP_ID); + assert_ne!(id_for(LaunchIdentity::Stable), id_for(LaunchIdentity::NightlyV1)); + assert_ne!(name_for(LaunchIdentity::Stable), name_for(LaunchIdentity::NightlyV1)); + // The window id is not the artifact id: the package/bundle one has no -v1. + assert!(NIGHTLY_APP_ID.ends_with(".nightly-v1")); + assert!(NIGHTLY_APP_ID.trim_end_matches("-v1").ends_with(".nightly")); + } + + #[test] + fn an_unselected_channel_is_stable_and_a_caption_carries_the_channel_name() { + assert_eq!(identity(), LaunchIdentity::Stable); + assert!(!is_nightly()); + assert_eq!(name(), APP_NAME); + assert_eq!(window_title(None), "LightCraft"); + assert_eq!(window_title(Some("")), "LightCraft"); + assert_eq!(window_title(Some("Wedding")), "LightCraft \u{2014} Wedding"); + assert_eq!(display_version(), env!("CARGO_PKG_VERSION")); + } +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 91d9dd2611..49a73997f7 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -2042,8 +2042,16 @@ fn about_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: &mut 1 => crate::credits::contributors_ui(app, ui), 2 => crate::credits::models_ui(ui), _ => { - ui.label(egui::RichText::new("LightCraft").font(t.semibold(20.0)).color(t.text)); - ui.label(crate::i18n::tr_format!("Version {} — a clean-room, pure-Rust photo library and raw developer.", env!("CARGO_PKG_VERSION"))); + ui.label(egui::RichText::new(crate::channel::name()).font(t.semibold(20.0)).color(t.text)); + ui.label(crate::i18n::tr_format!( + "Version {} — a clean-room, pure-Rust photo library and raw developer.", + crate::channel::display_version() + )); + // Nightly only: the exact source commit, so a report can name the build (plain text, as the + // catalogs carry no translated sentence for a build identity). + if let Some(commit) = crate::channel::commit() { + ui.label(format!("Nightly build {}", &commit[..commit.len().min(12)])); + } ui.label(crate::i18n::tr_format!( "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.", crate::theme::font_credits(app.chinese_font.is_some()) diff --git a/crates/ui-egui/src/dialogs/updates_ui.rs b/crates/ui-egui/src/dialogs/updates_ui.rs index 731818f1e1..a0f6908a65 100644 --- a/crates/ui-egui/src/dialogs/updates_ui.rs +++ b/crates/ui-egui/src/dialogs/updates_ui.rs @@ -1,4 +1,8 @@ //! Software updates, background check at startup, and startup prompt modal. +//! +//! Nightly is updated by the ArtCraft Launcher, never by this app's stable release feed: every entry +//! point below returns early on [`crate::channel::is_nightly`], so no check runs, no result dialog +//! opens and a ready stable update is never installed under a Nightly build. use serde_json::Value; @@ -57,6 +61,9 @@ impl LightcraftApp { /// in `on_exit` when the process ends there without dropping the app. #[cfg(not(target_arch = "wasm32"))] pub fn start_pending_update(&mut self) { + if crate::channel::is_nightly() { + return; + } self.updates_rt.updater.start_pending_update(); } } @@ -65,7 +72,7 @@ impl LightcraftApp { pub(crate) fn blocks_input(app: &LightcraftApp) -> bool { #[cfg(not(target_arch = "wasm32"))] { - app.updates_rt.updater.prompt_open() + !crate::channel::is_nightly() && app.updates_rt.updater.prompt_open() } #[cfg(target_arch = "wasm32")] { @@ -77,6 +84,10 @@ pub(crate) fn blocks_input(app: &LightcraftApp) -> bool { pub(crate) fn check(app: &mut LightcraftApp) -> Result { #[cfg(not(target_arch = "wasm32"))] { + if crate::channel::is_nightly() { + // Also keeps a command-palette or shortcut invocation from asking the stable feed. + return Err("LightCraft Nightly is updated by the ArtCraft Launcher".into()); + } app.updates_rt.check_requested = true; if let Some(ctx) = &app.updates_rt.repaint { ctx.request_repaint(); @@ -94,6 +105,9 @@ pub(crate) fn check(app: &mut LightcraftApp) -> Result { pub(crate) fn tick(app: &mut LightcraftApp, ctx: &egui::Context) { #[cfg(not(target_arch = "wasm32"))] { + if crate::channel::is_nightly() { + return; + } let rt = &mut app.updates_rt; rt.repaint = Some(ctx.clone()); if std::mem::take(&mut rt.check_requested) { @@ -118,6 +132,9 @@ fn result_window_shows(status: &Status, prompt_open: bool) -> bool { pub(crate) fn show(app: &mut LightcraftApp, ctx: &egui::Context) { #[cfg(not(target_arch = "wasm32"))] { + if crate::channel::is_nightly() { + return; + } // The close for a ready update waits until nothing is unsaved. let clean = app.session.unsaved().is_none(); match app.updates_rt.updater.show_if(ctx, clean) { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 755d16fc12..6233a00e14 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -17,6 +17,7 @@ pub const UPDATE_APP: craft_update::app::App = craft_update::app::App { pub mod brush_live; pub mod canvas_keys; +pub mod channel; mod command_error; pub mod control; pub mod destination; diff --git a/crates/ui-egui/src/menus/menubar.rs b/crates/ui-egui/src/menus/menubar.rs index e298e104c6..380af74f7d 100644 --- a/crates/ui-egui/src/menus/menubar.rs +++ b/crates/ui-egui/src/menus/menubar.rs @@ -363,6 +363,8 @@ pub(crate) fn selection_deleted(app: &LightcraftApp) -> bool { /// Restore and Delete Permanently replace Delete for photos in Recently Deleted. fn host_supports(app: &LightcraftApp, id: &str) -> bool { match id { + // Nightly is updated by the ArtCraft Launcher: the Help item would query the stable feed. + "app.checkForUpdates" => !crate::channel::is_nightly(), "file.backupLibrary" => app.services.backup_library.is_some(), "file.restoreLibrary" => app.services.restore_library.is_some(), "photo.restore" | "photo.deletePermanently" => selection_deleted(app), diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 5d595a5cd2..86a2722049 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -1694,7 +1694,7 @@ fn app_system_info_command(app: &mut LightcraftApp, p: &Value) -> Result&2; exit 1; } -cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$APP_ID.yml" +# Stable ships bin/lightcraft; a Nightly tar ships its launchers in bin/ and the real binaries in +# lib/lightcraft-nightly (packaging/linux/package.sh stage_nightly). +[[ -x "$WORK/stage/bin/lightcraft" || -x "$WORK/stage/lib/lightcraft-nightly/lightcraft" ]] \ + || { echo "error: $TARBALL has no LightCraft binary" >&2; exit 1; } +if [[ "$FLATPAK_ID" != "$APP_ID" ]]; then + gui="$WORK/stage/lib/lightcraft-nightly/lightcraft" + cli="$WORK/stage/lib/lightcraft-nightly/lightcraft-cli" + [[ -x "$gui" && -x "$cli" ]] \ + || { echo "error: $TARBALL is not a Nightly tar (no lib/lightcraft-nightly binaries); pass the -nightly- tarball from package.sh" >&2; exit 1; } + # The bundle installs the real binaries in /app/libexec and its own wrappers in /app/bin: inside + # the sandbox the Nightly Flatpak id isolates the data, and the profile keeps it explicit. + mv "$gui" "$WORK/stage/bin/lightcraft-bin" + mv "$cli" "$WORK/stage/bin/lightcraft-cli-bin" + rm -rf "$WORK/stage/lib" "$WORK/stage/bin/lightcraft-nightly" "$WORK/stage/bin/lightcraft-nightly-cli" + cat >"$WORK/stage/bin/lightcraft" <<'WRAPPER' +#!/bin/sh +set -eu +case "${1:-}" in + --launch-profile | --profile-root | --version | -V | --help | -h) exec /app/libexec/lightcraft "$@" ;; +esac +profile="${XDG_DATA_HOME:-${HOME:?HOME is required}/.var/app/ai.storyteller.lightcraft.nightly/data}/lightcraft-nightly" +exec /app/libexec/lightcraft --launch-profile nightly-v1 --profile-root "$profile" -- "$@" +WRAPPER + cat >"$WORK/stage/bin/lightcraft-cli" <<'WRAPPER' +#!/bin/sh +set -eu +case "${1:-}" in + --version | -V | --help | -h) exec /app/libexec/lightcraft-cli "$@" ;; +esac +profile="${XDG_DATA_HOME:-${HOME:?HOME is required}/.var/app/ai.storyteller.lightcraft.nightly/data}/lightcraft-nightly" +if [ -z "${LIGHTCRAFT_CONFIG_DIR+x}" ]; then export LIGHTCRAFT_CONFIG_DIR="$profile/Settings"; fi +if [ -z "${LIGHTCRAFT_LIBRARY+x}" ]; then export LIGHTCRAFT_LIBRARY="$profile/Library"; fi +exec /app/libexec/lightcraft-cli "$@" +WRAPPER + chmod 755 "$WORK/stage/bin/lightcraft" "$WORK/stage/bin/lightcraft-cli" + # The tar names the desktop entry, the metainfo, the icon and the doc folder for the *window* id + # (…nightly-v1). The Flatpak id (…nightly) is the artifact id and owns them inside the sandbox; + # StartupWMClass stays on the window id the app really sets. + nightly_id="$APP_ID.nightly-v1" + sed -e "s#^Exec=lightcraft-nightly\([[:space:]]\|$\)#Exec=lightcraft\1#" \ + -e "s|^TryExec=lightcraft-nightly$|TryExec=lightcraft|" \ + -e "s|^Icon=.*|Icon=$FLATPAK_ID|" \ + "$WORK/stage/share/applications/$nightly_id.desktop" >"$WORK/stage/share/applications/$FLATPAK_ID.desktop" + rm -f "$WORK/stage/share/applications/$nightly_id.desktop" + sed -e "s|$nightly_id|$FLATPAK_ID|g" \ + -e "s|$nightly_id.desktop|$FLATPAK_ID.desktop|g" \ + -e "s|$nightly_id|$FLATPAK_ID|g" \ + "$WORK/stage/share/metainfo/$nightly_id.metainfo.xml" >"$WORK/stage/share/metainfo/$FLATPAK_ID.metainfo.xml" + rm -f "$WORK/stage/share/metainfo/$nightly_id.metainfo.xml" + # Nightly opens no files from the file manager: no MIME database, as in the tar. + rm -rf "$WORK/stage/share/mime" + nightly_icon="$WORK/stage/share/icons/hicolor/256x256/apps/$nightly_id.png" + [[ -f "$nightly_icon" ]] || nightly_icon="$ROOT/assets/app-icon/lightcraft-nightly.png" + [[ -f "$nightly_icon" ]] || nightly_icon="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" + install -Dm644 "$nightly_icon" "$WORK/stage/share/icons/hicolor/256x256/apps/$FLATPAK_ID.png" + rm -f "$WORK/stage/share/icons/hicolor/256x256/apps/$nightly_id.png" + if [[ -d "$WORK/stage/share/doc/lightcraft-nightly" ]]; then + # The manifest copies share/doc/lightcraft (the stable name). + mv "$WORK/stage/share/doc/lightcraft-nightly" "$WORK/stage/share/doc/lightcraft" + fi + sed -e "s|ai\.storyteller\.lightcraft|$FLATPAK_ID|g" \ + -e 's|- install -Dm755 bin/lightcraft /app/bin/lightcraft|- install -Dm755 bin/lightcraft-bin /app/libexec/lightcraft\n - install -Dm755 bin/lightcraft /app/bin/lightcraft|' \ + -e 's|- install -Dm755 bin/lightcraft-cli /app/bin/lightcraft-cli|- install -Dm755 bin/lightcraft-cli-bin /app/libexec/lightcraft-cli\n - install -Dm755 bin/lightcraft-cli /app/bin/lightcraft-cli|' \ + -e '/# The same MIME definitions the deb\/rpm install\./d' \ + -e '/share\/mime\/packages/d' \ + "$HERE/flatpak/$APP_ID.bundle.yml" >"$WORK/$FLATPAK_ID.yml" +else + 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=lightcraft-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/scalable/apps' + flatpak info --user "$FLATPAK_ID" + flatpak run --command=lightcraft-cli "$FLATPAK_ID" --version + if [[ "$FLATPAK_ID" = "$APP_ID" ]]; then + flatpak run --command=sh "$FLATPAK_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/*/apps' + else + # Nightly installs no MIME database; the GUI lives in /app/libexec behind its /app/bin wrapper. + flatpak run --command=sh "$FLATPAK_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/icons/hicolor/*/apps /app/libexec' + fi fi echo "==> done" ls -lh "$OUT" diff --git a/packaging/linux/nfpm.yaml b/packaging/linux/nfpm.yaml index 47543d01d1..7ffd5f3d58 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: lightcraft +name: ${NFPM_NAME} arch: ${NFPM_ARCH} platform: linux version: ${VERSION} @@ -63,12 +63,15 @@ overrides: - xdg-desktop-portal contents: - - src: ${STAGE}/usr/bin/lightcraft - dst: /usr/bin/lightcraft + - src: ${STAGE}/usr/bin/${NFPM_BIN} + dst: /usr/bin/${NFPM_BIN} file_info: { mode: 0755 } - - src: ${STAGE}/usr/bin/lightcraft-cli - dst: /usr/bin/lightcraft-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-launch.sh b/packaging/linux/nightly-arch-launch.sh new file mode 100755 index 0000000000..22136e00d7 --- /dev/null +++ b/packaging/linux/nightly-arch-launch.sh @@ -0,0 +1,29 @@ +#!/bin/sh +set -eu + +# The Arch packager copies this file over bin/lightcraft (and bin/lightcraft-cli) and moves the +# real binaries into bin/.lightcraft-nightly/. Neither writes outside the Nightly profile. +self="$(readlink -f "$0")" +here="$(dirname "$self")" +# Never fall back to a relative path: an unresolvable $0 is a broken install, not a guess. +[ -n "$self" ] && [ "${here#/}" != "$here" ] || { echo "error: cannot resolve $0" >&2; exit 2; } +profile="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}/lightcraft-nightly" +case "$(basename "$0")" in + *-cli) + real_bin="$here/.lightcraft-nightly/lightcraft-cli" + case "${1:-}" in + --version | -V | --help | -h) exec "$real_bin" "$@" ;; + esac + # The headless CLI has no Launcher protocol: the same profile through its two host variables. + if [ -z "${LIGHTCRAFT_CONFIG_DIR+x}" ]; then export LIGHTCRAFT_CONFIG_DIR="$profile/Settings"; fi + if [ -z "${LIGHTCRAFT_LIBRARY+x}" ]; then export LIGHTCRAFT_LIBRARY="$profile/Library"; fi + exec "$real_bin" "$@" + ;; +esac +real_bin="$here/.lightcraft-nightly/lightcraft" +case "${1:-}" in + # The Launcher's own profile form is passed on untouched (its root wins over this default), and + # the queries are answered without any profile. + --launch-profile | --profile-root | --version | -V | --help | -h) exec "$real_bin" "$@" ;; +esac +exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile" -- "$@" diff --git a/packaging/linux/nightly-arch-tar-test.sh b/packaging/linux/nightly-arch-tar-test.sh new file mode 100755 index 0000000000..99501f1487 --- /dev/null +++ b/packaging/linux/nightly-arch-tar-test.sh @@ -0,0 +1,123 @@ +#!/usr/bin/env bash +# Validate the staged Arch launcher without building or opening LightCraft. +set -euo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +stage="$work/source" +dst="$work/dist" +base=lightcraft-0.0.1-nightly.1-linux-x86_64 +mkdir -p "$stage/bin" "$dst" "$work/extract" + +# A local argv/env recorder stands in for the compiled binaries. It never opens a UI. +cat >"$stage/bin/lightcraft" <<'RECORDER' +#!/bin/sh +printf 'CONFIG=<%s>\n' "${LIGHTCRAFT_CONFIG_DIR-}" +printf 'LIBRARY=<%s>\n' "${LIGHTCRAFT_LIBRARY-}" +for arg in "$@"; do + printf '<%s>\n' "$arg" +done +RECORDER +chmod 755 "$stage/bin/lightcraft" +cp "$stage/bin/lightcraft" "$stage/bin/lightcraft-cli" +# A minimal FHS share tree, so the Nightly desktop/metainfo/icon rewrite is exercised. +mkdir -p "$stage/share/applications" "$stage/share/metainfo" "$stage/share/icons/hicolor/256x256/apps" +cat >"$stage/share/applications/ai.storyteller.lightcraft.desktop" <<'DESKTOP' +[Desktop Entry] +Type=Application +Name=LightCraft +Exec=lightcraft %F +Icon=ai.storyteller.lightcraft +StartupWMClass=ai.storyteller.lightcraft +MimeType=image/jpeg; +DESKTOP +cat >"$stage/share/metainfo/ai.storyteller.lightcraft.metainfo.xml" <<'XML' + + + ai.storyteller.lightcraft + LightCraft + ai.storyteller.lightcraft.desktop + ai.storyteller.lightcraft + lightcraft + +XML +: >"$stage/share/icons/hicolor/256x256/apps/ai.storyteller.lightcraft.png" + +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/lightcraft" "$bin/lightcraft-nightly" +mv "$bin/lightcraft-cli" "$bin/lightcraft-nightly-cli" + +# The packager installs the tree as it is: no stable id may be left to rename. +nightly_id=ai.storyteller.lightcraft.nightly-v1 +share="$work/extract/$base/share" +test -f "$share/applications/$nightly_id.desktop" +test ! -e "$share/applications/ai.storyteller.lightcraft.desktop" +grep -qx "StartupWMClass=$nightly_id" "$share/applications/$nightly_id.desktop" +grep -qx "Icon=$nightly_id" "$share/applications/$nightly_id.desktop" +# The installed command is lightcraft-nightly (the stable launcher is renamed by the packager): +# `Exec=lightcraft %F` would start the stable app from the Nightly menu entry, arguments intact. +grep -qx 'Exec=lightcraft-nightly %F' "$share/applications/$nightly_id.desktop" +# `! grep` is not a condition: errexit skips it, so a match would pass. Fail the assertion explicitly. +if grep -q '^MimeType=' "$share/applications/$nightly_id.desktop"; then + echo 'FAIL: the Nightly desktop file still declares MimeType' >&2 + exit 1 +fi +test -f "$share/metainfo/$nightly_id.metainfo.xml" +grep -q "$nightly_id" "$share/metainfo/$nightly_id.metainfo.xml" +grep -q "lightcraft-nightly" "$share/metainfo/$nightly_id.metainfo.xml" +test -f "$share/icons/hicolor/256x256/apps/$nightly_id.png" + +test ! -e "$stage/bin/.lightcraft-nightly" +cmp "$stage/bin/lightcraft" "$bin/.lightcraft-nightly/lightcraft" +cmp "$stage/bin/lightcraft-cli" "$bin/.lightcraft-nightly/lightcraft-cli" +export HOME="$work/home with space" +unset XDG_DATA_HOME LIGHTCRAFT_CONFIG_DIR LIGHTCRAFT_LIBRARY +expect() { + expected="$1" + shift + actual="$(PATH="$bin:$PATH" lightcraft-nightly "$@")" + if [[ "$actual" != "$expected" ]]; then + printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2 + exit 1 + fi +} +# The GUI starts through the Nightly launch profile: one folder decision, made by the launcher. +profile="$HOME/.local/share/lightcraft-nightly" +expect "$(printf 'CONFIG=<>\nLIBRARY=<>\n<--launch-profile>\n\n<--profile-root>\n<%s>\n<-->\n\n<--other-name.dng>\n' "$profile")" \ + 'photo with spaces.dng' '--other-name.dng' +export XDG_DATA_HOME="$work/xdg with space" +profile="$XDG_DATA_HOME/lightcraft-nightly" +expect "$(printf 'CONFIG=<>\nLIBRARY=<>\n<--launch-profile>\n\n<--profile-root>\n<%s>\n<-->\n\n' "$profile")" sample.dng +# A bare query is answered by the binary as usual, with no profile tokens and no env written. +expect "$(printf 'CONFIG=<>\nLIBRARY=<>\n<--version>\n')" --version +expect "$(printf 'CONFIG=<>\nLIBRARY=<>\n<-V>\n')" -V +# The Launcher's own form arrives already shaped: its profile root wins and nothing is added. +expect "$(printf 'CONFIG=<>\nLIBRARY=<>\n<--launch-profile>\n\n<--profile-root>\n\n<--version>\n')" \ + --launch-profile nightly-v1 --profile-root /launcher/profiles/lightcraft --version +# An inherited stable variable is passed through untouched (the nightly build refuses it), never +# silently reinterpreted as the profile. +LIGHTCRAFT_CONFIG_DIR="$work/explicit with space" expect \ + "$(printf 'CONFIG=<%s>\nLIBRARY=<>\n<--launch-profile>\n\n<--profile-root>\n<%s>\n<-->\n\n' "$work/explicit with space" "$profile")" sample.dng + +# The headless CLI takes the same profile through its two host variables. +cli_actual=$(PATH="$bin:$PATH" lightcraft-nightly-cli calibrate) +cli_expected=$(printf 'CONFIG=<%s>\nLIBRARY=<%s>\n\n' "$profile/Settings" "$profile/Library") +if [[ "$cli_actual" != "$cli_expected" ]]; then + printf 'expected:\n%s\nactual:\n%s\n' "$cli_expected" "$cli_actual" >&2 + exit 1 +fi +cli_actual=$(LIGHTCRAFT_CONFIG_DIR="$work/cli settings" LIGHTCRAFT_LIBRARY="$work/cli library" PATH="$bin:$PATH" lightcraft-nightly-cli calibrate) +cli_expected=$(printf 'CONFIG=<%s>\nLIBRARY=<%s>\n\n' "$work/cli settings" "$work/cli library") +if [[ "$cli_actual" != "$cli_expected" ]]; then + printf 'expected:\n%s\nactual:\n%s\n' "$cli_expected" "$cli_actual" >&2 + exit 1 +fi + +echo "PASS: Arch Nightly handoff isolates the profile and preserves launch arguments" diff --git a/packaging/linux/nightly-arch-tar.sh b/packaging/linux/nightly-arch-tar.sh new file mode 100755 index 0000000000..4d317358a0 --- /dev/null +++ b/packaging/linux/nightly-arch-tar.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# Stage the LightCraft 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/.lightcraft-nightly" +mv "$stage/bin/lightcraft" "$stage/bin/.lightcraft-nightly/lightcraft" +mv "$stage/bin/lightcraft-cli" "$stage/bin/.lightcraft-nightly/lightcraft-cli" +cp "$here/nightly-arch-launch.sh" "$stage/bin/lightcraft" +cp "$here/nightly-arch-launch.sh" "$stage/bin/lightcraft-cli" +chmod 755 "$stage/bin/lightcraft" "$stage/bin/lightcraft-cli" + +# The packager installs this tree as it is, so the Nightly desktop entry, metainfo and icon are +# named for the Nightly channel here: leaving the stable ids would make them rename three files +# and would collide with a stable install's menu entry. +app_id=ai.storyteller.lightcraft +nightly_id="$app_id.nightly-v1" +if [ -f "$stage/share/applications/$app_id.desktop" ]; then + # The packager renames the launchers to lightcraft-nightly(-cli) when it installs this tree, so the + # menu entry must name the installed command: `Exec=lightcraft` would start stable beside it. + sed -e 's#^Exec=lightcraft\([[:space:]]\|$\)#Exec=lightcraft-nightly\1#' \ + -e 's#^TryExec=lightcraft$#TryExec=lightcraft-nightly#' \ + -e "s|^Icon=$app_id$|Icon=$nightly_id|" \ + -e "s|^StartupWMClass=.*|StartupWMClass=$nightly_id|" \ + -e "s|^Name=LightCraft$|Name=LightCraft Nightly|" \ + -e '/^MimeType=/d' \ + "$stage/share/applications/$app_id.desktop" >"$stage/share/applications/$nightly_id.desktop" + rm -f "$stage/share/applications/$app_id.desktop" +fi +if [ -f "$stage/share/metainfo/$app_id.metainfo.xml" ]; then + sed -e "s|$app_id|$nightly_id|g" \ + -e "s|LightCraft|LightCraft Nightly|g" \ + -e "s|$app_id.desktop|$nightly_id.desktop|g" \ + -e "s|$app_id|$nightly_id|g" \ + -e "s|lightcraft|lightcraft-nightly|g" \ + "$stage/share/metainfo/$app_id.metainfo.xml" >"$stage/share/metainfo/$nightly_id.metainfo.xml" + rm -f "$stage/share/metainfo/$app_id.metainfo.xml" +fi +if [ -d "$stage/share/icons/hicolor" ]; then + nightly_icon="$here/../../assets/app-icon/lightcraft-nightly.png" + if [ -f "$nightly_icon" ]; then + rm -rf "$stage/share/icons/hicolor" + install -Dm644 "$nightly_icon" "$stage/share/icons/hicolor/256x256/apps/$nightly_id.png" + fi +fi +tar -C "$work" -czf "$destination/$basename.tar.gz" "$basename" +echo "wrote $destination/$basename.tar.gz" diff --git a/packaging/linux/nightly-fhs-cli-launch.sh b/packaging/linux/nightly-fhs-cli-launch.sh new file mode 100755 index 0000000000..5b20b2efab --- /dev/null +++ b/packaging/linux/nightly-fhs-cli-launch.sh @@ -0,0 +1,17 @@ +#!/bin/sh +# The headless Nightly CLI (`usr/bin/lightcraft-nightly-cli`). It is not the GUI's Launcher +# protocol: the same profile reaches it through its two documented host variables, and an explicit +# value still wins. +set -eu +self="$(readlink -f "$0")" +here="$(dirname "$self")" +# Never fall back to a relative path: an unresolvable $0 is a broken install, not a guess. +[ -n "$self" ] && [ "${here#/}" != "$here" ] || { echo "error: cannot resolve $0" >&2; exit 2; } +real="$here/../lib/lightcraft-nightly/lightcraft-cli" +case "${1:-}" in + --version | -V | --help | -h) exec "$real" "$@" ;; +esac +profile="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}/lightcraft-nightly" +if [ -z "${LIGHTCRAFT_CONFIG_DIR+x}" ]; then export LIGHTCRAFT_CONFIG_DIR="$profile/Settings"; fi +if [ -z "${LIGHTCRAFT_LIBRARY+x}" ]; then export LIGHTCRAFT_LIBRARY="$profile/Library"; fi +exec "$real" "$@" diff --git a/packaging/linux/nightly-fhs-launch.sh b/packaging/linux/nightly-fhs-launch.sh new file mode 100755 index 0000000000..c18b678265 --- /dev/null +++ b/packaging/linux/nightly-fhs-launch.sh @@ -0,0 +1,17 @@ +#!/bin/sh +# The Nightly GUI of a .deb, a .rpm or an unpacked FHS tar (`usr/bin/lightcraft-nightly`). The +# launch profile selects the profile, so settings, models, logs, the library lock and the default +# library all sit under $profile. The real binary is resolved beside this launcher, so the same file +# works installed in /usr and unpacked anywhere. +set -eu +self="$(readlink -f "$0")" +here="$(dirname "$self")" +# Never fall back to a relative path: an unresolvable $0 is a broken install, not a guess. +[ -n "$self" ] && [ "${here#/}" != "$here" ] || { echo "error: cannot resolve $0" >&2; exit 2; } +real="$here/../lib/lightcraft-nightly/lightcraft" +case "${1:-}" in + # The Launcher's own profile form is passed on untouched, and the queries need no profile. + --launch-profile | --profile-root | --version | -V | --help | -h) exec "$real" "$@" ;; +esac +profile="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}/lightcraft-nightly" +exec "$real" --launch-profile nightly-v1 --profile-root "$profile" -- "$@" diff --git a/packaging/linux/nightly-launcher-test.sh b/packaging/linux/nightly-launcher-test.sh new file mode 100755 index 0000000000..1c3dd2275f --- /dev/null +++ b/packaging/linux/nightly-launcher-test.sh @@ -0,0 +1,83 @@ +#!/usr/bin/env bash +# Validate the Nightly launchers without building or opening LightCraft: the unpacked tar's +# `lightcraft` (GUI in `lightcraft-bin`) and the deb/rpm/FHS `lightcraft-nightly` (GUI in +# lib/lightcraft-nightly). A recorder stands in for both binaries and prints its argv and env. +set -euo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +cat >"$work/recorder" <<'RECORDER' +#!/bin/sh +printf 'CONFIG=<%s>\n' "${LIGHTCRAFT_CONFIG_DIR-}" +printf 'LIBRARY=<%s>\n' "${LIGHTCRAFT_LIBRARY-}" +for arg in "$@"; do + printf '<%s>\n' "$arg" +done +RECORDER +chmod 755 "$work/recorder" + +expect() { + local expected="$1" actual="$2" + if [[ "$actual" != "$expected" ]]; then + printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2 + exit 1 + fi +} + +unset XDG_DATA_HOME LIGHTCRAFT_CONFIG_DIR LIGHTCRAFT_LIBRARY +export HOME="$work/home with space" + +# ---- the unpacked tar: lightcraft (launcher) + lightcraft-bin (the GUI) -------------------------- +tar_dir="$work/tar" +mkdir -p "$tar_dir" +cp "$work/recorder" "$tar_dir/lightcraft-bin" +install -m755 "$HERE/nightly-tar-launch.sh" "$tar_dir/lightcraft" +profile="$HOME/.local/share/lightcraft-nightly" + +# A hand-unpacked tar opens its own Nightly profile, whatever the working directory is. +cd "$work" +expect "$(printf 'CONFIG=<>\nLIBRARY=<>\n<--launch-profile>\n\n<--profile-root>\n<%s>\n<-->\n\n<--other-name.dng>\n' "$profile")" \ + "$("$tar_dir/lightcraft" 'photo with spaces.dng' '--other-name.dng')" +export XDG_DATA_HOME="$work/xdg with space" +profile="$XDG_DATA_HOME/lightcraft-nightly" +expect "$(printf 'CONFIG=<>\nLIBRARY=<>\n<--launch-profile>\n\n<--profile-root>\n<%s>\n<-->\n\n' "$profile")" \ + "$("$tar_dir/lightcraft" sample.dng)" +unset XDG_DATA_HOME +profile="$HOME/.local/share/lightcraft-nightly" + +# The Launcher's own form arrives already shaped: its profile root wins and nothing is added. +expect "$(printf 'CONFIG=<>\nLIBRARY=<>\n<--launch-profile>\n\n<--profile-root>\n\n<--version>\n')" \ + "$("$tar_dir/lightcraft" --launch-profile nightly-v1 --profile-root /launcher/profiles/lightcraft --version)" +expect "$(printf 'CONFIG=<>\nLIBRARY=<>\n<--profile-root>\n<%s>\n<-->\n\n' "$work/explicit root")" \ + "$("$tar_dir/lightcraft" --profile-root "$work/explicit root" -- photo.dng)" +# The version query is answered by the binary itself, with no profile tokens. +expect "$(printf 'CONFIG=<>\nLIBRARY=<>\n<--version>\n')" "$("$tar_dir/lightcraft" --version)" + +# ---- the deb/rpm and the unpacked FHS tar: bin/lightcraft-nightly + lib/lightcraft-nightly ------- +fhs="$work/fhs" +mkdir -p "$fhs/bin" "$fhs/lib/lightcraft-nightly" +cp "$work/recorder" "$fhs/lib/lightcraft-nightly/lightcraft" +cp "$work/recorder" "$fhs/lib/lightcraft-nightly/lightcraft-cli" +install -m755 "$HERE/nightly-fhs-launch.sh" "$fhs/bin/lightcraft-nightly" +install -m755 "$HERE/nightly-fhs-cli-launch.sh" "$fhs/bin/lightcraft-nightly-cli" + +# The real binary is resolved beside the launcher, so an unpacked tree works anywhere. +expect "$(printf 'CONFIG=<>\nLIBRARY=<>\n<--launch-profile>\n\n<--profile-root>\n<%s>\n<-->\n\n' "$profile")" \ + "$("$fhs/bin/lightcraft-nightly" 'photo with spaces.dng')" +expect "$(printf 'CONFIG=<>\nLIBRARY=<>\n<--launch-profile>\n\n<--profile-root>\n\n<--version>\n')" \ + "$("$fhs/bin/lightcraft-nightly" --launch-profile nightly-v1 --profile-root /launcher/profiles/lightcraft --version)" +expect "$(printf 'CONFIG=<>\nLIBRARY=<>\n<--version>\n')" "$("$fhs/bin/lightcraft-nightly" --version)" + +# The headless CLI takes the same profile through its two host variables; explicit values win. +expect "$(printf 'CONFIG=<%s>\nLIBRARY=<%s>\n\n' "$profile/Settings" "$profile/Library")" \ + "$("$fhs/bin/lightcraft-nightly-cli" calibrate)" +expect "$(printf 'CONFIG=<%s>\nLIBRARY=<%s>\n\n' "$work/cli settings" "$work/cli library")" \ + "$(LIGHTCRAFT_CONFIG_DIR="$work/cli settings" LIGHTCRAFT_LIBRARY="$work/cli library" "$fhs/bin/lightcraft-nightly-cli" calibrate)" + +# Neither launcher writes anything by itself (no folder, no file). +test ! -e "$profile" +test ! -e "$HOME/Pictures" + +echo "PASS: the Nightly tar and FHS launchers isolate the profile and pass the Launcher protocol through" diff --git a/packaging/linux/nightly-tar-launch.sh b/packaging/linux/nightly-tar-launch.sh new file mode 100755 index 0000000000..53be551d38 --- /dev/null +++ b/packaging/linux/nightly-tar-launch.sh @@ -0,0 +1,18 @@ +#!/bin/sh +# LightCraft Nightly as unpacked from its tar: start the GUI in the Nightly profile, so a download +# unzipped by hand is as isolated as the AppImage, the deb/rpm and the Flatpak. +# +# ./lightcraft [files…] opens the Nightly library under $XDG_DATA_HOME/lightcraft-nightly +# ./lightcraft-bin [files…] the binary itself (stable's settings folder unless given a profile) +set -eu +self="$(readlink -f "$0")" +here="$(dirname "$self")" +# Never fall back to a relative path: an unresolvable $0 is a broken install, not a guess. +[ -n "$self" ] && [ "${here#/}" != "$here" ] || { echo "error: cannot resolve $0" >&2; exit 2; } +case "${1:-}" in + # The Launcher's own profile form is passed on untouched (its profile root wins over this + # default), and the queries are answered without any profile. + --launch-profile | --profile-root | --version | -V | --help | -h) exec "$here/lightcraft-bin" "$@" ;; +esac +profile="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}/lightcraft-nightly" +exec "$here/lightcraft-bin" --launch-profile nightly-v1 --profile-root "$profile" -- "$@" diff --git a/packaging/linux/nightly.sh b/packaging/linux/nightly.sh new file mode 100755 index 0000000000..65eb709a77 --- /dev/null +++ b/packaging/linux/nightly.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# App-owned GUI-only nightly tar: no FUSE/AppImage, CLI, association or install hooks. +set -euo pipefail +# The launcher lives beside this script. The sourced helpers define ROOT, not HERE, and an inherited +# HERE would install some other script as the launcher. +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +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/lightcraft-$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 GUI is `lightcraft-bin`; `lightcraft` is the launcher, so an unpacked tar starts in the +# Nightly profile instead of the stable settings folder. +install -m755 "$NIGHTLY_GUI" "$STAGE/lightcraft-bin" +install -m755 "$HERE/nightly-tar-launch.sh" "$STAGE/lightcraft" +install -m644 "$ROOT/assets/app-icon/lightcraft-nightly.png" "$STAGE/lightcraft-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 d42fc5fd3e..30c1414f15 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -7,7 +7,7 @@ # $DIST/lightcraft--linux-.rpm Fedora, openSUSE, RHEL, ... # $DIST/lightcraft--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] # Fonts: use CRAFT_FONTS_DIR or ../craft-fonts; download the pinned checkout if absent. # # Needs: cargo; nfpm for deb/rpm (https://nfpm.goreleaser.com); appimagetool for the AppImage @@ -24,10 +24,16 @@ APP_ID=ai.storyteller.lightcraft 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 @@ -41,9 +47,23 @@ case "$ARCH" in *) echo "unsupported architecture $ARCH" >&2; exit 2 ;; esac export LIGHTCRAFT_MAINTAINER="${LIGHTCRAFT_MAINTAINER:-LightCraft maintainers }" -BASENAME="lightcraft-$VERSION-linux-$ARCH" +IS_NIGHTLY=0 +if [[ "${LIGHTCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then + IS_NIGHTLY=1 + export LIGHTCRAFT_BUILD_CHANNEL=nightly-v1 +fi +ARTIFACT_VERSION="$VERSION" +if [[ "$IS_NIGHTLY" = 1 && "$VERSION" != *-nightly* ]]; then + ARTIFACT_VERSION="${VERSION}-nightly" +fi +BASENAME="lightcraft-$ARTIFACT_VERSION-linux-$ARCH" -echo "==> LightCraft $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 "==> LightCraft $VERSION for Linux $ARCH ($FORMATS, channel=${LIGHTCRAFT_BUILD_CHANNEL:-stable})" if [[ "$SKIP_BUILD" = 0 ]]; then # shellcheck source=../fonts.sh @@ -62,6 +82,11 @@ install -Dm755 "$BIN/lightcraft" "$STAGE/usr/bin/lightcraft" install -Dm755 "$BIN/lightcraft-cli" "$STAGE/usr/bin/lightcraft-cli" "${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/lightcraft" "$STAGE/usr/bin/lightcraft-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.lightcraft.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@/$LIGHTCRAFT_BUILD_DATE/g" \ @@ -83,21 +108,92 @@ has() { case " $FORMATS " in *" $format "*) return 0 ;; *) return 1 ;; esac } +# ---- the Nightly FHS layout (the plain tar and the deb/rpm share it) ----------------------------- +# The real binaries move to usr/lib/lightcraft-nightly and usr/bin holds launchers: the GUI starts +# through its launch profile, the headless CLI takes the same profile through its two host +# variables. One layout, so an unpacked tar, a .deb and a .rpm all behave the same. +stage_nightly() { + local stage="$WORK/nightly-root" icon + export NFPM_NAME="lightcraft-nightly" + export NFPM_BIN="lightcraft-nightly" + export NFPM_CLI="lightcraft-nightly-cli" + NIGHTLY_DESK_ID="$APP_ID.nightly-v1" + rm -rf "$stage" + cp -R "$STAGE" "$stage" + install -Dm755 "$stage/usr/bin/lightcraft" "$stage/usr/lib/lightcraft-nightly/lightcraft" + install -Dm755 "$stage/usr/bin/lightcraft-cli" "$stage/usr/lib/lightcraft-nightly/lightcraft-cli" + # The same launchers the unpacked tar runs (packaging/linux/nightly-*-launch.sh): they resolve the + # real binary beside themselves, so /usr and an unpacked tar behave alike. + install -Dm755 "$HERE/nightly-fhs-launch.sh" "$stage/usr/bin/$NFPM_BIN" + install -Dm755 "$HERE/nightly-fhs-cli-launch.sh" "$stage/usr/bin/$NFPM_CLI" + rm -f "$stage/usr/bin/lightcraft" "$stage/usr/bin/lightcraft-cli" + mv "$stage/usr/share/doc/lightcraft" "$stage/usr/share/doc/$NFPM_NAME" + sed -e "s#^Exec=lightcraft\([[:space:]]\|$\)#Exec=$NFPM_BIN\1#" \ + -e "s|^TryExec=lightcraft$|TryExec=$NFPM_BIN|" \ + -e "s|^Icon=$APP_ID$|Icon=$NIGHTLY_DESK_ID|" \ + -e "s|^StartupWMClass=.*|StartupWMClass=$NIGHTLY_DESK_ID|" \ + -e "s|^Name=LightCraft$|Name=LightCraft Nightly|" \ + -e '/^MimeType=/d' \ + "$stage/usr/share/applications/$APP_ID.desktop" >"$stage/usr/share/applications/$NIGHTLY_DESK_ID.desktop" + rm -f "$stage/usr/share/applications/$APP_ID.desktop" + sed -e "s|$APP_ID|$NIGHTLY_DESK_ID|g" \ + -e "s|LightCraft|LightCraft Nightly|g" \ + -e "s|$APP_ID.desktop|$NIGHTLY_DESK_ID.desktop|g" \ + -e "s|$APP_ID|$NIGHTLY_DESK_ID|g" \ + -e "s|lightcraft|$NFPM_BIN|g" \ + "$stage/usr/share/metainfo/$APP_ID.metainfo.xml" >"$stage/usr/share/metainfo/$NIGHTLY_DESK_ID.metainfo.xml" + rm -f "$stage/usr/share/metainfo/$APP_ID.metainfo.xml" + rm -rf "$stage/usr/share/mime" "$stage/usr/share/icons/hicolor" + icon="$ROOT/assets/app-icon/lightcraft-nightly.png" + [[ -f "$icon" ]] || icon="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" + install -Dm644 "$icon" "$stage/usr/share/icons/hicolor/256x256/apps/$NIGHTLY_DESK_ID.png" + NIGHTLY_STAGE="$stage" +} +NIGHTLY_STAGE="" +[[ "$IS_NIGHTLY" = 1 ]] && stage_nightly + # ---- .tar.gz ------------------------------------------------------------------------------------ if has tar; then + TAR_SRC="${NIGHTLY_STAGE:-$STAGE}" mkdir -p "$WORK/tar" - cp -R "$STAGE/usr" "$WORK/tar/$BASENAME" + cp -R "$TAR_SRC/usr" "$WORK/tar/$BASENAME" 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 builds +# its own launchers from the real binaries, so it takes the stable-layout tree, not the Nightly +# usr/bin wrappers; the Nightly desktop, metainfo and icon are added beside them. +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" + # stage_nightly already exported the Nightly names: re-exporting the stable ones here pointed + # the rendered nfpm.yaml at files the Nightly stage has removed (and named the package + # `lightcraft`, colliding with stable). + if [[ -z "$NIGHTLY_STAGE" ]]; then + export NFPM_NAME="lightcraft" + export NFPM_BIN="lightcraft" + export NFPM_CLI="lightcraft-cli" + fi + NFPM_STAGE="$STAGE" + [[ -n "$NIGHTLY_STAGE" ]] && NFPM_STAGE="$NIGHTLY_STAGE" # 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 @@ -121,10 +217,40 @@ if has appimage; then esac APPDIR="$WORK/LightCraft.AppDir" cp -R "$STAGE" "$APPDIR" - ln -s usr/bin/lightcraft "$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 + APPIMAGE_ID="$APP_ID.nightly-v1" + cat >"$APPDIR/AppRun" <<'APPRUN' +#!/bin/sh +set -eu +HERE="$(dirname "$(readlink -f "$0")")" +# A real script (not the stable symlink), so an AppImage launch selects the Nightly profile even +# when the desktop entry's Exec is bypassed; APPIMAGE/APPDIR stay untouched for the app. +case "${1:-}" in + --launch-profile | --profile-root | --version | -V | --help | -h) exec "$HERE/usr/bin/lightcraft" "$@" ;; +esac +profile="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}/lightcraft-nightly" +exec "$HERE/usr/bin/lightcraft" --launch-profile nightly-v1 --profile-root "$profile" -- "$@" +APPRUN + chmod 755 "$APPDIR/AppRun" + sed -e "s|^Icon=$APP_ID$|Icon=$APPIMAGE_ID|" \ + -e "s|^Name=LightCraft$|Name=LightCraft 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" + NIGHTLY_ICON="$ROOT/assets/app-icon/lightcraft-nightly.png" + [[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" + 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 + ln -s usr/bin/lightcraft "$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" + fi TOOL="${APPIMAGETOOL:-$(command -v appimagetool || true)}" if [[ -z "$TOOL" ]]; then @@ -169,11 +295,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/lightcraft}" - UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|lightcraft-*-linux-$ARCH.AppImage.zsync" + UPDATE_ARGS=() + if [[ "$IS_NIGHTLY" = 0 ]]; then + UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|lightcraft-*-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 pre-release tags matching `-nightly` rather than stable `latest`. + UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest-pre|lightcraft-*-nightly*-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 100644 index 0000000000..600455d9e1 --- /dev/null +++ b/packaging/macos/nightly-lib.sh @@ -0,0 +1,119 @@ +# 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='LightCraft Nightly.app' +MAC_NIGHTLY_ID='ai.storyteller.lightcraft.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" =~ ^lightcraft-(.+)-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 +} + +# The keychain import-cert.sh made. Every app's import-cert.sh puts its keychain in a private mktemp +# directory under RUNNER_TEMP and names it after the app, so the exact path is not predictable from +# outside this run: require the app's name, this run's private work directory, and a regular file. +mac_nightly_keychain_is_ours() { + local keychain="$1" work="$2" + [[ "$keychain" == "$work"/lightcraft-signing.keychain-db || "$keychain" == "$work"/*/lightcraft-signing.keychain-db ]] || return 1 + [[ -f "$keychain" && ! -L "$keychain" ]] +} + +# 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 LightCraft +# 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")" == LightCraft ]] || mac_nightly_die 'Contents/MacOS must hold only the LightCraft GUI (no CLI)' + [[ -f "$app/Contents/MacOS/LightCraft" && -x "$app/Contents/MacOS/LightCraft" ]] || mac_nightly_die 'missing executable GUI' + [[ "$(lipo -archs "$app/Contents/MacOS/LightCraft")" == arm64 ]] || mac_nightly_die 'the GUI must be thin arm64' + plist="$app/Contents/Info.plist" + for key in CFBundleIdentifier CFBundleExecutable LightCraftVersion; 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" == LightCraft ]] ;; + LightCraftVersion) [[ "$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 0000000000..4f67f0c91c --- /dev/null +++ b/packaging/macos/nightly-sign.sh @@ -0,0 +1,141 @@ +#!/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/lightcraft--macos-aarch64-nightly.zip \ +# --output /abs//lightcraft--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%/}/lightcraft-nightly-sign.XXXXXX")" +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}$ ]] || mac_nightly_die 'import-cert.sh did not import a signing identity' +mac_nightly_keychain_is_ours "$KEYCHAIN" "$WORK" || mac_nightly_die 'import-cert.sh put the signing keychain outside this run 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 "==> LightCraft 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/LightCraft" +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 0000000000..16a3058b17 --- /dev/null +++ b/packaging/macos/nightly-verify.sh @@ -0,0 +1,78 @@ +#!/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/lightcraft--macos-aarch64-nightly.zip --expect signed [--team ID] +# nightly-verify.sh --input /abs/lightcraft--macos-aarch64-nightly.zip --expect unsigned +# +# Both: the archive holds only the GUI-only Nightly bundle with the exact LightCraftVersion, 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 `LightCraft (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" +# shellcheck source=../nightly-common.sh +. "$HERE/../nightly-common.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 +# Every platform's credentials, not only this Mac's: a job that carries a Windows, Azure or Linux key is +# still a signing job, and the payload must not run beside any of them. +for name in "${NIGHTLY_SIGNING_ENV[@]}"; 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}}/lightcraft-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/LightCraft" "$@" 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" == "LightCraft $VERSION (nightly-v1)" ]] || mac_nightly_die "the version query ($*) reports '$out', not LightCraft $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): LightCraft $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 0000000000..a29b3793a7 --- /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/lightcraft--macos-aarch64-nightly.zip LightCraft Nightly.app, unsigned +# +# Usage: packaging/macos/nightly.sh --arch aarch64 +# +# Required env (nightly-common.sh): LIGHTCRAFT_BUILD_CHANNEL=nightly-v1, LIGHTCRAFT_VERSION, +# LIGHTCRAFT_BUILD_SHA, LIGHTCRAFT_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/lightcraft-$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/LightCraft" +chmod 755 "$APP/Contents/MacOS/LightCraft" +cp "$ROOT/assets/app-icon/lightcraft-nightly.icns" "$APP/Contents/Resources/lightcraft-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 "$LIGHTCRAFT_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 0000000000..2114469634 --- /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.lightcraft.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="LightCraft Nightly", + CFBundleName="LightCraft Nightly", + CFBundleIdentifier=IDENTIFIER, + CFBundleExecutable="LightCraft", + CFBundleIconFile="lightcraft-nightly", + CFBundleShortVersionString=match[1], + CFBundleVersion=match[1], + LightCraftVersion=version, + LightCraftBuildCommit=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 0000000000..45380a8579 --- /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("light_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.lightcraft.nightly") + self.assertEqual(rendered["CFBundleExecutable"], "LightCraft") + self.assertEqual(rendered["LightCraftVersion"], VERSION) + self.assertEqual(rendered["LightCraftBuildCommit"], COMMIT) + self.assertTrue(VERSION.startswith(rendered["CFBundleVersion"] + "-nightly.")) + for key in ("LSMinimumSystemVersion", "CFBundleLocalizations", "NSHighResolutionCapable", "NSHumanReadableCopyright"): + 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["LightCraftVersion"], VERSION) + self.assertEqual(result["LightCraftBuildCommit"], 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())["LightCraftVersion"], 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 0000000000..e3606bcfb3 --- /dev/null +++ b/packaging/macos/nightly_sign_tests.py @@ -0,0 +1,429 @@ +#!/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("light_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"lightcraft-{VERSION}-macos-aarch64-nightly.zip" +APP = "LightCraft 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.lightcraft.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/LightCraft" + exe.write_text(gui or f"#!/bin/sh\ntouch {self.ran}\necho 'LightCraft {version} (nightly-v1)'\n") + exe.chmod(0o755) + (app / "Contents/Resources/lightcraft-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.lightcraft.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"lightcraft-0.23.1-macos-aarch64.zip", f"lightcraft-{VERSION}-macos-universal-nightly.zip", + f"lightcraft-{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=lightcraft-1234\nSignature=adhoc\nTeamIdentifier=not set\n", + DETAILS.replace("ai.storyteller.lightcraft.nightly", "ai.storyteller.lightcraft"), + DETAILS.replace("ai.storyteller.lightcraft.nightly", "aiXstorytellerXlightcraftXnightly")): + 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], ["LightCraft", 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/LightCraft").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/lightcraft-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 'LightCraft {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 'LightCraft 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 'LightCraft {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() + # Not only the Mac's own names: a job carrying a Windows, Azure or Linux key is still a signing + # job, and no tool or payload may run in it. + for name in ("APPLE_PASSWORD", "APPLE_CERTIFICATE", "MACOS_KEYCHAIN", "WINDOWS_CERTIFICATE", + "WINDOWS_CERTIFICATE_PASSWORD", "AZURE_CLIENT_SECRET", "AZURE_SIGNING_ACCOUNT", + "LINUX_SIGNING_KEY"): + 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"}, + LIGHTCRAFT_BUILD_CHANNEL="nightly-v1", LIGHTCRAFT_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 100755 index 0000000000..25f8ec7b67 --- /dev/null +++ b/packaging/nightly-archive.py @@ -0,0 +1,130 @@ +#!/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 + if name not in {"lightcraft", "lightcraft-bin", "lightcraft-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 = {"lightcraft", "lightcraft-bin", "lightcraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE"} + 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. + info = tarfile.TarInfo(os.path.basename(destination)) + 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 0000000000..4865468d95 --- /dev/null +++ b/packaging/nightly-common.sh @@ -0,0 +1,103 @@ +# 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 + [[ "${LIGHTCRAFT_BUILD_CHANNEL:-}" == nightly-v1 ]] || nightly_die 'LIGHTCRAFT_BUILD_CHANNEL must be nightly-v1' + [[ "${LIGHTCRAFT_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' + [[ "${LIGHTCRAFT_BUILD_SHA:-}" =~ ^[0-9a-f]{40}$ ]] || nightly_die 'an exact source commit is required' + [[ "${LIGHTCRAFT_VERSION##*.g}" == "${LIGHTCRAFT_BUILD_SHA:0:12}" ]] || nightly_die 'version/source commit mismatch' + [[ "${LIGHTCRAFT_BUILD_DATE:-}" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || nightly_die 'the original run-created UTC date is required' + date_digits="${LIGHTCRAFT_VERSION#*-nightly.}" + date_digits="${date_digits%%.*}" + [[ "${LIGHTCRAFT_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)" == "$LIGHTCRAFT_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 + # env.sh retains the established notice copier. Required values above prohibit its stable fallbacks. + # shellcheck source=env.sh + . "$ROOT/packaging/env.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 (packaging/macos/nightly-verify.sh). +nightly_compile_gui() { + # Signing material never reaches compilation (the Windows -CheckBuildEnvironment rule). + nightly_refuse_signing_env + (cd "$ROOT" && LIGHTCRAFT_OVERRIDE_VERSION="$VERSION" cargo build --release --locked -p lightcraft --features heif --target "$NIGHTLY_RUST_TARGET") + NIGHTLY_GUI="$CARGO_TARGET_DIR/$NIGHTLY_RUST_TARGET/release/lightcraft" + [[ -f "$NIGHTLY_GUI" && ! -L "$NIGHTLY_GUI" ]] || nightly_die 'the owned GUI build did not produce a regular executable' + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$LIGHTCRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the build' +} + +nightly_build_gui() { + nightly_compile_gui + local actual launcher + # What the binary really prints: the prepared feed identity plus the channel, as build_flavor's + # version string makes it (apps/lightcraft/src/build_flavor.rs). Both query forms are answered by + # prepare_launch before any profile or window work, so neither may need a profile on disk. + actual="$("$NIGHTLY_GUI" --version)" || nightly_die 'side-effect-free nightly version verification failed' + [[ "$actual" == "LightCraft $VERSION (nightly-v1)" ]] || nightly_die 'the built version/flavor is not the prepared identity' + launcher="$("$NIGHTLY_GUI" --launch-profile nightly-v1 --profile-root "$NIGHTLY_WORK/profile-query" --version)" \ + || nightly_die 'the Launcher profile version query failed' + [[ "$launcher" == "$actual" ]] || nightly_die 'the Launcher profile query differs from the plain version query' + # prepare_launch answers that query before any profile work, so it must leave nothing behind. + [[ ! -e "$NIGHTLY_WORK/profile-query" ]] || nightly_die 'the Launcher version query created a profile' + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$LIGHTCRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the version query' +} + +# Every signing name release.yml passes, for every platform, and import-cert.sh's outputs. A step that +# must never run beside signing material (compilation, macOS payload verification) refuses any of them. +NIGHTLY_SIGNING_ENV=(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) + +# Signing material never reaches compilation (the Windows -CheckBuildEnvironment rule). +nightly_refuse_signing_env() { + local name + for name in "${NIGHTLY_SIGNING_ENV[@]}"; 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; do + [[ -f "$ROOT/$required" && ! -L "$ROOT/$required" ]] || nightly_die "missing regular app notice: $required" + done + copy_docs "$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-icons-tests.py b/packaging/nightly-icons-tests.py new file mode 100755 index 0000000000..94cd445b67 --- /dev/null +++ b/packaging/nightly-icons-tests.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""The Nightly icon derivation: only the field's share changes; foreground and alpha do not. + +Runs on any host with the committed renders (no resvg, iconutil or network). The committed outputs +are re-derived with `--check`, so a hand-edited or stale icon fails here. +""" +import importlib.util +import subprocess +import sys +from pathlib import Path +import unittest + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("light_nightly_icons", HERE / "nightly-icons.py") +ICONS = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(ICONS) +ASSETS = HERE.parent / "assets" / "app-icon" + + +def pixels(path): + return ICONS.read_png(path.read_bytes()) + + +class Downsample(unittest.TestCase): + def test_transparent_padding_never_darkens_a_blocks_colour(self): + # A 2x2 block of one amber pixel and three transparent ones: the visible colour stays the amber + # it was (PNG RGB is straight, not premultiplied) and only the coverage drops to a quarter. + master = bytearray([154, 102, 16, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) + self.assertEqual(tuple(ICONS.downsample(2, 2, master, 1)), (154, 102, 16, 64)) + + def test_a_fully_transparent_block_stays_transparent(self): + self.assertEqual(tuple(ICONS.downsample(2, 2, bytearray(16), 1)), (0, 0, 0, 0)) + + def test_two_colours_mix_by_coverage(self): + master = bytearray([0, 0, 0, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0]) + self.assertEqual(tuple(ICONS.downsample(2, 2, master, 1)), (128, 128, 128, 128)) + + +class Recolour(unittest.TestCase): + def test_the_field_moves_and_the_figure_does_not(self): + for colour, expected in ( + (ICONS.BACKGROUND, ICONS.NIGHTLY_BACKGROUND), + (ICONS.PAPER, ICONS.PAPER), + (ICONS.INK, ICONS.INK), + ): + self.assertEqual(tuple(round(c + ICONS.background_weight(colour) * (expected[i] - ICONS.BACKGROUND[i])) for i, c in enumerate(colour)), expected) + + def test_a_paper_and_ink_blend_keeps_its_exact_colour(self): + # A real anti-aliased blend of the two foreground colours: no field share at all. + for t in (0.0, 0.25, 0.5, 0.75, 1.0): + blend = tuple(round(t * ICONS.INK[i] + (1 - t) * ICONS.PAPER[i]) for i in range(3)) + self.assertEqual(ICONS.background_weight(blend), 0.0, blend) + + def test_a_field_and_paper_blend_keeps_its_paper_and_loses_the_old_field(self): + blend = tuple(round(0.5 * ICONS.BACKGROUND[i] + 0.5 * ICONS.PAPER[i]) for i in range(3)) + self.assertAlmostEqual(ICONS.background_weight(blend), 0.5, delta=0.02) + + @unittest.skipUnless((ASSETS / "lightcraft-nightly.png").exists(), "the Nightly icons are not derived yet") + def test_the_committed_png_changes_only_the_field_and_keeps_alpha(self): + width, height, stable = pixels(ASSETS / "hicolor/256x256/apps/ai.storyteller.lightcraft.png") + derived_width, derived_height, nightly = pixels(ASSETS / "lightcraft-nightly.png") + self.assertEqual((width, height), (derived_width, derived_height)) + for i in range(0, len(stable), 4): + self.assertEqual(stable[i + 3], nightly[i + 3], "alpha must be preserved exactly") + colour = (stable[i], stable[i + 1], stable[i + 2]) + expected = tuple(min(255, max(0, round(colour[j] + ICONS.background_weight(colour) * (ICONS.NIGHTLY_BACKGROUND[j] - ICONS.BACKGROUND[j])))) for j in range(3)) + self.assertEqual(tuple(nightly[i:i + 3]), expected) + + @unittest.skipUnless((ASSETS / "lightcraft-nightly-1024.png").exists(), "the Nightly icons are not derived yet") + def test_the_padded_master_keeps_its_margin_and_its_frame_sizes(self): + # The macOS master is the padded drawing: its transparent margin must stay transparent, and + # no frame is ever upscaled from a smaller render. + width, height, nightly = pixels(ASSETS / "lightcraft-nightly-1024.png") + self.assertEqual((width, height), (1024, 1024)) + self.assertEqual(nightly[3], 0, "the padded Mac margin is transparent") + self.assertEqual(nightly[-1], 0, "the padded Mac margin is transparent") + ico = ICONS.read_ico((ASSETS / "lightcraft-nightly.ico").read_bytes()) + self.assertEqual(sorted(ico), list(ICONS.ICO_FRAMES)) + slots = ICONS.read_icns((ASSETS / "lightcraft-nightly.icns").read_bytes()) + for kind, size in ICONS.ICNS_EXISTING.items(): + self.assertEqual(ICONS.read_png(slots[kind])[0], size) + for size, kind in ICONS.ICNS_FROM_MASTER.items(): + self.assertEqual(ICONS.read_png(slots[kind])[0], size) + + @unittest.skipUnless((ASSETS / "lightcraft-nightly.icns").exists(), "the Nightly icons are not derived yet") + def test_the_committed_icons_are_the_committed_derivation(self): + result = subprocess.run([sys.executable, str(HERE / "nightly-icons.py"), "--check"], capture_output=True, text=True, timeout=900) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/packaging/nightly-icons.py b/packaging/nightly-icons.py new file mode 100644 index 0000000000..97fecde094 --- /dev/null +++ b/packaging/nightly-icons.py @@ -0,0 +1,324 @@ +#!/usr/bin/env python3 +"""Derive the LightCraft Nightly icon set from the committed stable renders. + +The stable artwork is untouched: only the background contribution changes from LightCraft amber +to the deeper Nightly amber. Every pixel is decomposed in the stable drawing's three-colour +palette (ink, paper, background) and rebuilt with the Nightly background, so the foreground lines, +the paper, the alpha and the macOS padding stay exactly as they were drawn. There is no letter, +crescent or other badge; the app and the Launcher name the channel in text. + +Sources (all committed, all rendered from assets/app-icon/lightcraft.svg): + * assets/app-icon/lightcraft.ico nine full-bleed frames, 16-256 px + * assets/app-icon/lightcraft.icns padded macOS frames, 32-1024 px + * assets/app-icon/hicolor/256x256/...png the 256 px full-bleed frame + * assets/app-icon/lightcraft-macos-512.png the padded macOS master + +Outputs: + * assets/app-icon/lightcraft-nightly.png full-bleed 256 px (Windows/Linux tar) + * assets/app-icon/lightcraft-nightly.ico nine full-bleed frames, 16-256 px + * assets/app-icon/lightcraft-nightly-1024.png padded macOS 1024 px master + * assets/app-icon/lightcraft-nightly.icns eleven padded macOS frames, 16-1024 px + +Usage: python3 packaging/nightly-icons.py [--check] +`--check` re-derives into memory and compares the committed outputs' SHA-256 instead of writing. +""" +import argparse +import hashlib +import io +import struct +import sys +import zlib +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +ICONS = ROOT / "assets" / "app-icon" + +# The stable drawing's three colours (assets/app-icon/README.md) and the Nightly background. +INK = (0x0B, 0x0B, 0x0C) +PAPER = (0xEF, 0xE9, 0xDC) +BACKGROUND = (0xF2, 0xA5, 0x16) +NIGHTLY_BACKGROUND = (0x9A, 0x66, 0x10) + +ICO_FRAMES = (16, 20, 24, 32, 40, 48, 64, 128, 256) +# Padded macOS slots by pixel size: PNG slots the committed icns already holds, and the three +# small ones derived from the padded 512 px master. +ICNS_FROM_MASTER = {16: "icp4", 32: "icp5", 64: "icp6"} +# The padded frames the committed icns already holds, by slot and pixel size (16@2x, 32@2x, ...). +ICNS_EXISTING = {"ic11": 32, "ic12": 64, "ic07": 128, "ic08": 256, "ic13": 256, "ic09": 512, "ic14": 512, "ic10": 1024} + + +def read_png(data: bytes): + """Decode an 8-bit RGB/RGBA, non-interlaced PNG into (width, height, RGBA bytes).""" + if data[:8] != b"\x89PNG\r\n\x1a\n": + raise ValueError("not a PNG") + offset, header, compressed = 8, None, bytearray() + while offset < len(data): + length, kind = struct.unpack_from(">I4s", data, offset) + body = data[offset + 8:offset + 8 + length] + if kind == b"IHDR": + header = struct.unpack(">IIBBBBB", body) + elif kind == b"IDAT": + compressed += body + elif kind == b"IEND": + break + offset += 12 + length + width, height, depth, colour, _, _, interlace = header + if depth != 8 or colour not in (2, 6) or interlace != 0: + raise ValueError("expected an 8-bit non-interlaced RGB/RGBA PNG") + channels = 3 if colour == 2 else 4 + stride = width * channels + raw = zlib.decompress(bytes(compressed)) + if len(raw) != height * (stride + 1): + raise ValueError("unexpected PNG payload length") + pixels = bytearray(width * height * 4) + previous = bytearray(stride) + for y in range(height): + start = y * (stride + 1) + filter_kind = raw[start] + line = bytearray(raw[start + 1:start + 1 + stride]) + if filter_kind == 1: + for i in range(channels, stride): + line[i] = (line[i] + line[i - channels]) & 0xFF + elif filter_kind == 2: + for i in range(stride): + line[i] = (line[i] + previous[i]) & 0xFF + elif filter_kind == 3: + for i in range(stride): + left = line[i - channels] if i >= channels else 0 + line[i] = (line[i] + ((left + previous[i]) >> 1)) & 0xFF + elif filter_kind == 4: + for i in range(stride): + a = line[i - channels] if i >= channels else 0 + b = previous[i] + c = previous[i - channels] if i >= channels else 0 + p = a + b - c + pa, pb, pc = abs(p - a), abs(p - b), abs(p - c) + line[i] = (line[i] + (a if pa <= pb and pa <= pc else b if pb <= pc else c)) & 0xFF + elif filter_kind != 0: + raise ValueError("unknown PNG filter") + previous = line + out = y * width * 4 + if channels == 4: + pixels[out:out + width * 4] = line + else: + for x in range(width): + pixels[out + x * 4:out + x * 4 + 3] = line[x * 3:x * 3 + 3] + pixels[out + x * 4 + 3] = 255 + return width, height, pixels + + +def write_png(width: int, height: int, pixels: bytearray) -> bytes: + stride = width * 4 + raw = bytearray() + for y in range(height): + raw.append(0) + raw += pixels[y * stride:(y + 1) * stride] + + def chunk(kind: bytes, body: bytes) -> bytes: + return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body) & 0xFFFFFFFF) + + return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(bytes(raw), 9)) + chunk(b"IEND", b"")) + + +def _pairs(): + """The three two-colour mixtures the artwork can contain. + + The stable drawing is a flat amber field, then paper shapes and ink lines drawn over it, so an + edge pixel is a blend of exactly two of the three colours (a triple junction of three opacity + layers is not something the renderer produces). Solving all three weights at once is numerically + unstable here — ink and paper are nearly collinear with the neutral axis, and a half-unit of + rounding moves the ink/paper split by more than one — so each pixel is projected onto the nearest + two-colour segment instead. That is exact for a real blend, and a neutral pixel keeps its exact + ink/paper colour because the background's weight in that pair is zero. + """ + return ((INK, PAPER), (INK, BACKGROUND), (PAPER, BACKGROUND)) + + +def _project(colour, a, b): + """`(t, residual)` for the closest point to `colour` on the segment a + t (b - a).""" + direction = [b[i] - a[i] for i in range(3)] + length = sum(c * c for c in direction) + t = sum((colour[i] - a[i]) * direction[i] for i in range(3)) / length + t = min(1.0, max(0.0, t)) + residual = sum((colour[i] - (a[i] + t * direction[i])) ** 2 for i in range(3)) + return t, residual + + +def background_weight(colour) -> float: + """How much of this stable pixel is the amber field, in [0, 1].""" + if colour == BACKGROUND: + return 1.0 + best = (0.0, None, 0.0) + for a, b in _pairs(): + t, residual = _project(colour, a, b) + if best[1] is None or residual < best[2]: + best = (t, (a, b), residual) + t, (a, b), _ = best + if a == BACKGROUND: + return 1.0 - t + if b == BACKGROUND: + return t + return 0.0 + + +def recolour(pixels: bytearray) -> bytearray: + """Rebuild every pixel with the Nightly background, keeping its ink and paper exactly. + + The field's share of a blend pixel moves from BACKGROUND to NIGHTLY_BACKGROUND along that one + axis, so anti-aliasing against the new field is what the drawing would have looked like on it. + """ + shift = [NIGHTLY_BACKGROUND[i] - BACKGROUND[i] for i in range(3)] + out = bytearray(len(pixels)) + for i in range(0, len(pixels), 4): + alpha = pixels[i + 3] + if alpha == 0: + out[i + 3] = 0 + continue + colour = (pixels[i], pixels[i + 1], pixels[i + 2]) + weight = background_weight(colour) + out[i:i + 3] = bytes(min(255, max(0, round(colour[j] + weight * shift[j]))) for j in range(3)) + out[i + 3] = alpha + return out + + +def downsample(width: int, height: int, pixels: bytearray, size: int) -> bytearray: + """Box-filter `pixels` to `size` x `size`: only used to shrink the padded master, never to grow a frame.""" + if size > width or size > height: + raise ValueError("a frame is never upscaled") + factor = width // size + if factor * size != width or height != width: + raise ValueError("the master must divide evenly into each slot") + out = bytearray(size * size * 4) + area = factor * factor + for y in range(size): + for x in range(size): + weighted = [0, 0, 0] + alpha = 0 + for dy in range(factor): + row = ((y * factor + dy) * width + x * factor) * 4 + for dx in range(factor): + at = row + dx * 4 + # PNG stores straight alpha, so the colour is its alpha-weighted share of the + # block: averaging RGB by area would let transparent padding darken the edge. + coverage = pixels[at + 3] + for channel in range(3): + weighted[channel] += pixels[at + channel] * coverage + alpha += coverage + at = (y * size + x) * 4 + if alpha == 0: + continue + out[at] = round(weighted[0] / alpha) + out[at + 1] = round(weighted[1] / alpha) + out[at + 2] = round(weighted[2] / alpha) + out[at + 3] = round(alpha / area) + return out + + +def read_ico(data: bytes): + """Every PNG frame of an .ico as {size: png bytes}.""" + if data[:4] != b"\x00\x00\x01\x00": + raise ValueError("not an .ico") + count = struct.unpack_from(" bytes: + header = struct.pack("= 256 else size + entries += struct.pack("4sI", data, offset) + body = data[offset + 8:offset + length] + if body[:8] == b"\x89PNG\r\n\x1a\n": + slots[kind.decode("ascii")] = body + offset += length + return slots + + +def write_icns(slots) -> bytes: + order = ["icp4", "icp5", "icp6", "ic07", "ic08", "ic09", "ic10", "ic11", "ic12", "ic13", "ic14"] + body = bytearray() + for kind in order: + payload = slots[kind] + body += kind.encode("ascii") + struct.pack(">I", len(payload) + 8) + payload + return b"icns" + struct.pack(">I", len(body) + 8) + bytes(body) + + +def derive(): + """Build every Nightly artifact in memory: {relative path: bytes}.""" + outputs = {} + ico = read_ico((ICONS / "lightcraft.ico").read_bytes()) + nightly_frames = {} + for size in ICO_FRAMES: + width, height, pixels = read_png(ico[size]) + if width != size: + raise ValueError(f"the {size} px .ico frame is {width} px") + nightly_frames[size] = write_png(width, height, recolour(pixels)) + outputs["lightcraft-nightly.ico"] = write_ico(nightly_frames) + + two_fifty_six = read_png((ICONS / "hicolor/256x256/apps/ai.storyteller.lightcraft.png").read_bytes()) + outputs["lightcraft-nightly.png"] = write_png(two_fifty_six[0], two_fifty_six[1], recolour(two_fifty_six[2])) + + master = read_png((ICONS / "lightcraft-macos-512.png").read_bytes()) + recoloured_master = recolour(master[2]) + existing = read_icns((ICONS / "lightcraft.icns").read_bytes()) + slots = {} + for size, kind in ICNS_FROM_MASTER.items(): + slots[kind] = write_png(size, size, downsample(master[0], master[1], recoloured_master, size)) + for kind, size in ICNS_EXISTING.items(): + width, height, pixels = read_png(existing[kind]) + if width != size or height != size: + raise ValueError(f"the {kind} slot is {width}x{height}, not {size}x{size}") + slots[kind] = write_png(width, height, recolour(pixels)) + if size == 1024: + outputs["lightcraft-nightly-1024.png"] = slots[kind] + outputs["lightcraft-nightly.icns"] = write_icns(slots) + return outputs + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true", help="compare the committed outputs instead of writing") + args = parser.parse_args() + outputs = derive() + failed = False + for name, content in sorted(outputs.items()): + path = ICONS / name + digest = hashlib.sha256(content).hexdigest() + if args.check: + current = hashlib.sha256(path.read_bytes()).hexdigest() if path.exists() else "missing" + status = "ok" if current == digest else "differs" + failed |= current != digest + print(f"{status:8} {name} {digest}") + else: + path.write_bytes(content) + print(f"wrote {name} {digest} ({len(content)} bytes)") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py new file mode 100755 index 0000000000..4184346cfc --- /dev/null +++ b/packaging/nightly-release-tests.py @@ -0,0 +1,421 @@ +#!/usr/bin/env python3 +"""Local regression fixtures for LightCraft nightly workflows and signing policy.""" +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": "lightcraft-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] + + +def secret_declarations(source): + """Every uncommented line that declares `environment:` or `secrets:` at any depth. + + YAML keys may be quoted, so `"secrets": inherit` is the same header as `secrets: inherit`; + the check rejects both instead of trusting an unquoted spelling. + """ + hits = [] + for line in source.splitlines(): + if line.lstrip().startswith("#"): + continue + if re.match(r"\s*(?:-\s*)?[\"']?(?:environment|secrets)[\"']?\s*:", line, re.IGNORECASE): + hits.append(line) + return hits + + +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_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: lightcraft-nightly-release", "group: ${{ github.run_id }}"), + ("group: lightcraft-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.assertEqual(secret_declarations(executable), [], "no environment or secrets header") + self.assertNotIn("secrets.", executable) + + def test_quoted_secret_headers_are_rejected_like_unquoted_ones(self): + source = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + for line in (' secrets: inherit', + ' "secrets": inherit', + " 'secrets': inherit", + ' environment: release', + ' ENVIRONMENT: release'): + with self.subTest(line=line): + self.assertEqual(secret_declarations(source + "\n" + line + "\n"), [line]) + self.assertEqual(secret_declarations(source), []) + + +class NightlyTrustAnchors(unittest.TestCase): + """The public stable identities each platform's signed nightly must carry (all three platforms).""" + + def setUp(self): + self.policy = json.loads(INSTALLED_POLICY.read_text()) + + def test_each_platform_row_names_its_fixed_artifact_kind_and_stable_identity(self): + self.assertEqual(set(self.policy["platforms"]), set(NIGHTLY_TRUST)) + for platform, (field, value) in NIGHTLY_TRUST.items(): + row = self.policy["platforms"][platform] + with self.subTest(platform=platform): + self.assertEqual(row["unsigned_artifact_name"], f"nightly-unsigned-{platform}", + "the artifact kind is fixed by platform, never a caller pattern") + self.assertEqual(row["trust"], {field: value}, "trust must be stable's public identity") + + def test_trust_values_have_the_shapes_the_shared_signer_accepts(self): + rows = self.policy["platforms"] + self.assertRegex(rows["macos-aarch64"]["trust"]["apple_team_id"], r"^[A-Z0-9]{10}$") + self.assertRegex(rows["linux-x86_64"]["trust"]["fingerprint"], r"^[0-9A-F]{40}$") + subject = rows["windows-x86_64"]["trust"]["publisher_subject"] + self.assertTrue(0 < len(subject) <= 1024 and not set(subject) & {"\r", "\n", "\0"}) + + 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/lightcraft' && github.ref == 'refs/heads/main' && " + "github.ref_type == 'branch' && (github.event_name == 'schedule' || " + "github.event_name == 'workflow_dispatch')", + "nightly-sign.yml": "github.repository == 'storytold/lightcraft' && 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) + + +def push_block(source): + """The whole `push:` mapping, blank lines and nested keys included. + + A blank line does not end a YAML mapping, so the block is delimited by indentation rather than + by contiguous non-empty lines; a path filter after a blank line stays visible to the check. + """ + lines = source.splitlines() + for index, line in enumerate(lines): + if re.fullmatch(r" push:.*", line): + block = [] + for follow in lines[index + 1:]: + if follow.strip() and not follow.startswith(" "): + break + block.append(follow) + return "\n".join(block) + return None + + +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/lightcraft") + 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 None 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_equal_the_producer(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)) + + 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/lightcraft", "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 = push_block(source) + self.assertIsNotNone(push, "a required workflow must run on main pushes") + self.assertIn("branches: [main]", push) + self.assertNotRegex(push, r"(?m)^\s+paths(?:-ignore)?:", "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_a_path_filter_after_a_blank_line_is_still_rejected(self): + workflow = "on:\n push:\n branches: [main]\n\n paths: ['src/**']\n workflow_dispatch: {}\n" + block = push_block(workflow) + self.assertIsNotNone(block) + self.assertIn("branches: [main]", block) + self.assertRegex(block, r"(?m)^\s+paths(?:-ignore)?:") + for ignored in ("paths: ['src/**']", "paths-ignore: ['docs/**']"): + with self.subTest(ignored=ignored): + variant = workflow.replace(ignored.split(":")[0] + ": ['src/**']", ignored) + self.assertRegex(push_block(variant), r"(?m)^\s+paths(?:-ignore)?:", + "a quoted or unquoted filter must not hide behind a blank line") + + 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 0000000000..584d97b378 --- /dev/null +++ b/packaging/nightly-tests.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +"""Run the synthetic nightly packaging suites together; no app build, signing or network. + +The Linux archive and caller contract suite is packaging/nightly-release-tests.py; the macOS +scripts run here on any POSIX host against generated fixtures and stand-in Apple tools. The Windows +suites (packaging/windows/nightly-*-tests.ps1) need pwsh and run in their own job. +""" +import importlib.util +from pathlib import Path +import unittest + + +def main() -> int: + here = Path(__file__).resolve().parent + suite = unittest.TestSuite() + for name, relative in ( + ("light_icon_suite", "nightly-icons-tests.py"), + ("light_plist_suite", "macos/nightly_plist_tests.py"), + ("light_release_dispatch_suite", "nightly-release-tests.py"), + ("light_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)) + 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 0000000000..792198589e --- /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 0000000000..b9ccbe6f8c --- /dev/null +++ b/packaging/windows/nightly-package-tests.ps1 @@ -0,0 +1,102 @@ +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 'lightcraft-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 'lightcraft.exe') 'nightly must not ship the unqualified CLI' +Assert ($spec.AppId -eq 'ai.storyteller.lightcraft.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 'LightCraft Nightly' 'LightCraft 0.23.1-nightly.20261120.17.1.gabcdef012345 (nightly-v1)' '0.23.1-nightly.20261120.17.1.gabcdef012345' +foreach ($pair in @(@('LightCraft', 'LightCraft 0.23.1 (nightly-v1)'), @('LightCraft Nightly', 'LightCraft 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/lightcraft/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' + $interDir = Join-Path $repo 'assets\fonts' + New-Item -ItemType Directory -Force -Path $repo, $family, $stage, $interDir | 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" } + # Inter is embedded in every build, so its OFL must reach the stage and the ZIP. + Set-Content -LiteralPath (Join-Path $interDir 'OFL-Inter.txt') -Value 'inter-notice-example' + Set-Content -LiteralPath (Join-Path $family 'OFL.txt') -Value 'font-notice-example' + $notices = @($rootNames) + @('OFL-Inter.txt', 'OFL-ExampleFamily.txt') + Copy-NightlyNotices $repo $fontRepo $stage + foreach ($name in $notices) { + 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 $notices) { Assert ($name -in $names) "missing archived notice $name" } + foreach ($forbidden in @('portable.txt', 'lightcraft-cli.exe')) { Assert ($forbidden -notin $names) "unexpected payload $forbidden" } + $interEntry = $archive.GetEntry('OFL-Inter.txt') + $interReader = [IO.StreamReader]::new($interEntry.Open()) + try { Assert ($interReader.ReadToEnd().Contains('inter-notice-example')) 'wrong Inter license bytes in ZIP' } finally { $interReader.Dispose() } + $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 0000000000..7a3e749960 --- /dev/null +++ b/packaging/windows/nightly-signing-tests.ps1 @@ -0,0 +1,91 @@ +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','LIGHTCRAFT_BUILD_SHA','LIGHTCRAFT_BUILD_DATE') +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 +# nightly.ps1 builds the checkout it lives in, and its source identity must name that commit: the +# version's trailing 12 hex are the checkout's, and LIGHTCRAFT_BUILD_DATE is the version's own date. +$repositoryRoot = (Resolve-Path (Join-Path $PackagingRoot '..\..')).Path +$sourceState = Get-NightlySourceState $repositoryRoot +if ($sourceState.Status) { throw "these contracts need a clean checkout: $($sourceState.Status)" } +$version = '0.23.1-nightly.20261121.12345.1.g' + $sourceState.Head.Substring(0, 12) +$env:LIGHTCRAFT_VERSION = $version +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 + $env:LIGHTCRAFT_BUILD_SHA = $sourceState.Head + $env:LIGHTCRAFT_BUILD_DATE = '2026-11-21' + Invoke-Refusal { Invoke-Build -BuildOnly } 'FIXTURE_COMPILER_BOUNDARY' + Clear-SigningFixtures + 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 0000000000..714cb46bf4 --- /dev/null +++ b/packaging/windows/nightly.ps1 @@ -0,0 +1,140 @@ +<# 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 = "lightcraft-$Version-windows-x86_64-nightly.zip" + UnsignedArchive = "lightcraft-$Version-windows-x86_64-nightly.unsigned.zip" + Executables = @('lightcraft.exe') + Channel = 'nightly-v1' + AppId = 'ai.storyteller.lightcraft.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 (LIGHTCRAFT_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 (LIGHTCRAFT_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 'LightCraft Nightly' -or $VersionOutput -cne "LightCraft $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 } + } + # Inter is embedded in every GUI build (crates/ui-egui/src/theme.rs), so its OFL ships with the + # executable as OFL-Inter.txt beside the craft-fonts OFLs - the same set the stable FONT-LICENCES.txt + # collects. NOTICE names it, so a ZIP without it distributes the font unlicensed. + $inter = Join-Path $RepositoryRoot 'assets\fonts\OFL-Inter.txt' + if (-not (Test-Path -LiteralPath $inter -PathType Leaf)) { throw 'the app has no assets/fonts/OFL-Inter.txt to ship with the embedded Inter font' } + Copy-Item -LiteralPath $inter -Destination (Join-Path $Destination 'OFL-Inter.txt') + 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:LIGHTCRAFT_VERSION -or $Version -cne $env:LIGHTCRAFT_VERSION) { throw 'nightly-v1 requires explicit LIGHTCRAFT_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:LIGHTCRAFT_BUILD_SHA $env:LIGHTCRAFT_BUILD_DATE $Source.Head $Source.Status +$oldChannel = $env:LIGHTCRAFT_BUILD_CHANNEL +$oldVersionOverride = $env:LIGHTCRAFT_OVERRIDE_VERSION +try { + $env:LIGHTCRAFT_BUILD_CHANNEL = 'nightly-v1' + $env:LIGHTCRAFT_VERSION = $Version + $env:LIGHTCRAFT_OVERRIDE_VERSION = $Version + $env:LIGHTCRAFT_REQUIRE_WINRES = '1' + $env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS = '-C target-feature=+crt-static' + cargo build --release --locked -p lightcraft --features heif --target $Target + if ($LASTEXITCODE -ne 0) { throw "nightly cargo build failed: $LASTEXITCODE" } +} finally { + $env:LIGHTCRAFT_BUILD_CHANNEL = $oldChannel + $env:LIGHTCRAFT_OVERRIDE_VERSION = $oldVersionOverride +} +$Source = Get-NightlySourceState $Root +try { Assert-NightlySource $Version $env:LIGHTCRAFT_BUILD_SHA $env:LIGHTCRAFT_BUILD_DATE $Source.Head $Source.Status } +catch { throw "source changed during the build: $_" } +$Exe = Join-Path $TargetDir "$Target\release\lightcraft.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 'LightCraft 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 'lightcraft.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 ('lightcraft.exe' -notin $Names -or 'lightcraft-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 9cd0da6a2f..89372a69da 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -25,9 +25,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) { @@ -77,12 +80,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:LIGHTCRAFT_BUILD_SHA) { $env:LIGHTCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } -if (-not $env:LIGHTCRAFT_BUILD_DATE) { $env:LIGHTCRAFT_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:LIGHTCRAFT_BUILD_SHA) { $env:LIGHTCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } + if (-not $env:LIGHTCRAFT_BUILD_DATE) { $env:LIGHTCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } +} Write-Output "LightCraft $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:LIGHTCRAFT_BUILD_CHANNEL = 'stable' . (Join-Path $PSScriptRoot 'fonts.ps1') Initialize-CraftFonts $Root # Static CRT: no VC++ redistributable needed. Scoped to the target so host build scripts and @@ -112,6 +124,9 @@ foreach ($check in @(@('lightcraft.exe', 2), @('lightcraft-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 'lightcraft.exe')).VersionInfo.ProductName -eq 'LightCraft Nightly') { + throw 'a nightly executable cannot be packaged as stable' +} $Stage = Join-Path $TargetDir "windows-package\$Arch" Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Stage | Out-Null diff --git a/packaging/windows/sign.ps1 b/packaging/windows/sign.ps1 index 0a226f9b2c..6ae9fb2fe8 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/lightcraft.exe dist/Lightcraft.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 462b15b797..1cbf0b3b68 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -1,6 +1,6 @@ sonar.projectKey=storytold_lightcraft sonar.organization=storytold -sonar.coverage.exclusions=**/tools/**,**/docs/**,**/examples/** +sonar.coverage.exclusions=**/tools/**,**/docs/**,**/examples/**,packaging/** # Setting sonar.tests without sonar.sources stops the scanner defaulting to the whole repository, # which left only the packaging test indexed and the main branch analysed as empty. Sources and @@ -8,5 +8,5 @@ sonar.coverage.exclusions=**/tools/**,**/docs/**,**/examples/** # analysed as tests (outside production metrics and coverage) rather than left out. sonar.sources=. sonar.tests=. -sonar.test.inclusions=**/tests/**,**/tests.rs,**/tests_*.rs,**/*_tests.rs,**/test_*.py +sonar.test.inclusions=**/tests/**,**/tests.rs,**/tests_*.rs,**/*_tests.rs,**/test_*.py,packaging/nightly-tests.py,packaging/nightly-icons-tests.py,packaging/nightly-release-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 sonar.python.coverage.reportPaths=python-coverage.xml