vvauth 2.4.1 → 2.6.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/index.js CHANGED
@@ -4,248 +4,93 @@
4
4
  const os = require('os');
5
5
  const fs = require('fs');
6
6
  const path = require('path');
7
- const url = require('url');
8
- const {createHash} = require('crypto');
9
- const {encrypt, decrypt} = require('ssh-agent-crypt');
7
+ const {decrypt} = require('ssh-agent-crypt');
8
+ const VauthLogin = require('vauth-login');
9
+ const parseArgs = require('nyks/process/parseArgs');
10
10
  const {spawn, execFileSync} = require('child_process');
11
- const passthru = require('nyks/child_process/passthru');
12
- const boolPrompt = require('cnyks/prompt/bool');
11
+ const readline = require('readline');
13
12
 
14
- const {parse} = require('yaml');
15
13
  const semver = require('semver');
16
14
  const trim = require('mout/string/trim');
17
15
  const get = require('mout/object/get');
18
- const eachLimit = require('nyks/async/eachLimit');
19
16
  const walk = require('nyks/object/walk');
20
- const humanDiff = require('nyks/date/humanDiff');
17
+ const structuredClone = require('nyks/object/structuredClone');
21
18
 
22
- const request = require('nyks/http/request');
23
- const drain = require('nyks/stream/drain');
24
19
  const replaceEnv = require('nyks/string/replaceEnv');
25
- const promiser = require('nyks/function/promiser');
26
- const {args} = require('nyks/process/parseArgs')();
27
20
 
28
21
 
29
- const {createAgent} = require('ssh2/lib/agent');
30
- const debug = require('debug');
31
-
32
- const logger = {
33
- debug : debug('vvauth:debug'),
34
- info : debug('vvauth:info'),
35
- error : debug('vvauth:error'),
36
- };
37
-
38
-
39
- const VAUTH_RC = [process.env.VAUTHRC, path.join(process.cwd(), ".vauthrc"), path.join(os.homedir(), ".vauthrc")];
22
+ const {name : PACKAGE_NAME, version : VERSION} = require('./package.json');
40
23
  const FUNCTION_NAME = "venv";
41
24
  const FUNCTION_DECL = `function ${FUNCTION_NAME}() { source <(/usr/bin/env vauth env --source "$@"); }`;
42
25
 
43
- class vvauth {
26
+ class Vvauth extends VauthLogin {
44
27
  constructor() {
45
28
 
46
29
 
30
+ // A project may pin the vauth it expects: `"dependencies": {"vvauth": "^2.5.0"}`.
31
+ // Only vvauth itself is checked, against the running version.
47
32
  let manifest = path.resolve('package.json');
48
33
  if(fs.existsSync(manifest)) {
49
- let {dependencies = {}} = require(path.resolve('package.json'));
50
-
51
- for(let [module_name, module_version] of Object.entries(dependencies)) {
52
-
53
- let {version} = require(require.resolve(`${module_name}/package.json`, {
54
- paths : ['.', ...(require.main && require.main.paths || module.paths)]
55
- }));
56
-
57
- if(!semver.satisfies(version, module_version))
58
- throw `Unsupported ${module_name} version (requires ${module_version})`;
59
- }
34
+ const {dependencies = {}} = JSON.parse(fs.readFileSync(manifest, 'utf8'));
35
+ const required = dependencies[PACKAGE_NAME];
36
+ if(required && !semver.satisfies(VERSION, required))
37
+ throw `Unsupported ${PACKAGE_NAME} version ${VERSION} (project requires ${required})`;
60
38
  }
61
39
 
62
- this.rc = {};
63
-
64
- let vauth_rc = VAUTH_RC.filter(path => path && fs.existsSync(path))[0];
65
- if(vauth_rc) {
66
- let body = fs.readFileSync(vauth_rc, 'utf8');
67
- let rc = parse(body);
68
- let env = process.env;
69
-
70
- if(get(rc, 'env.gitlab') && !env.CI) {
71
- try {
72
- let remote_url = String(execFileSync('git', ['remote', 'get-url', 'origin'], {cwd : path.dirname(vauth_rc), stdio : ['ignore', 'pipe', 'ignore']})).trim();
73
- let match = remote_url.match(/^[^@]+@[^:]+:(.+)$/);
74
- let CI_PROJECT_PATH = match ? match[1] : trim(new URL(remote_url).pathname, '/');
75
- CI_PROJECT_PATH = trim(CI_PROJECT_PATH, '/').replace(/\.git$/, '');
76
-
77
- if(CI_PROJECT_PATH) {
78
- let parts = CI_PROJECT_PATH.split('/');
79
- let CI_PROJECT_NAME = parts.pop();
80
- let CI_PROJECT_NAMESPACE = parts.join('/');
81
- let CI_PROJECT_PATH_SLUG = String(CI_PROJECT_PATH).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
82
-
83
- env = {...env, CI_PROJECT_PATH, CI_PROJECT_NAME, CI_PROJECT_NAMESPACE, CI_PROJECT_PATH_SLUG};
84
- }
85
- } catch(err) {}
86
- }
40
+ super();
87
41
 
88
- this.rc = walk(rc, v => replaceEnv(v, {env}));
89
- }
42
+ const rc = this.RC;
43
+ let env = process.env;
90
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
+ }
91
62
 
92
- if(!process.env.SSH_AUTH_SOCK && process.platform !== 'win32')
93
- this.rc.token_cache = false;
63
+ 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}));
94
65
 
