@kaynooo/cli-guard 0.12.1 → 0.13.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 (2) hide show
  1. package/dist/cli.js +258 -43
  2. package/package.json +8 -8
package/dist/cli.js CHANGED
@@ -5,7 +5,7 @@
5
5
  import { appendFileSync as appendFileSync2, existsSync as existsSync5, mkdirSync as mkdirSync2, readFileSync as readFileSync6, rmSync, statSync as statSync2, writeFileSync } from "fs";
6
6
  import { homedir as homedir4 } from "os";
7
7
  import { dirname as dirname5 } from "path";
8
- import process16 from "process";
8
+ import process17 from "process";
9
9
  // ../kit/src/args.ts
10
10
  import process9 from "process";
11
11
  import { parseArgs } from "util";
@@ -344,6 +344,23 @@ var STATUS_WORDS = {
344
344
  var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
345
345
 
346
346
  // ../kit/src/format.ts
347
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
348
+ function formatSeconds(total) {
349
+ let rest = Math.max(0, Math.round(total));
350
+ const amounts = UNITS.map(([unit, size]) => {
351
+ const amount = Math.floor(rest / size);
352
+ rest -= amount * size;
353
+ return `${amount}${unit}`;
354
+ });
355
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
356
+ if (first === -1)
357
+ return "0s";
358
+ const next = amounts[first + 1];
359
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
360
+ }
361
+ function formatDuration(ms) {
362
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
363
+ }
347
364
  function upTo(text, separator) {
348
365
  const end = text.indexOf(separator);
349
366
  return end === -1 ? text : text.slice(0, end);
@@ -352,7 +369,7 @@ var ESCAPE = String.fromCharCode(27);
352
369
 
353
370
  // ../kit/src/help.ts
354
371
  import process7 from "process";
355
- var OPTIONAL = /\[[^\]]+\]/g;
372
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
356
373
  var USAGE_PREFIX = /^usage:\s*/i;
357
374
  var FULL_STOP = /\.$/;
358
375
  function usageLine(usage, colors = paint(process7.stdout)) {
@@ -391,29 +408,40 @@ function exampleRows(examples, colors = paint(process7.stdout)) {
391
408
  return [];
392
409
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
393
410
  }
411
+ var MAX_INLINE_CHOICES = 24;
394
412
  function optionRows(options, colors = paint(process7.stdout)) {
395
413
  const rows = Object.entries(options).map(([name, option]) => {
396
414
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
397
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
415
+ const choices = option.choices?.join("|");
416
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
417
+ const named = inline ? `<${choices}>` : "<value>";
398
418
  const placeholder = option.optional === undefined ? named : `[${named}]`;
399
419
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
400
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
420
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
421
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
401
422
  });
402
423
  const width = Math.max(0, ...rows.map((row) => row.width));
403
424
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
404
425
  }
405
426
 
406
427
  // ../kit/src/text.ts
407
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
408
428
  function distance(a, b) {
409
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
410
- for (const [i, left] of [...a].entries()) {
429
+ const left = [...a];
430
+ const right = [...b];
431
+ let before = [];
432
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
433
+ for (const [i, x] of left.entries()) {
411
434
  const current = [i + 1];
412
- for (const [j, right] of [...b].entries())
413
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
435
+ for (const [j, y] of right.entries()) {
436
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
437
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
438
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
439
+ current.push(cost);
440
+ }
441
+ before = previous;
414
442
  previous = current;
415
443
  }
416
- return previous[b.length] ?? 0;
444
+ return previous[right.length] ?? 0;
417
445
  }
418
446
  function closest(name, names) {
419
447
  const started = names.find((known) => known.startsWith(name));
@@ -775,13 +803,31 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
775
803
  // ../kit/src/cli.ts
776
804
  import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
777
805
  import { dirname as dirname3, join as join5 } from "path";
778
- import process13 from "process";
806
+ import process14 from "process";
807
+
808
+ // ../kit/src/notify.ts
809
+ import process12 from "process";
810
+ var NOTIFY_AFTER_MS = 1e4;
811
+ var CANCELLED = 130;
812
+ function base64(text) {
813
+ return Buffer.from(text).toString("base64");
814
+ }
815
+ function notification(title, body, env = process12.env) {
816
+ const id = `kit${process12.pid}`;
817
+ const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
818
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
819
+ }
820
+ function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
821
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
822
+ return;
823
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
824
+ }
779
825
 
780
826
  // ../kit/src/usage.ts
781
827
  import { appendFileSync, mkdirSync } from "fs";
782
828
  import { homedir as homedir3 } from "os";
783
829
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
784
- import process12 from "process";
830
+ import process13 from "process";
785
831
 
786
832
  // ../kit/src/logs.ts
787
833
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -795,14 +841,14 @@ var usageError;
795
841
  function noteUsageError(message) {
796
842
  usageError = message;
797
843
  }
798
- function stateHome(env = process12.env) {
844
+ function stateHome(env = process13.env) {
799
845
  const dir = env.XDG_STATE_HOME;
800
846
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
801
847
  }
802
- function usagePath(env = process12.env) {
848
+ function usagePath(env = process13.env) {
803
849
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
804
850
  }
805
- function usageRecorded(env = process12.env) {
851
+ function usageRecorded(env = process13.env) {
806
852
  const off = env.KAYNOOO_CLI_NO_USAGE;
807
853
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
808
854
  }
@@ -816,7 +862,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
816
862
  usageError = undefined;
817
863
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
818
864
  }
819
- function recordUsage(entry, env = process12.env) {
865
+ function recordUsage(entry, env = process13.env) {
820
866
  if (!usageRecorded(env))
821
867
  return;
822
868
  try {
@@ -906,8 +952,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
906
952
  `);
907
953
  }
908
954
  function printError(prefix, message, hint, cause) {
909
- const colors = paint(process13.stderr);
910
- const styled = takesControlCodes(process13.stderr);
955
+ const colors = paint(process14.stderr);
956
+ const styled = takesControlCodes(process14.stderr);
911
957
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
912
958
  const under = (label, text, tint) => text === undefined ? "" : `
913
959
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -950,11 +996,11 @@ async function dispatch(level, typed, { version, redact }) {
950
996
  }
951
997
  }
952
998
  if (name === undefined && level.path.length > 1) {
953
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
999
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
954
1000
  return 2;
955
1001
  }
956
1002
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
957
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
1003
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
958
1004
  return 0;
959
1005
  }
960
1006
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1089,10 +1135,13 @@ async function runCli(cli, argv = scriptArgs()) {
1089
1135
  const version = cli.version ?? packageVersion();
1090
1136
  if (argv[0] === COMPLETE)
1091
1137
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1138
+ const started = performance.now();
1092
1139
  const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
1140
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1141
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1093
1142
  if (cli.usage !== false) {
1094
1143
  try {
1095
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1144
+ recordUsage(usageEntry(cli.name, command, argv, code));
1096
1145
  } catch {}
1097
1146
  }
1098
1147
  return code;
@@ -1152,6 +1201,7 @@ var ANSI_ESCAPES = { n: `
1152
1201
  var ANSI_DIGITS = { x: 2, u: 4, U: 8 };
1153
1202
  var OCTAL = /^[0-7]{1,3}/;
1154
1203
  var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
1204
+ var INPUT_REDIRECT = /^\d*<(?![<&(>])/;
1155
1205
  var MAX_DEPTH = 8;
1156
1206
  var MAX_BRACES = 256;
1157
1207
  var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish", "csh", "tcsh", "nu", "xonsh", "elvish", "pwsh", "powershell"]);
@@ -1579,6 +1629,8 @@ function parseCommand(text) {
1579
1629
  } else if (tokens.length > 1 && CASE_LABEL.test(first)) {
1580
1630
  isWrapped = true;
1581
1631
  tokens.shift();
1632
+ } else if (INPUT_REDIRECT.test(first)) {
1633
+ tokens.splice(0, first.replace(INPUT_REDIRECT, "") === "" ? 2 : 1);
1582
1634
  } else if (spec !== undefined) {
1583
1635
  isWrapped = true;
1584
1636
  tokens.shift();
@@ -2183,6 +2235,52 @@ function printsTrackedEnv(program, args) {
2183
2235
  return !rest.some((arg) => GIT_NO_PATCH.has(arg));
2184
2236
  }
2185
2237
 
2238
+ // ../env/src/mask.ts
2239
+ var PLAIN_VALUE = /^(?:true|false|null|none|nil|yes|no|on|off|undefined)$/i;
2240
+ var PLACEHOLDER = /^[$%{<(*/]/;
2241
+ function isPlaceholder(value) {
2242
+ return PLACEHOLDER.test(value) || PLAIN_VALUE.test(value);
2243
+ }
2244
+ var STRONG_NAME = "password|passwd|secret|api[_-]?key|access[_-]?key|private[_-]?key|account[_-]?key|shared[_-]?access[_-]?key";
2245
+ var WEAK_NAME = "token|credentials?|auth";
2246
+ var PLAIN_WORD = /^[a-z]+$/i;
2247
+ var AFTER_COLON = /:\s*$/;
2248
+ var DIGIT = /\d/;
2249
+ var KEY_VALUE_GAP = "\\s*[:=]\\s*";
2250
+ function isProse(value, before) {
2251
+ return isPlaceholder(value) || AFTER_COLON.test(before) && PLAIN_WORD.test(value);
2252
+ }
2253
+ function isWeak(value, before) {
2254
+ return isProse(value, before) || !(DIGIT.test(value) || value.length >= 16);
2255
+ }
2256
+ function keyed(names, value) {
2257
+ return new RegExp(`(?<![\\w-])["']?(?:[\\w-]{0,30}[_-])?(?:${names})(?:[_-][\\w-]{0,30})?["']?${KEY_VALUE_GAP}${value}`, "dgi");
2258
+ }
2259
+ var TOKEN_FORMATS = [
2260
+ { kind: "GitHub token", pattern: /\b(?:gh[pousr]_|github_pat_)\w{20,}/dg },
2261
+ { kind: "GitLab token", pattern: /\bgl(?:pat|rt|dt|ptt)-[\w-]{20,}/dg },
2262
+ { kind: "Hugging Face token", pattern: /\bhf_[A-Za-z]{30,}/dg },
2263
+ { kind: "webhook secret", pattern: /\bwhsec_\w{20,}/dg },
2264
+ { kind: "DigitalOcean token", pattern: /\bdop_v1_\w{20,}/dg },
2265
+ { kind: "Shopify token", pattern: /\bshp(?:at|ca|pa|ss)_\w{20,}/dg },
2266
+ { kind: "password", pattern: /\bmysql(?:dump|admin)?\s+(?:\S+\s+)*?-p([^\s"'|;&-]\S{3,})/dg },
2267
+ { kind: "password", pattern: /\bsshpass\s+(?:-[a-oq-z]\s+)*-p\s*([^\s"'|;&]{4,})/dg },
2268
+ { kind: "API key", pattern: /\bsk-[\w-]{20,}/dg },
2269
+ { kind: "Slack token", pattern: /\bx(?:ox[abprs]|app)-[\w-]{10,}/dg },
2270
+ { kind: "JWT", pattern: /\beyJ[\w-]+\.[\w-]+\.[\w-]+/dg },
2271
+ { kind: "AWS access key", pattern: /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/dg },
2272
+ { kind: "npm token", pattern: /\bnpm_[A-Za-z0-9]{30,}/dg },
2273
+ { kind: "Stripe key", pattern: /\b[sr]k_(?:live|test)_[A-Za-z0-9]{10,}/dg },
2274
+ { kind: "Google API key", pattern: /\bAIza[\w-]{35}/dg },
2275
+ { kind: "SendGrid key", pattern: /\bSG\.[\w-]{16,}\.[\w-]{16,}/dg },
2276
+ { kind: "Authorization header", pattern: /\bAuthorization["']?\s*[:=]\s*["']?(?:Bearer|Basic|Token|Digest)\s+([^\s"',;]{8,})/dgi, skip: isPlaceholder },
2277
+ { kind: "Bearer token", pattern: /\bBearer\s+((?=[\w.~+/=-]*\d)[\w.~+/=-]{20,})/dg },
2278
+ { kind: "password", pattern: keyed(STRONG_NAME, `([^\\s"'&;,]{4,})`), skip: isProse },
2279
+ { kind: "password", pattern: keyed(WEAK_NAME, `([^\\s"'&;,]{4,})`), skip: isWeak },
2280
+ { kind: "password", pattern: keyed(STRONG_NAME, `(["'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1`), skip: isPlaceholder },
2281
+ { kind: "password", pattern: keyed(WEAK_NAME, `(["'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1`), skip: isWeak }
2282
+ ];
2283
+
2186
2284
  // ../env/src/files.ts
2187
2285
  var ENV_FILE = /^(?:\.env(?:\..+)?|.+\.env|\.envrc)$/;
2188
2286
  var TEMPLATE = /\.(?:example|sample|template|dist|defaults)$/;
@@ -2693,7 +2791,7 @@ function wrap(command) {
2693
2791
  // ../pkg/src/added.ts
2694
2792
  import { existsSync as existsSync4, readdirSync, readFileSync as readFileSync5 } from "fs";
2695
2793
  import { dirname as dirname4, join as join6 } from "path";
2696
- import process15 from "process";
2794
+ import process16 from "process";
2697
2795
  var REDIRECT2 = /^\d*[<>]/;
2698
2796
  var BARE_REDIRECT = /^\d*(?:[<>]|>>)$/;
2699
2797
  var ADDS = {
@@ -2725,7 +2823,7 @@ function manifestName(folder) {
2725
2823
  }
2726
2824
  function ownPackages() {
2727
2825
  const names = new Set;
2728
- let folder = process15.cwd();
2826
+ let folder = process16.cwd();
2729
2827
  while (true) {
2730
2828
  const name = manifestName(folder);
2731
2829
  if (name !== undefined)
@@ -2830,7 +2928,7 @@ var OPTION_FLAGS = new Map([
2830
2928
  ]);
2831
2929
  var DIR_FLAGS = new Set(["--cwd", "-C", "--dir", "--prefix"]);
2832
2930
  var VALUE_FLAGS2 = new Set([...DIR_FLAGS, "--filter", "-F"]);
2833
- var PLAIN_WORD = /^[\w=@./:+-]+$/;
2931
+ var PLAIN_WORD2 = /^[\w=@./:+-]+$/;
2834
2932
  function actions(byAction) {
2835
2933
  return new Map(Object.entries(byAction).flatMap(([action, names]) => names.map((name) => [name, action])));
2836
2934
  }
@@ -2843,7 +2941,7 @@ function translate(from, to, subcommand, rest) {
2843
2941
  const listed = ACTIONS[from].get(subcommand);
2844
2942
  const action = listed === "install" && packages.length > 0 ? "add" : listed;
2845
2943
  const command = action ? COMMANDS[to][action] : undefined;
2846
- if (!action || command === undefined || !packages.every((name) => PLAIN_WORD.test(name)))
2944
+ if (!action || command === undefined || !packages.every((name) => PLAIN_WORD2.test(name)))
2847
2945
  return null;
2848
2946
  const options = [];
2849
2947
  for (const flag of flags) {
@@ -2897,7 +2995,7 @@ function mismatchFor(request, pinned) {
2897
2995
  return null;
2898
2996
  const expected = [...pinned.managers];
2899
2997
  const only = expected.length === 1 ? expected[0] : undefined;
2900
- const canRewrite = only !== undefined && isRewritable && assignments.every((word) => PLAIN_WORD.test(word));
2998
+ const canRewrite = only !== undefined && isRewritable && assignments.every((word) => PLAIN_WORD2.test(word));
2901
2999
  const translated = canRewrite ? translate(program, only, subcommand, rest) : null;
2902
3000
  const leading = piece.text.slice(0, piece.text.length - piece.text.trimStart().length);
2903
3001
  const trailing = piece.text.slice(piece.text.trimEnd().length);
@@ -3176,6 +3274,10 @@ var FETCH_SUBSTITUTION = /(?:\$\(|<\(|`)\s*(?:curl|wget|fetch)\b/;
3176
3274
  var RECURSIVE_LETTER = /r/i;
3177
3275
  var HOME_PREFIX = /^(?:~|\$HOME|\$\{HOME(?::?[-?=+][^}]*)?\}?)(?=\/|$)/;
3178
3276
  var CURRENT_DIRECTORY = /^(?:\$PWD|\$\{PWD\}?|\$\(pwd\)?|`pwd`?)(?=\/|$)/;
3277
+ var ABSOLUTE_HOME = /^(?:home\/[^/]+|root)\/([^/]+)$/;
3278
+ var EXEC_FLAGS = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
3279
+ var REMOVER = /(?:^|\/)rm$/;
3280
+ var TRAILING_SLASH = /\/$/;
3179
3281
  var SAFE_REBASE = new Set(["--abort", "--continue", "--quit", "--show-current-patch", "--skip", "--edit-todo"]);
3180
3282
  var INTERPRETERS2 = new Set(["python", "node", "bun", "perl", "ruby"]);
3181
3283
  var VERSION_SUFFIX = /[\d.]+$/;
@@ -3191,6 +3293,10 @@ var BRANCH_DELETE = "Never `git branch -D`: it drops commits no other branch hol
3191
3293
  var REBASE = `Never start a \`git rebase\`: it rewrites history and stops halfway on conflicts in a tree others edit. ${COMMIT_FIRST} \`git cherry-pick\` or \`git merge\` keep history, and \`git worktree add\` gives a clean tree to do it in. \`--continue\` and \`--abort\` stay allowed.`;
3192
3294
  var REWRITE_HISTORY = "Never `git filter-branch` or `git filter-repo`: they rewrite every commit of the repository. Ask the user to run it themselves.";
3193
3295
  var BROAD_RM = "Never `rm -r` on `/`, `~`, `$HOME`, `.`, `..`, `*` or a top-level directory: it deletes far more than the task. Name the exact directory, such as `dist` or `node_modules`.";
3296
+ var PROTECTED_RM = "Never `rm -r` on a `.git` directory, on `~/Workspace` itself or on a dot-directory of the home (`~/.ssh`, `$HOME/.claude`, `~/.config`): it deletes a repository's whole history, every project, or the credentials and settings of the machine. Remove the named files inside, or ask the user to run it.";
3297
+ var FIND_DELETE_HOME = 'Never `find ~ -delete` or `find / -exec rm` (also `$HOME`): it deletes matches across the whole home or disk. Start `find` in the project folder or `.` and name the pattern, such as `find . -name "*.tmp" -delete`.';
3298
+ var REFLOG_EXPIRE = "Never `git reflog expire`, `git gc --prune=now` or `git update-ref -d`: they drop the reflog, unreachable commits or a ref, the only way back from a bad reset or rebase. Let git prune on its own schedule, and ask the user to run one when it is really wanted.";
3299
+ var DOCKER_PRUNE_ALL = "Never `docker system prune -a` (`--all`): it removes every image not used by a running container, volumes of other projects' stacks included with --volumes. `docker system prune` without -a drops only dangling data; remove named images with `docker rmi`.";
3194
3300
  var PIPE_TO_SHELL = 'Never run what `curl`/`wget` fetches straight in a shell (`| sh`, `bash <(curl ...)`, `eval "$(curl ...)"`): it runs code nobody read. Download it to a file, read it, then run it, or hand the command to the user.';
3195
3301
  function hasOption(args, long, shorts) {
3196
3302
  for (const arg of args) {
@@ -3220,15 +3326,32 @@ function isBroadPath(path) {
3220
3326
  return parts.length === 0;
3221
3327
  return isAbsolute ? parts.length <= 1 : parts.every((part) => part === "..");
3222
3328
  }
3223
- function removesBroadly(args) {
3224
- if (args.includes("--no-preserve-root"))
3225
- return true;
3329
+ function recursiveTargets(args) {
3226
3330
  const options = args.slice(0, args.includes("--") ? args.indexOf("--") : args.length);
3227
3331
  const isRecursive = options.some((arg) => arg === "--recursive" || SHORT_CLUSTER.test(arg) && RECURSIVE_LETTER.test(arg));
3228
- if (!isRecursive)
3229
- return false;
3230
- const targets = args.filter((arg, i) => !arg.startsWith("-") || args.includes("--") && i > args.indexOf("--"));
3231
- return targets.some(isBroadPath);
3332
+ return isRecursive ? args.filter((arg, i) => !arg.startsWith("-") || args.includes("--") && i > args.indexOf("--")) : [];
3333
+ }
3334
+ function isProtectedPath(path) {
3335
+ const home = HOME_PREFIX.exec(path);
3336
+ const parts = (home === null ? path : path.slice(home[0].length)).split("/").filter((part) => part !== "" && part !== ".");
3337
+ const last = parts.at(-1) ?? "";
3338
+ const absolute = path.startsWith("/") ? ABSOLUTE_HOME.exec(parts.join("/")) : null;
3339
+ const homeChild = parts.length === 1 ? last : undefined;
3340
+ const child = home === null ? absolute?.[1] : homeChild;
3341
+ return last === ".git" || child !== undefined && (child === "Workspace" || child.startsWith(".") && child !== "..");
3342
+ }
3343
+ function deletesFromHome(args) {
3344
+ const firstOption = args.findIndex((arg) => arg.startsWith("-") || arg === "(" || arg === "!");
3345
+ const starts = firstOption === -1 ? args : args.slice(0, firstOption);
3346
+ const deletes = args.includes("-delete") || args.some((arg, i) => EXEC_FLAGS.has(arg) && REMOVER.test(args[i + 1] ?? ""));
3347
+ return deletes && starts.some((start) => start === "/" || start.replace(TRAILING_SLASH, "") === HOME_PREFIX.exec(start)?.[0]);
3348
+ }
3349
+ function dockerPrunesAll(args) {
3350
+ const system = args.indexOf("system");
3351
+ return system !== -1 && args[system + 1] === "prune" && hasOption(args.slice(system + 2), ["--all"], "a");
3352
+ }
3353
+ function removesBroadly(args) {
3354
+ return args.includes("--no-preserve-root") || recursiveTargets(args).some(isBroadPath);
3232
3355
  }
3233
3356
  function checksOutTree(rest, operands) {
3234
3357
  if (rest.includes("--"))
@@ -3259,6 +3382,12 @@ function gitDestructive(name, rest) {
3259
3382
  }
3260
3383
  if (name === "branch")
3261
3384
  return hasOption(rest, [], "D") || hasOption(rest, ["--delete"], "d") && hasOption(rest, ["--force"], "f") ? BRANCH_DELETE : null;
3385
+ if (name === "reflog")
3386
+ return rest[0] === "expire" ? REFLOG_EXPIRE : null;
3387
+ if (name === "gc")
3388
+ return rest.some((arg) => arg === "--prune=now" || arg === "--prune=all") ? REFLOG_EXPIRE : null;
3389
+ if (name === "update-ref")
3390
+ return hasOption(rest, ["--delete"], "d") ? REFLOG_EXPIRE : null;
3262
3391
  if (name === "rebase")
3263
3392
  return rest.some((arg) => SAFE_REBASE.has(arg)) ? null : REBASE;
3264
3393
  return name === "filter-branch" || name === "filter-repo" ? REWRITE_HISTORY : null;
@@ -3292,6 +3421,12 @@ function destructiveViolation(command) {
3292
3421
  const { program, args } = parseCommand(piece.command);
3293
3422
  if (program === "rm" && removesBroadly(args))
3294
3423
  return BROAD_RM;
3424
+ if (program === "rm" && recursiveTargets(args).some(isProtectedPath))
3425
+ return PROTECTED_RM;
3426
+ if (program === "find" && deletesFromHome(args))
3427
+ return FIND_DELETE_HOME;
3428
+ if (program === "docker" && dockerPrunesAll(args))
3429
+ return DOCKER_PRUNE_ALL;
3295
3430
  const git = gitCommandOf(program, args);
3296
3431
  if (git === undefined)
3297
3432
  continue;
@@ -3302,6 +3437,83 @@ function destructiveViolation(command) {
3302
3437
  return null;
3303
3438
  }
3304
3439
 
3440
+ // src/embedded.ts
3441
+ var PRINTERS3 = new Set(["echo", "printf"]);
3442
+ var ECHO_FLAGS = /^-[neE]+$/;
3443
+ var SHELL_STRING_FLAG = /^-[ABD-Z]*C[A-Z]*$/i;
3444
+ var PRINTF_SPEC = /%[sb]/g;
3445
+ var ESCAPE2 = /\\(.)/gs;
3446
+ var VERSION_SUFFIX2 = /[\d.]+$/;
3447
+ var CODE_FLAGS = new Map([["python", ["-c"]], ["perl", ["-e", "-E"]], ["ruby", ["-e"]], ["node", ["-e", "--eval", "-p", "--print"]], ["bun", ["-e", "--eval", "-p", "--print"]]]);
3448
+ var BACKTICK = String.fromCharCode(96);
3449
+ var QUOTED = String.raw`'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|${BACKTICK}(?:[^${BACKTICK}\\]|\\.)*${BACKTICK}`;
3450
+ var ARGV = new RegExp(String.raw`[[(]\s*((?:(?:${QUOTED})\s*,\s*)+(?:${QUOTED}))\s*(?:,\s*)?[\])]`, "gs");
3451
+ var LITERAL = new RegExp(QUOTED, "gs");
3452
+ var RUNS_SHELL = /(?:\b(?:system|exec\w*|spawn\w*|popen|run|call|check_\w+|Popen|getoutput|qx)|\$)\s*(?:\(\s*)?$/;
3453
+ var SHELL_BACKTICKS = new Set(["perl", "ruby"]);
3454
+ var ESCAPED = new Map([["n", `
3455
+ `], ["t", " "]]);
3456
+ function decode(text) {
3457
+ return text.replaceAll(ESCAPE2, (_, char) => ESCAPED.get(char) ?? char);
3458
+ }
3459
+ function literalValue(literal) {
3460
+ return decode(literal.slice(1, -1));
3461
+ }
3462
+ function printfText(args) {
3463
+ const [format = "", ...values] = args;
3464
+ const specs = format.match(PRINTF_SPEC)?.length ?? 0;
3465
+ if (specs === 0)
3466
+ return decode(format);
3467
+ let text = "";
3468
+ for (let rest = values;; rest = rest.slice(specs)) {
3469
+ let index = 0;
3470
+ text += format.replaceAll(PRINTF_SPEC, () => rest[index++] ?? "");
3471
+ if (rest.length <= specs)
3472
+ return decode(text);
3473
+ }
3474
+ }
3475
+ function printed(command) {
3476
+ const { program, args } = parseCommand(command);
3477
+ if (!PRINTERS3.has(program))
3478
+ return null;
3479
+ if (program === "printf")
3480
+ return printfText(args[0] === "--" ? args.slice(1) : args);
3481
+ return args.filter((arg, index) => !(ECHO_FLAGS.test(arg) && args.slice(0, index).every((before) => ECHO_FLAGS.test(before)))).join(" ");
3482
+ }
3483
+ function readsStdin(args) {
3484
+ if (args.some((arg) => SHELL_STRING_FLAG.test(arg)))
3485
+ return false;
3486
+ return args.includes("-s") || args.includes("-") || args.every((arg) => arg.startsWith("-"));
3487
+ }
3488
+ function fedCommands(command) {
3489
+ const pieces = splitCommand(command);
3490
+ return pieces.flatMap((piece, index) => {
3491
+ const before = pieces[index - 1];
3492
+ const { program, args } = parseCommand(piece.command);
3493
+ if (!SHELLS.has(program) || before?.separator !== "|" || !readsStdin(args))
3494
+ return [];
3495
+ const text = printed(before.command);
3496
+ return text === null ? [] : text.split(`
3497
+ `).filter((line) => line.trim() !== "");
3498
+ });
3499
+ }
3500
+ function scriptedCommands(command) {
3501
+ return splitCommand(command).flatMap((piece) => {
3502
+ const { program, args } = parseCommand(piece.command);
3503
+ const language = program.replace(VERSION_SUFFIX2, "");
3504
+ const flags = CODE_FLAGS.get(language);
3505
+ const flag = flags === undefined ? -1 : args.findIndex((arg) => flags.includes(arg));
3506
+ const code = flag === -1 ? undefined : args[flag + 1];
3507
+ if (code === undefined)
3508
+ return [];
3509
+ const argvs = [...code.matchAll(ARGV)].map(([, list = ""]) => (list.match(LITERAL) ?? []).map(literalValue).join(" "));
3510
+ const runs = [...code.matchAll(LITERAL)].filter(({ 0: literal, index }) => RUNS_SHELL.test(code.slice(0, index)) || literal.startsWith("`") && SHELL_BACKTICKS.has(language));
3511
+ const lines = runs.flatMap(([literal]) => literalValue(literal).split(`
3512
+ `));
3513
+ return [...argvs, ...lines].filter((line) => line.trim() !== "");
3514
+ });
3515
+ }
3516
+
3305
3517
  // src/remote.ts
3306
3518
  var SHELL_PROGRAMS = new Set(["ssh", "scp", "sftp", "mosh", "mosh-client", "autossh"]);
3307
3519
  var SOCKET_PROGRAMS = new Set(["nc", "ncat", "netcat", "telnet", "socat"]);
@@ -3403,7 +3615,7 @@ var PYTHON_COUNT = /^\s*,\s*(\d+)\s*\)/;
3403
3615
  var SPACE2 = /^\s*/;
3404
3616
  var COMMA = /^\s*,\s*/;
3405
3617
  var REGEX_FLAGS = /^[gm]*$/;
3406
- var PLAIN_WORD2 = /^[\w@%+=:,./*?-]+$/;
3618
+ var PLAIN_WORD3 = /^[\w@%+=:,./*?-]+$/;
3407
3619
  var SED_SEPARATORS = /^[\s;]*/;
3408
3620
  var SED_SEPARATOR = /[\s;]/;
3409
3621
  var BRE_ESCAPED = new Map([["(", "("], [")", ")"], ["{", "{"], ["}", "}"], ["+", "+"], ["?", "?"], ["|", "|"]]);
@@ -3666,7 +3878,7 @@ function sedPairs(script, isExtended) {
3666
3878
  return pairs.length === 0 ? undefined : pairs;
3667
3879
  }
3668
3880
  function fileWord(path) {
3669
- return PLAIN_WORD2.test(path) ? path : shellQuote(path);
3881
+ return PLAIN_WORD3.test(path) ? path : shellQuote(path);
3670
3882
  }
3671
3883
  function flagsOf(pair) {
3672
3884
  return [pair.regex === true ? " --regex" : "", pair.all === true ? " --all" : "", pair.count === undefined ? "" : ` -n ${pair.count}`].join("");
@@ -3789,7 +4001,9 @@ async function checkCommand(command, context) {
3789
4001
  if (message !== null)
3790
4002
  violations.push({ rule, message });
3791
4003
  };
3792
- const run = commandsRun(command);
4004
+ const shown = commandsRun(command);
4005
+ const run = [...shown, ...shown.flatMap(fedCommands).flatMap((each) => commandsRun(each))];
4006
+ const scripted = run.flatMap(scriptedCommands).flatMap((each) => commandsRun(each));
3793
4007
  const first = (messages) => messages.find((message) => message !== null) ?? null;
3794
4008
  const guarded = async (rule, check) => {
3795
4009
  try {
@@ -3801,8 +4015,8 @@ async function checkCommand(command, context) {
3801
4015
  };
3802
4016
  const readSql = async (path) => Promise.resolve(context.read(absolute(path, context.cwd)));
3803
4017
  add("remote", await guarded("remote", () => first(run.map(remoteViolation))));
3804
- add("git", await guarded("git", () => first(run.map((each) => gitViolation(each, context.isPushAsked)))));
3805
- add("destructive", await guarded("destructive", () => first(run.map(destructiveViolation))));
4018
+ add("git", await guarded("git", () => first([...run, ...scripted].map((each) => gitViolation(each, context.isPushAsked)))));
4019
+ add("destructive", await guarded("destructive", () => first([...run, ...scripted].map(destructiveViolation))));
3806
4020
  const commit = await guarded("commit", () => first(run.map((each) => commitViolation(each, context))));
3807
4021
  add("commit", commit === null ? null : `${commit} ${USE_GC}`);
3808
4022
  add("sql", await guarded("sql", async () => first(await Promise.all(run.map(async (each) => sqlViolation(each, readSql))))));
@@ -3850,6 +4064,7 @@ var BINS = {
3850
4064
  gp: "`gp [--repos] [dir]...`: pushes the current branch when it is ahead of its upstream, with `-u` to origin when it has none, `--repos` every repository nested below too, `--dry-run` saying what would go, flags for git push after `--`; only when the user asked for a push, like `git push`.",
3851
4065
  gb: "`gb [branch]`: switches to a branch, a remote one getting its tracking branch, `gb -c <name>` creating one; without a terminal it lists the branches (`--json`), with how each stands against its upstream and whether it is merged.",
3852
4066
  gf: "`gf [--repos] [dir]...`: fetches with prune and fast-forwards the branch onto its upstream, saying what came in; a diverged branch or a tree the fast-forward would overwrite is refused untouched, `--no-pull` fetches only; use it instead of `git pull` and a git fetch per nested repository.",
4067
+ gm: "`gm [branch]`: merges the branch into the current one, saying fast-forward or merge commit, the commits and the files that came in; a conflict lists every conflicted file with its conflict regions and exits 1, `--dry-run` tries the merge without touching the tree, `--continue`/`--abort`, `--squash`; with no branch it picks one, or lists each with its verdict off a terminal; use it instead of git merge then git diff and reading conflict markers.",
3853
4068
  gcl: "`gcl <repo> [dir]`: clones a URL, scp address or owner/name into the workspace folder and prints the path, an existing clone being fetched instead; use it instead of git clone with the folder typed out.",
3854
4069
  gd: "`gd [path]...`: the tracked changes per file with added and removed lines, staged apart from unstaged, the patch of the paths given, `--staged`, `--ref <rev>`; use it instead of `git diff --stat` then `git diff <path>`.",
3855
4070
  gu: "`gu <path>...`: discards the unstaged changes of the paths after saving them as a patch, `--staged` unstages, `--commit` undoes the last unpushed commit keeping its changes staged; use it instead of git restore and git reset.",
@@ -4014,7 +4229,7 @@ function readText(path) {
4014
4229
  }
4015
4230
  function report2(violations) {
4016
4231
  for (const { rule, message } of violations)
4017
- console.log(`${role("problem", process16.stdout)(rule)}: ${message}`);
4232
+ console.log(`${role("problem", process17.stdout)(rule)}: ${message}`);
4018
4233
  }
4019
4234
  async function check(args) {
4020
4235
  const parsed = parse(args, checkUsage, checkOptions, { exits: CHECK_EXITS });
@@ -4026,7 +4241,7 @@ ${checkUsage}`);
4026
4241
  const given = positionals[0] ?? "-";
4027
4242
  const command = given === "-" ? await readInput("-", { noStdin: "give the command, or pipe it on stdin" }) : given;
4028
4243
  const context = {
4029
- cwd: values.cwd ?? process16.cwd(),
4244
+ cwd: values.cwd ?? process17.cwd(),
4030
4245
  home: homedir4(),
4031
4246
  isPushAsked: values["push-asked"] === true,
4032
4247
  canRewrite: true,
@@ -4041,7 +4256,7 @@ ${checkUsage}`);
4041
4256
  else
4042
4257
  report2(verdict.violations);
4043
4258
  if (values.json !== true && verdict.command !== command)
4044
- console.log(`${role("label", process16.stdout)("runs as:")} ${verdict.command}${verdict.notes.map((note) => `
4259
+ console.log(`${role("label", process17.stdout)("runs as:")} ${verdict.command}${verdict.notes.map((note) => `
4045
4260
  ${note}`).join("")}`);
4046
4261
  return verdict.violations.length > 0 ? 1 : 0;
4047
4262
  }
@@ -4072,7 +4287,7 @@ function rules(args) {
4072
4287
  return 0;
4073
4288
  }
4074
4289
  for (const rule of RULES2)
4075
- console.log(`${role("id", process16.stdout)(rule.name)}${" ".repeat(Math.max(0, 16 - rule.name.length))} ${rule.refuses}
4290
+ console.log(`${role("id", process17.stdout)(rule.name)}${" ".repeat(Math.max(0, 16 - rule.name.length))} ${rule.refuses}
4076
4291
  ${" ".repeat(16)} -> ${rule.route}${rule.runs === "hook" ? " (hook only)" : ""}`);
4077
4292
  return 0;
4078
4293
  }
@@ -4111,7 +4326,7 @@ ${hookUsage}`, 1);
4111
4326
  console.log(JSON.stringify(reply));
4112
4327
  return 0;
4113
4328
  }
4114
- process16.exitCode = await runCli({
4329
+ process17.exitCode = await runCli({
4115
4330
  name: "guard",
4116
4331
  usage: false,
4117
4332
  about: "the safety rules a Claude Code Bash call is held to, each refusal naming the route",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-guard",
3
3
  "type": "module",
4
- "version": "0.12.1",
4
+ "version": "0.13.0",
5
5
  "description": "guard: the safety rules a Claude Code Bash call is held to (git, remote machines, SQL writes, env files, package managers, commit messages), each refusal naming the route.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -36,12 +36,12 @@
36
36
  "guard": "$npm_execpath src/cli.ts"
37
37
  },
38
38
  "devDependencies": {
39
- "@kaynooo/cli-db": "0.12.1",
40
- "@kaynooo/cli-edit": "0.10.1",
41
- "@kaynooo/cli-env": "0.13.2",
42
- "@kaynooo/cli-git": "0.15.1",
43
- "@kaynooo/cli-kit": "0.38.2",
44
- "@kaynooo/cli-out": "0.14.3",
45
- "@kaynooo/cli-pkg": "0.15.0"
39
+ "@kaynooo/cli-db": "0.13.0",
40
+ "@kaynooo/cli-edit": "0.11.0",
41
+ "@kaynooo/cli-env": "0.13.3",
42
+ "@kaynooo/cli-git": "0.16.0",
43
+ "@kaynooo/cli-kit": "0.39.0",
44
+ "@kaynooo/cli-out": "0.14.4",
45
+ "@kaynooo/cli-pkg": "0.15.2"
46
46
  }
47
47
  }