@kaynooo/cli-env 0.14.0 → 0.15.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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # ev and redact
2
2
 
3
- Two CLIs that keep secrets out of a Claude Code transcript: `ev` lists and edits `.env` files with every secret masked, and `redact` masks secrets in any piped output.
3
+ `ev` keeps secrets out of a Claude Code transcript: it lists and edits `.env` files with every secret masked, and `ev redact` masks secrets in any piped output.
4
4
 
5
5
  ```sh
6
6
  bun install -g @kaynooo/cli-env
@@ -31,20 +31,20 @@ A value is masked when its key is named like a secret (`TOKEN`, `SECRET`, `PASSW
31
31
 
32
32
  Files are parsed and written back preserving comments, order, `export KEY=` prefixes, quoting and multiline values; only the lines a command touches change.
33
33
 
34
- ## redact
34
+ ## ev redact
35
35
 
36
36
  ```sh
37
- some-command 2>&1 | redact
38
- git diff --cached | redact --check
37
+ some-command 2>&1 | ev redact
38
+ git diff --cached | ev redact --check
39
39
  ```
40
40
 
41
- `redact` copies stdin to stdout line by line, masking:
41
+ `ev redact` copies stdin to stdout line by line, masking:
42
42
 
43
43
  - known token formats: `ghp_`, `github_pat_`, `glpat-`, `sk-`, `xox?-`, JWTs and the body of PEM private key blocks
44
44
  - the password and the tokens of any URL (webhook and push URLs, opaque path segments, token query parameters)
45
45
  - the values of secret-looking keys in the `.env*` files of the current folder and the folders below it (whole words only, from 4 characters, also in their percent-encoded and JSON-escaped forms), `--no-env` skips them
46
46
 
47
- `redact --check` prints nothing of the input: it lists `<file>:<line>: <kind>` for each secret found and exits 1. On a diff it reads the added lines only and names the new file's line numbers.
47
+ `ev redact --check` prints nothing of the input: it lists `<file>:<line>: <kind>` for each secret found and exits 1. On a diff it reads the added lines only and names the new file's line numbers.
48
48
 
49
49
  ## The parser and the guard
50
50
 
package/dist/ev.js CHANGED
@@ -594,7 +594,7 @@ class Completing {
594
594
  }
595
595
  var completion = { active: false };
596
596
  var OUTPUT_OPTIONS = {
597
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
597
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
598
598
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
599
599
  };
