vvauth 2.6.0 → 2.6.2

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/cmd/vauth/main.go CHANGED
@@ -19,14 +19,13 @@ const usage = `Usage: vauth <command> [--flag[=value]] [--ir://json]
19
19
  Commands:
20
20
  env [--source] [--renew] Resolve the .vauthrc environment (JSON with --ir://json)
21
21
  login [--source] [--renew] Authenticate; --source exports VAULT_TOKEN
22
- connect [--renew] Authenticate and print the token
23
- run <command> [args...] Run a command with the resolved environment
24
22
  dotenv Print the environment as K=v lines
25
23
  show Print the identity profile and .vauth_database
26
24
  set <key> <value> Store a key in the .vauth_database
27
25
  unset <key> Remove a key from the .vauth_database
28
26
  install Install the venv shell function in ~/.bashrc
29
27
  version Print the build version
28
+ gitlab Export CI_PROJECT_* from origin without login
30
29
  `
31
30
 
32
31
  // version is set by the release build (-ldflags "-X main.version=v1.2.3");
@@ -97,10 +96,13 @@ func main() {
97
96
  }
98
97
 
99
98
  func run(argv []string) error {
100
- if len(argv) > 0 && argv[0] == "run" {
101
- return runCommand(argv[1:])
102
- }
103
99
  args, dict := parseArgs(argv)
100
+ if len(args) > 1 && args[0] == "env" && args[1] == "gitlab" {
101
+ args = []string{"gitlab"}
102
+ }
103
+ if truthy(dict["gitlab"], dict["gitlab"] != "") {
104
+ args = []string{"gitlab"}
105
+ }
104
106
  if _, ok := dict["version"]; ok && len(args) == 0 {
105
107
  args = []string{"version"}
106
108
  }
@@ -115,6 +117,9 @@ func run(argv []string) error {
115
117
  return nil
116
118
  }
117
119
 
120
+ if command == "gitlab" {
121
+ return (&vvauth.Vauth{}).Gitlab()
122
+ }
118
123
  vvauth.Version = buildVersion()
119
124
  v, err := vvauth.New()
120
125
  if err != nil {
@@ -174,26 +179,6 @@ func run(argv []string) error {
174
179
  return fmt.Errorf("Invalid command key '%s'", command)
175
180
  }
176
181
 
177
- func runCommand(argv []string) error {
178
- if len(argv) > 0 && argv[0] == "--" {
179
- argv = argv[1:]
180
- }
181
- if len(argv) == 0 {
182
- return fmt.Errorf("run: missing command")
183
- }
184
- vvauth.Version = buildVersion()
185
- v, err := vvauth.New()
186
- if err != nil {
187
- return err
188
- }
189
- code, err := v.Run(argv[0], argv[1:]...)
190
- if err != nil {
191
- return err
192
- }
193
- os.Exit(code)
194
- return nil
195
- }
196
-
197
182
  // respond prints the command result: JSON with --ir://json, raw strings
198
183
  // otherwise (objects are still rendered as JSON).
199
184
  func respond(response any, jsonOutput bool) error {
package/cmd/vauth.js ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const cnyks = require('cnyks/lib/bundle');
5
+ const Vvauth = require('../index');
6
+ const {args, dict} = require('nyks/process/parseArgs')();
7
+ const command = args.shift();
8
+ const options = command ? [`--ir://run=${command}`] : [];
9
+ if(command === 'env' && !dict['ir://json'])
10
+ options.push('--ir://raw');
11
+
12
+ cnyks(Vvauth, 'vauth', options);
package/gitlab.go ADDED
@@ -0,0 +1,47 @@
1
+ package vvauth
2
+
3
+ import (
4
+ "fmt"
5
+ "net/url"
6
+ "os/exec"
7
+ "regexp"
8
+ "strings"
9
+ )
10
+
11
+ var scpRemote = regexp.MustCompile(`^[^@]+@[^:]+:(.+)$`)
12
+ var nonSlug = regexp.MustCompile(`[^a-z0-9]+`)
13
+
14
+ func (v *Vauth) Gitlab() error {
15
+ out, err := exec.Command("git", "remote", "get-url", "origin").Output()
16
+ if err != nil {
17
+ return err
18
+ }
19
+ remote := strings.TrimSpace(string(out))
20
+ var project string
21
+ if match := scpRemote.FindStringSubmatch(remote); !strings.Contains(remote, "://") && match != nil {
22
+ project = match[1]
23
+ } else {
24
+ parsed, err := url.Parse(remote)
25
+ if err != nil {
26
+ return err
27
+ }
28
+ project = parsed.Path
29
+ }
30
+ project = strings.TrimSuffix(strings.Trim(project, "/"), ".git")
31
+ if project == "" {
32
+ return fmt.Errorf("Could not resolve the Git project from origin")
33
+ }
34
+ parts := strings.Split(project, "/")
35
+ variables := map[string]string{
36
+ "CI_PROJECT_PATH": project,
37
+ "CI_PROJECT_NAME": parts[len(parts)-1],
38
+ "CI_PROJECT_NAMESPACE": strings.Join(parts[:len(parts)-1], "/"),
39
+ "CI_PROJECT_PATH_SLUG": strings.Trim(nonSlug.ReplaceAllString(strings.ToLower(project), "-"), "-"),
40
+ }
41
+ env := &OrderedMap{}
42
+ for _, key := range []string{"CI_PROJECT_PATH", "CI_PROJECT_NAME", "CI_PROJECT_NAMESPACE", "CI_PROJECT_PATH_SLUG"} {
43
+ env.Set(key, variables[key])
44
+ }
45
+ v.PublishEnv(env)
46
+ return nil
47
+ }
package/gitlab_test.go ADDED
@@ -0,0 +1,116 @@
1
+ package vvauth
2
+
3
+ import (
4
+ "bytes"
5
+ "encoding/json"
6
+ "os"
7
+ "os/exec"
8
+ "path/filepath"
9
+ "strings"
10
+ "testing"
11
+ )
12
+
13
+ func TestGitlabPublishesOnlyProjectVariables(t *testing.T) {
14
+ project := t.TempDir()
15
+ for _, args := range [][]string{{"init", "-q", project}, {"-C", project, "remote", "add", "origin", "ssh://git@git.example.test:2222/Team/sub/App.git"}} {
16
+ if out, err := exec.Command("git", args...).CombinedOutput(); err != nil {
17
+ t.Fatalf("git: %v %s", err, out)
18
+ }
19
+ }
20
+ file := filepath.Join(t.TempDir(), "fixture.vauthrc")
21
+ if err := os.WriteFile(file, []byte(`{"env":{"gitlab":true}}`), 0600); err != nil {
22
+ t.Fatal(err)
23
+ }
24
+ t.Setenv("VAUTHRC", file)
25
+ capture, err := os.Create(filepath.Join(t.TempDir(), "stdout"))
26
+ if err != nil {
27
+ t.Fatal(err)
28
+ }
29
+ stdout := os.Stdout
30
+ os.Stdout = capture
31
+ defer func() { os.Stdout = stdout; capture.Close() }()
32
+ before, err := os.ReadFile(file)
33
+ if err != nil {
34
+ t.Fatal(err)
35
+ }
36
+ cwd, err := os.Getwd()
37
+ if err != nil {
38
+ t.Fatal(err)
39
+ }
40
+ if err := os.Chdir(project); err != nil {
41
+ t.Fatal(err)
42
+ }
43
+ t.Cleanup(func() {
44
+ if err := os.Chdir(cwd); err != nil {
45
+ t.Error(err)
46
+ }
47
+ })
48
+ if err := (&Vauth{}).Gitlab(); err != nil {
49
+ t.Fatal(err)
50
+ }
51
+ if _, err := capture.Seek(0, 0); err != nil {
52
+ t.Fatal(err)
53
+ }
54
+ output := new(bytes.Buffer)
55
+ if _, err := output.ReadFrom(capture); err != nil {
56
+ t.Fatal(err)
57
+ }
58
+ for key, value := range map[string]string{"CI_PROJECT_PATH": "Team/sub/App", "CI_PROJECT_NAME": "App", "CI_PROJECT_NAMESPACE": "Team/sub", "CI_PROJECT_PATH_SLUG": "team-sub-app"} {
59
+ if !strings.Contains(output.String(), "export "+key+"='"+value+"'") {
60
+ t.Fatalf("missing %s", key)
61
+ }
62
+ }
63
+ if strings.Count(output.String(), "\n") != 8 || strings.Contains(output.String(), "VAULT_TOKEN") {
64
+ t.Fatal("unexpected exports")
65
+ }
66
+ after, err := os.ReadFile(file)
67
+ if err != nil {
68
+ t.Fatal(err)
69
+ }
70
+ if !bytes.Equal(before, after) {
71
+ t.Fatal("selected config changed")
72
+ }
73
+ if _, err := os.Stat(filepath.Join(project, ".vauthrc")); !os.IsNotExist(err) {
74
+ t.Fatal("project config created")
75
+ }
76
+ }
77
+
78
+ func TestConstructorGitlabGuardPrecedesAuthentication(t *testing.T) {
79
+ f := newFixture(t, fixtureOptions{})
80
+ file := filepath.Join(t.TempDir(), ".vauthrc")
81
+ document := map[string]any{"vault_addr": f.server.URL, "jwt_auth": map[string]any{"jwt": "test-jwt", "role": "test-role"}, "env": map[string]any{"gitlab": true, "map": map[string]any{"KEEP": "literal"}}}
82
+ body, err := json.Marshal(document)
83
+ if err != nil {
84
+ t.Fatal(err)
85
+ }
86
+ if err := os.WriteFile(file, body, 0600); err != nil {
87
+ t.Fatal(err)
88
+ }
89
+ t.Setenv("VAUTHRC", file)
90
+ t.Setenv("VAULT_TOKEN", "")
91
+ keys := []string{"CI_PROJECT_PATH", "CI_PROJECT_NAME", "CI_PROJECT_NAMESPACE", "CI_PROJECT_PATH_SLUG"}
92
+ for _, key := range keys {
93
+ t.Setenv(key, "")
94
+ }
95
+ if _, err := New(); err == nil || !strings.Contains(err.Error(), "Run venv --gitlab first") {
96
+ t.Fatal("constructor accepted missing vars")
97
+ }
98
+ equal(t, len(f.requests), 0)
99
+ for _, key := range keys {
100
+ t.Setenv(key, "provided")
101
+ }
102
+ v, err := New()
103
+ if err != nil {
104
+ t.Fatal(err)
105
+ }
106
+ v.TokenCache = false
107
+ env, err := v.Env(false)
108
+ if err != nil {
109
+ t.Fatal(err)
110
+ }
111
+ value, _ := env.Get("KEEP")
112
+ equal(t, value, "literal")
113
+ if len(f.requests) == 0 {
114
+ t.Fatal("normal auth not performed after initialization")
115
+ }
116
+ }
package/go.mod CHANGED
@@ -1,17 +1,18 @@
1
1
  module github.com/131/vvauth/v2
2
2
 
3
- // version: 2.6.0
3
+ // version: 2.6.2
4
4
 
5
5
  go 1.22
6
6
 
7
7
  require (
8
- github.com/131/ssh-agent-crypt v1.4.2
9
- github.com/131/vauth-login v1.1.5
8
+ github.com/131/ssh-agent-crypt v1.4.4
9
+ github.com/131/vauth-login v1.1.8
10
10
  github.com/Masterminds/semver/v3 v3.5.0
11
11
  gopkg.in/yaml.v3 v3.0.1
12
12
  )
13
13
 
14
14
  require (
15
+ github.com/131/nyks/v6 v6.18.0
15
16
  github.com/Microsoft/go-winio v0.6.2 // indirect
16
17
  golang.org/x/crypto v0.31.0 // indirect
17
18
  golang.org/x/sys v0.28.0 // indirect
package/go.sum CHANGED
@@ -1,13 +1,11 @@
1
- github.com/131/ssh-agent-crypt v1.4.1 h1:Ng6+kKhFkk6XvpCLT8+VhWH9J5wwh1wq4NlHsZwa4NA=
2
- github.com/131/ssh-agent-crypt v1.4.1/go.mod h1:XNiI2n3+2NTwjhyd/plFhrd0vSfWOZ58ocvqTlx1Ydk=
3
- github.com/131/ssh-agent-crypt v1.4.2 h1:e0srAUvSwbPaZXjkE2qY5OCWKxXNTCOVOVWyfrxhTM4=
4
- github.com/131/ssh-agent-crypt v1.4.2/go.mod h1:/YBOMh8URU2lc5kTxjTDftcVrJqGv1SIpo0TjwNQPCA=
5
- github.com/131/vauth-login v1.1.3 h1:XzwooJBhHIltt5PGRVoRXmgsrX6JTSNYPUNrG1O4SXM=
6
- github.com/131/vauth-login v1.1.3/go.mod h1:+Z5ibQE3Wa1ouVSRaiH7t5ckNPlAcpx0j8C8KF+5Z9M=
7
- github.com/131/vauth-login v1.1.4 h1:yv5+5m/0LNIDPlpFzfiKOiA5B6HH5bz1OfzfF9tRc/U=
8
- github.com/131/vauth-login v1.1.4/go.mod h1:4jGHBN8aLgvbhvHGhw1U9jPbl/bfgJUgNyz+O9g3A90=
9
- github.com/131/vauth-login v1.1.5 h1:Uho9fCexylScv5TBVlgctPGj/itVBjdvMFHjqsD4Xlg=
10
- github.com/131/vauth-login v1.1.5/go.mod h1:R0CIG8+HiwdPEsE/VPvltiN7QSeoMuIN46YP/T8JtAw=
1
+ github.com/131/nyks/v6 v6.18.0 h1:xpjRJk2YAyoqqgSvWrox0eIGZ1AY4IkEvqETavcwcQk=
2
+ github.com/131/nyks/v6 v6.18.0/go.mod h1:ckNI5ql4USp+kQyrG1c35tl/PrPSgpoNXktcnQGJpdk=
3
+ github.com/131/ssh-agent-crypt v1.4.4 h1:6MlDUao1Yq6iNY4Bgin/iZp2q3X/g6qD6H1X4ad8ukY=
4
+ github.com/131/ssh-agent-crypt v1.4.4/go.mod h1:/THxpIdVrEAHxNoc6t6lVYBsSEd1zkCROPZepDe8QTI=
5
+ github.com/131/vauth-login v1.1.7 h1:i256JyHP05WKqIrLv18ThfitGipH4oKnN7zpQESzV7U=
6
+ github.com/131/vauth-login v1.1.7/go.mod h1:Dch6CZkaAxnYCD1V83h0g0xPQORjQoZarOOVt4mhNv8=
7
+ github.com/131/vauth-login v1.1.8 h1:ElE+HTirBMmZNUPu788ndmAH844EnmWGFtCeHpi2WHs=
8
+ github.com/131/vauth-login v1.1.8/go.mod h1:t7h0e1phy9sBHfsHlK2jXFstlS7VszU5gcTS4mDSnMQ=
11
9
  github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAwZ/2OOE=
12
10
  github.com/Masterminds/semver/v3 v3.5.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
13
11
  github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
package/index.js CHANGED
@@ -6,13 +6,15 @@ const fs = require('fs');
6
6
  const path = require('path');
7
7
  const {decrypt} = require('ssh-agent-crypt');
8
8
  const VauthLogin = require('vauth-login');
9
+ const {spawn} = require('child_process');
10
+ const exec = require('nyks/child_process/exec');
9
11
  const parseArgs = require('nyks/process/parseArgs');
10
- const {spawn, execFileSync} = require('child_process');
11
12
  const readline = require('readline');
12
13
 
13
14
  const semver = require('semver');
14
15
  const trim = require('mout/string/trim');
15
16
  const get = require('mout/object/get');
17
+ const isPrimitive = require('mout/lang/isPrimitive');
16
18
  const walk = require('nyks/object/walk');
17
19
  const structuredClone = require('nyks/object/structuredClone');
18
20
 
@@ -40,28 +42,14 @@ class Vvauth extends VauthLogin {
40
42
  super();
41
43
 
42
44
  const rc = this.RC;
43
- let env = process.env;
44
-
45
- if(get(rc, 'env.gitlab') && !env.CI) {
46
- try {
47
- let remote_url = String(execFileSync('git', ['remote', 'get-url', 'origin'], {stdio : ['ignore', 'pipe', 'ignore']})).trim();
48
- let match = remote_url.match(/^[^@]+@[^:]+:(.+)$/);
49
- let CI_PROJECT_PATH = match ? match[1] : trim(new URL(remote_url).pathname, '/');
50
- CI_PROJECT_PATH = trim(CI_PROJECT_PATH, '/').replace(/\.git$/, '');
51
-
52
- if(CI_PROJECT_PATH) {
53
- let parts = CI_PROJECT_PATH.split('/');
54
- let CI_PROJECT_NAME = parts.pop();
55
- let CI_PROJECT_NAMESPACE = parts.join('/');
56
- let CI_PROJECT_PATH_SLUG = String(CI_PROJECT_PATH).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
57
-
58
- env = {...env, CI_PROJECT_PATH, CI_PROJECT_NAME, CI_PROJECT_NAMESPACE, CI_PROJECT_PATH_SLUG};
59
- }
60
- } catch(err) {}
61
- }
62
-
63
45
  const config = Object.fromEntries(['env', 'ssh-agent-crypt'].filter(key => rc && Object.hasOwn(rc, key)).map(key => [key, rc[key]]));
64
- this.config = walk(structuredClone(config), v => replaceEnv(v, {env}));
46
+ this.config = walk(structuredClone(config), v => replaceEnv(v, {env : process.env}));
47
+ if(this.config.env && this.config.env.gitlab === true) {
48
+ const {args, dict} = parseArgs();
49
+ const missing = ['CI_PROJECT_PATH', 'CI_PROJECT_NAME', 'CI_PROJECT_NAMESPACE', 'CI_PROJECT_PATH_SLUG'].filter(key => !process.env[key]);
50
+ if(!(dict.gitlab || args[0] === 'gitlab') && missing.length)
51
+ throw new Error(`Missing ${missing.join(', ')}. Run venv --gitlab first.`);
52
+ }
65
53
 
66
54
 
67
55
  if(!this.VAULT_ADDR)
@@ -69,20 +57,33 @@ class Vvauth extends VauthLogin {
69
57
 
70
58
  }
71
59
 
72
- static Version() {
60
+ static Version() /**
61
+ * @alias version
62
+ */ {
73
63
  return VERSION;
74
64
  }
75
65
 
76
- async Run(command, ...args) {
77
- const env = await this.Env();
78
- const child = spawn(command, args, {env : {...process.env, ...env}, stdio : 'inherit'});
79
- return new Promise((resolve, reject) => {
80
- child.once('error', reject);
81
- child.once('close', resolve);
82
- });
66
+ async Gitlab() /**
67
+ * @alias gitlab
68
+ */ {
69
+ const remote = String(await exec('git', ['remote', 'get-url', 'origin'], {stdio : ['ignore', 'pipe', 'ignore']})).trim();
70
+ const match = remote.includes('://') ? null : remote.match(/^[^@]+@[^:]+:(.+)$/);
71
+ const project = trim(match ? match[1] : decodeURIComponent(new URL(remote).pathname), '/').replace(/\.git$/, '');
72
+ if(!project)
73
+ throw new Error('Could not resolve the Git project from origin');
74
+ const parts = project.split('/');
75
+ const variables = {
76
+ CI_PROJECT_PATH : project,
77
+ CI_PROJECT_NAME : parts.pop(),
78
+ CI_PROJECT_NAMESPACE : parts.join('/'),
79
+ CI_PROJECT_PATH_SLUG : project.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, ''),
80
+ };
81
+ this.PublishEnv(variables);
83
82
  }
84
83
 
85
- async Login(source = false, renew = false) {
84
+ async Login(source = false, renew = false) /**
85
+ * @alias login
86
+ */ {
86
87
  await this.Connect(renew);
87
88
  if(source) {
88
89
  let env = {VAULT_TOKEN : this.VAULT_TOKEN || ''};
@@ -100,7 +101,9 @@ class Vvauth extends VauthLogin {
100
101
  }
101
102
 
102
103
 
103
- async Set(k, v) {
104
+ async Set(k, v) /**
105
+ * @alias set
106
+ */ {
104
107
  let {profile, database} = await this.GetProfile();
105
108
  if(!profile.VAUTH_USER_LOGIN)
106
109
  throw "Could not resolve VAUTH_USER_LOGIN from vault identity";
@@ -109,11 +112,15 @@ class Vvauth extends VauthLogin {
109
112
  await this._vault_write(`private/${profile.VAUTH_USER_LOGIN}`, '.vauth_database', database);
110
113
  }
111
114
 
112
- async Unset(k) {
115
+ async Unset(k) /**
116
+ * @alias unset
117
+ */ {
113
118
  await this.Set(k, undefined);
114
119
  }
115
120
 
116
- async Show() {
121
+ async Show() /**
122
+ * @alias show
123
+ */ {
117
124
  let {profile, database} = await this.GetProfile();
118
125
  return {...database, ...profile};
119
126
  }
@@ -136,7 +143,13 @@ class Vvauth extends VauthLogin {
136
143
  return {entity_id, identity, profile, database};
137
144
  }
138
145
 
139
- async Env(source = false, renew = false) {
146
+ async Env(source = false, renew = false, gitlab = false) /**
147
+ * @alias env
148
+ */ {
149
+ if(gitlab) {
150
+ await this.Gitlab();
151
+ return;
152
+ }
140
153
  let env = {}, secrets = {}, profile = {};
141
154
  let {git, map = {}, paths, path : mount = "secrets"} = this.config.env || {};
142
155
  const localCredentials = this.config['ssh-agent-crypt'] && !this.RC.ssh_auth && !this.RC.jwt_auth;
@@ -181,7 +194,7 @@ class Vvauth extends VauthLogin {
181
194
  // the key reaches `export KEY=...` unescaped; .vauthrc may come from an untrusted working directory
182
195
  if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k))
183
196
  throw new Error(`Invalid environment variable name '${k}' in env.map`);
184
- env[k] = replaceEnv(v, {env : process.env, profile, secrets});
197
+ env[k] = envValue(replaceEnv(envValue(v, k), {env : process.env, profile, secrets}), k);
185
198
  }
186
199
 
187
200
  if(source) {
@@ -191,7 +204,9 @@ class Vvauth extends VauthLogin {
191
204
  return env;
192
205
  }
193
206
 
194
- async Dotenv() {
207
+ async Dotenv() /**
208
+ * @alias dotenv
209
+ */ {
195
210
  const env = await this.Env();
196
211
 
197
212
  for(let [k, v] of Object.entries(env)) {
@@ -220,7 +235,9 @@ class Vvauth extends VauthLogin {
220
235
  return new Promise(resolve => child.on('exit', resolve));
221
236
  }
222
237
 
223
- async Install() {
238
+ async Install() /**
239
+ * @alias install
240
+ */ {
224
241
  const bashrc_path = path.resolve(os.homedir(), ".bashrc");
225
242
  let bashrc = fs.existsSync(bashrc_path) ? fs.readFileSync(bashrc_path, 'utf-8').trim() : '';
226
243
  if(await this._function_exists(FUNCTION_NAME) === 0) {
@@ -240,59 +257,17 @@ class Vvauth extends VauthLogin {
240
257
 
241
258
  }
242
259
 
260
+ const envValue = (value, key) => {
261
+ if(value == null)
262
+ return '';
263
+ if(!isPrimitive(value) || (typeof value === 'number' && !Number.isFinite(value)))
264
+ throw new Error(`Invalid environment value '${key}' in env.map: expected a scalar`);
265
+ return String(value);
266
+ };
267
+
243
268
  const shellEscape = (arg) => {
244
269
  // see man bash
245
270
  return "'" + String(arg).replace(/'/g, '\'"\'"\'') + "'";
246
271
  };
247
272
 
248
- // Command spelling is a CLI concern, not an SDK compatibility alias.
249
- async function main() {
250
- const argv = process.argv.slice(2);
251
- if(argv[0] === 'run') {
252
- const args = argv.slice(1);
253
- if(args[0] === '--') args.shift();
254
- const command = args.shift();
255
- if(!command) throw new Error('Missing command for run');
256
- process.exitCode = await new Vvauth().Run(command, ...args);
257
- return;
258
- }
259
- const {args, dict} = parseArgs(argv);
260
- const command = args.shift() || (dict.version ? 'version' : undefined);
261
- if(command === 'version') {
262
- process.stdout.write(Vvauth.Version() + '\n');
263
- return;
264
- }
265
- if(!['env', 'login', 'connect', 'dotenv', 'show', 'set', 'unset', 'install'].includes(command))
266
- throw new Error('Usage: vauth <env|login|connect|run|dotenv|show|set|unset|install|version>');
267
- if(Object.hasOwn(dict, 'ir://run'))
268
- throw new Error('Unsupported flag --ir://run');
269
- const param = (index, name) => index < args.length ? args[index] : dict[name];
270
- const enabled = value => value !== undefined && !['', 'false', '0'].includes(String(value).toLowerCase());
271
- const client = new Vvauth();
272
- let result;
273
- switch(command) {
274
- case 'env': result = await client.Env(enabled(param(0, 'source')), enabled(param(1, 'renew'))); break;
275
- case 'login': await client.Login(enabled(param(0, 'source')), enabled(param(1, 'renew'))); return;
276
- case 'connect': result = await client.Connect(enabled(param(0, 'renew'))); break;
277
- case 'dotenv': await client.Dotenv(); return;
278
- case 'show': result = await client.Show(); break;
279
- case 'set':
280
- if(param(0, 'k') === undefined || param(1, 'v') === undefined) throw new Error('Missing parameter --k or --v');
281
- await client.Set(param(0, 'k'), param(1, 'v')); return;
282
- case 'unset':
283
- if(param(0, 'k') === undefined) throw new Error('Missing parameter --k');
284
- await client.Unset(param(0, 'k')); return;
285
- case 'install': await client.Install(); return;
286
- }
287
- if(result !== undefined && result !== '') {
288
- if(Object.hasOwn(dict, 'ir://json') || typeof result !== 'string')
289
- process.stdout.write(JSON.stringify(result) + (Object.hasOwn(dict, 'ir://json') ? '' : '\n'));
290
- else
291
- process.stdout.write(result);
292
- }
293
- }
294
-
295
- if(require.main === module)
296
- main().catch(err => { console.error(err instanceof Error ? err.message : String(err)); process.exitCode = 1; });
297
-
298
273
  module.exports = Vvauth;
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "vvauth",
3
- "version": "2.6.0",
3
+ "version": "2.6.2",
4
4
  "description": "Vault Auth helper",
5
5
  "main": "index.js",
6
6
  "bin": {
7
- "vauth": "./index.js"
7
+ "vauth": "./cmd/vauth.js"
8
8
  },
9
9
  "scripts": {
10
10
  "test": "node --test test/token-cache.js",
@@ -13,11 +13,12 @@
13
13
  "author": "",
14
14
  "license": "ISC",
15
15
  "dependencies": {
16
+ "cnyks": "^3.2.4",
16
17
  "mout": "^1.2.4",
17
- "nyks": "^6.17.0",
18
+ "nyks": "^6.18.0",
18
19
  "semver": "^7.5.4",
19
- "ssh-agent-crypt": "^1.4.2",
20
- "vauth-login": "^1.1.5"
20
+ "ssh-agent-crypt": "^1.4.4",
21
+ "vauth-login": "^1.1.8"
21
22
  },
22
23
  "devDependencies": {
23
24
  "eslint": "^8.57.0",