okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
42.2 KiB776 linesraw
1#!/usr/bin/env bash
2# Sign the Strata Mac app (dmg or .app) and, optionally, the Mac Terminal archive with the owner's Developer ID, then notarise
3# them with Apple, so macOS opens them without the "damaged" / "unidentified developer" warning.
4#
5#   bash sign-and-notarize.sh <Strata-tester-mac.dmg | Strata.app> [--terminal <Strata-Terminal-Mac.zip>] [--engine <engine-folder.tar.gz>] [--updater-archive] [--out DIR] [--dry-run]
6#   bash sign-and-notarize.sh --terminal <Strata-Terminal-Mac.zip>            # the Terminal archive alone
7#   bash sign-and-notarize.sh --terminal <Terminal.tar.gz> --engine <strata-...-unsigned-folder.tar.gz>   # both in one run
8#
9# This script runs on the OWNER'S Mac, where the certificate "Developer ID Application: Niko Veit (79LR4R7RSC)" is in the Keychain and the
10# notarytool keychain profile "strata-notary" exists. It never asks for, reads or stores a password or a key: codesign and notarytool
11# take them from the Keychain themselves. Nothing is uploaded except what notarytool sends to Apple's notary service.
12#
13# Environment overrides (the defaults are the owner's values):
14#   SIGN_ID          the signing identity            (default: Developer ID Application: Niko Veit (79LR4R7RSC))
15#   NOTARY_PROFILE   the notarytool keychain profile (default: strata-notary)
16#   TMPDIR           where the work folder is made   (needs about 4 x the size of the input free)
17#
18# --dry-run: no Apple account is touched. Signs with the ad-hoc identity (SIGN_ID=-), skips notarytool/stapler/spctl-accept, and is
19#   how this script is tested on a Mac that has no certificate. An ad-hoc signature has no Team ID, so in a dry run the hardened-runtime
20#   "library validation" cannot be satisfied by libraries signed with the same identity; the dry run therefore adds
21#   com.apple.security.cs.disable-library-validation to node and python ONLY so that the smoke tests can run. A real run never does.
22#
23# What it does, in order (each step prints OK or FAIL; the first FAIL stops the run and the summary says which):
24#   1. copies the .app out of the dmg into a temporary folder;
25#   2. signs every nested Mach-O inside-out (deepest first): hardened runtime, secure timestamp, entitlements only where needed;
26#   3. rewrites the SHA-256 and size of every engine file it signed in the engine package's engine-component.json (Control refuses an
27#      engine whose files do not match that manifest), then signs the .app itself;
28#   4. codesign --verify --deep --strict, spctl -a -vvv;
29#   5. smoke tests of the SIGNED copy (the app's own --self-test, node loading every native addon, python imports, the engine's --version,
30#      and Control's own engine manifest check), so a signing mistake shows up here and not on a tester's Mac;
31#   6. notarises the .app, staples it, rebuilds the dmg (same layout as apps/desktop/scripts/make-dmg.sh), signs the dmg, notarises the dmg,
32#      staples it, spctl -a -t open --context context:primary-signature -vv;
33#   7. Terminal archive: signs every Mach-O inside, re-zips, notarises the zip (a zip cannot be stapled: see the note at the end).
34#   7b. --engine FOLDER.tar.gz (an engine package of the Mac that Control installs from the feed, a tar of one folder: its program, its
35#      metal/ sources and engine-component.json): signs every Mach-O in it like the engine inside the app (hardened runtime, timestamp, no entitlements),
36#      writes the signed files' SHA-256 and size into engine-component.json, codesign --verify --strict on each, checks that the signed
37#      program starts, notarises a zip of the folder, and packs it again as <component>-<version>-<platform>-<backend>-folder.tar.gz (modes
38#      kept). Sign the folder with the feed key AFTER this step, on the PC: signing changes the program, so the manifest changes with it.
39#   8. --updater-archive (opt-in, needs the app input): packs the signed, notarised, stapled .app into Strata.app.tar.gz, the file Tauri's in-app
40#      updater downloads on a Mac (Strata.app at the root of the archive), and checks it by unpacking it again. The archive is NOT signed with the
41#      Tauri updater key here: this script never touches that key. Sign it on the PC (npx tauri signer sign) and put it in the update file with
42#      packaging/feed_tool.py set-app-platform (see packaging/UPDATES.md). Any Strata.app.tar.gz / .sig that `tauri build` made earlier holds the
43#      UNSIGNED app and must not be published.
44set -u
45set -o pipefail
46
47SIGN_ID="${SIGN_ID:-Developer ID Application: Niko Veit (79LR4R7RSC)}"
48NOTARY_PROFILE="${NOTARY_PROFILE:-strata-notary}"
49HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
50ENT_NODE_SRC="$HERE/entitlements-node.plist"
51
52INPUT=""; TERMINAL=""; ENGINE=""; OUT=""; DRY=0; KEEP=0; SIGN_NESTED=0; UPDATER_ARCHIVE=0
53WORK=""
54LOG=""
55declare -a RESULTS=()
56declare -a MOUNTS=()
57declare -a FINAL=()
58NOTARY_ID=""
59
60usage() {
61  sed -n '2,/^set -u$/p' "${BASH_SOURCE[0]}" | sed '$d' | sed 's/^# \{0,1\}//'
62  exit "${1:-2}"
63}
64
65while [ $# -gt 0 ]; do
66  case "$1" in
67    --terminal)    [ $# -ge 2 ] || usage; TERMINAL="$2"; shift 2 ;;
68    --engine)      [ $# -ge 2 ] || usage; ENGINE="$2"; shift 2 ;;
69    --out)         [ $# -ge 2 ] || usage; OUT="$2"; shift 2 ;;
70    --dry-run)     DRY=1; shift ;;
71    --keep-work)   KEEP=1; shift ;;
72    --sign-nested) SIGN_NESTED=1; shift ;;
73    --updater-archive) UPDATER_ARCHIVE=1; shift ;;
74    -h|--help)     usage 0 ;;
75    -*)            echo "unknown option: $1" >&2; usage ;;
76    *)             if [ -z "$INPUT" ]; then INPUT="$1"; shift; else echo "unexpected argument: $1" >&2; usage; fi ;;
77  esac
78done
79[ -n "$INPUT" ] || [ -n "$TERMINAL" ] || [ -n "$ENGINE" ] || usage
80if [ "$UPDATER_ARCHIVE" -eq 1 ] && [ -z "$INPUT" ]; then echo "--updater-archive needs the app (a .dmg or .app) as the input" >&2; usage; fi
81
82# ----------------------------------------------------------------------------------------------------------------- output helpers
83say() { printf '%s\n' "$*"; [ -z "$LOG" ] || printf '%s\n' "$*" >>"$LOG"; }
84rec() { RESULTS+=("$1|$2|${3:-}"); say "  [$1] $2${3:+: $3}"; }
85
86summary() {
87  local rc=$1 line st name detail f sum
88  say ""
89  say "================================ SUMMARY ================================"
90  if [ "${#RESULTS[@]}" -gt 0 ]; then
91    for line in "${RESULTS[@]}"; do
92      st="${line%%|*}"; line="${line#*|}"; name="${line%%|*}"; detail="${line#*|}"
93      printf '  %-5s %s%s\n' "$st" "$name" "${detail:+  ($detail)}"
94    done
95  fi
96  if [ "${#FINAL[@]}" -gt 0 ]; then
97    say ""
98    say "Final files:"
99    for f in "${FINAL[@]}"; do
100      sum="$(shasum -a 256 "$f" | awk '{print $1}')"
101      say "  $f"
102      say "    sha256 $sum"
103      [ -z "$OUT" ] || printf '%s  %s\n' "$sum" "$(basename "$f")" >>"$OUT/SHA256SUMS.txt"
104    done
105  fi
106  say ""
107  if [ "$rc" -eq 0 ]; then
108    if [ "$DRY" -eq 1 ]; then say "RESULT: DRY RUN finished. Nothing was sent to Apple; these files are ad-hoc signed and are NOT for release."
109    else say "RESULT: all steps OK."; fi
110  else
111    say "RESULT: FAILED. Read the FAIL line above. Full log: ${LOG:-none}"
112  fi
113  if [ -n "$TERMINAL" ] || [ -n "$ENGINE" ]; then
114    say ""
115    say "Note on the Terminal zip and the engine folder: Apple cannot staple a ticket to bare command-line programs in a zip, so the zip carries no ticket. Notarisation is"
116    say "still recorded at Apple by the programs' hashes, and macOS checks that online the first time a quarantined (browser-downloaded) copy is opened."
117    say "Offline, the first open of such a copy needs a connection. Installs done with 'curl | sh' are not quarantined at all, so this mainly helps zips"
118    say "downloaded in a browser. The zip's sha256 changed: any feed or checksum list that names the old zip must be rebuilt from this one."
119  fi
120}
121
122finish() { summary "$1"; exit "$1"; }
123fail() { rec FAIL "$1" "${2:-}"; finish 1; }
124
125# shellcheck disable=SC2329  # run by the EXIT trap below
126cleanup() {
127  local m
128  if [ "${#MOUNTS[@]}" -gt 0 ]; then
129    for m in "${MOUNTS[@]}"; do hdiutil detach "$m" -force >/dev/null 2>&1 || true; done
130  fi
131  if [ -n "$WORK" ] && [ -d "$WORK" ]; then
132    if [ "$KEEP" -eq 1 ]; then echo "work folder kept: $WORK" >&2; else rm -rf "$WORK"; fi
133  fi
134}
135trap cleanup EXIT
136trap 'echo "interrupted" >&2; exit 130' INT TERM HUP
137
138# run a command, appending all its output to the log; on failure show the last lines of it
139logged() {
140  local tmp rc
141  tmp="$(mktemp "${WORK:-${TMPBASE:-/tmp}}/cmd.XXXXXX")"
142  "$@" >"$tmp" 2>&1; rc=$?
143  cat "$tmp" >>"${LOG:-/dev/null}"
144  [ "$rc" -eq 0 ] || { tail -n 12 "$tmp" | sed 's/^/        /' >&2; }
145  rm -f "$tmp"
146  return "$rc"
147}
148
149# run a command with a time limit (macOS has no timeout(1)); 124 = timed out
150run_timeout() {
151  local secs=$1 i=0 pid
152  shift
153  "$@" &
154  pid=$!
155  while kill -0 "$pid" 2>/dev/null; do
156    if [ "$i" -ge $((secs * 2)) ]; then
157      pkill -P "$pid" 2>/dev/null; kill "$pid" 2>/dev/null; sleep 1; kill -9 "$pid" 2>/dev/null
158      wait "$pid" 2>/dev/null
159      return 124
160    fi
161    sleep 0.5; i=$((i + 1))
162  done
163  wait "$pid"
164}
165
166# ----------------------------------------------------------------------------------------------------------------- preflight
167[ "$(uname -s)" = Darwin ] || { echo "This script runs on a Mac (it needs codesign, hdiutil, notarytool)." >&2; exit 2; }
168for tool in codesign hdiutil ditto shasum file xattr perl PlistBuddy; do
169  if [ "$tool" = PlistBuddy ]; then [ -x /usr/libexec/PlistBuddy ] || { echo "missing /usr/libexec/PlistBuddy" >&2; exit 2; }
170  else command -v "$tool" >/dev/null 2>&1 || { echo "missing tool: $tool" >&2; exit 2; }; fi
171done
172
173if [ "$DRY" -eq 1 ]; then
174  SIGN_ID="-"
175else
176  command -v xcrun >/dev/null 2>&1 || { echo "missing xcrun (install the Xcode command line tools: xcode-select --install)" >&2; exit 2; }
177fi
178if [ "$DRY" -eq 1 ]; then :
179elif [ "$SIGN_ID" = "-" ]; then
180  echo "SIGN_ID=- is an ad-hoc signature, which Apple cannot notarise. Add --dry-run to test with it." >&2; exit 2
181fi
182
183[ -z "$INPUT" ] || [ -e "$INPUT" ] || { echo "not found: $INPUT" >&2; exit 2; }
184[ -z "$TERMINAL" ] || [ -f "$TERMINAL" ] || { echo "not found: $TERMINAL" >&2; exit 2; }
185[ -z "$ENGINE" ] || [ -f "$ENGINE" ] || { echo "not found: $ENGINE" >&2; exit 2; }
186case "$ENGINE" in ""|*.tar.gz|*.tgz) ;; *) echo "--engine takes the engine folder as a .tar.gz: $ENGINE" >&2; exit 2 ;; esac
187
188if [ -z "$OUT" ]; then
189  first="${INPUT:-${TERMINAL:-$ENGINE}}"
190  OUT="$(cd "$(dirname "$first")" && pwd)/signed"
191fi
192mkdir -p "$OUT" || { echo "cannot create $OUT" >&2; exit 2; }
193OUT="$(cd "$OUT" && pwd)"
194TMPBASE="${TMPDIR:-/tmp}"; TMPBASE="${TMPBASE%/}"   # macOS TMPDIR ends in "/": a "//" in the path broke the app self-test
195WORK="$(mktemp -d "$TMPBASE/strata-sign.XXXXXX")" || { echo "cannot make a work folder" >&2; exit 2; }
196LOG="$OUT/sign-and-notarize.log"
197: >"$LOG"
198: >"$OUT/SHA256SUMS.txt"
199say "Strata sign-and-notarize, $(date '+%Y-%m-%d %H:%M:%S')"
200say "  identity : $SIGN_ID"
201if [ "$DRY" -eq 1 ]; then say "  mode     : DRY RUN (ad-hoc, no notarisation)"; else say "  profile  : $NOTARY_PROFILE"; fi
202say "  work     : $WORK"
203say "  output   : $OUT"
204say ""
205
206need_kb=0
207for f in "$INPUT" "$TERMINAL" "$ENGINE"; do
208  [ -n "$f" ] || continue
209  kb="$(du -sk "$f" | awk '{print $1}')"; need_kb=$((need_kb + kb * 5))
210done
211free_kb="$(df -k "$WORK" | awk 'NR==2 {print $4}')"
212if [ "$free_kb" -lt "$need_kb" ]; then
213  fail "free space" "about $((need_kb / 1048576)) GB needed in $WORK, $((free_kb / 1048576)) GB free; set TMPDIR to a bigger disk"
214fi
215
216if [ "$DRY" -eq 0 ]; then
217  if ! security find-identity -v -p codesigning 2>/dev/null | grep -qF "\"$SIGN_ID\""; then
218    fail "signing identity" "\"$SIGN_ID\" is not in your Keychain (security find-identity -v -p codesigning lists what is)"
219  fi
220  if ! xcrun notarytool history --keychain-profile "$NOTARY_PROFILE" >/dev/null 2>&1; then
221    fail "notary profile" "profile \"$NOTARY_PROFILE\" does not work (create it once: xcrun notarytool store-credentials $NOTARY_PROFILE ...), or there is no internet"
222  fi
223  rec OK "preflight" "identity and notary profile found"
224else
225  rec OK "preflight" "dry run, ad-hoc identity"
226fi
227
228# ----------------------------------------------------------------------------------------------------------------- entitlements
229# Every entitlement is a hole in the hardened runtime, so there are as few as work (each one was tested; see entitlements-node.plist).
230#   node:   com.apple.security.cs.allow-jit  (V8 writes machine code into MAP_JIT memory; without it node dies at start with
231#           "Failed to reserve virtual memory for CodeRange"). Nothing else: WebAssembly, regexp JIT and the native addons run with just this.
232#   python, the engine, the app shell, rg, spawn-helper, every .dylib/.so/.node: none. (Python's ctypes callbacks and numpy run without any;
233#   Metal compiles the engine's kernel sources through the system compiler service, which needs nothing from the engine process.)
234#   disable-library-validation: NOT used. It would only be needed if a hardened program loaded a library signed by somebody else; every
235#   library in these bundles is re-signed here with the one identity, so they share a Team ID. (Dry run only: see the header.)
236ENT_NODE="$ENT_NODE_SRC"
237ENT_DLV=""
238if [ "$DRY" -eq 1 ]; then
239  ENT_DLV="$WORK/dlv.plist"
240  ENT_NODE="$WORK/node-dryrun.plist"
241  cp "$ENT_NODE_SRC" "$ENT_NODE"
242  /usr/libexec/PlistBuddy -c "Add :com.apple.security.cs.disable-library-validation bool true" "$ENT_NODE" >/dev/null
243  printf '<?xml version="1.0" encoding="UTF-8"?>\n<plist version="1.0"><dict><key>com.apple.security.cs.disable-library-validation</key><true/></dict></plist>\n' >"$ENT_DLV"
244fi
245[ -f "$ENT_NODE_SRC" ] || fail "entitlements" "missing $ENT_NODE_SRC (keep it next to this script)"
246
247ent_for() {
248  case "$(basename "$1")" in
249    node) printf '%s' "$ENT_NODE" ;;
250    python|python3|python3.[0-9]*) printf '%s' "$ENT_DLV" ;;   # empty in a real run
251    *) printf '' ;;
252  esac
253}
254
255# ----------------------------------------------------------------------------------------------------------------- signing helpers
256# Every Mach-O (programs, .dylib, .so, .node, universal binaries), deepest path first. Object files cannot be signed and are skipped.
257find_macho() {
258  find "$1" -type f -print0 2>/dev/null | xargs -0 file --mime-type 2>/dev/null \
259    | sed -n 's/:[[:space:]]*application\/x-mach-binary$//p' | sed 's/ (for architecture [^)]*)$//' | sort -u \
260    | while IFS= read -r f; do
261        case "$(file -b "$f")" in *object*|*"core file"*) continue ;; esac
262        printf '%s\n' "$f"
263      done \
264    | awk '{ n = gsub("/", "/"); print n "\t" $0 }' | sort -rn | cut -f2-
265}
266
267codesign_item() {   # path [extra codesign args...]
268  local f=$1 ent try=1 rc=1
269  shift
270  local -a args=(--force --sign "$SIGN_ID" --options runtime)
271  if [ "$SIGN_ID" = "-" ]; then args+=(--timestamp=none); else args+=(--timestamp); fi
272  ent="$(ent_for "$f")"
273  [ -z "$ent" ] || args+=(--entitlements "$ent")
274  while [ "$try" -le 3 ]; do
275    logged codesign "${args[@]}" "$@" "$f" && { rc=0; break; }
276    say "        (attempt $try of 3 failed; the timestamp server is sometimes slow)"
277    try=$((try + 1)); sleep 3
278  done
279  return "$rc"
280}
281
282codesign_plain() {   # a disk image: signature and secure timestamp, no hardened-runtime flag (that flag is for programs)
283  local f=$1 try=1
284  local -a args=(--force --sign "$SIGN_ID")
285  if [ "$SIGN_ID" = "-" ]; then args+=(--timestamp=none); else args+=(--timestamp); fi
286  while [ "$try" -le 3 ]; do
287    logged codesign "${args[@]}" "$f" && return 0
288    try=$((try + 1)); sleep 3
289  done
290  return 1
291}
292
293sign_tree() {   # folder label: all Mach-O inside-out, then nested bundles
294  local dir=$1 label=$2 f n=0 bad=0 d
295  while IFS= read -r f; do
296    [ -n "$f" ] || continue
297    if codesign_item "$f"; then n=$((n + 1)); else say "        could not sign: $f"; bad=$((bad + 1)); fi
298  done < <(find_macho "$dir")
299  [ "$bad" -eq 0 ] || fail "sign $label" "$bad file(s) could not be signed (see the log)"
300  # nested bundles (frameworks, helper apps, XPC services), deepest first; there are none in today's app
301  while IFS= read -r d; do
302    [ -n "$d" ] || continue
303    [ "$d" != "$dir" ] || continue
304    if [ -f "$d/Contents/Info.plist" ] || [ -f "$d/Resources/Info.plist" ] || [ -d "$d/Versions" ]; then
305      codesign_item "$d" || fail "sign $label" "nested bundle $d"
306    fi
307  done < <(find "$dir" -type d \( -name '*.app' -o -name '*.framework' -o -name '*.xpc' -o -name '*.appex' \) 2>/dev/null | awk '{ n = gsub("/", "/"); print n "\t" $0 }' | sort -rn | cut -f2-)
308  rec OK "sign $label" "$n Mach-O file(s) signed"
309}
310
311# The engine packages inside the bundle carry engine-component.json with the SHA-256 and size of every file; Control checks them before it
312# starts an engine. Signing changes the engine binary, so the manifest must be brought up to date, or the signed app would refuse its own engine.
313update_engine_manifests() {   # folder label
314  local dir=$1 label=$2 m out rc n=0
315  while IFS= read -r m; do
316    [ -n "$m" ] || continue
317    out="$(perl -MJSON::PP -MDigest::SHA -e '
318      my ($file) = @ARGV; local $/; open my $fh, "<", $file or die "cannot read $file\n"; my $raw = <$fh>; close $fh;
319      $raw =~ s/^\xEF\xBB\xBF//;
320      my $json = JSON::PP->new->utf8->canonical->pretty; my $d = $json->decode($raw);
321      (my $dir = $file) =~ s{/[^/]+$}{};
322      if (defined $d->{signature}) { print "signed-manifest\n"; exit 3; }
323      my $changed = 0;
324      for my $e (@{ $d->{files} || [] }) {
325        my $p = "$dir/$e->{path}"; next unless -f $p;
326        open my $f, "<:raw", $p or die "cannot read $p\n"; my $sha = Digest::SHA->new(256); $sha->addfile($f); close $f;
327        my $hex = $sha->hexdigest; my $size = -s $p;
328        if (lc($e->{sha256}) ne $hex or $e->{bytes} != $size) { $e->{sha256} = $hex; $e->{bytes} = $size + 0; $changed++; }
329      }
330      if ($changed) { open my $o, ">", $file or die "cannot write $file\n"; print $o $json->encode($d); close $o; }
331      print "$changed\n";
332    ' "$m" 2>&1)"; rc=$?
333    if [ "$rc" -eq 3 ]; then
334      fail "engine manifest $label" "$m carries a release signature; changing a file would break it. Sign this engine package at its source, or re-sign its manifest with the release key"
335    elif [ "$rc" -ne 0 ]; then
336      fail "engine manifest $label" "$m: $out"
337    fi
338    n=$((n + 1)); say "        $m: $out entry(ies) updated"
339  done < <(find "$dir" -name engine-component.json -type f 2>/dev/null)
340  rec OK "engine manifests $label" "$n manifest(s) checked"
341}
342
343verify_signed() {   # path label
344  local p=$1 label=$2
345  if logged codesign --verify --deep --strict --verbose=2 "$p"; then rec OK "codesign --verify --deep --strict $label"
346  else fail "codesign --verify --deep --strict $label" "see the log"; fi
347}
348
349# notarytool submit --wait; sets NOTARY_ID. On anything but Accepted, fetches Apple's log and fails.
350notarize() {   # file label
351  local f=$1 label=$2 out status
352  out="$WORK/notary-$label.txt"
353  say "        sending $(basename "$f") to Apple ($(du -h "$f" | awk '{print $1}')); this waits for the result, usually 2 to 15 minutes ..."
354  xcrun notarytool submit "$f" --keychain-profile "$NOTARY_PROFILE" --wait --timeout 60m >"$out" 2>&1
355  cat "$out" >>"$LOG"
356  NOTARY_ID="$(awk '/^ *id:/ {print $2; exit}' "$out")"
357  status="$(awk '/^ *status:/ {s = $2} END {print s}' "$out")"
358  if [ "$status" = "Accepted" ]; then
359    rec OK "notarise $label" "Accepted, submission $NOTARY_ID"
360    return 0
361  fi
362  if [ -n "$NOTARY_ID" ]; then
363    xcrun notarytool log --keychain-profile "$NOTARY_PROFILE" "$NOTARY_ID" "$OUT/notary-log-$label.json" >>"$LOG" 2>&1
364    say ""
365    say "---- Apple's notarisation log for $label (submission $NOTARY_ID), also saved to $OUT/notary-log-$label.json ----"
366    cat "$OUT/notary-log-$label.json" 2>/dev/null | tee -a "$LOG"
367    say "-------------------------------------------------------------------------------"
368  else
369    tail -n 15 "$out" | sed 's/^/        /'
370  fi
371  fail "notarise $label" "status: ${status:-no answer from notarytool}"
372}
373
374# a finished file goes to the output folder only when every step for it has passed, so a half-done file is never mistaken for a release
375deliver() {   # file original
376  local f=$1 orig=$2 dest
377  dest="$OUT/$(basename "$f")"
378  if [ -e "$dest" ] && [ "$dest" -ef "$orig" ]; then fail "write the result" "$dest is the input file itself; choose another --out folder"; fi
379  cp -p "$f" "$dest" || fail "write the result" "cannot write $dest"
380  FINAL+=("$dest")
381}
382
383zip_dir() {   # src_dir out.zip  (keeps symlinks and permissions, no AppleDouble clutter)
384  ditto -c -k --norsrc --noextattr --noqtn --noacl --keepParent "$1" "$2"
385}
386
387# ----------------------------------------------------------------------------------------------------------------- smoke tests (signed copy)
388smoke_app() {   # app
389  local app=$1 res="$1/Contents/Resources" home="$WORK/smokehome" rep="$WORK/self-test.json" node py ctl rc f fails=0 out r engines=0
390  mkdir -p "$home"
391  node="$res/node/node"; ctl="$res/control"; py="$ctl/python/bin/python3"
392  export PYTHONDONTWRITEBYTECODE=1 PYTHONNOUSERSITE=1   # a smoke test must not write into the sealed bundle
393
394  # 1. the app's own headless self-test: private node, host, UI, Control on the bundled python
395  run_timeout 150 env HOME="$home" "$app/Contents/MacOS/strata-desktop" --self-test="$rep" >"$WORK/selftest.out" 2>&1; rc=$?
396  cat "$WORK/selftest.out" >>"$LOG"
397  if [ "$rc" -eq 0 ]; then rec OK "smoke: app --self-test (host, UI, Control)"
398  else
399    grep -E '"(name|ok|detail)"' "$rep" 2>/dev/null | paste - - - | grep 'false' | sed 's/^/        /'
400    fail "smoke: app --self-test" "exit $rc; the signed app cannot start its host (see the log)"
401  fi
402
403  # 2. every native addon loads in the signed, hardened node (library validation, JIT)
404  if [ -x "$node" ]; then
405    out="$WORK/addons.txt"; : >"$out"
406    while IFS= read -r f; do
407      case "$(file -b "$f")" in *arm64*) ;; *) continue ;; esac
408      r="$("$node" -e 'try { process.dlopen({ exports: {} }, process.argv[1]); console.log("OK"); } catch (e) { console.log("ERR " + String(e.message).split("\n")[0]); }' "$f" 2>&1 | head -n 1)"
409      [ -n "$r" ] || r="ERR killed by the system (code signature)"
410      printf '%s: %s\n' "$f" "$r" >>"$out"
411    done < <(find "$res" -name '*.node' -type f 2>/dev/null)
412    cat "$out" >>"$LOG"
413    if grep -qiE 'code signature|team id|library validation|not valid for use|killed' "$out"; then
414      grep -iE 'code signature|team id|library validation|not valid for use' "$out" | sed 's/^/        /'
415      fail "smoke: node loads its native addons" "library validation refuses an addon (a library with a different signature)"
416    fi
417    if ! "$node" -e 'WebAssembly.instantiate(new Uint8Array([0,97,115,109,1,0,0,0])).then(()=>{let s=0;for(let i=0;i<2e6;i++)s+=i%7;if(!/a+b/.test("aab"))process.exit(3);console.log("jit ok")})' >>"$LOG" 2>&1; then
418      fail "smoke: node JIT and WebAssembly" "the hardened node cannot run JIT code (entitlement missing?)"
419    fi
420    rec OK "smoke: node JIT, WebAssembly and native addons" "$(grep -c ': OK' "$out") addon(s) loaded"
421  else
422    rec SKIP "smoke: node" "no bundled node"
423  fi
424
425  # 3. Control's python imports its compiled modules
426  if [ -x "$py" ]; then
427    if (cd "$ctl" && env HOME="$home" "$py" -c '
428import ctypes, importlib, sys
429for m in ("numpy", "PIL.Image", "psutil", "yaml", "regex", "charset_normalizer", "markupsafe", "ssl", "sqlite3", "zlib", "lzma", "hashlib"):
430    try: importlib.import_module(m)
431    except ModuleNotFoundError: pass
432cb = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p)(lambda a, b: 0)
433arr = (ctypes.c_int * 4)(4, 3, 2, 1); ctypes.CDLL(None).qsort(arr, 4, 4, cb)
434print("python ok", sys.version.split()[0])' >>"$LOG" 2>&1); then rec OK "smoke: bundled python imports and ctypes callbacks"
435    else fail "smoke: bundled python" "an import or a ctypes callback failed under the hardened runtime (see the log)"; fi
436  fi
437
438  # 4. every bundled engine starts, and Control accepts its manifest (hashes of the signed files)
439  while IFS= read -r f; do
440    [ -n "$f" ] || continue
441    engines=$((engines + 1))
442    if run_timeout 30 "$f" --version >"$WORK/engine-version.txt" 2>&1; then say "        $(head -n 1 "$WORK/engine-version.txt")"; else
443      cat "$WORK/engine-version.txt" >>"$LOG"; fails=$((fails + 1)); say "        engine did not start: $f"
444    fi
445  done < <(find "$res/engine-bundle" -mindepth 2 -maxdepth 2 -type f \( -name strata -o -name strata-device -o -name strata-vision \) 2>/dev/null)
446  [ "$fails" -eq 0 ] || fail "smoke: bundled engine starts" "$fails engine(s) did not start under the hardened runtime"
447  if [ -x "$py" ] && [ -d "$res/engine-bundle" ]; then
448    out="$(cd "$ctl" && env HOME="$home" "$py" -c '
449import sys, pathlib
450from strata_control import engine_component as ec
451bad = 0; n = 0
452for m in sorted(pathlib.Path(sys.argv[1]).glob("*/engine-component.json")):
453    n += 1
454    try:
455        c = ec.read_manifest(m.parent); ec.verify(c, full=True); print("manifest ok", c.version, c.platform, c.backend)
456    except Exception as e:
457        bad += 1; print("MANIFEST PROBLEM", m, type(e).__name__, e)
458sys.exit(1 if bad or not n else 0)' "$res/engine-bundle" 2>&1)"; rc=$?
459    printf '%s\n' "$out" >>"$LOG"
460    if [ "$rc" -eq 0 ]; then rec OK "smoke: engine manifest matches the signed files (Control's own check)"
461    else printf '%s\n' "$out" | sed 's/^/        /'; fail "smoke: engine manifest" "Control would refuse the signed engine"; fi
462  fi
463  if [ "$engines" -gt 0 ]; then rec OK "smoke: bundled engine --version" "$engines engine(s), no model loaded"; else rec SKIP "smoke: bundled engine" "this app carries no engine"; fi
464}
465
466smoke_terminal() {   # extracted terminal folder
467  local root=$1 py f strata home="$WORK/termhome" out
468  mkdir -p "$home"
469  export PYTHONDONTWRITEBYTECODE=1 PYTHONNOUSERSITE=1
470  py="$(find "$root" -maxdepth 4 -path '*/python/bin/python3' \( -type f -o -type l \) 2>/dev/null | head -n 1)"
471  if [ -n "$py" ]; then
472    if env HOME="$home" "$py" -c 'import ctypes, ssl, sqlite3, zlib; print("python ok")' >>"$LOG" 2>&1; then rec OK "smoke: terminal python starts"
473    else fail "smoke: terminal python" "does not start under the hardened runtime"; fi
474    strata="$(dirname "$py")/../../bin/strata"
475    if [ -x "$strata" ]; then
476      if out="$(env HOME="$home" STRATA_NO_ACQUIRE=1 "$strata" --version 2>&1)"; then rec OK "smoke: strata --version" "$(printf '%s' "$out" | head -n 1)"
477      else printf '%s\n' "$out" | tail -n 5 | sed 's/^/        /'; fail "smoke: strata --version" "the Terminal launcher does not start"; fi
478    fi
479  else
480    rec SKIP "smoke: terminal python" "no bundled python in this archive"
481  fi
482  while IFS= read -r f; do
483    [ -n "$f" ] || continue
484    run_timeout 30 "$f" --version >>"$LOG" 2>&1 || fail "smoke: engine in the Terminal archive" "$f does not start"
485  done < <(find "$root" -type f \( -name strata -o -name strata-device -o -name strata-vision \) -perm -u+x 2>/dev/null | while IFS= read -r c; do file "$c" | grep -q 'Mach-O' && printf '%s\n' "$c"; done)
486}
487
488# ----------------------------------------------------------------------------------------------------------------- the app
489process_app() {
490  local app_src="" appdir="$WORK/app" app version vol dmg_name zip out_dmg mnt bundle_real
491
492  mkdir -p "$appdir"
493  if [ -d "$INPUT" ] && { [[ "$INPUT" == *.app ]] || [[ "$INPUT" == *.app/ ]]; }; then
494    app_src="${INPUT%/}"
495    ditto --norsrc --noextattr --noqtn "$app_src" "$appdir/$(basename "$app_src")" || fail "copy the app" "ditto failed"
496    app="$appdir/$(basename "$app_src")"
497    dmg_name="Strata.dmg"
498    rec OK "copy the app" "from $INPUT"
499  elif [ -f "$INPUT" ] && [[ "$INPUT" == *.dmg ]]; then
500    mnt="$WORK/mnt-in"; mkdir -p "$mnt"
501    logged hdiutil attach -nobrowse -readonly -noautoopen -mountpoint "$mnt" "$INPUT" || fail "open the dmg" "hdiutil attach failed (is it already mounted?)"
502    MOUNTS+=("$mnt")
503    app_src="$(find "$mnt" -maxdepth 1 -name '*.app' -type d | head -n 1)"
504    [ -n "$app_src" ] || fail "open the dmg" "no .app at the top of $INPUT"
505    ditto --norsrc --noextattr --noqtn "$app_src" "$appdir/$(basename "$app_src")" || fail "copy the app" "ditto failed"
506    hdiutil detach "$mnt" >/dev/null 2>&1 || hdiutil detach "$mnt" -force >/dev/null 2>&1
507    app="$appdir/$(basename "$app_src")"
508    dmg_name="$(basename "$INPUT")"
509    rec OK "copy the app out of the dmg" "$(basename "$app") ($(du -sh "$app" | awk '{print $1}'))"
510  else
511    fail "input" "$INPUT is neither a .dmg nor a .app"
512  fi
513  [ -f "$app/Contents/Info.plist" ] || fail "input" "$app has no Contents/Info.plist"
514  xattr -cr "$app" 2>/dev/null
515  version="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$app/Contents/Info.plist" 2>/dev/null || echo "")"
516
517  sign_tree "$app" "app contents"
518  update_engine_manifests "$app" "app"
519  if codesign_item "$app"; then rec OK "sign the .app itself"; else fail "sign the .app itself" "see the log"; fi
520
521  verify_signed "$app" "app"
522  if spctl -a -vvv -t exec "$app" >>"$LOG" 2>&1; then rec OK "spctl -a -vvv app" "accepted"
523  elif [ "$DRY" -eq 1 ]; then rec INFO "spctl -a -vvv app" "rejected, as expected for an ad-hoc dry run"
524  else rec INFO "spctl -a -vvv app" "rejected before notarisation (source=Unnotarized Developer ID); it is checked again after stapling"; fi
525
526  smoke_app "$app"
527  verify_signed "$app" "app after the smoke tests (nothing in the sealed bundle changed)"
528
529  bundle_real="$app"
530  if [ "$DRY" -eq 0 ]; then
531    zip="$WORK/$(basename "$app" .app)-notarize.zip"
532    zip_dir "$app" "$zip" || fail "zip the app for Apple" "ditto failed"
533    notarize "$zip" "app"
534    logged xcrun stapler staple "$app" || fail "staple the app" "stapler failed"
535    logged xcrun stapler validate "$app" || fail "staple the app" "stapler validate failed"
536    rec OK "staple the app"
537    if spctl -a -vvv -t exec "$app" >>"$LOG" 2>&1; then rec OK "spctl -a -vvv app (after notarisation)" "accepted, Notarized Developer ID"
538    else fail "spctl -a -vvv app (after notarisation)" "Gatekeeper still rejects the stapled app"; fi
539    rm -f "$zip"
540  fi
541
542  # the dmg, same layout as apps/desktop/scripts/make-dmg.sh: the app, an Applications link, the volume icon, no Finder arrangement
543  vol="Strata ${version:-app}"
544  mkdir -p "$WORK/final"
545  out_dmg="$WORK/final/$dmg_name"
546  build_dmg "$bundle_real" "$out_dmg" "$vol" || fail "build the dmg" "hdiutil failed (see the log)"
547  rec OK "build the dmg" "$vol"
548  codesign_plain "$out_dmg" || fail "sign the dmg" "see the log"
549  rec OK "sign the dmg"
550  if [ "$DRY" -eq 0 ]; then
551    notarize "$out_dmg" "dmg"
552    logged xcrun stapler staple "$out_dmg" || fail "staple the dmg" "stapler failed"
553    logged xcrun stapler validate "$out_dmg" || fail "staple the dmg" "stapler validate failed"
554    rec OK "staple the dmg"
555    if spctl -a -t open --context context:primary-signature -vv "$out_dmg" >>"$LOG" 2>&1; then rec OK "spctl -a -t open --context context:primary-signature -vv dmg" "accepted"
556    else fail "spctl on the dmg" "Gatekeeper rejects the notarised dmg"; fi
557  else
558    rec INFO "notarise, staple and spctl on the dmg" "skipped in a dry run"
559  fi
560  logged hdiutil verify "$out_dmg" || fail "hdiutil verify" "the dmg is damaged"
561  rec OK "hdiutil verify the dmg"
562
563  # the app inside the finished dmg is still the signed one
564  mnt="$WORK/mnt-out"; mkdir -p "$mnt"
565  if logged hdiutil attach -nobrowse -readonly -noautoopen -mountpoint "$mnt" "$out_dmg"; then
566    MOUNTS+=("$mnt")
567    if logged codesign --verify --deep --strict "$mnt/$(basename "$app")"; then rec OK "the app inside the final dmg verifies"
568    else hdiutil detach "$mnt" -force >/dev/null 2>&1; fail "the app inside the final dmg" "codesign --verify failed"; fi
569    hdiutil detach "$mnt" >/dev/null 2>&1 || hdiutil detach "$mnt" -force >/dev/null 2>&1
570  fi
571  deliver "$out_dmg" "$INPUT"
572  if [ "$UPDATER_ARCHIVE" -eq 1 ]; then make_updater_archive "$bundle_real"; fi
573}
574
575make_updater_archive() {   # the finished (signed, stapled) .app
576  local app=$1 name chk top out
577  name="$(basename "$app" .app).app.tar.gz"
578  out="$WORK/final/$name"
579  rm -f "$out"
580  # the layout Tauri's bundler makes and its updater unpacks: the .app folder at the root of a gzip tar, nothing else
581  # (COPYFILE_DISABLE keeps AppleDouble "._" files out; tar keeps symlinks and permissions)
582  ( cd "$(dirname "$app")" && COPYFILE_DISABLE=1 tar -czf "$out" "$(basename "$app")" ) || fail "pack the updater archive" "tar failed"
583  chk="$WORK/updater-check"; rm -rf "$chk"; mkdir -p "$chk"
584  tar -xzf "$out" -C "$chk" || fail "check the updater archive" "tar cannot unpack it"
585  top="$(ls -A "$chk")"
586  [ "$top" = "$(basename "$app")" ] || fail "check the updater archive" "the archive root holds '$top', not just $(basename "$app")"
587  find "$chk" -name '._*' | grep -q . && fail "check the updater archive" "AppleDouble files in the archive"
588  if logged codesign --verify --deep --strict "$chk/$top"; then rec OK "updater archive: the unpacked app verifies"
589  else fail "updater archive" "codesign --verify failed on the unpacked app"; fi
590  if [ "$DRY" -eq 0 ]; then
591    logged xcrun stapler validate "$chk/$top" || fail "updater archive" "the unpacked app has no valid notarisation ticket"
592    if spctl -a -vvv -t exec "$chk/$top" >>"$LOG" 2>&1; then rec OK "updater archive: spctl accepts the unpacked app" "Notarized Developer ID"
593    else fail "updater archive" "Gatekeeper rejects the unpacked app"; fi
594  else
595    rec INFO "updater archive: notarisation checks" "skipped in a dry run"
596  fi
597  rm -rf "$chk"
598  rec OK "pack the updater archive" "$name"
599  deliver "$out" "$INPUT"
600}
601
602build_dmg() {   # app out.dmg volname
603  local app=$1 out=$2 vol=$3 rw="$WORK/rw.dmg" mnt="$WORK/mnt-build" kb mb n=0 icon
604  kb="$(du -sk "$app" | awk '{print $1}')"; mb=$((kb * 13 / 10240 + 80))
605  rm -f "$rw" "$out"
606  logged hdiutil create -size "${mb}m" -fs HFS+ -volname "$vol" -type UDIF -ov "$rw" || return 1
607  mkdir -p "$mnt"
608  logged hdiutil attach -nobrowse -noautoopen -noverify -mountpoint "$mnt" "$rw" || return 1
609  MOUNTS+=("$mnt")
610  ditto --norsrc --noextattr --noqtn "$app" "$mnt/$(basename "$app")" || return 1
611  ln -s /Applications "$mnt/Applications"
612  icon="$app/Contents/Resources/Strata.icns"
613  if [ -f "$icon" ] && command -v SetFile >/dev/null 2>&1; then cp "$icon" "$mnt/.VolumeIcon.icns" && SetFile -a C "$mnt" 2>/dev/null; fi
614  sync
615  until hdiutil detach "$mnt" >/dev/null 2>&1; do
616    n=$((n + 1)); [ "$n" -lt 6 ] || { hdiutil detach "$mnt" -force >/dev/null 2>&1; break; }
617    sleep 2
618  done
619  logged hdiutil convert "$rw" -format UDZO -imagekey zlib-level=9 -o "$out" || return 1
620  rm -f "$rw"
621}
622
623# ----------------------------------------------------------------------------------------------------------------- the Terminal archive
624repack_nested() {   # extracted root: sign inside .tar.gz/.tgz/.zip archives within the archive (opt-in)
625  local root=$1 a tmp kind
626  while IFS= read -r a; do
627    [ -n "$a" ] || continue
628    tmp="$WORK/nested.$$.$RANDOM"; mkdir -p "$tmp"
629    case "$a" in
630      *.zip) kind=zip; ditto -x -k "$a" "$tmp" ;;
631      *)     kind=tar; tar -xzf "$a" -C "$tmp" ;;
632    esac || { rm -rf "$tmp"; continue; }
633    if [ -z "$(find_macho "$tmp" | head -n 1)" ]; then rm -rf "$tmp"; continue; fi
634    sign_tree "$tmp" "nested $(basename "$a")"
635    update_engine_manifests "$tmp" "nested $(basename "$a")"
636    if [ "$kind" = zip ]; then
637      ( cd "$tmp" && ditto -c -k --norsrc --noextattr --noqtn --noacl . "$a" )
638    else
639      ( cd "$tmp" && COPYFILE_DISABLE=1 tar -czf "$a" . )
640    fi
641    rm -rf "$tmp"
642    say "        re-packed $(basename "$a"); a signed feed that pins its hash (strata-feed.json) must be regenerated and re-signed with the release key"
643  done < <(find "$root" -type f \( -name '*.tar.gz' -o -name '*.tgz' -o -name '*.zip' \) 2>/dev/null)
644}
645
646process_terminal() {
647  local src=$TERMINAL tdir="$WORK/terminal" top stem final notarize_zip name tops nested
648  name="$(basename "$src")"
649  mkdir -p "$tdir"
650  case "$name" in
651    *.zip)          ditto -x -k "$src" "$tdir" || fail "unpack the Terminal archive" "ditto failed" ;;
652    *.tar.gz|*.tgz) tar -xzf "$src" -C "$tdir" || fail "unpack the Terminal archive" "tar failed" ;;
653    *)              fail "unpack the Terminal archive" "$name is not a .zip or .tar.gz" ;;
654  esac
655  rm -rf "$tdir/__MACOSX"
656  xattr -cr "$tdir" 2>/dev/null
657  rec OK "unpack the Terminal archive" "$name"
658
659  if [ -z "$(find_macho "$tdir" | head -n 1)" ]; then
660    nested="$(find "$tdir" -type f \( -name '*.tar.gz' -o -name '*.tgz' -o -name '*.zip' \) 2>/dev/null | wc -l | tr -d ' ')"
661    if [ "$SIGN_NESTED" -eq 0 ] && [ "$nested" -gt 0 ]; then
662      rec INFO "Terminal archive holds no program directly" "it contains $nested nested archive(s) (a feed folder); use --sign-nested to sign inside them"
663    fi
664  fi
665  sign_tree "$tdir" "terminal"
666  update_engine_manifests "$tdir" "terminal"
667  [ "$SIGN_NESTED" -eq 0 ] || repack_nested "$tdir"
668  if [ "$SIGN_NESTED" -eq 0 ]; then
669    nested="$(find "$tdir" -type f \( -name '*.tar.gz' -o -name '*.tgz' \) 2>/dev/null | wc -l | tr -d ' ')"
670    [ "$nested" -eq 0 ] || say "        $nested nested .tar.gz archive(s) were left untouched (they are installed by command-line tools and are not quarantined)"
671  fi
672
673  local bad=0 f
674  while IFS= read -r f; do
675    [ -n "$f" ] || continue
676    codesign --verify --strict "$f" >>"$LOG" 2>&1 || { say "        bad signature: $f"; bad=$((bad + 1)); }
677  done < <(find_macho "$tdir")
678  [ "$bad" -eq 0 ] || fail "codesign --verify --strict (terminal)" "$bad file(s)"
679  rec OK "codesign --verify --strict (terminal)" "every Mach-O"
680
681  smoke_terminal "$tdir"
682
683  # pack it again in the format it came in; Apple only takes a zip, so a tar.gz is notarised through a zip of the same files
684  tops="$(find "$tdir" -mindepth 1 -maxdepth 1 | wc -l | tr -d ' ')"
685  stem="${name%.tar.gz}"; stem="${stem%.tgz}"; stem="${stem%.zip}"
686  mkdir -p "$WORK/final"
687  case "$name" in *.zip) final="$WORK/final/$stem.zip" ;; *) final="$WORK/final/$stem.tar.gz" ;; esac
688  rm -f "$final"
689  notarize_zip="$WORK/$stem-notarize.zip"; rm -f "$notarize_zip"
690  if [ "$tops" -eq 1 ]; then
691    top="$(find "$tdir" -mindepth 1 -maxdepth 1)"
692    zip_dir "$top" "$notarize_zip" || fail "pack the Terminal archive" "ditto failed"
693    case "$name" in *.zip) ;; *) ( cd "$tdir" && COPYFILE_DISABLE=1 tar -czf "$final" "$(basename "$top")" ) || fail "pack the Terminal archive" "tar failed" ;; esac
694  else
695    ( cd "$tdir" && ditto -c -k --norsrc --noextattr --noqtn --noacl . "$notarize_zip" ) || fail "pack the Terminal archive" "ditto failed"
696    case "$name" in *.zip) ;; *) ( cd "$tdir" && COPYFILE_DISABLE=1 tar -czf "$final" . ) || fail "pack the Terminal archive" "tar failed" ;; esac
697  fi
698  case "$name" in *.zip) cp "$notarize_zip" "$final" ;; esac
699  rec OK "pack the Terminal archive" "$(basename "$final")"
700
701  if [ "$DRY" -eq 0 ]; then
702    notarize "$notarize_zip" "terminal"
703    rec INFO "staple the Terminal archive" "not possible for bare programs in a zip; Apple holds the ticket online"
704  else
705    rec INFO "notarise the Terminal archive" "skipped in a dry run"
706  fi
707  deliver "$final" "$src"
708}
709
710# ----------------------------------------------------------------------------------------------------------------- an engine package folder
711# A Mac engine package that Control installs from the update feed (a model shape's engine: its program, its metal/ sources,
712# engine-component.json) as a .tar.gz of ONE folder. The Qwen engine gets its Developer ID signature as a nested program of the signed
713# app; this does the same for a package outside the app. Same identity and options as every nested program above; no entitlements.
714process_engine() {
715  local src=$ENGINE edir="$WORK/engine" name stem top tops final notarize_zip bin f bad=0 n rc
716  name="$(basename "$src")"
717  mkdir -p "$edir"
718  tar -xzf "$src" -C "$edir" || fail "unpack the engine folder" "tar failed"
719  rm -rf "$edir/__MACOSX"
720  xattr -cr "$edir" 2>/dev/null
721  tops="$(find "$edir" -mindepth 1 -maxdepth 1 | wc -l | tr -d ' ')"
722  [ "$tops" -eq 1 ] || fail "unpack the engine folder" "$name must hold exactly one folder at its top, found $tops entries"
723  top="$(find "$edir" -mindepth 1 -maxdepth 1)"
724  [ -d "$top" ] || fail "unpack the engine folder" "$name holds a file at its top, not a folder"
725  [ -f "$top/engine-component.json" ] || fail "unpack the engine folder" "$(basename "$top") has no engine-component.json (is this an engine package?)"
726  rec OK "unpack the engine folder" "$name ($(basename "$top"))"
727
728  n="$(find_macho "$edir" | wc -l | tr -d ' ')"
729  [ "$n" -gt 0 ] || fail "engine folder" "no Mach-O program found in $name"
730  sign_tree "$edir" "engine package"
731  update_engine_manifests "$edir" "engine package"
732
733  while IFS= read -r f; do
734    [ -n "$f" ] || continue
735    codesign --verify --strict "$f" >>"$LOG" 2>&1 || { say "        bad signature: $f"; bad=$((bad + 1)); }
736  done < <(find_macho "$edir")
737  [ "$bad" -eq 0 ] || fail "codesign --verify --strict (engine package)" "$bad file(s)"
738  rec OK "codesign --verify --strict (engine package)" "every Mach-O"
739
740  # the signed program starts under the hardened runtime (a signing mistake kills it at once, exit 137); no model is loaded
741  bin="$(grep -o '"entrypoint"[^,]*' "$top/engine-component.json" 2>/dev/null | sed 's/.*: *"\(.*\)"/\1/' | head -n 1)"
742  if [ -n "$bin" ] && [ -x "$top/$bin" ]; then
743    run_timeout 30 "$top/$bin" --help >"$WORK/engine-help.txt" 2>&1; rc=$?
744    cat "$WORK/engine-help.txt" >>"$LOG"
745    if [ "$rc" -ge 128 ]; then fail "smoke: engine package starts" "$bin was killed (exit $rc) under the hardened runtime"
746    else rec OK "smoke: engine package starts" "$bin, no model loaded"; fi
747  else
748    rec SKIP "smoke: engine package" "no entrypoint program found in engine-component.json"
749  fi
750
751  # pack again (modes kept, no AppleDouble files); Apple takes a zip, so the notarisation goes through a zip of the same folder
752  stem="${name%.tar.gz}"; stem="${stem%.tgz}"
753  case "$stem" in *-unsigned-folder) stem="${stem%-unsigned-folder}-folder" ;; *-folder) ;; *) stem="$stem-signed" ;; esac
754  mkdir -p "$WORK/final"
755  final="$WORK/final/$stem.tar.gz"
756  rm -f "$final"
757  notarize_zip="$WORK/$stem-notarize.zip"; rm -f "$notarize_zip"
758  zip_dir "$top" "$notarize_zip" || fail "pack the engine folder" "ditto failed"
759  ( cd "$edir" && COPYFILE_DISABLE=1 tar -czf "$final" "$(basename "$top")" ) || fail "pack the engine folder" "tar failed"
760  find "$edir" -name '._*' | grep -q . && fail "pack the engine folder" "AppleDouble files in the folder"
761  rec OK "pack the engine folder" "$(basename "$final")"
762
763  if [ "$DRY" -eq 0 ]; then
764    notarize "$notarize_zip" "engine"
765    rec INFO "staple the engine folder" "not possible for bare programs; Apple holds the ticket online"
766  else
767    rec INFO "notarise the engine folder" "skipped in a dry run"
768  fi
769  deliver "$final" "$src"
770}
771
772# ----------------------------------------------------------------------------------------------------------------- run
773if [ -n "$INPUT" ]; then process_app; fi
774if [ -n "$TERMINAL" ]; then process_terminal; fi
775if [ -n "$ENGINE" ]; then process_engine; fi
776finish 0