@hasna/hooks 0.15.2 → 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.2",
4
+ "version": "0.15.4",
5
5
  "hooks": {
6
6
  "affected-tests": {
7
7
  "version": "0.1.0",
@@ -1,4 +1,4 @@
1
- import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, statSync, type Stats, writeFileSync, writeSync } from "node:fs";
1
+ import { type Dirent, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync, type Stats, writeFileSync, writeSync } from "node:fs";
2
2
  import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
3
3
  import { homedir, tmpdir } from "node:os";
4
4
 
@@ -1603,7 +1603,11 @@ const LEADING_CD = /^cd\s+(?:\/|~\/)[A-Za-z0-9._@+\/-]*$/;
1603
1603
  */
1604
1604
  export function ownScratchCommandAllowed(command: string): boolean {
1605
1605
  if (PARENT_COMPONENT.test(command) || HIDDEN_COMMAND.test(command) || /[()]/.test(command)) return false;
1606
- const pieces = command.split(/[;&|\n\r]+/).map((piece) => piece.trim()).filter(Boolean);
1606
+ // A stream redirection that only duplicates or closes a descriptor, or sends output to
1607
+ // /dev/null (`2>&1`, `>&2`, `2>&-`, `&>/dev/null`), runs nothing; its `&` is not a separator
1608
+ // (HAA-00119). It is dropped before the command is split into pieces.
1609
+ const withoutRedirections = command.replace(/(^|\s)(?:\d*[<>]&(?:\d+|-)|&>>?\/dev\/null)(?=\s|$)/g, "$1");
1610
+ const pieces = withoutRedirections.split(/[;&|\n\r]+/).map((piece) => piece.trim()).filter(Boolean);
1607
1611
  if (pieces.length > 0 && LEADING_CD.test(pieces[0])) pieces.shift();
1608
1612
  if (pieces.length === 0) return false;
1609
1613
  return pieces.every((piece) => {
@@ -1747,8 +1751,14 @@ const MAX_UNCERTAIN_CDS = 8;
1747
1751
  * itself sits behind a link (macOS /tmp is /private/tmp), a real path inside the root's real
1748
1752
  * location is mapped back under the root's own spelling, so the rule still recognises it.
1749
1753
  */
1750
- function inRuleSpelling(realPath: string, root: string): string {
1751
- 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
+ }
1752
1762
  if (!realRoot || realRoot === resolve(root)) return realPath;
1753
1763
  if (realPath === realRoot) return resolve(root);
1754
1764
  return isInsidePath(realPath, realRoot) ? join(resolve(root), relative(realRoot, realPath)) : realPath;
@@ -1768,16 +1778,224 @@ function isExistingDirectory(path: string): boolean {
1768
1778
  * there followed, as the kernel does) plus its own last name, which rm removes without
1769
1779
  * following. Null when the parent cannot be resolved, or when it equals `path`.
1770
1780
  */
1771
- function realParentLocation(path: string): string | null {
1781
+ function realParentLocation(path: string, realParents?: Map<string, string | null>): string | null {
1772
1782
  const resolved = resolve(path);
1773
1783
  const parent = dirname(resolved);
1774
1784
  if (parent === resolved) return null;
1775
- 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
+ }
1776
1792
  if (!realParent) return null;
1777
1793
  const real = join(realParent, basename(resolved));
1778
1794
  return real === resolved ? null : real;
1779
1795
  }
1780
1796
 
1797
+ /**
1798
+ * One budget per command for matching globs on disk (HAA-00119). The hook's own timeout fails
1799
+ * open, so a command whose globs would take long to check must be refused instead:
1800
+ * - every name read from a folder and every match cost one unit, and an lstat of a literal
1801
+ * component below a glob GLOB_WALK_LSTAT_COST, out of GLOB_WALK_BUDGET; a folder is read from
1802
+ * disk only once per command;
1803
+ * - only a match with a symbolic link on its way is resolved and judged, at most
1804
+ * MAX_GLOB_LINKED_LOCATIONS per command (resolving and judging is the expensive part);
1805
+ * - the whole walk stops at GLOB_WALK_DEADLINE_MS, measured from the start of the command's check.
1806
+ * Running out of any of them fails closed.
1807
+ */
1808
+ const GLOB_WALK_BUDGET = 200_000;
1809
+ const GLOB_WALK_LSTAT_COST = 8;
1810
+ const MAX_GLOB_LINKED_LOCATIONS = 256;
1811
+ const GLOB_WALK_DEADLINE_MS = 3_000;
1812
+
1813
+ interface GlobWalkBudget {
1814
+ remaining: number;
1815
+ linked: number;
1816
+ deadline: number;
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>;
1820
+ }
1821
+
1822
+ function newGlobWalkBudget(): GlobWalkBudget {
1823
+ return { remaining: GLOB_WALK_BUDGET, linked: 0, deadline: performance.now() + GLOB_WALK_DEADLINE_MS, folders: new Map(), links: new Map() };
1824
+ }
1825
+
1826
+ /**
1827
+ * Where a glob delete really acts when a link lies on the way to what it matches, as the shell
1828
+ * would expand it now (hidden names only for a pattern that starts with `.`):
1829
+ * - the pattern itself under the real location of its literal prefix (macOS /tmp is a link);
1830
+ * - for each match reached through a link in or below the first globbed component, its real
1831
+ * parent location (`rm -rf ~/l*​/state` through ~/lnhasna -> ~/.hasna), and, when the
1832
+ * target ends in a slash, the real location of a matched link, which rm then follows
1833
+ * (`rm -rf *​/`).
1834
+ * Null once the command's walk budget is spent, so the caller fails closed (HAA-00119).
1835
+ */
1836
+ function realLocationsOfGlobMatches(pattern: string, followsLastName: boolean, budget: GlobWalkBudget): string[] | null {
1837
+ const parts = resolve(pattern).split(sep).filter(Boolean);
1838
+ const firstGlob = parts.findIndex((part) => /[*?[]/.test(part));
1839
+ if (firstGlob === -1) return [];
1840
+ const prefix = sep + parts.slice(0, firstGlob).join(sep);
1841
+ const realPrefix = realpathThroughExisting(prefix) ?? prefix;
1842
+ const real: string[] = [];
1843
+ if (realPrefix !== resolve(prefix)) real.push(join(realPrefix, ...parts.slice(firstGlob)));
1844
+
1845
+ let current: Array<{ path: string; viaLink: boolean }> = [{ path: realPrefix, viaLink: false }];
1846
+ for (let index = firstGlob; index < parts.length; index += 1) {
1847
+ const part = parts[index];
1848
+ // rm follows a link in any middle component, and in the last one only with a trailing slash.
1849
+ const followed = index < parts.length - 1 || followsLastName;
1850
+ const next: Array<{ path: string; viaLink: boolean }> = [];
1851
+ for (const entry of current) {
1852
+ if (performance.now() > budget.deadline) return null;
1853
+ if (!/[*?[]/.test(part)) {
1854
+ const path = join(entry.path, part);
1855
+ let viaLink = entry.viaLink;
1856
+ if (followed) {
1857
+ budget.remaining -= GLOB_WALK_LSTAT_COST;
1858
+ if (budget.remaining < 0) return null;
1859
+ try {
1860
+ viaLink = viaLink || lstatSync(path).isSymbolicLink();
1861
+ } catch {
1862
+ continue; // Nothing there, nothing to delete below it.
1863
+ }
1864
+ }
1865
+ next.push({ path, viaLink });
1866
+ continue;
1867
+ }
1868
+ let entries = budget.folders.get(entry.path);
1869
+ if (entries === undefined) {
1870
+ try {
1871
+ entries = readdirSync(entry.path, { withFileTypes: true });
1872
+ } catch {
1873
+ entries = null;
1874
+ }
1875
+ budget.folders.set(entry.path, entries);
1876
+ }
1877
+ if (entries === null) continue;
1878
+ budget.remaining -= entries.length;
1879
+ if (budget.remaining < 0) return null;
1880
+ for (const dirent of entries) {
1881
+ const name = dirent.name;
1882
+ if (name.startsWith(".") && !part.startsWith(".")) continue;
1883
+ if (!globMatches(part, name)) continue;
1884
+ budget.remaining -= 1;
1885
+ if (budget.remaining < 0) return null;
1886
+ next.push({ path: join(entry.path, name), viaLink: entry.viaLink || (followed && dirent.isSymbolicLink()) });
1887
+ }
1888
+ }
1889
+ current = next;
1890
+ }
1891
+
1892
+ for (const match of current) {
1893
+ if (!match.viaLink) continue;
1894
+ budget.linked += 1;
1895
+ if (budget.linked > MAX_GLOB_LINKED_LOCATIONS || performance.now() > budget.deadline) return null;
1896
+ const parent = realParentLocation(match.path);
1897
+ if (parent) real.push(parent);
1898
+ if (!followsLastName) continue;
1899
+ try {
1900
+ if (lstatSync(match.path).isSymbolicLink()) real.push(realpathSync(match.path));
1901
+ } catch {
1902
+ // A dangling link deletes nothing behind it.
1903
+ }
1904
+ }
1905
+ return real;
1906
+ }
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
+
1781
1999
  function isMissingPathError(error: unknown): boolean {
1782
2000
  return error instanceof Error && "code" in error && (error as NodeJS.ErrnoException).code === "ENOENT";
1783
2001
  }
@@ -2082,7 +2300,8 @@ function rsyncDeleteTargets(command: string): DestructiveShellTarget[] {
2082
2300
  afterOptions = true;
2083
2301
  continue;
2084
2302
  }
2085
- 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-"))) {
2086
2305
  hasDelete = true;
2087
2306
  continue;
2088
2307
  }
@@ -2109,15 +2328,43 @@ function findDestructiveTargets(command: string): DestructiveShellTarget[] {
2109
2328
 
2110
2329
  let hasDelete = false;
2111
2330
  let hasExecRm = false;
2331
+ // `find -H` follows a link given as a starting point, and `find -L` every link: a root that
2332
+ // is a link is then searched where it points, as `rm -rf link/` is (HAA-00119).
2333
+ let followsLinks = false;
2112
2334
  const roots: string[] = [];
2113
2335
 
2114
- for (let i = findIndex + 1; i < tokens.length; i += 1) {
2336
+ // Leading options come before the starting points: -H, -L and -P (also combined, `-LH`,
2337
+ // the last letter wins), GNU `-D <debug options>` and `-O<level>`, BSD flags and `-f <path>`,
2338
+ // and `--`. Any of them stopped the
2339
+ // scan for starting points before, so `find -- ~/.hasna/state -delete` fell back to the
2340
+ // working folder and was judged there (HAA-00119).
2341
+ let i = findIndex + 1;
2342
+ for (; i < tokens.length; i += 1) {
2115
2343
  const token = tokens[i];
2116
- if (token === "-H" || token === "-L" || token === "-P") continue;
2117
- if (token === "-O") {
2344
+ if (/^-[HLP]+$/.test(token)) {
2345
+ followsLinks = token[token.length - 1] !== "P";
2346
+ continue;
2347
+ }
2348
+ if (token === "-D" || token === "-O") {
2118
2349
  i += 1;
2119
2350
  continue;
2120
2351
  }
2352
+ if (/^-O\d+$/.test(token) || /^-D\S+$/.test(token)) continue;
2353
+ // BSD (macOS) find: -E, -X, -d, -s, -x are flags, and `-f <path>` names a starting point.
2354
+ if (/^-[EXdsx]+$/.test(token)) continue;
2355
+ if (token === "-f") {
2356
+ if (i + 1 < tokens.length) roots.push(tokens[i + 1]);
2357
+ i += 1;
2358
+ continue;
2359
+ }
2360
+ if (token === "--") {
2361
+ i += 1;
2362
+ break;
2363
+ }
2364
+ break;
2365
+ }
2366
+ for (; i < tokens.length; i += 1) {
2367
+ const token = tokens[i];
2121
2368
  if (token.startsWith("-") || token === "!" || token === "(" || token === ")") break;
2122
2369
  roots.push(token);
2123
2370
  }
@@ -2133,7 +2380,7 @@ function findDestructiveTargets(command: string): DestructiveShellTarget[] {
2133
2380
 
2134
2381
  if (hasDelete || hasExecRm) {
2135
2382
  targets.push(...(roots.length > 0 ? roots : ["."]).map((path) => destructiveTarget(
2136
- path,
2383
+ followsLinks && !/[\\/]$/.test(path) ? `${path}/` : path,
2137
2384
  hasDelete ? "find -delete" : "find -exec rm"
2138
2385
  )));
2139
2386
  }
@@ -2449,7 +2696,71 @@ function shellCommandLayers(command: string): { layers: ShellCommandLayer[]; tru
2449
2696
  // `rm` followed ANYWHERE by a recursive flag. Anchoring it to the very next token missed
2450
2697
  // `rm -f -r /*`, `rm -v -f -r /*`, `rm --one-file-system -rf /*` and `rm <path> -rf`, each of
2451
2698
  // which sailed past the oversized-command gate unanalysed.
2452
- 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
+ }
2453
2764
 
2454
2765
  /**
2455
2766
  * A command too deeply wrapped or too wide to analyse within the caps is refused when it
@@ -2462,7 +2773,7 @@ const DESTRUCTIVE_VERB = /(?:^|[^\w.-])(?:[\w/.-]*\/)?(?:rm\b[^;&|\n]*?(?:\s-[A-
2462
2773
  * past the cap and it returned continue.
2463
2774
  */
2464
2775
  function truncatedAnalysisBlockReason(command: string): string | null {
2465
- if (!DESTRUCTIVE_VERB.test(command)) return null;
2776
+ if (!looksDestructive(command)) return null;
2466
2777
  return [
2467
2778
  "Blocked: this command nests more shell wrappers than the safety guard can analyse,",
2468
2779
  "and it contains a recursive delete. The guard refuses rather than guess, because an",
@@ -2472,6 +2783,49 @@ function truncatedAnalysisBlockReason(command: string): string | null {
2472
2783
  ].join(" ");
2473
2784
  }
2474
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
+
2799
+ /**
2800
+ * The reason when the globs of one command match or scan more names on disk than the guard
2801
+ * checks within its time budget (HAA-00119).
2802
+ */
2803
+ function globWalkBlockReason(command: string): string | null {
2804
+ if (!looksDestructive(command)) return null;
2805
+ return [
2806
+ "Blocked: the globs in this recursive delete match or scan more names on disk than the safety",
2807
+ "guard can check for links within its time budget (a glob ending in `/`, or with a wildcard in a",
2808
+ "middle folder name, is followed through every link it matches). Name the folders explicitly,",
2809
+ "drop the trailing `/`, or split the delete into smaller commands.",
2810
+ ].join(" ");
2811
+ }
2812
+
2813
+ /**
2814
+ * The reason when too many `cd`s may not have moved the shell (a folder that does not exist
2815
+ * yet, or one an earlier segment may have removed), so the guard can no longer tell which
2816
+ * folder a later relative delete runs in.
2817
+ */
2818
+ function uncertainCdsBlockReason(command: string): string | null {
2819
+ if (!looksDestructive(command)) return null;
2820
+ return [
2821
+ "Blocked: this command changes folder too many times in ways that may not take effect",
2822
+ "(a `cd` into a folder that does not exist yet, or one removed earlier in the same command,",
2823
+ "followed by `;` or a new line rather than `&&`), so the safety guard cannot tell which folder",
2824
+ "the recursive delete runs in. Join the `cd`s with `&&` (cd a && cd b && rm -rf build),",
2825
+ "or write the delete target as an absolute path.",
2826
+ ].join(" ");
2827
+ }
2828
+
2475
2829
  /**
2476
2830
  * Remote layers run against another machine's filesystem, so a relative or cwd-derived
2477
2831
  * target here would be a guess. Absolute targets (including `~` / `$HOME` forms, which the
@@ -2514,8 +2868,20 @@ const MAX_ANALYSABLE_COMMAND_LENGTH = 32_000_000;
2514
2868
  */
2515
2869
  interface AnalysisState {
2516
2870
  degraded: boolean;
2871
+ /** Set when the degradation came from too many `cd`s that may not have moved the shell. */
2872
+ uncertainCds?: boolean;
2873
+ /** Set when matching globs on disk used up the command's walk budget. */
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;
2517
2879
  }
2518
2880
 
2881
+ /** A segment that removes or moves files, after which an existing folder may be gone. */
2882
+ const REMOVES_FILES = /(?:^|[\s/])(?:rm|rmdir|unlink|mv|trash|rename)(?=\s|$)|\s-delete(?=\s|$)/;
2883
+ const MAX_REMOVED_PATHS = 64;
2884
+
2519
2885
  /**
2520
2886
  * Segments of one layer paired with the working directories in effect when they run.
2521
2887
  *
@@ -2535,6 +2901,24 @@ function cwdTrackedSegments(command: string, baseCwd: string, nonEmptyNames: Rea
2535
2901
  // cds that may have failed widen the set of folders a later relative delete is judged in;
2536
2902
  // past this many the set is not tracked further and the analysis fails closed instead.
2537
2903
  let uncertainCds = 0;
2904
+ // Once an earlier segment has removed or moved files, a folder that exists now may be gone
2905
+ // when a later cd runs: `rmdir ~/work/build; cd ~/work/build; rm -rf state` (HAA-00119).
2906
+ // Every word of such a segment that is not an option is kept as a path it may remove (a glob
2907
+ // by its literal prefix); a cd into one of them, or below one, is then uncertain. Past
2908
+ // MAX_REMOVED_PATHS every later cd is.
2909
+ const removedPaths: string[] = [];
2910
+ let removedAny = false;
2911
+ // A removed glob covers a folder when each of its components matches the folder's component at
2912
+ // the same depth: `rm -f *.log` covers only folders under a name ending in .log, not packages/a.
2913
+ const coveredByRemoved = (dir: string, removed: string) => {
2914
+ if (!pathHasGlob(removed)) return isInsidePath(dir, removed);
2915
+ const removedParts = resolve(removed).split(sep);
2916
+ const dirParts = resolve(dir).split(sep);
2917
+ return dirParts.length >= removedParts.length &&
2918
+ removedParts.every((part, index) => globMatches(part, dirParts[index]));
2919
+ };
2920
+ const mayHaveBeenRemoved = (dir: string) =>
2921
+ removedAny || removedPaths.some((removed) => coveredByRemoved(dir, removed));
2538
2922
  let stack: Array<{ group: number; cwds: string[]; previous: string[]; dirStack: string[][]; explicit: boolean }> = [
2539
2923
  { group: 0, cwds: [baseCwd], previous: [baseCwd], dirStack: [], explicit: false },
2540
2924
  ];
@@ -2596,7 +2980,14 @@ function cwdTrackedSegments(command: string, baseCwd: string, nonEmptyNames: Rea
2596
2980
  if (verb === "pushd") frame.dirStack.push(frame.cwds);
2597
2981
  // Skip cd's own flags (-P, -L, --) to reach the directory operand.
2598
2982
  let i = 1;
2599
- 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
+ }
2600
2991
  const operand = tokens[i];
2601
2992
  const priorCwds = frame.cwds;
2602
2993
  cdOperations += 1;
@@ -2651,16 +3042,25 @@ function cwdTrackedSegments(command: string, baseCwd: string, nonEmptyNames: Rea
2651
3042
  next.add(current);
2652
3043
  continue;
2653
3044
  }
2654
- 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));
2655
3054
  if (collapsed !== null) next.add(resolveFrom(current, collapsed));
2656
3055
  }
2657
3056
  // A cd may fail (a missing folder, no permission) and the shell runs the next
2658
3057
  // command anyway unless the two are joined by `&&`: `cd /nonexistent; rm -rf state`
2659
3058
  // deletes `state` in the folder the shell was already in. Unless the cd is followed
2660
3059
  // by `&&`, or every folder it can land in exists as a directory right now, the
2661
- // folder before it stays a candidate too (HAA-00113).
3060
+ // folder before it stays a candidate too (HAA-00113). A folder that exists now does
3061
+ // not count once an earlier segment of the command removed or moved files (HAA-00119).
2662
3062
  const landed = [...next];
2663
- const mayFail = followedBy !== "&&" && uncertainCds <= MAX_UNCERTAIN_CDS && !landed.every((dir) => isExistingDirectory(dir));
3063
+ const mayFail = followedBy !== "&&" && uncertainCds <= MAX_UNCERTAIN_CDS && (landed.some(mayHaveBeenRemoved) || !landed.every((dir) => isExistingDirectory(dir)));
2664
3064
  let candidates = landed;
2665
3065
  if (mayFail) {
2666
3066
  uncertainCds += 1;
@@ -2668,6 +3068,7 @@ function cwdTrackedSegments(command: string, baseCwd: string, nonEmptyNames: Rea
2668
3068
  else candidates = [...new Set([...landed, ...priorCwds])];
2669
3069
  }
2670
3070
  if (candidates.length > MAX_CWD_VARIANTS) analysis.degraded = true;
3071
+ if (mayFail && analysis.degraded) analysis.uncertainCds = true;
2671
3072
  frame.cwds = candidates.slice(0, MAX_CWD_VARIANTS);
2672
3073
  if (isAbsolute(expandHome(operand)) || collapsed !== null) frame.explicit = true;
2673
3074
  }
@@ -2675,6 +3076,15 @@ function cwdTrackedSegments(command: string, baseCwd: string, nonEmptyNames: Rea
2675
3076
  return;
2676
3077
  }
2677
3078
 
3079
+ if (REMOVES_FILES.test(segment)) {
3080
+ // `mv a b` removes a, not b: the last word of a plain mv is its destination.
3081
+ const words = tokens.slice(1).filter((word) => !word.startsWith("-"));
3082
+ if ((verb === "mv" || verb?.endsWith("/mv")) && !tokens.some((word) => word === "-t" || word.startsWith("--target-directory"))) words.pop();
3083
+ for (const word of words) {
3084
+ for (const dir of frame.cwds) removedPaths.push(resolveFrom(dir, expandHome(word)));
3085
+ }
3086
+ if (removedPaths.length > MAX_REMOVED_PATHS) removedAny = true;
3087
+ }
2678
3088
  chunks.push({ segment, segmentIndex, cwds: frame.cwds, explicitCwd: frame.explicit });
2679
3089
  });
2680
3090
  return chunks;
@@ -2848,7 +3258,10 @@ export async function classifyDangerousOperation(input: CodewithHookInput): Prom
2848
3258
 
2849
3259
  if (input.tool_name === "Bash") {
2850
3260
  const command = getCommand(input);
2851
- const analysis: AnalysisState = { degraded: false };
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>();
2852
3265
 
2853
3266
  // A command large enough that merely tokenizing it blows the hook's 20s budget cannot be
2854
3267
  // analysed at all, and a timed-out hook fails open. 70k repetitions of `cd /<4KB>` is a
@@ -2885,17 +3298,47 @@ export async function classifyDangerousOperation(input: CodewithHookInput): Prom
2885
3298
  // in a parent folder (`cd ~/link && rm -rf state`, `rm -rf ~/link/state`, with
2886
3299
  // ~/link -> ~/.hasna) moves the delete into a protected root the text never names
2887
3300
  // (HAA-00113). rm removes the last name itself without following it.
2888
- 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
+ }
2889
3313
  // A trailing slash (`rm -rf ~/link/`) makes rm follow the last name too, so the delete
2890
3314
  // acts inside wherever that link finally points (HAA-00113 review).
2891
- const realTarget = /[\\/]\.?$/.test(target.path) ? realpathThroughExisting(targetPath) : null;
2892
- const judgedLocations = [targetPath];
2893
- for (const location of [realLocation, realTarget]) {
2894
- if (location && !judgedLocations.includes(location)) judgedLocations.push(location);
3315
+ const followsLastName = /[\\/]\.?$/.test(target.path);
3316
+ const realTarget = followsLastName ? realpathThroughExisting(kernelTarget ?? targetPath) : null;
3317
+ // A glob with a trailing slash (`rm -rf */`, `~/ln*/`) follows every link it matches, and
3318
+ // a glob in a middle component (`~/l*/state`) can pass through one, so those globs are
3319
+ // matched on disk and judged where each match really acts (HAA-00119). A glob only in the
3320
+ // last component is already covered by realParentLocation. One walk budget covers the
3321
+ // whole command; once it is spent the analysis fails closed rather than skipping the rest.
3322
+ let linkedMatches: string[] = [];
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);
3327
+ if (found === null) {
3328
+ analysis.degraded = true;
3329
+ analysis.globWalkSpent = true;
3330
+ } else linkedMatches = found;
3331
+ }
3332
+ const judgedLocations = new Set<string>([targetPath]);
3333
+ const kernelParent = kernelTarget ? realParentLocation(kernelTarget, realParents) : null;
3334
+ for (const location of [realLocation, realTarget, kernelTarget, kernelParent, ...linkedMatches]) {
3335
+ if (location) judgedLocations.add(location);
2895
3336
  }
2896
3337
  for (const judged of judgedLocations) {
2897
3338
  for (const rule of rulesFor(judged)) {
2898
- 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);
2899
3342
  if (threatensRule(ruleJudged, rule, currentManagedRepoRoot)) {
2900
3343
  // A session removing content of its own scratch folder (session id from the
2901
3344
  // harness, not the command) is not a threat to the ~/.hasna tree.
@@ -2943,7 +3386,16 @@ export async function classifyDangerousOperation(input: CodewithHookInput): Prom
2943
3386
  // exactly. Checked here rather than at each bound so there is ONE fail-closed answer:
2944
3387
  // three bounds that each invented their own fallback all became root wipes.
2945
3388
  if (analysis.degraded) {
2946
- const reason = 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);
2947
3399
  if (reason) {
2948
3400
  return { block: true, operation: "unanalysable command", reason };
2949
3401
  }