mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-28 00:59:29 +01:00
packaging(linux): support co-installable nightly packages (#801)
Linux nightly packaging by @dylanmtaylor, with the per-app Nightly flavor commits stacked on his branch. Co-authored-by: Dylan M. Taylor <dylan@dylanmtaylor.com>
This commit is contained in:
1 parent
2a4ad138d9
commit
56efb48efb
72 files changed
+5488
-80
No files matched your search
@@ -13,6 +13,9 @@ set -u
|
||||
|
||||
APPDIR="$(dirname "$(readlink -f "$0")")"
|
||||
DESK_ID=ai.storyteller.texturecraft
|
||||
# package.sh rewrites this line for a Nightly AppImage, which starts the app with the Launcher's
|
||||
# private profile exactly as the deb, rpm, Arch, Flatpak and tarball launchers do.
|
||||
CHANNEL=stable
|
||||
|
||||
integrate() {
|
||||
case "${TEXTURECRAFT_NO_DESKTOP_INTEGRATION:-}" in
|
||||
@@ -69,4 +72,14 @@ integrate() {
|
||||
}
|
||||
|
||||
integrate
|
||||
|
||||
# The Launcher's own protocol, and a bare version query, pass through untouched: the first already
|
||||
# names its profile, and the second must answer without one.
|
||||
case "${1-}" in
|
||||
--launch-profile | --profile-root | --version | -V) exec "$APPDIR/usr/bin/texturecraft" "$@" ;;
|
||||
esac
|
||||
if [ "$CHANNEL" = nightly-v1 ]; then
|
||||
exec "$APPDIR/usr/bin/texturecraft" --launch-profile nightly-v1 \
|
||||
--profile-root "${XDG_DATA_HOME:-${HOME:-}/.local/share}/TextureCraft-Nightly" -- "$@"
|
||||
fi
|
||||
exec "$APPDIR/usr/bin/texturecraft" "$@"
|
||||
@@ -8,7 +8,7 @@ TryExec=texturecraft
|
||||
Icon=ai.storyteller.texturecraft
|
||||
Terminal=false
|
||||
StartupNotify=true
|
||||
StartupWMClass=texturecraft
|
||||
StartupWMClass=ai.storyteller.texturecraft
|
||||
Categories=Graphics;3DGraphics;
|
||||
Keywords=texture;paint;pbr;material;3d;mesh;bake;gltf;fbx;usd;
|
||||
MimeType=application/x-texturecraft;model/gltf-binary;model/gltf+json;model/x-fbx;model/vnd.collada+xml;model/x-usd;model/vnd.usda;model/vnd.usdz+zip;model/x-alembic;model/obj;model/x-ply;model/stl;
|
||||
@@ -95,4 +95,22 @@ out="$(APPIMAGE="$odd" "$APPDIR/AppRun" x)" || fail "launch with an odd path exi
|
||||
[[ "$out" = "stub: x" ]] || fail "odd path: $out"
|
||||
[[ ! -e "$XDG_DATA_HOME" ]] || fail "integrated an AppImage path that needs escaping"
|
||||
|
||||
# 10. A Nightly AppImage (package.sh rewrites the channel line) starts the app with the Launcher's
|
||||
# private profile; a version query still passes through untouched.
|
||||
NIGHTLY_APPDIR="$TMP/Nightly.AppDir"
|
||||
mkdir -p "$NIGHTLY_APPDIR/usr/bin"
|
||||
install -Dm755 "$HERE/AppRun" "$NIGHTLY_APPDIR/AppRun"
|
||||
cat >"$NIGHTLY_APPDIR/usr/bin/texturecraft" <<'RECORDER'
|
||||
#!/bin/sh
|
||||
printf '<%s>\n' "$@"
|
||||
RECORDER
|
||||
chmod +x "$NIGHTLY_APPDIR/usr/bin/texturecraft"
|
||||
sed -i 's|^CHANNEL=stable$|CHANNEL=nightly-v1|' "$NIGHTLY_APPDIR/AppRun"
|
||||
grep -qx 'CHANNEL=nightly-v1' "$NIGHTLY_APPDIR/AppRun" || fail "Nightly AppRun was not switched"
|
||||
out="$(env -u APPIMAGE XDG_DATA_HOME="$TMP/nightly-data" "$NIGHTLY_APPDIR/AppRun" a.glb)" || fail "Nightly AppRun exited non-zero"
|
||||
expected="$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$TMP/nightly-data/TextureCraft-Nightly" -- a.glb)"
|
||||
[[ "$out" = "$expected" ]] || fail "Nightly AppRun did not use the Launcher profile: $out"
|
||||
out="$(env -u APPIMAGE "$NIGHTLY_APPDIR/AppRun" --version)" || fail "Nightly version query exited non-zero"
|
||||
[[ "$out" = "<--version>" ]] || fail "Nightly AppRun rewrote a version query: $out"
|
||||
|
||||
echo "AppRun desktop integration ok"
|
||||
@@ -9,14 +9,20 @@
|
||||
# is built for the host architecture (x86_64 or aarch64), which must match the tarball's.
|
||||
# Needs flatpak, flatpak-builder and the SVG pixbuf loader (librsvg2-common) for the host's
|
||||
# `appstreamcli compose`; the freedesktop runtime and SDK named in the manifest are
|
||||
# installed per-user from Flathub. Unless --no-test, the bundle is then installed per-user and
|
||||
# `texturecraft-cli --version` is run inside the sandbox as a smoke test.
|
||||
# installed per-user from Flathub. Unless --no-test, the bundle is then installed per-user and the
|
||||
# app (`texturecraft --version`) is run inside the sandbox as a smoke test.
|
||||
# Manifest: packaging/linux/flatpak/ai.storyteller.TextureCraft.bundle.yml.
|
||||
set -euo pipefail
|
||||
# shellcheck source=../env.sh
|
||||
. "$(dirname "${BASH_SOURCE[0]}")/../env.sh"
|
||||
HERE="$ROOT/packaging/linux"
|
||||
APP_ID=ai.storyteller.texturecraft
|
||||
FLATPAK_ID="$APP_ID"
|
||||
# The remote indexes both app IDs on the stable ref branch; IDs isolate installations.
|
||||
FLATPAK_BRANCH=stable
|
||||
if [[ "${TEXTURECRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then
|
||||
FLATPAK_ID="$APP_ID.nightly"
|
||||
fi
|
||||
FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo
|
||||
# The OCI repository serves only the latest stable release, so a prerelease bundle gets no update
|
||||
# source: Flatpak would otherwise replace it with that older stable build.
|
||||
@@ -56,38 +62,98 @@ rm -rf "$WORK"
|
||||
mkdir -p "$WORK/stage"
|
||||
tar -xzf "$TARBALL" -C "$WORK/stage" --strip-components=1
|
||||
[[ -x "$WORK/stage/bin/texturecraft" ]] || { echo "error: $TARBALL has no bin/texturecraft" >&2; exit 1; }
|
||||
cp "$HERE/flatpak/ai.storyteller.TextureCraft.bundle.yml" "$WORK/$APP_ID.yml"
|
||||
if [[ "$FLATPAK_ID" != "$APP_ID" ]]; then
|
||||
# A Nightly tarball from package.sh already separates the launcher from the GUI; an older one
|
||||
# does not. Either way this bundle installs its own wrapper and the GUI in /app/libexec.
|
||||
if [[ -e "$WORK/stage/bin/texturecraft-bin" ]]; then
|
||||
rm -f "$WORK/stage/bin/texturecraft"
|
||||
else
|
||||
mv "$WORK/stage/bin/texturecraft" "$WORK/stage/bin/texturecraft-bin"
|
||||
fi
|
||||
cat >"$WORK/stage/bin/texturecraft" <<'WRAPPER'
|
||||
#!/bin/sh
|
||||
# TextureCraft Nightly: the GUI runs with the Launcher's private profile. Inside the sandbox
|
||||
# $XDG_DATA_HOME is the app's own per-app folder, so the profile never meets stable's.
|
||||
set -eu
|
||||
bin=/app/libexec/texturecraft
|
||||
profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/TextureCraft-Nightly"
|
||||
# The Launcher's protocol, and a bare version query, pass through untouched.
|
||||
case "${1-}" in
|
||||
--launch-profile | --profile-root | --version | -V) exec "$bin" "$@" ;;
|
||||
esac
|
||||
exec "$bin" --launch-profile nightly-v1 --profile-root "$profile" -- "$@"
|
||||
WRAPPER
|
||||
chmod 755 "$WORK/stage/bin/texturecraft"
|
||||
sed -e "s|^Icon=$APP_ID$|Icon=$FLATPAK_ID|" \
|
||||
-e "s|^Name=TextureCraft$|Name=TextureCraft Nightly|" \
|
||||
-e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.texturecraft.nightly-v1|' \
|
||||
-e '/^MimeType=/d' \
|
||||
"$WORK/stage/share/applications/$APP_ID.desktop" >"$WORK/stage/share/applications/$FLATPAK_ID.desktop"
|
||||
rm -f "$WORK/stage/share/applications/$APP_ID.desktop"
|
||||
# The Nightly entry drops MimeType=, so the metainfo must not advertise the types either.
|
||||
sed -e "s|<id>$APP_ID</id>|<id>$FLATPAK_ID</id>|g" \
|
||||
-e "s|<name>TextureCraft</name>|<name>TextureCraft 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"
|
||||
rm -rf "$WORK/stage/share/mime"
|
||||
rm -rf "$WORK/stage/share/icons/hicolor"
|
||||
NIGHTLY_ICON="$ROOT/assets/app-icon/texturecraft-nightly.png"
|
||||
if [[ ! -f "$NIGHTLY_ICON" ]]; then
|
||||
NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
|
||||
fi
|
||||
install -Dm644 "$NIGHTLY_ICON" \
|
||||
"$WORK/stage/share/icons/hicolor/256x256/apps/$FLATPAK_ID.png"
|
||||
# Omit conflicting MIME registrations and disable host Flatpak updater talk-name until
|
||||
# craft_update supports the nightly FLATPAK_ID. A Nightly bundle is also GUI-only: its tarball has
|
||||
# no texturecraft-cli, and a CLI would read Stable's Documents/TextureCraft brushes.
|
||||
sed -e "s|ai\.storyteller\.texturecraft|$FLATPAK_ID|g" \
|
||||
-e '/share\/mime\/packages\//d' \
|
||||
-e '/^\( *\)# \.tcraft, plus mesh types/d' \
|
||||
-e '/bin\/texturecraft-cli/d' \
|
||||
-e '/--talk-name=org\.freedesktop\.Flatpak/d' \
|
||||
-e 's|- install -Dm755 bin/texturecraft /app/bin/texturecraft|- install -Dm755 bin/texturecraft-bin /app/libexec/texturecraft\n - install -Dm755 bin/texturecraft /app/bin/texturecraft|' \
|
||||
"$HERE/flatpak/ai.storyteller.TextureCraft.bundle.yml" >"$WORK/$FLATPAK_ID.yml"
|
||||
else
|
||||
cp "$HERE/flatpak/ai.storyteller.TextureCraft.bundle.yml" "$WORK/$FLATPAK_ID.yml"
|
||||
fi
|
||||
|
||||
flatpak remote-add --user --if-not-exists flathub "$FLATHUB"
|
||||
# --disable-rofiles-fuse: no FUSE in containers and CI runners.
|
||||
flatpak-builder --user --install-deps-from=flathub --disable-rofiles-fuse --force-clean \
|
||||
--default-branch=stable --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$APP_ID.yml"
|
||||
--default-branch="$FLATPAK_BRANCH" --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$FLATPAK_ID.yml"
|
||||
|
||||
OUT="$DIST/$BASENAME.flatpak"
|
||||
# A release build (the shared release workflow sets SIGNING_FPR, SIGNING_PUBKEY and GNUPGHOME)
|
||||
# signs the commit and embeds the public key, so Flatpak verifies the bundle when installing it.
|
||||
GPG_KEYS=()
|
||||
if [[ -n "${SIGNING_FPR:-}" ]]; then
|
||||
flatpak build-sign "$WORK/repo" "$APP_ID" stable --gpg-sign="$SIGNING_FPR" --gpg-homedir="${GNUPGHOME:?}"
|
||||
flatpak build-sign "$WORK/repo" "$FLATPAK_ID" "$FLATPAK_BRANCH" --gpg-sign="$SIGNING_FPR" --gpg-homedir="${GNUPGHOME:?}"
|
||||
GPG_KEYS=(--gpg-keys="${SIGNING_PUBKEY:?}")
|
||||
if [[ "${OCI_SIGNATURES_READY:-}" != 1 ]]; then OCI_REPO=""; fi
|
||||
fi
|
||||
# --runtime-repo lets `flatpak install` fetch the freedesktop runtime from Flathub if missing.
|
||||
# --repo-url makes the installed origin update from the ArtCraft OCI repository.
|
||||
flatpak build-bundle --runtime-repo="$FLATHUB" ${OCI_REPO:+--repo-url="$OCI_REPO"} "${GPG_KEYS[@]}" "$WORK/repo" "$OUT" "$APP_ID" stable
|
||||
flatpak build-bundle --runtime-repo="$FLATHUB" ${OCI_REPO:+--repo-url="$OCI_REPO"} "${GPG_KEYS[@]}" "$WORK/repo" "$OUT" "$FLATPAK_ID" "$FLATPAK_BRANCH"
|
||||
echo "wrote $OUT"
|
||||
if [[ "$OCI" = 1 ]]; then
|
||||
OUT_OCI="$DIST/$BASENAME-oci"
|
||||
rm -rf "$OUT_OCI"
|
||||
flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$APP_ID" stable
|
||||
flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$FLATPAK_ID" "$FLATPAK_BRANCH"
|
||||
echo "wrote OCI layout to $OUT_OCI"
|
||||
fi
|
||||
|
||||
if [[ "$TEST" = 1 ]]; then
|
||||
flatpak install --user -y --noninteractive --reinstall "$OUT"
|
||||
flatpak info --user "$APP_ID"
|
||||
flatpak run --command=texturecraft-cli "$APP_ID" --version
|
||||
flatpak run --command=sh "$APP_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/scalable/apps'
|
||||
flatpak info --user "$FLATPAK_ID"
|
||||
flatpak run --command=texturecraft "$FLATPAK_ID" --version
|
||||
if [[ "$FLATPAK_ID" == "$APP_ID" ]]; then
|
||||
flatpak run --command=sh "$FLATPAK_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/*/apps'
|
||||
else
|
||||
flatpak run --command=sh "$FLATPAK_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/icons/hicolor/*/apps && test ! -e /app/share/mime/packages'
|
||||
fi
|
||||
fi
|
||||
echo "==> done"
|
||||
ls -lh "$OUT"
|
||||
@@ -1,9 +1,12 @@
|
||||
# .deb and .rpm packages (nfpm: https://nfpm.goreleaser.com). Run by package.sh, which stages
|
||||
# the file tree, substitutes its path for ${STAGE} (nfpm doesn't expand env vars in `src`) and
|
||||
# exports VERSION and NFPM_ARCH.
|
||||
# exports VERSION, NFPM_ARCH, NFPM_NAME, NFPM_BIN and NFPM_CLI (the Nightly package renames the
|
||||
# first two and has no CLI, so package.sh removes the CLI entry for it). By hand, all five are
|
||||
# needed:
|
||||
#
|
||||
# nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/
|
||||
name: texturecraft
|
||||
# VERSION=1.2.3 NFPM_ARCH=amd64 NFPM_NAME=texturecraft NFPM_BIN=texturecraft \
|
||||
# NFPM_CLI=texturecraft-cli nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/
|
||||
name: ${NFPM_NAME}
|
||||
arch: ${NFPM_ARCH}
|
||||
platform: linux
|
||||
version: ${VERSION}
|
||||
@@ -66,12 +69,15 @@ overrides:
|
||||
- xdg-desktop-portal
|
||||
|
||||
contents:
|
||||
- src: ${STAGE}/usr/bin/texturecraft
|
||||
dst: /usr/bin/texturecraft
|
||||
- src: ${STAGE}/usr/bin/${NFPM_BIN}
|
||||
dst: /usr/bin/${NFPM_BIN}
|
||||
file_info: { mode: 0755 }
|
||||
- src: ${STAGE}/usr/bin/texturecraft-cli
|
||||
dst: /usr/bin/texturecraft-cli
|
||||
- src: ${STAGE}/usr/bin/${NFPM_CLI}
|
||||
dst: /usr/bin/${NFPM_CLI}
|
||||
file_info: { mode: 0755 }
|
||||
- src: ${STAGE}/usr/lib/
|
||||
dst: /usr/lib/
|
||||
type: tree
|
||||
- src: ${STAGE}/usr/share/
|
||||
dst: /usr/share/
|
||||
type: tree
|
||||
|
||||
Executable
+14
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
# The TextureCraft Nightly launcher for the Arch handoff (packaging/linux/nightly-arch-tar.sh):
|
||||
# the real GUI stays in .texturecraft-nightly/, and this starts it with the Launcher's private
|
||||
# profile, as every other Nightly package does.
|
||||
set -eu
|
||||
|
||||
bin="$(dirname "$0")/.texturecraft-nightly/texturecraft"
|
||||
profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/TextureCraft-Nightly"
|
||||
|
||||
# The Launcher's protocol, and a bare version query, pass through untouched.
|
||||
case "${1-}" in
|
||||
--launch-profile | --profile-root | --version | -V) exec "$bin" "$@" ;;
|
||||
esac
|
||||
exec "$bin" --launch-profile nightly-v1 --profile-root "$profile" -- "$@"
|
||||
Executable
+58
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env bash
|
||||
# Validate the staged Arch launcher without building or opening TextureCraft.
|
||||
set -euo pipefail
|
||||
|
||||
HERE="$(cd "$(dirname "$0")" && pwd)"
|
||||
work="$(mktemp -d)"
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
stage="$work/source"
|
||||
dst="$work/dist"
|
||||
base=texturecraft-0.0.1-nightly.1-linux-x86_64
|
||||
mkdir -p "$stage/bin" "$dst" "$work/extract"
|
||||
|
||||
# A local argv recorder stands in for the compiled binaries. It never opens a UI.
|
||||
cat >"$stage/bin/texturecraft" <<'RECORDER'
|
||||
#!/bin/sh
|
||||
printf '<%s>\n' "$@"
|
||||
RECORDER
|
||||
chmod 755 "$stage/bin/texturecraft"
|
||||
|
||||
bash "$HERE/nightly-arch-tar.sh" "$stage" "$work/stage" "$dst" "$base"
|
||||
tar -xzf "$dst/$base.tar.gz" -C "$work/extract"
|
||||
bin="$work/extract/$base/bin"
|
||||
# Simulate the existing Arch bin-tree copy and public launcher rename.
|
||||
mkdir -p "$work/installed"
|
||||
cp -R "$bin" "$work/installed/bin"
|
||||
bin="$work/installed/bin"
|
||||
mv "$bin/texturecraft" "$bin/texturecraft-nightly"
|
||||
|
||||
test ! -e "$stage/bin/.texturecraft-nightly"
|
||||
cmp "$stage/bin/texturecraft" "$bin/.texturecraft-nightly/texturecraft"
|
||||
# A Nightly package is GUI-only: the handoff must not carry a CLI that would use Stable's brushes.
|
||||
test ! -e "$bin/texturecraft-nightly-cli" || { echo "FAIL: the Arch handoff still ships a Nightly CLI" >&2; exit 1; }
|
||||
profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/TextureCraft-Nightly"
|
||||
# A launch adds the Launcher's literal selector/root pair and the file delimiter; a version query or
|
||||
# an already-formed protocol passes through untouched.
|
||||
expect_launch() {
|
||||
expected="$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$profile" -- "$@")"
|
||||
actual=$(PATH="$bin:$PATH" texturecraft-nightly "$@")
|
||||
[[ "$actual" == "$expected" ]] || {
|
||||
printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
expect_forwarded() {
|
||||
expected="$(printf '<%s>\n' "$@")"
|
||||
actual=$(PATH="$bin:$PATH" texturecraft-nightly "$@")
|
||||
[[ "$actual" == "$expected" ]] || {
|
||||
printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
expect_launch
|
||||
expect_launch 'mesh with spaces.glb' '--other-name.tcraft'
|
||||
expect_forwarded --version
|
||||
expect_forwarded -V
|
||||
expect_forwarded --launch-profile nightly-v1 --profile-root /launcher/profile --version
|
||||
|
||||
echo "PASS: Arch Nightly handoff preserves binary layout and passes the Launcher profile"
|
||||
Executable
+22
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env bash
|
||||
# Stage the TextureCraft Nightly-only handoff for the Arch packager.
|
||||
set -euo pipefail
|
||||
|
||||
here="$(cd "$(dirname "$0")" && pwd)"
|
||||
source_tree="$1"
|
||||
work="$2"
|
||||
destination="$3"
|
||||
basename="$4"
|
||||
stage="$work/$basename"
|
||||
|
||||
mkdir -p "$work"
|
||||
cp -R "$source_tree" "$stage"
|
||||
# The Nightly package is GUI-only: texturecraft-cli would read and rewrite Stable's
|
||||
# Documents/TextureCraft brushes, which a private profile cannot redirect.
|
||||
rm -f "$stage/bin/texturecraft-cli"
|
||||
mkdir "$stage/bin/.texturecraft-nightly"
|
||||
mv "$stage/bin/texturecraft" "$stage/bin/.texturecraft-nightly/texturecraft"
|
||||
cp "$here/nightly-arch-launch.sh" "$stage/bin/texturecraft"
|
||||
chmod 755 "$stage/bin/texturecraft"
|
||||
tar -C "$work" -czf "$destination/$basename.tar.gz" "$basename"
|
||||
echo "wrote $destination/$basename.tar.gz"
|
||||
Executable
+57
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env bash
|
||||
# The launcher inside the plain Nightly tarball (packaging/linux/nightly-launch.sh): a launch adds
|
||||
# the Launcher's private profile, a version query or an existing protocol passes through, and the
|
||||
# fence's shape holds (absolute root, no parent traversal, outside this copy).
|
||||
set -euo pipefail
|
||||
|
||||
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
work="$(mktemp -d)"
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
mkdir -p "$work/tree"
|
||||
|
||||
# An argv recorder stands in for the GUI. It never opens a window.
|
||||
cat >"$work/tree/texturecraft-bin" <<'RECORDER'
|
||||
#!/bin/sh
|
||||
printf '<%s>\n' "$@"
|
||||
RECORDER
|
||||
chmod 755 "$work/tree/texturecraft-bin"
|
||||
cp "$HERE/nightly-launch.sh" "$work/tree/texturecraft"
|
||||
|
||||
profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/TextureCraft-Nightly"
|
||||
# The profile must be something the app's fence accepts: absolute, no parent traversal, and not
|
||||
# inside the unpacked copy (the running install).
|
||||
case "$profile" in
|
||||
/*) ;;
|
||||
*) echo "FAIL: the launcher profile is not absolute: $profile" >&2; exit 1 ;;
|
||||
esac
|
||||
case "/$profile/" in
|
||||
*/../*) echo "FAIL: the launcher profile contains parent traversal" >&2; exit 1 ;;
|
||||
esac
|
||||
case "$profile/" in
|
||||
"$work/tree/"*) echo "FAIL: the launcher profile is inside the unpacked copy" >&2; exit 1 ;;
|
||||
esac
|
||||
|
||||
expect_launch() {
|
||||
expected="$(printf '<%s>\n' --launch-profile nightly-v1 --profile-root "$profile" -- "$@")"
|
||||
actual=$("$work/tree/texturecraft" "$@")
|
||||
[[ "$actual" == "$expected" ]] || {
|
||||
printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
expect_forwarded() {
|
||||
expected="$(printf '<%s>\n' "$@")"
|
||||
actual=$("$work/tree/texturecraft" "$@")
|
||||
[[ "$actual" == "$expected" ]] || {
|
||||
printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
expect_launch
|
||||
expect_launch 'model with spaces.glb' '--other-name.tcraft'
|
||||
expect_forwarded --version
|
||||
expect_forwarded -V
|
||||
expect_forwarded --launch-profile nightly-v1 --profile-root /launcher/profile --version
|
||||
|
||||
echo "PASS: tarball Nightly launcher starts the GUI with the Launcher profile and forwards files"
|
||||
Executable
+21
@@ -0,0 +1,21 @@
|
||||
#!/bin/sh
|
||||
# The entry point inside the Nightly tarball (packaging/linux/nightly.sh installs it as
|
||||
# `texturecraft`, beside the GUI as `texturecraft-bin`).
|
||||
#
|
||||
# A Nightly build only starts with its private profile, and every package format passes the
|
||||
# Launcher's literal protocol: `--launch-profile nightly-v1 --profile-root <dir> -- <files>`. The
|
||||
# profile sits outside stable's folders (its own settings, ui.json, crash log, autosaves, smart
|
||||
# materials, layouts, templates and presets) and outside this unpacked copy, which the app's own
|
||||
# fence would refuse.
|
||||
set -eu
|
||||
|
||||
here="$(dirname "$(readlink -f "$0")")"
|
||||
bin="$here/texturecraft-bin"
|
||||
profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/TextureCraft-Nightly"
|
||||
|
||||
# The Launcher's protocol, and a bare version query, pass through untouched: the first already
|
||||
# names its profile, and the second must answer without one.
|
||||
case "${1-}" in
|
||||
--launch-profile | --profile-root | --version | -V) exec "$bin" "$@" ;;
|
||||
esac
|
||||
exec "$bin" --launch-profile nightly-v1 --profile-root "$profile" -- "$@"
|
||||
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/texturecraft-$VERSION-linux-x86_64-nightly.tar.gz"
|
||||
[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || nightly_die 'refusing to replace an existing nightly archive'
|
||||
nightly_build_gui
|
||||
STAGE="$NIGHTLY_WORK/stage"
|
||||
mkdir -p "$STAGE"
|
||||
# The launcher is the entry point (`texturecraft`); the GUI sits beside it and is started with the
|
||||
# Launcher's private profile, so an unpacked tarball never writes stable's folders. The flat layout
|
||||
# is what nightly-archive.py allows, and the launcher is a committed script so shellcheck covers
|
||||
# it like every other shell script.
|
||||
cp "$NIGHTLY_GUI" "$STAGE/texturecraft-bin"
|
||||
chmod 755 "$STAGE/texturecraft-bin"
|
||||
cp "$ROOT/packaging/linux/nightly-launch.sh" "$STAGE/texturecraft"
|
||||
chmod 755 "$STAGE/texturecraft"
|
||||
cp "$ROOT/assets/app-icon/texturecraft-nightly-1024.png" "$STAGE/texturecraft-nightly.png"
|
||||
nightly_copy_notices "$STAGE"
|
||||
# The private mktemp cwd is the helper authority root, not a CLI path parent.
|
||||
(cd "$NIGHTLY_WORK" && python3 "$ROOT/packaging/nightly-archive.py" linux stage archive.tar.gz)
|
||||
nightly_publish_archive "$NIGHTLY_WORK/archive.tar.gz" "$OUTPUT"
|
||||
+172
-12
@@ -7,7 +7,7 @@
|
||||
# $DIST/texturecraft-<version>-linux-<arch>.rpm Fedora, openSUSE, RHEL, ...
|
||||
# $DIST/texturecraft-<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.texturecraft
|
||||
|
||||
SKIP_BUILD=0
|
||||
FORMATS="appimage deb rpm tar"
|
||||
ARCH_TAR_DIR=
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--skip-build) SKIP_BUILD=1; shift ;;
|
||||
--formats) FORMATS="$2"; shift 2 ;;
|
||||
--arch-tar-dir)
|
||||
[[ -n "${2:-}" ]] || { echo "error: --arch-tar-dir needs a directory" >&2; exit 2; }
|
||||
ARCH_TAR_DIR="$2"
|
||||
shift 2
|
||||
;;
|
||||
-h | --help) sed -n '2,15p' "$0"; exit 0 ;;
|
||||
*) echo "unknown argument: $1" >&2; exit 2 ;;
|
||||
esac
|
||||
@@ -38,9 +44,24 @@ case "$ARCH" in
|
||||
*) echo "unsupported architecture $ARCH" >&2; exit 2 ;;
|
||||
esac
|
||||
export TEXTURECRAFT_MAINTAINER="${TEXTURECRAFT_MAINTAINER:-TextureCraft maintainers <texturecraft@storyteller.ai>}"
|
||||
IS_NIGHTLY=0
|
||||
if [[ "${TEXTURECRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then
|
||||
IS_NIGHTLY=1
|
||||
export TEXTURECRAFT_BUILD_CHANNEL=nightly-v1
|
||||
export TEXTURECRAFT_OVERRIDE_VERSION="$VERSION"
|
||||
fi
|
||||
NIGHTLY_ICON="$ROOT/assets/app-icon/texturecraft-nightly.png"
|
||||
if [[ ! -f "$NIGHTLY_ICON" ]]; then
|
||||
NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
|
||||
fi
|
||||
BASENAME="texturecraft-$VERSION-linux-$ARCH"
|
||||
|
||||
echo "==> TextureCraft $VERSION for Linux $ARCH ($FORMATS)"
|
||||
if [[ -n "$ARCH_TAR_DIR" && "$IS_NIGHTLY" != 1 ]]; then
|
||||
echo "error: --arch-tar-dir is only for Nightly builds" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
echo "==> TextureCraft $VERSION for Linux $ARCH ($FORMATS, channel=${TEXTURECRAFT_BUILD_CHANNEL:-stable})"
|
||||
|
||||
if [[ "$SKIP_BUILD" = 0 ]]; then
|
||||
(cd "$ROOT" && cargo build --release --locked -p texturecraft -p texturecraft-cli ${CROSS_TARGET:+--target "$CROSS_TARGET"})
|
||||
@@ -52,9 +73,20 @@ rm -rf "$WORK"
|
||||
|
||||
# ---- stage an FHS tree (shared by every format) -------------------------------------------------
|
||||
install -Dm755 "$BIN/texturecraft" "$STAGE/usr/bin/texturecraft"
|
||||
install -Dm755 "$BIN/texturecraft-cli" "$STAGE/usr/bin/texturecraft-cli"
|
||||
"${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/texturecraft" "$STAGE/usr/bin/texturecraft-cli" 2>/dev/null || true
|
||||
"${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/texturecraft" 2>/dev/null || true
|
||||
# The Nightly formats ship the GUI only (the kit's rule). texturecraft-cli loads its brush presets
|
||||
# from the host's Documents/TextureCraft, which is Stable's folder (`crates/automation`'s Headless),
|
||||
# so a Nightly CLI would read and rewrite Stable's brushes. Stable keeps its CLI.
|
||||
if [[ "$IS_NIGHTLY" = 0 ]]; then
|
||||
install -Dm755 "$BIN/texturecraft-cli" "$STAGE/usr/bin/texturecraft-cli"
|
||||
"${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/texturecraft-cli" 2>/dev/null || true
|
||||
fi
|
||||
install -Dm644 "$HERE/$APP_ID.desktop" "$STAGE/usr/share/applications/$APP_ID.desktop"
|
||||
if [[ "$IS_NIGHTLY" = 1 ]]; then
|
||||
sed -e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.texturecraft.nightly-v1|' \
|
||||
"$STAGE/usr/share/applications/$APP_ID.desktop" >"$STAGE/usr/share/applications/$APP_ID.desktop.tmp"
|
||||
mv "$STAGE/usr/share/applications/$APP_ID.desktop.tmp" "$STAGE/usr/share/applications/$APP_ID.desktop"
|
||||
fi
|
||||
install -Dm644 "$HERE/$APP_ID.mime.xml" "$STAGE/usr/share/mime/packages/$APP_ID.xml"
|
||||
mkdir -p "$STAGE/usr/share/metainfo"
|
||||
sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$TEXTURECRAFT_BUILD_DATE/g" \
|
||||
@@ -77,17 +109,91 @@ has() { case " $FORMATS " in *" $1 "*) return 0 ;; *) return 1 ;; esac; }
|
||||
if has tar; then
|
||||
mkdir -p "$WORK/tar"
|
||||
cp -R "$STAGE/usr" "$WORK/tar/$BASENAME"
|
||||
if [[ "$IS_NIGHTLY" = 1 ]]; then
|
||||
# A Nightly binary only starts with its private profile, so an unpacked tarball gets the same
|
||||
# launcher the other Nightly formats install: `texturecraft` starts `texturecraft-bin`.
|
||||
mv "$WORK/tar/$BASENAME/bin/texturecraft" "$WORK/tar/$BASENAME/bin/texturecraft-bin"
|
||||
install -Dm755 "$HERE/nightly-launch.sh" "$WORK/tar/$BASENAME/bin/texturecraft"
|
||||
fi
|
||||
tar -C "$WORK/tar" -czf "$DIST/$BASENAME.tar.gz" "$BASENAME"
|
||||
echo "wrote $DIST/$BASENAME.tar.gz"
|
||||
fi
|
||||
|
||||
# The Arch handoff keeps the same basename as the plain tarball in a separate directory.
|
||||
if [[ -n "$ARCH_TAR_DIR" ]]; then
|
||||
mkdir -p "$ARCH_TAR_DIR"
|
||||
if [[ "$(cd "$ARCH_TAR_DIR" && pwd -P)" == "$(cd "$DIST" && pwd -P)" ]]; then
|
||||
echo "error: the Arch tar directory must differ from the release directory" >&2
|
||||
exit 2
|
||||
fi
|
||||
bash "$HERE/nightly-arch-tar.sh" "$STAGE/usr" "$WORK/arch-tar" "$ARCH_TAR_DIR" "$BASENAME"
|
||||
fi
|
||||
|
||||
# ---- .deb / .rpm --------------------------------------------------------------------------------
|
||||
if has deb || has rpm; then
|
||||
command -v nfpm >/dev/null || { echo "error: nfpm not found (https://nfpm.goreleaser.com/install/)" >&2; exit 1; }
|
||||
export VERSION
|
||||
export NFPM_ARCH="$DEB_ARCH"
|
||||
NFPM_STAGE="$STAGE"
|
||||
export NFPM_NAME="texturecraft"
|
||||
export NFPM_BIN="texturecraft"
|
||||
export NFPM_CLI="texturecraft-cli"
|
||||
if [[ "$IS_NIGHTLY" = 1 ]]; then
|
||||
NIGHTLY_DESK_ID="$APP_ID.nightly-v1"
|
||||
export NFPM_NAME="texturecraft-nightly"
|
||||
export NFPM_BIN="texturecraft-nightly"
|
||||
NFPM_STAGE="$WORK/nfpm-root"
|
||||
rm -rf "$NFPM_STAGE"
|
||||
cp -R "$STAGE" "$NFPM_STAGE"
|
||||
install -Dm755 "$NFPM_STAGE/usr/bin/texturecraft" "$NFPM_STAGE/usr/lib/texturecraft-nightly/texturecraft"
|
||||
cat >"$NFPM_STAGE/usr/bin/$NFPM_BIN" <<'WRAPPER'
|
||||
#!/bin/sh
|
||||
# TextureCraft Nightly: the GUI runs with the Launcher's private profile, which holds every
|
||||
# per-user file (settings, ui.json, logs, autosaves, materials, layouts, templates, presets).
|
||||
set -eu
|
||||
bin=/usr/lib/texturecraft-nightly/texturecraft
|
||||
profile="${XDG_DATA_HOME:-${HOME:-}/.local/share}/TextureCraft-Nightly"
|
||||
# The Launcher's protocol, and a bare version query, pass through untouched.
|
||||
case "${1-}" in
|
||||
--launch-profile | --profile-root | --version | -V) exec "$bin" "$@" ;;
|
||||
esac
|
||||
exec "$bin" --launch-profile nightly-v1 --profile-root "$profile" -- "$@"
|
||||
WRAPPER
|
||||
chmod 755 "$NFPM_STAGE/usr/bin/$NFPM_BIN"
|
||||
rm -f "$NFPM_STAGE/usr/bin/texturecraft"
|
||||
mv "$NFPM_STAGE/usr/share/doc/texturecraft" "$NFPM_STAGE/usr/share/doc/$NFPM_NAME"
|
||||
sed -e "s#^Exec=texturecraft\([[:space:]]\|$\)#Exec=$NFPM_BIN\1#" \
|
||||
-e "s|^TryExec=texturecraft$|TryExec=$NFPM_BIN|" \
|
||||
-e "s|^Icon=$APP_ID$|Icon=$NIGHTLY_DESK_ID|" \
|
||||
-e "s|^Name=TextureCraft$|Name=TextureCraft Nightly|" \
|
||||
-e '/^MimeType=/d' \
|
||||
"$NFPM_STAGE/usr/share/applications/$APP_ID.desktop" >"$NFPM_STAGE/usr/share/applications/$NIGHTLY_DESK_ID.desktop"
|
||||
rm -f "$NFPM_STAGE/usr/share/applications/$APP_ID.desktop"
|
||||
# The Nightly entry claims no MIME types (stable keeps the associations), so the metainfo must
|
||||
# not advertise them either.
|
||||
sed -e "s|<id>$APP_ID</id>|<id>$NIGHTLY_DESK_ID</id>|g" \
|
||||
-e "s|<name>TextureCraft</name>|<name>TextureCraft 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>texturecraft</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"
|
||||
install -Dm644 "$NIGHTLY_ICON" \
|
||||
"$NFPM_STAGE/usr/share/icons/hicolor/256x256/apps/$NIGHTLY_DESK_ID.png"
|
||||
fi
|
||||
# nfpm expands env vars in fields like `version` and `arch`, but not in `contents[].src`.
|
||||
sed "s|\${STAGE}|$STAGE|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml"
|
||||
DROP_LIB_TREE=
|
||||
DROP_CLI=
|
||||
# shellcheck disable=SC2016
|
||||
[[ -d "$NFPM_STAGE/usr/lib" ]] || DROP_LIB_TREE='\|^ - src: \${STAGE}/usr/lib/|,+2d;'
|
||||
# A Nightly package has no CLI, so its file list must not name one either.
|
||||
# shellcheck disable=SC2016
|
||||
[[ "$IS_NIGHTLY" = 0 ]] || DROP_CLI='\|^ - src: \${STAGE}/usr/bin/\${NFPM_CLI}|,+2d;/Includes texturecraft-cli/d;'
|
||||
# shellcheck disable=SC2016
|
||||
sed "${DROP_LIB_TREE}${DROP_CLI}s|\${STAGE}|$NFPM_STAGE|g;s|\${NFPM_BIN}|$NFPM_BIN|g;s|\${NFPM_CLI}|$NFPM_CLI|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml"
|
||||
# The riscv64 cross sysroot is Ubuntu 24.04, whose glibc floor is 2.39.
|
||||
if [[ "$ARCH" = riscv64 ]]; then sed -i "s/libc6 (>= 2.35)/libc6 (>= 2.39)/" "$WORK/nfpm.yaml"; fi
|
||||
for fmt in deb rpm; do
|
||||
@@ -105,9 +211,46 @@ if has appimage; then
|
||||
# app_id to our icon instead of the generic Wayland logo (opt-out env in the
|
||||
# script header). Logic is covered by packaging/linux/apprun-test.sh.
|
||||
install -Dm755 "$HERE/AppRun" "$APPDIR/AppRun"
|
||||
cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop"
|
||||
cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png"
|
||||
ln -s "$APP_ID.png" "$APPDIR/.DirIcon"
|
||||
if [[ "$IS_NIGHTLY" = 1 ]]; then
|
||||
APPIMAGE_ID="$APP_ID.nightly-v1"
|
||||
# The desktop id and the channel line: a Nightly AppImage must start the app with the
|
||||
# Launcher's private profile, not with stable's folders (AppRun's tail does the exec).
|
||||
awk -v old_id="$APP_ID" -v new_id="$APPIMAGE_ID" '
|
||||
$0 == "DESK_ID=" old_id { print "DESK_ID=" new_id; next }
|
||||
$0 == "CHANNEL=stable" { print "CHANNEL=nightly-v1"; next }
|
||||
{ print }
|
||||
' "$APPDIR/AppRun" >"$APPDIR/AppRun.tmp"
|
||||
grep -qx 'CHANNEL=nightly-v1' "$APPDIR/AppRun.tmp" || {
|
||||
echo "error: AppRun has no CHANNEL=stable line to switch for Nightly" >&2
|
||||
exit 1
|
||||
}
|
||||
mv "$APPDIR/AppRun.tmp" "$APPDIR/AppRun"
|
||||
chmod 755 "$APPDIR/AppRun"
|
||||
sed -e "s|^Icon=$APP_ID$|Icon=$APPIMAGE_ID|" \
|
||||
-e "s|^Name=TextureCraft$|Name=TextureCraft Nightly|" \
|
||||
-e '/^MimeType=/d' \
|
||||
"$APPDIR/usr/share/applications/$APP_ID.desktop" >"$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop"
|
||||
rm -f "$APPDIR/usr/share/applications/$APP_ID.desktop"
|
||||
cp "$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop" "$APPDIR/$APPIMAGE_ID.desktop"
|
||||
# The Nightly desktop entry drops MimeType=, so the metainfo must not advertise the same types
|
||||
# either: AppStream would otherwise list a type the package cannot open.
|
||||
sed -e "s|<id>$APP_ID</id>|<id>$APPIMAGE_ID</id>|g" \
|
||||
-e "s|<name>TextureCraft</name>|<name>TextureCraft Nightly</name>|g" \
|
||||
-e "s|<launchable type=\"desktop-id\">$APP_ID.desktop</launchable>|<launchable type=\"desktop-id\">$APPIMAGE_ID.desktop</launchable>|g" \
|
||||
-e "s|<icon type=\"stock\">$APP_ID</icon>|<icon type=\"stock\">$APPIMAGE_ID</icon>|g" \
|
||||
-e '/<mediatype>/d' \
|
||||
"$APPDIR/usr/share/metainfo/$APP_ID.metainfo.xml" >"$APPDIR/usr/share/metainfo/$APPIMAGE_ID.metainfo.xml"
|
||||
rm -f "$APPDIR/usr/share/metainfo/$APP_ID.metainfo.xml"
|
||||
rm -rf "$APPDIR/usr/share/icons/hicolor"
|
||||
install -Dm644 "$NIGHTLY_ICON" \
|
||||
"$APPDIR/usr/share/icons/hicolor/256x256/apps/$APPIMAGE_ID.png"
|
||||
cp "$NIGHTLY_ICON" "$APPDIR/$APPIMAGE_ID.png"
|
||||
ln -s "$APPIMAGE_ID.png" "$APPDIR/.DirIcon"
|
||||
else
|
||||
cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop"
|
||||
cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png"
|
||||
ln -s "$APP_ID.png" "$APPDIR/.DirIcon"
|
||||
fi
|
||||
|
||||
TOOL="${APPIMAGETOOL:-$(command -v appimagetool || true)}"
|
||||
if [[ -z "$TOOL" ]]; then
|
||||
@@ -129,11 +272,24 @@ if has appimage; then
|
||||
# next to each AppImage on GitHub Releases. `latest` is the newest published release that is
|
||||
# not a pre-release. A fork's builds point at its own releases through GITHUB_REPOSITORY.
|
||||
REPO="${GITHUB_REPOSITORY:-storytold/texturecraft}"
|
||||
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|texturecraft-*-linux-$ARCH.AppImage.zsync"
|
||||
UPDATE_ARGS=()
|
||||
if [[ "$IS_NIGHTLY" = 0 ]]; then
|
||||
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|texturecraft-*-linux-$ARCH.AppImage.zsync"
|
||||
UPDATE_ARGS=(-u "$UPDATE_INFO")
|
||||
else
|
||||
# Nightly releases are GitHub pre-releases (`latest` only selects stable releases), so point
|
||||
# zsync update metadata at pre-release tags rather than stable `latest`.
|
||||
if [[ "$VERSION" == *-nightly* ]]; then
|
||||
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest-pre|texturecraft-*-nightly*-linux-$ARCH.AppImage.zsync"
|
||||
else
|
||||
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest-pre|texturecraft-*-linux-$ARCH.AppImage.zsync"
|
||||
fi
|
||||
UPDATE_ARGS=(-u "$UPDATE_INFO")
|
||||
fi
|
||||
# Extract-and-run: works without FUSE (containers, CI). The output embeds the static runtime,
|
||||
# so users don't need libfuse2 either. With zsyncmake on the host (CI installs the zsync
|
||||
# package) appimagetool also writes the .zsync, into its working directory, hence the cd.
|
||||
(cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream -u "$UPDATE_INFO" "$APPDIR" "$OUT")
|
||||
(cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream "${UPDATE_ARGS[@]}" "$APPDIR" "$OUT")
|
||||
echo "wrote $OUT"
|
||||
if [[ -s "$OUT.zsync" ]]; then
|
||||
echo "wrote $OUT.zsync"
|
||||
@@ -142,10 +298,14 @@ if has appimage; then
|
||||
fi
|
||||
fi
|
||||
|
||||
# A Stable tree is checked through its CLI; a Nightly tree has only the GUI, which answers the
|
||||
# same bare `--version` query (no profile, so nothing is created) with its channel line.
|
||||
SMOKE_BIN="$STAGE/usr/bin/texturecraft-cli"
|
||||
if [[ "$IS_NIGHTLY" = 1 ]]; then SMOKE_BIN="$STAGE/usr/bin/texturecraft"; fi
|
||||
if [[ -n "${CROSS_TARGET:-}" ]]; then
|
||||
if [[ -n "${EMULATOR:-}" ]]; then "$EMULATOR" "$STAGE/usr/bin/texturecraft-cli" --version; fi
|
||||
if [[ -n "${EMULATOR:-}" ]]; then "$EMULATOR" "$SMOKE_BIN" --version; fi
|
||||
else
|
||||
"$STAGE/usr/bin/texturecraft-cli" --version
|
||||
"$SMOKE_BIN" --version
|
||||
fi
|
||||
echo "==> done"
|
||||
ls -lh "$DIST"
|
||||
@@ -0,0 +1,125 @@
|
||||
# shellcheck shell=bash
|
||||
# Shared checks for the Apple-silicon Nightly scripts (nightly.sh, nightly-sign.sh, nightly-verify.sh).
|
||||
# Stable packaging (package.sh, verify.sh) does not source this file. The text checks take tool output
|
||||
# as arguments, so packaging/macos/nightly_sign_tests.py runs them without macOS.
|
||||
|
||||
MAC_NIGHTLY_APP='TextureCraft Nightly.app'
|
||||
MAC_NIGHTLY_ID='ai.storyteller.texturecraft.nightly'
|
||||
MAC_NIGHTLY_EXECUTABLE='TextureCraft'
|
||||
# nightly.sh copies it into the bundle; the file is linted on its own, without -x, so shellcheck
|
||||
# cannot see that use.
|
||||
# shellcheck disable=SC2034
|
||||
MAC_NIGHTLY_ICON='texturecraft-nightly'
|
||||
# The release environment's names, as release.yml passes them (packaging/macos/import-cert.sh).
|
||||
MAC_NIGHTLY_SECRETS=(APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID)
|
||||
|
||||
mac_nightly_die() { printf 'error: %s\n' "$*" >&2; exit 2; }
|
||||
|
||||
# The exact prepared version from the feed asset name, or failure.
|
||||
mac_nightly_version_from_asset() {
|
||||
local name="$1" version
|
||||
[[ "$name" =~ ^texturecraft-(.+)-macos-aarch64-nightly\.zip$ ]] || return 1
|
||||
version="${BASH_REMATCH[1]}"
|
||||
[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || return 1
|
||||
printf '%s\n' "$version"
|
||||
}
|
||||
|
||||
# Every signing and notarization value is set, and the team is one Apple team ID. No ad-hoc fallback.
|
||||
mac_nightly_require_secrets() {
|
||||
local name
|
||||
for name in "${MAC_NIGHTLY_SECRETS[@]}"; do
|
||||
[[ -n "${!name:-}" ]] || mac_nightly_die "$name is not set: Nightly signing and notarization are required, with no ad-hoc fallback"
|
||||
done
|
||||
[[ "$APPLE_TEAM_ID" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'APPLE_TEAM_ID is not an Apple team ID'
|
||||
if [[ -n "${NIGHTLY_APPLE_TEAM_ID:-}" && "$NIGHTLY_APPLE_TEAM_ID" != "$APPLE_TEAM_ID" ]]; then
|
||||
mac_nightly_die 'the signing team differs from the reviewed Nightly team (NIGHTLY_APPLE_TEAM_ID)'
|
||||
fi
|
||||
}
|
||||
|
||||
# The keychain this app's import-cert.sh made belongs to this run: a regular file (no link) with the
|
||||
# app's keychain name, inside the run directory. Its script makes its own name under RUNNER_TEMP, so
|
||||
# the path is read from its printed output rather than assumed.
|
||||
mac_nightly_keychain_is_ours() {
|
||||
local keychain="$1" work="$2"
|
||||
[[ -f "$keychain" && ! -L "$keychain" ]] || return 1
|
||||
[[ "$(basename -- "$keychain")" == texturecraft-signing.keychain-db ]] || return 1
|
||||
case "$keychain" in "$work"/*) return 0 ;; *) return 1 ;; esac
|
||||
}
|
||||
|
||||
# One line of `security find-identity -v -p codesigning`: the identity is a Developer ID Application of the team.
|
||||
mac_nightly_identity_is_team() {
|
||||
local line="$1" identity="$2" team="$3"
|
||||
[[ "$line" == *" $identity "* && "$line" == *'"Developer ID Application: '*" ($team)\""* ]]
|
||||
}
|
||||
|
||||
# `codesign -d --verbose=2` of the signed bundle: the Nightly identifier, a Developer ID Application of the
|
||||
# team, a secure timestamp and the hardened runtime (the checks of verify.sh, made strict).
|
||||
mac_nightly_check_signature() {
|
||||
local details="$1" team="$2" ok=0
|
||||
grep -Fqx "Identifier=$MAC_NIGHTLY_ID" <<<"$details" || { echo "error: the bundle is not signed as $MAC_NIGHTLY_ID" >&2; ok=1; }
|
||||
grep -q '^Authority=Developer ID Application:' <<<"$details" || { echo 'error: not signed with a Developer ID Application identity' >&2; ok=1; }
|
||||
grep -qx "TeamIdentifier=$team" <<<"$details" || { echo 'error: signed by a different team' >&2; ok=1; }
|
||||
grep -q '^Timestamp=' <<<"$details" || { echo 'error: the signature has no secure timestamp' >&2; ok=1; }
|
||||
grep -Eq '^CodeDirectory .*flags=0x[0-9a-f]+\([^)]*runtime' <<<"$details" || { echo 'error: not signed with the hardened runtime' >&2; ok=1; }
|
||||
return "$ok"
|
||||
}
|
||||
|
||||
# `spctl --assess --type execute -vv`: Gatekeeper accepts the bundle as notarized.
|
||||
mac_nightly_check_assessment() {
|
||||
grep -q 'accepted' <<<"$1" && grep -qx 'source=Notarized Developer ID' <<<"$1"
|
||||
}
|
||||
|
||||
# Before anything is unpacked: every ZIP entry is a regular file or directory inside the one Nightly
|
||||
# bundle, with no absolute path, `..`, backslash or empty component, and no link or special file.
|
||||
mac_nightly_check_zip_entries() {
|
||||
python3 -I - "$1" "$MAC_NIGHTLY_APP" <<'PY' || mac_nightly_die 'the archive has an entry outside the bundle, a link or a special file'
|
||||
import stat, sys, zipfile
|
||||
archive, app = sys.argv[1:]
|
||||
with zipfile.ZipFile(archive) as z:
|
||||
for info in z.infolist():
|
||||
name = info.filename
|
||||
parts = name.rstrip("/").split("/")
|
||||
mode = info.external_attr >> 16
|
||||
if (name.startswith("/") or "\\" in name or "\0" in name or parts[0] != app
|
||||
or any(part in ("", ".", "..") for part in parts)
|
||||
or stat.S_IFMT(mode) not in (0, stat.S_IFREG, stat.S_IFDIR)):
|
||||
sys.exit(f"refused entry: {name!r}")
|
||||
PY
|
||||
}
|
||||
|
||||
# An unpacked payload directory holds exactly the GUI-only Nightly bundle: one thin arm64 executable,
|
||||
# the Nightly identity and the exact version (no numeric fallback), no CLI, no links or special
|
||||
# files, no document or URL types.
|
||||
mac_nightly_check_bundle() {
|
||||
local payload="$1" version="$2" app entries plist key value
|
||||
app="$payload/$MAC_NIGHTLY_APP"
|
||||
entries="$(ls -A "$payload")"
|
||||
[[ "$entries" == "$MAC_NIGHTLY_APP" && -d "$app" && ! -L "$app" ]] || mac_nightly_die "the archive must hold exactly $MAC_NIGHTLY_APP"
|
||||
[[ -z "$(find "$payload" ! -type f ! -type d -print -quit)" ]] || mac_nightly_die 'the bundle contains links or special files'
|
||||
[[ "$(ls -A "$app/Contents/MacOS")" == "$MAC_NIGHTLY_EXECUTABLE" ]] || mac_nightly_die 'Contents/MacOS must hold only the GUI executable (no CLI)'
|
||||
[[ -f "$app/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE" && -x "$app/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE" ]] || mac_nightly_die 'missing executable GUI'
|
||||
[[ "$(lipo -archs "$app/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE")" == arm64 ]] || mac_nightly_die 'the GUI must be thin arm64'
|
||||
plist="$app/Contents/Info.plist"
|
||||
for key in CFBundleIdentifier CFBundleExecutable TextureCraftVersion; do
|
||||
value="$(plutil -extract "$key" raw -o - "$plist")" || mac_nightly_die "Info.plist has no $key"
|
||||
case "$key" in
|
||||
CFBundleIdentifier) [[ "$value" == "$MAC_NIGHTLY_ID" ]] ;;
|
||||
CFBundleExecutable) [[ "$value" == "$MAC_NIGHTLY_EXECUTABLE" ]] ;;
|
||||
TextureCraftVersion) [[ "$value" == "$version" ]] ;;
|
||||
esac || mac_nightly_die "Info.plist $key is not the prepared Nightly identity"
|
||||
done
|
||||
for key in CFBundleDocumentTypes CFBundleURLTypes UTExportedTypeDeclarations UTImportedTypeDeclarations; do
|
||||
if plutil -extract "$key" xml1 -o - "$plist" >/dev/null 2>&1; then mac_nightly_die "Nightly declares $key"; fi
|
||||
done
|
||||
}
|
||||
|
||||
# `stapler validate` asks the CloudKit service, which sometimes drops the connection (error 68)
|
||||
# though the ticket is there (verify.sh).
|
||||
mac_nightly_validate_staple() {
|
||||
local target="$1" attempt
|
||||
for attempt in 1 2 3 4 5; do
|
||||
xcrun stapler validate "$target" && return 0
|
||||
[[ "$attempt" = 5 ]] || sleep $((attempt * 20))
|
||||
done
|
||||
return 1
|
||||
}
|
||||
Executable
+141
@@ -0,0 +1,141 @@
|
||||
#!/usr/bin/env bash
|
||||
# Trusted signing step for the Apple-silicon Nightly, the stable release's macOS signing route
|
||||
# (import-cert.sh, then package.sh's codesign, notarytool and stapler steps):
|
||||
#
|
||||
# nightly-sign.sh --arch aarch64 --input /abs/texturecraft-<version>-macos-aarch64-nightly.zip \
|
||||
# --output /abs/<dir>/texturecraft-<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%/}/texturecraft-nightly-sign.XXXXXX")"
|
||||
KEYCHAIN="$WORK/texturecraft-signing.keychain-db"
|
||||
cleanup() {
|
||||
if [[ -e "$KEYCHAIN" ]]; then security delete-keychain "$KEYCHAIN" >/dev/null 2>&1 || rm -f -- "$KEYCHAIN"; fi
|
||||
rm -rf -- "$WORK"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
# ---- identity: import-cert.sh, into this run's private directory ------------------------------
|
||||
# An empty GITHUB_ENV makes it print the identity instead of exporting it to later steps.
|
||||
imported="$(GITHUB_ENV='' RUNNER_TEMP="$WORK" DIST="$WORK/dist" bash "$HERE/import-cert.sh")"
|
||||
IDENTITY="$(sed -n 's/^MACOS_SIGN_IDENTITY=//p' <<<"$imported")"
|
||||
KEYCHAIN="$(sed -n 's/^MACOS_KEYCHAIN=//p' <<<"$imported")"
|
||||
[[ "$IDENTITY" =~ ^[0-9A-F]{40}$ ]] || mac_nightly_die 'import-cert.sh did not import a signing identity'
|
||||
mac_nightly_keychain_is_ours "$KEYCHAIN" "$WORK" || mac_nightly_die 'import-cert.sh did not create this run keychain'
|
||||
mac_nightly_identity_is_team "$(security find-identity -v -p codesigning "$KEYCHAIN" | grep -F " $IDENTITY " || true)" "$IDENTITY" "$APPLE_TEAM_ID" \
|
||||
|| mac_nightly_die "the imported identity is not a Developer ID Application of team $APPLE_TEAM_ID"
|
||||
echo "==> TextureCraft Nightly $VERSION for macOS (aarch64), identity: $IDENTITY"
|
||||
|
||||
# ---- the unsigned bundle ---------------------------------------------------------------------------
|
||||
mac_nightly_check_zip_entries "$INPUT"
|
||||
ditto -x -k --norsrc --noextattr "$INPUT" "$WORK/payload"
|
||||
mac_nightly_check_bundle "$WORK/payload" "$VERSION"
|
||||
APP="$WORK/payload/$MAC_NIGHTLY_APP"
|
||||
|
||||
# ---- package.sh's signing and notarization, with a required Developer ID ---------------------------
|
||||
sign() {
|
||||
codesign --force --sign "$IDENTITY" --keychain "$KEYCHAIN" --timestamp "$@"
|
||||
}
|
||||
|
||||
notarize() {
|
||||
local file="$1" out id status
|
||||
echo "==> notarizing $(basename "$file") (this can take a few minutes)"
|
||||
out="$(xcrun notarytool submit "$file" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" \
|
||||
--team-id "$APPLE_TEAM_ID" --wait --timeout 1h --output-format json)" || true
|
||||
echo "$out"
|
||||
id="$(printf '%s' "$out" | plutil -extract id raw -o - - 2>/dev/null || true)"
|
||||
status="$(printf '%s' "$out" | plutil -extract status raw -o - - 2>/dev/null || true)"
|
||||
if [[ "$status" != "Accepted" ]]; then
|
||||
if [[ -n "$id" ]]; then
|
||||
# Capped: the shared signer bounds a step output at 256 KiB.
|
||||
xcrun notarytool log "$id" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" --team-id "$APPLE_TEAM_ID" | head -c 131072 || true
|
||||
fi
|
||||
echo "error: notarization of $(basename "$file") failed (status: ${status:-unknown})" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Stapling and validating both look the ticket up in the CloudKit service, which can drop the
|
||||
# connection right after notarization (error 68), so retry the pair (package.sh).
|
||||
staple() {
|
||||
local file="$1" attempt
|
||||
for attempt in 1 2 3 4 5; do
|
||||
if xcrun stapler staple "$file" && xcrun stapler validate "$file"; then
|
||||
return
|
||||
fi
|
||||
if [[ "$attempt" = 5 ]]; then
|
||||
echo "error: stapling $(basename "$file") failed after $attempt attempts" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "stapling $(basename "$file") failed (attempt $attempt); retrying in $((attempt * 20))s" >&2
|
||||
sleep $((attempt * 20))
|
||||
done
|
||||
}
|
||||
|
||||
# Inside-out: the executable, then the bundle (no --deep on the final signature).
|
||||
sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE"
|
||||
sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP"
|
||||
codesign --verify --strict --deep --verbose=2 "$APP"
|
||||
ditto -c -k --keepParent "$APP" "$WORK/notarize.zip"
|
||||
notarize "$WORK/notarize.zip"
|
||||
# The ticket goes into the bundle (Contents/CodeResources): the Launcher's extract restores no xattrs.
|
||||
staple "$APP"
|
||||
|
||||
# ---- the final archive, checked as the Launcher unpacks it -----------------------------------------
|
||||
ditto -c -k --norsrc --noextattr --noacl --keepParent "$APP" "$WORK/final.zip"
|
||||
ditto -x -k --norsrc --noextattr "$WORK/final.zip" "$WORK/check"
|
||||
mac_nightly_check_bundle "$WORK/check" "$VERSION"
|
||||
CHECK="$WORK/check/$MAC_NIGHTLY_APP"
|
||||
codesign --verify --strict --deep --verbose=2 "$CHECK"
|
||||
mac_nightly_check_signature "$(codesign -d --verbose=2 "$CHECK" 2>&1)" "$APPLE_TEAM_ID" \
|
||||
|| mac_nightly_die 'the signed bundle is not the required Developer ID signature'
|
||||
mac_nightly_validate_staple "$CHECK" || mac_nightly_die 'no notarization ticket is stapled into the bundle'
|
||||
# spctl lookup can lag a few seconds behind notarytool Accepted (verify.sh).
|
||||
for attempt in 1 2 3 4 5; do
|
||||
assessment="$(spctl --assess --type execute -vv "$CHECK" 2>&1)" || true
|
||||
mac_nightly_check_assessment "$assessment" && break
|
||||
[[ "$attempt" = 5 ]] || sleep 10
|
||||
done
|
||||
printf '%s\n' "$assessment"
|
||||
mac_nightly_check_assessment "$assessment" || mac_nightly_die 'Gatekeeper does not accept the bundle as notarized'
|
||||
|
||||
nightly_publish_archive "$WORK/final.zip" "$OUTPUT"
|
||||
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/texturecraft-<version>-macos-aarch64-nightly.zip --expect signed [--team ID]
|
||||
# nightly-verify.sh --input /abs/texturecraft-<version>-macos-aarch64-nightly.zip --expect unsigned
|
||||
#
|
||||
# Both: the archive holds only the GUI-only Nightly bundle with the exact TextureCraftVersion, unpacked
|
||||
# without extended attributes. `signed` (the feed artifact): Developer ID of the team (--team, else
|
||||
# NIGHTLY_APPLE_TEAM_ID), hardened runtime, secure timestamp, stapled ticket, Gatekeeper accepts it as
|
||||
# notarized. `unsigned` (nightly.sh compile output, e.g. pull-request CI) checks no signature.
|
||||
# Last, the GUI answers its version query with an empty environment, both plainly and in the
|
||||
# Launcher form `--launch-profile nightly-v1 --profile-root <fresh dir> --version` (the shared producer
|
||||
# smoke): each must exit 0 within 15 seconds, print exactly `TextureCraft <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,15p' "$0"; exit 0 ;;
|
||||
*) mac_nightly_die "unsupported argument: $1" ;;
|
||||
esac
|
||||
done
|
||||
for name in "${MAC_NIGHTLY_SECRETS[@]}" MACOS_SIGN_IDENTITY MACOS_KEYCHAIN; do
|
||||
[[ -z "${!name:-}" ]] || mac_nightly_die "refusing to run the payload with signing material in the environment ($name)"
|
||||
done
|
||||
[[ "$EXPECT" == signed || "$EXPECT" == unsigned ]] || mac_nightly_die '--expect must be signed or unsigned'
|
||||
[[ "$EXPECT" == unsigned || "$TEAM" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'a signed check needs the Apple team ID (--team or NIGHTLY_APPLE_TEAM_ID)'
|
||||
[[ "$INPUT" == /* && -f "$INPUT" && ! -L "$INPUT" ]] || mac_nightly_die '--input must be an absolute regular file'
|
||||
VERSION="$(mac_nightly_version_from_asset "$(basename -- "$INPUT")")" || mac_nightly_die 'the input is not a prepared Nightly archive name'
|
||||
[[ "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] || mac_nightly_die 'needs an Apple silicon Mac'
|
||||
|
||||
WORK="$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/texturecraft-nightly-verify.XXXXXX")"
|
||||
trap 'rm -rf -- "$WORK"' EXIT
|
||||
mac_nightly_check_zip_entries "$INPUT"
|
||||
ditto -x -k --norsrc --noextattr "$INPUT" "$WORK/payload"
|
||||
mac_nightly_check_bundle "$WORK/payload" "$VERSION"
|
||||
APP="$WORK/payload/$MAC_NIGHTLY_APP"
|
||||
|
||||
if [[ "$EXPECT" == signed ]]; then
|
||||
codesign --verify --strict --deep --verbose=2 "$APP"
|
||||
mac_nightly_check_signature "$(codesign -d --verbose=2 "$APP" 2>&1)" "$TEAM" \
|
||||
|| mac_nightly_die 'the bundle is not the required Developer ID signature'
|
||||
mac_nightly_validate_staple "$APP" || mac_nightly_die 'no notarization ticket is stapled into the bundle'
|
||||
for attempt in 1 2 3 4 5; do
|
||||
assessment="$(spctl --assess --type execute -vv "$APP" 2>&1)" || true
|
||||
mac_nightly_check_assessment "$assessment" && break
|
||||
[[ "$attempt" = 5 ]] || sleep 10
|
||||
done
|
||||
printf '%s\n' "$assessment"
|
||||
mac_nightly_check_assessment "$assessment" || mac_nightly_die 'Gatekeeper does not accept the bundle as notarized'
|
||||
fi
|
||||
|
||||
# macOS has no timeout(1): perl alarm survives its exec and ends a query that hangs (a dialog, say).
|
||||
query() {
|
||||
local out
|
||||
out="$(env -i HOME="$WORK/home" TMPDIR="$WORK/tmp/" PATH=/usr/bin:/bin \
|
||||
/usr/bin/perl -e 'alarm 15; exec @ARGV or die' "$APP/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE" "$@" 2>"$WORK/stderr")" \
|
||||
|| mac_nightly_die "the version query ($*) failed or did not finish within 15 s"
|
||||
[[ ! -s "$WORK/stderr" ]] || mac_nightly_die "the version query ($*) wrote to standard error: $(head -c 2000 "$WORK/stderr")"
|
||||
[[ "$out" == "TextureCraft $VERSION (nightly-v1)" ]] || mac_nightly_die "the version query ($*) reports '$out', not TextureCraft $VERSION (nightly-v1)"
|
||||
}
|
||||
mkdir -m 700 "$WORK/home" "$WORK/tmp" "$WORK/profile"
|
||||
query --version
|
||||
query --launch-profile nightly-v1 --profile-root "$WORK/profile" --version
|
||||
echo "==> verified ($EXPECT): TextureCraft $VERSION (nightly-v1), plain and in the Launcher profile form"
|
||||
Executable
+53
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env bash
|
||||
# App-owned GUI-only Nightly for Apple silicon, compile step only (no signing material):
|
||||
#
|
||||
# $DIST/texturecraft-<version>-macos-aarch64-nightly.zip TextureCraft Nightly.app, unsigned
|
||||
#
|
||||
# Usage: packaging/macos/nightly.sh --arch aarch64
|
||||
#
|
||||
# Required env (nightly-common.sh): TEXTURECRAFT_BUILD_CHANNEL=nightly-v1, TEXTURECRAFT_VERSION,
|
||||
# TEXTURECRAFT_BUILD_SHA, TEXTURECRAFT_BUILD_DATE, absolute CARGO_TARGET_DIR and DIST; CRAFT_FONTS_DIR optional.
|
||||
#
|
||||
# Not publishable by itself: the trusted step (nightly-sign.sh) signs, notarizes and staples it. No CLI,
|
||||
# DMG, document or URL types, and no stable package.sh. The bundle is not run here; the version query
|
||||
# runs on the signed bundle (nightly-verify.sh).
|
||||
set -euo pipefail
|
||||
ARCH=
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;;
|
||||
-h|--help) sed -n '2,13p' "$0"; exit 0 ;;
|
||||
*) echo "unsupported nightly argument: $1" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
[[ "$ARCH" == aarch64 && "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] || { echo 'only native macOS aarch64 nightly packaging is supported' >&2; exit 2; }
|
||||
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
# shellcheck source=../nightly-common.sh
|
||||
. "$HERE/../nightly-common.sh"
|
||||
# shellcheck source=nightly-lib.sh
|
||||
. "$HERE/nightly-lib.sh"
|
||||
nightly_refuse_signing_env
|
||||
nightly_init macos "$ARCH" aarch64-apple-darwin
|
||||
# Keep in sync with LSMinimumSystemVersion in Info.plist.in (as package.sh).
|
||||
export MACOSX_DEPLOYMENT_TARGET=11.0
|
||||
OUTPUT="$DIST/texturecraft-$VERSION-macos-aarch64-nightly.zip"
|
||||
[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || nightly_die 'refusing to replace an existing nightly archive'
|
||||
nightly_compile_gui
|
||||
|
||||
APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP"
|
||||
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
|
||||
cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE"
|
||||
chmod 755 "$APP/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE"
|
||||
cp "$ROOT/assets/app-icon/$MAC_NIGHTLY_ICON.icns" "$APP/Contents/Resources/$MAC_NIGHTLY_ICON.icns"
|
||||
nightly_copy_notices "$APP/Contents/Resources"
|
||||
# The private mktemp cwd is the helper authority root: stage the template inside it.
|
||||
cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in"
|
||||
(cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \
|
||||
--output "stage/$MAC_NIGHTLY_APP/Contents/Info.plist" --version "$VERSION" --source-commit "$TEXTURECRAFT_BUILD_SHA")
|
||||
plutil -lint "$APP/Contents/Info.plist"
|
||||
printf 'APPL????' >"$APP/Contents/PkgInfo"
|
||||
mac_nightly_check_bundle "$NIGHTLY_WORK/stage" "$VERSION"
|
||||
|
||||
# No resource forks, extended attributes or ACLs: the Launcher restores none, so nothing may depend on them.
|
||||
ditto -c -k --norsrc --noextattr --noacl --keepParent "$APP" "$NIGHTLY_WORK/archive.zip"
|
||||
nightly_publish_archive "$NIGHTLY_WORK/archive.zip" "$OUTPUT"
|
||||
@@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Nightly metadata: run from a private owned build cwd with a staged template.
|
||||
|
||||
All file arguments must stay beneath that cwd; this is not native/signing acceptance.
|
||||
"""
|
||||
import argparse
|
||||
import datetime
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import re
|
||||
import sys
|
||||
|
||||
# The shared helper location is fixed by this script, not by CLI file arguments.
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from nightly_paths import OwnedBuildRoot
|
||||
|
||||
MAX_TEMPLATE_BYTES = 256 * 1024
|
||||
|
||||
IDENTIFIER = "ai.storyteller.texturecraft.nightly"
|
||||
# Stable's own document, mesh and project declarations: a Nightly install registers no associations.
|
||||
ASSOCIATIONS = ("CFBundleDocumentTypes", "CFBundleURLTypes", "UTExportedTypeDeclarations", "UTImportedTypeDeclarations")
|
||||
VERSION = re.compile(r"([0-9]+\.[0-9]+\.[0-9]+)-nightly\.([0-9]{8})\.[0-9]+\.[0-9]+\.g([0-9a-f]{12})\Z")
|
||||
|
||||
|
||||
def render(template: bytes, version: str, commit: str) -> bytes:
|
||||
match = VERSION.fullmatch(version)
|
||||
if not match or not re.fullmatch(r"[0-9a-f]{40}", commit) or match[3] != commit[:12]:
|
||||
raise ValueError("exact prepared Nightly version and matching source commit are required")
|
||||
datetime.datetime.strptime(match[2], "%Y%m%d")
|
||||
data = plistlib.loads(template)
|
||||
if not isinstance(data, dict) or data.get("CFBundlePackageType") != "APPL":
|
||||
raise ValueError("expected the app-owned application plist template")
|
||||
for key in ASSOCIATIONS:
|
||||
data.pop(key, None)
|
||||
data.update(
|
||||
CFBundleDisplayName="TextureCraft Nightly",
|
||||
CFBundleName="TextureCraft Nightly",
|
||||
CFBundleIdentifier=IDENTIFIER,
|
||||
CFBundleExecutable="TextureCraft",
|
||||
CFBundleIconFile="texturecraft-nightly",
|
||||
CFBundleShortVersionString=match[1],
|
||||
CFBundleVersion=match[1],
|
||||
TextureCraftVersion=version,
|
||||
TextureCraftBuildCommit=commit,
|
||||
)
|
||||
return plistlib.dumps(data, fmt=plistlib.FMT_XML, sort_keys=False)
|
||||
|
||||
|
||||
def write_plist(template: Path, destination: Path, version: str, commit: str) -> None:
|
||||
with OwnedBuildRoot() as root:
|
||||
content = render(root.read_bytes(template, MAX_TEMPLATE_BYTES), version, commit)
|
||||
with root.create(destination) as stream:
|
||||
stream.write(content)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--template", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--version", required=True)
|
||||
parser.add_argument("--source-commit", required=True)
|
||||
args = parser.parse_args()
|
||||
write_plist(args.template, args.output, args.version, args.source_commit)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,202 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generated metadata/sentinel fixtures; no native binary, signature, archive or network."""
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import runpy
|
||||
import sys
|
||||
from unittest import mock
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
SPEC = importlib.util.spec_from_file_location("texturecraft_nightly_plist", HERE / "nightly_plist.py")
|
||||
POLICY = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(POLICY)
|
||||
COMMIT = "a" * 40
|
||||
VERSION = "0.23.1-nightly.20261121.12345.1.g" + COMMIT[:12]
|
||||
|
||||
|
||||
class NightlyMetadata(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.directory.cleanup)
|
||||
self.root = Path(self.directory.name).resolve()
|
||||
previous = Path.cwd()
|
||||
os.chdir(self.root)
|
||||
self.addCleanup(os.chdir, previous)
|
||||
self.template = self.root / "Info.plist.in"
|
||||
self.original = (HERE / "Info.plist.in").read_bytes()
|
||||
self.template.write_bytes(self.original)
|
||||
self.output = self.root / "Info.plist"
|
||||
|
||||
def test_nightly_transform_removes_associations_without_changing_stable_or_platform_metadata(self):
|
||||
stable = plistlib.loads(self.original)
|
||||
stable["CFBundleURLTypes"] = [{"CFBundleURLSchemes": ["generated-test-scheme"]}]
|
||||
prepared = plistlib.dumps(stable)
|
||||
self.template.write_bytes(prepared)
|
||||
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
|
||||
rendered = plistlib.loads(self.output.read_bytes())
|
||||
for key in POLICY.ASSOCIATIONS:
|
||||
self.assertNotIn(key, rendered)
|
||||
self.assertNotEqual(rendered["CFBundleIdentifier"], stable["CFBundleIdentifier"])
|
||||
self.assertEqual(rendered["CFBundleIdentifier"], "ai.storyteller.texturecraft.nightly")
|
||||
self.assertEqual(rendered["CFBundleExecutable"], "TextureCraft")
|
||||
self.assertEqual(rendered["TextureCraftVersion"], VERSION)
|
||||
self.assertEqual(rendered["TextureCraftBuildCommit"], COMMIT)
|
||||
self.assertTrue(VERSION.startswith(rendered["CFBundleVersion"] + "-nightly."))
|
||||
for key in ("LSMinimumSystemVersion", "LSApplicationCategoryType", "NSHighResolutionCapable", "NSHumanReadableCopyright"):
|
||||
self.assertEqual(rendered[key], stable[key])
|
||||
self.assertEqual(self.template.read_bytes(), prepared)
|
||||
self.assertEqual((HERE / "Info.plist.in").read_bytes(), self.original)
|
||||
|
||||
def test_bad_identity_or_template_refuses_before_creating_output(self):
|
||||
for version, commit in (("0.23.1", COMMIT), (VERSION, "b" * 40), (VERSION, "not-a-commit"), (VERSION.replace("20261121", "20261399"), COMMIT)):
|
||||
with self.subTest(version=version, commit=commit):
|
||||
with self.assertRaises(ValueError):
|
||||
POLICY.write_plist(self.template, self.output, version, commit)
|
||||
self.assertFalse(self.output.exists())
|
||||
self.assertEqual(self.template.read_bytes(), self.original)
|
||||
self.template.write_bytes(plistlib.dumps({"CFBundlePackageType": "generated-not-an-app"}))
|
||||
with self.assertRaises(ValueError):
|
||||
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
|
||||
self.assertFalse(self.output.exists())
|
||||
|
||||
def test_cli_writes_the_requested_identity_without_replacing_the_template(self):
|
||||
helper = HERE / "nightly_plist.py"
|
||||
argv = [str(helper), "--template", str(self.template), "--output", str(self.output), "--version", VERSION, "--source-commit", COMMIT]
|
||||
with mock.patch.object(sys, "argv", argv):
|
||||
runpy.run_path(str(helper), run_name="__main__")
|
||||
result = plistlib.loads(self.output.read_bytes())
|
||||
self.assertEqual(result["TextureCraftVersion"], VERSION)
|
||||
self.assertEqual(result["TextureCraftBuildCommit"], COMMIT)
|
||||
self.assertEqual(self.template.read_bytes(), self.original)
|
||||
|
||||
def test_template_alias_or_nonfile_refuses_before_output(self):
|
||||
alias = self.root / "template-alias"
|
||||
alias.symlink_to(self.template)
|
||||
for template in (alias, self.root, self.root / "missing-template"):
|
||||
with self.subTest(template=template), self.assertRaises(ValueError):
|
||||
POLICY.write_plist(template, self.output, VERSION, COMMIT)
|
||||
self.assertFalse(self.output.exists())
|
||||
self.assertEqual(self.template.read_bytes(), self.original)
|
||||
|
||||
def test_failed_write_cleans_owned_output_but_preserves_a_replacement(self):
|
||||
sentinel = b"generated replacement artifact"
|
||||
for disposition in ("owned", "missing", "replacement"):
|
||||
with self.subTest(disposition=disposition):
|
||||
if self.output.exists():
|
||||
self.output.unlink()
|
||||
|
||||
def fail_sync(_descriptor):
|
||||
# macOS/Linux allow unlink of an open file: exercise the real
|
||||
# cleanup ownership check, not a mocked inode comparison.
|
||||
if disposition != "owned":
|
||||
self.output.unlink()
|
||||
if disposition == "replacement":
|
||||
self.output.write_bytes(sentinel)
|
||||
raise OSError("generated fsync failure")
|
||||
|
||||
with mock.patch.object(POLICY.os, "fsync", side_effect=fail_sync), self.assertRaises(OSError):
|
||||
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
|
||||
if disposition == "replacement":
|
||||
self.assertEqual(self.output.read_bytes(), sentinel)
|
||||
else:
|
||||
self.assertFalse(self.output.exists())
|
||||
self.assertEqual(self.template.read_bytes(), self.original)
|
||||
|
||||
def test_exclusive_output_preserves_existing_bytes_and_symlink_targets(self):
|
||||
sentinel = b"generated owned sentinel, not an existing app or user file"
|
||||
self.output.write_bytes(sentinel)
|
||||
with self.assertRaises(FileExistsError):
|
||||
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
|
||||
self.assertEqual(self.output.read_bytes(), sentinel)
|
||||
self.output.unlink()
|
||||
external = self.root / "sentinel"
|
||||
external.write_bytes(sentinel)
|
||||
self.output.symlink_to(external)
|
||||
with self.assertRaisesRegex(ValueError, "symlinks or aliases"):
|
||||
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
|
||||
self.assertEqual(external.read_bytes(), sentinel)
|
||||
self.assertTrue(self.output.is_symlink())
|
||||
|
||||
|
||||
def test_template_outside_build_root_refuses_before_output(self):
|
||||
with tempfile.TemporaryDirectory() as external:
|
||||
template = Path(external) / "Info.plist.in"
|
||||
template.write_bytes(self.original)
|
||||
with self.assertRaises(ValueError):
|
||||
POLICY.write_plist(template, self.output, VERSION, COMMIT)
|
||||
self.assertFalse(self.output.exists())
|
||||
self.assertEqual(template.read_bytes(), self.original)
|
||||
|
||||
def test_output_outside_build_root_refuses_before_write(self):
|
||||
with tempfile.TemporaryDirectory() as external:
|
||||
output = Path(external) / "Info.plist"
|
||||
with self.assertRaises(ValueError):
|
||||
POLICY.write_plist(self.template, output, VERSION, COMMIT)
|
||||
self.assertFalse(output.exists())
|
||||
|
||||
def test_parent_traversal_refuses_even_to_an_owned_sibling(self):
|
||||
with tempfile.TemporaryDirectory(dir=self.root.parent) as external:
|
||||
output = Path("..") / Path(external).name / "Info.plist"
|
||||
with self.assertRaises(ValueError):
|
||||
POLICY.write_plist(self.template, output, VERSION, COMMIT)
|
||||
self.assertFalse((Path(external) / "Info.plist").exists())
|
||||
|
||||
def test_symlinked_output_parent_refuses(self):
|
||||
with tempfile.TemporaryDirectory() as external:
|
||||
alias = self.root / "alias"
|
||||
alias.symlink_to(external, target_is_directory=True)
|
||||
with self.assertRaises(ValueError):
|
||||
POLICY.write_plist(self.template, alias / "Info.plist", VERSION, COMMIT)
|
||||
self.assertFalse((Path(external) / "Info.plist").exists())
|
||||
|
||||
def test_template_read_is_bounded_before_output(self):
|
||||
self.template.write_bytes(plistlib.dumps({"CFBundlePackageType": "APPL", "fixture": "x" * 300000}))
|
||||
with self.assertRaises(ValueError):
|
||||
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
|
||||
self.assertFalse(self.output.exists())
|
||||
|
||||
def test_nonprivate_build_root_refuses(self):
|
||||
self.root.chmod(0o755)
|
||||
try:
|
||||
with self.assertRaises(ValueError):
|
||||
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
|
||||
self.assertFalse(self.output.exists())
|
||||
finally:
|
||||
self.root.chmod(0o700)
|
||||
|
||||
|
||||
def test_output_keeps_normal_new_file_permissions_inside_private_root(self):
|
||||
previous = os.umask(0o022)
|
||||
try:
|
||||
reference = self.root / "reference"
|
||||
reference.write_bytes(b"generated ordinary output")
|
||||
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
|
||||
finally:
|
||||
os.umask(previous)
|
||||
self.assertEqual(self.output.stat().st_mode & 0o777, reference.stat().st_mode & 0o777)
|
||||
|
||||
def test_open_parent_anchor_prevents_a_later_alias_redirect(self):
|
||||
parent = self.root / "stage"
|
||||
parent.mkdir()
|
||||
retained = self.root / "retained-stage"
|
||||
destination = parent / "Info.plist"
|
||||
original = POLICY.OwnedBuildRoot._parent
|
||||
with tempfile.TemporaryDirectory() as external:
|
||||
def swap_after_parent_open(root, path):
|
||||
descriptor, name = original(root, path)
|
||||
if Path(path) == destination:
|
||||
parent.rename(retained)
|
||||
parent.symlink_to(external, target_is_directory=True)
|
||||
return descriptor, name
|
||||
with mock.patch.object(POLICY.OwnedBuildRoot, "_parent", swap_after_parent_open):
|
||||
POLICY.write_plist(self.template, destination, VERSION, COMMIT)
|
||||
self.assertFalse((Path(external) / "Info.plist").exists())
|
||||
self.assertEqual(plistlib.loads((retained / "Info.plist").read_bytes())["TextureCraftVersion"], VERSION)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,182 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The Nightly signing and archive helpers, exercised on Linux with stand-in Apple tool output.
|
||||
|
||||
Nothing here signs, notarizes, unpacks or runs a payload: each helper takes the tool output (or a
|
||||
crafted archive) as an argument, which is why packaging/macos/nightly_sign_tests.py can run in the
|
||||
app's ordinary Linux CI.
|
||||
"""
|
||||
import os
|
||||
import stat
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
LIB = HERE / "nightly-lib.sh"
|
||||
APP = "TextureCraft Nightly.app"
|
||||
IDENTITY = "A" * 40
|
||||
TEAM = "DJ6XS33FX8"
|
||||
APP_CONFIG_ID = "ai.storyteller.texturecraft.nightly"
|
||||
|
||||
|
||||
|
||||
class VersionFromAsset(unittest.TestCase):
|
||||
def check(self, name):
|
||||
"""True when the helper accepts the asset name."""
|
||||
result = subprocess.run(
|
||||
["bash", "-c", '. "$LIB"; mac_nightly_version_from_asset "$1"', "bash", name],
|
||||
capture_output=True, text=True, env={"PATH": os.environ["PATH"], "LIB": str(LIB)},
|
||||
)
|
||||
return result.returncode == 0
|
||||
|
||||
def test_accepts_only_the_prepared_nightly_archive_name(self):
|
||||
version = "0.24.0-nightly.20261124.7.2.g" + "0123456789ab"
|
||||
self.assertTrue(self.check(f"texturecraft-{version}-macos-aarch64-nightly.zip"))
|
||||
for name in [
|
||||
f"texturecraft-{version}-macos-aarch64.zip",
|
||||
f"texturecraft-{version}-linux-x86_64-nightly.tar.gz",
|
||||
f"texturecraft-0.24.0-macos-aarch64-nightly.zip",
|
||||
f"texturecraft-{version.upper()}-macos-aarch64-nightly.zip",
|
||||
f"photocraft-{version}-macos-aarch64-nightly.zip",
|
||||
f"texturecraft-{version}-macos-x86_64-nightly.zip",
|
||||
f"texturecraft-{version}-macos-aarch64-nightly.zip.sig",
|
||||
]:
|
||||
self.assertFalse(self.check(name), name)
|
||||
|
||||
|
||||
class Keychain(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.directory.cleanup)
|
||||
self.work = Path(self.directory.name).resolve()
|
||||
self.keychain = self.work / "texturecraft-signing.keychain-db"
|
||||
self.keychain.write_bytes(b"stand-in keychain")
|
||||
|
||||
def ours(self, keychain, work=None):
|
||||
result = subprocess.run(
|
||||
["bash", "-c", '. "$LIB"; mac_nightly_keychain_is_ours "$1" "$2"', "bash", str(keychain), str(work or self.work)],
|
||||
capture_output=True, text=True, env={"PATH": os.environ["PATH"], "LIB": str(LIB)},
|
||||
)
|
||||
return result.returncode == 0
|
||||
|
||||
def test_only_this_runs_own_keychain_counts(self):
|
||||
self.assertTrue(self.ours(self.keychain))
|
||||
# import-cert.sh may put it in a private directory of its own under the run.
|
||||
nested = self.work / "private"
|
||||
nested.mkdir()
|
||||
self.assertFalse(self.ours(nested / "texturecraft-signing.keychain-db"), "a missing file is not ours")
|
||||
(nested / "texturecraft-signing.keychain-db").write_bytes(b"x")
|
||||
self.assertTrue(self.ours(nested / "texturecraft-signing.keychain-db"))
|
||||
self.assertFalse(self.ours(self.work / "other.keychain-db"))
|
||||
with tempfile.TemporaryDirectory() as outside:
|
||||
(Path(outside) / "texturecraft-signing.keychain-db").write_bytes(b"x")
|
||||
self.assertFalse(self.ours(Path(outside) / "texturecraft-signing.keychain-db"))
|
||||
alias = self.work / "texturecraft-signing.keychain-db-alias"
|
||||
alias.symlink_to(self.keychain)
|
||||
self.assertFalse(self.ours(alias))
|
||||
|
||||
|
||||
class Identity(unittest.TestCase):
|
||||
LINE = f' 1) {IDENTITY} "Developer ID Application: Learning Machines Inc ({TEAM})"'
|
||||
|
||||
def matcher(self, line, identity=IDENTITY, team=TEAM):
|
||||
result = subprocess.run(
|
||||
["bash", "-c", '. "$LIB"; mac_nightly_identity_is_team "$1" "$2" "$3"', "bash", line, identity, team],
|
||||
capture_output=True, text=True, env={"PATH": os.environ["PATH"], "LIB": str(LIB)},
|
||||
)
|
||||
return result.returncode == 0
|
||||
|
||||
def test_a_developer_id_of_the_team_and_nothing_else(self):
|
||||
self.assertTrue(self.matcher(self.LINE))
|
||||
self.assertFalse(self.matcher(self.LINE.replace("Developer ID Application", "Apple Development")))
|
||||
self.assertFalse(self.matcher(self.LINE.replace(TEAM, "ZZZZZZZZZZ")))
|
||||
self.assertFalse(self.matcher(self.LINE, identity="B" * 40))
|
||||
self.assertFalse(self.matcher(""))
|
||||
|
||||
|
||||
class Signature(unittest.TestCase):
|
||||
DETAILS = "\n".join([
|
||||
f"Identifier={APP_CONFIG_ID}",
|
||||
"Authority=Developer ID Application: Learning Machines Inc (DJ6XS33FX8)",
|
||||
"Authority=Developer ID Certification Authority",
|
||||
f"TeamIdentifier={TEAM}",
|
||||
"Timestamp=Nov 24, 2026 at 10:00:00",
|
||||
"CodeDirectory v=20500 size=1234 flags=0x10000(runtime) hashes=1+7 location=embedded",
|
||||
])
|
||||
|
||||
def check(self, details, team=TEAM):
|
||||
result = subprocess.run(
|
||||
["bash", "-c", '. "$LIB"; mac_nightly_check_signature "$1" "$2"', "bash", details, team],
|
||||
capture_output=True, text=True, env={"PATH": os.environ["PATH"], "LIB": str(LIB)},
|
||||
)
|
||||
return result.returncode == 0
|
||||
|
||||
def test_the_required_developer_id_signature(self):
|
||||
self.assertTrue(self.check(self.DETAILS))
|
||||
for missing in [
|
||||
"Timestamp=Nov 24, 2026 at 10:00:00",
|
||||
f"TeamIdentifier={TEAM}",
|
||||
"Authority=Developer ID Application: Learning Machines Inc (DJ6XS33FX8)",
|
||||
]:
|
||||
self.assertFalse(self.check(self.DETAILS.replace(missing, "")), missing)
|
||||
self.assertFalse(self.check(self.DETAILS.replace("flags=0x10000(runtime)", "flags=0x0(none)")))
|
||||
self.assertFalse(self.check(self.DETAILS, team="ZZZZZZZZZZ"))
|
||||
self.assertFalse(self.check(self.DETAILS.replace(APP_CONFIG_ID, "ai.storyteller.texturecraft")))
|
||||
|
||||
|
||||
class Assessment(unittest.TestCase):
|
||||
def check(self, text):
|
||||
result = subprocess.run(
|
||||
["bash", "-c", '. "$LIB"; mac_nightly_check_assessment "$1"', "bash", text],
|
||||
capture_output=True, text=True, env={"PATH": os.environ["PATH"], "LIB": str(LIB)},
|
||||
)
|
||||
return result.returncode == 0
|
||||
|
||||
def test_gatekeeper_must_report_a_notarized_developer_id(self):
|
||||
self.assertTrue(self.check(f"{APP}: accepted\nsource=Notarized Developer ID"))
|
||||
self.assertFalse(self.check(f"{APP}: accepted\nsource=Unnotarized Developer ID"))
|
||||
self.assertFalse(self.check(f"{APP}: rejected\nsource=Notarized Developer ID"))
|
||||
self.assertFalse(self.check(""))
|
||||
|
||||
|
||||
class ZipEntries(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.directory.cleanup)
|
||||
self.root = Path(self.directory.name)
|
||||
|
||||
def checked(self, entries):
|
||||
"""True when mac_nightly_check_zip_entries accepts the archive of (name, mode) entries."""
|
||||
archive = self.root / "test.zip"
|
||||
with zipfile.ZipFile(archive, "w") as z:
|
||||
for name, mode in entries:
|
||||
info = zipfile.ZipInfo(name)
|
||||
info.external_attr = (mode or stat.S_IFREG | 0o644) << 16 if mode else 0
|
||||
z.writestr(info, b"stand-in payload")
|
||||
result = subprocess.run(
|
||||
["bash", "-c", '. "$LIB"; mac_nightly_check_zip_entries "$1"', "bash", str(archive)],
|
||||
capture_output=True, text=True, env={"PATH": os.environ["PATH"], "LIB": str(LIB), "MAC_NIGHTLY_APP": APP},
|
||||
)
|
||||
return result.returncode == 0
|
||||
|
||||
def test_a_plain_bundle_is_accepted_and_anything_else_refused(self):
|
||||
good = [
|
||||
(f"{APP}/", stat.S_IFDIR | 0o755),
|
||||
(f"{APP}/Contents/Info.plist", stat.S_IFREG | 0o644),
|
||||
(f"{APP}/Contents/MacOS/TextureCraft", stat.S_IFREG | 0o755),
|
||||
]
|
||||
self.assertTrue(self.checked(good))
|
||||
for entry in [
|
||||
(f"{APP}/../escape", stat.S_IFREG | 0o644),
|
||||
("/absolute/path", stat.S_IFREG | 0o644),
|
||||
(f"{APP}/Contents/link", stat.S_IFLNK | 0o777),
|
||||
("Other.app/Contents/Info.plist", stat.S_IFREG | 0o644),
|
||||
(f"{APP}/Contents/with\\backslash", stat.S_IFREG | 0o644),
|
||||
]:
|
||||
self.assertFalse(self.checked([*good, entry]), entry[0])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Executable
+234
@@ -0,0 +1,234 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Synthetic app-owned archive/output tests; no native build or executable launch."""
|
||||
import gzip
|
||||
import importlib.util
|
||||
import os
|
||||
import runpy
|
||||
import sys
|
||||
from unittest import mock
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
SPEC = importlib.util.spec_from_file_location("photo_nightly_archive", HERE / "nightly-archive.py")
|
||||
ARCHIVE = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(ARCHIVE)
|
||||
|
||||
|
||||
class ArchivePolicy(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.scratch = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.scratch.cleanup)
|
||||
self.root = Path(self.scratch.name).resolve()
|
||||
previous = Path.cwd()
|
||||
os.chdir(self.root)
|
||||
self.addCleanup(os.chdir, previous)
|
||||
self.stage = self.root / "stage"
|
||||
self.stage.mkdir()
|
||||
self.output = self.root / "nightly.tar.gz"
|
||||
self.required = {"texturecraft", "texturecraft-bin", "texturecraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md"}
|
||||
for name in self.required:
|
||||
(self.stage / name).write_bytes(b"generated fixture: " + name.encode())
|
||||
(self.stage / "texturecraft").chmod(0o755)
|
||||
(self.stage / "texturecraft-bin").chmod(0o755)
|
||||
|
||||
def test_flat_regular_ustar_with_all_notices(self):
|
||||
(self.stage / "OFL-Font.txt").write_text("generated fixture license", encoding="utf-8")
|
||||
ARCHIVE.linux_archive(self.stage, self.output)
|
||||
with tarfile.open(self.output) as archive:
|
||||
self.assertEqual({m.name for m in archive}, self.required | {"OFL-Font.txt"})
|
||||
self.assertTrue(all(m.isfile() and not m.pax_headers for m in archive))
|
||||
self.assertEqual(archive.extractfile("texturecraft").read(), (self.stage / "texturecraft").read_bytes())
|
||||
# The launcher is what a user runs; the GUI beside it must be runnable too.
|
||||
modes = {member.name: member.mode for member in archive.getmembers()}
|
||||
for name in ("texturecraft", "texturecraft-bin"):
|
||||
self.assertEqual(modes[name] & 0o111, 0o111, f"{name} must be executable")
|
||||
with gzip.open(self.output, "rb") as stream:
|
||||
while (header := stream.read(512)) != bytes(512):
|
||||
self.assertEqual(len(header), 512)
|
||||
self.assertIn(header[156:157], {b"0", b"\0"})
|
||||
self.assertEqual(header[257:263], b"ustar\0")
|
||||
size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8)
|
||||
stream.read(((size + 511) // 512) * 512)
|
||||
|
||||
def test_each_required_member_is_required_before_output(self):
|
||||
for name in self.required:
|
||||
with self.subTest(name=name):
|
||||
content = (self.stage / name).read_bytes()
|
||||
(self.stage / name).unlink()
|
||||
with self.assertRaisesRegex(ValueError, "required"):
|
||||
ARCHIVE.linux_archive(self.stage, self.output)
|
||||
self.assertFalse(self.output.exists())
|
||||
(self.stage / name).write_bytes(content)
|
||||
|
||||
def test_unexpected_cli_portable_or_installer_member_refuses(self):
|
||||
for name in ["texturecraft-cli", "portable.txt", "texturecraft.desktop"]:
|
||||
with self.subTest(name=name):
|
||||
bad = self.stage / name
|
||||
bad.write_bytes(b"generated fixture")
|
||||
with self.assertRaisesRegex(ValueError, "unexpected"):
|
||||
ARCHIVE.linux_archive(self.stage, self.output)
|
||||
self.assertFalse(self.output.exists())
|
||||
bad.unlink()
|
||||
|
||||
def test_symlink_refuses_before_output(self):
|
||||
icon = self.stage / "texturecraft-nightly.png"
|
||||
icon.unlink()
|
||||
icon.symlink_to(self.stage / "README.md")
|
||||
with self.assertRaisesRegex(ValueError, "regular file|symlinks or aliases"):
|
||||
ARCHIVE.linux_archive(self.stage, self.output)
|
||||
self.assertFalse(self.output.exists())
|
||||
|
||||
def test_directory_refuses_before_output(self):
|
||||
icon = self.stage / "texturecraft-nightly.png"
|
||||
icon.unlink()
|
||||
icon.mkdir()
|
||||
with self.assertRaisesRegex(ValueError, "regular file"):
|
||||
ARCHIVE.linux_archive(self.stage, self.output)
|
||||
self.assertFalse(self.output.exists())
|
||||
|
||||
def test_long_notice_refuses_before_output(self):
|
||||
(self.stage / ("OFL-" + "x" * 100 + ".txt")).write_bytes(b"fixture")
|
||||
with self.assertRaisesRegex(ValueError, "short regular"):
|
||||
ARCHIVE.linux_archive(self.stage, self.output)
|
||||
self.assertFalse(self.output.exists())
|
||||
|
||||
def test_case_colliding_notices_refuse_before_output(self):
|
||||
for name in ["OFL-Font.txt", "OFL-font.txt"]:
|
||||
(self.stage / name).write_bytes(b"fixture")
|
||||
with self.assertRaisesRegex(ValueError, "case-colliding"):
|
||||
ARCHIVE.linux_archive(self.stage, self.output)
|
||||
self.assertFalse(self.output.exists())
|
||||
|
||||
def test_cli_dispatches_only_the_supported_archive_kind(self):
|
||||
helper = HERE / "nightly-archive.py"
|
||||
with mock.patch.object(sys, "argv", [str(helper), "linux", str(self.stage), str(self.output)]):
|
||||
runpy.run_path(str(helper), run_name="__main__")
|
||||
with tarfile.open(self.output) as archive:
|
||||
self.assertEqual({member.name for member in archive}, self.required)
|
||||
refused = self.root / "refused.tar.gz"
|
||||
for args in ([str(helper)], [str(helper), "unknown", str(self.stage), str(refused)]):
|
||||
with self.subTest(args=args), mock.patch.object(sys, "argv", args):
|
||||
with self.assertRaises(SystemExit):
|
||||
runpy.run_path(str(helper), run_name="__main__")
|
||||
self.assertFalse(refused.exists())
|
||||
|
||||
def test_existing_archive_is_unchanged(self):
|
||||
self.output.write_bytes(b"owned earlier artifact")
|
||||
with self.assertRaises(FileExistsError):
|
||||
ARCHIVE.linux_archive(self.stage, self.output)
|
||||
self.assertEqual(self.output.read_bytes(), b"owned earlier artifact")
|
||||
|
||||
|
||||
def test_archive_output_outside_build_root_refuses(self):
|
||||
with tempfile.TemporaryDirectory() as external:
|
||||
output = Path(external) / "nightly.tar.gz"
|
||||
with self.assertRaises(ValueError):
|
||||
ARCHIVE.linux_archive(self.stage, output)
|
||||
self.assertFalse(output.exists())
|
||||
|
||||
def test_archive_stage_outside_build_root_refuses(self):
|
||||
with tempfile.TemporaryDirectory() as external:
|
||||
stage = Path(external)
|
||||
for name in self.required:
|
||||
(stage / name).write_bytes(b"generated external fixture")
|
||||
with self.assertRaises(ValueError):
|
||||
ARCHIVE.linux_archive(stage, self.output)
|
||||
self.assertFalse(self.output.exists())
|
||||
|
||||
def test_archive_stage_alias_refuses(self):
|
||||
alias = self.root / "stage-alias"
|
||||
alias.symlink_to(self.stage, target_is_directory=True)
|
||||
with self.assertRaises(ValueError):
|
||||
ARCHIVE.linux_archive(alias, self.output)
|
||||
self.assertFalse(self.output.exists())
|
||||
|
||||
def test_archive_output_parent_alias_refuses(self):
|
||||
with tempfile.TemporaryDirectory() as external:
|
||||
alias = self.root / "output-alias"
|
||||
alias.symlink_to(external, target_is_directory=True)
|
||||
with self.assertRaises(ValueError):
|
||||
ARCHIVE.linux_archive(self.stage, alias / "nightly.tar.gz")
|
||||
self.assertFalse((Path(external) / "nightly.tar.gz").exists())
|
||||
|
||||
def test_archive_parent_traversal_refuses(self):
|
||||
with tempfile.TemporaryDirectory(dir=self.root.parent) as external:
|
||||
output = Path("..") / Path(external).name / "nightly.tar.gz"
|
||||
with self.assertRaises(ValueError):
|
||||
ARCHIVE.linux_archive(self.stage, output)
|
||||
self.assertFalse((Path(external) / "nightly.tar.gz").exists())
|
||||
|
||||
def test_nonflat_member_name_refuses(self):
|
||||
stage_root = os.path.realpath(self.stage)
|
||||
with open(self.stage / "README.md", "rb") as incoming:
|
||||
for bad in ("../escape", "/absolute", "nested/name", "x/../README.md", "", ".", ".."):
|
||||
with self.subTest(name=bad), self.assertRaises(ValueError):
|
||||
ARCHIVE.member_info(stage_root, bad, incoming)
|
||||
|
||||
def test_member_header_matches_what_gettarinfo_records(self):
|
||||
stage_root = os.path.realpath(self.stage)
|
||||
for name in sorted(self.required):
|
||||
with self.subTest(name=name), open(self.stage / name, "rb") as incoming:
|
||||
ours = ARCHIVE.member_info(stage_root, name, incoming)
|
||||
with tarfile.open(fileobj=__import__("io").BytesIO(), mode="w") as reference:
|
||||
theirs = reference.gettarinfo(fileobj=incoming, arcname=name)
|
||||
self.assertEqual(ours.get_info(), theirs.get_info())
|
||||
|
||||
def test_member_read_budget_refuses_before_output(self):
|
||||
(self.stage / "OFL-Large.txt").write_bytes(b"x" * 65)
|
||||
with mock.patch.object(ARCHIVE, "MAX_MEMBER_BYTES", 64, create=True):
|
||||
with self.assertRaises(ValueError):
|
||||
ARCHIVE.linux_archive(self.stage, self.output)
|
||||
self.assertFalse(self.output.exists())
|
||||
|
||||
|
||||
def test_member_growth_is_rechecked_before_copy_and_output_is_cleaned(self):
|
||||
growing = self.stage / "OFL-Growing.txt"
|
||||
growing.write_bytes(b"x" * 32)
|
||||
original = ARCHIVE.member_info
|
||||
|
||||
def grow_before_stat(stage_root, name, incoming):
|
||||
if name == growing.name:
|
||||
growing.write_bytes(b"x" * 65)
|
||||
return original(stage_root, name, incoming)
|
||||
|
||||
with mock.patch.object(ARCHIVE, "MAX_MEMBER_BYTES", 64), \
|
||||
mock.patch.object(ARCHIVE, "member_info", grow_before_stat):
|
||||
with self.assertRaises(ValueError):
|
||||
ARCHIVE.linux_archive(self.stage, self.output)
|
||||
self.assertFalse(self.output.exists())
|
||||
|
||||
|
||||
class ExclusiveOutput(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.scratch = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.scratch.cleanup)
|
||||
self.root = Path(self.scratch.name)
|
||||
self.source = self.root / "input archive"
|
||||
self.output = self.root / "final archive"
|
||||
self.source.write_bytes(b"generated archive fixture" * 1024)
|
||||
|
||||
def publish(self):
|
||||
return subprocess.run(["bash", "-c", 'set -euo pipefail; source "$1"; nightly_publish_archive "$2" "$3"', "test", str(HERE / "nightly-common.sh"), str(self.source), str(self.output)], capture_output=True, text=True, timeout=15)
|
||||
|
||||
def test_success_copies_exact_bytes(self):
|
||||
result = self.publish()
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(self.output.read_bytes(), self.source.read_bytes())
|
||||
|
||||
def test_existing_output_is_never_replaced(self):
|
||||
self.output.write_bytes(b"existing artifact")
|
||||
self.assertNotEqual(self.publish().returncode, 0)
|
||||
self.assertEqual(self.output.read_bytes(), b"existing artifact")
|
||||
|
||||
def test_missing_source_does_not_leave_a_fake_empty_artifact(self):
|
||||
self.source.unlink()
|
||||
self.assertNotEqual(self.publish().returncode, 0)
|
||||
self.assertFalse(self.output.exists())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Flat Linux archive policy, invoked from its private owned build cwd.
|
||||
|
||||
The stage and archive must both remain under that independently chosen root.
|
||||
No native build, platform signing, or malicious-same-UID sandbox is implied.
|
||||
"""
|
||||
import grp
|
||||
import gzip
|
||||
import os
|
||||
import pathlib
|
||||
import pwd
|
||||
import re
|
||||
import stat
|
||||
import sys
|
||||
import tarfile
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
from nightly_paths import OwnedBuildRoot
|
||||
|
||||
APP_DOCS = {"README.md", "LICENSE", "LICENSE-MIT", "LICENSE-APACHE", "COPYRIGHT", "NOTICE", "ATTRIBUTION.md"}
|
||||
MAX_MEMBER_BYTES = 512 * 1024 * 1024
|
||||
MAX_TOTAL_BYTES = 1024 * 1024 * 1024
|
||||
MAX_MEMBERS = 128
|
||||
|
||||
|
||||
def notice(name):
|
||||
return name in APP_DOCS or re.fullmatch(r"OFL-[A-Za-z0-9_.-]+\.txt", name) is not None
|
||||
|
||||
|
||||
def checked_entries(root, stage):
|
||||
entries = sorted(root.children(stage, MAX_MEMBERS), key=lambda item: item.name)
|
||||
folded = set()
|
||||
total = 0
|
||||
for entry in entries:
|
||||
name = entry.name
|
||||
if name not in {"texturecraft", "texturecraft-bin", "texturecraft-nightly.png"} and not notice(name):
|
||||
raise ValueError(f"unexpected nightly member: {name}")
|
||||
if len(name.encode("utf-8")) > 100:
|
||||
raise ValueError(f"nightly member must be a short regular file: {name}")
|
||||
with root.reader(entry, MAX_MEMBER_BYTES) as stream:
|
||||
total += os.fstat(stream.fileno()).st_size
|
||||
if total > MAX_TOTAL_BYTES:
|
||||
raise ValueError("nightly stage exceeds its read bound")
|
||||
if name.casefold() in folded:
|
||||
raise ValueError(f"case-colliding nightly member: {name}")
|
||||
folded.add(name.casefold())
|
||||
required = {"texturecraft", "texturecraft-bin", "texturecraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md"}
|
||||
if not required.issubset({item.name for item in entries}):
|
||||
raise ValueError("required GUI/icon/notices missing")
|
||||
return entries
|
||||
|
||||
|
||||
def member_info(stage_root, name, incoming):
|
||||
"""Header for one stage file, built from the file this run opened rather than from the archive.
|
||||
|
||||
Members are flat names that resolve directly inside the stage they came from.
|
||||
"""
|
||||
if os.path.isabs(name) or os.path.basename(name) != name or name in ("", ".", ".."):
|
||||
raise ValueError(f"nightly member name must be a flat file name: {name}")
|
||||
destination = os.path.realpath(os.path.join(stage_root, name))
|
||||
if not destination.startswith(stage_root + os.sep) or os.path.dirname(destination) != stage_root:
|
||||
raise ValueError(f"nightly member resolves outside its stage: {name}")
|
||||
status = os.fstat(incoming.fileno())
|
||||
if not stat.S_ISREG(status.st_mode):
|
||||
raise ValueError(f"nightly member must be a regular file: {name}")
|
||||
# The same fields TarFile.gettarinfo records for a regular file.
|
||||
info = tarfile.TarInfo(os.path.basename(destination))
|
||||
info.type = tarfile.REGTYPE
|
||||
info.mode = stat.S_IMODE(status.st_mode)
|
||||
info.uid, info.gid = status.st_uid, status.st_gid
|
||||
info.size = status.st_size
|
||||
info.mtime = status.st_mtime
|
||||
try:
|
||||
info.uname = pwd.getpwuid(status.st_uid).pw_name
|
||||
except KeyError:
|
||||
pass
|
||||
try:
|
||||
info.gname = grp.getgrgid(status.st_gid).gr_name
|
||||
except KeyError:
|
||||
pass
|
||||
return info
|
||||
|
||||
|
||||
def verify_headers(root, output):
|
||||
# Bounded ordinary headers, not a transparent PAX/GNU-normalizing reader.
|
||||
total = 0
|
||||
count = 0
|
||||
with root.reader(output, MAX_TOTAL_BYTES) as incoming, gzip.GzipFile(fileobj=incoming) as stream:
|
||||
while True:
|
||||
header = stream.read(512)
|
||||
if header == b"\0" * 512:
|
||||
break
|
||||
if len(header) != 512 or header[156:157] not in {b"0", b"\0"}:
|
||||
raise ValueError("non-ordinary TAR record was emitted")
|
||||
size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8)
|
||||
count += 1
|
||||
total += size
|
||||
if count > MAX_MEMBERS or size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES:
|
||||
raise ValueError("archive exceeds its bounded member budget")
|
||||
remaining = ((size + 511) // 512) * 512
|
||||
while remaining:
|
||||
chunk = stream.read(min(remaining, 1024 * 1024))
|
||||
if not chunk:
|
||||
raise ValueError("truncated TAR member")
|
||||
remaining -= len(chunk)
|
||||
|
||||
|
||||
def linux_archive(stage, output):
|
||||
with OwnedBuildRoot() as root:
|
||||
entries = checked_entries(root, stage)
|
||||
stage_root = os.path.realpath(os.path.join(root.directory, stage))
|
||||
total = 0
|
||||
with root.create(output) as outgoing:
|
||||
with tarfile.open(fileobj=outgoing, mode="w:gz", format=tarfile.USTAR_FORMAT) as archive:
|
||||
for entry in entries:
|
||||
with root.reader(entry, MAX_MEMBER_BYTES) as incoming:
|
||||
info = member_info(stage_root, entry.name, incoming)
|
||||
total += info.size
|
||||
if info.size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES:
|
||||
raise ValueError("nightly stage grew beyond its read bound")
|
||||
archive.addfile(info, incoming)
|
||||
outgoing.flush()
|
||||
os.fsync(outgoing.fileno())
|
||||
verify_headers(root, output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 4 or sys.argv[1] != "linux":
|
||||
raise SystemExit("usage: nightly-archive.py linux STAGE OUTPUT (from owned private build cwd)")
|
||||
linux_archive(pathlib.Path(sys.argv[2]), pathlib.Path(sys.argv[3]))
|
||||
Executable
+33
@@ -0,0 +1,33 @@
|
||||
#!/usr/bin/env bash
|
||||
# The Nightly checks that need no compiler, macOS or network: the synthetic suites (release
|
||||
# contracts, the macOS plist and signing helpers, the icons), the launcher tests, and `bash -n`
|
||||
# over every Nightly shell script. Run by .github/workflows/packaging-lint.yml.
|
||||
set -euo pipefail
|
||||
|
||||
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
ROOT="$(cd "$HERE/.." && pwd)"
|
||||
cd "$ROOT"
|
||||
|
||||
python3 packaging/nightly-tests.py
|
||||
bash packaging/linux/nightly-arch-tar-test.sh
|
||||
bash packaging/linux/nightly-launch-test.sh
|
||||
|
||||
for script in \
|
||||
packaging/nightly-common.sh \
|
||||
packaging/linux/nightly.sh \
|
||||
packaging/linux/nightly-launch.sh \
|
||||
packaging/linux/nightly-launch-test.sh \
|
||||
packaging/linux/nightly-arch-launch.sh \
|
||||
packaging/linux/nightly-arch-tar.sh \
|
||||
packaging/linux/nightly-arch-tar-test.sh \
|
||||
packaging/linux/package.sh \
|
||||
packaging/linux/flatpak-bundle.sh \
|
||||
packaging/linux/apprun-test.sh \
|
||||
packaging/macos/nightly.sh \
|
||||
packaging/macos/nightly-lib.sh \
|
||||
packaging/macos/nightly-sign.sh \
|
||||
packaging/macos/nightly-verify.sh; do
|
||||
bash -n "$script"
|
||||
done
|
||||
|
||||
echo "Nightly checks passed"
|
||||
@@ -0,0 +1,93 @@
|
||||
# shellcheck shell=bash
|
||||
# Shared setup for app-owned native nightly archives; stable packaging does not source this file.
|
||||
|
||||
nightly_die() { printf 'error: %s\n' "$*" >&2; exit 2; }
|
||||
|
||||
nightly_init() {
|
||||
local os="$1" arch="$2" target="$3" date_digits
|
||||
[[ "${TEXTURECRAFT_BUILD_CHANNEL:-}" == nightly-v1 ]] || nightly_die 'TEXTURECRAFT_BUILD_CHANNEL must be nightly-v1'
|
||||
[[ "${TEXTURECRAFT_VERSION:-}" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || nightly_die 'an exact prepared nightly version is required'
|
||||
[[ "${TEXTURECRAFT_BUILD_SHA:-}" =~ ^[0-9a-f]{40}$ ]] || nightly_die 'an exact source commit is required'
|
||||
[[ "${TEXTURECRAFT_VERSION##*.g}" == "${TEXTURECRAFT_BUILD_SHA:0:12}" ]] || nightly_die 'version/source commit mismatch'
|
||||
[[ "${TEXTURECRAFT_BUILD_DATE:-}" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || nightly_die 'the original run-created UTC date is required'
|
||||
date_digits="${TEXTURECRAFT_VERSION#*-nightly.}"
|
||||
date_digits="${date_digits%%.*}"
|
||||
[[ "${TEXTURECRAFT_BUILD_DATE//-/}" == "$date_digits" ]] || nightly_die 'version/original-run date mismatch'
|
||||
[[ "${CARGO_TARGET_DIR:-}" == /* && "$CARGO_TARGET_DIR" != / ]] || nightly_die 'an absolute owned CARGO_TARGET_DIR base is required'
|
||||
[[ "${DIST:-}" == /* && "$DIST" != / ]] || nightly_die 'an absolute DIST output directory is required'
|
||||
[[ "/$CARGO_TARGET_DIR/" != *'/../'* && "/$DIST/" != *'/../'* ]] || nightly_die 'output paths must not contain parent traversal'
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
[[ "$(git -C "$ROOT" rev-parse HEAD)" == "$TEXTURECRAFT_BUILD_SHA" ]] || nightly_die 'prepared source is not the checked-out commit'
|
||||
[[ -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'nightly packaging requires the frozen clean source'
|
||||
if [[ -n "${CRAFT_FONTS_DIR:-}" && ! -d "$CRAFT_FONTS_DIR/fonts" ]]; then
|
||||
nightly_die 'declared CRAFT_FONTS_DIR has no fonts directory'
|
||||
fi
|
||||
# env.sh retains the established notice copier. Required values above prohibit its stable fallbacks.
|
||||
# shellcheck source=./env.sh
|
||||
. "$ROOT/packaging/env.sh"
|
||||
export CARGO_TARGET_DIR="$CARGO_TARGET_DIR/nightly-v1/$os-$arch"
|
||||
NIGHTLY_RUST_TARGET="$target"
|
||||
mkdir -p "$CARGO_TARGET_DIR"
|
||||
NIGHTLY_WORK="$(mktemp -d "$CARGO_TARGET_DIR/nightly-package.XXXXXX")"
|
||||
trap 'rm -rf -- "$NIGHTLY_WORK"' EXIT
|
||||
}
|
||||
|
||||
# Compile only: macOS runs the version query after signing (packaging/macos/nightly-verify.sh).
|
||||
nightly_compile_gui() {
|
||||
# Signing material never reaches compilation (the Windows -CheckBuildEnvironment rule).
|
||||
nightly_refuse_signing_env
|
||||
(cd "$ROOT" && TEXTURECRAFT_OVERRIDE_VERSION="$VERSION" cargo build --release --locked -p texturecraft --target "$NIGHTLY_RUST_TARGET")
|
||||
NIGHTLY_GUI="$CARGO_TARGET_DIR/$NIGHTLY_RUST_TARGET/release/texturecraft"
|
||||
[[ -f "$NIGHTLY_GUI" && ! -L "$NIGHTLY_GUI" ]] || nightly_die 'the owned GUI build did not produce a regular executable'
|
||||
[[ "$(git -C "$ROOT" rev-parse HEAD)" == "$TEXTURECRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the build'
|
||||
}
|
||||
|
||||
nightly_build_gui() {
|
||||
nightly_compile_gui
|
||||
local actual
|
||||
actual="$("$NIGHTLY_GUI" --version)" || nightly_die 'side-effect-free nightly version verification failed'
|
||||
# Exactly what the flavor prints: the prepared version and its channel (build_flavor::version).
|
||||
[[ "$actual" == "TextureCraft $VERSION (nightly-v1)" ]] || nightly_die "the built binary reports '$actual', not TextureCraft $VERSION (nightly-v1)"
|
||||
[[ "$(git -C "$ROOT" rev-parse HEAD)" == "$TEXTURECRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the version query'
|
||||
}
|
||||
|
||||
# Signing material never reaches compilation (the Windows -CheckBuildEnvironment rule).
|
||||
nightly_refuse_signing_env() {
|
||||
local name
|
||||
# The signing names release.yml passes, for every platform, and import-cert.sh's outputs.
|
||||
for name in APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID \
|
||||
MACOS_SIGN_IDENTITY MACOS_KEYCHAIN WINDOWS_CERTIFICATE WINDOWS_CERTIFICATE_PASSWORD AZURE_TENANT_ID AZURE_CLIENT_ID \
|
||||
AZURE_CLIENT_SECRET AZURE_SIGNING_ENDPOINT AZURE_SIGNING_ACCOUNT AZURE_CERT_PROFILE LINUX_SIGNING_KEY; do
|
||||
[[ -z "${!name:-}" ]] || nightly_die "compilation must not receive signing configuration ($name); sign in the separate trusted step"
|
||||
done
|
||||
}
|
||||
|
||||
nightly_copy_notices() {
|
||||
local destination="$1" required
|
||||
for required in README.md LICENSE-MIT LICENSE-APACHE NOTICE ATTRIBUTION.md; do
|
||||
[[ -f "$ROOT/$required" && ! -L "$ROOT/$required" ]] || nightly_die "missing regular app notice: $required"
|
||||
done
|
||||
copy_docs "$destination"
|
||||
}
|
||||
|
||||
nightly_publish_archive() {
|
||||
# Exclusive creation: never replace an existing artifact, even if another writer raced the preflight.
|
||||
python3 -I - "$1" "$2" <<'PY'
|
||||
import os, shutil, sys
|
||||
source, destination = sys.argv[1:]
|
||||
created = False
|
||||
try:
|
||||
# Open the input first: a missing source must not leave an empty final artifact.
|
||||
with open(source, 'rb') as incoming:
|
||||
with open(destination, 'xb') as output:
|
||||
created = True
|
||||
shutil.copyfileobj(incoming, output, length=1024 * 1024)
|
||||
output.flush()
|
||||
os.fsync(output.fileno())
|
||||
except BaseException:
|
||||
if created:
|
||||
os.unlink(destination)
|
||||
raise
|
||||
PY
|
||||
printf 'Nightly artifact: %s\n' "$2"
|
||||
}
|
||||
Executable
+297
@@ -0,0 +1,297 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Derive TextureCraft's Nightly icons from the committed stable renders.
|
||||
|
||||
The Nightly icon is the same artwork on a deeper background — no badge, crescent or letter. Each
|
||||
pixel is fitted as a blend of the tile's background and one of the two engraved foregrounds (ink,
|
||||
paper); only the background's contribution is replaced, so the engraving and the alpha padding are
|
||||
untouched. Every frame comes from the committed stable master of its own size (the `.ico` and
|
||||
`.icns` frames, the hicolor PNGs and the 1024 master), never from an upscale.
|
||||
|
||||
packaging/nightly-icons.py # write the Nightly assets
|
||||
packaging/nightly-icons.py --check # fail if the committed Nightly assets differ
|
||||
|
||||
No third-party packages: zlib and struct only, as the build server has no Pillow or ImageMagick.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import sys
|
||||
import zlib
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
ICONS = ROOT / "assets" / "app-icon"
|
||||
STABLE_ID = "ai.storyteller.texturecraft"
|
||||
|
||||
# The palette the artwork is drawn in, read from the tile itself (the three colours it is made of).
|
||||
INK = (11, 11, 12)
|
||||
PAPER = (239, 233, 220)
|
||||
STABLE_BG = (194, 103, 43)
|
||||
NIGHTLY_BG = (100, 52, 24)
|
||||
|
||||
# How far a pixel may sit from the fitted blend before it is left alone (anti-aliased edges onto the
|
||||
# transparent margin, and the few pixels that shade the tile itself).
|
||||
RESIDUAL = 24
|
||||
PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
|
||||
|
||||
# Sizes the Nightly set carries (the 256 one is also the window and package icon). They live in
|
||||
# `assets/app-icon/nightly/`, not in `hicolor/`: Stable's Linux and FreeBSD packagers copy that
|
||||
# whole theme tree, so Nightly renders stored under it would ship in every Stable package.
|
||||
NIGHTLY_SIZES = (16, 24, 32, 48, 64, 128, 256, 512)
|
||||
|
||||
|
||||
def decode_png(data):
|
||||
"""(width, height, RGBA bytes) for an 8-bit RGB/RGBA PNG, filters included."""
|
||||
if data[:8] != PNG_MAGIC:
|
||||
raise ValueError("not a PNG")
|
||||
pos, idat, header = 8, [], None
|
||||
while pos < len(data):
|
||||
(length,) = struct.unpack(">I", data[pos:pos + 4])
|
||||
kind = data[pos + 4:pos + 8]
|
||||
body = data[pos + 8:pos + 8 + length]
|
||||
if kind == b"IHDR":
|
||||
header = struct.unpack(">IIBBBBB", body)
|
||||
elif kind == b"IDAT":
|
||||
idat.append(body)
|
||||
elif kind == b"IEND":
|
||||
break
|
||||
pos += 12 + length
|
||||
if header is None:
|
||||
raise ValueError("no IHDR")
|
||||
width, height, depth, color, _compression, _filter, interlace = header
|
||||
if depth != 8 or interlace != 0 or color not in (2, 6):
|
||||
raise ValueError(f"unsupported PNG (depth {depth}, color {color}, interlace {interlace})")
|
||||
channels = 3 if color == 2 else 4
|
||||
raw = zlib.decompress(b"".join(idat))
|
||||
stride = width * channels
|
||||
out = bytearray(width * height * 4)
|
||||
previous = bytearray(stride)
|
||||
position = 0
|
||||
for row in range(height):
|
||||
filter_type = raw[position]
|
||||
position += 1
|
||||
line = bytearray(raw[position:position + stride])
|
||||
position += stride
|
||||
if filter_type == 1:
|
||||
for i in range(channels, stride):
|
||||
line[i] = (line[i] + line[i - channels]) & 0xFF
|
||||
elif filter_type == 2:
|
||||
for i in range(stride):
|
||||
line[i] = (line[i] + previous[i]) & 0xFF
|
||||
elif filter_type == 3:
|
||||
for i in range(stride):
|
||||
left = line[i - channels] if i >= channels else 0
|
||||
line[i] = (line[i] + ((left + previous[i]) >> 1)) & 0xFF
|
||||
elif filter_type == 4:
|
||||
for i in range(stride):
|
||||
a = line[i - channels] if i >= channels else 0
|
||||
b = previous[i]
|
||||
c = previous[i - channels] if i >= channels else 0
|
||||
pa, pb, pc = abs(b - c), abs(a - c), abs(a + b - 2 * c)
|
||||
predictor = a if (pa <= pb and pa <= pc) else (b if pb <= pc else c)
|
||||
line[i] = (line[i] + predictor) & 0xFF
|
||||
elif filter_type != 0:
|
||||
raise ValueError(f"unknown PNG filter {filter_type}")
|
||||
if channels == 4:
|
||||
out[row * width * 4:(row + 1) * width * 4] = line
|
||||
else:
|
||||
for x in range(width):
|
||||
source = x * 3
|
||||
target = (row * width + x) * 4
|
||||
out[target:target + 3] = line[source:source + 3]
|
||||
out[target + 3] = 255
|
||||
previous = line
|
||||
return width, height, out
|
||||
|
||||
|
||||
def encode_png(width, height, rgba):
|
||||
raw = bytearray()
|
||||
stride = width * 4
|
||||
for row in range(height):
|
||||
raw.append(0)
|
||||
raw.extend(rgba[row * stride:(row + 1) * stride])
|
||||
|
||||
def chunk(kind, body):
|
||||
return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body) & 0xFFFFFFFF)
|
||||
|
||||
return (
|
||||
PNG_MAGIC
|
||||
+ chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0))
|
||||
+ chunk(b"IDAT", zlib.compress(bytes(raw), 9))
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
|
||||
|
||||
def solve(pixel):
|
||||
"""(ink, paper, background) weights for one pixel, clamped to the three-colour simplex.
|
||||
|
||||
The engraving is drawn as a mix of ink and paper over the tile, so a shaded grey is ink plus
|
||||
paper with no background at all; only the background share moves in a Nightly icon.
|
||||
"""
|
||||
rows = [[INK[c] - STABLE_BG[c] for c in range(3)], [PAPER[c] - STABLE_BG[c] for c in range(3)]]
|
||||
rhs = [pixel[c] - STABLE_BG[c] for c in range(3)]
|
||||
a11 = sum(v * v for v in rows[0])
|
||||
a12 = sum(rows[0][c] * rows[1][c] for c in range(3))
|
||||
a22 = sum(v * v for v in rows[1])
|
||||
b1 = sum(rows[0][c] * rhs[c] for c in range(3))
|
||||
b2 = sum(rows[1][c] * rhs[c] for c in range(3))
|
||||
determinant = a11 * a22 - a12 * a12
|
||||
if determinant == 0:
|
||||
return 0.0, 0.0, 1.0
|
||||
ink = (b1 * a22 - b2 * a12) / determinant
|
||||
paper = (b2 * a11 - b1 * a12) / determinant
|
||||
ink, paper = max(0.0, min(1.0, ink)), max(0.0, min(1.0, paper))
|
||||
if ink + paper > 1.0:
|
||||
total = ink + paper
|
||||
ink, paper = ink / total, paper / total
|
||||
return ink, paper, 1.0 - ink - paper
|
||||
|
||||
|
||||
def recolour(rgba):
|
||||
"""The same frame with only its background contribution moved to the Nightly colour."""
|
||||
out = bytearray(rgba)
|
||||
cache = {}
|
||||
for index in range(0, len(rgba), 4):
|
||||
if rgba[index + 3] == 0:
|
||||
continue
|
||||
pixel = (rgba[index], rgba[index + 1], rgba[index + 2])
|
||||
got = cache.get(pixel)
|
||||
if got is None:
|
||||
ink, paper, background = solve(pixel)
|
||||
fitted = tuple(ink * INK[c] + paper * PAPER[c] + background * STABLE_BG[c] for c in range(3))
|
||||
residual = sum(abs(pixel[c] - fitted[c]) for c in range(3))
|
||||
# A pixel the three-colour palette cannot explain is left exactly as it is.
|
||||
if residual <= RESIDUAL:
|
||||
got = bytes(min(255, max(0, round(ink * INK[c] + paper * PAPER[c] + background * NIGHTLY_BG[c]))) for c in range(3))
|
||||
else:
|
||||
got = bytes(pixel)
|
||||
cache[pixel] = got
|
||||
out[index:index + 3] = got
|
||||
return out
|
||||
|
||||
|
||||
def read_icon_frames(container):
|
||||
"""(kind, name, png_bytes) frames of an .ico or .icns file, in file order."""
|
||||
if container[:4] == b"icns":
|
||||
frames = []
|
||||
position = 8
|
||||
while position < len(container):
|
||||
kind = container[position:position + 4]
|
||||
(size,) = struct.unpack(">I", container[position + 4:position + 8])
|
||||
body = container[position + 8:position + size]
|
||||
if body[:8] != PNG_MAGIC:
|
||||
raise ValueError(f"{kind!r} is not a PNG frame; regenerate the stable .icns")
|
||||
frames.append(("icns", kind, body))
|
||||
position += size
|
||||
return frames
|
||||
reserved, kind, count = struct.unpack("<HHH", container[:6])
|
||||
if reserved != 0 or kind != 1:
|
||||
raise ValueError("not an .ico")
|
||||
frames = []
|
||||
for index in range(count):
|
||||
offset = 6 + index * 16
|
||||
width, height, _colors, _reserved, _planes, _bpp, size, start = struct.unpack("<BBBBHHII", container[offset:offset + 16])
|
||||
body = container[start:start + size]
|
||||
if body[:8] != PNG_MAGIC:
|
||||
raise ValueError("not a PNG .ico frame; regenerate the stable .ico")
|
||||
frames.append(("ico", (width or 256, height or 256), body))
|
||||
return frames
|
||||
|
||||
|
||||
def write_ico(frames):
|
||||
header = struct.pack("<HHH", 0, 1, len(frames))
|
||||
entries, payloads, offset = bytearray(), bytearray(), 6 + 16 * len(frames)
|
||||
for (width, height), png in frames:
|
||||
entries.extend(struct.pack("<BBBBHHII", width % 256, height % 256, 0, 0, 1, 32, len(png), offset))
|
||||
payloads.extend(png)
|
||||
offset += len(png)
|
||||
return header + bytes(entries) + bytes(payloads)
|
||||
|
||||
|
||||
def write_icns(frames):
|
||||
body = bytearray()
|
||||
for kind, png in frames:
|
||||
body.extend(kind + struct.pack(">I", len(png) + 8) + png)
|
||||
return b"icns" + struct.pack(">I", len(body) + 8) + bytes(body)
|
||||
|
||||
|
||||
def nightly_frames(container):
|
||||
frames = read_icon_frames(container)
|
||||
out = []
|
||||
for kind, name, png in frames:
|
||||
width, height, rgba = decode_png(png)
|
||||
out.append((kind, name, (width, height), encode_png(width, height, recolour(rgba))))
|
||||
return out
|
||||
|
||||
|
||||
def targets():
|
||||
"""Every Nightly asset the app and its packaging use, as (path, bytes)."""
|
||||
assets = []
|
||||
icon_frames = nightly_frames((ICONS / "texturecraft.icns").read_bytes())
|
||||
assets.append((ICONS / "texturecraft-nightly.icns", write_icns([(name, png) for _kind, name, _size, png in icon_frames])))
|
||||
ico_frames = nightly_frames((ICONS / "texturecraft.ico").read_bytes())
|
||||
assets.append((ICONS / "texturecraft-nightly.ico", write_ico([(size, png) for _kind, _name, size, png in ico_frames])))
|
||||
for size in NIGHTLY_SIZES:
|
||||
source = ICONS / "hicolor" / f"{size}x{size}" / "apps" / f"{STABLE_ID}.png"
|
||||
width, height, rgba = decode_png(source.read_bytes())
|
||||
assets.append((ICONS / "nightly" / f"{size}.png", encode_png(width, height, recolour(rgba))))
|
||||
width, height, rgba = decode_png((ICONS / "texturecraft-1024.png").read_bytes())
|
||||
assets.append((ICONS / "texturecraft-nightly-1024.png", encode_png(width, height, recolour(rgba))))
|
||||
# The window icon is the same 256 render the Nightly set carries.
|
||||
window = ICONS / "nightly" / "256.png"
|
||||
assets.append((ICONS / "texturecraft-nightly.png", next(data for path, data in assets if path == window)))
|
||||
return assets
|
||||
|
||||
|
||||
def provenance(assets):
|
||||
inputs = [ICONS / "texturecraft.icns", ICONS / "texturecraft.ico", ICONS / "texturecraft-1024.png"]
|
||||
inputs += [ICONS / "hicolor" / f"{size}x{size}" / "apps" / f"{STABLE_ID}.png" for size in NIGHTLY_SIZES]
|
||||
digest = lambda data: hashlib.sha256(data).hexdigest()
|
||||
return {
|
||||
"title": "TextureCraft nightly deep-background icons",
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"generator": "packaging/nightly-icons.py",
|
||||
"generator_sha256": digest(Path(__file__).read_bytes()),
|
||||
"inputs": [{"path": str(path.relative_to(ROOT)), "sha256": digest(path.read_bytes())} for path in inputs],
|
||||
"method": {
|
||||
"kind": "derivative of the project-owned stable renders; no badge, crescent or letter",
|
||||
"original_palette": {"ink": "#0b0b0c", "paper": "#efe9dc", "background": "#c2672b"},
|
||||
"nightly_background": "#643418",
|
||||
"transform": "Fit each pixel as the tile background plus one engraved foreground (ink or paper) and replace only the background contribution; keep alpha, padding and foreground detail. Each frame comes from the stable master of its own size: the .icns and .ico PNG frames are recoloured in place, and the per-size PNGs (in nightly/) and the 1024 master are recoloured from their own renders. No upscaling.",
|
||||
},
|
||||
"outputs": {str(path.relative_to(ROOT)): digest(data) for path, data in assets},
|
||||
"ico_frames": ["the stable .ico's own frames (16, 20, 24, 32, 40, 48, 64, 128, 256)"],
|
||||
"icns_slots": "the stable .icns's own PNG slots (icp4 through ic10)",
|
||||
"validation": "Byte comparison against the committed assets (packaging/nightly-archive-tests.py and the icon check in packaging/nightly-tests.py); native Explorer/Finder rendering is not exercised here. The per-size PNGs are kept out of hicolor/ because Stable's Linux and FreeBSD packages copy that theme tree whole.",
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--check", action="store_true", help="fail if the committed assets differ from these bytes")
|
||||
args = parser.parse_args()
|
||||
assets = targets()
|
||||
record = (json.dumps(provenance(assets), indent=2) + "\n").encode()
|
||||
if args.check:
|
||||
stale = [path for path, data in assets if not path.is_file() or path.read_bytes() != data]
|
||||
if not (ICONS / "nightly-provenance.json").is_file() or (ICONS / "nightly-provenance.json").read_bytes() != record:
|
||||
stale.append(ICONS / "nightly-provenance.json")
|
||||
if stale:
|
||||
for path in stale:
|
||||
print(f"stale: {path.relative_to(ROOT)}", file=sys.stderr)
|
||||
return 1
|
||||
print(f"{len(assets)} Nightly icon files match the generator")
|
||||
return 0
|
||||
for path, data in assets:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(data)
|
||||
print(f"wrote {path.relative_to(ROOT)} ({len(data)} bytes)")
|
||||
(ICONS / "nightly-provenance.json").write_bytes(record)
|
||||
print("wrote assets/app-icon/nightly-provenance.json")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Executable
+389
@@ -0,0 +1,389 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Local contract tests for TextureCraft nightly workflows and signing policy."""
|
||||
import copy
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json"
|
||||
|
||||
NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64")
|
||||
NIGHTLY_TRUST = {
|
||||
"windows-x86_64": ("publisher_subject",
|
||||
"CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"),
|
||||
"linux-x86_64": ("fingerprint", "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"),
|
||||
"macos-aarch64": ("apple_team_id", "DJ6XS33FX8"),
|
||||
}
|
||||
|
||||
# Mirrors the storytold release-managers team (id 19837241) minus echelon-robot.
|
||||
# Update by PR, in the caller and the policy, when the team changes.
|
||||
RELEASE_MANAGERS = ["bflatastic", "dylanmtaylor", "echelon", "FredApps", "skylartaylor"]
|
||||
|
||||
|
||||
def assert_nightly_serialization(source):
|
||||
"""Fail closed unless this app's plain root concurrency block retains its contract."""
|
||||
lines = source.splitlines()
|
||||
roots = [index for index, line in enumerate(lines) if line.startswith("concurrency:")]
|
||||
if len(roots) != 1 or lines[roots[0]] != "concurrency:":
|
||||
raise ValueError("one plain root concurrency block is required")
|
||||
values = {}
|
||||
for line in lines[roots[0] + 1:]:
|
||||
if not line.strip() or line.lstrip().startswith("#"):
|
||||
continue
|
||||
if not line[0].isspace():
|
||||
break
|
||||
row = re.fullmatch(r" (group|cancel-in-progress): ([^#]+?)(?: +#.*)?", line)
|
||||
if row is None or row[1] in values:
|
||||
raise ValueError("malformed or duplicate nightly concurrency entry")
|
||||
values[row[1]] = row[2].rstrip()
|
||||
if values != {"group": "texturecraft-nightly-release", "cancel-in-progress": "false"}:
|
||||
raise ValueError("nightly serialization must use its stable group and no cancellation")
|
||||
|
||||
|
||||
def job_conditions(jobs):
|
||||
"""Each job-level `if:` as (block indicator or None, the whole expression YAML would read)."""
|
||||
lines = jobs.splitlines()
|
||||
found = []
|
||||
for index, line in enumerate(lines):
|
||||
head = re.fullmatch(r" if:(?: (.*))?", line)
|
||||
if head is None:
|
||||
continue
|
||||
value = (head[1] or "").strip()
|
||||
continuation = []
|
||||
for follow in lines[index + 1:]:
|
||||
if follow.strip() and len(follow) - len(follow.lstrip(" ")) <= 4:
|
||||
break
|
||||
continuation.append(follow.strip())
|
||||
indicator = value if re.fullmatch(r"[>|][+-]?", value) else None
|
||||
parts = continuation if indicator else [value] + continuation
|
||||
found.append((indicator, " ".join(part for part in parts if part)))
|
||||
return found
|
||||
|
||||
|
||||
def producer_platforms(source):
|
||||
"""Read the one producer job's literal platform list."""
|
||||
rows = re.findall(r"(?m)^ platforms: (.*)$", source)
|
||||
if len(rows) != 1:
|
||||
raise ValueError("exactly one producer platform list is required")
|
||||
literal = re.fullmatch(r"'(\[[^']*\])'", rows[0])
|
||||
if literal is None:
|
||||
raise ValueError("the platform list must be one single-quoted literal")
|
||||
platforms = json.loads(literal[1])
|
||||
if not isinstance(platforms, list) or json.dumps(platforms, separators=(",", ":")) != literal[1]:
|
||||
raise ValueError("the platform list must be compact JSON")
|
||||
if len(set(platforms)) != len(platforms) or not set(platforms) <= set(NIGHTLY_PLATFORMS):
|
||||
raise ValueError("platforms must be distinct known nightly targets")
|
||||
if "windows-x86_64" not in platforms:
|
||||
raise ValueError("the Windows row stays in the producer")
|
||||
return platforms
|
||||
|
||||
|
||||
def reviewed_manual_actors(caller_source, policy):
|
||||
"""The one reviewed manual-actor list, identical in the producer caller and the policy."""
|
||||
rows = re.findall(r"(?m)^ manual-actors: '(\[[^']*\])'$", caller_source)
|
||||
if len(rows) != 1:
|
||||
raise ValueError("exactly one literal manual-actors list is required")
|
||||
caller = json.loads(rows[0])
|
||||
if caller != policy["manual_actors"]:
|
||||
raise ValueError("caller and policy must grant the same actors in the same order")
|
||||
if caller != RELEASE_MANAGERS:
|
||||
raise ValueError("manual actors must be exactly the reviewed release managers")
|
||||
if caller != sorted(caller, key=str.lower) or len({login.lower() for login in caller}) != len(caller):
|
||||
raise ValueError("manual actors must be distinct and sorted case-insensitively")
|
||||
if set(caller) & {login for login in policy["automatic_signer_actors"]}:
|
||||
raise ValueError("manual and automatic actors overlap")
|
||||
return caller
|
||||
|
||||
|
||||
def caller_pin(name):
|
||||
return re.findall(r"(?m)^ tooling-revision: ([0-9a-f]{40})$", (ROOT / ".github/workflows" / name).read_text())[0]
|
||||
|
||||
|
||||
class TrustedSourcePreparation(unittest.TestCase):
|
||||
def test_one_producer_and_one_signer_job_carry_every_platform(self):
|
||||
for name, job in (("nightly.yml", "unsigned"), ("nightly-sign.yml", "release")):
|
||||
jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1]
|
||||
with self.subTest(workflow=name):
|
||||
self.assertEqual(re.findall(r"(?m)^ ([^\s#][^:]*):", jobs), [job],
|
||||
"a platform is a list entry, not a separately activatable job")
|
||||
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
|
||||
self.assertNotRegex(signer, r"(?m)^\s*platforms?:", "the release policy, not the caller, admits platforms")
|
||||
|
||||
def test_malformed_or_narrowed_platform_lists_are_rejected(self):
|
||||
source = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
current = "platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"macos-aarch64\"]'"
|
||||
self.assertIn(current, source)
|
||||
for new in ("platforms: '[\"linux-x86_64\"]'",
|
||||
"platforms: '[\"linux-x86_64\",\"macos-aarch64\"]'",
|
||||
"platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"linux-x86_64\"]'",
|
||||
"platforms: '[\"windows-x86_64\",\"macos-x86_64\"]'",
|
||||
"platforms: '[\"windows-x86_64\",\"linux-arm64\"]'",
|
||||
"platforms: '[\"windows-x86_64\", \"linux-x86_64\"]'",
|
||||
"platforms: [\"windows-x86_64\",\"linux-x86_64\"]",
|
||||
"platforms: ${{ vars.NIGHTLY_PLATFORMS }}",
|
||||
"platforms: '{\"windows-x86_64\":1}'",
|
||||
current + "\n " + current):
|
||||
with self.subTest(change=new), self.assertRaises(ValueError):
|
||||
producer_platforms(source.replace(current, new))
|
||||
with self.assertRaises(ValueError):
|
||||
producer_platforms(source.replace(" " + current + "\n", ""))
|
||||
|
||||
def test_continuation_lines_of_any_scalar_form_reach_the_guard_checks(self):
|
||||
for name, workflow in (("nightly.yml", "nightly.yml"), ("nightly-sign.yml", "nightly-sign.yml")):
|
||||
source = (ROOT / ".github/workflows" / workflow).read_text()
|
||||
expected = NightlyEnabledCallers.GUARDS[name]
|
||||
guard = re.search(r"(?m)^ if: >-\n(?: [^\n]*\n)+", source)[0]
|
||||
for replacement in (guard + " || true\n", " if: " + expected + "\n || true\n"):
|
||||
jobs = source.replace(guard, replacement).split("\njobs:\n", 1)[1]
|
||||
with self.subTest(workflow=name, replacement=replacement[-30:]):
|
||||
(indicator, expression), = job_conditions(jobs)
|
||||
self.assertFalse(indicator == ">-" and " ".join(expression.split()) == expected)
|
||||
|
||||
def test_no_nightly_schedule_is_registered(self):
|
||||
for name, event in (("nightly.yml", "workflow_dispatch"),
|
||||
("nightly-sign.yml", "workflow_dispatch")):
|
||||
source = (ROOT / ".github/workflows" / name).read_text()
|
||||
events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0]
|
||||
triggers = [line for line in events.splitlines() if line.startswith(" ")
|
||||
and not line.startswith(" ") and line.strip() and not line.lstrip().startswith("#")]
|
||||
with self.subTest(workflow=name):
|
||||
self.assertEqual(triggers, [f" {event}:"], "schedule/activation needs explicit review")
|
||||
|
||||
def test_signer_serialization_contract_is_enforced(self):
|
||||
assert_nightly_serialization((ROOT / ".github/workflows/nightly-sign.yml").read_text())
|
||||
|
||||
def test_weakened_or_malformed_serialization_is_rejected(self):
|
||||
source = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
|
||||
for old, new in (
|
||||
("cancel-in-progress: false", "cancel-in-progress: false\n queue: max"),
|
||||
("cancel-in-progress: false", "cancel-in-progress: true"),
|
||||
("cancel-in-progress: false", "cancel-in-progress: ${{ github.event_name == 'push' }}"),
|
||||
("cancel-in-progress: false\n", ""),
|
||||
("group: texturecraft-nightly-release", "group: ${{ github.run_id }}"),
|
||||
("group: texturecraft-nightly-release", "group: release-${{ github.ref }}"),
|
||||
("concurrency:\n", "concurrency: ${{ github.run_id }}\n"),
|
||||
("concurrency:\n", " concurrency:\n"),
|
||||
):
|
||||
with self.subTest(change=new), self.assertRaises(ValueError):
|
||||
assert_nightly_serialization(source.replace(old, new))
|
||||
|
||||
def test_no_cache_actions_or_cache_setup_options_in_app_trusted_closure(self):
|
||||
for name in ("nightly.yml", "nightly-sign.yml"):
|
||||
source = (ROOT / ".github/workflows" / name).read_text()
|
||||
executable = "\n".join(line for line in source.splitlines()
|
||||
if not line.lstrip().startswith("#"))
|
||||
with self.subTest(workflow=name):
|
||||
self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache")
|
||||
self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:")
|
||||
self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):")
|
||||
self.assertNotIn("secrets.", executable)
|
||||
|
||||
|
||||
class NightlyTrustAnchors(unittest.TestCase):
|
||||
"""The public stable identities each platform's signed nightly must carry."""
|
||||
|
||||
def setUp(self):
|
||||
self.policy = json.loads(INSTALLED_POLICY.read_text())
|
||||
|
||||
def test_each_platform_row_names_its_fixed_artifact_kind_and_stable_identity(self):
|
||||
self.assertEqual(set(self.policy["platforms"]), set(NIGHTLY_TRUST))
|
||||
for platform, (field, value) in NIGHTLY_TRUST.items():
|
||||
row = self.policy["platforms"][platform]
|
||||
with self.subTest(platform=platform):
|
||||
self.assertEqual(row["unsigned_artifact_name"], f"nightly-unsigned-{platform}",
|
||||
"the artifact kind is fixed by platform, never a caller pattern")
|
||||
self.assertEqual(row["trust"], {field: value}, "trust must be stable's public identity")
|
||||
|
||||
def test_trust_values_have_the_shapes_the_shared_signer_accepts(self):
|
||||
rows = self.policy["platforms"]
|
||||
self.assertRegex(rows["macos-aarch64"]["trust"]["apple_team_id"], r"^[A-Z0-9]{10}$")
|
||||
self.assertRegex(rows["linux-x86_64"]["trust"]["fingerprint"], r"^[0-9A-F]{40}$")
|
||||
subject = rows["windows-x86_64"]["trust"]["publisher_subject"]
|
||||
self.assertTrue(0 < len(subject) <= 1024 and not set(subject) & {"\r", "\n", "\0"})
|
||||
|
||||
def test_both_callers_use_one_shared_pin_in_uses_and_tooling_revision(self):
|
||||
pins = set()
|
||||
for name, callee in (("nightly.yml", "nightly-unsigned.yml"), ("nightly-sign.yml", "nightly-release.yml")):
|
||||
source = (ROOT / ".github/workflows" / name).read_text()
|
||||
uses = re.findall(r"(?m)^ uses: storytold/craft-common-actions/\.github/workflows/"
|
||||
+ re.escape(callee) + r"@(\S+)$", source)
|
||||
tooling = re.findall(r"(?m)^ tooling-revision: (\S+)$", source)
|
||||
with self.subTest(workflow=name):
|
||||
self.assertEqual(len(uses), 1)
|
||||
self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match")
|
||||
pins.update(uses)
|
||||
self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit")
|
||||
self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder")
|
||||
|
||||
|
||||
class NightlyEnabledCallers(unittest.TestCase):
|
||||
"""Producer and signer run only in their exact context, for the reviewed manual actor."""
|
||||
|
||||
GUARDS = {
|
||||
"nightly.yml": "github.repository == 'storytold/texturecraft' && github.ref == 'refs/heads/main' && "
|
||||
"github.ref_type == 'branch' && (github.event_name == 'schedule' || "
|
||||
"github.event_name == 'workflow_dispatch')",
|
||||
"nightly-sign.yml": "github.repository == 'storytold/texturecraft' && github.event_name == 'workflow_dispatch' && "
|
||||
"github.ref == 'refs/heads/release' && github.ref_type == 'branch'",
|
||||
}
|
||||
|
||||
def test_enabled_jobs_keep_exact_context_guards(self):
|
||||
for name, expected in self.GUARDS.items():
|
||||
jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1]
|
||||
guards = job_conditions(jobs)
|
||||
with self.subTest(workflow=name):
|
||||
self.assertEqual(len(guards), 1)
|
||||
indicator, expression = guards[0]
|
||||
self.assertEqual(indicator, ">-")
|
||||
self.assertEqual(" ".join(expression.split()), expected, "guards may only change with review")
|
||||
|
||||
def test_manual_actors_are_the_release_managers_in_caller_and_policy(self):
|
||||
source = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
policy = json.loads(INSTALLED_POLICY.read_text())
|
||||
self.assertEqual(reviewed_manual_actors(source, policy), RELEASE_MANAGERS)
|
||||
self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule")
|
||||
|
||||
def test_an_actor_outside_the_release_managers_is_refused(self):
|
||||
source = (ROOT / ".github/workflows/nightly.yml").read_text()
|
||||
policy = json.loads(INSTALLED_POLICY.read_text())
|
||||
caller = json.dumps(RELEASE_MANAGERS, separators=(",", ":"))
|
||||
widened = sorted(RELEASE_MANAGERS + ["echelon-robot"], key=str.lower)
|
||||
for change in ("caller", "policy", "both", "order", "case"):
|
||||
mutated_source, mutated_policy = source, copy.deepcopy(policy)
|
||||
if change in ("caller", "both"):
|
||||
mutated_source = source.replace(caller, json.dumps(widened, separators=(",", ":")))
|
||||
if change in ("policy", "both"):
|
||||
mutated_policy["manual_actors"] = widened
|
||||
if change == "order":
|
||||
mutated_policy["manual_actors"] = list(reversed(RELEASE_MANAGERS))
|
||||
if change == "case":
|
||||
mutated_policy["manual_actors"] = [login.lower() for login in RELEASE_MANAGERS]
|
||||
with self.subTest(change=change), self.assertRaises(ValueError):
|
||||
reviewed_manual_actors(mutated_source, mutated_policy)
|
||||
|
||||
|
||||
def push_block(source):
|
||||
"""The whole `push:` mapping, blank lines and nested keys included.
|
||||
|
||||
A blank line does not end a YAML mapping, so the block is delimited by indentation rather than
|
||||
by contiguous non-empty lines; a path filter after a blank line stays visible to the check.
|
||||
"""
|
||||
lines = source.splitlines()
|
||||
for index, line in enumerate(lines):
|
||||
if re.fullmatch(r" push:.*", line):
|
||||
block = []
|
||||
for follow in lines[index + 1:]:
|
||||
if follow.strip() and not follow.startswith(" "):
|
||||
break
|
||||
block.append(follow)
|
||||
return "\n".join(block)
|
||||
return None
|
||||
|
||||
|
||||
class NightlyInstalledPolicy(unittest.TestCase):
|
||||
"""The installed v3 policy matches the callers, the repository and its documented sources."""
|
||||
|
||||
def setUp(self):
|
||||
self.assertFalse(INSTALLED_POLICY.is_symlink())
|
||||
self.policy = json.loads(INSTALLED_POLICY.read_text())
|
||||
|
||||
def test_exact_v3_fields_and_repository_identity(self):
|
||||
expected = {"schema", "repository", "repository_id", "producer_workflow_id",
|
||||
"producer_workflow_path", "producer_tooling_revision", "producer_workflow_ref",
|
||||
"signer_workflow_path", "signer_tooling_revision", "release_branch", "manual_actors",
|
||||
"automatic_signer_actors", "max_age_seconds", "candidate_policy",
|
||||
"max_artifact_bytes", "platforms"}
|
||||
self.assertEqual(set(self.policy), expected)
|
||||
self.assertEqual(self.policy["schema"], "craft-nightly-release-policy/v3")
|
||||
self.assertEqual(self.policy["repository"], "storytold/texturecraft")
|
||||
self.assertEqual(self.policy["release_branch"], "release")
|
||||
self.assertIs(type(self.policy["repository_id"]), int)
|
||||
self.assertGreater(self.policy["repository_id"], 0)
|
||||
# producer_workflow_id is null until nightly.yml is registered on main; once set, must be a positive int.
|
||||
prod_id = self.policy["producer_workflow_id"]
|
||||
if prod_id is not None:
|
||||
self.assertIs(type(prod_id), int)
|
||||
self.assertGreater(prod_id, 0)
|
||||
self.assertNotEqual(prod_id,
|
||||
self.policy["candidate_policy"]["required_workflows"][0]["workflow_id"],
|
||||
"the producer is not its own quality workflow")
|
||||
|
||||
def test_paths_and_tooling_match_the_callers(self):
|
||||
pin = caller_pin("nightly.yml")
|
||||
self.assertEqual(caller_pin("nightly-sign.yml"), pin)
|
||||
self.assertEqual(self.policy["producer_workflow_path"], ".github/workflows/nightly.yml")
|
||||
self.assertEqual(self.policy["signer_workflow_path"], ".github/workflows/nightly-sign.yml")
|
||||
self.assertEqual(self.policy["producer_tooling_revision"], pin)
|
||||
self.assertEqual(self.policy["signer_tooling_revision"], pin)
|
||||
self.assertEqual(self.policy["producer_workflow_ref"],
|
||||
"storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@" + pin)
|
||||
|
||||
def test_platforms_equal_the_producer(self):
|
||||
built = producer_platforms((ROOT / ".github/workflows/nightly.yml").read_text())
|
||||
self.assertEqual(built, list(NIGHTLY_PLATFORMS))
|
||||
self.assertEqual(set(self.policy["platforms"]), set(built))
|
||||
|
||||
def test_bounds(self):
|
||||
self.assertIs(type(self.policy["max_age_seconds"]), int)
|
||||
self.assertTrue(0 < self.policy["max_age_seconds"] <= 604800)
|
||||
self.assertIs(type(self.policy["max_artifact_bytes"]), int)
|
||||
self.assertTrue(0 < self.policy["max_artifact_bytes"] <= 16 * 1024 ** 3)
|
||||
|
||||
def test_candidate_workflows_run_on_every_main_push(self):
|
||||
candidate = self.policy["candidate_policy"]
|
||||
self.assertEqual(set(candidate), {"schema", "epoch", "repository", "branch", "required_workflows", "sonar"})
|
||||
self.assertEqual(candidate["schema"], "craft-nightly-candidate-policy/v3")
|
||||
self.assertEqual((candidate["repository"], candidate["branch"]), ("storytold/texturecraft", "main"))
|
||||
self.assertTrue(isinstance(candidate["epoch"], str) and 0 < len(candidate["epoch"]) <= 128)
|
||||
rows = candidate["required_workflows"]
|
||||
self.assertTrue(rows)
|
||||
for row in rows:
|
||||
with self.subTest(workflow=row["workflow_path"]):
|
||||
self.assertEqual(set(row), {"workflow_id", "workflow_path", "jobs"})
|
||||
self.assertIs(type(row["workflow_id"]), int)
|
||||
self.assertNotEqual(row["workflow_path"], self.policy["producer_workflow_path"])
|
||||
source = (ROOT / row["workflow_path"]).read_text()
|
||||
push = push_block(source)
|
||||
self.assertIsNotNone(push, "a required workflow must run on main pushes")
|
||||
self.assertIn("branches: [main]", push)
|
||||
self.assertNotRegex(push, r"(?m)^\s+paths(?:-ignore)?:", "a path filter would leave candidates without a run")
|
||||
names = [job["name"] for job in row["jobs"]]
|
||||
self.assertEqual(len(names), len(set(names)))
|
||||
for job in row["jobs"]:
|
||||
self.assertEqual(set(job), {"name", "app_id", "applicability"})
|
||||
self.assertEqual((job["app_id"], job["applicability"]), (15368, "required"))
|
||||
|
||||
def test_a_path_filter_after_a_blank_line_is_still_rejected(self):
|
||||
workflow = "on:\n push:\n branches: [main]\n\n paths: ['src/**']\n workflow_dispatch: {}\n"
|
||||
block = push_block(workflow)
|
||||
self.assertIsNotNone(block)
|
||||
self.assertIn("branches: [main]", block)
|
||||
self.assertRegex(block, r"(?m)^\s+paths(?:-ignore)?:")
|
||||
for ignored in ("paths: ['src/**']", "paths-ignore: ['docs/**']"):
|
||||
with self.subTest(ignored=ignored):
|
||||
variant = workflow.replace(ignored.split(":")[0] + ": ['src/**']", ignored)
|
||||
self.assertRegex(push_block(variant), r"(?m)^\s+paths(?:-ignore)?:",
|
||||
"a quoted or unquoted filter must not hide behind a blank line")
|
||||
|
||||
def test_sonar_identity_and_reviewed_scope(self):
|
||||
sonar = self.policy["candidate_policy"]["sonar"]
|
||||
self.assertEqual(sonar["organization"], "storytold")
|
||||
self.assertEqual(sonar["project"], "storytold_texturecraft")
|
||||
self.assertEqual((sonar["app_id"], sonar["check_name"]), (12526, "SonarCloud Code Analysis"))
|
||||
self.assertEqual(sonar["details_url"], "https://sonarcloud.io/dashboard?id=" + sonar["project"] + "&branch=main")
|
||||
metrics = [c["metric"] for c in sonar["accepted_conditions"] + sonar["required_conditions"]]
|
||||
self.assertEqual(len(metrics), len(set(metrics)))
|
||||
keys = [item["key"] for item in sonar["debt"]]
|
||||
self.assertEqual(len(keys), len(set(keys)))
|
||||
for item in sonar["debt"]:
|
||||
with self.subTest(issue=item["key"]):
|
||||
self.assertEqual(set(item), {"key", "rule", "component", "type", "severity", "hash"})
|
||||
self.assertTrue(item["component"].startswith(sonar["project"] + ":"))
|
||||
self.assertIn(item["type"], sonar["issue_types"])
|
||||
self.assertRegex(item["hash"], r"^[0-9a-f]{32}$")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
Executable
+46
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the synthetic Nightly packaging suites together; no app build, signing or network.
|
||||
|
||||
Suites that a checkout does not carry are skipped with a note: the Linux archive suite belongs to
|
||||
whoever owns `nightly-archive.py`, and this branch does not add one.
|
||||
"""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
|
||||
def load(here, name, relative, suite):
|
||||
path = here / relative
|
||||
if not path.is_file():
|
||||
print(f"skip: {relative} is not in this checkout", file=sys.stderr)
|
||||
return
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(module))
|
||||
|
||||
|
||||
def icons_match(here) -> bool:
|
||||
"""The committed Nightly icons must be exactly what the generator derives from the masters."""
|
||||
import subprocess
|
||||
result = subprocess.run([sys.executable, str(here / "nightly-icons.py"), "--check"], capture_output=True, text=True)
|
||||
print(result.stdout.strip(), file=sys.stderr)
|
||||
if result.returncode != 0:
|
||||
print(result.stderr.strip(), file=sys.stderr)
|
||||
return result.returncode == 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
here = Path(__file__).resolve().parent
|
||||
suite = unittest.TestSuite()
|
||||
load(here, "texturecraft_archive_suite", "nightly-archive-tests.py", suite)
|
||||
load(here, "texturecraft_plist_suite", "macos/nightly_plist_tests.py", suite)
|
||||
load(here, "texturecraft_release_dispatch_suite", "nightly-release-tests.py", suite)
|
||||
load(here, "texturecraft_mac_sign_suite", "macos/nightly_sign_tests.py", suite)
|
||||
passed = unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful()
|
||||
return 0 if passed and icons_match(here) else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -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,95 @@
|
||||
param([Parameter(Mandatory=$true)][string] $FixtureRoot)
|
||||
. (Join-Path $PSScriptRoot 'nightly.ps1') -FunctionsOnly
|
||||
function Assert([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } }
|
||||
$spec = Get-NightlyArchiveSpec '0.23.1-nightly.20261120.17.1.gabcdef012345' 'x64'
|
||||
Assert ($spec.Archive -eq 'texturecraft-0.23.1-nightly.20261120.17.1.gabcdef012345-windows-x86_64-nightly.zip') 'wrong nightly artifact name'
|
||||
Assert ($spec.Executables.Count -eq 1 -and $spec.Executables[0] -eq 'texturecraft.exe') 'nightly must not ship the unqualified CLI'
|
||||
Assert ($spec.AppId -eq 'ai.storyteller.texturecraft.nightly-v1') 'nightly identity is not distinct'
|
||||
foreach ($arch in @('x86', 'arm64')) {
|
||||
$refused = $false
|
||||
try { Get-NightlyArchiveSpec '0.23.1' $arch | Out-Null } catch { $refused = $true }
|
||||
Assert $refused 'unsupported target was accepted'
|
||||
}
|
||||
foreach ($bad in @('', '0.23.1', '../other', '0.23.1/elsewhere')) {
|
||||
$refused = $false
|
||||
try { Get-NightlyArchiveSpec $bad 'x64' | Out-Null } catch { $refused = $true }
|
||||
Assert $refused 'unsafe artifact version was accepted'
|
||||
}
|
||||
Assert-NightlyFlavor 'TextureCraft Nightly' 'TextureCraft 0.23.1-nightly.20261120.17.1.gabcdef012345 (nightly-v1)' '0.23.1-nightly.20261120.17.1.gabcdef012345'
|
||||
foreach ($pair in @(@('TextureCraft', 'TextureCraft 0.23.1 (nightly-v1)'), @('TextureCraft Nightly', 'TextureCraft 0.23.1'))) {
|
||||
$refused = $false
|
||||
try { Assert-NightlyFlavor $pair[0] $pair[1] '0.23.1-nightly.20261120.17.1.gabcdef012345' } catch { $refused = $true }
|
||||
Assert $refused 'stable or mismatched build flavor was accepted'
|
||||
}
|
||||
$sha = 'abcdef0123456789abcdef0123456789abcdef01'
|
||||
$good = '0.23.1-nightly.20261120.17.1.gabcdef012345'
|
||||
Assert-NightlySource $good $sha '2026-11-20' $sha ''
|
||||
$cases = @(
|
||||
@('missing commit', $good, '', '2026-11-20', $sha, ''),
|
||||
@('short commit', $good, 'abcdef012345', '2026-11-20', $sha, ''),
|
||||
@('uppercase commit', $good, $sha.ToUpper(), '2026-11-20', $sha.ToUpper(), ''),
|
||||
@('version names another commit', '0.23.1-nightly.20261120.17.1.g000000000000', $sha, '2026-11-20', $sha, ''),
|
||||
@('missing date', $good, $sha, '', $sha, ''),
|
||||
@('date differs from version', $good, $sha, '2026-11-21', $sha, ''),
|
||||
@('other commit checked out', $good, $sha, '2026-11-20', ('0' * 40), ''),
|
||||
@('dirty tree', $good, $sha, '2026-11-20', $sha, ' M apps/texturecraft/src/main.rs')
|
||||
)
|
||||
foreach ($case in $cases) {
|
||||
$refused = $false
|
||||
try { Assert-NightlySource $case[1] $case[2] $case[3] $case[4] $case[5] } catch { $refused = $true }
|
||||
Assert $refused "source identity accepted: $($case[0])"
|
||||
}
|
||||
Write-Output 'nightly packaging spec, target/version refusal, source identity and flavor-binding tests passed'
|
||||
|
||||
# Exercise the SAME production notice copier with the real repository layout, then inspect a ZIP.
|
||||
if (-not $FixtureRoot -or -not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'supply an owned absolute -FixtureRoot for the notices/ZIP regression' }
|
||||
$testRoot = Join-Path $FixtureRoot ("nightly-notices-" + [Guid]::NewGuid().ToString('N'))
|
||||
try {
|
||||
$repo = Join-Path $testRoot 'app'
|
||||
$fontRepo = Join-Path $testRoot 'craft-fonts'
|
||||
$family = Join-Path $fontRepo 'fonts\ExampleFamily'
|
||||
$stage = Join-Path $testRoot 'stage'
|
||||
New-Item -ItemType Directory -Force -Path $repo, $family, $stage | Out-Null
|
||||
$rootNames = @('README.md', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md')
|
||||
foreach ($name in $rootNames) { Set-Content -LiteralPath (Join-Path $repo $name) -Value "root-notice-$name" }
|
||||
Set-Content -LiteralPath (Join-Path $family 'OFL.txt') -Value 'font-notice-example'
|
||||
Copy-NightlyNotices $repo $fontRepo $stage
|
||||
foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) {
|
||||
Assert (Test-Path -LiteralPath (Join-Path $stage $name)) "missing staged notice $name"
|
||||
}
|
||||
$zip = Join-Path $testRoot 'notices.zip'
|
||||
Compress-Archive -Path (Join-Path $stage '*') -DestinationPath $zip
|
||||
$archive = [IO.Compression.ZipFile]::OpenRead($zip)
|
||||
try {
|
||||
$names = @($archive.Entries | ForEach-Object { $_.FullName })
|
||||
foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { Assert ($name -in $names) "missing archived notice $name" }
|
||||
foreach ($forbidden in @('portable.txt', 'texturecraft-cli.exe')) { Assert ($forbidden -notin $names) "unexpected payload $forbidden" }
|
||||
$entry = $archive.GetEntry('OFL-ExampleFamily.txt')
|
||||
$reader = [IO.StreamReader]::new($entry.Open())
|
||||
try { Assert ($reader.ReadToEnd().Contains('font-notice-example')) 'wrong font license bytes in ZIP' } finally { $reader.Dispose() }
|
||||
} finally { $archive.Dispose() }
|
||||
} finally {
|
||||
if (Test-Path -LiteralPath $testRoot) { Remove-Item -LiteralPath $testRoot -Recurse -Force }
|
||||
}
|
||||
Write-Output 'nightly mock-repository root and font notices are present in stage and ZIP'
|
||||
|
||||
# The source state comes from git itself: the checked-out commit, then a dirty tree.
|
||||
$gitRoot = Join-Path $FixtureRoot ("nightly-source-" + [Guid]::NewGuid().ToString('N'))
|
||||
try {
|
||||
New-Item -ItemType Directory -Force -Path $gitRoot | Out-Null
|
||||
git -C $gitRoot init -q; git -C $gitRoot -c user.name=fixture -c user.email=fixture@invalid commit -q --allow-empty -m fixture
|
||||
if ($LASTEXITCODE -ne 0) { throw 'cannot create the git fixture' }
|
||||
$head = (git -C $gitRoot rev-parse HEAD).Trim()
|
||||
$state = Get-NightlySourceState $gitRoot
|
||||
Assert ($state.Head -ceq $head -and -not $state.Status) 'clean checkout not reported as clean at HEAD'
|
||||
$version = '0.23.1-nightly.20261120.17.1.g' + $head.Substring(0, 12)
|
||||
Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status
|
||||
Set-Content -LiteralPath (Join-Path $gitRoot 'untracked.txt') -Value 'dirty'
|
||||
$state = Get-NightlySourceState $gitRoot
|
||||
$refused = $false
|
||||
try { Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status } catch { $refused = $true }
|
||||
Assert $refused 'a dirty checkout was accepted'
|
||||
} finally {
|
||||
if (Test-Path -LiteralPath $gitRoot) { Remove-Item -LiteralPath $gitRoot -Recurse -Force }
|
||||
}
|
||||
Write-Output 'nightly source state is read from git and a dirty checkout is refused'
|
||||
@@ -0,0 +1,104 @@
|
||||
param(
|
||||
[Parameter(Mandatory=$true)][string] $FixtureRoot,
|
||||
[string] $PackagingRoot = $PSScriptRoot,
|
||||
[switch] $PhaseGuardOnly
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
. (Join-Path $PackagingRoot 'nightly.ps1') -FunctionsOnly
|
||||
$sign = Join-Path $PackagingRoot 'sign.ps1'
|
||||
$names = @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_TENANT_ID','AZURE_CLIENT_ID','AZURE_CLIENT_SECRET','AZURE_SIGNING_ENDPOINT','AZURE_SIGNING_ACCOUNT','AZURE_CERT_PROFILE')
|
||||
function Clear-SigningFixtures { foreach ($name in $names) { [Environment]::SetEnvironmentVariable($name, $null) } }
|
||||
function Assert-Policy([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } }
|
||||
function Invoke-Refusal([scriptblock] $Operation, [string] $Message) {
|
||||
$errorText = ''
|
||||
try { & $Operation | Out-Null } catch { $errorText = $_.Exception.Message }
|
||||
Assert-Policy ($errorText.Contains($Message)) "expected refusal: $Message; got: $errorText"
|
||||
}
|
||||
function global:cargo { $global:SigningFixtureCargoCalls++; throw 'FIXTURE_COMPILER_BOUNDARY' }
|
||||
# The source preflight reads the real checkout; the fixture answers for its own commit, whose sha
|
||||
# the version names, so the clean case reaches the mocked compiler instead of the preflight.
|
||||
function global:git {
|
||||
param([Parameter(ValueFromRemainingArguments=$true)][object[]] $Arguments)
|
||||
$joined = ($Arguments | ForEach-Object { "$_" }) -join ' '
|
||||
if ($joined -match 'rev-parse HEAD$') { $global:LASTEXITCODE = 0; return ('a' * 40) }
|
||||
if ($joined -match 'status --porcelain$') { $global:LASTEXITCODE = 0; return '' }
|
||||
throw "the fixture must not run git: $joined"
|
||||
}
|
||||
function global:Invoke-WebRequest { throw 'fixture must not perform signing downloads' }
|
||||
$global:SigningFixtureCargoCalls = 0
|
||||
# The caller's own values, restored in `finally`: this script may run inside a developer's session.
|
||||
$savedEnvironment = foreach ($name in (@('TEXTURECRAFT_VERSION', 'TEXTURECRAFT_BUILD_SHA', 'TEXTURECRAFT_BUILD_DATE') + $names)) {
|
||||
[pscustomobject]@{ Name = $name; Value = [Environment]::GetEnvironmentVariable($name) }
|
||||
}
|
||||
if (-not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'use an owned absolute FixtureRoot' }
|
||||
$root = Join-Path $FixtureRoot ('signing-policy-' + [Guid]::NewGuid().ToString('N'))
|
||||
New-Item -ItemType Directory -Path $root | Out-Null
|
||||
$version = '0.23.1-nightly.20261121.12345.1.gaaaaaaaaaaaa'
|
||||
$env:TEXTURECRAFT_VERSION = $version
|
||||
# The identity the version names: the mocked HEAD and its run date.
|
||||
$env:TEXTURECRAFT_BUILD_SHA = 'a' * 40
|
||||
$env:TEXTURECRAFT_BUILD_DATE = '2026-11-21'
|
||||
function Invoke-Build([switch] $BuildOnly) {
|
||||
$arguments = @{Arch='x64';Version=$version;Target='x86_64-pc-windows-msvc';TargetDir=$root;Dist=(Join-Path $root 'dist')}
|
||||
if ($BuildOnly) { $arguments.BuildOnly = $true }
|
||||
& (Join-Path $PackagingRoot 'nightly.ps1') @arguments
|
||||
}
|
||||
try {
|
||||
Clear-SigningFixtures
|
||||
Invoke-Refusal { Invoke-Build } 'requires -BuildOnly'
|
||||
Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'default mode invoked Cargo'
|
||||
Write-Output 'PASS: explicit-build-phase-required'
|
||||
if ($PhaseGuardOnly) { return }
|
||||
|
||||
foreach ($name in @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_CLIENT_SECRET')) {
|
||||
Clear-SigningFixtures
|
||||
[Environment]::SetEnvironmentVariable($name, 'generated-fixture-not-a-secret')
|
||||
Invoke-Refusal { Invoke-Build -BuildOnly } 'Compilation must not receive signing credentials'
|
||||
Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'key-bearing compilation reached Cargo'
|
||||
}
|
||||
Write-Output 'PASS: credentials-rejected-before-compilation'
|
||||
|
||||
Clear-SigningFixtures
|
||||
Invoke-Refusal { Invoke-Build -BuildOnly } 'FIXTURE_COMPILER_BOUNDARY'
|
||||
Assert-Policy ($global:SigningFixtureCargoCalls -eq 1) 'clean compilation did not reach the mocked compiler boundary'
|
||||
Assert-Policy (-not (Test-Path (Join-Path $root 'dist'))) 'mocked compilation produced an artifact'
|
||||
Write-Output 'PASS: secret-free-build-reaches-only-mocked-boundary'
|
||||
|
||||
Clear-SigningFixtures
|
||||
Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required'
|
||||
$env:AZURE_CLIENT_SECRET = 'generated-partial-fixture'
|
||||
Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required'
|
||||
Write-Output 'PASS: required-signer-refuses-missing-and-partial-configuration'
|
||||
|
||||
Clear-SigningFixtures
|
||||
$env:WINDOWS_CERTIFICATE = 'generated-presence-fixture-not-a-certificate'
|
||||
& $sign -Required -CheckOnly
|
||||
Clear-SigningFixtures
|
||||
foreach ($name in $names | Where-Object { $_.StartsWith('AZURE_') }) { [Environment]::SetEnvironmentVariable($name, 'generated-presence-fixture') }
|
||||
& $sign -Required -CheckOnly
|
||||
Clear-SigningFixtures
|
||||
Write-Output 'PASS: supported-configuration-presence-without-signing'
|
||||
|
||||
# Load the policy function without signing. These objects are not crypto evidence.
|
||||
. $sign -CheckOnly
|
||||
foreach ($value in @($null, [pscustomobject]@{Status='NotSigned';SignerCertificate='fixture'}, [pscustomobject]@{Status='HashMismatch';SignerCertificate='fixture'}, [pscustomobject]@{Status='Valid';SignerCertificate=$null})) {
|
||||
Invoke-Refusal { Assert-AuthenticodeSignature $value } 'valid Authenticode signature'
|
||||
}
|
||||
Assert-AuthenticodeSignature ([pscustomobject]@{Status='Valid';SignerCertificate='generated-public-certificate-placeholder'})
|
||||
Write-Output 'PASS: required-signature-policy-rejects-invalid-or-missing-signer'
|
||||
|
||||
$file = Join-Path $root 'owned-sentinel.exe'
|
||||
[IO.File]::WriteAllText($file, 'generated sentinel, not a real executable')
|
||||
$before = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash
|
||||
& $sign -Files $file
|
||||
Assert-Policy ((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash -ceq $before) 'optional stable policy changed unsigned bytes'
|
||||
Write-Output 'PASS: stable-optional-policy-preserves-owned-bytes'
|
||||
} finally {
|
||||
# Put back exactly what the caller had (an unset variable is restored as unset), and drop the
|
||||
# command mocks: a `function global:` binding outlives this script and outranks the real program.
|
||||
foreach ($entry in $savedEnvironment) { [Environment]::SetEnvironmentVariable($entry.Name, $entry.Value) }
|
||||
foreach ($mock in @('cargo', 'git', 'Invoke-WebRequest')) {
|
||||
Remove-Item -LiteralPath "function:global:$mock" -ErrorAction SilentlyContinue
|
||||
}
|
||||
Remove-Item -LiteralPath $root -Recurse -Force
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
<# First nightly target only: Windows x86_64 GUI ZIP. No MSI, CLI, portable marker or association registration. #>
|
||||
param(
|
||||
[string] $Arch = 'x64',
|
||||
[string] $Version,
|
||||
[string] $Target,
|
||||
[string] $TargetDir,
|
||||
[string] $Dist,
|
||||
[switch] $SkipBuild,
|
||||
[switch] $BuildOnly,
|
||||
[switch] $FunctionsOnly
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
function Get-NightlyArchiveSpec([string] $Version, [string] $Arch) {
|
||||
if ($Arch -ne 'x64') { throw 'nightly-v1 supports only Windows x86_64' }
|
||||
if (-not $Version -or $Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' }
|
||||
return @{
|
||||
Archive = "texturecraft-$Version-windows-x86_64-nightly.zip"
|
||||
UnsignedArchive = "texturecraft-$Version-windows-x86_64-nightly.unsigned.zip"
|
||||
Executables = @('texturecraft.exe')
|
||||
Channel = 'nightly-v1'
|
||||
AppId = 'ai.storyteller.texturecraft.nightly-v1'
|
||||
}
|
||||
}
|
||||
|
||||
# The same source identity the Unix helper enforces (nightly-common.sh): the version names the
|
||||
# commit being built, the date is the original run's, and the tree is clean.
|
||||
function Assert-NightlySource([string] $Version, [string] $Sha, [string] $BuildDate, [string] $Head, [string] $Status) {
|
||||
if ($Sha -cnotmatch '^[0-9a-f]{40}\z') { throw 'an exact source commit is required (TEXTURECRAFT_BUILD_SHA)' }
|
||||
if ($Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' }
|
||||
if ($Version.Substring($Version.Length - 12) -cne $Sha.Substring(0, 12)) { throw 'version/source commit mismatch' }
|
||||
if ($BuildDate -cnotmatch '^\d{4}-\d{2}-\d{2}\z') { throw 'the original run-created UTC date is required (TEXTURECRAFT_BUILD_DATE)' }
|
||||
$versionDate = ($Version -split '-nightly\.', 2)[1].Substring(0, 8)
|
||||
if ($BuildDate.Replace('-', '') -cne $versionDate) { throw 'version/original-run date mismatch' }
|
||||
if ($Head -cne $Sha) { throw 'prepared source is not the checked-out commit' }
|
||||
if ($Status) { throw 'nightly packaging requires the frozen clean source' }
|
||||
}
|
||||
|
||||
function Get-NightlySourceState([string] $RepositoryRoot) {
|
||||
$head = git -C $RepositoryRoot rev-parse HEAD
|
||||
if ($LASTEXITCODE -ne 0) { throw 'cannot read the checked-out commit' }
|
||||
$status = git -C $RepositoryRoot status --porcelain
|
||||
if ($LASTEXITCODE -ne 0) { throw 'cannot read the source tree status' }
|
||||
return @{ Head = "$head".Trim(); Status = ($status | Out-String).Trim() }
|
||||
}
|
||||
|
||||
function Assert-NightlyFlavor([string] $ProductName, [string] $VersionOutput, [string] $ExpectedVersion) {
|
||||
if ($ProductName -ne 'TextureCraft Nightly' -or $VersionOutput -cne "TextureCraft $ExpectedVersion (nightly-v1)") {
|
||||
throw 'the executable is not the compiled nightly-v1 flavor'
|
||||
}
|
||||
}
|
||||
|
||||
function Copy-NightlyNotices([string] $RepositoryRoot, [string] $FontRepository, [string] $Destination) {
|
||||
foreach ($name in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') {
|
||||
$source = Join-Path $RepositoryRoot $name
|
||||
if (Test-Path -LiteralPath $source) { Copy-Item -LiteralPath $source -Destination $Destination }
|
||||
}
|
||||
if ($FontRepository) {
|
||||
$fonts = Join-Path $FontRepository 'fonts'
|
||||
if (-not (Test-Path -LiteralPath $fonts -PathType Container)) { throw 'CRAFT_FONTS_DIR has no fonts directory for the bundled notices' }
|
||||
foreach ($family in Get-ChildItem -LiteralPath $fonts -Directory) {
|
||||
$license = Join-Path $family.FullName 'OFL.txt'
|
||||
if (Test-Path -LiteralPath $license) { Copy-Item -LiteralPath $license -Destination (Join-Path $Destination "OFL-$($family.Name).txt") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($FunctionsOnly) { return }
|
||||
if (-not $env:TEXTURECRAFT_VERSION -or $Version -cne $env:TEXTURECRAFT_VERSION) { throw 'nightly-v1 requires explicit TEXTURECRAFT_VERSION, not the Cargo version fallback' }
|
||||
$Spec = Get-NightlyArchiveSpec $Version $Arch
|
||||
if ($SkipBuild) { throw 'nightly-v1 forbids -SkipBuild; the executable flavor must be built in this operation' }
|
||||
if ($Target -ne 'x86_64-pc-windows-msvc') { throw 'nightly-v1 target must be x86_64-pc-windows-msvc' }
|
||||
if (-not $BuildOnly) { throw 'Nightly compilation requires -BuildOnly; final archives are produced in the separate trusted signing job' }
|
||||
# No key values may enter compilation. This produces an internal intermediate, not a feed artifact.
|
||||
& (Join-Path $PSScriptRoot 'sign.ps1') -CheckBuildEnvironment
|
||||
$Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
|
||||
$Source = Get-NightlySourceState $Root
|
||||
Assert-NightlySource $Version $env:TEXTURECRAFT_BUILD_SHA $env:TEXTURECRAFT_BUILD_DATE $Source.Head $Source.Status
|
||||
$oldChannel = $env:TEXTURECRAFT_BUILD_CHANNEL
|
||||
try {
|
||||
# `build.rs` reads TEXTURECRAFT_VERSION (checked equal above) and this channel.
|
||||
$env:TEXTURECRAFT_BUILD_CHANNEL = 'nightly-v1'
|
||||
$env:TEXTURECRAFT_REQUIRE_WINRES = '1'
|
||||
$env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS = '-C target-feature=+crt-static'
|
||||
# The GUI only: a Nightly install ships no CLI.
|
||||
cargo build --release --locked -p texturecraft --target $Target
|
||||
if ($LASTEXITCODE -ne 0) { throw "nightly cargo build failed: $LASTEXITCODE" }
|
||||
} finally {
|
||||
$env:TEXTURECRAFT_BUILD_CHANNEL = $oldChannel
|
||||
}
|
||||
$Source = Get-NightlySourceState $Root
|
||||
try { Assert-NightlySource $Version $env:TEXTURECRAFT_BUILD_SHA $env:TEXTURECRAFT_BUILD_DATE $Source.Head $Source.Status }
|
||||
catch { throw "source changed during the build: $_" }
|
||||
$Exe = Join-Path $TargetDir "$Target\release\texturecraft.exe"
|
||||
$pe = [System.IO.File]::ReadAllBytes($Exe)
|
||||
if ($pe.Length -lt 64) { throw 'truncated nightly PE executable' }
|
||||
$offset = [BitConverter]::ToInt32($pe, 0x3C)
|
||||
if ($offset -lt 0 -or $offset -gt $pe.Length - 0x5E) { throw 'invalid nightly PE header offset' }
|
||||
if ([BitConverter]::ToUInt16($pe, $offset + 4) -ne 0x8664 -or [BitConverter]::ToUInt16($pe, $offset + 0x5C) -ne 2) {
|
||||
throw 'nightly executable must be x86_64 Windows GUI'
|
||||
}
|
||||
$VersionInfo = (Get-Item -LiteralPath $Exe).VersionInfo
|
||||
$ProductName = $VersionInfo.ProductName
|
||||
if ($VersionInfo.ProductVersion -cne $Version) { throw 'nightly PE ProductVersion differs from the feed identity' }
|
||||
# Check the embedded build flavor before invoking even the side-effect-free version query.
|
||||
if ($ProductName -ne 'TextureCraft Nightly') { throw 'nightly executable is missing the embedded build flavor' }
|
||||
$VersionOutput = (& $Exe --version | Out-String).Trim()
|
||||
if ($LASTEXITCODE -ne 0) { throw 'nightly --version query failed' }
|
||||
Assert-NightlyFlavor $ProductName $VersionOutput $Version
|
||||
$Stage = Join-Path $TargetDir 'windows-package\nightly-v1-x86_64'
|
||||
if (Test-Path -LiteralPath $Stage) { Remove-Item -LiteralPath $Stage -Recurse -Force }
|
||||
New-Item -ItemType Directory -Force -Path $Stage | Out-Null
|
||||
Copy-Item -LiteralPath $Exe -Destination (Join-Path $Stage 'texturecraft.exe')
|
||||
# Signing happens only in the separate trusted step, using sign.ps1 -Required.
|
||||
# The intermediate name cannot satisfy the feed-ready archive contract.
|
||||
Copy-NightlyNotices $Root $env:CRAFT_FONTS_DIR $Stage
|
||||
if ((Get-ChildItem -LiteralPath $Stage -Filter '*.exe').Count -ne 1 -or (Test-Path (Join-Path $Stage 'texturecraft-cli.exe')) -or (Test-Path (Join-Path $Stage 'portable.txt'))) {
|
||||
throw 'nightly stage contains an unexpected executable or portable fallback marker'
|
||||
}
|
||||
New-Item -ItemType Directory -Force -Path $Dist | Out-Null
|
||||
$Zip = Join-Path $Dist $Spec.UnsignedArchive
|
||||
if (Test-Path -LiteralPath $Zip) { throw 'Nightly output already exists; refusing to replace prepared artifact bytes' }
|
||||
Compress-Archive -Path (Join-Path $Stage '*') -DestinationPath $Zip
|
||||
$Archive = [System.IO.Compression.ZipFile]::OpenRead($Zip)
|
||||
try {
|
||||
$Names = @($Archive.Entries | ForEach-Object { $_.FullName })
|
||||
if ('texturecraft.exe' -notin $Names -or 'texturecraft-cli.exe' -in $Names -or 'portable.txt' -in $Names) {
|
||||
throw 'nightly ZIP payload violates the GUI-only profile contract'
|
||||
}
|
||||
} finally { $Archive.Dispose() }
|
||||
Write-Output "Nightly build intermediate (not publishable): $Zip ($VersionOutput)"
|
||||
@@ -21,9 +21,12 @@
|
||||
#>
|
||||
param(
|
||||
[ValidateSet('x64', 'x86', 'arm64')] [string] $Arch = 'x64',
|
||||
[switch] $SkipBuild
|
||||
[switch] $SkipBuild,
|
||||
[switch] $Nightly,
|
||||
[switch] $BuildOnly
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if ($BuildOnly -and -not $Nightly) { throw '-BuildOnly is only for secret-free nightly compilation' }
|
||||
$Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
|
||||
|
||||
function Invoke-Native([string] $What, [scriptblock] $Block) {
|
||||
@@ -50,12 +53,23 @@ $Dist = if ($env:DIST) { $env:DIST } else { Join-Path $Root 'dist\release' }
|
||||
$TargetDir = if ($env:CARGO_TARGET_DIR) { $env:CARGO_TARGET_DIR } else { Join-Path $Root 'target' }
|
||||
New-Item -ItemType Directory -Force -Path $Dist | Out-Null
|
||||
|
||||
if (-not $env:TEXTURECRAFT_BUILD_SHA) { $env:TEXTURECRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) }
|
||||
if (-not $env:TEXTURECRAFT_BUILD_DATE) { $env:TEXTURECRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') }
|
||||
# Nightly requires the prepared commit and original run date explicitly; nightly.ps1 checks both.
|
||||
if (-not $Nightly) {
|
||||
if (-not $env:TEXTURECRAFT_BUILD_SHA) { $env:TEXTURECRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) }
|
||||
if (-not $env:TEXTURECRAFT_BUILD_DATE) { $env:TEXTURECRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') }
|
||||
}
|
||||
|
||||
Write-Output "TextureCraft $Version for Windows $Arch ($Target)"
|
||||
|
||||
if ($Nightly) {
|
||||
& (Join-Path $PSScriptRoot 'nightly.ps1') -Arch $Arch -Version $Version -Target $Target -TargetDir $TargetDir -Dist $Dist -SkipBuild:$SkipBuild -BuildOnly:$BuildOnly
|
||||
if ($LASTEXITCODE -ne 0) { throw "nightly packaging failed: $LASTEXITCODE" }
|
||||
return
|
||||
}
|
||||
|
||||
if (-not $SkipBuild) {
|
||||
$env:TEXTURECRAFT_BUILD_CHANNEL = 'stable'
|
||||
|
||||
# Static CRT: no VC++ redistributable needed. Scoped to the target so host build scripts and
|
||||
# proc-macros are unaffected.
|
||||
$flagVar = 'CARGO_TARGET_' + ($Target.ToUpper() -replace '-', '_') + '_RUSTFLAGS'
|
||||
@@ -83,6 +97,9 @@ foreach ($check in @(@('texturecraft.exe', 2), @('texturecraft-cli.exe', 3))) {
|
||||
if ($h.Subsystem -ne $check[1]) { throw "$($check[0]) has PE subsystem $($h.Subsystem), expected $($check[1])" }
|
||||
Write-Output "ok $($check[0]): $Arch, PE subsystem $($h.Subsystem)"
|
||||
}
|
||||
if ((Get-Item -LiteralPath (Join-Path $Bin 'texturecraft.exe')).VersionInfo.ProductName -eq 'TextureCraft Nightly') {
|
||||
throw 'a nightly executable cannot be packaged as stable'
|
||||
}
|
||||
$Stage = Join-Path $TargetDir "windows-package\$Arch"
|
||||
Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinue
|
||||
New-Item -ItemType Directory -Force -Path $Stage | Out-Null
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
AZURE_SIGNING_ENDPOINT (e.g. https://eus.codesigning.azure.net),
|
||||
AZURE_SIGNING_ACCOUNT, AZURE_CERT_PROFILE
|
||||
With neither, it prints a warning and leaves the files unsigned (exit code 0), so test builds
|
||||
still produce installers.
|
||||
still produce installers. Nightly callers require signing with -Required and can
|
||||
check signing configuration with -Required -CheckOnly. Compilation uses the
|
||||
separate -CheckBuildEnvironment mode, without importing signing keys.
|
||||
|
||||
This is the one place to adapt when the signing setup changes (an HSM/cloud key, a different
|
||||
timestamp server, ...). Optional overrides: WINDOWS_TIMESTAMP_URL, SIGNTOOL (path to signtool.exe).
|
||||
@@ -18,8 +20,11 @@
|
||||
pwsh packaging/windows/sign.ps1 dist/texturecraft.exe dist/TextureCraft.msi
|
||||
#>
|
||||
param(
|
||||
[Parameter(Mandatory = $true, ValueFromRemainingArguments = $true)]
|
||||
[string[]] $Files
|
||||
[Parameter(Position = 0, ValueFromRemainingArguments = $true)]
|
||||
[string[]] $Files,
|
||||
[switch] $Required,
|
||||
[switch] $CheckOnly,
|
||||
[switch] $CheckBuildEnvironment
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
@@ -27,6 +32,12 @@ function Write-Warn([string] $Message) {
|
||||
if ($env:GITHUB_ACTIONS) { Write-Output "::warning::$Message" } else { Write-Warning $Message }
|
||||
}
|
||||
|
||||
function Assert-AuthenticodeSignature($Signature) {
|
||||
if (-not $Signature -or [string]$Signature.Status -cne 'Valid' -or -not $Signature.SignerCertificate) {
|
||||
throw 'Required signing must produce a valid Authenticode signature and signer certificate'
|
||||
}
|
||||
}
|
||||
|
||||
function Find-SignTool {
|
||||
if ($env:SIGNTOOL) { return $env:SIGNTOOL }
|
||||
$onPath = Get-Command signtool.exe -ErrorAction SilentlyContinue
|
||||
@@ -44,11 +55,28 @@ function Invoke-SignTool([string[]] $Arguments) {
|
||||
if ($LASTEXITCODE -ne 0) { throw "signtool $($Arguments[0]) failed with exit code $LASTEXITCODE" }
|
||||
}
|
||||
|
||||
$Files = $Files | ForEach-Object { (Resolve-Path $_).Path }
|
||||
$haveCert = [bool]$env:WINDOWS_CERTIFICATE
|
||||
$azureVars = 'AZURE_TENANT_ID', 'AZURE_CLIENT_ID', 'AZURE_CLIENT_SECRET', 'AZURE_SIGNING_ENDPOINT', 'AZURE_SIGNING_ACCOUNT', 'AZURE_CERT_PROFILE'
|
||||
if ($CheckBuildEnvironment) {
|
||||
if ($Required -or $CheckOnly -or $Files) { throw '-CheckBuildEnvironment is separate from signing' }
|
||||
$names = @('WINDOWS_CERTIFICATE', 'WINDOWS_CERTIFICATE_PASSWORD') + $azureVars
|
||||
if ($names | Where-Object { [Environment]::GetEnvironmentVariable($_) }) {
|
||||
throw 'Compilation must not receive signing credentials; use a separate trusted signing step'
|
||||
}
|
||||
return
|
||||
}
|
||||
$haveCert = [bool]$env:WINDOWS_CERTIFICATE
|
||||
$haveAzure = -not ($azureVars | Where-Object { -not [Environment]::GetEnvironmentVariable($_) })
|
||||
|
||||
if ($Required -and -not $haveCert -and -not $haveAzure) {
|
||||
throw 'Nightly signing is required: configure WINDOWS_CERTIFICATE or the complete existing Azure signing configuration'
|
||||
}
|
||||
if ($CheckOnly) {
|
||||
if ($Files) { throw '-CheckOnly does not sign files' }
|
||||
return
|
||||
}
|
||||
if (-not $Files) { throw 'At least one file is required for signing' }
|
||||
$Files = $Files | ForEach-Object { (Resolve-Path $_).Path }
|
||||
|
||||
if (-not $haveCert -and -not $haveAzure) {
|
||||
Write-Warn "Windows signing secrets not set (WINDOWS_CERTIFICATE or AZURE_*): leaving unsigned: $($Files -join ', ')"
|
||||
exit 0
|
||||
@@ -89,6 +117,9 @@ try {
|
||||
Invoke-SignTool ($common + @('/tr', $ts, '/dlib', $dlib.FullName, '/dmdf', $metadata) + $Files)
|
||||
}
|
||||
Invoke-SignTool (@('verify', '/pa', '/v') + $Files)
|
||||
if ($Required) {
|
||||
foreach ($file in $Files) { Assert-AuthenticodeSignature (Get-AuthenticodeSignature -LiteralPath $file) }
|
||||
}
|
||||
}
|
||||
finally {
|
||||
Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue
|
||||
|
||||
Reference in new issue
Block a user