@kaynooo/cli-env 0.13.2 → 0.14.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.
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 process18 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process10 from "process";
8
8
  import { parseArgs } from "util";
@@ -45,6 +45,9 @@ function outputMode(stream = process2.stdout, env = process2.env) {
45
45
  return "terminal";
46
46
  return isSet(env.CI) ? "ci" : "pipe";
47
47
  }
48
+ function isInteractive(streams = process2) {
49
+ return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
50
+ }
48
51
 
49
52
  // ../kit/src/style.ts
50
53
  import process6 from "process";
@@ -374,6 +377,23 @@ var STATUS_WORDS = {
374
377
  var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
375
378
 
376
379
  // ../kit/src/format.ts
380
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
381
+ function formatSeconds(total) {
382
+ let rest = Math.max(0, Math.round(total));
383
+ const amounts = UNITS.map(([unit, size]) => {
384
+ const amount = Math.floor(rest / size);
385
+ rest -= amount * size;
386
+ return `${amount}${unit}`;
387
+ });
388
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
389
+ if (first === -1)
390
+ return "0s";
391
+ const next = amounts[first + 1];
392
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
393
+ }
394
+ function formatDuration(ms) {
395
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
396
+ }
377
397
  function upTo(text, separator) {
378
398
  const end = text.indexOf(separator);
379
399
  return end === -1 ? text : text.slice(0, end);
@@ -434,7 +454,7 @@ function printJson(value) {
434
454
 
435
455
  // ../kit/src/help.ts
436
456
  import process8 from "process";
437
- var OPTIONAL = /\[[^\]]+\]/g;
457
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
438
458
  var USAGE_PREFIX = /^usage:\s*/i;
439
459
  var FULL_STOP = /\.$/;
440
460
  function usageLine(usage, colors = paint(process8.stdout)) {
@@ -473,29 +493,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
473
493
  return [];
474
494
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
475
495
  }
496
+ var MAX_INLINE_CHOICES = 24;
476
497
  function optionRows(options, colors = paint(process8.stdout)) {
477
498
  const rows = Object.entries(options).map(([name, option]) => {
478
499
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
479
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
500
+ const choices = option.choices?.join("|");
501
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
502
+ const named = inline ? `<${choices}>` : "<value>";
480
503
  const placeholder = option.optional === undefined ? named : `[${named}]`;
481
504
  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 ?? "" };
505
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
506
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
483
507
  });
484
508
  const width = Math.max(0, ...rows.map((row) => row.width));
485
509
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
486
510
  }
487
511
 
488
512
  // ../kit/src/text.ts
489
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
490
513
  function distance(a, b) {
491
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
492
- for (const [i, left] of [...a].entries()) {
514
+ const left = [...a];
515
+ const right = [...b];
516
+ let before = [];
517
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
518
+ for (const [i, x] of left.entries()) {
493
519
  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)));
520
+ for (const [j, y] of right.entries()) {
521
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
522
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
523
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
524
+ current.push(cost);
525
+ }
526
+ before = previous;
496
527
  previous = current;
497
528
  }
498
- return previous[b.length] ?? 0;
529
+ return previous[right.length] ?? 0;
499
530
  }
