AnyBot/deploy/mac/sign.sh

58 lines
2.3 KiB
Bash
Raw Permalink Normal View History

#!/bin/sh
# Sign AnyBot.app with this Mac's own signing key, the same one every build:
# deploy/mac/sign.sh dist/AnyBot.app
# macOS keeps 輔助使用 / 螢幕錄製 for an app by its signature. Signed "ad hoc", every build was a
# new app to it, so each update quietly lost those permissions and the bots could no longer read
# or operate other apps (agent-desktop answered PERM_DENIED). One fixed self-signed key, kept in
# its own keychain under AnyBot's folder (the login keychain is not touched), keeps them.
# Anything going wrong falls back to ad hoc signing.
set -u
APP=${1:?app}
DIR="$HOME/Library/Application Support/AnyBot/signing"
KC="$DIR/anybot-signing.keychain-db"
PWF="$DIR/keychain-password"
NAME="AnyBot Local Signing"
make_key() {
mkdir -p "$DIR" && chmod 700 "$DIR" || return 1
head -c 24 /dev/urandom | base64 > "$PWF" && chmod 600 "$PWF" || return 1
PW=$(cat "$PWF")
T=$(mktemp -d)
cat > "$T/cert.cnf" <<CNF
[req]
distinguished_name=dn
x509_extensions=ext
prompt=no
[dn]
CN=$NAME
[ext]
keyUsage=critical,digitalSignature
extendedKeyUsage=critical,codeSigning
basicConstraints=critical,CA:false
CNF
ok=1
/usr/bin/openssl req -x509 -newkey rsa:2048 -nodes -keyout "$T/key.pem" -out "$T/cert.pem" -days 7300 -config "$T/cert.cnf" >/dev/null 2>&1 \
&& /usr/bin/openssl pkcs12 -export -inkey "$T/key.pem" -in "$T/cert.pem" -out "$T/id.p12" -passout pass:"$PW" >/dev/null 2>&1 \
&& security create-keychain -p "$PW" "$KC" >/dev/null \
&& security set-keychain-settings "$KC" \
&& security unlock-keychain -p "$PW" "$KC" \
&& security import "$T/id.p12" -k "$KC" -P "$PW" -T /usr/bin/codesign >/dev/null \
&& security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$PW" "$KC" >/dev/null 2>&1 \
&& ok=0
rm -rf "$T"
return $ok
}
signed=1
if [ -f "$KC" ] || make_key; then
if security unlock-keychain -p "$(cat "$PWF")" "$KC" 2>/dev/null \
&& codesign --force --deep --keychain "$KC" -s "$NAME" "$APP" 2>/dev/null; then
signed=0
echo "已用這台 Mac 固定的簽章簽好(更新後「輔助使用」「螢幕錄製」權限會保留)"
fi
fi
if [ $signed -ne 0 ]; then
codesign --force --deep -s - "$APP"
echo "注意:用臨時簽章(更新後要重新允許「輔助使用」「螢幕錄製」)"
fi