@hasna/hooks 0.12.9 → 0.12.10

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.
@@ -33,7 +33,23 @@
33
33
  import { readFileSync } from "fs";
34
34
 
35
35
  /** The scanner surface this hook uses: `scanInputExposures` from @hasna/secrets. */
36
- export type ScanFn = (options: { text?: string; maxBytes?: number; timeoutMs?: number }) => {
36
+ export type ScanFn = (options: {
37
+ text?: string;
38
+ maxBytes?: number;
39
+ timeoutMs?: number;
40
+ /**
41
+ * The scanner's exemption markers. This hook sets it FALSE, and that is a
42
+ * load-bearing choice rather than an omission.
43
+ *
44
+ * The markers exist so an AUTHORED FILE can declare itself a fixture. This
45
+ * hook scans tool output: bytes another program produced, which may be a file
46
+ * dump, a diff, a log or a paste. Honouring a declaration found there would
47
+ * let the scanned bytes talk the scanner out of reporting them — and this
48
+ * hook's only job is to report them, because by the time it runs the output is
49
+ * already in the transcript.
50
+ */
51
+ honorMarkers?: boolean;
52
+ }) => {
37
53
  schema: string;
38
54
  version: number;
39
55
  source: string;
@@ -60,6 +76,13 @@ export type ScanFn = (options: { text?: string; maxBytes?: number; timeoutMs?: n
60
76
  preview: string;
61
77
  evidencePath: string;
62
78
  }[];
79
+ /**
80
+ * Findings the scanner exempted. Read defensively: with `honorMarkers: false`
81
+ * this must stay zero, and a non-zero value means the opt-out did not reach
82
+ * the scanner. `analyzeToolOutput` treats that as `unscanned` rather than
83
+ * `clean`, so the failure direction is a warning instead of a silent pass.
84
+ */
85
+ suppressionCount?: number;
63
86
  };
64
87
 
65
88
  export interface HookInput {
@@ -179,7 +202,8 @@ export function analyzeToolOutput(text: string, scan: ScanFn): ScanOutcome {
179
202
 
180
203
  let result: ReturnType<ScanFn>;
181
204
  try {
182
- result = scan({ text, maxBytes: MAX_SCAN_BYTES, timeoutMs: SCAN_TIMEOUT_MS });
205
+ // Tool output is not an authored file: it cannot declare itself exempt.
206
+ result = scan({ text, maxBytes: MAX_SCAN_BYTES, timeoutMs: SCAN_TIMEOUT_MS, honorMarkers: false });
183
207
  } catch (err) {
184
208
  return {
185
209
  status: "error",
@@ -206,8 +230,14 @@ export function analyzeToolOutput(text: string, scan: ScanFn): ScanOutcome {
206
230
  const skipped = stats?.skipped?.length ?? 0;
207
231
  const errors = stats?.errors?.length ?? 0;
208
232
  const bytes = stats?.bytesScanned ?? 0;
209
- if (result?.truncated || skipped > 0 || errors > 0 || bytes <= 0) {
233
+ // A suppressed finding is a finding this hook did not surface. It asks the
234
+ // scanner not to suppress anything (`honorMarkers: false`), so a non-zero
235
+ // count here means that request did not take effect — an unknown/older
236
+ // scanner, or a changed contract. Fail toward "unscanned", never "clean".
237
+ const suppressed = result?.suppressionCount ?? 0;
238
+ if (result?.truncated || skipped > 0 || errors > 0 || bytes <= 0 || suppressed > 0) {
210
239
  const reason =
240
+ (suppressed > 0 ? `${suppressed} finding(s) suppressed by an exemption marker` : undefined) ??
211
241
  result?.truncatedReason ??
212
242
  stats?.skipped?.[0]?.reason ??
213
243
  stats?.errors?.[0] ??
@@ -44,7 +44,10 @@
44
44
  * the command and its operands are read (see unwrapCommand); arguments they
45
45
  * cannot be parsed from fail closed. A Trash capture is read the way
46
46
  * @hasna/trash parses it, with options before, between or after its paths
47
- * until `--` (see trashOperands).
47
+ * until `--` (see trashOperands). A quoted command list that the `;`, `&&`,
48
+ * `||` and newline split cuts (`ssh host 'a; trash --version'`) is read as
49
+ * the commands it holds, and clears its parts only when none of them, nor
50
+ * the command it is an argument of, can delete or write (see cutPartReads).
48
51
  *
49
52
  * Allowed orgs default to hasna,hasnaxyz,hasna-products and are overridable
50
53
  * with the WORKSPACE_REPOS_GUARD_ORGS env var (comma-separated) or, where
@@ -1117,6 +1120,113 @@ export function bashTargets(command: string, home: string, cwd: string): PathTar
1117
1120
  return [...segmentTargets(data.outer, home, cwd), ...data.bodies.flatMap((body) => bashTargets(body, home, DETACHED_CWD))];
1118
1121
  }
1119
1122
 
1123
+ /** Where segmentTargets splits a command into parts; the capture keeps each separator as a part. */
1124
+ const LIST_SEPARATOR = /(\s*&&\s*|\s*\|\|\s*|;\s*|\n+)/;
1125
+
1126
+ /** A word written whole in one pair of quotes, whose text bash takes literally. */
1127
+ const LITERAL_QUOTED_WORD = /^(?:'[^']*'|"[^"$\x60\\]*")$/;
1128
+
1129
+ type LexedCommand = ReturnType<typeof lexCommand>;
1130
+ type LexedSegment = LexedCommand["segments"][number];
1131
+ type LexedWord = LexedSegment["words"][number];
1132
+
1133
+ interface ListSplitCuts {
1134
+ lexed: LexedCommand;
1135
+ /** Offset of each part of the split in the command. */
1136
+ offsets: number[];
1137
+ /** The words of the command a separator of the split lies inside. */
1138
+ words: LexedWord[];
1139
+ }
1140
+
1141
+ /**
1142
+ * The words segmentTargets' split cuts through. The split ignores quoting,
1143
+ * so a separator inside a quoted word (`ssh h 'a; trash --version'`) cuts
1144
+ * that word, and each part holding a piece of it carries an unbalanced
1145
+ * quote, which leaves only the opaque reading of the part. Null when no word
1146
+ * is cut, or the command cannot be lexed to its end or holds a substitution:
1147
+ * every part then keeps its own reading.
1148
+ */
1149
+ function listSplitCuts(command: string, parts: string[]): ListSplitCuts | null {
1150
+ const offsets: number[] = [];
1151
+ let at = 0;
1152
+ for (const part of parts) {
1153
+ offsets.push(at);
1154
+ at += part.length;
1155
+ }
1156
+ const lexed = lexCommand(command);
1157
+ if (!lexed.trustworthy || lexed.substitutions.length > 0) return null;
1158
+ const words = lexed.segments.flatMap((segment) => segment.words).filter((word) =>
1159
+ parts.some((part, k) => k % 2 === 1 && offsets[k] < word.end && offsets[k] + part.length > word.start));
1160
+ return words.length > 0 ? { lexed, offsets, words } : null;
1161
+ }
1162
+
1163
+ /**
1164
+ * Whether one lexed simple command, whose text is `text`, only reads:
1165
+ * - its rule-based reading (segmentOperation) is a read;
1166
+ * - no assignment precedes its command word: one can change what the word
1167
+ * runs (`PATH=...`), and in an option value (`ProxyCommand=mkdir x`) the
1168
+ * rest is itself a command;
1169
+ * - unless its command word, under both command-position models, runs no
1170
+ * command (`command -v`) or is a DATA_COMMANDS word, which never runs its
1171
+ * arguments as code, its words other than `skip`, as written and unquoted,
1172
+ * hold no delete or write under the opaque reading and no find action
1173
+ * (`-delete`, `-exec`), since it may run one of them.
1174
+ */
1175
+ function onlyReads(segment: LexedSegment, text: string, skip: LexedWord[] = []): boolean {
1176
+ if (segmentOperation(text) !== "read") return false;
1177
+ const index = commandWordIndex(segment);
1178
+ const kept = segment.words.filter((_, at) => !segment.redirects.has(at));
1179
+ const strict = unwrapCommand(kept.map((word) => ({ text: decodeWord(word.text), opaque: /[$\x60]/.test(word.text) })));
1180
+ if (strict === null) return false;
1181
+ const runsAt = [index < 0 ? Infinity : index, strict.index < 0 ? Infinity : segment.words.indexOf(kept[strict.index])];
1182
+ if (segment.words.some((word, at) => at < Math.max(...runsAt) && !segment.redirects.has(at) && ASSIGNMENT.test(decodeWord(word.text)))) return false;
1183
+ const names = [index < 0 ? null : segment.words[index].text, strict.index < 0 ? null : kept[strict.index].text];
1184
+ if (names.every((name) => name === null || DATA_COMMANDS.has(baseName(decodeWord(name))))) return true;
1185
+ const words = kept.filter((word) => !skip.includes(word));
1186
+ const decoded = words.map((word) => decodeWord(word.text));
1187
+ return opaqueOperation(words.map((word) => word.text).join(" ")) === "read" && opaqueOperation(decoded.join(" ")) === "read"
1188
+ && !decoded.some((word) => FIND_ACTIONS.has(word));
1189
+ }
1190
+
1191
+ /** The text of the lexed simple commands in `text`, first word to last. */
1192
+ const segmentText = (text: string, segment: LexedSegment): string =>
1193
+ text.slice(segment.words[0].start, segment.words[segment.words.length - 1].end);
1194
+
1195
+ /**
1196
+ * Whether the part of `command` from `from` to `to`, which holds a piece of a
1197
+ * word the split cut (listSplitCuts), only reads once every word in it is
1198
+ * read where it belongs (onlyReads):
1199
+ * - every command one of the part's words belongs to, read whole, with each
1200
+ * cut word as the one word it is (its own text is read next);
1201
+ * - the whole text of each cut word in the part, read as the command list it
1202
+ * would be if it ran: every command in it.
1203
+ * So a quoted list clears its parts only when no command in it, nor the
1204
+ * command it is an argument of, can delete or write. Only a word written
1205
+ * whole in one pair of quotes, with no expansion, is read this way; any other
1206
+ * cut word, or a list that cannot be lexed to its end or holds a
1207
+ * substitution, keeps the part's own reading. Redirections are not judged
1208
+ * here: segmentTargets still reads every redirect operand in the part as a
1209
+ * write. This only ever replaces a stronger reading with "read"; it never
1210
+ * makes a part stronger.
1211
+ */
1212
+ function cutPartReads(command: string, cuts: ListSplitCuts, from: number, to: number): boolean {
1213
+ const overlaps = (word: LexedWord) => word.start < to && word.end > from;
1214
+ const cut = cuts.words.filter(overlaps);
1215
+ if (cut.length === 0 || cut.some((word) => !LITERAL_QUOTED_WORD.test(word.text))) return false;
1216
+ for (const segment of cuts.lexed.segments.filter((segment) => segment.words.some(overlaps))) {
1217
+ if (!onlyReads(segment, segmentText(command, segment), cuts.words)) return false;
1218
+ }
1219
+ for (const word of cut) {
1220
+ const list = word.text.slice(1, -1);
1221
+ // The lexer drops a here-document body, which a shell in the list could run.
1222
+ if (list.includes("<<")) return false;
1223
+ const inner = lexCommand(list);
1224
+ if (!inner.trustworthy || inner.substitutions.length > 0) return false;
1225
+ if (!inner.segments.every((segment) => onlyReads(segment, segmentText(list, segment)))) return false;
1226
+ }
1227
+ return true;
1228
+ }
1229
+
1120
1230
  /**
1121
1231
  * Extract protected-repo-checkout targets from a Bash command. Recognises
1122
1232
  * explicit `~/...`, `$HOME/...`, `${HOME}/...` and literal-home references
@@ -1141,7 +1251,8 @@ function segmentTargets(command: string, home: string, cwd: string): PathTarget[
1141
1251
  if (!command) return [];
1142
1252
  const roots = protectedRoots(home);
1143
1253
  const underRoot = (path: string) => roots.some((root) => path === root || path.startsWith(`${root}${sep}`));
1144
- const parts = command.split(/(\s*&&\s*|\s*\|\|\s*|;\s*|\n+)/);
1254
+ const parts = command.split(LIST_SEPARATOR);
1255
+ const cuts = listSplitCuts(command, parts);
1145
1256
 
1146
1257
  const targets: PathTarget[] = [];
1147
1258
  // Every directory the current segment can run in, every directory any
@@ -1164,6 +1275,10 @@ function segmentTargets(command: string, home: string, cwd: string): PathTarget[
1164
1275
  for (let i = 0; i < opens; i++) subshells.push({ current: [...current], reachable: new Set(reachable), certain });
1165
1276
 
1166
1277
  const segment = unwrapSegment(rawSegment);
1278
+ // A part the split cut out of a quoted word is read as the commands its
1279
+ // words belong to (cutPartReads); when every one only reads, so does the
1280
+ // part, whatever its unbalanced quote makes the opaque reading say.
1281
+ const readsOnly = cuts !== null && cutPartReads(command, cuts, cuts.offsets[index], cuts.offsets[index] + rawSegment.length);
1167
1282
 
1168
1283
  const plainCd = segment.match(/^cd(?:\s+(?:-[A-Za-z@]+|--))*(?:\s+([^\s;&|<>()\x60]+))?$/);
1169
1284
  const embeddedCd = plainCd ? null : segment.match(/(?:^|\s)cd(?:\s+(?:-[A-Za-z]+|--))*\s+([^\s;&|<>()\x60]+)/);
@@ -1204,7 +1319,7 @@ function segmentTargets(command: string, home: string, cwd: string): PathTarget[
1204
1319
  if (operand) operands.push(operand);
1205
1320
  return " ";
1206
1321
  });
1207
- const commandOp = segmentOperation(commandPart);
1322
+ const commandOp: Operation = readsOnly ? "read" : segmentOperation(commandPart);
1208
1323
  return { commandPart, operands, op: opaqueRedirect && commandOp === "read" ? ("write" as Operation) : commandOp };
1209
1324
  });
1210
1325
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hasna/hooks",
3
- "version": "0.12.9",
3
+ "version": "0.12.10",
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": {