@kaynooo/cli-env 0.13.1 → 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/ev.js +642 -137
- package/dist/redact.js +171 -60
- package/package.json +2 -2
- package/src/commands/audit.ts +5 -3
- package/src/commands/compare.ts +7 -6
- package/src/commands/edit.ts +22 -18
- package/src/commands/pins.ts +5 -3
- package/src/commands/read.ts +13 -12
- package/src/commands/redact.ts +5 -2
- package/src/dotenv.ts +12 -1
- package/src/mask.ts +37 -6
package/dist/redact.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// @bun
|
|
3
3
|
|
|
4
4
|
// src/redact.ts
|
|
5
|
-
import
|
|
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,24 +454,20 @@ function printJson(value) {
|
|
|
434
454
|
|
|
435
455
|
// ../kit/src/help.ts
|
|
436
456
|
import process8 from "process";
|
|
437
|
-
var OPTIONAL =
|
|
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)) {
|
|
441
461
|
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
442
462
|
}
|
|
443
|
-
function helpText(usage, options, colors = paint(process8.stdout), { examples = [],
|
|
444
|
-
return [usageLine(usage, colors),
|
|
463
|
+
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
|
|
464
|
+
return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
445
465
|
`);
|
|
446
466
|
}
|
|
447
467
|
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
448
468
|
if (exits.length === 0)
|
|
449
469
|
return [];
|
|
450
|
-
|
|
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}`];
|
|
470
|
+
return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
|
|
455
471
|
}
|
|
456
472
|
function wantsHelpJson(env = process8.env) {
|
|
457
473
|
return env.KIT_HELP === "json";
|
|
@@ -477,29 +493,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
|
477
493
|
return [];
|
|
478
494
|
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
479
495
|
}
|
|
496
|
+
var MAX_INLINE_CHOICES = 24;
|
|
480
497
|
function optionRows(options, colors = paint(process8.stdout)) {
|
|
481
498
|
const rows = Object.entries(options).map(([name, option]) => {
|
|
482
499
|
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
483
|
-
const
|
|
500
|
+
const choices = option.choices?.join("|");
|
|
501
|
+
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
502
|
+
const named = inline ? `<${choices}>` : "<value>";
|
|
484
503
|
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
485
504
|
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
486
|
-
|
|
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 };
|
|
487
507
|
});
|
|
488
508
|
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
489
509
|
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
490
510
|
}
|
|
491
511
|
|
|
492
512
|
// ../kit/src/text.ts
|
|
493
|
-
var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
|
|
494
513
|
function distance(a, b) {
|
|
495
|
-
|
|
496
|
-
|
|
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()) {
|
|
497
519
|
const current = [i + 1];
|
|
498
|
-
for (const [j,
|
|
499
|
-
|
|
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;
|
|
500
527
|
previous = current;
|
|
501
528
|
}
|
|
502
|
-
return previous[
|
|
529
|
+
return previous[right.length] ?? 0;
|
|
503
530
|
}
|
|
504
531
|
function closest(name, names) {
|
|
505
532
|
const started = names.find((known) => known.startsWith(name));
|
|
@@ -739,21 +766,63 @@ function nearestOption(message, options, allowNegative) {
|
|
|
739
766
|
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
740
767
|
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
741
768
|
}
|
|
769
|
+
// ../kit/src/argv.ts
|
|
770
|
+
import { readFileSync as readFileSync3, realpathSync } from "fs";
|
|
771
|
+
import { resolve as resolve3 } from "path";
|
|
772
|
+
import process11 from "process";
|
|
773
|
+
function commandLine() {
|
|
774
|
+
try {
|
|
775
|
+
return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
|
|
776
|
+
} catch {
|
|
777
|
+
return;
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
function realPath(word) {
|
|
781
|
+
try {
|
|
782
|
+
return realpathSync(resolve3(word));
|
|
783
|
+
} catch {
|
|
784
|
+
return;
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), script = process11.argv[1]) {
|
|
788
|
+
const target = script === undefined ? undefined : realPath(script) ?? script;
|
|
789
|
+
const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
|
|
790
|
+
const after = at === -1 ? [] : cmdline.slice(at + 1);
|
|
791
|
+
return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
|
|
792
|
+
}
|
|
742
793
|
// ../kit/src/progress.ts
|
|
743
794
|
var ESC = String.fromCharCode(27);
|
|
744
795
|
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
745
796
|
var RESET_STYLE = `${ESC}[0m`;
|
|
746
797
|
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
747
798
|
// ../kit/src/cli.ts
|
|
748
|
-
import { readFileSync as
|
|
799
|
+
import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
|
|
749
800
|
import { dirname as dirname3, join as join5 } from "path";
|
|
801
|
+
import process14 from "process";
|
|
802
|
+
|
|
803
|
+
// ../kit/src/notify.ts
|
|
750
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
|
+
}
|
|
751
820
|
|
|
752
821
|
// ../kit/src/usage.ts
|
|
753
822
|
import { appendFileSync, mkdirSync } from "fs";
|
|
754
823
|
import { homedir as homedir3 } from "os";
|
|
755
824
|
import { dirname as dirname2, isAbsolute, join as join4 } from "path";
|
|
756
|
-
import
|
|
825
|
+
import process13 from "process";
|
|
757
826
|
|
|
758
827
|
// ../kit/src/logs.ts
|
|
759
828
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
@@ -767,14 +836,14 @@ var usageError;
|
|
|
767
836
|
function noteUsageError(message) {
|
|
768
837
|
usageError = message;
|
|
769
838
|
}
|
|
770
|
-
function stateHome(env =
|
|
839
|
+
function stateHome(env = process13.env) {
|
|
771
840
|
const dir = env.XDG_STATE_HOME;
|
|
772
841
|
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
773
842
|
}
|
|
774
|
-
function usagePath(env =
|
|
843
|
+
function usagePath(env = process13.env) {
|
|
775
844
|
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
776
845
|
}
|
|
777
|
-
function usageRecorded(env =
|
|
846
|
+
function usageRecorded(env = process13.env) {
|
|
778
847
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
779
848
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
780
849
|
}
|
|
@@ -788,7 +857,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
788
857
|
usageError = undefined;
|
|
789
858
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
790
859
|
}
|
|
791
|
-
function recordUsage(entry, env =
|
|
860
|
+
function recordUsage(entry, env = process13.env) {
|
|
792
861
|
if (!usageRecorded(env))
|
|
793
862
|
return;
|
|
794
863
|
try {
|
|
@@ -865,7 +934,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
|
|
|
865
934
|
header(colors, summary),
|
|
866
935
|
"",
|
|
867
936
|
usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
|
|
868
|
-
...replacesRows(replaces, colors),
|
|
869
937
|
"",
|
|
870
938
|
...await commandRows(commands, colors),
|
|
871
939
|
...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
|
|
@@ -879,8 +947,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
|
|
|
879
947
|
`);
|
|
880
948
|
}
|
|
881
949
|
function printError(prefix, message, hint, cause) {
|
|
882
|
-
const colors = paint(
|
|
883
|
-
const styled = takesControlCodes(
|
|
950
|
+
const colors = paint(process14.stderr);
|
|
951
|
+
const styled = takesControlCodes(process14.stderr);
|
|
884
952
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
885
953
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
886
954
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -923,11 +991,11 @@ async function dispatch(level, typed, { version, redact }) {
|
|
|
923
991
|
}
|
|
924
992
|
}
|
|
925
993
|
if (name === undefined && level.path.length > 1) {
|
|
926
|
-
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
994
|
+
console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
|
|
927
995
|
return 2;
|
|
928
996
|
}
|
|
929
997
|
if (name === undefined || name === "help" || name === "--help" || name === "-h") {
|
|
930
|
-
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]),
|
|
998
|
+
console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
|
|
931
999
|
return 0;
|
|
932
1000
|
}
|
|
933
1001
|
if (level.path.length === 1 && (name === "--version" || name === "-v")) {
|
|
@@ -983,24 +1051,24 @@ function candidateLine(candidate) {
|
|
|
983
1051
|
}
|
|
984
1052
|
function positionalBeingTyped(before, { options, positionals }) {
|
|
985
1053
|
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
986
|
-
|
|
1054
|
+
const typed = [];
|
|
987
1055
|
let at = 0;
|
|
988
1056
|
while (at < before.length) {
|
|
989
1057
|
const word = before[at];
|
|
990
1058
|
if (word === "--") {
|
|
991
|
-
|
|
1059
|
+
typed.push(...before.slice(at + 1));
|
|
992
1060
|
break;
|
|
993
1061
|
}
|
|
994
1062
|
if (!word.startsWith("-"))
|
|
995
|
-
|
|
1063
|
+
typed.push(word);
|
|
996
1064
|
else if (takesValue(word))
|
|
997
1065
|
at++;
|
|
998
1066
|
at++;
|
|
999
1067
|
}
|
|
1000
1068
|
const last = positionals.at(-1);
|
|
1001
|
-
if (
|
|
1002
|
-
return positionals[
|
|
1003
|
-
return last?.replace("]", "").endsWith("...") === true ? last : undefined;
|
|
1069
|
+
if (typed.length < positionals.length)
|
|
1070
|
+
return { name: positionals[typed.length], typed };
|
|
1071
|
+
return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
|
|
1004
1072
|
}
|
|
1005
1073
|
async function leafCandidates(run, words) {
|
|
1006
1074
|
const completing = await completingOf(run);
|
|
@@ -1008,12 +1076,12 @@ async function leafCandidates(run, words) {
|
|
|
1008
1076
|
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
1009
1077
|
const flag = words.at(-2);
|
|
1010
1078
|
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
1079
|
+
const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
|
|
1011
1080
|
if (option?.type === "string") {
|
|
1012
|
-
const values = option.choices === undefined ? await option.candidates?.() : option.choices;
|
|
1081
|
+
const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
|
|
1013
1082
|
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1014
1083
|
}
|
|
1015
|
-
const
|
|
1016
|
-
const values = name === undefined ? undefined : await completing.candidates[name]?.();
|
|
1084
|
+
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
1017
1085
|
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1018
1086
|
}
|
|
1019
1087
|
async function candidates(scope, defaultCommand, words, before = []) {
|
|
@@ -1044,9 +1112,13 @@ async function printCandidates(found) {
|
|
|
1044
1112
|
return 0;
|
|
1045
1113
|
}
|
|
1046
1114
|
function packageVersion(entry = Bun.main) {
|
|
1047
|
-
|
|
1115
|
+
let resolved = entry;
|
|
1116
|
+
try {
|
|
1117
|
+
resolved = realpathSync2(entry);
|
|
1118
|
+
} catch {}
|
|
1119
|
+
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
1048
1120
|
try {
|
|
1049
|
-
const { version } = JSON.parse(
|
|
1121
|
+
const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
|
|
1050
1122
|
if (typeof version === "string")
|
|
1051
1123
|
return version;
|
|
1052
1124
|
} catch {}
|
|
@@ -1054,14 +1126,17 @@ function packageVersion(entry = Bun.main) {
|
|
|
1054
1126
|
return "0.0.0";
|
|
1055
1127
|
}
|
|
1056
1128
|
}
|
|
1057
|
-
async function runCli(cli, argv =
|
|
1129
|
+
async function runCli(cli, argv = scriptArgs()) {
|
|
1058
1130
|
const version = cli.version ?? packageVersion();
|
|
1059
1131
|
if (argv[0] === COMPLETE)
|
|
1060
1132
|
return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
|
|
1133
|
+
const started = performance.now();
|
|
1061
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);
|
|
1062
1137
|
if (cli.usage !== false) {
|
|
1063
1138
|
try {
|
|
1064
|
-
recordUsage(usageEntry(cli.name,
|
|
1139
|
+
recordUsage(usageEntry(cli.name, command, argv, code));
|
|
1065
1140
|
} catch {}
|
|
1066
1141
|
}
|
|
1067
1142
|
return code;
|
|
@@ -1081,7 +1156,7 @@ function commandPath(scope, argv) {
|
|
|
1081
1156
|
}
|
|
1082
1157
|
return path.length === 0 ? undefined : path.join(" ");
|
|
1083
1158
|
}
|
|
1084
|
-
async function runMain({ name, version, run, redact, usage }, argv =
|
|
1159
|
+
async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
|
|
1085
1160
|
if (argv[0] === COMPLETE)
|
|
1086
1161
|
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
1087
1162
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
@@ -1089,11 +1164,13 @@ async function runMain({ name, version, run, redact, usage }, argv = process12.a
|
|
|
1089
1164
|
return 0;
|
|
1090
1165
|
}
|
|
1091
1166
|
let code;
|
|
1167
|
+
const started = performance.now();
|
|
1092
1168
|
try {
|
|
1093
1169
|
code = await run(argv);
|
|
1094
1170
|
} catch (error) {
|
|
1095
1171
|
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
1096
1172
|
}
|
|
1173
|
+
notifyEnd(name, code, performance.now() - started);
|
|
1097
1174
|
if (usage !== false) {
|
|
1098
1175
|
try {
|
|
1099
1176
|
recordUsage(usageEntry(name, undefined, argv, code));
|
|
@@ -1111,12 +1188,18 @@ async function compose(args, { flags = [], ...options } = {}) {
|
|
|
1111
1188
|
return captureOutput(["docker", "compose", ...flags, ...args], options);
|
|
1112
1189
|
}
|
|
1113
1190
|
// ../kit/src/folders.ts
|
|
1191
|
+
import { homedir as homedir4 } from "os";
|
|
1192
|
+
import { join as join6 } from "path";
|
|
1193
|
+
import process15 from "process";
|
|
1114
1194
|
var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
|
|
1115
1195
|
function ignoredFolders(extra = [], where = {}) {
|
|
1116
1196
|
const configured = readUserConfig("config", where).ignore;
|
|
1117
1197
|
const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
|
|
1118
1198
|
return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
|
|
1119
1199
|
}
|
|
1200
|
+
function cacheFolder({ home = homedir4(), env = process15.env } = {}) {
|
|
1201
|
+
return env.XDG_CACHE_HOME ?? join6(home, ".cache");
|
|
1202
|
+
}
|
|
1120
1203
|
// ../kit/src/secrets.ts
|
|
1121
1204
|
var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
|
|
1122
1205
|
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
@@ -1129,11 +1212,11 @@ var {Glob } = globalThis.Bun;
|
|
|
1129
1212
|
var SESSION_FILES = new Glob("*.json");
|
|
1130
1213
|
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
1131
1214
|
// src/commands/redact.ts
|
|
1132
|
-
import
|
|
1215
|
+
import process17 from "process";
|
|
1133
1216
|
|
|
1134
1217
|
// src/files.ts
|
|
1135
1218
|
import { chmod, chown, readdir, realpath, rename, rm, stat, writeFile } from "fs/promises";
|
|
1136
|
-
import { basename, dirname as dirname4, join as
|
|
1219
|
+
import { basename, dirname as dirname4, join as join7 } from "path";
|
|
1137
1220
|
|
|
1138
1221
|
// src/dotenv.ts
|
|
1139
1222
|
var ASSIGNMENT = /^\s*(?:export\s+)?([A-Z_][\w.-]*)\s*=(.*)$/i;
|
|
@@ -1191,7 +1274,8 @@ function parseDotenv(text) {
|
|
|
1191
1274
|
let body = start.slice(1);
|
|
1192
1275
|
let raw = line;
|
|
1193
1276
|
let end = closingQuote(body, quote);
|
|
1194
|
-
|
|
1277
|
+
const first = index;
|
|
1278
|
+
while (end === -1 && index + 1 < physical.length && !ASSIGNMENT.test(physical[index + 1] ?? "")) {
|
|
1195
1279
|
index++;
|
|
1196
1280
|
body += `
|
|
1197
1281
|
${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
|
|
@@ -1199,6 +1283,11 @@ ${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
|
|
|
1199
1283
|
${physical[index] ?? ""}`;
|
|
1200
1284
|
end = closingQuote(body, quote);
|
|
1201
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
|
+
}
|
|
1202
1291
|
const inner = end === -1 ? body : body.slice(0, end);
|
|
1203
1292
|
lines.push({ raw, key, value: quote === '"' ? unescapeDouble(inner) : unescapeDollar(inner) });
|
|
1204
1293
|
}
|
|
@@ -1264,9 +1353,30 @@ var ESCAPE2 = /[.*+?^${}()|[\]\\]/g;
|
|
|
1264
1353
|
function isPlaceholder(value) {
|
|
1265
1354
|
return PLACEHOLDER.test(value) || PLAIN_VALUE.test(value);
|
|
1266
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
|
+
}
|
|
1267
1371
|
var TOKEN_FORMATS = [
|
|
1268
1372
|
{ kind: "GitHub token", pattern: /\b(?:gh[pousr]_|github_pat_)\w{20,}/dg },
|
|
1269
|
-
{ kind: "GitLab token", pattern: /\
|
|
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 },
|
|
1270
1380
|
{ kind: "API key", pattern: /\bsk-[\w-]{20,}/dg },
|
|
1271
1381
|
{ kind: "Slack token", pattern: /\bx(?:ox[abprs]|app)-[\w-]{10,}/dg },
|
|
1272
1382
|
{ kind: "JWT", pattern: /\beyJ[\w-]+\.[\w-]+\.[\w-]+/dg },
|
|
@@ -1277,8 +1387,10 @@ var TOKEN_FORMATS = [
|
|
|
1277
1387
|
{ kind: "SendGrid key", pattern: /\bSG\.[\w-]{16,}\.[\w-]{16,}/dg },
|
|
1278
1388
|
{ kind: "Authorization header", pattern: /\bAuthorization["']?\s*[:=]\s*["']?(?:Bearer|Basic|Token|Digest)\s+([^\s"',;]{8,})/dgi, skip: isPlaceholder },
|
|
1279
1389
|
{ kind: "Bearer token", pattern: /\bBearer\s+((?=[\w.~+/=-]*\d)[\w.~+/=-]{20,})/dg },
|
|
1280
|
-
{ kind: "password", pattern:
|
|
1281
|
-
{ kind: "password", pattern:
|
|
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 }
|
|
1282
1394
|
];
|
|
1283
1395
|
var PEM_BEGIN = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
|
|
1284
1396
|
var PEM_END = /-----END [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
|
|
@@ -1383,7 +1495,7 @@ function findSecrets(line, known) {
|
|
|
1383
1495
|
if (start === undefined || end === undefined)
|
|
1384
1496
|
continue;
|
|
1385
1497
|
const value = line.slice(start, end);
|
|
1386
|
-
if (!skip?.(value))
|
|
1498
|
+
if (!skip?.(value, line.slice(0, start)))
|
|
1387
1499
|
found.push({ start, end, kind, mask: hint(value) });
|
|
1388
1500
|
}
|
|
1389
1501
|
}
|
|
@@ -1445,7 +1557,7 @@ async function envFiles(folder = process.cwd()) {
|
|
|
1445
1557
|
const found = await readdir(folder, { withFileTypes: true });
|
|
1446
1558
|
const names = [];
|
|
1447
1559
|
for (const entry of found) {
|
|
1448
|
-
if (ENV_FILE.test(entry.name) && await isFileEntry(entry,
|
|
1560
|
+
if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join7(folder, entry.name)))
|
|
1449
1561
|
names.push(entry.name);
|
|
1450
1562
|
}
|
|
1451
1563
|
return names.sort();
|
|
@@ -1469,7 +1581,7 @@ async function writeAtomic(path, text) {
|
|
|
1469
1581
|
if (error.code !== "ENOENT")
|
|
1470
1582
|
throw error;
|
|
1471
1583
|
}
|
|
1472
|
-
const temp =
|
|
1584
|
+
const temp = join7(dirname4(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
|
|
1473
1585
|
try {
|
|
1474
1586
|
await writeFile(temp, text, { mode: 384, flag: "wx" });
|
|
1475
1587
|
if (owner !== undefined)
|
|
@@ -1525,7 +1637,7 @@ async function acquire(path) {
|
|
|
1525
1637
|
try {
|
|
1526
1638
|
real = await realpath(path);
|
|
1527
1639
|
} catch {}
|
|
1528
|
-
const lock =
|
|
1640
|
+
const lock = join7(dirname4(real), `.${basename(real)}.lock`);
|
|
1529
1641
|
const deadline = Date.now() + LOCK_WAIT_MS;
|
|
1530
1642
|
while (true) {
|
|
1531
1643
|
try {
|
|
@@ -1560,7 +1672,7 @@ async function envFilesBelow(folder, depth = 0) {
|
|
|
1560
1672
|
return found;
|
|
1561
1673
|
}
|
|
1562
1674
|
for (const entry of children) {
|
|
1563
|
-
const path =
|
|
1675
|
+
const path = join7(folder, entry.name);
|
|
1564
1676
|
if (entry.isDirectory() && depth < KNOWN_DEPTH && !SKIPPED.has(entry.name))
|
|
1565
1677
|
found.push(...await envFilesBelow(path, depth + 1));
|
|
1566
1678
|
else if (ENV_FILE.test(entry.name) && await isFileEntry(entry, path))
|
|
@@ -1697,15 +1809,14 @@ function check(text, known) {
|
|
|
1697
1809
|
var usage2 = `redact [--check]
|
|
1698
1810
|
|
|
1699
1811
|
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.`;
|
|
1812
|
+
--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\`.`;
|
|
1813
|
+
var EXITS = [[0, "it copied the input or found no secret"], [1, "--check finds one"], [2, "a usage error"]];
|
|
1703
1814
|
var options = {
|
|
1704
1815
|
check: { type: "boolean", description: "list where secrets are instead of masking them, exit 1 when found" },
|
|
1705
1816
|
"no-env": { type: "boolean", description: "do not search for the values of the .env* files" }
|
|
1706
1817
|
};
|
|
1707
1818
|
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"]] });
|
|
1819
|
+
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
1820
|
const known = parsed.values["no-env"] === true ? undefined : await loadKnown();
|
|
1710
1821
|
if (parsed.values.check === true) {
|
|
1711
1822
|
const findings = check(await readInput("-"), known);
|
|
@@ -1716,10 +1827,10 @@ async function redact(args) {
|
|
|
1716
1827
|
const redactor = new Redactor(known);
|
|
1717
1828
|
const decoder = new TextDecoder;
|
|
1718
1829
|
for await (const chunk of Bun.stdin.stream())
|
|
1719
|
-
|
|
1720
|
-
|
|
1830
|
+
process17.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
|
|
1831
|
+
process17.stdout.write(redactor.push(decoder.decode()) + redactor.end());
|
|
1721
1832
|
return 0;
|
|
1722
1833
|
}
|
|
1723
1834
|
|
|
1724
1835
|
// src/redact.ts
|
|
1725
|
-
|
|
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.
|
|
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.
|
|
40
|
+
"@kaynooo/cli-kit": "0.40.0"
|
|
41
41
|
}
|
|
42
42
|
}
|
package/src/commands/audit.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
|
package/src/commands/compare.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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'
|