@kaynooo/cli-env 0.13.1 → 0.13.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/redact.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/redact.ts
5
- import process15 from "process";
5
+ import process17 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process10 from "process";
8
8
  import { parseArgs } from "util";
@@ -374,6 +374,23 @@ var STATUS_WORDS = {
374
374
  var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
375
375
 
376
376
  // ../kit/src/format.ts
377
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
378
+ function formatSeconds(total) {
379
+ let rest = Math.max(0, Math.round(total));
380
+ const amounts = UNITS.map(([unit, size]) => {
381
+ const amount = Math.floor(rest / size);
382
+ rest -= amount * size;
383
+ return `${amount}${unit}`;
384
+ });
385
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
386
+ if (first === -1)
387
+ return "0s";
388
+ const next = amounts[first + 1];
389
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
390
+ }
391
+ function formatDuration(ms) {
392
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
393
+ }
377
394
  function upTo(text, separator) {
378
395
  const end = text.indexOf(separator);
379
396
  return end === -1 ? text : text.slice(0, end);
@@ -434,24 +451,20 @@ function printJson(value) {
434
451
 
435
452
  // ../kit/src/help.ts
436
453
  import process8 from "process";
437
- var OPTIONAL = /\[[^\]]+\]/g;
454
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
438
455
  var USAGE_PREFIX = /^usage:\s*/i;
439
456
  var FULL_STOP = /\.$/;
440
457
  function usageLine(usage, colors = paint(process8.stdout)) {
441
458
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
442
459
  }
443
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
444
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
460
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
461
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
445
462
  `);
446
463
  }
447
464
  function exitRows(exits, colors = paint(process8.stdout)) {
448
465
  if (exits.length === 0)
449
466
  return [];
450
- const width = Math.max(...exits.map(([code]) => String(code).length));
451
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
452
- }
453
- function replacesRows(replaces, colors = paint(process8.stdout)) {
454
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
467
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
455
468
  }
456
469
  function wantsHelpJson(env = process8.env) {
457
470
  return env.KIT_HELP === "json";
@@ -477,29 +490,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
477
490
  return [];
478
491
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
479
492
  }
493
+ var MAX_INLINE_CHOICES = 24;
480
494
  function optionRows(options, colors = paint(process8.stdout)) {
481
495
  const rows = Object.entries(options).map(([name, option]) => {
482
496
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
483
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
497
+ const choices = option.choices?.join("|");
498
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
499
+ const named = inline ? `<${choices}>` : "<value>";
484
500
  const placeholder = option.optional === undefined ? named : `[${named}]`;
485
501
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
486
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
502
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
503
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
487
504
  });
488
505
  const width = Math.max(0, ...rows.map((row) => row.width));
489
506
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
490
507
  }
491
508
 
492
509
  // ../kit/src/text.ts
493
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
494
510
  function distance(a, b) {
495
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
496
- for (const [i, left] of [...a].entries()) {
511
+ const left = [...a];
512
+ const right = [...b];
513
+ let before = [];
514
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
515
+ for (const [i, x] of left.entries()) {
497
516
  const current = [i + 1];
498
- for (const [j, right] of [...b].entries())
499
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
517
+ for (const [j, y] of right.entries()) {
518
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
519
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
520
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
521
+ current.push(cost);
522
+ }
523
+ before = previous;
500
524
  previous = current;
501
525
  }
502
- return previous[b.length] ?? 0;
526
+ return previous[right.length] ?? 0;
503
527
  }
504
528
  function closest(name, names) {
505
529
  const started = names.find((known) => known.startsWith(name));
@@ -739,21 +763,63 @@ function nearestOption(message, options, allowNegative) {
739
763
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
740
764
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
741
765
  }
766
+ // ../kit/src/argv.ts
767
+ import { readFileSync as readFileSync3, realpathSync } from "fs";
768
+ import { resolve as resolve3 } from "path";
769
+ import process11 from "process";
770
+ function commandLine() {
771
+ try {
772
+ return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
773
+ } catch {
774
+ return;
775
+ }
776
+ }
777
+ function realPath(word) {
778
+ try {
779
+ return realpathSync(resolve3(word));
780
+ } catch {
781
+ return;
782
+ }
783
+ }
784
+ function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), script = process11.argv[1]) {
785
+ const target = script === undefined ? undefined : realPath(script) ?? script;
786
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
787
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
788
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
789
+ }
742
790
  // ../kit/src/progress.ts
743
791
  var ESC = String.fromCharCode(27);
744
792
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
745
793
  var RESET_STYLE = `${ESC}[0m`;
746
794
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
747
795
  // ../kit/src/cli.ts
748
- import { readFileSync as readFileSync3, realpathSync } from "fs";
796
+ import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
749
797
  import { dirname as dirname3, join as join5 } from "path";
798
+ import process14 from "process";
799
+
800
+ // ../kit/src/notify.ts
750
801
  import process12 from "process";
802
+ var NOTIFY_AFTER_MS = 1e4;
803
+ var CANCELLED = 130;
804
+ function base64(text) {
805
+ return Buffer.from(text).toString("base64");
806
+ }
807
+ function notification(title, body, env = process12.env) {
808
+ const id = `kit${process12.pid}`;
809
+ 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\\`];
810
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
811
+ }
812
+ function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
813
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
814
+ return;
815
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
816
+ }
751
817
 