500
531
  function closest(name, names) {
501
532
  const started = names.find((known) => known.startsWith(name));
@@ -767,13 +798,31 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
767
798
  // ../kit/src/cli.ts
768
799
  import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
769
800
  import { dirname as dirname3, join as join5 } from "path";
770
- import process13 from "process";
801
+ import process14 from "process";
802
+
803
+ // ../kit/src/notify.ts
804
+ import process12 from "process";
805
+ var NOTIFY_AFTER_MS = 1e4;
806
+ var CANCELLED = 130;
807
+ function base64(text) {
808
+ return Buffer.from(text).toString("base64");
809
+ }
810
+ function notification(title, body, env = process12.env) {
811
+ const id = `kit${process12.pid}`;
812
+ 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\\`];
813
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
814
+ }
815
+ function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
816
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
817
+ return;
818
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
819
+ }
771
820
 
772
821
  // ../kit/src/usage.ts
773
822
  import { appendFileSync, mkdirSync } from "fs";
774
823
  import { homedir as homedir3 } from "os";
775
824
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
776
- import process12 from "process";
825
+ import process13 from "process";
777
826
 
778
827
  // ../kit/src/logs.ts
779
828
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -787,14 +836,14 @@ var usageError;
787
836
  function noteUsageError(message) {
788
837
  usageError = message;
789
838
  }
790
- function stateHome(env = process12.env) {
839
+ function stateHome(env = process13.env) {
791
840
  const dir = env.XDG_STATE_HOME;
792
841
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
793
842
  }
794
- function usagePath(env = process12.env) {
843
+ function usagePath(env = process13.env) {
795
844
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
796
845
  }
797
- function usageRecorded(env = process12.env) {
846
+ function usageRecorded(env = process13.env) {
798
847
  const off = env.KAYNOOO_CLI_NO_USAGE;
799
848
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
800
849
  }
@@ -808,7 +857,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
808
857
  usageError = undefined;
809
858
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
810
859
  }
811
- function recordUsage(entry, env = process12.env) {
860
+ function recordUsage(entry, env = process13.env) {
812
861
  if (!usageRecorded(env))
813
862
  return;
814
863
  try {
@@ -898,8 +947,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
898
947
  `);
899
948
  }
