diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json new file mode 100644 index 00000000..92288670 --- /dev/null +++ b/.github/nightly-signing-policy.json @@ -0,0 +1,110 @@ +{ + "schema": "craft-nightly-release-policy/v3", + "repository": "storytold/texturecraft", + "repository_id": 1419654881, + "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": "texturecraft-nightly-20261124", + "repository": "storytold/texturecraft", + "branch": "main", + "required_workflows": [ + { + "workflow_id": 384666426, + "workflow_path": ".github/workflows/ci.yml", + "jobs": [ + { + "name": "gate / gate (ubuntu-24.04)", + "app_id": 15368, + "applicability": "required" + }, + { + "name": "gate / gate (windows-latest)", + "app_id": 15368, + "applicability": "required" + } + ] + } + ], + "sonar": { + "organization": "storytold", + "project": "storytold_texturecraft", + "app_id": 12526, + "check_name": "SonarCloud Code Analysis", + "details_url": "https://sonarcloud.io/dashboard?id=storytold_texturecraft&branch=main", + "issue_types": [ + "VULNERABILITY" + ], + "accepted_conditions": [], + "required_conditions": [ + { + "metric": "new_security_rating", + "comparator": "GT", + "error_threshold": "1" + }, + { + "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-macos.yml b/.github/workflows/nightly-macos.yml new file mode 100644 index 00000000..75134544 --- /dev/null +++ b/.github/workflows/nightly-macos.yml @@ -0,0 +1,91 @@ +name: Nightly macOS build + +# Builds the unsigned Apple-silicon TextureCraft 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 minutes are shared with release builds: pull requests run this only with the `full-ci` + # label, 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@605d58766e8f536564da8fc81d3676ac86816dea + with: + ref: aced4137c022f1f587624d48e81ec77e1914a9cc + - uses: storytold/craft-common-actions/actions/checkout-craft-i18n@605d58766e8f536564da8fc81d3676ac86816dea + - id: rust + uses: storytold/craft-common-actions/actions/rust-channel@605d58766e8f536564da8fc81d3676ac86816dea + 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 "TEXTURECRAFT_BUILD_SHA=$sha" + echo "TEXTURECRAFT_BUILD_DATE=$date" + echo "TEXTURECRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}" + } >>"$GITHUB_ENV" + - name: Build the unsigned Nightly bundle + env: + TEXTURECRAFT_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/texturecraft-$TEXTURECRAFT_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: texturecraft-nightly-macos-aarch64-unsigned + path: ${{ runner.temp }}/nightly-dist/texturecraft-${{ env.TEXTURECRAFT_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 00000000..d07db551 --- /dev/null +++ b/.github/workflows/nightly-sign.yml @@ -0,0 +1,42 @@ +name: TextureCraft 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: texturecraft-nightly-release + cancel-in-progress: false + +jobs: + release: + # Actual context guards: official repository, manual dispatch, real release branch. + if: >- + github.repository == 'storytold/texturecraft' && + 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 00000000..5345fe9a --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,34 @@ +name: TextureCraft 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/texturecraft' && + 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: texturecraft + manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' + craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc + # 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 f54b0538..feb8675d 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -21,3 +21,7 @@ jobs: lint: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/packaging-lint.yml@main + with: + # Runs the Nightly synthetic suites, the launcher tests and `bash -n` here, so the checks + # that need no compiler are part of CI rather than a local step. + extra-checks-script: packaging/nightly-checks.sh diff --git a/.gitignore b/.gitignore index 0996cb2f..14362878 100644 --- a/.gitignore +++ b/.gitignore @@ -7,5 +7,11 @@ target/ /log /secrets /temp +# The shared nightly workflow checks these out into the workspace; `nightly_init` refuses a dirty tree. +/.nightly-tools +/.nightly-input /craft-fonts +/craft-i18n +__pycache__/ +*.pyc *.tcraft.tmp diff --git a/apps/texturecraft-cli/build.rs b/apps/texturecraft-cli/build.rs index 37e0bd12..d58a4323 100644 --- a/apps/texturecraft-cli/build.rs +++ b/apps/texturecraft-cli/build.rs @@ -1,2 +1,71 @@ -// The same build provenance and Windows icon/VERSIONINFO as the app; see that file. -include!("../texturecraft/build.rs"); +// Provenance for the headless CLI: the same commit and date variables as the app, and (Windows +// only) its own icon and VERSIONINFO into `texturecraft-cli.exe`. +// +// This is deliberately not an `include!` of the app's build script: that one resolves a `#[path]` +// submodule and reads the Nightly channel, neither of which a CLI build has any use for, and a +// module path inside an included script is resolved from the included file, not from here. + +use std::process::Command; + +const ICON: &str = "../../assets/app-icon/texturecraft.ico"; + +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-changed={ICON}"); + for var in ["TEXTURECRAFT_BUILD_SHA", "TEXTURECRAFT_BUILD_DATE", "TEXTURECRAFT_REQUIRE_WINRES", "SOURCE_DATE_EPOCH"] { + println!("cargo:rerun-if-env-changed={var}"); + } + println!("cargo:rustc-env=TEXTURECRAFT_BUILD_SHA={}", env_or("TEXTURECRAFT_BUILD_SHA", git_sha)); + println!("cargo:rustc-env=TEXTURECRAFT_BUILD_DATE={}", env_or("TEXTURECRAFT_BUILD_DATE", today)); + + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { + windows_resources(); + } +} + +fn env_or(var: &str, fallback: fn() -> Option) -> String { + std::env::var(var).ok().map(|v| v.trim().to_owned()).filter(|v| !v.is_empty()).or_else(fallback).unwrap_or_default() +} + +fn git_sha() -> Option { + let out = Command::new("git").args(["rev-parse", "HEAD"]).output().ok().filter(|o| o.status.success())?; + let sha = String::from_utf8(out.stdout).ok()?.trim().to_owned(); + (sha.len() >= 7 && sha.bytes().all(|b| b.is_ascii_hexdigit())).then_some(sha) +} + +/// UTC date of `SOURCE_DATE_EPOCH`, or of now. +fn today() -> Option { + let secs = match std::env::var("SOURCE_DATE_EPOCH") { + Ok(v) => v.trim().parse::().ok()?, + Err(_) => std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok()?.as_secs(), + }; + // Days since 1970-01-01 to a civil date (Howard Hinnant's algorithm, proleptic Gregorian). + let z = i64::try_from(secs / 86_400).ok()? + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + Some(format!("{year:04}-{month:02}-{day:02}")) +} + +fn windows_resources() { + let mut res = winresource::WindowsResource::new(); + res.set_icon(ICON) + .set("ProductName", "TextureCraft") + .set("FileDescription", "TextureCraft command-line tool") + .set("CompanyName", "Learning Machines LLC") + .set("LegalCopyright", "Copyright (c) the TextureCraft contributors. MIT OR Apache-2.0.") + .set("OriginalFilename", "texturecraft-cli.exe") + .set("InternalName", "texturecraft-cli"); + if let Err(e) = res.compile() { + if std::env::var_os("TEXTURECRAFT_REQUIRE_WINRES").is_some() { + println!("cargo::error=embedding Windows resources into texturecraft-cli.exe failed: {e}"); + } else { + println!("cargo:warning=texturecraft-cli.exe built without icon/version resources: {e}"); + } + } +} diff --git a/apps/texturecraft-cli/src/main.rs b/apps/texturecraft-cli/src/main.rs index f15dc209..c38b323a 100644 --- a/apps/texturecraft-cli/src/main.rs +++ b/apps/texturecraft-cli/src/main.rs @@ -120,8 +120,18 @@ fn version() -> String { } } +/// The desktop app's Nightly launch options. The CLI never takes them: a Nightly install ships the +/// GUI only, and a script that passes them to the CLI has the wrong program. +fn is_launch_profile_flag(arg: &str) -> bool { + arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=") +} + fn main() { let args: Vec = std::env::args().skip(1).collect(); + if let Some(flag) = args.iter().find(|arg| is_launch_profile_flag(arg.as_str())) { + eprintln!("texturecraft-cli: `{flag}` is a TextureCraft desktop launch option, not a CLI argument"); + std::process::exit(2); + } let code = match args.first().map(String::as_str) { None => { eprint!("{USAGE}"); diff --git a/apps/texturecraft/Cargo.toml b/apps/texturecraft/Cargo.toml index e0c2f660..7f5ee538 100644 --- a/apps/texturecraft/Cargo.toml +++ b/apps/texturecraft/Cargo.toml @@ -30,7 +30,8 @@ ron = "0.12" # borderless (src/window_frame.rs; winsafe is MIT, User32 only). [target.'cfg(windows)'.dependencies] winit = { version = "0.30", default-features = false } -winsafe = { version = "0.0.29", default-features = false, features = ["user"] } +# `shell` carries SetCurrentProcessExplicitAppUserModelID, the Nightly taskbar identity (src/process_identity.rs). +winsafe = { version = "0.0.29", default-features = false, features = ["user", "shell"] } # The update helper is a copy of this program (`main`). craft-update = { workspace = true } diff --git a/apps/texturecraft/build.rs b/apps/texturecraft/build.rs index c77d91bd..9f712207 100644 --- a/apps/texturecraft/build.rs +++ b/apps/texturecraft/build.rs @@ -2,31 +2,78 @@ // // Shared by `texturecraft` and `texturecraft-cli` (whose build.rs `include!`s this file). // +// - Sets `TEXTURECRAFT_VERSION` for `env!`: the prepared Nightly feed identity when +// `TEXTURECRAFT_BUILD_CHANNEL=nightly-v1`, else the workspace package version. A Nightly build +// without a well-formed `TEXTURECRAFT_VERSION` fails rather than falling back to the Cargo +// version, so an archive can never carry the wrong identity. // - Always sets `TEXTURECRAFT_BUILD_SHA` (full git commit) and `TEXTURECRAFT_BUILD_DATE` // (`YYYY-MM-DD`, UTC) for `env!`. They come from the same-named environment variables (CI and // packaging/env.sh set them), else from `git` and the clock (`SOURCE_DATE_EPOCH` wins for // reproducible builds); either is an empty string when unknown, so source tarballs, wasm and // offline builds still compile. Without the env vars the commit is read when this script runs, // so a local build can show a stale commit; release builds always set the variable. -// - Windows targets only: embeds assets/app-icon/texturecraft.ico and VERSIONINFO into the exe. +// - Windows targets only: embeds the flavor's `assets/app-icon/*.ico` and VERSIONINFO into the exe. // A missing resource compiler is a warning, so a cross-compile still links, unless // `TEXTURECRAFT_REQUIRE_WINRES=1` (set by packaging/windows/package.ps1) makes it an error. -use std::process::Command; +#[path = "src/build_channel.rs"] +mod build_channel; -const ICON: &str = "../../assets/app-icon/texturecraft.ico"; +use std::process::Command; fn main() { println!("cargo:rerun-if-changed=build.rs"); - println!("cargo:rerun-if-changed={ICON}"); - for var in ["TEXTURECRAFT_BUILD_SHA", "TEXTURECRAFT_BUILD_DATE", "TEXTURECRAFT_REQUIRE_WINRES", "SOURCE_DATE_EPOCH"] { + println!("cargo:rerun-if-changed=src/build_channel.rs"); + for icon in [build_channel::windows_icon_path(false), build_channel::windows_icon_path(true)] { + println!("cargo:rerun-if-changed={icon}"); + } + for var in [ + "TEXTURECRAFT_BUILD_SHA", + "TEXTURECRAFT_BUILD_DATE", + "TEXTURECRAFT_BUILD_CHANNEL", + "TEXTURECRAFT_VERSION", + "TEXTURECRAFT_OVERRIDE_VERSION", + "TEXTURECRAFT_REQUIRE_WINRES", + "SOURCE_DATE_EPOCH", + ] { println!("cargo:rerun-if-env-changed={var}"); } + println!("cargo:rustc-check-cfg=cfg(texturecraft_nightly_v1)"); + let nightly = match std::env::var("TEXTURECRAFT_BUILD_CHANNEL").as_deref() { + Ok("nightly-v1") => { + println!("cargo:rustc-cfg=texturecraft_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 TEXTURECRAFT_BUILD_CHANNEL (expected stable or nightly-v1)"); + std::process::exit(1); + } + }; + // `TEXTURECRAFT_VERSION` is the feed identity the workflow exports; the packaging scripts + // (packaging/env.sh, nightly-common.sh, linux/package.sh) spell the same value + // `TEXTURECRAFT_OVERRIDE_VERSION`, so both name the version the binary reports. + let requested = ["TEXTURECRAFT_VERSION", "TEXTURECRAFT_OVERRIDE_VERSION"] + .into_iter() + .find_map(|name| std::env::var(name).ok().map(|value| value.trim().to_owned()).filter(|value| !value.is_empty())); + let built_version = if nightly { + match requested { + Some(version) if build_channel::is_nightly_version(&version) => version, + _ => { + eprintln!("nightly-v1 requires an explicit prepared feed identity in TEXTURECRAFT_VERSION"); + std::process::exit(1); + } + } + } else { + std::env::var("CARGO_PKG_VERSION").unwrap_or_default() + }; + println!("cargo:rustc-env=TEXTURECRAFT_VERSION={built_version}"); println!("cargo:rustc-env=TEXTURECRAFT_BUILD_SHA={}", env_or("TEXTURECRAFT_BUILD_SHA", git_sha)); println!("cargo:rustc-env=TEXTURECRAFT_BUILD_DATE={}", env_or("TEXTURECRAFT_BUILD_DATE", today)); if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { - windows_resources(); + windows_resources(nightly, &built_version); } } @@ -59,17 +106,27 @@ fn today() -> Option { Some(format!("{year:04}-{month:02}-{day:02}")) } -fn windows_resources() { +fn windows_resources(nightly: bool, built_version: &str) { let name = std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "texturecraft".into()); - let description = if name.ends_with("-cli") { "TextureCraft command-line tool" } else { "TextureCraft 3D texture painter" }; + let description = if name.ends_with("-cli") { + if nightly { "TextureCraft Nightly command-line tool" } else { "TextureCraft command-line tool" } + } else if nightly { + "TextureCraft Nightly 3D texture painter" + } else { + "TextureCraft 3D texture painter" + }; let mut res = winresource::WindowsResource::new(); - res.set_icon(ICON) - .set("ProductName", "TextureCraft") + res.set_icon(build_channel::windows_icon_path(nightly)) + .set("ProductName", if nightly { "TextureCraft Nightly" } else { "TextureCraft" }) .set("FileDescription", description) .set("CompanyName", "Learning Machines LLC") .set("LegalCopyright", "Copyright (c) the TextureCraft contributors. MIT OR Apache-2.0.") .set("OriginalFilename", &format!("{name}.exe")) .set("InternalName", &name); + if nightly { + // The Launcher checks 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("TEXTURECRAFT_REQUIRE_WINRES").is_some() { println!("cargo::error=embedding Windows resources into {name}.exe failed: {e}"); diff --git a/apps/texturecraft/src/build_channel.rs b/apps/texturecraft/src/build_channel.rs new file mode 100644 index 00000000..ebfc4a2a --- /dev/null +++ b/apps/texturecraft/src/build_channel.rs @@ -0,0 +1,62 @@ +//! The build-time nightly identity shared by the build script and its pure regression tests. +//! +//! `build.rs` includes this file (`#[path = "src/build_channel.rs"]`) and the app compiles it for +//! the same checks, so the icon and the version shape cannot drift apart between them. + +/// `X.Y.Z-nightly.YYYYMMDD...g`, the Launcher's immutable feed identity. +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))) +} + +/// The Windows icon embedded in the executable: the nightly art only in a nightly build. +pub fn windows_icon_path(nightly: bool) -> &'static str { + if nightly { "../../assets/app-icon/texturecraft-nightly.ico" } else { "../../assets/app-icon/texturecraft.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/texturecraft.ico"); + assert_eq!(windows_icon_path(true), "../../assets/app-icon/texturecraft-nightly.ico"); + } + + #[test] + fn explicit_feed_identity_is_required_for_a_nightly_build() { + assert!(is_nightly_version("0.23.1-nightly.20261120.17.1.gabcdef012345")); + for invalid in [ + "", + "0.23.1", + "0.23.1-nightly", + "0.23.1-nightly.20261120", + "0.23.1-nightly.20261120.17.1.gABCDEF012345", + "0.23.1-nightly.20261120.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.23.1-nightly.20261120.1.1.gabcdef012345", + "0.23.1-nightly.20261120.1.1.gabcdef012345/other", + "0.23.1-nightly.20261120.1.1.gabcdef012345\ncargo:rustc-cfg=other", + ] { + assert!(!is_nightly_version(invalid)); + } + } +} diff --git a/apps/texturecraft/src/build_flavor.rs b/apps/texturecraft/src/build_flavor.rs new file mode 100644 index 00000000..294f1e19 --- /dev/null +++ b/apps/texturecraft/src/build_flavor.rs @@ -0,0 +1,94 @@ +//! The build-time channel, which is distinct from a launch selector: no runtime environment can +//! promote a stable build into the Nightly one. + +use crate::launch_profile::Profile; +use std::ffi::OsString; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BuildFlavor { + Stable, + NightlyV1, +} + +/// `TEXTURECRAFT_BUILD_CHANNEL=nightly-v1` at compile time (`build.rs`). +pub const COMPILED: BuildFlavor = if cfg!(texturecraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable }; + +/// The version this binary was built as: the prepared feed identity in a nightly build, else the +/// workspace version (`build.rs` bakes it so both flavors read it the same way). +pub const BUILT_VERSION: &str = env!("TEXTURECRAFT_VERSION"); + +/// A nightly build starts only with its profile, and a stable build only without one. +pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> { + match (flavor, profile.is_nightly()) { + (BuildFlavor::NightlyV1, false) => Err("Open TextureCraft Nightly from ArtCraft Launcher".into()), + (BuildFlavor::Stable, true) => Err("This is a stable TextureCraft build; nightly-v1 requires the nightly build".into()), + _ => Ok(()), + } +} + +/// A refused nightly start explains itself in a native dialog: a release Windows build has no +/// console, and a Dock launch on macOS has none either. +pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool { + desktop_session && flavor == BuildFlavor::NightlyV1 +} + +/// `--version` or `-V` alone; a file called `--version` after `--` is never a query. +pub fn version_query(args: &[OsString]) -> bool { + matches!(args, [arg] if arg == "--version" || arg == "-V") +} + +/// The line `--version` prints: ` (nightly-v1)` in a nightly build, exactly as the +/// Launcher and the release smoke test read it. +pub fn version(flavor: BuildFlavor) -> String { + match flavor { + BuildFlavor::Stable => format!("TextureCraft {BUILT_VERSION}"), + BuildFlavor::NightlyV1 => format!("TextureCraft {BUILT_VERSION} (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_nightly_version_line_is_exact_and_says_its_channel() { + let nightly = version(BuildFlavor::NightlyV1); + assert!(nightly.starts_with("TextureCraft "), "{nightly}"); + assert!(nightly.ends_with(" (nightly-v1)"), "{nightly}"); + assert_eq!(nightly, format!("TextureCraft {} (nightly-v1)", BUILT_VERSION)); + assert_eq!(version(BuildFlavor::Stable), format!("TextureCraft {BUILT_VERSION}")); + } + + #[test] + fn only_a_bare_version_flag_is_a_query() { + assert!(version_query(&["--version".into()])); + assert!(version_query(&["-V".into()])); + assert!(!version_query(&["--".into(), "--version".into()])); + assert!(!version_query(&["--version".into(), "--version".into()])); + assert!(!version_query(&[])); + } +} diff --git a/apps/texturecraft/src/launch_profile.rs b/apps/texturecraft/src/launch_profile.rs new file mode 100644 index 00000000..84f5061f --- /dev/null +++ b/apps/texturecraft/src/launch_profile.rs @@ -0,0 +1,217 @@ +//! The Launcher's nightly-v1 bootstrap, selected before logging, updates, fonts or saved state. +//! Stable launches keep their arguments and directory policy unchanged, and no environment is +//! mutated: the profile is a value this process reads, not a variable it exports. + +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 directory resolution stays unchanged. +pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result) -> Result { + if let Profile::NightlyV1(root) = &launch.profile { + launch.profile = Profile::NightlyV1(validate(root)?); + } + Ok(launch) +} + +/// Resolve the selected private root before the caller's first startup effect. +pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option, exe: Option<&Path>) -> Result { + crate::profile_root::validate(root, env, exe, crate::profile_root::ensure_writable) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + + fn args(values: &[&str]) -> Vec { + values.iter().map(OsString::from).collect() + } + + fn absolute() -> &'static str { + if cfg!(windows) { r"C:\NightlyData\profiles\texturecraft" } else { "/nightly-data/profiles/texturecraft" } + } + + fn nightly() -> Vec { + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) + } + + #[test] + fn stable_arguments_and_directory_policy_are_unchanged() { + for argv in [args(&[]), args(&["model.glb"]), args(&["--gpu", "nvidia"]), args(&["--", "--launch-profile", "model.glb"])] { + 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", "model with spaces.glb"])); + let launch = parse(argv).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); + assert_eq!(launch.args, args(&["--", "--profile-root", "model with spaces.glb"])); + } + + #[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(), "--gpu", "nvidia", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute()]), + args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--profile-root=/nightly-data/profiles/texturecraft", "--"]), + ] { + assert!(parse(argv.clone()).is_err(), "{argv:?}"); + } + } + + #[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(), "--gpu", "nvidia", "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]), + args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]), + args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]), + args(&["--launch-profile", VERSION, "--version"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]), + ] { + assert!(!version_query(&argv), "{argv:?}"); + } + // Outside the query the strict protocol still refuses the version flag. + assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err()); + } + + #[test] + fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() { + let reached = Cell::new(false); + let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true)); + assert!(result.is_err()); + assert!(!reached.get()); + } + + #[test] + fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() { + let checked = PathBuf::from(absolute()).join("checked"); + let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap(); + assert_eq!(launch.profile.root(), Some(checked.as_path())); + assert!(launch.profile.is_nightly()); + } +} diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 7787e1cf..349b9275 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -5,11 +5,22 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#[cfg(test)] +mod build_channel; +mod build_flavor; mod control_server; mod gpu; +mod launch_profile; +mod nightly_session; +mod process_identity; +mod profile_root; mod window_frame; +use std::ffi::OsString; + +use launch_profile::Profile; use texturecraft_engine::Session; +use texturecraft_ui_egui::os_window::{self, LaunchIdentity}; use texturecraft_ui_egui::titlebar::TitleBar; use texturecraft_ui_egui::ui_state_store; use texturecraft_ui_egui::{TextureCraftApp, UiState}; @@ -17,14 +28,25 @@ use texturecraft_ui_egui::{TextureCraftApp, UiState}; /// The app name eframe keeps the settings under (`eframe::storage_dir`). const APP_NAME: &str = "TextureCraft"; +/// The data folder Dylan's #801 packaging lets a Stable wrapper set. A Nightly launch never reads +/// it: its profile arrives as the Launcher's literal selector/root pair, and nothing else. +const DATA_DIR_ENV: &str = "TEXTURECRAFT_DATA_DIR"; + /// The window's size when it opens, in points. const DEFAULT_SIZE: [f32; 2] = [1600.0, 960.0]; /// The smallest size the window can be resized to, in points. const MIN_SIZE: [f32; 2] = [960.0, 600.0]; const ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.texturecraft.png"); +/// The Nightly window icon: the same artwork on the deeper background the package icon uses. +const NIGHTLY_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/texturecraft-nightly.png"); +/// The version line: a Nightly build names its exact feed identity and channel, and every other +/// build keeps the workspace version with the commit and date it was built from. fn version() -> String { + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 { + return build_flavor::version(build_flavor::COMPILED); + } let sha = env!("TEXTURECRAFT_BUILD_SHA"); let short = sha.get(..7).unwrap_or(sha); let date = env!("TEXTURECRAFT_BUILD_DATE"); @@ -44,15 +66,23 @@ struct Args { power_pref: Option, } -fn parse_args() -> Result, String> { - parse_args_from(std::env::args().skip(1)) -} - fn parse_args_from>(it: I) -> Result, String> { let mut args = Args { file: None, control: None, empty: false, gpu: None, power_pref: None }; let mut it = it.into_iter(); + // Everything after `--` is a file, even when it looks like an option: the Launcher's nightly + // protocol passes the selected file that way (and a file may be called `--version`). + let mut after_delimiter = false; while let Some(a) = it.next() { + if after_delimiter { + // A Launcher hand-off may carry more than one file. Opening the first one beats a + // silent exit on a Windows build, which has no console to show the refusal on. + if args.file.is_none() { + args.file = Some(a); + } + continue; + } match a.as_str() { + "--" => after_delimiter = true, "--version" | "-V" => { println!("{}", version()); return Ok(None); @@ -119,7 +149,8 @@ fn initial_session(args: &Args) -> Session { } fn icon() -> Option { - let img = craft_image_codecs::decode(ICON_PNG).ok()?; + let png = if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 { NIGHTLY_ICON_PNG } else { ICON_PNG }; + let img = craft_image_codecs::decode(png).ok()?; Some(egui::IconData { rgba: img.to_rgba8(), width: img.width(), height: img.height() }) } @@ -134,13 +165,39 @@ fn set_taskbar_icon(w: &winit::window::Window) { } } +/// Directory for saved settings, UI state, and error logs: a Nightly launch's validated profile, +/// else `TEXTURECRAFT_DATA_DIR` (when non-empty, as a Stable package wrapper sets it), else +/// eframe's own folder for this app. +fn storage_dir() -> Option { + settings_folder( + launch_profile::current().root(), + std::env::var_os(DATA_DIR_ENV).filter(|v| !v.is_empty()).map(std::path::PathBuf::from), + eframe::storage_dir(APP_NAME), + ) +} + +/// The settings folder, in the order a launch decides it: a Nightly profile, a Stable wrapper's +/// `TEXTURECRAFT_DATA_DIR`, else eframe's own folder for this app. +/// +/// The last one is passed in rather than left to eframe. With `with_app_id` set (the Linux window +/// class the Stable entry needs), eframe derives its folder from the app id, so Stable's `app.ron` +/// — window state and the user's export presets — would move to `ai.storyteller.texturecraft` while +/// `ui.json` and `errors.log` stayed behind. `persistence_path` therefore names the file explicitly. +fn settings_folder( + profile: Option<&std::path::Path>, + wrapper_dir: Option, + legacy: Option, +) -> Option { + profile.map(std::path::Path::to_path_buf).or(wrapper_dir).or(legacy) +} + /// Preferences needed before opening the initial project or window, with legacy storage fallback. fn saved_prefs(ui_file: Option<&std::path::Path>, persistence_path: Option<&std::path::Path>) -> texturecraft_ui_egui::state::Prefs { if let Some(ui) = ui_file.and_then(ui_state_store::read) { return ui.prefs; } - let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("app.ron"))); + let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| storage_dir().map(|folder| folder.join("app.ron"))); let saved = file.and_then(|file| std::fs::read_to_string(file).ok()); let entries = saved.and_then(|text| ron::from_str::>(&text).ok()); entries.and_then(|entries| ron::from_str::(entries.get("ui")?).ok()).map(|ui| ui.prefs).unwrap_or_default() @@ -151,6 +208,10 @@ fn saved_prefs(ui_file: Option<&std::path::Path>, persistence_path: Option<&std: struct Shell { app: TextureCraftApp, window_frame: Option, + /// Runs once when the window closes. On macOS that is the only place a clean quit is handled: + /// Cmd+Q ends the process inside AppKit's terminate, after eframe's `on_exit` and before + /// `eframe::run_native` returns, so the Nightly session record is finished here, not there. + exit_hook: Option>, #[cfg(target_os = "macos")] movable: Option, } @@ -183,6 +244,12 @@ impl eframe::App for Shell { #[cfg(target_os = "macos")] texturecraft_ui_egui::titlebar::sync_native(&self.app.title_bar, ui, frame, &mut self.movable); } + + fn on_exit(&mut self) { + if let Some(hook) = self.exit_hook.take() { + hook(); + } + } } /// A script driving the app gets no network check and no update prompt over its window. @@ -190,20 +257,97 @@ fn checks_for_updates_at_start(control: Option) -> bool { control.is_none() } +/// The AppUserModelID a Nightly window is grouped under, set before any native window exists. +fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> { + process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, os_window::id_for(LaunchIdentity::NightlyV1)) +} + +/// A refused Nightly start explains itself in a dialog where there is a desktop to show one. +fn report_launch_profile_error(error: &str) { + eprintln!("texturecraft: {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!("texturecraft: {error}"); + return; + } + #[cfg(any(windows, target_os = "linux", target_os = "macos"))] + let _ = rfd::MessageDialog::new() + .set_title(os_window::name_for(LaunchIdentity::NightlyV1)) + .set_description(error) + .set_level(rfd::MessageLevel::Error) + .set_buttons(rfd::MessageButtons::Ok) + .show(); + } +} + +/// Select the immutable launch profile before any startup service or side effect, and answer the +/// Launcher's version queries before root validation, logging, IPC or a window. `None` means the +/// launch is already answered and the process returns. +fn prepare_launch() -> Option> { + let argv: Vec = std::env::args_os().skip(1).collect(); + // Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root + // --version`: both are answered here, with nothing but standard output written. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) { + use std::io::Write as _; + let _ = writeln!(std::io::stdout(), "{}", build_flavor::version(build_flavor::COMPILED)); + return None; + } + let early = launch_profile::parse(argv) + .and_then(|launch| { + build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; + initialize_nightly_process_identity().map_err(|error| error.to_string())?; + Ok(launch) + }) + .and_then(|launch| { + launch_profile::prepare(launch, |root| launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())) + }) + .unwrap_or_else(|error| { + report_launch_profile_error(&error); + std::process::exit(2) + }); + let identity = if early.profile.is_nightly() { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable }; + if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) { + report_launch_profile_error(&error); + std::process::exit(2); + } + if let Profile::NightlyV1(root) = launch_profile::current() { + // Every data folder follows the profile before the first one is used. + texturecraft_ui_egui::set_data_root(root.clone()); + texturecraft_ui_egui::os_window::set_display_version(build_flavor::BUILT_VERSION.to_owned()); + } + Some(early.args) +} + +/// The launch arguments as text. A Nightly protocol argument is a path the app opens, so a value +/// that is not valid Unicode is refused rather than silently replaced. +fn launch_arguments(arguments: Vec) -> Result, String> { + arguments.into_iter().map(|value| value.into_string().map_err(|_| "an argument is not valid Unicode".to_string())).collect() +} + fn main() { - // Windows: the update helper is a copy of this program started with `--finish-update` + // Windows: the update helper is a copy of this program started with `--finish-update`. A + // Nightly install is updated by ArtCraft Launcher, so it never installs an update itself. #[cfg(windows)] - if let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { + if build_flavor::COMPILED == build_flavor::BuildFlavor::Stable + && let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) + { std::process::exit(i32::from(result.is_err())); } - // Windows: the eyedropper's pointer keeper (screen_pick) is a copy of this program started with its own argument + // Windows: the eyedropper's pointer keeper (screen_pick) is a copy of this program started with + // its own argument. It reads no user state and is started without the profile tokens, so it + // runs before the launch protocol would refuse it. #[cfg(windows)] if std::env::args_os().nth(1).is_some_and(|arg| arg == texturecraft_ui_egui::screen_pick::KEEPER_ARG) { std::process::exit(texturecraft_ui_egui::screen_pick::keep_pointer()); } - let args = match parse_args() { + let Some(arguments) = prepare_launch() else { return }; + let nightly = launch_profile::current().is_nightly(); + let args = match launch_arguments(arguments).and_then(parse_args_from) { Ok(Some(a)) => a, Ok(None) => return, Err(e) => { @@ -211,6 +355,12 @@ fn main() { std::process::exit(2); } }; + // The control server is a stable-install service: a Nightly window is driven by the Launcher, + // and its token file would sit in the shared temp folder rather than its private profile. + if nightly && args.control.is_some() { + eprintln!("texturecraft: TextureCraft Nightly cannot start a control server (--control); use the stable app or texturecraft-cli"); + std::process::exit(2); + } // Errors before the window opens speak the system's language; the app then applies the saved one texturecraft_ui_egui::i18n::set_language(texturecraft_ui_egui::i18n::os_language()); @@ -221,11 +371,13 @@ fn main() { previous_hook(info); })); - // Scripted runs use temporary files so they cannot overwrite saved settings - let persistence_path = + // Scripted runs use temporary files so they cannot overwrite saved settings. Otherwise eframe + // is told the file explicitly, so `with_app_id` cannot move Stable's `app.ron` out of the + // folder `storage_dir` keeps `ui.json` and `errors.log` in (see `settings_folder`). + let no_prefs_path = std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id()))); - let ui_file = - persistence_path.as_ref().map(|path| path.with_extension("json")).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("ui.json"))); + let persistence_path = no_prefs_path.clone().or_else(|| storage_dir().map(|dir| dir.join("app.ron"))); + let ui_file = no_prefs_path.as_ref().map(|path| path.with_extension("json")).or_else(|| storage_dir().map(|folder| folder.join("ui.json"))); if let Some(file) = &ui_file { let _ = ui_state_store::FILE.set(file.clone()); } @@ -236,7 +388,11 @@ fn main() { prefs.apply_resource_limits(); let session = initial_session(&args); let title_bar = TitleBar::decide(prefs.system_title_bar); - let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size(DEFAULT_SIZE).with_min_inner_size(MIN_SIZE); + let mut viewport = egui::ViewportBuilder::default() + .with_app_id(os_window::app_id()) + .with_title(os_window::name()) + .with_inner_size(DEFAULT_SIZE) + .with_min_inner_size(MIN_SIZE); if let Some(i) = icon() { viewport = viewport.with_icon(i); } @@ -247,8 +403,34 @@ fn main() { std::process::exit(2); } let control = args.control; + // The Nightly session record: one owner per profile, an unclean exit reported by the next + // start, and no document name, path or diagnostic payload collected. + let (nightly_session, session_health_warning) = match nightly_session::Session::begin_with_health( + launch_profile::current().root(), + build_flavor::BUILT_VERSION, + Some(env!("TEXTURECRAFT_BUILD_SHA")), + ) { + 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); + // Set once a window has posted the interruption notice; until then the record must survive. + let unclean_notice_shown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let notice_shown_in_window = unclean_notice_shown.clone(); + let nightly_session: nightly_session::Shared = std::sync::Arc::new(std::sync::Mutex::new(nightly_session)); + // The exit hook is the controlled return on macOS, where every quit ends the process inside + // AppKit's terminate and `run_native` never returns. Elsewhere the return path below finishes. + let finish_at_exit = { + let shared = nightly_session.clone(); + let shown = unclean_notice_shown.clone(); + move || nightly_session::finish_once(&shared, shown.load(std::sync::atomic::Ordering::Relaxed)) + }; + let window_name = os_window::name(); let result = eframe::run_native( - APP_NAME, + window_name, options, Box::new(move |cc| { #[cfg(windows)] @@ -258,7 +440,7 @@ fn main() { // winit's Quit ends the process without asking; this menu's asks like the close button #[cfg(target_os = "macos")] - if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, APP_NAME) { + if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, window_name) { log::warn!("the app menu could not be installed: {e}"); } let window_frame = window_frame::service(cc, matches!(title_bar, TitleBar::App(_))); @@ -268,14 +450,27 @@ fn main() { if let Some(port) = control { app.control = Some(control_server::start(port, cc.egui_ctx.clone())); } + if previous_nightly_unclean || session_health_warning { + use texturecraft_ui_egui::i18n::tr; + app.banner = Some(if previous_nightly_unclean { + tr("The previous TextureCraft Nightly session did not finish normally. No diagnostics have been sent.") + } else { + tr("TextureCraft Nightly could not record session health in its profile; abnormal-exit detection is unavailable.") + }); + notice_shown_in_window.store(previous_nightly_unclean, std::sync::atomic::Ordering::Relaxed); + } Ok(Box::new(Shell { app, window_frame, + exit_hook: Some(Box::new(finish_at_exit)), #[cfg(target_os = "macos")] movable: None, })) }), ); + // A controlled return, including a handled startup error. On macOS a window already finished in + // its exit hook, so this is then a no-op. + nightly_session::finish_once(&nightly_session, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed)); if let Err(e) = result { fatal(&e.to_string(), true); std::process::exit(1); @@ -284,7 +479,7 @@ fn main() { /// The file startup errors and crashes are appended to, beside the saved settings. fn error_log() -> Option { - eframe::storage_dir(APP_NAME).map(|d| d.join("errors.log")) + storage_dir().map(|d| d.join("errors.log")) } /// Append a line with the time (Unix seconds) and the app version; true when it was written. @@ -305,7 +500,7 @@ fn fatal(msg: &str, dialog: bool) { let saved = log.map(|f| format!("\n\n{}", trf("Details saved to {file}", &[("file", &f.display())]))).unwrap_or_default(); rfd::MessageDialog::new() .set_level(rfd::MessageLevel::Error) - .set_title(APP_NAME) + .set_title(os_window::name()) .set_description(format!("{}\n\n{msg}{saved}", tr("TextureCraft had to close:"))) .set_buttons(rfd::MessageButtons::Ok) .show(); @@ -330,6 +525,55 @@ mod tests { assert_eq!(args.gpu.as_deref(), Some("3080")); } + #[test] + fn stable_settings_stay_in_the_folder_eframe_used_before_the_app_id() { + let legacy = std::path::PathBuf::from("/legacy/TextureCraft"); + // Stable, no wrapper folder: the folder eframe picked for `APP_NAME` before `with_app_id` + // existed, so `app.ron` (window state and the export presets stored in it) does not move. + let folder = settings_folder(None, None, Some(legacy.clone())).expect("a legacy folder"); + assert_eq!(folder.join("app.ron"), legacy.join("app.ron")); + // A Stable wrapper's data folder still wins, which is what #801's packaging expects. + let wrapper = std::path::PathBuf::from("/wrapper/data"); + assert_eq!(settings_folder(None, Some(wrapper.clone()), Some(legacy.clone())), Some(wrapper.clone())); + // A Nightly profile wins over both, so no Stable folder is ever read. + assert_eq!(settings_folder(Some(std::path::Path::new("/profile")), Some(wrapper), Some(legacy)), Some(std::path::PathBuf::from("/profile"))); + // Nothing resolvable: there is no folder to fall back to and eframe keeps its own default. + assert_eq!(settings_folder(None, None, None), None); + // The app's wiring: with no profile and no wrapper folder, `app.ron` sits beside `ui.json` + // in eframe's folder for `APP_NAME`, not in the folder of the app id `with_app_id` sets. + if std::env::var_os(DATA_DIR_ENV).is_none() + && !launch_profile::current().is_nightly() + && let Some(stable) = eframe::storage_dir(APP_NAME) + { + assert_eq!(storage_dir(), Some(stable.clone())); + assert_eq!(storage_dir().map(|dir| dir.join("app.ron")), Some(stable.join("app.ron"))); + } + } + + #[test] + fn a_file_after_the_delimiter_is_a_file_even_when_it_looks_like_an_option() { + let args = parse_args_from(["--".to_string(), "--version".to_string()]).unwrap().unwrap(); + assert_eq!(args.file.as_deref(), Some("--version")); + let args = parse_args_from(["--".to_string(), "--launch-profile".to_string()]).unwrap().unwrap(); + assert_eq!(args.file.as_deref(), Some("--launch-profile")); + // Options before the delimiter still parse as options. + let args = parse_args_from(["--gpu".to_string(), "nvidia".to_string(), "--".to_string(), "a.glb".to_string()]).unwrap().unwrap(); + assert_eq!((args.gpu.as_deref(), args.file.as_deref()), (Some("nvidia"), Some("a.glb"))); + // One window opens one project: extra files after the delimiter are ignored, in that order. + let args = parse_args_from(["--".to_string(), "a.glb".to_string(), "b.glb".to_string()]).unwrap().unwrap(); + assert_eq!(args.file.as_deref(), Some("a.glb")); + } + + #[test] + fn launch_arguments_refuse_a_name_that_is_not_unicode() { + assert_eq!(launch_arguments(vec![OsString::from("--version")]).unwrap(), vec!["--version".to_string()]); + #[cfg(unix)] + { + use std::os::unix::ffi::OsStringExt as _; + assert!(launch_arguments(vec![OsString::from_vec(vec![b'a', 0xff, b'b'])]).is_err()); + } + } + #[test] fn rejects_missing_or_invalid_gpu_args() { assert!(parse_args_from(["--gpu".to_string()]).is_err()); @@ -410,6 +654,7 @@ mod tests { let mut harness = builder.build_eframe(|cc| Shell { app: TextureCraftApp::new(cc, session), window_frame: None, + exit_hook: None, #[cfg(target_os = "macos")] movable: None, }); diff --git a/apps/texturecraft/src/nightly_session.rs b/apps/texturecraft/src/nightly_session.rs new file mode 100644 index 00000000..a1f2dee5 --- /dev/null +++ b/apps/texturecraft/src/nightly_session.rs @@ -0,0 +1,277 @@ +//! App-private Nightly session health, not telemetry and not a Launcher protocol. +//! +//! A live owner holds a separate persistent lease; a secondary launch never rewrites its record. +//! Dropping the guard does not clear the marker; only the app's controlled return path does. + +use std::fs::File; +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, PoisonError}; + +const RECORD: &str = "nightly-session.json"; +const LEASE: &str = "nightly-session.lock"; +const MAX_METADATA_BYTES: usize = 256; + +pub struct Session { + _lease: File, + path: PathBuf, + own_record: Vec, + previous_unclean: bool, +} + +fn regular_or_missing(path: &Path) -> io::Result { + match std::fs::symlink_metadata(path) { + Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true), + Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error), + } +} + +/// Write `bytes` to `path` without ever following a link at the destination: the temporary file is +/// created exclusively beside it and renamed over the name, which replaces a link rather than +/// writing through it (the engine's `write_atomic` deliberately resolves the target instead). +fn write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> { + let parent = path.parent().ok_or_else(|| io::Error::other("the Nightly record has no folder"))?; + let name = path.file_name().and_then(|name| name.to_str()).ok_or_else(|| io::Error::other("the Nightly record name is not Unicode"))?; + let temporary = parent.join(format!(".{name}.{}.tmp", std::process::id())); + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt as _; + options.mode(0o600); + } + let staged = write_staged(&mut options, &temporary, bytes).and_then(|()| std::fs::rename(&temporary, path)); + if let Err(error) = staged { + let _ = std::fs::remove_file(&temporary); + return Err(error); + } + // The rename is durable only once its folder is synced (no-op where the platform has no handle). + #[cfg(unix)] + if let Ok(folder) = File::open(parent) { + let _ = folder.sync_all(); + } + Ok(()) +} + +/// Write the whole file and flush it to the device before it may replace the destination. +fn write_staged(options: &mut std::fs::OpenOptions, temporary: &Path, bytes: &[u8]) -> io::Result<()> { + use std::io::Write as _; + let mut file = options.open(temporary)?; + file.write_all(bytes)?; + file.sync_all() +} + +/// The owner's session, shared by the app's exit hook (macOS) and the code after the event loop. +/// On macOS every quit ends the process inside AppKit's terminate, after eframe's `on_exit` and +/// before `eframe::run_native` could return, so the exit hook finishes it there; the return path +/// still runs for a start that created no window. +pub type Shared = Arc>>; + +/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing. +pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) { + let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take(); + if let Some(watch) = watch + && let Err(error) = watch.finish(unclean_notice_shown) + { + log::warn!("Nightly session state was left intact: {error}"); + } +} + +impl Session { + /// The warning belongs to this window: a busy secondary has no health-record coverage, while + /// Stable and a lease-owning Nightly window preserve their existing result. + pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option, bool)> { + let watch = Self::begin(root, version, commit)?; + let unavailable = root.is_some() && watch.is_none(); + Ok((watch, unavailable)) + } + + /// `None` is Stable or another owner of this profile. Neither case touches the record. + /// The supplied root must already be the validated private Nightly profile. + pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result> { + let Some(root) = root else { return Ok(None) }; + if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large")); + } + let lease_path = root.join(LEASE); + regular_or_missing(&lease_path)?; + let lease = std::fs::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, 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() + } + + /// A handled startup error is a controlled return too. 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!("texturecraft-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() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("cannot create owned fixture: {error}"), + } + } + } + } + impl Drop for Fixture { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).unwrap(); + } + } + + #[test] + fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() { + let fixture = Fixture::new(); + let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap(); + assert!(stable.is_none() && !warning); + let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap(); + assert!(!warning); + let first = first.unwrap(); + let record = std::fs::read(fixture.0.join(RECORD)).unwrap(); + let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap(); + assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage"); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record); + first.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() { + let fixture = Fixture::new(); + let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap(); + assert!(!first.previous_unclean()); + let own = std::fs::read(fixture.0.join(RECORD)).unwrap(); + assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none()); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record"); + first.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + let unfinished = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap(); + assert!(!unfinished.previous_unclean()); + drop(unfinished); // Unwind/abnormal-path ownership release, not a controlled completion. + let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap(); + assert!(next.previous_unclean()); + next.complete().unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn an_interruption_no_window_showed_survives_a_handled_startup_failure() { + let fixture = Fixture::new(); + drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap()); + let failed = Session::begin(Some(&fixture.0), "gpu-failed", None).unwrap().unwrap(); + assert!(failed.previous_unclean()); + failed.finish(false).unwrap(); + // The next start still sees the interruption and shows it. + let retry = Session::begin(Some(&fixture.0), "next", None).unwrap().unwrap(); + assert!(retry.previous_unclean()); + retry.finish(true).unwrap(); + assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record"); + let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap(); + assert!(!clean.previous_unclean()); + clean.finish(false).unwrap(); + assert!(!fixture.0.join(RECORD).exists()); + } + + #[test] + fn the_exit_hook_and_the_return_path_finish_the_session_once() { + let fixture = Fixture::new(); + let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap())); + // The exit hook (macOS quit: the only path that runs there). + finish_once(&shared, false); + assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit"); + // Elsewhere the return path runs too, by then possibly after a successor took the profile. + let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap(); + assert!(!successor.previous_unclean()); + let record = std::fs::read(fixture.0.join(RECORD)).unwrap(); + finish_once(&shared, false); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record"); + successor.complete().unwrap(); + } + + #[test] + fn cleanup_never_removes_an_unknown_changed_record() { + let fixture = Fixture::new(); + let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap(); + std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap(); + assert!(watch.complete().is_err()); + assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else"); + } + + #[test] + fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() { + let fixture = Fixture::new(); + assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err()); + assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0); + assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects"); + let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap(); + let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap(); + let fields = data.as_object().unwrap().keys().map(String::as_str).collect::>(); + assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect()); + assert!(data["commit"].is_null(), "missing provenance must not be invented"); + watch.complete().unwrap(); + } + + #[test] + #[cfg(unix)] + fn reserved_state_aliases_do_not_modify_external_files() { + let fixture = Fixture::new(); + let external = fixture.0.join("stable-document"); + std::fs::write(&external, b"stable bytes").unwrap(); + for name in [LEASE, RECORD] { + let alias = fixture.0.join(name); + std::os::unix::fs::symlink(&external, &alias).unwrap(); + assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err()); + assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes"); + std::fs::remove_file(alias).unwrap(); + } + } +} diff --git a/apps/texturecraft/src/process_identity.rs b/apps/texturecraft/src/process_identity.rs new file mode 100644 index 00000000..f9ef611e --- /dev/null +++ b/apps/texturecraft/src/process_identity.rs @@ -0,0 +1,78 @@ +//! Set the immutable Nightly Windows identity before any native window or COM service. +//! Stable deliberately leaves its implicit shortcut/path identity unchanged, so MSI shortcut +//! matching keeps working. + +use std::fmt; +use std::sync::OnceLock; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IdentityError(pub String); + +impl fmt::Display for IdentityError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for IdentityError {} + +/// The AppUserModelID the taskbar groups the Nightly window under, distinct from Stable's. +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) +} + +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/texturecraft/src/profile_root.rs b/apps/texturecraft/src/profile_root.rs new file mode 100644 index 00000000..71265909 --- /dev/null +++ b/apps/texturecraft/src/profile_root.rs @@ -0,0 +1,489 @@ +//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. +//! +//! A Nightly profile has to hold *all* of its user state: eframe's `app.ron`/`ui.json`, the error +//! log, session logs, autosave copies, smart materials, layouts, templates, brush and export +//! presets. Anything that resolves to a stable folder would read and prune Stable's files, so the +//! root is refused when it overlaps one of them, when an entry inside it is an alias that leaves it, +//! or when it is not writable. + +use std::ffi::OsString; +use std::path::{Component, Path, PathBuf}; + +/// The folder names the launch checks use for this app in each platform's location. +const BRAND: &str = "TextureCraft"; +/// The bundle identifier of the stable package (macOS library folders, the Linux Flatpak). +const STABLE_ID: &str = "ai.storyteller.texturecraft"; +/// The package id of the Nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`). Inside that +/// sandbox `FLATPAK_ID` is always set, so this exact id is the one a Nightly native launch accepts. +const NIGHTLY_ID: &str = "ai.storyteller.texturecraft.nightly"; +/// eframe lowercases its folder name on Linux (`file_storage.rs`), so Stable's real settings folder +/// is `$XDG_DATA_HOME/texturecraft`, not the capitalised `TextureCraft` the app is called. +const LINUX_STORAGE_BRAND: &str = "texturecraft"; + +#[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 an 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) +} + +/// Whether one path is the other or contains it (in either direction), compared component by +/// component and folded the way the platform's filesystem folds names. `TextureCraft2` is not +/// inside `TextureCraft`. +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) +} + +/// The running install: never let the profile live inside it (it would be replaced or removed by +/// the next update). +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 bundle, 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()) +} + +/// The default data folder, `Documents/TextureCraft`, as the app's own resolver builds it +/// (`crate::data_folder("")`): `USERPROFILE` on Windows and `HOME` elsewhere, then `Documents`. +fn default_data_folder(platform: Platform, env: &impl Fn(&str) -> Option) -> Result { + let home = match platform { + Platform::Windows => required_base(env, "USERPROFILE")?, + _ => required_base(env, "HOME")?, + }; + Ok(home.join("Documents").join(BRAND)) +} + +fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, exe: &Path) -> Result, String> { + let mut roots = match platform { + Platform::Windows => { + // eframe's settings folder (`%APPDATA%\TextureCraft`), its local counterpart, and the MSI's + // per-machine and any per-user install folders. A custom install folder is covered by the + // executable's own folder below. + let mut roots = ["APPDATA", "LOCALAPPDATA"].into_iter().map(|key| required_base(env, key).map(|p| p.join(BRAND))).collect::, _>>()?; + roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join(BRAND)); + 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(BRAND)); + } + } + roots + } + Platform::Linux => { + // The four XDG roots carry eframe's settings, caches and state under the app's name. + 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(BRAND))) + .collect::, _>>()?; + // eframe's own folder for this app on Linux, which is what holds Stable's `app.ron`, + // `ui.json` and `errors.log`: it folds the name, so it is the lowercase one. + roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join(LINUX_STORAGE_BRAND)); + roots.extend(["/usr/bin/texturecraft", "/usr/local/bin/texturecraft", "/opt/texturecraft"].map(PathBuf::from)); + // The stable Flatpak keeps its own per-app data folder. + roots.push(required_base(env, "HOME")?.join(format!(".var/app/{STABLE_ID}"))); + roots + } + Platform::Mac => { + let home = required_base(env, "HOME")?; + let library = home.join("Library"); + vec![ + library.join("Application Support").join(BRAND), + library.join("Caches").join(BRAND), + library.join("Caches").join(STABLE_ID), + library.join("Preferences").join(BRAND), + library.join("Preferences").join(format!("{STABLE_ID}.plist")), + library.join("Saved Application State").join(format!("{STABLE_ID}.savedState")), + home.join("Applications").join(format!("{BRAND}.app")), + PathBuf::from("/Applications").join(format!("{BRAND}.app")), + ] + } + }; + // The user's own documents folder is Stable's default data folder on every platform; a profile + // there would share autosaves, smart materials and presets with it. + roots.push(default_data_folder(platform, env)?); + roots.push(installation_boundary(platform, exe)?); + roots.into_iter().map(|p| canonical_future(&p)).collect() +} + +/// An entry inside the profile must resolve inside it, so a link planted there cannot point +/// Nightly's writes at another app's files. +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 (autosave, logs, library and so on) must resolve +/// inside it. +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(()) +} + +/// The app's writable probe: create a file exclusively in the profile and remove it again. +pub fn ensure_writable(dir: &Path) -> std::io::Result<()> { + let probe = dir.join("exclusive-write-probe"); + let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?; + drop(file); + std::fs::remove_file(probe) +} + +/// Refuse a stable folder, the running install or an alias, create a missing root with owner-only +/// access where the platform has it, and return the resolved root to use. +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")?; + // A native package must not carry another app's Flatpak namespace, and the Nightly bundle must + // be able to start inside its own sandbox, where the runtime always sets `FLATPAK_ID`. Its + // `~/.var/app/` sandbox is separate from stable's, so only other ids are refused. + if platform != Platform::Windows + && let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty()) + && id != NIGHTLY_ID + { + return Err("nightly-v1 only runs inside its own Flatpak; launch through the native Launcher or the Nightly bundle".into()); + } + let chosen = canonical_future(root)?; + 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()); + } + // Existing aliases under the profile must not redirect any of its folders elsewhere. + 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()); + } + 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!("texturecraft-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/texturecraft"); + 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.clone()), ("USERPROFILE", 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), ensure_writable) + } + + fn home(&self) -> PathBuf { + PathBuf::from(self.get("HOME").unwrap()) + } + + fn profile(&self, name: &str) -> PathBuf { + self.root.join("profiles").join(name) + } + } + + impl Drop for Fixture { + fn drop(&mut self) { + // Only the directory this fixture created is owned for removal. + std::fs::remove_dir_all(&self.root).unwrap(); + } + } + + #[test] + fn a_fresh_private_profile_is_created_and_returned_resolved() { + let fixture = Fixture::new(); + let profile = fixture.profile("nightly"); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + assert_eq!(fixture.check(platform, &profile).unwrap(), profile); + assert!(profile.is_dir()); + std::fs::remove_dir_all(&profile).ok(); + } + } + + #[test] + fn every_stable_data_folder_of_each_platform_is_refused_before_any_probe() { + let fixture = Fixture::new(); + let home = fixture.home(); + let candidates: Vec<(Platform, PathBuf)> = vec![ + (Platform::Windows, PathBuf::from(fixture.get("APPDATA").unwrap()).join(BRAND)), + (Platform::Windows, PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join(BRAND)), + (Platform::Windows, PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft").join(BRAND)), + (Platform::Windows, home.join("Documents").join(BRAND)), + (Platform::Linux, home.join(".config").join(BRAND)), + (Platform::Linux, home.join(".local/share").join(BRAND)), + (Platform::Linux, home.join(".local/share").join(LINUX_STORAGE_BRAND)), + (Platform::Linux, home.join(".cache").join(BRAND)), + (Platform::Linux, home.join(".local/state").join(BRAND)), + (Platform::Linux, home.join("Documents").join(BRAND)), + (Platform::Linux, PathBuf::from("/usr/bin/texturecraft")), + (Platform::Linux, PathBuf::from("/opt/texturecraft")), + (Platform::Linux, home.join(format!(".var/app/{STABLE_ID}"))), + (Platform::Mac, home.join("Library/Application Support").join(BRAND)), + (Platform::Mac, home.join("Library/Caches").join(BRAND)), + (Platform::Mac, home.join("Library/Preferences").join(format!("{STABLE_ID}.plist"))), + (Platform::Mac, home.join("Library/Saved Application State").join(format!("{STABLE_ID}.savedState"))), + (Platform::Mac, home.join("Documents").join(BRAND)), + (Platform::Mac, PathBuf::from(format!("/Applications/{BRAND}.app"))), + ]; + for (platform, stable) in candidates { + for candidate in [stable.clone(), stable.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(), "{platform:?} accepted {}", candidate.display()); + assert!(!probed.get(), "a refused root must not be probed: {}", candidate.display()); + } + } + } + + #[test] + fn the_running_install_is_fenced_on_every_platform() { + let fixture = Fixture::new(); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + let inside = fixture.exe.parent().unwrap().join("profile"); + assert!(fixture.check(platform, &inside).is_err(), "{platform:?} let the profile inside the install"); + } + } + + #[test] + fn lookalike_names_are_not_overlaps_but_case_folding_is() { + let fixture = Fixture::new(); + let documents = fixture.home().join("Documents"); + assert!(fixture.check(Platform::Linux, &documents.join("TextureCraft2")).is_ok(), "a neighbor with a suffix is a different folder"); + assert!(fixture.check(Platform::Linux, &documents.join("texturecraft")).is_ok(), "Linux folds names exactly"); + for platform in [Platform::Windows, Platform::Mac] { + assert!(fixture.check(platform, &documents.join("texturecraft")).is_err(), "{platform:?} must fold case"); + } + } + + #[test] + fn relative_parent_traversal_and_empty_roots_are_refused() { + let fixture = Fixture::new(); + for root in [PathBuf::from("relative/profile"), PathBuf::from("/nightly/../stable"), PathBuf::from("")] { + assert!(fixture.check(Platform::Linux, &root).is_err(), "{}", root.display()); + } + } + + #[test] + fn only_the_nightly_flatpak_may_start_with_its_own_id() { + let fixture = Fixture::new(); + let profile = fixture.profile("flatpak"); + assert!(fixture.check(Platform::Linux, &profile).is_ok()); + std::fs::remove_dir_all(&profile).ok(); + let check_with = |id: &str, candidate: &Path| { + let id = OsString::from(id); + validate_for( + Platform::Linux, + candidate, + |key| if key == "FLATPAK_ID" { Some(id.clone()) } else { fixture.get(key) }, + Some(&fixture.exe), + ensure_writable, + ) + }; + // Stable's id, its window id and an unrelated app's id are all refusals. + for id in [STABLE_ID, "ai.storyteller.texturecraft.nightly-v1", "org.example.other"] { + assert!(check_with(id, &profile).is_err(), "{id} was accepted"); + } + // The Nightly bundle's own id is the sandbox the Nightly package runs in: accepted, with the + // profile its wrapper names inside it (`${XDG_DATA_HOME}/TextureCraft-Nightly`). + let sandbox = fixture.home().join(format!(".var/app/{NIGHTLY_ID}")); + let sandboxed = sandbox.join(".local/share/TextureCraft-Nightly"); + assert_eq!(check_with(NIGHTLY_ID, &sandboxed).expect("the Nightly Flatpak may start"), sandboxed); + std::fs::remove_dir_all(&sandbox).ok(); + } + + #[test] + #[cfg(unix)] + fn an_entry_that_leaves_the_profile_is_refused() { + let fixture = Fixture::new(); + let profile = fixture.profile("aliased"); + let outside = fixture.root.join("somewhere else"); + std::fs::create_dir_all(&profile).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + std::os::unix::fs::symlink(&outside, profile.join("autosave")).unwrap(); + assert!(fixture.check(Platform::Linux, &profile).is_err(), "a link out of the profile must be refused"); + // A dangling link is not a missing folder that may be created. + std::fs::remove_file(profile.join("autosave")).unwrap(); + std::os::unix::fs::symlink(profile.join("missing"), profile.join("logs")).unwrap(); + assert!(fixture.check(Platform::Linux, &profile).is_err()); + std::fs::remove_file(profile.join("logs")).unwrap(); + // A plain folder inside it is fine. + std::fs::create_dir(profile.join("autosave")).unwrap(); + assert!(fixture.check(Platform::Linux, &profile).is_ok()); + } + + #[test] + fn a_failed_write_probe_never_falls_back_to_stable() { + let fixture = Fixture::new(); + let profile = fixture.profile("read only"); + let reached = std::cell::Cell::new(false); + let result = validate_for( + Platform::Linux, + &profile, + |key| fixture.get(key), + Some(&fixture.exe), + |_| { + reached.set(true); + Err(std::io::Error::other("read-only filesystem")) + }, + ); + assert!(result.is_err()); + assert!(reached.get()); + assert!(result.unwrap_err().contains("not writable")); + // The app must not then use the stable folder: it simply refuses to start. + assert!(fixture.check(Platform::Linux, &fixture.home().join("Documents").join(BRAND)).is_err()); + } + + #[test] + #[cfg(unix)] + fn a_profile_whose_existing_ancestor_is_a_link_resolves_before_the_fence() { + let fixture = Fixture::new(); + let real = fixture.root.join("real profiles"); + std::fs::create_dir_all(&real).unwrap(); + let link = fixture.root.join("linked"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + // A link to a private folder is fine, and the resolved root is what the app uses. + let resolved = fixture.check(Platform::Linux, &link.join("nightly")).unwrap(); + assert_eq!(resolved, real.join("nightly")); + } +} diff --git a/assets/app-icon/README.md b/assets/app-icon/README.md index 07351074..38a8538c 100644 --- a/assets/app-icon/README.md +++ b/assets/app-icon/README.md @@ -57,3 +57,23 @@ pillow and potracer): OPT=0.4 DP=1 python3 vectorize_tile.py source.png '#c2672b' 2048 2 texturecraft.svg OPT=1.0 DP=0 python3 vectorize_tile.py source.png '#c2672b' 1024 4 texturecraft-small.svg ``` + +## Nightly icon + +The Nightly build ships the same engraving on a deeper copper field (`#643418`): the background +contribution of each pixel is replaced and the ink, paper and alpha padding are left exactly as +they are. No badge, crescent or letter is added, so the two icons differ only in the field. + +| File | What | +|---|---| +| `texturecraft-nightly.png` | 256 px window icon (`apps/texturecraft/src/main.rs`) | +| `texturecraft-nightly-1024.png` | full tile, 1024 px (docs) | +| `texturecraft-nightly.icns` | macOS icon set, the stable `.icns`'s own PNG slots recoloured | +| `texturecraft-nightly.ico` | Windows icon, the stable `.ico`'s own frames (16 to 256 px) recoloured | +| `nightly/.png` | per-size renders for the Nightly package and the title bar's icon in a Nightly window (16 to 512 px). Kept out of `hicolor/`, which Stable's Linux and FreeBSD packagers copy whole | +| `nightly-provenance.json` | the inputs, the palette, the transform and the SHA-256 of every output | + +`packaging/nightly-icons.py` derives all of them from the committed stable renders (no upscale, no +resvg, no Pillow): run it after `packaging/icons.sh` changes a stable file, and +`python3 packaging/nightly-icons.py --check` (part of `packaging/nightly-tests.py`) fails when a +committed Nightly file has drifted. diff --git a/assets/app-icon/nightly-provenance.json b/assets/app-icon/nightly-provenance.json new file mode 100644 index 00000000..b9c4fc52 --- /dev/null +++ b/assets/app-icon/nightly-provenance.json @@ -0,0 +1,81 @@ +{ + "title": "TextureCraft nightly deep-background icons", + "license": "MIT OR Apache-2.0", + "generator": "packaging/nightly-icons.py", + "generator_sha256": "745786e3bfbecf29077df1e4a64ed717953694038f95533d2d37507c520b791c", + "inputs": [ + { + "path": "assets/app-icon/texturecraft.icns", + "sha256": "eb5e1b19679aa9a23531219d92922e37edbdc3e2046454b8f6c64423f471b57b" + }, + { + "path": "assets/app-icon/texturecraft.ico", + "sha256": "9c3366e4af9f2c0772e00193c348feba834d407fc8b826d4276a8fcb4cc01dcb" + }, + { + "path": "assets/app-icon/texturecraft-1024.png", + "sha256": "8451f91be8c1bc9c2e1a594e193ae5d1793d2d12f26a8bc64d2bd83fe4b789e4" + }, + { + "path": "assets/app-icon/hicolor/16x16/apps/ai.storyteller.texturecraft.png", + "sha256": "79ee309754be54b56052ab05fff87a2427bbc38bb057c96094f8f070ee13ca1d" + }, + { + "path": "assets/app-icon/hicolor/24x24/apps/ai.storyteller.texturecraft.png", + "sha256": "f8f89220ce68be236d63edfd94d4fef2aad2aa9840a50e430f874649a9816171" + }, + { + "path": "assets/app-icon/hicolor/32x32/apps/ai.storyteller.texturecraft.png", + "sha256": "ff8578ffc95f5123bb2e4a00636080f02adf259334ecb0ac9f952fac3378ddb2" + }, + { + "path": "assets/app-icon/hicolor/48x48/apps/ai.storyteller.texturecraft.png", + "sha256": "f7f19ffbd8904ff462bc6d785b865153112025bbdeb868bc0f136e39c7d725e1" + }, + { + "path": "assets/app-icon/hicolor/64x64/apps/ai.storyteller.texturecraft.png", + "sha256": "39d17421579ace5dbe4705fb0a52cd6002d433ded7ba0ee2fdeb5d6d7cd16c8c" + }, + { + "path": "assets/app-icon/hicolor/128x128/apps/ai.storyteller.texturecraft.png", + "sha256": "ac629a038a215a13d86172286142502b6efd17618869652050f291d9745346d2" + }, + { + "path": "assets/app-icon/hicolor/256x256/apps/ai.storyteller.texturecraft.png", + "sha256": "757f858b26897cb0e9f0c8cd43db9ade9664dd6199bd190d1af406839769c71f" + }, + { + "path": "assets/app-icon/hicolor/512x512/apps/ai.storyteller.texturecraft.png", + "sha256": "705513dc82aa908f962b9a466743b42e53b0f586752d2d69a5b6596b8ff928f0" + } + ], + "method": { + "kind": "derivative of the project-owned stable renders; no badge, crescent or letter", + "original_palette": { + "ink": "#0b0b0c", + "paper": "#efe9dc", + "background": "#c2672b" + }, + "nightly_background": "#643418", + "transform": "Fit each pixel as the tile background plus one engraved foreground (ink or paper) and replace only the background contribution; keep alpha, padding and foreground detail. Each frame comes from the stable master of its own size: the .icns and .ico PNG frames are recoloured in place, and the per-size PNGs (in nightly/) and the 1024 master are recoloured from their own renders. No upscaling." + }, + "outputs": { + "assets/app-icon/texturecraft-nightly.icns": "e21e2c90f7402e6289038ad7db896a14780766e07f33d9cb68cbe0d423efe66d", + "assets/app-icon/texturecraft-nightly.ico": "b0dc8817a3b07f0eb8175241c1fdc1ce21ffb8d5a54e6b03979ba2f73e62d47e", + "assets/app-icon/nightly/16.png": "657c7a39547828b0eaafe4b78df28771bb953afdb62440d0c001c695ff586e76", + "assets/app-icon/nightly/24.png": "b4c263436402faa93276b77614291107f6b44309ccfe329b71c3562c1f382c11", + "assets/app-icon/nightly/32.png": "cefb99a330d103f32a07d07e49542da2231897224a3dfe479e9c9d4a53a0a17b", + "assets/app-icon/nightly/48.png": "126316a058f4a225fbea7e1c0e49dc3d27941e2a91a7f033f35b84bc6d646f22", + "assets/app-icon/nightly/64.png": "d471a4bd691fca348603571bfe9c05357120e492566e31c7b2c936361a4a2510", + "assets/app-icon/nightly/128.png": "b36b07739b98b7884ce308641407725bb499adfefd87a4286c3aa117abdb57d5", + "assets/app-icon/nightly/256.png": "82c417bbcafd9b90929b117b7f80f403e631a77a327ee868bc9e8ca7a44c7fe2", + "assets/app-icon/nightly/512.png": "de756e67f16076a08cb5c2726d1a63181a0a8b61c73ff3df0cf49e065f1c8bc2", + "assets/app-icon/texturecraft-nightly-1024.png": "509ebc6130db6c10c380bc4ee2280a6b1810eea5dc03293b86a575c1ef120736", + "assets/app-icon/texturecraft-nightly.png": "82c417bbcafd9b90929b117b7f80f403e631a77a327ee868bc9e8ca7a44c7fe2" + }, + "ico_frames": [ + "the stable .ico's own frames (16, 20, 24, 32, 40, 48, 64, 128, 256)" + ], + "icns_slots": "the stable .icns's own PNG slots (icp4 through ic10)", + "validation": "Byte comparison against the committed assets (packaging/nightly-archive-tests.py and the icon check in packaging/nightly-tests.py); native Explorer/Finder rendering is not exercised here. The per-size PNGs are kept out of hicolor/ because Stable's Linux and FreeBSD packages copy that theme tree whole." +} diff --git a/assets/app-icon/nightly/128.png b/assets/app-icon/nightly/128.png new file mode 100644 index 00000000..c220657a Binary files /dev/null and b/assets/app-icon/nightly/128.png differ diff --git a/assets/app-icon/nightly/16.png b/assets/app-icon/nightly/16.png new file mode 100644 index 00000000..39ae3282 Binary files /dev/null and b/assets/app-icon/nightly/16.png differ diff --git a/assets/app-icon/nightly/24.png b/assets/app-icon/nightly/24.png new file mode 100644 index 00000000..6e15fead Binary files /dev/null and b/assets/app-icon/nightly/24.png differ diff --git a/assets/app-icon/nightly/256.png b/assets/app-icon/nightly/256.png new file mode 100644 index 00000000..3ca334c3 Binary files /dev/null and b/assets/app-icon/nightly/256.png differ diff --git a/assets/app-icon/nightly/32.png b/assets/app-icon/nightly/32.png new file mode 100644 index 00000000..aa3c8526 Binary files /dev/null and b/assets/app-icon/nightly/32.png differ diff --git a/assets/app-icon/nightly/48.png b/assets/app-icon/nightly/48.png new file mode 100644 index 00000000..db1aeaeb Binary files /dev/null and b/assets/app-icon/nightly/48.png differ diff --git a/assets/app-icon/nightly/512.png b/assets/app-icon/nightly/512.png new file mode 100644 index 00000000..f62c465e Binary files /dev/null and b/assets/app-icon/nightly/512.png differ diff --git a/assets/app-icon/nightly/64.png b/assets/app-icon/nightly/64.png new file mode 100644 index 00000000..a85b8233 Binary files /dev/null and b/assets/app-icon/nightly/64.png differ diff --git a/assets/app-icon/texturecraft-nightly-1024.png b/assets/app-icon/texturecraft-nightly-1024.png new file mode 100644 index 00000000..d43e9fbc Binary files /dev/null and b/assets/app-icon/texturecraft-nightly-1024.png differ diff --git a/assets/app-icon/texturecraft-nightly.icns b/assets/app-icon/texturecraft-nightly.icns new file mode 100644 index 00000000..9d96db5f Binary files /dev/null and b/assets/app-icon/texturecraft-nightly.icns differ diff --git a/assets/app-icon/texturecraft-nightly.ico b/assets/app-icon/texturecraft-nightly.ico new file mode 100644 index 00000000..9d1f3eb3 Binary files /dev/null and b/assets/app-icon/texturecraft-nightly.ico differ diff --git a/assets/app-icon/texturecraft-nightly.png b/assets/app-icon/texturecraft-nightly.png new file mode 100644 index 00000000..3ca334c3 Binary files /dev/null and b/assets/app-icon/texturecraft-nightly.png differ diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 47259f2b..9bc2866a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -89,6 +89,8 @@ mod orb_environment; mod orb_material; pub mod orb_previews; mod orb_shape; +/// The channel's OS identity (app id, window and app names) — see its module docs. +pub mod os_window; pub mod parity; mod past_end; mod path_hit; @@ -1216,6 +1218,26 @@ impl eframe::App for TextureCraftApp { #[cfg(not(target_arch = "wasm32"))] static DATA_FOLDER: std::sync::OnceLock = std::sync::OnceLock::new(); +/// A private Nightly profile's data folder, fixed before the first window (unset: stable's +/// Settings folder or the default). Every user folder this app writes — logs, autosave, smart +/// materials, layouts, templates, brushes and export presets — hangs off [`data_dir`], so a +/// Nightly install keeps all of it beside its own settings and never reads Stable's. +#[cfg(not(target_arch = "wasm32"))] +static DATA_ROOT: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Use `root` as the data folder for this process; called once, before the first window, by a +/// Nightly launch with its validated profile. The Settings › Data folder value is not consulted. +#[cfg(not(target_arch = "wasm32"))] +pub fn set_data_root(root: std::path::PathBuf) { + let _ = DATA_ROOT.set(root); +} + +/// Whether this process runs from a private Nightly profile. +#[cfg(not(target_arch = "wasm32"))] +pub fn has_data_root() -> bool { + DATA_ROOT.get().is_some() +} + /// The data folder for a `Prefs::data_folder` value: that path when it is absolute, otherwise /// `Documents/TextureCraft` in the user's home folder. #[cfg(not(target_arch = "wasm32"))] @@ -1228,9 +1250,12 @@ pub fn data_folder(pref: &str) -> std::path::PathBuf { std::path::Path::new(&home).join("Documents").join("TextureCraft") } -/// The data folder in use (Settings › Folders › Data folder). +/// The data folder in use: the Nightly profile when this is one, else Settings › Folders › Data folder. #[cfg(not(target_arch = "wasm32"))] pub fn data_dir() -> std::path::PathBuf { + if let Some(root) = DATA_ROOT.get() { + return root.clone(); + } DATA_FOLDER.get().cloned().unwrap_or_else(|| data_folder("")) } diff --git a/crates/ui-egui/src/os_window.rs b/crates/ui-egui/src/os_window.rs new file mode 100644 index 00000000..f1b60cbe --- /dev/null +++ b/crates/ui-egui/src/os_window.rs @@ -0,0 +1,120 @@ +//! The channel's OS identity: the app id every TextureCraft window carries and the names its +//! windows and About dialog show. +//! +//! The stable app id matches the `.desktop` file and the hicolor icon name, so Linux docks show +//! the TextureCraft icon and Wayland window rules match it. The Nightly window carries its own id +//! (the `.desktop` id the Nightly package installs), so a taskbar, a dock and a window rule can +//! tell the two side by side installs apart. The *package* identity is a different string again +//! (`ai.storyteller.texturecraft.nightly`, the bundle and package id); the two are never mixed. + +/// Matches the stable `.desktop` file and hicolor icon name. +pub const APP_ID: &str = "ai.storyteller.texturecraft"; + +/// The Nightly window's id, matching `packaging/linux/package.sh`'s `StartupWMClass` and the +/// nightly `.desktop` file. +pub const NIGHTLY_APP_ID: &str = "ai.storyteller.texturecraft.nightly-v1"; + +/// Immutable startup identity. The desktop app selects it before any window or service exists. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LaunchIdentity { + Stable, + NightlyV1, +} + +static IDENTITY: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + +/// `Err` when the identity was already selected: it is decided once per process, at startup. +pub fn select_identity(identity: LaunchIdentity) -> Result<(), String> { + let value = match identity { + LaunchIdentity::Stable => 1, + LaunchIdentity::NightlyV1 => 2, + }; + IDENTITY + .compare_exchange(0, value, std::sync::atomic::Ordering::AcqRel, std::sync::atomic::Ordering::Acquire) + .map(|_| ()) + .map_err(|_| "the window launch identity was already selected".into()) +} + +pub fn identity() -> LaunchIdentity { + if IDENTITY.load(std::sync::atomic::Ordering::Acquire) == 2 { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable } +} + +pub const fn id_for(identity: LaunchIdentity) -> &'static str { + match identity { + LaunchIdentity::Stable => APP_ID, + LaunchIdentity::NightlyV1 => 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 => "TextureCraft", + LaunchIdentity::NightlyV1 => "TextureCraft Nightly", + } +} + +/// The app's name in this window: "TextureCraft" or "TextureCraft Nightly". +pub fn name() -> &'static str { + name_for(identity()) +} + +/// Whether the services that belong to a stable install (updates, the control server) may run. +pub const fn stable_services_for(identity: LaunchIdentity) -> bool { + matches!(identity, LaunchIdentity::Stable) +} + +pub fn stable_services_allowed() -> bool { + stable_services_for(identity()) +} + +/// The version this window shows. A Nightly build is prepared with an exact feed identity, which +/// the engine's own constant (the workspace version) does not know; the app sets it at startup. +static DISPLAY_VERSION: std::sync::OnceLock = std::sync::OnceLock::new(); + +pub fn set_display_version(version: String) { + let _ = DISPLAY_VERSION.set(version); +} + +pub fn display_version() -> &'static str { + DISPLAY_VERSION.get().map(String::as_str).unwrap_or(texturecraft_engine::VERSION) +} + +/// A builder for an extra OS window, carrying [`app_id`]. +pub fn builder() -> egui::ViewportBuilder { + egui::ViewportBuilder::default().with_app_id(app_id()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nightly_identity_is_distinct_and_never_enables_stable_services() { + assert_eq!(id_for(LaunchIdentity::Stable), APP_ID); + assert_ne!(id_for(LaunchIdentity::NightlyV1), APP_ID); + assert_eq!(id_for(LaunchIdentity::NightlyV1), NIGHTLY_APP_ID); + assert!(stable_services_for(LaunchIdentity::Stable)); + assert!(!stable_services_for(LaunchIdentity::NightlyV1)); + assert_eq!(name_for(LaunchIdentity::Stable), "TextureCraft"); + assert_eq!(name_for(LaunchIdentity::NightlyV1), "TextureCraft Nightly"); + } + + #[test] + fn the_unset_process_is_the_stable_one_and_extra_windows_carry_its_id() { + // The identity is a process-wide value set once at startup; without it the app is stable. + assert_eq!(identity(), LaunchIdentity::Stable); + assert_eq!(builder().app_id.as_deref(), Some(APP_ID)); + assert_eq!(name(), "TextureCraft"); + } + + #[test] + fn the_shown_version_falls_back_to_the_workspace_version() { + // `set_display_version` is set once per process by the desktop app; the fallback is the + // engine's constant, which is what a stable build shows. + assert!(display_version() == texturecraft_engine::VERSION || !display_version().is_empty()); + } +} diff --git a/crates/ui-egui/src/settings_window.rs b/crates/ui-egui/src/settings_window.rs index 8fda17b0..88d73912 100644 --- a/crates/ui-egui/src/settings_window.rs +++ b/crates/ui-egui/src/settings_window.rs @@ -543,6 +543,12 @@ fn general( section(ui, n_("FOLDERS")); row(ui, tr("Data folder"), |ui, label| { + // A Nightly install keeps every folder inside its own profile (the Launcher picks it), + // so the Setting would be ignored: show where they are instead of editing it. + if crate::has_data_root() { + ui.label(RichText::new(crate::data_dir().display().to_string()).small().color(tk.text_dim)); + return; + } let default = crate::data_folder("").display().to_string(); ui.add(egui::TextEdit::singleline(&mut p.data_folder).hint_text(default).desired_width(CONTROL_WIDTH - 30.0)).labelled_by(label); if ui.button("...").on_hover_text(tr("Choose the data folder")).clicked() { @@ -554,9 +560,13 @@ fn general( } note( ui, - tr( - "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", - ), + if crate::has_data_root() { + tr("TextureCraft Nightly keeps its autosaves, smart materials, presets, templates and UI layouts in its own profile, beside its settings.") + } else { + tr( + "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", + ) + }, ); } } diff --git a/crates/ui-egui/src/titlebar.rs b/crates/ui-egui/src/titlebar.rs index 857c7f10..4f328a85 100644 --- a/crates/ui-egui/src/titlebar.rs +++ b/crates/ui-egui/src/titlebar.rs @@ -53,6 +53,16 @@ const ICONS: [(f32, &[u8]); 5] = [ (64.0, include_bytes!("../../../assets/app-icon/hicolor/64x64/apps/ai.storyteller.texturecraft.png")), ]; +/// The Nightly strip's icon PNGs, same sizes: the deeper background tells the two windows apart at +/// a glance and matches the packaged Nightly icon. +const NIGHTLY_ICONS: [(f32, &[u8]); 5] = [ + (16.0, include_bytes!("../../../assets/app-icon/nightly/16.png")), + (24.0, include_bytes!("../../../assets/app-icon/nightly/24.png")), + (32.0, include_bytes!("../../../assets/app-icon/nightly/32.png")), + (48.0, include_bytes!("../../../assets/app-icon/nightly/48.png")), + (64.0, include_bytes!("../../../assets/app-icon/nightly/64.png")), +]; + impl TitleBar { /// Decide who draws the title bar; call once at startup, before the window is created. /// `system` is Settings › Interface › System title bar. @@ -137,7 +147,8 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { /// The app icon at the cursor, [`ICON`] points square, centred on the row and on whole pixels. fn paint_icon(ui: &mut Ui) { let ppp = ui.ctx().pixels_per_point(); - let Some(&(px, png)) = ICONS.iter().find(|(px, _)| *px >= ICON * ppp - 0.5).or(ICONS.last()) else { return }; + let icons = if crate::os_window::stable_services_allowed() { &ICONS } else { &NIGHTLY_ICONS }; + let Some(&(px, png)) = icons.iter().find(|(px, _)| *px >= ICON * ppp - 0.5).or(icons.last()) else { return }; let id = Id::unique(("app_icon", px as u32)); let texture = match ui.data(|d| d.get_temp::>(id)) { Some(t) => t, diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index 26e6d85a..5544b8fc 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -22,12 +22,19 @@ impl Default for Runtime { impl TextureCraftApp { /// Whether the app asks for a newer release when it starts (off until the desktop app turns it on). pub fn set_startup_update_check(&mut self, on: bool) { - self.updates_rt.startup_check = on; + // A Nightly install is updated by ArtCraft Launcher with the rest of the suite, never by + // the app: an in-app update would replace a copy the Launcher believes it manages. + self.updates_rt.startup_check = on && crate::os_window::stable_services_allowed(); } } -/// Help > Check for Updates: the next frame starts a check that reports its outcome. +/// Help > Check for Updates: the next frame starts a check that reports its outcome. In a Nightly +/// build the Launcher owns updates, so it says so instead of checking. pub(crate) fn request_check(app: &mut TextureCraftApp, ctx: &egui::Context) { + if !crate::os_window::stable_services_allowed() { + app.toast(crate::i18n::tr("TextureCraft Nightly is updated by ArtCraft Launcher."), false); + return; + } app.updates_rt.check_requested = true; ctx.request_repaint(); } @@ -45,6 +52,9 @@ fn holds_keyboard(status: &Status, prompt_open: bool) -> bool { } pub(crate) fn tick(app: &mut TextureCraftApp, ctx: &egui::Context) { + if !crate::os_window::stable_services_allowed() { + return; + } let rt = &mut app.updates_rt; if std::mem::take(&mut rt.check_requested) { rt.updater.check_now(ctx); diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index f9e8fa5c..56e64caf 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -307,10 +307,13 @@ fn export_mesh(app: &mut TextureCraftApp, ctx: &egui::Context) { fn about(app: &mut TextureCraftApp, ctx: &egui::Context) { let tk = Tokens::get(ctx); let mut open = app.ui.windows.about; - dialog(ctx, "about", tr("About TextureCraft"), &mut open).show(ctx, |ui| { + let name = crate::os_window::name(); + // A Nightly window names its channel in the title too; the stable title keeps its translations. + let title = if name == "TextureCraft" { tr("About TextureCraft").to_owned() } else { trf("About {app}", &[("app", &name)]) }; + dialog(ctx, "about", &title, &mut open).show(ctx, |ui| { ui.vertical_centered(|ui| { - ui.label(RichText::new("TextureCraft").size(22.0).strong().color(tk.text_strong)); - ui.label(trf("Version {version}", &[("version", &texturecraft_engine::VERSION)])); + ui.label(RichText::new(name).size(22.0).strong().color(tk.text_strong)); + ui.label(trf("Version {version}", &[("version", &crate::os_window::display_version())])); ui.add_space(6.0); ui.label(tr("3D texture painting: layers, masks, smart materials, mesh map baking and export.")); ui.label(tr("Free and open source (MIT OR Apache-2.0), written in Rust.")); diff --git a/docs/nightly-release-preparation.md b/docs/nightly-release-preparation.md new file mode 100644 index 00000000..2b504a7e --- /dev/null +++ b/docs/nightly-release-preparation.md @@ -0,0 +1,133 @@ +# Windows, Linux and macOS release-ref nightly: supervised manual go-live + +**Enabled for supervised manual runs, not yet qualified.** The producer (`nightly.yml`, main) and the +signer (`nightly-sign.yml`, release) keep only their exact context guards and run when one of the reviewed +manual actors dispatches them. There is no schedule yet. The installed policy +[`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the v3 +policy. Once `nightly.yml` is registered on `main`, populate `producer_workflow_id` by reading: + +```bash +gh api repos/storytold/texturecraft/actions/workflows/nightly.yml --jq .id +``` + +The callers pass no platform secrets. The unsigned reusable caller's maximum OIDC/attestation +permissions are for its isolated attester; its compiler narrows to contents and Actions read +only, with no OIDC, attestation write, release environment or platform signing secrets. +Shared tooling is pinned to `605d58766e8f536564da8fc81d3676ac86816dea`, the craft-common-actions +main commit that merged [#339](https://github.com/storytold/craft-common-actions/pull/339) (bounded +lineage compares and an issue reread at the end of candidate admission) on top of +[#342](https://github.com/storytold/craft-common-actions/pull/342) (policy v3, the `platforms` input +and the Linux and macOS legs). Both callers name it in `uses` and `tooling-revision`. A pin is reviewed +source availability, not provider, queue, native signing or crypto qualification. +Existing stable workflows are unchanged. + +**First runs.** The first runs are manual dispatches in this order: `nightly.yml` on main (only a +listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `release` with that +producer run ID and attempt, by a listed manual actor. + +**Manual actors.** `bflatastic`, `dylanmtaylor`, `echelon`, `FredApps` and `skylartaylor`, in the +producer's `manual-actors` and the policy's `manual_actors`. The list mirrors the release-managers +team (id 19837241), leaving out `echelon-robot`, which only has read access; update it by PR +in both places when the team changes. + +**Admission timing.** The candidate check reads the newest CI run on the candidate commit and +main's latest finished Sonar analysis, so when to dispatch matters: +- The candidate must be main's latest finished Sonar analysis. Pick a quiet main, wait for its + CI and SonarCloud analysis to finish green, then dispatch the producer and, once it succeeds, + the signer, before another main push lands a newer analysis. + +**Platform rows.** The producer caller lists +`platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'` on its single job: one producer +run builds every listed platform for one all-or-nothing release (one failed or +skipped platform stops that night's release, Windows included), and the release-ref signer admits +platforms only from the protected policy, so there is no separate Linux or macOS caller job and +the signer caller has no platform input. + +## Installed policy values and their sources + +Read on 2026-11-24; re-read anything that may have moved before the policy is promoted to `release`. + +| Field | Value | Source | +|---|---|---| +| `repository_id` | `1419654881` | `gh api repos/storytold/texturecraft --jq .id` | +| `producer_workflow_id` | `null` (pending registration on `main`) | Populate via `gh api repos/storytold/texturecraft/actions/workflows/nightly.yml --jq .id` once `nightly.yml` reaches `main` | +| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `605d5876…` (craft-common-actions #339) | The callers' pin | +| `manual_actors` / `automatic_signer_actors` | the five release managers / `[]` | release-managers team (id 19837241) members who can push; equals the producer caller's `manual-actors` | +| `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist | +| `platforms` | three rows (`windows-x86_64`, `linux-x86_64`, `macos-aarch64`) | Stable suite signing identities (`Learning Machines Inc` Authenticode subject, Linux OpenPGP fingerprint `2B76741B414AAD6CD33E631213A005C0B9D7C3ED`, Apple Team ID `DJ6XS33FX8`) | +| `candidate_policy.required_workflows` | CI (`ci.yml`, workflow `384666426`), 2 gate jobs | Workflow list API; jobs that succeeded on recent `main` push runs | +| `candidate_policy.sonar` | `storytold` / `storytold_texturecraft`, app `12526` | SonarCloud check on `main` commits | +| Sonar `issue_types` / `debt` | `VULNERABILITY`; `[]` (0 unresolved main vulnerabilities) | `api/issues/search` on `main` | + +The candidate check refuses whenever main's unresolved vulnerability set differs from `debt`, whether +an issue is new or fixed, and whenever a required condition fails or a listed CI job is renamed. Refresh +those values in the same reviewed change that promotes the policy to `release`. + +## Ownership and interface + +- `.github/workflows/nightly.yml`: default-main registration of the unsigned producer, named + `TextureCraft unsigned nightly`, enabled for manual dispatch by `manual-actors`; no signing secrets + may be passed or inherited. +- `.github/workflows/nightly-sign.yml`: top-level release registration, enabled for manual dispatch, + and identical on main and release after reviewed promotion. It rejects wrong repository/event/actual branch, + including same-name tags. Its constant whole-run concurrency is distinct from stable, + cancellation is off and `queue: max` must be hosted-qualified. The caller itself passes no + credentials; only the shared callee's sign jobs bind the `release` environment. +- Shared reusable entrypoints are `nightly-unsigned.yml` and `nightly-release.yml` in + `storytold/craft-common-actions`. Both must resolve to a **real reviewed public immutable + commit**; the defining workflow SHA and tooling input must match. + +## Local regression checks + +`python3 packaging/nightly-release-tests.py` verifies the nightly workflow contracts: +- Both callers share one immutable 40-character SHA pin in `uses` and `tooling-revision`. +- Both callers keep their exact context guards (`if: >-` with no hidden continuation lines). +- `manual-actors` in `nightly.yml` and `manual_actors` in `.github/nightly-signing-policy.json` + match the reviewed release managers list, and `automatic_signer_actors` is empty. +- No nightly schedule is registered. +- No cache actions, cache setup options, `environment:`, or `secrets` appear in the app callers. +- `nightly-sign.yml` keeps its literal root `concurrency:` block (`texturecraft-nightly-release`, + `cancel-in-progress: false`, `queue: max`). +- `.github/nightly-signing-policy.json` matches the v3 schema, repository identity, platform + trust anchors, CI workflow trigger contract, and SonarCloud project identity. + + +## App-side producer scripts (Windows and macOS) + +**Every Linux Nightly format starts the app the flavor's way.** The `.deb`/`.rpm` wrapper, the +Arch launcher, the Flatpak wrapper, the AppImage's `AppRun` and the launcher inside the plain +`nightly.tar.gz` all exec the real GUI with the literal +`--launch-profile nightly-v1 --profile-root <${XDG_DATA_HOME:-~/.local/share}/TextureCraft-Nightly> --`, +and pass a Launcher protocol or a `--version`/`-V` query through untouched (so the smoke checks and +`texturecraft-nightly --version` still answer). The profile is outside stable's folders and outside +the unpacked or installed copy, which the flavor's fence would otherwise refuse. + +Every Nightly Linux format is GUI only. `texturecraft-cli` stays in the Stable packages: a headless +run loads its brush presets from `Documents/TextureCraft`, which is Stable's folder on every +platform and cannot be redirected by the launch profile, so a Nightly CLI would read and rewrite +Stable's brushes. The Flatpak smoke test therefore asks the app (`flatpak run --command=texturecraft`), +and the Arch handoff no longer stages a CLI. + +The producer's Windows and macOS legs run scripts this repository owns. Their inputs are the four +`TEXTURECRAFT_*` values the feed prepares (channel, exact version, commit, original run date), an +absolute `CARGO_TARGET_DIR` and `DIST`, and optionally `CRAFT_FONTS_DIR` with +`CRAFT_FONTS_REQUIRED=1`: + +| Platform | Compile step (no secrets) | Trusted signer step (release checkout) | +|---|---|---| +| Windows x86_64 | `pwsh packaging/windows/package.ps1 -Arch x64 -Nightly -BuildOnly` (through `nightly.ps1`) | `pwsh packaging/windows/sign.ps1 -Required` | +| macOS aarch64 | `bash packaging/macos/nightly.sh --arch aarch64` | `bash packaging/macos/nightly-sign.sh`, then `nightly-verify.sh --expect signed --team` in a job without secrets | + +Both compile steps refuse every signing variable before Cargo runs +(`sign.ps1 -CheckBuildEnvironment`, `nightly_refuse_signing_env`), require the prepared commit to +be the checked-out one and the tree clean, and refuse `-SkipBuild`/an existing output. The +archives are GUI only: `texturecraft.exe` plus notices on Windows, `TextureCraft Nightly.app` on +macOS. The app-side surface — the build channel, the launch profile, the data root and the +fences — is described in the PR that adds it; the installed policy above is unchanged by it. + +Local checks with no compiler, macOS or network: `python3 packaging/nightly-tests.py` (the plist, +release-dispatch and macOS signing suites, plus the Nightly icons must be byte-identical to what +`packaging/nightly-icons.py` derives), `packaging/windows/nightly-package-tests.ps1` and +`nightly-signing-tests.ps1` (Windows, with `-FixtureRoot`), and `bash -n` plus shellcheck over the +three macOS scripts. The full-ci macOS job (`nightly-macos.yml`) is the only place the bundle and +its version query actually run before the first supervised release. diff --git a/docs/nightly-signing-policy.example.json b/docs/nightly-signing-policy.example.json new file mode 100644 index 00000000..99924a91 --- /dev/null +++ b/docs/nightly-signing-policy.example.json @@ -0,0 +1,54 @@ +{ + "schema": "craft-nightly-release-policy/v3", + "repository": "storytold/texturecraft", + "repository_id": null, + "producer_workflow_id": null, + "producer_workflow_path": ".github/workflows/nightly.yml", + "producer_tooling_revision": null, + "producer_workflow_ref": null, + "signer_workflow_path": ".github/workflows/nightly-sign.yml", + "signer_tooling_revision": null, + "release_branch": "release", + "manual_actors": [], + "max_age_seconds": null, + "candidate_policy": { + "schema": "craft-nightly-candidate-policy/v3", + "epoch": null, + "repository": "storytold/texturecraft", + "branch": "main", + "required_workflows": null, + "sonar": { + "organization": null, + "project": null, + "app_id": null, + "check_name": null, + "details_url": null, + "issue_types": null, + "accepted_conditions": null, + "required_conditions": null, + "debt": null + } + }, + "max_artifact_bytes": null, + "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/packaging/linux/AppRun b/packaging/linux/AppRun index 4feb8f88..cd1fd9c2 100755 --- a/packaging/linux/AppRun +++ b/packaging/linux/AppRun @@ -13,6 +13,9 @@ set -u APPDIR="$(dirname "$(readlink -f "$0")")" DESK_ID=ai.storyteller.texturecraft +# package.sh rewrites this line for a Nightly AppImage, which starts the app with the Launcher's +# private profile exactly as the deb, rpm, Arch, Flatpak and tarball launchers do. +CHANNEL=stable integrate() { case "${TEXTURECRAFT_NO_DESKTOP_INTEGRATION:-}" in @@ -69,4 +72,14 @@ integrate() { } integrate + +# The Launcher's own protocol, and a bare version query, pass through untouched: the first already +# names its profile, and the second must answer without one. +case "${1-}" in + --launch-profile | --profile-root | --version | -V) exec "$APPDIR/usr/bin/texturecraft" "$@" ;; +esac +if [ "$CHANNEL" = nightly-v1 ]; then + exec "$APPDIR/usr/bin/texturecraft" --launch-profile nightly-v1 \ + --profile-root "${XDG_DATA_HOME:-${HOME:-}/.local/share}/TextureCraft-Nightly" -- "$@" +fi exec "$APPDIR/usr/bin/texturecraft" "$@" diff --git a/packaging/linux/ai.storyteller.texturecraft.desktop b/packaging/linux/ai.storyteller.texturecraft.desktop index ded29c5d..8c27063c 100644 --- a/packaging/linux/ai.storyteller.texturecraft.desktop +++ b/packaging/linux/ai.storyteller.texturecraft.desktop @@ -8,7 +8,7 @@ TryExec=texturecraft Icon=ai.storyteller.texturecraft Terminal=false StartupNotify=true -StartupWMClass=texturecraft +StartupWMClass=ai.storyteller.texturecraft Categories=Graphics;3DGraphics; Keywords=texture;paint;pbr;material;3d;mesh;bake;gltf;fbx;usd; MimeType=application/x-texturecraft;model/gltf-binary;model/gltf+json;model/x-fbx;model/vnd.collada+xml;model/x-usd;model/vnd.usda;model/vnd.usdz+zip;model/x-alembic;model/obj;model/x-ply;model/stl; diff --git a/packaging/linux/apprun-test.sh b/packaging/linux/apprun-test.sh index cfb9548e..34034f96 100755 --- a/packaging/linux/apprun-test.sh +++ b/packaging/linux/apprun-test.sh @@ -95,4 +95,22 @@ out="$(APPIMAGE="$odd" "$APPDIR/AppRun" x)" || fail "launch with an odd path exi [[ "$out" = "stub: x" ]] || fail "odd path: $out" [[ ! -e "$XDG_DATA_HOME" ]] || fail "integrated an AppImage path that needs escaping" +# 10. A Nightly AppImage (package.sh rewrites the channel line) starts the app with the Launcher's +# private profile; a version query still passes through untouched. +NIGHTLY_APPDIR="$TMP/Nightly.AppDir" +mkdir -p "$NIGHTLY_APPDIR/usr/bin" +install -Dm755 "$HERE/AppRun" "$NIGHTLY_APPDIR/AppRun" +cat >"$NIGHTLY_APPDIR/usr/bin/texturecraft" <<'RECORDER' +#!/bin/sh +printf '<%s>\n' "$@" +RECORDER +chmod +x "$NIGHTLY_APPDIR/usr/bin/texturecraft" +sed -i 's|^CHANNEL=stable$|CHANNEL=nightly-v1|' "$NIGHTLY_APPDIR/AppRun" +grep -qx 'CHANNEL=nightly-v1' "$NIGHTLY_APPDIR/AppRun" || fail "Nightly AppRun was not switched" +out="$(env -u APPIMAGE XDG_DATA_HOME="$TMP/nightly-data" "$NIGHTLY_APPDIR/AppRun" a.glb)" || fail "Nightly AppRun exited non-zero" +expected="$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$TMP/nightly-data/TextureCraft-Nightly" -- a.glb)" +[[ "$out" = "$expected" ]] || fail "Nightly AppRun did not use the Launcher profile: $out" +out="$(env -u APPIMAGE "$NIGHTLY_APPDIR/AppRun" --version)" || fail "Nightly version query exited non-zero" +[[ "$out" = "<--version>" ]] || fail "Nightly AppRun rewrote a version query: $out" + echo "AppRun desktop integration ok" diff --git a/packaging/linux/flatpak-bundle.sh b/packaging/linux/flatpak-bundle.sh index 4e884d84..1cce735c 100755 --- a/packaging/linux/flatpak-bundle.sh +++ b/packaging/linux/flatpak-bundle.sh @@ -9,14 +9,20 @@ # is built for the host architecture (x86_64 or aarch64), which must match the tarball's. # Needs flatpak, flatpak-builder and the SVG pixbuf loader (librsvg2-common) for the host's # `appstreamcli compose`; the freedesktop runtime and SDK named in the manifest are -# installed per-user from Flathub. Unless --no-test, the bundle is then installed per-user and -# `texturecraft-cli --version` is run inside the sandbox as a smoke test. +# installed per-user from Flathub. Unless --no-test, the bundle is then installed per-user and the +# app (`texturecraft --version`) is run inside the sandbox as a smoke test. # Manifest: packaging/linux/flatpak/ai.storyteller.TextureCraft.bundle.yml. set -euo pipefail # shellcheck source=../env.sh . "$(dirname "${BASH_SOURCE[0]}")/../env.sh" HERE="$ROOT/packaging/linux" APP_ID=ai.storyteller.texturecraft +FLATPAK_ID="$APP_ID" +# The remote indexes both app IDs on the stable ref branch; IDs isolate installations. +FLATPAK_BRANCH=stable +if [[ "${TEXTURECRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then + FLATPAK_ID="$APP_ID.nightly" +fi FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo # The OCI repository serves only the latest stable release, so a prerelease bundle gets no update # source: Flatpak would otherwise replace it with that older stable build. @@ -56,38 +62,98 @@ rm -rf "$WORK" mkdir -p "$WORK/stage" tar -xzf "$TARBALL" -C "$WORK/stage" --strip-components=1 [[ -x "$WORK/stage/bin/texturecraft" ]] || { echo "error: $TARBALL has no bin/texturecraft" >&2; exit 1; } -cp "$HERE/flatpak/ai.storyteller.TextureCraft.bundle.yml" "$WORK/$APP_ID.yml" +if [[ "$FLATPAK_ID" != "$APP_ID" ]]; then + # A Nightly tarball from package.sh already separates the launcher from the GUI; an older one + # does not. Either way this bundle installs its own wrapper and the GUI in /app/libexec. + if [[ -e "$WORK/stage/bin/texturecraft-bin" ]]; then + rm -f "$WORK/stage/bin/texturecraft" + else + mv "$WORK/stage/bin/texturecraft" "$WORK/stage/bin/texturecraft-bin" + fi + cat >"$WORK/stage/bin/texturecraft" <<'WRAPPER' +#!/bin/sh +# TextureCraft Nightly: the GUI runs with the Launcher's private profile. Inside the sandbox +# $XDG_DATA_HOME is the app's own per-app folder, so the profile never meets stable's. +set -eu +bin=/app/libexec/texturecraft +profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/TextureCraft-Nightly" +# The Launcher's protocol, and a bare version query, pass through untouched. +case "${1-}" in + --launch-profile | --profile-root | --version | -V) exec "$bin" "$@" ;; +esac +exec "$bin" --launch-profile nightly-v1 --profile-root "$profile" -- "$@" +WRAPPER + chmod 755 "$WORK/stage/bin/texturecraft" + sed -e "s|^Icon=$APP_ID$|Icon=$FLATPAK_ID|" \ + -e "s|^Name=TextureCraft$|Name=TextureCraft Nightly|" \ + -e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.texturecraft.nightly-v1|' \ + -e '/^MimeType=/d' \ + "$WORK/stage/share/applications/$APP_ID.desktop" >"$WORK/stage/share/applications/$FLATPAK_ID.desktop" + rm -f "$WORK/stage/share/applications/$APP_ID.desktop" + # The Nightly entry drops MimeType=, so the metainfo must not advertise the types either. + sed -e "s|$APP_ID|$FLATPAK_ID|g" \ + -e "s|TextureCraft|TextureCraft Nightly|g" \ + -e "s|$APP_ID.desktop|$FLATPAK_ID.desktop|g" \ + -e "s|$APP_ID|$FLATPAK_ID|g" \ + -e '//d' \ + "$WORK/stage/share/metainfo/$APP_ID.metainfo.xml" >"$WORK/stage/share/metainfo/$FLATPAK_ID.metainfo.xml" + rm -f "$WORK/stage/share/metainfo/$APP_ID.metainfo.xml" + rm -rf "$WORK/stage/share/mime" + rm -rf "$WORK/stage/share/icons/hicolor" + NIGHTLY_ICON="$ROOT/assets/app-icon/texturecraft-nightly.png" + if [[ ! -f "$NIGHTLY_ICON" ]]; then + NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" + fi + install -Dm644 "$NIGHTLY_ICON" \ + "$WORK/stage/share/icons/hicolor/256x256/apps/$FLATPAK_ID.png" + # Omit conflicting MIME registrations and disable host Flatpak updater talk-name until + # craft_update supports the nightly FLATPAK_ID. A Nightly bundle is also GUI-only: its tarball has + # no texturecraft-cli, and a CLI would read Stable's Documents/TextureCraft brushes. + sed -e "s|ai\.storyteller\.texturecraft|$FLATPAK_ID|g" \ + -e '/share\/mime\/packages\//d' \ + -e '/^\( *\)# \.tcraft, plus mesh types/d' \ + -e '/bin\/texturecraft-cli/d' \ + -e '/--talk-name=org\.freedesktop\.Flatpak/d' \ + -e 's|- install -Dm755 bin/texturecraft /app/bin/texturecraft|- install -Dm755 bin/texturecraft-bin /app/libexec/texturecraft\n - install -Dm755 bin/texturecraft /app/bin/texturecraft|' \ + "$HERE/flatpak/ai.storyteller.TextureCraft.bundle.yml" >"$WORK/$FLATPAK_ID.yml" +else + cp "$HERE/flatpak/ai.storyteller.TextureCraft.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" # A release build (the shared release workflow sets SIGNING_FPR, SIGNING_PUBKEY and GNUPGHOME) # signs the commit and embeds the public key, so Flatpak verifies the bundle when installing it. GPG_KEYS=() if [[ -n "${SIGNING_FPR:-}" ]]; then - flatpak build-sign "$WORK/repo" "$APP_ID" stable --gpg-sign="$SIGNING_FPR" --gpg-homedir="${GNUPGHOME:?}" + flatpak build-sign "$WORK/repo" "$FLATPAK_ID" "$FLATPAK_BRANCH" --gpg-sign="$SIGNING_FPR" --gpg-homedir="${GNUPGHOME:?}" GPG_KEYS=(--gpg-keys="${SIGNING_PUBKEY:?}") if [[ "${OCI_SIGNATURES_READY:-}" != 1 ]]; then OCI_REPO=""; fi fi # --runtime-repo lets `flatpak install` fetch the freedesktop runtime from Flathub if missing. # --repo-url makes the installed origin update from the ArtCraft OCI repository. -flatpak build-bundle --runtime-repo="$FLATHUB" ${OCI_REPO:+--repo-url="$OCI_REPO"} "${GPG_KEYS[@]}" "$WORK/repo" "$OUT" "$APP_ID" stable +flatpak build-bundle --runtime-repo="$FLATHUB" ${OCI_REPO:+--repo-url="$OCI_REPO"} "${GPG_KEYS[@]}" "$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=texturecraft-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=texturecraft "$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 + flatpak run --command=sh "$FLATPAK_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/icons/hicolor/*/apps && test ! -e /app/share/mime/packages' + fi fi echo "==> done" ls -lh "$OUT" diff --git a/packaging/linux/nfpm.yaml b/packaging/linux/nfpm.yaml index 8d4cebf0..1cea1c4b 100644 --- a/packaging/linux/nfpm.yaml +++ b/packaging/linux/nfpm.yaml @@ -1,9 +1,12 @@ # .deb and .rpm packages (nfpm: https://nfpm.goreleaser.com). Run by package.sh, which stages # the file tree, substitutes its path for ${STAGE} (nfpm doesn't expand env vars in `src`) and -# exports VERSION and NFPM_ARCH. +# exports VERSION, NFPM_ARCH, NFPM_NAME, NFPM_BIN and NFPM_CLI (the Nightly package renames the +# first two and has no CLI, so package.sh removes the CLI entry for it). By hand, all five are +# needed: # -# nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/ -name: texturecraft +# VERSION=1.2.3 NFPM_ARCH=amd64 NFPM_NAME=texturecraft NFPM_BIN=texturecraft \ +# NFPM_CLI=texturecraft-cli nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/ +name: ${NFPM_NAME} arch: ${NFPM_ARCH} platform: linux version: ${VERSION} @@ -66,12 +69,15 @@ overrides: - xdg-desktop-portal contents: - - src: ${STAGE}/usr/bin/texturecraft - dst: /usr/bin/texturecraft + - src: ${STAGE}/usr/bin/${NFPM_BIN} + dst: /usr/bin/${NFPM_BIN} file_info: { mode: 0755 } - - src: ${STAGE}/usr/bin/texturecraft-cli - dst: /usr/bin/texturecraft-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 00000000..6e5c07d5 --- /dev/null +++ b/packaging/linux/nightly-arch-launch.sh @@ -0,0 +1,14 @@ +#!/bin/sh +# The TextureCraft Nightly launcher for the Arch handoff (packaging/linux/nightly-arch-tar.sh): +# the real GUI stays in .texturecraft-nightly/, and this starts it with the Launcher's private +# profile, as every other Nightly package does. +set -eu + +bin="$(dirname "$0")/.texturecraft-nightly/texturecraft" +profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/TextureCraft-Nightly" + +# The Launcher's protocol, and a bare version query, pass through untouched. +case "${1-}" in + --launch-profile | --profile-root | --version | -V) exec "$bin" "$@" ;; +esac +exec "$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 00000000..5bd69fa2 --- /dev/null +++ b/packaging/linux/nightly-arch-tar-test.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +# Validate the staged Arch launcher without building or opening TextureCraft. +set -euo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +stage="$work/source" +dst="$work/dist" +base=texturecraft-0.0.1-nightly.1-linux-x86_64 +mkdir -p "$stage/bin" "$dst" "$work/extract" + +# A local argv recorder stands in for the compiled binaries. It never opens a UI. +cat >"$stage/bin/texturecraft" <<'RECORDER' +#!/bin/sh +printf '<%s>\n' "$@" +RECORDER +chmod 755 "$stage/bin/texturecraft" + +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/texturecraft" "$bin/texturecraft-nightly" + +test ! -e "$stage/bin/.texturecraft-nightly" +cmp "$stage/bin/texturecraft" "$bin/.texturecraft-nightly/texturecraft" +# A Nightly package is GUI-only: the handoff must not carry a CLI that would use Stable's brushes. +test ! -e "$bin/texturecraft-nightly-cli" || { echo "FAIL: the Arch handoff still ships a Nightly CLI" >&2; exit 1; } +profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/TextureCraft-Nightly" +# A launch adds the Launcher's literal selector/root pair and the file delimiter; a version query or +# an already-formed protocol passes through untouched. +expect_launch() { + expected="$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$profile" -- "$@")" + actual=$(PATH="$bin:$PATH" texturecraft-nightly "$@") + [[ "$actual" == "$expected" ]] || { + printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2 + exit 1 + } +} +expect_forwarded() { + expected="$(printf '<%s>\n' "$@")" + actual=$(PATH="$bin:$PATH" texturecraft-nightly "$@") + [[ "$actual" == "$expected" ]] || { + printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2 + exit 1 + } +} +expect_launch +expect_launch 'mesh with spaces.glb' '--other-name.tcraft' +expect_forwarded --version +expect_forwarded -V +expect_forwarded --launch-profile nightly-v1 --profile-root /launcher/profile --version + +echo "PASS: Arch Nightly handoff preserves binary layout and passes the Launcher profile" diff --git a/packaging/linux/nightly-arch-tar.sh b/packaging/linux/nightly-arch-tar.sh new file mode 100755 index 00000000..69581347 --- /dev/null +++ b/packaging/linux/nightly-arch-tar.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Stage the TextureCraft 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" +# The Nightly package is GUI-only: texturecraft-cli would read and rewrite Stable's +# Documents/TextureCraft brushes, which a private profile cannot redirect. +rm -f "$stage/bin/texturecraft-cli" +mkdir "$stage/bin/.texturecraft-nightly" +mv "$stage/bin/texturecraft" "$stage/bin/.texturecraft-nightly/texturecraft" +cp "$here/nightly-arch-launch.sh" "$stage/bin/texturecraft" +chmod 755 "$stage/bin/texturecraft" +tar -C "$work" -czf "$destination/$basename.tar.gz" "$basename" +echo "wrote $destination/$basename.tar.gz" diff --git a/packaging/linux/nightly-launch-test.sh b/packaging/linux/nightly-launch-test.sh new file mode 100755 index 00000000..4da17cd3 --- /dev/null +++ b/packaging/linux/nightly-launch-test.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# The launcher inside the plain Nightly tarball (packaging/linux/nightly-launch.sh): a launch adds +# the Launcher's private profile, a version query or an existing protocol passes through, and the +# fence's shape holds (absolute root, no parent traversal, outside this copy). +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT +mkdir -p "$work/tree" + +# An argv recorder stands in for the GUI. It never opens a window. +cat >"$work/tree/texturecraft-bin" <<'RECORDER' +#!/bin/sh +printf '<%s>\n' "$@" +RECORDER +chmod 755 "$work/tree/texturecraft-bin" +cp "$HERE/nightly-launch.sh" "$work/tree/texturecraft" + +profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/TextureCraft-Nightly" +# The profile must be something the app's fence accepts: absolute, no parent traversal, and not +# inside the unpacked copy (the running install). +case "$profile" in + /*) ;; + *) echo "FAIL: the launcher profile is not absolute: $profile" >&2; exit 1 ;; +esac +case "/$profile/" in + */../*) echo "FAIL: the launcher profile contains parent traversal" >&2; exit 1 ;; +esac +case "$profile/" in + "$work/tree/"*) echo "FAIL: the launcher profile is inside the unpacked copy" >&2; exit 1 ;; +esac + +expect_launch() { + expected="$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$profile" -- "$@")" + actual=$("$work/tree/texturecraft" "$@") + [[ "$actual" == "$expected" ]] || { + printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2 + exit 1 + } +} +expect_forwarded() { + expected="$(printf '<%s>\n' "$@")" + actual=$("$work/tree/texturecraft" "$@") + [[ "$actual" == "$expected" ]] || { + printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2 + exit 1 + } +} + +expect_launch +expect_launch 'model with spaces.glb' '--other-name.tcraft' +expect_forwarded --version +expect_forwarded -V +expect_forwarded --launch-profile nightly-v1 --profile-root /launcher/profile --version + +echo "PASS: tarball Nightly launcher starts the GUI with the Launcher profile and forwards files" diff --git a/packaging/linux/nightly-launch.sh b/packaging/linux/nightly-launch.sh new file mode 100755 index 00000000..77fa7d9c --- /dev/null +++ b/packaging/linux/nightly-launch.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# The entry point inside the Nightly tarball (packaging/linux/nightly.sh installs it as +# `texturecraft`, beside the GUI as `texturecraft-bin`). +# +# A Nightly build only starts with its private profile, and every package format passes the +# Launcher's literal protocol: `--launch-profile nightly-v1 --profile-root -- `. The +# profile sits outside stable's folders (its own settings, ui.json, crash log, autosaves, smart +# materials, layouts, templates and presets) and outside this unpacked copy, which the app's own +# fence would refuse. +set -eu + +here="$(dirname "$(readlink -f "$0")")" +bin="$here/texturecraft-bin" +profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/TextureCraft-Nightly" + +# The Launcher's protocol, and a bare version query, pass through untouched: the first already +# names its profile, and the second must answer without one. +case "${1-}" in + --launch-profile | --profile-root | --version | -V) exec "$bin" "$@" ;; +esac +exec "$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 00000000..687344c7 --- /dev/null +++ b/packaging/linux/nightly.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# App-owned GUI-only nightly tar: no FUSE/AppImage, CLI, association or install hooks. +set -euo pipefail +ARCH= +while [[ $# -gt 0 ]]; do + case "$1" in + --arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;; + -h|--help) echo 'Usage: nightly.sh --arch x86_64'; exit 0 ;; + *) echo "unsupported nightly argument: $1" >&2; exit 2 ;; + esac +done +[[ "$ARCH" == x86_64 && "$(uname -s)" == Linux ]] || { echo 'only native Linux x86_64 nightly packaging is supported' >&2; exit 2; } +# shellcheck source=../nightly-common.sh +. "$(dirname "${BASH_SOURCE[0]}")/../nightly-common.sh" +nightly_init linux "$ARCH" x86_64-unknown-linux-gnu +OUTPUT="$DIST/texturecraft-$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 launcher is the entry point (`texturecraft`); the GUI sits beside it and is started with the +# Launcher's private profile, so an unpacked tarball never writes stable's folders. The flat layout +# is what nightly-archive.py allows, and the launcher is a committed script so shellcheck covers +# it like every other shell script. +cp "$NIGHTLY_GUI" "$STAGE/texturecraft-bin" +chmod 755 "$STAGE/texturecraft-bin" +cp "$ROOT/packaging/linux/nightly-launch.sh" "$STAGE/texturecraft" +chmod 755 "$STAGE/texturecraft" +cp "$ROOT/assets/app-icon/texturecraft-nightly-1024.png" "$STAGE/texturecraft-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 a5a3ffd1..8c2ca936 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -7,7 +7,7 @@ # $DIST/texturecraft--linux-.rpm Fedora, openSUSE, RHEL, ... # $DIST/texturecraft--linux-.tar.gz plain FHS-style tree (bin/, share/) # -# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"] +# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"] [--arch-tar-dir DIRECTORY] # # Needs: cargo; nfpm for deb/rpm (https://nfpm.goreleaser.com); appimagetool for the AppImage # (downloaded into $CARGO_TARGET_DIR if missing). Build on an old distro (CI: Ubuntu 22.04, @@ -21,10 +21,16 @@ APP_ID=ai.storyteller.texturecraft 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,15p' "$0"; exit 0 ;; *) echo "unknown argument: $1" >&2; exit 2 ;; esac @@ -38,9 +44,24 @@ case "$ARCH" in *) echo "unsupported architecture $ARCH" >&2; exit 2 ;; esac export TEXTURECRAFT_MAINTAINER="${TEXTURECRAFT_MAINTAINER:-TextureCraft maintainers }" +IS_NIGHTLY=0 +if [[ "${TEXTURECRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then + IS_NIGHTLY=1 + export TEXTURECRAFT_BUILD_CHANNEL=nightly-v1 + export TEXTURECRAFT_OVERRIDE_VERSION="$VERSION" +fi +NIGHTLY_ICON="$ROOT/assets/app-icon/texturecraft-nightly.png" +if [[ ! -f "$NIGHTLY_ICON" ]]; then + NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" +fi BASENAME="texturecraft-$VERSION-linux-$ARCH" -echo "==> TextureCraft $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 "==> TextureCraft $VERSION for Linux $ARCH ($FORMATS, channel=${TEXTURECRAFT_BUILD_CHANNEL:-stable})" if [[ "$SKIP_BUILD" = 0 ]]; then (cd "$ROOT" && cargo build --release --locked -p texturecraft -p texturecraft-cli ${CROSS_TARGET:+--target "$CROSS_TARGET"}) @@ -52,9 +73,20 @@ rm -rf "$WORK" # ---- stage an FHS tree (shared by every format) ------------------------------------------------- install -Dm755 "$BIN/texturecraft" "$STAGE/usr/bin/texturecraft" -install -Dm755 "$BIN/texturecraft-cli" "$STAGE/usr/bin/texturecraft-cli" -"${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/texturecraft" "$STAGE/usr/bin/texturecraft-cli" 2>/dev/null || true +"${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/texturecraft" 2>/dev/null || true +# The Nightly formats ship the GUI only (the kit's rule). texturecraft-cli loads its brush presets +# from the host's Documents/TextureCraft, which is Stable's folder (`crates/automation`'s Headless), +# so a Nightly CLI would read and rewrite Stable's brushes. Stable keeps its CLI. +if [[ "$IS_NIGHTLY" = 0 ]]; then + install -Dm755 "$BIN/texturecraft-cli" "$STAGE/usr/bin/texturecraft-cli" + "${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/texturecraft-cli" 2>/dev/null || true +fi 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.texturecraft.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@/$TEXTURECRAFT_BUILD_DATE/g" \ @@ -77,17 +109,91 @@ has() { case " $FORMATS " in *" $1 "*) return 0 ;; *) return 1 ;; esac; } if has tar; then mkdir -p "$WORK/tar" cp -R "$STAGE/usr" "$WORK/tar/$BASENAME" + if [[ "$IS_NIGHTLY" = 1 ]]; then + # A Nightly binary only starts with its private profile, so an unpacked tarball gets the same + # launcher the other Nightly formats install: `texturecraft` starts `texturecraft-bin`. + mv "$WORK/tar/$BASENAME/bin/texturecraft" "$WORK/tar/$BASENAME/bin/texturecraft-bin" + install -Dm755 "$HERE/nightly-launch.sh" "$WORK/tar/$BASENAME/bin/texturecraft" + fi tar -C "$WORK/tar" -czf "$DIST/$BASENAME.tar.gz" "$BASENAME" echo "wrote $DIST/$BASENAME.tar.gz" fi +# The Arch handoff keeps the same basename as the plain tarball in a separate directory. +if [[ -n "$ARCH_TAR_DIR" ]]; then + mkdir -p "$ARCH_TAR_DIR" + if [[ "$(cd "$ARCH_TAR_DIR" && pwd -P)" == "$(cd "$DIST" && pwd -P)" ]]; then + echo "error: the Arch tar directory must differ from the release directory" >&2 + exit 2 + fi + bash "$HERE/nightly-arch-tar.sh" "$STAGE/usr" "$WORK/arch-tar" "$ARCH_TAR_DIR" "$BASENAME" +fi + # ---- .deb / .rpm -------------------------------------------------------------------------------- if has deb || has rpm; then command -v nfpm >/dev/null || { echo "error: nfpm not found (https://nfpm.goreleaser.com/install/)" >&2; exit 1; } export VERSION export NFPM_ARCH="$DEB_ARCH" + NFPM_STAGE="$STAGE" + export NFPM_NAME="texturecraft" + export NFPM_BIN="texturecraft" + export NFPM_CLI="texturecraft-cli" + if [[ "$IS_NIGHTLY" = 1 ]]; then + NIGHTLY_DESK_ID="$APP_ID.nightly-v1" + export NFPM_NAME="texturecraft-nightly" + export NFPM_BIN="texturecraft-nightly" + NFPM_STAGE="$WORK/nfpm-root" + rm -rf "$NFPM_STAGE" + cp -R "$STAGE" "$NFPM_STAGE" + install -Dm755 "$NFPM_STAGE/usr/bin/texturecraft" "$NFPM_STAGE/usr/lib/texturecraft-nightly/texturecraft" + cat >"$NFPM_STAGE/usr/bin/$NFPM_BIN" <<'WRAPPER' +#!/bin/sh +# TextureCraft Nightly: the GUI runs with the Launcher's private profile, which holds every +# per-user file (settings, ui.json, logs, autosaves, materials, layouts, templates, presets). +set -eu +bin=/usr/lib/texturecraft-nightly/texturecraft +profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/TextureCraft-Nightly" +# The Launcher's protocol, and a bare version query, pass through untouched. +case "${1-}" in + --launch-profile | --profile-root | --version | -V) exec "$bin" "$@" ;; +esac +exec "$bin" --launch-profile nightly-v1 --profile-root "$profile" -- "$@" +WRAPPER + chmod 755 "$NFPM_STAGE/usr/bin/$NFPM_BIN" + rm -f "$NFPM_STAGE/usr/bin/texturecraft" + mv "$NFPM_STAGE/usr/share/doc/texturecraft" "$NFPM_STAGE/usr/share/doc/$NFPM_NAME" + sed -e "s#^Exec=texturecraft\([[:space:]]\|$\)#Exec=$NFPM_BIN\1#" \ + -e "s|^TryExec=texturecraft$|TryExec=$NFPM_BIN|" \ + -e "s|^Icon=$APP_ID$|Icon=$NIGHTLY_DESK_ID|" \ + -e "s|^Name=TextureCraft$|Name=TextureCraft Nightly|" \ + -e '/^MimeType=/d' \ + "$NFPM_STAGE/usr/share/applications/$APP_ID.desktop" >"$NFPM_STAGE/usr/share/applications/$NIGHTLY_DESK_ID.desktop" + rm -f "$NFPM_STAGE/usr/share/applications/$APP_ID.desktop" + # The Nightly entry claims no MIME types (stable keeps the associations), so the metainfo must + # not advertise them either. + sed -e "s|$APP_ID|$NIGHTLY_DESK_ID|g" \ + -e "s|TextureCraft|TextureCraft Nightly|g" \ + -e "s|$APP_ID.desktop|$NIGHTLY_DESK_ID.desktop|g" \ + -e "s|$APP_ID|$NIGHTLY_DESK_ID|g" \ + -e "s|texturecraft|$NFPM_BIN|g" \ + -e '//d' \ + "$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" >"$NFPM_STAGE/usr/share/metainfo/$NIGHTLY_DESK_ID.metainfo.xml" + rm -f "$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" + rm -rf "$NFPM_STAGE/usr/share/mime" + rm -rf "$NFPM_STAGE/usr/share/icons/hicolor" + install -Dm644 "$NIGHTLY_ICON" \ + "$NFPM_STAGE/usr/share/icons/hicolor/256x256/apps/$NIGHTLY_DESK_ID.png" + fi # nfpm expands env vars in fields like `version` and `arch`, but not in `contents[].src`. - sed "s|\${STAGE}|$STAGE|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" + DROP_LIB_TREE= + DROP_CLI= + # shellcheck disable=SC2016 + [[ -d "$NFPM_STAGE/usr/lib" ]] || DROP_LIB_TREE='\|^ - src: \${STAGE}/usr/lib/|,+2d;' + # A Nightly package has no CLI, so its file list must not name one either. + # shellcheck disable=SC2016 + [[ "$IS_NIGHTLY" = 0 ]] || DROP_CLI='\|^ - src: \${STAGE}/usr/bin/\${NFPM_CLI}|,+2d;/Includes texturecraft-cli/d;' + # shellcheck disable=SC2016 + sed "${DROP_LIB_TREE}${DROP_CLI}s|\${STAGE}|$NFPM_STAGE|g;s|\${NFPM_BIN}|$NFPM_BIN|g;s|\${NFPM_CLI}|$NFPM_CLI|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" # The riscv64 cross sysroot is Ubuntu 24.04, whose glibc floor is 2.39. if [[ "$ARCH" = riscv64 ]]; then sed -i "s/libc6 (>= 2.35)/libc6 (>= 2.39)/" "$WORK/nfpm.yaml"; fi for fmt in deb rpm; do @@ -105,9 +211,46 @@ if has appimage; then # app_id to our icon instead of the generic Wayland logo (opt-out env in the # script header). Logic is covered by packaging/linux/apprun-test.sh. install -Dm755 "$HERE/AppRun" "$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" + # The desktop id and the channel line: a Nightly AppImage must start the app with the + # Launcher's private profile, not with stable's folders (AppRun's tail does the exec). + awk -v old_id="$APP_ID" -v new_id="$APPIMAGE_ID" ' + $0 == "DESK_ID=" old_id { print "DESK_ID=" new_id; next } + $0 == "CHANNEL=stable" { print "CHANNEL=nightly-v1"; next } + { print } + ' "$APPDIR/AppRun" >"$APPDIR/AppRun.tmp" + grep -qx 'CHANNEL=nightly-v1' "$APPDIR/AppRun.tmp" || { + echo "error: AppRun has no CHANNEL=stable line to switch for Nightly" >&2 + exit 1 + } + mv "$APPDIR/AppRun.tmp" "$APPDIR/AppRun" + chmod 755 "$APPDIR/AppRun" + sed -e "s|^Icon=$APP_ID$|Icon=$APPIMAGE_ID|" \ + -e "s|^Name=TextureCraft$|Name=TextureCraft 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" + # The Nightly desktop entry drops MimeType=, so the metainfo must not advertise the same types + # either: AppStream would otherwise list a type the package cannot open. + sed -e "s|$APP_ID|$APPIMAGE_ID|g" \ + -e "s|TextureCraft|TextureCraft Nightly|g" \ + -e "s|$APP_ID.desktop|$APPIMAGE_ID.desktop|g" \ + -e "s|$APP_ID|$APPIMAGE_ID|g" \ + -e '//d' \ + "$APPDIR/usr/share/metainfo/$APP_ID.metainfo.xml" >"$APPDIR/usr/share/metainfo/$APPIMAGE_ID.metainfo.xml" + rm -f "$APPDIR/usr/share/metainfo/$APP_ID.metainfo.xml" + rm -rf "$APPDIR/usr/share/icons/hicolor" + install -Dm644 "$NIGHTLY_ICON" \ + "$APPDIR/usr/share/icons/hicolor/256x256/apps/$APPIMAGE_ID.png" + cp "$NIGHTLY_ICON" "$APPDIR/$APPIMAGE_ID.png" + ln -s "$APPIMAGE_ID.png" "$APPDIR/.DirIcon" + else + cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop" + cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png" + ln -s "$APP_ID.png" "$APPDIR/.DirIcon" + fi TOOL="${APPIMAGETOOL:-$(command -v appimagetool || true)}" if [[ -z "$TOOL" ]]; then @@ -129,11 +272,24 @@ if has appimage; then # next to 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/texturecraft}" - UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|texturecraft-*-linux-$ARCH.AppImage.zsync" + UPDATE_ARGS=() + if [[ "$IS_NIGHTLY" = 0 ]]; then + UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|texturecraft-*-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 rather than stable `latest`. + if [[ "$VERSION" == *-nightly* ]]; then + UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest-pre|texturecraft-*-nightly*-linux-$ARCH.AppImage.zsync" + else + UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest-pre|texturecraft-*-linux-$ARCH.AppImage.zsync" + fi + 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 -u "$UPDATE_INFO" "$APPDIR" "$OUT") + (cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream "${UPDATE_ARGS[@]}" "$APPDIR" "$OUT") echo "wrote $OUT" if [[ -s "$OUT.zsync" ]]; then echo "wrote $OUT.zsync" @@ -142,10 +298,14 @@ if has appimage; then fi fi +# A Stable tree is checked through its CLI; a Nightly tree has only the GUI, which answers the +# same bare `--version` query (no profile, so nothing is created) with its channel line. +SMOKE_BIN="$STAGE/usr/bin/texturecraft-cli" +if [[ "$IS_NIGHTLY" = 1 ]]; then SMOKE_BIN="$STAGE/usr/bin/texturecraft"; fi if [[ -n "${CROSS_TARGET:-}" ]]; then - if [[ -n "${EMULATOR:-}" ]]; then "$EMULATOR" "$STAGE/usr/bin/texturecraft-cli" --version; fi + if [[ -n "${EMULATOR:-}" ]]; then "$EMULATOR" "$SMOKE_BIN" --version; fi else - "$STAGE/usr/bin/texturecraft-cli" --version + "$SMOKE_BIN" --version fi echo "==> done" ls -lh "$DIST" diff --git a/packaging/macos/nightly-lib.sh b/packaging/macos/nightly-lib.sh new file mode 100644 index 00000000..0bafd63d --- /dev/null +++ b/packaging/macos/nightly-lib.sh @@ -0,0 +1,125 @@ +# 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='TextureCraft Nightly.app' +MAC_NIGHTLY_ID='ai.storyteller.texturecraft.nightly' +MAC_NIGHTLY_EXECUTABLE='TextureCraft' +# nightly.sh copies it into the bundle; the file is linted on its own, without -x, so shellcheck +# cannot see that use. +# shellcheck disable=SC2034 +MAC_NIGHTLY_ICON='texturecraft-nightly' +# The release environment's names, as 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" =~ ^texturecraft-(.+)-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 this app's import-cert.sh made belongs to this run: a regular file (no link) with the +# app's keychain name, inside the run directory. Its script makes its own name under RUNNER_TEMP, so +# the path is read from its printed output rather than assumed. +mac_nightly_keychain_is_ours() { + local keychain="$1" work="$2" + [[ -f "$keychain" && ! -L "$keychain" ]] || return 1 + [[ "$(basename -- "$keychain")" == texturecraft-signing.keychain-db ]] || return 1 + case "$keychain" in "$work"/*) return 0 ;; *) return 1 ;; esac +} + +# 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 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")" == "$MAC_NIGHTLY_EXECUTABLE" ]] || mac_nightly_die 'Contents/MacOS must hold only the GUI executable (no CLI)' + [[ -f "$app/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE" && -x "$app/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE" ]] || mac_nightly_die 'missing executable GUI' + [[ "$(lipo -archs "$app/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE")" == arm64 ]] || mac_nightly_die 'the GUI must be thin arm64' + plist="$app/Contents/Info.plist" + for key in CFBundleIdentifier CFBundleExecutable TextureCraftVersion; 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" == "$MAC_NIGHTLY_EXECUTABLE" ]] ;; + TextureCraftVersion) [[ "$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 the 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 00000000..9ecc91b2 --- /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/texturecraft--macos-aarch64-nightly.zip \ +# --output /abs//texturecraft--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%/}/texturecraft-nightly-sign.XXXXXX")" +KEYCHAIN="$WORK/texturecraft-signing.keychain-db" +cleanup() { + if [[ -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 did not create this run keychain' +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 "==> TextureCraft 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 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 the 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/$MAC_NIGHTLY_EXECUTABLE" +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 lookup can lag a few seconds behind notarytool 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 00000000..07d968be --- /dev/null +++ b/packaging/macos/nightly-verify.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +# Check an Apple-silicon Nightly archive as the Launcher unpacks it, then ask the GUI its version. +# For a job without signing material (it refuses to run with any), after nightly-sign.sh: +# +# nightly-verify.sh --input /abs/texturecraft--macos-aarch64-nightly.zip --expect signed [--team ID] +# nightly-verify.sh --input /abs/texturecraft--macos-aarch64-nightly.zip --expect unsigned +# +# Both: the archive holds only the GUI-only Nightly bundle with the exact TextureCraftVersion, 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 compile output, e.g. pull-request CI) checks no signature. +# Last, the GUI answers its version query with an empty environment, both plainly and in the +# Launcher form `--launch-profile nightly-v1 --profile-root --version` (the shared producer +# smoke): each must exit 0 within 15 seconds, print exactly `TextureCraft (nightly-v1)` and +# write nothing to standard error. +set -euo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=nightly-lib.sh +. "$HERE/nightly-lib.sh" + +INPUT='' EXPECT='' TEAM="${NIGHTLY_APPLE_TEAM_ID:-}" +while [[ $# -gt 0 ]]; do + case "$1" in + --input | --expect | --team) + [[ $# -ge 2 ]] || mac_nightly_die "missing $1 value" + case "$1" in --input) INPUT="$2" ;; --expect) EXPECT="$2" ;; --team) TEAM="$2" ;; esac + shift 2 ;; + -h | --help) sed -n '2,15p' "$0"; exit 0 ;; + *) mac_nightly_die "unsupported argument: $1" ;; + esac +done +for name in "${MAC_NIGHTLY_SECRETS[@]}" MACOS_SIGN_IDENTITY MACOS_KEYCHAIN; do + [[ -z "${!name:-}" ]] || mac_nightly_die "refusing to run the payload with signing material in the environment ($name)" +done +[[ "$EXPECT" == signed || "$EXPECT" == unsigned ]] || mac_nightly_die '--expect must be signed or unsigned' +[[ "$EXPECT" == unsigned || "$TEAM" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'a signed check needs the Apple team ID (--team or NIGHTLY_APPLE_TEAM_ID)' +[[ "$INPUT" == /* && -f "$INPUT" && ! -L "$INPUT" ]] || mac_nightly_die '--input must be an absolute regular file' +VERSION="$(mac_nightly_version_from_asset "$(basename -- "$INPUT")")" || mac_nightly_die 'the input is not a prepared Nightly archive name' +[[ "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] || mac_nightly_die 'needs an Apple silicon Mac' + +WORK="$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/texturecraft-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 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/$MAC_NIGHTLY_EXECUTABLE" "$@" 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" == "TextureCraft $VERSION (nightly-v1)" ]] || mac_nightly_die "the version query ($*) reports '$out', not TextureCraft $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): TextureCraft $VERSION (nightly-v1), plain and in the Launcher profile form" diff --git a/packaging/macos/nightly.sh b/packaging/macos/nightly.sh new file mode 100755 index 00000000..4140e45a --- /dev/null +++ b/packaging/macos/nightly.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# App-owned GUI-only Nightly for Apple silicon, compile step only (no signing material): +# +# $DIST/texturecraft--macos-aarch64-nightly.zip TextureCraft Nightly.app, unsigned +# +# Usage: packaging/macos/nightly.sh --arch aarch64 +# +# Required env (nightly-common.sh): TEXTURECRAFT_BUILD_CHANNEL=nightly-v1, TEXTURECRAFT_VERSION, +# TEXTURECRAFT_BUILD_SHA, TEXTURECRAFT_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)" +# shellcheck source=../nightly-common.sh +. "$HERE/../nightly-common.sh" +# shellcheck source=nightly-lib.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/texturecraft-$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/$MAC_NIGHTLY_EXECUTABLE" +chmod 755 "$APP/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE" +cp "$ROOT/assets/app-icon/$MAC_NIGHTLY_ICON.icns" "$APP/Contents/Resources/$MAC_NIGHTLY_ICON.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 "$TEXTURECRAFT_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 100644 index 00000000..63a2e369 --- /dev/null +++ b/packaging/macos/nightly_plist.py @@ -0,0 +1,70 @@ +#!/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.texturecraft.nightly" +# Stable's own document, mesh and project declarations: a Nightly install registers no associations. +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="TextureCraft Nightly", + CFBundleName="TextureCraft Nightly", + CFBundleIdentifier=IDENTIFIER, + CFBundleExecutable="TextureCraft", + CFBundleIconFile="texturecraft-nightly", + CFBundleShortVersionString=match[1], + CFBundleVersion=match[1], + TextureCraftVersion=version, + TextureCraftBuildCommit=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 100644 index 00000000..1662c607 --- /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("texturecraft_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.texturecraft.nightly") + self.assertEqual(rendered["CFBundleExecutable"], "TextureCraft") + self.assertEqual(rendered["TextureCraftVersion"], VERSION) + self.assertEqual(rendered["TextureCraftBuildCommit"], COMMIT) + self.assertTrue(VERSION.startswith(rendered["CFBundleVersion"] + "-nightly.")) + for key in ("LSMinimumSystemVersion", "LSApplicationCategoryType", "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["TextureCraftVersion"], VERSION) + self.assertEqual(result["TextureCraftBuildCommit"], 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())["TextureCraftVersion"], 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 100644 index 00000000..f0a2eddc --- /dev/null +++ b/packaging/macos/nightly_sign_tests.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""The Nightly signing and archive helpers, exercised on Linux with stand-in Apple tool output. + +Nothing here signs, notarizes, unpacks or runs a payload: each helper takes the tool output (or a +crafted archive) as an argument, which is why packaging/macos/nightly_sign_tests.py can run in the +app's ordinary Linux CI. +""" +import os +import stat +import subprocess +import tempfile +import unittest +import zipfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +LIB = HERE / "nightly-lib.sh" +APP = "TextureCraft Nightly.app" +IDENTITY = "A" * 40 +TEAM = "DJ6XS33FX8" +APP_CONFIG_ID = "ai.storyteller.texturecraft.nightly" + + + +class VersionFromAsset(unittest.TestCase): + def check(self, name): + """True when the helper accepts the asset name.""" + result = subprocess.run( + ["bash", "-c", '. "$LIB"; mac_nightly_version_from_asset "$1"', "bash", name], + capture_output=True, text=True, env={"PATH": os.environ["PATH"], "LIB": str(LIB)}, + ) + return result.returncode == 0 + + def test_accepts_only_the_prepared_nightly_archive_name(self): + version = "0.24.0-nightly.20261124.7.2.g" + "0123456789ab" + self.assertTrue(self.check(f"texturecraft-{version}-macos-aarch64-nightly.zip")) + for name in [ + f"texturecraft-{version}-macos-aarch64.zip", + f"texturecraft-{version}-linux-x86_64-nightly.tar.gz", + f"texturecraft-0.24.0-macos-aarch64-nightly.zip", + f"texturecraft-{version.upper()}-macos-aarch64-nightly.zip", + f"photocraft-{version}-macos-aarch64-nightly.zip", + f"texturecraft-{version}-macos-x86_64-nightly.zip", + f"texturecraft-{version}-macos-aarch64-nightly.zip.sig", + ]: + self.assertFalse(self.check(name), name) + + +class Keychain(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.work = Path(self.directory.name).resolve() + self.keychain = self.work / "texturecraft-signing.keychain-db" + self.keychain.write_bytes(b"stand-in keychain") + + def ours(self, keychain, work=None): + result = subprocess.run( + ["bash", "-c", '. "$LIB"; mac_nightly_keychain_is_ours "$1" "$2"', "bash", str(keychain), str(work or self.work)], + capture_output=True, text=True, env={"PATH": os.environ["PATH"], "LIB": str(LIB)}, + ) + return result.returncode == 0 + + def test_only_this_runs_own_keychain_counts(self): + self.assertTrue(self.ours(self.keychain)) + # import-cert.sh may put it in a private directory of its own under the run. + nested = self.work / "private" + nested.mkdir() + self.assertFalse(self.ours(nested / "texturecraft-signing.keychain-db"), "a missing file is not ours") + (nested / "texturecraft-signing.keychain-db").write_bytes(b"x") + self.assertTrue(self.ours(nested / "texturecraft-signing.keychain-db")) + self.assertFalse(self.ours(self.work / "other.keychain-db")) + with tempfile.TemporaryDirectory() as outside: + (Path(outside) / "texturecraft-signing.keychain-db").write_bytes(b"x") + self.assertFalse(self.ours(Path(outside) / "texturecraft-signing.keychain-db")) + alias = self.work / "texturecraft-signing.keychain-db-alias" + alias.symlink_to(self.keychain) + self.assertFalse(self.ours(alias)) + + +class Identity(unittest.TestCase): + LINE = f' 1) {IDENTITY} "Developer ID Application: Learning Machines Inc ({TEAM})"' + + def matcher(self, line, identity=IDENTITY, team=TEAM): + result = subprocess.run( + ["bash", "-c", '. "$LIB"; mac_nightly_identity_is_team "$1" "$2" "$3"', "bash", line, identity, team], + capture_output=True, text=True, env={"PATH": os.environ["PATH"], "LIB": str(LIB)}, + ) + return result.returncode == 0 + + def test_a_developer_id_of_the_team_and_nothing_else(self): + self.assertTrue(self.matcher(self.LINE)) + self.assertFalse(self.matcher(self.LINE.replace("Developer ID Application", "Apple Development"))) + self.assertFalse(self.matcher(self.LINE.replace(TEAM, "ZZZZZZZZZZ"))) + self.assertFalse(self.matcher(self.LINE, identity="B" * 40)) + self.assertFalse(self.matcher("")) + + +class Signature(unittest.TestCase): + DETAILS = "\n".join([ + f"Identifier={APP_CONFIG_ID}", + "Authority=Developer ID Application: Learning Machines Inc (DJ6XS33FX8)", + "Authority=Developer ID Certification Authority", + f"TeamIdentifier={TEAM}", + "Timestamp=Nov 24, 2026 at 10:00:00", + "CodeDirectory v=20500 size=1234 flags=0x10000(runtime) hashes=1+7 location=embedded", + ]) + + def check(self, details, team=TEAM): + result = subprocess.run( + ["bash", "-c", '. "$LIB"; mac_nightly_check_signature "$1" "$2"', "bash", details, team], + capture_output=True, text=True, env={"PATH": os.environ["PATH"], "LIB": str(LIB)}, + ) + return result.returncode == 0 + + def test_the_required_developer_id_signature(self): + self.assertTrue(self.check(self.DETAILS)) + for missing in [ + "Timestamp=Nov 24, 2026 at 10:00:00", + f"TeamIdentifier={TEAM}", + "Authority=Developer ID Application: Learning Machines Inc (DJ6XS33FX8)", + ]: + self.assertFalse(self.check(self.DETAILS.replace(missing, "")), missing) + self.assertFalse(self.check(self.DETAILS.replace("flags=0x10000(runtime)", "flags=0x0(none)"))) + self.assertFalse(self.check(self.DETAILS, team="ZZZZZZZZZZ")) + self.assertFalse(self.check(self.DETAILS.replace(APP_CONFIG_ID, "ai.storyteller.texturecraft"))) + + +class Assessment(unittest.TestCase): + def check(self, text): + result = subprocess.run( + ["bash", "-c", '. "$LIB"; mac_nightly_check_assessment "$1"', "bash", text], + capture_output=True, text=True, env={"PATH": os.environ["PATH"], "LIB": str(LIB)}, + ) + return result.returncode == 0 + + def test_gatekeeper_must_report_a_notarized_developer_id(self): + self.assertTrue(self.check(f"{APP}: accepted\nsource=Notarized Developer ID")) + self.assertFalse(self.check(f"{APP}: accepted\nsource=Unnotarized Developer ID")) + self.assertFalse(self.check(f"{APP}: rejected\nsource=Notarized Developer ID")) + self.assertFalse(self.check("")) + + +class ZipEntries(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name) + + def checked(self, entries): + """True when mac_nightly_check_zip_entries accepts the archive of (name, mode) entries.""" + archive = self.root / "test.zip" + with zipfile.ZipFile(archive, "w") as z: + for name, mode in entries: + info = zipfile.ZipInfo(name) + info.external_attr = (mode or stat.S_IFREG | 0o644) << 16 if mode else 0 + z.writestr(info, b"stand-in payload") + result = subprocess.run( + ["bash", "-c", '. "$LIB"; mac_nightly_check_zip_entries "$1"', "bash", str(archive)], + capture_output=True, text=True, env={"PATH": os.environ["PATH"], "LIB": str(LIB), "MAC_NIGHTLY_APP": APP}, + ) + return result.returncode == 0 + + def test_a_plain_bundle_is_accepted_and_anything_else_refused(self): + good = [ + (f"{APP}/", stat.S_IFDIR | 0o755), + (f"{APP}/Contents/Info.plist", stat.S_IFREG | 0o644), + (f"{APP}/Contents/MacOS/TextureCraft", stat.S_IFREG | 0o755), + ] + self.assertTrue(self.checked(good)) + for entry in [ + (f"{APP}/../escape", stat.S_IFREG | 0o644), + ("/absolute/path", stat.S_IFREG | 0o644), + (f"{APP}/Contents/link", stat.S_IFLNK | 0o777), + ("Other.app/Contents/Info.plist", stat.S_IFREG | 0o644), + (f"{APP}/Contents/with\\backslash", stat.S_IFREG | 0o644), + ]: + self.assertFalse(self.checked([*good, entry]), entry[0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/nightly-archive-tests.py b/packaging/nightly-archive-tests.py new file mode 100755 index 00000000..e917ce8d --- /dev/null +++ b/packaging/nightly-archive-tests.py @@ -0,0 +1,234 @@ +#!/usr/bin/env python3 +"""Synthetic app-owned archive/output tests; no native build or executable launch.""" +import gzip +import importlib.util +import os +import runpy +import sys +from unittest import mock +from pathlib import Path +import subprocess +import tarfile +import tempfile +import unittest + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("photo_nightly_archive", HERE / "nightly-archive.py") +ARCHIVE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(ARCHIVE) + + +class ArchivePolicy(unittest.TestCase): + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.root = Path(self.scratch.name).resolve() + previous = Path.cwd() + os.chdir(self.root) + self.addCleanup(os.chdir, previous) + self.stage = self.root / "stage" + self.stage.mkdir() + self.output = self.root / "nightly.tar.gz" + self.required = {"texturecraft", "texturecraft-bin", "texturecraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md"} + for name in self.required: + (self.stage / name).write_bytes(b"generated fixture: " + name.encode()) + (self.stage / "texturecraft").chmod(0o755) + (self.stage / "texturecraft-bin").chmod(0o755) + + def test_flat_regular_ustar_with_all_notices(self): + (self.stage / "OFL-Font.txt").write_text("generated fixture license", encoding="utf-8") + ARCHIVE.linux_archive(self.stage, self.output) + with tarfile.open(self.output) as archive: + self.assertEqual({m.name for m in archive}, self.required | {"OFL-Font.txt"}) + self.assertTrue(all(m.isfile() and not m.pax_headers for m in archive)) + self.assertEqual(archive.extractfile("texturecraft").read(), (self.stage / "texturecraft").read_bytes()) + # The launcher is what a user runs; the GUI beside it must be runnable too. + modes = {member.name: member.mode for member in archive.getmembers()} + for name in ("texturecraft", "texturecraft-bin"): + self.assertEqual(modes[name] & 0o111, 0o111, f"{name} must be executable") + with gzip.open(self.output, "rb") as stream: + while (header := stream.read(512)) != bytes(512): + self.assertEqual(len(header), 512) + self.assertIn(header[156:157], {b"0", b"\0"}) + self.assertEqual(header[257:263], b"ustar\0") + size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8) + stream.read(((size + 511) // 512) * 512) + + def test_each_required_member_is_required_before_output(self): + for name in self.required: + with self.subTest(name=name): + content = (self.stage / name).read_bytes() + (self.stage / name).unlink() + with self.assertRaisesRegex(ValueError, "required"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + (self.stage / name).write_bytes(content) + + def test_unexpected_cli_portable_or_installer_member_refuses(self): + for name in ["texturecraft-cli", "portable.txt", "texturecraft.desktop"]: + with self.subTest(name=name): + bad = self.stage / name + bad.write_bytes(b"generated fixture") + with self.assertRaisesRegex(ValueError, "unexpected"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + bad.unlink() + + def test_symlink_refuses_before_output(self): + icon = self.stage / "texturecraft-nightly.png" + icon.unlink() + icon.symlink_to(self.stage / "README.md") + with self.assertRaisesRegex(ValueError, "regular file|symlinks or aliases"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_directory_refuses_before_output(self): + icon = self.stage / "texturecraft-nightly.png" + icon.unlink() + icon.mkdir() + with self.assertRaisesRegex(ValueError, "regular file"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_long_notice_refuses_before_output(self): + (self.stage / ("OFL-" + "x" * 100 + ".txt")).write_bytes(b"fixture") + with self.assertRaisesRegex(ValueError, "short regular"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_case_colliding_notices_refuse_before_output(self): + for name in ["OFL-Font.txt", "OFL-font.txt"]: + (self.stage / name).write_bytes(b"fixture") + with self.assertRaisesRegex(ValueError, "case-colliding"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_cli_dispatches_only_the_supported_archive_kind(self): + helper = HERE / "nightly-archive.py" + with mock.patch.object(sys, "argv", [str(helper), "linux", str(self.stage), str(self.output)]): + runpy.run_path(str(helper), run_name="__main__") + with tarfile.open(self.output) as archive: + self.assertEqual({member.name for member in archive}, self.required) + refused = self.root / "refused.tar.gz" + for args in ([str(helper)], [str(helper), "unknown", str(self.stage), str(refused)]): + with self.subTest(args=args), mock.patch.object(sys, "argv", args): + with self.assertRaises(SystemExit): + runpy.run_path(str(helper), run_name="__main__") + self.assertFalse(refused.exists()) + + def test_existing_archive_is_unchanged(self): + self.output.write_bytes(b"owned earlier artifact") + with self.assertRaises(FileExistsError): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertEqual(self.output.read_bytes(), b"owned earlier artifact") + + + def test_archive_output_outside_build_root_refuses(self): + with tempfile.TemporaryDirectory() as external: + output = Path(external) / "nightly.tar.gz" + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, output) + self.assertFalse(output.exists()) + + def test_archive_stage_outside_build_root_refuses(self): + with tempfile.TemporaryDirectory() as external: + stage = Path(external) + for name in self.required: + (stage / name).write_bytes(b"generated external fixture") + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(stage, self.output) + self.assertFalse(self.output.exists()) + + def test_archive_stage_alias_refuses(self): + alias = self.root / "stage-alias" + alias.symlink_to(self.stage, target_is_directory=True) + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(alias, self.output) + self.assertFalse(self.output.exists()) + + def test_archive_output_parent_alias_refuses(self): + with tempfile.TemporaryDirectory() as external: + alias = self.root / "output-alias" + alias.symlink_to(external, target_is_directory=True) + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, alias / "nightly.tar.gz") + self.assertFalse((Path(external) / "nightly.tar.gz").exists()) + + def test_archive_parent_traversal_refuses(self): + with tempfile.TemporaryDirectory(dir=self.root.parent) as external: + output = Path("..") / Path(external).name / "nightly.tar.gz" + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, output) + self.assertFalse((Path(external) / "nightly.tar.gz").exists()) + + def test_nonflat_member_name_refuses(self): + stage_root = os.path.realpath(self.stage) + with open(self.stage / "README.md", "rb") as incoming: + for bad in ("../escape", "/absolute", "nested/name", "x/../README.md", "", ".", ".."): + with self.subTest(name=bad), self.assertRaises(ValueError): + ARCHIVE.member_info(stage_root, bad, incoming) + + def test_member_header_matches_what_gettarinfo_records(self): + stage_root = os.path.realpath(self.stage) + for name in sorted(self.required): + with self.subTest(name=name), open(self.stage / name, "rb") as incoming: + ours = ARCHIVE.member_info(stage_root, name, incoming) + with tarfile.open(fileobj=__import__("io").BytesIO(), mode="w") as reference: + theirs = reference.gettarinfo(fileobj=incoming, arcname=name) + self.assertEqual(ours.get_info(), theirs.get_info()) + + def test_member_read_budget_refuses_before_output(self): + (self.stage / "OFL-Large.txt").write_bytes(b"x" * 65) + with mock.patch.object(ARCHIVE, "MAX_MEMBER_BYTES", 64, create=True): + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + + def test_member_growth_is_rechecked_before_copy_and_output_is_cleaned(self): + growing = self.stage / "OFL-Growing.txt" + growing.write_bytes(b"x" * 32) + original = ARCHIVE.member_info + + def grow_before_stat(stage_root, name, incoming): + if name == growing.name: + growing.write_bytes(b"x" * 65) + return original(stage_root, name, incoming) + + with mock.patch.object(ARCHIVE, "MAX_MEMBER_BYTES", 64), \ + mock.patch.object(ARCHIVE, "member_info", grow_before_stat): + with self.assertRaises(ValueError): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + +class ExclusiveOutput(unittest.TestCase): + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.root = Path(self.scratch.name) + self.source = self.root / "input archive" + self.output = self.root / "final archive" + self.source.write_bytes(b"generated archive fixture" * 1024) + + def publish(self): + return subprocess.run(["bash", "-c", 'set -euo pipefail; source "$1"; nightly_publish_archive "$2" "$3"', "test", str(HERE / "nightly-common.sh"), str(self.source), str(self.output)], capture_output=True, text=True, timeout=15) + + def test_success_copies_exact_bytes(self): + result = self.publish() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.output.read_bytes(), self.source.read_bytes()) + + def test_existing_output_is_never_replaced(self): + self.output.write_bytes(b"existing artifact") + self.assertNotEqual(self.publish().returncode, 0) + self.assertEqual(self.output.read_bytes(), b"existing artifact") + + def test_missing_source_does_not_leave_a_fake_empty_artifact(self): + self.source.unlink() + self.assertNotEqual(self.publish().returncode, 0) + self.assertFalse(self.output.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/nightly-archive.py b/packaging/nightly-archive.py new file mode 100644 index 00000000..b4b380ac --- /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 {"texturecraft", "texturecraft-bin", "texturecraft-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 = {"texturecraft", "texturecraft-bin", "texturecraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md"} + if not required.issubset({item.name for item in entries}): + raise ValueError("required GUI/icon/notices missing") + return entries + + +def member_info(stage_root, name, incoming): + """Header for one stage file, built from the file this run opened rather than from the archive. + + Members are flat names that resolve directly inside the stage they came from. + """ + if os.path.isabs(name) or os.path.basename(name) != name or name in ("", ".", ".."): + raise ValueError(f"nightly member name must be a flat file name: {name}") + destination = os.path.realpath(os.path.join(stage_root, name)) + if not destination.startswith(stage_root + os.sep) or os.path.dirname(destination) != stage_root: + raise ValueError(f"nightly member resolves outside its stage: {name}") + status = os.fstat(incoming.fileno()) + if not stat.S_ISREG(status.st_mode): + raise ValueError(f"nightly member must be a regular file: {name}") + # The same fields TarFile.gettarinfo records for a regular file. + 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-checks.sh b/packaging/nightly-checks.sh new file mode 100755 index 00000000..33c39b8f --- /dev/null +++ b/packaging/nightly-checks.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# The Nightly checks that need no compiler, macOS or network: the synthetic suites (release +# contracts, the macOS plist and signing helpers, the icons), the launcher tests, and `bash -n` +# over every Nightly shell script. Run by .github/workflows/packaging-lint.yml. +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "$HERE/.." && pwd)" +cd "$ROOT" + +python3 packaging/nightly-tests.py +bash packaging/linux/nightly-arch-tar-test.sh +bash packaging/linux/nightly-launch-test.sh + +for script in \ + packaging/nightly-common.sh \ + packaging/linux/nightly.sh \ + packaging/linux/nightly-launch.sh \ + packaging/linux/nightly-launch-test.sh \ + packaging/linux/nightly-arch-launch.sh \ + packaging/linux/nightly-arch-tar.sh \ + packaging/linux/nightly-arch-tar-test.sh \ + packaging/linux/package.sh \ + packaging/linux/flatpak-bundle.sh \ + packaging/linux/apprun-test.sh \ + packaging/macos/nightly.sh \ + packaging/macos/nightly-lib.sh \ + packaging/macos/nightly-sign.sh \ + packaging/macos/nightly-verify.sh; do + bash -n "$script" +done + +echo "Nightly checks passed" diff --git a/packaging/nightly-common.sh b/packaging/nightly-common.sh new file mode 100644 index 00000000..be77cca2 --- /dev/null +++ b/packaging/nightly-common.sh @@ -0,0 +1,93 @@ +# 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 + [[ "${TEXTURECRAFT_BUILD_CHANNEL:-}" == nightly-v1 ]] || nightly_die 'TEXTURECRAFT_BUILD_CHANNEL must be nightly-v1' + [[ "${TEXTURECRAFT_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' + [[ "${TEXTURECRAFT_BUILD_SHA:-}" =~ ^[0-9a-f]{40}$ ]] || nightly_die 'an exact source commit is required' + [[ "${TEXTURECRAFT_VERSION##*.g}" == "${TEXTURECRAFT_BUILD_SHA:0:12}" ]] || nightly_die 'version/source commit mismatch' + [[ "${TEXTURECRAFT_BUILD_DATE:-}" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || nightly_die 'the original run-created UTC date is required' + date_digits="${TEXTURECRAFT_VERSION#*-nightly.}" + date_digits="${date_digits%%.*}" + [[ "${TEXTURECRAFT_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)" == "$TEXTURECRAFT_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" && TEXTURECRAFT_OVERRIDE_VERSION="$VERSION" cargo build --release --locked -p texturecraft --target "$NIGHTLY_RUST_TARGET") + NIGHTLY_GUI="$CARGO_TARGET_DIR/$NIGHTLY_RUST_TARGET/release/texturecraft" + [[ -f "$NIGHTLY_GUI" && ! -L "$NIGHTLY_GUI" ]] || nightly_die 'the owned GUI build did not produce a regular executable' + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$TEXTURECRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the build' +} + +nightly_build_gui() { + nightly_compile_gui + local actual + actual="$("$NIGHTLY_GUI" --version)" || nightly_die 'side-effect-free nightly version verification failed' + # Exactly what the flavor prints: the prepared version and its channel (build_flavor::version). + [[ "$actual" == "TextureCraft $VERSION (nightly-v1)" ]] || nightly_die "the built binary reports '$actual', not TextureCraft $VERSION (nightly-v1)" + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$TEXTURECRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the version query' +} + +# Signing material never reaches compilation (the Windows -CheckBuildEnvironment rule). +nightly_refuse_signing_env() { + local name + # The signing names release.yml passes, for every platform, and import-cert.sh's outputs. + for name in APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID \ + MACOS_SIGN_IDENTITY MACOS_KEYCHAIN WINDOWS_CERTIFICATE WINDOWS_CERTIFICATE_PASSWORD AZURE_TENANT_ID AZURE_CLIENT_ID \ + AZURE_CLIENT_SECRET AZURE_SIGNING_ENDPOINT AZURE_SIGNING_ACCOUNT AZURE_CERT_PROFILE LINUX_SIGNING_KEY; do + [[ -z "${!name:-}" ]] || nightly_die "compilation must not receive signing configuration ($name); sign in the separate trusted step" + done +} + +nightly_copy_notices() { + local destination="$1" required + for required in README.md LICENSE-MIT LICENSE-APACHE NOTICE ATTRIBUTION.md; do + [[ -f "$ROOT/$required" && ! -L "$ROOT/$required" ]] || nightly_die "missing regular app notice: $required" + done + copy_docs "$destination" +} + +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.py b/packaging/nightly-icons.py new file mode 100755 index 00000000..1643e8c4 --- /dev/null +++ b/packaging/nightly-icons.py @@ -0,0 +1,297 @@ +#!/usr/bin/env python3 +"""Derive TextureCraft's Nightly icons from the committed stable renders. + +The Nightly icon is the same artwork on a deeper background — no badge, crescent or letter. Each +pixel is fitted as a blend of the tile's background and one of the two engraved foregrounds (ink, +paper); only the background's contribution is replaced, so the engraving and the alpha padding are +untouched. Every frame comes from the committed stable master of its own size (the `.ico` and +`.icns` frames, the hicolor PNGs and the 1024 master), never from an upscale. + + packaging/nightly-icons.py # write the Nightly assets + packaging/nightly-icons.py --check # fail if the committed Nightly assets differ + +No third-party packages: zlib and struct only, as the build server has no Pillow or ImageMagick. +""" +import argparse +import hashlib +import io +import json +from pathlib import Path +import struct +import sys +import zlib + +ROOT = Path(__file__).resolve().parent.parent +ICONS = ROOT / "assets" / "app-icon" +STABLE_ID = "ai.storyteller.texturecraft" + +# The palette the artwork is drawn in, read from the tile itself (the three colours it is made of). +INK = (11, 11, 12) +PAPER = (239, 233, 220) +STABLE_BG = (194, 103, 43) +NIGHTLY_BG = (100, 52, 24) + +# How far a pixel may sit from the fitted blend before it is left alone (anti-aliased edges onto the +# transparent margin, and the few pixels that shade the tile itself). +RESIDUAL = 24 +PNG_MAGIC = b"\x89PNG\r\n\x1a\n" + +# Sizes the Nightly set carries (the 256 one is also the window and package icon). They live in +# `assets/app-icon/nightly/`, not in `hicolor/`: Stable's Linux and FreeBSD packagers copy that +# whole theme tree, so Nightly renders stored under it would ship in every Stable package. +NIGHTLY_SIZES = (16, 24, 32, 48, 64, 128, 256, 512) + + +def decode_png(data): + """(width, height, RGBA bytes) for an 8-bit RGB/RGBA PNG, filters included.""" + if data[:8] != PNG_MAGIC: + raise ValueError("not a PNG") + pos, idat, header = 8, [], None + while pos < len(data): + (length,) = struct.unpack(">I", data[pos:pos + 4]) + kind = data[pos + 4:pos + 8] + body = data[pos + 8:pos + 8 + length] + if kind == b"IHDR": + header = struct.unpack(">IIBBBBB", body) + elif kind == b"IDAT": + idat.append(body) + elif kind == b"IEND": + break + pos += 12 + length + if header is None: + raise ValueError("no IHDR") + width, height, depth, color, _compression, _filter, interlace = header + if depth != 8 or interlace != 0 or color not in (2, 6): + raise ValueError(f"unsupported PNG (depth {depth}, color {color}, interlace {interlace})") + channels = 3 if color == 2 else 4 + raw = zlib.decompress(b"".join(idat)) + stride = width * channels + out = bytearray(width * height * 4) + previous = bytearray(stride) + position = 0 + for row in range(height): + filter_type = raw[position] + position += 1 + line = bytearray(raw[position:position + stride]) + position += stride + if filter_type == 1: + for i in range(channels, stride): + line[i] = (line[i] + line[i - channels]) & 0xFF + elif filter_type == 2: + for i in range(stride): + line[i] = (line[i] + previous[i]) & 0xFF + elif filter_type == 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_type == 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 + pa, pb, pc = abs(b - c), abs(a - c), abs(a + b - 2 * c) + predictor = a if (pa <= pb and pa <= pc) else (b if pb <= pc else c) + line[i] = (line[i] + predictor) & 0xFF + elif filter_type != 0: + raise ValueError(f"unknown PNG filter {filter_type}") + if channels == 4: + out[row * width * 4:(row + 1) * width * 4] = line + else: + for x in range(width): + source = x * 3 + target = (row * width + x) * 4 + out[target:target + 3] = line[source:source + 3] + out[target + 3] = 255 + previous = line + return width, height, out + + +def encode_png(width, height, rgba): + raw = bytearray() + stride = width * 4 + for row in range(height): + raw.append(0) + raw.extend(rgba[row * stride:(row + 1) * stride]) + + def chunk(kind, body): + return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body) & 0xFFFFFFFF) + + return ( + PNG_MAGIC + + 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 solve(pixel): + """(ink, paper, background) weights for one pixel, clamped to the three-colour simplex. + + The engraving is drawn as a mix of ink and paper over the tile, so a shaded grey is ink plus + paper with no background at all; only the background share moves in a Nightly icon. + """ + rows = [[INK[c] - STABLE_BG[c] for c in range(3)], [PAPER[c] - STABLE_BG[c] for c in range(3)]] + rhs = [pixel[c] - STABLE_BG[c] for c in range(3)] + a11 = sum(v * v for v in rows[0]) + a12 = sum(rows[0][c] * rows[1][c] for c in range(3)) + a22 = sum(v * v for v in rows[1]) + b1 = sum(rows[0][c] * rhs[c] for c in range(3)) + b2 = sum(rows[1][c] * rhs[c] for c in range(3)) + determinant = a11 * a22 - a12 * a12 + if determinant == 0: + return 0.0, 0.0, 1.0 + ink = (b1 * a22 - b2 * a12) / determinant + paper = (b2 * a11 - b1 * a12) / determinant + ink, paper = max(0.0, min(1.0, ink)), max(0.0, min(1.0, paper)) + if ink + paper > 1.0: + total = ink + paper + ink, paper = ink / total, paper / total + return ink, paper, 1.0 - ink - paper + + +def recolour(rgba): + """The same frame with only its background contribution moved to the Nightly colour.""" + out = bytearray(rgba) + cache = {} + for index in range(0, len(rgba), 4): + if rgba[index + 3] == 0: + continue + pixel = (rgba[index], rgba[index + 1], rgba[index + 2]) + got = cache.get(pixel) + if got is None: + ink, paper, background = solve(pixel) + fitted = tuple(ink * INK[c] + paper * PAPER[c] + background * STABLE_BG[c] for c in range(3)) + residual = sum(abs(pixel[c] - fitted[c]) for c in range(3)) + # A pixel the three-colour palette cannot explain is left exactly as it is. + if residual <= RESIDUAL: + got = bytes(min(255, max(0, round(ink * INK[c] + paper * PAPER[c] + background * NIGHTLY_BG[c]))) for c in range(3)) + else: + got = bytes(pixel) + cache[pixel] = got + out[index:index + 3] = got + return out + + +def read_icon_frames(container): + """(kind, name, png_bytes) frames of an .ico or .icns file, in file order.""" + if container[:4] == b"icns": + frames = [] + position = 8 + while position < len(container): + kind = container[position:position + 4] + (size,) = struct.unpack(">I", container[position + 4:position + 8]) + body = container[position + 8:position + size] + if body[:8] != PNG_MAGIC: + raise ValueError(f"{kind!r} is not a PNG frame; regenerate the stable .icns") + frames.append(("icns", kind, body)) + position += size + return frames + reserved, kind, count = struct.unpack("I", len(png) + 8) + png) + return b"icns" + struct.pack(">I", len(body) + 8) + bytes(body) + + +def nightly_frames(container): + frames = read_icon_frames(container) + out = [] + for kind, name, png in frames: + width, height, rgba = decode_png(png) + out.append((kind, name, (width, height), encode_png(width, height, recolour(rgba)))) + return out + + +def targets(): + """Every Nightly asset the app and its packaging use, as (path, bytes).""" + assets = [] + icon_frames = nightly_frames((ICONS / "texturecraft.icns").read_bytes()) + assets.append((ICONS / "texturecraft-nightly.icns", write_icns([(name, png) for _kind, name, _size, png in icon_frames]))) + ico_frames = nightly_frames((ICONS / "texturecraft.ico").read_bytes()) + assets.append((ICONS / "texturecraft-nightly.ico", write_ico([(size, png) for _kind, _name, size, png in ico_frames]))) + for size in NIGHTLY_SIZES: + source = ICONS / "hicolor" / f"{size}x{size}" / "apps" / f"{STABLE_ID}.png" + width, height, rgba = decode_png(source.read_bytes()) + assets.append((ICONS / "nightly" / f"{size}.png", encode_png(width, height, recolour(rgba)))) + width, height, rgba = decode_png((ICONS / "texturecraft-1024.png").read_bytes()) + assets.append((ICONS / "texturecraft-nightly-1024.png", encode_png(width, height, recolour(rgba)))) + # The window icon is the same 256 render the Nightly set carries. + window = ICONS / "nightly" / "256.png" + assets.append((ICONS / "texturecraft-nightly.png", next(data for path, data in assets if path == window))) + return assets + + +def provenance(assets): + inputs = [ICONS / "texturecraft.icns", ICONS / "texturecraft.ico", ICONS / "texturecraft-1024.png"] + inputs += [ICONS / "hicolor" / f"{size}x{size}" / "apps" / f"{STABLE_ID}.png" for size in NIGHTLY_SIZES] + digest = lambda data: hashlib.sha256(data).hexdigest() + return { + "title": "TextureCraft nightly deep-background icons", + "license": "MIT OR Apache-2.0", + "generator": "packaging/nightly-icons.py", + "generator_sha256": digest(Path(__file__).read_bytes()), + "inputs": [{"path": str(path.relative_to(ROOT)), "sha256": digest(path.read_bytes())} for path in inputs], + "method": { + "kind": "derivative of the project-owned stable renders; no badge, crescent or letter", + "original_palette": {"ink": "#0b0b0c", "paper": "#efe9dc", "background": "#c2672b"}, + "nightly_background": "#643418", + "transform": "Fit each pixel as the tile background plus one engraved foreground (ink or paper) and replace only the background contribution; keep alpha, padding and foreground detail. Each frame comes from the stable master of its own size: the .icns and .ico PNG frames are recoloured in place, and the per-size PNGs (in nightly/) and the 1024 master are recoloured from their own renders. No upscaling.", + }, + "outputs": {str(path.relative_to(ROOT)): digest(data) for path, data in assets}, + "ico_frames": ["the stable .ico's own frames (16, 20, 24, 32, 40, 48, 64, 128, 256)"], + "icns_slots": "the stable .icns's own PNG slots (icp4 through ic10)", + "validation": "Byte comparison against the committed assets (packaging/nightly-archive-tests.py and the icon check in packaging/nightly-tests.py); native Explorer/Finder rendering is not exercised here. The per-size PNGs are kept out of hicolor/ because Stable's Linux and FreeBSD packages copy that theme tree whole.", + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true", help="fail if the committed assets differ from these bytes") + args = parser.parse_args() + assets = targets() + record = (json.dumps(provenance(assets), indent=2) + "\n").encode() + if args.check: + stale = [path for path, data in assets if not path.is_file() or path.read_bytes() != data] + if not (ICONS / "nightly-provenance.json").is_file() or (ICONS / "nightly-provenance.json").read_bytes() != record: + stale.append(ICONS / "nightly-provenance.json") + if stale: + for path in stale: + print(f"stale: {path.relative_to(ROOT)}", file=sys.stderr) + return 1 + print(f"{len(assets)} Nightly icon files match the generator") + return 0 + for path, data in assets: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + print(f"wrote {path.relative_to(ROOT)} ({len(data)} bytes)") + (ICONS / "nightly-provenance.json").write_bytes(record) + print("wrote assets/app-icon/nightly-provenance.json") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py new file mode 100755 index 00000000..ee421e95 --- /dev/null +++ b/packaging/nightly-release-tests.py @@ -0,0 +1,389 @@ +#!/usr/bin/env python3 +"""Local contract tests for TextureCraft 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") +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": "texturecraft-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.""" + rows = re.findall(r"(?m)^ platforms: (.*)$", source) + if len(rows) != 1: + raise ValueError("exactly one producer platform list is required") + literal = re.fullmatch(r"'(\[[^']*\])'", rows[0]) + if literal is None: + raise ValueError("the platform list must be one single-quoted literal") + platforms = json.loads(literal[1]) + if not isinstance(platforms, list) or json.dumps(platforms, separators=(",", ":")) != literal[1]: + raise ValueError("the platform list must be compact JSON") + if len(set(platforms)) != len(platforms) or not set(platforms) <= set(NIGHTLY_PLATFORMS): + raise ValueError("platforms must be distinct known nightly targets") + if "windows-x86_64" not in platforms: + raise ValueError("the Windows row stays in the producer") + return platforms + + +def reviewed_manual_actors(caller_source, policy): + """The one reviewed manual-actor list, identical in the producer caller and the policy.""" + rows = re.findall(r"(?m)^ manual-actors: '(\[[^']*\])'$", caller_source) + if len(rows) != 1: + raise ValueError("exactly one literal manual-actors list is required") + caller = json.loads(rows[0]) + if caller != policy["manual_actors"]: + raise ValueError("caller and policy must grant the same actors in the same order") + if caller != RELEASE_MANAGERS: + raise ValueError("manual actors must be exactly the reviewed release managers") + if caller != sorted(caller, key=str.lower) or len({login.lower() for login in caller}) != len(caller): + raise ValueError("manual actors must be distinct and sorted case-insensitively") + if set(caller) & {login for login in policy["automatic_signer_actors"]}: + raise ValueError("manual and automatic actors overlap") + return caller + + +def caller_pin(name): + return re.findall(r"(?m)^ tooling-revision: ([0-9a-f]{40})$", (ROOT / ".github/workflows" / name).read_text())[0] + + +class TrustedSourcePreparation(unittest.TestCase): + def test_one_producer_and_one_signer_job_carry_every_platform(self): + for name, job in (("nightly.yml", "unsigned"), ("nightly-sign.yml", "release")): + jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1] + with self.subTest(workflow=name): + self.assertEqual(re.findall(r"(?m)^ ([^\s#][^:]*):", jobs), [job], + "a platform is a list entry, not a separately activatable job") + signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + self.assertNotRegex(signer, r"(?m)^\s*platforms?:", "the release policy, not the caller, admits platforms") + + def test_malformed_or_narrowed_platform_lists_are_rejected(self): + source = (ROOT / ".github/workflows/nightly.yml").read_text() + current = "platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"macos-aarch64\"]'" + self.assertIn(current, source) + for new in ("platforms: '[\"linux-x86_64\"]'", + "platforms: '[\"linux-x86_64\",\"macos-aarch64\"]'", + "platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"linux-x86_64\"]'", + "platforms: '[\"windows-x86_64\",\"macos-x86_64\"]'", + "platforms: '[\"windows-x86_64\",\"linux-arm64\"]'", + "platforms: '[\"windows-x86_64\", \"linux-x86_64\"]'", + "platforms: [\"windows-x86_64\",\"linux-x86_64\"]", + "platforms: ${{ vars.NIGHTLY_PLATFORMS }}", + "platforms: '{\"windows-x86_64\":1}'", + current + "\n " + current): + with self.subTest(change=new), self.assertRaises(ValueError): + producer_platforms(source.replace(current, new)) + with self.assertRaises(ValueError): + producer_platforms(source.replace(" " + current + "\n", "")) + + def test_continuation_lines_of_any_scalar_form_reach_the_guard_checks(self): + for name, workflow in (("nightly.yml", "nightly.yml"), ("nightly-sign.yml", "nightly-sign.yml")): + source = (ROOT / ".github/workflows" / workflow).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: texturecraft-nightly-release", "group: ${{ github.run_id }}"), + ("group: texturecraft-nightly-release", "group: release-${{ github.ref }}"), + ("concurrency:\n", "concurrency: ${{ github.run_id }}\n"), + ("concurrency:\n", " concurrency:\n"), + ): + with self.subTest(change=new), self.assertRaises(ValueError): + assert_nightly_serialization(source.replace(old, new)) + + def test_no_cache_actions_or_cache_setup_options_in_app_trusted_closure(self): + for name in ("nightly.yml", "nightly-sign.yml"): + source = (ROOT / ".github/workflows" / name).read_text() + executable = "\n".join(line for line in source.splitlines() + if not line.lstrip().startswith("#")) + with self.subTest(workflow=name): + self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache") + self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:") + self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):") + self.assertNotIn("secrets.", executable) + + +class NightlyTrustAnchors(unittest.TestCase): + """The public stable identities each platform's signed nightly must carry.""" + + 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/texturecraft' && github.ref == 'refs/heads/main' && " + "github.ref_type == 'branch' && (github.event_name == 'schedule' || " + "github.event_name == 'workflow_dispatch')", + "nightly-sign.yml": "github.repository == 'storytold/texturecraft' && 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/texturecraft") + self.assertEqual(self.policy["release_branch"], "release") + self.assertIs(type(self.policy["repository_id"]), int) + self.assertGreater(self.policy["repository_id"], 0) + # producer_workflow_id is null until nightly.yml is registered on main; once set, must be a positive int. + prod_id = self.policy["producer_workflow_id"] + if prod_id is not None: + self.assertIs(type(prod_id), int) + self.assertGreater(prod_id, 0) + self.assertNotEqual(prod_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/texturecraft", "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"] + self.assertEqual(sonar["organization"], "storytold") + self.assertEqual(sonar["project"], "storytold_texturecraft") + 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") + 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 00000000..0ff2ff4f --- /dev/null +++ b/packaging/nightly-tests.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Run the synthetic Nightly packaging suites together; no app build, signing or network. + +Suites that a checkout does not carry are skipped with a note: the Linux archive suite belongs to +whoever owns `nightly-archive.py`, and this branch does not add one. +""" +import importlib.util +from pathlib import Path +import sys +import unittest + + +def load(here, name, relative, suite): + path = here / relative + if not path.is_file(): + print(f"skip: {relative} is not in this checkout", file=sys.stderr) + return + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(module)) + + +def icons_match(here) -> bool: + """The committed Nightly icons must be exactly what the generator derives from the masters.""" + import subprocess + result = subprocess.run([sys.executable, str(here / "nightly-icons.py"), "--check"], capture_output=True, text=True) + print(result.stdout.strip(), file=sys.stderr) + if result.returncode != 0: + print(result.stderr.strip(), file=sys.stderr) + return result.returncode == 0 + + +def main() -> int: + here = Path(__file__).resolve().parent + suite = unittest.TestSuite() + load(here, "texturecraft_archive_suite", "nightly-archive-tests.py", suite) + load(here, "texturecraft_plist_suite", "macos/nightly_plist_tests.py", suite) + load(here, "texturecraft_release_dispatch_suite", "nightly-release-tests.py", suite) + load(here, "texturecraft_mac_sign_suite", "macos/nightly_sign_tests.py", suite) + passed = unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful() + return 0 if passed and icons_match(here) 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 00000000..79219858 --- /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 00000000..35a7811c --- /dev/null +++ b/packaging/windows/nightly-package-tests.ps1 @@ -0,0 +1,95 @@ +param([Parameter(Mandatory=$true)][string] $FixtureRoot) +. (Join-Path $PSScriptRoot 'nightly.ps1') -FunctionsOnly +function Assert([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } } +$spec = Get-NightlyArchiveSpec '0.23.1-nightly.20261120.17.1.gabcdef012345' 'x64' +Assert ($spec.Archive -eq 'texturecraft-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 'texturecraft.exe') 'nightly must not ship the unqualified CLI' +Assert ($spec.AppId -eq 'ai.storyteller.texturecraft.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 'TextureCraft Nightly' 'TextureCraft 0.23.1-nightly.20261120.17.1.gabcdef012345 (nightly-v1)' '0.23.1-nightly.20261120.17.1.gabcdef012345' +foreach ($pair in @(@('TextureCraft', 'TextureCraft 0.23.1 (nightly-v1)'), @('TextureCraft Nightly', 'TextureCraft 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/texturecraft/src/main.rs') +) +foreach ($case in $cases) { + $refused = $false + try { Assert-NightlySource $case[1] $case[2] $case[3] $case[4] $case[5] } catch { $refused = $true } + Assert $refused "source identity accepted: $($case[0])" +} +Write-Output 'nightly packaging spec, target/version refusal, source identity and flavor-binding tests passed' + +# Exercise the SAME production notice copier with the real repository layout, then inspect a ZIP. +if (-not $FixtureRoot -or -not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'supply an owned absolute -FixtureRoot for the notices/ZIP regression' } +$testRoot = Join-Path $FixtureRoot ("nightly-notices-" + [Guid]::NewGuid().ToString('N')) +try { + $repo = Join-Path $testRoot 'app' + $fontRepo = Join-Path $testRoot 'craft-fonts' + $family = Join-Path $fontRepo 'fonts\ExampleFamily' + $stage = Join-Path $testRoot 'stage' + New-Item -ItemType Directory -Force -Path $repo, $family, $stage | Out-Null + $rootNames = @('README.md', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') + foreach ($name in $rootNames) { Set-Content -LiteralPath (Join-Path $repo $name) -Value "root-notice-$name" } + Set-Content -LiteralPath (Join-Path $family 'OFL.txt') -Value 'font-notice-example' + Copy-NightlyNotices $repo $fontRepo $stage + foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { + Assert (Test-Path -LiteralPath (Join-Path $stage $name)) "missing staged notice $name" + } + $zip = Join-Path $testRoot 'notices.zip' + Compress-Archive -Path (Join-Path $stage '*') -DestinationPath $zip + $archive = [IO.Compression.ZipFile]::OpenRead($zip) + try { + $names = @($archive.Entries | ForEach-Object { $_.FullName }) + foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { Assert ($name -in $names) "missing archived notice $name" } + foreach ($forbidden in @('portable.txt', 'texturecraft-cli.exe')) { Assert ($forbidden -notin $names) "unexpected payload $forbidden" } + $entry = $archive.GetEntry('OFL-ExampleFamily.txt') + $reader = [IO.StreamReader]::new($entry.Open()) + try { Assert ($reader.ReadToEnd().Contains('font-notice-example')) 'wrong font license bytes in ZIP' } finally { $reader.Dispose() } + } finally { $archive.Dispose() } +} finally { + if (Test-Path -LiteralPath $testRoot) { Remove-Item -LiteralPath $testRoot -Recurse -Force } +} +Write-Output 'nightly mock-repository root and font notices are present in stage and ZIP' + +# The source state comes from git itself: the checked-out commit, then a dirty tree. +$gitRoot = Join-Path $FixtureRoot ("nightly-source-" + [Guid]::NewGuid().ToString('N')) +try { + New-Item -ItemType Directory -Force -Path $gitRoot | Out-Null + git -C $gitRoot init -q; git -C $gitRoot -c user.name=fixture -c user.email=fixture@invalid commit -q --allow-empty -m fixture + if ($LASTEXITCODE -ne 0) { throw 'cannot create the git fixture' } + $head = (git -C $gitRoot rev-parse HEAD).Trim() + $state = Get-NightlySourceState $gitRoot + Assert ($state.Head -ceq $head -and -not $state.Status) 'clean checkout not reported as clean at HEAD' + $version = '0.23.1-nightly.20261120.17.1.g' + $head.Substring(0, 12) + Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status + Set-Content -LiteralPath (Join-Path $gitRoot 'untracked.txt') -Value 'dirty' + $state = Get-NightlySourceState $gitRoot + $refused = $false + try { Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status } catch { $refused = $true } + Assert $refused 'a dirty checkout was accepted' +} finally { + if (Test-Path -LiteralPath $gitRoot) { Remove-Item -LiteralPath $gitRoot -Recurse -Force } +} +Write-Output 'nightly source state is read from git and a dirty checkout is refused' diff --git a/packaging/windows/nightly-signing-tests.ps1 b/packaging/windows/nightly-signing-tests.ps1 new file mode 100644 index 00000000..bf3bf959 --- /dev/null +++ b/packaging/windows/nightly-signing-tests.ps1 @@ -0,0 +1,104 @@ +param( + [Parameter(Mandatory=$true)][string] $FixtureRoot, + [string] $PackagingRoot = $PSScriptRoot, + [switch] $PhaseGuardOnly +) +$ErrorActionPreference = 'Stop' +. (Join-Path $PackagingRoot 'nightly.ps1') -FunctionsOnly +$sign = Join-Path $PackagingRoot 'sign.ps1' +$names = @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_TENANT_ID','AZURE_CLIENT_ID','AZURE_CLIENT_SECRET','AZURE_SIGNING_ENDPOINT','AZURE_SIGNING_ACCOUNT','AZURE_CERT_PROFILE') +function Clear-SigningFixtures { foreach ($name in $names) { [Environment]::SetEnvironmentVariable($name, $null) } } +function Assert-Policy([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } } +function Invoke-Refusal([scriptblock] $Operation, [string] $Message) { + $errorText = '' + try { & $Operation | Out-Null } catch { $errorText = $_.Exception.Message } + Assert-Policy ($errorText.Contains($Message)) "expected refusal: $Message; got: $errorText" +} +function global:cargo { $global:SigningFixtureCargoCalls++; throw 'FIXTURE_COMPILER_BOUNDARY' } +# The source preflight reads the real checkout; the fixture answers for its own commit, whose sha +# the version names, so the clean case reaches the mocked compiler instead of the preflight. +function global:git { + param([Parameter(ValueFromRemainingArguments=$true)][object[]] $Arguments) + $joined = ($Arguments | ForEach-Object { "$_" }) -join ' ' + if ($joined -match 'rev-parse HEAD$') { $global:LASTEXITCODE = 0; return ('a' * 40) } + if ($joined -match 'status --porcelain$') { $global:LASTEXITCODE = 0; return '' } + throw "the fixture must not run git: $joined" +} +function global:Invoke-WebRequest { throw 'fixture must not perform signing downloads' } +$global:SigningFixtureCargoCalls = 0 +# The caller's own values, restored in `finally`: this script may run inside a developer's session. +$savedEnvironment = foreach ($name in (@('TEXTURECRAFT_VERSION', 'TEXTURECRAFT_BUILD_SHA', 'TEXTURECRAFT_BUILD_DATE') + $names)) { + [pscustomobject]@{ Name = $name; Value = [Environment]::GetEnvironmentVariable($name) } +} +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 +$version = '0.23.1-nightly.20261121.12345.1.gaaaaaaaaaaaa' +$env:TEXTURECRAFT_VERSION = $version +# The identity the version names: the mocked HEAD and its run date. +$env:TEXTURECRAFT_BUILD_SHA = 'a' * 40 +$env:TEXTURECRAFT_BUILD_DATE = '2026-11-21' +function Invoke-Build([switch] $BuildOnly) { + $arguments = @{Arch='x64';Version=$version;Target='x86_64-pc-windows-msvc';TargetDir=$root;Dist=(Join-Path $root 'dist')} + if ($BuildOnly) { $arguments.BuildOnly = $true } + & (Join-Path $PackagingRoot 'nightly.ps1') @arguments +} +try { + Clear-SigningFixtures + Invoke-Refusal { Invoke-Build } 'requires -BuildOnly' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'default mode invoked Cargo' + Write-Output 'PASS: explicit-build-phase-required' + if ($PhaseGuardOnly) { return } + + foreach ($name in @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_CLIENT_SECRET')) { + Clear-SigningFixtures + [Environment]::SetEnvironmentVariable($name, 'generated-fixture-not-a-secret') + Invoke-Refusal { Invoke-Build -BuildOnly } 'Compilation must not receive signing credentials' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'key-bearing compilation reached Cargo' + } + Write-Output 'PASS: credentials-rejected-before-compilation' + + Clear-SigningFixtures + Invoke-Refusal { Invoke-Build -BuildOnly } 'FIXTURE_COMPILER_BOUNDARY' + Assert-Policy ($global:SigningFixtureCargoCalls -eq 1) 'clean compilation did not reach the mocked compiler boundary' + Assert-Policy (-not (Test-Path (Join-Path $root 'dist'))) 'mocked compilation produced an artifact' + Write-Output 'PASS: secret-free-build-reaches-only-mocked-boundary' + + Clear-SigningFixtures + Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required' + $env:AZURE_CLIENT_SECRET = 'generated-partial-fixture' + Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required' + Write-Output 'PASS: required-signer-refuses-missing-and-partial-configuration' + + Clear-SigningFixtures + $env:WINDOWS_CERTIFICATE = 'generated-presence-fixture-not-a-certificate' + & $sign -Required -CheckOnly + Clear-SigningFixtures + foreach ($name in $names | Where-Object { $_.StartsWith('AZURE_') }) { [Environment]::SetEnvironmentVariable($name, 'generated-presence-fixture') } + & $sign -Required -CheckOnly + Clear-SigningFixtures + Write-Output 'PASS: supported-configuration-presence-without-signing' + + # Load the policy function without signing. These objects are not crypto evidence. + . $sign -CheckOnly + foreach ($value in @($null, [pscustomobject]@{Status='NotSigned';SignerCertificate='fixture'}, [pscustomobject]@{Status='HashMismatch';SignerCertificate='fixture'}, [pscustomobject]@{Status='Valid';SignerCertificate=$null})) { + Invoke-Refusal { Assert-AuthenticodeSignature $value } 'valid Authenticode signature' + } + Assert-AuthenticodeSignature ([pscustomobject]@{Status='Valid';SignerCertificate='generated-public-certificate-placeholder'}) + Write-Output 'PASS: required-signature-policy-rejects-invalid-or-missing-signer' + + $file = Join-Path $root 'owned-sentinel.exe' + [IO.File]::WriteAllText($file, 'generated sentinel, not a real executable') + $before = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash + & $sign -Files $file + Assert-Policy ((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash -ceq $before) 'optional stable policy changed unsigned bytes' + Write-Output 'PASS: stable-optional-policy-preserves-owned-bytes' +} finally { + # Put back exactly what the caller had (an unset variable is restored as unset), and drop the + # command mocks: a `function global:` binding outlives this script and outranks the real program. + foreach ($entry in $savedEnvironment) { [Environment]::SetEnvironmentVariable($entry.Name, $entry.Value) } + foreach ($mock in @('cargo', 'git', 'Invoke-WebRequest')) { + Remove-Item -LiteralPath "function:global:$mock" -ErrorAction SilentlyContinue + } + Remove-Item -LiteralPath $root -Recurse -Force +} diff --git a/packaging/windows/nightly.ps1 b/packaging/windows/nightly.ps1 new file mode 100644 index 00000000..e7f610fc --- /dev/null +++ b/packaging/windows/nightly.ps1 @@ -0,0 +1,131 @@ +<# 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 = "texturecraft-$Version-windows-x86_64-nightly.zip" + UnsignedArchive = "texturecraft-$Version-windows-x86_64-nightly.unsigned.zip" + Executables = @('texturecraft.exe') + Channel = 'nightly-v1' + AppId = 'ai.storyteller.texturecraft.nightly-v1' + } +} + +# The same source identity the Unix 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 (TEXTURECRAFT_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 (TEXTURECRAFT_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 'TextureCraft Nightly' -or $VersionOutput -cne "TextureCraft $ExpectedVersion (nightly-v1)") { + throw 'the executable is not the compiled nightly-v1 flavor' + } +} + +function Copy-NightlyNotices([string] $RepositoryRoot, [string] $FontRepository, [string] $Destination) { + foreach ($name in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') { + $source = Join-Path $RepositoryRoot $name + if (Test-Path -LiteralPath $source) { Copy-Item -LiteralPath $source -Destination $Destination } + } + if ($FontRepository) { + $fonts = Join-Path $FontRepository 'fonts' + if (-not (Test-Path -LiteralPath $fonts -PathType Container)) { throw 'CRAFT_FONTS_DIR has no fonts directory for the bundled notices' } + foreach ($family in Get-ChildItem -LiteralPath $fonts -Directory) { + $license = Join-Path $family.FullName 'OFL.txt' + if (Test-Path -LiteralPath $license) { Copy-Item -LiteralPath $license -Destination (Join-Path $Destination "OFL-$($family.Name).txt") } + } + } +} + +if ($FunctionsOnly) { return } +if (-not $env:TEXTURECRAFT_VERSION -or $Version -cne $env:TEXTURECRAFT_VERSION) { throw 'nightly-v1 requires explicit TEXTURECRAFT_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:TEXTURECRAFT_BUILD_SHA $env:TEXTURECRAFT_BUILD_DATE $Source.Head $Source.Status +$oldChannel = $env:TEXTURECRAFT_BUILD_CHANNEL +try { + # `build.rs` reads TEXTURECRAFT_VERSION (checked equal above) and this channel. + $env:TEXTURECRAFT_BUILD_CHANNEL = 'nightly-v1' + $env:TEXTURECRAFT_REQUIRE_WINRES = '1' + $env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS = '-C target-feature=+crt-static' + # The GUI only: a Nightly install ships no CLI. + cargo build --release --locked -p texturecraft --target $Target + if ($LASTEXITCODE -ne 0) { throw "nightly cargo build failed: $LASTEXITCODE" } +} finally { + $env:TEXTURECRAFT_BUILD_CHANNEL = $oldChannel +} +$Source = Get-NightlySourceState $Root +try { Assert-NightlySource $Version $env:TEXTURECRAFT_BUILD_SHA $env:TEXTURECRAFT_BUILD_DATE $Source.Head $Source.Status } +catch { throw "source changed during the build: $_" } +$Exe = Join-Path $TargetDir "$Target\release\texturecraft.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 'TextureCraft 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 'texturecraft.exe') +# Signing happens only in the separate trusted step, using sign.ps1 -Required. +# The intermediate name 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 'texturecraft-cli.exe')) -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 ('texturecraft.exe' -notin $Names -or 'texturecraft-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 a5241d21..7296e424 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -21,9 +21,12 @@ #> param( [ValidateSet('x64', 'x86', 'arm64')] [string] $Arch = 'x64', - [switch] $SkipBuild + [switch] $SkipBuild, + [switch] $Nightly, + [switch] $BuildOnly ) $ErrorActionPreference = 'Stop' +if ($BuildOnly -and -not $Nightly) { throw '-BuildOnly is only for secret-free nightly compilation' } $Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path function Invoke-Native([string] $What, [scriptblock] $Block) { @@ -50,12 +53,23 @@ $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:TEXTURECRAFT_BUILD_SHA) { $env:TEXTURECRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } -if (-not $env:TEXTURECRAFT_BUILD_DATE) { $env:TEXTURECRAFT_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:TEXTURECRAFT_BUILD_SHA) { $env:TEXTURECRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } + if (-not $env:TEXTURECRAFT_BUILD_DATE) { $env:TEXTURECRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } +} Write-Output "TextureCraft $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 + if ($LASTEXITCODE -ne 0) { throw "nightly packaging failed: $LASTEXITCODE" } + return +} + if (-not $SkipBuild) { + $env:TEXTURECRAFT_BUILD_CHANNEL = 'stable' + # Static CRT: no VC++ redistributable needed. Scoped to the target so host build scripts and # proc-macros are unaffected. $flagVar = 'CARGO_TARGET_' + ($Target.ToUpper() -replace '-', '_') + '_RUSTFLAGS' @@ -83,6 +97,9 @@ foreach ($check in @(@('texturecraft.exe', 2), @('texturecraft-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 'texturecraft.exe')).VersionInfo.ProductName -eq 'TextureCraft 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 794dd266..c9fa6ea6 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/texturecraft.exe dist/TextureCraft.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 @@ -89,6 +117,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 new file mode 100644 index 00000000..21de440a --- /dev/null +++ b/sonar-project.properties @@ -0,0 +1 @@ +sonar.coverage.exclusions=packaging/**