600
600
  function applyOutput(color, plain, env = process10.env) {
@@ -800,6 +800,66 @@ import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs
800
800
  import { dirname as dirname3, join as join5 } from "path";
801
801
  import process14 from "process";
802
802
 
803
+ // ../kit/src/completions.ts
804
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
805
+ var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
806
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
807
+ set -l current (commandline -ct)
808
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
809
+ if test "$line" = __files__
810
+ __fish_complete_path $current
811
+ else
812
+ echo $line
813
+ end
814
+ end
815
+ end`;
816
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
817
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
818
+ local -a lines
819
+ COMPREPLY=()
820
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
821
+ for line in "\${lines[@]}"; do
822
+ if [[ $line == __files__ ]]; then
823
+ COMPREPLY+=($(compgen -f -- "$cur"))
824
+ else
825
+ words+="\${line%%$'\\t'*}"$'\\n'
826
+ fi
827
+ done
828
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
829
+ }`;
830
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
831
+ local line
832
+ local -a described plain
833
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
834
+ if [[ $line == __files__ ]]; then
835
+ _files
836
+ elif [[ $line == *$'\\t'* ]]; then
837
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
838
+ else
839
+ plain+=("$line")
840
+ fi
841
+ done
842
+ (( \${#described} )) && _describe -V value described
843
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
844
+ return 0
845
+ }`;
846
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
847
+ if (shell === "fish")
848
+ return `${header}
849
+ ${FISH_FUNCTION}
850
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
851
+ `).join("")}`;
852
+ if (shell === "bash")
853
+ return `${header}
854
+ ${BASH_FUNCTION}
855
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
856
+ `;
857
+ return `${header}
858
+ ${ZSH_FUNCTION}
859
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
860
+ `;
861
+ }
862
+
803
863
  // ../kit/src/notify.ts
804
864
  import process12 from "process";
805
865
  var NOTIFY_AFTER_MS = 1e4;
@@ -873,7 +933,11 @@ var LEVEL_OPTIONS = {
873
933
  ...OUTPUT_OPTIONS,
874
934
  help: { type: "boolean", short: "h", description: "show this help" }
875
935
  };
876
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
936
+ var TOP_OPTIONS = {
937
+ ...LEVEL_OPTIONS,
938
+ version: { type: "boolean", short: "v", description: "print the version" },
939
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
940
+ };
877
941
  async function commandRows(all, colors) {
878
942
  const commands = shown(all);
879
943
  const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
@@ -1106,6 +1170,19 @@ async function candidates(scope, defaultCommand, words, before = []) {
1106
1170
  }
1107
1171
  return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1108
1172
  }
1173
+ var COMPLETIONS = "--completions";
1174
+ function flagValue([flag = "", ...rest]) {
1175
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1176
+ }
1177
+ function printCompletionScript(name, args) {
1178
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1179
+ if (shell === undefined || args.length !== 1) {
1180
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1181
+ return 2;
1182
+ }
1183
+ console.log(completionScript(shell, [name]).trimEnd());
1184
+ return 0;
1185
+ }
1109
1186
  async function printCandidates(found) {
1110
1187
  for (const line of await found)
1111
1188
  console.log(line);
@@ -1130,6 +1207,8 @@ async function runCli(cli, argv = scriptArgs()) {
1130
1207
  const version = cli.version ?? packageVersion();
1131
1208
  if (argv[0] === COMPLETE)
1132
1209
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1210
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1211
+ return printCompletionScript(cli.name, flagValue(argv));
1133
1212
  const started = performance.now();
1134
1213
  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
1214
  const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
@@ -1156,28 +1235,6 @@ function commandPath(scope, argv) {
1156
1235
  }
1157
1236
  return path.length === 0 ? undefined : path.join(" ");
1158
1237
  }
1159
- async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1160
- if (argv[0] === COMPLETE)
1161
- return printCandidates(leafCandidates(run, argv.slice(1)));
1162
- if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1163
- console.log(version ?? packageVersion());
1164
- return 0;
1165
- }
1166
- let code;
1167
- const started = performance.now();
1168
- try {
1169
- code = await run(argv);
1170
- } catch (error) {
1171
- code = reportThrown(name, error, redact, wantsJson(argv));
1172
- }
1173
- notifyEnd(name, code, performance.now() - started);
1174
- if (usage !== false) {
1175
- try {
1176
- recordUsage(usageEntry(name, undefined, argv, code));
1177
- } catch {}
1178
- }
1179
- return code;
1180
- }
1181
1238
  // ../kit/src/compose.ts
1182
1239
  async function captureOutput(argv, { cwd, env } = {}) {
1183
1240
  const run = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, env: { ...process.env, ...env }, stdin: "ignore", stdout: "pipe", stderr: "pipe" });
@@ -3249,17 +3306,17 @@ function check(text, known) {
3249
3306
  }
3250
3307
 
3251
3308
  // src/commands/redact.ts
3252
- var usage4 = `redact [--check]
3309
+ var usage4 = `ev redact [--check]
3253
3310
 
3254
3311
  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.
3255
- --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\`.`;
3312
+ --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 | ev redact --check\`.`;
3256
3313
  var EXITS3 = [[0, "it copied the input or found no secret"], [1, "--check finds one"], [2, "a usage error"]];
3257
3314
  var options3 = {
3258
3315
  check: { type: "boolean", description: "list where secrets are instead of masking them, exit 1 when found" },
3259
3316
  "no-env": { type: "boolean", description: "do not search for the values of the .env* files" }
3260
3317
  };
