@kaynooo/cli-env 0.13.2 → 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/ev.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/ev.ts
5
- import process18 from "process";
5
+ import process19 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,7 +451,7 @@ 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)) {
@@ -473,29 +490,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
473
490
  return [];
474
491
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
475
492
  }
493
+ var MAX_INLINE_CHOICES = 24;
476
494
  function optionRows(options, colors = paint(process8.stdout)) {
477
495
  const rows = Object.entries(options).map(([name, option]) => {
478
496
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
479
- 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>";
480
500
  const placeholder = option.optional === undefined ? named : `[${named}]`;
481
501
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
482
- 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 };
483
504
  });
484
505
  const width = Math.max(0, ...rows.map((row) => row.width));
485
506
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
486
507
  }
487
508
 
488
509
  // ../kit/src/text.ts
489
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
490
510
  function distance(a, b) {
491
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
492
- 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()) {
493
516
  const current = [i + 1];
494
- for (const [j, right] of [...b].entries())
495
- 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;
496
524
  previous = current;
497
525
  }
498
- return previous[b.length] ?? 0;
526
+ return previous[right.length] ?? 0;
499
527
  }
500
528
  function closest(name, names) {
501
529
  const started = names.find((known) => known.startsWith(name));
@@ -767,13 +795,31 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
767
795
  // ../kit/src/cli.ts
768
796
  import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
769
797
  import { dirname as dirname3, join as join5 } from "path";
770
- import process13 from "process";
798
+ import process14 from "process";
799
+
800
+ // ../kit/src/notify.ts
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
+ }
771
817
 
772
818
  // ../kit/src/usage.ts
773
819
  import { appendFileSync, mkdirSync } from "fs";
774
820
  import { homedir as homedir3 } from "os";
775
821
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
776
- import process12 from "process";
822
+ import process13 from "process";
777
823
 
778
824
  // ../kit/src/logs.ts
779
825
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -787,14 +833,14 @@ var usageError;
787
833
  function noteUsageError(message) {
788
834
  usageError = message;
789
835
  }
