@hasna/hooks 0.15.3 → 0.15.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": 1,
3
3
  "package": "@hasna/hooks",
4
- "version": "0.15.3",
4
+ "version": "0.15.4",
5
5
  "hooks": {
6
6
  "affected-tests": {
7
7
  "version": "0.1.0",
@@ -1751,8 +1751,14 @@ const MAX_UNCERTAIN_CDS = 8;
1751
1751
  * itself sits behind a link (macOS /tmp is /private/tmp), a real path inside the root's real
1752
1752
  * location is mapped back under the root's own spelling, so the rule still recognises it.
1753
1753
  */
1754
- function inRuleSpelling(realPath: string, root: string): string {
1755
- const realRoot = realpathThroughExisting(root);
1754
+ function inRuleSpelling(realPath: string, root: string, realRoots?: Map<string, string | null>): string {
1755
+ // The real location of each rule root is read once per command when a cache is given: every
1756
+ // judged location is re-spelled for every rule, and a filesystem walk each time is slow.
1757
+ let realRoot: string | null | undefined = realRoots?.get(root);
1758
+ if (realRoot === undefined) {
1759
+ realRoot = realpathThroughExisting(root);
1760
+ realRoots?.set(root, realRoot);
1761
+ }
1756
1762
  if (!realRoot || realRoot === resolve(root)) return realPath;
1757
1763
  if (realPath === realRoot) return resolve(root);
1758
1764
  return isInsidePath(realPath, realRoot) ? join(resolve(root), relative(realRoot, realPath)) : realPath;
@@ -1772,11 +1778,17 @@ function isExistingDirectory(path: string): boolean {
1772
1778
  * there followed, as the kernel does) plus its own last name, which rm removes without
1773
1779
  * following. Null when the parent cannot be resolved, or when it equals `path`.
1774
1780
  */
1775
- function realParentLocation(path: string): string | null {
1781
+ function realParentLocation(path: string, realParents?: Map<string, string | null>): string | null {
1776
1782
  const resolved = resolve(path);
1777
1783
  const parent = dirname(resolved);
1778
1784
  if (parent === resolved) return null;
1779
- const realParent = realpathThroughExisting(parent);
1785
+ // Many targets in one command share a parent folder; with a cache its real location is read
1786
+ // from disk once per command (HAA-00121 review).
1787
+ let realParent = realParents?.get(parent);
1788
+ if (realParent === undefined) {
1789
+ realParent = realpathThroughExisting(parent);
1790
+ realParents?.set(parent, realParent);
1791
+ }
1780
1792
  if (!realParent) return null;
1781
1793
  const real = join(realParent, basename(resolved));
1782
1794
  return real === resolved ? null : real;
@@ -1803,10 +1815,12 @@ interface GlobWalkBudget {
1803
1815
  linked: number;
1804
1816
  deadline: number;
1805
1817
  folders: Map<string, Dirent[] | null>;
1818
+ /** Per-command cache for kernelLocation: a path's link target (null when it is no link). */
1819
+ links: Map<string, string | null>;
1806
1820
  }
1807
1821
 
1808
1822
  function newGlobWalkBudget(): GlobWalkBudget {
1809
- return { remaining: GLOB_WALK_BUDGET, linked: 0, deadline: performance.now() + GLOB_WALK_DEADLINE_MS, folders: new Map() };
1823
+ return { remaining: GLOB_WALK_BUDGET, linked: 0, deadline: performance.now() + GLOB_WALK_DEADLINE_MS, folders: new Map(), links: new Map() };
1810
1824
  }
1811
1825
 
1812
1826
  /**
@@ -1891,6 +1905,97 @@ function realLocationsOfGlobMatches(pattern: string, followsLastName: boolean, b
1891
1905
  return real;
1892
1906
  }
1893
1907
 
1908
+ const MAX_KERNEL_LINK_HOPS = 40;
1909
+
1910
+ /**
1911
+ * Where the kernel resolves `path`, written from `cwd`, up to its last name (HAA-00121).
1912
+ * resolve() drops `..` textually, but open(2) and rm walk the path one name at a time and
1913
+ * follow each link first, so `..` after a link climbs from the link's TARGET:
1914
+ * `rm -rf ~/lndeep/../deep`, with ~/lndeep -> ~/.hasna/state/deep, deletes
1915
+ * ~/.hasna/state/deep, not ~/deep. The walk starts at the physical working folder (a shell's
1916
+ * logical `cd ~/link` still leaves the process inside the link's target) and follows every link
1917
+ * before the last name, which rm removes without following. Glob components are kept as
1918
+ * written. Null when a `..` comes after a glob component, which cannot be resolved before the
1919
+ * shell expands it, or when the links loop.
1920
+ */
1921
+ const KERNEL_NAME_COST = 1;
1922
+ const KERNEL_LINK_COST = 16;
1923
+
1924
+ function kernelLocation(cwd: string, path: string, budget?: GlobWalkBudget): string | null {
1925
+ // expandHome joins with path.join, which already drops `..` textually; the home prefix is
1926
+ // replaced here without normalising the rest.
1927
+ const home = process.env.HOME || homedir();
1928
+ const homeForm = /^(?:~|\$HOME|\$\{HOME\})(?=\/|$)/.exec(path);
1929
+ const raw = homeForm ? home + path.slice(homeForm[0].length) : path;
1930
+ const names = raw.split(/[\\/]+/).filter(Boolean);
1931
+ // Every name walked is charged to the command's budget, and each lstat/realpath is cached
1932
+ // for the command, so thousands of `..` targets cannot hold the hook past its own timeout
1933
+ // (HAA-00121 review). A spent budget sets budget.remaining below zero and returns null.
1934
+ const spend = (units: number) => {
1935
+ if (!budget) return true;
1936
+ budget.remaining -= units;
1937
+ return budget.remaining >= 0 && performance.now() <= budget.deadline;
1938
+ };
1939
+ const linkTarget = (candidate: string): string | null => {
1940
+ const cached = budget?.links.get(candidate);
1941
+ if (cached !== undefined) return cached;
1942
+ let target: string | null = null;
1943
+ if (!spend(KERNEL_LINK_COST)) return null;
1944
+ try {
1945
+ if (lstatSync(candidate).isSymbolicLink()) target = realpathSync(candidate);
1946
+ } catch {
1947
+ // A missing name resolves as written.
1948
+ }
1949
+ budget?.links.set(candidate, target);
1950
+ return target;
1951
+ };
1952
+ let current: string;
1953
+ if (isAbsolute(raw)) current = sep;
1954
+ else {
1955
+ const key = `\u0000cwd:${cwd}`;
1956
+ const cached = budget?.links.get(key);
1957
+ current = cached ?? realpathThroughExisting(cwd) ?? resolve(cwd);
1958
+ budget?.links.set(key, current);
1959
+ }
1960
+ let afterGlob = false;
1961
+ let hops = 0;
1962
+ for (let index = 0; index < names.length; index += 1) {
1963
+ if (!spend(KERNEL_NAME_COST)) {
1964
+ if (budget) budget.remaining = -1;
1965
+ return null;
1966
+ }
1967
+ const name = names[index];
1968
+ if (name === ".") continue;
1969
+ if (name === "..") {
1970
+ if (afterGlob) return null;
1971
+ current = dirname(current);
1972
+ continue;
1973
+ }
1974
+ const next = join(current, name);
1975
+ const isLast = index === names.length - 1;
1976
+ if (/[*?[]/.test(name)) afterGlob = true;
1977
+ if (afterGlob || isLast) {
1978
+ current = next;
1979
+ continue;
1980
+ }
1981
+ const target = linkTarget(next);
1982
+ if (budget && budget.remaining < 0) return null;
1983
+ if (target !== null) {
1984
+ hops += 1;
1985
+ if (hops > MAX_KERNEL_LINK_HOPS) return null;
1986
+ current = target;
1987
+ continue;
1988
+ }
1989
+ current = next;
1990
+ }
1991
+ return current;
1992
+ }
1993
+
1994
+ /** Whether a path, as written, has a `..` component. */
1995
+ function hasParentComponent(path: string): boolean {
1996
+ return path.split(/[\\/]/).some((part) => part === "..");
1997
+ }
1998
+
1894
1999
  function isMissingPathError(error: unknown): boolean {
1895
2000
  return error instanceof Error && "code" in error && (error as NodeJS.ErrnoException).code === "ENOENT";
1896
2001
  }
@@ -2195,7 +2300,8 @@ function rsyncDeleteTargets(command: string): DestructiveShellTarget[] {
2195
2300
  afterOptions = true;
2196
2301
  continue;
2197
2302
  }
2198
- if (!afterOptions && (token === "--delete" || token.startsWith("--delete-"))) {
2303
+ // `--del` is rsync's own short name for --delete-during.
2304
+ if (!afterOptions && (token === "--delete" || token === "--del" || token.startsWith("--delete-"))) {
2199
2305
  hasDelete = true;
2200
2306
  continue;
2201
2307
  }
@@ -2590,7 +2696,71 @@ function shellCommandLayers(command: string): { layers: ShellCommandLayer[]; tru
2590
2696
  // `rm` followed ANYWHERE by a recursive flag. Anchoring it to the very next token missed
2591
2697
  // `rm -f -r /*`, `rm -v -f -r /*`, `rm --one-file-system -rf /*` and `rm <path> -rf`, each of
2592
2698
  // which sailed past the oversized-command gate unanalysed.
2593
- const DESTRUCTIVE_VERB = /(?:^|[^\w.-])(?:[\w/.-]*\/)?(?:rm\b[^;&|\n]*?(?:\s-[A-Za-z]*[rR][A-Za-z]*(?=[\s=;&|]|$)|\s--recursive\b|\s--dir\b)|rsync\s[^;&|]*--delete|find\s[^;&|]*(?:-delete|-execdir?\s)|git\s[^;&|]*(?:clean\s+-\S*[fd]|reset\s+--hard))/;
2699
+ /**
2700
+ * Whether one stretch of command text may hold a recursive delete: `rm` with a recursive flag,
2701
+ * `rsync --del…`, `find … -delete` / `-exec[dir]`, `git clean -f/-d` or `git reset --hard`.
2702
+ *
2703
+ * It runs in time linear in the text (HAA-00121 review 4). The single regular expression it
2704
+ * replaces scanned from every `rm`/`find`/`git`/`rsync` word to the end of its line, so its cost
2705
+ * grew with the square of how many such words shared a line: 80,000 ` rm x` took 27 s and a
2706
+ * timed-out hook fails open. Here the text is split once on separators; in each piece only the
2707
+ * first delete-capable word is found, and the rest of that piece is read once. Any later
2708
+ * occurrence of the same word in the piece is covered, because its tail is part of that rest.
2709
+ */
2710
+ const VERB_START = (verb: string) => new RegExp(`(?:^|[^\\w.-])${verb}(?![\\w])`);
2711
+ const RM_WORD = VERB_START("rm");
2712
+ const RSYNC_WORD = VERB_START("rsync");
2713
+ const FIND_WORD = VERB_START("find");
2714
+ const GIT_WORD = VERB_START("git");
2715
+
2716
+ function hasRecursiveRmFlag(rest: string): boolean {
2717
+ if (/\s--(?:recursive|dir)(?![\w-])/.test(rest)) return true;
2718
+ for (const word of rest.split(/\s+/)) {
2719
+ if (word.length < 2 || word[0] !== "-" || word[1] === "-") continue;
2720
+ // `-<letters>` alone, or followed by `=`: the same words the old pattern accepted.
2721
+ let index = 1;
2722
+ while (index < word.length && /[A-Za-z]/.test(word[index])) index += 1;
2723
+ if (index > 1 && (index === word.length || word[index] === "=") && /[rR]/.test(word.slice(1, index))) return true;
2724
+ }
2725
+ return false;
2726
+ }
2727
+
2728
+ function pieceAfter(piece: string, word: RegExp): string | null {
2729
+ const match = word.exec(piece);
2730
+ if (!match) return null;
2731
+ return piece.slice(match.index + match[0].length);
2732
+ }
2733
+
2734
+ function textHasRecursiveDelete(text: string): boolean {
2735
+ // Pieces are split on `;`, `&` and `|` only: the old pattern let the whitespace before a flag
2736
+ // be a new line (`rm\n-rf`), and rsync, find and git kept reading across new lines, so a
2737
+ // new line never ends a piece here. That can only add matches.
2738
+ for (const piece of text.split(/[;&|]/)) {
2739
+ const afterRm = pieceAfter(piece, RM_WORD);
2740
+ if (afterRm !== null && hasRecursiveRmFlag(afterRm)) return true;
2741
+ const afterRsync = pieceAfter(piece, RSYNC_WORD);
2742
+ if (afterRsync !== null && /--del(?:ete)?(?![\w])/.test(afterRsync)) return true;
2743
+ const afterFind = pieceAfter(piece, FIND_WORD);
2744
+ if (afterFind !== null && /-delete|-execdir?\s/.test(afterFind)) return true;
2745
+ const afterGit = pieceAfter(piece, GIT_WORD);
2746
+ if (afterGit !== null && /clean\s+-\S*[fd]|reset\s+--hard/.test(afterGit)) return true;
2747
+ }
2748
+ return false;
2749
+ }
2750
+
2751
+ /**
2752
+ * Whether the raw text of a command may hold a recursive delete. The shell removes quotes,
2753
+ * backslashes and line continuations before it runs a word, so `r""m -rf`, `rm -r''f`,
2754
+ * `r\m -rf`, `$'rm' -rf` and `rm \<newline>-rf` are all `rm -rf`. The refusals that decide on the
2755
+ * raw text alone (an oversized command, one nested too deep to analyse, an incomplete
2756
+ * analysis) also test that unquoted copy, so a spelling cannot turn their refusal into an
2757
+ * admission (HAA-00121 review 3). Both tests are linear in the text.
2758
+ */
2759
+ function looksDestructive(command: string): boolean {
2760
+ if (textHasRecursiveDelete(command)) return true;
2761
+ const unquoted = command.replace(/\\\r?\n/g, "").replace(/\$(?=['"])/g, "").replace(/["'\\]/g, "");
2762
+ return unquoted !== command && textHasRecursiveDelete(unquoted);
2763
+ }
2594
2764
 
2595
2765
  /**
2596
2766
  * A command too deeply wrapped or too wide to analyse within the caps is refused when it
@@ -2603,7 +2773,7 @@ const DESTRUCTIVE_VERB = /(?:^|[^\w.-])(?:[\w/.-]*\/)?(?:rm\b[^;&|\n]*?(?:\s-[A-
2603
2773
  * past the cap and it returned continue.
2604
2774
  */
2605
2775
  function truncatedAnalysisBlockReason(command: string): string | null {
2606
- if (!DESTRUCTIVE_VERB.test(command)) return null;
2776
+ if (!looksDestructive(command)) return null;
2607
2777
  return [
2608
2778
  "Blocked: this command nests more shell wrappers than the safety guard can analyse,",
2609
2779
  "and it contains a recursive delete. The guard refuses rather than guess, because an",
@@ -2613,12 +2783,25 @@ function truncatedAnalysisBlockReason(command: string): string | null {
2613
2783
  ].join(" ");
2614
2784
  }
2615
2785
 
2786
+ /**
2787
+ * The reason when a delete target has a `..` after a wildcard (or links that loop), which the
2788
+ * guard cannot resolve before the shell expands it (HAA-00121).
2789
+ */
2790
+ function parentAfterGlobBlockReason(command: string): string | null {
2791
+ if (!looksDestructive(command)) return null;
2792
+ return [
2793
+ "Blocked: a recursive delete target has `..` after a wildcard (or links that loop), so the",
2794
+ "safety guard cannot tell which folder it reaches: `..` after a link climbs from the link's",
2795
+ "target. Write the target as a plain absolute path without `..`.",
2796
+ ].join(" ");
2797
+ }
2798
+
2616
2799
  /**
2617
2800
  * The reason when the globs of one command match or scan more names on disk than the guard
2618
2801
  * checks within its time budget (HAA-00119).
2619
2802
  */
2620
2803
  function globWalkBlockReason(command: string): string | null {
2621
- if (!DESTRUCTIVE_VERB.test(command)) return null;
2804
+ if (!looksDestructive(command)) return null;
2622
2805
  return [
2623
2806
  "Blocked: the globs in this recursive delete match or scan more names on disk than the safety",
2624
2807
  "guard can check for links within its time budget (a glob ending in `/`, or with a wildcard in a",
@@ -2633,7 +2816,7 @@ function globWalkBlockReason(command: string): string | null {
2633
2816
  * folder a later relative delete runs in.
2634
2817
  */
2635
2818
  function uncertainCdsBlockReason(command: string): string | null {
2636
- if (!DESTRUCTIVE_VERB.test(command)) return null;
2819
+ if (!looksDestructive(command)) return null;
2637
2820
  return [
2638
2821
  "Blocked: this command changes folder too many times in ways that may not take effect",
2639
2822
  "(a `cd` into a folder that does not exist yet, or one removed earlier in the same command,",
@@ -2689,6 +2872,10 @@ interface AnalysisState {
2689
2872
  uncertainCds?: boolean;
2690
2873
  /** Set when matching globs on disk used up the command's walk budget. */
2691
2874
  globWalkSpent?: boolean;
2875
+ /** Set when a delete target has a `..` after a glob component, or links that loop. */
2876
+ parentAfterGlob?: boolean;
2877
+ /** The command's walk budget, shared by globs matched on disk and kernelLocation. */
2878
+ walk?: GlobWalkBudget;
2692
2879
  }
2693
2880
 
2694
2881
  /** A segment that removes or moves files, after which an existing folder may be gone. */
@@ -2793,7 +2980,14 @@ function cwdTrackedSegments(command: string, baseCwd: string, nonEmptyNames: Rea
2793
2980
  if (verb === "pushd") frame.dirStack.push(frame.cwds);
2794
2981
  // Skip cd's own flags (-P, -L, --) to reach the directory operand.
2795
2982
  let i = 1;
2796
- while (i < tokens.length && (tokens[i] === "-P" || tokens[i] === "-L" || tokens[i] === "-e" || tokens[i] === "-@" || tokens[i] === "--")) i += 1;
2983
+ // `cd -P` lands on the physical folder: every link followed, `..` applied after it, so
2984
+ // `cd -P ~/lndeep/..` reaches the link target's parent (HAA-00121). The last flag wins.
2985
+ let physicalCd = false;
2986
+ while (i < tokens.length && (tokens[i] === "-P" || tokens[i] === "-L" || tokens[i] === "-e" || tokens[i] === "-@" || tokens[i] === "--")) {
2987
+ if (tokens[i] === "-P") physicalCd = true;
2988
+ if (tokens[i] === "-L") physicalCd = false;
2989
+ i += 1;
2990
+ }
2797
2991
  const operand = tokens[i];
2798
2992
  const priorCwds = frame.cwds;
2799
2993
  cdOperations += 1;
@@ -2848,7 +3042,15 @@ function cwdTrackedSegments(command: string, baseCwd: string, nonEmptyNames: Rea
2848
3042
  next.add(current);
2849
3043
  continue;
2850
3044
  }
2851
- next.add(resolveFrom(current, operand));
3045
+ if (physicalCd) {
3046
+ const kernel = kernelLocation(current, operand, analysis.walk);
3047
+ if (kernel === null) {
3048
+ analysis.degraded = true;
3049
+ if (analysis.walk && analysis.walk.remaining < 0) analysis.globWalkSpent = true;
3050
+ else analysis.parentAfterGlob = true;
3051
+ }
3052
+ next.add(kernel === null ? resolveFrom(current, operand) : (realpathThroughExisting(kernel) ?? kernel));
3053
+ } else next.add(resolveFrom(current, operand));
2852
3054
  if (collapsed !== null) next.add(resolveFrom(current, collapsed));
2853
3055
  }
2854
3056
  // A cd may fail (a missing folder, no permission) and the shell runs the next
@@ -3056,8 +3258,10 @@ export async function classifyDangerousOperation(input: CodewithHookInput): Prom
3056
3258
 
3057
3259
  if (input.tool_name === "Bash") {
3058
3260
  const command = getCommand(input);
3059
- const analysis: AnalysisState = { degraded: false };
3060
3261
  const globWalk = newGlobWalkBudget();
3262
+ const analysis: AnalysisState = { degraded: false, walk: globWalk };
3263
+ const realRoots = new Map<string, string | null>();
3264
+ const realParents = new Map<string, string | null>();
3061
3265
 
3062
3266
  // A command large enough that merely tokenizing it blows the hook's 20s budget cannot be
3063
3267
  // analysed at all, and a timed-out hook fails open. 70k repetitions of `cd /<4KB>` is a
@@ -3094,32 +3298,47 @@ export async function classifyDangerousOperation(input: CodewithHookInput): Prom
3094
3298
  // in a parent folder (`cd ~/link && rm -rf state`, `rm -rf ~/link/state`, with
3095
3299
  // ~/link -> ~/.hasna) moves the delete into a protected root the text never names
3096
3300
  // (HAA-00113). rm removes the last name itself without following it.
3097
- const realLocation = realParentLocation(targetPath);
3301
+ const realLocation = realParentLocation(targetPath, realParents);
3302
+ // A `..` after a link climbs from the link's target, which resolve() cannot see, so a
3303
+ // target written with `..` is also judged where the kernel resolves it (HAA-00121).
3304
+ let kernelTarget: string | null = null;
3305
+ if (hasParentComponent(target.path)) {
3306
+ kernelTarget = globWalk.remaining < 0 ? null : kernelLocation(targetCwd, target.path, globWalk);
3307
+ if (kernelTarget === null) {
3308
+ analysis.degraded = true;
3309
+ if (globWalk.remaining < 0) analysis.globWalkSpent = true;
3310
+ else analysis.parentAfterGlob = true;
3311
+ }
3312
+ }
3098
3313
  // A trailing slash (`rm -rf ~/link/`) makes rm follow the last name too, so the delete
3099
3314
  // acts inside wherever that link finally points (HAA-00113 review).
3100
3315
  const followsLastName = /[\\/]\.?$/.test(target.path);
3101
- const realTarget = followsLastName ? realpathThroughExisting(targetPath) : null;
3316
+ const realTarget = followsLastName ? realpathThroughExisting(kernelTarget ?? targetPath) : null;
3102
3317
  // A glob with a trailing slash (`rm -rf */`, `~/ln*/`) follows every link it matches, and
3103
3318
  // a glob in a middle component (`~/l*/state`) can pass through one, so those globs are
3104
3319
  // matched on disk and judged where each match really acts (HAA-00119). A glob only in the
3105
3320
  // last component is already covered by realParentLocation. One walk budget covers the
3106
3321
  // whole command; once it is spent the analysis fails closed rather than skipping the rest.
3107
3322
  let linkedMatches: string[] = [];
3108
- const middleGlob = /[*?[]/.test(dirname(resolve(targetPath)));
3109
- if ((followsLastName || middleGlob) && pathHasGlob(targetPath)) {
3110
- const found = globWalk.remaining < 0 ? null : realLocationsOfGlobMatches(targetPath, followsLastName, globWalk);
3323
+ const walkedPath = kernelTarget ?? targetPath;
3324
+ const middleGlob = /[*?[]/.test(dirname(resolve(walkedPath)));
3325
+ if ((followsLastName || middleGlob) && pathHasGlob(walkedPath)) {
3326
+ const found = globWalk.remaining < 0 ? null : realLocationsOfGlobMatches(walkedPath, followsLastName, globWalk);
3111
3327
  if (found === null) {
3112
3328
  analysis.degraded = true;
3113
3329
  analysis.globWalkSpent = true;
3114
3330
  } else linkedMatches = found;
3115
3331
  }
3116
3332
  const judgedLocations = new Set<string>([targetPath]);
3117
- for (const location of [realLocation, realTarget, ...linkedMatches]) {
3333
+ const kernelParent = kernelTarget ? realParentLocation(kernelTarget, realParents) : null;
3334
+ for (const location of [realLocation, realTarget, kernelTarget, kernelParent, ...linkedMatches]) {
3118
3335
  if (location) judgedLocations.add(location);
3119
3336
  }
3120
3337
  for (const judged of judgedLocations) {
3121
3338
  for (const rule of rulesFor(judged)) {
3122
- const ruleJudged = judged === targetPath ? judged : inRuleSpelling(judged, rule.root);
3339
+ // Every location is re-spelled under the rule's own root when that root sits behind a
3340
+ // link (macOS /tmp): a physical cd (`cd -P`) can make even the target itself physical.
3341
+ const ruleJudged = inRuleSpelling(judged, rule.root, realRoots);
3123
3342
  if (threatensRule(ruleJudged, rule, currentManagedRepoRoot)) {
3124
3343
  // A session removing content of its own scratch folder (session id from the
3125
3344
  // harness, not the command) is not a threat to the ~/.hasna tree.
@@ -3167,9 +3386,16 @@ export async function classifyDangerousOperation(input: CodewithHookInput): Prom
3167
3386
  // exactly. Checked here rather than at each bound so there is ONE fail-closed answer:
3168
3387
  // three bounds that each invented their own fallback all became root wipes.
3169
3388
  if (analysis.degraded) {
3170
- const reason = analysis.globWalkSpent
3171
- ? globWalkBlockReason(command)
3172
- : analysis.uncertainCds ? uncertainCdsBlockReason(command) : truncatedAnalysisBlockReason(command);
3389
+ // The reason functions recognise a recursive delete by a pattern over the raw text, but the
3390
+ // target scan reads through shell quoting (`r""m -rf`, `r\m -rf`), so a delete the scan
3391
+ // found must be refused even when the pattern misses it: otherwise an incomplete analysis
3392
+ // turns a refusal into an admission (HAA-00121 review).
3393
+ const asIfDelete = targets.length > 0 && !looksDestructive(command) ? "rm -r" : command;
3394
+ const reason = analysis.parentAfterGlob
3395
+ ? parentAfterGlobBlockReason(asIfDelete)
3396
+ : analysis.globWalkSpent
3397
+ ? globWalkBlockReason(asIfDelete)
3398
+ : analysis.uncertainCds ? uncertainCdsBlockReason(asIfDelete) : truncatedAnalysisBlockReason(asIfDelete);
3173
3399
  if (reason) {
3174
3400
  return { block: true, operation: "unanalysable command", reason };
3175
3401
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hasna/hooks",
3
- "version": "0.15.3",
3
+ "version": "0.15.4",
4
4
  "description": "Open source hooks library for AI coding agents - Install safety, quality, and automation hooks with a single command",
5
5
  "type": "module",
6
6
  "bin": {