@hasna/hooks 0.14.1 → 0.15.0

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.
Files changed (37) hide show
  1. package/README.md +30 -10
  2. package/bin/hooks/stop-review.js +17 -9
  3. package/bin/hooks-mcp.js +741 -311
  4. package/bin/index.js +1669 -632
  5. package/bin/native-safety-entry.js +2 -2
  6. package/bin/native-safety-worker.cjs +36 -34
  7. package/bin/release-manifest.json +297 -0
  8. package/bin/serve.js +577 -151
  9. package/dist/index.js +1809 -1176
  10. package/dist/lib/error-events.d.ts +59 -0
  11. package/dist/lib/install-record.d.ts +136 -0
  12. package/dist/lib/manifest.d.ts +6 -0
  13. package/dist/lib/release-manifest.d.ts +162 -0
  14. package/dist/lib/store.d.ts +25 -2
  15. package/dist/openapi.d.ts +147 -0
  16. package/dist/registry-auth.d.ts +6 -1
  17. package/dist/registry-http.d.ts +2 -1
  18. package/dist/sdk/generated.d.ts +26 -0
  19. package/dist/sdk/index.js +14 -0
  20. package/hooks/codewith-native-common.ts +190 -6
  21. package/hooks/hook-signed-link-guard/README.md +46 -0
  22. package/hooks/hook-signed-link-guard/src/classify.ts +7 -3
  23. package/hooks/hook-signed-link-guard/src/jq.ts +205 -34
  24. package/hooks/hook-stop-review/README.md +5 -2
  25. package/hooks/hook-stop-review/src/jev.ts +9 -4
  26. package/hooks/hook-stop-review/src/policy.ts +7 -3
  27. package/hooks/hook-stop-review/src/runtime.ts +5 -4
  28. package/hooks/hook-trash-guard/README.md +9 -4
  29. package/hooks/hook-trash-guard/src/hook.ts +127 -10
  30. package/hooks/hook-workspace-repos-guard/src/hook.ts +27 -12
  31. package/hooks/pre-bash/README.md +47 -1
  32. package/hooks/pre-bash/src/hook.ts +168 -12
  33. package/hooks/shell-words.ts +40 -2
  34. package/package.json +3 -2
  35. package/scripts/build-release-manifest.ts +27 -0
  36. package/scripts/validate-package.ts +5 -1
  37. package/scripts/validate-release-manifest.ts +67 -0
@@ -1,4 +1,4 @@
1
- import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, writeFileSync, writeSync } from "node:fs";
1
+ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, 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
 
@@ -132,6 +132,13 @@ export interface GitCommandInfo {
132
132
  targetCwd: string;
133
133
  gitDir?: string;
134
134
  workTree?: string;
135
+ /**
136
+ * False when a `cd` earlier in the same command could not be modelled, so the target
137
+ * folder above is only where the shell started rather than where the git command runs.
138
+ * Callers that act on the target (the staged-secrets scan) must refuse rather than
139
+ * check the wrong folder.
140
+ */
141
+ targetCertain?: boolean;
135
142
  }
136
143
 
137
144
  // `$( ... )` and backtick substitutions are one operand of the surrounding command:
@@ -532,10 +539,15 @@ function gitInfoFromTokens(tokens: string[], baseCwd: string): GitCommandInfo |
532
539
 
