Files
omarchycn/bin/omarchy-system-factory-reset-finish
T
6fa4f78ee1 Add deferred first-boot provisioning and factory reset (#6621)
* Add OEM first-boot setup and factory reset

An OEM-mode ISO install (or omarchy-reset-computer) leaves the machine in OEM
state: fully installed, no user, /var/lib/omarchy/oem/pending armed. On the
next boot omarchy-oem-setup.service runs the configurator's user form on tty1,
creates the user with the groups system setup recorded, finalizes it offline
from the stashed Node tarball, re-keys LUKS from the throwaway install
passphrase to the user's password, and hands off to SDDM.

omarchy-reset-computer returns a machine to that state: it swaps the running
root for a fresh clone of the @factory snapshot the ISO takes at install time,
scrubs machine identity and prior users, and stages omarchy-factory-wipe to
drop the old root and recreate @home/@log on the next boot. Machines installed
before @factory existed get a degraded reset (current system kept, users and
state wiped) with that caveat surfaced in the confirmation.

omarchy-setup-system/-hardware gain --oem to run without an install user; the
group-granting install scripts now record their groups in
/var/lib/omarchy/oem/groups and only call usermod when the user exists.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Harden OEM setup: correct cryptsetup key-file usage, retry on failure

cryptsetup reads --test-passphrase/--key-file inputs byte-for-byte, so feed
passphrases through process substitution consistently instead of positional
args or stdin (which has different newline semantics). Run each first-boot
setup attempt as its own process so a failure offers a retry instead of
stranding the machine at a user-less login screen — bash ignores errexit
inside `while !` conditions, a child process does not.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Always grant wheel sudo in OEM first-boot setup

Detecting an existing %wheel grant by grepping sudoers is error-prone:
omarchy ships narrow '%wheel ALL=(ALL) NOPASSWD: <command>' rules (e.g.
asdcontrol) that match the naive pattern, which left the OEM-created user
matching sudoers entries but unable to run anything. Write the drop-in
unconditionally — a duplicate of an existing full grant is harmless.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Fix LUKS re-key device resolution and OEM state readability

archinstall's encrypted installs put cryptdevice=PARTUUID=... on the kernel
cmdline, not UUID=, so the first-boot re-key never found its device and
silently skipped — leaving the throwaway auto-unlock keyfile in place, i.e.
the disk effectively unencrypted. Parse every cryptdevice= source spec form
and make any re-key failure abort the attempt loudly: a retry prompt beats a
machine that quietly boots without a passphrase forever.

The OEM state directory also has to be world-readable (its one secret,
luks-key, stays 0600): user finalization reads the stashed Node tarball as
the new user, and the 0700 directory forced it onto the network fallback.

Step markers now land in /var/log/omarchy-oem-setup.log for debuggability.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Purge stale machine-id boot entries when resetting or re-keying

limine-entry-tool keys its limine.conf OS entries by machine-id. A factory
reset gives the machine a fresh identity, so the previous system's entry
survived every rebuild, sorted first, and made Limine stop at a Blake2b
hash-mismatch warning once the UKI was rebuilt. Start limine.conf over from
the shipped template (and drop foreign machine-id history directories on the
ESP) before any post-reset rebuild: in the staged chroot rebuild, in the
first-boot LUKS re-key, and — for unencrypted resets, where nothing else
rebuilds — in a dedicated first-boot refresh when foreign entries are found.

The staged rebuild also verifies every UKI hash referenced by limine.conf
against the file on the ESP before the subvolume swap, and the running
system's limine-snapper-sync is runtime-masked during staging so it cannot
rewrite the config behind the rebuild.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Harden reset and first-boot setup failure paths

Review findings from codex and Copilot:

- Generate throwaway passphrases without a trailing head stage: under
  pipefail, SIGPIPE from the infinite tr failed the substitution and errexit
  aborted every encrypted reset before it could stage anything.
- Stage the fallible parts of a degraded reset (LUKS re-key, boot rebuild)
  before arming the wipe, so a staging failure leaves the machine untouched
  instead of scheduling a wipe for a reset that never finished.
- Gate first-boot setup on the factory wipe having succeeded
  (ConditionPathExists=!wipe-pending plus an in-script guard): creating the
  new user on a half-wiped system would hand their data to the wipe retry.
- Abort the wipe (keeping its retry marker) when deleting the old root or
  recreating @home/@log fails, and abort resets that cannot remove a prior
  account — a surviving account keeps its password and wheel membership.
- Resume a partially-created account on setup retry instead of rejecting the
  username the failed attempt just created.
- Only purge machine-id directories the old limine.conf actually referenced;
  a shared ESP may hold other installations' boot artifacts.
- Recreate the hibernation swapfile (nested subvolume, so never captured by
  the factory snapshot) inside the factory root before its UKI rebuild, so a
  reset machine keeps disk-backed swap and a valid resume offset.
- Source base-test.sh in the OEM groups test per test conventions.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Recreate the hibernation swapfile even when resume drop-ins survive

omarchy-hibernation-setup short-circuits as 'already set up' when the resume
mkinitcpio drop-in exists — which it always does in a factory root, while the
swapfile itself never survives the snapshot (nested subvolume). Drop the
marker when the swapfile is gone so setup reconfigures from scratch, and
verify the swapfile actually exists before proceeding with the reset.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Second review pass: encrypted-config coverage, factory-baseline sanitization, recoverable rekey

Codex xhigh round 2:

- Detect the LUKS backing device by walking the root's device tree, not only
  the cmdline cryptdevice=; reset/first-boot now re-key roots reached via
  rd.luks/crypttab too, instead of silently leaving the seller's slots valid.
- Sanitize the retained @factory baseline (accounts, /etc/shadow, machine
  identity) during a full reset: the new wheel user could otherwise mount it
  to recover the seller's data, and a second reset would restore the account.
- Re-key the disk recoverably: rebuild the no-auto-unlock UKI before killing
  the throwaway slot or destroying the staged key, and restore the keyfile if
  that rebuild fails, so a retry with a different password can never leave the
  disk locked to the first attempt's password.
- Roll back a degraded reset's live-root auto-unlock material if its boot
  rebuild fails, instead of leaving it for a later rebuild to embed.
- Treat a missing current-machine limine entry as stale so a retry after a
  failed rebuild repairs the config instead of clearing OEM state over it.
- Erase fingerprint enrollments (/var/lib/fprint) in degraded wipes.
- Remove the resume-offset drop-in too when recreating the factory swapfile,
  so the rebuilt UKI gets a correct offset.
- Pin first-boot retries to the account the first attempt created.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Expose factory reset in the Setup menu

Add a 'Reset Computer' entry under Setup (Omarchy's Settings menu, where OS
factory resets conventionally live), guarded to btrfs roots and launched in a
floating terminal. omarchy-reset-computer now self-elevates via sudo so the
menu entry needs no sudo prefix, forwarding the caller's gum theme env as
env arguments so styling survives an env_reset sudoers. The typed 'reset'
confirmation and the sudo password prompt remain as the guards against
accidental triggering.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Defer keyboard selection to first boot for OEM installs

The OEM first-boot setup now runs a keyboard step before the user form,
mirroring the ISO configurator: it loads the chosen layout on the live VT so
the password (and the LUKS re-key that follows) are typed under it, and
persists it with systemd-firstboot so the installed system gets both the
console KEYMAP and the XKB layout Hyprland reads — exactly what a normal
install writes. Layouts localectl doesn't know keep the default, same as the
installer.

This lets the OEM operator set nothing user-specific: the machine's owner
picks their keyboard alongside their account at first boot.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Rename factory-reset commands to omarchy-system-factory-reset[-finish]

omarchy-reset-computer      -> omarchy-system-factory-reset
omarchy-factory-wipe        -> omarchy-system-factory-reset-finish
(and its systemd unit, log path, and temp mount to match)

Pure rename: every reference — the Setup menu action, the first-boot finish
service the reset stages and enables, the oem-setup ordering/gating, comments,
and the menu test — moves together, with no behavior change.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Rename OEM vocabulary to provisioning (runtime)

Commands unify under the provisioning family:
  omarchy-oem-setup      → omarchy-provision-owner
  omarchy-finalize-user  → omarchy-provision-user
  omarchy-first-run      → omarchy-provision-first-run

And the deferred-provisioning state/vocabulary replaces 'OEM':
  /var/lib/omarchy/oem/          → /var/lib/omarchy/provisioning/
  /etc/omarchy/oem.key           → /etc/omarchy/provisioning.key
  install/oem/                   → install/provisioning/
  OMARCHY_SETUP_CONTEXT=oem-firstboot → provision-owner
  omarchy-setup-system/-hardware --oem → --defer-provisioning

All callers (provision-first-run→provision-user, autostart, factory-reset
staging the provisioning units, the group-recording scripts) and comments
move together.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Drop remaining OEM mentions from the provisioning groups test

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Finish the omarchy-first-run rename in the docs

Two doc references to omarchy-first-run were missed when the script was renamed
to omarchy-provision-first-run; update them to match.

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 21:54:21 +02:00

172 lines
5.4 KiB
Bash
Executable File

#!/bin/bash
# omarchy:summary=First-boot worker that finishes an omarchy-system-factory-reset reset
# omarchy:group=setup
# omarchy:requires-sudo=true
# omarchy:examples=omarchy-system-factory-reset-finish
# Runs once, early on the first boot after omarchy-system-factory-reset, via
# omarchy-system-factory-reset-finish.service (armed by /var/lib/omarchy/provisioning/wipe-pending).
# Ordered before home.mount/var-log.mount so @home and @log can be dropped and
# recreated as empty subvolumes instead of rm -rf'd file by file.
#
# Two modes:
# - full reset: the root is already a fresh clone of @factory (staged by
# omarchy-system-factory-reset); this deletes the previous root (@omarchy-old-*),
# recreates @home/@log, and repairs /.snapshots.
# - degraded (wipe-degraded marker): machines installed before @factory
# existed keep their current root; user accounts and identity state are
# scrubbed here instead.
set -uo pipefail
PROVISIONING_DIR=/var/lib/omarchy/provisioning
TOP_MNT=/run/omarchy-system-factory-reset-finish-top
[[ -f $PROVISIONING_DIR/wipe-pending ]] || exit 0
if (( EUID != 0 )); then
echo "Error: omarchy-system-factory-reset-finish must run as root" >&2
exit 1
fi
# This runs before var-log.mount, so a log file under /var/log would be
# shadowed (and @log is recreated below anyway). stdout goes to the journal,
# which is volatile in /run this early and flushed into the fresh @log later.
echo "=== Omarchy factory wipe started: $(date '+%Y-%m-%d %H:%M:%S') ==="
log() {
echo "factory-wipe: $1"
}
root_device() {
findmnt -no SOURCE / | sed 's/\[.*\]//'
}
abort() {
# Keep wipe-pending so the wipe retries next boot, and so provisioning stays
# gated (it refuses to create a user on a half-wiped system).
log "$1 — aborting; the wipe will retry on the next boot"
umount "$TOP_MNT" 2>/dev/null || true
rmdir "$TOP_MNT" 2>/dev/null || true
exit 1
}
delete_subvolume() {
local path="$1"
[[ -d $path ]] || return 0
if ! btrfs subvolume delete --recursive "$path" 2>/dev/null; then
# Older btrfs-progs without --recursive: delete nested subvolumes deepest
# first, then the subvolume itself.
local nested
nested=$(btrfs subvolume list -o "$path" 2>/dev/null | awk '{print $NF}')
if [[ -n $nested ]]; then
local sub
while IFS= read -r sub; do
delete_subvolume "$TOP_MNT/${sub#<FS_TREE>/}"
done <<<"$nested"
fi
btrfs subvolume delete "$path"
fi
}
recreate_subvolume() {
local name="$1"
delete_subvolume "$TOP_MNT/$name"
btrfs subvolume create "$TOP_MNT/$name"
}
scrub_degraded_state() {
log "degraded reset: scrubbing user accounts and machine identity in place"
local user
for user in $(awk -F: '$3 >= 1000 && $3 < 60000 { print $1 }' /etc/passwd); do
log "removing user $user"
rm -rf "/var/lib/fprint/$user" # enrolled fingerprints outlive userdel
userdel "$user" 2>/dev/null || abort "could not remove user $user"
done
rm -f /etc/ssh/ssh_host_*
rm -f /etc/NetworkManager/system-connections/*
rm -rf /var/lib/NetworkManager/* /var/lib/tailscale /var/lib/iwd
rm -f /var/lib/sddm/state.conf /etc/sddm.conf.d/autologin.conf
# Fresh machine identity from the next boot on.
systemd-id128 new >/etc/machine-id 2>/dev/null || :>/etc/machine-id
}
repair_snapshots_dir() {
# A snapshot of @ carries /.snapshots only as a plain empty directory
# (nested subvolumes are not part of snapshots). Snapper needs it to be a
# subvolume again.
if [[ -d /.snapshots ]] && ! btrfs subvolume show /.snapshots >/dev/null 2>&1; then
rm -rf /.snapshots
fi
if [[ ! -d /.snapshots ]]; then
btrfs subvolume create /.snapshots
chmod 750 /.snapshots
fi
}
wipe_snapper_snapshots() {
# Degraded resets keep the current root, so its accumulated snapper
# snapshots (nested under /.snapshots) still exist. Full resets already lost
# them with the old root.
local snapshot
for snapshot in /.snapshots/*/snapshot; do
[[ -d $snapshot ]] || continue
delete_subvolume "$snapshot"
rm -rf "$(dirname "$snapshot")"
done
}
main() {
local device
device=$(root_device)
if [[ -z $device ]]; then
log "could not determine the btrfs root device; aborting"
exit 1
fi
mkdir -p "$TOP_MNT"
if ! mount -o subvolid=5 "$device" "$TOP_MNT"; then
log "could not mount the btrfs top level from $device; aborting"
exit 1
fi
if [[ -f $PROVISIONING_DIR/wipe-degraded ]]; then
scrub_degraded_state
wipe_snapper_snapshots
fi
local old
for old in "$TOP_MNT"/@omarchy-old-*; do
[[ -d $old ]] || continue
log "deleting previous system root $(basename "$old")"
delete_subvolume "$old" || abort "could not delete $(basename "$old")"
done
# A wipe that cannot recreate @home has not wiped anything — the seller's
# data would survive a "successful" factory reset.
log "recreating @home and @log"
recreate_subvolume @home || abort "could not recreate @home"
recreate_subvolume @log || abort "could not recreate @log"
repair_snapshots_dir
umount "$TOP_MNT"
rmdir "$TOP_MNT" 2>/dev/null || true
log "trimming free space"
fstrim -a 2>/dev/null || true
rm -f "$PROVISIONING_DIR/wipe-pending" "$PROVISIONING_DIR/wipe-degraded"
rm -f /etc/systemd/system/sysinit.target.wants/omarchy-system-factory-reset-finish.service
rm -f /etc/systemd/system/omarchy-system-factory-reset-finish.service
log "factory wipe complete"
}
main