95
- this.VAULT_ADDR = this.rc.vault_addr || process.env.VAULT_ADDR; //might be null
96
- this.VAULT_TOKEN = process.env.VAULT_TOKEN;
97
66
 
98
67
  if(!this.VAULT_ADDR)
99
68
  console.error("Not bound to any vault");
100
69
 
101
70
  }
102
71
 
103
- async run() {
104
- let args = process.argv.slice(process.argv.indexOf("run") + 1);
105
- let env = await this.env(), cmd = args.shift();
106
- await passthru(cmd, args, {env : {...process.env, ...env}}).catch((err) => (console.error("run failure : ", err), process.exit(1)));
107
- process.exit();
108
- }
109
-
110
- _token_cache_key() {
111
- const {ssh_auth, jwt_auth} = this.rc;
112
- return createHash('sha256').update(JSON.stringify({
113
- vault_addr : trim(this.VAULT_ADDR || '', '/'), ssh_auth, jwt_auth,
114
- })).digest('hex');
115
- }
116
-
117
- _token_cache_file() {
118
- return path.join(os.homedir(), '.vauth', 'tokens', this._token_cache_key() + '.creds');
119
- }
120
-
121
- async _read_token_cache() {
122
- if(this.rc.token_cache === false)
123
- return;
124
- try {
125
- const armor = fs.readFileSync(this._token_cache_file(), 'utf8');
126
- return JSON.parse(await decrypt(armor));
127
- } catch(err) {}
128
- }
129
-
130
- async _save_cached_token(token, metadata) {
131
- if(this.rc.token_cache === false)
132
- return;
133
- const ttl = metadata.ttl === undefined ? metadata.lease_duration : metadata.ttl;
134
- const file = this._token_cache_file();
135
- const temporary = file + '.next';
136
- try {
137
- const {lease_duration} = metadata;
138
- const cache = {
139
- token, lease_duration, renewable : metadata.renewable === true,
140
- expires_at : ttl === 0 ? null : Date.now() + ttl * 1000,
141
- };
142
- fs.mkdirSync(path.dirname(file), {recursive : true, mode : 0o700});
143
- const identity = process.env.VAUTH_USER_IDENTITY || process.env.VAUTH_USER_MAIL;
144
- const armor = await encrypt(JSON.stringify(cache), identity);
145
- fs.writeFileSync(temporary, armor, {mode : 0o600});
146
- fs.renameSync(temporary, file);
147
- } catch(err) {
148
- // Cache failures must not prevent authentication or expose credentials.
149
- console.error('Could not encrypt/write token cache; token not persisted');
150
- } finally {
151
- try { fs.unlinkSync(temporary); } catch(err) {}
152
- }
153
- }
154
-
155
- _token_status(operation, metadata) {
156
- const ttl = metadata.ttl === undefined ? metadata.lease_duration : metadata.ttl;
157
- const validity = ttl === 0 ? 'valid indefinitely' : humanDiff(ttl, 2);
158
- console.error('Vauth token: %s · %s · %s', operation, this.VAULT_ADDR, validity);
72
+ static Version() {
73
+ return VERSION;
159
74
  }
160
75
 
161
- async connect(renew = false) {
162
- const {ssh_auth, jwt_auth} = this.rc;
163
- if(!ssh_auth && !jwt_auth) {
164
- this.VAULT_TOKEN = undefined;
165
- return;
166
- }
167
- if(this._connected && !renew)
168
- return this.VAULT_TOKEN;
169
- this._connected = false;
170
-
171
- const cached = await this._read_token_cache();
172
- let token = this.VAULT_TOKEN || (cached && cached.token);
173
- const had_token = !!token;
174
- let metadata, operation = 'reused';
175
- if(renew || (cached && token === cached.token && cached.expires_at !== null && cached.expires_at <= Date.now()))
176
- token = undefined;
177
-
178
- if(token) {
179
- try {
180
- if(cached && cached.token === token) {
181
- const ttl = cached.expires_at === null ? 0 : (cached.expires_at - Date.now()) / 1000;
182
- metadata = {...cached, ttl};
183
- } else {
184
- metadata = await this._lookup_token(token);
185
- }
186
- const {ttl, renewable, lease_duration} = metadata;
187
- if(ttl > 0 && ttl <= lease_duration / 3) {
188
- if(renewable) {
189
- metadata = await this._renew_token(token);
190
- token = metadata.client_token;
191
- operation = 'renewed';
192
- } else {
193
- token = undefined;
194
- }
195
- }
196
- } catch(err) {
197
- // Reauthenticate on invalid tokens, not network/server failures.
198
- const status = err.res && err.res.statusCode;
199
- if(![400, 403].includes(status))
200
- throw err;
201
- token = undefined;
202
- }
203
- }
204
-
205
- if(!token) {
206
- const agent_path = process.env.SSH_AUTH_SOCK || (process.platform === 'win32' ? 'pageant' : null);
207
- if(ssh_auth && agent_path) {
208
- metadata = await this._login_vault_ssh({...ssh_auth}, agent_path);
209
- } else if(jwt_auth && jwt_auth.jwt) {
210
- const {path, jwt, role} = jwt_auth;
211
- metadata = await this._login_vault(path, {jwt, role});
212
- }
213
- token = metadata && metadata.client_token;
214
- if(!token && (renew || had_token))
215
- throw new Error('Could not login to vault: no authentication method available');
216
- operation = 'generated';
217
- }
218
-
219
- if(token) {
220
- if(operation !== 'reused' || !cached || cached.token !== token)
221
- await this._save_cached_token(token, metadata);
222
- this._token_status(operation, metadata);
223
- }
224
- this.VAULT_TOKEN = token;
225
- this._connected = true;
226
- return token;
227
- }
228
-
229
- async _renew_token(token) {
230
- const remote_url = `${trim(this.VAULT_ADDR, '/')}/v1/auth/token/renew-self`;
231
- const query = {...url.parse(remote_url), headers : {'x-vault-token' : token}, expect : 200, json : true};
232
- const res = await request(query, {});
233
- const auth = JSON.parse(String(await drain(res))).auth;
234
- if(!auth.client_token || !Number.isFinite(auth.lease_duration) || auth.lease_duration < 0)
235
- throw new Error('Invalid Vault token renewal response');
236
- return auth;
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
+ });
237
83
  }
