Eric Bower
·
2026-07-21
1#!/bin/sh
2#
3# rotate keys and reencrypt passwords
4#
5# Reuse identities file: export PA_IDENTITIES=~/.local/share/pa/identities
6# Reuse recipients file: export PA_RECIPIENTS=~/.local/share/pa/recipients
7
8die() {
9 printf '%s: %s.\n' "$(basename "$0")" "$1" >&2
10 exit 1
11}
12
13age=$(command -v age || command -v rage) ||
14 die "age not found, install per https://age-encryption.org"
15
16age_keygen=$(command -v age-keygen || command -v rage-keygen) ||
17 die "age-keygen not found, install per https://age-encryption.org"
18
19# Restrict permissions of any new files to only the current user.
20umask 077
21
22: "${PA_DIR:=${XDG_DATA_HOME:-$HOME/.local/share}/pa}"
23
24realstore=$(realpath "$PA_DIR/passwords") ||
25 die "couldn't get path to password directory"
26
27tmpdir=$PA_DIR/tmp
28
29mkdir "$tmpdir" ||
30 die "couldn't create temporary directory"
31
32trap 'rm -rf "$tmpdir"; exit' EXIT
33trap 'rm -rf "$tmpdir"; trap - INT; kill -s INT 0' INT
34
35cp -Rp "$realstore" "$tmpdir/passwords" ||
36 die "couldn't copy password directory"
37
38# Remove git repository for forward secrecy.
39rm -rf "$tmpdir/passwords/.git"
40
41[ "$PA_IDENTITIES" ] && cp "$PA_IDENTITIES" "$tmpdir/identities"
42[ "$PA_RECIPIENTS" ] && cp "$PA_RECIPIENTS" "$tmpdir/recipients"
43
44$age_keygen >>"$tmpdir/identities" 2>/dev/null
45$age_keygen -y "$tmpdir/identities" >>"$tmpdir/recipients" 2>/dev/null
46
47pa l | while read -r name; do
48 pa s "$name" |
49 $age -R "$tmpdir/recipients" -o "$tmpdir/passwords/$name.age" ||
50 die "couldn't encrypt $name.age"
51done
52
53trap - INT EXIT
54
55rm -rf "$realstore" ||
56 die "couldn't remove password directory"
57
58mv "$tmpdir/passwords" "$realstore"
59mv "$tmpdir/identities" "$(realpath "$PA_DIR/identities")"
60mv "$tmpdir/recipients" "$(realpath "$PA_DIR/recipients")"
61rmdir "$tmpdir"
62
63# Recreate git repository if needed.
64pa l >/dev/null
65