@hasna/hooks 0.12.16 → 0.12.18

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
@@ -46440,7 +46440,7 @@ async function verifyNativeSafetyCommand(command, home = homedir8(), guard = "tr
46440
46440
  }
46441
46441
 
46442
46442
  // src/lib/codex-safety-check.ts
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"];
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
46445
 
46446
46446
  class CodexSafetyError extends Error {
@@ -2,7 +2,7 @@ import { type NativeSafetyName } from "./native-safety.js";
2
2
  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
- 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"];
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
6
  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
7
  export declare class CodexSafetyError extends Error {
8
8
  readonly code: CodexSafetyCode;
@@ -90,7 +90,7 @@ import {
90
90
  type WrapperSpec,
91
91
  } from "../../shell-words";
92
92
  export { expandBraces } from "../../shell-words";
93
- import { launchedCommands, localExecutor, shellProgram } from "../../local-executors";
93
+ import { ansiPlain, launchedCommands, localExecutor, shellProgram } from "../../local-executors";
94
94
 
95
95
  const RULE = "trash-guard";
96
96
 
@@ -1095,7 +1095,7 @@ export function commandWordIndex(segment: Segment): number {
1095
1095
  while (index < segment.words.length && guard++ < 32) {
1096
1096
  if (segment.redirects.has(index)) { index++; continue; }
1097
1097
  const raw = segment.words[index].text;
1098
- const decoded = decodeWord(raw);
1098
+ const decoded = decodeCommandWord(raw);
1099
1099
  if (ASSIGNMENT_RE.test(decoded) && !decoded.startsWith("-")) {
1100
1100
  index++;
1101
1101
  continue;
@@ -1108,7 +1108,7 @@ export function commandWordIndex(segment: Segment): number {
1108
1108
  // command -v/-V looks up every following name without executing one.
1109
1109
  if (wrapper === "command") {
1110
1110
  for (const word of segment.words.filter((_, at) => at > index && !segment.redirects.has(at))) {
1111
- const option = decodeWord(word.text);
1111
+ const option = decodeCommandWord(word.text);
1112
1112
  if (option === "--" || !option.startsWith("-")) break;
1113
1113
  if (/^-[pvV]*[vV][pvV]*$/.test(option)) return -1;
1114
1114
  }
@@ -1119,7 +1119,7 @@ export function commandWordIndex(segment: Segment): number {
1119
1119
  index++;
1120
1120
  while (index < segment.words.length) {
1121
1121
  if (segment.redirects.has(index)) { index++; continue; }
1122
- const option = decodeWord(segment.words[index].text);
1122
+ const option = decodeCommandWord(segment.words[index].text);
1123
1123
  if (!option.startsWith("-") || option === "-") break;
1124
1124
  if (option === "--") {
1125
1125
  index++;
@@ -1136,7 +1136,7 @@ export function commandWordIndex(segment: Segment): number {
1136
1136
  }
1137
1137
  let positionals = WRAPPER_POSITIONALS[wrapper] ?? 0;
1138
1138
  while (positionals > 0 && index < segment.words.length) {
1139
- const positional = decodeWord(segment.words[index].text);
1139
+ const positional = decodeCommandWord(segment.words[index].text);
1140
1140
  if (positional.startsWith("-") && positional !== "-") break;
1141
1141
  index++;
1142
1142
  positionals--;
@@ -1550,7 +1550,7 @@ function readLocalExecutor(
1550
1550
  // own: read it as a command in its own right, by both command-position
1551
1551
  // models, with the launcher's operands (find's start paths) and cwd deciding
1552
1552
  // whether it runs under a checkout.
1553
- for (const launched of launchedCommands(segment.words.map((word) => decodeWord(word.text)), index, (at) => segment.redirects.has(at))) {
1553
+ for (const launched of launchedCommands(segment.words.map((word) => decodeCommandWord(word.text)), index, (at) => segment.redirects.has(at))) {
1554
1554
  if (depth >= 8) return executorTargetsHandoff(scope.segment, scope.index, cwd, ctx.home) ? { kind: "refuse", reason: LAUNCHER_DEPTH_REASON } : null;
1555
1555
  const sub: Segment = {
1556
1556
  words: segment.words.slice(launched.start, launched.end),
@@ -1564,20 +1564,20 @@ function readLocalExecutor(
1564
1564
  }
1565
1565
  }
1566
1566
  // `sh|bash|… -c PROGRAM` / `eval WORD…` whose program is not a plain literal
1567
- // (an expansion, a substitution, several eval words) cannot be read at all;
1567
+ // (an expansion, a substitution, ANSI-C `$'…'` quoting, several eval words) cannot be read at all;
1568
1568
  // under a checkout it is refused. A literal program keeps the shell-string
1569
1569
  // reading below (OPAQUE_COMMANDS), as before.
1570
1570
  const kept = segment.words.map((word, at) => ({ word, at })).filter(({ at }) => !segment.redirects.has(at));
1571
1571
  const keptIndex = kept.findIndex(({ at }) => at === index);
1572
- const shell = keptIndex < 0 ? null : shellProgram(kept.map(({ word }) => word.text), keptIndex);
1572
+ const shell = keptIndex < 0 ? null : shellProgram(kept.map(({ word }) => word.text), keptIndex, decodeCommandWord);
1573
1573
  if (shell && !shell.literal && (executorTargetsHandoff(segment, index, cwd, ctx.home) || executorTargetsHandoff(scope.segment, scope.index, cwd, ctx.home))) {
1574
1574
  return {
1575
1575
  kind: "refuse",
1576
- reason: `\`${verb}\` runs a shell program that is not a plain literal (an expansion, a substitution or several words), so this hook cannot read what it would delete under a protected repository checkout. Write the program out literally, or run it from outside the checkout.`,
1576
+ reason: `\`${verb}\` runs a shell program that is not a plain literal (an expansion, a substitution, ANSI-C \`$'…'\` quoting or several words), so this hook cannot read what it would delete under a protected repository checkout. Write the program out literally, or run it from outside the checkout.`,
1577
1577
  };
1578
1578
  }
1579
1579
  const exec = localExecutor(
1580
- segment.words.map((word) => decodeWord(word.text)),
1580
+ segment.words.map((word) => decodeCommandWord(word.text)),
1581
1581
  index,
1582
1582
  (at) => at >= 0 && at < segment.words.length && (segment.redirects.has(at) || expandsWord(segment.words[at].text)),
1583
1583
  );
@@ -1633,7 +1633,11 @@ export function scanCommand(command: string, options: { cwd: string; home: strin
1633
1633
  };
1634
1634
 
1635
1635
  if (!lexed.trustworthy) {
1636
- return result;
1636
+ // A command the lexer stops trusting at a `\'` inside `$'…'` is scanned
1637
+ // in the spelling it follows, which the shell runs the same; it stays
1638
+ // untrusted, so it is never rewritten.
1639
+ const plain = ansiPlain(command);
1640
+ return plain === command ? result : { ...scanCommand(plain, options), trustworthy: false };
1637
1641
  }
1638
1642
 
1639
1643
  // Refusals that only the strict or fail-closed reading finds come after every
@@ -65,6 +65,7 @@ import { homedir } from "node:os";
65
65
  import { dirname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
66
66
  import {
67
67
  commandWordIndex,
68
+ decodeCommandWord,
68
69
  decodeWord,
69
70
  envSplitCommandText,
70
71
  gitSubcommand,
@@ -82,7 +83,7 @@ import {
82
83
  type CodewithHookOutput,
83
84
  } from "../../codewith-native-common";
84
85
  import { ASSIGNMENT, baseName, expandBraces, splitsOrMoves, unwrapCommand, type ShellWord } from "../../shell-words";
85
- import { embeddedProgramIsReadOnly, launchedCommands, localExecutor, shellProgram, type ExecutorFinding } from "../../local-executors";
86
+ import { ansiPlain, embeddedProgramIsReadOnly, launchedCommands, localExecutor, shellProgram, type ExecutorFinding } from "../../local-executors";
86
87
 
87
88
  export { expandBraces, unwrapCommand };
88
89
 
@@ -491,7 +492,7 @@ function partOperation(part: ReturnType<typeof lexCommand>["segments"][number]):
491
492
  const kept = part.words.map((word, at) => ({ word, at })).filter(({ at }) => !part.redirects.has(at));
492
493
  const index = commandWordIndex(part);
493
494
  const shared = index < 0 ? "read" : commandOperation(part, index);
494
- const strict = unwrapCommand(kept.map(({ word }) => ({ text: decodeWord(word.text), opaque: /[$\x60]/.test(word.text) })));
495
+ const strict = unwrapCommand(kept.map(({ word }) => strictWord(word.text)));
495
496
  if (strict === null) return strongest(shared, opaqueOperation(kept.map(({ word }) => decodeWord(word.text)).join(" ")));
496
497
  if (strict.index < 0 || kept[strict.index].at === index) return shared;
497
498
  return strongest(shared, commandOperation(part, kept[strict.index].at));
@@ -515,13 +516,14 @@ function runsDestructiveLocalProgram(part: ReturnType<typeof lexCommand>["segmen
515
516
  // except that a destructive local executor inside it counts here too.
516
517
  const kept = part.words.map((word, at) => ({ word, at })).filter(({ at }) => !part.redirects.has(at));
517
518
  const keptIndex = kept.findIndex(({ at }) => at === index);
518
- const shell = keptIndex < 0 ? null : shellProgram(kept.map(({ word }) => word.text), keptIndex);
519
+ const shell = keptIndex < 0 ? null : shellProgram(kept.map(({ word }) => word.text), keptIndex, decodeCommandWord);
519
520
  if (shell) {
520
521
  if (!shell.literal) return true;
521
522
  const inner = lexCommand(shell.program!);
522
523
  if (inner.trustworthy && inner.segments.some((segment) => segmentRunsDestructive(segment, depth + 1))) return true;
523
524
  }
524
- const decoded = part.words.map((word) => decodeWord(word.text));
525
+ // Words as the shell passes them, ANSI-C `$'…'` decoded (`$'sed'` is sed).
526
+ const decoded = part.words.map((word) => decodeCommandWord(word.text));
525
527
  // A launcher (find -exec/-execdir/-ok/-okdir, xargs) runs a command of its
526
528
  // own; that command is read like one in command position, wrappers included.
527
529
  for (const launched of launchedCommands(decoded, index, (at) => part.redirects.has(at))) {
@@ -543,11 +545,62 @@ function subSegment(part: ReturnType<typeof lexCommand>["segments"][number], sta
543
545
 
544
546
  /** Whether a lexed simple command, read by both command-position models, runs a destructive local program. */
545
547
  function segmentRunsDestructive(segment: ReturnType<typeof lexCommand>["segments"][number], depth = 0): boolean {
548
+ return commandIndices(segment).some((index) => runsDestructiveLocalProgram(segment, index, depth));
549
+ }
550
+
551
+ /**
552
+ * A word for the strict wrapper model: decoded as the shell passes it, and
553
+ * opaque when it expands at runtime. A word of plain characters and ANSI-C
554
+ * `$'…'` parts (`$'sudo'`, `ba$'sh'`) is decoded exactly, not opaque.
555
+ */
556
+ function strictWord(raw: string): ShellWord {
557
+ return { text: decodeCommandWord(raw), opaque: /[$\x60]/.test(raw) && !/^(?:[^$\x60"'\\]|\$'(?:[^'\\]|\\.)*')+$/.test(raw) };
558
+ }
559
+
560
+ /** The command word of a lexed simple command under both command-position models (the shared walk and the strict wrapper model). */
561
+ function commandIndices(segment: ReturnType<typeof lexCommand>["segments"][number]): number[] {
562
+ const indices = new Set<number>();
546
563
  const shared = commandWordIndex(segment);
547
- if (shared >= 0 && runsDestructiveLocalProgram(segment, shared, depth)) return true;
564
+ if (shared >= 0) indices.add(shared);
548
565
  const kept = segment.words.map((word, at) => ({ word, at })).filter(({ at }) => !segment.redirects.has(at));
549
- const strict = unwrapCommand(kept.map(({ word }) => ({ text: decodeWord(word.text), opaque: /[$\x60]/.test(word.text) })));
550
- return strict !== null && strict.index >= 0 && kept[strict.index].at !== shared && runsDestructiveLocalProgram(segment, kept[strict.index].at, depth);
566
+ const strict = unwrapCommand(kept.map(({ word }) => strictWord(word.text)));
567
+ if (strict !== null && strict.index >= 0) indices.add(kept[strict.index].at);
568
+ return [...indices];
569
+ }
570
+
571
+ /**
572
+ * The files lexed simple commands write through their own program: sed's
573
+ * `w`, `W` and `s///w` targets (localExecutor `writes`), with the command in
574
+ * command position, behind a wrapper, run by find or xargs, or inside a
575
+ * command substitution. segmentTargets judges each exactly as it judges a `>`
576
+ * redirect target. A sed script this cannot read is refused elsewhere: it is
577
+ * an unresolved local executor (runsDestructiveLocalProgram).
578
+ */
579
+ function programWriteTargets(lexed: { segments: ReturnType<typeof lexCommand>["segments"]; substitutions?: string[] }, depth = 0): string[] {
580
+ if (depth > 8) return [];
581
+ const files: string[] = [];
582
+ for (const segment of lexed.segments) {
583
+ const decoded = segment.words.map((word) => decodeCommandWord(word.text));
584
+ const opaqueAt = (at: number) => at >= 0 && at < segment.words.length && (segment.redirects.has(at) || expandsAtRuntime(segment.words[at].text));
585
+ const kept = segment.words.filter((_, at) => !segment.redirects.has(at));
586
+ for (const index of commandIndices(segment)) {
587
+ // A sed target is a file name as written: `$HOME/t` and `~/t` are not expanded.
588
+ files.push(...(localExecutor(decoded, index, opaqueAt)?.writes ?? []).map((file) => (file[0] === "/" ? file : `./${file}`)));
589
+ // A literal `sh -c`/`eval` program writes where its own sed writes, as a
590
+ // `>` inside the program does.
591
+ const shell = shellProgram(kept.map((word) => word.text), kept.indexOf(segment.words[index]), decodeCommandWord);
592
+ const inner = shell?.literal ? lexCommand(shell.program!) : null;
593
+ if (inner?.trustworthy) files.push(...programWriteTargets(inner, depth + 1));
594
+ for (const launched of launchedCommands(decoded, index, (at) => segment.redirects.has(at))) {
595
+ files.push(...programWriteTargets({ segments: [subSegment(segment, launched.start, launched.end)] }, depth + 1));
596
+ }
597
+ }
598
+ }
599
+ for (const body of lexed.substitutions ?? []) {
600
+ const inner = lexCommand(body);
601
+ if (inner.trustworthy) files.push(...programWriteTargets(inner, depth + 1));
602
+ }
603
+ return files;
551
604
  }
552
605
 
553
606
  /**
@@ -562,6 +615,10 @@ function segmentRunsDestructive(segment: ReturnType<typeof lexCommand>["segments
562
615
  function hidesDestructiveExecutor(text: string, depth = 0): boolean {
563
616
  if (depth > 4) return false;
564
617
  const lexed = lexCommand(text);
618
+ // A command the lexer stops trusting at a `\'` inside `$'…'` is read in
619
+ // the spelling it follows, which the shell runs the same.
620
+ const plain = lexed.trustworthy ? text : ansiPlain(text);
621
+ if (plain !== text) return hidesDestructiveExecutor(plain, depth + 1);
565
622
  if (lexed.trustworthy && lexed.segments.some((segment) => segmentRunsDestructive(segment))) return true;
566
623
  const bodies = commandSubstitutions(text);
567
624
  return (bodies ?? lexed.substitutions).some((body) => hidesDestructiveExecutor(body, depth + 1));
@@ -574,7 +631,7 @@ function commandOperation(part: ReturnType<typeof lexCommand>["segments"][number
574
631
  // its own command word would otherwise read as.
575
632
  if (runsDestructiveLocalProgram(part, index)) return "delete";
576
633
  const kept = part.words.filter((_, at) => at >= index && !part.redirects.has(at));
577
- const words = kept.map((word) => decodeWord(word.text));
634
+ const words = kept.map((word) => decodeCommandWord(word.text));
578
635
  const tool = words[0].split("/").pop();
579
636
  if (["rm", "rmdir", "shred"].includes(tool ?? "")) return asksForHelp(words, 1, false) ? "read" : "delete";
580
637
  // POSIX/BSD unlink takes no options, so `unlink --help` removes a file
@@ -1193,9 +1250,14 @@ const DETACHED_CWD = "/";
1193
1250
  */
1194
1251
  export function bashTargets(command: string, home: string, cwd: string): PathTarget[] {
1195
1252
  if (!command) return [];
1253
+ // A command the lexer stops trusting at a `\'` inside `$'…'` is also read in
1254
+ // the spelling it follows, which the shell runs the same.
1255
+ const plain = lexCommand(command).trustworthy ? command : ansiPlain(command);
1196
1256
  const data = dataHeredocs(command);
1197
- if (!data) return segmentTargets(command, home, cwd);
1198
- return [...segmentTargets(data.outer, home, cwd), ...data.bodies.flatMap((body) => bashTargets(body, home, DETACHED_CWD))];
1257
+ return [
1258
+ ...(plain === command ? [] : bashTargets(plain, home, cwd)),
1259
+ ...(data ? [...segmentTargets(data.outer, home, cwd), ...data.bodies.flatMap((body) => bashTargets(body, home, DETACHED_CWD))] : segmentTargets(command, home, cwd)),
1260
+ ];
1199
1261
  }
1200
1262
 
1201
1263
  /** Where segmentTargets splits a command into parts; the capture keeps each separator as a part. */
@@ -1256,7 +1318,7 @@ function onlyReads(segment: LexedSegment, text: string, skip: LexedWord[] = []):
1256
1318
  if (segmentOperation(text) !== "read") return false;
1257
1319
  const index = commandWordIndex(segment);
1258
1320
  const kept = segment.words.filter((_, at) => !segment.redirects.has(at));
1259
- const strict = unwrapCommand(kept.map((word) => ({ text: decodeWord(word.text), opaque: /[$\x60]/.test(word.text) })));
1321
+ const strict = unwrapCommand(kept.map((word) => strictWord(word.text)));
1260
1322
  if (strict === null) return false;
1261
1323
  const runsAt = [index < 0 ? Infinity : index, strict.index < 0 ? Infinity : segment.words.indexOf(kept[strict.index])];
1262
1324
  if (segment.words.some((word, at) => at < Math.max(...runsAt) && !segment.redirects.has(at) && ASSIGNMENT.test(decodeWord(word.text)))) return false;
@@ -1417,8 +1479,24 @@ function segmentTargets(command: string, home: string, cwd: string): PathTarget[
1417
1479
  // trailing operand counts only when that stage's own command writes or
1418
1480
  // deletes, so the last word of a later read-only stage (`| head -60`) is
1419
1481
  // never taken as the write target of an earlier stage.
1420
- const stages = pipelineStages(segment).map((stage) => {
1421
- const operands: string[] = [];
1482
+ // Files a command's own program writes (sed `w` targets) are write
1483
+ // targets, like redirect operands. A part that holds a piece of a quoted
1484
+ // word the split cut takes them from the owning commands of the whole
1485
+ // lexed command, whose script is not cut.
1486
+ const partFrom = execCuts === null ? 0 : execCuts.offsets[index];
1487
+ const inPart = (word: LexedWord) => word.start < partFrom + rawSegment.length && word.end > partFrom;
1488
+ // Otherwise they come from the part itself, read whole before any group
1489
+ // unwrapping (which strips a trailing `)` from `x=$(sed …)`) and as
1490
+ // unwrapped; every target counts once per part, on its first stage.
1491
+ const partWrites = execCuts !== null && execCuts.words.some(inPart)
1492
+ ? programWriteTargets({ segments: execCuts.lexed.segments.filter((owner) => owner.words.some(inPart)) })
1493
+ : [rawSegment.trim(), segment].flatMap((text) => {
1494
+ let lexedPart = lexCommand(text);
1495
+ if (!lexedPart.trustworthy) lexedPart = lexCommand(ansiPlain(text));
1496
+ return lexedPart.trustworthy ? programWriteTargets(lexedPart) : [];
1497
+ });
1498
+ const stages = pipelineStages(segment).map((stage, stageIndex) => {
1499
+ const operands: string[] = stageIndex === 0 ? [...new Set(partWrites)] : [];
1422
1500
  // A redirect whose target cannot be read statically (empty, or built
1423
1501
  // from `$...`/`$( )`/backticks) may write anywhere, including a
1424
1502
  // protected path the stage names: the stage then counts as a write.