238
84
 
239
- async login(source = false, renew = false) {
240
- await this.connect(renew);
85
+ async Login(source = false, renew = false) {
86
+ await this.Connect(renew);
241
87
  if(source) {
242
- let env = {VAULT_TOKEN : this.VAULT_TOKEN};
243
- this._publish_env(env);
244
- process.exit();
88
+ let env = {VAULT_TOKEN : this.VAULT_TOKEN || ''};
89
+ this.PublishEnv(env);
245
90
  }
246
91
  }
247
92
 
248
- _publish_env(env) {
93
+ PublishEnv(env) {
249
94
  let cmds = [];
250
95
  for(let [k, v] of Object.entries(env)) {
251
96
  cmds.push(`export ${k}=${shellEscape(v)}`);
@@ -255,8 +100,8 @@ class vvauth {
255
100
  }
256
101
 
257
102
 
258
- async set(k, v) {
259
- let {profile, database} = await this._vault_get_profile();
103
+ async Set(k, v) {
104
+ let {profile, database} = await this.GetProfile();
260
105
  if(!profile.VAUTH_USER_LOGIN)
261
106
  throw "Could not resolve VAUTH_USER_LOGIN from vault identity";
262
107
 
@@ -264,23 +109,24 @@ class vvauth {
264
109
  await this._vault_write(`private/${profile.VAUTH_USER_LOGIN}`, '.vauth_database', database);
265
110
  }
266
111
 
267
- async unset(k) {
268
- await this.set(k, undefined);
112
+ async Unset(k) {
113
+ await this.Set(k, undefined);
269
114
  }
270
115
 
271
- async show() {
272
- let {profile, database} = await this._vault_get_profile();
116
+ async Show() {
117
+ let {profile, database} = await this.GetProfile();
273
118
  return {...database, ...profile};
274
119
  }
275
120
 
276
- async _vault_get_profile(renew = false) {
277
- await this.connect(renew);
121
+ async GetProfile(renew = false) {
122
+ await this.Connect(renew);
278
123
 
279
- if(!this.VAULT_TOKEN)
280
- return {};
124
+ if(!this.VAULT_TOKEN || !this.VAULT_ADDR)
125
+ return {profile : {}, database : {}};
281
126
 
282
- let {entity_id} = await this._lookup_token(this.VAULT_TOKEN);
283
- let identity = await this._lookup_identity(this.VAULT_TOKEN, entity_id);
127
+ const {entity_id} = await this.LookupSelf(this.VAULT_TOKEN);
128
+ const {body} = await this.Request('GET', `identity/entity/id/${entity_id}`, this.VAULT_TOKEN);
129
+ const identity = JSON.parse(body).data;
284
130
  let profile = {...(identity.metadata)};
285
131
  let database = {};
286
132
 
@@ -290,12 +136,16 @@ class vvauth {
290
136
  return {entity_id, identity, profile, database};
291
137
  }
292
138
 
293
- async _get_env(renew = false) {
294
- let {profile, database} = await this._vault_get_profile(renew);
295
- profile = {...database, ...profile};
296
-
297
- let env = {}, secrets = {},
298
- {git, map = {}, paths, path : mount = "secrets"} = this.rc.env || {};
139
+ async Env(source = false, renew = false) {
140
+ let env = {}, secrets = {}, profile = {};
141
+ let {git, map = {}, paths, path : mount = "secrets"} = this.config.env || {};
142
+ const localCredentials = this.config['ssh-agent-crypt'] && !this.RC.ssh_auth && !this.RC.jwt_auth;
143
+ if(localCredentials) {
144
+ await this.Connect(renew);
145
+ } else {
146
+ const current = await this.GetProfile(renew);
147
+ profile = {...current.database, ...current.profile};
148
+ }
299
149
 
300
150
  if(this.VAULT_TOKEN)
301
151
  env.VAULT_TOKEN = this.VAULT_TOKEN;
@@ -303,7 +153,7 @@ class vvauth {
303
153
  env.VAULT_ADDR = this.VAULT_ADDR;
304
154
 
305
155
 
306
- let {'ssh-agent-crypt' : agent } = this.rc;
156
+ let {'ssh-agent-crypt' : agent } = this.config;
307
157
  if(agent) {
308
158
  const {path, identity} = agent;
309
159
  const body = await decrypt(fs.readFileSync(path), identity);
@@ -327,106 +177,59 @@ class vvauth {
327
177
  secrets = {...secrets, ...data};
328
178
  }
329
179
  }
330
- for(let [k, v] of Object.entries(map))
180
+ for(let [k, v] of Object.entries(map)) {
181
+ // the key reaches `export KEY=...` unescaped; .vauthrc may come from an untrusted working directory
182
+ if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k))
183
+ throw new Error(`Invalid environment variable name '${k}' in env.map`);
331
184
  env[k] = replaceEnv(v, {env : process.env, profile, secrets});
185
+ }
332
186
 
187
+ if(source) {
188
+ this.PublishEnv(env);
189
+ return;
190
+ }
333
191
  return env;
334
192
  }
335
193
 
336
- async dotenv() {
337
- const env = await this._get_env();
194
+ async Dotenv() {
195
+ const env = await this.Env();
338
196
 
339
197
  for(let [k, v] of Object.entries(env)) {
340
198
  process.stdout.write(`${k}=${String(v)}\n`);
341
199
  process.stderr.write(`export ${k}=[redacted]\n`);
342
200
  }
343
201
 
344
- process.exit();
345
- }
346
-
347
- async env(source = false, renew = false) {
348
- const env = await this._get_env(renew);
349
-
350
- if(source) {
351
- this._publish_env(env);
352
- process.exit();
353
- }
354
-
355
- return env;
356
202
  }
357
203
 
358
204
  async _vault_read(mount, secret_path, optional = false) {
359
- let remote_url = `${trim(this.VAULT_ADDR, '/')}/v1/${mount}/data/${trim(secret_path, '/')}`;
360
- let query = {...url.parse(remote_url), headers : {'x-vault-token' : this.VAULT_TOKEN}};
361
- let res = await request(query);
362
- let body = String(await drain(res));
363
-
364
- if(optional && res.statusCode == 404)
205
+ const {status, body} = await this.Request('GET', `${mount}/data/${trim(secret_path, '/')}`, this.VAULT_TOKEN, null, 0);
206
+ if(optional && status === 404)
365
207
  return {};
366
-
367
- if(res.statusCode != 200)
368
- throw `Could not read vault secret '${mount}/${trim(secret_path, '/')}' : ${body}`;
369
-
208
+ if(status !== 200)
209
+ throw new VauthLogin.HTTPError(status, body.toString());
370
210
  return get(JSON.parse(body), 'data.data');
371
211
  }
372
212
 
373
213
  async _vault_write(mount, secret_path, data) {
374
- let remote_url = `${trim(this.VAULT_ADDR, '/')}/v1/${mount}/data/${trim(secret_path, '/')}`;
375
- let query = {...url.parse(remote_url), headers : {'x-vault-token' : this.VAULT_TOKEN}, json : true};
376
- let res = await request(query, {data});
377
- let body = String(await drain(res));
378
-
379
- if(res.statusCode != 200)
380
- throw `Could not write vault secret '${mount}/${trim(secret_path, '/')}' : ${body}`;
381
-
382
- return body ? JSON.parse(body) : {};
214
+ const {body} = await this.Request('POST', `${mount}/data/${trim(secret_path, '/')}`, this.VAULT_TOKEN, {data}, 200);
215
+ return body.length ? JSON.parse(body) : {};
383
216
  }
384
217
 
385
-
386
- async _login_vault_ssh({path = 'ssh', role}, agent_path = process.env.SSH_AUTH_SOCK) {
387
- logger.info("Trying to auth as '%s'", role);
388
-
389
- let agent = createAgent(agent_path);
390
- let keys = await promiser(chain => agent.getIdentities(chain));
391
-
392
-
393
- let auth;
394
- await eachLimit(keys, 1, async (pubKey) => {
395
- if(auth)
396
- return;
397
-
398
- let remote_url = `${trim(this.VAULT_ADDR, '/')}/v1/auth/${path}/nonce`;
399
- let query = {...url.parse(remote_url), json : true};
400
- let res = await request(query);
401
- let {data : {nonce}} = JSON.parse(String(await drain(res)));
402
-
403
- const signature = (await promiser(chain => agent.sign(pubKey, Buffer.from(nonce), {}, chain))).toString('base64');
404
- const public_key = pubKey.type + ' ' + pubKey.getPublicSSH().toString('base64');
405
- const payload = {public_key, role, nonce : Buffer.from(nonce).toString('base64'), signature};
406
- try {
407
- auth = await this._login_vault(path, payload);
408
- } catch(err) {
409
- logger.debug("ssh : invalid challenge for public key", pubKey.comment);
410
- }
411
- });
412
-
413
-
414
- if(!auth || !auth.client_token)
415
- throw `Could not login to vault`;
416
-
417
- return auth;
418
- }
419
218
  async _function_exists(alias) {
420
219
  let child = spawn('bash', ["-lc", `declare -F ${alias}`]);
421
220
  return new Promise(resolve => child.on('exit', resolve));
422
221
  }
423
222
 
424
- async install() {
223
+ async Install() {
425
224
  const bashrc_path = path.resolve(os.homedir(), ".bashrc");
426
225
  let bashrc = fs.existsSync(bashrc_path) ? fs.readFileSync(bashrc_path, 'utf-8').trim() : '';
427
226
  if(await this._function_exists(FUNCTION_NAME) === 0) {
428
- if(!await boolPrompt("Function already defined, override current definition? ", false))
429
- return;
227
+ const prompt = readline.createInterface({input : process.stdin, output : process.stdout});
228
+ const answer = await new Promise(resolve => {
229
+ prompt.once('close', () => resolve(''));
230
+ prompt.question('Function already defined, override current definition? [y/N] ', value => { resolve(value); prompt.close(); });
231
+ });
232
+ if(!/^y(es)?$/i.test(answer.trim())) return;
430
233
  }
431
234
  console.error("Installing function %s in %s", FUNCTION_NAME, bashrc_path);
432
235
 
@@ -434,51 +237,6 @@ class vvauth {
434
237
  console.error(`Installation ok, please \nsource ${bashrc_path}`);
435
238
  }
436
239
 
437
- async _lookup_token(token) {
438
- let remote_url = `${trim(this.VAULT_ADDR, '/')}/v1/auth/token/lookup-self`;
439
- let query = {...url.parse(remote_url), headers : {'x-vault-token' : token}, expect : 200};
440
- let res = await request(query);
441
- let response = JSON.parse(await drain(res)).data;
442
- if(!Number.isFinite(response.ttl) || response.ttl < 0)
443
- throw new Error('Invalid Vault token TTL');
444
- const cached = await this._read_token_cache();
445
- if(cached && cached.token === token)
446
- response.lease_duration = cached.lease_duration;
447
- else
448
- response.lease_duration = response.creation_ttl;
449
- return response;
450
- }
451
-
452
- async _lookup_identity(token, id) {
453
- let remote_url = `${trim(this.VAULT_ADDR, '/')}/v1/identity/entity/id/${id}`;
454
- let query = {...url.parse(remote_url), headers : {'x-vault-token' : token}, expect : 200};
455
- let res = await request(query);
456
- return JSON.parse(String(await drain(res))).data;
457
- }
458
-
459
- async _update_identity(token, id, payload) {
460
- let remote_url = `${trim(this.VAULT_ADDR, '/')}/v1/identity/entity/id/${id}`;
461
- let query = {...url.parse(remote_url), headers : {'x-vault-token' : token}, expect : 204, json : true};
462
- await request(query, payload);
463
- return payload;
464
- }
465
-
466
-
467
-
468
- async _login_vault(path, payload) {
469
- let remote_url = `${trim(this.VAULT_ADDR, '/')}/v1/auth/${path}/login`;
470
- let query = {...url.parse(remote_url), json : true};
471
- let res = await request(query, payload);
472
- let response = String(await drain(res));
473
-
474
- if(res.statusCode !== 200)
475
- throw `Could not login to vault : ${response}`;
476
-
477
- const auth = JSON.parse(response).auth;
478
- if(!auth.client_token || !Number.isFinite(auth.lease_duration) || auth.lease_duration < 0)
479
- throw new Error('Invalid Vault login response');
480
- return auth;
481
- }
482
240
 
483
241
  }
484
242
 
@@ -487,11 +245,54 @@ const shellEscape = (arg) => {
487
245
  return "'" + String(arg).replace(/'/g, '\'"\'"\'') + "'";
488
246
  };
489
247
 
490
- //ensure module is called directly, i.e. not required
491
- if(module.parent === null) {
492
- let cmd = args.shift();
493
- const output = process.argv.includes('--ir://json') ? '--ir://json' : '--ir://raw';
494
- require('cnyks/lib/bundle')(vvauth, null, cmd ? [`--ir://run=${cmd}`, output] : []);
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
+ }
495
293
  }
496
294
 
497
- module.exports = vvauth;
295
+ if(require.main === module)
296
+ main().catch(err => { console.error(err instanceof Error ? err.message : String(err)); process.exitCode = 1; });
297
+
298
+ module.exports = Vvauth;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vvauth",
3
- "version": "2.4.1",
3
+ "version": "2.6.0",
4
4
  "description": "Vault Auth helper",
5
5
  "main": "index.js",
6
6
  "bin": {
@@ -13,14 +13,11 @@
13
13
  "author": "",
14
14
  "license": "ISC",
15
15
  "dependencies": {
16
- "cnyks": "^3.2.1",
17
- "debug": "^4.3.4",
18
16
  "mout": "^1.2.4",
19
- "nyks": "^6.15.0",
17
+ "nyks": "^6.17.0",
20
18
  "semver": "^7.5.4",
21
- "ssh-agent-crypt": "^1.2.0",
22
- "ssh2": "^1.16.0",
23
- "yaml": "^2.6.1"
19
+ "ssh-agent-crypt": "^1.4.2",
20
+ "vauth-login": "^1.1.5"
24
21
  },
25
22
  "devDependencies": {
26
23
  "eslint": "^8.57.0",
@@ -32,5 +29,8 @@
32
29
  "repository": {
33
30
  "type": "git",
34
31
  "url": "git@github.com:131/vvauth.git"
32
+ },
33
+ "engines": {
34
+ "node": ">=16"
35
35
  }
36
36
  }