From b63374f388dfb451e2b4686752024ce94c8e0f56 Mon Sep 17 00:00:00 2001 From: "J. S. Brown" Date: Fri, 21 Aug 2026 16:29:43 -0700 Subject: [PATCH 001/194] Remember wallpaper choices per theme --- bin/omarchy-theme-set | 63 ++++++++++--- test/shell.d/theme-background-memory-test.sh | 96 ++++++++++++++++++++ 2 files changed, 145 insertions(+), 14 deletions(-) create mode 100644 test/shell.d/theme-background-memory-test.sh diff --git a/bin/omarchy-theme-set b/bin/omarchy-theme-set index d987d97aa675..2637ac681747 100755 --- a/bin/omarchy-theme-set +++ b/bin/omarchy-theme-set @@ -10,8 +10,10 @@ if [[ -z $1 ]]; then fi CURRENT_THEME_PATH="$HOME/.local/state/omarchy/current/theme" +CURRENT_THEME_NAME_PATH="$HOME/.local/state/omarchy/current/theme.name" NEXT_THEME_PATH="$HOME/.local/state/omarchy/current/next-theme" CURRENT_BACKGROUND_LINK="$HOME/.local/state/omarchy/current/background" +THEME_BACKGROUND_STATE_PATH="$HOME/.local/state/omarchy/theme-backgrounds" BACKGROUND_TRANSITION_CACHE="$HOME/.cache/omarchy/background-transitions" THEME_SET_LOCK="${XDG_RUNTIME_DIR:-/tmp}/omarchy-theme-set.lock" USER_THEMES_PATH="$HOME/.config/omarchy/themes" @@ -56,9 +58,27 @@ snapshot_current_background() { snapshot_background_path "$current_background" "previous" } +theme_background_state_file() { + local theme="$1" + + [[ -n $theme && ${theme##*/} == $theme && $theme != "." && $theme != ".." ]] || return 1 + printf '%s/%s\n' "$THEME_BACKGROUND_STATE_PATH" "$theme" +} + +remember_current_theme_background() { + local current_background state_file + + state_file=$(theme_background_state_file "$PREVIOUS_THEME_NAME") || return + current_background=$(readlink -f "$CURRENT_BACKGROUND_LINK" 2>/dev/null || true) + [[ -f $current_background ]] || return + + mkdir -p "$THEME_BACKGROUND_STATE_PATH" + printf '%s\n' "$current_background" >"$state_file" +} + choose_theme_background() { local backgrounds=() - local current_background index next_index i + local current_background remembered_background state_file index next_index i CHOSEN_THEME_BACKGROUND="" mapfile -d '' -t backgrounds < <( @@ -69,21 +89,33 @@ choose_theme_background() { (( ${#backgrounds[@]} > 0 )) || return 1 - current_background=$(readlink "$CURRENT_BACKGROUND_LINK" 2>/dev/null || true) - index=-1 - for i in "${!backgrounds[@]}"; do - if [[ ${backgrounds[$i]} == $current_background ]]; then - index=$i - break + if [[ $PREVIOUS_THEME_NAME == "$THEME_NAME" ]]; then + current_background=$(readlink "$CURRENT_BACKGROUND_LINK" 2>/dev/null || true) + index=-1 + for i in "${!backgrounds[@]}"; do + if [[ ${backgrounds[$i]} == $current_background ]]; then + index=$i + break + fi + done + + if (( index != -1 )); then + next_index=$(((index + 1) % ${#backgrounds[@]})) + CHOSEN_THEME_BACKGROUND="${backgrounds[$next_index]}" + else + CHOSEN_THEME_BACKGROUND="${backgrounds[0]}" fi - done + return + fi - if (( index == -1 )); then - CHOSEN_THEME_BACKGROUND="${backgrounds[0]}" - else - next_index=$(((index + 1) % ${#backgrounds[@]})) - CHOSEN_THEME_BACKGROUND="${backgrounds[$next_index]}" + state_file=$(theme_background_state_file "$THEME_NAME" 2>/dev/null || true) + remembered_background=$(cat "$state_file" 2>/dev/null || true) + if [[ -f $remembered_background ]]; then + CHOSEN_THEME_BACKGROUND="$remembered_background" + return fi + + CHOSEN_THEME_BACKGROUND="${backgrounds[0]}" } set_theme_background_link() { @@ -139,6 +171,9 @@ fi exec 9>"$THEME_SET_LOCK" flock 9 +PREVIOUS_THEME_NAME=$(cat "$CURRENT_THEME_NAME_PATH" 2>/dev/null || true) +remember_current_theme_background + # Setup clean next theme directory (for atomic theme config swapping) rm -rf "$NEXT_THEME_PATH" mkdir -p "$NEXT_THEME_PATH" @@ -165,7 +200,7 @@ rm -rf "$CURRENT_THEME_PATH" mv "$NEXT_THEME_PATH" "$CURRENT_THEME_PATH" # Store theme name for reference -echo "$THEME_NAME" >"$HOME/.local/state/omarchy/current/theme.name" +echo "$THEME_NAME" >"$CURRENT_THEME_NAME_PATH" # Make the running shell pick up the new palette immediately while the rest of # the theme hooks run. diff --git a/test/shell.d/theme-background-memory-test.sh b/test/shell.d/theme-background-memory-test.sh new file mode 100644 index 000000000000..53304c251c5c --- /dev/null +++ b/test/shell.d/theme-background-memory-test.sh @@ -0,0 +1,96 @@ +#!/bin/bash + +set -euo pipefail + +source "$(dirname "$0")/base-test.sh" + +test_tmp=$(mktemp -d) +trap 'rm -rf "$test_tmp"' EXIT + +test_home="$test_tmp/home" +runtime_dir="$test_tmp/runtime" +current_state="$test_home/.local/state/omarchy/current" +background_state="$test_home/.local/state/omarchy/theme-backgrounds" +mkdir -p "$test_home" "$runtime_dir" + +set_theme() { + HOME="$test_home" XDG_RUNTIME_DIR="$runtime_dir" OMARCHY_PATH="$ROOT" PATH="$ROOT/bin:$PATH" \ + OMARCHY_THEME_HEADLESS=1 "$ROOT/bin/omarchy-theme-set" "$1" >/dev/null +} + +current_background_name() { + basename "$(readlink "$current_state/background")" +} + +theme_a="tokyo-night" +theme_b="catppuccin" + +set_theme "$theme_a" +mapfile -t theme_a_backgrounds < <(find "$current_state/theme/backgrounds" -maxdepth 1 -type f -print | sort) +(( ${#theme_a_backgrounds[@]} > 1 )) || fail "test theme has multiple backgrounds" +theme_a_first=${theme_a_backgrounds[0]##*/} +theme_a_selected_path=${theme_a_backgrounds[1]} +theme_a_selected=${theme_a_selected_path##*/} +ln -nsf "$theme_a_selected_path" "$current_state/background" + +set_theme "$theme_b" +mapfile -t theme_b_backgrounds < <(find "$current_state/theme/backgrounds" -maxdepth 1 -type f -print | sort) +(( ${#theme_b_backgrounds[@]} > 1 )) || fail "second test theme has multiple backgrounds" +theme_b_first=${theme_b_backgrounds[0]##*/} + +common_background=$(comm -12 \ + <(find "$ROOT/themes/$theme_a/backgrounds" -maxdepth 1 -type f -printf '%f\n' | sort) \ + <(find "$current_state/theme/backgrounds" -maxdepth 1 -type f -printf '%f\n' | sort) | head -n 1) +[[ -n $common_background ]] || fail "test themes share a background filename" +theme_b_common_path=$(find "$current_state/theme/backgrounds" -maxdepth 1 -type f -name "$common_background" -print -quit) +ln -nsf "$theme_b_common_path" "$current_state/background" + +[[ $(<"$background_state/$theme_a") == "$theme_a_selected_path" ]] || fail "theme switch remembers the outgoing background path" +pass "theme switch remembers the outgoing background path" + +set_theme "$theme_a" +[[ $(current_background_name) == "$theme_a_selected" ]] || fail "shared filenames do not override the remembered background" +pass "shared filenames do not override the remembered background" + +set_theme "$theme_b" +[[ $(current_background_name) == "$common_background" ]] || fail "themes remember backgrounds independently" +pass "themes remember backgrounds independently" + +external_background="$test_tmp/external-background.webp" +cp "$(readlink -f "$current_state/background")" "$external_background" +ln -nsf "$external_background" "$current_state/background" +set_theme "$theme_a" +set_theme "$theme_b" +[[ $(readlink -f "$current_state/background") == "$external_background" ]] || fail "theme switch restores an external background path" +pass "theme switch restores an external background path" + +set_theme "$theme_b" +[[ $(current_background_name) == "$theme_b_first" ]] || fail "reapplying a theme with an external background falls back to the first image" +pass "reapplying a theme with an external background falls back to the first image" + +set_theme "$theme_a" +user_background_dir="$test_home/.config/omarchy/backgrounds/$theme_a" +user_background="$user_background_dir/$theme_a_first" +mkdir -p "$user_background_dir" +cp "${theme_a_backgrounds[0]}" "$user_background" +ln -nsf "$user_background" "$current_state/background" +set_theme "$theme_b" +set_theme "$theme_a" +[[ $(readlink -f "$current_state/background") == "$user_background" ]] || fail "theme switch distinguishes duplicate background filenames" +pass "theme switch distinguishes duplicate background filenames" + +set_theme "$theme_b" +rm -f "$user_background" +printf '%s\n' "$test_tmp/missing-background.webp" >"$background_state/$theme_a" +set_theme "$theme_a" +[[ $(current_background_name) == "$theme_a_first" ]] || fail "missing remembered background falls back to the first image" +pass "missing remembered background falls back to the first image" + +set_theme "$theme_a" +[[ $(current_background_name) == "$theme_a_selected" ]] || fail "reapplying the active theme still cycles backgrounds" +pass "reapplying the active theme still cycles backgrounds" + +printf '%s\n' "../escaped" >"$current_state/theme.name" +set_theme "$theme_b" +[[ ! -e $test_home/.local/state/omarchy/escaped ]] || fail "invalid theme names cannot escape the background state directory" +pass "invalid theme names cannot escape the background state directory" From fa3f607705749692ecaf8c0d7aa806476d108b27 Mon Sep 17 00:00:00 2001 From: Paolo Pellicori Date: Sun, 23 Aug 2026 16:42:13 +0200 Subject: [PATCH 002/194] [Security] Keep the Windows VM password out of the RDP client's argument list MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `launch_windows` passed the VM password to xfreerdp3 as `/p:"$WIN_PASS"`. `/proc//cmdline` is world-readable, so every other user on the machine could read the password for as long as the session stayed open — `ps` was enough. The arguments now go in over stdin with `/args-from:stdin`, leaving only that flag in the process list. The argument list itself is unchanged, and building it as an array also fixes the unquoted `$RDP_SCALE` expansion. --- bin/omarchy-windows-vm | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/bin/omarchy-windows-vm b/bin/omarchy-windows-vm index 793c19692f14..31d0230ccc14 100755 --- a/bin/omarchy-windows-vm +++ b/bin/omarchy-windows-vm @@ -363,8 +363,31 @@ To stop: omarchy-windows-vm stop" fi # If scale is less than 130%, don't set any scale (use default 100) - # Connect with RDP in fullscreen (auto-detects resolution) - xfreerdp3 /u:"$WIN_USER" /p:"$WIN_PASS" /v:127.0.0.1:3389 -grab-keyboard /sound /microphone /clipboard /cert:ignore /title:"Windows VM - Omarchy" /dynamic-resolution /gfx:AVC444 /floatbar:sticky:off,default:visible,show:fullscreen $RDP_SCALE + RDP_ARGS=( + "/u:$WIN_USER" + "/p:$WIN_PASS" + /v:127.0.0.1:3389 + -grab-keyboard + /sound + /microphone + /clipboard + /cert:ignore + "/title:Windows VM - Omarchy" + /dynamic-resolution + /gfx:AVC444 + /floatbar:sticky:off,default:visible,show:fullscreen + ) + if [[ -n $RDP_SCALE ]]; then + RDP_ARGS+=("$RDP_SCALE") + fi + + # Connect with RDP in fullscreen (auto-detects resolution). The arguments go + # in over stdin rather than on the command line: /proc//cmdline is + # world-readable, so passing the VM password as /p:"$WIN_PASS" would show it + # to every other user on the machine for as long as the session is open. + # /args-from must stay the only argument here — FreeRDP rejects it outright + # when it is combined with any other, so new flags belong in RDP_ARGS above. + printf '%s\n' "${RDP_ARGS[@]}" | xfreerdp3 /args-from:stdin # After RDP closes, stop the container unless --keep-alive was specified if [[ $KEEP_ALIVE = "false" ]]; then From f6a8c6c02f025deb863cddf7956c824845cfd7d7 Mon Sep 17 00:00:00 2001 From: Miguel Mendez Date: Sun, 30 Aug 2026 01:17:31 +0200 Subject: [PATCH 003/194] Mark omarchy-install-service-dropbox as requires-sudo bin/omarchy scans the first 80 lines of every command for omarchy:* metadata. The requires-sudo flag is surfaced via 'omarchy commands --json', and the interactive launcher and menu use it to flag entries that need elevation before the user clicks them. Every install-service script in bin/ has the directive: spotify, signal, 1password, sunshine, dropbox-remove, nordvpn, once, tailscale, plus the full omarchy-install-* and omarchy-apply-* trees. omarchy-remove-service-dropbox has it. omarchy-install-service-dropbox is the outlier. The menu hints 'needs sudo' for removing Dropbox but not for installing it. The install path runs pacman via omarchy-pkg-add, which needs elevation. The missing directive is an oversight, not a deliberate choice. --- bin/omarchy-install-service-dropbox | 1 + 1 file changed, 1 insertion(+) diff --git a/bin/omarchy-install-service-dropbox b/bin/omarchy-install-service-dropbox index 0ee07bfbfc1f..7a4e190ec52f 100755 --- a/bin/omarchy-install-service-dropbox +++ b/bin/omarchy-install-service-dropbox @@ -1,6 +1,7 @@ #!/bin/bash # omarchy:summary=Install and start the Dropbox service. Must then be authenticated via the web. +# omarchy:requires-sudo=true echo "Installing all dependencies..." omarchy-pkg-add dropbox dropbox-cli libappindicator-gtk3 python-gpgme nautilus-dropbox From 0bec60f6e4012d95e6d0bea24ac05dbc017691b8 Mon Sep 17 00:00:00 2001 From: ogarza Date: Sun, 30 Aug 2026 05:26:46 -0400 Subject: [PATCH 004/194] Center the Quake console in a 2:1 panel instead of spanning the screen. Size it from leftover workspace gaps so it refits per monitor, and let omarchy_qconsole_ratio change the width. --- config/hypr/hyprland.lua | 5 + default/hypr/qconsole.lua | 161 ++++++++++++++++++++++--- manual/04-navigation.md | 2 + test/shell.d/hyprland-qconsole-test.sh | 88 +++++++++++++- 4 files changed, 232 insertions(+), 24 deletions(-) diff --git a/config/hypr/hyprland.lua b/config/hypr/hyprland.lua index 45c9b664b066..354e079c0a0c 100644 --- a/config/hypr/hyprland.lua +++ b/config/hypr/hyprland.lua @@ -10,6 +10,11 @@ dofile((os.getenv("OMARCHY_PATH") or "/usr/share/omarchy") .. "/default/hypr/boo -- keeping core window-manager bindings: -- omarchy_preinstalled_bindings = false +-- Center the quake console in a tiling box. The number is how many times +-- wider the box is than its height. 1 is a square. Comment this out for a +-- full-width drop-down. +omarchy_qconsole_ratio = 2 + -- Load Omarchy defaults. require("default.hypr.omarchy") diff --git a/default/hypr/qconsole.lua b/default/hypr/qconsole.lua index d3a36ae68002..235b46758e53 100644 --- a/default/hypr/qconsole.lua +++ b/default/hypr/qconsole.lua @@ -4,6 +4,9 @@ -- How much of the usable screen the console covers, measured from the top. local share = 0.5 +local min_size = 64 + +local SCRATCHPAD = "special:scratchpad" -- Seed the console with the default agent the first time it opens, rather than -- at boot, so nothing is running until it is wanted. The exec rule has to pin @@ -25,20 +28,33 @@ hl.config({ -- Refitting replaces the rule in place rather than stacking a new one, but it -- still schedules a monitor and window state refresh, and monitor.focused fires --- on every hop between screens. Most of those hops do not change the number, so +-- on every hop between screens. Most of those hops do not change the gaps, so -- only write the rule when it actually moves. local covering = nil -local function cover(bottom) - if covering == bottom then - return +local function same_gaps(a, b) + return a + and b + and a.top == b.top + and a.right == b.right + and a.bottom == b.bottom + and a.left == b.left +end + +local function cover(gaps_out) + if type(gaps_out) == "number" then + gaps_out = { top = 0, right = 0, bottom = gaps_out, left = 0 } + end + + if same_gaps(covering, gaps_out) then + return false end - covering = bottom + covering = gaps_out hl.workspace_rule({ - workspace = "special:scratchpad", + workspace = SCRATCHPAD, gaps_in = 0, - gaps_out = { top = 0, right = 0, bottom = bottom, left = 0 }, + gaps_out = gaps_out, -- Nothing to highlight in a console that is only ever focused when it is -- open, and the active border reads as a stray frame around a panel that @@ -47,39 +63,148 @@ local function cover(bottom) on_created_empty = seed, }) + + return true +end + +local function reserved_edges(monitor) + local reserved = monitor.reserved + if type(reserved) ~= "table" then + return { top = 0, right = 0, bottom = 0, left = 0 } + end + + return { + top = reserved.top or 0, + right = reserved.right or 0, + bottom = reserved.bottom or 0, + left = reserved.left or 0, + } +end + +-- A positive omarchy_qconsole_ratio (set in hyprland.lua before defaults load) +-- centers the console in a tiling box that many times wider than it is tall. +-- Values below 1 clamp to a square. Unset keeps the full-width drop-down. +local function box_ratio() + local ratio = _G.omarchy_qconsole_ratio + if type(ratio) == "number" and ratio > 0 then + return math.max(1, ratio) + end + return nil +end + +local function is_scratchpad(ws) + return ws and (ws.name == SCRATCHPAD or ws.name == "scratchpad") end -- Sizing the console with a window rule would freeze it at whatever the screen -- measured when it first opened, because Hyprland resolves those expressions -- once, as the window maps. Rescaling the monitor afterwards would leave a -- console that is no longer half of anything. Gaps are re-applied by the layout --- instead, so the console is sized by the gap left underneath it and that gap --- is recomputed whenever the monitor layout changes. -local function fit() - local monitor = hl.get_active_monitor() +-- instead, so the console is sized by the leftover area and that area is +-- recomputed whenever the monitor it is opening on changes. +local function fit(monitor) + monitor = monitor or hl.get_active_monitor() -- A monitor handle whose output has gone away answers nil to every field, and -- layout changes are exactly when that happens, so this also covers reading -- height and reserved below. if not monitor or not monitor.scale or monitor.scale <= 0 then - return + return false end -- Monitor dimensions are in physical pixels; gaps are logical, so the scale -- has to come out before the reserved area (already logical) comes off. - local reserved = monitor.reserved - local usable = monitor.height / monitor.scale - reserved.top - reserved.bottom + local reserved = reserved_edges(monitor) + local usable_h = monitor.height / monitor.scale - reserved.top - reserved.bottom + local usable_w = nil + if monitor.width then + usable_w = monitor.width / monitor.scale - reserved.left - reserved.right + end + + local ratio = box_ratio() + local h = math.max(min_size, math.floor(usable_h * share)) + local side = 0 + local bottom = math.max(0, math.floor(usable_h - h)) + + if ratio and usable_w then + local w = math.floor(h * ratio) + if w > usable_w then + w = math.floor(usable_w) + end + side = math.max(0, math.floor((usable_w - w) / 2)) + if usable_w - (side * 2) < min_size then + side = math.max(0, math.floor((usable_w - min_size) / 2)) + end + end - cover(math.max(0, math.floor(usable * (1 - share)))) + if usable_h - bottom < min_size then + bottom = math.max(0, math.floor(usable_h - min_size)) + end + + return cover({ top = 0, right = side, bottom = bottom, left = side }) +end + +local function apply_now() + if hl.exec_scheduled_prop_refresh_immediately then + hl.exec_scheduled_prop_refresh_immediately() + end +end + +local function scratchpad_on_other_monitor(mon) + if not hl.get_workspace or not mon then + return false + end + + local ws = hl.get_workspace(SCRATCHPAD) + if not is_scratchpad(ws) or not ws.visible or not ws.monitor or not ws.monitor.name or not mon.name then + return false + end + + return ws.monitor.name ~= mon.name end -- Until a monitor can be read, cover the whole work area rather than leaving -- the console unruled, so it is never seeded without its placement. -cover(0) +cover({ top = 0, right = 0, bottom = 0, left = 0 }) fit() -hl.on("monitor.layout_changed", fit) -hl.on("monitor.focused", fit) +hl.on("monitor.layout_changed", function() + local ws = hl.get_workspace and hl.get_workspace(SCRATCHPAD) + if is_scratchpad(ws) and ws.visible and ws.monitor then + fit(ws.monitor) + else + fit() + end +end) + +-- follow_mouse hops fire this; do not rewrite an open console to a different +-- output's gaps (that is what zeroed the window on the 1080p screen). +hl.on("monitor.focused", function(mon) + if scratchpad_on_other_monitor(mon) then + return + end + fit(mon) +end) + +-- Special workspaces toggle on the monitor they open on, not whichever output +-- last happened to be focused when the rule was written. +hl.on("workspace.special_active", function(ws, mon) + if not is_scratchpad(ws) then + return + end + if fit(mon) then + apply_now() + end +end) + +hl.on("workspace.move_to_monitor", function(ws, mon) + if not is_scratchpad(ws) then + return + end + if fit(mon) then + apply_now() + end +end) -- The direction names the edge the offset is measured from, not where the -- workspace goes: "slide top" drops it down into view, and "slide bottom" diff --git a/manual/04-navigation.md b/manual/04-navigation.md index 549833bf32ca..1b62b0dfff7b 100644 --- a/manual/04-navigation.md +++ b/manual/04-navigation.md @@ -66,6 +66,8 @@ Finally, there's a special scratchpad workspace that drops down over whatever wo It works especially well for a terminal running an agent, or for controls you want to interact with quickly without leaving the current workspace. To move a window off the scratchpad, send it directly to another workspace with something like `Super + Shift + 1`. +By default the scratchpad drops down as a centered panel. Open `~/.config/hypr/hyprland.lua` if you want to change how wide that panel is (`omarchy_qconsole_ratio` is near the top). `1` makes a square; `2` makes a panel twice as wide as it is tall; `3` or `4` is wider still. Anything smaller than `1` still gives you a square. Comment the line out if you'd rather have it span the full width of the screen. + ### It takes some getting used to! It takes a little while to get used to navigating your desktop like this, but once you do, it'll be hard to go back to a traditional mouse-driven desktop experience! diff --git a/test/shell.d/hyprland-qconsole-test.sh b/test/shell.d/hyprland-qconsole-test.sh index 57bdea8da405..9360e3c8d951 100755 --- a/test/shell.d/hyprland-qconsole-test.sh +++ b/test/shell.d/hyprland-qconsole-test.sh @@ -10,9 +10,10 @@ require_command lua # scaled display, so it is worth pinning down. # base-test.sh does not set -e, so the assertions have to fail the file # themselves rather than leaving the pass below to run regardless. -OMARCHY_PATH="$ROOT" lua - <<'LUA' || fail "the console covers half the work area at any monitor scale" +OMARCHY_PATH="$ROOT" lua - <<'LUA' || fail "the console is a half-height 2:1 panel by default" local rules, handlers = {}, {} local monitor = nil +local workspace = nil hl = { config = function() end, @@ -20,8 +21,14 @@ hl = { workspace_rule = function(rule) table.insert(rules, rule) end, on = function(event, callback) handlers[event] = callback end, get_active_monitor = function() return monitor end, + get_workspace = function() return workspace end, + exec_scheduled_prop_refresh_immediately = function() end, } +-- Same default as config/hypr/hyprland.lua: a centered panel twice as wide as +-- it is tall. Commenting that assignment out is what restores full width. +omarchy_qconsole_ratio = 2 + dofile(os.getenv("OMARCHY_PATH") .. "/default/hypr/bootstrap.lua") require("default.hypr.qconsole") @@ -29,6 +36,11 @@ local function current() return rules[#rules] end +local function gaps() + local g = current().gaps_out + return g.top, g.right, g.bottom, g.left +end + -- Config loads before the outputs are up, so the first pass has no monitor to -- read. It still has to leave a rule behind, or the console would open unseeded. assert(#rules > 0, "console is ruled even before a monitor can be read") @@ -44,6 +56,7 @@ local function rescale(height, scale, bar) end -- Same panel, same logical size, different scale: the console must not care. +-- These fixtures omit width, so the ratio cannot inset the sides yet. assert(rescale(1080, 1, 40) == 520, "half of a 1080p work area, unscaled") assert(rescale(2160, 2, 40) == 520, "the same half once the monitor is scaled 2x") assert(rescale(2160, 1.5, 40) == 700, "and at a fractional scale") @@ -52,11 +65,10 @@ assert(rescale(2160, 1.5, 40) == 700, "and at a fractional scale") -- console short. assert(rescale(1440, 1, 0) == 720, "a monitor with nothing reserved") --- The console stays flush with the top and the sides, the way a Quake console --- drops in, and keeps its seed across every refit. local final = current() -assert(final.gaps_out.top == 0 and final.gaps_out.left == 0 and final.gaps_out.right == 0, - "the console is flush to the top and sides") +assert(final.gaps_out.top == 0, "the console stays flush with the top") +assert(final.gaps_out.left == 0 and final.gaps_out.right == 0, + "without a width the sides stay flush") assert(final.on_created_empty:find("omarchy%-agent"), "refitting keeps the console seeded") assert(final.no_border == true, "the console drops the active window border") @@ -86,5 +98,69 @@ monitor.scale = 2 handlers["monitor.layout_changed"]() assert(#rules == written + 1, "a real change still rewrites it") assert(current().gaps_out.bottom == 360, "and lands on half the rescaled screen") + +-- Default ratio: 16:9 is a centered 2:1 panel, not a full-width drop-down. +monitor = { width = 1920, height = 1080, scale = 1, reserved = { top = 0, bottom = 0, left = 0, right = 0 } } +handlers["monitor.layout_changed"]() +local top, right, bottom, left = gaps() +assert(top == 0 and left == 420 and right == 420 and bottom == 540, "16:9 default is a 1080x540 panel") + +local dell = { name = "DP-1", width = 6144, height = 2560, scale = 1, reserved = { top = 30, bottom = 0, left = 0, right = 0 } } +monitor = dell +handlers["monitor.layout_changed"]() +top, right, bottom, left = gaps() +assert(left == 1807 and right == 1807 and bottom == 1265, "the same 2:1 panel on 6K") + +-- Same logical box at scale 2x (physical 12288x5120). +-- It checks that scale does not change the panel's logical size. +monitor = { name = "DP-1", width = 12288, height = 5120, scale = 2, reserved = { top = 30, bottom = 0, left = 0, right = 0 } } +handlers["monitor.layout_changed"]() +top, right, bottom, left = gaps() +assert(left == 1807 and right == 1807 and bottom == 1265, "the 6K box is in logical pixels") + +-- Acer 1920x1080, bar 30, same ratio. Opening here after a 6K fit must rewrite; +-- leaving 6K side gaps would make leftover width negative. +local acer = { name = "HDMI-A-1", width = 1920, height = 1080, scale = 1, reserved = { top = 30, bottom = 0, left = 0, right = 0 } } +monitor = dell +handlers["monitor.layout_changed"]() +handlers["workspace.special_active"]({ name = "special:scratchpad" }, acer) +top, right, bottom, left = gaps() +assert(left == 435 and right == 435 and bottom == 525, "opening on 1080p after a 6K fit resizes the 2:1 box") +assert(1920 - left - right > 0 and 1080 - 30 - bottom > 0, "1080p leftover is never negative") + +-- follow_mouse onto the 6K while the console is already showing on 1080p must +-- not steal the global rule (that is what oversized the Dell after a hop). +workspace = { name = "special:scratchpad", visible = true, monitor = acer } +written = #rules +handlers["monitor.focused"](dell) +assert(#rules == written, "focus on another output does not rewrite an open console") +workspace = nil + +-- Cache: same 1440p height, 16:9 vs 21:9. Sides change even when bottom does not. +monitor = { width = 2560, height = 1440, scale = 1, reserved = { top = 0, bottom = 0, left = 0, right = 0 } } +handlers["monitor.layout_changed"]() +written = #rules +monitor = { width = 3440, height = 1440, scale = 1, reserved = { top = 0, bottom = 0, left = 0, right = 0 } } +handlers["monitor.layout_changed"]() +assert(#rules == written + 1, "a same-height ultrawide hop still rewrites the sides") +top, right, bottom, left = gaps() +assert(left == 1000 and right == 1000 and bottom == 720, "3440x1440 at ratio 2 is a 2:1 box") + +omarchy_qconsole_ratio = 1 +monitor = { width = 1920, height = 1080, scale = 1, reserved = { top = 0, bottom = 0, left = 0, right = 0 } } +handlers["monitor.layout_changed"]() +top, right, bottom, left = gaps() +assert(left == 690 and right == 690 and bottom == 540, "ratio 1 is a square") + +omarchy_qconsole_ratio = 0.5 +handlers["monitor.layout_changed"]() +top, right, bottom, left = gaps() +assert(left == 690 and right == 690 and bottom == 540, "a ratio below 1 clamps to a square") + +omarchy_qconsole_ratio = nil +monitor = dell +handlers["monitor.layout_changed"]() +top, right, bottom, left = gaps() +assert(left == 0 and right == 0 and bottom == 1265, "clearing the ratio restores full width") LUA -pass "the console covers half the work area at any monitor scale" +pass "the console is a half-height 2:1 panel by default" From a59afb9659ca0d2a33316d510fac70755d9752f1 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 30 Aug 2026 14:50:40 +0200 Subject: [PATCH 005/194] Give the width back when a second app joins the console The scratchpad spanned the whole screen whatever was on it, which reads as a band rather than a console when it holds the single agent it is usually opened for. It now sizes to a centered panel twice as wide as it is tall, and hands the full width back as soon as a second app is on the scratchpad: two windows splitting a half-width column is worse than the band this replaced. The panel is still drawn with workspace gaps rather than a window rule, because Hyprland resolves a rule's size once as the window maps and the console has to survive a rescale. It is always flush with the top and always centered, so two numbers describe it, and the memo that suppresses no-op rewrites compares those rather than four edges. The window count is read on window.open and window.destroy, the two events that run after the workspace's count has settled; window.close and window.move_to_workspace both still count the window on its way out, so refitting from either reads one too many and strands the console at full width. The count is only chased while the console is on screen, since a hidden one is refitted on its way in by workspace.special_active, and every window opened anywhere on the desktop would otherwise rewrite the rule. Monitor width and height are the panel's own pixels, so an output turned on its side still reports them the way the panel is built rather than the way it hangs. The odd transforms are the quarter turns and those swap the work area: without that a rotated 1920x1080 sized its console from 1920x1080 instead of 1080x1920 and left a 214x1367 sliver. Co-Authored-By: Claude Opus 5 (1M context) Co-Authored-By: Codex XHigh --- config/hypr/hyprland.lua | 5 - default/hypr/qconsole.lua | 205 +++++++++++-------------- manual/04-navigation.md | 2 +- test/shell.d/hyprland-qconsole-test.sh | 170 ++++++++++++++------ 4 files changed, 209 insertions(+), 173 deletions(-) diff --git a/config/hypr/hyprland.lua b/config/hypr/hyprland.lua index 354e079c0a0c..45c9b664b066 100644 --- a/config/hypr/hyprland.lua +++ b/config/hypr/hyprland.lua @@ -10,11 +10,6 @@ dofile((os.getenv("OMARCHY_PATH") or "/usr/share/omarchy") .. "/default/hypr/boo -- keeping core window-manager bindings: -- omarchy_preinstalled_bindings = false --- Center the quake console in a tiling box. The number is how many times --- wider the box is than its height. 1 is a square. Comment this out for a --- full-width drop-down. -omarchy_qconsole_ratio = 2 - -- Load Omarchy defaults. require("default.hypr.omarchy") diff --git a/default/hypr/qconsole.lua b/default/hypr/qconsole.lua index 235b46758e53..cb248f4c6846 100644 --- a/default/hypr/qconsole.lua +++ b/default/hypr/qconsole.lua @@ -4,7 +4,12 @@ -- How much of the usable screen the console covers, measured from the top. local share = 0.5 -local min_size = 64 + +-- A console holding a single window is boxed into a centered panel this many +-- times wider than it is tall, rather than stretched the width of the screen. +-- A second app on the scratchpad gets the full width back: two windows splitting +-- a half-width column is worse than the band this replaced. +local box = 2 local SCRATCHPAD = "special:scratchpad" @@ -26,35 +31,25 @@ hl.config({ }, }) +-- The panel is always flush with the top and always centered, so two numbers +-- describe it: the gap down each side and the gap underneath. +-- -- Refitting replaces the rule in place rather than stacking a new one, but it -- still schedules a monitor and window state refresh, and monitor.focused fires -- on every hop between screens. Most of those hops do not change the gaps, so -- only write the rule when it actually moves. -local covering = nil - -local function same_gaps(a, b) - return a - and b - and a.top == b.top - and a.right == b.right - and a.bottom == b.bottom - and a.left == b.left -end +local beside, below = nil, nil -local function cover(gaps_out) - if type(gaps_out) == "number" then - gaps_out = { top = 0, right = 0, bottom = gaps_out, left = 0 } - end - - if same_gaps(covering, gaps_out) then +local function cover(side, bottom) + if beside == side and below == bottom then return false end - covering = gaps_out + beside, below = side, bottom hl.workspace_rule({ workspace = SCRATCHPAD, gaps_in = 0, - gaps_out = gaps_out, + gaps_out = { top = 0, right = side, bottom = bottom, left = side }, -- Nothing to highlight in a console that is only ever focused when it is -- open, and the active border reads as a stray frame around a panel that @@ -67,145 +62,121 @@ local function cover(gaps_out) return true end -local function reserved_edges(monitor) - local reserved = monitor.reserved - if type(reserved) ~= "table" then - return { top = 0, right = 0, bottom = 0, left = 0 } - end - - return { - top = reserved.top or 0, - right = reserved.right or 0, - bottom = reserved.bottom or 0, - left = reserved.left or 0, - } -end - --- A positive omarchy_qconsole_ratio (set in hyprland.lua before defaults load) --- centers the console in a tiling box that many times wider than it is tall. --- Values below 1 clamp to a square. Unset keeps the full-width drop-down. -local function box_ratio() - local ratio = _G.omarchy_qconsole_ratio - if type(ratio) == "number" and ratio > 0 then - return math.max(1, ratio) - end - return nil -end - -local function is_scratchpad(ws) - return ws and (ws.name == SCRATCHPAD or ws.name == "scratchpad") +-- One window reads as a console and gets the panel. A second app has turned the +-- scratchpad into a workspace, and a workspace wants the whole width. +local function alone() + local ws = hl.get_workspace(SCRATCHPAD) + return not ws or ws.windows <= 1 end -- Sizing the console with a window rule would freeze it at whatever the screen -- measured when it first opened, because Hyprland resolves those expressions -- once, as the window maps. Rescaling the monitor afterwards would leave a -- console that is no longer half of anything. Gaps are re-applied by the layout --- instead, so the console is sized by the leftover area and that area is --- recomputed whenever the monitor it is opening on changes. +-- instead, so the console is sized by the area left around it, and that area is +-- recomputed whenever the monitor it opens on changes. local function fit(monitor) - monitor = monitor or hl.get_active_monitor() - -- A monitor handle whose output has gone away answers nil to every field, and -- layout changes are exactly when that happens, so this also covers reading - -- height and reserved below. + -- width, height and reserved below. if not monitor or not monitor.scale or monitor.scale <= 0 then return false end - -- Monitor dimensions are in physical pixels; gaps are logical, so the scale - -- has to come out before the reserved area (already logical) comes off. - local reserved = reserved_edges(monitor) - local usable_h = monitor.height / monitor.scale - reserved.top - reserved.bottom - local usable_w = nil - if monitor.width then - usable_w = monitor.width / monitor.scale - reserved.left - reserved.right + -- Width and height are the panel's own pixels, so a monitor turned on its + -- side still reports them the way the panel is built. The odd transforms are + -- the quarter turns, and those are the ones that swap the work area. + local width, height = monitor.width, monitor.height + if monitor.transform % 2 == 1 then + width, height = height, width end - local ratio = box_ratio() - local h = math.max(min_size, math.floor(usable_h * share)) - local side = 0 - local bottom = math.max(0, math.floor(usable_h - h)) - - if ratio and usable_w then - local w = math.floor(h * ratio) - if w > usable_w then - w = math.floor(usable_w) - end - side = math.max(0, math.floor((usable_w - w) / 2)) - if usable_w - (side * 2) < min_size then - side = math.max(0, math.floor((usable_w - min_size) / 2)) - end - end + -- Monitor dimensions are in physical pixels; gaps are logical, so the scale + -- has to come out before the reserved area (already logical) comes off. + local reserved = monitor.reserved + height = height / monitor.scale - reserved.top - reserved.bottom + width = width / monitor.scale - reserved.left - reserved.right - if usable_h - bottom < min_size then - bottom = math.max(0, math.floor(usable_h - min_size)) + local tall = math.floor(height * share) + local wide = width + if alone() then + wide = math.min(width, tall * box) end - return cover({ top = 0, right = side, bottom = bottom, left = side }) + return cover(math.floor((width - wide) / 2), math.floor(height - tall)) end -local function apply_now() - if hl.exec_scheduled_prop_refresh_immediately then - hl.exec_scheduled_prop_refresh_immediately() - end -end +-- The console keeps the geometry of the output it is open on: a follow_mouse hop +-- onto another screen must not resize a console that is already showing. While +-- it is hidden there is nothing to size but the output that will show it next. +local function console_monitor() + local ws = hl.get_workspace(SCRATCHPAD) + local mon = ws and ws.visible and ws.monitor -local function scratchpad_on_other_monitor(mon) - if not hl.get_workspace or not mon then - return false + if mon and mon.scale and mon.scale > 0 then + return mon end - local ws = hl.get_workspace(SCRATCHPAD) - if not is_scratchpad(ws) or not ws.visible or not ws.monitor or not ws.monitor.name or not mon.name then - return false - end + return hl.get_active_monitor() +end - return ws.monitor.name ~= mon.name +local function refit(monitor) + if fit(monitor or console_monitor()) then + -- Land the new gaps in this pass rather than a frame later, so the console + -- does not visibly resize itself once it has already dropped down. + hl.exec_scheduled_prop_refresh_immediately() + end end -- Until a monitor can be read, cover the whole work area rather than leaving --- the console unruled, so it is never seeded without its placement. -cover({ top = 0, right = 0, bottom = 0, left = 0 }) -fit() +-- the console unruled, so it is never seeded without its placement. A reload +-- runs this again with the console already on screen, so it starts from the +-- output the console is on rather than whichever one the pointer is over. +cover(0, 0) +fit(console_monitor()) hl.on("monitor.layout_changed", function() - local ws = hl.get_workspace and hl.get_workspace(SCRATCHPAD) - if is_scratchpad(ws) and ws.visible and ws.monitor then - fit(ws.monitor) - else - fit() - end + refit() end) --- follow_mouse hops fire this; do not rewrite an open console to a different --- output's gaps (that is what zeroed the window on the 1080p screen). -hl.on("monitor.focused", function(mon) - if scratchpad_on_other_monitor(mon) then - return - end - fit(mon) +hl.on("monitor.focused", function() + refit() end) --- Special workspaces toggle on the monitor they open on, not whichever output --- last happened to be focused when the rule was written. +-- Special workspaces open on the monitor they are toggled on, not on whichever +-- output last happened to be focused when the rule was written, so these two +-- take the monitor they are handed rather than looking one up. hl.on("workspace.special_active", function(ws, mon) - if not is_scratchpad(ws) then - return - end - if fit(mon) then - apply_now() + if ws and ws.name == SCRATCHPAD then + refit(mon) end end) hl.on("workspace.move_to_monitor", function(ws, mon) - if not is_scratchpad(ws) then - return - end - if fit(mon) then - apply_now() + if ws and ws.name == SCRATCHPAD then + refit(mon) end end) +-- The panel is only centered while the console holds one window, so the count +-- has to be rechecked as apps come and go. These are the two events that run +-- after the workspace's count has already moved: window.close and +-- window.move_to_workspace still count the window on its way out, and refitting +-- from those would read one too many and leave the console full width. +-- +-- Only while it is on screen, though. A hidden console is refitted on its way in +-- by workspace.special_active, and every window opened anywhere on the desktop +-- would otherwise rewrite the rule. +local function recount() + local ws = hl.get_workspace(SCRATCHPAD) + if ws and ws.visible then + refit() + end +end + +hl.on("window.open", recount) +hl.on("window.destroy", recount) + -- The direction names the edge the offset is measured from, not where the -- workspace goes: "slide top" drops it down into view, and "slide bottom" -- retracts it back up the way a Quake console does. diff --git a/manual/04-navigation.md b/manual/04-navigation.md index 1b62b0dfff7b..0b3404ffeb6e 100644 --- a/manual/04-navigation.md +++ b/manual/04-navigation.md @@ -66,7 +66,7 @@ Finally, there's a special scratchpad workspace that drops down over whatever wo It works especially well for a terminal running an agent, or for controls you want to interact with quickly without leaving the current workspace. To move a window off the scratchpad, send it directly to another workspace with something like `Super + Shift + 1`. -By default the scratchpad drops down as a centered panel. Open `~/.config/hypr/hyprland.lua` if you want to change how wide that panel is (`omarchy_qconsole_ratio` is near the top). `1` makes a square; `2` makes a panel twice as wide as it is tall; `3` or `4` is wider still. Anything smaller than `1` still gives you a square. Comment the line out if you'd rather have it span the full width of the screen. +While the scratchpad holds a single window, it drops down as a centered panel rather than spanning the screen. Put a second app on it and it goes back to the full width, so the two have room to sit side by side. ### It takes some getting used to! diff --git a/test/shell.d/hyprland-qconsole-test.sh b/test/shell.d/hyprland-qconsole-test.sh index 9360e3c8d951..c5123d03dfcd 100755 --- a/test/shell.d/hyprland-qconsole-test.sh +++ b/test/shell.d/hyprland-qconsole-test.sh @@ -4,13 +4,13 @@ source "$(dirname "${BASH_SOURCE[0]}")/base-test.sh" require_command lua -# The console is sized by the gap underneath it, recomputed from the monitor, +# The console is sized by the gaps around it, recomputed from the monitor, # because a window rule's size would freeze at whatever the screen measured when -# the console first opened. The arithmetic is what keeps it half a screen on a -# scaled display, so it is worth pinning down. +# the console first opened. The arithmetic is what keeps it a half-height panel +# on a scaled display, so it is worth pinning down. # base-test.sh does not set -e, so the assertions have to fail the file # themselves rather than leaving the pass below to run regardless. -OMARCHY_PATH="$ROOT" lua - <<'LUA' || fail "the console is a half-height 2:1 panel by default" +OMARCHY_PATH="$ROOT" lua - <<'LUA' || fail "the console is a centered panel until a second app joins it" local rules, handlers = {}, {} local monitor = nil local workspace = nil @@ -25,10 +25,6 @@ hl = { exec_scheduled_prop_refresh_immediately = function() end, } --- Same default as config/hypr/hyprland.lua: a centered panel twice as wide as --- it is tall. Commenting that assignment out is what restores full width. -omarchy_qconsole_ratio = 2 - dofile(os.getenv("OMARCHY_PATH") .. "/default/hypr/bootstrap.lua") require("default.hypr.qconsole") @@ -50,13 +46,12 @@ assert(current().on_created_empty:find("^%[workspace special:scratchpad silent%] assert(current().workspace == "special:scratchpad") local function rescale(height, scale, bar) - monitor = { height = height, scale = scale, reserved = { top = bar, bottom = 0, left = 0, right = 0 } } + monitor = { width = 1920, height = height, scale = scale, transform = 0, reserved = { top = bar, bottom = 0, left = 0, right = 0 } } handlers["monitor.layout_changed"]() return current().gaps_out.bottom end -- Same panel, same logical size, different scale: the console must not care. --- These fixtures omit width, so the ratio cannot inset the sides yet. assert(rescale(1080, 1, 40) == 520, "half of a 1080p work area, unscaled") assert(rescale(2160, 2, 40) == 520, "the same half once the monitor is scaled 2x") assert(rescale(2160, 1.5, 40) == 700, "and at a fractional scale") @@ -66,9 +61,8 @@ assert(rescale(2160, 1.5, 40) == 700, "and at a fractional scale") assert(rescale(1440, 1, 0) == 720, "a monitor with nothing reserved") local final = current() -assert(final.gaps_out.top == 0, "the console stays flush with the top") -assert(final.gaps_out.left == 0 and final.gaps_out.right == 0, - "without a width the sides stay flush") +assert(final.gaps_out.top == 0, "the console stays flush with the top, the way a drop-down arrives") +assert(final.gaps_out.left == final.gaps_out.right, "the panel is centered") assert(final.on_created_empty:find("omarchy%-agent"), "refitting keeps the console seeded") assert(final.no_border == true, "the console drops the active window border") @@ -81,86 +75,162 @@ assert(current().gaps_out.bottom == before, "an absent monitor leaves the consol -- A monitor handle outliving its output answers nil to everything, which is -- what a layout change looks like mid-flight. Reading height or reserved off -- that would throw, so the scale guard has to catch it first. -monitor = setmetatable({}, { __index = function() return nil end }) +local expired = setmetatable({}, { __index = function() return nil end }) +monitor = expired handlers["monitor.layout_changed"]() assert(current().gaps_out.bottom == before, "an expired monitor handle is not read to pieces") -- Refitting to the size it already is would still cost a state refresh, and -- monitor.focused fires on every hop between screens. -monitor = { height = 1440, scale = 1, reserved = { top = 0, bottom = 0, left = 0, right = 0 } } +monitor = { width = 2560, height = 1440, scale = 1, transform = 0, reserved = { top = 0, bottom = 0, left = 0, right = 0 } } handlers["monitor.layout_changed"]() local written = #rules handlers["monitor.focused"]() handlers["monitor.layout_changed"]() assert(#rules == written, "refitting to the same size does not rewrite the rule") -monitor.scale = 2 -handlers["monitor.layout_changed"]() -assert(#rules == written + 1, "a real change still rewrites it") -assert(current().gaps_out.bottom == 360, "and lands on half the rescaled screen") - --- Default ratio: 16:9 is a centered 2:1 panel, not a full-width drop-down. -monitor = { width = 1920, height = 1080, scale = 1, reserved = { top = 0, bottom = 0, left = 0, right = 0 } } +-- A centered 2:1 panel, not a full-width drop-down. +monitor = { width = 1920, height = 1080, scale = 1, transform = 0, reserved = { top = 0, bottom = 0, left = 0, right = 0 } } handlers["monitor.layout_changed"]() local top, right, bottom, left = gaps() -assert(top == 0 and left == 420 and right == 420 and bottom == 540, "16:9 default is a 1080x540 panel") +assert(top == 0 and left == 420 and right == 420 and bottom == 540, "16:9 leaves a 1080x540 panel") -local dell = { name = "DP-1", width = 6144, height = 2560, scale = 1, reserved = { top = 30, bottom = 0, left = 0, right = 0 } } +local dell = { name = "DP-1", width = 6144, height = 2560, scale = 1, transform = 0, reserved = { top = 30, bottom = 0, left = 0, right = 0 } } monitor = dell handlers["monitor.layout_changed"]() top, right, bottom, left = gaps() assert(left == 1807 and right == 1807 and bottom == 1265, "the same 2:1 panel on 6K") --- Same logical box at scale 2x (physical 12288x5120). --- It checks that scale does not change the panel's logical size. -monitor = { name = "DP-1", width = 12288, height = 5120, scale = 2, reserved = { top = 30, bottom = 0, left = 0, right = 0 } } +-- Same logical box at scale 2x (physical 12288x5120): scale does not change the +-- panel's logical size. +monitor = { name = "DP-1", width = 12288, height = 5120, scale = 2, transform = 0, reserved = { top = 30, bottom = 0, left = 0, right = 0 } } handlers["monitor.layout_changed"]() top, right, bottom, left = gaps() assert(left == 1807 and right == 1807 and bottom == 1265, "the 6K box is in logical pixels") --- Acer 1920x1080, bar 30, same ratio. Opening here after a 6K fit must rewrite; --- leaving 6K side gaps would make leftover width negative. -local acer = { name = "HDMI-A-1", width = 1920, height = 1080, scale = 1, reserved = { top = 30, bottom = 0, left = 0, right = 0 } } +-- Same height, different width: the sides have to move even though the bottom +-- gap is identical, so the cache cannot key on height alone. +monitor = { width = 2560, height = 1440, scale = 1, transform = 0, reserved = { top = 0, bottom = 0, left = 0, right = 0 } } +handlers["monitor.layout_changed"]() +written = #rules +monitor = { width = 3440, height = 1440, scale = 1, transform = 0, reserved = { top = 0, bottom = 0, left = 0, right = 0 } } +handlers["monitor.layout_changed"]() +assert(#rules == written + 1, "a same-height ultrawide hop still rewrites the sides") +top, right, bottom, left = gaps() +assert(left == 1000 and right == 1000 and bottom == 720, "3440x1440 leaves a 1440x720 box") + +-- A panel wider than the screen is just the screen: a portrait monitor has no +-- room for a 2:1 box and falls back to the full width rather than a negative gap. +monitor = { width = 1080, height = 1920, scale = 1, transform = 0, reserved = { top = 0, bottom = 0, left = 0, right = 0 } } +handlers["monitor.layout_changed"]() +top, right, bottom, left = gaps() +assert(left == 0 and right == 0 and bottom == 960, "a portrait monitor keeps the full width") +assert(left >= 0 and right >= 0 and bottom >= 0, "gaps are never negative") + +-- A monitor turned on its side still reports the panel's own pixels, so the +-- work area has to be turned with it. Measured against Hyprland 0.56.2: a +-- rotated 1920x1080 lays its windows out in 1080x1920 while width and height +-- still read 1920 and 1080. Quarter turns are the odd transforms; a half turn +-- leaves the shape alone. +monitor = { width = 1920, height = 1080, scale = 1, transform = 1, reserved = { top = 30, bottom = 0, left = 0, right = 0 } } +handlers["monitor.layout_changed"]() +top, right, bottom, left = gaps() +assert(left == 0 and right == 0 and bottom == 945, "a quarter-turned monitor is sized portrait") + +monitor = { width = 1920, height = 1080, scale = 1, transform = 3, reserved = { top = 30, bottom = 0, left = 0, right = 0 } } +handlers["monitor.layout_changed"]() +top, right, bottom, left = gaps() +assert(left == 0 and right == 0 and bottom == 945, "and so is the other quarter turn") + +monitor = { width = 1920, height = 1080, scale = 1, transform = 2, reserved = { top = 30, bottom = 0, left = 0, right = 0 } } +handlers["monitor.layout_changed"]() +top, right, bottom, left = gaps() +assert(left == 435 and right == 435 and bottom == 525, "a half turn is still landscape") + +-- Special workspaces open on the monitor they are toggled on, not on whichever +-- output was focused when the rule was last written. Opening on 1080p after a +-- 6K fit has to resize the box. +local acer = { name = "HDMI-A-1", width = 1920, height = 1080, scale = 1, transform = 0, reserved = { top = 30, bottom = 0, left = 0, right = 0 } } monitor = dell handlers["monitor.layout_changed"]() handlers["workspace.special_active"]({ name = "special:scratchpad" }, acer) top, right, bottom, left = gaps() -assert(left == 435 and right == 435 and bottom == 525, "opening on 1080p after a 6K fit resizes the 2:1 box") +assert(left == 435 and right == 435 and bottom == 525, "opening on 1080p after a 6K fit resizes the box") assert(1920 - left - right > 0 and 1080 - 30 - bottom > 0, "1080p leftover is never negative") -- follow_mouse onto the 6K while the console is already showing on 1080p must --- not steal the global rule (that is what oversized the Dell after a hop). -workspace = { name = "special:scratchpad", visible = true, monitor = acer } +-- not steal the rule; that is what oversized the Dell after a hop. +workspace = { name = "special:scratchpad", visible = true, monitor = acer, windows = 1 } +monitor = dell written = #rules handlers["monitor.focused"](dell) assert(#rules == written, "focus on another output does not rewrite an open console") -workspace = nil --- Cache: same 1440p height, 16:9 vs 21:9. Sides change even when bottom does not. -monitor = { width = 2560, height = 1440, scale = 1, reserved = { top = 0, bottom = 0, left = 0, right = 0 } } -handlers["monitor.layout_changed"]() -written = #rules -monitor = { width = 3440, height = 1440, scale = 1, reserved = { top = 0, bottom = 0, left = 0, right = 0 } } +-- The output the console is showing on can go away mid-layout-change. Its +-- handle then answers nil to everything, and preferring it blindly would leave +-- the console stranded at the gaps of the monitor that is gone. The rule is +-- still the 1080p one here, so only refitting on the Dell can satisfy this. +workspace = { name = "special:scratchpad", visible = true, monitor = expired, windows = 1 } +monitor = dell handlers["monitor.layout_changed"]() -assert(#rules == written + 1, "a same-height ultrawide hop still rewrites the sides") top, right, bottom, left = gaps() -assert(left == 1000 and right == 1000 and bottom == 720, "3440x1440 at ratio 2 is a 2:1 box") +assert(left == 1807 and right == 1807 and bottom == 1265, + "a console whose output vanished refits on the monitor that is still there") -omarchy_qconsole_ratio = 1 -monitor = { width = 1920, height = 1080, scale = 1, reserved = { top = 0, bottom = 0, left = 0, right = 0 } } +-- Back onto the 1080p panel for the window-count checks below. +workspace = { name = "special:scratchpad", visible = true, monitor = acer, windows = 1 } +monitor = acer handlers["monitor.layout_changed"]() top, right, bottom, left = gaps() -assert(left == 690 and right == 690 and bottom == 540, "ratio 1 is a square") +assert(left == 435 and right == 435 and bottom == 525, "and refits again once it is back on a live output") -omarchy_qconsole_ratio = 0.5 -handlers["monitor.layout_changed"]() +-- One window reads as a console and keeps the panel. A second app has turned +-- the scratchpad into a workspace, and a workspace wants the whole width. +workspace = { name = "special:scratchpad", visible = true, monitor = acer, windows = 2 } +handlers["window.open"]() top, right, bottom, left = gaps() -assert(left == 690 and right == 690 and bottom == 540, "a ratio below 1 clamps to a square") +assert(left == 0 and right == 0, "a second app on the scratchpad restores the full width") +assert(bottom == 525, "and the console keeps its half-height drop") -omarchy_qconsole_ratio = nil +workspace.windows = 3 +written = #rules +handlers["window.open"]() +assert(#rules == written, "a third app changes nothing that is already full width") + +workspace.windows = 1 +handlers["window.destroy"]() +top, right, bottom, left = gaps() +assert(left == 435 and right == 435, "closing back down to one window recenters the panel") + +-- An empty scratchpad is about to be seeded with a single agent, so it is sized +-- as a console rather than as a workspace. +workspace.windows = 0 +handlers["window.destroy"]() +top, right, bottom, left = gaps() +assert(left == 435 and right == 435, "an empty console is still a console") + +-- A hidden console is refitted on its way back in, so the count does not have to +-- be chased while it is off screen; every window on the desktop would otherwise +-- rewrite the rule. +workspace = { name = "special:scratchpad", visible = false, monitor = acer, windows = 4 } monitor = dell +written = #rules +handlers["window.open"]() +assert(#rules == written, "a window opening elsewhere does not rewrite a hidden console") + +-- A scratchpad nothing has opened yet has no workspace to read at all, and is +-- sized as the console the seed is about to put a single agent into. +workspace = nil +monitor = { width = 1920, height = 1080, scale = 1, transform = 0, reserved = { top = 0, bottom = 0, left = 0, right = 0 } } handlers["monitor.layout_changed"]() top, right, bottom, left = gaps() -assert(left == 0 and right == 0 and bottom == 1265, "clearing the ratio restores full width") +assert(left == 420 and right == 420 and bottom == 540, "a scratchpad that does not exist yet is sized as a console") + +-- window.close and window.move_to_workspace both run while the workspace still +-- counts the window that is leaving, so a refit from either reads one too many +-- and strands the console at full width. window.open and window.destroy are the +-- two that run after the count has already moved, and are the only ones hooked. +assert(handlers["window.close"] == nil, "window.close counts the window on its way out") +assert(handlers["window.move_to_workspace"] == nil, "window.move_to_workspace does too") LUA -pass "the console is a half-height 2:1 panel by default" +pass "the console is a centered panel until a second app joins it" From 1136a715c08b73009d794ab6c2cc43c9406af720 Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Mon, 31 Aug 2026 21:27:50 +0100 Subject: [PATCH 006/194] OM-SEC-14: Run update hooks without reusable sudo authority --- bin/omarchy-refresh-pacman | 243 +++- bin/omarchy-update | 243 +++- .../add-custom-repo.sample | 15 +- default/agents/skills/omarchy/hooks.md | 6 +- default/omarchy/sudo-no-update/sudo | 27 + docs/update-process.md | 35 +- test/shell.d/update-hook-security-test.sh | 1040 +++++++++++++++++ test/shell.d/update-sequence-test.sh | 60 +- 8 files changed, 1628 insertions(+), 41 deletions(-) create mode 100755 default/omarchy/sudo-no-update/sudo create mode 100644 test/shell.d/update-hook-security-test.sh diff --git a/bin/omarchy-refresh-pacman b/bin/omarchy-refresh-pacman index 299d6c20d20d..612a31ded5eb 100755 --- a/bin/omarchy-refresh-pacman +++ b/bin/omarchy-refresh-pacman @@ -1,26 +1,245 @@ -#!/bin/bash +#!/bin/bash -p # omarchy:summary=Overwrite the package configuration for /etc/pacman with the Omarchy default of using its dedicated mirrors and repositories, then update all packages. # omarchy:requires-sudo=true -sudo cp -f /etc/pacman.conf /etc/pacman.conf.bak -sudo cp -f /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.bak +if [[ $- != *p* ]]; then + echo "Refusing an unsafe Bash startup for pacman refresh." >&2 + exit 126 +fi + +require_privileged_bash_startup() { + [[ $- == *p* ]] || return 1 + /usr/bin/env -i /usr/bin/bash -p -c ' + [[ $1 =~ ^[1-9][0-9]*$ ]] || exit 1 + mapfile -d "" -t argv <"/proc/$1/cmdline" || exit 1 + executable=$(/usr/bin/readlink -e -- "/proc/$1/exe") || exit 1 + [[ $executable == /usr/bin/bash ]] + [[ ${argv[0]:-} == /bin/bash || ${argv[0]:-} == /usr/bin/bash ]] + [[ ${argv[1]:-} == -p ]] + ' omarchy-bash-startup "$$" +} +if ! require_privileged_bash_startup; then + echo "Refusing an unsafe Bash startup for pacman refresh." >&2 + exit 126 +fi +unset -f require_privileged_bash_startup + +set -e + +sanitize_bash_startup_environment() { + local environment_entry environment_name + local needs_reexec=0 + local -a environment_unsets=(-u BASH_ENV -u ENV) + + [[ -z ${BASH_ENV+x} && -z ${ENV+x} ]] || needs_reexec=1 + while IFS= read -r -d '' environment_entry; do + environment_name="${environment_entry%%=*}" + if [[ $environment_name == BASH_FUNC_*%% ]]; then + environment_unsets+=(-u "$environment_name") + needs_reexec=1 + fi + done < <(/usr/bin/env -0) + + if (( needs_reexec )); then + exec /usr/bin/env "${environment_unsets[@]}" /usr/bin/bash -p "$0" "$@" + fi +} +sanitize_bash_startup_environment "$@" +unset -f sanitize_bash_startup_environment + +usage() { + echo "Usage: omarchy-refresh-pacman [stable|rc|edge]" >&2 +} + +# Composite commands can postpone the legacy user hook until their own final +# privilege boundary. The two internal modes are deliberately paired: a caller +# that defers must invoke --run-deferred-hook exactly once after all of its +# sudo-capable work has finished. +channel=stable +hook_mode=normal +case "$#:$1:${2:-}" in + 0::) + ;; + 1:stable: | 1:rc: | 1:edge:) + channel="$1" + ;; + 1:--run-deferred-hook:) + hook_mode=run-deferred + ;; + 2:stable:--defer-hook | 2:rc:--defer-hook | 2:edge:--defer-hook) + channel="$1" + hook_mode=defer + ;; + *) + usage + exit 2 + ;; +esac + +trusted_directory_chain() { + local current="$1" allow_current_user="$2" canonical owner mode current_uid + current_uid=$(/usr/bin/id -u) || return 1 + + while :; do + [[ -d $current && ! -L $current ]] || return 1 + canonical=$(/usr/bin/realpath -e -- "$current") || return 1 + [[ $canonical == "$current" ]] || return 1 + [[ $current == / ]] && break + read -r owner mode < <(/usr/bin/stat -Lc '%u %a' -- "$current") || return 1 + if [[ $owner != 0 ]] && ! { [[ $allow_current_user == "true" && $owner == "$current_uid" ]]; }; then + return 1 + fi + (( (8#$mode & 0022) == 0 )) || return 1 + current=${current%/*} + [[ -n $current ]] || current=/ + done +} + +trusted_omarchy_source_root() { + local config=/etc/omarchy.conf default_root=/usr/share/omarchy configured_root="" canonical="" + local owner="" mode="" links="" size="" line="" encoded="" decoded="" character="" + local index=0 escaped=0 lines=() + + if [[ ! -e $config && ! -L $config ]]; then + configured_root="$default_root" + else + [[ -f $config && ! -L $config ]] || return 1 + canonical=$(/usr/bin/realpath -e -- "$config") || return 1 + [[ $canonical == "$config" ]] || return 1 + read -r owner mode links size < <(/usr/bin/stat -Lc '%u %a %h %s' -- "$config") || return 1 + [[ $owner == "0" && $links == "1" ]] || return 1 + (( (8#$mode & 0022) == 0 && size > 0 && size <= 4096 )) || return 1 + trusted_directory_chain /etc false || return 1 + mapfile -t lines <"$config" || return 1 + (( ${#lines[@]} == 1 )) || return 1 + line="${lines[0]}" + [[ $line == 'export OMARCHY_PATH="'*'"' ]] || return 1 + encoded="${line#'export OMARCHY_PATH="'}" + encoded="${encoded%'"'}" + for (( index = 0; index < ${#encoded}; index++ )); do + character="${encoded:index:1}" + if (( escaped )); then + case "$character" in + '\' | '"' | '$' | '`') decoded+="$character" ;; + *) return 1 ;; + esac + escaped=0 + elif [[ $character == '\' ]]; then + escaped=1 + elif [[ $character == '"' ]]; then + return 1 + else + decoded+="$character" + fi + done + (( escaped == 0 )) || return 1 + configured_root="$decoded" + fi -channel="${1:-stable}" + [[ -d $configured_root && ! -L $configured_root ]] || return 1 + canonical=$(/usr/bin/realpath -e -- "$configured_root") || return 1 + [[ $canonical == "$configured_root" ]] || return 1 + if [[ $configured_root == "$default_root" ]]; then + trusted_directory_chain "$configured_root" false || return 1 + else + trusted_directory_chain "$configured_root" true || return 1 + fi + printf '%s\n' "$configured_root" +} -if [[ $channel != "stable" && $channel != "rc" && $channel != "edge" ]]; then - echo "Error: Invalid channel '$channel'. Must be one of: stable, rc, edge" +trusted_omarchy_source_file() { + local relative="$1" source="$OMARCHY_PATH/$1" canonical owner mode links directory current_uid + current_uid=$(/usr/bin/id -u) || return 1 + [[ $relative != /* && $relative != ../* && $relative != */../* && $relative != */.. ]] || return 1 + [[ -f $source && ! -L $source ]] || return 1 + canonical=$(/usr/bin/realpath -e -- "$source") || return 1 + [[ $canonical == "$source" && $canonical == "$OMARCHY_PATH/"* ]] || return 1 + read -r owner mode links < <(/usr/bin/stat -Lc '%u %a %h' -- "$source") || return 1 + [[ $links == 1 ]] && (( (8#$mode & 0022) == 0 )) || return 1 + if [[ $OMARCHY_PATH == /usr/share/omarchy ]]; then + [[ $owner == 0 ]] || return 1 + else + [[ $owner == 0 || $owner == "$current_uid" ]] || return 1 + fi + + directory=${source%/*} + while [[ $directory == "$OMARCHY_PATH" || $directory == "$OMARCHY_PATH/"* ]]; do + [[ -d $directory && ! -L $directory ]] || return 1 + canonical=$(/usr/bin/realpath -e -- "$directory") || return 1 + [[ $canonical == "$directory" ]] || return 1 + read -r owner mode < <(/usr/bin/stat -Lc '%u %a' -- "$directory") || return 1 + (( (8#$mode & 0022) == 0 )) || return 1 + if [[ $OMARCHY_PATH == /usr/share/omarchy ]]; then + [[ $owner == 0 ]] || return 1 + else + [[ $owner == 0 || $owner == "$current_uid" ]] || return 1 + fi + [[ $directory == "$OMARCHY_PATH" ]] && break + directory=${directory%/*} + done + printf '%s\n' "$source" +} + +if ! OMARCHY_PATH=$(trusted_omarchy_source_root); then + echo "Refusing to refresh pacman from an untrusted Omarchy source root." >&2 exit 1 fi +export OMARCHY_PATH +user_path="${PATH:-/usr/bin:/bin}" +PATH="$OMARCHY_PATH/bin:/usr/bin:/usr/sbin:/bin:/sbin" +export PATH + +as_root() { + if ((EUID == 0)); then + "$@" + elif [[ ${OMARCHY_SUDO_NO_UPDATE:-0} == 1 ]]; then + /usr/bin/sudo -N -- "$@" + else + /usr/bin/sudo -- "$@" + fi +} + +cleanup_sudo_credentials() { + /usr/bin/sudo -k || true +} + +trap cleanup_sudo_credentials EXIT + +if [[ $hook_mode == "run-deferred" ]]; then + /usr/bin/sudo -k || exit 1 + PATH="$user_path" "$OMARCHY_PATH/bin/omarchy-hook" pre-refresh-pacman + exit +fi + +pacman_source=$(trusted_omarchy_source_file "default/pacman/pacman-$channel.conf") || { + echo "Refusing an untrusted pacman configuration source." >&2 + exit 1 +} +mirror_source=$(trusted_omarchy_source_file "default/pacman/mirrorlist-$channel") || { + echo "Refusing an untrusted pacman mirror source." >&2 + exit 1 +} + +as_root /usr/bin/cp -f -- /etc/pacman.conf /etc/pacman.conf.bak +as_root /usr/bin/cp -f -- /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.bak echo "Setting channel to $channel" echo -sudo cp -f "$OMARCHY_PATH/default/pacman/pacman-$channel.conf" /etc/pacman.conf -sudo cp -f "$OMARCHY_PATH/default/pacman/mirrorlist-$channel" /etc/pacman.d/mirrorlist +# The unprivileged shell opens the authorized source. Root consumes only the +# inherited descriptor, never a caller-writable development-checkout pathname. +as_root /usr/bin/install -T -o root -g root -m 0644 /dev/stdin /etc/pacman.conf <"$pacman_source" +as_root /usr/bin/install -T -o root -g root -m 0644 /dev/stdin /etc/pacman.d/mirrorlist <"$mirror_source" -# Allow user customization of /etc/pacman.conf before the upgrade runs -omarchy-hook pre-refresh-pacman +# Reset all package DBs and then update. +as_root /usr/bin/env OMARCHY_UPDATE_PACMAN=1 /usr/bin/pacman -Syyuu --noconfirm -# Reset all package DBs and then update -sudo env OMARCHY_UPDATE_PACMAN=1 pacman -Syyuu --noconfirm +# This legacy hook used to run before pacman. Executable user code cannot +# safely precede a later sudo authentication: a child can wait for the new +# timestamp even if the parent invalidates around the hook. Keep the hook, but +# run it only after every privileged refresh step and with a cold credential. +if [[ $hook_mode == "normal" ]]; then + /usr/bin/sudo -k || exit 1 + PATH="$user_path" "$OMARCHY_PATH/bin/omarchy-hook" pre-refresh-pacman +fi diff --git a/bin/omarchy-update b/bin/omarchy-update index e71e808664ee..4b0b1cc8044c 100755 --- a/bin/omarchy-update +++ b/bin/omarchy-update @@ -1,12 +1,217 @@ -#!/bin/bash +#!/bin/bash -p # omarchy:summary=Update Omarchy and system packages # omarchy:args=[-y] # omarchy:examples=omarchy update | omarchy update -y # omarchy:requires-sudo=true +if [[ $- != *p* ]]; then + echo "Refusing an unsafe Bash startup for the Omarchy update." >&2 + exit 126 +fi + +require_privileged_bash_startup() { + [[ $- == *p* ]] || return 1 + /usr/bin/env -i /usr/bin/bash -p -c ' + [[ $1 =~ ^[1-9][0-9]*$ ]] || exit 1 + mapfile -d "" -t argv <"/proc/$1/cmdline" || exit 1 + executable=$(/usr/bin/readlink -e -- "/proc/$1/exe") || exit 1 + [[ $executable == /usr/bin/bash ]] + [[ ${argv[0]:-} == /bin/bash || ${argv[0]:-} == /usr/bin/bash ]] + [[ ${argv[1]:-} == -p ]] + ' omarchy-bash-startup "$$" +} +if ! require_privileged_bash_startup; then + echo "Refusing an unsafe Bash startup for the Omarchy update." >&2 + exit 126 +fi +unset -f require_privileged_bash_startup + set -e +# Privileged mode prevents BASH_ENV and exported functions from running before +# this boundary. Re-exec once without their raw environment records so ordinary +# Bash helpers cannot import them again and bypass the trusted command paths. +sanitize_bash_startup_environment() { + local environment_entry environment_name + local needs_reexec=0 + local -a environment_unsets=(-u BASH_ENV -u ENV) + + [[ -z ${BASH_ENV+x} && -z ${ENV+x} ]] || needs_reexec=1 + while IFS= read -r -d '' environment_entry; do + environment_name="${environment_entry%%=*}" + if [[ $environment_name == BASH_FUNC_*%% ]]; then + environment_unsets+=(-u "$environment_name") + needs_reexec=1 + fi + done < <(/usr/bin/env -0) + + if (( needs_reexec )); then + exec /usr/bin/env "${environment_unsets[@]}" /usr/bin/bash -p "$0" "$@" + fi +} +sanitize_bash_startup_environment "$@" +unset -f sanitize_bash_startup_environment + +trusted_directory_chain() { + local current="$1" allow_current_user="$2" canonical owner mode current_uid + current_uid=$(/usr/bin/id -u) || return 1 + + while :; do + [[ -d $current && ! -L $current ]] || return 1 + canonical=$(/usr/bin/realpath -e -- "$current") || return 1 + [[ $canonical == "$current" ]] || return 1 + [[ $current == / ]] && break + read -r owner mode < <(/usr/bin/stat -Lc '%u %a' -- "$current") || return 1 + if [[ $owner != 0 ]] && ! { [[ $allow_current_user == "true" && $owner == "$current_uid" ]]; }; then + return 1 + fi + (( (8#$mode & 0022) == 0 )) || return 1 + current=${current%/*} + [[ -n $current ]] || current=/ + done +} + +trusted_omarchy_source_root() { + local config=/etc/omarchy.conf + local default_root=/usr/share/omarchy + local configured_root="" + local canonical="" + local owner="" + local mode="" + local links="" + local size="" + local line="" + local encoded="" + local decoded="" + local character="" + local index=0 + local escaped=0 + local lines=() + + if [[ ! -e $config && ! -L $config ]]; then + configured_root="$default_root" + else + [[ -f $config && ! -L $config ]] || return 1 + canonical=$(/usr/bin/realpath -e -- "$config") || return 1 + [[ $canonical == "$config" ]] || return 1 + read -r owner mode links size < <(/usr/bin/stat -Lc '%u %a %h %s' -- "$config") || return 1 + [[ $owner == "0" && $links == "1" ]] || return 1 + (( (8#$mode & 0022) == 0 && size > 0 && size <= 4096 )) || return 1 + trusted_directory_chain /etc false || return 1 + + mapfile -t lines <"$config" || return 1 + (( ${#lines[@]} == 1 )) || return 1 + line="${lines[0]}" + [[ $line == 'export OMARCHY_PATH="'*'"' ]] || return 1 + encoded="${line#'export OMARCHY_PATH="'}" + encoded="${encoded%'"'}" + + for (( index = 0; index < ${#encoded}; index++ )); do + character="${encoded:index:1}" + if (( escaped )); then + case "$character" in + '\' | '"' | '$' | '`') decoded+="$character" ;; + *) return 1 ;; + esac + escaped=0 + elif [[ $character == '\' ]]; then + escaped=1 + elif [[ $character == '"' ]]; then + return 1 + else + decoded+="$character" + fi + done + (( escaped == 0 )) || return 1 + configured_root="$decoded" + fi + + [[ -d $configured_root && ! -L $configured_root ]] || return 1 + canonical=$(/usr/bin/realpath -e -- "$configured_root") || return 1 + [[ $canonical == "$configured_root" ]] || return 1 + + if [[ $configured_root == "$default_root" ]]; then + trusted_directory_chain "$configured_root" false || return 1 + else + trusted_directory_chain "$configured_root" true || return 1 + fi + + printf '%s\n' "$configured_root" +} + +sudo_supports_no_update() { + LC_ALL=C /usr/bin/sudo -h 2>&1 | /usr/bin/grep -Eq '^usage: sudo .*\[[^]]*N[^]]*\]' +} + +validate_non_reusable_sudo() { + local wrapper_dir="$OMARCHY_PATH/default/omarchy/sudo-no-update" + local wrapper="$wrapper_dir/sudo" canonical="" current="" owner="" mode="" + + sudo_supports_no_update || { + echo "This sudo does not support --no-update; refusing to run a mixed-trust update." >&2 + return 1 + } + [[ -f $wrapper && -x $wrapper && ! -L $wrapper ]] || { + echo "Trusted no-update sudo wrapper is missing; refusing to run a mixed-trust update." >&2 + return 1 + } + canonical=$(/usr/bin/realpath -e -- "$wrapper") || return 1 + [[ $canonical == "$wrapper" ]] || return 1 + if [[ $OMARCHY_PATH == "/usr/share/omarchy" ]]; then + current="$wrapper" + while :; do + [[ ! -L $current ]] || return 1 + read -r owner mode < <(/usr/bin/stat -Lc '%u %a' -- "$current") || return 1 + [[ $owner == "0" ]] || return 1 + (( (8#$mode & 0022) == 0 )) || return 1 + [[ $current == "$OMARCHY_PATH" ]] && break + current=${current%/*} + done + fi +} + +enable_non_reusable_sudo() { + local wrapper_dir="$OMARCHY_PATH/default/omarchy/sudo-no-update" + + validate_non_reusable_sudo + PATH="$wrapper_dir:$PATH" + export PATH +} + +if ! OMARCHY_PATH=$(trusted_omarchy_source_root); then + echo "Refusing to update from an untrusted Omarchy source root." >&2 + exit 1 +fi +export OMARCHY_PATH +user_path="${PATH:-/usr/bin:/bin}" +PATH="$OMARCHY_PATH/bin:/usr/bin:/usr/sbin:/bin:/sbin" +export PATH +update_stay_awake_stopped=0 + +# Verify and enable the security primitive before any update-owned privileged +# work. Every authorization in this workflow is command-scoped (`sudo -N`): it +# may prompt for the command being run, but it never publishes a reusable +# timestamp to a dev hook, migration tool, AUR build, or detached child. +validate_non_reusable_sudo || exit 1 +if [[ ${OMARCHY_SUDO_NO_UPDATE:-0} == 1 ]]; then + enable_non_reusable_sudo +fi +/usr/bin/sudo -k || exit 1 +enable_non_reusable_sudo +export OMARCHY_SUDO_NO_UPDATE=1 + +cleanup_update() { + local status=$? + + trap - EXIT + if (( update_stay_awake_stopped == 0 )); then + omarchy-update-stay-awake stop || true + fi + /usr/bin/sudo -k || true + exit "$status" +} + if [[ -z ${OMARCHY_UPDATE_LOGGED:-} ]]; then script_command=$(printf '%q ' "$0" "$@") exec env OMARCHY_UPDATE_LOGGED=1 script -qefc "$script_command" "/tmp/omarchy-update.log" @@ -17,7 +222,7 @@ if ! omarchy-update-lock held; then fi trap 'echo ""; echo -e "\033[0;31mSomething went wrong during the update!\n\nPlease review the output above carefully, correct the error, and retry the update.\n\nIf you need assistance, get help from the community at https://omarchy.org/discord\033[0m"' ERR -trap 'omarchy-update-stay-awake stop' EXIT +trap cleanup_update EXIT omarchy-update-requires-free-space @@ -38,6 +243,9 @@ if [[ ${1:-} == "-y" ]] || omarchy-update-confirm; then omarchy-update-stay-awake start + # A dev link explicitly authorizes its checkout through root-owned system + # configuration (including sudo's secure_path), so preserve the established + # pull-before-packages/migrations ordering for that trusted mode. omarchy-update-dev omarchy-update-keyring @@ -45,20 +253,41 @@ if [[ ${1:-} == "-y" ]] || omarchy-update-confirm; then # them, so everything below waits on this finishing. An upgrade that stopped # takes the update with it rather than migrating against what is still on disk. omarchy-update-system-pkgs + + # Historical migrations are strictly ordered and mix user hooks/downloaded + # tooling with privileged repairs. The no-update sudo wrapper has covered the + # whole update, so neither the package transaction nor a later repair can + # publish a timestamp to a detached migration child. + /usr/bin/sudo -k omarchy-migrate - omarchy-hook post-update - omarchy-update-aur-pkgs - omarchy-update-mise omarchy-update-orphan-pkgs omarchy-update-analyze-logs omarchy-update-status + # Service restart helpers can need sudo. Run them before any user-controlled + # update tooling; the reboot-only phase below performs no privileged work. + omarchy-update-restart --services-only + # Release update-owned inhibitors before offering a reboot. A confirmed # reboot can terminate this process before its EXIT trap gets a chance to # remove the persistent Stay Awake marker. omarchy-update-stay-awake stop - trap - EXIT + update_stay_awake_stopped=1 + + # AUR installation can refresh sudo after running package build code. No + # privileged update stage may follow it: user-controlled code can outlive + # its parent and wait for a later timestamp even if we invalidate in between. + omarchy-update-aur-pkgs + /usr/bin/sudo -k + + # Hooks and mise execute user-controlled code. Give each a cold credential + # boundary and run mise last so it cannot wait for a legitimate hook sudo. + # Only the unprivileged reboot prompt follows them. + PATH="$user_path" "$OMARCHY_PATH/bin/omarchy-hook" post-update + /usr/bin/sudo -k + PATH="$user_path" "$OMARCHY_PATH/bin/omarchy-update-mise" + /usr/bin/sudo -k - omarchy-update-restart + "$OMARCHY_PATH/bin/omarchy-update-restart" --reboot-only fi diff --git a/config/omarchy/hooks/pre-refresh-pacman.d/add-custom-repo.sample b/config/omarchy/hooks/pre-refresh-pacman.d/add-custom-repo.sample index cebec4fc8dba..0c8ba7c437b0 100644 --- a/config/omarchy/hooks/pre-refresh-pacman.d/add-custom-repo.sample +++ b/config/omarchy/hooks/pre-refresh-pacman.d/add-custom-repo.sample @@ -1,17 +1,20 @@ #!/bin/bash -# This hook is called by `omarchy refresh pacman` AFTER the channel template -# is copied to /etc/pacman.conf and BEFORE `pacman -Syyuu` runs. Use it to -# layer customizations onto the freshly-written pacman.conf so they're -# respected by the upgrade — common cases are adding a custom repository +# This legacy-named hook is called by `omarchy refresh pacman` AFTER the +# channel template is copied and the privileged package transaction finishes. +# During `omarchy channel set`, it is deferred until the package switch and +# complete update have also finished. +# Use it to layer customizations onto the freshly-written pacman.conf for +# subsequent package operations — common cases are adding a custom repository # (e.g. CachyOS, Chaotic-AUR, an internal company repo) or extra IgnorePkg # lines. # -# The hook runs as the invoking user with a warm sudo cache. +# The hook runs as the invoking user after Omarchy invalidates its sudo cache. +# A sudo command here therefore requires its own explicit authorization. # # To put it into use, remove .sample from this file name. -# Example: add an Include line above [core] for a custom repo. +# Example: add an Include line above [core] for future package operations. # Maintain the repo entries in /etc/pacman.d/custom-repos.conf yourself. CONF=/etc/pacman.conf diff --git a/default/agents/skills/omarchy/hooks.md b/default/agents/skills/omarchy/hooks.md index 4f8236ac0b79..4878c7e19847 100644 --- a/default/agents/skills/omarchy/hooks.md +++ b/default/agents/skills/omarchy/hooks.md @@ -14,8 +14,8 @@ file first, if one exists. ├── battery-low.d/ # Low battery (percentage in $1) ├── font-set.d/ # After font change (font name in $1) ├── post-boot.d/ # After the desktop starts -├── post-update.d/ # During `omarchy update`, after system packages and migrations -├── pre-refresh-pacman.d/ # Before `omarchy refresh pacman` re-syncs packages +├── post-update.d/ # At the end of `omarchy update`, after privileged work +├── pre-refresh-pacman.d/ # After `omarchy refresh pacman` finishes (legacy name) └── theme-set.d/ # After theme change (theme slug in $1) ``` @@ -26,3 +26,5 @@ THEME_NAME=$1 echo "Theme changed to: $THEME_NAME" # Add custom actions here ``` + +Update-related hooks run only after the workflow's privileged work and after Omarchy invalidates its sudo timestamp. A hook that invokes `sudo` must therefore request its own explicit authorization. The legacy-named `pre-refresh-pacman` hook runs after the refresh transaction; during `omarchy channel set`, it is deferred further until the package switch and complete update finish. Executable user code cannot safely run before a later sudo authentication because a detached child could wait for the new timestamp. diff --git a/default/omarchy/sudo-no-update/sudo b/default/omarchy/sudo-no-update/sudo new file mode 100755 index 000000000000..ca94c1e63ff5 --- /dev/null +++ b/default/omarchy/sudo-no-update/sudo @@ -0,0 +1,27 @@ +#!/bin/bash -p + +# Internal update/migration sudo boundary. Authentication may authorize this +# command, but -N prevents it from publishing a timestamp that detached user +# code can silently reuse. + +if [[ $- != *p* ]]; then + echo "Refusing an unsafe Bash startup for the sudo boundary." >&2 + exit 126 +fi + +require_privileged_bash_startup() { + [[ $- == *p* ]] || return 1 + /usr/bin/env -i /usr/bin/bash -p -c ' + [[ $1 =~ ^[1-9][0-9]*$ ]] || exit 1 + mapfile -d "" -t argv <"/proc/$1/cmdline" || exit 1 + executable=$(/usr/bin/readlink -e -- "/proc/$1/exe") || exit 1 + [[ $executable == /usr/bin/bash ]] + [[ ${argv[0]:-} == /bin/bash || ${argv[0]:-} == /usr/bin/bash ]] + [[ ${argv[1]:-} == -p ]] + ' omarchy-bash-startup "$$" +} +if ! require_privileged_bash_startup; then + echo "Refusing an unsafe Bash startup for the sudo boundary." >&2 + exit 126 +fi +exec /usr/bin/sudo -N -- "$@" diff --git a/docs/update-process.md b/docs/update-process.md index bec3350d1d46..bb73d27101ac 100644 --- a/docs/update-process.md +++ b/docs/update-process.md @@ -26,7 +26,7 @@ The design goal is: | `~/.local/state/omarchy/current/` | user | Generated active theme, selected theme name, and current background symlink. | | `~/.local/state/omarchy/migrations/` | user | Per-user migration markers. | | `~/.local/state/omarchy/reboot-required` | user | Optional reboot marker checked by `omarchy-update-restart`. | -| `~/.local/state/omarchy/restart-*-required` | user | Optional service/app restart markers checked by `omarchy-update-restart`. The shell needs no marker: it is restarted unconditionally after every update. | +| `~/.local/state/omarchy/restart-*-required` | user | Optional allowlisted service/app restart markers checked by `omarchy-update-restart`. Marker names select fixed commands from the system-authorized Omarchy tree; they are not resolved through caller `PATH`. The shell needs no marker: it is restarted unconditionally after every update. | ## Migration layout @@ -56,6 +56,13 @@ privileged work should invoke the appropriate helper or privilege prompt. Migrations must be idempotent; if one user already applied a machine-wide repair, the migration should no-op for other users. +The runner derives the migration source from root-owned `/etc/omarchy.conf`, +starts from a cold sudo timestamp, and routes migration sudo calls through +`sudo --no-update`. Historical migrations are strictly ordered and can mix +user-controlled tools or theme hooks with later privileged repairs; no-update +authentication lets those repairs run without publishing a credential a +detached earlier process could reuse. + For watchers and diagnostics, `omarchy-migrate --pending` prints pending migration names and exits `0` when any are pending. When no migrations are pending, it prints nothing and exits non-zero. @@ -125,18 +132,28 @@ omarchy-update │ installed but unconfigured fails the snapshot loudly, pointing at │ install/config/snapper.sh, and the update continues without one) ├─ omarchy-update-stay-awake start - ├─ run package updates, migrations, hooks, and log analysis + ├─ run system-package updates + ├─ invalidate sudo, then run migrations and all later privileged work with + │ no-update authentication + ├─ run orphan review and log analysis ├─ omarchy-update-status │ └─ refresh or clear the shell update indicator + ├─ restart marked services and the shell ├─ omarchy-update-stay-awake stop │ └─ release the sleep inhibitor and restore shell idle state, if changed - └─ omarchy-update-restart + ├─ update AUR packages + ├─ invalidate sudo credentials + ├─ run the post-update hook, invalidate again, then update mise tools + └─ offer the unprivileged reboot prompt ``` Important behavior: -- In dev-link mode, `omarchy update` fast-forwards the active checkout from its - configured upstream before changing system packages or running migrations. +- `omarchy update` derives its source tree from root-owned `/etc/omarchy.conf`, or the root-owned `/usr/share/omarchy` default when that file is absent. It does not trust inherited `OMARCHY_PATH` or caller `PATH` for the privileged phase. +- Mixed-trust update entrypoints start Bash in privileged mode, discard `BASH_ENV`, `ENV`, and exported-function records before launching helpers, and reject an ordinary `bash path/to/command` invocation. Run them as executables (normally through the `omarchy` CLI); `/usr/bin/bash -p path/to/command` is the explicit interpreter form. This keeps shell startup injection from replacing the no-update sudo boundary. +- In dev-link mode, the root-owned configuration is the explicit authorization for the user-writable checkout. `omarchy update` fast-forwards that authorized checkout from its configured upstream before changing system packages or running migrations. +- Migrations remain in chronological order even though historical entries mix user-controlled code with later privileged repairs. Before entering that mixed-trust tail, Omarchy invalidates its timestamp and forces every later sudo call—including AUR's configurable sudo command—to use `--no-update`; prompts authorize one command without publishing a reusable timestamp. Yay's credential loop is disabled for the update. +- User-controlled post-update hooks and mise tools run only after every sudo-capable update stage. Omarchy invalidates its sudo timestamp before each boundary and on every exit; detached children therefore have no later reusable update authorization to wait for. - `-y` exports `OMARCHY_UPDATE_UNATTENDED=1` — a promise not to ask anything. Steps that would prompt (orphan removal, conflict handoff) report and skip instead of blocking. @@ -251,6 +268,9 @@ which pacman repo the mirrorlist points at (and swap between the `omarchy` and `omarchy-dev` packages through a guard-allowed pacman run), while `dev` links the runtime to a git checkout via the dev-link mechanism, after which `omarchy update` fast-forwards that checkout instead of upgrading a package. +Channel switching defers the legacy `pre-refresh-pacman` hook across the package +swap and the complete update. The hook runs exactly once at the final cold +credential boundary; it is skipped if the composite operation fails earlier. There is no version file at runtime. `omarchy-version` derives the version from `pacman -Q` on whichever package is installed, or reports `dev ()` for a @@ -272,8 +292,7 @@ scripts. | `omarchy-update-confirm` | Gum confirmation copy for `omarchy update`. | **Question.** Could be inlined into `omarchy-update`; separate file only helps keep copy isolated. | | `omarchy-update-dev` | Fast-forwards the active dev-linked checkout from its configured upstream; no-ops for package-backed installs. | **Keep.** Runs before package updates so a checkout conflict stops the update before system mutation. | | `omarchy-update-keyring` | Ensures Omarchy keyring and Arch keyring are current before the main transaction. | **Keep, but review.** It uses targeted `pacman -Sy` for keyring bootstrapping; acceptable for this special case but should remain tightly scoped. | -| `omarchy-update-system-pkgs` | Runs `sudo env OMARCHY_UPDATE_PACMAN=1 pacman -Syu --noconfirm` with `--overwrite '/usr/share/omarchy/*'`, capturing stderr to a report file; on failure it execs `omarchy-update-system-pkgs-when-conflicted`. | **Keep for now.** Small leaf command, clear/testable. | -| `omarchy-update-system-pkgs-when-conflicted` | Hidden conflict handler: quarantines unowned conflicting files under `/var/lib/omarchy/replaced`, retries the upgrade once, restores files the upgrade didn't claim, and hands package-vs-package conflicts to an interactive pacman run (never under `-y`). | **Keep internal/hidden.** Keeps conflict recovery out of the happy path. | +| `omarchy-update-system-pkgs` | Runs the ordinary guarded `pacman -Syu --noconfirm`. Package-vs-package conflicts may be retried interactively with `pacman -Su`; filesystem conflicts fail closed without moving, restoring, quarantining, or broadly overwriting live paths. The production Quattro transition performs the sole explicit settings-package takeover with `--overwrite='*'`; all later production and developer package transactions obey Pacman's ownership checks. | **Keep.** Small leaf command with no generic privileged conflict handler. | | `omarchy-update-pkg-prune` | Trims the pacman cache to two versions per package (`paccache -rk2`) before the snapshot, keeping the offline downgrade path while capping snapshot growth. | **Keep internal/hidden.** | | `omarchy-update-requires-free-space` | Aborts the update below a 10 GiB free-space threshold on `/`; silently skipped when free space cannot be determined; `OMARCHY_UPDATE_FORCE=1` bypasses. | **Keep internal/hidden.** | | `omarchy-migrate` | Public migration command. Waits for pacman, then runs all pending migrations for the current user. Supports `--pending`. | **Keep.** This replaces the discarded `omarchy-update-user-finalize` name and no longer needs `--force`. | @@ -285,7 +304,7 @@ scripts. | `omarchy-update-mise` | Runs `MISE_MINIMUM_RELEASE_AGE=0 mise up` for mise-managed tools — the override of mise's release-age cooldown is the point. | **Keep.** Mise-managed tools are intentionally part of the blessed update path. | | `omarchy-update-orphan-pkgs` | Lists orphans and prompts before removal; noninteractive mode never removes. | **Keep for now.** Safe because it is prompt-only. | | `omarchy-update-analyze-logs` | Scans `/tmp/omarchy-update.log` for known failure patterns, currently initramfs generation. | **Keep/expand.** Useful safety net; should grow only for high-signal checks. | -| `omarchy-update-restart` | Prompts for reboot after kernel/Hyprland updates, restarts components with `restart-*-required` markers, and always restarts the shell. | **Keep.** Important final step; may eventually include service-restart checks. | +| `omarchy-update-restart` | Restarts allowlisted components selected by `restart-*-required` markers, always restarts the shell, and prompts for reboot after kernel/Hyprland updates. Internal phase flags let the update finish sudo-capable restarts before user hooks and defer only the unprivileged reboot prompt. | **Keep.** Important final step; may eventually include service-restart checks. | | `omarchy-update-firmware` | Manual firmware update command using fwupd. Not part of the normal update pipeline. | **Keep separate.** Firmware is not a routine system update step. | | `omarchy-update-time` | Restarts `systemd-timesyncd`. | **Question.** Not really an update command. Consider renaming/moving under system/time maintenance. | diff --git a/test/shell.d/update-hook-security-test.sh b/test/shell.d/update-hook-security-test.sh new file mode 100644 index 000000000000..6245205f3007 --- /dev/null +++ b/test/shell.d/update-hook-security-test.sh @@ -0,0 +1,1040 @@ +#!/bin/bash + +set -euo pipefail + +source "$(dirname "$0")/base-test.sh" + +# The setuid helper below models the strongest sudo timestamp mode: one token +# shared by every process for this uid. That makes a detached hook child a +# faithful regression for both global timestamps and the easier tty-sharing +# case. The helper is mounted over /usr/bin/sudo only in this private namespace +# so the scripts must use the fixed trusted invalidation path. +if [[ ${OMARCHY_UPDATE_HOOK_SECURITY_NS:-} != 1 ]]; then + outer_uid=$(id -u) + outer_gid=$(id -g) + subuid=$(awk -F: -v user="$(id -un)" '$1 == user { print $2; exit }' /etc/subuid) + subgid=$(awk -F: -v group="$(id -gn)" '$1 == group { print $2; exit }' /etc/subgid) + + if [[ -z $subuid || -z $subgid ]]; then + pass "no subordinate uid/gid range; skipping update-hook namespace proof" + exit 0 + fi + + exec unshare --user --mount \ + --map-users "0:$outer_uid:1" --map-users "1:$subuid:65536" \ + --map-groups "0:$outer_gid:1" --map-groups "1:$subgid:65536" \ + env OMARCHY_UPDATE_HOOK_SECURITY_NS=1 bash "$0" +fi + +[[ $(id -u) == 0 ]] || fail "update-hook proof entered its root namespace" + +mount -t tmpfs -o mode=0755 tmpfs /run +run_bound=1 +test_tmp=$(mktemp -d -p /run omarchy-update-hook-security.XXXXXXXX) +mount -t tmpfs -o mode=0755 tmpfs "$test_tmp" +chmod 0755 "$test_tmp" +sudo_path_bound=0 +channel_paths_bound=0 +channel_wrapper_tree_bound=0 +aur_paths_bound=0 +font_paths_bound=0 +migration_pkg_paths_bound=0 +etc_bound=0 +persistent_pids=() +cleanup() { + local pid pid_file + for pid_file in "$test_home"/*.pid; do + if [[ -s $pid_file ]]; then + persistent_pids+=("$(<"$pid_file")") + fi + done + for pid in "${persistent_pids[@]}"; do + kill "$pid" 2>/dev/null || true + done + sleep 0.05 + for pid in "${persistent_pids[@]}"; do + kill -KILL "$pid" 2>/dev/null || true + done + if (( sudo_path_bound )); then + umount /usr/bin/sudo + fi + if (( channel_paths_bound )); then + umount /usr/bin/pacman + umount /usr/bin/omarchy-dev-unlink + umount /usr/bin/omarchy-state + umount /usr/bin/omarchy-refresh-pacman + umount /usr/bin/omarchy-update + fi + if (( channel_wrapper_tree_bound )); then + umount /usr/share/omarchy + fi + if (( aur_paths_bound )); then + umount /usr/bin/omarchy-pkg-aur-accessible + umount /usr/bin/yay + fi + if (( font_paths_bound )); then + umount /usr/bin/omarchy-launch-floating-terminal-with-presentation + umount /usr/bin/omarchy-pkg-add + umount /usr/bin/omarchy-font-set + fi + if (( migration_pkg_paths_bound )); then + umount /usr/bin/omarchy-pkg-missing + umount /usr/bin/omarchy-pkg-add + fi + if (( etc_bound )); then + umount /etc + fi + rm -rf "$test_tmp"/* + umount "$test_tmp" + rmdir "$test_tmp" + if (( run_bound )); then + umount /run + fi +} +trap cleanup EXIT + +stub_bin="$test_tmp/bin" +test_home="$test_tmp/home" +root_dir="$test_tmp/root" +token="$test_tmp/sudo-token" +event_log="$test_tmp/events" +hook_log="$test_home/hook-events" +mkdir -p "$stub_bin" "$test_home/.config/omarchy/hooks" "$root_dir" +mkdir -p "$test_tmp/default/omarchy/sudo-no-update" +cp "$ROOT/default/omarchy/sudo-no-update/sudo" "$test_tmp/default/omarchy/sudo-no-update/sudo" +chmod 0755 "$test_tmp/default/omarchy/sudo-no-update/sudo" +mkdir -p "$test_tmp/default/pacman" +cp "$ROOT/default/pacman"/* "$test_tmp/default/pacman/" +chmod 0755 "$test_tmp/default" "$test_tmp/default/omarchy" \ + "$test_tmp/default/omarchy/sudo-no-update" "$test_tmp/default/pacman" +chmod 0644 "$test_tmp/default/pacman"/* +touch "$event_log" "$hook_log" +chown -R 1000:1000 "$test_home" +chown 1000:1000 "$event_log" +chmod 0700 "$test_home" +chmod 0600 "$event_log" "$hook_log" +chmod 0755 "$stub_bin" "$root_dir" + +cat >"$test_tmp/sudo.c" <<'C' +#include +#include +#include +#include +#include +#include +#include + +static const char *required_env(const char *name) { + const char *value = getenv(name); + if (!value || !*value) exit(125); + return value; +} + +static void log_event(const char *event) { + int fd = open(required_env("TEST_SUDO_EVENT_LOG"), O_WRONLY | O_APPEND); + if (fd < 0) exit(125); + if (dprintf(fd, "%s\n", event) < 0) exit(125); + close(fd); +} + +static int authenticate(void) { + int fd = open(required_env("TEST_SUDO_TOKEN"), O_WRONLY | O_CREAT | O_TRUNC, 0600); + if (fd < 0) return 125; + close(fd); + return 0; +} + +static int token_valid(void) { + struct stat st; + return stat(required_env("TEST_SUDO_TOKEN"), &st) == 0 && st.st_uid == 0; +} + +static int is_pacman_command(int argc, char **argv) { + int index; + for (index = 1; index < argc; index++) { + const char *base = strrchr(argv[index], '/'); + base = base ? base + 1 : argv[index]; + if (strcmp(base, "pacman") == 0) return 1; + } + return 0; +} + +int main(int argc, char **argv) { + int no_update = 0; + if (argc == 2 && strcmp(argv[1], "-h") == 0) { + const char *disable = getenv("TEST_SUDO_NO_N"); + if (disable && strcmp(disable, "1") == 0) { + fputs("usage: sudo [-ABbEHknPS] command\n", stdout); + } else { + fputs("usage: sudo [-ABbEHkNnPS] command\n", stdout); + } + return 0; + } + if (argc > 1 && strcmp(argv[1], "-N") == 0) { + no_update = 1; + argc--; + argv++; + } + if (argc > 1 && strcmp(argv[1], "--") == 0) { + argc--; + argv++; + } + if (argc == 2 && strcmp(argv[1], "--authenticate-for-test") == 0) { + if (no_update) { + log_event("authenticate-no-update"); + return 0; + } else { + log_event("authenticate"); + return authenticate(); + } + } + if (argc == 2 && strcmp(argv[1], "-k") == 0) { + log_event("invalidate"); + if (unlink(required_env("TEST_SUDO_TOKEN")) < 0 && errno != ENOENT) return 125; + return 0; + } + if (!token_valid() && !no_update) { + if (is_pacman_command(argc, argv)) { + log_event("authenticate-command"); + if (authenticate() != 0) return 125; + } else { + log_event("deny"); + fputs("sudo: a password is required\n", stderr); + return 1; + } + } + log_event(no_update ? "grant-no-update" : "grant"); + if (argc < 2 || setuid(0) < 0) return 125; + execvp(argv[1], &argv[1]); + return 125; +} +C +gcc -O2 -Wall -Wextra -o "$stub_bin/sudo" "$test_tmp/sudo.c" +chown 0:0 "$stub_bin/sudo" +chmod 4755 "$stub_bin/sudo" +mount --bind "$stub_bin/sudo" /usr/bin/sudo +sudo_path_bound=1 +mount --bind "$ROOT/bin/omarchy-refresh-pacman" /usr/bin/omarchy-refresh-pacman +mount --bind "$ROOT/bin/omarchy-update" /usr/bin/omarchy-update +mount -t tmpfs -o mode=0755 tmpfs /usr/share/omarchy +mkdir -p /usr/share/omarchy/default/omarchy/sudo-no-update +cp "$ROOT/default/omarchy/sudo-no-update/sudo" /usr/share/omarchy/default/omarchy/sudo-no-update/sudo +chmod 0755 /usr/share/omarchy/default /usr/share/omarchy/default/omarchy \ + /usr/share/omarchy/default/omarchy/sudo-no-update +chmod 0755 /usr/share/omarchy/default/omarchy/sudo-no-update/sudo +channel_wrapper_tree_bound=1 + +# Authorize this private tree exactly as omarchy-dev-link authorizes a +# development checkout. Hiding the host /etc keeps the proof self-contained. +mount -t tmpfs -o mode=0755 tmpfs /etc +etc_bound=1 +mkdir -p /etc/pacman.d +touch /etc/pacman.conf /etc/pacman.d/mirrorlist +chmod 0644 /etc/pacman.conf /etc/pacman.d/mirrorlist +printf 'root:x:0:0:root:/root:/bin/bash\n' >/etc/passwd +printf 'root:x:0:\n' >/etc/group +chmod 0644 /etc/passwd /etc/group +write_authorized_source_root() { + local source_root="$1" + local quoted="$source_root" + + quoted=${quoted//\\/\\\\} + quoted=${quoted//\"/\\\"} + quoted=${quoted//\$/\\\$} + quoted=${quoted//\`/\\\`} + printf 'export OMARCHY_PATH="%s"\n' "$quoted" >/etc/omarchy.conf + chown 0:0 /etc/omarchy.conf + chmod 0644 /etc/omarchy.conf +} +write_authorized_source_root "$test_tmp" + +cat >"$test_home/launch-persistent-attack" <<'ATTACK' +#!/bin/bash +/usr/bin/setsid --fork /bin/bash -c ' + printf "%s\n" "$$" >"$3" + for (( attempt = 0; attempt < 200; attempt++ )); do + if /usr/bin/sudo /usr/bin/install -o 0 -g 0 -m 0600 "$1" "$2" 2>/dev/null; then + exit 0 + fi + /usr/bin/sleep 0.01 + done +' omarchy-hook-child "$HOME/payload" "$1" "$2" +ATTACK +cat >"$test_home/payload" <<'PAYLOAD' +RUN+="/tmp/update-hook-payload" +PAYLOAD +chown 1000:1000 "$test_home/launch-persistent-attack" "$test_home/payload" +chmod 0700 "$test_home/launch-persistent-attack" +chmod 0600 "$test_home/payload" + +cat >"$stub_bin/omarchy-update-lock" <<'STUB' +#!/bin/bash +[[ ${1:-} == held ]] +STUB +cat >"$stub_bin/omarchy-update-system-pkgs" <<'STUB' +#!/bin/bash +[[ ${TEST_SKIP_UPDATE_AUTH:-0} == 1 ]] || sudo --authenticate-for-test +STUB +cat >"$stub_bin/omarchy-update-orphan-pkgs" <<'STUB' +#!/bin/bash +[[ ${TEST_SKIP_LATE_AUTH:-0} == 1 ]] || sudo --authenticate-for-test +STUB +cat >"$stub_bin/omarchy-update-aur-pkgs" <<'STUB' +#!/bin/bash +[[ ${TEST_SKIP_LATE_AUTH:-0} == 1 ]] || sudo --authenticate-for-test +STUB +cat >"$stub_bin/omarchy-update-mise" <<'STUB' +#!/bin/bash +sudo /usr/bin/true 2>/dev/null && exit 97 +"$HOME/launch-persistent-attack" "$TEST_MISE_VICTIM" "$TEST_MISE_PID" +STUB +cat >"$stub_bin/omarchy-update-restart" <<'STUB' +#!/bin/bash +printf 'restart:%s\n' "$1" >>"$TEST_HOOK_LOG" +if [[ $1 == --services-only && ${TEST_SKIP_LATE_AUTH:-0} != 1 ]]; then + sudo --authenticate-for-test +fi +STUB +cat >"$stub_bin/omarchy-update-confirm" <<'STUB' +#!/bin/bash +exit 0 +STUB +cat >"$stub_bin/omarchy-migrate" <<'STUB' +#!/bin/bash +if [[ ${TEST_REAL_MIGRATE:-0} == 1 ]]; then + exec "$TEST_ROOT/bin/omarchy-migrate" +fi +if [[ ${TEST_FAILING_STAGE:-} == signal ]]; then + kill -TERM "$PPID" + sleep 0.1 +fi +[[ ${TEST_FAILING_STAGE:-} != migration ]] +STUB +cat >"$stub_bin/omarchy-hook" <<'STUB' +#!/bin/bash +exec bash "$TEST_ROOT/bin/omarchy-hook" "$@" +STUB +cat >"$stub_bin/omarchy-dev-unlink" <<'STUB' +#!/bin/bash +exit 0 +STUB +cat >"$stub_bin/omarchy-state" <<'STUB' +#!/bin/bash +exit 0 +STUB +for command in \ + omarchy-update-requires-free-space omarchy-update-pkg-prune omarchy-snapshot \ + omarchy-update-stay-awake omarchy-update-dev omarchy-update-keyring \ + omarchy-update-analyze-logs omarchy-update-status; do + cat >"$stub_bin/$command" <<'STUB' +#!/bin/bash +exit 0 +STUB +done +cat >"$stub_bin/cp" <<'STUB' +#!/bin/bash +printf 'cp:%s\n' "$*" >>"$TEST_SUDO_EVENT_LOG" +exit 0 +STUB +cat >"$stub_bin/pacman" <<'STUB' +#!/bin/bash +[[ -z ${TEST_PACMAN_DELAY:-} ]] || /usr/bin/sleep "$TEST_PACMAN_DELAY" +exit "${TEST_PACMAN_STATUS:-0}" +STUB +chmod 0755 "$stub_bin"/* +chmod 4755 "$stub_bin/sudo" +mount --bind "$stub_bin/omarchy-dev-unlink" /usr/bin/omarchy-dev-unlink +mount --bind "$stub_bin/omarchy-state" /usr/bin/omarchy-state +mount --bind "$stub_bin/pacman" /usr/bin/pacman +channel_paths_bound=1 + +evil_update_bin="$test_home/evil-update-bin" +evil_update_root="$test_home/evil-update-root" +evil_update_marker="$test_home/evil-update-ran" +mkdir -p "$evil_update_bin" "$evil_update_root/migrations" +for command in script omarchy-migrate omarchy-update-system-pkgs; do + cat >"$evil_update_bin/$command" <<'STUB' +#!/bin/bash +touch "$TEST_EVIL_UPDATE_MARKER" +exit 97 +STUB +done +cat >"$evil_update_bin/omarchy-dev-unlink" <<'STUB' +#!/bin/bash +touch "$TEST_EVIL_CHANNEL_HELPER_MARKER" +sudo /usr/bin/install -o 0 -g 0 -m 0600 "$HOME/payload" "$TEST_EVIL_CHANNEL_VICTIM" +STUB +cat >"$evil_update_root/migrations/9999999999.sh" <<'STUB' +#!/bin/bash +sudo /usr/bin/install -o 0 -g 0 -m 0600 "$HOME/payload" "$TEST_EVIL_MIGRATION_VICTIM" +touch "$TEST_EVIL_UPDATE_MARKER" +STUB +chown -R 1000:1000 "$evil_update_bin" "$evil_update_root" +chmod 0755 "$evil_update_bin"/* "$evil_update_root/migrations/9999999999.sh" + +write_attack_hook() { + local hook_name="$1" + + mkdir -p "$test_home/.config/omarchy/hooks/$hook_name.d" + cat >"$test_home/.config/omarchy/hooks/$hook_name" <<'HOOK' +#!/bin/bash +printf 'file:%s\n' "$(id -u)" >>"$TEST_HOOK_LOG" +sudo /usr/bin/install -o 0 -g 0 -m 0600 "$HOME/payload" "$TEST_ROOT_VICTIM" 2>/dev/null || true +"$HOME/launch-persistent-attack" "$TEST_PERSISTENT_VICTIM" "$TEST_PERSISTENT_PID" +HOOK + cat >"$test_home/.config/omarchy/hooks/$hook_name.d/10-attack" <<'HOOK' +#!/bin/bash +printf 'directory:%s\n' "$(id -u)" >>"$TEST_HOOK_LOG" +sudo /usr/bin/install -o 0 -g 0 -m 0600 "$HOME/payload" "$TEST_ROOT_DIR_VICTIM" 2>/dev/null || true +HOOK + chown -R 1000:1000 "$test_home/.config/omarchy/hooks/$hook_name" \ + "$test_home/.config/omarchy/hooks/$hook_name.d" + chmod 0700 "$test_home/.config/omarchy/hooks/$hook_name" \ + "$test_home/.config/omarchy/hooks/$hook_name.d/10-attack" +} + +reset_case() { + local pid_file + for pid_file in "$test_home"/*.pid; do + if [[ -s $pid_file ]]; then + persistent_pids+=("$(<"$pid_file")") + kill "$(<"$pid_file")" 2>/dev/null || true + fi + done + rm -f "$test_home"/*.pid "$token" "$root_dir"/* + : >"$event_log" + setpriv --reuid 1000 --regid 1000 --clear-groups /usr/bin/truncate -s 0 "$hook_log" +} + +run_as_user() { + setpriv --reuid 1000 --regid 1000 --clear-groups \ + env HOME="$test_home" PATH="$stub_bin:/usr/bin:/bin" OMARCHY_PATH="$ROOT" \ + TEST_ROOT="$ROOT" TEST_SUDO_TOKEN="$token" TEST_SUDO_EVENT_LOG="$event_log" \ + TEST_HOOK_LOG="$hook_log" "$@" +} + +authenticate_for_test() { + TEST_SUDO_TOKEN="$token" TEST_SUDO_EVENT_LOG="$event_log" \ + /usr/bin/sudo --authenticate-for-test +} + +wait_for_persistent_attempts() { + local pid_file="$1" + local pid="" + for (( attempt = 0; attempt < 100; attempt++ )); do + [[ -s $pid_file ]] && break + sleep 0.01 + done + [[ -s $pid_file ]] || fail "detached hook child did not start" + pid=$(<"$pid_file") + persistent_pids+=("$pid") + sleep 0.2 +} + +assert_hook_sandboxed() { + local direct_victim="$1" + local directory_victim="$2" + local persistent_victim="$3" + + [[ ! -e $direct_victim && ! -e $directory_victim && ! -e $persistent_victim ]] || + fail "hook code reused an Omarchy sudo credential" + grep -qxF 'file:1000' "$hook_log" || fail "the regular hook did not run as the desktop user" + grep -qxF 'directory:1000' "$hook_log" || fail "the hook-directory entry did not run as the desktop user" + [[ ! -e $token ]] || fail "the workflow left its modeled sudo credential live" +} + +write_attack_hook post-update +update_victim="$root_dir/80-update-hook.rules" +update_dir_victim="$root_dir/81-update-hook-dir.rules" +update_persistent_victim="$root_dir/82-update-hook-child.rules" +mise_victim="$root_dir/83-mise-child.rules" +reset_case +set +e +run_as_user env PATH="$evil_update_bin:$stub_bin:/usr/bin:/bin" OMARCHY_PATH="$evil_update_root" \ + TEST_EVIL_UPDATE_MARKER="$evil_update_marker" \ + TEST_ROOT_VICTIM="$update_victim" TEST_ROOT_DIR_VICTIM="$update_dir_victim" \ + TEST_PERSISTENT_VICTIM="$update_persistent_victim" TEST_PERSISTENT_PID="$test_home/update.pid" \ + TEST_MISE_VICTIM="$mise_victim" TEST_MISE_PID="$test_home/mise.pid" \ + OMARCHY_UPDATE_LOGGED=1 "$ROOT/bin/omarchy-update" -y \ + >"$test_tmp/update.out" 2>"$test_tmp/update.err" +status=$? +set -e +(( status == 0 )) || fail "isolated unattended update failed" "$(<"$test_tmp/update.err")" +wait_for_persistent_attempts "$test_home/update.pid" +wait_for_persistent_attempts "$test_home/mise.pid" +assert_hook_sandboxed "$update_victim" "$update_dir_victim" "$update_persistent_victim" +[[ ! -e $mise_victim ]] || fail "detached mise code observed a later update authorization" +[[ ! -e $evil_update_marker ]] || fail "update trusted an inherited PATH or OMARCHY_PATH override" +grep -qxF 'restart:--services-only' "$hook_log" || fail "privileged restart phase did not run before user code" +grep -qxF 'restart:--reboot-only' "$hook_log" || fail "reboot-only phase did not run after user code" +pass "update leaves no later sudo authentication for mise or persistent hook children" + +# OM-SEC-14 ends at the final cold hook boundary. Later sections exercise +# separate migration, restart-marker, channel, and installer findings in their +# own PRs. +exit 0 + +# Exercise the real migration dispatcher separately from PATH spoofing. An old +# update inherited the evil root here and ran its migration with the live +# system-package credential; the fixed update exports the authorized root. +evil_migration_victim="$root_dir/90-evil-migration.rules" +reset_case +set +e +run_as_user env OMARCHY_PATH="$evil_update_root" TEST_REAL_MIGRATE=1 \ + TEST_EVIL_UPDATE_MARKER="$evil_update_marker" TEST_EVIL_MIGRATION_VICTIM="$evil_migration_victim" \ + TEST_ROOT_VICTIM="$update_victim" TEST_ROOT_DIR_VICTIM="$update_dir_victim" \ + TEST_PERSISTENT_VICTIM="$update_persistent_victim" TEST_PERSISTENT_PID="$test_home/update.pid" \ + TEST_MISE_VICTIM="$mise_victim" TEST_MISE_PID="$test_home/mise.pid" \ + OMARCHY_MIGRATION_STATE="$test_home/migration-state" OMARCHY_UPDATE_LOGGED=1 \ + "$ROOT/bin/omarchy-update" -y >"$test_tmp/update-root-spoof.out" 2>"$test_tmp/update-root-spoof.err" +status=$? +set -e +(( status == 0 )) || fail "authorized-root update with real migration dispatcher failed" +[[ ! -e $evil_update_marker && ! -e $evil_migration_victim ]] || + fail "update dispatched a migration from inherited OMARCHY_PATH" +pass "update rejects inherited OMARCHY_PATH for real migration dispatch" + +# The login-notification workflow invokes omarchy-migrate directly, outside an +# update that already normalized OMARCHY_PATH. It must independently reject an +# inherited attacker tree rather than running the migration placed there. +reset_case +set +e +run_as_user env OMARCHY_PATH="$evil_update_root" \ + TEST_EVIL_UPDATE_MARKER="$evil_update_marker" TEST_EVIL_MIGRATION_VICTIM="$evil_migration_victim" \ + OMARCHY_MIGRATION_STATE="$test_home/direct-migration-state" \ + "$ROOT/bin/omarchy-migrate" >"$test_tmp/direct-migrate.out" 2>"$test_tmp/direct-migrate.err" +status=$? +set -e +(( status == 0 )) || fail "direct authorized migration dispatch failed" +[[ ! -e $evil_update_marker && ! -e $evil_migration_victim ]] || + fail "direct migration dispatch trusted inherited OMARCHY_PATH" +pass "direct migration dispatch derives its source from root-owned configuration" + +# Reproduce the real historical ordering that exposed the remaining gap: the +# mise-wrapper migration can execute user tooling at 1784909971, while the +# 1784914435 migration invokes sudo later. A following migration also invokes +# the real absolute-path package helper, which cannot be protected by PATH +# alone. Every later authorization must inherit the exported no-update policy. +mkdir -p "$test_tmp/migrations" "$test_home/.local/bin" +chmod 0755 "$test_tmp/migrations" +cp "$ROOT/migrations/1784909971.sh" "$test_tmp/migrations/1784909971.sh" +cp "$ROOT/migrations/1784914435.sh" "$test_tmp/migrations/1784914435.sh" +cat >"$test_tmp/migrations/1784914436.sh" <<'STUB' +#!/bin/bash +/usr/bin/omarchy-pkg-add migration-security-fixture +STUB +chmod 0644 "$test_tmp/migrations/1784909971.sh" "$test_tmp/migrations/1784914435.sh" \ + "$test_tmp/migrations/1784914436.sh" +cat >"$test_home/.local/bin/legacy-mise-wrapper" <<'STUB' +#!/bin/bash +mise use -g "github:attacker/tool" +exec "attacker-tool" "$@" +STUB +cat >"$stub_bin/omarchy-mise-install" <<'STUB' +#!/bin/bash +"$HOME/launch-persistent-attack" "$TEST_MIGRATION_VICTIM" "$TEST_MIGRATION_PID" +STUB +cat >"$stub_bin/nmcli" <<'STUB' +#!/bin/bash +printf '%s\n' "$(id -u)" >"$TEST_PRIV_MIGRATION_MARKER" +STUB +cat >"$stub_bin/omarchy-notification-dismiss" <<'STUB' +#!/bin/bash +exit 0 +STUB +chmod 0755 "$stub_bin/omarchy-mise-install" "$stub_bin/nmcli" \ + "$stub_bin/omarchy-notification-dismiss" "$test_home/.local/bin/legacy-mise-wrapper" +chown -R 1000:1000 "$test_home/.local" +cat >"$stub_bin/omarchy-pkg-missing" <<'STUB' +#!/bin/bash +exit 0 +STUB +chmod 0755 "$stub_bin/omarchy-pkg-missing" +mount --bind "$ROOT/bin/omarchy-pkg-add" /usr/bin/omarchy-pkg-add +mount --bind "$stub_bin/omarchy-pkg-missing" /usr/bin/omarchy-pkg-missing +migration_pkg_paths_bound=1 +migration_victim="$root_dir/95-migration-child.rules" +migration_marker="$root_dir/96-privileged-migration-ran" +reset_case +set +e +run_as_user env OMARCHY_PATH="$evil_update_root" \ + TEST_MIGRATION_VICTIM="$migration_victim" TEST_MIGRATION_PID="$test_home/migration.pid" \ + TEST_PRIV_MIGRATION_MARKER="$migration_marker" TEST_PACMAN_DELAY=0.2 \ + OMARCHY_MIGRATION_STATE="$test_home/mixed-migration-state" \ + "$ROOT/bin/omarchy-migrate" >"$test_tmp/mixed-migrate.out" 2>"$test_tmp/mixed-migrate.err" +status=$? +set -e +(( status == 0 )) || fail "real mixed-trust migration sequence failed" "$(<"$test_tmp/mixed-migrate.err")" +wait_for_persistent_attempts "$test_home/migration.pid" +[[ -f $migration_marker && $(<"$migration_marker") == 0 ]] || fail "later privileged migration did not run as root" +[[ ! -e $migration_victim && ! -e $token ]] || fail "mise migration child reused a later migration authorization" +(( $(grep -c '^grant-no-update$' "$event_log") >= 2 )) || + fail "direct package-helper migration did not inherit the no-update policy" +pass "real mise-before-sudo and absolute package-helper migrations publish no reusable timestamp" +umount /usr/bin/omarchy-pkg-missing +umount /usr/bin/omarchy-pkg-add +migration_pkg_paths_bound=0 + +# Bash can import both BASH_ENV startup code and exported functions before an +# ordinary script body. An exported sudo function used to bypass the PATH +# wrapper in a later helper, publishing a global token to a BASH_ENV child that +# had started before migration invalidation. Exercise both injection channels +# through a normal-shebang child of the privileged migration shell. +cat >"$test_tmp/migrations/9999999998.sh" <<'STUB' +#!/bin/bash +"$HOME/launch-persistent-attack" "$TEST_BASH_STARTUP_VICTIM" "$TEST_BASH_STARTUP_PID" +omarchy-exported-function-auth +STUB +cat >"$stub_bin/omarchy-exported-function-auth" <<'STUB' +#!/bin/bash +sudo --authenticate-for-test +STUB +cat >"$test_home/bash-env-attack" <<'STUB' +#!/bin/bash +if [[ ! -e $TEST_BASH_ENV_MARKER ]]; then + /usr/bin/touch "$TEST_BASH_ENV_MARKER" + "$HOME/launch-persistent-attack" "$TEST_BASH_ENV_VICTIM" "$TEST_BASH_ENV_PID" +fi +STUB +chmod 0755 "$test_tmp/migrations/9999999998.sh" "$stub_bin/omarchy-exported-function-auth" +chown 1000:1000 "$test_home/bash-env-attack" +chmod 0600 "$test_home/bash-env-attack" +bash_startup_victim="$root_dir/99-exported-function-child.rules" +bash_env_victim="$root_dir/100-bash-env-child.rules" +bash_env_marker="$test_home/bash-env-ran" +reset_case +set +e +run_as_user env \ + 'BASH_FUNC_sudo%%=() { /usr/bin/sudo "$@"; }' \ + TEST_MULTILINE_ENV=$'value\nBASH_FUNC_fake%%=not-an-environment-record' \ + BASH_ENV="$test_home/bash-env-attack" \ + TEST_BASH_ENV_MARKER="$bash_env_marker" \ + TEST_BASH_ENV_VICTIM="$bash_env_victim" TEST_BASH_ENV_PID="$test_home/bash-env.pid" \ + TEST_BASH_STARTUP_VICTIM="$bash_startup_victim" TEST_BASH_STARTUP_PID="$test_home/bash-startup.pid" \ + OMARCHY_MIGRATION_STATE="$test_home/bash-startup-migration-state" \ + "$ROOT/bin/omarchy-migrate" >"$test_tmp/bash-startup.out" 2>"$test_tmp/bash-startup.err" +status=$? +set -e +(( status == 0 )) || fail "migration rejected a sanitized Bash startup environment" "$(<"$test_tmp/bash-startup.err")" +wait_for_persistent_attempts "$test_home/bash-startup.pid" +sleep 0.2 +[[ ! -e $bash_env_marker && ! -e $bash_env_victim ]] || + fail "BASH_ENV ran before or beneath the migration security boundary" +[[ ! -e $bash_startup_victim && ! -e $token ]] || + fail "an exported sudo function published a reusable migration credential" +grep -q '^grant-no-update$' "$event_log" || fail "sanitized helper did not use sudo --no-update" +grep -qxF 'exec /usr/bin/sudo -N -- "$@"' "$ROOT/default/omarchy/sudo-no-update/sudo" || + fail "no-update sudo wrapper omitted the option terminator" +pass "Bash startup injection cannot bypass the no-update sudo boundary" + +# Invoking a mixed-trust entrypoint with an ordinary explicit Bash bypasses its +# shebang. A BASH_ENV can erase its own environment record and retain a DEBUG +# trap, so environment-record cleanup alone is not a sufficient startup gate. +# The exact interpreter argv/privileged-mode check must reject this process +# before update authentication, leaving even its already-detached child cold. +cat >"$test_home/self-erasing-bash-env" <<'STUB' +#!/bin/bash +unset BASH_ENV ENV +trap ' + if [[ ! -e $TEST_DEBUG_TRAP_MARKER ]]; then + /usr/bin/touch "$TEST_DEBUG_TRAP_MARKER" + "$HOME/launch-persistent-attack" "$TEST_DEBUG_TRAP_VICTIM" "$TEST_DEBUG_TRAP_PID" + fi +' DEBUG +STUB +chown 1000:1000 "$test_home/self-erasing-bash-env" +chmod 0600 "$test_home/self-erasing-bash-env" +debug_trap_marker="$test_home/debug-trap-ran" +debug_trap_victim="$root_dir/101-debug-trap-child.rules" +reset_case +set +e +run_as_user env BASH_ENV="$test_home/self-erasing-bash-env" \ + TEST_DEBUG_TRAP_MARKER="$debug_trap_marker" TEST_DEBUG_TRAP_VICTIM="$debug_trap_victim" \ + TEST_DEBUG_TRAP_PID="$test_home/debug-trap.pid" OMARCHY_UPDATE_LOGGED=1 \ + /usr/bin/bash "$ROOT/bin/omarchy-update" -y \ + >"$test_tmp/unsafe-bash.out" 2>"$test_tmp/unsafe-bash.err" +status=$? +set -e +(( status == 126 )) || fail "update did not reject an unsafe explicit Bash interpreter" +[[ -e $debug_trap_marker ]] || fail "self-erasing BASH_ENV regression did not install its DEBUG trap" +wait_for_persistent_attempts "$test_home/debug-trap.pid" +[[ ! -e $debug_trap_victim && ! -e $token ]] || + fail "unsafe Bash startup reached update authentication" +! grep -qE '^(authenticate|authenticate-command|grant|grant-no-update)$' "$event_log" || + fail "unsafe Bash startup reached privileged update work" +grep -q 'unsafe Bash startup' "$test_tmp/unsafe-bash.err" || + fail "unsafe Bash startup rejection lacked a diagnostic" +pass "self-erasing BASH_ENV and DEBUG traps cannot cross the interpreter gate" + +# Model a hostile yay configuration that selects absolute /usr/bin/sudo and a +# refresh loop. The real AUR helper must override both on its command line, so +# even a migration child already polling the global token sees no credential. +cat >"$stub_bin/omarchy-pkg-aur-accessible" <<'STUB' +#!/bin/bash +exit 0 +STUB +cat >"$stub_bin/yay" <<'STUB' +#!/bin/bash +sudo_command=/usr/bin/sudo +sudoflags="" +sudoloop=true +while (($#)); do + case "$1" in + --sudo) + sudo_command="$2" + shift 2 + ;; + --sudoloop=false) + sudoloop=false + shift + ;; + --sudoflags=-N) + sudoflags=-N + shift + ;; + *) + shift + ;; + esac +done +printf 'sudo=%s sudoflags=%s sudoloop=%s\n' "$sudo_command" "$sudoflags" "$sudoloop" >"$TEST_YAY_LOG" +"$sudo_command" $sudoflags --authenticate-for-test +STUB +chmod 0755 "$stub_bin/omarchy-pkg-aur-accessible" "$stub_bin/yay" +mount --bind "$stub_bin/omarchy-pkg-aur-accessible" /usr/bin/omarchy-pkg-aur-accessible +mount --bind "$stub_bin/yay" /usr/bin/yay +aur_paths_bound=1 +yay_victim="$root_dir/97-yay-override-child.rules" +reset_case +run_as_user env TEST_YAY_LOG="$test_home/yay.log" \ + "$test_home/launch-persistent-attack" "$yay_victim" "$test_home/yay-child.pid" +wait_for_persistent_attempts "$test_home/yay-child.pid" +run_as_user env OMARCHY_PATH="$test_tmp" OMARCHY_SUDO_NO_UPDATE=1 TEST_YAY_LOG="$test_home/yay.log" \ + "$ROOT/bin/omarchy-update-aur-pkgs" >"$test_tmp/yay.out" 2>"$test_tmp/yay.err" +sleep 0.2 +grep -qxF "sudo=/usr/bin/sudo sudoflags=-N sudoloop=false" "$test_home/yay.log" || + fail "AUR update did not override hostile yay sudo settings" +[[ ! -e $yay_victim && ! -e $token ]] || fail "hostile yay sudo configuration published a reusable timestamp" +pass "AUR updates force no-update sudo and disable yay's credential loop" + +# A pre-existing credential and skipped package paths exercise the interactive +# branch independently of authority acquired by update helpers. +reset_case +authenticate_for_test +set +e +run_as_user env TEST_SKIP_UPDATE_AUTH=1 TEST_SKIP_LATE_AUTH=1 \ + TEST_ROOT_VICTIM="$update_victim" TEST_ROOT_DIR_VICTIM="$update_dir_victim" \ + TEST_PERSISTENT_VICTIM="$update_persistent_victim" TEST_PERSISTENT_PID="$test_home/update.pid" \ + TEST_MISE_VICTIM="$mise_victim" TEST_MISE_PID="$test_home/mise.pid" \ + OMARCHY_UPDATE_LOGGED=1 "$ROOT/bin/omarchy-update" \ + >"$test_tmp/update-interactive.out" 2>"$test_tmp/update-interactive.err" +status=$? +set -e +(( status == 0 )) || fail "isolated interactive update failed" +wait_for_persistent_attempts "$test_home/update.pid" +assert_hook_sandboxed "$update_victim" "$update_dir_victim" "$update_persistent_victim" +pass "interactive update invalidates a pre-existing credential before user code" + +for failing_stage in migration signal; do + reset_case + set +e + run_as_user env TEST_FAILING_STAGE="$failing_stage" TEST_SKIP_LATE_AUTH=1 \ + TEST_ROOT_VICTIM="$update_victim" TEST_ROOT_DIR_VICTIM="$update_dir_victim" \ + TEST_PERSISTENT_VICTIM="$update_persistent_victim" TEST_PERSISTENT_PID="$test_home/update.pid" \ + TEST_MISE_VICTIM="$mise_victim" TEST_MISE_PID="$test_home/mise.pid" \ + OMARCHY_UPDATE_LOGGED=1 "$ROOT/bin/omarchy-update" -y \ + >"$test_tmp/update-$failing_stage.out" 2>"$test_tmp/update-$failing_stage.err" + status=$? + set -e + (( status != 0 )) || fail "update $failing_stage case unexpectedly succeeded" + [[ ! -e $token ]] || fail "update $failing_stage exit left its credential live" + [[ ! -s $hook_log ]] || fail "update $failing_stage case reached user-controlled stages" +done +pass "failed and signaled updates invalidate credentials before user code" + +reset_case +set +e +run_as_user env TEST_SUDO_NO_N=1 OMARCHY_UPDATE_LOGGED=1 \ + "$ROOT/bin/omarchy-update" -y >"$test_tmp/no-update-unsupported.out" 2>"$test_tmp/no-update-unsupported.err" +status=$? +set -e +(( status != 0 )) || fail "update accepted sudo without --no-update support" +! grep -qE '^(authenticate|grant)' "$event_log" || fail "unsupported sudo reached privileged update work" +grep -q 'does not support --no-update' "$test_tmp/no-update-unsupported.err" || + fail "unsupported sudo failure did not explain the missing security primitive" +pass "update fails closed before privileged work when sudo lacks --no-update" + +# The config parser is the authority for all three scoped commands. Exercise a +# different unsafe shape through each copy before restoring the valid config. +chmod 0666 /etc/omarchy.conf +if run_as_user env OMARCHY_UPDATE_LOGGED=1 "$ROOT/bin/omarchy-update" -y \ + >"$test_tmp/untrusted-update.out" 2>"$test_tmp/untrusted-update.err"; then + fail "update accepted a writable source-root authorization" +fi + +/usr/bin/mv /etc/omarchy.conf /etc/omarchy.real +/usr/bin/ln -s /etc/omarchy.real /etc/omarchy.conf +if run_as_user "$ROOT/bin/omarchy-refresh-pacman" stable \ + >"$test_tmp/untrusted-refresh.out" 2>"$test_tmp/untrusted-refresh.err"; then + fail "pacman refresh accepted a symlinked source-root authorization" +fi +/usr/bin/rm /etc/omarchy.conf +/usr/bin/mv /etc/omarchy.real /etc/omarchy.conf + +chown 1000:1000 /etc/omarchy.conf +if run_as_user "$ROOT/bin/omarchy-update-restart" --services-only \ + >"$test_tmp/untrusted-restart.out" 2>"$test_tmp/untrusted-restart.err"; then + fail "update restart accepted a non-root source-root authorization" +fi +write_authorized_source_root "$test_tmp" +pass "update commands reject writable, symlinked, and non-root source-root authorization" + +# A root-owned config may authorize a development checkout, but not a tree +# another local account (or every account) can rewrite. Exercise both unsafe +# directory-chain shapes before restoring the valid authorized fixture. +writable_source_root="$test_tmp/writable-source-root" +foreign_source_root="$test_tmp/foreign-source-root" +mkdir -p "$writable_source_root" "$foreign_source_root" +chown 1000:1000 "$writable_source_root" +chmod 0777 "$writable_source_root" +chown 1001:1001 "$foreign_source_root" +chmod 0755 "$foreign_source_root" + +write_authorized_source_root "$writable_source_root" +if run_as_user env OMARCHY_UPDATE_LOGGED=1 "$ROOT/bin/omarchy-update" -y \ + >"$test_tmp/writable-source.out" 2>"$test_tmp/writable-source.err"; then + fail "update accepted a group/world-writable authorized source tree" +fi +grep -q 'untrusted Omarchy source root' "$test_tmp/writable-source.err" || + fail "writable source-root rejection happened after the trust parser" + +write_authorized_source_root "$foreign_source_root" +if run_as_user "$ROOT/bin/omarchy-migrate" --pending \ + >"$test_tmp/foreign-source.out" 2>"$test_tmp/foreign-source.err"; then + fail "migration runner accepted a foreign-owned authorized source tree" +fi +grep -q 'untrusted Omarchy source root' "$test_tmp/foreign-source.err" || + fail "foreign source-root rejection happened after the trust parser" +write_authorized_source_root "$test_tmp" +pass "authorized source roots reject foreign-owned and group/world-writable path components" + +# The restart marker is attacker-writable, but its value is now an allowlisted +# selector into the configured Omarchy tree rather than a command resolved by +# PATH. A dev-linked tree is honored only through root-owned /etc/omarchy.conf. +reset_case +restart_home="$test_tmp/restart-home" +restart_log="$test_tmp/restart.log" +mkdir -p "$restart_home/.local/state/omarchy" +touch "$restart_log" +chown -R 1000:1000 "$restart_home" +chown 1000:1000 "$restart_log" +touch "$restart_home/.local/state/omarchy/restart-btop-required" \ + "$restart_home/.local/state/omarchy/restart-evil-required" +chown 1000:1000 "$restart_home/.local/state/omarchy"/* +cat >"$stub_bin/omarchy-restart-btop" <<'STUB' +#!/bin/bash +echo trusted-btop >>"$TEST_RESTART_LOG" +STUB +cat >"$stub_bin/omarchy-restart-shell" <<'STUB' +#!/bin/bash +echo trusted-shell >>"$TEST_RESTART_LOG" +STUB +evil_bin="$test_home/evil-bin" +mkdir -p "$evil_bin" +cat >"$evil_bin/omarchy-restart-btop" <<'STUB' +#!/bin/bash +echo path-btop >>"$TEST_RESTART_LOG" +STUB +cat >"$evil_bin/omarchy-restart-evil" <<'STUB' +#!/bin/bash +echo path-evil >>"$TEST_RESTART_LOG" +sudo /usr/bin/true +STUB +chown -R 1000:1000 "$evil_bin" +chmod 0755 "$stub_bin/omarchy-restart-btop" "$stub_bin/omarchy-restart-shell" "$evil_bin"/* +run_as_user env HOME="$restart_home" PATH="$evil_bin:$stub_bin:/usr/bin:/bin" \ + OMARCHY_PATH="$test_home/evil-root" TEST_RESTART_LOG="$restart_log" \ + "$ROOT/bin/omarchy-update-restart" --services-only >"$test_tmp/restart.out" 2>"$test_tmp/restart.err" +grep -qxF trusted-btop "$restart_log" || fail "allowed marker did not use the configured Omarchy command" +grep -qxF trusted-shell "$restart_log" || fail "shell restart did not use the configured Omarchy command" +! grep -q '^path-' "$restart_log" || fail "restart marker resolved an attacker PATH command" +[[ ! -e $restart_home/.local/state/omarchy/restart-evil-required ]] || fail "unsupported restart marker was retained" +pass "restart markers use an allowlist and fixed configured command paths" + +special_root="$test_tmp/dev root\\checkout\$cash" +special_home="$test_tmp/special-home" +special_log="$test_tmp/special.log" +mkdir -p "$special_root/bin" "$special_home/.local/state/omarchy" +touch "$special_home/.local/state/omarchy/restart-btop-required" "$special_log" +chown -R 1000:1000 "$special_home" "$special_log" +cat >"$special_root/bin/omarchy-restart-btop" <<'STUB' +#!/bin/bash +echo special-btop >>"$TEST_RESTART_LOG" +STUB +cat >"$special_root/bin/omarchy-restart-shell" <<'STUB' +#!/bin/bash +exit 0 +STUB +chmod 0755 "$special_root/bin"/* +chown -R 1000:1000 "$special_root" +write_authorized_source_root "$special_root" +run_as_user env HOME="$special_home" TEST_RESTART_LOG="$special_log" \ + "$ROOT/bin/omarchy-update-restart" --services-only \ + >"$test_tmp/special-root.out" 2>"$test_tmp/special-root.err" +grep -qxF special-btop "$special_log" || fail "authorized quoted dev root did not dispatch its restart helper" +write_authorized_source_root "$test_tmp" +pass "source-root authorization decodes spaces, backslashes, and dollar signs" + +# The legacy pre-refresh hook now runs only after pacman; a detached child can +# no longer wait for a later authentication in either tty or global mode. +write_attack_hook pre-refresh-pacman +refresh_victim="$root_dir/84-refresh-hook.rules" +refresh_dir_victim="$root_dir/85-refresh-hook-dir.rules" +refresh_persistent_victim="$root_dir/86-refresh-hook-child.rules" +reset_case +authenticate_for_test +cat >"$evil_bin/cp" <<'STUB' +#!/bin/bash +touch "$TEST_EVIL_REFRESH_MARKER" +exit 97 +STUB +chmod 0755 "$evil_bin/cp" +evil_refresh_marker="$test_home/evil-refresh-ran" +set +e +run_as_user env PATH="$evil_bin:$stub_bin:/usr/bin:/bin" OMARCHY_PATH="$evil_update_root" \ + TEST_EVIL_REFRESH_MARKER="$evil_refresh_marker" \ + TEST_ROOT_VICTIM="$refresh_victim" TEST_ROOT_DIR_VICTIM="$refresh_dir_victim" \ + TEST_PERSISTENT_VICTIM="$refresh_persistent_victim" TEST_PERSISTENT_PID="$test_home/refresh.pid" \ + "$ROOT/bin/omarchy-refresh-pacman" stable >"$test_tmp/refresh.out" 2>"$test_tmp/refresh.err" +status=$? +set -e +(( status == 0 )) || fail "isolated pacman refresh failed" "$(<"$test_tmp/refresh.err")" +wait_for_persistent_attempts "$test_home/refresh.pid" +assert_hook_sandboxed "$refresh_victim" "$refresh_dir_victim" "$refresh_persistent_victim" +[[ ! -e $evil_refresh_marker ]] || fail "pacman refresh resolved cp through caller PATH" +/usr/bin/cmp -s "$test_tmp/default/pacman/pacman-stable.conf" /etc/pacman.conf || + fail "pacman refresh did not copy config from the authorized source root" +[[ ! -e $evil_refresh_marker ]] || fail "pacman refresh copied from inherited OMARCHY_PATH or PATH" +pass "pacman refresh runs its legacy hook only after all privileged work" + +reset_case +authenticate_for_test +set +e +run_as_user env TEST_PACMAN_STATUS=1 TEST_ROOT_VICTIM="$refresh_victim" \ + TEST_ROOT_DIR_VICTIM="$refresh_dir_victim" TEST_PERSISTENT_VICTIM="$refresh_persistent_victim" \ + TEST_PERSISTENT_PID="$test_home/refresh.pid" "$ROOT/bin/omarchy-refresh-pacman" stable \ + >"$test_tmp/refresh-fail.out" 2>"$test_tmp/refresh-fail.err" +status=$? +set -e +(( status != 0 )) || fail "failing pacman refresh unexpectedly succeeded" +[[ ! -e $token ]] || fail "failed pacman refresh left its credential live" +[[ ! -s $hook_log ]] || fail "failed pacman transaction reached the refresh hook" +pass "failed pacman refresh invalidates and does not run its hook" + +# Channel switching is a composite refresh caller: after refreshing it +# authenticates for the package swap and runs the full update. Exercise the +# real channel, refresh, update, and hook commands against the global-token +# model. A detached legacy refresh-hook child must not start until that entire +# chain has finished. +cat >"$test_home/.config/omarchy/hooks/post-update" <<'HOOK' +#!/bin/bash +printf 'post-update:%s\n' "$(id -u)" >>"$TEST_HOOK_LOG" +HOOK +chown 1000:1000 "$test_home/.config/omarchy/hooks/post-update" +chmod 0700 "$test_home/.config/omarchy/hooks/post-update" +channel_victim="$root_dir/91-channel-refresh-hook.rules" +channel_dir_victim="$root_dir/92-channel-refresh-dir.rules" +channel_persistent_victim="$root_dir/93-channel-refresh-child.rules" +channel_mise_victim="$root_dir/94-channel-mise-child.rules" +reset_case +set +e +evil_channel_helper_marker="$test_home/evil-channel-helper-ran" +evil_channel_helper_victim="$root_dir/98-channel-path-helper.rules" +run_as_user env PATH="$evil_update_bin:$stub_bin:/usr/bin:/bin" \ + TEST_EVIL_CHANNEL_HELPER_MARKER="$evil_channel_helper_marker" \ + TEST_EVIL_CHANNEL_VICTIM="$evil_channel_helper_victim" \ + TEST_ROOT_VICTIM="$channel_victim" TEST_ROOT_DIR_VICTIM="$channel_dir_victim" \ + TEST_PERSISTENT_VICTIM="$channel_persistent_victim" TEST_PERSISTENT_PID="$test_home/channel.pid" \ + TEST_MISE_VICTIM="$channel_mise_victim" TEST_MISE_PID="$test_home/channel-mise.pid" \ + OMARCHY_UPDATE_LOGGED=1 "$ROOT/bin/omarchy-channel-set" stable \ + >"$test_tmp/channel.out" 2>"$test_tmp/channel.err" +status=$? +set -e +(( status == 0 )) || fail "isolated channel switch failed" "$(<"$test_tmp/channel.err")" +wait_for_persistent_attempts "$test_home/channel.pid" +wait_for_persistent_attempts "$test_home/channel-mise.pid" +assert_hook_sandboxed "$channel_victim" "$channel_dir_victim" "$channel_persistent_victim" +[[ ! -e $channel_mise_victim ]] || fail "channel mise child reused a later refresh-hook credential" +[[ ! -e $evil_channel_helper_marker && ! -e $evil_channel_helper_victim ]] || + fail "channel switch resolved a post-pacman helper through caller PATH" +[[ $(grep -c '^file:1000$' "$hook_log") == 1 ]] || fail "channel switch did not run the deferred refresh hook exactly once" +pass "channel switching defers its refresh hook past every later authentication" + +cat >"$stub_bin/omarchy-launch-floating-terminal-with-presentation" <<'STUB' +#!/bin/bash +exec bash -c "$1" +STUB +cat >"$stub_bin/omarchy-pkg-add" <<'STUB' +#!/bin/bash +[[ ${OMARCHY_SUDO_NO_UPDATE:-0} == 1 ]] || exit 98 +/usr/bin/sudo -N -- /usr/bin/true +exit "${TEST_PKG_STATUS:-0}" +STUB +cat >"$stub_bin/omarchy-font-set" <<'STUB' +#!/bin/bash +exec bash "$TEST_ROOT/bin/omarchy-font-set" "$@" +STUB +cat >"$stub_bin/fc-list" <<'STUB' +#!/bin/bash +echo 'Example Family' +STUB +cat >"$stub_bin/omarchy-restart-shell" <<'STUB' +#!/bin/bash +exit 0 +STUB +cat >"$stub_bin/pgrep" <<'STUB' +#!/bin/bash +exit 1 +STUB +cat >"$stub_bin/sleep" <<'STUB' +#!/bin/bash +exit 0 +STUB +chmod 0755 "$stub_bin"/* +chmod 4755 "$stub_bin/sudo" +mount --bind "$stub_bin/omarchy-launch-floating-terminal-with-presentation" \ + /usr/bin/omarchy-launch-floating-terminal-with-presentation +mount --bind "$stub_bin/omarchy-pkg-add" /usr/bin/omarchy-pkg-add +mount --bind "$stub_bin/omarchy-font-set" /usr/bin/omarchy-font-set +font_paths_bound=1 + +write_attack_hook font-set +font_victim="$root_dir/87-font-hook.rules" +font_dir_victim="$root_dir/88-font-hook-dir.rules" +font_persistent_victim="$root_dir/89-font-hook-child.rules" +reset_case +set +e +run_as_user env TEST_ROOT_VICTIM="$font_victim" TEST_ROOT_DIR_VICTIM="$font_dir_victim" \ + TEST_PERSISTENT_VICTIM="$font_persistent_victim" TEST_PERSISTENT_PID="$test_home/font.pid" \ + "$ROOT/bin/omarchy-install-font" 'Example Font' example-font 'Example Family' \ + >"$test_tmp/font.out" 2>"$test_tmp/font.err" +status=$? +set -e +(( status == 0 )) || fail "isolated font install failed" "$(<"$test_tmp/font.err")" +wait_for_persistent_attempts "$test_home/font.pid" +assert_hook_sandboxed "$font_victim" "$font_dir_victim" "$font_persistent_victim" +pass "font installation invalidates before file, directory, and persistent hooks" + +reset_case +set +e +run_as_user env TEST_PKG_STATUS=1 TEST_ROOT_VICTIM="$font_victim" \ + TEST_ROOT_DIR_VICTIM="$font_dir_victim" TEST_PERSISTENT_VICTIM="$font_persistent_victim" \ + TEST_PERSISTENT_PID="$test_home/font.pid" \ + "$ROOT/bin/omarchy-install-font" 'Example Font' example-font 'Example Family' \ + >"$test_tmp/font-fail.out" 2>"$test_tmp/font-fail.err" +status=$? +set -e +(( status != 0 )) || fail "failing font package installation unexpectedly succeeded" +[[ ! -e $token ]] || fail "failed font package installation left its credential live" +[[ ! -s $hook_log ]] || fail "failed font package installation reached the hook" +pass "failed font installation invalidates without running its hook" diff --git a/test/shell.d/update-sequence-test.sh b/test/shell.d/update-sequence-test.sh index 2dd62b6e43fb..edac120937bc 100755 --- a/test/shell.d/update-sequence-test.sh +++ b/test/shell.d/update-sequence-test.sh @@ -4,8 +4,55 @@ set -euo pipefail source "$(dirname "$0")/base-test.sh" -test_tmp=$(mktemp -d) -trap 'rm -rf "$test_tmp"' EXIT +if [[ -z ${OMARCHY_UPDATE_SEQUENCE_NS:-} ]]; then + outer_uid=$(id -u) + outer_gid=$(id -g) + subuid=$(awk -F: -v user="$(id -un)" '$1 == user { print $2; exit }' /etc/subuid) + subgid=$(awk -F: -v group="$(id -gn)" '$1 == group { print $2; exit }' /etc/subgid) + if [[ -z $subuid || -z $subgid ]]; then + pass "no subordinate uid/gid range; skipping authorized update-sequence test" + exit 0 + fi + exec unshare --user --mount \ + --map-users "0:$outer_uid:1" --map-users "1:$subuid:65536" \ + --map-groups "0:$outer_gid:1" --map-groups "1:$subgid:65536" \ + env OMARCHY_UPDATE_SEQUENCE_NS=setup bash "$0" +elif [[ $OMARCHY_UPDATE_SEQUENCE_NS == setup ]]; then + mount -t tmpfs -o mode=0755 tmpfs /run + namespace_tmp=$(mktemp -d -p /run omarchy-update-sequence.XXXXXXXX) + chmod 0755 "$namespace_tmp" + mkdir -p "$namespace_tmp/default/omarchy/sudo-no-update" + cp "$ROOT/default/omarchy/sudo-no-update/sudo" "$namespace_tmp/default/omarchy/sudo-no-update/sudo" + chmod 0755 "$namespace_tmp/default/omarchy/sudo-no-update/sudo" + cat >"$namespace_tmp/fixed-sudo" <<'STUB' +#!/bin/bash +if [[ ${1:-} == "-h" ]]; then + echo 'usage: sudo [-ABbEHkNnPS] command' +fi +exit 0 +STUB + chmod 0755 "$namespace_tmp/fixed-sudo" + mount --bind "$namespace_tmp/fixed-sudo" /usr/bin/sudo + mount -t tmpfs -o mode=0755 tmpfs /etc + printf 'export OMARCHY_PATH="%s"\n' "$namespace_tmp" >/etc/omarchy.conf + chmod 0644 /etc/omarchy.conf + chown -R 1000:1000 "$namespace_tmp" + + set +e + setpriv --reuid 1000 --regid 1000 --clear-groups \ + env OMARCHY_UPDATE_SEQUENCE_NS=run OMARCHY_AUTHORIZED_TEST_ROOT="$namespace_tmp" bash "$0" + status=$? + set -e + + umount /usr/bin/sudo + umount /etc + rm -rf "$namespace_tmp" + umount /run + exit "$status" +fi + +test_tmp="$OMARCHY_AUTHORIZED_TEST_ROOT" +trap 'rm -rf "$test_tmp"/*' EXIT stub_bin="$test_tmp/bin" mkdir -p "$stub_bin" @@ -49,7 +96,7 @@ run_update() { FAILING_STEP="${FAILING_STEP:-}" \ OMARCHY_UPDATE_LOGGED=1 \ PATH="$stub_bin:$PATH" \ - bash "$ROOT/bin/omarchy-update" "$@" >"$test_tmp/out" 2>"$test_tmp/err" + "$ROOT/bin/omarchy-update" "$@" >"$test_tmp/out" 2>"$test_tmp/err" } steps_run() { @@ -70,13 +117,14 @@ expected_steps() { omarchy-update-keyring \ omarchy-update-system-pkgs \ omarchy-migrate \ - omarchy-hook \ - omarchy-update-aur-pkgs \ - omarchy-update-mise \ omarchy-update-orphan-pkgs \ omarchy-update-analyze-logs \ omarchy-update-status \ + omarchy-update-restart \ omarchy-update-stay-awake \ + omarchy-update-aur-pkgs \ + omarchy-hook \ + omarchy-update-mise \ omarchy-update-restart } From 87625c2ad8cf0e0bc08676127548a532d318036e Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Mon, 31 Aug 2026 21:27:48 +0100 Subject: [PATCH 007/194] OM-SEC-01: Make passwordless sudo expiry fail closed --- bin/omarchy-security-functions | 87 ++++ bin/omarchy-sudo-passwordless | 483 +++++++++++++++++++-- etc/tmpfiles.d/omarchy-nopasswd-sudo.conf | 8 +- manual/48-security.md | 2 +- migrations/1788163635.sh | 6 + test/shell.d/nopasswd-sudo-expiry-test.sh | 497 +++++++++++++++++----- 6 files changed, 945 insertions(+), 138 deletions(-) create mode 100755 bin/omarchy-security-functions create mode 100644 migrations/1788163635.sh mode change 100644 => 100755 test/shell.d/nopasswd-sudo-expiry-test.sh diff --git a/bin/omarchy-security-functions b/bin/omarchy-security-functions new file mode 100755 index 000000000000..2f3d2242ec57 --- /dev/null +++ b/bin/omarchy-security-functions @@ -0,0 +1,87 @@ +#!/bin/bash + +# omarchy:hidden=true +# omarchy:summary=Provide internal fail-closed helpers for security-sensitive commands + +# Shared fail-closed primitives for security-sensitive Omarchy commands. This +# file is sourced from the same package-owned bin directory as its consumers. + +if [[ ${BASH_SOURCE[0]} == "$0" ]]; then + echo "omarchy-security-functions is an internal function library." >&2 + exit 64 +fi + +omarchy_security_require_privileged_bash_startup() { + local pid=${1:-$$} + + [[ $- == *p* && $pid =~ ^[1-9][0-9]*$ ]] || return 1 + /usr/bin/env -i /usr/bin/bash -p -c ' + mapfile -d "" -t argv <"/proc/$1/cmdline" || exit 1 + executable=$(/usr/bin/readlink -e -- "/proc/$1/exe") || exit 1 + [[ $executable == /usr/bin/bash ]] + [[ ${argv[0]:-} == /bin/bash || ${argv[0]:-} == /usr/bin/bash ]] + [[ ${argv[1]:-} == -p ]] + ' omarchy-bash-startup "$pid" +} + +omarchy_security_sudo_supports_no_update() { + LC_ALL=C /usr/bin/sudo -h 2>&1 | + /usr/bin/grep -Eq '^usage: sudo .*\[[^]]*N[^]]*\]' +} + +omarchy_security_revoke_sudo_timestamp() { + /usr/bin/sudo -k >/dev/null 2>&1 +} + +omarchy_security_exit_with_revoked_sudo() { + local status=$1 + local message=${2:-Could not invalidate cached sudo authorization.} + + trap - EXIT HUP INT TERM + if ! omarchy_security_revoke_sudo_timestamp; then + echo "$message" >&2 + (( status != 0 )) || status=1 + fi + exit "$status" +} + +omarchy_security_install_signal_exit_traps() { + trap 'exit 129' HUP + trap 'exit 130' INT + trap 'exit 143' TERM +} + +omarchy_security_run_sudo_cleanup_trap() { + local status=$? + + omarchy_security_exit_with_revoked_sudo "$status" \ + "${OMARCHY_SECURITY_SUDO_CLEANUP_MESSAGE:-Could not invalidate cached sudo authorization.}" +} + +omarchy_security_install_sudo_cleanup_traps() { + OMARCHY_SECURITY_SUDO_CLEANUP_MESSAGE=${1:-Could not invalidate cached sudo authorization.} + trap omarchy_security_run_sudo_cleanup_trap EXIT + omarchy_security_install_signal_exit_traps +} + +omarchy_security_assert_root_directory() { + local path=$1 expected_mode=$2 canonical owner actual_mode + + [[ $path == /* && -d $path && ! -L $path ]] || return 1 + canonical=$(/usr/bin/realpath -e -- "$path") || return 1 + [[ $canonical == "$path" ]] || return 1 + read -r owner actual_mode < <(/usr/bin/stat -Lc '%u %a' -- "$path") || return 1 + [[ $owner == "0" && $actual_mode == "$expected_mode" ]] +} + +omarchy_security_prepare_private_root_directory() { + local path=$1 parent=$2 + + omarchy_security_assert_root_directory "$parent" 755 || return 1 + if [[ -e $path || -L $path ]]; then + omarchy_security_assert_root_directory "$path" 700 + else + /usr/bin/install -d -o root -g root -m 0700 -- "$path" || return 1 + omarchy_security_assert_root_directory "$path" 700 + fi +} diff --git a/bin/omarchy-sudo-passwordless b/bin/omarchy-sudo-passwordless index 719d881bfe71..717e8aaf243b 100755 --- a/bin/omarchy-sudo-passwordless +++ b/bin/omarchy-sudo-passwordless @@ -1,70 +1,481 @@ -#!/bin/bash +#!/bin/bash -p # omarchy:summary=Toggle passwordless sudo for the current user. # omarchy:args=[MINUTES] # omarchy:requires-sudo=true -NOPASSWD_FILE="/etc/sudoers.d/99-omarchy-nopasswd-${USER}" -TIMER_NAME="omarchy-nopasswd-expire-${USER}" +source "${BASH_SOURCE[0]%/*}/omarchy-security-functions" || exit 126 -MINUTES=${1:-15} -if [[ $1 && ! $1 =~ ^[0-9]+$ ]]; then +if [[ ${BASH_SOURCE[0]} == "$0" ]]; then + omarchy_security_require_privileged_bash_startup || { + echo "Refusing an unsafe Bash startup for passwordless sudo." >&2 + exit 126 + } + unset BASH_ENV ENV +fi + +set -euo pipefail + +readonly DEFAULT_MINUTES=15 +readonly MAX_MINUTES=1440 +readonly STATE_DIR=/var/lib/omarchy/sudo-passwordless +readonly RUNTIME_DIR=/run/omarchy/sudo-passwordless +readonly LOCK_FILE=/run/lock/omarchy-sudo-passwordless.lock +readonly BOOT_CLEANUP_FILE=/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf +readonly INSTALLED_SELF=/usr/bin/omarchy-sudo-passwordless + +usage() { echo "Usage: omarchy-sudo-passwordless [MINUTES]" >&2 + echo "MINUTES must be between 1 and $MAX_MINUTES." >&2 exit 1 -fi +} -arm_expiry() { - if sudo systemd-run --on-active=${MINUTES}m --timer-property=AccuracySec=1s --unit="$TIMER_NAME" \ - rm -f -- "$NOPASSWD_FILE"; then - return 0 +valid_minutes() { + [[ $1 =~ ^[0-9]+$ ]] && ((10#$1 >= 1 && 10#$1 <= MAX_MINUTES)) +} + +valid_uid() { + [[ $1 =~ ^[0-9]+$ ]] && ((10#$1 >= 1 && 10#$1 <= 4294967294)) +} + +valid_account_name() { + [[ $1 =~ ^[a-z_][a-z0-9_-]{0,31}$ ]] +} + +resolve_account() { + local uid="$1" entry + valid_uid "$uid" || return 1 + entry=$(/usr/bin/getent passwd "$((10#$uid))") || return 1 + IFS=: read -r ACCOUNT_NAME _ ACCOUNT_UID _ _ _ _ <<<"$entry" + [[ $ACCOUNT_UID == "$((10#$uid))" ]] || return 1 + # Sudoers names and the legacy filename both have metacharacters. Omarchy + # accounts use this portable subset; refusing anything else is safer than + # attempting to quote privileged policy syntax. + valid_account_name "$ACCOUNT_NAME" || return 1 + ACCOUNT_UID=$((10#$uid)) +} + +verify_sudo_caller() { + local requested_uid="$1" + ((EUID == 0)) || return 1 + valid_uid "$requested_uid" || return 1 + [[ ${SUDO_UID:-} =~ ^[0-9]+$ ]] || return 1 + ((10#$SUDO_UID == 10#$requested_uid)) || return 1 + resolve_account "$requested_uid" +} + +prepare_root_state() { + omarchy_security_assert_root_directory /var 755 || return 1 + [[ -d /var/lib && ! -L /var/lib ]] || return 1 + [[ $(/usr/bin/stat -Lc '%u' /var/lib) == 0 ]] || return 1 + ! ((8#$(/usr/bin/stat -Lc '%a' /var/lib) & 022)) || return 1 + + if [[ ! -e /var/lib/omarchy && ! -L /var/lib/omarchy ]]; then + /usr/bin/install -d -o root -g root -m 0755 /var/lib/omarchy || return 1 fi + omarchy_security_assert_root_directory /var/lib/omarchy 755 || return 1 + omarchy_security_prepare_private_root_directory "$STATE_DIR" /var/lib/omarchy || return 1 - echo "Failed to schedule passwordless sudo expiry. Revoking access now." >&2 - if ! sudo rm -f -- "$NOPASSWD_FILE"; then - echo "CRITICAL: Could not remove $NOPASSWD_FILE. Remove it as root immediately." >&2 + omarchy_security_assert_root_directory /run 755 || return 1 + if [[ ! -e /run/omarchy && ! -L /run/omarchy ]]; then + /usr/bin/install -d -o root -g root -m 0755 /run/omarchy || return 1 fi - return 1 + omarchy_security_assert_root_directory /run/omarchy 755 || return 1 + omarchy_security_prepare_private_root_directory "$RUNTIME_DIR" /run/omarchy } -echo "Toggle passwordless sudo..." +with_root_lock() { + local fd rc=0 + # The boot cleanup cannot depend on STATE_DIR or RUNTIME_DIR being healthy: + # those are exactly the kinds of partial-install state it must fail closed + # through. /run/lock is established by the OS before sysinit services run. + omarchy_security_assert_root_directory /run 755 || return 1 + [[ -d /run/lock && ! -L /run/lock ]] || return 1 + [[ $(/usr/bin/stat -Lc '%u' /run/lock) == 0 ]] || return 1 + ! ((8#$(/usr/bin/stat -Lc '%a' /run/lock) & 022)) || return 1 + exec {fd}>"$LOCK_FILE" || return 1 + /usr/bin/chown root:root "$LOCK_FILE" || return 1 + /usr/bin/chmod 0600 "$LOCK_FILE" || return 1 + /usr/bin/flock -x "$fd" || return 1 + "$@" || rc=$? + /usr/bin/flock -u "$fd" || rc=1 + exec {fd}>&- + return "$rc" +} -# Safety: if the file exists but the timer doesn't (e.g. after reboot), clean up -if sudo test -f "$NOPASSWD_FILE" && ! systemctl is-active "${TIMER_NAME}.timer" &>/dev/null; then - sudo rm "$NOPASSWD_FILE" -fi +rule_file() { + printf '/etc/sudoers.d/99-omarchy-nopasswd-%s' "$1" +} -# Check for the file directly — sudo -n can stay cached or be granted by other rules -if sudo test -f "$NOPASSWD_FILE"; then - if [[ $1 ]]; then - sudo systemctl stop "${TIMER_NAME}.timer" 2>/dev/null - arm_expiry || exit 1 - echo "Passwordless sudo timer updated. It will now automatically disable in ${MINUTES} minutes." +state_file() { + printf '%s/%s.state' "$STATE_DIR" "$1" +} + +read_state_record() { + local uid="$1" file state_uid name expires timer canonical_uid + local -a lines=() + valid_uid "$uid" || return 1 + canonical_uid=$((10#$uid)) + file=$(state_file "$uid") + [[ -f $file && ! -L $file ]] || return 1 + mapfile -t lines <"$file" || return 1 + (( ${#lines[@]} == 4 )) || return 1 + [[ ${lines[0]} == UID=* && ${lines[1]} == USER=* && + ${lines[2]} == EXPIRES=* && ${lines[3]} == TIMER=* ]] || return 1 + state_uid=${lines[0]#UID=} + name=${lines[1]#USER=} + expires=${lines[2]#EXPIRES=} + timer=${lines[3]#TIMER=} + [[ $state_uid == "$canonical_uid" ]] || return 1 + valid_account_name "$name" || return 1 + [[ $expires =~ ^[1-9][0-9]{0,10}$ ]] || return 1 + [[ $timer =~ ^omarchy-nopasswd-expire-${canonical_uid}-[0-9a-f]{32}$ ]] || return 1 + printf '%s\t%s\t%s' "$name" "$expires" "$timer" +} + +read_state_timer() { + local record + record=$(read_state_record "$1") || return 1 + printf '%s' "${record##*$'\t'}" +} + +current_epoch() { + local now + now=$(/usr/bin/date +%s) || return 1 + [[ $now =~ ^[1-9][0-9]{0,10}$ ]] || return 1 + printf '%s' "$now" +} + +valid_expiry() { + [[ $1 =~ ^[1-9][0-9]{0,10}$ ]] +} + +valid_timer_for_uid() { + local uid="$1" timer="$2" + valid_uid "$uid" || return 1 + uid=$((10#$uid)) + [[ $timer =~ ^omarchy-nopasswd-expire-${uid}-[0-9a-f]{32}$ ]] +} + +stop_timer() { + local timer="$1" + [[ $timer =~ ^omarchy-nopasswd-expire-[0-9]+-[0-9a-f]{32}$ ]] || return 0 + /usr/bin/systemctl stop "${timer}.timer" "${timer}.service" >/dev/null 2>&1 || true + /usr/bin/systemctl reset-failed "${timer}.timer" "${timer}.service" >/dev/null 2>&1 || true +} + +classify_generated_rule() { + local file=$1 suffix contents name + + GENERATED_RULE_LEGACY_TIMER="" + [[ -f $file && ! -L $file ]] || return 1 + contents=$(/usr/bin/cat -- "$file") || return 2 + suffix=${file##*/99-omarchy-nopasswd-} + + if [[ $suffix =~ ^[0-9]+$ ]]; then + name=${contents%' ALL=(ALL) NOPASSWD: ALL'} + valid_account_name "$name" && [[ $contents == "$name ALL=(ALL) NOPASSWD: ALL" ]] + elif valid_account_name "$suffix" && [[ $contents == "$suffix ALL=(ALL) NOPASSWD: ALL" ]]; then + GENERATED_RULE_LEGACY_TIMER="omarchy-nopasswd-expire-${suffix}" else - sudo rm "$NOPASSWD_FILE" - sudo systemctl stop "${TIMER_NAME}.timer" 2>/dev/null + return 1 + fi +} + +remove_known_legacy_rules() { + local file classification failed=0 + shopt -s nullglob + for file in /etc/sudoers.d/99-omarchy-nopasswd-*; do + if classify_generated_rule "$file"; then + # A crash after publishing the numeric rule but before its state rename + # must not survive the next boot. Do not require the account to still + # exist: a deleted account could otherwise make the rule immortal and a + # later username reuse could activate it again. + /usr/bin/rm -f -- "$file" || failed=1 + [[ -z $GENERATED_RULE_LEGACY_TIMER ]] || + /usr/bin/systemctl stop "${GENERATED_RULE_LEGACY_TIMER}.timer" \ + "${GENERATED_RULE_LEGACY_TIMER}.service" >/dev/null 2>&1 || true + else + classification=$? + # An unreadable candidate cannot be proven inert. A symlink, non-file, + # or administrator-authored body is unrelated and remains untouched. + (( classification == 1 )) || failed=1 + fi + done + shopt -u nullglob + return "$failed" +} + +cleanup_uid_locked() { + local uid="$1" timer="" + valid_uid "$uid" || return 1 + timer=$(read_state_timer "$uid" 2>/dev/null || true) + # Remove policy first. A failed timer stop can only leave an inert cleanup + # job behind, never extend passwordless access. + /usr/bin/rm -f -- "$(rule_file "$uid")" || return 1 + /usr/bin/rm -f -- "$(state_file "$uid")" || return 1 + [[ -z $timer ]] || stop_timer "$timer" +} + +cleanup_all_locked() { + local state uid failed=0 file classification + shopt -s nullglob + for state in "$STATE_DIR"/*.state; do + uid=${state##*/} + uid=${uid%.state} + if valid_uid "$uid" && ! cleanup_uid_locked "$uid"; then failed=1; fi + done + shopt -u nullglob + remove_known_legacy_rules || failed=1 + + # Never report a successful boot cleanup while an exact rule emitted by any + # Omarchy implementation is still active. Administrator-extended files do + # not match these complete bodies and remain untouched. + shopt -s nullglob + for file in /etc/sudoers.d/99-omarchy-nopasswd-*; do + if classify_generated_rule "$file"; then + failed=1 + else + classification=$? + (( classification == 1 )) || failed=1 + fi + done + shopt -u nullglob + return "$failed" +} + +verify_boot_cleanup() { + local owner mode canonical current active_rules + [[ -f $BOOT_CLEANUP_FILE && ! -L $BOOT_CLEANUP_FILE ]] || return 1 + canonical=$(/usr/bin/realpath -e -- "$BOOT_CLEANUP_FILE") || return 1 + [[ $canonical == "$BOOT_CLEANUP_FILE" ]] || return 1 + owner=$(/usr/bin/stat -Lc '%u' -- "$BOOT_CLEANUP_FILE") || return 1 + mode=$(/usr/bin/stat -Lc '%a' -- "$BOOT_CLEANUP_FILE") || return 1 + [[ $owner == 0 && $mode =~ ^[0-7]+$ ]] && ! ((8#$mode & 022)) || return 1 + + current=${BOOT_CLEANUP_FILE%/*} + while :; do + [[ -d $current && ! -L $current ]] || return 1 + canonical=$(/usr/bin/realpath -e -- "$current") || return 1 + [[ $canonical == "$current" ]] || return 1 + read -r owner mode < <(/usr/bin/stat -Lc '%u %a' -- "$current") || return 1 + [[ $owner == 0 && $mode =~ ^[0-7]+$ ]] && ! ((8#$mode & 022)) || return 1 + [[ $current == / ]] && break + current=${current%/*} + [[ -n $current ]] || current=/ + done + + active_rules=$(/usr/bin/awk '!/^[[:space:]]*(#|$)/ { print }' "$BOOT_CLEANUP_FILE") || return 1 + [[ $active_rules == 'r! /etc/sudoers.d/99-omarchy-nopasswd-*' ]] +} + +prepare_state_file() { + local uid="$1" name="$2" expires="$3" timer="$4" tmp + tmp=$(/usr/bin/mktemp "$STATE_DIR/.state.XXXXXX") || return 1 + if ! /usr/bin/printf 'UID=%s\nUSER=%s\nEXPIRES=%s\nTIMER=%s\n' \ + "$uid" "$name" "$expires" "$timer" >"$tmp" || + ! /usr/bin/chown root:root "$tmp" || ! /usr/bin/chmod 0600 "$tmp"; then + /usr/bin/rm -f -- "$tmp" + return 1 + fi + printf '%s' "$tmp" +} + +start_expiry_timer() { + local uid="$1" expires="$2" timer="$3" + valid_uid "$uid" && valid_expiry "$expires" && valid_timer_for_uid "$uid" "$timer" || return 1 + # Calendar timers use CLOCK_REALTIME and catch up immediately after resume; + # a monotonic OnActiveSec timer pauses while the machine is suspended. + /usr/bin/systemd-run --quiet --collect --on-calendar="@${expires}" \ + --timer-property=AccuracySec=1s --unit="$timer" \ + -- "$INSTALLED_SELF" __expire "$uid" || return 1 + /usr/bin/systemctl is-active --quiet "${timer}.timer" +} + +publish_rule() { + local uid="$1" name="$2" destination tmp + destination=$(rule_file "$uid") + tmp=$(/usr/bin/mktemp "$STATE_DIR/.sudoers.XXXXXX") || return 1 + if ! /usr/bin/printf '%s ALL=(ALL) NOPASSWD: ALL\n' "$name" >"$tmp" || + ! /usr/bin/chown root:root "$tmp" || ! /usr/bin/chmod 0440 "$tmp" || + ! /usr/sbin/visudo -cf "$tmp" >/dev/null || + ! /usr/bin/install -o root -g root -m 0440 -- "$tmp" "$destination"; then + /usr/bin/rm -f -- "$tmp" + return 1 + fi + /usr/bin/rm -f -- "$tmp" +} + +enable_locked() { + local uid="$1" minutes="$2" old_timer="" timer token expires pending_state now + resolve_account "$uid" || return 1 + valid_minutes "$minutes" || return 1 + prepare_root_state || return 1 + verify_boot_cleanup || { + echo "omarchy-sudo-passwordless: package-owned boot cleanup rule is missing or unsafe" >&2 + return 1 + } + + old_timer=$(read_state_timer "$uid" 2>/dev/null || true) + token=$(/usr/bin/tr -d '-' = 10#$expires)) || ! /usr/bin/systemctl is-active --quiet "${timer}.timer"; then + # The timer may have expired or failed between its initial verification and + # rule publication. Revoke synchronously so a suspended or heavily loaded + # machine cannot turn a short grant into a reboot-long one. + cleanup_uid_locked "$uid" || true + return 1 + fi + [[ -z $old_timer || $old_timer == "$timer" ]] || stop_timer "$old_timer" +} + +status_locked() { + local uid="$1" record state_name expires timer now remainder + resolve_account "$uid" || return 1 + [[ -f $(rule_file "$uid") && ! -L $(rule_file "$uid") ]] || return 1 + record=$(read_state_record "$uid") || { + cleanup_uid_locked "$uid" + return 1 + } + state_name=${record%%$'\t'*} + remainder=${record#*$'\t'} + expires=${remainder%%$'\t'*} + timer=${record##*$'\t'} + [[ $state_name == "$ACCOUNT_NAME" ]] || { + cleanup_uid_locked "$uid" + return 1 + } + now=$(current_epoch) || { + cleanup_uid_locked "$uid" + return 1 + } + ((10#$now < 10#$expires)) || { + cleanup_uid_locked "$uid" + return 1 + } + /usr/bin/systemctl is-active --quiet "${timer}.timer" || { + cleanup_uid_locked "$uid" + return 1 + } +} + +root_dispatch() { + local action="$1" + shift + case "$action" in + __status) + (($# == 1)) && verify_sudo_caller "$1" || return 1 + with_root_lock status_locked "$1" + ;; + __enable) + (($# == 2)) && verify_sudo_caller "$1" && valid_minutes "$2" || return 1 + with_root_lock enable_locked "$1" "$2" + ;; + __disable) + (($# == 1)) && verify_sudo_caller "$1" || return 1 + with_root_lock cleanup_uid_locked "$1" + ;; + __expire) + (($# == 1)) && ((EUID == 0)) && valid_uid "$1" || return 1 + with_root_lock cleanup_uid_locked "$1" + ;; + __cleanup-all) + (($# == 0)) && ((EUID == 0)) || return 1 + with_root_lock cleanup_all_locked + ;; + *) return 1 ;; + esac +} + +case "${1:-}" in + __status|__enable|__disable|__expire|__cleanup-all) + action=$1 + shift + root_dispatch "$action" "$@" + exit + ;; +esac + +(($# <= 1)) || usage +minutes=${1:-$DEFAULT_MINUTES} +valid_minutes "$minutes" || usage +uid=$(/usr/bin/id -u) +valid_uid "$uid" || { + echo "omarchy-sudo-passwordless: cannot grant passwordless sudo to this account" >&2 + exit 1 +} + +omarchy_security_sudo_supports_no_update || { + echo "This sudo does not support --no-update; refusing the passwordless-sudo workflow." >&2 + exit 1 +} + +omarchy_security_install_sudo_cleanup_traps +/usr/bin/sudo -k >/dev/null 2>&1 || { + echo "Could not start from a cold sudo credential state." >&2 + exit 1 +} + +echo "Toggle passwordless sudo..." +if /usr/bin/sudo -N -- "$INSTALLED_SELF" __status "$uid"; then + if (($# == 0)); then + /usr/bin/sudo -N -- "$INSTALLED_SELF" __disable "$uid" echo "Passwordless sudo has been DISABLED. Sudo will require a password again." + else + /usr/bin/sudo -N -- "$INSTALLED_SELF" __enable "$uid" "$minutes" + echo "Passwordless sudo timer updated. It will automatically disable in ${minutes} minutes." fi else echo "" echo "⚠️ WARNING: This will allow ANY process running as your user to" - echo "execute ANY command as root WITHOUT a password for ${MINUTES} minutes." + echo "execute ANY command as root WITHOUT a password for ${minutes} minutes." echo "" echo "This is useful for AI agents that need to run sudo commands," echo "but it significantly weakens the security of your system." echo "Anyone or anything with access to your user account gets full root." echo "" - echo "Passwordless sudo will automatically disable after ${MINUTES} minutes." + echo "Passwordless sudo will automatically disable after ${minutes} minutes," + echo "including if the machine reboots before the timer fires." echo "Run this command again to disable it early." echo "" - if gum confirm "Enable passwordless sudo for ${MINUTES} minutes? This is a significant security risk!"; then - echo "${USER} ALL=(ALL) NOPASSWD: ALL" | sudo tee "$NOPASSWD_FILE" > /dev/null - sudo chmod 440 "$NOPASSWD_FILE" - arm_expiry || exit 1 - + if /usr/bin/gum confirm "Enable passwordless sudo for ${minutes} minutes? This is a significant security risk!"; then + /usr/bin/sudo -N -- "$INSTALLED_SELF" __enable "$uid" "$minutes" echo "" - echo "Passwordless sudo has been ENABLED. It will automatically disable in ${MINUTES} minutes." - echo "A restart removes the passwordless sudo rule as well." + echo "Passwordless sudo has been ENABLED. It will automatically disable in ${minutes} minutes." else echo "Aborted. No changes made." fi diff --git a/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf b/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf index 2c644ff1fc9c..be81137ad053 100644 --- a/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf +++ b/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf @@ -1,5 +1,5 @@ -# omarchy-sudo-passwordless writes /etc/sudoers.d/99-omarchy-nopasswd- and -# arms a transient systemd-run timer to remove it again. Transient units do not -# survive a reboot, so remove any remaining grant during early boot. Boot-only -# (r!) ensures a later systemd-tmpfiles --remove cannot cut a live grant short. +# omarchy-sudo-passwordless creates grants in this owned filename namespace. +# Transient expiry timers do not survive reboot, so early boot removes every +# remaining grant. The boot-only modifier prevents later tmpfiles runs from +# shortening a live, explicitly requested window. r! /etc/sudoers.d/99-omarchy-nopasswd-* diff --git a/manual/48-security.md b/manual/48-security.md index 45750398e309..86028a230f6c 100644 --- a/manual/48-security.md +++ b/manual/48-security.md @@ -20,7 +20,7 @@ It works by restoring the baseline snapshot the installer takes, so it's only av ## Passwordless sudo -Sometimes you want `sudo` to stop asking, most often when an AI agent is doing a long stretch of system work for you. _Setup > Security > Passwordless Sudo_ turns that off for 15 minutes and then puts it back automatically. Run it again before the timer runs out to end it early, and pass your own number of minutes with `omarchy-sudo-passwordless 30` if 15 isn't enough. A restart removes the passwordless sudo rule as well. +Sometimes you want `sudo` to stop asking, most often when an AI agent is doing a long stretch of system work for you. _Setup > Security > Passwordless Sudo_ turns that off for 15 wall-clock minutes and then puts it back automatically, including immediately after resuming from a suspend that crossed the deadline. A package-owned boot-time cleanup rule removes the grant before logins if the computer restarts first. Run the command again before the timer runs out to end it early, and pass your own number of minutes (from 1 to 1440) with `omarchy-sudo-passwordless 30` if 15 isn't enough. Be clear-eyed about this one: while it's on, anything running as your user can do anything as root without being asked. That's the whole point, and it's also the whole risk. diff --git a/migrations/1788163635.sh b/migrations/1788163635.sh new file mode 100644 index 000000000000..e2fe22725d21 --- /dev/null +++ b/migrations/1788163635.sh @@ -0,0 +1,6 @@ +echo "Remove legacy temporary passwordless sudo grants" + +# This removes current numeric grants, exact legacy username grants, corrupt or +# orphaned state, and their known timers. Administrator-authored sudoers files +# whose contents do not exactly match Omarchy's generated grammar are preserved. +sudo /usr/bin/omarchy-sudo-passwordless __cleanup-all diff --git a/test/shell.d/nopasswd-sudo-expiry-test.sh b/test/shell.d/nopasswd-sudo-expiry-test.sh old mode 100644 new mode 100755 index f332f80e414f..6d54633ca133 --- a/test/shell.d/nopasswd-sudo-expiry-test.sh +++ b/test/shell.d/nopasswd-sudo-expiry-test.sh @@ -2,122 +2,425 @@ set -euo pipefail -source "$(dirname "$0")/base-test.sh" +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" -script="$ROOT/bin/omarchy-sudo-passwordless" -tmpfiles_file="$ROOT/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf" +command_path="$ROOT/bin/omarchy-sudo-passwordless" +security_library_path="$ROOT/bin/omarchy-security-functions" +tmpfiles_path="$ROOT/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf" +migration_path="$ROOT/migrations/1788163635.sh" test_tmp=$(mktemp -d) trap 'rm -rf "$test_tmp"' EXIT -mock_bin="$test_tmp/bin" -grant="$test_tmp/grant" -calls="$test_tmp/calls" -mkdir -p "$mock_bin" +function_prefix() { + printf 'source %q\n' "$security_library_path" + awk '/^source .*omarchy-security-functions/ { next } /^case "\$\{1:-\}" in$/ { exit } { print }' "$command_path" +} -cat >"$mock_bin/gum" <<'SH' -#!/bin/bash -exit 0 -SH +# Exercise the validation code itself. Leading zeroes remain numeric, but zero, +# negatives, oversized grants, and shell syntax are rejected. +( + source <(function_prefix) + for minutes in 1 15 1440 00015; do + valid_minutes "$minutes" || fail "passwordless sudo accepts bounded duration $minutes" + done + for minutes in 0 1441 -1 1m '1;id' ''; do + ! valid_minutes "$minutes" || fail "passwordless sudo rejects invalid duration '$minutes'" + done +) +pass "passwordless sudo validates a bounded positive duration" -cat >"$mock_bin/systemctl" <<'SH' -#!/bin/bash +# The public entry point uses the kernel-backed numeric identity; $USER is +# never interpolated into a privileged filename or sudoers rule. +grep -F 'uid=$(/usr/bin/id -u)' "$command_path" >/dev/null || + fail "passwordless sudo derives the caller from id -u" +! grep -Eq '\$\{?USER\}?' "$command_path" || + fail "passwordless sudo does not trust USER for privileged policy" +grep -F '[[ ${SUDO_UID:-} =~ ^[0-9]+$ ]]' "$command_path" >/dev/null || + fail "passwordless sudo validates sudo provenance" +pass "passwordless sudo derives and validates trusted account identity" -printf 'systemctl %s\n' "$*" >>"$TEST_CALLS" -[[ ${1:-} == "is-active" && ${TEST_TIMER_ACTIVE:-false} == "true" ]] -SH +# Status inspection and the confirmation UI are mixed-trust: a normal sudo +# status call would publish a timestamp that a hostile prompt helper could use +# even when the user declines the grant. Exercise the public flow with a sudo +# model that publishes a token only when -N is missing. +grep -Fxq '#!/bin/bash -p' "$command_path" || + fail "passwordless sudo no longer suppresses Bash startup injection" +grep -F '[[ ${argv[1]:-} == -p ]]' "$security_library_path" >/dev/null || + fail "passwordless sudo accepts a decoy post-script -p" -cat >"$mock_bin/sudo" <<'SH' +public_sudo_stub="$test_tmp/public-sudo" +public_gum_stub="$test_tmp/public-gum" +public_token="$test_tmp/public-token" +public_exploit="$test_tmp/public-exploit" +cat >"$public_sudo_stub" <<'STUB' #!/bin/bash - -printf 'sudo %s\n' "$*" >>"$TEST_CALLS" - -case ${1:-} in -test) - [[ ${2:-} == "-f" && -f $TEST_GRANT ]] - ;; -tee) - /usr/bin/tee "$TEST_GRANT" - ;; -chmod) - /usr/bin/chmod "$2" "$TEST_GRANT" - ;; -systemd-run) - [[ ${TEST_FAIL_SYSTEMD_RUN:-false} != "true" ]] - ;; -rm) - /usr/bin/rm -f -- "$TEST_GRANT" - ;; -systemctl) +if [[ ${1:-} == -h ]]; then + echo 'usage: sudo [-ABbEHkNnPS] command' + exit 0 +fi +if [[ ${1:-} == -k ]]; then + rm -f -- "$TEST_PUBLIC_TOKEN" exit 0 - ;; -*) - echo "unexpected sudo command: $*" >&2 - exit 90 - ;; +fi +no_update=0 +if [[ ${1:-} == -N ]]; then no_update=1; shift; fi +[[ ${1:-} != -- ]] || shift +((no_update)) || : >"$TEST_PUBLIC_TOKEN" +case "${2:-}" in + __status) exit 1 ;; + __enable|__disable) exit 0 ;; + *) exit 2 ;; esac -SH +STUB +cat >"$public_gum_stub" <<'STUB' +#!/bin/bash +[[ ! -e $TEST_PUBLIC_TOKEN ]] || : >"$TEST_PUBLIC_EXPLOIT" +exit 1 +STUB +chmod 0755 "$public_sudo_stub" "$public_gum_stub" +public_flow="$test_tmp/passwordless-public-flow" +/usr/bin/cp "$security_library_path" "$test_tmp/omarchy-security-functions" +/usr/bin/sed \ + -e "s#/usr/bin/sudo#$public_sudo_stub#g" \ + -e "s#/usr/bin/gum#$public_gum_stub#g" \ + "$command_path" >"$public_flow" +chmod 0755 "$public_flow" +TEST_PUBLIC_TOKEN="$public_token" TEST_PUBLIC_EXPLOIT="$public_exploit" \ + /usr/bin/bash -p "$public_flow" 15 >/dev/null +[[ ! -e $public_token && ! -e $public_exploit ]] || + fail "passwordless confirmation inherited a reusable status credential" -chmod +x "$mock_bin/gum" "$mock_bin/sudo" "$mock_bin/systemctl" +startup_env="$test_tmp/passwordless-bash-env" +startup_marker="$test_tmp/passwordless-bash-env-ran" +cat >"$startup_env" <<'STUB' +: >"$TEST_STARTUP_MARKER" +set -o privileged +unset BASH_ENV +STUB +if BASH_ENV="$startup_env" TEST_STARTUP_MARKER="$startup_marker" \ + /usr/bin/bash "$public_flow" -p >/dev/null 2>&1; then + fail "passwordless sudo accepted an unsafe interpreter with a decoy -p" +fi +[[ -e $startup_marker && ! -e $public_token && ! -e $public_exploit ]] || + fail "unsafe passwordless startup reached its sudo workflow" +pass "passwordless confirmation uses a cold command-scoped credential boundary" -run_command() { - TEST_CALLS="$calls" TEST_GRANT="$grant" PATH="$mock_bin:$PATH" USER=alice \ - "$script" "$@" -} +# Source a path-rewritten copy so the real cleanup implementation can be +# exercised without touching /etc. Exact generated numeric rules are removed +# even after account deletion or a crash before state publication. Anything an +# administrator changed, and every symlink, is preserved. +fake_sudoers="$test_tmp/sudoers.d" +mkdir "$fake_sudoers" +rewritten="$test_tmp/passwordless-lib.sh" +function_prefix | sed "s#/etc/sudoers.d#$fake_sudoers#g" >"$rewritten" +( + source "$rewritten" + printf 'deleteduser ALL=(ALL) NOPASSWD: ALL\n' >"$fake_sudoers/99-omarchy-nopasswd-424242" + printf 'admin ALL=(ALL) NOPASSWD: /usr/bin/pacman\n' >"$fake_sudoers/99-omarchy-nopasswd-424243" + ln -s "$fake_sudoers/99-omarchy-nopasswd-424243" "$fake_sudoers/99-omarchy-nopasswd-424244" + remove_known_legacy_rules +) +[[ ! -e $fake_sudoers/99-omarchy-nopasswd-424242 ]] || + fail "boot cleanup removes a state-less numeric orphan" +[[ -f $fake_sudoers/99-omarchy-nopasswd-424243 ]] || + fail "boot cleanup preserves administrator-authored policy" +[[ -L $fake_sudoers/99-omarchy-nopasswd-424244 ]] || + fail "boot cleanup refuses sudoers symlinks" +pass "boot cleanup removes crash/deleted-account orphans conservatively" -: >"$calls" -enable_output=$(run_command 15) -[[ -f $grant ]] || fail "successful timer setup leaves the passwordless sudo grant enabled" -[[ $(cat "$grant") == "alice ALL=(ALL) NOPASSWD: ALL" ]] || - fail "the enabled grant belongs to the current user" "$(cat "$grant")" -grep -q '^sudo systemd-run --on-active=15m .* rm -f -- /etc/sudoers.d/99-omarchy-nopasswd-alice$' "$calls" || - fail "enabling arms the expiry timer" "$(cat "$calls")" -[[ $enable_output == *"automatically disable in 15 minutes"* ]] || - fail "success is reported after the timer is armed" "$enable_output" -pass "enabling arms expiry before reporting success" - -: >"$calls" -rm -f "$grant" -if failure_output=$(TEST_FAIL_SYSTEMD_RUN=true run_command 15 2>&1); then - fail "enabling fails when the expiry timer cannot be armed" -fi -[[ ! -e $grant ]] || fail "timer setup failure revokes the new passwordless sudo grant" -[[ $failure_output == *"Revoking access now"* ]] || - fail "timer setup failure explains the fail-closed revocation" "$failure_output" -[[ $failure_output != *"Passwordless sudo has been ENABLED"* ]] || - fail "timer setup failure does not report that passwordless sudo was enabled" "$failure_output" -pass "timer setup failure revokes a new grant" - -: >"$calls" -printf 'alice ALL=(ALL) NOPASSWD: ALL\n' >"$grant" -if update_output=$(TEST_TIMER_ACTIVE=true TEST_FAIL_SYSTEMD_RUN=true run_command 30 2>&1); then - fail "updating fails when the replacement expiry timer cannot be armed" -fi -[[ ! -e $grant ]] || fail "timer update failure revokes the existing passwordless sudo grant" -[[ $update_output != *"timer updated"* ]] || - fail "timer update failure does not report success" "$update_output" -pass "timer update failure revokes the existing grant" +# A boot gate must not report success when deletion itself fails. Exercise the +# real cleanup and post-cleanup verification with a deterministic failing rm. +rm_failure_dir="$test_tmp/rm-failure-sudoers" +mkdir "$rm_failure_dir" +printf 'deleteduser ALL=(ALL) NOPASSWD: ALL\n' >"$rm_failure_dir/99-omarchy-nopasswd-424245" +failing_rm="$test_tmp/failing-rm" +cat >"$failing_rm" <<'FAILING_RM' +#!/bin/bash +exit 1 +FAILING_RM +chmod +x "$failing_rm" +rm_failure_lib="$test_tmp/rm-failure-lib.sh" +function_prefix | + sed -e "s#/etc/sudoers.d#$rm_failure_dir#g" \ + -e "s#/var/lib/omarchy/sudo-passwordless#$test_tmp/empty-state#g" \ + -e "s#/usr/bin/rm#$failing_rm#g" >"$rm_failure_lib" +mkdir "$test_tmp/empty-state" +( + source "$rm_failure_lib" + ! cleanup_all_locked +) || fail "boot cleanup fails when an Omarchy rule cannot be removed" +[[ -f $rm_failure_dir/99-omarchy-nopasswd-424245 ]] || + fail "rm-failure fixture remains available for verification" +pass "boot cleanup fails closed when policy deletion fails" + +# Reproduce the migration's real sudo provenance: sudo sets SUDO_UID. Rewrite +# only the read-only EUID probe so this unprivileged test can exercise the root +# dispatcher, then assert that cleanup (which can only revoke privilege) runs. +dispatch_lib="$test_tmp/dispatch-lib.sh" +function_prefix | sed 's/((EUID == 0))/((TEST_EUID == 0))/g' >"$dispatch_lib" +( + source "$dispatch_lib" + called="" + cleanup_all_locked() { called=cleanup; } + with_root_lock() { "$@"; } + TEST_EUID=0 SUDO_UID=1000 root_dispatch __cleanup-all + [[ $called == cleanup ]] +) || fail "migration cleanup dispatch accepts authenticated sudo provenance" +pass "migration can invoke fail-closed cleanup through sudo" + +# A grant cannot be published until the static unit is verified/enabled, and a +# timer setup failure removes its pending state without calling publish_rule. +transaction_dir="$test_tmp/transaction" +mkdir "$transaction_dir" +transaction_lib="$test_tmp/transaction-lib.sh" +function_prefix | sed "s#/var/lib/omarchy/sudo-passwordless#$transaction_dir#g" >"$transaction_lib" +( + source "$transaction_lib" + ACCOUNT_NAME=audituser + resolve_account() { ACCOUNT_NAME=audituser; ACCOUNT_UID=1000; } + prepare_root_state() { :; } + verify_boot_cleanup() { return 1; } + publish_rule() { return 99; } + ! enable_locked 1000 15 +) +( + source "$transaction_lib" + ACCOUNT_NAME=audituser + resolve_account() { ACCOUNT_NAME=audituser; ACCOUNT_UID=1000; } + prepare_root_state() { :; } + verify_boot_cleanup() { return 0; } + read_state_timer() { return 1; } + prepare_state_file() { local pending="$transaction_dir/pending"; : >"$pending"; printf %s "$pending"; } + start_expiry_timer() { return 1; } + publish_rule() { printf published >"$transaction_dir/published"; } + cleanup_uid_locked() { : >"$transaction_dir/failed-timer-cleanup"; } + ! enable_locked 1000 15 + [[ ! -e $transaction_dir/pending && ! -e $transaction_dir/published && + -e $transaction_dir/failed-timer-cleanup ]] +) || fail "passwordless sudo fails closed on prerequisite/timer failure" +pass "passwordless sudo publishes no rule after partial setup failure" -mapfile -t tmpfiles_rules < <(grep -vE '^[[:space:]]*(#|$)' "$tmpfiles_file") -(( ${#tmpfiles_rules[@]} == 1 )) || - fail "passwordless sudo ships one tmpfiles rule" "${tmpfiles_rules[*]}" +# Erik's predecessor fix revoked an already-active grant when an extension +# could not arm its replacement timer. Keep that fail-closed property while +# the new transaction deliberately leaves the old timer armed until the new +# one is verified. +replacement_state="$transaction_dir/1000.state" +replacement_rule="$transaction_dir/1000.rule" +replacement_stopped="$transaction_dir/old-timer-stopped" +old_timer=omarchy-nopasswd-expire-1000-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +printf 'UID=1000\nUSER=audituser\nEXPIRES=2000000000\nTIMER=%s\n' "$old_timer" >"$replacement_state" +printf 'audituser ALL=(ALL) NOPASSWD: ALL\n' >"$replacement_rule" +( + source "$transaction_lib" + resolve_account() { ACCOUNT_NAME=audituser; ACCOUNT_UID=1000; } + prepare_root_state() { :; } + verify_boot_cleanup() { return 0; } + state_file() { printf '%s' "$replacement_state"; } + rule_file() { printf '%s' "$replacement_rule"; } + prepare_state_file() { local pending="$transaction_dir/replacement-pending"; : >"$pending"; printf %s "$pending"; } + start_expiry_timer() { return 1; } + stop_timer() { [[ $1 == "$old_timer" ]] && : >"$replacement_stopped"; } + ! enable_locked 1000 30 + [[ ! -e $replacement_state && ! -e $replacement_rule && -e $replacement_stopped ]] +) || fail "passwordless sudo leaves an existing grant live after replacement timer failure" +pass "replacement timer failure revokes the existing grant" -fake_root="$test_tmp/root" +# Expiry is a wall-clock promise, so the transient timer must carry the exact +# absolute epoch recorded in root state. A monotonic-only --on-active timer +# pauses during suspend and can otherwise extend a short grant by hours. +timer_args="$test_tmp/timer-args" +calendar_systemd_run="$test_tmp/calendar-systemd-run" +calendar_systemctl="$test_tmp/calendar-systemctl" +cat >"$calendar_systemd_run" <<'STUB' +#!/bin/bash +printf '%s\n' "$@" >"$TEST_TIMER_ARGS" +STUB +cat >"$calendar_systemctl" <<'STUB' +#!/bin/bash +exit 0 +STUB +chmod 0755 "$calendar_systemd_run" "$calendar_systemctl" +calendar_lib="$test_tmp/calendar-lib.sh" +function_prefix | + sed -e "s#/usr/bin/systemd-run#$calendar_systemd_run#g" \ + -e "s#/usr/bin/systemctl#$calendar_systemctl#g" >"$calendar_lib" +( + source "$calendar_lib" + TEST_TIMER_ARGS="$timer_args" start_expiry_timer 1000 2000000000 \ + omarchy-nopasswd-expire-1000-0123456789abcdef0123456789abcdef +) || fail "passwordless sudo cannot arm its absolute expiry timer" +grep -Fx -- '--on-calendar=@2000000000' "$timer_args" >/dev/null || + fail "passwordless sudo timer does not advance across suspend" +pass "passwordless sudo arms the recorded absolute wall-clock expiry" + +# A resumed machine can briefly observe the timer as active before systemd +# dispatches its overdue service. Status must independently enforce EXPIRES and +# synchronously remove policy instead of trusting timer activity alone. +expired_state="$test_tmp/expired-state" +expired_sudoers="$test_tmp/expired-sudoers" +mkdir "$expired_state" "$expired_sudoers" +expired_timer=omarchy-nopasswd-expire-1000-0123456789abcdef0123456789abcdef +printf 'UID=1000\nUSER=audituser\nEXPIRES=1\nTIMER=%s\n' "$expired_timer" >"$expired_state/1000.state" +printf 'audituser ALL=(ALL) NOPASSWD: ALL\n' >"$expired_sudoers/99-omarchy-nopasswd-1000" +expired_lib="$test_tmp/expired-lib.sh" +function_prefix | + sed -e "s#/var/lib/omarchy/sudo-passwordless#$expired_state#g" \ + -e "s#/etc/sudoers.d#$expired_sudoers#g" \ + -e "s#/usr/bin/systemctl#$calendar_systemctl#g" >"$expired_lib" +( + source "$expired_lib" + resolve_account() { ACCOUNT_NAME=audituser; ACCOUNT_UID=1000; } + ! status_locked 1000 +) || fail "passwordless sudo accepts expired root state while its timer is active" +[[ ! -e $expired_state/1000.state && ! -e $expired_sudoers/99-omarchy-nopasswd-1000 ]] || + fail "passwordless sudo does not synchronously revoke expired state" +pass "passwordless sudo enforces wall-clock expiry independently of timer dispatch" + +# If the transient timer fires between its first active check and publication, +# the just-created rule must be synchronously revoked instead of surviving to +# reboot. Model that narrow transition with the real enable transaction. +inactive_systemctl="$test_tmp/inactive-systemctl" +cat >"$inactive_systemctl" <<'STUB' +#!/bin/bash +exit 1 +STUB +chmod 0755 "$inactive_systemctl" +post_publish_lib="$test_tmp/post-publish-lib.sh" +sed "s#/usr/bin/systemctl#$inactive_systemctl#g" "$transaction_lib" >"$post_publish_lib" +( + source "$post_publish_lib" + resolve_account() { ACCOUNT_NAME=audituser; ACCOUNT_UID=1000; } + prepare_root_state() { :; } + verify_boot_cleanup() { return 0; } + read_state_timer() { return 1; } + prepare_state_file() { local pending="$transaction_dir/pending-after-arm"; : >"$pending"; printf %s "$pending"; } + start_expiry_timer() { return 0; } + publish_rule() { : >"$transaction_dir/published-after-arm"; } + cleanup_uid_locked() { rm -f "$transaction_dir/published-after-arm"; : >"$transaction_dir/revoked-after-arm"; } + ! enable_locked 1000 15 + [[ ! -e $transaction_dir/published-after-arm && -e $transaction_dir/revoked-after-arm ]] +) || fail "passwordless sudo leaves a grant when its armed timer expires before publication completes" +pass "timer expiry during publication revokes the grant synchronously" + +# Follow the maintainer's package-owned tmpfiles design: one boot-only rule +# owns this filename namespace. A routine --remove leaves live grants alone; +# early boot removes them before a user can log in. The migration only revokes +# legacy runtime state and never writes static policy into /usr. +mapfile -t tmpfiles_rules < <(/usr/bin/grep -vE '^[[:space:]]*(#|$)' "$tmpfiles_path") +(( ${#tmpfiles_rules[@]} == 1 )) || fail "passwordless sudo ships one boot cleanup rule" +[[ ${tmpfiles_rules[0]} == 'r! /etc/sudoers.d/99-omarchy-nopasswd-*' ]] || + fail "passwordless sudo boot cleanup does not own the exact generated namespace" +fake_root="$test_tmp/tmpfiles-root" sudoers_dir="$fake_root/etc/sudoers.d" mkdir -p "$sudoers_dir" -grant_names=(alice buildbot-2 user.123 'service$') -for grant_name in "${grant_names[@]}"; do - touch "$sudoers_dir/99-omarchy-nopasswd-$grant_name" +for name in alice buildbot-2 424242; do + : >"$sudoers_dir/99-omarchy-nopasswd-$name" done -touch "$sudoers_dir/omarchy-dns" +: >"$sudoers_dir/omarchy-dns" +/usr/bin/systemd-tmpfiles --root="$fake_root" --remove --inline "${tmpfiles_rules[0]}" +[[ -e $sudoers_dir/99-omarchy-nopasswd-alice ]] || fail "non-boot tmpfiles run shortened a live grant" +/usr/bin/systemd-tmpfiles --root="$fake_root" --remove --boot --inline "${tmpfiles_rules[0]}" +! find "$sudoers_dir" -name '99-omarchy-nopasswd-*' -print -quit | /usr/bin/grep -q . || + fail "boot cleanup left a generated passwordless grant" +[[ -e $sudoers_dir/omarchy-dns ]] || fail "boot cleanup removed an unrelated sudoers rule" +/usr/bin/grep -Fx 'sudo /usr/bin/omarchy-sudo-passwordless __cleanup-all' "$migration_path" >/dev/null +! /usr/bin/grep -q 'omarchy-sudo-passwordless-cleanup.service' "$migration_path" || + fail "migration retained a custom boot service instead of package-owned tmpfiles" +pass "package-owned boot cleanup is narrow, boot-only, and migration-safe" -systemd-tmpfiles --root="$fake_root" --remove --inline "${tmpfiles_rules[@]}" -[[ -f $sudoers_dir/99-omarchy-nopasswd-alice ]] || - fail "boot-only cleanup leaves a live grant alone outside boot" +# Removing the settings package also removes the tmpfiles rule. Its package +# lifecycle must therefore revoke the same owned namespace synchronously, while +# preserving every unrelated sudoers file. +pkgs_candidates=( + "${OMARCHY_PKGS_PATH:-}" + "$ROOT/../omarchy-pkgs" + "$ROOT/../../omarchy-pkgs" + "$HOME/Work/omarchy/omarchy-pkgs" + "$HOME/Work/omacom/omarchy-pkgs" +) +pkgs_root="" +for candidate in "${pkgs_candidates[@]}"; do + if [[ -n $candidate && -d $candidate/pkgbuilds/omarchy-settings ]]; then + pkgs_root=$candidate + break + fi +done +[[ -n $pkgs_root ]] || fail "omarchy-pkgs checkout found for passwordless package-removal coverage" -systemd-tmpfiles --root="$fake_root" --remove --boot --inline "${tmpfiles_rules[@]}" -for grant_name in "${grant_names[@]}"; do - stale_grant="$sudoers_dir/99-omarchy-nopasswd-$grant_name" - [[ ! -e $stale_grant ]] || fail "boot cleanup removes every generated grant" "$stale_grant" +for package_name in omarchy-settings omarchy-settings-dev; do + install_script="$pkgs_root/pkgbuilds/$package_name/$package_name.install" + transformed_install="$test_tmp/$package_name.install" + removal_root="$test_tmp/$package_name-remove" + removal_sudoers="$removal_root/etc/sudoers.d" + mkdir -p "$removal_sudoers" + : >"$removal_sudoers/99-omarchy-nopasswd-1000" + : >"$removal_sudoers/99-omarchy-nopasswd-legacy-user" + : >"$removal_sudoers/omarchy-dns" + ln -s ../usr/share/omarchy/etc-overrides/os-release "$removal_root/etc/os-release" + grep -Fq 'ln -s ../usr/share/omarchy/etc-overrides/os-release /etc/os-release' "$install_script" || + fail "$package_name installation does not select package-owned OS metadata" + sed "s#/etc/#$removal_root/etc/#g" "$install_script" >"$transformed_install" + ( + source "$transformed_install" + post_remove + ) || fail "$package_name removal revokes active passwordless grants" + ! find "$removal_sudoers" -name '99-omarchy-nopasswd-*' -print -quit | grep -q . || + fail "$package_name removal leaves a passwordless grant behind" + [[ -e $removal_sudoers/omarchy-dns ]] || + fail "$package_name removal deletes an unrelated sudoers policy" + [[ -L $removal_root/etc/os-release ]] && + [[ $(readlink "$removal_root/etc/os-release") == ../usr/lib/os-release ]] || + fail "$package_name removal does not restore the standard OS selector" + + ln -sfn ../administrator/os-release "$removal_root/etc/os-release" + : >"$removal_sudoers/99-omarchy-nopasswd-1001" + ( + source "$transformed_install" + post_remove + ) || fail "$package_name removal handles administrator OS selector state" + [[ $(readlink "$removal_root/etc/os-release") == ../administrator/os-release ]] || + fail "$package_name removal overwrites an administrator OS selector" + [[ ! -e $removal_sudoers/99-omarchy-nopasswd-1001 ]] || + fail "$package_name removal grant cleanup depends on OS selector state" done -[[ -f $sudoers_dir/omarchy-dns ]] || fail "boot cleanup preserves unrelated sudoers rules" -pass "systemd-tmpfiles removes generated grants only during boot" +pass "settings package removal revokes grants and preserves package-selector ownership" + +# Exercise the production flock wrapper under contention. mkdir is an atomic +# overlap detector; all workers must enter and leave the protected region. +lock_dir="$test_tmp/lock-runtime" +mkdir "$lock_dir" +lock_lib="$test_tmp/lock-lib.sh" +function_prefix | + sed -e "s#/run/omarchy/sudo-passwordless#$lock_dir#g" \ + -e "s#/run/lock/omarchy-sudo-passwordless.lock#$test_tmp/passwordless.lock#g" \ + -e 's#/usr/bin/chown root:root "$LOCK_FILE"#/usr/bin/true#' >"$lock_lib" +worker="$test_tmp/worker.sh" +cat >"$worker" <<'WORKER' +#!/bin/bash +set -euo pipefail +source "$LOCK_LIB" +prepare_root_state() { :; } +critical() { + mkdir "$LOCK_SENTINEL" + sleep 0.03 + rmdir "$LOCK_SENTINEL" + printf x >>"$LOCK_RESULTS" +} +with_root_lock critical +WORKER +chmod +x "$worker" +for _ in {1..8}; do + LOCK_LIB="$lock_lib" LOCK_SENTINEL="$test_tmp/held" LOCK_RESULTS="$test_tmp/results" bash "$worker" & +done +wait +[[ $(wc -c <"$test_tmp/results") == 8 ]] || fail "concurrent passwordless operations serialize" +pass "passwordless sudo serializes concurrent operations" + +# Same-boot expiry calls the fixed installed cleanup command, and cleanup +# removes policy before touching a timer so timer failures cannot extend it. +grep -F '"$INSTALLED_SELF" __expire "$uid"' "$command_path" >/dev/null +cleanup_body=$(awk '/^cleanup_uid_locked\(\) \{/ { in_body=1 } in_body { print } in_body && /^}/ { exit }' "$command_path") +rm_line=$(grep -n '/usr/bin/rm -f' <<<"$cleanup_body" | head -1 | cut -d: -f1) +stop_line=$(grep -n 'stop_timer' <<<"$cleanup_body" | tail -1 | cut -d: -f1) +((rm_line < stop_line)) || fail "expiry removes sudo policy before timer cleanup" +pass "same-boot expiration is fixed-target and fail closed" From 8c303495acdc7db220219c373b67f0aab20d7f98 Mon Sep 17 00:00:00 2001 From: Taksh Date: Tue, 1 Sep 2026 23:55:53 +0530 Subject: [PATCH 008/194] fix: use subl for the Sublime Text default editor Signed-off-by: Taksh --- bin/omarchy-default-editor | 2 +- bin/omarchy-launch-editor | 3 +++ default/omarchy/omarchy-menu.jsonc | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/bin/omarchy-default-editor b/bin/omarchy-default-editor index 25134081d36e..1e82e17245da 100755 --- a/bin/omarchy-default-editor +++ b/bin/omarchy-default-editor @@ -25,7 +25,7 @@ case "$1" in code) selection="code"; editor="code"; name="VSCode"; glyph= ;; cursor) selection="cursor"; editor="cursor"; name="Cursor"; glyph= ;; zed | zeditor) selection="zed"; editor="zeditor"; name="Zed"; glyph= ;; -sublime_text) selection="sublime_text"; editor="sublime_text"; name="Sublime Text"; glyph= ;; +sublime_text | subl) selection="sublime_text"; editor="subl"; name="Sublime Text"; glyph= ;; helix) selection="helix"; editor="helix"; name="Helix"; glyph= ;; vim) selection="vim"; editor="vim"; name="Vim"; glyph= ;; emacs) selection="emacs"; editor="emacs"; name="Emacs"; glyph= ;; diff --git a/bin/omarchy-launch-editor b/bin/omarchy-launch-editor index 8a69dabd4bbc..52999719b0e5 100755 --- a/bin/omarchy-launch-editor +++ b/bin/omarchy-launch-editor @@ -18,6 +18,9 @@ else editor="nvim" fi +# sublime-text-4 ships `subl` on PATH, not `sublime_text`. +[[ $editor == sublime_text ]] && editor=subl + omarchy-cmd-present "$editor" || editor="nvim" case "${editor##*/}" in diff --git a/default/omarchy/omarchy-menu.jsonc b/default/omarchy/omarchy-menu.jsonc index 30ee45fcb198..ef1a53ce6d39 100644 --- a/default/omarchy/omarchy-menu.jsonc +++ b/default/omarchy/omarchy-menu.jsonc @@ -164,7 +164,7 @@ "setup.default.editor.vscode": {"icon":"","label":"VSCode","checked":"[[ \"$(omarchy-default-editor)\" == \"code\" ]]","action":"omarchy-default-editor code"}, "setup.default.editor.cursor": {"icon":"","label":"Cursor","checked":"[[ \"$(omarchy-default-editor)\" == \"cursor\" ]]","action":"omarchy-default-editor cursor"}, "setup.default.editor.zed": {"icon":"","label":"Zed","checked":"[[ \"$(omarchy-default-editor)\" == \"zeditor\" ]]","action":"omarchy-default-editor zed"}, - "setup.default.editor.sublime": {"icon":"","label":"Sublime Text","checked":"[[ \"$(omarchy-default-editor)\" == \"sublime_text\" ]]","action":"omarchy-default-editor sublime_text"}, + "setup.default.editor.sublime": {"icon":"","label":"Sublime Text","when":"omarchy-cmd-present subl","checked":"[[ \"$(omarchy-default-editor)\" == \"subl\" ]]","action":"omarchy-default-editor sublime_text"}, "setup.default.editor.helix": {"icon":"","label":"Helix","checked":"[[ \"$(omarchy-default-editor)\" == \"helix\" ]]","action":"omarchy-default-editor helix"}, "setup.default.editor.vim": {"icon":"","label":"Vim","checked":"[[ \"$(omarchy-default-editor)\" == \"vim\" ]]","action":"omarchy-default-editor vim"}, "setup.default.editor.emacs": {"icon":"","label":"Emacs","checked":"[[ \"$(omarchy-default-editor)\" == \"emacs\" ]]","action":"omarchy-default-editor emacs"}, From 0a65b45ab145c5bc134b6846e72e12dbf459de53 Mon Sep 17 00:00:00 2001 From: Adolanium <94890352+Adolanium@users.noreply.github.com> Date: Tue, 25 Aug 2026 08:48:49 +0300 Subject: [PATCH 009/194] Refuse hook and state names that are paths omarchy-hook and omarchy-state set join a name straight into a path. A name with a slash, or a bare . or .., points outside the hooks or state directory. Every caller in the repo passes a fixed label, so this is a footgun guard for future callers, not a fix for anything that ships today. Names with dots in the middle (a..b) stay allowed. omarchy-state clear is untouched: find -name matches basenames only. --- bin/omarchy-hook | 12 +++ bin/omarchy-state | 15 ++- test/shell.d/hook-state-name-guard-test.sh | 109 +++++++++++++++++++++ 3 files changed, 135 insertions(+), 1 deletion(-) create mode 100644 test/shell.d/hook-state-name-guard-test.sh diff --git a/bin/omarchy-hook b/bin/omarchy-hook index 8c2a59d99c12..499cdf14cfa5 100755 --- a/bin/omarchy-hook +++ b/bin/omarchy-hook @@ -11,6 +11,18 @@ if (( $# < 1 )); then fi HOOK=$1 + +# Hook names are fixed labels chosen by Omarchy code (post-update, theme-set, +# font-set). The name becomes a filename under the hooks directory. A slash +# would turn it into directory levels, and a bare `.` or `..` would point bash +# at the directory itself or its parent. Refuse those rather than follow them. +# Dots inside a name (a..b) are fine; once slashes are out, only the whole +# name being `.` or `..` can leave the directory. +if [[ -z $HOOK || $HOOK == */* || $HOOK == "." || $HOOK == ".." ]]; then + echo "Invalid hook name: $HOOK" >&2 + exit 2 +fi + HOOK_PATH="$HOME/.config/omarchy/hooks/$1" HOOK_DIR="$HOOK_PATH.d" shift diff --git a/bin/omarchy-state b/bin/omarchy-state index 4fda5b3a63ab..3b2f5e17e40f 100755 --- a/bin/omarchy-state +++ b/bin/omarchy-state @@ -21,6 +21,19 @@ if [[ -z $STATE_NAME ]]; then fi case "$COMMAND" in -set) touch "$STATE_DIR/$STATE_NAME" ;; +set) + # State names are fixed labels (reboot-required, restart-*-required). The + # name becomes a filename under the state directory. A slash would turn it + # into directory levels, and a bare `.` or `..` would touch the directory + # itself or its parent. Refuse those. Dots inside a name (a..b) are fine; + # once slashes are out, only the whole name being `.` or `..` can leave the + # directory. clear needs no such guard: find -name matches basenames only, + # so a pattern can never walk out of the directory. + if [[ $STATE_NAME == */* || $STATE_NAME == "." || $STATE_NAME == ".." ]]; then + echo "Invalid state name: $STATE_NAME" >&2 + exit 2 + fi + touch "$STATE_DIR/$STATE_NAME" + ;; clear) find "$STATE_DIR" -maxdepth 1 -type f -name "$STATE_NAME" -delete ;; esac diff --git a/test/shell.d/hook-state-name-guard-test.sh b/test/shell.d/hook-state-name-guard-test.sh new file mode 100644 index 000000000000..2955ad27b67c --- /dev/null +++ b/test/shell.d/hook-state-name-guard-test.sh @@ -0,0 +1,109 @@ +#!/bin/bash + +set -euo pipefail + +source "$(dirname "${BASH_SOURCE[0]}")/base-test.sh" + +work_dir=$(mktemp -d) +trap 'rm -rf "$work_dir"' EXIT + +fake_home="$work_dir/home" +mkdir -p "$fake_home/.config/omarchy/hooks" "$fake_home/.local/state/omarchy" + +# --- omarchy-hook -------------------------------------------------------------- + +# A hook name is a label, not a path. One carrying a slash, or one that is a +# bare `.` or `..`, would run a script from outside the hooks directory. + +cat >"$fake_home/.config/omarchy/hooks/test-hook" <<'SH' +touch "$HOME/hook-ran" +SH + +HOME="$fake_home" "$ROOT/bin/omarchy-hook" test-hook +[[ -f $fake_home/hook-ran ]] || + fail "omarchy hook runs a named hook from the hooks directory" +pass "omarchy hook runs a named hook from the hooks directory" + +# Dots inside a name are not a path. a..b stays inside the hooks directory. +cat >"$fake_home/.config/omarchy/hooks/a..b" <<'SH' +touch "$HOME/dotted-hook-ran" +SH + +HOME="$fake_home" "$ROOT/bin/omarchy-hook" a..b +[[ -f $fake_home/dotted-hook-ran ]] || + fail "omarchy hook accepts a hook name with dots in the middle" +pass "omarchy hook accepts a hook name with dots in the middle" + +for name in . ..; do + status=0 + HOME="$fake_home" "$ROOT/bin/omarchy-hook" "$name" >/dev/null 2>&1 || status=$? + (( status == 2 )) || + fail "omarchy hook refuses a hook name of $name" "exit: $status" + pass "omarchy hook refuses a hook name of $name" +done + +# This file sits where a name of ../../evil would resolve: hooks/../.. is +# ~/.config. +cat >"$fake_home/.config/evil" <<'SH' +touch "$HOME/escape-ran" +SH +chmod +x "$fake_home/.config/evil" + +status=0 +HOME="$fake_home" "$ROOT/bin/omarchy-hook" "../../evil" >/dev/null 2>&1 || status=$? +(( status == 2 )) || + fail "omarchy hook refuses a hook name with a dot-dot" "exit: $status" +[[ ! -e $fake_home/escape-ran ]] || + fail "omarchy hook runs nothing when it refuses the name" +pass "omarchy hook refuses a hook name with a dot-dot" + +status=0 +HOME="$fake_home" "$ROOT/bin/omarchy-hook" "sub/dir" >/dev/null 2>&1 || status=$? +(( status == 2 )) || + fail "omarchy hook refuses a hook name with a slash" "exit: $status" +pass "omarchy hook refuses a hook name with a slash" + +# --- omarchy-state ------------------------------------------------------------- + +state_dir="$fake_home/.local/state/omarchy" + +HOME="$fake_home" "$ROOT/bin/omarchy-state" set reboot-required +[[ -f $state_dir/reboot-required ]] || + fail "omarchy state set still creates a plain state file" +pass "omarchy state set still creates a plain state file" + +HOME="$fake_home" "$ROOT/bin/omarchy-state" set v1..2 +[[ -f $state_dir/v1..2 ]] || + fail "omarchy state set accepts a state name with dots in the middle" +pass "omarchy state set accepts a state name with dots in the middle" + +for name in . ..; do + status=0 + HOME="$fake_home" "$ROOT/bin/omarchy-state" set "$name" >/dev/null 2>&1 || status=$? + (( status == 2 )) || + fail "omarchy state set refuses a state name of $name" "exit: $status" + pass "omarchy state set refuses a state name of $name" +done + +# state/../.. is ~/.local. The guard must fire before touch gets there. +status=0 +HOME="$fake_home" "$ROOT/bin/omarchy-state" set "../../escape" >/dev/null 2>&1 || status=$? +(( status == 2 )) || + fail "omarchy state set refuses a state name with a dot-dot" "exit: $status" +[[ ! -e $fake_home/.local/escape ]] || + fail "omarchy state set creates nothing outside the state directory" +pass "omarchy state set refuses a state name with a dot-dot" + +status=0 +HOME="$fake_home" "$ROOT/bin/omarchy-state" set "sub/dir" >/dev/null 2>&1 || status=$? +(( status == 2 )) || + fail "omarchy state set refuses a state name with a slash" "exit: $status" +pass "omarchy state set refuses a state name with a slash" + +# clear takes patterns by design ("state-name-or-pattern") and matches +# basenames through find -name, so it can never walk out of the directory. +touch "$state_dir/restart-a-required" "$state_dir/restart-b-required" "$state_dir/keep-me" +HOME="$fake_home" "$ROOT/bin/omarchy-state" clear "restart-*-required" +[[ ! -e $state_dir/restart-a-required && ! -e $state_dir/restart-b-required && -f $state_dir/keep-me ]] || + fail "omarchy state clear still clears matching patterns only" +pass "omarchy state clear still clears matching patterns only" From 2f816a83af81e6fcbe4196860c958b99880e6050 Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Tue, 1 Sep 2026 21:35:15 +0100 Subject: [PATCH 010/194] Document privileged Bash startup exception --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index e4a0084eadf8..6de19cb9a501 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,7 +28,7 @@ Three documentation trees, split by genre and audience: - Prefer `(( ))` over numeric operators inside `[[ ]]` (e.g., `(( count < 50 ))`, not `[[ $count -lt 50 ]]`) - Prefer a full `if`/`else` conditional for simple two-path control flow; don't rely on `exec` or `exit` in one branch to make following statements unreachable - For strings/paths with spaces, quote them instead of escaping spaces with `\ ` (e.g., `"$APP_DIR/Disk Usage.desktop"`, not `$APP_DIR/Disk\ Usage.desktop`) -- Shebangs must use `#!/bin/bash` consistently (never `#!/usr/bin/env bash`) +- Shebangs must use `#!/bin/bash` consistently (never `#!/usr/bin/env bash`). A security-sensitive entrypoint may use the exact `#!/bin/bash -p` form only when it must suppress `BASH_ENV` and exported-function startup injection before its first command; that exception must be explained at the boundary and covered by a regression that rejects an ordinary Bash launch with a decoy `-p` argument. - Scripts under `install/` and `migrations/` may be sourced and intentionally omit shebangs # Command Naming From 03e697b364b0633812eb2ff36392f531751b3c32 Mon Sep 17 00:00:00 2001 From: Ivan Skodje <6776092+ivanskodje@users.noreply.github.com> Date: Thu, 3 Sep 2026 12:43:33 +0200 Subject: [PATCH 011/194] Make status bar badges readable at rest and on hover --- default/themed/vscode-theme.json.tpl | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/default/themed/vscode-theme.json.tpl b/default/themed/vscode-theme.json.tpl index 0897ca0568d1..30e54bbeaaa0 100644 --- a/default/themed/vscode-theme.json.tpl +++ b/default/themed/vscode-theme.json.tpl @@ -440,18 +440,22 @@ "statusBarItem.activeBackground": "{{ muted }}", "statusBarItem.hoverBackground": "{{ muted }}60", "statusBarItem.hoverForeground": "{{ foreground }}", - "statusBarItem.prominentForeground": "{{ foreground }}", + "statusBarItem.prominentForeground": "{{ background }}", "statusBarItem.prominentBackground": "{{ accent }}", "statusBarItem.prominentHoverBackground": "{{ accent }}80", + "statusBarItem.prominentHoverForeground": "{{ background }}", "statusBarItem.remoteBackground": "{{ accent }}", "statusBarItem.remoteForeground": "{{ background }}", "statusBarItem.remoteHoverBackground": "{{ accent }}80", + "statusBarItem.remoteHoverForeground": "{{ background }}", "statusBarItem.errorBackground": "{{ red }}", "statusBarItem.errorForeground": "{{ background }}", "statusBarItem.errorHoverBackground": "{{ red }}80", + "statusBarItem.errorHoverForeground": "{{ background }}", "statusBarItem.warningBackground": "{{ yellow }}", "statusBarItem.warningForeground": "{{ background }}", "statusBarItem.warningHoverBackground": "{{ yellow }}80", + "statusBarItem.warningHoverForeground": "{{ background }}", "statusBarItem.compactHoverBackground": "{{ muted }}", "statusBarItem.focusBorder": "{{ accent }}", From eb8fcdd0b95a27a596be0668bcb7c94a92aaf7e9 Mon Sep 17 00:00:00 2001 From: Ivan Skodje <6776092+ivanskodje@users.noreply.github.com> Date: Thu, 3 Sep 2026 12:49:50 +0200 Subject: [PATCH 012/194] Give the current line a visible highlight in every theme --- default/themed/vscode-theme.json.tpl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/default/themed/vscode-theme.json.tpl b/default/themed/vscode-theme.json.tpl index 30e54bbeaaa0..e8a37857f01b 100644 --- a/default/themed/vscode-theme.json.tpl +++ b/default/themed/vscode-theme.json.tpl @@ -230,8 +230,8 @@ "searchEditor.findMatchBackground": "{{ yellow }}40", "searchEditor.findMatchBorder": "{{ yellow }}", "editor.hoverHighlightBackground": "{{ accent }}20", - "editor.lineHighlightBackground": "{{ background }}60", - "editor.lineHighlightBorder": "{{ background }}00", + "editor.lineHighlightBackground": "{{ mix background foreground 6% }}", + "editor.lineHighlightBorder": "{{ mix background foreground 30% }}", "editorLink.activeForeground": "{{ blue }}", "editor.rangeHighlightBackground": "{{ accent }}10", "editor.rangeHighlightBorder": "{{ accent }}20", From 6d892d4315ae68dc85ea10329f63f250a5af4f4e Mon Sep 17 00:00:00 2001 From: Ivan Skodje <6776092+ivanskodje@users.noreply.github.com> Date: Thu, 3 Sep 2026 15:55:15 +0200 Subject: [PATCH 013/194] Give invisible hover and active states a visible value --- default/themed/vscode-theme.json.tpl | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/default/themed/vscode-theme.json.tpl b/default/themed/vscode-theme.json.tpl index 0897ca0568d1..ce52ae9378d6 100644 --- a/default/themed/vscode-theme.json.tpl +++ b/default/themed/vscode-theme.json.tpl @@ -61,7 +61,7 @@ "textPreformat.background": "{{ background }}", "textSeparator.foreground": "{{ muted }}", - "toolbar.hoverBackground": "{{ background }}", + "toolbar.hoverBackground": "{{ muted }}60", "toolbar.activeBackground": "{{ muted }}", "button.background": "{{ accent }}", @@ -69,7 +69,7 @@ "button.hoverBackground": "{{ blue }}", "button.secondaryForeground": "{{ foreground }}", "button.secondaryBackground": "{{ muted }}", - "button.secondaryHoverBackground": "{{ background }}", + "button.secondaryHoverBackground": "{{ muted }}80", "button.border": "{{ accent }}20", "checkbox.background": "{{ background }}", "checkbox.foreground": "{{ foreground }}", @@ -135,7 +135,7 @@ "tree.indentGuidesStroke": "{{ muted }}", "tree.inactiveIndentGuidesStroke": "{{ muted }}60", "tree.tableColumnsBorder": "{{ muted }}", - "tree.tableOddRowsBackground": "{{ background }}40", + "tree.tableOddRowsBackground": "{{ muted }}20", "activityBar.background": "{{ background }}", "activityBar.dropBorder": "{{ accent }}", @@ -145,7 +145,7 @@ "activityBarBadge.background": "{{ accent }}", "activityBarBadge.foreground": "{{ background }}", "activityBar.activeBorder": "{{ accent }}", - "activityBar.activeBackground": "{{ background }}40", + "activityBar.activeBackground": "{{ muted }}80", "sideBar.background": "{{ background }}", "sideBar.foreground": "{{ foreground }}", @@ -526,7 +526,7 @@ "keybindingLabel.border": "{{ muted }}", "keybindingLabel.bottomBorder": "{{ muted }}", "keybindingTable.headerBackground": "{{ background }}", - "keybindingTable.rowsBackground": "{{ background }}40", + "keybindingTable.rowsBackground": "{{ muted }}20", "terminal.background": "{{ background }}", "terminal.foreground": "{{ foreground }}", @@ -623,7 +623,7 @@ "settings.checkboxBackground": "{{ background }}", "settings.checkboxForeground": "{{ foreground }}", "settings.checkboxBorder": "{{ muted }}", - "settings.rowHoverBackground": "{{ background }}", + "settings.rowHoverBackground": "{{ muted }}60", "settings.textInputBackground": "{{ background }}", "settings.textInputForeground": "{{ foreground }}", "settings.textInputBorder": "{{ muted }}", @@ -704,12 +704,12 @@ "notebook.editorBackground": "{{ background }}", "notebook.cellBorderColor": "{{ muted }}40", - "notebook.cellHoverBackground": "{{ background }}40", + "notebook.cellHoverBackground": "{{ muted }}40", "notebook.cellInsertionIndicator": "{{ accent }}", "notebook.cellStatusBarItemHoverBackground": "{{ muted }}", "notebook.cellToolbarSeparator": "{{ muted }}", "notebook.cellEditorBackground": "{{ background }}", - "notebook.focusedCellBackground": "{{ background }}60", + "notebook.focusedCellBackground": "{{ muted }}80", "notebook.focusedCellBorder": "{{ accent }}", "notebook.focusedEditorBorder": "{{ accent }}", "notebook.inactiveFocusedCellBorder": "{{ muted }}", From 977e0fcdc2ca46b2fbf7dbeab6bd5b29b49b1398 Mon Sep 17 00:00:00 2001 From: Macho0x <187364057+Macho0x@users.noreply.github.com> Date: Fri, 4 Sep 2026 14:32:41 +0700 Subject: [PATCH 014/194] Make VS Code-family editors reload the Omarchy theme when it changes --- bin/omarchy-theme-set-vscode | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/bin/omarchy-theme-set-vscode b/bin/omarchy-theme-set-vscode index c87b6bb8e81e..6517809990c6 100755 --- a/bin/omarchy-theme-set-vscode +++ b/bin/omarchy-theme-set-vscode @@ -68,8 +68,17 @@ install_generated_extension() { ui_theme="vs-dark" fi + # VS Code caches loaded color themes in memory and only rebuilds a registry + # entry when the providing extension changes, so derive the version from the + # theme content: identical palettes keep the cache, new palettes invalidate it. + GENERATED_EXTENSION_VERSION="1.0.$(cksum "$GENERATED_THEME" | cut -d' ' -f1)" + mkdir -p "$ext_dir/themes" - ln -sfn "$GENERATED_THEME" "$ext_dir/themes/omarchy-color-theme.json" + # A real file rather than a symlink into current/theme: the _watch watcher + # below needs a same-inode rewrite to fire, and a symlink would dangle while + # omarchy-theme-set swaps current/theme via rm + mv. + rm -f "$ext_dir/themes/omarchy-color-theme.json" + cat "$GENERATED_THEME" >"$ext_dir/themes/omarchy-color-theme.json" cat > "$ext_dir/package.json" < Date: Fri, 4 Sep 2026 20:18:48 +0200 Subject: [PATCH 015/194] Secure OCaml removal sudo boundary --- bin/omarchy-remove-dev-env | 36 ++- .../remove-dev-env-sudo-security-test.sh | 251 ++++++++++++++++++ 2 files changed, 286 insertions(+), 1 deletion(-) create mode 100755 test/shell.d/remove-dev-env-sudo-security-test.sh diff --git a/bin/omarchy-remove-dev-env b/bin/omarchy-remove-dev-env index a24e7f9e2946..de27eec575f3 100755 --- a/bin/omarchy-remove-dev-env +++ b/bin/omarchy-remove-dev-env @@ -9,6 +9,35 @@ if [[ -z $1 ]]; then exit 1 fi +cleanup_ocaml_sudo_credentials() { + local status=$? + trap - EXIT HUP INT TERM + + if ! /usr/bin/sudo -k >/dev/null 2>&1; then + echo "Failed to invalidate sudo credentials after OCaml removal." >&2 + (( status != 0 )) || status=1 + fi + + exit "$status" +} + +begin_ocaml_sudo_boundary() { + trap cleanup_ocaml_sudo_credentials EXIT + trap 'exit 129' HUP + trap 'exit 130' INT + trap 'exit 143' TERM + + /usr/bin/sudo -k >/dev/null || { + echo "Unable to start OCaml removal with a cold sudo credential state." >&2 + exit 1 + } + + if ! /usr/bin/sudo -N -V >/dev/null 2>&1; then + echo "This sudo does not support --no-update; refusing to remove OCaml." >&2 + exit 1 + fi +} + remove_php() { omarchy-pkg-drop php composer php-sqlite xdebug } @@ -87,10 +116,15 @@ dotnet) mise rm -g dotnet ;; ocaml) + begin_ocaml_sudo_boundary + echo -e "Removing OCaml...\n" opam switch remove default -y 2>/dev/null || true rm -rf ~/.opam 2>/dev/null || true - sudo rm -f /usr/local/bin/opam 2>/dev/null || true + if ! /usr/bin/sudo -N -- /usr/bin/rm -f /usr/local/bin/opam; then + echo "Failed to remove the system opam launcher." >&2 + exit 1 + fi ;; clojure) echo -e "Removing Clojure...\n" diff --git a/test/shell.d/remove-dev-env-sudo-security-test.sh b/test/shell.d/remove-dev-env-sudo-security-test.sh new file mode 100755 index 000000000000..b5e7959d99d0 --- /dev/null +++ b/test/shell.d/remove-dev-env-sudo-security-test.sh @@ -0,0 +1,251 @@ +#!/bin/bash + +set -euo pipefail + +source "$(dirname "$0")/base-test.sh" + +require_command gcc +require_command setpriv +require_command unshare + +if [[ ${OMARCHY_REMOVE_DEV_ENV_SECURITY_NS:-0} != 1 ]]; then + outer_uid=$(id -u) + outer_gid=$(id -g) + subuid=$(awk -F: -v user="$(id -un)" '$1 == user { print $2; exit }' /etc/subuid) + subgid=$(awk -F: -v user="$(id -un)" '$1 == user { print $2; exit }' /etc/subgid) + + if [[ -z $subuid || -z $subgid ]]; then + pass "no subordinate uid/gid range; skipping OCaml sudo namespace proof" + exit 0 + fi + + exec unshare --user --mount \ + --map-users "0:$outer_uid:1" --map-users "1:$subuid:65536" \ + --map-groups "0:$outer_gid:1" --map-groups "1:$subgid:65536" \ + env OMARCHY_REMOVE_DEV_ENV_SECURITY_NS=1 bash "$0" +fi + +[[ $(id -u) == 0 ]] || fail "OCaml sudo proof did not enter its root namespace" + +test_tmp=$(mktemp -d) +test_home=$test_tmp/home +stub_bin=$test_home/bin +event_log=$test_tmp/events +token=$test_tmp/sudo-token +protected_target=$test_tmp/root-reused +active_session="" + +cleanup() { + local status=$? + trap - EXIT + + if [[ $active_session =~ ^[1-9][0-9]*$ ]]; then + kill -TERM -- "-$active_session" 2>/dev/null || kill -TERM "$active_session" 2>/dev/null || true + kill -KILL -- "-$active_session" 2>/dev/null || kill -KILL "$active_session" 2>/dev/null || true + fi + + if [[ -s $test_home/attack.pid ]]; then + attack_pid=$(<"$test_home/attack.pid") + kill "$attack_pid" 2>/dev/null || true + fi + + umount -l /usr/bin/sudo 2>/dev/null || true + umount -l "$test_tmp" 2>/dev/null || true + rm -rf "$test_tmp" 2>/dev/null || true + exit "$status" +} +trap cleanup EXIT + +mount -t tmpfs -o mode=0755,suid tmpfs "$test_tmp" +mkdir -p "$stub_bin" +touch "$event_log" + +cat >"$test_tmp/sudo.c" <<'C' +#include +#include +#include +#include +#include +#include + +static const char *required(const char *name) { + const char *value = getenv(name); + if (!value || !*value) exit(125); + return value; +} + +static void event(const char *message) { + int fd = open(required("TEST_EVENT_LOG"), O_WRONLY | O_APPEND); + if (fd < 0) exit(125); + dprintf(fd, "%s\n", message); + close(fd); +} + +int main(int argc, char **argv) { + const char *token = required("TEST_SUDO_TOKEN"); + + if (geteuid() != 0) return 125; + + if (argc == 2 && strcmp(argv[1], "-k") == 0) { + event("invalidate"); + if (unlink(token) && errno != ENOENT) return 125; + return 0; + } + + if (argc == 3 && strcmp(argv[1], "-N") == 0 && strcmp(argv[2], "-V") == 0) { + event("probe-no-update"); + return getenv("TEST_SUDO_NO_N") ? 2 : 0; + } + + if (argc == 6 && strcmp(argv[1], "-N") == 0 && strcmp(argv[2], "--") == 0 && + strcmp(argv[3], "/usr/bin/rm") == 0 && strcmp(argv[4], "-f") == 0 && + strcmp(argv[5], "/usr/local/bin/opam") == 0) { + event("remove-opam-no-update"); + return getenv("TEST_RM_FAIL") ? 83 : 0; + } + + if (argc >= 3 && strcmp(argv[1], "-n") == 0) { + if (access(token, F_OK) == 0) { + int fd = open(required("TEST_PROTECTED_TARGET"), O_WRONLY | O_CREAT | O_TRUNC, 0600); + if (fd < 0) return 125; + close(fd); + event("attack-reused-root"); + return 0; + } + event("attack-denied"); + return 1; + } + + event("unexpected-sudo"); + return 124; +} +C + +gcc -O2 -Wall -Wextra -o "$test_tmp/sudo" "$test_tmp/sudo.c" +chown 0:0 "$test_tmp/sudo" +chmod 4755 "$test_tmp/sudo" +mount --bind "$test_tmp/sudo" /usr/bin/sudo + +cat >"$stub_bin/attack" <<'STUB' +#!/bin/bash + +printf '%s\n' "$$" >"$HOME/attack.pid" +for _ in {1..200}; do + if /usr/bin/sudo -n -- /usr/bin/true 2>/dev/null; then + exit 0 + fi + /usr/bin/sleep 0.005 +done +STUB + +cat >"$stub_bin/opam" <<'STUB' +#!/bin/bash + +printf 'opam-ran\n' >>"$TEST_EVENT_LOG" +/usr/bin/setsid --fork "$HOME/bin/attack" >/dev/null 2>&1 + +if [[ ${TEST_OPAM_BLOCK:-0} == 1 ]]; then + printf 'ready\n' >"$HOME/ready" + trap 'exit 143' TERM + while :; do /usr/bin/sleep 0.05; done +fi +STUB + +cat >"$stub_bin/mise" <<'STUB' +#!/bin/bash +printf 'mise:%s\n' "$*" >>"$TEST_EVENT_LOG" +STUB + +chmod 0755 "$stub_bin"/* +chown -R 1000:1000 "$test_home" +chown 1000:1000 "$event_log" + +base_env=( + HOME="$test_home" + USER=test + LOGNAME=test + PATH="$stub_bin:/usr/bin:/bin" + TEST_EVENT_LOG="$event_log" + TEST_SUDO_TOKEN="$token" + TEST_PROTECTED_TARGET="$protected_target" +) + +run_user() { + setpriv --reuid=1000 --regid=1000 --clear-groups env -i "${base_env[@]}" "$@" +} + +reset_case() { + if [[ -s $test_home/attack.pid ]]; then + attack_pid=$(<"$test_home/attack.pid") + kill "$attack_pid" 2>/dev/null || true + fi + : >"$event_log" + chown 1000:1000 "$event_log" + rm -f "$token" "$protected_target" "$test_home/attack.pid" "$test_home/ready" +} + +wait_for_attack() { + for _ in {1..240}; do + grep -q '^attack-' "$event_log" 2>/dev/null && return 0 + sleep 0.005 + done + return 1 +} + +reset_case +touch "$token" +chown 0:0 "$token" +run_user bash "$ROOT/bin/omarchy-remove-dev-env" ocaml +wait_for_attack || fail "hostile opam did not exercise the detached sudo poller" +[[ ! -e $protected_target ]] || fail "hostile opam reused root authorization" +[[ ! -e $token ]] || fail "OCaml removal left a reusable sudo credential" +grep -Fxq 'remove-opam-no-update' "$event_log" || fail "OCaml removal did not use sudo --no-update" +! grep -Fxq 'attack-reused-root' "$event_log" || fail "OCaml removal published reusable authorization" +pass "OCaml removal keeps user-controlled opam outside reusable sudo authorization" + +reset_case +if run_user env TEST_SUDO_NO_N=1 bash "$ROOT/bin/omarchy-remove-dev-env" ocaml; then + fail "OCaml removal accepted sudo without --no-update support" +fi +! grep -Fxq 'opam-ran' "$event_log" || fail "unsupported sudo reached user-controlled opam" +pass "OCaml removal validates --no-update support before running opam" + +reset_case +if run_user env TEST_RM_FAIL=1 bash "$ROOT/bin/omarchy-remove-dev-env" ocaml; then + fail "OCaml removal ignored root cleanup failure" +fi +[[ ! -e $token ]] || fail "failed OCaml cleanup left a reusable sudo credential" +pass "OCaml cleanup failures propagate and invalidate credentials" + +reset_case +touch "$token" +chown 0:0 "$token" +setpriv --reuid=1000 --regid=1000 --clear-groups \ + env -i "${base_env[@]}" TEST_OPAM_BLOCK=1 \ + /usr/bin/setsid bash "$ROOT/bin/omarchy-remove-dev-env" ocaml & +session=$! +active_session=$session + +for _ in {1..200}; do + [[ -e $test_home/ready ]] && break + sleep 0.005 +done +[[ -e $test_home/ready ]] || fail "OCaml signal fixture did not become ready" +kill -TERM -- "-$session" 2>/dev/null || kill -TERM "$session" +set +e +wait "$session" +signal_status=$? +set -e +active_session="" +(( signal_status != 0 )) || fail "terminated OCaml removal unexpectedly succeeded" +[[ ! -e $token ]] || fail "terminated OCaml removal left a reusable sudo credential" +[[ ! -e $protected_target ]] || fail "detached opam child reused root after termination" +pass "OCaml removal invalidates credentials on signals" + +reset_case +run_user bash "$ROOT/bin/omarchy-remove-dev-env" node +! grep -Eq '^(invalidate|probe-no-update|unexpected-sudo)$' "$event_log" || + fail "non-OCaml removal crossed the sudo boundary" +grep -Fxq 'mise:uninstall node --all' "$event_log" || fail "Node removal did not run" +grep -Fxq 'mise:rm -g node' "$event_log" || fail "Node removal did not clear the global version" +pass "non-OCaml removals do not inspect or invalidate sudo credentials" From 73a09695f98c7d4c95d88040b5876c858cc5e02e Mon Sep 17 00:00:00 2001 From: Erik Melton Date: Fri, 4 Sep 2026 20:27:53 +0200 Subject: [PATCH 016/194] Strengthen OCaml sudo security test --- .../remove-dev-env-sudo-security-test.sh | 31 +++++++++++++------ 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/test/shell.d/remove-dev-env-sudo-security-test.sh b/test/shell.d/remove-dev-env-sudo-security-test.sh index b5e7959d99d0..27bb3f8bbbe1 100755 --- a/test/shell.d/remove-dev-env-sudo-security-test.sh +++ b/test/shell.d/remove-dev-env-sudo-security-test.sh @@ -8,24 +8,27 @@ require_command gcc require_command setpriv require_command unshare -if [[ ${OMARCHY_REMOVE_DEV_ENV_SECURITY_NS:-0} != 1 ]]; then +if [[ ${OMARCHY_REMOVE_DEV_ENV_SECURITY_NS:-0} != "1" ]]; then outer_uid=$(id -u) outer_gid=$(id -g) - subuid=$(awk -F: -v user="$(id -un)" '$1 == user { print $2; exit }' /etc/subuid) - subgid=$(awk -F: -v user="$(id -un)" '$1 == user { print $2; exit }' /etc/subgid) + outer_user=$(id -un) + subuid_entry=$(awk -F: -v user="$outer_user" -v uid="$outer_uid" '($1 == user || $1 == uid) && $2 ~ /^[0-9]+$/ && $3 ~ /^[0-9]+$/ && $3 >= 1000 { print $2 ":" $3; exit }' /etc/subuid) + subgid_entry=$(awk -F: -v user="$outer_user" -v uid="$outer_uid" '($1 == user || $1 == uid) && $2 ~ /^[0-9]+$/ && $3 ~ /^[0-9]+$/ && $3 >= 1000 { print $2 ":" $3; exit }' /etc/subgid) - if [[ -z $subuid || -z $subgid ]]; then - pass "no subordinate uid/gid range; skipping OCaml sudo namespace proof" + if [[ -z $subuid_entry || -z $subgid_entry ]]; then + pass "no subordinate uid/gid range covering test user 1000; skipping OCaml sudo namespace proof" exit 0 fi + IFS=: read -r subuid subuid_count <<<"$subuid_entry" + IFS=: read -r subgid subgid_count <<<"$subgid_entry" exec unshare --user --mount \ - --map-users "0:$outer_uid:1" --map-users "1:$subuid:65536" \ - --map-groups "0:$outer_gid:1" --map-groups "1:$subgid:65536" \ + --map-users "0:$outer_uid:1" --map-users "1:$subuid:$subuid_count" \ + --map-groups "0:$outer_gid:1" --map-groups "1:$subgid:$subgid_count" \ env OMARCHY_REMOVE_DEV_ENV_SECURITY_NS=1 bash "$0" fi -[[ $(id -u) == 0 ]] || fail "OCaml sudo proof did not enter its root namespace" +(( EUID == 0 )) || fail "OCaml sudo proof did not enter its root namespace" test_tmp=$(mktemp -d) test_home=$test_tmp/home @@ -144,7 +147,7 @@ cat >"$stub_bin/opam" <<'STUB' printf 'opam-ran\n' >>"$TEST_EVENT_LOG" /usr/bin/setsid --fork "$HOME/bin/attack" >/dev/null 2>&1 -if [[ ${TEST_OPAM_BLOCK:-0} == 1 ]]; then +if [[ ${TEST_OPAM_BLOCK:-0} == "1" ]]; then printf 'ready\n' >"$HOME/ready" trap 'exit 143' TERM while :; do /usr/bin/sleep 0.05; done @@ -192,6 +195,12 @@ wait_for_attack() { return 1 } +assert_ocaml_invalidations() { + local context=$1 invalidations + invalidations=$(grep -Fxc 'invalidate' "$event_log" || true) + (( invalidations == 2 )) || fail "$context did not invalidate sudo credentials before and after OCaml removal (saw $invalidations invalidations)" +} + reset_case touch "$token" chown 0:0 "$token" @@ -199,6 +208,7 @@ run_user bash "$ROOT/bin/omarchy-remove-dev-env" ocaml wait_for_attack || fail "hostile opam did not exercise the detached sudo poller" [[ ! -e $protected_target ]] || fail "hostile opam reused root authorization" [[ ! -e $token ]] || fail "OCaml removal left a reusable sudo credential" +assert_ocaml_invalidations "successful OCaml removal" grep -Fxq 'remove-opam-no-update' "$event_log" || fail "OCaml removal did not use sudo --no-update" ! grep -Fxq 'attack-reused-root' "$event_log" || fail "OCaml removal published reusable authorization" pass "OCaml removal keeps user-controlled opam outside reusable sudo authorization" @@ -208,6 +218,7 @@ if run_user env TEST_SUDO_NO_N=1 bash "$ROOT/bin/omarchy-remove-dev-env" ocaml; fail "OCaml removal accepted sudo without --no-update support" fi ! grep -Fxq 'opam-ran' "$event_log" || fail "unsupported sudo reached user-controlled opam" +assert_ocaml_invalidations "unsupported sudo exit" pass "OCaml removal validates --no-update support before running opam" reset_case @@ -215,6 +226,7 @@ if run_user env TEST_RM_FAIL=1 bash "$ROOT/bin/omarchy-remove-dev-env" ocaml; th fail "OCaml removal ignored root cleanup failure" fi [[ ! -e $token ]] || fail "failed OCaml cleanup left a reusable sudo credential" +assert_ocaml_invalidations "failed OCaml cleanup" pass "OCaml cleanup failures propagate and invalidate credentials" reset_case @@ -240,6 +252,7 @@ active_session="" (( signal_status != 0 )) || fail "terminated OCaml removal unexpectedly succeeded" [[ ! -e $token ]] || fail "terminated OCaml removal left a reusable sudo credential" [[ ! -e $protected_target ]] || fail "detached opam child reused root after termination" +assert_ocaml_invalidations "terminated OCaml removal" pass "OCaml removal invalidates credentials on signals" reset_case From 7ea464988ebe2b004068467d9132368fe1ad6cfd Mon Sep 17 00:00:00 2001 From: Akiko Date: Sat, 5 Sep 2026 08:04:22 +0200 Subject: [PATCH 017/194] Remove link to Omarchy 3 manual --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index 5cedfc5ce656..5834780f5b78 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,7 @@ Read more at [omarchy.org](https://omarchy.org). ## The Omarchy Manual -The manual lives in [`manual/`](manual/), which is its authoritative source. It's -mirrored to [learn.omacom.io](https://learn.omacom.io/2/the-omarchy-manual), where -its screenshots are also hosted. +The manual lives in [`manual/`](manual/), which is its authoritative source. - [Welcome to Omarchy!](manual/01-welcome-to-omarchy.md) From a75924aca4ad20275557332956fd2d8665160eab Mon Sep 17 00:00:00 2001 From: Akshar Patel Date: Sat, 5 Sep 2026 17:57:11 -0400 Subject: [PATCH 018/194] Erase old password hashes during factory reset --- bin/omarchy-system-factory-reset | 39 ++++-- test/shell.d/factory-reset-accounts-test.sh | 146 ++++++++++++++++++++ 2 files changed, 171 insertions(+), 14 deletions(-) create mode 100644 test/shell.d/factory-reset-accounts-test.sh diff --git a/bin/omarchy-system-factory-reset b/bin/omarchy-system-factory-reset index 51eca40110a1..f9e57d95f47b 100755 --- a/bin/omarchy-system-factory-reset +++ b/bin/omarchy-system-factory-reset @@ -297,19 +297,34 @@ rebuild_next_boot() { umount "$next$esp_mount" } +# Both the staged system and the retained baseline must lose the old hashes. +scrub_factory_accounts() { + local root="$1" user users + + users=$(awk -F: '$3 >= 1000 && $3 < 60000 { print $1 }' "$root/etc/passwd") || return 1 + for user in $users; do + userdel --root "$root" "$user" 2>>"$LOG_FILE" || return 1 + rm -rf "${root:?}/home/$user" || return 1 + done + + # passwd --lock preserves the hash. Replace it, then remove the backups + # that userdel and usermod leave behind. + usermod --root "$root" --password '!' root >>"$LOG_FILE" 2>&1 || return 1 + rm -f "$root/etc/"{shadow-,gshadow-,passwd-,group-} +} + # Remove the seller's account material and machine identity from the retained # @factory baseline so it can neither be mounted for recovery nor restore the # seller's account on a future reset. Idempotent (a scrubbed baseline has no # uid>=1000 accounts left to remove). sanitize_factory_baseline() { - local factory="$1" user + local factory="$1" btrfs property set -ts "$factory" ro false - for user in $(awk -F: '$3 >= 1000 && $3 < 60000 { print $1 }' "$factory/etc/passwd"); do - userdel --root "$factory" "$user" 2>>"$LOG_FILE" || true - rm -rf "${factory:?}/home/$user" - done - passwd --root "$factory" --lock root >>"$LOG_FILE" 2>&1 || true + if ! scrub_factory_accounts "$factory"; then + btrfs property set -ts "$factory" ro true + fail "could not remove account credentials from the factory baseline (see $LOG_FILE)" + fi rm -f "$factory"/etc/ssh/ssh_host_* rm -f "$factory"/etc/NetworkManager/system-connections/* rm -rf "$factory"/var/lib/NetworkManager/* "$factory/var/lib/tailscale" "$factory/var/lib/iwd" @@ -337,17 +352,13 @@ stage_full_reset() { rm -rf "$next"/var/lib/NetworkManager/* "$next/var/lib/tailscale" "$next/var/lib/iwd" rm -f "$next/var/lib/sddm/state.conf" "$next/etc/sddm.conf.d/autologin.conf" - # A factory snapshot from a normal (normal) install contains the original + # A factory snapshot from a normal install contains the original # user account; first-boot setup must start from none. A leftover account # would keep its password hash and group memberships (including wheel), so # failure here has to abort the reset, not be shrugged off. - local user - for user in $(awk -F: '$3 >= 1000 && $3 < 60000 { print $1 }' "$next/etc/passwd"); do - log "Removing user $user from the factory system" - userdel --root "$next" "$user" 2>>"$LOG_FILE" || - fail "could not remove user $user from the factory system (see $LOG_FILE)" - done - passwd --root "$next" --lock root >>"$LOG_FILE" 2>&1 || true + log "Removing account credentials from the factory system" + scrub_factory_accounts "$next" || + fail "could not remove account credentials from the factory system (see $LOG_FILE)" # @factory itself survives the wipe as the baseline for future resets. If it # came from a normal install it still holds the seller's account and diff --git a/test/shell.d/factory-reset-accounts-test.sh b/test/shell.d/factory-reset-accounts-test.sh new file mode 100644 index 000000000000..7f6f4a3101af --- /dev/null +++ b/test/shell.d/factory-reset-accounts-test.sh @@ -0,0 +1,146 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +if (( EUID != 0 )); then + if unshare --user --map-root-user true 2>/dev/null; then + exec unshare --user --map-root-user bash "$0" + fi + pass "no unprivileged user namespace; skipping factory account cleanup" + exit 0 +fi + +test_tmp=$(mktemp -d) +trap 'rm -rf "$test_tmp"' EXIT + +# Load the production functions without self-elevation or the reset entrypoint. +awk ' + /^[a-z_]+\(\) \{/ { copying = 1 } + copying { print } + /^}/ { copying = 0 } +' "$ROOT/bin/omarchy-system-factory-reset" >"$test_tmp/functions" + +cat >"$test_tmp/reset" <<'SH' +#!/bin/bash +set -euo pipefail +source "$1/functions" +TOP_MNT="$2" +NEXT_NAME=@omarchy-reset-next +PROVISIONING_DIR=/var/lib/omarchy/provisioning +LOG_FILE="$TOP_MNT/reset.log" + +log() { printf '%s\n' "$1" >>"$LOG_FILE"; } +fail() { log "$1"; exit 1; } + +# Account tools are real. Only snapshots, boot rebuilding, and system services +# are replaced: all writes stay inside this test's disposable directory. +btrfs() { + if [[ $1 == "subvolume" && $2 == "snapshot" ]]; then + mkdir -p "$4" + cp -a "$3/." "$4/" + elif [[ $1 == "property" ]]; then + printf '%s\n' "$6" >"$4/read-only" + else + return 1 + fi +} +systemd-id128() { printf '%032d\n' 1; } +install_provisioning_units() { :; } +encrypted_install() { return 1; } +rebuild_next_boot() { touch "$TOP_MNT/rebuilt"; } +sync() { :; } + +userdel() { + [[ ${FAIL_COMMAND:-} == "userdel" && $2 == "$FAIL_ROOT" ]] && return 42 + command userdel "$@" +} +usermod() { + [[ ${FAIL_COMMAND:-} == "usermod" && $2 == "$FAIL_ROOT" ]] && return 42 + command usermod "$@" +} +rm() { + [[ ${FAIL_COMMAND:-} == "rm" && $* == *"$FAIL_ROOT/etc/shadow-"* ]] && return 42 + command rm "$@" +} + +stage_full_reset +SH + +make_fixture() { + local top="$1" root_hash="${2:-original-root-hash}" + local factory="$top/@factory" + mkdir -p "$top/@" "$factory/etc" "$factory/home/seller" \ + "$factory/usr/bin" "$factory/usr/share/omarchy/install/provisioning" \ + "$factory/var/lib/omarchy/provisioning/packages" + touch "$top/@/old-system" "$factory/home/seller/private-file" \ + "$factory/usr/share/omarchy/install/provisioning/omarchy-provision-owner.service" \ + "$factory/var/lib/omarchy/provisioning/packages/node-v0.tar.gz" + printf '#!/bin/bash\n' >"$factory/usr/bin/omarchy-provision-owner" + chmod +x "$factory/usr/bin/omarchy-provision-owner" + printf 'true\n' >"$factory/read-only" + cat >"$factory/etc/passwd" <<'EOF' +root:x:0:0:root:/root:/bin/bash +daemon:x:1:1:daemon:/:/usr/bin/nologin +seller:x:1000:1000:Seller:/home/seller:/bin/bash +EOF + printf 'root:%s:20000:0:99999:7:::\ndaemon:*:20000:0:99999:7:::\nseller:original-user-hash:20000:0:99999:7:::\n' \ + "$root_hash" >"$factory/etc/shadow" + printf 'root:x:0:\ndaemon:x:1:\nseller:x:1000:\nwheel:x:998:seller\n' >"$factory/etc/group" + printf 'root:!::\ndaemon:!::\nseller:!::\nwheel:!::seller\n' >"$factory/etc/gshadow" + printf 'USERGROUPS_ENAB yes\n' >"$factory/etc/login.defs" + chmod 600 "$factory/etc/"{shadow,gshadow} + for file in passwd shadow group gshadow; do + cp "$factory/etc/$file" "$factory/etc/$file-" + done +} + +assert_scrubbed() { + local root="$1" file + [[ $(awk -F: '$1 == "root" { print $2 }' "$root/etc/shadow") == "!" ]] || + fail "reset erases the root hash while keeping the account locked" + ! grep -q 'original-.*-hash\|seller' "$root/etc/"{passwd,shadow,group,gshadow} || + fail "reset removes seller account credentials and group membership" + [[ ! -e $root/home/seller ]] || fail "reset removes the seller's baseline home" + grep -q '^daemon:\*:' "$root/etc/shadow" || fail "reset preserves service accounts" + [[ $(stat -c '%a' "$root/etc/shadow") == "600" ]] || fail "shadow stays private" + for file in passwd shadow group gshadow; do + [[ ! -e $root/etc/$file- ]] || fail "reset removes the $file backup" + done +} + +for scenario in normal locked; do + top="$test_tmp/$scenario" + if [[ $scenario == "locked" ]]; then + make_fixture "$top" '!' + else + make_fixture "$top" + fi + bash "$test_tmp/reset" "$test_tmp" "$top" || fail "$scenario reset stages successfully" + assert_scrubbed "$top/@factory" + assert_scrubbed "$top/@" + [[ $(cat "$top/@factory/read-only") == "true" ]] || fail "baseline returns to read-only" + [[ -f $top/@/var/lib/omarchy/provisioning/pending && -f $top/rebuilt ]] || + fail "reset reaches provisioning after cleanup" + + bash "$test_tmp/reset" "$test_tmp" "$top" || fail "$scenario reset can be repeated" + assert_scrubbed "$top/@factory" + assert_scrubbed "$top/@" + pass "$scenario reset scrubs both roots, preserves service accounts, and can be repeated" +done + +for target in @omarchy-reset-next @factory; do + for command in userdel usermod rm; do + top="$test_tmp/fail-$target-$command" + make_fixture "$top" + if FAIL_COMMAND="$command" FAIL_ROOT="$top/$target" bash "$test_tmp/reset" "$test_tmp" "$top"; then + fail "reset accepted failed $command in $target" + fi + [[ -f $top/@/old-system && ! -e $top/rebuilt ]] || + fail "failed cleanup must not activate or rebuild the reset system" + [[ $(cat "$top/@factory/read-only") == "true" ]] || + fail "failed cleanup must leave the baseline read-only" + pass "failed $command in $target aborts reset before activation" + done +done From a00be8fa16c941749886a80d91413e9bbe3c09e4 Mon Sep 17 00:00:00 2001 From: omarchybot Date: Sun, 6 Sep 2026 05:37:10 -0700 Subject: [PATCH 019/194] Remove the subuid and subgid backups during the factory scrub userdel rewrites /etc/subuid and /etc/subgid, and like every shadow-utils database write it leaves the previous contents behind in a dash-suffixed backup. The scrub removed four of the six backups those tools produce, so the retained @factory baseline still named the previous owner in /etc/subuid- and /etc/subgid- along with their subordinate ID range. Co-Authored-By: Claude Opus 5 (1M context) --- bin/omarchy-system-factory-reset | 2 +- test/shell.d/factory-reset-accounts-test.sh | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/bin/omarchy-system-factory-reset b/bin/omarchy-system-factory-reset index f9e57d95f47b..43348e5a4d0a 100755 --- a/bin/omarchy-system-factory-reset +++ b/bin/omarchy-system-factory-reset @@ -310,7 +310,7 @@ scrub_factory_accounts() { # passwd --lock preserves the hash. Replace it, then remove the backups # that userdel and usermod leave behind. usermod --root "$root" --password '!' root >>"$LOG_FILE" 2>&1 || return 1 - rm -f "$root/etc/"{shadow-,gshadow-,passwd-,group-} + rm -f "$root/etc/"{shadow-,gshadow-,passwd-,group-,subuid-,subgid-} } # Remove the seller's account material and machine identity from the retained diff --git a/test/shell.d/factory-reset-accounts-test.sh b/test/shell.d/factory-reset-accounts-test.sh index 7f6f4a3101af..ed2bb69757d8 100644 --- a/test/shell.d/factory-reset-accounts-test.sh +++ b/test/shell.d/factory-reset-accounts-test.sh @@ -90,8 +90,10 @@ EOF printf 'root:x:0:\ndaemon:x:1:\nseller:x:1000:\nwheel:x:998:seller\n' >"$factory/etc/group" printf 'root:!::\ndaemon:!::\nseller:!::\nwheel:!::seller\n' >"$factory/etc/gshadow" printf 'USERGROUPS_ENAB yes\n' >"$factory/etc/login.defs" + printf 'seller:100000:65536\n' >"$factory/etc/subuid" + printf 'seller:100000:65536\n' >"$factory/etc/subgid" chmod 600 "$factory/etc/"{shadow,gshadow} - for file in passwd shadow group gshadow; do + for file in passwd shadow group gshadow subuid subgid; do cp "$factory/etc/$file" "$factory/etc/$file-" done } @@ -105,7 +107,7 @@ assert_scrubbed() { [[ ! -e $root/home/seller ]] || fail "reset removes the seller's baseline home" grep -q '^daemon:\*:' "$root/etc/shadow" || fail "reset preserves service accounts" [[ $(stat -c '%a' "$root/etc/shadow") == "600" ]] || fail "shadow stays private" - for file in passwd shadow group gshadow; do + for file in passwd shadow group gshadow subuid subgid; do [[ ! -e $root/etc/$file- ]] || fail "reset removes the $file backup" done } From a805ef990e93b8dfa71d1d8c71541fb1c63e956b Mon Sep 17 00:00:00 2001 From: Erik Melton Date: Sun, 6 Sep 2026 15:46:59 +0200 Subject: [PATCH 020/194] Fix OCaml sudo test portability --- .../remove-dev-env-sudo-security-test.sh | 32 +++++++++++++------ 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/test/shell.d/remove-dev-env-sudo-security-test.sh b/test/shell.d/remove-dev-env-sudo-security-test.sh index 27bb3f8bbbe1..0de3976f24f1 100755 --- a/test/shell.d/remove-dev-env-sudo-security-test.sh +++ b/test/shell.d/remove-dev-env-sudo-security-test.sh @@ -22,15 +22,26 @@ if [[ ${OMARCHY_REMOVE_DEV_ENV_SECURITY_NS:-0} != "1" ]]; then IFS=: read -r subuid subuid_count <<<"$subuid_entry" IFS=: read -r subgid subgid_count <<<"$subgid_entry" - exec unshare --user --mount \ - --map-users "0:$outer_uid:1" --map-users "1:$subuid:$subuid_count" \ - --map-groups "0:$outer_gid:1" --map-groups "1:$subgid:$subgid_count" \ - env OMARCHY_REMOVE_DEV_ENV_SECURITY_NS=1 bash "$0" + namespace_args=( + --user --mount + --map-users "0:$outer_uid:1" --map-users "1:$subuid:$subuid_count" + --map-groups "0:$outer_gid:1" --map-groups "1:$subgid:$subgid_count" + ) + + # Probe only the prerequisites; failures from the actual test must propagate. + if unshare "${namespace_args[@]}" /usr/bin/true; then + exec unshare "${namespace_args[@]}" env OMARCHY_REMOVE_DEV_ENV_SECURITY_NS=1 bash "$0" + else + pass "user/mount namespace setup unavailable; skipping OCaml sudo namespace proof" + exit 0 + fi fi (( EUID == 0 )) || fail "OCaml sudo proof did not enter its root namespace" -test_tmp=$(mktemp -d) +# Keep the synthetic user's paths traversable even when TMPDIR is private. +test_tmp=$(mktemp -d /tmp/omarchy-remove-dev-env-security.XXXXXX) +test_helper=$test_tmp/omarchy-remove-dev-env test_home=$test_tmp/home stub_bin=$test_home/bin event_log=$test_tmp/events @@ -60,6 +71,7 @@ cleanup() { trap cleanup EXIT mount -t tmpfs -o mode=0755,suid tmpfs "$test_tmp" +install -m 0755 "$ROOT/bin/omarchy-remove-dev-env" "$test_helper" mkdir -p "$stub_bin" touch "$event_log" @@ -204,7 +216,7 @@ assert_ocaml_invalidations() { reset_case touch "$token" chown 0:0 "$token" -run_user bash "$ROOT/bin/omarchy-remove-dev-env" ocaml +run_user bash "$test_helper" ocaml wait_for_attack || fail "hostile opam did not exercise the detached sudo poller" [[ ! -e $protected_target ]] || fail "hostile opam reused root authorization" [[ ! -e $token ]] || fail "OCaml removal left a reusable sudo credential" @@ -214,7 +226,7 @@ grep -Fxq 'remove-opam-no-update' "$event_log" || fail "OCaml removal did not us pass "OCaml removal keeps user-controlled opam outside reusable sudo authorization" reset_case -if run_user env TEST_SUDO_NO_N=1 bash "$ROOT/bin/omarchy-remove-dev-env" ocaml; then +if run_user env TEST_SUDO_NO_N=1 bash "$test_helper" ocaml; then fail "OCaml removal accepted sudo without --no-update support" fi ! grep -Fxq 'opam-ran' "$event_log" || fail "unsupported sudo reached user-controlled opam" @@ -222,7 +234,7 @@ assert_ocaml_invalidations "unsupported sudo exit" pass "OCaml removal validates --no-update support before running opam" reset_case -if run_user env TEST_RM_FAIL=1 bash "$ROOT/bin/omarchy-remove-dev-env" ocaml; then +if run_user env TEST_RM_FAIL=1 bash "$test_helper" ocaml; then fail "OCaml removal ignored root cleanup failure" fi [[ ! -e $token ]] || fail "failed OCaml cleanup left a reusable sudo credential" @@ -234,7 +246,7 @@ touch "$token" chown 0:0 "$token" setpriv --reuid=1000 --regid=1000 --clear-groups \ env -i "${base_env[@]}" TEST_OPAM_BLOCK=1 \ - /usr/bin/setsid bash "$ROOT/bin/omarchy-remove-dev-env" ocaml & + /usr/bin/setsid bash "$test_helper" ocaml & session=$! active_session=$session @@ -256,7 +268,7 @@ assert_ocaml_invalidations "terminated OCaml removal" pass "OCaml removal invalidates credentials on signals" reset_case -run_user bash "$ROOT/bin/omarchy-remove-dev-env" node +run_user bash "$test_helper" node ! grep -Eq '^(invalidate|probe-no-update|unexpected-sudo)$' "$event_log" || fail "non-OCaml removal crossed the sudo boundary" grep -Fxq 'mise:uninstall node --all' "$event_log" || fail "Node removal did not run" From 35b318ed097792a57d74afc8d2ee5624f348c3b5 Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Sun, 6 Sep 2026 22:26:06 +0100 Subject: [PATCH 021/194] Complete command-scoped authentication across update phases --- AGENTS.md | 2 +- bin/omarchy-channel-set | 5 +- bin/omarchy-refresh-pacman | 261 +---- bin/omarchy-security-functions | 91 ++ bin/omarchy-update | 227 +--- bin/omarchy-update-aur-pkgs | 9 +- bin/omarchy-update-restart | 85 +- bin/omarchy-update-stay-awake | 71 +- default/omarchy/sudo-no-update/sudo | 30 +- docs/update-process.md | 18 +- test/shell.d/channel-test.sh | 14 +- test/shell.d/fixtures/sudo-boundary-test.sh | 124 ++ test/shell.d/update-hook-security-test.sh | 1123 ++----------------- test/shell.d/update-lock-test.sh | 71 +- test/shell.d/update-restart-phases-test.sh | 39 + test/shell.d/update-sequence-test.sh | 62 +- 16 files changed, 586 insertions(+), 1646 deletions(-) create mode 100644 bin/omarchy-security-functions create mode 100644 test/shell.d/fixtures/sudo-boundary-test.sh mode change 100644 => 100755 test/shell.d/update-hook-security-test.sh create mode 100755 test/shell.d/update-restart-phases-test.sh diff --git a/AGENTS.md b/AGENTS.md index e4a0084eadf8..a25ea7a18e1a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,7 +28,7 @@ Three documentation trees, split by genre and audience: - Prefer `(( ))` over numeric operators inside `[[ ]]` (e.g., `(( count < 50 ))`, not `[[ $count -lt 50 ]]`) - Prefer a full `if`/`else` conditional for simple two-path control flow; don't rely on `exec` or `exit` in one branch to make following statements unreachable - For strings/paths with spaces, quote them instead of escaping spaces with `\ ` (e.g., `"$APP_DIR/Disk Usage.desktop"`, not `$APP_DIR/Disk\ Usage.desktop`) -- Shebangs must use `#!/bin/bash` consistently (never `#!/usr/bin/env bash`) +- Shebangs must use `#!/bin/bash` consistently (never `#!/usr/bin/env bash`). A security entrypoint may use `#!/bin/bash -p` when it must suppress inherited startup code before its first command; document the boundary and test rejection of ordinary Bash with a decoy `-p` argument. - Scripts under `install/` and `migrations/` may be sourced and intentionally omit shebangs # Command Naming diff --git a/bin/omarchy-channel-set b/bin/omarchy-channel-set index 7e1123885086..b711da93d8ca 100755 --- a/bin/omarchy-channel-set +++ b/bin/omarchy-channel-set @@ -83,7 +83,7 @@ if [[ -n $dev_checkout ]]; then omarchy-state set reboot-required fi -omarchy-refresh-pacman "$pacman_channel" +omarchy-refresh-pacman "$pacman_channel" defer-hook # --ask 4 accepts omarchy <-> omarchy-dev replacement prompts without file overwrites. sudo env OMARCHY_UPDATE_PACMAN=1 pacman -S --needed --noconfirm --ask 4 "${packages[@]}" @@ -97,3 +97,6 @@ if [[ -z $dev_checkout ]]; then fi omarchy-update -y + +# No channel-owned privileged work follows the historical refresh hook. +omarchy-refresh-pacman "$pacman_channel" run-deferred diff --git a/bin/omarchy-refresh-pacman b/bin/omarchy-refresh-pacman index 612a31ded5eb..af552abb69c8 100755 --- a/bin/omarchy-refresh-pacman +++ b/bin/omarchy-refresh-pacman @@ -4,242 +4,43 @@ # omarchy:requires-sudo=true if [[ $- != *p* ]]; then - echo "Refusing an unsafe Bash startup for pacman refresh." >&2 + echo "Refusing an unsafe Bash startup." >&2 exit 126 fi -require_privileged_bash_startup() { - [[ $- == *p* ]] || return 1 - /usr/bin/env -i /usr/bin/bash -p -c ' - [[ $1 =~ ^[1-9][0-9]*$ ]] || exit 1 - mapfile -d "" -t argv <"/proc/$1/cmdline" || exit 1 - executable=$(/usr/bin/readlink -e -- "/proc/$1/exe") || exit 1 - [[ $executable == /usr/bin/bash ]] - [[ ${argv[0]:-} == /bin/bash || ${argv[0]:-} == /usr/bin/bash ]] - [[ ${argv[1]:-} == -p ]] - ' omarchy-bash-startup "$$" -} -if ! require_privileged_bash_startup; then - echo "Refusing an unsafe Bash startup for pacman refresh." >&2 - exit 126 -fi -unset -f require_privileged_bash_startup - +source "${BASH_SOURCE[0]%/*}/omarchy-security-functions" || exit 126 +omarchy_security_require_privileged_bash_startup || exit 126 set -e - -sanitize_bash_startup_environment() { - local environment_entry environment_name - local needs_reexec=0 - local -a environment_unsets=(-u BASH_ENV -u ENV) - - [[ -z ${BASH_ENV+x} && -z ${ENV+x} ]] || needs_reexec=1 - while IFS= read -r -d '' environment_entry; do - environment_name="${environment_entry%%=*}" - if [[ $environment_name == BASH_FUNC_*%% ]]; then - environment_unsets+=(-u "$environment_name") - needs_reexec=1 - fi - done < <(/usr/bin/env -0) - - if (( needs_reexec )); then - exec /usr/bin/env "${environment_unsets[@]}" /usr/bin/bash -p "$0" "$@" - fi -} -sanitize_bash_startup_environment "$@" -unset -f sanitize_bash_startup_environment - -usage() { - echo "Usage: omarchy-refresh-pacman [stable|rc|edge]" >&2 -} - -# Composite commands can postpone the legacy user hook until their own final -# privilege boundary. The two internal modes are deliberately paired: a caller -# that defers must invoke --run-deferred-hook exactly once after all of its -# sudo-capable work has finished. -channel=stable -hook_mode=normal -case "$#:$1:${2:-}" in - 0::) - ;; - 1:stable: | 1:rc: | 1:edge:) - channel="$1" - ;; - 1:--run-deferred-hook:) - hook_mode=run-deferred - ;; - 2:stable:--defer-hook | 2:rc:--defer-hook | 2:edge:--defer-hook) - channel="$1" - hook_mode=defer - ;; - *) - usage - exit 2 - ;; -esac - -trusted_directory_chain() { - local current="$1" allow_current_user="$2" canonical owner mode current_uid - current_uid=$(/usr/bin/id -u) || return 1 - - while :; do - [[ -d $current && ! -L $current ]] || return 1 - canonical=$(/usr/bin/realpath -e -- "$current") || return 1 - [[ $canonical == "$current" ]] || return 1 - [[ $current == / ]] && break - read -r owner mode < <(/usr/bin/stat -Lc '%u %a' -- "$current") || return 1 - if [[ $owner != 0 ]] && ! { [[ $allow_current_user == "true" && $owner == "$current_uid" ]]; }; then - return 1 - fi - (( (8#$mode & 0022) == 0 )) || return 1 - current=${current%/*} - [[ -n $current ]] || current=/ - done -} - -trusted_omarchy_source_root() { - local config=/etc/omarchy.conf default_root=/usr/share/omarchy configured_root="" canonical="" - local owner="" mode="" links="" size="" line="" encoded="" decoded="" character="" - local index=0 escaped=0 lines=() - - if [[ ! -e $config && ! -L $config ]]; then - configured_root="$default_root" - else - [[ -f $config && ! -L $config ]] || return 1 - canonical=$(/usr/bin/realpath -e -- "$config") || return 1 - [[ $canonical == "$config" ]] || return 1 - read -r owner mode links size < <(/usr/bin/stat -Lc '%u %a %h %s' -- "$config") || return 1 - [[ $owner == "0" && $links == "1" ]] || return 1 - (( (8#$mode & 0022) == 0 && size > 0 && size <= 4096 )) || return 1 - trusted_directory_chain /etc false || return 1 - mapfile -t lines <"$config" || return 1 - (( ${#lines[@]} == 1 )) || return 1 - line="${lines[0]}" - [[ $line == 'export OMARCHY_PATH="'*'"' ]] || return 1 - encoded="${line#'export OMARCHY_PATH="'}" - encoded="${encoded%'"'}" - for (( index = 0; index < ${#encoded}; index++ )); do - character="${encoded:index:1}" - if (( escaped )); then - case "$character" in - '\' | '"' | '$' | '`') decoded+="$character" ;; - *) return 1 ;; - esac - escaped=0 - elif [[ $character == '\' ]]; then - escaped=1 - elif [[ $character == '"' ]]; then - return 1 - else - decoded+="$character" - fi - done - (( escaped == 0 )) || return 1 - configured_root="$decoded" - fi - - [[ -d $configured_root && ! -L $configured_root ]] || return 1 - canonical=$(/usr/bin/realpath -e -- "$configured_root") || return 1 - [[ $canonical == "$configured_root" ]] || return 1 - if [[ $configured_root == "$default_root" ]]; then - trusted_directory_chain "$configured_root" false || return 1 - else - trusted_directory_chain "$configured_root" true || return 1 - fi - printf '%s\n' "$configured_root" -} - -trusted_omarchy_source_file() { - local relative="$1" source="$OMARCHY_PATH/$1" canonical owner mode links directory current_uid - current_uid=$(/usr/bin/id -u) || return 1 - [[ $relative != /* && $relative != ../* && $relative != */../* && $relative != */.. ]] || return 1 - [[ -f $source && ! -L $source ]] || return 1 - canonical=$(/usr/bin/realpath -e -- "$source") || return 1 - [[ $canonical == "$source" && $canonical == "$OMARCHY_PATH/"* ]] || return 1 - read -r owner mode links < <(/usr/bin/stat -Lc '%u %a %h' -- "$source") || return 1 - [[ $links == 1 ]] && (( (8#$mode & 0022) == 0 )) || return 1 - if [[ $OMARCHY_PATH == /usr/share/omarchy ]]; then - [[ $owner == 0 ]] || return 1 - else - [[ $owner == 0 || $owner == "$current_uid" ]] || return 1 - fi - - directory=${source%/*} - while [[ $directory == "$OMARCHY_PATH" || $directory == "$OMARCHY_PATH/"* ]]; do - [[ -d $directory && ! -L $directory ]] || return 1 - canonical=$(/usr/bin/realpath -e -- "$directory") || return 1 - [[ $canonical == "$directory" ]] || return 1 - read -r owner mode < <(/usr/bin/stat -Lc '%u %a' -- "$directory") || return 1 - (( (8#$mode & 0022) == 0 )) || return 1 - if [[ $OMARCHY_PATH == /usr/share/omarchy ]]; then - [[ $owner == 0 ]] || return 1 - else - [[ $owner == 0 || $owner == "$current_uid" ]] || return 1 - fi - [[ $directory == "$OMARCHY_PATH" ]] && break - directory=${directory%/*} - done - printf '%s\n' "$source" -} - -if ! OMARCHY_PATH=$(trusted_omarchy_source_root); then - echo "Refusing to refresh pacman from an untrusted Omarchy source root." >&2 - exit 1 +omarchy_security_sanitize_bash_environment "$0" "$@" +user_path=$PATH +omarchy_security_revoke_sudo_timestamp || exit 1 +omarchy_security_install_sudo_cleanup_traps +omarchy_security_enable_no_update_sudo + +channel="${1:-stable}" +hook_mode="${2:-normal}" +if [[ $channel != "stable" && $channel != "rc" && $channel != "edge" ]]; then + echo "Invalid channel: $channel" >&2 + exit 2 fi -export OMARCHY_PATH -user_path="${PATH:-/usr/bin:/bin}" -PATH="$OMARCHY_PATH/bin:/usr/bin:/usr/sbin:/bin:/sbin" -export PATH - -as_root() { - if ((EUID == 0)); then - "$@" - elif [[ ${OMARCHY_SUDO_NO_UPDATE:-0} == 1 ]]; then - /usr/bin/sudo -N -- "$@" - else - /usr/bin/sudo -- "$@" - fi -} - -cleanup_sudo_credentials() { - /usr/bin/sudo -k || true -} - -trap cleanup_sudo_credentials EXIT - -if [[ $hook_mode == "run-deferred" ]]; then - /usr/bin/sudo -k || exit 1 - PATH="$user_path" "$OMARCHY_PATH/bin/omarchy-hook" pre-refresh-pacman - exit +if [[ $hook_mode != "normal" && $hook_mode != "defer-hook" && $hook_mode != "run-deferred" ]]; then + echo "Invalid refresh hook mode: $hook_mode" >&2 + exit 2 fi -pacman_source=$(trusted_omarchy_source_file "default/pacman/pacman-$channel.conf") || { - echo "Refusing an untrusted pacman configuration source." >&2 - exit 1 -} -mirror_source=$(trusted_omarchy_source_file "default/pacman/mirrorlist-$channel") || { - echo "Refusing an untrusted pacman mirror source." >&2 - exit 1 -} - -as_root /usr/bin/cp -f -- /etc/pacman.conf /etc/pacman.conf.bak -as_root /usr/bin/cp -f -- /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.bak - -echo "Setting channel to $channel" -echo - -# The unprivileged shell opens the authorized source. Root consumes only the -# inherited descriptor, never a caller-writable development-checkout pathname. -as_root /usr/bin/install -T -o root -g root -m 0644 /dev/stdin /etc/pacman.conf <"$pacman_source" -as_root /usr/bin/install -T -o root -g root -m 0644 /dev/stdin /etc/pacman.d/mirrorlist <"$mirror_source" - -# Reset all package DBs and then update. -as_root /usr/bin/env OMARCHY_UPDATE_PACMAN=1 /usr/bin/pacman -Syyuu --noconfirm +if [[ $hook_mode != "run-deferred" ]]; then + sudo cp -f /etc/pacman.conf /etc/pacman.conf.bak + sudo cp -f /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.bak + echo "Setting channel to $channel" + sudo cp -f "$OMARCHY_PATH/default/pacman/pacman-$channel.conf" /etc/pacman.conf + sudo cp -f "$OMARCHY_PATH/default/pacman/mirrorlist-$channel" /etc/pacman.d/mirrorlist + sudo env OMARCHY_UPDATE_PACMAN=1 pacman -Syyuu --noconfirm +fi -# This legacy hook used to run before pacman. Executable user code cannot -# safely precede a later sudo authentication: a child can wait for the new -# timestamp even if the parent invalidates around the hook. Keep the hook, but -# run it only after every privileged refresh step and with a cold credential. -if [[ $hook_mode == "normal" ]]; then - /usr/bin/sudo -k || exit 1 - PATH="$user_path" "$OMARCHY_PATH/bin/omarchy-hook" pre-refresh-pacman +# Keep the historical hook name, but finish every privileged refresh operation +# before running user code. Callers with later root work can defer the hook. +if [[ $hook_mode != "defer-hook" ]]; then + omarchy_security_revoke_sudo_timestamp + PATH="$OMARCHY_PATH/default/omarchy/sudo-no-update:$user_path" \ + "$OMARCHY_PATH/bin/omarchy-hook" pre-refresh-pacman fi diff --git a/bin/omarchy-security-functions b/bin/omarchy-security-functions new file mode 100644 index 000000000000..5c9bd9e48e85 --- /dev/null +++ b/bin/omarchy-security-functions @@ -0,0 +1,91 @@ +#!/bin/bash + +# omarchy:hidden=true +# omarchy:summary=Provide internal helpers for command-scoped sudo authentication + +if [[ ${BASH_SOURCE[0]} == "$0" ]]; then + echo "omarchy-security-functions is an internal function library." >&2 + exit 64 +fi + +omarchy_security_require_privileged_bash_startup() { + [[ $- == *p* ]] || return 1 + /usr/bin/env -i /usr/bin/bash -p -c ' + mapfile -d "" -t argv <"/proc/$1/cmdline" || exit 1 + executable=$(/usr/bin/readlink -e -- "/proc/$1/exe") || exit 1 + [[ $executable == "/usr/bin/bash" && + ( ${argv[0]:-} == "/bin/bash" || ${argv[0]:-} == "/usr/bin/bash" ) && + ${argv[1]:-} == "-p" ]] + ' omarchy-bash-startup "$$" +} + +omarchy_security_sanitize_bash_environment() { + local script=$1 + shift + local entry name environment_fd environment_pid + local -a unsets=() + + # Read the raw environment: privileged Bash ignores exported functions, but + # leaves their records for ordinary child interpreters to import later. + exec {environment_fd}< <(/usr/bin/env -0) + environment_pid=$! + while IFS= read -r -d '' entry <&"$environment_fd"; do + name=${entry%%=*} + case "$name" in + BASH_ENV|ENV|SHELLOPTS|BASHOPTS|PS4|CDPATH|GLOBIGNORE|BASH_FUNC_*%%) + unsets+=(-u "$name") + ;; + esac + done + exec {environment_fd}<&- + wait "$environment_pid" || return 1 + if (( ${#unsets[@]} > 0 )); then + exec /usr/bin/env "${unsets[@]}" /usr/bin/bash -p -- "$script" "$@" + fi +} + +omarchy_security_sudo_supports_no_update() { + local help + help=$(LC_ALL=C /usr/bin/sudo -h 2>&1) || return 1 + /usr/bin/grep -Eq '^usage: sudo .*\[[^]]*N[^]]*\]' <<< "$help" +} + +omarchy_security_revoke_sudo_timestamp() { + /usr/bin/sudo -k +} + +omarchy_security_exit_with_revoked_sudo() { + local status=$1 + trap - EXIT HUP INT TERM + if ! omarchy_security_revoke_sudo_timestamp; then + echo "Could not invalidate cached sudo authorization." >&2 + (( status != 0 )) || status=1 + fi + exit "$status" +} + +omarchy_security_install_signal_exit_traps() { + trap 'exit 129' HUP + trap 'exit 130' INT + trap 'exit 143' TERM +} + +omarchy_security_install_sudo_cleanup_traps() { + trap 'omarchy_security_exit_with_revoked_sudo "$?"' EXIT + omarchy_security_install_signal_exit_traps +} + +omarchy_security_enable_no_update_sudo() { + local wrapper_dir="$OMARCHY_PATH/default/omarchy/sudo-no-update" + if ! omarchy_security_sudo_supports_no_update; then + echo "This sudo does not support --no-update; refusing mixed-trust work." >&2 + return 1 + fi + if [[ ! -f $wrapper_dir/sudo || ! -x $wrapper_dir/sudo ]]; then + echo "The command-scoped sudo wrapper is missing." >&2 + return 1 + fi + PATH="$wrapper_dir:$OMARCHY_PATH/bin:/usr/bin:/usr/sbin:/bin:/sbin" + OMARCHY_SUDO_NO_UPDATE=1 + export PATH OMARCHY_SUDO_NO_UPDATE +} diff --git a/bin/omarchy-update b/bin/omarchy-update index 4b0b1cc8044c..a3cc94a91607 100755 --- a/bin/omarchy-update +++ b/bin/omarchy-update @@ -6,210 +6,27 @@ # omarchy:requires-sudo=true if [[ $- != *p* ]]; then - echo "Refusing an unsafe Bash startup for the Omarchy update." >&2 + echo "Refusing an unsafe Bash startup." >&2 exit 126 fi -require_privileged_bash_startup() { - [[ $- == *p* ]] || return 1 - /usr/bin/env -i /usr/bin/bash -p -c ' - [[ $1 =~ ^[1-9][0-9]*$ ]] || exit 1 - mapfile -d "" -t argv <"/proc/$1/cmdline" || exit 1 - executable=$(/usr/bin/readlink -e -- "/proc/$1/exe") || exit 1 - [[ $executable == /usr/bin/bash ]] - [[ ${argv[0]:-} == /bin/bash || ${argv[0]:-} == /usr/bin/bash ]] - [[ ${argv[1]:-} == -p ]] - ' omarchy-bash-startup "$$" -} -if ! require_privileged_bash_startup; then - echo "Refusing an unsafe Bash startup for the Omarchy update." >&2 - exit 126 -fi -unset -f require_privileged_bash_startup - +source "${BASH_SOURCE[0]%/*}/omarchy-security-functions" || exit 126 +omarchy_security_require_privileged_bash_startup || exit 126 set -e +omarchy_security_sanitize_bash_environment "$0" "$@" +user_path=$PATH +omarchy_security_revoke_sudo_timestamp || exit 1 +omarchy_security_install_sudo_cleanup_traps +omarchy_security_enable_no_update_sudo -# Privileged mode prevents BASH_ENV and exported functions from running before -# this boundary. Re-exec once without their raw environment records so ordinary -# Bash helpers cannot import them again and bypass the trusted command paths. -sanitize_bash_startup_environment() { - local environment_entry environment_name - local needs_reexec=0 - local -a environment_unsets=(-u BASH_ENV -u ENV) - - [[ -z ${BASH_ENV+x} && -z ${ENV+x} ]] || needs_reexec=1 - while IFS= read -r -d '' environment_entry; do - environment_name="${environment_entry%%=*}" - if [[ $environment_name == BASH_FUNC_*%% ]]; then - environment_unsets+=(-u "$environment_name") - needs_reexec=1 - fi - done < <(/usr/bin/env -0) - - if (( needs_reexec )); then - exec /usr/bin/env "${environment_unsets[@]}" /usr/bin/bash -p "$0" "$@" - fi -} -sanitize_bash_startup_environment "$@" -unset -f sanitize_bash_startup_environment - -trusted_directory_chain() { - local current="$1" allow_current_user="$2" canonical owner mode current_uid - current_uid=$(/usr/bin/id -u) || return 1 - - while :; do - [[ -d $current && ! -L $current ]] || return 1 - canonical=$(/usr/bin/realpath -e -- "$current") || return 1 - [[ $canonical == "$current" ]] || return 1 - [[ $current == / ]] && break - read -r owner mode < <(/usr/bin/stat -Lc '%u %a' -- "$current") || return 1 - if [[ $owner != 0 ]] && ! { [[ $allow_current_user == "true" && $owner == "$current_uid" ]]; }; then - return 1 - fi - (( (8#$mode & 0022) == 0 )) || return 1 - current=${current%/*} - [[ -n $current ]] || current=/ - done -} - -trusted_omarchy_source_root() { - local config=/etc/omarchy.conf - local default_root=/usr/share/omarchy - local configured_root="" - local canonical="" - local owner="" - local mode="" - local links="" - local size="" - local line="" - local encoded="" - local decoded="" - local character="" - local index=0 - local escaped=0 - local lines=() - - if [[ ! -e $config && ! -L $config ]]; then - configured_root="$default_root" - else - [[ -f $config && ! -L $config ]] || return 1 - canonical=$(/usr/bin/realpath -e -- "$config") || return 1 - [[ $canonical == "$config" ]] || return 1 - read -r owner mode links size < <(/usr/bin/stat -Lc '%u %a %h %s' -- "$config") || return 1 - [[ $owner == "0" && $links == "1" ]] || return 1 - (( (8#$mode & 0022) == 0 && size > 0 && size <= 4096 )) || return 1 - trusted_directory_chain /etc false || return 1 - - mapfile -t lines <"$config" || return 1 - (( ${#lines[@]} == 1 )) || return 1 - line="${lines[0]}" - [[ $line == 'export OMARCHY_PATH="'*'"' ]] || return 1 - encoded="${line#'export OMARCHY_PATH="'}" - encoded="${encoded%'"'}" - - for (( index = 0; index < ${#encoded}; index++ )); do - character="${encoded:index:1}" - if (( escaped )); then - case "$character" in - '\' | '"' | '$' | '`') decoded+="$character" ;; - *) return 1 ;; - esac - escaped=0 - elif [[ $character == '\' ]]; then - escaped=1 - elif [[ $character == '"' ]]; then - return 1 - else - decoded+="$character" - fi - done - (( escaped == 0 )) || return 1 - configured_root="$decoded" - fi - - [[ -d $configured_root && ! -L $configured_root ]] || return 1 - canonical=$(/usr/bin/realpath -e -- "$configured_root") || return 1 - [[ $canonical == "$configured_root" ]] || return 1 - - if [[ $configured_root == "$default_root" ]]; then - trusted_directory_chain "$configured_root" false || return 1 - else - trusted_directory_chain "$configured_root" true || return 1 - fi - - printf '%s\n' "$configured_root" -} - -sudo_supports_no_update() { - LC_ALL=C /usr/bin/sudo -h 2>&1 | /usr/bin/grep -Eq '^usage: sudo .*\[[^]]*N[^]]*\]' -} - -validate_non_reusable_sudo() { - local wrapper_dir="$OMARCHY_PATH/default/omarchy/sudo-no-update" - local wrapper="$wrapper_dir/sudo" canonical="" current="" owner="" mode="" - - sudo_supports_no_update || { - echo "This sudo does not support --no-update; refusing to run a mixed-trust update." >&2 - return 1 - } - [[ -f $wrapper && -x $wrapper && ! -L $wrapper ]] || { - echo "Trusted no-update sudo wrapper is missing; refusing to run a mixed-trust update." >&2 - return 1 - } - canonical=$(/usr/bin/realpath -e -- "$wrapper") || return 1 - [[ $canonical == "$wrapper" ]] || return 1 - if [[ $OMARCHY_PATH == "/usr/share/omarchy" ]]; then - current="$wrapper" - while :; do - [[ ! -L $current ]] || return 1 - read -r owner mode < <(/usr/bin/stat -Lc '%u %a' -- "$current") || return 1 - [[ $owner == "0" ]] || return 1 - (( (8#$mode & 0022) == 0 )) || return 1 - [[ $current == "$OMARCHY_PATH" ]] && break - current=${current%/*} - done - fi -} - -enable_non_reusable_sudo() { - local wrapper_dir="$OMARCHY_PATH/default/omarchy/sudo-no-update" - - validate_non_reusable_sudo - PATH="$wrapper_dir:$PATH" - export PATH -} - -if ! OMARCHY_PATH=$(trusted_omarchy_source_root); then - echo "Refusing to update from an untrusted Omarchy source root." >&2 - exit 1 -fi -export OMARCHY_PATH -user_path="${PATH:-/usr/bin:/bin}" -PATH="$OMARCHY_PATH/bin:/usr/bin:/usr/sbin:/bin:/sbin" -export PATH update_stay_awake_stopped=0 - -# Verify and enable the security primitive before any update-owned privileged -# work. Every authorization in this workflow is command-scoped (`sudo -N`): it -# may prompt for the command being run, but it never publishes a reusable -# timestamp to a dev hook, migration tool, AUR build, or detached child. -validate_non_reusable_sudo || exit 1 -if [[ ${OMARCHY_SUDO_NO_UPDATE:-0} == 1 ]]; then - enable_non_reusable_sudo -fi -/usr/bin/sudo -k || exit 1 -enable_non_reusable_sudo -export OMARCHY_SUDO_NO_UPDATE=1 - cleanup_update() { local status=$? - - trap - EXIT + trap - EXIT HUP INT TERM if (( update_stay_awake_stopped == 0 )); then - omarchy-update-stay-awake stop || true + omarchy-update-stay-awake stop || status=1 fi - /usr/bin/sudo -k || true - exit "$status" + omarchy_security_exit_with_revoked_sudo "$status" } if [[ -z ${OMARCHY_UPDATE_LOGGED:-} ]]; then @@ -223,6 +40,7 @@ fi trap 'echo ""; echo -e "\033[0;31mSomething went wrong during the update!\n\nPlease review the output above carefully, correct the error, and retry the update.\n\nIf you need assistance, get help from the community at https://omarchy.org/discord\033[0m"' ERR trap cleanup_update EXIT +omarchy_security_install_signal_exit_traps omarchy-update-requires-free-space @@ -243,9 +61,7 @@ if [[ ${1:-} == "-y" ]] || omarchy-update-confirm; then omarchy-update-stay-awake start - # A dev link explicitly authorizes its checkout through root-owned system - # configuration (including sudo's secure_path), so preserve the established - # pull-before-packages/migrations ordering for that trusted mode. + # Preserve the established development-checkout update ordering. omarchy-update-dev omarchy-update-keyring @@ -258,7 +74,7 @@ if [[ ${1:-} == "-y" ]] || omarchy-update-confirm; then # tooling with privileged repairs. The no-update sudo wrapper has covered the # whole update, so neither the package transaction nor a later repair can # publish a timestamp to a detached migration child. - /usr/bin/sudo -k + omarchy_security_revoke_sudo_timestamp omarchy-migrate omarchy-update-orphan-pkgs @@ -275,19 +91,18 @@ if [[ ${1:-} == "-y" ]] || omarchy-update-confirm; then omarchy-update-stay-awake stop update_stay_awake_stopped=1 - # AUR installation can refresh sudo after running package build code. No - # privileged update stage may follow it: user-controlled code can outlive - # its parent and wait for a later timestamp even if we invalidate in between. + # AUR package installation must also use the no-update wrapper. Finish + # update-owned system work before build code, hooks, or mise can run. omarchy-update-aur-pkgs - /usr/bin/sudo -k + omarchy_security_revoke_sudo_timestamp # Hooks and mise execute user-controlled code. Give each a cold credential # boundary and run mise last so it cannot wait for a legitimate hook sudo. # Only the unprivileged reboot prompt follows them. - PATH="$user_path" "$OMARCHY_PATH/bin/omarchy-hook" post-update - /usr/bin/sudo -k - PATH="$user_path" "$OMARCHY_PATH/bin/omarchy-update-mise" - /usr/bin/sudo -k + PATH="$OMARCHY_PATH/default/omarchy/sudo-no-update:$user_path" "$OMARCHY_PATH/bin/omarchy-hook" post-update + omarchy_security_revoke_sudo_timestamp + PATH="$OMARCHY_PATH/default/omarchy/sudo-no-update:$user_path" "$OMARCHY_PATH/bin/omarchy-update-mise" + omarchy_security_revoke_sudo_timestamp "$OMARCHY_PATH/bin/omarchy-update-restart" --reboot-only fi diff --git a/bin/omarchy-update-aur-pkgs b/bin/omarchy-update-aur-pkgs index 4f496b331fc4..8cdfb617317e 100755 --- a/bin/omarchy-update-aur-pkgs +++ b/bin/omarchy-update-aur-pkgs @@ -2,10 +2,17 @@ # omarchy:summary=Update AUR packages if any are installed +sudo_options=() +if [[ ${OMARCHY_SUDO_NO_UPDATE:-0} == "1" ]]; then + sudo_wrapper="$OMARCHY_PATH/default/omarchy/sudo-no-update/sudo" + [[ -x $sudo_wrapper ]] || exit 1 + sudo_options=(--sudo "$sudo_wrapper" --nosudoloop) +fi + if pacman -Qem >/dev/null; then if omarchy-pkg-aur-accessible; then echo -e "\e[32m\nUpdate AUR packages\e[0m" - yay -Sua --noconfirm --cleanafter --ignore gcc14,gcc14-libs + yay "${sudo_options[@]}" -Sua --noconfirm --cleanafter --ignore gcc14,gcc14-libs || exit 1 echo else echo -e "\e[31m\nAUR is unavailable (so skipping updates)\e[0m" diff --git a/bin/omarchy-update-restart b/bin/omarchy-update-restart index 05f7ba056ec4..393d95e0de75 100755 --- a/bin/omarchy-update-restart +++ b/bin/omarchy-update-restart @@ -1,51 +1,66 @@ #!/bin/bash # omarchy:summary=Prompt for required reboot or service restarts after updates +# omarchy:args=[--services-only|--reboot-only] -echo +mode="${1:-all}" +case "$mode" in + all|--services-only|--reboot-only) ;; + *) echo "Unknown restart phase: $mode" >&2; exit 2 ;; +esac +echo confirm_reboot() { - gum confirm "$1" && { omarchy-system-reboot; exit 0; } + if [[ ${OMARCHY_UPDATE_UNATTENDED:-0} == "1" ]]; then + echo "$1 Run omarchy-system-reboot when ready." + elif gum confirm "$1"; then + omarchy-system-reboot + exit 0 + fi } -running_kernel=$(uname -r) -kernel_updated=true +if [[ $mode != "--services-only" ]]; then + running_kernel=$(uname -r) + kernel_updated=true -for kernel in /usr/lib/modules/*/vmlinuz; do - if [[ -f $kernel ]] && pacman -Qo "$kernel" &>/dev/null; then - installed_kernel=$(basename "$(dirname "$kernel")") + for kernel in /usr/lib/modules/*/vmlinuz; do + if [[ -f $kernel ]] && pacman -Qo "$kernel" &>/dev/null; then + installed_kernel=$(basename "$(dirname "$kernel")") - if [[ $installed_kernel == $running_kernel ]]; then - kernel_updated=false - break + if [[ $installed_kernel == $running_kernel ]]; then + kernel_updated=false + break + fi fi + done + + if [[ $kernel_updated == "true" ]]; then + confirm_reboot "Linux kernel has been updated. Reboot?" + elif [[ -f $HOME/.local/state/omarchy/reboot-required ]]; then + confirm_reboot "Updates require reboot. Ready?" fi -done -if [[ $kernel_updated == "true" ]]; then - confirm_reboot "Linux kernel has been updated. Reboot?" -elif [[ -f $HOME/.local/state/omarchy/reboot-required ]]; then - confirm_reboot "Updates require reboot. Ready?" + running_hyprland=$(readlink /proc/$(pgrep -x Hyprland)/exe 2>/dev/null) + if [[ $running_hyprland == *"(deleted)"* ]]; then + confirm_reboot "Hyprland has been updated. Reboot?" + fi fi -running_hyprland=$(readlink /proc/$(pgrep -x Hyprland)/exe 2>/dev/null) -if [[ $running_hyprland == *"(deleted)"* ]]; then - confirm_reboot "Hyprland has been updated. Reboot?" -fi +if [[ $mode != "--reboot-only" ]]; then + for file in "$HOME"/.local/state/omarchy/restart-*-required; do + if [[ -f $file ]]; then + filename=$(basename "$file") + service=$(echo "$filename" | sed 's/restart-\(.*\)-required/\1/') + echo "Restarting $service" + omarchy-state clear "$filename" + omarchy-restart-"$service" + fi + done -for file in "$HOME"/.local/state/omarchy/restart-*-required; do - if [[ -f $file ]]; then - filename=$(basename "$file") - service=$(echo "$filename" | sed 's/restart-\(.*\)-required/\1/') - echo "Restarting $service" - omarchy-state clear "$filename" - omarchy-restart-"$service" - fi -done - -# Updates routinely replace the shell's QML, and a stale process can lazy-load -# new files into old code. A restart failure (locked session, ssh, TTY) only -# prints its reason: the next update or login gets a fresh shell anyway. -echo -e "\e[32m\nRestarting shell\e[0m" -echo "All plugins have been reloaded" -omarchy-restart-shell || true + # Updates routinely replace the shell's QML, and a stale process can lazy-load + # new files into old code. A restart failure (locked session, ssh, TTY) only + # prints its reason: the next update or login gets a fresh shell anyway. + echo -e "\e[32m\nRestarting shell\e[0m" + echo "All plugins have been reloaded" + omarchy-restart-shell || true +fi diff --git a/bin/omarchy-update-stay-awake b/bin/omarchy-update-stay-awake index 5fd9eb151b57..826fee5ef417 100755 --- a/bin/omarchy-update-stay-awake +++ b/bin/omarchy-update-stay-awake @@ -81,45 +81,54 @@ stop() { } start() { - local inhibit_pid="" - local inhibit_start_time="" - local inhibit_runner=() local idle_owner="$$:$RANDOM:$RANDOM" stop mkdir -p "$state_dir" - if omarchy-cmd-present systemd-inhibit; then - if (( EUID != 0 )); then - if [[ -t 0 ]]; then - sudo -v - inhibit_runner=(sudo) - else - inhibit_runner=(pkexec) - fi - fi + # sudo authenticates in the foreground, then backgrounds the inhibitor. + # The held command drops back to this user before publishing its PID, so stop + # can release the inhibitor without another privileged operation or ticket. + local hold_command=( + /usr/bin/systemd-inhibit --what=sleep:idle --who=omarchy-update + --why="Omarchy update in progress" --mode=block + /usr/bin/setpriv --reuid "$UID" --regid "$(id -g)" --clear-groups + /usr/bin/bash -p -c ' + read -r process_stat <"/proc/$$/stat" + process_stat=${process_stat##*) } + read -r -a fields <<< "$process_stat" + printf "%s %s\n" "$$" "${fields[19]}" >"$1" + exec /usr/bin/sleep infinity + ' omarchy-update-inhibitor "$inhibit_pid_file" + ) + + if (( EUID == 0 )); then + ( [[ -z ${OMARCHY_UPDATE_LOCK_FD:-} ]] || exec {OMARCHY_UPDATE_LOCK_FD}>&- + exec "${hold_command[@]}" ) & + elif [[ -t 0 ]]; then + sudo -N -b -- "${hold_command[@]}" + else + ( [[ -z ${OMARCHY_UPDATE_LOCK_FD:-} ]] || exec {OMARCHY_UPDATE_LOCK_FD}>&- + exec pkexec "${hold_command[@]}" ) & + fi - if [[ -n ${OMARCHY_UPDATE_LOCK_FD:-} ]]; then - "${inhibit_runner[@]}" systemd-inhibit \ - --what=sleep:idle \ - --who=omarchy-update \ - --why="Omarchy update in progress" \ - --mode=block \ - sleep infinity >/dev/null 2>&1 {OMARCHY_UPDATE_LOCK_FD}>&- & - else - "${inhibit_runner[@]}" systemd-inhibit \ - --what=sleep:idle \ - --who=omarchy-update \ - --why="Omarchy update in progress" \ - --mode=block \ - sleep infinity >/dev/null 2>&1 & + # For graphical authentication the launcher may wait for a password. Wait for + # either the user-owned held command to become ready or the launcher to fail. + local launcher_pid=${!:-} + local readiness_attempts=0 + while [[ ! -s $inhibit_pid_file ]]; do + if [[ -n $launcher_pid ]] && ! kill -0 "$launcher_pid" 2>/dev/null; then + wait "$launcher_pid" || return 1 + echo "The update sleep inhibitor did not start." >&2 + return 1 fi - inhibit_pid=$! - inhibit_start_time=$(process_start_time "$inhibit_pid" 2>/dev/null || true) - if [[ -n $inhibit_start_time ]]; then - printf '%s %s\n' "$inhibit_pid" "$inhibit_start_time" >"$inhibit_pid_file" + readiness_attempts=$((readiness_attempts + 1)) + if [[ -t 0 ]] && (( EUID != 0 && readiness_attempts >= 100 )); then + echo "The update sleep inhibitor did not become ready." >&2 + return 1 fi - fi + sleep 0.05 + done if [[ ! -f $stay_awake_state ]]; then printf '%s\n' "$idle_owner" >"$idle_owner_file" diff --git a/default/omarchy/sudo-no-update/sudo b/default/omarchy/sudo-no-update/sudo index ca94c1e63ff5..de69347bab43 100755 --- a/default/omarchy/sudo-no-update/sudo +++ b/default/omarchy/sudo-no-update/sudo @@ -1,27 +1,19 @@ #!/bin/bash -p -# Internal update/migration sudo boundary. Authentication may authorize this -# command, but -N prevents it from publishing a timestamp that detached user -# code can silently reuse. - +# Preserve sudo options while preventing authentication from refreshing the +# credential cache. Timestamp maintenance and informational modes stand alone. if [[ $- != *p* ]]; then echo "Refusing an unsafe Bash startup for the sudo boundary." >&2 exit 126 fi +source "${BASH_SOURCE[0]%/*}/../../../bin/omarchy-security-functions" || exit 126 +omarchy_security_require_privileged_bash_startup || exit 126 -require_privileged_bash_startup() { - [[ $- == *p* ]] || return 1 - /usr/bin/env -i /usr/bin/bash -p -c ' - [[ $1 =~ ^[1-9][0-9]*$ ]] || exit 1 - mapfile -d "" -t argv <"/proc/$1/cmdline" || exit 1 - executable=$(/usr/bin/readlink -e -- "/proc/$1/exe") || exit 1 - [[ $executable == /usr/bin/bash ]] - [[ ${argv[0]:-} == /bin/bash || ${argv[0]:-} == /usr/bin/bash ]] - [[ ${argv[1]:-} == -p ]] - ' omarchy-bash-startup "$$" -} -if ! require_privileged_bash_startup; then - echo "Refusing an unsafe Bash startup for the sudo boundary." >&2 - exit 126 +if (( $# == 1 )); then + case "$1" in + -k|--reset-timestamp|-K|--remove-timestamp|-h|--help|-V|--version) + exec /usr/bin/sudo "$@" + ;; + esac fi -exec /usr/bin/sudo -N -- "$@" +exec /usr/bin/sudo -N "$@" diff --git a/docs/update-process.md b/docs/update-process.md index bb73d27101ac..9ec3b96c7f60 100644 --- a/docs/update-process.md +++ b/docs/update-process.md @@ -26,7 +26,7 @@ The design goal is: | `~/.local/state/omarchy/current/` | user | Generated active theme, selected theme name, and current background symlink. | | `~/.local/state/omarchy/migrations/` | user | Per-user migration markers. | | `~/.local/state/omarchy/reboot-required` | user | Optional reboot marker checked by `omarchy-update-restart`. | -| `~/.local/state/omarchy/restart-*-required` | user | Optional allowlisted service/app restart markers checked by `omarchy-update-restart`. Marker names select fixed commands from the system-authorized Omarchy tree; they are not resolved through caller `PATH`. The shell needs no marker: it is restarted unconditionally after every update. | +| `~/.local/state/omarchy/restart-*-required` | user | Optional service/app restart markers checked by `omarchy-update-restart`. The shell needs no marker: it is restarted unconditionally after every update. | ## Migration layout @@ -56,12 +56,7 @@ privileged work should invoke the appropriate helper or privilege prompt. Migrations must be idempotent; if one user already applied a machine-wide repair, the migration should no-op for other users. -The runner derives the migration source from root-owned `/etc/omarchy.conf`, -starts from a cold sudo timestamp, and routes migration sudo calls through -`sudo --no-update`. Historical migrations are strictly ordered and can mix -user-controlled tools or theme hooks with later privileged repairs; no-update -authentication lets those repairs run without publishing a credential a -detached earlier process could reuse. +When invoked by the update, migrations inherit its cold credential state and no-update sudo wrapper. The standalone migration runner has its own security changes in the migration-boundary PR; this update change does not establish that standalone boundary. Historical migrations remain strictly ordered. For watchers and diagnostics, `omarchy-migrate --pending` prints pending migration names and exits `0` when any are pending. When no migrations are @@ -149,9 +144,9 @@ omarchy-update Important behavior: -- `omarchy update` derives its source tree from root-owned `/etc/omarchy.conf`, or the root-owned `/usr/share/omarchy` default when that file is absent. It does not trust inherited `OMARCHY_PATH` or caller `PATH` for the privileged phase. +- `omarchy update` uses the session’s `OMARCHY_PATH` and a fixed command search path for its system phases. User PATH is restored behind the sudo wrapper for hooks and mise. - Mixed-trust update entrypoints start Bash in privileged mode, discard `BASH_ENV`, `ENV`, and exported-function records before launching helpers, and reject an ordinary `bash path/to/command` invocation. Run them as executables (normally through the `omarchy` CLI); `/usr/bin/bash -p path/to/command` is the explicit interpreter form. This keeps shell startup injection from replacing the no-update sudo boundary. -- In dev-link mode, the root-owned configuration is the explicit authorization for the user-writable checkout. `omarchy update` fast-forwards that authorized checkout from its configured upstream before changing system packages or running migrations. +- In dev-link mode, `omarchy update` fast-forwards the active checkout from its configured upstream before changing system packages or running migrations. - Migrations remain in chronological order even though historical entries mix user-controlled code with later privileged repairs. Before entering that mixed-trust tail, Omarchy invalidates its timestamp and forces every later sudo call—including AUR's configurable sudo command—to use `--no-update`; prompts authorize one command without publishing a reusable timestamp. Yay's credential loop is disabled for the update. - User-controlled post-update hooks and mise tools run only after every sudo-capable update stage. Omarchy invalidates its sudo timestamp before each boundary and on every exit; detached children therefore have no later reusable update authorization to wait for. - `-y` exports `OMARCHY_UPDATE_UNATTENDED=1` — a promise not to ask anything. @@ -292,7 +287,8 @@ scripts. | `omarchy-update-confirm` | Gum confirmation copy for `omarchy update`. | **Question.** Could be inlined into `omarchy-update`; separate file only helps keep copy isolated. | | `omarchy-update-dev` | Fast-forwards the active dev-linked checkout from its configured upstream; no-ops for package-backed installs. | **Keep.** Runs before package updates so a checkout conflict stops the update before system mutation. | | `omarchy-update-keyring` | Ensures Omarchy keyring and Arch keyring are current before the main transaction. | **Keep, but review.** It uses targeted `pacman -Sy` for keyring bootstrapping; acceptable for this special case but should remain tightly scoped. | -| `omarchy-update-system-pkgs` | Runs the ordinary guarded `pacman -Syu --noconfirm`. Package-vs-package conflicts may be retried interactively with `pacman -Su`; filesystem conflicts fail closed without moving, restoring, quarantining, or broadly overwriting live paths. The production Quattro transition performs the sole explicit settings-package takeover with `--overwrite='*'`; all later production and developer package transactions obey Pacman's ownership checks. | **Keep.** Small leaf command with no generic privileged conflict handler. | +| `omarchy-update-system-pkgs` | Runs `sudo env OMARCHY_UPDATE_PACMAN=1 pacman -Syu --noconfirm` with `--overwrite '/usr/share/omarchy/*'`, capturing stderr to a report file; on failure it execs `omarchy-update-system-pkgs-when-conflicted`. | **Keep for now.** Small leaf command, clear/testable. | +| `omarchy-update-system-pkgs-when-conflicted` | Hidden conflict handler: quarantines unowned conflicting files under `/var/lib/omarchy/replaced`, retries the upgrade once, restores files the upgrade didn't claim, and hands package-vs-package conflicts to an interactive pacman run (never under `-y`). | **Keep internal/hidden.** Keeps conflict recovery out of the happy path. | | `omarchy-update-pkg-prune` | Trims the pacman cache to two versions per package (`paccache -rk2`) before the snapshot, keeping the offline downgrade path while capping snapshot growth. | **Keep internal/hidden.** | | `omarchy-update-requires-free-space` | Aborts the update below a 10 GiB free-space threshold on `/`; silently skipped when free space cannot be determined; `OMARCHY_UPDATE_FORCE=1` bypasses. | **Keep internal/hidden.** | | `omarchy-migrate` | Public migration command. Waits for pacman, then runs all pending migrations for the current user. Supports `--pending`. | **Keep.** This replaces the discarded `omarchy-update-user-finalize` name and no longer needs `--force`. | @@ -304,7 +300,7 @@ scripts. | `omarchy-update-mise` | Runs `MISE_MINIMUM_RELEASE_AGE=0 mise up` for mise-managed tools — the override of mise's release-age cooldown is the point. | **Keep.** Mise-managed tools are intentionally part of the blessed update path. | | `omarchy-update-orphan-pkgs` | Lists orphans and prompts before removal; noninteractive mode never removes. | **Keep for now.** Safe because it is prompt-only. | | `omarchy-update-analyze-logs` | Scans `/tmp/omarchy-update.log` for known failure patterns, currently initramfs generation. | **Keep/expand.** Useful safety net; should grow only for high-signal checks. | -| `omarchy-update-restart` | Restarts allowlisted components selected by `restart-*-required` markers, always restarts the shell, and prompts for reboot after kernel/Hyprland updates. Internal phase flags let the update finish sudo-capable restarts before user hooks and defer only the unprivileged reboot prompt. | **Keep.** Important final step; may eventually include service-restart checks. | +| `omarchy-update-restart` | Restarts components selected by `restart-*-required` markers, always restarts the shell, and prompts for reboot after kernel/Hyprland updates. Internal phase flags let the update finish sudo-capable restarts before user hooks and defer only the unprivileged reboot prompt. | **Keep.** Important final step; may eventually include service-restart checks. | | `omarchy-update-firmware` | Manual firmware update command using fwupd. Not part of the normal update pipeline. | **Keep separate.** Firmware is not a routine system update step. | | `omarchy-update-time` | Restarts `systemd-timesyncd`. | **Question.** Not really an update command. Consider renaming/moving under system/time maintenance. | diff --git a/test/shell.d/channel-test.sh b/test/shell.d/channel-test.sh index 664e17c50b53..a799e6e00df9 100644 --- a/test/shell.d/channel-test.sh +++ b/test/shell.d/channel-test.sh @@ -105,7 +105,7 @@ assert_log_line() { } run_channel stable -assert_log_line $'refresh\tstable' "stable refreshes the stable pacman channel" +assert_log_line $'refresh\tstable\tdefer-hook' "stable refreshes the stable pacman channel" assert_log_line $'sudo\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy\tomarchy-settings' "stable installs stable Omarchy packages" assert_log_line $'unlink\t--no-reboot' "stable restores the package-backed Omarchy path without an early reboot prompt" assert_log_line $'update\t-y\tOMARCHY_PATH=/usr/share/omarchy' "stable runs the normal update pipeline from the package-backed path" @@ -115,13 +115,13 @@ fi pass "stable does not require reboot when already package-backed" run_channel rc -assert_log_line $'refresh\trc' "rc refreshes the rc pacman channel" +assert_log_line $'refresh\trc\tdefer-hook' "rc refreshes the rc pacman channel" assert_log_line $'sudo\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy\tomarchy-settings' "rc installs rc Omarchy packages" assert_log_line $'unlink\t--no-reboot' "rc restores the package-backed Omarchy path without an early reboot prompt" assert_log_line $'update\t-y\tOMARCHY_PATH=/usr/share/omarchy' "rc runs the normal update pipeline from the package-backed path" OMARCHY_TEST_PATH="$ROOT" run_channel edge -assert_log_line $'refresh\tedge' "edge refreshes the edge pacman channel" +assert_log_line $'refresh\tedge\tdefer-hook' "edge refreshes the edge pacman channel" assert_log_line $'sudo\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev' "edge installs development Omarchy packages" assert_log_line $'unlink\t--no-reboot' "edge unlinks dev without an early reboot prompt" assert_log_line $'state\tset\treboot-required' "edge marks reboot required when leaving dev" @@ -137,7 +137,7 @@ if run_channel dev >"$test_tmp/occupied.out" 2>"$test_tmp/occupied.err"; then fi grep -q "already exists and is not a git checkout" "$test_tmp/occupied.err" || fail "dev explains occupied checkout paths" "$(cat "$test_tmp/occupied.err")" -if grep -Fx $'refresh\tedge' "$log_file" >/dev/null; then +if grep -Fx $'refresh\tedge\tdefer-hook' "$log_file" >/dev/null; then fail "dev validates checkout path before changing packages" "$(cat "$log_file")" fi pass "dev refuses occupied non-checkout paths before package changes" @@ -145,15 +145,17 @@ pass "dev refuses occupied non-checkout paths before package changes" rmdir "$checkout" run_channel dev assert_log_line $'gum\tconfirm\t--default=false\tSwitch to dev channel?' "dev asks for confirmation" -assert_log_line $'refresh\tedge' "dev refreshes the edge pacman channel" +assert_log_line $'refresh\tedge\tdefer-hook' "dev refreshes the edge pacman channel" assert_log_line $'sudo\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev' "dev installs development Omarchy packages" assert_log_line $'git\tclone\thttps://github.com/basecamp/omarchy.git\t'"$checkout" "dev clones the source checkout to ~/omarchy" assert_log_line $'link\t'"$checkout"$'\t--no-reboot' "dev links ~/omarchy without an early reboot prompt" assert_log_line $'state\tset\treboot-required' "dev defers the reboot prompt to the update pipeline" assert_log_line $'update\t-y\tOMARCHY_PATH='"$checkout" "dev runs the normal update pipeline from the source checkout" -[[ $(grep -E '^(git|link|state|refresh|sudo|update)' "$log_file") == $'git\tclone\thttps://github.com/basecamp/omarchy.git\t'"$checkout"$'\nlink\t'"$checkout"$'\t--no-reboot\nstate\tset\treboot-required\nrefresh\tedge\nsudo\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev\nupdate\t-y\tOMARCHY_PATH='"$checkout" ]] || +[[ $(grep -E '^(git|link|state|refresh|sudo|update)' "$log_file" | sed '/run-deferred/d') == $'git\tclone\thttps://github.com/basecamp/omarchy.git\t'"$checkout"$'\nlink\t'"$checkout"$'\t--no-reboot\nstate\tset\treboot-required\nrefresh\tedge\tdefer-hook\nsudo\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev\nupdate\t-y\tOMARCHY_PATH='"$checkout" ]] || fail "dev activates the checkout before changing or updating packages" "$(cat "$log_file")" pass "dev activates the checkout before changing or updating packages" +[[ $(tail -1 "$log_file") == $'refresh\tedge\trun-deferred' ]] || fail "channel refresh hook must run after the complete update" +pass "channel changes defer the refresh hook until all update work finishes" OMARCHY_TEST_PATH="$checkout" run_channel stable assert_log_line $'unlink\t--no-reboot' "switching from dev to stable unlinks without an early reboot prompt" diff --git a/test/shell.d/fixtures/sudo-boundary-test.sh b/test/shell.d/fixtures/sudo-boundary-test.sh new file mode 100644 index 000000000000..cabad278e252 --- /dev/null +++ b/test/shell.d/fixtures/sudo-boundary-test.sh @@ -0,0 +1,124 @@ +#!/bin/bash + +# Test the real orchestration with fixed privileged paths redirected to harmless +# stand-ins. No host sudo, package transaction, namespace root, or exploit runs. +boundary_tmp=$(mktemp -d) +trap 'rm -rf "$boundary_tmp"' EXIT +export SUDO_TEST_ROOT="$boundary_tmp/omarchy" +export SUDO_TEST_LOG="$boundary_tmp/events" +export SUDO_TEST_CACHE="$boundary_tmp/cache" +export OMARCHY_PATH="$SUDO_TEST_ROOT" +export SUDO_TEST_HOME="$boundary_tmp/home" +mkdir -p "$SUDO_TEST_HOME" +mkdir -p "$SUDO_TEST_ROOT/bin" "$SUDO_TEST_ROOT/mock" "$SUDO_TEST_ROOT/default/omarchy/sudo-no-update" +: >"$SUDO_TEST_LOG" + +copy_boundary_file() { + python3 - "$ROOT" "$SUDO_TEST_ROOT" "$1" <<'PY' +import sys +from pathlib import Path +source, target, name = map(Path,sys.argv[1:]) +p=target/name +p.parent.mkdir(parents=True,exist_ok=True) +s=(source/name).read_text().replace('$HOME', '$SUDO_TEST_HOME') +for command in ['sudo','pacman','omarchy-pkg-missing','systemd-inhibit','setpriv','snapper']: + s=s.replace('/usr/bin/'+command, str(target/'mock'/command)) +s=s.replace('PATH=/usr/bin:/usr/sbin:/bin:/sbin', 'PATH="'+str(target/'bin')+':/usr/bin:/usr/sbin:/bin:/sbin"') +p.write_text(s) +p.chmod((source/name).stat().st_mode & 0o777) +PY +} + +copy_boundary_file bin/omarchy-security-functions +copy_boundary_file default/omarchy/sudo-no-update/sudo + +cat >"$SUDO_TEST_ROOT/mock/sudo" <<'STUB' +#!/bin/bash +set -euo pipefail +printf 'sudo' >>"$SUDO_TEST_LOG" +printf ' %q' "$@" >>"$SUDO_TEST_LOG" +printf '\n' >>"$SUDO_TEST_LOG" +if [[ ${1:-} == "-h" ]]; then + if [[ ${SUDO_TEST_UNSUPPORTED:-0} == "1" ]]; then + echo 'usage: sudo [-ABbEHknPS] command' + else + echo 'usage: sudo [-ABbEHkNnPS] command' + fi + exit 0 +fi +if [[ ${1:-} == "-k" || ${1:-} == "-K" ]]; then + [[ ${SUDO_TEST_REVOKE_FAIL:-0} != "1" ]] || exit 1 + rm -f "$SUDO_TEST_CACHE" + exit 0 +fi +if [[ ${1:-} == "-N" ]]; then + shift +else + touch "$SUDO_TEST_CACHE" +fi +[[ ${SUDO_TEST_SUDO_FAIL:-0} != "1" ]] || exit 1 +background=0 +while (( $# )); do + case "$1" in + -N|-n) shift ;; + -b) background=1; shift ;; + -v) exit 0 ;; + -u|--user) shift 2 ;; + --) shift; break ;; + *) break ;; + esac +done +(( $# )) || exit 0 +if (( background )); then + "$@" & +else + "$@" +fi +STUB +chmod +x "$SUDO_TEST_ROOT/mock/sudo" + +cat >"$SUDO_TEST_ROOT/bin/test-step" <<'STUB' +#!/bin/bash +set -euo pipefail +step=${0##*/} +printf 'step:%s %s\n' "$step" "$*" >>"$SUDO_TEST_LOG" +if [[ $step == "omarchy-hook" || $step == "omarchy-update-mise" ]]; then + [[ ! -e $SUDO_TEST_CACHE ]] || exit 91 +fi +if [[ ${SUDO_TEST_FAIL_STEP:-} == "$step" ]]; then + # Model a misbehaving child leaving state behind, then failing. Cleanup must + # still revoke it. This never invokes real sudo or exercises a privilege flaw. + touch "$SUDO_TEST_CACHE" + exit 17 +fi +if [[ ${SUDO_TEST_SIGNAL_STEP:-} == "$step" ]]; then + touch "$SUDO_TEST_CACHE" + kill -TERM "$PPID" + exit 0 +fi +case "$step" in + omarchy-update-system-pkgs|omarchy-update-keyring|omarchy-snapshot) + sudo /usr/bin/true + ;; + pacman) exit 0 ;; + yay) + [[ $* == *"--sudo $OMARCHY_PATH/default/omarchy/sudo-no-update/sudo"* ]] || exit 92 + [[ $* == *"--nosudoloop"* ]] || exit 93 + ;; +esac +STUB +chmod +x "$SUDO_TEST_ROOT/bin/test-step" +for step in omarchy-update-lock omarchy-update-requires-free-space omarchy-update-confirm omarchy-update-pkg-prune omarchy-snapshot omarchy-update-stay-awake omarchy-update-dev omarchy-update-keyring omarchy-update-system-pkgs omarchy-migrate omarchy-hook omarchy-update-aur-pkgs omarchy-update-mise omarchy-update-orphan-pkgs omarchy-update-analyze-logs omarchy-update-status omarchy-update-restart omarchy-pkg-aur-accessible omarchy-notification-dismiss pacman cp yay; do + ln -s test-step "$SUDO_TEST_ROOT/bin/$step" +done +ln -s ../bin/test-step "$SUDO_TEST_ROOT/mock/pacman" + +reset_boundary() { + : >"$SUDO_TEST_LOG" + rm -f "$SUDO_TEST_CACHE" + unset SUDO_TEST_FAIL_STEP SUDO_TEST_SIGNAL_STEP SUDO_TEST_SUDO_FAIL SUDO_TEST_REVOKE_FAIL SUDO_TEST_UNSUPPORTED +} +assert_boundary_cold() { + [[ ! -e $SUDO_TEST_CACHE ]] || fail "$1 left cached authorization" + [[ $(tail -1 "$SUDO_TEST_LOG") == "sudo -k" ]] || fail "$1 did not revoke at exit" "$(<"$SUDO_TEST_LOG")" +} diff --git a/test/shell.d/update-hook-security-test.sh b/test/shell.d/update-hook-security-test.sh old mode 100644 new mode 100755 index 6245205f3007..4e0922c3d6c3 --- a/test/shell.d/update-hook-security-test.sh +++ b/test/shell.d/update-hook-security-test.sh @@ -2,1039 +2,116 @@ set -euo pipefail -source "$(dirname "$0")/base-test.sh" - -# The setuid helper below models the strongest sudo timestamp mode: one token -# shared by every process for this uid. That makes a detached hook child a -# faithful regression for both global timestamps and the easier tty-sharing -# case. The helper is mounted over /usr/bin/sudo only in this private namespace -# so the scripts must use the fixed trusted invalidation path. -if [[ ${OMARCHY_UPDATE_HOOK_SECURITY_NS:-} != 1 ]]; then - outer_uid=$(id -u) - outer_gid=$(id -g) - subuid=$(awk -F: -v user="$(id -un)" '$1 == user { print $2; exit }' /etc/subuid) - subgid=$(awk -F: -v group="$(id -gn)" '$1 == group { print $2; exit }' /etc/subgid) - - if [[ -z $subuid || -z $subgid ]]; then - pass "no subordinate uid/gid range; skipping update-hook namespace proof" - exit 0 - fi - - exec unshare --user --mount \ - --map-users "0:$outer_uid:1" --map-users "1:$subuid:65536" \ - --map-groups "0:$outer_gid:1" --map-groups "1:$subgid:65536" \ - env OMARCHY_UPDATE_HOOK_SECURITY_NS=1 bash "$0" -fi - -[[ $(id -u) == 0 ]] || fail "update-hook proof entered its root namespace" - -mount -t tmpfs -o mode=0755 tmpfs /run -run_bound=1 -test_tmp=$(mktemp -d -p /run omarchy-update-hook-security.XXXXXXXX) -mount -t tmpfs -o mode=0755 tmpfs "$test_tmp" -chmod 0755 "$test_tmp" -sudo_path_bound=0 -channel_paths_bound=0 -channel_wrapper_tree_bound=0 -aur_paths_bound=0 -font_paths_bound=0 -migration_pkg_paths_bound=0 -etc_bound=0 -persistent_pids=() -cleanup() { - local pid pid_file - for pid_file in "$test_home"/*.pid; do - if [[ -s $pid_file ]]; then - persistent_pids+=("$(<"$pid_file")") - fi - done - for pid in "${persistent_pids[@]}"; do - kill "$pid" 2>/dev/null || true - done - sleep 0.05 - for pid in "${persistent_pids[@]}"; do - kill -KILL "$pid" 2>/dev/null || true - done - if (( sudo_path_bound )); then - umount /usr/bin/sudo - fi - if (( channel_paths_bound )); then - umount /usr/bin/pacman - umount /usr/bin/omarchy-dev-unlink - umount /usr/bin/omarchy-state - umount /usr/bin/omarchy-refresh-pacman - umount /usr/bin/omarchy-update - fi - if (( channel_wrapper_tree_bound )); then - umount /usr/share/omarchy - fi - if (( aur_paths_bound )); then - umount /usr/bin/omarchy-pkg-aur-accessible - umount /usr/bin/yay - fi - if (( font_paths_bound )); then - umount /usr/bin/omarchy-launch-floating-terminal-with-presentation - umount /usr/bin/omarchy-pkg-add - umount /usr/bin/omarchy-font-set - fi - if (( migration_pkg_paths_bound )); then - umount /usr/bin/omarchy-pkg-missing - umount /usr/bin/omarchy-pkg-add - fi - if (( etc_bound )); then - umount /etc - fi - rm -rf "$test_tmp"/* - umount "$test_tmp" - rmdir "$test_tmp" - if (( run_bound )); then - umount /run - fi -} -trap cleanup EXIT - -stub_bin="$test_tmp/bin" -test_home="$test_tmp/home" -root_dir="$test_tmp/root" -token="$test_tmp/sudo-token" -event_log="$test_tmp/events" -hook_log="$test_home/hook-events" -mkdir -p "$stub_bin" "$test_home/.config/omarchy/hooks" "$root_dir" -mkdir -p "$test_tmp/default/omarchy/sudo-no-update" -cp "$ROOT/default/omarchy/sudo-no-update/sudo" "$test_tmp/default/omarchy/sudo-no-update/sudo" -chmod 0755 "$test_tmp/default/omarchy/sudo-no-update/sudo" -mkdir -p "$test_tmp/default/pacman" -cp "$ROOT/default/pacman"/* "$test_tmp/default/pacman/" -chmod 0755 "$test_tmp/default" "$test_tmp/default/omarchy" \ - "$test_tmp/default/omarchy/sudo-no-update" "$test_tmp/default/pacman" -chmod 0644 "$test_tmp/default/pacman"/* -touch "$event_log" "$hook_log" -chown -R 1000:1000 "$test_home" -chown 1000:1000 "$event_log" -chmod 0700 "$test_home" -chmod 0600 "$event_log" "$hook_log" -chmod 0755 "$stub_bin" "$root_dir" - -cat >"$test_tmp/sudo.c" <<'C' -#include -#include -#include -#include -#include -#include -#include - -static const char *required_env(const char *name) { - const char *value = getenv(name); - if (!value || !*value) exit(125); - return value; -} - -static void log_event(const char *event) { - int fd = open(required_env("TEST_SUDO_EVENT_LOG"), O_WRONLY | O_APPEND); - if (fd < 0) exit(125); - if (dprintf(fd, "%s\n", event) < 0) exit(125); - close(fd); +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" +source "$SHELL_TEST_DIR/fixtures/sudo-boundary-test.sh" +copy_boundary_file bin/omarchy-update +copy_boundary_file bin/omarchy-refresh-pacman +# Replace the step symlink, preserving the real fixture dispatcher. +rm "$SUDO_TEST_ROOT/bin/omarchy-update-aur-pkgs" +copy_boundary_file bin/omarchy-update-aur-pkgs +export OMARCHY_UPDATE_LOGGED=1 + +run_update() { + "$SUDO_TEST_ROOT/bin/omarchy-update" "$@" >"$boundary_tmp/output" 2>&1 } -static int authenticate(void) { - int fd = open(required_env("TEST_SUDO_TOKEN"), O_WRONLY | O_CREAT | O_TRUNC, 0600); - if (fd < 0) return 125; - close(fd); - return 0; -} - -static int token_valid(void) { - struct stat st; - return stat(required_env("TEST_SUDO_TOKEN"), &st) == 0 && st.st_uid == 0; -} - -static int is_pacman_command(int argc, char **argv) { - int index; - for (index = 1; index < argc; index++) { - const char *base = strrchr(argv[index], '/'); - base = base ? base + 1 : argv[index]; - if (strcmp(base, "pacman") == 0) return 1; - } - return 0; -} - -int main(int argc, char **argv) { - int no_update = 0; - if (argc == 2 && strcmp(argv[1], "-h") == 0) { - const char *disable = getenv("TEST_SUDO_NO_N"); - if (disable && strcmp(disable, "1") == 0) { - fputs("usage: sudo [-ABbEHknPS] command\n", stdout); - } else { - fputs("usage: sudo [-ABbEHkNnPS] command\n", stdout); - } - return 0; - } - if (argc > 1 && strcmp(argv[1], "-N") == 0) { - no_update = 1; - argc--; - argv++; - } - if (argc > 1 && strcmp(argv[1], "--") == 0) { - argc--; - argv++; - } - if (argc == 2 && strcmp(argv[1], "--authenticate-for-test") == 0) { - if (no_update) { - log_event("authenticate-no-update"); - return 0; - } else { - log_event("authenticate"); - return authenticate(); - } - } - if (argc == 2 && strcmp(argv[1], "-k") == 0) { - log_event("invalidate"); - if (unlink(required_env("TEST_SUDO_TOKEN")) < 0 && errno != ENOENT) return 125; - return 0; - } - if (!token_valid() && !no_update) { - if (is_pacman_command(argc, argv)) { - log_event("authenticate-command"); - if (authenticate() != 0) return 125; - } else { - log_event("deny"); - fputs("sudo: a password is required\n", stderr); - return 1; - } - } - log_event(no_update ? "grant-no-update" : "grant"); - if (argc < 2 || setuid(0) < 0) return 125; - execvp(argv[1], &argv[1]); - return 125; -} -C -gcc -O2 -Wall -Wextra -o "$stub_bin/sudo" "$test_tmp/sudo.c" -chown 0:0 "$stub_bin/sudo" -chmod 4755 "$stub_bin/sudo" -mount --bind "$stub_bin/sudo" /usr/bin/sudo -sudo_path_bound=1 -mount --bind "$ROOT/bin/omarchy-refresh-pacman" /usr/bin/omarchy-refresh-pacman -mount --bind "$ROOT/bin/omarchy-update" /usr/bin/omarchy-update -mount -t tmpfs -o mode=0755 tmpfs /usr/share/omarchy -mkdir -p /usr/share/omarchy/default/omarchy/sudo-no-update -cp "$ROOT/default/omarchy/sudo-no-update/sudo" /usr/share/omarchy/default/omarchy/sudo-no-update/sudo -chmod 0755 /usr/share/omarchy/default /usr/share/omarchy/default/omarchy \ - /usr/share/omarchy/default/omarchy/sudo-no-update -chmod 0755 /usr/share/omarchy/default/omarchy/sudo-no-update/sudo -channel_wrapper_tree_bound=1 - -# Authorize this private tree exactly as omarchy-dev-link authorizes a -# development checkout. Hiding the host /etc keeps the proof self-contained. -mount -t tmpfs -o mode=0755 tmpfs /etc -etc_bound=1 -mkdir -p /etc/pacman.d -touch /etc/pacman.conf /etc/pacman.d/mirrorlist -chmod 0644 /etc/pacman.conf /etc/pacman.d/mirrorlist -printf 'root:x:0:0:root:/root:/bin/bash\n' >/etc/passwd -printf 'root:x:0:\n' >/etc/group -chmod 0644 /etc/passwd /etc/group -write_authorized_source_root() { - local source_root="$1" - local quoted="$source_root" - - quoted=${quoted//\\/\\\\} - quoted=${quoted//\"/\\\"} - quoted=${quoted//\$/\\\$} - quoted=${quoted//\`/\\\`} - printf 'export OMARCHY_PATH="%s"\n' "$quoted" >/etc/omarchy.conf - chown 0:0 /etc/omarchy.conf - chmod 0644 /etc/omarchy.conf -} -write_authorized_source_root "$test_tmp" - -cat >"$test_home/launch-persistent-attack" <<'ATTACK' -#!/bin/bash -/usr/bin/setsid --fork /bin/bash -c ' - printf "%s\n" "$$" >"$3" - for (( attempt = 0; attempt < 200; attempt++ )); do - if /usr/bin/sudo /usr/bin/install -o 0 -g 0 -m 0600 "$1" "$2" 2>/dev/null; then - exit 0 - fi - /usr/bin/sleep 0.01 - done -' omarchy-hook-child "$HOME/payload" "$1" "$2" -ATTACK -cat >"$test_home/payload" <<'PAYLOAD' -RUN+="/tmp/update-hook-payload" -PAYLOAD -chown 1000:1000 "$test_home/launch-persistent-attack" "$test_home/payload" -chmod 0700 "$test_home/launch-persistent-attack" -chmod 0600 "$test_home/payload" - -cat >"$stub_bin/omarchy-update-lock" <<'STUB' -#!/bin/bash -[[ ${1:-} == held ]] -STUB -cat >"$stub_bin/omarchy-update-system-pkgs" <<'STUB' -#!/bin/bash -[[ ${TEST_SKIP_UPDATE_AUTH:-0} == 1 ]] || sudo --authenticate-for-test -STUB -cat >"$stub_bin/omarchy-update-orphan-pkgs" <<'STUB' -#!/bin/bash -[[ ${TEST_SKIP_LATE_AUTH:-0} == 1 ]] || sudo --authenticate-for-test -STUB -cat >"$stub_bin/omarchy-update-aur-pkgs" <<'STUB' -#!/bin/bash -[[ ${TEST_SKIP_LATE_AUTH:-0} == 1 ]] || sudo --authenticate-for-test -STUB -cat >"$stub_bin/omarchy-update-mise" <<'STUB' -#!/bin/bash -sudo /usr/bin/true 2>/dev/null && exit 97 -"$HOME/launch-persistent-attack" "$TEST_MISE_VICTIM" "$TEST_MISE_PID" -STUB -cat >"$stub_bin/omarchy-update-restart" <<'STUB' -#!/bin/bash -printf 'restart:%s\n' "$1" >>"$TEST_HOOK_LOG" -if [[ $1 == --services-only && ${TEST_SKIP_LATE_AUTH:-0} != 1 ]]; then - sudo --authenticate-for-test -fi -STUB -cat >"$stub_bin/omarchy-update-confirm" <<'STUB' -#!/bin/bash -exit 0 -STUB -cat >"$stub_bin/omarchy-migrate" <<'STUB' -#!/bin/bash -if [[ ${TEST_REAL_MIGRATE:-0} == 1 ]]; then - exec "$TEST_ROOT/bin/omarchy-migrate" -fi -if [[ ${TEST_FAILING_STAGE:-} == signal ]]; then - kill -TERM "$PPID" - sleep 0.1 -fi -[[ ${TEST_FAILING_STAGE:-} != migration ]] -STUB -cat >"$stub_bin/omarchy-hook" <<'STUB' -#!/bin/bash -exec bash "$TEST_ROOT/bin/omarchy-hook" "$@" -STUB -cat >"$stub_bin/omarchy-dev-unlink" <<'STUB' -#!/bin/bash -exit 0 -STUB -cat >"$stub_bin/omarchy-state" <<'STUB' -#!/bin/bash -exit 0 -STUB -for command in \ - omarchy-update-requires-free-space omarchy-update-pkg-prune omarchy-snapshot \ - omarchy-update-stay-awake omarchy-update-dev omarchy-update-keyring \ - omarchy-update-analyze-logs omarchy-update-status; do - cat >"$stub_bin/$command" <<'STUB' -#!/bin/bash -exit 0 -STUB +for args in '-y' ''; do + reset_boundary + touch "$SUDO_TEST_CACHE" + run_update $args || fail "update failed" "$(<"$boundary_tmp/output")" + assert_boundary_cold "successful update" + grep -q '^sudo -N /usr/bin/true$' "$SUDO_TEST_LOG" || fail "update package helpers must use no-update sudo" + python3 - "$SUDO_TEST_LOG" <<'PY' +import sys +s=open(sys.argv[1]).read().splitlines() +positions=[next(i for i,line in enumerate(s) if line.startswith(prefix)) for prefix in ['step:omarchy-update-restart --services-only','step:omarchy-update-stay-awake stop','step:yay','step:omarchy-hook post-update','step:omarchy-update-mise','step:omarchy-update-restart --reboot-only']] +assert positions==sorted(positions), s +assert not any(line.startswith('sudo -N ') for line in s[positions[3]:]), s +PY + pass "update $args runs privileged phases before hooks and exits cold" done -cat >"$stub_bin/cp" <<'STUB' -#!/bin/bash -printf 'cp:%s\n' "$*" >>"$TEST_SUDO_EVENT_LOG" -exit 0 -STUB -cat >"$stub_bin/pacman" <<'STUB' -#!/bin/bash -[[ -z ${TEST_PACMAN_DELAY:-} ]] || /usr/bin/sleep "$TEST_PACMAN_DELAY" -exit "${TEST_PACMAN_STATUS:-0}" -STUB -chmod 0755 "$stub_bin"/* -chmod 4755 "$stub_bin/sudo" -mount --bind "$stub_bin/omarchy-dev-unlink" /usr/bin/omarchy-dev-unlink -mount --bind "$stub_bin/omarchy-state" /usr/bin/omarchy-state -mount --bind "$stub_bin/pacman" /usr/bin/pacman -channel_paths_bound=1 -evil_update_bin="$test_home/evil-update-bin" -evil_update_root="$test_home/evil-update-root" -evil_update_marker="$test_home/evil-update-ran" -mkdir -p "$evil_update_bin" "$evil_update_root/migrations" -for command in script omarchy-migrate omarchy-update-system-pkgs; do - cat >"$evil_update_bin/$command" <<'STUB' -#!/bin/bash -touch "$TEST_EVIL_UPDATE_MARKER" -exit 97 -STUB +for step in omarchy-update-system-pkgs yay omarchy-hook omarchy-update-mise; do + reset_boundary + export SUDO_TEST_FAIL_STEP=$step + if run_update -y; then fail "$step failure must fail the update"; fi + assert_boundary_cold "failed $step" + pass "update revokes credentials after $step fails" done -cat >"$evil_update_bin/omarchy-dev-unlink" <<'STUB' -#!/bin/bash -touch "$TEST_EVIL_CHANNEL_HELPER_MARKER" -sudo /usr/bin/install -o 0 -g 0 -m 0600 "$HOME/payload" "$TEST_EVIL_CHANNEL_VICTIM" -STUB -cat >"$evil_update_root/migrations/9999999999.sh" <<'STUB' -#!/bin/bash -sudo /usr/bin/install -o 0 -g 0 -m 0600 "$HOME/payload" "$TEST_EVIL_MIGRATION_VICTIM" -touch "$TEST_EVIL_UPDATE_MARKER" -STUB -chown -R 1000:1000 "$evil_update_bin" "$evil_update_root" -chmod 0755 "$evil_update_bin"/* "$evil_update_root/migrations/9999999999.sh" - -write_attack_hook() { - local hook_name="$1" - - mkdir -p "$test_home/.config/omarchy/hooks/$hook_name.d" - cat >"$test_home/.config/omarchy/hooks/$hook_name" <<'HOOK' -#!/bin/bash -printf 'file:%s\n' "$(id -u)" >>"$TEST_HOOK_LOG" -sudo /usr/bin/install -o 0 -g 0 -m 0600 "$HOME/payload" "$TEST_ROOT_VICTIM" 2>/dev/null || true -"$HOME/launch-persistent-attack" "$TEST_PERSISTENT_VICTIM" "$TEST_PERSISTENT_PID" -HOOK - cat >"$test_home/.config/omarchy/hooks/$hook_name.d/10-attack" <<'HOOK' -#!/bin/bash -printf 'directory:%s\n' "$(id -u)" >>"$TEST_HOOK_LOG" -sudo /usr/bin/install -o 0 -g 0 -m 0600 "$HOME/payload" "$TEST_ROOT_DIR_VICTIM" 2>/dev/null || true -HOOK - chown -R 1000:1000 "$test_home/.config/omarchy/hooks/$hook_name" \ - "$test_home/.config/omarchy/hooks/$hook_name.d" - chmod 0700 "$test_home/.config/omarchy/hooks/$hook_name" \ - "$test_home/.config/omarchy/hooks/$hook_name.d/10-attack" -} - -reset_case() { - local pid_file - for pid_file in "$test_home"/*.pid; do - if [[ -s $pid_file ]]; then - persistent_pids+=("$(<"$pid_file")") - kill "$(<"$pid_file")" 2>/dev/null || true - fi - done - rm -f "$test_home"/*.pid "$token" "$root_dir"/* - : >"$event_log" - setpriv --reuid 1000 --regid 1000 --clear-groups /usr/bin/truncate -s 0 "$hook_log" -} - -run_as_user() { - setpriv --reuid 1000 --regid 1000 --clear-groups \ - env HOME="$test_home" PATH="$stub_bin:/usr/bin:/bin" OMARCHY_PATH="$ROOT" \ - TEST_ROOT="$ROOT" TEST_SUDO_TOKEN="$token" TEST_SUDO_EVENT_LOG="$event_log" \ - TEST_HOOK_LOG="$hook_log" "$@" -} - -authenticate_for_test() { - TEST_SUDO_TOKEN="$token" TEST_SUDO_EVENT_LOG="$event_log" \ - /usr/bin/sudo --authenticate-for-test -} - -wait_for_persistent_attempts() { - local pid_file="$1" - local pid="" - for (( attempt = 0; attempt < 100; attempt++ )); do - [[ -s $pid_file ]] && break - sleep 0.01 - done - [[ -s $pid_file ]] || fail "detached hook child did not start" - pid=$(<"$pid_file") - persistent_pids+=("$pid") - sleep 0.2 -} - -assert_hook_sandboxed() { - local direct_victim="$1" - local directory_victim="$2" - local persistent_victim="$3" - - [[ ! -e $direct_victim && ! -e $directory_victim && ! -e $persistent_victim ]] || - fail "hook code reused an Omarchy sudo credential" - grep -qxF 'file:1000' "$hook_log" || fail "the regular hook did not run as the desktop user" - grep -qxF 'directory:1000' "$hook_log" || fail "the hook-directory entry did not run as the desktop user" - [[ ! -e $token ]] || fail "the workflow left its modeled sudo credential live" -} - -write_attack_hook post-update -update_victim="$root_dir/80-update-hook.rules" -update_dir_victim="$root_dir/81-update-hook-dir.rules" -update_persistent_victim="$root_dir/82-update-hook-child.rules" -mise_victim="$root_dir/83-mise-child.rules" -reset_case -set +e -run_as_user env PATH="$evil_update_bin:$stub_bin:/usr/bin:/bin" OMARCHY_PATH="$evil_update_root" \ - TEST_EVIL_UPDATE_MARKER="$evil_update_marker" \ - TEST_ROOT_VICTIM="$update_victim" TEST_ROOT_DIR_VICTIM="$update_dir_victim" \ - TEST_PERSISTENT_VICTIM="$update_persistent_victim" TEST_PERSISTENT_PID="$test_home/update.pid" \ - TEST_MISE_VICTIM="$mise_victim" TEST_MISE_PID="$test_home/mise.pid" \ - OMARCHY_UPDATE_LOGGED=1 "$ROOT/bin/omarchy-update" -y \ - >"$test_tmp/update.out" 2>"$test_tmp/update.err" -status=$? -set -e -(( status == 0 )) || fail "isolated unattended update failed" "$(<"$test_tmp/update.err")" -wait_for_persistent_attempts "$test_home/update.pid" -wait_for_persistent_attempts "$test_home/mise.pid" -assert_hook_sandboxed "$update_victim" "$update_dir_victim" "$update_persistent_victim" -[[ ! -e $mise_victim ]] || fail "detached mise code observed a later update authorization" -[[ ! -e $evil_update_marker ]] || fail "update trusted an inherited PATH or OMARCHY_PATH override" -grep -qxF 'restart:--services-only' "$hook_log" || fail "privileged restart phase did not run before user code" -grep -qxF 'restart:--reboot-only' "$hook_log" || fail "reboot-only phase did not run after user code" -pass "update leaves no later sudo authentication for mise or persistent hook children" - -# OM-SEC-14 ends at the final cold hook boundary. Later sections exercise -# separate migration, restart-marker, channel, and installer findings in their -# own PRs. -exit 0 - -# Exercise the real migration dispatcher separately from PATH spoofing. An old -# update inherited the evil root here and ran its migration with the live -# system-package credential; the fixed update exports the authorized root. -evil_migration_victim="$root_dir/90-evil-migration.rules" -reset_case -set +e -run_as_user env OMARCHY_PATH="$evil_update_root" TEST_REAL_MIGRATE=1 \ - TEST_EVIL_UPDATE_MARKER="$evil_update_marker" TEST_EVIL_MIGRATION_VICTIM="$evil_migration_victim" \ - TEST_ROOT_VICTIM="$update_victim" TEST_ROOT_DIR_VICTIM="$update_dir_victim" \ - TEST_PERSISTENT_VICTIM="$update_persistent_victim" TEST_PERSISTENT_PID="$test_home/update.pid" \ - TEST_MISE_VICTIM="$mise_victim" TEST_MISE_PID="$test_home/mise.pid" \ - OMARCHY_MIGRATION_STATE="$test_home/migration-state" OMARCHY_UPDATE_LOGGED=1 \ - "$ROOT/bin/omarchy-update" -y >"$test_tmp/update-root-spoof.out" 2>"$test_tmp/update-root-spoof.err" -status=$? -set -e -(( status == 0 )) || fail "authorized-root update with real migration dispatcher failed" -[[ ! -e $evil_update_marker && ! -e $evil_migration_victim ]] || - fail "update dispatched a migration from inherited OMARCHY_PATH" -pass "update rejects inherited OMARCHY_PATH for real migration dispatch" -# The login-notification workflow invokes omarchy-migrate directly, outside an -# update that already normalized OMARCHY_PATH. It must independently reject an -# inherited attacker tree rather than running the migration placed there. -reset_case -set +e -run_as_user env OMARCHY_PATH="$evil_update_root" \ - TEST_EVIL_UPDATE_MARKER="$evil_update_marker" TEST_EVIL_MIGRATION_VICTIM="$evil_migration_victim" \ - OMARCHY_MIGRATION_STATE="$test_home/direct-migration-state" \ - "$ROOT/bin/omarchy-migrate" >"$test_tmp/direct-migrate.out" 2>"$test_tmp/direct-migrate.err" -status=$? -set -e -(( status == 0 )) || fail "direct authorized migration dispatch failed" -[[ ! -e $evil_update_marker && ! -e $evil_migration_victim ]] || - fail "direct migration dispatch trusted inherited OMARCHY_PATH" -pass "direct migration dispatch derives its source from root-owned configuration" - -# Reproduce the real historical ordering that exposed the remaining gap: the -# mise-wrapper migration can execute user tooling at 1784909971, while the -# 1784914435 migration invokes sudo later. A following migration also invokes -# the real absolute-path package helper, which cannot be protected by PATH -# alone. Every later authorization must inherit the exported no-update policy. -mkdir -p "$test_tmp/migrations" "$test_home/.local/bin" -chmod 0755 "$test_tmp/migrations" -cp "$ROOT/migrations/1784909971.sh" "$test_tmp/migrations/1784909971.sh" -cp "$ROOT/migrations/1784914435.sh" "$test_tmp/migrations/1784914435.sh" -cat >"$test_tmp/migrations/1784914436.sh" <<'STUB' -#!/bin/bash -/usr/bin/omarchy-pkg-add migration-security-fixture -STUB -chmod 0644 "$test_tmp/migrations/1784909971.sh" "$test_tmp/migrations/1784914435.sh" \ - "$test_tmp/migrations/1784914436.sh" -cat >"$test_home/.local/bin/legacy-mise-wrapper" <<'STUB' -#!/bin/bash -mise use -g "github:attacker/tool" -exec "attacker-tool" "$@" -STUB -cat >"$stub_bin/omarchy-mise-install" <<'STUB' -#!/bin/bash -"$HOME/launch-persistent-attack" "$TEST_MIGRATION_VICTIM" "$TEST_MIGRATION_PID" -STUB -cat >"$stub_bin/nmcli" <<'STUB' -#!/bin/bash -printf '%s\n' "$(id -u)" >"$TEST_PRIV_MIGRATION_MARKER" -STUB -cat >"$stub_bin/omarchy-notification-dismiss" <<'STUB' -#!/bin/bash -exit 0 -STUB -chmod 0755 "$stub_bin/omarchy-mise-install" "$stub_bin/nmcli" \ - "$stub_bin/omarchy-notification-dismiss" "$test_home/.local/bin/legacy-mise-wrapper" -chown -R 1000:1000 "$test_home/.local" -cat >"$stub_bin/omarchy-pkg-missing" <<'STUB' -#!/bin/bash -exit 0 -STUB -chmod 0755 "$stub_bin/omarchy-pkg-missing" -mount --bind "$ROOT/bin/omarchy-pkg-add" /usr/bin/omarchy-pkg-add -mount --bind "$stub_bin/omarchy-pkg-missing" /usr/bin/omarchy-pkg-missing -migration_pkg_paths_bound=1 -migration_victim="$root_dir/95-migration-child.rules" -migration_marker="$root_dir/96-privileged-migration-ran" -reset_case -set +e -run_as_user env OMARCHY_PATH="$evil_update_root" \ - TEST_MIGRATION_VICTIM="$migration_victim" TEST_MIGRATION_PID="$test_home/migration.pid" \ - TEST_PRIV_MIGRATION_MARKER="$migration_marker" TEST_PACMAN_DELAY=0.2 \ - OMARCHY_MIGRATION_STATE="$test_home/mixed-migration-state" \ - "$ROOT/bin/omarchy-migrate" >"$test_tmp/mixed-migrate.out" 2>"$test_tmp/mixed-migrate.err" -status=$? -set -e -(( status == 0 )) || fail "real mixed-trust migration sequence failed" "$(<"$test_tmp/mixed-migrate.err")" -wait_for_persistent_attempts "$test_home/migration.pid" -[[ -f $migration_marker && $(<"$migration_marker") == 0 ]] || fail "later privileged migration did not run as root" -[[ ! -e $migration_victim && ! -e $token ]] || fail "mise migration child reused a later migration authorization" -(( $(grep -c '^grant-no-update$' "$event_log") >= 2 )) || - fail "direct package-helper migration did not inherit the no-update policy" -pass "real mise-before-sudo and absolute package-helper migrations publish no reusable timestamp" -umount /usr/bin/omarchy-pkg-missing -umount /usr/bin/omarchy-pkg-add -migration_pkg_paths_bound=0 - -# Bash can import both BASH_ENV startup code and exported functions before an -# ordinary script body. An exported sudo function used to bypass the PATH -# wrapper in a later helper, publishing a global token to a BASH_ENV child that -# had started before migration invalidation. Exercise both injection channels -# through a normal-shebang child of the privileged migration shell. -cat >"$test_tmp/migrations/9999999998.sh" <<'STUB' -#!/bin/bash -"$HOME/launch-persistent-attack" "$TEST_BASH_STARTUP_VICTIM" "$TEST_BASH_STARTUP_PID" -omarchy-exported-function-auth -STUB -cat >"$stub_bin/omarchy-exported-function-auth" <<'STUB' -#!/bin/bash -sudo --authenticate-for-test -STUB -cat >"$test_home/bash-env-attack" <<'STUB' -#!/bin/bash -if [[ ! -e $TEST_BASH_ENV_MARKER ]]; then - /usr/bin/touch "$TEST_BASH_ENV_MARKER" - "$HOME/launch-persistent-attack" "$TEST_BASH_ENV_VICTIM" "$TEST_BASH_ENV_PID" -fi -STUB -chmod 0755 "$test_tmp/migrations/9999999998.sh" "$stub_bin/omarchy-exported-function-auth" -chown 1000:1000 "$test_home/bash-env-attack" -chmod 0600 "$test_home/bash-env-attack" -bash_startup_victim="$root_dir/99-exported-function-child.rules" -bash_env_victim="$root_dir/100-bash-env-child.rules" -bash_env_marker="$test_home/bash-env-ran" -reset_case -set +e -run_as_user env \ - 'BASH_FUNC_sudo%%=() { /usr/bin/sudo "$@"; }' \ - TEST_MULTILINE_ENV=$'value\nBASH_FUNC_fake%%=not-an-environment-record' \ - BASH_ENV="$test_home/bash-env-attack" \ - TEST_BASH_ENV_MARKER="$bash_env_marker" \ - TEST_BASH_ENV_VICTIM="$bash_env_victim" TEST_BASH_ENV_PID="$test_home/bash-env.pid" \ - TEST_BASH_STARTUP_VICTIM="$bash_startup_victim" TEST_BASH_STARTUP_PID="$test_home/bash-startup.pid" \ - OMARCHY_MIGRATION_STATE="$test_home/bash-startup-migration-state" \ - "$ROOT/bin/omarchy-migrate" >"$test_tmp/bash-startup.out" 2>"$test_tmp/bash-startup.err" -status=$? -set -e -(( status == 0 )) || fail "migration rejected a sanitized Bash startup environment" "$(<"$test_tmp/bash-startup.err")" -wait_for_persistent_attempts "$test_home/bash-startup.pid" -sleep 0.2 -[[ ! -e $bash_env_marker && ! -e $bash_env_victim ]] || - fail "BASH_ENV ran before or beneath the migration security boundary" -[[ ! -e $bash_startup_victim && ! -e $token ]] || - fail "an exported sudo function published a reusable migration credential" -grep -q '^grant-no-update$' "$event_log" || fail "sanitized helper did not use sudo --no-update" -grep -qxF 'exec /usr/bin/sudo -N -- "$@"' "$ROOT/default/omarchy/sudo-no-update/sudo" || - fail "no-update sudo wrapper omitted the option terminator" -pass "Bash startup injection cannot bypass the no-update sudo boundary" +reset_boundary +export SUDO_TEST_SIGNAL_STEP=omarchy-hook +if run_update -y; then fail "interrupted update must fail"; fi +assert_boundary_cold "interrupted update" +pass "update revokes credentials on TERM" + +reset_boundary +export SUDO_TEST_REVOKE_FAIL=1 +if run_update -y; then fail "failed initial revocation must fail the update"; fi +if grep -q '^step:' "$SUDO_TEST_LOG"; then fail "failed revocation must precede update work"; fi +pass "a failed cold start prevents update work" + +reset_boundary +export SUDO_TEST_UNSUPPORTED=1 +if run_update -y; then fail "unsupported sudo must prevent mixed-trust work"; fi +assert_boundary_cold "unsupported sudo" +pass "unsupported sudo fails without running update steps" + +for mode in normal defer-hook run-deferred; do + reset_boundary + "$SUDO_TEST_ROOT/bin/omarchy-refresh-pacman" stable "$mode" >"$boundary_tmp/output" 2>&1 || fail "refresh $mode failed" "$(<"$boundary_tmp/output")" + assert_boundary_cold "refresh $mode" + python3 - "$SUDO_TEST_LOG" "$mode" <<'PY' +import sys +s=open(sys.argv[1]).read().splitlines();mode=sys.argv[2] +hooks=[i for i,l in enumerate(s) if l.startswith('step:omarchy-hook')] +priv=[i for i,l in enumerate(s) if l.startswith('sudo -N ')] +assert bool(hooks)==(mode!='defer-hook'), s +assert bool(priv)==(mode!='run-deferred'), s +if hooks: assert not any(i>hooks[0] for i in priv),s +PY + pass "refresh $mode preserves the final cold hook boundary" +done -# Invoking a mixed-trust entrypoint with an ordinary explicit Bash bypasses its -# shebang. A BASH_ENV can erase its own environment record and retain a DEBUG -# trap, so environment-record cleanup alone is not a sufficient startup gate. -# The exact interpreter argv/privileged-mode check must reject this process -# before update authentication, leaving even its already-detached child cold. -cat >"$test_home/self-erasing-bash-env" <<'STUB' -#!/bin/bash -unset BASH_ENV ENV -trap ' - if [[ ! -e $TEST_DEBUG_TRAP_MARKER ]]; then - /usr/bin/touch "$TEST_DEBUG_TRAP_MARKER" - "$HOME/launch-persistent-attack" "$TEST_DEBUG_TRAP_VICTIM" "$TEST_DEBUG_TRAP_PID" - fi -' DEBUG -STUB -chown 1000:1000 "$test_home/self-erasing-bash-env" -chmod 0600 "$test_home/self-erasing-bash-env" -debug_trap_marker="$test_home/debug-trap-ran" -debug_trap_victim="$root_dir/101-debug-trap-child.rules" -reset_case -set +e -run_as_user env BASH_ENV="$test_home/self-erasing-bash-env" \ - TEST_DEBUG_TRAP_MARKER="$debug_trap_marker" TEST_DEBUG_TRAP_VICTIM="$debug_trap_victim" \ - TEST_DEBUG_TRAP_PID="$test_home/debug-trap.pid" OMARCHY_UPDATE_LOGGED=1 \ - /usr/bin/bash "$ROOT/bin/omarchy-update" -y \ - >"$test_tmp/unsafe-bash.out" 2>"$test_tmp/unsafe-bash.err" -status=$? -set -e -(( status == 126 )) || fail "update did not reject an unsafe explicit Bash interpreter" -[[ -e $debug_trap_marker ]] || fail "self-erasing BASH_ENV regression did not install its DEBUG trap" -wait_for_persistent_attempts "$test_home/debug-trap.pid" -[[ ! -e $debug_trap_victim && ! -e $token ]] || - fail "unsafe Bash startup reached update authentication" -! grep -qE '^(authenticate|authenticate-command|grant|grant-no-update)$' "$event_log" || - fail "unsafe Bash startup reached privileged update work" -grep -q 'unsafe Bash startup' "$test_tmp/unsafe-bash.err" || - fail "unsafe Bash startup rejection lacked a diagnostic" -pass "self-erasing BASH_ENV and DEBUG traps cannot cross the interpreter gate" +for step in pacman omarchy-hook; do + reset_boundary + export SUDO_TEST_FAIL_STEP=$step + if "$SUDO_TEST_ROOT/bin/omarchy-refresh-pacman" stable >"$boundary_tmp/output" 2>&1; then fail "refresh must propagate $step failure"; fi + assert_boundary_cold "failed refresh $step" + pass "refresh revokes after $step failure" +done -# Model a hostile yay configuration that selects absolute /usr/bin/sudo and a -# refresh loop. The real AUR helper must override both on its command line, so -# even a migration child already polling the global token sees no credential. -cat >"$stub_bin/omarchy-pkg-aur-accessible" <<'STUB' -#!/bin/bash -exit 0 -STUB -cat >"$stub_bin/yay" <<'STUB' -#!/bin/bash -sudo_command=/usr/bin/sudo -sudoflags="" -sudoloop=true -while (($#)); do - case "$1" in - --sudo) - sudo_command="$2" - shift 2 - ;; - --sudoloop=false) - sudoloop=false - shift - ;; - --sudoflags=-N) - sudoflags=-N - shift - ;; - *) - shift - ;; +# The wrapper must preserve sudo's own option parser, including validation and +# explicit --, while standalone timestamp maintenance cannot be combined with N. +for args in '-v' '-n /usr/bin/true' '--user test -- /usr/bin/true' '-- /usr/bin/true' '-k' '-K'; do + reset_boundary + "$SUDO_TEST_ROOT/default/omarchy/sudo-no-update/sudo" $args + case "$args" in + -k|-K) expected="sudo $args" ;; + *) expected="sudo -N $args" ;; esac + [[ $(<"$SUDO_TEST_LOG") == "$expected" ]] || fail "wrapper changed options: $args" "$(<"$SUDO_TEST_LOG")" + [[ ! -e $SUDO_TEST_CACHE ]] || fail "wrapper refreshed credentials" + pass "sudo wrapper preserves $args" done -printf 'sudo=%s sudoflags=%s sudoloop=%s\n' "$sudo_command" "$sudoflags" "$sudoloop" >"$TEST_YAY_LOG" -"$sudo_command" $sudoflags --authenticate-for-test -STUB -chmod 0755 "$stub_bin/omarchy-pkg-aur-accessible" "$stub_bin/yay" -mount --bind "$stub_bin/omarchy-pkg-aur-accessible" /usr/bin/omarchy-pkg-aur-accessible -mount --bind "$stub_bin/yay" /usr/bin/yay -aur_paths_bound=1 -yay_victim="$root_dir/97-yay-override-child.rules" -reset_case -run_as_user env TEST_YAY_LOG="$test_home/yay.log" \ - "$test_home/launch-persistent-attack" "$yay_victim" "$test_home/yay-child.pid" -wait_for_persistent_attempts "$test_home/yay-child.pid" -run_as_user env OMARCHY_PATH="$test_tmp" OMARCHY_SUDO_NO_UPDATE=1 TEST_YAY_LOG="$test_home/yay.log" \ - "$ROOT/bin/omarchy-update-aur-pkgs" >"$test_tmp/yay.out" 2>"$test_tmp/yay.err" -sleep 0.2 -grep -qxF "sudo=/usr/bin/sudo sudoflags=-N sudoloop=false" "$test_home/yay.log" || - fail "AUR update did not override hostile yay sudo settings" -[[ ! -e $yay_victim && ! -e $token ]] || fail "hostile yay sudo configuration published a reusable timestamp" -pass "AUR updates force no-update sudo and disable yay's credential loop" - -# A pre-existing credential and skipped package paths exercise the interactive -# branch independently of authority acquired by update helpers. -reset_case -authenticate_for_test -set +e -run_as_user env TEST_SKIP_UPDATE_AUTH=1 TEST_SKIP_LATE_AUTH=1 \ - TEST_ROOT_VICTIM="$update_victim" TEST_ROOT_DIR_VICTIM="$update_dir_victim" \ - TEST_PERSISTENT_VICTIM="$update_persistent_victim" TEST_PERSISTENT_PID="$test_home/update.pid" \ - TEST_MISE_VICTIM="$mise_victim" TEST_MISE_PID="$test_home/mise.pid" \ - OMARCHY_UPDATE_LOGGED=1 "$ROOT/bin/omarchy-update" \ - >"$test_tmp/update-interactive.out" 2>"$test_tmp/update-interactive.err" -status=$? -set -e -(( status == 0 )) || fail "isolated interactive update failed" -wait_for_persistent_attempts "$test_home/update.pid" -assert_hook_sandboxed "$update_victim" "$update_dir_victim" "$update_persistent_victim" -pass "interactive update invalidates a pre-existing credential before user code" -for failing_stage in migration signal; do - reset_case - set +e - run_as_user env TEST_FAILING_STAGE="$failing_stage" TEST_SKIP_LATE_AUTH=1 \ - TEST_ROOT_VICTIM="$update_victim" TEST_ROOT_DIR_VICTIM="$update_dir_victim" \ - TEST_PERSISTENT_VICTIM="$update_persistent_victim" TEST_PERSISTENT_PID="$test_home/update.pid" \ - TEST_MISE_VICTIM="$mise_victim" TEST_MISE_PID="$test_home/mise.pid" \ - OMARCHY_UPDATE_LOGGED=1 "$ROOT/bin/omarchy-update" -y \ - >"$test_tmp/update-$failing_stage.out" 2>"$test_tmp/update-$failing_stage.err" - status=$? - set -e - (( status != 0 )) || fail "update $failing_stage case unexpectedly succeeded" - [[ ! -e $token ]] || fail "update $failing_stage exit left its credential live" - [[ ! -s $hook_log ]] || fail "update $failing_stage case reached user-controlled stages" +for script in bin/omarchy-update bin/omarchy-refresh-pacman default/omarchy/sudo-no-update/sudo; do + reset_boundary + if /usr/bin/bash "$SUDO_TEST_ROOT/$script" -p >"$boundary_tmp/output" 2>&1; then fail "$script accepted an ordinary Bash launch"; fi + [[ ! -s $SUDO_TEST_LOG ]] || fail "$script reached sudo through an invalid interpreter" + pass "$script rejects a decoy privileged-mode argument" done -pass "failed and signaled updates invalidate credentials before user code" - -reset_case -set +e -run_as_user env TEST_SUDO_NO_N=1 OMARCHY_UPDATE_LOGGED=1 \ - "$ROOT/bin/omarchy-update" -y >"$test_tmp/no-update-unsupported.out" 2>"$test_tmp/no-update-unsupported.err" -status=$? -set -e -(( status != 0 )) || fail "update accepted sudo without --no-update support" -! grep -qE '^(authenticate|grant)' "$event_log" || fail "unsupported sudo reached privileged update work" -grep -q 'does not support --no-update' "$test_tmp/no-update-unsupported.err" || - fail "unsupported sudo failure did not explain the missing security primitive" -pass "update fails closed before privileged work when sudo lacks --no-update" - -# The config parser is the authority for all three scoped commands. Exercise a -# different unsafe shape through each copy before restoring the valid config. -chmod 0666 /etc/omarchy.conf -if run_as_user env OMARCHY_UPDATE_LOGGED=1 "$ROOT/bin/omarchy-update" -y \ - >"$test_tmp/untrusted-update.out" 2>"$test_tmp/untrusted-update.err"; then - fail "update accepted a writable source-root authorization" -fi - -/usr/bin/mv /etc/omarchy.conf /etc/omarchy.real -/usr/bin/ln -s /etc/omarchy.real /etc/omarchy.conf -if run_as_user "$ROOT/bin/omarchy-refresh-pacman" stable \ - >"$test_tmp/untrusted-refresh.out" 2>"$test_tmp/untrusted-refresh.err"; then - fail "pacman refresh accepted a symlinked source-root authorization" -fi -/usr/bin/rm /etc/omarchy.conf -/usr/bin/mv /etc/omarchy.real /etc/omarchy.conf - -chown 1000:1000 /etc/omarchy.conf -if run_as_user "$ROOT/bin/omarchy-update-restart" --services-only \ - >"$test_tmp/untrusted-restart.out" 2>"$test_tmp/untrusted-restart.err"; then - fail "update restart accepted a non-root source-root authorization" -fi -write_authorized_source_root "$test_tmp" -pass "update commands reject writable, symlinked, and non-root source-root authorization" - -# A root-owned config may authorize a development checkout, but not a tree -# another local account (or every account) can rewrite. Exercise both unsafe -# directory-chain shapes before restoring the valid authorized fixture. -writable_source_root="$test_tmp/writable-source-root" -foreign_source_root="$test_tmp/foreign-source-root" -mkdir -p "$writable_source_root" "$foreign_source_root" -chown 1000:1000 "$writable_source_root" -chmod 0777 "$writable_source_root" -chown 1001:1001 "$foreign_source_root" -chmod 0755 "$foreign_source_root" - -write_authorized_source_root "$writable_source_root" -if run_as_user env OMARCHY_UPDATE_LOGGED=1 "$ROOT/bin/omarchy-update" -y \ - >"$test_tmp/writable-source.out" 2>"$test_tmp/writable-source.err"; then - fail "update accepted a group/world-writable authorized source tree" -fi -grep -q 'untrusted Omarchy source root' "$test_tmp/writable-source.err" || - fail "writable source-root rejection happened after the trust parser" - -write_authorized_source_root "$foreign_source_root" -if run_as_user "$ROOT/bin/omarchy-migrate" --pending \ - >"$test_tmp/foreign-source.out" 2>"$test_tmp/foreign-source.err"; then - fail "migration runner accepted a foreign-owned authorized source tree" -fi -grep -q 'untrusted Omarchy source root' "$test_tmp/foreign-source.err" || - fail "foreign source-root rejection happened after the trust parser" -write_authorized_source_root "$test_tmp" -pass "authorized source roots reject foreign-owned and group/world-writable path components" - -# The restart marker is attacker-writable, but its value is now an allowlisted -# selector into the configured Omarchy tree rather than a command resolved by -# PATH. A dev-linked tree is honored only through root-owned /etc/omarchy.conf. -reset_case -restart_home="$test_tmp/restart-home" -restart_log="$test_tmp/restart.log" -mkdir -p "$restart_home/.local/state/omarchy" -touch "$restart_log" -chown -R 1000:1000 "$restart_home" -chown 1000:1000 "$restart_log" -touch "$restart_home/.local/state/omarchy/restart-btop-required" \ - "$restart_home/.local/state/omarchy/restart-evil-required" -chown 1000:1000 "$restart_home/.local/state/omarchy"/* -cat >"$stub_bin/omarchy-restart-btop" <<'STUB' -#!/bin/bash -echo trusted-btop >>"$TEST_RESTART_LOG" -STUB -cat >"$stub_bin/omarchy-restart-shell" <<'STUB' -#!/bin/bash -echo trusted-shell >>"$TEST_RESTART_LOG" -STUB -evil_bin="$test_home/evil-bin" -mkdir -p "$evil_bin" -cat >"$evil_bin/omarchy-restart-btop" <<'STUB' -#!/bin/bash -echo path-btop >>"$TEST_RESTART_LOG" -STUB -cat >"$evil_bin/omarchy-restart-evil" <<'STUB' -#!/bin/bash -echo path-evil >>"$TEST_RESTART_LOG" -sudo /usr/bin/true -STUB -chown -R 1000:1000 "$evil_bin" -chmod 0755 "$stub_bin/omarchy-restart-btop" "$stub_bin/omarchy-restart-shell" "$evil_bin"/* -run_as_user env HOME="$restart_home" PATH="$evil_bin:$stub_bin:/usr/bin:/bin" \ - OMARCHY_PATH="$test_home/evil-root" TEST_RESTART_LOG="$restart_log" \ - "$ROOT/bin/omarchy-update-restart" --services-only >"$test_tmp/restart.out" 2>"$test_tmp/restart.err" -grep -qxF trusted-btop "$restart_log" || fail "allowed marker did not use the configured Omarchy command" -grep -qxF trusted-shell "$restart_log" || fail "shell restart did not use the configured Omarchy command" -! grep -q '^path-' "$restart_log" || fail "restart marker resolved an attacker PATH command" -[[ ! -e $restart_home/.local/state/omarchy/restart-evil-required ]] || fail "unsupported restart marker was retained" -pass "restart markers use an allowlist and fixed configured command paths" - -special_root="$test_tmp/dev root\\checkout\$cash" -special_home="$test_tmp/special-home" -special_log="$test_tmp/special.log" -mkdir -p "$special_root/bin" "$special_home/.local/state/omarchy" -touch "$special_home/.local/state/omarchy/restart-btop-required" "$special_log" -chown -R 1000:1000 "$special_home" "$special_log" -cat >"$special_root/bin/omarchy-restart-btop" <<'STUB' -#!/bin/bash -echo special-btop >>"$TEST_RESTART_LOG" -STUB -cat >"$special_root/bin/omarchy-restart-shell" <<'STUB' -#!/bin/bash -exit 0 -STUB -chmod 0755 "$special_root/bin"/* -chown -R 1000:1000 "$special_root" -write_authorized_source_root "$special_root" -run_as_user env HOME="$special_home" TEST_RESTART_LOG="$special_log" \ - "$ROOT/bin/omarchy-update-restart" --services-only \ - >"$test_tmp/special-root.out" 2>"$test_tmp/special-root.err" -grep -qxF special-btop "$special_log" || fail "authorized quoted dev root did not dispatch its restart helper" -write_authorized_source_root "$test_tmp" -pass "source-root authorization decodes spaces, backslashes, and dollar signs" - -# The legacy pre-refresh hook now runs only after pacman; a detached child can -# no longer wait for a later authentication in either tty or global mode. -write_attack_hook pre-refresh-pacman -refresh_victim="$root_dir/84-refresh-hook.rules" -refresh_dir_victim="$root_dir/85-refresh-hook-dir.rules" -refresh_persistent_victim="$root_dir/86-refresh-hook-child.rules" -reset_case -authenticate_for_test -cat >"$evil_bin/cp" <<'STUB' -#!/bin/bash -touch "$TEST_EVIL_REFRESH_MARKER" -exit 97 -STUB -chmod 0755 "$evil_bin/cp" -evil_refresh_marker="$test_home/evil-refresh-ran" -set +e -run_as_user env PATH="$evil_bin:$stub_bin:/usr/bin:/bin" OMARCHY_PATH="$evil_update_root" \ - TEST_EVIL_REFRESH_MARKER="$evil_refresh_marker" \ - TEST_ROOT_VICTIM="$refresh_victim" TEST_ROOT_DIR_VICTIM="$refresh_dir_victim" \ - TEST_PERSISTENT_VICTIM="$refresh_persistent_victim" TEST_PERSISTENT_PID="$test_home/refresh.pid" \ - "$ROOT/bin/omarchy-refresh-pacman" stable >"$test_tmp/refresh.out" 2>"$test_tmp/refresh.err" -status=$? -set -e -(( status == 0 )) || fail "isolated pacman refresh failed" "$(<"$test_tmp/refresh.err")" -wait_for_persistent_attempts "$test_home/refresh.pid" -assert_hook_sandboxed "$refresh_victim" "$refresh_dir_victim" "$refresh_persistent_victim" -[[ ! -e $evil_refresh_marker ]] || fail "pacman refresh resolved cp through caller PATH" -/usr/bin/cmp -s "$test_tmp/default/pacman/pacman-stable.conf" /etc/pacman.conf || - fail "pacman refresh did not copy config from the authorized source root" -[[ ! -e $evil_refresh_marker ]] || fail "pacman refresh copied from inherited OMARCHY_PATH or PATH" -pass "pacman refresh runs its legacy hook only after all privileged work" - -reset_case -authenticate_for_test -set +e -run_as_user env TEST_PACMAN_STATUS=1 TEST_ROOT_VICTIM="$refresh_victim" \ - TEST_ROOT_DIR_VICTIM="$refresh_dir_victim" TEST_PERSISTENT_VICTIM="$refresh_persistent_victim" \ - TEST_PERSISTENT_PID="$test_home/refresh.pid" "$ROOT/bin/omarchy-refresh-pacman" stable \ - >"$test_tmp/refresh-fail.out" 2>"$test_tmp/refresh-fail.err" -status=$? -set -e -(( status != 0 )) || fail "failing pacman refresh unexpectedly succeeded" -[[ ! -e $token ]] || fail "failed pacman refresh left its credential live" -[[ ! -s $hook_log ]] || fail "failed pacman transaction reached the refresh hook" -pass "failed pacman refresh invalidates and does not run its hook" - -# Channel switching is a composite refresh caller: after refreshing it -# authenticates for the package swap and runs the full update. Exercise the -# real channel, refresh, update, and hook commands against the global-token -# model. A detached legacy refresh-hook child must not start until that entire -# chain has finished. -cat >"$test_home/.config/omarchy/hooks/post-update" <<'HOOK' -#!/bin/bash -printf 'post-update:%s\n' "$(id -u)" >>"$TEST_HOOK_LOG" -HOOK -chown 1000:1000 "$test_home/.config/omarchy/hooks/post-update" -chmod 0700 "$test_home/.config/omarchy/hooks/post-update" -channel_victim="$root_dir/91-channel-refresh-hook.rules" -channel_dir_victim="$root_dir/92-channel-refresh-dir.rules" -channel_persistent_victim="$root_dir/93-channel-refresh-child.rules" -channel_mise_victim="$root_dir/94-channel-mise-child.rules" -reset_case -set +e -evil_channel_helper_marker="$test_home/evil-channel-helper-ran" -evil_channel_helper_victim="$root_dir/98-channel-path-helper.rules" -run_as_user env PATH="$evil_update_bin:$stub_bin:/usr/bin:/bin" \ - TEST_EVIL_CHANNEL_HELPER_MARKER="$evil_channel_helper_marker" \ - TEST_EVIL_CHANNEL_VICTIM="$evil_channel_helper_victim" \ - TEST_ROOT_VICTIM="$channel_victim" TEST_ROOT_DIR_VICTIM="$channel_dir_victim" \ - TEST_PERSISTENT_VICTIM="$channel_persistent_victim" TEST_PERSISTENT_PID="$test_home/channel.pid" \ - TEST_MISE_VICTIM="$channel_mise_victim" TEST_MISE_PID="$test_home/channel-mise.pid" \ - OMARCHY_UPDATE_LOGGED=1 "$ROOT/bin/omarchy-channel-set" stable \ - >"$test_tmp/channel.out" 2>"$test_tmp/channel.err" -status=$? -set -e -(( status == 0 )) || fail "isolated channel switch failed" "$(<"$test_tmp/channel.err")" -wait_for_persistent_attempts "$test_home/channel.pid" -wait_for_persistent_attempts "$test_home/channel-mise.pid" -assert_hook_sandboxed "$channel_victim" "$channel_dir_victim" "$channel_persistent_victim" -[[ ! -e $channel_mise_victim ]] || fail "channel mise child reused a later refresh-hook credential" -[[ ! -e $evil_channel_helper_marker && ! -e $evil_channel_helper_victim ]] || - fail "channel switch resolved a post-pacman helper through caller PATH" -[[ $(grep -c '^file:1000$' "$hook_log") == 1 ]] || fail "channel switch did not run the deferred refresh hook exactly once" -pass "channel switching defers its refresh hook past every later authentication" - -cat >"$stub_bin/omarchy-launch-floating-terminal-with-presentation" <<'STUB' -#!/bin/bash -exec bash -c "$1" -STUB -cat >"$stub_bin/omarchy-pkg-add" <<'STUB' -#!/bin/bash -[[ ${OMARCHY_SUDO_NO_UPDATE:-0} == 1 ]] || exit 98 -/usr/bin/sudo -N -- /usr/bin/true -exit "${TEST_PKG_STATUS:-0}" -STUB -cat >"$stub_bin/omarchy-font-set" <<'STUB' -#!/bin/bash -exec bash "$TEST_ROOT/bin/omarchy-font-set" "$@" -STUB -cat >"$stub_bin/fc-list" <<'STUB' -#!/bin/bash -echo 'Example Family' -STUB -cat >"$stub_bin/omarchy-restart-shell" <<'STUB' -#!/bin/bash -exit 0 -STUB -cat >"$stub_bin/pgrep" <<'STUB' -#!/bin/bash -exit 1 -STUB -cat >"$stub_bin/sleep" <<'STUB' -#!/bin/bash -exit 0 -STUB -chmod 0755 "$stub_bin"/* -chmod 4755 "$stub_bin/sudo" -mount --bind "$stub_bin/omarchy-launch-floating-terminal-with-presentation" \ - /usr/bin/omarchy-launch-floating-terminal-with-presentation -mount --bind "$stub_bin/omarchy-pkg-add" /usr/bin/omarchy-pkg-add -mount --bind "$stub_bin/omarchy-font-set" /usr/bin/omarchy-font-set -font_paths_bound=1 - -write_attack_hook font-set -font_victim="$root_dir/87-font-hook.rules" -font_dir_victim="$root_dir/88-font-hook-dir.rules" -font_persistent_victim="$root_dir/89-font-hook-child.rules" -reset_case -set +e -run_as_user env TEST_ROOT_VICTIM="$font_victim" TEST_ROOT_DIR_VICTIM="$font_dir_victim" \ - TEST_PERSISTENT_VICTIM="$font_persistent_victim" TEST_PERSISTENT_PID="$test_home/font.pid" \ - "$ROOT/bin/omarchy-install-font" 'Example Font' example-font 'Example Family' \ - >"$test_tmp/font.out" 2>"$test_tmp/font.err" -status=$? -set -e -(( status == 0 )) || fail "isolated font install failed" "$(<"$test_tmp/font.err")" -wait_for_persistent_attempts "$test_home/font.pid" -assert_hook_sandboxed "$font_victim" "$font_dir_victim" "$font_persistent_victim" -pass "font installation invalidates before file, directory, and persistent hooks" -reset_case -set +e -run_as_user env TEST_PKG_STATUS=1 TEST_ROOT_VICTIM="$font_victim" \ - TEST_ROOT_DIR_VICTIM="$font_dir_victim" TEST_PERSISTENT_VICTIM="$font_persistent_victim" \ - TEST_PERSISTENT_PID="$test_home/font.pid" \ - "$ROOT/bin/omarchy-install-font" 'Example Font' example-font 'Example Family' \ - >"$test_tmp/font-fail.out" 2>"$test_tmp/font-fail.err" -status=$? -set -e -(( status != 0 )) || fail "failing font package installation unexpectedly succeeded" -[[ ! -e $token ]] || fail "failed font package installation left its credential live" -[[ ! -s $hook_log ]] || fail "failed font package installation reached the hook" -pass "failed font installation invalidates without running its hook" +reset_boundary +printf '%s\n' 'printf startup-ran >>"$SUDO_TEST_ROOT/startup-marker"' >"$boundary_tmp/startup" +BASH_ENV="$boundary_tmp/startup" ENV="$boundary_tmp/startup" run_update -y || fail "sanitized update failed" "$(<"$boundary_tmp/output")" +[[ ! -e $SUDO_TEST_ROOT/startup-marker ]] || fail "startup code leaked into an update helper" +pass "inherited startup files do not run in the updater or its child scripts" + +reset_boundary +function printf() { /usr/bin/touch "$SUDO_TEST_ROOT/function-marker"; } +export -f printf +run_update -y || fail "update failed with inherited function" "$(<"$boundary_tmp/output")" +unset -f printf +[[ ! -e $SUDO_TEST_ROOT/function-marker ]] || fail "an inherited function reached an update helper" +pass "exported functions do not reach update helper interpreters" diff --git a/test/shell.d/update-lock-test.sh b/test/shell.d/update-lock-test.sh index 6c65428dc899..7348848cf9b6 100644 --- a/test/shell.d/update-lock-test.sh +++ b/test/shell.d/update-lock-test.sh @@ -4,16 +4,31 @@ set -euo pipefail source "$(dirname "$0")/base-test.sh" -test_tmp=$(mktemp -d) -trap 'rm -rf "$test_tmp"' EXIT - -stub_bin="$test_tmp/bin" -test_home="$test_tmp/home" +source "$SHELL_TEST_DIR/fixtures/sudo-boundary-test.sh" +test_tmp="$boundary_tmp" +stub_bin="$SUDO_TEST_ROOT/bin" +test_home="$SUDO_TEST_HOME" runtime_dir="$test_tmp/runtime" -mkdir -p "$stub_bin" "$test_home" "$runtime_dir" +mkdir -p "$runtime_dir" +for command in omarchy-update omarchy-update-lock omarchy-update-stay-awake; do + rm -f "$SUDO_TEST_ROOT/bin/$command" + copy_boundary_file "bin/$command" +done +cat >"$SUDO_TEST_ROOT/mock/setpriv" <<'STUB' +#!/bin/bash +while [[ ${1:-} == --* ]]; do + case "$1" in + --reuid|--regid) shift 2 ;; + --clear-groups) shift ;; + *) exit 90 ;; + esac +done +exec "$@" +STUB +chmod +x "$SUDO_TEST_ROOT/mock/setpriv" run_with_lock_env() { - HOME="$test_home" \ + SUDO_TEST_HOME="$test_home" \ XDG_RUNTIME_DIR="$runtime_dir" \ XDG_STATE_HOME="$test_tmp/state" \ PATH="$stub_bin:$ROOT/bin:$PATH" \ @@ -24,6 +39,7 @@ write_stub() { local name="$1" local body="$2" + rm -f "$stub_bin/$name" cat >"$stub_bin/$name" <"$TEST_MARKER"; sleep 2; exit 0' -OMARCHY_UPDATE_LOGGED=1 TEST_MARKER="$update_snapshot_marker" run_with_lock_env "$ROOT/bin/omarchy-update" -y >"$test_tmp/update-first.out" 2>&1 & +OMARCHY_UPDATE_LOGGED=1 TEST_MARKER="$update_snapshot_marker" run_with_lock_env "$SUDO_TEST_ROOT/bin/omarchy-update" -y >"$test_tmp/update-first.out" 2>&1 & update_pid=$! for _ in {1..50}; do @@ -67,7 +85,7 @@ done [[ -f $update_snapshot_marker ]] || fail "first omarchy-update reached snapshot under lock" set +e -OMARCHY_UPDATE_LOGGED=1 TEST_MARKER="$test_tmp/update-second-snapshot-started" run_with_lock_env "$ROOT/bin/omarchy-update" -y >"$test_tmp/update-second.out" 2>&1 +OMARCHY_UPDATE_LOGGED=1 TEST_MARKER="$test_tmp/update-second-snapshot-started" run_with_lock_env "$SUDO_TEST_ROOT/bin/omarchy-update" -y >"$test_tmp/update-second.out" 2>&1 update_second_status=$? set -e @@ -85,11 +103,11 @@ pass "omarchy-update prevents overlapping top-level updates" inhibit_pid_file="$test_tmp/inhibit-pid" keyring_marker="$test_tmp/keyring-started" write_stub omarchy-snapshot 'exit 0' -write_stub systemd-inhibit 'echo "$$" >"$INHIBIT_PID_FILE"; exec sleep 30' +write_stub systemd-inhibit '[[ -z ${INHIBIT_PID_FILE:-} ]] || echo "$$" >"$INHIBIT_PID_FILE"; while [[ $1 == --* ]]; do shift; done; exec "$@"' write_stub omarchy-update-keyring 'echo started >"$TEST_MARKER"; sleep 3; exit 0' OMARCHY_UPDATE_LOGGED=1 TEST_MARKER="$keyring_marker" INHIBIT_PID_FILE="$inhibit_pid_file" \ - run_with_lock_env "$ROOT/bin/omarchy-update" -y >"$test_tmp/update-inhibit.out" 2>&1 & + run_with_lock_env "$SUDO_TEST_ROOT/bin/omarchy-update" -y >"$test_tmp/update-inhibit.out" 2>&1 & inhibit_update_pid=$! for _ in {1..100}; do @@ -123,11 +141,10 @@ if (( EUID != 0 )); then terminal_inhibit_pid_file="$test_tmp/terminal-inhibit-pid" write_stub sudo ' printf "%s\n" "$*" >>"$SUDO_LOG" -if [[ $1 == "-v" ]]; then - exit 0 -fi -exec "$@"' - write_stub pkexec 'touch "$PKEXEC_MARKER"; exec "$@"' +[[ $1 == "-N" && $2 == "-b" && $3 == "--" ]] || exit 90 +shift 3 +"$@" &' + write_stub pkexec '[[ -z ${PKEXEC_MARKER:-} ]] || touch "$PKEXEC_MARKER"; exec "$@"' # start leaves the inhibitor running on purpose, but script tears the pty down # the moment its command returns, which SIGHUPs that inhibitor before it can @@ -137,7 +154,7 @@ exec "$@"' #!/bin/bash omarchy-update-stay-awake start for _ in {1..200}; do - grep -q '^systemd-inhibit ' "$SUDO_LOG" && break + grep -q -- '^-N -b -- ' "$SUDO_LOG" && break sleep 0.05 done SH @@ -146,10 +163,10 @@ SH SUDO_LOG="$sudo_log" PKEXEC_MARKER="$pkexec_marker" INHIBIT_PID_FILE="$terminal_inhibit_pid_file" \ run_with_lock_env script -qefc "$terminal_driver" /dev/null >/dev/null - grep -qx -- '-v' "$sudo_log" || fail "terminal sleep inhibition validates sudo in the foreground" - grep -q '^systemd-inhibit ' "$sudo_log" || fail "terminal sleep inhibition runs through sudo" + grep -q -- '^-N -b -- ' "$sudo_log" || fail "terminal inhibition authenticates its background command without a reusable timestamp" + grep -q -- '^-N -b -- ' "$sudo_log" || fail "terminal sleep inhibition runs through sudo" [[ ! -e $pkexec_marker ]] || fail "terminal sleep inhibition does not use pkexec" - run_with_lock_env "$ROOT/bin/omarchy-update-stay-awake" stop + run_with_lock_env "$SUDO_TEST_ROOT/bin/omarchy-update-stay-awake" stop pass "terminal updates use sudo instead of Polkit for sleep inhibition" fi @@ -158,7 +175,7 @@ fi write_stub omarchy-snapshot 'exit 0' write_stub omarchy-update-keyring 'exit 0' write_stub omarchy-toggle-idle ' -state_file="$HOME/.local/state/omarchy/indicators/stay-awake" +state_file="$SUDO_TEST_HOME/.local/state/omarchy/indicators/stay-awake" case "$1" in stay-awake) mkdir -p "$(dirname "$state_file")" @@ -169,20 +186,20 @@ case "$1" in ;; esac' write_stub omarchy-update-restart ' -state_file="$HOME/.local/state/omarchy/indicators/stay-awake" -if [[ ${EXPECT_STAY_AWAKE:-0} == "1" ]]; then +state_file="$SUDO_TEST_HOME/.local/state/omarchy/indicators/stay-awake" +if [[ ${1:-} == "--services-only" || ${EXPECT_STAY_AWAKE:-0} == "1" ]]; then [[ -f $state_file ]] else [[ ! -f $state_file ]] fi' rm -f "$test_home/.local/state/omarchy/indicators/stay-awake" -OMARCHY_UPDATE_LOGGED=1 run_with_lock_env "$ROOT/bin/omarchy-update" -y +OMARCHY_UPDATE_LOGGED=1 run_with_lock_env "$SUDO_TEST_ROOT/bin/omarchy-update" -y [[ ! -f $test_home/.local/state/omarchy/indicators/stay-awake ]] || fail "update clears its Stay Awake state before restart handling" mkdir -p "$test_home/.local/state/omarchy/indicators" touch "$test_home/.local/state/omarchy/indicators/stay-awake" -OMARCHY_UPDATE_LOGGED=1 EXPECT_STAY_AWAKE=1 run_with_lock_env "$ROOT/bin/omarchy-update" -y +OMARCHY_UPDATE_LOGGED=1 EXPECT_STAY_AWAKE=1 run_with_lock_env "$SUDO_TEST_ROOT/bin/omarchy-update" -y [[ -f $test_home/.local/state/omarchy/indicators/stay-awake ]] || fail "update preserves pre-existing Stay Awake state" pass "omarchy-update restores only its own Stay Awake state before restart handling" @@ -194,7 +211,7 @@ mkdir -p "$stay_awake_helper_state" "$(dirname "$stay_awake_state")" printf '%s\n' "old-update-owner" >"$stay_awake_helper_state/idle-owner" printf '%s\n' "user-choice" >"$stay_awake_state" -run_with_lock_env "$ROOT/bin/omarchy-update-stay-awake" stop +run_with_lock_env "$SUDO_TEST_ROOT/bin/omarchy-update-stay-awake" stop [[ $(<"$stay_awake_state") == "user-choice" ]] || fail "stale update ownership does not remove a newer Stay Awake choice" pass "stale update ownership preserves a newer Stay Awake choice" @@ -206,7 +223,7 @@ unrelated_start_time=$(awk '{ print $22 }' "/proc/$unrelated_pid/stat") mkdir -p "$stay_awake_helper_state" printf '%s %s\n' "$unrelated_pid" "$((unrelated_start_time + 1))" >"$stay_awake_helper_state/inhibit-pid" -run_with_lock_env "$ROOT/bin/omarchy-update-stay-awake" stop +run_with_lock_env "$SUDO_TEST_ROOT/bin/omarchy-update-stay-awake" stop kill -0 "$unrelated_pid" 2>/dev/null || fail "stale inhibitor state does not terminate a reused PID" kill "$unrelated_pid" diff --git a/test/shell.d/update-restart-phases-test.sh b/test/shell.d/update-restart-phases-test.sh new file mode 100755 index 000000000000..baddde914898 --- /dev/null +++ b/test/shell.d/update-restart-phases-test.sh @@ -0,0 +1,39 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" +source "$SHELL_TEST_DIR/fixtures/sudo-boundary-test.sh" +rm "$SUDO_TEST_ROOT/bin/omarchy-update-restart" +copy_boundary_file bin/omarchy-update-restart +for step in omarchy-state omarchy-restart-sshd omarchy-restart-shell omarchy-system-reboot; do + ln -s test-step "$SUDO_TEST_ROOT/bin/$step" +done +cat >"$SUDO_TEST_ROOT/bin/gum" <<'STUB' +#!/bin/bash +printf 'prompt:%s\n' "$*" >>"$SUDO_TEST_LOG" +exit 1 +STUB +chmod +x "$SUDO_TEST_ROOT/bin/gum" +mkdir -p "$SUDO_TEST_HOME/.local/state/omarchy" +touch "$SUDO_TEST_HOME/.local/state/omarchy/reboot-required" "$SUDO_TEST_HOME/.local/state/omarchy/restart-sshd-required" + +for mode in --services-only --reboot-only; do + reset_boundary + PATH="$SUDO_TEST_ROOT/bin:$PATH" "$SUDO_TEST_ROOT/bin/omarchy-update-restart" "$mode" >"$boundary_tmp/output" 2>&1 + if [[ $mode == "--services-only" ]]; then + grep -q '^step:omarchy-restart-sshd ' "$SUDO_TEST_LOG" || fail "service phase did not restart a marked service" + grep -q '^step:omarchy-restart-shell ' "$SUDO_TEST_LOG" || fail "service phase did not restart the shell" + if grep -q '^prompt:' "$SUDO_TEST_LOG"; then fail "service phase offered a reboot before update cleanup"; fi + else + grep -q '^prompt:' "$SUDO_TEST_LOG" || fail "reboot phase did not offer the required reboot" + if grep -q '^step:omarchy-restart-' "$SUDO_TEST_LOG"; then fail "reboot phase performed later service work"; fi + fi + pass "restart $mode performs only its selected phase" +done +reset_boundary +OMARCHY_UPDATE_UNATTENDED=1 PATH="$SUDO_TEST_ROOT/bin:$PATH" "$SUDO_TEST_ROOT/bin/omarchy-update-restart" --reboot-only >"$boundary_tmp/output" 2>&1 +if grep -Eq "^(prompt:|step:omarchy-restart-|step:omarchy-system-reboot)" "$SUDO_TEST_LOG"; then + fail "unattended reboot phase prompted or performed service work" +fi +pass "unattended reboot phase reports a required reboot without prompting" diff --git a/test/shell.d/update-sequence-test.sh b/test/shell.d/update-sequence-test.sh index edac120937bc..994dc4932472 100755 --- a/test/shell.d/update-sequence-test.sh +++ b/test/shell.d/update-sequence-test.sh @@ -2,60 +2,11 @@ set -euo pipefail -source "$(dirname "$0")/base-test.sh" - -if [[ -z ${OMARCHY_UPDATE_SEQUENCE_NS:-} ]]; then - outer_uid=$(id -u) - outer_gid=$(id -g) - subuid=$(awk -F: -v user="$(id -un)" '$1 == user { print $2; exit }' /etc/subuid) - subgid=$(awk -F: -v group="$(id -gn)" '$1 == group { print $2; exit }' /etc/subgid) - if [[ -z $subuid || -z $subgid ]]; then - pass "no subordinate uid/gid range; skipping authorized update-sequence test" - exit 0 - fi - exec unshare --user --mount \ - --map-users "0:$outer_uid:1" --map-users "1:$subuid:65536" \ - --map-groups "0:$outer_gid:1" --map-groups "1:$subgid:65536" \ - env OMARCHY_UPDATE_SEQUENCE_NS=setup bash "$0" -elif [[ $OMARCHY_UPDATE_SEQUENCE_NS == setup ]]; then - mount -t tmpfs -o mode=0755 tmpfs /run - namespace_tmp=$(mktemp -d -p /run omarchy-update-sequence.XXXXXXXX) - chmod 0755 "$namespace_tmp" - mkdir -p "$namespace_tmp/default/omarchy/sudo-no-update" - cp "$ROOT/default/omarchy/sudo-no-update/sudo" "$namespace_tmp/default/omarchy/sudo-no-update/sudo" - chmod 0755 "$namespace_tmp/default/omarchy/sudo-no-update/sudo" - cat >"$namespace_tmp/fixed-sudo" <<'STUB' -#!/bin/bash -if [[ ${1:-} == "-h" ]]; then - echo 'usage: sudo [-ABbEHkNnPS] command' -fi -exit 0 -STUB - chmod 0755 "$namespace_tmp/fixed-sudo" - mount --bind "$namespace_tmp/fixed-sudo" /usr/bin/sudo - mount -t tmpfs -o mode=0755 tmpfs /etc - printf 'export OMARCHY_PATH="%s"\n' "$namespace_tmp" >/etc/omarchy.conf - chmod 0644 /etc/omarchy.conf - chown -R 1000:1000 "$namespace_tmp" - - set +e - setpriv --reuid 1000 --regid 1000 --clear-groups \ - env OMARCHY_UPDATE_SEQUENCE_NS=run OMARCHY_AUTHORIZED_TEST_ROOT="$namespace_tmp" bash "$0" - status=$? - set -e - - umount /usr/bin/sudo - umount /etc - rm -rf "$namespace_tmp" - umount /run - exit "$status" -fi - -test_tmp="$OMARCHY_AUTHORIZED_TEST_ROOT" -trap 'rm -rf "$test_tmp"/*' EXIT - -stub_bin="$test_tmp/bin" -mkdir -p "$stub_bin" +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" +source "$SHELL_TEST_DIR/fixtures/sudo-boundary-test.sh" +copy_boundary_file bin/omarchy-update +test_tmp="$boundary_tmp" +stub_bin="$SUDO_TEST_ROOT/bin" # Every step omarchy-update runs, recorded in order with the unattended flag it # was handed. One of them can be told to fail. @@ -80,6 +31,7 @@ steps=( ) for step in "${steps[@]}"; do + rm -f "$stub_bin/$step" cat >"$stub_bin/$step" <<'STUB' #!/bin/bash printf '%s unattended=%s\n' "${0##*/}" "${OMARCHY_UPDATE_UNATTENDED:-}" >>"$STEP_LOG" @@ -96,7 +48,7 @@ run_update() { FAILING_STEP="${FAILING_STEP:-}" \ OMARCHY_UPDATE_LOGGED=1 \ PATH="$stub_bin:$PATH" \ - "$ROOT/bin/omarchy-update" "$@" >"$test_tmp/out" 2>"$test_tmp/err" + "$SUDO_TEST_ROOT/bin/omarchy-update" "$@" >"$test_tmp/out" 2>"$test_tmp/err" } steps_run() { From c52381f09225e4a6956c272dff0d5ef706985ae0 Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Sun, 6 Sep 2026 22:32:34 +0100 Subject: [PATCH 022/194] Keep update regressions isolated from host authentication --- test/shell.d/fixtures/sudo-boundary-test.sh | 4 ++-- test/shell.d/update-disk-space-test.sh | 20 ++++++++++++-------- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/test/shell.d/fixtures/sudo-boundary-test.sh b/test/shell.d/fixtures/sudo-boundary-test.sh index cabad278e252..6c6bada37bdd 100644 --- a/test/shell.d/fixtures/sudo-boundary-test.sh +++ b/test/shell.d/fixtures/sudo-boundary-test.sh @@ -48,7 +48,7 @@ if [[ ${1:-} == "-h" ]]; then fi if [[ ${1:-} == "-k" || ${1:-} == "-K" ]]; then [[ ${SUDO_TEST_REVOKE_FAIL:-0} != "1" ]] || exit 1 - rm -f "$SUDO_TEST_CACHE" + /usr/bin/rm -f "$SUDO_TEST_CACHE" exit 0 fi if [[ ${1:-} == "-N" ]]; then @@ -115,7 +115,7 @@ ln -s ../bin/test-step "$SUDO_TEST_ROOT/mock/pacman" reset_boundary() { : >"$SUDO_TEST_LOG" - rm -f "$SUDO_TEST_CACHE" + /usr/bin/rm -f "$SUDO_TEST_CACHE" unset SUDO_TEST_FAIL_STEP SUDO_TEST_SIGNAL_STEP SUDO_TEST_SUDO_FAIL SUDO_TEST_REVOKE_FAIL SUDO_TEST_UNSUPPORTED } assert_boundary_cold() { diff --git a/test/shell.d/update-disk-space-test.sh b/test/shell.d/update-disk-space-test.sh index 2c7368ea6305..e40401ebfeb2 100644 --- a/test/shell.d/update-disk-space-test.sh +++ b/test/shell.d/update-disk-space-test.sh @@ -9,18 +9,21 @@ unset OMARCHY_UPDATE_FORCE unset TEST_AVAILABLE_BYTES unset TEST_DF_INVALID -test_tmp=$(mktemp -d) -trap 'rm -rf "$test_tmp"' EXIT - -stub_bin="$test_tmp/bin" -test_home="$test_tmp/home" +source "$SHELL_TEST_DIR/fixtures/sudo-boundary-test.sh" +test_tmp="$boundary_tmp" +stub_bin="$SUDO_TEST_ROOT/bin" +test_home="$SUDO_TEST_HOME" runtime_dir="$test_tmp/runtime" snapshot_marker="$test_tmp/snapshot" gum_marker="$test_tmp/gum" -mkdir -p "$stub_bin" "$test_home" "$runtime_dir" +mkdir -p "$runtime_dir" +for command in omarchy-update omarchy-update-requires-free-space omarchy-update-confirm; do + rm -f "$stub_bin/$command" + copy_boundary_file "bin/$command" +done run_update() { - HOME="$test_home" \ + SUDO_TEST_HOME="$test_home" \ XDG_RUNTIME_DIR="$runtime_dir" \ PATH="$stub_bin:$ROOT/bin:$PATH" \ LC_ALL=C \ @@ -30,13 +33,14 @@ run_update() { SNAPSHOT_MARKER="$snapshot_marker" \ GUM_MARKER="$gum_marker" \ GUM_STATUS=${GUM_STATUS:-1} \ - "$ROOT/bin/omarchy-update" "$@" + "$SUDO_TEST_ROOT/bin/omarchy-update" "$@" } write_stub() { local name="$1" local body="$2" + rm -f "$stub_bin/$name" cat >"$stub_bin/$name" < Date: Sun, 6 Sep 2026 22:49:43 +0100 Subject: [PATCH 023/194] Revoke before session cleanup and protect standalone inhibition --- bin/omarchy-update | 5 ++++ bin/omarchy-update-stay-awake | 15 ++++++++++-- test/shell.d/update-hook-security-test.sh | 6 +++++ test/shell.d/update-lock-test.sh | 29 ++++++++++++++++------- 4 files changed, 44 insertions(+), 11 deletions(-) diff --git a/bin/omarchy-update b/bin/omarchy-update index a3cc94a91607..b6e5c7bd5766 100755 --- a/bin/omarchy-update +++ b/bin/omarchy-update @@ -23,6 +23,10 @@ update_stay_awake_stopped=0 cleanup_update() { local status=$? trap - EXIT HUP INT TERM + if ! omarchy_security_revoke_sudo_timestamp; then + echo "Could not invalidate sudo before update cleanup." >&2 + omarchy_security_exit_with_revoked_sudo 1 + fi if (( update_stay_awake_stopped == 0 )); then omarchy-update-stay-awake stop || status=1 fi @@ -88,6 +92,7 @@ if [[ ${1:-} == "-y" ]] || omarchy-update-confirm; then # Release update-owned inhibitors before offering a reboot. A confirmed # reboot can terminate this process before its EXIT trap gets a chance to # remove the persistent Stay Awake marker. + omarchy_security_revoke_sudo_timestamp omarchy-update-stay-awake stop update_stay_awake_stopped=1 diff --git a/bin/omarchy-update-stay-awake b/bin/omarchy-update-stay-awake index 826fee5ef417..4b214ca0ac81 100755 --- a/bin/omarchy-update-stay-awake +++ b/bin/omarchy-update-stay-awake @@ -1,10 +1,21 @@ -#!/bin/bash +#!/bin/bash -p # omarchy:summary=Manage sleep and idle inhibition during an update # omarchy:args= # omarchy:hidden=true +if [[ $- != *p* ]]; then + echo "Refusing an unsafe Bash startup." >&2 + exit 126 +fi + +source "${BASH_SOURCE[0]%/*}/omarchy-security-functions" || exit 126 +omarchy_security_require_privileged_bash_startup || exit 126 set -e +omarchy_security_sanitize_bash_environment "$0" "$@" +omarchy_security_revoke_sudo_timestamp || exit 1 +omarchy_security_install_sudo_cleanup_traps +omarchy_security_enable_no_update_sudo state_dir="${XDG_RUNTIME_DIR:-/tmp/omarchy-$UID}/omarchy-update-stay-awake" idle_owner_file="$state_dir/idle-owner" @@ -106,7 +117,7 @@ start() { ( [[ -z ${OMARCHY_UPDATE_LOCK_FD:-} ]] || exec {OMARCHY_UPDATE_LOCK_FD}>&- exec "${hold_command[@]}" ) & elif [[ -t 0 ]]; then - sudo -N -b -- "${hold_command[@]}" + /usr/bin/sudo -N -b -- "${hold_command[@]}" else ( [[ -z ${OMARCHY_UPDATE_LOCK_FD:-} ]] || exec {OMARCHY_UPDATE_LOCK_FD}>&- exec pkexec "${hold_command[@]}" ) & diff --git a/test/shell.d/update-hook-security-test.sh b/test/shell.d/update-hook-security-test.sh index 4e0922c3d6c3..0181b800b951 100755 --- a/test/shell.d/update-hook-security-test.sh +++ b/test/shell.d/update-hook-security-test.sh @@ -36,6 +36,12 @@ for step in omarchy-update-system-pkgs yay omarchy-hook omarchy-update-mise; do export SUDO_TEST_FAIL_STEP=$step if run_update -y; then fail "$step failure must fail the update"; fi assert_boundary_cold "failed $step" + python3 - "$SUDO_TEST_LOG" <<'PY' +import sys +s=open(sys.argv[1]).read().splitlines() +for i,line in enumerate(s): + if line=='step:omarchy-update-stay-awake stop': assert i>0 and s[i-1]=='sudo -k',s +PY pass "update revokes credentials after $step fails" done diff --git a/test/shell.d/update-lock-test.sh b/test/shell.d/update-lock-test.sh index 7348848cf9b6..5b0e3b54de64 100644 --- a/test/shell.d/update-lock-test.sh +++ b/test/shell.d/update-lock-test.sh @@ -136,14 +136,10 @@ kill -0 "$inhibitor_pid" 2>/dev/null && pass "omarchy-update waits for its sleep inhibitor to stop" if (( EUID != 0 )); then - sudo_log="$test_tmp/sudo.log" + sudo_log="$SUDO_TEST_LOG" + : >"$sudo_log" pkexec_marker="$test_tmp/pkexec-used" terminal_inhibit_pid_file="$test_tmp/terminal-inhibit-pid" - write_stub sudo ' -printf "%s\n" "$*" >>"$SUDO_LOG" -[[ $1 == "-N" && $2 == "-b" && $3 == "--" ]] || exit 90 -shift 3 -"$@" &' write_stub pkexec '[[ -z ${PKEXEC_MARKER:-} ]] || touch "$PKEXEC_MARKER"; exec "$@"' # start leaves the inhibitor running on purpose, but script tears the pty down @@ -154,7 +150,7 @@ shift 3 #!/bin/bash omarchy-update-stay-awake start for _ in {1..200}; do - grep -q -- '^-N -b -- ' "$SUDO_LOG" && break + grep -q -- '^sudo -N -b -- ' "$SUDO_LOG" && break sleep 0.05 done SH @@ -163,8 +159,7 @@ SH SUDO_LOG="$sudo_log" PKEXEC_MARKER="$pkexec_marker" INHIBIT_PID_FILE="$terminal_inhibit_pid_file" \ run_with_lock_env script -qefc "$terminal_driver" /dev/null >/dev/null - grep -q -- '^-N -b -- ' "$sudo_log" || fail "terminal inhibition authenticates its background command without a reusable timestamp" - grep -q -- '^-N -b -- ' "$sudo_log" || fail "terminal sleep inhibition runs through sudo" + grep -q -- '^sudo -N -b -- ' "$sudo_log" || fail "terminal inhibition authenticates its background command without a reusable timestamp" [[ ! -e $pkexec_marker ]] || fail "terminal sleep inhibition does not use pkexec" run_with_lock_env "$SUDO_TEST_ROOT/bin/omarchy-update-stay-awake" stop pass "terminal updates use sudo instead of Polkit for sleep inhibition" @@ -229,3 +224,19 @@ kill -0 "$unrelated_pid" 2>/dev/null || kill "$unrelated_pid" wait "$unrelated_pid" 2>/dev/null || true pass "stale inhibitor state does not terminate a reused PID" + +# The hidden helper also establishes its own boundary when invoked directly. +reset_boundary +touch "$SUDO_TEST_CACHE" +run_with_lock_env "$SUDO_TEST_ROOT/bin/omarchy-update-stay-awake" stop +[[ $(head -1 "$SUDO_TEST_LOG") == "sudo -k" ]] || fail "standalone inhibitor cleanup did not start cold" +assert_boundary_cold "standalone inhibitor cleanup" +pass "standalone inhibitor cleanup revokes before and after session work" + +reset_boundary +export SUDO_TEST_REVOKE_FAIL=1 +if run_with_lock_env "$SUDO_TEST_ROOT/bin/omarchy-update-stay-awake" start; then + fail "inhibitor started after failed initial revocation" +fi +[[ ! -e $stay_awake_helper_state/inhibit-pid ]] || fail "failed revocation started an inhibitor" +pass "failed initial revocation prevents standalone inhibition" From a9e9954e3eb147b26e742c5a23e75b815cd030f4 Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Sun, 6 Sep 2026 22:59:08 +0100 Subject: [PATCH 024/194] Clarify unattended updates still require sudo authorization --- bin/omarchy-update | 4 ++-- docs/update-process.md | 4 +--- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/bin/omarchy-update b/bin/omarchy-update index b6e5c7bd5766..68582cd0cac2 100755 --- a/bin/omarchy-update +++ b/bin/omarchy-update @@ -48,8 +48,8 @@ omarchy_security_install_signal_exit_traps omarchy-update-requires-free-space -# -y is a promise not to ask anything. Steps that would need an answer report -# and move on instead of waiting on a prompt nobody is here to give. +# -y suppresses Omarchy confirmation prompts; sudo authorization is still +# required. Interactive review steps report and move on instead of waiting. [[ ${1:-} != "-y" ]] || export OMARCHY_UPDATE_UNATTENDED=1 if [[ ${1:-} == "-y" ]] || omarchy-update-confirm; then diff --git a/docs/update-process.md b/docs/update-process.md index 9ec3b96c7f60..52a8b4231c92 100644 --- a/docs/update-process.md +++ b/docs/update-process.md @@ -149,9 +149,7 @@ Important behavior: - In dev-link mode, `omarchy update` fast-forwards the active checkout from its configured upstream before changing system packages or running migrations. - Migrations remain in chronological order even though historical entries mix user-controlled code with later privileged repairs. Before entering that mixed-trust tail, Omarchy invalidates its timestamp and forces every later sudo call—including AUR's configurable sudo command—to use `--no-update`; prompts authorize one command without publishing a reusable timestamp. Yay's credential loop is disabled for the update. - User-controlled post-update hooks and mise tools run only after every sudo-capable update stage. Omarchy invalidates its sudo timestamp before each boundary and on every exit; detached children therefore have no later reusable update authorization to wait for. -- `-y` exports `OMARCHY_UPDATE_UNATTENDED=1` — a promise not to ask anything. - Steps that would prompt (orphan removal, conflict handoff) report and skip - instead of blocking. +- `-y` exports `OMARCHY_UPDATE_UNATTENDED=1` and suppresses Omarchy confirmation prompts. Interactive review steps (orphan removal, conflict handoff) report and skip instead of blocking. Privileged commands still require sudo authorization, and command-scoped authentication can prompt separately for each command. - The free-space requirement uses a 10 GiB threshold and stops the update before confirmation when it is not met. If free space cannot be determined, the check is silently skipped. Set `OMARCHY_UPDATE_FORCE=1` to bypass the check. From 978dffaa3e0fdc92855c14855b22595b3d72604d Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Sun, 6 Sep 2026 23:32:28 +0100 Subject: [PATCH 025/194] Use required gum directly in AI removal prompts --- bin/omarchy-remove-ai-hermes | 2 +- bin/omarchy-remove-ai-openclaw | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/omarchy-remove-ai-hermes b/bin/omarchy-remove-ai-hermes index f6b9f292d209..9525164ad706 100755 --- a/bin/omarchy-remove-ai-hermes +++ b/bin/omarchy-remove-ai-hermes @@ -73,7 +73,7 @@ fi # never owned, a yes takes that with it, and saying so is the prompt's job. # Without a terminal to ask in, keeping everything is the answer. data_removed=false -if [[ -d $HOME/.hermes || -d $HOME/.config/Hermes ]] && [[ -t 0 ]] && command -v gum >/dev/null; then +if [[ -d $HOME/.hermes || -d $HOME/.config/Hermes ]] && [[ -t 0 ]]; then # du answers non-zero when either directory is missing, and pipefail would # turn that into an aborted removal; the size is worth no such thing. size=$(du -shc "$HOME/.hermes" "$HOME/.config/Hermes" 2>/dev/null | tail -1 | cut -f1 || true) diff --git a/bin/omarchy-remove-ai-openclaw b/bin/omarchy-remove-ai-openclaw index 47658a205882..a5b15a23edbf 100755 --- a/bin/omarchy-remove-ai-openclaw +++ b/bin/omarchy-remove-ai-openclaw @@ -61,7 +61,7 @@ gtk-update-icon-cache "$HOME/.local/share/icons/hicolor" &>/dev/null || true # front of the user with the size rather than left silent. Without a terminal # to ask in, keeping it is the answer. state_removed=false -if [[ -d $HOME/.openclaw && -t 0 ]] && command -v gum >/dev/null; then +if [[ -d $HOME/.openclaw && -t 0 ]]; then size=$(du -sh "$HOME/.openclaw" 2>/dev/null | cut -f1) if gum confirm --default=false "Also delete ~/.openclaw ($size: chats, memories, credentials, and downloaded plugins)?"; then rm -rf "$HOME/.openclaw" From d41ca88f767f93dc6e2c60443aecf7fde82eb32a Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Mon, 7 Sep 2026 00:03:53 +0100 Subject: [PATCH 026/194] Wait for the actual Stay Awake launcher --- bin/omarchy-update-stay-awake | 6 +++++- test/shell.d/update-lock-test.sh | 14 +++++++------- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/bin/omarchy-update-stay-awake b/bin/omarchy-update-stay-awake index 4b214ca0ac81..ff311561dff5 100755 --- a/bin/omarchy-update-stay-awake +++ b/bin/omarchy-update-stay-awake @@ -93,6 +93,7 @@ stop() { start() { local idle_owner="$$:$RANDOM:$RANDOM" + local launcher_pid="" stop mkdir -p "$state_dir" @@ -116,16 +117,19 @@ start() { if (( EUID == 0 )); then ( [[ -z ${OMARCHY_UPDATE_LOCK_FD:-} ]] || exec {OMARCHY_UPDATE_LOCK_FD}>&- exec "${hold_command[@]}" ) & + launcher_pid=$! elif [[ -t 0 ]]; then /usr/bin/sudo -N -b -- "${hold_command[@]}" else ( [[ -z ${OMARCHY_UPDATE_LOCK_FD:-} ]] || exec {OMARCHY_UPDATE_LOCK_FD}>&- exec pkexec "${hold_command[@]}" ) & + launcher_pid=$! fi # For graphical authentication the launcher may wait for a password. Wait for # either the user-owned held command to become ready or the launcher to fail. - local launcher_pid=${!:-} + # sudo -b backgrounds internally, so Bash has no launcher PID in the TTY path; + # $! there can still refer to a completed startup process substitution. local readiness_attempts=0 while [[ ! -s $inhibit_pid_file ]]; do if [[ -n $launcher_pid ]] && ! kill -0 "$launcher_pid" 2>/dev/null; then diff --git a/test/shell.d/update-lock-test.sh b/test/shell.d/update-lock-test.sh index 5b0e3b54de64..846e968aafb6 100644 --- a/test/shell.d/update-lock-test.sh +++ b/test/shell.d/update-lock-test.sh @@ -141,18 +141,18 @@ if (( EUID != 0 )); then pkexec_marker="$test_tmp/pkexec-used" terminal_inhibit_pid_file="$test_tmp/terminal-inhibit-pid" write_stub pkexec '[[ -z ${PKEXEC_MARKER:-} ]] || touch "$PKEXEC_MARKER"; exec "$@"' + write_stub systemd-inhibit 'sleep 0.2; while [[ $1 == --* ]]; do shift; done; exec "$@"' - # start leaves the inhibitor running on purpose, but script tears the pty down - # the moment its command returns, which SIGHUPs that inhibitor before it can - # exec. Keep the session open from the inside until the stub has logged. + # sudo -b returns before its child is ready. Require start to wait for the + # delayed child and succeed, then stop it before script tears down the PTY. terminal_driver="$test_tmp/terminal-stay-awake" cat >"$terminal_driver" <<'SH' #!/bin/bash +set -euo pipefail omarchy-update-stay-awake start -for _ in {1..200}; do - grep -q -- '^sudo -N -b -- ' "$SUDO_LOG" && break - sleep 0.05 -done +[[ -s $XDG_RUNTIME_DIR/omarchy-update-stay-awake/inhibit-pid ]] +omarchy-update-stay-awake stop +[[ ! -e $XDG_RUNTIME_DIR/omarchy-update-stay-awake/inhibit-pid ]] SH chmod +x "$terminal_driver" From 177d5729c9b84db418377c8265890bb3fc1e32b5 Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Mon, 7 Sep 2026 00:08:07 +0100 Subject: [PATCH 027/194] Wait for notifications when restarting the shell --- bin/omarchy-restart-shell | 16 +++++++++++++++- test/shell.d/restart-shell-test.sh | 22 +++++++++++++++++++++- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/bin/omarchy-restart-shell b/bin/omarchy-restart-shell index dfc21724620f..9891e7e8a7c3 100755 --- a/bin/omarchy-restart-shell +++ b/bin/omarchy-restart-shell @@ -61,6 +61,19 @@ relock_session() { return 1 } +notifications_ready() { + [[ $(busctl --user call org.freedesktop.DBus /org/freedesktop/DBus \ + org.freedesktop.DBus NameHasOwner s org.freedesktop.Notifications 2>/dev/null) == "b true" ]] +} + +# Core IPC can answer before the notification plugin has registered its bus +# name. Restore an existing notification service before update hooks or setup +# invitations send their one-time toasts; a disabled service need not appear. +notifications_were_running=0 +if notifications_ready; then + notifications_were_running=1 +fi + # Each kill stops the oldest matching instance and only returns once it has # fully exited, so the no-duplicate launch below can't race a dying shell. while timeout 5 quickshell kill -p "$CONFIG_DIR" --any-display >/dev/null 2>&1; do :; done @@ -70,7 +83,8 @@ while timeout 5 quickshell kill -p "$CONFIG_DIR" --any-display >/dev/null 2>&1; hyprctl dispatch 'hl.dsp.exec_cmd("omarchy-launch-shell")' >/dev/null for (( attempt = 0; attempt < 20; attempt++ )); do - if OMARCHY_PATH="$session_omarchy_path" OMARCHY_SHELL_IPC_TIMEOUT=0.5s omarchy-shell shell ping >/dev/null 2>&1; then + if OMARCHY_PATH="$session_omarchy_path" OMARCHY_SHELL_IPC_TIMEOUT=0.5s omarchy-shell shell ping >/dev/null 2>&1 && + { (( notifications_were_running == 0 )) || notifications_ready; }; then # The session stays compositor-locked after the old lock client died, so # re-acquire the lock and let the user authenticate out of it. if (( relock )) && ! relock_session; then diff --git a/test/shell.d/restart-shell-test.sh b/test/shell.d/restart-shell-test.sh index 094c74f6449b..31901736d198 100755 --- a/test/shell.d/restart-shell-test.sh +++ b/test/shell.d/restart-shell-test.sh @@ -172,7 +172,24 @@ else fi SH -chmod +x "$restart_bin/qs" "$restart_bin/quickshell" "$restart_bin/hyprctl" "$restart_bin/systemd-cat" "$restart_bin/systemctl" +cat >"$restart_bin/busctl" <<'SH' +#!/bin/bash +if [[ -z ${OMARCHY_TEST_NOTIFICATION_CHECKS:-} ]]; then + echo 'b false' +else + checks=0 + [[ ! -f $OMARCHY_TEST_NOTIFICATION_CHECKS ]] || read -r checks <"$OMARCHY_TEST_NOTIFICATION_CHECKS" + (( checks += 1 )) + printf '%s\n' "$checks" >"$OMARCHY_TEST_NOTIFICATION_CHECKS" + if (( checks == 1 || checks >= 4 )); then + echo 'b true' + else + echo 'b false' + fi +fi +SH + +chmod +x "$restart_bin/qs" "$restart_bin/quickshell" "$restart_bin/hyprctl" "$restart_bin/systemd-cat" "$restart_bin/systemctl" "$restart_bin/busctl" sleep 30 & restart_pid_one=$! @@ -194,6 +211,7 @@ OMARCHY_TEST_DISPATCH_LOG="$dispatch_log" \ OMARCHY_TEST_IPC_LOG="$ipc_log" \ OMARCHY_TEST_SESSION_PATH="$restart_root" \ OMARCHY_TEST_TRANSIENT_ENV=leaked \ +OMARCHY_TEST_NOTIFICATION_CHECKS="$test_tmp/notification-checks" \ timeout 5 "$ROOT/bin/omarchy-restart-shell" if kill -0 "$restart_pid_one" 2>/dev/null; then @@ -213,6 +231,8 @@ grep -F "kill -p $restart_root/shell --any-display" "$restart_log" >/dev/null || grep -F 'hl.dsp.exec_cmd("omarchy-launch-shell")' "$dispatch_log" >/dev/null || fail "restart launches the fresh shell through Hyprland" grep -F "ipc -n -p $restart_root/shell call -- shell ping" "$ipc_log" >/dev/null || fail "restart checks readiness in the session checkout" pass "restart replaces duplicate shell instances from the session checkout" +[[ $(<"$test_tmp/notification-checks") == 4 ]] || fail "restart waits for the existing notification service after core IPC is ready" +pass "restart waits for notification readiness before one-time update hooks" : >"$restart_log" printf '303\n' >"$restart_state" From 35551b04daf5b338b9a85754e2a05154f45989d6 Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Mon, 7 Sep 2026 00:24:43 +0100 Subject: [PATCH 028/194] Disable the Yay sudo loop with its supported option --- bin/omarchy-update-aur-pkgs | 2 +- test/shell.d/fixtures/sudo-boundary-test.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/omarchy-update-aur-pkgs b/bin/omarchy-update-aur-pkgs index 8cdfb617317e..a860a97d3083 100755 --- a/bin/omarchy-update-aur-pkgs +++ b/bin/omarchy-update-aur-pkgs @@ -6,7 +6,7 @@ sudo_options=() if [[ ${OMARCHY_SUDO_NO_UPDATE:-0} == "1" ]]; then sudo_wrapper="$OMARCHY_PATH/default/omarchy/sudo-no-update/sudo" [[ -x $sudo_wrapper ]] || exit 1 - sudo_options=(--sudo "$sudo_wrapper" --nosudoloop) + sudo_options=(--sudo "$sudo_wrapper" --sudoloop=false) fi if pacman -Qem >/dev/null; then diff --git a/test/shell.d/fixtures/sudo-boundary-test.sh b/test/shell.d/fixtures/sudo-boundary-test.sh index 6c6bada37bdd..2ed8438bdd58 100644 --- a/test/shell.d/fixtures/sudo-boundary-test.sh +++ b/test/shell.d/fixtures/sudo-boundary-test.sh @@ -103,7 +103,7 @@ case "$step" in pacman) exit 0 ;; yay) [[ $* == *"--sudo $OMARCHY_PATH/default/omarchy/sudo-no-update/sudo"* ]] || exit 92 - [[ $* == *"--nosudoloop"* ]] || exit 93 + [[ $* == *"--sudoloop=false"* ]] || exit 93 ;; esac STUB From 5b692c5b30bba4d7adcd34ec2e71184f4b69661f Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Mon, 7 Sep 2026 14:31:07 +0100 Subject: [PATCH 029/194] Preserve user PATH across updater relaunches --- bin/omarchy-update | 9 ++-- test/shell.d/update-user-path-test.sh | 67 +++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 3 deletions(-) create mode 100644 test/shell.d/update-user-path-test.sh diff --git a/bin/omarchy-update b/bin/omarchy-update index 68582cd0cac2..9a8093514f3f 100755 --- a/bin/omarchy-update +++ b/bin/omarchy-update @@ -14,7 +14,10 @@ source "${BASH_SOURCE[0]%/*}/omarchy-security-functions" || exit 126 omarchy_security_require_privileged_bash_startup || exit 126 set -e omarchy_security_sanitize_bash_environment "$0" "$@" -user_path=$PATH +# Logging and lock acquisition re-exec this command with a sanitized PATH. +# Preserve the caller's path only for the later unprivileged hook/mise phases. +user_path=${OMARCHY_UPDATE_USER_PATH:-$PATH} +unset OMARCHY_UPDATE_USER_PATH omarchy_security_revoke_sudo_timestamp || exit 1 omarchy_security_install_sudo_cleanup_traps omarchy_security_enable_no_update_sudo @@ -35,11 +38,11 @@ cleanup_update() { if [[ -z ${OMARCHY_UPDATE_LOGGED:-} ]]; then script_command=$(printf '%q ' "$0" "$@") - exec env OMARCHY_UPDATE_LOGGED=1 script -qefc "$script_command" "/tmp/omarchy-update.log" + exec env OMARCHY_UPDATE_LOGGED=1 OMARCHY_UPDATE_USER_PATH="$user_path" script -qefc "$script_command" "/tmp/omarchy-update.log" fi if ! omarchy-update-lock held; then - exec omarchy-update-lock run "$0" "$@" + exec env OMARCHY_UPDATE_USER_PATH="$user_path" omarchy-update-lock run "$0" "$@" fi trap 'echo ""; echo -e "\033[0;31mSomething went wrong during the update!\n\nPlease review the output above carefully, correct the error, and retry the update.\n\nIf you need assistance, get help from the community at https://omarchy.org/discord\033[0m"' ERR diff --git a/test/shell.d/update-user-path-test.sh b/test/shell.d/update-user-path-test.sh new file mode 100644 index 000000000000..f76f0faf8b01 --- /dev/null +++ b/test/shell.d/update-user-path-test.sh @@ -0,0 +1,67 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" +source "$SHELL_TEST_DIR/fixtures/sudo-boundary-test.sh" +copy_boundary_file bin/omarchy-update + +# Model the two exec boundaries without a host update log or a real lock. +# Both child processes inherit the environment exactly as script/lock would. +cat >"$SUDO_TEST_ROOT/bin/script" <<'STUB' +#!/bin/bash +printf 'logged-reexec\n' >>"$SUDO_TEST_LOG" +[[ $1 == "-qefc" ]] || exit 90 +exec /usr/bin/bash -p -c "$2" +STUB +rm "$SUDO_TEST_ROOT/bin/omarchy-update-lock" +cat >"$SUDO_TEST_ROOT/bin/omarchy-update-lock" <<'STUB' +#!/bin/bash +case "$1" in + held) [[ ${SUDO_TEST_LOCKED:-0} == "1" ]] ;; + run) + shift + printf 'locked-reexec\n' >>"$SUDO_TEST_LOG" + export SUDO_TEST_LOCKED=1 + exec "$@" + ;; +esac +STUB +mkdir "$boundary_tmp/user commands" +cat >"$boundary_tmp/user commands/update-user-tool" <<'STUB' +#!/bin/bash +printf 'user-tool:%s\n' "$1" >>"$SUDO_TEST_LOG" +STUB +chmod +x "$SUDO_TEST_ROOT/bin/script" "$SUDO_TEST_ROOT/bin/omarchy-update-lock" "$boundary_tmp/user commands/update-user-tool" + +for step in omarchy-hook omarchy-update-mise; do + rm "$SUDO_TEST_ROOT/bin/$step" + cat >"$SUDO_TEST_ROOT/bin/$step" <<'STUB' +#!/bin/bash +[[ ! -e $SUDO_TEST_CACHE ]] || exit 91 +[[ $(command -v sudo) == "$OMARCHY_PATH/default/omarchy/sudo-no-update/sudo" ]] || exit 92 +update-user-tool "${0##*/}" +STUB + chmod +x "$SUDO_TEST_ROOT/bin/$step" +done + +for entry in fresh logged locked; do + reset_boundary + unset OMARCHY_UPDATE_LOGGED OMARCHY_UPDATE_USER_PATH SUDO_TEST_LOCKED + case "$entry" in + logged) export OMARCHY_UPDATE_LOGGED=1 ;; + locked) export OMARCHY_UPDATE_LOGGED=1 SUDO_TEST_LOCKED=1 ;; + esac + PATH="$boundary_tmp/user commands:$PATH" "$SUDO_TEST_ROOT/bin/omarchy-update" -y >"$boundary_tmp/output" 2>&1 || + fail "$entry update lost the original user PATH" "$(<"$boundary_tmp/output")" + grep -q '^user-tool:omarchy-hook$' "$SUDO_TEST_LOG" || fail "$entry hook could not run a user-installed tool" + grep -q '^user-tool:omarchy-update-mise$' "$SUDO_TEST_LOG" || fail "$entry mise could not run a user-installed tool" + if [[ $entry == "fresh" ]]; then + grep -q '^logged-reexec$' "$SUDO_TEST_LOG" || fail "fresh update did not exercise the logging exec" + fi + if [[ $entry != "locked" ]]; then + grep -q '^locked-reexec$' "$SUDO_TEST_LOG" || fail "$entry update did not exercise the lock exec" + fi + assert_boundary_cold "$entry update" + pass "$entry update preserves the original user PATH through logging and locking with no-update sudo first" +done From f37c73fa2028f54958779ad5320a07775a9f2a68 Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Mon, 7 Sep 2026 17:27:04 +0100 Subject: [PATCH 030/194] Bind protected update commands to their source root --- bin/omarchy-refresh-pacman | 1 + bin/omarchy-security-functions | 14 +++++ bin/omarchy-update | 1 + bin/omarchy-update-stay-awake | 1 + docs/update-process.md | 3 +- test/shell.d/security-source-root-test.sh | 65 +++++++++++++++++++++++ 6 files changed, 84 insertions(+), 1 deletion(-) create mode 100755 test/shell.d/security-source-root-test.sh diff --git a/bin/omarchy-refresh-pacman b/bin/omarchy-refresh-pacman index af552abb69c8..de6ca40515a6 100755 --- a/bin/omarchy-refresh-pacman +++ b/bin/omarchy-refresh-pacman @@ -12,6 +12,7 @@ source "${BASH_SOURCE[0]%/*}/omarchy-security-functions" || exit 126 omarchy_security_require_privileged_bash_startup || exit 126 set -e omarchy_security_sanitize_bash_environment "$0" "$@" +omarchy_security_require_source_root "$0" user_path=$PATH omarchy_security_revoke_sudo_timestamp || exit 1 omarchy_security_install_sudo_cleanup_traps diff --git a/bin/omarchy-security-functions b/bin/omarchy-security-functions index 5c9bd9e48e85..703fd630f1a6 100644 --- a/bin/omarchy-security-functions +++ b/bin/omarchy-security-functions @@ -44,6 +44,20 @@ omarchy_security_sanitize_bash_environment() { fi } +omarchy_security_require_source_root() { + local command_source command_name=${1##*/} + command_source=$(/usr/bin/readlink -e -- "$1") || return 1 + + # A runtime root selects the code used by this invocation. Accept the + # canonical checkout containing the entrypoint or the package's bin links. + if [[ $OMARCHY_PATH != /* || $(/usr/bin/realpath -e -- "$OMARCHY_PATH") != "$OMARCHY_PATH" ]] || + ! { [[ $command_source == "$OMARCHY_PATH/bin/$command_name" ]] || + [[ $OMARCHY_PATH == "/usr/share/omarchy" && $command_source == "/usr/bin/$command_name" ]]; }; then + echo "OMARCHY_PATH does not match this Omarchy command." >&2 + return 1 + fi +} + omarchy_security_sudo_supports_no_update() { local help help=$(LC_ALL=C /usr/bin/sudo -h 2>&1) || return 1 diff --git a/bin/omarchy-update b/bin/omarchy-update index 9a8093514f3f..2026e5e912f9 100755 --- a/bin/omarchy-update +++ b/bin/omarchy-update @@ -14,6 +14,7 @@ source "${BASH_SOURCE[0]%/*}/omarchy-security-functions" || exit 126 omarchy_security_require_privileged_bash_startup || exit 126 set -e omarchy_security_sanitize_bash_environment "$0" "$@" +omarchy_security_require_source_root "$0" # Logging and lock acquisition re-exec this command with a sanitized PATH. # Preserve the caller's path only for the later unprivileged hook/mise phases. user_path=${OMARCHY_UPDATE_USER_PATH:-$PATH} diff --git a/bin/omarchy-update-stay-awake b/bin/omarchy-update-stay-awake index ff311561dff5..4cb0af5289c6 100755 --- a/bin/omarchy-update-stay-awake +++ b/bin/omarchy-update-stay-awake @@ -13,6 +13,7 @@ source "${BASH_SOURCE[0]%/*}/omarchy-security-functions" || exit 126 omarchy_security_require_privileged_bash_startup || exit 126 set -e omarchy_security_sanitize_bash_environment "$0" "$@" +omarchy_security_require_source_root "$0" omarchy_security_revoke_sudo_timestamp || exit 1 omarchy_security_install_sudo_cleanup_traps omarchy_security_enable_no_update_sudo diff --git a/docs/update-process.md b/docs/update-process.md index 52a8b4231c92..ab073e83b049 100644 --- a/docs/update-process.md +++ b/docs/update-process.md @@ -144,11 +144,12 @@ omarchy-update Important behavior: -- `omarchy update` uses the session’s `OMARCHY_PATH` and a fixed command search path for its system phases. User PATH is restored behind the sudo wrapper for hooks and mise. +- Protected update entrypoints require the session's canonical `OMARCHY_PATH` to match their own checkout or the packaged `/usr/bin` entrypoint before selecting commands or the sudo wrapper. This preserves intentionally trusted development checkouts while rejecting a command paired with a different source root. System phases use a fixed command search path; user PATH is restored behind the sudo wrapper for hooks and mise. - Mixed-trust update entrypoints start Bash in privileged mode, discard `BASH_ENV`, `ENV`, and exported-function records before launching helpers, and reject an ordinary `bash path/to/command` invocation. Run them as executables (normally through the `omarchy` CLI); `/usr/bin/bash -p path/to/command` is the explicit interpreter form. This keeps shell startup injection from replacing the no-update sudo boundary. - In dev-link mode, `omarchy update` fast-forwards the active checkout from its configured upstream before changing system packages or running migrations. - Migrations remain in chronological order even though historical entries mix user-controlled code with later privileged repairs. Before entering that mixed-trust tail, Omarchy invalidates its timestamp and forces every later sudo call—including AUR's configurable sudo command—to use `--no-update`; prompts authorize one command without publishing a reusable timestamp. Yay's credential loop is disabled for the update. - User-controlled post-update hooks and mise tools run only after every sudo-capable update stage. Omarchy invalidates its sudo timestamp before each boundary and on every exit; detached children therefore have no later reusable update authorization to wait for. +- This lifecycle controls authorization created by the protected workflow. `sudo -N` prevents cache updates but can use an existing valid credential, and `sudo -k` revokes the current session's timestamp. It does not isolate the account from unrelated concurrent authentication in another workflow. - `-y` exports `OMARCHY_UPDATE_UNATTENDED=1` and suppresses Omarchy confirmation prompts. Interactive review steps (orphan removal, conflict handoff) report and skip instead of blocking. Privileged commands still require sudo authorization, and command-scoped authentication can prompt separately for each command. - The free-space requirement uses a 10 GiB threshold and stops the update before confirmation when it is not met. If free space cannot be determined, the diff --git a/test/shell.d/security-source-root-test.sh b/test/shell.d/security-source-root-test.sh new file mode 100755 index 000000000000..c872e78d120f --- /dev/null +++ b/test/shell.d/security-source-root-test.sh @@ -0,0 +1,65 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" +source "$SHELL_TEST_DIR/fixtures/sudo-boundary-test.sh" +source "$SUDO_TEST_ROOT/bin/omarchy-security-functions" + +rm -f "$SUDO_TEST_ROOT/bin/omarchy-update" +copy_boundary_file bin/omarchy-update +omarchy_security_require_source_root "$SUDO_TEST_ROOT/bin/omarchy-update" || fail "matching checkout root was rejected" +pass "a canonical checkout matches its own entrypoint" + +mkdir "$boundary_tmp/other-root" +ln -s "$SUDO_TEST_ROOT" "$boundary_tmp/root-link" +for root in "$boundary_tmp/other-root" "$boundary_tmp/root-link" .; do + if OMARCHY_PATH="$root" omarchy_security_require_source_root "$SUDO_TEST_ROOT/bin/omarchy-update" >"$boundary_tmp/output" 2>&1; then + fail "a different or noncanonical source root was accepted" + fi +done +pass "different, symlink and relative roots are rejected" + +# Redirect only the two package-layout literals into the fixture. Resolution +# still uses real readlink/realpath; no host /usr/bin file is changed or run. +package_root="$boundary_tmp/usr/share/omarchy" +package_bin="$boundary_tmp/usr/bin" +mkdir -p "$package_root/bin" "$package_bin" +cp "$SUDO_TEST_ROOT/bin/omarchy-update" "$package_bin/omarchy-update" +cp "$SUDO_TEST_ROOT/bin/omarchy-update" "$package_bin/different-command" +ln -s "$package_bin/omarchy-update" "$package_root/bin/omarchy-update" +python3 - "$SUDO_TEST_ROOT/bin/omarchy-security-functions" "$boundary_tmp/package-library" "$package_root" "$package_bin" <<'PY' +import sys +from pathlib import Path +source, output, root, binaries = sys.argv[1:] +text = Path(source).read_text() +text = text.replace('"/usr/share/omarchy"', f'"{root}"') +text = text.replace('"/usr/bin/$command_name"', f'"{binaries}/$command_name"') +Path(output).write_text(text) +PY +source "$boundary_tmp/package-library" +OMARCHY_PATH="$package_root" omarchy_security_require_source_root "$package_bin/omarchy-update" || fail "package binary was rejected" +OMARCHY_PATH="$package_root" omarchy_security_require_source_root "$package_root/bin/omarchy-update" || fail "package link was rejected" +pass "the package binary and its matching source-tree link are accepted" + +ln -sfn "$package_bin/different-command" "$package_root/bin/omarchy-update" +if OMARCHY_PATH="$package_root" omarchy_security_require_source_root "$package_root/bin/omarchy-update" >"$boundary_tmp/output" 2>&1; then + fail "a package link to a different command was accepted" +fi +pass "a package link must resolve to its named command" + +# Run the protected entrypoints themselves with a mismatched root. These must +# stop before any sudo or operational fixture command, not merely validate in +# an isolated library test. +for command in omarchy-update omarchy-refresh-pacman omarchy-update-stay-awake; do + rm -f "$SUDO_TEST_ROOT/bin/$command" + copy_boundary_file "bin/$command" + for root in "$boundary_tmp/other-root" .; do + reset_boundary + if OMARCHY_PATH="$root" "$SUDO_TEST_ROOT/bin/$command" >"$boundary_tmp/output" 2>&1; then + fail "$command accepted a mismatched root" + fi + [[ ! -s $SUDO_TEST_LOG ]] || fail "$command ran work before rejecting its root" + done + pass "$command rejects mismatched and relative roots before work" +done From 5bc41b2585d664e5a37708055d9a2621f44c5ac4 Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Mon, 7 Sep 2026 17:31:54 +0100 Subject: [PATCH 031/194] Resolve security libraries beside canonical entrypoints --- bin/omarchy-refresh-pacman | 3 +- bin/omarchy-security-functions | 2 +- bin/omarchy-update | 3 +- bin/omarchy-update-stay-awake | 3 +- default/omarchy/sudo-no-update/sudo | 3 +- .../security-entrypoint-symlink-test.sh | 34 +++++++++++++++++++ 6 files changed, 43 insertions(+), 5 deletions(-) create mode 100755 test/shell.d/security-entrypoint-symlink-test.sh diff --git a/bin/omarchy-refresh-pacman b/bin/omarchy-refresh-pacman index de6ca40515a6..d70ffd9ca427 100755 --- a/bin/omarchy-refresh-pacman +++ b/bin/omarchy-refresh-pacman @@ -8,7 +8,8 @@ if [[ $- != *p* ]]; then exit 126 fi -source "${BASH_SOURCE[0]%/*}/omarchy-security-functions" || exit 126 +security_entrypoint=$(/usr/bin/readlink -e -- "${BASH_SOURCE[0]}") || exit 126 +source "${security_entrypoint%/*}/omarchy-security-functions" || exit 126 omarchy_security_require_privileged_bash_startup || exit 126 set -e omarchy_security_sanitize_bash_environment "$0" "$@" diff --git a/bin/omarchy-security-functions b/bin/omarchy-security-functions index 703fd630f1a6..5826c8256460 100644 --- a/bin/omarchy-security-functions +++ b/bin/omarchy-security-functions @@ -50,7 +50,7 @@ omarchy_security_require_source_root() { # A runtime root selects the code used by this invocation. Accept the # canonical checkout containing the entrypoint or the package's bin links. - if [[ $OMARCHY_PATH != /* || $(/usr/bin/realpath -e -- "$OMARCHY_PATH") != "$OMARCHY_PATH" ]] || + if [[ ${OMARCHY_PATH:-} != /* || $(/usr/bin/realpath -e -- "$OMARCHY_PATH") != "$OMARCHY_PATH" ]] || ! { [[ $command_source == "$OMARCHY_PATH/bin/$command_name" ]] || [[ $OMARCHY_PATH == "/usr/share/omarchy" && $command_source == "/usr/bin/$command_name" ]]; }; then echo "OMARCHY_PATH does not match this Omarchy command." >&2 diff --git a/bin/omarchy-update b/bin/omarchy-update index 2026e5e912f9..3873a6bc4010 100755 --- a/bin/omarchy-update +++ b/bin/omarchy-update @@ -10,7 +10,8 @@ if [[ $- != *p* ]]; then exit 126 fi -source "${BASH_SOURCE[0]%/*}/omarchy-security-functions" || exit 126 +security_entrypoint=$(/usr/bin/readlink -e -- "${BASH_SOURCE[0]}") || exit 126 +source "${security_entrypoint%/*}/omarchy-security-functions" || exit 126 omarchy_security_require_privileged_bash_startup || exit 126 set -e omarchy_security_sanitize_bash_environment "$0" "$@" diff --git a/bin/omarchy-update-stay-awake b/bin/omarchy-update-stay-awake index 4cb0af5289c6..af941c4a3d11 100755 --- a/bin/omarchy-update-stay-awake +++ b/bin/omarchy-update-stay-awake @@ -9,7 +9,8 @@ if [[ $- != *p* ]]; then exit 126 fi -source "${BASH_SOURCE[0]%/*}/omarchy-security-functions" || exit 126 +security_entrypoint=$(/usr/bin/readlink -e -- "${BASH_SOURCE[0]}") || exit 126 +source "${security_entrypoint%/*}/omarchy-security-functions" || exit 126 omarchy_security_require_privileged_bash_startup || exit 126 set -e omarchy_security_sanitize_bash_environment "$0" "$@" diff --git a/default/omarchy/sudo-no-update/sudo b/default/omarchy/sudo-no-update/sudo index de69347bab43..7019a4dc0e27 100755 --- a/default/omarchy/sudo-no-update/sudo +++ b/default/omarchy/sudo-no-update/sudo @@ -6,7 +6,8 @@ if [[ $- != *p* ]]; then echo "Refusing an unsafe Bash startup for the sudo boundary." >&2 exit 126 fi -source "${BASH_SOURCE[0]%/*}/../../../bin/omarchy-security-functions" || exit 126 +security_entrypoint=$(/usr/bin/readlink -e -- "${BASH_SOURCE[0]}") || exit 126 +source "${security_entrypoint%/*}/../../../bin/omarchy-security-functions" || exit 126 omarchy_security_require_privileged_bash_startup || exit 126 if (( $# == 1 )); then diff --git a/test/shell.d/security-entrypoint-symlink-test.sh b/test/shell.d/security-entrypoint-symlink-test.sh new file mode 100755 index 000000000000..678a6742f463 --- /dev/null +++ b/test/shell.d/security-entrypoint-symlink-test.sh @@ -0,0 +1,34 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" +source "$SHELL_TEST_DIR/fixtures/sudo-boundary-test.sh" +export OMARCHY_UPDATE_LOGGED=1 + +# The real fixed entrypoints run only fixture operations. The sibling library +# is a harmless sentinel: invoking a command through another directory must +# source the library beside the resolved command instead of this file. +mkdir "$boundary_tmp/links" +printf '%s\n' 'touch "$SUDO_TEST_HOME/wrong-library"' >"$boundary_tmp/links/omarchy-security-functions" +for command in omarchy-update omarchy-refresh-pacman omarchy-update-stay-awake; do + rm -f "$SUDO_TEST_ROOT/bin/$command" + copy_boundary_file "bin/$command" + ln -s "$SUDO_TEST_ROOT/bin/$command" "$boundary_tmp/links/$command" + reset_boundary + args=(unexpected) + [[ $command != "omarchy-update" ]] || args=(-y) + status=0 + "$boundary_tmp/links/$command" "${args[@]}" >"$boundary_tmp/output" 2>&1 || status=$? + [[ ! -e $SUDO_TEST_HOME/wrong-library ]] || fail "$command sourced a library beside its symlink" + (( status != 126 )) || fail "$command failed to locate its actual library" "$(<"$boundary_tmp/output")" + [[ -s $SUDO_TEST_LOG ]] || fail "$command did not reach the protected fixture boundary" + assert_boundary_cold "$command symlink" + pass "$command resolves its own library when invoked through a symlink" +done + +ln -s "$SUDO_TEST_ROOT/default/omarchy/sudo-no-update/sudo" "$boundary_tmp/links/sudo" +reset_boundary +"$boundary_tmp/links/sudo" -k || fail "symlinked sudo wrapper lost its source library" +[[ $(<"$SUDO_TEST_LOG") == "sudo -k" ]] || fail "symlinked wrapper did not reach the fixed sudo stand-in" +pass "the sudo wrapper resolves its source library independently of its invocation link" From c8697407cb54213f971652e1a89d9757882ca823 Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Mon, 7 Sep 2026 17:33:33 +0100 Subject: [PATCH 032/194] Keep channel transitions inside command-scoped sudo --- bin/omarchy-channel-set | 24 +++- docs/update-process.md | 1 + test/shell.d/channel-sudo-boundary-test.sh | 131 ++++++++++++++++++ test/shell.d/channel-test.sh | 52 ++++--- .../security-entrypoint-symlink-test.sh | 2 +- test/shell.d/security-source-root-test.sh | 2 +- 6 files changed, 189 insertions(+), 23 deletions(-) create mode 100755 test/shell.d/channel-sudo-boundary-test.sh diff --git a/bin/omarchy-channel-set b/bin/omarchy-channel-set index b711da93d8ca..f1f050634692 100755 --- a/bin/omarchy-channel-set +++ b/bin/omarchy-channel-set @@ -1,10 +1,23 @@ -#!/bin/bash +#!/bin/bash -p # omarchy:summary=Set the Omarchy package channel. # omarchy:args= # omarchy:requires-sudo=true +if [[ $- != *p* ]]; then + echo "Refusing an unsafe Bash startup for channel switching." >&2 + exit 126 +fi +security_entrypoint=$(/usr/bin/readlink -e -- "${BASH_SOURCE[0]}") || exit 126 +source "${security_entrypoint%/*}/omarchy-security-functions" || exit 126 +omarchy_security_require_privileged_bash_startup || exit 126 set -euo pipefail +omarchy_security_sanitize_bash_environment "$0" "$@" +omarchy_security_require_source_root "$0" +user_path=$PATH +omarchy_security_revoke_sudo_timestamp || exit 1 +omarchy_security_install_sudo_cleanup_traps +omarchy_security_enable_no_update_sudo usage() { echo "Usage: omarchy-channel-set [stable|rc|edge|dev]"; } fail() { echo "Error: $*" >&2; exit 1; } @@ -79,7 +92,7 @@ fi if [[ -n $dev_checkout ]]; then link_dev_checkout "$dev_checkout" export OMARCHY_PATH="$dev_checkout" - export PATH="$OMARCHY_PATH/bin:$PATH" + omarchy_security_enable_no_update_sudo omarchy-state set reboot-required fi @@ -90,13 +103,16 @@ sudo env OMARCHY_UPDATE_PACMAN=1 pacman -S --needed --noconfirm --ask 4 "${packa if [[ -z $dev_checkout ]]; then omarchy-dev-unlink --no-reboot export OMARCHY_PATH=/usr/share/omarchy + omarchy_security_enable_no_update_sudo if (( leaving_dev )); then omarchy-state set reboot-required fi fi -omarchy-update -y +OMARCHY_UPDATE_USER_PATH="$user_path" "$OMARCHY_PATH/bin/omarchy-update" -y # No channel-owned privileged work follows the historical refresh hook. -omarchy-refresh-pacman "$pacman_channel" run-deferred +omarchy_security_revoke_sudo_timestamp +PATH="$OMARCHY_PATH/default/omarchy/sudo-no-update:$user_path" \ + "$OMARCHY_PATH/bin/omarchy-refresh-pacman" "$pacman_channel" run-deferred diff --git a/docs/update-process.md b/docs/update-process.md index ab073e83b049..b530c590fa66 100644 --- a/docs/update-process.md +++ b/docs/update-process.md @@ -150,6 +150,7 @@ Important behavior: - Migrations remain in chronological order even though historical entries mix user-controlled code with later privileged repairs. Before entering that mixed-trust tail, Omarchy invalidates its timestamp and forces every later sudo call—including AUR's configurable sudo command—to use `--no-update`; prompts authorize one command without publishing a reusable timestamp. Yay's credential loop is disabled for the update. - User-controlled post-update hooks and mise tools run only after every sudo-capable update stage. Omarchy invalidates its sudo timestamp before each boundary and on every exit; detached children therefore have no later reusable update authorization to wait for. - This lifecycle controls authorization created by the protected workflow. `sudo -N` prevents cache updates but can use an existing valid credential, and `sudo -k` revokes the current session's timestamp. It does not isolate the account from unrelated concurrent authentication in another workflow. +- Channel switching establishes the same boundary before dev link/unlink, refresh and package operations. It keeps the wrapper first when changing source roots, carries the original user PATH into update hooks and mise, and runs the deferred refresh hook only after the full update succeeds and authorization is revoked again. Failed and interrupted channel switches revoke on exit. - `-y` exports `OMARCHY_UPDATE_UNATTENDED=1` and suppresses Omarchy confirmation prompts. Interactive review steps (orphan removal, conflict handoff) report and skip instead of blocking. Privileged commands still require sudo authorization, and command-scoped authentication can prompt separately for each command. - The free-space requirement uses a 10 GiB threshold and stops the update before confirmation when it is not met. If free space cannot be determined, the diff --git a/test/shell.d/channel-sudo-boundary-test.sh b/test/shell.d/channel-sudo-boundary-test.sh new file mode 100755 index 000000000000..a2aba4407286 --- /dev/null +++ b/test/shell.d/channel-sudo-boundary-test.sh @@ -0,0 +1,131 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" +source "$SHELL_TEST_DIR/fixtures/sudo-boundary-test.sh" +copy_boundary_file bin/omarchy-channel-set +copy_boundary_file bin/omarchy-refresh-pacman +copy_boundary_file bin/omarchy-update +export OMARCHY_UPDATE_LOGGED=1 + +# Relocate the package root into the fixture, including the explicit handoff +# from the development checkout. All privileged operations remain stand-ins. +python3 - "$SUDO_TEST_ROOT/bin/omarchy-channel-set" "$SUDO_TEST_ROOT" <<'PY' +import sys +from pathlib import Path +p = Path(sys.argv[1]) +p.write_text(p.read_text().replace('/usr/share/omarchy', sys.argv[2])) +PY + +for command in omarchy-dev-link omarchy-dev-unlink omarchy-state gum git; do + cat >"$SUDO_TEST_ROOT/bin/$command" <<'STUB' +#!/bin/bash +set -euo pipefail +step=${0##*/} +printf 'step:%s %s\n' "$step" "$*" >>"$SUDO_TEST_LOG" +case "$step" in + omarchy-dev-link|omarchy-dev-unlink) sudo /usr/bin/true ;; + git) + [[ $1 == "clone" ]] || exit 90 + /usr/bin/cp -a "$SUDO_TEST_ROOT" "${@: -1}" + mkdir -p "${@: -1}/.git" "${@: -1}/shell" + ;; +esac +STUB + chmod +x "$SUDO_TEST_ROOT/bin/$command" +done + +assert_scoped_channel() { + local label=$1 + assert_boundary_cold "$label" + python3 - "$SUDO_TEST_LOG" <<'PY' +import sys +events = open(sys.argv[1]).read().splitlines() +assert events[0] == 'sudo -k', events +sudo = [event for event in events if event.startswith('sudo ')] +assert all(event in ('sudo -h', 'sudo -k') or event.startswith('sudo -N ') for event in sudo), events +hooks = [i for i, event in enumerate(events) if event.startswith('step:omarchy-hook ')] +assert len(hooks) == 2, events +assert events[hooks[-1]] == 'step:omarchy-hook pre-refresh-pacman', events +assert not any(event.startswith('sudo -N ') for event in events[hooks[0]:]), events +PY +} + +run_channel() { + "$OMARCHY_PATH/bin/omarchy-channel-set" "$@" >"$boundary_tmp/output" 2>&1 +} +for channel in stable rc edge dev; do + reset_boundary + run_channel "$channel" || fail "$channel failed" "$(<"$boundary_tmp/output")" + assert_scoped_channel "$channel" + pass "$channel starts cold, authorizes only individual commands, defers hooks and exits cold" +done + +reset_boundary +OMARCHY_PATH="$SUDO_TEST_HOME/omarchy" run_channel stable || fail "leaving dev failed" "$(<"$boundary_tmp/output")" +assert_scoped_channel "dev to stable" +pass "leaving dev preserves no-update sudo through unlink and the packaged update" + +mkdir "$boundary_tmp/user tools" +cat >"$boundary_tmp/user tools/channel-user-tool" <<'STUB' +#!/bin/bash +printf 'user-tool:%s\n' "$*" >>"$SUDO_TEST_LOG" +STUB +chmod +x "$boundary_tmp/user tools/channel-user-tool" +for command in omarchy-hook omarchy-update-mise; do + rm "$SUDO_TEST_ROOT/bin/$command" + cat >"$SUDO_TEST_ROOT/bin/$command" <<'STUB' +#!/bin/bash +[[ ! -e $SUDO_TEST_CACHE ]] || exit 91 +[[ $(command -v sudo) == "$OMARCHY_PATH/default/omarchy/sudo-no-update/sudo" ]] || exit 92 +channel-user-tool "${0##*/}" "$@" +STUB + chmod +x "$SUDO_TEST_ROOT/bin/$command" +done +reset_boundary +PATH="$boundary_tmp/user tools:$PATH" run_channel stable || fail "channel hooks lost the user's PATH" "$(<"$boundary_tmp/output")" +for event in 'omarchy-hook post-update' 'omarchy-update-mise' 'omarchy-hook pre-refresh-pacman'; do + grep -Fxq "user-tool:$event" "$SUDO_TEST_LOG" || fail "user PATH was not preserved for $event" +done +assert_boundary_cold "channel user PATH" +for command in omarchy-hook omarchy-update-mise; do + ln -sfn test-step "$SUDO_TEST_ROOT/bin/$command" +done +pass "channel switching preserves user tools behind the wrapper for both hooks and mise" + +for step in pacman omarchy-update-system-pkgs omarchy-hook; do + reset_boundary + if SUDO_TEST_FAIL_STEP="$step" run_channel stable; then fail "$step failure was ignored"; fi + assert_boundary_cold "$step failure" + if grep -q '^step:omarchy-hook pre-refresh-pacman$' "$SUDO_TEST_LOG"; then fail "$step failure reached the deferred hook"; fi + pass "$step failure exits cold without the deferred hook" +done + +for signal in HUP INT TERM; do + reset_boundary + cat >"$SUDO_TEST_ROOT/bin/omarchy-dev-unlink" <<'STUB' +#!/bin/bash +sudo /usr/bin/true || exit 1 +kill -s "$SUDO_TEST_CHANNEL_SIGNAL" "$PPID" +STUB + if SUDO_TEST_CHANNEL_SIGNAL="$signal" run_channel stable; then fail "$signal was ignored"; fi + assert_boundary_cold "$signal" + if grep -q '^step:omarchy-hook ' "$SUDO_TEST_LOG"; then fail "$signal reached an update hook"; fi + pass "$signal stops the channel transition and revokes authorization" +done + +for refusal in unsupported-sudo failed-revocation ordinary-bash; do + reset_boundary + case "$refusal" in + unsupported-sudo) export SUDO_TEST_UNSUPPORTED=1 ;; + failed-revocation) export SUDO_TEST_REVOKE_FAIL=1 ;; + esac + if [[ $refusal == "ordinary-bash" ]]; then + if /usr/bin/bash "$SUDO_TEST_ROOT/bin/omarchy-channel-set" -p >"$boundary_tmp/output" 2>&1; then fail "$refusal was accepted"; fi + elif run_channel stable; then + fail "$refusal was accepted" + fi + if grep -q '^step:' "$SUDO_TEST_LOG"; then fail "$refusal reached channel work"; fi + pass "$refusal is rejected before channel work" +done diff --git a/test/shell.d/channel-test.sh b/test/shell.d/channel-test.sh index a799e6e00df9..712ef8a40dd0 100644 --- a/test/shell.d/channel-test.sh +++ b/test/shell.d/channel-test.sh @@ -4,10 +4,18 @@ set -euo pipefail source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" -test_tmp=$(mktemp -d) -trap 'rm -rf "$test_tmp"' EXIT - -stub_bin="$test_tmp/bin" +source "$SHELL_TEST_DIR/fixtures/sudo-boundary-test.sh" +test_tmp="$boundary_tmp" +package_root="$SUDO_TEST_ROOT" +copy_boundary_file bin/omarchy-channel-set +python3 - "$SUDO_TEST_ROOT/bin/omarchy-channel-set" "$package_root" <<'PYTHON' +import sys +from pathlib import Path +p = Path(sys.argv[1]) +p.write_text(p.read_text().replace("/usr/share/omarchy", sys.argv[2])) +PYTHON + +stub_bin="$SUDO_TEST_ROOT/bin" log_file="$test_tmp/channel.log" mkdir -p "$stub_bin" "$test_tmp/home" @@ -15,6 +23,7 @@ write_stub() { local name="$1" local body="$2" + rm -f "$stub_bin/$name" cat >"$stub_bin/$name" <<<"$body" chmod +x "$stub_bin/$name" } @@ -26,11 +35,17 @@ printf "\n" >>"$OMARCHY_CHANNEL_TEST_LOG" ' write_stub sudo '#!/bin/bash +case "${1:-}" in + -h) echo "usage: sudo [-ABbEHkNnPS] command"; exit 0 ;; + -k|-K) exit 0 ;; +esac printf "sudo" >>"$OMARCHY_CHANNEL_TEST_LOG" for arg in "$@"; do printf "\t%s" "$arg" >>"$OMARCHY_CHANNEL_TEST_LOG"; done printf "\n" >>"$OMARCHY_CHANNEL_TEST_LOG" ' +cp "$stub_bin/sudo" "$SUDO_TEST_ROOT/mock/sudo" + write_stub omarchy-dev-unlink '#!/bin/bash printf "unlink" >>"$OMARCHY_CHANNEL_TEST_LOG" for arg in "$@"; do printf "\t%s" "$arg" >>"$OMARCHY_CHANNEL_TEST_LOG"; done @@ -63,7 +78,8 @@ for arg in "$@"; do printf "\t%s" "$arg" >>"$OMARCHY_CHANNEL_TEST_LOG"; done printf "\n" >>"$OMARCHY_CHANNEL_TEST_LOG" if [[ $1 == "clone" ]]; then dest="${@: -1}" - mkdir -p "$dest/.git" "$dest/bin" "$dest/default" "$dest/shell" + /usr/bin/cp -a "$SUDO_TEST_ROOT" "$dest" + mkdir -p "$dest/.git" "$dest/shell" fi ' @@ -90,10 +106,10 @@ esac run_channel() { : >"$log_file" OMARCHY_CHANNEL_TEST_LOG="$log_file" \ - OMARCHY_PATH="${OMARCHY_TEST_PATH:-/usr/share/omarchy}" \ + OMARCHY_PATH="${OMARCHY_TEST_PATH:-$package_root}" \ HOME="$test_tmp/home" \ PATH="$stub_bin:$ROOT/bin:$PATH" \ - "$ROOT/bin/omarchy-channel-set" "$@" + "${OMARCHY_TEST_PATH:-$package_root}/bin/omarchy-channel-set" "$@" } assert_log_line() { @@ -106,9 +122,9 @@ assert_log_line() { run_channel stable assert_log_line $'refresh\tstable\tdefer-hook' "stable refreshes the stable pacman channel" -assert_log_line $'sudo\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy\tomarchy-settings' "stable installs stable Omarchy packages" +assert_log_line $'sudo\t-N\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy\tomarchy-settings' "stable installs stable Omarchy packages" assert_log_line $'unlink\t--no-reboot' "stable restores the package-backed Omarchy path without an early reboot prompt" -assert_log_line $'update\t-y\tOMARCHY_PATH=/usr/share/omarchy' "stable runs the normal update pipeline from the package-backed path" +assert_log_line $'update\t-y\tOMARCHY_PATH='"$package_root" "stable runs the normal update pipeline from the package-backed path" if grep -q $'^state\tset\treboot-required$' "$log_file"; then fail "stable does not require reboot when already package-backed" "$(cat "$log_file")" fi @@ -116,17 +132,19 @@ pass "stable does not require reboot when already package-backed" run_channel rc assert_log_line $'refresh\trc\tdefer-hook' "rc refreshes the rc pacman channel" -assert_log_line $'sudo\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy\tomarchy-settings' "rc installs rc Omarchy packages" +assert_log_line $'sudo\t-N\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy\tomarchy-settings' "rc installs rc Omarchy packages" assert_log_line $'unlink\t--no-reboot' "rc restores the package-backed Omarchy path without an early reboot prompt" -assert_log_line $'update\t-y\tOMARCHY_PATH=/usr/share/omarchy' "rc runs the normal update pipeline from the package-backed path" +assert_log_line $'update\t-y\tOMARCHY_PATH='"$package_root" "rc runs the normal update pipeline from the package-backed path" -OMARCHY_TEST_PATH="$ROOT" run_channel edge +active_checkout="$test_tmp/active-checkout" +cp -a "$package_root" "$active_checkout" +OMARCHY_TEST_PATH="$active_checkout" run_channel edge assert_log_line $'refresh\tedge\tdefer-hook' "edge refreshes the edge pacman channel" -assert_log_line $'sudo\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev' "edge installs development Omarchy packages" +assert_log_line $'sudo\t-N\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev' "edge installs development Omarchy packages" assert_log_line $'unlink\t--no-reboot' "edge unlinks dev without an early reboot prompt" assert_log_line $'state\tset\treboot-required' "edge marks reboot required when leaving dev" -assert_log_line $'update\t-y\tOMARCHY_PATH=/usr/share/omarchy' "edge runs the normal update pipeline from the package-backed path" -[[ $(grep -E '^(unlink|state|update)' "$log_file") == $'unlink\t--no-reboot\nstate\tset\treboot-required\nupdate\t-y\tOMARCHY_PATH=/usr/share/omarchy' ]] || +assert_log_line $'update\t-y\tOMARCHY_PATH='"$package_root" "edge runs the normal update pipeline from the package-backed path" +[[ $(grep -E '^(unlink|state|update)' "$log_file") == $'unlink\t--no-reboot\nstate\tset\treboot-required\nupdate\t-y\tOMARCHY_PATH='"$package_root" ]] || fail "edge defers the reboot prompt until the update restart stage" "$(cat "$log_file")" pass "edge defers the reboot prompt until the update restart stage" @@ -146,12 +164,12 @@ rmdir "$checkout" run_channel dev assert_log_line $'gum\tconfirm\t--default=false\tSwitch to dev channel?' "dev asks for confirmation" assert_log_line $'refresh\tedge\tdefer-hook' "dev refreshes the edge pacman channel" -assert_log_line $'sudo\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev' "dev installs development Omarchy packages" +assert_log_line $'sudo\t-N\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev' "dev installs development Omarchy packages" assert_log_line $'git\tclone\thttps://github.com/basecamp/omarchy.git\t'"$checkout" "dev clones the source checkout to ~/omarchy" assert_log_line $'link\t'"$checkout"$'\t--no-reboot' "dev links ~/omarchy without an early reboot prompt" assert_log_line $'state\tset\treboot-required' "dev defers the reboot prompt to the update pipeline" assert_log_line $'update\t-y\tOMARCHY_PATH='"$checkout" "dev runs the normal update pipeline from the source checkout" -[[ $(grep -E '^(git|link|state|refresh|sudo|update)' "$log_file" | sed '/run-deferred/d') == $'git\tclone\thttps://github.com/basecamp/omarchy.git\t'"$checkout"$'\nlink\t'"$checkout"$'\t--no-reboot\nstate\tset\treboot-required\nrefresh\tedge\tdefer-hook\nsudo\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev\nupdate\t-y\tOMARCHY_PATH='"$checkout" ]] || +[[ $(grep -E '^(git|link|state|refresh|sudo|update)' "$log_file" | sed '/run-deferred/d') == $'git\tclone\thttps://github.com/basecamp/omarchy.git\t'"$checkout"$'\nlink\t'"$checkout"$'\t--no-reboot\nstate\tset\treboot-required\nrefresh\tedge\tdefer-hook\nsudo\t-N\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev\nupdate\t-y\tOMARCHY_PATH='"$checkout" ]] || fail "dev activates the checkout before changing or updating packages" "$(cat "$log_file")" pass "dev activates the checkout before changing or updating packages" [[ $(tail -1 "$log_file") == $'refresh\tedge\trun-deferred' ]] || fail "channel refresh hook must run after the complete update" diff --git a/test/shell.d/security-entrypoint-symlink-test.sh b/test/shell.d/security-entrypoint-symlink-test.sh index 678a6742f463..1b00cd133a1f 100755 --- a/test/shell.d/security-entrypoint-symlink-test.sh +++ b/test/shell.d/security-entrypoint-symlink-test.sh @@ -11,7 +11,7 @@ export OMARCHY_UPDATE_LOGGED=1 # source the library beside the resolved command instead of this file. mkdir "$boundary_tmp/links" printf '%s\n' 'touch "$SUDO_TEST_HOME/wrong-library"' >"$boundary_tmp/links/omarchy-security-functions" -for command in omarchy-update omarchy-refresh-pacman omarchy-update-stay-awake; do +for command in omarchy-update omarchy-refresh-pacman omarchy-update-stay-awake omarchy-channel-set; do rm -f "$SUDO_TEST_ROOT/bin/$command" copy_boundary_file "bin/$command" ln -s "$SUDO_TEST_ROOT/bin/$command" "$boundary_tmp/links/$command" diff --git a/test/shell.d/security-source-root-test.sh b/test/shell.d/security-source-root-test.sh index c872e78d120f..25ff2e98a85d 100755 --- a/test/shell.d/security-source-root-test.sh +++ b/test/shell.d/security-source-root-test.sh @@ -51,7 +51,7 @@ pass "a package link must resolve to its named command" # Run the protected entrypoints themselves with a mismatched root. These must # stop before any sudo or operational fixture command, not merely validate in # an isolated library test. -for command in omarchy-update omarchy-refresh-pacman omarchy-update-stay-awake; do +for command in omarchy-update omarchy-refresh-pacman omarchy-update-stay-awake omarchy-channel-set; do rm -f "$SUDO_TEST_ROOT/bin/$command" copy_boundary_file "bin/$command" for root in "$boundary_tmp/other-root" .; do From 0add43f9b70f54b26de0b87846d219b1cdb14e68 Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Mon, 7 Sep 2026 17:38:36 +0100 Subject: [PATCH 033/194] Check dev update support before changing the system --- bin/omarchy-channel-set | 11 ++++++++++- test/shell.d/channel-sudo-boundary-test.sh | 12 ++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/bin/omarchy-channel-set b/bin/omarchy-channel-set index f1f050634692..cf8e515f0150 100755 --- a/bin/omarchy-channel-set +++ b/bin/omarchy-channel-set @@ -46,9 +46,18 @@ validate_dev_checkout() { } link_dev_checkout() { - local checkout="$1" + local checkout="$1" required [[ -d $checkout/.git ]] || git clone https://github.com/basecamp/omarchy.git "$checkout" + # Check the destination before changing /etc/omarchy.conf or sudo's path. + # An existing checkout is not pulled automatically and may predate this policy. + for required in bin/omarchy-security-functions bin/omarchy-update bin/omarchy-refresh-pacman default/omarchy/sudo-no-update/sudo; do + if [[ ! -f $checkout/$required || ! -r $checkout/$required || + ( $required != "bin/omarchy-security-functions" && ! -x $checkout/$required ) ]]; then + fail "Update the checkout before switching to dev; missing required update support in $required." + fi + done + omarchy-dev-link "$checkout" --no-reboot } diff --git a/test/shell.d/channel-sudo-boundary-test.sh b/test/shell.d/channel-sudo-boundary-test.sh index a2aba4407286..b7fabf0257e6 100755 --- a/test/shell.d/channel-sudo-boundary-test.sh +++ b/test/shell.d/channel-sudo-boundary-test.sh @@ -62,6 +62,18 @@ for channel in stable rc edge dev; do pass "$channel starts cold, authorizes only individual commands, defers hooks and exits cold" done +reset_boundary +wrapper="$SUDO_TEST_HOME/omarchy/default/omarchy/sudo-no-update/sudo" +mv "$wrapper" "$boundary_tmp/saved-wrapper" +if run_channel dev; then fail "an old checkout without the wrapper was accepted"; fi +if grep -Eq '^step:omarchy-(dev-link|state)|^sudo -N ' "$SUDO_TEST_LOG"; then + fail "an incompatible dev checkout changed the system before rejection" +fi +grep -q 'Update the checkout before switching to dev' "$boundary_tmp/output" || fail "stale checkout rejection lacks recovery guidance" +assert_boundary_cold "stale checkout" +mv "$boundary_tmp/saved-wrapper" "$wrapper" +pass "a stale dev checkout is rejected before linking or privileged work" + reset_boundary OMARCHY_PATH="$SUDO_TEST_HOME/omarchy" run_channel stable || fail "leaving dev failed" "$(<"$boundary_tmp/output")" assert_scoped_channel "dev to stable" From e522a18ef0d31b5024a5a92697215abe7b57042e Mon Sep 17 00:00:00 2001 From: Adolanium <94890352+Adolanium@users.noreply.github.com> Date: Mon, 7 Sep 2026 20:59:36 +0300 Subject: [PATCH 034/194] Refuse path-like names in omarchy-hook-install too The runner already rejects a slash, a bare . or .. The installer still joined the type into hooks/.d before mkdir/cp, so a name nothing can run could still land on disk. --- bin/omarchy-hook-install | 11 +++++ test/shell.d/hook-state-name-guard-test.sh | 49 ++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/bin/omarchy-hook-install b/bin/omarchy-hook-install index 7c53648259be..6e954bd158b8 100755 --- a/bin/omarchy-hook-install +++ b/bin/omarchy-hook-install @@ -15,6 +15,17 @@ fi HOOK_TYPE=$1 HOOK_FILE=$2 + +# Hook types are the same labels omarchy-hook runs (post-update, theme-set). +# The type becomes a directory under the hooks directory. A slash would turn +# it into directory levels. A bare `.` or `..` is a name the runner already +# refuses, so installing under it would write a hook nothing can run. Refuse +# those rather than mkdir/cp into them. Dots inside a name (a..b) are fine. +if [[ -z $HOOK_TYPE || $HOOK_TYPE == */* || $HOOK_TYPE == "." || $HOOK_TYPE == ".." ]]; then + echo "Invalid hook name: $HOOK_TYPE" >&2 + exit 2 +fi + HOOK_DIR="$HOME/.config/omarchy/hooks/$HOOK_TYPE.d" HOOK_NAME=$(basename "$HOOK_FILE") HOOK_PATH="$HOOK_DIR/$HOOK_NAME" diff --git a/test/shell.d/hook-state-name-guard-test.sh b/test/shell.d/hook-state-name-guard-test.sh index 2955ad27b67c..0157202b4d1a 100644 --- a/test/shell.d/hook-state-name-guard-test.sh +++ b/test/shell.d/hook-state-name-guard-test.sh @@ -63,6 +63,55 @@ HOME="$fake_home" "$ROOT/bin/omarchy-hook" "sub/dir" >/dev/null 2>&1 || status=$ fail "omarchy hook refuses a hook name with a slash" "exit: $status" pass "omarchy hook refuses a hook name with a slash" +# --- omarchy-hook-install ------------------------------------------------------ + +# The installer joins the type into ~/.config/omarchy/hooks/.d before +# mkdir/cp. The runner already refuses a slashed type; install must too, or a +# name the runner will not run still lands on disk. + +source_hook="$work_dir/source-hook" +cat >"$source_hook" <<'SH' +#!/bin/bash +true +SH + +HOME="$fake_home" "$ROOT/bin/omarchy-hook-install" post-update "$source_hook" >/dev/null +[[ -f $fake_home/.config/omarchy/hooks/post-update.d/source-hook ]] || + fail "omarchy hook install still installs a named hook" +pass "omarchy hook install still installs a named hook" + +HOME="$fake_home" "$ROOT/bin/omarchy-hook-install" a..b "$source_hook" >/dev/null +[[ -f $fake_home/.config/omarchy/hooks/a..b.d/source-hook ]] || + fail "omarchy hook install accepts a hook name with dots in the middle" +pass "omarchy hook install accepts a hook name with dots in the middle" + +for name in . ..; do + status=0 + HOME="$fake_home" "$ROOT/bin/omarchy-hook-install" "$name" "$source_hook" >/dev/null 2>&1 || status=$? + (( status == 2 )) || + fail "omarchy hook install refuses a hook name of $name" "exit: $status" + [[ ! -e $fake_home/.config/omarchy/hooks/${name}.d ]] || + fail "omarchy hook install creates no directory for a hook name of $name" + pass "omarchy hook install refuses a hook name of $name" +done + +# hooks/../../evil.d is ~/.config/evil.d. The guard must fire before mkdir. +status=0 +HOME="$fake_home" "$ROOT/bin/omarchy-hook-install" "../../evil" "$source_hook" >/dev/null 2>&1 || status=$? +(( status == 2 )) || + fail "omarchy hook install refuses a hook name with a dot-dot" "exit: $status" +[[ ! -e $fake_home/.config/evil.d ]] || + fail "omarchy hook install creates nothing outside the hooks directory" +pass "omarchy hook install refuses a hook name with a dot-dot" + +status=0 +HOME="$fake_home" "$ROOT/bin/omarchy-hook-install" "sub/dir" "$source_hook" >/dev/null 2>&1 || status=$? +(( status == 2 )) || + fail "omarchy hook install refuses a hook name with a slash" "exit: $status" +[[ ! -e $fake_home/.config/omarchy/hooks/sub ]] || + fail "omarchy hook install creates no nested directory from a slashed name" +pass "omarchy hook install refuses a hook name with a slash" + # --- omarchy-state ------------------------------------------------------------- state_dir="$fake_home/.local/state/omarchy" From 4ae25cd4d241392158607ac96edd2e92717ee7ba Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Mon, 7 Sep 2026 21:50:47 +0100 Subject: [PATCH 035/194] Keep temporary sudo grants bounded through lifecycle failures --- bin/omarchy-security-functions | 90 ++++++-- bin/omarchy-sudo-passwordless | 133 ++++++++---- docs/passwordless-sudo.md | 25 +++ manual/48-security.md | 2 + test/shell.d/nopasswd-sudo-expiry-test.sh | 70 ++++-- .../passwordless-grant-lifecycle-test.sh | 199 ++++++++++++++++++ 6 files changed, 440 insertions(+), 79 deletions(-) create mode 100644 docs/passwordless-sudo.md create mode 100644 test/shell.d/passwordless-grant-lifecycle-test.sh diff --git a/bin/omarchy-security-functions b/bin/omarchy-security-functions index 2f3d2242ec57..890d4430d805 100755 --- a/bin/omarchy-security-functions +++ b/bin/omarchy-security-functions @@ -1,10 +1,7 @@ #!/bin/bash # omarchy:hidden=true -# omarchy:summary=Provide internal fail-closed helpers for security-sensitive commands - -# Shared fail-closed primitives for security-sensitive Omarchy commands. This -# file is sourced from the same package-owned bin directory as its consumers. +# omarchy:summary=Provide internal helpers for command-scoped sudo authentication if [[ ${BASH_SOURCE[0]} == "$0" ]]; then echo "omarchy-security-functions is an internal function library." >&2 @@ -12,25 +9,63 @@ if [[ ${BASH_SOURCE[0]} == "$0" ]]; then fi omarchy_security_require_privileged_bash_startup() { - local pid=${1:-$$} - - [[ $- == *p* && $pid =~ ^[1-9][0-9]*$ ]] || return 1 + [[ $- == *p* ]] || return 1 /usr/bin/env -i /usr/bin/bash -p -c ' mapfile -d "" -t argv <"/proc/$1/cmdline" || exit 1 executable=$(/usr/bin/readlink -e -- "/proc/$1/exe") || exit 1 - [[ $executable == /usr/bin/bash ]] - [[ ${argv[0]:-} == /bin/bash || ${argv[0]:-} == /usr/bin/bash ]] - [[ ${argv[1]:-} == -p ]] - ' omarchy-bash-startup "$pid" + [[ $executable == "/usr/bin/bash" && + ( ${argv[0]:-} == "/bin/bash" || ${argv[0]:-} == "/usr/bin/bash" ) && + ${argv[1]:-} == "-p" ]] + ' omarchy-bash-startup "$$" +} + +omarchy_security_sanitize_bash_environment() { + local script=$1 + shift + local entry name environment_fd environment_pid + local -a unsets=() + + # Read the raw environment: privileged Bash ignores exported functions, but + # leaves their records for ordinary child interpreters to import later. + exec {environment_fd}< <(/usr/bin/env -0) + environment_pid=$! + while IFS= read -r -d '' entry <&"$environment_fd"; do + name=${entry%%=*} + case "$name" in + BASH_ENV|ENV|SHELLOPTS|BASHOPTS|PS4|CDPATH|GLOBIGNORE|BASH_FUNC_*%%) + unsets+=(-u "$name") + ;; + esac + done + exec {environment_fd}<&- + wait "$environment_pid" || return 1 + if (( ${#unsets[@]} > 0 )); then + exec /usr/bin/env "${unsets[@]}" /usr/bin/bash -p -- "$script" "$@" + fi +} + +omarchy_security_require_source_root() { + local command_source command_name=${1##*/} + command_source=$(/usr/bin/readlink -e -- "$1") || return 1 + + # A runtime root selects the code used by this invocation. Accept the + # canonical checkout containing the entrypoint or the package's bin links. + if [[ ${OMARCHY_PATH:-} != /* || $(/usr/bin/realpath -e -- "$OMARCHY_PATH") != "$OMARCHY_PATH" ]] || + ! { [[ $command_source == "$OMARCHY_PATH/bin/$command_name" ]] || + [[ $OMARCHY_PATH == "/usr/share/omarchy" && $command_source == "/usr/bin/$command_name" ]]; }; then + echo "OMARCHY_PATH does not match this Omarchy command." >&2 + return 1 + fi } omarchy_security_sudo_supports_no_update() { - LC_ALL=C /usr/bin/sudo -h 2>&1 | - /usr/bin/grep -Eq '^usage: sudo .*\[[^]]*N[^]]*\]' + local help + help=$(LC_ALL=C /usr/bin/sudo -h 2>&1) || return 1 + /usr/bin/grep -Eq '^usage: sudo .*\[[^]]*N[^]]*\]' <<< "$help" } omarchy_security_revoke_sudo_timestamp() { - /usr/bin/sudo -k >/dev/null 2>&1 + /usr/bin/sudo -k } omarchy_security_exit_with_revoked_sudo() { @@ -51,6 +86,27 @@ omarchy_security_install_signal_exit_traps() { trap 'exit 143' TERM } +omarchy_security_install_sudo_cleanup_traps() { + OMARCHY_SECURITY_SUDO_CLEANUP_MESSAGE=${1:-Could not invalidate cached sudo authorization.} + trap omarchy_security_run_sudo_cleanup_trap EXIT + omarchy_security_install_signal_exit_traps +} + +omarchy_security_enable_no_update_sudo() { + local wrapper_dir="$OMARCHY_PATH/default/omarchy/sudo-no-update" + if ! omarchy_security_sudo_supports_no_update; then + echo "This sudo does not support --no-update; refusing mixed-trust work." >&2 + return 1 + fi + if [[ ! -f $wrapper_dir/sudo || ! -x $wrapper_dir/sudo ]]; then + echo "The command-scoped sudo wrapper is missing." >&2 + return 1 + fi + PATH="$wrapper_dir:$OMARCHY_PATH/bin:/usr/bin:/usr/sbin:/bin:/sbin" + OMARCHY_SUDO_NO_UPDATE=1 + export PATH OMARCHY_SUDO_NO_UPDATE +} + omarchy_security_run_sudo_cleanup_trap() { local status=$? @@ -58,12 +114,6 @@ omarchy_security_run_sudo_cleanup_trap() { "${OMARCHY_SECURITY_SUDO_CLEANUP_MESSAGE:-Could not invalidate cached sudo authorization.}" } -omarchy_security_install_sudo_cleanup_traps() { - OMARCHY_SECURITY_SUDO_CLEANUP_MESSAGE=${1:-Could not invalidate cached sudo authorization.} - trap omarchy_security_run_sudo_cleanup_trap EXIT - omarchy_security_install_signal_exit_traps -} - omarchy_security_assert_root_directory() { local path=$1 expected_mode=$2 canonical owner actual_mode diff --git a/bin/omarchy-sudo-passwordless b/bin/omarchy-sudo-passwordless index 717e8aaf243b..5f7cd1dc7507 100755 --- a/bin/omarchy-sudo-passwordless +++ b/bin/omarchy-sudo-passwordless @@ -4,14 +4,20 @@ # omarchy:args=[MINUTES] # omarchy:requires-sudo=true -source "${BASH_SOURCE[0]%/*}/omarchy-security-functions" || exit 126 +if [[ $- != *p* && ${BASH_SOURCE[0]} == "$0" ]]; then + echo "Refusing an unsafe Bash startup for passwordless sudo." >&2 + exit 126 +fi + +security_entrypoint=$(/usr/bin/readlink -e -- "${BASH_SOURCE[0]}") || exit 126 +source "${security_entrypoint%/*}/omarchy-security-functions" || exit 126 if [[ ${BASH_SOURCE[0]} == "$0" ]]; then omarchy_security_require_privileged_bash_startup || { echo "Refusing an unsafe Bash startup for passwordless sudo." >&2 exit 126 } - unset BASH_ENV ENV + omarchy_security_sanitize_bash_environment "$0" "$@" || exit 126 fi set -euo pipefail @@ -22,7 +28,9 @@ readonly STATE_DIR=/var/lib/omarchy/sudo-passwordless readonly RUNTIME_DIR=/run/omarchy/sudo-passwordless readonly LOCK_FILE=/run/lock/omarchy-sudo-passwordless.lock readonly BOOT_CLEANUP_FILE=/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf +readonly REMOVAL_BLOCKER=/run/omarchy-sudo-passwordless-package-removing readonly INSTALLED_SELF=/usr/bin/omarchy-sudo-passwordless +readonly STATUS_INACTIVE=3 usage() { echo "Usage: omarchy-sudo-passwordless [MINUTES]" >&2 @@ -31,15 +39,15 @@ usage() { } valid_minutes() { - [[ $1 =~ ^[0-9]+$ ]] && ((10#$1 >= 1 && 10#$1 <= MAX_MINUTES)) + [[ $1 =~ ^0*[1-9][0-9]{0,3}$ ]] && ((10#$1 <= MAX_MINUTES)) } valid_uid() { - [[ $1 =~ ^[0-9]+$ ]] && ((10#$1 >= 1 && 10#$1 <= 4294967294)) + [[ $1 =~ ^0*[1-9][0-9]{0,9}$ ]] && ((10#$1 <= 4294967294)) } valid_account_name() { - [[ $1 =~ ^[a-z_][a-z0-9_-]{0,31}$ ]] + [[ $1 =~ ^[a-z_][a-z0-9_-]{0,31}\$?$ ]] && (( ${#1} <= 32 )) } resolve_account() { @@ -191,10 +199,13 @@ remove_known_legacy_rules() { # must not survive the next boot. Do not require the account to still # exist: a deleted account could otherwise make the rule immortal and a # later username reuse could activate it again. - /usr/bin/rm -f -- "$file" || failed=1 - [[ -z $GENERATED_RULE_LEGACY_TIMER ]] || - /usr/bin/systemctl stop "${GENERATED_RULE_LEGACY_TIMER}.timer" \ - "${GENERATED_RULE_LEGACY_TIMER}.service" >/dev/null 2>&1 || true + if /usr/bin/rm -f -- "$file" && [[ ! -e $file && ! -L $file ]]; then + [[ -z $GENERATED_RULE_LEGACY_TIMER ]] || + /usr/bin/systemctl stop "${GENERATED_RULE_LEGACY_TIMER}.timer" \ + "${GENERATED_RULE_LEGACY_TIMER}.service" >/dev/null 2>&1 || true + else + failed=1 + fi else classification=$? # An unreadable candidate cannot be proven inert. A symlink, non-file, @@ -213,6 +224,7 @@ cleanup_uid_locked() { # Remove policy first. A failed timer stop can only leave an inert cleanup # job behind, never extend passwordless access. /usr/bin/rm -f -- "$(rule_file "$uid")" || return 1 + [[ ! -e $(rule_file "$uid") && ! -L $(rule_file "$uid") ]] || return 1 /usr/bin/rm -f -- "$(state_file "$uid")" || return 1 [[ -z $timer ]] || stop_timer "$timer" } @@ -246,6 +258,7 @@ cleanup_all_locked() { verify_boot_cleanup() { local owner mode canonical current active_rules + [[ ! -e $REMOVAL_BLOCKER && ! -L $REMOVAL_BLOCKER ]] || return 1 [[ -f $BOOT_CLEANUP_FILE && ! -L $BOOT_CLEANUP_FILE ]] || return 1 canonical=$(/usr/bin/realpath -e -- "$BOOT_CLEANUP_FILE") || return 1 [[ $canonical == "$BOOT_CLEANUP_FILE" ]] || return 1 @@ -288,7 +301,7 @@ start_expiry_timer() { # a monotonic OnActiveSec timer pauses while the machine is suspended. /usr/bin/systemd-run --quiet --collect --on-calendar="@${expires}" \ --timer-property=AccuracySec=1s --unit="$timer" \ - -- "$INSTALLED_SELF" __expire "$uid" || return 1 + -- "$INSTALLED_SELF" __expire "$uid" "$timer" || return 1 /usr/bin/systemctl is-active --quiet "${timer}.timer" } @@ -306,6 +319,20 @@ publish_rule() { /usr/bin/rm -f -- "$tmp" } +abort_enable_locked() { + local uid=$1 timer=$2 old_timer=$3 pending_state=$4 + # Publication can install policy and then fail while cleaning its temporary + # file. Never disarm either expiry job until policy revocation is confirmed. + if cleanup_uid_locked "$uid"; then + stop_timer "$timer" + [[ -z $old_timer ]] || stop_timer "$old_timer" + else + echo "Could not revoke passwordless sudo after a failed grant; expiry jobs remain armed. Administrator cleanup is required." >&2 + fi + /usr/bin/rm -f -- "$pending_state" || true + return 1 +} + enable_locked() { local uid="$1" minutes="$2" old_timer="" timer token expires pending_state now resolve_account "$uid" || return 1 @@ -329,34 +356,26 @@ enable_locked() { # grant rather than extending it. pending_state=$(prepare_state_file "$uid" "$ACCOUNT_NAME" "$expires" "$timer") || return 1 if ! start_expiry_timer "$uid" "$expires" "$timer"; then - /usr/bin/rm -f -- "$pending_state" - # Preserve the predecessor fix's fail-closed extension semantics: a caller - # must never mistake a failed replacement for a safely extended grant. - # The old timer is still armed here, but revoking the old rule as well is - # the unambiguous failure state. - cleanup_uid_locked "$uid" || true + abort_enable_locked "$uid" "$timer" "$old_timer" "$pending_state" return 1 fi if ! /usr/bin/mv -fT -- "$pending_state" "$(state_file "$uid")"; then - stop_timer "$timer" - /usr/bin/rm -f -- "$pending_state" - cleanup_uid_locked "$uid" || true + abort_enable_locked "$uid" "$timer" "$old_timer" "$pending_state" return 1 fi - if ! publish_rule "$uid" "$ACCOUNT_NAME"; then - stop_timer "$timer" - /usr/bin/rm -f -- "$(state_file "$uid")" "$(rule_file "$uid")" + if ! verify_boot_cleanup || ! publish_rule "$uid" "$ACCOUNT_NAME"; then + abort_enable_locked "$uid" "$timer" "$old_timer" "$pending_state" return 1 fi now=$(current_epoch) || { - cleanup_uid_locked "$uid" || true + abort_enable_locked "$uid" "$timer" "$old_timer" "$pending_state" return 1 } - if ((10#$now >= 10#$expires)) || ! /usr/bin/systemctl is-active --quiet "${timer}.timer"; then + if ((10#$now >= 10#$expires)) || ! /usr/bin/systemctl is-active --quiet "${timer}.timer" || ! verify_boot_cleanup; then # The timer may have expired or failed between its initial verification and # rule publication. Revoke synchronously so a suspended or heavily loaded # machine cannot turn a short grant into a reboot-long one. - cleanup_uid_locked "$uid" || true + abort_enable_locked "$uid" "$timer" "$old_timer" "$pending_state" return 1 fi [[ -z $old_timer || $old_timer == "$timer" ]] || stop_timer "$old_timer" @@ -364,40 +383,68 @@ enable_locked() { status_locked() { local uid="$1" record state_name expires timer now remainder - resolve_account "$uid" || return 1 - [[ -f $(rule_file "$uid") && ! -L $(rule_file "$uid") ]] || return 1 + resolve_account "$uid" || return 2 + if [[ ! -e $(rule_file "$uid") && ! -L $(rule_file "$uid") ]]; then + return "$STATUS_INACTIVE" + fi record=$(read_state_record "$uid") || { - cleanup_uid_locked "$uid" - return 1 + revoke_inactive_grant "$uid" + return $? } state_name=${record%%$'\t'*} remainder=${record#*$'\t'} expires=${remainder%%$'\t'*} timer=${record##*$'\t'} [[ $state_name == "$ACCOUNT_NAME" ]] || { - cleanup_uid_locked "$uid" - return 1 + revoke_inactive_grant "$uid" + return $? } now=$(current_epoch) || { - cleanup_uid_locked "$uid" - return 1 + revoke_inactive_grant "$uid" + return $? } ((10#$now < 10#$expires)) || { - cleanup_uid_locked "$uid" - return 1 + revoke_inactive_grant "$uid" + return $? } /usr/bin/systemctl is-active --quiet "${timer}.timer" || { - cleanup_uid_locked "$uid" - return 1 + revoke_inactive_grant "$uid" + return $? } } +revoke_inactive_grant() { + if cleanup_uid_locked "$1"; then + return "$STATUS_INACTIVE" + else + echo "Could not revoke invalid or expired passwordless sudo. Administrator cleanup is required." >&2 + return 2 + fi +} + +expire_locked() { + local uid=$1 timer=${2:-} current_timer status + if [[ -n $timer ]]; then + current_timer=$(read_state_timer "$uid" 2>/dev/null || true) + # A delayed predecessor must not revoke a newer, independently timed grant. + [[ -z $current_timer || $current_timer == "$timer" ]] || return 0 + cleanup_uid_locked "$uid" + elif status_locked "$uid"; then + # Compatibility with already scheduled UID-only jobs: enforce the current + # grant's expiry instead of letting an old timer shorten its replacement. + return 0 + else + status=$? + (( status == STATUS_INACTIVE )) + fi +} + root_dispatch() { local action="$1" shift case "$action" in __status) - (($# == 1)) && verify_sudo_caller "$1" || return 1 + (($# == 1)) && verify_sudo_caller "$1" || return 2 with_root_lock status_locked "$1" ;; __enable) @@ -409,8 +456,9 @@ root_dispatch() { with_root_lock cleanup_uid_locked "$1" ;; __expire) - (($# == 1)) && ((EUID == 0)) && valid_uid "$1" || return 1 - with_root_lock cleanup_uid_locked "$1" + (($# == 1 || $# == 2)) && ((EUID == 0)) && valid_uid "$1" || return 1 + [[ -z ${2:-} ]] || valid_timer_for_uid "$1" "$2" || return 1 + with_root_lock expire_locked "$@" ;; __cleanup-all) (($# == 0)) && ((EUID == 0)) || return 1 @@ -459,6 +507,11 @@ if /usr/bin/sudo -N -- "$INSTALLED_SELF" __status "$uid"; then echo "Passwordless sudo timer updated. It will automatically disable in ${minutes} minutes." fi else + status=$? + if (( status != STATUS_INACTIVE )); then + echo "Could not safely inspect passwordless sudo; no grant will be enabled. Resolve the reported authorization or cleanup error first." >&2 + exit 1 + fi echo "" echo "⚠️ WARNING: This will allow ANY process running as your user to" echo "execute ANY command as root WITHOUT a password for ${minutes} minutes." diff --git a/docs/passwordless-sudo.md b/docs/passwordless-sudo.md new file mode 100644 index 000000000000..b97160e460f8 --- /dev/null +++ b/docs/passwordless-sudo.md @@ -0,0 +1,25 @@ +# Temporary passwordless sudo + +`omarchy-sudo-passwordless` publishes a bounded grant for the numeric UID authenticated by sudo. Its user interface runs without a reusable sudo timestamp; fixed installed internal actions run as root and serialize on `/run/lock/omarchy-sudo-passwordless.lock`. + +## Grant lifecycle + +Root state records the resolved account name, absolute expiry epoch and unique timer name. A calendar timer is armed and verified before the generated policy becomes active. Publication rechecks the package-owned boot cleanup before and after installing policy. Policy revocation must succeed before expiry jobs are stopped; a deletion error leaves those jobs armed and reports that administrator cleanup is required. + +An internal status result is `0` for an active, validated grant and `3` for confirmed inactive access. All other results are errors, including failed authentication and failed revocation. The user interface only offers a new grant after result `3`. It must not turn an inspection failure into a claim that no grant exists. + +Each new expiry callback carries its timer identity. A delayed predecessor cannot revoke a newer grant. Already scheduled UID-only callbacks remain compatible by checking the current grant's expiry. Boot-time tmpfiles cleanup removes the reserved generated filename namespace before users log in; it does not run during routine non-boot tmpfiles maintenance. + +## Package ownership + +The packaging companion must put the publication/expiry command, `omarchy-security-functions` and `omarchy-nopasswd-sudo.conf` in the settings package together. Removing the desktop runtime alone must leave a working expiry command behind. Stable and development package pairs must transfer ownership in one transaction without duplicate files. + +Before settings removal or upgrade, its scriptlet acquires the same grant lock, sets `/run/omarchy-sudo-passwordless-package-removing` and revokes existing policy. The marker prevents a waiting publisher from creating a new grant while package files change. A successful installation clears the marker only after boot cleanup exists. Failed scriptlet cleanup returns an error and prints recovery guidance; a package-manager scriptlet failure must not be represented as an automatic transaction rollback. + +The runtime marker need not survive reboot: pre-removal revokes the old grants before package files disappear, and a new invocation independently verifies boot cleanup. Both root operations use fixed machine paths. The marker is not a user-controlled mode switch. + +## Validation + +`test/shell.d/nopasswd-sudo-expiry-test.sh` covers the public interface, cold authentication, timer setup, boot cleanup, package transitions and lock contention. `test/shell.d/passwordless-grant-lifecycle-test.sh` covers publication/cleanup failures, error status, supported account syntax, predecessor callbacks and the shared package-removal lock. Supply `OMARCHY_PKGS_PATH` as either a repository root or its `pkgbuilds` directory. + +These tests use private filesystem fixtures and mapped privileged commands. Package archive ownership, actual install/upgrade/removal, real calendar expiry, suspend/resume and boot cleanup must also be validated in a disposable VM before claiming release readiness. Changes to the common library require integration checks on the downstream update, migration, installer, package-picker and diagnostic PRs. diff --git a/manual/48-security.md b/manual/48-security.md index 86028a230f6c..6db0dff5f17c 100644 --- a/manual/48-security.md +++ b/manual/48-security.md @@ -22,6 +22,8 @@ It works by restoring the baseline snapshot the installer takes, so it's only av Sometimes you want `sudo` to stop asking, most often when an AI agent is doing a long stretch of system work for you. _Setup > Security > Passwordless Sudo_ turns that off for 15 wall-clock minutes and then puts it back automatically, including immediately after resuming from a suspend that crossed the deadline. A package-owned boot-time cleanup rule removes the grant before logins if the computer restarts first. Run the command again before the timer runs out to end it early, and pass your own number of minutes (from 1 to 1440) with `omarchy-sudo-passwordless 30` if 15 isn't enough. +Updating or removing Omarchy's settings package ends any temporary grant before its expiry support changes. If the command reports an authorization or cleanup error, resolve it before trying to enable another grant; an error does not mean passwordless access is inactive. + Be clear-eyed about this one: while it's on, anything running as your user can do anything as root without being asked. That's the whole point, and it's also the whole risk. ## Signing Keys diff --git a/test/shell.d/nopasswd-sudo-expiry-test.sh b/test/shell.d/nopasswd-sudo-expiry-test.sh index 6d54633ca133..06965215f0aa 100755 --- a/test/shell.d/nopasswd-sudo-expiry-test.sh +++ b/test/shell.d/nopasswd-sudo-expiry-test.sh @@ -13,7 +13,7 @@ trap 'rm -rf "$test_tmp"' EXIT function_prefix() { printf 'source %q\n' "$security_library_path" - awk '/^source .*omarchy-security-functions/ { next } /^case "\$\{1:-\}" in$/ { exit } { print }' "$command_path" + awk '/^set -euo pipefail$/ { functions=1 } /^case "\$\{1:-\}" in$/ { exit } functions { print }' "$command_path" } # Exercise the validation code itself. Leading zeroes remain numeric, but zero, @@ -23,7 +23,7 @@ function_prefix() { for minutes in 1 15 1440 00015; do valid_minutes "$minutes" || fail "passwordless sudo accepts bounded duration $minutes" done - for minutes in 0 1441 -1 1m '1;id' ''; do + for minutes in 0 1441 -1 1m '1;id' '' 18446744073709551617; do ! valid_minutes "$minutes" || fail "passwordless sudo rejects invalid duration '$minutes'" done ) @@ -45,8 +45,6 @@ pass "passwordless sudo derives and validates trusted account identity" # model that publishes a token only when -N is missing. grep -Fxq '#!/bin/bash -p' "$command_path" || fail "passwordless sudo no longer suppresses Bash startup injection" -grep -F '[[ ${argv[1]:-} == -p ]]' "$security_library_path" >/dev/null || - fail "passwordless sudo accepts a decoy post-script -p" public_sudo_stub="$test_tmp/public-sudo" public_gum_stub="$test_tmp/public-gum" @@ -67,19 +65,20 @@ if [[ ${1:-} == -N ]]; then no_update=1; shift; fi [[ ${1:-} != -- ]] || shift ((no_update)) || : >"$TEST_PUBLIC_TOKEN" case "${2:-}" in - __status) exit 1 ;; + __status) exit "${TEST_PUBLIC_STATUS:-3}" ;; __enable|__disable) exit 0 ;; *) exit 2 ;; esac STUB cat >"$public_gum_stub" <<'STUB' #!/bin/bash +[[ -z ${TEST_PUBLIC_GUM_LOG:-} ]] || : >"$TEST_PUBLIC_GUM_LOG" [[ ! -e $TEST_PUBLIC_TOKEN ]] || : >"$TEST_PUBLIC_EXPLOIT" exit 1 STUB chmod 0755 "$public_sudo_stub" "$public_gum_stub" public_flow="$test_tmp/passwordless-public-flow" -/usr/bin/cp "$security_library_path" "$test_tmp/omarchy-security-functions" +/usr/bin/sed "s#/usr/bin/sudo#$public_sudo_stub#g" "$security_library_path" >"$test_tmp/omarchy-security-functions" /usr/bin/sed \ -e "s#/usr/bin/sudo#$public_sudo_stub#g" \ -e "s#/usr/bin/gum#$public_gum_stub#g" \ @@ -89,6 +88,16 @@ TEST_PUBLIC_TOKEN="$public_token" TEST_PUBLIC_EXPLOIT="$public_exploit" \ /usr/bin/bash -p "$public_flow" 15 >/dev/null [[ ! -e $public_token && ! -e $public_exploit ]] || fail "passwordless confirmation inherited a reusable status credential" +for status in 1 2; do + if TEST_PUBLIC_TOKEN="$public_token" TEST_PUBLIC_EXPLOIT="$public_exploit" \ + TEST_PUBLIC_STATUS="$status" TEST_PUBLIC_GUM_LOG="$test_tmp/unsafe-status-confirmation" \ + /usr/bin/bash -p "$public_flow" 15 >"$test_tmp/status-error.output" 2>&1; then + fail "passwordless sudo treats status/authorization failure $status as inactive" + fi + [[ ! -e $test_tmp/unsafe-status-confirmation ]] || fail "failed status inspection opens the enable prompt" + grep -q 'Could not safely inspect passwordless sudo' "$test_tmp/status-error.output" || + fail "failed status inspection lacks recovery guidance" +done startup_env="$test_tmp/passwordless-bash-env" startup_marker="$test_tmp/passwordless-bash-env-ran" @@ -341,6 +350,9 @@ pkgs_candidates=( pkgs_root="" for candidate in "${pkgs_candidates[@]}"; do if [[ -n $candidate && -d $candidate/pkgbuilds/omarchy-settings ]]; then + pkgs_root=$candidate/pkgbuilds + break + elif [[ -n $candidate && -d $candidate/omarchy-settings ]]; then pkgs_root=$candidate break fi @@ -348,31 +360,36 @@ done [[ -n $pkgs_root ]] || fail "omarchy-pkgs checkout found for passwordless package-removal coverage" for package_name in omarchy-settings omarchy-settings-dev; do - install_script="$pkgs_root/pkgbuilds/$package_name/$package_name.install" + install_script="$pkgs_root/$package_name/$package_name.install" transformed_install="$test_tmp/$package_name.install" removal_root="$test_tmp/$package_name-remove" removal_sudoers="$removal_root/etc/sudoers.d" - mkdir -p "$removal_sudoers" + mkdir -p "$removal_sudoers" "$removal_root/run/lock" "$removal_root/etc/tmpfiles.d" : >"$removal_sudoers/99-omarchy-nopasswd-1000" : >"$removal_sudoers/99-omarchy-nopasswd-legacy-user" : >"$removal_sudoers/omarchy-dns" - ln -s ../usr/share/omarchy/etc-overrides/os-release "$removal_root/etc/os-release" - grep -Fq 'ln -s ../usr/share/omarchy/etc-overrides/os-release /etc/os-release' "$install_script" || - fail "$package_name installation does not select package-owned OS metadata" - sed "s#/etc/#$removal_root/etc/#g" "$install_script" >"$transformed_install" + ln -s ../administrator/os-release "$removal_root/etc/os-release" + package_stat="$test_tmp/package-stat" + cat >"$package_stat" <<'STUB' +#!/bin/bash +if [[ $2 == '%u' ]]; then printf '0\n'; else /usr/bin/stat "$@"; fi +STUB + chmod +x "$package_stat" + sed -e "s#/etc/#$removal_root/etc/#g" \ + -e "s#/run#$removal_root/run#g" \ + -e "s#/usr/bin/stat#$package_stat#g" "$install_script" >"$transformed_install" ( source "$transformed_install" + pre_remove + [[ -f $removal_root/run/omarchy-sudo-passwordless-package-removing ]] post_remove ) || fail "$package_name removal revokes active passwordless grants" ! find "$removal_sudoers" -name '99-omarchy-nopasswd-*' -print -quit | grep -q . || fail "$package_name removal leaves a passwordless grant behind" [[ -e $removal_sudoers/omarchy-dns ]] || fail "$package_name removal deletes an unrelated sudoers policy" - [[ -L $removal_root/etc/os-release ]] && - [[ $(readlink "$removal_root/etc/os-release") == ../usr/lib/os-release ]] || - fail "$package_name removal does not restore the standard OS selector" - - ln -sfn ../administrator/os-release "$removal_root/etc/os-release" + [[ $(readlink "$removal_root/etc/os-release") == ../administrator/os-release ]] || + fail "$package_name removal changes unrelated OS metadata" : >"$removal_sudoers/99-omarchy-nopasswd-1001" ( source "$transformed_install" @@ -382,8 +399,23 @@ for package_name in omarchy-settings omarchy-settings-dev; do fail "$package_name removal overwrites an administrator OS selector" [[ ! -e $removal_sudoers/99-omarchy-nopasswd-1001 ]] || fail "$package_name removal grant cleanup depends on OS selector state" + + ( + source "$transformed_install" + _etc_overrides_apply() { :; } + if post_install; then exit 1; fi + [[ -f $removal_root/run/omarchy-sudo-passwordless-package-removing ]] + : >"$removal_root/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf" + post_install + [[ ! -e $removal_root/run/omarchy-sudo-passwordless-package-removing ]] + : >"$removal_sudoers/99-omarchy-nopasswd-1002" + pre_upgrade + [[ ! -e $removal_sudoers/99-omarchy-nopasswd-1002 ]] + post_upgrade + [[ ! -e $removal_root/run/omarchy-sudo-passwordless-package-removing ]] + ) || fail "$package_name restores grant availability only after boot cleanup is installed" done -pass "settings package removal revokes grants and preserves package-selector ownership" +pass "settings package transitions revoke grants and preserve unrelated configuration" # Exercise the production flock wrapper under contention. mkdir is an atomic # overlap detector; all workers must enter and leave the protected region. @@ -418,7 +450,7 @@ pass "passwordless sudo serializes concurrent operations" # Same-boot expiry calls the fixed installed cleanup command, and cleanup # removes policy before touching a timer so timer failures cannot extend it. -grep -F '"$INSTALLED_SELF" __expire "$uid"' "$command_path" >/dev/null +grep -F '"$INSTALLED_SELF" __expire "$uid" "$timer"' "$command_path" >/dev/null cleanup_body=$(awk '/^cleanup_uid_locked\(\) \{/ { in_body=1 } in_body { print } in_body && /^}/ { exit }' "$command_path") rm_line=$(grep -n '/usr/bin/rm -f' <<<"$cleanup_body" | head -1 | cut -d: -f1) stop_line=$(grep -n 'stop_timer' <<<"$cleanup_body" | tail -1 | cut -d: -f1) diff --git a/test/shell.d/passwordless-grant-lifecycle-test.sh b/test/shell.d/passwordless-grant-lifecycle-test.sh new file mode 100644 index 000000000000..c70d69e5ebf0 --- /dev/null +++ b/test/shell.d/passwordless-grant-lifecycle-test.sh @@ -0,0 +1,199 @@ +#!/bin/bash + +set -euo pipefail +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +test_tmp=$(mktemp -d) +children=() +cleanup() { + local status=$? + trap - EXIT + if (( ${#children[@]} )); then + kill "${children[@]}" 2>/dev/null || true + wait "${children[@]}" 2>/dev/null || true + fi + rm -rf "$test_tmp" + exit "$status" +} +trap cleanup EXIT + +# All policy, state, locks and command mutations stay in this private fixture. +# Native visudo validates inert fragments; no test installs host sudo policy. +mkdir -p "$test_tmp/bin" "$test_tmp/state" "$test_tmp/etc/sudoers.d" "$test_tmp/etc/tmpfiles.d" "$test_tmp/run/lock" +export TEST_GRANT_ROOT="$test_tmp" +cat >"$test_tmp/bin/stat" <<'STUB' +#!/bin/bash +case $2 in + '%u') printf '0\n' ;; + '%a') if [[ -d ${@: -1} ]]; then printf '755\n'; else printf '644\n'; fi ;; + '%u %a') if [[ -d ${@: -1} ]]; then printf '0 755\n'; else printf '0 644\n'; fi ;; + *) exec /usr/bin/stat "$@" ;; +esac +STUB +cat >"$test_tmp/bin/install" <<'STUB' +#!/bin/bash +args=() +while (($#)); do + case $1 in -o|-g) shift 2 ;; *) args+=("$1"); shift ;; esac +done +exec /usr/bin/install "${args[@]}" +STUB +cat >"$test_tmp/bin/rm" <<'STUB' +#!/bin/bash +for path in "$@"; do + if [[ ${TEST_FAIL_TEMP_CLEANUP:-0} == 1 && $path == "$TEST_GRANT_ROOT/state/".sudoers.* ]]; then exit 1; fi + if [[ ${TEST_FAIL_RULE_DELETE:-0} == 1 && $path == "$TEST_GRANT_ROOT/etc/sudoers.d/"* ]]; then exit 1; fi +done +exec /usr/bin/rm "$@" +STUB +cat >"$test_tmp/bin/systemctl" <<'STUB' +#!/bin/bash +printf '%s\n' "$*" >>"$TEST_GRANT_ROOT/systemctl.log" +exit 0 +STUB +chmod +x "$test_tmp/bin/"* +library="$test_tmp/grant-functions.sh" +{ + printf 'source %q\n' "$ROOT/bin/omarchy-security-functions" + awk '/^set -euo pipefail$/ { functions=1 } /^case "\$\{1:-\}" in$/ { exit } functions { print }' "$ROOT/bin/omarchy-sudo-passwordless" +} | sed \ + -e "s|/var/lib/omarchy/sudo-passwordless|$test_tmp/state|g" \ + -e "s|/etc/sudoers.d|$test_tmp/etc/sudoers.d|g" \ + -e "s|/etc/tmpfiles.d|$test_tmp/etc/tmpfiles.d|g" \ + -e "s|/run/lock/omarchy-sudo-passwordless.lock|$test_tmp/run/lock/omarchy-sudo-passwordless.lock|g" \ + -e "s|/run/omarchy-sudo-passwordless-package-removing|$test_tmp/run/omarchy-sudo-passwordless-package-removing|g" \ + -e "s|/usr/bin/stat|$test_tmp/bin/stat|g" \ + -e "s|/usr/bin/install|$test_tmp/bin/install|g" \ + -e "s|/usr/bin/rm|$test_tmp/bin/rm|g" \ + -e "s|/usr/bin/systemctl|$test_tmp/bin/systemctl|g" \ + -e 's|/usr/bin/chown|/usr/bin/true|g' >"$library" + +printf 'r! /etc/sudoers.d/99-omarchy-nopasswd-*\n' >"$test_tmp/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf" +# The expected policy text is mapped along with its filename in this fixture. +sed -i "s|/etc/sudoers.d|$test_tmp/etc/sudoers.d|" "$test_tmp/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf" + +( + source "$library" + for name in 'buildbot$' audituser aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; do + valid_account_name "$name" || fail "supported account name rejected: $name" + printf '%s ALL=(ALL) NOPASSWD: ALL\n' "$name" >"$test_tmp/name-policy" + /usr/sbin/visudo -cf "$test_tmp/name-policy" >/dev/null + done + for name in 'a$b' '$' aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; do + ! valid_account_name "$name" || fail "invalid account name accepted" + done + ! valid_uid 18446744073709551617 || fail "overflowed UID accepted" + printf 'buildbot$ ALL=(ALL) NOPASSWD: ALL\n' >"$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-buildbot$" + remove_known_legacy_rules + [[ ! -e $test_tmp/etc/sudoers.d/99-omarchy-nopasswd-buildbot\$ ]] +) || fail "supported account names and legacy cleanup disagree" +pass "provisioning-compatible names validate as sudoers and clean up correctly" + +transaction_setup() { + resolve_account() { ACCOUNT_NAME=audituser; ACCOUNT_UID=1000; } + prepare_root_state() { :; } + start_expiry_timer() { printf '%s\n' "$3" >>"$test_tmp/armed"; } + stop_timer() { printf '%s\n' "$1" >>"$test_tmp/stopped"; } +} + +( + source "$library" + transaction_setup + TEST_FAIL_TEMP_CLEANUP=1 enable_locked 1000 15 && exit 1 + [[ ! -e $(rule_file 1000) && ! -e $(state_file 1000) && -s $test_tmp/stopped ]] +) || fail "post-publication cleanup failure did not revoke before timer cleanup" +pass "failed temporary cleanup after publication revokes the live policy" + +rm -f "$test_tmp/stopped" +( + source "$library" + transaction_setup + TEST_FAIL_TEMP_CLEANUP=1 TEST_FAIL_RULE_DELETE=1 enable_locked 1000 15 && exit 1 + [[ -f $(rule_file 1000) && -f $(state_file 1000) && ! -e $test_tmp/stopped ]] + if TEST_FAIL_RULE_DELETE=1 revoke_inactive_grant 1000; then exit 1; else status=$?; fi + (( status == 2 )) +) || fail "failed policy revocation disarmed expiry or claimed inactive status" +pass "failed revocation preserves expiry jobs and returns a distinct error" + +( + source "$library" + transaction_setup + current_timer=$(read_state_timer 1000) + expire_locked 1000 omarchy-nopasswd-expire-1000-ffffffffffffffffffffffffffffffff + [[ -f $(rule_file 1000) ]] + expire_locked 1000 + [[ -f $(rule_file 1000) ]] + expire_locked 1000 "$current_timer" + [[ ! -e $(rule_file 1000) ]] +) || fail "a predecessor timer invalidates its replacement" +pass "old and legacy timer callbacks preserve a newer valid grant" + +( + source "$library" + transaction_setup + start_expiry_timer() { + : >"$REMOVAL_BLOCKER" + return 0 + } + enable_locked 1000 15 && exit 1 + [[ ! -e $(rule_file 1000) ]] +) || fail "publication ignores a lost package prerequisite" +rm "$test_tmp/run/omarchy-sudo-passwordless-package-removing" +pass "grant publication rechecks package availability after timer setup" + +pkgs_path=${OMARCHY_PKGS_PATH:-$ROOT/../omarchy-pkgs} +[[ ! -d $pkgs_path/pkgbuilds ]] || pkgs_path=$pkgs_path/pkgbuilds +package_script="$pkgs_path/omarchy-settings/omarchy-settings.install" +[[ -f $package_script ]] || fail "package checkout is required for shared lifecycle coverage" +sed -e "s|/etc/|$test_tmp/etc/|g" \ + -e "s|/run|$test_tmp/run|g" \ + -e "s|/usr/bin/stat|$test_tmp/bin/stat|g" \ + -e "s|/usr/bin/rm|$test_tmp/bin/rm|g" "$package_script" >"$test_tmp/package.install" + +worker="$test_tmp/publisher.sh" +{ + printf '#!/bin/bash\nset -euo pipefail\nsource %q\n' "$library" + declare -f transaction_setup + printf 'test_tmp=%q\ntransaction_setup\n' "$test_tmp" + cat <<'WORKER' +publish_rule() { + : >"$test_tmp/publisher.entered" + while [[ ! -e $test_tmp/publisher.release ]]; do sleep 0.02; done + printf 'audituser ALL=(ALL) NOPASSWD: ALL\n' >"$(rule_file "$1")" +} +with_root_lock enable_locked 1000 15 +WORKER +} >"$worker" +bash "$worker" >"$test_tmp/publisher.output" 2>&1 & +children+=("$!") +for ((attempt = 0; attempt < 250; attempt++)); do + [[ ! -e $test_tmp/publisher.entered ]] || break + sleep 0.02 +done +[[ -e $test_tmp/publisher.entered ]] || fail "grant publisher did not enter the shared lock" +bash -euo pipefail -c 'source "$1"; : >"$2"; pre_remove; post_remove' bash \ + "$test_tmp/package.install" "$test_tmp/removal.started" >"$test_tmp/removal.output" 2>&1 & +children+=("$!") +for ((attempt = 0; attempt < 250; attempt++)); do + [[ ! -e $test_tmp/removal.started ]] || break + sleep 0.02 +done +[[ -e $test_tmp/removal.started ]] || fail "package removal did not start" +touch "$test_tmp/publisher.release" +for child in "${children[@]}"; do wait "$child" || fail "shared lifecycle worker failed"; done +children=() +[[ ! -e $test_tmp/etc/sudoers.d/99-omarchy-nopasswd-1000 ]] || fail "removal left a concurrently published grant" +[[ -f $test_tmp/run/omarchy-sudo-passwordless-package-removing ]] || fail "removal did not block later publication" +( + source "$library" + transaction_setup + ! with_root_lock enable_locked 1000 15 +) || fail "a publisher can create a grant after package removal begins" +pass "package removal shares the grant lock and blocks later publication" + +printf 'audituser ALL=(ALL) NOPASSWD: ALL\n' >"$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-1000" +if TEST_FAIL_RULE_DELETE=1 bash -euo pipefail -c 'source "$1"; post_remove' bash "$test_tmp/package.install" >"$test_tmp/removal-failure.output" 2>&1; then + fail "package removal hid a failed policy deletion" +fi +grep -q 'Administrator cleanup is required' "$test_tmp/removal-failure.output" || fail "package deletion failure lacks recovery guidance" +pass "package removal reports cleanup failures instead of successful revocation" From a6385e60b836f41895fd016bf170c9b62128c59a Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Mon, 7 Sep 2026 22:17:32 +0100 Subject: [PATCH 036/194] Bound sudo policy natively and guard expiry package transactions --- bin/omarchy-sudo-passwordless | 70 ++++++++++++++----- .../hooks/05-omarchy-passwordless-revoke.hook | 12 ++++ docs/passwordless-sudo.md | 6 +- .../passwordless-grant-lifecycle-test.sh | 38 +++++++++- 4 files changed, 106 insertions(+), 20 deletions(-) create mode 100644 default/libalpm/hooks/05-omarchy-passwordless-revoke.hook diff --git a/bin/omarchy-sudo-passwordless b/bin/omarchy-sudo-passwordless index 5f7cd1dc7507..92d7ae168a78 100755 --- a/bin/omarchy-sudo-passwordless +++ b/bin/omarchy-sudo-passwordless @@ -28,6 +28,7 @@ readonly STATE_DIR=/var/lib/omarchy/sudo-passwordless readonly RUNTIME_DIR=/run/omarchy/sudo-passwordless readonly LOCK_FILE=/run/lock/omarchy-sudo-passwordless.lock readonly BOOT_CLEANUP_FILE=/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf +readonly PACKAGE_HOOK=/usr/share/libalpm/hooks/05-omarchy-passwordless-revoke.hook readonly REMOVAL_BLOCKER=/run/omarchy-sudo-passwordless-package-removing readonly INSTALLED_SELF=/usr/bin/omarchy-sudo-passwordless readonly STATUS_INACTIVE=3 @@ -182,7 +183,11 @@ classify_generated_rule() { if [[ $suffix =~ ^[0-9]+$ ]]; then name=${contents%' ALL=(ALL) NOPASSWD: ALL'} - valid_account_name "$name" && [[ $contents == "$name ALL=(ALL) NOPASSWD: ALL" ]] + if valid_account_name "$name" && [[ $contents == "$name ALL=(ALL) NOPASSWD: ALL" ]]; then + return 0 + fi + name=${contents%%' ALL=(ALL) NOTAFTER='*} + valid_account_name "$name" && [[ $contents =~ ^[a-z_][a-z0-9_-]*\$?\ ALL=\(ALL\)\ NOTAFTER=[0-9]{14}Z\ NOPASSWD:\ ALL$ ]] elif valid_account_name "$suffix" && [[ $contents == "$suffix ALL=(ALL) NOPASSWD: ALL" ]]; then GENERATED_RULE_LEGACY_TIMER="omarchy-nopasswd-expire-${suffix}" else @@ -256,17 +261,16 @@ cleanup_all_locked() { return "$failed" } -verify_boot_cleanup() { - local owner mode canonical current active_rules - [[ ! -e $REMOVAL_BLOCKER && ! -L $REMOVAL_BLOCKER ]] || return 1 - [[ -f $BOOT_CLEANUP_FILE && ! -L $BOOT_CLEANUP_FILE ]] || return 1 - canonical=$(/usr/bin/realpath -e -- "$BOOT_CLEANUP_FILE") || return 1 - [[ $canonical == "$BOOT_CLEANUP_FILE" ]] || return 1 - owner=$(/usr/bin/stat -Lc '%u' -- "$BOOT_CLEANUP_FILE") || return 1 - mode=$(/usr/bin/stat -Lc '%a' -- "$BOOT_CLEANUP_FILE") || return 1 +verify_root_policy_file() { + local file=$1 owner mode canonical current + [[ -f $file && ! -L $file ]] || return 1 + canonical=$(/usr/bin/realpath -e -- "$file") || return 1 + [[ $canonical == "$file" ]] || return 1 + owner=$(/usr/bin/stat -Lc '%u' -- "$file") || return 1 + mode=$(/usr/bin/stat -Lc '%a' -- "$file") || return 1 [[ $owner == 0 && $mode =~ ^[0-7]+$ ]] && ! ((8#$mode & 022)) || return 1 - current=${BOOT_CLEANUP_FILE%/*} + current=${file%/*} while :; do [[ -d $current && ! -L $current ]] || return 1 canonical=$(/usr/bin/realpath -e -- "$current") || return 1 @@ -277,9 +281,36 @@ verify_boot_cleanup() { current=${current%/*} [[ -n $current ]] || current=/ done +} +verify_boot_cleanup() { + local active_rules hook + [[ ! -e $REMOVAL_BLOCKER && ! -L $REMOVAL_BLOCKER ]] || return 1 + verify_root_policy_file "$BOOT_CLEANUP_FILE" || return 1 active_rules=$(/usr/bin/awk '!/^[[:space:]]*(#|$)/ { print }' "$BOOT_CLEANUP_FILE") || return 1 - [[ $active_rules == 'r! /etc/sudoers.d/99-omarchy-nopasswd-*' ]] + [[ $active_rules == 'r! /etc/sudoers.d/99-omarchy-nopasswd-*' ]] || return 1 + verify_root_policy_file "$PACKAGE_HOOK" || return 1 + hook=$(/usr/bin/cat -- "$PACKAGE_HOOK") || return 1 + [[ $hook == '[Trigger] +Operation = Upgrade +Operation = Remove +Type = Package +Target = omarchy-settings +Target = omarchy-settings-dev + +[Action] +Description = Revoking temporary Omarchy sudo grants before settings changes... +When = PreTransaction +Exec = /usr/bin/omarchy-sudo-passwordless __package-removing +AbortOnFail' ]] +} + +package_removing_locked() { + # ALPM must abort before removing the helper or boot cleanup if revocation + # fails. The marker also blocks publication after this lock is released. + (umask 077; : >"$REMOVAL_BLOCKER") || return 1 + /usr/bin/rm -f -- /etc/sudoers.d/99-omarchy-nopasswd-* || return 1 + cleanup_all_locked } prepare_state_file() { @@ -306,10 +337,13 @@ start_expiry_timer() { } publish_rule() { - local uid="$1" name="$2" destination tmp + local uid="$1" name="$2" expires="$3" destination tmp deadline + valid_expiry "$expires" || return 1 + deadline=$(/usr/bin/date -u -d "@$expires" +%Y%m%d%H%M%SZ) || return 1 + [[ $deadline =~ ^[0-9]{14}Z$ ]] || return 1 destination=$(rule_file "$uid") tmp=$(/usr/bin/mktemp "$STATE_DIR/.sudoers.XXXXXX") || return 1 - if ! /usr/bin/printf '%s ALL=(ALL) NOPASSWD: ALL\n' "$name" >"$tmp" || + if ! /usr/bin/printf '%s ALL=(ALL) NOTAFTER=%s NOPASSWD: ALL\n' "$name" "$deadline" >"$tmp" || ! /usr/bin/chown root:root "$tmp" || ! /usr/bin/chmod 0440 "$tmp" || ! /usr/sbin/visudo -cf "$tmp" >/dev/null || ! /usr/bin/install -o root -g root -m 0440 -- "$tmp" "$destination"; then @@ -339,7 +373,7 @@ enable_locked() { valid_minutes "$minutes" || return 1 prepare_root_state || return 1 verify_boot_cleanup || { - echo "omarchy-sudo-passwordless: package-owned boot cleanup rule is missing or unsafe" >&2 + echo "omarchy-sudo-passwordless: package-owned boot cleanup or transaction hook is missing or unsafe" >&2 return 1 } @@ -363,7 +397,7 @@ enable_locked() { abort_enable_locked "$uid" "$timer" "$old_timer" "$pending_state" return 1 fi - if ! verify_boot_cleanup || ! publish_rule "$uid" "$ACCOUNT_NAME"; then + if ! verify_boot_cleanup || ! publish_rule "$uid" "$ACCOUNT_NAME" "$expires"; then abort_enable_locked "$uid" "$timer" "$old_timer" "$pending_state" return 1 fi @@ -464,12 +498,16 @@ root_dispatch() { (($# == 0)) && ((EUID == 0)) || return 1 with_root_lock cleanup_all_locked ;; + __package-removing) + (($# == 0)) && ((EUID == 0)) || return 1 + with_root_lock package_removing_locked + ;; *) return 1 ;; esac } case "${1:-}" in - __status|__enable|__disable|__expire|__cleanup-all) + __status|__enable|__disable|__expire|__cleanup-all|__package-removing) action=$1 shift root_dispatch "$action" "$@" diff --git a/default/libalpm/hooks/05-omarchy-passwordless-revoke.hook b/default/libalpm/hooks/05-omarchy-passwordless-revoke.hook new file mode 100644 index 000000000000..f0bce15d324d --- /dev/null +++ b/default/libalpm/hooks/05-omarchy-passwordless-revoke.hook @@ -0,0 +1,12 @@ +[Trigger] +Operation = Upgrade +Operation = Remove +Type = Package +Target = omarchy-settings +Target = omarchy-settings-dev + +[Action] +Description = Revoking temporary Omarchy sudo grants before settings changes... +When = PreTransaction +Exec = /usr/bin/omarchy-sudo-passwordless __package-removing +AbortOnFail diff --git a/docs/passwordless-sudo.md b/docs/passwordless-sudo.md index b97160e460f8..0e805e6a2ee7 100644 --- a/docs/passwordless-sudo.md +++ b/docs/passwordless-sudo.md @@ -4,7 +4,7 @@ ## Grant lifecycle -Root state records the resolved account name, absolute expiry epoch and unique timer name. A calendar timer is armed and verified before the generated policy becomes active. Publication rechecks the package-owned boot cleanup before and after installing policy. Policy revocation must succeed before expiry jobs are stopped; a deletion error leaves those jobs armed and reports that administrator cleanup is required. +Root state records the resolved account name, absolute expiry epoch and unique timer name. A calendar timer is armed and verified before the generated policy becomes active. The sudoers rule also embeds the same UTC deadline with `NOTAFTER`, so sudo independently rejects it after expiry even if timer cleanup is delayed. Publication rechecks the package-owned boot cleanup before and after installing policy. Policy revocation must succeed before expiry jobs are stopped; a deletion error leaves those jobs armed and reports that administrator cleanup is required. An internal status result is `0` for an active, validated grant and `3` for confirmed inactive access. All other results are errors, including failed authentication and failed revocation. The user interface only offers a new grant after result `3`. It must not turn an inspection failure into a claim that no grant exists. @@ -12,9 +12,9 @@ Each new expiry callback carries its timer identity. A delayed predecessor canno ## Package ownership -The packaging companion must put the publication/expiry command, `omarchy-security-functions` and `omarchy-nopasswd-sudo.conf` in the settings package together. Removing the desktop runtime alone must leave a working expiry command behind. Stable and development package pairs must transfer ownership in one transaction without duplicate files. +The packaging companion must put the publication/expiry command, `omarchy-security-functions` `omarchy-nopasswd-sudo.conf` and the pre-transaction revocation hook in the settings package together. Removing the desktop runtime alone must leave a working expiry command behind. Stable and development package pairs must transfer ownership in one transaction without duplicate files. -Before settings removal or upgrade, its scriptlet acquires the same grant lock, sets `/run/omarchy-sudo-passwordless-package-removing` and revokes existing policy. The marker prevents a waiting publisher from creating a new grant while package files change. A successful installation clears the marker only after boot cleanup exists. Failed scriptlet cleanup returns an error and prints recovery guidance; a package-manager scriptlet failure must not be represented as an automatic transaction rollback. +Before settings removal or upgrade, the installed ALPM `PreTransaction` hook invokes the fixed `__package-removing` action, acquires the same grant lock, sets `/run/omarchy-sudo-passwordless-package-removing` and revokes existing policy. The marker prevents a waiting publisher from creating a new grant while package files change. A successful installation clears the marker only after boot cleanup exists. The hook uses `AbortOnFail` because a scriptlet failure alone does not abort pacman. The scriptlets repeat cleanup as a fallback for upgrades from older packages that have no installed hook. New grants require both the boot rule and hook before publication. Failed or interrupted transactions leave the marker set; retry the package transaction successfully before requesting another grant. The runtime marker need not survive reboot: pre-removal revokes the old grants before package files disappear, and a new invocation independently verifies boot cleanup. Both root operations use fixed machine paths. The marker is not a user-controlled mode switch. diff --git a/test/shell.d/passwordless-grant-lifecycle-test.sh b/test/shell.d/passwordless-grant-lifecycle-test.sh index c70d69e5ebf0..b3198405642b 100644 --- a/test/shell.d/passwordless-grant-lifecycle-test.sh +++ b/test/shell.d/passwordless-grant-lifecycle-test.sh @@ -19,7 +19,7 @@ trap cleanup EXIT # All policy, state, locks and command mutations stay in this private fixture. # Native visudo validates inert fragments; no test installs host sudo policy. -mkdir -p "$test_tmp/bin" "$test_tmp/state" "$test_tmp/etc/sudoers.d" "$test_tmp/etc/tmpfiles.d" "$test_tmp/run/lock" +mkdir -p "$test_tmp/bin" "$test_tmp/state" "$test_tmp/etc/sudoers.d" "$test_tmp/etc/tmpfiles.d" "$test_tmp/run/lock" "$test_tmp/hooks" export TEST_GRANT_ROOT="$test_tmp" cat >"$test_tmp/bin/stat" <<'STUB' #!/bin/bash @@ -60,6 +60,7 @@ library="$test_tmp/grant-functions.sh" -e "s|/var/lib/omarchy/sudo-passwordless|$test_tmp/state|g" \ -e "s|/etc/sudoers.d|$test_tmp/etc/sudoers.d|g" \ -e "s|/etc/tmpfiles.d|$test_tmp/etc/tmpfiles.d|g" \ + -e "s|/usr/share/libalpm/hooks|$test_tmp/hooks|g" \ -e "s|/run/lock/omarchy-sudo-passwordless.lock|$test_tmp/run/lock/omarchy-sudo-passwordless.lock|g" \ -e "s|/run/omarchy-sudo-passwordless-package-removing|$test_tmp/run/omarchy-sudo-passwordless-package-removing|g" \ -e "s|/usr/bin/stat|$test_tmp/bin/stat|g" \ @@ -68,6 +69,8 @@ library="$test_tmp/grant-functions.sh" -e "s|/usr/bin/systemctl|$test_tmp/bin/systemctl|g" \ -e 's|/usr/bin/chown|/usr/bin/true|g' >"$library" +cp "$ROOT/default/libalpm/hooks/05-omarchy-passwordless-revoke.hook" "$test_tmp/hooks/" + printf 'r! /etc/sudoers.d/99-omarchy-nopasswd-*\n' >"$test_tmp/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf" # The expected policy text is mapped along with its filename in this fixture. sed -i "s|/etc/sudoers.d|$test_tmp/etc/sudoers.d|" "$test_tmp/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf" @@ -197,3 +200,36 @@ if TEST_FAIL_RULE_DELETE=1 bash -euo pipefail -c 'source "$1"; post_remove' bash fi grep -q 'Administrator cleanup is required' "$test_tmp/removal-failure.output" || fail "package deletion failure lacks recovery guidance" pass "package removal reports cleanup failures instead of successful revocation" + +( + source "$library" + transaction_setup + rm -f "$REMOVAL_BLOCKER" + enable_locked 1000 5 + record=$(read_state_record 1000) + expiry=${record#*$'\t'} + expiry=${expiry%%$'\t'*} + deadline=$(/usr/bin/date -u -d "@$expiry" +%Y%m%d%H%M%SZ) + [[ $(cat "$(rule_file 1000)") == "audituser ALL=(ALL) NOTAFTER=$deadline NOPASSWD: ALL" ]] + /usr/sbin/visudo -cf "$(rule_file 1000)" >/dev/null + classify_generated_rule "$(rule_file 1000)" + rm -f "$(state_file 1000)" + remove_known_legacy_rules + [[ ! -e $(rule_file 1000) ]] +) || fail "native sudo deadline or state-independent bounded rule cleanup is incorrect" +pass "sudo policy contains the same deadline and bounded orphan rules are recognized" + +( + source "$library" + transaction_setup + rm -f "$REMOVAL_BLOCKER" + enable_locked 1000 5 + if TEST_FAIL_RULE_DELETE=1 package_removing_locked; then exit 1; fi + [[ -f $REMOVAL_BLOCKER && -f $(rule_file 1000) ]] + ! enable_locked 1000 5 + package_removing_locked + [[ ! -e $(rule_file 1000) ]] + rm -f "$REMOVAL_BLOCKER" "$PACKAGE_HOOK" + ! enable_locked 1000 5 +) || fail "pre-transaction revocation error or missing hook does not prevent new grants" +pass "package hook fails closed and grants require its installed policy" From bb13b55698e327f41364fc60d3b1dd0e2f4c7d03 Mon Sep 17 00:00:00 2001 From: Taksh Date: Tue, 8 Sep 2026 14:59:34 +0530 Subject: [PATCH 037/194] fix: keep Sublime on the editor menu and persist subl A when: subl guard hid the row before install, which is how the editor gets packaged. Map stored sublime_text to subl so an existing default stays ticked, and update the default-apps tests for the PATH name. --- bin/omarchy-default-editor | 3 +++ default/omarchy/omarchy-menu.jsonc | 2 +- test/shell.d/default-apps-test.sh | 4 ++-- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/bin/omarchy-default-editor b/bin/omarchy-default-editor index 1e82e17245da..33e395531aa4 100755 --- a/bin/omarchy-default-editor +++ b/bin/omarchy-default-editor @@ -17,6 +17,9 @@ if (($# == 0)); then read -r editor <"$editor_file" fi + # sublime-text-4 ships `subl`; older defaults stored `sublime_text`. + [[ $editor == sublime_text ]] && editor=subl + [[ -n $editor ]] && echo "$editor" || echo "nvim" exit 0 fi diff --git a/default/omarchy/omarchy-menu.jsonc b/default/omarchy/omarchy-menu.jsonc index ef1a53ce6d39..e9826b220d98 100644 --- a/default/omarchy/omarchy-menu.jsonc +++ b/default/omarchy/omarchy-menu.jsonc @@ -164,7 +164,7 @@ "setup.default.editor.vscode": {"icon":"","label":"VSCode","checked":"[[ \"$(omarchy-default-editor)\" == \"code\" ]]","action":"omarchy-default-editor code"}, "setup.default.editor.cursor": {"icon":"","label":"Cursor","checked":"[[ \"$(omarchy-default-editor)\" == \"cursor\" ]]","action":"omarchy-default-editor cursor"}, "setup.default.editor.zed": {"icon":"","label":"Zed","checked":"[[ \"$(omarchy-default-editor)\" == \"zeditor\" ]]","action":"omarchy-default-editor zed"}, - "setup.default.editor.sublime": {"icon":"","label":"Sublime Text","when":"omarchy-cmd-present subl","checked":"[[ \"$(omarchy-default-editor)\" == \"subl\" ]]","action":"omarchy-default-editor sublime_text"}, + "setup.default.editor.sublime": {"icon":"","label":"Sublime Text","checked":"[[ \"$(omarchy-default-editor)\" == \"subl\" ]]","action":"omarchy-default-editor sublime_text"}, "setup.default.editor.helix": {"icon":"","label":"Helix","checked":"[[ \"$(omarchy-default-editor)\" == \"helix\" ]]","action":"omarchy-default-editor helix"}, "setup.default.editor.vim": {"icon":"","label":"Vim","checked":"[[ \"$(omarchy-default-editor)\" == \"vim\" ]]","action":"omarchy-default-editor vim"}, "setup.default.editor.emacs": {"icon":"","label":"Emacs","checked":"[[ \"$(omarchy-default-editor)\" == \"emacs\" ]]","action":"omarchy-default-editor emacs"}, diff --git a/test/shell.d/default-apps-test.sh b/test/shell.d/default-apps-test.sh index 8151c250fd21..d4aaa26a46d3 100755 --- a/test/shell.d/default-apps-test.sh +++ b/test/shell.d/default-apps-test.sh @@ -69,7 +69,7 @@ omarchy-pkg-add|omarchy-pkg-aur-add) firefox) command=firefox ;; zen-browser-bin) command=zen-browser ;; cursor-bin) command=cursor ;; - sublime-text-4) command=sublime_text ;; + sublime-text-4) command=subl ;; vim) command=vim ;; neovim) command=nvim ;; esac @@ -169,7 +169,7 @@ editor_cases=( 'code code editor:vscode' 'cursor cursor pkg:cursor-bin' 'zed zeditor editor:zed' - 'sublime_text sublime_text pkg:sublime-text-4' + 'sublime_text subl pkg:sublime-text-4' 'helix helix editor:helix' 'vim vim pkg:vim' 'emacs emacs editor:emacs' From 5bfc8b5cc3403971388e03c192e0afec9b570574 Mon Sep 17 00:00:00 2001 From: Erik Melton Date: Tue, 8 Sep 2026 19:47:11 +0200 Subject: [PATCH 038/194] Update packaging companion instructions for clarity Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- docs/passwordless-sudo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/passwordless-sudo.md b/docs/passwordless-sudo.md index 0e805e6a2ee7..9c58b2910ddf 100644 --- a/docs/passwordless-sudo.md +++ b/docs/passwordless-sudo.md @@ -12,7 +12,7 @@ Each new expiry callback carries its timer identity. A delayed predecessor canno ## Package ownership -The packaging companion must put the publication/expiry command, `omarchy-security-functions` `omarchy-nopasswd-sudo.conf` and the pre-transaction revocation hook in the settings package together. Removing the desktop runtime alone must leave a working expiry command behind. Stable and development package pairs must transfer ownership in one transaction without duplicate files. +The packaging companion must put the publication/expiry command, `omarchy-security-functions`, `omarchy-nopasswd-sudo.conf`, and the pre-transaction revocation hook in the settings package together. Removing the desktop runtime alone must leave a working expiry command behind. Stable and development package pairs must transfer ownership in one transaction without duplicate files. Before settings removal or upgrade, the installed ALPM `PreTransaction` hook invokes the fixed `__package-removing` action, acquires the same grant lock, sets `/run/omarchy-sudo-passwordless-package-removing` and revokes existing policy. The marker prevents a waiting publisher from creating a new grant while package files change. A successful installation clears the marker only after boot cleanup exists. The hook uses `AbortOnFail` because a scriptlet failure alone does not abort pacman. The scriptlets repeat cleanup as a fallback for upgrades from older packages that have no installed hook. New grants require both the boot rule and hook before publication. Failed or interrupted transactions leave the marker set; retry the package transaction successfully before requesting another grant. From 212a4540396101c02b8c31bbe5cb1428191e0624 Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Thu, 10 Sep 2026 15:12:11 +0100 Subject: [PATCH 039/194] Clarify update hook timing in the user manual --- manual/31-dotfiles.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/manual/31-dotfiles.md b/manual/31-dotfiles.md index ec148b445b14..a81a6596adb5 100644 --- a/manual/31-dotfiles.md +++ b/manual/31-dotfiles.md @@ -37,12 +37,14 @@ Omarchy fires hooks at a handful of moments, and you can hang your own scripts o | Event | When it runs | | ----- | ------------ | | `post-boot` | Right after the desktop has started | -| `post-update` | During `omarchy update`, after packages and migrations | -| `pre-refresh-pacman` | Before `omarchy refresh pacman` re-syncs the package config | +| `post-update` | Near the end of `omarchy update`, after packages, migrations, and service restarts, before mise tools are updated | +| `pre-refresh-pacman` | After `omarchy refresh pacman` re-syncs the package config and finishes updating packages; during a channel switch, after the package switch and complete update finish | | `theme-set` | After a theme change (theme name in `$1`) | | `font-set` | After a font change (font name in `$1`) | | `battery-low` | When the battery gets low (percentage in `$1`) | +The `pre-refresh-pacman` name is kept for compatibility. Its edits to the refreshed package config apply to future package operations, after the current transaction has finished. Both update-related hooks run as your user after Omarchy clears its cached sudo authorization, so a hook that uses `sudo` needs its own authorization and may ask for your password. + Each of those directories already holds a `.sample` file showing the shape of a hook — drop the `.sample` from the name to put it to work. To install a script you've written elsewhere, use `omarchy hook install post-boot ~/my-hook`, which copies it in and makes it executable. ### Adding your own menu entries From c46f321680744bc8a53c069e4571595fdabde067 Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Thu, 10 Sep 2026 22:01:09 +0100 Subject: [PATCH 040/194] Simplify passwordless sudo grant lifecycle --- bin/omarchy-sudo-passwordless | 404 ++++--------- docs/passwordless-sudo.md | 10 +- migrations/1788163635.sh | 8 +- .../fixtures/passwordless-sudo-test.sh | 125 ++++ test/shell.d/nopasswd-sudo-expiry-test.sh | 563 +++++------------- .../passwordless-grant-lifecycle-test.sh | 329 ++++------ 6 files changed, 510 insertions(+), 929 deletions(-) create mode 100644 test/shell.d/fixtures/passwordless-sudo-test.sh diff --git a/bin/omarchy-sudo-passwordless b/bin/omarchy-sudo-passwordless index 92d7ae168a78..91695c69e1ff 100755 --- a/bin/omarchy-sudo-passwordless +++ b/bin/omarchy-sudo-passwordless @@ -24,12 +24,11 @@ set -euo pipefail readonly DEFAULT_MINUTES=15 readonly MAX_MINUTES=1440 -readonly STATE_DIR=/var/lib/omarchy/sudo-passwordless -readonly RUNTIME_DIR=/run/omarchy/sudo-passwordless readonly LOCK_FILE=/run/lock/omarchy-sudo-passwordless.lock readonly BOOT_CLEANUP_FILE=/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf readonly PACKAGE_HOOK=/usr/share/libalpm/hooks/05-omarchy-passwordless-revoke.hook readonly REMOVAL_BLOCKER=/run/omarchy-sudo-passwordless-package-removing +readonly MIGRATION_MARKER=/var/lib/omarchy/migrations/1788163635 readonly INSTALLED_SELF=/usr/bin/omarchy-sudo-passwordless readonly STATUS_INACTIVE=3 @@ -73,26 +72,6 @@ verify_sudo_caller() { resolve_account "$requested_uid" } -prepare_root_state() { - omarchy_security_assert_root_directory /var 755 || return 1 - [[ -d /var/lib && ! -L /var/lib ]] || return 1 - [[ $(/usr/bin/stat -Lc '%u' /var/lib) == 0 ]] || return 1 - ! ((8#$(/usr/bin/stat -Lc '%a' /var/lib) & 022)) || return 1 - - if [[ ! -e /var/lib/omarchy && ! -L /var/lib/omarchy ]]; then - /usr/bin/install -d -o root -g root -m 0755 /var/lib/omarchy || return 1 - fi - omarchy_security_assert_root_directory /var/lib/omarchy 755 || return 1 - omarchy_security_prepare_private_root_directory "$STATE_DIR" /var/lib/omarchy || return 1 - - omarchy_security_assert_root_directory /run 755 || return 1 - if [[ ! -e /run/omarchy && ! -L /run/omarchy ]]; then - /usr/bin/install -d -o root -g root -m 0755 /run/omarchy || return 1 - fi - omarchy_security_assert_root_directory /run/omarchy 755 || return 1 - omarchy_security_prepare_private_root_directory "$RUNTIME_DIR" /run/omarchy -} - with_root_lock() { local fd rc=0 # The boot cleanup cannot depend on STATE_DIR or RUNTIME_DIR being healthy: @@ -116,67 +95,23 @@ rule_file() { printf '/etc/sudoers.d/99-omarchy-nopasswd-%s' "$1" } -state_file() { - printf '%s/%s.state' "$STATE_DIR" "$1" -} - -read_state_record() { - local uid="$1" file state_uid name expires timer canonical_uid - local -a lines=() - valid_uid "$uid" || return 1 - canonical_uid=$((10#$uid)) - file=$(state_file "$uid") - [[ -f $file && ! -L $file ]] || return 1 - mapfile -t lines <"$file" || return 1 - (( ${#lines[@]} == 4 )) || return 1 - [[ ${lines[0]} == UID=* && ${lines[1]} == USER=* && - ${lines[2]} == EXPIRES=* && ${lines[3]} == TIMER=* ]] || return 1 - state_uid=${lines[0]#UID=} - name=${lines[1]#USER=} - expires=${lines[2]#EXPIRES=} - timer=${lines[3]#TIMER=} - [[ $state_uid == "$canonical_uid" ]] || return 1 - valid_account_name "$name" || return 1 - [[ $expires =~ ^[1-9][0-9]{0,10}$ ]] || return 1 - [[ $timer =~ ^omarchy-nopasswd-expire-${canonical_uid}-[0-9a-f]{32}$ ]] || return 1 - printf '%s\t%s\t%s' "$name" "$expires" "$timer" -} - -read_state_timer() { - local record - record=$(read_state_record "$1") || return 1 - printf '%s' "${record##*$'\t'}" -} - -current_epoch() { - local now - now=$(/usr/bin/date +%s) || return 1 - [[ $now =~ ^[1-9][0-9]{0,10}$ ]] || return 1 - printf '%s' "$now" -} - -valid_expiry() { - [[ $1 =~ ^[1-9][0-9]{0,10}$ ]] -} - -valid_timer_for_uid() { - local uid="$1" timer="$2" - valid_uid "$uid" || return 1 - uid=$((10#$uid)) - [[ $timer =~ ^omarchy-nopasswd-expire-${uid}-[0-9a-f]{32}$ ]] -} - -stop_timer() { - local timer="$1" - [[ $timer =~ ^omarchy-nopasswd-expire-[0-9]+-[0-9a-f]{32}$ ]] || return 0 - /usr/bin/systemctl stop "${timer}.timer" "${timer}.service" >/dev/null 2>&1 || true - /usr/bin/systemctl reset-failed "${timer}.timer" "${timer}.service" >/dev/null 2>&1 || true +# The sudoers rule is the only grant record. A missing file is distinct from +# an unreadable, unsafe, or administrator-modified file. +read_grant() { + local file contents + file=$(rule_file "$1") + [[ -e $file || -L $file ]] || return "$STATUS_INACTIVE" + verify_root_path "$file" && [[ -f $file ]] || return 2 + contents=$(/usr/bin/cat -- "$file") || return 2 + [[ $contents =~ ^([a-z_][a-z0-9_-]*\$?)\ ALL=\(ALL\)\ NOTAFTER=([0-9]{14}Z)\ NOPASSWD:\ ALL$ ]] || return 2 + GRANT_NAME=${BASH_REMATCH[1]} + GRANT_DEADLINE=${BASH_REMATCH[2]} + valid_account_name "$GRANT_NAME" || return 2 } classify_generated_rule() { local file=$1 suffix contents name - GENERATED_RULE_LEGACY_TIMER="" [[ -f $file && ! -L $file ]] || return 1 contents=$(/usr/bin/cat -- "$file") || return 2 suffix=${file##*/99-omarchy-nopasswd-} @@ -189,81 +124,40 @@ classify_generated_rule() { name=${contents%%' ALL=(ALL) NOTAFTER='*} valid_account_name "$name" && [[ $contents =~ ^[a-z_][a-z0-9_-]*\$?\ ALL=\(ALL\)\ NOTAFTER=[0-9]{14}Z\ NOPASSWD:\ ALL$ ]] elif valid_account_name "$suffix" && [[ $contents == "$suffix ALL=(ALL) NOPASSWD: ALL" ]]; then - GENERATED_RULE_LEGACY_TIMER="omarchy-nopasswd-expire-${suffix}" + return 0 else return 1 fi } -remove_known_legacy_rules() { - local file classification failed=0 - shopt -s nullglob - for file in /etc/sudoers.d/99-omarchy-nopasswd-*; do - if classify_generated_rule "$file"; then - # A crash after publishing the numeric rule but before its state rename - # must not survive the next boot. Do not require the account to still - # exist: a deleted account could otherwise make the rule immortal and a - # later username reuse could activate it again. - if /usr/bin/rm -f -- "$file" && [[ ! -e $file && ! -L $file ]]; then - [[ -z $GENERATED_RULE_LEGACY_TIMER ]] || - /usr/bin/systemctl stop "${GENERATED_RULE_LEGACY_TIMER}.timer" \ - "${GENERATED_RULE_LEGACY_TIMER}.service" >/dev/null 2>&1 || true - else - failed=1 - fi - else - classification=$? - # An unreadable candidate cannot be proven inert. A symlink, non-file, - # or administrator-authored body is unrelated and remains untouched. - (( classification == 1 )) || failed=1 - fi - done - shopt -u nullglob - return "$failed" -} - cleanup_uid_locked() { - local uid="$1" timer="" - valid_uid "$uid" || return 1 - timer=$(read_state_timer "$uid" 2>/dev/null || true) - # Remove policy first. A failed timer stop can only leave an inert cleanup - # job behind, never extend passwordless access. - /usr/bin/rm -f -- "$(rule_file "$uid")" || return 1 - [[ ! -e $(rule_file "$uid") && ! -L $(rule_file "$uid") ]] || return 1 - /usr/bin/rm -f -- "$(state_file "$uid")" || return 1 - [[ -z $timer ]] || stop_timer "$timer" + local file + file=$(rule_file "$1") + [[ -e $file || -L $file ]] || return 0 + verify_root_path "$file" && classify_generated_rule "$file" || return 1 + /usr/bin/rm -f -- "$file" && [[ ! -e $file && ! -L $file ]] } cleanup_all_locked() { - local state uid failed=0 file classification - shopt -s nullglob - for state in "$STATE_DIR"/*.state; do - uid=${state##*/} - uid=${uid%.state} - if valid_uid "$uid" && ! cleanup_uid_locked "$uid"; then failed=1; fi - done - shopt -u nullglob - remove_known_legacy_rules || failed=1 - - # Never report a successful boot cleanup while an exact rule emitted by any - # Omarchy implementation is still active. Administrator-extended files do - # not match these complete bodies and remain untouched. - shopt -s nullglob + local file classification failed=0 + verify_root_path /etc/sudoers.d || return 1 for file in /etc/sudoers.d/99-omarchy-nopasswd-*; do + [[ -e $file || -L $file ]] || continue if classify_generated_rule "$file"; then - failed=1 + if ! /usr/bin/rm -f -- "$file" || [[ -e $file || -L $file ]]; then + failed=1 + fi else classification=$? (( classification == 1 )) || failed=1 fi done - shopt -u nullglob return "$failed" } -verify_root_policy_file() { +verify_root_path() { local file=$1 owner mode canonical current - [[ -f $file && ! -L $file ]] || return 1 + [[ ( -f $file || -d $file ) && ! -L $file ]] || return 1 canonical=$(/usr/bin/realpath -e -- "$file") || return 1 [[ $canonical == "$file" ]] || return 1 owner=$(/usr/bin/stat -Lc '%u' -- "$file") || return 1 @@ -286,10 +180,10 @@ verify_root_policy_file() { verify_boot_cleanup() { local active_rules hook [[ ! -e $REMOVAL_BLOCKER && ! -L $REMOVAL_BLOCKER ]] || return 1 - verify_root_policy_file "$BOOT_CLEANUP_FILE" || return 1 + verify_root_path "$BOOT_CLEANUP_FILE" || return 1 active_rules=$(/usr/bin/awk '!/^[[:space:]]*(#|$)/ { print }' "$BOOT_CLEANUP_FILE") || return 1 [[ $active_rules == 'r! /etc/sudoers.d/99-omarchy-nopasswd-*' ]] || return 1 - verify_root_policy_file "$PACKAGE_HOOK" || return 1 + verify_root_path "$PACKAGE_HOOK" || return 1 hook=$(/usr/bin/cat -- "$PACKAGE_HOOK") || return 1 [[ $hook == '[Trigger] Operation = Upgrade @@ -313,165 +207,112 @@ package_removing_locked() { cleanup_all_locked } -prepare_state_file() { - local uid="$1" name="$2" expires="$3" timer="$4" tmp - tmp=$(/usr/bin/mktemp "$STATE_DIR/.state.XXXXXX") || return 1 - if ! /usr/bin/printf 'UID=%s\nUSER=%s\nEXPIRES=%s\nTIMER=%s\n' \ - "$uid" "$name" "$expires" "$timer" >"$tmp" || - ! /usr/bin/chown root:root "$tmp" || ! /usr/bin/chmod 0600 "$tmp"; then - /usr/bin/rm -f -- "$tmp" - return 1 - fi - printf '%s' "$tmp" -} - -start_expiry_timer() { - local uid="$1" expires="$2" timer="$3" - valid_uid "$uid" && valid_expiry "$expires" && valid_timer_for_uid "$uid" "$timer" || return 1 - # Calendar timers use CLOCK_REALTIME and catch up immediately after resume; - # a monotonic OnActiveSec timer pauses while the machine is suspended. - /usr/bin/systemd-run --quiet --collect --on-calendar="@${expires}" \ - --timer-property=AccuracySec=1s --unit="$timer" \ - -- "$INSTALLED_SELF" __expire "$uid" "$timer" || return 1 - /usr/bin/systemctl is-active --quiet "${timer}.timer" +migration_complete() { + [[ -f $MIGRATION_MARKER && ! -s $MIGRATION_MARKER ]] && verify_root_path "$MIGRATION_MARKER" } -publish_rule() { - local uid="$1" name="$2" expires="$3" destination tmp deadline - valid_expiry "$expires" || return 1 - deadline=$(/usr/bin/date -u -d "@$expires" +%Y%m%d%H%M%SZ) || return 1 - [[ $deadline =~ ^[0-9]{14}Z$ ]] || return 1 - destination=$(rule_file "$uid") - tmp=$(/usr/bin/mktemp "$STATE_DIR/.sudoers.XXXXXX") || return 1 - if ! /usr/bin/printf '%s ALL=(ALL) NOTAFTER=%s NOPASSWD: ALL\n' "$name" "$deadline" >"$tmp" || - ! /usr/bin/chown root:root "$tmp" || ! /usr/bin/chmod 0440 "$tmp" || - ! /usr/sbin/visudo -cf "$tmp" >/dev/null || - ! /usr/bin/install -o root -g root -m 0440 -- "$tmp" "$destination"; then - /usr/bin/rm -f -- "$tmp" - return 1 +migrate_locked() { + local directory + if migration_complete; then + return 0 fi - /usr/bin/rm -f -- "$tmp" + [[ ! -e $MIGRATION_MARKER && ! -L $MIGRATION_MARKER ]] || return 1 + verify_root_path /var/lib || return 1 + for directory in /var/lib/omarchy /var/lib/omarchy/migrations; do + if [[ ! -e $directory && ! -L $directory ]]; then + /usr/bin/install -d -o root -g root -m 0755 -- "$directory" || return 1 + fi + verify_root_path "$directory" || return 1 + done + cleanup_all_locked || return 1 + # The empty marker is written only after cleanup succeeds, under the same + # machine lock. Later accounts need no sudo and cannot revoke newer grants. + /usr/bin/install -o root -g root -m 0644 /dev/null "$MIGRATION_MARKER" } -abort_enable_locked() { - local uid=$1 timer=$2 old_timer=$3 pending_state=$4 - # Publication can install policy and then fail while cleaning its temporary - # file. Never disarm either expiry job until policy revocation is confirmed. - if cleanup_uid_locked "$uid"; then - stop_timer "$timer" - [[ -z $old_timer ]] || stop_timer "$old_timer" +# Old callbacks only remove an expired current rule. Renewing a grant never +# needs a second state file or a stored timer generation to identify it. +expire_locked() { + local status now + if read_grant "$1"; then + now=$(/usr/bin/date -u +%Y%m%d%H%M%SZ) || return 2 + [[ $now < $GRANT_DEADLINE ]] && return 0 + cleanup_uid_locked "$1" else - echo "Could not revoke passwordless sudo after a failed grant; expiry jobs remain armed. Administrator cleanup is required." >&2 - fi - /usr/bin/rm -f -- "$pending_state" || true - return 1 -} - -enable_locked() { - local uid="$1" minutes="$2" old_timer="" timer token expires pending_state now - resolve_account "$uid" || return 1 - valid_minutes "$minutes" || return 1 - prepare_root_state || return 1 - verify_boot_cleanup || { - echo "omarchy-sudo-passwordless: package-owned boot cleanup or transaction hook is missing or unsafe" >&2 - return 1 - } - - old_timer=$(read_state_timer "$uid" 2>/dev/null || true) - token=$(/usr/bin/tr -d '-' = 10#$expires)) || ! /usr/bin/systemctl is-active --quiet "${timer}.timer" || ! verify_boot_cleanup; then - # The timer may have expired or failed between its initial verification and - # rule publication. Revoke synchronously so a suspended or heavily loaded - # machine cannot turn a short grant into a reboot-long one. - abort_enable_locked "$uid" "$timer" "$old_timer" "$pending_state" - return 1 + status=$? + if (( status == STATUS_INACTIVE )); then + return 0 + else + cleanup_uid_locked "$1" + fi fi - [[ -z $old_timer || $old_timer == "$timer" ]] || stop_timer "$old_timer" } status_locked() { - local uid="$1" record state_name expires timer now remainder - resolve_account "$uid" || return 2 - if [[ ! -e $(rule_file "$uid") && ! -L $(rule_file "$uid") ]]; then + local status now + resolve_account "$1" || return 2 + if read_grant "$1"; then + [[ $GRANT_NAME == "$ACCOUNT_NAME" ]] || return 2 + now=$(/usr/bin/date -u +%Y%m%d%H%M%SZ) || return 2 + if [[ $now < $GRANT_DEADLINE ]]; then + return 0 + fi + cleanup_uid_locked "$1" || return 2 return "$STATUS_INACTIVE" + else + status=$? + return "$status" fi - record=$(read_state_record "$uid") || { - revoke_inactive_grant "$uid" - return $? - } - state_name=${record%%$'\t'*} - remainder=${record#*$'\t'} - expires=${remainder%%$'\t'*} - timer=${record##*$'\t'} - [[ $state_name == "$ACCOUNT_NAME" ]] || { - revoke_inactive_grant "$uid" - return $? - } - now=$(current_epoch) || { - revoke_inactive_grant "$uid" - return $? - } - ((10#$now < 10#$expires)) || { - revoke_inactive_grant "$uid" - return $? - } - /usr/bin/systemctl is-active --quiet "${timer}.timer" || { - revoke_inactive_grant "$uid" - return $? - } } -revoke_inactive_grant() { - if cleanup_uid_locked "$1"; then - return "$STATUS_INACTIVE" - else - echo "Could not revoke invalid or expired passwordless sudo. Administrator cleanup is required." >&2 - return 2 +finish_enable() { + local status=$? + trap - EXIT HUP INT TERM + if (( status != 0 )); then + if cleanup_uid_locked "$uid"; then + [[ -z $timer ]] || /usr/bin/systemctl stop "$timer.timer" "$timer.service" >/dev/null 2>&1 || true + else + echo "Could not revoke passwordless sudo; expiry remains armed. Administrator cleanup is required." >&2 + fi fi + [[ -z $pending ]] || /usr/bin/rm -f -- "$pending" + exit "$status" } -expire_locked() { - local uid=$1 timer=${2:-} current_timer status - if [[ -n $timer ]]; then - current_timer=$(read_state_timer "$uid" 2>/dev/null || true) - # A delayed predecessor must not revoke a newer, independently timed grant. - [[ -z $current_timer || $current_timer == "$timer" ]] || return 0 - cleanup_uid_locked "$uid" - elif status_locked "$uid"; then - # Compatibility with already scheduled UID-only jobs: enforce the current - # grant's expiry instead of letting an old timer shorten its replacement. - return 0 +enable_locked() ( + local uid=$1 minutes=$2 now expires deadline token timer="" pending="" file status + resolve_account "$uid" && valid_minutes "$minutes" || return 1 + verify_boot_cleanup && verify_root_path /etc/sudoers.d || return 1 + file=$(rule_file "$uid") + if read_grant "$uid"; then + [[ $GRANT_NAME == "$ACCOUNT_NAME" ]] || return 1 else status=$? - (( status == STATUS_INACTIVE )) + (( status == STATUS_INACTIVE )) || return 1 fi -} + trap finish_enable EXIT + omarchy_security_install_signal_exit_traps + now=$(/usr/bin/date +%s) || return 1 + expires=$((now + 10#$minutes * 60)) + deadline=$(/usr/bin/date -u -d "@$expires" +%Y%m%d%H%M%SZ) || return 1 + pending=$(/usr/bin/mktemp /etc/sudoers.d/.omarchy-nopasswd.XXXXXX) || return 1 + /usr/bin/printf '%s ALL=(ALL) NOTAFTER=%s NOPASSWD: ALL\n' "$ACCOUNT_NAME" "$deadline" >"$pending" || return 1 + /usr/bin/chown root:root "$pending" && /usr/bin/chmod 0440 "$pending" || return 1 + /usr/sbin/visudo -cf "$pending" >/dev/null || return 1 + token=$(/usr/bin/tr -d '-' /dev/null || true + wait "${children[@]}" 2>/dev/null || true + fi + rm -rf "$test_tmp" + exit "$status" +} +trap cleanup_grant_fixture EXIT +export TEST_GRANT_ROOT=$test_tmp +mkdir -p "$test_tmp/bin" "$test_tmp/etc/sudoers.d" "$test_tmp/etc/tmpfiles.d" "$test_tmp/run/lock" "$test_tmp/var/lib" "$test_tmp/hooks" +cat >"$test_tmp/bin/mock" <<'STUB' +#!/bin/bash +set -euo pipefail +name=${0##*/} +printf '%s %s\n' "$name" "$*" >>"$TEST_GRANT_ROOT/commands" +case "$name" in + stat) + path=${@: -1} + owner=0 + mode=$(/usr/bin/stat -Lc '%a' -- "$path") + [[ $path != /tmp ]] || mode=755 + [[ $path != "${TEST_BAD_PATH:-}" ]] || owner=1000 + case $2 in + '%u') echo "$owner" ;; + '%a') echo "$mode" ;; + '%u %a') echo "$owner $mode" ;; + *) exec /usr/bin/stat "$@" ;; + esac + ;; + chown) exit 0 ;; + install) + args=() + while (($#)); do + case $1 in -o|-g) shift 2 ;; *) args+=("$1"); shift ;; esac + done + exec /usr/bin/install "${args[@]}" + ;; + rm) + for path in "$@"; do + if [[ ${TEST_DELETE_FAIL:-0} == 1 && $path == "$TEST_GRANT_ROOT/etc/sudoers.d/99-omarchy-nopasswd-1000" ]]; then exit 1; fi + done + exec /usr/bin/rm "$@" + ;; + mv) + [[ ${TEST_PUBLISH_FAIL:-0} != 1 ]] || exit 1 + /usr/bin/mv "$@" + [[ ${TEST_POST_PUBLISH_FAIL:-0} != 1 ]] || : >"$TEST_GRANT_ROOT/run/omarchy-sudo-passwordless-package-removing" + ;; + systemd-run) + [[ ${TEST_TIMER_FAIL:-0} != 1 ]] || exit 1 + if [[ ${TEST_CANCEL_ENABLE:-0} == 1 ]]; then kill -TERM "$PPID"; fi + ;; + systemctl) + [[ $1 != "is-active" || ${TEST_INACTIVE_TIMER:-0} != 1 ]] + ;; + date) + if [[ ${TEST_EXPIRED:-0} == 1 && $* == '-u +%Y%m%d%H%M%SZ' ]]; then echo 99991231235959Z; else /usr/bin/date "$@"; fi + ;; + getent) printf '%s:x:1000:1000:Test:/nonexistent:/bin/bash\n' "${TEST_ACCOUNT:-audituser}" ;; + sudo) + if [[ ${1:-} == -h ]]; then echo 'usage: sudo [-N] command'; exit 0; fi + if [[ ${1:-} == -k ]]; then exit 0; fi + if [[ ${1:-} == -N ]]; then shift; fi + if [[ ${1:-} == -- ]]; then shift; fi + if [[ ${TEST_MIGRATION:-0} == 1 ]]; then + [[ ${TEST_NO_SUDO:-0} != 1 ]] || exit 1 + TEST_EUID=0 /usr/bin/bash -p "$@" + else + [[ ${2:-} != __status ]] || exit "${TEST_STATUS:-3}" + fi + ;; + gum) exit 1 ;; + *) exit 99 ;; +esac +STUB +chmod +x "$test_tmp/bin/mock" +for name in stat chown install rm mv systemd-run systemctl date getent sudo gum; do + ln -s mock "$test_tmp/bin/$name" +done + +python3 - "$ROOT" "$test_tmp" <<'PY' +from pathlib import Path +import sys +root, temp = map(Path, sys.argv[1:]) +for name in ('omarchy-sudo-passwordless', 'omarchy-security-functions'): + text = (root/'bin'/name).read_text() + for path in ('/etc/', '/var/lib', '/run/', '/usr/share/libalpm/hooks'): + target = str(temp/'hooks') if path == '/usr/share/libalpm/hooks' else str(temp) + path + text = text.replace(path, target) + text = text.replace('((EUID == 0))', '((${TEST_EUID:-1} == 0))') + for command in ('stat', 'chown', 'install', 'rm', 'mv', 'systemd-run', 'systemctl', 'date', 'getent', 'sudo', 'gum'): + text = text.replace('/usr/bin/' + command, str(temp/'bin'/command)) + (temp/name).write_text(text) + (temp/name).chmod(0o755) +PY +library="$test_tmp/functions.sh" +{ + printf 'source %q\n' "$test_tmp/omarchy-security-functions" + awk '/^set -euo pipefail$/ { functions=1 } /^case "\$\{1:-\}" in$/ { exit } functions { print }' "$test_tmp/omarchy-sudo-passwordless" +} >"$library" +cp "$ROOT/default/libalpm/hooks/05-omarchy-passwordless-revoke.hook" "$test_tmp/hooks/" +sed "s|/etc/|$test_tmp/etc/|g" "$ROOT/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf" >"$test_tmp/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf" +: >"$test_tmp/commands" + +# New subshell per case prevents one test's overrides and readonly constants +# from affecting the next. External commands log enough to verify ordering. +assert_status() { + local expected=$1 actual=0 + shift + "$@" || actual=$? + (( actual == expected )) || fail "expected status $expected, got $actual from $*" +} +reset_grant() { + rm -f "$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-1000" "$test_tmp/run/omarchy-sudo-passwordless-package-removing" + : >"$test_tmp/commands" +} diff --git a/test/shell.d/nopasswd-sudo-expiry-test.sh b/test/shell.d/nopasswd-sudo-expiry-test.sh index 06965215f0aa..173ea1b00c0b 100755 --- a/test/shell.d/nopasswd-sudo-expiry-test.sh +++ b/test/shell.d/nopasswd-sudo-expiry-test.sh @@ -1,458 +1,163 @@ #!/bin/bash set -euo pipefail - source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" +source "$SHELL_TEST_DIR/fixtures/passwordless-sudo-test.sh" -command_path="$ROOT/bin/omarchy-sudo-passwordless" -security_library_path="$ROOT/bin/omarchy-security-functions" -tmpfiles_path="$ROOT/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf" -migration_path="$ROOT/migrations/1788163635.sh" -test_tmp=$(mktemp -d) -trap 'rm -rf "$test_tmp"' EXIT - -function_prefix() { - printf 'source %q\n' "$security_library_path" - awk '/^set -euo pipefail$/ { functions=1 } /^case "\$\{1:-\}" in$/ { exit } functions { print }' "$command_path" -} - -# Exercise the validation code itself. Leading zeroes remain numeric, but zero, -# negatives, oversized grants, and shell syntax are rejected. ( - source <(function_prefix) - for minutes in 1 15 1440 00015; do - valid_minutes "$minutes" || fail "passwordless sudo accepts bounded duration $minutes" - done - for minutes in 0 1441 -1 1m '1;id' '' 18446744073709551617; do - ! valid_minutes "$minutes" || fail "passwordless sudo rejects invalid duration '$minutes'" - done + source "$library" + for minutes in 1 15 1440 00015; do valid_minutes "$minutes" || exit 1; done + for minutes in 0 1441 -1 1m '' 18446744073709551617; do ! valid_minutes "$minutes" || exit 1; done + for name in audituser 'buildbot$'; do valid_account_name "$name" || exit 1; done + for name in 'a$b' '$' aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; do ! valid_account_name "$name" || exit 1; done + ! valid_uid 18446744073709551617 ) -pass "passwordless sudo validates a bounded positive duration" +pass "duration and account validation retains bounded inputs and trailing-dollar usernames" -# The public entry point uses the kernel-backed numeric identity; $USER is -# never interpolated into a privileged filename or sudoers rule. -grep -F 'uid=$(/usr/bin/id -u)' "$command_path" >/dev/null || - fail "passwordless sudo derives the caller from id -u" -! grep -Eq '\$\{?USER\}?' "$command_path" || - fail "passwordless sudo does not trust USER for privileged policy" -grep -F '[[ ${SUDO_UID:-} =~ ^[0-9]+$ ]]' "$command_path" >/dev/null || - fail "passwordless sudo validates sudo provenance" -pass "passwordless sudo derives and validates trusted account identity" - -# Status inspection and the confirmation UI are mixed-trust: a normal sudo -# status call would publish a timestamp that a hostile prompt helper could use -# even when the user declines the grant. Exercise the public flow with a sudo -# model that publishes a token only when -N is missing. -grep -Fxq '#!/bin/bash -p' "$command_path" || - fail "passwordless sudo no longer suppresses Bash startup injection" - -public_sudo_stub="$test_tmp/public-sudo" -public_gum_stub="$test_tmp/public-gum" -public_token="$test_tmp/public-token" -public_exploit="$test_tmp/public-exploit" -cat >"$public_sudo_stub" <<'STUB' -#!/bin/bash -if [[ ${1:-} == -h ]]; then - echo 'usage: sudo [-ABbEHkNnPS] command' - exit 0 -fi -if [[ ${1:-} == -k ]]; then - rm -f -- "$TEST_PUBLIC_TOKEN" - exit 0 -fi -no_update=0 -if [[ ${1:-} == -N ]]; then no_update=1; shift; fi -[[ ${1:-} != -- ]] || shift -((no_update)) || : >"$TEST_PUBLIC_TOKEN" -case "${2:-}" in - __status) exit "${TEST_PUBLIC_STATUS:-3}" ;; - __enable|__disable) exit 0 ;; - *) exit 2 ;; -esac -STUB -cat >"$public_gum_stub" <<'STUB' -#!/bin/bash -[[ -z ${TEST_PUBLIC_GUM_LOG:-} ]] || : >"$TEST_PUBLIC_GUM_LOG" -[[ ! -e $TEST_PUBLIC_TOKEN ]] || : >"$TEST_PUBLIC_EXPLOIT" -exit 1 -STUB -chmod 0755 "$public_sudo_stub" "$public_gum_stub" -public_flow="$test_tmp/passwordless-public-flow" -/usr/bin/sed "s#/usr/bin/sudo#$public_sudo_stub#g" "$security_library_path" >"$test_tmp/omarchy-security-functions" -/usr/bin/sed \ - -e "s#/usr/bin/sudo#$public_sudo_stub#g" \ - -e "s#/usr/bin/gum#$public_gum_stub#g" \ - "$command_path" >"$public_flow" -chmod 0755 "$public_flow" -TEST_PUBLIC_TOKEN="$public_token" TEST_PUBLIC_EXPLOIT="$public_exploit" \ - /usr/bin/bash -p "$public_flow" 15 >/dev/null -[[ ! -e $public_token && ! -e $public_exploit ]] || - fail "passwordless confirmation inherited a reusable status credential" -for status in 1 2; do - if TEST_PUBLIC_TOKEN="$public_token" TEST_PUBLIC_EXPLOIT="$public_exploit" \ - TEST_PUBLIC_STATUS="$status" TEST_PUBLIC_GUM_LOG="$test_tmp/unsafe-status-confirmation" \ - /usr/bin/bash -p "$public_flow" 15 >"$test_tmp/status-error.output" 2>&1; then - fail "passwordless sudo treats status/authorization failure $status as inactive" +( + source "$library" + assert_status 2 root_dispatch __status 1000 + assert_status 2 env TEST_EUID=0 SUDO_UID=1001 /usr/bin/bash -p "$test_tmp/omarchy-sudo-passwordless" __status 1000 + assert_status 3 env TEST_EUID=0 SUDO_UID=1000 /usr/bin/bash -p "$test_tmp/omarchy-sudo-passwordless" __status 1000 +) +pass "internal actions reject missing root and mismatched sudo identity" + +for status in 1 2 3; do + : >"$test_tmp/commands" + result=0 + TEST_STATUS=$status /usr/bin/bash -p "$test_tmp/omarchy-sudo-passwordless" 15 >"$test_tmp/public.log" 2>&1 || result=$? + if (( status == 3 )); then + (( result == 0 )) && grep -q '^gum confirm ' "$test_tmp/commands" || fail "inactive status must allow confirmation" + else + (( result != 0 )) && ! grep -q '^gum ' "$test_tmp/commands" || fail "inspection errors must not offer enablement" fi - [[ ! -e $test_tmp/unsafe-status-confirmation ]] || fail "failed status inspection opens the enable prompt" - grep -q 'Could not safely inspect passwordless sudo' "$test_tmp/status-error.output" || - fail "failed status inspection lacks recovery guidance" + grep -q '^sudo -N -- .* __status ' "$test_tmp/commands" || fail "status must not publish reusable authorization" + [[ $(tail -1 "$test_tmp/commands") == 'sudo -k' ]] || fail "public exit must revoke its authorization" done +pass "public status distinguishes inactive from errors and revokes authorization on exit" -startup_env="$test_tmp/passwordless-bash-env" -startup_marker="$test_tmp/passwordless-bash-env-ran" -cat >"$startup_env" <<'STUB' -: >"$TEST_STARTUP_MARKER" -set -o privileged -unset BASH_ENV -STUB -if BASH_ENV="$startup_env" TEST_STARTUP_MARKER="$startup_marker" \ - /usr/bin/bash "$public_flow" -p >/dev/null 2>&1; then - fail "passwordless sudo accepted an unsafe interpreter with a decoy -p" +printf ': >"$TEST_STARTUP_MARKER"\nset -o privileged\nunset BASH_ENV\n' >"$test_tmp/startup" +: >"$test_tmp/commands" +if TEST_STARTUP_MARKER="$test_tmp/startup-ran" BASH_ENV="$test_tmp/startup" bash "$test_tmp/omarchy-sudo-passwordless" -p >/dev/null 2>&1; then + fail "ordinary Bash with a decoy -p was accepted" fi -[[ -e $startup_marker && ! -e $public_token && ! -e $public_exploit ]] || - fail "unsafe passwordless startup reached its sudo workflow" -pass "passwordless confirmation uses a cold command-scoped credential boundary" +[[ -f $test_tmp/startup-ran && ! -s $test_tmp/commands ]] || fail "startup rejection must precede sudo" +pass "startup validation rejects ordinary Bash before authorization" -# Source a path-rewritten copy so the real cleanup implementation can be -# exercised without touching /etc. Exact generated numeric rules are removed -# even after account deletion or a crash before state publication. Anything an -# administrator changed, and every symlink, is preserved. -fake_sudoers="$test_tmp/sudoers.d" -mkdir "$fake_sudoers" -rewritten="$test_tmp/passwordless-lib.sh" -function_prefix | sed "s#/etc/sudoers.d#$fake_sudoers#g" >"$rewritten" ( - source "$rewritten" - printf 'deleteduser ALL=(ALL) NOPASSWD: ALL\n' >"$fake_sudoers/99-omarchy-nopasswd-424242" - printf 'admin ALL=(ALL) NOPASSWD: /usr/bin/pacman\n' >"$fake_sudoers/99-omarchy-nopasswd-424243" - ln -s "$fake_sudoers/99-omarchy-nopasswd-424243" "$fake_sudoers/99-omarchy-nopasswd-424244" - remove_known_legacy_rules + source "$library" + enable_locked 1000 15 + read_grant 1000 + [[ $GRANT_NAME == audituser && $(stat -c '%a' "$(rule_file 1000)") == 440 ]] + /usr/sbin/visudo -cf "$(rule_file 1000)" >/dev/null + expiry=$(sed -n 's/^systemd-run .*--on-calendar=@\([0-9]*\).*$/\1/p' "$test_tmp/commands" | tail -1) + [[ $GRANT_DEADLINE == "$(/usr/bin/date -u -d "@$expiry" +%Y%m%d%H%M%SZ)" ]] + if [[ -n ${OMARCHY_TEST_SUDOERS:-} ]]; then + [[ -x $OMARCHY_TEST_SUDOERS ]] || fail "OMARCHY_TEST_SUDOERS must name an executable" + printf 'root:x:0:0:root:/root:/bin/bash\naudituser:x:1000:1000:Test:/nonexistent:/bin/bash\n' >"$test_tmp/passwd" + printf 'root:x:0:\naudituser:x:1000:\n' >"$test_tmp/group" + { printf 'audituser ALL=(ALL) ALL\n'; cat "$(rule_file 1000)"; } >"$test_tmp/policy" + for offset in -1 1; do + when=$(/usr/bin/date -u -d "@$((expiry + offset))" +%Y%m%d%H%M%SZ) + "$OMARCHY_TEST_SUDOERS" -p "$test_tmp/passwd" -P "$test_tmp/group" -T "$when" audituser /usr/bin/true <"$test_tmp/policy" >"$test_tmp/policy-result" + if (( offset < 0 )); then + ! grep -q 'Password required' "$test_tmp/policy-result" || fail "native policy requires a password before expiry" + else + grep -q 'Password required' "$test_tmp/policy-result" || fail "native policy remains passwordless after expiry" + fi + done + pass "native sudoers evaluation requires authentication after the generated deadline" + fi + assert_status 0 status_locked 1000 + TEST_INACTIVE_TIMER=1 assert_status 0 status_locked 1000 + [[ ! -e $test_tmp/var/lib/omarchy/sudo-passwordless ]] + ! compgen -G "$test_tmp/etc/sudoers.d/.omarchy-nopasswd.*" ) -[[ ! -e $fake_sudoers/99-omarchy-nopasswd-424242 ]] || - fail "boot cleanup removes a state-less numeric orphan" -[[ -f $fake_sudoers/99-omarchy-nopasswd-424243 ]] || - fail "boot cleanup preserves administrator-authored policy" -[[ -L $fake_sudoers/99-omarchy-nopasswd-424244 ]] || - fail "boot cleanup refuses sudoers symlinks" -pass "boot cleanup removes crash/deleted-account orphans conservatively" - -# A boot gate must not report success when deletion itself fails. Exercise the -# real cleanup and post-cleanup verification with a deterministic failing rm. -rm_failure_dir="$test_tmp/rm-failure-sudoers" -mkdir "$rm_failure_dir" -printf 'deleteduser ALL=(ALL) NOPASSWD: ALL\n' >"$rm_failure_dir/99-omarchy-nopasswd-424245" -failing_rm="$test_tmp/failing-rm" -cat >"$failing_rm" <<'FAILING_RM' -#!/bin/bash -exit 1 -FAILING_RM -chmod +x "$failing_rm" -rm_failure_lib="$test_tmp/rm-failure-lib.sh" -function_prefix | - sed -e "s#/etc/sudoers.d#$rm_failure_dir#g" \ - -e "s#/var/lib/omarchy/sudo-passwordless#$test_tmp/empty-state#g" \ - -e "s#/usr/bin/rm#$failing_rm#g" >"$rm_failure_lib" -mkdir "$test_tmp/empty-state" -( - source "$rm_failure_lib" - ! cleanup_all_locked -) || fail "boot cleanup fails when an Omarchy rule cannot be removed" -[[ -f $rm_failure_dir/99-omarchy-nopasswd-424245 ]] || - fail "rm-failure fixture remains available for verification" -pass "boot cleanup fails closed when policy deletion fails" +pass "one complete mode-0440 sudoers rule holds the deadline with no separate grant state" -# Reproduce the migration's real sudo provenance: sudo sets SUDO_UID. Rewrite -# only the read-only EUID probe so this unprivileged test can exercise the root -# dispatcher, then assert that cleanup (which can only revoke privilege) runs. -dispatch_lib="$test_tmp/dispatch-lib.sh" -function_prefix | sed 's/((EUID == 0))/((TEST_EUID == 0))/g' >"$dispatch_lib" ( - source "$dispatch_lib" - called="" - cleanup_all_locked() { called=cleanup; } - with_root_lock() { "$@"; } - TEST_EUID=0 SUDO_UID=1000 root_dispatch __cleanup-all - [[ $called == cleanup ]] -) || fail "migration cleanup dispatch accepts authenticated sudo provenance" -pass "migration can invoke fail-closed cleanup through sudo" + source "$library" + before=$(cat "$(rule_file 1000)") + expire_locked 1000 omarchy-nopasswd-expire-1000-ffffffffffffffffffffffffffffffff + [[ $(cat "$(rule_file 1000)") == "$before" ]] + enable_locked 1000 30 + renewed=$(cat "$(rule_file 1000)") + [[ $renewed != "$before" ]] + expire_locked 1000 + [[ $(cat "$(rule_file 1000)") == "$renewed" ]] + TEST_EXPIRED=1 expire_locked 1000 + [[ ! -e $(rule_file 1000) ]] +) +pass "legacy and current callbacks preserve renewed grants and remove expired ones" -# A grant cannot be published until the static unit is verified/enabled, and a -# timer setup failure removes its pending state without calling publish_rule. -transaction_dir="$test_tmp/transaction" -mkdir "$transaction_dir" -transaction_lib="$test_tmp/transaction-lib.sh" -function_prefix | sed "s#/var/lib/omarchy/sudo-passwordless#$transaction_dir#g" >"$transaction_lib" ( - source "$transaction_lib" - ACCOUNT_NAME=audituser - resolve_account() { ACCOUNT_NAME=audituser; ACCOUNT_UID=1000; } - prepare_root_state() { :; } - verify_boot_cleanup() { return 1; } - publish_rule() { return 99; } - ! enable_locked 1000 15 + source "$library" + enable_locked 1000 1 + assert_status 2 env TEST_EXPIRED=1 TEST_DELETE_FAIL=1 TEST_EUID=0 SUDO_UID=1000 /usr/bin/bash -p "$test_tmp/omarchy-sudo-passwordless" __status 1000 + [[ -e $(rule_file 1000) ]] + TEST_EXPIRED=1 assert_status 3 status_locked 1000 + [[ ! -e $(rule_file 1000) ]] ) -( - source "$transaction_lib" - ACCOUNT_NAME=audituser - resolve_account() { ACCOUNT_NAME=audituser; ACCOUNT_UID=1000; } - prepare_root_state() { :; } - verify_boot_cleanup() { return 0; } - read_state_timer() { return 1; } - prepare_state_file() { local pending="$transaction_dir/pending"; : >"$pending"; printf %s "$pending"; } - start_expiry_timer() { return 1; } - publish_rule() { printf published >"$transaction_dir/published"; } - cleanup_uid_locked() { : >"$transaction_dir/failed-timer-cleanup"; } - ! enable_locked 1000 15 - [[ ! -e $transaction_dir/pending && ! -e $transaction_dir/published && - -e $transaction_dir/failed-timer-cleanup ]] -) || fail "passwordless sudo fails closed on prerequisite/timer failure" -pass "passwordless sudo publishes no rule after partial setup failure" +pass "expired status reports cleanup failure separately from confirmed inactivity" -# Erik's predecessor fix revoked an already-active grant when an extension -# could not arm its replacement timer. Keep that fail-closed property while -# the new transaction deliberately leaves the old timer armed until the new -# one is verified. -replacement_state="$transaction_dir/1000.state" -replacement_rule="$transaction_dir/1000.rule" -replacement_stopped="$transaction_dir/old-timer-stopped" -old_timer=omarchy-nopasswd-expire-1000-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -printf 'UID=1000\nUSER=audituser\nEXPIRES=2000000000\nTIMER=%s\n' "$old_timer" >"$replacement_state" -printf 'audituser ALL=(ALL) NOPASSWD: ALL\n' >"$replacement_rule" -( - source "$transaction_lib" - resolve_account() { ACCOUNT_NAME=audituser; ACCOUNT_UID=1000; } - prepare_root_state() { :; } - verify_boot_cleanup() { return 0; } - state_file() { printf '%s' "$replacement_state"; } - rule_file() { printf '%s' "$replacement_rule"; } - prepare_state_file() { local pending="$transaction_dir/replacement-pending"; : >"$pending"; printf %s "$pending"; } - start_expiry_timer() { return 1; } - stop_timer() { [[ $1 == "$old_timer" ]] && : >"$replacement_stopped"; } - ! enable_locked 1000 30 - [[ ! -e $replacement_state && ! -e $replacement_rule && -e $replacement_stopped ]] -) || fail "passwordless sudo leaves an existing grant live after replacement timer failure" -pass "replacement timer failure revokes the existing grant" +for failure in TEST_TIMER_FAIL TEST_INACTIVE_TIMER TEST_PUBLISH_FAIL TEST_POST_PUBLISH_FAIL TEST_CANCEL_ENABLE; do + reset_grant + expected=1 + if [[ $failure == "TEST_CANCEL_ENABLE" ]]; then expected=143; fi + ( + source "$library" + enable_locked 1000 15 + assert_status "$expected" env "$failure=1" TEST_EUID=0 SUDO_UID=1000 /usr/bin/bash -p "$test_tmp/omarchy-sudo-passwordless" __enable 1000 30 + [[ ! -e $(rule_file 1000) ]] + ) +done +pass "timer, publication, post-publication and cancellation failures revoke renewed access" -# Expiry is a wall-clock promise, so the transient timer must carry the exact -# absolute epoch recorded in root state. A monotonic-only --on-active timer -# pauses during suspend and can otherwise extend a short grant by hours. -timer_args="$test_tmp/timer-args" -calendar_systemd_run="$test_tmp/calendar-systemd-run" -calendar_systemctl="$test_tmp/calendar-systemctl" -cat >"$calendar_systemd_run" <<'STUB' -#!/bin/bash -printf '%s\n' "$@" >"$TEST_TIMER_ARGS" -STUB -cat >"$calendar_systemctl" <<'STUB' -#!/bin/bash -exit 0 -STUB -chmod 0755 "$calendar_systemd_run" "$calendar_systemctl" -calendar_lib="$test_tmp/calendar-lib.sh" -function_prefix | - sed -e "s#/usr/bin/systemd-run#$calendar_systemd_run#g" \ - -e "s#/usr/bin/systemctl#$calendar_systemctl#g" >"$calendar_lib" +reset_grant ( - source "$calendar_lib" - TEST_TIMER_ARGS="$timer_args" start_expiry_timer 1000 2000000000 \ - omarchy-nopasswd-expire-1000-0123456789abcdef0123456789abcdef -) || fail "passwordless sudo cannot arm its absolute expiry timer" -grep -Fx -- '--on-calendar=@2000000000' "$timer_args" >/dev/null || - fail "passwordless sudo timer does not advance across suspend" -pass "passwordless sudo arms the recorded absolute wall-clock expiry" + source "$library" + TEST_POST_PUBLISH_FAIL=1 TEST_DELETE_FAIL=1 assert_status 1 enable_locked 1000 15 + [[ -e $(rule_file 1000) ]] + ! grep -q '^systemctl stop ' "$test_tmp/commands" +) +pass "failed policy deletion retains the timer and reports failure" -# A resumed machine can briefly observe the timer as active before systemd -# dispatches its overdue service. Status must independently enforce EXPIRES and -# synchronously remove policy instead of trusting timer activity alone. -expired_state="$test_tmp/expired-state" -expired_sudoers="$test_tmp/expired-sudoers" -mkdir "$expired_state" "$expired_sudoers" -expired_timer=omarchy-nopasswd-expire-1000-0123456789abcdef0123456789abcdef -printf 'UID=1000\nUSER=audituser\nEXPIRES=1\nTIMER=%s\n' "$expired_timer" >"$expired_state/1000.state" -printf 'audituser ALL=(ALL) NOPASSWD: ALL\n' >"$expired_sudoers/99-omarchy-nopasswd-1000" -expired_lib="$test_tmp/expired-lib.sh" -function_prefix | - sed -e "s#/var/lib/omarchy/sudo-passwordless#$expired_state#g" \ - -e "s#/etc/sudoers.d#$expired_sudoers#g" \ - -e "s#/usr/bin/systemctl#$calendar_systemctl#g" >"$expired_lib" +reset_grant ( - source "$expired_lib" - resolve_account() { ACCOUNT_NAME=audituser; ACCOUNT_UID=1000; } - ! status_locked 1000 -) || fail "passwordless sudo accepts expired root state while its timer is active" -[[ ! -e $expired_state/1000.state && ! -e $expired_sudoers/99-omarchy-nopasswd-1000 ]] || - fail "passwordless sudo does not synchronously revoke expired state" -pass "passwordless sudo enforces wall-clock expiry independently of timer dispatch" + source "$library" + printf 'audituser ALL=(ALL) NOPASSWD: /usr/bin/true\n' >"$(rule_file 1000)" + cp "$(rule_file 1000)" "$test_tmp/admin-rule" + assert_status 2 status_locked 1000 + assert_status 1 enable_locked 1000 15 + assert_status 1 cleanup_uid_locked 1000 + cmp "$(rule_file 1000)" "$test_tmp/admin-rule" + rm "$(rule_file 1000)" + ln -s "$test_tmp/admin-rule" "$(rule_file 1000)" + assert_status 2 status_locked 1000 + assert_status 1 cleanup_uid_locked 1000 + [[ -L $(rule_file 1000) ]] +) +pass "grant operations preserve administrator policies and reject symlinks" -# If the transient timer fires between its first active check and publication, -# the just-created rule must be synchronously revoked instead of surviving to -# reboot. Model that narrow transition with the real enable transaction. -inactive_systemctl="$test_tmp/inactive-systemctl" -cat >"$inactive_systemctl" <<'STUB' -#!/bin/bash -exit 1 -STUB -chmod 0755 "$inactive_systemctl" -post_publish_lib="$test_tmp/post-publish-lib.sh" -sed "s#/usr/bin/systemctl#$inactive_systemctl#g" "$transaction_lib" >"$post_publish_lib" +reset_grant ( - source "$post_publish_lib" - resolve_account() { ACCOUNT_NAME=audituser; ACCOUNT_UID=1000; } - prepare_root_state() { :; } - verify_boot_cleanup() { return 0; } - read_state_timer() { return 1; } - prepare_state_file() { local pending="$transaction_dir/pending-after-arm"; : >"$pending"; printf %s "$pending"; } - start_expiry_timer() { return 0; } - publish_rule() { : >"$transaction_dir/published-after-arm"; } - cleanup_uid_locked() { rm -f "$transaction_dir/published-after-arm"; : >"$transaction_dir/revoked-after-arm"; } - ! enable_locked 1000 15 - [[ ! -e $transaction_dir/published-after-arm && -e $transaction_dir/revoked-after-arm ]] -) || fail "passwordless sudo leaves a grant when its armed timer expires before publication completes" -pass "timer expiry during publication revokes the grant synchronously" - -# Follow the maintainer's package-owned tmpfiles design: one boot-only rule -# owns this filename namespace. A routine --remove leaves live grants alone; -# early boot removes them before a user can log in. The migration only revokes -# legacy runtime state and never writes static policy into /usr. -mapfile -t tmpfiles_rules < <(/usr/bin/grep -vE '^[[:space:]]*(#|$)' "$tmpfiles_path") -(( ${#tmpfiles_rules[@]} == 1 )) || fail "passwordless sudo ships one boot cleanup rule" -[[ ${tmpfiles_rules[0]} == 'r! /etc/sudoers.d/99-omarchy-nopasswd-*' ]] || - fail "passwordless sudo boot cleanup does not own the exact generated namespace" -fake_root="$test_tmp/tmpfiles-root" -sudoers_dir="$fake_root/etc/sudoers.d" -mkdir -p "$sudoers_dir" -for name in alice buildbot-2 424242; do - : >"$sudoers_dir/99-omarchy-nopasswd-$name" -done -: >"$sudoers_dir/omarchy-dns" -/usr/bin/systemd-tmpfiles --root="$fake_root" --remove --inline "${tmpfiles_rules[0]}" -[[ -e $sudoers_dir/99-omarchy-nopasswd-alice ]] || fail "non-boot tmpfiles run shortened a live grant" -/usr/bin/systemd-tmpfiles --root="$fake_root" --remove --boot --inline "${tmpfiles_rules[0]}" -! find "$sudoers_dir" -name '99-omarchy-nopasswd-*' -print -quit | /usr/bin/grep -q . || - fail "boot cleanup left a generated passwordless grant" -[[ -e $sudoers_dir/omarchy-dns ]] || fail "boot cleanup removed an unrelated sudoers rule" -/usr/bin/grep -Fx 'sudo /usr/bin/omarchy-sudo-passwordless __cleanup-all' "$migration_path" >/dev/null -! /usr/bin/grep -q 'omarchy-sudo-passwordless-cleanup.service' "$migration_path" || - fail "migration retained a custom boot service instead of package-owned tmpfiles" -pass "package-owned boot cleanup is narrow, boot-only, and migration-safe" - -# Removing the settings package also removes the tmpfiles rule. Its package -# lifecycle must therefore revoke the same owned namespace synchronously, while -# preserving every unrelated sudoers file. -pkgs_candidates=( - "${OMARCHY_PKGS_PATH:-}" - "$ROOT/../omarchy-pkgs" - "$ROOT/../../omarchy-pkgs" - "$HOME/Work/omarchy/omarchy-pkgs" - "$HOME/Work/omacom/omarchy-pkgs" + source "$library" + TEST_BAD_PATH="$test_tmp/etc/sudoers.d" assert_status 1 enable_locked 1000 15 + [[ ! -e $(rule_file 1000) ]] + rm "$PACKAGE_HOOK" + assert_status 1 enable_locked 1000 15 ) -pkgs_root="" -for candidate in "${pkgs_candidates[@]}"; do - if [[ -n $candidate && -d $candidate/pkgbuilds/omarchy-settings ]]; then - pkgs_root=$candidate/pkgbuilds - break - elif [[ -n $candidate && -d $candidate/omarchy-settings ]]; then - pkgs_root=$candidate - break - fi -done -[[ -n $pkgs_root ]] || fail "omarchy-pkgs checkout found for passwordless package-removal coverage" +pass "publication requires trusted paths and the packaged cleanup hook" -for package_name in omarchy-settings omarchy-settings-dev; do - install_script="$pkgs_root/$package_name/$package_name.install" - transformed_install="$test_tmp/$package_name.install" - removal_root="$test_tmp/$package_name-remove" - removal_sudoers="$removal_root/etc/sudoers.d" - mkdir -p "$removal_sudoers" "$removal_root/run/lock" "$removal_root/etc/tmpfiles.d" - : >"$removal_sudoers/99-omarchy-nopasswd-1000" - : >"$removal_sudoers/99-omarchy-nopasswd-legacy-user" - : >"$removal_sudoers/omarchy-dns" - ln -s ../administrator/os-release "$removal_root/etc/os-release" - package_stat="$test_tmp/package-stat" - cat >"$package_stat" <<'STUB' -#!/bin/bash -if [[ $2 == '%u' ]]; then printf '0\n'; else /usr/bin/stat "$@"; fi -STUB - chmod +x "$package_stat" - sed -e "s#/etc/#$removal_root/etc/#g" \ - -e "s#/run#$removal_root/run#g" \ - -e "s#/usr/bin/stat#$package_stat#g" "$install_script" >"$transformed_install" - ( - source "$transformed_install" - pre_remove - [[ -f $removal_root/run/omarchy-sudo-passwordless-package-removing ]] - post_remove - ) || fail "$package_name removal revokes active passwordless grants" - ! find "$removal_sudoers" -name '99-omarchy-nopasswd-*' -print -quit | grep -q . || - fail "$package_name removal leaves a passwordless grant behind" - [[ -e $removal_sudoers/omarchy-dns ]] || - fail "$package_name removal deletes an unrelated sudoers policy" - [[ $(readlink "$removal_root/etc/os-release") == ../administrator/os-release ]] || - fail "$package_name removal changes unrelated OS metadata" - : >"$removal_sudoers/99-omarchy-nopasswd-1001" - ( - source "$transformed_install" - post_remove - ) || fail "$package_name removal handles administrator OS selector state" - [[ $(readlink "$removal_root/etc/os-release") == ../administrator/os-release ]] || - fail "$package_name removal overwrites an administrator OS selector" - [[ ! -e $removal_sudoers/99-omarchy-nopasswd-1001 ]] || - fail "$package_name removal grant cleanup depends on OS selector state" - - ( - source "$transformed_install" - _etc_overrides_apply() { :; } - if post_install; then exit 1; fi - [[ -f $removal_root/run/omarchy-sudo-passwordless-package-removing ]] - : >"$removal_root/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf" - post_install - [[ ! -e $removal_root/run/omarchy-sudo-passwordless-package-removing ]] - : >"$removal_sudoers/99-omarchy-nopasswd-1002" - pre_upgrade - [[ ! -e $removal_sudoers/99-omarchy-nopasswd-1002 ]] - post_upgrade - [[ ! -e $removal_root/run/omarchy-sudo-passwordless-package-removing ]] - ) || fail "$package_name restores grant availability only after boot cleanup is installed" -done -pass "settings package transitions revoke grants and preserve unrelated configuration" - -# Exercise the production flock wrapper under contention. mkdir is an atomic -# overlap detector; all workers must enter and leave the protected region. -lock_dir="$test_tmp/lock-runtime" -mkdir "$lock_dir" -lock_lib="$test_tmp/lock-lib.sh" -function_prefix | - sed -e "s#/run/omarchy/sudo-passwordless#$lock_dir#g" \ - -e "s#/run/lock/omarchy-sudo-passwordless.lock#$test_tmp/passwordless.lock#g" \ - -e 's#/usr/bin/chown root:root "$LOCK_FILE"#/usr/bin/true#' >"$lock_lib" -worker="$test_tmp/worker.sh" -cat >"$worker" <<'WORKER' -#!/bin/bash -set -euo pipefail -source "$LOCK_LIB" -prepare_root_state() { :; } -critical() { - mkdir "$LOCK_SENTINEL" - sleep 0.03 - rmdir "$LOCK_SENTINEL" - printf x >>"$LOCK_RESULTS" -} -with_root_lock critical -WORKER -chmod +x "$worker" -for _ in {1..8}; do - LOCK_LIB="$lock_lib" LOCK_SENTINEL="$test_tmp/held" LOCK_RESULTS="$test_tmp/results" bash "$worker" & -done -wait -[[ $(wc -c <"$test_tmp/results") == 8 ]] || fail "concurrent passwordless operations serialize" -pass "passwordless sudo serializes concurrent operations" - -# Same-boot expiry calls the fixed installed cleanup command, and cleanup -# removes policy before touching a timer so timer failures cannot extend it. -grep -F '"$INSTALLED_SELF" __expire "$uid" "$timer"' "$command_path" >/dev/null -cleanup_body=$(awk '/^cleanup_uid_locked\(\) \{/ { in_body=1 } in_body { print } in_body && /^}/ { exit }' "$command_path") -rm_line=$(grep -n '/usr/bin/rm -f' <<<"$cleanup_body" | head -1 | cut -d: -f1) -stop_line=$(grep -n 'stop_timer' <<<"$cleanup_body" | tail -1 | cut -d: -f1) -((rm_line < stop_line)) || fail "expiry removes sudo policy before timer cleanup" -pass "same-boot expiration is fixed-target and fail closed" +reset_grant +cp "$ROOT/default/libalpm/hooks/05-omarchy-passwordless-revoke.hook" "$test_tmp/hooks/" +( + source "$library" + TEST_ACCOUNT='buildbot$' enable_locked 1000 15 + read_grant 1000 + [[ $GRANT_NAME == 'buildbot$' ]] + /usr/sbin/visudo -cf "$(rule_file 1000)" >/dev/null + cleanup_uid_locked 1000 + [[ ! -e $(rule_file 1000) ]] +) +pass "trailing-dollar accounts publish and revoke valid native policy" diff --git a/test/shell.d/passwordless-grant-lifecycle-test.sh b/test/shell.d/passwordless-grant-lifecycle-test.sh index b3198405642b..a0be9d4f0ceb 100644 --- a/test/shell.d/passwordless-grant-lifecycle-test.sh +++ b/test/shell.d/passwordless-grant-lifecycle-test.sh @@ -2,234 +2,135 @@ set -euo pipefail source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" - -test_tmp=$(mktemp -d) -children=() -cleanup() { - local status=$? - trap - EXIT - if (( ${#children[@]} )); then - kill "${children[@]}" 2>/dev/null || true - wait "${children[@]}" 2>/dev/null || true - fi - rm -rf "$test_tmp" - exit "$status" -} -trap cleanup EXIT - -# All policy, state, locks and command mutations stay in this private fixture. -# Native visudo validates inert fragments; no test installs host sudo policy. -mkdir -p "$test_tmp/bin" "$test_tmp/state" "$test_tmp/etc/sudoers.d" "$test_tmp/etc/tmpfiles.d" "$test_tmp/run/lock" "$test_tmp/hooks" -export TEST_GRANT_ROOT="$test_tmp" -cat >"$test_tmp/bin/stat" <<'STUB' -#!/bin/bash -case $2 in - '%u') printf '0\n' ;; - '%a') if [[ -d ${@: -1} ]]; then printf '755\n'; else printf '644\n'; fi ;; - '%u %a') if [[ -d ${@: -1} ]]; then printf '0 755\n'; else printf '0 644\n'; fi ;; - *) exec /usr/bin/stat "$@" ;; -esac -STUB -cat >"$test_tmp/bin/install" <<'STUB' -#!/bin/bash -args=() -while (($#)); do - case $1 in -o|-g) shift 2 ;; *) args+=("$1"); shift ;; esac -done -exec /usr/bin/install "${args[@]}" -STUB -cat >"$test_tmp/bin/rm" <<'STUB' -#!/bin/bash -for path in "$@"; do - if [[ ${TEST_FAIL_TEMP_CLEANUP:-0} == 1 && $path == "$TEST_GRANT_ROOT/state/".sudoers.* ]]; then exit 1; fi - if [[ ${TEST_FAIL_RULE_DELETE:-0} == 1 && $path == "$TEST_GRANT_ROOT/etc/sudoers.d/"* ]]; then exit 1; fi -done -exec /usr/bin/rm "$@" -STUB -cat >"$test_tmp/bin/systemctl" <<'STUB' -#!/bin/bash -printf '%s\n' "$*" >>"$TEST_GRANT_ROOT/systemctl.log" -exit 0 -STUB -chmod +x "$test_tmp/bin/"* -library="$test_tmp/grant-functions.sh" -{ - printf 'source %q\n' "$ROOT/bin/omarchy-security-functions" - awk '/^set -euo pipefail$/ { functions=1 } /^case "\$\{1:-\}" in$/ { exit } functions { print }' "$ROOT/bin/omarchy-sudo-passwordless" -} | sed \ - -e "s|/var/lib/omarchy/sudo-passwordless|$test_tmp/state|g" \ - -e "s|/etc/sudoers.d|$test_tmp/etc/sudoers.d|g" \ - -e "s|/etc/tmpfiles.d|$test_tmp/etc/tmpfiles.d|g" \ - -e "s|/usr/share/libalpm/hooks|$test_tmp/hooks|g" \ - -e "s|/run/lock/omarchy-sudo-passwordless.lock|$test_tmp/run/lock/omarchy-sudo-passwordless.lock|g" \ - -e "s|/run/omarchy-sudo-passwordless-package-removing|$test_tmp/run/omarchy-sudo-passwordless-package-removing|g" \ - -e "s|/usr/bin/stat|$test_tmp/bin/stat|g" \ - -e "s|/usr/bin/install|$test_tmp/bin/install|g" \ - -e "s|/usr/bin/rm|$test_tmp/bin/rm|g" \ - -e "s|/usr/bin/systemctl|$test_tmp/bin/systemctl|g" \ - -e 's|/usr/bin/chown|/usr/bin/true|g' >"$library" - -cp "$ROOT/default/libalpm/hooks/05-omarchy-passwordless-revoke.hook" "$test_tmp/hooks/" - -printf 'r! /etc/sudoers.d/99-omarchy-nopasswd-*\n' >"$test_tmp/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf" -# The expected policy text is mapped along with its filename in this fixture. -sed -i "s|/etc/sudoers.d|$test_tmp/etc/sudoers.d|" "$test_tmp/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf" +source "$SHELL_TEST_DIR/fixtures/passwordless-sudo-test.sh" ( source "$library" - for name in 'buildbot$' audituser aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; do - valid_account_name "$name" || fail "supported account name rejected: $name" - printf '%s ALL=(ALL) NOPASSWD: ALL\n' "$name" >"$test_tmp/name-policy" - /usr/sbin/visudo -cf "$test_tmp/name-policy" >/dev/null - done - for name in 'a$b' '$' aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; do - ! valid_account_name "$name" || fail "invalid account name accepted" - done - ! valid_uid 18446744073709551617 || fail "overflowed UID accepted" + printf 'deleteduser ALL=(ALL) NOPASSWD: ALL\n' >"$(rule_file 1000)" printf 'buildbot$ ALL=(ALL) NOPASSWD: ALL\n' >"$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-buildbot$" - remove_known_legacy_rules - [[ ! -e $test_tmp/etc/sudoers.d/99-omarchy-nopasswd-buildbot\$ ]] -) || fail "supported account names and legacy cleanup disagree" -pass "provisioning-compatible names validate as sudoers and clean up correctly" - -transaction_setup() { - resolve_account() { ACCOUNT_NAME=audituser; ACCOUNT_UID=1000; } - prepare_root_state() { :; } - start_expiry_timer() { printf '%s\n' "$3" >>"$test_tmp/armed"; } - stop_timer() { printf '%s\n' "$1" >>"$test_tmp/stopped"; } + printf 'admin ALL=(ALL) NOPASSWD: /usr/bin/true\n' >"$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-custom" + TEST_DELETE_FAIL=1 assert_status 1 cleanup_all_locked + [[ -e $(rule_file 1000) ]] + cleanup_all_locked + [[ ! -e $(rule_file 1000) && -e $test_tmp/etc/sudoers.d/99-omarchy-nopasswd-custom ]] + ! compgen -G "$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-buildbot*" +) +pass "legacy cleanup removes generated orphan rules and preserves custom policy" + +# Run the actual migration queue for separate temporary homes. Sudo only calls +# the mapped helper and can be refused without requesting host authorization. +mkdir -p "$test_tmp/source/migrations" +sed "s|/usr/bin/omarchy-sudo-passwordless|$test_tmp/omarchy-sudo-passwordless|g" \ + "$ROOT/migrations/1788163635.sh" >"$test_tmp/source/migrations/1788163635.sh" +printf 'echo "later migration ran"\n' >"$test_tmp/source/migrations/1788163636.sh" +run_migrations() { + TEST_MIGRATION=1 OMARCHY_PATH="$test_tmp/source" OMARCHY_MIGRATION_STATE="$test_tmp/$1" \ + PATH="$test_tmp/bin:$PATH" /usr/bin/bash "$ROOT/bin/omarchy-migrate" >"$test_tmp/migrations.log" 2>&1 } - -( - source "$library" - transaction_setup - TEST_FAIL_TEMP_CLEANUP=1 enable_locked 1000 15 && exit 1 - [[ ! -e $(rule_file 1000) && ! -e $(state_file 1000) && -s $test_tmp/stopped ]] -) || fail "post-publication cleanup failure did not revoke before timer cleanup" -pass "failed temporary cleanup after publication revokes the live policy" - -rm -f "$test_tmp/stopped" +marker="$test_tmp/var/lib/omarchy/migrations/1788163635" ( source "$library" - transaction_setup - TEST_FAIL_TEMP_CLEANUP=1 TEST_FAIL_RULE_DELETE=1 enable_locked 1000 15 && exit 1 - [[ -f $(rule_file 1000) && -f $(state_file 1000) && ! -e $test_tmp/stopped ]] - if TEST_FAIL_RULE_DELETE=1 revoke_inactive_grant 1000; then exit 1; else status=$?; fi - (( status == 2 )) -) || fail "failed policy revocation disarmed expiry or claimed inactive status" -pass "failed revocation preserves expiry jobs and returns a distinct error" + printf 'audituser ALL=(ALL) NOPASSWD: ALL\n' >"$(rule_file 1000)" + TEST_DELETE_FAIL=1 assert_status 1 run_migrations first + [[ ! -e $marker && ! -e $test_tmp/first/1788163636.sh ]] + run_migrations first + [[ -f $marker && -f $test_tmp/first/1788163636.sh ]] + enable_locked 1000 15 + cp "$(rule_file 1000)" "$test_tmp/renewed" + : >"$test_tmp/commands" + TEST_NO_SUDO=1 run_migrations second + [[ -f $test_tmp/second/1788163636.sh ]] + ! grep -q '^sudo ' "$test_tmp/commands" + cmp "$(rule_file 1000)" "$test_tmp/renewed" +) +pass "migration completion is machine-wide, retryable, and needs no sudo for later users" ( source "$library" - transaction_setup - current_timer=$(read_state_timer 1000) - expire_locked 1000 omarchy-nopasswd-expire-1000-ffffffffffffffffffffffffffffffff - [[ -f $(rule_file 1000) ]] - expire_locked 1000 - [[ -f $(rule_file 1000) ]] - expire_locked 1000 "$current_timer" - [[ ! -e $(rule_file 1000) ]] -) || fail "a predecessor timer invalidates its replacement" -pass "old and legacy timer callbacks preserve a newer valid grant" - -( - source "$library" - transaction_setup - start_expiry_timer() { - : >"$REMOVAL_BLOCKER" - return 0 - } - enable_locked 1000 15 && exit 1 - [[ ! -e $(rule_file 1000) ]] -) || fail "publication ignores a lost package prerequisite" -rm "$test_tmp/run/omarchy-sudo-passwordless-package-removing" -pass "grant publication rechecks package availability after timer setup" - + TEST_BAD_PATH="$marker" assert_status 1 migration_complete + rm "$marker" + ln -s "$test_tmp/renewed" "$marker" + assert_status 1 migration_complete + assert_status 1 migrate_locked + [[ -L $marker ]] + rm "$marker" +) +pass "migration checks marker ownership and rejects symlinks" + +# Keep real package scripts in the contract: source and packaging share the +# same lock and blocker, including the legacy scriptlet fallback. pkgs_path=${OMARCHY_PKGS_PATH:-$ROOT/../omarchy-pkgs} [[ ! -d $pkgs_path/pkgbuilds ]] || pkgs_path=$pkgs_path/pkgbuilds -package_script="$pkgs_path/omarchy-settings/omarchy-settings.install" -[[ -f $package_script ]] || fail "package checkout is required for shared lifecycle coverage" -sed -e "s|/etc/|$test_tmp/etc/|g" \ - -e "s|/run|$test_tmp/run|g" \ - -e "s|/usr/bin/stat|$test_tmp/bin/stat|g" \ - -e "s|/usr/bin/rm|$test_tmp/bin/rm|g" "$package_script" >"$test_tmp/package.install" +for name in omarchy-settings omarchy-settings-dev; do + script="$pkgs_path/$name/$name.install" + [[ -f $script ]] || fail "set OMARCHY_PKGS_PATH to the companion package checkout" + sed -e "s|/etc/|$test_tmp/etc/|g" -e "s|/run|$test_tmp/run|g" \ + -e "s|/usr/bin/stat|$test_tmp/bin/stat|g" -e "s|/usr/bin/rm|$test_tmp/bin/rm|g" \ + "$script" >"$test_tmp/$name.install" + reset_grant + ( + source "$library" + source "$test_tmp/$name.install" + _etc_overrides_apply() { :; } + enable_locked 1000 15 + TEST_DELETE_FAIL=1 assert_status 1 pre_remove + [[ -e $REMOVAL_BLOCKER && -e $(rule_file 1000) ]] + assert_status 1 enable_locked 1000 15 + pre_remove && post_remove + [[ ! -e $(rule_file 1000) ]] + post_install + [[ ! -e $REMOVAL_BLOCKER ]] + enable_locked 1000 15 + pre_upgrade && post_upgrade + [[ ! -e $(rule_file 1000) && ! -e $REMOVAL_BLOCKER ]] + ) +done +pass "both settings packages revoke grants, block publication, and recover on installation" -worker="$test_tmp/publisher.sh" -{ - printf '#!/bin/bash\nset -euo pipefail\nsource %q\n' "$library" - declare -f transaction_setup - printf 'test_tmp=%q\ntransaction_setup\n' "$test_tmp" - cat <<'WORKER' -publish_rule() { - : >"$test_tmp/publisher.entered" - while [[ ! -e $test_tmp/publisher.release ]]; do sleep 0.02; done - printf 'audituser ALL=(ALL) NOPASSWD: ALL\n' >"$(rule_file "$1")" +reset_grant +# Hold the source lock, then start package removal. A native flock on the +# mapped file must serialize both implementations. +cat >"$test_tmp/worker" <<'WORKER' +#!/bin/bash +set -euo pipefail +source "$TEST_LIBRARY" +critical() { + touch "$TEST_GRANT_ROOT/entered" + for (( attempt=0; attempt<500; attempt++ )); do + [[ ! -e $TEST_GRANT_ROOT/release ]] || break + sleep 0.01 + done + [[ -e $TEST_GRANT_ROOT/release ]] || return 1 + enable_locked 1000 15 } -with_root_lock enable_locked 1000 15 +with_root_lock critical WORKER -} >"$worker" -bash "$worker" >"$test_tmp/publisher.output" 2>&1 & -children+=("$!") -for ((attempt = 0; attempt < 250; attempt++)); do - [[ ! -e $test_tmp/publisher.entered ]] || break - sleep 0.02 -done -[[ -e $test_tmp/publisher.entered ]] || fail "grant publisher did not enter the shared lock" -bash -euo pipefail -c 'source "$1"; : >"$2"; pre_remove; post_remove' bash \ - "$test_tmp/package.install" "$test_tmp/removal.started" >"$test_tmp/removal.output" 2>&1 & -children+=("$!") -for ((attempt = 0; attempt < 250; attempt++)); do - [[ ! -e $test_tmp/removal.started ]] || break - sleep 0.02 +TEST_LIBRARY="$library" /usr/bin/bash "$test_tmp/worker" >"$test_tmp/publisher.log" 2>&1 & +publisher=$! +children+=("$publisher") +for (( attempt=0; attempt<200; attempt++ )); do + [[ ! -e $test_tmp/entered ]] || break + sleep 0.01 done -[[ -e $test_tmp/removal.started ]] || fail "package removal did not start" -touch "$test_tmp/publisher.release" -for child in "${children[@]}"; do wait "$child" || fail "shared lifecycle worker failed"; done +[[ -f $test_tmp/entered ]] || fail "publisher failed to acquire the lock" +/usr/bin/bash -euo pipefail -c 'source "$1"; pre_remove; post_remove' bash "$test_tmp/omarchy-settings.install" >"$test_tmp/removal.log" 2>&1 & +removal=$! +children+=("$removal") +touch "$test_tmp/release" +wait "$publisher" || fail "publisher failed" "$(cat "$test_tmp/publisher.log")" +wait "$removal" || fail "removal failed" "$(cat "$test_tmp/removal.log")" children=() -[[ ! -e $test_tmp/etc/sudoers.d/99-omarchy-nopasswd-1000 ]] || fail "removal left a concurrently published grant" -[[ -f $test_tmp/run/omarchy-sudo-passwordless-package-removing ]] || fail "removal did not block later publication" -( - source "$library" - transaction_setup - ! with_root_lock enable_locked 1000 15 -) || fail "a publisher can create a grant after package removal begins" -pass "package removal shares the grant lock and blocks later publication" - -printf 'audituser ALL=(ALL) NOPASSWD: ALL\n' >"$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-1000" -if TEST_FAIL_RULE_DELETE=1 bash -euo pipefail -c 'source "$1"; post_remove' bash "$test_tmp/package.install" >"$test_tmp/removal-failure.output" 2>&1; then - fail "package removal hid a failed policy deletion" -fi -grep -q 'Administrator cleanup is required' "$test_tmp/removal-failure.output" || fail "package deletion failure lacks recovery guidance" -pass "package removal reports cleanup failures instead of successful revocation" - -( - source "$library" - transaction_setup - rm -f "$REMOVAL_BLOCKER" - enable_locked 1000 5 - record=$(read_state_record 1000) - expiry=${record#*$'\t'} - expiry=${expiry%%$'\t'*} - deadline=$(/usr/bin/date -u -d "@$expiry" +%Y%m%d%H%M%SZ) - [[ $(cat "$(rule_file 1000)") == "audituser ALL=(ALL) NOTAFTER=$deadline NOPASSWD: ALL" ]] - /usr/sbin/visudo -cf "$(rule_file 1000)" >/dev/null - classify_generated_rule "$(rule_file 1000)" - rm -f "$(state_file 1000)" - remove_known_legacy_rules - [[ ! -e $(rule_file 1000) ]] -) || fail "native sudo deadline or state-independent bounded rule cleanup is incorrect" -pass "sudo policy contains the same deadline and bounded orphan rules are recognized" - -( - source "$library" - transaction_setup - rm -f "$REMOVAL_BLOCKER" - enable_locked 1000 5 - if TEST_FAIL_RULE_DELETE=1 package_removing_locked; then exit 1; fi - [[ -f $REMOVAL_BLOCKER && -f $(rule_file 1000) ]] - ! enable_locked 1000 5 - package_removing_locked - [[ ! -e $(rule_file 1000) ]] - rm -f "$REMOVAL_BLOCKER" "$PACKAGE_HOOK" - ! enable_locked 1000 5 -) || fail "pre-transaction revocation error or missing hook does not prevent new grants" -pass "package hook fails closed and grants require its installed policy" +[[ ! -e $test_tmp/etc/sudoers.d/99-omarchy-nopasswd-1000 ]] +[[ -f $test_tmp/run/omarchy-sudo-passwordless-package-removing ]] +pass "native lock serializes grant publication with package removal" + +# systemd-tmpfiles operates on an explicit disposable root, never the host. +reset_grant +: >"$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-1000" +: >"$test_tmp/etc/sudoers.d/unrelated" +rule='r! /etc/sudoers.d/99-omarchy-nopasswd-*' +/usr/bin/systemd-tmpfiles --root="$test_tmp" --remove --inline "$rule" +[[ -f $test_tmp/etc/sudoers.d/99-omarchy-nopasswd-1000 ]] || fail "routine tmpfiles shortened a live grant" +/usr/bin/systemd-tmpfiles --root="$test_tmp" --remove --boot --inline "$rule" +[[ ! -e $test_tmp/etc/sudoers.d/99-omarchy-nopasswd-1000 && -f $test_tmp/etc/sudoers.d/unrelated ]] || fail "boot cleanup boundary" +pass "native boot cleanup removes grants while routine tmpfiles preserves them" From 31bd80daa4613ffdee995ac27467fce5a2990806 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Fri, 11 Sep 2026 21:51:13 +0200 Subject: [PATCH 041/194] Keep the KEF LSX II LT USB sink from suspending (#11318) The speaker's USB firmware stops answering control requests when the host stops the audio stream after WirePlumber's 5 s idle suspend. The kernel then logs usb_set_interface failed (-110), clock source 1 is not valid, and cannot set freq 48000 err -110; PipeWire fails to start the sink and only a replug recovers it. On one machine this happened on six days over three weeks, up to hundreds of timeouts a day. A WirePlumber rule sets session.suspend-timeout-seconds = 0 for the KEF node only, so the stream is never stopped and the trigger never fires. Other sinks keep the default. The migration seeds the file for existing installs and restarts WirePlumber if it is running, since conf.d is only read at startup. Co-authored-by: Claude Fable 5.1 --- .../kef-lsx-no-suspend.conf | 19 +++++++++++++++++++ migrations/1789130779.sh | 9 +++++++++ 2 files changed, 28 insertions(+) create mode 100644 config/wireplumber/wireplumber.conf.d/kef-lsx-no-suspend.conf create mode 100644 migrations/1789130779.sh diff --git a/config/wireplumber/wireplumber.conf.d/kef-lsx-no-suspend.conf b/config/wireplumber/wireplumber.conf.d/kef-lsx-no-suspend.conf new file mode 100644 index 000000000000..02955660051b --- /dev/null +++ b/config/wireplumber/wireplumber.conf.d/kef-lsx-no-suspend.conf @@ -0,0 +1,19 @@ +## Never suspend the KEF LSX II LT USB sink. +## The speaker's USB firmware stops answering control requests when the host +## stops the stream after idle (usb_set_interface -110), and only a replug +## recovers it. Keeping the stream open avoids the trigger. + +monitor.alsa.rules = [ + { + matches = [ + { + node.name = "~alsa_output.usb-KEF_LSX_II_LT.*" + } + ] + actions = { + update-props = { + session.suspend-timeout-seconds = 0 + } + } + } +] diff --git a/migrations/1789130779.sh b/migrations/1789130779.sh new file mode 100644 index 000000000000..56d9fe2077be --- /dev/null +++ b/migrations/1789130779.sh @@ -0,0 +1,9 @@ +echo "Keep the KEF LSX II LT USB sink from suspending" + +conf="wireplumber/wireplumber.conf.d/kef-lsx-no-suspend.conf" + +if [[ ! -f "$HOME/.config/$conf" ]]; then + omarchy-refresh-config "$conf" + # WirePlumber only reads conf.d at startup; restart it if it is running. + systemctl --user try-restart wireplumber.service 2>/dev/null || true +fi From 7270ee5021ac54f1b64293d20e6873e107a1c695 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sat, 12 Sep 2026 16:48:59 +0200 Subject: [PATCH 042/194] Fix automatic Neovim yanks in remote sessions --- migrations/1788996284.sh | 9 ++++ test/shell.d/neovim-remote-yanks-test.sh | 52 ++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 migrations/1788996284.sh create mode 100755 test/shell.d/neovim-remote-yanks-test.sh diff --git a/migrations/1788996284.sh b/migrations/1788996284.sh new file mode 100644 index 000000000000..e47894f8c207 --- /dev/null +++ b/migrations/1788996284.sh @@ -0,0 +1,9 @@ +echo "Enable automatic Neovim clipboard yanks in remote sessions" + +nvim_provider="$HOME/.config/nvim/lua/config/remote_clipboard.lua" + +if [[ -f $nvim_provider ]] && + grep -qF 'name = "OmarchyRemoteClipboard"' "$nvim_provider" && + ! grep -qF 'vim.opt.clipboard = "unnamedplus"' "$nvim_provider"; then + sed -i '/^ vim.g.clipboard = {/i\ -- LazyVim disables clipboard syncing over SSH; our provider supports it.\n vim.opt.clipboard = "unnamedplus"\n' "$nvim_provider" +fi diff --git a/test/shell.d/neovim-remote-yanks-test.sh b/test/shell.d/neovim-remote-yanks-test.sh new file mode 100755 index 000000000000..94b2e7a915d3 --- /dev/null +++ b/test/shell.d/neovim-remote-yanks-test.sh @@ -0,0 +1,52 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +test_home=$(mktemp -d) +trap 'rm -rf "$test_home"' EXIT +provider="$test_home/.config/nvim/lua/config/remote_clipboard.lua" +migration="$ROOT/migrations/1788996284.sh" + +env HOME="$test_home" bash -euo pipefail "$migration" +[[ ! -e $provider ]] || fail "missing Neovim config is left alone" +pass "missing Neovim config is left alone" + +mkdir -p "$(dirname "$provider")" +printf '%s\n' '-- Custom provider' >"$provider" +cp "$provider" "$test_home/before.lua" +env HOME="$test_home" bash -euo pipefail "$migration" +cmp "$provider" "$test_home/before.lua" || fail "custom provider is preserved" +pass "custom provider is preserved" + +cat >"$provider" <<'LUA' +local M = {} +function M.setup() + if not vim.env.SSH_CONNECTION then + return + end + vim.g.clipboard = { + name = "OmarchyRemoteClipboard", + } +end +return M +LUA +env HOME="$test_home" bash -euo pipefail "$migration" +require_command nvim +cat >"$test_home/check.lua" <<'LUA' +vim.env.SSH_CONNECTION = nil +vim.opt.clipboard = "" +dofile(vim.env.TEST_PROVIDER).setup() +assert(vim.o.clipboard == "") +vim.env.SSH_CONNECTION = "test" +dofile(vim.env.TEST_PROVIDER).setup() +assert(vim.o.clipboard == "unnamedplus") +LUA +env NVIM_LOG_FILE="$test_home/nvim.log" TEST_PROVIDER="$provider" nvim --clean -n --headless -i NONE -l "$test_home/check.lua" +pass "clipboard syncing is enabled inside remote provider setup" + +cp "$provider" "$test_home/once.lua" +env HOME="$test_home" bash -euo pipefail "$migration" +cmp "$provider" "$test_home/once.lua" || fail "migration is idempotent" +pass "migration is idempotent" From b72d7e5768bcb19749f78ad380a5fd6958ec2c1c Mon Sep 17 00:00:00 2001 From: LM Date: Sat, 12 Sep 2026 10:18:01 +0200 Subject: [PATCH 043/194] Treat command operands as literal values --- bin/omarchy-cmd-missing | 2 +- bin/omarchy-cmd-present | 2 +- bin/omarchy-hook-install | 4 +- bin/omarchy-hw-match | 4 +- bin/omarchy-launch-editor | 6 +- bin/omarchy-pkg-add | 6 +- bin/omarchy-pkg-aur-add | 4 +- bin/omarchy-pkg-missing | 2 +- bin/omarchy-pkg-present | 2 +- bin/omarchy-restart-app | 2 +- .../command-operand-boundaries-test.sh | 259 ++++++++++++++++++ 11 files changed, 276 insertions(+), 17 deletions(-) create mode 100755 test/shell.d/command-operand-boundaries-test.sh diff --git a/bin/omarchy-cmd-missing b/bin/omarchy-cmd-missing index 470d69c31e30..2b48be8152e8 100755 --- a/bin/omarchy-cmd-missing +++ b/bin/omarchy-cmd-missing @@ -3,7 +3,7 @@ # omarchy:summary=Check whether any required commands are missing for cmd in "$@"; do - if ! command -v "$cmd" &>/dev/null; then + if ! command -v -- "$cmd" &>/dev/null; then exit 0 fi done diff --git a/bin/omarchy-cmd-present b/bin/omarchy-cmd-present index 4e758760ab32..57b0510250cf 100755 --- a/bin/omarchy-cmd-present +++ b/bin/omarchy-cmd-present @@ -3,7 +3,7 @@ # omarchy:summary=Check whether all required commands are available for cmd in "$@"; do - command -v "$cmd" &>/dev/null || exit 1 + command -v -- "$cmd" &>/dev/null || exit 1 done exit 0 diff --git a/bin/omarchy-hook-install b/bin/omarchy-hook-install index 7c53648259be..3eb1197a48cc 100755 --- a/bin/omarchy-hook-install +++ b/bin/omarchy-hook-install @@ -16,7 +16,7 @@ fi HOOK_TYPE=$1 HOOK_FILE=$2 HOOK_DIR="$HOME/.config/omarchy/hooks/$HOOK_TYPE.d" -HOOK_NAME=$(basename "$HOOK_FILE") +HOOK_NAME=$(basename -- "$HOOK_FILE") HOOK_PATH="$HOOK_DIR/$HOOK_NAME" if [[ ! -f $HOOK_FILE ]]; then @@ -25,7 +25,7 @@ if [[ ! -f $HOOK_FILE ]]; then fi mkdir -p "$HOOK_DIR" -cp "$HOOK_FILE" "$HOOK_PATH" +cp -- "$HOOK_FILE" "$HOOK_PATH" chmod 755 "$HOOK_PATH" echo "Installed $HOOK_TYPE hook: $HOOK_PATH" diff --git a/bin/omarchy-hw-match b/bin/omarchy-hw-match index 318ca7e8c69b..cecca3b08e73 100755 --- a/bin/omarchy-hw-match +++ b/bin/omarchy-hw-match @@ -3,5 +3,5 @@ # omarchy:summary=Match against the computer's DMI product name or product family (case-insensitive). # omarchy:args= -grep -qi "$1" /sys/class/dmi/id/product_name 2>/dev/null || -grep -qi "$1" /sys/class/dmi/id/product_family 2>/dev/null +grep -qi -- "$1" /sys/class/dmi/id/product_name 2>/dev/null || +grep -qi -- "$1" /sys/class/dmi/id/product_family 2>/dev/null diff --git a/bin/omarchy-launch-editor b/bin/omarchy-launch-editor index 8a69dabd4bbc..926e75d1e759 100755 --- a/bin/omarchy-launch-editor +++ b/bin/omarchy-launch-editor @@ -23,12 +23,12 @@ omarchy-cmd-present "$editor" || editor="nvim" case "${editor##*/}" in nvim | vim | nano | micro | hx | helix | fresh) if [[ $inline == "true" ]]; then - exec "$editor" "$@" + exec "$editor" -- "$@" else - exec omarchy-launch-tui "$editor" "$@" + exec omarchy-launch-tui "$editor" -- "$@" fi ;; *) - exec setsid uwsm-app -- "$editor" "$@" + exec setsid uwsm-app -- "$editor" -- "$@" ;; esac diff --git a/bin/omarchy-pkg-add b/bin/omarchy-pkg-add index 977d7efdbc98..1f5e40913d33 100755 --- a/bin/omarchy-pkg-add +++ b/bin/omarchy-pkg-add @@ -7,15 +7,15 @@ if omarchy-pkg-missing "$@"; then if (( EUID == 0 )); then - pacman -S --noconfirm --needed "$@" || exit 1 + pacman -S --noconfirm --needed -- "$@" || exit 1 else - sudo pacman -S --noconfirm --needed "$@" || exit 1 + sudo pacman -S --noconfirm --needed -- "$@" || exit 1 fi fi for pkg in "$@"; do # Secondary check to handle states where pacman doesn't actually register an error - if ! pacman -Q "$pkg" &>/dev/null; then + if ! pacman -Q -- "$pkg" &>/dev/null; then echo -e "\033[31mError: Package '$pkg' did not install\033[0m" >&2 exit 1 fi diff --git a/bin/omarchy-pkg-aur-add b/bin/omarchy-pkg-aur-add index 7a152be7fe8a..64ad097c6202 100755 --- a/bin/omarchy-pkg-aur-add +++ b/bin/omarchy-pkg-aur-add @@ -4,12 +4,12 @@ # omarchy:args= if omarchy-pkg-missing "$@"; then - yay -S --noconfirm --needed "$@" || exit 1 + yay -S --noconfirm --needed -- "$@" || exit 1 fi for pkg in "$@"; do # Secondary check to handle states where pacman doesn't actually register an error - if ! pacman -Q "$pkg" &>/dev/null; then + if ! pacman -Q -- "$pkg" &>/dev/null; then echo -e "\033[31mError: Package '$pkg' did not install\033[0m" >&2 exit 1 fi diff --git a/bin/omarchy-pkg-missing b/bin/omarchy-pkg-missing index c4059dff83ca..b282d2f33683 100755 --- a/bin/omarchy-pkg-missing +++ b/bin/omarchy-pkg-missing @@ -4,7 +4,7 @@ # omarchy:args= for pkg in "$@"; do - if ! pacman -Q "$pkg" &>/dev/null; then + if ! pacman -Q -- "$pkg" &>/dev/null; then exit 0 fi done diff --git a/bin/omarchy-pkg-present b/bin/omarchy-pkg-present index 8c4340d65f3d..0a0645bda167 100755 --- a/bin/omarchy-pkg-present +++ b/bin/omarchy-pkg-present @@ -4,7 +4,7 @@ # omarchy:args= for pkg in "$@"; do - pacman -Q "$pkg" &>/dev/null || exit 1 + pacman -Q -- "$pkg" &>/dev/null || exit 1 done exit 0 diff --git a/bin/omarchy-restart-app b/bin/omarchy-restart-app index d250650dbd12..e7d7ce5d6d51 100755 --- a/bin/omarchy-restart-app +++ b/bin/omarchy-restart-app @@ -3,5 +3,5 @@ # omarchy:summary=Restart an application by killing it and relaunching via uwsm. # omarchy:args= [application-args...] -pkill -x $1 +pkill -x -- "$1" setsid uwsm-app -- "$@" >/dev/null 2>&1 & diff --git a/test/shell.d/command-operand-boundaries-test.sh b/test/shell.d/command-operand-boundaries-test.sh new file mode 100755 index 000000000000..652b1ce71d26 --- /dev/null +++ b/test/shell.d/command-operand-boundaries-test.sh @@ -0,0 +1,259 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +export OMARCHY_PATH="$ROOT" + +if "$ROOT/bin/omarchy-cmd-present" -p; then + fail "cmd-present treats an option-shaped command name literally" +fi +pass "cmd-present treats an option-shaped command name literally" + +"$ROOT/bin/omarchy-cmd-missing" -p || + fail "cmd-missing treats an option-shaped command name literally" +pass "cmd-missing treats an option-shaped command name literally" + +"$ROOT/bin/omarchy-cmd-present" bash || fail "cmd-present still finds an ordinary command" +pass "cmd-present still finds an ordinary command" + +test_tmp=$(mktemp -d) +trap 'rm -rf "$test_tmp"' EXIT + +mock_bin="$test_tmp/bin" +mkdir -p "$mock_bin" + +cat >"$mock_bin/pacman" <<'STUB' +#!/bin/bash + +if [[ -n ${OMARCHY_TEST_PACKAGE_CALLS:-} ]]; then + { + printf 'pacman' + printf ' <%s>' "$@" + printf '\n' + } >>"$OMARCHY_TEST_PACKAGE_CALLS" +fi + +if [[ $1 == "-S" ]]; then + exit 0 +elif [[ $1 != "-Q" ]]; then + exit 2 +fi +shift + +if [[ -n ${OMARCHY_TEST_PACKAGE_CALLS:-} ]]; then + exit 0 +elif [[ ${1:-} == "--" ]]; then + shift + [[ ${1:-} == "installed" ]] +elif [[ ${1:-} == "--help" ]]; then + exit 0 +else + [[ ${1:-} == "installed" ]] +fi +STUB +chmod +x "$mock_bin/pacman" + +if PATH="$mock_bin:$PATH" "$ROOT/bin/omarchy-pkg-present" --help; then + fail "pkg-present treats an option-shaped package name literally" +fi +pass "pkg-present treats an option-shaped package name literally" + +PATH="$mock_bin:$PATH" "$ROOT/bin/omarchy-pkg-missing" --help || + fail "pkg-missing treats an option-shaped package name literally" +pass "pkg-missing treats an option-shaped package name literally" + +PATH="$mock_bin:$PATH" "$ROOT/bin/omarchy-pkg-present" installed || + fail "pkg-present still finds an installed package" +pass "pkg-present still finds an installed package" + +package_calls="$test_tmp/package-calls" +cat >"$mock_bin/omarchy-pkg-missing" <<'STUB' +#!/bin/bash + +exit 0 +STUB +cat >"$mock_bin/sudo" <<'STUB' +#!/bin/bash + +exec "$@" +STUB +cat >"$mock_bin/yay" <<'STUB' +#!/bin/bash + +: "${OMARCHY_TEST_PACKAGE_CALLS:?}" +{ + printf 'yay' + printf ' <%s>' "$@" + printf '\n' +} >>"$OMARCHY_TEST_PACKAGE_CALLS" +STUB +chmod +x "$mock_bin/omarchy-pkg-missing" "$mock_bin/sudo" "$mock_bin/yay" + +: >"$package_calls" +PATH="$mock_bin:$ROOT/bin:$PATH" OMARCHY_TEST_PACKAGE_CALLS="$package_calls" \ + "$ROOT/bin/omarchy-pkg-add" --hookdir=/tmp/hooks + +grep -Fx 'pacman <-S> <--noconfirm> <--needed> <--> <--hookdir=/tmp/hooks>' "$package_calls" >/dev/null || + fail "pkg-add separates package operands from pacman options" "$(<"$package_calls")" +grep -Fx 'pacman <-Q> <--> <--hookdir=/tmp/hooks>' "$package_calls" >/dev/null || + fail "pkg-add verifies an option-shaped package name literally" "$(<"$package_calls")" +pass "pkg-add keeps option-shaped package names out of pacman option parsing" + +: >"$package_calls" +PATH="$mock_bin:$ROOT/bin:$PATH" OMARCHY_TEST_PACKAGE_CALLS="$package_calls" \ + "$ROOT/bin/omarchy-pkg-aur-add" --hookdir=/tmp/hooks + +grep -Fx 'yay <-S> <--noconfirm> <--needed> <--> <--hookdir=/tmp/hooks>' "$package_calls" >/dev/null || + fail "pkg-aur-add separates package operands from yay options" "$(<"$package_calls")" +grep -Fx 'pacman <-Q> <--> <--hookdir=/tmp/hooks>' "$package_calls" >/dev/null || + fail "pkg-aur-add verifies an option-shaped package name literally" "$(<"$package_calls")" +pass "pkg-aur-add keeps option-shaped package names out of package-manager option parsing" + +cat >"$mock_bin/grep" <<'STUB' +#!/bin/bash + +if [[ $1 != "-qi" ]]; then + exit 2 +fi +shift + +if [[ ${1:-} == "--help" ]]; then + exit 0 +elif [[ ${1:-} == "--" ]]; then + shift +fi +[[ ${1:-} == "known-hardware" ]] +STUB +chmod +x "$mock_bin/grep" + +if PATH="$mock_bin:$PATH" "$ROOT/bin/omarchy-hw-match" --help; then + fail "hw-match treats an option-shaped hardware pattern literally" +fi +pass "hw-match treats an option-shaped hardware pattern literally" + +PATH="$mock_bin:$PATH" "$ROOT/bin/omarchy-hw-match" known-hardware || + fail "hw-match still accepts an ordinary hardware pattern" +pass "hw-match still accepts an ordinary hardware pattern" + +pkill_calls="$test_tmp/pkill-calls" +cat >"$mock_bin/pkill" <<'STUB' +#!/bin/bash + +: "${OMARCHY_TEST_PKILL_CALLS:?}" +printf '<%s>\n' "$@" >"$OMARCHY_TEST_PKILL_CALLS" +STUB +cat >"$mock_bin/setsid" <<'STUB' +#!/bin/bash + +if [[ -n ${OMARCHY_TEST_SETSID_CALLS:-} ]]; then + printf '<%s>\n' "$@" >"$OMARCHY_TEST_SETSID_CALLS" +fi +exit 0 +STUB +chmod +x "$mock_bin/pkill" "$mock_bin/setsid" + +PATH="$mock_bin:$PATH" OMARCHY_TEST_PKILL_CALLS="$pkill_calls" \ + "$ROOT/bin/omarchy-restart-app" "-9 kitty" + +pkill_argv=$(<"$pkill_calls") +[[ $pkill_argv == $'<-x>\n<-->\n<-9 kitty>' ]] || + fail "restart-app treats the application name as one literal pkill pattern" "$pkill_argv" +pass "restart-app treats the application name as one literal pkill pattern" + +fake_home="$test_tmp/home" +editor_calls="$test_tmp/editor-calls" +mkdir -p "$fake_home/.local/state/omarchy/defaults" +printf 'nvim\n' >"$fake_home/.local/state/omarchy/defaults/editor" + +cat >"$mock_bin/nvim" <<'STUB' +#!/bin/bash + +: "${OMARCHY_TEST_EDITOR_CALLS:?}" +printf '<%s>\n' "$@" >"$OMARCHY_TEST_EDITOR_CALLS" +STUB +chmod +x "$mock_bin/nvim" + +HOME="$fake_home" PATH="$mock_bin:$ROOT/bin:$PATH" OMARCHY_TEST_EDITOR_CALLS="$editor_calls" \ + "$ROOT/bin/omarchy-launch-editor" --inline -cquit + +editor_argv=$(<"$editor_calls") +[[ $editor_argv == $'<-->\n<-cquit>' ]] || + fail "launch-editor separates an option-shaped path from editor options" "$editor_argv" +pass "launch-editor separates an option-shaped path from editor options" + +cat >"$mock_bin/omarchy-launch-tui" <<'STUB' +#!/bin/bash + +: "${OMARCHY_TEST_EDITOR_CALLS:?}" +printf '<%s>\n' "$@" >"$OMARCHY_TEST_EDITOR_CALLS" +STUB +chmod +x "$mock_bin/omarchy-launch-tui" + +HOME="$fake_home" PATH="$mock_bin:$ROOT/bin:$PATH" OMARCHY_TEST_EDITOR_CALLS="$editor_calls" \ + "$ROOT/bin/omarchy-launch-editor" -cquit + +editor_argv=$(<"$editor_calls") +[[ $editor_argv == $'\n<-->\n<-cquit>' ]] || + fail "launch-editor separates a terminal editor path from editor options" "$editor_argv" +pass "launch-editor separates a terminal editor path from editor options" + +setsid_calls="$test_tmp/setsid-calls" +printf 'code\n' >"$fake_home/.local/state/omarchy/defaults/editor" +cat >"$mock_bin/code" <<'STUB' +#!/bin/bash + +exit 0 +STUB +chmod +x "$mock_bin/code" + +HOME="$fake_home" PATH="$mock_bin:$ROOT/bin:$PATH" OMARCHY_TEST_SETSID_CALLS="$setsid_calls" \ + "$ROOT/bin/omarchy-launch-editor" -cquit + +setsid_argv=$(<"$setsid_calls") +[[ $setsid_argv == $'\n<-->\n\n<-->\n<-cquit>' ]] || + fail "launch-editor separates a graphical editor path from editor options" "$setsid_argv" +pass "launch-editor separates a graphical editor path from editor options" + +hook_calls="$test_tmp/hook-calls" +hook_home="$test_tmp/hook-home" +printf '#!/bin/bash\n' >"$test_tmp/--help" +cat >"$mock_bin/basename" <<'STUB' +#!/bin/bash + +: "${OMARCHY_TEST_HOOK_CALLS:?}" +{ + printf 'basename' + printf ' <%s>' "$@" + printf '\n' +} >>"$OMARCHY_TEST_HOOK_CALLS" +printf 'literal-hook\n' +STUB +cat >"$mock_bin/cp" <<'STUB' +#!/bin/bash + +: "${OMARCHY_TEST_HOOK_CALLS:?}" +{ + printf 'cp' + printf ' <%s>' "$@" + printf '\n' +} >>"$OMARCHY_TEST_HOOK_CALLS" +STUB +for command in mkdir chmod; do + printf '#!/bin/bash\nexit 0\n' >"$mock_bin/$command" +done +chmod +x "$mock_bin/basename" "$mock_bin/cp" "$mock_bin/mkdir" "$mock_bin/chmod" + +: >"$hook_calls" +( + cd -- "$test_tmp" + HOME="$hook_home" PATH="$mock_bin:$PATH" OMARCHY_TEST_HOOK_CALLS="$hook_calls" \ + "$ROOT/bin/omarchy-hook-install" post-update --help >/dev/null +) + +hook_argv=$(<"$hook_calls") +expected_hook_argv=$'basename <--> <--help>\ncp <--> <--help> <'"$hook_home"'/.config/omarchy/hooks/post-update.d/literal-hook>' +[[ $hook_argv == $expected_hook_argv ]] || + fail "hook-install treats its source file as an operand" "$hook_argv" +pass "hook-install treats its source file as an operand" From 21cf0db6e9024ed5ec3aa2a6b261b0eda9608aaa Mon Sep 17 00:00:00 2001 From: LM Date: Sat, 12 Sep 2026 20:10:41 +0200 Subject: [PATCH 044/194] Update shell tests for operand delimiters --- bin/omarchy-setup-security-fingerprint | 2 +- .../fingerprint-driver-migration-test.sh | 24 +++++++++++++++---- test/shell.d/fingerprint-package-test.sh | 11 +++++++-- test/shell.d/menu-guards-test.sh | 6 ++++- 4 files changed, 34 insertions(+), 9 deletions(-) diff --git a/bin/omarchy-setup-security-fingerprint b/bin/omarchy-setup-security-fingerprint index e46aaed9ba32..a57dea4a1269 100755 --- a/bin/omarchy-setup-security-fingerprint +++ b/bin/omarchy-setup-security-fingerprint @@ -80,7 +80,7 @@ fi # one transaction, so a failed install leaves the existing driver in place. if omarchy-pkg-missing libfprint-git fprintd usbutils; then echo "Installing required packages..." - sudo pacman -S --needed --noconfirm --ask 4 libfprint-git fprintd usbutils + sudo pacman -S --needed --noconfirm --ask 4 -- libfprint-git fprintd usbutils fi # Enroll first fingerprint diff --git a/test/shell.d/fingerprint-driver-migration-test.sh b/test/shell.d/fingerprint-driver-migration-test.sh index 6b3f523caccf..3164c2dd4389 100755 --- a/test/shell.d/fingerprint-driver-migration-test.sh +++ b/test/shell.d/fingerprint-driver-migration-test.sh @@ -24,12 +24,26 @@ STUB cat > "$scratch/bin/pacman" <<'STUB' #!/bin/bash case "$1" in - -Q) grep -qx "$2" <<< "${INSTALLED:-}" || grep -qx "$2" "$INSTALLED_LOG" ;; + -Q) + if [[ $2 == "--" ]]; then + shift 2 + else + shift + fi + if grep -qx -- "$1" <<< "${INSTALLED:-}"; then + : + else + grep -qx -- "$1" "$INSTALLED_LOG" + fi + ;; -S) printf 'pacman %s\n' "$*" >> "$CALL_LOG" - for arg in "$@"; do - [[ $arg == -* ]] || printf '%s\n' "$arg" >> "$INSTALLED_LOG" - done + if [[ $4 == "--" ]]; then + shift 4 + for arg in "$@"; do + printf '%s\n' "$arg" >> "$INSTALLED_LOG" + done + fi ;; *) printf 'pacman %s\n' "$*" >> "$CALL_LOG" ;; esac @@ -44,7 +58,7 @@ run_migration() { } INSTALLED='fprintd' run_migration -grep -qx 'pacman -S --noconfirm --needed libfprint-git' "$CALL_LOG" || fail "fprintd without a library gets libfprint-git" +grep -qx 'pacman -S --noconfirm --needed -- libfprint-git' "$CALL_LOG" || fail "fprintd without a library gets libfprint-git" pass "fprintd without a library gets libfprint-git" INSTALLED=$'libfprint-git\nfprintd' run_migration diff --git a/test/shell.d/fingerprint-package-test.sh b/test/shell.d/fingerprint-package-test.sh index 70329982613d..efc14fcc52e7 100755 --- a/test/shell.d/fingerprint-package-test.sh +++ b/test/shell.d/fingerprint-package-test.sh @@ -30,7 +30,14 @@ STUB cat > "$scratch/bin/pacman" <<'STUB' #!/bin/bash case "$1" in - -Q) grep -qx "$2" <<< "${INSTALLED:-}" ;; + -Q) + if [[ $2 == "--" ]]; then + shift 2 + else + shift + fi + grep -qx -- "$1" <<< "${INSTALLED:-}" + ;; -S) printf 'pacman %s\n' "$*" >> "$CALL_LOG" exit "${INSTALL_STATUS:-0}" @@ -62,7 +69,7 @@ run_setup() { } assert_installs() { - grep -qx 'pacman -S --needed --noconfirm --ask 4 libfprint-git fprintd usbutils' "$CALL_LOG" || fail "$1" + grep -qx 'pacman -S --needed --noconfirm --ask 4 -- libfprint-git fprintd usbutils' "$CALL_LOG" || fail "$1" (( $(grep -c '^pacman ' "$CALL_LOG") == 1 )) || fail "$1: one pacman transaction" } diff --git a/test/shell.d/menu-guards-test.sh b/test/shell.d/menu-guards-test.sh index 660d77c5bce1..546596ce0bf4 100755 --- a/test/shell.d/menu-guards-test.sh +++ b/test/shell.d/menu-guards-test.sh @@ -118,7 +118,11 @@ Version : 9.2-1 INFO ;; -Q) - shift + if [[ $2 == "--" ]]; then + shift 2 + else + shift + fi for want in "$@"; do case "${want%%[<>=]*}" in bash | gvim | sh | vim | xxd) ;; *) exit 1 ;; esac done From 55799c4ab09f9cf9a60aed42b79f9ecf9f44bb2b Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 13 Sep 2026 08:56:39 +0200 Subject: [PATCH 045/194] Poll the active power profile over D-Bus instead of powerprofilesctl The battery service ran `powerprofilesctl get` every two seconds to keep the active profile visible to the wallpaper and lock services. That command is a PyGObject script, so the shell spawned a Python interpreter for it tens of thousands of times a day. Roughly once a day one of those exits into a CPython 3.14 finalization race (python/cpython#124619): the GLib D-Bus worker thread calls PyGILState_Ensure after the interpreter is torn down and the process dies with SIGSEGV, leaving a core dump and a crash notification behind. Read the ActiveProfile property straight from power-profiles-daemon with busctl, the same way omarchy-powerprofiles-set already reads UPower. The output is JSON, so an empty or malformed reply when the daemon is not running still reads as no active profile, matching the previous behaviour. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_011gbfh4Mi9dK6SAd1P2xMTi --- shell/plugins/services/battery/Service.qml | 26 +++++++++++++++++----- test/shell.d/video-background-test.sh | 3 ++- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/shell/plugins/services/battery/Service.qml b/shell/plugins/services/battery/Service.qml index a1b01cfff60a..eb7561f10f91 100644 --- a/shell/plugins/services/battery/Service.qml +++ b/shell/plugins/services/battery/Service.qml @@ -59,6 +59,16 @@ Item { if (!powerProfileReadProcess.running) powerProfileReadProcess.running = true } + function parseActiveProfile(text) { + // busctl --json=short prints {"type":"s","data":"balanced"}; an empty or + // malformed reply (daemon not running) reads as no active profile. + try { + return String(JSON.parse(text).data || "").trim() + } catch (e) { + return "" + } + } + Process { id: warningProcess } Process { @@ -71,17 +81,23 @@ Item { Process { id: powerProfileReadProcess - command: ["powerprofilesctl", "get"] + // Read the property straight from the daemon rather than via + // `powerprofilesctl get`. That is a PyGObject script, and spawning a Python + // interpreter for it every two seconds trips a CPython 3.14 shutdown race + // (python/cpython#124619): the GLib D-Bus worker thread re-enters the + // interpreter after finalization and the process dies with SIGSEGV, + // leaving a core dump and a crash notification behind roughly daily. + command: ["busctl", "--json=short", "get-property", "net.hadess.PowerProfiles", "/net/hadess/PowerProfiles", "net.hadess.PowerProfiles", "ActiveProfile"] stdout: StdioCollector { waitForEnd: true - onStreamFinished: root.activePowerProfile = String(text || "").trim() + onStreamFinished: root.activePowerProfile = root.parseActiveProfile(text) } } Timer { - // powerprofilesctl has no portable monitor subcommand; keep profile changes - // visible to consumers such as the wallpaper service without requiring the - // power panel to be open. + // There is no portable way to subscribe to profile changes from QML; keep + // them visible to consumers such as the wallpaper service without requiring + // the power panel to be open. interval: 2000 running: true repeat: true diff --git a/test/shell.d/video-background-test.sh b/test/shell.d/video-background-test.sh index 1a15dacef6a4..7ebad86bf67a 100755 --- a/test/shell.d/video-background-test.sh +++ b/test/shell.d/video-background-test.sh @@ -174,7 +174,8 @@ assert( assert( batteryService.includes('property string activePowerProfile') && batteryService.includes('UPower.onBattery && activePowerProfile === "power-saver"') && - batteryService.includes('["powerprofilesctl", "get"]') && + batteryService.includes('"get-property", "net.hadess.PowerProfiles", "/net/hadess/PowerProfiles", "net.hadess.PowerProfiles", "ActiveProfile"') && + !batteryService.includes('["powerprofilesctl"') && batteryService.includes('interval: 2000'), 'the battery service tracks the active power-saver profile' ) From 1b001a69d30bf89e4672a8fc15ea38c7359bff96 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 13 Sep 2026 00:56:44 -0700 Subject: [PATCH 046/194] Re-center the Plymouth prompt when a display appears late (#11641) The theme laid out the logo, password entry and progress bar once, when the script first ran. Plymouth sizes its window to the largest display present, so a monitor that comes up after plymouthd starts (a Thunderbolt display whose DisplayPort tunnel is established about a second after the kernel's display driver loads, a dock, an MST hub) got the prompt drawn at the internal panel's coordinates: off-center on the external display and partly off-screen on the panel. With the lid closed the passphrase box was effectively invisible. Move the layout into a function and re-run it from the refresh callback whenever Window.GetWidth/GetHeight change, which is how Plymouth's script plugin exposes a display being added or removed. Existing bullets are repositioned too. Co-authored-by: Claude Fable 5.1 --- default/plymouth/omarchy.script | 81 ++++++++++++++++++++++----------- 1 file changed, 54 insertions(+), 27 deletions(-) diff --git a/default/plymouth/omarchy.script b/default/plymouth/omarchy.script index 581514d73173..0c9492bd97a6 100644 --- a/default/plymouth/omarchy.script +++ b/default/plymouth/omarchy.script @@ -5,8 +5,6 @@ Window.SetBackgroundBottomColor(0.101, 0.105, 0.149); logo.image = Image("logo.png"); logo.sprite = Sprite(logo.image); -logo.sprite.SetX(Window.GetWidth() / 2 - logo.image.GetWidth() / 2); -logo.sprite.SetY(Window.GetHeight() / 2 - logo.image.GetHeight() / 2); logo.sprite.SetOpacity(1); # Use these to adjust the progress bar timing @@ -22,7 +20,18 @@ global.fake_progress_start_time = 0.0; # Track when fake progress started global.password_shown = 0; # Track if password dialog has been shown global.max_progress = 0.0; # Track the maximum progress reached to prevent backwards movement +# Window size the sprites were last laid out for +global.layout_width = 0; +global.layout_height = 0; + fun refresh_callback() { + # Displays can show up after this script ran, e.g. a Thunderbolt monitor + # whose DisplayPort tunnel comes up after plymouthd started. The window + # grows to the largest display, so re-center everything when it changes. + if (Window.GetWidth() != global.layout_width || Window.GetHeight() != global.layout_height) { + layout(); + } + global.animation_frame++; # Animate fake progress to limit over time with easing @@ -108,27 +117,23 @@ entry.image = Image("entry.png"); bullet.image = Image("bullet.png"); entry.sprite = Sprite(entry.image); -entry.x = Window.GetWidth() / 2 - entry.image.GetWidth() / 2; -entry.y = logo.sprite.GetY() + logo.image.GetHeight() + 40; -entry.sprite.SetPosition(entry.x, entry.y, 10001); entry.sprite.SetOpacity(0); # Scale lock to be slightly shorter than entry field height # Original lock is 84x96, entry height determines scale -lock_height = entry.image.GetHeight() * 0.8; -lock_scale = lock_height / 96; -lock_width = 84 * lock_scale; - -scaled_lock = lock.image.Scale(lock_width, lock_height); -lock.sprite = Sprite(scaled_lock); -lock.x = entry.x - lock_width - 15; -lock.y = entry.y + entry.image.GetHeight() / 2 - lock_height / 2; -lock.sprite.SetPosition(lock.x, lock.y, 10001); +lock.height = entry.image.GetHeight() * 0.8; +lock.width = 84 * (lock.height / 96); + +lock.sprite = Sprite(lock.image.Scale(lock.width, lock.height)); lock.sprite.SetOpacity(0); # Bullet array bullet.sprites = []; +fun position_bullet(index) { + bullet.sprites[index].SetPosition(entry.x + 20 + index * (7 + 5), entry.y + entry.image.GetHeight() / 2 - 3.5, 10002); +} + fun display_normal_callback() { hide_password_dialog(); @@ -165,11 +170,8 @@ fun display_password_callback(prompt, bullets) { for (index = 0; index < bullets_to_show; index++) { if (!bullet.sprites[index]) { # Scale bullet image to 7x7 pixels - scaled_bullet = bullet.image.Scale(7, 7); - bullet.sprites[index] = Sprite(scaled_bullet); - bullet.x = entry.x + 20 + index * (7 + 5); - bullet.y = entry.y + entry.image.GetHeight() / 2 - 3.5; - bullet.sprites[index].SetPosition(bullet.x, bullet.y, 10002); + bullet.sprites[index] = Sprite(bullet.image.Scale(7, 7)); + position_bullet(index); } bullet.sprites[index].SetOpacity(1); @@ -183,19 +185,11 @@ Plymouth.SetDisplayPasswordFunction(display_password_callback); progress_box.image = Image("progress_box.png"); progress_box.sprite = Sprite(progress_box.image); - -progress_box.x = Window.GetWidth() / 2 - progress_box.image.GetWidth() / 2; -progress_box.y = entry.y + entry.image.GetHeight() / 2 - progress_box.image.GetHeight() / 2; -progress_box.sprite.SetPosition(progress_box.x, progress_box.y, 0); progress_box.sprite.SetOpacity(0); progress_bar.original_image = Image("progress_bar.png"); progress_bar.sprite = Sprite(); progress_bar.image = progress_bar.original_image.Scale(1, progress_bar.original_image.GetHeight()); - -progress_bar.x = Window.GetWidth() / 2 - progress_bar.original_image.GetWidth() / 2; -progress_bar.y = progress_box.y + (progress_box.image.GetHeight() - progress_bar.original_image.GetHeight()) / 2; -progress_bar.sprite.SetPosition(progress_bar.x, progress_bar.y, 1); progress_bar.sprite.SetOpacity(0); fun progress_callback(duration, progress) { @@ -216,6 +210,39 @@ fun progress_callback(duration, progress) { Plymouth.SetBootProgressFunction(progress_callback); +#----------------------------------------- Layout -------------------------------- + +# Center the logo, dialogue and progress bar for the current window size +fun layout() { + global.layout_width = Window.GetWidth(); + global.layout_height = Window.GetHeight(); + + logo.sprite.SetX(global.layout_width / 2 - logo.image.GetWidth() / 2); + logo.sprite.SetY(global.layout_height / 2 - logo.image.GetHeight() / 2); + + entry.x = global.layout_width / 2 - entry.image.GetWidth() / 2; + entry.y = logo.sprite.GetY() + logo.image.GetHeight() + 40; + entry.sprite.SetPosition(entry.x, entry.y, 10001); + + lock.x = entry.x - lock.width - 15; + lock.y = entry.y + entry.image.GetHeight() / 2 - lock.height / 2; + lock.sprite.SetPosition(lock.x, lock.y, 10001); + + for (index = 0; bullet.sprites[index]; index++) { + position_bullet(index); + } + + progress_box.x = global.layout_width / 2 - progress_box.image.GetWidth() / 2; + progress_box.y = entry.y + entry.image.GetHeight() / 2 - progress_box.image.GetHeight() / 2; + progress_box.sprite.SetPosition(progress_box.x, progress_box.y, 0); + + progress_bar.x = global.layout_width / 2 - progress_bar.original_image.GetWidth() / 2; + progress_bar.y = progress_box.y + (progress_box.image.GetHeight() - progress_bar.original_image.GetHeight()) / 2; + progress_bar.sprite.SetPosition(progress_bar.x, progress_bar.y, 1); +} + +layout(); + #----------------------------------------- Message -------------------------------- message_sprite = Sprite(); From f5194e3ff596789b71b912ba945d90e3693cf6aa Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 13 Sep 2026 10:21:38 +0200 Subject: [PATCH 047/194] Shield Omarchy pacman transactions from desktop session teardown Upgrading systemd runs its post_upgrade scriptlet mid-transaction, which reexecs both the system manager and every user manager. When pacman runs inside a user-session scope (the floating update terminal), that reexec can SIGKILL it and abandon the transaction halfway, with packages upgraded but none of the post-transaction hooks run. Route every Omarchy-owned system mutation through a new hidden omarchy-update-pacman helper that registers the transaction as a PID 1 scope via systemd-run, keeping it out of the user manager's cgroups. System scopes survive the system manager's own reexec, and as a bonus the transaction now also survives its terminal window closing. On unbooted systems (the installer chroot) the helper runs pacman directly. Co-Authored-By: Claude Fable 5 --- bin/omarchy-channel-set | 2 +- bin/omarchy-refresh-pacman | 2 +- bin/omarchy-reinstall-pkgs | 4 ++-- bin/omarchy-update-pacman | 25 +++++++++++++++++++++++++ bin/omarchy-update-system-pkgs | 4 ++-- docs/update-process.md | 14 ++++++++++---- test/shell.d/channel-test.sh | 18 ++++++++++++------ 7 files changed, 53 insertions(+), 16 deletions(-) create mode 100755 bin/omarchy-update-pacman diff --git a/bin/omarchy-channel-set b/bin/omarchy-channel-set index 7e1123885086..dcc9bdb44388 100755 --- a/bin/omarchy-channel-set +++ b/bin/omarchy-channel-set @@ -85,7 +85,7 @@ fi omarchy-refresh-pacman "$pacman_channel" # --ask 4 accepts omarchy <-> omarchy-dev replacement prompts without file overwrites. -sudo env OMARCHY_UPDATE_PACMAN=1 pacman -S --needed --noconfirm --ask 4 "${packages[@]}" +omarchy-update-pacman -S --needed --noconfirm --ask 4 "${packages[@]}" if [[ -z $dev_checkout ]]; then omarchy-dev-unlink --no-reboot diff --git a/bin/omarchy-refresh-pacman b/bin/omarchy-refresh-pacman index 299d6c20d20d..af16a3470031 100755 --- a/bin/omarchy-refresh-pacman +++ b/bin/omarchy-refresh-pacman @@ -23,4 +23,4 @@ sudo cp -f "$OMARCHY_PATH/default/pacman/mirrorlist-$channel" /etc/pacman.d/mirr omarchy-hook pre-refresh-pacman # Reset all package DBs and then update -sudo env OMARCHY_UPDATE_PACMAN=1 pacman -Syyuu --noconfirm +omarchy-update-pacman -Syyuu --noconfirm diff --git a/bin/omarchy-reinstall-pkgs b/bin/omarchy-reinstall-pkgs index c1d51cbf3ca6..97aff9c6a561 100755 --- a/bin/omarchy-reinstall-pkgs +++ b/bin/omarchy-reinstall-pkgs @@ -11,8 +11,8 @@ set -e omarchy-refresh-pacman # Downgrade any packages to the stable setup -sudo env OMARCHY_UPDATE_PACMAN=1 pacman -Suu --noconfirm +omarchy-update-pacman -Suu --noconfirm # Ensure all packages are installed mapfile -t packages < <(grep -v '^#' "$OMARCHY_PATH/install/omarchy-base.packages" | grep -v '^$') -sudo env OMARCHY_UPDATE_PACMAN=1 pacman -Syu --noconfirm --needed "${packages[@]}" +omarchy-update-pacman -Syu --noconfirm --needed "${packages[@]}" diff --git a/bin/omarchy-update-pacman b/bin/omarchy-update-pacman new file mode 100755 index 000000000000..66f66731ef14 --- /dev/null +++ b/bin/omarchy-update-pacman @@ -0,0 +1,25 @@ +#!/bin/bash + +# omarchy:summary=Run a pacman transaction for the Omarchy update flow, shielded from desktop session teardown. +# omarchy:args= +# omarchy:hidden=true +# omarchy:requires-sudo=true + +# Upgrading systemd runs its post_upgrade scriptlet mid-transaction, which +# reexecs both the system manager and every user manager. A pacman running +# inside a user-session scope can be SIGKILLed by that reexec, abandoning the +# transaction halfway. Registering the transaction as a PID 1 scope keeps it +# out of the user manager's cgroups entirely, and system scopes survive the +# system manager's own reexec. +scope=() +if [[ -d /run/systemd/system && ! -L /run/systemd/system ]]; then + scope=(systemd-run --scope --quiet --collect) +fi + +# LC_ALL passes through so callers that parse pacman's stderr can pin the locale. +env_args=(OMARCHY_UPDATE_PACMAN=1) +if [[ -n ${LC_ALL:-} ]]; then + env_args+=(LC_ALL="$LC_ALL") +fi + +exec sudo env "${env_args[@]}" "${scope[@]}" pacman "$@" diff --git a/bin/omarchy-update-system-pkgs b/bin/omarchy-update-system-pkgs index 9e6f99983571..c2e863882683 100755 --- a/bin/omarchy-update-system-pkgs +++ b/bin/omarchy-update-system-pkgs @@ -10,7 +10,7 @@ set -e # a stream, because an upgrade without --noconfirm prompts on stderr. The # handler has already said why, so no heading here either. if [[ ${OMARCHY_UPDATE_CONFLICT:-} == 1 && ${OMARCHY_UPDATE_INTERACTIVE:-} == 1 ]]; then - exec sudo env OMARCHY_UPDATE_PACMAN=1 pacman -Syu --overwrite '/usr/share/omarchy/*' + exec omarchy-update-pacman -Syu --overwrite '/usr/share/omarchy/*' fi echo -e "\e[32m\nUpdate system packages\e[0m" @@ -23,7 +23,7 @@ trap 'rm -f "$errors"' EXIT # # Progress bars stay on stdout. Errors are on stderr, kept for the conflict # handler below; LC_ALL=C is what keeps them parseable in any locale. -if sudo env LC_ALL=C OMARCHY_UPDATE_PACMAN=1 pacman -Syu --noconfirm \ +if LC_ALL=C omarchy-update-pacman -Syu --noconfirm \ --overwrite '/usr/share/omarchy/*' 2>"$errors"; then cat "$errors" >&2 exit 0 diff --git a/docs/update-process.md b/docs/update-process.md index bec3350d1d46..efecb94c0ede 100644 --- a/docs/update-process.md +++ b/docs/update-process.md @@ -82,13 +82,18 @@ Omarchy update command, the hook exits non-zero with `AbortOnFail`, which stops the transaction before packages are changed. `omarchy-update-system-pkgs`, `omarchy-refresh-pacman`, `omarchy-reinstall-pkgs`, -`omarchy-channel-set`, and the v4 upgrader run pacman through: +and `omarchy-channel-set` run pacman through the hidden `omarchy-update-pacman` +helper (the v4 upgrader sets `OMARCHY_UPDATE_PACMAN=1` directly): ```bash -env OMARCHY_UPDATE_PACMAN=1 pacman ... +sudo env OMARCHY_UPDATE_PACMAN=1 systemd-run --scope --quiet --collect pacman ... ``` -so the guard allows Omarchy-owned update flows. A user can intentionally bypass +so the guard allows Omarchy-owned update flows. The `systemd-run --scope` +wrapper registers the transaction as a PID 1 scope: upgrading systemd reexecs +the system and user managers mid-transaction, and a pacman left inside a +user-session scope can be SIGKILLed by that reexec. On unbooted systems (such +as the installer chroot) the helper runs pacman directly. A user can intentionally bypass the guard with: ```bash @@ -272,12 +277,13 @@ scripts. | `omarchy-update-confirm` | Gum confirmation copy for `omarchy update`. | **Question.** Could be inlined into `omarchy-update`; separate file only helps keep copy isolated. | | `omarchy-update-dev` | Fast-forwards the active dev-linked checkout from its configured upstream; no-ops for package-backed installs. | **Keep.** Runs before package updates so a checkout conflict stops the update before system mutation. | | `omarchy-update-keyring` | Ensures Omarchy keyring and Arch keyring are current before the main transaction. | **Keep, but review.** It uses targeted `pacman -Sy` for keyring bootstrapping; acceptable for this special case but should remain tightly scoped. | -| `omarchy-update-system-pkgs` | Runs `sudo env OMARCHY_UPDATE_PACMAN=1 pacman -Syu --noconfirm` with `--overwrite '/usr/share/omarchy/*'`, capturing stderr to a report file; on failure it execs `omarchy-update-system-pkgs-when-conflicted`. | **Keep for now.** Small leaf command, clear/testable. | +| `omarchy-update-system-pkgs` | Runs `omarchy-update-pacman -Syu --noconfirm` with `--overwrite '/usr/share/omarchy/*'`, capturing stderr to a report file; on failure it execs `omarchy-update-system-pkgs-when-conflicted`. | **Keep for now.** Small leaf command, clear/testable. | | `omarchy-update-system-pkgs-when-conflicted` | Hidden conflict handler: quarantines unowned conflicting files under `/var/lib/omarchy/replaced`, retries the upgrade once, restores files the upgrade didn't claim, and hands package-vs-package conflicts to an interactive pacman run (never under `-y`). | **Keep internal/hidden.** Keeps conflict recovery out of the happy path. | | `omarchy-update-pkg-prune` | Trims the pacman cache to two versions per package (`paccache -rk2`) before the snapshot, keeping the offline downgrade path while capping snapshot growth. | **Keep internal/hidden.** | | `omarchy-update-requires-free-space` | Aborts the update below a 10 GiB free-space threshold on `/`; silently skipped when free space cannot be determined; `OMARCHY_UPDATE_FORCE=1` bypasses. | **Keep internal/hidden.** | | `omarchy-migrate` | Public migration command. Waits for pacman, then runs all pending migrations for the current user. Supports `--pending`. | **Keep.** This replaces the discarded `omarchy-update-user-finalize` name and no longer needs `--force`. | | `omarchy-update-pacman-guard` | ALPM pre-transaction guard that aborts direct `pacman -Syu` style upgrades unless Omarchy set `OMARCHY_UPDATE_PACMAN=1` or the user explicitly set `OMARCHY_ALLOW_DIRECT_PACMAN=1`. | **Keep internal/hidden.** This is what nudges users back to `omarchy update`. | +| `omarchy-update-pacman` | Hidden helper that runs a guard-approved pacman transaction as a PID 1 scope (`systemd-run --scope`) so a mid-transaction systemd reexec cannot kill it; runs pacman directly when not booted under systemd. | **Keep internal/hidden.** Single place that owns how Omarchy invokes pacman for system mutation. | | `omarchy-migrate-notify` | Internal login-time notification helper. Uses `omarchy-migrate --pending` and shows a notification only when this user has pending migrations. | **Keep internal/hidden.** Clear name now that the public command is `omarchy-migrate`. | | `omarchy-update-user-notify` | Hidden compatibility wrapper for `omarchy-migrate-notify`. | **Temporary.** Keep only for old callers. | | `omarchy-update-available` | Update checker for shell widget and post-update refresh. | **Keep.** Could eventually be renamed `omarchy-update-check`, but current name matches widget semantics. | diff --git a/test/shell.d/channel-test.sh b/test/shell.d/channel-test.sh index 664e17c50b53..122a15aadb7b 100644 --- a/test/shell.d/channel-test.sh +++ b/test/shell.d/channel-test.sh @@ -31,6 +31,12 @@ for arg in "$@"; do printf "\t%s" "$arg" >>"$OMARCHY_CHANNEL_TEST_LOG"; done printf "\n" >>"$OMARCHY_CHANNEL_TEST_LOG" ' +write_stub omarchy-update-pacman '#!/bin/bash +printf "update-pacman" >>"$OMARCHY_CHANNEL_TEST_LOG" +for arg in "$@"; do printf "\t%s" "$arg" >>"$OMARCHY_CHANNEL_TEST_LOG"; done +printf "\n" >>"$OMARCHY_CHANNEL_TEST_LOG" +' + write_stub omarchy-dev-unlink '#!/bin/bash printf "unlink" >>"$OMARCHY_CHANNEL_TEST_LOG" for arg in "$@"; do printf "\t%s" "$arg" >>"$OMARCHY_CHANNEL_TEST_LOG"; done @@ -106,7 +112,7 @@ assert_log_line() { run_channel stable assert_log_line $'refresh\tstable' "stable refreshes the stable pacman channel" -assert_log_line $'sudo\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy\tomarchy-settings' "stable installs stable Omarchy packages" +assert_log_line $'update-pacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy\tomarchy-settings' "stable installs stable Omarchy packages" assert_log_line $'unlink\t--no-reboot' "stable restores the package-backed Omarchy path without an early reboot prompt" assert_log_line $'update\t-y\tOMARCHY_PATH=/usr/share/omarchy' "stable runs the normal update pipeline from the package-backed path" if grep -q $'^state\tset\treboot-required$' "$log_file"; then @@ -116,17 +122,17 @@ pass "stable does not require reboot when already package-backed" run_channel rc assert_log_line $'refresh\trc' "rc refreshes the rc pacman channel" -assert_log_line $'sudo\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy\tomarchy-settings' "rc installs rc Omarchy packages" +assert_log_line $'update-pacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy\tomarchy-settings' "rc installs rc Omarchy packages" assert_log_line $'unlink\t--no-reboot' "rc restores the package-backed Omarchy path without an early reboot prompt" assert_log_line $'update\t-y\tOMARCHY_PATH=/usr/share/omarchy' "rc runs the normal update pipeline from the package-backed path" OMARCHY_TEST_PATH="$ROOT" run_channel edge assert_log_line $'refresh\tedge' "edge refreshes the edge pacman channel" -assert_log_line $'sudo\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev' "edge installs development Omarchy packages" +assert_log_line $'update-pacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev' "edge installs development Omarchy packages" assert_log_line $'unlink\t--no-reboot' "edge unlinks dev without an early reboot prompt" assert_log_line $'state\tset\treboot-required' "edge marks reboot required when leaving dev" assert_log_line $'update\t-y\tOMARCHY_PATH=/usr/share/omarchy' "edge runs the normal update pipeline from the package-backed path" -[[ $(grep -E '^(unlink|state|update)' "$log_file") == $'unlink\t--no-reboot\nstate\tset\treboot-required\nupdate\t-y\tOMARCHY_PATH=/usr/share/omarchy' ]] || +[[ $(grep -E $'^(unlink|state|update)\t' "$log_file") == $'unlink\t--no-reboot\nstate\tset\treboot-required\nupdate\t-y\tOMARCHY_PATH=/usr/share/omarchy' ]] || fail "edge defers the reboot prompt until the update restart stage" "$(cat "$log_file")" pass "edge defers the reboot prompt until the update restart stage" @@ -146,12 +152,12 @@ rmdir "$checkout" run_channel dev assert_log_line $'gum\tconfirm\t--default=false\tSwitch to dev channel?' "dev asks for confirmation" assert_log_line $'refresh\tedge' "dev refreshes the edge pacman channel" -assert_log_line $'sudo\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev' "dev installs development Omarchy packages" +assert_log_line $'update-pacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev' "dev installs development Omarchy packages" assert_log_line $'git\tclone\thttps://github.com/basecamp/omarchy.git\t'"$checkout" "dev clones the source checkout to ~/omarchy" assert_log_line $'link\t'"$checkout"$'\t--no-reboot' "dev links ~/omarchy without an early reboot prompt" assert_log_line $'state\tset\treboot-required' "dev defers the reboot prompt to the update pipeline" assert_log_line $'update\t-y\tOMARCHY_PATH='"$checkout" "dev runs the normal update pipeline from the source checkout" -[[ $(grep -E '^(git|link|state|refresh|sudo|update)' "$log_file") == $'git\tclone\thttps://github.com/basecamp/omarchy.git\t'"$checkout"$'\nlink\t'"$checkout"$'\t--no-reboot\nstate\tset\treboot-required\nrefresh\tedge\nsudo\tenv\tOMARCHY_UPDATE_PACMAN=1\tpacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev\nupdate\t-y\tOMARCHY_PATH='"$checkout" ]] || +[[ $(grep -E '^(git|link|state|refresh|sudo|update)' "$log_file") == $'git\tclone\thttps://github.com/basecamp/omarchy.git\t'"$checkout"$'\nlink\t'"$checkout"$'\t--no-reboot\nstate\tset\treboot-required\nrefresh\tedge\nupdate-pacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev\nupdate\t-y\tOMARCHY_PATH='"$checkout" ]] || fail "dev activates the checkout before changing or updating packages" "$(cat "$log_file")" pass "dev activates the checkout before changing or updating packages" From bc0753dfcbf723a362060c32b3e36739798fee38 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 13 Sep 2026 10:21:46 +0200 Subject: [PATCH 048/194] Show a failure state when a presented command exits non-zero The floating-terminal presentation wrapper showed the green "Done!" prompt for every exit code except Ctrl-C, so a failed update or channel switch closed looking like a success. Pass the command's exit code through to omarchy-show-done and render a red "Failed (exit code N)!" prompt when it is non-zero. The pkg install/remove pickers get the same treatment. Co-Authored-By: Claude Fable 5 --- ...omarchy-launch-floating-terminal-with-presentation | 3 ++- bin/omarchy-pkg-aur-install | 3 ++- bin/omarchy-pkg-install | 2 +- bin/omarchy-pkg-remove | 2 +- bin/omarchy-show-done | 11 +++++++++-- 5 files changed, 15 insertions(+), 6 deletions(-) diff --git a/bin/omarchy-launch-floating-terminal-with-presentation b/bin/omarchy-launch-floating-terminal-with-presentation index c9cb255abf7e..4497ff0dd74e 100755 --- a/bin/omarchy-launch-floating-terminal-with-presentation +++ b/bin/omarchy-launch-floating-terminal-with-presentation @@ -8,6 +8,7 @@ source omarchy-restart-gum cmd="$*" -presentation_script="omarchy-show-logo; $cmd; if (( \$? != 130 )); then omarchy-show-done; fi" +# 130 is the user bailing with Ctrl-C; anything else gets the Done/Failed prompt. +presentation_script="omarchy-show-logo; $cmd; code=\$?; if (( code != 130 )); then omarchy-show-done \$code; fi" exec setsid uwsm-app -- xdg-terminal-exec --app-id=org.omarchy.terminal --title=Omarchy -e bash -c "$presentation_script" diff --git a/bin/omarchy-pkg-aur-install b/bin/omarchy-pkg-aur-install index 3d38b4db75b6..dc393b8dc304 100755 --- a/bin/omarchy-pkg-aur-install +++ b/bin/omarchy-pkg-aur-install @@ -24,6 +24,7 @@ if [[ -n $pkg_names ]]; then source omarchy-sudo-keepalive echo "$pkg_names" | sed 's/^/aur\//' | tr '\n' ' ' | xargs yay -S --noconfirm + code=$? sudo updatedb --prune-bind-mounts=no --add-prunepaths=/.snapshots - omarchy-show-done + omarchy-show-done $code fi diff --git a/bin/omarchy-pkg-install b/bin/omarchy-pkg-install index 15e5e288ef17..e5e0fb429f8f 100755 --- a/bin/omarchy-pkg-install +++ b/bin/omarchy-pkg-install @@ -22,5 +22,5 @@ if [[ -n $pkg_names ]]; then # Convert newline-separated selections to space-separated for pacman echo "$pkg_names" | tr '\n' ' ' | xargs sudo pacman -S --noconfirm - omarchy-show-done + omarchy-show-done $? fi diff --git a/bin/omarchy-pkg-remove b/bin/omarchy-pkg-remove index 486d37721234..37ca448e9b59 100755 --- a/bin/omarchy-pkg-remove +++ b/bin/omarchy-pkg-remove @@ -20,5 +20,5 @@ pkg_names=$(yay -Qqe | fzf "${fzf_args[@]}") if [[ -n $pkg_names ]]; then # Convert newline-separated selections to space-separated for yay echo "$pkg_names" | tr '\n' ' ' | xargs sudo pacman -Rns --noconfirm - omarchy-show-done + omarchy-show-done $? fi diff --git a/bin/omarchy-show-done b/bin/omarchy-show-done index d5d8ccdee892..14c9f156a0bb 100755 --- a/bin/omarchy-show-done +++ b/bin/omarchy-show-done @@ -1,6 +1,9 @@ #!/bin/bash -# omarchy:summary=Display a "Done!" message and wait for user to press any key. +# omarchy:summary=Display a "Done!" or "Failed!" message and wait for user to press any key. +# omarchy:args=[exit-code] + +code="${1:-0}" # The device node is there whether or not a terminal is behind it, so opening # it is the only test that means anything. @@ -13,6 +16,10 @@ while read -rsn 1 -t 0.1 _ /dev/tty +if (( code == 0 )); then + printf '\n\033[32m● \033[0mDone! Press any key to close...' >/dev/tty +else + printf '\n\033[31m● \033[0mFailed (exit code %d)! Press any key to close...' "$code" >/dev/tty +fi read -rsn 1 /dev/tty From 24841ac5d24552ebb7bfe4e0491949236e22963a Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 13 Sep 2026 10:21:46 +0200 Subject: [PATCH 049/194] Tell how to resume a channel switch that failed partway omarchy-channel-set runs under set -e, so a failure after it has begun mutating the system (dev link, pacman channel, packages) died silently with the switch half-applied. Trap ERR once the mutation phase starts and say how to pick the switch back up. Co-Authored-By: Claude Fable 5 --- bin/omarchy-channel-set | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/bin/omarchy-channel-set b/bin/omarchy-channel-set index dcc9bdb44388..d4c482f2d80c 100755 --- a/bin/omarchy-channel-set +++ b/bin/omarchy-channel-set @@ -72,6 +72,10 @@ case "$channel" in ;; esac +# A failure past this point leaves the channel switch half-applied, so say how +# to pick it back up rather than dying silently under set -e. +trap 'echo -e "\nThe channel switch did not complete. Review the error above, then rerun: omarchy-channel-set '"$channel"'" >&2' ERR + if [[ -z $dev_checkout && $OMARCHY_PATH != "/usr/share/omarchy" ]]; then leaving_dev=1 fi From 83c6dd230c1e9ec35550c6ad077a206b17a99b8b Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 13 Sep 2026 10:35:32 +0200 Subject: [PATCH 050/194] Keep the conflict tests inside their fixture despite the scope wrapper The update conflict tests stub sudo and pacman, but omarchy-update-pacman now puts systemd-run between them, so on a systemd-booted host the tests would reach for the real system manager. Stub systemd-run to drop the wrapper's options and run the command, and cover the helper's own invocation composition in a new test. Raised by codex review. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_015zcqENR1UbhuwC1v5u3Wop --- test/shell.d/update-file-conflict-test.sh | 10 ++++- test/shell.d/update-package-conflict-test.sh | 10 ++++- test/shell.d/update-pacman-test.sh | 39 ++++++++++++++++++++ 3 files changed, 57 insertions(+), 2 deletions(-) create mode 100755 test/shell.d/update-pacman-test.sh diff --git a/test/shell.d/update-file-conflict-test.sh b/test/shell.d/update-file-conflict-test.sh index 5fa954eafd70..526a1c6c1d2f 100755 --- a/test/shell.d/update-file-conflict-test.sh +++ b/test/shell.d/update-file-conflict-test.sh @@ -15,6 +15,14 @@ cat >"$stub_bin/sudo" <<'STUB' exec "$@" STUB +# omarchy-update-pacman wraps the transaction in a real PID 1 scope; the tests +# must stay inside the fixture, so drop the wrapper's options and run the command. +cat >"$stub_bin/systemd-run" <<'STUB' +#!/bin/bash +while [[ $1 == -* ]]; do shift; done +exec "$@" +STUB + # Fails the first -Syu with the report under test, then succeeds unless the case # asked for the retry to fail too. cat >"$stub_bin/pacman" <<'STUB' @@ -40,7 +48,7 @@ fi echo "upgrade complete" STUB -chmod +x "$stub_bin/sudo" "$stub_bin/pacman" +chmod +x "$stub_bin/sudo" "$stub_bin/systemd-run" "$stub_bin/pacman" replaced="$test_tmp/replaced" diff --git a/test/shell.d/update-package-conflict-test.sh b/test/shell.d/update-package-conflict-test.sh index cbe6286f9c5a..e05e8f7bc3e2 100755 --- a/test/shell.d/update-package-conflict-test.sh +++ b/test/shell.d/update-package-conflict-test.sh @@ -17,6 +17,14 @@ cat >"$stub_bin/sudo" <<'STUB' exec "$@" STUB +# omarchy-update-pacman wraps the transaction in a real PID 1 scope; the tests +# must stay inside the fixture, so drop the wrapper's options and run the command. +cat >"$stub_bin/systemd-run" <<'STUB' +#!/bin/bash +while [[ $1 == -* ]]; do shift; done +exec "$@" +STUB + # Fails the first -Syu with the report under test, then succeeds. Every call # records its arguments and which of its streams reached a terminal: pacman puts # its questions on stderr once it is not running --noconfirm, so a retry meant @@ -39,7 +47,7 @@ fi echo "upgrade complete" STUB -chmod +x "$stub_bin/sudo" "$stub_bin/pacman" +chmod +x "$stub_bin/sudo" "$stub_bin/systemd-run" "$stub_bin/pacman" # Everything a blocked qemu-common upgrade leaves on stderr, and no more. The # ":: ... Remove qemu-block-gluster? [y/N]" pacman asked is deliberately absent: diff --git a/test/shell.d/update-pacman-test.sh b/test/shell.d/update-pacman-test.sh new file mode 100755 index 000000000000..a9278b3752a9 --- /dev/null +++ b/test/shell.d/update-pacman-test.sh @@ -0,0 +1,39 @@ +#!/bin/bash + +set -euo pipefail + +source "$(dirname "$0")/base-test.sh" + +test_tmp=$(mktemp -d) +trap 'rm -rf "$test_tmp"' EXIT + +stub_bin="$test_tmp/bin" +mkdir -p "$stub_bin" + +cat >"$stub_bin/sudo" <<'STUB' +#!/bin/bash +printf '%s\n' "$*" >"$SUDO_CALL_LOG" +STUB +chmod +x "$stub_bin/sudo" + +run_helper() { + PATH="$stub_bin:$PATH" SUDO_CALL_LOG="$test_tmp/call" "$ROOT/bin/omarchy-update-pacman" "$@" +} + +# The scope wrapper only applies on a systemd-booted host, so expect what the +# helper's own booted check would decide for this machine. +if [[ -d /run/systemd/system && ! -L /run/systemd/system ]]; then + expected_scope="systemd-run --scope --quiet --collect " +else + expected_scope="" +fi + +run_helper -Syu --noconfirm +[[ $(cat "$test_tmp/call") == "env OMARCHY_UPDATE_PACMAN=1 ${expected_scope}pacman -Syu --noconfirm" ]] || + fail "helper composes the guarded pacman invocation" "$(cat "$test_tmp/call")" +pass "helper composes the guarded pacman invocation" + +LC_ALL=C run_helper -Syu +[[ $(cat "$test_tmp/call") == "env OMARCHY_UPDATE_PACMAN=1 LC_ALL=C ${expected_scope}pacman -Syu" ]] || + fail "helper forwards LC_ALL to the transaction" "$(cat "$test_tmp/call")" +pass "helper forwards LC_ALL to the transaction" From dae1f4bf0e3f0a4c1e1a01b423e7b0f5f442d17a Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 13 Sep 2026 11:53:27 +0200 Subject: [PATCH 051/194] Use the kyber I/O scheduler on real disks The kernel leaves NVMe on none and everything else on mq-deadline. Neither bounds latency once the device queue fills, so a large build, copy, or package upgrade can make the desktop sluggish while reads wait behind a wall of writes. Kyber keeps separate read and sync-write queues and throttles the depth it submits to hit a 2ms read target, which keeps interactive reads flowing under heavy writes at negligible CPU cost. The trade is a small ceiling on peak throughput on very fast devices, which matters for a storage server chasing IOPS but not for a desktop. Ships as a package-owned udev rule in /etc so it applies at boot and on hot-plug. Existing installs pick it up at the next boot. zram is left alone since it has nothing to schedule. Co-Authored-By: Claude Fable 5.1 --- etc/udev/rules.d/60-omarchy-io-scheduler.rules | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 etc/udev/rules.d/60-omarchy-io-scheduler.rules diff --git a/etc/udev/rules.d/60-omarchy-io-scheduler.rules b/etc/udev/rules.d/60-omarchy-io-scheduler.rules new file mode 100644 index 000000000000..7f83f6cedd38 --- /dev/null +++ b/etc/udev/rules.d/60-omarchy-io-scheduler.rules @@ -0,0 +1,6 @@ +# Kyber targets read latency (2ms) and throttles writes to hold it, so the +# desktop stays responsive under a large build, copy, or package upgrade. +# The kernel default is none for NVMe and mq-deadline for everything else, +# neither of which bounds latency once the device queue fills. Applies to real +# disks only; zram is memory and has nothing to schedule. +ACTION=="add|change", KERNEL=="nvme[0-9]*n[0-9]*|sd[a-z]*|mmcblk[0-9]*|vd[a-z]*", ATTR{queue/scheduler}="kyber" From 795ac57a6c65ed1943c62739efb228bffce048bd Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 13 Sep 2026 12:09:50 +0200 Subject: [PATCH 052/194] Match only whole disks in the kyber udev rule udev patterns are shell globs, so nvme[0-9]*n[0-9]* also matched every partition. Partitions have no queue/scheduler, and udev logged a "Could not chase sysfs attribute" for each one at boot. Restrict the match to SUBSYSTEM block with DEVTYPE disk, which also keeps mmcblk boot areas and NVMe multipath nodes out. Reword the comment: kyber targets a read latency rather than bounding it, and the kernel's default choice depends on the device rather than being a fixed NVMe versus everything-else split. Co-Authored-By: Claude Fable 5.1 --- etc/udev/rules.d/60-omarchy-io-scheduler.rules | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/etc/udev/rules.d/60-omarchy-io-scheduler.rules b/etc/udev/rules.d/60-omarchy-io-scheduler.rules index 7f83f6cedd38..1f389f4b9804 100644 --- a/etc/udev/rules.d/60-omarchy-io-scheduler.rules +++ b/etc/udev/rules.d/60-omarchy-io-scheduler.rules @@ -1,6 +1,8 @@ -# Kyber targets read latency (2ms) and throttles writes to hold it, so the -# desktop stays responsive under a large build, copy, or package upgrade. -# The kernel default is none for NVMe and mq-deadline for everything else, -# neither of which bounds latency once the device queue fills. Applies to real -# disks only; zram is memory and has nothing to schedule. -ACTION=="add|change", KERNEL=="nvme[0-9]*n[0-9]*|sd[a-z]*|mmcblk[0-9]*|vd[a-z]*", ATTR{queue/scheduler}="kyber" +# Kyber keeps reads in their own queue and throttles the depth it submits to +# hold a 2ms read latency target, so interactive reads keep flowing while a +# large build, copy, or package upgrade floods the disk with writes. The +# kernel's own pick (none or mq-deadline, depending on the device) does not +# regulate latency once the queue fills. Whole disks only: partitions have no +# scheduler of their own, and zram is memory with nothing to schedule. Zoned +# btrfs disks are moved back to mq-deadline by 64-btrfs-zoned.rules. +ACTION=="add|change", SUBSYSTEM=="block", ENV{DEVTYPE}=="disk", KERNEL=="nvme*|sd*|mmcblk*|vd*", ATTR{queue/scheduler}="kyber" From 5db4a40195eee1c8c45ba318d0c5ce307db08bd3 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 13 Sep 2026 12:11:00 +0200 Subject: [PATCH 053/194] Loosen the offline Node pin so mise up tracks new releases Offline installs unpack the bundled tarball and pin Node to its exact version, since latest can't be resolved without network. But nothing ever loosened that pin, so Node stayed frozen at the ISO's version and mup skipped it forever, while online installs tracked latest. Rewrite the pin to latest right after registering the bundled version: mise resolves latest to the installed version while offline (verified with no network and an empty cache), and the first mise up with network picks up new releases just like an online install. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_017LseZ1jcLaFBnndRnW4yb5 --- install/user/mise-work.sh | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/install/user/mise-work.sh b/install/user/mise-work.sh index f77d5561e0e6..7490979ffd7b 100644 --- a/install/user/mise-work.sh +++ b/install/user/mise-work.sh @@ -37,6 +37,11 @@ if [[ -n $NODE_PACKAGE_DIR ]]; then mkdir -p "$NODE_INSTALL_DIR" tar -xzf "$NODE_TARBALL" --strip-components=1 -C "$NODE_INSTALL_DIR" mise use -g node@"$NODE_VERSION" + + # That pinned the exact bundled version, which would exempt Node from + # mise up forever. Loosen it to latest, like an online install gets: + # mise resolves latest to the installed version while offline. + mise config set tools.node latest --file "$HOME/.config/mise/config.toml" fi else mise use -g node@latest From 9246647071329fed57066cfd8acb34438d01df5d Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 13 Sep 2026 12:15:27 +0200 Subject: [PATCH 054/194] Switch TCP congestion control to BBR with fq pacing Cubic keeps pushing until packets drop, which stands queues up in the path on fast links. BBR paces to its estimate of bottleneck bandwidth and minimum RTT instead, cutting queueing latency while keeping throughput. fq is the qdisc BBR is built to pace through. tcp_bbr and sch_fq are modules in every kernel Omarchy ships and autoload when the sysctls are set. The migration re-applies the shipped file so new connections switch without a reboot, no-ops once the live values match, and flags a reboot if applying fails. Co-Authored-By: Claude Fable 5.1 --- etc/sysctl.d/99-omarchy-sysctl.conf | 6 ++++++ migrations/1789294350.sh | 11 +++++++++++ 2 files changed, 17 insertions(+) create mode 100644 migrations/1789294350.sh diff --git a/etc/sysctl.d/99-omarchy-sysctl.conf b/etc/sysctl.d/99-omarchy-sysctl.conf index 1cce6d7fcc08..dac0fb2b215d 100644 --- a/etc/sysctl.d/99-omarchy-sysctl.conf +++ b/etc/sysctl.d/99-omarchy-sysctl.conf @@ -1,6 +1,12 @@ # Solve common flakiness with SSH (MTU discovery on flaky links). net.ipv4.tcp_mtu_probing=1 +# BBR estimates bottleneck bandwidth and minimum RTT and paces to them, where +# cubic keeps pushing until packets drop. That cuts queueing latency +# (bufferbloat) on fast links. fq is the qdisc BBR is built to pace through. +net.core.default_qdisc=fq +net.ipv4.tcp_congestion_control=bbr + # Tune reclaim for swap on zram, which is orders of magnitude faster than the # disk swapfile these defaults assume. diff --git a/migrations/1789294350.sh b/migrations/1789294350.sh new file mode 100644 index 000000000000..9eba04162ca4 --- /dev/null +++ b/migrations/1789294350.sh @@ -0,0 +1,11 @@ +echo "Switch TCP congestion control to BBR with fq pacing" + +# Boot applies the shipped file regardless; this only makes new connections +# use BBR now. Setting the sysctls autoloads tcp_bbr and sch_fq. Qdiscs +# already attached to interfaces stay until they are recreated, normally at +# reboot. +if [[ $(sysctl -n net.ipv4.tcp_congestion_control) == "bbr" && $(sysctl -n net.core.default_qdisc) == "fq" ]]; then + exit 0 +fi + +sudo sysctl -p /etc/sysctl.d/99-omarchy-sysctl.conf >/dev/null || omarchy-state set reboot-required From d377569edb7890270e98b4e83b94189716dc7ab7 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 13 Sep 2026 12:37:08 +0200 Subject: [PATCH 055/194] Count only tiled windows and refit when apps move or float A floating window on the console is not laid out by the gaps, so it no longer stretches the panel to full width. Moving an app onto or off the scratchpad and toggling floating now refit too, via window.move_to_workspace and window.update_rules; both were measured on Hyprland 0.56.2 to carry the settled count. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_012UyVoFTM98Tduoxg7qZax7 --- default/hypr/qconsole.lua | 28 ++++++++++---- test/shell.d/hyprland-qconsole-test.sh | 53 +++++++++++++++++++++++--- 2 files changed, 68 insertions(+), 13 deletions(-) diff --git a/default/hypr/qconsole.lua b/default/hypr/qconsole.lua index cb248f4c6846..a512f8ae5ed6 100644 --- a/default/hypr/qconsole.lua +++ b/default/hypr/qconsole.lua @@ -63,10 +63,17 @@ local function cover(side, bottom) end -- One window reads as a console and gets the panel. A second app has turned the --- scratchpad into a workspace, and a workspace wants the whole width. +-- scratchpad into a workspace, and a workspace wants the whole width. Only tiled +-- windows count: the gaps are what size the panel, and a floating window on top +-- of the console is not laid out by them. local function alone() - local ws = hl.get_workspace(SCRATCHPAD) - return not ws or ws.windows <= 1 + local tiled = 0 + for _, window in ipairs(hl.get_workspace_windows(SCRATCHPAD)) do + if not window.floating then + tiled = tiled + 1 + end + end + return tiled <= 1 end -- Sizing the console with a window rule would freeze it at whatever the screen @@ -158,11 +165,14 @@ hl.on("workspace.move_to_monitor", function(ws, mon) end end) --- The panel is only centered while the console holds one window, so the count --- has to be rechecked as apps come and go. These are the two events that run --- after the workspace's count has already moved: window.close and --- window.move_to_workspace still count the window on its way out, and refitting --- from those would read one too many and leave the console full width. +-- The panel is only centered while the console holds one tiled window, so the +-- count has to be rechecked as apps come and go: opened and closed, moved on or +-- off (Super+Alt+S, Super+Shift+1), and floated or tiled (Super+T, Super+O). +-- window.close is left out, since it still counts the window on its way out and +-- window.destroy follows it anyway. Measured on Hyprland 0.56.2, a move is +-- trailed by several window.update_rules, as is a float toggle, and the last of +-- those always reads the settled count; the earlier ones refit to what the rule +-- already is, which cover() skips. -- -- Only while it is on screen, though. A hidden console is refitted on its way in -- by workspace.special_active, and every window opened anywhere on the desktop @@ -176,6 +186,8 @@ end hl.on("window.open", recount) hl.on("window.destroy", recount) +hl.on("window.move_to_workspace", recount) +hl.on("window.update_rules", recount) -- The direction names the edge the offset is measured from, not where the -- workspace goes: "slide top" drops it down into view, and "slide bottom" diff --git a/test/shell.d/hyprland-qconsole-test.sh b/test/shell.d/hyprland-qconsole-test.sh index c5123d03dfcd..57feb1769e14 100755 --- a/test/shell.d/hyprland-qconsole-test.sh +++ b/test/shell.d/hyprland-qconsole-test.sh @@ -22,6 +22,14 @@ hl = { on = function(event, callback) handlers[event] = callback end, get_active_monitor = function() return monitor end, get_workspace = function() return workspace end, + -- workspace.windows is the tiled count here and workspace.floats the floating + -- one, so the fixtures can say which kind of window is on the console. + get_workspace_windows = function() + local list = {} + for _ = 1, workspace and workspace.windows or 0 do table.insert(list, { floating = false }) end + for _ = 1, workspace and workspace.floats or 0 do table.insert(list, { floating = true }) end + return list + end, exec_scheduled_prop_refresh_immediately = function() end, } @@ -226,11 +234,46 @@ handlers["monitor.layout_changed"]() top, right, bottom, left = gaps() assert(left == 420 and right == 420 and bottom == 540, "a scratchpad that does not exist yet is sized as a console") --- window.close and window.move_to_workspace both run while the workspace still --- counts the window that is leaving, so a refit from either reads one too many --- and strands the console at full width. window.open and window.destroy are the --- two that run after the count has already moved, and are the only ones hooked. +-- Back to a console on screen for the move and float checks. +workspace = { name = "special:scratchpad", visible = true, monitor = acer, windows = 1 } +monitor = acer +handlers["monitor.layout_changed"]() +top, right, bottom, left = gaps() +assert(left == 435 and right == 435, "a single tiled window is a console") + +-- A floating window on top of the console is not laid out by the gaps, so it +-- must not stretch the panel out from under the agent. +workspace.floats = 1 +handlers["window.open"]() +top, right, bottom, left = gaps() +assert(left == 435 and right == 435, "a floating window on the console keeps the panel") + +-- Tiling that float (Super+T) makes it a second app, and floating it again +-- gives the panel back. Both arrive as window.update_rules. +workspace.floats, workspace.windows = 0, 2 +handlers["window.update_rules"]() +top, right, bottom, left = gaps() +assert(left == 0 and right == 0, "tiling a float on the console restores the full width") + +workspace.floats, workspace.windows = 1, 1 +handlers["window.update_rules"]() +top, right, bottom, left = gaps() +assert(left == 435 and right == 435, "floating it again recenters the panel") + +-- Sending an app onto the scratchpad (Super+Alt+S) or off it (Super+Shift+1) +-- does not open or destroy anything, so the move itself has to refit. +workspace.floats, workspace.windows = 0, 2 +handlers["window.move_to_workspace"]() +top, right, bottom, left = gaps() +assert(left == 0 and right == 0, "moving a second app onto the console restores the full width") + +workspace.windows = 1 +handlers["window.move_to_workspace"]() +top, right, bottom, left = gaps() +assert(left == 435 and right == 435, "moving it back off recenters the panel") + +-- window.close still counts the window on its way out, and window.destroy +-- follows it with the settled count, so only destroy is hooked. assert(handlers["window.close"] == nil, "window.close counts the window on its way out") -assert(handlers["window.move_to_workspace"] == nil, "window.move_to_workspace does too") LUA pass "the console is a centered panel until a second app joins it" From 6ecf4bf2008ce79fefa7b80a6ac7871cc7d638e0 Mon Sep 17 00:00:00 2001 From: vatsal nadkarni Date: Sun, 13 Sep 2026 19:34:17 +0530 Subject: [PATCH 056/194] Only force NVIDIA VA-API/GLX env when NVIDIA drives the display --- bin/omarchy-hw-nvidia-display | 45 ++++++++++++++++++++++++++++++++++ default/hypr/nvidia.lua | 15 +++++++++--- test/shell.d/hw-nvidia-test.sh | 38 +++++++++++++++++++++++++--- 3 files changed, 92 insertions(+), 6 deletions(-) create mode 100755 bin/omarchy-hw-nvidia-display diff --git a/bin/omarchy-hw-nvidia-display b/bin/omarchy-hw-nvidia-display new file mode 100755 index 000000000000..1cdf5b70d05b --- /dev/null +++ b/bin/omarchy-hw-nvidia-display @@ -0,0 +1,45 @@ +#!/bin/bash + +# omarchy:summary=Detect whether NVIDIA drives the display (rather than a hybrid iGPU). + +# On hybrid laptops the display is usually wired to the integrated GPU while +# the NVIDIA card only handles offloaded rendering. Forcing NVIDIA's VA-API and +# GLX drivers globally then breaks Chromium-based browsers (black video with +# audio still playing), so the Hyprland NVIDIA env only applies when NVIDIA is +# the display GPU. +# +# sysfs exposes which VGA device drives the display via boot_vga. When no +# device claims it (attribute missing or unreadable), assume NVIDIA is the +# display GPU to preserve the current behavior on machines we cannot tell. +# +# Read the cached sysfs IDs rather than lspci, which reads PCI config space and +# resumes runtime-suspended GPUs. +pci_devices_path="${OMARCHY_PCI_DEVICES_PATH:-/sys/bus/pci/devices}" + +shopt -s nullglob + +nvidia_boot=0 +other_boot=0 + +for device in "$pci_devices_path"/*; do + [[ $(< "$device/class") == 0x03* ]] || continue + boot_vga=0 + if [[ -f $device/boot_vga ]]; then + boot_vga=$(< "$device/boot_vga") + fi + if [[ $(< "$device/vendor") == "0x10de" ]]; then + if (( boot_vga == 1 )); then + nvidia_boot=1 + fi + else + if (( boot_vga == 1 )); then + other_boot=1 + fi + fi +done + +if (( other_boot == 1 && nvidia_boot == 0 )); then + exit 1 +else + exit 0 +fi diff --git a/default/hypr/nvidia.lua b/default/hypr/nvidia.lua index 663fe79e1bb8..a3a155465503 100644 --- a/default/hypr/nvidia.lua +++ b/default/hypr/nvidia.lua @@ -1,6 +1,7 @@ local paths = require("default.hypr.paths") local nvidia = paths.omarchy_path .. "/bin/omarchy-hw-nvidia" +local nvidia_display = paths.omarchy_path .. "/bin/omarchy-hw-nvidia-display" local nvidia_gsp = paths.omarchy_path .. "/bin/omarchy-hw-nvidia-gsp" local nvidia_without_gsp = paths.omarchy_path .. "/bin/omarchy-hw-nvidia-without-gsp" @@ -8,12 +9,20 @@ local nvidia_without_gsp = paths.omarchy_path .. "/bin/omarchy-hw-nvidia-without -- lspci reads PCI config space, which resumes a runtime-suspended GPU, and on a -- hybrid laptop that wake alone outlasts Hyprland's 1.5s config reload budget. if o.shell_succeeds(o.shell_quote(nvidia)) then + -- On hybrid laptops the display is wired to the iGPU, so forcing NVIDIA's + -- VA-API/GLX drivers globally breaks Chromium-based browsers (black video). + -- Only apply those when NVIDIA actually drives the display. + local nvidia_is_display = o.shell_succeeds(o.shell_quote(nvidia_display)) if o.shell_succeeds(o.shell_quote(nvidia_gsp)) then hl.env("NVD_BACKEND", "direct") - hl.env("LIBVA_DRIVER_NAME", "nvidia") - hl.env("__GLX_VENDOR_LIBRARY_NAME", "nvidia") + if nvidia_is_display then + hl.env("LIBVA_DRIVER_NAME", "nvidia") + hl.env("__GLX_VENDOR_LIBRARY_NAME", "nvidia") + end elseif o.shell_succeeds(o.shell_quote(nvidia_without_gsp)) then hl.env("NVD_BACKEND", "egl") - hl.env("__GLX_VENDOR_LIBRARY_NAME", "nvidia") + if nvidia_is_display then + hl.env("__GLX_VENDOR_LIBRARY_NAME", "nvidia") + end end end diff --git a/test/shell.d/hw-nvidia-test.sh b/test/shell.d/hw-nvidia-test.sh index da461ce44cec..72dc5a7b7719 100755 --- a/test/shell.d/hw-nvidia-test.sh +++ b/test/shell.d/hw-nvidia-test.sh @@ -7,7 +7,8 @@ source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" tmp_dir=$(mktemp -d) trap 'rm -rf "$tmp_dir"' EXIT -# Each argument is a PCI device as "vendor:device:class", in sysfs's own format. +# Each argument is a PCI device as "vendor:device:class[:boot_vga]", in sysfs's +# own format. boot_vga is omitted to simulate firmware that lacks the flag. write_pci_devices() { rm -rf "$tmp_dir/devices" mkdir -p "$tmp_dir/devices" @@ -18,9 +19,12 @@ write_pci_devices() { local slot slot=$(printf '0000:%02x:00.0' "$index") mkdir -p "$tmp_dir/devices/$slot" - printf '%s\n' "${spec%%:*}" >"$tmp_dir/devices/$slot/vendor" + printf '%s\n' "$(cut -d: -f1 <<<"$spec")" >"$tmp_dir/devices/$slot/vendor" printf '%s\n' "$(cut -d: -f2 <<<"$spec")" >"$tmp_dir/devices/$slot/device" - printf '%s\n' "${spec##*:}" >"$tmp_dir/devices/$slot/class" + printf '%s\n' "$(cut -d: -f3 <<<"$spec")" >"$tmp_dir/devices/$slot/class" + if [[ $spec == *:*:*:* ]]; then + printf '%s\n' "$(cut -d: -f4 <<<"$spec")" >"$tmp_dir/devices/$slot/boot_vga" + fi index=$((index + 1)) done } @@ -54,6 +58,18 @@ assert_detects() { pass "$description" } +assert_display() { + local description="$1" expected="$2" + + local actual=no + OMARCHY_PCI_DEVICES_PATH="$tmp_dir/devices" "$ROOT/bin/omarchy-hw-nvidia-display" && actual=yes + + [[ $actual == "$expected" ]] || + fail "$description" "omarchy-hw-nvidia-display: expected $expected, got $actual" + + pass "$description" +} + # AMD Cezanne integrated graphics. write_pci_devices 0x1002:0x15e7:0x030000 assert_detects "a machine without an NVIDIA GPU detects nothing" no no no @@ -97,3 +113,19 @@ assert_detects "a non-display NVIDIA function is not a GPU" no no no write_pci_devices assert_detects "a machine with no PCI devices detects nothing" no no no + +# AMD Phoenix iGPU drives the display, NVIDIA RTX 3050 is discrete. +write_pci_devices 0x1002:0x15bf:0x030000:1 0x10de:0x25ac:0x030000:0 +assert_display "a hybrid laptop with an AMD display GPU is not NVIDIA-driven" no + +# Intel Alder Lake iGPU drives the display, NVIDIA Turing is discrete. +write_pci_devices 0x8086:0x46a6:0x030000:1 0x10de:0x1f91:0x030000:0 +assert_display "a hybrid Intel+NVIDIA laptop is not NVIDIA-driven" no + +# NVIDIA-only desktop keeps the current behavior. +write_pci_devices 0x10de:0x2c02:0x030000:1 +assert_display "an NVIDIA-only machine is NVIDIA-driven" yes + +# Fixtures without boot_vga preserve the current behavior. +write_pci_devices 0x10de:0x25ac:0x030000 +assert_display "missing boot_vga info assumes NVIDIA drives the display" yes From 69c67c63d69db8e39ce3b32ac879b757925ea9c5 Mon Sep 17 00:00:00 2001 From: Anton Kesy Date: Sun, 13 Sep 2026 16:28:44 +0200 Subject: [PATCH 057/194] Fix typo in manual --- manual/46-faq.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/manual/46-faq.md b/manual/46-faq.md index 6c6254072123..21b11db94136 100644 --- a/manual/46-faq.md +++ b/manual/46-faq.md @@ -62,7 +62,7 @@ export OMARCHY_SCREENSHOT_DIR="$HOME/Pictures/Screenshots" You can do the same for screenrecordings using `OMARCHY_SCREENRECORD_DIR`. -Just remember to create the directoy you want to save to and restart Omarchy for this to take effect. +Just remember to create the directory you want to save to and restart Omarchy for this to take effect. ### How do I get the speakers + webcam working on my Apple Studio Display? From a389bd1852c96a6f0f8a5572b3435efe042ba28e Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 13 Sep 2026 16:59:33 +0200 Subject: [PATCH 058/194] Add Cloudflare CLI lazy wrapper --- install/user/mise.sh | 1 + migrations/1789310715.sh | 5 +++++ 2 files changed, 6 insertions(+) create mode 100644 migrations/1789310715.sh diff --git a/install/user/mise.sh b/install/user/mise.sh index 81e0364c69a6..dfc56aa2a86e 100644 --- a/install/user/mise.sh +++ b/install/user/mise.sh @@ -19,6 +19,7 @@ omarchy-mise-install npm:@kitlangton/ghui ghui omarchy-mise-install aqua:modem-dev/hunk hunk omarchy-mise-install github:basecamp/hey-cli hey omarchy-mise-install github:basecamp/basecamp-cli basecamp +omarchy-mise-install npm:cf cf omarchy-mise-install github:OpenRouterLabs/ori-releases ori # Every line above writes a stub and cannot fail. This one can: it exits # non-zero when Hermes Desktop owns Hermes but has not finished setting it up, diff --git a/migrations/1789310715.sh b/migrations/1789310715.sh new file mode 100644 index 000000000000..a182dc8b5482 --- /dev/null +++ b/migrations/1789310715.sh @@ -0,0 +1,5 @@ +echo "Install cf (Cloudflare CLI) via mise wrapper" + +if [[ ! -f $HOME/.local/state/omarchy/preinstalls-removed ]]; then + omarchy-mise-install npm:cf cf +fi From 9ca462b153637bd28d749bc491a2e72e139e2993 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 13 Sep 2026 17:05:40 +0200 Subject: [PATCH 059/194] Match 1Password's new window class so it floats again 1Password 8.12 changed its app id from "1Password" to "com.onepassword.OnePassword" (its .desktop file now declares that as StartupWMClass). Our window rule only matched the old name, so the main window came up tiled and lost the no_screen_share protection. Match both forms so older installs keep working. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01LSFKDatumRZHB8zqk5CP5C --- default/hypr/apps/1password.lua | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/default/hypr/apps/1password.lua b/default/hypr/apps/1password.lua index d57bf651dfb3..156835999195 100644 --- a/default/hypr/apps/1password.lua +++ b/default/hypr/apps/1password.lua @@ -1 +1,3 @@ -o.window("^(1[p|P]assword)$", { no_screen_share = true, tag = "+floating-window" }) +-- 1Password 8.12 renamed its app id from "1Password" to the reverse-DNS form, +-- so match both to keep older installs floating too. +o.window("^(1[pP]assword|com\\.onepassword\\.OnePassword)$", { no_screen_share = true, tag = "+floating-window" }) From d78ea9e158727a9e384858059080c61a7264f842 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 13 Sep 2026 17:20:29 +0200 Subject: [PATCH 060/194] Point GitHub URLs at omacom/omarchy instead of basecamp/omarchy The repo moved to the omacom org. GitHub redirects the old URLs, but `omarchy channel set dev` was still cloning from basecamp/omarchy, which left every dev checkout with a stale origin remote that confuses gh (pr create fails with "No commits between omacom:quattro and basecamp:"). Update the clone URL, the quattro upgrade tarball, the update-confirm release link, the systemd Documentation link, and the manual. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01LSFKDatumRZHB8zqk5CP5C --- bin/omarchy-channel-set | 2 +- bin/omarchy-update-confirm | 2 +- bin/omarchy-upgrade-to-quattro | 2 +- default/hypr/apps/jetbrains.lua | 2 +- default/systemd/user/omarchy-speaker-tuning.service | 2 +- manual/30-updates.md | 4 ++-- manual/49-omarchy-on.md | 6 +++--- test/shell.d/channel-test.sh | 4 ++-- 8 files changed, 12 insertions(+), 12 deletions(-) diff --git a/bin/omarchy-channel-set b/bin/omarchy-channel-set index d4c482f2d80c..baceaa926079 100755 --- a/bin/omarchy-channel-set +++ b/bin/omarchy-channel-set @@ -34,7 +34,7 @@ validate_dev_checkout() { link_dev_checkout() { local checkout="$1" - [[ -d $checkout/.git ]] || git clone https://github.com/basecamp/omarchy.git "$checkout" + [[ -d $checkout/.git ]] || git clone https://github.com/omacom/omarchy.git "$checkout" omarchy-dev-link "$checkout" --no-reboot } diff --git a/bin/omarchy-update-confirm b/bin/omarchy-update-confirm index 472927f1e95b..c3ca37e669ca 100755 --- a/bin/omarchy-update-confirm +++ b/bin/omarchy-update-confirm @@ -8,7 +8,7 @@ gum style --border normal --padding "1 2" \ "• You cannot stop the update once you start!" \ "• Make sure you're connected to power or have a full battery" \ "" \ - "What's new: https://github.com/basecamp/omarchy/releases/latest" + "What's new: https://github.com/omacom/omarchy/releases/latest" echo diff --git a/bin/omarchy-upgrade-to-quattro b/bin/omarchy-upgrade-to-quattro index e6a27ee610b6..86f1efcef79d 100755 --- a/bin/omarchy-upgrade-to-quattro +++ b/bin/omarchy-upgrade-to-quattro @@ -965,7 +965,7 @@ populate_legacy_hypr_defaults() { tmp_dir=$(mktemp -d) archive_dir="$tmp_dir/archive" mkdir -p "$archive_dir" - if curl -fsSL https://github.com/basecamp/omarchy/archive/refs/heads/master.tar.gz | tar -xz -C "$archive_dir" && + if curl -fsSL https://github.com/omacom/omarchy/archive/refs/heads/master.tar.gz | tar -xz -C "$archive_dir" && [[ -d $archive_dir/omarchy-master/default/hypr ]]; then cp -a "$archive_dir/omarchy-master/default/hypr/." "$shim_hypr_dir/" fi diff --git a/default/hypr/apps/jetbrains.lua b/default/hypr/apps/jetbrains.lua index 678e823e29f6..1b9658e385d8 100644 --- a/default/hypr/apps/jetbrains.lua +++ b/default/hypr/apps/jetbrains.lua @@ -1,2 +1,2 @@ --- Disable mouse focus (see https://github.com/basecamp/omarchy/pull/5183#issuecomment-4189299971). +-- Disable mouse focus (see https://github.com/omacom/omarchy/pull/5183#issuecomment-4189299971). o.window("^(jetbrains-.*)$", { no_follow_mouse = true }) diff --git a/default/systemd/user/omarchy-speaker-tuning.service b/default/systemd/user/omarchy-speaker-tuning.service index 53b374478728..ed6145a95844 100644 --- a/default/systemd/user/omarchy-speaker-tuning.service +++ b/default/systemd/user/omarchy-speaker-tuning.service @@ -1,6 +1,6 @@ [Unit] Description=Omarchy speaker tuning filter-chain -Documentation=https://github.com/basecamp/omarchy/blob/master/docs/audio-tuning.md +Documentation=https://github.com/omacom/omarchy/blob/master/docs/audio-tuning.md # WirePlumber does the linking, so starting before it is up risks the output being # linked before the speaker device has been discovered. After=pipewire.service wireplumber.service diff --git a/manual/30-updates.md b/manual/30-updates.md index 246138c386a6..f0e82cede850 100644 --- a/manual/30-updates.md +++ b/manual/30-updates.md @@ -2,7 +2,7 @@ Omarchy and your packages are kept up to date via _Update > Omarchy_ in the Omarchy menu (`Super + Space`). -Omarchy itself is installed as regular pacman packages from the [Omarchy Package Repository](https://github.com/omacom-io/omarchy-pkgs), so an update installs [the latest Omarchy release](https://github.com/basecamp/omarchy/releases), runs any pending migrations to get your system in sync with the latest, and updates all system packages from the [Omarchy Arch Mirror](https://github.com/omacom-io/omarchy-mirror) and [AUR](https://aur.archlinux.org/) (if you have installed any AUR packages). +Omarchy itself is installed as regular pacman packages from the [Omarchy Package Repository](https://github.com/omacom-io/omarchy-pkgs), so an update installs [the latest Omarchy release](https://github.com/omacom/omarchy/releases), runs any pending migrations to get your system in sync with the latest, and updates all system packages from the [Omarchy Arch Mirror](https://github.com/omacom-io/omarchy-mirror) and [AUR](https://aur.archlinux.org/) (if you have installed any AUR packages). When new releases are made, a circle arrow icon will appear to the right of your clock. Click it and the update process will start. @@ -10,7 +10,7 @@ When new releases are made, a circle arrow icon will appear to the right of your ### Four channels -Omarchy is updated along four channels: stable, RC, edge, and dev. New installations start on the stable channel, which tracks the [official releases](https://github.com/basecamp/omarchy/releases/), as well as the [stable Omarchy Arch mirror](https://github.com/omacom-io/omarchy-mirror) that's running one month behind the latest, so we can catch any new incompatibilities that require config changes before they cause problems for people. +Omarchy is updated along four channels: stable, RC, edge, and dev. New installations start on the stable channel, which tracks the [official releases](https://github.com/omacom/omarchy/releases/), as well as the [stable Omarchy Arch mirror](https://github.com/omacom-io/omarchy-mirror) that's running one month behind the latest, so we can catch any new incompatibilities that require config changes before they cause problems for people. But if you'd like to help spot those potential issues, you can run on the edge channel. That'll keep your Omarchy packages tracking the latest development builds, and lets you update to the latest Arch packages as soon as they're available. You should only do this if you're experienced with Linux, and know how to recover a system that has problems. diff --git a/manual/49-omarchy-on.md b/manual/49-omarchy-on.md index c33642fd7a7a..af066999d07e 100644 --- a/manual/49-omarchy-on.md +++ b/manual/49-omarchy-on.md @@ -6,15 +6,15 @@ ### Apple Virtual Machine -You can also install Omarchy inside a Parallels VM. Quite the cumbersome process, but there's [a user-driven guide](https://github.com/basecamp/omarchy/discussions/452) for that too. +You can also install Omarchy inside a Parallels VM. Quite the cumbersome process, but there's [a user-driven guide](https://github.com/omacom/omarchy/discussions/452) for that too. ### VirtualBox -VirtualBox is a popular VM runner. [You can run Omarchy inside that too](https://github.com/basecamp/omarchy/discussions/176). But performance probably won't be great. +VirtualBox is a popular VM runner. [You can run Omarchy inside that too](https://github.com/omacom/omarchy/discussions/176). But performance probably won't be great. ### VMware Workstation on Windows 11 -Another popular VM runner for Windows. [Omarchy has been setup inside of that as well](https://github.com/basecamp/omarchy/discussions/572). +Another popular VM runner for Windows. [Omarchy has been setup inside of that as well](https://github.com/omacom/omarchy/discussions/572). ### Steam Deck diff --git a/test/shell.d/channel-test.sh b/test/shell.d/channel-test.sh index 122a15aadb7b..7e7d417061ed 100644 --- a/test/shell.d/channel-test.sh +++ b/test/shell.d/channel-test.sh @@ -153,11 +153,11 @@ run_channel dev assert_log_line $'gum\tconfirm\t--default=false\tSwitch to dev channel?' "dev asks for confirmation" assert_log_line $'refresh\tedge' "dev refreshes the edge pacman channel" assert_log_line $'update-pacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev' "dev installs development Omarchy packages" -assert_log_line $'git\tclone\thttps://github.com/basecamp/omarchy.git\t'"$checkout" "dev clones the source checkout to ~/omarchy" +assert_log_line $'git\tclone\thttps://github.com/omacom/omarchy.git\t'"$checkout" "dev clones the source checkout to ~/omarchy" assert_log_line $'link\t'"$checkout"$'\t--no-reboot' "dev links ~/omarchy without an early reboot prompt" assert_log_line $'state\tset\treboot-required' "dev defers the reboot prompt to the update pipeline" assert_log_line $'update\t-y\tOMARCHY_PATH='"$checkout" "dev runs the normal update pipeline from the source checkout" -[[ $(grep -E '^(git|link|state|refresh|sudo|update)' "$log_file") == $'git\tclone\thttps://github.com/basecamp/omarchy.git\t'"$checkout"$'\nlink\t'"$checkout"$'\t--no-reboot\nstate\tset\treboot-required\nrefresh\tedge\nupdate-pacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev\nupdate\t-y\tOMARCHY_PATH='"$checkout" ]] || +[[ $(grep -E '^(git|link|state|refresh|sudo|update)' "$log_file") == $'git\tclone\thttps://github.com/omacom/omarchy.git\t'"$checkout"$'\nlink\t'"$checkout"$'\t--no-reboot\nstate\tset\treboot-required\nrefresh\tedge\nupdate-pacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev\nupdate\t-y\tOMARCHY_PATH='"$checkout" ]] || fail "dev activates the checkout before changing or updating packages" "$(cat "$log_file")" pass "dev activates the checkout before changing or updating packages" From 90f00546582969a8d9359baf7271916e6aa374e1 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 13 Sep 2026 17:46:13 +0200 Subject: [PATCH 061/194] Upgrade known clipboard providers with backups and package version guard --- migrations/1788996284.sh | 35 ++- .../fixtures/neovim-clipboard/initial-fix.lua | 102 +++++++ .../fixtures/neovim-clipboard/july.lua | 99 +++++++ .../fixtures/neovim-clipboard/june.lua | 275 ++++++++++++++++++ .../fixtures/neovim-clipboard/parity-pr.lua | 179 ++++++++++++ test/shell.d/neovim-remote-yanks-test.sh | 90 +++--- 6 files changed, 734 insertions(+), 46 deletions(-) create mode 100644 test/shell.d/fixtures/neovim-clipboard/initial-fix.lua create mode 100644 test/shell.d/fixtures/neovim-clipboard/july.lua create mode 100644 test/shell.d/fixtures/neovim-clipboard/june.lua create mode 100644 test/shell.d/fixtures/neovim-clipboard/parity-pr.lua diff --git a/migrations/1788996284.sh b/migrations/1788996284.sh index e47894f8c207..5a9437288204 100644 --- a/migrations/1788996284.sh +++ b/migrations/1788996284.sh @@ -1,9 +1,34 @@ -echo "Enable automatic Neovim clipboard yanks in remote sessions" +echo "Repair remote Neovim clipboard yanks and paste" nvim_provider="$HOME/.config/nvim/lua/config/remote_clipboard.lua" +provider_source="/usr/share/omarchy-nvim/config/lua/config/remote_clipboard.lua" -if [[ -f $nvim_provider ]] && - grep -qF 'name = "OmarchyRemoteClipboard"' "$nvim_provider" && - ! grep -qF 'vim.opt.clipboard = "unnamedplus"' "$nvim_provider"; then - sed -i '/^ vim.g.clipboard = {/i\ -- LazyVim disables clipboard syncing over SSH; our provider supports it.\n vim.opt.clipboard = "unnamedplus"\n' "$nvim_provider" +[[ -f $nvim_provider ]] || exit 0 + +# Replace only known Omarchy versions, including the June file-backed provider +# and the two earlier proposed fixes. Preserve all user-authored changes. +provider_hash=$(sha256sum "$nvim_provider") +case ${provider_hash%% *} in + c0c15941ed7cf97a1a3d3c60f0b13875e85f641bdb7431c3283e6f86fbc95f4e|bac8268c3dde4e747772467d6671e626aa4982478551d8fc8ebe1259a4854f2c|7f012a235c05e3c559b48211c1534af2f4c919750b76db88ec3d5b7814259d30|8b371d0f271e522b27696f1b71083d0a6ba7896cd3ff7b0a938b7327fcb06a46) ;; + *) + if [[ -f $provider_source ]] && cmp -s "$nvim_provider" "$provider_source"; then + exit 0 + fi + echo "Preserving customized Neovim provider: $nvim_provider" + echo "Review remote clipboard settings manually, or use omarchy-nvim-refresh to reset them." + exit 0 + ;; +esac + +# Updates install packages before migrations. Refuse an older package so this +# migration remains pending instead of installing the provider it must repair. +nvim_package=$(pacman -Q omarchy-nvim) +if [[ $(vercmp "${nvim_package#* }" "2026.8.13-2") == -* ]] || [[ ! -f $provider_source ]]; then + echo "Update omarchy-nvim to 2026.8.13-2 or newer before rerunning this migration." >&2 + exit 1 fi + +provider_backup=$(mktemp "$nvim_provider.bak.XXXXXX") +cp -p "$nvim_provider" "$provider_backup" +install -m 0644 "$provider_source" "$nvim_provider" +echo "Previous Neovim provider saved to $provider_backup" diff --git a/test/shell.d/fixtures/neovim-clipboard/initial-fix.lua b/test/shell.d/fixtures/neovim-clipboard/initial-fix.lua new file mode 100644 index 000000000000..5f3248a6dce7 --- /dev/null +++ b/test/shell.d/fixtures/neovim-clipboard/initial-fix.lua @@ -0,0 +1,102 @@ +-- Clipboard for sessions whose yanks may need to reach another machine: +-- every copy is emitted as OSC 52 (inside tmux this becomes a tmux buffer, +-- rebroadcast to every attached client, local or SSH). Paste prefers the +-- local Wayland clipboard when one is available, so content copied in other +-- apps remains pasteable; without a display, paste is an OSC 52 query that +-- tmux (or the terminal) answers. +local M = {} + +local function proc_lines(pid, file) + local ok, lines = pcall(vim.fn.readfile, "/proc/" .. pid .. "/" .. file) + return ok and lines or {} +end + +local function proc_ppid(pid) + for _, line in ipairs(proc_lines(pid, "status")) do + local ppid = line:match("^PPid:%s+(%d+)") + if ppid then + return tonumber(ppid) + end + end +end + +local function ancestor_process_named(name) + local pid = vim.fn.getpid() + + for _ = 1, 16 do + local ppid = proc_ppid(pid) + if not ppid or ppid <= 1 then + return false + end + + local comm = proc_lines(ppid, "comm")[1] or "" + if comm:find(name, 1, true) then + return true + end + + pid = ppid + end + + return false +end + +function M.setup() + local in_tmux = vim.env.TMUX ~= nil + local in_ssh = vim.env.SSH_TTY ~= nil or vim.env.SSH_CONNECTION ~= nil + local in_herdr = vim.env.HERDR_PANE_ID ~= nil or ancestor_process_named("herdr") + + if not (in_tmux or in_ssh or in_herdr) then + return + end + + local osc52 = require("vim.ui.clipboard.osc52") + local has_wayland = vim.env.WAYLAND_DISPLAY ~= nil + and vim.fn.executable("wl-copy") == 1 + and vim.fn.executable("wl-paste") == 1 + + local function copy(register) + local emit = osc52.copy(register) + + return function(lines) + if has_wayland then + local cmd = { "wl-copy", "--sensitive", "--type", "text/plain" } + if register == "*" then + cmd[#cmd + 1] = "--primary" + end + vim.fn.system(cmd, lines) + end + + if vim.g.omarchy_remote_clipboard_osc52 ~= false then + emit(lines) + end + end + end + + local function paste(register) + if not has_wayland then + return osc52.paste(register) + end + + return function() + local cmd = { "wl-paste", "--no-newline" } + if register == "*" then + cmd[#cmd + 1] = "--primary" + end + + local lines = vim.fn.systemlist(cmd, "", 1) + return vim.v.shell_error == 0 and lines or {} + end + end + + -- LazyVim disables clipboard syncing over SSH; our provider supports it. + vim.opt.clipboard = "unnamedplus" + + vim.g.clipboard = { + name = "OmarchyRemoteClipboard", + copy = { ["+"] = copy("+"), ["*"] = copy("*") }, + paste = { ["+"] = paste("+"), ["*"] = paste("*") }, + cache_enabled = 0, + } +end + +return M diff --git a/test/shell.d/fixtures/neovim-clipboard/july.lua b/test/shell.d/fixtures/neovim-clipboard/july.lua new file mode 100644 index 000000000000..b54c54e670de --- /dev/null +++ b/test/shell.d/fixtures/neovim-clipboard/july.lua @@ -0,0 +1,99 @@ +-- Clipboard for sessions whose yanks may need to reach another machine: +-- every copy is emitted as OSC 52 (inside tmux this becomes a tmux buffer, +-- rebroadcast to every attached client, local or SSH). Paste prefers the +-- local Wayland clipboard when one is available, so content copied in other +-- apps remains pasteable; without a display, paste is an OSC 52 query that +-- tmux (or the terminal) answers. +local M = {} + +local function proc_lines(pid, file) + local ok, lines = pcall(vim.fn.readfile, "/proc/" .. pid .. "/" .. file) + return ok and lines or {} +end + +local function proc_ppid(pid) + for _, line in ipairs(proc_lines(pid, "status")) do + local ppid = line:match("^PPid:%s+(%d+)") + if ppid then + return tonumber(ppid) + end + end +end + +local function ancestor_process_named(name) + local pid = vim.fn.getpid() + + for _ = 1, 16 do + local ppid = proc_ppid(pid) + if not ppid or ppid <= 1 then + return false + end + + local comm = proc_lines(ppid, "comm")[1] or "" + if comm:find(name, 1, true) then + return true + end + + pid = ppid + end + + return false +end + +function M.setup() + local in_tmux = vim.env.TMUX ~= nil + local in_ssh = vim.env.SSH_TTY ~= nil or vim.env.SSH_CONNECTION ~= nil + local in_herdr = vim.env.HERDR_PANE_ID ~= nil or ancestor_process_named("herdr") + + if not (in_tmux or in_ssh or in_herdr) then + return + end + + local osc52 = require("vim.ui.clipboard.osc52") + local has_wayland = vim.env.WAYLAND_DISPLAY ~= nil + and vim.fn.executable("wl-copy") == 1 + and vim.fn.executable("wl-paste") == 1 + + local function copy(register) + local emit = osc52.copy(register) + + return function(lines) + if has_wayland then + local cmd = { "wl-copy", "--sensitive", "--type", "text/plain" } + if register == "*" then + cmd[#cmd + 1] = "--primary" + end + vim.fn.system(cmd, lines) + end + + if vim.g.omarchy_remote_clipboard_osc52 ~= false then + emit(lines) + end + end + end + + local function paste(register) + if not has_wayland then + return osc52.paste(register) + end + + return function() + local cmd = { "wl-paste", "--no-newline" } + if register == "*" then + cmd[#cmd + 1] = "--primary" + end + + local lines = vim.fn.systemlist(cmd, "", 1) + return vim.v.shell_error == 0 and lines or {} + end + end + + vim.g.clipboard = { + name = "OmarchyRemoteClipboard", + copy = { ["+"] = copy("+"), ["*"] = copy("*") }, + paste = { ["+"] = paste("+"), ["*"] = paste("*") }, + cache_enabled = 0, + } +end + +return M diff --git a/test/shell.d/fixtures/neovim-clipboard/june.lua b/test/shell.d/fixtures/neovim-clipboard/june.lua new file mode 100644 index 000000000000..c43aa23424c7 --- /dev/null +++ b/test/shell.d/fixtures/neovim-clipboard/june.lua @@ -0,0 +1,275 @@ +local M = {} +local uv = vim.uv or vim.loop + +local function secure_runtime_dir() + local uid = uv.getuid() + local candidates = {} + + local function add(path) + if path and path ~= "" then + candidates[#candidates + 1] = path + end + end + + add(vim.env.XDG_RUNTIME_DIR) + if uid then + add("/run/user/" .. uid) + add("/dev/shm/nvim-remote-clipboard-" .. uid) + end + + for _, dir in ipairs(candidates) do + if dir:sub(1, 9) == "/dev/shm/" then + pcall(vim.fn.mkdir, dir, "p", 448) + pcall(vim.fn.setfperm, dir, "rwx------") + end + + local stat = uv.fs_stat(dir) + if stat and stat.type == "directory" and stat.uid == uid and stat.mode % 512 == 448 then + return dir + end + end +end + +local function wayland_connection(runtime_dir) + if vim.fn.executable("wl-copy") ~= 1 or vim.fn.executable("wl-paste") ~= 1 then + return nil + end + + local function valid_socket(path) + local stat = uv.fs_stat(path) + return stat and stat.type == "socket" + end + + if vim.env.WAYLAND_DISPLAY and vim.env.WAYLAND_DISPLAY ~= "" then + local display = vim.env.WAYLAND_DISPLAY + local socket_path = display:sub(1, 1) == "/" and display or (runtime_dir .. "/" .. display) + if valid_socket(socket_path) then + return display + end + end + + for _, path in ipairs(vim.fn.glob(runtime_dir .. "/wayland-*", false, true)) do + local display = vim.fn.fnamemodify(path, ":t") + if not display:match("%.lock$") and valid_socket(path) then + return display + end + end +end + +local function write_private_file(path, payload) + local tmp_path = path .. "." .. vim.fn.getpid() .. ".tmp" + + vim.fn.writefile({ payload }, tmp_path, "b") + vim.fn.setfperm(tmp_path, "rw-------") + vim.fn.rename(tmp_path, path) + vim.fn.setfperm(path, "rw-------") +end + +local function proc_lines(pid, file) + local ok, lines = pcall(vim.fn.readfile, "/proc/" .. pid .. "/" .. file) + return ok and lines or {} +end + +local function proc_ppid(pid) + for _, line in ipairs(proc_lines(pid, "status")) do + local ppid = line:match("^PPid:%s+(%d+)") + if ppid then + return tonumber(ppid) + end + end +end + +local function ancestor_process_named(name) + local pid = vim.fn.getpid() + + for _ = 1, 16 do + local ppid = proc_ppid(pid) + if not ppid or ppid <= 1 then + return false + end + + local comm = proc_lines(ppid, "comm")[1] or "" + if comm:find(name, 1, true) then + return true + end + + pid = ppid + end + + return false +end + +local function copy_to_client_clipboard(register, lines) + if vim.g.omarchy_remote_clipboard_osc52 == false then + return + end + + local ok, osc52 = pcall(require, "vim.ui.clipboard.osc52") + if ok then + pcall(osc52.copy(register), lines) + end +end + +function M.setup() + local in_tmux = vim.env.TMUX ~= nil + local has_display = vim.env.WAYLAND_DISPLAY or vim.env.DISPLAY + local in_remote_session = vim.env.SSH_TTY or vim.env.SSH_CONNECTION + local in_herdr = vim.env.HERDR_PANE_ID ~= nil or ancestor_process_named("herdr") + local needs_remote_clipboard = not in_tmux and (in_herdr or (in_remote_session and not has_display)) + + if not needs_remote_clipboard then + return + end + + local runtime_dir = secure_runtime_dir() + if not runtime_dir then + return + end + + local wayland_display = wayland_connection(runtime_dir) + local ttl_seconds = 10 * 60 + + local function empty_clipboard() + return { {}, "v" } + end + + local function read_regtype(path) + local stat = uv.fs_stat(path) + if not stat or stat.uid ~= uv.getuid() or stat.mode % 512 ~= 384 then + return "v" + end + + local ok, file_lines = pcall(vim.fn.readfile, path) + if not ok or #file_lines == 0 then + return "v" + end + + local ok_decode, data = pcall(vim.fn.json_decode, table.concat(file_lines, "\n")) + if not ok_decode or type(data) ~= "table" then + return "v" + end + + if type(data.created_at) == "number" and os.time() - data.created_at > ttl_seconds then + vim.fn.delete(path) + return "v" + end + + return type(data.regtype) == "string" and data.regtype or "v" + end + + if wayland_display then + local regtype_path = runtime_dir .. "/nvim-remote-clipboard-regtype.json" + local env = { + "env", + "XDG_RUNTIME_DIR=" .. runtime_dir, + "WAYLAND_DISPLAY=" .. wayland_display, + } + + local function write_regtype(regtype) + write_private_file(regtype_path, vim.fn.json_encode({ + regtype = regtype, + created_at = os.time(), + })) + end + + local function copy(register) + return function(lines, regtype) + write_regtype(regtype) + + local cmd = vim.list_extend(vim.deepcopy(env), { + "wl-copy", + "--sensitive", + "--type", + "text/plain", + }) + if register == "*" then + cmd[#cmd + 1] = "--primary" + end + + vim.fn.system(cmd, lines) + copy_to_client_clipboard(register, lines) + end + end + + local function paste(register) + return function() + local cmd = vim.list_extend(vim.deepcopy(env), { "wl-paste", "--no-newline" }) + if register == "*" then + cmd[#cmd + 1] = "--primary" + end + + local lines = vim.fn.systemlist(cmd, "", 1) + if vim.v.shell_error ~= 0 then + return empty_clipboard() + end + + return { lines, read_regtype(regtype_path) } + end + end + + vim.g.clipboard = { + name = "OmarchyWaylandClipboard", + copy = { + ["+"] = copy("+"), + ["*"] = copy("*"), + }, + paste = { + ["+"] = paste("+"), + ["*"] = paste("*"), + }, + cache_enabled = 0, + } + else + local clipboard_path = runtime_dir .. "/nvim-remote-clipboard.json" + + local function copy(register) + return function(lines, regtype) + write_private_file(clipboard_path, vim.fn.json_encode({ + lines = lines, + regtype = regtype, + created_at = os.time(), + })) + copy_to_client_clipboard(register, lines) + end + end + + local function read_clipboard() + local stat = uv.fs_stat(clipboard_path) + if not stat or stat.uid ~= uv.getuid() or stat.mode % 512 ~= 384 then + return empty_clipboard() + end + + local ok, file_lines = pcall(vim.fn.readfile, clipboard_path) + if not ok or #file_lines == 0 then + return empty_clipboard() + end + + local ok_decode, data = pcall(vim.fn.json_decode, table.concat(file_lines, "\n")) + if not ok_decode or type(data) ~= "table" or type(data.lines) ~= "table" then + return empty_clipboard() + end + + if type(data.created_at) == "number" and os.time() - data.created_at > ttl_seconds then + vim.fn.delete(clipboard_path) + return empty_clipboard() + end + + return { data.lines, data.regtype or "v" } + end + + vim.g.clipboard = { + name = "RemoteRuntimeClipboard", + copy = { + ["+"] = copy("+"), + ["*"] = copy("*"), + }, + paste = { + ["+"] = read_clipboard, + ["*"] = read_clipboard, + }, + cache_enabled = 0, + } + end +end + +return M diff --git a/test/shell.d/fixtures/neovim-clipboard/parity-pr.lua b/test/shell.d/fixtures/neovim-clipboard/parity-pr.lua new file mode 100644 index 000000000000..9ee982274473 --- /dev/null +++ b/test/shell.d/fixtures/neovim-clipboard/parity-pr.lua @@ -0,0 +1,179 @@ +-- Clipboard for sessions whose yanks may need to reach another machine, so that +-- yanking, deleting and putting behave the same whether Neovim is local, in +-- tmux, over SSH, or any combination of those. LazyVim empties 'clipboard' +-- whenever SSH_CONNECTION is set, which leaves a plain `y` in the unnamed +-- register; this restores 'unnamedplus' and backs it with a provider that has a +-- fast path in every one of those environments. +-- +-- Writes go to whichever transports the session has: the local Wayland +-- clipboard when there is a display, and the terminal on the other end of the +-- connection via OSC 52 -- emitted by tmux itself where possible, since `tmux +-- load-buffer -w` keeps the payload out of tmux's own input parser and its size +-- limit. Reads prefer whichever clipboard the person is actually sitting in +-- front of, and fall back to the last value this Neovim copied rather than +-- blocking on an OSC 52 query that most terminals refuse to answer. +local M = {} + +local function proc_lines(pid, file) + local ok, lines = pcall(vim.fn.readfile, "/proc/" .. pid .. "/" .. file) + return ok and lines or {} +end + +local function proc_ppid(pid) + for _, line in ipairs(proc_lines(pid, "status")) do + local ppid = line:match("^PPid:%s+(%d+)") + if ppid then + return tonumber(ppid) + end + end +end + +local function ancestor_process_named(name) + local pid = vim.fn.getpid() + + for _ = 1, 16 do + local ppid = proc_ppid(pid) + if not ppid or ppid <= 1 then + return false + end + + local comm = proc_lines(ppid, "comm")[1] or "" + if comm:find(name, 1, true) then + return true + end + + pid = ppid + end + + return false +end + +local function empty(lines) + return lines == nil or #lines == 0 or (#lines == 1 and lines[1] == "") +end + +function M.setup() + local in_tmux = vim.env.TMUX ~= nil + local in_ssh = vim.env.SSH_TTY ~= nil or vim.env.SSH_CONNECTION ~= nil + local in_herdr = vim.env.HERDR_PANE_ID ~= nil or ancestor_process_named("herdr") + + if not (in_tmux or in_ssh or in_herdr) then + return + end + + local osc52 = require("vim.ui.clipboard.osc52") + local has_wayland = vim.env.WAYLAND_DISPLAY ~= nil + and vim.fn.executable("wl-copy") == 1 + and vim.fn.executable("wl-paste") == 1 + local has_tmux = in_tmux and vim.fn.executable("tmux") == 1 + + -- The last value this Neovim put on the clipboard, per register, as + -- { lines, regtype }. A session with no readable clipboard still has to + -- answer a put, and answering it with our own last copy keeps `"+y` `"+p` + -- working instead of failing with E353. + local last_copy = {} + + local function copy(register) + local emit = osc52.copy(register) + + return function(lines, regtype) + last_copy[register] = { lines, regtype or "" } + + if has_wayland then + local cmd = { "wl-copy", "--sensitive", "--type", "text/plain" } + if register == "*" then + cmd[#cmd + 1] = "--primary" + end + vim.fn.system(cmd, lines) + end + + if vim.g.omarchy_remote_clipboard_osc52 == false then + return + end + + -- tmux has no notion of a primary selection, so `*` keeps using the + -- escape sequence directly. + if has_tmux and register == "+" then + vim.fn.system({ "tmux", "load-buffer", "-w", "-" }, lines) + else + emit(lines) + end + end + end + + local function read_wayland(register) + local cmd = { "wl-paste", "--no-newline" } + if register == "*" then + cmd[#cmd + 1] = "--primary" + end + + local lines = vim.fn.systemlist(cmd, "", 1) + if vim.v.shell_error == 0 then + return lines + end + end + + -- `refresh-client -l` asks the attached client for its clipboard; the short + -- sleep gives the reply time to land before the buffer is read. A terminal + -- that refuses simply leaves tmux's newest buffer in place, so this returns + -- something useful either way and never blocks the way an OSC 52 query does. + local function read_tmux() + local lines = vim.fn.systemlist( + { "sh", "-c", "tmux refresh-client -l 2>/dev/null; sleep 0.05; tmux save-buffer -" }, + "", + 1 + ) + if vim.v.shell_error == 0 then + return lines + end + end + + local function read_osc52(register) + if not (vim.g.termfeatures or {}).osc52 then + return + end + + local result = osc52.paste(register)() + if type(result) == "table" then + return result + end + end + + local function paste(register) + return function() + local lines + + -- Over SSH the clipboard worth reading is the one on the machine the + -- person is sitting at, which is the far end of the connection, not the + -- display this Neovim happens to have. + if in_ssh and has_tmux then + lines = read_tmux() + elseif has_wayland then + lines = read_wayland(register) + elseif has_tmux then + lines = read_tmux() + else + lines = read_osc52(register) + end + + if not empty(lines) then + return lines + end + + return last_copy[register] or { vim.fn.getreg('"', 1, true), vim.fn.getregtype('"') } + end + end + + vim.g.clipboard = { + name = "OmarchyRemoteClipboard", + copy = { ["+"] = copy("+"), ["*"] = copy("*") }, + paste = { ["+"] = paste("+"), ["*"] = paste("*") }, + cache_enabled = 0, + } + + -- LazyVim empties this whenever SSH_CONNECTION is set. Restore it so yanking, + -- deleting and putting reach the clipboard exactly as they do locally. + vim.opt.clipboard = "unnamedplus" +end + +return M diff --git a/test/shell.d/neovim-remote-yanks-test.sh b/test/shell.d/neovim-remote-yanks-test.sh index 94b2e7a915d3..d96e4621b0f5 100755 --- a/test/shell.d/neovim-remote-yanks-test.sh +++ b/test/shell.d/neovim-remote-yanks-test.sh @@ -1,52 +1,60 @@ #!/bin/bash - set -euo pipefail - source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" test_home=$(mktemp -d) trap 'rm -rf "$test_home"' EXIT provider="$test_home/.config/nvim/lua/config/remote_clipboard.lua" -migration="$ROOT/migrations/1788996284.sh" +mkdir -p "$(dirname "$provider")" "$test_home/bin" +# Redirect only the packaged source path; run the actual migration logic. +sed "s@/usr/share/omarchy-nvim/config/lua/config/remote_clipboard.lua@$test_home/package.lua@" \ + "$ROOT/migrations/1788996284.sh" >"$test_home/migration.sh" +printf '%s\n' '-- corrected packaged provider' >"$test_home/package.lua" +cat >"$test_home/bin/pacman" <<'STUB' +#!/bin/bash +[[ $* == '-Q omarchy-nvim' ]] || exit 1 +printf 'omarchy-nvim %s\n' "${TEST_NVIM_VERSION:-2026.8.13-2}" +STUB +chmod +x "$test_home/bin/pacman" +run_migration() { + env HOME="$test_home" PATH="$test_home/bin:$PATH" bash -euo pipefail "$test_home/migration.sh" +} -env HOME="$test_home" bash -euo pipefail "$migration" -[[ ! -e $provider ]] || fail "missing Neovim config is left alone" -pass "missing Neovim config is left alone" +run_migration +[[ ! -e $provider ]] || fail "missing provider is left alone" +pass "missing provider is left alone" -mkdir -p "$(dirname "$provider")" -printf '%s\n' '-- Custom provider' >"$provider" -cp "$provider" "$test_home/before.lua" -env HOME="$test_home" bash -euo pipefail "$migration" -cmp "$provider" "$test_home/before.lua" || fail "custom provider is preserved" -pass "custom provider is preserved" +for fixture in "$SHELL_TEST_DIR/fixtures/neovim-clipboard/"*.lua; do + cp "$fixture" "$provider" + run_migration + cmp "$provider" "$test_home/package.lua" || fail "known provider is upgraded: $fixture" + backup=$(ls -t "$provider".bak.* | head -n1) + cmp "$backup" "$fixture" || fail "known provider is backed up: $fixture" + [[ $(stat -c %a "$provider") == "644" ]] || fail "provider is mode 0644" + before=$(ls "$provider".bak.*) + run_migration + [[ $(ls "$provider".bak.*) == "$before" ]] || fail "repeat migration does not create backups" + pass "known provider is backed up and upgraded idempotently: ${fixture##*/}" +done -cat >"$provider" <<'LUA' -local M = {} -function M.setup() - if not vim.env.SSH_CONNECTION then - return - end - vim.g.clipboard = { - name = "OmarchyRemoteClipboard", - } -end -return M -LUA -env HOME="$test_home" bash -euo pipefail "$migration" -require_command nvim -cat >"$test_home/check.lua" <<'LUA' -vim.env.SSH_CONNECTION = nil -vim.opt.clipboard = "" -dofile(vim.env.TEST_PROVIDER).setup() -assert(vim.o.clipboard == "") -vim.env.SSH_CONNECTION = "test" -dofile(vim.env.TEST_PROVIDER).setup() -assert(vim.o.clipboard == "unnamedplus") -LUA -env NVIM_LOG_FILE="$test_home/nvim.log" TEST_PROVIDER="$provider" nvim --clean -n --headless -i NONE -l "$test_home/check.lua" -pass "clipboard syncing is enabled inside remote provider setup" +cp "$SHELL_TEST_DIR/fixtures/neovim-clipboard/july.lua" "$provider" +printf '%s\n' '-- user customization' >>"$provider" +cp "$provider" "$test_home/custom.lua" +run_migration >"$test_home/output" +cmp "$provider" "$test_home/custom.lua" || fail "customized provider is preserved" +grep -q 'Preserving customized' "$test_home/output" || fail "customized provider receives guidance" +printf '%s\n' '-- unrelated provider' >"$provider" +cp "$provider" "$test_home/custom.lua" +run_migration +cmp "$provider" "$test_home/custom.lua" || fail "unrelated provider is preserved" +pass "customized and unrelated providers are preserved" -cp "$provider" "$test_home/once.lua" -env HOME="$test_home" bash -euo pipefail "$migration" -cmp "$provider" "$test_home/once.lua" || fail "migration is idempotent" -pass "migration is idempotent" +cp "$SHELL_TEST_DIR/fixtures/neovim-clipboard/june.lua" "$provider" +export TEST_NVIM_VERSION=2026.8.13-1 +if run_migration; then fail "old package leaves migration pending"; fi +cmp "$provider" "$SHELL_TEST_DIR/fixtures/neovim-clipboard/june.lua" || fail "old package leaves provider unchanged" +unset TEST_NVIM_VERSION +mv "$test_home/package.lua" "$test_home/package.saved" +if run_migration; then fail "missing package source leaves migration pending"; fi +cmp "$provider" "$SHELL_TEST_DIR/fixtures/neovim-clipboard/june.lua" || fail "missing source leaves provider unchanged" +pass "old or missing package cannot mark an unrepaired provider complete" From 8369601f26b41164ab285f61d35434f6933479de Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 13 Sep 2026 17:58:17 +0200 Subject: [PATCH 062/194] Remove CODEOWNERS No branch on the repo is protected and there are no rulesets, so the file never enforced owner review. Its only effect was auto-requesting a review from the other owner on every PR, which nobody acted on. Co-Authored-By: Claude Fable 5.1 --- .github/CODEOWNERS | 2 -- 1 file changed, 2 deletions(-) delete mode 100644 .github/CODEOWNERS diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS deleted file mode 100644 index 4e9460ddb315..000000000000 --- a/.github/CODEOWNERS +++ /dev/null @@ -1,2 +0,0 @@ -# Merges to protected branches need sign-off from an org owner. -* @dhh @ryanrhughes From 8a972da9756dbebe4e46512079363278dfb2a62a Mon Sep 17 00:00:00 2001 From: Ryan Hughes Date: Sun, 13 Sep 2026 14:43:47 -0400 Subject: [PATCH 063/194] Migrate Panther Lake systems to the Omarchy PTL kernel --- etc/limine-entry-tool.d/omarchy-defaults.conf | 2 +- install/hardware/all.sh | 2 +- install/hardware/fix-elgato-camlink-4k.sh | 2 +- install/hardware/intel/ptl-kernel.sh | 13 +- install/hardware/nvidia.sh | 2 +- install/omarchy-other.packages | 4 +- migrations/1789095456.sh | 45 ++++ test/shell.d/limine-defaults-test.sh | 4 + test/shell.d/ptl-kernel-migration-test.sh | 195 ++++++++++++++++++ 9 files changed, 257 insertions(+), 12 deletions(-) create mode 100644 migrations/1789095456.sh create mode 100644 test/shell.d/ptl-kernel-migration-test.sh diff --git a/etc/limine-entry-tool.d/omarchy-defaults.conf b/etc/limine-entry-tool.d/omarchy-defaults.conf index 49c6204bcb4b..1703dab42e96 100644 --- a/etc/limine-entry-tool.d/omarchy-defaults.conf +++ b/etc/limine-entry-tool.d/omarchy-defaults.conf @@ -15,7 +15,7 @@ ENABLE_LIMINE_FALLBACK=yes # Find and add other bootloaders FIND_BOOTLOADERS=yes -BOOT_ORDER="*, *fallback, Snapshots" +BOOT_ORDER="linux-omarchy-*, *, *fallback, Snapshots" # Snapper is configured with NUMBER_LIMIT="5" (see default/snapper/root), but # limine-snapper-sync can see the newly created sixth snapshot before cleanup diff --git a/install/hardware/all.sh b/install/hardware/all.sh index defeef1c7d22..df695c65d041 100644 --- a/install/hardware/all.sh +++ b/install/hardware/all.sh @@ -17,7 +17,7 @@ run_logged "$OMARCHY_INSTALL/hardware/intel/thermald.sh" # Swap in the Panther Lake kernel before anything pulls DKMS modules in. # intel-ipu7-camera drags in ipu7-drivers, vision-drivers and v4l2loopback, # and building all three against the stock kernel only to rebuild them against -# linux-ptl and tear the first set down again cost ~25s of the install. +# the PTL kernel and tear the first set down again cost ~25s of the install. run_logged "$OMARCHY_INSTALL/hardware/intel/ptl-kernel.sh" run_logged "$OMARCHY_INSTALL/hardware/intel/ipu7-camera.sh" run_logged "$OMARCHY_INSTALL/hardware/intel/fred.sh" diff --git a/install/hardware/fix-elgato-camlink-4k.sh b/install/hardware/fix-elgato-camlink-4k.sh index f726fd9a506d..eec9771f3972 100644 --- a/install/hardware/fix-elgato-camlink-4k.sh +++ b/install/hardware/fix-elgato-camlink-4k.sh @@ -4,7 +4,7 @@ # v4l2-relayd re-exposes it at 1280x720 under the same name. if omarchy-hw-elgato-camlink-4k; then - mapfile -t kernel_headers < <(pacman -Qqs '^linux(-zen|-lts|-hardened|-t2|-ptl|-omarchy-bore)?$' | sed 's/$/-headers/') + mapfile -t kernel_headers < <(pacman -Qqs '^linux(-zen|-lts|-hardened|-t2|-ptl|-omarchy-bore|-omarchy-ptl-novrr-mm)?$' | sed 's/$/-headers/') omarchy-pkg-add "${kernel_headers[@]}" v4l2loopback-dkms v4l2loopback-utils v4l2-relayd sudo install -Dm644 "$OMARCHY_PATH/default/udev/elgato-camlink-4k.rules" /etc/udev/rules.d/71-elgato-camlink-4k.rules diff --git a/install/hardware/intel/ptl-kernel.sh b/install/hardware/intel/ptl-kernel.sh index 794827249c41..12659a28a71a 100644 --- a/install/hardware/intel/ptl-kernel.sh +++ b/install/hardware/intel/ptl-kernel.sh @@ -1,16 +1,17 @@ # Install Panther Lake kernel for Dell XPS Panther Lake systems -# The linux-ptl kernel includes audio driver patches not yet in mainline. +# The Omarchy PTL kernel includes Panther Lake display and memory fixes. if omarchy-hw-match "XPS" && omarchy-hw-intel-ptl; then echo "Detected Dell XPS Panther Lake, installing PTL kernel..." - omarchy-pkg-add linux-ptl linux-ptl-headers + # linux-ptl required SOF firmware; the new kernel only lists it as optional. + omarchy-pkg-add linux-omarchy-ptl-novrr-mm linux-omarchy-ptl-novrr-mm-headers sof-firmware pacman -Rdd --noconfirm linux linux-headers || true - # linux-ptl doesn't provide=linux, so anything depending on linux drags the + # The PTL kernel doesn't provide=linux, so anything depending on linux drags the # stock kernel back in and the boot menu grows a second, slower entry. if pacman -Qq linux &>/dev/null; then - echo "WARNING: stock linux kernel still installed alongside linux-ptl:" + echo "WARNING: stock linux kernel still installed alongside the Omarchy PTL kernel:" pacman -Qi linux | grep -i "required by" fi @@ -19,7 +20,7 @@ if omarchy-hw-match "XPS" && omarchy-hw-intel-ptl; then # the last BOOT_ORDER wins, so an earlier-sorting name is a silent no-op. rm -f /etc/limine-entry-tool.d/dell-xps-panther-lake.conf cat > /etc/limine-entry-tool.d/zz-dell-xps-panther-lake.conf <<'EOF' -# Only show Panther Lake kernel in boot menu on Dell XPS Panther Lake -BOOT_ORDER="linux-ptl*, *fallback, Snapshots" +# Prefer Omarchy kernels while keeping other kernels available for recovery +BOOT_ORDER="linux-omarchy-*, *, *fallback, Snapshots" EOF fi diff --git a/install/hardware/nvidia.sh b/install/hardware/nvidia.sh index e73709955114..81e1556e9e61 100644 --- a/install/hardware/nvidia.sh +++ b/install/hardware/nvidia.sh @@ -1,6 +1,6 @@ if lspci | grep -qi 'nvidia'; then # Check which kernel is installed and set appropriate headers package - KERNEL_PACKAGE=$(pacman -Qqs '^linux(-zen|-lts|-hardened|-t2|-ptl)?$' | head -1 || true) + KERNEL_PACKAGE=$(pacman -Qqs '^linux(-zen|-lts|-hardened|-t2|-ptl|-omarchy-ptl-novrr-mm)?$' | head -1 || true) [[ -n $KERNEL_PACKAGE ]] && omarchy-pkg-add "$KERNEL_PACKAGE-headers" if omarchy-hw-nvidia-gsp; then diff --git a/install/omarchy-other.packages b/install/omarchy-other.packages index 3214657a6630..873e5048bf15 100644 --- a/install/omarchy-other.packages +++ b/install/omarchy-other.packages @@ -23,8 +23,8 @@ limine-snapper-sync linux linux-firmware linux-headers -linux-ptl -linux-ptl-headers +linux-omarchy-ptl-novrr-mm +linux-omarchy-ptl-novrr-mm-headers macbook12-spi-driver-dkms nvidia-580xx-dkms nvidia-dkms diff --git a/migrations/1789095456.sh b/migrations/1789095456.sh new file mode 100644 index 000000000000..574d3d9ee192 --- /dev/null +++ b/migrations/1789095456.sh @@ -0,0 +1,45 @@ +echo "Install the Omarchy Panther Lake kernel and prefer Omarchy kernels in Limine" + +omarchy-pkg-present linux-ptl || exit 0 + +limine_conf="${OMARCHY_PTL_LIMINE_CONF:-/etc/default/limine}" +limine_drop_ins="${OMARCHY_PTL_LIMINE_DROP_INS:-/etc/limine-entry-tool.d}" +rebuild_marker="${OMARCHY_PTL_REBUILD_MARKER:-/var/lib/omarchy/migrations/1789095456}" +kernel="linux-omarchy-ptl-novrr-mm" + +# Completion is machine-wide even though migrations run once per user. Leave +# the old kernel installed so it remains available if the new one cannot boot. +[[ ! -e $rebuild_marker ]] || exit 0 +omarchy-pkg-add "$kernel" "$kernel-headers" + +# /etc/default/limine and the Dell drop-ins were written by the installer. +# omarchy-settings ships omarchy-defaults.conf, but pacman's backup protection +# can leave its update in a .pacnew when other settings were customized. Repair +# only the old boot order in the active files, preserving custom orders and +# unrelated settings, including the root filesystem's kernel command line. +for conf in "$limine_conf" \ + "$limine_drop_ins/omarchy-defaults.conf" \ + "$limine_drop_ins/dell-xps-panther-lake.conf" \ + "$limine_drop_ins/zz-dell-xps-panther-lake.conf"; do + if [[ -f $conf ]]; then + sudo sed -i -E \ + 's/^([[:space:]]*BOOT_ORDER=)"(\*|linux-ptl\*), \*fallback, Snapshots"([[:space:]]*(#.*)?)$/\1"linux-omarchy-*, *, *fallback, Snapshots"\3/' \ + "$conf" + fi +done + +# Package hooks ran before the config repair. Rebuild the new kernel's image +# and boot entry explicitly, including on retries after a failed rebuild. +sudo limine-mkinitcpio "$kernel" + +# limine-mkinitcpio can return success after skipping a failed kernel build. +# Do not mark the migration complete unless the new kernel is in the menu. +if ! sudo limine-entry-tool --tree | grep -F "$kernel" >/dev/null; then + echo "The new Panther Lake kernel has no Limine boot entry; rerun omarchy-migrate after fixing the boot image build." >&2 + exit 1 +fi + +# Keeping the running kernel installed prevents the updater from detecting a +# kernel replacement, so request the reboot explicitly. +omarchy-state set reboot-required +sudo install -Dm644 /dev/null "$rebuild_marker" diff --git a/test/shell.d/limine-defaults-test.sh b/test/shell.d/limine-defaults-test.sh index e4c420fffa1c..cf93ebdfa198 100644 --- a/test/shell.d/limine-defaults-test.sh +++ b/test/shell.d/limine-defaults-test.sh @@ -9,3 +9,7 @@ packaged_defaults="$ROOT/etc/limine-entry-tool.d/omarchy-defaults.conf" grep -Fq 'KERNEL_CMDLINE[default]+=" initramfs_async=0"' "$packaged_defaults" || fail "the packaged Limine defaults still unpack the initramfs synchronously" pass "packaged Limine defaults keep Plymouth alive at the LUKS prompt" + +grep -Fxq 'BOOT_ORDER="linux-omarchy-*, *, *fallback, Snapshots"' "$packaged_defaults" || + fail "packaged Limine defaults prefer Omarchy kernels and retain recovery entries" +pass "packaged Limine defaults prefer Omarchy kernels and retain recovery entries" diff --git a/test/shell.d/ptl-kernel-migration-test.sh b/test/shell.d/ptl-kernel-migration-test.sh new file mode 100644 index 000000000000..874397c03815 --- /dev/null +++ b/test/shell.d/ptl-kernel-migration-test.sh @@ -0,0 +1,195 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +migration="$ROOT/migrations/1789095456.sh" +scratch=$(mktemp -d) +trap 'rm -rf "$scratch"' EXIT +mkdir -p "$scratch/bin" "$scratch/drop-ins" + +export PATH="$scratch/bin:$ROOT/bin:$PATH" +export CALL_LOG="$scratch/calls" +export INSTALLED_PACKAGES="$scratch/packages" +export OMARCHY_PTL_LIMINE_CONF="$scratch/limine" +export OMARCHY_PTL_LIMINE_DROP_INS="$scratch/drop-ins" +export OMARCHY_PTL_REBUILD_MARKER="$scratch/state/completed" +kernel="linux-omarchy-ptl-novrr-mm" +boot_order='BOOT_ORDER="linux-omarchy-*, *, *fallback, Snapshots"' + +# Exercise the real package helpers, including their post-install queries. +cat > "$scratch/bin/pacman" <<'SH' +#!/bin/bash +case "$1" in + -Q) grep -Fxq "$2" "$INSTALLED_PACKAGES" ;; + -S) + printf 'pacman %s\n' "$*" >> "$CALL_LOG" + [[ ${INSTALL_FAIL:-0} == "0" ]] || exit 1 + for arg in "$@"; do + [[ $arg == -* ]] || printf '%s\n' "$arg" >> "$INSTALLED_PACKAGES" + done + ;; + *) exit 99 ;; +esac +SH + +cat > "$scratch/bin/sudo" <<'SH' +#!/bin/bash +printf 'sudo %s\n' "$*" >> "$CALL_LOG" +case "$1" in + pacman | sed | install | limine-mkinitcpio | limine-entry-tool) exec "$@" ;; + *) exit 99 ;; +esac +SH + +cat > "$scratch/bin/limine-mkinitcpio" <<'SH' +#!/bin/bash +[[ ${REBUILD_FAIL:-0} == "0" ]] +SH + +cat > "$scratch/bin/limine-entry-tool" <<'SH' +#!/bin/bash +[[ $* == "--tree" ]] || exit 99 +printf '%s\n' 'Omarchy' ' linux-ptl' ' Snapshots' +if [[ ${MISSING_ENTRY:-0} == "0" ]]; then + printf '%s\n' ' linux-omarchy-ptl-novrr-mm' +fi +SH + +cat > "$scratch/bin/omarchy-state" <<'SH' +#!/bin/bash +[[ $* == "set reboot-required" ]] || exit 99 +printf 'state %s\n' "$*" >> "$CALL_LOG" +SH +chmod +x "$scratch/bin/"* + +reset_fixture() { + : > "$CALL_LOG" + printf '%s\n' linux-ptl linux-ptl-headers > "$INSTALLED_PACKAGES" + rm -f "$OMARCHY_PTL_REBUILD_MARKER" "$OMARCHY_PTL_LIMINE_DROP_INS/"*.conf + cat > "$OMARCHY_PTL_LIMINE_CONF" <<'CONF' +KERNEL_CMDLINE[default]="root=UUID=keep-me rw cryptdevice=UUID=keep-me:root" +BOOT_ORDER="*, *fallback, Snapshots" +ENABLE_UKI=yes +CONF + cp "$OMARCHY_PTL_LIMINE_CONF" "$scratch/original-limine" +} + +run_migration() { + bash -euo pipefail "$migration" > "$scratch/output" 2>&1 +} + +assert_preferred() { + grep -Fxq "$boot_order" "$1" || fail "Omarchy kernels are preferred in $1" +} + +reset_fixture +printf '%s\n' linux > "$INSTALLED_PACKAGES" +run_migration +[[ ! -s $CALL_LOG ]] || fail "systems without linux-ptl do not change" +cmp -s "$OMARCHY_PTL_LIMINE_CONF" "$scratch/original-limine" || fail "unaffected Limine settings stay unchanged" +[[ ! -e $OMARCHY_PTL_REBUILD_MARKER ]] || fail "unaffected systems do not get a completion marker" +pass "systems without linux-ptl are skipped" + +reset_fixture +for name in dell-xps-panther-lake zz-dell-xps-panther-lake; do + printf '%s\n' 'BOOT_ORDER="linux-ptl*, *fallback, Snapshots"' > "$OMARCHY_PTL_LIMINE_DROP_INS/$name.conf" +done +cp "$OMARCHY_PTL_LIMINE_CONF" "$OMARCHY_PTL_LIMINE_DROP_INS/omarchy-defaults.conf" +run_migration +grep -Fxq "pacman -S --noconfirm --needed $kernel $kernel-headers" "$CALL_LOG" || fail "both new packages are installed" +grep -Fxq linux-ptl "$INSTALLED_PACKAGES" || fail "the old kernel is kept for recovery" +grep -Fxq linux-ptl-headers "$INSTALLED_PACKAGES" || fail "the old kernel headers are kept" +assert_preferred "$OMARCHY_PTL_LIMINE_CONF" +for conf in "$OMARCHY_PTL_LIMINE_DROP_INS/"*.conf; do + assert_preferred "$conf" +done +diff -u <(sed '/^BOOT_ORDER=/d' "$scratch/original-limine") \ + <(sed '/^BOOT_ORDER=/d' "$OMARCHY_PTL_LIMINE_CONF") || fail "kernel command line and unrelated settings are preserved" +grep -Fxq "sudo limine-mkinitcpio $kernel" "$CALL_LOG" || fail "the new kernel's boot image is rebuilt" +[[ -f $OMARCHY_PTL_REBUILD_MARKER ]] || fail "successful completion is recorded" +grep -Fxq 'state set reboot-required' "$CALL_LOG" || fail "the updater must offer a reboot when retaining the old kernel" +pass "new packages install, all stock boot orders are repaired, and the old kernel remains available" + +: > "$CALL_LOG" +run_migration +[[ ! -s $CALL_LOG ]] || fail "another user's run does not repeat the machine-wide migration" +pass "repeat runs are a no-op after successful completion" + +reset_fixture +printf '%s\n' "$kernel" >> "$INSTALLED_PACKAGES" +run_migration +grep -Fxq "$kernel-headers" "$INSTALLED_PACKAGES" || fail "missing headers install when the kernel is already present" +pass "a partially installed kernel gets its missing headers" + +reset_fixture +printf '%s\n' "$kernel" "$kernel-headers" >> "$INSTALLED_PACKAGES" +run_migration +! grep -q '^pacman -S' "$CALL_LOG" || fail "already installed packages are not reinstalled" +assert_preferred "$OMARCHY_PTL_LIMINE_CONF" +pass "existing new packages still receive the config repair and boot rebuild" + +reset_fixture +if INSTALL_FAIL=1 run_migration; then + fail "package installation failure must fail the migration" +fi +cmp -s "$OMARCHY_PTL_LIMINE_CONF" "$scratch/original-limine" || fail "install failure leaves the config untouched" +! grep -q 'limine-mkinitcpio' "$CALL_LOG" || fail "install failure does not rebuild" +[[ ! -e $OMARCHY_PTL_REBUILD_MARKER ]] || fail "install failure stays pending" +pass "package failures leave the old boot setup intact and the migration pending" + +reset_fixture +if REBUILD_FAIL=1 run_migration; then + fail "boot rebuild failure must fail the migration" +fi +[[ ! -e $OMARCHY_PTL_REBUILD_MARKER ]] || fail "rebuild failure stays pending" +! grep -q '^state ' "$CALL_LOG" || fail "rebuild failure must not request a reboot" +assert_preferred "$OMARCHY_PTL_LIMINE_CONF" +: > "$CALL_LOG" +run_migration +grep -Fxq "sudo limine-mkinitcpio $kernel" "$CALL_LOG" || fail "retry must rebuild even after config and packages are repaired" +[[ -f $OMARCHY_PTL_REBUILD_MARKER ]] || fail "retry records successful completion" +pass "a failed rebuild is retried even after config and package changes succeeded" + +reset_fixture +if MISSING_ENTRY=1 run_migration; then + fail "a silently skipped kernel build must fail the migration" +fi +[[ ! -e $OMARCHY_PTL_REBUILD_MARKER ]] || fail "a missing boot entry stays pending" +! grep -q '^state ' "$CALL_LOG" || fail "a missing boot entry must not request a reboot" +run_migration +[[ -f $OMARCHY_PTL_REBUILD_MARKER ]] || fail "a missing boot entry can be repaired on retry" +pass "a successful command without a new boot entry cannot complete the migration" + +reset_fixture +printf '%s\n' 'BOOT_ORDER="linux-lts, *, *fallback, Snapshots"' > "$OMARCHY_PTL_LIMINE_CONF" +cp "$OMARCHY_PTL_LIMINE_CONF" "$scratch/custom-limine" +run_migration +cmp -s "$OMARCHY_PTL_LIMINE_CONF" "$scratch/custom-limine" || fail "custom boot orders stay unchanged" +pass "administrator-defined boot orders are preserved" + +reset_fixture +cp "$OMARCHY_PTL_LIMINE_CONF" "$OMARCHY_PTL_LIMINE_DROP_INS/omarchy-defaults.conf" +printf '%s\n' 'ENABLE_SORT=yes' >> "$OMARCHY_PTL_LIMINE_DROP_INS/omarchy-defaults.conf" +cp "$ROOT/etc/limine-entry-tool.d/omarchy-defaults.conf" "$OMARCHY_PTL_LIMINE_DROP_INS/omarchy-defaults.conf.pacnew" +run_migration +assert_preferred "$OMARCHY_PTL_LIMINE_DROP_INS/omarchy-defaults.conf" +grep -Fxq 'ENABLE_SORT=yes' "$OMARCHY_PTL_LIMINE_DROP_INS/omarchy-defaults.conf" || fail "custom packaged settings survive the repair" +cmp -s "$ROOT/etc/limine-entry-tool.d/omarchy-defaults.conf" \ + "$OMARCHY_PTL_LIMINE_DROP_INS/omarchy-defaults.conf.pacnew" || fail "the pending pacnew is left for the administrator to merge" +pass "active packaged defaults are repaired when customized settings leave the update in a pacnew" + +reset_fixture +printf '%s\n' ' BOOT_ORDER="*, *fallback, Snapshots" # keep this comment' > "$OMARCHY_PTL_LIMINE_CONF" +run_migration +grep -Fxq " $boot_order # keep this comment" "$OMARCHY_PTL_LIMINE_CONF" || fail "stock orders with comments are repaired" +pass "indentation and comments survive the repair" + +reset_fixture +rm "$OMARCHY_PTL_LIMINE_CONF" +cp "$ROOT/etc/limine-entry-tool.d/omarchy-defaults.conf" "$OMARCHY_PTL_LIMINE_DROP_INS/omarchy-defaults.conf" +run_migration +[[ ! -e $OMARCHY_PTL_LIMINE_CONF ]] || fail "missing central config is not fabricated" +assert_preferred "$OMARCHY_PTL_LIMINE_DROP_INS/omarchy-defaults.conf" +pass "installs without a central config inherit the packaged boot order" From 905ff1f79228e11a47bcf3b8731335d032ad355e Mon Sep 17 00:00:00 2001 From: Ryan Hughes Date: Sun, 13 Sep 2026 19:48:41 -0400 Subject: [PATCH 064/194] Replace Neovim providers atomically and preserve dotfile links --- migrations/1788996284.sh | 19 ++++++++- test/shell.d/neovim-remote-yanks-test.sh | 51 ++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/migrations/1788996284.sh b/migrations/1788996284.sh index 5a9437288204..f2326812b9bd 100644 --- a/migrations/1788996284.sh +++ b/migrations/1788996284.sh @@ -3,6 +3,18 @@ echo "Repair remote Neovim clipboard yanks and paste" nvim_provider="$HOME/.config/nvim/lua/config/remote_clipboard.lua" provider_source="/usr/share/omarchy-nvim/config/lua/config/remote_clipboard.lua" +# Dotfile managers may own either the file or a parent directory through a +# symlink. Preserve that layout rather than detaching or editing its target. +provider_path="$nvim_provider" +while [[ $provider_path != "$HOME" && $provider_path != / ]]; do + if [[ -L $provider_path ]]; then + echo "Preserving symlink-managed Neovim provider: $nvim_provider" + echo "Review remote clipboard settings in your dotfile configuration manually." + exit 0 + fi + provider_path=$(dirname "$provider_path") +done + [[ -f $nvim_provider ]] || exit 0 # Replace only known Omarchy versions, including the June file-backed provider @@ -30,5 +42,10 @@ fi provider_backup=$(mktemp "$nvim_provider.bak.XXXXXX") cp -p "$nvim_provider" "$provider_backup" -install -m 0644 "$provider_source" "$nvim_provider" +provider_staged=$(mktemp "$nvim_provider.new.XXXXXX") +trap 'rm -f -- "$provider_staged"' EXIT +install -m 0644 "$provider_source" "$provider_staged" +# A failed write leaves the recognized original live, so retries can repair it. +# The temporary file is on the same filesystem for an atomic replacement. +mv -fT -- "$provider_staged" "$nvim_provider" echo "Previous Neovim provider saved to $provider_backup" diff --git a/test/shell.d/neovim-remote-yanks-test.sh b/test/shell.d/neovim-remote-yanks-test.sh index d96e4621b0f5..84a0c721e521 100755 --- a/test/shell.d/neovim-remote-yanks-test.sh +++ b/test/shell.d/neovim-remote-yanks-test.sh @@ -58,3 +58,54 @@ mv "$test_home/package.lua" "$test_home/package.saved" if run_migration; then fail "missing package source leaves migration pending"; fi cmp "$provider" "$SHELL_TEST_DIR/fixtures/neovim-clipboard/june.lua" || fail "missing source leaves provider unchanged" pass "old or missing package cannot mark an unrepaired provider complete" + +mv "$test_home/package.saved" "$test_home/package.lua" +# A write that fails after producing partial output must never damage the live +# provider. Exercise the real install destination with a failing replacement. +cat >"$test_home/bin/install" <<'STUB' +#!/bin/bash +printf '%s' '-- truncated replacement' >"${@: -1}" +exit 1 +STUB +chmod +x "$test_home/bin/install" +if run_migration; then fail "failed staging write leaves migration pending"; fi +cmp "$provider" "$SHELL_TEST_DIR/fixtures/neovim-clipboard/june.lua" || fail "failed write preserves live provider" +if compgen -G "$provider.new.*" >/dev/null; then fail "failed staging file is cleaned up"; fi +rm "$test_home/bin/install" +run_migration +cmp "$provider" "$test_home/package.lua" || fail "retry repairs the recognized original" +pass "failed write preserves original and retry succeeds" + +# Also fail the final rename, after successful staging. +cp "$SHELL_TEST_DIR/fixtures/neovim-clipboard/july.lua" "$provider" +printf '#!/bin/bash\nexit 1\n' >"$test_home/bin/mv" +chmod +x "$test_home/bin/mv" +if run_migration; then fail "failed rename leaves migration pending"; fi +cmp "$provider" "$SHELL_TEST_DIR/fixtures/neovim-clipboard/july.lua" || fail "failed rename preserves original" +if compgen -G "$provider.new.*" >/dev/null; then fail "failed rename staging file is cleaned up"; fi +rm "$test_home/bin/mv" +run_migration +cmp "$provider" "$test_home/package.lua" || fail "retry after rename failure succeeds" +pass "failed rename preserves original and retry succeeds" + +cp "$SHELL_TEST_DIR/fixtures/neovim-clipboard/july.lua" "$test_home/dotfile.lua" +rm "$provider" +ln -s "$test_home/dotfile.lua" "$provider" +run_migration >"$test_home/output" +[[ -L $provider ]] || fail "provider symlink is preserved" +cmp "$test_home/dotfile.lua" "$SHELL_TEST_DIR/fixtures/neovim-clipboard/july.lua" || fail "symlink target is preserved" +grep -q 'symlink-managed' "$test_home/output" || fail "linked provider receives guidance" +rm "$provider" +ln -s "$test_home/absent.lua" "$provider" +run_migration +[[ -L $provider && ! -e $provider ]] || fail "dangling symlink is preserved" +rm "$provider" + +mkdir "$test_home/dotfiles" +mv "$test_home/.config/nvim/lua/config" "$test_home/dotfiles/config" +ln -s "$test_home/dotfiles/config" "$test_home/.config/nvim/lua/config" +cp "$SHELL_TEST_DIR/fixtures/neovim-clipboard/july.lua" "$provider" +run_migration +[[ -L $test_home/.config/nvim/lua/config ]] || fail "linked config directory is preserved" +cmp "$provider" "$SHELL_TEST_DIR/fixtures/neovim-clipboard/july.lua" || fail "provider in linked directory is preserved" +pass "linked files, dangling links and linked directories are preserved" From ff85faf8dda228de9c6a6d3eb0c74cdde8b3bb99 Mon Sep 17 00:00:00 2001 From: Ryan Hughes Date: Mon, 14 Sep 2026 16:32:09 -0400 Subject: [PATCH 065/194] Make linux-omarchy the default kernel except on T2 Macs --- etc/limine-entry-tool.d/omarchy-defaults.conf | 3 +- install/hardware/all.sh | 11 +- install/hardware/fix-elgato-camlink-4k.sh | 2 +- install/hardware/intel/ptl-kernel.sh | 26 -- install/hardware/kernel.sh | 9 + install/hardware/nvidia.sh | 2 +- install/omarchy-other.packages | 4 +- migrations/1789095456.sh | 45 ---- migrations/1789325478.sh | 44 ++++ test/shell.d/limine-defaults-test.sh | 6 +- test/shell.d/omarchy-kernel-install-test.sh | 84 ++++++ test/shell.d/omarchy-kernel-migration-test.sh | 248 ++++++++++++++++++ test/shell.d/ptl-kernel-migration-test.sh | 195 -------------- test/shell.d/xps13-sidecar-amps-test.sh | 11 +- 14 files changed, 402 insertions(+), 288 deletions(-) delete mode 100644 install/hardware/intel/ptl-kernel.sh create mode 100644 install/hardware/kernel.sh delete mode 100644 migrations/1789095456.sh create mode 100644 migrations/1789325478.sh create mode 100644 test/shell.d/omarchy-kernel-install-test.sh create mode 100644 test/shell.d/omarchy-kernel-migration-test.sh delete mode 100644 test/shell.d/ptl-kernel-migration-test.sh diff --git a/etc/limine-entry-tool.d/omarchy-defaults.conf b/etc/limine-entry-tool.d/omarchy-defaults.conf index 1703dab42e96..ec0fa96f4c71 100644 --- a/etc/limine-entry-tool.d/omarchy-defaults.conf +++ b/etc/limine-entry-tool.d/omarchy-defaults.conf @@ -15,7 +15,8 @@ ENABLE_LIMINE_FALLBACK=yes # Find and add other bootloaders FIND_BOOTLOADERS=yes -BOOT_ORDER="linux-omarchy-*, *, *fallback, Snapshots" +# Keep T2 Macs on their specialized kernel; prefer linux-omarchy elsewhere. +BOOT_ORDER="linux-t2, linux-omarchy, linux-omarchy-*, *, *fallback, Snapshots" # Snapper is configured with NUMBER_LIMIT="5" (see default/snapper/root), but # limine-snapper-sync can see the newly created sixth snapshot before cleanup diff --git a/install/hardware/all.sh b/install/hardware/all.sh index df695c65d041..d40069b26936 100644 --- a/install/hardware/all.sh +++ b/install/hardware/all.sh @@ -1,3 +1,5 @@ +run_logged "$OMARCHY_INSTALL/hardware/kernel.sh" + run_logged "$OMARCHY_INSTALL/hardware/asus-rog.sh" run_logged "$OMARCHY_INSTALL/hardware/framework16.sh" run_logged "$OMARCHY_INSTALL/hardware/dell-xps-touchpad-haptics.sh" @@ -14,21 +16,14 @@ run_logged "$OMARCHY_INSTALL/hardware/vulkan.sh" run_logged "$OMARCHY_INSTALL/hardware/intel/video-acceleration.sh" run_logged "$OMARCHY_INSTALL/hardware/intel/lpmd.sh" run_logged "$OMARCHY_INSTALL/hardware/intel/thermald.sh" -# Swap in the Panther Lake kernel before anything pulls DKMS modules in. -# intel-ipu7-camera drags in ipu7-drivers, vision-drivers and v4l2loopback, -# and building all three against the stock kernel only to rebuild them against -# the PTL kernel and tear the first set down again cost ~25s of the install. -run_logged "$OMARCHY_INSTALL/hardware/intel/ptl-kernel.sh" run_logged "$OMARCHY_INSTALL/hardware/intel/ipu7-camera.sh" run_logged "$OMARCHY_INSTALL/hardware/intel/fred.sh" run_logged "$OMARCHY_INSTALL/hardware/intel/fix-wifi7-eht.sh" run_logged "$OMARCHY_INSTALL/hardware/intel/sof-firmware.sh" -# Pulls in v4l2loopback-dkms, so it sits after the Panther Lake kernel swap. run_logged "$OMARCHY_INSTALL/hardware/fix-elgato-camlink-4k.sh" -# Rebuilds the boot image, so it has to follow the Panther Lake kernel swap -# above rather than sit with the other Dell leaf at the top of this file. +# Rebuilds the boot image, so it follows kernel and camera module setup. run_logged "$OMARCHY_INSTALL/hardware/dell-xps13-sidecar-amps.sh" run_logged "$OMARCHY_INSTALL/hardware/asus/fix-asus-ptl-display-backlight.sh" diff --git a/install/hardware/fix-elgato-camlink-4k.sh b/install/hardware/fix-elgato-camlink-4k.sh index eec9771f3972..274076cef57c 100644 --- a/install/hardware/fix-elgato-camlink-4k.sh +++ b/install/hardware/fix-elgato-camlink-4k.sh @@ -4,7 +4,7 @@ # v4l2-relayd re-exposes it at 1280x720 under the same name. if omarchy-hw-elgato-camlink-4k; then - mapfile -t kernel_headers < <(pacman -Qqs '^linux(-zen|-lts|-hardened|-t2|-ptl|-omarchy-bore|-omarchy-ptl-novrr-mm)?$' | sed 's/$/-headers/') + mapfile -t kernel_headers < <(pacman -Qqs '^linux(-zen|-lts|-hardened|-t2|-ptl|-omarchy(-bore|-ptl-novrr-mm)?)?$' | sed 's/$/-headers/') omarchy-pkg-add "${kernel_headers[@]}" v4l2loopback-dkms v4l2loopback-utils v4l2-relayd sudo install -Dm644 "$OMARCHY_PATH/default/udev/elgato-camlink-4k.rules" /etc/udev/rules.d/71-elgato-camlink-4k.rules diff --git a/install/hardware/intel/ptl-kernel.sh b/install/hardware/intel/ptl-kernel.sh deleted file mode 100644 index 12659a28a71a..000000000000 --- a/install/hardware/intel/ptl-kernel.sh +++ /dev/null @@ -1,26 +0,0 @@ -# Install Panther Lake kernel for Dell XPS Panther Lake systems -# The Omarchy PTL kernel includes Panther Lake display and memory fixes. - -if omarchy-hw-match "XPS" && omarchy-hw-intel-ptl; then - echo "Detected Dell XPS Panther Lake, installing PTL kernel..." - - # linux-ptl required SOF firmware; the new kernel only lists it as optional. - omarchy-pkg-add linux-omarchy-ptl-novrr-mm linux-omarchy-ptl-novrr-mm-headers sof-firmware - pacman -Rdd --noconfirm linux linux-headers || true - - # The PTL kernel doesn't provide=linux, so anything depending on linux drags the - # stock kernel back in and the boot menu grows a second, slower entry. - if pacman -Qq linux &>/dev/null; then - echo "WARNING: stock linux kernel still installed alongside the Omarchy PTL kernel:" - pacman -Qi linux | grep -i "required by" - fi - - mkdir -p /etc/limine-entry-tool.d - # Named to sort after omarchy-defaults.conf: drop-ins are read in order and - # the last BOOT_ORDER wins, so an earlier-sorting name is a silent no-op. - rm -f /etc/limine-entry-tool.d/dell-xps-panther-lake.conf - cat > /etc/limine-entry-tool.d/zz-dell-xps-panther-lake.conf <<'EOF' -# Prefer Omarchy kernels while keeping other kernels available for recovery -BOOT_ORDER="linux-omarchy-*, *, *fallback, Snapshots" -EOF -fi diff --git a/install/hardware/kernel.sh b/install/hardware/kernel.sh new file mode 100644 index 000000000000..ed259c66223c --- /dev/null +++ b/install/hardware/kernel.sh @@ -0,0 +1,9 @@ +# Install the default kernel before hardware setup pulls in DKMS modules. +# On a fresh T2 install linux-t2 is not installed yet, so also check the chip. +if [[ $(uname -m) == "x86_64" ]] && ! omarchy-pkg-present linux-t2; then + pci_devices=$(lspci -nn) + if ! grep "106b:180[12]" <<< "$pci_devices" >/dev/null; then + echo "Installing the Omarchy kernel..." + omarchy-pkg-add linux-omarchy linux-omarchy-headers + fi +fi diff --git a/install/hardware/nvidia.sh b/install/hardware/nvidia.sh index 81e1556e9e61..48f62cd4b15a 100644 --- a/install/hardware/nvidia.sh +++ b/install/hardware/nvidia.sh @@ -1,6 +1,6 @@ if lspci | grep -qi 'nvidia'; then # Check which kernel is installed and set appropriate headers package - KERNEL_PACKAGE=$(pacman -Qqs '^linux(-zen|-lts|-hardened|-t2|-ptl|-omarchy-ptl-novrr-mm)?$' | head -1 || true) + KERNEL_PACKAGE=$(pacman -Qqs '^linux(-zen|-lts|-hardened|-t2|-ptl|-omarchy(-bore|-ptl-novrr-mm)?)?$' | head -1 || true) [[ -n $KERNEL_PACKAGE ]] && omarchy-pkg-add "$KERNEL_PACKAGE-headers" if omarchy-hw-nvidia-gsp; then diff --git a/install/omarchy-other.packages b/install/omarchy-other.packages index 873e5048bf15..1f325b245e09 100644 --- a/install/omarchy-other.packages +++ b/install/omarchy-other.packages @@ -23,8 +23,8 @@ limine-snapper-sync linux linux-firmware linux-headers -linux-omarchy-ptl-novrr-mm -linux-omarchy-ptl-novrr-mm-headers +linux-omarchy +linux-omarchy-headers macbook12-spi-driver-dkms nvidia-580xx-dkms nvidia-dkms diff --git a/migrations/1789095456.sh b/migrations/1789095456.sh deleted file mode 100644 index 574d3d9ee192..000000000000 --- a/migrations/1789095456.sh +++ /dev/null @@ -1,45 +0,0 @@ -echo "Install the Omarchy Panther Lake kernel and prefer Omarchy kernels in Limine" - -omarchy-pkg-present linux-ptl || exit 0 - -limine_conf="${OMARCHY_PTL_LIMINE_CONF:-/etc/default/limine}" -limine_drop_ins="${OMARCHY_PTL_LIMINE_DROP_INS:-/etc/limine-entry-tool.d}" -rebuild_marker="${OMARCHY_PTL_REBUILD_MARKER:-/var/lib/omarchy/migrations/1789095456}" -kernel="linux-omarchy-ptl-novrr-mm" - -# Completion is machine-wide even though migrations run once per user. Leave -# the old kernel installed so it remains available if the new one cannot boot. -[[ ! -e $rebuild_marker ]] || exit 0 -omarchy-pkg-add "$kernel" "$kernel-headers" - -# /etc/default/limine and the Dell drop-ins were written by the installer. -# omarchy-settings ships omarchy-defaults.conf, but pacman's backup protection -# can leave its update in a .pacnew when other settings were customized. Repair -# only the old boot order in the active files, preserving custom orders and -# unrelated settings, including the root filesystem's kernel command line. -for conf in "$limine_conf" \ - "$limine_drop_ins/omarchy-defaults.conf" \ - "$limine_drop_ins/dell-xps-panther-lake.conf" \ - "$limine_drop_ins/zz-dell-xps-panther-lake.conf"; do - if [[ -f $conf ]]; then - sudo sed -i -E \ - 's/^([[:space:]]*BOOT_ORDER=)"(\*|linux-ptl\*), \*fallback, Snapshots"([[:space:]]*(#.*)?)$/\1"linux-omarchy-*, *, *fallback, Snapshots"\3/' \ - "$conf" - fi -done - -# Package hooks ran before the config repair. Rebuild the new kernel's image -# and boot entry explicitly, including on retries after a failed rebuild. -sudo limine-mkinitcpio "$kernel" - -# limine-mkinitcpio can return success after skipping a failed kernel build. -# Do not mark the migration complete unless the new kernel is in the menu. -if ! sudo limine-entry-tool --tree | grep -F "$kernel" >/dev/null; then - echo "The new Panther Lake kernel has no Limine boot entry; rerun omarchy-migrate after fixing the boot image build." >&2 - exit 1 -fi - -# Keeping the running kernel installed prevents the updater from detecting a -# kernel replacement, so request the reboot explicitly. -omarchy-state set reboot-required -sudo install -Dm644 /dev/null "$rebuild_marker" diff --git a/migrations/1789325478.sh b/migrations/1789325478.sh new file mode 100644 index 000000000000..14ba7d98b303 --- /dev/null +++ b/migrations/1789325478.sh @@ -0,0 +1,44 @@ +echo "Install the Omarchy kernel and make it the first Limine boot entry" + +# linux-omarchy is an x86_64 kernel. T2 Macs must keep their specialized kernel, +# including when other kernels are installed or the running T2 package is gone. +[[ $(uname -m) == "x86_64" ]] || exit 0 +running_kernel=$(uname -r) +if omarchy-pkg-present linux-t2 || [[ ${running_kernel,,} == *-t2* ]]; then + exit 0 +fi + +limine_conf="${OMARCHY_KERNEL_LIMINE_CONF:-/etc/default/limine}" +rebuild_marker="${OMARCHY_KERNEL_REBUILD_MARKER:-/var/lib/omarchy/migrations/1789325478}" +kernel="linux-omarchy" + +# Completion is machine-wide even though migrations run once per user. Leave +# the old kernel installed so it remains available if the new one cannot boot. +# The new filename and marker also reach users who completed 1789095456. +[[ ! -e $rebuild_marker ]] || exit 0 +omarchy-pkg-add "$kernel" "$kernel-headers" + +# /etc/default/limine has priority over every drop-in, including old Dell +# settings and customized package files whose updates landed in a .pacnew. +# Set the exact kernel first: linux-omarchy-* only matches its older variants. +# Preserve unrelated settings, especially the root filesystem's kernel cmdline. +sudo mkdir -p "$(dirname "$limine_conf")" +sudo touch "$limine_conf" +sudo sed -i -E '/^[[:space:]]*BOOT_ORDER[[:space:]]*=/d' "$limine_conf" +printf '\n%s\n' 'BOOT_ORDER="linux-omarchy, linux-omarchy-*, *, *fallback, Snapshots"' | sudo tee -a "$limine_conf" >/dev/null + +# Package hooks ran before the config repair. Rebuild the new kernel's image +# and boot entry explicitly, including on retries after a failed rebuild. +sudo limine-mkinitcpio "$kernel" + +# limine-mkinitcpio can return success after skipping a failed kernel build. +# Do not mark the migration complete unless the new kernel is in the menu. +if ! sudo limine-entry-tool --tree | grep -E "(^|[^[:alnum:]_-])$kernel([^[:alnum:]_-]|$)" >/dev/null; then + echo "The Omarchy kernel has no Limine boot entry; rerun omarchy-migrate after fixing the boot image build." >&2 + exit 1 +fi + +# Keeping the running kernel installed prevents the updater from detecting a +# kernel replacement, so request the reboot explicitly. +omarchy-state set reboot-required +sudo install -Dm644 /dev/null "$rebuild_marker" diff --git a/test/shell.d/limine-defaults-test.sh b/test/shell.d/limine-defaults-test.sh index cf93ebdfa198..21adc94fc990 100644 --- a/test/shell.d/limine-defaults-test.sh +++ b/test/shell.d/limine-defaults-test.sh @@ -10,6 +10,6 @@ grep -Fq 'KERNEL_CMDLINE[default]+=" initramfs_async=0"' "$packaged_defaults" || fail "the packaged Limine defaults still unpack the initramfs synchronously" pass "packaged Limine defaults keep Plymouth alive at the LUKS prompt" -grep -Fxq 'BOOT_ORDER="linux-omarchy-*, *, *fallback, Snapshots"' "$packaged_defaults" || - fail "packaged Limine defaults prefer Omarchy kernels and retain recovery entries" -pass "packaged Limine defaults prefer Omarchy kernels and retain recovery entries" +grep -Fxq 'BOOT_ORDER="linux-t2, linux-omarchy, linux-omarchy-*, *, *fallback, Snapshots"' "$packaged_defaults" || + fail "packaged Limine defaults protect T2 Macs and prefer the exact Omarchy kernel elsewhere" +pass "packaged Limine defaults protect T2 Macs and prefer the exact Omarchy kernel elsewhere" diff --git a/test/shell.d/omarchy-kernel-install-test.sh b/test/shell.d/omarchy-kernel-install-test.sh new file mode 100644 index 000000000000..cee20d9c88a7 --- /dev/null +++ b/test/shell.d/omarchy-kernel-install-test.sh @@ -0,0 +1,84 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +leaf="$ROOT/install/hardware/kernel.sh" +scratch=$(mktemp -d) +trap 'rm -rf "$scratch"' EXIT +mkdir -p "$scratch/bin" +export PATH="$scratch/bin:$PATH" CALL_LOG="$scratch/calls" + +cat > "$scratch/bin/uname" <<'SH' +#!/bin/bash +[[ $* == "-m" ]] || exit 99 +printf '%s\n' "${TEST_ARCH:-x86_64}" +SH + +cat > "$scratch/bin/omarchy-pkg-present" <<'SH' +#!/bin/bash +[[ $* == "linux-t2" ]] || exit 99 +[[ ${T2_INSTALLED:-0} == "1" ]] +SH + +cat > "$scratch/bin/lspci" <<'SH' +#!/bin/bash +[[ $* == "-nn" ]] || exit 99 +[[ ${PCI_FAIL:-0} == "0" ]] || exit 1 +printf '%s\n' "${PCI_DEVICES:-00:02.0 VGA compatible controller: Intel [8086:1234]}" +SH + +cat > "$scratch/bin/omarchy-pkg-add" <<'SH' +#!/bin/bash +printf 'add %s\n' "$*" >> "$CALL_LOG" +[[ ${INSTALL_FAIL:-0} == "0" ]] +SH +chmod +x "$scratch/bin/"* + +run_leaf() { + : > "$CALL_LOG" + bash -euo pipefail "$leaf" > "$scratch/output" 2>&1 +} + +run_leaf +grep -Fxq 'add linux-omarchy linux-omarchy-headers' "$CALL_LOG" || fail "ordinary systems install the generic kernel and headers" +pass "ordinary x86_64 installs receive the Omarchy kernel without a Panther Lake hardware gate" + +T2_INSTALLED=1 run_leaf +[[ ! -s $CALL_LOG ]] || fail "an installed T2 kernel excludes the system" +pass "hardware setup skips systems with linux-t2 installed" + +for device in 1801 1802; do + PCI_DEVICES="04:00.0 Mass storage controller: Apple Inc. T2 [106b:$device]" run_leaf + [[ ! -s $CALL_LOG ]] || fail "fresh T2 hardware must not install the generic kernel" +done +pass "fresh T2 hardware is excluded before its specialized kernel has been installed" + +TEST_ARCH=aarch64 run_leaf +[[ ! -s $CALL_LOG ]] || fail "ARM hardware cannot install an x86_64 kernel" +pass "ARM hardware is excluded" + +if PCI_FAIL=1 run_leaf; then + fail "failed T2 hardware detection must stop kernel setup" +fi +[[ ! -s $CALL_LOG ]] || fail "unidentified hardware must not install the generic kernel" +pass "failed PCI detection prevents installing the generic kernel on unidentified hardware" + +if INSTALL_FAIL=1 run_leaf; then + fail "package installation failure must fail kernel setup" +fi +pass "kernel package installation failures stop hardware setup" + +kernel_line=$(grep -n 'hardware/kernel.sh' "$ROOT/install/hardware/all.sh" | cut -d: -f1) +for script in nvidia.sh intel/ipu7-camera.sh fix-elgato-camlink-4k.sh; do + driver_line=$(grep -n "hardware/$script" "$ROOT/install/hardware/all.sh" | cut -d: -f1) + (( kernel_line < driver_line )) || fail "the generic kernel is installed before $script pulls in DKMS drivers" +done +pass "kernel setup precedes NVIDIA, IPU7, and Cam Link DKMS setup" + +for package in linux-omarchy linux-omarchy-headers; do + grep -Fxq "$package" "$ROOT/install/omarchy-other.packages" || fail "the ISO includes $package" +done +! grep -q 'linux-omarchy-ptl-novrr-mm' "$ROOT/install/omarchy-other.packages" || fail "the ISO must not pull in the retired PTL variant" +pass "the ISO package list includes the generic kernel and headers" diff --git a/test/shell.d/omarchy-kernel-migration-test.sh b/test/shell.d/omarchy-kernel-migration-test.sh new file mode 100644 index 000000000000..24e3480b3aa9 --- /dev/null +++ b/test/shell.d/omarchy-kernel-migration-test.sh @@ -0,0 +1,248 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +migration="$ROOT/migrations/1789325478.sh" +scratch=$(mktemp -d) +trap 'rm -rf "$scratch"' EXIT +mkdir -p "$scratch/bin" "$scratch/drop-ins" + +export PATH="$scratch/bin:$ROOT/bin:$PATH" +export CALL_LOG="$scratch/calls" +export INSTALLED_PACKAGES="$scratch/packages" +export OMARCHY_KERNEL_LIMINE_CONF="$scratch/limine" +export OMARCHY_KERNEL_LIMINE_DROP_INS="$scratch/drop-ins" +export OMARCHY_KERNEL_REBUILD_MARKER="$scratch/state/1789325478" +kernel="linux-omarchy" +boot_order='BOOT_ORDER="linux-omarchy, linux-omarchy-*, *, *fallback, Snapshots"' + +# Exercise the real package helpers, including their post-install queries. +cat > "$scratch/bin/pacman" <<'SH' +#!/bin/bash +case "$1" in + -Q) grep -Fxq "$2" "$INSTALLED_PACKAGES" ;; + -S) + printf 'pacman %s\n' "$*" >> "$CALL_LOG" + [[ ${INSTALL_FAIL:-0} == "0" ]] || exit 1 + for arg in "$@"; do + [[ $arg == -* ]] || printf '%s\n' "$arg" >> "$INSTALLED_PACKAGES" + done + ;; + *) exit 99 ;; +esac +SH + +cat > "$scratch/bin/sudo" <<'SH' +#!/bin/bash +printf 'sudo %s\n' "$*" >> "$CALL_LOG" +case "$1" in + pacman | mkdir | touch | sed | tee | install | limine-mkinitcpio | limine-entry-tool) exec "$@" ;; + *) exit 99 ;; +esac +SH + +cat > "$scratch/bin/limine-mkinitcpio" <<'SH' +#!/bin/bash +[[ ${REBUILD_FAIL:-0} == "0" ]] +SH + +cat > "$scratch/bin/limine-entry-tool" <<'SH' +#!/bin/bash +[[ $* == "--tree" ]] || exit 99 +printf '%s\n' 'Omarchy' ' linux-ptl' ' linux-omarchy-ptl-novrr-mm' ' linux-omarchy-bore' ' linux-omarchy-fallback' ' Snapshots' +if [[ ${MISSING_ENTRY:-0} == "0" ]]; then + printf '%s\n' ' linux-omarchy' +fi +SH + +cat > "$scratch/bin/omarchy-state" <<'SH' +#!/bin/bash +[[ $* == "set reboot-required" ]] || exit 99 +printf 'state %s\n' "$*" >> "$CALL_LOG" +SH + +cat > "$scratch/bin/uname" <<'SH' +#!/bin/bash +case "$1" in + -m) printf '%s\n' "${TEST_ARCH:-x86_64}" ;; + -r) printf '%s\n' "${TEST_KERNEL_RELEASE:-7.2.5-arch1-1}" ;; + *) exit 99 ;; +esac +SH + +cat > "$scratch/bin/omarchy-notification-dismiss" <<'SH' +#!/bin/bash +exit 0 +SH +chmod +x "$scratch/bin/"* + +reset_fixture() { + : > "$CALL_LOG" + printf '%s\n' linux-ptl linux-ptl-headers > "$INSTALLED_PACKAGES" + rm -f "$OMARCHY_KERNEL_REBUILD_MARKER" "$OMARCHY_KERNEL_LIMINE_DROP_INS/"* + cat > "$OMARCHY_KERNEL_LIMINE_CONF" <<'CONF' +KERNEL_CMDLINE[default]="root=UUID=keep-me rw cryptdevice=UUID=keep-me:root" +BOOT_ORDER="*, *fallback, Snapshots" +ENABLE_UKI=yes +CONF + cp "$OMARCHY_KERNEL_LIMINE_CONF" "$scratch/original-limine" +} + +run_migration() { + bash -euo pipefail "$migration" > "$scratch/output" 2>&1 +} + +assert_preferred() { + grep -Fxq "$boot_order" "$1" || fail "Omarchy kernels are preferred in $1" +} + +assert_skipped() { + [[ ! -s $CALL_LOG ]] || fail "excluded systems do not change" "$(<"$CALL_LOG")" + cmp -s "$OMARCHY_KERNEL_LIMINE_CONF" "$scratch/original-limine" || fail "excluded systems keep their boot settings" + [[ ! -e $OMARCHY_KERNEL_REBUILD_MARKER ]] || fail "excluded systems do not get a completion marker" +} + +for old_kernel in linux linux-lts linux-zen linux-ptl linux-omarchy-ptl-novrr-mm; do + reset_fixture + printf '%s\n' "$old_kernel" "$old_kernel-headers" > "$INSTALLED_PACKAGES" + run_migration + grep -Fxq "$kernel" "$INSTALLED_PACKAGES" || fail "the generic kernel is installed" + grep -Fxq "$kernel-headers" "$INSTALLED_PACKAGES" || fail "its headers are installed" + grep -Fxq "$old_kernel" "$INSTALLED_PACKAGES" || fail "the previous kernel remains available" + assert_preferred "$OMARCHY_KERNEL_LIMINE_CONF" + pass "$old_kernel systems receive the generic Omarchy kernel and retain their recovery kernel" +done + +for installed in linux-t2 $'linux-t2\nlinux\nlinux-ptl\nlinux-omarchy'; do + reset_fixture + printf '%s\n' "$installed" > "$INSTALLED_PACKAGES" + run_migration + assert_skipped +done +pass "linux-t2 systems are skipped even with other kernels installed" + +reset_fixture +TEST_KERNEL_RELEASE=7.2.5-arch1-T2 run_migration +assert_skipped +pass "a running T2 kernel is excluded even if its package is no longer installed" + +reset_fixture +TEST_ARCH=aarch64 run_migration +assert_skipped +pass "ARM systems cannot receive an x86_64 kernel" + +reset_fixture +printf '%s\n' linux-omarchy-ptl-novrr-mm > "$INSTALLED_PACKAGES" +mkdir -p "$scratch/state" "$scratch/user-markers" "$scratch/omarchy/migrations" +export OMARCHY_PTL_REBUILD_MARKER="$scratch/state/1789095456" +export OMARCHY_MIGRATION_STATE="$scratch/user-markers" +touch "$OMARCHY_PTL_REBUILD_MARKER" "$OMARCHY_MIGRATION_STATE/1789095456.sh" +cp "$migration" "$scratch/omarchy/migrations/" +[[ ! -e $ROOT/migrations/1789095456.sh ]] || fail "the superseded migration must not install the PTL variant first" +pending=$(OMARCHY_PATH="$scratch/omarchy" "$ROOT/bin/omarchy-migrate" --pending) +[[ $pending == "1789325478.sh" ]] || fail "the renamed migration is pending after completing the old migration" +OMARCHY_PATH="$scratch/omarchy" "$ROOT/bin/omarchy-migrate" > "$scratch/output" 2>&1 +grep -Fxq "$kernel" "$INSTALLED_PACKAGES" || fail "the old completion markers cannot skip the generic kernel" +[[ -f $OMARCHY_KERNEL_REBUILD_MARKER && -f $OMARCHY_MIGRATION_STATE/1789325478.sh ]] || fail "new machine and user completion markers are recorded" +assert_preferred "$OMARCHY_KERNEL_LIMINE_CONF" +pass "users who completed the PTL migration run the renamed migration with fresh completion markers" + +reset_fixture +for name in dell-xps-panther-lake zz-dell-xps-panther-lake; do + printf '%s\n' 'BOOT_ORDER="linux-ptl*, *fallback, Snapshots"' > "$OMARCHY_KERNEL_LIMINE_DROP_INS/$name.conf" +done +cp "$OMARCHY_KERNEL_LIMINE_CONF" "$OMARCHY_KERNEL_LIMINE_DROP_INS/omarchy-defaults.conf" +run_migration +grep -Fxq "pacman -S --noconfirm --needed $kernel $kernel-headers" "$CALL_LOG" || fail "both new packages are installed" +grep -Fxq linux-ptl "$INSTALLED_PACKAGES" || fail "the old kernel is kept for recovery" +grep -Fxq linux-ptl-headers "$INSTALLED_PACKAGES" || fail "the old kernel headers are kept" +assert_preferred "$OMARCHY_KERNEL_LIMINE_CONF" +diff -u <(sed '/^BOOT_ORDER=/d; /^$/d' "$scratch/original-limine") \ + <(sed '/^BOOT_ORDER=/d; /^$/d' "$OMARCHY_KERNEL_LIMINE_CONF") || fail "kernel command line and unrelated settings are preserved" +grep -Fxq "sudo limine-mkinitcpio $kernel" "$CALL_LOG" || fail "the new kernel's boot image is rebuilt" +[[ -f $OMARCHY_KERNEL_REBUILD_MARKER ]] || fail "successful completion is recorded" +grep -Fxq 'state set reboot-required' "$CALL_LOG" || fail "the updater must offer a reboot when retaining the old kernel" +pass "new packages install, the central boot order is set, and the old kernel remains available" + +: > "$CALL_LOG" +run_migration +[[ ! -s $CALL_LOG ]] || fail "another user's run does not repeat the machine-wide migration" +pass "repeat runs are a no-op after successful completion" + +reset_fixture +printf '%s\n' "$kernel" >> "$INSTALLED_PACKAGES" +run_migration +grep -Fxq "$kernel-headers" "$INSTALLED_PACKAGES" || fail "missing headers install when the kernel is already present" +pass "a partially installed kernel gets its missing headers" + +reset_fixture +printf '%s\n' "$kernel" "$kernel-headers" >> "$INSTALLED_PACKAGES" +run_migration +! grep -q '^pacman -S' "$CALL_LOG" || fail "already installed packages are not reinstalled" +assert_preferred "$OMARCHY_KERNEL_LIMINE_CONF" +pass "existing new packages still receive the config repair and boot rebuild" + +reset_fixture +if INSTALL_FAIL=1 run_migration; then + fail "package installation failure must fail the migration" +fi +cmp -s "$OMARCHY_KERNEL_LIMINE_CONF" "$scratch/original-limine" || fail "install failure leaves the config untouched" +! grep -q 'limine-mkinitcpio' "$CALL_LOG" || fail "install failure does not rebuild" +[[ ! -e $OMARCHY_KERNEL_REBUILD_MARKER ]] || fail "install failure stays pending" +pass "package failures leave the old boot setup intact and the migration pending" + +reset_fixture +if REBUILD_FAIL=1 run_migration; then + fail "boot rebuild failure must fail the migration" +fi +[[ ! -e $OMARCHY_KERNEL_REBUILD_MARKER ]] || fail "rebuild failure stays pending" +! grep -q '^state ' "$CALL_LOG" || fail "rebuild failure must not request a reboot" +assert_preferred "$OMARCHY_KERNEL_LIMINE_CONF" +: > "$CALL_LOG" +run_migration +grep -Fxq "sudo limine-mkinitcpio $kernel" "$CALL_LOG" || fail "retry must rebuild even after config and packages are repaired" +[[ -f $OMARCHY_KERNEL_REBUILD_MARKER ]] || fail "retry records successful completion" +pass "a failed rebuild is retried even after config and package changes succeeded" + +reset_fixture +if MISSING_ENTRY=1 run_migration; then + fail "a silently skipped kernel build must fail the migration" +fi +[[ ! -e $OMARCHY_KERNEL_REBUILD_MARKER ]] || fail "a missing boot entry stays pending" +! grep -q '^state ' "$CALL_LOG" || fail "a missing boot entry must not request a reboot" +run_migration +[[ -f $OMARCHY_KERNEL_REBUILD_MARKER ]] || fail "a missing boot entry can be repaired on retry" +pass "older Omarchy variants and fallback entries cannot satisfy generic kernel verification" + +reset_fixture +cat >> "$OMARCHY_KERNEL_LIMINE_CONF" <<'CONF' +BOOT_ORDER="linux-omarchy-*, *, *fallback, Snapshots" + BOOT_ORDER = 'linux-lts, *, *fallback, Snapshots' +CONF +run_migration +assert_preferred "$OMARCHY_KERNEL_LIMINE_CONF" +[[ $(grep -c '^BOOT_ORDER=' "$OMARCHY_KERNEL_LIMINE_CONF") == "1" ]] || fail "only one boot order is written" +! grep -Eq '^[[:space:]]+BOOT_ORDER' "$OMARCHY_KERNEL_LIMINE_CONF" || fail "a later custom assignment cannot override first position" +pass "the exact generic kernel takes first position over previous PTL and custom orders" + +reset_fixture +for name in omarchy-defaults dell-xps-panther-lake zz-dell-xps-panther-lake; do + printf '%s\n' 'BOOT_ORDER="linux-ptl*, *fallback, Snapshots"' > "$OMARCHY_KERNEL_LIMINE_DROP_INS/$name.conf" +done +printf '%s\n' 'ENABLE_SORT=yes' >> "$OMARCHY_KERNEL_LIMINE_DROP_INS/omarchy-defaults.conf" +cp "$ROOT/etc/limine-entry-tool.d/omarchy-defaults.conf" "$OMARCHY_KERNEL_LIMINE_DROP_INS/omarchy-defaults.conf.pacnew" +run_migration +effective_order=$(bash -c 'declare -A KERNEL_CMDLINE; for conf in "$1/"*.conf "$2"; do source "$conf"; done; printf "%s" "$BOOT_ORDER"' -- "$OMARCHY_KERNEL_LIMINE_DROP_INS" "$OMARCHY_KERNEL_LIMINE_CONF") +[[ $effective_order == "linux-omarchy, linux-omarchy-*, *, *fallback, Snapshots" ]] || fail "the central config wins over old and customized drop-ins" +grep -Fxq 'ENABLE_SORT=yes' "$OMARCHY_KERNEL_LIMINE_DROP_INS/omarchy-defaults.conf" || fail "custom packaged settings survive" +cmp -s "$ROOT/etc/limine-entry-tool.d/omarchy-defaults.conf" \ + "$OMARCHY_KERNEL_LIMINE_DROP_INS/omarchy-defaults.conf.pacnew" || fail "the pacnew is left for the administrator to merge" +pass "the central boot order overrides legacy drop-ins and pacnew files without rewriting them" + +reset_fixture +rm "$OMARCHY_KERNEL_LIMINE_CONF" +run_migration +assert_preferred "$OMARCHY_KERNEL_LIMINE_CONF" +pass "a missing central config is created with the exact kernel first" diff --git a/test/shell.d/ptl-kernel-migration-test.sh b/test/shell.d/ptl-kernel-migration-test.sh deleted file mode 100644 index 874397c03815..000000000000 --- a/test/shell.d/ptl-kernel-migration-test.sh +++ /dev/null @@ -1,195 +0,0 @@ -#!/bin/bash - -set -euo pipefail - -source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" - -migration="$ROOT/migrations/1789095456.sh" -scratch=$(mktemp -d) -trap 'rm -rf "$scratch"' EXIT -mkdir -p "$scratch/bin" "$scratch/drop-ins" - -export PATH="$scratch/bin:$ROOT/bin:$PATH" -export CALL_LOG="$scratch/calls" -export INSTALLED_PACKAGES="$scratch/packages" -export OMARCHY_PTL_LIMINE_CONF="$scratch/limine" -export OMARCHY_PTL_LIMINE_DROP_INS="$scratch/drop-ins" -export OMARCHY_PTL_REBUILD_MARKER="$scratch/state/completed" -kernel="linux-omarchy-ptl-novrr-mm" -boot_order='BOOT_ORDER="linux-omarchy-*, *, *fallback, Snapshots"' - -# Exercise the real package helpers, including their post-install queries. -cat > "$scratch/bin/pacman" <<'SH' -#!/bin/bash -case "$1" in - -Q) grep -Fxq "$2" "$INSTALLED_PACKAGES" ;; - -S) - printf 'pacman %s\n' "$*" >> "$CALL_LOG" - [[ ${INSTALL_FAIL:-0} == "0" ]] || exit 1 - for arg in "$@"; do - [[ $arg == -* ]] || printf '%s\n' "$arg" >> "$INSTALLED_PACKAGES" - done - ;; - *) exit 99 ;; -esac -SH - -cat > "$scratch/bin/sudo" <<'SH' -#!/bin/bash -printf 'sudo %s\n' "$*" >> "$CALL_LOG" -case "$1" in - pacman | sed | install | limine-mkinitcpio | limine-entry-tool) exec "$@" ;; - *) exit 99 ;; -esac -SH - -cat > "$scratch/bin/limine-mkinitcpio" <<'SH' -#!/bin/bash -[[ ${REBUILD_FAIL:-0} == "0" ]] -SH - -cat > "$scratch/bin/limine-entry-tool" <<'SH' -#!/bin/bash -[[ $* == "--tree" ]] || exit 99 -printf '%s\n' 'Omarchy' ' linux-ptl' ' Snapshots' -if [[ ${MISSING_ENTRY:-0} == "0" ]]; then - printf '%s\n' ' linux-omarchy-ptl-novrr-mm' -fi -SH - -cat > "$scratch/bin/omarchy-state" <<'SH' -#!/bin/bash -[[ $* == "set reboot-required" ]] || exit 99 -printf 'state %s\n' "$*" >> "$CALL_LOG" -SH -chmod +x "$scratch/bin/"* - -reset_fixture() { - : > "$CALL_LOG" - printf '%s\n' linux-ptl linux-ptl-headers > "$INSTALLED_PACKAGES" - rm -f "$OMARCHY_PTL_REBUILD_MARKER" "$OMARCHY_PTL_LIMINE_DROP_INS/"*.conf - cat > "$OMARCHY_PTL_LIMINE_CONF" <<'CONF' -KERNEL_CMDLINE[default]="root=UUID=keep-me rw cryptdevice=UUID=keep-me:root" -BOOT_ORDER="*, *fallback, Snapshots" -ENABLE_UKI=yes -CONF - cp "$OMARCHY_PTL_LIMINE_CONF" "$scratch/original-limine" -} - -run_migration() { - bash -euo pipefail "$migration" > "$scratch/output" 2>&1 -} - -assert_preferred() { - grep -Fxq "$boot_order" "$1" || fail "Omarchy kernels are preferred in $1" -} - -reset_fixture -printf '%s\n' linux > "$INSTALLED_PACKAGES" -run_migration -[[ ! -s $CALL_LOG ]] || fail "systems without linux-ptl do not change" -cmp -s "$OMARCHY_PTL_LIMINE_CONF" "$scratch/original-limine" || fail "unaffected Limine settings stay unchanged" -[[ ! -e $OMARCHY_PTL_REBUILD_MARKER ]] || fail "unaffected systems do not get a completion marker" -pass "systems without linux-ptl are skipped" - -reset_fixture -for name in dell-xps-panther-lake zz-dell-xps-panther-lake; do - printf '%s\n' 'BOOT_ORDER="linux-ptl*, *fallback, Snapshots"' > "$OMARCHY_PTL_LIMINE_DROP_INS/$name.conf" -done -cp "$OMARCHY_PTL_LIMINE_CONF" "$OMARCHY_PTL_LIMINE_DROP_INS/omarchy-defaults.conf" -run_migration -grep -Fxq "pacman -S --noconfirm --needed $kernel $kernel-headers" "$CALL_LOG" || fail "both new packages are installed" -grep -Fxq linux-ptl "$INSTALLED_PACKAGES" || fail "the old kernel is kept for recovery" -grep -Fxq linux-ptl-headers "$INSTALLED_PACKAGES" || fail "the old kernel headers are kept" -assert_preferred "$OMARCHY_PTL_LIMINE_CONF" -for conf in "$OMARCHY_PTL_LIMINE_DROP_INS/"*.conf; do - assert_preferred "$conf" -done -diff -u <(sed '/^BOOT_ORDER=/d' "$scratch/original-limine") \ - <(sed '/^BOOT_ORDER=/d' "$OMARCHY_PTL_LIMINE_CONF") || fail "kernel command line and unrelated settings are preserved" -grep -Fxq "sudo limine-mkinitcpio $kernel" "$CALL_LOG" || fail "the new kernel's boot image is rebuilt" -[[ -f $OMARCHY_PTL_REBUILD_MARKER ]] || fail "successful completion is recorded" -grep -Fxq 'state set reboot-required' "$CALL_LOG" || fail "the updater must offer a reboot when retaining the old kernel" -pass "new packages install, all stock boot orders are repaired, and the old kernel remains available" - -: > "$CALL_LOG" -run_migration -[[ ! -s $CALL_LOG ]] || fail "another user's run does not repeat the machine-wide migration" -pass "repeat runs are a no-op after successful completion" - -reset_fixture -printf '%s\n' "$kernel" >> "$INSTALLED_PACKAGES" -run_migration -grep -Fxq "$kernel-headers" "$INSTALLED_PACKAGES" || fail "missing headers install when the kernel is already present" -pass "a partially installed kernel gets its missing headers" - -reset_fixture -printf '%s\n' "$kernel" "$kernel-headers" >> "$INSTALLED_PACKAGES" -run_migration -! grep -q '^pacman -S' "$CALL_LOG" || fail "already installed packages are not reinstalled" -assert_preferred "$OMARCHY_PTL_LIMINE_CONF" -pass "existing new packages still receive the config repair and boot rebuild" - -reset_fixture -if INSTALL_FAIL=1 run_migration; then - fail "package installation failure must fail the migration" -fi -cmp -s "$OMARCHY_PTL_LIMINE_CONF" "$scratch/original-limine" || fail "install failure leaves the config untouched" -! grep -q 'limine-mkinitcpio' "$CALL_LOG" || fail "install failure does not rebuild" -[[ ! -e $OMARCHY_PTL_REBUILD_MARKER ]] || fail "install failure stays pending" -pass "package failures leave the old boot setup intact and the migration pending" - -reset_fixture -if REBUILD_FAIL=1 run_migration; then - fail "boot rebuild failure must fail the migration" -fi -[[ ! -e $OMARCHY_PTL_REBUILD_MARKER ]] || fail "rebuild failure stays pending" -! grep -q '^state ' "$CALL_LOG" || fail "rebuild failure must not request a reboot" -assert_preferred "$OMARCHY_PTL_LIMINE_CONF" -: > "$CALL_LOG" -run_migration -grep -Fxq "sudo limine-mkinitcpio $kernel" "$CALL_LOG" || fail "retry must rebuild even after config and packages are repaired" -[[ -f $OMARCHY_PTL_REBUILD_MARKER ]] || fail "retry records successful completion" -pass "a failed rebuild is retried even after config and package changes succeeded" - -reset_fixture -if MISSING_ENTRY=1 run_migration; then - fail "a silently skipped kernel build must fail the migration" -fi -[[ ! -e $OMARCHY_PTL_REBUILD_MARKER ]] || fail "a missing boot entry stays pending" -! grep -q '^state ' "$CALL_LOG" || fail "a missing boot entry must not request a reboot" -run_migration -[[ -f $OMARCHY_PTL_REBUILD_MARKER ]] || fail "a missing boot entry can be repaired on retry" -pass "a successful command without a new boot entry cannot complete the migration" - -reset_fixture -printf '%s\n' 'BOOT_ORDER="linux-lts, *, *fallback, Snapshots"' > "$OMARCHY_PTL_LIMINE_CONF" -cp "$OMARCHY_PTL_LIMINE_CONF" "$scratch/custom-limine" -run_migration -cmp -s "$OMARCHY_PTL_LIMINE_CONF" "$scratch/custom-limine" || fail "custom boot orders stay unchanged" -pass "administrator-defined boot orders are preserved" - -reset_fixture -cp "$OMARCHY_PTL_LIMINE_CONF" "$OMARCHY_PTL_LIMINE_DROP_INS/omarchy-defaults.conf" -printf '%s\n' 'ENABLE_SORT=yes' >> "$OMARCHY_PTL_LIMINE_DROP_INS/omarchy-defaults.conf" -cp "$ROOT/etc/limine-entry-tool.d/omarchy-defaults.conf" "$OMARCHY_PTL_LIMINE_DROP_INS/omarchy-defaults.conf.pacnew" -run_migration -assert_preferred "$OMARCHY_PTL_LIMINE_DROP_INS/omarchy-defaults.conf" -grep -Fxq 'ENABLE_SORT=yes' "$OMARCHY_PTL_LIMINE_DROP_INS/omarchy-defaults.conf" || fail "custom packaged settings survive the repair" -cmp -s "$ROOT/etc/limine-entry-tool.d/omarchy-defaults.conf" \ - "$OMARCHY_PTL_LIMINE_DROP_INS/omarchy-defaults.conf.pacnew" || fail "the pending pacnew is left for the administrator to merge" -pass "active packaged defaults are repaired when customized settings leave the update in a pacnew" - -reset_fixture -printf '%s\n' ' BOOT_ORDER="*, *fallback, Snapshots" # keep this comment' > "$OMARCHY_PTL_LIMINE_CONF" -run_migration -grep -Fxq " $boot_order # keep this comment" "$OMARCHY_PTL_LIMINE_CONF" || fail "stock orders with comments are repaired" -pass "indentation and comments survive the repair" - -reset_fixture -rm "$OMARCHY_PTL_LIMINE_CONF" -cp "$ROOT/etc/limine-entry-tool.d/omarchy-defaults.conf" "$OMARCHY_PTL_LIMINE_DROP_INS/omarchy-defaults.conf" -run_migration -[[ ! -e $OMARCHY_PTL_LIMINE_CONF ]] || fail "missing central config is not fabricated" -assert_preferred "$OMARCHY_PTL_LIMINE_DROP_INS/omarchy-defaults.conf" -pass "installs without a central config inherit the packaged boot order" diff --git a/test/shell.d/xps13-sidecar-amps-test.sh b/test/shell.d/xps13-sidecar-amps-test.sh index d82498f94d09..b7935fb23bc0 100755 --- a/test/shell.d/xps13-sidecar-amps-test.sh +++ b/test/shell.d/xps13-sidecar-amps-test.sh @@ -13,13 +13,12 @@ grep -q 'run_logged .*hardware/dell-xps13-sidecar-amps.sh' "$all" || fail "the sidecar amplifier workaround runs during hardware setup" pass "the sidecar amplifier workaround runs during hardware setup" -# The apply step rebuilds the boot image, so it has to see the Panther Lake -# kernel that ptl-kernel.sh swaps in rather than the stock one it replaces. -ptl_line=$(grep -n 'hardware/intel/ptl-kernel.sh' "$all" | cut -d: -f1) +# The apply step rebuilds the boot image, so the default kernel must be installed. +kernel_line=$(grep -n 'hardware/kernel.sh' "$all" | cut -d: -f1) amps_line=$(grep -n 'hardware/dell-xps13-sidecar-amps.sh' "$all" | cut -d: -f1) -((ptl_line < amps_line)) || - fail "the sidecar amplifier workaround runs after the Panther Lake kernel swap" -pass "the sidecar amplifier workaround runs after the Panther Lake kernel swap" +((kernel_line < amps_line)) || + fail "the sidecar amplifier workaround runs after the default kernel is installed" +pass "the sidecar amplifier workaround runs after the default kernel is installed" [[ -n $migration ]] || fail "a migration enables the workaround on existing installs" pass "a migration enables the workaround on existing installs" From 08a875852e6233b973de5041dc04d8ccbdfbb69f Mon Sep 17 00:00:00 2001 From: Ryan Hughes Date: Mon, 14 Sep 2026 16:46:45 -0400 Subject: [PATCH 066/194] Leave fresh-install kernel selection to the ISO --- install/hardware/all.sh | 4 +- install/hardware/kernel.sh | 9 --- test/shell.d/omarchy-kernel-install-test.sh | 84 --------------------- test/shell.d/xps13-sidecar-amps-test.sh | 7 -- 4 files changed, 1 insertion(+), 103 deletions(-) delete mode 100644 install/hardware/kernel.sh delete mode 100644 test/shell.d/omarchy-kernel-install-test.sh diff --git a/install/hardware/all.sh b/install/hardware/all.sh index d40069b26936..12add110c51f 100644 --- a/install/hardware/all.sh +++ b/install/hardware/all.sh @@ -1,5 +1,3 @@ -run_logged "$OMARCHY_INSTALL/hardware/kernel.sh" - run_logged "$OMARCHY_INSTALL/hardware/asus-rog.sh" run_logged "$OMARCHY_INSTALL/hardware/framework16.sh" run_logged "$OMARCHY_INSTALL/hardware/dell-xps-touchpad-haptics.sh" @@ -23,7 +21,7 @@ run_logged "$OMARCHY_INSTALL/hardware/intel/sof-firmware.sh" run_logged "$OMARCHY_INSTALL/hardware/fix-elgato-camlink-4k.sh" -# Rebuilds the boot image, so it follows kernel and camera module setup. +# Rebuilds the boot image, so it follows camera module setup. run_logged "$OMARCHY_INSTALL/hardware/dell-xps13-sidecar-amps.sh" run_logged "$OMARCHY_INSTALL/hardware/asus/fix-asus-ptl-display-backlight.sh" diff --git a/install/hardware/kernel.sh b/install/hardware/kernel.sh deleted file mode 100644 index ed259c66223c..000000000000 --- a/install/hardware/kernel.sh +++ /dev/null @@ -1,9 +0,0 @@ -# Install the default kernel before hardware setup pulls in DKMS modules. -# On a fresh T2 install linux-t2 is not installed yet, so also check the chip. -if [[ $(uname -m) == "x86_64" ]] && ! omarchy-pkg-present linux-t2; then - pci_devices=$(lspci -nn) - if ! grep "106b:180[12]" <<< "$pci_devices" >/dev/null; then - echo "Installing the Omarchy kernel..." - omarchy-pkg-add linux-omarchy linux-omarchy-headers - fi -fi diff --git a/test/shell.d/omarchy-kernel-install-test.sh b/test/shell.d/omarchy-kernel-install-test.sh deleted file mode 100644 index cee20d9c88a7..000000000000 --- a/test/shell.d/omarchy-kernel-install-test.sh +++ /dev/null @@ -1,84 +0,0 @@ -#!/bin/bash - -set -euo pipefail - -source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" - -leaf="$ROOT/install/hardware/kernel.sh" -scratch=$(mktemp -d) -trap 'rm -rf "$scratch"' EXIT -mkdir -p "$scratch/bin" -export PATH="$scratch/bin:$PATH" CALL_LOG="$scratch/calls" - -cat > "$scratch/bin/uname" <<'SH' -#!/bin/bash -[[ $* == "-m" ]] || exit 99 -printf '%s\n' "${TEST_ARCH:-x86_64}" -SH - -cat > "$scratch/bin/omarchy-pkg-present" <<'SH' -#!/bin/bash -[[ $* == "linux-t2" ]] || exit 99 -[[ ${T2_INSTALLED:-0} == "1" ]] -SH - -cat > "$scratch/bin/lspci" <<'SH' -#!/bin/bash -[[ $* == "-nn" ]] || exit 99 -[[ ${PCI_FAIL:-0} == "0" ]] || exit 1 -printf '%s\n' "${PCI_DEVICES:-00:02.0 VGA compatible controller: Intel [8086:1234]}" -SH - -cat > "$scratch/bin/omarchy-pkg-add" <<'SH' -#!/bin/bash -printf 'add %s\n' "$*" >> "$CALL_LOG" -[[ ${INSTALL_FAIL:-0} == "0" ]] -SH -chmod +x "$scratch/bin/"* - -run_leaf() { - : > "$CALL_LOG" - bash -euo pipefail "$leaf" > "$scratch/output" 2>&1 -} - -run_leaf -grep -Fxq 'add linux-omarchy linux-omarchy-headers' "$CALL_LOG" || fail "ordinary systems install the generic kernel and headers" -pass "ordinary x86_64 installs receive the Omarchy kernel without a Panther Lake hardware gate" - -T2_INSTALLED=1 run_leaf -[[ ! -s $CALL_LOG ]] || fail "an installed T2 kernel excludes the system" -pass "hardware setup skips systems with linux-t2 installed" - -for device in 1801 1802; do - PCI_DEVICES="04:00.0 Mass storage controller: Apple Inc. T2 [106b:$device]" run_leaf - [[ ! -s $CALL_LOG ]] || fail "fresh T2 hardware must not install the generic kernel" -done -pass "fresh T2 hardware is excluded before its specialized kernel has been installed" - -TEST_ARCH=aarch64 run_leaf -[[ ! -s $CALL_LOG ]] || fail "ARM hardware cannot install an x86_64 kernel" -pass "ARM hardware is excluded" - -if PCI_FAIL=1 run_leaf; then - fail "failed T2 hardware detection must stop kernel setup" -fi -[[ ! -s $CALL_LOG ]] || fail "unidentified hardware must not install the generic kernel" -pass "failed PCI detection prevents installing the generic kernel on unidentified hardware" - -if INSTALL_FAIL=1 run_leaf; then - fail "package installation failure must fail kernel setup" -fi -pass "kernel package installation failures stop hardware setup" - -kernel_line=$(grep -n 'hardware/kernel.sh' "$ROOT/install/hardware/all.sh" | cut -d: -f1) -for script in nvidia.sh intel/ipu7-camera.sh fix-elgato-camlink-4k.sh; do - driver_line=$(grep -n "hardware/$script" "$ROOT/install/hardware/all.sh" | cut -d: -f1) - (( kernel_line < driver_line )) || fail "the generic kernel is installed before $script pulls in DKMS drivers" -done -pass "kernel setup precedes NVIDIA, IPU7, and Cam Link DKMS setup" - -for package in linux-omarchy linux-omarchy-headers; do - grep -Fxq "$package" "$ROOT/install/omarchy-other.packages" || fail "the ISO includes $package" -done -! grep -q 'linux-omarchy-ptl-novrr-mm' "$ROOT/install/omarchy-other.packages" || fail "the ISO must not pull in the retired PTL variant" -pass "the ISO package list includes the generic kernel and headers" diff --git a/test/shell.d/xps13-sidecar-amps-test.sh b/test/shell.d/xps13-sidecar-amps-test.sh index b7935fb23bc0..a8313a486833 100755 --- a/test/shell.d/xps13-sidecar-amps-test.sh +++ b/test/shell.d/xps13-sidecar-amps-test.sh @@ -13,13 +13,6 @@ grep -q 'run_logged .*hardware/dell-xps13-sidecar-amps.sh' "$all" || fail "the sidecar amplifier workaround runs during hardware setup" pass "the sidecar amplifier workaround runs during hardware setup" -# The apply step rebuilds the boot image, so the default kernel must be installed. -kernel_line=$(grep -n 'hardware/kernel.sh' "$all" | cut -d: -f1) -amps_line=$(grep -n 'hardware/dell-xps13-sidecar-amps.sh' "$all" | cut -d: -f1) -((kernel_line < amps_line)) || - fail "the sidecar amplifier workaround runs after the default kernel is installed" -pass "the sidecar amplifier workaround runs after the default kernel is installed" - [[ -n $migration ]] || fail "a migration enables the workaround on existing installs" pass "a migration enables the workaround on existing installs" From f464b6087dd4550ed153d940fccd38531a83425b Mon Sep 17 00:00:00 2001 From: Ryan Hughes Date: Mon, 14 Sep 2026 23:45:34 -0400 Subject: [PATCH 067/194] Use Omarchy kernel headers for hardware DKMS drivers --- install/hardware/fix-bcm43xx.sh | 2 +- install/hardware/fix-tuxedo-backlight.sh | 2 +- install/hardware/fix-yt6801-ethernet-adapter.sh | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/install/hardware/fix-bcm43xx.sh b/install/hardware/fix-bcm43xx.sh index 6b7e5648f1f0..94fd16e6e560 100644 --- a/install/hardware/fix-bcm43xx.sh +++ b/install/hardware/fix-bcm43xx.sh @@ -6,5 +6,5 @@ pci_info=$(lspci -nn) if (echo "$pci_info" | grep -q "14e4:43a0" || echo "$pci_info" | grep -q "14e4:4331"); then echo "BCM4360 / BCM4331 detected" - omarchy-pkg-add broadcom-wl-dkms linux-headers + omarchy-pkg-add broadcom-wl-dkms linux-omarchy-headers fi diff --git a/install/hardware/fix-tuxedo-backlight.sh b/install/hardware/fix-tuxedo-backlight.sh index 9644d310e612..a2d3b8c6145d 100644 --- a/install/hardware/fix-tuxedo-backlight.sh +++ b/install/hardware/fix-tuxedo-backlight.sh @@ -1,7 +1,7 @@ # Install Tuxedo drivers for keyboard backlighting on Tuxedo laptops and # compatible devices like the Slimbook Executive (Clevo/Tuxedo chassis). if cat /sys/class/dmi/id/sys_vendor 2>/dev/null | grep -qi "TUXEDO\|Slimbook"; then - omarchy-pkg-add linux-headers tuxedo-drivers-nocompatcheck-dkms + omarchy-pkg-add linux-omarchy-headers tuxedo-drivers-nocompatcheck-dkms # Blacklist the legacy clevo_xsm_wmi module which conflicts with the tuxedo-drivers # clevo_wmi module. When clevo_xsm_wmi loads first, it grabs the Clevo WMI GUIDs, diff --git a/install/hardware/fix-yt6801-ethernet-adapter.sh b/install/hardware/fix-yt6801-ethernet-adapter.sh index 34331a0fa883..7c0360e6bac8 100644 --- a/install/hardware/fix-yt6801-ethernet-adapter.sh +++ b/install/hardware/fix-yt6801-ethernet-adapter.sh @@ -1,4 +1,4 @@ # Install drivers for Motorcomm YT6801 ethernet adapter used by the Slimbook Executive if lspci | grep -i "YT6801\|Motorcomm.*Ethernet"; then - omarchy-pkg-add linux-headers yt6801-dkms + omarchy-pkg-add linux-omarchy-headers yt6801-dkms fi From 662051ecde66c5d4f9501df1e816ae5136a408cb Mon Sep 17 00:00:00 2001 From: Ryan Hughes Date: Tue, 15 Sep 2026 00:06:17 -0400 Subject: [PATCH 068/194] Install matching kernel headers for every DKMS setup --- bin/omarchy-install-gaming-xbox-controllers | 3 +- bin/omarchy-pkg-add-kernel-headers | 13 +++ install/hardware/apple/fix-spi-keyboard.sh | 1 + install/hardware/fix-bcm43xx.sh | 3 +- install/hardware/fix-elgato-camlink-4k.sh | 4 +- install/hardware/fix-tuxedo-backlight.sh | 3 +- .../hardware/fix-yt6801-ethernet-adapter.sh | 3 +- install/hardware/intel/ipu7-camera.sh | 1 + install/hardware/nvidia.sh | 5 +- install/omarchy-other.packages | 2 - migrations/1789444024.sh | 8 ++ test/acceptance.d/system-test.sh | 16 +++- test/shell.d/kernel-headers-test.sh | 89 +++++++++++++++++++ 13 files changed, 138 insertions(+), 13 deletions(-) create mode 100755 bin/omarchy-pkg-add-kernel-headers create mode 100644 migrations/1789444024.sh create mode 100755 test/shell.d/kernel-headers-test.sh diff --git a/bin/omarchy-install-gaming-xbox-controllers b/bin/omarchy-install-gaming-xbox-controllers index f4134f767fdf..8f7bdf28f8c1 100755 --- a/bin/omarchy-install-gaming-xbox-controllers +++ b/bin/omarchy-install-gaming-xbox-controllers @@ -10,7 +10,8 @@ set -e echo "Installing Xbox controller Bluetooth support..." # Install xpadneo to ensure controllers work out of the box -omarchy-pkg-add linux-headers xpadneo-dkms +omarchy-pkg-add-kernel-headers +omarchy-pkg-add xpadneo-dkms # Prevent xpad/xpadneo driver conflict echo blacklist xpad | sudo tee /etc/modprobe.d/blacklist-xpad.conf >/dev/null diff --git a/bin/omarchy-pkg-add-kernel-headers b/bin/omarchy-pkg-add-kernel-headers new file mode 100755 index 000000000000..28590b3626ca --- /dev/null +++ b/bin/omarchy-pkg-add-kernel-headers @@ -0,0 +1,13 @@ +#!/bin/bash + +# omarchy:summary=Install headers for the supported system kernel +# omarchy:hidden=true +# omarchy:requires-sudo=true + +# Inspect the target's packages: uname reports the live ISO kernel in a chroot. +# A retained stock kernel must not take precedence over the Omarchy kernel. +if omarchy-pkg-present linux-t2; then + omarchy-pkg-add linux-t2-headers +else + omarchy-pkg-add linux-omarchy-headers +fi diff --git a/install/hardware/apple/fix-spi-keyboard.sh b/install/hardware/apple/fix-spi-keyboard.sh index 330081b76318..fd5d8e45c656 100644 --- a/install/hardware/apple/fix-spi-keyboard.sh +++ b/install/hardware/apple/fix-spi-keyboard.sh @@ -3,6 +3,7 @@ product_name="$(cat /sys/class/dmi/id/product_name 2>/dev/null)" if [[ $product_name =~ MacBook[89],1|MacBook1[02],1|MacBookPro13,[123]|MacBookPro14,[123] ]]; then echo "Detected MacBook with SPI keyboard" + omarchy-pkg-add-kernel-headers omarchy-pkg-add macbook12-spi-driver-dkms sudo mkdir -p /etc/mkinitcpio.conf.d if [[ $product_name == "MacBook8,1" ]]; then diff --git a/install/hardware/fix-bcm43xx.sh b/install/hardware/fix-bcm43xx.sh index 94fd16e6e560..f829749e9c25 100644 --- a/install/hardware/fix-bcm43xx.sh +++ b/install/hardware/fix-bcm43xx.sh @@ -6,5 +6,6 @@ pci_info=$(lspci -nn) if (echo "$pci_info" | grep -q "14e4:43a0" || echo "$pci_info" | grep -q "14e4:4331"); then echo "BCM4360 / BCM4331 detected" - omarchy-pkg-add broadcom-wl-dkms linux-omarchy-headers + omarchy-pkg-add-kernel-headers + omarchy-pkg-add broadcom-wl-dkms fi diff --git a/install/hardware/fix-elgato-camlink-4k.sh b/install/hardware/fix-elgato-camlink-4k.sh index 274076cef57c..d12cbfe4fa8d 100644 --- a/install/hardware/fix-elgato-camlink-4k.sh +++ b/install/hardware/fix-elgato-camlink-4k.sh @@ -4,8 +4,8 @@ # v4l2-relayd re-exposes it at 1280x720 under the same name. if omarchy-hw-elgato-camlink-4k; then - mapfile -t kernel_headers < <(pacman -Qqs '^linux(-zen|-lts|-hardened|-t2|-ptl|-omarchy(-bore|-ptl-novrr-mm)?)?$' | sed 's/$/-headers/') - omarchy-pkg-add "${kernel_headers[@]}" v4l2loopback-dkms v4l2loopback-utils v4l2-relayd + omarchy-pkg-add-kernel-headers + omarchy-pkg-add v4l2loopback-dkms v4l2loopback-utils v4l2-relayd sudo install -Dm644 "$OMARCHY_PATH/default/udev/elgato-camlink-4k.rules" /etc/udev/rules.d/71-elgato-camlink-4k.rules sudo install -Dm644 "$OMARCHY_PATH/default/v4l2-relayd/camlink.conf" /etc/v4l2-relayd.d/camlink.conf diff --git a/install/hardware/fix-tuxedo-backlight.sh b/install/hardware/fix-tuxedo-backlight.sh index a2d3b8c6145d..c40fadb8268e 100644 --- a/install/hardware/fix-tuxedo-backlight.sh +++ b/install/hardware/fix-tuxedo-backlight.sh @@ -1,7 +1,8 @@ # Install Tuxedo drivers for keyboard backlighting on Tuxedo laptops and # compatible devices like the Slimbook Executive (Clevo/Tuxedo chassis). if cat /sys/class/dmi/id/sys_vendor 2>/dev/null | grep -qi "TUXEDO\|Slimbook"; then - omarchy-pkg-add linux-omarchy-headers tuxedo-drivers-nocompatcheck-dkms + omarchy-pkg-add-kernel-headers + omarchy-pkg-add tuxedo-drivers-nocompatcheck-dkms # Blacklist the legacy clevo_xsm_wmi module which conflicts with the tuxedo-drivers # clevo_wmi module. When clevo_xsm_wmi loads first, it grabs the Clevo WMI GUIDs, diff --git a/install/hardware/fix-yt6801-ethernet-adapter.sh b/install/hardware/fix-yt6801-ethernet-adapter.sh index 7c0360e6bac8..e20cb92ee402 100644 --- a/install/hardware/fix-yt6801-ethernet-adapter.sh +++ b/install/hardware/fix-yt6801-ethernet-adapter.sh @@ -1,4 +1,5 @@ # Install drivers for Motorcomm YT6801 ethernet adapter used by the Slimbook Executive if lspci | grep -i "YT6801\|Motorcomm.*Ethernet"; then - omarchy-pkg-add linux-omarchy-headers yt6801-dkms + omarchy-pkg-add-kernel-headers + omarchy-pkg-add yt6801-dkms fi diff --git a/install/hardware/intel/ipu7-camera.sh b/install/hardware/intel/ipu7-camera.sh index 97e5549bb6d6..45f1aced337d 100644 --- a/install/hardware/intel/ipu7-camera.sh +++ b/install/hardware/intel/ipu7-camera.sh @@ -1,5 +1,6 @@ # Install MIPI camera support for Intel IPU7 hardware if grep -q "OVTI08F4" /sys/bus/acpi/devices/*/hid 2>/dev/null; then + omarchy-pkg-add-kernel-headers omarchy-pkg-add intel-ipu7-camera fi diff --git a/install/hardware/nvidia.sh b/install/hardware/nvidia.sh index 48f62cd4b15a..3b9adc182fb6 100644 --- a/install/hardware/nvidia.sh +++ b/install/hardware/nvidia.sh @@ -1,8 +1,4 @@ if lspci | grep -qi 'nvidia'; then - # Check which kernel is installed and set appropriate headers package - KERNEL_PACKAGE=$(pacman -Qqs '^linux(-zen|-lts|-hardened|-t2|-ptl|-omarchy(-bore|-ptl-novrr-mm)?)?$' | head -1 || true) - [[ -n $KERNEL_PACKAGE ]] && omarchy-pkg-add "$KERNEL_PACKAGE-headers" - if omarchy-hw-nvidia-gsp; then PACKAGES=(nvidia-open-dkms nvidia-utils lib32-nvidia-utils libva-nvidia-driver) elif omarchy-hw-nvidia-without-gsp; then @@ -15,6 +11,7 @@ if lspci | grep -qi 'nvidia'; then exit 0 fi + omarchy-pkg-add-kernel-headers omarchy-pkg-add "${PACKAGES[@]}" # Per-session Hyprland NVIDIA env vars are handled by default/hypr/nvidia.lua. diff --git a/install/omarchy-other.packages b/install/omarchy-other.packages index 1f325b245e09..4a8b128ff95f 100644 --- a/install/omarchy-other.packages +++ b/install/omarchy-other.packages @@ -20,9 +20,7 @@ libva-nvidia-driver limine limine-mkinitcpio-hook limine-snapper-sync -linux linux-firmware -linux-headers linux-omarchy linux-omarchy-headers macbook12-spi-driver-dkms diff --git a/migrations/1789444024.sh b/migrations/1789444024.sh new file mode 100644 index 000000000000..05107342429f --- /dev/null +++ b/migrations/1789444024.sh @@ -0,0 +1,8 @@ +echo "Install missing headers for the Omarchy or T2 kernel" + +# Fresh ISO installs mark earlier migrations complete, so the kernel migration +# cannot repair headers omitted by those installers. Package installation is +# idempotent when another user has already applied this repair. +if omarchy-pkg-present linux-omarchy || omarchy-pkg-present linux-t2; then + omarchy-pkg-add-kernel-headers +fi diff --git a/test/acceptance.d/system-test.sh b/test/acceptance.d/system-test.sh index 0d648e9c16ea..af0d5204f83c 100644 --- a/test/acceptance.d/system-test.sh +++ b/test/acceptance.d/system-test.sh @@ -24,6 +24,20 @@ verify_core_packages() { pass "all Omarchy core packages are installed (${#missing[@]} missing)" } +verify_kernel_headers() { + local kernel=linux-omarchy + local release + release=$(uname -r) + omarchy-pkg-present linux-t2 && kernel=linux-t2 + + [[ $(cat "/usr/lib/modules/$release/pkgbase") == "$kernel" ]] || + fail "the installed system boots the supported kernel" "$release is not $kernel" + omarchy-pkg-present "$kernel-headers" || fail "kernel headers are installed" "$kernel-headers is missing" + [[ $(cat "/usr/lib/modules/$release/build/include/config/kernel.release") == "$release" ]] || + fail "headers match the running kernel" "$release has missing or mismatched headers" + pass "the running $kernel kernel has matching headers ($release)" +} + verify_defaults() { [[ $(omarchy-default-browser) == "chromium" ]] || fail "Chromium is the default browser" pass "Chromium is the default browser" @@ -112,7 +126,7 @@ verify_user_setup() { pass "Omarchy user state and shell configuration exist" } -for check in verify_core_packages verify_defaults verify_services verify_runtime_tools verify_user_setup; do +for check in verify_core_packages verify_kernel_headers verify_defaults verify_services verify_runtime_tools verify_user_setup; do if ! ("$check"); then status=1 fi diff --git a/test/shell.d/kernel-headers-test.sh b/test/shell.d/kernel-headers-test.sh new file mode 100755 index 000000000000..51db25d023c7 --- /dev/null +++ b/test/shell.d/kernel-headers-test.sh @@ -0,0 +1,89 @@ +#!/bin/bash + +set -euo pipefail +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +tmp_dir=$(mktemp -d) +trap 'rm -rf "$tmp_dir"' EXIT +mkdir -p "$tmp_dir/bin" "$tmp_dir/etc/modprobe.d" "$tmp_dir/sys/class/dmi/id" "$tmp_dir/sys/bus/acpi/devices/camera" +export INSTALLED_PACKAGES="$tmp_dir/installed" CALL_LOG="$tmp_dir/calls" +export PATH="$tmp_dir/bin:$ROOT/bin:$PATH" OMARCHY_PATH="$ROOT" + +cat > "$tmp_dir/bin/pacman" <<'SH' +#!/bin/bash +[[ $1 == "-Q" ]] || exit 1 +grep -Fxq -- "$2" "$INSTALLED_PACKAGES" +SH +cat > "$tmp_dir/bin/omarchy-pkg-add" <<'SH' +#!/bin/bash +printf '%s\n' "$*" >> "$CALL_LOG" +[[ ${FAIL_HEADERS:-0} != 1 || $* != *-headers* ]] +SH +cat > "$tmp_dir/bin/lspci" <<'SH' +#!/bin/bash +printf '%s\n' 'NVIDIA [10de:2560]' 'Broadcom [14e4:43a0]' 'Motorcomm YT6801 Ethernet' +SH +cat > "$tmp_dir/bin/id" <<'SH' +#!/bin/bash +echo input +SH +for command in sudo lsmod omarchy-hw-nvidia-gsp omarchy-hw-elgato-camlink-4k; do + printf '#!/bin/bash\nexit 0\n' > "$tmp_dir/bin/$command" +done +chmod +x "$tmp_dir/bin/"* + +for installed in linux-omarchy linux-t2 linux; do + echo "$installed" > "$INSTALLED_PACKAGES" + : > "$CALL_LOG" + bash -euo pipefail "$ROOT/migrations/1789444024.sh" >/dev/null + if [[ $installed == "linux" ]]; then + [[ ! -s $CALL_LOG ]] || fail "header repair skips systems without a supported kernel" + else + [[ $(cat "$CALL_LOG") == "$installed-headers" ]] || fail "header repair covers existing $installed installs" + fi +done +pass "header repair covers existing Omarchy and T2 installs" +echo MacBook8,1 > "$tmp_dir/sys/class/dmi/id/product_name" +echo TUXEDO > "$tmp_dir/sys/class/dmi/id/sys_vendor" +echo OVTI08F4 > "$tmp_dir/sys/bus/acpi/devices/camera/hid" + +for installed in 'linux-omarchy' 'linux linux-omarchy' 'linux' 'linux-t2' 'linux linux-omarchy linux-t2'; do + expected=linux-omarchy-headers + [[ $installed == *linux-t2* ]] && expected=linux-t2-headers + read -ra packages <<< "$installed" + printf '%s\n' "${packages[@]}" > "$INSTALLED_PACKAGES" + : > "$CALL_LOG" + omarchy-pkg-add-kernel-headers + [[ $(cat "$CALL_LOG") == "$expected" ]] || fail "headers match supported kernel with $installed installed" + pass "headers match supported kernel with $installed installed" +done + +# Run every DKMS installer against hardware fixtures and stub package writes. +# Redirect absolute filesystem paths in sourced leaves into the fixture too. +for family in linux-omarchy linux-t2; do + printf '%s\n' linux "$family" > "$INSTALLED_PACKAGES" + for script in \ + bin/omarchy-install-gaming-xbox-controllers \ + install/hardware/nvidia.sh \ + install/hardware/apple/fix-spi-keyboard.sh \ + install/hardware/intel/ipu7-camera.sh \ + install/hardware/fix-bcm43xx.sh \ + install/hardware/fix-tuxedo-backlight.sh \ + install/hardware/fix-yt6801-ethernet-adapter.sh \ + install/hardware/fix-elgato-camlink-4k.sh; do + sed -e "s|/etc/|$tmp_dir/etc/|g" -e "s|/sys/|$tmp_dir/sys/|g" \ + -e "s|/lib/modules/|$tmp_dir/lib/modules/|g" "$ROOT/$script" > "$tmp_dir/installer.sh" + : > "$CALL_LOG" + bash -e "$tmp_dir/installer.sh" >/dev/null + [[ $(head -1 "$CALL_LOG") == "$family-headers" ]] || fail "$script installs $family headers first" "$(cat "$CALL_LOG")" + (( $(wc -l < "$CALL_LOG") == 2 )) || fail "$script installs its driver after the headers" + ! grep -wq linux-headers "$CALL_LOG" || fail "$script avoids stock headers" + + : > "$CALL_LOG" + if FAIL_HEADERS=1 bash -e "$tmp_dir/installer.sh" >/dev/null; then + fail "$script stops when headers cannot be installed" + fi + [[ $(cat "$CALL_LOG") == "$family-headers" ]] || fail "$script must not install DKMS drivers without headers" + pass "$script uses $family headers and stops on header installation failure" + done +done From 24417bf191e09fc4d672c74c34e184449e92aeda Mon Sep 17 00:00:00 2001 From: Ryan Hughes Date: Tue, 15 Sep 2026 00:46:30 -0400 Subject: [PATCH 069/194] Treat matching kernel headers as a base system guarantee --- agents/skills/install-scripts.md | 1 + bin/omarchy-install-gaming-xbox-controllers | 1 - bin/omarchy-pkg-add-kernel-headers | 13 --- install/hardware/apple/fix-spi-keyboard.sh | 1 - install/hardware/fix-bcm43xx.sh | 1 - install/hardware/fix-elgato-camlink-4k.sh | 1 - install/hardware/fix-tuxedo-backlight.sh | 1 - .../hardware/fix-yt6801-ethernet-adapter.sh | 1 - install/hardware/intel/ipu7-camera.sh | 1 - install/hardware/nvidia.sh | 1 - migrations/1789444024.sh | 8 +- test/shell.d/kernel-headers-migration-test.sh | 58 ++++++++++++ test/shell.d/kernel-headers-test.sh | 89 ------------------- 13 files changed, 64 insertions(+), 113 deletions(-) delete mode 100755 bin/omarchy-pkg-add-kernel-headers create mode 100755 test/shell.d/kernel-headers-migration-test.sh delete mode 100755 test/shell.d/kernel-headers-test.sh diff --git a/agents/skills/install-scripts.md b/agents/skills/install-scripts.md index 999a6e9ca0a7..aa993e5e54bd 100644 --- a/agents/skills/install-scripts.md +++ b/agents/skills/install-scripts.md @@ -13,6 +13,7 @@ commands and reusable setup leaves: - use `$OMARCHY_INSTALL` and `$OMARCHY_PATH` instead of hard-coded Omarchy paths. - keep root-scoped hardware setup under `install/hardware/` and orchestrate it through `install/hardware/all.sh`. - keep every per-user setup leaf under `install/user/` (including `install/user/hardware/` and `install/user/first-run/`) so it is clear what must run for each user. +- The base install supplies matching kernel headers before hardware setup. DKMS installers should install their driver packages and assume the headers exist. - prefer helper commands for package and command checks where available. Raw `command -v`, `pacman`, and `pacman-key` are acceptable in package-helper diff --git a/bin/omarchy-install-gaming-xbox-controllers b/bin/omarchy-install-gaming-xbox-controllers index 8f7bdf28f8c1..f2cda4e7c6c4 100755 --- a/bin/omarchy-install-gaming-xbox-controllers +++ b/bin/omarchy-install-gaming-xbox-controllers @@ -10,7 +10,6 @@ set -e echo "Installing Xbox controller Bluetooth support..." # Install xpadneo to ensure controllers work out of the box -omarchy-pkg-add-kernel-headers omarchy-pkg-add xpadneo-dkms # Prevent xpad/xpadneo driver conflict diff --git a/bin/omarchy-pkg-add-kernel-headers b/bin/omarchy-pkg-add-kernel-headers deleted file mode 100755 index 28590b3626ca..000000000000 --- a/bin/omarchy-pkg-add-kernel-headers +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash - -# omarchy:summary=Install headers for the supported system kernel -# omarchy:hidden=true -# omarchy:requires-sudo=true - -# Inspect the target's packages: uname reports the live ISO kernel in a chroot. -# A retained stock kernel must not take precedence over the Omarchy kernel. -if omarchy-pkg-present linux-t2; then - omarchy-pkg-add linux-t2-headers -else - omarchy-pkg-add linux-omarchy-headers -fi diff --git a/install/hardware/apple/fix-spi-keyboard.sh b/install/hardware/apple/fix-spi-keyboard.sh index fd5d8e45c656..330081b76318 100644 --- a/install/hardware/apple/fix-spi-keyboard.sh +++ b/install/hardware/apple/fix-spi-keyboard.sh @@ -3,7 +3,6 @@ product_name="$(cat /sys/class/dmi/id/product_name 2>/dev/null)" if [[ $product_name =~ MacBook[89],1|MacBook1[02],1|MacBookPro13,[123]|MacBookPro14,[123] ]]; then echo "Detected MacBook with SPI keyboard" - omarchy-pkg-add-kernel-headers omarchy-pkg-add macbook12-spi-driver-dkms sudo mkdir -p /etc/mkinitcpio.conf.d if [[ $product_name == "MacBook8,1" ]]; then diff --git a/install/hardware/fix-bcm43xx.sh b/install/hardware/fix-bcm43xx.sh index f829749e9c25..0f9cf474a5be 100644 --- a/install/hardware/fix-bcm43xx.sh +++ b/install/hardware/fix-bcm43xx.sh @@ -6,6 +6,5 @@ pci_info=$(lspci -nn) if (echo "$pci_info" | grep -q "14e4:43a0" || echo "$pci_info" | grep -q "14e4:4331"); then echo "BCM4360 / BCM4331 detected" - omarchy-pkg-add-kernel-headers omarchy-pkg-add broadcom-wl-dkms fi diff --git a/install/hardware/fix-elgato-camlink-4k.sh b/install/hardware/fix-elgato-camlink-4k.sh index d12cbfe4fa8d..9ae9e343d47c 100644 --- a/install/hardware/fix-elgato-camlink-4k.sh +++ b/install/hardware/fix-elgato-camlink-4k.sh @@ -4,7 +4,6 @@ # v4l2-relayd re-exposes it at 1280x720 under the same name. if omarchy-hw-elgato-camlink-4k; then - omarchy-pkg-add-kernel-headers omarchy-pkg-add v4l2loopback-dkms v4l2loopback-utils v4l2-relayd sudo install -Dm644 "$OMARCHY_PATH/default/udev/elgato-camlink-4k.rules" /etc/udev/rules.d/71-elgato-camlink-4k.rules diff --git a/install/hardware/fix-tuxedo-backlight.sh b/install/hardware/fix-tuxedo-backlight.sh index c40fadb8268e..7fb408e0d543 100644 --- a/install/hardware/fix-tuxedo-backlight.sh +++ b/install/hardware/fix-tuxedo-backlight.sh @@ -1,7 +1,6 @@ # Install Tuxedo drivers for keyboard backlighting on Tuxedo laptops and # compatible devices like the Slimbook Executive (Clevo/Tuxedo chassis). if cat /sys/class/dmi/id/sys_vendor 2>/dev/null | grep -qi "TUXEDO\|Slimbook"; then - omarchy-pkg-add-kernel-headers omarchy-pkg-add tuxedo-drivers-nocompatcheck-dkms # Blacklist the legacy clevo_xsm_wmi module which conflicts with the tuxedo-drivers diff --git a/install/hardware/fix-yt6801-ethernet-adapter.sh b/install/hardware/fix-yt6801-ethernet-adapter.sh index e20cb92ee402..f88a9cec624b 100644 --- a/install/hardware/fix-yt6801-ethernet-adapter.sh +++ b/install/hardware/fix-yt6801-ethernet-adapter.sh @@ -1,5 +1,4 @@ # Install drivers for Motorcomm YT6801 ethernet adapter used by the Slimbook Executive if lspci | grep -i "YT6801\|Motorcomm.*Ethernet"; then - omarchy-pkg-add-kernel-headers omarchy-pkg-add yt6801-dkms fi diff --git a/install/hardware/intel/ipu7-camera.sh b/install/hardware/intel/ipu7-camera.sh index 45f1aced337d..97e5549bb6d6 100644 --- a/install/hardware/intel/ipu7-camera.sh +++ b/install/hardware/intel/ipu7-camera.sh @@ -1,6 +1,5 @@ # Install MIPI camera support for Intel IPU7 hardware if grep -q "OVTI08F4" /sys/bus/acpi/devices/*/hid 2>/dev/null; then - omarchy-pkg-add-kernel-headers omarchy-pkg-add intel-ipu7-camera fi diff --git a/install/hardware/nvidia.sh b/install/hardware/nvidia.sh index 3b9adc182fb6..1c36787b7705 100644 --- a/install/hardware/nvidia.sh +++ b/install/hardware/nvidia.sh @@ -11,7 +11,6 @@ if lspci | grep -qi 'nvidia'; then exit 0 fi - omarchy-pkg-add-kernel-headers omarchy-pkg-add "${PACKAGES[@]}" # Per-session Hyprland NVIDIA env vars are handled by default/hypr/nvidia.lua. diff --git a/migrations/1789444024.sh b/migrations/1789444024.sh index 05107342429f..b5bc9149dded 100644 --- a/migrations/1789444024.sh +++ b/migrations/1789444024.sh @@ -3,6 +3,8 @@ echo "Install missing headers for the Omarchy or T2 kernel" # Fresh ISO installs mark earlier migrations complete, so the kernel migration # cannot repair headers omitted by those installers. Package installation is # idempotent when another user has already applied this repair. -if omarchy-pkg-present linux-omarchy || omarchy-pkg-present linux-t2; then - omarchy-pkg-add-kernel-headers -fi +for kernel in linux-omarchy linux-t2; do + if omarchy-pkg-present "$kernel"; then + omarchy-pkg-add "$kernel-headers" + fi +done diff --git a/test/shell.d/kernel-headers-migration-test.sh b/test/shell.d/kernel-headers-migration-test.sh new file mode 100755 index 000000000000..458ea3307ecf --- /dev/null +++ b/test/shell.d/kernel-headers-migration-test.sh @@ -0,0 +1,58 @@ +#!/bin/bash + +set -euo pipefail +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +tmp_dir=$(mktemp -d) +trap 'rm -rf "$tmp_dir"' EXIT +mkdir -p "$tmp_dir/bin" +export INSTALLED_PACKAGES="$tmp_dir/installed" CALL_LOG="$tmp_dir/calls" +export PATH="$tmp_dir/bin:$ROOT/bin:$PATH" + +# Keep the real package helpers, but contain every pacman transaction here. +cat > "$tmp_dir/bin/pacman" <<'SH' +#!/bin/bash +case "$1" in + -Q) grep -Fxq -- "$2" "$INSTALLED_PACKAGES" ;; + -S) + [[ ${FAIL_INSTALL:-0} == 0 ]] || exit 1 + shift 3 # -S --noconfirm --needed + printf '%s\n' "$@" >> "$INSTALLED_PACKAGES" + printf '%s\n' "$@" >> "$CALL_LOG" + ;; + *) exit 1 ;; +esac +SH +cat > "$tmp_dir/bin/sudo" <<'SH' +#!/bin/bash +[[ $1 == "pacman" ]] || exit 1 +"$@" +SH +chmod +x "$tmp_dir/bin/"* + +migration="$ROOT/migrations/1789444024.sh" +for kernels in linux-omarchy linux-t2 'linux-omarchy linux-t2'; do + read -ra installed <<< "$kernels" + printf '%s\n' linux linux-headers "${installed[@]}" > "$INSTALLED_PACKAGES" + : > "$CALL_LOG" + bash -euo pipefail "$migration" >/dev/null + for kernel in "${installed[@]}"; do + grep -Fxq "$kernel-headers" "$INSTALLED_PACKAGES" || fail "$kernel gets its headers" + done + : > "$CALL_LOG" + bash -euo pipefail "$migration" >/dev/null + [[ ! -s $CALL_LOG ]] || fail "header repair is idempotent" + pass "missing headers are repaired once for $kernels" +done + +printf '%s\n' linux linux-aarch64 > "$INSTALLED_PACKAGES" +: > "$CALL_LOG" +bash -euo pipefail "$migration" >/dev/null +[[ ! -s $CALL_LOG ]] || fail "header repair skips unrelated kernels" +pass "header repair skips unrelated kernels" + +echo linux-omarchy > "$INSTALLED_PACKAGES" +if FAIL_INSTALL=1 bash -euo pipefail "$migration" >/dev/null; then + fail "a failed header installation must leave the migration pending" +fi +pass "header installation failure is propagated" diff --git a/test/shell.d/kernel-headers-test.sh b/test/shell.d/kernel-headers-test.sh deleted file mode 100755 index 51db25d023c7..000000000000 --- a/test/shell.d/kernel-headers-test.sh +++ /dev/null @@ -1,89 +0,0 @@ -#!/bin/bash - -set -euo pipefail -source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" - -tmp_dir=$(mktemp -d) -trap 'rm -rf "$tmp_dir"' EXIT -mkdir -p "$tmp_dir/bin" "$tmp_dir/etc/modprobe.d" "$tmp_dir/sys/class/dmi/id" "$tmp_dir/sys/bus/acpi/devices/camera" -export INSTALLED_PACKAGES="$tmp_dir/installed" CALL_LOG="$tmp_dir/calls" -export PATH="$tmp_dir/bin:$ROOT/bin:$PATH" OMARCHY_PATH="$ROOT" - -cat > "$tmp_dir/bin/pacman" <<'SH' -#!/bin/bash -[[ $1 == "-Q" ]] || exit 1 -grep -Fxq -- "$2" "$INSTALLED_PACKAGES" -SH -cat > "$tmp_dir/bin/omarchy-pkg-add" <<'SH' -#!/bin/bash -printf '%s\n' "$*" >> "$CALL_LOG" -[[ ${FAIL_HEADERS:-0} != 1 || $* != *-headers* ]] -SH -cat > "$tmp_dir/bin/lspci" <<'SH' -#!/bin/bash -printf '%s\n' 'NVIDIA [10de:2560]' 'Broadcom [14e4:43a0]' 'Motorcomm YT6801 Ethernet' -SH -cat > "$tmp_dir/bin/id" <<'SH' -#!/bin/bash -echo input -SH -for command in sudo lsmod omarchy-hw-nvidia-gsp omarchy-hw-elgato-camlink-4k; do - printf '#!/bin/bash\nexit 0\n' > "$tmp_dir/bin/$command" -done -chmod +x "$tmp_dir/bin/"* - -for installed in linux-omarchy linux-t2 linux; do - echo "$installed" > "$INSTALLED_PACKAGES" - : > "$CALL_LOG" - bash -euo pipefail "$ROOT/migrations/1789444024.sh" >/dev/null - if [[ $installed == "linux" ]]; then - [[ ! -s $CALL_LOG ]] || fail "header repair skips systems without a supported kernel" - else - [[ $(cat "$CALL_LOG") == "$installed-headers" ]] || fail "header repair covers existing $installed installs" - fi -done -pass "header repair covers existing Omarchy and T2 installs" -echo MacBook8,1 > "$tmp_dir/sys/class/dmi/id/product_name" -echo TUXEDO > "$tmp_dir/sys/class/dmi/id/sys_vendor" -echo OVTI08F4 > "$tmp_dir/sys/bus/acpi/devices/camera/hid" - -for installed in 'linux-omarchy' 'linux linux-omarchy' 'linux' 'linux-t2' 'linux linux-omarchy linux-t2'; do - expected=linux-omarchy-headers - [[ $installed == *linux-t2* ]] && expected=linux-t2-headers - read -ra packages <<< "$installed" - printf '%s\n' "${packages[@]}" > "$INSTALLED_PACKAGES" - : > "$CALL_LOG" - omarchy-pkg-add-kernel-headers - [[ $(cat "$CALL_LOG") == "$expected" ]] || fail "headers match supported kernel with $installed installed" - pass "headers match supported kernel with $installed installed" -done - -# Run every DKMS installer against hardware fixtures and stub package writes. -# Redirect absolute filesystem paths in sourced leaves into the fixture too. -for family in linux-omarchy linux-t2; do - printf '%s\n' linux "$family" > "$INSTALLED_PACKAGES" - for script in \ - bin/omarchy-install-gaming-xbox-controllers \ - install/hardware/nvidia.sh \ - install/hardware/apple/fix-spi-keyboard.sh \ - install/hardware/intel/ipu7-camera.sh \ - install/hardware/fix-bcm43xx.sh \ - install/hardware/fix-tuxedo-backlight.sh \ - install/hardware/fix-yt6801-ethernet-adapter.sh \ - install/hardware/fix-elgato-camlink-4k.sh; do - sed -e "s|/etc/|$tmp_dir/etc/|g" -e "s|/sys/|$tmp_dir/sys/|g" \ - -e "s|/lib/modules/|$tmp_dir/lib/modules/|g" "$ROOT/$script" > "$tmp_dir/installer.sh" - : > "$CALL_LOG" - bash -e "$tmp_dir/installer.sh" >/dev/null - [[ $(head -1 "$CALL_LOG") == "$family-headers" ]] || fail "$script installs $family headers first" "$(cat "$CALL_LOG")" - (( $(wc -l < "$CALL_LOG") == 2 )) || fail "$script installs its driver after the headers" - ! grep -wq linux-headers "$CALL_LOG" || fail "$script avoids stock headers" - - : > "$CALL_LOG" - if FAIL_HEADERS=1 bash -e "$tmp_dir/installer.sh" >/dev/null; then - fail "$script stops when headers cannot be installed" - fi - [[ $(cat "$CALL_LOG") == "$family-headers" ]] || fail "$script must not install DKMS drivers without headers" - pass "$script uses $family headers and stops on header installation failure" - done -done From 45e32c8c2d000ffee5488e16fb7601100a2c0511 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Tue, 15 Sep 2026 08:10:58 -0400 Subject: [PATCH 070/194] Set up browser integration when choosing Claude --- bin/omarchy-agent | 2 +- bin/omarchy-default-agent | 5 +++ bin/omarchy-install-chromium-claude | 43 +++++++++++++++++++ manual/17-ai.md | 2 + test/shell.d/chromium-claude-test.sh | 50 +++++++++++++++++++++++ test/shell.d/default-agent-test.sh | 22 +++++++++- test/shell.d/unowned-system-paths-test.sh | 7 +++- 7 files changed, 126 insertions(+), 5 deletions(-) create mode 100755 bin/omarchy-install-chromium-claude create mode 100644 test/shell.d/chromium-claude-test.sh diff --git a/bin/omarchy-agent b/bin/omarchy-agent index e35bcf04ada9..23d0e2f3bea9 100755 --- a/bin/omarchy-agent +++ b/bin/omarchy-agent @@ -75,7 +75,7 @@ crush) fi ;; claude) - command=(claude --permission-mode auto) + command=(claude --permission-mode auto --chrome) [[ -n ${prompt:-} ]] && command+=(-- "$prompt") ;; grok) diff --git a/bin/omarchy-default-agent b/bin/omarchy-default-agent index af93d8635f11..8c14a4f2ebc9 100755 --- a/bin/omarchy-default-agent +++ b/bin/omarchy-default-agent @@ -86,6 +86,11 @@ if ! agent_install; then exit 1 fi +if [[ $agent == "claude" ]] && ! omarchy-install-chromium-claude; then + echo "Could not install the Claude browser extension" >&2 + exit 1 +fi + mkdir -p "$(dirname "$agent_file")" printf '%s\n' "$agent" >"$agent_file" diff --git a/bin/omarchy-install-chromium-claude b/bin/omarchy-install-chromium-claude new file mode 100755 index 000000000000..df3382712923 --- /dev/null +++ b/bin/omarchy-install-chromium-claude @@ -0,0 +1,43 @@ +#!/bin/bash + +# omarchy:summary=Install the Claude extension for Chromium-based browsers +# omarchy:requires-sudo=true + +set -euo pipefail + +if (( EUID == 0 )); then + export PATH=/usr/bin:/bin +fi + +EXTENSION_ID="fcoeoabgfenejglbffodgkkbkcdhcgfn" +EXTENSION_JSON='{ "external_update_url": "https://clients2.google.com/service/update2/crx" }' +PACKAGED_PATH=/usr/bin/omarchy-install-chromium-claude + +# Brave and Brave Origin share Chromium's external extension directory. +# Seed all supported browsers, including those installed after choosing Claude. +EXTENSION_DIRS=( + /usr/share/chromium/extensions + /usr/share/google-chrome/extensions + /usr/share/microsoft-edge/extensions +) + +installed=true +for dir in "${EXTENSION_DIRS[@]}"; do + if [[ ! -f $dir/$EXTENSION_ID.json ]] || [[ $(cat "$dir/$EXTENSION_ID.json") != "$EXTENSION_JSON" ]]; then + installed=false + fi +done + +if [[ $installed == "true" ]]; then + exit 0 +fi + +if (( EUID == 0 )); then + for dir in "${EXTENSION_DIRS[@]}"; do + printf '%s\n' "$EXTENSION_JSON" | install -D -m 0644 /dev/stdin "$dir/$EXTENSION_ID.json" + done +elif [[ -t 0 ]]; then + exec sudo "$PACKAGED_PATH" +else + exec pkexec "$PACKAGED_PATH" +fi diff --git a/manual/17-ai.md b/manual/17-ai.md index 8c3d48b024ca..7f76d4817c0c 100644 --- a/manual/17-ai.md +++ b/manual/17-ai.md @@ -26,6 +26,8 @@ To wrap an additional CLI the same way, run `omarchy-mise-install [com Pick your default agent with `omarchy default agent ` or under _Setup > Defaults > Agent_ in the Omarchy Menu (`Super + Space`). If the agent isn't installed yet, picking it installs it first. A fresh Omarchy will invite you to make this choice with a one-time notification. +Choosing Claude also sets up its browser extension for Chromium, Chrome, Brave, Brave Origin, and Edge, and enables browser integration when launched through `omarchy agent`. The extension setup applies to all users and may ask for your system password; cancelling leaves your previous default agent selected. Restart your browser, enable the extension if prompted, and sign in to Claude to finish connecting it. Run `/chrome` in Claude to check the connection. Firefox and Zen do not support this extension. If Claude was already your default before this setup was added, select it again to install the extension. + [Muse Code](https://dev.meta.ai) — Meta's `muse` — uses a preinstalled mise stub like the other agents. Picking it as the default installs Meta's official launcher through mise's HTTP backend. The launcher verifies and updates the native binary for your machine. Once you've chosen, `Super + Shift + Ctrl + A` launches the default agent in a dedicated terminal window (or brings up the picker if you haven't chosen yet). You can also launch it straight into a task with `omarchy agent prompt "Review this project"`. Agents launched this way run unattended in their respective don't-stop-to-ask modes, so be ready for them to actually do things! And since agents refuse to remember trust for your home directory, launches from `$HOME` start in `~/Work` instead. diff --git a/test/shell.d/chromium-claude-test.sh b/test/shell.d/chromium-claude-test.sh new file mode 100644 index 000000000000..5d8c61ef5df0 --- /dev/null +++ b/test/shell.d/chromium-claude-test.sh @@ -0,0 +1,50 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +# Exercise the privileged installer without writing to the host's /usr/share. +if ! command -v bwrap >/dev/null || ! bwrap --ro-bind / / --unshare-user --uid 0 --gid 0 true 2>/dev/null; then + pass "user namespaces unavailable; skipping isolated Claude extension installation" + exit 0 +fi + +test_tmp=$(mktemp -d) +trap 'rm -rf "$test_tmp"' EXIT +mkdir -p "$test_tmp/share" "$test_tmp/bin" +installer="$ROOT/bin/omarchy-install-chromium-claude" +extension_id=fcoeoabgfenejglbffodgkkbkcdhcgfn +sandbox=(bwrap --ro-bind / / --bind "$test_tmp" "$test_tmp" --dev /dev --proc /proc --unshare-user) + +"${sandbox[@]}" --uid 0 --gid 0 --bind "$test_tmp/share" /usr/share bash "$installer" +for browser in chromium google-chrome microsoft-edge; do + file="$test_tmp/share/$browser/extensions/$extension_id.json" + jq -e '.external_update_url == "https://clients2.google.com/service/update2/crx"' "$file" >/dev/null || + fail "$browser registers the official Claude Web Store extension" + [[ $(stat -c '%a' "$file") == "644" ]] || fail "$browser extension registration is readable" +done +pass "Claude extension installer registers all supported browser families" + +cat >"$test_tmp/bin/pkexec" <<'SH' +#!/bin/bash +printf '%s\n' "$@" >"$AUTH_LOG" +exit 42 +SH +chmod +x "$test_tmp/bin/pkexec" +export AUTH_LOG="$test_tmp/auth-log" +export PATH="$test_tmp/bin:$PATH" + +# A read-only /usr/share and a failing auth stub prove that a repeated run +# neither rewrites the files nor requests authentication. +"${sandbox[@]}" --uid 1000 --gid 1000 --ro-bind "$test_tmp/share" /usr/share bash "$installer" "$mock_bin/omarchy-install-chromium-claude" <<'SH' +#!/bin/bash +echo claude-extension >>"$OMARCHY_TEST_STUB_LOG" +[[ ${OMARCHY_TEST_EXTENSION_FAIL:-false} != "true" ]] +SH + cat >"$mock_bin/omarchy-notification-send" <<'SH' #!/bin/bash printf '%s\0' "$@" >>"$OMARCHY_TEST_NOTIFICATION_HISTORY" @@ -406,9 +412,16 @@ declare -A expected_packages=( for selection in "${!expected_agents[@]}"; do expected=${expected_agents[$selection]} : >"$agent_open_log" + : >"$stub_log" OMARCHY_TEST_AGENT_INSTALLED=true omarchy-default-agent "$selection" [[ $(omarchy-default-agent) == $expected ]] || fail "default agent canonicalizes $selection" + if [[ $expected == "claude" ]]; then + grep -qx claude-extension "$stub_log" || fail "Claude selection installs the browser extension" + else + [[ ! -s $stub_log ]] || fail "other agents do not install the Claude extension" + fi + mapfile -d '' -t mise_args <"$mise_log" [[ ${mise_args[0]} == "use" && ${mise_args[1]} == "-g" ]] || fail "default agent installs $selection globally through mise" @@ -427,6 +440,11 @@ pass "default agent selects and opens every supported provider and alias" pass "default agent stores its selection in Omarchy user config" OMARCHY_TEST_AGENT_INSTALLED=true omarchy-default-agent pi +if OMARCHY_TEST_AGENT_INSTALLED=true OMARCHY_TEST_EXTENSION_FAIL=true omarchy-default-agent claude >"$test_tmp/extension-failure" 2>&1; then + fail "Claude selection fails when browser extension installation fails" +fi +[[ $(omarchy-default-agent) == "pi" ]] || fail "extension installation failure preserves the default agent" +pass "extension installation failure preserves the default agent" : >"$notification_history" : >"$agent_open_log" : >"$terminal_log" @@ -644,7 +662,7 @@ assert_launch pi pi "Review this project" assert_launch omp omp --auto-approve -- "Review this project" assert_launch opencode opencode --auto --prompt "Review this project" assert_launch ori ori code --interactive --prompt "Review this project" -assert_launch claude claude --permission-mode auto -- "Review this project" +assert_launch claude claude --permission-mode auto --chrome -- "Review this project" assert_launch codex codex --approve-for-me -- "Review this project" assert_launch muse muse --approval-mode never -- "Review this project" assert_launch crush crush run "Review this project" @@ -672,7 +690,7 @@ assert_bypass pi pi assert_bypass omp omp --auto-approve assert_bypass opencode opencode --auto assert_bypass ori ori code -assert_bypass claude claude --permission-mode auto +assert_bypass claude claude --permission-mode auto --chrome assert_bypass codex codex --approve-for-me assert_bypass muse muse --approval-mode never assert_bypass crush crush --yolo diff --git a/test/shell.d/unowned-system-paths-test.sh b/test/shell.d/unowned-system-paths-test.sh index e24506191470..efe940b4ea6c 100755 --- a/test/shell.d/unowned-system-paths-test.sh +++ b/test/shell.d/unowned-system-paths-test.sh @@ -31,10 +31,13 @@ allowed = { # them so the hook does not exist where it does not apply. "/usr/lib/systemd/system-sleep", # Written through a variable, so the scan below cannot see them at the point - # they are written. Both drop configuration into another project's tree rather - # than Omarchy's, which is why neither is a candidate for omarchy-settings. + # they are written. These drop configuration into another project's tree + # rather than Omarchy's and are not candidates for omarchy-settings. "/usr/share/chromium/extensions", "/usr/lib/firefox/distribution", + # Claude's extension is registered only when the user selects Claude. + "/usr/share/google-chrome/extensions", + "/usr/share/microsoft-edge/extensions", # Static content that belongs in omarchy-settings. It cannot move there in the # same release that first ships omarchy-update-system-pkgs-when-conflicted: the # upgrade carrying the handler is the one that would hit the conflict, and the From 49418942c898c8ed9ea604c35a71f0d5275ae26c Mon Sep 17 00:00:00 2001 From: Adolanium <94890352+Adolanium@users.noreply.github.com> Date: Tue, 15 Sep 2026 18:50:20 +0300 Subject: [PATCH 071/194] Merge pull request #7807 from Adolanium/keyring-fail-loud Stop update-keyring from claiming success when key operations fail --- bin/omarchy-update-keyring | 9 ++ test/shell.d/update-keyring-test.sh | 137 ++++++++++++++++++++++++++++ 2 files changed, 146 insertions(+) create mode 100644 test/shell.d/update-keyring-test.sh diff --git a/bin/omarchy-update-keyring b/bin/omarchy-update-keyring index d561e22a2773..3a1c1c17692e 100755 --- a/bin/omarchy-update-keyring +++ b/bin/omarchy-update-keyring @@ -3,6 +3,11 @@ # omarchy:summary=Ensure the Omarchy and Arch keyring packages are installed and populated # omarchy:requires-sudo=true +# omarchy-update runs this under set -e as a trusted pre-step, so a failed recv +# or a broken keyring has to stop this script here, not surface later as +# signature errors in the middle of the main transaction. +set -euo pipefail + if omarchy-pkg-missing omarchy-keyring || ! sudo pacman-key --list-keys 40DFB630FF42BCFFB047046CF0134EE680CAC571 &>/dev/null; then sudo pacman-key --recv-keys 40DFB630FF42BCFFB047046CF0134EE680CAC571 --keyserver keys.openpgp.org sudo pacman-key --lsign-key 40DFB630FF42BCFFB047046CF0134EE680CAC571 @@ -19,4 +24,8 @@ fi # Always reinstall, as the keyring can be updated without a package version bump. echo -e "\e[32m\nUpdate Arch signing keys\e[0m" sudo pacman -Sy --noconfirm archlinux-keyring >/dev/null 2> >(grep -vE '^warning: archlinux-keyring-[^ ]+ is up to date -- reinstalling$' >&2) + +# Say "correct" only once the key verifiably is: before the failure checks +# above, a failed recv or reinstall still ended here with exit 0. +sudo pacman-key --list-keys 40DFB630FF42BCFFB047046CF0134EE680CAC571 >/dev/null echo "Keys are correct" diff --git a/test/shell.d/update-keyring-test.sh b/test/shell.d/update-keyring-test.sh new file mode 100644 index 000000000000..15d5bb52fbec --- /dev/null +++ b/test/shell.d/update-keyring-test.sh @@ -0,0 +1,137 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +test_tmp=$(mktemp -d) +trap 'rm -rf "$test_tmp"' EXIT + +stub_bin="$test_tmp/bin" +log_file="$test_tmp/keyring.log" +mkdir -p "$stub_bin" + +# Behavior is driven by env vars so each case can pick its failure point: +# KEYRING_TEST_PKG_MISSING exit status of omarchy-pkg-missing (default 1: installed) +# KEYRING_TEST_LIST_FAIL_ON which --list-keys call fails, counted per run (default: none) +# KEYRING_TEST_RECV_STATUS exit status of --recv-keys (default 0) +# KEYRING_TEST_REINSTALL_STATUS exit status of the archlinux-keyring reinstall (default 0) +cat >"$stub_bin/sudo" <<'SH' +#!/bin/bash + +printf 'sudo' >>"$KEYRING_TEST_LOG" +for arg in "$@"; do + printf '\t%s' "$arg" >>"$KEYRING_TEST_LOG" +done +printf '\n' >>"$KEYRING_TEST_LOG" + +if [[ $1 == "pacman-key" && $2 == "--list-keys" ]]; then + calls_file="$KEYRING_TEST_DIR/list-calls" + calls=$(( $(cat "$calls_file" 2>/dev/null || echo 0) + 1 )) + echo "$calls" >"$calls_file" + if [[ ${KEYRING_TEST_LIST_FAIL_ON:-} == "$calls" ]]; then + exit 1 + fi + exit 0 +fi + +if [[ $1 == "pacman-key" && $2 == "--recv-keys" ]]; then + exit "${KEYRING_TEST_RECV_STATUS:-0}" +fi + +if [[ $1 == "pacman-key" && $2 == "--lsign-key" ]]; then + exit 0 +fi + +if [[ $1 == "pacman" && $* == *archlinux-keyring* ]]; then + exit "${KEYRING_TEST_REINSTALL_STATUS:-0}" +fi + +exit 0 +SH +chmod +x "$stub_bin/sudo" + +cat >"$stub_bin/omarchy-pkg-missing" <<'SH' +#!/bin/bash + +exit "${KEYRING_TEST_PKG_MISSING:-1}" +SH +chmod +x "$stub_bin/omarchy-pkg-missing" + +cat >"$stub_bin/omarchy-pkg-add" <<'SH' +#!/bin/bash + +printf 'pkg-add\t%s\n' "$1" >>"$KEYRING_TEST_LOG" +exit 0 +SH +chmod +x "$stub_bin/omarchy-pkg-add" + +run_keyring() { + KEYRING_TEST_LOG="$log_file" \ + KEYRING_TEST_DIR="$test_tmp" \ + PATH="$stub_bin:$PATH" \ + "$ROOT/bin/omarchy-update-keyring" "$@" +} + +# Everything healthy: the key and package are present, the reinstall works. +: >"$log_file" +rm -f "$test_tmp/list-calls" +run_keyring >"$test_tmp/ok.out" + +grep -F "Keys are correct" "$test_tmp/ok.out" >/dev/null || + fail "update-keyring reports success when the keyring is healthy" "$(cat "$test_tmp/ok.out")" +pass "update-keyring reports success when the keyring is healthy" + +grep -Eq $'^sudo\tpacman\t-Sy\t--noconfirm\tarchlinux-keyring$' "$log_file" || + fail "update-keyring still reinstalls archlinux-keyring" "$(cat "$log_file")" +pass "update-keyring still reinstalls archlinux-keyring" + +# Key and package missing: the full populate path runs and verifies at the end. +: >"$log_file" +rm -f "$test_tmp/list-calls" +KEYRING_TEST_PKG_MISSING=0 run_keyring >"$test_tmp/populate.out" + +grep -F "Keys are correct" "$test_tmp/populate.out" >/dev/null || + fail "update-keyring populates a missing keyring and reports success" "$(cat "$test_tmp/populate.out")" +for expected in 'recv-keys' 'lsign-key' $'pkg-add\tomarchy-keyring'; do + grep -Eq "$expected" "$log_file" || + fail "update-keyring populates a missing keyring and reports success" "$(cat "$log_file")" +done +pass "update-keyring populates a missing keyring and reports success" + +# recv-keys failing must stop the script, not end in "Keys are correct". +: >"$log_file" +rm -f "$test_tmp/list-calls" +if KEYRING_TEST_PKG_MISSING=0 KEYRING_TEST_RECV_STATUS=1 run_keyring >"$test_tmp/recv.out" 2>&1; then + fail "update-keyring fails when recv-keys fails" +fi +if grep -F "Keys are correct" "$test_tmp/recv.out" >/dev/null; then + fail "update-keyring fails when recv-keys fails" "$(cat "$test_tmp/recv.out")" +fi +if grep -q 'lsign-key' "$log_file"; then + fail "update-keyring stops at the failed recv instead of signing anyway" "$(cat "$log_file")" +fi +pass "update-keyring fails when recv-keys fails" + +# A failed archlinux-keyring reinstall must not end in success either. +: >"$log_file" +rm -f "$test_tmp/list-calls" +if KEYRING_TEST_REINSTALL_STATUS=1 run_keyring >"$test_tmp/reinstall.out" 2>&1; then + fail "update-keyring fails when the archlinux-keyring reinstall fails" +fi +if grep -F "Keys are correct" "$test_tmp/reinstall.out" >/dev/null; then + fail "update-keyring fails when the archlinux-keyring reinstall fails" "$(cat "$test_tmp/reinstall.out")" +fi +pass "update-keyring fails when the archlinux-keyring reinstall fails" + +# The closing check is what backs the success line: the first --list-keys +# passes (key present, populate skipped), the verifying one fails. +: >"$log_file" +rm -f "$test_tmp/list-calls" +if KEYRING_TEST_LIST_FAIL_ON=2 run_keyring >"$test_tmp/verify.out" 2>&1; then + fail "update-keyring fails when the final key check fails" +fi +if grep -F "Keys are correct" "$test_tmp/verify.out" >/dev/null; then + fail "update-keyring fails when the final key check fails" "$(cat "$test_tmp/verify.out")" +fi +pass "update-keyring fails when the final key check fails" From b44fb747803e22903ddab642b1aad517b223b677 Mon Sep 17 00:00:00 2001 From: Taksh Kothari Date: Tue, 15 Sep 2026 21:23:37 +0530 Subject: [PATCH 072/194] [Security] Keep screen-recording state out of world-writable /tmp (#8374) * Keep screen-recording state out of world-writable /tmp * Compare the /tmp name across the run instead of requiring it absent Co-Authored-By: Claude Opus 5 (1M context) * Fall back to the state directory when there is no runtime dir * Let the /tmp snapshot come back empty Co-Authored-By: Claude Opus 5 (1M context) * Resolve the region file the same way in the resizer Co-Authored-By: Claude Opus 5 (1M context) * Protect recording fallback state and document its path --------- Co-authored-by: Omabot Co-authored-by: Claude Opus 5 (1M context) --- bin/omarchy-capture-screenrecording | 25 +++- bin/omarchy-capture-webcam-resize | 5 +- default/agents/skills/omarchy/capture.md | 2 +- default/agents/skills/omarchy/contributing.md | 2 +- test/shell.d/screenrecording-test.sh | 111 ++++++++++++++++++ 5 files changed, 137 insertions(+), 8 deletions(-) diff --git a/bin/omarchy-capture-screenrecording b/bin/omarchy-capture-screenrecording index d57b26fee50f..0c4c5494c952 100755 --- a/bin/omarchy-capture-screenrecording +++ b/bin/omarchy-capture-screenrecording @@ -15,8 +15,9 @@ # start. # # Env: OMARCHY_SCREENRECORD_DEBUG=true appends gpu-screen-recorder's stderr (and -# the picker target it was launched with) to /tmp/omarchy-screenrecord.log so -# users can attach a log when reporting capture failures. +# the picker target it was launched with) to +# $XDG_RUNTIME_DIR/omarchy-screenrecord.log so users can attach a log when +# reporting capture failures. [[ -f ~/.config/user-dirs.dirs ]] && source ~/.config/user-dirs.dirs OUTPUT_DIR="${OMARCHY_SCREENRECORD_DIR:-${XDG_VIDEOS_DIR:-$HOME/Videos}}" @@ -34,9 +35,18 @@ WEBCAM_SIZE="medium" RESOLUTION="" FULLSCREEN="false" STOP_RECORDING="false" -RECORDING_FILE="/tmp/omarchy-screenrecord-filename" -REGION_FILE="${XDG_RUNTIME_DIR:-/tmp}/omarchy-screenrecord-region" -LOG_FILE=$([[ ${OMARCHY_SCREENRECORD_DEBUG:-false} == "true" ]] && echo "/tmp/omarchy-screenrecord.log" || echo "/dev/null") +# Both of these live in the per-user runtime directory, which is 0700. What +# RECORDING_FILE holds is read back on stop and used as a path -- ffmpeg writes +# beside it, `mv` replaces it, and `rm -f` deletes its preview -- so a name in +# world-writable /tmp is a name any other local account can create first and +# then point wherever it likes. The debug log carries the recorder's stderr and +# the picked geometry, which is nobody else's business either. Fall back to +# the state directory when there is no session runtime dir -- :-/tmp would put +# both files back at the fixed names this comment describes. +RUNTIME_DIR="${XDG_RUNTIME_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/omarchy}" +RECORDING_FILE="$RUNTIME_DIR/omarchy-screenrecord-filename" +REGION_FILE="$RUNTIME_DIR/omarchy-screenrecord-region" +LOG_FILE=$([[ ${OMARCHY_SCREENRECORD_DEBUG:-false} == "true" ]] && echo "$RUNTIME_DIR/omarchy-screenrecord.log" || echo "/dev/null") for arg in "$@"; do case "$arg" in @@ -144,6 +154,11 @@ select_capture_target() { } start_screenrecording() { + mkdir -p "$RUNTIME_DIR" || return 1 + # XDG_STATE_HOME may be outside a private home; protect existing fallbacks too. + if [[ -z ${XDG_RUNTIME_DIR:-} ]]; then + chmod 700 "$RUNTIME_DIR" || return 1 + fi local capture_args=() local target diff --git a/bin/omarchy-capture-webcam-resize b/bin/omarchy-capture-webcam-resize index cde61e087cfa..3c9d12155846 100755 --- a/bin/omarchy-capture-webcam-resize +++ b/bin/omarchy-capture-webcam-resize @@ -8,7 +8,10 @@ set -euo pipefail readonly MARGIN=40 -readonly REGION_FILE="${XDG_RUNTIME_DIR:-/tmp}/omarchy-screenrecord-region" +# Has to resolve to whatever omarchy-capture-screenrecording writes, fallback +# included, or a recording without a session runtime dir anchors the camera to +# the whole monitor instead of the region it recorded. +readonly REGION_FILE="${XDG_RUNTIME_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/omarchy}/omarchy-screenrecord-region" usage() { echo "Usage: omarchy-capture-webcam-resize " >&2 diff --git a/default/agents/skills/omarchy/capture.md b/default/agents/skills/omarchy/capture.md index 41a52b6cd205..621bc2989f61 100644 --- a/default/agents/skills/omarchy/capture.md +++ b/default/agents/skills/omarchy/capture.md @@ -33,7 +33,7 @@ Recordings land in the configured Videos directory (override with `omarchy capture webcam resize `. If recording fails to start, rerun with `OMARCHY_SCREENRECORD_DEBUG=true` to -collect a log at `/tmp/omarchy-screenrecord.log` worth attaching to a bug +collect a log at `$XDG_RUNTIME_DIR/omarchy-screenrecord.log` (or `${XDG_STATE_HOME:-$HOME/.local/state}/omarchy/omarchy-screenrecord.log` without a session runtime directory) worth attaching to a bug report. ## Text Capture (OCR) diff --git a/default/agents/skills/omarchy/contributing.md b/default/agents/skills/omarchy/contributing.md index b5fd05335d33..c76c12d61f88 100644 --- a/default/agents/skills/omarchy/contributing.md +++ b/default/agents/skills/omarchy/contributing.md @@ -38,7 +38,7 @@ drag-and-drop in the web form, so save the capture and hand the user the file path to attach (`gh` cannot upload media). For screen-recording failures specifically, rerun with -`OMARCHY_SCREENRECORD_DEBUG=true` and attach `/tmp/omarchy-screenrecord.log`. +`OMARCHY_SCREENRECORD_DEBUG=true` and attach `$XDG_RUNTIME_DIR/omarchy-screenrecord.log` (or `${XDG_STATE_HOME:-$HOME/.local/state}/omarchy/omarchy-screenrecord.log` without a session runtime directory). File the issue with `gh` when available: diff --git a/test/shell.d/screenrecording-test.sh b/test/shell.d/screenrecording-test.sh index 7859ec14b377..438ccc57a9b2 100644 --- a/test/shell.d/screenrecording-test.sh +++ b/test/shell.d/screenrecording-test.sh @@ -299,3 +299,114 @@ grep -F 'move = { "(monitor_w-monitor_h*2/9-40)", "(monitor_h-monitor_h/4-40)" } grep -F 'move = { "(monitor_w-monitor_h*3/10-40)", "(monitor_h-monitor_h*27/80-40)" }' "$webcam_rules" >/dev/null || \ fail "large webcam starts at its final corner position" pass "webcam size rules place the initial window in its final corner" + +# The stop path reads the recording state file back and uses its contents as a +# path -- ffmpeg writes beside it, `mv` replaces it, `rm -f` deletes its +# preview -- so it has to live in the per-user runtime directory rather than +# under a name in world-writable /tmp that another account can create first. +recording_dir="$tmp_dir/recordings" +mkdir -p "$recording_dir" + +cat >"$stub_bin/pgrep" <<'SH' +#!/bin/bash +exit 1 +SH + +cat >"$stub_bin/omarchy-hyprland-monitor-focused" <<'SH' +#!/bin/bash +printf 'DP-1\n' +SH + +cat >"$stub_bin/gpu-screen-recorder" <<'SH' +#!/bin/bash +for i in "$@"; do + [[ -n ${take_next:-} ]] && { : >"$i"; break; } + [[ $i == "-o" ]] && take_next=1 +done +sleep 5 +SH + +cat >"$stub_bin/omarchy-shell" <<'SH' +#!/bin/bash +exit 0 +SH + +chmod +x "$stub_bin"/pgrep "$stub_bin"/omarchy-hyprland-monitor-focused \ + "$stub_bin"/gpu-screen-recorder "$stub_bin"/omarchy-shell + +# Compare that name across the run rather than demanding it be absent: the +# whole point of the finding is that anyone can own it already, and a leftover +# from a pre-fix recording would red-light the fixed script. +tmp_state="/tmp/omarchy-screenrecord-filename" +tmp_state_before=$(stat -c '%y %s' "$tmp_state" 2>/dev/null || true) + +OMARCHY_SCREENRECORD_DIR="$recording_dir" \ + "$ROOT/bin/omarchy-capture-screenrecording" --fullscreen >/dev/null 2>&1 + +pkill -f "$stub_bin/gpu-screen-recorder" 2>/dev/null || true + +[[ $(stat -c '%y %s' "$tmp_state" 2>/dev/null) == "$tmp_state_before" ]] || + fail "screen recording keeps no state under a fixed /tmp name" +pass "screen recording keeps no state under a fixed /tmp name" + +[[ -s $XDG_RUNTIME_DIR/omarchy-screenrecord-filename ]] || + fail "the recording state file lives in the per-user runtime directory" \ + "$(ls -a "$XDG_RUNTIME_DIR")" +pass "the recording state file lives in the per-user runtime directory" + +[[ $(<"$XDG_RUNTIME_DIR/omarchy-screenrecord-filename") == "$recording_dir"/* ]] || + fail "the recording state file names the recording that was started" \ + "$(<"$XDG_RUNTIME_DIR/omarchy-screenrecord-filename")" +pass "the recording state file names the recording that was started" + +# The :-/tmp fallback would reopen the hole this PR closes. A recording +# started without a session runtime dir has to land under the state directory. +state_home="$tmp_dir/state-home" +mkdir -p "$state_home/omarchy" "$tmp_dir/home-fallback" +chmod 755 "$state_home/omarchy" +tmp_state_before=$(stat -c '%y %s' "$tmp_state" 2>/dev/null || true) + +env -u XDG_RUNTIME_DIR \ + HOME="$tmp_dir/home-fallback" \ + XDG_STATE_HOME="$state_home" \ + OMARCHY_SCREENRECORD_DIR="$recording_dir" \ + "$ROOT/bin/omarchy-capture-screenrecording" --fullscreen >/dev/null 2>&1 + +pkill -f "$stub_bin/gpu-screen-recorder" 2>/dev/null || true + +[[ $(stat -c '%y %s' "$tmp_state" 2>/dev/null) == "$tmp_state_before" ]] || + fail "without a runtime dir, screen recording still keeps no state under a fixed /tmp name" +pass "without a runtime dir, screen recording still keeps no state under a fixed /tmp name" + +fallback_file="$state_home/omarchy/omarchy-screenrecord-filename" +[[ -s $fallback_file ]] || + fail "without a runtime dir the recording state file lives in the state directory" \ + "$(ls -la "$state_home/omarchy" 2>/dev/null || true)" +pass "without a runtime dir the recording state file lives in the state directory" + +[[ $(<"$fallback_file") == "$recording_dir"/* ]] || + fail "the fallback state file names the recording that was started" \ + "$(<"$fallback_file")" +pass "the fallback state file names the recording that was started" + +# The overlay resizer reads the region file the recorder writes, so the two +# have to resolve the same fallback as well as the same runtime dir. +: >"$OMARCHY_TEST_HYPRCTL_ARGS" +echo "800x600+100+100" >"$state_home/omarchy/omarchy-screenrecord-region" +env -u XDG_RUNTIME_DIR \ + HOME="$tmp_dir/home-fallback" \ + XDG_STATE_HOME="$state_home" \ + "$ROOT/bin/omarchy-capture-webcam-resize" reset + +printf '%s\n' \ + 'dispatch hl.dsp.window.resize({ window = "address:0xabc", x = 133, y = 150 })' \ + 'dispatch hl.dsp.window.move({ window = "address:0xabc", x = 727, y = 510 })' >"$expected_hyprctl_args" + +if ! cmp -s "$OMARCHY_TEST_HYPRCTL_ARGS" "$expected_hyprctl_args"; then + fail "without a runtime dir the webcam anchors to the recorded region" "$(diff -u "$expected_hyprctl_args" "$OMARCHY_TEST_HYPRCTL_ARGS")" +fi +pass "without a runtime dir the webcam anchors to the recorded region" + +mode=$(stat -c '%a' "$state_home/omarchy" 2>/dev/null || stat -f '%Lp' "$state_home/omarchy") +[[ $mode == "700" ]] || fail "fallback directory is private even when it already existed" "mode: $mode" +pass "fallback directory is private even when it already existed" From a73bcbfc0a9570ba7072791639dc97eb567b6f41 Mon Sep 17 00:00:00 2001 From: Erik Melton Date: Tue, 15 Sep 2026 18:02:17 +0200 Subject: [PATCH 073/194] Remove unsafe project bin PATH injection (#11336) * Remove unsafe project bin PATH injection * Cover customized unsafe Mise paths * Revoke legacy Mise Work trust * Harden legacy Mise trust cleanup * Preserve ignored Mise Work configs * Scope Mise path cleanup to env * Accept paranoid Mise ignore marker Reported-by: infosec-us-team --- install/user/mise-work.sh | 7 - manual/19-shell-tools.md | 2 + migrations/1789095456.sh | 99 ++++++++++ test/shell.d/mise-work-path-test.sh | 270 ++++++++++++++++++++++++++++ 4 files changed, 371 insertions(+), 7 deletions(-) create mode 100644 migrations/1789095456.sh create mode 100644 test/shell.d/mise-work-path-test.sh diff --git a/install/user/mise-work.sh b/install/user/mise-work.sh index f77d5561e0e6..9ce5249fef0a 100644 --- a/install/user/mise-work.sh +++ b/install/user/mise-work.sh @@ -2,13 +2,6 @@ mkdir -p "$HOME/Work" mkdir -p "$HOME/Work/tries" -cat >"$HOME/Work/.mise.toml" <<'EOF' -[env] -_.path = "{{ cwd }}/bin" -EOF - -mise trust ~/Work/.mise.toml - # Offline installs unpack the Node tarball bundled by the ISO: from # /opt/packages in the ISO chroot, or from the copy staged in provisioning state when # omarchy-provision-owner finalizes the user at first boot. diff --git a/manual/19-shell-tools.md b/manual/19-shell-tools.md index 69965fdd4617..8252d795f95a 100644 --- a/manual/19-shell-tools.md +++ b/manual/19-shell-tools.md @@ -57,3 +57,5 @@ The full manual can be found via `man yt-dlp`. ## try [try](https://github.com/tobi/try) makes it easy to manage programming experiments with date-stamped directories. All experiments live in `~/Work/tries` and you can access them via `try`. + +Omarchy does not add a project's `bin/` directory to `PATH` automatically. Run trusted project-local tools with an explicit relative path, such as `bin/rails` or `./bin/dev`. diff --git a/migrations/1789095456.sh b/migrations/1789095456.sh new file mode 100644 index 000000000000..381557fc79b7 --- /dev/null +++ b/migrations/1789095456.sh @@ -0,0 +1,99 @@ +echo "Remove automatic project bin directories from PATH" + +work_dir="$HOME/Work" +mise_config="$work_dir/.mise.toml" +# install/user/mise-work.sh as shipped in Omarchy 4.0.3. +stock_sha="bd04f191d63bbde86920f44f76f0989fad980afc84e268e8474c201ec7149245" +cwd_bin='\{\{[[:space:]]*cwd[[:space:]]*\}\}/bin' +unsafe_path="^[[:space:]]*_[.]path[[:space:]]*=[[:space:]]*(\"$cwd_bin\"|'$cwd_bin')[[:space:]]*(#.*)?$" +env_section='^[[:space:]]*\[[[:space:]]*env[[:space:]]*\][[:space:]]*(#.*)?$' +any_section='^[[:space:]]*\[\[?.*\]\]?[[:space:]]*(#.*)?$' + +remove_empty_work_dir=false +if [[ ! -e $work_dir ]]; then + mkdir -p "$work_dir" + remove_empty_work_dir=true +fi + +was_ignored=false +if [[ -d $work_dir ]]; then + mise_state_dir=${MISE_STATE_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/mise} + ignored_configs_dir="$mise_state_dir/ignored-configs" + work_target=$(readlink -m "$work_dir") + config_path_target="$work_target/.mise.toml" + config_target=$(readlink -m "$mise_config") + + if [[ -d $ignored_configs_dir ]]; then + for ignored_entry in "$ignored_configs_dir"/*; do + [[ -L $ignored_entry ]] || continue + ignored_target=$(readlink "$ignored_entry") + if [[ $ignored_target == $work_target || $ignored_target == $config_path_target || $ignored_target == $config_target ]]; then + was_ignored=true + break + fi + done + fi + + if [[ $was_ignored == "false" ]]; then + # Normal Mise trust is recorded against the config-root directory, while + # paranoid trust is recorded against the file and its contents. Stage an + # empty, inert config when the legacy file is gone so either trust mode can + # resolve and revoke the original grant. + remove_empty_mise_config=false + if [[ ! -e $mise_config && ! -L $mise_config ]]; then + if (set -o noclobber; : >"$mise_config") 2>/dev/null; then + remove_empty_mise_config=true + fi + fi + + untrust_target="$work_dir" + if [[ -f $mise_config ]]; then + untrust_target="$mise_config" + fi + + if mise trust --untrust "$untrust_target"; then + : + else + if [[ $remove_empty_mise_config == "true" ]]; then + rm -f -- "$mise_config" + fi + exit 1 + fi + + if [[ $remove_empty_mise_config == "true" ]]; then + rm -f -- "$mise_config" + fi + fi +fi + +if [[ -f $mise_config ]]; then + if [[ ! -L $mise_config && $(sha256sum "$mise_config" | cut -d ' ' -f 1) == $stock_sha ]]; then + rm -f -- "$mise_config" + else + unsafe_env_paths=$(sed -n -E "\\%$env_section%,\\%$any_section% { \\%$unsafe_path%p; }" "$mise_config") + if [[ -n $unsafe_env_paths ]]; then + backup=$(mktemp "$mise_config.bak.XXXXXX") + cp -p -- "$mise_config" "$backup" + sed --follow-symlinks -i -E "\\%$env_section%,\\%$any_section% { \\%$unsafe_path%d; }" "$mise_config" + + printf '\n%s\n' \ + "Automatic project bin directories were removed from your Mise PATH." \ + "Your other Mise settings were preserved." + printf '\nBackup saved to:\n %s\n' "$backup" + fi + fi +fi + +if [[ -f $mise_config ]]; then + if [[ $was_ignored == "true" ]]; then + printf '\n%s\n' "This custom config remains ignored by Mise." + else + printf '\n%s\n %s\n' \ + "Mise trust for this custom config was revoked. Review it before trusting it again:" \ + "mise trust $mise_config" + fi +fi + +if [[ $remove_empty_work_dir == "true" ]]; then + rmdir "$work_dir" 2>/dev/null || true +fi diff --git a/test/shell.d/mise-work-path-test.sh b/test/shell.d/mise-work-path-test.sh new file mode 100644 index 000000000000..9c50b91b2540 --- /dev/null +++ b/test/shell.d/mise-work-path-test.sh @@ -0,0 +1,270 @@ +#!/bin/bash + +set -euo pipefail +source "$(dirname "${BASH_SOURCE[0]}")/base-test.sh" + +require_command mise + +test_dir=$(mktemp -d) +trap 'rm -rf "$test_dir"' EXIT +migration="$ROOT/migrations/1789095456.sh" + +run_migration() { + local test_home="$1" + + env -i \ + HOME="$test_home" \ + XDG_CACHE_HOME="$test_home/.cache" \ + XDG_CONFIG_HOME="$test_home/.config" \ + XDG_DATA_HOME="$test_home/.local/share" \ + XDG_STATE_HOME="$test_home/.local/state" \ + MISE_PARANOID="${OMARCHY_TEST_MISE_PARANOID:-false}" \ + PATH=/usr/bin \ + bash -euo pipefail "$migration" +} + +run_mise() { + local test_home="$1" + shift + + env -i \ + HOME="$test_home" \ + XDG_CACHE_HOME="$test_home/.cache" \ + XDG_CONFIG_HOME="$test_home/.config" \ + XDG_DATA_HOME="$test_home/.local/share" \ + XDG_STATE_HOME="$test_home/.local/state" \ + MISE_PARANOID="${OMARCHY_TEST_MISE_PARANOID:-false}" \ + PATH=/usr/bin \ + mise "$@" +} + +mise_environment() { + local test_home="$1" + local project="$2" + + ( + cd "$project" + run_mise "$test_home" env -s bash + ) +} + +mise_path_active() { + local test_home="$1" + local project="$2" + local output + + if ! output=$(mise_environment "$test_home" "$project" 2>/dev/null); then + return 1 + fi + + grep -F "$project/bin" <<<"$output" >/dev/null +} + +assert_unsafe_variant_removed() { + local variant="$1" + local assignment="$2" + local variant_home="$test_dir/$variant-home" + local variant_config="$variant_home/Work/.mise.toml" + local variant_project="$variant_home/Work/tries/untrusted-repository" + + mkdir -p "$variant_project/bin" + printf '[env]\n%s\n' "$assignment" >"$variant_config" + run_mise "$variant_home" trust "$variant_config" >/dev/null + + mise_path_active "$variant_home" "$variant_project" || fail "$variant legacy config prepends the repository bin directory" + + run_migration "$variant_home" >/dev/null + if mise_path_active "$variant_home" "$variant_project"; then + fail "$variant repository bin directory remains in PATH after migration" + fi +} + +install_home="$test_dir/install-home" +install_log="$test_dir/install-mise.log" +mkdir -p "$install_home" "$test_dir/bin" +cat >"$test_dir/bin/mise" <<'SH' +#!/bin/bash +printf '%s\n' "$*" >>"$MISE_TEST_LOG" +SH +chmod +x "$test_dir/bin/mise" + +env \ + HOME="$install_home" \ + MISE_TEST_LOG="$install_log" \ + OMARCHY_SETUP_CONTEXT=runtime \ + PATH="$test_dir/bin:/usr/bin" \ + bash -euo pipefail -c 'source "$1"' bash "$ROOT/install/user/mise-work.sh" + +[[ -d $install_home/Work/tries ]] || fail "installer creates the work and tries directories" +[[ ! -e $install_home/Work/.mise.toml ]] || fail "installer does not create a trusted Work Mise config" +[[ $(<"$install_log") == "use -g node@latest" ]] || fail "installer only invokes Mise for the global Node setup" +pass "new installs do not add project bin directories to PATH" + +stock_home="$test_dir/stock-home" +stock_config="$stock_home/Work/.mise.toml" +stock_project="$stock_home/Work/tries/untrusted-repository" +mkdir -p "$stock_project/bin" +cat >"$stock_config" <<'TOML' +[env] +_.path = "{{ cwd }}/bin" +TOML +run_mise "$stock_home" trust "$stock_config" >/dev/null + +mise_path_active "$stock_home" "$stock_project" || fail "legacy config prepends the repository bin directory" + +run_migration "$stock_home" >/dev/null +[[ ! -e $stock_config ]] || fail "migration removes the stock Work Mise config" +cat >"$stock_config" <<'TOML' +[env] +_.path = "{{ cwd }}/bin" +TOML +if mise_path_active "$stock_home" "$stock_project"; then + fail "recreated Work config remains trusted after migration" +fi +run_migration "$stock_home" >/dev/null +[[ ! -e $stock_config ]] || fail "stock migration is idempotent" +pass "migration removes the repository bin directory and revokes the Work trust root" + +assert_unsafe_variant_removed inline-comment '_.path = "{{ cwd }}/bin" # Omarchy default' +assert_unsafe_variant_removed single-quoted "_.path = '{{ cwd }}/bin'" +pass "migration removes annotated and single-quoted project bin paths" + +custom_home="$test_dir/custom-home" +custom_config="$custom_home/Work/.mise.toml" +mkdir -p "$(dirname "$custom_config")" +cat >"$custom_config" <<'TOML' +[env] +KEEP = "yes" + _.path = "{{ cwd }}/bin" +# _.path = "{{ cwd }}/bin" + +[tools] +ruby = "latest" + +[other] +_.path = "{{ cwd }}/bin" +TOML +cp "$custom_config" "$test_dir/custom-original" +cat >"$test_dir/custom-expected" <<'TOML' +[env] +KEEP = "yes" +# _.path = "{{ cwd }}/bin" + +[tools] +ruby = "latest" + +[other] +_.path = "{{ cwd }}/bin" +TOML +chmod 600 "$custom_config" +run_mise "$custom_home" trust "$custom_config" >/dev/null + +custom_output=$(run_migration "$custom_home") +cmp -s "$test_dir/custom-expected" "$custom_config" || fail "migration preserves unrelated custom Mise settings" +[[ $(stat -c %a "$custom_config") == "600" ]] || fail "migration preserves custom config permissions" +grep -F "mise trust $custom_config" <<<"$custom_output" >/dev/null || fail "migration explains how to review and re-trust a custom config" +custom_backups=("$custom_config".bak.*) +[[ -f ${custom_backups[0]} ]] || fail "migration backs up a customized Mise config" +(( ${#custom_backups[@]} == 1 )) || fail "migration creates one custom config backup" +cmp -s "$test_dir/custom-original" "${custom_backups[0]}" || fail "custom config backup preserves the original" + +run_migration "$custom_home" >/dev/null +custom_backups=("$custom_config".bak.*) +(( ${#custom_backups[@]} == 1 )) || fail "custom migration does not create another backup on rerun" +cmp -s "$test_dir/custom-expected" "$custom_config" || fail "custom migration is idempotent" +pass "custom Mise settings, permissions, and original backup survive the repair" + +unrelated_home="$test_dir/unrelated-home" +unrelated_config="$unrelated_home/Work/.mise.toml" +unrelated_project="$unrelated_home/Work/tries/untrusted-repository" +mkdir -p "$unrelated_project/bin" +printf '[env]\nKEEP = "yes"\n' >"$unrelated_config" +cp "$unrelated_config" "$test_dir/unrelated-original" +run_mise "$unrelated_home" trust "$unrelated_config" >/dev/null +run_migration "$unrelated_home" >/dev/null +cmp -s "$test_dir/unrelated-original" "$unrelated_config" || fail "unrelated Mise config remains unchanged" +unrelated_backups=("$unrelated_config".bak.*) +[[ ! -e ${unrelated_backups[0]} ]] || fail "unchanged Mise config is not backed up" +printf '[env]\n_.path = "{{ cwd }}/bin"\n' >"$unrelated_config" +if mise_path_active "$unrelated_home" "$unrelated_project"; then + fail "safe Work config retains its old trust grant" +fi + +absent_home="$test_dir/absent-home" +absent_config="$absent_home/Work/.mise.toml" +absent_project="$absent_home/Work/tries/untrusted-repository" +mkdir -p "$(dirname "$absent_config")" +printf '[env]\n_.path = "{{ cwd }}/bin"\n' >"$absent_config" +run_mise "$absent_home" trust "$absent_config" >/dev/null +rm "$absent_config" +rmdir "$absent_home/Work" +run_migration "$absent_home" >/dev/null +[[ ! -e $absent_home/Work ]] || fail "migration does not retain a temporary Work directory" +mkdir -p "$absent_project/bin" +printf '[env]\n_.path = "{{ cwd }}/bin"\n' >"$absent_config" +if mise_path_active "$absent_home" "$absent_project"; then + fail "deleted Work directory retains its stale trust grant" +fi +pass "migration leaves unrelated configs alone and revokes dangling Work trust" + +paranoid_home="$test_dir/paranoid-home" +paranoid_work="$paranoid_home/Work" +paranoid_config="$paranoid_work/.mise.toml" +paranoid_project="$paranoid_work/tries/untrusted-repository" +mkdir -p "$paranoid_project/bin" +printf '[env]\n_.path = "{{ cwd }}/bin"\n' >"$paranoid_config" +OMARCHY_TEST_MISE_PARANOID=true run_mise "$paranoid_home" trust "$paranoid_config" >/dev/null +OMARCHY_TEST_MISE_PARANOID=true mise_path_active "$paranoid_home" "$paranoid_project" || fail "paranoid legacy config prepends the repository bin directory" +rm -r "$paranoid_work" + +OMARCHY_TEST_MISE_PARANOID=true run_migration "$paranoid_home" >/dev/null +[[ ! -e $paranoid_work ]] || fail "paranoid migration removes its temporary Work directory" +mkdir -p "$paranoid_project/bin" +printf '[env]\n_.path = "{{ cwd }}/bin"\n' >"$paranoid_config" +if OMARCHY_TEST_MISE_PARANOID=true mise_path_active "$paranoid_home" "$paranoid_project"; then + fail "paranoid migration retains content-bound trust for the deleted legacy config" +fi +pass "migration revokes stale content-bound trust in Mise paranoid mode" + +ignored_home="$test_dir/ignored-home" +ignored_config="$ignored_home/Work/.mise.toml" +ignored_project="$ignored_home/Work/tries/untrusted-repository" +mkdir -p "$ignored_project/bin" +cat >"$ignored_config" <<'TOML' +[env] +_.path = "{{ cwd }}/bin" +KEEP = "yes" +TOML +run_mise "$ignored_home" trust "$ignored_config" >/dev/null +run_mise "$ignored_home" trust --ignore "$ignored_config" >/dev/null + +ignored_output=$(run_migration "$ignored_home") +grep -F '{{ cwd }}/bin' "$ignored_config" >/dev/null && fail "ignored config retains the unsafe path" +grep -Fx 'KEEP = "yes"' "$ignored_config" >/dev/null || fail "ignored config keeps unrelated settings" +ignored_entries=("$ignored_home/.local/state/mise/ignored-configs/"*) +[[ -L ${ignored_entries[0]} ]] || fail "migration preserves the explicit Mise ignore marker" +(( ${#ignored_entries[@]} == 1 )) || fail "migration preserves exactly one Mise ignore marker" +ignored_target=$(readlink "${ignored_entries[0]}") +[[ $ignored_target == $ignored_home/Work || $ignored_target == $ignored_config ]] || fail "preserved Mise ignore marker still targets the Work config" +grep -F "remains ignored by Mise" <<<"$ignored_output" >/dev/null || fail "migration reports that the custom config remains ignored" +if mise_path_active "$ignored_home" "$ignored_project"; then + fail "ignored config becomes active after migration" +fi +pass "migration preserves an explicit decision to ignore the Work config" + +symlink_home="$test_dir/symlink-home" +symlink_config="$symlink_home/Work/.mise.toml" +symlink_target="$test_dir/dotfiles-mise.toml" +mkdir -p "$(dirname "$symlink_config")" +cat >"$symlink_target" <<'TOML' +[env] +_.path = "{{ cwd }}/bin" +KEEP = "yes" +TOML +ln -s "$symlink_target" "$symlink_config" + +run_migration "$symlink_home" >/dev/null +[[ -L $symlink_config ]] || fail "migration preserves a dotfile symlink" +grep -F '{{ cwd }}/bin' "$symlink_target" >/dev/null && fail "symlink target retains the unsafe path" +grep -Fx 'KEEP = "yes"' "$symlink_target" >/dev/null || fail "symlink target keeps unrelated settings" +pass "custom dotfile symlinks survive the repair" From 8fa9f4d03e02411f62772f2defc2b6139e86d222 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Tue, 15 Sep 2026 12:38:00 -0400 Subject: [PATCH 074/194] Leave Claude browser integration settings unchanged --- bin/omarchy-agent | 2 +- manual/17-ai.md | 2 +- test/shell.d/default-agent-test.sh | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/bin/omarchy-agent b/bin/omarchy-agent index 23d0e2f3bea9..e35bcf04ada9 100755 --- a/bin/omarchy-agent +++ b/bin/omarchy-agent @@ -75,7 +75,7 @@ crush) fi ;; claude) - command=(claude --permission-mode auto --chrome) + command=(claude --permission-mode auto) [[ -n ${prompt:-} ]] && command+=(-- "$prompt") ;; grok) diff --git a/manual/17-ai.md b/manual/17-ai.md index 7f76d4817c0c..24ade4f46627 100644 --- a/manual/17-ai.md +++ b/manual/17-ai.md @@ -26,7 +26,7 @@ To wrap an additional CLI the same way, run `omarchy-mise-install [com Pick your default agent with `omarchy default agent ` or under _Setup > Defaults > Agent_ in the Omarchy Menu (`Super + Space`). If the agent isn't installed yet, picking it installs it first. A fresh Omarchy will invite you to make this choice with a one-time notification. -Choosing Claude also sets up its browser extension for Chromium, Chrome, Brave, Brave Origin, and Edge, and enables browser integration when launched through `omarchy agent`. The extension setup applies to all users and may ask for your system password; cancelling leaves your previous default agent selected. Restart your browser, enable the extension if prompted, and sign in to Claude to finish connecting it. Run `/chrome` in Claude to check the connection. Firefox and Zen do not support this extension. If Claude was already your default before this setup was added, select it again to install the extension. +Choosing Claude also sets up its browser extension for Chromium, Chrome, Brave, Brave Origin, and Edge. The extension setup applies to all users and may ask for your system password; cancelling leaves your previous default agent selected. Restart your browser, enable the extension if prompted, and sign in to Claude to finish connecting it. Run `/chrome` in Claude to check the connection. Firefox and Zen do not support this extension. If Claude was already your default before this setup was added, select it again to install the extension. [Muse Code](https://dev.meta.ai) — Meta's `muse` — uses a preinstalled mise stub like the other agents. Picking it as the default installs Meta's official launcher through mise's HTTP backend. The launcher verifies and updates the native binary for your machine. diff --git a/test/shell.d/default-agent-test.sh b/test/shell.d/default-agent-test.sh index 1ce05582b39c..7fd0609300f9 100644 --- a/test/shell.d/default-agent-test.sh +++ b/test/shell.d/default-agent-test.sh @@ -662,7 +662,7 @@ assert_launch pi pi "Review this project" assert_launch omp omp --auto-approve -- "Review this project" assert_launch opencode opencode --auto --prompt "Review this project" assert_launch ori ori code --interactive --prompt "Review this project" -assert_launch claude claude --permission-mode auto --chrome -- "Review this project" +assert_launch claude claude --permission-mode auto -- "Review this project" assert_launch codex codex --approve-for-me -- "Review this project" assert_launch muse muse --approval-mode never -- "Review this project" assert_launch crush crush run "Review this project" @@ -690,7 +690,7 @@ assert_bypass pi pi assert_bypass omp omp --auto-approve assert_bypass opencode opencode --auto assert_bypass ori ori code -assert_bypass claude claude --permission-mode auto --chrome +assert_bypass claude claude --permission-mode auto assert_bypass codex codex --approve-for-me assert_bypass muse muse --approval-mode never assert_bypass crush crush --yolo From 677e69d4f13e90ee83251d75e7839f76532f97bc Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Tue, 15 Sep 2026 12:40:25 -0400 Subject: [PATCH 075/194] Make Claude browser extension installation best effort --- bin/omarchy-default-agent | 5 ++--- manual/17-ai.md | 2 +- test/shell.d/default-agent-test.sh | 18 ++++++++++++------ 3 files changed, 15 insertions(+), 10 deletions(-) diff --git a/bin/omarchy-default-agent b/bin/omarchy-default-agent index 8c14a4f2ebc9..eb2ef7fb457b 100755 --- a/bin/omarchy-default-agent +++ b/bin/omarchy-default-agent @@ -86,9 +86,8 @@ if ! agent_install; then exit 1 fi -if [[ $agent == "claude" ]] && ! omarchy-install-chromium-claude; then - echo "Could not install the Claude browser extension" >&2 - exit 1 +if [[ $agent == "claude" ]]; then + omarchy-install-chromium-claude 2>/dev/null || true fi mkdir -p "$(dirname "$agent_file")" diff --git a/manual/17-ai.md b/manual/17-ai.md index 24ade4f46627..0d62622d947f 100644 --- a/manual/17-ai.md +++ b/manual/17-ai.md @@ -26,7 +26,7 @@ To wrap an additional CLI the same way, run `omarchy-mise-install [com Pick your default agent with `omarchy default agent ` or under _Setup > Defaults > Agent_ in the Omarchy Menu (`Super + Space`). If the agent isn't installed yet, picking it installs it first. A fresh Omarchy will invite you to make this choice with a one-time notification. -Choosing Claude also sets up its browser extension for Chromium, Chrome, Brave, Brave Origin, and Edge. The extension setup applies to all users and may ask for your system password; cancelling leaves your previous default agent selected. Restart your browser, enable the extension if prompted, and sign in to Claude to finish connecting it. Run `/chrome` in Claude to check the connection. Firefox and Zen do not support this extension. If Claude was already your default before this setup was added, select it again to install the extension. +Choosing Claude also attempts to set up its browser extension for Chromium, Chrome, Brave, Brave Origin, and Edge. The extension setup applies to all users and may ask for your system password; cancelling or a failed extension install still selects and launches Claude. Restart your browser, enable the extension if prompted, and sign in to Claude to finish connecting it. Run `/chrome` in Claude to check the connection. Firefox and Zen do not support this extension. If Claude was already your default before this setup was added, select it again to install the extension. [Muse Code](https://dev.meta.ai) — Meta's `muse` — uses a preinstalled mise stub like the other agents. Picking it as the default installs Meta's official launcher through mise's HTTP backend. The launcher verifies and updates the native binary for your machine. diff --git a/test/shell.d/default-agent-test.sh b/test/shell.d/default-agent-test.sh index 7fd0609300f9..60e630d34c52 100644 --- a/test/shell.d/default-agent-test.sh +++ b/test/shell.d/default-agent-test.sh @@ -25,7 +25,10 @@ mkdir -p "$mock_bin" "$test_home" cat >"$mock_bin/omarchy-install-chromium-claude" <<'SH' #!/bin/bash echo claude-extension >>"$OMARCHY_TEST_STUB_LOG" -[[ ${OMARCHY_TEST_EXTENSION_FAIL:-false} != "true" ]] +if [[ ${OMARCHY_TEST_EXTENSION_FAIL:-false} == "true" ]]; then + echo "Extension installation failed" >&2 + exit 1 +fi SH cat >"$mock_bin/omarchy-notification-send" <<'SH' @@ -440,11 +443,14 @@ pass "default agent selects and opens every supported provider and alias" pass "default agent stores its selection in Omarchy user config" OMARCHY_TEST_AGENT_INSTALLED=true omarchy-default-agent pi -if OMARCHY_TEST_AGENT_INSTALLED=true OMARCHY_TEST_EXTENSION_FAIL=true omarchy-default-agent claude >"$test_tmp/extension-failure" 2>&1; then - fail "Claude selection fails when browser extension installation fails" -fi -[[ $(omarchy-default-agent) == "pi" ]] || fail "extension installation failure preserves the default agent" -pass "extension installation failure preserves the default agent" +: >"$agent_open_log" +OMARCHY_TEST_AGENT_INSTALLED=true OMARCHY_TEST_EXTENSION_FAIL=true omarchy-default-agent claude >"$test_tmp/extension-failure" 2>&1 +[[ $(omarchy-default-agent) == "claude" ]] || fail "extension installation failure still selects Claude" +mapfile -d '' -t agent_open_args <"$agent_open_log" +[[ ${agent_open_args[*]} == "omarchy-agent" ]] || fail "extension installation failure still launches Claude" +[[ ! -s $test_tmp/extension-failure ]] || fail "extension installation failure is silent" +pass "extension installation failure silently continues selecting and launching Claude" +OMARCHY_TEST_AGENT_INSTALLED=true omarchy-default-agent pi : >"$notification_history" : >"$agent_open_log" : >"$terminal_log" From 181ad4b4d399feb7f797fa941150d3c65866a496 Mon Sep 17 00:00:00 2001 From: nunomaduro Date: Wed, 16 Sep 2026 16:56:47 +0100 Subject: [PATCH 076/194] feat: improves php and laravel installation --- bin/omarchy-install-dev-env | 36 +++++------------------------- bin/omarchy-remove-dev-env | 7 +++++- default/omarchy/omarchy-menu.jsonc | 8 +++---- 3 files changed, 15 insertions(+), 36 deletions(-) diff --git a/bin/omarchy-install-dev-env b/bin/omarchy-install-dev-env index 263fd7556371..5dcd819af246 100755 --- a/bin/omarchy-install-dev-env +++ b/bin/omarchy-install-dev-env @@ -12,37 +12,11 @@ if [[ -z $1 ]]; then fi install_php() { - omarchy-pkg-add php composer php-sqlite xdebug + mise tool-alias set php github:nunomaduro/static-php-builds + mise use --global php@latest - # Install Path for Composer - if [[ :$PATH: != *:$HOME/.config/composer/vendor/bin:* ]]; then - echo 'export PATH="$HOME/.config/composer/vendor/bin:$PATH"' >>"$HOME/.bashrc" - source "$HOME/.bashrc" - echo "Added Composer global bin directory to PATH." - else - echo "Composer global bin directory already in PATH." - fi - - # Enable some extensions - local php_ini_path="/etc/php/php.ini" - local extensions_to_enable=( - "bcmath" - "intl" - "iconv" - "openssl" - "pdo_sqlite" - "pdo_mysql" - ) - - # Enable Xdebug - sudo sed -i \ - -e 's/^;zend_extension=xdebug.so/zend_extension=xdebug.so/' \ - -e 's/^;xdebug.mode=debug/xdebug.mode=debug/' \ - /etc/php/conf.d/xdebug.ini - - for ext in "${extensions_to_enable[@]}"; do - sudo sed -i "s/^;extension=${ext}/extension=${ext}/" "$php_ini_path" - done + # Composer's global binaries go to ~/.local/bin, which is already on PATH + mise x php -- composer global config bin-dir "$HOME/.local/bin" } install_node() { @@ -84,7 +58,7 @@ laravel) echo -e "Installing PHP and Laravel...\n" install_php install_node - composer global require laravel/installer + mise x php -- composer global require laravel/installer echo -e "\nYou can now run: laravel new myproject" ;; symfony) diff --git a/bin/omarchy-remove-dev-env b/bin/omarchy-remove-dev-env index a24e7f9e2946..b586ed09292d 100755 --- a/bin/omarchy-remove-dev-env +++ b/bin/omarchy-remove-dev-env @@ -10,6 +10,11 @@ if [[ -z $1 ]]; then fi remove_php() { + mise uninstall php --all + mise rm -g php + mise tool-alias unset php + + # PHP from before it moved to mise omarchy-pkg-drop php composer php-sqlite xdebug } @@ -46,7 +51,7 @@ php) ;; laravel) echo -e "Removing Laravel...\n" - composer global remove laravel/installer 2>/dev/null || true + mise x php -- composer global remove laravel/installer 2>/dev/null || true ;; symfony) echo -e "Removing Symfony CLI...\n" diff --git a/default/omarchy/omarchy-menu.jsonc b/default/omarchy/omarchy-menu.jsonc index 7583d8d8ce95..2ee24576c86c 100644 --- a/default/omarchy/omarchy-menu.jsonc +++ b/default/omarchy/omarchy-menu.jsonc @@ -277,8 +277,8 @@ "install.development.javascript.node": {"icon":"","label":"Node.js","disabled":"[[ -d $HOME/.local/share/mise/installs/node ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-install-dev-env node'"}, "install.development.javascript.bun": {"icon":"","label":"Bun","disabled":"[[ -d $HOME/.local/share/mise/installs/bun ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-install-dev-env bun'"}, "install.development.javascript.deno": {"icon":"","label":"Deno","disabled":"[[ -d $HOME/.local/share/mise/installs/deno ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-install-dev-env deno'"}, - "install.development.php.php": {"icon":"","label":"PHP","disabled":"omarchy-pkg-present php","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-install-dev-env php'"}, - "install.development.php.laravel": {"icon":"","label":"Laravel","disabled":"[[ -x $HOME/.config/composer/vendor/bin/laravel ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-install-dev-env laravel'"}, + "install.development.php.php": {"icon":"","label":"PHP","disabled":"[[ -d $HOME/.local/share/mise/installs/php ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-install-dev-env php'"}, + "install.development.php.laravel": {"icon":"","label":"Laravel","disabled":"[[ -x $HOME/.local/bin/laravel ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-install-dev-env laravel'"}, "install.development.php.symfony": {"icon":"","label":"Symfony","disabled":"omarchy-pkg-present symfony-cli","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-install-dev-env symfony'"}, "install.development.elixir.elixir": {"icon":"","label":"Elixir","disabled":"[[ -d $HOME/.local/share/mise/installs/elixir ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-install-dev-env elixir'"}, "install.development.elixir.phoenix": {"icon":"","label":"Phoenix","disabled":"compgen -G \"$HOME/.mix/archives/phx_new*\"","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-install-dev-env phoenix'"}, @@ -343,8 +343,8 @@ "remove.development.javascript.node": {"icon":"","label":"Node.js","when":"[[ -d $HOME/.local/share/mise/installs/node ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-dev-env node'"}, "remove.development.javascript.bun": {"icon":"","label":"Bun","when":"[[ -d $HOME/.local/share/mise/installs/bun ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-dev-env bun'"}, "remove.development.javascript.deno": {"icon":"","label":"Deno","when":"[[ -d $HOME/.local/share/mise/installs/deno ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-dev-env deno'"}, - "remove.development.php.php": {"icon":"","label":"PHP","when":"omarchy-pkg-present php","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-dev-env php'"}, - "remove.development.php.laravel": {"icon":"","label":"Laravel","when":"[[ -x $HOME/.config/composer/vendor/bin/laravel ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-dev-env laravel'"}, + "remove.development.php.php": {"icon":"","label":"PHP","when":"[[ -d $HOME/.local/share/mise/installs/php ]] || omarchy-pkg-present php","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-dev-env php'"}, + "remove.development.php.laravel": {"icon":"","label":"Laravel","when":"[[ -x $HOME/.local/bin/laravel || -x $HOME/.config/composer/vendor/bin/laravel ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-dev-env laravel'"}, "remove.development.php.symfony": {"icon":"","label":"Symfony","when":"omarchy-pkg-present symfony-cli","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-dev-env symfony'"}, "remove.development.elixir.elixir": {"icon":"","label":"Elixir","when":"[[ -d $HOME/.local/share/mise/installs/elixir ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-dev-env elixir'"}, "remove.development.elixir.phoenix": {"icon":"","label":"Phoenix","when":"[[ -d $HOME/.local/share/mise/installs/elixir ]]","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-remove-dev-env phoenix'"}, From 456af5cc8899b1a67219f9bd7489746441f78daf Mon Sep 17 00:00:00 2001 From: nunomaduro Date: Wed, 16 Sep 2026 17:44:30 +0100 Subject: [PATCH 077/194] chore: removes useless comment --- bin/omarchy-install-dev-env | 1 - 1 file changed, 1 deletion(-) diff --git a/bin/omarchy-install-dev-env b/bin/omarchy-install-dev-env index 5dcd819af246..03577198d6f2 100755 --- a/bin/omarchy-install-dev-env +++ b/bin/omarchy-install-dev-env @@ -15,7 +15,6 @@ install_php() { mise tool-alias set php github:nunomaduro/static-php-builds mise use --global php@latest - # Composer's global binaries go to ~/.local/bin, which is already on PATH mise x php -- composer global config bin-dir "$HOME/.local/bin" } From 486e1cab9b98c9064522741d7bc878f6c93c9497 Mon Sep 17 00:00:00 2001 From: nunomaduro Date: Wed, 16 Sep 2026 20:35:34 +0100 Subject: [PATCH 078/194] fix: removes the laravel binary even when php is already gone Co-Authored-By: Claude Fable 5.1 --- bin/omarchy-remove-dev-env | 3 +++ 1 file changed, 3 insertions(+) diff --git a/bin/omarchy-remove-dev-env b/bin/omarchy-remove-dev-env index b586ed09292d..46bc8459d15a 100755 --- a/bin/omarchy-remove-dev-env +++ b/bin/omarchy-remove-dev-env @@ -52,6 +52,9 @@ php) laravel) echo -e "Removing Laravel...\n" mise x php -- composer global remove laravel/installer 2>/dev/null || true + + # Composer cannot run once PHP is gone, so drop the installer binary directly (new and old bin-dir) + rm -f "$HOME/.local/bin/laravel" "$HOME/.config/composer/vendor/bin/laravel" ;; symfony) echo -e "Removing Symfony CLI...\n" From 85da80dd7c280e99ef333bb2804fe4a7a6c91c7e Mon Sep 17 00:00:00 2001 From: nunomaduro Date: Wed, 16 Sep 2026 20:46:40 +0100 Subject: [PATCH 079/194] chore: removes comment --- bin/omarchy-remove-dev-env | 1 - 1 file changed, 1 deletion(-) diff --git a/bin/omarchy-remove-dev-env b/bin/omarchy-remove-dev-env index 46bc8459d15a..1be245b79a76 100755 --- a/bin/omarchy-remove-dev-env +++ b/bin/omarchy-remove-dev-env @@ -53,7 +53,6 @@ laravel) echo -e "Removing Laravel...\n" mise x php -- composer global remove laravel/installer 2>/dev/null || true - # Composer cannot run once PHP is gone, so drop the installer binary directly (new and old bin-dir) rm -f "$HOME/.local/bin/laravel" "$HOME/.config/composer/vendor/bin/laravel" ;; symfony) From 6d2069230e6d679e846816e03f7de8d242ad0079 Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Tue, 1 Sep 2026 22:23:00 +0100 Subject: [PATCH 080/194] Replace YT6801 DKMS driver --- .../hardware/fix-yt6801-ethernet-adapter.sh | 6 +- install/omarchy-other.packages | 1 - migrations/1788279117.sh | 41 +++++++++++ test/shell.d/yt6801-driver-test.sh | 72 +++++++++++++++++++ 4 files changed, 116 insertions(+), 4 deletions(-) create mode 100644 migrations/1788279117.sh create mode 100644 test/shell.d/yt6801-driver-test.sh diff --git a/install/hardware/fix-yt6801-ethernet-adapter.sh b/install/hardware/fix-yt6801-ethernet-adapter.sh index f88a9cec624b..8dac5db02d9d 100644 --- a/install/hardware/fix-yt6801-ethernet-adapter.sh +++ b/install/hardware/fix-yt6801-ethernet-adapter.sh @@ -1,4 +1,4 @@ -# Install drivers for Motorcomm YT6801 ethernet adapter used by the Slimbook Executive -if lspci | grep -i "YT6801\|Motorcomm.*Ethernet"; then - omarchy-pkg-add yt6801-dkms +# Use the upstream driver for the Motorcomm YT6801 adapter used by the Slimbook Executive. +if [[ -n $(lspci -Dn -d 1f0a:6801) ]]; then + omarchy-pkg-drop yt6801-dkms fi diff --git a/install/omarchy-other.packages b/install/omarchy-other.packages index 4a8b128ff95f..ee7607a7573b 100644 --- a/install/omarchy-other.packages +++ b/install/omarchy-other.packages @@ -42,7 +42,6 @@ thermald webp-pixbuf-loader yay-debug tuxedo-drivers-nocompatcheck-dkms -yt6801-dkms zram-generator # Intel encoding processing diff --git a/migrations/1788279117.sh b/migrations/1788279117.sh new file mode 100644 index 000000000000..e7022ce76ab9 --- /dev/null +++ b/migrations/1788279117.sh @@ -0,0 +1,41 @@ +echo "Replace the YT6801 vendor DKMS driver with the upstream kernel driver" + +mapfile -t yt6801_devices < <(lspci -Dn -d 1f0a:6801 | awk '{ print $1 }') + +if (( ${#yt6801_devices[@]} == 0 )); then + omarchy-pkg-drop yt6801-dkms + exit 0 +fi + +for device in "${yt6801_devices[@]}"; do + if [[ ! $device =~ ^[[:xdigit:]]{4}:[[:xdigit:]]{2}:[[:xdigit:]]{2}\.[[:xdigit:]]$ ]]; then + echo "Invalid YT6801 PCI address: $device" >&2 + exit 1 + fi +done + +if ! modinfo -F alias dwmac-motorcomm | grep -Fqx 'pci:v00001F0Ad00006801sv*sd*bc*sc*i*'; then + echo "The running kernel does not provide YT6801 support in dwmac-motorcomm." >&2 + echo "Reboot into the latest Omarchy kernel and rerun omarchy-migrate." >&2 + exit 1 +fi + +# Load and validate the replacement before removing the installed fallback. +sudo modprobe dwmac-motorcomm +omarchy-pkg-drop yt6801-dkms + +if lsmod | awk '$1 == "yt6801" { found = 1 } END { exit !found }'; then + sudo modprobe -r yt6801 + + for device in "${yt6801_devices[@]}"; do + printf '%s\n' "$device" | sudo tee /sys/bus/pci/drivers_probe >/dev/null + done +fi + +for device in "${yt6801_devices[@]}"; do + if ! lspci -Dks "$device" | grep -Eq 'Kernel driver in use: dwmac[-_]motorcomm'; then + echo "YT6801 device $device did not bind to dwmac-motorcomm." >&2 + echo "Reboot and rerun omarchy-migrate." >&2 + exit 1 + fi +done diff --git a/test/shell.d/yt6801-driver-test.sh b/test/shell.d/yt6801-driver-test.sh new file mode 100644 index 000000000000..4f771ed02dbd --- /dev/null +++ b/test/shell.d/yt6801-driver-test.sh @@ -0,0 +1,72 @@ +#!/bin/bash + +source "$(dirname "$0")/base-test.sh" + +test_tmp=$(mktemp -d) +trap 'rm -rf "$test_tmp"' EXIT + +stub_bin="$test_tmp/bin" +calls="$test_tmp/calls" +mkdir -p "$stub_bin" + +cat >"$stub_bin/lspci" <<'SH' +#!/bin/bash +if [[ $* == "-Dn -d 1f0a:6801" ]]; then + printf '%s\n' '0000:01:00.0 0200: 1f0a:6801' +elif [[ $* == "-Dks 0000:01:00.0" ]]; then + printf '%s\n' 'Kernel driver in use: dwmac-motorcomm' +fi +SH + +cat >"$stub_bin/modinfo" <<'SH' +#!/bin/bash +printf '%s\n' 'pci:v00001F0Ad00006801sv*sd*bc*sc*i*' +SH + +cat >"$stub_bin/lsmod" <<'SH' +#!/bin/bash +printf '%s\n' 'yt6801 65536 0' +SH + +for command in modprobe omarchy-pkg-drop tee; do + cat >"$stub_bin/$command" <<'SH' +#!/bin/bash +printf '%s\t%s\n' "${0##*/}" "$*" >>"$TEST_CALLS" +if [[ ${0##*/} == "tee" ]]; then + cat >/dev/null +fi +SH +done + +cat >"$stub_bin/sudo" <<'SH' +#!/bin/bash +printf 'sudo\t%s\n' "$*" >>"$TEST_CALLS" +"$@" +SH + +chmod +x "$stub_bin"/* +export TEST_CALLS="$calls" + +PATH="$stub_bin:$PATH" bash "$ROOT/install/hardware/fix-yt6801-ethernet-adapter.sh" +grep -Fqx $'omarchy-pkg-drop\tyt6801-dkms' "$calls" || + fail "hardware setup did not remove the vendor DKMS package" +if grep -Fq $'modprobe\t' "$calls"; then + fail "hardware setup tried to load a module against the installer kernel" +fi + +: >"$calls" +PATH="$stub_bin:$PATH" bash -euo pipefail "$ROOT/migrations/1788279117.sh" +grep -Fqx $'sudo\tmodprobe dwmac-motorcomm' "$calls" || + fail "migration did not validate-load the upstream driver" +grep -Fqx $'omarchy-pkg-drop\tyt6801-dkms' "$calls" || + fail "migration did not remove the vendor DKMS package" +grep -Fqx $'sudo\tmodprobe -r yt6801' "$calls" || + fail "migration did not unload the vulnerable driver" +grep -Fqx $'sudo\ttee /sys/bus/pci/drivers_probe' "$calls" || + fail "migration did not reprobe the YT6801 device" + +if grep -Fxq 'yt6801-dkms' "$ROOT/install/omarchy-other.packages"; then + fail "default package list still installs yt6801-dkms" +fi + +pass "YT6801 installs and migrations use the upstream kernel driver" From ea21c37d986af8faf4f600639a93c46fbd63631a Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Thu, 3 Sep 2026 11:23:00 +0100 Subject: [PATCH 081/194] Make YT6801 migration retry-safe --- migrations/1788279117.sh | 8 +++++--- test/shell.d/yt6801-driver-test.sh | 32 ++++++++++++++++++++++++++---- 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/migrations/1788279117.sh b/migrations/1788279117.sh index e7022ce76ab9..a154e2698f92 100644 --- a/migrations/1788279117.sh +++ b/migrations/1788279117.sh @@ -26,11 +26,13 @@ omarchy-pkg-drop yt6801-dkms if lsmod | awk '$1 == "yt6801" { found = 1 } END { exit !found }'; then sudo modprobe -r yt6801 +fi - for device in "${yt6801_devices[@]}"; do +for device in "${yt6801_devices[@]}"; do + if ! lspci -Dks "$device" | grep -Eq 'Kernel driver in use: dwmac[-_]motorcomm'; then printf '%s\n' "$device" | sudo tee /sys/bus/pci/drivers_probe >/dev/null - done -fi + fi +done for device in "${yt6801_devices[@]}"; do if ! lspci -Dks "$device" | grep -Eq 'Kernel driver in use: dwmac[-_]motorcomm'; then diff --git a/test/shell.d/yt6801-driver-test.sh b/test/shell.d/yt6801-driver-test.sh index 4f771ed02dbd..857a9680ac79 100644 --- a/test/shell.d/yt6801-driver-test.sh +++ b/test/shell.d/yt6801-driver-test.sh @@ -14,7 +14,11 @@ cat >"$stub_bin/lspci" <<'SH' if [[ $* == "-Dn -d 1f0a:6801" ]]; then printf '%s\n' '0000:01:00.0 0200: 1f0a:6801' elif [[ $* == "-Dks 0000:01:00.0" ]]; then - printf '%s\n' 'Kernel driver in use: dwmac-motorcomm' + if [[ -e $TEST_BOUND_STATE ]]; then + printf '%s\n' 'Kernel driver in use: dwmac-motorcomm' + else + printf '%s\n' 'Kernel modules: dwmac-motorcomm' + fi fi SH @@ -25,7 +29,7 @@ SH cat >"$stub_bin/lsmod" <<'SH' #!/bin/bash -printf '%s\n' 'yt6801 65536 0' +[[ ${TEST_VENDOR_LOADED:-1} == 1 ]] && printf '%s\n' 'yt6801 65536 0' SH for command in modprobe omarchy-pkg-drop tee; do @@ -34,6 +38,7 @@ for command in modprobe omarchy-pkg-drop tee; do printf '%s\t%s\n' "${0##*/}" "$*" >>"$TEST_CALLS" if [[ ${0##*/} == "tee" ]]; then cat >/dev/null + touch "$TEST_BOUND_STATE" fi SH done @@ -46,6 +51,7 @@ SH chmod +x "$stub_bin"/* export TEST_CALLS="$calls" +export TEST_BOUND_STATE="$test_tmp/upstream-bound" PATH="$stub_bin:$PATH" bash "$ROOT/install/hardware/fix-yt6801-ethernet-adapter.sh" grep -Fqx $'omarchy-pkg-drop\tyt6801-dkms' "$calls" || @@ -55,7 +61,7 @@ if grep -Fq $'modprobe\t' "$calls"; then fi : >"$calls" -PATH="$stub_bin:$PATH" bash -euo pipefail "$ROOT/migrations/1788279117.sh" +TEST_VENDOR_LOADED=1 PATH="$stub_bin:$PATH" bash -euo pipefail "$ROOT/migrations/1788279117.sh" grep -Fqx $'sudo\tmodprobe dwmac-motorcomm' "$calls" || fail "migration did not validate-load the upstream driver" grep -Fqx $'omarchy-pkg-drop\tyt6801-dkms' "$calls" || @@ -65,8 +71,26 @@ grep -Fqx $'sudo\tmodprobe -r yt6801' "$calls" || grep -Fqx $'sudo\ttee /sys/bus/pci/drivers_probe' "$calls" || fail "migration did not reprobe the YT6801 device" +# A failed first cutover can leave the vendor module unloaded and the device +# unbound. Rerunning must still reprobe instead of repeating the same failure. +: >"$calls" +rm -f "$TEST_BOUND_STATE" +TEST_VENDOR_LOADED=0 PATH="$stub_bin:$PATH" bash -euo pipefail "$ROOT/migrations/1788279117.sh" +if grep -Fqx $'sudo\tmodprobe -r yt6801' "$calls"; then + fail "retry tried to unload a vendor module that was already absent" +fi +grep -Fqx $'sudo\ttee /sys/bus/pci/drivers_probe' "$calls" || + fail "retry did not reprobe an unbound YT6801 device" +[[ -e $TEST_BOUND_STATE ]] || fail "retry did not restore the upstream binding" + +: >"$calls" +TEST_VENDOR_LOADED=0 PATH="$stub_bin:$PATH" bash -euo pipefail "$ROOT/migrations/1788279117.sh" +if grep -Fq $'sudo\ttee /sys/bus/pci/drivers_probe' "$calls"; then + fail "settled migration unnecessarily reprobed an already-bound device" +fi + if grep -Fxq 'yt6801-dkms' "$ROOT/install/omarchy-other.packages"; then fail "default package list still installs yt6801-dkms" fi -pass "YT6801 installs and migrations use the upstream kernel driver" +pass "YT6801 installs and retry-safe migrations use the upstream kernel driver" From 71be7b16afe9f06109a00136f0130eb8f22ef4b7 Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Sun, 6 Sep 2026 21:44:26 +0100 Subject: [PATCH 082/194] Propagate package discovery failures before removal --- bin/omarchy-pkg-drop | 11 +++++++++-- test/shell.d/pkg-drop-test.sh | 25 ++++++++++++++++++++++++- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/bin/omarchy-pkg-drop b/bin/omarchy-pkg-drop index bfb70598fb84..7b173c8de9d3 100755 --- a/bin/omarchy-pkg-drop +++ b/bin/omarchy-pkg-drop @@ -8,9 +8,16 @@ installed=() declare -A installed_exact=() declare -A selected=() +if ! installed_packages=$(pacman -Qq); then + echo "Unable to query installed packages; no packages were removed." >&2 + exit 1 +fi + while IFS= read -r package_name; do - installed_exact[$package_name]=1 -done < <(pacman -Qq) + if [[ -n $package_name ]]; then + installed_exact[$package_name]=1 + fi +done <<< "$installed_packages" for pkg in "$@"; do if [[ -n ${installed_exact[$pkg]} && -z ${selected[$pkg]} ]]; then diff --git a/test/shell.d/pkg-drop-test.sh b/test/shell.d/pkg-drop-test.sh index e15fd5c712be..379c60b57b3a 100755 --- a/test/shell.d/pkg-drop-test.sh +++ b/test/shell.d/pkg-drop-test.sh @@ -13,13 +13,17 @@ mkdir -p "$mock_path" cat >"$mock_path/pacman" <<'EOF' #!/bin/bash if [[ $1 == "-Qq" ]]; then - printf '%s\n' exact-package provider-package + if [[ ${TEST_PACKAGES_EMPTY:-0} == "0" ]]; then + printf '%s\n' exact-package provider-package + fi + exit "${TEST_QUERY_STATUS:-0}" fi EOF cat >"$mock_path/sudo" <<'EOF' #!/bin/bash printf '%s\n' "$*" >"$TEST_TMP/pkg-drop-command" +exit "${TEST_REMOVE_STATUS:-0}" EOF chmod +x "$mock_path/pacman" "$mock_path/sudo" @@ -30,3 +34,22 @@ PATH="$mock_path:$PATH" TEST_TMP="$test_tmp" \ [[ $(<"$test_tmp/pkg-drop-command") == "pacman -Rns --noconfirm exact-package provider-package" ]] || fail "package removal targets exact installed names only" pass "package removal ignores providers and duplicate arguments" + +rm "$test_tmp/pkg-drop-command" +if PATH="$mock_path:$PATH" TEST_TMP="$test_tmp" TEST_QUERY_STATUS=1 \ + "$ROOT/bin/omarchy-pkg-drop" exact-package >"$test_tmp/output" 2>&1; then + fail "failed package discovery must fail removal even with partial output" +fi +[[ ! -e $test_tmp/pkg-drop-command ]] || fail "failed discovery must not request privileges" +pass "package removal propagates discovery errors before requesting privileges" + +PATH="$mock_path:$PATH" TEST_TMP="$test_tmp" TEST_PACKAGES_EMPTY=1 \ + "$ROOT/bin/omarchy-pkg-drop" exact-package +[[ ! -e $test_tmp/pkg-drop-command ]] || fail "empty package database must not request privileges" +pass "an empty package database is a successful no-op" + +if PATH="$mock_path:$PATH" TEST_TMP="$test_tmp" TEST_REMOVE_STATUS=1 \ + "$ROOT/bin/omarchy-pkg-drop" exact-package; then + fail "failed package transaction must fail removal" +fi +pass "package removal propagates transaction failures" From efa476114bbef902afc4d0658808b44f4aa1c66b Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Sun, 6 Sep 2026 21:46:19 +0100 Subject: [PATCH 083/194] Verify YT6801 cutover before retiring the vendor driver --- .../hardware/fix-yt6801-ethernet-adapter.sh | 7 +- migrations/1788279117.sh | 93 ++-- test/shell.d/yt6801-driver-test.sh | 412 +++++++++++++++--- 3 files changed, 418 insertions(+), 94 deletions(-) diff --git a/install/hardware/fix-yt6801-ethernet-adapter.sh b/install/hardware/fix-yt6801-ethernet-adapter.sh index 8dac5db02d9d..e048cc7936c1 100644 --- a/install/hardware/fix-yt6801-ethernet-adapter.sh +++ b/install/hardware/fix-yt6801-ethernet-adapter.sh @@ -1,4 +1,9 @@ # Use the upstream driver for the Motorcomm YT6801 adapter used by the Slimbook Executive. -if [[ -n $(lspci -Dn -d 1f0a:6801) ]]; then +if ! yt6801_devices=$(lspci -Dn -d 1f0a:6801); then + echo "Unable to discover YT6801 adapters." >&2 + return 1 +fi + +if [[ -n $yt6801_devices ]]; then omarchy-pkg-drop yt6801-dkms fi diff --git a/migrations/1788279117.sh b/migrations/1788279117.sh index a154e2698f92..35f3571a9754 100644 --- a/migrations/1788279117.sh +++ b/migrations/1788279117.sh @@ -1,43 +1,86 @@ echo "Replace the YT6801 vendor DKMS driver with the upstream kernel driver" -mapfile -t yt6801_devices < <(lspci -Dn -d 1f0a:6801 | awk '{ print $1 }') - -if (( ${#yt6801_devices[@]} == 0 )); then - omarchy-pkg-drop yt6801-dkms - exit 0 +if ! yt6801_pci=$(lspci -Dn -d 1f0a:6801); then + echo "Unable to discover YT6801 adapters; rerun omarchy-migrate." >&2 + exit 1 fi -for device in "${yt6801_devices[@]}"; do - if [[ ! $device =~ ^[[:xdigit:]]{4}:[[:xdigit:]]{2}:[[:xdigit:]]{2}\.[[:xdigit:]]$ ]]; then +yt6801_devices=() +while read -r device _; do + [[ -n $device ]] || continue + if [[ ! $device =~ ^[[:xdigit:]]{4}:[[:xdigit:]]{2}:[[:xdigit:]]{2}\.[0-7]$ ]]; then echo "Invalid YT6801 PCI address: $device" >&2 exit 1 fi -done + yt6801_devices+=("$device") +done <<< "$yt6801_pci" -if ! modinfo -F alias dwmac-motorcomm | grep -Fqx 'pci:v00001F0Ad00006801sv*sd*bc*sc*i*'; then - echo "The running kernel does not provide YT6801 support in dwmac-motorcomm." >&2 - echo "Reboot into the latest Omarchy kernel and rerun omarchy-migrate." >&2 - exit 1 -fi +yt6801_uses_upstream() { + local driver + driver=$(readlink -f "/sys/bus/pci/devices/$1/driver") && + [[ $driver == "/sys/bus/pci/drivers/dwmac-motorcomm" ]] +} -# Load and validate the replacement before removing the installed fallback. -sudo modprobe dwmac-motorcomm -omarchy-pkg-drop yt6801-dkms +yt6801_check_binding() { + local device + for device in "${yt6801_devices[@]}"; do + if ! yt6801_uses_upstream "$device"; then + echo "YT6801 device $device did not bind to dwmac-motorcomm." >&2 + echo "Reboot into the latest Omarchy kernel and rerun omarchy-migrate." >&2 + exit 1 + fi + done +} -if lsmod | awk '$1 == "yt6801" { found = 1 } END { exit !found }'; then - sudo modprobe -r yt6801 -fi +# Check discovery before changing hardware or packages. A failed query must not +# turn into an empty list and mark the migration complete. +installed_packages=$(pacman -Qq) +loaded_modules=$(lsmod) +yt6801_pending=() for device in "${yt6801_devices[@]}"; do - if ! lspci -Dks "$device" | grep -Eq 'Kernel driver in use: dwmac[-_]motorcomm'; then - printf '%s\n' "$device" | sudo tee /sys/bus/pci/drivers_probe >/dev/null + if ! yt6801_uses_upstream "$device"; then + yt6801_pending+=("$device") fi done -for device in "${yt6801_devices[@]}"; do - if ! lspci -Dks "$device" | grep -Eq 'Kernel driver in use: dwmac[-_]motorcomm'; then - echo "YT6801 device $device did not bind to dwmac-motorcomm." >&2 - echo "Reboot and rerun omarchy-migrate." >&2 +if (( ${#yt6801_pending[@]} > 0 )); then + if ! aliases=$(modinfo -F alias dwmac-motorcomm) || + ! grep -Fxq 'pci:v00001F0Ad00006801sv*sd*bc*sc*i*' <<< "$aliases"; then + echo "The running kernel does not provide YT6801 support in dwmac-motorcomm." >&2 + echo "Reboot into the latest Omarchy kernel and rerun omarchy-migrate." >&2 exit 1 fi + + # Validate the replacement before unloading the installed fallback. Already + # migrated machines need no module load or privilege prompt for later users. + sudo modprobe dwmac-motorcomm +fi + +if grep -Eq '^yt6801[[:space:]]' <<< "$loaded_modules"; then + # rmmod also works on retries after DKMS has deleted the module files and + # lookup index. Never force removal of a module that is still busy. + sudo rmmod yt6801 +fi + +for device in "${yt6801_pending[@]}"; do + if ! yt6801_uses_upstream "$device"; then + printf '%s\n' "$device" | sudo tee /sys/bus/pci/drivers_probe >/dev/null + fi done +yt6801_check_binding + +# Keep the package available until the live cutover succeeds. Package removal +# invokes DKMS/depmod hooks, so unloading must happen before this transaction. +if grep -Fxq 'yt6801-dkms' <<< "$installed_packages"; then + omarchy-pkg-drop yt6801-dkms +fi + +installed_packages=$(pacman -Qq) +loaded_modules=$(lsmod) +if grep -Fxq 'yt6801-dkms' <<< "$installed_packages" || + grep -Eq '^yt6801[[:space:]]' <<< "$loaded_modules"; then + echo "The YT6801 vendor package or module is still present; rerun omarchy-migrate." >&2 + exit 1 +fi +yt6801_check_binding diff --git a/test/shell.d/yt6801-driver-test.sh b/test/shell.d/yt6801-driver-test.sh index 857a9680ac79..db8b12c198bc 100644 --- a/test/shell.d/yt6801-driver-test.sh +++ b/test/shell.d/yt6801-driver-test.sh @@ -1,96 +1,372 @@ #!/bin/bash -source "$(dirname "$0")/base-test.sh" +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" test_tmp=$(mktemp -d) trap 'rm -rf "$test_tmp"' EXIT stub_bin="$test_tmp/bin" -calls="$test_tmp/calls" mkdir -p "$stub_bin" +export TEST_STATE="$test_tmp/state" +export TEST_CALLS="$test_tmp/calls" +export TEST_FAULT="" +export TEST_DEVICE="0000:01:00.0" +export TEST_DEVICE_2="0000:02:00.0" +export PATH="$stub_bin:$PATH" -cat >"$stub_bin/lspci" <<'SH' +# Model kernel state separately from package files: DKMS removal deletes the +# latter and refreshes depmod, but cannot unload the module already in memory. +cat >"$stub_bin/stub" <<'SH' #!/bin/bash -if [[ $* == "-Dn -d 1f0a:6801" ]]; then - printf '%s\n' '0000:01:00.0 0200: 1f0a:6801' -elif [[ $* == "-Dks 0000:01:00.0" ]]; then - if [[ -e $TEST_BOUND_STATE ]]; then - printf '%s\n' 'Kernel driver in use: dwmac-motorcomm' - else - printf '%s\n' 'Kernel modules: dwmac-motorcomm' +set -euo pipefail +command=${0##*/} +printf '%s %s\n' "$command" "$*" >>"$TEST_CALLS" + +case "$command" in + lspci) + [[ $* == "-Dn -d 1f0a:6801" ]] || exit 90 + [[ $TEST_FAULT != "pci-fail" ]] || exit 1 + cat "$TEST_STATE/devices" + [[ $TEST_FAULT != "pci-partial" ]] || exit 1 + ;; + pacman) + if [[ $* == "-Qq" ]]; then + query_count=$(<"$TEST_STATE/queries") + query_count=$((query_count + 1)) + printf '%s\n' "$query_count" >"$TEST_STATE/queries" + printf '%s\n' linux + if [[ -e $TEST_STATE/package ]]; then + printf '%s\n' yt6801-dkms + fi + [[ $TEST_FAULT != "query-fail" ]] || exit 1 + if [[ $TEST_FAULT == "helper-query-fail" ]] && (( query_count == 2 )); then + exit 1 + fi + if [[ $TEST_FAULT == "final-query-fail" ]] && [[ ! -e $TEST_STATE/package ]]; then + exit 1 + fi + elif [[ $* == "-Rns --noconfirm yt6801-dkms" ]]; then + [[ $TEST_FAULT != "remove-fail" ]] || exit 1 + if [[ $TEST_FAULT != "remove-noop" ]]; then + rm -f "$TEST_STATE/package" "$TEST_STATE/module-files" + fi + if [[ $TEST_FAULT == "remove-reload" ]]; then + touch "$TEST_STATE/vendor-loaded" + elif [[ $TEST_FAULT == "remove-unbind" ]]; then + rm -f "$TEST_STATE/bindings/$TEST_DEVICE" + fi + [[ $TEST_FAULT != "remove-interrupt" ]] || exit 1 + else + exit 90 + fi + ;; + lsmod) + [[ $TEST_FAULT != "modules-fail" ]] || exit 1 + if [[ $TEST_FAULT == "final-modules-fail" && ! -e $TEST_STATE/package ]]; then + exit 1 + fi + printf '%s\n' 'Module Size Used by' + if [[ -e $TEST_STATE/vendor-loaded ]]; then + printf '%s\n' 'yt6801 65536 0' + fi + ;; + readlink) + [[ $# == 2 && $1 == "-f" && $2 == /sys/bus/pci/devices/*/driver ]] || exit 90 + device=${2%/driver} + device=${device##*/} + [[ $TEST_FAULT != "binding-read-fail" ]] || exit 1 + if [[ -e $TEST_STATE/bindings/$device ]]; then + printf '/sys/bus/pci/drivers/%s\n' "$(<"$TEST_STATE/bindings/$device")" + else + printf '%s\n' "$2" + fi + ;; + modinfo) + [[ $* == "-F alias dwmac-motorcomm" ]] || exit 90 + [[ $TEST_FAULT != "alias-fail" ]] || exit 1 + if [[ $TEST_FAULT == "alias-wrong" ]]; then + printf '%s\n' 'pci:v00001F0Ad00006802sv*sd*bc*sc*i*' + else + printf '%s\n' 'pci:v00001F0Ad00006801sv*sd*bc*sc*i*' + fi + ;; + modprobe) + # Real modprobe cannot resolve a module through its deleted lookup entry. + if [[ $* == "-r yt6801" ]]; then + [[ -e $TEST_STATE/module-files ]] || exit 1 + exit 90 + fi + [[ $* == "dwmac-motorcomm" ]] || exit 90 + [[ $TEST_FAULT != "load-fail" ]] || exit 1 + if [[ $TEST_FAULT != "load-noop" ]]; then + touch "$TEST_STATE/upstream-loaded" + fi + [[ $TEST_FAULT != "load-interrupt" ]] || exit 1 + ;; + rmmod) + [[ $* == "yt6801" ]] || exit 90 + [[ $TEST_FAULT != "unload-fail" ]] || exit 1 + [[ -e $TEST_STATE/vendor-loaded ]] || exit 1 + if [[ $TEST_FAULT != "unload-noop" ]]; then + rm "$TEST_STATE/vendor-loaded" + for binding in "$TEST_STATE/bindings/"*; do + if [[ -f $binding && $(<"$binding") == "yt6801" ]]; then + rm "$binding" + fi + done + fi + [[ $TEST_FAULT != "unload-interrupt" ]] || exit 1 + ;; + tee) + [[ $* == "/sys/bus/pci/drivers_probe" ]] || exit 90 + read -r device + [[ $device == "$TEST_DEVICE" || $device == "$TEST_DEVICE_2" ]] || exit 90 + [[ $TEST_FAULT != "probe-fail" ]] || exit 1 + if [[ $TEST_FAULT != "probe-noop" && -e $TEST_STATE/upstream-loaded && ! -e $TEST_STATE/bindings/$device ]]; then + if [[ $TEST_FAULT != "second-probe-noop" || $device != "$TEST_DEVICE_2" ]]; then + printf '%s\n' dwmac-motorcomm >"$TEST_STATE/bindings/$device" + fi + fi + [[ $TEST_FAULT != "probe-interrupt" ]] || exit 1 + ;; + sudo) + [[ $TEST_FAULT != "sudo-fail" ]] || exit 1 + case "$*" in + 'modprobe dwmac-motorcomm'|'rmmod yt6801'|'tee /sys/bus/pci/drivers_probe'|'pacman -Rns --noconfirm yt6801-dkms') "$@" ;; + *) exit 90 ;; + esac + ;; + omarchy-notification-dismiss) ;; + *) exit 90 ;; +esac +SH +chmod +x "$stub_bin/stub" +for command in lspci pacman lsmod readlink modinfo modprobe rmmod tee sudo omarchy-notification-dismiss; do + ln -s stub "$stub_bin/$command" +done +ln -s "$ROOT/bin/omarchy-pkg-drop" "$stub_bin/omarchy-pkg-drop" + +reset_state() { + rm -rf "$TEST_STATE" + mkdir -p "$TEST_STATE/bindings" + : >"$TEST_CALLS" + TEST_FAULT="" + printf '%s\n' 0 >"$TEST_STATE/queries" + printf '%s 0200: 1f0a:6801\n' "$TEST_DEVICE" >"$TEST_STATE/devices" + printf '%s\n' yt6801 >"$TEST_STATE/bindings/$TEST_DEVICE" + touch "$TEST_STATE/package" "$TEST_STATE/module-files" "$TEST_STATE/vendor-loaded" +} + +run_migration() { + bash -euo pipefail "$ROOT/migrations/1788279117.sh" >"$test_tmp/output" 2>&1 +} + +assert_complete() { + [[ ! -e $TEST_STATE/package ]] || fail "completed migration left the vendor package installed" + [[ ! -e $TEST_STATE/vendor-loaded ]] || fail "completed migration left the vendor module loaded" + local device rest + while read -r device rest; do + [[ -n $device ]] || continue + [[ -f $TEST_STATE/bindings/$device && $(<"$TEST_STATE/bindings/$device") == "dwmac-motorcomm" ]] || + fail "completed migration left an adapter without the upstream driver" "$device" + done <"$TEST_STATE/devices" +} + +assert_no_privileges() { + if grep -q '^sudo ' "$TEST_CALLS"; then + fail "$1" "$(<"$TEST_CALLS")" fi +} + +reset_state +run_migration +assert_complete +# Enforce the safe ordering across the modeled DKMS package transaction. +[[ $(grep -E '^(modprobe|rmmod|tee|pacman -Rns) ' "$TEST_CALLS") == "$(printf '%s\n' \ + 'modprobe dwmac-motorcomm' 'rmmod yt6801' 'tee /sys/bus/pci/drivers_probe' 'pacman -Rns --noconfirm yt6801-dkms')" ]] || + fail "the replacement must bind before DKMS package removal" +pass "migration cuts over before removing the vendor package and module files" + +: >"$TEST_CALLS" +TEST_FAULT=sudo-fail +run_migration +assert_complete +assert_no_privileges "a later user's completed migration must need no privileges" +if grep -Eq '^(modinfo|modprobe|rmmod|tee) ' "$TEST_CALLS"; then + fail "a completed migration must not need module metadata or reprobe" fi -SH +pass "completed machines need no privileges, module metadata, or reprobe" -cat >"$stub_bin/modinfo" <<'SH' -#!/bin/bash -printf '%s\n' 'pci:v00001F0Ad00006801sv*sd*bc*sc*i*' -SH +reset_state +printf '%s 0200: 1f0a:6801\n' "$TEST_DEVICE_2" >>"$TEST_STATE/devices" +printf '%s\n' yt6801 >"$TEST_STATE/bindings/$TEST_DEVICE_2" +run_migration +assert_complete +pass "every target adapter is rebound and verified" -cat >"$stub_bin/lsmod" <<'SH' -#!/bin/bash -[[ ${TEST_VENDOR_LOADED:-1} == 1 ]] && printf '%s\n' 'yt6801 65536 0' -SH +for fault in pci-fail pci-partial query-fail modules-fail alias-fail alias-wrong; do + reset_state + TEST_FAULT=$fault + if run_migration; then + fail "migration must fail on $fault" + fi + assert_no_privileges "$fault must be detected before changing hardware or packages" + [[ -e $TEST_STATE/package && -e $TEST_STATE/vendor-loaded ]] || fail "$fault lost the installed fallback" + pass "$fault fails before cutover" +done -for command in modprobe omarchy-pkg-drop tee; do - cat >"$stub_bin/$command" <<'SH' -#!/bin/bash -printf '%s\t%s\n' "${0##*/}" "$*" >>"$TEST_CALLS" -if [[ ${0##*/} == "tee" ]]; then - cat >/dev/null - touch "$TEST_BOUND_STATE" +reset_state +printf '%s\n' 'invalid-address 0200: 1f0a:6801' >"$TEST_STATE/devices" +if run_migration; then + fail "malformed PCI enumeration must fail the migration" fi -SH +assert_no_privileges "invalid PCI data must be rejected before privileged work" +pass "invalid PCI addresses cannot reach the reprobe command" + +for fault in sudo-fail load-fail load-noop unload-fail unload-noop probe-fail probe-noop binding-read-fail helper-query-fail remove-fail; do + reset_state + TEST_FAULT=$fault + if run_migration; then + fail "migration must fail on $fault" + fi + [[ -e $TEST_STATE/package ]] || fail "$fault discarded the package before cutover succeeded" + TEST_FAULT="" + run_migration + assert_complete + pass "$fault preserves the package and permits a successful retry" done -cat >"$stub_bin/sudo" <<'SH' -#!/bin/bash -printf 'sudo\t%s\n' "$*" >>"$TEST_CALLS" -"$@" -SH +for fault in remove-noop remove-reload remove-unbind final-query-fail final-modules-fail; do + reset_state + TEST_FAULT=$fault + if run_migration; then + fail "postconditions must detect $fault" + fi + TEST_FAULT="" + run_migration + assert_complete + pass "postconditions detect $fault and a retry completes" +done + +for fault in load-interrupt unload-interrupt probe-interrupt remove-interrupt; do + reset_state + TEST_FAULT=$fault + if run_migration; then + fail "interrupted $fault must fail the migration" + fi + TEST_FAULT="" + run_migration + assert_complete + pass "retry completes after $fault" +done + +reset_state +rm "$TEST_STATE/package" "$TEST_STATE/module-files" +run_migration +assert_complete +pass "retry unloads the vendor module even after an earlier DKMS removal deleted its files" -chmod +x "$stub_bin"/* -export TEST_CALLS="$calls" -export TEST_BOUND_STATE="$test_tmp/upstream-bound" +reset_state +rm "$TEST_STATE/vendor-loaded" "$TEST_STATE/bindings/$TEST_DEVICE" +run_migration +assert_complete +pass "an initially unbound adapter is reprobed without unloading an absent vendor module" -PATH="$stub_bin:$PATH" bash "$ROOT/install/hardware/fix-yt6801-ethernet-adapter.sh" -grep -Fqx $'omarchy-pkg-drop\tyt6801-dkms' "$calls" || - fail "hardware setup did not remove the vendor DKMS package" -if grep -Fq $'modprobe\t' "$calls"; then - fail "hardware setup tried to load a module against the installer kernel" +reset_state +rm "$TEST_STATE/vendor-loaded" +printf '%s\n' dwmac-motorcomm >"$TEST_STATE/bindings/$TEST_DEVICE" +TEST_FAULT=alias-fail +run_migration +assert_complete +pass "an already-bound adapter only needs package cleanup even if module metadata is unavailable" + +reset_state +printf '%s 0200: 1f0a:6801\n' "$TEST_DEVICE_2" >>"$TEST_STATE/devices" +printf '%s\n' yt6801 >"$TEST_STATE/bindings/$TEST_DEVICE_2" +TEST_FAULT=second-probe-noop +if run_migration; then + fail "one working adapter must not hide another adapter's failed cutover" fi +[[ -e $TEST_STATE/package ]] || fail "partial cutover removed the vendor package" +TEST_FAULT="" +run_migration +assert_complete +pass "partial multi-adapter cutover remains pending and can be retried" + +for driver in dwmac-motorcomm-extra dwmac_motorcomm vfio-pci; do + reset_state + rm "$TEST_STATE/vendor-loaded" + printf '%s\n' "$driver" >"$TEST_STATE/bindings/$TEST_DEVICE" + if run_migration; then + fail "unexpected driver $driver must not count as upstream binding" + fi + [[ -e $TEST_STATE/package && $(<"$TEST_STATE/bindings/$TEST_DEVICE") == "$driver" ]] || + fail "failed cutover must preserve an unrelated binding and the package" + pass "exact sysfs binding rejects $driver without forcibly unbinding it" +done + +reset_state +: >"$TEST_STATE/devices" +rm -f "$TEST_STATE/bindings/$TEST_DEVICE" +run_migration +assert_complete +pass "without target hardware, the migration still unloads and removes the vendor driver" -: >"$calls" -TEST_VENDOR_LOADED=1 PATH="$stub_bin:$PATH" bash -euo pipefail "$ROOT/migrations/1788279117.sh" -grep -Fqx $'sudo\tmodprobe dwmac-motorcomm' "$calls" || - fail "migration did not validate-load the upstream driver" -grep -Fqx $'omarchy-pkg-drop\tyt6801-dkms' "$calls" || - fail "migration did not remove the vendor DKMS package" -grep -Fqx $'sudo\tmodprobe -r yt6801' "$calls" || - fail "migration did not unload the vulnerable driver" -grep -Fqx $'sudo\ttee /sys/bus/pci/drivers_probe' "$calls" || - fail "migration did not reprobe the YT6801 device" - -# A failed first cutover can leave the vendor module unloaded and the device -# unbound. Rerunning must still reprobe instead of repeating the same failure. -: >"$calls" -rm -f "$TEST_BOUND_STATE" -TEST_VENDOR_LOADED=0 PATH="$stub_bin:$PATH" bash -euo pipefail "$ROOT/migrations/1788279117.sh" -if grep -Fqx $'sudo\tmodprobe -r yt6801' "$calls"; then - fail "retry tried to unload a vendor module that was already absent" +: >"$TEST_CALLS" +TEST_FAULT=sudo-fail +run_migration +assert_no_privileges "an unaffected machine must need no privileges" +pass "an unaffected machine is a successful no-op" + +# Setup leaves are sourced, and must not inspect/load the live ISO kernel. +reset_state +bash -eE -c 'source "$1"' bash "$ROOT/install/hardware/fix-yt6801-ethernet-adapter.sh" +[[ ! -e $TEST_STATE/package ]] || fail "hardware setup did not remove the vendor package" +if grep -Eq '^(modinfo|modprobe|rmmod|tee) ' "$TEST_CALLS"; then + fail "hardware setup must not manipulate the installer kernel" fi -grep -Fqx $'sudo\ttee /sys/bus/pci/drivers_probe' "$calls" || - fail "retry did not reprobe an unbound YT6801 device" -[[ -e $TEST_BOUND_STATE ]] || fail "retry did not restore the upstream binding" - -: >"$calls" -TEST_VENDOR_LOADED=0 PATH="$stub_bin:$PATH" bash -euo pipefail "$ROOT/migrations/1788279117.sh" -if grep -Fq $'sudo\ttee /sys/bus/pci/drivers_probe' "$calls"; then - fail "settled migration unnecessarily reprobed an already-bound device" +pass "fresh setup removes the package independently of the ISO kernel" + +for fault in pci-fail pci-partial query-fail remove-fail; do + reset_state + TEST_FAULT=$fault + if bash -eE -c 'source "$1"' bash "$ROOT/install/hardware/fix-yt6801-ethernet-adapter.sh" >"$test_tmp/output" 2>&1; then + fail "hardware setup must fail on $fault" + fi + [[ -e $TEST_STATE/package ]] || fail "failed setup unexpectedly removed the package" + pass "fresh setup propagates $fault" +done + +reset_state +: >"$TEST_STATE/devices" +bash -eE -c 'source "$1"' bash "$ROOT/install/hardware/fix-yt6801-ethernet-adapter.sh" +assert_no_privileges "setup without target hardware must need no privileges" +pass "fresh setup skips machines without target hardware" + +# Exercise the real runner's completion markers and queue, without using the +# current user's state directory or running any other repository migrations. +reset_state +mkdir -p "$test_tmp/omarchy/migrations" +ln -s "$ROOT/migrations/1788279117.sh" "$test_tmp/omarchy/migrations/1788279117.sh" +printf '%s\n' 'touch "$TEST_STATE/later-migration"' >"$test_tmp/omarchy/migrations/1788279118.sh" +export OMARCHY_PATH="$test_tmp/omarchy" +export OMARCHY_MIGRATION_STATE="$test_tmp/migration-state" +TEST_FAULT=probe-noop +if "$ROOT/bin/omarchy-migrate" >"$test_tmp/output" 2>&1; then + fail "migration runner must fail when cutover is incomplete" fi +[[ ! -e $OMARCHY_MIGRATION_STATE/1788279117.sh && ! -e $TEST_STATE/later-migration ]] || + fail "failed cutover must not write a completion marker or run later migrations" +TEST_FAULT="" +"$ROOT/bin/omarchy-migrate" >"$test_tmp/output" 2>&1 +assert_complete +[[ -f $OMARCHY_MIGRATION_STATE/1788279117.sh && -f $TEST_STATE/later-migration ]] || + fail "successful retry must mark completion and continue the queue" +pass "the real migration runner keeps failures pending and completes successful retries" if grep -Fxq 'yt6801-dkms' "$ROOT/install/omarchy-other.packages"; then fail "default package list still installs yt6801-dkms" fi - -pass "YT6801 installs and retry-safe migrations use the upstream kernel driver" +pass "the default package list no longer installs the vendor driver" From 824be4b5241b025d2c5aa545f5456b4ea36cc52a Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Tue, 8 Sep 2026 00:30:32 +0100 Subject: [PATCH 084/194] Keep YT6801 fallback through hardware reruns --- .../hardware/fix-yt6801-ethernet-adapter.sh | 13 +++------ test/shell.d/yt6801-driver-test.sh | 29 +++++-------------- 2 files changed, 11 insertions(+), 31 deletions(-) diff --git a/install/hardware/fix-yt6801-ethernet-adapter.sh b/install/hardware/fix-yt6801-ethernet-adapter.sh index e048cc7936c1..89997bec3dc8 100644 --- a/install/hardware/fix-yt6801-ethernet-adapter.sh +++ b/install/hardware/fix-yt6801-ethernet-adapter.sh @@ -1,9 +1,4 @@ -# Use the upstream driver for the Motorcomm YT6801 adapter used by the Slimbook Executive. -if ! yt6801_devices=$(lspci -Dn -d 1f0a:6801); then - echo "Unable to discover YT6801 adapters." >&2 - return 1 -fi - -if [[ -n $yt6801_devices ]]; then - omarchy-pkg-drop yt6801-dkms -fi +# Fresh installs use the kernel's upstream dwmac-motorcomm driver and do not +# install yt6801-dkms. Existing systems retire that fallback in migration +# 1788279117 only after proving the running kernel alias and every live binding; +# a manual hardware-setup rerun must not remove it ahead of that cutover. diff --git a/test/shell.d/yt6801-driver-test.sh b/test/shell.d/yt6801-driver-test.sh index db8b12c198bc..8039318931f1 100644 --- a/test/shell.d/yt6801-driver-test.sh +++ b/test/shell.d/yt6801-driver-test.sh @@ -320,30 +320,15 @@ run_migration assert_no_privileges "an unaffected machine must need no privileges" pass "an unaffected machine is a successful no-op" -# Setup leaves are sourced, and must not inspect/load the live ISO kernel. +# Setup leaves are sourced. A manual rerun on an old or partially migrated +# system must leave the fallback in place for the migration's proven cutover. reset_state bash -eE -c 'source "$1"' bash "$ROOT/install/hardware/fix-yt6801-ethernet-adapter.sh" -[[ ! -e $TEST_STATE/package ]] || fail "hardware setup did not remove the vendor package" -if grep -Eq '^(modinfo|modprobe|rmmod|tee) ' "$TEST_CALLS"; then - fail "hardware setup must not manipulate the installer kernel" -fi -pass "fresh setup removes the package independently of the ISO kernel" - -for fault in pci-fail pci-partial query-fail remove-fail; do - reset_state - TEST_FAULT=$fault - if bash -eE -c 'source "$1"' bash "$ROOT/install/hardware/fix-yt6801-ethernet-adapter.sh" >"$test_tmp/output" 2>&1; then - fail "hardware setup must fail on $fault" - fi - [[ -e $TEST_STATE/package ]] || fail "failed setup unexpectedly removed the package" - pass "fresh setup propagates $fault" -done - -reset_state -: >"$TEST_STATE/devices" -bash -eE -c 'source "$1"' bash "$ROOT/install/hardware/fix-yt6801-ethernet-adapter.sh" -assert_no_privileges "setup without target hardware must need no privileges" -pass "fresh setup skips machines without target hardware" +[[ -e $TEST_STATE/package && -e $TEST_STATE/vendor-loaded ]] || + fail "manual hardware setup retired the YT6801 fallback" +[[ ! -s $TEST_CALLS ]] || + fail "manual hardware setup performed package, discovery, or module work" "$(cat "$TEST_CALLS")" +pass "manual hardware setup leaves the vendor fallback for the proven migration cutover" # Exercise the real runner's completion markers and queue, without using the # current user's state directory or running any other repository migrations. From 3eb314231358c4206d51a818df98ffb18136e7a4 Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Wed, 16 Sep 2026 22:55:37 +0100 Subject: [PATCH 085/194] Recognize legacy sudo grants for any account name The legacy command wrote the caller's unvalidated name into both the sudoers filename and the rule. Cleanup applied the current lower-case account pattern to that suffix, so an exact legacy grant for an account such as Alice was classified as administrator policy, left active, and the machine-wide migration marker was written anyway. Match a legacy grant by its exact filename and rule relationship instead of the account policy, and cover it in the lifecycle suite through both the unit cleanup and the real migration runner. The account pattern itself stays lower-case: sudoers reads an upper-case word such as ALICE as a User_Alias reference, and ALL as every user, so such names must never reach the generated rule. Pin that with a test. Co-Authored-By: Claude Fable 5.1 --- bin/omarchy-sudo-passwordless | 31 +++++++++++-------- docs/passwordless-sudo.md | 2 +- test/shell.d/nopasswd-sudo-expiry-test.sh | 7 +++-- .../passwordless-grant-lifecycle-test.sh | 12 +++++-- 4 files changed, 34 insertions(+), 18 deletions(-) diff --git a/bin/omarchy-sudo-passwordless b/bin/omarchy-sudo-passwordless index 91695c69e1ff..3b0af89de855 100755 --- a/bin/omarchy-sudo-passwordless +++ b/bin/omarchy-sudo-passwordless @@ -56,9 +56,10 @@ resolve_account() { entry=$(/usr/bin/getent passwd "$((10#$uid))") || return 1 IFS=: read -r ACCOUNT_NAME _ ACCOUNT_UID _ _ _ _ <<<"$entry" [[ $ACCOUNT_UID == "$((10#$uid))" ]] || return 1 - # Sudoers names and the legacy filename both have metacharacters. Omarchy - # accounts use this portable subset; refusing anything else is safer than - # attempting to quote privileged policy syntax. + # Sudoers has metacharacters, and it reads an upper-case word such as ALICE + # as an alias reference rather than a user. Accounts use this portable + # lower-case subset; refusing anything else is safer than attempting to + # quote privileged policy syntax. valid_account_name "$ACCOUNT_NAME" || return 1 ACCOUNT_UID=$((10#$uid)) } @@ -109,6 +110,8 @@ read_grant() { valid_account_name "$GRANT_NAME" || return 2 } +# Returns 0 for a rule this command generated, 1 for anything else under the +# owned prefix (preserved as administrator policy), and 2 when unreadable. classify_generated_rule() { local file=$1 suffix contents name @@ -116,18 +119,20 @@ classify_generated_rule() { contents=$(/usr/bin/cat -- "$file") || return 2 suffix=${file##*/99-omarchy-nopasswd-} - if [[ $suffix =~ ^[0-9]+$ ]]; then - name=${contents%' ALL=(ALL) NOPASSWD: ALL'} - if valid_account_name "$name" && [[ $contents == "$name ALL=(ALL) NOPASSWD: ALL" ]]; then - return 0 - fi - name=${contents%%' ALL=(ALL) NOTAFTER='*} - valid_account_name "$name" && [[ $contents =~ ^[a-z_][a-z0-9_-]*\$?\ ALL=\(ALL\)\ NOTAFTER=[0-9]{14}Z\ NOPASSWD:\ ALL$ ]] - elif valid_account_name "$suffix" && [[ $contents == "$suffix ALL=(ALL) NOPASSWD: ALL" ]]; then + # The legacy command wrote the caller's unvalidated name into both the + # filename and the rule. That exact relationship is its fingerprint, so an + # account the current policy would reject still has its old grant removed. + if [[ $contents == "$suffix ALL=(ALL) NOPASSWD: ALL" ]]; then + return 0 + fi + + [[ $suffix =~ ^[0-9]+$ ]] || return 1 + name=${contents%' ALL=(ALL) NOPASSWD: ALL'} + if valid_account_name "$name" && [[ $contents == "$name ALL=(ALL) NOPASSWD: ALL" ]]; then return 0 - else - return 1 fi + name=${contents%%' ALL=(ALL) NOTAFTER='*} + valid_account_name "$name" && [[ $contents =~ ^[a-z_][a-z0-9_-]*\$?\ ALL=\(ALL\)\ NOTAFTER=[0-9]{14}Z\ NOPASSWD:\ ALL$ ]] } cleanup_uid_locked() { diff --git a/docs/passwordless-sudo.md b/docs/passwordless-sudo.md index 393555040afb..1a846995f8c8 100644 --- a/docs/passwordless-sudo.md +++ b/docs/passwordless-sudo.md @@ -10,7 +10,7 @@ An internal status result is `0` for an active, validated grant and `3` for conf Calendar timers clean up expired files; their liveness does not define authorization. Callbacks read the current rule and remove it only when expired. Earlier callbacks cannot shorten a renewed grant, so no timer identity needs to be persisted. Old UID-only and token-bearing callbacks remain accepted. Pending callbacks after renewal or manual disable are harmless and expire within the maximum 24-hour grant window. Boot-time tmpfiles cleanup removes the reserved generated filename namespace before users log in; routine non-boot tmpfiles maintenance leaves live grants alone. -Legacy cleanup uses a root-owned machine marker under `/var/lib/omarchy/migrations/`, written only after successful cleanup under the grant lock. Later accounts can finish their migration queues without sudo and without revoking grants created after the repair. Old grant state files are no longer consulted; generated legacy policy is removed conservatively and administrator-modified policy is preserved by the migration. +Legacy cleanup uses a root-owned machine marker under `/var/lib/omarchy/migrations/`, written only after successful cleanup under the grant lock. Later accounts can finish their migration queues without sudo and without revoking grants created after the repair. Old grant state files are no longer consulted. A legacy grant is recognized by its exact filename and rule relationship, since the old command wrote the caller's unvalidated name into both, so accounts outside the current name policy are still cleaned up; administrator-modified policy under the owned prefix is preserved by the migration. ## Package ownership diff --git a/test/shell.d/nopasswd-sudo-expiry-test.sh b/test/shell.d/nopasswd-sudo-expiry-test.sh index 173ea1b00c0b..d6b1a5057ac5 100755 --- a/test/shell.d/nopasswd-sudo-expiry-test.sh +++ b/test/shell.d/nopasswd-sudo-expiry-test.sh @@ -9,7 +9,8 @@ source "$SHELL_TEST_DIR/fixtures/passwordless-sudo-test.sh" for minutes in 1 15 1440 00015; do valid_minutes "$minutes" || exit 1; done for minutes in 0 1441 -1 1m '' 18446744073709551617; do ! valid_minutes "$minutes" || exit 1; done for name in audituser 'buildbot$'; do valid_account_name "$name" || exit 1; done - for name in 'a$b' '$' aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; do ! valid_account_name "$name" || exit 1; done + # Upper-case words are sudoers alias references, so ALICE must never publish. + for name in 'a$b' '$' 'a b' 'a#b' Alice ALICE ALL aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; do ! valid_account_name "$name" || exit 1; done ! valid_uid 18446744073709551617 ) pass "duration and account validation retains bounded inputs and trailing-dollar usernames" @@ -159,5 +160,7 @@ cp "$ROOT/default/libalpm/hooks/05-omarchy-passwordless-revoke.hook" "$test_tmp/ /usr/sbin/visudo -cf "$(rule_file 1000)" >/dev/null cleanup_uid_locked 1000 [[ ! -e $(rule_file 1000) ]] + TEST_ACCOUNT=ALICE assert_status 1 enable_locked 1000 15 + [[ ! -e $(rule_file 1000) ]] ) -pass "trailing-dollar accounts publish and revoke valid native policy" +pass "trailing-dollar accounts publish valid native policy and alias-shaped names never publish" diff --git a/test/shell.d/passwordless-grant-lifecycle-test.sh b/test/shell.d/passwordless-grant-lifecycle-test.sh index a0be9d4f0ceb..91a0ba895a76 100644 --- a/test/shell.d/passwordless-grant-lifecycle-test.sh +++ b/test/shell.d/passwordless-grant-lifecycle-test.sh @@ -8,14 +8,20 @@ source "$SHELL_TEST_DIR/fixtures/passwordless-sudo-test.sh" source "$library" printf 'deleteduser ALL=(ALL) NOPASSWD: ALL\n' >"$(rule_file 1000)" printf 'buildbot$ ALL=(ALL) NOPASSWD: ALL\n' >"$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-buildbot$" + # The legacy command never validated the account name, so a manual or NSS + # account outside the current policy still has its exact old grant removed. + printf 'Alice ALL=(ALL) NOPASSWD: ALL\n' >"$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-Alice" printf 'admin ALL=(ALL) NOPASSWD: /usr/bin/true\n' >"$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-custom" + printf 'Alice ALL=(ALL) NOPASSWD: ALL\n' >"$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-handwritten" TEST_DELETE_FAIL=1 assert_status 1 cleanup_all_locked [[ -e $(rule_file 1000) ]] cleanup_all_locked - [[ ! -e $(rule_file 1000) && -e $test_tmp/etc/sudoers.d/99-omarchy-nopasswd-custom ]] + [[ ! -e $(rule_file 1000) && ! -e $test_tmp/etc/sudoers.d/99-omarchy-nopasswd-Alice ]] + [[ -e $test_tmp/etc/sudoers.d/99-omarchy-nopasswd-custom && -e $test_tmp/etc/sudoers.d/99-omarchy-nopasswd-handwritten ]] ! compgen -G "$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-buildbot*" + rm "$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-custom" "$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-handwritten" ) -pass "legacy cleanup removes generated orphan rules and preserves custom policy" +pass "legacy cleanup removes generated orphan rules for any account and preserves custom policy" # Run the actual migration queue for separate temporary homes. Sudo only calls # the mapped helper and can be refused without requesting host authorization. @@ -31,10 +37,12 @@ marker="$test_tmp/var/lib/omarchy/migrations/1788163635" ( source "$library" printf 'audituser ALL=(ALL) NOPASSWD: ALL\n' >"$(rule_file 1000)" + printf 'Alice ALL=(ALL) NOPASSWD: ALL\n' >"$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-Alice" TEST_DELETE_FAIL=1 assert_status 1 run_migrations first [[ ! -e $marker && ! -e $test_tmp/first/1788163636.sh ]] run_migrations first [[ -f $marker && -f $test_tmp/first/1788163636.sh ]] + [[ ! -e $test_tmp/etc/sudoers.d/99-omarchy-nopasswd-Alice ]] enable_locked 1000 15 cp "$(rule_file 1000)" "$test_tmp/renewed" : >"$test_tmp/commands" From ea617b9126e9d3ae88544687080af0b6849d205a Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Wed, 16 Sep 2026 23:23:23 +0100 Subject: [PATCH 086/194] Quarantine unrecognized policy under the generated sudoers prefix Matching a legacy grant by its filename and rule relationship is not a complete fingerprint: the legacy writer took the filename from $USER but produced the rule with echo, and under BASH_ENV with xpg_echo a name such as ali\0143e yields an alice rule in a mismatched file. Preserving that as administrator policy let the migration certify success with an unrestricted grant still live until the next boot. The prefix is reserved anyway: boot cleanup and the package hook remove everything under it. Move any file the classifier does not recognize into a fresh root-only directory under /var/lib/omarchy/sudoers-quarantine/ as `policy`, with the original name stored beside it, so nothing there stays live, the administrator keeps the content, and a legacy filename already close to NAME_MAX still fits. An untrusted quarantine directory keeps the migration pending. Cover the mismatched and maximum-length legacy files in the unit cleanup and through the real migration runner. Co-Authored-By: Claude Fable 5.1 --- bin/omarchy-sudo-passwordless | 23 ++++++++++- docs/passwordless-sudo.md | 2 +- .../passwordless-grant-lifecycle-test.sh | 38 +++++++++++++++---- 3 files changed, 54 insertions(+), 9 deletions(-) diff --git a/bin/omarchy-sudo-passwordless b/bin/omarchy-sudo-passwordless index 3b0af89de855..58a9b15c6116 100755 --- a/bin/omarchy-sudo-passwordless +++ b/bin/omarchy-sudo-passwordless @@ -29,6 +29,7 @@ readonly BOOT_CLEANUP_FILE=/etc/tmpfiles.d/omarchy-nopasswd-sudo.conf readonly PACKAGE_HOOK=/usr/share/libalpm/hooks/05-omarchy-passwordless-revoke.hook readonly REMOVAL_BLOCKER=/run/omarchy-sudo-passwordless-package-removing readonly MIGRATION_MARKER=/var/lib/omarchy/migrations/1788163635 +readonly QUARANTINE_DIR=/var/lib/omarchy/sudoers-quarantine readonly INSTALLED_SELF=/usr/bin/omarchy-sudo-passwordless readonly STATUS_INACTIVE=3 @@ -143,6 +144,24 @@ cleanup_uid_locked() { /usr/bin/rm -f -- "$file" && [[ ! -e $file && ! -L $file ]] } +# The generated prefix is reserved: boot cleanup and the package hook already +# remove everything in it, and the legacy writer could produce a rule whose +# body differs from its filename. Nothing unrecognized may stay live there, but +# its content is kept for the administrator instead of being deleted. +quarantine_foreign_rule() { + local file=$1 target + if [[ ! -e /var/lib/omarchy && ! -L /var/lib/omarchy ]]; then + /usr/bin/install -d -o root -g root -m 0755 -- /var/lib/omarchy || return 1 + fi + omarchy_security_prepare_private_root_directory "$QUARANTINE_DIR" /var/lib/omarchy || return 1 + # A legacy filename can already be close to NAME_MAX, so the destination + # name is fixed and the original name travels beside it. + target=$(/usr/bin/mktemp -d "$QUARANTINE_DIR/XXXXXXXXXX") || return 1 + /usr/bin/printf '%s\n' "${file##*/}" >"$target/name" || return 1 + /usr/bin/mv -fT -- "$file" "$target/policy" && [[ ! -e $file && ! -L $file ]] || return 1 + echo "Moved unrecognized sudoers policy $file to $target/policy" >&2 +} + cleanup_all_locked() { local file classification failed=0 verify_root_path /etc/sudoers.d || return 1 @@ -154,7 +173,9 @@ cleanup_all_locked() { fi else classification=$? - (( classification == 1 )) || failed=1 + if (( classification != 1 )) || ! quarantine_foreign_rule "$file"; then + failed=1 + fi fi done return "$failed" diff --git a/docs/passwordless-sudo.md b/docs/passwordless-sudo.md index 1a846995f8c8..4aa6e31d58b5 100644 --- a/docs/passwordless-sudo.md +++ b/docs/passwordless-sudo.md @@ -10,7 +10,7 @@ An internal status result is `0` for an active, validated grant and `3` for conf Calendar timers clean up expired files; their liveness does not define authorization. Callbacks read the current rule and remove it only when expired. Earlier callbacks cannot shorten a renewed grant, so no timer identity needs to be persisted. Old UID-only and token-bearing callbacks remain accepted. Pending callbacks after renewal or manual disable are harmless and expire within the maximum 24-hour grant window. Boot-time tmpfiles cleanup removes the reserved generated filename namespace before users log in; routine non-boot tmpfiles maintenance leaves live grants alone. -Legacy cleanup uses a root-owned machine marker under `/var/lib/omarchy/migrations/`, written only after successful cleanup under the grant lock. Later accounts can finish their migration queues without sudo and without revoking grants created after the repair. Old grant state files are no longer consulted. A legacy grant is recognized by its exact filename and rule relationship, since the old command wrote the caller's unvalidated name into both, so accounts outside the current name policy are still cleaned up; administrator-modified policy under the owned prefix is preserved by the migration. +Legacy cleanup uses a root-owned machine marker under `/var/lib/omarchy/migrations/`, written only after successful cleanup under the grant lock. Later accounts can finish their migration queues without sudo and without revoking grants created after the repair. Old grant state files are no longer consulted. A legacy grant is recognized by its exact filename and rule relationship, since the old command wrote the caller's unvalidated name into both, so accounts outside the current name policy are still cleaned up. The generated filename prefix is reserved: boot cleanup and the package hook already remove everything under it, and the old writer could emit a rule whose body differs from its filename, so the migration moves any other file found there into a fresh root-only directory under `/var/lib/omarchy/sudoers-quarantine/`, as `policy` with the original name stored beside it, rather than leaving it live or deleting its content. ## Package ownership diff --git a/test/shell.d/passwordless-grant-lifecycle-test.sh b/test/shell.d/passwordless-grant-lifecycle-test.sh index 91a0ba895a76..71f34b2409c2 100644 --- a/test/shell.d/passwordless-grant-lifecycle-test.sh +++ b/test/shell.d/passwordless-grant-lifecycle-test.sh @@ -4,6 +4,19 @@ set -euo pipefail source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" source "$SHELL_TEST_DIR/fixtures/passwordless-sudo-test.sh" +quarantine="$test_tmp/var/lib/omarchy/sudoers-quarantine" +quarantined_policy() { + local entry + for entry in "$quarantine"/*/; do + if [[ $(cat "$entry/name") == "$1" ]]; then + cat "$entry/policy" + return 0 + fi + done + return 1 +} +# The old writer accepted any $USER, so a basename can sit just under NAME_MAX. +long_suffix=$(printf 'l%.0s' {1..223}) ( source "$library" printf 'deleteduser ALL=(ALL) NOPASSWD: ALL\n' >"$(rule_file 1000)" @@ -11,17 +24,23 @@ source "$SHELL_TEST_DIR/fixtures/passwordless-sudo-test.sh" # The legacy command never validated the account name, so a manual or NSS # account outside the current policy still has its exact old grant removed. printf 'Alice ALL=(ALL) NOPASSWD: ALL\n' >"$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-Alice" + # The legacy writer produced the body with echo. Under BASH_ENV with + # xpg_echo, USER='ali\0143e' yields this filename with an 'alice' rule, so + # a suffix/body mismatch does not prove administrator authorship. + printf 'alice ALL=(ALL) NOPASSWD: ALL\n' >"$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-ali\\0143e" + printf 'alice ALL=(ALL) NOPASSWD: ALL\n' >"$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-$long_suffix" printf 'admin ALL=(ALL) NOPASSWD: /usr/bin/true\n' >"$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-custom" - printf 'Alice ALL=(ALL) NOPASSWD: ALL\n' >"$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-handwritten" TEST_DELETE_FAIL=1 assert_status 1 cleanup_all_locked [[ -e $(rule_file 1000) ]] cleanup_all_locked - [[ ! -e $(rule_file 1000) && ! -e $test_tmp/etc/sudoers.d/99-omarchy-nopasswd-Alice ]] - [[ -e $test_tmp/etc/sudoers.d/99-omarchy-nopasswd-custom && -e $test_tmp/etc/sudoers.d/99-omarchy-nopasswd-handwritten ]] - ! compgen -G "$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-buildbot*" - rm "$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-custom" "$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-handwritten" + ! compgen -G "$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-*" + [[ $(stat -c '%a' "$quarantine") == 700 ]] + [[ $(quarantined_policy '99-omarchy-nopasswd-ali\0143e') == 'alice ALL=(ALL) NOPASSWD: ALL' ]] + [[ $(quarantined_policy "99-omarchy-nopasswd-$long_suffix") == 'alice ALL=(ALL) NOPASSWD: ALL' ]] + [[ $(quarantined_policy 99-omarchy-nopasswd-custom) == 'admin ALL=(ALL) NOPASSWD: /usr/bin/true' ]] + (( $(ls -A "$quarantine" | wc -l) == 3 )) ) -pass "legacy cleanup removes generated orphan rules for any account and preserves custom policy" +pass "legacy cleanup removes generated rules for any account and quarantines everything else in the prefix" # Run the actual migration queue for separate temporary homes. Sudo only calls # the mapped helper and can be refused without requesting host authorization. @@ -36,13 +55,18 @@ run_migrations() { marker="$test_tmp/var/lib/omarchy/migrations/1788163635" ( source "$library" + # A quarantine that cannot be trusted keeps the migration pending. + printf 'alice ALL=(ALL) NOPASSWD: ALL\n' >"$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-mismatch" + TEST_BAD_PATH="$test_tmp/var/lib/omarchy" assert_status 1 run_migrations first + [[ ! -e $marker && -e $test_tmp/etc/sudoers.d/99-omarchy-nopasswd-mismatch ]] printf 'audituser ALL=(ALL) NOPASSWD: ALL\n' >"$(rule_file 1000)" printf 'Alice ALL=(ALL) NOPASSWD: ALL\n' >"$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-Alice" TEST_DELETE_FAIL=1 assert_status 1 run_migrations first [[ ! -e $marker && ! -e $test_tmp/first/1788163636.sh ]] run_migrations first [[ -f $marker && -f $test_tmp/first/1788163636.sh ]] - [[ ! -e $test_tmp/etc/sudoers.d/99-omarchy-nopasswd-Alice ]] + ! compgen -G "$test_tmp/etc/sudoers.d/99-omarchy-nopasswd-*" + [[ $(quarantined_policy 99-omarchy-nopasswd-mismatch) == 'alice ALL=(ALL) NOPASSWD: ALL' ]] enable_locked 1000 15 cp "$(rule_file 1000)" "$test_tmp/renewed" : >"$test_tmp/commands" From 13a4306a8edd8708d8e2d5814593312a8f321921 Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Thu, 17 Sep 2026 10:52:34 +0100 Subject: [PATCH 087/194] Run the refresh hook before its transaction and keep the inhibitor through user work Three review findings on the update-hook boundary: The pre-refresh-pacman hook had been moved after the refresh transaction and, during a channel switch, deferred to the very end. That defeated the hook's purpose: custom repositories and IgnorePkg entries were not in place when the downgrade-capable -Syyuu ran. Run the hook where it used to run, after the package config is re-synced and before the transaction, but cold: revoke the timestamp, run it behind the no-update wrapper with the caller's original PATH, and revoke again before continuing. Every later privileged command authenticates with --no-update, so a detached child left by the hook has no reusable timestamp to wait for. Channel switching hands the caller's PATH to the refresh the same way the updater receives it, and no longer defers or re-runs the hook. Stay Awake was released before AUR builds, hooks and mise, so the machine could sleep during the longest part of an update. Releasing the inhibitor needs no privilege because the held command already dropped to the user, so stop it after mise and before the reboot prompt, as before. A packaged channel destination cannot be inspected before its package is installed, and a transaction can replace the running tree with a release that predates the command-scoped wrapper; from then on a bare sudo would resolve to /usr/bin/sudo and publish a timestamp, and the destination's own updater authenticates the same way. The switch used to abort only after the packages had changed, with generic rerun advice. Now it checks for the wrapper after each transaction before any further privileged step, completes what it safely can, and stops cold with instructions to run that release's update from a fresh session instead of launching it. Boundary tests pin the hook between the config copies and the transaction with a cold timestamp on both sides, the older-destination stop with its guidance and no launched updater, the new inhibitor position, and the post-update hook staying unreached on failures and signals. Docs, the manual and the sample hook describe the restored timing. Co-Authored-By: Claude Fable 5.1 --- bin/omarchy-channel-set | 31 +++++++-- bin/omarchy-refresh-pacman | 43 ++++++------ bin/omarchy-update | 16 +++-- .../add-custom-repo.sample | 15 ++-- default/agents/skills/omarchy/hooks.md | 4 +- docs/update-process.md | 13 ++-- manual/31-dotfiles.md | 4 +- test/shell.d/channel-sudo-boundary-test.sh | 69 +++++++++++++++++-- test/shell.d/channel-test.sh | 14 ++-- test/shell.d/fixtures/sudo-boundary-test.sh | 7 +- test/shell.d/update-hook-security-test.sh | 29 ++++---- test/shell.d/update-sequence-test.sh | 2 +- 12 files changed, 160 insertions(+), 87 deletions(-) diff --git a/bin/omarchy-channel-set b/bin/omarchy-channel-set index 86130903a4e6..a00c9d929df1 100755 --- a/bin/omarchy-channel-set +++ b/bin/omarchy-channel-set @@ -61,6 +61,25 @@ link_dev_checkout() { omarchy-dev-link "$checkout" --no-reboot } +# A packaged destination cannot be inspected before its package is installed, +# and a package transaction can replace the running tree with a release that +# predates the command-scoped wrapper. After that, a bare sudo would resolve to +# /usr/bin/sudo and publish a timestamp, and the destination's own updater +# authenticates the same way. Neither may run from a flow that has just run +# user hooks: stop at a consistent point and say how to finish from a fresh +# session. +stop_for_older_destination() { + cat >&2 < 0 )) || { usage; exit 1; } dev_checkout="" @@ -109,23 +128,21 @@ if [[ -n $dev_checkout ]]; then omarchy-state set reboot-required fi -omarchy-refresh-pacman "$pacman_channel" defer-hook +OMARCHY_UPDATE_USER_PATH="$user_path" omarchy-refresh-pacman "$pacman_channel" +# Each transaction can have replaced this tree; check before the next sudo. +wrapper_present || stop_for_older_destination # --ask 4 accepts omarchy <-> omarchy-dev replacement prompts without file overwrites. omarchy-update-pacman -S --needed --noconfirm --ask 4 "${packages[@]}" +wrapper_present || stop_for_older_destination if [[ -z $dev_checkout ]]; then omarchy-dev-unlink --no-reboot export OMARCHY_PATH=/usr/share/omarchy - omarchy_security_enable_no_update_sudo if (( leaving_dev )); then omarchy-state set reboot-required fi + omarchy_security_enable_no_update_sudo 2>/dev/null || stop_for_older_destination fi OMARCHY_UPDATE_USER_PATH="$user_path" "$OMARCHY_PATH/bin/omarchy-update" -y - -# No channel-owned privileged work follows the historical refresh hook. -omarchy_security_revoke_sudo_timestamp -PATH="$OMARCHY_PATH/default/omarchy/sudo-no-update:$user_path" \ - "$OMARCHY_PATH/bin/omarchy-refresh-pacman" "$pacman_channel" run-deferred diff --git a/bin/omarchy-refresh-pacman b/bin/omarchy-refresh-pacman index f09a0925201e..cd9eab1113ff 100755 --- a/bin/omarchy-refresh-pacman +++ b/bin/omarchy-refresh-pacman @@ -14,36 +14,35 @@ omarchy_security_require_privileged_bash_startup || exit 126 set -e omarchy_security_sanitize_bash_environment "$0" "$@" omarchy_security_require_source_root "$0" -user_path=$PATH +# Channel switching calls this behind its own sanitized PATH and hands the +# caller's original path over the same way the updater receives it. +user_path=${OMARCHY_UPDATE_USER_PATH:-$PATH} +unset OMARCHY_UPDATE_USER_PATH omarchy_security_revoke_sudo_timestamp || exit 1 omarchy_security_install_sudo_cleanup_traps omarchy_security_enable_no_update_sudo channel="${1:-stable}" -hook_mode="${2:-normal}" if [[ $channel != "stable" && $channel != "rc" && $channel != "edge" ]]; then echo "Invalid channel: $channel" >&2 exit 2 fi -if [[ $hook_mode != "normal" && $hook_mode != "defer-hook" && $hook_mode != "run-deferred" ]]; then - echo "Invalid refresh hook mode: $hook_mode" >&2 - exit 2 -fi -if [[ $hook_mode != "run-deferred" ]]; then - sudo cp -f /etc/pacman.conf /etc/pacman.conf.bak - sudo cp -f /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.bak - echo "Setting channel to $channel" - sudo cp -f "$OMARCHY_PATH/default/pacman/pacman-$channel.conf" /etc/pacman.conf - sudo cp -f "$OMARCHY_PATH/default/pacman/mirrorlist-$channel" /etc/pacman.d/mirrorlist - # Reset all package DBs and then update - omarchy-update-pacman -Syyuu --noconfirm -fi +sudo cp -f /etc/pacman.conf /etc/pacman.conf.bak +sudo cp -f /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.bak +echo "Setting channel to $channel" +sudo cp -f "$OMARCHY_PATH/default/pacman/pacman-$channel.conf" /etc/pacman.conf +sudo cp -f "$OMARCHY_PATH/default/pacman/mirrorlist-$channel" /etc/pacman.d/mirrorlist -# Keep the historical hook name, but finish every privileged refresh operation -# before running user code. Callers with later root work can defer the hook. -if [[ $hook_mode != "defer-hook" ]]; then - omarchy_security_revoke_sudo_timestamp - PATH="$OMARCHY_PATH/default/omarchy/sudo-no-update:$user_path" \ - "$OMARCHY_PATH/bin/omarchy-hook" pre-refresh-pacman -fi +# Allow user customization of /etc/pacman.conf before the upgrade runs, so +# custom repositories and IgnorePkg entries shape the downgrade-capable +# transaction below. The hook is user code: it runs cold behind the no-update +# wrapper, and the timestamp is revoked again afterwards so any authorization +# the hook obtained for itself cannot carry into the transaction. +omarchy_security_revoke_sudo_timestamp +PATH="$OMARCHY_PATH/default/omarchy/sudo-no-update:$user_path" \ + "$OMARCHY_PATH/bin/omarchy-hook" pre-refresh-pacman +omarchy_security_revoke_sudo_timestamp + +# Reset all package DBs and then update +omarchy-update-pacman -Syyuu --noconfirm diff --git a/bin/omarchy-update b/bin/omarchy-update index 3873a6bc4010..2d5ad4746c72 100755 --- a/bin/omarchy-update +++ b/bin/omarchy-update @@ -94,15 +94,9 @@ if [[ ${1:-} == "-y" ]] || omarchy-update-confirm; then # update tooling; the reboot-only phase below performs no privileged work. omarchy-update-restart --services-only - # Release update-owned inhibitors before offering a reboot. A confirmed - # reboot can terminate this process before its EXIT trap gets a chance to - # remove the persistent Stay Awake marker. - omarchy_security_revoke_sudo_timestamp - omarchy-update-stay-awake stop - update_stay_awake_stopped=1 - # AUR package installation must also use the no-update wrapper. Finish # update-owned system work before build code, hooks, or mise can run. + omarchy_security_revoke_sudo_timestamp omarchy-update-aur-pkgs omarchy_security_revoke_sudo_timestamp @@ -114,5 +108,13 @@ if [[ ${1:-} == "-y" ]] || omarchy-update-confirm; then PATH="$OMARCHY_PATH/default/omarchy/sudo-no-update:$user_path" "$OMARCHY_PATH/bin/omarchy-update-mise" omarchy_security_revoke_sudo_timestamp + # The sleep inhibitor covers AUR builds, hooks and mise as well; releasing it + # needs no privilege because the held command already dropped to this user. + # Release it before offering a reboot: a confirmed reboot can terminate this + # process before its EXIT trap gets a chance to remove the persistent Stay + # Awake marker. + omarchy-update-stay-awake stop + update_stay_awake_stopped=1 + "$OMARCHY_PATH/bin/omarchy-update-restart" --reboot-only fi diff --git a/config/omarchy/hooks/pre-refresh-pacman.d/add-custom-repo.sample b/config/omarchy/hooks/pre-refresh-pacman.d/add-custom-repo.sample index 0c8ba7c437b0..fdc3a871ce1d 100644 --- a/config/omarchy/hooks/pre-refresh-pacman.d/add-custom-repo.sample +++ b/config/omarchy/hooks/pre-refresh-pacman.d/add-custom-repo.sample @@ -1,20 +1,17 @@ #!/bin/bash -# This legacy-named hook is called by `omarchy refresh pacman` AFTER the -# channel template is copied and the privileged package transaction finishes. -# During `omarchy channel set`, it is deferred until the package switch and -# complete update have also finished. -# Use it to layer customizations onto the freshly-written pacman.conf for -# subsequent package operations — common cases are adding a custom repository -# (e.g. CachyOS, Chaotic-AUR, an internal company repo) or extra IgnorePkg -# lines. +# This hook is called by `omarchy refresh pacman` AFTER the channel template +# is copied and BEFORE the package transaction runs, so your changes shape +# that transaction. Use it to layer customizations onto the freshly-written +# pacman.conf — common cases are adding a custom repository (e.g. CachyOS, +# Chaotic-AUR, an internal company repo) or extra IgnorePkg lines. # # The hook runs as the invoking user after Omarchy invalidates its sudo cache. # A sudo command here therefore requires its own explicit authorization. # # To put it into use, remove .sample from this file name. -# Example: add an Include line above [core] for future package operations. +# Example: add an Include line above [core]. # Maintain the repo entries in /etc/pacman.d/custom-repos.conf yourself. CONF=/etc/pacman.conf diff --git a/default/agents/skills/omarchy/hooks.md b/default/agents/skills/omarchy/hooks.md index 4878c7e19847..5da16fcc1d77 100644 --- a/default/agents/skills/omarchy/hooks.md +++ b/default/agents/skills/omarchy/hooks.md @@ -15,7 +15,7 @@ file first, if one exists. ├── font-set.d/ # After font change (font name in $1) ├── post-boot.d/ # After the desktop starts ├── post-update.d/ # At the end of `omarchy update`, after privileged work -├── pre-refresh-pacman.d/ # After `omarchy refresh pacman` finishes (legacy name) +├── pre-refresh-pacman.d/ # After `omarchy refresh pacman` re-syncs the package config, before it updates packages └── theme-set.d/ # After theme change (theme slug in $1) ``` @@ -27,4 +27,4 @@ echo "Theme changed to: $THEME_NAME" # Add custom actions here ``` -Update-related hooks run only after the workflow's privileged work and after Omarchy invalidates its sudo timestamp. A hook that invokes `sudo` must therefore request its own explicit authorization. The legacy-named `pre-refresh-pacman` hook runs after the refresh transaction; during `omarchy channel set`, it is deferred further until the package switch and complete update finish. Executable user code cannot safely run before a later sudo authentication because a detached child could wait for the new timestamp. +Update-related hooks run as your user after Omarchy invalidates its sudo timestamp, behind the no-update wrapper. A hook that invokes `sudo` must therefore request its own explicit authorization, and Omarchy revokes the timestamp again before continuing. `post-update` runs after every sudo-capable update stage. `pre-refresh-pacman` runs after `omarchy refresh pacman` re-syncs the package config and before the package transaction, so custom repositories and `IgnorePkg` entries shape that transaction; every later privileged command still authenticates without publishing a reusable timestamp, so a detached child left behind by the hook has nothing to wait for. diff --git a/docs/update-process.md b/docs/update-process.md index 97511a5c1a5a..f96b28c48604 100644 --- a/docs/update-process.md +++ b/docs/update-process.md @@ -139,11 +139,10 @@ omarchy-update ├─ omarchy-update-status │ └─ refresh or clear the shell update indicator ├─ restart marked services and the shell + ├─ invalidate sudo credentials, then update AUR packages + ├─ invalidate again, run the post-update hook, invalidate again, then update mise tools ├─ omarchy-update-stay-awake stop │ └─ release the sleep inhibitor and restore shell idle state, if changed - ├─ update AUR packages - ├─ invalidate sudo credentials - ├─ run the post-update hook, invalidate again, then update mise tools └─ offer the unprivileged reboot prompt ``` @@ -155,7 +154,7 @@ Important behavior: - Migrations remain in chronological order even though historical entries mix user-controlled code with later privileged repairs. Before entering that mixed-trust tail, Omarchy invalidates its timestamp and forces every later sudo call—including AUR's configurable sudo command—to use `--no-update`; prompts authorize one command without publishing a reusable timestamp. Yay's credential loop is disabled for the update. - User-controlled post-update hooks and mise tools run only after every sudo-capable update stage. Omarchy invalidates its sudo timestamp before each boundary and on every exit; detached children therefore have no later reusable update authorization to wait for. - This lifecycle controls authorization created by the protected workflow. `sudo -N` prevents cache updates but can use an existing valid credential, and `sudo -k` revokes the current session's timestamp. It does not isolate the account from unrelated concurrent authentication in another workflow. -- Channel switching establishes the same boundary before dev link/unlink, refresh and package operations. It keeps the wrapper first when changing source roots, carries the original user PATH into update hooks and mise, and runs the deferred refresh hook only after the full update succeeds and authorization is revoked again. Failed and interrupted channel switches revoke on exit. +- Channel switching establishes the same boundary before dev link/unlink, refresh and package operations. It keeps the wrapper first when changing source roots, carries the original user PATH into update hooks and mise, and checks after each package transaction that the wrapper still exists before any further privileged step, since a transaction can replace the running tree with a release that predates it; when it is gone, or the destination otherwise lacks it, the switch stops after the package switch with instructions to run that release's update from a fresh session rather than letting a bare `sudo` or an updater that authenticates without `--no-update` publish a timestamp. Failed and interrupted channel switches revoke on exit. - `-y` exports `OMARCHY_UPDATE_UNATTENDED=1` and suppresses Omarchy confirmation prompts. Interactive review steps (orphan removal, conflict handoff) report and skip instead of blocking. Privileged commands still require sudo authorization, and command-scoped authentication can prompt separately for each command. - The free-space requirement uses a 10 GiB threshold and stops the update before confirmation when it is not met. If free space cannot be determined, the @@ -268,9 +267,9 @@ which pacman repo the mirrorlist points at (and swap between the `omarchy` and `omarchy-dev` packages through a guard-allowed pacman run), while `dev` links the runtime to a git checkout via the dev-link mechanism, after which `omarchy update` fast-forwards that checkout instead of upgrading a package. -Channel switching defers the legacy `pre-refresh-pacman` hook across the package -swap and the complete update. The hook runs exactly once at the final cold -credential boundary; it is skipped if the composite operation fails earlier. +Channel switching runs the `pre-refresh-pacman` hook once, during its refresh +step: cold, behind the no-update wrapper, after the package config is re-synced +and before the refresh transaction. It does not run if the switch fails earlier. There is no version file at runtime. `omarchy-version` derives the version from `pacman -Q` on whichever package is installed, or reports `dev ()` for a diff --git a/manual/31-dotfiles.md b/manual/31-dotfiles.md index a81a6596adb5..420350fe761e 100644 --- a/manual/31-dotfiles.md +++ b/manual/31-dotfiles.md @@ -38,12 +38,12 @@ Omarchy fires hooks at a handful of moments, and you can hang your own scripts o | ----- | ------------ | | `post-boot` | Right after the desktop has started | | `post-update` | Near the end of `omarchy update`, after packages, migrations, and service restarts, before mise tools are updated | -| `pre-refresh-pacman` | After `omarchy refresh pacman` re-syncs the package config and finishes updating packages; during a channel switch, after the package switch and complete update finish | +| `pre-refresh-pacman` | After `omarchy refresh pacman` re-syncs the package config, before it updates packages; a channel switch runs it during that same refresh step | | `theme-set` | After a theme change (theme name in `$1`) | | `font-set` | After a font change (font name in `$1`) | | `battery-low` | When the battery gets low (percentage in `$1`) | -The `pre-refresh-pacman` name is kept for compatibility. Its edits to the refreshed package config apply to future package operations, after the current transaction has finished. Both update-related hooks run as your user after Omarchy clears its cached sudo authorization, so a hook that uses `sudo` needs its own authorization and may ask for your password. +The `pre-refresh-pacman` hook is where custom repositories or `IgnorePkg` lines belong, since it runs before the package transaction. Both update-related hooks run as your user after Omarchy clears its cached sudo authorization, so a hook that uses `sudo` needs its own authorization and may ask for your password. Each of those directories already holds a `.sample` file showing the shape of a hook — drop the `.sample` from the name to put it to work. To install a script you've written elsewhere, use `omarchy hook install post-boot ~/my-hook`, which copies it in and makes it executable. diff --git a/test/shell.d/channel-sudo-boundary-test.sh b/test/shell.d/channel-sudo-boundary-test.sh index b7fabf0257e6..336ed26c2327 100755 --- a/test/shell.d/channel-sudo-boundary-test.sh +++ b/test/shell.d/channel-sudo-boundary-test.sh @@ -47,8 +47,12 @@ sudo = [event for event in events if event.startswith('sudo ')] assert all(event in ('sudo -h', 'sudo -k') or event.startswith('sudo -N ') for event in sudo), events hooks = [i for i, event in enumerate(events) if event.startswith('step:omarchy-hook ')] assert len(hooks) == 2, events -assert events[hooks[-1]] == 'step:omarchy-hook pre-refresh-pacman', events -assert not any(event.startswith('sudo -N ') for event in events[hooks[0]:]), events +assert events[hooks[0]] == 'step:omarchy-hook pre-refresh-pacman', events +assert events[hooks[1]] == 'step:omarchy-hook post-update', events +assert events[hooks[0] - 1] == 'sudo -k' and events[hooks[0] + 1] == 'sudo -k', events +transaction = next(i for i, event in enumerate(events) if event.startswith('step:pacman ')) +assert hooks[0] < transaction, events +assert not any(event.startswith('sudo -N ') for event in events[hooks[1]:]), events PY } @@ -59,7 +63,7 @@ for channel in stable rc edge dev; do reset_boundary run_channel "$channel" || fail "$channel failed" "$(<"$boundary_tmp/output")" assert_scoped_channel "$channel" - pass "$channel starts cold, authorizes only individual commands, defers hooks and exits cold" + pass "$channel starts cold, authorizes only individual commands, runs the refresh hook cold before its transaction and exits cold" done reset_boundary @@ -79,6 +83,59 @@ OMARCHY_PATH="$SUDO_TEST_HOME/omarchy" run_channel stable || fail "leaving dev f assert_scoped_channel "dev to stable" pass "leaving dev preserves no-update sudo through unlink and the packaged update" +# A packaged destination that predates the wrapper cannot be checked before its +# package is installed. Its updater authenticates without --no-update, so the +# switch must not launch it: it stops at a consistent point with instructions. +reset_boundary +mv "$SUDO_TEST_ROOT/default/omarchy/sudo-no-update/sudo" "$boundary_tmp/saved-package-wrapper" +mv "$SUDO_TEST_ROOT/bin/omarchy-update" "$boundary_tmp/saved-package-update" +ln -s test-step "$SUDO_TEST_ROOT/bin/omarchy-update" +if OMARCHY_PATH="$SUDO_TEST_HOME/omarchy" run_channel stable; then fail "an older packaged destination was updated with ordinary sudo" "$(<"$SUDO_TEST_LOG")"; fi +grep -q "predates command-scoped sudo" "$boundary_tmp/output" || fail "an older packaged destination was not reported" "$(<"$boundary_tmp/output")" +grep -q "Run 'omarchy update' from a new terminal to finish" "$boundary_tmp/output" || fail "an older packaged destination lacks recovery guidance" "$(<"$boundary_tmp/output")" +grep -Fxq 'step:omarchy-dev-unlink --no-reboot' "$SUDO_TEST_LOG" || fail "the package switch was not completed before stopping" "$(<"$SUDO_TEST_LOG")" +grep -Fxq 'step:omarchy-state set reboot-required' "$SUDO_TEST_LOG" || fail "leaving dev for an older release did not mark the reboot" "$(<"$SUDO_TEST_LOG")" +if grep -q '^step:omarchy-update ' "$SUDO_TEST_LOG"; then fail "an older packaged updater was launched from the hardened switch" "$(<"$SUDO_TEST_LOG")"; fi +grep -q 'The channel switch did not complete' "$boundary_tmp/output" && fail "the stop was reported as an error needing a rerun" "$(<"$boundary_tmp/output")" +assert_boundary_cold "older packaged destination" +rm "$SUDO_TEST_ROOT/bin/omarchy-update" +mv "$boundary_tmp/saved-package-update" "$SUDO_TEST_ROOT/bin/omarchy-update" +mv "$boundary_tmp/saved-package-wrapper" "$SUDO_TEST_ROOT/default/omarchy/sudo-no-update/sudo" +pass "an older packaged destination stops the switch cold with instructions instead of running its updater" + +# A package-backed source can be downgraded by its own transaction to a release +# without the wrapper. From then on a bare sudo would be the real one, so no +# privileged step may follow either transaction without checking first. A decoy +# sudo in the package bin catches any such call instead of reaching the host. +cat >"$SUDO_TEST_ROOT/bin/sudo" <<'STUB' +#!/bin/bash +printf 'unwrapped-sudo %s\n' "$*" >>"$SUDO_TEST_LOG" +exit 97 +STUB +chmod +x "$SUDO_TEST_ROOT/bin/sudo" +cp "$SUDO_TEST_ROOT/default/omarchy/sudo-no-update/sudo" "$boundary_tmp/saved-package-wrapper" +for pattern in 'pacman -Syyuu*' 'pacman -S --needed*'; do + reset_boundary + export SUDO_TEST_REMOVE_WRAPPER_STEP=$pattern + if run_channel rc; then fail "a downgrade during '$pattern' was not detected" "$(<"$SUDO_TEST_LOG")"; fi + unset SUDO_TEST_REMOVE_WRAPPER_STEP + grep -q "predates command-scoped sudo" "$boundary_tmp/output" || fail "downgrade during '$pattern' was not reported" "$(<"$boundary_tmp/output")" + if grep -q '^unwrapped-sudo ' "$SUDO_TEST_LOG"; then fail "downgrade during '$pattern' reached ordinary sudo" "$(<"$SUDO_TEST_LOG")"; fi + if grep -q '^step:omarchy-dev-unlink' "$SUDO_TEST_LOG"; then fail "downgrade during '$pattern' still unlinked" "$(<"$SUDO_TEST_LOG")"; fi + if grep -q '^step:omarchy-update ' "$SUDO_TEST_LOG"; then fail "downgrade during '$pattern' still updated" "$(<"$SUDO_TEST_LOG")"; fi + python3 - "$SUDO_TEST_LOG" "$pattern" <<'PY' +import sys +events = open(sys.argv[1]).read().splitlines() +transactions = [e for e in events if e.startswith('step:pacman ')] +assert len(transactions) == (1 if sys.argv[2].startswith('pacman -Syyuu') else 2), events +assert all(e in ('sudo -h', 'sudo -k') or e.startswith('sudo -N ') for e in events if e.startswith('sudo ')), events +PY + assert_boundary_cold "downgrade during $pattern" + cp "$boundary_tmp/saved-package-wrapper" "$SUDO_TEST_ROOT/default/omarchy/sudo-no-update/sudo" + pass "a transaction that removes the wrapper stops the switch before any further sudo ($pattern)" +done +rm "$SUDO_TEST_ROOT/bin/sudo" + mkdir "$boundary_tmp/user tools" cat >"$boundary_tmp/user tools/channel-user-tool" <<'STUB' #!/bin/bash @@ -110,8 +167,8 @@ for step in pacman omarchy-update-system-pkgs omarchy-hook; do reset_boundary if SUDO_TEST_FAIL_STEP="$step" run_channel stable; then fail "$step failure was ignored"; fi assert_boundary_cold "$step failure" - if grep -q '^step:omarchy-hook pre-refresh-pacman$' "$SUDO_TEST_LOG"; then fail "$step failure reached the deferred hook"; fi - pass "$step failure exits cold without the deferred hook" + if grep -q '^step:omarchy-hook post-update$' "$SUDO_TEST_LOG"; then fail "$step failure reached the post-update hook"; fi + pass "$step failure exits cold without the post-update hook" done for signal in HUP INT TERM; do @@ -123,7 +180,7 @@ kill -s "$SUDO_TEST_CHANNEL_SIGNAL" "$PPID" STUB if SUDO_TEST_CHANNEL_SIGNAL="$signal" run_channel stable; then fail "$signal was ignored"; fi assert_boundary_cold "$signal" - if grep -q '^step:omarchy-hook ' "$SUDO_TEST_LOG"; then fail "$signal reached an update hook"; fi + if grep -q '^step:omarchy-hook post-update$' "$SUDO_TEST_LOG"; then fail "$signal reached the post-update hook"; fi pass "$signal stops the channel transition and revokes authorization" done diff --git a/test/shell.d/channel-test.sh b/test/shell.d/channel-test.sh index 5640e292eb84..cbbfc6e88311 100644 --- a/test/shell.d/channel-test.sh +++ b/test/shell.d/channel-test.sh @@ -127,7 +127,7 @@ assert_log_line() { } run_channel stable -assert_log_line $'refresh\tstable\tdefer-hook' "stable refreshes the stable pacman channel" +assert_log_line $'refresh\tstable' "stable refreshes the stable pacman channel" assert_log_line $'update-pacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy\tomarchy-settings' "stable installs stable Omarchy packages" assert_log_line $'unlink\t--no-reboot' "stable restores the package-backed Omarchy path without an early reboot prompt" assert_log_line $'update\t-y\tOMARCHY_PATH='"$package_root" "stable runs the normal update pipeline from the package-backed path" @@ -137,7 +137,7 @@ fi pass "stable does not require reboot when already package-backed" run_channel rc -assert_log_line $'refresh\trc\tdefer-hook' "rc refreshes the rc pacman channel" +assert_log_line $'refresh\trc' "rc refreshes the rc pacman channel" assert_log_line $'update-pacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy\tomarchy-settings' "rc installs rc Omarchy packages" assert_log_line $'unlink\t--no-reboot' "rc restores the package-backed Omarchy path without an early reboot prompt" assert_log_line $'update\t-y\tOMARCHY_PATH='"$package_root" "rc runs the normal update pipeline from the package-backed path" @@ -145,7 +145,7 @@ assert_log_line $'update\t-y\tOMARCHY_PATH='"$package_root" "rc runs the normal active_checkout="$test_tmp/active-checkout" cp -a "$package_root" "$active_checkout" OMARCHY_TEST_PATH="$active_checkout" run_channel edge -assert_log_line $'refresh\tedge\tdefer-hook' "edge refreshes the edge pacman channel" +assert_log_line $'refresh\tedge' "edge refreshes the edge pacman channel" assert_log_line $'update-pacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev' "edge installs development Omarchy packages" assert_log_line $'unlink\t--no-reboot' "edge unlinks dev without an early reboot prompt" assert_log_line $'state\tset\treboot-required' "edge marks reboot required when leaving dev" @@ -161,7 +161,7 @@ if run_channel dev >"$test_tmp/occupied.out" 2>"$test_tmp/occupied.err"; then fi grep -q "already exists and is not a git checkout" "$test_tmp/occupied.err" || fail "dev explains occupied checkout paths" "$(cat "$test_tmp/occupied.err")" -if grep -Fx $'refresh\tedge\tdefer-hook' "$log_file" >/dev/null; then +if grep -Fx $'refresh\tedge' "$log_file" >/dev/null; then fail "dev validates checkout path before changing packages" "$(cat "$log_file")" fi pass "dev refuses occupied non-checkout paths before package changes" @@ -169,17 +169,15 @@ pass "dev refuses occupied non-checkout paths before package changes" rmdir "$checkout" run_channel dev assert_log_line $'gum\tconfirm\t--default=false\tSwitch to dev channel?' "dev asks for confirmation" -assert_log_line $'refresh\tedge\tdefer-hook' "dev refreshes the edge pacman channel" +assert_log_line $'refresh\tedge' "dev refreshes the edge pacman channel" assert_log_line $'update-pacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev' "dev installs development Omarchy packages" assert_log_line $'git\tclone\thttps://github.com/omacom/omarchy.git\t'"$checkout" "dev clones the source checkout to ~/omarchy" assert_log_line $'link\t'"$checkout"$'\t--no-reboot' "dev links ~/omarchy without an early reboot prompt" assert_log_line $'state\tset\treboot-required' "dev defers the reboot prompt to the update pipeline" assert_log_line $'update\t-y\tOMARCHY_PATH='"$checkout" "dev runs the normal update pipeline from the source checkout" -[[ $(grep -E '^(git|link|state|refresh|sudo|update)' "$log_file" | sed '/run-deferred/d') == $'git\tclone\thttps://github.com/omacom/omarchy.git\t'"$checkout"$'\nlink\t'"$checkout"$'\t--no-reboot\nstate\tset\treboot-required\nrefresh\tedge\tdefer-hook\nupdate-pacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev\nupdate\t-y\tOMARCHY_PATH='"$checkout" ]] || +[[ $(grep -E '^(git|link|state|refresh|sudo|update)' "$log_file") == $'git\tclone\thttps://github.com/omacom/omarchy.git\t'"$checkout"$'\nlink\t'"$checkout"$'\t--no-reboot\nstate\tset\treboot-required\nrefresh\tedge\nupdate-pacman\t-S\t--needed\t--noconfirm\t--ask\t4\tomarchy-dev\tomarchy-settings-dev\nupdate\t-y\tOMARCHY_PATH='"$checkout" ]] || fail "dev activates the checkout before changing or updating packages" "$(cat "$log_file")" pass "dev activates the checkout before changing or updating packages" -[[ $(tail -1 "$log_file") == $'refresh\tedge\trun-deferred' ]] || fail "channel refresh hook must run after the complete update" -pass "channel changes defer the refresh hook until all update work finishes" OMARCHY_TEST_PATH="$checkout" run_channel stable assert_log_line $'unlink\t--no-reboot' "switching from dev to stable unlinks without an early reboot prompt" diff --git a/test/shell.d/fixtures/sudo-boundary-test.sh b/test/shell.d/fixtures/sudo-boundary-test.sh index a8c05d4505d1..43b0a66fd075 100644 --- a/test/shell.d/fixtures/sudo-boundary-test.sh +++ b/test/shell.d/fixtures/sudo-boundary-test.sh @@ -92,6 +92,11 @@ fi if [[ $step == "omarchy-hook" || $step == "omarchy-update-mise" ]]; then [[ ! -e $SUDO_TEST_CACHE ]] || exit 91 fi +if [[ -n ${SUDO_TEST_REMOVE_WRAPPER_STEP:-} && "$step $*" == $SUDO_TEST_REMOVE_WRAPPER_STEP ]]; then + # Model a package transaction replacing the running tree with a release + # that predates the wrapper. + /usr/bin/rm -f "$OMARCHY_PATH/default/omarchy/sudo-no-update/sudo" +fi if [[ ${SUDO_TEST_FAIL_STEP:-} == "$step" ]]; then # Model a misbehaving child leaving state behind, then failing. Cleanup must # still revoke it. This never invokes real sudo or exercises a privilege flaw. @@ -123,7 +128,7 @@ ln -s ../bin/test-step "$SUDO_TEST_ROOT/mock/pacman" reset_boundary() { : >"$SUDO_TEST_LOG" /usr/bin/rm -f "$SUDO_TEST_CACHE" - unset SUDO_TEST_FAIL_STEP SUDO_TEST_SIGNAL_STEP SUDO_TEST_SUDO_FAIL SUDO_TEST_REVOKE_FAIL SUDO_TEST_UNSUPPORTED + unset SUDO_TEST_FAIL_STEP SUDO_TEST_SIGNAL_STEP SUDO_TEST_SUDO_FAIL SUDO_TEST_REVOKE_FAIL SUDO_TEST_UNSUPPORTED SUDO_TEST_REMOVE_WRAPPER_STEP } assert_boundary_cold() { [[ ! -e $SUDO_TEST_CACHE ]] || fail "$1 left cached authorization" diff --git a/test/shell.d/update-hook-security-test.sh b/test/shell.d/update-hook-security-test.sh index 0181b800b951..ed18c756d1d9 100755 --- a/test/shell.d/update-hook-security-test.sh +++ b/test/shell.d/update-hook-security-test.sh @@ -24,9 +24,9 @@ for args in '-y' ''; do python3 - "$SUDO_TEST_LOG" <<'PY' import sys s=open(sys.argv[1]).read().splitlines() -positions=[next(i for i,line in enumerate(s) if line.startswith(prefix)) for prefix in ['step:omarchy-update-restart --services-only','step:omarchy-update-stay-awake stop','step:yay','step:omarchy-hook post-update','step:omarchy-update-mise','step:omarchy-update-restart --reboot-only']] +positions=[next(i for i,line in enumerate(s) if line.startswith(prefix)) for prefix in ['step:omarchy-update-restart --services-only','step:yay','step:omarchy-hook post-update','step:omarchy-update-mise','step:omarchy-update-stay-awake stop','step:omarchy-update-restart --reboot-only']] assert positions==sorted(positions), s -assert not any(line.startswith('sudo -N ') for line in s[positions[3]:]), s +assert not any(line.startswith('sudo -N ') for line in s[positions[2]:]), s PY pass "update $args runs privileged phases before hooks and exits cold" done @@ -63,21 +63,20 @@ if run_update -y; then fail "unsupported sudo must prevent mixed-trust work"; fi assert_boundary_cold "unsupported sudo" pass "unsupported sudo fails without running update steps" -for mode in normal defer-hook run-deferred; do - reset_boundary - "$SUDO_TEST_ROOT/bin/omarchy-refresh-pacman" stable "$mode" >"$boundary_tmp/output" 2>&1 || fail "refresh $mode failed" "$(<"$boundary_tmp/output")" - assert_boundary_cold "refresh $mode" - python3 - "$SUDO_TEST_LOG" "$mode" <<'PY' +reset_boundary +"$SUDO_TEST_ROOT/bin/omarchy-refresh-pacman" stable >"$boundary_tmp/output" 2>&1 || fail "refresh failed" "$(<"$boundary_tmp/output")" +assert_boundary_cold "refresh" +python3 - "$SUDO_TEST_LOG" <<'PY' import sys -s=open(sys.argv[1]).read().splitlines();mode=sys.argv[2] -hooks=[i for i,l in enumerate(s) if l.startswith('step:omarchy-hook')] -priv=[i for i,l in enumerate(s) if l.startswith('sudo -N ')] -assert bool(hooks)==(mode!='defer-hook'), s -assert bool(priv)==(mode!='run-deferred'), s -if hooks: assert not any(i>hooks[0] for i in priv),s +s=open(sys.argv[1]).read().splitlines() +hook=next(i for i,l in enumerate(s) if l=='step:omarchy-hook pre-refresh-pacman') +copies=[i for i,l in enumerate(s) if l.startswith('sudo -N cp ')] +transaction=next(i for i,l in enumerate(s) if l.startswith('step:pacman ')) +assert len(copies)==4 and max(copies) < hook < transaction, s +assert s[hook-1]=='sudo -k' and s[hook+1]=='sudo -k', s +assert all(l in ('sudo -h','sudo -k') or l.startswith('sudo -N ') for l in s if l.startswith('sudo ')), s PY - pass "refresh $mode preserves the final cold hook boundary" -done +pass "refresh runs the hook cold between the config re-sync and the transaction" for step in pacman omarchy-hook; do reset_boundary diff --git a/test/shell.d/update-sequence-test.sh b/test/shell.d/update-sequence-test.sh index 994dc4932472..a1013308fdc7 100755 --- a/test/shell.d/update-sequence-test.sh +++ b/test/shell.d/update-sequence-test.sh @@ -73,10 +73,10 @@ expected_steps() { omarchy-update-analyze-logs \ omarchy-update-status \ omarchy-update-restart \ - omarchy-update-stay-awake \ omarchy-update-aur-pkgs \ omarchy-hook \ omarchy-update-mise \ + omarchy-update-stay-awake \ omarchy-update-restart } From b34b117fd03278b8578f331d0f7eb3cdb434b196 Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Thu, 17 Sep 2026 17:02:43 +0100 Subject: [PATCH 088/194] Recover the session lock before waiting for notifications Restarting the shell waited for the notification bus name to reappear before it would re-acquire a lock whose client had died. A slow or failed notification plugin then left the user stranded behind Hyprland's failsafe even though the lock service worked. Wait for the shell's core IPC, re-secure the lock immediately, and only then wait for a previously running notification service, reporting it separately if it never returns. Cover the never-returning case: the lock comes back and the restart still reports the missing service. Co-Authored-By: Claude Fable 5.1 --- bin/omarchy-restart-shell | 60 +++++++++++++++++++++--------- test/shell.d/restart-shell-test.sh | 38 +++++++++++++++++++ 2 files changed, 80 insertions(+), 18 deletions(-) diff --git a/bin/omarchy-restart-shell b/bin/omarchy-restart-shell index 9891e7e8a7c3..4ca6ba293c92 100755 --- a/bin/omarchy-restart-shell +++ b/bin/omarchy-restart-shell @@ -82,26 +82,50 @@ while timeout 5 quickshell kill -p "$CONFIG_DIR" --any-display >/dev/null 2>&1; # not transient variables from a terminal, SSH connection, or development tool. hyprctl dispatch 'hl.dsp.exec_cmd("omarchy-launch-shell")' >/dev/null +shell_ready=0 for (( attempt = 0; attempt < 20; attempt++ )); do - if OMARCHY_PATH="$session_omarchy_path" OMARCHY_SHELL_IPC_TIMEOUT=0.5s omarchy-shell shell ping >/dev/null 2>&1 && - { (( notifications_were_running == 0 )) || notifications_ready; }; then - # The session stays compositor-locked after the old lock client died, so - # re-acquire the lock and let the user authenticate out of it. - if (( relock )) && ! relock_session; then - echo "Omarchy shell restarted, but the session lock was not re-secured." >&2 - exit 1 - fi - # Invitation toasts (like Voxtype/fingerprint setup) die with the old - # shell, and their notify-send waiters hang forever: the dying server - # never emits NotificationClosed. A still-running omarchy-*-invitation - # unit is therefore an unanswered invitation — re-run it so its toast - # reappears on the new shell. Answered invitations have already exited - # and been collected, so the glob no longer matches them. - systemctl --user try-restart 'omarchy-*-invitation.service' 2>/dev/null || true - exit 0 + if OMARCHY_PATH="$session_omarchy_path" OMARCHY_SHELL_IPC_TIMEOUT=0.5s omarchy-shell shell ping >/dev/null 2>&1; then + shell_ready=1 + break fi sleep 0.1 done +if (( shell_ready == 0 )); then + echo "Omarchy shell did not become ready after restart." >&2 + exit 1 +fi + +# The session stays compositor-locked after the old lock client died, so +# re-acquire the lock and let the user authenticate out of it. This comes +# first and depends on nothing else: a user stranded behind the failsafe must +# not wait on the notification plugin, which may be slow or absent. +if (( relock )) && ! relock_session; then + echo "Omarchy shell restarted, but the session lock was not re-secured." >&2 + exit 1 +fi + +# Core IPC answers before the notification plugin has registered its bus +# name, so wait for it separately before one-time toasts are sent. +if (( notifications_were_running )); then + notifications_restored=0 + for (( attempt = 0; attempt < 20; attempt++ )); do + if notifications_ready; then + notifications_restored=1 + break + fi + sleep 0.1 + done + if (( notifications_restored == 0 )); then + echo "Omarchy shell restarted, but its notification service did not become ready." >&2 + exit 1 + fi +fi -echo "Omarchy shell did not become ready after restart." >&2 -exit 1 +# Invitation toasts (like Voxtype/fingerprint setup) die with the old +# shell, and their notify-send waiters hang forever: the dying server +# never emits NotificationClosed. A still-running omarchy-*-invitation +# unit is therefore an unanswered invitation — re-run it so its toast +# reappears on the new shell. Answered invitations have already exited +# and been collected, so the glob no longer matches them. +systemctl --user try-restart 'omarchy-*-invitation.service' 2>/dev/null || true +exit 0 diff --git a/test/shell.d/restart-shell-test.sh b/test/shell.d/restart-shell-test.sh index 31901736d198..e6d81e627357 100755 --- a/test/shell.d/restart-shell-test.sh +++ b/test/shell.d/restart-shell-test.sh @@ -181,6 +181,12 @@ else [[ ! -f $OMARCHY_TEST_NOTIFICATION_CHECKS ]] || read -r checks <"$OMARCHY_TEST_NOTIFICATION_CHECKS" (( checks += 1 )) printf '%s\n' "$checks" >"$OMARCHY_TEST_NOTIFICATION_CHECKS" + # The service was running before the restart and, when asked to, never + # comes back afterwards. + if [[ ${OMARCHY_TEST_NOTIFICATIONS_DIE:-0} == 1 ]]; then + (( checks == 1 )) && echo 'b true' || echo 'b false' + exit 0 + fi if (( checks == 1 || checks >= 4 )); then echo 'b true' else @@ -285,3 +291,35 @@ restart_pid_one="" grep -F "ipc -n -p $restart_root/shell call -- lock lock" "$ipc_log" >/dev/null || fail "dead-lock recovery re-acquires the session lock" grep -F "ipc -n -p $restart_root/shell call -- lock status" "$ipc_log" >/dev/null || fail "dead-lock recovery waits for the lock to become secure" pass "restart recovers a locked session whose lock client died" + +# Lock recovery must not wait on the notification plugin: a stranded user gets +# the lock back even when notifications never return, and the restart then +# reports the missing service rather than claiming success. +sleep 30 & +restart_pid_one=$! +printf '%s\n' "$restart_pid_one" >"$restart_state" +rm -f "$restart_state.locked" "$test_tmp/notification-checks" +: >"$restart_log" +: >"$ipc_log" + +if PATH="$restart_bin:$PATH" \ + OMARCHY_PATH="$restart_root" \ + XDG_RUNTIME_DIR="$runtime_dir" \ + OMARCHY_TEST_SESSION_LOCKED=1 \ + OMARCHY_TEST_QS_STATE="$restart_state" \ + OMARCHY_TEST_QS_LOG="$restart_log" \ + OMARCHY_TEST_QS_ENV_LOG="$restart_env_log" \ + OMARCHY_TEST_DISPATCH_LOG="$dispatch_log" \ + OMARCHY_TEST_IPC_LOG="$ipc_log" \ + OMARCHY_TEST_SESSION_PATH="$restart_root" \ + OMARCHY_TEST_NOTIFICATION_CHECKS="$test_tmp/notification-checks" \ + OMARCHY_TEST_NOTIFICATIONS_DIE=1 \ + timeout 10 "$ROOT/bin/omarchy-restart-shell" >"$test_tmp/dead-notifications.out" 2>&1; then + fail "a restart whose notification service never returns must not report success" +fi +wait "$restart_pid_one" 2>/dev/null || true +restart_pid_one="" +grep -F "ipc -n -p $restart_root/shell call -- lock lock" "$ipc_log" >/dev/null || fail "lock recovery waited on the notification service" "$(cat "$ipc_log")" +[[ -f $restart_state.locked ]] || fail "lock recovery did not re-secure the session without notifications" +grep -q "notification service did not become ready" "$test_tmp/dead-notifications.out" || fail "a missing notification service is not reported" "$(cat "$test_tmp/dead-notifications.out")" +pass "restart recovers the lock even when the notification service never returns" From 43b91163f6033f3a562653e4c4217cb407eb72f0 Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Thu, 17 Sep 2026 20:33:59 +0100 Subject: [PATCH 089/194] Install cleanup traps before the entry revocation and bound the bus probe The protected entrypoints revoked the sudo timestamp before installing their cleanup traps, so a signal or failure during that first sudo -k exited without the cleanup path. Install the traps first. The shell restart probed the notification bus name with busctl's default 25 second timeout, so an unresponsive user bus could stall the restart by that much per probe. Bound each probe to one second. Co-Authored-By: Claude Fable 5.1 --- bin/omarchy-channel-set | 4 +++- bin/omarchy-refresh-pacman | 4 +++- bin/omarchy-restart-shell | 4 +++- bin/omarchy-update | 4 +++- bin/omarchy-update-stay-awake | 4 +++- 5 files changed, 15 insertions(+), 5 deletions(-) diff --git a/bin/omarchy-channel-set b/bin/omarchy-channel-set index a00c9d929df1..039d3292cdf8 100755 --- a/bin/omarchy-channel-set +++ b/bin/omarchy-channel-set @@ -15,8 +15,10 @@ set -euo pipefail omarchy_security_sanitize_bash_environment "$0" "$@" omarchy_security_require_source_root "$0" user_path=$PATH -omarchy_security_revoke_sudo_timestamp || exit 1 +# Traps first, so a signal or failure during the entry revocation still +# exits through the cleanup path. omarchy_security_install_sudo_cleanup_traps +omarchy_security_revoke_sudo_timestamp || exit 1 omarchy_security_enable_no_update_sudo usage() { echo "Usage: omarchy-channel-set [stable|rc|edge|dev]"; } diff --git a/bin/omarchy-refresh-pacman b/bin/omarchy-refresh-pacman index cd9eab1113ff..7406e6ad9db3 100755 --- a/bin/omarchy-refresh-pacman +++ b/bin/omarchy-refresh-pacman @@ -18,8 +18,10 @@ omarchy_security_require_source_root "$0" # caller's original path over the same way the updater receives it. user_path=${OMARCHY_UPDATE_USER_PATH:-$PATH} unset OMARCHY_UPDATE_USER_PATH -omarchy_security_revoke_sudo_timestamp || exit 1 +# Traps first, so a signal or failure during the entry revocation still +# exits through the cleanup path. omarchy_security_install_sudo_cleanup_traps +omarchy_security_revoke_sudo_timestamp || exit 1 omarchy_security_enable_no_update_sudo channel="${1:-stable}" diff --git a/bin/omarchy-restart-shell b/bin/omarchy-restart-shell index 4ca6ba293c92..8d3d6ce94aef 100755 --- a/bin/omarchy-restart-shell +++ b/bin/omarchy-restart-shell @@ -61,8 +61,10 @@ relock_session() { return 1 } +# A short timeout keeps an unresponsive user bus from stalling the restart; +# busctl would otherwise wait 25 seconds per probe. notifications_ready() { - [[ $(busctl --user call org.freedesktop.DBus /org/freedesktop/DBus \ + [[ $(busctl --user --timeout=1s call org.freedesktop.DBus /org/freedesktop/DBus \ org.freedesktop.DBus NameHasOwner s org.freedesktop.Notifications 2>/dev/null) == "b true" ]] } diff --git a/bin/omarchy-update b/bin/omarchy-update index 2d5ad4746c72..9c6d21d70d4f 100755 --- a/bin/omarchy-update +++ b/bin/omarchy-update @@ -20,8 +20,10 @@ omarchy_security_require_source_root "$0" # Preserve the caller's path only for the later unprivileged hook/mise phases. user_path=${OMARCHY_UPDATE_USER_PATH:-$PATH} unset OMARCHY_UPDATE_USER_PATH -omarchy_security_revoke_sudo_timestamp || exit 1 +# Traps first, so a signal or failure during the entry revocation still +# exits through the cleanup path. omarchy_security_install_sudo_cleanup_traps +omarchy_security_revoke_sudo_timestamp || exit 1 omarchy_security_enable_no_update_sudo update_stay_awake_stopped=0 diff --git a/bin/omarchy-update-stay-awake b/bin/omarchy-update-stay-awake index af941c4a3d11..be27a2cc962a 100755 --- a/bin/omarchy-update-stay-awake +++ b/bin/omarchy-update-stay-awake @@ -15,8 +15,10 @@ omarchy_security_require_privileged_bash_startup || exit 126 set -e omarchy_security_sanitize_bash_environment "$0" "$@" omarchy_security_require_source_root "$0" -omarchy_security_revoke_sudo_timestamp || exit 1 +# Traps first, so a signal or failure during the entry revocation still +# exits through the cleanup path. omarchy_security_install_sudo_cleanup_traps +omarchy_security_revoke_sudo_timestamp || exit 1 omarchy_security_enable_no_update_sudo state_dir="${XDG_RUNTIME_DIR:-/tmp/omarchy-$UID}/omarchy-update-stay-awake" From c8407ee73fa5ba056ef213c00df59b786765bbb4 Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Thu, 17 Sep 2026 20:30:27 +0100 Subject: [PATCH 090/194] Cover completion failures in the package scriptlet contract pacman continues a transaction after a failed scriptlet. Model that in the shared package-scriptlet contract: a failed pre_upgrade followed by post_upgrade must keep the removal blocker while a rule remains, a clean retry recovers, a stranded blocker with a live rule is cleaned by the next completed installation, a fresh install that cannot remove a leftover rule leaves publication refused, and the sweep does not depend on inherited glob state. Co-Authored-By: Claude Fable 5.1 --- .../passwordless-grant-lifecycle-test.sh | 54 +++++++++++++++++-- 1 file changed, 51 insertions(+), 3 deletions(-) diff --git a/test/shell.d/passwordless-grant-lifecycle-test.sh b/test/shell.d/passwordless-grant-lifecycle-test.sh index 71f34b2409c2..2eee2dea3003 100644 --- a/test/shell.d/passwordless-grant-lifecycle-test.sh +++ b/test/shell.d/passwordless-grant-lifecycle-test.sh @@ -115,9 +115,49 @@ for name in omarchy-settings omarchy-settings-dev; do enable_locked 1000 15 pre_upgrade && post_upgrade [[ ! -e $(rule_file 1000) && ! -e $REMOVAL_BLOCKER ]] + # pacman does not stop a transaction on a failed scriptlet, so a failed + # pre_upgrade can be followed directly by post_upgrade. Completion must + # not clear the blocker while a rule remains, and a clean retry recovers. + enable_locked 1000 15 + TEST_DELETE_FAIL=1 assert_status 1 pre_upgrade + TEST_DELETE_FAIL=1 assert_status 1 post_upgrade + [[ -e $REMOVAL_BLOCKER && -e $(rule_file 1000) ]] + assert_status 1 enable_locked 1000 15 + post_upgrade + [[ ! -e $(rule_file 1000) && ! -e $REMOVAL_BLOCKER ]] + # A stranded blocker plus a live rule from an interrupted removal is + # cleaned by the next completed installation, not merely unblocked. + enable_locked 1000 15 + : >"$REMOVAL_BLOCKER" + post_install + [[ ! -e $(rule_file 1000) && ! -e $REMOVAL_BLOCKER ]] + # A fresh install has no earlier step, so completion must hold the blocker + # itself while it sweeps: a leftover rule it cannot remove leaves + # publication refused rather than merely reporting an error. + enable_locked 1000 15 + rm -f "$REMOVAL_BLOCKER" + TEST_DELETE_FAIL=1 assert_status 1 post_install + [[ -e $REMOVAL_BLOCKER && -e $(rule_file 1000) ]] + assert_status 1 enable_locked 1000 15 + post_install + [[ ! -e $(rule_file 1000) && ! -e $REMOVAL_BLOCKER ]] + # The sweep must not depend on the glob state pacman's shell inherits. + enable_locked 1000 15 + ( set -f; GLOBIGNORE='*' post_upgrade ) + [[ ! -e $(rule_file 1000) && ! -e $REMOVAL_BLOCKER ]] + # A failure before the lock is even taken, such as an untrusted lock + # directory, must still leave publication refused. + enable_locked 1000 15 + rm -f "$REMOVAL_BLOCKER" + TEST_BAD_PATH="$test_tmp/run/lock" assert_status 1 post_install + [[ -e $REMOVAL_BLOCKER && -e $(rule_file 1000) ]] + TEST_BAD_PATH="$test_tmp/run/lock" assert_status 1 pre_upgrade + [[ -e $REMOVAL_BLOCKER ]] + post_install + [[ ! -e $(rule_file 1000) && ! -e $REMOVAL_BLOCKER ]] ) done -pass "both settings packages revoke grants, block publication, and recover on installation" +pass "both settings packages revoke grants, block publication, and recover on installation only with the namespace empty" reset_grant # Hold the source lock, then start package removal. A native flock on the @@ -148,13 +188,21 @@ done /usr/bin/bash -euo pipefail -c 'source "$1"; pre_remove; post_remove' bash "$test_tmp/omarchy-settings.install" >"$test_tmp/removal.log" 2>&1 & removal=$! children+=("$removal") +# The removal announces itself before waiting for the lock, so a publisher +# still holding it is refused rather than allowed to publish a rule that the +# removal would delete a moment later. +for (( attempt=0; attempt<200; attempt++ )); do + [[ ! -f $test_tmp/run/omarchy-sudo-passwordless-package-removing ]] || break + sleep 0.01 +done +[[ -f $test_tmp/run/omarchy-sudo-passwordless-package-removing ]] || fail "removal did not announce itself before waiting for the lock" touch "$test_tmp/release" -wait "$publisher" || fail "publisher failed" "$(cat "$test_tmp/publisher.log")" +if wait "$publisher"; then fail "publisher was allowed to publish after removal announced itself" "$(cat "$test_tmp/publisher.log")"; fi wait "$removal" || fail "removal failed" "$(cat "$test_tmp/removal.log")" children=() [[ ! -e $test_tmp/etc/sudoers.d/99-omarchy-nopasswd-1000 ]] [[ -f $test_tmp/run/omarchy-sudo-passwordless-package-removing ]] -pass "native lock serializes grant publication with package removal" +pass "an announced package removal refuses a waiting publisher and clears the namespace" # systemd-tmpfiles operates on an explicit disposable root, never the host. reset_grant From 67a813d8d23d0783898b56aa8ed99d87d038a5ca Mon Sep 17 00:00:00 2001 From: Afonso Oliveira Date: Thu, 17 Sep 2026 20:37:17 +0100 Subject: [PATCH 091/194] Bound the grant lock wait The settings package's pre-transaction hook runs this command under pacman's transaction. Its lock wait was unbounded, so a stalled grant operation could hang pacman indefinitely before AbortOnFail ever saw a result. Grant operations are short; wait at most 60 seconds. Co-Authored-By: Claude Fable 5.1 --- bin/omarchy-sudo-passwordless | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/bin/omarchy-sudo-passwordless b/bin/omarchy-sudo-passwordless index 58a9b15c6116..b5f88a941104 100755 --- a/bin/omarchy-sudo-passwordless +++ b/bin/omarchy-sudo-passwordless @@ -86,7 +86,9 @@ with_root_lock() { exec {fd}>"$LOCK_FILE" || return 1 /usr/bin/chown root:root "$LOCK_FILE" || return 1 /usr/bin/chmod 0600 "$LOCK_FILE" || return 1 - /usr/bin/flock -x "$fd" || return 1 + # Grant operations are short. A stalled holder must not hang a caller + # indefinitely, least of all pacman's pre-transaction hook. + /usr/bin/flock -x -w 60 "$fd" || return 1 "$@" || rc=$? /usr/bin/flock -u "$fd" || rc=1 exec {fd}>&- From 531c3e890ff0b3c062fa046c8115f72a9122bf09 Mon Sep 17 00:00:00 2001 From: Spencer Bull Date: Wed, 16 Sep 2026 13:09:54 -0500 Subject: [PATCH 092/194] Install Elsewhen, the world clock plugin, by default Elsewhen (omacom.elsewhen) arrives as the elsewhen package under /usr/share/omarchy/plugins, the packaged root the shell scans between its bundled plugins and the user's. It opens the right section of the default bar, just before the tray, and a migration installs the package, writes the widget into a customized shell.json in the same spot, and retires a pristine pre-package clone of the upstream repo that the package now shadows. --- config/omarchy/shell.json | 3 + default/agents/skills/omarchy/plugins.md | 5 + docs/file-layout.md | 3 + docs/omarchy-shell.md | 13 + install/omarchy-base.packages | 1 + migrations/1789581661.sh | 85 ++++++ shell/README.md | 14 + shell/plugins/README.md | 6 +- test/shell.d/config-test.sh | 5 +- .../elsewhen-default-migration-test.sh | 285 ++++++++++++++++++ 10 files changed, 417 insertions(+), 3 deletions(-) create mode 100644 migrations/1789581661.sh create mode 100644 test/shell.d/elsewhen-default-migration-test.sh diff --git a/config/omarchy/shell.json b/config/omarchy/shell.json index e6202da85d90..64cc40751bc6 100644 --- a/config/omarchy/shell.json +++ b/config/omarchy/shell.json @@ -38,6 +38,9 @@ } ], "right": [ + { + "id": "omacom.elsewhen" + }, { "id": "omarchy.tray" }, diff --git a/default/agents/skills/omarchy/plugins.md b/default/agents/skills/omarchy/plugins.md index 6e3ab0695ea5..bf1033b3ec05 100644 --- a/default/agents/skills/omarchy/plugins.md +++ b/default/agents/skills/omarchy/plugins.md @@ -9,9 +9,14 @@ inside a single long-running Quickshell process (`omarchy-shell`). ``` ~/.config/omarchy/shell.json # User overrides: bar, plugins, idle ~/.config/omarchy/plugins// # User-owned shell plugins +/usr/share/omarchy/plugins// # Packaged plugins (pacman), e.g. omacom.elsewhen $OMARCHY_PATH/config/omarchy/shell.json # Canonical defaults ``` +Packaged plugins such as Elsewhen (`elsewhen` package) update with `omarchy update` and are removed with pacman; +`omarchy plugin update` and `omarchy plugin remove` refuse them and name the +package. + The shell hot-reloads `shell.json` on save — no restart needed for layout changes. `idle.screensaver` and `idle.lock` are seconds since user idle began. diff --git a/docs/file-layout.md b/docs/file-layout.md index f261085f0eae..8bbcd5b2cdd3 100644 --- a/docs/file-layout.md +++ b/docs/file-layout.md @@ -78,6 +78,9 @@ install/** ──► omarchy /usr/share/omarchy migrations/** ──► omarchy /usr/share/omarchy/migrations/ themes/** ──► omarchy /usr/share/omarchy/themes/ shell/** ──► omarchy /usr/share/omarchy/shell/ + (packaged plugins from their own + packages, e.g. elsewhen, land beside it + in /usr/share/omarchy/plugins//) version ──► omarchy /usr/share/omarchy/version + /etc/skel/.local/state/omarchy/migrations/* diff --git a/docs/omarchy-shell.md b/docs/omarchy-shell.md index d62ff7436df9..18a6189616c9 100644 --- a/docs/omarchy-shell.md +++ b/docs/omarchy-shell.md @@ -88,6 +88,19 @@ bar from the CLI — `use | reset | defaults | position | transparent | put | move | set`, with placement flags such as `--section` and `--index`. The lower-level IPC methods remain available through `omarchy-shell shell ...`. +## Packaged plugins + +A default plugin can ship as its own Arch package instead of in the Omarchy +checkout: Elsewhen (`omacom.elsewhen`) is the `elsewhen` package. pacman installs them at +`/usr/share/omarchy/plugins//`, a root the shell scans between +`$OMARCHY_PATH/shell/plugins` and `~/.config/omarchy/plugins`. A packaged +`omarchy.*` id is trusted like a bundled plugin and loads by default; any other +packaged id behaves like an installed plugin. Precedence is bundled, then +packaged, then user, so a checkout under `omarchy dev link` overrides the +package. Packaged plugins update through `omarchy update` and leave through +pacman; `omarchy plugin update` and `omarchy plugin remove` refuse them and +name the package, and Setup › Plugins › Remove does not list them. + ## IPC The shell exposes a `shell` target (the host also registers diff --git a/install/omarchy-base.packages b/install/omarchy-base.packages index 76e741108cf6..0a8e27cca73a 100644 --- a/install/omarchy-base.packages +++ b/install/omarchy-base.packages @@ -26,6 +26,7 @@ docker-compose dosfstools dotnet-runtime dua-cli +elsewhen evince exfatprogs expac diff --git a/migrations/1789581661.sh b/migrations/1789581661.sh new file mode 100644 index 000000000000..fd5d30be8837 --- /dev/null +++ b/migrations/1789581661.sh @@ -0,0 +1,85 @@ +echo "Install Elsewhen, the world clock plugin" + +# Elsewhen ships as the elsewhen package rather than in this checkout; pacman +# puts it under /usr/share/omarchy/plugins, where the shell looks next to its +# bundled plugins. A package the mirror does not carry yet fails the migration +# on purpose: nothing before this line has changed anything, and the runner +# retries it on the next update or login rather than quietly leaving the +# machine without the plugin. +omarchy-pkg-add elsewhen + +# A shell that already knows the packaged root (dev-linked, or restarted +# since) picks the plugin up here; the one an update runs under predates it +# and is replaced by omarchy-update-restart right after the migrations. +omarchy-shell -q shell rescanPlugins || true + +# Before the package, the README had users run +# `omarchy plugin add https://github.com/omacom/elsewhen.git`, which left a +# git clone under ~/.config/omarchy/plugins. The packaged copy now shadows +# it: the shell logs a rejection on every scan, and `omarchy plugin update` +# keeps pulling a checkout nothing loads. A pristine clone of the upstream +# repo is retired the way `omarchy plugin remove` retires one (the repo +# remains upstream). Anything else -- a symlink, a plain directory, local +# changes, a fork, a checkout git cannot read -- is the user's and stays. This +# runs only once the package is in place, so the plugin never leaves a +# machine; its id stays in shell.json either way, which is what keeps it +# enabled. The shell an update runs under predates the packaged root, and it +# watches this directory: dropping the checkout empties the widget's slot in +# that shell until omarchy-update-restart replaces it a few steps later with +# one that finds the package. A one-time gap of a few minutes, during the +# update itself. +upstream_checkout() { + local dir="$1" origin status + [[ -d $dir && ! -L $dir && -d $dir/.git ]] || return 1 + origin=$(git -C "$dir" remote get-url origin 2>/dev/null) || return 1 + origin=${origin,,} + origin=${origin%/} + origin=${origin%.git} + [[ $origin =~ ^([a-z+]+://)?([^/@]+@)?github\.com[/:]omacom/elsewhen$ ]] || return 1 + status=$(git -C "$dir" status --porcelain 2>/dev/null) || return 1 + [[ -z $status ]] +} + +checkout="$HOME/.config/omarchy/plugins/omacom.elsewhen" +if [[ -e $checkout || -L $checkout ]]; then + if upstream_checkout "$checkout"; then + rm -rf "$checkout" + echo "Retired the omacom.elsewhen checkout at $checkout in favour of the elsewhen package." + else + echo "The elsewhen package takes precedence over $checkout, which is left as it is." + fi +fi + +# The widget opens the right section of the default bar, just before the +# tray, which a machine without a shell.json takes on as soon as the shell +# restarts. A customized bar gets the entry written into its file rather than +# placed over IPC: the shell this runs under cannot see a widget its scan +# never reached and would refuse it, whereas the file it hot-reloads carries +# the entry through to the restart. A bar that already carries the widget +# keeps it where the user put it. +source omarchy-shell-config + +[[ -s $CONFIG_FILE ]] || exit 0 +# A file the shell cannot read is left for its owner to repair. +jq empty "$CONFIG_FILE" 2>/dev/null || exit 0 + +entry_id='def entry_id: if type == "object" then (.id // "" | tostring) else tostring end;' + +if jq -e "$entry_id"' + any((.bar.layout // {} | .left, .center, .right | arrays)[]; entry_id == "omacom.elsewhen") +' "$CONFIG_FILE" >/dev/null; then + exit 0 +fi + +commit "$NORMALIZE | $entry_id"' + def ids: map(entry_id); + def insert_at($section; $index): + .bar.layout[$section] = .bar.layout[$section][:$index] + [{id: "omacom.elsewhen"}] + .bar.layout[$section][$index:]; + . as $config + | (["left", "center", "right"] | map(select($config.bar.layout[.] | ids | index("omarchy.tray") != null)) | first) as $section + | if $section != null then + insert_at($section; .bar.layout[$section] | ids | index("omarchy.tray")) + else + insert_at("right"; 0) + end +' diff --git a/shell/README.md b/shell/README.md index ca07b520ae44..23a25ca656f3 100644 --- a/shell/README.md +++ b/shell/README.md @@ -140,6 +140,19 @@ You can still drop a plugin in without git: `barWidget.defaultSection`, or in the center when it is omitted, and can be moved with `omarchy bar move`; a full bar replaces the one in use. +### Packaged plugins + +Some default plugins ship as their own Arch package rather than in this +checkout: Elsewhen (`omacom.elsewhen`) is the `elsewhen` package. pacman installs such a plugin, +root-owned, at `/usr/share/omarchy/plugins//`, and +the shell scans that root between its bundled plugins and the user's. A +packaged `omarchy.*` id is trusted exactly like a bundled one; a packaged +plugin under any other id is treated like a user plugin. They update with +`omarchy update` and are removed with pacman, so `omarchy plugin update` and +`omarchy plugin remove` refuse them and name the package instead. A bundled +copy in `$OMARCHY_PATH/shell/plugins` wins over the packaged one, which is how +a packaged plugin is developed under `omarchy dev link`. + The lower-level IPC equivalents remain available via `omarchy-shell shell rescanPlugins`, `omarchy-shell shell enablePlugin '{}'`, and `omarchy-shell shell listPlugins`. The `omarchy plugin` commands wrap those calls. `omarchy bar move` and @@ -224,6 +237,7 @@ customization from the shipped defaults lives in it. |-----------------------------------|----------------|--------------------------------------------------------| | `~/.config/omarchy/shell.json` | the shell | full layout + per-entry settings + enabled plugin list | | `~/.config/omarchy/plugins//` | user | drop-in third-party plugin source files | +| `/usr/share/omarchy/plugins//` | pacman | packaged plugins (e.g. `elsewhen`), updated by `omarchy update` | The `config/omarchy/shell.json` default config describes the fresh-install state. When the user has no `shell.json`, the shell uses diff --git a/shell/plugins/README.md b/shell/plugins/README.md index 66cb74e14fdb..1a2d26fb0bc5 100644 --- a/shell/plugins/README.md +++ b/shell/plugins/README.md @@ -9,7 +9,10 @@ First-party non-bar plugins are enabled unless listed in `disabledPlugins[]`; at startup; other panels, overlays, and menus are loaded on demand. User-installed plugins live alongside these conceptually but on disk under -`~/.config/omarchy/plugins//` rather than in this directory. +`~/.config/omarchy/plugins//` rather than in this directory. A few +default plugins arrive as their own package instead: pacman installs them at +`/usr/share/omarchy/plugins//`, where an `omarchy.*` id is trusted +like the plugins here, and a copy in this directory shadows the packaged one. | Plugin | id | kinds | entry point | |---------------|---------------------------|-------------------------|---------------------------------------| @@ -28,6 +31,7 @@ User-installed plugins live alongside these conceptually but on disk under | Power | `omarchy.power` | `bar-widget` | `panels/power/Panel.qml` | | Tailscale | `omarchy.tailscale` | `bar-widget` | `panels/tailscale/Panel.qml` | | Agents | `omarchy.agents` | `bar-widget` | `agents/Panel.qml` | +| Elsewhen | `omacom.elsewhen` | `bar-widget` | packaged: `elsewhen` installs `/usr/share/omarchy/plugins/omacom.elsewhen/` | | Weather | `omarchy.weather` | `bar-widget` | `panels/weather/BarWidget.qml` | | Media | `omarchy.media` | `service`, `bar-widget` | `services/media/Service.qml`, `services/media/BarWidget.qml` | | Battery | `omarchy.battery` | `service` | `services/battery/Service.qml` | diff --git a/test/shell.d/config-test.sh b/test/shell.d/config-test.sh index 355ca26b9e02..d9086d4469ab 100755 --- a/test/shell.d/config-test.sh +++ b/test/shell.d/config-test.sh @@ -41,11 +41,12 @@ pass "default clock date format has no leading zero" jq -e ' def ids: map(.id // .); (.bar.layout.right | ids) as $ids | + ($ids | index("omacom.elsewhen")) as $elsewhen | ($ids | index("omarchy.tray")) as $tray | ($ids | index("omarchy.agents")) as $agents | - $tray != null and $agents == $tray + 1 + $elsewhen == 0 and $tray == 1 and $agents == $tray + 1 ' "$ROOT/config/omarchy/shell.json" >/dev/null -pass "default right layout keeps agents next to the tray" +pass "default right layout opens with elsewhen and the tray, then agents" ROOT="$ROOT" python3 <<'PY' import json diff --git a/test/shell.d/elsewhen-default-migration-test.sh b/test/shell.d/elsewhen-default-migration-test.sh new file mode 100644 index 000000000000..438ba1d30220 --- /dev/null +++ b/test/shell.d/elsewhen-default-migration-test.sh @@ -0,0 +1,285 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +require_command jq +require_command git + +migration="$ROOT/migrations/1789581661.sh" +test_dir=$(mktemp -d) +trap 'rm -rf "$test_dir"' EXIT + +mkdir -p "$test_dir/bin" +export INSTALLED_PACKAGES="$test_dir/installed" CALL_LOG="$test_dir/calls" SHELL_CALLS="$test_dir/shell-calls" +# The checkout cases use the real git; keep the developer's config (signing, +# hooks, safe.directory) out of what it sees. +export GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 +export GIT_AUTHOR_NAME=test GIT_AUTHOR_EMAIL=test@example.com +export GIT_COMMITTER_NAME=test GIT_COMMITTER_EMAIL=test@example.com + +# Keep the real package helpers, but contain every pacman transaction here. +cat >"$test_dir/bin/pacman" <<'SH' +#!/bin/bash +case "$1" in + -Q) grep -Fxq -- "$2" "$INSTALLED_PACKAGES" ;; + -S) + [[ ${FAIL_INSTALL:-0} == 0 ]] || exit 1 + shift 3 # -S --noconfirm --needed + printf '%s\n' "$@" >>"$INSTALLED_PACKAGES" + printf '%s\n' "$@" >>"$CALL_LOG" + ;; + *) exit 1 ;; +esac +SH +cat >"$test_dir/bin/sudo" <<'SH' +#!/bin/bash +[[ $1 == "pacman" ]] || exit 1 +"$@" +SH +# The migration runs under a shell that predates the packaged root, or under +# none at all, so it must only ever ask the shell for best-effort refreshes. +cat >"$test_dir/bin/omarchy-shell" <<'SH' +#!/bin/bash +printf '%s\n' "$*" >>"$SHELL_CALLS" +[[ $1 != "-q" ]] || exit 0 +exit "${SHELL_STATUS:-0}" +SH +chmod +x "$test_dir/bin/"* + +home="$test_dir/home" +config="$home/.config/omarchy/shell.json" +checkout="$home/.config/omarchy/plugins/omacom.elsewhen" +output="$test_dir/output" +mkdir -p "$home/.config/omarchy" + +run_migration() { + : >"$CALL_LOG" + : >"$SHELL_CALLS" + HOME="$home" OMARCHY_PATH="$ROOT" PATH="$test_dir/bin:$ROOT/bin:$PATH" \ + bash -euo pipefail "$migration" >"$output" +} + +ids() { + jq -c ".bar.layout.$1 | map(if type == \"object\" then .id else . end)" "$config" +} + +# ------------------------------------------------------------ package install +: >"$INSTALLED_PACKAGES" +cat >"$config" <<'JSON' +{ + "version": 1, + "bar": { + "layout": { + "left": [{ "id": "omarchy.menu" }], + "center": [{ "id": "omarchy.clock", "format": "HH:mm" }], + "right": [ + { "id": "omarchy.tray" }, + { "id": "omarchy.agents", "syncMode": "On" }, + { "id": "omarchy.power" } + ] + } + }, + "plugins": [] +} +JSON + +run_migration +grep -Fxq elsewhen "$CALL_LOG" || fail "migration installs the elsewhen package" "$(cat "$CALL_LOG")" +pass "migration installs the elsewhen package" + +[[ $(ids right) == '["omacom.elsewhen","omarchy.tray","omarchy.agents","omarchy.power"]' ]] || + fail "migration puts the widget just before the tray" "$(cat "$config")" +pass "migration puts the widget just before the tray" + +[[ $(jq -c '.bar.layout.right[2]' "$config") == '{"id":"omarchy.agents","syncMode":"On"}' ]] || + fail "migration keeps the settings of its neighbours" "$(cat "$config")" +[[ $(jq -c '.bar.layout.center[0]' "$config") == '{"format":"HH:mm","id":"omarchy.clock"}' ]] || + fail "migration leaves other sections alone" "$(cat "$config")" +pass "migration leaves the rest of the layout alone" + +grep -q 'shell rescanPlugins' "$SHELL_CALLS" && grep -q 'shell reloadConfig' "$SHELL_CALLS" || + fail "migration asks the running shell to rescan and reload" "$(cat "$SHELL_CALLS")" +pass "migration asks the running shell to rescan and reload" + +before=$(sha256sum "$config") +run_migration +[[ $before == $(sha256sum "$config") ]] || fail "migration is idempotent" "$(cat "$config")" +[[ ! -s $CALL_LOG ]] || fail "migration does not reinstall a present package" "$(cat "$CALL_LOG")" +pass "migration is idempotent" + +# ------------------------------------------------------------- placements +cat >"$config" <<'JSON' +{ + "version": 1, + "bar": { "layout": { "left": [], "center": ["omarchy.clock", "omarchy.tray"], "right": ["omarchy.power"] } } +} +JSON +run_migration +[[ $(ids center) == '["omarchy.clock","omacom.elsewhen","omarchy.tray"]' && $(ids right) == '["omarchy.power"]' ]] || + fail "migration follows the tray into another section and reads string entries" "$(cat "$config")" +pass "migration follows the tray into another section and reads string entries" + +cat >"$config" <<'JSON' +{ "version": 1, "bar": { "layout": { "right": [{ "id": "omarchy.agents" }, { "id": "omarchy.power" }] } } } +JSON +run_migration +[[ $(ids right) == '["omacom.elsewhen","omarchy.agents","omarchy.power"]' ]] || + fail "migration prepends to the right section when the tray is off the bar" "$(cat "$config")" +pass "migration prepends to the right section when the tray is off the bar" + +cat >"$config" <<'JSON' +{ + "version": 1, + "bar": { "layout": { "left": [{ "id": "omacom.elsewhen" }], "center": [], "right": [{ "id": "omarchy.tray" }, { "id": "omarchy.agents" }] } } +} +JSON +before=$(sha256sum "$config") +run_migration +[[ $before == $(sha256sum "$config") ]] || + fail "migration leaves a widget the user already placed where it is" "$(cat "$config")" +pass "migration leaves a widget the user already placed where it is" + +# ------------------------------------------------------------- edge cases +rm -f "$config" +run_migration +[[ ! -e $config ]] || fail "migration writes no shell.json where the defaults apply" "$(cat "$config")" +pass "migration writes no shell.json where the defaults apply" + +printf '{ not json' >"$config" +run_migration +[[ $(cat "$config") == '{ not json' ]] || fail "migration leaves an unparsable config untouched" "$(cat "$config")" +pass "migration leaves an unparsable config untouched" + +cat >"$config" <<'JSON' +{ "version": 1, "bar": { "layout": { "right": [{ "id": "omarchy.tray" }, { "id": "omarchy.agents" }] } } } +JSON +SHELL_STATUS=1 run_migration +[[ $(ids right) == '["omacom.elsewhen","omarchy.tray","omarchy.agents"]' ]] || + fail "migration places the widget with no shell running" "$(cat "$config")" +pass "migration places the widget with no shell running" + +# A package the mirror does not carry yet leaves the migration pending rather +# than half-done: the layout must not name a widget nothing can install. +: >"$INSTALLED_PACKAGES" +cat >"$config" <<'JSON' +{ "version": 1, "bar": { "layout": { "right": [{ "id": "omarchy.tray" }, { "id": "omarchy.agents" }] } } } +JSON +before=$(sha256sum "$config") +if FAIL_INSTALL=1 run_migration 2>/dev/null; then + fail "a failed package installation must leave the migration pending" +fi +[[ $before == $(sha256sum "$config") ]] || + fail "a failed package installation leaves the layout untouched" "$(cat "$config")" +pass "a failed package installation is propagated and changes nothing" + +# ------------------------------------------------- pre-package checkouts +# Users who followed the README before the package existed hold a git clone +# under ~/.config/omarchy/plugins, which the packaged copy now shadows. Only a +# clone of the upstream repo with nothing local in it is retired; everything +# else is the user's and stays, and shell.json gets the widget either way. + +# A clone made by `omarchy plugin add`: one commit, the given origin, nothing +# local. Built with init rather than clone so the origin can be any URL form. +make_checkout() { + local origin="$1" + rm -rf "$checkout" + mkdir -p "$checkout" + git -C "$checkout" init -q + git -C "$checkout" remote add origin "$origin" + printf '{ "id": "omacom.elsewhen" }\n' >"$checkout/manifest.json" + printf 'import QtQuick\nItem {}\n' >"$checkout/Panel.qml" + git -C "$checkout" add -A + git -C "$checkout" commit -q -m "Elsewhen" +} + +reset_layout() { + cat >"$config" <<'JSON' +{ "version": 1, "bar": { "layout": { "right": [{ "id": "omarchy.tray" }, { "id": "omarchy.power" }] } } } +JSON +} + +assert_widget_placed() { + [[ $(ids right) == '["omacom.elsewhen","omarchy.tray","omarchy.power"]' ]] || + fail "$1 still gets the widget" "$(cat "$config")" +} + +assert_retired() { + local description="$1" + [[ ! -e $checkout && ! -L $checkout ]] || fail "$description is retired" "$(ls -la "$checkout")" + grep -q 'Retired the omacom.elsewhen checkout' "$output" || fail "$description is reported as retired" "$(cat "$output")" + assert_widget_placed "$description" + pass "$description is retired" +} + +assert_kept() { + local description="$1" + [[ -e $checkout || -L $checkout ]] || fail "$description is kept" + grep -q 'takes precedence over' "$output" || fail "$description is reported as shadowed" "$(cat "$output")" + assert_widget_placed "$description" + pass "$description is kept" +} + +for origin in \ + https://github.com/omacom/elsewhen.git \ + https://github.com/omacom/elsewhen \ + git@github.com:omacom/elsewhen.git \ + ssh://git@github.com/omacom/elsewhen.git \ + https://GitHub.com/Omacom/Elsewhen/; do + make_checkout "$origin" + reset_layout + run_migration + assert_retired "a pristine clone with origin $origin" +done + +make_checkout https://github.com/omacom/elsewhen.git +printf 'import QtQuick\nItem { id: mine }\n' >"$checkout/Panel.qml" +reset_layout +run_migration +assert_kept "a clone with a modified tracked file" +[[ $(cat "$checkout/Panel.qml") == $'import QtQuick\nItem { id: mine }' ]] || + fail "a kept clone keeps its local change" "$(cat "$checkout/Panel.qml")" +pass "a kept clone keeps its local change" + +make_checkout https://github.com/omacom/elsewhen.git +printf 'notes\n' >"$checkout/NOTES.md" +reset_layout +run_migration +assert_kept "a clone with an untracked file" + +make_checkout https://github.com/someone/elsewhen-fork.git +reset_layout +run_migration +assert_kept "a clone of another repository" + +make_checkout https://github.com/omacom/elsewhen.git +git -C "$checkout" remote remove origin +reset_layout +run_migration +assert_kept "a clone without an origin remote" + +rm -rf "$checkout" +mkdir -p "$checkout" +printf '{ "id": "omacom.elsewhen" }\n' >"$checkout/manifest.json" +reset_layout +run_migration +assert_kept "a plain directory without .git" + +rm -rf "$checkout" +make_checkout https://github.com/omacom/elsewhen.git +mv "$checkout" "$test_dir/elsewhen-src" +ln -s "$test_dir/elsewhen-src" "$checkout" +reset_layout +run_migration +assert_kept "a symlinked checkout" +[[ -L $checkout && -f $test_dir/elsewhen-src/manifest.json ]] || + fail "a symlinked checkout stays a symlink with its target intact" "$(ls -la "$checkout" "$test_dir/elsewhen-src")" +pass "a symlinked checkout stays a symlink with its target intact" + +rm -f "$checkout" +reset_layout +run_migration +grep -q 'omacom.elsewhen checkout\|takes precedence' "$output" && fail "no checkout means no checkout report" "$(cat "$output")" +assert_widget_placed "a machine without a checkout" +pass "a machine without a checkout is left alone" From 49286d0e66b22d6b91e21c0f8c8fe8bd1a6ce064 Mon Sep 17 00:00:00 2001 From: Spencer Bull Date: Thu, 17 Sep 2026 21:07:08 -0500 Subject: [PATCH 093/194] Place Elsewhen immediately before the center clock --- config/omarchy/shell.json | 6 +-- default/agents/skills/omarchy/plugins.md | 4 +- docs/omarchy-shell.md | 11 +----- migrations/1789581661.sh | 10 ++--- shell/README.md | 11 +----- test/shell.d/config-test.sh | 14 +++++-- .../elsewhen-default-migration-test.sh | 37 ++++++++++++------- 7 files changed, 45 insertions(+), 48 deletions(-) diff --git a/config/omarchy/shell.json b/config/omarchy/shell.json index 64cc40751bc6..b8aa5de48eb6 100644 --- a/config/omarchy/shell.json +++ b/config/omarchy/shell.json @@ -21,6 +21,9 @@ { "id": "omarchy.indicators" }, + { + "id": "omacom.elsewhen" + }, { "id": "omarchy.clock", "format": "dddd HH:mm", @@ -38,9 +41,6 @@ } ], "right": [ - { - "id": "omacom.elsewhen" - }, { "id": "omarchy.tray" }, diff --git a/default/agents/skills/omarchy/plugins.md b/default/agents/skills/omarchy/plugins.md index bf1033b3ec05..1c58c83ac38f 100644 --- a/default/agents/skills/omarchy/plugins.md +++ b/default/agents/skills/omarchy/plugins.md @@ -13,9 +13,7 @@ inside a single long-running Quickshell process (`omarchy-shell`). $OMARCHY_PATH/config/omarchy/shell.json # Canonical defaults ``` -Packaged plugins such as Elsewhen (`elsewhen` package) update with `omarchy update` and are removed with pacman; -`omarchy plugin update` and `omarchy plugin remove` refuse them and name the -package. +Packaged plugins such as Elsewhen (`elsewhen` package) update with `omarchy update` and are removed with pacman; `omarchy plugin update` and `omarchy plugin remove` refuse them and name the package. The shell hot-reloads `shell.json` on save — no restart needed for layout changes. `idle.screensaver` and `idle.lock` are seconds since user idle began. diff --git a/docs/omarchy-shell.md b/docs/omarchy-shell.md index 18a6189616c9..dd8cc18a7bcb 100644 --- a/docs/omarchy-shell.md +++ b/docs/omarchy-shell.md @@ -90,16 +90,7 @@ The lower-level IPC methods remain available through `omarchy-shell shell ...`. ## Packaged plugins -A default plugin can ship as its own Arch package instead of in the Omarchy -checkout: Elsewhen (`omacom.elsewhen`) is the `elsewhen` package. pacman installs them at -`/usr/share/omarchy/plugins//`, a root the shell scans between -`$OMARCHY_PATH/shell/plugins` and `~/.config/omarchy/plugins`. A packaged -`omarchy.*` id is trusted like a bundled plugin and loads by default; any other -packaged id behaves like an installed plugin. Precedence is bundled, then -packaged, then user, so a checkout under `omarchy dev link` overrides the -package. Packaged plugins update through `omarchy update` and leave through -pacman; `omarchy plugin update` and `omarchy plugin remove` refuse them and -name the package, and Setup › Plugins › Remove does not list them. +A default plugin can ship as its own Arch package instead of in the Omarchy checkout: Elsewhen (`omacom.elsewhen`) is the `elsewhen` package. pacman installs it at `/usr/share/omarchy/plugins//`, a root the shell scans between `$OMARCHY_PATH/shell/plugins` and `~/.config/omarchy/plugins`. A packaged `omarchy.*` id is trusted like a bundled plugin and loads by default; any other packaged id behaves like an installed plugin. Precedence is bundled, then packaged, then user, so a checkout under `omarchy dev link` overrides the package. Packaged plugins update through `omarchy update` and leave through pacman; `omarchy plugin update` and `omarchy plugin remove` refuse them and name the package, and Setup › Plugins › Remove does not list them. ## IPC diff --git a/migrations/1789581661.sh b/migrations/1789581661.sh index fd5d30be8837..163deb9c07f0 100644 --- a/migrations/1789581661.sh +++ b/migrations/1789581661.sh @@ -50,8 +50,8 @@ if [[ -e $checkout || -L $checkout ]]; then fi fi -# The widget opens the right section of the default bar, just before the -# tray, which a machine without a shell.json takes on as soon as the shell +# The widget sits just before the clock in the center of the default bar, +# which a machine without a shell.json takes on as soon as the shell # restarts. A customized bar gets the entry written into its file rather than # placed over IPC: the shell this runs under cannot see a widget its scan # never reached and would refuse it, whereas the file it hot-reloads carries @@ -76,10 +76,10 @@ commit "$NORMALIZE | $entry_id"' def insert_at($section; $index): .bar.layout[$section] = .bar.layout[$section][:$index] + [{id: "omacom.elsewhen"}] + .bar.layout[$section][$index:]; . as $config - | (["left", "center", "right"] | map(select($config.bar.layout[.] | ids | index("omarchy.tray") != null)) | first) as $section + | (["left", "center", "right"] | map(select($config.bar.layout[.] | ids | index("omarchy.clock") != null)) | first) as $section | if $section != null then - insert_at($section; .bar.layout[$section] | ids | index("omarchy.tray")) + insert_at($section; .bar.layout[$section] | ids | index("omarchy.clock")) else - insert_at("right"; 0) + insert_at("center"; 0) end ' diff --git a/shell/README.md b/shell/README.md index 23a25ca656f3..53425139b8e4 100644 --- a/shell/README.md +++ b/shell/README.md @@ -142,16 +142,7 @@ You can still drop a plugin in without git: ### Packaged plugins -Some default plugins ship as their own Arch package rather than in this -checkout: Elsewhen (`omacom.elsewhen`) is the `elsewhen` package. pacman installs such a plugin, -root-owned, at `/usr/share/omarchy/plugins//`, and -the shell scans that root between its bundled plugins and the user's. A -packaged `omarchy.*` id is trusted exactly like a bundled one; a packaged -plugin under any other id is treated like a user plugin. They update with -`omarchy update` and are removed with pacman, so `omarchy plugin update` and -`omarchy plugin remove` refuse them and name the package instead. A bundled -copy in `$OMARCHY_PATH/shell/plugins` wins over the packaged one, which is how -a packaged plugin is developed under `omarchy dev link`. +Some default plugins ship as their own Arch package rather than in this checkout: Elsewhen (`omacom.elsewhen`) is the `elsewhen` package. pacman installs such a plugin, root-owned, at `/usr/share/omarchy/plugins//`, and the shell scans that root between its bundled plugins and the user's. A packaged `omarchy.*` id is trusted exactly like a bundled one; a packaged plugin under any other id is treated like a user plugin. They update with `omarchy update` and are removed with pacman, so `omarchy plugin update` and `omarchy plugin remove` refuse them and name the package instead. A bundled copy in `$OMARCHY_PATH/shell/plugins` wins over the packaged one, which is how a packaged plugin is developed under `omarchy dev link`. The lower-level IPC equivalents remain available via `omarchy-shell shell rescanPlugins`, `omarchy-shell shell enablePlugin '{}'`, and `omarchy-shell shell listPlugins`. diff --git a/test/shell.d/config-test.sh b/test/shell.d/config-test.sh index d9086d4469ab..1cd47e3381d3 100755 --- a/test/shell.d/config-test.sh +++ b/test/shell.d/config-test.sh @@ -33,6 +33,15 @@ jq -e ' ' "$ROOT/config/omarchy/shell.json" >/dev/null pass "default center anchor exists in center layout" +jq -e ' + def ids: map(.id // .); + (.bar.layout.center | ids) as $ids | + ($ids | index("omacom.elsewhen")) as $elsewhen | + ($ids | index("omarchy.clock")) as $clock | + $elsewhen != null and $clock == $elsewhen + 1 +' "$ROOT/config/omarchy/shell.json" >/dev/null +pass "default center layout puts elsewhen immediately before the clock" + jq -e ' any(.bar.layout.center[]; (.id // .) == "omarchy.clock" and (.formatAlt // "") == "d MMMM \u0027W\u0027ww yyyy") ' "$ROOT/config/omarchy/shell.json" >/dev/null @@ -41,12 +50,11 @@ pass "default clock date format has no leading zero" jq -e ' def ids: map(.id // .); (.bar.layout.right | ids) as $ids | - ($ids | index("omacom.elsewhen")) as $elsewhen | ($ids | index("omarchy.tray")) as $tray | ($ids | index("omarchy.agents")) as $agents | - $elsewhen == 0 and $tray == 1 and $agents == $tray + 1 + $tray == 0 and $agents == $tray + 1 ' "$ROOT/config/omarchy/shell.json" >/dev/null -pass "default right layout opens with elsewhen and the tray, then agents" +pass "default right layout opens with the tray, then agents" ROOT="$ROOT" python3 <<'PY' import json diff --git a/test/shell.d/elsewhen-default-migration-test.sh b/test/shell.d/elsewhen-default-migration-test.sh index 438ba1d30220..89585f22fb0c 100644 --- a/test/shell.d/elsewhen-default-migration-test.sh +++ b/test/shell.d/elsewhen-default-migration-test.sh @@ -89,14 +89,14 @@ run_migration grep -Fxq elsewhen "$CALL_LOG" || fail "migration installs the elsewhen package" "$(cat "$CALL_LOG")" pass "migration installs the elsewhen package" -[[ $(ids right) == '["omacom.elsewhen","omarchy.tray","omarchy.agents","omarchy.power"]' ]] || - fail "migration puts the widget just before the tray" "$(cat "$config")" -pass "migration puts the widget just before the tray" +[[ $(ids center) == '["omacom.elsewhen","omarchy.clock"]' && $(ids right) == '["omarchy.tray","omarchy.agents","omarchy.power"]' ]] || + fail "migration puts the widget just before the center clock" "$(cat "$config")" +pass "migration puts the widget just before the center clock" -[[ $(jq -c '.bar.layout.right[2]' "$config") == '{"id":"omarchy.agents","syncMode":"On"}' ]] || +[[ $(jq -c '.bar.layout.right[1]' "$config") == '{"id":"omarchy.agents","syncMode":"On"}' ]] || fail "migration keeps the settings of its neighbours" "$(cat "$config")" -[[ $(jq -c '.bar.layout.center[0]' "$config") == '{"format":"HH:mm","id":"omarchy.clock"}' ]] || - fail "migration leaves other sections alone" "$(cat "$config")" +[[ $(jq -c '.bar.layout.center[1]' "$config") == '{"format":"HH:mm","id":"omarchy.clock"}' ]] || + fail "migration keeps the clock settings" "$(cat "$config")" pass "migration leaves the rest of the layout alone" grep -q 'shell rescanPlugins' "$SHELL_CALLS" && grep -q 'shell reloadConfig' "$SHELL_CALLS" || @@ -117,17 +117,17 @@ cat >"$config" <<'JSON' } JSON run_migration -[[ $(ids center) == '["omarchy.clock","omacom.elsewhen","omarchy.tray"]' && $(ids right) == '["omarchy.power"]' ]] || - fail "migration follows the tray into another section and reads string entries" "$(cat "$config")" -pass "migration follows the tray into another section and reads string entries" +[[ $(ids center) == '["omacom.elsewhen","omarchy.clock","omarchy.tray"]' && $(ids right) == '["omarchy.power"]' ]] || + fail "migration reads string clock entries" "$(cat "$config")" +pass "migration reads string clock entries" cat >"$config" <<'JSON' { "version": 1, "bar": { "layout": { "right": [{ "id": "omarchy.agents" }, { "id": "omarchy.power" }] } } } JSON run_migration -[[ $(ids right) == '["omacom.elsewhen","omarchy.agents","omarchy.power"]' ]] || - fail "migration prepends to the right section when the tray is off the bar" "$(cat "$config")" -pass "migration prepends to the right section when the tray is off the bar" +[[ $(ids center) == '["omacom.elsewhen"]' && $(ids right) == '["omarchy.agents","omarchy.power"]' ]] || + fail "migration prepends to the center section when the clock is off the bar" "$(cat "$config")" +pass "migration prepends to the center section when the clock is off the bar" cat >"$config" <<'JSON' { @@ -141,6 +141,15 @@ run_migration fail "migration leaves a widget the user already placed where it is" "$(cat "$config")" pass "migration leaves a widget the user already placed where it is" +# A customized clock keeps its section and settings; insert only its neighbour. +for section in left right; do + jq -n --arg section "$section" '{version: 1, bar: {layout: {center: ["omarchy.weather"], ($section): ["omarchy.menu", {id: "omarchy.clock", format: "HH:mm"}]}}}' >"$config" + run_migration + [[ $(ids "$section") == '["omarchy.menu","omacom.elsewhen","omarchy.clock"]' && $(ids center) == '["omarchy.weather"]' ]] || + fail "migration follows a clock customized into $section" "$(cat "$config")" + pass "migration follows a clock customized into $section" +done + # ------------------------------------------------------------- edge cases rm -f "$config" run_migration @@ -156,7 +165,7 @@ cat >"$config" <<'JSON' { "version": 1, "bar": { "layout": { "right": [{ "id": "omarchy.tray" }, { "id": "omarchy.agents" }] } } } JSON SHELL_STATUS=1 run_migration -[[ $(ids right) == '["omacom.elsewhen","omarchy.tray","omarchy.agents"]' ]] || +[[ $(ids center) == '["omacom.elsewhen"]' && $(ids right) == '["omarchy.tray","omarchy.agents"]' ]] || fail "migration places the widget with no shell running" "$(cat "$config")" pass "migration places the widget with no shell running" @@ -201,7 +210,7 @@ JSON } assert_widget_placed() { - [[ $(ids right) == '["omacom.elsewhen","omarchy.tray","omarchy.power"]' ]] || + [[ $(ids center) == '["omacom.elsewhen"]' && $(ids right) == '["omarchy.tray","omarchy.power"]' ]] || fail "$1 still gets the widget" "$(cat "$config")" } From e8a8236a22e9d05f4fccded51639d522a88903ca Mon Sep 17 00:00:00 2001 From: Spencer Bull Date: Thu, 17 Sep 2026 22:07:54 -0500 Subject: [PATCH 094/194] Preserve local Elsewhen work and fallback bar layouts Retire only checkouts whose refs and reflogs are reachable from recorded origin history, and preserve ignored files. Leave configs without an explicit supported bar layout untouched so migration does not replace the shell fallback with an almost empty bar. Co-Authored-By: Codex XHigh --- migrations/1789581661.sh | 13 ++-- .../elsewhen-default-migration-test.sh | 69 +++++++++++++++++++ 2 files changed, 77 insertions(+), 5 deletions(-) diff --git a/migrations/1789581661.sh b/migrations/1789581661.sh index 163deb9c07f0..f581d4d03397 100644 --- a/migrations/1789581661.sh +++ b/migrations/1789581661.sh @@ -29,15 +29,18 @@ omarchy-shell -q shell rescanPlugins || true # one that finds the package. A one-time gap of a few minutes, during the # update itself. upstream_checkout() { - local dir="$1" origin status + local dir="$1" origin status unpublished [[ -d $dir && ! -L $dir && -d $dir/.git ]] || return 1 origin=$(git -C "$dir" remote get-url origin 2>/dev/null) || return 1 origin=${origin,,} origin=${origin%/} origin=${origin%.git} [[ $origin =~ ^([a-z+]+://)?([^/@]+@)?github\.com[/:]omacom/elsewhen$ ]] || return 1 - status=$(git -C "$dir" status --porcelain 2>/dev/null) || return 1 - [[ -z $status ]] + status=$(git -C "$dir" status --porcelain --untracked-files=all --ignored 2>/dev/null) || return 1 + [[ -z $status ]] || return 1 + # Local branches, stashes, and reflogs may hold work absent from a clean tree. + unpublished=$(git -C "$dir" rev-list HEAD --all --reflog --not --remotes=origin 2>/dev/null) || return 1 + [[ -z $unpublished ]] } checkout="$HOME/.config/omarchy/plugins/omacom.elsewhen" @@ -60,8 +63,8 @@ fi source omarchy-shell-config [[ -s $CONFIG_FILE ]] || exit 0 -# A file the shell cannot read is left for its owner to repair. -jq empty "$CONFIG_FILE" 2>/dev/null || exit 0 +# Preserve configs whose bar comes from the shell fallback instead of an explicit layout. +jq -e 'type == "object" and .version == 1 and (.bar | type == "object") and (.bar.layout | type == "object")' "$CONFIG_FILE" >/dev/null 2>&1 || exit 0 entry_id='def entry_id: if type == "object" then (.id // "" | tostring) else tostring end;' diff --git a/test/shell.d/elsewhen-default-migration-test.sh b/test/shell.d/elsewhen-default-migration-test.sh index 89585f22fb0c..525094e5f9df 100644 --- a/test/shell.d/elsewhen-default-migration-test.sh +++ b/test/shell.d/elsewhen-default-migration-test.sh @@ -156,6 +156,18 @@ run_migration [[ ! -e $config ]] || fail "migration writes no shell.json where the defaults apply" "$(cat "$config")" pass "migration writes no shell.json where the defaults apply" +for partial in \ + '{"version":1,"idle":{"lock":600}}' \ + '{"version":1,"bar":null,"idle":{"lock":600}}' \ + '{"version":1,"bar":{"position":"bottom"}}' \ + '{"bar":{"layout":{"center":["omarchy.clock"]}}}'; do + printf '%s\n' "$partial" >"$config" + before=$(sha256sum "$config") + run_migration + [[ $before == $(sha256sum "$config") ]] || fail "migration preserves fallback configuration" "$(cat "$config")" + pass "migration preserves fallback configuration: $partial" +done + printf '{ not json' >"$config" run_migration [[ $(cat "$config") == '{ not json' ]] || fail "migration leaves an unparsable config untouched" "$(cat "$config")" @@ -201,6 +213,7 @@ make_checkout() { printf 'import QtQuick\nItem {}\n' >"$checkout/Panel.qml" git -C "$checkout" add -A git -C "$checkout" commit -q -m "Elsewhen" + git -C "$checkout" update-ref refs/remotes/origin/main HEAD } reset_layout() { @@ -257,6 +270,62 @@ reset_layout run_migration assert_kept "a clone with an untracked file" +make_checkout https://github.com/omacom/elsewhen.git +printf 'import QtQuick\nItem { id: mine }\n' >"$checkout/Panel.qml" +git -C "$checkout" add Panel.qml +git -C "$checkout" commit -q -m "Local customization" +local_commit=$(git -C "$checkout" rev-parse HEAD) +reset_layout +run_migration +assert_kept "a clean clone with an unpublished commit" +[[ $(git -C "$checkout" rev-parse HEAD) == "$local_commit" ]] || fail "local commit survives" + +make_checkout https://github.com/omacom/elsewhen.git +git -C "$checkout" checkout -qb local-work +printf 'local branch\n' >"$checkout/Panel.qml" +git -C "$checkout" commit -qam "Unpublished branch" +git -C "$checkout" checkout -q --detach refs/remotes/origin/main +reset_layout +run_migration +assert_kept "an unpublished commit on another branch" + +make_checkout https://github.com/omacom/elsewhen.git +printf 'stashed work\n' >"$checkout/Panel.qml" +git -C "$checkout" stash push -q +reset_layout +run_migration +assert_kept "a clean clone with stashed work" + +make_checkout https://github.com/omacom/elsewhen.git +git -C "$checkout" config status.showUntrackedFiles no +printf 'private-notes\n' >"$checkout/.git/info/exclude" +printf 'ignored work\n' >"$checkout/private-notes" +reset_layout +run_migration +assert_kept "a clone with an ignored file" +[[ $(cat "$checkout/private-notes") == "ignored work" ]] || fail "ignored file survives" + +make_checkout https://github.com/omacom/elsewhen.git +printf 'recoverable work\n' >"$checkout/Panel.qml" +git -C "$checkout" commit -qam "Recoverable local commit" +git -C "$checkout" reset -q --hard refs/remotes/origin/main +reset_layout +run_migration +assert_kept "a local commit retained only by the reflog" + +make_checkout https://github.com/omacom/elsewhen.git +git -C "$checkout" update-ref -d refs/remotes/origin/main +reset_layout +run_migration +assert_kept "a clone without recorded upstream history" + +make_checkout https://github.com/omacom/elsewhen.git +git -C "$checkout" config status.showUntrackedFiles no +printf 'untracked work\n' >"$checkout/NOTES.md" +reset_layout +run_migration +assert_kept "untracked files hidden by the user Git configuration" + make_checkout https://github.com/someone/elsewhen-fork.git reset_layout run_migration From 5f34ce4581f7cd65b9555d821a61f58e6314821a Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Fri, 18 Sep 2026 14:10:14 +0200 Subject: [PATCH 095/194] Detach 1Password from installer terminal --- bin/omarchy-install-service-1password | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/omarchy-install-service-1password b/bin/omarchy-install-service-1password index f59cab9257c9..fc7238a6dd80 100755 --- a/bin/omarchy-install-service-1password +++ b/bin/omarchy-install-service-1password @@ -28,7 +28,7 @@ echo "Installing 1Password extension for Chromium..." install_chromium_extension echo "Opening 1Password..." -uwsm-app -- 1password >/dev/null 2>&1 & +setsid uwsm-app -- 1password >/dev/null 2>&1 & echo "" echo "1Password has been installed. Restart Chromium to load the browser extension." From d174d4aa279ea7393d4fad4a80fed147866106b9 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Fri, 18 Sep 2026 15:34:01 +0200 Subject: [PATCH 096/194] Add omarchy up alias --- bin/omarchy-update | 1 + 1 file changed, 1 insertion(+) diff --git a/bin/omarchy-update b/bin/omarchy-update index e71e808664ee..1738ebffc4fd 100755 --- a/bin/omarchy-update +++ b/bin/omarchy-update @@ -1,6 +1,7 @@ #!/bin/bash # omarchy:summary=Update Omarchy and system packages +# omarchy:alias=omarchy up # omarchy:args=[-y] # omarchy:examples=omarchy update | omarchy update -y # omarchy:requires-sudo=true From d01ef2d5d0ab5048ad8e2c662bdbf1e7d65479bd Mon Sep 17 00:00:00 2001 From: Bjarne Oeverli <1419214+bjarneo@users.noreply.github.com> Date: Fri, 18 Sep 2026 18:23:21 +0200 Subject: [PATCH 097/194] Let OWE own video backgrounds while it runs The background plugin now watches for the OWE daemon socket. While OWE is running, the desktop yields video playback to it and the shell keeps stills. The lock screen keeps its own playback. This lets Omarchy cooperate with OWE without OWE editing shell.json, so the engine can ship as a package. Add a package-list note that owe-wallpaper-engine must be added once it is packaged. --- install/omarchy-base.packages | 2 ++ manual/39-backgrounds.md | 2 +- shell/Ui/BackgroundMedia.qml | 6 +++++- shell/plugins/background/Background.qml | 25 ++++++++++++++++++++++++- test/shell.d/video-background-test.sh | 9 +++++++++ 5 files changed, 41 insertions(+), 3 deletions(-) diff --git a/install/omarchy-base.packages b/install/omarchy-base.packages index 76e741108cf6..b38c68b80597 100644 --- a/install/omarchy-base.packages +++ b/install/omarchy-base.packages @@ -107,6 +107,8 @@ python-poetry-core ttfx qemu-user-static-binfmt qrencode +# TODO: add owe-wallpaper-engine here once it is packaged. The shell yields +# video backgrounds to it while its daemon runs. qt6-imageformats qt6-multimedia qt6-multimedia-ffmpeg diff --git a/manual/39-backgrounds.md b/manual/39-backgrounds.md index f2cd51eb69f4..f02916538bf0 100644 --- a/manual/39-backgrounds.md +++ b/manual/39-backgrounds.md @@ -4,6 +4,6 @@ Every theme ships with its own set of backgrounds, and you can add extras of you You can do this most easily by going to _Install > Style > Background_ in the Omarchy Menu. That'll bring up the folder where the backgrounds for that theme is stored. Hit `Super + Shift + F` to start another file manager, find your background, copy it over. Now it'll be included in the choices of backgrounds you can select between using `Super + Ctrl + Space`. -Backgrounds can be videos as well as stills. Drop an `mp4`, `m4v`, `mov`, `webm`, `mkv`, or `avi` file in the same folder and it appears alongside the images, playing on a loop. Only your first monitor's wallpaper plays a video's sound track, through the default audio output at the system volume, and the lock screen stays silent. Playback stops on its own whenever nothing can see it — while a fullscreen window covers that monitor, while the screensaver is up, and once a locked screen has gone dark — but a video wallpaper still costs far more power than a still one, and each monitor decodes its own copy. +Backgrounds can be videos as well as stills. Drop an `mp4`, `m4v`, `mov`, `webm`, `mkv`, or `avi` file in the same folder and it appears alongside the images, playing on a loop. Only your first monitor's wallpaper plays a video's sound track, through the default audio output at the system volume, and the lock screen stays silent. Playback stops on its own whenever nothing can see it — while a fullscreen window covers that monitor, while the screensaver is up, and once a locked screen has gone dark — but a video wallpaper still costs far more power than a still one, and each monitor decodes its own copy. When the OWE wallpaper engine is running, it takes over video backgrounds and the shell keeps only stills. You can find a huge collection of cool curated backgrounds on https://github.com/dharmx/walls. diff --git a/shell/Ui/BackgroundMedia.qml b/shell/Ui/BackgroundMedia.qml index b281ae223ac5..f3ab7743aa6e 100644 --- a/shell/Ui/BackgroundMedia.qml +++ b/shell/Ui/BackgroundMedia.qml @@ -8,6 +8,10 @@ Item { property int version: 0 property bool playbackEnabled: true property bool audioEnabled: false + // The desktop yields video playback to OWE while it runs, so two engines + // never decode the same file. The lock screen leaves this off and keeps its + // own playback. + property bool deferVideo: false // Bumped when the file behind an unchanged path may have been replaced. // Images cache-bust through version; a video is rebuilt, since FFmpeg // would read a query as part of the filename. @@ -37,7 +41,7 @@ Item { Loader { id: videoLoader anchors.fill: parent - active: root.path !== "" && root.video && !root.reloading + active: root.path !== "" && root.video && !root.reloading && !root.deferVideo source: "BackgroundVideo.qml" } diff --git a/shell/plugins/background/Background.qml b/shell/plugins/background/Background.qml index dea93a4cf658..f8929fa9fb0b 100644 --- a/shell/plugins/background/Background.qml +++ b/shell/plugins/background/Background.qml @@ -32,6 +32,25 @@ Item { // services so playback can stop whenever nothing can see the wallpaper. property var shell: null + // When the OWE wallpaper engine is running, it owns video backgrounds. This + // plugin keeps stills, which OWE hands back to it, and the lock screen keeps + // its own playback. + property bool oweActive: false + + Process { + id: oweStatusProc + command: ["bash", "-c", "test -S \"${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/owe/owed.sock\""] + onExited: root.oweActive = (exitCode === 0) + } + + Timer { + id: oweStatusTimer + interval: 5000 + repeat: true + running: true + onTriggered: if (!oweStatusProc.running) oweStatusProc.running = true + } + // Stop a video wallpaper's decoding whenever it is covered. Qt's FFmpeg // engine drives its own clock, so an unseen player keeps decoding until it // is told not to — a locked laptop would otherwise decode until it died. @@ -204,7 +223,10 @@ Item { } } - Component.onCompleted: refreshBackground() + Component.onCompleted: { + oweStatusProc.running = true + refreshBackground() + } Variants { model: Quickshell.screens @@ -264,6 +286,7 @@ Item { anchors.fill: parent path: root.displayedBackground reloads: root.displayedReloads + deferVideo: root.oweActive playbackEnabled: !root.sessionObscured && !root.powerSaverActive && !panel.fullscreenHere audioEnabled: panel.firstScreen onReadyChanged: { diff --git a/test/shell.d/video-background-test.sh b/test/shell.d/video-background-test.sh index 7ebad86bf67a..d3591b4f52a6 100755 --- a/test/shell.d/video-background-test.sh +++ b/test/shell.d/video-background-test.sh @@ -87,6 +87,15 @@ assert( 'video switches bypass the image-only reveal stack and use the durable background path' ) assert(backgroundQml.includes('BackgroundMedia {') && lockQml.includes('BackgroundMedia {'), 'desktop and lock screen share video-capable media rendering') +assert( + backgroundQml.includes('property bool oweActive: false') && + backgroundQml.includes('/owe/owed.sock') && + /deferVideo: root\.oweActive/.test(backgroundQml) && + /property bool deferVideo: false/.test(mediaQml) && + /active: root\.path !== "" && root\.video && !root\.reloading && !root\.deferVideo/.test(mediaQml) && + !lockQml.includes('deferVideo'), + 'the desktop yields video backgrounds to OWE while it is running, and the lock keeps its own playback' +) assert( lockQml.includes('source: wallpaper.video ? null : wallpaper') && lockQml.includes('visible: !wallpaper.video') && From 02bb92bc74acd2d0b5ff01708f4043e4eec87c92 Mon Sep 17 00:00:00 2001 From: Bjarne Oeverli <1419214+bjarneo@users.noreply.github.com> Date: Fri, 18 Sep 2026 18:36:07 +0200 Subject: [PATCH 098/194] Mark the desktop video path as the no-OWE fallback --- shell/plugins/background/Background.qml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/shell/plugins/background/Background.qml b/shell/plugins/background/Background.qml index f8929fa9fb0b..2161694073f0 100644 --- a/shell/plugins/background/Background.qml +++ b/shell/plugins/background/Background.qml @@ -34,7 +34,8 @@ Item { // When the OWE wallpaper engine is running, it owns video backgrounds. This // plugin keeps stills, which OWE hands back to it, and the lock screen keeps - // its own playback. + // its own playback. The desktop video path and its pause policy stay as the + // fallback for systems without OWE. property bool oweActive: false Process { From dbebc458db93bcffd4f453a2fa6af1bc12df4d4d Mon Sep 17 00:00:00 2001 From: Bjarne Oeverli <1419214+bjarneo@users.noreply.github.com> Date: Fri, 18 Sep 2026 18:46:17 +0200 Subject: [PATCH 099/194] Replace the desktop video path with OWE The desktop background no longer plays videos. OWE owns video backgrounds, and the shell layer stays empty behind one. The shell keeps stills, which OWE hands back to it. Remove the desktop video pause plumbing that only existed to stop an unseen player: the lock, idle, and battery service lookups, the per-output fullscreen check, the first-screen audio opt-in, and the audio output in BackgroundVideo. The lock screen keeps its own silent playback. Update the background tests, the manual, and the package note. --- install/omarchy-base.packages | 4 +- manual/39-backgrounds.md | 2 +- shell/Ui/BackgroundMedia.qml | 19 +++------ shell/Ui/BackgroundVideo.qml | 23 +++------- shell/plugins/background/Background.qml | 57 ++----------------------- test/shell.d/video-background-test.sh | 51 +++++++++------------- 6 files changed, 37 insertions(+), 119 deletions(-) diff --git a/install/omarchy-base.packages b/install/omarchy-base.packages index b38c68b80597..634b72aa226a 100644 --- a/install/omarchy-base.packages +++ b/install/omarchy-base.packages @@ -107,8 +107,8 @@ python-poetry-core ttfx qemu-user-static-binfmt qrencode -# TODO: add owe-wallpaper-engine here once it is packaged. The shell yields -# video backgrounds to it while its daemon runs. +# TODO: add owe-wallpaper-engine here once it is packaged. The shell keeps +# stills and the lock screen, and OWE owns desktop video backgrounds. qt6-imageformats qt6-multimedia qt6-multimedia-ffmpeg diff --git a/manual/39-backgrounds.md b/manual/39-backgrounds.md index f02916538bf0..7670ea6107b3 100644 --- a/manual/39-backgrounds.md +++ b/manual/39-backgrounds.md @@ -4,6 +4,6 @@ Every theme ships with its own set of backgrounds, and you can add extras of you You can do this most easily by going to _Install > Style > Background_ in the Omarchy Menu. That'll bring up the folder where the backgrounds for that theme is stored. Hit `Super + Shift + F` to start another file manager, find your background, copy it over. Now it'll be included in the choices of backgrounds you can select between using `Super + Ctrl + Space`. -Backgrounds can be videos as well as stills. Drop an `mp4`, `m4v`, `mov`, `webm`, `mkv`, or `avi` file in the same folder and it appears alongside the images, playing on a loop. Only your first monitor's wallpaper plays a video's sound track, through the default audio output at the system volume, and the lock screen stays silent. Playback stops on its own whenever nothing can see it — while a fullscreen window covers that monitor, while the screensaver is up, and once a locked screen has gone dark — but a video wallpaper still costs far more power than a still one, and each monitor decodes its own copy. When the OWE wallpaper engine is running, it takes over video backgrounds and the shell keeps only stills. +Backgrounds can be videos as well as stills. Drop an `mp4`, `m4v`, `mov`, `webm`, `mkv`, or `avi` file in the same folder and it appears alongside the images. Videos are played by the OWE wallpaper engine. It decodes once for every monitor and keeps playback silent, and it stops playback whenever nothing can see it. The lock screen keeps its own silent playback. A video wallpaper still costs far more power than a still one. You can find a huge collection of cool curated backgrounds on https://github.com/dharmx/walls. diff --git a/shell/Ui/BackgroundMedia.qml b/shell/Ui/BackgroundMedia.qml index f3ab7743aa6e..fa6b33451c1c 100644 --- a/shell/Ui/BackgroundMedia.qml +++ b/shell/Ui/BackgroundMedia.qml @@ -7,11 +7,9 @@ Item { property string path: "" property int version: 0 property bool playbackEnabled: true - property bool audioEnabled: false - // The desktop yields video playback to OWE while it runs, so two engines - // never decode the same file. The lock screen leaves this off and keeps its - // own playback. - property bool deferVideo: false + // The desktop turns this off because OWE owns video backgrounds. The lock + // screen leaves it on and keeps its own playback. + property bool videoEnabled: true // Bumped when the file behind an unchanged path may have been replaced. // Images cache-bust through version; a video is rebuilt, since FFmpeg // would read a query as part of the filename. @@ -27,7 +25,7 @@ Item { // Both test the path directly: going through `video` lets a URL evaluate // against the stale flag and leak the wrong file for one pass. readonly property url imageUrl: path && !Util.isVideoPath(path) ? Util.fileUrl(path) + (version ? "?v=" + version : "") : "" - readonly property url videoUrl: path && Util.isVideoPath(path) ? Util.fileUrl(path) : "" + readonly property url videoUrl: path && Util.isVideoPath(path) && videoEnabled ? Util.fileUrl(path) : "" Loader { id: imageLoader @@ -41,7 +39,7 @@ Item { Loader { id: videoLoader anchors.fill: parent - active: root.path !== "" && root.video && !root.reloading && !root.deferVideo + active: root.path !== "" && root.video && !root.reloading && root.videoEnabled source: "BackgroundVideo.qml" } @@ -68,13 +66,6 @@ Item { when: videoLoader.item !== null } - Binding { - target: videoLoader.item - property: "audioEnabled" - value: root.audioEnabled - when: videoLoader.item !== null - } - Component { id: imageComponent diff --git a/shell/Ui/BackgroundVideo.qml b/shell/Ui/BackgroundVideo.qml index 519e8bd99f02..0d0d34e16393 100644 --- a/shell/Ui/BackgroundVideo.qml +++ b/shell/Ui/BackgroundVideo.qml @@ -1,15 +1,15 @@ import QtQuick import QtMultimedia -// Deliberately a bare MediaPlayer and VideoOutput rather than the Video -// convenience type: Video always builds an AudioOutput, and a muted sink still -// decodes the audio stream and opens an audio client on every output. +// The lock screen is the only user. Playback is always silent, so this is a +// bare MediaPlayer and VideoOutput rather than the Video convenience type: +// Video always builds an AudioOutput, and a muted sink still decodes the audio +// stream and opens an audio client. Item { id: root property url mediaSource: "" property bool playbackEnabled: true - property bool audioEnabled: false property int mediaGeneration: 0 property bool priming: false property int primingGeneration: -1 @@ -74,23 +74,12 @@ Item { fillMode: VideoOutput.PreserveAspectCrop } - // Sound is opted into per output: with a player per monitor, every output - // playing the track would layer copies of it. The sink is only built once - // the media reports a sound track, so a silent file never opens an audio - // client or its threads. Priming a paused player must not be heard. - Loader { - id: audioLoader - active: root.audioEnabled && player.hasAudio - sourceComponent: AudioOutput { - muted: root.priming || !root.playbackEnabled - } - } - + // No audio output is built, so the lock never decodes an audio stream or + // opens an audio client. MediaPlayer { id: player source: root.mediaSource videoOutput: output - audioOutput: audioLoader.item loops: MediaPlayer.Infinite autoPlay: root.playbackEnabled onMediaStatusChanged: { diff --git a/shell/plugins/background/Background.qml b/shell/plugins/background/Background.qml index 2161694073f0..c51181ed5646 100644 --- a/shell/plugins/background/Background.qml +++ b/shell/plugins/background/Background.qml @@ -1,5 +1,4 @@ import Quickshell -import Quickshell.Hyprland import Quickshell.Io import Quickshell.Wayland import QtQuick @@ -28,43 +27,6 @@ Item { property string pendingShellRaw: "" property real revealProgress: 1 - // Injected by the first-party service loader; used to reach the lock and idle - // services so playback can stop whenever nothing can see the wallpaper. - property var shell: null - - // When the OWE wallpaper engine is running, it owns video backgrounds. This - // plugin keeps stills, which OWE hands back to it, and the lock screen keeps - // its own playback. The desktop video path and its pause policy stay as the - // fallback for systems without OWE. - property bool oweActive: false - - Process { - id: oweStatusProc - command: ["bash", "-c", "test -S \"${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/owe/owed.sock\""] - onExited: root.oweActive = (exitCode === 0) - } - - Timer { - id: oweStatusTimer - interval: 5000 - repeat: true - running: true - onTriggered: if (!oweStatusProc.running) oweStatusProc.running = true - } - - // Stop a video wallpaper's decoding whenever it is covered. Qt's FFmpeg - // engine drives its own clock, so an unseen player keeps decoding until it - // is told not to — a locked laptop would otherwise decode until it died. - readonly property var lockService: shell && shell.services ? shell.firstPartyServiceFor("omarchy.lock") : null - readonly property var idleService: shell && shell.services ? shell.firstPartyServiceFor("omarchy.idle") : null - readonly property var batteryService: shell && shell.services ? shell.firstPartyServiceFor("omarchy.battery") : null - readonly property bool lockActive: lockService ? lockService.locked : false - readonly property bool screensaverActive: idleService ? idleService.screensaverWindowCount > 0 : false - readonly property bool powerSaverActive: batteryService ? batteryService.powerSaverOnBattery : false - // A lock or a screensaver covers every output, so it is decided once here. - // Fullscreen is decided per output below, because it only covers its own. - readonly property bool sessionObscured: lockActive || screensaverActive - function isVideo(path) { return Util.isVideoPath(path) } @@ -252,19 +214,6 @@ Item { // by pausing playback rather than by parking the layer. updatesEnabled: true - // Pausing every wallpaper for one fullscreen window would freeze the one - // still on show next to it, which costs a viewer more than it saves. The - // workspace on show here knows whether a fullscreen window covers it, - // wherever focus happens to be. - readonly property var hyprlandMonitor: Hyprland.monitorFor(modelData) - readonly property var visibleWorkspace: hyprlandMonitor ? hyprlandMonitor.activeWorkspace : null - readonly property bool fullscreenHere: visibleWorkspace ? visibleWorkspace.hasFullscreen : false - - // A sound track plays from one output only, or every monitor would - // layer its own copy of it. - readonly property bool firstScreen: Quickshell.screens.length > 0 - && String(Quickshell.screens[0].name || "") === String(modelData.name || "") - property bool maskReady: false function maybeStartReveal() { @@ -282,14 +231,14 @@ Item { WlrLayershell.keyboardFocus: WlrKeyboardFocus.None exclusionMode: ExclusionMode.Ignore + // OWE owns video backgrounds. This layer draws stills, and stays empty + // behind a video so OWE's own layer shows through. BackgroundMedia { id: base anchors.fill: parent path: root.displayedBackground reloads: root.displayedReloads - deferVideo: root.oweActive - playbackEnabled: !root.sessionObscured && !root.powerSaverActive && !panel.fullscreenHere - audioEnabled: panel.firstScreen + videoEnabled: false onReadyChanged: { if (ready && root.finishingTransition) { root.incomingBackground = "" diff --git a/test/shell.d/video-background-test.sh b/test/shell.d/video-background-test.sh index d3591b4f52a6..f9eab0db6109 100755 --- a/test/shell.d/video-background-test.sh +++ b/test/shell.d/video-background-test.sh @@ -33,7 +33,7 @@ assert( videoQml.includes('autoPlay: root.playbackEnabled') && videoQml.includes('fillMode: VideoOutput.PreserveAspectCrop') && /imageUrl: path && !Util\.isVideoPath\(path\) \? Util\.fileUrl\(path\) \+ \(version \? "\?v=" \+ version : ""\) : ""/.test(mediaQml) && - /videoUrl: path && Util\.isVideoPath\(path\) \? Util\.fileUrl\(path\) : ""/.test(mediaQml), + /videoUrl: path && Util\.isVideoPath\(path\) && videoEnabled \? Util\.fileUrl\(path\) : ""/.test(mediaQml), 'background media plays aspect-cropped videos on a loop, and hands each loader only its own kind of file' ) assert( @@ -62,16 +62,12 @@ assert( ) assert( !/^\s*Video\s*\{/m.test(videoQml) && - /property bool audioEnabled: false/.test(videoQml) && - /property bool audioEnabled: false/.test(mediaQml) && - /active: root\.audioEnabled && player\.hasAudio/.test(videoQml) && - /audioOutput: audioLoader\.item/.test(videoQml) && - /muted: root\.priming \|\| !root\.playbackEnabled/.test(videoQml) && - /property: "audioEnabled"\s*\n\s*value: root\.audioEnabled/.test(mediaQml) && - /firstScreen: Quickshell\.screens\.length > 0\s*\n\s*&& String\(Quickshell\.screens\[0\]\.name/.test(backgroundQml) && - backgroundQml.includes('audioEnabled: panel.firstScreen') && + !videoQml.includes('AudioOutput {') && + !videoQml.includes('audioOutput:') && + !mediaQml.includes('audioEnabled') && + !backgroundQml.includes('audioEnabled') && !lockQml.includes('audioEnabled'), - 'a sound track plays from the first monitor only, a silent file builds no audio output, and the lock stays quiet' + 'playback is silent everywhere, so no audio output or audio client is built' ) assert( /property: "mediaSource"[\s\S]*?when: videoLoader\.item !== null && Util\.isVideoPath\(root\.path\)\s*\n\s*restoreMode: Binding\.RestoreNone/.test(mediaQml) && @@ -88,13 +84,20 @@ assert( ) assert(backgroundQml.includes('BackgroundMedia {') && lockQml.includes('BackgroundMedia {'), 'desktop and lock screen share video-capable media rendering') assert( - backgroundQml.includes('property bool oweActive: false') && - backgroundQml.includes('/owe/owed.sock') && - /deferVideo: root\.oweActive/.test(backgroundQml) && - /property bool deferVideo: false/.test(mediaQml) && - /active: root\.path !== "" && root\.video && !root\.reloading && !root\.deferVideo/.test(mediaQml) && - !lockQml.includes('deferVideo'), - 'the desktop yields video backgrounds to OWE while it is running, and the lock keeps its own playback' + backgroundQml.includes('videoEnabled: false') && + /property bool videoEnabled: true/.test(mediaQml) && + /active: root\.path !== "" && root\.video && !root\.reloading && root\.videoEnabled/.test(mediaQml) && + !lockQml.includes('videoEnabled'), + 'the desktop hands video backgrounds to OWE, and the lock keeps its own playback' +) +assert( + !backgroundQml.includes('playbackEnabled') && + !backgroundQml.includes('sessionObscured') && + !backgroundQml.includes('fullscreenHere') && + !backgroundQml.includes('Hyprland.monitorFor') && + !backgroundQml.includes('omarchy.lock') && + !backgroundQml.includes('omarchy.battery'), + 'the desktop no longer carries the shell video pause policy' ) assert( lockQml.includes('source: wallpaper.video ? null : wallpaper') && @@ -102,20 +105,6 @@ assert( lockQml.includes('visible: wallpaper.video'), 'lock screen bypasses its image effect for video output' ) -assert( - /sessionObscured:\s*lockActive \|\| screensaverActive/.test(backgroundQml) && - backgroundQml.includes('playbackEnabled: !root.sessionObscured && !root.powerSaverActive && !panel.fullscreenHere') && - backgroundQml.includes('omarchy.lock') && - backgroundQml.includes('omarchy.idle') && - backgroundQml.includes('omarchy.battery'), - 'desktop playback stops while covered or on battery power-saver' -) -assert( - backgroundQml.includes('Hyprland.monitorFor(modelData)') && - /fullscreenHere: visibleWorkspace \? visibleWorkspace\.hasFullscreen : false/.test(backgroundQml) && - !backgroundQml.includes('ToplevelManager.activeToplevel'), - 'a fullscreen window pauses only the output it covers, wherever focus is' -) assert( /if \(displayedBackground === finalPath\) displayedReloads \+= 1/.test(backgroundQml) && backgroundQml.includes('reloads: root.displayedReloads') && From 831626daea4acaaf745d336937da30d411cde635 Mon Sep 17 00:00:00 2001 From: Bjarne Oeverli <1419214+bjarneo@users.noreply.github.com> Date: Fri, 18 Sep 2026 21:02:01 +0200 Subject: [PATCH 100/194] Note that OWE plays the desktop video audio --- manual/39-backgrounds.md | 2 +- test/shell.d/video-background-test.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/manual/39-backgrounds.md b/manual/39-backgrounds.md index 7670ea6107b3..6629ef27bffa 100644 --- a/manual/39-backgrounds.md +++ b/manual/39-backgrounds.md @@ -4,6 +4,6 @@ Every theme ships with its own set of backgrounds, and you can add extras of you You can do this most easily by going to _Install > Style > Background_ in the Omarchy Menu. That'll bring up the folder where the backgrounds for that theme is stored. Hit `Super + Shift + F` to start another file manager, find your background, copy it over. Now it'll be included in the choices of backgrounds you can select between using `Super + Ctrl + Space`. -Backgrounds can be videos as well as stills. Drop an `mp4`, `m4v`, `mov`, `webm`, `mkv`, or `avi` file in the same folder and it appears alongside the images. Videos are played by the OWE wallpaper engine. It decodes once for every monitor and keeps playback silent, and it stops playback whenever nothing can see it. The lock screen keeps its own silent playback. A video wallpaper still costs far more power than a still one. +Backgrounds can be videos as well as stills. Drop an `mp4`, `m4v`, `mov`, `webm`, `mkv`, or `avi` file in the same folder and it appears alongside the images. Videos are played by the OWE wallpaper engine. It decodes once for every monitor and plays the video's sound through the default audio output, and it stops playback whenever nothing can see it. The lock screen keeps its own silent playback. A video wallpaper still costs far more power than a still one. You can find a huge collection of cool curated backgrounds on https://github.com/dharmx/walls. diff --git a/test/shell.d/video-background-test.sh b/test/shell.d/video-background-test.sh index f9eab0db6109..126537216acb 100755 --- a/test/shell.d/video-background-test.sh +++ b/test/shell.d/video-background-test.sh @@ -67,7 +67,7 @@ assert( !mediaQml.includes('audioEnabled') && !backgroundQml.includes('audioEnabled') && !lockQml.includes('audioEnabled'), - 'playback is silent everywhere, so no audio output or audio client is built' + 'the shell builds no audio output: OWE plays the desktop video audio and the lock stays silent' ) assert( /property: "mediaSource"[\s\S]*?when: videoLoader\.item !== null && Util\.isVideoPath\(root\.path\)\s*\n\s*restoreMode: Binding\.RestoreNone/.test(mediaQml) && From 2e3142a105cfce2f4c06036c84c6bf96a056d92f Mon Sep 17 00:00:00 2001 From: Bjarne Oeverli <1419214+bjarneo@users.noreply.github.com> Date: Fri, 18 Sep 2026 21:28:04 +0200 Subject: [PATCH 101/194] Point the owe package note at the omarchy-pkgs pull request --- install/omarchy-base.packages | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/install/omarchy-base.packages b/install/omarchy-base.packages index 634b72aa226a..0ec925d0e29e 100644 --- a/install/omarchy-base.packages +++ b/install/omarchy-base.packages @@ -107,8 +107,9 @@ python-poetry-core ttfx qemu-user-static-binfmt qrencode -# TODO: add owe-wallpaper-engine here once it is packaged. The shell keeps -# stills and the lock screen, and OWE owns desktop video backgrounds. +# TODO: add owe here once omarchy-pkgs#519 lands. The shell keeps stills and +# the lock screen, and OWE owns desktop video backgrounds. Version 0.1.1 or +# newer plays the video's audio. qt6-imageformats qt6-multimedia qt6-multimedia-ffmpeg From eff410f91e4c54b932db03670883706ca9e5c498 Mon Sep 17 00:00:00 2001 From: Bjarne Oeverli <1419214+bjarneo@users.noreply.github.com> Date: Fri, 18 Sep 2026 22:49:47 +0200 Subject: [PATCH 102/194] Draw the lock screen video from the OWE lock feed The shell drops its own player: BackgroundMedia is image-only, and the lock loads Owe.LockFeedSurface through a Loader, so a system without the module shows no lock video instead of losing the whole lock screen. The feed pauses per output when the panel blanks or power saver turns on. The lock view keeps its still effect path and darkens the feed for legibility. QtMultimedia and the shell video pause policy are gone, and the base package list requires owe and owe-lockfeed instead. --- install/omarchy-base.packages | 8 +- shell/Ui/BackgroundMedia.qml | 56 ++---------- shell/Ui/BackgroundVideo.qml | 111 ------------------------ shell/Ui/qmldir | 1 - shell/plugins/background/Background.qml | 7 -- shell/plugins/lock/LockFeedSurface.qml | 11 +++ shell/plugins/lock/LockView.qml | 35 ++++++-- test/shell.d/video-background-test.sh | 111 ++++++++++-------------- 8 files changed, 92 insertions(+), 248 deletions(-) delete mode 100644 shell/Ui/BackgroundVideo.qml create mode 100644 shell/plugins/lock/LockFeedSurface.qml diff --git a/install/omarchy-base.packages b/install/omarchy-base.packages index 0ec925d0e29e..c292828fcfc9 100644 --- a/install/omarchy-base.packages +++ b/install/omarchy-base.packages @@ -107,12 +107,10 @@ python-poetry-core ttfx qemu-user-static-binfmt qrencode -# TODO: add owe here once omarchy-pkgs#519 lands. The shell keeps stills and -# the lock screen, and OWE owns desktop video backgrounds. Version 0.1.1 or -# newer plays the video's audio. +# OWE owns desktop video backgrounds and feeds the lock screen its frames. +owe +owe-lockfeed qt6-imageformats -qt6-multimedia -qt6-multimedia-ffmpeg quickshell ripgrep ruby diff --git a/shell/Ui/BackgroundMedia.qml b/shell/Ui/BackgroundMedia.qml index fa6b33451c1c..aabde8d1f818 100644 --- a/shell/Ui/BackgroundMedia.qml +++ b/shell/Ui/BackgroundMedia.qml @@ -1,31 +1,19 @@ import QtQuick import qs.Commons +// The shell draws stills only. OWE owns video backgrounds on the desktop, and +// it feeds the lock screen through its own socket. Item { id: root property string path: "" property int version: 0 - property bool playbackEnabled: true - // The desktop turns this off because OWE owns video backgrounds. The lock - // screen leaves it on and keeps its own playback. - property bool videoEnabled: true - // Bumped when the file behind an unchanged path may have been replaced. - // Images cache-bust through version; a video is rebuilt, since FFmpeg - // would read a query as part of the filename. - property int reloads: 0 - property bool reloading: false - readonly property var current: video ? videoLoader.item : imageLoader.item + readonly property var current: imageLoader.item readonly property bool ready: current ? current.ready : false readonly property bool video: Util.isVideoPath(path) - // Cache-bust images selected in a running lock session. FFmpeg treats the - // query as part of a local filename, so videos must keep their plain URL. - // Each URL is empty for the other kind, so a switch never hands the still - // loader a video, or the player a still, in the moment before it unloads. - // Both test the path directly: going through `video` lets a URL evaluate - // against the stale flag and leak the wrong file for one pass. - readonly property url imageUrl: path && !Util.isVideoPath(path) ? Util.fileUrl(path) + (version ? "?v=" + version : "") : "" - readonly property url videoUrl: path && Util.isVideoPath(path) && videoEnabled ? Util.fileUrl(path) : "" + // Cache-bust images selected in a running lock session, so a theme switch + // that replaces the file behind an unchanged path shows the new pixels. + readonly property url imageUrl: path && !video ? Util.fileUrl(path) + (version ? "?v=" + version : "") : "" Loader { id: imageLoader @@ -34,38 +22,6 @@ Item { sourceComponent: imageComponent } - // Loaded by URL rather than from a Component here, so QtMultimedia and its - // audio dependency closure never map into a session that only shows images. - Loader { - id: videoLoader - anchors.fill: parent - active: root.path !== "" && root.video && !root.reloading && root.videoEnabled - source: "BackgroundVideo.qml" - } - - onReloadsChanged: { - if (!video) return - reloading = true - Qt.callLater(function() { root.reloading = false }) - } - - // A player on its way out keeps its source: pushing an empty one starts a - // load of nothing that its destructor then cancels, which FFmpeg logs. - Binding { - target: videoLoader.item - property: "mediaSource" - value: root.videoUrl - when: videoLoader.item !== null && Util.isVideoPath(root.path) - restoreMode: Binding.RestoreNone - } - - Binding { - target: videoLoader.item - property: "playbackEnabled" - value: root.playbackEnabled - when: videoLoader.item !== null - } - Component { id: imageComponent diff --git a/shell/Ui/BackgroundVideo.qml b/shell/Ui/BackgroundVideo.qml deleted file mode 100644 index 0d0d34e16393..000000000000 --- a/shell/Ui/BackgroundVideo.qml +++ /dev/null @@ -1,111 +0,0 @@ -import QtQuick -import QtMultimedia - -// The lock screen is the only user. Playback is always silent, so this is a -// bare MediaPlayer and VideoOutput rather than the Video convenience type: -// Video always builds an AudioOutput, and a muted sink still decodes the audio -// stream and opens an audio client. -Item { - id: root - - property url mediaSource: "" - property bool playbackEnabled: true - property int mediaGeneration: 0 - property bool priming: false - property int primingGeneration: -1 - property bool frameReceived: false - readonly property bool ready: player.hasVideo - - onMediaSourceChanged: { - mediaGeneration += 1 - priming = false - primingGeneration = -1 - frameReceived = false - primePauseTimer.stop() - framePauseTimer.stop() - output.clearOutput() - } - - onPlaybackEnabledChanged: { - priming = false - frameReceived = false - primePauseTimer.stop() - framePauseTimer.stop() - if (playbackEnabled) player.play() - else player.pause() - } - - function pauseAfterPrimedFrame() { - if (!priming - || root.playbackEnabled - || primingGeneration !== root.mediaGeneration) return - - priming = false - primePauseTimer.stop() - framePauseTimer.stop() - player.pause() - } - - // A paused MediaPlayer can load a source without presenting its first frame. - // Prime it until VideoOutput receives a frame, with a timeout so a stalled - // decoder cannot keep running indefinitely on battery. - Timer { - id: primePauseTimer - interval: 1000 - repeat: false - - onTriggered: root.pauseAfterPrimedFrame() - } - - // Receiving a frame means the decoder has produced it, but the scene graph - // may not have committed it yet. Give VideoOutput a render cycle before - // pausing so the first frame is not lost on a source switch. - Timer { - id: framePauseTimer - interval: 50 - repeat: false - - onTriggered: root.pauseAfterPrimedFrame() - } - - VideoOutput { - id: output - anchors.fill: parent - fillMode: VideoOutput.PreserveAspectCrop - } - - // No audio output is built, so the lock never decodes an audio stream or - // opens an audio client. - MediaPlayer { - id: player - source: root.mediaSource - videoOutput: output - loops: MediaPlayer.Infinite - autoPlay: root.playbackEnabled - onMediaStatusChanged: { - if (mediaStatus !== MediaPlayer.LoadedMedia) return - - if (!root.playbackEnabled) { - root.priming = true - root.primingGeneration = root.mediaGeneration - root.frameReceived = false - primePauseTimer.restart() - } - player.play() - } - } - - Connections { - target: output.videoSink - function onVideoFrameChanged() { - if (player.mediaStatus !== MediaPlayer.BufferedMedia) return - if (!root.priming - || root.playbackEnabled - || root.primingGeneration !== root.mediaGeneration - || root.frameReceived) return - - root.frameReceived = true - framePauseTimer.restart() - } - } -} diff --git a/shell/Ui/qmldir b/shell/Ui/qmldir index 092caf6c6091..464e25b74a1a 100644 --- a/shell/Ui/qmldir +++ b/shell/Ui/qmldir @@ -4,7 +4,6 @@ BarIndicator 1.0 BarIndicator.qml BarIconButton 1.0 BarIconButton.qml BarWidget 1.0 BarWidget.qml BackgroundMedia 1.0 BackgroundMedia.qml -BackgroundVideo 1.0 BackgroundVideo.qml BorderOverlay 1.0 BorderOverlay.qml BorderSurface 1.0 BorderSurface.qml Button 1.0 Button.qml diff --git a/shell/plugins/background/Background.qml b/shell/plugins/background/Background.qml index c51181ed5646..8c113e4b0689 100644 --- a/shell/plugins/background/Background.qml +++ b/shell/plugins/background/Background.qml @@ -16,7 +16,6 @@ Item { property string currentBackground: "" property string displayedBackground: "" - property int displayedReloads: 0 property string incomingBackground: "" property string oldBackground: "" property bool finishingTransition: false @@ -60,9 +59,6 @@ Item { if (instant || !displayedBackground || isVideo(path) || isVideo(displayedBackground)) { oldBackground = "" incomingBackground = "" - // A theme switch can replace the file behind an unchanged path, which - // an unchanged property would never pick up. - if (displayedBackground === finalPath) displayedReloads += 1 displayedBackground = finalPath revealProgress = 1 return @@ -187,7 +183,6 @@ Item { } Component.onCompleted: { - oweStatusProc.running = true refreshBackground() } @@ -237,8 +232,6 @@ Item { id: base anchors.fill: parent path: root.displayedBackground - reloads: root.displayedReloads - videoEnabled: false onReadyChanged: { if (ready && root.finishingTransition) { root.incomingBackground = "" diff --git a/shell/plugins/lock/LockFeedSurface.qml b/shell/plugins/lock/LockFeedSurface.qml new file mode 100644 index 000000000000..38bd46129114 --- /dev/null +++ b/shell/plugins/lock/LockFeedSurface.qml @@ -0,0 +1,11 @@ +import QtQuick +import Owe.LockFeed + +// Loaded through a Loader from LockView, so a system without the module shows +// no lock video instead of losing the whole lock screen. +LockFeed { + id: root + + property bool feedEnabled: true + active: root.feedEnabled +} diff --git a/shell/plugins/lock/LockView.qml b/shell/plugins/lock/LockView.qml index e7a430ac67fa..9366b28985a4 100644 --- a/shell/plugins/lock/LockView.qml +++ b/shell/plugins/lock/LockView.qml @@ -43,6 +43,9 @@ Item { ? Border.surfaceSpec("lock", "border-error", Color.lock.borderError, root.outlineThickness, "border-alpha") : Border.surfaceSpec("lock", "border-active", Color.lock.borderActive, root.outlineThickness, "border-alpha") + readonly property bool video: Util.isVideoPath(root.backgroundPath) + readonly property bool feedActive: root.video && root.loadBackground && !root.displaysBlank && !root.powerSaverActive + signal submitPassword(string password) signal passwordTextEdited(string password) signal clearFailureRequested() @@ -89,15 +92,33 @@ Item { BackgroundMedia { id: wallpaper anchors.fill: parent - path: root.loadBackground ? root.backgroundPath : "" + path: root.video ? "" : root.backgroundPath version: root.backgroundVersion - playbackEnabled: root.loadBackground && !root.displaysBlank && !root.powerSaverActive + visible: !root.video + } + + // OWE decodes the video once and feeds these frames to every lock surface. + // The feed pauses when this output blanks or on battery power saver. + Loader { + id: feedLoader + anchors.fill: parent + active: root.video + source: "LockFeedSurface.qml" + visible: status === Loader.Ready + + Binding { + target: feedLoader.item + property: "feedEnabled" + value: root.feedActive + when: feedLoader.item !== null + restoreMode: Binding.RestoreNone + } } MultiEffect { anchors.fill: wallpaper - source: wallpaper.video ? null : wallpaper - visible: !wallpaper.video + source: root.video ? null : wallpaper + visible: !root.video autoPaddingEnabled: false blurEnabled: root.loadBackground && wallpaper.ready blur: 1.0 @@ -106,11 +127,11 @@ Item { contrast: -0.08 } - // Qt's video output cannot be sampled by MultiEffect on every renderer. + // The feed item cannot be sampled by MultiEffect on every renderer. // Keep video wallpapers visible and darken them slightly for legibility. Rectangle { - anchors.fill: wallpaper - visible: wallpaper.video + anchors.fill: feedLoader + visible: root.video color: "#22000000" } diff --git a/test/shell.d/video-background-test.sh b/test/shell.d/video-background-test.sh index 126537216acb..31ac754d2dc3 100755 --- a/test/shell.d/video-background-test.sh +++ b/test/shell.d/video-background-test.sh @@ -9,15 +9,13 @@ const fs = require('fs') const utilQml = fs.readFileSync(path.join(root, 'shell/Commons/Util.qml'), 'utf8') const mediaQml = fs.readFileSync(path.join(root, 'shell/Ui/BackgroundMedia.qml'), 'utf8') -const videoQml = fs.readFileSync(path.join(root, 'shell/Ui/BackgroundVideo.qml'), 'utf8') const backgroundQml = fs.readFileSync(path.join(root, 'shell/plugins/background/Background.qml'), 'utf8') const lockQml = fs.readFileSync(path.join(root, 'shell/plugins/lock/LockView.qml'), 'utf8') +const lockFeedQml = fs.readFileSync(path.join(root, 'shell/plugins/lock/LockFeedSurface.qml'), 'utf8') const themeSwitcher = fs.readFileSync(path.join(root, 'bin/omarchy-theme-switcher'), 'utf8') const quattroUpgrade = fs.readFileSync(path.join(root, 'bin/omarchy-upgrade-to-quattro'), 'utf8') -const multimediaMigration = fs.readFileSync(path.join(root, 'migrations/1786609204.sh'), 'utf8') const barTextColor = fs.readFileSync(path.join(root, 'bin/omarchy-bar-text-color'), 'utf8') const menuImages = fs.readFileSync(path.join(root, 'bin/omarchy-menu-images'), 'utf8') -const lockView = fs.readFileSync(path.join(root, 'shell/plugins/lock/LockView.qml'), 'utf8') const lockService = fs.readFileSync(path.join(root, 'shell/plugins/lock/Service.qml'), 'utf8') const batteryService = fs.readFileSync(path.join(root, 'shell/plugins/services/battery/Service.qml'), 'utf8') const themeSet = fs.readFileSync(path.join(root, 'bin/omarchy-theme-set'), 'utf8') @@ -29,50 +27,45 @@ assert( 'shared media helper identifies video paths without truncating valid local names' ) assert( - videoQml.includes('loops: MediaPlayer.Infinite') && - videoQml.includes('autoPlay: root.playbackEnabled') && - videoQml.includes('fillMode: VideoOutput.PreserveAspectCrop') && - /imageUrl: path && !Util\.isVideoPath\(path\) \? Util\.fileUrl\(path\) \+ \(version \? "\?v=" \+ version : ""\) : ""/.test(mediaQml) && - /videoUrl: path && Util\.isVideoPath\(path\) && videoEnabled \? Util\.fileUrl\(path\) : ""/.test(mediaQml), - 'background media plays aspect-cropped videos on a loop, and hands each loader only its own kind of file' + !fs.existsSync(path.join(root, 'shell/Ui/BackgroundVideo.qml')), + 'the shell keeps no video player of its own' ) assert( - videoQml.includes('MediaPlayer.LoadedMedia') && - videoQml.includes('primePauseTimer') && - videoQml.includes('mediaGeneration') && - videoQml.includes('videoSink') && - videoQml.includes('onVideoFrameChanged') && - videoQml.includes('MediaPlayer.BufferedMedia') && - videoQml.includes('mediaStatus !== MediaPlayer.BufferedMedia') && - videoQml.includes('interval: 1000') && - videoQml.includes('interval: 50') && - videoQml.includes('frameReceived') && - videoQml.includes('output.clearOutput()') && - !videoQml.includes('KeepLastFrame') && - /onPlaybackEnabledChanged:[\s\S]*?if \(playbackEnabled\) player\.play\(\)[\s\S]*?else player\.pause\(\)/.test(videoQml) && - videoQml.includes('primingGeneration') && - videoQml.includes('player.play()') && - videoQml.includes('player.pause()'), - 'paused video sources are primed to display their first frame' + /imageUrl: path && !video \? Util\.fileUrl\(path\) \+ \(version \? "\?v=" \+ version : ""\) : ""/.test(mediaQml) && + /active: root\.path !== "" && !root\.video/.test(mediaQml) && + !mediaQml.includes('videoUrl') && + !mediaQml.includes('videoLoader') && + !mediaQml.includes('videoEnabled'), + 'background media is image-only: it loads stills and leaves videos to OWE' ) assert( !/^\s*import QtMultimedia/m.test(mediaQml) && - mediaQml.includes('source: "BackgroundVideo.qml"'), - 'the still-image path never imports QtMultimedia, so image-only sessions do not map it' + !/^\s*import QtMultimedia/m.test(backgroundQml) && + !/^\s*import QtMultimedia/m.test(lockQml) && + !backgroundQml.includes('MediaPlayer') && + !lockQml.includes('MediaPlayer'), + 'no shell surface builds a Qt Multimedia pipeline' ) assert( - !/^\s*Video\s*\{/m.test(videoQml) && - !videoQml.includes('AudioOutput {') && - !videoQml.includes('audioOutput:') && - !mediaQml.includes('audioEnabled') && - !backgroundQml.includes('audioEnabled') && - !lockQml.includes('audioEnabled'), - 'the shell builds no audio output: OWE plays the desktop video audio and the lock stays silent' + /^import Owe\.LockFeed$/m.test(lockFeedQml) && + lockFeedQml.includes('LockFeed {') && + lockFeedQml.includes('active: root.feedEnabled') && + lockQml.includes('source: "LockFeedSurface.qml"') && + lockQml.includes('active: root.video') && + /feedActive: root\.video && root\.loadBackground && !root\.displaysBlank && !root\.powerSaverActive/.test(lockQml) && + /property: "feedEnabled"[\s\S]*?value: root\.feedActive/.test(lockQml), + 'the lock screen shows video through the OWE lock feed, loaded so a missing module costs only the video' ) assert( - /property: "mediaSource"[\s\S]*?when: videoLoader\.item !== null && Util\.isVideoPath\(root\.path\)\s*\n\s*restoreMode: Binding\.RestoreNone/.test(mediaQml) && - !videoQml.includes('Component.onDestruction'), - 'a player on its way out keeps its source, so nothing is left loading for its destructor to cancel' + !/^import Owe\./m.test(lockQml), + 'the lock view itself carries no foreign import, so the lock still loads without the feed module' +) +assert( + lockQml.includes('path: root.video ? "" : root.backgroundPath') && + lockQml.includes('visible: !root.video') && + lockQml.includes('visible: root.video') && + !lockQml.includes('wallpaper.video'), + 'the lock screen keeps its image effect for stills and shows the feed for videos' ) assert( !mediaQml.includes('mipmap'), @@ -82,13 +75,12 @@ assert( /instant \|\| !displayedBackground \|\| isVideo\(path\) \|\| isVideo\(displayedBackground\)[\s\S]*displayedBackground = finalPath/.test(backgroundQml), 'video switches bypass the image-only reveal stack and use the durable background path' ) -assert(backgroundQml.includes('BackgroundMedia {') && lockQml.includes('BackgroundMedia {'), 'desktop and lock screen share video-capable media rendering') +assert(backgroundQml.includes('BackgroundMedia {') && lockQml.includes('BackgroundMedia {'), 'desktop and lock screen share still rendering') assert( - backgroundQml.includes('videoEnabled: false') && - /property bool videoEnabled: true/.test(mediaQml) && - /active: root\.path !== "" && root\.video && !root\.reloading && root\.videoEnabled/.test(mediaQml) && - !lockQml.includes('videoEnabled'), - 'the desktop hands video backgrounds to OWE, and the lock keeps its own playback' + !backgroundQml.includes('videoEnabled') && + !backgroundQml.includes('displayedReloads') && + !mediaQml.includes('displayedReloads'), + 'the desktop hands video backgrounds to OWE with no player switch to carry' ) assert( !backgroundQml.includes('playbackEnabled') && @@ -99,19 +91,6 @@ assert( !backgroundQml.includes('omarchy.battery'), 'the desktop no longer carries the shell video pause policy' ) -assert( - lockQml.includes('source: wallpaper.video ? null : wallpaper') && - lockQml.includes('visible: !wallpaper.video') && - lockQml.includes('visible: wallpaper.video'), - 'lock screen bypasses its image effect for video output' -) -assert( - /if \(displayedBackground === finalPath\) displayedReloads \+= 1/.test(backgroundQml) && - backgroundQml.includes('reloads: root.displayedReloads') && - /active: root\.path !== "" && root\.video && !root\.reloading/.test(mediaQml) && - /onReloadsChanged: \{[\s\S]*?reloading = true/.test(mediaQml), - 'a theme switch that keeps the video path still reopens the replaced file' -) assert( barTextColor.includes('magick "$background_path[0]"'), 'bar colour sampling reads one frame instead of decoding a whole video' @@ -161,13 +140,12 @@ assert( 'a locked video wallpaper follows what each panel actually did, not only what the lock asked for' ) assert( - lockView.includes('playbackEnabled: root.loadBackground && !root.displaysBlank') && - lockView.includes('&& !root.powerSaverActive') && + /feedActive: root\.video && root\.loadBackground && !root\.displaysBlank && !root\.powerSaverActive/.test(lockQml) && /displaysBlank: root\.screenBlank\(/.test(lockService) && /powerSaverActive: root\.powerSaverActive/.test(lockService) && /function runBlank\(\) \{\s*\n\s*root\.displaysBlank = true/.test(lockService) && /function runWake\(\) \{\s*\n\s*root\.displaysBlank = false/.test(lockService), - 'the lock screen stops playback once displays go dark or power-saver is active' + 'the lock feed stops once displays go dark or power-saver is active' ) assert( batteryService.includes('property string activePowerProfile') && @@ -184,10 +162,6 @@ assert( 'theme switcher previews video-only themes, named preview files included' ) assert(quattroUpgrade.includes("-iname '*.mp4'"), 'Quattro upgrade can seed a video-only theme background') -assert( - multimediaMigration.includes('omarchy-pkg-add qt6-multimedia qt6-multimedia-ffmpeg'), - 'existing Quattro installations receive video playback dependencies' -) JS test_tmp=$(mktemp -d) @@ -301,8 +275,11 @@ timeout_rows=$(PATH="$test_tmp/bin:$PATH" XDG_CACHE_HOME="$timeout_cache" \ timeout_marker=$(find "$timeout_cache/omarchy/image-selector" -maxdepth 1 -type f -name '*.failed' -print -quit) [[ -z $timeout_marker ]] || fail "a timed out video is left to retry rather than remembered as failed" -grep -qx 'qt6-multimedia' "$ROOT/install/omarchy-base.packages" || fail "Qt Multimedia runtime is a base package" -grep -qx 'qt6-multimedia-ffmpeg' "$ROOT/install/omarchy-base.packages" || fail "Qt Multimedia FFmpeg backend is a base package" +grep -qx 'owe' "$ROOT/install/omarchy-base.packages" || fail "OWE is a base package" +grep -qx 'owe-lockfeed' "$ROOT/install/omarchy-base.packages" || fail "the OWE lock feed module is a base package" +if grep -qx 'qt6-multimedia' "$ROOT/install/omarchy-base.packages"; then + fail "Qt Multimedia is no longer needed by the shell" +fi pass "menu image generator creates thumbnails consumed by the picker" pass "direct picker generates and reuses still thumbnails" @@ -310,7 +287,7 @@ pass "direct picker omits videos whose thumbnails cannot be generated" pass "a rejected video is remembered so it costs nothing on the next open" pass "a timed out video is left to retry" pass "a locked video wallpaper follows the panels' real DPMS state" -pass "Qt Multimedia playback dependencies are declared" +pass "OWE and its lock feed module are declared" source <(awk ' /^(is_video_path|snapshot_background_path|background_transition_uses_snapshots|choose_theme_background|choose_staged_theme_background|set_theme_background)\(\) \{/ { copying=1 } From b0bf4876b10619743e5b93b577e19a37cbbe45cc Mon Sep 17 00:00:00 2001 From: Bjarne Oeverli <1419214+bjarneo@users.noreply.github.com> Date: Fri, 18 Sep 2026 22:55:27 +0200 Subject: [PATCH 103/194] Describe the lock feed in the background manual --- manual/39-backgrounds.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/manual/39-backgrounds.md b/manual/39-backgrounds.md index 6629ef27bffa..f57d23d28168 100644 --- a/manual/39-backgrounds.md +++ b/manual/39-backgrounds.md @@ -4,6 +4,6 @@ Every theme ships with its own set of backgrounds, and you can add extras of you You can do this most easily by going to _Install > Style > Background_ in the Omarchy Menu. That'll bring up the folder where the backgrounds for that theme is stored. Hit `Super + Shift + F` to start another file manager, find your background, copy it over. Now it'll be included in the choices of backgrounds you can select between using `Super + Ctrl + Space`. -Backgrounds can be videos as well as stills. Drop an `mp4`, `m4v`, `mov`, `webm`, `mkv`, or `avi` file in the same folder and it appears alongside the images. Videos are played by the OWE wallpaper engine. It decodes once for every monitor and plays the video's sound through the default audio output, and it stops playback whenever nothing can see it. The lock screen keeps its own silent playback. A video wallpaper still costs far more power than a still one. +Backgrounds can be videos as well as stills. Drop an `mp4`, `m4v`, `mov`, `webm`, `mkv`, or `avi` file in the same folder and it appears alongside the images. Videos are played by the OWE wallpaper engine. It decodes the video once for all monitors and plays its sound through the default audio output, and it stops playback whenever nothing can see it. The lock screen draws the same decode, muted, through OWE. A video wallpaper still costs far more power than a still one. You can find a huge collection of cool curated backgrounds on https://github.com/dharmx/walls. From 9e3ff71f4805a4deb20605c5178a78dce7c578b9 Mon Sep 17 00:00:00 2001 From: Spencer Bull Date: Sat, 19 Sep 2026 00:00:15 -0500 Subject: [PATCH 104/194] Simplify Elsewhen installation and bar migration Link the package into the existing plugin directory and let bar put handle enablement, clock-relative placement, and the missing-clock fallback. Preserve user checkouts and existing placements, and seed the same link for new users. This removes the Atreyu packaged-discovery prerequisite and the checkout cleanup and JSON rewrite machinery. --- config/omarchy/plugins/omacom.elsewhen | 1 + default/agents/skills/omarchy/plugins.md | 3 - docs/file-layout.md | 3 - docs/omarchy-shell.md | 4 +- migrations/1789581661.sh | 89 +---- shell/README.md | 5 - shell/plugins/README.md | 6 +- test/shell.d/config-test.sh | 4 +- .../elsewhen-default-migration-test.sh | 374 +++--------------- 9 files changed, 57 insertions(+), 432 deletions(-) create mode 120000 config/omarchy/plugins/omacom.elsewhen diff --git a/config/omarchy/plugins/omacom.elsewhen b/config/omarchy/plugins/omacom.elsewhen new file mode 120000 index 000000000000..19840c51cbb9 --- /dev/null +++ b/config/omarchy/plugins/omacom.elsewhen @@ -0,0 +1 @@ +/usr/share/omarchy/plugins/omacom.elsewhen \ No newline at end of file diff --git a/default/agents/skills/omarchy/plugins.md b/default/agents/skills/omarchy/plugins.md index 1c58c83ac38f..6e3ab0695ea5 100644 --- a/default/agents/skills/omarchy/plugins.md +++ b/default/agents/skills/omarchy/plugins.md @@ -9,12 +9,9 @@ inside a single long-running Quickshell process (`omarchy-shell`). ``` ~/.config/omarchy/shell.json # User overrides: bar, plugins, idle ~/.config/omarchy/plugins// # User-owned shell plugins -/usr/share/omarchy/plugins// # Packaged plugins (pacman), e.g. omacom.elsewhen $OMARCHY_PATH/config/omarchy/shell.json # Canonical defaults ``` -Packaged plugins such as Elsewhen (`elsewhen` package) update with `omarchy update` and are removed with pacman; `omarchy plugin update` and `omarchy plugin remove` refuse them and name the package. - The shell hot-reloads `shell.json` on save — no restart needed for layout changes. `idle.screensaver` and `idle.lock` are seconds since user idle began. diff --git a/docs/file-layout.md b/docs/file-layout.md index 8bbcd5b2cdd3..f261085f0eae 100644 --- a/docs/file-layout.md +++ b/docs/file-layout.md @@ -78,9 +78,6 @@ install/** ──► omarchy /usr/share/omarchy migrations/** ──► omarchy /usr/share/omarchy/migrations/ themes/** ──► omarchy /usr/share/omarchy/themes/ shell/** ──► omarchy /usr/share/omarchy/shell/ - (packaged plugins from their own - packages, e.g. elsewhen, land beside it - in /usr/share/omarchy/plugins//) version ──► omarchy /usr/share/omarchy/version + /etc/skel/.local/state/omarchy/migrations/* diff --git a/docs/omarchy-shell.md b/docs/omarchy-shell.md index dd8cc18a7bcb..6e999682a882 100644 --- a/docs/omarchy-shell.md +++ b/docs/omarchy-shell.md @@ -88,9 +88,9 @@ bar from the CLI — `use | reset | defaults | position | transparent | put | move | set`, with placement flags such as `--section` and `--index`. The lower-level IPC methods remain available through `omarchy-shell shell ...`. -## Packaged plugins +## Elsewhen -A default plugin can ship as its own Arch package instead of in the Omarchy checkout: Elsewhen (`omacom.elsewhen`) is the `elsewhen` package. pacman installs it at `/usr/share/omarchy/plugins//`, a root the shell scans between `$OMARCHY_PATH/shell/plugins` and `~/.config/omarchy/plugins`. A packaged `omarchy.*` id is trusted like a bundled plugin and loads by default; any other packaged id behaves like an installed plugin. Precedence is bundled, then packaged, then user, so a checkout under `omarchy dev link` overrides the package. Packaged plugins update through `omarchy update` and leave through pacman; `omarchy plugin update` and `omarchy plugin remove` refuse them and name the package, and Setup › Plugins › Remove does not list them. +Elsewhen (`omacom.elsewhen`) ships in the `elsewhen` package at `/usr/share/omarchy/plugins/omacom.elsewhen`. A symlink in `~/.config/omarchy/plugins/` makes it available to the shell. New installs place it immediately before the clock; the migration uses `omarchy bar put omacom.elsewhen --before omarchy.clock`, which preserves an existing placement and uses Elsewhen's normal right-side placement if the clock is absent. Existing plugin directories and symlinks are left intact. ## IPC diff --git a/migrations/1789581661.sh b/migrations/1789581661.sh index f581d4d03397..10f18e660a7c 100644 --- a/migrations/1789581661.sh +++ b/migrations/1789581661.sh @@ -1,88 +1,13 @@ echo "Install Elsewhen, the world clock plugin" -# Elsewhen ships as the elsewhen package rather than in this checkout; pacman -# puts it under /usr/share/omarchy/plugins, where the shell looks next to its -# bundled plugins. A package the mirror does not carry yet fails the migration -# on purpose: nothing before this line has changed anything, and the runner -# retries it on the next update or login rather than quietly leaving the -# machine without the plugin. omarchy-pkg-add elsewhen -# A shell that already knows the packaged root (dev-linked, or restarted -# since) picks the plugin up here; the one an update runs under predates it -# and is replaced by omarchy-update-restart right after the migrations. -omarchy-shell -q shell rescanPlugins || true - -# Before the package, the README had users run -# `omarchy plugin add https://github.com/omacom/elsewhen.git`, which left a -# git clone under ~/.config/omarchy/plugins. The packaged copy now shadows -# it: the shell logs a rejection on every scan, and `omarchy plugin update` -# keeps pulling a checkout nothing loads. A pristine clone of the upstream -# repo is retired the way `omarchy plugin remove` retires one (the repo -# remains upstream). Anything else -- a symlink, a plain directory, local -# changes, a fork, a checkout git cannot read -- is the user's and stays. This -# runs only once the package is in place, so the plugin never leaves a -# machine; its id stays in shell.json either way, which is what keeps it -# enabled. The shell an update runs under predates the packaged root, and it -# watches this directory: dropping the checkout empties the widget's slot in -# that shell until omarchy-update-restart replaces it a few steps later with -# one that finds the package. A one-time gap of a few minutes, during the -# update itself. -upstream_checkout() { - local dir="$1" origin status unpublished - [[ -d $dir && ! -L $dir && -d $dir/.git ]] || return 1 - origin=$(git -C "$dir" remote get-url origin 2>/dev/null) || return 1 - origin=${origin,,} - origin=${origin%/} - origin=${origin%.git} - [[ $origin =~ ^([a-z+]+://)?([^/@]+@)?github\.com[/:]omacom/elsewhen$ ]] || return 1 - status=$(git -C "$dir" status --porcelain --untracked-files=all --ignored 2>/dev/null) || return 1 - [[ -z $status ]] || return 1 - # Local branches, stashes, and reflogs may hold work absent from a clean tree. - unpublished=$(git -C "$dir" rev-list HEAD --all --reflog --not --remotes=origin 2>/dev/null) || return 1 - [[ -z $unpublished ]] -} - -checkout="$HOME/.config/omarchy/plugins/omacom.elsewhen" -if [[ -e $checkout || -L $checkout ]]; then - if upstream_checkout "$checkout"; then - rm -rf "$checkout" - echo "Retired the omacom.elsewhen checkout at $checkout in favour of the elsewhen package." - else - echo "The elsewhen package takes precedence over $checkout, which is left as it is." - fi -fi - -# The widget sits just before the clock in the center of the default bar, -# which a machine without a shell.json takes on as soon as the shell -# restarts. A customized bar gets the entry written into its file rather than -# placed over IPC: the shell this runs under cannot see a widget its scan -# never reached and would refuse it, whereas the file it hot-reloads carries -# the entry through to the restart. A bar that already carries the widget -# keeps it where the user put it. -source omarchy-shell-config - -[[ -s $CONFIG_FILE ]] || exit 0 -# Preserve configs whose bar comes from the shell fallback instead of an explicit layout. -jq -e 'type == "object" and .version == 1 and (.bar | type == "object") and (.bar.layout | type == "object")' "$CONFIG_FILE" >/dev/null 2>&1 || exit 0 - -entry_id='def entry_id: if type == "object" then (.id // "" | tostring) else tostring end;' - -if jq -e "$entry_id"' - any((.bar.layout // {} | .left, .center, .right | arrays)[]; entry_id == "omacom.elsewhen") -' "$CONFIG_FILE" >/dev/null; then - exit 0 +plugin="$HOME/.config/omarchy/plugins/omacom.elsewhen" +mkdir -p "$(dirname "$plugin")" +if [[ ! -e $plugin && ! -L $plugin ]]; then + ln -s /usr/share/omarchy/plugins/omacom.elsewhen "$plugin" fi -commit "$NORMALIZE | $entry_id"' - def ids: map(entry_id); - def insert_at($section; $index): - .bar.layout[$section] = .bar.layout[$section][:$index] + [{id: "omacom.elsewhen"}] + .bar.layout[$section][$index:]; - . as $config - | (["left", "center", "right"] | map(select($config.bar.layout[.] | ids | index("omarchy.clock") != null)) | first) as $section - | if $section != null then - insert_at($section; .bar.layout[$section] | ids | index("omarchy.clock")) - else - insert_at("center"; 0) - end -' +omarchy-shell shell rescanPlugins +omarchy-bar put omacom.elsewhen --before omarchy.clock +omarchy-restart-shell diff --git a/shell/README.md b/shell/README.md index 53425139b8e4..ca07b520ae44 100644 --- a/shell/README.md +++ b/shell/README.md @@ -140,10 +140,6 @@ You can still drop a plugin in without git: `barWidget.defaultSection`, or in the center when it is omitted, and can be moved with `omarchy bar move`; a full bar replaces the one in use. -### Packaged plugins - -Some default plugins ship as their own Arch package rather than in this checkout: Elsewhen (`omacom.elsewhen`) is the `elsewhen` package. pacman installs such a plugin, root-owned, at `/usr/share/omarchy/plugins//`, and the shell scans that root between its bundled plugins and the user's. A packaged `omarchy.*` id is trusted exactly like a bundled one; a packaged plugin under any other id is treated like a user plugin. They update with `omarchy update` and are removed with pacman, so `omarchy plugin update` and `omarchy plugin remove` refuse them and name the package instead. A bundled copy in `$OMARCHY_PATH/shell/plugins` wins over the packaged one, which is how a packaged plugin is developed under `omarchy dev link`. - The lower-level IPC equivalents remain available via `omarchy-shell shell rescanPlugins`, `omarchy-shell shell enablePlugin '{}'`, and `omarchy-shell shell listPlugins`. The `omarchy plugin` commands wrap those calls. `omarchy bar move` and @@ -228,7 +224,6 @@ customization from the shipped defaults lives in it. |-----------------------------------|----------------|--------------------------------------------------------| | `~/.config/omarchy/shell.json` | the shell | full layout + per-entry settings + enabled plugin list | | `~/.config/omarchy/plugins//` | user | drop-in third-party plugin source files | -| `/usr/share/omarchy/plugins//` | pacman | packaged plugins (e.g. `elsewhen`), updated by `omarchy update` | The `config/omarchy/shell.json` default config describes the fresh-install state. When the user has no `shell.json`, the shell uses diff --git a/shell/plugins/README.md b/shell/plugins/README.md index 1a2d26fb0bc5..66cb74e14fdb 100644 --- a/shell/plugins/README.md +++ b/shell/plugins/README.md @@ -9,10 +9,7 @@ First-party non-bar plugins are enabled unless listed in `disabledPlugins[]`; at startup; other panels, overlays, and menus are loaded on demand. User-installed plugins live alongside these conceptually but on disk under -`~/.config/omarchy/plugins//` rather than in this directory. A few -default plugins arrive as their own package instead: pacman installs them at -`/usr/share/omarchy/plugins//`, where an `omarchy.*` id is trusted -like the plugins here, and a copy in this directory shadows the packaged one. +`~/.config/omarchy/plugins//` rather than in this directory. | Plugin | id | kinds | entry point | |---------------|---------------------------|-------------------------|---------------------------------------| @@ -31,7 +28,6 @@ like the plugins here, and a copy in this directory shadows the packaged one. | Power | `omarchy.power` | `bar-widget` | `panels/power/Panel.qml` | | Tailscale | `omarchy.tailscale` | `bar-widget` | `panels/tailscale/Panel.qml` | | Agents | `omarchy.agents` | `bar-widget` | `agents/Panel.qml` | -| Elsewhen | `omacom.elsewhen` | `bar-widget` | packaged: `elsewhen` installs `/usr/share/omarchy/plugins/omacom.elsewhen/` | | Weather | `omarchy.weather` | `bar-widget` | `panels/weather/BarWidget.qml` | | Media | `omarchy.media` | `service`, `bar-widget` | `services/media/Service.qml`, `services/media/BarWidget.qml` | | Battery | `omarchy.battery` | `service` | `services/battery/Service.qml` | diff --git a/test/shell.d/config-test.sh b/test/shell.d/config-test.sh index 1cd47e3381d3..82a51e6f57be 100755 --- a/test/shell.d/config-test.sh +++ b/test/shell.d/config-test.sh @@ -52,9 +52,9 @@ jq -e ' (.bar.layout.right | ids) as $ids | ($ids | index("omarchy.tray")) as $tray | ($ids | index("omarchy.agents")) as $agents | - $tray == 0 and $agents == $tray + 1 + $tray != null and $agents == $tray + 1 ' "$ROOT/config/omarchy/shell.json" >/dev/null -pass "default right layout opens with the tray, then agents" +pass "default right layout keeps agents next to the tray" ROOT="$ROOT" python3 <<'PY' import json diff --git a/test/shell.d/elsewhen-default-migration-test.sh b/test/shell.d/elsewhen-default-migration-test.sh index 525094e5f9df..bda62fd63507 100644 --- a/test/shell.d/elsewhen-default-migration-test.sh +++ b/test/shell.d/elsewhen-default-migration-test.sh @@ -3,361 +3,75 @@ set -euo pipefail source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" - require_command jq -require_command git -migration="$ROOT/migrations/1789581661.sh" test_dir=$(mktemp -d) trap 'rm -rf "$test_dir"' EXIT +mkdir -p "$test_dir/bin" "$test_dir/home" +export CALL_LOG="$test_dir/calls" -mkdir -p "$test_dir/bin" -export INSTALLED_PACKAGES="$test_dir/installed" CALL_LOG="$test_dir/calls" SHELL_CALLS="$test_dir/shell-calls" -# The checkout cases use the real git; keep the developer's config (signing, -# hooks, safe.directory) out of what it sees. -export GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 -export GIT_AUTHOR_NAME=test GIT_AUTHOR_EMAIL=test@example.com -export GIT_COMMITTER_NAME=test GIT_COMMITTER_EMAIL=test@example.com - -# Keep the real package helpers, but contain every pacman transaction here. -cat >"$test_dir/bin/pacman" <<'SH' +cat >"$test_dir/bin/omarchy-pkg-add" <<'SH' #!/bin/bash -case "$1" in - -Q) grep -Fxq -- "$2" "$INSTALLED_PACKAGES" ;; - -S) - [[ ${FAIL_INSTALL:-0} == 0 ]] || exit 1 - shift 3 # -S --noconfirm --needed - printf '%s\n' "$@" >>"$INSTALLED_PACKAGES" - printf '%s\n' "$@" >>"$CALL_LOG" - ;; - *) exit 1 ;; -esac +printf 'package %s\n' "$*" >>"$CALL_LOG" +exit "${PACKAGE_STATUS:-0}" SH -cat >"$test_dir/bin/sudo" <<'SH' +cat >"$test_dir/bin/omarchy-shell" <<'SH' #!/bin/bash -[[ $1 == "pacman" ]] || exit 1 -"$@" +printf '%s\n' "$*" >>"$CALL_LOG" +[[ $2 != "rescanPlugins" ]] || exit "${SCAN_STATUS:-0}" +printf '%s\n' "${TEST_PUT_RESULT:-ok}" SH -# The migration runs under a shell that predates the packaged root, or under -# none at all, so it must only ever ask the shell for best-effort refreshes. -cat >"$test_dir/bin/omarchy-shell" <<'SH' +cat >"$test_dir/bin/omarchy-restart-shell" <<'SH' #!/bin/bash -printf '%s\n' "$*" >>"$SHELL_CALLS" -[[ $1 != "-q" ]] || exit 0 -exit "${SHELL_STATUS:-0}" +printf 'restart\n' >>"$CALL_LOG" SH chmod +x "$test_dir/bin/"* -home="$test_dir/home" -config="$home/.config/omarchy/shell.json" -checkout="$home/.config/omarchy/plugins/omacom.elsewhen" -output="$test_dir/output" -mkdir -p "$home/.config/omarchy" - +plugin="$test_dir/home/.config/omarchy/plugins/omacom.elsewhen" run_migration() { : >"$CALL_LOG" - : >"$SHELL_CALLS" - HOME="$home" OMARCHY_PATH="$ROOT" PATH="$test_dir/bin:$ROOT/bin:$PATH" \ - bash -euo pipefail "$migration" >"$output" -} - -ids() { - jq -c ".bar.layout.$1 | map(if type == \"object\" then .id else . end)" "$config" -} - -# ------------------------------------------------------------ package install -: >"$INSTALLED_PACKAGES" -cat >"$config" <<'JSON' -{ - "version": 1, - "bar": { - "layout": { - "left": [{ "id": "omarchy.menu" }], - "center": [{ "id": "omarchy.clock", "format": "HH:mm" }], - "right": [ - { "id": "omarchy.tray" }, - { "id": "omarchy.agents", "syncMode": "On" }, - { "id": "omarchy.power" } - ] - } - }, - "plugins": [] + HOME="$test_dir/home" OMARCHY_PATH="$ROOT" PATH="$test_dir/bin:$ROOT/bin:$PATH" \ + bash -euo pipefail "$ROOT/migrations/1789581661.sh" >"$test_dir/output" 2>&1 } -JSON - -run_migration -grep -Fxq elsewhen "$CALL_LOG" || fail "migration installs the elsewhen package" "$(cat "$CALL_LOG")" -pass "migration installs the elsewhen package" - -[[ $(ids center) == '["omacom.elsewhen","omarchy.clock"]' && $(ids right) == '["omarchy.tray","omarchy.agents","omarchy.power"]' ]] || - fail "migration puts the widget just before the center clock" "$(cat "$config")" -pass "migration puts the widget just before the center clock" - -[[ $(jq -c '.bar.layout.right[1]' "$config") == '{"id":"omarchy.agents","syncMode":"On"}' ]] || - fail "migration keeps the settings of its neighbours" "$(cat "$config")" -[[ $(jq -c '.bar.layout.center[1]' "$config") == '{"format":"HH:mm","id":"omarchy.clock"}' ]] || - fail "migration keeps the clock settings" "$(cat "$config")" -pass "migration leaves the rest of the layout alone" - -grep -q 'shell rescanPlugins' "$SHELL_CALLS" && grep -q 'shell reloadConfig' "$SHELL_CALLS" || - fail "migration asks the running shell to rescan and reload" "$(cat "$SHELL_CALLS")" -pass "migration asks the running shell to rescan and reload" - -before=$(sha256sum "$config") -run_migration -[[ $before == $(sha256sum "$config") ]] || fail "migration is idempotent" "$(cat "$config")" -[[ ! -s $CALL_LOG ]] || fail "migration does not reinstall a present package" "$(cat "$CALL_LOG")" -pass "migration is idempotent" - -# ------------------------------------------------------------- placements -cat >"$config" <<'JSON' -{ - "version": 1, - "bar": { "layout": { "left": [], "center": ["omarchy.clock", "omarchy.tray"], "right": ["omarchy.power"] } } -} -JSON -run_migration -[[ $(ids center) == '["omacom.elsewhen","omarchy.clock","omarchy.tray"]' && $(ids right) == '["omarchy.power"]' ]] || - fail "migration reads string clock entries" "$(cat "$config")" -pass "migration reads string clock entries" - -cat >"$config" <<'JSON' -{ "version": 1, "bar": { "layout": { "right": [{ "id": "omarchy.agents" }, { "id": "omarchy.power" }] } } } -JSON -run_migration -[[ $(ids center) == '["omacom.elsewhen"]' && $(ids right) == '["omarchy.agents","omarchy.power"]' ]] || - fail "migration prepends to the center section when the clock is off the bar" "$(cat "$config")" -pass "migration prepends to the center section when the clock is off the bar" - -cat >"$config" <<'JSON' -{ - "version": 1, - "bar": { "layout": { "left": [{ "id": "omacom.elsewhen" }], "center": [], "right": [{ "id": "omarchy.tray" }, { "id": "omarchy.agents" }] } } -} -JSON -before=$(sha256sum "$config") -run_migration -[[ $before == $(sha256sum "$config") ]] || - fail "migration leaves a widget the user already placed where it is" "$(cat "$config")" -pass "migration leaves a widget the user already placed where it is" - -# A customized clock keeps its section and settings; insert only its neighbour. -for section in left right; do - jq -n --arg section "$section" '{version: 1, bar: {layout: {center: ["omarchy.weather"], ($section): ["omarchy.menu", {id: "omarchy.clock", format: "HH:mm"}]}}}' >"$config" - run_migration - [[ $(ids "$section") == '["omarchy.menu","omacom.elsewhen","omarchy.clock"]' && $(ids center) == '["omarchy.weather"]' ]] || - fail "migration follows a clock customized into $section" "$(cat "$config")" - pass "migration follows a clock customized into $section" -done - -# ------------------------------------------------------------- edge cases -rm -f "$config" -run_migration -[[ ! -e $config ]] || fail "migration writes no shell.json where the defaults apply" "$(cat "$config")" -pass "migration writes no shell.json where the defaults apply" - -for partial in \ - '{"version":1,"idle":{"lock":600}}' \ - '{"version":1,"bar":null,"idle":{"lock":600}}' \ - '{"version":1,"bar":{"position":"bottom"}}' \ - '{"bar":{"layout":{"center":["omarchy.clock"]}}}'; do - printf '%s\n' "$partial" >"$config" - before=$(sha256sum "$config") - run_migration - [[ $before == $(sha256sum "$config") ]] || fail "migration preserves fallback configuration" "$(cat "$config")" - pass "migration preserves fallback configuration: $partial" -done - -printf '{ not json' >"$config" -run_migration -[[ $(cat "$config") == '{ not json' ]] || fail "migration leaves an unparsable config untouched" "$(cat "$config")" -pass "migration leaves an unparsable config untouched" - -cat >"$config" <<'JSON' -{ "version": 1, "bar": { "layout": { "right": [{ "id": "omarchy.tray" }, { "id": "omarchy.agents" }] } } } -JSON -SHELL_STATUS=1 run_migration -[[ $(ids center) == '["omacom.elsewhen"]' && $(ids right) == '["omarchy.tray","omarchy.agents"]' ]] || - fail "migration places the widget with no shell running" "$(cat "$config")" -pass "migration places the widget with no shell running" -# A package the mirror does not carry yet leaves the migration pending rather -# than half-done: the layout must not name a widget nothing can install. -: >"$INSTALLED_PACKAGES" -cat >"$config" <<'JSON' -{ "version": 1, "bar": { "layout": { "right": [{ "id": "omarchy.tray" }, { "id": "omarchy.agents" }] } } } -JSON -before=$(sha256sum "$config") -if FAIL_INSTALL=1 run_migration 2>/dev/null; then - fail "a failed package installation must leave the migration pending" +if PACKAGE_STATUS=1 run_migration; then + fail "package failure stops the migration" fi -[[ $before == $(sha256sum "$config") ]] || - fail "a failed package installation leaves the layout untouched" "$(cat "$config")" -pass "a failed package installation is propagated and changes nothing" +[[ ! -e $plugin && ! -L $plugin && $(cat "$CALL_LOG") == "package elsewhen" ]] || + fail "package failure leaves the plugin and shell untouched" +pass "package failure stops before linking or changing the shell" -# ------------------------------------------------- pre-package checkouts -# Users who followed the README before the package existed hold a git clone -# under ~/.config/omarchy/plugins, which the packaged copy now shadows. Only a -# clone of the upstream repo with nothing local in it is retired; everything -# else is the user's and stays, and shell.json gets the widget either way. - -# A clone made by `omarchy plugin add`: one commit, the given origin, nothing -# local. Built with init rather than clone so the origin can be any URL form. -make_checkout() { - local origin="$1" - rm -rf "$checkout" - mkdir -p "$checkout" - git -C "$checkout" init -q - git -C "$checkout" remote add origin "$origin" - printf '{ "id": "omacom.elsewhen" }\n' >"$checkout/manifest.json" - printf 'import QtQuick\nItem {}\n' >"$checkout/Panel.qml" - git -C "$checkout" add -A - git -C "$checkout" commit -q -m "Elsewhen" - git -C "$checkout" update-ref refs/remotes/origin/main HEAD -} - -reset_layout() { - cat >"$config" <<'JSON' -{ "version": 1, "bar": { "layout": { "right": [{ "id": "omarchy.tray" }, { "id": "omarchy.power" }] } } } -JSON -} - -assert_widget_placed() { - [[ $(ids center) == '["omacom.elsewhen"]' && $(ids right) == '["omarchy.tray","omarchy.power"]' ]] || - fail "$1 still gets the widget" "$(cat "$config")" -} - -assert_retired() { - local description="$1" - [[ ! -e $checkout && ! -L $checkout ]] || fail "$description is retired" "$(ls -la "$checkout")" - grep -q 'Retired the omacom.elsewhen checkout' "$output" || fail "$description is reported as retired" "$(cat "$output")" - assert_widget_placed "$description" - pass "$description is retired" -} - -assert_kept() { - local description="$1" - [[ -e $checkout || -L $checkout ]] || fail "$description is kept" - grep -q 'takes precedence over' "$output" || fail "$description is reported as shadowed" "$(cat "$output")" - assert_widget_placed "$description" - pass "$description is kept" -} - -for origin in \ - https://github.com/omacom/elsewhen.git \ - https://github.com/omacom/elsewhen \ - git@github.com:omacom/elsewhen.git \ - ssh://git@github.com/omacom/elsewhen.git \ - https://GitHub.com/Omacom/Elsewhen/; do - make_checkout "$origin" - reset_layout - run_migration - assert_retired "a pristine clone with origin $origin" -done - -make_checkout https://github.com/omacom/elsewhen.git -printf 'import QtQuick\nItem { id: mine }\n' >"$checkout/Panel.qml" -reset_layout -run_migration -assert_kept "a clone with a modified tracked file" -[[ $(cat "$checkout/Panel.qml") == $'import QtQuick\nItem { id: mine }' ]] || - fail "a kept clone keeps its local change" "$(cat "$checkout/Panel.qml")" -pass "a kept clone keeps its local change" - -make_checkout https://github.com/omacom/elsewhen.git -printf 'notes\n' >"$checkout/NOTES.md" -reset_layout -run_migration -assert_kept "a clone with an untracked file" - -make_checkout https://github.com/omacom/elsewhen.git -printf 'import QtQuick\nItem { id: mine }\n' >"$checkout/Panel.qml" -git -C "$checkout" add Panel.qml -git -C "$checkout" commit -q -m "Local customization" -local_commit=$(git -C "$checkout" rev-parse HEAD) -reset_layout -run_migration -assert_kept "a clean clone with an unpublished commit" -[[ $(git -C "$checkout" rev-parse HEAD) == "$local_commit" ]] || fail "local commit survives" - -make_checkout https://github.com/omacom/elsewhen.git -git -C "$checkout" checkout -qb local-work -printf 'local branch\n' >"$checkout/Panel.qml" -git -C "$checkout" commit -qam "Unpublished branch" -git -C "$checkout" checkout -q --detach refs/remotes/origin/main -reset_layout -run_migration -assert_kept "an unpublished commit on another branch" - -make_checkout https://github.com/omacom/elsewhen.git -printf 'stashed work\n' >"$checkout/Panel.qml" -git -C "$checkout" stash push -q -reset_layout -run_migration -assert_kept "a clean clone with stashed work" - -make_checkout https://github.com/omacom/elsewhen.git -git -C "$checkout" config status.showUntrackedFiles no -printf 'private-notes\n' >"$checkout/.git/info/exclude" -printf 'ignored work\n' >"$checkout/private-notes" -reset_layout -run_migration -assert_kept "a clone with an ignored file" -[[ $(cat "$checkout/private-notes") == "ignored work" ]] || fail "ignored file survives" - -make_checkout https://github.com/omacom/elsewhen.git -printf 'recoverable work\n' >"$checkout/Panel.qml" -git -C "$checkout" commit -qam "Recoverable local commit" -git -C "$checkout" reset -q --hard refs/remotes/origin/main -reset_layout -run_migration -assert_kept "a local commit retained only by the reflog" - -make_checkout https://github.com/omacom/elsewhen.git -git -C "$checkout" update-ref -d refs/remotes/origin/main -reset_layout -run_migration -assert_kept "a clone without recorded upstream history" - -make_checkout https://github.com/omacom/elsewhen.git -git -C "$checkout" config status.showUntrackedFiles no -printf 'untracked work\n' >"$checkout/NOTES.md" -reset_layout run_migration -assert_kept "untracked files hidden by the user Git configuration" +[[ $(readlink "$plugin") == /usr/share/omarchy/plugins/omacom.elsewhen ]] || fail "package link is installed" +[[ $(readlink "$ROOT/config/omarchy/plugins/omacom.elsewhen") == "$(readlink "$plugin")" ]] || fail "fresh installs use the same package link" +pass "migration and fresh installs link to the package" -make_checkout https://github.com/someone/elsewhen-fork.git -reset_layout -run_migration -assert_kept "a clone of another repository" +expected=$'package elsewhen\nshell rescanPlugins\nshell putBarWidget omacom.elsewhen {"before":"omarchy.clock"}\nrestart' +[[ $(cat "$CALL_LOG") == "$expected" ]] || fail "install, scan, placement and restart run in order" "$(cat "$CALL_LOG")" +pass "real bar helper enables and places before the clock, then restarts" -make_checkout https://github.com/omacom/elsewhen.git -git -C "$checkout" remote remove origin -reset_layout run_migration -assert_kept "a clone without an origin remote" +[[ $(cat "$CALL_LOG") == "$expected" ]] || fail "migration can be rerun" +pass "migration can be rerun with its package link present" -rm -rf "$checkout" -mkdir -p "$checkout" -printf '{ "id": "omacom.elsewhen" }\n' >"$checkout/manifest.json" -reset_layout +rm "$plugin" +mkdir "$plugin" +printf 'local work\n' >"$plugin/notes" run_migration -assert_kept "a plain directory without .git" +[[ ! -L $plugin && $(cat "$plugin/notes") == "local work" ]] || fail "existing checkout is preserved" +pass "existing checkout and local files are preserved" -rm -rf "$checkout" -make_checkout https://github.com/omacom/elsewhen.git -mv "$checkout" "$test_dir/elsewhen-src" -ln -s "$test_dir/elsewhen-src" "$checkout" -reset_layout +rm "$plugin/notes" +rmdir "$plugin" +ln -s "$test_dir/custom-plugin" "$plugin" run_migration -assert_kept "a symlinked checkout" -[[ -L $checkout && -f $test_dir/elsewhen-src/manifest.json ]] || - fail "a symlinked checkout stays a symlink with its target intact" "$(ls -la "$checkout" "$test_dir/elsewhen-src")" -pass "a symlinked checkout stays a symlink with its target intact" +[[ $(readlink "$plugin") == "$test_dir/custom-plugin" ]] || fail "existing symlink is preserved" +pass "existing symlink is preserved, including a missing target" -rm -f "$checkout" -reset_layout -run_migration -grep -q 'omacom.elsewhen checkout\|takes precedence' "$output" && fail "no checkout means no checkout report" "$(cat "$output")" -assert_widget_placed "a machine without a checkout" -pass "a machine without a checkout is left alone" +for failure in 'SCAN_STATUS=1' 'TEST_PUT_RESULT=unknown'; do + if env "$failure" HOME="$test_dir/home" OMARCHY_PATH="$ROOT" PATH="$test_dir/bin:$ROOT/bin:$PATH" \ + bash -euo pipefail "$ROOT/migrations/1789581661.sh" >"$test_dir/output" 2>&1; then + fail "$failure must leave the migration pending" + fi + pass "$failure leaves the migration pending" +done From 16cc7d7a9dcf40320016dae37da8b97889d7cb58 Mon Sep 17 00:00:00 2001 From: Spencer Bull Date: Sat, 19 Sep 2026 00:06:29 -0500 Subject: [PATCH 105/194] Leave the shell restart to the update flow Restarting immediately after the plugin rescan races Quickshell IPC handler creation and can crash the exiting shell. The normal update flow already restarts after migrations. Let this migration finish through live enablement and placement without adding timing workarounds. --- docs/omarchy-shell.md | 2 +- migrations/1789581661.sh | 1 - test/shell.d/elsewhen-default-migration-test.sh | 9 +++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/omarchy-shell.md b/docs/omarchy-shell.md index 6e999682a882..d62661a79b9c 100644 --- a/docs/omarchy-shell.md +++ b/docs/omarchy-shell.md @@ -90,7 +90,7 @@ The lower-level IPC methods remain available through `omarchy-shell shell ...`. ## Elsewhen -Elsewhen (`omacom.elsewhen`) ships in the `elsewhen` package at `/usr/share/omarchy/plugins/omacom.elsewhen`. A symlink in `~/.config/omarchy/plugins/` makes it available to the shell. New installs place it immediately before the clock; the migration uses `omarchy bar put omacom.elsewhen --before omarchy.clock`, which preserves an existing placement and uses Elsewhen's normal right-side placement if the clock is absent. Existing plugin directories and symlinks are left intact. +Elsewhen (`omacom.elsewhen`) ships in the `elsewhen` package at `/usr/share/omarchy/plugins/omacom.elsewhen`. A symlink in `~/.config/omarchy/plugins/` makes it available to the shell. New installs place it immediately before the clock; the migration uses `omarchy bar put omacom.elsewhen --before omarchy.clock`, which preserves an existing placement and uses Elsewhen's normal right-side placement if the clock is absent. Existing plugin directories and symlinks are left intact. The normal update flow restarts the shell after migrations; the migration does not interrupt plugin loading with an immediate restart. ## IPC diff --git a/migrations/1789581661.sh b/migrations/1789581661.sh index 10f18e660a7c..5c022e1c957f 100644 --- a/migrations/1789581661.sh +++ b/migrations/1789581661.sh @@ -10,4 +10,3 @@ fi omarchy-shell shell rescanPlugins omarchy-bar put omacom.elsewhen --before omarchy.clock -omarchy-restart-shell diff --git a/test/shell.d/elsewhen-default-migration-test.sh b/test/shell.d/elsewhen-default-migration-test.sh index bda62fd63507..c0a2de8ff1c8 100644 --- a/test/shell.d/elsewhen-default-migration-test.sh +++ b/test/shell.d/elsewhen-default-migration-test.sh @@ -23,7 +23,8 @@ printf '%s\n' "${TEST_PUT_RESULT:-ok}" SH cat >"$test_dir/bin/omarchy-restart-shell" <<'SH' #!/bin/bash -printf 'restart\n' >>"$CALL_LOG" +echo 'migration must leave the restart to omarchy update' >&2 +exit 1 SH chmod +x "$test_dir/bin/"* @@ -46,9 +47,9 @@ run_migration [[ $(readlink "$ROOT/config/omarchy/plugins/omacom.elsewhen") == "$(readlink "$plugin")" ]] || fail "fresh installs use the same package link" pass "migration and fresh installs link to the package" -expected=$'package elsewhen\nshell rescanPlugins\nshell putBarWidget omacom.elsewhen {"before":"omarchy.clock"}\nrestart' -[[ $(cat "$CALL_LOG") == "$expected" ]] || fail "install, scan, placement and restart run in order" "$(cat "$CALL_LOG")" -pass "real bar helper enables and places before the clock, then restarts" +expected=$'package elsewhen\nshell rescanPlugins\nshell putBarWidget omacom.elsewhen {"before":"omarchy.clock"}' +[[ $(cat "$CALL_LOG") == "$expected" ]] || fail "install, scan and placement run in order" "$(cat "$CALL_LOG")" +pass "real bar helper enables and places before the clock without restarting during reload" run_migration [[ $(cat "$CALL_LOG") == "$expected" ]] || fail "migration can be rerun" From e38c1d1289252d2adb96372eeac48d02e489c5b7 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sat, 19 Sep 2026 21:53:09 +0200 Subject: [PATCH 106/194] Ignore claude --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index 8de9215b5a47..1de1faa693b8 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,5 @@ # Python bytecode (orchestrator) __pycache__/ *.pyc + +.claude/ From e265934bb16c76cb47144d4625d19626b1ab36f6 Mon Sep 17 00:00:00 2001 From: Ryan Hughes Date: Mon, 31 Aug 2026 15:43:14 -0400 Subject: [PATCH 107/194] Use Omasnap for screenshots --- agents/skills/visual-verification.md | 5 +- bin/omarchy-capture-screenshot | 81 +++--------------- bin/omarchy-clipboard-open | 2 +- config/imv/config | 4 +- default/agents/skills/omarchy/capture.md | 6 +- default/hypr/apps/screenshot-selection.lua | 5 +- default/hypr/apps/system.lua | 2 - default/uwsm/default | 4 +- docs/file-layout.md | 1 - install/omarchy-base.packages | 2 +- manual/12-screenshots-recording.md | 21 +++-- manual/14-omarchy-cli.md | 2 +- manual/46-faq.md | 6 +- migrations/1788129995.sh | 13 +++ shell/Commons/Util.qml | 2 +- test/shell.d/clipboard-test.sh | 12 +-- test/shell.d/omasnap-test.sh | 99 ++++++++++++++++++++++ test/shell.d/screenshot-sanity-test.sh | 20 ++--- 18 files changed, 169 insertions(+), 118 deletions(-) create mode 100644 migrations/1788129995.sh create mode 100644 test/shell.d/omasnap-test.sh diff --git a/agents/skills/visual-verification.md b/agents/skills/visual-verification.md index 56dc8e7841b1..7df6caa1c997 100644 --- a/agents/skills/visual-verification.md +++ b/agents/skills/visual-verification.md @@ -15,10 +15,7 @@ Take a full-screen screenshot without opening the editor: omarchy capture screenshot fullscreen save ``` -The command prints the saved path and writes to the configured Pictures -directory. Use `omarchy screenshot` for the interactive smart-region flow. -Capture reference and candidate states as separate images when changing a -layer-shell surface or layout, then compare both. +The command writes to Omasnap's configured screenshot directory. Use `omarchy screenshot` for the interactive editor flow. Capture reference and candidate states as separate images when changing a layer-shell surface or layout, then compare both. Record a short full-screen video for animation, transition, timing, capture, or screen-recording changes: diff --git a/bin/omarchy-capture-screenshot b/bin/omarchy-capture-screenshot index 6f7b91bf537d..ec383fcd5994 100755 --- a/bin/omarchy-capture-screenshot +++ b/bin/omarchy-capture-screenshot @@ -2,81 +2,22 @@ # omarchy:summary=Take a screenshot # omarchy:group=capture -# omarchy:args=[smart|region|windows|fullscreen] [slurp|copy|save] [--editor=] +# omarchy:args=[smart|region|windows|fullscreen|scroll] [copy|save] # omarchy:examples=omarchy screenshot | omarchy capture screenshot region # omarchy:aliases=omarchy screenshot -[[ -f ~/.config/user-dirs.dirs ]] && source ~/.config/user-dirs.dirs -OUTPUT_DIR="${OMARCHY_SCREENSHOT_DIR:-${XDG_PICTURES_DIR:-$HOME/Pictures}}" - -if [[ ! -d $OUTPUT_DIR ]]; then - mkdir -p "$OUTPUT_DIR" - omarchy-notification-send "Created screenshot directory: $OUTPUT_DIR" -t 2000 +if [[ -n ${OMARCHY_SCREENSHOT_DIR:-} && -z ${OMASNAP_SCREENSHOT_DIR:-} ]]; then + export OMASNAP_SCREENSHOT_DIR="$OMARCHY_SCREENSHOT_DIR" fi -pkill slurp && exit 0 - -SCREENSHOT_EDITOR="${OMARCHY_SCREENSHOT_EDITOR:-tensaku-edit}" - -# Parse --editor flag from any position -ARGS=() +omasnap_args=() for arg in "$@"; do - if [[ $arg == --editor=* ]]; then - SCREENSHOT_EDITOR="${arg#--editor=}" - else - ARGS+=("$arg") - fi + case "$arg" in + copy) omasnap_args+=(--copy) ;; + save) omasnap_args+=(--save) ;; + slurp) ;; + *) omasnap_args+=("$arg") ;; + esac done -set -- "${ARGS[@]}" - -MODE="${1:-smart}" -PROCESSING="${2:-slurp}" - -# The picker leaves the screen freeze running (PID on its first output line) -# so grim captures the frozen overlay rather than live content shifting -# during teardown. -# -# Software-composited cursors (Hyprland's fallback on GPUs without working -# hardware cursors) are baked into the frames grim captures, so force -# hardware cursors until after grim runs and restore the setting on exit. -NO_HW_CURSORS=$(hyprctl getoption cursor:no_hardware_cursors -j | jq '.int') - -set_no_hw_cursors() { - hyprctl eval "hl.config({ cursor = { no_hardware_cursors = $1 } })" &>/dev/null || - hyprctl keyword cursor:no_hardware_cursors "$1" &>/dev/null -} - -cleanup() { - [[ -n $FREEZE_PID ]] && kill $FREEZE_PID 2>/dev/null - set_no_hw_cursors "$NO_HW_CURSORS" -} -trap cleanup EXIT - -set_no_hw_cursors 0 -{ read -r FREEZE_PID; read -r SELECTION; } < <(omarchy-capture-region "$MODE" --keep-freeze) - -[[ -z $SELECTION ]] && exit 0 - -FILENAME="screenshot-$(date +'%Y-%m-%d_%H-%M-%S').png" -FILEPATH="$OUTPUT_DIR/$FILENAME" - -case "$PROCESSING" in - slurp) - grim -g "$SELECTION" "$FILEPATH" || exit 1 - echo "$FILEPATH" - wl-copy --type image/png <"$FILEPATH" - # Best-effort: the screenshot is already saved and on the clipboard, so a - # notification outage must not report the capture itself as failed. - omarchy-notification-send "Screenshot saved to clipboard and file" "Edit with Super + Alt + , (or click this)" \ - --image "$FILEPATH" \ - --exec "$SCREENSHOT_EDITOR" "$FILEPATH" || true - ;; - copy) - grim -g "$SELECTION" - | wl-copy --type image/png - ;; - save) - grim -g "$SELECTION" "$FILEPATH" || exit 1 - echo "$FILEPATH" - ;; -esac +exec omasnap "${omasnap_args[@]}" diff --git a/bin/omarchy-clipboard-open b/bin/omarchy-clipboard-open index 98f26bb2babb..827fe263376e 100755 --- a/bin/omarchy-clipboard-open +++ b/bin/omarchy-clipboard-open @@ -30,7 +30,7 @@ open_image() { local path="$1" [[ -r $path ]] || exit 1 - exec tensaku-edit "$path" + exec omasnap "$path" } open_text() { diff --git a/config/imv/config b/config/imv/config index f96aa6a397f0..5de2530e1f4f 100644 --- a/config/imv/config +++ b/config/imv/config @@ -12,5 +12,5 @@ # Rotate the currently open image by 90 degrees = exec mogrify -rotate 90 "$imv_current_file" -# Edit the current image in Tensaku and quit the viewer - = exec tensaku-edit "$imv_current_file" & ; quit +# Edit the current image in Omasnap and quit the viewer + = exec omasnap "$imv_current_file" & ; quit diff --git a/default/agents/skills/omarchy/capture.md b/default/agents/skills/omarchy/capture.md index 621bc2989f61..4390fe75a373 100644 --- a/default/agents/skills/omarchy/capture.md +++ b/default/agents/skills/omarchy/capture.md @@ -10,12 +10,10 @@ omarchy screenshot # Interactive smart-region flow omarchy capture screenshot region # Select a region omarchy capture screenshot windows # Pick a window omarchy capture screenshot fullscreen save # Full screen, straight to disk (no editor) +omarchy capture screenshot scroll # Capture and stitch a scrolling region ``` -The first argument picks the mode (`smart|region|windows|fullscreen`), the -second what happens with it (`slurp|copy|save`). `save` skips the annotation -editor and prints the saved path. Screenshots land in the configured Pictures -directory (override with `OMARCHY_SCREENSHOT_DIR`). +The first argument picks the Omasnap mode (`smart|region|windows|fullscreen|scroll`). With no second argument, the selection opens in Omasnap's annotation editor; `copy` or `save` skips the editor and sends the screenshot straight to that destination. Screenshots land in `~/Pictures/Screenshots` by default (override with `OMASNAP_SCREENSHOT_DIR`; the legacy `OMARCHY_SCREENSHOT_DIR` is also honored by the Omarchy command). ## Screen Recording diff --git a/default/hypr/apps/screenshot-selection.lua b/default/hypr/apps/screenshot-selection.lua index f4e3b2fdeaa3..4c93f703ef58 100644 --- a/default/hypr/apps/screenshot-selection.lua +++ b/default/hypr/apps/screenshot-selection.lua @@ -1,2 +1,5 @@ --- Remove the 1px border around the slurp region selection used by screenshots. +-- Remove the 1px border around the slurp region selection used by recordings, OCR, and QR capture. hl.layer_rule({ match = { namespace = "selection" }, no_anim = true, animation = "none" }) + +-- Keep the Omasnap overlay immediate and out of screen shares. +hl.layer_rule({ match = { namespace = "^omasnap$" }, no_anim = true, animation = "none", no_screen_share = true }) diff --git a/default/hypr/apps/system.lua b/default/hypr/apps/system.lua index 789e3e03e514..3235e7b96e5d 100644 --- a/default/hypr/apps/system.lua +++ b/default/hypr/apps/system.lua @@ -27,8 +27,6 @@ o.window("org.omarchy.about", { float = true }) o.window("org.omarchy.about", { center = true }) o.window("org.omarchy.about", { size = { 920, 480 } }) -o.window("dev.tensaku.Tensaku", { float = true }) -o.window("dev.tensaku.Tensaku", { center = true }) o.window("omacalc", { float = true }) -- Fullscreen screensaver. diff --git a/default/uwsm/default b/default/uwsm/default index d2ad7cc30db1..ba98b166c91e 100644 --- a/default/uwsm/default +++ b/default/uwsm/default @@ -10,8 +10,8 @@ export TERMINAL=xdg-terminal-exec # Used by terminal programs to open files with the selected Omarchy default editor export EDITOR="omarchy-launch-editor --inline" -# Use a custom directory for screenshots (remember to make the directory!) -# export OMARCHY_SCREENSHOT_DIR="$HOME/Pictures/Screenshots" +# Use a custom directory for screenshots +# export OMASNAP_SCREENSHOT_DIR="$HOME/Pictures/Screenshots" # Use a custom directory for screenrecordings (remember to make the directory!) # export OMARCHY_SCREENRECORD_DIR="$HOME/Videos/Screencasts" diff --git a/docs/file-layout.md b/docs/file-layout.md index f261085f0eae..73c48c4f340a 100644 --- a/docs/file-layout.md +++ b/docs/file-layout.md @@ -116,7 +116,6 @@ default/** ──► omarchy-settings /usr/share/omarchy ├─ hypr/toggles/*.lua (flags, │ single-window-aspect-ratio, window-no-gaps) /etc/skel/.local/state/omarchy/toggles/hypr/ ├─ nautilus-python/extensions/*.py /etc/skel/.local/share/nautilus-python/extensions/ - ├─ tensaku/state.toml /etc/skel/.local/state/tensaku/state.toml ├─ uwsm/env.d/10-omarchy /usr/share/uwsm/env.d/ ├─ environment.d/*.conf /usr/lib/environment.d/ ├─ fontconfig/conf.avail/50-omarchy.conf /usr/share/fontconfig/conf.avail/ diff --git a/install/omarchy-base.packages b/install/omarchy-base.packages index 0a8e27cca73a..b3df3e2050bb 100644 --- a/install/omarchy-base.packages +++ b/install/omarchy-base.packages @@ -96,6 +96,7 @@ omacalc omacut omawrite omarchy-nvim +omasnap pacman-contrib pamixer pinta @@ -114,7 +115,6 @@ qt6-multimedia-ffmpeg quickshell ripgrep ruby -tensaku sddm slurp socat diff --git a/manual/12-screenshots-recording.md b/manual/12-screenshots-recording.md index 9c476231d5ea..b3447b57db9f 100644 --- a/manual/12-screenshots-recording.md +++ b/manual/12-screenshots-recording.md @@ -13,13 +13,13 @@ Everything you can grab off the screen hangs off the Print Screen key. One key o ## Screenshots -Hit `Print Screen` and the screen freezes so nothing shifts under you while you aim. Drag a box for a freeform region, or just click once and the shot snaps to whatever rectangle you clicked in — a window if you landed on one, the whole monitor if you landed on the bar or in a gap. Changed your mind? Hit `Print Screen` again to dismiss the picker. +Hit `Print Screen` and Omasnap captures the focused monitor before its overlay appears, so nothing shifts under you while you aim. Drag a freeform region, or use the tabs across the top to switch between Region, Scrolling Region, Window, and Fullscreen capture. Changed your mind? Hit `Print Screen` again to dismiss Omasnap. -The result goes two places at once: a PNG in your pictures directory, and the clipboard, so you can paste it straight into a chat window with `Super + V`. A notification pops up with a thumbnail. Click it (or hit `Super + Alt + ,` to invoke the last notification) and the shot opens in Tensaku, the annotation editor, where you can draw arrows and boxes on it before you send it. +After you select an area, Omasnap opens its annotation editor. It can draw arrows, lines, shapes, highlights, numbered markers, text, and secure redactions; crop or cut out part of the image; OCR its text; and add a backdrop. Press `Enter` to copy and save the finished PNG, `Ctrl + C` to copy it without saving, `Ctrl + S` to save it without copying, or `P` to pin it above your windows. -Files land in `~/Pictures` by default, named `screenshot-2026-08-13_14-22-05.png`. If you'd rather keep them in their own folder, set `OMARCHY_SCREENSHOT_DIR` — see [the FAQ](46-faq.md) for where to put session environment variables. Omarchy creates the directory for you if it isn't there. You can swap the editor too with `OMARCHY_SCREENSHOT_EDITOR`. +Files land in `~/Pictures/Screenshots` by default, with a name such as `screenshot-2026-08-13_14-22-05-firefox.png`. Set `OMASNAP_SCREENSHOT_DIR` to use another directory — see [the FAQ](46-faq.md) for where to put session environment variables. Omasnap creates the directory when it saves the first shot. -From the terminal, `omarchy screenshot` takes the same shot, and you can be explicit about it: `omarchy capture screenshot region` for freeform only, `windows` to snap to window and monitor rectangles, or `fullscreen` to skip the picker entirely and grab the focused monitor. A second argument of `copy` puts the shot only on the clipboard, and `save` only on disk. +From the terminal, `omarchy screenshot` opens the same overlay, and you can choose its starting mode: `omarchy capture screenshot region`, `windows`, `fullscreen`, or `scroll`. A second argument of `copy` or `save` bypasses the annotation editor and sends the shot straight to that destination. ### Driving the picker from the keyboard @@ -27,16 +27,19 @@ While the selection is up, you don't have to use the mouse at all: | Key | Function | | --- | -------- | +| `Space` | Step through Region, Scrolling Region, and Window modes | +| `S` | Toggle scrolling-region mode | +| `Super + Arrow keys` | Move among windows in Window mode | | `Return` | Capture the highlighted window | -| `Ctrl + Return` | Capture the whole screen | -| `Tab` / `Ctrl + Tab` | Highlight the next / previous window | -| Arrow keys | Highlight the window in that direction | +| `Ctrl + A` | Capture the full focused monitor | +| `R` | Restore the last region drawn in this session | +| `Esc` | Dismiss Omasnap | -The arrows and Tab move the cursor to the window they pick, so the highlight follows along and you can see what you're about to capture. These bindings only exist while a selection is on screen, so they can't collide with anything in your own config. +These bindings only exist while Omasnap is open, so they can't collide with anything in your own config. ## Screen recording -`Alt + Print Screen` opens _Trigger > Capture > Screenrecord_, which asks what you want on the soundtrack: no audio, desktop audio, desktop plus microphone, or desktop plus microphone plus webcam. That last one only shows up if you actually have a camera plugged in. Pick one and you get the same picker as a screenshot: drag a region, or click a window or monitor. +`Alt + Print Screen` opens _Trigger > Capture > Screenrecord_, which asks what you want on the soundtrack: no audio, desktop audio, desktop plus microphone, or desktop plus microphone plus webcam. That last one only shows up if you actually have a camera plugged in. Pick one and Omarchy's recording picker lets you drag a region or click a window or monitor. Recording runs on gpu-screen-recorder, which encodes on the GPU at 60fps and falls back to the CPU if it has to. The result is an MP4 in `~/Videos`, named `screenrecording-2026-08-13_14-22-05.mp4`. Set `OMARCHY_SCREENRECORD_DIR` to change that — but note that unlike the screenshot directory, this one has to exist already, or the recording refuses to start. diff --git a/manual/14-omarchy-cli.md b/manual/14-omarchy-cli.md index fa5d0a05b70d..76f386e82073 100644 --- a/manual/14-omarchy-cli.md +++ b/manual/14-omarchy-cli.md @@ -50,7 +50,7 @@ Capture commands — Screenshots and screen recording: omarchy capture qr Decode a QR code from a screenshot region omarchy capture screenrecording [--fullscreen] [--with-desktop-audio] [--with-microphone-audio] [--with-webcam] [--webcam-device=] [--webcam-size=] [--resolution=] [--stop-recording] Start or stop screen recording omarchy capture screenrecording with webcam Pick a webcam and start a screen recording with it - omarchy capture screenshot [smart|region|windows|fullscreen] [slurp|copy|save] [--editor=] Take a screenshot + omarchy capture screenshot [smart|region|windows|fullscreen|scroll] [copy|save] Take a screenshot omarchy capture text Extract text from a screenshot region with OCR omarchy capture webcam resize Resize the active webcam recording overlay ``` diff --git a/manual/46-faq.md b/manual/46-faq.md index 21b11db94136..8985439bafff 100644 --- a/manual/46-faq.md +++ b/manual/46-faq.md @@ -54,15 +54,15 @@ Automatic discovery, where printers on the network appear without being added, i ### How do I change where screenshots or screenrecordings are saved? -If you want screenshots to be saved to `~/Pictures/Screenshots` instead of just `~/Pictures`, you can add this to a file under `~/.config/uwsm/env.d/` (like `~/.config/uwsm/env.d/capture`): +Omasnap saves screenshots to `~/Pictures/Screenshots` by default. To use another directory, add this to a file under `~/.config/uwsm/env.d/` (like `~/.config/uwsm/env.d/capture`): ``` -export OMARCHY_SCREENSHOT_DIR="$HOME/Pictures/Screenshots" +export OMASNAP_SCREENSHOT_DIR="$HOME/Pictures/Captures" ``` You can do the same for screenrecordings using `OMARCHY_SCREENRECORD_DIR`. -Just remember to create the directory you want to save to and restart Omarchy for this to take effect. +Omasnap creates its screenshot directory automatically. Create the screenrecording directory yourself, then restart Omarchy for either environment change to take effect. ### How do I get the speakers + webcam working on my Apple Studio Display? diff --git a/migrations/1788129995.sh b/migrations/1788129995.sh new file mode 100644 index 000000000000..041a3ef86840 --- /dev/null +++ b/migrations/1788129995.sh @@ -0,0 +1,13 @@ +echo "Replace Tensaku with Omasnap" + +omarchy-pkg-add omasnap + +imv_config="$HOME/.config/imv/config" +if [[ -f $imv_config ]]; then + sed -i --follow-symlinks \ + -e 's/^# Edit the current image in Tensaku and quit the viewer$/# Edit the current image in Omasnap and quit the viewer/' \ + -e 's|^ = exec tensaku-edit "$imv_current_file" & ; quit$| = exec omasnap "$imv_current_file" \& ; quit|' \ + "$imv_config" +fi + +omarchy-pkg-drop tensaku diff --git a/shell/Commons/Util.qml b/shell/Commons/Util.qml index 14af44fed9ec..cacc98d25517 100644 --- a/shell/Commons/Util.qml +++ b/shell/Commons/Util.qml @@ -61,7 +61,7 @@ QtObject { // Run an argv vector without a shell interpreting it: the constant `exec "$@"` // means the args only ever land in positional parameters, which bash expands // without re-tokenizing — so untrusted data ($(id), a filename) stays literal. - // The login shell (-l) keeps the PATH/session env GUI targets (tensaku, mpv, + // The login shell (-l) keeps the PATH/session env GUI targets (omasnap, mpv, // xdg-open) need. Prefer this over execDetached for anything built from input. function execArgv(argv) { Quickshell.execDetached(["bash", "-lc", 'exec "$@"', "bash"].concat(argv)) diff --git a/test/shell.d/clipboard-test.sh b/test/shell.d/clipboard-test.sh index 962d529e0f4a..5580a694114a 100644 --- a/test/shell.d/clipboard-test.sh +++ b/test/shell.d/clipboard-test.sh @@ -277,12 +277,12 @@ printf '%s\n' "$1" >"$EDITOR_PATH_OUT" cat "$1" >"$EDITOR_TEXT_OUT" SH -cat >"$TMPDIR/bin/tensaku-edit" <<'SH' +cat >"$TMPDIR/bin/omasnap" <<'SH' #!/bin/bash -printf '%s\n' "$*" >"$TENSAKU_OUT" +printf '%s\n' "$*" >"$OMASNAP_OUT" SH -chmod +x "$TMPDIR/bin/wl-copy" "$TMPDIR/bin/wl-paste" "$TMPDIR/bin/wtype" "$TMPDIR/bin/omarchy-launch-browser" "$TMPDIR/bin/omarchy-launch-editor" "$TMPDIR/bin/tensaku-edit" +chmod +x "$TMPDIR/bin/wl-copy" "$TMPDIR/bin/wl-paste" "$TMPDIR/bin/wtype" "$TMPDIR/bin/omarchy-launch-browser" "$TMPDIR/bin/omarchy-launch-editor" "$TMPDIR/bin/omasnap" capture_output=$(XDG_RUNTIME_DIR="$TMPDIR" XDG_STATE_HOME="$TMPDIR/state" PATH="$TMPDIR/bin:$PATH" "$ROOT/shell/plugins/clipboard/capture.sh") [[ $capture_output == '{"type":"text","text":"terminal copy"}' ]] || fail "clipboard capture records normal text events" @@ -513,8 +513,8 @@ pass "clipboard open helper opens text entries in editor" [[ $(<"$TMPDIR/editor-path") == "$TMPDIR"/state/omarchy/clipboard-open/clipboard.*.txt ]] || fail "clipboard open helper writes text entries to a temporary file" pass "clipboard open helper writes text entries to a temporary file" -TENSAKU_OUT="$TMPDIR/tensaku" HOME="$TMPDIR/home" PATH="$TMPDIR/bin:$PATH" \ +OMASNAP_OUT="$TMPDIR/omasnap" HOME="$TMPDIR/home" PATH="$TMPDIR/bin:$PATH" \ "$ROOT/bin/omarchy-clipboard-open" --history-index 2 -[[ $(<"$TMPDIR/tensaku") == "$TMPDIR/image.png" ]] || fail "clipboard open helper opens image entries in Tensaku" -pass "clipboard open helper opens image entries in Tensaku" +[[ $(<"$TMPDIR/omasnap") == "$TMPDIR/image.png" ]] || fail "clipboard open helper opens image entries in Omasnap" +pass "clipboard open helper opens image entries in Omasnap" diff --git a/test/shell.d/omasnap-test.sh b/test/shell.d/omasnap-test.sh new file mode 100644 index 000000000000..342e5f8fc0e4 --- /dev/null +++ b/test/shell.d/omasnap-test.sh @@ -0,0 +1,99 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +packages="$ROOT/install/omarchy-base.packages" +migration="$ROOT/migrations/1788129995.sh" + +grep -qxF omasnap "$packages" || fail "fresh installs include Omasnap" +! grep -qxF tensaku "$packages" || fail "fresh installs no longer include Tensaku" +pass "fresh installs use Omasnap as the screenshot editor" + +grep -Fq 'namespace = "^omasnap$"' "$ROOT/default/hypr/apps/screenshot-selection.lua" || + fail "Omasnap has a layer rule" +grep -Fq 'no_screen_share = true' "$ROOT/default/hypr/apps/screenshot-selection.lua" || + fail "the Omasnap overlay is excluded from screen sharing" +! grep -Fq 'dev.tensaku.Tensaku' "$ROOT/default/hypr/apps/system.lua" || + fail "the removed Tensaku window rules are gone" +pass "Hyprland applies Omasnap's overlay policy without stale Tensaku rules" + +test_tmp=$(mktemp -d) +trap 'rm -rf "$test_tmp"' EXIT + +stub_bin="$test_tmp/bin" +mkdir -p "$stub_bin" + +cat >"$stub_bin/omasnap" <<'SH' +#!/bin/bash +printf '%s\t%s\n' "${OMASNAP_SCREENSHOT_DIR:-}" "$*" >>"$OMASNAP_TEST_LOG" +SH +chmod +x "$stub_bin/omasnap" + +capture_log="$test_tmp/capture.log" +OMASNAP_TEST_LOG="$capture_log" PATH="$stub_bin:$PATH" \ + "$ROOT/bin/omarchy-capture-screenshot" +[[ $(<"$capture_log") == $'\t' ]] || fail "the default screenshot opens Omasnap without extra arguments" + +: >"$capture_log" +OMASNAP_TEST_LOG="$capture_log" OMARCHY_SCREENSHOT_DIR="$test_tmp/legacy-output" PATH="$stub_bin:$PATH" \ + "$ROOT/bin/omarchy-capture-screenshot" windows copy +[[ $(<"$capture_log") == "$test_tmp/legacy-output"$'\twindows --copy' ]] || + fail "the screenshot command maps the legacy directory and copy argument to Omasnap" + +: >"$capture_log" +OMASNAP_TEST_LOG="$capture_log" OMARCHY_SCREENSHOT_DIR="$test_tmp/legacy-output" OMASNAP_SCREENSHOT_DIR="$test_tmp/native-output" PATH="$stub_bin:$PATH" \ + "$ROOT/bin/omarchy-capture-screenshot" fullscreen save +[[ $(<"$capture_log") == "$test_tmp/native-output"$'\tfullscreen --save' ]] || + fail "the native Omasnap directory wins while legacy save syntax still works" + +: >"$capture_log" +OMASNAP_TEST_LOG="$capture_log" PATH="$stub_bin:$PATH" \ + "$ROOT/bin/omarchy-capture-screenshot" region slurp +[[ $(<"$capture_log") == $'\tregion' ]] || fail "the former default slurp argument remains a harmless compatibility no-op" + +: >"$capture_log" +OMASNAP_TEST_LOG="$capture_log" PATH="$stub_bin:$PATH" \ + "$ROOT/bin/omarchy-capture-screenshot" scroll --save +[[ $(<"$capture_log") == $'\tscroll --save' ]] || fail "native Omasnap modes and flags pass through unchanged" + +pass "the Omarchy screenshot route delegates compatible arguments to Omasnap" + +cat >"$stub_bin/omarchy-pkg-add" <<'SH' +#!/bin/bash +printf 'add\t%s\n' "$*" >>"$OMASNAP_MIGRATION_LOG" +SH +cat >"$stub_bin/omarchy-pkg-drop" <<'SH' +#!/bin/bash +printf 'drop\t%s\n' "$*" >>"$OMASNAP_MIGRATION_LOG" +SH +chmod +x "$stub_bin/omarchy-pkg-add" "$stub_bin/omarchy-pkg-drop" + +migration_home="$test_tmp/home" +mkdir -p "$migration_home/.config/imv" "$migration_home/dotfiles" +cat >"$migration_home/dotfiles/imv.config" <<'EOF' +[binds] + +# Edit the current image in Tensaku and quit the viewer + = exec tensaku-edit "$imv_current_file" & ; quit + = exec custom-editor "$imv_current_file" & ; quit +EOF +ln -s "$migration_home/dotfiles/imv.config" "$migration_home/.config/imv/config" + +migration_log="$test_tmp/migration.log" +OMASNAP_MIGRATION_LOG="$migration_log" HOME="$migration_home" PATH="$stub_bin:$PATH" \ + bash -euo pipefail "$migration" >/dev/null + +[[ $(sed -n '1p' "$migration_log") == $'add\tomasnap' ]] || fail "the migration installs Omasnap first" +[[ $(sed -n '2p' "$migration_log") == $'drop\ttensaku' ]] || fail "the migration removes Tensaku after Omasnap is ready" +grep -Fq '# Edit the current image in Omasnap and quit the viewer' "$migration_home/.config/imv/config" || + fail "the migration updates the stock imv editor comment" +grep -Fq ' = exec omasnap "$imv_current_file" & ; quit' "$migration_home/.config/imv/config" || + fail "the migration sends the stock imv edit binding to Omasnap" +grep -Fq ' = exec custom-editor "$imv_current_file" & ; quit' "$migration_home/.config/imv/config" || + fail "the migration preserves custom imv bindings" +[[ -L $migration_home/.config/imv/config ]] || fail "the migration preserves a dotfile-managed imv symlink" +[[ $(stat -c '%a' "$migration") == 644 ]] || fail "the Omasnap migration has mode 0644" + +pass "the migration swaps packages and safely updates only the stock imv binding" diff --git a/test/shell.d/screenshot-sanity-test.sh b/test/shell.d/screenshot-sanity-test.sh index 636642edaef7..756ffc65b921 100755 --- a/test/shell.d/screenshot-sanity-test.sh +++ b/test/shell.d/screenshot-sanity-test.sh @@ -25,13 +25,13 @@ if ! command -v quickshell >/dev/null 2>&1; then exit 0 fi -if pgrep -x slurp >/dev/null 2>&1; then - pass "slurp is already running; skipping screenshot sanity test" +if pgrep -x omasnap >/dev/null 2>&1; then + pass "omasnap is already running; skipping screenshot sanity test" exit 0 fi require_command hyprctl -require_command grim +require_command omasnap require_command jq require_command python3 @@ -118,13 +118,13 @@ jq -e ' fail_with_log "screenshot test shell rendered visible bar widgets" } -screenshot=$( - OMARCHY_PATH="$test_root" \ - OMARCHY_SCREENSHOT_DIR="$screenshot_dir" \ - HOME="$test_home" \ - PATH="$stub_bin:$ROOT/bin:$PATH" \ - "$ROOT/bin/omarchy" capture screenshot fullscreen save 2>"$screenshot_err" | tail -n 1 -) +OMARCHY_PATH="$test_root" \ +OMASNAP_SCREENSHOT_DIR="$screenshot_dir" \ +HOME="$test_home" \ +PATH="$stub_bin:$ROOT/bin:$PATH" \ + "$ROOT/bin/omarchy" capture screenshot fullscreen save >/dev/null 2>"$screenshot_err" + +screenshot=$(find "$screenshot_dir" -maxdepth 1 -type f -name '*.png' -print -quit) [[ -n $screenshot && -f $screenshot ]] || fail_with_log "fullscreen screenshot was captured" From 45748a2812f42e32f915b053caf4074e150e2048 Mon Sep 17 00:00:00 2001 From: Ryan Hughes Date: Sun, 20 Sep 2026 14:25:34 -0400 Subject: [PATCH 108/194] Remove obsolete Elsewhen plugin symlink --- config/omarchy/plugins/omacom.elsewhen | 1 - docs/omarchy-shell.md | 2 +- migrations/1789581661.sh | 6 ------ test/shell.d/elsewhen-default-migration-test.sh | 14 +++++++------- 4 files changed, 8 insertions(+), 15 deletions(-) delete mode 120000 config/omarchy/plugins/omacom.elsewhen diff --git a/config/omarchy/plugins/omacom.elsewhen b/config/omarchy/plugins/omacom.elsewhen deleted file mode 120000 index 19840c51cbb9..000000000000 --- a/config/omarchy/plugins/omacom.elsewhen +++ /dev/null @@ -1 +0,0 @@ -/usr/share/omarchy/plugins/omacom.elsewhen \ No newline at end of file diff --git a/docs/omarchy-shell.md b/docs/omarchy-shell.md index d62661a79b9c..b0da00e4bd65 100644 --- a/docs/omarchy-shell.md +++ b/docs/omarchy-shell.md @@ -90,7 +90,7 @@ The lower-level IPC methods remain available through `omarchy-shell shell ...`. ## Elsewhen -Elsewhen (`omacom.elsewhen`) ships in the `elsewhen` package at `/usr/share/omarchy/plugins/omacom.elsewhen`. A symlink in `~/.config/omarchy/plugins/` makes it available to the shell. New installs place it immediately before the clock; the migration uses `omarchy bar put omacom.elsewhen --before omarchy.clock`, which preserves an existing placement and uses Elsewhen's normal right-side placement if the clock is absent. Existing plugin directories and symlinks are left intact. The normal update flow restarts the shell after migrations; the migration does not interrupt plugin loading with an immediate restart. +Elsewhen (`omacom.elsewhen`) ships in the `elsewhen` package at `/usr/share/omarchy/shell/plugins/omacom.elsewhen`, where the shell discovers it automatically. New installs place it immediately before the clock; the migration uses `omarchy bar put omacom.elsewhen --before omarchy.clock`, which preserves an existing placement and uses Elsewhen's normal right-side placement if the clock is absent. Existing plugin directories and symlinks are left intact. The normal update flow restarts the shell after migrations; the migration does not interrupt plugin loading with an immediate restart. ## IPC diff --git a/migrations/1789581661.sh b/migrations/1789581661.sh index 5c022e1c957f..7a84855003e6 100644 --- a/migrations/1789581661.sh +++ b/migrations/1789581661.sh @@ -2,11 +2,5 @@ echo "Install Elsewhen, the world clock plugin" omarchy-pkg-add elsewhen -plugin="$HOME/.config/omarchy/plugins/omacom.elsewhen" -mkdir -p "$(dirname "$plugin")" -if [[ ! -e $plugin && ! -L $plugin ]]; then - ln -s /usr/share/omarchy/plugins/omacom.elsewhen "$plugin" -fi - omarchy-shell shell rescanPlugins omarchy-bar put omacom.elsewhen --before omarchy.clock diff --git a/test/shell.d/elsewhen-default-migration-test.sh b/test/shell.d/elsewhen-default-migration-test.sh index c0a2de8ff1c8..585f65bac03b 100644 --- a/test/shell.d/elsewhen-default-migration-test.sh +++ b/test/shell.d/elsewhen-default-migration-test.sh @@ -40,12 +40,12 @@ if PACKAGE_STATUS=1 run_migration; then fi [[ ! -e $plugin && ! -L $plugin && $(cat "$CALL_LOG") == "package elsewhen" ]] || fail "package failure leaves the plugin and shell untouched" -pass "package failure stops before linking or changing the shell" +pass "package failure stops before changing the shell" run_migration -[[ $(readlink "$plugin") == /usr/share/omarchy/plugins/omacom.elsewhen ]] || fail "package link is installed" -[[ $(readlink "$ROOT/config/omarchy/plugins/omacom.elsewhen") == "$(readlink "$plugin")" ]] || fail "fresh installs use the same package link" -pass "migration and fresh installs link to the package" +[[ ! -e $plugin && ! -L $plugin ]] || fail "migration does not create a user plugin link" +[[ ! -e $ROOT/config/omarchy/plugins/omacom.elsewhen && ! -L $ROOT/config/omarchy/plugins/omacom.elsewhen ]] || fail "fresh installs do not ship a user plugin link" +pass "migration and fresh installs rely on the packaged plugin directory" expected=$'package elsewhen\nshell rescanPlugins\nshell putBarWidget omacom.elsewhen {"before":"omarchy.clock"}' [[ $(cat "$CALL_LOG") == "$expected" ]] || fail "install, scan and placement run in order" "$(cat "$CALL_LOG")" @@ -53,10 +53,10 @@ pass "real bar helper enables and places before the clock without restarting dur run_migration [[ $(cat "$CALL_LOG") == "$expected" ]] || fail "migration can be rerun" -pass "migration can be rerun with its package link present" +[[ ! -e $plugin && ! -L $plugin ]] || fail "rerunning the migration does not create a user plugin link" +pass "migration can be rerun without a user plugin link" -rm "$plugin" -mkdir "$plugin" +mkdir -p "$plugin" printf 'local work\n' >"$plugin/notes" run_migration [[ ! -L $plugin && $(cat "$plugin/notes") == "local work" ]] || fail "existing checkout is preserved" From b423f4993d68b0db70ae778f8cd4b3f516e3c500 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 20 Sep 2026 20:36:19 -0500 Subject: [PATCH 109/194] Complete OWE service setup and lock feed fallback --- install/omarchy-base.packages | 6 +- install/user/first-run/enable-user-units.sh | 3 + manual/39-backgrounds.md | 2 + migrations/1786609204.sh | 4 +- migrations/1789764927.sh | 17 ++++ shell/plugins/background/Background.qml | 7 +- shell/plugins/lock/LockFeedSurface.qml | 4 - shell/plugins/lock/LockView.qml | 37 ++++----- shell/plugins/lock/Service.qml | 29 +++++++ shell/plugins/lock/poster.sh | 24 ++++++ test/shell.d/fixtures/owe-lock/shell.qml | 69 ++++++++++++++++ test/shell.d/owe-integration-test.sh | 90 +++++++++++++++++++++ test/shell.d/owe-lock-test.sh | 30 +++++++ test/shell.d/video-background-test.sh | 10 +-- 14 files changed, 289 insertions(+), 43 deletions(-) create mode 100644 migrations/1789764927.sh create mode 100755 shell/plugins/lock/poster.sh create mode 100644 test/shell.d/fixtures/owe-lock/shell.qml create mode 100644 test/shell.d/owe-integration-test.sh create mode 100644 test/shell.d/owe-lock-test.sh diff --git a/install/omarchy-base.packages b/install/omarchy-base.packages index c292828fcfc9..e4dd69a2cf9c 100644 --- a/install/omarchy-base.packages +++ b/install/omarchy-base.packages @@ -95,6 +95,9 @@ omacalc omacut omawrite omarchy-nvim +# OWE owns desktop video backgrounds and feeds the lock screen its frames. +owe +owe-lockfeed pacman-contrib pamixer pinta @@ -107,9 +110,6 @@ python-poetry-core ttfx qemu-user-static-binfmt qrencode -# OWE owns desktop video backgrounds and feeds the lock screen its frames. -owe -owe-lockfeed qt6-imageformats quickshell ripgrep diff --git a/install/user/first-run/enable-user-units.sh b/install/user/first-run/enable-user-units.sh index 9865fc207e4c..e08885c9e0dc 100755 --- a/install/user/first-run/enable-user-units.sh +++ b/install/user/first-run/enable-user-units.sh @@ -14,8 +14,11 @@ set -euo pipefail systemctl --user daemon-reload systemctl --user enable --now \ bt-agent.service \ + owed.service \ omarchy-recover-internal-monitor.service \ omarchy-sleep-lock.service \ omarchy-migrate-notify.service \ omarchy-fcitx5.service \ omarchy-crash-watch.service + +omarchy-hook-install theme-set /usr/share/owe/10-owe-sync diff --git a/manual/39-backgrounds.md b/manual/39-backgrounds.md index f57d23d28168..3bc1f77bfb22 100644 --- a/manual/39-backgrounds.md +++ b/manual/39-backgrounds.md @@ -7,3 +7,5 @@ You can do this most easily by going to _Install > Style > Background_ in the Om Backgrounds can be videos as well as stills. Drop an `mp4`, `m4v`, `mov`, `webm`, `mkv`, or `avi` file in the same folder and it appears alongside the images. Videos are played by the OWE wallpaper engine. It decodes the video once for all monitors and plays its sound through the default audio output, and it stops playback whenever nothing can see it. The lock screen draws the same decode, muted, through OWE. A video wallpaper still costs far more power than a still one. You can find a huge collection of cool curated backgrounds on https://github.com/dharmx/walls. + +Video backgrounds keep a cached still on the lock screen while playback is paused or unavailable. Animated GIFs play on the desktop and show a still frame on the lock screen. diff --git a/migrations/1786609204.sh b/migrations/1786609204.sh index b7833092083e..ce1442ca0d93 100644 --- a/migrations/1786609204.sh +++ b/migrations/1786609204.sh @@ -1,3 +1 @@ -echo "Install native video wallpaper playback dependencies" - -omarchy-pkg-add qt6-multimedia qt6-multimedia-ffmpeg +echo "Native video dependencies are superseded by the OWE migration" diff --git a/migrations/1789764927.sh b/migrations/1789764927.sh new file mode 100644 index 000000000000..e2d1541e4fe4 --- /dev/null +++ b/migrations/1789764927.sh @@ -0,0 +1,17 @@ +echo "Enable OWE desktop video backgrounds and lock feed" + +omarchy-pkg-add owe owe-lockfeed +omarchy-hook-install theme-set /usr/share/owe/10-owe-sync + +systemctl --user daemon-reload >/dev/null 2>&1 || true +if ! systemctl --user enable owed.service; then + wants_dir="$HOME/.config/systemd/user/graphical-session.target.wants" + mkdir -p "$wants_dir" + ln -sfn /usr/lib/systemd/user/owed.service "$wants_dir/owed.service" +fi + +# A TTY update enables the next graphical login without starting a renderer +# against a missing Wayland session. A failed live start leaves this pending. +if [[ ${OMARCHY_UPGRADE_TO_QUATTRO_LIVE:-0} != 1 ]] && systemctl --user is-active --quiet graphical-session.target; then + systemctl --user start owed.service +fi diff --git a/shell/plugins/background/Background.qml b/shell/plugins/background/Background.qml index 8c113e4b0689..b3dd7dabc542 100644 --- a/shell/plugins/background/Background.qml +++ b/shell/plugins/background/Background.qml @@ -182,9 +182,7 @@ Item { } } - Component.onCompleted: { - refreshBackground() - } + Component.onCompleted: refreshBackground() Variants { model: Quickshell.screens @@ -205,8 +203,7 @@ Item { // Keep render updates enabled. The background layer has been observed to // lose its committed buffer while parked with updatesEnabled=false, // leaving a black desktop until omarchy-shell is restarted. A still - // wallpaper costs nothing to keep enabled, and a video one is throttled - // by pausing playback rather than by parking the layer. + // wallpaper costs nothing to keep enabled. OWE manages video layers. updatesEnabled: true property bool maskReady: false diff --git a/shell/plugins/lock/LockFeedSurface.qml b/shell/plugins/lock/LockFeedSurface.qml index 38bd46129114..ecd1f7d47fce 100644 --- a/shell/plugins/lock/LockFeedSurface.qml +++ b/shell/plugins/lock/LockFeedSurface.qml @@ -4,8 +4,4 @@ import Owe.LockFeed // Loaded through a Loader from LockView, so a system without the module shows // no lock video instead of losing the whole lock screen. LockFeed { - id: root - - property bool feedEnabled: true - active: root.feedEnabled } diff --git a/shell/plugins/lock/LockView.qml b/shell/plugins/lock/LockView.qml index 9366b28985a4..7084fb0fec9d 100644 --- a/shell/plugins/lock/LockView.qml +++ b/shell/plugins/lock/LockView.qml @@ -7,6 +7,7 @@ Item { id: root property string backgroundPath: "" + property string videoPosterPath: "" property int backgroundVersion: 0 property bool fingerprintConfigured: false property bool authenticatingPassword: false @@ -91,34 +92,15 @@ Item { BackgroundMedia { id: wallpaper + objectName: "lockWallpaper" anchors.fill: parent - path: root.video ? "" : root.backgroundPath + path: root.loadBackground ? (root.video ? root.videoPosterPath : root.backgroundPath) : "" version: root.backgroundVersion - visible: !root.video - } - - // OWE decodes the video once and feeds these frames to every lock surface. - // The feed pauses when this output blanks or on battery power saver. - Loader { - id: feedLoader - anchors.fill: parent - active: root.video - source: "LockFeedSurface.qml" - visible: status === Loader.Ready - - Binding { - target: feedLoader.item - property: "feedEnabled" - value: root.feedActive - when: feedLoader.item !== null - restoreMode: Binding.RestoreNone - } } MultiEffect { anchors.fill: wallpaper - source: root.video ? null : wallpaper - visible: !root.video + source: wallpaper autoPaddingEnabled: false blurEnabled: root.loadBackground && wallpaper.ready blur: 1.0 @@ -127,6 +109,17 @@ Item { contrast: -0.08 } + // The cached poster stays behind the feed when policy pauses playback, + // the module is unavailable, or a new connection has not received a frame. + Loader { + id: feedLoader + objectName: "lockFeedLoader" + anchors.fill: parent + active: root.feedActive + source: "LockFeedSurface.qml" + visible: status === Loader.Ready + } + // The feed item cannot be sampled by MultiEffect on every renderer. // Keep video wallpapers visible and darken them slightly for legibility. Rectangle { diff --git a/shell/plugins/lock/Service.qml b/shell/plugins/lock/Service.qml index 94d43b68ebd0..6e1f703eb396 100644 --- a/shell/plugins/lock/Service.qml +++ b/shell/plugins/lock/Service.qml @@ -28,6 +28,7 @@ Item { property string failureMessage: "" property int failedAttempts: 0 property string backgroundPath: "" + property string videoPosterPath: "" property int backgroundVersion: 0 property string lastEvent: "init" property string lastEventAt: "" @@ -113,6 +114,16 @@ Item { if (!readlinkProc.running) readlinkProc.running = true } + function refreshPoster() { + if (!root.videoBackground) { + root.videoPosterPath = "" + return + } + if (posterProc.running) return + posterProc.sourcePath = root.backgroundPath + posterProc.running = true + } + function refreshFingerprintStatus() { if (!fingerprintCheckProc.running) fingerprintCheckProc.running = true } @@ -307,6 +318,7 @@ Item { id: lockView anchors.fill: parent backgroundPath: root.backgroundPath + videoPosterPath: root.videoPosterPath backgroundVersion: root.backgroundVersion fingerprintConfigured: root.fingerprintConfigured authenticatingPassword: root.authenticatingPassword @@ -339,6 +351,7 @@ Item { LockView { anchors.fill: parent backgroundPath: root.backgroundPath + videoPosterPath: root.videoPosterPath backgroundVersion: root.backgroundVersion fingerprintConfigured: root.fingerprintConfigured authenticatingPassword: false @@ -409,9 +422,25 @@ Item { onStreamFinished: { var next = String(text || "").trim() if (next !== root.backgroundPath) { + root.videoPosterPath = "" root.backgroundPath = next root.backgroundVersion += 1 } + root.refreshPoster() + } + } + } + + Process { + id: posterProc + property string sourcePath: "" + command: ["bash", Quickshell.env("OMARCHY_PATH") + "/shell/plugins/lock/poster.sh", sourcePath] + stdout: StdioCollector { id: posterOutput; waitForEnd: true } + onExited: function(exitCode) { + if (sourcePath !== root.backgroundPath) { + root.refreshPoster() + } else { + root.videoPosterPath = exitCode === 0 ? String(posterOutput.text || "").trim() : "" } } } diff --git a/shell/plugins/lock/poster.sh b/shell/plugins/lock/poster.sh new file mode 100755 index 000000000000..836d01f06f09 --- /dev/null +++ b/shell/plugins/lock/poster.sh @@ -0,0 +1,24 @@ +#!/bin/bash + +# One cached frame shared by all lock outputs, including when OWE is paused. +set -euo pipefail + +source_path=$1 +cache_dir="${XDG_CACHE_HOME:-$HOME/.cache}/omarchy/lock-poster" +signature=$(stat -Lc '%s:%y:%z' "$source_path") +key=$(printf '%s\n%s' "$source_path" "$signature" | sha256sum | cut -d ' ' -f 1) +poster="$cache_dir/poster-$key.jpg" +mkdir -p "$cache_dir" +exec {lock_fd}>"$cache_dir/.lock" +flock -w 10 "$lock_fd" + +if [[ ! -s $poster ]]; then + temporary=$(mktemp "$cache_dir/.poster-XXXXXX.jpg") + trap 'rm -f "$temporary"' EXIT + timeout -k 1 5 ffmpegthumbnailer -i "$source_path" -o "$temporary" -s 1920 -q 8 {lock_fd}>&- + [[ -s $temporary ]] + mv -f "$temporary" "$poster" + find "$cache_dir" -maxdepth 1 -type f -name 'poster-*.jpg' ! -name "poster-$key.jpg" -delete +fi + +printf '%s\n' "$poster" diff --git a/test/shell.d/fixtures/owe-lock/shell.qml b/test/shell.d/fixtures/owe-lock/shell.qml new file mode 100644 index 000000000000..dc9f88fa8a15 --- /dev/null +++ b/test/shell.d/fixtures/owe-lock/shell.qml @@ -0,0 +1,69 @@ +import QtQuick +import Quickshell + +ShellRoot { + id: root + property var view + property var wallpaper + property var feed + property int step: 0 + + Item { id: host; width: 1000; height: 700 } + + function findItem(item, name) { + if (item.objectName === name) return item + for (var i = 0; i < item.children.length; i++) { + var found = findItem(item.children[i], name) + if (found) return found + } + return null + } + + function check(condition, message) { + if (!condition) throw new Error(message) + } + + Timer { + interval: 150 + repeat: true + running: true + onTriggered: { + try { + if (root.step === 0) { + var component = Qt.createComponent("file://" + Quickshell.env("OMARCHY_PATH") + "/shell/plugins/lock/LockView.qml") + check(component.status === Component.Ready, component.errorString()) + root.view = component.createObject(host, {width: 1000, height: 700, backgroundPath: "/still.png", loadBackground: false}) + check(root.view !== null, component.errorString()) + root.wallpaper = findItem(root.view, "lockWallpaper") + root.feed = findItem(root.view, "lockFeedLoader") + check(root.wallpaper.path === "", "hidden still must not decode") + root.view.backgroundPath = "/video.mp4" + root.view.videoPosterPath = "/poster.jpg" + } else if (root.step === 1) { + check(!root.feed.active && root.feed.item === null, "hidden video must not load a feed client") + root.view.loadBackground = true + root.view.powerSaverActive = true + } else if (root.step === 2) { + check(root.wallpaper.path === "/poster.jpg", "power saver keeps the video poster") + check(!root.feed.active, "power saver must not connect to the feed") + root.view.powerSaverActive = false + } else if (root.step === 3) { + check(root.feed.active, "visible video enables the isolated feed loader") + check(root.wallpaper.path === "/poster.jpg", "poster stays beneath the feed before its first frame") + root.view.displaysBlank = true + } else if (root.step === 4) { + check(!root.feed.active && root.feed.item === null, "blanking releases the feed client") + root.view.loadBackground = false + } else { + check(root.wallpaper.path === "", "unlock releases the poster image") + console.log("OWE_LOCK_TEST_PASS") + Qt.quit() + } + root.step++ + } catch (error) { + console.error("OWE_LOCK_TEST_FAIL: " + error) + Qt.quit() + } + } + } +} diff --git a/test/shell.d/owe-integration-test.sh b/test/shell.d/owe-integration-test.sh new file mode 100644 index 000000000000..cde79db26f95 --- /dev/null +++ b/test/shell.d/owe-integration-test.sh @@ -0,0 +1,90 @@ +#!/bin/bash +set -euo pipefail +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +mkdir -p "$work/bin" "$work/home" +export TEST_CALLS="$work/calls" +for command in omarchy-pkg-add omarchy-hook-install systemctl; do + cat >"$work/bin/$command" <<'SH' +#!/bin/bash +printf '%s %s\n' "${0##*/}" "$*" >>"$TEST_CALLS" +case "$*" in + '--user enable owed.service') [[ ${TEST_TTY:-0} == 0 ]] ;; + '--user is-active --quiet graphical-session.target') [[ ${TEST_TTY:-0} == 0 ]] ;; + '--user start owed.service') [[ ${TEST_START_FAIL:-0} == 0 ]] ;; + *) exit 0 ;; +esac +SH + chmod +x "$work/bin/$command" +done + +migration="$ROOT/migrations/1789764927.sh" +run_migration() { + HOME="$work/home" PATH="$work/bin:$PATH" bash -euo pipefail "$migration" +} +run_migration +run_migration +grep -Fx 'omarchy-pkg-add owe owe-lockfeed' "$TEST_CALLS" >/dev/null +grep -Fx 'omarchy-hook-install theme-set /usr/share/owe/10-owe-sync' "$TEST_CALLS" >/dev/null +grep -Fx 'systemctl --user start owed.service' "$TEST_CALLS" >/dev/null +pass "migration installs OWE, its theme refresh hook, and starts the graphical session service" + +: >"$TEST_CALLS" +TEST_TTY=1 run_migration +TEST_TTY=1 run_migration +[[ $(readlink "$work/home/.config/systemd/user/graphical-session.target.wants/owed.service") == /usr/lib/systemd/user/owed.service ]] +if grep -F 'systemctl --user start' "$TEST_CALLS" >/dev/null; then + fail "TTY migration must not start the renderer" +fi +pass "TTY migrations enable the next login without starting a renderer" + +: >"$TEST_CALLS" +OMARCHY_UPGRADE_TO_QUATTRO_LIVE=1 run_migration +if grep -F 'systemctl --user start' "$TEST_CALLS" >/dev/null; then + fail "Quattro upgrade must defer OWE until the new graphical session" +fi +pass "Quattro upgrade enables OWE without starting it in the old shell" + +if TEST_START_FAIL=1 run_migration; then + fail "a failed live service start leaves the migration pending" +fi +pass "a failed live service start fails the migration" + +: >"$TEST_CALLS" +HOME="$work/home" PATH="$work/bin:$PATH" bash "$ROOT/install/user/first-run/enable-user-units.sh" +grep -E '^systemctl --user enable --now .*owed.service' "$TEST_CALLS" >/dev/null +grep -Fx 'omarchy-hook-install theme-set /usr/share/owe/10-owe-sync' "$TEST_CALLS" >/dev/null +pass "fresh installs enable OWE and install the theme refresh hook" + +cat >"$work/bin/ffmpegthumbnailer" <<'SH' +#!/bin/bash +printf 'thumbnail\n' >>"$TEST_CALLS" +while (( $# )); do + case "$1" in + -o) output=$2; shift 2 ;; + *) shift ;; + esac +done +[[ ${TEST_POSTER_FAIL:-0} == 0 ]] || exit 1 +printf 'poster\n' >"$output" +SH +chmod +x "$work/bin/ffmpegthumbnailer" +source_path="$work/video with 'quotes'.mp4" +printf 'source\n' >"$source_path" +poster() { + PATH="$work/bin:$PATH" XDG_CACHE_HOME="$work/cache" bash "$ROOT/shell/plugins/lock/poster.sh" "$source_path" +} +: >"$TEST_CALLS" +first=$(poster) +[[ -s $first && $(poster) == "$first" ]] +[[ $(wc -l <"$TEST_CALLS") == 1 ]] +printf 'changed source\n' >>"$source_path" +second=$(poster) +[[ -s $second && $second != "$first" && ! -e $first ]] +pass "lock posters are cached, refreshed after source changes, and old frames are evicted" +printf 'broken source\n' >>"$source_path" +if TEST_POSTER_FAIL=1 poster; then fail "failed poster generation must fail"; fi +[[ -z $(find "$work/cache" -name '.poster-*.jpg' -print -quit) ]] +pass "failed poster generation never publishes a partial image" diff --git a/test/shell.d/owe-lock-test.sh b/test/shell.d/owe-lock-test.sh new file mode 100644 index 000000000000..4f3831c75448 --- /dev/null +++ b/test/shell.d/owe-lock-test.sh @@ -0,0 +1,30 @@ +#!/bin/bash +set -euo pipefail +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +if ! command -v quickshell >/dev/null 2>&1; then + pass "quickshell unavailable; skipping lock feed QML lifecycle" + exit 0 +fi +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +mkdir -p "$work/config" "$work/runtime" "$work/home" +chmod 700 "$work/runtime" +cp "$SHELL_TEST_DIR/fixtures/owe-lock/shell.qml" "$work/config/shell.qml" +ln -s "$ROOT/shell/Ui" "$work/config/Ui" +ln -s "$ROOT/shell/Commons" "$work/config/Commons" + +# Offscreen rendering exercises the real QML bindings without taking a lock +# or connecting to the user's compositor. +HOME="$work/home" XDG_RUNTIME_DIR="$work/runtime" \ + OMARCHY_PATH="$ROOT" QT_QPA_PLATFORM=offscreen QT_QPA_PLATFORMTHEME= \ + QT_STYLE_OVERRIDE= QT_QUICK_BACKEND=software \ + timeout 15 quickshell -p "$work/config" --no-color >"$work/log" 2>&1 || { + cat "$work/log" >&2 + fail "lock feed QML lifecycle runs" + } +if ! grep -q 'OWE_LOCK_TEST_PASS' "$work/log" || grep -q 'OWE_LOCK_TEST_FAIL' "$work/log"; then + cat "$work/log" >&2 + fail "lock feed respects visibility and keeps its poster fallback" +fi +pass "lock feed respects visibility, power saver and blanking; hidden views release images" diff --git a/test/shell.d/video-background-test.sh b/test/shell.d/video-background-test.sh index 31ac754d2dc3..761c97a9aed7 100755 --- a/test/shell.d/video-background-test.sh +++ b/test/shell.d/video-background-test.sh @@ -49,11 +49,9 @@ assert( assert( /^import Owe\.LockFeed$/m.test(lockFeedQml) && lockFeedQml.includes('LockFeed {') && - lockFeedQml.includes('active: root.feedEnabled') && lockQml.includes('source: "LockFeedSurface.qml"') && - lockQml.includes('active: root.video') && - /feedActive: root\.video && root\.loadBackground && !root\.displaysBlank && !root\.powerSaverActive/.test(lockQml) && - /property: "feedEnabled"[\s\S]*?value: root\.feedActive/.test(lockQml), + lockQml.includes('active: root.feedActive') && + /feedActive: root\.video && root\.loadBackground && !root\.displaysBlank && !root\.powerSaverActive/.test(lockQml), 'the lock screen shows video through the OWE lock feed, loaded so a missing module costs only the video' ) assert( @@ -61,8 +59,8 @@ assert( 'the lock view itself carries no foreign import, so the lock still loads without the feed module' ) assert( - lockQml.includes('path: root.video ? "" : root.backgroundPath') && - lockQml.includes('visible: !root.video') && + lockQml.includes('path: root.loadBackground ? (root.video ? root.videoPosterPath : root.backgroundPath) : ""') && + lockQml.indexOf('id: feedLoader') > lockQml.indexOf('MultiEffect {') && lockQml.includes('visible: root.video') && !lockQml.includes('wallpaper.video'), 'the lock screen keeps its image effect for stills and shows the feed for videos' From 0d5232ed7bed85b6c099b452602ebb5de192d43a Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 21 Sep 2026 03:38:10 +0200 Subject: [PATCH 110/194] Fix Elsewhen migration for dev checkouts --- migrations/1789581661.sh | 8 +++++++ .../elsewhen-default-migration-test.sh | 21 ++++++++++++++----- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/migrations/1789581661.sh b/migrations/1789581661.sh index 7a84855003e6..ad0dfd5ef838 100644 --- a/migrations/1789581661.sh +++ b/migrations/1789581661.sh @@ -2,5 +2,13 @@ echo "Install Elsewhen, the world clock plugin" omarchy-pkg-add elsewhen +# Dev checkouts do not contain plugins installed by system packages. +packaged_plugin="/usr/share/omarchy/shell/plugins/omacom.elsewhen" +user_plugin="$HOME/.config/omarchy/plugins/omacom.elsewhen" +if [[ ! $OMARCHY_PATH -ef /usr/share/omarchy && -d $packaged_plugin && ! -e $user_plugin && ! -L $user_plugin ]]; then + mkdir -p "${user_plugin%/*}" + ln -s "$packaged_plugin" "$user_plugin" +fi + omarchy-shell shell rescanPlugins omarchy-bar put omacom.elsewhen --before omarchy.clock diff --git a/test/shell.d/elsewhen-default-migration-test.sh b/test/shell.d/elsewhen-default-migration-test.sh index 585f65bac03b..0c2565f4f0b4 100644 --- a/test/shell.d/elsewhen-default-migration-test.sh +++ b/test/shell.d/elsewhen-default-migration-test.sh @@ -28,11 +28,14 @@ exit 1 SH chmod +x "$test_dir/bin/"* +mkdir -p "$test_dir/packaged/shell/plugins/omacom.elsewhen" +sed "s|/usr/share/omarchy|$test_dir/packaged|g" "$ROOT/migrations/1789581661.sh" >"$test_dir/migration.sh" + plugin="$test_dir/home/.config/omarchy/plugins/omacom.elsewhen" run_migration() { : >"$CALL_LOG" - HOME="$test_dir/home" OMARCHY_PATH="$ROOT" PATH="$test_dir/bin:$ROOT/bin:$PATH" \ - bash -euo pipefail "$ROOT/migrations/1789581661.sh" >"$test_dir/output" 2>&1 + HOME="$test_dir/home" OMARCHY_PATH="${1:-$test_dir/packaged}" PATH="$test_dir/bin:$ROOT/bin:$PATH" \ + bash -euo pipefail "$test_dir/migration.sh" >"$test_dir/output" 2>&1 } if PACKAGE_STATUS=1 run_migration; then @@ -56,22 +59,30 @@ run_migration [[ ! -e $plugin && ! -L $plugin ]] || fail "rerunning the migration does not create a user plugin link" pass "migration can be rerun without a user plugin link" +run_migration "$ROOT" +[[ $(readlink "$plugin") == "$test_dir/packaged/shell/plugins/omacom.elsewhen" ]] || fail "dev checkout links the packaged plugin" +pass "dev checkout discovers Elsewhen through a user plugin link" +run_migration "$ROOT" +[[ $(readlink "$plugin") == "$test_dir/packaged/shell/plugins/omacom.elsewhen" ]] || fail "dev link survives a rerun" +pass "dev link is idempotent" +rm "$plugin" + mkdir -p "$plugin" printf 'local work\n' >"$plugin/notes" -run_migration +run_migration "$ROOT" [[ ! -L $plugin && $(cat "$plugin/notes") == "local work" ]] || fail "existing checkout is preserved" pass "existing checkout and local files are preserved" rm "$plugin/notes" rmdir "$plugin" ln -s "$test_dir/custom-plugin" "$plugin" -run_migration +run_migration "$ROOT" [[ $(readlink "$plugin") == "$test_dir/custom-plugin" ]] || fail "existing symlink is preserved" pass "existing symlink is preserved, including a missing target" for failure in 'SCAN_STATUS=1' 'TEST_PUT_RESULT=unknown'; do if env "$failure" HOME="$test_dir/home" OMARCHY_PATH="$ROOT" PATH="$test_dir/bin:$ROOT/bin:$PATH" \ - bash -euo pipefail "$ROOT/migrations/1789581661.sh" >"$test_dir/output" 2>&1; then + bash -euo pipefail "$test_dir/migration.sh" >"$test_dir/output" 2>&1; then fail "$failure must leave the migration pending" fi pass "$failure leaves the migration pending" From c0ba99670d5cc3a52832e079053e59182c9b6acd Mon Sep 17 00:00:00 2001 From: Ryan Hughes Date: Mon, 21 Sep 2026 02:14:54 -0400 Subject: [PATCH 111/194] Clean up legacy screenshot tools in Omasnap migration --- migrations/1788129995.sh | 9 ++++-- test/shell.d/omasnap-test.sh | 63 +++++++++++++++++++++++++++++++++--- 2 files changed, 66 insertions(+), 6 deletions(-) diff --git a/migrations/1788129995.sh b/migrations/1788129995.sh index 041a3ef86840..965e01db56af 100644 --- a/migrations/1788129995.sh +++ b/migrations/1788129995.sh @@ -1,13 +1,18 @@ -echo "Replace Tensaku with Omasnap" +echo "Replace Satty and Tensaku with Omasnap" omarchy-pkg-add omasnap +# The old source installer left a NoDisplay entry that overrides the packaged launcher. +rm -f "$HOME/.local/share/applications/omasnap.desktop" + imv_config="$HOME/.config/imv/config" if [[ -f $imv_config ]]; then sed -i --follow-symlinks \ -e 's/^# Edit the current image in Tensaku and quit the viewer$/# Edit the current image in Omasnap and quit the viewer/' \ + -e 's/^# Edit the current image in Satty and quit the viewer$/# Edit the current image in Omasnap and quit the viewer/' \ -e 's|^ = exec tensaku-edit "$imv_current_file" & ; quit$| = exec omasnap "$imv_current_file" \& ; quit|' \ + -e 's|^ = exec satty --filename "$imv_current_file" & ; quit$| = exec omasnap "$imv_current_file" \& ; quit|' \ "$imv_config" fi -omarchy-pkg-drop tensaku +omarchy-pkg-drop satty tensaku diff --git a/test/shell.d/omasnap-test.sh b/test/shell.d/omasnap-test.sh index 342e5f8fc0e4..abf3293c01fc 100644 --- a/test/shell.d/omasnap-test.sh +++ b/test/shell.d/omasnap-test.sh @@ -9,7 +9,8 @@ migration="$ROOT/migrations/1788129995.sh" grep -qxF omasnap "$packages" || fail "fresh installs include Omasnap" ! grep -qxF tensaku "$packages" || fail "fresh installs no longer include Tensaku" -pass "fresh installs use Omasnap as the screenshot editor" +! grep -qxF satty "$packages" || fail "fresh installs no longer include Satty" +pass "fresh installs use Omasnap as the screenshot tool" grep -Fq 'namespace = "^omasnap$"' "$ROOT/default/hypr/apps/screenshot-selection.lua" || fail "Omasnap has a layer rule" @@ -63,6 +64,7 @@ pass "the Omarchy screenshot route delegates compatible arguments to Omasnap" cat >"$stub_bin/omarchy-pkg-add" <<'SH' #!/bin/bash printf 'add\t%s\n' "$*" >>"$OMASNAP_MIGRATION_LOG" +exit "${OMASNAP_PACKAGE_STATUS:-0}" SH cat >"$stub_bin/omarchy-pkg-drop" <<'SH' #!/bin/bash @@ -82,11 +84,16 @@ EOF ln -s "$migration_home/dotfiles/imv.config" "$migration_home/.config/imv/config" migration_log="$test_tmp/migration.log" -OMASNAP_MIGRATION_LOG="$migration_log" HOME="$migration_home" PATH="$stub_bin:$PATH" \ - bash -euo pipefail "$migration" >/dev/null +run_migration() { + : >"$migration_log" + OMASNAP_MIGRATION_LOG="$migration_log" HOME="$migration_home" PATH="$stub_bin:$PATH" \ + bash -euo pipefail "$migration" >/dev/null +} + +run_migration [[ $(sed -n '1p' "$migration_log") == $'add\tomasnap' ]] || fail "the migration installs Omasnap first" -[[ $(sed -n '2p' "$migration_log") == $'drop\ttensaku' ]] || fail "the migration removes Tensaku after Omasnap is ready" +[[ $(sed -n '2p' "$migration_log") == $'drop\tsatty tensaku' ]] || fail "the migration removes Satty and Tensaku after Omasnap is ready" grep -Fq '# Edit the current image in Omasnap and quit the viewer' "$migration_home/.config/imv/config" || fail "the migration updates the stock imv editor comment" grep -Fq ' = exec omasnap "$imv_current_file" & ; quit' "$migration_home/.config/imv/config" || @@ -97,3 +104,51 @@ grep -Fq ' = exec custom-editor "$imv_current_file" & ; quit' "$migratio [[ $(stat -c '%a' "$migration") == 644 ]] || fail "the Omasnap migration has mode 0644" pass "the migration swaps packages and safely updates only the stock imv binding" + +cat >"$migration_home/dotfiles/imv.config" <<'EOF' +[binds] + +# Edit the current image in Satty and quit the viewer + = exec satty --filename "$imv_current_file" & ; quit + = exec custom-editor "$imv_current_file" & ; quit +EOF +cp "$migration_home/dotfiles/imv.config" "$test_tmp/imv-before" +legacy_desktop="$migration_home/.local/share/applications/omasnap.desktop" +mkdir -p "$(dirname "$legacy_desktop")" +cat >"$legacy_desktop" <<'EOF' +[Desktop Entry] +Type=Application +Name=Omasnap +Exec=omasnap +NoDisplay=true +EOF +if OMASNAP_PACKAGE_STATUS=1 run_migration; then + fail "Omasnap install failure stops the migration" +fi +[[ $(<"$migration_log") == $'add\tomasnap' ]] || fail "install failure leaves old screenshot packages installed" +cmp -s "$test_tmp/imv-before" "$migration_home/dotfiles/imv.config" || fail "install failure leaves the imv binding untouched" +[[ -f $legacy_desktop ]] || fail "install failure preserves the existing launcher entry" +pass "Omasnap install failure preserves the previous screenshot setup" + +run_migration +[[ ! -e $legacy_desktop && ! -L $legacy_desktop ]] || fail "the migration removes the old user-local Omasnap desktop entry" +pass "the migration removes the desktop entry that hides the packaged launcher" +grep -Fq '# Edit the current image in Omasnap and quit the viewer' "$migration_home/.config/imv/config" || + fail "the migration updates the stock Satty comment" +grep -Fq ' = exec omasnap "$imv_current_file" & ; quit' "$migration_home/.config/imv/config" || + fail "the migration replaces the stock Satty binding before removing Satty" +grep -Fq ' = exec custom-editor "$imv_current_file" & ; quit' "$migration_home/.config/imv/config" || + fail "the Satty migration preserves custom bindings" +[[ -L $migration_home/.config/imv/config ]] || fail "the Satty migration preserves the imv symlink" +pass "the migration upgrades the stock Satty binding to Omasnap" + +cp "$migration_home/dotfiles/imv.config" "$test_tmp/imv-migrated" +run_migration +cmp -s "$test_tmp/imv-migrated" "$migration_home/dotfiles/imv.config" || fail "rerunning the migration preserves the updated imv config" +pass "the migration can be rerun" + +printf ' = exec custom-editor "$imv_current_file" & ; quit\n' >"$migration_home/dotfiles/imv.config" +cp "$migration_home/dotfiles/imv.config" "$test_tmp/imv-custom" +run_migration +cmp -s "$test_tmp/imv-custom" "$migration_home/dotfiles/imv.config" || fail "the migration preserves a custom edit shortcut" +pass "custom imv edit shortcuts remain unchanged" From 95120838d3c75f152879ee9d8eaa024bf3cf5404 Mon Sep 17 00:00:00 2001 From: Ryan Hughes Date: Mon, 21 Sep 2026 02:14:55 -0400 Subject: [PATCH 112/194] Document Omasnap's default capture flow --- agents/skills/visual-verification.md | 2 +- default/agents/skills/omarchy/capture.md | 5 +++-- manual/12-screenshots-recording.md | 11 ++++++----- manual/46-faq.md | 2 +- 4 files changed, 11 insertions(+), 9 deletions(-) diff --git a/agents/skills/visual-verification.md b/agents/skills/visual-verification.md index 7df6caa1c997..a8ed63d7ae26 100644 --- a/agents/skills/visual-verification.md +++ b/agents/skills/visual-verification.md @@ -15,7 +15,7 @@ Take a full-screen screenshot without opening the editor: omarchy capture screenshot fullscreen save ``` -The command writes to Omasnap's configured screenshot directory. Use `omarchy screenshot` for the interactive editor flow. Capture reference and candidate states as separate images when changing a layer-shell surface or layout, then compare both. +The command writes to Omasnap's configured screenshot directory. Use `omarchy screenshot` for the interactive capture flow, which copies the capture and shows a timed preview. Use `omarchy screenshot --editor=overlay` to test annotation before output. Capture reference and candidate states as separate images when changing a layer-shell surface or layout, then compare both. Record a short full-screen video for animation, transition, timing, capture, or screen-recording changes: diff --git a/default/agents/skills/omarchy/capture.md b/default/agents/skills/omarchy/capture.md index 4390fe75a373..a898db86a87e 100644 --- a/default/agents/skills/omarchy/capture.md +++ b/default/agents/skills/omarchy/capture.md @@ -10,10 +10,11 @@ omarchy screenshot # Interactive smart-region flow omarchy capture screenshot region # Select a region omarchy capture screenshot windows # Pick a window omarchy capture screenshot fullscreen save # Full screen, straight to disk (no editor) -omarchy capture screenshot scroll # Capture and stitch a scrolling region +omarchy capture screenshot scroll # Capture and stitch a scrolling region +omarchy screenshot --editor=overlay # Opt into annotation before output ``` -The first argument picks the Omasnap mode (`smart|region|windows|fullscreen|scroll`). With no second argument, the selection opens in Omasnap's annotation editor; `copy` or `save` skips the editor and sends the screenshot straight to that destination. Screenshots land in `~/Pictures/Screenshots` by default (override with `OMASNAP_SCREENSHOT_DIR`; the legacy `OMARCHY_SCREENSHOT_DIR` is also honored by the Omarchy command). +The first argument picks the Omasnap mode (`smart|region|windows|fullscreen|scroll`). By default, a capture copies to the clipboard and shows a preview for 10 seconds. Use the preview's Edit action to annotate, or pass `--editor=overlay` or `--editor=window` to edit before output. A second argument of `copy` or `save` skips the preview and sends the screenshot straight to that destination. Saved screenshots land in `~/Pictures/Screenshots` by default (override with `OMASNAP_SCREENSHOT_DIR`; the legacy `OMARCHY_SCREENSHOT_DIR` is also honored by the Omarchy command). ## Screen Recording diff --git a/manual/12-screenshots-recording.md b/manual/12-screenshots-recording.md index b3447b57db9f..41d6052d3b6e 100644 --- a/manual/12-screenshots-recording.md +++ b/manual/12-screenshots-recording.md @@ -13,13 +13,15 @@ Everything you can grab off the screen hangs off the Print Screen key. One key o ## Screenshots -Hit `Print Screen` and Omasnap captures the focused monitor before its overlay appears, so nothing shifts under you while you aim. Drag a freeform region, or use the tabs across the top to switch between Region, Scrolling Region, Window, and Fullscreen capture. Changed your mind? Hit `Print Screen` again to dismiss Omasnap. +Hit `Print Screen` and Omasnap captures the focused monitor before its overlay appears, so nothing shifts under you while you aim. Drag a freeform region, click a window to capture it, or click open space to capture the whole monitor. Press `S` before drawing to capture a scrolling region. Changed your mind? Hit `Print Screen` again to dismiss Omasnap. -After you select an area, Omasnap opens its annotation editor. It can draw arrows, lines, shapes, highlights, numbered markers, text, and secure redactions; crop or cut out part of the image; OCR its text; and add a backdrop. Press `Enter` to copy and save the finished PNG, `Ctrl + C` to copy it without saving, `Ctrl + S` to save it without copying, or `P` to pin it above your windows. +After you select an area, Omasnap copies the capture to the clipboard and shows a preview for 10 seconds. Use the preview's pin button or `Ctrl + P` to keep it on screen, or choose Edit to annotate it. -Files land in `~/Pictures/Screenshots` by default, with a name such as `screenshot-2026-08-13_14-22-05-firefox.png`. Set `OMASNAP_SCREENSHOT_DIR` to use another directory — see [the FAQ](46-faq.md) for where to put session environment variables. Omasnap creates the directory when it saves the first shot. +The annotation editor can draw arrows, lines, shapes, highlights, numbered markers, text, and secure redactions; crop or cut out part of the image; OCR its text; and add a backdrop. In the editor, press `Enter` to copy and save the finished PNG, `Ctrl + C` to copy it without saving, or `Ctrl + S` to save it without copying. -From the terminal, `omarchy screenshot` opens the same overlay, and you can choose its starting mode: `omarchy capture screenshot region`, `windows`, `fullscreen`, or `scroll`. A second argument of `copy` or `save` bypasses the annotation editor and sends the shot straight to that destination. +Saved screenshots land in `~/Pictures/Screenshots` by default, with a name such as `screenshot-2026-08-13_14-22-05-firefox.png`. Set `OMASNAP_SCREENSHOT_DIR` to use another directory — see [the FAQ](46-faq.md) for where to put session environment variables. Omasnap creates the directory when it saves the first shot. + +From the terminal, `omarchy screenshot` opens the same overlay, and you can choose its starting mode: `omarchy capture screenshot region`, `windows`, `fullscreen`, or `scroll`. A second argument of `copy` or `save` skips the preview and sends the shot straight to that destination. To edit before output, use `omarchy screenshot --editor=overlay` for a fullscreen editor or `omarchy screenshot --editor=window` for a separate window. ### Driving the picker from the keyboard @@ -27,7 +29,6 @@ While the selection is up, you don't have to use the mouse at all: | Key | Function | | --- | -------- | -| `Space` | Step through Region, Scrolling Region, and Window modes | | `S` | Toggle scrolling-region mode | | `Super + Arrow keys` | Move among windows in Window mode | | `Return` | Capture the highlighted window | diff --git a/manual/46-faq.md b/manual/46-faq.md index 8985439bafff..5def15d6a881 100644 --- a/manual/46-faq.md +++ b/manual/46-faq.md @@ -54,7 +54,7 @@ Automatic discovery, where printers on the network appear without being added, i ### How do I change where screenshots or screenrecordings are saved? -Omasnap saves screenshots to `~/Pictures/Screenshots` by default. To use another directory, add this to a file under `~/.config/uwsm/env.d/` (like `~/.config/uwsm/env.d/capture`): +Saved screenshots go to `~/Pictures/Screenshots` by default. To use another directory, add this to a file under `~/.config/uwsm/env.d/` (like `~/.config/uwsm/env.d/capture`): ``` export OMASNAP_SCREENSHOT_DIR="$HOME/Pictures/Captures" From b094787f1ad258bce3e4848109023a2a321bcb1f Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 21 Sep 2026 10:09:24 +0200 Subject: [PATCH 113/194] Point shell documentation to the canonical reference --- manual/32-shell-plugins.md | 2 +- shell/README.md | 305 +------------------------------------ 2 files changed, 7 insertions(+), 300 deletions(-) diff --git a/manual/32-shell-plugins.md b/manual/32-shell-plugins.md index 38ae40018ade..fc83a16f69d4 100644 --- a/manual/32-shell-plugins.md +++ b/manual/32-shell-plugins.md @@ -95,7 +95,7 @@ omarchy plugin validate ./my-plugin That runs the same checks the shell does at load time: the schema version, the required fields, an id that isn't reserved, entry points that are safe relative paths and actually exist, an entry point for every kind you claimed, and no symlinks anywhere inside the folder. -For the full picture, the source is the documentation: `shell/README.md` in the Omarchy repo covers the manifest schema, the shell's IPC contract, and the exact shape of `shell.json`, and `shell/plugins/README.md` lists every first-party plugin with its id, kinds, and entry points. +For plugin development, see the [shell reference](https://github.com/omacom/omarchy/blob/quattro/docs/omarchy-shell.md) and [first-party plugin catalog](https://github.com/omacom/omarchy/blob/quattro/shell/plugins/README.md). ## Sharing yours with the world diff --git a/shell/README.md b/shell/README.md index ca07b520ae44..5d464a0d072c 100644 --- a/shell/README.md +++ b/shell/README.md @@ -1,302 +1,9 @@ # Omarchy shell -`omarchy-shell` is a single long-running [Quickshell](https://quickshell.org/) -instance that hosts the Omarchy desktop. Hyprland autostart launches one shell -per graphical session; everything else — the bar, background switcher, panels, -and overlays — runs **inside** the shell as a plugin. +The Omarchy desktop runs in one long-lived Quickshell process. Its bar, panels, overlays, menus, and services are plugins hosted by `shell.qml`. -Hosting everything inside one shell means: - -- shared services and singletons live once, not once per process -- summoning a panel is an IPC call into a process that is already running, - not a fresh `quickshell -p ...` cold start -- third-party plugins can be loaded from disk without changing any source - code in Omarchy itself - -The runtime layout: - -``` -shell/ - shell.qml entry point (ShellRoot) - services/ - PluginRegistry.qml discovers, validates plugins, looks up enabled state in shell.json - BarWidgetRegistry.qml unified registry for bar widgets (1p + 3p) - plugins/ - bar/ first-party plugins (see plugins/README.md) - image-picker/ - menu/ - notifications/ - panels/ - audio/ - bluetooth/ - monitor/ - network/ - power/ - weather/ - agents/ - services/ - battery/ - idle/ - osd/ - polkit/ -``` - -The plugin discovery path is documented in [plugins/README.md](plugins/README.md). - -## Plugin manifest - -Every plugin ships a `manifest.json` describing what it is and how the -shell should load it. Minimal example: - -```json -{ - "schemaVersion": 1, - "id": "my.org.cool-clock", - "name": "Cool clock", - "version": "1.0.0", - "author": "You", - "description": "A clock that does cool things", - "kinds": ["bar-widget"], - "entryPoints": { "barWidget": "Widget.qml" }, - "barWidget": { - "displayName": "Cool clock", - "category": "Time", - "allowMultiple": false, - "defaultSection": "left", - "defaults": { "format": "HH:mm" }, - "schema": [ - { "key": "format", "type": "string", "label": "Format" } - ] - } -} -``` - -Supported `kinds`: - -| Kind | What it is | -|--------------|--------------------------------------------------------------| -| `bar-widget` | A component that the active bar can drop into a section | -| `panel` | A persistent or summoned floating window (e.g. OSD) | -| `overlay` | A fullscreen overlay (e.g. background switcher) | -| `menu` | A summoned menu surface | -| `service` | A headless singleton, no UI | -| `bar` | A full bar option that can replace the built-in `omarchy.bar` | - -Only one `bar` plugin is active at a time. Missing or invalid selections fall -back to the built-in `omarchy.bar`, so users always have a safe path home. -Panels, overlays, and menus are loaded when summoned. Plugins that need -to outlive a single summon can set `keepLoaded: true` (e.g. the image -picker keeps its overlay window mounted between summons). The same flag -keeps a service mounted across plugin hot-reload, so tearing down a -changed bar widget cannot destroy `omarchy.lock` while Hyprland still -holds the session lock. The kept instance is not replaced, so code -changes to a `keepLoaded` service itself only take effect on a shell -restart. First-party services are loaded at startup. - -Entry points may declare `omarchyPath`, `shell`, `manifest`, `pluginRegistry`, and `barWidgetRegistry` properties for host injection. Built-in plugins receive the trusted host objects. Third-party plugins receive capability-scoped facades: ordinary plugins can look up and control only their own service and lifecycle, built-in clones retain narrow source-specific configuration and UI compatibility, menu plugins receive an application-library facade, and plugins can read detached scalar bar state. A full-bar plugin additionally receives detached bar configuration and widget-catalog snapshots, narrow proxies for the non-authentication services used by built-in bar widgets, and lifecycle control over configured non-authentication UI plugins. Authentication capabilities are stamped from trusted first-party manifests, authentication services are retained outside the host's public service map and QML object tree, and changing a third-party registry or configuration snapshot cannot mutate host state. Facades do not isolate visual widgets from the parent hierarchy of the shared QML scene, so sensitive state must remain outside that reachable graph. - -Widgets rendered by a third-party replacement bar receive a service-less entry facade with target-scoped lifecycle and settings operations. Their live service objects are available only when the trusted built-in bar hosts them; otherwise the replacement bar could request and retain any configured widget's service. - -The full schema lives in `services/PluginRegistry.qml`. - -## Installing a third-party plugin - -A plugin is a **git repo** with a `manifest.json` at its root. Adding one -clones it straight into `~/.config/omarchy/plugins//` (named by the -manifest id); updating is a fast-forward pull of that checkout. - -```bash -omarchy plugin add https://github.com/acme/omarchy-weather.git -omarchy plugin update acme.weather # fetches, shows a diff, fast-forwards -omarchy plugin update # updates every git-managed plugin -omarchy plugin remove acme.weather -``` - -> ⚠️ **Plugins run as unsandboxed code inside `omarchy-shell`.** Adding warns you before cloning, plugins land disabled so you can review the code before enabling, and updates show a diff of the changes before touching anything. The scoped QML interfaces remove direct authentication-service and generic replacement-bar service lookups, but visual plugins still share and can traverse the ordinary host scene. Only add repos whose code you are willing to run. - -Each command is **interactive** when run bare in a terminal (gum pickers, -confirmation, a diff to review) and fully **non-interactive** when given -arguments. Pass `--yes` to skip every prompt — this is the path for scripts and -AI agents: - -```bash -omarchy plugin add https://github.com/acme/omarchy-weather.git --enable --yes -omarchy plugin update --yes -``` - -The installer never runs plugin code, install hooks, or sudo — it only clones -files, validates the manifest, and toggles enabled state over shell IPC. Since -an installed plugin is a plain git checkout, anything beyond add/update -(pinning a ref, switching branches) is ordinary git in the plugin directory. - -### Installing by hand - -You can still drop a plugin in without git: - -1. Put it in `~/.config/omarchy/plugins//` with a `manifest.json` - plus the QML referenced from its `entryPoints`. -2. `omarchy-shell shell rescanPlugins`. -3. `omarchy plugin enable `. Bar widgets start in - `barWidget.defaultSection`, or in the center when it is omitted, and can be - moved with `omarchy bar move`; a full bar replaces the one in use. - -The lower-level IPC equivalents remain available via `omarchy-shell shell rescanPlugins`, -`omarchy-shell shell enablePlugin '{}'`, and `omarchy-shell shell listPlugins`. -The `omarchy plugin` commands wrap those calls. `omarchy bar move` and -`omarchy bar set` edit the persisted widget layout in `shell.json`. - -To hack on a built-in plugin safely, clone it into user config instead of -editing the built-in source. The complete plugin directory is copied, including -every declared kind and local dependency. A built-in id such as -`omarchy.clock` becomes `.clock` (e.g. `dhh.clock`), with `My Clock` -as its display name. The username prefix keeps shared clones from colliding -with each other or with other plugin authors. - -```bash -omarchy plugin clone omarchy.clock -``` - -Cloning switches from the built-in to the new personal plugin, preserving an -existing bar widget's position and settings. Setup > Plugins > Clone provides -the interactive picker, then opens the new `.*` directory in `$EDITOR`. -Existing shortcuts and shell IPC calls made to the built-in id are routed to -the enabled clone, so cloning does not require changing its callers. Removing -an active clone switches back to its built-in source. -Saving a file anywhere under `~/.config/omarchy/plugins/` reloads plugin code -automatically; `omarchy-shell shell rescanPlugins` remains available to force a reload. - -First-party plugins under `shell/plugins/` are discovered the same way and load -by default. Disabling a non-widget records it in `disabledPlugins[]`; disabling -a widget removes it from the bar layout while leaving its component available -to add again. A full bar has no off state and is replaced by enabling another. - -## IPC contract - -The shell exposes a single `shell` IPC target plus whatever extra targets -individual plugins register (e.g. the bar's `bar` target for refresh -hooks, the image picker's `image-selector` target). `omarchy-menu` uses the -shell target to summon the first-party `omarchy.menu` plugin instead of -running a separate Quickshell instance. - -| Method | Returns | Effect | -|------------------------------------------|---------|-------------------------------------------------------| -| `ping` | `ok` | health check | -| `summon ` | `ok` / `unknown` | load + open a panel/overlay plugin | -| `hide ` | — | close a previously-summoned plugin | -| `toggle ` | — | summon if closed, hide if open | -| `call ` | string | call a method on an already-loaded plugin | -| `rescanPlugins` | — | re-walk plugin dirs and hot-reload plugin code | -| `reloadConfig` | `ok` | reload `~/.config/omarchy/shell.json` | -| `setPluginEnabled ` | `ok` / `unknown` | flip the persisted enabled bit (see note) | -| `listPlugins` | JSON | every discovered plugin, sorted by name | - -Direct invocation: - -``` -quickshell ipc -p $OMARCHY_PATH/shell call shell ping -``` - -Hyprland autostart launches the shell directly with `quickshell -p -$OMARCHY_PATH/shell`. Use `omarchy-restart-shell` to stop every running -instance of that config and launch one fresh shell process. - -A convenience wrapper, [`omarchy-shell`](../bin/omarchy-shell), forwards IPC -calls to the running shell. It does not start the shell. - -``` -omarchy-shell shell ping -omarchy-shell shell toggle omarchy.menu '{"menu":"root"}' -omarchy-shell shell listPlugins -omarchy-shell shell rescanPlugins -``` - -**Note on `setPluginEnabled`:** the `enabled` argument is a string. Only the -literal `"true"` enables the plugin; every other value (including `"True"`, -`"1"`, `"yes"`, or omitted) disables it. This keeps the IPC surface -type-stable across QML's `string`-only IPC arguments. - -## Persisted state - -There is one user config file. Everything that distinguishes your -customization from the shipped defaults lives in it. - -| Path | Owner | Purpose | -|-----------------------------------|----------------|--------------------------------------------------------| -| `~/.config/omarchy/shell.json` | the shell | full layout + per-entry settings + enabled plugin list | -| `~/.config/omarchy/plugins//` | user | drop-in third-party plugin source files | - -The `config/omarchy/shell.json` default config describes the -fresh-install state. When the user has no `shell.json`, the shell uses -the defaults verbatim. Once the user customizes anything, `shell.json` -becomes the authoritative file — we do **not** deep-merge defaults back in. - -### shell.json shape - -```json -{ - "version": 1, - "idle": { - "screensaver": 150, - "lock": 300 - }, - "bar": { - "id": "omarchy.bar", - "position": "top", - "transparent": false, - "centerAnchor": "omarchy.clock", - "layout": { - "left": [ { "id": "omarchy.menu" }, { "id": "omarchy.workspaces" } ], - "center": [ { "id": "omarchy.clock", "format": "HH:mm" } ], - "right": [ - { "id": "omarchy.audio" } - ] - } - }, - "plugins": [] -} -``` - -### Storage rules - -1. **The active bar option is `bar.id`.** Omit it or set it to `omarchy.bar` - to use the built-in bar. Set it to another plugin id whose manifest declares - `kind: "bar"` to replace the full bar. -2. **Every plugin instance is one entry.** Either in `bar.layout.
` - for bar widgets, or in `plugins[]` for panels, overlays, services, - menus, and anything else non-bar. -3. **Settings are inline on the entry.** No `config:` sub-object, no - separate per-plugin settings file, no merge layers. The fields on each - entry are the values the plugin sees. -4. **Built-in widget ids are namespaced.** Use ids such as `omarchy.clock`, - `omarchy.audio`, and `omarchy.network`. The migration rewrites older ids - like `Clock` and `AudioPanel` forward. -5. **Third-party enabled ⇔ present.** A third-party plugin is enabled iff - its id appears somewhere in shell.json. For full bar options, that means - `bar.id`; for bar widgets, plugin enable/disable adds/removes layout entries; - other plugin kinds are enabled the same way. First-party non-bar plugins - are enabled unless listed in `disabledPlugins[]`. -6. **Multiple instances** are allowed when a manifest sets - `allowMultiple: true`. Each instance is independent — e.g. two clock - widgets in different timezones are just two `{"id":"omarchy.clock", "timezone": ...}` - entries with their own values. -7. **Idle timings are top-level.** `idle.screensaver` and `idle.lock` - are seconds since user idle began, so the default lock fires at 300s - even if the 150s screensaver starts first. -8. **`version: 1` is required** at the top level. The shell will fall back - to defaults rather than load an unknown version. - -## Implementation history - -Built up in phases on this branch: - -- Phase 1 — `omarchy-shell phase 1: host the existing bar in a single shell` -- Phase 2 — `omarchy-shell phase 2: plugin registry and bar widget registry` -- Phase 3 — `omarchy-shell phase 3: fold bar-settings into the shell as a panel plugin` -- Phase 4 — `omarchy-shell phase 4: absorb background-switcher as a plugin` -- Phase 5 — `omarchy-shell phase 5: docs, cleanup, and migration crumbs` -- Phase 6 — `omarchy-shell phase 6: reviewer cleanup (path traversal, collision, races)` -- Phase 7 — `omarchy-shell phase 7: replace socket with IpcHandler, rename to image-picker` -- Phase 8a — `omarchy-shell phase 8a: unified shell.json with inline plugin settings` - -Shared services and Pipewire/UPower/Hyprland consolidation are explicitly -out of scope here and deferred to a follow-up after a review pass. +- [Shell reference](../docs/omarchy-shell.md) — plugin manifests, IPC, configuration, and shared UI contracts. +- [Plugin user guide](../manual/32-shell-plugins.md) — install, configure, and clone plugins. +- [First-party plugins](plugins/README.md) — bundled plugin IDs, kinds, and entry points. +- [Shell development guide](../agents/skills/shell-dev.md) — conventions for changing the desktop. +- [Theming reference](../docs/theming.md) — theme tokens, templates, and generated configuration. From 1aa1423eac60471b5d385b4c17dcb595add27572 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 21 Sep 2026 10:10:02 +0200 Subject: [PATCH 114/194] Retire the shipped Copy URL migration test --- .../copy-url-shortcut-migration-test.sh | 238 ------------------ 1 file changed, 238 deletions(-) delete mode 100644 test/shell.d/copy-url-shortcut-migration-test.sh diff --git a/test/shell.d/copy-url-shortcut-migration-test.sh b/test/shell.d/copy-url-shortcut-migration-test.sh deleted file mode 100644 index 934a57eeb020..000000000000 --- a/test/shell.d/copy-url-shortcut-migration-test.sh +++ /dev/null @@ -1,238 +0,0 @@ -#!/bin/bash - -set -euo pipefail - -source "$(dirname "${BASH_SOURCE[0]}")/base-test.sh" - -require_command jq -require_command python3 - -migration="$ROOT/migrations/1786643346.sh" -test_dir=$(mktemp -d) -trap 'rm -rf "$test_dir"' EXIT - -home="$test_dir/home" -profile_root="$home/.config/chromium" -preferences="$profile_root/Default/Preferences" -mkdir -p "$(dirname "$preferences")" - -# Any id Chromium once derived from the extension's keyless load path; the -# repair keys off the registered command name, not the id. -ghost_id="ikkebdkaanlebnifjnbeiaklodhbjcci" -pinned_id="bgpiichlckmfanooecilcjemknkcpngb" - -write_stale_preferences() { - jq -n --arg ghost "$ghost_id" --arg pinned "$pinned_id" '{extensions: {commands: {"linux:Alt+Shift+L": {command_name: "copy-url", extension: $ghost, global: false}}, settings: {($ghost): {commands: {"copy-url": {suggested_key: "Alt+Shift+L", was_assigned: true}}}, ($pinned): {commands: {"copy-url": {suggested_key: "Alt+Shift+L"}}}}}}' >"$preferences" -} - -stub_bin="$test_dir/bin" -mkdir -p "$stub_bin" - -cat >"$stub_bin/python3" <<'STUB' -#!/bin/bash -exit 127 -STUB -chmod +x "$stub_bin/python3" - -# Test stubs must delegate to the system interpreter, not a user shim that can -# route python3 back through the stubs and recurse. -REAL_PYTHON=$(PATH="$stub_bin:$PATH" command -p -v python3) -[[ $REAL_PYTHON != "$stub_bin/python3" ]] || fail "real Python resolution bypasses user shims" -export REAL_PYTHON -rm -f "$stub_bin/python3" - -run_migration() { - HOME="$home" PATH="$stub_bin:$PATH" bash -euo pipefail "$migration" >/dev/null 2>&1 -} - -# A running Chromium-family browser marks its profile root with a SingletonLock -# symlink to -, a target that never exists on disk. That lock — -# not the mere presence of a browser process — is what the migration waits on. -open_browser() { - mkdir -p "$profile_root" - ln -sfn "test-host-1234" "$profile_root/SingletonLock" -} -close_browser() { - rm -f "$profile_root/SingletonLock" -} - -# The affected profile being open prompts for the windows to be closed; -# declining (or having no terminal to ask in) defers the repair so a -# rewrite-on-exit cannot revert it. -printf '#!/bin/bash\nexit 1\n' >"$stub_bin/gum" -chmod +x "$stub_bin/gum" -write_stale_preferences -open_browser - -before_hash=$(sha256sum "$preferences" | cut -d' ' -f1) - -run_migration && fail "migration defers while the affected profile is open" -[[ $(sha256sum "$preferences" | cut -d' ' -f1) == "$before_hash" ]] || - fail "migration leaves preferences alone while the affected profile is open" -pass "migration defers the repair while the affected profile is open" - -# gum paints its prompt on stderr, so that stream has to stay attached: -# suppressing it leaves gum reading keys behind an unpainted screen, which -# reads as a hung update. -cat >"$stub_bin/gum" <<'STUB' -#!/bin/bash -echo "gum-prompt-painted" >&2 -exit 1 -STUB -prompt_stderr="$test_dir/prompt-stderr" -HOME="$home" PATH="$stub_bin:$PATH" bash -euo pipefail "$migration" >/dev/null 2>"$prompt_stderr" && - fail "migration defers when the browser prompt is declined" -grep -q "gum-prompt-painted" "$prompt_stderr" || fail "migration keeps the browser prompt visible" -pass "migration keeps the browser prompt visible" - -# A browser holding a different profile root cannot revert this repair, so it -# must not hold the update: the repair goes through without ever reaching the -# prompt, which the still-declining gum stub would otherwise fail. -close_browser -mkdir -p "$home/.config/google-chrome" -ln -sfn "test-host-1234" "$home/.config/google-chrome/SingletonLock" -write_stale_preferences -run_migration || fail "migration repairs while a different profile root is open" -jq -e --arg pinned "$pinned_id" '.extensions.commands["linux:Alt+Shift+L"].extension == $pinned' "$preferences" >/dev/null || - fail "migration repairs the shortcut while a different profile root is open" -pass "migration ignores a browser on a different profile root" -rm -f "$home/.config/google-chrome/SingletonLock" "$preferences.omarchy-copy-url-repair.bak" - -# Closing the affected profile and confirming the prompt lets the repair -# proceed. -write_stale_preferences -open_browser -cat >"$stub_bin/gum" <<'STUB' -#!/bin/bash -"$CLOSE_BROWSER" -touch "${GUM_CALLED:?}" -exit 0 -STUB -cat >"$stub_bin/close-browser" <<'STUB' -#!/bin/bash -rm -f "$HOME/.config/chromium/SingletonLock" -STUB -chmod +x "$stub_bin/gum" "$stub_bin/close-browser" -GUM_CALLED="$test_dir/gum-called" CLOSE_BROWSER="$stub_bin/close-browser" \ - HOME="$home" PATH="$stub_bin:$PATH" bash -euo pipefail "$migration" >/dev/null 2>&1 || - fail "migration proceeds once the profile is closed and the prompt confirmed" -[[ -e $test_dir/gum-called ]] || fail "migration asks before repairing under a running browser" -jq -e --arg pinned "$pinned_id" '.extensions.commands["linux:Alt+Shift+L"].extension == $pinned' "$preferences" >/dev/null || - fail "migration repairs after the browser prompt is confirmed" -pass "migration asks to close the browser and repairs on confirmation" -rm -f "$preferences.omarchy-copy-url-repair.bak" - -# With the affected profile closed the ghost registration moves to the pinned id. -printf '#!/bin/bash\nexit 1\n' >"$stub_bin/gum" -close_browser -write_stale_preferences -run_migration || fail "migration repairs the shortcut when no browser is running" - -jq -e --arg ghost "$ghost_id" --arg pinned "$pinned_id" ' - .extensions.commands["linux:Alt+Shift+L"].extension == $pinned and - (.extensions.settings | has($ghost) | not) and - .extensions.settings[$pinned].commands["copy-url"].was_assigned == true -' "$preferences" >/dev/null || fail "migration rebinds the Copy URL shortcut to the pinned extension id" -[[ -f $preferences.omarchy-copy-url-repair.bak ]] || - fail "migration backs up preferences before the repair" -pass "migration rebinds the Copy URL shortcut to the pinned extension id" - -# A repaired profile has no ghost registration left, so nothing is pending — -# even while that same profile is open. -rm "$preferences.omarchy-copy-url-repair.bak" -repaired_hash=$(sha256sum "$preferences" | cut -d' ' -f1) -open_browser -run_migration || fail "migration reruns cleanly after the repair" -[[ $(sha256sum "$preferences" | cut -d' ' -f1) == "$repaired_hash" && ! -e $preferences.omarchy-copy-url-repair.bak ]] || - fail "migration is idempotent after the repair" -pass "migration is idempotent after the repair" -close_browser - -# A remapped shortcut keeps the user's chosen key while moving to the pinned id. -jq -n --arg ghost "$ghost_id" '{extensions: {commands: {"linux:Ctrl+Alt+P": {command_name: "copy-url", extension: $ghost, global: false}}, settings: {}}}' >"$preferences" -run_migration || fail "migration repairs remapped shortcuts" -jq -e --arg pinned "$pinned_id" '.extensions.commands["linux:Ctrl+Alt+P"].extension == $pinned' "$preferences" >/dev/null || - fail "migration keeps the remapped key while rebinding to the pinned id" -pass "migration keeps remapped shortcut keys" - -# When the pinned extension already holds a copy-url binding (the user fixed -# it by hand), the ghost is dropped rather than doubled into a second binding. -jq -n --arg ghost "$ghost_id" --arg pinned "$pinned_id" '{extensions: {commands: {"linux:Ctrl+Alt+P": {command_name: "copy-url", extension: $pinned, global: false}, "linux:Alt+Shift+L": {command_name: "copy-url", extension: $ghost, global: false}}, settings: {}}}' >"$preferences" -run_migration || fail "migration cleans ghosts alongside a manual repair" -jq -e --arg pinned "$pinned_id" ' - (.extensions.commands | has("linux:Alt+Shift+L") | not) and - .extensions.commands["linux:Ctrl+Alt+P"].extension == $pinned -' "$preferences" >/dev/null || fail "migration drops the ghost instead of double-binding the pinned extension" -pass "migration never double-binds the pinned extension" - -# A browser starting mid-repair may write stale Preferences back on exit, so -# the migration must stay pending for a later browser-free run to verify. A -# stub hands the repair call through and opens the profile right after it. -write_stale_preferences -close_browser -rm -f "$preferences.omarchy-copy-url-repair.bak" -cat >"$stub_bin/python3" <<'STUB' -#!/bin/bash -# Called as `python3 -c