900
949
  function printError(prefix, message, hint, cause) {
901
- const colors = paint(process13.stderr);
902
- const styled = takesControlCodes(process13.stderr);
950
+ const colors = paint(process14.stderr);
951
+ const styled = takesControlCodes(process14.stderr);
903
952
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
904
953
  const under = (label, text, tint) => text === undefined ? "" : `
905
954
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -942,11 +991,11 @@ async function dispatch(level, typed, { version, redact }) {
942
991
  }
943
992
  }
944
993
  if (name === undefined && level.path.length > 1) {
945
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
994
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
946
995
  return 2;
947
996
  }
948
997
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
949
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
998
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
950
999
  return 0;
951
1000
  }
952
1001
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1081,10 +1130,13 @@ async function runCli(cli, argv = scriptArgs()) {
1081
1130
  const version = cli.version ?? packageVersion();
1082
1131
  if (argv[0] === COMPLETE)
1083
1132
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1133
+ const started = performance.now();
1084
1134
  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 });
1135
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1136
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1085
1137
  if (cli.usage !== false) {
1086
1138
  try {
1087
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1139
+ recordUsage(usageEntry(cli.name, command, argv, code));
1088
1140
  } catch {}
1089
1141
  }
1090
1142
  return code;
@@ -1112,11 +1164,13 @@ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs(
1112
1164
  return 0;
1113
1165
  }
1114
1166
  let code;
1167
+ const started = performance.now();
1115
1168
  try {
1116
1169
  code = await run(argv);
1117
1170
  } catch (error) {
1118
1171
  code = reportThrown(name, error, redact, wantsJson(argv));
1119
1172
  }
1173
+ notifyEnd(name, code, performance.now() - started);
1120
1174
  if (usage !== false) {
1121
1175
  try {
1122
1176
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1134,12 +1188,18 @@ async function compose(args, { flags = [], ...options } = {}) {
1134
1188
  return captureOutput(["docker", "compose", ...flags, ...args], options);
1135
1189
  }
1136
1190
  // ../kit/src/folders.ts
1191
+ import { homedir as homedir4 } from "os";
1192
+ import { join as join6 } from "path";
1193
+ import process15 from "process";
1137
1194
  var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1138
1195
  function ignoredFolders(extra = [], where = {}) {
1139
1196
  const configured = readUserConfig("config", where).ignore;
1140
1197
  const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
1141
1198
  return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
1142
1199
  }
1200
+ function cacheFolder({ home = homedir4(), env = process15.env } = {}) {
1201
+ return env.XDG_CACHE_HOME ?? join6(home, ".cache");
1202
+ }
1143
1203
  // ../kit/src/secrets.ts
1144
1204
  var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
1145
1205
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
@@ -1152,11 +1212,11 @@ var {Glob } = globalThis.Bun;
1152
1212
  var SESSION_FILES = new Glob("*.json");
1153
1213
  var ACCOUNT_DIRS = new Glob("*/sessions");
1154
1214
  // src/commands/redact.ts
1155
- import process15 from "process";
1215
+ import process17 from "process";
1156
1216
 
1157
1217
  // src/files.ts
1158
1218
  import { chmod, chown, readdir, realpath, rename, rm, stat, writeFile } from "fs/promises";
1159
- import { basename, dirname as dirname4, join as join6 } from "path";
1219
+ import { basename, dirname as dirname4, join as join7 } from "path";
1160
1220
 
1161
1221
  // src/dotenv.ts
1162
1222
  var ASSIGNMENT = /^\s*(?:export\s+)?([A-Z_][\w.-]*)\s*=(.*)$/i;
@@ -1214,7 +1274,8 @@ function parseDotenv(text) {
1214
1274
  let body = start.slice(1);
1215
1275
  let raw = line;
1216
1276
  let end = closingQuote(body, quote);
1217
- while (end === -1 && index + 1 < physical.length) {
1277
+ const first = index;
1278
+ while (end === -1 && index + 1 < physical.length && !ASSIGNMENT.test(physical[index + 1] ?? "")) {
1218
1279
  index++;
1219
1280
  body += `
1220
1281
  ${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
@@ -1222,6 +1283,11 @@ ${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
1222
1283
  ${physical[index] ?? ""}`;
1223
1284
  end = closingQuote(body, quote);
1224
1285
  }
1286
+ if (end === -1 && index + 1 < physical.length) {
1287
+ index = first;
1288
+ lines.push({ raw: line, key, value: unescapeDollar(start.replace(INLINE_COMMENT, "").trim()), unterminated: true });
1289
+ continue;
1290
+ }
1225
1291
  const inner = end === -1 ? body : body.slice(0, end);
1226
1292
  lines.push({ raw, key, value: quote === '"' ? unescapeDouble(inner) : unescapeDollar(inner) });
1227
1293
  }
@@ -1287,9 +1353,30 @@ var ESCAPE2 = /[.*+?^${}()|[\]\\]/g;
1287
1353
  function isPlaceholder(value) {
1288
1354
  return PLACEHOLDER.test(value) || PLAIN_VALUE.test(value);
1289
1355
  }
1356
+ var STRONG_NAME = "password|passwd|secret|api[_-]?key|access[_-]?key|private[_-]?key|account[_-]?key|shared[_-]?access[_-]?key";
1357
+ var WEAK_NAME = "token|credentials?|auth";
1358
+ var PLAIN_WORD = /^[a-z]+$/i;
1359
+ var AFTER_COLON = /:\s*$/;
1360
+ var DIGIT = /\d/;
1361
+ var KEY_VALUE_GAP = "\\s*[:=]\\s*";
1362
+ function isProse(value, before) {
1363
+ return isPlaceholder(value) || AFTER_COLON.test(before) && PLAIN_WORD.test(value);
1364
+ }
1365
+ function isWeak(value, before) {
1366
+ return isProse(value, before) || !(DIGIT.test(value) || value.length >= 16);
1367
+ }
1368
+ function keyed(names, value) {
1369
+ return new RegExp(`(?<![\\w-])["']?(?:[\\w-]{0,30}[_-])?(?:${names})(?:[_-][\\w-]{0,30})?["']?${KEY_VALUE_GAP}${value}`, "dgi");
1370
+ }
1290
1371
  var TOKEN_FORMATS = [
1291
1372
  { kind: "GitHub token", pattern: /\b(?:gh[pousr]_|github_pat_)\w{20,}/dg },
1292
- { kind: "GitLab token", pattern: /\bglpat-[\w-]{20,}/dg },
1373
+ { kind: "GitLab token", pattern: /\bgl(?:pat|rt|dt|ptt)-[\w-]{20,}/dg },
1374
+ { kind: "Hugging Face token", pattern: /\bhf_[A-Za-z]{30,}/dg },
1375
+ { kind: "webhook secret", pattern: /\bwhsec_\w{20,}/dg },
1376
+ { kind: "DigitalOcean token", pattern: /\bdop_v1_\w{20,}/dg },
1377
+ { kind: "Shopify token", pattern: /\bshp(?:at|ca|pa|ss)_\w{20,}/dg },
1378
+ { kind: "password", pattern: /\bmysql(?:dump|admin)?\s+(?:\S+\s+)*?-p([^\s"'|;&-]\S{3,})/dg },
1379
+ { kind: "password", pattern: /\bsshpass\s+(?:-[a-oq-z]\s+)*-p\s*([^\s"'|;&]{4,})/dg },
1293
1380
  { kind: "API key", pattern: /\bsk-[\w-]{20,}/dg },
1294
1381
  { kind: "Slack token", pattern: /\bx(?:ox[abprs]|app)-[\w-]{10,}/dg },
1295
1382
  { kind: "JWT", pattern: /\beyJ[\w-]+\.[\w-]+\.[\w-]+/dg },
@@ -1300,8 +1387,10 @@ var TOKEN_FORMATS = [
1300
1387
  { kind: "SendGrid key", pattern: /\bSG\.[\w-]{16,}\.[\w-]{16,}/dg },
1301
1388
  { kind: "Authorization header", pattern: /\bAuthorization["']?\s*[:=]\s*["']?(?:Bearer|Basic|Token|Digest)\s+([^\s"',;]{8,})/dgi, skip: isPlaceholder },
1302
1389
  { 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 }
1390
+ { kind: "password", pattern: keyed(STRONG_NAME, `([^\\s"'&;,]{4,})`), skip: isProse },
1391
+ { kind: "password", pattern: keyed(WEAK_NAME, `([^\\s"'&;,]{4,})`), skip: isWeak },
1392
+ { kind: "password", pattern: keyed(STRONG_NAME, `(["'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1`), skip: isPlaceholder },
1393
+ { kind: "password", pattern: keyed(WEAK_NAME, `(["'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1`), skip: isWeak }
1305
1394
  ];
1306
1395
  var PEM_BEGIN = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
1307
1396
  var PEM_END = /-----END [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
@@ -1406,7 +1495,7 @@ function findSecrets(line, known) {
1406
1495
  if (start === undefined || end === undefined)
1407
1496
  continue;
1408
1497
  const value = line.slice(start, end);
1409
- if (!skip?.(value))
1498
+ if (!skip?.(value, line.slice(0, start)))
1410
1499
  found.push({ start, end, kind, mask: hint(value) });
1411
1500
  }
1412
1501
  }
@@ -1468,7 +1557,7 @@ async function envFiles(folder = process.cwd()) {
1468
1557
  const found = await readdir(folder, { withFileTypes: true });
1469
1558
  const names = [];
1470
1559
  for (const entry of found) {
1471
- if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join6(folder, entry.name)))
1560
+ if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join7(folder, entry.name)))
1472
1561
  names.push(entry.name);
1473
1562
  }
1474
1563
  return names.sort();
@@ -1492,7 +1581,7 @@ async function writeAtomic(path, text) {
1492
1581
  if (error.code !== "ENOENT")
1493
1582
  throw error;
1494
1583
  }
1495
- const temp = join6(dirname4(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
1584
+ const temp = join7(dirname4(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
1496
1585
  try {
1497
1586
  await writeFile(temp, text, { mode: 384, flag: "wx" });
1498
1587
  if (owner !== undefined)
@@ -1548,7 +1637,7 @@ async function acquire(path) {
1548
1637
  try {
1549
1638
  real = await realpath(path);
1550
1639
  } catch {}
1551
- const lock = join6(dirname4(real), `.${basename(real)}.lock`);
1640
+ const lock = join7(dirname4(real), `.${basename(real)}.lock`);
1552
1641
  const deadline = Date.now() + LOCK_WAIT_MS;
1553
1642
  while (true) {
1554
1643
  try {
@@ -1583,7 +1672,7 @@ async function envFilesBelow(folder, depth = 0) {
1583
1672
  return found;
1584
1673
  }
1585
1674
  for (const entry of children) {
1586
- const path = join6(folder, entry.name);
1675
+ const path = join7(folder, entry.name);
1587
1676
  if (entry.isDirectory() && depth < KNOWN_DEPTH && !SKIPPED.has(entry.name))
1588
1677
  found.push(...await envFilesBelow(path, depth + 1));
1589
1678
  else if (ENV_FILE.test(entry.name) && await isFileEntry(entry, path))
@@ -1738,10 +1827,10 @@ async function redact(args) {
1738
1827
  const redactor = new Redactor(known);
1739
1828
  const decoder = new TextDecoder;
1740
1829
  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());
1830
+ process17.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
1831
+ process17.stdout.write(redactor.push(decoder.decode()) + redactor.end());
1743
1832
  return 0;
1744
1833
  }
1745
1834
 
1746
1835
  // src/redact.ts
1747
- process16.exitCode = await runMain({ name: "redact", run: redact });
1836
+ process18.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.14.0",
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.40.0"
41
41
  }
42
42
  }
@@ -1,5 +1,6 @@
1
1
  import type { ExitRow } from '@kaynooo/cli-kit'
2
- import { badUsage, fail, parse, readInput } from '@kaynooo/cli-kit'
2
+ import { badUsage, fail, isInteractive, parse, readInput } from '@kaynooo/cli-kit'
3
+ import { input } from '@kaynooo/cli-kit/prompt'
3
4
  import { entries, lastLine, removeKey, setLine } from '../dotenv'
4
5
  import { loadKnown, readEnv, withLocks, writeEnv } from '../files'
5
6
  import { maskValue } from '../mask'
@@ -12,9 +13,9 @@ const QUIET = { quiet: { type: 'boolean', short: 'q', description: 'print nothin
12
13
 
13
14
  const setUsage = `ev set KEY [file] [--quiet]
14
15
 
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.`
16
+ 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; on a terminal with nothing piped it is asked for, masked as it is typed. --empty sets it to an empty value.`
16
17
 
17
- const SET_EXITS: ExitRow[] = [[0, 'it wrote the key'], [1, 'it could not'], [2, 'a usage error']]
18
+ const SET_EXITS: ExitRow[] = [[0, 'it wrote the key'], [1, 'it could not'], [2, 'a usage error'], [130, 'the prompt was cancelled']]
18
19
 
19
20
  const unsetUsage = `ev unset KEY [file] [--quiet]
20
21
 
@@ -34,13 +35,15 @@ Copies KEY's value from one file to another without printing it, replacing the k
34
35
 
35
36
  const CP_EXITS: ExitRow[] = [[0, 'it copied the key'], [1, 'the source lacks it'], [2, 'a usage error']]
36
37
 
37
- async function readValue(from: string | undefined): Promise<string> {
38
- const input = await readInput(from ?? '-', { noStdin: 'pipe the value on stdin or give -F <file>, it is never taken from the command line' })
38
+ async function readValue(key: string, from: string | undefined): Promise<string> {
39
+ const value = from === undefined && isInteractive()
40
+ ? await input(`value of ${key}`, { mask: true }) ?? fail('cancelled, nothing was written', 130)
41
+ : await readInput(from ?? '-', { noStdin: 'pipe the value on stdin or give -F <file>, it is never taken from the command line' })
39
42
 
40
- if (input === '')
43
+ if (value === '')
41
44
  fail('the value is empty, nothing was written: --empty sets an empty value')
42
45
 
43
- return input.replace(TRAILING_NEWLINE, '')
46
+ return value.replace(TRAILING_NEWLINE, '')
44
47
  }
45
48
 
46
49
  // A key that is not a plain name could carry a line break or an `=` and write more than one line.
@@ -70,7 +73,7 @@ export async function set(args: string[]): Promise<number> {
70
73
 
71
74
  checkKey(key)
72
75
 
73
- const value = parsed.values.empty === true ? '' : await readValue(parsed.values.file)
76
+ const value = parsed.values.empty === true ? '' : await readValue(key, parsed.values.file)
74
77
 
75
78
  const file = await withLocks([target], async () => {
76
79
  const current = await readOrEmpty(target)
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
  }