752
818
  // ../kit/src/usage.ts
753
819
  import { appendFileSync, mkdirSync } from "fs";
754
820
  import { homedir as homedir3 } from "os";
755
821
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
756
- import process11 from "process";
822
+ import process13 from "process";
757
823
 
758
824
  // ../kit/src/logs.ts
759
825
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -767,14 +833,14 @@ var usageError;
767
833
  function noteUsageError(message) {
768
834
  usageError = message;
769
835
  }
770
- function stateHome(env = process11.env) {
836
+ function stateHome(env = process13.env) {
771
837
  const dir = env.XDG_STATE_HOME;
772
838
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
773
839
  }
774
- function usagePath(env = process11.env) {
840
+ function usagePath(env = process13.env) {
775
841
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
776
842
  }
777
- function usageRecorded(env = process11.env) {
843
+ function usageRecorded(env = process13.env) {
778
844
  const off = env.KAYNOOO_CLI_NO_USAGE;
779
845
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
780
846
  }
@@ -788,7 +854,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
788
854
  usageError = undefined;
789
855
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
790
856
  }
791
- function recordUsage(entry, env = process11.env) {
857
+ function recordUsage(entry, env = process13.env) {
792
858
  if (!usageRecorded(env))
793
859
  return;
794
860
  try {
@@ -865,7 +931,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
865
931
  header(colors, summary),
866
932
  "",
867
933
  usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
868
- ...replacesRows(replaces, colors),
869
934
  "",
870
935
  ...await commandRows(commands, colors),
871
936
  ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
@@ -879,8 +944,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
879
944
  `);
880
945
  }
881
946
  function printError(prefix, message, hint, cause) {
882
- const colors = paint(process12.stderr);
883
- const styled = takesControlCodes(process12.stderr);
947
+ const colors = paint(process14.stderr);
948
+ const styled = takesControlCodes(process14.stderr);
884
949
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
885
950
  const under = (label, text, tint) => text === undefined ? "" : `
886
951
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -923,11 +988,11 @@ async function dispatch(level, typed, { version, redact }) {
923
988
  }
924
989
  }
925
990
  if (name === undefined && level.path.length > 1) {
926
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stderr));
991
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
927
992
  return 2;
928
993
  }
929
994
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
930
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stdout));
995
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
931
996
  return 0;
932
997
  }
933
998
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -983,24 +1048,24 @@ function candidateLine(candidate) {
983
1048
  }
984
1049
  function positionalBeingTyped(before, { options, positionals }) {
985
1050
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
986
- let index = 0;
1051
+ const typed = [];
987
1052
  let at = 0;
988
1053
  while (at < before.length) {
989
1054
  const word = before[at];
990
1055
  if (word === "--") {
991
- index += before.length - at - 1;
1056
+ typed.push(...before.slice(at + 1));
992
1057
  break;
993
1058
  }
994
1059
  if (!word.startsWith("-"))
995
- index++;
1060
+ typed.push(word);
996
1061
  else if (takesValue(word))
997
1062
  at++;
998
1063
  at++;
999
1064
  }
1000
1065
  const last = positionals.at(-1);
1001
- if (index < positionals.length)
1002
- return positionals[index];
1003
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
1066
+ if (typed.length < positionals.length)
1067
+ return { name: positionals[typed.length], typed };
1068
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1004
1069
  }