533
540
  export function gitCommandInfo(command: string, baseCwd: string = process.cwd()): GitCommandInfo | null {
534
541
  const read = (): GitCommandInfo | null => {
535
- for (const segment of splitShellSegments(command)) {
536
- const tokens = shellWords(segment);
537
- const info = gitInfoFromTokens(tokens, baseCwd);
538
- if (info) return info;
542
+ for (const layer of shellCommandLayers(command).layers) {
543
+ // The folder the git command runs in is the one a `cd` before it establishes, not
544
+ // the folder the hook started in. Reading only the starting folder scanned repo A
545
+ // while the commit landed in repo B (`cd /b && git commit`).
546
+ const analysis: AnalysisState = { degraded: false };
547
+ for (const chunk of cwdTrackedSegments(layer.command, baseCwd, new Set<string>(), analysis)) {
548
+ const info = gitInfoFromTokens(shellWords(chunk.segment), chunk.cwds[0]);
549
+ if (info) return analysis.degraded ? { ...info, targetCertain: false } : info;
550
+ }
539
551
  }
540
552
  return null;
541
553
  };
@@ -1540,6 +1552,167 @@ function shouldSkipHasnaTreeRule(targetPath: string, rule: ProtectedPathRule, cu
1540
1552
  return isInsidePath(target, currentManagedRepoRoot);
1541
1553
  }
1542
1554
 
1555
+ /** A scratch folder name the carve-out reads at all (the same shape trash-guard accepts). */
1556
+ const OWN_SCRATCH_SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
1557
+ /** A scratch folder named by a prefix of the session id must carry at least this much of it. */
1558
+ const OWN_SCRATCH_MIN_PREFIX = 8;
1559
+ /** A `..` path component anywhere in the command (after a separator, quote or start). */
1560
+ const PARENT_COMPONENT = /(?:^|[\s/'"`=:;&|()<>{},])\.\.(?=$|[\s/'"`;&|()<>{},])/;
1561
+ /** The only command words a command using the own-scratch exception may run, written literally. */
1562
+ const DELETE_ONLY_WORD = /^(?:\/bin\/|\/usr\/bin\/)?(?:rm|rmdir|find)$/;
1563
+ /** Shell constructs that can run or build a command the word check cannot see. */
1564
+ const HIDDEN_COMMAND = /\$\(|`|<\(|>\(|\$\{|\$'|\\\n/;
1565
+ /** find actions that run or open something other than a delete, or that follow links. */
1566
+ const FIND_RUNS_SOMETHING = /(?:^|\s)-(?:exec|execdir|ok|okdir|fprint|fprint0|fprintf|fls|L|H|follow)(?=\s|$)/;
1567
+
1568
+ /**
1569
+ * Whether the command as a whole may use the own-scratch exception at all. It must be
1570
+ * made only of deletes: every simple command (split on `;`, `&`, `|` and newlines, more
1571
+ * finely than the shell would, so a quoted separator only splits more) starts with the
1572
+ * literal word `rm`, `rmdir` or `find` (optionally `/bin/` or `/usr/bin/`), a `find`
1573
+ * piece has no quote or backslash (which could hide `-exec`) and runs no `-exec`-like
1574
+ * action and no `-L`/`-H`/`-follow`, and nothing builds a command the words cannot show
1575
+ * (`$(…)`, backticks, any parenthesis — process substitution, zsh `=(…)` and glob
1576
+ * qualifiers included —, `${…}`, `$'…'`, a line continuation). Anything else
1577
+ * could make or move a link in the same run, which a check made before the command
1578
+ * cannot see. Also refused: any `..` component (a symbolic link followed by `..` is
1579
+ * resolved by the kernel from the link's target, which a textual path check cannot see).
1580
+ */
1581
+ export function ownScratchCommandAllowed(command: string): boolean {
1582
+ if (PARENT_COMPONENT.test(command) || HIDDEN_COMMAND.test(command) || /[()]/.test(command)) return false;
1583
+ const pieces = command.split(/[;&|\n\r]+/).map((piece) => piece.trim()).filter(Boolean);
1584
+ if (pieces.length === 0) return false;
1585
+ return pieces.every((piece) => {
1586
+ const first = piece.split(/\s+/)[0];
1587
+ if (!DELETE_ONLY_WORD.test(first)) return false;
1588
+ if (!first.endsWith("find")) return true;
1589
+ return !/['"\\]/.test(piece) && !FIND_RUNS_SOMETHING.test(piece);
1590
+ });
1591
+ }
1592
+
1593
+ /**
1594
+ * Whether a delete of `targetPath` is content of the CALLING session's own scratch
1595
+ * folder, `~/.hasna/scratchpad/scratch/<own id>/…`, which every session is told to
1596
+ * clean up itself (global-scratch-is-transient, global-recoverable-file-removal).
1597
+ *
1598
+ * `<own id>` is read from the harness's `session_id` in the hook input, never from
1599
+ * the command. The folder name must equal it exactly, or be a prefix of it of at least
1600
+ * OWN_SCRATCH_MIN_PREFIX characters whose `meta.json`, if it has one at all, is a
1601
+ * regular file naming exactly that session id (prefix folders carry none today). The folder must be a real directory, not a symbolic
1602
+ * link, and no existing component from it down to the target may be a symbolic link
1603
+ * (checked with lstat, never followed). Still refused: the scratch root, another
1604
+ * session's folder, the session folder itself and its `meta.json` / `.lock` control
1605
+ * files, any glob character below the folder, a `.` or `..` component, and a path with
1606
+ * a `.git` component. Only the `~/.hasna` tree rule consults this, together with
1607
+ * ownScratchCommandAllowed and a target written as an absolute path; every other
1608
+ * protected root keeps its verdict.
1609
+ */
1610
+ export function isOwnScratchContent(targetPath: string, hasnaRoot: string, sessionId: string | undefined): boolean {
1611
+ if (!sessionId || !OWN_SCRATCH_SEGMENT.test(sessionId)) return false;
1612
+ if (targetPath.split(/[\\/]/).some((part) => part === ".." || part === ".")) return false;
1613
+ const scratchRoot = join(hasnaRoot, "scratchpad", "scratch");
1614
+ const target = resolve(targetPath);
1615
+ if (target === scratchRoot || !isInsidePath(target, scratchRoot)) return false;
1616
+ const parts = relative(scratchRoot, target).split(sep);
1617
+ const [segment, firstChild] = parts;
1618
+ if (!segment || !firstChild) return false;
1619
+ if (segment.endsWith(".") || !OWN_SCRATCH_SEGMENT.test(segment)) return false;
1620
+ if (parts.some((part) => /[*?[\]{}]/.test(part))) return false;
1621
+ const control = firstChild.normalize("NFKC").toLowerCase();
1622
+ if (control === "meta.json" || control === ".lock") return false;
1623
+ if (parts.some((part) => part.toLowerCase() === ".git")) return false;
1624
+ const folderPath = join(scratchRoot, segment);
1625
+ if (!isRealDirectory(folderPath)) return false;
1626
+ if (segment !== sessionId) {
1627
+ if (segment.length < OWN_SCRATCH_MIN_PREFIX || !sessionId.startsWith(segment)) return false;
1628
+ // Prefix-named folders carry no meta.json today; one that does must name this session.
1629
+ const meta = metaSessionId(join(folderPath, "meta.json"));
1630
+ if (meta !== undefined && meta !== sessionId) return false;
1631
+ }
1632
+ // No symbolic link on the way down: `rm` and `find` follow every link in the middle of
1633
+ // a path, so a link anywhere below the folder could point the delete outside it.
1634
+ let current = folderPath;
1635
+ for (const part of parts.slice(1)) {
1636
+ current = join(current, part);
1637
+ let isLink: boolean;
1638
+ try {
1639
+ isLink = lstatSync(current).isSymbolicLink();
1640
+ } catch (error) {
1641
+ if (isMissingPathError(error)) break;
1642
+ return false;
1643
+ }
1644
+ if (isLink) return false;
1645
+ }
1646
+ // Belt and braces: the real location must still be strictly inside the real folder.
1647
+ const realFolder = realpathThroughExisting(folderPath);
1648
+ const realTarget = realpathThroughExisting(target);
1649
+ if (!realFolder || !realTarget || realTarget === realFolder || !isInsidePath(realTarget, realFolder)) return false;
1650
+ const realChild = relative(realFolder, realTarget).split(sep)[0].normalize("NFKC").toLowerCase();
1651
+ return realChild !== "meta.json" && realChild !== ".lock";
1652
+ }
1653
+
1654
+ /** How to remove own scratch content, appended when a refused target lies under the scratch root. */
1655
+ function ownScratchHint(targetPath: string, rule: ProtectedPathRule): string {
1656
+ if (rule.label !== "Hasna state root ~/.hasna") return "";
1657
+ const scratchRoot = join(rule.root, "scratchpad", "scratch");
1658
+ if (!isInsidePath(resolve(targetPath), scratchRoot) || resolve(targetPath) === scratchRoot) return "";
1659
+ return " To remove content of your own scratch folder, write each target as an absolute path below ~/.hasna/scratchpad/scratch/<your session id>/, with no `..`, in a command made only of rm, rmdir or find -delete.";
1660
+ }
1661
+
1662
+ /** True only for an existing directory that is not itself a symbolic link. */
1663
+ function isRealDirectory(path: string): boolean {
1664
+ try {
1665
+ const stat = lstatSync(path);
1666
+ return stat.isDirectory() && !stat.isSymbolicLink();
1667
+ } catch {
1668
+ return false;
1669
+ }
1670
+ }
1671
+
1672
+ /**
1673
+ * The `sessionId` a scratch folder's `meta.json` records; undefined when there is no
1674
+ * entry of that name at all; null when there is one that is not a plain regular file
1675
+ * (a link, a directory) or cannot be read or parsed.
1676
+ */
1677
+ function metaSessionId(metaPath: string): string | null | undefined {
1678
+ let stat: Stats;
1679
+ try {
1680
+ stat = lstatSync(metaPath);
1681
+ } catch (error) {
1682
+ return isMissingPathError(error) ? undefined : null;
1683
+ }
1684
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1_048_576) return null;
1685
+ try {
1686
+ const parsed = JSON.parse(readFileSync(metaPath, "utf8")) as unknown;
1687
+ if (!parsed || typeof parsed !== "object") return null;
1688
+ const value = (parsed as { sessionId?: unknown }).sessionId;
1689
+ return typeof value === "string" ? value : null;
1690
+ } catch {
1691
+ return null;
1692
+ }
1693
+ }
1694
+
1695
+ /**
1696
+ * The real path of `path`: the deepest ancestor that exists is resolved with
1697
+ * realpath (every symbolic link followed) and the missing remainder appended as
1698
+ * written. Null when a component cannot be read for any reason but absence.
1699
+ */
1700
+ function realpathThroughExisting(path: string): string | null {
1701
+ const missing: string[] = [];
1702
+ let current = resolve(path);
1703
+ for (;;) {
1704
+ try {
1705
+ return missing.length ? join(realpathSync(current), ...missing.reverse()) : realpathSync(current);
1706
+ } catch (error) {
1707
+ if (!isMissingPathError(error)) return null;
1708
+ const parent = dirname(current);
1709
+ if (parent === current) return null;
1710
+ missing.push(basename(current));
1711
+ current = parent;
1712
+ }
1713
+ }
1714
+ }
1715
+
1543
1716
  function isMissingPathError(error: unknown): boolean {
1544
1717
  return error instanceof Error && "code" in error && (error as NodeJS.ErrnoException).code === "ENOENT";
1545
1718
  }
@@ -2625,13 +2798,24 @@ export async function classifyDangerousOperation(input: CodewithHookInput): Prom
2625
2798
 
2626
2799
  for (const rule of rulesFor(targetPath)) {
2627
2800
  if (threatensRule(targetPath, rule, currentManagedRepoRoot)) {
2801
+ // A session removing content of its own scratch folder (session id from the
2802
+ // harness, not the command) is not a threat to the ~/.hasna tree.
2803
+ // The target must be written as an absolute path (the same wherever the command
2804
+ // runs), so no `cd`, `pushd` or `cd -P` before it can move what it means.
2805
+ if (
2806
+ rule.label === "Hasna state root ~/.hasna" &&
2807
+ ownScratchCommandAllowed(command) &&
2808
+ isAbsolute(expandHome(target.path)) &&
2809
+ !target.path.split(/[\\/]/).some((part) => part === ".." || part === ".") &&
2810
+ isOwnScratchContent(targetPath, rule.root, input.session_id)
2811
+ ) continue;
2628
2812
  return {
2629
2813
  block: true,
2630
2814
  targetPath,
2631
2815
  protectedPath: rule.root,
2632
2816
  protectedLabel: rule.label,
2633
2817
  operation: target.operation,
2634
- reason: scopedBlockReason(target.operation, targetPath, rule, target.remote),
2818
+ reason: scopedBlockReason(target.operation, targetPath, rule, target.remote) + ownScratchHint(targetPath, rule),
2635
2819
  };
2636
2820
  }
2637
2821
  }
@@ -131,6 +131,52 @@ Accepted examples: `.head.sha`, `.[] | .name`, `[.number, .title]`,
131
131
  `.[] | select(.user.login == "x") | .id`, and on a single pull request or
132
132
  issue the counts `.commits`, `.comments` and `.review_comments`.
133
133
 
134
+ Letter-only text (HO-00192): `gsub("[^A-Za-z ]"; "")` with literal arguments
135
+ removes every character but ASCII letters and spaces:
136
+ `gh api repos/o/r/issues/1/comments --jq '.[-1].body | gsub("[^A-Za-z ]"; "")'`
137
+ passes. The pattern must be exactly a negated class of `A-Z`, `a-z` and space
138
+ (optionally followed by `+`), the replacement only ASCII letters and spaces
139
+ written without a backslash escape, and there is no third (flags) argument;
140
+ `sub`, other patterns and interpolated arguments stay refused. Two further
141
+ limits keep the removed characters from coming back:
142
+
143
+ - The result may be printed, measured (`length`), tested (`test`, `==`) or
144
+ narrowed by another such `gsub`. Any step that could rebuild text from it
145
+ (`split`, `join`, `+`, interpolation, an array or object, a format, a slice,
146
+ a field, iteration) is refused, so markers placed before the `gsub` cannot be
147
+ swapped back after it.
148
+ - Its input must be a field reached from the response through field reads,
149
+ iteration and indexing only, optionally through `ascii_downcase`,
150
+ `ascii_upcase`, the trims or a type filter. A value that went through any
151
+ other function (`split`, `join`, `tojson`, `tostring`, `to_entries`,
152
+ `sort_by`, a format) or a slice of a field (`.body[0:1]`, with literal or
153
+ computed bounds) is refused, as is anything iterated or read from it
154
+ afterwards (`split(":") | to_entries | .[] | .value`), so the body cannot be
155
+ turned into a letters-only code before the `gsub`.
156
+
157
+ Cut text (HO-00203): `split`, `indices` and a slice cut text into pieces or
158
+ positions, and a filter can then answer once per piece. `[.body | split("")[] |
159
+ (select(. == "a") | "a"), (select(. == "b") | "b"), …] | join("")` used to pass
160
+ and printed the body byte for byte, as did a per-character Boolean matrix,
161
+ `indices("a"), indices("b"), …` (every position of every character) and a list
162
+ of one-character slices. So:
163
+
164
+ - A piece of text, the positions `indices` returns, and a slice of anything but
165
+ the response root or a scalar field may not be tested, compared, measured or
166
+ filtered: no `select`, `==`, `test`, `startswith`, `contains`, `length`,
167
+ `any`, `all`, `isempty` or sort key on it. That stays true after it is wrapped
168
+ (`[.]`, `"\(.)"`, `{c: .}`), re-encoded, iterated or used as a key.
169
+ - A slice of the response's array, or of an array field, still yields whole
170
+ elements: `.commits[-3:] | .[] | .sha` and `.labels[0:2] | .[] | .name`
171
+ pass. So do slices and splits of scalar fields (`.[] | .title[0:60]`,
172
+ `.title | split(" ") | length`) and filters of whole records
173
+ (`.[] | select(.body | contains("x")) | .id`).
174
+ - Slice bounds are checked like any other expression.
175
+ - Still admitted: a fixed number of literal tests or positions of a whole text
176
+ (`.body | test("^https")`, `.body | index("http")`). Each answers once per
177
+ response element however long the text is, so the filter's own length (at
178
+ most 4,096 characters) bounds what they reveal.
179
+
134
180
  Scalar leaves are identifiers, numbers, counts, booleans, enums, refs, object
135
181
  ids, timestamps and short names (`id`, `number`, `state`, `conclusion`,
136
182
  `name`, `login`, `sha`, `title`, `created_at`, `digest`, `size_in_bytes`,
@@ -38,7 +38,7 @@
38
38
  * command that may be an alias, an unterminated command) fails closed.
39
39
  */
40
40
 
41
- import { blankComments, commandWordIndex, decodeCommandWord, envSplitCommandText, heredocMarkerAt, lexCommand, scanParenAt, skipHeredocBodies, type Word } from "../../hook-trash-guard/src/hook";
41
+ import { ansiPlainBash, blankComments, commandWordIndex, decodeCommandWord, envSplitCommandText, heredocMarkerAt, lexCommand, scanParenAt, skipHeredocBodies, type Word } from "../../hook-trash-guard/src/hook";
42
42
  import { jqProjectionIsScalar } from "./jq";
43
43
  import { ansiPlain, ansiPlainEvery } from "../../local-executors";
44
44
 
@@ -997,7 +997,8 @@ function scriptsFromSubstitutions(raw: string, depth: number, ctx: Context): Sig
997
997
  * inside an ANSI-C `$'…'` word is also read with it spelled `\x27` (ansiPlain, HO-00213), because the lexer ended the
998
998
  * word at the escaped quote and could hide the next lines. Those words are found in one pass from the left and, beside
999
999
  * that, from every `$'` (ansiPlainEvery, HO-00222), because a `$'` bash does not read as ANSI-C can start a word that
1000
- * hides the real one. Refused when any reading refuses.
1000
+ * hides the real one, and as bash reads them (ansiPlainBash, HO-00233), because the reading from every `$'` also
1001
+ * respelled an escaped `\$'a\'`, whose quote then never closed. Refused when any reading refuses.
1001
1002
  */
1002
1003
  export function classifyCommand(command: string, depth = 0, inheritedDebug = false): SignedLinkVerdict {
1003
1004
  const verdict = classifyReading(command, depth, inheritedDebug);
@@ -1009,7 +1010,10 @@ export function classifyCommand(command: string, depth = 0, inheritedDebug = fal
1009
1010
  const spelled = plain === command ? other : classifyCommand(plain, depth, inheritedDebug);
1010
1011
  if (spelled.refused) return spelled;
1011
1012
  const every = ansiPlainEvery(command);
1012
- return every === command || every === plain ? spelled : classifyCommand(every, depth, inheritedDebug);
1013
+ const respelled = every === command || every === plain ? spelled : classifyCommand(every, depth, inheritedDebug);
1014
+ if (respelled.refused) return respelled;
1015
+ const bash = ansiPlainBash(command);
1016
+ return bash === command || bash === plain || bash === every ? respelled : classifyCommand(bash, depth, inheritedDebug);
1013
1017
  }
1014
1018
 
1015
1019
  function classifyReading(command: string, depth: number, inheritedDebug: boolean): SignedLinkVerdict {