3261
3318
  async function redact(args) {
3262
- const parsed = parse(args, usage4, options3, { exits: EXITS3, 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"]] });
3319
+ const parsed = parse(args, usage4, options3, { exits: EXITS3, replaces: "printing a command's secrets into a log or a transcript", examples: [["docker compose config | ev redact", "the resolved compose file, secrets masked"], ["git diff --cached | ev redact --check", "refuse a commit carrying a secret"]] });
3263
3320
  const known = parsed.values["no-env"] === true ? undefined : await loadKnown();
3264
3321
  if (parsed.values.check === true) {
3265
3322
  const findings = check(await readInput("-"), known);
package/package.json CHANGED
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-env",
3
3
  "type": "module",
4
- "version": "0.14.0",
5
- "description": "ev lists and edits .env files with secrets masked, redact masks secrets in any piped output.",
4
+ "version": "0.15.0",
5
+ "description": "ev lists and edits .env files with secrets masked, and ev redact masks secrets in any piped output.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
8
- "homepage": "https://git.kaynooo.fr/kaynooo/cli/src/branch/main/packages/env#readme",
8
+ "homepage": "https://github.com/Kayno0o/cli/tree/main/packages/env#readme",
9
9
  "repository": {
10
10
  "type": "git",
11
- "url": "git+https://git.kaynooo.fr/kaynooo/cli.git",
11
+ "url": "git+https://github.com/Kayno0o/cli.git",
12
12
  "directory": "packages/env"
13
13
  },
14
- "bugs": "https://git.kaynooo.fr/kaynooo/cli/issues",
14
+ "bugs": "https://github.com/Kayno0o/cli/issues",
15
15
  "keywords": ["env", "dotenv", "secrets", "redact", "mask"],
16
16
  "exports": {
17
17
  "./dotenv": "./src/dotenv.ts",
@@ -21,8 +21,7 @@
21
21
  "./redactor": "./src/redactor.ts"
22
22
  },
23
23
  "bin": {
24
- "ev": "./dist/ev.js",
25
- "redact": "./dist/redact.js"
24
+ "ev": "./dist/ev.js"
26
25
  },
27
26
  "files": ["dist", "src"],
28
27
  "engines": {
@@ -32,11 +31,10 @@
32
31
  "registry": "https://git.kaynooo.fr/api/packages/kaynooo/npm/"
33
32
  },
34
33
  "scripts": {
35
- "build": "$npm_execpath build src/ev.ts src/redact.ts --target bun --outdir dist",
36
- "ev": "$npm_execpath src/ev.ts",
37
- "redact": "$npm_execpath src/redact.ts"
34
+ "build": "$npm_execpath build src/ev.ts --target bun --outdir dist",
35
+ "ev": "$npm_execpath src/ev.ts"
38
36
  },
39
- "devDependencies": {
40
- "@kaynooo/cli-kit": "0.40.0"
37
+ "dependencies": {
38
+ "@kaynooo/cli-kit": "0.41.0"
41
39
  }
42
40
  }
@@ -4,10 +4,10 @@ import { parse, readInput } from '@kaynooo/cli-kit'
4
4
  import { loadKnown } from '../files'
5
5
  import { check, Redactor } from '../redactor'
6
6
 
7
- const usage = `redact [--check]
7
+ const usage = `ev redact [--check]
8
8
 
9
9
  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.
10
- --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\`.`
10
+ --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 | ev redact --check\`.`
11
11
 
12
12
  const EXITS: ExitRow[] = [[0, 'it copied the input or found no secret'], [1, '--check finds one'], [2, 'a usage error']]
13
13
 
@@ -17,7 +17,7 @@ const options = {
17
17
  } as const
18
18
 
19
19
  export async function redact(args: string[]): Promise<number> {
20
- const parsed = parse(args, usage, 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']] })
20
+ const parsed = parse(args, usage, options, { exits: EXITS, replaces: 'printing a command\'s secrets into a log or a transcript', examples: [['docker compose config | ev redact', 'the resolved compose file, secrets masked'], ['git diff --cached | ev redact --check', 'refuse a commit carrying a secret']] })
21
21
 
22
22
  const known = parsed.values['no-env'] === true ? undefined : await loadKnown()
23
23
 
@@ -16,7 +16,7 @@ const CODE_OPTIONS = new Set(['-e', '-c', '-p', '-E', '-pe', '-r', '--eval', '--
16
16
  const CAN_REACH_FILES = /read|write|open|exec|spawn|system|popen|import|require|eval|load|fetch|glob|stream|source|getline|constructor|file(?!s\b)|\bcat\b|\b(?:Bun|Deno|fs|os|io|sh|bash|process|globalThis|window|Function|qx)\b|\$\s*[`({]|`/i
17
17
  const DECLARERS = new Set(['export', 'declare', 'local', 'readonly', 'typeset'])
18
18
  // Programs that name an env file without reading it: listing, testing, or loading it into a process that prints nothing.
19
- const HARMLESS = new Set(['ev', 'redact', 'ls', 'stat', 'test', '[', '[[', 'touch'])
19
+ const HARMLESS = new Set(['ev', 'ls', 'stat', 'test', '[', '[[', 'touch'])
20
20
  const GIT_HARMLESS = new Set(['check-ignore', 'ls-files', 'status'])
21
21
 
22
22
  // The values each variable is given in a command, by assignment, `export` or a `for` list.
@@ -4,7 +4,7 @@ import { namesEnv } from './guard-names'
4
4
  import { searchesEnvNames } from './guard-search'
5
5
 
6
6
  // Programs an `xargs` can run on a listing of names without printing a line of the files.
7
- const XARGS_SAFE = new Set(['ls', 'stat', 'wc', 'test', '[', 'touch', 'echo', 'printf', 'basename', 'dirname', 'ev', 'redact', ''])
7
+ const XARGS_SAFE = new Set(['ls', 'stat', 'wc', 'test', '[', 'touch', 'echo', 'printf', 'basename', 'dirname', 'ev', ''])
8
8
  // GNU parallel's options taking their value as the next word, before the command it runs.
9
9
  const PARALLEL_VALUE_OPTIONS = new Set(['-j', '--jobs', '-P', '--max-procs', '-S', '--sshlogin', '-C', '--colsep', '-n', '--max-args', '-N', '-d', '--delimiter', '-E', '-I', '--timeout', '--delay', '--joblog', '--results', '--tmpdir', '-a', '--arg-file', '--halt', '--retries', '--tag-string'])
10
10
  const IDENTIFIER = /^[A-Z_]\w*$/i
package/src/guard.ts CHANGED
@@ -8,7 +8,7 @@ import { searchesEnv } from './guard-search'
8
8
  // Code printing the whole environment Bun filled from the .env files.
9
9
  const ENV_DUMP = /(?:console\.\w+|JSON\.stringify|Object\.(?:entries|keys|values)|print)\(\s*process\.env\s*[,)]/
10
10
 
11
- export const USE_EV = '.env files hold secrets that must never reach the transcript, so they are not read, edited or printed directly. Use `ev` instead: `ev list`, `ev get KEY` (masked), `ev grep <regex>` for the keys matching it, `ev show <rev>:<file>` for one at a git revision, `printf %s "$value" | ev set KEY [file]` (`--empty` for an empty value), `ev unset KEY`, `ev cp KEY --from .env --to .env.local`, `ev mv KEY --from .env --to .env.local`, `ev diff a b`, `ev missing`; and pipe output that may carry a secret through `redact`, as `docker compose exec <svc> printenv | redact` or `docker compose config | redact`. If `ev` is missing: `bun install -g @kaynooo/cli-env`.'
11
+ export const USE_EV = '.env files hold secrets that must never reach the transcript, so they are not read, edited or printed directly. Use `ev` instead: `ev list`, `ev get KEY` (masked), `ev grep <regex>` for the keys matching it, `ev show <rev>:<file>` for one at a git revision, `printf %s "$value" | ev set KEY [file]` (`--empty` for an empty value), `ev unset KEY`, `ev cp KEY --from .env --to .env.local`, `ev mv KEY --from .env --to .env.local`, `ev diff a b`, `ev missing`; and pipe output that may carry a secret through `ev redact`, as `docker compose exec <svc> printenv | ev redact` or `docker compose config | ev redact`. If `ev` is missing: `bun install -g @kaynooo/cli-env`.'
12
12
 
13
13
  export const USE_EV_SEARCH = 'To search them, `ev grep <regex>` prints the matching keys, masked. `grep -l`, `-L` and `-c` (file names and counts) are allowed, and a tree-wide search can run as `rg <regex>`, which skips gitignored files, or `grep -r --exclude=\'.env*\' <regex> .`.'
14
14
 
@@ -32,9 +32,11 @@ export function touchingPieces(command: string, options: { hasTrackedEnv?: boole
32
32
  if (!isDump)
33
33
  return false
34
34
 
35
- // a redact further down its pipeline masks what the command prints
35
+ // an `ev redact` further down its pipeline masks what the command prints
36
36
  for (let at = index; pieces[at]?.separator === '|'; at++) {
37
- if (parseCommand(pieces[at + 1]?.command ?? '').program === 'redact')
37
+ const next = parseCommand(pieces[at + 1]?.command ?? '')
38
+
39
+ if (next.program === 'ev' && next.args[0] === 'redact')
38
40
  return false
39
41
  }
40
42
 
@@ -42,7 +44,7 @@ export function touchingPieces(command: string, options: { hasTrackedEnv?: boole
42
44
  })
43
45
  }
44
46
 
45
- // True when the command would read, write or print an env file or the whole environment; an env file named only inside a quoted message or a heredoc body is text, and a container's environment piped through `redact` is masked.
47
+ // True when the command would read, write or print an env file or the whole environment; an env file named only inside a quoted message or a heredoc body is text, and a container's environment piped through `ev redact` is masked.
46
48
  export function touchesEnv(command: string, options: { hasTrackedEnv?: boolean } = {}): boolean {
47
49
  return touchingPieces(command, options).length > 0
48
50
  }