1005
1070
  async function leafCandidates(run, words) {
1006
1071
  const completing = await completingOf(run);
@@ -1008,12 +1073,12 @@ async function leafCandidates(run, words) {
1008
1073
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1009
1074
  const flag = words.at(-2);
1010
1075
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1076
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1011
1077
  if (option?.type === "string") {
1012
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1078
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1013
1079
  return values === undefined ? [FILES] : values.map(candidateLine);
1014
1080
  }
1015
- const name = positionalBeingTyped(words.slice(0, -1), completing);
1016
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
1081
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1017
1082
  return values === undefined ? [FILES] : values.map(candidateLine);
1018
1083
  }
1019
1084
  async function candidates(scope, defaultCommand, words, before = []) {
@@ -1044,9 +1109,13 @@ async function printCandidates(found) {
1044
1109
  return 0;
1045
1110
  }
1046
1111
  function packageVersion(entry = Bun.main) {
1047
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
1112
+ let resolved = entry;
1113
+ try {
1114
+ resolved = realpathSync2(entry);
1115
+ } catch {}
1116
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1048
1117
  try {
1049
- const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
1118
+ const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
1050
1119
  if (typeof version === "string")
1051
1120
  return version;
1052
1121
  } catch {}
@@ -1054,14 +1123,17 @@ function packageVersion(entry = Bun.main) {
1054
1123
  return "0.0.0";
1055
1124
  }
1056
1125
  }
1057
- async function runCli(cli, argv = process12.argv.slice(2)) {
1126
+ async function runCli(cli, argv = scriptArgs()) {
1058
1127
  const version = cli.version ?? packageVersion();
1059
1128
  if (argv[0] === COMPLETE)
1060
1129
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1130
+ const started = performance.now();
1061
1131
  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 });
1132
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1133
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1062
1134
  if (cli.usage !== false) {
1063
1135
  try {
1064
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1136
+ recordUsage(usageEntry(cli.name, command, argv, code));
1065
1137
  } catch {}
1066
1138
  }
1067
1139
  return code;
@@ -1081,7 +1153,7 @@ function commandPath(scope, argv) {
1081
1153
  }
1082
1154
  return path.length === 0 ? undefined : path.join(" ");
1083
1155
  }
1084
- async function runMain({ name, version, run, redact, usage }, argv = process12.argv.slice(2)) {
1156
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1085
1157
  if (argv[0] === COMPLETE)
1086
1158
  return printCandidates(leafCandidates(run, argv.slice(1)));
1087
1159
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1089,11 +1161,13 @@ async function runMain({ name, version, run, redact, usage }, argv = process12.a
1089
1161
  return 0;
1090
1162
  }
1091
1163
  let code;
1164
+ const started = performance.now();
1092
1165
  try {
1093
1166
  code = await run(argv);
1094
1167
  } catch (error) {
1095
1168
  code = reportThrown(name, error, redact, wantsJson(argv));
1096
1169
  }
1170
+ notifyEnd(name, code, performance.now() - started);
1097
1171
  if (usage !== false) {
1098
1172
  try {
1099
1173
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1129,7 +1203,7 @@ var {Glob } = globalThis.Bun;
1129
1203
  var SESSION_FILES = new Glob("*.json");
1130
1204
  var ACCOUNT_DIRS = new Glob("*/sessions");
1131
1205
  // src/commands/redact.ts
1132
- import process14 from "process";
1206
+ import process16 from "process";
1133
1207
 
1134
1208
  // src/files.ts
1135
1209
  import { chmod, chown, readdir, realpath, rename, rm, stat, writeFile } from "fs/promises";
@@ -1191,7 +1265,8 @@ function parseDotenv(text) {
1191
1265
  let body = start.slice(1);
1192
1266
  let raw = line;
1193
1267
  let end = closingQuote(body, quote);
1194
- while (end === -1 && index + 1 < physical.length) {
1268
+ const first = index;
1269
+ while (end === -1 && index + 1 < physical.length && !ASSIGNMENT.test(physical[index + 1] ?? "")) {
1195
1270
  index++;
1196
1271
  body += `
1197
1272
  ${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
@@ -1199,6 +1274,11 @@ ${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
1199
1274
  ${physical[index] ?? ""}`;
1200
1275
  end = closingQuote(body, quote);
1201
1276
  }
1277
+ if (end === -1 && index + 1 < physical.length) {
1278
+ index = first;
1279
+ lines.push({ raw: line, key, value: unescapeDollar(start.replace(INLINE_COMMENT, "").trim()), unterminated: true });
1280
+ continue;
1281
+ }
1202
1282
  const inner = end === -1 ? body : body.slice(0, end);
1203
1283
  lines.push({ raw, key, value: quote === '"' ? unescapeDouble(inner) : unescapeDollar(inner) });
1204
1284
  }
@@ -1264,9 +1344,30 @@ var ESCAPE2 = /[.*+?^${}()|[\]\\]/g;
1264
1344
  function isPlaceholder(value) {
1265
1345
  return PLACEHOLDER.test(value) || PLAIN_VALUE.test(value);
1266
1346
  }
1347
+ var STRONG_NAME = "password|passwd|secret|api[_-]?key|access[_-]?key|private[_-]?key|account[_-]?key|shared[_-]?access[_-]?key";
1348
+ var WEAK_NAME = "token|credentials?|auth";
1349
+ var PLAIN_WORD = /^[a-z]+$/i;
1350
+ var AFTER_COLON = /:\s*$/;
1351
+ var DIGIT = /\d/;
1352
+ var KEY_VALUE_GAP = "\\s*[:=]\\s*";
1353
+ function isProse(value, before) {
1354
+ return isPlaceholder(value) || AFTER_COLON.test(before) && PLAIN_WORD.test(value);
1355
+ }
1356
+ function isWeak(value, before) {
1357
+ return isProse(value, before) || !(DIGIT.test(value) || value.length >= 16);
1358
+ }
1359
+ function keyed(names, value) {
1360
+ return new RegExp(`(?<![\\w-])["']?(?:[\\w-]{0,30}[_-])?(?:${names})(?:[_-][\\w-]{0,30})?["']?${KEY_VALUE_GAP}${value}`, "dgi");
1361
+ }
1267
1362
  var TOKEN_FORMATS = [
1268
1363
  { kind: "GitHub token", pattern: /\b(?:gh[pousr]_|github_pat_)\w{20,}/dg },
1269
- { kind: "GitLab token", pattern: /\bglpat-[\w-]{20,}/dg },
1364
+ { kind: "GitLab token", pattern: /\bgl(?:pat|rt|dt|ptt)-[\w-]{20,}/dg },
1365
+ { kind: "Hugging Face token", pattern: /\bhf_[A-Za-z]{30,}/dg },
1366
+ { kind: "webhook secret", pattern: /\bwhsec_\w{20,}/dg },
1367
+ { kind: "DigitalOcean token", pattern: /\bdop_v1_\w{20,}/dg },
1368
+ { kind: "Shopify token", pattern: /\bshp(?:at|ca|pa|ss)_\w{20,}/dg },
1369
+ { kind: "password", pattern: /\bmysql(?:dump|admin)?\s+(?:\S+\s+)*?-p([^\s"'|;&-]\S{3,})/dg },
1370
+ { kind: "password", pattern: /\bsshpass\s+(?:-[a-oq-z]\s+)*-p\s*([^\s"'|;&]{4,})/dg },
1270
1371
  { kind: "API key", pattern: /\bsk-[\w-]{20,}/dg },
1271
1372
  { kind: "Slack token", pattern: /\bx(?:ox[abprs]|app)-[\w-]{10,}/dg },
1272
1373
  { kind: "JWT", pattern: /\beyJ[\w-]+\.[\w-]+\.[\w-]+/dg },
@@ -1277,8 +1378,10 @@ var TOKEN_FORMATS = [
1277
1378
  { kind: "SendGrid key", pattern: /\bSG\.[\w-]{16,}\.[\w-]{16,}/dg },
1278
1379
  { kind: "Authorization header", pattern: /\bAuthorization["']?\s*[:=]\s*["']?(?:Bearer|Basic|Token|Digest)\s+([^\s"',;]{8,})/dgi, skip: isPlaceholder },
1279
1380
  { kind: "Bearer token", pattern: /\bBearer\s+((?=[\w.~+/=-]*\d)[\w.~+/=-]{20,})/dg },
1280
- { kind: "password", pattern: /(?<![\w-])(?:[\w-]{0,30}[_-])?(?:password|passwd|secret|api[_-]?key)(?:[_-][\w-]{0,30})?=([^\s"'&;,]{4,})/dgi, skip: isPlaceholder },
1281
- { kind: "password", pattern: /(?<![\w-])["']?(?:[\w-]{0,30}[_-])?(?:password|passwd|secret|api[_-]?key)(?:[_-][\w-]{0,30})?["']?\s*[:=]\s*(["'])((?:\\.|(?!\1)[^\\\n]){4,})\1/dgi, skip: isPlaceholder }
1381
+ { kind: "password", pattern: keyed(STRONG_NAME, `([^\\s"'&;,]{4,})`), skip: isProse },
1382
+ { kind: "password", pattern: keyed(WEAK_NAME, `([^\\s"'&;,]{4,})`), skip: isWeak },
1383
+ { kind: "password", pattern: keyed(STRONG_NAME, `(["'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1`), skip: isPlaceholder },
1384
+ { kind: "password", pattern: keyed(WEAK_NAME, `(["'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1`), skip: isWeak }
1282
1385
  ];
1283
1386
  var PEM_BEGIN = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
1284
1387
  var PEM_END = /-----END [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
@@ -1383,7 +1486,7 @@ function findSecrets(line, known) {
1383
1486
  if (start === undefined || end === undefined)
1384
1487
  continue;
1385
1488
  const value = line.slice(start, end);
1386
- if (!skip?.(value))
1489
+ if (!skip?.(value, line.slice(0, start)))
1387
1490
  found.push({ start, end, kind, mask: hint(value) });
1388
1491
  }
1389
1492
  }
@@ -1697,15 +1800,14 @@ function check(text, known) {
1697
1800
  var usage2 = `redact [--check]
1698
1801
 
1699
1802
  Copies stdin to stdout line by line with secrets masked: known token formats (GitHub, GitLab, Slack, AWS, npm, Stripe, Google and SendGrid keys, sk-, JWTs, Authorization headers, password= and secret= pairs), private key blocks, the password and the tokens of any URL and the values of secret-looking keys in this folder's .env* files.
1700
- --check prints nothing of the input and lists the file and line of each secret found, exiting 1 when there is any: \`git diff --cached | redact --check\`.
1701
-
1702
- Exits 0 when it copied the input or found no secret, 1 when --check finds one, 2 on a usage error.`;
1803
+ --check prints nothing of the input and lists the file and line of each secret found, exiting 1 when there is any: \`git diff --cached | redact --check\`.`;
1804
+ var EXITS = [[0, "it copied the input or found no secret"], [1, "--check finds one"], [2, "a usage error"]];
1703
1805
  var options = {
1704
1806
  check: { type: "boolean", description: "list where secrets are instead of masking them, exit 1 when found" },
1705
1807
  "no-env": { type: "boolean", description: "do not search for the values of the .env* files" }
1706
1808
  };
1707
1809
  async function redact(args) {
1708
- const parsed = parse(args, usage2, options, { replaces: "printing a command's secrets into a log or a transcript", examples: [["docker compose config | redact", "the resolved compose file, secrets masked"], ["git diff --cached | redact --check", "refuse a commit carrying a secret"]] });
1810
+ const parsed = parse(args, usage2, options, { exits: EXITS, replaces: "printing a command's secrets into a log or a transcript", examples: [["docker compose config | redact", "the resolved compose file, secrets masked"], ["git diff --cached | redact --check", "refuse a commit carrying a secret"]] });
1709
1811
  const known = parsed.values["no-env"] === true ? undefined : await loadKnown();
1710
1812
  if (parsed.values.check === true) {
1711
1813
  const findings = check(await readInput("-"), known);
@@ -1716,10 +1818,10 @@ async function redact(args) {
1716
1818
  const redactor = new Redactor(known);
1717
1819
  const decoder = new TextDecoder;
1718
1820
  for await (const chunk of Bun.stdin.stream())
1719
- process14.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
1720
- process14.stdout.write(redactor.push(decoder.decode()) + redactor.end());
1821
+ process16.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
1822
+ process16.stdout.write(redactor.push(decoder.decode()) + redactor.end());
1721
1823
  return 0;
1722
1824
  }
1723
1825
 
1724
1826
  // src/redact.ts
1725
- process15.exitCode = await runMain({ name: "redact", run: redact });
1827
+ process17.exitCode = await runMain({ name: "redact", run: redact });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-env",
3
3
  "type": "module",
4
- "version": "0.13.1",
4
+ "version": "0.13.3",
5
5
  "description": "ev lists and edits .env files with secrets masked, redact masks secrets in any piped output.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -37,6 +37,6 @@
37
37
  "redact": "$npm_execpath src/redact.ts"
38
38
  },
39
39
  "devDependencies": {
40
- "@kaynooo/cli-kit": "0.37.0"
40
+ "@kaynooo/cli-kit": "0.39.0"
41
41
  }
42
42
  }
@@ -1,3 +1,4 @@
1
+ import type { ExitRow } from '@kaynooo/cli-kit'
1
2
  import type { Exposure } from '../audit'
2
3
  import type { ComposeFix } from '../fix'
3
4
  import { stat } from 'node:fs/promises'
@@ -12,8 +13,9 @@ const usage = `ev audit [dir...] [--fix]
12
13
 
13
14
  Lists the .env files any account on the machine can read or git tracks, and the compose files any account can read that write a secret out (a secret-named value or a URL password) instead of reading it from a .env, never printing a value.
14
15
  Looks under each folder (the current one by default) down to 5 levels, skipping node_modules, vendor and .git, and leaves .example, .sample, .template and .dist files out. A folder it cannot read is named on stderr.
15
- With --fix, moves each secret a listed compose file writes out into the .env beside it as \${KEY}, puts it back when \`docker compose config\` resolves differently after, and shuts other accounts out of both files and of every listed .env; a key the .env already sets to another value stays put.
16
- Exits 0 when it finds none (with --fix, when none is left), 1 when it finds one, 2 on a usage error.`
16
+ With --fix, moves each secret a listed compose file writes out into the .env beside it as \${KEY}, puts it back when \`docker compose config\` resolves differently after, and shuts other accounts out of both files and of every listed .env; a key the .env already sets to another value stays put.`
17
+
18
+ const EXITS: ExitRow[] = [[0, 'it finds none (with --fix, when none is left)'], [1, 'it finds one'], [2, 'a usage error']]
17
19
 
18
20
  const options = {
19
21
  json: jsonOption('the findings and the folders it could not read'),
@@ -76,7 +78,7 @@ async function fixAll(exposed: Exposure[], json: boolean): Promise<{ fixed: Comp
76
78
  }
77
79
 
78
80
  export async function audit(args: string[]): Promise<number> {
79
- const parsed = parse(args, usage, options)
81
+ const parsed = parse(args, usage, options, { exits: EXITS })
80
82
 
81
83
  const roots = (parsed.positionals.length > 0 ? parsed.positionals : ['.']).map(dir => resolve(dir))
82
84
 
@@ -1,3 +1,4 @@
1
+ import type { ExitRow } from '@kaynooo/cli-kit'
1
2
  import process from 'node:process'
2
3
  import { fail, jsonOption, parse, printJson, role } from '@kaynooo/cli-kit'
3
4
  import { entries } from '../dotenv'
@@ -7,17 +8,17 @@ const diffUsage = `ev diff <a> <b>
7
8
 
8
9
  Names the keys set in one file and not the other, never their values.
9
10
 
10
- --json prints {a, b, onlyA, onlyB}.
11
+ --json prints {a, b, onlyA, onlyB}.`
11
12
 
12
- Exits 0 when both set the same keys, 1 when they differ, 2 on a usage error.`
13
+ const DIFF_EXITS: ExitRow[] = [[0, 'both set the same keys'], [1, 'they differ'], [2, 'a usage error']]
13
14
 
14
15
  const missingUsage = `ev missing [file]
15
16
 
16
17
  Names the keys the reference file sets that the file (.env by default) does not.
17
18
 
18
- --json prints {a, b, onlyA, onlyB} with the reference as a, so onlyA is what is missing.
19
+ --json prints {a, b, onlyA, onlyB} with the reference as a, so onlyA is what is missing.`
19
20
 
20
- Exits 0 when none is missing, 1 when some are, 2 on a usage error.`
21
+ const MISSING_EXITS: ExitRow[] = [[0, 'none is missing'], [1, 'some are'], [2, 'a usage error']]
21
22
 
22
23
  const jsonFlag = { json: jsonOption() } as const
23
24
 
@@ -26,7 +27,7 @@ async function keys(path: string): Promise<Set<string>> {
26
27
  }
27
28
 
28
29
  export async function diff(args: string[]): Promise<number> {
29
- const parsed = parse(args, diffUsage, jsonFlag)
30
+ const parsed = parse(args, diffUsage, jsonFlag, { exits: DIFF_EXITS })
30
31
 
31
32
  const [a, b] = parsed.positionals
32
33
 
@@ -57,7 +58,7 @@ export async function diff(args: string[]): Promise<number> {
57
58
  }
58
59
 
59
60
  export async function missing(args: string[]): Promise<number> {
60
- const parsed = parse(args, missingUsage, { against: { type: 'string', description: 'the reference file (.env.example by default)' }, ...jsonFlag })
61
+ const parsed = parse(args, missingUsage, { against: { type: 'string', description: 'the reference file (.env.example by default)' }, ...jsonFlag }, { exits: MISSING_EXITS })
61
62
 
62
63
  const [file = '.env'] = parsed.positionals
63
64
  const against = parsed.values.against ?? '.env.example'
@@ -1,3 +1,4 @@
1
+ import type { ExitRow } from '@kaynooo/cli-kit'
1
2
  import { badUsage, fail, parse, readInput } from '@kaynooo/cli-kit'
2
3
  import { entries, lastLine, removeKey, setLine } from '../dotenv'
3
4
  import { loadKnown, readEnv, withLocks, writeEnv } from '../files'
@@ -11,27 +12,27 @@ const QUIET = { quiet: { type: 'boolean', short: 'q', description: 'print nothin
11
12
 
12
13
  const setUsage = `ev set KEY [file] [--quiet]
13
14
 
14
- Sets KEY in the file (.env by default, created when missing), replacing its line in place or appending one. The value is read from stdin, or from -F <file>, so it never appears in a command line; --empty sets it to an empty value.
15
+ Sets KEY in the file (.env by default, created when missing), replacing its line in place or appending one. The value is read from stdin, or from -F <file>, so it never appears in a command line; --empty sets it to an empty value.`
15
16
 
16
- Exits 0 when it wrote the key, 1 when it could not, 2 on a usage error.`
17
+ const SET_EXITS: ExitRow[] = [[0, 'it wrote the key'], [1, 'it could not'], [2, 'a usage error']]
17
18
 
18
19
  const unsetUsage = `ev unset KEY [file] [--quiet]
19
20
 
20
- Removes every line setting KEY from the file (.env by default), leaving comments and other lines as they are.
21
+ Removes every line setting KEY from the file (.env by default), leaving comments and other lines as they are.`
21
22
 
22
- Exits 0 when it removed the key, 1 when the file does not set it, 2 on a usage error.`
23
+ const UNSET_EXITS: ExitRow[] = [[0, 'it removed the key'], [1, 'the file does not set it'], [2, 'a usage error']]
23
24
 
24
25
  const mvUsage = `ev mv KEY --from <file> --to <file> [--quiet]
25
26
 
26
- Moves KEY's line from one file to another, as written. Refuses to replace a key the target already sets unless --force.
27
+ Moves KEY's line from one file to another, as written. Refuses to replace a key the target already sets unless --force.`
27
28
 
28
- Exits 0 when it moved the key, 1 when the source lacks it or the target already sets it, 2 on a usage error.`
29
+ const MV_EXITS: ExitRow[] = [[0, 'it moved the key'], [1, 'the source lacks it or the target already sets it'], [2, 'a usage error']]
29
30
 
30
31
  const cpUsage = `ev cp KEY --from <file> --to <file> [--as NEWKEY] [--quiet]
31
32
 
32
- Copies KEY's value from one file to another without printing it, replacing the key's line in the target in place or appending one, and prints the masked result as ev set does. --as stores the copy under another key.
33
+ Copies KEY's value from one file to another without printing it, replacing the key's line in the target in place or appending one, and prints the masked result as ev set does. --as stores the copy under another key.`
33
34
 
34
- Exits 0 when it copied the key, 1 when the source lacks it, 2 on a usage error.`
35
+ const CP_EXITS: ExitRow[] = [[0, 'it copied the key'], [1, 'the source lacks it'], [2, 'a usage error']]
35
36
 
36
37
  async function readValue(from: string | undefined): Promise<string> {
37
38
  const input = await readInput(from ?? '-', { noStdin: 'pipe the value on stdin or give -F <file>, it is never taken from the command line' })
@@ -57,7 +58,7 @@ export async function set(args: string[]): Promise<number> {
57
58
  file: { type: 'string', short: 'F', description: 'read the value from this file instead of stdin' },
58
59
  empty: { type: 'boolean', description: 'set an empty value, reading nothing' },
59
60
  ...QUIET,
60
- })
61
+ }, { exits: SET_EXITS })
61
62
 
62
63
  const [key, target = DEFAULT_FILE] = parsed.positionals
63
64
 
@@ -87,7 +88,7 @@ export async function set(args: string[]): Promise<number> {
87
88
  }
88
89
 
89
90
  export async function unset(args: string[]): Promise<number> {
90
- const parsed = parse(args, unsetUsage, QUIET)
91
+ const parsed = parse(args, unsetUsage, QUIET, { exits: UNSET_EXITS })
91
92
 
92
93
  const [key, target = DEFAULT_FILE] = parsed.positionals
93
94
 
@@ -145,7 +146,7 @@ export async function mv(args: string[]): Promise<number> {
145
146
  to: { type: 'string', description: 'the file to put KEY in, created when missing' },
146
147
  force: { type: 'boolean', description: 'replace KEY when the target already sets it' },
147
148
  ...QUIET,
148
- })
149
+ }, { exits: MV_EXITS })
149
150
 
150
151
  const [key] = parsed.positionals
151
152
  const { from, to, force } = parsed.values
@@ -172,7 +173,7 @@ export async function cp(args: string[]): Promise<number> {
172
173
  to: { type: 'string', description: 'the file to put the copy in, created when missing' },
173
174
  as: { type: 'string', description: 'store the copy under this key instead' },
174
175
  ...QUIET,
175
- })
176
+ }, { exits: CP_EXITS })
176
177
 
177
178
  const [key] = parsed.positionals
178
179
  const { from, to, as } = parsed.values
@@ -1,3 +1,4 @@
1
+ import type { ExitRow } from '@kaynooo/cli-kit'
1
2
  import type { AppPins } from '../pins'
2
3
  import { readdir, stat } from 'node:fs/promises'
3
4
  import { join, resolve } from 'node:path'
@@ -10,8 +11,9 @@ Checks that an app's tests pin the env that reaches outside.
10
11
  Reads the app's env schema (the file calling defineEnv, src/env.ts) and lists its optional URL, key, token, secret, password and host variables, then the ones no \`.env.test\` entry, test-level overrideEnv or local bunfig preload dropping what .env sets pins, and each test file that calls testSite or proxyKeyTests without pinning them all.
11
12
  A file whose pages reach none of them says so with a \`// ev pins: none reached, <why>\` comment.
12
13
  The dir is an app, or a monorepo holding apps one level down (the current folder by default).
13
- Reads variable names only, never a value.
14
- Exits 0 when everything is pinned, 1 when something is not, 2 on a usage error.`
14
+ Reads variable names only, never a value.`
15
+
16
+ const EXITS: ExitRow[] = [[0, 'everything is pinned'], [1, 'something is not'], [2, 'a usage error']]
15
17
 
16
18
  const options = {
17
19
  json: jsonOption('each app with its reaching, unpinned variables and flagged test files'),
@@ -57,7 +59,7 @@ function name(app: AppPins, root: string): string {
57
59
  }
58
60
 
59
61
  export async function pins(args: string[]): Promise<number> {
60
- const parsed = parse(args, usage, options, { positionals: ['[dir]'] })
62
+ const parsed = parse(args, usage, options, { positionals: ['[dir]'], exits: EXITS })
61
63
  const json = parsed.values.json === true
62
64
  const root = resolve(parsed.positionals[0] ?? '.')
63
65
  const except = new Set((parsed.values.except ?? '').split(',').map(entry => entry.trim()).filter(entry => entry !== ''))