@hasna/hooks 0.12.18 → 0.12.20

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.
package/dist/index.js CHANGED
@@ -46442,6 +46442,7 @@ async function verifyNativeSafetyCommand(command, home = homedir8(), guard = "tr
46442
46442
  // src/lib/codex-safety-check.ts
46443
46443
  var SUPPORTED_CODEX_SAFETY_VERSIONS = ["codex-cli 0.153.0", "codex-cli 0.154.0", "codex-cli 0.154.0-alpha.6.1", "codex-cli 0.155.0", "codex-cli 0.155.1", "codex-cli 0.156.1", "codex-cli 0.157.0", "codex-cli 0.157.1", "codex-cli 0.158.0", "codex-cli 0.159.0", "codex-cli 0.159.2", "codex-cli 0.159.3", "codex-cli 0.160.0", "codex-cli 0.160.1", "codex-cli 0.161.0", "codex-cli 0.162.0", "codex-cli 0.162.1"];
46444
46444
  var versions = new Set(SUPPORTED_CODEX_SAFETY_VERSIONS);
46445
+ var CODEX_EXECUTABLE_MAX_BYTES = 512000000;
46445
46446
 
46446
46447
  class CodexSafetyError extends Error {
46447
46448
  code;
@@ -46483,9 +46484,9 @@ function executable2(command) {
46483
46484
  const fd = openSync15(path, constants15.O_RDONLY | constants15.O_NOFOLLOW | constants15.O_NONBLOCK);
46484
46485
  try {
46485
46486
  const stat2 = fstatSync10(fd);
46486
- need8(stat2.isFile() && [0, process.getuid?.()].includes(stat2.uid) && !(stat2.mode & 18) && !!(stat2.mode & 64) && stat2.size <= 256000000, "native_unsafe_executable");
46487
+ need8(stat2.isFile() && [0, process.getuid?.()].includes(stat2.uid) && !(stat2.mode & 18) && !!(stat2.mode & 64) && stat2.size <= CODEX_EXECUTABLE_MAX_BYTES, "native_unsafe_executable");
46487
46488
  const bytes = readFileSync19(fd);
46488
- need8(bytes.length <= 256000000, "native_unavailable");
46489
+ need8(bytes.length <= CODEX_EXECUTABLE_MAX_BYTES, "native_unavailable");
46489
46490
  need8(nativeHeader(bytes), "native_executable_required");
46490
46491
  return { path, sha256: digest3(bytes) };
46491
46492
  } finally {
@@ -3,6 +3,10 @@ import { verifyNativeSafetyCommand } from "../native-safety.js";
3
3
  /** Exact `codex --version` outputs whose app-server protocol was measured
4
4
  * against the real native binary. Anything else refuses as native_unsupported. */
5
5
  export declare const SUPPORTED_CODEX_SAFETY_VERSIONS: readonly ["codex-cli 0.153.0", "codex-cli 0.154.0", "codex-cli 0.154.0-alpha.6.1", "codex-cli 0.155.0", "codex-cli 0.155.1", "codex-cli 0.156.1", "codex-cli 0.157.0", "codex-cli 0.157.1", "codex-cli 0.158.0", "codex-cli 0.159.0", "codex-cli 0.159.2", "codex-cli 0.159.3", "codex-cli 0.160.0", "codex-cli 0.160.1", "codex-cli 0.161.0", "codex-cli 0.162.0", "codex-cli 0.162.1"];
6
+ /** Hard sanity bound on the native Codex executable, which is read whole into
7
+ * memory for the header check and SHA-256 pin. Not a platform contract: the
8
+ * measured 0.162.1 binaries are 246.6 MB (darwin-arm64) to 294.4 MB (linux-x64). */
9
+ export declare const CODEX_EXECUTABLE_MAX_BYTES = 512000000;
6
10
  export type CodexSafetyCode = "native_unavailable" | "native_unsafe_executable" | "native_executable_required" | "native_unsupported" | "native_failed" | "native_discovery_failed" | "hooks_disabled" | "guard_missing" | "guard_ambiguous" | "guard_definition_invalid" | "guard_disabled" | "guard_untrusted" | "guard_changed" | "guard_failed";
7
11
  export declare class CodexSafetyError extends Error {
8
12
  readonly code: CodexSafetyCode;
@@ -301,6 +301,26 @@ function splitShellSegmentsUncached(command: string): ShellSegment[] {
301
301
  }));
302
302
  }
303
303
 
304
+ /**
305
+ * Set while a reader reads a command a second time with the earlier
306
+ * double-quote backslash reading (shellWordsPass), so that whatever it
307
+ * blocked stays blocked.
308
+ */
309
+ let legacyQuotes = false;
310
+
311
+ function withLegacyQuotes<T>(read: () => T): T {
312
+ const was = legacyQuotes;
313
+ legacyQuotes = true;
314
+ try {
315
+ return read();
316
+ } finally {
317
+ legacyQuotes = was;
318
+ }
319
+ }
320
+
321
+ /** A command holding a backslash and a double quote, which the two readings may read differently. */
322
+ const mayReadTwoWays = (command: string): boolean => command.includes("\\") && command.includes('"');
323
+
304
324
  function shellWordsPass(segment: string, atomicSubstitutions: boolean): { words: string[]; unterminated: boolean } {
305
325
  const words: string[] = [];
306
326
  let current = "";
@@ -348,6 +368,16 @@ function shellWordsPass(segment: string, atomicSubstitutions: boolean): { words:
348
368
  continue;
349
369
  }
350
370
  if (ch === "\\" && quote !== "'") {
371
+ const next = segment[i + 1] ?? "";
372
+ // Inside double quotes bash removes a backslash only before $ ` " \ and a
373
+ // newline (a line continuation, which removes both); before any other
374
+ // character the backslash is part of the word. The earlier reading
375
+ // (legacyQuotes) removed it before every character.
376
+ if (quote === '"' && !legacyQuotes && !/[$`"\\]/.test(next)) {
377
+ if (next === "\n") i += 1;
378
+ else current += ch;
379
+ continue;
380
+ }
351
381
  escaped = true;
352
382
  continue;
353
383
  }
@@ -501,12 +531,17 @@ function gitInfoFromTokens(tokens: string[], baseCwd: string): GitCommandInfo |
501
531
  }
502
532
 
503
533
  export function gitCommandInfo(command: string, baseCwd: string = process.cwd()): GitCommandInfo | null {
504
- for (const segment of splitShellSegments(command)) {
505
- const tokens = shellWords(segment);
506
- const info = gitInfoFromTokens(tokens, baseCwd);
507
- if (info) return info;
508
- }
509
- return null;
534
+ 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;
539
+ }
540
+ return null;
541
+ };
542
+ // A commit or push the earlier reading finds is reported as it reported it
543
+ // (its target folder included); one only bash's reading finds is added.
544
+ return (mayReadTwoWays(command) ? withLegacyQuotes(read) : null) ?? read();
510
545
  }
511
546
 
512
547
  export function isGitCommitOrPush(command: string): boolean {
@@ -2569,14 +2604,18 @@ export async function classifyDangerousOperation(input: CodewithHookInput): Prom
2569
2604
  return reason ? { block: true, operation: "oversized command", reason } : { block: false };
2570
2605
  }
2571
2606
 
2572
- if (shellCommandLayers(command).truncated) {
2607
+ if (shellCommandLayers(command).truncated || (mayReadTwoWays(command) && withLegacyQuotes(() => shellCommandLayers(command).truncated))) {
2573
2608
  const reason = truncatedAnalysisBlockReason(command);
2574
2609
  if (reason) {
2575
2610
  return { block: true, operation: "unanalysable nested command", reason };
2576
2611
  }
2577
2612
  }
2578
2613
 
2579
- for (const target of destructiveShellTargets(command, cwd, analysis)) {
2614
+ const targets = destructiveShellTargets(command, cwd, analysis);
2615
+ // Read with the earlier double-quote backslash reading first (legacyQuotes),
2616
+ // so that what it blocked stays blocked with the same reason.
2617
+ if (mayReadTwoWays(command)) targets.unshift(...withLegacyQuotes(() => destructiveShellTargets(command, cwd, analysis)));
2618
+ for (const target of targets) {
2580
2619
  const targetCwd = target.baseCwd ?? cwd;
2581
2620
  const targetPath = resolveFrom(targetCwd, target.path);
2582
2621
  const rulesFor = (path: string) => {
@@ -90,7 +90,7 @@ import {
90
90
  type WrapperSpec,
91
91
  } from "../../shell-words";
92
92
  export { expandBraces } from "../../shell-words";
93
- import { ansiPlain, launchedCommands, localExecutor, shellProgram } from "../../local-executors";
93
+ import { ansiPlain, launchedCommands, legacyQuotes, localExecutor, readWithLegacyQuotes, shellProgram } from "../../local-executors";
94
94
 
95
95
  const RULE = "trash-guard";
96
96
 
@@ -135,7 +135,7 @@ const REFUSED_VERBS: Record<string, string> = {
135
135
  * place. When one of these is in command position and the command mentions a
136
136
  * delete verb, the command is refused rather than guessed at.
137
137
  */
138
- const OPAQUE_COMMANDS = new Set(["sh", "bash", "zsh", "dash", "ksh", "ash", "eval", "source", ".", "su", "runuser", "env"]);
138
+ const OPAQUE_COMMANDS = new Set(["sh", "bash", "zsh", "dash", "ksh", "ash", "mksh", "eval", "source", ".", "su", "runuser", "env"]);
139
139
 
140
140
  /** Wrapper commands whose real command follows them (with their value-taking options). */
141
141
  const WRAPPERS: Record<string, string[]> = {
@@ -297,17 +297,28 @@ function readAnsiC(raw: string, from: number): { text: string; end: number } {
297
297
  * `$'rm'` and `$'\x72m'` are `rm`.
298
298
  */
299
299
  export function decodeCommandWord(raw: string): string {
300
+ return decodeQuoted(raw, true);
301
+ }
302
+
303
+ /**
304
+ * Quote removal as bash does it. Outside quotes a backslash quotes the next
305
+ * character. Inside double quotes it is removed only before `$`, a backtick,
306
+ * `"`, `\` or a newline (a line continuation: both go) and kept before any
307
+ * other character, so `"\%a%e cmd"` is the sed script `\%a%e cmd`. The
308
+ * earlier reading (legacyQuotes) dropped it before every character.
309
+ */
310
+ function decodeQuoted(raw: string, ansi: boolean): string {
300
311
  let out = "";
301
312
  let i = 0;
302
313
  while (i < raw.length) {
303
314
  const ch = raw[i];
304
- if (ch === "$" && raw[i + 1] === "'") {
305
- const ansi = readAnsiC(raw, i + 2);
306
- out += ansi.text;
307
- i = ansi.end;
315
+ if (ansi && ch === "$" && raw[i + 1] === "'") {
316
+ const decoded = readAnsiC(raw, i + 2);
317
+ out += decoded.text;
318
+ i = decoded.end;
308
319
  continue;
309
320
  }
310
- if (ch === "$" && raw[i + 1] === '"') {
321
+ if (ansi && ch === "$" && raw[i + 1] === '"') {
311
322
  i++;
312
323
  continue;
313
324
  }
@@ -330,7 +341,8 @@ export function decodeCommandWord(raw: string): string {
330
341
  i++;
331
342
  while (i < raw.length && raw[i] !== '"') {
332
343
  if (raw[i] === "\\" && i + 1 < raw.length) {
333
- out += raw[i + 1];
344
+ const next = raw[i + 1];
345
+ out += legacyQuotes.on || /[$`"\\]/.test(next) ? next : next === "\n" ? "" : `\\${next}`;
334
346
  i += 2;
335
347
  continue;
336
348
  }
@@ -1037,45 +1049,9 @@ function findHeredocEnd(rest: string, delimiter: string): number {
1037
1049
  return -1;
1038
1050
  }
1039
1051
 
1040
- /** Strip one word's quoting and escapes, the way the shell would for a name. */
1052
+ /** Strip one word's quoting and escapes, the way the shell would for a name (decodeQuoted). */
1041
1053
  export function decodeWord(text: string): string {
1042
- let out = "";
1043
- let i = 0;
1044
- while (i < text.length) {
1045
- const ch = text[i];
1046
- if (ch === "\\") {
1047
- if (i + 1 < text.length) out += text[i + 1];
1048
- i += 2;
1049
- continue;
1050
- }
1051
- if (ch === "'") {
1052
- const end = text.indexOf("'", i + 1);
1053
- if (end === -1) {
1054
- out += text.slice(i + 1);
1055
- break;
1056
- }
1057
- out += text.slice(i + 1, end);
1058
- i = end + 1;
1059
- continue;
1060
- }
1061
- if (ch === '"') {
1062
- i++;
1063
- while (i < text.length && text[i] !== '"') {
1064
- if (text[i] === "\\" && i + 1 < text.length) {
1065
- out += text[i + 1];
1066
- i += 2;
1067
- continue;
1068
- }
1069
- out += text[i];
1070
- i++;
1071
- }
1072
- i++;
1073
- continue;
1074
- }
1075
- out += ch;
1076
- i++;
1077
- }
1078
- return out;
1054
+ return decodeQuoted(text, false);
1079
1055
  }
1080
1056
 
1081
1057
  /* ------------------------------------------------------------------ */
@@ -1887,34 +1863,14 @@ function resolveTrash(deps: GuardDependencies): { path: string | null; error: st
1887
1863
  const ABSENT_REASON =
1888
1864
  "[trash-guard] No verified @hasna/trash guard was found on PATH. This deletion is refused. Install the current @hasna/trash package with Bun and run its setup; the operating-system trash utility is not a compatible guard.";
1889
1865
 
1890
- export function evaluate(input: CodewithHookInput, deps: GuardDependencies): CodewithHookOutput {
1891
- if (input.hook_event_name !== "PreToolUse") return { continue: true };
1892
- if (["apply_patch", "ApplyPatch", "functions.apply_patch"].includes(input.tool_name ?? "")) {
1893
- const patch = input.tool_input?.command;
1894
- if (typeof patch !== "string") return deny("[trash-guard] Unreadable patch input; deletion safety cannot be checked.");
1895
- if (/^\s*\*\*\* Delete File:/m.test(patch)) {
1896
- return deny("[trash-guard] Delete File would bypass recoverable deletion. First use `trash put -- <path>` or the trash_put MCP tool, then submit any remaining edits without the deletion block.");
1897
- }
1898
- return { continue: true };
1899
- }
1900
- if (input.tool_name !== "Bash") return { continue: true };
1901
-
1902
- // A command we cannot READ is a payload we cannot verify, and the harness
1903
- // falls back to the ORIGINAL tool input whenever `updatedInput` is missing or
1904
- // empty -- so "cannot tell" must never resolve to "run it". Refuse instead.
1905
- // A command that is PRESENT and empty runs nothing, so that stays allowed.
1906
- const rawCommand = (input as { tool_input?: { command?: unknown } }).tool_input?.command;
1907
- if (typeof rawCommand !== "string") {
1908
- return deny(
1909
- "[trash-guard] The Bash tool call carried no readable `command`, so this hook cannot verify what would run. Refusing a call it cannot verify. Re-run the delete explicitly as `rm -- <path>` so it can be redirected into trash.",
1910
- );
1911
- }
1912
-
1913
- const command = getCommand(input);
1914
- if (!command.trim()) return { continue: true };
1915
-
1916
- const scanned = scanCommand(command, { cwd: deps.cwd, home: deps.home });
1866
+ const REWRITE_UNVERIFIED_REASON =
1867
+ "[trash-guard] The rewrite of this command did not verify (the delete could not be redirected cleanly), so the command is refused rather than run unredirected. Re-run the delete as a plain `rm -- <path>` command.";
1917
1868
 
1869
+ /**
1870
+ * The verdict a scan decides on its own (a refusal, or no delete to
1871
+ * redirect), or null when its `rm` hits are to be rewritten.
1872
+ */
1873
+ function scanVerdict(scanned: ScanResult, command: string): CodewithHookOutput | null {
1918
1874
  if (scanned.refusals.length > 0) {
1919
1875
  return deny(`[trash-guard] ${scanned.refusals[0].reason}`);
1920
1876
  }
@@ -1944,11 +1900,9 @@ export function evaluate(input: CodewithHookInput, deps: GuardDependencies): Cod
1944
1900
  "[trash-guard] This delete runs from inside a protected repository checkout but names only paths outside it. Run it from outside the checkout (`cd /tmp && rm -- <path>`), where it is redirected into trash.",
1945
1901
  );
1946
1902
  }
1947
- if (scanned.handoffHits.length > 0) {
1948
- // Every delete here belongs to the guarded repo-checkout roots, which
1949
- // `workspace-repos-guard` owns. Abstain and let that hook decide.
1950
- return { continue: true };
1951
- }
1903
+ // No delete to redirect. Any handed off belongs to the guarded
1904
+ // repo-checkout roots, which `workspace-repos-guard` owns: abstain and
1905
+ // let that hook decide.
1952
1906
  return { continue: true };
1953
1907
  }
1954
1908
 
@@ -1957,6 +1911,54 @@ export function evaluate(input: CodewithHookInput, deps: GuardDependencies): Cod
1957
1911
  "[trash-guard] This command mixes a delete under the protected repo-checkout roots (owned by workspace-repos-guard) with a delete outside them, and a partial rewrite would leave one of them unredirected. Re-run them as separate commands, so each delete is handled by the hook that owns it.",
1958
1912
  );
1959
1913
  }
1914
+ return null;
1915
+ }
1916
+
1917
+ export function evaluate(input: CodewithHookInput, deps: GuardDependencies): CodewithHookOutput {
1918
+ if (input.hook_event_name !== "PreToolUse") return { continue: true };
1919
+ if (["apply_patch", "ApplyPatch", "functions.apply_patch"].includes(input.tool_name ?? "")) {
1920
+ const patch = input.tool_input?.command;
1921
+ if (typeof patch !== "string") return deny("[trash-guard] Unreadable patch input; deletion safety cannot be checked.");
1922
+ if (/^\s*\*\*\* Delete File:/m.test(patch)) {
1923
+ return deny("[trash-guard] Delete File would bypass recoverable deletion. First use `trash put -- <path>` or the trash_put MCP tool, then submit any remaining edits without the deletion block.");
1924
+ }
1925
+ return { continue: true };
1926
+ }
1927
+ if (input.tool_name !== "Bash") return { continue: true };
1928
+
1929
+ // A command we cannot READ is a payload we cannot verify, and the harness
1930
+ // falls back to the ORIGINAL tool input whenever `updatedInput` is missing or
1931
+ // empty -- so "cannot tell" must never resolve to "run it". Refuse instead.
1932
+ // A command that is PRESENT and empty runs nothing, so that stays allowed.
1933
+ const rawCommand = (input as { tool_input?: { command?: unknown } }).tool_input?.command;
1934
+ if (typeof rawCommand !== "string") {
1935
+ return deny(
1936
+ "[trash-guard] The Bash tool call carried no readable `command`, so this hook cannot verify what would run. Refusing a call it cannot verify. Re-run the delete explicitly as `rm -- <path>` so it can be redirected into trash.",
1937
+ );
1938
+ }
1939
+
1940
+ const command = getCommand(input);
1941
+ if (!command.trim()) return { continue: true };
1942
+
1943
+ const scan = () => scanCommand(command, { cwd: deps.cwd, home: deps.home });
1944
+ const hits = (result: ScanResult) => result.rmHits.map((hit) => hit.word.start).join();
1945
+ // A check fails if it fails with either double-quote backslash reading.
1946
+ const fails = (check: () => boolean) => check() || !!readWithLegacyQuotes(command, check);
1947
+ const scanned = scan();
1948
+ const verdict = scanVerdict(scanned, command);
1949
+ // Read with the earlier double-quote backslash reading too (legacyQuotes):
1950
+ // what it refused stays refused, with the same reason, and a delete only it
1951
+ // would have redirected is refused, not run unredirected.
1952
+ const legacy = readWithLegacyQuotes(command, () => {
1953
+ const result = scan();
1954
+ return { result, verdict: scanVerdict(result, command) };
1955
+ });
1956
+ if (legacy) {
1957
+ const { result: earlierScan, verdict: earlier } = legacy;
1958
+ if (earlier && !("continue" in earlier)) return earlier;
1959
+ if (!earlier && (!verdict || "continue" in verdict) && hits(earlierScan) !== hits(scanned)) return deny(REWRITE_UNVERIFIED_REASON);
1960
+ }
1961
+ if (verdict) return verdict;
1960
1962
 
1961
1963
  const trash = resolveTrash(deps);
1962
1964
  if (trash.error !== null) {
@@ -1969,20 +1971,18 @@ export function evaluate(input: CodewithHookInput, deps: GuardDependencies): Cod
1969
1971
  }
1970
1972
  const trashPath = trash.path;
1971
1973
 
1972
- if (deps.execution && changesExecutionEnvironment(command)) {
1974
+ if (deps.execution && fails(() => changesExecutionEnvironment(command))) {
1973
1975
  return deny("[trash-guard] A deletion combined with shell environment changes cannot use the verified native execution context. Run the deletion as a separate plain rm command.");
1974
1976
  }
1975
1977
  const rewritten = rewriteCommand(command, scanned.rmHits, trashPath, deps.execution);
1976
1978
  const updatedInput = buildUpdatedInput(input.tool_input, rewritten);
1977
1979
  if (deps.execution) updatedInput.hasna_execution = "hasna.hooks.execution.v1";
1978
1980
 
1979
- if (!updatedInputIsComplete(updatedInput, command, scanned.rmHits, deps.cwd, deps.home)) {
1981
+ if (fails(() => !updatedInputIsComplete(updatedInput, command, scanned.rmHits, deps.cwd, deps.home))) {
1980
1982
  // Never allow a partial rewrite: the harness falls back to the ORIGINAL
1981
1983
  // tool input when `updatedInput` is missing or empty, which runs the raw
1982
1984
  // `rm`. Refuse instead.
1983
- return deny(
1984
- "[trash-guard] The rewrite of this command did not verify (the delete could not be redirected cleanly), so the command is refused rather than run unredirected. Re-run the delete as a plain `rm -- <path>` command.",
1985
- );
1985
+ return deny(REWRITE_UNVERIFIED_REASON);
1986
1986
  }
1987
1987
 
1988
1988
  return allowRewrite(updatedInput);
@@ -1990,7 +1990,7 @@ export function evaluate(input: CodewithHookInput, deps: GuardDependencies): Cod
1990
1990
 
1991
1991
  /** Verdict used when the hook itself fails: refuse anything that could delete. */
1992
1992
  export function fallbackVerdict(command: string): CodewithHookOutput {
1993
- return mentionsDeleteVerb(command) || /^\s*\*\*\* Delete File:/m.test(command)
1993
+ return mentionsDeleteVerb(command) || readWithLegacyQuotes(command, () => mentionsDeleteVerb(command)) || /^\s*\*\*\* Delete File:/m.test(command)
1994
1994
  ? deny(
1995
1995
  "[trash-guard] The hook failed while classifying this command, so it cannot be proven free of an unredirected delete. Re-run the delete as a plain `rm -- <path>` command.",
1996
1996
  )
@@ -83,7 +83,7 @@ import {
83
83
  type CodewithHookOutput,
84
84
  } from "../../codewith-native-common";
85
85
  import { ASSIGNMENT, baseName, expandBraces, splitsOrMoves, unwrapCommand, type ShellWord } from "../../shell-words";
86
- import { ansiPlain, embeddedProgramIsReadOnly, launchedCommands, localExecutor, shellProgram, type ExecutorFinding } from "../../local-executors";
86
+ import { ansiPlain, embeddedProgramIsReadOnly, launchedCommands, legacyQuotes, localExecutor, readWithLegacyQuotes, shellProgram, type ExecutorFinding } from "../../local-executors";
87
87
 
88
88
  export { expandBraces, unwrapCommand };
89
89
 
@@ -344,8 +344,9 @@ function shellWords(command: string): ShellWord[] {
344
344
  }
345
345
  if (ch === "\\" && i + 1 < command.length) {
346
346
  const next = command[i + 1];
347
- // Inside double quotes a backslash escapes only $ ` " \ and newline.
348
- text += quote === '"' && !/[$\x60"\\\n]/.test(next) ? ch + next : next;
347
+ // Inside double quotes a backslash escapes only $ ` " \ and newline,
348
+ // and a line continuation removes the backslash and the newline.
349
+ text += quote === '"' && !/[$\x60"\\\n]/.test(next) ? ch + next : quote === '"' && next === "\n" && !legacyQuotes.on ? "" : next;
349
350
  raw += ch + next;
350
351
  inWord = true;
351
352
  i++;
@@ -665,7 +666,7 @@ function commandOperation(part: ReturnType<typeof lexCommand>["segments"][number
665
666
  // opaque reading below.
666
667
  if (tool === "find" && !kept.some((word) => expandsAtRuntime(word.text)) && !words.some((word) => FIND_ACTIONS.has(word))) return "read";
667
668
  if (tool === "env" && mentionsDeleteVerb(envSplitCommandText(words))) return "delete";
668
- if (["sh", "bash", "zsh", "dash", "ksh", "ash", "eval", "source", ".", "su", "runuser", "env", "xargs", "find", "busybox", "toybox"].includes(tool ?? "")) {
669
+ if (["sh", "bash", "zsh", "dash", "ksh", "ash", "mksh", "eval", "source", ".", "su", "runuser", "env", "xargs", "find", "busybox", "toybox"].includes(tool ?? "")) {
669
670
  return opaqueOperation(words.join(" "));
670
671
  }
671
672
  if (["mkdir", "mkfile", "touch", "mv", "cp", "ln", "tee", "install", "dd", "rsync", "scp", "truncate"].includes(tool ?? "")) return "write";
@@ -1650,6 +1651,9 @@ export function evaluate(input: CodewithHookInput, options: { home?: string } =
1650
1651
  if (!command) return { output: { continue: true }, warnings };
1651
1652
  const cwd = typeof input.cwd === "string" && input.cwd ? input.cwd : process.cwd();
1652
1653
  const targets = bashTargets(command, home, cwd);
1654
+ // Read with the earlier double-quote backslash reading first (legacyQuotes),
1655
+ // so that what it blocked stays blocked, with the same reason.
1656
+ targets.unshift(...(readWithLegacyQuotes(command, () => bashTargets(command, home, cwd)) ?? []));
1653
1657
  for (const target of targets) {
1654
1658
  for (const root of roots) {
1655
1659
  const verdict = classifyPath(target.path, root, orgs, target.op);
@@ -48,6 +48,30 @@ export function mentionsDeleteVerb(text: string): boolean {
48
48
  return /(^|[^A-Za-z0-9_.-])(rm|rmdir|unlink|shred|trash)(?![A-Za-z0-9_.-])/.test(text);
49
49
  }
50
50
 
51
+ /**
52
+ * Bash keeps a backslash inside double quotes unless it comes before `$`, a
53
+ * backtick, `"`, `\` or a newline, and the guards' word decoders read it so.
54
+ * Their earlier reading dropped it before every character. `on` is set while
55
+ * a guard reads a command a second time with that earlier reading
56
+ * (readWithLegacyQuotes), so that whatever it refused stays refused.
57
+ */
58
+ export const legacyQuotes = { on: false };
59
+
60
+ /**
61
+ * `read()` with the earlier double-quote backslash reading, or undefined for
62
+ * a command both readings read alike (it holds no backslash or no `"`).
63
+ */
64
+ export function readWithLegacyQuotes<T>(command: string, read: () => T): T | undefined {
65
+ if (!command.includes("\\") || !command.includes('"')) return undefined;
66
+ const was = legacyQuotes.on;
67
+ legacyQuotes.on = true;
68
+ try {
69
+ return read();
70
+ } finally {
71
+ legacyQuotes.on = was;
72
+ }
73
+ }
74
+
51
75
  /** The grammar an embedded program is written in, which decides how it reads. */
52
76
  export type ProgramKind = "c-interp" | "awk" | "shell";
53
77
 
@@ -544,7 +568,8 @@ export function literalWord(raw: string): string | null {
544
568
  for (; j < raw.length && raw[j] !== '"'; j++) {
545
569
  const c = raw[j];
546
570
  if (c === "$" || c === "\x60") return null;
547
- if (c === "\\" && j + 1 < raw.length && /[$\x60"\\\n]/.test(raw[j + 1])) { out += raw[++j]; continue; }
571
+ // A line continuation removes the backslash and the newline.
572
+ if (c === "\\" && j + 1 < raw.length && /[$\x60"\\\n]/.test(raw[j + 1])) { if (raw[++j] !== "\n" || legacyQuotes.on) out += raw[j]; continue; }
548
573
  out += c;
549
574
  }
550
575
  if (j >= raw.length) return null;
@@ -2,6 +2,7 @@ import { homedir } from "node:os";
2
2
  import { isAbsolute } from "node:path";
3
3
  import { evaluate as evaluateTrash, findTrashBinary, inspectTrashBinary, scanCommand } from "./hook-trash-guard/src/hook";
4
4
  import { evaluate as evaluateRepos } from "./hook-workspace-repos-guard/src/hook";
5
+ import { readWithLegacyQuotes } from "./local-executors";
5
6
  import { evaluate as evaluateSignedLinks } from "./hook-signed-link-guard/src/hook";
6
7
  import type { CodewithHookInput, CodewithHookOutput } from "./codewith-native-common";
7
8
 
@@ -58,7 +59,10 @@ export function evaluateComposite(guard: string, inputText: string): string {
58
59
  // registration of this entry. Its refusal outranks a Trash rewrite, because an
59
60
  // allowed rewrite would also run the composite gh read.
60
61
  const signedLinks = evaluateSignedLinks(evaluated);
61
- const handoff = shellCommand && scanCommand(evaluated.tool_input!.command as string, { home: homedir(), cwd: input.cwd }).handoffHits.length > 0;
62
+ const command = evaluated.tool_input!.command as string;
63
+ const handsOff = () => scanCommand(command, { home: homedir(), cwd: input.cwd }).handoffHits.length > 0;
64
+ // Read with the earlier double-quote backslash reading too (legacyQuotes).
65
+ const handoff = shellCommand && (handsOff() || !!readWithLegacyQuotes(command, handsOff));
62
66
  let trash: CodewithHookOutput = name === "trash-guard" && (!monitor || shellCommand)
63
67
  ? evaluateTrash(evaluated, { home: homedir(), cwd: input.cwd, findTrash: findTrashBinary, inspectTrash: inspectTrashBinary, execution }) : { continue: true };
64
68
  // A Trash rewrite is proven only for Bash. Under Monitor the deletion is
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hasna/hooks",
3
- "version": "0.12.18",
3
+ "version": "0.12.20",
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": {