#!/bin/bash set -euo pipefail identity='Parcel Development' keychain="$HOME/Library/Keychains/login.keychain-db" if [[ ! -t 0 ]]; then echo 'Run this script in a terminal to confirm keychain changes.' >&2 exit 1 fi printf 'Create and trust "%s" in your login keychain? [y/N] ' "$identity" >&2 read -r answer if [[ $answer != y && $answer != Y && $answer != yes && $answer != YES ]]; then echo 'No changes made.' >&2 exit 1 fi if security find-certificate -c "$identity" "$keychain" >/dev/null 2>&1; then echo "A certificate named $identity already exists in your login keychain; refusing to replace it." >&2 exit 1 fi umask 077 work=$(mktemp -d "${TMPDIR:-/tmp}/parcel-cert.XXXXXX") trap 'rm -rf "$work"' EXIT export PARCEL_P12_PASSWORD PARCEL_P12_PASSWORD=$(openssl rand -hex 32) if ! openssl req -new -x509 -newkey rsa:2048 -nodes -sha256 -days 3650 \ -subj "/CN=$identity" \ -addext 'basicConstraints=critical,CA:TRUE' \ -addext 'keyUsage=critical,digitalSignature,keyCertSign' \ -addext 'extendedKeyUsage=codeSigning' \ -keyout "$work/key.pem" -out "$work/cert.pem" 2> "$work/openssl.log"; then /bin/cat "$work/openssl.log" >&2 exit 1 fi openssl pkcs12 -export -inkey "$work/key.pem" -in "$work/cert.pem" \ -name "$identity" -descert -keypbe PBE-SHA1-3DES -macalg sha1 \ -passout env:PARCEL_P12_PASSWORD -out "$work/identity.p12" security import "$work/identity.p12" -k "$keychain" -f pkcs12 \ -P "$PARCEL_P12_PASSWORD" -T /usr/bin/codesign security add-trusted-cert -r trustRoot -p codeSign -k "$keychain" "$work/cert.pem" fingerprint=$(openssl x509 -in "$work/cert.pem" -noout -sha1 -fingerprint | cut -d= -f2 | tr -d ':') if ! security find-identity -v -p codesigning "$keychain" | grep -Fq "$fingerprint"; then echo 'Certificate was imported but is not a valid code signing identity. Check its trust and private key in Keychain Access.' >&2 exit 1 fi printf 'Use PARCEL_SIGN_IDENTITY="%s" for local builds. Keep this identity to preserve grants.\n' "$fingerprint"