@kaynooo/cli-guard 0.7.2 → 0.8.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 (3) hide show
  1. package/README.md +1 -0
  2. package/dist/cli.js +409 -283
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -24,6 +24,7 @@ Every rule reads the command with one shell parser (`packages/kit/src/shell.ts`)
24
24
 
25
25
  ## Behaviour
26
26
 
27
+ - `guard rules [--json]` lists every rule with what it refuses, its route and where it runs. A test checks that `guard check` and `guard hook` give the same refusals for a corpus of commands.
27
28
  - `guard check <command>` takes the command as one argument, or from stdin with `-` or when none is given; `--cwd` is the directory it runs in, for the files and lockfiles the rules read.
28
29
  - Clean: nothing printed, exit 0. Broken: one `<rule>: <route>` line per broken rule, exit 1.
29
30
  - Some rules rewrite rather than refuse: an install with the wrong manager runs with the pinned one, and a noisy test, lint or build run goes through `out` when it is installed (`--no-wrap` to skip). The text output says `runs as: <command>` and why.
package/dist/cli.js CHANGED
@@ -2,13 +2,13 @@
2
2
  // @bun
3
3
 
4
4
  // src/cli.ts
5
- import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "fs";
6
- import { homedir } from "os";
7
- import { dirname } from "path";
8
- import process7 from "process";
5
+ import { appendFileSync as appendFileSync2, existsSync, mkdirSync as mkdirSync2, readFileSync, rmSync, statSync, writeFileSync } from "fs";
6
+ import { homedir as homedir2 } from "os";
7
+ import { dirname as dirname2 } from "path";
8
+ import process10 from "process";
9
9
 
10
10
  // ../kit/src/args.ts
11
- import process3 from "process";
11
+ import process5 from "process";
12
12
  import { parseArgs } from "util";
13
13
 
14
14
  // ../kit/src/style.ts
@@ -298,6 +298,55 @@ function upTo(text, separator) {
298
298
  }
299
299
  var ESCAPE = String.fromCharCode(27);
300
300
 
301
+ // ../kit/src/help.ts
302
+ import process3 from "process";
303
+ var OPTIONAL = /\[[^\]]+\]/g;
304
+ var USAGE_PREFIX = /^usage:\s*/i;
305
+ var FULL_STOP = /\.$/;
306
+ function usageLine(usage, colors = paint(process3.stdout)) {
307
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
308
+ }
309
+ function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
310
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
311
+ `);
312
+ }
313
+ function replacesRows(replaces, colors = paint(process3.stdout)) {
314
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
315
+ }
316
+ function wantsHelpJson(env = process3.env) {
317
+ return env.KIT_HELP === "json";
318
+ }
319
+ function description(usage, { examples = [], replaces } = {}) {
320
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
321
+ `);
322
+ const first = lines[0];
323
+ const colon = first.indexOf(": ");
324
+ const prose = lines[lines.indexOf("") + 1] ?? "";
325
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
326
+ return {
327
+ synopsis: colon === -1 ? first : first.slice(0, colon),
328
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
329
+ ...replaces === undefined ? {} : { replaces },
330
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
331
+ };
332
+ }
333
+ function exampleRows(examples, colors = paint(process3.stdout)) {
334
+ if (examples.length === 0)
335
+ return [];
336
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
337
+ }
338
+ function optionRows(options, colors = paint(process3.stdout)) {
339
+ const rows = Object.entries(options).map(([name, option]) => {
340
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
341
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
342
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
343
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
344
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
345
+ });
346
+ const width = Math.max(0, ...rows.map((row) => row.width));
347
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
348
+ }
349
+
301
350
  // ../kit/src/text.ts
302
351
  var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
303
352
  function distance(a, b) {
@@ -317,8 +366,22 @@ function closest(name, names) {
317
366
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
318
367
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
319
368
  }
369
+ // ../kit/src/input.ts
370
+ import process4 from "process";
371
+ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
372
+ if (path === "-") {
373
+ if (process4.stdin.isTTY)
374
+ fail(noStdin);
375
+ return Bun.stdin.text();
376
+ }
377
+ const file = Bun.file(path);
378
+ if (!await file.exists())
379
+ fail(`no file ${path}`);
380
+ return file.text();
381
+ }
320
382
 
321
383
  // ../kit/src/args.ts
384
+ var DASHES = /^-+/;
322
385
  function jsonOption(holds) {
323
386
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
324
387
  }
@@ -362,58 +425,11 @@ class Completing {
362
425
  }
363
426
  }
364
427
  var completion = { active: false };
365
- var OPTIONAL = /\[[^\]]+\]/g;
366
- var USAGE_PREFIX = /^usage:\s*/i;
367
- var FULL_STOP = /\.$/;
368
- var DASHES = /^-+/;
369
- function usageLine(usage, colors = paint(process3.stdout)) {
370
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
371
- }
372
- function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
373
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
374
- `);
375
- }
376
- function replacesRows(replaces, colors = paint(process3.stdout)) {
377
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
378
- }
379
- function wantsHelpJson(env = process3.env) {
380
- return env.KIT_HELP === "json";
381
- }
382
- function description(usage, { examples = [], replaces } = {}) {
383
- const lines = usage.replace(USAGE_PREFIX, "").split(`
384
- `);
385
- const first = lines[0];
386
- const colon = first.indexOf(": ");
387
- const prose = lines[lines.indexOf("") + 1] ?? "";
388
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
389
- return {
390
- synopsis: colon === -1 ? first : first.slice(0, colon),
391
- summary: colon === -1 ? fallback : first.slice(colon + 2),
392
- ...replaces === undefined ? {} : { replaces },
393
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
394
- };
395
- }
396
- function exampleRows(examples, colors = paint(process3.stdout)) {
397
- if (examples.length === 0)
398
- return [];
399
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
400
- }
401
- function optionRows(options, colors = paint(process3.stdout)) {
402
- const rows = Object.entries(options).map(([name, option]) => {
403
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
404
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
405
- const placeholder = option.optional === undefined ? named : `[${named}]`;
406
- const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
407
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
408
- });
409
- const width = Math.max(0, ...rows.map((row) => row.width));
410
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
411
- }
412
428
  var OUTPUT_OPTIONS = {
413
429
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
414
430
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
415
431
  };
416
- function applyOutput(color, plain, env = process3.env) {
432
+ function applyOutput(color, plain, env = process5.env) {
417
433
  const when = plain === true ? "never" : color ?? "auto";
418
434
  if (when === "auto")
419
435
  return;
@@ -570,20 +586,9 @@ function nearestOption(message, options, allowNegative) {
570
586
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
571
587
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
572
588
  }
573
- async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
574
- if (path === "-") {
575
- if (process3.stdin.isTTY)
576
- fail(noStdin);
577
- return Bun.stdin.text();
578
- }
579
- const file = Bun.file(path);
580
- if (!await file.exists())
581
- fail(`no file ${path}`);
582
- return file.text();
583
- }
584
589
  // ../kit/src/process.ts
585
590
  import { constants } from "os";
586
- import process4 from "process";
591
+ import process6 from "process";
587
592
  var KILL_GRACE_MS = 2000;
588
593
  function exitCodeOf(code, signal) {
589
594
  if (code !== null)
@@ -603,7 +608,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
603
608
  return;
604
609
  try {
605
610
  if (grouped)
606
- process4.kill(-proc.pid, killing);
611
+ process6.kill(-proc.pid, killing);
607
612
  else
608
613
  proc.kill(killing);
609
614
  } catch {}
@@ -677,7 +682,59 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
677
682
  var RESET_STYLE = `${ESC}[0m`;
678
683
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
679
684
  // ../kit/src/cli.ts
680
- import process5 from "process";
685
+ import process8 from "process";
686
+
687
+ // ../kit/src/usage.ts
688
+ import { appendFileSync, mkdirSync } from "fs";
689
+ import { homedir } from "os";
690
+ import { dirname, isAbsolute, join } from "path";
691
+ import process7 from "process";
692
+
693
+ // ../kit/src/logs.ts
694
+ var DAY_MS = 24 * 60 * 60 * 1000;
695
+ var CLI_FOLDER = "kaynooo-cli";
696
+
697
+ // ../kit/src/usage.ts
698
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
699
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
700
+ var LONGEST_NAME = 40;
701
+ var usageError;
702
+ function noteUsageError(message) {
703
+ usageError = message;
704
+ }
705
+ function stateHome(env = process7.env) {
706
+ const dir = env.XDG_STATE_HOME;
707
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
708
+ }
709
+ function usagePath(env = process7.env) {
710
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
711
+ }
712
+ function usageRecorded(env = process7.env) {
713
+ const off = env.KAYNOOO_CLI_NO_USAGE;
714
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
715
+ }
716
+ function flagNames(argv) {
717
+ const end = argv.indexOf("--");
718
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
719
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
720
+ }
721
+ function usageEntry(bin, command, argv, code, now = new Date) {
722
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
723
+ usageError = undefined;
724
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
725
+ }
726
+ function recordUsage(entry, env = process7.env) {
727
+ if (!usageRecorded(env))
728
+ return;
729
+ try {
730
+ const path = usagePath(env);
731
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
732
+ appendFileSync(path, `${JSON.stringify(entry)}
733
+ `, { mode: 384 });
734
+ } catch {}
735
+ }
736
+
737
+ // ../kit/src/cli.ts
681
738
  var LEVEL_OPTIONS = {
682
739
  ...OUTPUT_OPTIONS,
683
740
  help: { type: "boolean", short: "h", description: "show this help" }
@@ -730,7 +787,7 @@ async function expand(scope, words) {
730
787
  }
731
788
  return { ...scope, commands, lazy: [] };
732
789
  }
733
- async function help({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
790
+ async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
734
791
  const colors = paint(stream);
735
792
  const prefix = path.join(" ");
736
793
  const summary = await resolveSummary(lazySummary);
@@ -757,8 +814,8 @@ async function help({ path, header, summary: lazySummary, commands, defaultComma
757
814
  `);
