Repository Public
1#!/bin/zsh2# Nightly encrypted backup with verification.3# database -> pg_dump, encrypted with AES-256 (key: ~/.config/sp-message/backup.key)4# blobs -> rsync snapshot (the objects are already ciphertext produced in browsers)5# Verification: the archive is decrypted and restored into a scratch database, and row counts are compared.6set -euo pipefail7export PATH="/opt/homebrew/bin:/opt/homebrew/opt/postgresql@17/bin:/usr/bin:/bin:/usr/sbin:/sbin"8DB="${SPM_DB:-sp_message}"9DATA="${SPM_DATA_DIR:-$HOME/sp-message-data}"10OUT="$HOME/backups/sp-message"11KEY="$HOME/.config/sp-message/backup.key"12STAMP=$(date -u +%Y%m%dT%H%M%SZ)13mkdir -p "$OUT/blobs"14F="$OUT/db-$STAMP.dump.enc"15pg_dump -Fc "$DB" | openssl enc -aes-256-cbc -pbkdf2 -iter 200000 -salt -pass "file:$KEY" -out "$F"16rsync -a --delete "$DATA/blobs/" "$OUT/blobs/"1718SCRATCH="sp_message_verify_$$"19createdb "$SCRATCH"20trap 'dropdb --if-exists "$SCRATCH"' EXIT21openssl enc -d -aes-256-cbc -pbkdf2 -iter 200000 -pass "file:$KEY" -in "$F" | pg_restore --no-owner -d "$SCRATCH"22for t in users devices conversations messages files; do23 a=$(psql -tAc "select count(*) from $t" "$DB"); b=$(psql -tAc "select count(*) from $t" "$SCRATCH")24 # the live database may have grown during the dump: the restored count must not exceed it and must not be empty when live is not25 if [ "$b" -gt "$a" ] || { [ "$a" -gt 0 ] && [ "$b" -eq 0 ]; }; then echo "BACKUP VERIFICATION FAILED on $t (live $a, restored $b)"; exit 1; fi26done27ls -1t "$OUT"/db-*.dump.enc | tail -n +15 | xargs -r rm -f28echo "$(date -u +%FT%TZ) backup ok: $F ($(du -h "$F" | cut -f1)), restore verified"29