@env-ctrl/cli 0.0.0-stage → 0.1.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 +20 -2
- package/bin/envctrl.js +183 -0
- package/package.json +33 -4
package/README.md
CHANGED
|
@@ -1,3 +1,21 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @env-ctrl/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Start any command with the environment variables of one env-ctrl environment.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
export ENVCTRL_TOKEN=ec_svc_... # the only secret your app/server needs
|
|
7
|
+
npx @env-ctrl/cli run -- npm start # npm start sees DATABASE_URL, STRIPE_SECRET_KEY, ...
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
| Command | What it does |
|
|
11
|
+
|---|---|
|
|
12
|
+
| `envctrl run -- <cmd>` | Fetches variables and starts `<cmd>` with them. Nothing is written to disk. `--strict` refuses to start if required keys are missing; `--keep-existing` lets variables from your shell win. |
|
|
13
|
+
| `envctrl pull [--out .env] [--format json]` | Prints or writes the variables (file mode 600). |
|
|
14
|
+
| `envctrl check` | Exits 1 if required keys are missing or a value fails its type / regex check. Use it in CI before deploying. |
|
|
15
|
+
| `envctrl whoami` | Shows the project and environment the token belongs to. |
|
|
16
|
+
|
|
17
|
+
Create the token in the env-ctrl dashboard at [envctrl.com](https://envctrl.com) (project → Access tokens).
|
|
18
|
+
|
|
19
|
+
API: `https://api.envctrl.com` by default; set `ENVCTRL_URL` (or `--url`, or `"url"` in `.envctrl.json`) for a self-hosted or local instance.
|
|
20
|
+
|
|
21
|
+
Token lookup: `--token`, `$ENVCTRL_TOKEN`, or `.envctrl.json` (`{"token": "...", "url": "..."}`) in the current or a parent directory. Add `.envctrl.json` to `.gitignore`.
|
package/bin/envctrl.js
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// env-ctrl CLI. Zero dependencies, Node >= 18.
|
|
3
|
+
//
|
|
4
|
+
// envctrl run -- npm start start a command with all variables of the token's environment
|
|
5
|
+
// envctrl pull [--out .env] print / write the variables (dotenv or --format json)
|
|
6
|
+
// envctrl check exit 1 if required keys are missing or invalid (for CI / deploy gates)
|
|
7
|
+
// envctrl whoami which project / environment the token points at
|
|
8
|
+
//
|
|
9
|
+
// Token: --token, $ENVCTRL_TOKEN, or .envctrl.json ({ "token": "...", "url": "..." }) in this or a parent dir.
|
|
10
|
+
// API: --url, $ENVCTRL_URL, .envctrl.json, default https://api.envctrl.com (local dev: ENVCTRL_URL=http://localhost:8080).
|
|
11
|
+
import { spawn } from 'node:child_process';
|
|
12
|
+
import { chmodSync, existsSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
|
|
13
|
+
import { dirname, join, resolve } from 'node:path';
|
|
14
|
+
import { pathToFileURL } from 'node:url';
|
|
15
|
+
|
|
16
|
+
const HELP = `envctrl: environment variables from env-ctrl
|
|
17
|
+
|
|
18
|
+
Usage:
|
|
19
|
+
envctrl run [options] -- <command> [args...]
|
|
20
|
+
envctrl pull [--format dotenv|json] [--out <file>]
|
|
21
|
+
envctrl check
|
|
22
|
+
envctrl whoami
|
|
23
|
+
|
|
24
|
+
Options:
|
|
25
|
+
--token <t> access token (default: $ENVCTRL_TOKEN or .envctrl.json)
|
|
26
|
+
--url <url> env-ctrl API URL (default: $ENVCTRL_URL or https://api.envctrl.com)
|
|
27
|
+
--keep-existing run: variables already set in your shell win over env-ctrl
|
|
28
|
+
--strict run: refuse to start if required keys are missing or invalid
|
|
29
|
+
-h, --help show this help`;
|
|
30
|
+
|
|
31
|
+
function parseArgs(argv) {
|
|
32
|
+
const opts = { _: [], rest: [] };
|
|
33
|
+
for (let i = 0; i < argv.length; i++) {
|
|
34
|
+
const a = argv[i];
|
|
35
|
+
if (a === '--') { opts.rest = argv.slice(i + 1); break; }
|
|
36
|
+
if (a === '-h' || a === '--help') opts.help = true;
|
|
37
|
+
else if (a === '--keep-existing') opts.keepExisting = true;
|
|
38
|
+
else if (a === '--strict') opts.strict = true;
|
|
39
|
+
else if (['--token', '--url', '--format', '--out'].includes(a)) opts[a.slice(2)] = argv[++i];
|
|
40
|
+
else if (a.startsWith('--') && a.includes('=')) { const [k, v] = a.slice(2).split(/=(.*)/s); opts[k] = v; }
|
|
41
|
+
else if (opts._.length === 0 || opts._[0] !== 'run') opts._.push(a);
|
|
42
|
+
else { opts.rest = argv.slice(i); break; } // `envctrl run node app.js` without --
|
|
43
|
+
}
|
|
44
|
+
return opts;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function findConfig(start = process.cwd()) {
|
|
48
|
+
let dir = resolve(start);
|
|
49
|
+
for (;;) {
|
|
50
|
+
const f = join(dir, '.envctrl.json');
|
|
51
|
+
if (existsSync(f)) {
|
|
52
|
+
try { return JSON.parse(readFileSync(f, 'utf8')); }
|
|
53
|
+
catch { fail(`Invalid JSON in ${f}`); }
|
|
54
|
+
}
|
|
55
|
+
const parent = dirname(dir);
|
|
56
|
+
if (parent === dir) return {};
|
|
57
|
+
dir = parent;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function fail(msg, code = 1) {
|
|
62
|
+
process.stderr.write(`envctrl: ${msg}\n`);
|
|
63
|
+
process.exit(code);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function settings(opts) {
|
|
67
|
+
const file = findConfig();
|
|
68
|
+
const token = opts.token ?? process.env.ENVCTRL_TOKEN ?? file.token;
|
|
69
|
+
const url = (opts.url ?? process.env.ENVCTRL_URL ?? file.url ?? 'https://api.envctrl.com').replace(/\/+$/, '');
|
|
70
|
+
if (!token) fail('no token. Set ENVCTRL_TOKEN, pass --token, or add .envctrl.json');
|
|
71
|
+
return { token, url };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function api(path, { token, url }) {
|
|
75
|
+
let res;
|
|
76
|
+
try {
|
|
77
|
+
res = await fetch(url + path, { headers: { Authorization: `Bearer ${token}`, 'User-Agent': 'envctrl-cli/0.1' } });
|
|
78
|
+
} catch (e) {
|
|
79
|
+
fail(`cannot reach ${url} (${e.cause?.code ?? e.message})`);
|
|
80
|
+
}
|
|
81
|
+
if (res.status === 401) fail('token rejected (revoked, expired or wrong kind; a service token is required)');
|
|
82
|
+
if (res.status === 429) fail(`rate limited, retry in ${res.headers.get('retry-after') ?? '?'}s`);
|
|
83
|
+
if (!res.ok) fail(`API error ${res.status}: ${(await res.text()).slice(0, 300)}`);
|
|
84
|
+
return res;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function fetchEnv(s) {
|
|
88
|
+
const res = await api('/v1/env', s);
|
|
89
|
+
const list = (h) => (res.headers.get(h) ?? '').split(',').filter(Boolean);
|
|
90
|
+
return { values: await res.json(), missing: list('x-envctrl-missing'), invalid: list('x-envctrl-invalid') };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Problems with the fetched environment: required keys without a value, values failing their type / regex. */
|
|
94
|
+
function problems({ missing, invalid }) {
|
|
95
|
+
return [
|
|
96
|
+
...(missing.length ? [`missing required keys: ${missing.join(', ')}`] : []),
|
|
97
|
+
...(invalid.length ? [`invalid values (after \${...} references): ${invalid.join(', ')}`] : []),
|
|
98
|
+
];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Same quoting as the API's DotEnv.write: single quotes when possible, because docker compose,
|
|
103
|
+
* dotenv-expand and python-dotenv expand $VAR inside double quotes; double quotes with \$ escaped
|
|
104
|
+
* only for values containing ' or a line break.
|
|
105
|
+
*/
|
|
106
|
+
export function quoteDotenv(v) {
|
|
107
|
+
if (/^[A-Za-z0-9_./:@+\-,]*$/.test(v)) return v;
|
|
108
|
+
if (!/['\n\r]/.test(v)) return `'${v}'`;
|
|
109
|
+
return '"' + v.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\$/g, '\\$')
|
|
110
|
+
.replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '"';
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function toDotenv(values) {
|
|
114
|
+
return Object.entries(values).map(([k, v]) => `${k}=${quoteDotenv(v)}`).join('\n') + '\n';
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** True when this file is the program being run (npm shims, symlinks, Windows paths, spaces). */
|
|
118
|
+
function isMain() {
|
|
119
|
+
if (!process.argv[1]) return false;
|
|
120
|
+
try {
|
|
121
|
+
return import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href;
|
|
122
|
+
} catch {
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function main() {
|
|
128
|
+
const opts = parseArgs(process.argv.slice(2));
|
|
129
|
+
const cmd = opts._[0];
|
|
130
|
+
if (opts.help || !cmd) { console.log(HELP); return; }
|
|
131
|
+
const s = settings(opts);
|
|
132
|
+
|
|
133
|
+
switch (cmd) {
|
|
134
|
+
case 'run': {
|
|
135
|
+
if (!opts.rest.length) fail('nothing to run. Usage: envctrl run -- <command>');
|
|
136
|
+
const fetched = await fetchEnv(s);
|
|
137
|
+
const { values } = fetched;
|
|
138
|
+
for (const msg of problems(fetched)) {
|
|
139
|
+
if (opts.strict) fail(msg);
|
|
140
|
+
process.stderr.write(`envctrl: warning: ${msg}\n`);
|
|
141
|
+
}
|
|
142
|
+
const env = opts.keepExisting ? { ...values, ...process.env } : { ...process.env, ...values };
|
|
143
|
+
delete env.ENVCTRL_TOKEN; // the child gets its variables, not the key to fetch them
|
|
144
|
+
const child = spawn(opts.rest[0], opts.rest.slice(1), { stdio: 'inherit', env, shell: process.platform === 'win32' });
|
|
145
|
+
for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(sig, () => child.kill(sig));
|
|
146
|
+
child.on('error', (e) => fail(`cannot start ${opts.rest[0]}: ${e.message}`, 127));
|
|
147
|
+
child.on('exit', (code, signal) => process.exit(code ?? (signal ? 128 : 1)));
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
case 'pull': {
|
|
151
|
+
const fetched = await fetchEnv(s);
|
|
152
|
+
const { values } = fetched;
|
|
153
|
+
const out = opts.format === 'json' ? JSON.stringify(values, null, 2) + '\n' : toDotenv(values);
|
|
154
|
+
if (opts.out) {
|
|
155
|
+
writeFileSync(opts.out, out, { mode: 0o600 });
|
|
156
|
+
chmodSync(opts.out, 0o600); // mode above only applies when the file is created
|
|
157
|
+
process.stderr.write(`envctrl: wrote ${Object.keys(values).length} variables to ${opts.out}\n`);
|
|
158
|
+
} else {
|
|
159
|
+
process.stdout.write(out);
|
|
160
|
+
}
|
|
161
|
+
for (const msg of problems(fetched)) process.stderr.write(`envctrl: warning: ${msg}\n`);
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
case 'check': {
|
|
165
|
+
const fetched = await fetchEnv(s);
|
|
166
|
+
const found = problems(fetched);
|
|
167
|
+
if (found.length) fail(found.join('; '));
|
|
168
|
+
console.log(`ok: ${Object.keys(fetched.values).length} variables, nothing missing or invalid`);
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
case 'whoami': {
|
|
172
|
+
const me = await (await api('/v1/whoami', s)).json();
|
|
173
|
+
console.log(`${me.project} / ${me.environment} (${me.tokenKind} token) via ${s.url}`);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
default:
|
|
177
|
+
fail(`unknown command "${cmd}"\n\n${HELP}`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if (isMain()) {
|
|
182
|
+
main().catch((e) => fail(e.stack ?? String(e)));
|
|
183
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@env-ctrl/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Run any command with its environment variables from env-ctrl (envctrl.com): one token instead of a .env file.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"envctrl": "bin/envctrl.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin",
|
|
11
|
+
"README.md"
|
|
12
|
+
],
|
|
13
|
+
"engines": {
|
|
14
|
+
"node": ">=18"
|
|
15
|
+
},
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"scripts": {
|
|
18
|
+
"test": "node --test test.mjs"
|
|
19
|
+
},
|
|
20
|
+
"homepage": "https://envctrl.com",
|
|
21
|
+
"keywords": [
|
|
22
|
+
"env",
|
|
23
|
+
"environment-variables",
|
|
24
|
+
"secrets",
|
|
25
|
+
"dotenv",
|
|
26
|
+
"config",
|
|
27
|
+
"cli",
|
|
28
|
+
"envctrl",
|
|
29
|
+
"secrets-manager"
|
|
30
|
+
],
|
|
31
|
+
"author": "Andrei Shelenhouski",
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public"
|
|
34
|
+
}
|
|
35
|
+
}
|