758
815
  }
759
816
  function printError(prefix, message, hint, cause) {
760
- const colors = paint(process5.stderr);
761
- const styled = takesControlCodes(process5.stderr);
817
+ const colors = paint(process8.stderr);
818
+ const styled = takesControlCodes(process8.stderr);
762
819
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
763
820
  const under = (label, text, tint) => text === undefined ? "" : `
764
821
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -777,6 +834,8 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
777
834
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
778
835
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
779
836
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
837
+ if (error instanceof UsageError)
838
+ noteUsageError(error.message);
780
839
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
781
840
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
782
841
  return error instanceof Exit ? error.code : 1;
@@ -799,11 +858,11 @@ async function dispatch(level, typed, { version, redact }) {
799
858
  }
800
859
  }
801
860
  if (name === undefined && level.path.length > 1) {
802
- console.error(await help(await expand(level, [...level.path.slice(1), ...argv]), process5.stderr));
861
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stderr));
803
862
  return 2;
804
863
  }
805
864
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
806
- console.log(await help(await expand(level, [...level.path.slice(1), ...argv]), process5.stdout));
865
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process8.stdout));
807
866
  return 0;
808
867
  }
809
868
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -919,13 +978,32 @@ async function printCandidates(found) {
919
978
  console.log(line);
920
979
  return 0;
921
980
  }
922
- async function runCli(cli, argv = process5.argv.slice(2)) {
981
+ async function runCli(cli, argv = process8.argv.slice(2)) {
923
982
  if (argv[0] === COMPLETE)
924
983
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
925
- return dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(cli.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: cli.version, redact: cli.redact });
984
+ const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(cli.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: cli.version, redact: cli.redact });
985
+ if (cli.usage !== false) {
986
+ try {
987
+ recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
988
+ } catch {}
989
+ }
990
+ return code;
991
+ }
992
+ function commandPath(scope, argv) {
993
+ const path = [];
994
+ let level = scope;
995
+ for (const word of argv.filter((each) => !each.startsWith("-"))) {
996
+ const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
997
+ const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
998
+ if (command === undefined)
999
+ break;
1000
+ path.push(word);
1001
+ if (!("commands" in command))
1002
+ break;
1003
+ level = scopeOf(command.commands, command.extraCommands, command.aliases);
1004
+ }
1005
+ return path.length === 0 ? undefined : path.join(" ");
926
1006
  }
927
- // ../kit/src/logs.ts
928
- var DAY_MS = 24 * 60 * 60 * 1000;
929
1007
  // ../kit/src/secrets.ts
930
1008
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
931
1009
  // ../kit/src/sessions.ts
@@ -933,7 +1011,7 @@ var {Glob } = globalThis.Bun;
933
1011
  var SESSION_FILES = new Glob("*.json");
934
1012
  var ACCOUNT_DIRS = new Glob("*/sessions");
935
1013
  // package.json
936
- var version = "0.7.2";
1014
+ var version = "0.8.0";
937
1015
 
938
1016
  // ../kit/src/shell.ts
939
1017
  var SEPARATORS = new Set([`
@@ -1524,13 +1602,12 @@ function resolvePath(base, arg, home) {
1524
1602
  return `/${parts.join("/")}`;
1525
1603
  }
1526
1604
 
1527
- // ../db/src/guard.ts
1605
+ // ../db/src/sql-tokens.ts
1528
1606
  var WORD_START = /[a-z_\P{ASCII}]/iu;
1529
1607
  var WORD_PART = /[\w$\P{ASCII}]/u;
1530
1608
  var SPACE = /\s/;
1531
1609
  var ESCAPE_PREFIX = /e/i;
1532
1610
  var DOLLAR_TAG = /^\$(?:[a-z_]\w*)?\$/i;
1533
- var LOCK_KIND = /^(?:update|share|no|key)$/;
1534
1611
  var DIGITS = /\d/;
1535
1612
  var COMMAND_ENDS = ";";
1536
1613
  var UNCLOSED = "unclosed";
@@ -1538,11 +1615,6 @@ var NUL = "\x00";
1538
1615
  var UNICODE_IDENTIFIER = 'U&"';
1539
1616
  var UNICODE_PREFIX = /u&$/i;
1540
1617
  var LINE_END = /[\r\n]/;
1541
- var PRIVILEGED_SET = new Set(["role", "session", "transaction", "global", "persist", "persist_only", "password", "default"]);
1542
- var READ_STARTS = new Set(["select", "with", "values", "table", "show", "explain", "describe", "desc"]);
1543
- var WRITING_STARTS = new Set(["replace", "load", "rename", "flush", "kill", "shutdown", "install", "uninstall", "purge", "optimize", "repair", "import", "prepare", "execute"]);
1544
- var WRITE_WORDS = new Set(["insert", "update", "delete", "merge", "truncate", "drop", "alter", "create", "grant", "revoke", "into", "call", "vacuum", "lock", "refresh", "reindex", "cluster", "do"]);
1545
- var SIDE_EFFECT_FUNCTIONS = /^(?:nextval|setval|set_config|pg_terminate_backend|pg_cancel_backend|pg_reload_conf|pg_rotate_logfile|pg_switch_wal|pg_create_restore_point|pg_advisory_lock\w*|pg_advisory_xact_lock\w*|pg_try_advisory\w*|pg_notify|lo_\w+|dblink\w*|pg_read_file|pg_read_binary_file|pg_ls_\w+|pg_stat_file|pg_sleep\w*|pg_export_snapshot|pg_backup_start|pg_backup_stop|pg_start_backup|pg_stop_backup|txid_current|pg_current_xact_id|pg_current_logfile|pg_wal_replay_\w+|\w+_to_xml\w*|pg_logical_\w+|pg_replication_\w+|pg_drop_replication_slot|pg_stat_reset\w*|pg_promote|pg_file_\w+|sleep|benchmark|get_lock|release_lock|release_all_locks|load_file|master_pos_wait|source_pos_wait|sys_exec|sys_eval)$/;
1546
1618
  function tokenize2(sql, dialect = "postgres") {
1547
1619
  const tokens = [];
1548
1620
  const isMysql = dialect === "mysql";
@@ -1640,6 +1712,23 @@ function splitStatements(tokens) {
1640
1712
  }
1641
1713
  return statements.filter((statement) => statement.length > 0);
1642
1714
  }
1715
+
1716
+ // ../db/src/guard-test.ts
1717
+ var TEST_WRITE_STARTS = new Set(["insert", "update", "delete", "replace", "merge", "truncate", "create", "alter", "drop", "rename", "with", "select", "values", "table", "comment", "refresh"]);
1718
+ var DEFINITION_STARTS = new Set(["create", "alter", "drop", "rename"]);
1719
+ var STORED_CODE = new Set(["event", "procedure", "function", "trigger", "rule", "aggregate"]);
1720
+ var DEFINITION_MODIFIERS = new Set(["or", "replace", "temporary", "temp", "unlogged", "unique", "fulltext", "spatial", "definer"]);
1721
+ var SERVER_OBJECTS = new Set(["database", "user", "role", "server", "tablespace", "extension", "system", "subscription", "publication", "logfile", "instance", "resource"]);
1722
+ var FILE_WORDS = new Set(["infile", "outfile", "dumpfile"]);
1723
+ var SEQUENCE_FUNCTIONS = new Set(["nextval", "setval"]);
1724
+
1725
+ // ../db/src/guard.ts
1726
+ var LOCK_KIND = /^(?:update|share|no|key)$/;
1727
+ var PRIVILEGED_SET = new Set(["role", "session", "transaction", "global", "persist", "persist_only", "password", "default"]);
1728
+ var READ_STARTS = new Set(["select", "with", "values", "table", "show", "explain", "describe", "desc"]);
1729
+ var WRITING_STARTS = new Set(["replace", "load", "rename", "flush", "kill", "shutdown", "install", "uninstall", "purge", "optimize", "repair", "import", "prepare", "execute"]);
1730
+ var WRITE_WORDS = new Set(["insert", "update", "delete", "merge", "truncate", "drop", "alter", "create", "grant", "revoke", "into", "call", "vacuum", "lock", "refresh", "reindex", "cluster", "do"]);
1731
+ var SIDE_EFFECT_FUNCTIONS = /^(?:nextval|setval|set_config|pg_terminate_backend|pg_cancel_backend|pg_reload_conf|pg_rotate_logfile|pg_switch_wal|pg_create_restore_point|pg_advisory_lock\w*|pg_advisory_xact_lock\w*|pg_try_advisory\w*|pg_notify|lo_\w+|dblink\w*|pg_read_file|pg_read_binary_file|pg_ls_\w+|pg_stat_file|pg_sleep\w*|pg_export_snapshot|pg_backup_start|pg_backup_stop|pg_start_backup|pg_stop_backup|txid_current|pg_current_xact_id|pg_current_logfile|pg_wal_replay_\w+|\w+_to_xml\w*|pg_logical_\w+|pg_replication_\w+|pg_drop_replication_slot|pg_stat_reset\w*|pg_promote|pg_file_\w+|sleep|benchmark|get_lock|release_lock|release_all_locks|load_file|master_pos_wait|source_pos_wait|sys_exec|sys_eval)$/;
1643
1732
  var isPunct = (token, text) => token?.kind === "punct" && token.text === text;
1644
1733
  function copyReads(statement, index) {
1645
1734
  let depth = 0;
@@ -1697,13 +1786,6 @@ function statementWrites(statement) {
1697
1786
  function writes(sql, dialect = "postgres") {
1698
1787
  return [...new Set(splitStatements(tokenize2(sql, dialect)).flatMap(statementWrites))];
1699
1788
  }
1700
- var TEST_WRITE_STARTS = new Set(["insert", "update", "delete", "replace", "merge", "truncate", "create", "alter", "drop", "rename", "with", "select", "values", "table", "comment", "refresh"]);
1701
- var DEFINITION_STARTS = new Set(["create", "alter", "drop", "rename"]);
1702
- var STORED_CODE = new Set(["event", "procedure", "function", "trigger", "rule", "aggregate"]);
1703
- var DEFINITION_MODIFIERS = new Set(["or", "replace", "temporary", "temp", "unlogged", "unique", "fulltext", "spatial", "definer"]);
1704
- var SERVER_OBJECTS = new Set(["database", "user", "role", "server", "tablespace", "extension", "system", "subscription", "publication", "logfile", "instance", "resource"]);
1705
- var FILE_WORDS = new Set(["infile", "outfile", "dumpfile"]);
1706
- var SEQUENCE_FUNCTIONS = new Set(["nextval", "setval"]);
1707
1789
 
1708
1790
  // ../db/src/clients.ts
1709
1791
  var SQL_CLIENTS = new Set(["psql", "mysql", "mariadb", "pgcli", "mycli", "sqlite3"]);
@@ -1854,57 +1936,14 @@ async function sqlViolation(command, read) {
1854
1936
  return null;
1855
1937
  }
1856
1938
 
1857
- // ../env/src/files.ts
1858
- var ENV_FILE = /^(?:\.env(?:\..+)?|.+\.env|\.envrc)$/;
1859
- var TEMPLATE = /\.(?:example|sample|template|dist|defaults)$/;
1860
- var SKIPPED = new Set(["node_modules", ".git", "vendor"]);
1861
-
1862
- // ../env/src/guard.ts
1863
- var REDIRECT = /^\d*[<>]+&?/;
1864
- var ENVRC = ".envrc";
1865
- var PROC_ENVIRON = /^\/proc\/[^/]+\/environ$/;
1866
- var ENV_NAME_IN_CODE = /(?:^|[^\w.-])(\.env(?:\.[\w.-]*\w)?|\.envrc)(?![\w-])/g;
1867
- var ENV_NAME_IN_PATTERN = /(?:^|[^\w-])\.env(?![\w-])/;
1868
- var PYTHON_ENVIRON = /\bos\.environ\b(?!\s*(?:\[|\.get\b))/;
1869
- var VARIABLE = /\$(?:(\w+)|\{(\w+)\})/;
1870
- var ASSIGNMENT2 = /^\w+=/;
1871
- var SHORT_FLAGS = /^-[a-z]+$/i;
1939
+ // ../env/src/guard-dumps.ts
1872
1940
  var OPENER = /^[({]+/;
1873
- var ENV_SAMPLES = [".env", ".env.local", ".env.production", ".envrc"];
1874
- var MAX_VARIANTS = 64;
1875
- var INTERPRETERS = new Set(["bun", "deno", "node", "python", "python3", "ruby", "perl", "php", "lua", "awk", "gawk"]);
1876
- var CODE_OPTIONS = new Set(["-e", "-c", "-p", "-E", "-pe", "-r", "--eval", "--print", "--command"]);
1877
- var GREPS = new Set(["grep", "egrep", "fgrep"]);
1878
- var GREP_VALUE_OPTIONS = new Set(["-e", "-f", "-m", "-A", "-B", "-C", "-d", "-D", "--regexp", "--file", "--max-count", "--include", "--exclude", "--exclude-dir", "--exclude-from", "--context", "--after-context", "--before-context", "--label", "--binary-files", "--directories", "--devices"]);
1879
- var RG_VALUE_OPTIONS = new Set(["-e", "-f", "-g", "-t", "-T", "-m", "-A", "-B", "-C", "-j", "-d", "-r", "-M", "-E", "--replace", "--max-columns", "--encoding", "--regexp", "--file", "--glob", "--iglob", "--type", "--type-not", "--max-count", "--context", "--after-context", "--before-context", "--threads", "--max-depth", "--max-filesize"]);
1880
- var PATTERN_OPTIONS = new Set(["-e", "-f", "--regexp", "--file"]);
1881
- var GREP_NAMES_ONLY = new Set("lLcq");
1882
- var RG_NAMES_ONLY = new Set("lcq");
1883
- var NAMES_ONLY_LONG = new Set(["--files-with-matches", "--files-without-match", "--count", "--count-matches", "--quiet", "--silent"]);
1884
- var FIND_ACTIONS = new Set(["-exec", "-execdir", "-ok", "-okdir", "-delete", "-fprint", "-fprint0", "-fprintf", "-fls", "-files0-from"]);
1885
- var CAN_REACH_FILES = /read|write|open|exec|spawn|system|popen|import|require|eval|load|fetch|glob|stream|source|getline|constructor|file(?!s\b)|\bcat\b|\b(?:Bun|Deno|fs|os|io|sh|bash|process|globalThis|window|Function|qx)\b|\$\s*[`({]|`/i;
1886
- var HIDDEN_FLAGS = /^(?:-u{2,}|--hidden|-\.)$/i;
1887
- var REGEX_SPECIALS = /[.+^${}()|\\[\]]/g;
1888
- var NEGATED_CLASS = /^!/;
1889
- var GLOB_CHAR = /[*?[]/;
1890
- var HAS_R = /r/i;
1891
1941
  var DUMP_FLAGS = /^-[a-z]*[px]/;
1892
- var DECLARERS = new Set(["export", "declare", "local", "readonly", "typeset"]);
1893
- var WHOLE_TREE_OPERAND = /^(?:(?:\.\.?\/?)+|~\/?|\$HOME\/?|\/)$/;
1894
1942
  var GIT_PATCHES = new Set(["diff", "log", "show", "whatchanged", "format-patch", "grep"]);
1895
1943
  var GIT_NO_PATCH = new Set(["--stat", "--numstat", "--shortstat", "--name-only", "--name-status", "--summary", "-s", "--no-patch", "--check", "--quiet"]);
1896
1944
  var GIT_VALUE_OPTIONS = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path"]);
1897
1945
  var GIT_PATCH_FLAGS = new Set(["-p", "-u", "--patch", "-c", "--cc", "--patch-with-stat", "--patch-with-raw"]);
1898
1946
  var GIT_EXCLUDE = /^:(?:!|\^|\(exclude\))/;
1899
- var EXCLUDES_ENV = /^(?:--exclude(?:-dir)?=.*env|(?:--glob=|--iglob=|-g)?!.*env)/;
1900
- var EXCLUDE_OPTIONS = new Set(["--exclude", "--exclude-dir", "-g", "--glob", "--iglob"]);
1901
- var ENV_DUMP = /(?:console\.\w+|JSON\.stringify|Object\.(?:entries|keys|values)|print)\(\s*process\.env\s*[,)]/;
1902
- var HARMLESS = new Set(["ev", "redact", "ls", "stat", "test", "[", "[[", "touch"]);
1903
- var GIT_HARMLESS = new Set(["check-ignore", "ls-files", "status"]);
1904
- var XARGS_SAFE = new Set(["ls", "stat", "wc", "test", "[", "touch", "echo", "printf", "basename", "dirname", "ev", "redact", ""]);
1905
- var PARALLEL_VALUE_OPTIONS = new Set(["-j", "--jobs", "-P", "--max-procs", "-S", "--sshlogin", "-C", "--colsep", "-n", "--max-args", "-N", "-d", "--delimiter", "-E", "-I", "--timeout", "--delay", "--joblog", "--results", "--tmpdir", "-a", "--arg-file", "--halt", "--retries", "--tag-string"]);
1906
- var IDENTIFIER = /^[A-Z_]\w*$/i;
1907
- var READ_VALUE_OPTIONS = new Set(["-a", "-d", "-i", "-n", "-N", "-p", "-t", "-u"]);
1908
1947
  var ENV_PRINTERS = new Set(["env", "printenv"]);
1909
1948
  var DOCKER = new Set(["docker", "docker-compose"]);
1910
1949
  var SHELLS2 = new Set(["sh", "bash", "zsh", "ash"]);
@@ -1913,35 +1952,101 @@ var EXEC_VALUE_OPTIONS = new Set(["-e", "--env", "--env-file", "-u", "--user", "
1913
1952
  var CONFIG_LISTS = new Set(["--services", "--volumes", "--profiles", "--images", "--networks", "--hash", "-q", "--quiet"]);
1914
1953
  var FORMAT_OPTIONS = new Set(["-f", "--format"]);
1915
1954
  var WHOLE_FORMAT = /Env|\{\{\s*json\s+\.\s*\}\}|^json$/;
1916
- var USE_EV = '.env files hold secrets that must never reach the transcript, so they are not read, edited or printed directly. Use `ev` instead: `ev list`, `ev get KEY` (masked), `ev grep <regex>` for the keys matching it, `ev show <rev>:<file>` for one at a git revision, `printf %s "$value" | ev set KEY [file]` (`--empty` for an empty value), `ev unset KEY`, `ev cp KEY --from .env --to .env.local`, `ev mv KEY --from .env --to .env.local`, `ev diff a b`, `ev missing`; and pipe output that may carry a secret through `redact`, as `docker compose exec <svc> printenv | redact` or `docker compose config | redact`. If `ev` is missing: `bun install -g @kaynooo/cli-env`.';
1917
- var USE_EV_SEARCH = "To search them, `ev grep <regex>` prints the matching keys, masked. `grep -l`, `-L` and `-c` (file names and counts) are allowed, and a tree-wide search can run as `rg <regex>`, which skips gitignored files, or `grep -r --exclude='.env*' <regex> .`.";
1918
- function isSearchCommand(piece) {
1919
- const { program } = parseCommand(piece.command);
1920
- return GREPS.has(program) || program === "rg" || program === "ag";
1921
- }
1922
- function isEnvFile(path) {
1923
- const name = path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf(":")) + 1);
1924
- return (ENV_FILE.test(name) || name === ".env*" || name === ENVRC) && !TEMPLATE.test(name);
1925
- }
1926
- function globRegex(glob) {
1927
- let source = "";
1928
- for (let i = 0;i < glob.length; i++) {
1929
- const char = glob[i] ?? "";
1930
- const close = char === "[" ? glob.indexOf("]", i + 2) : -1;
1931
- if (char === "*") {
1932
- source += ".*";
1933
- } else if (char === "?") {
1934
- source += ".";
1935
- } else if (close === -1) {
1936
- source += char.replace(REGEX_SPECIALS, String.raw`\$&`);
1937
- } else {
1938
- source += `[${glob.slice(i + 1, close).replace(NEGATED_CLASS, "^")}]`;
1939
- i = close;
1940
- }
1955
+ function firstOperand(words, valueOptions) {
1956
+ for (let i = 0;i < words.length; i++) {
1957
+ const word = words[i] ?? "";
1958
+ if (valueOptions.has(word))
1959
+ i++;
1960
+ else if (!word.startsWith("-"))
1961
+ return i;
1941
1962
  }
1942
- return new RegExp(`^${source}$`);
1963
+ return words.length;
1943
1964
  }
1944
- function globReachesEnv(path) {
1965
+ function printsEnv([program = "", ...args]) {
1966
+ if (SHELLS2.has(program) && args[0] === "-c")
1967
+ return splitCommand(args[1] ?? "").some((piece) => ENV_PRINTERS.has(tokenize(piece.command)[0] ?? ""));
1968
+ return ENV_PRINTERS.has(program);
1969
+ }
1970
+ function dumpsContainerEnv(program, args) {
1971
+ if (!DOCKER.has(program))
1972
+ return false;
1973
+ const afterOptions = (words) => words.slice(firstOperand(words, DOCKER_VALUE_OPTIONS));
1974
+ let rest = afterOptions(args);
1975
+ const isCompose = program === "docker-compose" || rest[0] === "compose";
1976
+ if (program === "docker" && isCompose)
1977
+ rest = afterOptions(rest.slice(1));
1978
+ const [subcommand = "", ...after] = rest;
1979
+ if (subcommand === "exec")
1980
+ return printsEnv(after.slice(firstOperand(after, EXEC_VALUE_OPTIONS) + 1));
1981
+ if (isCompose)
1982
+ return subcommand === "config" && !after.some((word) => CONFIG_LISTS.has(word));
1983
+ if (subcommand !== "inspect" && (subcommand !== "container" || after[0] !== "inspect"))
1984
+ return false;
1985
+ const format = after.find((_, i) => FORMAT_OPTIONS.has(after[i - 1] ?? "")) ?? after.find((word) => word.startsWith("--format="))?.slice("--format=".length);
1986
+ return format === undefined || WHOLE_FORMAT.test(format);
1987
+ }
1988
+ function dumpsEnvironment(program, args, tokens) {
1989
+ const isBare = args.every((arg) => arg.startsWith("-"));
1990
+ if (program === "printenv" || program === "export")
1991
+ return isBare;
1992
+ if (program === "declare" || program === "typeset")
1993
+ return isBare && args.some((arg) => DUMP_FLAGS.test(arg));
1994
+ if (program === "set")
1995
+ return args.length === 0;
1996
+ return program === "" && tokens.some((token) => token.replace(OPENER, "") === "env");
1997
+ }
1998
+ function printsTrackedEnv(program, args) {
1999
+ if (program !== "git")
2000
+ return false;
2001
+ const at = args.findIndex((arg, i) => !arg.startsWith("-") && !GIT_VALUE_OPTIONS.has(args[i - 1] ?? ""));
2002
+ const name = args[at] ?? "";
2003
+ const rest = args.slice(at + 1);
2004
+ if (!GIT_PATCHES.has(name) || rest.some((arg) => GIT_EXCLUDE.test(arg)))
2005
+ return false;
2006
+ if (name === "grep")
2007
+ return true;
2008
+ if (name === "log" || name === "whatchanged")
2009
+ return rest.some((arg) => GIT_PATCH_FLAGS.has(arg));
2010
+ return !rest.some((arg) => GIT_NO_PATCH.has(arg));
2011
+ }
2012
+
2013
+ // ../env/src/files.ts
2014
+ var ENV_FILE = /^(?:\.env(?:\..+)?|.+\.env|\.envrc)$/;
2015
+ var TEMPLATE = /\.(?:example|sample|template|dist|defaults)$/;
2016
+ var SKIPPED = new Set(["node_modules", ".git", "vendor"]);
2017
+
2018
+ // ../env/src/guard-paths.ts
2019
+ var REDIRECT = /^\d*[<>]+&?/;
2020
+ var ENVRC = ".envrc";
2021
+ var PROC_ENVIRON = /^\/proc\/[^/]+\/environ$/;
2022
+ var ENV_SAMPLES = [".env", ".env.local", ".env.production", ".envrc"];
2023
+ var REGEX_SPECIALS = /[.+^${}()|\\[\]]/g;
2024
+ var NEGATED_CLASS = /^!/;
2025
+ var GLOB_CHAR = /[*?[]/;
2026
+ var EXCLUDE_OPTIONS = new Set(["--exclude", "--exclude-dir", "-g", "--glob", "--iglob"]);
2027
+ function isEnvFile(path) {
2028
+ const name = path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf(":")) + 1);
2029
+ return (ENV_FILE.test(name) || name === ".env*" || name === ENVRC) && !TEMPLATE.test(name);
2030
+ }
2031
+ function globRegex(glob) {
2032
+ let source = "";
2033
+ for (let i = 0;i < glob.length; i++) {
2034
+ const char = glob[i] ?? "";
2035
+ const close = char === "[" ? glob.indexOf("]", i + 2) : -1;
2036
+ if (char === "*") {
2037
+ source += ".*";
2038
+ } else if (char === "?") {
2039
+ source += ".";
2040
+ } else if (close === -1) {
2041
+ source += char.replace(REGEX_SPECIALS, String.raw`\$&`);
2042
+ } else {
2043
+ source += `[${glob.slice(i + 1, close).replace(NEGATED_CLASS, "^")}]`;
2044
+ i = close;
2045
+ }
2046
+ }
2047
+ return new RegExp(`^${source}$`);
2048
+ }
2049
+ function globReachesEnv(path) {
1945
2050
  const name = path.slice(path.lastIndexOf("/") + 1);
1946
2051
  if (!name.startsWith(".") || !GLOB_CHAR.test(name))
1947
2052
  return false;
@@ -1961,43 +2066,25 @@ function namesEnvFile(word, previous, isGlob) {
1961
2066
  const path = targetOf(word);
1962
2067
  return isEnvFile(path) || PROC_ENVIRON.test(path) || isGlob && globReachesEnv(path);
1963
2068
  }
1964
- function variablesOf(command) {
1965
- const variables = new Map;
1966
- const add = (assignment) => {
1967
- const at = assignment.indexOf("=");
1968
- const name = assignment.slice(0, at);
1969
- variables.set(name, [...variables.get(name) ?? [], assignment.slice(at + 1)]);
1970
- };
1971
- for (const piece of splitCommand(command)) {
1972
- const { program, args, assignments } = parseCommand(piece.command);
1973
- const tokens = tokenize(piece.command);
1974
- const declared = DECLARERS.has(program) ? args.filter((arg) => ASSIGNMENT2.test(arg)) : [];
1975
- for (const assignment of [...assignments, ...declared])
1976
- add(assignment);
1977
- if (tokens[0] === "for" && tokens[2] === "in" && tokens[1] !== undefined)
1978
- variables.set(tokens[1], [...variables.get(tokens[1]) ?? [], ...tokens.slice(3)]);
1979
- }
1980
- return variables;
1981
- }
1982
- function variantsOf(word, variables) {
1983
- let found = [word.text];
1984
- for (let round = 0;round < 4 && found.some((each) => VARIABLE.test(each)); round++) {
1985
- found = found.flatMap((each) => {
1986
- const match = VARIABLE.exec(each);
1987
- const values = variables.get(match?.[1] ?? match?.[2] ?? "");
1988
- if (match === null || values === undefined)
1989
- return [each.replace(VARIABLE, "")];
1990
- return values.map((value) => each.slice(0, match.index) + value + each.slice(match.index + match[0].length));
1991
- }).slice(0, MAX_VARIANTS);
1992
- }
1993
- return found.flatMap((each) => word.hasBrace ? braceExpand(each) : [each]);
1994
- }
1995
- function codeReadsEnvFile(code) {
1996
- return [...code.matchAll(ENV_NAME_IN_CODE)].some((match) => isEnvFile(match[1] ?? "")) && CAN_REACH_FILES.test(code);
1997
- }
1998
- function codeReadsEnv(found, heredocs) {
1999
- const sources = [...found.filter((word, i) => word.isProse || CODE_OPTIONS.has(found[i - 1]?.text ?? "")).map((word) => word.text), ...heredocs];
2000
- return sources.some((code) => PYTHON_ENVIRON.test(code) || codeReadsEnvFile(code));
2069
+
2070
+ // ../env/src/guard-search.ts
2071
+ var ENV_NAME_IN_PATTERN = /(?:^|[^\w-])\.env(?![\w-])/;
2072
+ var SHORT_FLAGS = /^-[a-z]+$/i;
2073
+ var GREPS = new Set(["grep", "egrep", "fgrep"]);
2074
+ var GREP_VALUE_OPTIONS = new Set(["-e", "-f", "-m", "-A", "-B", "-C", "-d", "-D", "--regexp", "--file", "--max-count", "--include", "--exclude", "--exclude-dir", "--exclude-from", "--context", "--after-context", "--before-context", "--label", "--binary-files", "--directories", "--devices"]);
2075
+ var RG_VALUE_OPTIONS = new Set(["-e", "-f", "-g", "-t", "-T", "-m", "-A", "-B", "-C", "-j", "-d", "-r", "-M", "-E", "--replace", "--max-columns", "--encoding", "--regexp", "--file", "--glob", "--iglob", "--type", "--type-not", "--max-count", "--context", "--after-context", "--before-context", "--threads", "--max-depth", "--max-filesize"]);
2076
+ var PATTERN_OPTIONS = new Set(["-e", "-f", "--regexp", "--file"]);
2077
+ var GREP_NAMES_ONLY = new Set("lLcq");
2078
+ var RG_NAMES_ONLY = new Set("lcq");
2079
+ var NAMES_ONLY_LONG = new Set(["--files-with-matches", "--files-without-match", "--count", "--count-matches", "--quiet", "--silent"]);
2080
+ var FIND_ACTIONS = new Set(["-exec", "-execdir", "-ok", "-okdir", "-delete", "-fprint", "-fprint0", "-fprintf", "-fls", "-files0-from"]);
2081
+ var HIDDEN_FLAGS = /^(?:-u{2,}|--hidden|-\.)$/i;
2082
+ var HAS_R = /r/i;
2083
+ var WHOLE_TREE_OPERAND = /^(?:(?:\.\.?\/?)+|~\/?|\$HOME\/?|\/)$/;
2084
+ var EXCLUDES_ENV = /^(?:--exclude(?:-dir)?=.*env|(?:--glob=|--iglob=|-g)?!.*env)/;
2085
+ function isSearchCommand(piece) {
2086
+ const { program } = parseCommand(piece.command);
2087
+ return GREPS.has(program) || program === "rg" || program === "ag";
2001
2088
  }
2002
2089
  function printsNamesOnly(program, args) {
2003
2090
  const isGrep = GREPS.has(program);
@@ -2065,58 +2152,6 @@ function patternIndex(args, valueOptions) {
2065
2152
  }
2066
2153
  return;
2067
2154
  }
2068
- function firstOperand(words, valueOptions) {
2069
- for (let i = 0;i < words.length; i++) {
2070
- const word = words[i] ?? "";
2071
- if (valueOptions.has(word))
2072
- i++;
2073
- else if (!word.startsWith("-"))
2074
- return i;
2075
- }
2076
- return words.length;
2077
- }
2078
- function printsEnv([program = "", ...args]) {
2079
- if (SHELLS2.has(program) && args[0] === "-c")
2080
- return splitCommand(args[1] ?? "").some((piece) => ENV_PRINTERS.has(tokenize(piece.command)[0] ?? ""));
2081
- return ENV_PRINTERS.has(program);
2082
- }
2083
- function dumpsContainerEnv(program, args) {
2084
- if (!DOCKER.has(program))
2085
- return false;
2086
- const afterOptions = (words) => words.slice(firstOperand(words, DOCKER_VALUE_OPTIONS));
2087
- let rest = afterOptions(args);
2088
- const isCompose = program === "docker-compose" || rest[0] === "compose";
2089
- if (program === "docker" && isCompose)
2090
- rest = afterOptions(rest.slice(1));
2091
- const [subcommand = "", ...after] = rest;
2092
- if (subcommand === "exec")
2093
- return printsEnv(after.slice(firstOperand(after, EXEC_VALUE_OPTIONS) + 1));
2094
- if (isCompose)
2095
- return subcommand === "config" && !after.some((word) => CONFIG_LISTS.has(word));
2096
- if (subcommand !== "inspect" && (subcommand !== "container" || after[0] !== "inspect"))
2097
- return false;
2098
- const format = after.find((_, i) => FORMAT_OPTIONS.has(after[i - 1] ?? "")) ?? after.find((word) => word.startsWith("--format="))?.slice("--format=".length);
2099
- return format === undefined || WHOLE_FORMAT.test(format);
2100
- }
2101
- function readsEnv(piece, variables) {
2102
- const { program, args } = parseCommand(piece.command);
2103
- if (program === "" || HARMLESS.has(program) || program === "git" && GIT_HARMLESS.has(args[0] ?? ""))
2104
- return false;
2105
- if (INTERPRETERS.has(program) && codeReadsEnv(words(piece.command), piece.heredocs))
2106
- return true;
2107
- if (printsNamesOnly(program, args) || listsFiles(program, args))
2108
- return false;
2109
- return namesEnv(piece, variables);
2110
- }
2111
- function namesEnv(piece, variables) {
2112
- const { program, args } = parseCommand(piece.command);
2113
- const found = words(piece.command);
2114
- const isExclusion = (word) => program === "git" && GIT_EXCLUDE.test(word.text);
2115
- const isSearch = GREPS.has(program) || program === "rg" || program === "ag";
2116
- const patternAt = isSearch ? patternIndex(args, GREPS.has(program) ? GREP_VALUE_OPTIONS : RG_VALUE_OPTIONS) : undefined;
2117
- const pattern = patternAt === undefined ? undefined : found.length - args.length + patternAt;
2118
- return found.some((word, index) => index !== pattern && !word.isProse && !isExclusion(word) && variantsOf(word, variables).some((variant) => namesEnvFile(variant, found[index - 1]?.text, word.hasGlob)));
2119
- }
2120
2155
  function operandsOf(args, valueOptions) {
2121
2156
  const operands = [];
2122
2157
  let hasPattern = false;
@@ -2143,30 +2178,6 @@ function searchesEnv(program, args) {
2143
2178
  const operands = operandsOf(args, isGrep ? GREP_VALUE_OPTIONS : RG_VALUE_OPTIONS);
2144
2179
  return operands.length === 0 || operands.some((operand) => WHOLE_TREE_OPERAND.test(operand));
2145
2180
  }
2146
- function dumpsEnvironment(program, args, tokens) {
2147
- const isBare = args.every((arg) => arg.startsWith("-"));
2148
- if (program === "printenv" || program === "export")
2149
- return isBare;
2150
- if (program === "declare" || program === "typeset")
2151
- return isBare && args.some((arg) => DUMP_FLAGS.test(arg));
2152
- if (program === "set")
2153
- return args.length === 0;
2154
- return program === "" && tokens.some((token) => token.replace(OPENER, "") === "env");
2155
- }
2156
- function printsTrackedEnv(program, args) {
2157
- if (program !== "git")
2158
- return false;
2159
- const at = args.findIndex((arg, i) => !arg.startsWith("-") && !GIT_VALUE_OPTIONS.has(args[i - 1] ?? ""));
2160
- const name = args[at] ?? "";
2161
- const rest = args.slice(at + 1);
2162
- if (!GIT_PATCHES.has(name) || rest.some((arg) => GIT_EXCLUDE.test(arg)))
2163
- return false;
2164
- if (name === "grep")
2165
- return true;
2166
- if (name === "log" || name === "whatchanged")
2167
- return rest.some((arg) => GIT_PATCH_FLAGS.has(arg));
2168
- return !rest.some((arg) => GIT_NO_PATCH.has(arg));
2169
- }
2170
2181
  function searchesEnvNames(piece) {
2171
2182
  const { program, args } = parseCommand(piece.command);
2172
2183
  if (!GREPS.has(program) && program !== "rg")
@@ -2174,6 +2185,82 @@ function searchesEnvNames(piece) {
2174
2185
  const at = patternIndex(args, GREPS.has(program) ? GREP_VALUE_OPTIONS : RG_VALUE_OPTIONS);
2175
2186
  return at !== undefined && ENV_NAME_IN_PATTERN.test((args[at] ?? "").replaceAll("\\", ""));
2176
2187
  }
2188
+
2189
+ // ../env/src/guard-names.ts
2190
+ var ENV_NAME_IN_CODE = /(?:^|[^\w.-])(\.env(?:\.[\w.-]*\w)?|\.envrc)(?![\w-])/g;
2191
+ var PYTHON_ENVIRON = /\bos\.environ\b(?!\s*(?:\[|\.get\b))/;
2192
+ var VARIABLE = /\$(?:(\w+)|\{(\w+)\})/;
2193
+ var ASSIGNMENT2 = /^\w+=/;
2194
+ var MAX_VARIANTS = 64;
2195
+ var INTERPRETERS = new Set(["bun", "deno", "node", "python", "python3", "ruby", "perl", "php", "lua", "awk", "gawk"]);
2196
+ var CODE_OPTIONS = new Set(["-e", "-c", "-p", "-E", "-pe", "-r", "--eval", "--print", "--command"]);
2197
+ var CAN_REACH_FILES = /read|write|open|exec|spawn|system|popen|import|require|eval|load|fetch|glob|stream|source|getline|constructor|file(?!s\b)|\bcat\b|\b(?:Bun|Deno|fs|os|io|sh|bash|process|globalThis|window|Function|qx)\b|\$\s*[`({]|`/i;
2198
+ var DECLARERS = new Set(["export", "declare", "local", "readonly", "typeset"]);
2199
+ var HARMLESS = new Set(["ev", "redact", "ls", "stat", "test", "[", "[[", "touch"]);
2200
+ var GIT_HARMLESS = new Set(["check-ignore", "ls-files", "status"]);
2201
+ function variablesOf(command) {
2202
+ const variables = new Map;
2203
+ const add = (assignment) => {
2204
+ const at = assignment.indexOf("=");
2205
+ const name = assignment.slice(0, at);
2206
+ variables.set(name, [...variables.get(name) ?? [], assignment.slice(at + 1)]);
2207
+ };
2208
+ for (const piece of splitCommand(command)) {
2209
+ const { program, args, assignments } = parseCommand(piece.command);
2210
+ const tokens = tokenize(piece.command);
2211
+ const declared = DECLARERS.has(program) ? args.filter((arg) => ASSIGNMENT2.test(arg)) : [];
2212
+ for (const assignment of [...assignments, ...declared])
2213
+ add(assignment);
2214
+ if (tokens[0] === "for" && tokens[2] === "in" && tokens[1] !== undefined)
2215
+ variables.set(tokens[1], [...variables.get(tokens[1]) ?? [], ...tokens.slice(3)]);
2216
+ }
2217
+ return variables;
2218
+ }
2219
+ function variantsOf(word, variables) {
2220
+ let found = [word.text];
2221
+ for (let round = 0;round < 4 && found.some((each) => VARIABLE.test(each)); round++) {
2222
+ found = found.flatMap((each) => {
2223
+ const match = VARIABLE.exec(each);
2224
+ const values = variables.get(match?.[1] ?? match?.[2] ?? "");
2225
+ if (match === null || values === undefined)
2226
+ return [each.replace(VARIABLE, "")];
2227
+ return values.map((value) => each.slice(0, match.index) + value + each.slice(match.index + match[0].length));
2228
+ }).slice(0, MAX_VARIANTS);
2229
+ }
2230
+ return found.flatMap((each) => word.hasBrace ? braceExpand(each) : [each]);
2231
+ }
2232
+ function codeReadsEnvFile(code) {
2233
+ return [...code.matchAll(ENV_NAME_IN_CODE)].some((match) => isEnvFile(match[1] ?? "")) && CAN_REACH_FILES.test(code);
2234
+ }
2235
+ function codeReadsEnv(found, heredocs) {
2236
+ const sources = [...found.filter((word, i) => word.isProse || CODE_OPTIONS.has(found[i - 1]?.text ?? "")).map((word) => word.text), ...heredocs];
2237
+ return sources.some((code) => PYTHON_ENVIRON.test(code) || codeReadsEnvFile(code));
2238
+ }
2239
+ function readsEnv(piece, variables) {
2240
+ const { program, args } = parseCommand(piece.command);
2241
+ if (program === "" || HARMLESS.has(program) || program === "git" && GIT_HARMLESS.has(args[0] ?? ""))
2242
+ return false;
2243
+ if (INTERPRETERS.has(program) && codeReadsEnv(words(piece.command), piece.heredocs))
2244
+ return true;
2245
+ if (printsNamesOnly(program, args) || listsFiles(program, args))
2246
+ return false;
2247
+ return namesEnv(piece, variables);
2248
+ }
2249
+ function namesEnv(piece, variables) {
2250
+ const { program, args } = parseCommand(piece.command);
2251
+ const found = words(piece.command);
2252
+ const isExclusion = (word) => program === "git" && GIT_EXCLUDE.test(word.text);
2253
+ const isSearch = GREPS.has(program) || program === "rg" || program === "ag";
2254
+ const patternAt = isSearch ? patternIndex(args, GREPS.has(program) ? GREP_VALUE_OPTIONS : RG_VALUE_OPTIONS) : undefined;
2255
+ const pattern = patternAt === undefined ? undefined : found.length - args.length + patternAt;
2256
+ return found.some((word, index) => index !== pattern && !word.isProse && !isExclusion(word) && variantsOf(word, variables).some((variant) => namesEnvFile(variant, found[index - 1]?.text, word.hasGlob)));
2257
+ }
2258
+
2259
+ // ../env/src/guard-pipes.ts
2260
+ var XARGS_SAFE = new Set(["ls", "stat", "wc", "test", "[", "touch", "echo", "printf", "basename", "dirname", "ev", "redact", ""]);
2261
+ var PARALLEL_VALUE_OPTIONS = new Set(["-j", "--jobs", "-P", "--max-procs", "-S", "--sshlogin", "-C", "--colsep", "-n", "--max-args", "-N", "-d", "--delimiter", "-E", "-I", "--timeout", "--delay", "--joblog", "--results", "--tmpdir", "-a", "--arg-file", "--halt", "--retries", "--tag-string"]);
2262
+ var IDENTIFIER = /^[A-Z_]\w*$/i;
2263
+ var READ_VALUE_OPTIONS = new Set(["-a", "-d", "-i", "-n", "-N", "-p", "-t", "-u"]);
2177
2264
  function listsEnvUpstream(pieces, index, variables) {
2178
2265
  for (let at = index - 1;at >= 0 && pieces[at]?.separator.startsWith("|"); at--) {
2179
2266
  if (namesEnv(pieces[at], variables) || searchesEnvNames(pieces[at]))
@@ -2214,6 +2301,11 @@ function loopReadsListedEnv(pieces, index, variables) {
2214
2301
  }
2215
2302
  return false;
2216
2303
  }
2304
+
2305
+ // ../env/src/guard.ts
2306
+ var ENV_DUMP = /(?:console\.\w+|JSON\.stringify|Object\.(?:entries|keys|values)|print)\(\s*process\.env\s*[,)]/;
2307
+ var USE_EV = '.env files hold secrets that must never reach the transcript, so they are not read, edited or printed directly. Use `ev` instead: `ev list`, `ev get KEY` (masked), `ev grep <regex>` for the keys matching it, `ev show <rev>:<file>` for one at a git revision, `printf %s "$value" | ev set KEY [file]` (`--empty` for an empty value), `ev unset KEY`, `ev cp KEY --from .env --to .env.local`, `ev mv KEY --from .env --to .env.local`, `ev diff a b`, `ev missing`; and pipe output that may carry a secret through `redact`, as `docker compose exec <svc> printenv | redact` or `docker compose config | redact`. If `ev` is missing: `bun install -g @kaynooo/cli-env`.';
2308
+ var USE_EV_SEARCH = "To search them, `ev grep <regex>` prints the matching keys, masked. `grep -l`, `-L` and `-c` (file names and counts) are allowed, and a tree-wide search can run as `rg <regex>`, which skips gitignored files, or `grep -r --exclude='.env*' <regex> .`.";
2217
2309
  function touchingPieces(command, options = {}) {
2218
2310
  const pieces = splitCommand(command);
2219
2311
  if (ENV_DUMP.test(command) || substitutions(command).some((each) => touchesEnv(each, options)))
@@ -3476,6 +3568,19 @@ async function hook(event, input, machine) {
3476
3568
  return event === "user-prompt-submit" ? userPromptSubmit(input, machine) : sessionStart(machine);
3477
3569
  }
3478
3570
 
3571
+ // src/rules.ts
3572
+ var LISTED = [
3573
+ { name: "remote", refuses: "ssh, scp, rsync and deploys to a remote machine", route: "hand the command to the user" },
3574
+ { name: "git", refuses: "stash, whole-tree add and commit, push without being asked, tags", route: "stage by path with `gc`, push only when asked" },
3575
+ { name: "commit", refuses: "a commit message breaking the format, an unreadable one, trailers", route: "`gc <title> -m <line> -- <path>...`" },
3576
+ { name: "sql", refuses: "SQL writes and DDL, a file the client cannot read", route: '`db "<sql>"`, writes on a `*_test` database or handed over' },
3577
+ { name: "env", refuses: "reading or printing an env file, a diff of a tracked one", route: "`ev`, and `rg` for a tree-wide search" },
3578
+ { name: "edit", refuses: "sed -i and replace scripts", route: "`sub` (only while `sub` is installed)" },
3579
+ { name: "package-manager", refuses: "a manager other than the repo's lockfile pins", route: "the pinned manager, rewritten by `guard check`, named by `guard hook`" },
3580
+ { name: "pkg", refuses: "an install `pkg check` refuses or cannot check", route: "`pkg <name>` before adding it", runs: "hook" }
3581
+ ];
3582
+ var RULES2 = LISTED.map((rule) => ({ runs: "check and hook", ...rule }));
3583
+
3479
3584
  // src/cli.ts
3480
3585
  var checkUsage = `guard check [options] [<command> | -]
3481
3586
 
@@ -3528,8 +3633,8 @@ ${checkUsage}`);
3528
3633
  const given = positionals[0] ?? "-";
3529
3634
  const command = given === "-" ? await readInput("-", { noStdin: "give the command, or pipe it on stdin" }) : given;
3530
3635
  const context = {
3531
- cwd: values.cwd ?? process7.cwd(),
3532
- home: homedir(),
3636
+ cwd: values.cwd ?? process10.cwd(),
3637
+ home: homedir2(),
3533
3638
  isPushAsked: values["push-asked"] === true,
3534
3639
  canRewrite: true,
3535
3640
  canWrap: values["no-wrap"] !== true && Bun.which("out") !== null,
@@ -3560,9 +3665,28 @@ ${pathUsage}`);
3560
3665
  report(violations);
3561
3666
  return violations.length > 0 ? 1 : 0;
3562
3667
  }
3668
+ var rulesUsage = `guard rules [--json]
3669
+
3670
+ Lists every rule \`guard check\` and \`guard hook\` apply: its name as a violation carries it, what it refuses, the route its refusal points at and where it runs.
3671
+
3672
+ Exits 0 once it listed them.`;
3673
+ var rulesOptions = {
3674
+ json: jsonOption("[{name, refuses, route, runs}]")
3675
+ };
3676
+ function rules(args) {
3677
+ const parsed = parse(args, rulesUsage, rulesOptions);
3678
+ if (parsed.values.json === true) {
3679
+ console.log(JSON.stringify(RULES2));
3680
+ return 0;
3681
+ }
3682
+ for (const rule of RULES2)
3683
+ console.log(`${rule.name.padEnd(16)} ${rule.refuses}
3684
+ ${" ".repeat(16)} -> ${rule.route}${rule.runs === "hook" ? " (hook only)" : ""}`);
3685
+ return 0;
3686
+ }
3563
3687
  function machine() {
3564
- const home = homedir();
3565
- const stateDir = `${process7.env.XDG_STATE_HOME ?? `${home}/.local/state`}/guard`;
3688
+ const home = homedir2();
3689
+ const stateDir = `${stateHome()}/guard`;
3566
3690
  return {
3567
3691
  home,
3568
3692
  stateDir,
@@ -3571,14 +3695,14 @@ function machine() {
3571
3695
  read: readText,
3572
3696
  exists: existsSync,
3573
3697
  write: (path, text) => {
3574
- mkdirSync(dirname(path), { recursive: true });
3698
+ mkdirSync2(dirname2(path), { recursive: true });
3575
3699
  writeFileSync(path, text);
3576
3700
  },
3577
3701
  remove: (path) => rmSync(path, { force: true }),
3578
3702
  log: (text) => {
3579
3703
  try {
3580
- mkdirSync(stateDir, { recursive: true });
3581
- appendFileSync(`${stateDir}/errors.log`, text);
3704
+ mkdirSync2(stateDir, { recursive: true });
3705
+ appendFileSync2(`${stateDir}/errors.log`, text);
3582
3706
  } catch {}
3583
3707
  }
3584
3708
  };
@@ -3595,15 +3719,17 @@ ${hookUsage}`, 1);
3595
3719
  console.log(JSON.stringify(reply));
3596
3720
  return 0;
3597
3721
  }
3598
- process7.exitCode = await runCli({
3722
+ process10.exitCode = await runCli({
3599
3723
  name: "guard",
3600
3724
  version,
3725
+ usage: false,
3601
3726
  about: "the safety rules a Claude Code Bash call is held to, each refusal naming the route",
3602
3727
  replaces: "a hook script per rule, each wording its own refusal",
3603
3728
  examples: [['guard check "git push --force"', "the rules a command breaks, with their routes"], ["guard path .env", "whether a file tool may open a path"]],
3604
3729
  commands: {
3605
3730
  check: { run: check, summary: "check a shell command, printing each broken rule with its route" },
3606
3731
  path: { run: async (args) => Promise.resolve(path(args)), summary: "check a path a file tool would open" },
3732
+ rules: { run: async (args) => Promise.resolve(rules(args)), summary: "list every rule with what it refuses and its route" },
3607
3733
  hook: { run: hookCommand, summary: "answer a Claude Code hook event, JSON in and out" }
3608
3734
  },
3609
3735
  defaultCommand: "check"
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-guard",
3
3
  "type": "module",
4
- "version": "0.7.2",
4
+ "version": "0.8.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",
@@ -40,7 +40,7 @@
40
40
  "@kaynooo/cli-edit": "0.4.0",
41
41
  "@kaynooo/cli-env": "0.8.0",
42
42
  "@kaynooo/cli-git": "0.5.1",
43
- "@kaynooo/cli-kit": "0.19.0",
43
+ "@kaynooo/cli-kit": "0.20.0",
44
44
  "@kaynooo/cli-out": "0.7.0",
45
45
  "@kaynooo/cli-pkg": "0.7.0"
46
46
  }