790
- function stateHome(env = process12.env) {
836
+ function stateHome(env = process13.env) {
791
837
  const dir = env.XDG_STATE_HOME;
792
838
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
793
839
  }
794
- function usagePath(env = process12.env) {
840
+ function usagePath(env = process13.env) {
795
841
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
796
842
  }
797
- function usageRecorded(env = process12.env) {
843
+ function usageRecorded(env = process13.env) {
798
844
  const off = env.KAYNOOO_CLI_NO_USAGE;
799
845
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
800
846
  }
@@ -808,7 +854,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
808
854
  usageError = undefined;
809
855
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
810
856
  }
811
- function recordUsage(entry, env = process12.env) {
857
+ function recordUsage(entry, env = process13.env) {
812
858
  if (!usageRecorded(env))
813
859
  return;
814
860
  try {
@@ -898,8 +944,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
898
944
  `);
899
945
  }
900
946
  function printError(prefix, message, hint, cause) {
901
- const colors = paint(process13.stderr);
902
- const styled = takesControlCodes(process13.stderr);
947
+ const colors = paint(process14.stderr);
948
+ const styled = takesControlCodes(process14.stderr);
903
949
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
904
950
  const under = (label, text, tint) => text === undefined ? "" : `
905
951
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -942,11 +988,11 @@ async function dispatch(level, typed, { version, redact }) {
942
988
  }
943
989
  }
944
990
  if (name === undefined && level.path.length > 1) {
945
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
991
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
946
992
  return 2;
947
993
  }
948
994
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
949
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
995
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
950
996
  return 0;
951
997
  }
952
998
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1081,10 +1127,13 @@ async function runCli(cli, argv = scriptArgs()) {
1081
1127
  const version = cli.version ?? packageVersion();
1082
1128
  if (argv[0] === COMPLETE)
1083
1129
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1130
+ const started = performance.now();
1084
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);
1085
1134
  if (cli.usage !== false) {
1086
1135
  try {
1087
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1136
+ recordUsage(usageEntry(cli.name, command, argv, code));
1088
1137
  } catch {}
1089
1138
  }
1090
1139
  return code;
@@ -1112,11 +1161,13 @@ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs(
1112
1161
  return 0;
1113
1162
  }
1114
1163
  let code;
1164
+ const started = performance.now();
1115
1165
  try {
1116
1166
  code = await run(argv);
1117
1167
  } catch (error) {
1118
1168
  code = reportThrown(name, error, redact, wantsJson(argv));
1119
1169
  }
1170
+ notifyEnd(name, code, performance.now() - started);
1120
1171
  if (usage !== false) {
1121
1172
  try {
1122
1173
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1154,7 +1205,7 @@ var ACCOUNT_DIRS = new Glob("*/sessions");
1154
1205
  // src/commands/audit.ts
1155
1206
  import { stat as stat4 } from "fs/promises";
1156
1207
  import { relative, resolve as resolve4 } from "path";
1157
- import process15 from "process";
1208
+ import process16 from "process";
1158
1209
 
1159
1210
  // ../kit/src/shell.ts
1160
1211
  var SEPARATORS = new Set([`
@@ -1268,7 +1319,8 @@ function parseDotenv(text) {
1268
1319
  let body = start.slice(1);
1269
1320
  let raw = line;
1270
1321
  let end = closingQuote(body, quote);
1271
- while (end === -1 && index + 1 < physical.length) {
1322
+ const first = index;
1323
+ while (end === -1 && index + 1 < physical.length && !ASSIGNMENT.test(physical[index + 1] ?? "")) {
1272
1324
  index++;
1273
1325
  body += `
1274
1326
  ${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
@@ -1276,6 +1328,11 @@ ${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
1276
1328
  ${physical[index] ?? ""}`;
1277
1329
  end = closingQuote(body, quote);
1278
1330
  }
1331
+ if (end === -1 && index + 1 < physical.length) {
1332
+ index = first;
1333
+ lines.push({ raw: line, key, value: unescapeDollar(start.replace(INLINE_COMMENT, "").trim()), unterminated: true });
1334
+ continue;
1335
+ }
1279
1336
  const inner = end === -1 ? body : body.slice(0, end);
1280
1337
  lines.push({ raw, key, value: quote === '"' ? unescapeDouble(inner) : unescapeDollar(inner) });
1281
1338
  }
@@ -1341,9 +1398,30 @@ var ESCAPE2 = /[.*+?^${}()|[\]\\]/g;
1341
1398
  function isPlaceholder(value) {
1342
1399
  return PLACEHOLDER.test(value) || PLAIN_VALUE.test(value);
1343
1400
  }
1401
+ var STRONG_NAME = "password|passwd|secret|api[_-]?key|access[_-]?key|private[_-]?key|account[_-]?key|shared[_-]?access[_-]?key";
1402
+ var WEAK_NAME = "token|credentials?|auth";
1403
+ var PLAIN_WORD = /^[a-z]+$/i;
1404
+ var AFTER_COLON = /:\s*$/;
1405
+ var DIGIT = /\d/;
1406
+ var KEY_VALUE_GAP = "\\s*[:=]\\s*";
1407
+ function isProse(value, before) {
1408
+ return isPlaceholder(value) || AFTER_COLON.test(before) && PLAIN_WORD.test(value);
1409
+ }
1410
+ function isWeak(value, before) {
1411
+ return isProse(value, before) || !(DIGIT.test(value) || value.length >= 16);
1412
+ }
1413
+ function keyed(names, value) {
1414
+ return new RegExp(`(?<![\\w-])["']?(?:[\\w-]{0,30}[_-])?(?:${names})(?:[_-][\\w-]{0,30})?["']?${KEY_VALUE_GAP}${value}`, "dgi");
1415
+ }
1344
1416
  var TOKEN_FORMATS = [
1345
1417
  { kind: "GitHub token", pattern: /\b(?:gh[pousr]_|github_pat_)\w{20,}/dg },
1346
- { kind: "GitLab token", pattern: /\bglpat-[\w-]{20,}/dg },
1418
+ { kind: "GitLab token", pattern: /\bgl(?:pat|rt|dt|ptt)-[\w-]{20,}/dg },
1419
+ { kind: "Hugging Face token", pattern: /\bhf_[A-Za-z]{30,}/dg },
1420
+ { kind: "webhook secret", pattern: /\bwhsec_\w{20,}/dg },
1421
+ { kind: "DigitalOcean token", pattern: /\bdop_v1_\w{20,}/dg },
1422
+ { kind: "Shopify token", pattern: /\bshp(?:at|ca|pa|ss)_\w{20,}/dg },
1423
+ { kind: "password", pattern: /\bmysql(?:dump|admin)?\s+(?:\S+\s+)*?-p([^\s"'|;&-]\S{3,})/dg },
1424
+ { kind: "password", pattern: /\bsshpass\s+(?:-[a-oq-z]\s+)*-p\s*([^\s"'|;&]{4,})/dg },
1347
1425
  { kind: "API key", pattern: /\bsk-[\w-]{20,}/dg },
1348
1426
  { kind: "Slack token", pattern: /\bx(?:ox[abprs]|app)-[\w-]{10,}/dg },
1349
1427
  { kind: "JWT", pattern: /\beyJ[\w-]+\.[\w-]+\.[\w-]+/dg },
@@ -1354,8 +1432,10 @@ var TOKEN_FORMATS = [
1354
1432
  { kind: "SendGrid key", pattern: /\bSG\.[\w-]{16,}\.[\w-]{16,}/dg },
1355
1433
  { kind: "Authorization header", pattern: /\bAuthorization["']?\s*[:=]\s*["']?(?:Bearer|Basic|Token|Digest)\s+([^\s"',;]{8,})/dgi, skip: isPlaceholder },
1356
1434
  { kind: "Bearer token", pattern: /\bBearer\s+((?=[\w.~+/=-]*\d)[\w.~+/=-]{20,})/dg },
1357
- { kind: "password", pattern: /(?<![\w-])(?:[\w-]{0,30}[_-])?(?:password|passwd|secret|api[_-]?key)(?:[_-][\w-]{0,30})?=([^\s"'&;,]{4,})/dgi, skip: isPlaceholder },
1358
- { kind: "password", pattern: /(?<![\w-])["']?(?:[\w-]{0,30}[_-])?(?:password|passwd|secret|api[_-]?key)(?:[_-][\w-]{0,30})?["']?\s*[:=]\s*(["'])((?:\\.|(?!\1)[^\\\n]){4,})\1/dgi, skip: isPlaceholder }
1435
+ { kind: "password", pattern: keyed(STRONG_NAME, `([^\\s"'&;,]{4,})`), skip: isProse },
1436
+ { kind: "password", pattern: keyed(WEAK_NAME, `([^\\s"'&;,]{4,})`), skip: isWeak },
1437
+ { kind: "password", pattern: keyed(STRONG_NAME, `(["'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1`), skip: isPlaceholder },
1438
+ { kind: "password", pattern: keyed(WEAK_NAME, `(["'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1`), skip: isWeak }
1359
1439
  ];
1360
1440
  var PEM_BEGIN = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
1361
1441
  var PEM_END = /-----END [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
@@ -1460,7 +1540,7 @@ function findSecrets(line, known) {
1460
1540
  if (start === undefined || end === undefined)
1461
1541
  continue;
1462
1542
  const value = line.slice(start, end);
1463
- if (!skip?.(value))
1543
+ if (!skip?.(value, line.slice(0, start)))
1464
1544
  found.push({ start, end, kind, mask: hint(value) });
1465
1545
  }
1466
1546
  }
@@ -1971,12 +2051,12 @@ async function isFolder(path) {
1971
2051
  }
1972
2052
  }
1973
2053
  function shown2(path) {
1974
- return path.startsWith(`${process15.cwd()}/`) ? relative(process15.cwd(), path) : path;
2054
+ return path.startsWith(`${process16.cwd()}/`) ? relative(process16.cwd(), path) : path;
1975
2055
  }
1976
2056
  async function fixAll(exposed, json) {
1977
2057
  const fixed = [];
1978
2058
  let left = false;
1979
- const tint = role("path", process15.stdout);
2059
+ const tint = role("path", process16.stdout);
1980
2060
  for (const { path, readable, group, tracked, secrets } of exposed) {
1981
2061
  const fix = secrets === undefined ? undefined : await fixCompose(path, group === true);
1982
2062
  const open = fix?.open ?? (readable && !await shutOthersOut(path, group === true) ? [path] : []);
@@ -2028,8 +2108,8 @@ async function audit2(args) {
2028
2108
  console.log("no exposed .env file nor compose file writing a secret out");
2029
2109
  return 0;
2030
2110
  }
2031
- const uid = process15.getuid?.();
2032
- const tint = role("path", process15.stdout);
2111
+ const uid = process16.getuid?.();
2112
+ const tint = role("path", process16.stdout);
2033
2113
  for (const { path, readable, group, tracked, secrets } of exposed) {
2034
2114
  const sudo = uid !== undefined && uid !== 0 && (await stat4(path)).uid !== uid ? "sudo " : "";
2035
2115
  const problems = [
@@ -2045,7 +2125,7 @@ async function audit2(args) {
2045
2125
  }
2046
2126
 
2047
2127
  // src/commands/compare.ts
2048
- import process16 from "process";
2128
+ import process17 from "process";
2049
2129
  var diffUsage = `ev diff <a> <b>
2050
2130
 
2051
2131
  Names the keys set in one file and not the other, never their values.
@@ -2077,8 +2157,8 @@ ${diffUsage}`);
2077
2157
  printJson({ a, b, onlyA, onlyB });
2078
2158
  return onlyA.length + onlyB.length === 0 ? 0 : 1;
2079
2159
  }
2080
- const path = role("path", process16.stdout);
2081
- const value = role("value", process16.stdout);
2160
+ const path = role("path", process17.stdout);
2161
+ const value = role("value", process17.stdout);
2082
2162
  const lines = [...onlyA.map((key) => `only in ${path(a)}: ${value(key)}`), ...onlyB.map((key) => `only in ${path(b)}: ${value(key)}`)];
2083
2163
  if (lines.length === 0)
2084
2164
  return 0;
@@ -2099,8 +2179,8 @@ async function missing(args) {
2099
2179
  }
2100
2180
  if (absent.length === 0)
2101
2181
  return 0;
2102
- const path = role("path", process16.stdout);
2103
- const value = role("value", process16.stdout);
2182
+ const path = role("path", process17.stdout);
2183
+ const value = role("value", process17.stdout);
2104
2184
  console.log(absent.map((key) => `${value(key)} (set in ${path(against)}, not in ${path(file)})`).join(`
2105
2185
  `));
2106
2186
  return 1;
@@ -2638,7 +2718,7 @@ ${showUsage}`);
2638
2718
  }
2639
2719
 
2640
2720
  // src/commands/redact.ts
2641
- import process17 from "process";
2721
+ import process18 from "process";
2642
2722
 
2643
2723
  // src/redactor.ts
2644
2724
  var DIFF_START = /^(?:diff --git |@@ )/;
@@ -2777,13 +2857,13 @@ async function redact(args) {
2777
2857
  const redactor = new Redactor(known);
2778
2858
  const decoder = new TextDecoder;
2779
2859
  for await (const chunk of Bun.stdin.stream())
2780
- process17.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
2781
- process17.stdout.write(redactor.push(decoder.decode()) + redactor.end());
2860
+ process18.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
2861
+ process18.stdout.write(redactor.push(decoder.decode()) + redactor.end());
2782
2862
  return 0;
2783
2863
  }
2784
2864
 
2785
2865
  // src/ev.ts
2786
- process18.exitCode = await runCli({
2866
+ process19.exitCode = await runCli({
2787
2867
  name: "ev",
2788
2868
  about: ".env files listed and edited with secrets masked",
2789
2869
  replaces: "cat .env, grep on env files and editing them by hand",
package/dist/redact.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/redact.ts
5
- import process16 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,7 +451,7 @@ 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)) {
@@ -473,29 +490,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
473
490
  return [];
474
491
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
475
492
  }
493
+ var MAX_INLINE_CHOICES = 24;
476
494
  function optionRows(options, colors = paint(process8.stdout)) {
477
495
  const rows = Object.entries(options).map(([name, option]) => {
478
496
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
479
- 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>";
480
500
  const placeholder = option.optional === undefined ? named : `[${named}]`;
481
501
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
482
- 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 };
483
504
  });
484
505
  const width = Math.max(0, ...rows.map((row) => row.width));
485
506
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
486
507
  }
487
508
 
488
509
  // ../kit/src/text.ts
489
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
490
510
  function distance(a, b) {
491
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
492
- 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()) {
493
516
  const current = [i + 1];
494
- for (const [j, right] of [...b].entries())
495
- 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;
496
524
  previous = current;
497
525
  }
498
- return previous[b.length] ?? 0;
526
+ return previous[right.length] ?? 0;
499
527
  }
500
528
  function closest(name, names) {
501
529
  const started = names.find((known) => known.startsWith(name));
@@ -767,13 +795,31 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
767
795
  // ../kit/src/cli.ts
768
796
  import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
769
797
  import { dirname as dirname3, join as join5 } from "path";
770
- import process13 from "process";
798
+ import process14 from "process";
799
+
800
+ // ../kit/src/notify.ts
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
+ }
771
817
 
772
818
  // ../kit/src/usage.ts
773
819
  import { appendFileSync, mkdirSync } from "fs";
774
820
  import { homedir as homedir3 } from "os";
775
821
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
776
- import process12 from "process";
822
+ import process13 from "process";
777
823
 
778
824
  // ../kit/src/logs.ts
779
825
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -787,14 +833,14 @@ var usageError;
787
833
  function noteUsageError(message) {
788
834
  usageError = message;
789
835
  }
790
- function stateHome(env = process12.env) {
836
+ function stateHome(env = process13.env) {
791
837
  const dir = env.XDG_STATE_HOME;
792
838
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
793
839
  }
794
- function usagePath(env = process12.env) {
840
+ function usagePath(env = process13.env) {
795
841
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
796
842
  }
797
- function usageRecorded(env = process12.env) {
843
+ function usageRecorded(env = process13.env) {
798
844
  const off = env.KAYNOOO_CLI_NO_USAGE;
799
845
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
800
846
  }
@@ -808,7 +854,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
808
854
  usageError = undefined;
809
855
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
810
856
  }
811
- function recordUsage(entry, env = process12.env) {
857
+ function recordUsage(entry, env = process13.env) {
812
858
  if (!usageRecorded(env))
813
859
  return;
814
860
  try {
@@ -898,8 +944,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
898
944
  `);
899
945
  }
900
946
  function printError(prefix, message, hint, cause) {
901
- const colors = paint(process13.stderr);
902
- const styled = takesControlCodes(process13.stderr);
947
+ const colors = paint(process14.stderr);
948
+ const styled = takesControlCodes(process14.stderr);
903
949
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
904
950
  const under = (label, text, tint) => text === undefined ? "" : `
905
951
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -942,11 +988,11 @@ async function dispatch(level, typed, { version, redact }) {
942
988
  }
943
989
  }
944
990
  if (name === undefined && level.path.length > 1) {
945
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
991
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
946
992
  return 2;
947
993
  }
948
994
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
949
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
995
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
950
996
  return 0;
951
997
  }
952
998
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1081,10 +1127,13 @@ async function runCli(cli, argv = scriptArgs()) {
1081
1127
  const version = cli.version ?? packageVersion();
1082
1128
  if (argv[0] === COMPLETE)
1083
1129
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1130
+ const started = performance.now();
1084
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);
1085
1134
  if (cli.usage !== false) {
1086
1135
  try {
1087
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1136
+ recordUsage(usageEntry(cli.name, command, argv, code));
1088
1137
  } catch {}
1089
1138
  }
1090
1139
  return code;
@@ -1112,11 +1161,13 @@ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs(
1112
1161
  return 0;
1113
1162
  }
1114
1163
  let code;
1164
+ const started = performance.now();
1115
1165
  try {
1116
1166
  code = await run(argv);
1117
1167
  } catch (error) {
1118
1168
  code = reportThrown(name, error, redact, wantsJson(argv));
1119
1169
  }
1170
+ notifyEnd(name, code, performance.now() - started);
1120
1171
  if (usage !== false) {
1121
1172
  try {
1122
1173
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1152,7 +1203,7 @@ var {Glob } = globalThis.Bun;
1152
1203
  var SESSION_FILES = new Glob("*.json");
1153
1204
  var ACCOUNT_DIRS = new Glob("*/sessions");
1154
1205
  // src/commands/redact.ts
1155
- import process15 from "process";
1206
+ import process16 from "process";
1156
1207
 
1157
1208
  // src/files.ts
1158
1209
  import { chmod, chown, readdir, realpath, rename, rm, stat, writeFile } from "fs/promises";
@@ -1214,7 +1265,8 @@ function parseDotenv(text) {
1214
1265
  let body = start.slice(1);
1215
1266
  let raw = line;
1216
1267
  let end = closingQuote(body, quote);
1217
- while (end === -1 && index + 1 < physical.length) {
1268
+ const first = index;
1269
+ while (end === -1 && index + 1 < physical.length && !ASSIGNMENT.test(physical[index + 1] ?? "")) {
1218
1270
  index++;
1219
1271
  body += `
1220
1272
  ${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
@@ -1222,6 +1274,11 @@ ${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
1222
1274
  ${physical[index] ?? ""}`;
1223
1275
  end = closingQuote(body, quote);
1224
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
+ }
1225
1282
  const inner = end === -1 ? body : body.slice(0, end);
1226
1283
  lines.push({ raw, key, value: quote === '"' ? unescapeDouble(inner) : unescapeDollar(inner) });
1227
1284
  }
@@ -1287,9 +1344,30 @@ var ESCAPE2 = /[.*+?^${}()|[\]\\]/g;
1287
1344
  function isPlaceholder(value) {
1288
1345
  return PLACEHOLDER.test(value) || PLAIN_VALUE.test(value);
1289
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
+ }
1290
1362
  var TOKEN_FORMATS = [
1291
1363
  { kind: "GitHub token", pattern: /\b(?:gh[pousr]_|github_pat_)\w{20,}/dg },
1292
- { 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 },
1293
1371
  { kind: "API key", pattern: /\bsk-[\w-]{20,}/dg },
1294
1372
  { kind: "Slack token", pattern: /\bx(?:ox[abprs]|app)-[\w-]{10,}/dg },
1295
1373
  { kind: "JWT", pattern: /\beyJ[\w-]+\.[\w-]+\.[\w-]+/dg },
@@ -1300,8 +1378,10 @@ var TOKEN_FORMATS = [
1300
1378
  { kind: "SendGrid key", pattern: /\bSG\.[\w-]{16,}\.[\w-]{16,}/dg },
1301
1379
  { kind: "Authorization header", pattern: /\bAuthorization["']?\s*[:=]\s*["']?(?:Bearer|Basic|Token|Digest)\s+([^\s"',;]{8,})/dgi, skip: isPlaceholder },
1302
1380
  { kind: "Bearer token", pattern: /\bBearer\s+((?=[\w.~+/=-]*\d)[\w.~+/=-]{20,})/dg },
1303
- { kind: "password", pattern: /(?<![\w-])(?:[\w-]{0,30}[_-])?(?:password|passwd|secret|api[_-]?key)(?:[_-][\w-]{0,30})?=([^\s"'&;,]{4,})/dgi, skip: isPlaceholder },
1304
- { 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 }
1305
1385
  ];
1306
1386
  var PEM_BEGIN = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
1307
1387
  var PEM_END = /-----END [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
@@ -1406,7 +1486,7 @@ function findSecrets(line, known) {
1406
1486
  if (start === undefined || end === undefined)
1407
1487
  continue;
1408
1488
  const value = line.slice(start, end);
1409
- if (!skip?.(value))
1489
+ if (!skip?.(value, line.slice(0, start)))
1410
1490
  found.push({ start, end, kind, mask: hint(value) });
1411
1491
  }
1412
1492
  }
@@ -1738,10 +1818,10 @@ async function redact(args) {
1738
1818
  const redactor = new Redactor(known);
1739
1819
  const decoder = new TextDecoder;
1740
1820
  for await (const chunk of Bun.stdin.stream())
1741
- process15.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
1742
- process15.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());
1743
1823
  return 0;
1744
1824
  }
1745
1825
 
1746
1826
  // src/redact.ts
1747
- process16.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.2",
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.38.2"
40
+ "@kaynooo/cli-kit": "0.39.0"
41
41
  }
42
42
  }
package/src/dotenv.ts CHANGED
@@ -3,6 +3,8 @@ export interface DotenvLine {
3
3
  raw: string
4
4
  key?: string
5
5
  value?: string
6
+ // The value opens a quote that no line closes before the next assignment: it is read as the rest of its own line, as Bun does.
7
+ unterminated?: boolean
6
8
  }
7
9
 
8
10
  export interface Dotenv {
@@ -83,13 +85,22 @@ export function parseDotenv(text: string): Dotenv {
83
85
  let raw = line
84
86
  let end = closingQuote(body, quote)
85
87
 
86
- while (end === -1 && index + 1 < physical.length) {
88
+ const first = index
89
+
90
+ while (end === -1 && index + 1 < physical.length && !ASSIGNMENT.test(physical[index + 1] ?? '')) {
87
91
  index++
88
92
  body += `\n${(physical[index] ?? '').replace(CARRIAGE_RETURN, '')}`
89
93
  raw += `\n${physical[index] ?? ''}`
90
94
  end = closingQuote(body, quote)
91
95
  }
92
96
 
97
+ if (end === -1 && index + 1 < physical.length) {
98
+ index = first
99
+ lines.push({ raw: line, key, value: unescapeDollar(start.replace(INLINE_COMMENT, '').trim()), unterminated: true })
100
+
101
+ continue
102
+ }
103
+
93
104
  const inner = end === -1 ? body : body.slice(0, end)
94
105
 
95
106
  lines.push({ raw, key, value: quote === '"' ? unescapeDouble(inner) : unescapeDollar(inner) })
package/src/mask.ts CHANGED
@@ -28,8 +28,8 @@ const ESCAPE = /[.*+?^${}()|[\]\\]/g
28
28
  interface TokenFormat {
29
29
  kind: string
30
30
  pattern: RegExp
31
- // Skips a candidate that is a placeholder or a plain word.
32
- skip?: (value: string) => boolean
31
+ // Skips a candidate that is a placeholder or a plain word. `before` is the line text ahead of it.
32
+ skip?: (value: string, before: string) => boolean
33
33
  }
34
34
 
35
35
  // A secret value starting like this is a reference or a placeholder, not the secret.
@@ -37,10 +37,39 @@ function isPlaceholder(value: string): boolean {
37
37
  return PLACEHOLDER.test(value) || PLAIN_VALUE.test(value)
38
38
  }
39
39
 
40
+ // Names that are secrets whatever they are followed by, and names that also open prose (`token: expired`, `auth: failed`).
41
+ const STRONG_NAME = 'password|passwd|secret|api[_-]?key|access[_-]?key|private[_-]?key|account[_-]?key|shared[_-]?access[_-]?key'
42
+ const WEAK_NAME = 'token|credentials?|auth'
43
+ const PLAIN_WORD = /^[a-z]+$/i
44
+ const AFTER_COLON = /:\s*$/
45
+ const DIGIT = /\d/
46
+ const KEY_VALUE_GAP = '\\s*[:=]\\s*'
47
+
48
+ // A strong name before a colon, so likely prose, holding only a word is left alone.
49
+ function isProse(value: string, before: string): boolean {
50
+ return isPlaceholder(value) || (AFTER_COLON.test(before) && PLAIN_WORD.test(value))
51
+ }
52
+
53
+ // A value under a weak name is a secret only when it holds a digit or is long, which a word of prose never does.
54
+ function isWeak(value: string, before: string): boolean {
55
+ return isProse(value, before) || !(DIGIT.test(value) || value.length >= 16)
56
+ }
57
+
58
+ // A key name holding one of the words: `AWS_SECRET_ACCESS_KEY`, `X-Api-Key`, `access_token`.
59
+ function keyed(names: string, value: string): RegExp {
60
+ return new RegExp(`(?<![\\w-])["']?(?:[\\w-]{0,30}[_-])?(?:${names})(?:[_-][\\w-]{0,30})?["']?${KEY_VALUE_GAP}${value}`, 'dgi')
61
+ }
62
+
40
63
  // A pattern with a group masks that group only, else the whole match.
41
64
  const TOKEN_FORMATS: TokenFormat[] = [
42
65
  { kind: 'GitHub token', pattern: /\b(?:gh[pousr]_|github_pat_)\w{20,}/dg },
43
- { kind: 'GitLab token', pattern: /\bglpat-[\w-]{20,}/dg },
66
+ { kind: 'GitLab token', pattern: /\bgl(?:pat|rt|dt|ptt)-[\w-]{20,}/dg },
67
+ { kind: 'Hugging Face token', pattern: /\bhf_[A-Za-z]{30,}/dg },
68
+ { kind: 'webhook secret', pattern: /\bwhsec_\w{20,}/dg },
69
+ { kind: 'DigitalOcean token', pattern: /\bdop_v1_\w{20,}/dg },
70
+ { kind: 'Shopify token', pattern: /\bshp(?:at|ca|pa|ss)_\w{20,}/dg },
71
+ { kind: 'password', pattern: /\bmysql(?:dump|admin)?\s+(?:\S+\s+)*?-p([^\s"'|;&-]\S{3,})/dg },
72
+ { kind: 'password', pattern: /\bsshpass\s+(?:-[a-oq-z]\s+)*-p\s*([^\s"'|;&]{4,})/dg },
44
73
  { kind: 'API key', pattern: /\bsk-[\w-]{20,}/dg },
45
74
  { kind: 'Slack token', pattern: /\bx(?:ox[abprs]|app)-[\w-]{10,}/dg },
46
75
  { kind: 'JWT', pattern: /\beyJ[\w-]+\.[\w-]+\.[\w-]+/dg },
@@ -51,8 +80,10 @@ const TOKEN_FORMATS: TokenFormat[] = [
51
80
  { kind: 'SendGrid key', pattern: /\bSG\.[\w-]{16,}\.[\w-]{16,}/dg },
52
81
  { kind: 'Authorization header', pattern: /\bAuthorization["']?\s*[:=]\s*["']?(?:Bearer|Basic|Token|Digest)\s+([^\s"',;]{8,})/dgi, skip: isPlaceholder },
53
82
  { kind: 'Bearer token', pattern: /\bBearer\s+((?=[\w.~+/=-]*\d)[\w.~+/=-]{20,})/dg },
54
- { kind: 'password', pattern: /(?<![\w-])(?:[\w-]{0,30}[_-])?(?:password|passwd|secret|api[_-]?key)(?:[_-][\w-]{0,30})?=([^\s"'&;,]{4,})/dgi, skip: isPlaceholder },
55
- { kind: 'password', pattern: /(?<![\w-])["']?(?:[\w-]{0,30}[_-])?(?:password|passwd|secret|api[_-]?key)(?:[_-][\w-]{0,30})?["']?\s*[:=]\s*(["'])((?:\\.|(?!\1)[^\\\n]){4,})\1/dgi, skip: isPlaceholder },
83
+ { kind: 'password', pattern: keyed(STRONG_NAME, '([^\\s"\'&;,]{4,})'), skip: isProse },
84
+ { kind: 'password', pattern: keyed(WEAK_NAME, '([^\\s"\'&;,]{4,})'), skip: isWeak },
85
+ { kind: 'password', pattern: keyed(STRONG_NAME, '(["\'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1'), skip: isPlaceholder },
86
+ { kind: 'password', pattern: keyed(WEAK_NAME, '(["\'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1'), skip: isWeak },
56
87
  ]
57
88
 
58
89
  // A private key block (PEM, PGP). Its body is masked from just after the BEGIN marker to the END marker or the end of the line, so one line may hold the whole key escaped as JSON.
@@ -207,7 +238,7 @@ export function findSecrets(line: string, known?: KnownSecrets): Match[] {
207
238
 
208
239
  const value = line.slice(start, end)
209
240
 
210
- if (!skip?.(value))
241
+ if (!skip?.(value, line.slice(0, start)))
211
242
  found.push({ start, end, kind, mask: hint(value) })
212
243
  }
213
244
  }