small pixel drawing of a pufferfish pa

contrib/pa-rekey

#!/bin/sh
#
# rotate keys and reencrypt passwords
#
# Reuse identities file: export PA_IDENTITIES=~/.local/share/pa/identities
# Reuse recipients file: export PA_RECIPIENTS=~/.local/share/pa/recipients

die() {
    printf 'error: %s.\n' "$1" >&2
    exit 1
}

age=$(command -v age || command -v rage) ||
    die "age not found, install per https://age-encryption.org"

age_keygen=$(command -v age-keygen || command -v rage-keygen) ||
    die "age-keygen not found, install per https://age-encryption.org"

# Restrict permissions of any new files to only the current user.
umask 077

basedir=${XDG_DATA_HOME:=$HOME/.local/share}/pa
: "${PA_DIR:=$basedir/passwords}"

mkdir "$basedir/tmp" ||
    die "Couldn't create temporary directory"

trap 'rm -rf "$basedir/tmp"; exit' EXIT
trap 'rm -rf "$basedir/tmp"; trap - INT; kill -s INT 0' INT

cp -R "$PA_DIR" "$basedir/tmp/passwords" ||
    die "Couldn't copy password directory"

# Remove git repository for forward secrecy.
rm -rf "$basedir/tmp/passwords/.git"

[ "$PA_IDENTITIES" ] && cp "$PA_IDENTITIES" "$basedir/tmp/identities"
[ "$PA_RECIPIENTS" ] && cp "$PA_RECIPIENTS" "$basedir/tmp/recipients"

$age_keygen >>"$basedir/tmp/identities" 2>/dev/null
$age_keygen -y "$basedir/tmp/identities" >>"$basedir/tmp/recipients" 2>/dev/null

pa list | while read -r name; do
    pa show "$name" | $age -R "$basedir/tmp/recipients" -o "$basedir/tmp/passwords/$name.age" ||
        die "Couldn't encrypt $name.age"
done

trap - INT EXIT

rm -rf "$PA_DIR"
mv "$basedir/tmp/passwords" "$PA_DIR"
mv "$basedir/tmp/identities" "$basedir/identities"
mv "$basedir/tmp/recipients" "$basedir/recipients"
rmdir "$basedir/tmp"

# Recreate git repository if needed.
pa list >/dev/null