@hasna/hooks 0.15.1 → 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.
|
|
4
|
+
"version": "0.15.3",
|
|
5
5
|
"hooks": {
|
|
6
6
|
"affected-tests": {
|
|
7
7
|
"version": "0.1.0",
|
|
@@ -176,7 +176,7 @@
|
|
|
176
176
|
"pre-bash": {
|
|
177
177
|
"version": "0.1.0",
|
|
178
178
|
"script": "hooks/pre-bash/src/hook.ts",
|
|
179
|
-
"sha256": "
|
|
179
|
+
"sha256": "76bd1336efd61eaf8497f93df017236f4382fba664fdb921699c2bf51a05d196"
|
|
180
180
|
},
|
|
181
181
|
"precompact": {
|
|
182
182
|
"version": "0.1.0",
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, 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
|
|
|
@@ -149,8 +149,11 @@ export interface GitCommandInfo {
|
|
|
149
149
|
function splitShellSegmentsPass(
|
|
150
150
|
command: string,
|
|
151
151
|
atomicSubstitutions: boolean
|
|
152
|
-
): { segments: string[]; isolation: boolean[]; depths: number[]; groups: number[]; piped: boolean[]; shortCircuit: boolean[]; unterminated: boolean } {
|
|
152
|
+
): { segments: string[]; isolation: boolean[]; depths: number[]; groups: number[]; piped: boolean[]; shortCircuit: boolean[]; followedBy: string[]; unterminated: boolean } {
|
|
153
153
|
const segments: string[] = [];
|
|
154
|
+
// The separator after each segment: ";", "&", "&&", "||", "|", "(", ")", "\n" or "end".
|
|
155
|
+
// The `&` of a redirection such as `2>&1` is not a separator and stays in the segment.
|
|
156
|
+
const followedBy: string[] = [];
|
|
154
157
|
const isolation: boolean[] = [];
|
|
155
158
|
const depths: number[] = [];
|
|
156
159
|
const groups: number[] = [];
|
|
@@ -170,9 +173,10 @@ function splitShellSegmentsPass(
|
|
|
170
173
|
let groupCounter = 0;
|
|
171
174
|
const groupStack: number[] = [0];
|
|
172
175
|
|
|
173
|
-
const flush = (nextSeparator: string | null) => {
|
|
176
|
+
const flush = (nextSeparator: string | null, separatorToken: string = nextSeparator ?? "end") => {
|
|
174
177
|
if (current.trim()) {
|
|
175
178
|
segments.push(current.trim());
|
|
179
|
+
followedBy.push(separatorToken);
|
|
176
180
|
// A stage of a pipeline runs in its own process, as does anything inside `( … )`.
|
|
177
181
|
isolation.push(parenDepth > 0 || pipedFromPrevious || nextSeparator === "|");
|
|
178
182
|
depths.push(parenDepth);
|
|
@@ -235,8 +239,16 @@ function splitShellSegmentsPass(
|
|
|
235
239
|
}
|
|
236
240
|
if (ch === ";" || ch === "|" || ch === "&" || ch === "(" || ch === ")" || ch === "\n") {
|
|
237
241
|
const doubled = (ch === "|" || ch === "&") && command[i + 1] === ch;
|
|
242
|
+
// A single `&` inside a redirection (`2>&1`, `>&2`, `<&0`, `&>file`, `&>>file`) is not a
|
|
243
|
+
// separator at all: it stays inside the segment, so a real background `&` after it
|
|
244
|
+
// (`cd /tmp >/dev/null 2>&1 & rm -rf x`) still ends the cd's own segment (HAA-00113).
|
|
245
|
+
// An escaped `\>` is a literal character, not a redirection.
|
|
246
|
+
if (ch === "&" && !doubled && (/(^|[^\\])(\\\\)*[<>]$/.test(current) || command[i + 1] === ">")) {
|
|
247
|
+
current += ch;
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
238
250
|
// `||` and `&&` are sequencing, not a pipe.
|
|
239
|
-
flush(ch === "|" && !doubled ? "|" : null);
|
|
251
|
+
flush(ch === "|" && !doubled ? "|" : null, doubled ? ch + ch : ch);
|
|
240
252
|
// `a && X=1` and `a || X=1` run X= only if the left side decided so.
|
|
241
253
|
precededByShortCircuit = doubled && (ch === "|" || ch === "&");
|
|
242
254
|
if (ch === "(") {
|
|
@@ -254,7 +266,7 @@ function splitShellSegmentsPass(
|
|
|
254
266
|
}
|
|
255
267
|
|
|
256
268
|
flush(null);
|
|
257
|
-
return { segments, isolation, depths, groups, piped: pipedFlags, shortCircuit: shortCircuitFlags, unterminated: substitutionDepth > 0 || inBacktick };
|
|
269
|
+
return { segments, isolation, depths, groups, piped: pipedFlags, shortCircuit: shortCircuitFlags, followedBy, unterminated: substitutionDepth > 0 || inBacktick };
|
|
258
270
|
}
|
|
259
271
|
|
|
260
272
|
function splitShellSegments(command: string): string[] {
|
|
@@ -272,6 +284,12 @@ interface ShellSegment {
|
|
|
272
284
|
piped: boolean;
|
|
273
285
|
/** Reached only via `&&` / `||`, so whether it ran depends on the previous command. */
|
|
274
286
|
shortCircuit: boolean;
|
|
287
|
+
/**
|
|
288
|
+
* The separator after this segment: ";", "&", "&&", "||", "|", "(", ")", "\n" or "end".
|
|
289
|
+
* A `cd` followed by a single "&" runs in the background and moves nothing; one followed
|
|
290
|
+
* by anything but "&&" may have failed while the next command still runs.
|
|
291
|
+
*/
|
|
292
|
+
followedBy: string;
|
|
275
293
|
/**
|
|
276
294
|
* True when the segment runs in a subshell `( … )` or as a stage of a pipeline. A `cd`
|
|
277
295
|
* there affects only that child process, so treating it as persistent silently moves the
|
|
@@ -304,6 +322,7 @@ function splitShellSegmentsUncached(command: string): ShellSegment[] {
|
|
|
304
322
|
group: chosen.groups[index] ?? 0,
|
|
305
323
|
piped: chosen.piped[index] ?? false,
|
|
306
324
|
shortCircuit: chosen.shortCircuit[index] ?? false,
|
|
325
|
+
followedBy: chosen.followedBy[index] ?? "end",
|
|
307
326
|
isolated: chosen.isolation[index] ?? false,
|
|
308
327
|
}));
|
|
309
328
|
}
|
|
@@ -1584,10 +1603,21 @@ const LEADING_CD = /^cd\s+(?:\/|~\/)[A-Za-z0-9._@+\/-]*$/;
|
|
|
1584
1603
|
*/
|
|
1585
1604
|
export function ownScratchCommandAllowed(command: string): boolean {
|
|
1586
1605
|
if (PARENT_COMPONENT.test(command) || HIDDEN_COMMAND.test(command) || /[()]/.test(command)) return false;
|
|
1587
|
-
|
|
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);
|
|
1588
1611
|
if (pieces.length > 0 && LEADING_CD.test(pieces[0])) pieces.shift();
|
|
1589
1612
|
if (pieces.length === 0) return false;
|
|
1590
|
-
return pieces.every((piece) =>
|
|
1613
|
+
return pieces.every((piece) => {
|
|
1614
|
+
const words = piece.split(/\s+/);
|
|
1615
|
+
if (!DELETE_ONLY_WORD.test(words[0])) return false;
|
|
1616
|
+
// `rmdir -p <own>/b` removes <own>/b and then every empty parent, the session folder
|
|
1617
|
+
// itself included, which the exception refuses (HAA-00114).
|
|
1618
|
+
if (words[0].endsWith("rmdir") && words.slice(1).some((word) => word === "--parents" || /^-[A-Za-z]*p[A-Za-z]*$/.test(word))) return false;
|
|
1619
|
+
return true;
|
|
1620
|
+
});
|
|
1591
1621
|
}
|
|
1592
1622
|
|
|
1593
1623
|
/**
|
|
@@ -1713,6 +1743,154 @@ function realpathThroughExisting(path: string): string | null {
|
|
|
1713
1743
|
}
|
|
1714
1744
|
}
|
|
1715
1745
|
|
|
1746
|
+
/** Uncertain cds (that may have failed) tracked before the analysis fails closed. */
|
|
1747
|
+
const MAX_UNCERTAIN_CDS = 8;
|
|
1748
|
+
|
|
1749
|
+
/**
|
|
1750
|
+
* A real location re-spelled under a protected root as the rules write it: when the root
|
|
1751
|
+
* itself sits behind a link (macOS /tmp is /private/tmp), a real path inside the root's real
|
|
1752
|
+
* location is mapped back under the root's own spelling, so the rule still recognises it.
|
|
1753
|
+
*/
|
|
1754
|
+
function inRuleSpelling(realPath: string, root: string): string {
|
|
1755
|
+
const realRoot = realpathThroughExisting(root);
|
|
1756
|
+
if (!realRoot || realRoot === resolve(root)) return realPath;
|
|
1757
|
+
if (realPath === realRoot) return resolve(root);
|
|
1758
|
+
return isInsidePath(realPath, realRoot) ? join(resolve(root), relative(realRoot, realPath)) : realPath;
|
|
1759
|
+
}
|
|
1760
|
+
|
|
1761
|
+
/** True only for a path that exists now and is a directory (links followed, as cd does). */
|
|
1762
|
+
function isExistingDirectory(path: string): boolean {
|
|
1763
|
+
try {
|
|
1764
|
+
return statSync(path).isDirectory();
|
|
1765
|
+
} catch {
|
|
1766
|
+
return false;
|
|
1767
|
+
}
|
|
1768
|
+
}
|
|
1769
|
+
|
|
1770
|
+
/**
|
|
1771
|
+
* Where an `rm` of `path` really acts: the real location of its parent folder (every link
|
|
1772
|
+
* there followed, as the kernel does) plus its own last name, which rm removes without
|
|
1773
|
+
* following. Null when the parent cannot be resolved, or when it equals `path`.
|
|
1774
|
+
*/
|
|
1775
|
+
function realParentLocation(path: string): string | null {
|
|
1776
|
+
const resolved = resolve(path);
|
|
1777
|
+
const parent = dirname(resolved);
|
|
1778
|
+
if (parent === resolved) return null;
|
|
1779
|
+
const realParent = realpathThroughExisting(parent);
|
|
1780
|
+
if (!realParent) return null;
|
|
1781
|
+
const real = join(realParent, basename(resolved));
|
|
1782
|
+
return real === resolved ? null : real;
|
|
1783
|
+
}
|
|
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
|
+
|
|
1716
1894
|
function isMissingPathError(error: unknown): boolean {
|
|
1717
1895
|
return error instanceof Error && "code" in error && (error as NodeJS.ErrnoException).code === "ENOENT";
|
|
1718
1896
|
}
|
|
@@ -2044,15 +2222,43 @@ function findDestructiveTargets(command: string): DestructiveShellTarget[] {
|
|
|
2044
2222
|
|
|
2045
2223
|
let hasDelete = false;
|
|
2046
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;
|
|
2047
2228
|
const roots: string[] = [];
|
|
2048
2229
|
|
|
2049
|
-
|
|
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) {
|
|
2050
2237
|
const token = tokens[i];
|
|
2051
|
-
if (token
|
|
2052
|
-
|
|
2238
|
+
if (/^-[HLP]+$/.test(token)) {
|
|
2239
|
+
followsLinks = token[token.length - 1] !== "P";
|
|
2240
|
+
continue;
|
|
2241
|
+
}
|
|
2242
|
+
if (token === "-D" || token === "-O") {
|
|
2053
2243
|
i += 1;
|
|
2054
2244
|
continue;
|
|
2055
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];
|
|
2056
2262
|
if (token.startsWith("-") || token === "!" || token === "(" || token === ")") break;
|
|
2057
2263
|
roots.push(token);
|
|
2058
2264
|
}
|
|
@@ -2068,7 +2274,7 @@ function findDestructiveTargets(command: string): DestructiveShellTarget[] {
|
|
|
2068
2274
|
|
|
2069
2275
|
if (hasDelete || hasExecRm) {
|
|
2070
2276
|
targets.push(...(roots.length > 0 ? roots : ["."]).map((path) => destructiveTarget(
|
|
2071
|
-
path,
|
|
2277
|
+
followsLinks && !/[\\/]$/.test(path) ? `${path}/` : path,
|
|
2072
2278
|
hasDelete ? "find -delete" : "find -exec rm"
|
|
2073
2279
|
)));
|
|
2074
2280
|
}
|
|
@@ -2407,6 +2613,36 @@ function truncatedAnalysisBlockReason(command: string): string | null {
|
|
|
2407
2613
|
].join(" ");
|
|
2408
2614
|
}
|
|
2409
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
|
+
|
|
2410
2646
|
/**
|
|
2411
2647
|
* Remote layers run against another machine's filesystem, so a relative or cwd-derived
|
|
2412
2648
|
* target here would be a guess. Absolute targets (including `~` / `$HOME` forms, which the
|
|
@@ -2449,8 +2685,16 @@ const MAX_ANALYSABLE_COMMAND_LENGTH = 32_000_000;
|
|
|
2449
2685
|
*/
|
|
2450
2686
|
interface AnalysisState {
|
|
2451
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;
|
|
2452
2692
|
}
|
|
2453
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
|
+
|
|
2454
2698
|
/**
|
|
2455
2699
|
* Segments of one layer paired with the working directories in effect when they run.
|
|
2456
2700
|
*
|
|
@@ -2467,6 +2711,27 @@ function cwdTrackedSegments(command: string, baseCwd: string, nonEmptyNames: Rea
|
|
|
2467
2711
|
// outright left `(cd / && rm -rf *)`, the standard "cd without moving my shell" idiom,
|
|
2468
2712
|
// completely unguarded. Depth 0 is the parent shell.
|
|
2469
2713
|
let cdOperations = 0;
|
|
2714
|
+
// cds that may have failed widen the set of folders a later relative delete is judged in;
|
|
2715
|
+
// past this many the set is not tracked further and the analysis fails closed instead.
|
|
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));
|
|
2470
2735
|
let stack: Array<{ group: number; cwds: string[]; previous: string[]; dirStack: string[][]; explicit: boolean }> = [
|
|
2471
2736
|
{ group: 0, cwds: [baseCwd], previous: [baseCwd], dirStack: [], explicit: false },
|
|
2472
2737
|
];
|
|
@@ -2489,7 +2754,7 @@ function cwdTrackedSegments(command: string, baseCwd: string, nonEmptyNames: Rea
|
|
|
2489
2754
|
return stack[depth];
|
|
2490
2755
|
};
|
|
2491
2756
|
|
|
2492
|
-
splitShellSegmentsDetailed(command).forEach(({ text: segment, depth, group, piped, shortCircuit }, segmentIndex) => {
|
|
2757
|
+
splitShellSegmentsDetailed(command).forEach(({ text: segment, depth, group, piped, shortCircuit, followedBy }, segmentIndex) => {
|
|
2493
2758
|
const frame = frameFor(depth, group);
|
|
2494
2759
|
// A leading `{` from a brace group is not part of the command.
|
|
2495
2760
|
const tokens = shellWords(segment).filter((token, index) => !(index === 0 && (token === "{" || token === "}")));
|
|
@@ -2514,6 +2779,9 @@ function cwdTrackedSegments(command: string, baseCwd: string, nonEmptyNames: Rea
|
|
|
2514
2779
|
// reached via `&&`/`||` may not run at all: `cd /home/hasna; false && cd /tmp;
|
|
2515
2780
|
// rm -rf *` left the guard in /tmp while bash stayed in the home directory.
|
|
2516
2781
|
if (piped) return;
|
|
2782
|
+
// `cd /tmp & rm -rf x` runs the cd in a background job: the shell that runs the rm
|
|
2783
|
+
// never moved, so the tracked cwd must not move either (HAA-00113).
|
|
2784
|
+
if (followedBy === "&") return;
|
|
2517
2785
|
if (shortCircuit) {
|
|
2518
2786
|
analysis.degraded = true;
|
|
2519
2787
|
return;
|
|
@@ -2583,13 +2851,38 @@ function cwdTrackedSegments(command: string, baseCwd: string, nonEmptyNames: Rea
|
|
|
2583
2851
|
next.add(resolveFrom(current, operand));
|
|
2584
2852
|
if (collapsed !== null) next.add(resolveFrom(current, collapsed));
|
|
2585
2853
|
}
|
|
2586
|
-
|
|
2854
|
+
// A cd may fail (a missing folder, no permission) and the shell runs the next
|
|
2855
|
+
// command anyway unless the two are joined by `&&`: `cd /nonexistent; rm -rf state`
|
|
2856
|
+
// deletes `state` in the folder the shell was already in. Unless the cd is followed
|
|
2857
|
+
// by `&&`, or every folder it can land in exists as a directory right now, the
|
|
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).
|
|
2860
|
+
const landed = [...next];
|
|
2861
|
+
const mayFail = followedBy !== "&&" && uncertainCds <= MAX_UNCERTAIN_CDS && (landed.some(mayHaveBeenRemoved) || !landed.every((dir) => isExistingDirectory(dir)));
|
|
2862
|
+
let candidates = landed;
|
|
2863
|
+
if (mayFail) {
|
|
2864
|
+
uncertainCds += 1;
|
|
2865
|
+
if (uncertainCds > MAX_UNCERTAIN_CDS) analysis.degraded = true;
|
|
2866
|
+
else candidates = [...new Set([...landed, ...priorCwds])];
|
|
2867
|
+
}
|
|
2868
|
+
if (candidates.length > MAX_CWD_VARIANTS) analysis.degraded = true;
|
|
2869
|
+
if (mayFail && analysis.degraded) analysis.uncertainCds = true;
|
|
2870
|
+
frame.cwds = candidates.slice(0, MAX_CWD_VARIANTS);
|
|
2587
2871
|
if (isAbsolute(expandHome(operand)) || collapsed !== null) frame.explicit = true;
|
|
2588
2872
|
}
|
|
2589
2873
|
frame.previous = priorCwds;
|
|
2590
2874
|
return;
|
|
2591
2875
|
}
|
|
2592
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
|
+
}
|
|
2593
2886
|
chunks.push({ segment, segmentIndex, cwds: frame.cwds, explicitCwd: frame.explicit });
|
|
2594
2887
|
});
|
|
2595
2888
|
return chunks;
|
|
@@ -2764,6 +3057,7 @@ export async function classifyDangerousOperation(input: CodewithHookInput): Prom
|
|
|
2764
3057
|
if (input.tool_name === "Bash") {
|
|
2765
3058
|
const command = getCommand(input);
|
|
2766
3059
|
const analysis: AnalysisState = { degraded: false };
|
|
3060
|
+
const globWalk = newGlobWalkBudget();
|
|
2767
3061
|
|
|
2768
3062
|
// A command large enough that merely tokenizing it blows the hook's 20s budget cannot be
|
|
2769
3063
|
// analysed at all, and a timed-out hook fails open. 70k repetitions of `cd /<4KB>` is a
|
|
@@ -2796,27 +3090,57 @@ export async function classifyDangerousOperation(input: CodewithHookInput): Prom
|
|
|
2796
3090
|
return extraRule ? [...rules, extraRule] : rules;
|
|
2797
3091
|
};
|
|
2798
3092
|
|
|
2799
|
-
|
|
2800
|
-
|
|
2801
|
-
|
|
2802
|
-
|
|
2803
|
-
|
|
2804
|
-
|
|
2805
|
-
|
|
2806
|
-
|
|
2807
|
-
|
|
2808
|
-
|
|
2809
|
-
|
|
2810
|
-
|
|
2811
|
-
|
|
2812
|
-
|
|
2813
|
-
|
|
2814
|
-
|
|
2815
|
-
|
|
2816
|
-
|
|
2817
|
-
|
|
2818
|
-
|
|
2819
|
-
|
|
3093
|
+
// Judge the target where the command names it, and also where it really acts: a link
|
|
3094
|
+
// in a parent folder (`cd ~/link && rm -rf state`, `rm -rf ~/link/state`, with
|
|
3095
|
+
// ~/link -> ~/.hasna) moves the delete into a protected root the text never names
|
|
3096
|
+
// (HAA-00113). rm removes the last name itself without following it.
|
|
3097
|
+
const realLocation = realParentLocation(targetPath);
|
|
3098
|
+
// A trailing slash (`rm -rf ~/link/`) makes rm follow the last name too, so the delete
|
|
3099
|
+
// acts inside wherever that link finally points (HAA-00113 review).
|
|
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);
|
|
3119
|
+
}
|
|
3120
|
+
for (const judged of judgedLocations) {
|
|
3121
|
+
for (const rule of rulesFor(judged)) {
|
|
3122
|
+
const ruleJudged = judged === targetPath ? judged : inRuleSpelling(judged, rule.root);
|
|
3123
|
+
if (threatensRule(ruleJudged, rule, currentManagedRepoRoot)) {
|
|
3124
|
+
// A session removing content of its own scratch folder (session id from the
|
|
3125
|
+
// harness, not the command) is not a threat to the ~/.hasna tree.
|
|
3126
|
+
// The target must be written as an absolute path (the same wherever the command
|
|
3127
|
+
// runs), so no `cd`, `pushd` or `cd -P` before it can move what it means.
|
|
3128
|
+
if (
|
|
3129
|
+
rule.label === "Hasna state root ~/.hasna" &&
|
|
3130
|
+
ownScratchCommandAllowed(command) &&
|
|
3131
|
+
isAbsolute(expandHome(target.path)) &&
|
|
3132
|
+
!target.path.split(/[\\/]/).some((part) => part === ".." || part === ".") &&
|
|
3133
|
+
isOwnScratchContent(ruleJudged, rule.root, input.session_id)
|
|
3134
|
+
) continue;
|
|
3135
|
+
return {
|
|
3136
|
+
block: true,
|
|
3137
|
+
targetPath: ruleJudged,
|
|
3138
|
+
protectedPath: rule.root,
|
|
3139
|
+
protectedLabel: rule.label,
|
|
3140
|
+
operation: target.operation,
|
|
3141
|
+
reason: scopedBlockReason(target.operation, ruleJudged, rule, target.remote) + ownScratchHint(ruleJudged, rule),
|
|
3142
|
+
};
|
|
3143
|
+
}
|
|
2820
3144
|
}
|
|
2821
3145
|
}
|
|
2822
3146
|
|
|
@@ -2843,7 +3167,9 @@ export async function classifyDangerousOperation(input: CodewithHookInput): Prom
|
|
|
2843
3167
|
// exactly. Checked here rather than at each bound so there is ONE fail-closed answer:
|
|
2844
3168
|
// three bounds that each invented their own fallback all became root wipes.
|
|
2845
3169
|
if (analysis.degraded) {
|
|
2846
|
-
const reason =
|
|
3170
|
+
const reason = analysis.globWalkSpent
|
|
3171
|
+
? globWalkBlockReason(command)
|
|
3172
|
+
: analysis.uncertainCds ? uncertainCdsBlockReason(command) : truncatedAnalysisBlockReason(command);
|
|
2847
3173
|
if (reason) {
|
|
2848
3174
|
return { block: true, operation: "unanalysable command", reason };
|
|
2849
3175
|
}
|
|
@@ -150,7 +150,7 @@ async function runStagedSecretsScan(targetCwd: string, targetCertain: boolean):
|
|
|
150
150
|
status: "skipped",
|
|
151
151
|
scanned: false,
|
|
152
152
|
code: "gitleaks-inconclusive",
|
|
153
|
-
detail: `git could not resolve a work tree for ${targetCwd}${top.exitCode ? ` (git rev-parse exited ${top.exitCode})` : ""}, so this git command was NOT scanned for staged secrets
|
|
153
|
+
detail: `git could not resolve a work tree for ${targetCwd}${top.exitCode ? ` (git rev-parse exited ${top.exitCode})` : ""}, so this git command was NOT scanned for staged secrets.${/\$/.test(targetCwd) ? " The repository path holds a shell variable the scan cannot expand: write the path literally (git -C /full/path/to/repo …)." : ""}`,
|
|
154
154
|
};
|
|
155
155
|
}
|
|
156
156
|
|
package/package.json
CHANGED