mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-25 07:13:30 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e2e29c8b89 | ||
|
|
c179a31619 | ||
|
|
6e92d33e07 |
@@ -0,0 +1,16 @@
|
||||
-----BEGIN PGP PUBLIC KEY BLOCK-----
|
||||
|
||||
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
|
||||
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
|
||||
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
|
||||
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
|
||||
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
|
||||
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
|
||||
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
|
||||
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
|
||||
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
|
||||
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
|
||||
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
|
||||
ga/qCA==
|
||||
=3wGQ
|
||||
-----END PGP PUBLIC KEY BLOCK-----
|
||||
@@ -0,0 +1,107 @@
|
||||
{
|
||||
"schema": "craft-nightly-release-policy/v3",
|
||||
"repository": "storytold/wordcraft",
|
||||
"repository_id": 1408489772,
|
||||
"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": "wordcraft-nightly-20261124",
|
||||
"repository": "storytold/wordcraft",
|
||||
"branch": "main",
|
||||
"required_workflows": [
|
||||
{
|
||||
"workflow_id": 380135788,
|
||||
"workflow_path": ".github/workflows/ci.yml",
|
||||
"jobs": [
|
||||
{
|
||||
"name": "gate / gate (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"sonar": {
|
||||
"organization": "storytold",
|
||||
"project": "storytold_wordcraft",
|
||||
"app_id": 12526,
|
||||
"check_name": "SonarCloud Code Analysis",
|
||||
"details_url": "https://sonarcloud.io/dashboard?id=storytold_wordcraft&branch=main",
|
||||
"issue_types": [
|
||||
"VULNERABILITY"
|
||||
],
|
||||
"accepted_conditions": [
|
||||
{
|
||||
"metric": "new_security_rating",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "1",
|
||||
"maximum": "5"
|
||||
}
|
||||
],
|
||||
"required_conditions": [
|
||||
{
|
||||
"metric": "new_reliability_rating",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "1"
|
||||
},
|
||||
{
|
||||
"metric": "new_maintainability_rating",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "1"
|
||||
},
|
||||
{
|
||||
"metric": "new_coverage",
|
||||
"comparator": "LT",
|
||||
"error_threshold": "80"
|
||||
},
|
||||
{
|
||||
"metric": "new_duplicated_lines_density",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "3"
|
||||
},
|
||||
{
|
||||
"metric": "new_security_hotspots_reviewed",
|
||||
"comparator": "LT",
|
||||
"error_threshold": "100"
|
||||
}
|
||||
],
|
||||
"debt": []
|
||||
}
|
||||
},
|
||||
"max_artifact_bytes": 2147483648,
|
||||
"automatic_signer_actors": [],
|
||||
"platforms": {
|
||||
"windows-x86_64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
|
||||
"trust": {
|
||||
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
|
||||
}
|
||||
},
|
||||
"linux-x86_64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
|
||||
"trust": {
|
||||
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
|
||||
}
|
||||
},
|
||||
"macos-aarch64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
|
||||
"trust": {
|
||||
"apple_team_id": "DJ6XS33FX8"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
name: Nightly build check
|
||||
|
||||
# Builds the unsigned WordCraft Nightly the way the producer does (packaging/linux/nightly.sh,
|
||||
# packaging/windows/package.ps1 -Nightly, packaging/macos/nightly.sh) and checks each archive as the
|
||||
# Launcher unpacks it. No secrets and no environment: the real Nightly is signed by the shared
|
||||
# release-ref signer (craft-common-actions), which calls packaging/macos/nightly-sign.sh and the
|
||||
# app's sign.ps1.
|
||||
on:
|
||||
# The platform runners 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-build-${{ 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:
|
||||
linux:
|
||||
name: Nightly tar (x86_64, 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: ubuntu-latest
|
||||
timeout-minutes: 120
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Install the system libraries the GUI links
|
||||
run: sudo apt-get update && sudo apt-get install -y pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev libxi-dev libgtk-3-dev libfontconfig1-dev libfreetype-dev
|
||||
- name: Check out craft-fonts
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@1754016e67ca9b74dfa4cf4678b2ac3548e9840f
|
||||
with:
|
||||
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@1754016e67ca9b74dfa4cf4678b2ac3548e9840f
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
- name: Prepare a Nightly identity for this commit
|
||||
shell: bash
|
||||
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 "WORDCRAFT_BUILD_SHA=$sha"
|
||||
echo "WORDCRAFT_BUILD_DATE=$date"
|
||||
echo "WORDCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
|
||||
echo "WORDCRAFT_BUILD_CHANNEL=nightly-v1"
|
||||
echo "CARGO_TARGET_DIR=$RUNNER_TEMP/nightly-targets"
|
||||
echo "DIST=$RUNNER_TEMP/nightly-dist"
|
||||
echo "CRAFT_FONTS_DIR=$GITHUB_WORKSPACE/craft-fonts"
|
||||
echo "CRAFT_FONTS_REQUIRED=1"
|
||||
} >>"$GITHUB_ENV"
|
||||
- name: Build the unsigned Nightly tar
|
||||
run: bash packaging/linux/nightly.sh --arch x86_64
|
||||
- name: Check the tar as the Launcher unpacks it, and ask its version
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
work="$RUNNER_TEMP/nightly-check"
|
||||
mkdir -p "$work"
|
||||
archive="$DIST/wordcraft-$WORDCRAFT_VERSION-linux-x86_64-nightly.tar.gz"
|
||||
# The launcher and the GUI it starts, the icon and the notices; the embedded fonts'
|
||||
# OFL-*.txt licences appear when the build has CRAFT_FONTS_DIR.
|
||||
core="$(tar -tzf "$archive" | sort | grep -Ev '^OFL-[A-Za-z0-9_.-]+\.txt$' | tr '\n' ' ')"
|
||||
[ "$core" = "ATTRIBUTION.md LICENSE-APACHE LICENSE-MIT NOTICE README.md wordcraft wordcraft-bin wordcraft-nightly.png " ] \
|
||||
|| { echo "unexpected members: $core"; exit 1; }
|
||||
tar -xzf "$archive" -C "$work"
|
||||
[ -x "$work/wordcraft" ] && [ ! -L "$work/wordcraft" ]
|
||||
[ "$(stat -c %a "$work/wordcraft")" = 755 ]
|
||||
[ -x "$work/wordcraft-bin" ] && [ ! -L "$work/wordcraft-bin" ]
|
||||
mkdir -p "$work/home" "$work/profile"
|
||||
chmod 700 "$work/home" "$work/profile"
|
||||
out="$(env -i HOME="$work/home" PATH=/usr/bin:/bin "$work/wordcraft" --version 2>"$work/stderr")" \
|
||||
|| { cat "$work/stderr"; exit 1; }
|
||||
[ ! -s "$work/stderr" ]
|
||||
[ "$out" = "WordCraft $WORDCRAFT_VERSION (nightly-v1)" ]
|
||||
out="$(env -i HOME="$work/home" PATH=/usr/bin:/bin "$work/wordcraft" --launch-profile nightly-v1 --profile-root "$work/profile" --version)"
|
||||
[ "$out" = "WordCraft $WORDCRAFT_VERSION (nightly-v1)" ]
|
||||
[ "$(head -c 2 "$work/wordcraft")" = '#!' ]
|
||||
echo "==> verified (unsigned): $out"
|
||||
- name: Keep the unsigned archive
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: wordcraft-nightly-linux-x86_64-unsigned
|
||||
path: ${{ runner.temp }}/nightly-dist/wordcraft-${{ env.WORDCRAFT_VERSION }}-linux-x86_64-nightly.tar.gz
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
compression-level: 0
|
||||
|
||||
windows:
|
||||
name: Nightly ZIP (x86_64, 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: windows-latest
|
||||
timeout-minutes: 150
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
defaults:
|
||||
run:
|
||||
shell: pwsh
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Check out craft-fonts
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@1754016e67ca9b74dfa4cf4678b2ac3548e9840f
|
||||
with:
|
||||
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@1754016e67ca9b74dfa4cf4678b2ac3548e9840f
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
targets: x86_64-pc-windows-msvc
|
||||
- name: Prepare a Nightly identity for this commit
|
||||
shell: bash
|
||||
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 "WORDCRAFT_BUILD_SHA=$sha"
|
||||
echo "WORDCRAFT_BUILD_DATE=$date"
|
||||
echo "WORDCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
|
||||
echo "WORDCRAFT_BUILD_CHANNEL=nightly-v1"
|
||||
echo "CARGO_TARGET_DIR=$RUNNER_TEMP/nightly-targets"
|
||||
echo "DIST=$RUNNER_TEMP/nightly-dist"
|
||||
echo "CRAFT_FONTS_DIR=$GITHUB_WORKSPACE/craft-fonts"
|
||||
echo "CRAFT_FONTS_REQUIRED=1"
|
||||
} >>"$GITHUB_ENV"
|
||||
- name: Build the unsigned Nightly intermediate
|
||||
run: ./packaging/windows/package.ps1 -Arch x64 -Nightly -BuildOnly -Target x86_64-pc-windows-msvc -TargetDir $env:CARGO_TARGET_DIR -Dist $env:DIST
|
||||
- name: Run the packaging contracts (no signing material)
|
||||
run: ./packaging/windows/nightly-package-tests.ps1 -FixtureRoot $env:RUNNER_TEMP
|
||||
- name: Run the signing contracts (dummy keys, no signing)
|
||||
run: ./packaging/windows/nightly-signing-tests.ps1 -FixtureRoot $env:RUNNER_TEMP
|
||||
- name: Keep the unsigned intermediate
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: wordcraft-nightly-windows-x86_64-unsigned
|
||||
path: ${{ runner.temp }}/nightly-dist/wordcraft-${{ env.WORDCRAFT_VERSION }}-windows-x86_64-nightly.unsigned.zip
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
compression-level: 0
|
||||
|
||||
macos:
|
||||
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: 120
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Check out craft-fonts
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@1754016e67ca9b74dfa4cf4678b2ac3548e9840f
|
||||
with:
|
||||
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@1754016e67ca9b74dfa4cf4678b2ac3548e9840f
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
targets: aarch64-apple-darwin
|
||||
- name: Prepare a Nightly identity for this commit
|
||||
shell: bash
|
||||
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 "WORDCRAFT_BUILD_SHA=$sha"
|
||||
echo "WORDCRAFT_BUILD_DATE=$date"
|
||||
echo "WORDCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
|
||||
echo "WORDCRAFT_BUILD_CHANNEL=nightly-v1"
|
||||
echo "CARGO_TARGET_DIR=$RUNNER_TEMP/nightly-targets"
|
||||
echo "DIST=$RUNNER_TEMP/nightly-dist"
|
||||
echo "CRAFT_FONTS_DIR=$GITHUB_WORKSPACE/craft-fonts"
|
||||
echo "CRAFT_FONTS_REQUIRED=1"
|
||||
} >>"$GITHUB_ENV"
|
||||
- name: Build the unsigned Nightly bundle
|
||||
run: bash packaging/macos/nightly.sh --arch aarch64
|
||||
- name: Check the archive and the bundle version
|
||||
run: bash packaging/macos/nightly-verify.sh --expect unsigned --input "$DIST/wordcraft-$WORDCRAFT_VERSION-macos-aarch64-nightly.zip"
|
||||
- name: Keep the unsigned archive
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: wordcraft-nightly-macos-aarch64-unsigned
|
||||
path: ${{ runner.temp }}/nightly-dist/wordcraft-${{ env.WORDCRAFT_VERSION }}-macos-aarch64-nightly.zip
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
compression-level: 0
|
||||
@@ -0,0 +1,42 @@
|
||||
name: WordCraft 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: wordcraft-nightly-release
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
release:
|
||||
# Actual context guards: official repository, manual dispatch, real release branch.
|
||||
if: >-
|
||||
github.repository == 'storytold/wordcraft' &&
|
||||
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@1754016e67ca9b74dfa4cf4678b2ac3548e9840f
|
||||
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.
|
||||
@@ -0,0 +1,34 @@
|
||||
name: WordCraft 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/wordcraft' &&
|
||||
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@1754016e67ca9b74dfa4cf4678b2ac3548e9840f
|
||||
with:
|
||||
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
|
||||
app-name: wordcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
|
||||
# craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the
|
||||
# Linux/macOS signer (#342).
|
||||
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
|
||||
@@ -5,9 +5,9 @@ name: Packaging lint
|
||||
on:
|
||||
push:
|
||||
branches: [main, release]
|
||||
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
|
||||
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
|
||||
pull_request:
|
||||
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
|
||||
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -28,7 +28,7 @@ jobs:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
@@ -49,3 +49,24 @@ jobs:
|
||||
- name: Build and check non-executable installer fixtures
|
||||
shell: pwsh
|
||||
run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests')
|
||||
|
||||
nightly-source-contract:
|
||||
name: Nightly source contracts (no build or signing)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Enforce nightly serialization and synthetic packaging contracts
|
||||
run: python3 packaging/nightly-tests.py
|
||||
- name: Check the Arch Nightly handoff launcher (no build)
|
||||
run: bash packaging/linux/nightly-arch-tar-test.sh
|
||||
- name: Render and run the Nightly tar launcher (no build)
|
||||
run: bash packaging/linux/nightly-package-test.sh
|
||||
|
||||
@@ -8,3 +8,7 @@ plan/
|
||||
/.claude/
|
||||
/target-*/
|
||||
/craft-fonts/
|
||||
/.nightly-tools
|
||||
/.nightly-input
|
||||
/craft-i18n
|
||||
__pycache__/
|
||||
|
||||
@@ -26,6 +26,12 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
|
||||
| `assets/app-icon/hicolor/scalable/apps/ai.storyteller.wordcraft.svg` | WordCraft contributors | original artwork drawn in SVG (`assets/app-icon/wordcraft.svg`), rendered by `packaging/icons.sh` | MIT OR Apache-2.0 | Placeholder app icon until the WordCraft mascot drawing lands |
|
||||
| `assets/app-icon/hicolor/48x48/apps/ai.storyteller.wordcraft.png` | WordCraft contributors | original artwork drawn in SVG (`assets/app-icon/wordcraft.svg`), rendered by `packaging/icons.sh` | MIT OR Apache-2.0 | Placeholder app icon until the WordCraft mascot drawing lands |
|
||||
| `assets/app-icon/hicolor/512x512/apps/ai.storyteller.wordcraft.png` | WordCraft contributors | original artwork drawn in SVG (`assets/app-icon/wordcraft.svg`), rendered by `packaging/icons.sh` | MIT OR Apache-2.0 | Placeholder app icon until the WordCraft mascot drawing lands |
|
||||
| `assets/app-icon/wordcraft-nightly.png` | WordCraft contributors | derived from `assets/app-icon/hicolor/256x256/apps/ai.storyteller.wordcraft.png` by `packaging/nightly-icons.py` (nightly field `#232c67`); input hashes and the recipe are in `assets/app-icon/nightly-provenance.json` | MIT OR Apache-2.0 | Nightly 256 px render; the icon the Linux Nightly tar ships |
|
||||
| `assets/app-icon/wordcraft-nightly-1024.png` | WordCraft contributors | derived from `assets/app-icon/wordcraft-1024.png` by `packaging/nightly-icons.py` | MIT OR Apache-2.0 | 1024 px master the Nightly `.icns` is generated from |
|
||||
| `assets/app-icon/wordcraft-nightly.ico` | WordCraft contributors | derived from `assets/app-icon/wordcraft.ico` by `packaging/nightly-icons.py` | MIT OR Apache-2.0 | Windows Nightly icon (16-256 px), embedded by `apps/wordcraft/build.rs` into the Nightly executable only |
|
||||
| `assets/app-icon/wordcraft-nightly.icns` | WordCraft contributors | derived from `assets/app-icon/wordcraft.icns` by `packaging/nightly-icons.py` | MIT OR Apache-2.0 | macOS Nightly bundle icon (`CFBundleIconFile wordcraft-nightly`) |
|
||||
| `assets/app-icon/nightly-provenance.json` | WordCraft contributors | original work for this repository | MIT OR Apache-2.0 | The exact inputs, palette and transform that produced the Nightly icon set |
|
||||
| `assets/app-icon/README.md` | WordCraft contributors | original description of this repository's own icon artwork | MIT OR Apache-2.0 | Names the master, the sizes and the regeneration steps |
|
||||
| `assets/fonts/Inter-Medium.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface (Latin UI/document font, carried over from DesignCraft) |
|
||||
| `assets/fonts/Inter-Regular.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface (Latin UI/document font, carried over from DesignCraft) |
|
||||
| `assets/fonts/Inter-SemiBold.ttf` | Rasmus Andersson / The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | Open-source typeface (Latin UI/document font, carried over from DesignCraft) |
|
||||
|
||||
Generated
+6
@@ -6442,6 +6442,9 @@ dependencies = [
|
||||
"raw-window-handle",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"wayland-backend",
|
||||
"wayland-client",
|
||||
"wayland-protocols",
|
||||
"web-sys",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
@@ -8970,10 +8973,13 @@ dependencies = [
|
||||
"eframe",
|
||||
"egui",
|
||||
"log",
|
||||
"rfd",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"thiserror 2.0.21",
|
||||
"winit",
|
||||
"winresource",
|
||||
"winsafe",
|
||||
"wordcraft-control-key",
|
||||
"wordcraft-doc",
|
||||
"wordcraft-engine",
|
||||
|
||||
@@ -897,8 +897,21 @@ fn parity_markdown(p: &Value) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
/// The Launcher's Nightly bootstrap belongs to the desktop app: a CLI must not accept it, in the
|
||||
/// separate-token or `=` form, so a mis-routed launch fails loudly instead of editing stable data.
|
||||
fn launcher_profile_flag(args: &[OsString]) -> bool {
|
||||
args.iter().any(|arg| {
|
||||
let arg = arg.to_string_lossy();
|
||||
arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=")
|
||||
})
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let args: Vec<OsString> = std::env::args_os().skip(1).collect();
|
||||
if launcher_profile_flag(&args) {
|
||||
eprintln!("wordcraft-cli: --launch-profile and --profile-root are the desktop app's Nightly bootstrap, not a CLI option");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
// Language packs installed in the suite's font store are used; `proof.installPack` installs
|
||||
// only while the person has turned downloading on in the app.
|
||||
wordcraft_engine::packs::use_font_store(false);
|
||||
|
||||
@@ -1,6 +1,23 @@
|
||||
use super::*;
|
||||
use std::io::Read;
|
||||
|
||||
/// The desktop app's Nightly bootstrap is never a CLI option, in either spelling.
|
||||
#[test]
|
||||
fn the_launcher_profile_bootstrap_is_refused_in_both_forms() {
|
||||
for argv in [
|
||||
&["--launch-profile", "nightly-v1", "--profile-root", "/nightly/profiles/wordcraft", "--version"][..],
|
||||
&["--launch-profile=nightly-v1", "--profile-root=/nightly/profiles/wordcraft"][..],
|
||||
&["--profile-root", "/nightly/profiles/wordcraft"][..],
|
||||
] {
|
||||
let argv: Vec<std::ffi::OsString> = argv.iter().map(std::ffi::OsString::from).collect();
|
||||
assert!(launcher_profile_flag(&argv), "{argv:?}");
|
||||
}
|
||||
for argv in [&["--version"][..], &["proof.check", "--launch-profiles"][..], &["--profile-roots"][..]] {
|
||||
let argv: Vec<std::ffi::OsString> = argv.iter().map(std::ffi::OsString::from).collect();
|
||||
assert!(!launcher_profile_flag(&argv), "{argv:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn args(values: &[&str]) -> Vec<String> {
|
||||
values.iter().map(|value| (*value).into()).collect()
|
||||
}
|
||||
|
||||
@@ -25,6 +25,9 @@ eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "
|
||||
egui = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
# The nightly launch profile's refusal dialog (a native message box, like the app's other OS errors).
|
||||
rfd = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
# The suite's shared libraries: the runtime hooks (`ui`, `ui-app`), file dialogs, the control
|
||||
# channel's arguments, the GPU choice, printing, settings and window placement, the OS appearance
|
||||
# reader and the system clipboard.
|
||||
@@ -68,3 +71,6 @@ xkbcommon-dl = { version = "0.4.2", features = ["x11"] }
|
||||
# The update helper: a copy of this program started with `--finish-update`
|
||||
# (`craft::update::self_update::finish`).
|
||||
craft = { workspace = true, features = ["update"] }
|
||||
# The nightly Windows identity: an explicit AppUserModelID, so Nightly gets its own taskbar
|
||||
# button instead of sharing the stable app's (#16335's rule for the suite).
|
||||
winsafe = { version = "=0.0.29", default-features = false, features = ["user", "shell"] }
|
||||
|
||||
+43
-5
@@ -1,25 +1,63 @@
|
||||
//! Windows only: embed the app icon and version info (VERSIONINFO) into `wordcraft.exe`, so it
|
||||
//! shows in Explorer, the taskbar, the Start menu and Alt-Tab.
|
||||
//!
|
||||
//! On every other target this does nothing. A missing resource compiler is a warning, so a
|
||||
//! cross-compile from macOS or Linux still links, unless `WORDCRAFT_REQUIRE_WINRES=1` turns it
|
||||
//! The build channel (`WORDCRAFT_BUILD_CHANNEL`) is decided here, before any code is compiled: a
|
||||
//! nightly-v1 build gets its own cfg, its own icon and its exact feed version in VERSIONINFO.
|
||||
//! On every other target this does nothing but that. A missing resource compiler is a warning, so
|
||||
//! a cross-compile from macOS or Linux still links, unless `WORDCRAFT_REQUIRE_WINRES=1` turns it
|
||||
//! into an error (for release builds).
|
||||
|
||||
#[path = "src/build_channel.rs"]
|
||||
mod build_channel;
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
println!("cargo:rerun-if-env-changed=WORDCRAFT_BUILD_CHANNEL");
|
||||
println!("cargo:rustc-check-cfg=cfg(wordcraft_nightly_v1)");
|
||||
let nightly = match std::env::var("WORDCRAFT_BUILD_CHANNEL").as_deref() {
|
||||
Ok("nightly-v1") => {
|
||||
println!("cargo:rustc-cfg=wordcraft_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 WORDCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
println!("cargo:rerun-if-changed=../../assets/app-icon/wordcraft.ico");
|
||||
println!("cargo:rerun-if-changed=../../assets/app-icon/wordcraft-nightly.ico");
|
||||
println!("cargo:rerun-if-env-changed=WORDCRAFT_REQUIRE_WINRES");
|
||||
println!("cargo:rerun-if-env-changed=WORDCRAFT_VERSION");
|
||||
let built_version = if nightly {
|
||||
match std::env::var("WORDCRAFT_VERSION") {
|
||||
Ok(version) if build_channel::is_nightly_version(&version) => version,
|
||||
_ => {
|
||||
eprintln!("nightly-v1 requires an explicit WORDCRAFT_VERSION feed identity");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
|
||||
};
|
||||
println!("cargo:rustc-env=WORDCRAFT_BUILT_VERSION={built_version}");
|
||||
|
||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
|
||||
return;
|
||||
}
|
||||
let mut res = winresource::WindowsResource::new();
|
||||
res.set_icon("../../assets/app-icon/wordcraft.ico")
|
||||
.set("ProductName", "WordCraft")
|
||||
.set("FileDescription", "WordCraft word processor")
|
||||
res.set_icon(build_channel::windows_icon_path(nightly))
|
||||
.set("ProductName", if nightly { "WordCraft Nightly" } else { "WordCraft" })
|
||||
.set("FileDescription", if nightly { "WordCraft Nightly word processor" } else { "WordCraft word processor" })
|
||||
.set("CompanyName", "Learning Machines LLC")
|
||||
.set("LegalCopyright", "Copyright (c) the WordCraft authors. MIT OR Apache-2.0.")
|
||||
.set("OriginalFilename", "wordcraft.exe")
|
||||
.set("InternalName", "wordcraft");
|
||||
if nightly {
|
||||
// The Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion.
|
||||
res.set("ProductVersion", &built_version);
|
||||
}
|
||||
if let Err(e) = res.compile() {
|
||||
if std::env::var_os("WORDCRAFT_REQUIRE_WINRES").is_some() {
|
||||
eprintln!("embedding Windows resources failed: {e}");
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
//! The build-time nightly identity shared by the build script and its pure regression tests.
|
||||
pub fn is_nightly_version(version: &str) -> bool {
|
||||
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
|
||||
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
|
||||
let base: Vec<_> = base.split('.').collect();
|
||||
let parts: Vec<_> = suffix.split('.').collect();
|
||||
base.len() == 3
|
||||
&& base.iter().all(|s| digits(s))
|
||||
&& parts.len() == 4
|
||||
&& parts[0].len() == 8
|
||||
&& digits(parts[0])
|
||||
&& digits(parts[1])
|
||||
&& digits(parts[2])
|
||||
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
|
||||
}
|
||||
pub fn windows_icon_path(nightly: bool) -> &'static str {
|
||||
if nightly { "../../assets/app-icon/wordcraft-nightly.ico" } else { "../../assets/app-icon/wordcraft.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/wordcraft.ico");
|
||||
assert_eq!(windows_icon_path(true), "../../assets/app-icon/wordcraft-nightly.ico");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_feed_identity_is_required_for_a_nightly_build() {
|
||||
assert!(is_nightly_version("0.18.1-nightly.20261124.17.1.gabcdef012345"));
|
||||
for invalid in [
|
||||
"",
|
||||
"0.18.1",
|
||||
"0.18.1-nightly",
|
||||
"0.18.1-nightly.20261124",
|
||||
"0.18.1-nightly.20261124.17.1.gABCDEF012345",
|
||||
"0.18.1-nightly.20261124.17.1.gabcdef012345\n",
|
||||
] {
|
||||
assert!(!is_nightly_version(invalid), "{invalid:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
|
||||
for invalid in [
|
||||
"../0.18.1-nightly.20261124.1.1.gabcdef012345",
|
||||
"0.18.1-nightly.20261124.1.1.gabcdef012345/other",
|
||||
"0.18.1-nightly.20261124.1.1.gabcdef012345\ncargo:rustc-cfg=other",
|
||||
] {
|
||||
assert!(!is_nightly_version(invalid));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
|
||||
use crate::launch_profile::Profile;
|
||||
use std::ffi::OsString;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BuildFlavor {
|
||||
Stable,
|
||||
NightlyV1,
|
||||
}
|
||||
|
||||
pub const COMPILED: BuildFlavor = if cfg!(wordcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
|
||||
|
||||
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
|
||||
match (flavor, profile.is_nightly()) {
|
||||
(BuildFlavor::NightlyV1, false) => Err("Open WordCraft Nightly from ArtCraft Launcher".into()),
|
||||
(BuildFlavor::Stable, true) => Err("This is a stable WordCraft build; nightly-v1 requires the nightly build".into()),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
|
||||
desktop_session && flavor == BuildFlavor::NightlyV1
|
||||
}
|
||||
|
||||
/// The Launcher's version line: `WordCraft <version> (nightly-v1)` for a nightly build.
|
||||
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
|
||||
match flavor {
|
||||
BuildFlavor::Stable => stable.to_owned(),
|
||||
BuildFlavor::NightlyV1 => format!("WordCraft {stable} (nightly-v1)"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A plain `--version` / `-V`: the only arguments, answered before any startup work.
|
||||
pub fn version_query(args: &[OsString]) -> bool {
|
||||
matches!(args, [arg] if arg == "--version" || arg == "-V")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
|
||||
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
|
||||
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, true));
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_build_without_a_profile_is_refused_before_startup() {
|
||||
let started = std::cell::Cell::new(false);
|
||||
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
|
||||
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
|
||||
assert!(!started.get());
|
||||
}
|
||||
#[test]
|
||||
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
|
||||
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
|
||||
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
|
||||
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
|
||||
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
|
||||
}
|
||||
#[test]
|
||||
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
|
||||
assert_eq!(version(BuildFlavor::Stable, "0.18.1"), "0.18.1");
|
||||
assert_eq!(version(BuildFlavor::NightlyV1, "0.18.1"), "WordCraft 0.18.1 (nightly-v1)");
|
||||
assert!(version_query(&["--version".into()]));
|
||||
assert!(version_query(&["-V".into()]));
|
||||
assert!(!version_query(&["--".into(), "--version".into()]));
|
||||
assert!(!version_query(&[]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, preferences, fonts or saved state.
|
||||
//! Stable launches retain their original arguments and directory policy. No environment mutation.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
pub const VERSION: &str = "nightly-v1";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Profile {
|
||||
Stable,
|
||||
NightlyV1(PathBuf),
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
pub fn is_nightly(&self) -> bool {
|
||||
matches!(self, Self::NightlyV1(_))
|
||||
}
|
||||
|
||||
pub fn root(&self) -> Option<&Path> {
|
||||
match self {
|
||||
Self::Stable => None,
|
||||
Self::NightlyV1(root) => Some(root),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Launch {
|
||||
pub profile: Profile,
|
||||
pub args: Vec<OsString>,
|
||||
}
|
||||
|
||||
static PROFILE: OnceLock<Profile> = 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<OsString>) -> Result<Launch, String> {
|
||||
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 settings-folder resolution stays unchanged.
|
||||
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
|
||||
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) -> Result<PathBuf, String> {
|
||||
crate::profile_root::validate(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref(), crate::profile_root::probe_writable)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
fn args(values: &[&str]) -> Vec<OsString> {
|
||||
values.iter().map(OsString::from).collect()
|
||||
}
|
||||
fn absolute() -> &'static str {
|
||||
if cfg!(windows) { r"C:\NightlyData\profiles\wordcraft" } else { "/nightly-data/profiles/wordcraft" }
|
||||
}
|
||||
fn nightly() -> Vec<OsString> {
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_arguments_and_directory_policy_are_unchanged() {
|
||||
for argv in [args(&[]), args(&["--control", "7981", "a.docx"]), args(&["--", "--launch-profile", "file.docx"])] {
|
||||
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", "letter with spaces.docx"]));
|
||||
let launch = parse(argv).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
|
||||
assert_eq!(launch.args, args(&["--", "--profile-root", "letter with spaces.docx"]));
|
||||
}
|
||||
|
||||
#[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(), "--sample", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
] {
|
||||
assert!(parse(argv).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
|
||||
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
|
||||
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
|
||||
for flag in ["--version", "-V"] {
|
||||
for form in [pair, reversed] {
|
||||
let mut argv = args(form);
|
||||
argv.push(flag.into());
|
||||
assert!(version_query(&argv), "{argv:?}");
|
||||
}
|
||||
}
|
||||
for argv in [
|
||||
args(&["--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--sample", "--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());
|
||||
}
|
||||
}
|
||||
+191
-22
@@ -14,9 +14,16 @@
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod appimage_env;
|
||||
#[cfg(test)]
|
||||
mod build_channel;
|
||||
mod build_flavor;
|
||||
mod control_server;
|
||||
mod default_apps;
|
||||
mod launch_profile;
|
||||
mod nightly_session;
|
||||
mod prefs;
|
||||
mod process_identity;
|
||||
mod profile_root;
|
||||
mod region;
|
||||
|
||||
use std::path::PathBuf;
|
||||
@@ -58,6 +65,9 @@ struct App {
|
||||
spool: Spool,
|
||||
/// The control server, when `--control` started one; it removes the token file it made.
|
||||
control: Option<control_server::Control>,
|
||||
/// The app binary's last step as the app leaves, run once at the end of `finish` (a Nightly
|
||||
/// quit ends the process inside AppKit's terminate, after eframe's `on_exit`).
|
||||
exit: Option<Box<dyn FnOnce()>>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
@@ -95,7 +105,12 @@ impl App {
|
||||
if let Some(control) = self.control.take() {
|
||||
control.shut_down();
|
||||
}
|
||||
self.app.start_pending_update();
|
||||
if !launch_profile::current().is_nightly() {
|
||||
self.app.start_pending_update();
|
||||
}
|
||||
if let Some(exit) = self.exit.take() {
|
||||
exit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,10 +217,12 @@ type MakeDefault = Box<dyn Fn() -> Result<DefaultApp, DefaultAppError>>;
|
||||
/// What the app takes from its host beyond the runtime: File › Print through the system spooler,
|
||||
/// personal templates (#2852, made on first save in `Templates` in the settings folder), and making
|
||||
/// WordCraft the default app for Word documents (#295; macOS has no way to, so no button there).
|
||||
fn services(spool: Spool, intake: FileIntake) -> Services {
|
||||
fn services(spool: Spool, intake: FileIntake, nightly: bool) -> Services {
|
||||
// Nightly never claims the stable app's file associations: the button would rewrite the same
|
||||
// OS registration the stable WordCraft owns.
|
||||
#[cfg(any(unix, windows))]
|
||||
let make_default_app =
|
||||
(!cfg!(target_os = "macos")).then(|| -> MakeDefault { Box::new(|| craft::platform::default_app::make_default(&default_apps::identity())) });
|
||||
let make_default_app = (!cfg!(target_os = "macos") && !nightly)
|
||||
.then(|| -> MakeDefault { Box::new(|| craft::platform::default_app::make_default(&default_apps::identity())) });
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
let make_default_app: Option<MakeDefault> = None;
|
||||
Services {
|
||||
@@ -258,9 +275,9 @@ fn build_sha() -> &'static str {
|
||||
|
||||
/// The arguments as text, and apart the files whose names aren't valid Unicode, such as a Latin-1
|
||||
/// one (#1440). A `--control` port, a token or a token file that isn't is an error.
|
||||
fn text_args() -> (Vec<String>, Vec<std::path::PathBuf>) {
|
||||
fn text_args(arguments: Vec<std::ffi::OsString>) -> (Vec<String>, Vec<std::path::PathBuf>) {
|
||||
let (mut args, mut files) = (Vec::new(), Vec::new());
|
||||
for (i, a) in std::env::args_os().skip(1).enumerate() {
|
||||
for (i, a) in arguments.into_iter().enumerate() {
|
||||
match a.into_string() {
|
||||
Ok(a) => args.push(a),
|
||||
Err(a) if args.last().is_some_and(|p| matches!(p.as_str(), "--control" | "--control-token" | "--control-token-file")) => {
|
||||
@@ -318,18 +335,96 @@ fn complain(message: std::fmt::Arguments<'_>) {
|
||||
let _ = std::io::Write::write_fmt(&mut std::io::stderr(), format_args!("wordcraft: {message}\n"));
|
||||
}
|
||||
|
||||
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
|
||||
process_identity::initialize(
|
||||
build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1,
|
||||
wordcraft_ui_egui::os_window::id_for(wordcraft_ui_egui::os_window::LaunchIdentity::NightlyV1),
|
||||
)
|
||||
}
|
||||
|
||||
/// Tell the person why a Launcher launch was refused, with a native message box on a desktop
|
||||
/// session (a Launcher start has no terminal to read standard error from).
|
||||
fn report_launch_profile_error(error: &str) {
|
||||
complain(format_args!("launch profile: {error}"));
|
||||
let desktop_session = cfg!(windows)
|
||||
|| cfg!(target_os = "macos")
|
||||
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
|
||||
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
|
||||
if let Err(identity) = initialize_nightly_process_identity() {
|
||||
complain(format_args!("launch profile: {identity}"));
|
||||
return;
|
||||
}
|
||||
let _ = rfd::MessageDialog::new()
|
||||
.set_title("WordCraft Nightly")
|
||||
.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.
|
||||
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
// The trusted Launcher protocol is decided before logging, crash handling, the update helper,
|
||||
// fonts, preferences or the settings folder.
|
||||
let argv: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
|
||||
// --version`: answered before root validation, process identity, IPC or any window.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
|
||||
{
|
||||
let line = build_flavor::version(build_flavor::COMPILED, env!("WORDCRAFT_BUILT_VERSION"));
|
||||
let _ = std::io::Write::write_all(&mut std::io::stdout(), format!("{line}\n").as_bytes());
|
||||
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, launch_profile::validate_root))
|
||||
.unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2)
|
||||
});
|
||||
let identity = if early.profile.is_nightly() {
|
||||
wordcraft_ui_egui::os_window::LaunchIdentity::NightlyV1
|
||||
} else {
|
||||
wordcraft_ui_egui::os_window::LaunchIdentity::Stable
|
||||
};
|
||||
if let Err(error) = launch_profile::install(early.profile).and_then(|()| wordcraft_ui_egui::os_window::select_identity(identity)) {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
}
|
||||
// One data root for everything the app keeps: preferences, window place, logs, recovery,
|
||||
// fonts, templates, dictionaries and control token files all come from it.
|
||||
if let Some(root) = launch_profile::current().root()
|
||||
&& let Err(error) = wordcraft_control_key::use_settings_dir(root.to_path_buf())
|
||||
{
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
}
|
||||
Some(early.args)
|
||||
}
|
||||
|
||||
/// Parses the command line, installs logging and the panic hook, restores preferences and window
|
||||
/// geometry, opens requested documents or the Start screen, starts the control server when
|
||||
/// asked, and runs the eframe event loop.
|
||||
fn main() -> eframe::Result {
|
||||
// Windows: the print helper is a copy of this program that runs one job in its own process.
|
||||
// It reads only its own job folder, so it runs before the launch profile is parsed: a Nightly
|
||||
// wants a profile on every start, and the helper must print without one.
|
||||
#[cfg(windows)]
|
||||
if let Some(code) = craft::print::spool::isolated::helper_main() {
|
||||
std::process::exit(code);
|
||||
}
|
||||
let Some(arguments) = prepare_launch() else { return Ok(()) };
|
||||
// Windows: the update helper is a copy of this program started with `--finish-update`.
|
||||
// A Nightly never updates itself: the Launcher owns its updates.
|
||||
#[cfg(windows)]
|
||||
if let Some(result) = craft::update::self_update::finish(&wordcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
|
||||
if !launch_profile::current().is_nightly()
|
||||
&& let Some(result) = craft::update::self_update::finish(&wordcraft_ui_egui::UPDATE_APP, &arguments)
|
||||
{
|
||||
std::process::exit(i32::from(result.is_err()));
|
||||
}
|
||||
// Linux: before anything reads another program's AppImage variables, or a thread starts (#5653).
|
||||
@@ -352,7 +447,7 @@ fn main() -> eframe::Result {
|
||||
let mut flags = ControlOptions::default();
|
||||
let mut files = Vec::new();
|
||||
let mut sample = false;
|
||||
let (args, other_files) = text_args();
|
||||
let (args, other_files) = text_args(arguments);
|
||||
// Only macOS (Finder / LaunchServices) adds these; elsewhere `-NS…` could be a real file name.
|
||||
let args = if cfg!(target_os = "macos") { without_launch_args(args) } else { args };
|
||||
let mut bad_control: Option<Option<String>> = None;
|
||||
@@ -388,6 +483,7 @@ fn main() -> eframe::Result {
|
||||
},
|
||||
"--sample" => sample = true,
|
||||
"--version" => {
|
||||
// A nightly build reported its channel line before this parser ran.
|
||||
println!("wordcraft {} ({})", env!("CARGO_PKG_VERSION"), build_sha());
|
||||
return Ok(());
|
||||
}
|
||||
@@ -422,6 +518,13 @@ fn main() -> eframe::Result {
|
||||
complain(format_args!("--control needs a port number from 1 to 65535, got \"0\""));
|
||||
std::process::exit(2);
|
||||
}
|
||||
// Nightly runs the Launcher's documents only: no control server, token file or automation
|
||||
// switch, and none inherited from a stable launch's environment.
|
||||
if launch_profile::current().is_nightly() && (control.port.is_some() || control.token.is_some() || control.token_file.is_some()) {
|
||||
complain(format_args!("a WordCraft Nightly window does not start a control server; open documents through ArtCraft Launcher"));
|
||||
std::process::exit(2);
|
||||
}
|
||||
let nightly = launch_profile::current().is_nightly();
|
||||
let settings_dir = wordcraft_control_key::settings_dir();
|
||||
// The log file lives in the settings directory, next to the preferences; opened after the
|
||||
// arguments, so `--version` leaves no file behind. Records logged until now are written to it
|
||||
@@ -440,10 +543,16 @@ fn main() -> eframe::Result {
|
||||
None => logger.stderr_only(),
|
||||
}
|
||||
}
|
||||
// A Nightly window always carries its own id; a stable one keeps the Flatpak sandbox's id
|
||||
// when it runs inside one (so docks match the flatpak's desktop file).
|
||||
let app_id = match launch_profile::current().root() {
|
||||
Some(_) => wordcraft_ui_egui::os_window::app_id().to_string(),
|
||||
None => std::env::var("FLATPAK_ID").ok().filter(|id| !id.is_empty()).unwrap_or_else(|| wordcraft_ui_egui::os_window::APP_ID.to_string()),
|
||||
};
|
||||
let mut options = eframe::NativeOptions {
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.with_title("WordCraft")
|
||||
.with_app_id("ai.storyteller.wordcraft")
|
||||
.with_title(wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()))
|
||||
.with_app_id(app_id)
|
||||
.with_inner_size([1440.0, 920.0])
|
||||
.with_min_inner_size(wordcraft_ui_egui::window_geometry::MIN_SIZE)
|
||||
.with_drag_and_drop(true)
|
||||
@@ -504,9 +613,33 @@ fn main() -> eframe::Result {
|
||||
let _apple_events = craft::platform::open::apple_events::install(sender);
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
drop(sender);
|
||||
// Nightly's own health record: one owner per profile, cleared only by a controlled return.
|
||||
let (nightly_record, health_unavailable) = match nightly_session::Session::begin_with_health(
|
||||
launch_profile::current().root(),
|
||||
env!("WORDCRAFT_BUILT_VERSION"),
|
||||
option_env!("WORDCRAFT_BUILD_SHA"),
|
||||
) {
|
||||
Ok(pair) => pair,
|
||||
Err(error) => {
|
||||
log::warn!("Nightly session health is unavailable: {error}");
|
||||
(None, launch_profile::current().is_nightly())
|
||||
}
|
||||
};
|
||||
let session_health_warning: Option<String> = health_unavailable.then(|| {
|
||||
"WordCraft Nightly could not record session health in its private profile. You can still edit, but abnormal-exit detection is unavailable."
|
||||
.to_string()
|
||||
});
|
||||
let previous_nightly_unclean = nightly_record.as_ref().is_some_and(nightly_session::Session::previous_unclean);
|
||||
let nightly_watch: nightly_session::Shared = Arc::new(Mutex::new(nightly_record));
|
||||
let unclean_notice_shown = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
// The window body and its exit hook each take a clone of the flag; the return path keeps the
|
||||
// other, so a start that created no window can still finish the record.
|
||||
let session_for_exit = nightly_watch.clone();
|
||||
let noticed_for_exit = unclean_notice_shown.clone();
|
||||
let noticed_in_window = unclean_notice_shown.clone();
|
||||
let exit_settings = settings.clone();
|
||||
let result = eframe::run_native(
|
||||
"WordCraft",
|
||||
wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()),
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
let ctx = cc.egui_ctx.clone();
|
||||
@@ -528,7 +661,7 @@ fn main() -> eframe::Result {
|
||||
);
|
||||
let shell = ShellInfo::current().backend(if x11 { Backend::X11 } else { Backend::from_env() });
|
||||
let spec = InstallSpec::new(shell, Arc::new(SystemWindows))
|
||||
.app_id("ai.storyteller.wordcraft")
|
||||
.app_id(wordcraft_ui_egui::os_window::app_id())
|
||||
.system(SystemReader::start(wake))
|
||||
.clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png)))
|
||||
.placement(placement);
|
||||
@@ -547,19 +680,31 @@ fn main() -> eframe::Result {
|
||||
prefs::load_user_dictionary(&mut session, &settings, path);
|
||||
}
|
||||
let spool = Spool::new(host.jobs_shared().clone());
|
||||
let mut app = WordApp::new(session, services(spool.clone(), intake)).with_host(host).with_settings(settings.clone());
|
||||
let mut app = WordApp::new(session, services(spool.clone(), intake, nightly)).with_host(host).with_settings(settings.clone());
|
||||
// PLAN: writer note 9 puts `with_settings` after `with_control`; it comes first here because
|
||||
// the region check below reads the saved region the settings apply.
|
||||
if std::env::var("WORDCRAFT_FILE_DIALOG").is_ok_and(|v| v.trim().eq_ignore_ascii_case("builtin")) {
|
||||
app = app.with_fallback_chooser(true);
|
||||
}
|
||||
app.set_startup_update_check(true);
|
||||
// After the preferences, so the reason it gives is in the interface language.
|
||||
if updates_unsafe {
|
||||
app.disable_self_update();
|
||||
if nightly {
|
||||
// The Launcher installs Nightly; Help › Check for Updates says so instead.
|
||||
app.use_launcher_updates();
|
||||
} else {
|
||||
app.set_startup_update_check(true);
|
||||
// After the preferences, so the reason it gives is in the interface language.
|
||||
if updates_unsafe {
|
||||
app.disable_self_update();
|
||||
}
|
||||
}
|
||||
// Language packs from the suite's font store; an Install click is the person's own.
|
||||
wordcraft_engine::packs::use_font_store(true);
|
||||
// Nightly keeps its own store in the profile, so a pack installed there is not a
|
||||
// change to the stable apps' shared fonts.
|
||||
match launch_profile::current().root() {
|
||||
Some(root) => wordcraft_engine::packs::use_font_store_in(root.join("FontStore"), true),
|
||||
None => {
|
||||
wordcraft_engine::packs::use_font_store(true);
|
||||
}
|
||||
}
|
||||
// A region chosen in File › Options replaces the system's for the first blank
|
||||
// document too (#838).
|
||||
if !sample && app.session.prefs.region.is_some() {
|
||||
@@ -576,7 +721,8 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
}
|
||||
let mut control_server = None;
|
||||
if let Some(port) = control.port
|
||||
if !nightly
|
||||
&& let Some(port) = control.port
|
||||
&& let Some((rx, started)) =
|
||||
control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
|
||||
{
|
||||
@@ -598,9 +744,32 @@ fn main() -> eframe::Result {
|
||||
for f in other_files {
|
||||
open_non_unicode(&mut app, &f);
|
||||
}
|
||||
Ok(Box::new(App { app, panels, drops, settings, spool, control: control_server }))
|
||||
// The personal agent files, the session record and the control token all live in the
|
||||
// profile; the app's own services are built with the nightly rule in mind.
|
||||
if let Some(warning) = &session_health_warning {
|
||||
app.status_long(warning.clone());
|
||||
}
|
||||
if previous_nightly_unclean {
|
||||
app.status_long(
|
||||
"The previous WordCraft Nightly session did not finish normally. You can report a problem from Help › About. No diagnostics have been sent.",
|
||||
);
|
||||
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
Ok(Box::new(App {
|
||||
app,
|
||||
panels,
|
||||
drops,
|
||||
settings,
|
||||
spool,
|
||||
control: control_server,
|
||||
exit: Some(Box::new(move || {
|
||||
nightly_session::finish_once(&session_for_exit, noticed_for_exit.load(std::sync::atomic::Ordering::Relaxed));
|
||||
})),
|
||||
}))
|
||||
}),
|
||||
);
|
||||
// The exit hook has run; this is the no-op fallback for a start that created no window.
|
||||
nightly_session::finish_once(&nightly_watch, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed));
|
||||
// The app is dropped by now: whatever it saved on the way out is in the store.
|
||||
if let Err(e) = exit_settings.lock().flush() {
|
||||
log::warn!("preferences: {e}");
|
||||
@@ -802,8 +971,8 @@ mod smoke {
|
||||
let (intake, sender) = FileIntake::new(Wake::new(|| {}));
|
||||
let drops = intake.sender();
|
||||
let session = Session::new(wordcraft_doc::Document::new());
|
||||
let app = WordApp::new(session, services(spool.clone(), intake)).with_host(host).with_settings(settings.clone());
|
||||
Run { app: App { app, panels, drops, settings, spool, control: None }, frames, ctx, sender }
|
||||
let app = WordApp::new(session, services(spool.clone(), intake, false)).with_host(host).with_settings(settings.clone());
|
||||
Run { app: App { app, panels, drops, settings, spool, control: None, exit: None }, frames, ctx, sender }
|
||||
}
|
||||
|
||||
/// One frame as eframe runs it: the input hook once, the logic once, the UI per pass.
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
//! App-private Nightly session health, not telemetry or a Launcher protocol.
|
||||
//! A live owner holds a separate persistent lease; secondary launches never rewrite its record.
|
||||
//! Dropping the guard does not clear the marker. Only the app's controlled return path does.
|
||||
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{self, Read};
|
||||
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<u8>,
|
||||
previous_unclean: bool,
|
||||
}
|
||||
|
||||
fn regular_or_missing(path: &Path) -> io::Result<bool> {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
|
||||
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write `bytes` to `path` through a fresh temporary file in the same folder and a rename: the
|
||||
/// destination entry is replaced, never followed, so a link planted at `path` is not written
|
||||
/// through. The file is synced and the folder is synced after the rename.
|
||||
fn write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
let directory = path.parent().ok_or_else(|| io::Error::other("the session record has no folder"))?;
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let temporary = directory.join(format!(".{name}.{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
|
||||
let mut file = OpenOptions::new().write(true).create_new(true).open(&temporary)?;
|
||||
let written = std::io::Write::write_all(&mut file, bytes).and_then(|()| file.sync_all());
|
||||
drop(file);
|
||||
if let Err(error) = written {
|
||||
let _ = std::fs::remove_file(&temporary);
|
||||
return Err(error);
|
||||
}
|
||||
if let Err(error) = std::fs::rename(&temporary, path) {
|
||||
let _ = std::fs::remove_file(&temporary);
|
||||
return Err(error);
|
||||
}
|
||||
if let Ok(directory) = File::open(directory) {
|
||||
let _ = directory.sync_all();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The owner's session, shared by the app's exit hook (macOS: a quit ends the process inside
|
||||
/// AppKit's terminate) and the code after the event loop.
|
||||
pub type Shared = Arc<Mutex<Option<Session>>>;
|
||||
|
||||
/// 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<Self>, 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<Option<Self>> {
|
||||
let Some(root) = root else { return Ok(None) };
|
||||
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
|
||||
}
|
||||
let lease_path = root.join(LEASE);
|
||||
regular_or_missing(&lease_path)?;
|
||||
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
|
||||
match lease.try_lock() {
|
||||
Ok(()) => {}
|
||||
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
|
||||
Err(std::fs::TryLockError::Error(error)) => return Err(error),
|
||||
}
|
||||
let path = root.join(RECORD);
|
||||
let previous_unclean = regular_or_missing(&path)?;
|
||||
let own_record = serde_json::to_vec(&serde_json::json!({
|
||||
"schema_version": 1,
|
||||
"channel": "nightly-v1",
|
||||
"version": version,
|
||||
"commit": commit.filter(|value| !value.is_empty()),
|
||||
}))?;
|
||||
write_no_follow(&path, &own_record)?;
|
||||
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
|
||||
}
|
||||
|
||||
pub fn previous_unclean(&self) -> bool {
|
||||
self.previous_unclean
|
||||
}
|
||||
|
||||
/// Controlled return. If an earlier session's interruption was detected but no window showed
|
||||
/// it yet, the record is left for the next owner to report; otherwise this is [`Self::complete`].
|
||||
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
|
||||
if self.previous_unclean && !unclean_notice_shown {
|
||||
return Ok(());
|
||||
}
|
||||
self.complete()
|
||||
}
|
||||
|
||||
/// Controlled event-loop completion includes a handled startup error, not only exit 0.
|
||||
/// An unwind, abort, forced exit or killed process never calls this method.
|
||||
pub fn complete(self) -> io::Result<()> {
|
||||
if !regular_or_missing(&self.path)? {
|
||||
return Ok(());
|
||||
}
|
||||
let mut current = Vec::new();
|
||||
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
|
||||
if current != self.own_record {
|
||||
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
|
||||
}
|
||||
std::fs::remove_file(&self.path)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
struct Fixture(PathBuf);
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
loop {
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("wordcraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
match std::fs::create_dir(&path) {
|
||||
Ok(()) => return Self(path),
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("cannot create owned fixture: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
std::fs::remove_dir_all(&self.0).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
|
||||
let fixture = Fixture::new();
|
||||
let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap();
|
||||
assert!(stable.is_none() && !warning);
|
||||
let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap();
|
||||
assert!(!warning);
|
||||
let first = first.unwrap();
|
||||
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
|
||||
let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap();
|
||||
assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage");
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
|
||||
first.complete().unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
|
||||
let fixture = Fixture::new();
|
||||
let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap();
|
||||
assert!(!first.previous_unclean());
|
||||
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none());
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record");
|
||||
first.complete().unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
let unimportant = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap();
|
||||
assert!(!unimportant.previous_unclean());
|
||||
drop(unimportant); // 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());
|
||||
// The window never started: no notice was shown.
|
||||
let failed = Session::begin(Some(&fixture.0), "startup-failed", None).unwrap().unwrap();
|
||||
assert!(failed.previous_unclean());
|
||||
failed.finish(false).unwrap();
|
||||
// The next start still sees the interruption and shows it.
|
||||
let next = Session::begin(Some(&fixture.0), "next", None).unwrap().unwrap();
|
||||
assert!(next.previous_unclean());
|
||||
next.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::<std::collections::BTreeSet<_>>();
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,9 +15,11 @@ use wordcraft_ui_egui::prefs::{Prefs, import_legacy_window, legacy_ui_json};
|
||||
/// The most of an old `ui.json` read for its window entry; the file is a few kilobytes.
|
||||
const LEGACY_LIMIT: u64 = 8 << 20;
|
||||
|
||||
/// Whether this run reads and writes preferences. `WORDCRAFT_NO_PREFS` turns them off.
|
||||
/// Whether this run reads and writes preferences. `WORDCRAFT_NO_PREFS` turns them off; a Nightly
|
||||
/// profile always keeps its own, so an inherited developer switch cannot leave the app with no
|
||||
/// preferences folder at all.
|
||||
pub fn enabled() -> bool {
|
||||
std::env::var_os("WORDCRAFT_NO_PREFS").is_none()
|
||||
crate::launch_profile::current().is_nightly() || std::env::var_os("WORDCRAFT_NO_PREFS").is_none()
|
||||
}
|
||||
|
||||
/// `custom-dictionary.txt` in the settings folder: the words Add to Dictionary kept (#40).
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
//! Set the immutable nightly Windows identity before any native window or COM service.
|
||||
//! Stable deliberately leaves its implicit shortcut/path identity unchanged.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
#[derive(Clone, Debug, thiserror::Error)]
|
||||
pub enum IdentityError {
|
||||
#[error("{0}")]
|
||||
Configuration(String),
|
||||
}
|
||||
|
||||
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
|
||||
configure(nightly && cfg!(windows), app_id, |id| {
|
||||
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
|
||||
RESULT
|
||||
.get_or_init(|| {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
winsafe::SetCurrentProcessExplicitAppUserModelID(id)
|
||||
.map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
|
||||
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
|
||||
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
|
||||
if actual != id {
|
||||
return Err("the native Windows identity did not match the selected nightly channel".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = id;
|
||||
Ok(())
|
||||
}
|
||||
})
|
||||
.clone()
|
||||
})
|
||||
.map_err(IdentityError::Configuration)
|
||||
}
|
||||
|
||||
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
|
||||
if explicit_nightly { set(app_id) } else { Ok(()) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn stable_does_not_call_the_explicit_identity_api() {
|
||||
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_applies_the_supplied_identity_once() {
|
||||
let calls = std::cell::Cell::new(0);
|
||||
configure(true, "nightly-id", |id| {
|
||||
assert_eq!(id, "nightly-id");
|
||||
calls.set(calls.get() + 1);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(calls.get(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
|
||||
let started = std::cell::Cell::new(false);
|
||||
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
|
||||
assert_eq!(result.unwrap_err(), "native identity refused");
|
||||
assert!(!started.get());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,535 @@
|
||||
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
|
||||
//!
|
||||
//! WordCraft keeps all of its user state in one settings folder (`wordcraft_control_key::settings_dir`):
|
||||
//! `config.toml`, `window.json`, `logs/`, `recovery/`, `fonts/`, `Templates/`,
|
||||
//! `custom-dictionary.txt` and the control token files. The suite's shared font store
|
||||
//! (`Craft Fonts` / `craft-fonts`, which also holds installed Language packs) is the one other
|
||||
//! per-user folder the app writes, and Nightly points it at the profile too
|
||||
//! (`wordcraft_engine::packs::use_font_store_in`). Every stable location of either is fenced here.
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
/// The app id of the nightly Flatpak this build ships in (`packaging/linux/flatpak-bundle.sh`).
|
||||
pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.wordcraft.nightly";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Platform {
|
||||
Windows,
|
||||
Linux,
|
||||
Mac,
|
||||
}
|
||||
|
||||
impl Platform {
|
||||
fn current() -> Result<Self, String> {
|
||||
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<PathBuf, String> {
|
||||
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<OsString>, key: &str) -> Result<PathBuf, String> {
|
||||
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<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
|
||||
match env(key).filter(|v| !v.is_empty()) {
|
||||
Some(value) => absolute(PathBuf::from(value), key),
|
||||
None => Ok(required_base(env, "HOME")?.join(fallback)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
|
||||
/// is not a missing directory that may be replaced or followed later.
|
||||
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
|
||||
let mut parent = path;
|
||||
let mut missing = Vec::new();
|
||||
loop {
|
||||
match std::fs::symlink_metadata(parent) {
|
||||
Ok(_) => break,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
|
||||
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
|
||||
}
|
||||
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
|
||||
}
|
||||
}
|
||||
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
|
||||
for part in missing.into_iter().rev() {
|
||||
resolved.push(part);
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
|
||||
let parts = |p: &Path| {
|
||||
p.components()
|
||||
.map(|c| {
|
||||
let value = c.as_os_str().to_string_lossy().into_owned();
|
||||
if platform.ignores_case() { value.to_lowercase() } else { value }
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let (a, b) = (parts(a), parts(b));
|
||||
a.starts_with(&b) || b.starts_with(&a)
|
||||
}
|
||||
|
||||
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
|
||||
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
|
||||
if platform == Platform::Mac {
|
||||
// A profile in Resources is still inside the versioned install, not beside MacOS.
|
||||
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
|
||||
return Ok(bundle.to_path_buf());
|
||||
}
|
||||
}
|
||||
Ok(parent.to_path_buf())
|
||||
}
|
||||
|
||||
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
|
||||
let mut roots = match platform {
|
||||
Platform::Windows => {
|
||||
let mut roots = ["APPDATA", "LOCALAPPDATA"]
|
||||
.into_iter()
|
||||
.map(|key| required_base(env, key).map(|p| p.join("WordCraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
// The suite's shared font store and the MSI's default per-user and per-machine folders.
|
||||
roots.push(required_base(env, "LOCALAPPDATA")?.join("Craft Fonts"));
|
||||
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("WordCraft"));
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
|
||||
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("WordCraft"));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
Platform::Linux => {
|
||||
let mut roots =
|
||||
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
|
||||
.into_iter()
|
||||
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("wordcraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
// The shared font store (fonts and Language packs) and the native packages' locations.
|
||||
roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join("craft-fonts"));
|
||||
roots.extend(["/usr/bin/wordcraft", "/usr/local/bin/wordcraft", "/opt/wordcraft"].map(PathBuf::from));
|
||||
// The stable Flatpak keeps its data in its own per-app folder.
|
||||
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.wordcraft"));
|
||||
roots
|
||||
}
|
||||
Platform::Mac => {
|
||||
let home = required_base(env, "HOME")?;
|
||||
let library = home.join("Library");
|
||||
vec![
|
||||
library.join("Application Support/WordCraft"),
|
||||
library.join("Caches/WordCraft"),
|
||||
library.join("Caches/ai.storyteller.wordcraft"),
|
||||
library.join("Preferences/WordCraft"),
|
||||
library.join("Preferences/ai.storyteller.wordcraft.plist"),
|
||||
library.join("Saved Application State/ai.storyteller.wordcraft.savedState"),
|
||||
library.join("Application Support/Craft Fonts"),
|
||||
home.join("Applications/WordCraft.app"),
|
||||
PathBuf::from("/Applications/WordCraft.app"),
|
||||
]
|
||||
}
|
||||
};
|
||||
roots.push(installation_boundary(platform, exe)?);
|
||||
roots.into_iter().map(|p| canonical_future(&p)).collect()
|
||||
}
|
||||
|
||||
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
|
||||
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 (`config.toml`, `logs`, `recovery`, `fonts`,
|
||||
/// `Templates`, `window.json` and so on) must resolve inside it, so a link there cannot point
|
||||
/// Nightly's writes at another app's data.
|
||||
fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
let entries = match std::fs::read_dir(root) {
|
||||
Ok(entries) => entries,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The app's exclusive create probe: a file only this process can have made, created and removed.
|
||||
pub fn probe_writable(dir: &Path) -> std::io::Result<()> {
|
||||
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
let probe = dir.join(format!(".nightly-writable-{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
|
||||
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
|
||||
drop(file);
|
||||
std::fs::remove_file(probe)
|
||||
}
|
||||
|
||||
/// The writable hook is injected so filesystem boundary tests exercise the real policy without
|
||||
/// starting the app or creating the profile of the person running them.
|
||||
pub fn validate(
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
validate_for(Platform::current()?, root, env, exe, writable)
|
||||
}
|
||||
|
||||
fn validate_for(
|
||||
platform: Platform,
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
absolute(root.to_path_buf(), "the nightly profile root")?;
|
||||
// The developer switch that points a run at any folder: Nightly's folder comes from the Launcher.
|
||||
if env("WORDCRAFT_PROFILE_DIR").is_some_and(|v| !v.is_empty()) {
|
||||
return Err("nightly-v1 cannot be combined with WORDCRAFT_PROFILE_DIR".into());
|
||||
}
|
||||
// These rows are native tar/app-bundle launches, not a Flatpak package. Inheriting a Flatpak
|
||||
// runtime could point another profile at the stable app's token files; the nightly Flatpak
|
||||
// itself (`packaging/linux/flatpak-bundle.sh`) is the one sandbox this build ships in.
|
||||
if platform != Platform::Windows
|
||||
&& let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty())
|
||||
&& id != NIGHTLY_FLATPAK_ID
|
||||
{
|
||||
return Err("nightly-v1 native packages cannot inherit a Flatpak instance; launch through the native Launcher".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 its own subfolders elsewhere.
|
||||
entries_stay_inside(&chosen)?;
|
||||
// Recovery can read, adopt and sweep entries; a link there must never leave the profile.
|
||||
private_subdirectory(&chosen, "recovery", "recovery folder")?;
|
||||
let mut create = std::fs::DirBuilder::new();
|
||||
create.recursive(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::DirBuilderExt as _;
|
||||
create.mode(0o700);
|
||||
}
|
||||
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
|
||||
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
|
||||
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
|
||||
return Err("the nightly profile changed while it was being validated".into());
|
||||
}
|
||||
private_subdirectory(&confirmed, "recovery", "recovery folder")?;
|
||||
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<String, OsString>,
|
||||
exe: PathBuf,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let root = loop {
|
||||
let candidate =
|
||||
std::env::temp_dir().join(format!("wordcraft-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/wordcraft");
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
|
||||
std::fs::write(&exe, b"fixture executable, never run").unwrap();
|
||||
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
|
||||
.into_iter()
|
||||
.map(|(key, value)| (key.into(), value.into_os_string()))
|
||||
.collect();
|
||||
Self { root, env, exe }
|
||||
}
|
||||
|
||||
fn get(&self, key: &str) -> Option<OsString> {
|
||||
self.env.get(key).cloned()
|
||||
}
|
||||
|
||||
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
|
||||
validate_for(
|
||||
platform,
|
||||
root,
|
||||
|key| self.get(key),
|
||||
Some(&self.exe),
|
||||
|dir| {
|
||||
let probe = dir.join("exclusive-test-probe");
|
||||
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
|
||||
drop(file);
|
||||
std::fs::remove_file(probe)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn home(&self) -> PathBuf {
|
||||
PathBuf::from(self.get("HOME").unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
// Only the directory successfully created by this fixture is owned for removal.
|
||||
std::fs::remove_dir_all(&self.root).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_fences_the_settings_folders_font_store_and_packages_but_allows_the_launcher_sibling() {
|
||||
let mut fixture = Fixture::new();
|
||||
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
|
||||
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
|
||||
}
|
||||
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
|
||||
let stable = PathBuf::from(fixture.get(key).unwrap()).join("wordcraft");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
|
||||
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
|
||||
}
|
||||
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
|
||||
}
|
||||
let fonts = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap()).join("craft-fonts");
|
||||
std::fs::create_dir_all(fonts.join("language-packs")).unwrap();
|
||||
for candidate in [fonts.clone(), fonts.join("nightly")] {
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
|
||||
}
|
||||
for package in ["/usr/bin/wordcraft", "/usr/local/bin/wordcraft", "/opt/wordcraft"] {
|
||||
assert!(fixture.check(Platform::Linux, &PathBuf::from(package)).is_err());
|
||||
}
|
||||
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
|
||||
let nightly = data.join("ArtCraftLauncher/nightly/profiles/wordcraft");
|
||||
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
|
||||
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_fences_the_stable_flatpak_data_folder() {
|
||||
let fixture = Fixture::new();
|
||||
let flatpak = fixture.home().join(".var/app/ai.storyteller.wordcraft");
|
||||
for candidate in [flatpak.clone(), flatpak.join("data/nightly")] {
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
|
||||
}
|
||||
assert!(!flatpak.exists());
|
||||
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
|
||||
// Inside the Nightly Flatpak, XDG_DATA_HOME is this app's own persistent data folder, so
|
||||
// the launcher's profile lands there rather than on the discarded sandbox home.
|
||||
let nightly = fixture.home().join(".var/app/ai.storyteller.wordcraft.nightly/data/wordcraft-nightly");
|
||||
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_fences_the_app_library_subtrees_the_shared_font_store_and_the_whole_bundle() {
|
||||
let mut fixture = Fixture::new();
|
||||
fixture.exe = fixture.root.join("install/WordCraft Nightly.app/Contents/MacOS/WordCraft");
|
||||
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
|
||||
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
|
||||
let library = fixture.home().join("Library");
|
||||
for suffix in [
|
||||
"Application Support/WordCraft",
|
||||
"Caches/WordCraft",
|
||||
"Caches/ai.storyteller.wordcraft",
|
||||
"Preferences/WordCraft",
|
||||
"Saved Application State/ai.storyteller.wordcraft.savedState",
|
||||
"Application Support/Craft Fonts",
|
||||
] {
|
||||
let stable = library.join(suffix);
|
||||
assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(!stable.exists());
|
||||
}
|
||||
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
|
||||
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
|
||||
assert!(!inside_resources.exists());
|
||||
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/wordcraft");
|
||||
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_roaming_local_font_store_and_install_fences_remain_active() {
|
||||
let fixture = Fixture::new();
|
||||
let mut fixture = fixture;
|
||||
for key in ["APPDATA", "LOCALAPPDATA"] {
|
||||
let stable = PathBuf::from(fixture.get(key).unwrap()).join("WordCraft");
|
||||
assert!(fixture.check(Platform::Windows, &stable.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(!stable.exists());
|
||||
}
|
||||
let fonts = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Craft Fonts");
|
||||
assert!(fixture.check(Platform::Windows, &fonts.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(fixture.check(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_err());
|
||||
let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap());
|
||||
let per_user = local.join("Programs").join("ArtCraft").join("WordCraft");
|
||||
assert!(fixture.check(Platform::Windows, &per_user.join("nightly")).unwrap_err().contains("overlap"));
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
let base = fixture.root.join(format!("machine {key}"));
|
||||
fixture.env.insert(key.into(), base.clone().into_os_string());
|
||||
let machine = base.join("ArtCraft").join("WordCraft");
|
||||
assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(!machine.exists());
|
||||
}
|
||||
let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("wordcraft");
|
||||
assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not WordCraft's install");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
|
||||
let fixture = Fixture::new();
|
||||
let root = fixture.home().join("nightly/profiles/wordcraft");
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
assert!(overlaps(&root, &root.join("recovery"), platform));
|
||||
assert!(overlaps(&root.join("recovery"), &root, platform));
|
||||
assert!(!overlaps(&root, &root.with_file_name("wordcraft-other"), platform));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn recovery_and_entry_aliases_cannot_leave_the_profile_and_stable_bytes_stay_untouched() {
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".config/wordcraft/recovery");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
|
||||
for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() {
|
||||
let private = fixture.root.join(format!("nightly-{index}"));
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&target, private.join("recovery")).unwrap();
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&private,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.is_err(), "recovery must not escape the private profile or follow a dangling alias");
|
||||
assert!(!probed.get());
|
||||
}
|
||||
for name in ["logs", "fonts", "config.toml"] {
|
||||
let private = fixture.root.join(format!("nightly-entry-{name}"));
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_err(), "{name} must not lead outside the profile");
|
||||
}
|
||||
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
|
||||
assert_eq!(std::fs::read_dir(stable).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_recovery_alias_inside_the_profile_keeps_it_usable() {
|
||||
let fixture = Fixture::new();
|
||||
let private = fixture.root.join("nightly-private");
|
||||
let recovery = private.join("private-recovery");
|
||||
std::fs::create_dir_all(&recovery).unwrap();
|
||||
std::os::unix::fs::symlink(&recovery, private.join("recovery")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok());
|
||||
assert_eq!(std::fs::canonicalize(private.join("recovery")).unwrap(), recovery);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
|
||||
let mut fixture = Fixture::new();
|
||||
let candidate = fixture.home().join("nightly/profiles/wordcraft");
|
||||
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
|
||||
fixture.env.remove("XDG_CACHE_HOME");
|
||||
fixture.env.insert("WORDCRAFT_PROFILE_DIR".into(), fixture.home().join("custom-stable").into_os_string());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("WORDCRAFT_PROFILE_DIR"));
|
||||
fixture.env.remove("WORDCRAFT_PROFILE_DIR");
|
||||
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.wordcraft".into());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
|
||||
fixture.env.remove("FLATPAK_ID");
|
||||
// The nightly Flatpak is the one sandbox this build ships in, so its own id is accepted.
|
||||
let flatpak_profile = fixture.home().join("nightly/flatpak-profile");
|
||||
fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into());
|
||||
assert_eq!(fixture.check(Platform::Linux, &flatpak_profile).unwrap(), flatpak_profile);
|
||||
fixture.env.remove("FLATPAK_ID");
|
||||
fixture.env.remove("HOME");
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME"));
|
||||
assert!(!candidate.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_directory_and_failed_write_probe_never_fall_back_to_stable() {
|
||||
let fixture = Fixture::new();
|
||||
let file = fixture.home().join("not-a-directory");
|
||||
std::fs::write(&file, b"do not replace me").unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &file).is_err());
|
||||
assert_eq!(std::fs::read(file).unwrap(), b"do not replace me");
|
||||
let candidate = fixture.home().join("nightly");
|
||||
let calls = std::cell::Cell::new(0);
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&candidate,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
calls.set(calls.get() + 1);
|
||||
Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "injected write refusal"))
|
||||
},
|
||||
);
|
||||
assert!(result.unwrap_err().contains("not writable"));
|
||||
assert_eq!(calls.get(), 1);
|
||||
assert!(!fixture.home().join(".config/wordcraft").exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn symlink_and_dangling_aliases_cannot_create_or_modify_stable_data() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".config/wordcraft");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("sentinel"), b"untouched").unwrap();
|
||||
let alias = fixture.home().join("alias");
|
||||
symlink(&stable, &alias).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &alias.join("nightly")).unwrap_err().contains("overlap"));
|
||||
let missing = fixture.home().join("missing-target");
|
||||
let dangling = fixture.home().join("dangling");
|
||||
symlink(&missing, &dangling).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &dangling.join("nightly")).is_err());
|
||||
assert!(!missing.exists());
|
||||
assert!(!stable.join("nightly").exists());
|
||||
assert_eq!(std::fs::read(stable.join("sentinel")).unwrap(), b"untouched");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
# WordCraft app icon
|
||||
|
||||
A **page and pen**: a sheet of paper with a folded corner and ruled lines, with a fountain pen
|
||||
lying across its lower right, on the app's blue field. It is drawn in the canvas palette the app's
|
||||
own artwork uses (`#3b5bdb` field, `#efe9dc` paper, `#0b0b0c` ink).
|
||||
|
||||
`wordcraft.svg` is the canonical master: a full-bleed 512-unit tile with a rounded square
|
||||
(`rx=112`) and no border. Windows and Linux use the tile as it is; the macOS renders sit on
|
||||
Apple's grid, an 824/1024 body with a transparent margin.
|
||||
|
||||
## Files
|
||||
|
||||
- `wordcraft.svg`: canonical master (also the hicolor scalable icon).
|
||||
- `wordcraft-1024.png`: 1024 px full-bleed render.
|
||||
- `wordcraft-macos-512.png`: the padded macOS render (Dock, window icon; embedded by the app).
|
||||
- `wordcraft.icns`: macOS bundle icon (`CFBundleIconFile`), padded frames.
|
||||
- `wordcraft.ico`: Windows icon, 16–256 px, embedded in `wordcraft.exe` by
|
||||
`apps/wordcraft/build.rs`.
|
||||
- `hicolor/<size>/apps/ai.storyteller.wordcraft.png` (16–512) and `hicolor/scalable/...svg`:
|
||||
Linux icon theme.
|
||||
|
||||
## Regenerate
|
||||
|
||||
Replace `wordcraft.svg`, then run `packaging/icons.sh`. It needs `resvg`, plus `iconutil` on macOS;
|
||||
`cargo run -p xtask -- ico` packs the Windows icon.
|
||||
|
||||
## Nightly channel
|
||||
|
||||
The Nightly icons keep the drawing, its alpha and the macOS padding exactly as the stable renders
|
||||
have them. Only the background contribution changes: from the app blue to the deeper Nightly
|
||||
background `#232c67`. There is no letter badge, crescent or other mark; the app and the Launcher
|
||||
name the channel in text.
|
||||
|
||||
`packaging/nightly-icons.py` derives the four files from the committed stable renders (the `.ico`
|
||||
frames, the `.icns` slots, the 256 px hicolor render and the padded 512 px macOS master) and
|
||||
records their hashes in [`nightly-provenance.json`](nightly-provenance.json). `--check` re-derives
|
||||
them and compares. The three smallest macOS slots (16, 32 and 64 px) are box-filtered from the
|
||||
padded master; every other frame is the same size as the stable frame it comes from, so nothing is
|
||||
upscaled. The stable files are not modified.
|
||||
@@ -0,0 +1,72 @@
|
||||
{
|
||||
"title": "WordCraft nightly deep-background icons",
|
||||
"author": "@skylartaylor",
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"source_commit": null,
|
||||
"inputs": [
|
||||
{
|
||||
"path": "assets/app-icon/hicolor/256x256/apps/ai.storyteller.wordcraft.png",
|
||||
"sha256": "7c1791408282d01e8c5d0cb1f4080971eaa412c60518694a1cec1e60b23c7406",
|
||||
"purpose": "Windows/Linux native256 master"
|
||||
},
|
||||
{
|
||||
"path": "assets/app-icon/wordcraft.ico",
|
||||
"sha256": "53a23dcf66260f44d87d4d143d633395f3e967f391eda47e6e9cc3a52f820225",
|
||||
"purpose": "nine full-bleed frames, 16-256 px"
|
||||
},
|
||||
{
|
||||
"path": "assets/app-icon/wordcraft.icns",
|
||||
"sha256": "02ac9dcb7ee06858416c7ef70ca2b359cad38dbef4a0b526bb1f28953d90170f",
|
||||
"purpose": "padded macOS frames, 32-1024 px"
|
||||
},
|
||||
{
|
||||
"path": "assets/app-icon/wordcraft-macos-512.png",
|
||||
"sha256": "5a8a4476c1fb67123f803a8ab7a7a0dbd9912675ae54d695c17e74454913ceae",
|
||||
"purpose": "padded macOS master (box-filtered down to the 16/32/64 px slots, never upscaled)"
|
||||
}
|
||||
],
|
||||
"method": {
|
||||
"kind": "derived from the project-owned stable renders by a committed, reproducible script",
|
||||
"original_palette": {
|
||||
"ink": "#0b0b0c",
|
||||
"paper": "#efe9dc",
|
||||
"background": "#3b5bdb"
|
||||
},
|
||||
"nightly_background": "#232c67",
|
||||
"transform": "Decompose every pixel in the stable three-colour palette (ink, paper, background) and rebuild it with the Nightly background, keeping the ink and paper weights, alpha and padding. Clamped and renormalised where an antialiased pixel falls outside the triangle. No crescent, letter or badge.",
|
||||
"generator": "packaging/nightly-icons.py",
|
||||
"generator_sha256": "7a31bc6d3a00d991cf4fd6b1f2ce06b3bdc9201525d207ba84a935a877ee8e4a",
|
||||
"reproduce": "python3 packaging/nightly-icons.py --check"
|
||||
},
|
||||
"outputs": {
|
||||
"assets/app-icon/wordcraft-nightly.png": "43a002255f6db703599de99224cd47274905b8742d92f91d0f7c41c8cb5656e2",
|
||||
"assets/app-icon/wordcraft-nightly.ico": "f4bb314bb6c8c131c7250e441407be5e22e645579881f0a80fe7bd963adda54a",
|
||||
"assets/app-icon/wordcraft-nightly-1024.png": "36e21d31b852ac222c787ee27af45667882353eb9b1c3bfb62a9038c17843b25",
|
||||
"assets/app-icon/wordcraft-nightly.icns": "0b359aa7f07fda079298a97215da207486ca092bbe9c6b277a5de3d3fbc4f9ef"
|
||||
},
|
||||
"ico_frame_sizes": [
|
||||
16,
|
||||
20,
|
||||
24,
|
||||
32,
|
||||
40,
|
||||
48,
|
||||
64,
|
||||
128,
|
||||
256
|
||||
],
|
||||
"icns_png_slots": {
|
||||
"icp4": 16,
|
||||
"icp5": 32,
|
||||
"icp6": 64,
|
||||
"ic07": 128,
|
||||
"ic08": 256,
|
||||
"ic13": 256,
|
||||
"ic09": 512,
|
||||
"ic14": 512,
|
||||
"ic10": 1024,
|
||||
"ic11": 32,
|
||||
"ic12": 64
|
||||
},
|
||||
"validation": "Every output is re-derived from the committed inputs by the committed script (--check) and compared by SHA-256; the frames' pixel dimensions and the containers' members are checked while deriving; the foreground and padding were compared visually against the stable renders. Native Explorer/Finder qualification is unrun."
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 22 KiB |
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 4.1 KiB |
@@ -4,14 +4,34 @@
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The folder the desktop app chose before any of its state was read: a Launcher-selected
|
||||
/// Nightly profile (`launch_profile`). Set once, at startup, before the first [`settings_dir`]
|
||||
/// call; tests and the CLI leave it unset.
|
||||
static CHOSEN: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
|
||||
|
||||
/// Point [`settings_dir`] at `dir` for this process. Fails when a folder was already chosen.
|
||||
pub fn use_settings_dir(dir: PathBuf) -> Result<(), String> {
|
||||
CHOSEN.set(dir).map_err(|_| "the settings folder was already selected".into())
|
||||
}
|
||||
|
||||
/// The app's settings folder (preferences, logs, token files): macOS
|
||||
/// `~/Library/Application Support/WordCraft`, Windows `%APPDATA%\WordCraft`, otherwise
|
||||
/// `$XDG_CONFIG_HOME/wordcraft` or `~/.config/wordcraft`.
|
||||
/// `WORDCRAFT_PROFILE_DIR` overrides the entire folder for isolated runs.
|
||||
/// A folder chosen by the app through [`use_settings_dir`] wins: it is a launch decision, not
|
||||
/// an environment variable a child or a wrapper might have inherited. `WORDCRAFT_PROFILE_DIR`
|
||||
/// overrides the entire folder for isolated runs otherwise.
|
||||
pub fn settings_dir() -> Option<PathBuf> {
|
||||
if let Some(path) = CHOSEN.get() {
|
||||
return Some(path.clone());
|
||||
}
|
||||
if let Some(path) = std::env::var_os("WORDCRAFT_PROFILE_DIR").filter(|p| !p.is_empty()) {
|
||||
return Some(PathBuf::from(path));
|
||||
}
|
||||
platform_settings_dir()
|
||||
}
|
||||
|
||||
/// The platform's own folder, when nothing chose one (see [`settings_dir`]).
|
||||
fn platform_settings_dir() -> Option<PathBuf> {
|
||||
if cfg!(target_os = "macos") {
|
||||
std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/WordCraft"))
|
||||
} else if cfg!(windows) {
|
||||
@@ -67,6 +87,18 @@ mod tests {
|
||||
assert_eq!(parse_instance_id("app=ai.storyteller.wordcraft\n"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chosen_folder_wins_over_the_environment() {
|
||||
// The chosen folder is process-wide and set once, so this test only reads the rule when
|
||||
// nothing chose one (the crate's own tests and the CLI never do).
|
||||
if CHOSEN.get().is_none() {
|
||||
assert_eq!(settings_dir(), super::platform_settings_dir());
|
||||
assert!(use_settings_dir(PathBuf::from("/chosen/profile")).is_ok());
|
||||
assert_eq!(settings_dir().as_deref(), Some(std::path::Path::new("/chosen/profile")));
|
||||
assert!(use_settings_dir(PathBuf::from("/other")).is_err(), "the folder is selected once");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn key_file_per_instance() {
|
||||
let dir = Path::new("/settings/wordcraft");
|
||||
|
||||
@@ -102,6 +102,8 @@ impl WordApp {
|
||||
command_catalog_lang: "",
|
||||
key_overrides: Default::default(),
|
||||
command_states: Default::default(),
|
||||
command_states_cache: None,
|
||||
keytip_cache: None,
|
||||
fonts_frames: 0,
|
||||
clipboard_published: false,
|
||||
printing: Default::default(),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! The app's side of the framework command runtime: the catalog of commands and their default
|
||||
//! chords, the per-frame state (enabled, checked, hint) and the running of what the runtime fired.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::keymap::Overrides;
|
||||
@@ -83,6 +83,62 @@ fn with_word_chords(catalog: AppCatalog) -> AppCatalog {
|
||||
.fold(catalog, |catalog, command| catalog.replace_defaults(command.id(), Vec::new()))
|
||||
}
|
||||
|
||||
/// Precomputed command references, translated hints, and last gate results for
|
||||
/// [`WordApp::command_input`], rebuilt when the engine registry or interface language changes.
|
||||
///
|
||||
/// Every command's gate predicate still runs on every frame so enabled/disabled state is never
|
||||
/// stale; only the per-frame `CATALOG.lines()` parsing, `i18n` hint formatting, and full
|
||||
/// `CommandStates` map rebuild are skipped when nothing changed.
|
||||
pub(crate) struct CommandStatesCache {
|
||||
registry: Arc<wordcraft_engine::Registry>,
|
||||
lang: &'static str,
|
||||
/// `(id, location, label, prebuilt CommandRef, last (enabled, reason))` for every registered
|
||||
/// engine command, in registry order.
|
||||
registered: Vec<(&'static str, &'static str, &'static str, CommandRef, Option<(bool, Option<&'static str>)>)>,
|
||||
/// `(id, prebuilt CommandRef, last enabled)` for gated `ui.*` commands.
|
||||
ui_commands: Vec<(&'static str, CommandRef, Option<bool>)>,
|
||||
/// `(id, prebuilt CommandRef, last enabled)` for unimplemented Word catalog commands.
|
||||
unimplemented: Vec<(&'static str, CommandRef, Option<bool>)>,
|
||||
/// Precomputed `CommandRef` and last enabled state for `ui.dialog {"name": "commands"}`.
|
||||
commands_dialog: (CommandRef, Option<bool>),
|
||||
/// Translated fallback hint shared by all unimplemented catalog commands.
|
||||
unavailable_hint: Option<Arc<str>>,
|
||||
/// Cached translated hints by `(spec index, disabled reason)` for the current language.
|
||||
hints: HashMap<(usize, Option<&'static str>), Option<Arc<str>>>,
|
||||
}
|
||||
|
||||
impl CommandStatesCache {
|
||||
fn new(registry: Arc<wordcraft_engine::Registry>, lang: &'static str) -> Self {
|
||||
let registered = registry.all().iter().map(|spec| (spec.id, spec.location, spec.label, CommandRef::new(spec.id), None)).collect();
|
||||
let ui_commands = ["ui.collapseRibbon", "ui.resetInterfaceSize", "ui.print", "ui.printSubmit"]
|
||||
.into_iter()
|
||||
.chain(GATED_UI_COMMANDS.iter().map(|(id, _)| *id))
|
||||
.map(|id| (id, CommandRef::new(id), None))
|
||||
.collect();
|
||||
let unimplemented = unimplemented_catalog_commands(®istry).map(|(id, _)| (id, CommandRef::new(id), None)).collect();
|
||||
let commands_dialog = (CommandRef::with_params("ui.dialog", json!({"name": "commands"})), None);
|
||||
let unavailable_hint = crate::widgets::command_hint("", "", Some("")).map(Arc::from);
|
||||
CommandStatesCache { registry, lang, registered, ui_commands, unimplemented, commands_dialog, unavailable_hint, hints: HashMap::new() }
|
||||
}
|
||||
|
||||
fn matches(&self, registry: &Arc<wordcraft_engine::Registry>, lang: &'static str) -> bool {
|
||||
self.lang == lang && Arc::ptr_eq(&self.registry, registry)
|
||||
}
|
||||
|
||||
fn hint_for(&mut self, idx: usize, location: &str, label: &str, reason: Option<&'static str>) -> Option<Arc<str>> {
|
||||
self.hints.entry((idx, reason)).or_insert_with(|| crate::widgets::command_hint(location, label, reason).map(Arc::from)).clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Gate check for a command known to live in `app.session.registry` (skips the extra registry lookup).
|
||||
fn gate_registered(app: &WordApp, id: &str) -> (bool, Option<&'static str>) {
|
||||
if !app.has_document() && !super::commands::works_without_document(id) {
|
||||
return (false, None);
|
||||
}
|
||||
let reason = app.session.why_disabled(id);
|
||||
(reason.is_none(), reason)
|
||||
}
|
||||
|
||||
impl WordApp {
|
||||
/// The app's commands as the keymap knows them: every engine command with its default
|
||||
/// chords, then the interface commands. The interface commands come last because a tie in the
|
||||
@@ -177,36 +233,108 @@ impl WordApp {
|
||||
if let Some(catalog) = self.catalog() {
|
||||
input = input.catalog(catalog);
|
||||
}
|
||||
let mut states = CommandStates::new();
|
||||
for spec in registry.all() {
|
||||
let (enabled, reason) = gate(self, spec.id); // A toggle's checked state is bound at its ribbon button, not here.
|
||||
let mut state = CommandState::new().enabled(enabled);
|
||||
if let Some(hint) = crate::widgets::command_hint(spec.location, spec.label, reason) {
|
||||
state = state.hint(hint);
|
||||
let lang = crate::i18n::current().code();
|
||||
let fresh_cache = !self.command_states_cache.as_ref().is_some_and(|cache| cache.matches(®istry, lang));
|
||||
let mut cache = if fresh_cache {
|
||||
CommandStatesCache::new(registry, lang)
|
||||
} else {
|
||||
self.command_states_cache.take().unwrap_or_else(|| CommandStatesCache::new(registry, lang))
|
||||
};
|
||||
|
||||
if fresh_cache {
|
||||
let mut states = CommandStates::new();
|
||||
for i in 0..cache.registered.len() {
|
||||
let (id, location, label, _, _) = cache.registered[i];
|
||||
let current = gate_registered(self, id);
|
||||
cache.registered[i].4 = Some(current);
|
||||
let mut state = CommandState::new().enabled(current.0);
|
||||
if let Some(hint) = cache.hint_for(i, location, label, current.1) {
|
||||
state = state.hint(hint);
|
||||
}
|
||||
states.set(cache.registered[i].3.clone(), state);
|
||||
}
|
||||
states.set(CommandRef::new(spec.id), state);
|
||||
}
|
||||
// Print acts on the document, so with none open it is off like the engine's commands (#1129); a command with
|
||||
// no state here resolves as enabled.
|
||||
let ids = ["ui.collapseRibbon", "ui.resetInterfaceSize", "ui.print", "ui.printSubmit"]
|
||||
.into_iter()
|
||||
.chain(GATED_UI_COMMANDS.iter().map(|(id, _)| *id));
|
||||
for id in ids {
|
||||
states.set(CommandRef::new(id), CommandState::new().enabled(command_enabled(self, id)));
|
||||
}
|
||||
let unavailable_hint: Option<Arc<str>> = crate::widgets::command_hint("", "", Some("")).map(Arc::from);
|
||||
for (id, _) in unimplemented_catalog_commands(®istry) {
|
||||
let mut state = CommandState::new().enabled(command_enabled(self, id));
|
||||
if let Some(hint) = unavailable_hint.as_ref() {
|
||||
state = state.hint(Arc::clone(hint));
|
||||
for i in 0..cache.ui_commands.len() {
|
||||
let id = cache.ui_commands[i].0;
|
||||
let enabled = command_enabled(self, id);
|
||||
cache.ui_commands[i].2 = Some(enabled);
|
||||
states.set(cache.ui_commands[i].1.clone(), CommandState::new().enabled(enabled));
|
||||
}
|
||||
states.set(CommandRef::new(id), state);
|
||||
for i in 0..cache.unimplemented.len() {
|
||||
let id = cache.unimplemented[i].0;
|
||||
let enabled = command_enabled(self, id);
|
||||
cache.unimplemented[i].2 = Some(enabled);
|
||||
let mut state = CommandState::new().enabled(enabled);
|
||||
if let Some(hint) = cache.unavailable_hint.as_ref() {
|
||||
state = state.hint(Arc::clone(hint));
|
||||
}
|
||||
states.set(cache.unimplemented[i].1.clone(), state);
|
||||
}
|
||||
let dialog_enabled = command_enabled(self, "ui.dialog");
|
||||
cache.commands_dialog.1 = Some(dialog_enabled);
|
||||
states.set(cache.commands_dialog.0.clone(), CommandState::new().enabled(dialog_enabled));
|
||||
if *self.command_states != states {
|
||||
self.command_states.edit(|kept| *kept = states);
|
||||
}
|
||||
self.command_states_cache = Some(cache);
|
||||
return input.states(&self.command_states);
|
||||
}
|
||||
let commands = CommandRef::with_params("ui.dialog", json!({"name": "commands"}));
|
||||
states.set(commands, CommandState::new().enabled(command_enabled(self, "ui.dialog")));
|
||||
if *self.command_states != states {
|
||||
self.command_states.edit(|kept| *kept = states);
|
||||
|
||||
// Steady-state path: re-evaluate every gate without allocating, and only touch
|
||||
// `self.command_states` when at least one command's gate actually changed.
|
||||
let mut reg_changes: Vec<(usize, bool, Option<&'static str>)> = Vec::new();
|
||||
for (i, &(id, _, _, _, last)) in cache.registered.iter().enumerate() {
|
||||
let current = gate_registered(self, id);
|
||||
if last != Some(current) {
|
||||
reg_changes.push((i, current.0, current.1));
|
||||
}
|
||||
}
|
||||
let mut ui_changes: Vec<(usize, bool)> = Vec::new();
|
||||
for (i, &(id, _, last)) in cache.ui_commands.iter().enumerate() {
|
||||
let enabled = command_enabled(self, id);
|
||||
if last != Some(enabled) {
|
||||
ui_changes.push((i, enabled));
|
||||
}
|
||||
}
|
||||
let mut unimpl_changes: Vec<(usize, bool)> = Vec::new();
|
||||
for (i, &(id, _, last)) in cache.unimplemented.iter().enumerate() {
|
||||
let enabled = command_enabled(self, id);
|
||||
if last != Some(enabled) {
|
||||
unimpl_changes.push((i, enabled));
|
||||
}
|
||||
}
|
||||
let dialog_enabled = command_enabled(self, "ui.dialog");
|
||||
let dialog_changed = cache.commands_dialog.1 != Some(dialog_enabled);
|
||||
|
||||
if !reg_changes.is_empty() || !ui_changes.is_empty() || !unimpl_changes.is_empty() || dialog_changed {
|
||||
self.command_states.edit(|kept| {
|
||||
for (i, enabled, reason) in reg_changes {
|
||||
let (_, location, label, _, _) = cache.registered[i];
|
||||
cache.registered[i].4 = Some((enabled, reason));
|
||||
let mut state = CommandState::new().enabled(enabled);
|
||||
if let Some(hint) = cache.hint_for(i, location, label, reason) {
|
||||
state = state.hint(hint);
|
||||
}
|
||||
kept.set(cache.registered[i].3.clone(), state);
|
||||
}
|
||||
for (i, enabled) in ui_changes {
|
||||
cache.ui_commands[i].2 = Some(enabled);
|
||||
kept.set(cache.ui_commands[i].1.clone(), CommandState::new().enabled(enabled));
|
||||
}
|
||||
for (i, enabled) in unimpl_changes {
|
||||
cache.unimplemented[i].2 = Some(enabled);
|
||||
let mut state = CommandState::new().enabled(enabled);
|
||||
if let Some(hint) = cache.unavailable_hint.as_ref() {
|
||||
state = state.hint(Arc::clone(hint));
|
||||
}
|
||||
kept.set(cache.unimplemented[i].1.clone(), state);
|
||||
}
|
||||
if dialog_changed {
|
||||
cache.commands_dialog.1 = Some(dialog_enabled);
|
||||
kept.set(cache.commands_dialog.0.clone(), CommandState::new().enabled(dialog_enabled));
|
||||
}
|
||||
});
|
||||
}
|
||||
self.command_states_cache = Some(cache);
|
||||
input.states(&self.command_states)
|
||||
}
|
||||
|
||||
@@ -321,4 +449,42 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Cached `command_input()` keeps steady-state idle calls zero-change while immediately reflecting
|
||||
/// table/context transitions and document-open state changes.
|
||||
#[test]
|
||||
fn command_input_cache_tracks_state_transitions_and_is_noop_when_idle() {
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
let _ = app.command_input();
|
||||
let rev_after_first = app.command_states.revision();
|
||||
assert!(
|
||||
!app.command_states.get(&CommandRef::new("table.deleteRow")).unwrap().is_enabled(),
|
||||
"table.deleteRow starts disabled outside a table"
|
||||
);
|
||||
assert!(app.command_states.get(&CommandRef::new("format.bold")).unwrap().is_enabled(), "format.bold starts enabled");
|
||||
|
||||
// Repeated idle calls must not mutate `command_states` or bump its revision.
|
||||
for _ in 0..5 {
|
||||
let _ = app.command_input();
|
||||
}
|
||||
assert_eq!(app.command_states.revision(), rev_after_first, "idle frames leave command_states revision untouched");
|
||||
|
||||
// Entering a table enables `table.deleteRow` immediately on the next `command_input()`.
|
||||
app.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
|
||||
let _ = app.command_input();
|
||||
let rev_after_table = app.command_states.revision();
|
||||
assert_ne!(rev_after_table, rev_after_first, "state change bumps command_states revision");
|
||||
assert!(app.command_states.get(&CommandRef::new("table.deleteRow")).unwrap().is_enabled(), "table.deleteRow is enabled inside a table");
|
||||
|
||||
// Closing the document disables document commands immediately.
|
||||
app.no_document = Some(app.session.document_id());
|
||||
let _ = app.command_input();
|
||||
assert!(!app.command_states.get(&CommandRef::new("format.bold")).unwrap().is_enabled(), "format.bold disables when no document is open");
|
||||
|
||||
// Dropping the cache and rebuilding from scratch must produce the exact same `CommandStates`.
|
||||
let incremental = (*app.command_states).clone();
|
||||
app.command_states_cache = None;
|
||||
let _ = app.command_input();
|
||||
assert_eq!(*app.command_states, incremental, "incremental cache matches full rebuild exactly");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,22 +66,59 @@ pub fn credits() -> Credits {
|
||||
}
|
||||
|
||||
/// The About tab's contents: name, blurb, version and build, and the project links in the old About's order (site,
|
||||
/// Discord, source), one to a line.
|
||||
/// Discord, source), one to a line. A Nightly window names its channel, its exact feed version
|
||||
/// and commit, and offers a link to report a problem.
|
||||
pub fn about_info() -> AboutInfo {
|
||||
let build = option_env!("WORDCRAFT_BUILD_SHA").map(|s| s.get(..8).unwrap_or(s)).unwrap_or(tl!("development build"));
|
||||
// The dialog's own "Version {version}" words the line, so this is the number and the build only.
|
||||
let version = crate::i18n::fmt(tl!("{version} ({build})"), &[("version", env!("CARGO_PKG_VERSION")), ("build", build)]);
|
||||
AboutInfo::new(
|
||||
tl!("WordCraft").to_string(),
|
||||
tl!("A free, open-source word processor written from scratch in Rust.\nPart of the Crafting Apps from the ArtCraft team.").to_string(),
|
||||
version.to_string(),
|
||||
)
|
||||
.links([
|
||||
AboutLink::new(tl!("getartcraft.com/apps/wordcraft").to_string(), "https://getartcraft.com/apps/wordcraft"),
|
||||
AboutLink::new(tl!("Join us on Discord: discord.gg/artcraft").to_string(), "https://discord.gg/artcraft"),
|
||||
AboutLink::new(tl!("Source code: github.com/storytold/wordcraft").to_string(), "https://github.com/storytold/wordcraft"),
|
||||
])
|
||||
.built_with(tl!("MIT OR Apache-2.0. Copyright (c) 2026 ArtCraft Team and the WordCraft contributors.").to_string())
|
||||
about_info_for(crate::os_window::identity(), option_env!("WORDCRAFT_BUILD_SHA"))
|
||||
}
|
||||
|
||||
/// The About tab's three lines for `identity`: (name, blurb, version line). A Nightly window's
|
||||
/// are English only: they are not one of the stable catalogs' strings.
|
||||
fn about_text(identity: crate::os_window::LaunchIdentity, commit: Option<&str>) -> (String, String, String) {
|
||||
match identity {
|
||||
crate::os_window::LaunchIdentity::NightlyV1 => {
|
||||
let version = option_env!("WORDCRAFT_VERSION").unwrap_or(env!("CARGO_PKG_VERSION"));
|
||||
let commit = commit.filter(|value| !value.is_empty()).unwrap_or("unavailable");
|
||||
(
|
||||
crate::os_window::name_for(identity).to_string(),
|
||||
"A free, open-source word processor written from scratch in Rust.\nPart of the Crafting Apps from the ArtCraft team.".to_string(),
|
||||
format!("{version}\nCommit: {commit}"),
|
||||
)
|
||||
}
|
||||
crate::os_window::LaunchIdentity::Stable => {
|
||||
let build = commit.map(|s| s.get(..8).unwrap_or(s)).unwrap_or(tl!("development build"));
|
||||
// The dialog's own "Version {version}" words the line, so this is the number and the build only.
|
||||
let version = crate::i18n::fmt(tl!("{version} ({build})"), &[("version", env!("CARGO_PKG_VERSION")), ("build", build)]);
|
||||
(
|
||||
tl!("WordCraft").to_string(),
|
||||
tl!("A free, open-source word processor written from scratch in Rust.\nPart of the Crafting Apps from the ArtCraft team.")
|
||||
.to_string(),
|
||||
version.to_string(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn about_info_for(identity: crate::os_window::LaunchIdentity, commit: Option<&str>) -> AboutInfo {
|
||||
let (name, blurb, version) = about_text(identity, commit);
|
||||
if identity == crate::os_window::LaunchIdentity::NightlyV1 {
|
||||
return AboutInfo::new(name, blurb, version)
|
||||
.links([
|
||||
AboutLink::new("getartcraft.com/apps/wordcraft".to_string(), "https://getartcraft.com/apps/wordcraft"),
|
||||
AboutLink::new("Join us on Discord: discord.gg/artcraft".to_string(), "https://discord.gg/artcraft"),
|
||||
AboutLink::new("Source code: github.com/storytold/wordcraft".to_string(), "https://github.com/storytold/wordcraft"),
|
||||
// Opens only after a click; nothing is collected or sent automatically.
|
||||
AboutLink::new("Report a problem".to_string(), "https://github.com/storytold/wordcraft/issues"),
|
||||
])
|
||||
.built_with("MIT OR Apache-2.0. Copyright (c) 2026 ArtCraft Team and the WordCraft contributors.".to_string());
|
||||
}
|
||||
AboutInfo::new(name, blurb, version)
|
||||
.links([
|
||||
AboutLink::new(tl!("getartcraft.com/apps/wordcraft").to_string(), "https://getartcraft.com/apps/wordcraft"),
|
||||
AboutLink::new(tl!("Join us on Discord: discord.gg/artcraft").to_string(), "https://discord.gg/artcraft"),
|
||||
AboutLink::new(tl!("Source code: github.com/storytold/wordcraft").to_string(), "https://github.com/storytold/wordcraft"),
|
||||
])
|
||||
.built_with(tl!("MIT OR Apache-2.0. Copyright (c) 2026 ArtCraft Team and the WordCraft contributors.").to_string())
|
||||
}
|
||||
|
||||
/// The About dialog opened on `tab`, with the Language data tab after Models (`AboutTab::App(0)`). The name
|
||||
@@ -90,3 +127,39 @@ pub(crate) fn about(tab: AboutTab) -> HostedAbout {
|
||||
// PLAN: assumed `HostedAbout::layout(self, AboutLayout) -> Self` (look-dialogs-b framework fix)
|
||||
HostedAbout::new(about_info(), credits()).app_tab(language_data_tab()).tab(tab).layout(AboutLayout::Listed)
|
||||
}
|
||||
|
||||
/// A Nightly window's About names its channel, keeps the full feed version and commit, invents
|
||||
/// nothing when the commit is missing, and adds the report link the stable About does not have.
|
||||
#[cfg(test)]
|
||||
mod nightly_about_tests {
|
||||
use crate::os_window::LaunchIdentity;
|
||||
|
||||
const COMMIT: &str = "0123456789abcdef0123456789abcdef01234567";
|
||||
|
||||
#[test]
|
||||
fn nightly_about_names_the_channel_and_keeps_the_full_version_and_commit() {
|
||||
let (name, blurb, version) = super::about_text(LaunchIdentity::NightlyV1, Some(COMMIT));
|
||||
assert_eq!(name, "WordCraft Nightly");
|
||||
assert!(blurb.contains("word processor"));
|
||||
let package = option_env!("WORDCRAFT_VERSION").unwrap_or(env!("CARGO_PKG_VERSION"));
|
||||
assert_eq!(version, format!("{package}\nCommit: {COMMIT}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_about_invents_no_provenance_when_the_commit_is_missing() {
|
||||
for commit in [None, Some("")] {
|
||||
let (_, _, version) = super::about_text(LaunchIdentity::NightlyV1, commit);
|
||||
assert!(version.ends_with("\nCommit: unavailable"), "{version}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_nightly_about_offers_the_report_link_and_the_stable_name_is_unchanged() {
|
||||
let nightly = super::about_info_for(LaunchIdentity::NightlyV1, Some(COMMIT));
|
||||
assert!(nightly.links.iter().any(|link| link.url == "https://github.com/storytold/wordcraft/issues"));
|
||||
let stable = super::about_info_for(LaunchIdentity::Stable, Some(COMMIT));
|
||||
assert!(!stable.links.iter().any(|link| link.url == "https://github.com/storytold/wordcraft/issues"));
|
||||
let (name, _, _) = super::about_text(LaunchIdentity::Stable, Some(COMMIT));
|
||||
assert_eq!(name, "WordCraft");
|
||||
}
|
||||
}
|
||||
|
||||
+115
-52
@@ -3,7 +3,7 @@
|
||||
//! machine, badges, claimed keys) is the framework's `Keytips`; this module gives it WordCraft's
|
||||
//! tabs, controls, legacy sequences and regions.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
use craft::behavior::overlay::MinWidth;
|
||||
use craft::keymap::CommandRef;
|
||||
@@ -59,29 +59,32 @@ pub const SEARCH_LETTER: &str = "Q";
|
||||
/// Legacy menu keys (#1697): Word 2003 menu sequences Word for Windows still takes after Alt,
|
||||
/// observed there. Hidden, as in Word: no badges, not in Customize Keyboard. They start only on
|
||||
/// letters no tab keytip or Search uses (see the test).
|
||||
fn legacy() -> Vec<(&'static str, CommandRef)> {
|
||||
let cmd = CommandRef::new;
|
||||
let dialog = |name: &str| CommandRef::with_params("ui.dialog", serde_json::json!({ "name": name }));
|
||||
vec![
|
||||
("VU", cmd("view.fullScreenView")),
|
||||
("VP", cmd("view.printLayout")),
|
||||
("VW", cmd("view.webLayout")),
|
||||
("VO", cmd("view.outline")),
|
||||
("VN", cmd("view.draft")),
|
||||
("VD", cmd("view.navigationPane")),
|
||||
("VL", cmd("view.ruler")),
|
||||
("VZ", dialog("zoom")),
|
||||
("EL", cmd("select.all")),
|
||||
("EF", dialog("find")),
|
||||
("EE", dialog("replace")),
|
||||
("EG", dialog("goto")),
|
||||
("IS", dialog("symbol")),
|
||||
("IPF", cmd("insert.picture")),
|
||||
("OF", dialog("font")),
|
||||
("OP", dialog("paragraph")),
|
||||
("TW", cmd("review.wordCount")),
|
||||
("AIT", dialog("insertTable")),
|
||||
]
|
||||
fn legacy() -> &'static [(&'static str, CommandRef)] {
|
||||
static LEGACY: OnceLock<Vec<(&'static str, CommandRef)>> = OnceLock::new();
|
||||
LEGACY.get_or_init(|| {
|
||||
let cmd = CommandRef::new;
|
||||
let dialog = |name: &str| CommandRef::with_params("ui.dialog", serde_json::json!({ "name": name }));
|
||||
vec![
|
||||
("VU", cmd("view.fullScreenView")),
|
||||
("VP", cmd("view.printLayout")),
|
||||
("VW", cmd("view.webLayout")),
|
||||
("VO", cmd("view.outline")),
|
||||
("VN", cmd("view.draft")),
|
||||
("VD", cmd("view.navigationPane")),
|
||||
("VL", cmd("view.ruler")),
|
||||
("VZ", dialog("zoom")),
|
||||
("EL", cmd("select.all")),
|
||||
("EF", dialog("find")),
|
||||
("EE", dialog("replace")),
|
||||
("EG", dialog("goto")),
|
||||
("IS", dialog("symbol")),
|
||||
("IPF", cmd("insert.picture")),
|
||||
("OF", dialog("font")),
|
||||
("OP", dialog("paragraph")),
|
||||
("TW", cmd("review.wordCount")),
|
||||
("AIT", dialog("insertTable")),
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
/// The letter badge for a tab (empty when it has none).
|
||||
@@ -379,13 +382,82 @@ fn controls(tab: &str) -> Vec<Control> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A control with the letters it asks for.
|
||||
/// Maps an ASCII alphanumeric keytip letter to a static single-character `&'static str`, avoiding
|
||||
/// per-control `String` allocations when caching [`KeytipControl`].
|
||||
fn ascii_upper_str(c: char) -> Option<&'static str> {
|
||||
const CHARS: &str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
let idx = CHARS.find(c.to_ascii_uppercase())?;
|
||||
CHARS.get(idx..idx + 1)
|
||||
}
|
||||
|
||||
/// Cached keytip controls and reserved shortcut letters per engine registry and active ribbon tab,
|
||||
/// avoiding per-frame `registry.all()` scans and `KeytipControl` / `CommandRef` allocations while
|
||||
/// idle.
|
||||
pub(crate) struct KeytipCache {
|
||||
registry: Arc<wordcraft_engine::Registry>,
|
||||
reserved: Vec<char>,
|
||||
tab: String,
|
||||
tab_controls: Vec<KeytipControl<'static>>,
|
||||
}
|
||||
|
||||
impl KeytipCache {
|
||||
fn build_tab_controls(app: &WordApp, tab: &str) -> Vec<KeytipControl<'static>> {
|
||||
let mut out: Vec<KeytipControl<'static>> = controls(tab)
|
||||
.into_iter()
|
||||
.map(|control| {
|
||||
let letters = shortcut_letter(app, &control.command.id).and_then(ascii_upper_str);
|
||||
KeytipControl::new(control.command, control.tip, letters)
|
||||
})
|
||||
.collect();
|
||||
out.push(KeytipControl::new(CommandRef::new("tools.search"), "Search", Some(SEARCH_LETTER)));
|
||||
out
|
||||
}
|
||||
|
||||
fn new(app: &WordApp, tab: &str) -> Self {
|
||||
KeytipCache {
|
||||
registry: app.session.registry.clone(),
|
||||
reserved: reserved_letters(app),
|
||||
tab: tab.to_owned(),
|
||||
tab_controls: Self::build_tab_controls(app, tab),
|
||||
}
|
||||
}
|
||||
|
||||
fn sync(&mut self, app: &WordApp, tab: &str) {
|
||||
let reg_changed = !Arc::ptr_eq(&self.registry, &app.session.registry);
|
||||
if reg_changed {
|
||||
self.registry = app.session.registry.clone();
|
||||
self.reserved = reserved_letters(app);
|
||||
}
|
||||
if reg_changed || self.tab != tab {
|
||||
self.tab.clear();
|
||||
self.tab.push_str(tab);
|
||||
self.tab_controls = Self::build_tab_controls(app, tab);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Backstage's pages as cached static keytip controls.
|
||||
fn backstage_controls() -> &'static [KeytipControl<'static>] {
|
||||
static CONTROLS: OnceLock<Vec<KeytipControl<'static>>> = OnceLock::new();
|
||||
CONTROLS.get_or_init(|| {
|
||||
crate::backstage::KEYTIPS
|
||||
.iter()
|
||||
.map(|(page, letter)| {
|
||||
KeytipControl::new(CommandRef::with_params("ui.backstage", serde_json::json!({ "page": page })), page, Some(letter))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
|
||||
/// A control with the letters it asks for (used by unit tests).
|
||||
#[cfg(test)]
|
||||
struct Row {
|
||||
control: Control,
|
||||
letters: Option<String>,
|
||||
}
|
||||
|
||||
/// A tab's controls with the shortcut letter each keeps, when its command has an Alt+letter shortcut.
|
||||
#[cfg(test)]
|
||||
fn rows(app: &WordApp, tab: &str) -> Vec<Row> {
|
||||
controls(tab)
|
||||
.into_iter()
|
||||
@@ -396,22 +468,6 @@ fn rows(app: &WordApp, tab: &str) -> Vec<Row> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The Search box: its badge is Alt, Q on every tab.
|
||||
fn search_row() -> Row {
|
||||
Row { control: Control { tip: "Search", command: CommandRef::new("tools.search") }, letters: Some(SEARCH_LETTER.to_string()) }
|
||||
}
|
||||
|
||||
/// The Backstage's pages, one badge each: the first letter its page has in `KEYTIPS`.
|
||||
fn backstage_rows() -> Vec<Row> {
|
||||
crate::backstage::KEYTIPS
|
||||
.iter()
|
||||
.map(|(page, letter)| Row {
|
||||
control: Control { tip: page, command: CommandRef::with_params("ui.backstage", serde_json::json!({ "page": page })) },
|
||||
letters: Some(letter.to_string()),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Shows the keytips after the shell and the regions they place badges on, and acts on what the keys chose.
|
||||
pub(crate) fn show(ui: &mut Ui, app: &mut WordApp, ribbon: &RibbonOutput<String>, screen_bar: Option<Rect>) {
|
||||
let ctx = ui.ctx().clone();
|
||||
@@ -426,14 +482,15 @@ pub(crate) fn show(ui: &mut Ui, app: &mut WordApp, ribbon: &RibbonOutput<String>
|
||||
.filter_map(|t| ribbon.tab_ids.iter().find(|(name, _)| name == t).map(|(_, id)| (Label::from(t), tab_letter(t), *id)))
|
||||
.collect();
|
||||
|
||||
let mut rows = if app.ui.backstage { backstage_rows() } else { rows(app, &app.ui.tab) };
|
||||
if !app.ui.backstage {
|
||||
rows.push(search_row());
|
||||
}
|
||||
let controls: Vec<KeytipControl<'_>> =
|
||||
rows.iter().map(|r| KeytipControl::new(r.control.command.clone(), r.control.tip, r.letters.as_deref())).collect();
|
||||
|
||||
let sequences = if cfg!(target_os = "macos") { Vec::new() } else { legacy() };
|
||||
let cache = match app.keytip_cache.take() {
|
||||
Some(mut cache) => {
|
||||
cache.sync(app, &app.ui.tab);
|
||||
cache
|
||||
}
|
||||
None => KeytipCache::new(app, &app.ui.tab),
|
||||
};
|
||||
let controls: &[KeytipControl<'_>] = if app.ui.backstage { backstage_controls() } else { &cache.tab_controls };
|
||||
let sequences: &[(&str, CommandRef)] = if cfg!(target_os = "macos") { &[] } else { legacy() };
|
||||
// A hidden toolbar has no badges, and a disabled command's button has none to press.
|
||||
let digits: Vec<CommandRef> = if app.ui.quick_access_toolbar {
|
||||
app.session
|
||||
@@ -447,7 +504,6 @@ pub(crate) fn show(ui: &mut Ui, app: &mut WordApp, ribbon: &RibbonOutput<String>
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let reserved = reserved_letters(app);
|
||||
|
||||
let mut places: Vec<Arc<Recorded>> = Vec::new();
|
||||
places.extend(ribbon.controls.clone());
|
||||
@@ -457,8 +513,15 @@ pub(crate) fn show(ui: &mut Ui, app: &mut WordApp, ribbon: &RibbonOutput<String>
|
||||
places.extend(inspect::recorded(&ctx, backstage_region()));
|
||||
}
|
||||
|
||||
let out =
|
||||
Keytips::new(enabled).tabs(&tabs).controls(&controls).sequences(&sequences).digits(&digits).reserved(&reserved).places(&places).show_over(ui);
|
||||
let out = Keytips::new(enabled)
|
||||
.tabs(&tabs)
|
||||
.controls(controls)
|
||||
.sequences(sequences)
|
||||
.digits(&digits)
|
||||
.reserved(&cache.reserved)
|
||||
.places(&places)
|
||||
.show_over(ui);
|
||||
app.keytip_cache = Some(cache);
|
||||
// PLAN: `WordApp::keytips_active` is app-hub's (rb.A11).
|
||||
app.keytips_active = out.active;
|
||||
if let Some(tab) = out.tab.as_deref().and_then(tab_of_badge) {
|
||||
|
||||
@@ -83,7 +83,7 @@ fn legacy_menu_keys_stay_off_the_ribbon_letters_and_all_resolve() {
|
||||
for (keys, command) in legacy() {
|
||||
let first = &keys[..1];
|
||||
assert!(!taken.iter().any(|l| l.starts_with(first)), "{keys} starts on a ribbon letter");
|
||||
assert!(!legacy().iter().any(|(k, _)| *k != keys && k.starts_with(keys)), "{keys} hides a longer sequence");
|
||||
assert!(!legacy().iter().any(|(k, _)| *k != *keys && k.starts_with(*keys)), "{keys} hides a longer sequence");
|
||||
let mut b = app();
|
||||
// The hosted parameter dialogs open nothing before the window's context is known.
|
||||
b.ctx = Some(egui::Context::default());
|
||||
@@ -253,3 +253,25 @@ fn keytips_option_persists() {
|
||||
b.apply_prefs(serde_json::from_str("{}").unwrap());
|
||||
assert!(b.ui.keytips_enabled, "older preferences retain enabled KeyTips");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keytip_cache_reuses_tab_controls_and_updates_on_tab_switch() {
|
||||
let mut h = harness(app());
|
||||
assert_eq!(h.state().keytip_cache.as_ref().map(|c| c.tab.as_str()), Some("Home"));
|
||||
let home_ptr = h.state().keytip_cache.as_ref().unwrap().tab_controls.as_ptr();
|
||||
let reserved_ptr = h.state().keytip_cache.as_ref().unwrap().reserved.as_ptr();
|
||||
|
||||
// Idle frames reuse the cached control and reserved-letter buffers without rebuilding.
|
||||
crate::test_harness::frames(&mut h, 4);
|
||||
assert_eq!(h.state().keytip_cache.as_ref().unwrap().tab_controls.as_ptr(), home_ptr);
|
||||
assert_eq!(h.state().keytip_cache.as_ref().unwrap().reserved.as_ptr(), reserved_ptr);
|
||||
|
||||
// Switching tabs rebuilds the cached tab controls while keeping reserved letters intact.
|
||||
h.state_mut().run("ui.tab", serde_json::json!({"tab": "Insert"})).unwrap();
|
||||
crate::test_harness::frame(&mut h);
|
||||
let cache = h.state().keytip_cache.as_ref().unwrap();
|
||||
assert_eq!(cache.tab, "Insert");
|
||||
// Tab controls plus the trailing Search badge (`SEARCH_LETTER`).
|
||||
assert_eq!(cache.tab_controls.len(), controls("Insert").len() + 1);
|
||||
assert_eq!(cache.reserved.as_ptr(), reserved_ptr);
|
||||
}
|
||||
|
||||
@@ -55,6 +55,8 @@ pub mod md_source;
|
||||
pub mod mini_toolbar;
|
||||
pub mod objects;
|
||||
pub mod options;
|
||||
/// The window identity of the channel this build runs as (stable or Nightly).
|
||||
pub mod os_window;
|
||||
pub mod panes;
|
||||
pub mod paste_picture;
|
||||
pub mod prefs;
|
||||
@@ -400,6 +402,11 @@ pub struct WordApp {
|
||||
/// The app-scope command states handed to the runtime, edited only when they change: the runtime resolves
|
||||
/// commands again only when their revision moves ([`WordApp::command_input`]).
|
||||
pub(crate) command_states: craft::ui::contract::Tracked<craft::ui::runtime::commands::CommandStates>,
|
||||
/// Precomputed command metadata, translated hints, and last gate results for [`WordApp::command_input`],
|
||||
/// avoiding per-frame allocations and catalog reparsing while idle.
|
||||
pub(crate) command_states_cache: Option<app::command_board::CommandStatesCache>,
|
||||
/// Cached keytip control lists and reserved shortcut letters per registry and active ribbon tab.
|
||||
pub(crate) keytip_cache: Option<keytips::KeytipCache>,
|
||||
/// Frames drawn so far, counted to 2: the control channel's queued requests wait until the
|
||||
/// fonts are warm.
|
||||
pub(crate) fonts_frames: u8,
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
//! The app id every WordCraft OS window carries and the channel its title shows: the root window
|
||||
//! (`main.rs`), the runtime's windows (`InstallSpec::app_id`) and the document windows
|
||||
//! (`craft::window`), so docks show the WordCraft icon on them and Wayland compositors' window
|
||||
//! rules can match them. Without one the app id is empty.
|
||||
|
||||
/// Matches the `.desktop` file and hicolor icon name, so Wayland docks pick up the icon.
|
||||
pub const APP_ID: &str = "ai.storyteller.wordcraft";
|
||||
|
||||
/// Immutable startup identity. The desktop selects it before any UI/runtime service is created.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LaunchIdentity {
|
||||
Stable,
|
||||
NightlyV1,
|
||||
}
|
||||
|
||||
static IDENTITY: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
|
||||
|
||||
pub fn select_identity(identity: LaunchIdentity) -> Result<(), String> {
|
||||
let value = match identity {
|
||||
LaunchIdentity::Stable => 1,
|
||||
LaunchIdentity::NightlyV1 => 2,
|
||||
};
|
||||
IDENTITY
|
||||
.compare_exchange(0, value, std::sync::atomic::Ordering::AcqRel, std::sync::atomic::Ordering::Acquire)
|
||||
.map(|_| ())
|
||||
.map_err(|_| "the window launch identity was already selected".into())
|
||||
}
|
||||
|
||||
pub fn identity() -> LaunchIdentity {
|
||||
if IDENTITY.load(std::sync::atomic::Ordering::Acquire) == 2 { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable }
|
||||
}
|
||||
|
||||
pub const fn id_for(identity: LaunchIdentity) -> &'static str {
|
||||
match identity {
|
||||
LaunchIdentity::Stable => APP_ID,
|
||||
LaunchIdentity::NightlyV1 => "ai.storyteller.wordcraft.nightly-v1",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn app_id() -> &'static str {
|
||||
id_for(identity())
|
||||
}
|
||||
|
||||
pub const fn name_for(identity: LaunchIdentity) -> &'static str {
|
||||
match identity {
|
||||
LaunchIdentity::Stable => "WordCraft",
|
||||
LaunchIdentity::NightlyV1 => "WordCraft Nightly",
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn stable_services_for(identity: LaunchIdentity) -> bool {
|
||||
matches!(identity, LaunchIdentity::Stable)
|
||||
}
|
||||
|
||||
pub fn stable_services_allowed() -> bool {
|
||||
stable_services_for(identity())
|
||||
}
|
||||
|
||||
#[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!(stable_services_for(LaunchIdentity::Stable));
|
||||
assert!(!stable_services_for(LaunchIdentity::NightlyV1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_channel_names_are_distinct_and_keep_the_stable_name() {
|
||||
assert_eq!(name_for(LaunchIdentity::Stable), "WordCraft");
|
||||
assert_eq!(name_for(LaunchIdentity::NightlyV1), "WordCraft Nightly");
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,16 @@ impl WordApp {
|
||||
rt.updater = Updater::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")).with_translator(translate).with_source(refused_check());
|
||||
}
|
||||
|
||||
/// The Nightly channel's rule: ArtCraft Launcher installs and replaces the nightly build, so
|
||||
/// this window never checks for, offers or starts one. Nightly-only text is English: it is not
|
||||
/// one of the stable catalogs' strings.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn use_launcher_updates(&mut self) {
|
||||
let rt = &mut self.updates_rt;
|
||||
rt.startup_check = false;
|
||||
rt.updater = Updater::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")).with_translator(translate).with_source(launcher_check());
|
||||
}
|
||||
|
||||
/// Answers every update check with "up to date" instead of asking GitHub, so a test's result
|
||||
/// doesn't depend on the network or its rate limit (#7463).
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
@@ -90,6 +100,13 @@ fn refused_check() -> craft::update::updater::CheckSource {
|
||||
std::sync::Arc::new(move || Err(why.clone().into()))
|
||||
}
|
||||
|
||||
/// A check whose only answer is that the Launcher owns this build's updates.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn launcher_check() -> craft::update::updater::CheckSource {
|
||||
let why = "Updates for WordCraft Nightly are managed by ArtCraft Launcher. Open ArtCraft Launcher to update it.".to_string();
|
||||
std::sync::Arc::new(move || Err(why.clone().into()))
|
||||
}
|
||||
|
||||
/// Help ▸ Check for Updates. The result dialog opens from [`run`] while the updater has a status.
|
||||
pub(crate) fn check(app: &mut WordApp) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -270,3 +287,14 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Nightly channel's rule: the Launcher owns its updates, so a check never reaches the network
|
||||
/// and says why.
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod launcher_updates {
|
||||
#[test]
|
||||
fn a_nightly_check_never_reaches_the_network_and_names_the_launcher() {
|
||||
let error = super::launcher_check()().unwrap_err();
|
||||
assert!(error.to_string().contains("ArtCraft Launcher"), "{error}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,6 +146,8 @@ impl WordApp {
|
||||
command_catalog_lang: _,
|
||||
key_overrides: _,
|
||||
command_states: _,
|
||||
command_states_cache: _,
|
||||
keytip_cache: _,
|
||||
fonts_frames: _,
|
||||
printing: _,
|
||||
print_feedback_seen: _,
|
||||
|
||||
@@ -43,9 +43,27 @@ use crate::{WordApp, documents, window_geometry::MIN_SIZE, window_ui::WindowUi};
|
||||
|
||||
pub(crate) mod arrange;
|
||||
|
||||
/// The window title for a document called `name`.
|
||||
/// The window title for a document called `name`, in the channel this window runs as: a Nightly
|
||||
/// keeps its name in every document window's title, so the two channels never look alike.
|
||||
pub(crate) fn title(name: &str, dirty: bool) -> String {
|
||||
format!("{name}{} - WordCraft", if dirty { " •" } else { "" })
|
||||
channel_title(name, dirty, crate::os_window::name_for(crate::os_window::identity()))
|
||||
}
|
||||
|
||||
/// [`title`] for an explicit channel name: the stable spelling is unchanged, and a Nightly's keeps
|
||||
/// its channel after the document and the unsaved dot.
|
||||
fn channel_title(name: &str, dirty: bool, app: &str) -> String {
|
||||
format!("{name}{} - {app}", if dirty { " •" } else { "" })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod channel_title_tests {
|
||||
#[test]
|
||||
fn the_channel_name_stays_in_every_document_title() {
|
||||
assert_eq!(super::channel_title("Document1", false, "WordCraft"), "Document1 - WordCraft");
|
||||
assert_eq!(super::channel_title("Document1", true, "WordCraft"), "Document1 • - WordCraft");
|
||||
assert_eq!(super::channel_title("Letter", false, "WordCraft Nightly"), "Letter - WordCraft Nightly");
|
||||
assert_eq!(super::channel_title("Letter", true, "WordCraft Nightly"), "Letter • - WordCraft Nightly");
|
||||
}
|
||||
}
|
||||
|
||||
/// The id of the container that shows window `id`; the window host names its viewport by it.
|
||||
@@ -469,7 +487,7 @@ impl WordApp {
|
||||
/// The drawn window's title: its document's name as View › Window › Switch Windows gives it.
|
||||
pub(crate) fn window_title(&self) -> String {
|
||||
if !self.has_document() {
|
||||
return "WordCraft".to_string();
|
||||
return crate::os_window::name_for(crate::os_window::identity()).to_string();
|
||||
}
|
||||
let name = self.window_menu().title(self.windows.shown).map(str::to_string).unwrap_or_else(|| self.title_stem());
|
||||
title(&name, self.session.dirty)
|
||||
@@ -479,7 +497,7 @@ impl WordApp {
|
||||
fn title_in(menu: &WindowMenu, id: WindowId) -> String {
|
||||
match menu.get(id).filter(|e| !e.title.is_empty()) {
|
||||
Some(e) => title(&e.title, e.dirty),
|
||||
None => "WordCraft".to_string(),
|
||||
None => crate::os_window::name_for(crate::os_window::identity()).to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
# 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` lands on `main`, populate `producer_workflow_id` before promoting the policy to
|
||||
`release` by reading:
|
||||
|
||||
```bash
|
||||
gh api repos/storytold/wordcraft/actions/workflows/nightly.yml --jq .id
|
||||
```
|
||||
|
||||
The callers pass no platform secrets. The unsigned reusable caller's maximum OIDC/attestation
|
||||
permissions are for its isolated attester; its compiler narrows to contents and Actions read
|
||||
only, with no OIDC, attestation write, release environment or platform signing secrets.
|
||||
Shared tooling is pinned to `605d58766e8f536564da8fc81d3676ac86816dea`, the craft-common-actions
|
||||
main commit that merged [#339](https://github.com/storytold/craft-common-actions/pull/339) (bounded
|
||||
lineage compares and an issue reread at the end of candidate admission) on top of
|
||||
[#342](https://github.com/storytold/craft-common-actions/pull/342) (policy v3, the `platforms` input
|
||||
and the Linux and macOS legs). Both callers name it in `uses` and `tooling-revision`. A pin is reviewed
|
||||
source availability, not provider, queue, native signing or crypto qualification.
|
||||
Existing stable workflows are unchanged.
|
||||
|
||||
**The shared-workflow port is a prerequisite.** At this pin both reusable workflows admit only
|
||||
PhotoCraft: `nightly-unsigned.yml` requires `inputs.app-name == 'photocraft'` and
|
||||
`github.repository == 'storytold/photocraft'` on its build jobs, and `nightly-release.yml` requires the
|
||||
same repository in `validate` and every signing job (its concurrency group is
|
||||
`craft-release-ref-signer-photocraft`). A WordCraft dispatch therefore builds and signs nothing until
|
||||
`storytold/craft-common-actions` admits `storytold/wordcraft`. No dispatch can produce a release before
|
||||
that port, and both callers' `uses`, `tooling-revision` and the policy pins must move to the same
|
||||
reviewed revision together. The port is craft-common-actions #363 ("run the shared nightly pipeline for any
|
||||
reviewed registry app"); until it merges these callers are inert.
|
||||
|
||||
**First runs.** The first runs are manual dispatches in this order: `nightly.yml` on main (only a
|
||||
listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `release` with that
|
||||
producer run ID and attempt, by a listed manual actor.
|
||||
|
||||
**Manual actors.** `bflatastic`, `dylanmtaylor`, `echelon`, `FredApps` and `skylartaylor`, in the
|
||||
producer's `manual-actors` and the policy's `manual_actors`. The list mirrors the release-managers
|
||||
team (id 19837241), leaving out `echelon-robot`; update it by PR in both places when the team changes.
|
||||
|
||||
**Admission timing.** The candidate check reads the newest CI run on the candidate commit and
|
||||
main's latest finished Sonar analysis, so pick a quiet main, wait for its CI and SonarCloud analysis
|
||||
to finish green, then dispatch the producer and, once it succeeds, the signer, before another main
|
||||
push lands a newer analysis.
|
||||
|
||||
**Platform rows.** The producer caller lists
|
||||
`platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'` on its single job: one producer
|
||||
run builds every listed platform for one all-or-nothing release (one failed or skipped platform stops
|
||||
that night's release), and the release-ref signer admits platforms only from the protected policy, so
|
||||
there is no separate Linux or macOS caller job and the signer caller has no platform input.
|
||||
|
||||
## Installed policy values and their sources
|
||||
|
||||
Read on 2026-11-24; re-read anything that may have moved (and fill in `producer_workflow_id` after
|
||||
`nightly.yml` lands on `main`) before the policy is promoted to `release`.
|
||||
|
||||
| Field | Value | Source |
|
||||
|---|---|---|
|
||||
| `repository_id` | `1408489772` | `gh api repos/storytold/wordcraft --jq .id` |
|
||||
| `producer_workflow_id` | `null` (pending `main` registration) | Read via `gh api repos/storytold/wordcraft/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; equals the producer caller's `manual-actors` |
|
||||
| `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist |
|
||||
| `platforms` | three rows | Storytold stable signing identities (Windows Authenticode subject, Linux OpenPGP fingerprint, macOS Apple Team ID `DJ6XS33FX8`) |
|
||||
| `candidate_policy.required_workflows` | CI (`ci.yml`, workflow `380135788`), `gate / gate (ubuntu-24.04)` | Workflow list API; always-run main push gate job |
|
||||
| `candidate_policy.sonar` | `storytold` / `storytold_wordcraft`, app `12526` | `sonar-project.properties` |
|
||||
| Sonar conditions | `new_security_rating` accepted (max 5); the other five required | Standard Storytold SonarCloud quality gate |
|
||||
| Sonar `issue_types` / `debt` | `VULNERABILITY`; `[]` | Refresh from SonarCloud before promoting policy to `release` |
|
||||
|
||||
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
|
||||
`WordCraft 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 (`wordcraft-nightly-release`,
|
||||
`queue: max`, `cancel-in-progress: false`) is distinct from stable. 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.
|
||||
- `packaging/windows/sign.ps1 -Required` is the app-owned Windows adapter, invoked only from the
|
||||
immutable release execution SHA checkout.
|
||||
|
||||
## Local regression checks
|
||||
|
||||
`python3 packaging/nightly-release-tests.py` verifies:
|
||||
- Both callers share one full 40-char commit pin in `uses` and `tooling-revision`.
|
||||
- Both callers keep their exact context guards (reading all continuation lines), have no cache
|
||||
actions/options or secrets, and register no schedule.
|
||||
- `nightly-sign.yml` keeps its literal `wordcraft-nightly-release` concurrency group, `queue: max`,
|
||||
and `cancel-in-progress: false`.
|
||||
- `manual-actors` in `nightly.yml` and `manual_actors` in `.github/nightly-signing-policy.json` are
|
||||
identical and equal to the reviewed release managers list, with `automatic_signer_actors` empty.
|
||||
- `.github/nightly-signing-policy.json` matches the `craft-nightly-release-policy/v3` schema,
|
||||
repository identity, platform trust anchors, CI workflow trigger, and `sonar-project.properties`.
|
||||
@@ -28,3 +28,45 @@ Local packaging: `packaging/macos/package.sh --arch universal`, `packaging/windo
|
||||
A scheduled dry run runs on `main` nightly at 03:00 UTC. It builds every release target except
|
||||
macOS, without signing, entering the `release` environment, pushing Flatpak images or making a
|
||||
draft release. Manual dispatch uses the normal release path (`dry-run` is false).
|
||||
|
||||
## The Nightly channel
|
||||
|
||||
A separate **Nightly** channel exists beside the release above. Its producer and signer are
|
||||
**enabled for supervised manual runs only** (no schedule, no automatic dispatch) and its signing
|
||||
policy is installed; it is not the release dry run above.
|
||||
|
||||
What the channel is:
|
||||
|
||||
- A build channel: `WORDCRAFT_BUILD_CHANNEL=nightly-v1` (with `WORDCRAFT_VERSION`, `WORDCRAFT_BUILD_SHA`
|
||||
and `WORDCRAFT_BUILD_DATE`) compiles a `WordCraft Nightly` build with its own version line,
|
||||
Windows identity and icon. Unset or `stable` stays the ordinary build.
|
||||
- The Launcher protocol: `--launch-profile nightly-v1 --profile-root <abs> -- files`, with
|
||||
`--version` answered in both plain and profile form before any state is read. A Nightly build
|
||||
without a profile is refused (it never falls back to the stable data).
|
||||
- Its own data: preferences, window place, logs, recovery, fonts, templates, the dictionary, the
|
||||
suite font store and any control tokens live under that profile, which may not overlap stable
|
||||
data, the shared font store or an installation.
|
||||
- Packaging: `packaging/linux/nightly.sh --arch x86_64` (plus the Arch handoff in
|
||||
`packaging/linux/nightly-arch-tar.sh`), `packaging/windows/package.ps1 -Arch x64 -Nightly
|
||||
-BuildOnly`, `packaging/macos/nightly.sh --arch aarch64` with `nightly-sign.sh` and
|
||||
`nightly-verify.sh` for the trusted step, and `packaging/nightly-icons.py` for its icons.
|
||||
- Qualification: `.github/workflows/nightly-build.yml` builds and checks all three unsigned
|
||||
archives on the `full-ci` label or on dispatch, with no secrets;
|
||||
`packaging/nightly-tests.py` runs the synthetic suites in Packaging lint.
|
||||
|
||||
Every Linux format ships one launcher (`packaging/linux/nightly-launcher.sh`) that starts the
|
||||
binary the channel's way, because a Nightly build refuses to run without a profile:
|
||||
`wordcraft --launch-profile nightly-v1 --profile-root "${XDG_DATA_HOME:-$HOME/.local/share}/wordcraft-nightly" -- "$@"`.
|
||||
That launcher is the deb/rpm `/usr/bin/wordcraft-nightly` wrapper (real binary in
|
||||
`/usr/lib/wordcraft-nightly/`), the AppImage `AppRun` (a script, not a symlink, calling
|
||||
`usr/bin/wordcraft`), the Arch `bin/wordcraft-nightly` launcher (real binary in
|
||||
`bin/.wordcraft-nightly/`), the app-owned Nightly tar's `wordcraft` (real binary `wordcraft-bin`)
|
||||
and the plain tar's `bin/wordcraft` (real binary in `lib/wordcraft-nightly/`), which the Flatpak
|
||||
bundle also installs. `XDG_DATA_HOME` keeps the profile on the app's own data directory inside the
|
||||
Flatpak sandbox (`~/.var/app/ai.storyteller.wordcraft.nightly/data/wordcraft-nightly`), which
|
||||
persists; the sandbox's home is discarded. Redirecting `XDG_*` alone is refused: the build's root
|
||||
validator derives the stable boundary from it, so the profile would sit inside it. The launcher
|
||||
passes an already-supplied Launcher form (`--launch-profile`, and `--version`/`-V`) straight
|
||||
through, so the ArtCraft Launcher's own root is used and its version check opens no window. The
|
||||
remaining activation steps are described in
|
||||
[nightly-release-preparation.md](nightly-release-preparation.md).
|
||||
|
||||
@@ -17,6 +17,12 @@ set -euo pipefail
|
||||
. "$(dirname "${BASH_SOURCE[0]}")/../env.sh"
|
||||
HERE="$ROOT/packaging/linux"
|
||||
APP_ID=ai.storyteller.wordcraft
|
||||
FLATPAK_ID="$APP_ID"
|
||||
# The remote indexes both app IDs on the stable ref branch; IDs isolate installations.
|
||||
FLATPAK_BRANCH=stable
|
||||
if [[ "${WORDCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then
|
||||
FLATPAK_ID="$APP_ID.nightly"
|
||||
fi
|
||||
FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo
|
||||
|
||||
TEST=1
|
||||
@@ -38,7 +44,11 @@ case "$ARCH" in
|
||||
aarch64 | arm64) ARCH=aarch64 ;;
|
||||
*) echo "unsupported architecture $ARCH" >&2; exit 2 ;;
|
||||
esac
|
||||
BASENAME="wordcraft-$VERSION-linux-$ARCH"
|
||||
BASENAME_VERSION="$VERSION"
|
||||
if [[ "$FLATPAK_ID" != "$APP_ID" && "$BASENAME_VERSION" != *-nightly* ]]; then
|
||||
BASENAME_VERSION="$BASENAME_VERSION-nightly"
|
||||
fi
|
||||
BASENAME="wordcraft-$BASENAME_VERSION-linux-$ARCH"
|
||||
TARBALL="${TARBALL:-$DIST/$BASENAME.tar.gz}"
|
||||
[[ -f "$TARBALL" ]] || { echo "error: $TARBALL not found (run packaging/linux/package.sh --formats tar first)" >&2; exit 1; }
|
||||
for tool in flatpak flatpak-builder; do
|
||||
@@ -52,29 +62,64 @@ rm -rf "$WORK"
|
||||
mkdir -p "$WORK/stage"
|
||||
tar -xzf "$TARBALL" -C "$WORK/stage" --strip-components=1
|
||||
[[ -x "$WORK/stage/bin/wordcraft" ]] || { echo "error: $TARBALL has no bin/wordcraft" >&2; exit 1; }
|
||||
cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$APP_ID.yml"
|
||||
if [[ "$FLATPAK_ID" != "$APP_ID" ]]; then
|
||||
sed -e "s|^Icon=$APP_ID$|Icon=$FLATPAK_ID|" \
|
||||
-e "s|^Name=WordCraft$|Name=WordCraft Nightly|" \
|
||||
-e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.wordcraft.nightly-v1|' \
|
||||
-e '/^MimeType=/d' \
|
||||
"$WORK/stage/share/applications/$APP_ID.desktop" >"$WORK/stage/share/applications/$FLATPAK_ID.desktop"
|
||||
rm -f "$WORK/stage/share/applications/$APP_ID.desktop"
|
||||
sed -e "s|<id>$APP_ID</id>|<id>$FLATPAK_ID</id>|g" \
|
||||
-e "s|<name>WordCraft</name>|<name>WordCraft Nightly</name>|g" \
|
||||
-e "s|<launchable type=\"desktop-id\">$APP_ID.desktop</launchable>|<launchable type=\"desktop-id\">$FLATPAK_ID.desktop</launchable>|g" \
|
||||
-e "s|<icon type=\"stock\">$APP_ID</icon>|<icon type=\"stock\">$FLATPAK_ID</icon>|g" \
|
||||
-e '/<mediatype>/d' \
|
||||
"$WORK/stage/share/metainfo/$APP_ID.metainfo.xml" >"$WORK/stage/share/metainfo/$FLATPAK_ID.metainfo.xml"
|
||||
rm -f "$WORK/stage/share/metainfo/$APP_ID.metainfo.xml"
|
||||
mv "$WORK/stage/share/mime/packages/$APP_ID.xml" "$WORK/stage/share/mime/packages/$FLATPAK_ID.xml"
|
||||
rm -rf "$WORK/stage/share/icons/hicolor"
|
||||
NIGHTLY_ICON="$ROOT/assets/app-icon/wordcraft-nightly.png"
|
||||
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
|
||||
install -Dm644 "$NIGHTLY_ICON" \
|
||||
"$WORK/stage/share/icons/hicolor/256x256/apps/$FLATPAK_ID.png"
|
||||
# The nightly tar carries the launcher in bin/wordcraft and the GUI in lib/wordcraft-nightly/;
|
||||
# the bundle must install both. The launcher keeps the profile under XDG_DATA_HOME, which inside
|
||||
# the sandbox is this app's own persistent data directory
|
||||
# (~/.var/app/ai.storyteller.wordcraft.nightly/data), not the throwaway sandbox home.
|
||||
sed -e "s|ai\.storyteller\.wordcraft|$FLATPAK_ID|g" \
|
||||
-e 's|^\( - install -Dm755 bin/wordcraft /app/bin/wordcraft\)$|\1\n - install -Dm755 lib/wordcraft-nightly/wordcraft /app/lib/wordcraft-nightly/wordcraft|' \
|
||||
"$HERE/flatpak/$APP_ID.bundle.yml" >"$WORK/$FLATPAK_ID.yml"
|
||||
grep -qx ' - install -Dm755 lib/wordcraft-nightly/wordcraft /app/lib/wordcraft-nightly/wordcraft' \
|
||||
"$WORK/$FLATPAK_ID.yml" || { echo "error: the nightly manifest did not take the launcher's binary" >&2; exit 1; }
|
||||
else
|
||||
cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$FLATPAK_ID.yml"
|
||||
fi
|
||||
|
||||
flatpak remote-add --user --if-not-exists flathub "$FLATHUB"
|
||||
# --disable-rofiles-fuse: no FUSE in containers and CI runners.
|
||||
flatpak-builder --user --install-deps-from=flathub --disable-rofiles-fuse --force-clean \
|
||||
--default-branch=stable --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$APP_ID.yml"
|
||||
--default-branch="$FLATPAK_BRANCH" --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$FLATPAK_ID.yml"
|
||||
|
||||
OUT="$DIST/$BASENAME.flatpak"
|
||||
# --runtime-repo lets `flatpak install` fetch the freedesktop runtime from Flathub if missing.
|
||||
flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$APP_ID" stable
|
||||
flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$FLATPAK_ID" "$FLATPAK_BRANCH"
|
||||
echo "wrote $OUT"
|
||||
if [[ "$OCI" = 1 ]]; then
|
||||
OUT_OCI="$DIST/$BASENAME-oci"
|
||||
rm -rf "$OUT_OCI"
|
||||
flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$APP_ID" stable
|
||||
flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$FLATPAK_ID" "$FLATPAK_BRANCH"
|
||||
echo "wrote OCI layout to $OUT_OCI"
|
||||
fi
|
||||
|
||||
if [[ "$TEST" = 1 ]]; then
|
||||
flatpak install --user -y --noninteractive --reinstall "$OUT"
|
||||
flatpak info --user "$APP_ID"
|
||||
flatpak run --command=wordcraft-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=wordcraft-cli "$FLATPAK_ID" --version
|
||||
if [[ "$FLATPAK_ID" != "$APP_ID" ]]; then
|
||||
# The launcher and the GUI it starts are both installed, and the version query answers.
|
||||
flatpak run --command=wordcraft "$FLATPAK_ID" --version
|
||||
fi
|
||||
flatpak run --command=sh "$FLATPAK_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/*/apps'
|
||||
fi
|
||||
echo "==> done"
|
||||
ls -lh "$OUT"
|
||||
|
||||
+16
-13
@@ -3,7 +3,7 @@
|
||||
# exports VERSION and NFPM_ARCH.
|
||||
#
|
||||
# nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/
|
||||
name: wordcraft
|
||||
name: ${NFPM_NAME}
|
||||
arch: ${NFPM_ARCH}
|
||||
platform: linux
|
||||
version: ${VERSION}
|
||||
@@ -67,26 +67,29 @@ overrides:
|
||||
- espeak-ng
|
||||
|
||||
contents:
|
||||
- src: ${STAGE}/usr/bin/wordcraft
|
||||
dst: /usr/bin/wordcraft
|
||||
- src: ${STAGE}/usr/bin/${NFPM_BIN}
|
||||
dst: /usr/bin/${NFPM_BIN}
|
||||
file_info: { mode: 0755 }
|
||||
- src: ${STAGE}/usr/bin/wordcraft-cli
|
||||
dst: /usr/bin/wordcraft-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
|
||||
# Named one by one rather than as a tree of /usr/share: a tree would also own shared directories
|
||||
# such as /usr/share/mime, which openSUSE's filesystem package owns with other modes, and RPM
|
||||
# refuses to install a package that conflicts with it.
|
||||
- src: ${STAGE}/usr/share/applications/ai.storyteller.wordcraft.desktop
|
||||
dst: /usr/share/applications/ai.storyteller.wordcraft.desktop
|
||||
- src: ${STAGE}/usr/share/mime/packages/ai.storyteller.wordcraft.xml
|
||||
dst: /usr/share/mime/packages/ai.storyteller.wordcraft.xml
|
||||
- src: ${STAGE}/usr/share/metainfo/ai.storyteller.wordcraft.metainfo.xml
|
||||
dst: /usr/share/metainfo/ai.storyteller.wordcraft.metainfo.xml
|
||||
- src: ${STAGE}/usr/share/applications/${NFPM_APP_ID}.desktop
|
||||
dst: /usr/share/applications/${NFPM_APP_ID}.desktop
|
||||
- src: ${STAGE}/usr/share/mime/packages/${NFPM_APP_ID}.xml
|
||||
dst: /usr/share/mime/packages/${NFPM_APP_ID}.xml
|
||||
- src: ${STAGE}/usr/share/metainfo/${NFPM_APP_ID}.metainfo.xml
|
||||
dst: /usr/share/metainfo/${NFPM_APP_ID}.metainfo.xml
|
||||
- src: ${STAGE}/usr/share/icons/hicolor/
|
||||
dst: /usr/share/icons/hicolor/
|
||||
type: tree
|
||||
- src: ${STAGE}/usr/share/doc/wordcraft/
|
||||
dst: /usr/share/doc/wordcraft/
|
||||
- src: ${STAGE}/usr/share/doc/${NFPM_NAME}/
|
||||
dst: /usr/share/doc/${NFPM_NAME}/
|
||||
type: tree
|
||||
|
||||
scripts:
|
||||
|
||||
Executable
+72
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env bash
|
||||
# Validate the staged Arch launcher without building or opening WordCraft.
|
||||
set -euo pipefail
|
||||
|
||||
HERE="$(cd "$(dirname "$0")" && pwd)"
|
||||
work="$(mktemp -d)"
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
stage="$work/source"
|
||||
dst="$work/dist"
|
||||
base=wordcraft-0.0.1-nightly.1-linux-x86_64
|
||||
mkdir -p "$stage/bin" "$dst" "$work/extract"
|
||||
|
||||
# A local argv/env recorder stands in for the compiled binaries. It never opens a UI.
|
||||
cat >"$stage/bin/wordcraft" <<'RECORDER'
|
||||
#!/bin/sh
|
||||
printf 'XDG_CONFIG_HOME=%s\n' "${XDG_CONFIG_HOME:-}"
|
||||
printf 'XDG_DATA_HOME=%s\n' "${XDG_DATA_HOME:-}"
|
||||
printf '<%s>\n' "$@"
|
||||
RECORDER
|
||||
chmod 755 "$stage/bin/wordcraft"
|
||||
cp "$stage/bin/wordcraft" "$stage/bin/wordcraft-cli"
|
||||
|
||||
bash "$HERE/nightly-arch-tar.sh" "$stage" "$work/stage" "$dst" "$base"
|
||||
tar -xzf "$dst/$base.tar.gz" -C "$work/extract"
|
||||
bin="$work/extract/$base/bin"
|
||||
# Simulate the existing Arch bin-tree copy and public launcher rename.
|
||||
mkdir -p "$work/installed"
|
||||
cp -R "$bin" "$work/installed/bin"
|
||||
bin="$work/installed/bin"
|
||||
mv "$bin/wordcraft" "$bin/wordcraft-nightly"
|
||||
mv "$bin/wordcraft-cli" "$bin/wordcraft-nightly-cli"
|
||||
|
||||
test ! -e "$stage/bin/.wordcraft-nightly"
|
||||
cmp "$stage/bin/wordcraft" "$bin/.wordcraft-nightly/wordcraft"
|
||||
cmp "$stage/bin/wordcraft-cli" "$bin/wordcraft-nightly-cli"
|
||||
export HOME="$work/home with space"
|
||||
# The launcher must not redirect XDG_* (the profile holds the state); the recorder prints them so
|
||||
# a regression to the environment model is visible.
|
||||
export XDG_CONFIG_HOME="$work/xdg config with space"
|
||||
export XDG_DATA_HOME="$work/xdg data with space"
|
||||
expect() {
|
||||
expected="$1"
|
||||
shift
|
||||
actual=$(PATH="$bin:$PATH" wordcraft-nightly "$@")
|
||||
if [[ "$actual" != "$expected" ]]; then
|
||||
printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
profile="$XDG_DATA_HOME/wordcraft-nightly"
|
||||
prefix="$(printf 'XDG_CONFIG_HOME=%s\nXDG_DATA_HOME=%s' "$XDG_CONFIG_HOME" "$XDG_DATA_HOME")"
|
||||
# Run from a directory that holds no .wordcraft-nightly: a launcher found through PATH must
|
||||
# resolve its own folder, and must never follow XDG_* to the profile.
|
||||
cd "$work"
|
||||
expect "$(printf '%s\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>' "$prefix" \
|
||||
--launch-profile nightly-v1 --profile-root "$profile" --)"
|
||||
expect "$(printf '%s\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>' "$prefix" \
|
||||
--launch-profile nightly-v1 --profile-root "$profile" -- 'doc with spaces.docx' '--other-name.docx')" \
|
||||
'doc with spaces.docx' '--other-name.docx'
|
||||
expect "$(printf '%s\n<%s>' "$prefix" --version)" --version
|
||||
expect "$(printf '%s\n<%s>' "$prefix" -V)" -V
|
||||
# The ArtCraft Launcher's form passes through untouched: wrapping it again would make its tokens
|
||||
# file names and ignore the root it chose.
|
||||
root="$work/launcher profile with space"
|
||||
expect "$(printf '%s\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>' "$prefix" \
|
||||
--launch-profile nightly-v1 --profile-root "$root" -- 'a.docx')" \
|
||||
--launch-profile nightly-v1 --profile-root "$root" -- 'a.docx'
|
||||
expect "$(printf '%s\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>' "$prefix" \
|
||||
--launch-profile nightly-v1 --profile-root "$root" --version)" \
|
||||
--launch-profile nightly-v1 --profile-root "$root" --version
|
||||
|
||||
echo "PASS: Arch Nightly handoff isolates the profile and preserves launch arguments"
|
||||
Executable
+19
@@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env bash
|
||||
# Stage the WordCraft Nightly-only handoff for the Arch packager.
|
||||
set -euo pipefail
|
||||
|
||||
here="$(cd "$(dirname "$0")" && pwd)"
|
||||
source_tree="$1"
|
||||
work="$2"
|
||||
destination="$3"
|
||||
basename="$4"
|
||||
stage="$work/$basename"
|
||||
|
||||
mkdir -p "$work"
|
||||
cp -R "$source_tree" "$stage"
|
||||
mkdir "$stage/bin/.wordcraft-nightly"
|
||||
mv "$stage/bin/wordcraft" "$stage/bin/.wordcraft-nightly/wordcraft"
|
||||
cp "$here/nightly-launcher.sh" "$stage/bin/wordcraft"
|
||||
chmod 755 "$stage/bin/wordcraft"
|
||||
tar -C "$work" -czf "$destination/$basename.tar.gz" "$basename"
|
||||
echo "wrote $destination/$basename.tar.gz"
|
||||
Executable
+53
@@ -0,0 +1,53 @@
|
||||
#!/bin/sh
|
||||
# The Nightly channel's launcher, installed by every Linux format in place of the GUI binary.
|
||||
#
|
||||
# A Nightly keeps all of its user state in its own launch profile, so the launcher adds
|
||||
# `--launch-profile nightly-v1 --profile-root ...` and passes the user's arguments after `--`.
|
||||
# Redirecting XDG_* instead is refused by the build's profile validator, which derives the stable
|
||||
# boundary from the environment, so the chosen profile would sit inside that boundary.
|
||||
#
|
||||
# The GUI sits beside the launcher in one of these layouts:
|
||||
# wordcraft-bin an unpacked app-owned nightly tar (nightly.sh)
|
||||
# .wordcraft-nightly/wordcraft the Arch handoff (nightly-arch-tar.sh)
|
||||
# ../lib/wordcraft-nightly/wordcraft deb/rpm and the plain FHS tar (package.sh)
|
||||
# usr/bin/wordcraft an AppImage, whose AppRun is this launcher
|
||||
# The path is resolved from this script, never from the working directory, and only a regular
|
||||
# executable is used.
|
||||
#
|
||||
# The ArtCraft Launcher starts the tar's `wordcraft` with the profile form already supplied
|
||||
# (`--launch-profile nightly-v1 --profile-root <abs> -- files`, or `--version` for its check).
|
||||
# That form passes straight through: wrapping it again would turn its tokens into file names and
|
||||
# ignore the root the Launcher chose. `--version`/`-V` do too, so a version check opens no window
|
||||
# and creates no profile.
|
||||
set -eu
|
||||
|
||||
case $0 in
|
||||
*/*) self=$0 ;;
|
||||
*) self=$(command -v -- "$0") || { echo "wordcraft: cannot locate this launcher" >&2; exit 2; } ;;
|
||||
esac
|
||||
here=$(CDPATH='' cd -- "$(dirname -- "$self")" && pwd -P) \
|
||||
|| { echo "wordcraft: cannot resolve this launcher's folder" >&2; exit 2; }
|
||||
|
||||
real_bin=
|
||||
for candidate in \
|
||||
"$here/wordcraft-bin" \
|
||||
"$here/.wordcraft-nightly/wordcraft" \
|
||||
"$here/../lib/wordcraft-nightly/wordcraft" \
|
||||
"$here/usr/bin/wordcraft"
|
||||
do
|
||||
if [ -f "$candidate" ] && [ -x "$candidate" ]; then
|
||||
real_bin=$candidate
|
||||
break
|
||||
fi
|
||||
done
|
||||
[ -n "$real_bin" ] || { echo "wordcraft: cannot find the Nightly GUI next to $here" >&2; exit 2; }
|
||||
|
||||
case ${1:-} in
|
||||
--launch-profile | --version | -V) exec "$real_bin" "$@" ;;
|
||||
esac
|
||||
|
||||
data_home=${XDG_DATA_HOME:-}
|
||||
if [ -z "$data_home" ]; then
|
||||
data_home=${HOME:?HOME is required}/.local/share
|
||||
fi
|
||||
exec "$real_bin" --launch-profile nightly-v1 --profile-root "$data_home/wordcraft-nightly" -- "$@"
|
||||
Executable
+99
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env bash
|
||||
# Render the Nightly Linux tar exactly as package.sh does, without building or opening WordCraft,
|
||||
# and run the launcher it installs. Guards the tar step's paths and the launcher's argument rules.
|
||||
set -euo pipefail
|
||||
|
||||
HERE="$(cd "$(dirname "$0")" && pwd)"
|
||||
ROOT="$(cd "$HERE/../.." && pwd)"
|
||||
work="$(mktemp -d)"
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
|
||||
export CARGO_TARGET_DIR="$work/target"
|
||||
export DIST="$work/dist"
|
||||
export WORDCRAFT_BUILD_CHANNEL=nightly-v1
|
||||
export WORDCRAFT_VERSION="0.0.0-nightly.20260101.1.1.g0123456789ab"
|
||||
export WORDCRAFT_BUILD_DATE="2026-01-01"
|
||||
mkdir -p "$CARGO_TARGET_DIR/release" "$DIST"
|
||||
|
||||
# A local argv recorder stands in for the compiled binaries. It never opens a UI.
|
||||
cat >"$CARGO_TARGET_DIR/release/wordcraft" <<'RECORDER'
|
||||
#!/bin/sh
|
||||
printf '<%s>\n' "$@"
|
||||
RECORDER
|
||||
cp "$CARGO_TARGET_DIR/release/wordcraft" "$CARGO_TARGET_DIR/release/wordcraft-cli"
|
||||
chmod 755 "$CARGO_TARGET_DIR/release/wordcraft" "$CARGO_TARGET_DIR/release/wordcraft-cli"
|
||||
|
||||
# The tar format is first in package.sh's default set; a broken nightly tar aborted every run here.
|
||||
(cd "$ROOT" && bash packaging/linux/package.sh --skip-build --formats tar)
|
||||
|
||||
base="wordcraft-$WORDCRAFT_VERSION-linux-$(uname -m)"
|
||||
archive="$DIST/$base.tar.gz"
|
||||
[ -f "$archive" ] || { echo "error: package.sh wrote no $archive" >&2; exit 1; }
|
||||
tar -xzf "$archive" -C "$work"
|
||||
tree="$work/$base"
|
||||
|
||||
# The FHS tree the desktop file and the Flatpak bundle expect: the launcher in bin/, the GUI in
|
||||
# lib/wordcraft-nightly/.
|
||||
[ -x "$tree/bin/wordcraft" ] && [ ! -L "$tree/bin/wordcraft" ] || { echo 'error: bin/wordcraft is not the launcher' >&2; exit 1; }
|
||||
[ -x "$tree/lib/wordcraft-nightly/wordcraft" ] || { echo 'error: no GUI in lib/wordcraft-nightly' >&2; exit 1; }
|
||||
cmp "$tree/lib/wordcraft-nightly/wordcraft" "$CARGO_TARGET_DIR/release/wordcraft"
|
||||
cmp "$tree/bin/wordcraft" "$HERE/nightly-launcher.sh"
|
||||
|
||||
home="$work/home with space"
|
||||
mkdir -p "$home"
|
||||
expect() {
|
||||
expected="$1"
|
||||
shift
|
||||
actual=$(env -i HOME="$home" PATH="/usr/bin:/bin" "$tree/bin/wordcraft" "$@")
|
||||
if [ "$actual" != "$expected" ]; then
|
||||
printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
profile="$home/.local/share/wordcraft-nightly"
|
||||
expect "$(printf '<%s>\n<%s>\n<%s>\n<%s>\n<%s>' \
|
||||
--launch-profile nightly-v1 --profile-root "$profile" --)"
|
||||
expect "$(printf '<%s>\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>' \
|
||||
--launch-profile nightly-v1 --profile-root "$profile" -- 'doc with spaces.docx' '--other-name.docx')" \
|
||||
'doc with spaces.docx' '--other-name.docx'
|
||||
expect "$(printf '<%s>' --version)" --version
|
||||
expect "$(printf '<%s>' -V)" -V
|
||||
# The ArtCraft Launcher's own form passes through untouched, including the root it chose.
|
||||
root="$work/launcher profile with space"
|
||||
expect "$(printf '<%s>\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>' \
|
||||
--launch-profile nightly-v1 --profile-root "$root" -- 'a.docx')" \
|
||||
--launch-profile nightly-v1 --profile-root "$root" -- 'a.docx'
|
||||
expect "$(printf '<%s>\n<%s>\n<%s>\n<%s>\n<%s>' \
|
||||
--launch-profile nightly-v1 --profile-root "$root" --version)" \
|
||||
--launch-profile nightly-v1 --profile-root "$root" --version
|
||||
|
||||
# A data directory the person set themselves (and the Flatpak sandbox's own) keeps the profile
|
||||
# beside the stable folder rather than on the throwaway home.
|
||||
data="$work/xdg data with space"
|
||||
mkdir -p "$data"
|
||||
actual=$(env -i HOME="$home" XDG_DATA_HOME="$data" PATH="/usr/bin:/bin" "$tree/bin/wordcraft" --version)
|
||||
[ "$actual" = '<--version>' ]
|
||||
actual=$(env -i HOME="$home" XDG_DATA_HOME="$data" PATH="/usr/bin:/bin" "$tree/bin/wordcraft" 'x.docx')
|
||||
[ "$actual" = "$(printf '<%s>\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>' --launch-profile nightly-v1 --profile-root "$data/wordcraft-nightly" -- x.docx)" ]
|
||||
|
||||
# A launcher found through PATH still resolves its own folder, never the working directory.
|
||||
mkdir -p "$work/elsewhere"
|
||||
actual=$(cd "$work/elsewhere" && env -i HOME="$home" PATH="$tree/bin:/usr/bin:/bin" wordcraft --version)
|
||||
[ "$actual" = '<--version>' ]
|
||||
|
||||
# The other two layouts the same file is installed in: the AppImage (AppRun beside usr/bin) and
|
||||
# the app-owned nightly tar (wordcraft-bin beside the launcher).
|
||||
mkdir -p "$work/AppDir/usr/bin" "$work/flat"
|
||||
install -m 755 "$HERE/nightly-launcher.sh" "$work/AppDir/AppRun"
|
||||
cp "$CARGO_TARGET_DIR/release/wordcraft" "$work/AppDir/usr/bin/wordcraft"
|
||||
install -m 755 "$HERE/nightly-launcher.sh" "$work/flat/wordcraft"
|
||||
cp "$CARGO_TARGET_DIR/release/wordcraft" "$work/flat/wordcraft-bin"
|
||||
for layout in "$work/AppDir/AppRun" "$work/flat/wordcraft"; do
|
||||
actual=$(env -i HOME="$home" PATH="/usr/bin:/bin" "$layout" 'x.docx')
|
||||
[ "$actual" = "$(printf '<%s>\n<%s>\n<%s>\n<%s>\n<%s>\n<%s>' --launch-profile nightly-v1 --profile-root "$home/.local/share/wordcraft-nightly" -- x.docx)" ] \
|
||||
|| { echo "error: $layout did not wrap: $actual" >&2; exit 1; }
|
||||
actual=$(env -i HOME="$home" PATH="/usr/bin:/bin" "$layout" --version)
|
||||
[ "$actual" = '<--version>' ] || { echo "error: $layout did not pass --version: $actual" >&2; exit 1; }
|
||||
done
|
||||
|
||||
echo "PASS: the Nightly tar starts the GUI through its launcher and keeps the profile it is given"
|
||||
Executable
+33
@@ -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/wordcraft-$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"
|
||||
# An unpacked GUI tar is isolated too: `wordcraft` is the channel's launcher and `wordcraft-bin`
|
||||
# is the GUI it starts beside it. Redirecting XDG_* instead is refused by the build's root
|
||||
# validator.
|
||||
cp "$NIGHTLY_GUI" "$STAGE/wordcraft-bin"
|
||||
chmod 755 "$STAGE/wordcraft-bin"
|
||||
install -m 755 "$ROOT/packaging/linux/nightly-launcher.sh" "$STAGE/wordcraft"
|
||||
NIGHTLY_ICON="$ROOT/assets/app-icon/wordcraft-nightly.png"
|
||||
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/wordcraft-1024.png"
|
||||
cp "$NIGHTLY_ICON" "$STAGE/wordcraft-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"
|
||||
+143
-10
@@ -7,7 +7,7 @@
|
||||
# $DIST/wordcraft-<version>-linux-<arch>.rpm Fedora, openSUSE, RHEL, ...
|
||||
# $DIST/wordcraft-<version>-linux-<arch>.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.wordcraft
|
||||
|
||||
SKIP_BUILD=0
|
||||
FORMATS="appimage deb rpm tar"
|
||||
ARCH_TAR_DIR=
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--skip-build) SKIP_BUILD=1; shift ;;
|
||||
--formats) FORMATS="$2"; shift 2 ;;
|
||||
--arch-tar-dir)
|
||||
[[ -n "${2:-}" ]] || { echo "error: --arch-tar-dir needs a directory" >&2; exit 2; }
|
||||
ARCH_TAR_DIR="$2"
|
||||
shift 2
|
||||
;;
|
||||
-h | --help) sed -n '2,17p' "$0"; exit 0 ;;
|
||||
*) echo "unknown argument: $1" >&2; exit 2 ;;
|
||||
esac
|
||||
@@ -38,9 +44,23 @@ case "$ARCH" in
|
||||
*) echo "unsupported architecture $ARCH" >&2; exit 2 ;;
|
||||
esac
|
||||
export WORDCRAFT_MAINTAINER="${WORDCRAFT_MAINTAINER:-WordCraft maintainers <wordcraft@storyteller.ai>}"
|
||||
BASENAME="wordcraft-$VERSION-linux-$ARCH"
|
||||
IS_NIGHTLY=0
|
||||
if [[ "${WORDCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then
|
||||
IS_NIGHTLY=1
|
||||
export WORDCRAFT_BUILD_CHANNEL=nightly-v1
|
||||
fi
|
||||
BASENAME_VERSION="$VERSION"
|
||||
if [[ "$IS_NIGHTLY" = 1 && "$BASENAME_VERSION" != *-nightly* ]]; then
|
||||
BASENAME_VERSION="$BASENAME_VERSION-nightly"
|
||||
fi
|
||||
BASENAME="wordcraft-$BASENAME_VERSION-linux-$ARCH"
|
||||
|
||||
echo "==> WordCraft $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 "==> WordCraft $VERSION for Linux $ARCH ($FORMATS, channel=${WORDCRAFT_BUILD_CHANNEL:-stable})"
|
||||
|
||||
if [[ "$SKIP_BUILD" = 0 ]]; then
|
||||
if [[ -n "${CROSS_TARGET:-}" ]]; then
|
||||
@@ -59,6 +79,11 @@ install -Dm755 "$BIN/wordcraft" "$STAGE/usr/bin/wordcraft"
|
||||
install -Dm755 "$BIN/wordcraft-cli" "$STAGE/usr/bin/wordcraft-cli"
|
||||
"${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/wordcraft" "$STAGE/usr/bin/wordcraft-cli" 2>/dev/null || true
|
||||
install -Dm644 "$HERE/$APP_ID.desktop" "$STAGE/usr/share/applications/$APP_ID.desktop"
|
||||
if [[ "$IS_NIGHTLY" = 1 ]]; then
|
||||
sed -e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.wordcraft.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@/$WORDCRAFT_BUILD_DATE/g" \
|
||||
@@ -77,21 +102,99 @@ fi
|
||||
|
||||
has() { local item="$1"; case " $FORMATS " in *" $item "*) return 0 ;; *) return 1 ;; esac; }
|
||||
|
||||
# The Nightly channel starts only through its own launch profile, which holds every piece of user
|
||||
# state (preferences, window place, logs, recovery, fonts, templates, the dictionary and the suite
|
||||
# font store). Redirecting XDG_* instead is refused: the build's root validator derives the stable
|
||||
# boundary from it, so the chosen profile would sit inside it. One launcher serves every format
|
||||
# (packaging/linux/nightly-launcher.sh); it finds the GUI in ../lib/wordcraft-nightly/wordcraft,
|
||||
# the layout the packages, the plain tar and the Flatpak bundle built from that tar install.
|
||||
nightly_launcher() {
|
||||
install -Dm755 "$HERE/nightly-launcher.sh" "$1"
|
||||
}
|
||||
|
||||
# ---- .tar.gz ------------------------------------------------------------------------------------
|
||||
if has tar; then
|
||||
mkdir -p "$WORK/tar"
|
||||
cp -R "$STAGE/usr" "$WORK/tar/$BASENAME"
|
||||
if [[ "$IS_NIGHTLY" = 1 ]]; then
|
||||
# An unpacked nightly tar is isolated too: the launcher keeps the desktop file's Exec
|
||||
# (bin/wordcraft) and the real binary moves to lib/wordcraft-nightly/, the layout the
|
||||
# deb/rpm wrapper and the Flatpak bundle built from this tar use as well. The tar holds the
|
||||
# contents of usr/, so these paths have no usr/ component.
|
||||
install -d "$WORK/tar/$BASENAME/lib/wordcraft-nightly"
|
||||
mv "$WORK/tar/$BASENAME/bin/wordcraft" "$WORK/tar/$BASENAME/lib/wordcraft-nightly/wordcraft"
|
||||
nightly_launcher "$WORK/tar/$BASENAME/bin/wordcraft"
|
||||
fi
|
||||
tar -C "$WORK/tar" -czf "$DIST/$BASENAME.tar.gz" "$BASENAME"
|
||||
echo "wrote $DIST/$BASENAME.tar.gz"
|
||||
fi
|
||||
|
||||
# The Arch handoff keeps the same basename as the plain tarball in a separate directory. It
|
||||
# stages the plain usr/ tree (GUI in bin/, no launcher), then installs its own launcher there.
|
||||
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="wordcraft"
|
||||
export NFPM_BIN="wordcraft"
|
||||
export NFPM_CLI="wordcraft-cli"
|
||||
export NFPM_APP_ID="$APP_ID"
|
||||
if [[ "$IS_NIGHTLY" = 1 ]]; then
|
||||
NIGHTLY_DESK_ID="$APP_ID.nightly-v1"
|
||||
export NFPM_NAME="wordcraft-nightly"
|
||||
export NFPM_BIN="wordcraft-nightly"
|
||||
export NFPM_CLI="wordcraft-nightly-cli"
|
||||
export NFPM_APP_ID="$NIGHTLY_DESK_ID"
|
||||
NFPM_STAGE="$WORK/nfpm-root"
|
||||
rm -rf "$NFPM_STAGE"
|
||||
cp -R "$STAGE" "$NFPM_STAGE"
|
||||
install -Dm755 "$NFPM_STAGE/usr/bin/wordcraft" "$NFPM_STAGE/usr/lib/wordcraft-nightly/wordcraft"
|
||||
nightly_launcher "$NFPM_STAGE/usr/bin/$NFPM_BIN"
|
||||
rm -f "$NFPM_STAGE/usr/bin/wordcraft"
|
||||
mv "$NFPM_STAGE/usr/bin/wordcraft-cli" "$NFPM_STAGE/usr/bin/$NFPM_CLI"
|
||||
mv "$NFPM_STAGE/usr/share/doc/wordcraft" "$NFPM_STAGE/usr/share/doc/$NFPM_NAME"
|
||||
sed -e "s#^Exec=wordcraft\([[:space:]]\|$\)#Exec=$NFPM_BIN\1#" \
|
||||
-e "s|^TryExec=wordcraft$|TryExec=$NFPM_BIN|" \
|
||||
-e "s|^Icon=$APP_ID$|Icon=$NIGHTLY_DESK_ID|" \
|
||||
-e "s|^Name=WordCraft$|Name=WordCraft Nightly|" \
|
||||
-e '/^MimeType=/d' \
|
||||
"$NFPM_STAGE/usr/share/applications/$APP_ID.desktop" >"$NFPM_STAGE/usr/share/applications/$NIGHTLY_DESK_ID.desktop"
|
||||
rm -f "$NFPM_STAGE/usr/share/applications/$APP_ID.desktop"
|
||||
sed -e "s|<id>$APP_ID</id>|<id>$NIGHTLY_DESK_ID</id>|g" \
|
||||
-e "s|<name>WordCraft</name>|<name>WordCraft Nightly</name>|g" \
|
||||
-e "s|<launchable type=\"desktop-id\">$APP_ID.desktop</launchable>|<launchable type=\"desktop-id\">$NIGHTLY_DESK_ID.desktop</launchable>|g" \
|
||||
-e "s|<icon type=\"stock\">$APP_ID</icon>|<icon type=\"stock\">$NIGHTLY_DESK_ID</icon>|g" \
|
||||
-e "s|<binary>wordcraft</binary>|<binary>$NFPM_BIN</binary>|g" \
|
||||
-e '/<mediatype>/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"
|
||||
NIGHTLY_ICON="$ROOT/assets/app-icon/wordcraft-nightly.png"
|
||||
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
|
||||
install -Dm644 "$NIGHTLY_ICON" \
|
||||
"$NFPM_STAGE/usr/share/icons/hicolor/256x256/apps/$NIGHTLY_DESK_ID.png"
|
||||
fi
|
||||
# nfpm expands env vars in fields like `version` and `arch`, but not in `contents[].src`.
|
||||
sed "s|\${STAGE}|$STAGE|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml"
|
||||
DROP_LIB_TREE=
|
||||
# shellcheck disable=SC2016
|
||||
[[ -d "$NFPM_STAGE/usr/lib" ]] || DROP_LIB_TREE='\|^ - src: \${STAGE}/usr/lib/|,+2d;'
|
||||
DROP_MIME=
|
||||
# shellcheck disable=SC2016
|
||||
[[ -f "$NFPM_STAGE/usr/share/mime/packages/$NFPM_APP_ID.xml" ]] || DROP_MIME='\|^ - src: \${STAGE}/usr/share/mime/packages/|,+1d;'
|
||||
# shellcheck disable=SC2016
|
||||
sed "${DROP_LIB_TREE}${DROP_MIME}s|\${STAGE}|$NFPM_STAGE|g;s|\${NFPM_BIN}|$NFPM_BIN|g;s|\${NFPM_CLI}|$NFPM_CLI|g;s|\${NFPM_APP_ID}|$NFPM_APP_ID|g;s|\${NFPM_NAME}|$NFPM_NAME|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml"
|
||||
for fmt in deb rpm; do
|
||||
if has "$fmt"; then (cd "$ROOT" && nfpm package -f "$WORK/nfpm.yaml" -p "$fmt" -t "$DIST/$BASENAME.$fmt"); fi
|
||||
done
|
||||
@@ -131,10 +234,31 @@ if has appimage; then
|
||||
}
|
||||
APPDIR="$WORK/WordCraft.AppDir"
|
||||
cp -R "$STAGE" "$APPDIR"
|
||||
ln -s usr/bin/wordcraft "$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"
|
||||
# A real file, not a symlink to the binary: the Nightly build starts only through its own
|
||||
# launch profile, which holds every piece of user state. The launcher finds the GUI in
|
||||
# usr/bin/wordcraft inside this AppDir.
|
||||
nightly_launcher "$APPDIR/AppRun"
|
||||
sed -e "s|^Icon=$APP_ID$|Icon=$APPIMAGE_ID|" \
|
||||
-e "s|^Name=WordCraft$|Name=WordCraft Nightly|" \
|
||||
-e '/^MimeType=/d' \
|
||||
"$APPDIR/usr/share/applications/$APP_ID.desktop" >"$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop"
|
||||
rm -f "$APPDIR/usr/share/applications/$APP_ID.desktop"
|
||||
cp "$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop" "$APPDIR/$APPIMAGE_ID.desktop"
|
||||
rm -rf "$APPDIR/usr/share/icons/hicolor"
|
||||
NIGHTLY_ICON="$ROOT/assets/app-icon/wordcraft-nightly.png"
|
||||
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
|
||||
install -Dm644 "$NIGHTLY_ICON" \
|
||||
"$APPDIR/usr/share/icons/hicolor/256x256/apps/$APPIMAGE_ID.png"
|
||||
cp "$NIGHTLY_ICON" "$APPDIR/$APPIMAGE_ID.png"
|
||||
ln -s "$APPIMAGE_ID.png" "$APPDIR/.DirIcon"
|
||||
else
|
||||
ln -s usr/bin/wordcraft "$APPDIR/AppRun"
|
||||
cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop"
|
||||
cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png"
|
||||
ln -s "$APP_ID.png" "$APPDIR/.DirIcon"
|
||||
fi
|
||||
|
||||
TOOL="${APPIMAGETOOL:-$(command -v appimagetool || true)}"
|
||||
if [[ -z "$TOOL" ]]; then
|
||||
@@ -162,12 +286,21 @@ if has appimage; then
|
||||
# each AppImage on GitHub Releases. `latest` is the newest published release that is not a
|
||||
# pre-release. A fork's builds point at its own releases through GITHUB_REPOSITORY.
|
||||
REPO="${GITHUB_REPOSITORY:-storytold/wordcraft}"
|
||||
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|wordcraft-*-linux-$ARCH.AppImage.zsync"
|
||||
UPDATE_ARGS=()
|
||||
if [[ "$IS_NIGHTLY" = 0 ]]; then
|
||||
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|wordcraft-*-linux-$ARCH.AppImage.zsync"
|
||||
UPDATE_ARGS=(-u "$UPDATE_INFO")
|
||||
else
|
||||
# Nightly releases are GitHub pre-releases (`latest` only selects stable releases), so point
|
||||
# zsync update metadata at pre-release tags matching `-nightly` rather than stable `latest`.
|
||||
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest-pre|wordcraft-*-nightly*-linux-$ARCH.AppImage.zsync"
|
||||
UPDATE_ARGS=(-u "$UPDATE_INFO")
|
||||
fi
|
||||
# Extract-and-run: works without FUSE (containers, CI). The output embeds the pinned static
|
||||
# runtime, so users don't need libfuse2 either. With zsyncmake on the host (CI installs the zsync
|
||||
# package) appimagetool also writes the .zsync, into its working directory, hence the cd.
|
||||
(cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream \
|
||||
--runtime-file "$RUNTIME" -u "$UPDATE_INFO" "$APPDIR" "$OUT")
|
||||
--runtime-file "$RUNTIME" "${UPDATE_ARGS[@]}" "$APPDIR" "$OUT")
|
||||
echo "wrote $OUT"
|
||||
if [[ -s "$OUT.zsync" ]]; then
|
||||
echo "wrote $OUT.zsync"
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
# shellcheck shell=bash
|
||||
# Shared checks for the Apple-silicon Nightly scripts (nightly.sh, nightly-sign.sh, nightly-verify.sh).
|
||||
# Stable packaging (package.sh, verify.sh) does not source this file. The text checks take tool output
|
||||
# as arguments, so packaging/macos/nightly_sign_tests.py runs them without macOS.
|
||||
|
||||
MAC_NIGHTLY_APP='WordCraft Nightly.app'
|
||||
MAC_NIGHTLY_ID='ai.storyteller.wordcraft.nightly'
|
||||
# The release environment's names, as stable release.yml passes them (packaging/macos/import-cert.sh).
|
||||
MAC_NIGHTLY_SECRETS=(APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID)
|
||||
|
||||
mac_nightly_die() { printf 'error: %s\n' "$*" >&2; exit 2; }
|
||||
|
||||
# The exact prepared version from the feed asset name, or failure.
|
||||
mac_nightly_version_from_asset() {
|
||||
local name="$1" version
|
||||
[[ "$name" =~ ^wordcraft-(.+)-macos-aarch64-nightly\.zip$ ]] || return 1
|
||||
version="${BASH_REMATCH[1]}"
|
||||
[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || return 1
|
||||
printf '%s\n' "$version"
|
||||
}
|
||||
|
||||
# Every signing and notarization value is set, and the team is one Apple team ID. No ad-hoc fallback.
|
||||
mac_nightly_require_secrets() {
|
||||
local name
|
||||
for name in "${MAC_NIGHTLY_SECRETS[@]}"; do
|
||||
[[ -n "${!name:-}" ]] || mac_nightly_die "$name is not set: Nightly signing and notarization are required, with no ad-hoc fallback"
|
||||
done
|
||||
[[ "$APPLE_TEAM_ID" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'APPLE_TEAM_ID is not an Apple team ID'
|
||||
if [[ -n "${NIGHTLY_APPLE_TEAM_ID:-}" && "$NIGHTLY_APPLE_TEAM_ID" != "$APPLE_TEAM_ID" ]]; then
|
||||
mac_nightly_die 'the signing team differs from the reviewed Nightly team (NIGHTLY_APPLE_TEAM_ID)'
|
||||
fi
|
||||
}
|
||||
|
||||
# One line of `security find-identity -v -p codesigning`: the identity is a Developer ID Application of the team.
|
||||
mac_nightly_identity_is_team() {
|
||||
local line="$1" identity="$2" team="$3"
|
||||
[[ "$line" == *" $identity "* && "$line" == *'"Developer ID Application: '*" ($team)\""* ]]
|
||||
}
|
||||
|
||||
# `codesign -d --verbose=2` of the signed bundle: the Nightly identifier, a Developer ID Application of the
|
||||
# team, a secure timestamp and the hardened runtime (the checks of verify.sh, made strict).
|
||||
mac_nightly_check_signature() {
|
||||
local details="$1" team="$2" ok=0
|
||||
grep -Fqx "Identifier=$MAC_NIGHTLY_ID" <<<"$details" || { echo "error: the bundle is not signed as $MAC_NIGHTLY_ID" >&2; ok=1; }
|
||||
grep -q '^Authority=Developer ID Application:' <<<"$details" || { echo 'error: not signed with a Developer ID Application identity' >&2; ok=1; }
|
||||
grep -qx "TeamIdentifier=$team" <<<"$details" || { echo 'error: signed by a different team' >&2; ok=1; }
|
||||
grep -q '^Timestamp=' <<<"$details" || { echo 'error: the signature has no secure timestamp' >&2; ok=1; }
|
||||
grep -Eq '^CodeDirectory .*flags=0x[0-9a-f]+\([^)]*runtime' <<<"$details" || { echo 'error: not signed with the hardened runtime' >&2; ok=1; }
|
||||
return "$ok"
|
||||
}
|
||||
|
||||
# `spctl --assess --type execute -vv`: Gatekeeper accepts the bundle as notarized.
|
||||
mac_nightly_check_assessment() {
|
||||
grep -q 'accepted' <<<"$1" && grep -qx 'source=Notarized Developer ID' <<<"$1"
|
||||
}
|
||||
|
||||
# Before anything is unpacked: every ZIP entry is a regular file or directory inside the one Nightly
|
||||
# bundle, with no absolute path, `..`, backslash or empty component, and no link or special file.
|
||||
mac_nightly_check_zip_entries() {
|
||||
python3 -I - "$1" "$MAC_NIGHTLY_APP" <<'PY' || mac_nightly_die 'the archive has an entry outside the bundle, a link or a special file'
|
||||
import stat, sys, zipfile
|
||||
archive, app = sys.argv[1:]
|
||||
with zipfile.ZipFile(archive) as z:
|
||||
for info in z.infolist():
|
||||
name = info.filename
|
||||
parts = name.rstrip("/").split("/")
|
||||
mode = info.external_attr >> 16
|
||||
if (name.startswith("/") or "\\" in name or "\0" in name or parts[0] != app
|
||||
or any(part in ("", ".", "..") for part in parts)
|
||||
or stat.S_IFMT(mode) not in (0, stat.S_IFREG, stat.S_IFDIR)):
|
||||
sys.exit(f"refused entry: {name!r}")
|
||||
PY
|
||||
}
|
||||
|
||||
# An unpacked payload directory holds exactly the GUI-only Nightly bundle: one thin arm64 WordCraft
|
||||
# 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")" == WordCraft ]] || mac_nightly_die 'Contents/MacOS must hold only the WordCraft GUI (no CLI)'
|
||||
[[ -f "$app/Contents/MacOS/WordCraft" && -x "$app/Contents/MacOS/WordCraft" ]] || mac_nightly_die 'missing executable GUI'
|
||||
[[ "$(lipo -archs "$app/Contents/MacOS/WordCraft")" == arm64 ]] || mac_nightly_die 'the GUI must be thin arm64'
|
||||
plist="$app/Contents/Info.plist"
|
||||
for key in CFBundleIdentifier CFBundleExecutable WordCraftVersion; 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" == WordCraft ]] ;;
|
||||
WordCraftVersion) [[ "$value" == "$version" ]] ;;
|
||||
esac || mac_nightly_die "Info.plist $key is not the prepared Nightly identity"
|
||||
done
|
||||
for key in CFBundleDocumentTypes CFBundleURLTypes UTExportedTypeDeclarations UTImportedTypeDeclarations; do
|
||||
if plutil -extract "$key" xml1 -o - "$plist" >/dev/null 2>&1; then mac_nightly_die "Nightly declares $key"; fi
|
||||
done
|
||||
}
|
||||
|
||||
# `stapler validate` asks Apple's CloudKit service, which sometimes drops the connection (error 68)
|
||||
# though the ticket is there (verify.sh).
|
||||
mac_nightly_validate_staple() {
|
||||
local target="$1" attempt
|
||||
for attempt in 1 2 3 4 5; do
|
||||
xcrun stapler validate "$target" && return 0
|
||||
[[ "$attempt" = 5 ]] || sleep $((attempt * 20))
|
||||
done
|
||||
return 1
|
||||
}
|
||||
Executable
+144
@@ -0,0 +1,144 @@
|
||||
#!/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/wordcraft-<version>-macos-aarch64-nightly.zip \
|
||||
# --output /abs/<dir>/wordcraft-<version>-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%/}/wordcraft-nightly-sign.XXXXXX")"
|
||||
cleanup() {
|
||||
# import-cert.sh makes its keychain in a private folder of its own under RUNNER_TEMP.
|
||||
if [[ -n "${MACOS_KEYCHAIN:-}" && -e "$MACOS_KEYCHAIN" ]]; then security delete-keychain "$MACOS_KEYCHAIN" >/dev/null 2>&1 || rm -f -- "$MACOS_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. It keeps
|
||||
# its own private folder under RUNNER_TEMP and names the keychain it made; that path must stay
|
||||
# inside this work directory (this app's script differs from PhotoCraft's in that layout).
|
||||
imported="$(GITHUB_ENV='' RUNNER_TEMP="$WORK" bash "$HERE/import-cert.sh")"
|
||||
IDENTITY="$(sed -n 's/^MACOS_SIGN_IDENTITY=//p' <<<"$imported")"
|
||||
MACOS_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'
|
||||
[[ "$MACOS_KEYCHAIN" == "$WORK"/* && -f "$MACOS_KEYCHAIN" && ! -L "$MACOS_KEYCHAIN" ]] \
|
||||
|| mac_nightly_die 'import-cert.sh did not make its keychain inside this run private directory'
|
||||
mac_nightly_identity_is_team "$(security find-identity -v -p codesigning "$MACOS_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 "==> WordCraft 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 "$MACOS_KEYCHAIN" --timestamp "$@"
|
||||
}
|
||||
|
||||
notarize() {
|
||||
local file="$1" out id status
|
||||
echo "==> notarizing $(basename "$file") (this can take a few minutes)"
|
||||
out="$(xcrun notarytool submit "$file" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" \
|
||||
--team-id "$APPLE_TEAM_ID" --wait --timeout 1h --output-format json)" || true
|
||||
echo "$out"
|
||||
id="$(printf '%s' "$out" | plutil -extract id raw -o - - 2>/dev/null || true)"
|
||||
status="$(printf '%s' "$out" | plutil -extract status raw -o - - 2>/dev/null || true)"
|
||||
if [[ "$status" != "Accepted" ]]; then
|
||||
if [[ -n "$id" ]]; then
|
||||
# Capped: the shared signer bounds a step's output at 256 KiB.
|
||||
xcrun notarytool log "$id" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" --team-id "$APPLE_TEAM_ID" | head -c 131072 || true
|
||||
fi
|
||||
echo "error: notarization of $(basename "$file") failed (status: ${status:-unknown})" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Stapling and validating both look the ticket up in Apple's CloudKit service, which can drop the
|
||||
# connection right after notarization (error 68), so retry the pair (package.sh).
|
||||
staple() {
|
||||
local file="$1" attempt
|
||||
for attempt in 1 2 3 4 5; do
|
||||
if xcrun stapler staple "$file" && xcrun stapler validate "$file"; then
|
||||
return
|
||||
fi
|
||||
if [[ "$attempt" = 5 ]]; then
|
||||
echo "error: stapling $(basename "$file") failed after $attempt attempts" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "stapling $(basename "$file") failed (attempt $attempt); retrying in $((attempt * 20))s" >&2
|
||||
sleep $((attempt * 20))
|
||||
done
|
||||
}
|
||||
|
||||
# Inside-out: the executable, then the bundle (no --deep on the final signature).
|
||||
sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/MacOS/WordCraft"
|
||||
sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP"
|
||||
codesign --verify --strict --deep --verbose=2 "$APP"
|
||||
ditto -c -k --keepParent "$APP" "$WORK/notarize.zip"
|
||||
notarize "$WORK/notarize.zip"
|
||||
# The ticket goes into the bundle (Contents/CodeResources): the Launcher's extract restores no xattrs.
|
||||
staple "$APP"
|
||||
|
||||
# ---- the final archive, checked as the Launcher unpacks it -----------------------------------------
|
||||
ditto -c -k --norsrc --noextattr --noacl --keepParent "$APP" "$WORK/final.zip"
|
||||
ditto -x -k --norsrc --noextattr "$WORK/final.zip" "$WORK/check"
|
||||
mac_nightly_check_bundle "$WORK/check" "$VERSION"
|
||||
CHECK="$WORK/check/$MAC_NIGHTLY_APP"
|
||||
codesign --verify --strict --deep --verbose=2 "$CHECK"
|
||||
mac_nightly_check_signature "$(codesign -d --verbose=2 "$CHECK" 2>&1)" "$APPLE_TEAM_ID" \
|
||||
|| mac_nightly_die 'the signed bundle is not the required Developer ID signature'
|
||||
mac_nightly_validate_staple "$CHECK" || mac_nightly_die 'no notarization ticket is stapled into the bundle'
|
||||
# spctl's lookup can lag a few seconds behind notarytool's "Accepted" (verify.sh).
|
||||
for attempt in 1 2 3 4 5; do
|
||||
assessment="$(spctl --assess --type execute -vv "$CHECK" 2>&1)" || true
|
||||
mac_nightly_check_assessment "$assessment" && break
|
||||
[[ "$attempt" = 5 ]] || sleep 10
|
||||
done
|
||||
printf '%s\n' "$assessment"
|
||||
mac_nightly_check_assessment "$assessment" || mac_nightly_die 'Gatekeeper does not accept the bundle as notarized'
|
||||
|
||||
nightly_publish_archive "$WORK/final.zip" "$OUTPUT"
|
||||
Executable
+74
@@ -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/wordcraft-<version>-macos-aarch64-nightly.zip --expect signed [--team ID]
|
||||
# nightly-verify.sh --input /abs/wordcraft-<version>-macos-aarch64-nightly.zip --expect unsigned
|
||||
#
|
||||
# Both: the archive holds only the GUI-only Nightly bundle with the exact WordCraftVersion, unpacked
|
||||
# without extended attributes. `signed` (the feed artifact): Developer ID of the team (--team, else
|
||||
# NIGHTLY_APPLE_TEAM_ID), hardened runtime, secure timestamp, stapled ticket, Gatekeeper accepts it as
|
||||
# notarized. `unsigned` (nightly.sh's compile output, e.g. pull-request CI) checks no signature.
|
||||
# Last, the bundle's GUI answers its version query with an empty environment, both plainly and in the
|
||||
# Launcher's form `--launch-profile nightly-v1 --profile-root <fresh dir> --version` (the shared producer
|
||||
# smoke): each must exit 0 within 15 seconds, print exactly `WordCraft <version> (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,18p' "$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}}/wordcraft-nightly-verify.XXXXXX")"
|
||||
trap 'rm -rf -- "$WORK"' EXIT
|
||||
mac_nightly_check_zip_entries "$INPUT"
|
||||
ditto -x -k --norsrc --noextattr "$INPUT" "$WORK/payload"
|
||||
mac_nightly_check_bundle "$WORK/payload" "$VERSION"
|
||||
APP="$WORK/payload/$MAC_NIGHTLY_APP"
|
||||
|
||||
if [[ "$EXPECT" == signed ]]; then
|
||||
codesign --verify --strict --deep --verbose=2 "$APP"
|
||||
mac_nightly_check_signature "$(codesign -d --verbose=2 "$APP" 2>&1)" "$TEAM" \
|
||||
|| mac_nightly_die 'the bundle is not the required Developer ID signature'
|
||||
mac_nightly_validate_staple "$APP" || mac_nightly_die 'no notarization ticket is stapled into the bundle'
|
||||
for attempt in 1 2 3 4 5; do
|
||||
assessment="$(spctl --assess --type execute -vv "$APP" 2>&1)" || true
|
||||
mac_nightly_check_assessment "$assessment" && break
|
||||
[[ "$attempt" = 5 ]] || sleep 10
|
||||
done
|
||||
printf '%s\n' "$assessment"
|
||||
mac_nightly_check_assessment "$assessment" || mac_nightly_die 'Gatekeeper does not accept the bundle as notarized'
|
||||
fi
|
||||
|
||||
# macOS has no timeout(1): perl's alarm survives its exec and ends a query that hangs (a dialog, say).
|
||||
query() {
|
||||
local out
|
||||
out="$(env -i HOME="$WORK/home" TMPDIR="$WORK/tmp/" PATH=/usr/bin:/bin \
|
||||
/usr/bin/perl -e 'alarm 15; exec @ARGV or die' "$APP/Contents/MacOS/WordCraft" "$@" 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" == "WordCraft $VERSION (nightly-v1)" ]] || mac_nightly_die "the version query ($*) reports '$out', not WordCraft $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): WordCraft $VERSION (nightly-v1), plain and in the Launcher's profile form"
|
||||
Executable
+51
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env bash
|
||||
# App-owned GUI-only Nightly for Apple silicon, compile step only (no signing material):
|
||||
#
|
||||
# $DIST/wordcraft-<version>-macos-aarch64-nightly.zip WordCraft Nightly.app, unsigned
|
||||
#
|
||||
# Usage: packaging/macos/nightly.sh --arch aarch64
|
||||
#
|
||||
# Required env (nightly-common.sh): WORDCRAFT_BUILD_CHANNEL=nightly-v1, WORDCRAFT_VERSION,
|
||||
# WORDCRAFT_BUILD_SHA, WORDCRAFT_BUILD_DATE, absolute CARGO_TARGET_DIR and DIST; CRAFT_FONTS_DIR optional.
|
||||
#
|
||||
# Not publishable by itself: the trusted step (nightly-sign.sh) signs, notarizes and staples it. No CLI,
|
||||
# DMG, document or URL types, and no stable package.sh. The bundle is not run here; the version query
|
||||
# runs on the signed bundle (nightly-verify.sh).
|
||||
set -euo pipefail
|
||||
ARCH=
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;;
|
||||
-h|--help) sed -n '2,13p' "$0"; exit 0 ;;
|
||||
*) echo "unsupported nightly argument: $1" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
[[ "$ARCH" == aarch64 && "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] || { echo 'only native macOS aarch64 nightly packaging is supported' >&2; exit 2; }
|
||||
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
. "$HERE/../nightly-common.sh"
|
||||
. "$HERE/nightly-lib.sh"
|
||||
nightly_refuse_signing_env
|
||||
nightly_init macos "$ARCH" aarch64-apple-darwin
|
||||
# Keep in sync with LSMinimumSystemVersion in Info.plist.in (as package.sh).
|
||||
export MACOSX_DEPLOYMENT_TARGET=11.0
|
||||
OUTPUT="$DIST/wordcraft-$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/WordCraft"
|
||||
chmod 755 "$APP/Contents/MacOS/WordCraft"
|
||||
cp "$ROOT/assets/app-icon/wordcraft-nightly.icns" "$APP/Contents/Resources/wordcraft-nightly.icns"
|
||||
nightly_copy_notices "$APP/Contents/Resources"
|
||||
# The private mktemp cwd is the helper authority root: stage the template inside it.
|
||||
cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in"
|
||||
(cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \
|
||||
--output "stage/$MAC_NIGHTLY_APP/Contents/Info.plist" --version "$VERSION" --source-commit "$WORDCRAFT_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"
|
||||
Executable
+69
@@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Nightly metadata: run from a private owned build cwd with a staged template.
|
||||
|
||||
All file arguments must stay beneath that cwd; this is not native/signing acceptance.
|
||||
"""
|
||||
import argparse
|
||||
import datetime
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import re
|
||||
import sys
|
||||
|
||||
# The shared helper location is fixed by this script, not by CLI file arguments.
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from nightly_paths import OwnedBuildRoot
|
||||
|
||||
MAX_TEMPLATE_BYTES = 256 * 1024
|
||||
|
||||
IDENTIFIER = "ai.storyteller.wordcraft.nightly"
|
||||
ASSOCIATIONS = ("CFBundleDocumentTypes", "CFBundleURLTypes", "UTExportedTypeDeclarations", "UTImportedTypeDeclarations")
|
||||
VERSION = re.compile(r"([0-9]+\.[0-9]+\.[0-9]+)-nightly\.([0-9]{8})\.[0-9]+\.[0-9]+\.g([0-9a-f]{12})\Z")
|
||||
|
||||
|
||||
def render(template: bytes, version: str, commit: str) -> bytes:
|
||||
match = VERSION.fullmatch(version)
|
||||
if not match or not re.fullmatch(r"[0-9a-f]{40}", commit) or match[3] != commit[:12]:
|
||||
raise ValueError("exact prepared Nightly version and matching source commit are required")
|
||||
datetime.datetime.strptime(match[2], "%Y%m%d")
|
||||
data = plistlib.loads(template)
|
||||
if not isinstance(data, dict) or data.get("CFBundlePackageType") != "APPL":
|
||||
raise ValueError("expected the app-owned application plist template")
|
||||
for key in ASSOCIATIONS:
|
||||
data.pop(key, None)
|
||||
data.update(
|
||||
CFBundleDisplayName="WordCraft Nightly",
|
||||
CFBundleName="WordCraft Nightly",
|
||||
CFBundleIdentifier=IDENTIFIER,
|
||||
CFBundleExecutable="WordCraft",
|
||||
CFBundleIconFile="wordcraft-nightly",
|
||||
CFBundleShortVersionString=match[1],
|
||||
CFBundleVersion=match[1],
|
||||
WordCraftVersion=version,
|
||||
WordCraftBuildCommit=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()
|
||||
Executable
+203
@@ -0,0 +1,203 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generated metadata/sentinel fixtures; no native binary, signature, archive or network."""
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import runpy
|
||||
import sys
|
||||
from unittest import mock
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
SPEC = importlib.util.spec_from_file_location("photo_nightly_plist", HERE / "nightly_plist.py")
|
||||
POLICY = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(POLICY)
|
||||
COMMIT = "a" * 40
|
||||
VERSION = "0.23.1-nightly.20261121.12345.1.g" + COMMIT[:12]
|
||||
|
||||
|
||||
class NightlyMetadata(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.directory.cleanup)
|
||||
self.root = Path(self.directory.name).resolve()
|
||||
previous = Path.cwd()
|
||||
os.chdir(self.root)
|
||||
self.addCleanup(os.chdir, previous)
|
||||
self.template = self.root / "Info.plist.in"
|
||||
self.original = (HERE / "Info.plist.in").read_bytes()
|
||||
self.template.write_bytes(self.original)
|
||||
self.output = self.root / "Info.plist"
|
||||
|
||||
def test_nightly_transform_removes_associations_without_changing_stable_or_platform_metadata(self):
|
||||
stable = plistlib.loads(self.original)
|
||||
stable["CFBundleURLTypes"] = [{"CFBundleURLSchemes": ["generated-test-scheme"]}]
|
||||
prepared = plistlib.dumps(stable)
|
||||
self.template.write_bytes(prepared)
|
||||
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
|
||||
rendered = plistlib.loads(self.output.read_bytes())
|
||||
for key in POLICY.ASSOCIATIONS:
|
||||
self.assertNotIn(key, rendered)
|
||||
self.assertNotEqual(rendered["CFBundleIdentifier"], stable["CFBundleIdentifier"])
|
||||
self.assertEqual(rendered["CFBundleIdentifier"], "ai.storyteller.wordcraft.nightly")
|
||||
self.assertEqual(rendered["CFBundleExecutable"], "WordCraft")
|
||||
self.assertEqual(rendered["WordCraftVersion"], VERSION)
|
||||
self.assertEqual(rendered["WordCraftBuildCommit"], COMMIT)
|
||||
self.assertTrue(VERSION.startswith(rendered["CFBundleVersion"] + "-nightly."))
|
||||
# WordCraft's own Info.plist platform metadata survives the Nightly transform unchanged.
|
||||
for key in ("LSMinimumSystemVersion", "NSHighResolutionCapable", "NSHumanReadableCopyright", "NSSupportsAutomaticGraphicsSwitching", "LSApplicationCategoryType"):
|
||||
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["WordCraftVersion"], VERSION)
|
||||
self.assertEqual(result["WordCraftBuildCommit"], 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())["WordCraftVersion"], VERSION)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Executable
+425
@@ -0,0 +1,425 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The macOS Nightly signing and verification scripts, run on any POSIX host against generated
|
||||
fixtures and stand-in Apple tools (codesign, notarytool, stapler, spctl, security, ditto, plutil,
|
||||
lipo) that log their arguments. This proves the scripts' order, refusals and cleanup; it is not a
|
||||
real signature, notarization or Mac run."""
|
||||
import base64
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import textwrap
|
||||
import time
|
||||
import unittest
|
||||
import zipfile
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
SPEC = importlib.util.spec_from_file_location("photo_mac_nightly_plist", HERE / "nightly_plist.py")
|
||||
PLIST = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(PLIST)
|
||||
COMMIT = "b" * 40
|
||||
VERSION = "0.23.1-nightly.20261123.4567.1.g" + COMMIT[:12]
|
||||
ASSET = f"wordcraft-{VERSION}-macos-aarch64-nightly.zip"
|
||||
APP = "WordCraft Nightly.app"
|
||||
TEAM = "ABCDE12345"
|
||||
IDENTITY = "0123456789ABCDEF0123456789ABCDEF01234567"
|
||||
SECRETS = {
|
||||
"APPLE_CERTIFICATE": base64.b64encode(b"generated fixture, not a certificate").decode(),
|
||||
"APPLE_CERTIFICATE_PASSWORD": "generated-fixture",
|
||||
"KEYCHAIN_PASSWORD": "generated-fixture",
|
||||
"APPLE_ID": "fixture@example.invalid",
|
||||
"APPLE_PASSWORD": "generated-fixture",
|
||||
"APPLE_TEAM_ID": TEAM,
|
||||
}
|
||||
|
||||
# One stand-in for every Apple tool, dispatched on its own name. Each logs its argv as a JSON line.
|
||||
SHIM = r"""
|
||||
import json, os, plistlib, sys, zipfile
|
||||
from pathlib import Path
|
||||
name = Path(sys.argv[0]).name
|
||||
args = sys.argv[1:]
|
||||
with open(os.environ["SHIM_LOG"], "a") as log:
|
||||
log.write(json.dumps([name] + args) + "\n")
|
||||
team = os.environ.get("SHIM_TEAM", "")
|
||||
if name == "uname":
|
||||
print({"-s": "Darwin", "-m": "arm64"}.get(args[0], "Darwin"))
|
||||
elif name == "lipo":
|
||||
print("arm64")
|
||||
elif name == "ditto":
|
||||
paths = [a for a in args if not a.startswith("-")]
|
||||
src, dst = paths
|
||||
if "-x" in args:
|
||||
with zipfile.ZipFile(src) as z:
|
||||
for info in z.infolist():
|
||||
target = Path(dst) / info.filename
|
||||
if info.is_dir():
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
continue
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(z.read(info))
|
||||
mode = (info.external_attr >> 16) & 0o777
|
||||
if mode:
|
||||
target.chmod(mode)
|
||||
else:
|
||||
root = Path(src)
|
||||
with zipfile.ZipFile(dst, "x") as z:
|
||||
for path in sorted([root] + list(root.rglob("*"))):
|
||||
arc = (Path(root.name) / path.relative_to(root)).as_posix()
|
||||
if path.is_dir():
|
||||
z.writestr(zipfile.ZipInfo(arc + "/"), b"")
|
||||
else:
|
||||
info = zipfile.ZipInfo(arc)
|
||||
info.external_attr = (path.stat().st_mode & 0xFFFF) << 16
|
||||
z.writestr(info, path.read_bytes())
|
||||
elif name == "plutil":
|
||||
if args[0] == "-lint":
|
||||
sys.exit(0)
|
||||
key, fmt, source = args[1], args[2], args[-1]
|
||||
data = sys.stdin.read() if source == "-" else Path(source).read_bytes()
|
||||
value = json.loads(data) if source == "-" else plistlib.loads(data)
|
||||
if key not in value:
|
||||
sys.exit(1)
|
||||
print(value[key] if fmt == "raw" else "<present/>")
|
||||
elif name == "security":
|
||||
verb = args[0]
|
||||
if verb == "create-keychain":
|
||||
Path(args[-1]).write_bytes(b"keychain")
|
||||
elif verb == "find-identity":
|
||||
print(' 1) %s "Developer ID Application: Generated Fixture (%s)"' % (os.environ["SHIM_IDENTITY"], team))
|
||||
print(" 1 valid identities found")
|
||||
elif verb == "delete-keychain":
|
||||
Path(args[-1]).unlink()
|
||||
elif name == "codesign":
|
||||
target = Path(args[-1])
|
||||
if "--sign" in args and target.suffix == ".app":
|
||||
(target / "Contents/_CodeSignature").mkdir(exist_ok=True)
|
||||
(target / "Contents/_CodeSignature/CodeResources").write_bytes(b"sealed")
|
||||
if "-d" in args:
|
||||
sys.stderr.write("Executable=%s\nIdentifier=ai.storyteller.wordcraft.nightly\n"
|
||||
"CodeDirectory v=20500 size=1 flags=0x10000(runtime) hashes=1+7 location=embedded\n"
|
||||
"Authority=Developer ID Application: Generated Fixture (%s)\n"
|
||||
"Timestamp=23 Nov 2026 at 17:00:00\nTeamIdentifier=%s\n" % (target, team, team))
|
||||
elif name == "xcrun":
|
||||
if args[:2] == ["notarytool", "submit"]:
|
||||
print(json.dumps({"id": "generated-id", "status": os.environ.get("SHIM_NOTARY", "Accepted")}))
|
||||
elif args[:2] == ["stapler", "staple"]:
|
||||
(Path(args[2]) / "Contents/CodeResources").write_bytes(b"ticket")
|
||||
elif args[:2] == ["stapler", "validate"]:
|
||||
sys.exit(0 if (Path(args[2]) / "Contents/CodeResources").is_file() else 1)
|
||||
elif name == "spctl":
|
||||
sys.stderr.write("%s: accepted\nsource=Notarized Developer ID\n" % args[-1])
|
||||
elif name == "cargo":
|
||||
sys.exit(1)
|
||||
# sleep: the retry waits pass at once.
|
||||
"""
|
||||
|
||||
TOOLS = ("uname", "lipo", "ditto", "plutil", "security", "codesign", "xcrun", "spctl", "cargo", "sleep")
|
||||
|
||||
|
||||
class Fixture:
|
||||
def __init__(self, test):
|
||||
self.directory = tempfile.TemporaryDirectory()
|
||||
test.addCleanup(self.directory.cleanup)
|
||||
self.root = Path(self.directory.name).resolve()
|
||||
self.bin = self.root / "bin"
|
||||
self.bin.mkdir()
|
||||
shim = self.bin / "shim.py"
|
||||
shim.write_text(SHIM)
|
||||
for tool in TOOLS:
|
||||
path = self.bin / tool
|
||||
path.write_text(f"#!{sys.executable}\nimport sys\nsys.argv[0] = {str(path)!r}\nexec(compile(open({str(shim)!r}).read(), 'shim', 'exec'), {{'__name__': '__main__'}})\n")
|
||||
path.chmod(0o755)
|
||||
self.log = self.root / "tools.log"
|
||||
self.ran = self.root / "payload-ran"
|
||||
self.temp = self.root / "runner-temp"
|
||||
self.temp.mkdir()
|
||||
self.dist = self.root / "unsigned"
|
||||
self.dist.mkdir()
|
||||
self.signed = self.root / "signed"
|
||||
self.signed.mkdir()
|
||||
self.input = self.dist / ASSET
|
||||
self.output = self.signed / ASSET
|
||||
# Every script runs from a directory with modules a Python helper must not import (-I).
|
||||
self.cwd = self.root / "cwd"
|
||||
self.cwd.mkdir()
|
||||
self.hijacked = self.root / "hijacked"
|
||||
for module in ("shutil", "zipfile", "stat"):
|
||||
(self.cwd / f"{module}.py").write_text(f"open({str(self.hijacked)!r}, 'a').write({module!r})\n")
|
||||
|
||||
def add_entry(self, info, data=b""):
|
||||
"""Append one raw entry to the input archive."""
|
||||
with zipfile.ZipFile(self.input, "a") as z:
|
||||
z.writestr(info, data)
|
||||
|
||||
def bundle(self, version=VERSION, extra=None, gui=None):
|
||||
"""The archive nightly.sh makes: the real template through the real plist helper."""
|
||||
stage = self.root / "stage"
|
||||
shutil.rmtree(stage, ignore_errors=True)
|
||||
app = stage / APP
|
||||
(app / "Contents/MacOS").mkdir(parents=True)
|
||||
(app / "Contents/Resources").mkdir()
|
||||
exe = app / "Contents/MacOS/WordCraft"
|
||||
exe.write_text(gui or f"#!/bin/sh\ntouch {self.ran}\necho 'WordCraft {version} (nightly-v1)'\n")
|
||||
exe.chmod(0o755)
|
||||
(app / "Contents/Resources/wordcraft-nightly.icns").write_bytes(b"generated icon")
|
||||
rendered = PLIST.render((HERE / "Info.plist.in").read_bytes(), version, COMMIT)
|
||||
(app / "Contents/Info.plist").write_bytes(rendered)
|
||||
for relative, data in (extra or {}).items():
|
||||
(app / relative).write_bytes(data)
|
||||
(app / relative).chmod(0o755)
|
||||
if self.input.exists():
|
||||
self.input.unlink()
|
||||
with zipfile.ZipFile(self.input, "x") as z:
|
||||
for path in sorted([app] + list(app.rglob("*"))):
|
||||
arc = (Path(APP) / path.relative_to(app)).as_posix()
|
||||
info = zipfile.ZipInfo(arc + ("/" if path.is_dir() else ""))
|
||||
info.external_attr = (path.stat().st_mode & 0xFFFF) << 16
|
||||
z.writestr(info, b"" if path.is_dir() else path.read_bytes())
|
||||
return self.input
|
||||
|
||||
def env(self, **changes):
|
||||
env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.root), "SHIM_LOG": str(self.log),
|
||||
"SHIM_TEAM": TEAM, "SHIM_IDENTITY": IDENTITY, "RUNNER_TEMP": str(self.temp), **SECRETS}
|
||||
env.update(changes)
|
||||
return {key: value for key, value in env.items() if value is not None}
|
||||
|
||||
def run(self, script, *args, **env):
|
||||
if self.log.exists():
|
||||
self.log.unlink()
|
||||
return subprocess.run(["bash", str(HERE / script), *map(str, args)], env=self.env(**env), cwd=self.cwd,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120)
|
||||
|
||||
def sign(self, **env):
|
||||
return self.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.input, "--output", self.output, **env)
|
||||
|
||||
def calls(self):
|
||||
if not self.log.exists():
|
||||
return []
|
||||
return [json.loads(line) for line in self.log.read_text().splitlines()]
|
||||
|
||||
|
||||
def lib(function, *args):
|
||||
"""Run one nightly-lib.sh function; returns (exit status, stdout)."""
|
||||
script = f'. {str(HERE / "nightly-lib.sh")!r}; {function} "$@"'
|
||||
result = subprocess.run(["bash", "-c", script, "lib", *args], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
|
||||
return result.returncode, result.stdout.strip()
|
||||
|
||||
|
||||
DETAILS = (f"Identifier=ai.storyteller.wordcraft.nightly\nCodeDirectory v=20500 size=1 flags=0x10000(runtime) hashes=1\n"
|
||||
f"Authority=Developer ID Application: Generated Fixture ({TEAM})\nAuthority=Developer ID Certification Authority\n"
|
||||
f"Timestamp=23 Nov 2026\nTeamIdentifier={TEAM}\n")
|
||||
|
||||
|
||||
class Checks(unittest.TestCase):
|
||||
def test_the_version_comes_only_from_a_prepared_nightly_asset_name(self):
|
||||
self.assertEqual(lib("mac_nightly_version_from_asset", ASSET), (0, VERSION))
|
||||
for name in (f"wordcraft-0.23.1-macos-aarch64.zip", f"wordcraft-{VERSION}-macos-universal-nightly.zip",
|
||||
f"wordcraft-{VERSION}-linux-x86_64-nightly.tar.gz", ASSET.replace(".g", ".x"), "../" + ASSET):
|
||||
with self.subTest(name=name):
|
||||
self.assertNotEqual(lib("mac_nightly_version_from_asset", name)[0], 0)
|
||||
|
||||
def test_signature_needs_every_part_of_the_developer_id_signature(self):
|
||||
self.assertEqual(lib("mac_nightly_check_signature", DETAILS, TEAM)[0], 0)
|
||||
for broken in (DETAILS.replace("flags=0x10000(runtime)", "flags=0x0(none)"),
|
||||
DETAILS.replace("Timestamp=23 Nov 2026\n", "Signed Time=23 Nov 2026\n"),
|
||||
"Identifier=wordcraft-1234\nSignature=adhoc\nTeamIdentifier=not set\n",
|
||||
DETAILS.replace("ai.storyteller.wordcraft.nightly", "ai.storyteller.wordcraft"),
|
||||
DETAILS.replace("ai.storyteller.wordcraft.nightly", "aiXstorytellerXwordcraftXnightly")):
|
||||
with self.subTest(broken=broken):
|
||||
self.assertNotEqual(lib("mac_nightly_check_signature", broken, TEAM)[0], 0)
|
||||
self.assertNotEqual(lib("mac_nightly_check_signature", DETAILS, "ZZZZZ99999")[0], 0, "another team")
|
||||
|
||||
def test_gatekeeper_must_accept_the_bundle_as_notarized(self):
|
||||
self.assertEqual(lib("mac_nightly_check_assessment", "x.app: accepted\nsource=Notarized Developer ID\n")[0], 0)
|
||||
for text in ("x.app: accepted\nsource=Developer ID\n", "x.app: rejected\nsource=Unnotarized Developer ID\n"):
|
||||
with self.subTest(text=text):
|
||||
self.assertNotEqual(lib("mac_nightly_check_assessment", text)[0], 0)
|
||||
|
||||
def test_the_imported_identity_must_be_a_developer_id_of_the_team(self):
|
||||
line = f' 1) {IDENTITY} "Developer ID Application: Generated Fixture ({TEAM})"'
|
||||
self.assertEqual(lib("mac_nightly_identity_is_team", line, IDENTITY, TEAM)[0], 0)
|
||||
self.assertNotEqual(lib("mac_nightly_identity_is_team", line, IDENTITY, "ZZZZZ99999")[0], 0)
|
||||
self.assertNotEqual(lib("mac_nightly_identity_is_team", line.replace("Developer ID Application", "Apple Development"), IDENTITY, TEAM)[0], 0)
|
||||
|
||||
|
||||
class Sign(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.f = Fixture(self)
|
||||
self.f.bundle()
|
||||
self.unsigned = self.f.input.read_bytes()
|
||||
|
||||
def assert_refused_untouched(self, result, signed=False):
|
||||
self.assertNotEqual(result.returncode, 0, result.stdout)
|
||||
self.assertFalse(self.f.output.exists())
|
||||
self.assertEqual(self.f.input.read_bytes(), self.unsigned)
|
||||
self.assertFalse(self.f.ran.exists(), "the payload must never run in the signing step")
|
||||
names = [call[0] for call in self.f.calls()]
|
||||
self.assertNotIn("cargo", names)
|
||||
if not signed:
|
||||
self.assertNotIn("codesign", names)
|
||||
self.assertNotIn("xcrun", names)
|
||||
self.assertEqual(list(self.f.temp.iterdir()), [], "the work directory and keychain are removed")
|
||||
|
||||
def test_signs_notarizes_and_staples_without_running_the_payload(self):
|
||||
result = self.f.sign()
|
||||
self.assertEqual(result.returncode, 0, result.stdout)
|
||||
self.assertFalse(self.f.hijacked.exists(), "helpers run isolated (python3 -I) beside the secrets")
|
||||
calls = self.f.calls()
|
||||
names = [call[0] for call in calls]
|
||||
self.assertNotIn("cargo", names)
|
||||
self.assertFalse(self.f.ran.exists(), "the payload must never run in the signing step")
|
||||
self.assertEqual(self.f.input.read_bytes(), self.unsigned)
|
||||
signs = [call for call in calls if call[0] == "codesign" and "--sign" in call]
|
||||
self.assertEqual([Path(call[-1]).name for call in signs], ["WordCraft", APP], "inside-out: executable, then bundle")
|
||||
for call in signs:
|
||||
for flag in ("--force", "--timestamp", "runtime", str(HERE / "entitlements.plist"), IDENTITY):
|
||||
self.assertIn(flag, call)
|
||||
order = [" ".join(call[:3]) for call in calls]
|
||||
submit = order.index("xcrun notarytool submit")
|
||||
staple = order.index("xcrun stapler staple")
|
||||
self.assertLess(max(i for i, call in enumerate(calls) if call[0] == "codesign" and "--sign" in call), submit)
|
||||
self.assertLess(submit, staple)
|
||||
final = [i for i, call in enumerate(calls) if call[0] == "ditto" and "-c" in call][-1]
|
||||
self.assertLess(staple, final, "the final archive carries the stapled ticket")
|
||||
self.assertIn("--noextattr", calls[final])
|
||||
self.assertIn(["security", "delete-keychain"], [call[:2] for call in calls])
|
||||
self.assertEqual(list(self.f.temp.iterdir()), [], "the work directory and keychain are removed")
|
||||
with zipfile.ZipFile(self.f.output) as z:
|
||||
names = set(z.namelist())
|
||||
self.assertIn(f"{APP}/Contents/CodeResources", names, "stapled ticket inside the bundle")
|
||||
self.assertIn(f"{APP}/Contents/_CodeSignature/CodeResources", names)
|
||||
self.assertTrue(all(name.startswith(APP) for name in names))
|
||||
mode = z.getinfo(f"{APP}/Contents/MacOS/WordCraft").external_attr >> 16
|
||||
self.assertTrue(mode & stat.S_IXUSR)
|
||||
|
||||
def test_every_signing_and_notarization_secret_is_required(self):
|
||||
for name in SECRETS:
|
||||
with self.subTest(missing=name):
|
||||
self.assert_refused_untouched(self.f.sign(**{name: None}))
|
||||
self.assertEqual(self.f.calls(), [], "no tool runs before the configuration is complete")
|
||||
self.assert_refused_untouched(self.f.sign(NIGHTLY_APPLE_TEAM_ID="ZZZZZ99999"))
|
||||
self.assert_refused_untouched(self.f.sign(APPLE_TEAM_ID="not-a-team"))
|
||||
|
||||
def test_refuses_another_team_s_identity(self):
|
||||
self.assert_refused_untouched(self.f.sign(SHIM_TEAM="ZZZZZ99999"))
|
||||
|
||||
def test_never_replaces_an_output_or_renames_the_asset(self):
|
||||
self.f.output.write_bytes(b"generated existing artifact")
|
||||
result = self.f.sign()
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual(self.f.output.read_bytes(), b"generated existing artifact")
|
||||
self.f.output.unlink()
|
||||
renamed = self.f.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.f.input, "--output", self.f.signed / "other.zip")
|
||||
self.assertNotEqual(renamed.returncode, 0)
|
||||
relative = self.f.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.f.input.name, "--output", self.f.output)
|
||||
self.assertNotEqual(relative.returncode, 0)
|
||||
self.assertEqual(list(self.f.signed.iterdir()), [])
|
||||
|
||||
def test_refuses_a_payload_that_is_not_the_exact_gui_only_nightly(self):
|
||||
cases = {
|
||||
"cli": dict(extra={"Contents/MacOS/wordcraft-cli": b"generated cli"}),
|
||||
"version": dict(version=VERSION.replace("4567", "4568")),
|
||||
}
|
||||
for label, change in cases.items():
|
||||
with self.subTest(label=label):
|
||||
self.f.bundle(**change)
|
||||
self.unsigned = self.f.input.read_bytes()
|
||||
self.assert_refused_untouched(self.f.sign())
|
||||
|
||||
def test_refuses_links_traversal_and_foreign_entries_before_unpacking(self):
|
||||
link = zipfile.ZipInfo(f"{APP}/Contents/Resources/link")
|
||||
link.external_attr = (stat.S_IFLNK | 0o777) << 16
|
||||
fifo = zipfile.ZipInfo(f"{APP}/Contents/Resources/fifo")
|
||||
fifo.external_attr = (stat.S_IFIFO | 0o644) << 16
|
||||
for label, info in (("link", link), ("special", fifo), ("traversal", zipfile.ZipInfo(f"{APP}/../outside")),
|
||||
("absolute", zipfile.ZipInfo("/tmp/outside")), ("foreign root", zipfile.ZipInfo("Other.app/x"))):
|
||||
with self.subTest(label=label):
|
||||
self.f.bundle()
|
||||
self.f.add_entry(info, b"/etc/passwd")
|
||||
self.unsigned = self.f.input.read_bytes()
|
||||
result = self.f.sign()
|
||||
self.assert_refused_untouched(result)
|
||||
self.assertNotIn("ditto", [call[0] for call in self.f.calls()], "refused before unpacking")
|
||||
|
||||
def test_a_rejected_notarization_publishes_nothing_and_removes_the_keychain(self):
|
||||
result = self.f.sign(SHIM_NOTARY="Invalid")
|
||||
self.assert_refused_untouched(result, signed=True)
|
||||
self.assertIn(["xcrun", "notarytool", "log"], [call[:3] for call in self.f.calls()])
|
||||
self.assertNotIn(["xcrun", "stapler", "staple"], [call[:3] for call in self.f.calls()])
|
||||
|
||||
|
||||
class Verify(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.f = Fixture(self)
|
||||
|
||||
def verify(self, *args, **env):
|
||||
return self.f.run("nightly-verify.sh", "--input", self.f.input, *args, **{name: None for name in SECRETS}, **env)
|
||||
|
||||
def test_asks_the_gui_its_version_with_an_empty_environment(self):
|
||||
self.f.bundle(gui=f"#!/bin/sh\n[ -z \"$INHERITED\" ] || exit 9\necho 'WordCraft {VERSION} (nightly-v1)'\n")
|
||||
result = self.verify("--expect", "unsigned", INHERITED="generated")
|
||||
self.assertEqual(result.returncode, 0, result.stdout)
|
||||
self.f.bundle(gui="#!/bin/sh\necho 'WordCraft 0.23.1 (stable)'\n")
|
||||
self.assertNotEqual(self.verify("--expect", "unsigned").returncode, 0)
|
||||
|
||||
def test_the_launcher_profile_form_must_answer_promptly_and_cleanly(self):
|
||||
answer = f"echo 'WordCraft {VERSION} (nightly-v1)'"
|
||||
# The shared producer smoke's exact form, with a fresh profile directory.
|
||||
exact = ('#!/bin/sh\nif [ "$1" = --launch-profile ]; then\n'
|
||||
' [ "$#" = 5 ] && [ "$2" = nightly-v1 ] && [ "$3" = --profile-root ] && [ -d "$4" ] && [ "$5" = --version ] || exit 7\n'
|
||||
f'fi\n{answer}\n')
|
||||
self.f.bundle(gui=exact)
|
||||
result = self.verify("--expect", "unsigned")
|
||||
self.assertEqual(result.returncode, 0, result.stdout)
|
||||
hangs = f'#!/bin/sh\n[ "$1" != --launch-profile ] || exec /bin/sleep 60\n{answer}\n'
|
||||
self.f.bundle(gui=hangs)
|
||||
started = time.monotonic()
|
||||
result = self.verify("--expect", "unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("within 15 s", result.stdout)
|
||||
self.assertLess(time.monotonic() - started, 45, "a hanging query is ended, not waited for")
|
||||
noisy = f'#!/bin/sh\n[ "$1" != --launch-profile ] || echo refusal >&2\n{answer}\n'
|
||||
self.f.bundle(gui=noisy)
|
||||
result = self.verify("--expect", "unsigned")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("standard error", result.stdout)
|
||||
|
||||
def test_a_signed_check_needs_the_signature_ticket_and_team(self):
|
||||
self.f.bundle()
|
||||
self.assertNotEqual(self.verify("--expect", "signed").returncode, 0, "no team to check against")
|
||||
self.assertNotEqual(self.verify("--expect", "signed", "--team", TEAM).returncode, 0, "no stapled ticket")
|
||||
self.f.bundle(extra={"Contents/CodeResources": b"ticket"})
|
||||
self.assertEqual(self.verify("--expect", "signed", "--team", TEAM).returncode, 0)
|
||||
self.assertNotEqual(self.verify("--expect", "signed", "--team", TEAM, SHIM_TEAM="ZZZZZ99999").returncode, 0)
|
||||
|
||||
def test_refuses_to_run_the_payload_beside_signing_material(self):
|
||||
self.f.bundle()
|
||||
for name in ("APPLE_PASSWORD", "APPLE_CERTIFICATE", "MACOS_KEYCHAIN"):
|
||||
with self.subTest(name=name):
|
||||
result = self.f.run("nightly-verify.sh", "--input", self.f.input, "--expect", "unsigned",
|
||||
**{**{key: None for key in SECRETS}, name: "generated"})
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertFalse(self.f.ran.exists())
|
||||
self.assertEqual(self.f.calls(), [])
|
||||
|
||||
|
||||
class Build(unittest.TestCase):
|
||||
def test_compilation_refuses_signing_material_before_building(self):
|
||||
f = Fixture(self)
|
||||
for name in ("APPLE_CERTIFICATE", "APPLE_PASSWORD", "MACOS_SIGN_IDENTITY", "WINDOWS_CERTIFICATE", "AZURE_CLIENT_SECRET", "LINUX_SIGNING_KEY"):
|
||||
with self.subTest(name=name):
|
||||
result = f.run("nightly.sh", "--arch", "aarch64", **{**{key: None for key in SECRETS}, name: "generated"},
|
||||
WORDCRAFT_BUILD_CHANNEL="nightly-v1", WORDCRAFT_VERSION=VERSION)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn(name, result.stdout)
|
||||
self.assertNotIn("cargo", [call[0] for call in f.calls()])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Executable
+238
@@ -0,0 +1,238 @@
|
||||
#!/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 = {
|
||||
"wordcraft",
|
||||
"wordcraft-bin",
|
||||
"wordcraft-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 / "wordcraft").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("wordcraft").read(), (self.stage / "wordcraft").read_bytes())
|
||||
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 ["wordcraft-cli", "portable.txt", "wordcraft.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 / "wordcraft-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 / "wordcraft-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()
|
||||
@@ -0,0 +1,142 @@
|
||||
#!/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
|
||||
# wordcraft is the launcher and wordcraft-bin the GUI it starts (nightly.sh).
|
||||
if name not in {"wordcraft", "wordcraft-bin", "wordcraft-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 = {
|
||||
"wordcraft",
|
||||
"wordcraft-bin",
|
||||
"wordcraft-nightly.png",
|
||||
"README.md",
|
||||
"LICENSE-MIT",
|
||||
"LICENSE-APACHE",
|
||||
"NOTICE",
|
||||
"ATTRIBUTION.md",
|
||||
}
|
||||
if not required.issubset({item.name for item in entries}):
|
||||
raise ValueError("required GUI/icon/notices missing")
|
||||
return entries
|
||||
|
||||
|
||||
def member_info(stage_root, name, incoming):
|
||||
"""Header for one stage file, built from the file this run opened rather than from the archive.
|
||||
|
||||
Members are flat names that resolve directly inside the stage they came from.
|
||||
"""
|
||||
if os.path.isabs(name) or os.path.basename(name) != name or name in ("", ".", ".."):
|
||||
raise ValueError(f"nightly member name must be a flat file name: {name}")
|
||||
destination = os.path.realpath(os.path.join(stage_root, name))
|
||||
if not destination.startswith(stage_root + os.sep) or os.path.dirname(destination) != stage_root:
|
||||
raise ValueError(f"nightly member resolves outside its stage: {name}")
|
||||
status = os.fstat(incoming.fileno())
|
||||
if not stat.S_ISREG(status.st_mode):
|
||||
raise ValueError(f"nightly member must be a regular file: {name}")
|
||||
# The same fields TarFile.gettarinfo records for a regular file.
|
||||
# The header keeps the validated stage name, not the resolved one: a stage symlink must
|
||||
# never rename a member or leave a required name out of the archive.
|
||||
info = tarfile.TarInfo(name)
|
||||
info.type = tarfile.REGTYPE
|
||||
info.mode = stat.S_IMODE(status.st_mode)
|
||||
info.uid, info.gid = status.st_uid, status.st_gid
|
||||
info.size = status.st_size
|
||||
info.mtime = status.st_mtime
|
||||
try:
|
||||
info.uname = pwd.getpwuid(status.st_uid).pw_name
|
||||
except KeyError:
|
||||
pass
|
||||
try:
|
||||
info.gname = grp.getgrgid(status.st_gid).gr_name
|
||||
except KeyError:
|
||||
pass
|
||||
return info
|
||||
|
||||
|
||||
def verify_headers(root, output):
|
||||
# Bounded ordinary headers, not a transparent PAX/GNU-normalizing reader.
|
||||
total = 0
|
||||
count = 0
|
||||
with root.reader(output, MAX_TOTAL_BYTES) as incoming, gzip.GzipFile(fileobj=incoming) as stream:
|
||||
while True:
|
||||
header = stream.read(512)
|
||||
if header == b"\0" * 512:
|
||||
break
|
||||
if len(header) != 512 or header[156:157] not in {b"0", b"\0"}:
|
||||
raise ValueError("non-ordinary TAR record was emitted")
|
||||
size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8)
|
||||
count += 1
|
||||
total += size
|
||||
if count > MAX_MEMBERS or size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES:
|
||||
raise ValueError("archive exceeds its bounded member budget")
|
||||
remaining = ((size + 511) // 512) * 512
|
||||
while remaining:
|
||||
chunk = stream.read(min(remaining, 1024 * 1024))
|
||||
if not chunk:
|
||||
raise ValueError("truncated TAR member")
|
||||
remaining -= len(chunk)
|
||||
|
||||
|
||||
def linux_archive(stage, output):
|
||||
with OwnedBuildRoot() as root:
|
||||
entries = checked_entries(root, stage)
|
||||
stage_root = os.path.realpath(os.path.join(root.directory, stage))
|
||||
total = 0
|
||||
with root.create(output) as outgoing:
|
||||
with tarfile.open(fileobj=outgoing, mode="w:gz", format=tarfile.USTAR_FORMAT) as archive:
|
||||
for entry in entries:
|
||||
with root.reader(entry, MAX_MEMBER_BYTES) as incoming:
|
||||
info = member_info(stage_root, entry.name, incoming)
|
||||
total += info.size
|
||||
if info.size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES:
|
||||
raise ValueError("nightly stage grew beyond its read bound")
|
||||
archive.addfile(info, incoming)
|
||||
outgoing.flush()
|
||||
os.fsync(outgoing.fileno())
|
||||
verify_headers(root, output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 4 or sys.argv[1] != "linux":
|
||||
raise SystemExit("usage: nightly-archive.py linux STAGE OUTPUT (from owned private build cwd)")
|
||||
linux_archive(pathlib.Path(sys.argv[2]), pathlib.Path(sys.argv[3]))
|
||||
@@ -0,0 +1,97 @@
|
||||
# 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
|
||||
[[ "${WORDCRAFT_BUILD_CHANNEL:-}" == nightly-v1 ]] || nightly_die 'WORDCRAFT_BUILD_CHANNEL must be nightly-v1'
|
||||
[[ "${WORDCRAFT_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'
|
||||
[[ "${WORDCRAFT_BUILD_SHA:-}" =~ ^[0-9a-f]{40}$ ]] || nightly_die 'an exact source commit is required'
|
||||
[[ "${WORDCRAFT_VERSION##*.g}" == "${WORDCRAFT_BUILD_SHA:0:12}" ]] || nightly_die 'version/source commit mismatch'
|
||||
[[ "${WORDCRAFT_BUILD_DATE:-}" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || nightly_die 'the original run-created UTC date is required'
|
||||
date_digits="${WORDCRAFT_VERSION#*-nightly.}"
|
||||
date_digits="${date_digits%%.*}"
|
||||
[[ "${WORDCRAFT_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)" == "$WORDCRAFT_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).
|
||||
# The channel and the exact feed version are passed explicitly: apps/wordcraft/build.rs reads
|
||||
# WORDCRAFT_BUILD_CHANNEL and WORDCRAFT_VERSION (not the older WORDCRAFT_OVERRIDE_VERSION), and
|
||||
# the built binary answers `--version` with `build_flavor::version`, i.e. "WordCraft <version>
|
||||
# (nightly-v1)". A stable compile here would print the Cargo version and fail the check below.
|
||||
nightly_compile_gui() {
|
||||
# The guard sits here as well as in the entrypoints: no caller may compile with signing material.
|
||||
nightly_refuse_signing_env
|
||||
(cd "$ROOT" && WORDCRAFT_BUILD_CHANNEL=nightly-v1 WORDCRAFT_VERSION="$VERSION" \
|
||||
cargo build --release --locked -p wordcraft --target "$NIGHTLY_RUST_TARGET")
|
||||
NIGHTLY_GUI="$CARGO_TARGET_DIR/$NIGHTLY_RUST_TARGET/release/wordcraft"
|
||||
[[ -f "$NIGHTLY_GUI" && ! -L "$NIGHTLY_GUI" ]] || nightly_die 'the owned GUI build did not produce a regular executable'
|
||||
[[ "$(git -C "$ROOT" rev-parse HEAD)" == "$WORDCRAFT_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'
|
||||
[[ "$actual" == "WordCraft $VERSION (nightly-v1)" ]] || nightly_die 'the built version/flavor is not the prepared identity'
|
||||
[[ "$(git -C "$ROOT" rev-parse HEAD)" == "$WORDCRAFT_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"
|
||||
}
|
||||
Executable
+78
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The committed Nightly icons are exactly what the committed derivation produces."""
|
||||
import hashlib
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import json
|
||||
import struct
|
||||
import unittest
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
ROOT = HERE.parent
|
||||
ICONS = ROOT / "assets" / "app-icon"
|
||||
SPEC = importlib.util.spec_from_file_location("word_nightly_icons", HERE / "nightly-icons.py")
|
||||
ICON_POLICY = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(ICON_POLICY)
|
||||
|
||||
|
||||
class NightlyIcons(unittest.TestCase):
|
||||
def test_committed_outputs_are_what_the_derivation_produces(self):
|
||||
outputs = ICON_POLICY.derive()
|
||||
self.assertEqual(set(outputs), {
|
||||
"wordcraft-nightly.png", "wordcraft-nightly.ico",
|
||||
"wordcraft-nightly-1024.png", "wordcraft-nightly.icns",
|
||||
})
|
||||
for name, content in outputs.items():
|
||||
self.assertEqual(hashlib.sha256((ICONS / name).read_bytes()).hexdigest(),
|
||||
hashlib.sha256(content).hexdigest(), f"{name} is stale: run packaging/nightly-icons.py")
|
||||
|
||||
def test_provenance_records_the_same_hashes_and_the_committed_generator(self):
|
||||
provenance = json.loads((ICONS / "nightly-provenance.json").read_text())
|
||||
for relative, digest in provenance["outputs"].items():
|
||||
path = ROOT / relative
|
||||
self.assertTrue(path.is_file(), relative)
|
||||
self.assertEqual(hashlib.sha256(path.read_bytes()).hexdigest(), digest, relative)
|
||||
for row in provenance["inputs"]:
|
||||
self.assertEqual(hashlib.sha256((ROOT / row["path"]).read_bytes()).hexdigest(), row["sha256"], row["path"])
|
||||
generator = ROOT / provenance["method"]["generator"]
|
||||
self.assertEqual(hashlib.sha256(generator.read_bytes()).hexdigest(), provenance["method"]["generator_sha256"])
|
||||
self.assertNotEqual(provenance["method"]["nightly_background"], provenance["method"]["original_palette"]["background"],
|
||||
"the Nightly field must differ from the app blue")
|
||||
|
||||
def test_the_containers_hold_the_frames_the_platforms_expect(self):
|
||||
ico = (ICONS / "wordcraft-nightly.ico").read_bytes()
|
||||
count = struct.unpack_from("<H", ico, 4)[0]
|
||||
sizes = []
|
||||
for index in range(count):
|
||||
width, height, _, _, _, bpp, size, offset = struct.unpack_from("<BBBBHHII", ico, 6 + 16 * index)
|
||||
self.assertEqual(width, height)
|
||||
self.assertEqual(bpp, 32)
|
||||
self.assertEqual(ico[offset:offset + 8], b"\x89PNG\r\n\x1a\n")
|
||||
sizes.append(width or 256)
|
||||
self.assertEqual(sorted(sizes), list(ICON_POLICY.ICO_FRAMES))
|
||||
|
||||
icns = (ICONS / "wordcraft-nightly.icns").read_bytes()
|
||||
self.assertEqual(icns[:4], b"icns")
|
||||
self.assertEqual(struct.unpack_from(">I", icns, 4)[0], len(icns))
|
||||
slots, offset = [], 8
|
||||
while offset < len(icns):
|
||||
kind, length = struct.unpack_from(">4sI", icns, offset)
|
||||
self.assertEqual(icns[offset + 8:offset + 16], b"\x89PNG\r\n\x1a\n", kind)
|
||||
slots.append(kind.decode("ascii"))
|
||||
offset += length
|
||||
expected = list(ICON_POLICY.ICNS_FROM_MASTER.values()) + list(ICON_POLICY.ICNS_EXISTING)
|
||||
self.assertEqual(len(expected), len(set(expected)), "each macOS slot is written once")
|
||||
self.assertEqual(sorted(slots), sorted(expected))
|
||||
self.assertEqual(offset, len(icns))
|
||||
|
||||
def test_a_frame_is_never_upscaled_from_the_committed_master(self):
|
||||
master = ICON_POLICY.read_png((ICONS / "wordcraft-macos-512.png").read_bytes())
|
||||
for size in ICON_POLICY.ICNS_FROM_MASTER:
|
||||
self.assertLessEqual(size, master[0])
|
||||
for slot, size in ICON_POLICY.ICNS_EXISTING.items():
|
||||
width, height, _ = ICON_POLICY.read_png(ICON_POLICY.read_icns((ICONS / "wordcraft.icns").read_bytes())[slot])
|
||||
self.assertEqual((width, height), (size, size), f"the {slot} frame must already be {size} px")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Executable
+306
@@ -0,0 +1,306 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Derive the WordCraft Nightly icon set from the committed stable renders.
|
||||
|
||||
The stable artwork is untouched: only the background contribution changes from the app's blue
|
||||
to the deeper Nightly background. Every pixel is decomposed in the stable drawing's three-colour
|
||||
palette (ink, paper, background) and rebuilt with the Nightly background, so the foreground lines,
|
||||
the paper, the alpha and the macOS padding stay exactly as they were drawn. There is no letter,
|
||||
crescent or other badge; the app and the Launcher name the channel in text.
|
||||
|
||||
Sources (all committed, all rendered from assets/app-icon/wordcraft.svg):
|
||||
* assets/app-icon/wordcraft.ico nine full-bleed frames, 16-256 px
|
||||
* assets/app-icon/wordcraft.icns padded macOS frames, 32-1024 px
|
||||
* assets/app-icon/hicolor/256x256/...png the 256 px full-bleed frame
|
||||
* assets/app-icon/wordcraft-macos-512.png the padded macOS master
|
||||
|
||||
Outputs:
|
||||
* assets/app-icon/wordcraft-nightly.png full-bleed 256 px (Windows/Linux tar)
|
||||
* assets/app-icon/wordcraft-nightly.ico nine full-bleed frames, 16-256 px
|
||||
* assets/app-icon/wordcraft-nightly-1024.png padded macOS 1024 px master
|
||||
* assets/app-icon/wordcraft-nightly.icns eleven padded macOS frames, 16-1024 px
|
||||
|
||||
Usage: python3 packaging/nightly-icons.py [--check]
|
||||
`--check` re-derives into memory and compares the committed outputs' SHA-256 instead of writing.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import struct
|
||||
import sys
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ICONS = ROOT / "assets" / "app-icon"
|
||||
|
||||
# The stable drawing's three colours (assets/app-icon/README.md) and the Nightly background.
|
||||
INK = (0x0B, 0x0B, 0x0C)
|
||||
PAPER = (0xEF, 0xE9, 0xDC)
|
||||
BACKGROUND = (0x3B, 0x5B, 0xDB)
|
||||
NIGHTLY_BACKGROUND = (0x23, 0x2C, 0x67)
|
||||
|
||||
ICO_FRAMES = (16, 20, 24, 32, 40, 48, 64, 128, 256)
|
||||
# Padded macOS slots by pixel size: PNG slots the committed icns already holds, and the three
|
||||
# small ones derived from the padded 512 px master.
|
||||
ICNS_FROM_MASTER = {16: "icp4", 32: "icp5", 64: "icp6"}
|
||||
# The padded frames the committed icns already holds, by slot and pixel size (16@2x, 32@2x, ...).
|
||||
ICNS_EXISTING = {"ic11": 32, "ic12": 64, "ic07": 128, "ic08": 256, "ic13": 256, "ic09": 512, "ic14": 512, "ic10": 1024}
|
||||
|
||||
|
||||
def read_png(data: bytes):
|
||||
"""Decode an 8-bit RGB/RGBA, non-interlaced PNG into (width, height, RGBA bytes)."""
|
||||
if data[:8] != b"\x89PNG\r\n\x1a\n":
|
||||
raise ValueError("not a PNG")
|
||||
offset, header, compressed = 8, None, bytearray()
|
||||
while offset < len(data):
|
||||
length, kind = struct.unpack_from(">I4s", data, offset)
|
||||
body = data[offset + 8:offset + 8 + length]
|
||||
if kind == b"IHDR":
|
||||
header = struct.unpack(">IIBBBBB", body)
|
||||
elif kind == b"IDAT":
|
||||
compressed += body
|
||||
elif kind == b"IEND":
|
||||
break
|
||||
offset += 12 + length
|
||||
width, height, depth, colour, _, _, interlace = header
|
||||
if depth != 8 or colour not in (2, 6) or interlace != 0:
|
||||
raise ValueError("expected an 8-bit non-interlaced RGB/RGBA PNG")
|
||||
channels = 3 if colour == 2 else 4
|
||||
stride = width * channels
|
||||
raw = zlib.decompress(bytes(compressed))
|
||||
if len(raw) != height * (stride + 1):
|
||||
raise ValueError("unexpected PNG payload length")
|
||||
pixels = bytearray(width * height * 4)
|
||||
previous = bytearray(stride)
|
||||
for y in range(height):
|
||||
start = y * (stride + 1)
|
||||
filter_kind = raw[start]
|
||||
line = bytearray(raw[start + 1:start + 1 + stride])
|
||||
if filter_kind == 1:
|
||||
for i in range(channels, stride):
|
||||
line[i] = (line[i] + line[i - channels]) & 0xFF
|
||||
elif filter_kind == 2:
|
||||
for i in range(stride):
|
||||
line[i] = (line[i] + previous[i]) & 0xFF
|
||||
elif filter_kind == 3:
|
||||
for i in range(stride):
|
||||
left = line[i - channels] if i >= channels else 0
|
||||
line[i] = (line[i] + ((left + previous[i]) >> 1)) & 0xFF
|
||||
elif filter_kind == 4:
|
||||
for i in range(stride):
|
||||
a = line[i - channels] if i >= channels else 0
|
||||
b = previous[i]
|
||||
c = previous[i - channels] if i >= channels else 0
|
||||
p = a + b - c
|
||||
pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
|
||||
line[i] = (line[i] + (a if pa <= pb and pa <= pc else b if pb <= pc else c)) & 0xFF
|
||||
elif filter_kind != 0:
|
||||
raise ValueError("unknown PNG filter")
|
||||
previous = line
|
||||
out = y * width * 4
|
||||
if channels == 4:
|
||||
pixels[out:out + width * 4] = line
|
||||
else:
|
||||
for x in range(width):
|
||||
pixels[out + x * 4:out + x * 4 + 3] = line[x * 3:x * 3 + 3]
|
||||
pixels[out + x * 4 + 3] = 255
|
||||
return width, height, pixels
|
||||
|
||||
|
||||
def write_png(width: int, height: int, pixels: bytearray) -> bytes:
|
||||
stride = width * 4
|
||||
raw = bytearray()
|
||||
for y in range(height):
|
||||
raw.append(0)
|
||||
raw += pixels[y * stride:(y + 1) * stride]
|
||||
|
||||
def chunk(kind: bytes, body: bytes) -> bytes:
|
||||
return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body) & 0xFFFFFFFF)
|
||||
|
||||
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0))
|
||||
+ chunk(b"IDAT", zlib.compress(bytes(raw), 9)) + chunk(b"IEND", b""))
|
||||
|
||||
|
||||
def _inverse(matrix):
|
||||
(a, b, c), (d, e, f), (g, h, i) = matrix
|
||||
determinant = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g)
|
||||
if abs(determinant) < 1e-9:
|
||||
raise ValueError("the palette's colours are not independent")
|
||||
return (
|
||||
((e * i - f * h) / determinant, (c * h - b * i) / determinant, (b * f - c * e) / determinant),
|
||||
((f * g - d * i) / determinant, (a * i - c * g) / determinant, (c * d - a * f) / determinant),
|
||||
((d * h - e * g) / determinant, (b * g - a * h) / determinant, (a * e - b * d) / determinant),
|
||||
)
|
||||
|
||||
|
||||
def _weights():
|
||||
"""Each palette colour as a weight (ink, paper, background) per channel."""
|
||||
matrix = ((INK[0], PAPER[0], BACKGROUND[0]), (INK[1], PAPER[1], BACKGROUND[1]), (INK[2], PAPER[2], BACKGROUND[2]))
|
||||
return _inverse(matrix)
|
||||
|
||||
|
||||
def recolour(pixels: bytearray) -> bytearray:
|
||||
"""Rebuild every pixel with the Nightly background, keeping its ink and paper weights."""
|
||||
inverse = _weights()
|
||||
out = bytearray(len(pixels))
|
||||
for i in range(0, len(pixels), 4):
|
||||
alpha = pixels[i + 3]
|
||||
if alpha == 0:
|
||||
continue
|
||||
red, green, blue = pixels[i], pixels[i + 1], pixels[i + 2]
|
||||
# The three palette weights that reproduce this colour exactly.
|
||||
w_ink = inverse[0][0] * red + inverse[0][1] * green + inverse[0][2] * blue
|
||||
w_paper = inverse[1][0] * red + inverse[1][1] * green + inverse[1][2] * blue
|
||||
w_background = inverse[2][0] * red + inverse[2][1] * green + inverse[2][2] * blue
|
||||
# A pixel between two edges can fall outside the triangle: clamp and renormalise, so the
|
||||
# result is still a mixture of the three colours and never a new tint.
|
||||
weights = [max(0.0, w_ink), max(0.0, w_paper), max(0.0, w_background)]
|
||||
total = sum(weights)
|
||||
if total <= 0:
|
||||
out[i:i + 4] = bytes((*NIGHTLY_BACKGROUND, alpha))
|
||||
continue
|
||||
weights = [w / total for w in weights]
|
||||
mixed = [weights[0] * INK[j] + weights[1] * PAPER[j] + weights[2] * NIGHTLY_BACKGROUND[j] for j in range(3)]
|
||||
out[i:i + 3] = bytes(min(255, max(0, round(v))) for v in mixed)
|
||||
out[i + 3] = alpha
|
||||
return out
|
||||
|
||||
|
||||
def downsample(width: int, height: int, pixels: bytearray, size: int) -> bytearray:
|
||||
"""Box-filter `pixels` to `size` x `size`: only used to shrink the padded master, never to grow a frame."""
|
||||
if size > width or size > height:
|
||||
raise ValueError("a frame is never upscaled")
|
||||
factor = width // size
|
||||
if factor * size != width or height != width:
|
||||
raise ValueError("the master must divide evenly into each slot")
|
||||
out = bytearray(size * size * 4)
|
||||
area = factor * factor
|
||||
for y in range(size):
|
||||
for x in range(size):
|
||||
total = [0, 0, 0, 0]
|
||||
for dy in range(factor):
|
||||
row = ((y * factor + dy) * width + x * factor) * 4
|
||||
for dx in range(factor):
|
||||
at = row + dx * 4
|
||||
total[0] += pixels[at]
|
||||
total[1] += pixels[at + 1]
|
||||
total[2] += pixels[at + 2]
|
||||
total[3] += pixels[at + 3]
|
||||
at = (y * size + x) * 4
|
||||
alpha = total[3]
|
||||
if alpha == 0:
|
||||
continue
|
||||
out[at] = round(total[0] / area)
|
||||
out[at + 1] = round(total[1] / area)
|
||||
out[at + 2] = round(total[2] / area)
|
||||
out[at + 3] = round(alpha / area)
|
||||
return out
|
||||
|
||||
|
||||
def read_ico(data: bytes):
|
||||
"""Every PNG frame of an .ico as {size: png bytes}."""
|
||||
if data[:4] != b"\x00\x00\x01\x00":
|
||||
raise ValueError("not an .ico")
|
||||
count = struct.unpack_from("<H", data, 4)[0]
|
||||
frames = {}
|
||||
for index in range(count):
|
||||
width, height, _, _, _, _, size, offset = struct.unpack_from("<BBBBHHII", data, 6 + 16 * index)
|
||||
body = data[offset:offset + size]
|
||||
if body[:8] != b"\x89PNG\r\n\x1a\n":
|
||||
raise ValueError("only PNG-compressed .ico frames are expected")
|
||||
size_px = width or 256
|
||||
if height and height != width:
|
||||
raise ValueError("square .ico frames are expected")
|
||||
frames[size_px or 256] = body
|
||||
return frames
|
||||
|
||||
|
||||
def write_ico(frames) -> bytes:
|
||||
header = struct.pack("<HHH", 0, 1, len(frames))
|
||||
entries, bodies, offset = bytearray(), bytearray(), 6 + 16 * len(frames)
|
||||
for size in sorted(frames):
|
||||
body = frames[size]
|
||||
width = 0 if size >= 256 else size
|
||||
entries += struct.pack("<BBBBHHII", width, width, 0, 0, 1, 32, len(body), offset)
|
||||
bodies += body
|
||||
offset += len(body)
|
||||
return header + bytes(entries) + bytes(bodies)
|
||||
|
||||
|
||||
def read_icns(data: bytes):
|
||||
"""The PNG slots of an .icns as {four-letter type: png bytes}, in file order."""
|
||||
if data[:4] != b"icns":
|
||||
raise ValueError("not an .icns")
|
||||
offset, slots = 8, {}
|
||||
while offset < len(data):
|
||||
kind, length = struct.unpack_from(">4sI", data, offset)
|
||||
body = data[offset + 8:offset + length]
|
||||
if body[:8] == b"\x89PNG\r\n\x1a\n":
|
||||
slots[kind.decode("ascii")] = body
|
||||
offset += length
|
||||
return slots
|
||||
|
||||
|
||||
def write_icns(slots) -> bytes:
|
||||
order = ["icp4", "icp5", "icp6", "ic07", "ic08", "ic09", "ic10", "ic11", "ic12", "ic13", "ic14"]
|
||||
body = bytearray()
|
||||
for kind in order:
|
||||
payload = slots[kind]
|
||||
body += kind.encode("ascii") + struct.pack(">I", len(payload) + 8) + payload
|
||||
return b"icns" + struct.pack(">I", len(body) + 8) + bytes(body)
|
||||
|
||||
|
||||
def derive():
|
||||
"""Build every Nightly artifact in memory: {relative path: bytes}."""
|
||||
outputs = {}
|
||||
ico = read_ico((ICONS / "wordcraft.ico").read_bytes())
|
||||
nightly_frames = {}
|
||||
for size in ICO_FRAMES:
|
||||
width, height, pixels = read_png(ico[size])
|
||||
if width != size:
|
||||
raise ValueError(f"the {size} px .ico frame is {width} px")
|
||||
nightly_frames[size] = write_png(width, height, recolour(pixels))
|
||||
outputs["wordcraft-nightly.ico"] = write_ico(nightly_frames)
|
||||
|
||||
two_fifty_six = read_png((ICONS / "hicolor/256x256/apps/ai.storyteller.wordcraft.png").read_bytes())
|
||||
outputs["wordcraft-nightly.png"] = write_png(two_fifty_six[0], two_fifty_six[1], recolour(two_fifty_six[2]))
|
||||
|
||||
master = read_png((ICONS / "wordcraft-macos-512.png").read_bytes())
|
||||
recoloured_master = recolour(master[2])
|
||||
existing = read_icns((ICONS / "wordcraft.icns").read_bytes())
|
||||
slots = {}
|
||||
for size, kind in ICNS_FROM_MASTER.items():
|
||||
slots[kind] = write_png(size, size, downsample(master[0], master[1], recoloured_master, size))
|
||||
for kind, size in ICNS_EXISTING.items():
|
||||
width, height, pixels = read_png(existing[kind])
|
||||
if width != size or height != size:
|
||||
raise ValueError(f"the {kind} slot is {width}x{height}, not {size}x{size}")
|
||||
slots[kind] = write_png(width, height, recolour(pixels))
|
||||
if size == 1024:
|
||||
outputs["wordcraft-nightly-1024.png"] = slots[kind]
|
||||
outputs["wordcraft-nightly.icns"] = write_icns(slots)
|
||||
return outputs
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--check", action="store_true", help="compare the committed outputs instead of writing")
|
||||
args = parser.parse_args()
|
||||
outputs = derive()
|
||||
failed = False
|
||||
for name, content in sorted(outputs.items()):
|
||||
path = ICONS / name
|
||||
digest = hashlib.sha256(content).hexdigest()
|
||||
if args.check:
|
||||
current = hashlib.sha256(path.read_bytes()).hexdigest() if path.exists() else "missing"
|
||||
status = "ok" if current == digest else "differs"
|
||||
failed |= current != digest
|
||||
print(f"{status:8} {name} {digest}")
|
||||
else:
|
||||
path.write_bytes(content)
|
||||
print(f"wrote {name} {digest} ({len(content)} bytes)")
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+413
@@ -0,0 +1,413 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Local regression checks for WordCraft's supervised manual nightly workflows and v3 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"
|
||||
|
||||
|
||||
def assert_nightly_serialization(source):
|
||||
"""Fail closed unless this app's plain root concurrency block retains its contract.
|
||||
|
||||
This is a deliberately narrow source guard, not a general YAML parser; actionlint
|
||||
still checks all other syntax. Expressions, aliases and alternate block shapes
|
||||
refuse rather than delegating queue-value validation to the old linter.
|
||||
"""
|
||||
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": "wordcraft-nightly-release", "cancel-in-progress": "false"}:
|
||||
raise ValueError("nightly serialization must use its stable group and no cancellation")
|
||||
|
||||
|
||||
def literal_off(condition):
|
||||
expression = " ".join(condition.split())
|
||||
if expression.startswith("${{") and expression.endswith("}}"):
|
||||
expression = expression[3:-2].strip()
|
||||
if expression == "false":
|
||||
return True
|
||||
if not expression.startswith("false && "):
|
||||
return False
|
||||
# A top-level OR could override the leading false; parentheses must balance.
|
||||
expression = re.sub(r"'(?:''|[^'])*'", "''", expression)
|
||||
depth = 0
|
||||
for token in re.findall(r"\(|\)|\|\|", expression):
|
||||
if token == "(":
|
||||
depth += 1
|
||||
elif token == ")":
|
||||
depth -= 1
|
||||
if depth < 0:
|
||||
return False
|
||||
elif depth == 0:
|
||||
return False
|
||||
return depth == 0
|
||||
|
||||
|
||||
def job_conditions(jobs):
|
||||
"""Each job-level `if:` as (block indicator or None, the whole expression YAML would read).
|
||||
|
||||
A narrow source reader, not a YAML parser: every following line indented deeper than the
|
||||
job keys continues the value, for block scalars and plain multi-line scalars alike, so a
|
||||
continuation line can never hide from the guard checks.
|
||||
"""
|
||||
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
|
||||
|
||||
|
||||
NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64")
|
||||
# Each platform's one trust field in policy v3, and the public stable identity it must name.
|
||||
NIGHTLY_TRUST = {
|
||||
"windows-x86_64": ("publisher_subject",
|
||||
"CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"),
|
||||
"linux-x86_64": ("fingerprint", "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"),
|
||||
"macos-aarch64": ("apple_team_id", "DJ6XS33FX8"),
|
||||
}
|
||||
|
||||
# Mirrors the storytold release-managers team (id 19837241) minus echelon-robot.
|
||||
# Update by PR, in the caller and the policy, when the team changes.
|
||||
RELEASE_MANAGERS = ["bflatastic", "dylanmtaylor", "echelon", "FredApps", "skylartaylor"]
|
||||
|
||||
|
||||
def producer_platforms(source):
|
||||
"""Read the one producer job's literal platform list; a narrow source guard, not YAML.
|
||||
|
||||
One producer run builds every listed platform for one all-or-nothing release, so the
|
||||
list must be a compact JSON list of distinct known platforms that keeps Windows.
|
||||
"""
|
||||
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_dormancy_guard_rejects_activation_and_top_level_or(self):
|
||||
for condition in ("true", "vars.ENABLE_NIGHTLY", "false || true", "false && true || true",
|
||||
"false && (true || true", "false && true) || true"):
|
||||
with self.subTest(condition=condition):
|
||||
self.assertFalse(literal_off(condition))
|
||||
self.assertTrue(literal_off("${{ false }}"))
|
||||
self.assertTrue(literal_off("false && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')"))
|
||||
|
||||
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: true"),
|
||||
("cancel-in-progress: false", "cancel-in-progress: ${{ github.event_name == 'push' }}"),
|
||||
("cancel-in-progress: false\n", ""),
|
||||
("group: wordcraft-nightly-release", "group: ${{ github.run_id }}"),
|
||||
("group: wordcraft-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 (all three platforms)."""
|
||||
|
||||
def setUp(self):
|
||||
self.policy = json.loads(INSTALLED_POLICY.read_text())
|
||||
|
||||
def test_each_platform_row_names_its_fixed_artifact_kind_and_stable_identity(self):
|
||||
self.assertEqual(set(self.policy["platforms"]), set(NIGHTLY_TRUST))
|
||||
for platform, (field, value) in NIGHTLY_TRUST.items():
|
||||
row = self.policy["platforms"][platform]
|
||||
with self.subTest(platform=platform):
|
||||
self.assertEqual(row["unsigned_artifact_name"], f"nightly-unsigned-{platform}",
|
||||
"the artifact kind is fixed by platform, never a caller pattern")
|
||||
self.assertEqual(row["trust"], {field: value}, "trust must be stable's public identity")
|
||||
|
||||
def test_trust_values_have_the_shapes_the_shared_signer_accepts(self):
|
||||
rows = self.policy["platforms"]
|
||||
self.assertRegex(rows["macos-aarch64"]["trust"]["apple_team_id"], r"^[A-Z0-9]{10}$")
|
||||
self.assertRegex(rows["linux-x86_64"]["trust"]["fingerprint"], r"^[0-9A-F]{40}$")
|
||||
subject = rows["windows-x86_64"]["trust"]["publisher_subject"]
|
||||
self.assertTrue(0 < len(subject) <= 1024 and not set(subject) & {"\r", "\n", "\0"})
|
||||
|
||||
def test_both_callers_use_one_shared_pin_in_uses_and_tooling_revision(self):
|
||||
pins = set()
|
||||
for name, callee in (("nightly.yml", "nightly-unsigned.yml"), ("nightly-sign.yml", "nightly-release.yml")):
|
||||
source = (ROOT / ".github/workflows" / name).read_text()
|
||||
uses = re.findall(r"(?m)^ uses: storytold/craft-common-actions/\.github/workflows/"
|
||||
+ re.escape(callee) + r"@(\S+)$", source)
|
||||
tooling = re.findall(r"(?m)^ tooling-revision: (\S+)$", source)
|
||||
with self.subTest(workflow=name):
|
||||
self.assertEqual(len(uses), 1)
|
||||
self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match")
|
||||
pins.update(uses)
|
||||
self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit")
|
||||
self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder")
|
||||
|
||||
|
||||
class NightlyEnabledCallers(unittest.TestCase):
|
||||
"""Producer and signer run only in their exact context, for the reviewed manual actor."""
|
||||
|
||||
GUARDS = {
|
||||
"nightly.yml": "github.repository == 'storytold/wordcraft' && github.ref == 'refs/heads/main' && "
|
||||
"github.ref_type == 'branch' && (github.event_name == 'schedule' || "
|
||||
"github.event_name == 'workflow_dispatch')",
|
||||
"nightly-sign.yml": "github.repository == 'storytold/wordcraft' && github.event_name == 'workflow_dispatch' && "
|
||||
"github.ref == 'refs/heads/release' && github.ref_type == 'branch'",
|
||||
}
|
||||
|
||||
def test_enabled_jobs_keep_exact_context_guards(self):
|
||||
for name, expected in self.GUARDS.items():
|
||||
jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1]
|
||||
guards = job_conditions(jobs)
|
||||
with self.subTest(workflow=name):
|
||||
self.assertEqual(len(guards), 1)
|
||||
indicator, expression = guards[0]
|
||||
self.assertEqual(indicator, ">-")
|
||||
self.assertEqual(" ".join(expression.split()), expected, "guards may only change with review")
|
||||
|
||||
def test_manual_actors_are_the_release_managers_in_caller_and_policy(self):
|
||||
source = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
policy = json.loads(INSTALLED_POLICY.read_text())
|
||||
self.assertEqual(reviewed_manual_actors(source, policy), RELEASE_MANAGERS)
|
||||
self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule")
|
||||
|
||||
def test_an_actor_outside_the_release_managers_is_refused(self):
|
||||
source = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
policy = json.loads(INSTALLED_POLICY.read_text())
|
||||
caller = json.dumps(RELEASE_MANAGERS, separators=(",", ":"))
|
||||
widened = sorted(RELEASE_MANAGERS + ["echelon-robot"], key=str.lower)
|
||||
for change in ("caller", "policy", "both", "order", "case"):
|
||||
mutated_source, mutated_policy = source, copy.deepcopy(policy)
|
||||
if change in ("caller", "both"):
|
||||
mutated_source = source.replace(caller, json.dumps(widened, separators=(",", ":")))
|
||||
if change in ("policy", "both"):
|
||||
mutated_policy["manual_actors"] = widened
|
||||
if change == "order":
|
||||
mutated_policy["manual_actors"] = list(reversed(RELEASE_MANAGERS))
|
||||
if change == "case":
|
||||
mutated_policy["manual_actors"] = [login.lower() for login in RELEASE_MANAGERS]
|
||||
with self.subTest(change=change), self.assertRaises(ValueError):
|
||||
reviewed_manual_actors(mutated_source, mutated_policy)
|
||||
|
||||
|
||||
class NightlyInstalledPolicy(unittest.TestCase):
|
||||
"""The installed v3 policy matches the callers, the repository and its documented sources."""
|
||||
|
||||
EXPECTED_KEYS = {
|
||||
"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",
|
||||
}
|
||||
|
||||
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):
|
||||
self.assertEqual(set(self.policy), self.EXPECTED_KEYS)
|
||||
self.assertEqual(self.policy["schema"], "craft-nightly-release-policy/v3")
|
||||
self.assertEqual(self.policy["repository"], "storytold/wordcraft")
|
||||
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, then a positive int.
|
||||
producer_id = self.policy["producer_workflow_id"]
|
||||
if producer_id is not None:
|
||||
self.assertIs(type(producer_id), int)
|
||||
self.assertGreater(producer_id, 0)
|
||||
self.assertNotEqual(producer_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), "one release carries Windows, Linux and macOS")
|
||||
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/wordcraft", "main"))
|
||||
self.assertTrue(isinstance(candidate["epoch"], str) and 0 < len(candidate["epoch"]) <= 128)
|
||||
rows = candidate["required_workflows"]
|
||||
self.assertTrue(rows)
|
||||
for row in rows:
|
||||
with self.subTest(workflow=row["workflow_path"]):
|
||||
self.assertEqual(set(row), {"workflow_id", "workflow_path", "jobs"})
|
||||
self.assertIs(type(row["workflow_id"]), int)
|
||||
self.assertNotEqual(row["workflow_path"], self.policy["producer_workflow_path"])
|
||||
source = (ROOT / row["workflow_path"]).read_text()
|
||||
push = re.search(r"(?m)^ push:\n((?: .*\n)+)", source)
|
||||
self.assertIsNotNone(push, "a required workflow must run on main pushes")
|
||||
self.assertIn(" branches: [main]\n", push[1])
|
||||
self.assertNotRegex(push[1], r"paths", "a path filter would leave candidates without a run")
|
||||
names = [job["name"] for job in row["jobs"]]
|
||||
self.assertEqual(len(names), len(set(names)))
|
||||
for job in row["jobs"]:
|
||||
self.assertEqual(set(job), {"name", "app_id", "applicability"})
|
||||
self.assertEqual((job["app_id"], job["applicability"]), (15368, "required"))
|
||||
|
||||
def test_sonar_identity_and_reviewed_scope(self):
|
||||
sonar = self.policy["candidate_policy"]["sonar"]
|
||||
properties = dict(line.split("=", 1) for line in (ROOT / "sonar-project.properties").read_text().splitlines()
|
||||
if line and not line.startswith("#"))
|
||||
self.assertEqual(sonar["organization"], properties["sonar.organization"])
|
||||
self.assertEqual(sonar["project"], properties["sonar.projectKey"])
|
||||
self.assertEqual((sonar["app_id"], sonar["check_name"]), (12526, "SonarCloud Code Analysis"))
|
||||
self.assertEqual(sonar["details_url"], "https://sonarcloud.io/dashboard?id=" + sonar["project"] + "&branch=main")
|
||||
accepted = {"bugs": "BUG", "vulnerabilities": "VULNERABILITY", "code_smells": "CODE_SMELL",
|
||||
"security_rating": "VULNERABILITY", "new_security_rating": "VULNERABILITY"}
|
||||
self.assertEqual({accepted[c["metric"]] for c in sonar["accepted_conditions"]}, set(sonar["issue_types"]))
|
||||
metrics = [c["metric"] for c in sonar["accepted_conditions"] + sonar["required_conditions"]]
|
||||
self.assertEqual(len(metrics), len(set(metrics)))
|
||||
keys = [item["key"] for item in sonar["debt"]]
|
||||
self.assertEqual(len(keys), len(set(keys)))
|
||||
for item in sonar["debt"]:
|
||||
with self.subTest(issue=item["key"]):
|
||||
self.assertEqual(set(item), {"key", "rule", "component", "type", "severity", "hash"})
|
||||
self.assertTrue(item["component"].startswith(sonar["project"] + ":"))
|
||||
self.assertIn(item["type"], sonar["issue_types"])
|
||||
self.assertRegex(item["hash"], r"^[0-9a-f]{32}$")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
Executable
+26
@@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the existing synthetic packaging suites together; no app build or signing."""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
|
||||
def main() -> int:
|
||||
here = Path(__file__).resolve().parent
|
||||
suite = unittest.TestSuite()
|
||||
for name, relative in (
|
||||
("word_icons_suite", "nightly-icons-tests.py"),
|
||||
("word_archive_suite", "nightly-archive-tests.py"),
|
||||
("word_plist_suite", "macos/nightly_plist_tests.py"),
|
||||
("word_release_dispatch_suite", "nightly-release-tests.py"),
|
||||
("word_mac_sign_suite", "macos/nightly_sign_tests.py"),
|
||||
):
|
||||
spec = importlib.util.spec_from_file_location(name, here / relative)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(module))
|
||||
return 0 if unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful() else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -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)
|
||||
@@ -0,0 +1,30 @@
|
||||
# Windows packaging
|
||||
|
||||
See [installation policy checks](INSTALLATION.md) for the installer scope and path gates.
|
||||
|
||||
## Nightly build and signing boundary
|
||||
|
||||
`package.ps1 -Arch x64 -Nightly -BuildOnly` is for the secret-free compilation job.
|
||||
It refuses signing credential variables and builds the GUI only, without CLI,
|
||||
portable marker, installer or associations. Its `*-nightly.unsigned.zip` is an
|
||||
internal intermediate, not the final feed artifact. There is no unsigned
|
||||
publication switch.
|
||||
|
||||
The separate trusted producer signing job safely unpacks that new intermediate,
|
||||
checks its exact identity/inventory, then invokes the existing backend:
|
||||
|
||||
```powershell
|
||||
pwsh packaging/windows/sign.ps1 -Required -CheckOnly
|
||||
pwsh packaging/windows/sign.ps1 -Required -Files <stage>/wordcraft.exe
|
||||
```
|
||||
|
||||
Missing or partial configuration fails. `-Required` verifies Authenticode and
|
||||
a signer certificate after the existing signtool verification. Stable local
|
||||
packaging keeps its existing optional-signing policy. The producer independently
|
||||
verifies the final signature, PE identity and inventory before archiving under
|
||||
the normal feed filename, and refuses to overwrite prepared outputs. It never
|
||||
executes the payload in the signing step. Real keys belong only to that step,
|
||||
not compilation. These interfaces do not configure or grant access to keys.
|
||||
|
||||
The signing-policy fixtures use generated dummy values and a mocked compiler
|
||||
boundary; they do not prove real certificate signing or release readiness.
|
||||
@@ -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 'wordcraft-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 'wordcraft.exe') 'nightly must not ship the unqualified CLI'
|
||||
Assert ($spec.AppId -eq 'ai.storyteller.wordcraft.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 'WordCraft Nightly' 'WordCraft 0.23.1-nightly.20261120.17.1.gabcdef012345 (nightly-v1)' '0.23.1-nightly.20261120.17.1.gabcdef012345'
|
||||
foreach ($pair in @(@('WordCraft', 'WordCraft 0.23.1 (nightly-v1)'), @('WordCraft Nightly', 'WordCraft 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/wordcraft/src/main.rs')
|
||||
)
|
||||
foreach ($case in $cases) {
|
||||
$refused = $false
|
||||
try { Assert-NightlySource $case[1] $case[2] $case[3] $case[4] $case[5] } catch { $refused = $true }
|
||||
Assert $refused "source identity accepted: $($case[0])"
|
||||
}
|
||||
Write-Output 'nightly packaging spec, target/version refusal, source identity and flavor-binding tests passed'
|
||||
|
||||
# Exercise the SAME production notice copier with the real repository layout, then inspect a ZIP.
|
||||
if (-not $FixtureRoot -or -not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'supply an owned absolute -FixtureRoot for the notices/ZIP regression' }
|
||||
$testRoot = Join-Path $FixtureRoot ("nightly-notices-" + [Guid]::NewGuid().ToString('N'))
|
||||
try {
|
||||
$repo = Join-Path $testRoot 'app'
|
||||
$fontRepo = Join-Path $testRoot 'craft-fonts'
|
||||
$family = Join-Path $fontRepo 'fonts\ExampleFamily'
|
||||
$stage = Join-Path $testRoot 'stage'
|
||||
New-Item -ItemType Directory -Force -Path $repo, $family, $stage | Out-Null
|
||||
$rootNames = @('README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md')
|
||||
foreach ($name in $rootNames) { Set-Content -LiteralPath (Join-Path $repo $name) -Value "root-notice-$name" }
|
||||
Set-Content -LiteralPath (Join-Path $family 'OFL.txt') -Value 'font-notice-example'
|
||||
Copy-NightlyNotices $repo $fontRepo $stage
|
||||
foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) {
|
||||
Assert (Test-Path -LiteralPath (Join-Path $stage $name)) "missing staged notice $name"
|
||||
}
|
||||
$zip = Join-Path $testRoot 'notices.zip'
|
||||
Compress-Archive -Path (Join-Path $stage '*') -DestinationPath $zip
|
||||
$archive = [IO.Compression.ZipFile]::OpenRead($zip)
|
||||
try {
|
||||
$names = @($archive.Entries | ForEach-Object { $_.FullName })
|
||||
foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { Assert ($name -in $names) "missing archived notice $name" }
|
||||
foreach ($forbidden in @('portable.txt', 'wordcraft-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'
|
||||
@@ -0,0 +1,90 @@
|
||||
param(
|
||||
[Parameter(Mandatory=$true)][string] $FixtureRoot,
|
||||
[string] $PackagingRoot = $PSScriptRoot,
|
||||
[switch] $PhaseGuardOnly
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
. (Join-Path $PackagingRoot 'nightly.ps1') -FunctionsOnly
|
||||
$sign = Join-Path $PackagingRoot 'sign.ps1'
|
||||
$names = @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_TENANT_ID','AZURE_CLIENT_ID','AZURE_CLIENT_SECRET','AZURE_SIGNING_ENDPOINT','AZURE_SIGNING_ACCOUNT','AZURE_CERT_PROFILE')
|
||||
function Clear-SigningFixtures { foreach ($name in $names) { [Environment]::SetEnvironmentVariable($name, $null) } }
|
||||
function Assert-Policy([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } }
|
||||
function Invoke-Refusal([scriptblock] $Operation, [string] $Message) {
|
||||
$errorText = ''
|
||||
try { & $Operation | Out-Null } catch { $errorText = $_.Exception.Message }
|
||||
Assert-Policy ($errorText.Contains($Message)) "expected refusal: $Message; got: $errorText"
|
||||
}
|
||||
function global:cargo { $global:SigningFixtureCargoCalls++; throw 'FIXTURE_COMPILER_BOUNDARY' }
|
||||
function global:Invoke-WebRequest { throw 'fixture must not perform signing downloads' }
|
||||
$global:SigningFixtureCargoCalls = 0
|
||||
if (-not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'use an owned absolute FixtureRoot' }
|
||||
$root = Join-Path $FixtureRoot ('signing-policy-' + [Guid]::NewGuid().ToString('N'))
|
||||
New-Item -ItemType Directory -Path $root | Out-Null
|
||||
# The fixture mocks Cargo, but nightly.ps1 checks the same source identity a packaging run does:
|
||||
# the version names this checkout's commit and the run's UTC date, and the tree is clean. Deriving
|
||||
# them here keeps the fixture reaching the mocked compiler instead of failing in source validation.
|
||||
$sha = "$(git -C $PSScriptRoot rev-parse HEAD)".Trim()
|
||||
$runDate = (Get-Date).ToUniversalTime().ToString('yyyyMMdd')
|
||||
$version = "0.23.1-nightly.$runDate.12345.1.g$($sha.Substring(0, 12))"
|
||||
$env:WORDCRAFT_VERSION = $version
|
||||
$env:WORDCRAFT_BUILD_SHA = $sha
|
||||
$env:WORDCRAFT_BUILD_DATE = "$($runDate.Substring(0, 4))-$($runDate.Substring(4, 2))-$($runDate.Substring(6, 2))"
|
||||
function Invoke-Build([switch] $BuildOnly) {
|
||||
$arguments = @{Arch='x64';Version=$version;Target='x86_64-pc-windows-msvc';TargetDir=$root;Dist=(Join-Path $root 'dist')}
|
||||
if ($BuildOnly) { $arguments.BuildOnly = $true }
|
||||
& (Join-Path $PackagingRoot 'nightly.ps1') @arguments
|
||||
}
|
||||
try {
|
||||
Clear-SigningFixtures
|
||||
Invoke-Refusal { Invoke-Build } 'requires -BuildOnly'
|
||||
Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'default mode invoked Cargo'
|
||||
Write-Output 'PASS: explicit-build-phase-required'
|
||||
if ($PhaseGuardOnly) { return }
|
||||
|
||||
foreach ($name in @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_CLIENT_SECRET')) {
|
||||
Clear-SigningFixtures
|
||||
[Environment]::SetEnvironmentVariable($name, 'generated-fixture-not-a-secret')
|
||||
Invoke-Refusal { Invoke-Build -BuildOnly } 'Compilation must not receive signing credentials'
|
||||
Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'key-bearing compilation reached Cargo'
|
||||
}
|
||||
Write-Output 'PASS: credentials-rejected-before-compilation'
|
||||
|
||||
Clear-SigningFixtures
|
||||
Invoke-Refusal { Invoke-Build -BuildOnly } 'FIXTURE_COMPILER_BOUNDARY'
|
||||
Assert-Policy ($global:SigningFixtureCargoCalls -eq 1) 'clean compilation did not reach the mocked compiler boundary'
|
||||
Assert-Policy (-not (Test-Path (Join-Path $root 'dist'))) 'mocked compilation produced an artifact'
|
||||
Write-Output 'PASS: secret-free-build-reaches-only-mocked-boundary'
|
||||
|
||||
Clear-SigningFixtures
|
||||
Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required'
|
||||
$env:AZURE_CLIENT_SECRET = 'generated-partial-fixture'
|
||||
Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required'
|
||||
Write-Output 'PASS: required-signer-refuses-missing-and-partial-configuration'
|
||||
|
||||
Clear-SigningFixtures
|
||||
$env:WINDOWS_CERTIFICATE = 'generated-presence-fixture-not-a-certificate'
|
||||
& $sign -Required -CheckOnly
|
||||
Clear-SigningFixtures
|
||||
foreach ($name in $names | Where-Object { $_.StartsWith('AZURE_') }) { [Environment]::SetEnvironmentVariable($name, 'generated-presence-fixture') }
|
||||
& $sign -Required -CheckOnly
|
||||
Clear-SigningFixtures
|
||||
Write-Output 'PASS: supported-configuration-presence-without-signing'
|
||||
|
||||
# Load the policy function without signing. These objects are not crypto evidence.
|
||||
. $sign -CheckOnly
|
||||
foreach ($value in @($null, [pscustomobject]@{Status='NotSigned';SignerCertificate='fixture'}, [pscustomobject]@{Status='HashMismatch';SignerCertificate='fixture'}, [pscustomobject]@{Status='Valid';SignerCertificate=$null})) {
|
||||
Invoke-Refusal { Assert-AuthenticodeSignature $value } 'valid Authenticode signature'
|
||||
}
|
||||
Assert-AuthenticodeSignature ([pscustomobject]@{Status='Valid';SignerCertificate='generated-public-certificate-placeholder'})
|
||||
Write-Output 'PASS: required-signature-policy-rejects-invalid-or-missing-signer'
|
||||
|
||||
$file = Join-Path $root 'owned-sentinel.exe'
|
||||
[IO.File]::WriteAllText($file, 'generated sentinel, not a real executable')
|
||||
$before = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash
|
||||
& $sign -Files $file
|
||||
Assert-Policy ((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash -ceq $before) 'optional stable policy changed unsigned bytes'
|
||||
Write-Output 'PASS: stable-optional-policy-preserves-owned-bytes'
|
||||
} finally {
|
||||
Clear-SigningFixtures
|
||||
Remove-Item -LiteralPath $root -Recurse -Force
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<# 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 = "wordcraft-$Version-windows-x86_64-nightly.zip"
|
||||
UnsignedArchive = "wordcraft-$Version-windows-x86_64-nightly.unsigned.zip"
|
||||
Executables = @('wordcraft.exe')
|
||||
Channel = 'nightly-v1'
|
||||
AppId = 'ai.storyteller.wordcraft.nightly-v1'
|
||||
}
|
||||
}
|
||||
|
||||
# The same source identity the Linux helper enforces (nightly-common.sh): the version names the
|
||||
# commit being built, the date is the original run's, and the tree is clean.
|
||||
function Assert-NightlySource([string] $Version, [string] $Sha, [string] $BuildDate, [string] $Head, [string] $Status) {
|
||||
if ($Sha -cnotmatch '^[0-9a-f]{40}\z') { throw 'an exact source commit is required (WORDCRAFT_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 (WORDCRAFT_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 'WordCraft Nightly' -or $VersionOutput -cne "WordCraft $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:WORDCRAFT_VERSION -or $Version -cne $env:WORDCRAFT_VERSION) { throw 'nightly-v1 requires explicit WORDCRAFT_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:WORDCRAFT_BUILD_SHA $env:WORDCRAFT_BUILD_DATE $Source.Head $Source.Status
|
||||
$oldChannel = $env:WORDCRAFT_BUILD_CHANNEL
|
||||
try {
|
||||
$env:WORDCRAFT_BUILD_CHANNEL = 'nightly-v1'
|
||||
$env:WORDCRAFT_REQUIRE_WINRES = '1'
|
||||
$env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS = '-C target-feature=+crt-static'
|
||||
cargo build --release --locked -p wordcraft --target $Target
|
||||
if ($LASTEXITCODE -ne 0) { throw "nightly cargo build failed: $LASTEXITCODE" }
|
||||
} finally {
|
||||
$env:WORDCRAFT_BUILD_CHANNEL = $oldChannel
|
||||
}
|
||||
$Source = Get-NightlySourceState $Root
|
||||
try { Assert-NightlySource $Version $env:WORDCRAFT_BUILD_SHA $env:WORDCRAFT_BUILD_DATE $Source.Head $Source.Status }
|
||||
catch { throw "source changed during the build: $_" }
|
||||
$Exe = Join-Path $TargetDir "$Target\release\wordcraft.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 'WordCraft 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 'wordcraft.exe')
|
||||
# Signing happens only in the separate trusted step, using sign.ps1 -Required.
|
||||
# The intermediate's filename cannot satisfy the feed-ready archive contract.
|
||||
Copy-NightlyNotices $Root $env:CRAFT_FONTS_DIR $Stage
|
||||
if ((Get-ChildItem -LiteralPath $Stage -Filter '*.exe').Count -ne 1 -or (Test-Path (Join-Path $Stage 'portable.txt'))) {
|
||||
throw 'nightly stage contains an unexpected executable or portable fallback marker'
|
||||
}
|
||||
New-Item -ItemType Directory -Force -Path $Dist | Out-Null
|
||||
$Zip = Join-Path $Dist $Spec.UnsignedArchive
|
||||
if (Test-Path -LiteralPath $Zip) { throw 'Nightly output already exists; refusing to replace prepared artifact bytes' }
|
||||
Compress-Archive -Path (Join-Path $Stage '*') -DestinationPath $Zip
|
||||
$Archive = [System.IO.Compression.ZipFile]::OpenRead($Zip)
|
||||
try {
|
||||
$Names = @($Archive.Entries | ForEach-Object { $_.FullName })
|
||||
if ('wordcraft.exe' -notin $Names -or 'wordcraft-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)"
|
||||
@@ -26,9 +26,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) {
|
||||
@@ -55,12 +58,22 @@ $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:WORDCRAFT_BUILD_SHA) { $env:WORDCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) }
|
||||
if (-not $env:WORDCRAFT_BUILD_DATE) { $env:WORDCRAFT_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:WORDCRAFT_BUILD_SHA) { $env:WORDCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) }
|
||||
if (-not $env:WORDCRAFT_BUILD_DATE) { $env:WORDCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') }
|
||||
}
|
||||
|
||||
Write-Output "WordCraft $Version for Windows $Arch ($Target)"
|
||||
|
||||
if ($Nightly) {
|
||||
& (Join-Path $PSScriptRoot 'nightly.ps1') -Arch $Arch -Version $Version -Target $Target -TargetDir $TargetDir -Dist $Dist -SkipBuild:$SkipBuild -BuildOnly:$BuildOnly
|
||||
return
|
||||
}
|
||||
|
||||
if (-not $SkipBuild) {
|
||||
$env:WORDCRAFT_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'
|
||||
@@ -88,6 +101,9 @@ foreach ($check in @(@('wordcraft.exe', 2), @('wordcraft-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 'wordcraft.exe')).VersionInfo.ProductName -eq 'WordCraft 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
|
||||
|
||||
@@ -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/wordcraft.exe dist/Wordcraft.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,29 @@ 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) {
|
||||
# Compilation must never receive key material: the Nightly compiler calls this first.
|
||||
if ($Required -or $CheckOnly -or $Files) { throw '-CheckBuildEnvironment is separate from signing' }
|
||||
$names = @('WINDOWS_CERTIFICATE', 'WINDOWS_CERTIFICATE_PASSWORD') + $azureVars
|
||||
if ($names | Where-Object { [Environment]::GetEnvironmentVariable($_) }) {
|
||||
throw 'Compilation must not receive signing credentials; use a separate trusted signing step'
|
||||
}
|
||||
return
|
||||
}
|
||||
$haveCert = [bool]$env:WINDOWS_CERTIFICATE
|
||||
$haveAzure = -not ($azureVars | Where-Object { -not [Environment]::GetEnvironmentVariable($_) })
|
||||
|
||||
if ($Required -and -not $haveCert -and -not $haveAzure) {
|
||||
throw 'Nightly signing is required: configure WINDOWS_CERTIFICATE or the complete existing Azure signing configuration'
|
||||
}
|
||||
if ($CheckOnly) {
|
||||
if ($Files) { throw '-CheckOnly does not sign files' }
|
||||
return
|
||||
}
|
||||
if (-not $Files) { throw 'At least one file is required for signing' }
|
||||
$Files = $Files | ForEach-Object { (Resolve-Path $_).Path }
|
||||
|
||||
if (-not $haveCert -and -not $haveAzure) {
|
||||
Write-Warn "Windows signing secrets not set (WINDOWS_CERTIFICATE or AZURE_*): leaving unsigned: $($Files -join ', ')"
|
||||
exit 0
|
||||
@@ -96,6 +125,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
|
||||
|
||||
@@ -1,9 +1,24 @@
|
||||
sonar.projectKey=storytold_wordcraft
|
||||
sonar.organization=storytold
|
||||
|
||||
# Setting test roots disables the CLI default; keep all production sources analyzed.
|
||||
sonar.sources=.
|
||||
# These exact fixture runners are tests, not production code. Do not exclude helpers.
|
||||
sonar.tests=packaging
|
||||
sonar.test.inclusions=packaging/nightly-tests.py,packaging/nightly-icons-tests.py,packaging/nightly-archive-tests.py,packaging/macos/nightly_plist_tests.py,packaging/macos/nightly_sign_tests.py,packaging/windows/nightly-package-tests.ps1,packaging/windows/nightly-signing-tests.ps1,packaging/nightly-release-tests.py
|
||||
sonar.python.coverage.reportPaths=python-coverage.xml
|
||||
|
||||
# S4790 (weak hash): SHA-1 is a start-key and "SHA1/1K" checksum algorithm that ODF package
|
||||
# encryption (ODF 1.3 Part 2 §4.16) names, and older office suites wrote it. It is needed to open
|
||||
# those files, not chosen for new security: WordCraft writes a SHA-256 start key and checksum.
|
||||
sonar.issue.ignore.multicriteria=odt_sha1
|
||||
sonar.issue.ignore.multicriteria.odt_sha1.ruleKey=rust:S4790
|
||||
sonar.issue.ignore.multicriteria.odt_sha1.resourceKey=crates/formats/src/odt/crypt.rs
|
||||
|
||||
# Packaging scripts and their standalone unittest suites are not measured by Rust llvm-cov.
|
||||
# `main.rs` in both binaries is the process entrypoint: the coverage job runs `cargo llvm-cov`'s
|
||||
# tests, never the GUI or the CLI's startup, so its lines can never be covered. Everything either
|
||||
# `main` decides lives in modules with unit tests (build_flavor, launch_profile, profile_root,
|
||||
# os_window, control-key). process_identity.rs is Windows-only (the taskbar AUMID) and cannot run
|
||||
# on the Linux runner either.
|
||||
sonar.coverage.exclusions=packaging/**,apps/wordcraft/src/main.rs,apps/wordcraft-cli/src/main.rs,apps/wordcraft/src/process_identity.rs
|
||||
|
||||
Reference in New Issue
Block a user