@hasna/hooks 0.15.2 → 0.15.3

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.3",
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) => {
@@ -1778,6 +1782,115 @@ function realParentLocation(path: string): string | null {
1778
1782
  return real === resolved ? null : real;
1779
1783
  }
1780
1784
 
1785
+ /**
1786
+ * One budget per command for matching globs on disk (HAA-00119). The hook's own timeout fails
1787
+ * open, so a command whose globs would take long to check must be refused instead:
1788
+ * - every name read from a folder and every match cost one unit, and an lstat of a literal
1789
+ * component below a glob GLOB_WALK_LSTAT_COST, out of GLOB_WALK_BUDGET; a folder is read from
1790
+ * disk only once per command;
1791
+ * - only a match with a symbolic link on its way is resolved and judged, at most
1792
+ * MAX_GLOB_LINKED_LOCATIONS per command (resolving and judging is the expensive part);
1793
+ * - the whole walk stops at GLOB_WALK_DEADLINE_MS, measured from the start of the command's check.
1794
+ * Running out of any of them fails closed.
1795
+ */
1796
+ const GLOB_WALK_BUDGET = 200_000;
1797
+ const GLOB_WALK_LSTAT_COST = 8;
1798
+ const MAX_GLOB_LINKED_LOCATIONS = 256;
1799
+ const GLOB_WALK_DEADLINE_MS = 3_000;
1800
+
1801
+ interface GlobWalkBudget {
1802
+ remaining: number;
1803
+ linked: number;
1804
+ deadline: number;
1805
+ folders: Map<string, Dirent[] | null>;
1806
+ }
1807
+
1808
+ function newGlobWalkBudget(): GlobWalkBudget {
1809
+ return { remaining: GLOB_WALK_BUDGET, linked: 0, deadline: performance.now() + GLOB_WALK_DEADLINE_MS, folders: new Map() };
1810
+ }
1811
+
1812
+ /**
1813
+ * Where a glob delete really acts when a link lies on the way to what it matches, as the shell
1814
+ * would expand it now (hidden names only for a pattern that starts with `.`):
1815
+ * - the pattern itself under the real location of its literal prefix (macOS /tmp is a link);
1816
+ * - for each match reached through a link in or below the first globbed component, its real
1817
+ * parent location (`rm -rf ~/l*​/state` through ~/lnhasna -> ~/.hasna), and, when the
1818
+ * target ends in a slash, the real location of a matched link, which rm then follows
1819
+ * (`rm -rf *​/`).
1820
+ * Null once the command's walk budget is spent, so the caller fails closed (HAA-00119).
1821
+ */
1822
+ function realLocationsOfGlobMatches(pattern: string, followsLastName: boolean, budget: GlobWalkBudget): string[] | null {
1823
+ const parts = resolve(pattern).split(sep).filter(Boolean);
1824
+ const firstGlob = parts.findIndex((part) => /[*?[]/.test(part));
1825
+ if (firstGlob === -1) return [];
1826
+ const prefix = sep + parts.slice(0, firstGlob).join(sep);
1827
+ const realPrefix = realpathThroughExisting(prefix) ?? prefix;
1828
+ const real: string[] = [];
1829
+ if (realPrefix !== resolve(prefix)) real.push(join(realPrefix, ...parts.slice(firstGlob)));
1830
+
1831
+ let current: Array<{ path: string; viaLink: boolean }> = [{ path: realPrefix, viaLink: false }];
1832
+ for (let index = firstGlob; index < parts.length; index += 1) {
1833
+ const part = parts[index];
1834
+ // rm follows a link in any middle component, and in the last one only with a trailing slash.
1835
+ const followed = index < parts.length - 1 || followsLastName;
1836
+ const next: Array<{ path: string; viaLink: boolean }> = [];
1837
+ for (const entry of current) {
1838
+ if (performance.now() > budget.deadline) return null;
1839
+ if (!/[*?[]/.test(part)) {
1840
+ const path = join(entry.path, part);
1841
+ let viaLink = entry.viaLink;
1842
+ if (followed) {
1843
+ budget.remaining -= GLOB_WALK_LSTAT_COST;
1844
+ if (budget.remaining < 0) return null;
1845
+ try {
1846
+ viaLink = viaLink || lstatSync(path).isSymbolicLink();
1847
+ } catch {
1848
+ continue; // Nothing there, nothing to delete below it.
1849
+ }
1850
+ }
1851
+ next.push({ path, viaLink });
1852
+ continue;
1853
+ }
1854
+ let entries = budget.folders.get(entry.path);
1855
+ if (entries === undefined) {
1856
+ try {
1857
+ entries = readdirSync(entry.path, { withFileTypes: true });
1858
+ } catch {
1859
+ entries = null;
1860
+ }
1861
+ budget.folders.set(entry.path, entries);
1862
+ }
1863
+ if (entries === null) continue;
1864
+ budget.remaining -= entries.length;
1865
+ if (budget.remaining < 0) return null;
1866
+ for (const dirent of entries) {
1867
+ const name = dirent.name;
1868
+ if (name.startsWith(".") && !part.startsWith(".")) continue;
1869
+ if (!globMatches(part, name)) continue;
1870
+ budget.remaining -= 1;
1871
+ if (budget.remaining < 0) return null;
1872
+ next.push({ path: join(entry.path, name), viaLink: entry.viaLink || (followed && dirent.isSymbolicLink()) });
1873
+ }
1874
+ }
1875
+ current = next;
1876
+ }
1877
+
1878
+ for (const match of current) {
1879
+ if (!match.viaLink) continue;
1880
+ budget.linked += 1;
1881
+ if (budget.linked > MAX_GLOB_LINKED_LOCATIONS || performance.now() > budget.deadline) return null;
1882
+ const parent = realParentLocation(match.path);
1883
+ if (parent) real.push(parent);
1884
+ if (!followsLastName) continue;
1885
+ try {
1886
+ if (lstatSync(match.path).isSymbolicLink()) real.push(realpathSync(match.path));
1887
+ } catch {
1888
+ // A dangling link deletes nothing behind it.
1889
+ }
1890
+ }
1891
+ return real;
1892
+ }
1893
+
1781
1894
  function isMissingPathError(error: unknown): boolean {
1782
1895
  return error instanceof Error && "code" in error && (error as NodeJS.ErrnoException).code === "ENOENT";
1783
1896
  }
@@ -2109,15 +2222,43 @@ function findDestructiveTargets(command: string): DestructiveShellTarget[] {
2109
2222
 
2110
2223
  let hasDelete = false;
2111
2224
  let hasExecRm = false;
2225
+ // `find -H` follows a link given as a starting point, and `find -L` every link: a root that
2226
+ // is a link is then searched where it points, as `rm -rf link/` is (HAA-00119).
2227
+ let followsLinks = false;
2112
2228
  const roots: string[] = [];
2113
2229
 
2114
- for (let i = findIndex + 1; i < tokens.length; i += 1) {
2230
+ // Leading options come before the starting points: -H, -L and -P (also combined, `-LH`,
2231
+ // the last letter wins), GNU `-D <debug options>` and `-O<level>`, BSD flags and `-f <path>`,
2232
+ // and `--`. Any of them stopped the
2233
+ // scan for starting points before, so `find -- ~/.hasna/state -delete` fell back to the
2234
+ // working folder and was judged there (HAA-00119).
2235
+ let i = findIndex + 1;
2236
+ for (; i < tokens.length; i += 1) {
2115
2237
  const token = tokens[i];
2116
- if (token === "-H" || token === "-L" || token === "-P") continue;
2117
- if (token === "-O") {
2238
+ if (/^-[HLP]+$/.test(token)) {
2239
+ followsLinks = token[token.length - 1] !== "P";
2240
+ continue;
2241
+ }
2242
+ if (token === "-D" || token === "-O") {
2118
2243
  i += 1;
2119
2244
  continue;
2120
2245
  }
2246
+ if (/^-O\d+$/.test(token) || /^-D\S+$/.test(token)) continue;
2247
+ // BSD (macOS) find: -E, -X, -d, -s, -x are flags, and `-f <path>` names a starting point.
2248
+ if (/^-[EXdsx]+$/.test(token)) continue;
2249
+ if (token === "-f") {
2250
+ if (i + 1 < tokens.length) roots.push(tokens[i + 1]);
2251
+ i += 1;
2252
+ continue;
2253
+ }
2254
+ if (token === "--") {
2255
+ i += 1;
2256
+ break;
2257
+ }
2258
+ break;
2259
+ }
2260
+ for (; i < tokens.length; i += 1) {
2261
+ const token = tokens[i];
2121
2262
  if (token.startsWith("-") || token === "!" || token === "(" || token === ")") break;
2122
2263
  roots.push(token);
2123
2264
  }
@@ -2133,7 +2274,7 @@ function findDestructiveTargets(command: string): DestructiveShellTarget[] {
2133
2274
 
2134
2275
  if (hasDelete || hasExecRm) {
2135
2276
  targets.push(...(roots.length > 0 ? roots : ["."]).map((path) => destructiveTarget(
2136
- path,
2277
+ followsLinks && !/[\\/]$/.test(path) ? `${path}/` : path,
2137
2278
  hasDelete ? "find -delete" : "find -exec rm"
2138
2279
  )));
2139
2280
  }
@@ -2472,6 +2613,36 @@ function truncatedAnalysisBlockReason(command: string): string | null {
2472
2613
  ].join(" ");
2473
2614
  }
2474
2615
 
2616
+ /**
2617
+ * The reason when the globs of one command match or scan more names on disk than the guard
2618
+ * checks within its time budget (HAA-00119).
2619
+ */
2620
+ function globWalkBlockReason(command: string): string | null {
2621
+ if (!DESTRUCTIVE_VERB.test(command)) return null;
2622
+ return [
2623
+ "Blocked: the globs in this recursive delete match or scan more names on disk than the safety",
2624
+ "guard can check for links within its time budget (a glob ending in `/`, or with a wildcard in a",
2625
+ "middle folder name, is followed through every link it matches). Name the folders explicitly,",
2626
+ "drop the trailing `/`, or split the delete into smaller commands.",
2627
+ ].join(" ");
2628
+ }
2629
+
2630
+ /**
2631
+ * The reason when too many `cd`s may not have moved the shell (a folder that does not exist
2632
+ * yet, or one an earlier segment may have removed), so the guard can no longer tell which
2633
+ * folder a later relative delete runs in.
2634
+ */
2635
+ function uncertainCdsBlockReason(command: string): string | null {
2636
+ if (!DESTRUCTIVE_VERB.test(command)) return null;
2637
+ return [
2638
+ "Blocked: this command changes folder too many times in ways that may not take effect",
2639
+ "(a `cd` into a folder that does not exist yet, or one removed earlier in the same command,",
2640
+ "followed by `;` or a new line rather than `&&`), so the safety guard cannot tell which folder",
2641
+ "the recursive delete runs in. Join the `cd`s with `&&` (cd a && cd b && rm -rf build),",
2642
+ "or write the delete target as an absolute path.",
2643
+ ].join(" ");
2644
+ }
2645
+
2475
2646
  /**
2476
2647
  * Remote layers run against another machine's filesystem, so a relative or cwd-derived
2477
2648
  * target here would be a guess. Absolute targets (including `~` / `$HOME` forms, which the
@@ -2514,8 +2685,16 @@ const MAX_ANALYSABLE_COMMAND_LENGTH = 32_000_000;
2514
2685
  */
2515
2686
  interface AnalysisState {
2516
2687
  degraded: boolean;
2688
+ /** Set when the degradation came from too many `cd`s that may not have moved the shell. */
2689
+ uncertainCds?: boolean;
2690
+ /** Set when matching globs on disk used up the command's walk budget. */
2691
+ globWalkSpent?: boolean;
2517
2692
  }
2518
2693
 
2694
+ /** A segment that removes or moves files, after which an existing folder may be gone. */
2695
+ const REMOVES_FILES = /(?:^|[\s/])(?:rm|rmdir|unlink|mv|trash|rename)(?=\s|$)|\s-delete(?=\s|$)/;
2696
+ const MAX_REMOVED_PATHS = 64;
2697
+
2519
2698
  /**
2520
2699
  * Segments of one layer paired with the working directories in effect when they run.
2521
2700
  *
@@ -2535,6 +2714,24 @@ function cwdTrackedSegments(command: string, baseCwd: string, nonEmptyNames: Rea
2535
2714
  // cds that may have failed widen the set of folders a later relative delete is judged in;
2536
2715
  // past this many the set is not tracked further and the analysis fails closed instead.
2537
2716
  let uncertainCds = 0;
2717
+ // Once an earlier segment has removed or moved files, a folder that exists now may be gone
2718
+ // when a later cd runs: `rmdir ~/work/build; cd ~/work/build; rm -rf state` (HAA-00119).
2719
+ // Every word of such a segment that is not an option is kept as a path it may remove (a glob
2720
+ // by its literal prefix); a cd into one of them, or below one, is then uncertain. Past
2721
+ // MAX_REMOVED_PATHS every later cd is.
2722
+ const removedPaths: string[] = [];
2723
+ let removedAny = false;
2724
+ // A removed glob covers a folder when each of its components matches the folder's component at
2725
+ // the same depth: `rm -f *.log` covers only folders under a name ending in .log, not packages/a.
2726
+ const coveredByRemoved = (dir: string, removed: string) => {
2727
+ if (!pathHasGlob(removed)) return isInsidePath(dir, removed);
2728
+ const removedParts = resolve(removed).split(sep);
2729
+ const dirParts = resolve(dir).split(sep);
2730
+ return dirParts.length >= removedParts.length &&
2731
+ removedParts.every((part, index) => globMatches(part, dirParts[index]));
2732
+ };
2733
+ const mayHaveBeenRemoved = (dir: string) =>
2734
+ removedAny || removedPaths.some((removed) => coveredByRemoved(dir, removed));
2538
2735
  let stack: Array<{ group: number; cwds: string[]; previous: string[]; dirStack: string[][]; explicit: boolean }> = [
2539
2736
  { group: 0, cwds: [baseCwd], previous: [baseCwd], dirStack: [], explicit: false },
2540
2737
  ];
@@ -2658,9 +2855,10 @@ function cwdTrackedSegments(command: string, baseCwd: string, nonEmptyNames: Rea
2658
2855
  // command anyway unless the two are joined by `&&`: `cd /nonexistent; rm -rf state`
2659
2856
  // deletes `state` in the folder the shell was already in. Unless the cd is followed
2660
2857
  // 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).
2858
+ // folder before it stays a candidate too (HAA-00113). A folder that exists now does
2859
+ // not count once an earlier segment of the command removed or moved files (HAA-00119).
2662
2860
  const landed = [...next];
2663
- const mayFail = followedBy !== "&&" && uncertainCds <= MAX_UNCERTAIN_CDS && !landed.every((dir) => isExistingDirectory(dir));
2861
+ const mayFail = followedBy !== "&&" && uncertainCds <= MAX_UNCERTAIN_CDS && (landed.some(mayHaveBeenRemoved) || !landed.every((dir) => isExistingDirectory(dir)));
2664
2862
  let candidates = landed;
2665
2863
  if (mayFail) {
2666
2864
  uncertainCds += 1;
@@ -2668,6 +2866,7 @@ function cwdTrackedSegments(command: string, baseCwd: string, nonEmptyNames: Rea
2668
2866
  else candidates = [...new Set([...landed, ...priorCwds])];
2669
2867
  }
2670
2868
  if (candidates.length > MAX_CWD_VARIANTS) analysis.degraded = true;
2869
+ if (mayFail && analysis.degraded) analysis.uncertainCds = true;
2671
2870
  frame.cwds = candidates.slice(0, MAX_CWD_VARIANTS);
2672
2871
  if (isAbsolute(expandHome(operand)) || collapsed !== null) frame.explicit = true;
2673
2872
  }
@@ -2675,6 +2874,15 @@ function cwdTrackedSegments(command: string, baseCwd: string, nonEmptyNames: Rea
2675
2874
  return;
2676
2875
  }
2677
2876
 
2877
+ if (REMOVES_FILES.test(segment)) {
2878
+ // `mv a b` removes a, not b: the last word of a plain mv is its destination.
2879
+ const words = tokens.slice(1).filter((word) => !word.startsWith("-"));
2880
+ if ((verb === "mv" || verb?.endsWith("/mv")) && !tokens.some((word) => word === "-t" || word.startsWith("--target-directory"))) words.pop();
2881
+ for (const word of words) {
2882
+ for (const dir of frame.cwds) removedPaths.push(resolveFrom(dir, expandHome(word)));
2883
+ }
2884
+ if (removedPaths.length > MAX_REMOVED_PATHS) removedAny = true;
2885
+ }
2678
2886
  chunks.push({ segment, segmentIndex, cwds: frame.cwds, explicitCwd: frame.explicit });
2679
2887
  });
2680
2888
  return chunks;
@@ -2849,6 +3057,7 @@ export async function classifyDangerousOperation(input: CodewithHookInput): Prom
2849
3057
  if (input.tool_name === "Bash") {
2850
3058
  const command = getCommand(input);
2851
3059
  const analysis: AnalysisState = { degraded: false };
3060
+ const globWalk = newGlobWalkBudget();
2852
3061
 
2853
3062
  // A command large enough that merely tokenizing it blows the hook's 20s budget cannot be
2854
3063
  // analysed at all, and a timed-out hook fails open. 70k repetitions of `cd /<4KB>` is a
@@ -2888,10 +3097,25 @@ export async function classifyDangerousOperation(input: CodewithHookInput): Prom
2888
3097
  const realLocation = realParentLocation(targetPath);
2889
3098
  // A trailing slash (`rm -rf ~/link/`) makes rm follow the last name too, so the delete
2890
3099
  // 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);
3100
+ const followsLastName = /[\\/]\.?$/.test(target.path);
3101
+ const realTarget = followsLastName ? realpathThroughExisting(targetPath) : null;
3102
+ // A glob with a trailing slash (`rm -rf */`, `~/ln*/`) follows every link it matches, and
3103
+ // a glob in a middle component (`~/l*/state`) can pass through one, so those globs are
3104
+ // matched on disk and judged where each match really acts (HAA-00119). A glob only in the
3105
+ // last component is already covered by realParentLocation. One walk budget covers the
3106
+ // whole command; once it is spent the analysis fails closed rather than skipping the rest.
3107
+ 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);
3111
+ if (found === null) {
3112
+ analysis.degraded = true;
3113
+ analysis.globWalkSpent = true;
3114
+ } else linkedMatches = found;
3115
+ }
3116
+ const judgedLocations = new Set<string>([targetPath]);
3117
+ for (const location of [realLocation, realTarget, ...linkedMatches]) {
3118
+ if (location) judgedLocations.add(location);
2895
3119
  }
2896
3120
  for (const judged of judgedLocations) {
2897
3121
  for (const rule of rulesFor(judged)) {
@@ -2943,7 +3167,9 @@ export async function classifyDangerousOperation(input: CodewithHookInput): Prom
2943
3167
  // exactly. Checked here rather than at each bound so there is ONE fail-closed answer:
2944
3168
  // three bounds that each invented their own fallback all became root wipes.
2945
3169
  if (analysis.degraded) {
2946
- const reason = truncatedAnalysisBlockReason(command);
3170
+ const reason = analysis.globWalkSpent
3171
+ ? globWalkBlockReason(command)
3172
+ : analysis.uncertainCds ? uncertainCdsBlockReason(command) : truncatedAnalysisBlockReason(command);
2947
3173
  if (reason) {
2948
3174
  return { block: true, operation: "unanalysable command", reason };
2949
3175
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hasna/hooks",
3
- "version": "0.15.2",
3
+ "version": "0.15.3",
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": {