Skill Tracer
Skills › gstack › freeze › check-freeze.sh

check-freeze.sh

372 lines · freeze/bin/check-freeze.sh at 3f79d81

1#!/usr/bin/env bash
2# check-freeze.sh — PreToolUse hook for /freeze skill
3# Reads JSON from stdin, checks if the edited path is within the freeze
4# boundary: file_path for Edit/Write, notebook_path for NotebookEdit (#3067).
5# Returns a PreToolUse hookSpecificOutput with permissionDecision "deny" to block,
6# or {} to allow. The decision MUST be nested under hookSpecificOutput — Claude
7# Code ignores a top-level permissionDecision, which silently no-ops the block.
8#
9# Polarity: freeze is a DENY-tier hook, so an unreadable payload DENIES
10# (fail closed). A payload that parses but has no file_path is a non-file
11# tool — allow. This is the opposite edge-handling from careful's ask-tier
12# and intentionally so: /guard runs both, and a boundary that fails open is
13# not a boundary.
14set -euo pipefail
16# Deny-tier backstop: any unexpected non-zero death (a failing pipeline under
17# set -e, a deleted cwd, EACCES) would otherwise exit with no decision JSON,
18# which Claude Code treats as non-blocking — the edit proceeds. Every
19# deliberate output below sets _FREEZE_DECIDED first so a late failure after
20# a decision never prints a second JSON object.
21_FREEZE_DECIDED=""
22_freeze_backstop() {
23 local rc=$?
24 if [ "$rc" -ne 0 ] && [ -z "$_FREEZE_DECIDED" ]; then
25 _FREEZE_DECIDED=1
26 printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"[freeze] Hook failed unexpectedly (exit %s) - blocked, fail closed. Re-run ./setup or /unfreeze."}}\n' "$rc"
27 exit 0
28 fi
30trap _freeze_backstop EXIT
32# Read stdin
33INPUT=$(cat)
35# Shared JSON helpers (extractor + encoder) — one copy for careful AND freeze.
36# freeze previously carried its own grep-first extractor which truncated at
37# escaped quotes and failed OPEN; the shared file kills that drift class.
38_HOOK_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
39# shellcheck source=careful/bin/hook-extract.sh
40# Freeze is deny-tier: if its own helpers are missing/broken (partial install,
41# mid-upgrade state), the boundary must fail CLOSED — inline JSON, since the
42# encoder we would normally use lives in the file that just failed to load.
43# NOTE: bash treats `.` on a MISSING file as fatal in non-interactive shells
44# (an if-guard cannot catch it) — the existence check must come first.
45_HOOK_HELPER="$_HOOK_DIR/../../careful/bin/hook-extract.sh"
46if [ ! -f "$_HOOK_HELPER" ] || ! . "$_HOOK_HELPER" 2>/dev/null; then
47 _FREEZE_DECIDED=1
48 printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"[freeze] Hook helpers unavailable (broken install?) - blocked, fail closed. Reinstall gstack or run /unfreeze."}}\n'
49 exit 0
50fi
52# Locate the freeze directory state file. The writer (/freeze via
53# gstack-paths) and this reader MUST resolve the same root or the boundary
54# fails open: with GSTACK_HOME set, /freeze wrote freeze-dir.txt under
55# GSTACK_HOME while this hook read $HOME/.gstack, found nothing, and allowed
56# everything (#1459, #1509). gstack_hook_state_root mirrors gstack-paths.
57# A helper from an older install that lacks the function must fail CLOSED
58# (the existence check above only proves the file sourced), never exit 127
59# with no JSON — Claude Code treats that as non-blocking.
60if ! command -v gstack_hook_state_root >/dev/null 2>&1 || ! command -v gstack_hook_normalize_path >/dev/null 2>&1 || ! command -v gstack_hook_extract_tool >/dev/null 2>&1; then
61 _FREEZE_DECIDED=1
62 printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"[freeze] Hook helpers out of date (partial upgrade?) - blocked, fail closed. Re-run ./setup or /unfreeze."}}\n'
63 exit 0
64fi
65STATE_DIR="$(gstack_hook_state_root; printf x)"; STATE_DIR="${STATE_DIR%x}"
66FREEZE_FILE="$STATE_DIR/freeze-dir.txt"
68# If no freeze file exists, allow everything (not yet configured)
69if [ ! -f "$FREEZE_FILE" ]; then
70 _FREEZE_DECIDED=1
71 echo '{}'
72 exit 0
73fi
76 IFS= read -r FREEZE_DIR || true
77 IFS= read -r FREEZE_OWNER_LINE || true
78} < "$FREEZE_FILE"
79case "$FREEZE_OWNER_LINE" in
80 gstack-freeze-v1:*) ;;
81 *) FREEZE_DIR=$(printf '%s\n' "$FREEZE_DIR" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') ;;
82esac
83# A literal leading ~ in the state file never matches absolute tool paths
84# (tilde is not expanded from variables) — expand it here.
85case "$FREEZE_DIR" in
86 "~/"*) FREEZE_DIR="$HOME/${FREEZE_DIR#\~/}" ;;
87 "~") FREEZE_DIR="$HOME" ;;
88esac
90# If freeze dir is empty, allow
91if [ -z "$FREEZE_DIR" ]; then
92 _FREEZE_DECIDED=1
93 echo '{}'
94 exit 0
95fi
97# A deny for a path whose landing spot cannot be worked out: never fall back
98# to comparing the raw string (that fallback was the fail-open in #3623).
99_freeze_unresolved() {
100 gstack_hook_log_fire freeze boundary_deny
101 gstack_hook_decision deny "[freeze] Blocked: cannot tell where $1 lands ($2), so the freeze boundary cannot be checked (fail closed). Use a plain absolute path, or run /unfreeze to remove the boundary."
102 _FREEZE_DECIDED=1
103 exit 0
106# Windows path rules apply on Windows bash and to drive-letter or UNC paths
107# on any platform (the normalizer rewrites those everywhere): there '..'
108# never climbs above X:\ or \\server\share, and names lose trailing dots
109# and spaces.
110_freeze_win_shaped() {
111 [ "$GSTACK_HOOK_IS_WINDOWS" = 1 ] && return 0
112 case "$1" in
113 [A-Za-z]:[\\/]*|[A-Za-z]:|\\\\[!\\/]*) return 0 ;;
114 esac
115 return 1
118# Both sides of the comparison go through one canonicalization: the state
119# file may hold C:\dev\proj\ or the /c/dev/proj/ that `pwd` prints in Git
120# Bash, and Claude Code on Windows reports file_path as C:\... (#2876).
121FREEZE_DIR_WIN=0
122if _freeze_win_shaped "$FREEZE_DIR"; then FREEZE_DIR_WIN=1; fi
123gstack_hook_normalize_path "$FREEZE_DIR"
124FREEZE_DIR="$GSTACK_HOOK_PATH"
126case "$FREEZE_DIR" in
127 /*) ;;
128 *)
129 gstack_hook_decision deny '[freeze] Legacy relative boundary is ambiguous. Re-run /freeze with an absolute directory chosen by the user; the saved state was preserved.'
130 _FREEZE_DECIDED=1
131 exit 0
132 ;;
133esac
135# Extract the edited path with the shared real-JSON parser. Edit and Write
136# carry tool_input.file_path; NotebookEdit carries tool_input.notebook_path
137# (Claude Code Agent SDK reference, NotebookEditInput), so a notebook edit
138# used to parse as "no path" and pass every boundary.
139set +e
140gstack_hook_extract_tool "$INPUT" file_path notebook_path
141EXTRACT_RC=$?
142set -e
143FILE_PATH="$GSTACK_HOOK_VALUE"
144TOOL_LABEL="${GSTACK_HOOK_TOOL:+$GSTACK_HOOK_TOOL }$GSTACK_HOOK_FIELD"
146# Unparseable payload (or no parser available): DENY. A boundary hook that
147# allows what it cannot read is not a boundary.
148if [ "$EXTRACT_RC" -ne 0 ] && [ -n "$INPUT" ]; then
149 gstack_hook_decision deny "[freeze] Could not parse the tool payload to check the freeze boundary. Blocked (fail closed). Freeze boundary: $FREEZE_DIR"
150 _FREEZE_DECIDED=1
151 exit 0
152fi
154# Parsed fine but no path field: a non-file tool payload — allow.
155if [ -z "$FILE_PATH" ]; then
156 _FREEZE_DECIDED=1
157 echo '{}'
158 exit 0
159fi
161# bash 3.2 expands $'...' only outside double quotes, so keep these in
162# variables for use inside parameter expansions.
163_FREEZE_NL=$'\n'
164_FREEZE_CR=$'\r'
166# No real file name holds a line break, and command substitution would drop
167# a trailing one ('<b>\n' is a sibling of the boundary, not the boundary).
168case "$FILE_PATH" in
169 *"$_FREEZE_NL"*|*"$_FREEZE_CR"*) _freeze_unresolved "$TOOL_LABEL $FILE_PATH" "a line break in the path" ;;
170esac
171# The walk below costs time quadratic in the path length, and a hook that
172# outlives the host's timeout lets the edit through. No real path is longer
173# than PATH_MAX (4096 on Linux), so bound the work before it starts.
174if [ "${#FILE_PATH}" -gt 4096 ]; then
175 _freeze_unresolved "$TOOL_LABEL path of ${#FILE_PATH} characters" "longer than 4096 characters"
176fi
178# A leading ~ is the home directory to the host's file tools, never a
179# directory named '~' under cwd: joined onto cwd, '~/.zshrc' passed whenever
180# cwd sat inside the boundary (#3623). Windows bash also writes '~\'.
181case "$FILE_PATH" in
182 "~") FILE_PATH="$HOME" ;;
183 "~/"*) FILE_PATH="$HOME/${FILE_PATH#\~/}" ;;
184 "~\\"*) if [ "$GSTACK_HOOK_IS_WINDOWS" = 1 ]; then FILE_PATH="$HOME/${FILE_PATH#\~?}"; fi ;;
185esac
187# 'C:', 'C:x' and 'C:..\x' are relative to drive C's own working directory, and
188# '\c\dev' to the current drive's root; this hook sees neither, and the
189# normalizer would read them as cwd-relative or as drive C.
190if [ "$GSTACK_HOOK_IS_WINDOWS" = 1 ]; then
191 case "$FILE_PATH" in
192 [A-Za-z]:|[A-Za-z]:[!\\/]*) _freeze_unresolved "$TOOL_LABEL $FILE_PATH" "a drive-relative path" ;;
193 \\[!\\]*) _freeze_unresolved "$TOOL_LABEL $FILE_PATH" "a path relative to the current drive's root" ;;
194 esac
195fi
197FILE_PATH_WIN=0
198if _freeze_win_shaped "$FILE_PATH"; then FILE_PATH_WIN=1; fi
199# Canonicalize before the absolute test: a drive-letter path does not start
200# with '/', so it used to be joined onto cwd and every edit was denied.
201gstack_hook_normalize_path "$FILE_PATH"
202FILE_PATH="$GSTACK_HOOK_PATH"
204# Resolve file_path to absolute if it isn't already, against the physical
205# cwd the host process has (a logical $PWD through a symlink differs, and
206# command substitution would drop a trailing newline from either).
207case "$FILE_PATH" in
208 /*) ;; # already absolute
209 *)
210 _FREEZE_PWD=$(pwd -P && printf x) || _freeze_unresolved "$TOOL_LABEL $FILE_PATH" "the working directory cannot be read"
211 _FREEZE_PWD="${_FREEZE_PWD%"$_FREEZE_NL"x}"
212 case "$_FREEZE_PWD" in
213 *"$_FREEZE_NL"*|*"$_FREEZE_CR"*) _freeze_unresolved "$TOOL_LABEL $FILE_PATH" "a line break in the working directory" ;;
214 esac
215 FILE_PATH="$_FREEZE_PWD/$FILE_PATH"
216 ;;
217esac
219# Resolve an absolute path to where a write would land (bash 3.2 builtins
220# plus readlink). Components are walked left to right: empty and '.' drop,
221# '..' pops, and a symlink at ANY depth is replaced by its target, even when
222# the rest of the path does not exist yet. The old resolver followed only the
223# final component and ran 'cd && pwd -P' on the immediate parent, comparing
224# the raw string when that parent did not exist, so '<b>/../x/new/f',
225# '<b>/link-out/new/f' and '<b>/..' all passed (#3623). The walk also replaces
226# a per-line sed squeeze that let a newline split '..' off a name.
227# $2 lexical: apply '..' to the text and follow no symlink, the reading of a
228# path normalizer such as Node's path.resolve.
229# $3 1: Windows rules ('..' stops at /c or //server/share; link targets
230# use Windows syntax; a name ending in a dot or space, which Windows
231# trims, three leading slashes, and a UNC server or share of '', '.',
232# '..' or '?' cannot be placed). Without it a target like 'C:\..' is one
233# POSIX file name. On a POSIX host a Windows path names no local file,
234# so it is resolved as text and no local symlink is followed.
235# Returns 1 for a symlink loop, a chain over 40 links, an unreadable or
236# line-broken link, a Windows link target relative to a drive or its root,
237# link targets that add up past 8192 characters with the path (the walk is
238# quadratic, so its total input stays bounded), or an unplaceable Windows
239# name; the caller fails closed.
240_resolve_path() {
241 local _rem="$1" _win="${3:-0}" _lead="" _cur="" _n=0 _min=0 _reroot=1
242 local _part _tgt _p _tail="" _hops=0 _probe=1 _budget="${#1}"
243 if [ "$_win" = 1 ] && [ "$GSTACK_HOOK_IS_WINDOWS" != 1 ]; then _probe=0; fi
244 while :; do
245 if [ "$_reroot" = 1 ]; then
246 _reroot=0; _lead=""; _cur=""; _n=0; _min=0
247 case "$_rem" in
248 ///*)
249 if [ "$_win" = 1 ]; then return 1; fi
250 while [ "${_rem#/}" != "$_rem" ]; do _rem="${_rem#/}"; done
251 ;;
252 //[!/]*)
253 if [ "$_win" = 1 ]; then
254 _lead="/"; _rem="${_rem#//}"; _min=2
255 else
256 _rem="${_rem#//}"
257 fi
258 ;;
259 *)
260 while [ "${_rem#/}" != "$_rem" ]; do _rem="${_rem#/}"; done
261 if [ "$_win" = 1 ]; then
262 case "$_rem" in [A-Za-z]|[A-Za-z]/*) _min=1 ;; esac
263 fi
264 ;;
265 esac
266 fi
267 [ -n "$_rem" ] || break
268 _part="${_rem%%/*}"
269 case "$_rem" in */*) _rem="${_rem#*/}" ;; *) _rem="" ;; esac
270 if [ "$_win" = 1 ] && [ -n "$_lead" ] && [ "$_n" -lt 2 ]; then
271 case "$_part" in ''|.|..|'?') return 1 ;; esac
272 fi
273 case "$_part" in
274 ''|.) continue ;;
275 ..)
276 if [ "$_n" -gt "$_min" ]; then _cur="${_cur%/*}"; _n=$((_n - 1)); fi
277 continue
278 ;;
279 esac
280 if [ "$_win" = 1 ]; then
281 case "$_part" in *[.\ ]) return 1 ;; esac
282 fi
283 if [ "${2:-}" = lexical ] || [ "$_probe" = 0 ] || [ ! -L "$_lead$_cur/$_part" ]; then
284 _cur="$_cur/$_part"; _n=$((_n + 1))
285 continue
286 fi
287 _hops=$((_hops + 1))
288 [ "$_hops" -le 40 ] || return 1
289 _tgt=$(readlink "$_lead$_cur/$_part" && printf x) || return 1
290 _tgt="${_tgt%x}"; _tgt="${_tgt%"$_FREEZE_NL"}"
291 case "$_tgt" in ''|*"$_FREEZE_NL"*|*"$_FREEZE_CR"*) return 1 ;; esac
292 if [ "$_win" = 1 ]; then
293 case "$_tgt" in [A-Za-z]:|[A-Za-z]:[!\\/]*|\\|\\[!\\]*) return 1 ;; esac
294 gstack_hook_normalize_path "$_tgt"
295 _tgt="$GSTACK_HOOK_PATH"
296 fi
297 case "$_tgt" in /*) _reroot=1 ;; esac
298 _budget=$((_budget + ${#_tgt}))
299 [ "$_budget" -le 8192 ] || return 1
300 _rem="${_tgt%/}${_rem:+/$_rem}"
301 done
302 _p="$_lead$_cur"
303 if [ "${2:-}" != lexical ] && [ "$_probe" = 1 ]; then
304 # pwd -P on the deepest existing directory answers in the platform's own
305 # dialect (/cygdrive/c/... on Cygwin) and sees links -L misses there.
306 while [ -n "$_cur" ] && [ ! -d "$_lead$_cur" ]; do
307 _tail="/${_cur##*/}$_tail"
308 _cur="${_cur%/*}"
309 done
310 if [ -n "$_cur" ]; then
311 if _p=$(cd "$_lead$_cur" 2>/dev/null && pwd -P && printf x); then
312 _p="${_p%"$_FREEZE_NL"x}"
313 case "$_p" in *"$_FREEZE_NL"*|*"$_FREEZE_CR"*) return 1 ;; esac
314 else
315 _p="$_lead$_cur"
316 fi
317 _p="${_p%/}$_tail"
318 else
319 _p="$_lead$_tail"
320 fi
321 # Git Bash spells one folder several ways through its mounts (/tmp is
322 # %TEMP%, and HOME converts through them); cygpath -m gives the one drive
323 # spelling Claude Code reports.
324 if [ -n "$_p" ] && [ "$GSTACK_HOOK_IS_WINDOWS" = 1 ] && command -v cygpath >/dev/null 2>&1; then
325 _p=$(cygpath -m "$_p" && printf x) || return 1
326 _p="${_p%"$_FREEZE_NL"x}"
327 case "$_p" in ''|*"$_FREEZE_NL"*|*"$_FREEZE_CR"*) return 1 ;; esac
328 fi
329 fi
330 [ -n "$_p" ] || _p="/"
331 gstack_hook_normalize_path "$_p"
332 printf '%s' "$GSTACK_HOOK_PATH"
335_FREEZE_WHY="a symlink loop, a chain over 40 links, a path and link targets over 8192 characters in all, an unreadable link, a Windows link target relative to a drive or its root, or a Windows name that cannot be placed"
336FREEZE_DIR_RAW="$FREEZE_DIR"
337FREEZE_DIR=$(_resolve_path "$FREEZE_DIR_RAW" physical "$FREEZE_DIR_WIN") || _freeze_unresolved "the freeze boundary $FREEZE_DIR_RAW" "$_FREEZE_WHY"
338# Hosts disagree on '<link>/..': the OS means the target's parent, a lexical
339# normalizer means the link's parent. The edit is inside only when both
340# readings land inside the boundary.
341FILE_PATH_RAW="$FILE_PATH"
342FILE_PATH=$(_resolve_path "$FILE_PATH_RAW" physical "$FILE_PATH_WIN") || _freeze_unresolved "$TOOL_LABEL $FILE_PATH_RAW" "$_FREEZE_WHY"
343FILE_PATH_LEXICAL=$(_resolve_path "$FILE_PATH_RAW" lexical "$FILE_PATH_WIN") || _freeze_unresolved "$TOOL_LABEL $FILE_PATH_RAW" "$_FREEZE_WHY"
344FILE_PATH_LEXICAL=$(_resolve_path "$FILE_PATH_LEXICAL" physical "$FILE_PATH_WIN") || _freeze_unresolved "$TOOL_LABEL $FILE_PATH_RAW" "$_FREEZE_WHY"
346# Check: does the file path start with the freeze directory? Windows paths
347# are case-insensitive, so compare that way there.
348[ "$GSTACK_HOOK_IS_WINDOWS" = 1 ] && shopt -s nocasematch
349_freeze_inside() {
350 case "$1" in
351 "${FREEZE_DIR%/}/"*|"${FREEZE_DIR}") return 0 ;;
352 esac
353 return 1
355if _freeze_inside "$FILE_PATH" && _freeze_inside "$FILE_PATH_LEXICAL"; then
356 # Inside freeze boundary — allow
357 _FREEZE_DECIDED=1
358 echo '{}'
359else
360 # Outside freeze boundary — deny
361 # Log hook fire event (shared helper respects GSTACK_HOME)
362 gstack_hook_log_fire freeze boundary_deny
363 if _freeze_inside "$FILE_PATH"; then FILE_PATH="$FILE_PATH_LEXICAL"; fi
364 _FREEZE_SHOWN="$FILE_PATH_RAW"
365 if [ "$FILE_PATH" != "$FILE_PATH_RAW" ]; then _FREEZE_SHOWN="$FILE_PATH_RAW (lands at $FILE_PATH)"; fi
367 # The reason is JSON-encoded by the shared helper. Never interpolate paths
368 # into hand-built JSON: a path containing a quote or newline produced
369 # malformed JSON here, and the deny silently no-oped.
370 gstack_hook_decision deny "[freeze] Blocked: $TOOL_LABEL $_FREEZE_SHOWN is outside the freeze boundary ($FREEZE_DIR). Only edits within the frozen directory are allowed; run /unfreeze to remove the boundary."
371 _FREEZE_DECIDED=1
372fi